/
code_alpaca_2k.json
10087 lines (10087 loc) · 778 KB
/
code_alpaca_2k.json
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
[
{
"instruction": "What are the distinct values from the given list?",
"input": "dataList = [3, 9, 3, 5, 7, 9, 5]",
"output": "The distinct values from the given list are 3, 5, 7 and 9."
},
{
"instruction": "How would you order a sequence of letters alphabetically?",
"input": "A, B, C, D",
"output": "The sequence of letters ordered alphabetically is A, B, C, D."
},
{
"instruction": "Write a JavaScript code to loop over all elements in the given array.",
"input": "numbersArray = [45, 6, 23, 12, 35]",
"output": "for(let i = 0; i < numbersArray.length; i++) {\n console.log(numbersArray[i]);\n}"
},
{
"instruction": "Write a Python function to calculate the factorial of a given number.",
"input": "",
"output": "def factorial(number):\n fact = 1\n for i in range(1, number + 1):\n fact = fact * i\n return fact"
},
{
"instruction": "What would be the output of the following JavaScript snippet?",
"input": "let area = 6 * 5;\nlet radius = area / 3.14;",
"output": "The output of the JavaScript snippet is the radius, which is 1.91."
},
{
"instruction": "Write a Python code to check if a given number is even or odd.",
"input": "",
"output": "def is_even(number):\n if number % 2 == 0:\n return True\n else:\n return False"
},
{
"instruction": "Write an SQL query to select names of all employees who work in the Accounting department.",
"input": "",
"output": "SELECT Name FROM Employees WHERE Department = 'Accounting';"
},
{
"instruction": "How would you sort a list of integer numbers in descending order?",
"input": "",
"output": "The list of integer numbers can be sorted in descending order using the Python's list sorting method: numbers.sort(reverse=True)."
},
{
"instruction": "Write a function in JavaScript that takes in a string and returns its length.",
"input": "",
"output": "function stringLength(string){\n return string.length;\n}"
},
{
"instruction": "Write an if-else statement in Java that checks if a given number is between 0 and 10.",
"input": "",
"output": "if (number >= 0 && number <= 10) {\n System.out.println(\"The number is between 0 and 10.\");\n} else {\n System.out.println(\"The number is not between 0 and 10.\");\n}"
},
{
"instruction": "How would you convert a string to a float in Python?",
"input": "",
"output": "The string can be converted to a float in Python by using the float() method: float(string)."
},
{
"instruction": "Write a SQL query to select employee names who earn a salary greater than $50,000.",
"input": "",
"output": "SELECT Name FROM Employees WHERE Salary > 50000;"
},
{
"instruction": "Write a JavaScript program to check if a given string is a palindrome.",
"input": "",
"output": "function isPalindrome(str){\n let reversed = str.split('').reverse().join('');\n return str === reversed;\n}"
},
{
"instruction": "Write a Java code to find the sum of two numbers.",
"input": "",
"output": "public int sumOfTwo(int a, int b) {\n return a + b;\n}"
},
{
"instruction": "What is the syntax for creating a custom exception in Python?",
"input": "",
"output": "The syntax for creating a custom exception in Python is: class CustomException(Exception):."
},
{
"instruction": "Generate the HTML code for a page with a centered headline that says \"My Portfolio\".",
"input": "",
"output": "<html>\n <head>\n <title>My Portfolio</title>\n </head>\n <body>\n <center>\n <h1>My Portfolio</h1>\n </center>\n </body>\n</html>"
},
{
"instruction": "Create a ruby function that takes two strings as parameters and returns true if the two strings are anagrams.",
"input": "",
"output": "def is_anagram?(str1, str2)\n return str1.downcase.split(\"\").sort == str2.downcase.split(\"\").sort\nend"
},
{
"instruction": "Suppose you have an array of objects and you want to sort them by the value of a given key. Write a JavaScript function to do the sorting.",
"input": "array = [\n { name: \u201cJohn\u201d, age: 63},\n { name: \u201cSam\u201d, age: 21},\n { name: \u201cRob\u201d, age: 42}\n]\nkey = \u201cage\u201d",
"output": "function sortByKey(array, key) {\n return array.sort((a, b) => (a[key] > b[key] ? 1 : -1));\n}\nsortByKey(array, \"age\");"
},
{
"instruction": "Write a SQL code to count the number of records in a table.",
"input": "",
"output": "SELECT COUNT(*) FROM tableName;"
},
{
"instruction": "Create a Java program to calculate the factorial of a number.",
"input": "",
"output": "public class FactorialCalculator {\n \n public static int calculateFactorial(int number) {\n int result = 1;\n for (int i = 2; i <= number; i++) {\n result *= i;\n }\n return result;\n }\n \n public static void main(String[] args) {\n System.out.println(calculateFactorial(5));\n }\n}"
},
{
"instruction": "Rewrite this JavaScript function to use ES6 syntax.",
"input": "function doubleValue(x) {\n return x * 2;\n}",
"output": "const doubleValue = x => x * 2;"
},
{
"instruction": "Create an array of strings with only the elements of another array that have a length longer than 5 characters.",
"input": "array = [\"January\", \"February\", \"March\", \"April\", \"May\", \"June\", \"July\"]",
"output": "const longNames = array.filter(name => name.length > 5);"
},
{
"instruction": "Create a for loop in Python to print out the items in the following list.",
"input": "list = [\"apple\", \"banana\", \"cherry\", \"orange\"]",
"output": "for item in list:\n print(item)"
},
{
"instruction": "Create a C++ program to compute the sum of two numbers.",
"input": "",
"output": "#include <iostream>\n \nint main()\n{\n int firstNumber, secondNumber, sumOfTwoNumbers;\n \n std::cout << \"Enter two integers: \";\n std::cin >> firstNumber >> secondNumber;\n \n // sum of two numbers in stored in variable sumOfTwoNumbers\n sumOfTwoNumbers = firstNumber + secondNumber;\n \n // Prints sum \n std::cout << firstNumber << \" + \" << secondNumber << \" = \" << sumOfTwoNumbers; \n \n return 0;\n}"
},
{
"instruction": "Rewrite this JavaScript code snippet to take advantage of array destructuring.",
"input": "let car1 = cars[0];\nlet color1 = car1.color;",
"output": "let [{color: color1}] = cars;"
},
{
"instruction": "Create SQL code to find the most expensive item in a table.",
"input": "",
"output": "SELECT * FROM tableName ORDER BY price DESC LIMIT 1;"
},
{
"instruction": "Write a function in Python that takes two lists and returns a new list with elements of the first list followed by the second list.",
"input": "list1 = [\u2018a\u2019, \u2018b\u2019, \u2018c\u2019]\nlist2 = [1, 2, 3]",
"output": "def combine_lists(list1, list2):\n return list1 + list2 \ncombine_lists(list1, list2)"
},
{
"instruction": "Create a C# program to perform a linear search on an array.",
"input": "",
"output": "public static int LinearSearch(int[] inputArray, int key) \n{ \n int size = inputArray.Length; \n \n for (int i=0; i<size; i++) { \n if (inputArray[i] == key) { \n return i; \n } \n } \n \n return -1; \n}"
},
{
"instruction": "Create a php code to capitalize the first letter of every word in a string.",
"input": "string = \u201cwelcome to the world of coding\u201d",
"output": "<?php \n$string = \u201cwelcome to the world of coding\u201d;\necho ucwords($string);\n?>"
},
{
"instruction": "Construct a forEach loop to loop over every item in an array and print that item.",
"input": "array = [\u201capple\u201d, \u201cbanana\u201d, \u201ccherry\u201d]",
"output": "array.forEach(function(item){\n console.log(item);\n});"
},
{
"instruction": "Write a shell script to print all odd numbers from 1 to 10.",
"input": "",
"output": "#!/bin/bash \nfor num in {1..10}\n do \n if (( $num % 2 == 1)) \n then \n echo $num\n fi \n done"
},
{
"instruction": "Write a JavaScript function to generate a random number between 0 to 10.",
"input": "",
"output": "function getRandomNumber(){\n return Math.floor(Math.random() * 10);\n}"
},
{
"instruction": "Write a SQL query to find all records in a table where the city is London.",
"input": "Table:\n\n| Name | City |\n|--------|--------|\n| John | NYC |\n| Kate | London|\n| Alan | London|",
"output": "SELECT * FROM Table WHERE City = 'London';"
},
{
"instruction": "Write a Java program to sort an array of integers in descending order.",
"input": "Array: [2, 3, 11, 4, 5]",
"output": "int[] arr = {2, 3, 11, 4, 5};\n\nArrays.sort(arr, Collections.reverseOrder());\n\nSystem.out.println(Arrays.toString(arr));"
},
{
"instruction": "Write a SQL query to find the total revenue of a company's sales in the month of June.",
"input": "Table:\n\n| Orders | Date | Revenue |\n|-----------|-----------|----------|\n| Order 1 | 6/15/19 | $45 |\n| Order 2 | 6/20/19 | $80 |\n| Order 3 | 7/15/19 | $100 |",
"output": "SELECT SUM(Revenue) FROM Table WHERE Date LIKE '6/__/19'"
},
{
"instruction": "Write an HTML code snippet to show a button with the text \"Click me!\".",
"input": "",
"output": "<button type=\"button\">Click me!</button>"
},
{
"instruction": "Write a Java program to compute the factorial of a given integer.",
"input": "",
"output": "// Java program to calculate factorial of a number\npublic class Factorial\n{\n public static int factorial(int n)\n {\n if (n == 0)\n return 1;\n \n return n*factorial(n-1);\n }\n \n public static void main(String[] args)\n {\n int num = 5;\n System.out.println(\"Factorial of \"+ num + \" is: \"+factorial(num));\n }\n}"
},
{
"instruction": "Write a JavaScript code snippet to remove all occurrences of a given substring from a string.",
"input": "String: 'Hello World!'\nSubstring: 'o'",
"output": "let str = 'Hello World!';\nlet subStr = 'o';\n\nlet newStr = str.replace(new RegExp(subStr, 'g'), '');\n\nconsole.log(newStr); // Output: Hell Wrld!"
},
{
"instruction": "Write an HTML code snippet to show a hyperlink to an external website.",
"input": "",
"output": "<a href=\"https://example.com\">Visit external website</a>"
},
{
"instruction": "Write a Python program to check if a given string contains any punctuation character or not.",
"input": "",
"output": "import string\n\ndef is_punctuation(word):\n for c in word:\n if c in string.punctuation:\n return True\n return False"
},
{
"instruction": "Write a SQL query to calculate the average revenue of the company in the last 3 months.",
"input": "Table:\n\n| Orders | Date | Revenue |\n|-----------|-----------|----------|\n| Order 1 | 2/15/19 | $90 |\n| Order 2 | 3/20/19 | $30 |\n| Order 3 | 4/15/19 | $100 |",
"output": "SELECT AVG(Revenue) FROM Table WHERE Date >= DATEADD(month, -3, GETDATE())"
},
{
"instruction": "Create a function in Python with 2 input parameters a and b and return a string which contains their product.",
"input": "",
"output": "def product_string(a, b):\n return \"The product of a and b is \" + str(a * b)"
},
{
"instruction": "Create a Visual Basic program that prints the given input string in reversed order.",
"input": "\"Hello!\"",
"output": "Module Module1\n Sub Main()\n Dim input_string As String = \"Hello!\"\n Dim reversed As String = \"\"\n For i = input_string.Length - 1 To 0 Step -1\n reversed += input_string(i)\n Next\n Console.WriteLine(reversed)\n End Sub\nEnd Module"
},
{
"instruction": "Write an SQL query that finds the total number of orders from customers whose name contains \"ar\".",
"input": "",
"output": "SELECT COUNT(*) FROM orders WHERE customer_name LIKE '%ar%';"
},
{
"instruction": "Create a Java program to print out the words of a given string in reverse order.",
"input": "\"Hello world\"",
"output": "public class ReverseStr {\n public static void main(String[] args) {\n String inputStr = \"Hello world\";\n String reversedStr = \"\";\n for(int i = inputStr.length() - 1; i >= 0; i--) {\n reversedStr = reversedStr + inputStr.charAt(i);\n }\n System.out.println(reversedStr);\n }\n}"
},
{
"instruction": "Create a JavaScript program that counts the number of vowels in a given string.",
"input": "\"Hello world\"",
"output": "const str = \"Hello world\";\n\nconst countVowels = (str) => {\n let vowelsCount = 0;\n for (let i = 0; i < str.length; i++) {\n if (str[i] === \"a\" || str[i] === \"e\" || str[i] === \"i\" || str[i] === \"o\" || str[i] === \"u\") {\n vowelsCount += 1;\n }\n }\n return vowelsCount;\n};\n\nconsole.log(countVowels(str));"
},
{
"instruction": "Rewrite the given code to define a function factorial in Python.",
"input": "# Factorial\n#n = 5\n#Product = 1\n#for x in range (1,n+1):\n# Product = Product * x",
"output": "def factorial(n):\n product = 1\n for x in range(1, n+1):\n product = product * x\n return product"
},
{
"instruction": "Write a SQL query to find the names of customers who have placed more than 10 orders.",
"input": "",
"output": "SELECT customer_name\nFROM orders\nGROUP BY customer_name\nHAVING COUNT(*) > 10;"
},
{
"instruction": "Create a function in Java that takes in an integer n as a parameter and returns the sum of the first n natural numbers.",
"input": "",
"output": "public static int sumFirstNNaturalNumbers(int n) {\n int sum = 0;\n for (int i = 1; i <= n; i++) {\n sum += i;\n }\n return sum;\n}"
},
{
"instruction": "Create a JavaScript program that takes two strings and returns true if they are pairwise anagrams of each other.",
"input": "\"anagram\"\n\"margana\"",
"output": "const pairwiseAnagrams = (str1, str2) => {\n if (str1.length !== str2.length) return false;\n \n const countLetters = (str) => {\n let obj = {};\n for (let i = 0; i < str.length; i++) {\n let char = str[i];\n if (!obj[char]) {\n obj[char] = 1;\n }\n else {\n obj[char]++;\n } \n }\n return obj;\n }\n let letterCount1 = countLetters(str1);\n let letterCount2 = countLetters(str2);\n for (let letter in letterCount1) {\n if (letterCount1[letter] !== letterCount2[letter]) return false;\n }\n return true;\n};\n\nconsole.log(pairwiseAnagrams(\"anagram\", \"margana\"));"
},
{
"instruction": "Write an SQL Query to find the customer name and order date for all customers who have placed an order yesterday.",
"input": "",
"output": "SELECT customer_name, order_date\nFROM orders\nWHERE order_date = DATE_SUB(CURDATE(), INTERVAL 1 DAY);"
},
{
"instruction": "Create a Visual Basic program that prints the even numbers between 1 and the given input number n.",
"input": "10",
"output": "Module Module1\n Sub Main()\n Dim n As Integer = 10\n For i As Integer = 2 To n Step 2\n Console.WriteLine(i)\n Next\n End Sub\nEnd Module"
},
{
"instruction": "Rewrite the given code to sort the list of numbers in ascending order.",
"input": "numbers = [3, 5, 1, 4, 2]",
"output": "numbers = [3, 5, 1, 4, 2]\ndef ascending_sort(numbers):\n for i in range(len(numbers)-1):\n for j in range(i+1, len(numbers)):\n if numbers[i] > numbers[j]:\n temp = numbers[i];\n numbers[i] = numbers[j];\n numbers[j] = temp;\n return numbers\n\nprint(ascending_sort(numbers))"
},
{
"instruction": "Create a JavaScript program that takes in a string and returns the number of pairs of matching letters in the string.",
"input": "\"mississippi\"",
"output": "const matchingPairs = (str) => {\n let count = 0;\n str = str.toLowerCase();\n for (let i = 0; i < str.length-1; i++) {\n if (str[i] === str[i+1]) {\n count++;\n }\n }\n return count;\n}\nconsole.log(matchingPairs(\"mississippi\"));"
},
{
"instruction": "Create a C++ function that checks if a given integer is an Armstrong number.",
"input": "",
"output": "#include <iostream>\n\nusing namespace std;\n\nint getNumDigits(int num) {\n int digits = 0;\n while (num > 0) {\n digits++;\n num /= 10;\n }\n return digits;\n}\n\nbool isArmstrong(int num) {\n int digits = getNumDigits(num);\n int sum = 0;\n int tempNum = num;\n while (tempNum > 0) {\n int digit = tempNum % 10;\n sum += pow(digit, digits);\n tempNum /= 10;\n }\n return sum == num;\n}\n\nint main() {\n cout << isArmstrong(153) << endl;\n return 0;\n}"
},
{
"instruction": "What is a possible way to check whether an element exists in a set?",
"input": "",
"output": "A possible way to check whether an element exists in a set is to use the keyword 'in', which returns True if the element exists and False otherwise."
},
{
"instruction": "Explain the difference between a variable and a constant.",
"input": "",
"output": "A variable is a named location in memory that stores values that can be changed. A constant is a named location in memory that stores a fixed value which cannot be changed."
},
{
"instruction": "Write an HTML code to make a button display a message on a web page.",
"input": "",
"output": "<button onclick=\"alert('Hello World!')\">Click Me</button>"
},
{
"instruction": "Generate a correct logic for updating a data field in a table.",
"input": "Assuming the table \"user\" has a field \"balance\"",
"output": "UPDATE user\nSET balance = balance + 10\nWHERE condition;"
},
{
"instruction": "Create a C++ class to calculate the maximum value in an array.",
"input": "",
"output": "class MaxValue\n{\npublic:\n int maxValue(int numbers[], int length)\n {\n int maxValue = numbers[0];\n for(int i = 1; i < length; ++i)\n {\n if(numbers[i] > maxValue)\n maxValue = numbers[i];\n }\n return maxValue;\n }\n};"
},
{
"instruction": "What is the difference between an abstract class and an interface in Java?",
"input": "",
"output": "The main difference between an abstract class and an interface in Java is that a class can extend only one abstract class but it can implement multiple interfaces. An abstract class can contain both implemented and unimplemented methods, while an interface can contain only abstract methods."
},
{
"instruction": "Write a JavaScript code to delete duplicate elements from an array.",
"input": "",
"output": "function deleteDuplicates(array) {\n let unique_array = Array.from(new Set(array))\n return unique_array\n}"
},
{
"instruction": "Amend the following SQL query to select distinct elements.",
"input": "SELECT * FROM employee;",
"output": "SELECT DISTINCT * FROM employee;"
},
{
"instruction": "Identify the correct syntax for an if-else construct in Java.",
"input": "",
"output": "if(condition) {\n // code block to be executed if the condition is true\n} else {\n // code block to be executed if the condition is false\n}"
},
{
"instruction": "Create a Python function to sort a string in descending order.",
"input": "",
"output": "def Descending_Order(str1): \n\tstr1 = sorted(str1, reverse = True) \n\treturn ''.join(str1)"
},
{
"instruction": "Find the longest word in a sentence using JavaScript.",
"input": "This is a sentence with a few words.",
"output": "function findLongestWord(str) {\n let words = str.split(\" \");\n let longestWord = 0;\n\n for (let i = 0; i < words.length; i++) {\n if (words[i].length > longestWord) {\n longestWord = words[i].length;\n }\n }\n return longestWord;\n}"
},
{
"instruction": "Explain the concept of Data Encapsulation.",
"input": "",
"output": "Data encapsulation is the process of combining related variables, such as data fields and methods into a single unit, known as a class. Data encapsulation helps simplify the process of software development by binding together data and functions that manipulate that data, making the data more secure and easier to maintain."
},
{
"instruction": "Create a Swift function to find the smallest element in an array.",
"input": "",
"output": "func findSml(arr: [Int]) -> Int {\n var smallest = arr[0]\n\n for index in 0..<arr.count {\n if arr[index] < smallest {\n smallest = arr[index]\n }\n }\n return smallest\n}"
},
{
"instruction": "Write a function to remove an element from an array in JavaScript.",
"input": "const array = [1, 2, 3, 4, 5];",
"output": "function removeElement(array, element) {\n let newArray = [];\n for (let i = 0; i < array.length; i++) {\n if(array[i] !== element) {\n newArray.push(array[i]);\n }\n }\n return newArray;\n}"
},
{
"instruction": "Create a simple class named Employee in Java.",
"input": "",
"output": "public class Employee {\n \n private String name;\n private int age;\n \n public Employee(String name, int age) {\n this.name = name;\n this.age = age;\n }\n \n public String getName() {\n return name;\n }\n \n public int getAge() {\n return age;\n }\n \n public void setName(String name) {\n this.name = name;\n }\n \n public void setAge(int age) {\n this.age = age;\n }\n \n @Override\n public String toString() {\n return \"Employee{\" +\n \"name='\" + name + '\\'' +\n \", age=\" + age +\n '}';\n }\n}"
},
{
"instruction": "Create a data structure that stores the following data: name, age, and salary.",
"input": "",
"output": "public class EmployeeData {\n \n private String name;\n private int age;\n private float salary;\n \n public EmployeeData(String name, int age, float salary) {\n this.name = name;\n this.age = age;\n this.salary = salary;\n }\n \n public String getName() {\n return name;\n }\n \n public int getAge() {\n return age;\n }\n \n public float getSalary() {\n return salary;\n }\n \n public void setName(String name) {\n this.name = name;\n }\n \n public void setAge(int age) {\n this.age = age;\n }\n \n public void setSalary(float salary) {\n this.salary = salary;\n }\n \n public String toString() {\n return \"Employee Data { Name: \" + name + \", Age: \" + age + \", Salary: \" + salary + \" }\";\n }\n \n}"
},
{
"instruction": "Edit the following HTML structure to include the Bootstrap 4 library.",
"input": "<html>\n<head>\n <title>My Web Page</title>\n</head>\n<body>\n\n</body>\n</html>",
"output": "<html>\n<head>\n <title>My Web Page</title>\n <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css\" integrity=\"sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z\" crossorigin=\"anonymous\">\n <script src=\"https://code.jquery.com/jquery-3.5.1.slim.min.js\" integrity=\"sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj\" crossorigin=\"anonymous\"></script>\n <script src=\"https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js\" integrity=\"sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN\" crossorigin=\"anonymous\"></script>\n <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js\" integrity=\"sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV\" crossorigin=\"anonymous\"></script>\n</head>\n<body>\n\n</body>\n</html>"
},
{
"instruction": "Create a SQL query to get the list of employees who have a salary greater than 20,000.",
"input": "",
"output": "SELECT name \nFROM Employees \nWHERE salary > 20000;"
},
{
"instruction": "Write a Java program to compare two strings.",
"input": "String str1 = \"Hello\";\nString str2 = \"World\";",
"output": "public class CompareString {\n\n public static void main(String[] args) {\n\n String str1 = \"Hello\";\n String str2 = \"World\";\n\n int result = str1.compareTo(str2);\n\n if (result < 0) {\n System.out.println(\"str1 is less than str2\");\n } else if (result == 0) {\n System.out.println(\"str1 is equal to str2\");\n } else {\n System.out.println(\"str1 is greater than str2\");\n }\n }\n}"
},
{
"instruction": "Write a JavaScript program to print the Fibonacci series.",
"input": "",
"output": "function printFibonacciSeries(number){\n let num1 = 0;\n let num2 = 1; \n\n console.log(num1); \n let sum;\n for(let i = 0; i<number; i++){\n sum = num1 + num2;\n num1 = num2;\n num2 = sum;\n console.log(num1);\n } \n}\n\nprintFibonacciSeries(10);"
},
{
"instruction": "Implement the bubble sort algorithm in C++.",
"input": "",
"output": "void bubbleSort(int arr[], int n)\n{\n int i, j;\n for (i = 0; i < n-1; i++)\n \n // Last i elements are already in place \n for (j = 0; j < n-i-1; j++) \n if (arr[j] > arr[j+1])\n swap(&arr[j], &arr[j+1]);\n}"
},
{
"instruction": "Create a basic web server using Express in Node.js.",
"input": "",
"output": "const express = require('express');\nconst app = express();\n\napp.get('/', (req, res) => {\n res.send('Hello World!');\n});\n\nconst port = 3000;\n\napp.listen(port, () => {\n console.log(`Server is running on port ${port}`);\n});"
},
{
"instruction": "Create an object named \"Account\" in Python with two attributes: name and balance.",
"input": "",
"output": "class Account:\n def __init__(self, name, balance):\n self.name = name\n self.balance = balance"
},
{
"instruction": "Write a SQL query to get the list of customers who have the same name as their email address.",
"input": "",
"output": "SELECT name \nFROM Customers \nWHERE name = email;"
},
{
"instruction": "Create a program in Ruby to generate all combinations of the characters in a string.",
"input": "str = \"ABC\"",
"output": "def combinations(str)\n result = []\n 0.upto(str.size - 1) do |i|\n 0.upto(str.size - 1) do |j|\n result << [str[i], str[j]].join\n end\n end\n result\nend\n\nprint combinations('ABC')"
},
{
"instruction": "Design a structure in C to represent a point in a 2-dimentional plane.",
"input": "",
"output": "typedef struct {\n int x;\n int y;\n} Point;"
},
{
"instruction": "Create a JavaScript program to manipulate an array of string and return only the words containing a given letter.",
"input": "Given an array [\"work\",\"dog\",\"learn\",\"beyond\",\"monkey\"], and letter 'o'.",
"output": "var arr = [\"work\",\"dog\",\"learn\",\"beyond\",\"monkey\"];\n \nfunction getWordsWithLetter(array, letter){\n var result = [];\n for(var i = 0; i < array.length; i++){\n if(array[i].includes(letter)){\n result.push(array[i]);\n }\n }\n return result;\n}\n \nconsole.log(getWordsWithLetter(arr, \"o\"));\n\n// Output:[\"work\", \"dog\", \"learn\"]"
},
{
"instruction": "Write a function for creating a dictionary in Python using the following logic.",
"input": "Given data in the format {\"key1\":\"value1\",\"key2\":\"value2\",\"key3\":\"value3\"}",
"output": "def createDictionary(data):\n dict_data = {}\n for key, value in data.items():\n dict_data[key] = value\n \n return dict_data"
},
{
"instruction": "Implement a SQL query to find the top 5 customer first names along with the total number of purchases made by each.",
"input": "",
"output": "SELECT customername, COUNT(*) AS 'total_purchases' \nFROM customers \nGROUP BY customername \nORDER BY total_purchases DESC \nLIMIT 5;"
},
{
"instruction": "Construct a Java program to print the following sequence of numbers.",
"input": "1,3,7,15,31,?",
"output": "public class PrintSequence {\n\n public static void main(String[] args) {\n int prev = 1;\n for (int i = 1; i <= 6; i++) {\n System.out.print(prev + \" \");\n prev = prev * 2 + 1;\n }\n }\n}\n\n// Output: 1 3 7 15 31 63"
},
{
"instruction": "Suggest a modification to the following C code.",
"input": "int a,b; \nif (a > b)\nprintf(\"a is greater than b\");",
"output": "int a,b; \nif (a > b){\n printf(\"a is greater than b\");\n}"
},
{
"instruction": "Create a SQL query to show the total number of orders in each Month.",
"input": "",
"output": "SELECT COUNT(orderdate) as 'TotalOrders', MONTH(orderdate) as 'month'\nFROM Orders\nGROUP BY MONTH(orderdate);"
},
{
"instruction": "Write a piece of Python code to generate a random number between 1 and 10.",
"input": "",
"output": "import random\n\nrandom_number = random.randint(1, 10)\nprint(random_number)"
},
{
"instruction": "Construct a C++ program to print the nth Fibonacci number.",
"input": "",
"output": "#include <iostream> \n\nusing namespace std; \n\nint Fibonacci(int n) \n{ \n\tif (n <= 1) \n\t\treturn n; \n\treturn Fibonacci(n-1) + Fibonacci(n-2); \n} \n\nint main() \n{ \n\tint n;\n\tcin >> n;\n\tcout << Fibonacci(n); \n\treturn 0; \n}"
},
{
"instruction": "Write a php function to find the length of the longest common string found in two separate strings.",
"input": "Given two strings: \"abcdabcef\" and \"abcdabxefg\"",
"output": "<?php\nfunction longest_common_string($s1, $s2) {\n $m = strlen($s1);\n $n = strlen($s2);\n \n $max=0;\n\n for ($i=0; $i<=$m; $i++) \n { \n for ($j=0; $j<=$n; $j++) \n { \n if ($i==0 || $j==0) {\n $l[$i][$j] = 0; \n } else if ($s1[$i-1] == $s2[$j-1]) {\n $l[$i][$j] = $l[$i - 1][$j - 1] + 1; \n $max = max($max, $l[$i][$j]);\n } else {\n $l[$i][$j] = 0; \n } \n } \n }\n return $max;\n}\n?>"
},
{
"instruction": "Write a Python code snippet to remove the vowels from a given string.",
"input": "Given string=\"learningpython\"",
"output": "def removeVowels(string): \n vowels = ('a', 'e', 'i', 'o', 'u') \n for x in string.lower(): \n if x in vowels: \n string = string.replace(x, \"\") \n return string\n\nstring = \"learningpython\"\nprint(removeVowels(string))\n\n// Output: lrngpythn"
},
{
"instruction": "Recreate the following matrix using multidimensional array in JavaScript.",
"input": "Matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]",
"output": "let matrix = [[1,2,3], [4,5,6], [7,8,9]];\n \nconsole.log(matrix);\n \n// Output: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]"
},
{
"instruction": "Write a Bash script to calculate the sum of the digits in a given number.",
"input": "Given the number 4567",
"output": "#!/bin/bash\n\nsum_digits (){\n n=$1\n sum=0\n while [ $n -gt 0 ]; do\n rem=$(($n % 10))\n sum=$(($sum + $rem))\n n=$(($n / 10))\n done\n echo \"$sum\"\n}\n\nsum_digits 4567 \n\n// Output: 24"
},
{
"instruction": "Construct a JavaScript program to find the longest common prefix of a given array of strings.",
"input": "Given array [\"code\", \"codes\", \"codelab\", \"coding\"]",
"output": "function longestCommonPrefix(arr) {\n if(arr.length == 0) {\n return \"\";\n }\n \n let prefix = arr[0];\n \n for(let i = 1; i < arr.length; i++) {\n let j = 0;\n while (j < arr[i].length && j < prefix.length && \n arr[i][j] === prefix[j]) {\n j++;\n }\n prefix = prefix.substring(0, j);\n }\n return prefix;\n}\n\nlet arr = [\"code\", \"codes\", \"codelab\", \"coding\"];\nlet result = longestCommonPrefix(arr);\nconsole.log(result);\n\n// Output: \"code\""
},
{
"instruction": "Generate a C program to find the sum of all the elements in a given array.",
"input": "Given array [5, 6, 12, 4, 8]",
"output": "#include <stdio.h>\n \n// Function to find sum of all elements \nint getSum(int arr[], int n) \n{ \n int sum = 0; \n for (int i = 0; i < n; i++) \n sum += arr[i]; \n\n return sum; \n} \n \nint main()\n{\n int arr[] = { 5, 6, 12, 4, 8 }; \n int n = sizeof(arr) / sizeof(arr[0]); \n \n // Function call\n int sum = getSum(arr, n); \n printf(\"Sum of array elements is: %d\", sum); \n \n return 0; \n}\n \n// Output: Sum of array elements is: 35"
},
{
"instruction": "Construct an Objective-C program to check if a given number is a palindrome",
"input": "Given number 1221",
"output": "int isPalindrome(int num)\n{ \n int orig_num, rest, sum= 0;\n \n orig_num = num; \n \n while (num > 0)\n {\n rest = num % 10; \n sum = (sum * 10) + rest; \n num = num / 10; \n } \n \n if (orig_num == sum) \n return 1; \n \n return 0;\n} \n \nint main (void)\n{\n int num = 1221;\n \n if (isPalindrome(num))\n printf(\"%d is a palindrome.\", num);\n else\n printf(\"%d isn't a palindrome.\", num); \n return 0;\n} \n\n// Output: 1221 is a palindrome."
},
{
"instruction": "Write a JavaScript function that returns the number of days from today till a given date.",
"input": "given_date=\"2021-02-14\";",
"output": "function daysUntil(given_date) {\n const today = new Date();\n const expiration = new Date(given_date);\n return Math.ceil((expiration - today)/(1000*60*60*24))\n}"
},
{
"instruction": "Write a Python class called Student which contains the following fields: name, age, and grade.",
"input": "",
"output": "class Student:\n def __init__(self, name, age, grade):\n self.name = name\n self.age = age\n self.grade = grade"
},
{
"instruction": "Create a JavaScript array containing 5 fruits.",
"input": "",
"output": "let fruits = [\"apple\", \"orange\", \"mango\", \"banana\", \"grape\"];"
},
{
"instruction": "Use TensorFlow 2.0 to create a convolutional neural network (CNN) model to classify different types of flowers.",
"input": "",
"output": "model = Sequential()\nmodel.add(Conv2D(32, (3, 3), activation='relu', input_shape=(32, 32, 3)))\nmodel.add(Conv2D(64, (3, 3), activation='relu'))\nmodel.add(MaxPooling2D((2, 2)))\nmodel.add(Flatten())\nmodel.add(Dense(128, activation='relu'))\nmodel.add(Dense(5, activation='softmax'))\nmodel.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])"
},
{
"instruction": "Sort the numbers in a given list from biggest to smallest using Ruby.",
"input": "[3, 5, 2, 1, 4]",
"output": "def sort_list(list)\n list.sort {|a, b| b<=>a}\nend"
},
{
"instruction": "Create an HTML page containing a login form with the following fields: username, password, and submit button.",
"input": "",
"output": "<html>\n <head>\n <title>Login Form</title>\n </head>\n <body>\n <form action=\"/login\" method=\"POST\">\n <input type=\"text\" name=\"username\" placeholder=\"Username\"/>\n <input type=\"password\" name=\"password\" placeholder=\"Password\"/>\n <input type=\"submit\" value=\"Submit\"/>\n </form>\n </body>\n</html>"
},
{
"instruction": "Write a Python function to print an n by n multiplication table.",
"input": "",
"output": "def print_multiplication_table(n): \n for i in range(1, n+1):\n for j in range(1, n+1):\n print(i*j, end = ' ')\n print()"
},
{
"instruction": "Use a combination of React and JavaScript to create a simple counter application that allows you to increase, decrease, or reset a count.",
"input": "",
"output": "import React, { useState } from 'react';\n\nfunction App() {\n const [count, setCount] = useState(0);\n\n const increaseCount = () => {\n setCount(count + 1);\n }\n\n const decreaseCount = () => {\n setCount(count - 1);\n }\n\n const resetCount = () => {\n setCount(0);\n }\n\n return (\n <div>\n <h1>Counter: {count}</h1>\n <button onClick={increaseCount}>Increase</button>\n <button onClick={decreaseCount}>Decrease</button>\n <button onClick={resetCount}>Reset</button>\n </div>\n );\n}\n\nexport default App;"
},
{
"instruction": "Write a C program to remove all vowels from an input string.",
"input": "string = \"Hello World\"",
"output": "#include <stdio.h> \n#include <string.h> \n \nvoid removeVowels(char *str) \n{ \n int i = 0; \n \n while (str[i]) { \n if (str[i] == 'A' || str[i]=='E' || str[i]=='I' || \n str[i]=='O' || str[i]=='U' || str[i]=='a' || \n str[i]=='e' || str[i]=='i' || str[i]=='o' || \n str[i]=='u') \n str[i] = '\\0'; \n i++; \n } \n} \n \nint main() \n{ \n char str[] = \"geeksforgeeks\"; \n removeVowels(str); \n printf(\"%s\", str); \n return 0; \n}"
},
{
"instruction": "Create a JavaScript object that stores the chosen values for a survey.",
"input": "",
"output": "let surveyValues = {\n firstName: \"John\",\n lastName: \"Smith\",\n age: 32,\n gender: \"male\",\n politicalOrientation: \"liberal\"\n};"
},
{
"instruction": "Write a C++ function to check if two given strings are anagrams of each other.",
"input": "string1=\"listen\"; string2=\"silent\";",
"output": "bool isAnagram(string string1, string string2) \n{ \n int n1 = string1.length(); \n int n2 = string2.length(); \n \n if (n1 != n2) \n return false; \n \n sort(string1.begin(), string1.end()); \n sort(string2.begin(), string2.end()); \n \n for (int i = 0; i < n1; i++) \n if (string1[i] != string2[i]) \n return false; \n \n return true; \n}"
},
{
"instruction": "Create an HTML page with a text input form and a submit button.",
"input": "",
"output": "<html>\n <head>\n <title>Text Input Form</title>\n </head>\n <body>\n <form action=\"/submit\" method=\"POST\">\n <input type=\"text\" name=\"input\" placeholder=\"Enter Text\"/>\n <input type=\"submit\" value=\"Submit\"/>\n </form>\n </body>\n</html>"
},
{
"instruction": "Write a JavaScript function that takes two numbers as parameters and returns the sum of those two numbers.",
"input": "",
"output": "function add(a, b) {\n return a + b;\n}"
},
{
"instruction": "Write a Ruby program that creates a hash called movies and stores the movie titles extracted from a given array of movie names.",
"input": "movies_array = [\"Titanic\", \"Star Wars\", \"Jurassic Park\"]",
"output": "movies = {}\nmovies_array.each do |movie|\n movies[movie] = 1\nend"
},
{
"instruction": "Create a SQL query to display the first name and last name of all customers in the customer table who live in California.",
"input": "",
"output": "SELECT first_name, last_name \nFROM customers \nWHERE state = \"California\";"
},
{
"instruction": "Develop a code snippet to get the value of the key 'name' from the following dictionary.",
"input": "info = {\n 'name': 'John',\n 'address': '123 Main Street'\n}",
"output": "name_val = info['name']"
},
{
"instruction": "Below is a piece of code in which task you need to make it compatible with Python 3.",
"input": "print \"Hello World\"",
"output": "print(\"Hello World\")"
},
{
"instruction": "Compress the following string using the gzip module.",
"input": "my_string = \"This is a string that needs to be compressed!\"",
"output": "import gzip\n\nwith gzip.open('string.gz', 'wb') as f:\n f.write(my_string.encode())"
},
{
"instruction": "Write a python program to print the Odd numbers from the list.",
"input": "my_list = [1,2,3,4,5,6,7,8,9]",
"output": "for i in my_list:\n if i % 2 == 1:\n print(i)"
},
{
"instruction": "Write a single line of code to convert this list to a set.",
"input": "my_list = [1,2,3,3,3,3,4]",
"output": "myset = set(my_list)"
},
{
"instruction": "Debug the following code to make it run without errors.",
"input": "def my_func(p1, p2):\n return p1 - p2\n \nprint(my_func(4))",
"output": "def my_func(p1, p2):\n if p2 is None:\n p2 = 0\n return p1 - p2\n \nprint(my_func(4))"
},
{
"instruction": "Write a code snippet that counts the number of occurrences of a certain character in a given string.",
"input": "my_string = \"Hello world!\"\ncharacter = \"l\"",
"output": "count = my_string.count(character)\nprint(count)"
},
{
"instruction": "Write a single line of code to select all the even numbers from the given list.",
"input": "my_list = [1,2,3,4,5,6,7,8,9]",
"output": "even_list = [num for num in my_list if num % 2 == 0]"
},
{
"instruction": "Write a function which takes a list as an input and returns a dictionary using the list values as keys and the corresponding index as value.",
"input": "my_list = ['a', 'b', 'c', 'd']",
"output": "def list_to_dict(lst):\n return dict((v, i) for i, v in enumerate(lst))\n\ndict_from_list = list_to_dict(my_list)\nprint(dict_from_list)"
},
{
"instruction": "Write a code snippet to get the fifth element of the following list.",
"input": "my_list = [1,2,3,4,5,6,7,8,9]",
"output": "fifth_element = my_list[4]\nprint(fifth_element)"
},
{
"instruction": "Write a code snippet to change the third-element in the following tuple.",
"input": "my_tuple = (1,2,3,4,5)",
"output": "my_tuple = my_tuple[:2] + (10,) + my_tuple[3:]"
},
{
"instruction": "Using the following data structure, write a code snippet to get the value of the key 'dob'.",
"input": "person = {\n 'name': 'John',\n 'dob': 'Jan 1st, 2000',\n 'address': '123 Main Street'\n}",
"output": "dob = person['dob']\nprint(dob)"
},
{
"instruction": "Develop a code snippet to remove the item from the following list.",
"input": "my_list = [1,2,3,4,5]",
"output": "my_list.remove(3)"
},
{
"instruction": "How can we evaluate a Machine learning model?",
"input": "",
"output": "We can evaluate a machine learning model by using metrics such as accuracy, precision, recall, ROC AUC, F1 score, log loss, etc. We can also use cross-validation such as k-fold validation to estimate the model performance on unseen data. Additionally, we can use validation curves, confusion matrix, and different learning curves to diagnose potential bias or variance problems with the models."
},
{
"instruction": "Find the most frequent 5 words in a string",
"input": "String = \"Python is a high-level programming language.\"",
"output": "def most_frequent_words(string):\n words = string.split(' ')\n word_freq = {}\n for word in words:\n if word in word_freq:\n word_freq[word] += 1\n else:\n word_freq[word] = 1\n sorted_words = sorted(word_freq.items(), key=lambda x:x[1], reverse=True)\n return sorted_words[:5]"
},
{
"instruction": "Create a loop using \"for\" that prints the numbers 0 to 5",
"input": "",
"output": "for i in range(6):\n print(i)"
},
{
"instruction": "Compute the inverse of a matrix",
"input": "Matrix = [1,2,3; 4,5,6; 7,8,9]",
"output": "def inverse_matrix(M):\n det = M[0][0]*(M[1][1]*M[2][2]- M[2][1]*M[1][2]) - M[0][1]*(M[1][0]*M[2][2]- M[1][2]*M[2][0]) + M[0][2]*(M[1][0]*M[2][1]- M[1][1]*M[2][0])\n if det == 0:\n return \"The determinant is 0, so the inverse matrix doesn't exist\"\n else:\n inv_matrix = [[(M[1][1]*M[2][2]- M[2][1]*M[1][2])/det, -(M[0][1]*M[2][2] - M[2][1]*M[0][2])/det, (M[0][1]*M[1][2]- M[1][1]*M[0][2])/det],\n [-(M[1][0]*M[2][2] - M[2][0]*M[1][2])/det , (M[0][0]*M[2][2] - M[2][0]*M[0][2])/det, -(M[0][0]*M[1][2] - M[1][0]*M[0][2])/det],\n [(M[1][0]*M[2][1] - M[2][0]*M[1][1])/det, -(M[0][0]*M[2][1] - M[2][0]*M[0][1])/det, (M[0][0]*M[1][1] - M[1][0]*M[0][1])/det]]\n return inv_matrix"
},
{
"instruction": "Find the smallest prime number in the list.",
"input": "List = [4,7,11,13,15]",
"output": "The smallest prime number in the list is 7."
},
{
"instruction": "Convert the given string to camelCase",
"input": "String = \"this_is_mango\"",
"output": "def convert_to_camelCase(string):\n words = string.split('_')\n words = [word[0].upper() + word[1:] for word in words]\n return ''.join(words)\n\nconverted_string = convert_to_camelCase(string)\nprint(converted_string)\n# Output: thisIsMango"
},
{
"instruction": "Write a code to generate a random integer within a given range",
"input": "Minimum = 10\nMaximum = 20",
"output": "import random\n\ndef random_int_generator(min_val, max_val):\n return random.randint(min_val, max_val)\n\nprint(random_int_generator(10, 20))"
},
{
"instruction": "How would you monitor your model's performance?",
"input": "",
"output": "We can monitor our model\u2019s performance by measuring metrics such as accuracy, precision, recall, F1 score, ROC AUC, log loss, etc. We can also create validation curves and learning curves, plot confusion matrices, and perform k-fold cross-validation to evaluate our models. Additionally, we can use scatter plots, regression metrics and train/validation loss plots to visualize how our model performs under different conditions."
},
{
"instruction": "Populate the Dictionary with the following keys and values",
"input": "Key1 : Value1, Key2: Value2",
"output": "dictionary = {\n \"Key1\": \"Value1\",\n \"Key2\": \"Value2\"\n}"
},
{
"instruction": "Explain the concept of supervised machine learning",
"input": "",
"output": "Supervised machine learning is a type of machine learning algorithm that uses labeled data to train the model. Labeled data is composed of input features and output labels. The input features are used to learn the relationships between the features and labels. Then, the model is tested on unseen data and its performance is evaluated. Supervised machine learning can be used for classification and regression tasks."
},
{
"instruction": "Normalize the given data",
"input": "Data = [-3, 4, 2, 0, 1]",
"output": "def normalize_data(data):\n min_value = min(data)\n max_value = max(data)\n normalized_data = [(x - min_value) / (max_value - min_value) for x in data]\n return normalized_data\n\nprint(normalize_data([-3, 4, 2, 0, 1]))\n# Output: [-1.0, 1.0, 0.25, 0.0, 0.5]"
},
{
"instruction": "Find the longest palindrome in a given string",
"input": "String = \"leveled\"",
"output": "def longest_palindrome(string):\n s_len = len(string)\n l_palindrome = \"\"\n\n i = 0\n while i < s_len:\n j = s_len\n while j > i:\n if string[i:j] == string[i:j][::-1]:\n if len(string[i:j]) > len(l_palindrome):\n l_palindrome = string[i:j]\n j -= 1\n i += 1\n\n return l_palindrome\n\nprint(longest_palindrome(\"leveled\"))\n# Output: leve"
},
{
"instruction": "Write an algorithm to traverse a binary tree",
"input": "",
"output": "def traverse_binary_tree(node): \n if node is None: \n return\n \n # First visit the root \n print(node.data) \n \n # Traverse Left Subtree \n traverse_binary_tree(node.left) \n \n # Traverse Right Subtree \n traverse_binary_tree(node.right)"
},
{
"instruction": "Convert a given temperature from Celsius to Fahrenheit",
"input": "Temp = 100",
"output": "def convert_celsius_to_fahrenheit(temp):\n return temp * 9/5 + 32\n\nprint(convert_celsius_to_fahrenheit(100))\n# Output: 212"
},
{
"instruction": "Explain the working of bubble sort algorithm.",
"input": "",
"output": "Bubble sort is a simple sorting algorithm that repeatedly steps through a list, compares adjacent elements and swaps them if they are in the wrong order. The pass through the list is repeated until the list is sorted. The algorithm, which is also known as sinking sort, starts at the beginning of the list and compares each pair of adjacent items and swaps them if they are in the wrong order. It then moves onto the next pair, and so on, until it reaches the end of the list. The algorithm needs to be repeated several times until all items are sorted."
},
{
"instruction": "Create a C program that lists all prime numbers between 1 and 50.",
"input": "",
"output": "#include<stdio.h>\nint main()\n{\n int num, count, i;\n printf(\"The prime numbers between 1 to 50 are:\\n\");\n for(num=1; num<=50; num++)\n {\n count=0;\n for(i=2; i<num; i++)\n {\n if(num%i==0)\n {\n count++;\n break;\n }\n }\n \n if(count==0)\n printf(\"%d\\n\",num);\n }\n \n return 0;\n}"
},
{
"instruction": "Write a SQL query to retrieve the maximum salary a department has paid.",
"input": "Table name: Salary\nColumns: Department_ID, Salary\n\n<noinput>",
"output": "SELECT MAX(Salary)\nFROM Salary"
},
{
"instruction": "Explain what is a deque (double-ended queue) in Python.",
"input": "",
"output": "A deque (short for \"double-ended queue\") is a data structure in Python that allows for the insertion and removal of data from either end of the structure. It is similar to a list but with the added benefit of allowing for elements to be added and removed from both the front and back of the structure giving it O(1) complexity for insertion and deletion compared to a list O(n) insertion and deletion. Deques are often used in applications where quickly inserting and removing elements from both ends of the data structure is necessary."
},
{
"instruction": "How is a hash table used in database management?",
"input": "",
"output": "A hash table is a data structure that is commonly used in database management systems. It is used to quickly store and retrieve data by treating the table as an array by computing a specific data item's index within the table based on a \"hash function\". One of the main benefits of using a hash table is that it allows for quick access to an element through a unique key, and provides a way to immediately locate a specific item in a database without having to traverse the entire database."
},
{
"instruction": "Create a program to analyze the sentiment of a given text.",
"input": "\"I love this software!\"",
"output": "def analyze_sentiment(text):\n positive_words = [\"love\", \"like\", \"enjoy\", \"happy\", \"amazing\"]\n sentiment = 0\n for word in text.split():\n if word in positive_words:\n sentiment += 1\n return sentiment\n\nsentiment = analyze_sentiment(\"I love this software!\")\nprint(sentiment) # Output: 1"
},
{
"instruction": "Describe the kernel methods of machine learning?",
"input": "",
"output": "Kernel methods are a form of machine learning algorithms that are based on \"kernel functions\". These functions map the data into a higher-dimensional space, which allows for a non-linear decision boundary to be created. Kernel functions also allow more complex relationships between the data points to be discovered. This is useful in tasks such as pattern recognition, feature extraction, and numerical optimization. Popular kernel methods include support vector machines, gaussian processes and radial basis functions."
},
{
"instruction": "Explain difference between linear regression and logistic regression.",
"input": "",
"output": "Linear regression is a type of predictive modeling technique which is used to predict continuous variables like sales, cost, price, etc. Linear regression is used to establish a linear relationship between a dependent variable and one or more independent variables.\nLogistic regression is a type of predictive modeling technique which is used to predict a binary outcome like whether a customer will buy a product or not. Logistic regression is used to establish a relationship between a dependent variable and one or more independent variables where the output is in the form of probability, either 0 or 1."
},
{
"instruction": "Give an example of a recursive function.",
"input": "",
"output": "def factorial(n): \n if n == 1: \n return 1 \n else: \n return n*factorial(n-1)"
},
{
"instruction": "What is the output of the following code\n\"print(1 + 2 * 3)\"",
"input": "",
"output": "7"
},
{
"instruction": "Create a function that prints a triangle of specified height.",
"input": "",
"output": "def triangle(n): \n for i in range(n): \n for j in range(i+1): \n print(\"*\", end=\"\") \n print(\"\") \n \ntriangle(4) \n\n# Output:\n# *\n# **\n# ***\n# ****"
},
{
"instruction": "Design a function that takes an array of integers as an argument and returns the median of the array.",
"input": "[2, 3, 5, 7, 11, 13]",
"output": "def find_median(arr):\n arr.sort()\n length = len(arr)\n if length % 2 == 0:\n return (arr[(length)//2] + arr[(length)//2 - 1]) / 2\n else:\n return arr[(length - 1)//2]"
},
{
"instruction": "Write a Java program to count the number of vowels and consonants in a given string.",
"input": "",
"output": "public static int countVowelsAndConsonants(String str) {\n int vowels = 0;\n int consonants = 0;\n for(int i = 0; i < str.length(); i++) {\n char c = str.charAt(i);\n if(c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') {\n vowels++;\n }\n else if((c >= 'a' && c <= 'z')) {\n consonants++;\n }\n }\n \n return vowels + consonants;\n}"
},
{
"instruction": "Design a program to generate Fibonacci sequence up to the n-th term.",
"input": "",
"output": "def fibonacci(n):\n fibarray = [0, 1]\n for i in range(2,n):\n fibarray.append(fibarray[i-2] + fibarray[i-1])\n return fibarray[n-1]"
},
{
"instruction": "Write a Python program to remove all adjacent duplicates from a string.",
"input": "\"aaabccddd\"",
"output": "def remove_adjacent_duplicates(string):\n result = ''\n for c in string:\n if result and result[-1] == c:\n continue\n result += c\n return result"
},
{
"instruction": "Write an efficient SQL query to get the second highest salary in a given table named 'employees'.",
"input": "",
"output": "SELECT MAX(salary) FROM employees WHERE salary NOT IN (SELECT MAX(salary) FROM employees);"
},
{
"instruction": "Design a Java program to sort elements in an array using insertion sort.",
"input": "",
"output": "public static void insertionSort(int arr[]) \n{ \n int n = arr.length; \n for (int i = 1; i < n; ++i) { \n int key = arr[i]; \n int j = i - 1; \n while (j >= 0 && arr[j] > key) { \n arr[j + 1] = arr[j]; \n j = j - 1; \n } \n arr[j + 1] = key; \n } \n}"
},
{
"instruction": "Generate a random string made up of lowercase letters.",
"input": "",
"output": "import string\nimport random\n\ndef generate_random_string(length):\n letters = string.ascii_lowercase\n return ''.join(random.choice(letters) for _ in range(length))"
},
{
"instruction": "Design an algorithm to find the longest common substring between two strings.",
"input": "\"abcdefgh\" and \"xyzabcde\"",
"output": "def longest_common_substring(str1, str2):\n\n n1 = len(str1)\n n2 = len(str2)\n result = \"\"\n len_result = 0\n mat = [[0 for x in range(n2)] for y in range(n1)]\n\n for i in range(n1):\n for j in range(n2):\n if str1[i] == str2[j]:\n if i == 0 or j == 0:\n mat[i][j] = 1\n\n else:\n mat[i][j] = mat[i-1][j-1]+1\n\n if mat[i][j]>len_result:\n len_result = mat[i][j]\n result = str1[i-len_result+1:i+1] # get the actual substring\n\n return result"
},
{
"instruction": "Build a program to convert a given integer to its binary form.",
"input": "",
"output": "def to_binary(n): \n if n > 1: \n to_binary(n//2) \n print(n % 2,end = '')"
},
{
"instruction": "Design a function to count the number of occurrences of a particular character in a given string.",
"input": "\"Hello World!\" and 'o'",
"output": "def count_occurrences(string, char):\n count = 0\n for c in string:\n if c == char:\n count += 1\n return count"
},
{
"instruction": "Write a function in Java to calculate the area of a triangle given 3 sides.",
"input": "Side1 = 4; Side2 = 5; Side3 = 6",
"output": "public static float triangleArea(float a, float b, float c) { \n //calculate the semi-perimeter \n float s = (a + b + c) / 2; \n \n //calculate the area \n float area = (float)Math.sqrt(s * (s - a) * (s - b) * (s - c)); \n return area;\n}"
},
{
"instruction": "How can you print out the contents of a variable in JavaScript?",
"input": "",
"output": "You can use the \"console.log\" function to print out the contents of a variable in JavaScript. The syntax would be \"console.log(variable_name)\"."
},
{
"instruction": "Write a regular expression pattern to match any email address.",
"input": "",
"output": "The regular expression pattern to match any email address is:\n/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,}$/i"
},
{
"instruction": "Write an HTML code snippet to create an anchor link to a website.",
"input": "The URL is https://www.example.com",
"output": "<a href=\"https://www.example.com\">Go to example.com</a>"
},
{
"instruction": "Write a JavaScript code to validate a given form.",
"input": "The form has two input fields named 'username' and 'password'",
"output": "function validateForm() {\n let username = document.getElementById('username').value;\n let password = document.getElementById('password').value;\n\n if(username.length < 5) {\n alert('Username should at least have 5 characters!');\n return false;\n }\n\n if(password.length < 8) {\n alert('Password should at least have 8 characters!');\n return false;\n }\n\n return true;\n}"
},
{
"instruction": "How can you check the version of installed Node Package Manager (NPM) package?",
"input": "",
"output": "You can run the command \"npm -v\" in the terminal to check the version of an installed NPM package."
},
{
"instruction": "Write a C++ code to access JSON data in a given string.",
"input": "String: {\u201cname\u201d : \u201cJohn\u201d, \u201cage\u201d : 30}",
"output": "#include <iostream>\n#include <string>\n#include <json/json.h>\n\nint main() {\n std::string json_string = \"{\\\"name\\\" : \\\"John\\\", \\\"age\\\" : 30}\";\n Json::Value root; \n Json::Reader reader;\n\n bool parsedSuccess = reader.parse(json_string, root, false);\n\n if(!parsedSuccess) {\n std::cout << \"Failed to parse JSON\" << std::endl;\n return 1;\n }\n\n std::string name = root.get(\"name\", \"\").asString();\n int age = root.get(\"age\", 0).asInt();\n\n std::cout << \"Name : \" << name << std::endl;\n std::cout << \"Age : \" << age << std::endl;\n\n return 0;\n}"
},
{
"instruction": "How can you set a cookie in PHP?",
"input": "",
"output": "You can use the setcookie() function to set a cookie in PHP. The syntax is setcookie(\"name\", \"value\", expiration);"
},
{
"instruction": "Describe any five of the React lifecycle methods.",
"input": "",
"output": "1. componentDidMount() - This is called immediately after a component is mounted to the DOM.\n2. componentWillUnmount() - This is called when a component is being unmounted from the DOM.\n3. shouldComponentUpdate() - This method is used to limit unnecessary re-rendering of a component, by returning false when the component's state does not need updating.\n4. getDerivedStateFromProps() - This method is invoked right before calling the render method. It is used for setting state.\n5. componentDidUpdate() - This is called immediately after the component's update is propagated to the DOM. It can be used for updating the DOM in response to prop or state changes."
},
{
"instruction": "How can you run a Python script from the command line?",
"input": "",
"output": "You can run a Python script from the command line by using the \"python\" command followed by the name of the Python file. The syntax would be \"python script_name.py\"."
},
{
"instruction": "Write a MySQL query to display the most recent five records from a table named 'products'.",
"input": "",
"output": "SELECT * FROM products ORDER BY id DESC LIMIT 5;"
},
{
"instruction": "How can you convert an integer to a string in Java?",
"input": "",
"output": "You can convert an integer to a string in Java by using the Integer.toString() method. The syntax would be \"String str = Integer.toString(int_value)\"."
},
{
"instruction": "Create a function to calculate average speed of a car based on distance and time.",
"input": "Distance covered: 20 miles\nTime taken: 40 minutes",
"output": "\"\"\"\nCreate a function to calculate the average speed of a car.\n\"\"\"\n\ndef avg_speed(distance, time):\n #Convert minutes to hours \n time_hours = time/60\n #Calculate speed\n speed = distance / time_hours\n return speed\n\nif __name__ == '__main__':\n distance = 20\n time = 40\n speed = avg_speed(distance, time)\n print(\"Average speed:\", speed, \"miles/hour\")"
},
{
"instruction": "Write a loop to print the numbers from 1-10 in Ascending Order.",
"input": "",
"output": "for i in range(1,11):\n print(i)"
},
{
"instruction": "Write a function for reversing a given string.",
"input": "String : hello world",
"output": "\"\"\"\nWrite a function for revering a given string.\n\"\"\"\n\ndef reverse_string(string):\n reversed_str = \"\" \n for char in string: \n reversed_str = char + reversed_str \n \n return reversed_str \n \nif __name__ == '__main__':\n string = \"hello world\"\n print(\"The original string is : \",string) \n print(\"The reversed string is : \",reverse_string(string))"
},
{
"instruction": "Sort this input array [1, 6, 4, 3, 0, 9] in ascending order.",
"input": "[1, 6, 4, 3, 0, 9]",
"output": "[0, 1, 3, 4, 6, 9]"
},
{
"instruction": "Write a function for merging two lists.",
"input": "list1=[21, 56, 78, 4]\nlist2=[56, 98, 19, 34]",
"output": "\"\"\"\nWrite a function for merging two lists.\n\"\"\"\n\ndef merge_lists(list1, list2):\n return list1 + list2\n\nif __name__ == '__main__': \n list1 = [21, 56, 78, 4]\n list2 = [56, 98, 19, 34]\n print(\"Merged list: \",merge_lists(list1, list2))"
},
{
"instruction": "Write a SQL query to get the records of employee name whose salary is higher than 10000.",
"input": "",
"output": "SELECT name FROM employee WHERE salary > 10000;"
},
{
"instruction": "Convert the given list ['apple', 'banana', 'cherry', 'mango'] to a Dictionary",
"input": "['apple', 'banana', 'cherry', 'mango']",
"output": "dict = {'apple': 0, 'banana': 1, 'cherry': 2, 'mango': 3}"
},
{
"instruction": "Create a function that calculates the total cost based on quantity of items and price.",
"input": "Quantity: 4\nPrice: $20",
"output": "\"\"\"\nCreate a function that calculates the total cost based on quantity of items and price.\n\"\"\"\n\ndef total_cost(quantity, price):\n return quantity * price\n\nif __name__ == '__main__': \n quantity = 4\n price = 20\n print(\"The total cost is: \", total_cost(quantity, price))"
},
{
"instruction": "Write a code to sort an input array of 3 numbers [10, 9, 8] in Descending Order.",
"input": "[10, 9, 8]",
"output": "array = [10, 9, 8]\n\n# Sort array in descending order\narray.sort(reverse=True)\nprint(array) # [10, 9, 8]"
},
{
"instruction": "Construct a for loop to generate a list of the form [0, 2, 6, 12, 20].",
"input": "",
"output": "# Construct a for loop to generate a list of the form [0, 2, 6, 12, 20]\n\nlist = []\n\nfor i in range(5):\n list.append(i*(i+1))\n\nprint(list) # [0, 2, 6, 12, 20]"
},
{
"instruction": "Create a program in Java that takes in an array of integers and returns the sum of all the elements.",
"input": "[1, 2, 3, 4, 5]",
"output": "public static int sumIntArray(int[] arr) { \n \n int sum = 0; \n \n for (int i = 0; i < arr.length; i++) \n sum += arr[i]; \n \n return sum; \n}"
},
{
"instruction": "Build an SQL query to select all rows from the table \"customers\" where the first column contains the value \"John\".",
"input": "",
"output": "SELECT * FROM customers WHERE customers.c1 = 'John';"
},
{
"instruction": "Design and implement an HTML form that supports a two-level drop down menu.",
"input": "",
"output": "<form>\n <select>\n <option value=\"level1\">Level 1</option>\n <optgroup label=\"Level 2\">\n <option value=\"2.1\">Option 2.1</option>\n <option value=\"2.2\">Option 2.2</option>\n <option value=\"2.3\">Option 2.3</option>\n </optgroup>\n </select>\n <input type=\"submit\">\n</form>"
},
{
"instruction": "Create a program in C# to generate a random password of length 8 characters that contains alphanumeric characters.",
"input": "",
"output": "public static string GeneratePassword(int length){\n string chars = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\";\n var stringChars = new char[length];\n var random = new Random();\n \n for (int i = 0; i < stringChars.Length; i++)\n {\n stringChars[i] = chars[random.Next(chars.Length)];\n }\n \n return new String(stringChars);\n}"
},
{
"instruction": "Create a function in R that prints the factorial of a given number.",
"input": "",
"output": "factorial <- function(x) {\n if (x <= 1)\n return(1)\n else\n return(x * factorial(x-1))\n}"
},
{
"instruction": "Design a regex expression that validates a given password based on a given criteria.",
"input": "Password must have at least one lowercase letter, one uppercase letter, one number and should be at least 6 characters long.",
"output": "^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])[a-zA-Z0-9]{6,}$"
},
{
"instruction": "Write a JavaScript code to get the length of an array.",
"input": "",
"output": "let arr = [1, 2, 3];\nlet arrLength = arr.length;"
},
{
"instruction": "Generate a MySQL query to retrieve all rows from a table that have a certain value in one column.",
"input": "Table Name: customers \nSearch Value: John",
"output": "SELECT * FROM customers WHERE customers.c1 = 'John'"
},
{
"instruction": "Create a CSS code to set the font size of a paragraph to 12px.",
"input": "",
"output": "p {\n font-size: 12px;\n}"
},
{
"instruction": "Write a Ruby program to count the number of times a given character appears in a string.",
"input": "String: \"Apple\", Character: 'p'",
"output": "def count_char(string, char)\n count = 0\n string.each_char { |c| count += 1 if c == char }\n count\nend\n\nputs count_char('Apple', 'p')"
},
{
"instruction": "Develop a C program to calculate the mean of a given array of integers.",
"input": "[1, 2, 3, 4]",
"output": "#include <stdio.h>\n \nint main() \n{\n int arr[] = {1, 2, 3, 4};\n int n = sizeof(arr)/sizeof(arr[0]); \n float mean = getMean(arr, n); \n printf(\"Mean = %.2f\", mean); \n return 0; \n} \n\nfloat getMean(int arr[], int n) \n{ \n int sum = 0; \n for (int i = 0; i < n; i++) \n sum += arr[i]; \n \n return (float)sum/(float)n; \n}"
},
{
"instruction": "Construct a Django code for creating a Web application.",
"input": "",
"output": "from django.conf.urls import url\nfrom .import views\n\nurlpatterns = [\n url(r'^$', views.my_view, name='my_view'),\n]"
},
{
"instruction": "Code a PHP program to delete a value from an associative array whose key is given.",
"input": "Array: ['Name' => 'John', 'Age' => 20], Key: 'Name'",
"output": "$arr = array('Name' => 'John', 'Age' => 20);\n\nfunction deleteValue($arr, $key) {\n if (array_key_exists($key, $arr)) {\n \tunset($arr[$key]);\n }\n return $arr;\n} \n\n$arr = deleteValue($arr, 'Name');"
},
{
"instruction": "Implement a Java program to sort an array of strings alphabetically.",
"input": "[\"cat\", \"dog\", \"elephant\", \"apple\"]",
"output": "public class sortingExample {\n public static void main(String[] args)\n {\n String[] words = { \"cat\", \"dog\", \"elephant\", \"apple\" };\n Arrays.sort(words);\n\n System.out.println(\"Sorted words: \" + Arrays.toString(words));\n }\n}"
},
{
"instruction": "Create a function to return the length of the longest word in a given sentence.",
"input": "sent = \"This is a sample sentence with a lot of words.\"",
"output": "def find_longest_word_length(sent):\n # split the sentence into words \n words = sent.split()\n\n # iterate through words and find the length of the longest one\n longest_word_length = 0\n for word in words:\n word_length = len(word)\n if word_length > longest_word_length:\n longest_word_length = word_length\n \n # return the longest word length\n return longest_word_length"
},
{
"instruction": "Sort the following items in numerical order using the bubble sort algorithm in Python.",
"input": "arr = [2, 4, 1, 4, 6]",
"output": "def bubbleSort(arr):\n n = len(arr)\n # Traverse through all array elements \n for i in range(n): \n\t# Last i elements are already in place \n\tfor j in range(0, n-i-1): \n\t\t# Traverse the array from 0 to n-i-1 \n\t\t# Swap if the element found is greater \n\t\t# than the next element \n\t\tif arr[j] > arr[j+1] : \n\t\t\tarr[j], arr[j+1] = arr[j+1], arr[j]\n\n# Driver code to test above \narr = [2, 4, 1, 4, 6]\nbubbleSort(arr) \nprint (\"Sorted array is:\") \nfor i in range(len(arr)): \n\tprint (\"%d\" %arr[i]),"
},
{
"instruction": "Write code to print the square root of a given number using the Newton-Raphson Method in Java.",
"input": "number = 25",
"output": "import java.util.Scanner;\n\npublic class SquareRootByNewtonRaphson {\n\n\tpublic static void main(String[] args) {\n\t\tdouble number, root;\n\t\t\n\t\tScanner scan = new Scanner(System.in);\n\t\t\n\t\tSystem.out.print(\"Enter the number: \");\n\t\tnumber = scan.nextDouble();\n\t\t\n\t\troot = number / 2;\n\t\t\n\t\twhile (root - (number / root) > 0.001) {\n\t\t root = (root + (number / root)) / 2;\n\t\t}\n\t\t \n\t\tSystem.out.println(\"Square root of \"+number+\" is: \"+root);\n\t\t\n\t\tscan.close();\n\t}\n\n}"
},
{
"instruction": "Write an algorithm to print the sum of all elements from a given array in Java.",
"input": "int[] arr = {1, 2, 3, 4, 5};",
"output": "public class SumOfArrayElements {\n\n\tpublic static void main(String args[]) {\n\t\tint[] arr = { 1, 2, 3, 4, 5 };\n\t\t\n\t\t// Initializing sum\n\t\tint sum = 0;\n\t\t\n\t\t// Iterating array elements\n\t\tfor(int i=0; i<arr.length; i++)\n\t\t\tsum += arr[i];\n\t\t\n\t\tSystem.out.println(\"Sum of array elements is: \" + sum);\n\t}\n\n}"
},
{
"instruction": "Create a C++ program to find the last occurrence of a given character in a string.",
"input": "String s = \"Hello world\";",
"output": "#include<iostream>\n#include<string>\n\nusing namespace std;\n\nint last_occurrence(string s, char c) \n{ \n int n = s.length(); \n \n int index = -1;\n for (int i = 0; i<n; i++) { \n if (s[i] == c)\n index = i;\n } \n \n return index;\n} \n\nint main() \n{ \n string s = \"Hello world\"; \n char c = 'l'; \n cout << \"Last occurrence of the character '\" << c\n << \"' is at position \" << last_occurrence(s, c); \n return 0; \n}"