text stringlengths 141 2.89k ⌀ | instruction stringlengths 19 1.5k ⌀ | input stringlengths 0 800 ⌀ | output stringlengths 1 2.5k ⌀ |
|---|---|---|---|
null | Build a Python function that takes in two integers and returns the greatest common divisor. | 4 and 8 | def gcd(a, b):
if b == 0:
return a
return gcd(b, a % b)
print(gcd(4, 8)) # Output: 4 |
null | Write a Python program to find the closest pair of points in a given set of points. | [[2, 3], [12, 30], [40, 50], [5, 1], [12, 10], [3, 4]] | import math
def closest_pair(points):
closest_pair = None
closest_distance = float('inf')
for i in range(len(points)):
for j in range(i + 1, len(points)):
distance = calc_distance(points[i], points[j])
if distance < closest_distance:
closest_distance = distance
closest_pair = (points[i], points[j])
return cl... |
null | What is the correct syntax to create a dictionary in Python? | my_dict = {'key1':'value1','key2':'value2'} | |
null | Extract only the digits from a given string using Python. | import re def extract_digits(string): regex = r"\D" return re.sub(regex, "", string) | |
null | Create a Python script to convert the given JSON object into an XML document. | { "username": "John123", "age": 23, "country": "USA" } | import xmltodict import json json_object = { "username": "John123", "age": 23, "country": "USA" } xml_message = xmltodict.unparse(json.loads(json.dumps(json_object)), pretty=True) print(xml_message) Output: <root> <username>John123</username> <age>23</age> <country>USA</country> </root> |
[CS Wikipedia] Albert Goodheir
Albert Goodheir (26. června 1912, Utrecht, Nizozemsko – 27. prosince 1995, Glasgow, Spojené království) byl skotský lékař, spisovatel, překladatel a esperantista. Dílo Vlastní dílo Merlo sur menhiro Fondita sur roko''' Nia kultura heredaĵo kaj esperanto Překlady D-ro Jekyll kaj S-ro Hyde... | null | null | null |
null | Write code in Python using PyTorch to predict the outcome of a binary classification problem. | Not applicable | import torch
import torch.nn as nn
# input data
X = torch.tensor([[0.5, 0.4], [0.7, 0.2], [0.3, 0.1], [0.6, 0.9]])
y = torch.tensor([0, 1, 0, 1])
# define the model
model = nn.Sequential(
nn.Linear(2, 1),
nn.Sigmoid())
# define the loss function and the optimization algorithm
criterion = nn.BCELoss... |
null | Create a program in Python to design and implement a knapsack problem. | n = 5, W = 8, weights = [2, 3, 4, 5, 6], values = [2, 5, 6, 12, 9] | def knapsack(n, W, weights, values):
# create a 2D array, dp[n+1][W+1], and fill with zeros
dp = [[0 for x in range(W+1)] for x in range(n+1)]
#iterating over array rows
for i in range(n+1):
#iterating over array columns
for w in range(W+1):
if i==0 or w==0 :
... |
null | Generate an array of 10 random numbers between 1 and 100 using Python | import random def generate_random_array(n): array= [] for _ in range(n): array.append(random.randint(1, 100)) return array print(generate_random_array(10)) // Output // [14, 20, 32, 84, 59, 45, 11, 34, 57, 19] | |
null | Create a list of all prime numbers from 1 to 1000 using Python. | # Create an empty list
prime_list = []
# loop 1 to 1000
for num in range(2,1001):
prime = True
for i in range(2,num):
if (num % i == 0):
prime = False
if prime:
prime_list.append(num)
print("Prime numbers from 1 to 1000 are:")
print(prime_list) | |
null | What is the purpose of using a data structure? | The purpose of using a data structure is to store, organize, and manipulate data quickly and effectively. By using an appropriate data structure depending on the type of data and the operations being performed, it is possible to make data processing efficient and improve the performance of the program. | |
null | Design a program in Python to detect the vowel in a given string. | Hello World | def vowelCheck(inputString):
vowels = ['a','e','i','o','u','A','E','I','O','U']
for x in inputString:
if x in vowels:
return x |
null | Generate a dictionary with 10 elements and display it. | dictionary = { 'A': 'Apple', 'B': 'Ball', 'C': 'Cat', 'D': 'Dog', 'E': 'Elephant', 'F': 'Fish', 'G': 'Goat', 'H': 'Horse', 'I': 'Ink', 'J': 'Jelly' } print(dictionary) | |
null | Find the sum of three numbers and add five to it. | a = 4, b = 7, c = 10 | sum = a + b + c result = sum + 5 |
null | Create a Python script that inputs an integer and prints "odd" if the number is odd, or "even" if the number is even. | def check_even_or_odd(num): if num % 2 == 0: print("even") else: print("odd") check_even_or_odd(5) # odd | |
null | Find the reverse of an array in Python. | arr = [1, 2, 3, 4, 5] | arr = [5, 4, 3, 2, 1] |
null | Write a Python program to generate a table of values for sin and cos functions between 0 and 10. | Not applicable | import math
def generate_table():
# headers
print ("angle (in degrees) sin(angle) cos(angle)")
# values
for angle in range(0, 370, 10):
print("{:7} {:15.4f} {:15.4f}".format(angle,math.sin(math.radians(angle)),math.cos(math.radians(angle))))
if __name__ == "__main__":
generate_table() |
null | Please generate a Python script that calculates the mean of a given array of numbers. | [4, 9, 3, 5] | def calculateMean(array):
# sum up all elements in the array
mean = 0
for i in range(len(array)):
mean += array[i]
# calculate the mean by dividing the sum by number of elements
mean /= len(array)
return mean
array = [4, 9, 3, 5]
mean = calculateMean(array)
print(mean) |
null | Write a Python script that takes a paragraph as input and prints the unique words in it. | This is a sample paragraph. | paragraph = "This is a sample paragraph."
# split the string into words
words = paragraph.split()
# sort the words alphabetically
words.sort()
# remove duplicates
unique_words = []
for word in words:
if word not in unique_words:
unique_words.append(word)
# print the unique words
print(", ".join(unique_w... |
[EN Wikipedia] 2010 Vegalta Sendai season
2010 Vegalta Sendai season. Competitions J. League 1 Emperor's Cup J. League Cup Player statistics Other pages J. League official site Vegalta Sendai Vegalta Sendai seasons | null | null | null |
null | Create a python script to detect a palindrome from a given string. | def is_palindrome(s):
s = s.lower()
return s == s[::-1] | |
null | Extract a character's count from a given string. | string = "this is a sample string" | def count_characters(string): '''This function takes a string as argument and returns a dictionary that contains the count of characters in the given string.''' # create an empty dictionary char_count = {} # iterate over the characters and add to dictionary if not already present for char in string: if char not in char... |
null | Create a function to delete a specific row from a table named 'Orders'. | Primary Key of the order: 1234 | def delete_row(table, order_key): query = 'DELETE FROM {} WHERE order_key = ?'.format(table) try: cursor.execute(query, (order_key,)) cursor.commit() except: cursor.rollback() print('Error occurred while deleting order') |
null | Change the given code so that the variable is incremented only if the condition returns true. | x = 0 if (condition): x += 1 | |
null | How would you create a for-loop in Python to iterate through all the integers from 1 to 10? | for i in range(1,11): print(i) | |
[DE Wikipedia] Oblast Russe
Die Oblast Russe () ist eine Verwaltungseinheit im Norden Bulgariens mit der gleichnamigen Stadt Russe als Verwaltungssitz. Die nördliche Grenze zu Rumänien wird durch den Verlauf der Donau gebildet. Auf 2.803 km² leben Einwohner. Verwaltungsgliederung Die Oblast Russe gliedert sich in acht... | null | null | null |
[CS Wikipedia] Vůz ARmpee832 ČD
{{DISPLAYTITLE:Vůz ARmpee832 ČD}} Vozy ARmpee832, číslované v intervalu 61 54 85-71, jsou řadou osobních vozů první třídy s barovým oddílem z vozového parku Českých drah. Všechny tyto vozy (001–006) vznikly v letech 2009–2010 modernizací pěti vozů řady BRm830 a jednoho vozu řady BRcm831... | null | null | null |
[EN Wikipedia] 1954 World Professional Match-play Championship
The 1954 World Professional Match-play Championship was a professional snooker tournament held from 5 October 1953 to 6 March 1954 across various locations in the British Isles. The final was held at Houldsworth Hall in Manchester, England. Fred Davis won ... | null | null | null |
null | Create a Python script to generate a random password with at least one uppercase, one lowercase and one number. | import string
import random
def generate_password():
letters = string.ascii_letters + string.digits
password = list(random.choice(letters) for i in range(8))
while not any(l.isupper() for l in password) or not any(l.islower() for l in password) or not any(l.isdigit() for l in password):
password = ... | |
null | Generate a Python class for an address book program. The class should contain methods for adding a new person's name, phone number and email, and editing an existing contact. | Not applicable | class AddressBook:
def __init__(self):
self.people = {}
def add_person(self, name):
self.people[name] = { 'phone': None, 'email': None }
def edit_person(self, name, phone=None, email=None):
person = self.people[name]
if phone:
person['phone'] = phone
if email:
person['email'] = email |
[HI Wikipedia] बार्बी रैपुन्ज़ेल
बार्बी रैपुन्ज़ेल (अंग्रेज़ी: Barbie as Rapunzel) एक २००२ प्रत्यक्ष-से-वीडियो कंप्यूटर एनिमेटेड फिल्म है। यह फिल्म 2 समग्र बार्बी फिल्म श्रृंखला में। इस बार्बी के रूप में केली शेरिडन की आवाज सुविधाएँ। हिंदी डबिंग संस्करण बार्बी के रूप में राजश्री नाथ सुविधाएँ। कहानी अनुकूलित है से ब्रद... | null | null | null |
null | Create a class that can represent a 2D coordinate system. | """ Create a class that can represent a 2D coordinate system """ class CoordinateSystem: def __init__(self,x,y): self.x = x self.y = y def add(self,other): x = self.x + other.x y = self.y + other.y return CoordinateSystem(x,y) if __name__ == '__main__': a = CoordinateSystem(1,2) b = CoordinateSystem(3,4) print(a.add(b)... | |
null | Train a recurrent neural network in Python to generate a text summary of a given article | The text of a news article about the US 2020 presidential election | import tensorflow as tf
from tensorflow.keras.layers import Input, Dense, Embedding, GRU, Dropout
def build_model(vocab_size, embedding_dim):
model = tf.keras.Sequential()
# Embedding layer
model.add(Embedding(vocab_size, embedding_dim, input_length=500))
# GRU layer
model.add(GRU(128, dropout=0.25... |
[HI Wikipedia] जिब्राल्टर आम चुनाव, 2011
जिब्राल्टर आम चुनाव ब्रिटिश प्रवासी शासित प्रदेश जिब्राल्टर में 8 दिसम्बर 2011 के दिन आयोजित हुए थे। चुनाव के अंदर दो दल (जिब्राल्टर सोशल डैमोक्रैट्स और प्रोग्रेसिव डैमोक्रेटिक पार्टी) तथा एक गठबंधन (जिब्राल्टर सोशलिस्ट लेबर पार्टी और जिब्राल्टर लिबरल पार्टी) ने अपने उम्मीदवार ... | null | null | null |
null | Write a Python function to calculate the maximum value of two numbers given by the user. | x = 24
y = 63 | def maximum_numbers(x, y):
if x > y:
return x
else:
return y
print(maximum_numbers(x, y)) |
[CS Wikipedia] Lusigny-sur-Barse
Lusigny-sur-Barse je francouzská obec v departementu Aube v regionu Grand Est. V roce 2010 zde žilo 1 755 obyvatel. Vývoj počtu obyvatel Související články Seznam obcí v departementu Aube Externí odkazy Reference Obce v departementu Aube | null | null | null |
null | Generate python code to encode a given string in base64. | string = 'This is a test string.' | def base64_encode(string):
encoded_string = base64.b64encode(string.encode('utf-8'))
return encoded_string.decode('utf-8') |
null | Optimize a program in Python for searching for a string in a list. | value = 'apple'
list = ['bannanas', 'oranges', 'apple'] | def search(value, list):
for i in range(len(list)):
if list[i] == value:
return i
return -1
value= 'apple'
list = ['bannanas', 'oranges', 'apple']
print(search(value, list)) |
null | Write a Ruby program to create a class called "Person" with variables such as name, age, gender, etc. | class Person attr_accessor :name, :age, :gender def initialize(name, age, gender) @name = name @age = age @gender = gender end end | |
null | Generate a query in SQL which can retrieve the maximum price for each product. | SELECT product_id, MAX(price) FROM product_table GROUP BY product_id; | |
[HI Wikipedia] महर्षि दयानन्द सरस्वती विश्वविद्यालय, अजमेर
महर्षि दयानन्द सरस्वती विश्वविद्यालय, अजमेर भारत का एक प्रमुख विश्वविद्यालय है। इसकी स्थापना १९८७ में हुई थी। 'नेशनल असेसमेण्ट ऐण्ड एक्रेडिशन काउन्सिल बंगलुरु' ने २००४ में इसे बी++ ग्रेड दिया था। लगभग २०० से अधिक महाविद्यालय इससे सम्बद्ध हैं। बाहरी कड़ियाँ महर... | null | null | null |
null | Write an SQL query to select all employees from department 1 having a salary greater than 50,000. | SELECT * FROM employees WHERE department = 1 AND salary > 50000; | |
null | Create a Python program to scramble a given string and return the scrambled version. | The string: "Hello World" | import random
def scrambleString(string):
# Split the string into a list
chars = list(string)
# Shuffle the list
random.shuffle(chars)
# Join the list to form the scrambled string
scrambled = "".join(chars)
return scrambled
# Create the string
string = "Hello World"
# Scramble the string
scrambled =... |
null | Create a HTML code to show a green square with a width of 100px and a height of 100px. | <div style="width:100px; height:100px; background-color:green"></div> | |
[DE Wikipedia] Liste der Monuments historiques in Marac
Die Liste der Monuments historiques in Marac führt die Monuments historiques in der französischen Gemeinde Marac auf. Liste der Immobilien |} Weblinks Marac Marac ! | null | null | null |
null | Implementation the quicksort algorithm using c++. | // C++ code for quick sort #include <bits/stdc++.h> using namespace std; // A utility function to swap two elements void swap(int* a, int* b) { int t = *a; *a = *b; *b = t; } /* This function takes last element as pivot, places the pivot element at its correct position in sorted array, and places all smaller (smaller t... | |
[DE Wikipedia] Kosch-Prinzip
Das Kosch-Prinzip (auch Kosh, Qosh, Qoʻsh, Kasch, Kash oder Qash geschrieben) ist ein städtebauliches Prinzip der Anordnung zweier repräsentativer Bauten in zentralasiatischen Städten. Der Name ist aus dem persischen Wort „Qash“ abgeleitet, das „gegenüber“ bedeutet. Anordnung Gemäß dem Kos... | null | null | null |
null | Develop a Java program to rotate a two-dimensional array clockwise by 90 degrees. | [[1, 2], [3, 4]] | public class RotateMatrix { public static void rotate(int[][] arr, int n) { for (int x = 0; x < n/2; x++) { for (int y = x; y < n-x-1; y++) { int temp = arr[x][y]; arr[x][y] = arr[y][n-1-x]; arr[y][n-1-x] = arr[n-1-x][n-1-y]; arr[n-1-x][n-1-y] = arr[n-1-y][x]; arr[n-1-y][x] = temp; } } } } |
null | Edit this Python program to make the output more accurate | def calculate_average(numbers):
total = 0
for n in numbers:
total += n
return float(total) / len(numbers) | def calculate_average(numbers):
total = 0
for n in numbers:
total += n
return float(total) / len(numbers) if len(numbers) > 0 else 0 |
[DE Wikipedia] Pfarrkirche Preding
Die römisch-katholische Pfarrkirche Preding steht auf einer Anhöhe in der Marktgemeinde Preding im Bezirk Deutschlandsberg in der Steiermark. Die auf die heilige Maria im Dorn geweihte Pfarrkirche und Wallfahrtskirche gehörte bis Ende August 2018 zum dann aufgelösten Dekanat Deutschl... | null | null | null |
null | Create a web application that allows users to search for movies and save their favorites. | """ Create a web application that allows users to search for movies and save their favorites """ # Import libraries import flask import sqlalchemy # Create Flask application app = flask.Flask(__name__) # Connect to database engine = sqlalchemy.create_engine('sqlite:///movies.db') # Define routes @app.route("/") def ind... | |
null | Generate a Python program to check if any element of a given list is palindrome or not. | list1 = [12, 121, 3] | list1 = [12, 121, 3]
# Iterate through the list
for element in list1:
# Convert the element to a string
element = str(element)
# Check if the element is a palindrome
if element == element[::-1]:
print(element + " is a palindrome")
else:
print(element + " is not a palindrome") |
null | Construct an SQL query to select the total number of employees in the table 'Employees'. | SELECT COUNT(*) FROM Employees; | |
null | Translate the following JSON into an XML format. | { "person": { "name": "Jane", "age": 30 } } | <?xml version="1.0"?> <person> <name>Jane</name> <age>30</age> </person> |
null | Create a Python program to process raw customer data into a summary report. | Raw Customer Data (JSON):
[
{
"customer_name": "John Doe",
"total_amount_spent": 2000
},
{
"customer_name": "Jane Doe",
"total_amount_spent": 800
},
{
"customer_name": "Joe Smith",
"total_amount_spent": 200
}
] | import json
raw_data = [
{
"customer_name": "John Doe",
"total_amount_spent": 2000
},
{
"customer_name": "Jane Doe",
"total_amount_spent": 800
},
{
"customer_name": "Joe Smith",
"total_amount_spent": 200
}
]
# calculate total amount spent
total_amount_spent = 0
for customer in raw_data:
total_amoun... |
[HI Wikipedia] दिलदार नगर जंक्शन
दिलदार नगर जंक्शन भारत के उत्तर प्रदेश राज्य के नगर दिलदार नगर में स्थित उत्तर पूर्व रेलवे की पूर्व रेलवे शाखा के अन्तर्गत आने वाला रेलवे स्टेशन है। दिलदार नगर में अन्य स्टेशन दिलदार नगर उत्तर प्रदेश में रेलवे स्टेशन | null | null | null |
null | Write a class to represent a point in a 2-D plane. | class Point: def __init__(self, x_coordinate, y_coordinate): self.x = x_coordinate self.y = y_coordinate def get_x(self): return self.x def get_y(self): return self.y def set_x(self, x_coordinate): self.x = x_coordinate def set_y(self, y_coordinate): self.y = y_coordinate def distance(self, other_point): x_diff_sq = (s... | |
[CS Wikipedia] Timmy Trumpet
Timmy Trumpet vlastním jménem Timothy Jude Smith (* 9. června 1982, Sydney) je australský DJ a hudební producent. Jeho popularita v posledních letech rychle roste, zatímco v roce 2016 se v anketě TOP 100 DJs magazínu DJ mag, kde lidé hlasují o svých nejoblíbenějších DJs, umístil na 75. mís... | null | null | null |
null | Compare this object-oriented code in Python to the same code written in Java. | class Car:
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
self.odometer_reading = 0
def get_make_and_model(self):
return f'{self.make} {self.model}' | // Java code
public class Car {
private String make;
private String model;
private int year;
private int odometerReading;
public Car(String make, String model, int year) {
this.make = make;
this.model = model;
this.year = year;
this.odometerReading = 0;
}
pu... |
null | Create a Python program that implements a search algorithm (e.g. binary search, linear search). | Array: [1, 3, 4, 6, 8, 9, 11, 12, 14]
Target: 11 | def linear_search(arr, target):
for i in range(len(arr)):
if arr[i] == target:
return i
return -1
arr = [1, 3, 4, 6, 8, 9, 11, 12, 14]
target = 11
result = linear_search(arr, target)
if result == -1:
print('Element not found')
else:
print(f'Element found at index {result}')
Output:
Element found at index 6 |
null | Edit the following HTML code to enable a toggle to show and hide a DIV element when a button is clicked. | <div> <button>Toggle</button> <p>This is a text paragraph.</p> </div> | <div> <button onclick="toggleFunction()">Toggle</button> <p>This is a text paragraph.</p> <div id="myDIV" style="display:none;"> <p>This is the toggleable content.</p> </div> <script> function toggleFunction() { let x = document.getElementById("myDIV"); if (x.style.display === "none") { x.style.display = "block"; } els... |
[EN Wikipedia] Anglo-French War (1213–1214)
The Anglo-French War was a major medieval conflict that pitted the Kingdom of France against the Kingdom of England and various other states. It was fought in an attempt to curb the rising power of King Philip II of France and regain the Angevin continental possessions King ... | null | null | null |
null | Write a function in Python to generate a random password of 8 characters. | import random, string
def random_password(length):
chars = string.ascii_letters + string.digits + '!@#$%^&*()'
random_password = ''.join(random.choice(chars) for i in range(length))
return random_password
print(random_password(8)) | |
null | Write a Python program to print out the list of even numbers from 0 to given limit. | limit = 10 | # declare list of numbers numbers = [x for x in range(0, limit+1)] # declare empty list of even numbers even_numbers = [] # loop through list of numbers for num in numbers: # if number is even, append to even_numbers list if num % 2 == 0: even_numbers.append(num) # print even numbers print(even_numbers) # Output: [0, 2... |
[HI Wikipedia] गंजाम
गंजाम (Ganjam) भारत के ओड़िशा राज्य के गंजाम ज़िले में स्थित एक नगर है। यह ज़िले का मुख्यालय नहीं है और ज़िला मुख्यालय छत्रपुर में है। गंजाम से राष्ट्रीय राजमार्ग 16 गुज़रता है। शहर से कुछ दूर पूर्व में बंगाल की खाड़ी का तट है। जनसांख्यिकी भारत की जनगणना २०११ के अनुसार पालिका क्षेत्र की जनसंख्या १... | null | null | null |
null | Write a C# program to filter the entities from a given array. | Array = [0, "Apple", 1, "Orange", 2, "Banana", 3, "Mango"]. Condition = Entity should be a number | int[] entities = Array.OfType<int>().ToArray(); |
null | Create a C++ program to generate a multiplication table of size n x n. | <n = 3> | #include <iostream> using namespace std; int main() { int n = 3; for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) cout << i * j << " "; cout << endl; } return 0; } |
null | What is a dynamic programming algorithm? | Dynamic programming is an algorithm design technique that is used to solve optimization problems by breaking them down into smaller subproblems. It enables you to solve a problem by combining solutions to similar subproblems, saving time and often being more efficient than standard methods. It is widely used in operati... | |
null | Find the logarithm (base 10) of a number. | 1000 | 3.0 |
null | Create a program in C++ to find the max and min of an array of fixed size. | array = [3, 5, 8, 6, 10, 1] | #include <iostream> using namespace std; // Function to find maximum and minimum of an array void minMax(int arr[], int n) { int max = arr[0]; int min = arr[0]; for (int i = 1; i < n; i++) { if (arr[i] > max) max = arr[i]; if (arr[i] < min) min = arr[i]; } cout << "Maximum element = " << max << endl; cout << "Minimum e... |
null | From the given data set, calculate the mean and print it out. | [1, 2, 3, 4, 5] | data_set = [1, 2, 3, 4, 5] mean = sum(data_set) / len(data_set) print("The mean is {}".format(mean)) |
[DE Wikipedia] Onken
Die Onken GmbH ist ein 1940 von Hermann Onken gegründeter deutscher Hersteller von Molkereiprodukten mit Sitz in Moers. Seit 2011 gehört die Marke Onken zur Schweizer Milchverarbeiterin Emmi. Geschichte 1940 übernahm Hermann Onken die An- und Verkaufsgenossenschaft vereinigter Milchproduzenten in ... | null | null | null |
[EN Wikipedia] Tokanui River
The Tokanui River is a river in New Zealand, flowing into Toetoes Bay. See also List of rivers of New Zealand References Rivers of Southland, New Zealand Foveaux Strait Rivers of New Zealand | null | null | null |
null | How can we use the reduce() function in JavaScript to find the sum of an array of numbers? | const numbers = [10, 20, 30] const sum = numbers.reduce((acc, val) => acc + val, 0) console.log(sum) | |
null | Create a React component that displays the current day of the week and date. | import React from "react"; const Date = () => { const today = new Date(); const currentDay = today.getDay(); const dayList = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]; return ( <div> {dayList[currentDay]}, {today.getFullYear()}/{today.getMonth()+1}/{today.getDate()} </div> ); }; exp... | |
null | Create a for-loop in JavaScript that iterates through numbers from 1 to 10 and prints out the current number. | for (let i = 1; i <= 10; i++) { console.log(i); } | |
null | Generate Python code to find numbers that are multiples of both 3 and 5 between 0 and 100. | Not applicable | # List of numbers which are multiples of both 3 and 5 between 0 and 100
multiples_3_5 = []
# Iterate over all numbers between 0 and 100
for num in range(101):
# Check for multiples of both 3 and 5
if num % 3 == 0 and num % 5 == 0:
multiples_3_5.append(num)
print(multiples_3_5) |
null | Write a SQL query to select all the books written by a specific author. | author: "Robert Louis Stevenson" | SELECT * FROM books WHERE author = "Robert Louis Stevenson" |
[CS Wikipedia] Těleso
Těleso je, ve fyzice či mechanice, obecný hmotný živý či neživý předmět, který je objektem zkoumání fyziky, resp. mechaniky. Vyplňuje daným způsobem určitou část objemu prostoru, která je nějakým způsobem ohraničena a která obsahuje látku daného skupenství. Těleso má na rozdíl od látky tvar, rozm... | null | null | null |
null | Create a Ruby class for a customer and add attributes for name, age and address. | class Customer attr_accessor :name, :age, :address def initialize(name, age, address) @name = name @age = age @address = address end end | |
null | Create a Python class called Car with properties for make, model, year, color and fuel type. | Not applicable | class Car:
def __init__(self, make, model, year, color, fuel):
self.make = make
self.model = model
self.year = year
self.color = color
self.fuel = fuel
def get_make(self):
return self.make
def get_model(self):
return self.model
def get_year(self):
return self.year
... |
null | Create an API endpoint for a Python Flask application that takes a string as an input and returns the frequency of all the words that appear in the given string. | String: "Hello world, hello again world!" | from flask import Flask, request
from collections import Counter
app = Flask(name)
@app.route('/word-frequency', methods=['POST'])
def word_frequency():
string = request.json['string']
counts = Counter(string.split())
return {'frequency': counts}
if name == 'main':
app.run(debug=True) |
null | Write a Python script to classify a given article into one of the following categories: 'Politics', 'Technology', 'Social'. | "The company announced a range of new innovative technologies to help combat climate change." | from sklearn.naive_bayes import MultinomialNB
from sklearn.feature_extraction.text import CountVectorizer
article = "The company announced a range of new innovative technologies to help combat climate change."
text = [article]
cv = CountVectorizer()
X = cv.fit_transform(text)
clf = MultinomialNB()
clf.fit(X, ['Techn... |
[HI Wikipedia] सैमसंग गैलेक्सी टैब
सैमसंग गैलेक्सी टैब एन्ड्रॉइड् आधारित टैबलेट कंप्यूटरों की शृंख्ला है जिसके निर्माता सैमसंग हैं। शृंख्ला का पहला प्रादर्श, 7 इंच सैमसंग गैलेक्सी टैब, 2 सितंबर 2010 को आईएफ़ए बर्लिन में विमोचित हुआ था। तब से लेकर कई प्रादर्श जारी किये जा चुके हैं, इनमें 7.7, 8.9 तथा 10.1 इंच डिस्प्ले ... | null | null | null |
null | Estimate the value of pi to four decimal places. | The estimated value of pi is 3.1416. | |
[HI Wikipedia] गॉथिक वास्तुकला
गॉथिक वास्तुकला (Gothic architecture) वास्तुकला की एक शैली है जो यूरोप में उत्तर मध्यकाल में प्रचलित थी। गॉथिक शैली 'रोमनेस्क वास्तुकला' से जन्मी। यह शैली फ्रांस में १२वीं शती में जन्मी तथा १६वीं शती तक प्रचलित रही। उस काल में इसे 'फ्रांसीसी कर्म' (Opus Francigenum) कहा जाता था। 'गॉथिक' ... | null | null | null |
null | Create a program to detect a palindrome in a given sentence using Python. | Not applicable | import re
def hasPalindrome(sentence):
words = sentence.split(' ')
for word in words:
if word == word[::-1]:
return True
return False
def isPalindrome(sentence):
sentence = re.sub('\W+', '', sentence.lower())
return sentence == sentence[::-1]
if __name__ == '__main__':
sentence = 'A man, a plan, a canal,... |
[EN Wikipedia] The Neuroscientist
The Neuroscientist is a peer-reviewed academic journal that publishes papers in the field of Neurology and Neuroscience. The journal's editor is Stephen G Waxman (Yale University). It has been in publication since 1995 and is currently published by SAGE Publications. Scope The Neurosc... | null | null | null |
[EN Wikipedia] Frankfurter Würstchen
A Frankfurter Würstchen (Frankfurt sausage) is a thin parboiled sausage in a casing of sheep's intestine. The flavor is acquired by a method of low temperature smoking. For consumption, Frankfurters are occasionally not boiled; they are heated in hot water for only about eight minu... | null | null | null |
null | Write an algorithm in Python that takes as input an array of numbers and returns the maximum element. | [15, 25, 7, 1] | def maxElement(arr):
maxElement = arr[0];
for i in range(1, len(arr)):
if maxElement < arr[i]:
maxElement = arr[i];
return maxElement;
arr = [15, 25, 7, 1];
maxElement = maxElement(arr);
print ("Maximum element in the array is:", maxElement); |
null | Design a python code to build a web application using Django's MVC framework. | # Importing essential libraries
import os
import sys
# start a new Django project
from django.core.management import execute_from_command_line
# check the requirements.txt file to get the list of libraries
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "my_app.settings")
try:
... | |
null | Generate a Python function to generate an equation with given coefficients and variables. | coefficients: [2, 3, 1], variables: ["x", "y", "z"] | def generate_equation(coefficients, variables):
equation = ""
for i, coeff in enumerate(coefficients):
equation += str(coeff) + variables[i] + " + "
equation = equation[:-3]
return equation |
null | Create a web crawler written in Python that scrapes hotel reviews from an online travel website. | Not applicable | import requests
from bs4 import BeautifulSoup
def scraper(url):
response = requests.get(url)
html = response.content
soup = BeautifulSoup(html, 'lxml')
reviews_container = soup.find_all('div', class_='review_container')
reviews = []
for review in reviews_container:
rating = review.find('span', attr... |
null | Use a SQL query to extract all the rows from the table "Employees" that includes employees with the last name Smith. | SELECT * FROM Employees WHERE last_name = 'Smith' | |
[DE Wikipedia] Elbląg (Fluss)
Der Elbląg () ist ein 14,5 Kilometer langer Fluss in der polnischen Woiwodschaft Ermland-Masuren, der durch die Stadt Elbląg () fließt. Der Elbląg entwässert den Druzno () und mündet in das Frische Haff () und damit in die Ostsee. Er ist auf seiner gesamten Länge schiffbar und verbindet a... | null | null | null |
null | Optimize the following Python code for counting the number of vowels in a string. | def count_vowels(str):
count = 0
vowels = ["a", "e", "i", "o", "u"]
for i in str:
if i in vowels:
count += 1
return count | def count_vowels(str):
count = 0
vowels = set("aeiou")
for i in str:
if i in vowels:
count += 1
return count |
null | Create a Java program to find the max number within a list. | public static int findMax(int[] array) { int max = array[0]; for (int i = 0; i < array.length; i++) { if (array[i] > max) { max = array[i]; } } return max; } | |
[EN Wikipedia] Articles of Confederation
The Articles of Confederation and Perpetual Union was an agreement among the 13 states of the United States, formerly the Thirteen Colonies, that served as the nation's first frame of government. It was debated by the Second Continental Congress at Independence Hall in Philadel... | null | null | null |
null | Construct a query in PostgreSQL to find the names and emails of all users who have "google.com" in their emails. | SELECT name, email FROM users WHERE email LIKES '%google.com%'; | |
null | Create a JavaScript function to validate an email address with the following conditions. | function validateEmail(email) { const 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); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.