Dataset Viewer
Auto-converted to Parquet Duplicate
instruction
stringlengths
18
473
input
stringlengths
1
1.42k
⌀
output
stringlengths
22
5.94k
text
stringlengths
106
6.69k
language
stringclasses
69 values
Create a TensorFlow model that takes text data as input and outputs a sentiment score between 0 (negative sentiment) and 1 (positive sentiment).
Not applicable
```python import tensorflow as tf def create_model(): #initialize model model = tf.keras.Sequential() #add two embedding layers model.add(tf.keras.layers.Embedding(input_dim=vocab_size, output_dim=embedding_dim, input_length=max_length)) model.add(tf.keras.layers.GlobalAveragePooling1D()) #add dense layer mod...
### Instruction: Create a TensorFlow model that takes text data as input and outputs a sentiment score between 0 (negative sentiment) and 1 (positive sentiment). ### Input: Not applicable ### Output: ```python import tensorflow as tf def create_model(): #initialize model model = tf.keras.Sequential() #add two em...
Python
Generate an SQL query to find the most recent entry for each user in a table.
NoInput
```scdoc SELECT user_id, MAX(date) FROM table GROUP BY user_id; ```
### Instruction: Generate an SQL query to find the most recent entry for each user in a table. ### Input: NoInput ### Output: ```scdoc SELECT user_id, MAX(date) FROM table GROUP BY user_id; ```
scdoc
Generate a JavaScript code snippet to replace all the whitespace characters_ from a given string with an underscore.
"Let us replace whitespaces"
```gdscript const newStr = str.replace(/\s+/g, '_'); console.log(newStr); // "Let_us_replace_whitespaces" ```
### Instruction: Generate a JavaScript code snippet to replace all the whitespace characters_ from a given string with an underscore. ### Input: "Let us replace whitespaces" ### Output: ```gdscript const newStr = str.replace(/\s+/g, '_'); console.log(newStr); // "Let_us_replace_whitespaces" ```
GDScript
Create a basic SQL query to find the number of customers in the “customers” table with a country of “United States”
Not applicable
```scdoc SELECT COUNT(*) FROM customers WHERE country = 'United States'; ```
### Instruction: Create a basic SQL query to find the number of customers in the “customers” table with a country of “United States” ### Input: Not applicable ### Output: ```scdoc SELECT COUNT(*) FROM customers WHERE country = 'United States'; ```
scdoc
Create a React component to display a simple dropdown with three items.
options = ['Option 1', 'Option 2', 'Option 3'];
```python import React from 'react'; import { Select } from 'antd'; const Dropdown = ({ options }) => { return ( <Select> {options.map((option, index) => ( <Select.Option key={index} value={option}> {option} </Select.Option> ))} </Select> ); }; export default Dropdown; ```
### Instruction: Create a React component to display a simple dropdown with three items. ### Input: options = ['Option 1', 'Option 2', 'Option 3']; ### Output: ```python import React from 'react'; import { Select } from 'antd'; const Dropdown = ({ options }) => { return ( <Select> {options.map((option, index) =>...
Python
Parse the given XML document and store its contents into a JSON object.
<books> <book> <title>The Cat in the Hat</title> <author>Dr. Seuss</author> </book> <book> <title>Alice in Wonderland</title> <author>Lewis Carroll</author> </book> </books>
```python import xml.etree.ElementTree as ET import json def parse_xml_to_json(xml): root = ET.fromstring(xml) json_data = [] for book in root.findall('book'): book_data = {} book_data['title'] = book.find('title').text book_data['author'] = book.find('author').text jso...
### Instruction: Parse the given XML document and store its contents into a JSON object. ### Input: <books> <book> <title>The Cat in the Hat</title> <author>Dr. Seuss</author> </book> <book> <title>Alice in Wonderland</title> <author>Lewis Carroll</author> </book> </book...
Python
Implement an AI agent that can solve a maze using a Depth-First Search algorithm.
Maze (matrix) [ [0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0], [1, 1, 0, 0, 1, 0], [0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 1, 0], [0, 0, 0, 0, 0, 0] ]
```transact-sql # define the matrix as numbers # 0 - ' ' blank # 1 - 'X' wall # 2 - '*' path # 3 - 'O' goal MAZE = [ [0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0], [1, 1, 0, 0, 1, 0], [0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 1, 0], [0, 0, 0, 0, 0, 3] ] # define size # rows M = 6 # cols N = 6 # empty array for saving found pa...
### Instruction: Implement an AI agent that can solve a maze using a Depth-First Search algorithm. ### Input: Maze (matrix) [ [0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0], [1, 1, 0, 0, 1, 0], [0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 1, 0], [0, 0, 0, 0, 0, 0] ] ### Output: ```transact-sql # define the matrix as numbers # 0 - ' ' ...
Transact-SQL
Create a program to find the factorial of a given number.
5
```scdoc def factorial(n): if n == 0: return 1 return n * factorial(n-1) result = factorial(5) print(result) ```
### Instruction: Create a program to find the factorial of a given number. ### Input: 5 ### Output: ```scdoc def factorial(n): if n == 0: return 1 return n * factorial(n-1) result = factorial(5) print(result) ```
scdoc
Create a Rust library for validating user email addresses. The library should contain functions for checking the syntax and format of the email address and a function for checking if the email address domain exists.
Not applicable
```objectivec extern crate regex; extern crate dns; pub mod email { use regex::Regex; use std::net::ToSocketAddrs; use std::str::FromStr; use dns::client::{AsyncDnsClient, DnsHandle}; use dns::error::DnsError; use std::sync::Arc; pub async fn validate_email(email: &str, dns_handle: &Ar...
### Instruction: Create a Rust library for validating user email addresses. The library should contain functions for checking the syntax and format of the email address and a function for checking if the email address domain exists. ### Input: Not applicable ### Output: ```objectivec extern crate regex; extern crate ...
Objective-C
Design a program in C language to find the largest number in an array.
[10, 40, 50, 25, 60]
```transact-sql #include <stdio.h> int getMax(int arr[], int n) { int max = arr[0]; int i; for (i = 1; i < n; i++) if (arr[i] > max) max = arr[i]; return max; } int main() { int arr[] = {10, 40, 50, 25, 60}; int n = sizeof(arr) / sizeof(arr[0]); printf("La...
### Instruction: Design a program in C language to find the largest number in an array. ### Input: [10, 40, 50, 25, 60] ### Output: ```transact-sql #include <stdio.h> int getMax(int arr[], int n) { int max = arr[0]; int i; for (i = 1; i < n; i++) if (arr[i] > max) max = arr[i]; ...
Transact-SQL
Create a dictionary with keys and values that compute the length of each word in a string.
String: "Hello World"
```transact-sql def word_lengths(sentence): words = sentence.split(" ") word_length_dict = {} for word in words: word_length_dict[word] = len(word) return word_length_dict if __name__== "__main__": sentence = "Hello World" word_length_dict = word_lengths(sentence) print(word_length_...
### Instruction: Create a dictionary with keys and values that compute the length of each word in a string. ### Input: String: "Hello World" ### Output: ```transact-sql def word_lengths(sentence): words = sentence.split(" ") word_length_dict = {} for word in words: word_length_dict[word] = len(wor...
Transact-SQL
Create an algorithm for solving the knapsack problem.
weights = [5, 4, 6, 3] values = [10, 40, 30, 50] knapsack_capacity = 10
```transact-sql # Knapsack 0-1 problem # Parameters: # weights: array (n) containing the weights of the items # values: array (n) containing the values of the items # knapsack_capacity: the capacity of the knapsack def knapsack(weights, values, knapsack_capacity): n = len(weights) # Create a matrix to store t...
### Instruction: Create an algorithm for solving the knapsack problem. ### Input: weights = [5, 4, 6, 3] values = [10, 40, 30, 50] knapsack_capacity = 10 ### Output: ```transact-sql # Knapsack 0-1 problem # Parameters: # weights: array (n) containing the weights of the items # values: array (n) containing the values ...
Transact-SQL
Create a function to find the maximum and minimum element in a list.
input_list = [5, 8, 9, 10, 4, 3]
```scdoc def min_max(input_list): min = input_list[0] max = input_list[0] for num in input_list: if num < min: min = num if num > max: max = num return (min, max) print(min_max(input_list)) ```
### Instruction: Create a function to find the maximum and minimum element in a list. ### Input: input_list = [5, 8, 9, 10, 4, 3] ### Output: ```scdoc def min_max(input_list): min = input_list[0] max = input_list[0] for num in input_list: if num < min: min = num if num > max: ...
scdoc
Design a function in C++ which takes a vector of strings as input and sorts it using a given sorting function.
["Hello", "World", "!"], sort by length
```arduino #include <algorithm> #include <vector> // A comparison function which sorts the strings by length bool compare_by_length(const std::string& first, const std::string& second) { return first.length() < second.length(); } // Function which takes the vector of strings and the sorting function as parameters, s...
### Instruction: Design a function in C++ which takes a vector of strings as input and sorts it using a given sorting function. ### Input: ["Hello", "World", "!"], sort by length ### Output: ```arduino #include <algorithm> #include <vector> // A comparison function which sorts the strings by length bool compare_by_l...
Arduino
Create an Android app with a splash screen with a logo and a welcome message that stays for two seconds before moving to the home screen.
Not applicable
```xml // Create a basic view for the Splash Screen <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <ImageView android:background="@drawable/logo" android:layout_marginTop="50dp" a...
### Instruction: Create an Android app with a splash screen with a logo and a welcome message that stays for two seconds before moving to the home screen. ### Input: Not applicable ### Output: ```xml // Create a basic view for the Splash Screen <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" ...
XML
Develop a Linux commandline tool in C++ to check the performance of your computer.
Not applicable
```arduino #include <iostream> #include <string> #include <unistd.h> int main( int argc, char** argv ) { std::string cmd = "lscpu"; char* buffer[128]; // Executing the command std::cout << "Executing command: " << cmd << std::endl; FILE *fp = popen(cmd.c_str(), "r"); // Read the output ...
### Instruction: Develop a Linux commandline tool in C++ to check the performance of your computer. ### Input: Not applicable ### Output: ```arduino #include <iostream> #include <string> #include <unistd.h> int main( int argc, char** argv ) { std::string cmd = "lscpu"; char* buffer[128]; // Executing...
Arduino
Create a program to remove all duplicate elements from an array.
[2, 3, 4, 2, 1, 5, 4]
```scdoc def remove_duplicates(arr): new_arr = [] for i in arr: if i not in new_arr: new_arr.append(i) return new_arr ```
### Instruction: Create a program to remove all duplicate elements from an array. ### Input: [2, 3, 4, 2, 1, 5, 4] ### Output: ```scdoc def remove_duplicates(arr): new_arr = [] for i in arr: if i not in new_arr: new_arr.append(i) return new_arr ```
scdoc
Design a Java program for printing all possible combination of given letters.
['a', 'b', 'c']
```tera term macro public static void printCombinations(List<Character> letters) { for (int i = 0; i < letters.size(); i++) { for (int j = i+1; j < letters.size(); j++) { for (int k = j+1; k < letters.size(); k++) { System.out.println(letters.get(i) + "" + letters.get(j) + "" + l...
### Instruction: Design a Java program for printing all possible combination of given letters. ### Input: ['a', 'b', 'c'] ### Output: ```tera term macro public static void printCombinations(List<Character> letters) { for (int i = 0; i < letters.size(); i++) { for (int j = i+1; j < letters.size(); j++) { ...
Tera Term macro
Create a Machine Learning model to classify a movie review as positive or negative.
Not applicable
```python import pandas as pd from sklearn.feature_extraction.text import CountVectorizer from sklearn.model_selection import train_test_split from sklearn.naive_bayes import MultinomialNB # Read data into a DataFrame df = pd.read_csv('movie_reviews.csv') # Convert the text in the reviews to a vector of words cv = Co...
### Instruction: Create a Machine Learning model to classify a movie review as positive or negative. ### Input: Not applicable ### Output: ```python import pandas as pd from sklearn.feature_extraction.text import CountVectorizer from sklearn.model_selection import train_test_split from sklearn.naive_bayes import Mult...
Python
Write a function to calculate the maximum in a set of numbers.
[2, 3, 4, 5, 7, 1]
```transact-sql def max_value(nums): max = nums[0] for i in range(1, len(nums)): if nums[i] > max: max = nums[i] return max ```
### Instruction: Write a function to calculate the maximum in a set of numbers. ### Input: [2, 3, 4, 5, 7, 1] ### Output: ```transact-sql def max_value(nums): max = nums[0] for i in range(1, len(nums)): if nums[i] > max: max = nums[i] return max ```
Transact-SQL
Develop a web page that displays a message when the user hovers a button.
Button text: "Click Here" Message text: "You clicked the button!"
```xml <html> <head> <style> div { position: relative; } span { position: absolute; display: none; } input:hover + span { display: inline-block; } </style> </head> <body> <div> <input type="button" value="Click Here"> <spa...
### Instruction: Develop a web page that displays a message when the user hovers a button. ### Input: Button text: "Click Here" Message text: "You clicked the button!" ### Output: ```xml <html> <head> <style> div { position: relative; } span { position: absolute; displa...
XML
Analyze the data and calculate the mean age of the people in the given dataset.
[ {'name': 'John', 'age': 20}, {'name': 'Smith', 'age': 60}, {'name': 'Alex', 'age': 20}, {'name': 'David', 'age': 40} ]
```scdoc def meanAge(people): age_list = [] for person in people: age_list.append(person['age']) return sum(age_list) / len(age_list) people = [ {'name': 'John', 'age': 20}, {'name': 'Smith', 'age': 60}, {'name': 'Alex', 'age': 20}, {'name': 'David', 'age': 40} ] print(meanAge(pe...
### Instruction: Analyze the data and calculate the mean age of the people in the given dataset. ### Input: [ {'name': 'John', 'age': 20}, {'name': 'Smith', 'age': 60}, {'name': 'Alex', 'age': 20}, {'name': 'David', 'age': 40} ] ### Output: ```scdoc def meanAge(people): age_list = [] for per...
scdoc
Create a program to find distance between two sets of coordinates.
p1 = (1, 2) p2 = (3, 4)
```python import math def find_distance(p1, p2): x1, y1 = p1 x2, y2 = p2 dist = math.sqrt(math.pow(x2 - x1, 2) + math.pow(y2 - y1, 2)) return dist find_distance(p1, p2) # Output: 2.8284271247461903 ```
### Instruction: Create a program to find distance between two sets of coordinates. ### Input: p1 = (1, 2) p2 = (3, 4) ### Output: ```python import math def find_distance(p1, p2): x1, y1 = p1 x2, y2 = p2 dist = math.sqrt(math.pow(x2 - x1, 2) + math.pow(y2 - y1, 2)) return dist find_distance(p1, p2)...
Python
Can you optimize the code to select elements from a list based on a given condition?
def select_elements(nums): new_nums = [] for num in nums: if num % 2 == 0: new_nums.append(num) return new_nums
```scdoc def select_elements(nums): return [num for num in nums if num % 2 == 0] ```
### Instruction: Can you optimize the code to select elements from a list based on a given condition? ### Input: def select_elements(nums): new_nums = [] for num in nums: if num % 2 == 0: new_nums.append(num) return new_nums ### Output: ```scdoc def select_elements(nums): return [num for num in nums...
scdoc
Create an API with Flask to add an item to a shopping cart.
Table: shopping_cart Columns: user_id, item_name, item_cost
```python from flask import Flask, request import sqlite3 app = Flask(name) @app.route('/addItem', methods=['POST']) def add_item(): conn = sqlite3.connect('shopping_cart.db') c = conn.cursor() # get the item_name and the item_cost user_id = request.json['user_id'] item_name = request.json['item_name'] item_...
### Instruction: Create an API with Flask to add an item to a shopping cart. ### Input: Table: shopping_cart Columns: user_id, item_name, item_cost ### Output: ```python from flask import Flask, request import sqlite3 app = Flask(name) @app.route('/addItem', methods=['POST']) def add_item(): conn = sqlite3.connec...
Python
Create a Python script that takes a number and a power as parameters and calculates the result.
Example input: number=2 power=3
```scdoc def power(number, power): return number**power print(power(2, 3)) # Output: 8 ```
### Instruction: Create a Python script that takes a number and a power as parameters and calculates the result. ### Input: Example input: number=2 power=3 ### Output: ```scdoc def power(number, power): return number**power print(power(2, 3)) # Output: 8 ```
scdoc
Create a React application with an advanced search feature. The search should allow users to search by fields such as name, address, and age and results should be paginated.
[ { name: 'John Doe', address: '123 Main St', age: 23 }, { name: 'Jane Doe', address: '456 High St', age: 35 }, { name: 'Jack Smith', address: '789 Center St', age: 22 } ]
```python import React, { useState, useEffect } from 'react'; const App = () => { const [data, setData] = useState([]); const [searchQuery, setSearchQuery] = useState(''); const [page, setPage] = useState(1); const [results, setResults] = useState([]); useEffect(() => { setData(input); }, []); const handleSe...
### Instruction: Create a React application with an advanced search feature. The search should allow users to search by fields such as name, address, and age and results should be paginated. ### Input: [ { name: 'John Doe', address: '123 Main St', age: 23 }, { name: 'Jane Doe', address: '456 High St', age: 35...
Python
How would you optimize the following code?
def check_sum(a, b): result = 0 for i in range(len(a)): result += a[i] * b[i] return result
```transact-sql def check_sum(a, b): result = 0 for i in range(len(a)): result += a[i] * b[i] return result # Optimized def check_sum_opt(a, b): return sum(a[i] * b[i] for i in range(len(a))) ```
### Instruction: How would you optimize the following code? ### Input: def check_sum(a, b): result = 0 for i in range(len(a)): result += a[i] * b[i] return result ### Output: ```transact-sql def check_sum(a, b): result = 0 for i in range(len(a)): result += a[i] * b[i] return re...
Transact-SQL
Create an application that runs on the command line and outputs the output of a command-line program to the console.
Command line program to run: ps aux
```gdscript const { spawn } = require('child_process'); const child = spawn('ps', ['aux']); child.stdout.on('data', function(data) { console.log('stdout: ', data.toString()); }); child.stderr.on('data', function(data) { console.log('stderr: ', data.toString()); }); ```
### Instruction: Create an application that runs on the command line and outputs the output of a command-line program to the console. ### Input: Command line program to run: ps aux ### Output: ```gdscript const { spawn } = require('child_process'); const child = spawn('ps', ['aux']); child.stdout.on('data', functio...
GDScript
Compose a SQL query that returns data within a specific date range.
Table Name: Orders Desired Date Range: 01-01-2021 to 12-31-2021
```scdoc SELECT * FROM Orders WHERE date BETWEEN '2021-01-01' AND '2021-12-31'; ```
### Instruction: Compose a SQL query that returns data within a specific date range. ### Input: Table Name: Orders Desired Date Range: 01-01-2021 to 12-31-2021 ### Output: ```scdoc SELECT * FROM Orders WHERE date BETWEEN '2021-01-01' AND '2021-12-31'; ```
scdoc
Generate a class in Java that encapsulates the concept of an Item in a store. The class should have a constructor to set the name and price of the item, and two methods, one to get the name and the other to get the price of the item.
Not applicable
```tera term macro public class Item { private String name; private double price; public Item(String name, double price) { this.name = name; this.price = price; } public String getName() { return name; } public double getPrice() { return price; } } ```
### Instruction: Generate a class in Java that encapsulates the concept of an Item in a store. The class should have a constructor to set the name and price of the item, and two methods, one to get the name and the other to get the price of the item. ### Input: Not applicable ### Output: ```tera term macro public cla...
Tera Term macro
Create a Google Cloud Function in Python to parse an incoming JSON object and extract its values
Not applicable
```python import json def parse_json_object(request): # Parse the incoming JSON object data = json.loads(request.data) # Extract the values param1 = data['param1'] param2 = data['param2'] return 'Parameters extracted: param1={}, param2={}'.format(param1,param2) ```
### Instruction: Create a Google Cloud Function in Python to parse an incoming JSON object and extract its values ### Input: Not applicable ### Output: ```python import json def parse_json_object(request): # Parse the incoming JSON object data = json.loads(request.data) # Extract the values param1 = data['para...
Python
Generate the Python code that calculates the numbers of characters in a given string.
"Hello, World!"
```tera term macro myString = "Hello, World!" charCount = 0 for char in myString: charCount += 1 print("Number of characters:", charCount) ```
### Instruction: Generate the Python code that calculates the numbers of characters in a given string. ### Input: "Hello, World!" ### Output: ```tera term macro myString = "Hello, World!" charCount = 0 for char in myString: charCount += 1 print("Number of characters:", charCount) ```
Tera Term macro
Convert the following pseudocode into Java code.
IF x > 10 THEN x = 10 ELSE x = x + 2
```tera term macro if (x > 10) { x = 10; } else { x = x + 2; } ```
### Instruction: Convert the following pseudocode into Java code. ### Input: IF x > 10 THEN x = 10 ELSE x = x + 2 ### Output: ```tera term macro if (x > 10) { x = 10; } else { x = x + 2; } ```
Tera Term macro
Create a logic puzzle game in JavaScript where the user must balance a set of weights across 6 scales.
Not applicable
```transact-sql // Game Functionality function resetScales() { // Initialize the weights and scales let weights = [1, 2, 4, 8, 16]; let scales = Array(6).fill(0); // Main game loop while (weights.length > 0) { let i = Math.floor(Math.random() * weights.length); let weight = weights[i]; // Add the weight ...
### Instruction: Create a logic puzzle game in JavaScript where the user must balance a set of weights across 6 scales. ### Input: Not applicable ### Output: ```transact-sql // Game Functionality function resetScales() { // Initialize the weights and scales let weights = [1, 2, 4, 8, 16]; let scales = Array(6).fi...
Transact-SQL
Create a Golang program which takes two strings as input and checks if the first string contains all characters of the second string.
"abcd", "abd"
```python package main import ( "fmt" ) func checkIfSubstring(str1 string, str2 string) bool { str1_map := make(map[rune]int) for _, char := range str1 { str1_map[char] = str1_map[char] + 1 } for _, char := range str2 { if _, ok := str1_map[char]; !ok { // Character not present in str1 retur...
### Instruction: Create a Golang program which takes two strings as input and checks if the first string contains all characters of the second string. ### Input: "abcd", "abd" ### Output: ```python package main import ( "fmt" ) func checkIfSubstring(str1 string, str2 string) bool { str1_map := make(map[rune]int) ...
Python
Can you develop a program to check if two strings are anagrams?
String 1: Animal String 2: Lamin
```scdoc def is_anagram(str1, str2): return sorted(str1.lower()) == sorted(str2.lower()) # Driver code str1 = "Animal" str2 = "Lamin" print(is_anagram(str1, str2)) ```
### Instruction: Can you develop a program to check if two strings are anagrams? ### Input: String 1: Animal String 2: Lamin ### Output: ```scdoc def is_anagram(str1, str2): return sorted(str1.lower()) == sorted(str2.lower()) # Driver code str1 = "Animal" str2 = "Lamin" print(is_anagram(str1, str2)) ```
scdoc
Create a Node.js Express application to access a MongoDB database. This application should include a route to create a new document and a route to retrieve an existing document.
Not applicable
```gdscript const express = require('express'); const mongoose = require('mongoose'); const bodyParser = require('body-parser'); const app = express(); app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()); const db = mongoose.connect('mongodb://localhost:27017/mydb'); const Document = requ...
### Instruction: Create a Node.js Express application to access a MongoDB database. This application should include a route to create a new document and a route to retrieve an existing document. ### Input: Not applicable ### Output: ```gdscript const express = require('express'); const mongoose = require('mongoose');...
GDScript
Create a React component that displays a list of countries and a button labeled 'Show Details'. When the button is clicked, it should display more detailed information about the selected country including population size, GDP, major exports, etc.
Not applicable
```python import React, {useState} from 'react'; const CountryList = ({countries)) => { const [selectedCountry, setSelectedCountry] = useState(null); const handleCountrySelect = event => { setSelectedCountry(event.target.value); }; const renderDetails = () => { const country = countries.find(country => country...
### Instruction: Create a React component that displays a list of countries and a button labeled 'Show Details'. When the button is clicked, it should display more detailed information about the selected country including population size, GDP, major exports, etc. ### Input: Not applicable ### Output: ```python import...
Python
Create an algorithm in C++ that takes a matrix of integers and reverses its rows and columns.
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
```transact-sql #include <vector> vector<vector<int>> reverseMatrix(vector<vector<int>> matrix) { int row = matrix.size(); int col = matrix[0].size(); for (int i = 0; i < row; i++) { for (int j = i; j < col; j++) { swap(matrix[i][j], matrix[j][i]); } } ...
### Instruction: Create an algorithm in C++ that takes a matrix of integers and reverses its rows and columns. ### Input: [[1, 2, 3], [4, 5, 6], [7, 8, 9]] ### Output: ```transact-sql #include <vector> vector<vector<int>> reverseMatrix(vector<vector<int>> matrix) { int row = matrix.size(); int col = m...
Transact-SQL
Design a reinforcement learning algorithm for an autonomous car that optimizes its route to a destination.
<Map Terrain>
```numpy import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D # Define map terrain map_terrain = <Map Terrain> # Define function to calculate reward def get_reward(location): reward = map_terrain[location[0]][location[1]] return reward # Set up environment env = np.zeros...
### Instruction: Design a reinforcement learning algorithm for an autonomous car that optimizes its route to a destination. ### Input: <Map Terrain> ### Output: ```numpy import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D # Define map terrain map_terrain = <Map Terrain> # Defi...
NumPy
Implement a sorting algorithm in Java that can sort an array of integers.
[12, 6, 8, 10]
```transact-sql class SortingExample { void sort(int arr[]) { int n = arr.length; // One by one move boundary of unsorted subarray for (int i = 0; i < n-1; i++) { // Find the minimum element in unsorted array int min_idx = i; for (...
### Instruction: Implement a sorting algorithm in Java that can sort an array of integers. ### Input: [12, 6, 8, 10] ### Output: ```transact-sql class SortingExample { void sort(int arr[]) { int n = arr.length; // One by one move boundary of unsorted subarray for (int i = 0; i...
Transact-SQL
Create an algorithm which sorts a list of integers using a bubble sort.
[1, 5, 6, 8, 3]
```transact-sql def bubble_sort(list_of_numbers): list_length = len(list_of_numbers) for outer_index in range(list_length - 1): for inner_index in range(list_length - outer_index - 1): if list_of_numbers[inner_index] > list_of_numbers[inner_index + 1]: list_of_n...
### Instruction: Create an algorithm which sorts a list of integers using a bubble sort. ### Input: [1, 5, 6, 8, 3] ### Output: ```transact-sql def bubble_sort(list_of_numbers): list_length = len(list_of_numbers) for outer_index in range(list_length - 1): for inner_index in range(list_le...
Transact-SQL
Write a Node.js program to create a JWT token from a given set of user credentials.
const payload = { userId: 'username', userName: 'User Name', roles: ['user'] }
```gdscript const jwt = require('jsonwebtoken'); const payload = { userId: 'username', userName: 'User Name', roles: ['user'] } const token = jwt.sign(payload, 'SECRET_KEY'); console.log(token); ```
### Instruction: Write a Node.js program to create a JWT token from a given set of user credentials. ### Input: const payload = { userId: 'username', userName: 'User Name', roles: ['user'] } ### Output: ```gdscript const jwt = require('jsonwebtoken'); const payload = { userId: 'username', userName: 'User Name',...
GDScript
Write a JavaScript code snippet to loop through an array of integers and output each one to the console.
[1, 2, 3, 4]
```text only [1, 2, 3, 4].forEach(num => { console.log(num); }); ```
### Instruction: Write a JavaScript code snippet to loop through an array of integers and output each one to the console. ### Input: [1, 2, 3, 4] ### Output: ```text only [1, 2, 3, 4].forEach(num => { console.log(num); }); ```
Text only
Generate a C++ program to swap two elements of an array.
Array = [7, 9, 5]
```transact-sql #include <iostream> using namespace std; void swap(int arr[], int i, int j) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } int main() { int arr[] = {7, 9, 5}; int i = 0, j = 2; swap(arr, i, j); cout << "After Swapping arr[i] = " << arr[i] ...
### Instruction: Generate a C++ program to swap two elements of an array. ### Input: Array = [7, 9, 5] ### Output: ```transact-sql #include <iostream> using namespace std; void swap(int arr[], int i, int j) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } int main() { int arr[] = {7, 9...
Transact-SQL
Create a Golang program that reads integers from standard input and prints out the summation of them.
5 10 15
```python package main import ( "fmt" ) func main() { var sum int for { var n int _, err := fmt.Scanf("%d", &n) if err != nil { break } sum += n } fmt.Println(sum) } ```
### Instruction: Create a Golang program that reads integers from standard input and prints out the summation of them. ### Input: 5 10 15 ### Output: ```python package main import ( "fmt" ) func main() { var sum int for { var n int _, err := fmt.Scanf("%d", &n) if err != nil { break } sum += n } fmt.Prin...
Python
Create a program that will take two strings as input and returns the minimum length of the two.
str1 = "hello" str2 = "word"
```scdoc def min_len(str1, str2): return min(len(str1), len(str2)) ```
### Instruction: Create a program that will take two strings as input and returns the minimum length of the two. ### Input: str1 = "hello" str2 = "word" ### Output: ```scdoc def min_len(str1, str2): return min(len(str1), len(str2)) ```
scdoc
Write a JavaScript program to compare two string and output a message if they are equal or not.
str1 = "Hello"; str2 = "World"
```tera term macro function compareStrings(str1, str2) { if (str1 === str2) { console.log("Strings are equal.") } else { console.log("Strings are not equal.") } } compareStrings("Hello", "World"); ```
### Instruction: Write a JavaScript program to compare two string and output a message if they are equal or not. ### Input: str1 = "Hello"; str2 = "World" ### Output: ```tera term macro function compareStrings(str1, str2) { if (str1 === str2) { console.log("Strings are equal.") } else { console.log("Strin...
Tera Term macro
Create an MySQL table to store user information. The table should include columns for a user's ID, username, password, email address, and age.
Not applicable
```scdoc CREATE TABLE users ( id INT AUTO_INCREMENT PRIMARY KEY, username VARCHAR(255) NOT NULL, password VARCHAR(255) NOT NULL, email VARCHAR(255) NOT NULL, age INT ); ```
### Instruction: Create an MySQL table to store user information. The table should include columns for a user's ID, username, password, email address, and age. ### Input: Not applicable ### Output: ```scdoc CREATE TABLE users ( id INT AUTO_INCREMENT PRIMARY KEY, username VARCHAR(255) NOT NULL, password VARCHAR(255...
scdoc
Rewrite the following python program using list comprehension
list = ['apple', 'banana', 'cat', 'dog', 'elephant'] new_list = [] for x in list: new_list.append(x.upper())
```scdoc list = ['apple', 'banana', 'cat', 'dog', 'elephant'] new_list = [x.upper() for x in list] ```
### Instruction: Rewrite the following python program using list comprehension ### Input: list = ['apple', 'banana', 'cat', 'dog', 'elephant'] new_list = [] for x in list: new_list.append(x.upper()) ### Output: ```scdoc list = ['apple', 'banana', 'cat', 'dog', 'elephant'] new_list = [x.upper() for x in list] ```
scdoc
Create an automated web crawler using Python.
Not applicable
```python import requests from bs4 import BeautifulSoup def crawl(url): page = requests.get(url) soup = BeautifulSoup(page.text, 'html.parser') # retrieve all of the anchor tags # We are going to find all links out of the page tags = soup('a') for tag in tags: link = tag.get(...
### Instruction: Create an automated web crawler using Python. ### Input: Not applicable ### Output: ```python import requests from bs4 import BeautifulSoup def crawl(url): page = requests.get(url) soup = BeautifulSoup(page.text, 'html.parser') # retrieve all of the anchor tags # We are goin...
Python
Update the following JavaScript program to add a second parameter “num2" and modify the add function so that it adds num1 and num2.
Not applicable
```gdscript class Calculator { constructor(num1) { this.num1 = num1; this.num2 = 0; } add(num2) { return this.num1 + num2; } subtract(num2) { return this.num1 - num2; } } const calc = new Calculator(5); console.log(calc.add(3)); // Output: 8 console.log(calc.subtract(3)); // Output: 2 ```
### Instruction: Update the following JavaScript program to add a second parameter “num2" and modify the add function so that it adds num1 and num2. ### Input: Not applicable ### Output: ```gdscript class Calculator { constructor(num1) { this.num1 = num1; this.num2 = 0; } add(num2) { return this.num1 + num2; ...
GDScript
Generator a React Native component for a quick login page with a Sign In and Sign Up button.
Not applicable
```python import React from 'react'; import {View, Text, StyleSheet, TouchableOpacity} from 'react-native'; export default function LoginButtons() { return ( <View style={styles.container}> <TouchableOpacity style={styles.signInButton}> <Text style={styles.text}>Sign In</Text> ...
### Instruction: Generator a React Native component for a quick login page with a Sign In and Sign Up button. ### Input: Not applicable ### Output: ```python import React from 'react'; import {View, Text, StyleSheet, TouchableOpacity} from 'react-native'; export default function LoginButtons() { return ( ...
Python
Compute the sum of two matrices and store it in another matrix.
A = [[3, 2, 5], [1, 4, 6]] B = [[4, 2, 6], [2, 3, 7]]
```transact-sql def sum_matrix(A, B): """This function takes two matrices and computes their sum and stores the result in another matrix.""" # Initialize the resulting matrix result_matrix = [[0 for col in range(len(A[0]))] for row in range(len(A))] # Iterate over the given matrices for ro...
### Instruction: Compute the sum of two matrices and store it in another matrix. ### Input: A = [[3, 2, 5], [1, 4, 6]] B = [[4, 2, 6], [2, 3, 7]] ### Output: ```transact-sql def sum_matrix(A, B): """This function takes two matrices and computes their sum and stores the result in another matrix.""" ...
Transact-SQL
Create a Vue.js application for displaying data from an online API. The application should fetch data from the API, display the data in a table, and allow users to search and filter the data.
Not applicable
```transact-sql <template> <div> <input type="text" v-model="search" placeholder="Search"> <table> <tr> <th v-for="key in filteredData[0]"> {{ key }} </th> </tr> <tr v-for="entry in filteredData"> <td v-for="key in entry"> {{ entry[key] }} ...
### Instruction: Create a Vue.js application for displaying data from an online API. The application should fetch data from the API, display the data in a table, and allow users to search and filter the data. ### Input: Not applicable ### Output: ```transact-sql <template> <div> <input type="text" v-model="sear...
Transact-SQL
Create a function called "get_best_score()" which takes a list of scores and returns the maximum score.
[87, 56, 74, 90, 92]
```scdoc def get_best_score(scores): max_score = scores[0] for score in scores: if score > max_score: max_score = score return max_score ```
### Instruction: Create a function called "get_best_score()" which takes a list of scores and returns the maximum score. ### Input: [87, 56, 74, 90, 92] ### Output: ```scdoc def get_best_score(scores): max_score = scores[0] for score in scores: if score > max_score: max_score = score r...
scdoc
Write a JavaScript function for removing duplicate entries in an array.
[1, 2, 3, 4, 1, 4, 6, 9, 3]
```gdscript const removeDuplicates = (arr) => { const unique = new Set(arr); return [...unique]; } ```
### Instruction: Write a JavaScript function for removing duplicate entries in an array. ### Input: [1, 2, 3, 4, 1, 4, 6, 9, 3] ### Output: ```gdscript const removeDuplicates = (arr) => { const unique = new Set(arr); return [...unique]; } ```
GDScript
Create a HTML page to display a calculator with buttons to achieve basic math operations.
Not applicable
```html <!DOCTYPE html> <html> <head> <title>Calculator</title> <style> #container { text-align: center; margin: auto; width: 300px; } </style> </head> <body> <div id="container"> <input id="display" type="text"> <div class="row"> <input type="button" value="1"> ...
### Instruction: Create a HTML page to display a calculator with buttons to achieve basic math operations. ### Input: Not applicable ### Output: ```html <!DOCTYPE html> <html> <head> <title>Calculator</title> <style> #container { text-align: center; margin: auto; width: 300px; } </...
HTML
Write an algorithm to implement an efficient string search through a text.
The text is a short novel consisting of 8 chapters with around seven thousand words.
```transact-sql def stringSearch(text, string): currIndex = 0 textLen = len(text) stringLen = len(string) for i in range(textLen - stringLen): foundMatch = True for j in range(stringLen): if text[i+j] != string[j]: foundMatch = False break if foundMatch: currIndex = ...
### Instruction: Write an algorithm to implement an efficient string search through a text. ### Input: The text is a short novel consisting of 8 chapters with around seven thousand words. ### Output: ```transact-sql def stringSearch(text, string): currIndex = 0 textLen = len(text) stringLen = len(string) for...
Transact-SQL
Design a function to classify an input text according to its sentiment as either positive, negative or neutral.
text = 'I love programming but it can be daunting sometimes.'
```python def classify_sentiment(text): # Load the required libraries import nltk from nltk.sentiment.vader import SentimentIntensityAnalyzer # Create the sentiment analyzer analyzer = SentimentIntensityAnalyzer() # Compute the sentiment score score = analyzer.polarity_scores(text)['compou...
### Instruction: Design a function to classify an input text according to its sentiment as either positive, negative or neutral. ### Input: text = 'I love programming but it can be daunting sometimes.' ### Output: ```python def classify_sentiment(text): # Load the required libraries import nltk from nltk....
Python
Convert the below pseudocode to Javascript.
PRINT "Hello World"
```text only console.log("Hello World"); ```
### Instruction: Convert the below pseudocode to Javascript. ### Input: PRINT "Hello World" ### Output: ```text only console.log("Hello World"); ```
Text only
Create a function in Python to generate a 5x5 two-dimensional array with random integers between 0 and 9.
Not applicable
```python import random def generateArray(): arr = [[0 for i in range(5)] for j in range(5)] for i in range (5): for j in range (5): arr[i][j] = random.randint(0,9) return arr print(generateArray()) ```
### Instruction: Create a function in Python to generate a 5x5 two-dimensional array with random integers between 0 and 9. ### Input: Not applicable ### Output: ```python import random def generateArray(): arr = [[0 for i in range(5)] for j in range(5)] for i in range (5): for j in range (5): arr[i][j] = rand...
Python
Find the most common word in the following article and count its occurrence.
Donald Trump has accused China of “gross negligence” when it comes to the outbreak of the coronavirus. He claims that the virus was “purposely” released by the Chinese authorities and has been spreading globally.
```python """ Find the most common word in the article and count its occurrence """ from collections import Counter def find_most_common_word(text): words = text.split() word_count = Counter(words).most_common() return word_count[0][0], word_count[0][1] if __name__ == '__main__': text = "Donald Trump...
### Instruction: Find the most common word in the following article and count its occurrence. ### Input: Donald Trump has accused China of “gross negligence” when it comes to the outbreak of the coronavirus. He claims that the virus was “purposely” released by the Chinese authorities and has been spreading globally. ...
Python
Edit the code to concatenate the first and last names into a single string.
firstName = "John" lastName = "Smith"
```text only firstName = "John" lastName = "Smith" fullName = firstName + " " + lastName print(fullName) # Outputs 'John Smith' ```
### Instruction: Edit the code to concatenate the first and last names into a single string. ### Input: firstName = "John" lastName = "Smith" ### Output: ```text only firstName = "John" lastName = "Smith" fullName = firstName + " " + lastName print(fullName) # Outputs 'John Smith' ```
Text only
Construct an SQL query to find the last five customers in a database, sorted in ascending order by their birthdays
A sample database Table "Customers" (id, firstname, lastname, dateofbirth)
```scdoc SELECT * FROM Customers ORDER BY dateofbirth asc LIMIT 5; ```
### Instruction: Construct an SQL query to find the last five customers in a database, sorted in ascending order by their birthdays ### Input: A sample database Table "Customers" (id, firstname, lastname, dateofbirth) ### Output: ```scdoc SELECT * FROM Customers ORDER BY dateofbirth asc LIMIT 5; ```
scdoc
Can you write an algorithm in C++ to find the sum of values in a two-dimensional array?
[[1, 2], [3, 4], [5, 6]]
```transact-sql #include <iostream> int sum2dArray(int arr[][2], int size) { int sum = 0; for (int i = 0; i < size; i++) { for (int j = 0; j < 2; j++) { sum += arr[i][j]; } } return sum; } int main() { int arr[][2] = {{1,2}, {3,4}, {5,6}}; int size = sizeof(arr)/s...
### Instruction: Can you write an algorithm in C++ to find the sum of values in a two-dimensional array? ### Input: [[1, 2], [3, 4], [5, 6]] ### Output: ```transact-sql #include <iostream> int sum2dArray(int arr[][2], int size) { int sum = 0; for (int i = 0; i < size; i++) { for (int j = 0; j < 2; j...
Transact-SQL
Rewrite the given function using an optimized approach.
function findNumber(int array[], int number) { for (int index = 0; index < array.length; index++) { if(array[index] == number) return index; } return -1; }
```matlab function findNumber(int array[], int number) { int low = 0; int high = array.length - 1; while (low <= high) { int mid = low + (high - low) / 2; if (array[mid] == number) return mid; if (array[mid] < number) low = mid + 1; else ...
### Instruction: Rewrite the given function using an optimized approach. ### Input: function findNumber(int array[], int number) { for (int index = 0; index < array.length; index++) { if(array[index] == number) return index; } return -1; } ### Output: ```matlab function findNumber(int array[], int n...
Matlab
You are given a square matrix of size N. Sort the matrix along the columns.
arr = [[2, 4, 5], [1, 3, 8], [7, 6, 9]]
```transact-sql def sortColumns(arr): N = 3 temp = [0]*N for i in range(N): for j in range(N): temp[j] = arr[j][i] temp.sort() for j in range(N): arr[j][i] = temp[j] ```
### Instruction: You are given a square matrix of size N. Sort the matrix along the columns. ### Input: arr = [[2, 4, 5], [1, 3, 8], [7, 6, 9]] ### Output: ```transact-sql def sortColumns(arr): N = 3 temp = [0]*N for i in range(N): for j in range(N): temp[j] = arr[j][i]...
Transact-SQL
Create a vector of length n with random values following a normal distribution.
n = 20
```numpy import numpy as np n = 20 vector = np.random.normal(size=n) ```
### Instruction: Create a vector of length n with random values following a normal distribution. ### Input: n = 20 ### Output: ```numpy import numpy as np n = 20 vector = np.random.normal(size=n) ```
NumPy
Create an HTML application to navigate through three webpages.
Not applicable
```xml <html> <head> <title>Navigation Web App</title> </head> <body> <nav> <ul> <li><a href="page1.html">Page1</a></li> <li><a href="page2.html">Page2</a></li> <li><a href="page3.html">Page3</a></li> </ul> </nav...
### Instruction: Create an HTML application to navigate through three webpages. ### Input: Not applicable ### Output: ```xml <html> <head> <title>Navigation Web App</title> </head> <body> <nav> <ul> <li><a href="page1.html">Page1</a></li> <li><a ...
XML
Write a function which takes two numbers and returns the sum of all numbers between them.
3 and 8
```scdoc def sum_between(num1, num2): sum = sum(range(num1, num2+1)) return sum ```
### Instruction: Write a function which takes two numbers and returns the sum of all numbers between them. ### Input: 3 and 8 ### Output: ```scdoc def sum_between(num1, num2): sum = sum(range(num1, num2+1)) return sum ```
scdoc
Create a SQL query to find all the users who ordered five or more items within the past week.
Not applicable
```googlesql SELECT u.id, u.name FROM users u INNER JOIN orders o ON u.id = o.user_id WHERE o.date_ordered > CURDATE() - INTERVAL 1 WEEK GROUP BY u.id, u.name HAVING COUNT(o.id) >= 5; ```
### Instruction: Create a SQL query to find all the users who ordered five or more items within the past week. ### Input: Not applicable ### Output: ```googlesql SELECT u.id, u.name FROM users u INNER JOIN orders o ON u.id = o.user_id WHERE o.date_ordered > CURDATE() - INTERVAL 1 WEEK GROUP BY u.id, u.name HAVING COU...
GoogleSQL
Create an algorithm for a natural language processing model used to classify news articles sentiment.
Not applicable
```scdoc def sentiment_classification(text): # tokenize the input text tokens = tokenize(text) # remove stopwords tokens = remove_stopwords(tokens) # vectorize input text using a predefined vocabulary vector = vectorize(tokens) # calculate sentiment score score = calculate_score(tokens) # classify sentiment i...
### Instruction: Create an algorithm for a natural language processing model used to classify news articles sentiment. ### Input: Not applicable ### Output: ```scdoc def sentiment_classification(text): # tokenize the input text tokens = tokenize(text) # remove stopwords tokens = remove_stopwords(tokens) # vecto...
scdoc
Generate a Fibonacci sequence with a specified length.
length = 10
```scdoc def generate_fibonacci(length): result = [0, 1] for i in range(2, length): result.append(result[i-1] + result[i-2]) return result fibonacci = generate_fibonacci(length) print(fibonacci) ```
### Instruction: Generate a Fibonacci sequence with a specified length. ### Input: length = 10 ### Output: ```scdoc def generate_fibonacci(length): result = [0, 1] for i in range(2, length): result.append(result[i-1] + result[i-2]) return result fibonacci = generate_fibonacci(length) print(fibon...
scdoc
Create a Python program to create a human-readable log of errors in an application.
Not applicable
```python import logging # Create logutillogger logutillogger = logging.getLogger('logutil') logutillogger.setLevel(logging.ERROR) # Create a file handler file_handler = logging.FileHandler('app_error.log') file_handler.setLevel(logging.ERROR) # Create a formatter formatter = logging.Formatter('%(asctime)s - %(level...
### Instruction: Create a Python program to create a human-readable log of errors in an application. ### Input: Not applicable ### Output: ```python import logging # Create logutillogger logutillogger = logging.getLogger('logutil') logutillogger.setLevel(logging.ERROR) # Create a file handler file_handler = logging...
Python
Create an ARKit application for iOS that lets the user point the device camera at a surface and add virtual objects to that surface.
Not applicable
```python import UIKit import ARKit class ARViewController: UIViewController { var sceneView: ARSCNView! override func viewDidLoad() { super.viewDidLoad() setupScene() } func setupScene() { let scene = SCNScene() sceneView = ARSCNView(frame: CGRect(x: 0, ...
### Instruction: Create an ARKit application for iOS that lets the user point the device camera at a surface and add virtual objects to that surface. ### Input: Not applicable ### Output: ```python import UIKit import ARKit class ARViewController: UIViewController { var sceneView: ARSCNView! override func vi...
Python
Write a function in Python that takes an array of integer values and reverses the order of the values.
[1, 2, 3, 4, 5]
```cplint def reverse_array(arr): return arr[::-1] # Returns a slice of the list in reverse order ```
### Instruction: Write a function in Python that takes an array of integer values and reverses the order of the values. ### Input: [1, 2, 3, 4, 5] ### Output: ```cplint def reverse_array(arr): return arr[::-1] # Returns a slice of the list in reverse order ```
cplint
Create a basic HTML/CSS page that contains a table showing the population of different countries.
Population Data for the USA and Canada USA: 327 Million Canada: 36.5 Million
```html <!DOCTYPE html> <html> <head> <title>Population Data</title> <style type="text/css"> th, td { padding: 10px; } </style> </head> <body> <table> <tr> <th>Country</th> <th>Population</th> </tr> <tr> <td>USA</td> <td>327 Million</td> </tr> <tr> <td>Canada</td> <td>36.5 Million</td> </tr>...
### Instruction: Create a basic HTML/CSS page that contains a table showing the population of different countries. ### Input: Population Data for the USA and Canada USA: 327 Million Canada: 36.5 Million ### Output: ```html <!DOCTYPE html> <html> <head> <title>Population Data</title> <style type="text/css"> th, td...
HTML
Compile a MATLAB script that finds the maximum value from a given array.
[2 3 4 5 7 9]
```matlab % Script to find the maximum value in an array arr = [2 3 4 5 7 9]; max_val = arr(1); for i=1:length(arr) if arr(i)> max_val max_val = arr(i); end end fprintf('The maximum value is: %f\n', max_val) ```
### Instruction: Compile a MATLAB script that finds the maximum value from a given array. ### Input: [2 3 4 5 7 9] ### Output: ```matlab % Script to find the maximum value in an array arr = [2 3 4 5 7 9]; max_val = arr(1); for i=1:length(arr) if arr(i)> max_val max_val = arr(i); end end fprintf('Th...
Matlab
Create a C# program that uses LINQ to finds the longest word in a list of strings.
List of strings: "Hello", "World", "Foo", "Bar"
```gdscript using System; using System.Linq; public class Program { public static void Main() { string[] words = {"Hello", "World", "Foo", "Bar" }; var longestWord = words.OrderByDescending(word => word.Length).First(); Console.WriteLine("Longest word is: {0}", longestWord); } } ```
### Instruction: Create a C# program that uses LINQ to finds the longest word in a list of strings. ### Input: List of strings: "Hello", "World", "Foo", "Bar" ### Output: ```gdscript using System; using System.Linq; public class Program { public static void Main() { string[] words = {"Hello", "World", "Foo", "Bar...
GDScript
Can you create an optimization algorithm in Python to minimize the following function?
f(x) = x^4 + 7x^3 + 6x^2 - 6x
```numpy import numpy as np def minimize(x): return np.power(x,4) + 7 * np.power(x,3) + 6 * np.power(x,2) - 6 * x def optimize(f, x): best_x = x best_val = f(x) while True: new_x = x - 1e-3 new_val = f(new_x) if new_val < best_val: best_x = new_x best_val = new_val x = new_...
### Instruction: Can you create an optimization algorithm in Python to minimize the following function? ### Input: f(x) = x^4 + 7x^3 + 6x^2 - 6x ### Output: ```numpy import numpy as np def minimize(x): return np.power(x,4) + 7 * np.power(x,3) + 6 * np.power(x,2) - 6 * x def optimize(f, x): best_x = x best_va...
NumPy
Create a function that takes a number as parameter and prints its double value.
3
```scdoc def double_num(num): print(num * 2) double_num(3) ```
### Instruction: Create a function that takes a number as parameter and prints its double value. ### Input: 3 ### Output: ```scdoc def double_num(num): print(num * 2) double_num(3) ```
scdoc
Create a Java servlet that takes in a web form with two fields and prints out the values of the fields in JSON format.
Form fields: field1: value1 field2: value2
```python import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet("/form") public class For...
### Instruction: Create a Java servlet that takes in a web form with two fields and prints out the values of the fields in JSON format. ### Input: Form fields: field1: value1 field2: value2 ### Output: ```python import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import jav...
Python
Write a code to calculate the maximum score given scores of all the players.
scores = [87, 95, 74, 73, 51]
```scdoc def get_max_score(scores): max_score = scores[0] for score in scores: if score > max_score: max_score = score return max_score ```
### Instruction: Write a code to calculate the maximum score given scores of all the players. ### Input: scores = [87, 95, 74, 73, 51] ### Output: ```scdoc def get_max_score(scores): max_score = scores[0] for score in scores: if score > max_score: max_score = score return max_score ```
scdoc
Using the provided input, generate the relevant Swift code to create an account registration flow.
fields: username: string displayName: string email: string is_active: boolean
```python import Foundation struct RegistrationRequest { let username: String let displayName: String let email: String let is_active: Bool init(username: String, displayName: String, email: String, is_active: Bool) { self.username = username self.displayName = displayName self.email = email self.is_active ...
### Instruction: Using the provided input, generate the relevant Swift code to create an account registration flow. ### Input: fields: username: string displayName: string email: string is_active: boolean ### Output: ```python import Foundation struct RegistrationRequest { let username: String let displayN...
Python
Create a Node.js program to poll an API and log the results. The program should accept an API URL, the polling interval, and the number of times to poll as arguments.
Not applicable
```gdscript const request = require('request'); const url = process.argv[2]; const interval = process.argv[3]; const numberOfRuns = process.argv[4]; let i = 0; function pollApi() { request(url, (err, response, body) => { console.log(`#${i}: ${body}`); if(i < numberOfRuns){ setTimeout(pollApi, interval); ...
### Instruction: Create a Node.js program to poll an API and log the results. The program should accept an API URL, the polling interval, and the number of times to poll as arguments. ### Input: Not applicable ### Output: ```gdscript const request = require('request'); const url = process.argv[2]; const interval = pr...
GDScript
Create a function in Java to insert an item at a specified position in an array.
[50, 40, 20]
```transact-sql public void insertItemAtPosition(int arr[], int item, int position){ int length = arr.length; if(position > length){ System.out.println("Invalid position given."); return; } int[] newarr = new int[length + 1]; for(int i = 0; i < position; i++){ newarr[i]...
### Instruction: Create a function in Java to insert an item at a specified position in an array. ### Input: [50, 40, 20] ### Output: ```transact-sql public void insertItemAtPosition(int arr[], int item, int position){ int length = arr.length; if(position > length){ System.out.println("Invalid pos...
Transact-SQL
Create a Node.js script that composes an email using the nodemailer module and sends it to a user.
To: example@example.com Subject: Hello
```xml const nodemailer = require('nodemailer'); const to = process.argv[2]; const subject = process.argv[3]; const message = `<p>Hello,</p> <p>This is an automated message.</p>`; const transporter = nodemailer.createTransport({ host: 'smtp.example.com', port: 587, secure: false, // true for 465, false for other ...
### Instruction: Create a Node.js script that composes an email using the nodemailer module and sends it to a user. ### Input: To: example@example.com Subject: Hello ### Output: ```xml const nodemailer = require('nodemailer'); const to = process.argv[2]; const subject = process.argv[3]; const message = `<p>Hello,</...
XML
Create a C program to generate the Look and Say sequence up to the given number n
Number: 5
```transact-sql #include<stdio.h> #include<string.h> int main() { char s[100], res[100]; int i, j, count, k; i=j=count=k=0; printf("Enter the number n: "); scanf("%s", s); printf("Look and Say sequence: \n"); while(s[i] != '\0') { while(s[i] == s[i+1]) { ...
### Instruction: Create a C program to generate the Look and Say sequence up to the given number n ### Input: Number: 5 ### Output: ```transact-sql #include<stdio.h> #include<string.h> int main() { char s[100], res[100]; int i, j, count, k; i=j=count=k=0; printf("Enter the number n: "); scanf(...
Transact-SQL
Create a unique list of items from a given list in Python.
given_list = [2, 2, 4, 5, 5, 6, 8, 8]
```scdoc # Unique list unq_list = list(set(given_list)) #Print unique list print(unq_list) ```
### Instruction: Create a unique list of items from a given list in Python. ### Input: given_list = [2, 2, 4, 5, 5, 6, 8, 8] ### Output: ```scdoc # Unique list unq_list = list(set(given_list)) #Print unique list print(unq_list) ```
scdoc
Create a Python AI program that can predict the probability of a book being a bestseller.
Book title, genre, author, publisher, release date, number of reviews, average ratings
```numpy import pandas as pd import numpy as np from sklearn.preprocessing import StandardScaler from sklearn.model_selection import train_test_split from sklearn.linear_model import LogisticRegression # read the dataset df = pd.read_csv('path/to/dataset/file.csv') # feature selection X = df[['title', 'genre', 'aut...
### Instruction: Create a Python AI program that can predict the probability of a book being a bestseller. ### Input: Book title, genre, author, publisher, release date, number of reviews, average ratings ### Output: ```numpy import pandas as pd import numpy as np from sklearn.preprocessing import StandardScaler fr...
NumPy
Design an automated program to extract text mentions of locations in a sentence.
The person just moved to San Francisco following graduation.
```python """ Design an automated program to extract text mentions of locations in a given sentence """ import re def extract_locations(sentence): locations_list = [] # extract words that follow the pattern "word in/at some location" pattern = r"(?:in|at)\s+([\w\s]+)" matches = re.findall(pattern, sen...
### Instruction: Design an automated program to extract text mentions of locations in a sentence. ### Input: The person just moved to San Francisco following graduation. ### Output: ```python """ Design an automated program to extract text mentions of locations in a given sentence """ import re def extract_location...
Python
Write a Python script to remove all leading and trailing whitespace from all string data in a list of dictionaries.
data = [{'name': 'John Doe ', 'age': 34}, {'name': 'Tim Smith ', 'age': 14}]
```transact-sql def strip_whitespace_from_data(data): for i in range(len(data)): for key, value in data[i].items(): if isinstance(value, str): data[i][key] = value.strip() return data data = [{'name': 'John Doe ', 'age': 34}, {'name': 'Tim Smith ', 'age': 14}] data = s...
### Instruction: Write a Python script to remove all leading and trailing whitespace from all string data in a list of dictionaries. ### Input: data = [{'name': 'John Doe ', 'age': 34}, {'name': 'Tim Smith ', 'age': 14}] ### Output: ```transact-sql def strip_whitespace_from_data(data): for i in range(len(da...
Transact-SQL
Generate code to encrypt a text using Caesar Cipher.
text = "Hello, World!" shift = 3
```scdoc def caesar_cipher(text, shift): # initialize an empty output output = "" # traverse the text to encrypt for char in text: # limit of the ASCII shift lim = ord('z') # shifting by 3 c = ord(char) + shift # shift beyond z if c > lim: c ...
### Instruction: Generate code to encrypt a text using Caesar Cipher. ### Input: text = "Hello, World!" shift = 3 ### Output: ```scdoc def caesar_cipher(text, shift): # initialize an empty output output = "" # traverse the text to encrypt for char in text: # limit of the ASCII shift l...
scdoc
Build a network architecture in Keras based on the given parameters.
Input Layer : 5 Hidden Layer 1 : 5 Hidden Layer 2 : 5 Output Layer : 2
```python import keras from keras.models import Sequential from keras.layers import Dense # Create model model = Sequential() model.add(Dense(5, input_dim=5, activation='relu')) model.add(Dense(5, activation='relu')) model.add(Dense(5, activation='relu')) model.add(Dense(2, activation='linear')) # Compile mod...
### Instruction: Build a network architecture in Keras based on the given parameters. ### Input: Input Layer : 5 Hidden Layer 1 : 5 Hidden Layer 2 : 5 Output Layer : 2 ### Output: ```python import keras from keras.models import Sequential from keras.layers import Dense # Create model model = Sequential() mo...
Python
Given a number n, write a function to print out all Prime pairs whose sum is equal to n.
n = 5
```scdoc def get_prime_pairs(n): result = [] for i in range(2, n): if is_prime(i) and is_prime(n - i): result.append([i, n - i]) return result def is_prime(num): if num <= 1: return False for i in range(2, num): if num % i == 0: return False return True ```
### Instruction: Given a number n, write a function to print out all Prime pairs whose sum is equal to n. ### Input: n = 5 ### Output: ```scdoc def get_prime_pairs(n): result = [] for i in range(2, n): if is_prime(i) and is_prime(n - i): result.append([i, n - i]) return result def is_prime(...
scdoc
Update the following program to print out the frequency of words in a given text.
Not applicable
```transact-sql text = 'This is a test text to find the frequency of words' words = text.split() freq = {} for word in words: if word in freq: freq[word] += 1 else: freq[word] = 1 for word, count in freq.items(): print('{} : {}'.format(word, count)) ```
### Instruction: Update the following program to print out the frequency of words in a given text. ### Input: Not applicable ### Output: ```transact-sql text = 'This is a test text to find the frequency of words' words = text.split() freq = {} for word in words: if word in freq: freq[word] += 1 else...
Transact-SQL
Produce a Google App Engine application in Python that shows the current weather forecast for a specific city.
Not applicable
```python import webapp2 from google.appengine.api import urlfetch import json class MainHandler(webapp2.RequestHandler): def get(self): city = 'London' api_key = '<your_api_key>' url = 'http://api.openweathermap.org/data/2.5/weather?q={}&APPID={}'.format(city, api_key) result = urlfetch.fetch(url) self.response...
### Instruction: Produce a Google App Engine application in Python that shows the current weather forecast for a specific city. ### Input: Not applicable ### Output: ```python import webapp2 from google.appengine.api import urlfetch import json class MainHandler(webapp2.RequestHandler): def get(self): city = 'Lond...
Python
Design a Django Rest Framework API that provides access to a ToDo list. The API should be able to create, list, update, and delete tasks.
Not applicable
```python from django.db import models class Task(models.Model): description = models.CharField(max_length=120) def __str__(self): return self.description from rest_framework import viewsets from .serializers import TaskSerializer from .models import Task class TaskViewSet(viewsets.ModelViewSet): queryset = Task...
### Instruction: Design a Django Rest Framework API that provides access to a ToDo list. The API should be able to create, list, update, and delete tasks. ### Input: Not applicable ### Output: ```python from django.db import models class Task(models.Model): description = models.CharField(max_length=120) def __str_...
Python
End of preview. Expand in Data Studio
README.md exists but content is empty.
Downloads last month
19