messages
listlengths
2
2
instruction
stringlengths
14
288
input
stringlengths
0
635
output
stringlengths
1
3.91k
[ { "role": "user", "content": "Design a class named Car and build its constructor." }, { "role": "assistant", "content": "Class Car{\n // constructor\n Car(){ \n // instance variables\n this.make = \"\";\n this.model = \"\";\n this.year = 0;\n }\n}" } ]
Design a class named Car and build its constructor.
Class Car{ // constructor Car(){ // instance variables this.make = ""; this.model = ""; this.year = 0; } }
[ { "role": "user", "content": "Compute the number of ways for a host to select 3 items from a list of 8 options." }, { "role": "assistant", "content": "def compute_combination(n, r):\n \"\"\"\n Compute the number of ways for a host to select 'r' items from\n a list of 'n' options.\n\n ...
Compute the number of ways for a host to select 3 items from a list of 8 options.
def compute_combination(n, r): """ Compute the number of ways for a host to select 'r' items from a list of 'n' options. Parameters ---------- n : int The total number of items r : int The number of items to select Returns ------- num : int The number of...
[ { "role": "user", "content": "Given a list of strings, write a Python program to print each individual string in uppercase.\n\nstring_list = [\"apple\",\"banana\",\"oranges\"]" }, { "role": "assistant", "content": "def print_uppercase(string_list):\n for string in string_list:\n print(string...
Given a list of strings, write a Python program to print each individual string in uppercase.
string_list = ["apple","banana","oranges"]
def print_uppercase(string_list): for string in string_list: print(string.upper())
[ { "role": "user", "content": "You are given a string of symbols. Write a program to remove all the symbols and get a valid text string.\n\n\"This , is an example string %\"" }, { "role": "assistant", "content": "def remove_symbols(string):\n text_string = ''\n for c in string:\n if c.isalph...
You are given a string of symbols. Write a program to remove all the symbols and get a valid text string.
"This , is an example string %"
def remove_symbols(string): text_string = '' for c in string: if c.isalpha() or c.isdigit(): text_string += c return text_string print(remove_symbols("This , is an example string %"))
[ { "role": "user", "content": "Compile a Java program using the command line." }, { "role": "assistant", "content": "javac filename.java" } ]
Compile a Java program using the command line.
javac filename.java
[ { "role": "user", "content": "What data structure would be best to store an employee roster containing their name, age, and gender?" }, { "role": "assistant", "content": "The best data structure for storing an employee roster containing their name, age, and gender would be a hash table. A hash t...
What data structure would be best to store an employee roster containing their name, age, and gender?
The best data structure for storing an employee roster containing their name, age, and gender would be a hash table. A hash table is a data structure that allows for fast lookups and inserts by mapping values to keys. Each employee can be stored as a key-value pair, with their name, age, and gender as the respective va...
[ { "role": "user", "content": "Create a python class to represent a 3x3 matrix" }, { "role": "assistant", "content": "class Matrix:\n def __init__(self, array):\n self.array = array\n self.rows = len(array)\n self.cols = len(array[0])\n\n def get_matrix(self):\n ...
Create a python class to represent a 3x3 matrix
class Matrix: def __init__(self, array): self.array = array self.rows = len(array) self.cols = len(array[0]) def get_matrix(self): return self.array def set_matrix(self, array): self.rows = len(array) self.cols = len(array[0]) self.array = array if ...
[ { "role": "user", "content": "Write a CSS code snippet to set the default font size to 16px and color to green for all links." }, { "role": "assistant", "content": "a {\n font-size: 16px;\n color: green;\n}" } ]
Write a CSS code snippet to set the default font size to 16px and color to green for all links.
a { font-size: 16px; color: green; }
[ { "role": "user", "content": "Write a Python program to find the equilibrium index of an array. An index of an array is called equilibrium index if the sum of elements at lower indexes is equal to the sum of elements at higher indexes.\n\narr = [-7, 1, 9, -4, 3, 2]" }, { "role": "assistant", "co...
Write a Python program to find the equilibrium index of an array. An index of an array is called equilibrium index if the sum of elements at lower indexes is equal to the sum of elements at higher indexes.
arr = [-7, 1, 9, -4, 3, 2]
def find_equilibrium_index(arr): total_sum = sum(arr) left_sum = 0 for index, num in enumerate(arr): total_sum -= num if left_sum == total_sum: return index left_sum += num return -1 arr = [-7, 1, 9, -4, 3, 2] print(find_equilibrium_index(arr)) # Output: 2
[ { "role": "user", "content": "What type of loop can be used to iterate through the items of a list in Python?" }, { "role": "assistant", "content": "The most common type of loop for iterating through the items of a list in Python is the for loop. This loop iterates through each item in the list ...
What type of loop can be used to iterate through the items of a list in Python?
The most common type of loop for iterating through the items of a list in Python is the for loop. This loop iterates through each item in the list one by one, allowing the programmer to perform operations on each item in the list. For example: my_list = [1, 2, 3] for item in my_list: print(item) # Output # 1 # 2 ...
[ { "role": "user", "content": "Construct a boolean check to detect if a given string contains the word \"hello\"." }, { "role": "assistant", "content": "def contains_hello(input_string):\n return \"hello\" in input_string" } ]
Construct a boolean check to detect if a given string contains the word "hello".
def contains_hello(input_string): return "hello" in input_string
[ { "role": "user", "content": "Generate a Python function to get the index of a given string from a list of strings.\n\nlist_of_strings = [\"apple\", \"banana\", \"cherry\"]" }, { "role": "assistant", "content": "def find_index(list_of_strings, target_string):\n for i, string in enumerate(list...
Generate a Python function to get the index of a given string from a list of strings.
list_of_strings = ["apple", "banana", "cherry"]
def find_index(list_of_strings, target_string): for i, string in enumerate(list_of_strings): if string == target_string: return i return -1
[ { "role": "user", "content": "Edit the following HTML to make all text 16px font size.\n\n<h1>This is a heading</h1>\n<p>This is a paragraph.</p>" }, { "role": "assistant", "content": "<h1 style=\"font-size: 16px;\">This is a heading</h1>\n<p style=\"font-size: 16px;\">This is a paragraph.</p>" ...
Edit the following HTML to make all text 16px font size.
<h1>This is a heading</h1> <p>This is a paragraph.</p>
<h1 style="font-size: 16px;">This is a heading</h1> <p style="font-size: 16px;">This is a paragraph.</p>
[ { "role": "user", "content": "Use JavaScript to encrypt a given string using MD5 algorithm.\n\nstring = \"This is a test.\"" }, { "role": "assistant", "content": "let encryptedString = CryptoJS.MD5(string).toString();" } ]
Use JavaScript to encrypt a given string using MD5 algorithm.
string = "This is a test."
let encryptedString = CryptoJS.MD5(string).toString();
[ { "role": "user", "content": "Sort an array of characters in alphabetic order.\n\n['x', 'q', 'b', 'j']" }, { "role": "assistant", "content": "\"\"\"\nSort an array of characters in alphabetic order\n\"\"\"\n\ndef sort_alphabetically(arr):\n arr.sort()\n return arr\n\nif __name__ == '__main...
Sort an array of characters in alphabetic order.
['x', 'q', 'b', 'j']
""" Sort an array of characters in alphabetic order """ def sort_alphabetically(arr): arr.sort() return arr if __name__ == '__main__': print(sort_alphabetically(['x', 'q', 'b', 'j']))
[ { "role": "user", "content": "Write a PHP script to compare two strings and return the number of characters and words which are common in both strings\n\nThe quick brown fox jumps over the lazy dog\nThe brown fox jumps quickly" }, { "role": "assistant", "content": "<?php \n\n$string1 = \"The qui...
Write a PHP script to compare two strings and return the number of characters and words which are common in both strings
The quick brown fox jumps over the lazy dog The brown fox jumps quickly
<?php $string1 = "The quick brown fox jumps over the lazy dog"; $string2 = "The brown fox jumps quickly"; // Create two arrays from the strings $arr1 = explode(" ", $string1); $arr2 = explode(" ", $string2); // Initialize a variable to store the count of common words $wordCount = 0; // Initialize a variable...
[ { "role": "user", "content": "Write a Ruby program to create a class called \"Person\" with variables such as name, age, gender, etc." }, { "role": "assistant", "content": "class Person \n attr_accessor :name, :age, :gender \n \n def initialize(name, age, gender) \n @name = name \n @age...
Write a Ruby program to create a class called "Person" with variables such as name, age, gender, etc.
class Person attr_accessor :name, :age, :gender def initialize(name, age, gender) @name = name @age = age @gender = gender end end
[ { "role": "user", "content": "Create a program to tokenize a given string into a list of strings.\n\n'Hello! My name is Bob.'" }, { "role": "assistant", "content": "import nltk\n\ndef tokenize(string):\n tokens = nltk.word_tokenize(string)\n return tokens\n\nprint(tokenize('Hello! My name ...
Create a program to tokenize a given string into a list of strings.
'Hello! My name is Bob.'
import nltk def tokenize(string): tokens = nltk.word_tokenize(string) return tokens print(tokenize('Hello! My name is Bob.')) # prints ["Hello", "!", "My", "name", "is", "Bob", "."]
[ { "role": "user", "content": "Reduce the 3-dimensional numpy array to a 2-dimensional numpy array." }, { "role": "assistant", "content": "import numpy as np\n\na_3d_array = np.array([[[1,2], [3,4]], [[5,6], [7,8]]])\n\na_2d_array = a_3d_array.reshape(4,2)" } ]
Reduce the 3-dimensional numpy array to a 2-dimensional numpy array.
import numpy as np a_3d_array = np.array([[[1,2], [3,4]], [[5,6], [7,8]]]) a_2d_array = a_3d_array.reshape(4,2)
[ { "role": "user", "content": "Estimate the memory usage of the following array of integers.\n\nnums = [1, 4, 5, 8, 12, 15]" }, { "role": "assistant", "content": "The memory usage of the given array of integers is approximately 48 bytes. This is because each integer takes up 4 bytes of memory and...
Estimate the memory usage of the following array of integers.
nums = [1, 4, 5, 8, 12, 15]
The memory usage of the given array of integers is approximately 48 bytes. This is because each integer takes up 4 bytes of memory and there are 6 integers in the given array.
[ { "role": "user", "content": "Develop a C program to count and print the number of characters in a sentence.\n\nThe quick brown fox" }, { "role": "assistant", "content": "#include<stdio.h>\n\nint main(){\n char sentence[100];\n int count = 0;\n scanf(\"%[^\\n]s\", sentence);\n for (int i=0; ...
Develop a C program to count and print the number of characters in a sentence.
The quick brown fox
#include<stdio.h> int main(){ char sentence[100]; int count = 0; scanf("%[^\n]s", sentence); for (int i=0; sentence[i]!='\0'; i++){ count++; } printf("Number of characters: %d\n", count); return 0; }
[ { "role": "user", "content": "Construct an algorithm to detect a cycle in a linked list" }, { "role": "assistant", "content": "A cycle can be detected in a linked list using the Floyd's Algorithm. This algorithm works by using two pointers; a slow pointer and a fast pointer. The slow pointer mov...
Construct an algorithm to detect a cycle in a linked list
A cycle can be detected in a linked list using the Floyd's Algorithm. This algorithm works by using two pointers; a slow pointer and a fast pointer. The slow pointer moves one node of the list at a time, while the fast pointer moves two nodes at a time. If the two pointers point to the same node, then a cycle exists in...
[ { "role": "user", "content": "Convert the given input string to lower case keeping all other characters same.\n\nFEDCbA" }, { "role": "assistant", "content": "fedcba" } ]
Convert the given input string to lower case keeping all other characters same.
FEDCbA
fedcba
[ { "role": "user", "content": "Write a SQL statement to select all the authors whose age is greater than 18." }, { "role": "assistant", "content": "SELECT * \nFROM authors\nWHERE age > 18" } ]
Write a SQL statement to select all the authors whose age is greater than 18.
SELECT * FROM authors WHERE age > 18
[ { "role": "user", "content": "Normalize a column \"Weight\" in a Pandas dataframe." }, { "role": "assistant", "content": "import pandas as pd\n\n# Read data from csv file\ndf = pd.read_csv(\"data.csv\")\n\n# Normalize the column \"Weight\"\ndf['Weight']=(df['Weight']-df['Weight'].min())/(df['Wei...
Normalize a column "Weight" in a Pandas dataframe.
import pandas as pd # Read data from csv file df = pd.read_csv("data.csv") # Normalize the column "Weight" df['Weight']=(df['Weight']-df['Weight'].min())/(df['Weight'].max()-df['Weight'].min()) # Print the dataframe print(df)
[ { "role": "user", "content": "Write Java code to generate random numbers between 0 and 10." }, { "role": "assistant", "content": "Random rand = new Random(); \n \n// Generate random integers in range 0 to 10 \nint rand_int1 = rand.nextInt(11);" } ]
Write Java code to generate random numbers between 0 and 10.
Random rand = new Random(); // Generate random integers in range 0 to 10 int rand_int1 = rand.nextInt(11);
[ { "role": "user", "content": "Using a recursive algorithm, reverse the order of elements in a list.\n\narr = [1, 2, 3, 4, 5]" }, { "role": "assistant", "content": "# recursive approach\ndef recursive_reverse(arr, length):\n if length == 0:\n return\n\n recursive_reverse(arr, length ...
Using a recursive algorithm, reverse the order of elements in a list.
arr = [1, 2, 3, 4, 5]
# recursive approach def recursive_reverse(arr, length): if length == 0: return recursive_reverse(arr, length - 1) arr.append(arr[length - 1]) arr.pop(length - 1) # call function on the data recursive_reverse(arr, len(arr))
[ { "role": "user", "content": "Write a code to merge two given lists of equal size.\n\nlist1 = [1,2,3]\nlist2 = [4,5,6]" }, { "role": "assistant", "content": "\"\"\"\nWrite a code to merge two given lists of equal size\n\"\"\"\n\n# Given lists\nlist1 = [1,2,3]\nlist2 = [4,5,6]\n\n# Initialising a...
Write a code to merge two given lists of equal size.
list1 = [1,2,3] list2 = [4,5,6]
""" Write a code to merge two given lists of equal size """ # Given lists list1 = [1,2,3] list2 = [4,5,6] # Initialising an empty list merged_list = [] # Merging the lists for i in range(len(list1)): merged_list.append(list1[i]) merged_list.append(list2[i]) # Printing the merged list print("Merged list is",...
[ { "role": "user", "content": "Create a Python class with the same content as a JSON string.\n\nmyjson_string = '{\"name\": \"John\", \"age\": 20}'" }, { "role": "assistant", "content": "import json\n\nclass Person:\n def __init__(self, json_string):\n data = json.loads(json_string)\n self.name...
Create a Python class with the same content as a JSON string.
myjson_string = '{"name": "John", "age": 20}'
import json class Person: def __init__(self, json_string): data = json.loads(json_string) self.name = data['name'] self.age = data['age'] myjson_string = '{"name": "John", "age": 20}' person = Person(myjson_string) print(person.name, person.age)
[ { "role": "user", "content": "Create a MySQL query to list the authors and the number of books they wrote." }, { "role": "assistant", "content": "SELECT authors.name, COUNT(book.id)\nFROM authors INNER JOIN books\nON authors.id = books.author_id\nGROUP BY authors.name;" } ]
Create a MySQL query to list the authors and the number of books they wrote.
SELECT authors.name, COUNT(book.id) FROM authors INNER JOIN books ON authors.id = books.author_id GROUP BY authors.name;
[ { "role": "user", "content": "Edit the following HTML code to add a link to an external website.\n\n<div>\n <p>Hello!</p>\n</div>" }, { "role": "assistant", "content": "<div>\n <p>Hello! <a href=\"https://www.example.com\" target=\"_blank\">Visit my website</a></p>\n</div>" } ]
Edit the following HTML code to add a link to an external website.
<div> <p>Hello!</p> </div>
<div> <p>Hello! <a href="https://www.example.com" target="_blank">Visit my website</a></p> </div>
[ { "role": "user", "content": "Write a C++ program to print out a multiplication table up to 10x10." }, { "role": "assistant", "content": "#include <iostream>\nusing namespace std; \n \nint main() \n{ \n cout << \"Multiplication Table from 1 to 10:\" << endl; \n \n for (int i = 1; i <= 10...
Write a C++ program to print out a multiplication table up to 10x10.
#include <iostream> using namespace std; int main() { cout << "Multiplication Table from 1 to 10:" << endl; for (int i = 1; i <= 10; i++) { for (int j = 1; j <= 10; j++) { cout << i << "*" << j << " = " << i * j << endl; } cout << endl; } return 0; ...
[ { "role": "user", "content": "Generate a regular expression to match the following patterns\n\nwxyz - w:[a-c] x:[0-9] y:[a-z] z:[A-Z]" }, { "role": "assistant", "content": "^[a-c][0-9][a-z][A-Z]$" } ]
Generate a regular expression to match the following patterns
wxyz - w:[a-c] x:[0-9] y:[a-z] z:[A-Z]
^[a-c][0-9][a-z][A-Z]$
[ { "role": "user", "content": "Write a script in JavaScript to iterate over a given array of objects and return all objects with the color green.\n\nconst arr = [{ color: 'blue', shape: 'square' }, { color: 'red', shape: 'triangle' }, { color: 'green', shape: 'circle' }]" }, { "role": "assistant", ...
Write a script in JavaScript to iterate over a given array of objects and return all objects with the color green.
const arr = [{ color: 'blue', shape: 'square' }, { color: 'red', shape: 'triangle' }, { color: 'green', shape: 'circle' }]
const greenObjects = arr.filter(obj => obj.color === 'green');
[ { "role": "user", "content": "Explain the concept of the depth-first search algorithm and provide an example." }, { "role": "assistant", "content": "Depth-first search (DFS) is an algorithm used to traverse a tree or graph data structure. It starts at the root of the tree, explores as far as pos...
Explain the concept of the depth-first search algorithm and provide an example.
Depth-first search (DFS) is an algorithm used to traverse a tree or graph data structure. It starts at the root of the tree, explores as far as possible down a given branch and then backtracks along the same path before exploring a new branch. For example, consider a BST (Binary Search Tree) where we want to traverse a...
[ { "role": "user", "content": "Create a C program that asks for a user input, adds 10 to the value, and prints the result." }, { "role": "assistant", "content": "#include <stdio.h> \n \nint main() \n{ \n int num; \n printf(\"Enter a number: \"); \n scanf(\"%d\", &num);\n num += 10;\n ...
Create a C program that asks for a user input, adds 10 to the value, and prints the result.
#include <stdio.h> int main() { int num; printf("Enter a number: "); scanf("%d", &num); num += 10; printf("The result is %d", num); return 0; }
[ { "role": "user", "content": "Develop an algorithm in Java that removes duplicate elements from an array.\n\n[1, 3, 5, 3, 4, 5]" }, { "role": "assistant", "content": "public static int[] removeDuplicates(int[] arr) { \n int n = arr.length; \n \n // To store index of next unique element \n...
Develop an algorithm in Java that removes duplicate elements from an array.
[1, 3, 5, 3, 4, 5]
public static int[] removeDuplicates(int[] arr) { int n = arr.length; // To store index of next unique element int j = 0; // Doing same as done in Method 1 // Just maintaining another updated index i.e. j for (int i = 0; i < n-1; i++) if (arr[i] != arr[i+1] ) ar...
[ { "role": "user", "content": "Create a CSS class to make all the text in the body of the page blue." }, { "role": "assistant", "content": "body {\n font-color: blue;\n}" } ]
Create a CSS class to make all the text in the body of the page blue.
body { font-color: blue; }
[ { "role": "user", "content": "Create a function in C that takes a string as input and returns an integer, which represents the number of occurences of a given character in the string.\n\n\"Hello, World!\", 'o'" }, { "role": "assistant", "content": "int count_occurrences(char *str, char c) \n{ \n...
Create a function in C that takes a string as input and returns an integer, which represents the number of occurences of a given character in the string.
"Hello, World!", 'o'
int count_occurrences(char *str, char c) { int count = 0; // Traverse the string and check // for occurrences of character. for (int i=0; str[i] != '\0'; i++) if (str[i] == c) count++; return count; }
[ { "role": "user", "content": "Create a program in Ruby to print out all prime numbers up to a given positive integer m." }, { "role": "assistant", "content": "def is_prime?(num)\n is_prime = true\n for divisor in 2..(num-1)\n if (num % divisor == 0) \n is_prime = false\n break\n ...
Create a program in Ruby to print out all prime numbers up to a given positive integer m.
def is_prime?(num) is_prime = true for divisor in 2..(num-1) if (num % divisor == 0) is_prime = false break end end return is_prime end def primes_upto(m) primes = [] for n in 2..m primes << n if is_prime?(n) end return primes end
[ { "role": "user", "content": "Create a Python class for a student that holds their name, age and grade." }, { "role": "assistant", "content": "class Student:\n def __init__(self, name, age, grade):\n self.name = name\n self.age = age\n self.grade = grade\n\ndef get_student_info(self):\n retu...
Create a Python class for a student that holds their name, age and grade.
class Student: def __init__(self, name, age, grade): self.name = name self.age = age self.grade = grade def get_student_info(self): return (f"{self.name}, {self.age}, {self.grade}")
[ { "role": "user", "content": "Find out the number of odd numbers in an array\n\n[2, 9, 0, 5, 3]" }, { "role": "assistant", "content": "def odd_num(arr): \n count = 0\n for num in arr: \n if num % 2 != 0: \n count += 1\n return count \n \n# Test Array \narr = [2,...
Find out the number of odd numbers in an array
[2, 9, 0, 5, 3]
def odd_num(arr): count = 0 for num in arr: if num % 2 != 0: count += 1 return count # Test Array arr = [2, 9, 0, 5, 3] # Function Call odd_num(arr)
[ { "role": "user", "content": "Construct a CSS code that adds a background color of red to the ’div' element." }, { "role": "assistant", "content": "div {\n background-color: red;\n}" } ]
Construct a CSS code that adds a background color of red to the ’div' element.
div { background-color: red; }
[ { "role": "user", "content": "Write a Python program that generates a random integer between 1 and 5 and prints it out." }, { "role": "assistant", "content": "import random\n\nrandom_integer = random.randint(1, 5)\n\nprint(random_integer)" } ]
Write a Python program that generates a random integer between 1 and 5 and prints it out.
import random random_integer = random.randint(1, 5) print(random_integer)
[ { "role": "user", "content": "Insert a new row in the table Inventory with itemname as \"keyboard\", quantity of 10, and price of 10.25.\n\nTable structure:\n\n Inventory \n \nid | itemname | quantity | price |" }, { "role": "assistant", "content": "INSERT INTO Inventory (itemname, quantity, pri...
Insert a new row in the table Inventory with itemname as "keyboard", quantity of 10, and price of 10.25.
Table structure: Inventory id | itemname | quantity | price |
INSERT INTO Inventory (itemname, quantity, price) VALUES ('keyboard', 10, 10.25);
[ { "role": "user", "content": "Read the following block of code. What is the main goal of the code?\n\ndef first_duplicate(arr):\n seen = set()\n for i in arr:\n if i in seen:\n return i\n seen.add(i)\n return -1" }, { "role": "assistant", "content": "The main go...
Read the following block of code. What is the main goal of the code?
def first_duplicate(arr): seen = set() for i in arr: if i in seen: return i seen.add(i) return -1
The main goal of the code is to find the first duplicate element in an array.
[ { "role": "user", "content": "Convert the list of numbers below to a numpy array.\n\n[2, 4, 6, 8, 10]" }, { "role": "assistant", "content": "import numpy as np \n\narr = np.array([2,4,6,8,10])" } ]
Convert the list of numbers below to a numpy array.
[2, 4, 6, 8, 10]
import numpy as np arr = np.array([2,4,6,8,10])
[ { "role": "user", "content": "Write a Python program to determine if a given number is an Armstrong number." }, { "role": "assistant", "content": "def isArmstrongNumber(num):\n sum = 0\n temp = num\n while temp > 0:\n digit = temp % 10\n sum += digit ** 3\n temp //= 10\n if num == sum:\n ret...
Write a Python program to determine if a given number is an Armstrong number.
def isArmstrongNumber(num): sum = 0 temp = num while temp > 0: digit = temp % 10 sum += digit ** 3 temp //= 10 if num == sum: return True else: return False
[ { "role": "user", "content": "Print a binary tree level by level, starting from the root level." }, { "role": "assistant", "content": "#include<iostream>\n#include<queue>\nusing namespace std;\n\n// A Binary Tree Node\nstruct Node\n{\n int data;\n struct Node *left, *right;\n};\n \n// Func...
Print a binary tree level by level, starting from the root level.
#include<iostream> #include<queue> using namespace std; // A Binary Tree Node struct Node { int data; struct Node *left, *right; }; // Function to print the level order traversal of the tree void levelOrder(struct Node *root) { // Base Case if (root == NULL) return; // Create an empty queue fo...
[ { "role": "user", "content": "Develop a function in Java that, given a positive number, returns the factorial of that number.\n\nnum = 5" }, { "role": "assistant", "content": "public static int factorial(int num){\n if (num == 0){ \n return 1;\n }\n else{\n int factorial =...
Develop a function in Java that, given a positive number, returns the factorial of that number.
num = 5
public static int factorial(int num){ if (num == 0){ return 1; } else{ int factorial = num * factorial(num - 1); return factorial; } }
[ { "role": "user", "content": "Write a code snippet to read characters from a given string until a whitespace is encountered" }, { "role": "assistant", "content": "def read_until_space(string):\n result = \"\"\n for char in string:\n if char == \" \":\n break\n result += char\n re...
Write a code snippet to read characters from a given string until a whitespace is encountered
def read_until_space(string): result = "" for char in string: if char == " ": break result += char return result
[ { "role": "user", "content": "Prompt a clarification from the user when the reply provided is unclear\n\nInput Reply: I don't know" }, { "role": "assistant", "content": "Can you please explain what you mean when you say \"I don't know\"?" } ]
Prompt a clarification from the user when the reply provided is unclear
Input Reply: I don't know
Can you please explain what you mean when you say "I don't know"?
[ { "role": "user", "content": "What is the Python built-in function to swap two values?" }, { "role": "assistant", "content": "The Python built-in function to swap two values is the \"tuple unpacking\" operator (x, y = y, x). This allows you to swap two variables without having to use a temporary...
What is the Python built-in function to swap two values?
The Python built-in function to swap two values is the "tuple unpacking" operator (x, y = y, x). This allows you to swap two variables without having to use a temporary variable.
[ { "role": "user", "content": "Create an algorithm to detect if a linked list contains a cycle." }, { "role": "assistant", "content": "def has_cycle(head):\n slow = head\n fast = head\n while fast and fast.next:\n slow = slow.next\n fast = fast.next.next\n if slow ==...
Create an algorithm to detect if a linked list contains a cycle.
def has_cycle(head): slow = head fast = head while fast and fast.next: slow = slow.next fast = fast.next.next if slow == fast: return True return False
[ { "role": "user", "content": "Construct a for loop which adds up numbers." }, { "role": "assistant", "content": "nums = [3, 4, 5, 6]\ntotal = 0\n\nfor num in nums:\n total += num \n\nprint(total) # prints 18" } ]
Construct a for loop which adds up numbers.
nums = [3, 4, 5, 6] total = 0 for num in nums: total += num print(total) # prints 18
[ { "role": "user", "content": "Edit the provided code to yield the correct output.\n\ndef hello_world():\n string = \"Hello World\"\n print(string.lower())" }, { "role": "assistant", "content": "def hello_world():\n string = \"Hello World\"\n print(string.upper())" } ]
Edit the provided code to yield the correct output.
def hello_world(): string = "Hello World" print(string.lower())
def hello_world(): string = "Hello World" print(string.upper())
[ { "role": "user", "content": "Explain the functional programming paradigm." }, { "role": "assistant", "content": "Functional Programming is a programming paradigm that emphasizes the use of functions, or predefined sequences of commands, to produce desired results. This paradigm tries to avoid s...
Explain the functional programming paradigm.
Functional Programming is a programming paradigm that emphasizes the use of functions, or predefined sequences of commands, to produce desired results. This paradigm tries to avoid state and mutable data, and instead use higher-order functions to pass functions as arguments. This makes it easier to understand, debug, a...
[ { "role": "user", "content": "Use the following code, and write a script to print out all the numbers from 1-50 that are divisible by 7.\n\nfor i in range(1, 50):" }, { "role": "assistant", "content": "for number in range(1, 50):\n if number % 7 == 0:\n print(number)" } ]
Use the following code, and write a script to print out all the numbers from 1-50 that are divisible by 7.
for i in range(1, 50):
for number in range(1, 50): if number % 7 == 0: print(number)
[ { "role": "user", "content": "Write a function to count the number of times a given character is found in an input string.\n\n\"Hello World\" and \"l\"" }, { "role": "assistant", "content": "def count_characters(text, char):\n count = 0\n for c in text:\n if c == char:\n ...
Write a function to count the number of times a given character is found in an input string.
"Hello World" and "l"
def count_characters(text, char): count = 0 for c in text: if c == char: count += 1 return count
[ { "role": "user", "content": "In Python, write code to sort a list of integers in ascending order.\n\n[9, 15, 5, 11, 4]" }, { "role": "assistant", "content": "def sort_list(list_of_numbers):\n list_of_numbers.sort()\n return list_of_numbers\n\nprint(sort_list([9, 15, 5, 11, 4])) # Output: [4...
In Python, write code to sort a list of integers in ascending order.
[9, 15, 5, 11, 4]
def sort_list(list_of_numbers): list_of_numbers.sort() return list_of_numbers print(sort_list([9, 15, 5, 11, 4])) # Output: [4, 5, 9, 11, 15]
[ { "role": "user", "content": "Create an MySQL query that finds customers whose age is between 18 and 25" }, { "role": "assistant", "content": "SELECT * FROM customers \nWHERE age BETWEEN 18 AND 25;" } ]
Create an MySQL query that finds customers whose age is between 18 and 25
SELECT * FROM customers WHERE age BETWEEN 18 AND 25;
[ { "role": "user", "content": "Construct a query in SQL to find the names of the customers who made purchase on a given date.\n\nThe table name is 'Orders' and the given date is '2020-06-25'." }, { "role": "assistant", "content": "SELECT customer FROM orders WHERE date = '2020-06-25';" } ]
Construct a query in SQL to find the names of the customers who made purchase on a given date.
The table name is 'Orders' and the given date is '2020-06-25'.
SELECT customer FROM orders WHERE date = '2020-06-25';
[ { "role": "user", "content": "Create code to extract the middle character of a given string.\n\nstring = \"middle\"" }, { "role": "assistant", "content": "def get_middle_char(string):\n \"\"\"Returns the middle character of a given string.\"\"\"\n middle_index = int(len(string) / 2)\n r...
Create code to extract the middle character of a given string.
string = "middle"
def get_middle_char(string): """Returns the middle character of a given string.""" middle_index = int(len(string) / 2) return string[middle_index] if __name__ == '__main__': string = "middle" print(get_middle_char(string))
[ { "role": "user", "content": "What should be written in place of \"___\" to make the following code a valid if-else statement in Python?\n\nif x >= 0:\n ___" }, { "role": "assistant", "content": "if x >= 0:\n print(\"x is positive\")" } ]
What should be written in place of "___" to make the following code a valid if-else statement in Python?
if x >= 0: ___
if x >= 0: print("x is positive")
[ { "role": "user", "content": "Improve the following React component to render a link with the text \"Visit us Here\"." }, { "role": "assistant", "content": "import React from 'react'; \n\nclass Link extends React.Component { \n\trender() { \n\t\treturn ( \n\t\t\t<div> \n\t\t\t\t<a href=\"#\">Vis...
Improve the following React component to render a link with the text "Visit us Here".
import React from 'react'; class Link extends React.Component { render() { return ( <div> <a href="#">Visit us Here</a> </div> ); } } export default Link;
[ { "role": "user", "content": "Develop a Python program\n\nCreate a program to validate an ISBN number." }, { "role": "assistant", "content": "def is_valid_isbn(isbn):\n isbn_length = len(isbn)\n if isbn_length != 10:\n return False\n \n # Calculate the check digit\n sum = 0\...
Develop a Python program
Create a program to validate an ISBN number.
def is_valid_isbn(isbn): isbn_length = len(isbn) if isbn_length != 10: return False # Calculate the check digit sum = 0 for i in range(9): sum += (i+1) * int(isbn[i]) check_digit = sum % 11 # Check if the check digit matches the last character of the ISBN. if chec...
[ { "role": "user", "content": "Insert a line of code to change the value of the string \"text\" to \"Hello World\".\n\nString text = \"\";" }, { "role": "assistant", "content": "String text = \"\";\ntext = \"Hello World\";" } ]
Insert a line of code to change the value of the string "text" to "Hello World".
String text = "";
String text = ""; text = "Hello World";
[ { "role": "user", "content": "Write a Python program to create a copy of a given set.\n\nmy_set = {1, 2, 3, 4, 5}" }, { "role": "assistant", "content": "def clone_set(my_set):\n new_set = set()\n for item in my_set:\n new_set.add(item)\n return new_set" } ]
Write a Python program to create a copy of a given set.
my_set = {1, 2, 3, 4, 5}
def clone_set(my_set): new_set = set() for item in my_set: new_set.add(item) return new_set
[ { "role": "user", "content": "Compute the number of ways to make a change of N with coins of given denominations.\n\nN = 4; Coins = {1,2,3}" }, { "role": "assistant", "content": "def change(n, coins): \n m = len(coins) \n table = [[0 for x in range(m)] for x in range(n+1)] \n\n # Fill t...
Compute the number of ways to make a change of N with coins of given denominations.
N = 4; Coins = {1,2,3}
def change(n, coins): m = len(coins) table = [[0 for x in range(m)] for x in range(n+1)] # Fill the entries for 0 value case (n = 0) for i in range(m): table[0][i] = 1 # Fill rest of the table entries in bottom-up manner for i in range(1, n+1): for j in range(m): ...
[ { "role": "user", "content": "Write a code to insert an element at the beginning of an array.\n\narr = [1, 2, 3, 4]\nelement = 0" }, { "role": "assistant", "content": "def insertAtBegining(arr,element): \n arr.insert(0, element) \n return arr \n \n# Driver code \narr = [1, 2, 3, 4]\ne...
Write a code to insert an element at the beginning of an array.
arr = [1, 2, 3, 4] element = 0
def insertAtBegining(arr,element): arr.insert(0, element) return arr # Driver code arr = [1, 2, 3, 4] element = 0 print(insertAtBegining(arr, element))
[ { "role": "user", "content": "Explain the following CSS rule.\n\np {\n font-size: 20px;\n font-weight: bold;\n}" }, { "role": "assistant", "content": "The CSS rule will assign a font size of 20px and a font weight of bold to all paragraph elements. It will make the text in any \"p\" element di...
Explain the following CSS rule.
p { font-size: 20px; font-weight: bold; }
The CSS rule will assign a font size of 20px and a font weight of bold to all paragraph elements. It will make the text in any "p" element display in a bold font with a font size of 20px.
[ { "role": "user", "content": "Write a SQL query that returns the names of people who have a higher salary than their manager" }, { "role": "assistant", "content": "SELECT e1.name\nFROM Employee e1\nJOIN Employee e2 ON e1.manager_id = e2.id \nWHERE e1.salary > e2.salary" } ]
Write a SQL query that returns the names of people who have a higher salary than their manager
SELECT e1.name FROM Employee e1 JOIN Employee e2 ON e1.manager_id = e2.id WHERE e1.salary > e2.salary
[ { "role": "user", "content": "Create a program in C to find the biggest of three numbers." }, { "role": "assistant", "content": "int max(int a, int b, int c)\n{\n int big = a;\n if(b > big)\n big = b;\n if(c > big)\n big = c;\n return big;\n}" } ]
Create a program in C to find the biggest of three numbers.
int max(int a, int b, int c) { int big = a; if(b > big) big = b; if(c > big) big = c; return big; }
[ { "role": "user", "content": "Build a web scraper that stores the main titles and content of article links from a given website.\n\nWebsite: https://www.techvoice.org/" }, { "role": "assistant", "content": "\"\"\"\nBuild a web scraper to store titles and content of article links from a given web...
Build a web scraper that stores the main titles and content of article links from a given website.
Website: https://www.techvoice.org/
""" Build a web scraper to store titles and content of article links from a given website """ import requests from bs4 import BeautifulSoup def scrape_website(url): response = requests.get(url) data = response.text soup = BeautifulSoup(data) titles = [] contents = [] for article in soup.fin...
[ { "role": "user", "content": "Write a SQL query to find the average score of students who are aged between 20 and 23." }, { "role": "assistant", "content": "SELECT AVG(score) \nFROM students \nWHERE age BETWEEN 20 AND 23;" } ]
Write a SQL query to find the average score of students who are aged between 20 and 23.
SELECT AVG(score) FROM students WHERE age BETWEEN 20 AND 23;
[ { "role": "user", "content": "In JavaScript, construct a function to count the occurence of an element in an array.\n\nvar array = [1, 2, 3, 4, 1];\nint element = 1;" }, { "role": "assistant", "content": "function countOccurence(array, element) {\n let count = 0;\n array.forEach(el => {\n ...
In JavaScript, construct a function to count the occurence of an element in an array.
var array = [1, 2, 3, 4, 1]; int element = 1;
function countOccurence(array, element) { let count = 0; array.forEach(el => { if(el === element) count++ }); return count; } var array = [1, 2, 3, 4, 1]; let element = 1; console.log(countOccurence(array, element)); // 2
[ { "role": "user", "content": "Read the following string in PHP and print it in the browser.\n\nString: \"PHP scripting language\"" }, { "role": "assistant", "content": "<?php \n $str = \"PHP scripting language\"; \n echo $str; \n?>" } ]
Read the following string in PHP and print it in the browser.
String: "PHP scripting language"
<?php $str = "PHP scripting language"; echo $str; ?>
[ { "role": "user", "content": "What is the difference between = (assignment) operator and == (comparison) operator?" }, { "role": "assistant", "content": "The = operator assigns a value to a variable, while the == operator checks if two values are equal." } ]
What is the difference between = (assignment) operator and == (comparison) operator?
The = operator assigns a value to a variable, while the == operator checks if two values are equal.
[ { "role": "user", "content": "Given a positive integer number, generate the Fibonacci series." }, { "role": "assistant", "content": "def Fibonacci(n): \n if n<0: \n print(\"Incorrect input\") \n # First Fibonacci number is 0 \n elif n==1: \n return 0\n # Second Fibonacc...
Given a positive integer number, generate the Fibonacci series.
def Fibonacci(n): if n<0: print("Incorrect input") # First Fibonacci number is 0 elif n==1: return 0 # Second Fibonacci number is 1 elif n==2: return 1 else: return Fibonacci(n-1)+Fibonacci(n-2)
[ { "role": "user", "content": "Rewrite a react class component as a functional component.\n\nclass App extends React.Component {\n constructor(props) {\n super(props);\n this.state = { name: 'John' };\n }\n\n handleChange = (e) => {\n this.setState({ name: e.target.value });\n };\n\n render() {...
Rewrite a react class component as a functional component.
class App extends React.Component { constructor(props) { super(props); this.state = { name: 'John' }; } handleChange = (e) => { this.setState({ name: e.target.value }); }; render() { return ( <div> <input value={this.state.name} onChange={this.handleChange} ...
const App = () => { const [name, setName] = useState('John'); const handleChange = (e) => { setName(e.target.value); }; return ( <div> <input value={name} onChange={handleChange} /> </div> ); }
[ { "role": "user", "content": "Generate a script to print out the sum of all even numbers in a given list\n\n[2, 4, 5, 6, 7, 8]" }, { "role": "assistant", "content": "def get_sum_of_evens(numbers):\n sum_of_evens = 0\n for num in numbers:\n if num % 2 == 0: \n sum_of_evens...
Generate a script to print out the sum of all even numbers in a given list
[2, 4, 5, 6, 7, 8]
def get_sum_of_evens(numbers): sum_of_evens = 0 for num in numbers: if num % 2 == 0: sum_of_evens += num return sum_of_evens numbers = [2, 4, 5, 6, 7, 8] print(get_sum_of_evens(numbers))
[ { "role": "user", "content": "Edit the following JavaScript code to make it able to log even numbers.\n\nconst myArray = [1, 2, 3, 4, 5]\nfor (let i = 0; i < myArray.length; i++) {\n console.log(myArray[i])\n}" }, { "role": "assistant", "content": "const myArray = [1, 2, 3, 4, 5]\nfor (let i = ...
Edit the following JavaScript code to make it able to log even numbers.
const myArray = [1, 2, 3, 4, 5] for (let i = 0; i < myArray.length; i++) { console.log(myArray[i]) }
const myArray = [1, 2, 3, 4, 5] for (let i = 0; i < myArray.length; i++) { if (myArray[i] % 2 == 0) { console.log(myArray[i]) } }
[ { "role": "user", "content": "Unwrap the value in the following nested tuple.\n\nmy_tuple = ((1, (2, (3, 4))), 5)" }, { "role": "assistant", "content": "4" } ]
Unwrap the value in the following nested tuple.
my_tuple = ((1, (2, (3, 4))), 5)
4
[ { "role": "user", "content": "Compose a SQL query to count the number of users who logged in yesterday." }, { "role": "assistant", "content": "SELECT COUNT(*) FROM users\n WHERE login_date = CURRENT_DATE - INTERVAL 1 DAY" } ]
Compose a SQL query to count the number of users who logged in yesterday.
SELECT COUNT(*) FROM users WHERE login_date = CURRENT_DATE - INTERVAL 1 DAY
[ { "role": "user", "content": "Create an HTML radio button that allows users to select between two options." }, { "role": "assistant", "content": "<input type=\"radio\" name=\"selection\" value=\"option1\"> Option 1\n<input type=\"radio\" name=\"selection\" value=\"option2\"> Option 2" } ]
Create an HTML radio button that allows users to select between two options.
<input type="radio" name="selection" value="option1"> Option 1 <input type="radio" name="selection" value="option2"> Option 2
[ { "role": "user", "content": "Calculate the area of a rectangle given height and width.\n\nheight = 2\nwidth = 5" }, { "role": "assistant", "content": "def area_rectangle(height, width):\n return height*width\n\nif __name__ == '__main__':\n print(area_rectangle(2, 5))" } ]
Calculate the area of a rectangle given height and width.
height = 2 width = 5
def area_rectangle(height, width): return height*width if __name__ == '__main__': print(area_rectangle(2, 5))
[ { "role": "user", "content": "Fix the following Java code by replacing the letter \"u\" with \"v\".\n\nString s1 = \"Update\";" }, { "role": "assistant", "content": "String s1 = \"Update\";\nString s2 = s1.replace('u','v');" } ]
Fix the following Java code by replacing the letter "u" with "v".
String s1 = "Update";
String s1 = "Update"; String s2 = s1.replace('u','v');
[ { "role": "user", "content": "Replace the placeholder with a for loop for iterating over the numbers from 1 to n and printing them.\n\nfor i in range(n):\n # TODO" }, { "role": "assistant", "content": "for i in range(1, n+1):\n print(i)" } ]
Replace the placeholder with a for loop for iterating over the numbers from 1 to n and printing them.
for i in range(n): # TODO
for i in range(1, n+1): print(i)
[ { "role": "user", "content": "Given a string and two substrings, create a function to replace the two substrings with another string.\n\nmain_string = \"Replace the first and last substring with this string\", start_substring = \"first\", end_substring = \"last\"" }, { "role": "assistant", "cont...
Given a string and two substrings, create a function to replace the two substrings with another string.
main_string = "Replace the first and last substring with this string", start_substring = "first", end_substring = "last"
def replace_substrings(main_string, start_substring, end_substring): start_index = main_string.index(start_substring) end_index = main_string.index(end_substring) + len(end_substring) return main_string[:start_index] + "this string" + main_string[end_index:]
[ { "role": "user", "content": "Edit the following code to make the function return the value of n mod m.\n\nint modulo(int n, int m)\n{\n return n / m;\n}" }, { "role": "assistant", "content": "int modulo(int n, int m)\n{\n return n % m;\n}" } ]
Edit the following code to make the function return the value of n mod m.
int modulo(int n, int m) { return n / m; }
int modulo(int n, int m) { return n % m; }
[ { "role": "user", "content": "Generate a 5-dimensional array using the numpy library" }, { "role": "assistant", "content": "import numpy as np\n\narr = np.zeros((5,5,5,5,5))" } ]
Generate a 5-dimensional array using the numpy library
import numpy as np arr = np.zeros((5,5,5,5,5))
[ { "role": "user", "content": "Create a program that draws a triangle with stars (*) with a given height." }, { "role": "assistant", "content": "def draw_triangle(n): \n for i in range(0, n): \n for j in range(0, i+1): \n print(\"*\",end=\"\") \n print(\"\\r\")" } ]
Create a program that draws a triangle with stars (*) with a given height.
def draw_triangle(n): for i in range(0, n): for j in range(0, i+1): print("*",end="") print("\r")
[ { "role": "user", "content": "Change the following code snippet to generate a random integer from 0 to 10." }, { "role": "assistant", "content": "import random\n\nrandom_int = random.randint(0, 10)" } ]
Change the following code snippet to generate a random integer from 0 to 10.
import random random_int = random.randint(0, 10)
[ { "role": "user", "content": "Design a Python program to read string inputs and print out the reverse of the same" }, { "role": "assistant", "content": "def reverse_string(string):\n string = string[::-1]\n return string" } ]
Design a Python program to read string inputs and print out the reverse of the same
def reverse_string(string): string = string[::-1] return string
[ { "role": "user", "content": "Create a SQL query to find the employees who live in California and earn more than $80,000 per year." }, { "role": "assistant", "content": "SELECT * FROM employees \nWHERE state = 'California' AND salary > 80000;" } ]
Create a SQL query to find the employees who live in California and earn more than $80,000 per year.
SELECT * FROM employees WHERE state = 'California' AND salary > 80000;
[ { "role": "user", "content": "Go through the following code and create test cases for it.\n\ndef reverse_string(string):\n rev_str = \"\"\n\n # Loop through the string in reverse order\n for i in range(len(string)-1, -1, -1):\n rev_str += string[i]\n\n return rev_str" }, { "role": "assistant"...
Go through the following code and create test cases for it.
def reverse_string(string): rev_str = "" # Loop through the string in reverse order for i in range(len(string)-1, -1, -1): rev_str += string[i] return rev_str
import unittest class ReverseStringTests(unittest.TestCase): def test_reverse_string_with_single_character_string(self): result = reverse_string("a") self.assertEqual(result, "a") def test_reverse_string_with_even_length_string(self): result = reverse_string("hello") self.asser...
[ { "role": "user", "content": "Create a Java program to print out factorials from 1 to 10." }, { "role": "assistant", "content": "public class Factorial {\n public static void main(String[] args) {\n for (int i = 1; i <= 10; ++i) {\n System.out.println(i + \"! = \" + factoria...
Create a Java program to print out factorials from 1 to 10.
public class Factorial { public static void main(String[] args) { for (int i = 1; i <= 10; ++i) { System.out.println(i + "! = " + factorial(i)); } } public static long factorial(int n) { if (n == 0) return 1; else return n * factorial(n - 1...
[ { "role": "user", "content": "Construct a lambda function to filter a given list based on a given predicate.\n\nnumbers = [1, 2, 3, 4, 5, 6]\npredicate = lambda x: x % 2 == 0" }, { "role": "assistant", "content": "filtered_list = list(filter(predicate, numbers)) #=> [2, 4, 6]" } ]
Construct a lambda function to filter a given list based on a given predicate.
numbers = [1, 2, 3, 4, 5, 6] predicate = lambda x: x % 2 == 0
filtered_list = list(filter(predicate, numbers)) #=> [2, 4, 6]
[ { "role": "user", "content": "Compose a for loop in Java to print the numbers from 4 to 1 one line." }, { "role": "assistant", "content": "for (int i = 4; i > 0; i--) {\n System.out.print(i + \" \");\n}" } ]
Compose a for loop in Java to print the numbers from 4 to 1 one line.
for (int i = 4; i > 0; i--) { System.out.print(i + " "); }
[ { "role": "user", "content": "What is the syntax for declaring a constant in Java?" }, { "role": "assistant", "content": "In Java, the syntax for declaring a constant is \n\npublic static final <data-type> <constant-name> = <value>;" } ]
What is the syntax for declaring a constant in Java?
In Java, the syntax for declaring a constant is public static final <data-type> <constant-name> = <value>;