Dataset Viewer
Auto-converted to Parquet
output
stringlengths
2
2.92k
input
stringlengths
0
1.64k
instruction
stringlengths
9
250
# Python code def sum_sequence(sequence): sum = 0 for num in sequence: sum += num return sum
[1, 2, 3, 4, 5]
Create a function to calculate the sum of a sequence of integers.
def add_strings(str1, str2): """This function takes two strings and returns the sum of them.""" return str1 + str2 str1 = "Hello " str2 = "world" sum_of_strings = add_strings(str1, str2)
str1 = "Hello " str2 = "world"
Develop a function that will add two strings
#include <map> #include <string> class GroceryStoreInventory { private: std::map<std::string, int> items; public: void addItems(std::string item, int quantity) { items[item] = quantity; } int getQuantity(std::string item) { if (items.find(item) != items.end()) { return items[item]; } return 0; } };
Design a data structure in C++ to store information of a grocery store inventory.
def bubble_sort(arr): n = len(arr) # Traverse through all array elements for i in range(n): # Last i elements are already in place for j in range(0, n-i-1): # traverse the array from 0 to n-i-1 # Swap if the element found is greater # than the next element if arr[j] > arr[j+1] : arr[j], arr[j+1] = arr[j+1], arr[j] # Driver code to test above arr = [3, 1, 4, 5, 9, 0] bubble_sort(arr) print ("Sorted array is:") for i in range(len(arr)): print ("%d" %arr[i]),
[3, 1, 4, 5, 9, 0]
Implement a sorting algorithm to sort a given array.
import UIKit class ExpenseViewController: UIViewController { // MARK: - Variables var expenses = [Expense]() @IBOutlet weak var tableView: UITableView! // MARK: - UIViewController override func viewDidLoad() { super.viewDidLoad() tableView.dataSource = self tableView.delegate = self setUpNavigationBar() } // MARK: - Private Functions func setUpNavigationBar() { let addButton = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(addButtonTapped)) navigationItem.setRightBarButton(addButton, animated: true) } @objc func addButtonTapped() { let expenseDetailViewController = ExpenseDetailViewController() expenseDetailViewController.delegate = self present(expenseDetailViewController, animated: true, completion: nil) } } extension ExpenseViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return expenses.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "expenseCell", for: indexPath) let expense = expenses[indexPath.row] cell.textLabel?.text = expense.name cell.detailTextLabel?.text = expense.ammount return cell } } extension ExpenseViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { } } extension ExpenseViewController: ExpenseDetailViewControllerDelegate { func expenseDetailViewController(_ controller: ExpenseDetailViewController, didCreateExpense expense: Expense) { expenses.append(expense) tableView.reloadData() } }
Not applicable
Design a Swift application for tracking expenses. The app should have a view for creating new expenses, and a view for displaying all expenses in a table view.
<?php $timestamp = $_GET['timestamp']; if(empty($timestamp)) { echo json_encode(["error" => "Please provide a valid UNIX timestamp."]); die(); } $date = date("Y-m-d H:i", $timestamp); echo json_encode(["date" => $date]); ?>
Not Applicable
Create a REST API to convert a UNIX timestamp to human readable date.
import requests import re def crawl_website_for_phone_numbers(website): response = requests.get(website) phone_numbers = re.findall('\d{3}-\d{3}-\d{4}', response.text) return phone_numbers if __name__ == '__main__': print(crawl_website_for_phone_numbers('www.example.com'))
website: www.example.com data to crawl: phone numbers
Generate a Python code for crawling a website for a specific type of data.
[x*x for x in [1, 2, 3, 5, 8, 13]]
Create a Python list comprehension to get the squared values of a list [1, 2, 3, 5, 8, 13].
SELECT * FROM products ORDER BY price DESC LIMIT 1;
Create a MySQL query to find the most expensive product from the table "products".
public class Library { // map of books in the library, key is book id, value is Book object private Map<String, Book> books; // Constructor public Library() { books = new HashMap<>(); } public void addBook(Book book) { books.put(book.getId(), book); } public boolean hasBook(String bookId) { return books.containsKey(bookId); } public void borrowBook(String bookId) { Book book = books.get(bookId); if (book != null) { book.borrow(); } } }
Not applicable
Create a data structure in Java for storing and managing books in a library. The data structure should include methods for adding a new book, checking if a particular book is available, and borrowing a book from the library.
import tensorflow as tf from tensorflow.keras.layers import Dense, Input # Preparing data X_train, y_train, X_test, y_test = get_data() # Returns training and testing datasets # Building model inputs = Input(shape=(X_train.shape[1], )) x = Dense(64, activation='relu')(inputs) x = Dense(32, activation='relu')(x) predictions = Dense(1, activation='sigmoid')(x) # Compiling model model = tf.keras.Model(inputs=inputs, outputs=predictions) model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy']) # Training the model model.fit(X_train, y_train, epochs=30, batch_size=32) # Evaluating the model scores = model.evaluate(X_test, y_test, verbose=0) print("Accuracy: %.2f%%" % (scores[1]*100))
Design a neural network model to classify emails into spam and non-spam.
function generateRandomString() { const chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; let str = ''; for (let i = 0; i < 8; i++) { str += chars[Math.floor(Math.random() * chars.length)]; } return str; } console.log(generateRandomString()); // "3xB9uU3d"
Not applicable
Generate a random string of 8 characters that contains at least one number.
import org.smslib.Library; import org.smslib.http.SMSHttpProvider; import org.smslib.smsserver.SMSServer; public class SMSProvider { public void configureProvider(String username, String password) { SMSServer.getInstance().setSmsProvider(new SMSHttpProvider()); SMSServer.getInstance().getSmsProvider().configure( "username=" + username + "," + "password=" + password, Library.getLibrary().getSettings()); } }
Not applicable
Create a Java application for sending SMS messages. This application should include a class for configuring the SMS provider.
class PrimeNumber { public static void main(String a[]) { int n = 10; int i; int j; System.out.print("Prime numbers between 1 and " + n + " are : "); for (i = 1; i < n; i++) { int counter = 0; for (j = i; j >= 1; j--) { if (i % j == 0) { counter = counter + 1; } } if (counter == 2) { System.out.print(i + " "); } } } } // Output: Prime numbers between 1 and 10 are : 2 3 5 7
10
Create a Java program that generates a list of prime numbers from 2 to a given input.
const object = { "Apple": "", "Orange": "", "Carrot": "" };
Apple, Orange, Carrot
Create a JavaScript object containing key-value pairs for each item in the following list:
def remove_duplicates(string): result = "" prev = '' for char in string: if char != prev: result += char prev = char return result result = remove_duplicates("AAABBCCCD") print(result)
Given a string, remove all the consecutive duplicates from the string. Input: "AAABBCCCD"
Generate a python script to perform this action.
public class Sum { public static void main(String[] args) { int[] numbers = {1, 2, 3, 4, 5}; System.out.println("The sum is: " + getSum(numbers)); } public static int getSum(int[] numbers) { int sum = 0; for (int number : numbers) { sum += number; } return sum; } }
public class Sum { public static void main(String[] args) { int[] numbers = {1, 2, 3, 4, 5}; System.out.println("The sum is: " + getSum(numbers)); } }
Edit the following Java code to create a method that calculates the sum of an array of integers.
rectArea :: Num a => a -> a -> a rectArea l w = l * w
Design a Haskell solution for finding the area of a rectangle.
import React, { useState } from "react"; const App = () => { const [input1, setInput1] = useState(0); const [input2, setInput2] = useState(0); const [result, setResult] = useState(0); const handleInput1Change = (e) => { setInput1(e.target.value); }; const handleInput2Change = (e) => { setInput2(e.target.value); }; const handleSubmit = (e) => { e.preventDefault(); setResult(Number(input1) - Number(input2)); }; return ( <> <form onSubmit={handleSubmit}> <input type="number" value={input1} onChange={handleInput1Change} /> - <input type="number" value={input2} onChange={handleInput2Change} /> <button type="submit">Calculate</button> </form> <p>Result: {result}</p> </> ); }; export default App;
Not applicable
Create a React application to input two numbers and subtract them, displaying the result.
def generate_random_divisible_number(): import random while True: # Generate a random number process = random.randint(0, 9) # Check if the number is divisible by 3 if process % 3 == 0: # If it is divisible, return it return process
Write a python script to generates random numbers between 0 and 9 that are divisible by 3.
import numpy as np matrix = np.random.randint(1, 10, (3, 2)) print(matrix)
Generate a 3x2 matrix filled with random numbers.
def subtract(a,b): return a-b print(subtract(110, 15)) # Output: 95
110, 15
Create a program which subtracts two numbers and prints the result.
import os import django os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'webapp.settings') django.setup() from stocks.models import Stock stocks = [ {'name': 'AAPL', 'price': 428.31, 'change': -1.51, 'percent_change': -0.35}, {'name': 'MSFT', 'price': 217.31, 'change': 2.24, 'percent_change': 1.04}, {'name': 'AMZN', 'price': 3282.19, 'change': 5.78, 'percent_change': 0.18}, {'name': 'FB', 'price': 262.83, 'change': 4.68, 'percent_change': 1.81}, {'name': 'GOOG', 'price': 1517.11, 'change': 5.58, 'percent_change': 0.37}, ] for stock in stocks: Stock.objects.create(**stock)
NYSE:AAPL, 428.31, -1.51, -0.35 NYSE:MSFT, 217.31, 2.24, 1.04 NYSE:AMZN, 3282.19, 5.78, 0.18 NYSE:FB, 262.83, 4.68, 1.81 NYSE:GOOG, 1517.11, 5.58, 0.37
Create a Django web application that displays a table of stocks with the following columns - name, current stock price, change and percentage change.
public class User { public int Id { get; set; } public string Name { get; set; } public string EmailAddress { get; set; } public User(int id, string name, string emailAddress) { Id = id; Name = name; EmailAddress = emailAddress; } }
Generate a class in C# that can be used to represent users in a database.
A = [3, 7, 23, 17]; %Input list answer = sum(A); % Calculation fprintf('Summation of the given list is %d', answer); % Output
[3, 7, 23, 17]
Create a Matlab program that computes the summation of an given list of numbers.
def reverse_string(string): # Reverse the string if len(string) == 0: return string else: return reverse_str(string[1:]) + string[0]
def reverse_string(string): #TODO
In the function below, write an algorithm to reverse a string.
import random import string def generateRandomString(n): letters = string.ascii_lowercase return ''.join(random.choice(letters) for i in range(n))
Create a code snippet that will generate a random string with length n (n is an input to the program).
import tensorflow as tf from tensorflow.keras.datasets import mnist from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense, Dropout, Flatten from tensorflow.keras.layers import Conv2D, MaxPooling2D # Input image dimensions img_rows, img_cols = 28, 28 # Load image data (x_train, y_train), (x_valid, y_valid) = mnist.load_data() # Reshape it for Conv2D x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols, 1) x_valid = x_valid.reshape(x_valid.shape[0], img_rows, img_cols, 1) # Convert to float32 x_train = x_train.astype('float32') x_valid = x_valid.astype('float32') # Normalize data x_train /= 255 x_valid /= 255 # Build and compile the model model = Sequential() model.add(Conv2D(32, kernel_size=(3,3), activation='relu', input_shape=x_train.shape[1:])) model.add(MaxPooling2D(pool_size=(2,2))) model.add(Dropout(0.25)) model.add(Flatten()) model.add(Dense(128, activation='relu')) model.add(Dropout(0.5)) model.add(Dense(10, activation='softmax')) model.compile(loss='sparse_categorical_crossentropy', optimizer='adam', metrics=['accuracy']) model.fit(x_train, y_train, epochs=10, batch_size=128, validation_data=(x_valid, y_valid))
Build a program to train a model to recognize handwritten digits using a convolutional neural network.
<!DOCTYPE html> <html> <head> <title>Tree visualization</title> <style> ul { list-style-type: none; padding: 0; margin: 0; } li { display: flex; flex-direction: row; justify-content: flex-start; font-size: 48px; padding: 5px 0; margin-bottom: 10px; } li::before { content: " "; flex: 0 0 90%; padding-right: 10px; border-left: 1px solid gray; } </style> </head> <body> <ul> <li>0 <ul> <li>1 <ul> <li>3</li> <li>4</li> </ul> </li> <li>2 <ul> <li>5</li> </ul> </li> </ul> </li> </ul> </body> </html>
Tree structure: +---0 +---1 | +---3 | +---4 +---2 +---5
Create a web page to visualize the tree structure provided as an input.
def find_max(nums, max_num=None): if len(nums) == 0: return None for num in nums: if num > max_num: max_num = num return max_num
def find_max(nums, max_num=None): if len(nums) == 0: return None if max_num is None: max_num = nums[0] for num in nums: if num > max_num: max_num = num return max_num
Rewrite the following code to remove two lines that are not necessary.
#include <iostream> //Define the base class class GameObject { public: // All game objects have a position double x, y, z; // Every game object should have an update method virtual void Update() { }; //Destructor virtual ~GameObject() { } }; //Define a derived class class Player : public GameObject { public: //Player objects have a health int health; // Every Player should update in its own way void Update() override { // Do something here } }; //Define another derived class class Enemy : public GameObject { public: //Enemy objects have an attack damage int attackDamage; // Every Enemy should update in its own way void Update() override { // Do something here } };
Not applicable
Design an object-oriented architecture for a game in C++.
def remove_whitespace(string): return string.replace(" ", "")
string = “ Hello World ”
Create a function to remove all white spaces in a string.
// The main function to get recommendations function getRecommendations(userInput) { // Get data from the API call let data = await API.getData(); // Process data to extract important information let processedData = processData(data); // Process user input to extract important information let processedUserInput = processUserInput(userInput); // Compare the processed data and processed user input let comparisons = compareInputs(processedData, processedUserInput); // Get the most similar value let topMatch = getTopMatch(comparisons); // Create the recommendations with the top match let recommendations = createRecommendations(topMatch); return recommendations; }
Not applicable
Implement a recommendation engine in your mobile application which can offer customized suggestions based on user interaction.
#include <iostream> #include <vector> using namespace std; void optimizeMatrix (vector<vector<int>> &mat, int val) { // Iterate over the matrix for (int i = 0; i < mat.size(); i++) { for (int j = 0; j < mat[i].size(); j++) { // Substitute all elements to be // greater than or equal to value if (mat[i][j] < val) mat[i][j] = val; } } } int main() { // Create a matrix vector<vector<int>> mat = { {4, 5, 7}, {9, 1, 8}, {1, 2, 4} }; int val = 3; // print matrix optimizeMatrix(mat, val); // Print after optimization for (int i = 0; i < mat.size(); i++) { for (int j = 0; j < mat[i].size(); j++) cout << mat[i][j] << " "; cout << endl; } return 0; }
Write a C ++ program to optimize a given matrix with specific values.
def bubble_sort(arr): n = len(arr) # Loop through the array from the beginning to the end for i in range(n): # Create a flag to determine if a swap is necessary swap_flag = False # Iterate through all elements before the last for j in range(0, n-i-1): # Compare the two elements if arr[j] > arr[j+1] : # Swap the two elements arr[j], arr[j+1] = arr[j+1], arr[j] # Set the flag swap_flag = True # Break out of the loop if no swap is needed if swap_flag == False: break # example arr = [5,1,4,2,3] bubble_sort(arr) print(arr) # [1, 2, 3, 4, 5]
[5,1,4,2,3]
Create a bubble sort algorithm to sort an array of integers in ascending order.
import React from 'react'; const CommentsList = ({ comments }) => { const sortedComments = comments.sort((a, b) => b.rating - a.rating); return ( <ul> {sortedComments.map(comment => ( <li key={comment.id}> <p> <b>Rating:</b> {comment.rating} </p> <p>{comment.body}</p> <p> <b>Author:</b> {comment.author} </p> </li> ))} </ul> ); }; export default CommentsList;
Not applicable
Develop a React component to render a list of user comments sorted by highest rating to lowest rating.
function calculateAge(dateString) { let today = new Date(); let birthDate = new Date(dateString); let age = today.getFullYear() - birthDate.getFullYear(); let m = today.getMonth() - birthDate.getMonth(); if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) { age--; } return age; } console.log(calculateAge("1982/3/21")); // Output: 38
date = 1982/3/21
To evaluate a user's birthdate, write a JavaScript function to calculate age given a date of birth.
SELECT * FROM table ORDER BY date ASC;
Not applicable
Create a SQL query to select all records from a table ordered by date from oldest to newest.
// File: routes/users.js const express = require('express'); const { createUser, getUser, updateUser, deleteUser } = require('../controller/usersController'); const router = express.Router(); // Create a new User router.post('/users', createUser); // Get a User router.get('/users/:id', getUser); // Update a User router.put('/users/:id', updateUser); // Delete a User router.delete('/users/:id', deleteUser); module.exports = router;
Not applicable
Develop an Express application to manage Users. This application should have routes for creating a new User, getting a User, updating a User, and deleting a User.
public static void splitArray(int arr[]) { int mid = (arr.length + 1) / 2; int a[] = Arrays.copyOfRange(arr, 0, mid); int b[] = Arrays.copyOfRange(arr, mid, arr.length); System.out.println("First Array: "+Arrays.toString(a)); System.out.println("Second Array: "+Arrays.toString(b)); }
Array: {2, 4, 1, 6, 7, 8, 3, 5}
Write a function in Java to split the array into two halves.
class Point { constructor(x, y) { this.x = x; this.y = y; } }
Not applicable
Generate a valid JavaScript class constructor that takes in x and y coordinates.
def third_largest(lst): if len(lst) < 3: return distinct = [] for i in lst: if i not in distinct: distinct.append(i) distinct.sort(reverse=True) return distinct[2]
[12, 13, 13, 45, 22, 99]
Write a Python code to get the third largest element in a given row.
def max_sum_tuple(tuples): # Initialize the max_sum as 0 max_sum = 0 # Iterate through the list of tuples for tup in tuples: # Get the sum of the current tuple sum_tup = sum(tup) # Update the max_sum if the current sum is greater if sum_tup > max_sum: max_sum = sum_tup max_tup = tup return max_tup print(max_sum_tuple(tuples))
tuples = [(1, 2), (5, 6), (7, 8), (4, 9)]
Given a list of tuples, write a program to find the tuple with the maximum sum.
function binarize(arr) convertedArr = zeros(size(arr)) for i in eachindex(arr) if arr[i] > 0 convertedArr[i] = 1 end end return convertedArr end
Create a Julia function to binarize an input array
from flask import Flask, request from flask_sqlalchemy import SQLAlchemy app = Flask(name) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db' db = SQLAlchemy(app) class Record(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(120), unique=True) db.create_all() @app.route('/records', methods=['GET']) def get_records(): records = Record.query.all() return {'records':[record.name for record in records]} @app.route('/records', methods=['POST']) def create_record(): record = Record(name=request.json['name']) db.session.add(record) db.session.commit() return {'id': record.id} @app.route('/records/int:id', methods=['PUT']) def update_record(id): record = Record.query.get(id) record.name = request.json['name'] db.session.commit() return {'message': 'Record updated'} @app.route('/records/int:id', methods=['DELETE']) def delete_record(id): Record.query.filter_by(id=id).delete() db.session.commit() return {'message': 'Record deleted'} if name == 'main': app.run(debug=True)
Not applicable
Generate a REST API with Python and Flask that allows users to create, read, update, and delete records from a database.
def valid_sudoku(board): # Row check for row in board: if sorted(row) != [1,2,3,4,5,6,7,8,9]: return False # Column check for col in list(zip(*board)): if sorted(col) != [1,2,3,4,5,6,7,8,9]: return False # 3x3 check for i in [0,3,6]: for j in [0,3,6]: subset = [board[x][y] for x in range(i,i+3) for y in range(j,j+3)] if sorted(subset) != [1,2,3,4,5,6,7,8,9]: return False # If everything passes, the board is valid return True
3 4 6 8 2 9 7 5 1 7 8 9 6 5 1 4 3 2 5 2 1 4 7 3 6 9 8 6 3 7 9 4 8 5 2 1 2 9 4 5 1 6 3 8 7 8 1 5 3 6 7 9 4 2 9 6 8 1 3 5 2 7 4 1 7 3 2 8 4 9 6 5 4 5 2 7 9 6 1 0 8
Generate an algorithm that checks for the validity of a sudoku puzzle solution
public static double calculateMean(List<Integer> list) { double sum = 0; for (int num : list) { sum += num; } double mean = sum / (list.size()); return mean; }
List of Numbers: [1, 3, 2, 5, 4]
Devise an algorithm in Java that takes a list of numbers as input and outputs the mean (average) of the numbers.
We can use the following linear classifier: y = mx + c with m = 3 and c = 0, our classifier would look like: y = 3x + 0 For the given data points (1, 5) and (2, 8) we can classify them like so: Point (1, 5) -> 5 = 3(1) + 0 -> y = 3x, classify as class 1 Point (2, 8) -> 8 = 3(2) + 0 -> y = 3x, classify as class 1
Attempt to classify the following data points (1, 5) and (2, 8) using a linear classifier.
SELECT CASE WHEN age BETWEEN 18 AND 25 THEN 'Young Adult' WHEN age BETWEEN 26 AND 30 THEN 'Adult' WHEN age > 30 THEN 'Senior' END AS age_group FROM table;
IF age is between 18 and 25 output "Young Adult" ELSE IF age is between 26 and 30 output "Adult" ELSE IF age is greater than 30 output "Senior"
Convert the following pseudocode into SQL query.
def binary_elements(arr): result = [] for val in arr: if val == True or val == False: result.append(val) return result
[1, 2, True, False, 0, 4]
Design a program to identify the elements present in a list which are binary values.
def contains_words(input_string, words): for word in words: if word not in input_string: return False return True print(contains_words('This is a test', ['test', 'this', 'is'])) # True
'This is a test', ['test', 'this', 'is']
Create a Python function that takes in a string and a list of words and returns true if the string contains all the words in the list.
function moveZeros(arr){ let notZero = []; let zeros = []; for(let item of arr){ if(item === 0){ zeros.push(item); } else { notZero.push(item); } } for (let zero of zeros){ notZero.push(zero); } return notZero; } console.log(moveZeros([0, 4, 0, 10, 0, 2, 14]))
[0, 4, 0, 10, 0, 2, 14]
Write a JavaScript program to move all zeros in an array to the end.
regex_pattern = r"^&.*"
Construct a regex pattern that can detect any strings that contain ampersand character as the first letter.
# Define the model model = Sequential() model.add(Input(shape=(None,))) #Input layer model.add(Embedding(input_dim=VOCAB_SIZE, output_dim=EMBEDDING_DIM)) model.add(Bidirectional(LSTM(units=128))) model.add(Dense(units=2, activation="softmax")) # Compile the model model.compile( optimizer="adam", loss="binary_crossentropy", metrics=['acc'] ) # Train the model model.fit( x=data, y=labels, batch_size=64, epochs=30 )
Two sets of text strings, one for each category
Create a Keras model with one input and one output that classifies text strings into two categories.
def max_thermometer_reading(l): '''This function computes the maximum thermometer reading given as a list of strings''' order = {'F': 0, 'C': 1} max_val = float('-inf') for reading in l: num, unit = reading[:-1], reading[-1] if order[unit] > order[max_val[-1]]: max_val = reading elif order[unit] == order[max_val[-1]]: if float(max_val[:-1]) < float(num): max_val = reading return max_val
["100F", "45C", "30C"]
Write a function to compute the maximum thermometer reading given as a list of strings?
query { countries { name population } }
Not applicable
Create a GraphQL query which returns the list of countries with their populations.
const axios = require('axios'); const cron = require('node-cron'); const nodemailer = require('nodemailer'); // Create a cron job to trigger the monitoring cron.schedule('* * * * *', async () => { // Make an API call to get the resource const response = await axios.get('<url of resource endpoint>'); const data = response.data; // Check if the value has changed from the last time if (data.value !== <previous_value>) { // Send the alert const transporter = nodemailer.createTransport({ host: <host>, port: <port>, auth: { user: <user>, pass: <password> } }); const mailOptions = { from: <sender email>, to: <recipient email>, subject: 'Resource Change Alert', text: `The value of the resource has been changed to ${data.value}` }; transporter.sendMail(mailOptions, (error, info) => { if (error) { console.log(error); } else { console.log('Email sent: ' + info.response); } }); } <update previous_value to the latest value> });
Not applicable
Program a webhook to continuously monitor a specific resource for any changes and send an alert in the form of an email when a change is detected.
function reverseString(str) { let reversedStr = ''; for(let i = str.length -1; i >= 0; i--) { reversedStr += str[i]; } return reversedStr; }
Create a function which reverses a string in JavaScript.
<html> <head> <title>Input Form</title> </head> <body> <form action="" method="post"> <label for="name">Name: </label> <input type="text" name="name" id="name"> <input type="submit" name="submit" value="Submit"> </form> </body> </html>
Create a HTML page with an input form to capture the name of a user
def is_palindrome(s): '''This function returns True if the string s is a palindrome and False if it isn't.''' return s == s[::-1] # Checks if s is the same as its reverse.
def is_palindrome(s): '''Write your code here.'''
What should this Python program do?
import boto3 client = boto3.client('polly') def text_to_speech(text): response = client.synthesize_speech( OutputFormat='mp3', Text=text, VoiceId='Joanna' ) return response
Use the Amazon Text-to-Speech API to generate speech from a given text.
import java.util.Arrays; public class Permutation { public static void permute(int[] arr, int index, int n) { if (index >= n) { System.out.println(Arrays.toString(arr)); return; } for (int i = index; i < n; i++) { // Swapping int temp = arr[i]; arr[i] = arr[index]; arr[index] = temp; permute(arr, index + 1, n); // Backtrack temp = arr[i]; arr[i] = arr[index]; arr[index] = temp; } } public static void main(String[] args) { int[] arr = {1, 2, 3}; permute(arr, 0, arr.length); } }
import java.util.Arrays; public class Permutation { public static void main(String[] args) { int[] arr = {1, 2, 3}; System.out.println(Arrays.toString(arr)); } }
Rewrite this Java program to extend it to do all permutations of a given array.
from sklearn.linear_model import LogisticRegression model = LogisticRegression(max_iter=80)
Use the Sklearn API to create a logistic regression model with maximum iterations of 80.
15
[1, 5, 10, 8, 15]
Output the maximum element in an array.
<template> <div> <button @click="handleClick">Click me!</button> </div> </template> <script> export default { name: 'MyComponent', methods: { handleClick() { // call an action here } } } </script>
Not applicable
Create a Vue.js component with a button that calls an action when clicked.
public class HelloClass { private String name; public HelloClass(String name) { this.name = name; } public void sayHello() { System.out.println("Hello " + name); } }
A string variable called 'name' and a function called 'sayHello' which prints 'Hello {name}'.
Create a program that creates a class with variables and methods
struct Student { int id; string name; string email; int age; int grade; string address; }; unordered_map<int, Student> studentDB;
Design and create a data structure to efficiently store and retrieve student information.
public static int getMaxElement(int[] arr) { if (arr.length == 0) return 0; int maxElement = arr[0]; for (int i = 1; i < arr.length; i++) if (arr[i] > maxElement) maxElement = arr[i]; return maxElement; } int[] arr = { 6, 1, 4, 9, -2 }; int maximumElement = getMaxElement(arr); System.out.println("Maximum element of the array is: " + maximumElement); # Output: 9
[6, 1, 4, 9, -2]
Design a function in Java to calculate the maximum of a given array.
arr = [17, 41, 5, 22, 54, 6, 29, 3, 13] arr.sort() print(arr) # Output: [3, 5, 6, 13, 17, 22, 29, 41, 54]
[17, 41, 5, 22, 54, 6, 29, 3, 13]
Create a Python program to sort and print out the elements of an array of integers.
def simulate_particle(x0, y0, vx0, vy0, dt): """Simulate the movement of a particle in two dimensions given initial x, y postions and the x, y velocities.""" x_position = x0 + vx0 * dt y_position = y0 + vy0 * dt return (x_position, y_position) x, y = simulate_particle(0, 0, 5, 10, 0.2) print("X position: ", x) print("Y position: ", y)
Create a program to simulate the movement of a particle in two dimensions.
The model would take the utterance as input and be trained on a labeled dataset of intents and utterances. The outputs of the model can be probabilities of each intent corresponding to the input utterance. The model could for example be a recurrent neural network (RNN) with an attention layer which is trained on the dataset.
Utterance: I would like to book a flight
Implement a deep learning model to classify intents in a utterance.
<!DOCTYPE html> <html> <head> <title>BMI Calculator</title> <script> function calculateBMI(){ // get the user's weight and height from the inputs let weight = document.getElementById('weight').value; let height = document.getElementById('height').value; // calculate BMI let bmi = weight / (height * height); //display the result document.getElementById('result').innerHTML = 'Your BMI is ' + bmi; } </script> </head> <body> <h1>Body Mass Index (BMI) Calculator</h1> <input type="text" id="weight" placeholder="Enter your weight in kg"> <input type="text" id="height" placeholder="Enter your height in meters"> <button onclick="calculateBMI()">Calculate BMI</button> <p id="result"></p> </body> </html>
Not applicable
Create an HTML page with a JavaScript function that calculates a user's Body Mass Index (BMI).
CREATE PROCEDURE insert_user(IN first_name VARCHAR(255), IN last_name VARCHAR(255), IN email VARCHAR(255), IN user_level INT) BEGIN INSERT INTO users(first_name, last_name, email, user_level) VALUES(first_name, last_name, email, user_level); END;
Create a stored procedure in MySQL to insert new data into the table 'users'.
def double_add(num1, num2): return (num1 + num2) * 2
Generate a Python program that adds two then doubles the result.
class MyClass { public: MyClass(const MyClass& other){}; private: };
class MyClass { public: private: };
Edit the given C++ class so that the copy constructor is defined.
String sql = "SELECT SUM(payment_amount) FROM orders"; Statement st = conn.createStatement(); ResultSet rs = st.executeQuery(sql); while(rs.next()) { System.out.println("Sum of payment_amount : " + rs.getInt("SUM(payment_amount)")); }
Table name: orders Column name: payment_amount
Create a Java program that creates an SQL query to calculate the summation of values in a given column.
SELECT * FROM Employees;
Table Name: Employees
Generate an optimized SQL query that select all rows in the table.
import numpy as np arr = np.random.randint(0, 100, 10) median = np.median(arr)
Create a NumPy array called "arr" with 10 elements and compute the median.
const table = document.querySelector('table'); const rows = table.querySelectorAll('tr'); const data = []; rows.forEach(row => { let cells = row.querySelectorAll('td'); let rowData = {}; for (let i = 0; i < cells.length; i += 2) { const key = cells[i].textContent; const value = cells[i+1].textContent; rowData[key] = value; } data.push(rowData); }); console.log(data); /* [ { "id": 1, "name": "John Smith", "email": "[email protected]" }, { "id": 2, "name": "Jane Doe", "email": "[email protected]" } ] */
[ { "id": 1, "name": "John Smith", "email": "[email protected]" }, { "id": 2, "name": "Jane Doe", "email": "[email protected]" } ]
Generate a JavaScript script for parsing HTML tables.
import React, { Component } from 'react'; import { Line } from 'react-chartjs-2'; class Chart extends Component { render() { const data = { labels: [1, 2, 3], datasets: [ { label: 'Data points', data: this.props.dataPoints, fill: false, lineTension: 0.1, backgroundColor: 'rgba(75,192,192,0.4)', borderColor: 'rgba(75,192,192,1)', borderCapStyle: 'butt', borderDash: [], borderDashOffset: 0.0, borderJoinStyle: 'miter', pointBorderColor: 'rgba(75,192,192,1)', pointBackgroundColor: '#fff', pointBorderWidth: 1, pointHoverRadius: 5, pointHoverBackgroundColor: 'rgba(75,192,192,1)', pointHoverBorderColor: 'rgba(220,220,220,1)', pointHoverBorderWidth: 2, pointRadius: 1, pointHitRadius: 10, } ] }; return ( <div> <Line data={data} /> </div> ) } } export default Chart;
Data Points: [{x: 1, y: 10}, {x: 2, y: 20}, {x: 3, y: 30}]
Create a React component that displays given data points in a graphical format.
<template> <div> <h2>User Information</h2> <ul> <li>Name: {{user.name}}</li> <li>Email: {{user.email}}</li> <li>Age: {{user.age}}</li> <li>Country: {{user.country}}</li> </ul> </div> </template> <script> export default { data() { return { user: { name: 'John Doe', email: '[email protected]', age: 34, country: 'USA' } } } } </script>
Not applicable
Create a Vue.js application to display basic information about a user.
pragma solidity ^0.6.6; contract ToDoList { struct Task { string title; bool status; } // Define an array to store tasks Task[] tasks; // Create a task function createTask(string memory _title) public { Task memory newTask = Task(_title, false); tasks.push(newTask); } // Check off a task function checkOffTask(uint _id) public { Task storage task = tasks[_id]; require(task.status == false, "Task already checked off"); task.status = true; } // Delete a task function deleteTask(uint _id) public { require(_id < tasks.length, "Index does not exist"); delete tasks[_id]; } }
Not applicable
Create a Ethereum smart contract for a simple ToDo list application. This application should include methods to create, check off, and delete tasks with each task having a title and a status (open, checked off).
const Readline = require('readline'); const rl = Readline.createInterface({ input: process.stdin, output: process.stdout }); rl.question('Enter time in seconds: ', (answer) => { let seconds = parseInt(answer); console.log(`Starting timer for ${seconds} seconds.`); const start = Date.now(); const end = start + (seconds * 1000); const timer = setInterval(() => { let now = Date.now(); if (now > end) { clearInterval(timer); console.log("Time's up!"); rl.close(); return; } let remainingTime = Math.round((end-now)/1000); console.log(`Time remaining: ${remainingTime} seconds`); }, 1000); });
Create a simple node program that runs a timer.
""" Design a solution to track the employees working in a company """ Create a database table with fields to store employee information such as: -ID: unique ID of the employee -Name: Name of the employee -Department: Department in which the employee works -Address: Home address of the employee -Start Date: Date when the employee joined the company -End Date: Date when the employee left the company (if applicable) Create an interface for users to view and update the employee database. The interface should include functions to add new employees, view/edit current employee information, and track employee events such as promotions, transfers, and terminations.
Design a solution to track the employees working in a company
const express = require('express'); const uuid = require('uuid'); const pdf = require('html-pdf'); const app = express(); let orders = [ { orderId: 'ORD0001', items: [ { name: 'Apple', quantity: 2, price: 2.99 }, { name: 'Banana', quantity: 5, price: 0.99 } ] } ]; app.get('/invoice', async (req, res) => { const orderId = req.query.orderId; const order = orders.find(order => order.orderId === orderId); if (!order) res.status(400).send({ error: 'Order not found' }); const invoiceHtml = ` <div> <h1>Invoice</h1> <ul> ${order.items .map(item => `<li>${item.name} (${item.quantity}) - ${item.price * item.quantity}</li>`) .join('')} </ul> </div> `; const filename = `invoice-${uuid.v4()}.pdf`; const options = { format: 'Letter' }; try { const file = await pdf.create(invoiceHtml, options); res.setHeader('Content-Disposition', `attachment; filename=${filename}`); file.toStream().pipe(res); } catch (err) { res.status(500).send(err); } }); app.listen(3000, () => console.log('Server started'));
Not applicable
Create an endpoint in an Express application that generates a PDF invoice for a given order.
def extract_words(sentence): non_vowel_words = [] words = sentence.split() vowels = ['a','e','i','o','u','A','E','I','O','U'] for word in words: if not any(char in vowels for char in word): non_vowel_words.append(word) return non_vowel_words
This machine learning project is challenging.
Write a python program to extract the non-vowel words in a sentence.
def is_palindrome(sentence): sentence = sentence.lower().replace(' ', '') if sentence == sentence[::-1]: return True else: return False
Sentence: Was it a car or a cat I saw?
Create a function to check for palindromes in a sentence.
SELECT type, MAX(price) AS 'highest_price' FROM products GROUP BY type;
Write a SQL query to find the highest price for each product type.
class Program { static void Main(string[] args) { // Get the number from the user Console.Write("Please enter a number: "); int number = Int32.Parse(Console.ReadLine()); // Print out the multiplication table for (int i = 1; i <= 10; i++) { Console.WriteLine("{0} x {1} = {2}", number, i, number * i); } } }
Not applicable
Create a program in C# that prints out multiplication tables of any given number up to 10.
function printReverseLinkedList(head) { if (head === null) return; printReverseLinkedList(head.next); console.log(head.data); }
Create a function to print the elements of a linked list in a reverse order.
# Dictionary to store Roman to Decimal values roman_val = { 'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000 } # Function to convert Roman numerals to Number def ConvertRoman(st): # Initialize result res = 0 # Traverse given input for i in range(len(st)): # Getting value of symbol s[i] s1 = roman_val[st[i]] if (i+1 < len(st)): # Getting value of symbol s[i+1] s2 = roman_val[st[i+1]] # Comparing both values if (s1 >= s2): # Value of current symbol is greater # or equal to the next symbol res = res + s1 else: # Value of current symbol is greater # or equal to the next symbol res = res + s2 - s1 i += 1 else: res = res + s1 return res
Create a program to convert from Roman numerals to decimal numbers.
list_of_positive_integers = [1, 5, 6, 7, 8] total = sum(list_of_positive_integers) avg = total/len(list_of_positive_integers) print("The average of the list of positive integers is {}".format(avg))
List of positive integers: [1, 5, 6, 7, 8]
Write a Python program to calculate the average of a list of positive integers and output the result.
# Imports import tensorflow as tf from tensorflow import keras from tensorflow.keras import layers # Input data data = tf.data.Dataset.from_tensor_slices(texts, sentiments) # Define model model = keras.Sequential() model.add(layers.InputLayer(input_shape=X_train.shape[1])) model.add(layers.Embedding(input_dim=1000, output_dim=32, input_length=60)) model.add(layers.Dropout(rate=0.2)) model.add(layers.LSTM(units=32)) model.add(layers.Dense(1, activation='sigmoid')) # Compile model.compile(loss='binary_crossentropy', optimizer='rmsprop', metrics=['accuracy']) # Train model.fit(train_data, train_sentiments, epochs=50, batch_size=64)
Not applicable
Generate a Tensorflow model for a sentiment analysis task.
function validateEmail(email) { var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; return re.test(email); }
Create a JavaScript function to check if a string is a valid email address or not.
import { connect } from "pg"; import { Handler } from "aws-lambda"; const handler: Handler = async (event, _context) => { const { host, user, database, password } = process.env; const connection = await connect({ host, user, database, password, }); const res = connection.query( "SELECT first_name, last_name FROM users;" ); return res.rows; } export { handler }
Database: PostgreSQL Query: SELECT first_name, last_name FROM users;
Create an AWS Lambda function that queries a database and returns the results of the query.
SELECT name, age FROM people;
Write a SQL statement to select the fields "name" and "age" from a table called `people`.
def generate_random_numbers (0..10).to_a.sample(5) end puts generate_random_numbers
Not applicable
Develop a Ruby program to generate five random numbers between 0 and 10
class Student { private String name; private String rollNumber; private int marks; public Student(String name, String rollNumber, int marks) { this.name = name; this.rollNumber = rollNumber; this.marks = marks; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getRollNumber() { return rollNumber; } public void setRollNumber(String rollNumber) { this.rollNumber = rollNumber; } public int getMarks() { return marks; } public void setMarks(int marks) { this.marks = marks; } }
Produce a class in Java to represent a student with fields like rollNumber, name and marks?
<html> <body> <table> <tr> <th>Employee Name</th> <th>Salary</th> </tr> <tr> <td>John Doe</td> <td>50000</td> </tr> <tr> <td>Jane Doe</td> <td>45000</td> </tr> <tr> <td>Dr. Smith</td> <td>75000</td> </tr> </table> </body> </html>
Employee Name | Salary John Doe | 50000 Jane Doe | 45000 Dr. Smith | 75000
Create a HTML document that displays a table with the employee data given below.
def pascal_triangle(n): trow = [1] y = [0] for x in range(max(n, 0)): print(trow) trow=[l+r for l,r in zip(trow + y, y + trow)] return n>=1 pascal_triangle(5)
Develop a function in Python that prints out the Pascal's triangle for a given number of rows.
End of preview. Expand in Data Studio

No dataset card yet

Downloads last month
2