text stringlengths 141 2.89k ⌀ | instruction stringlengths 19 1.5k ⌀ | input stringlengths 0 800 ⌀ | output stringlengths 1 2.5k ⌀ |
|---|---|---|---|
null | Create a numerical sequence using Ruby code with 4 elements. | [1, 2, 4, 8] | |
null | Create a new list that is the combination of two other given lists. | list_a = ["A", "B", "C"] list_b = [1, 2, 3] | new_list = ["A", "B", "C", 1, 2, 3] |
[CS Wikipedia] Kyselina m-chlorperoxybenzoová
Kyselina meta-chlorperoxybenzoová (též kyselina m-chlorperoxybenzoová) je karboxylová peroxokyselina často používaná v organické syntéze jako oxidační činidlo. Obvykle se upřednostňuje před ostatními peroxokyselinami, protože se snáze skladuje. Mezi hlavní způsoby jejího p... | null | null | null |
null | Create a PHP code to check if an array contains a given item. | $input_array = array(1,2,3,4,5); $item_to_check = 3; | <?php $input_array = array(1,2,3,4,5); $item_to_check = 3; if(in_array($item_to_check, $input_array)) { echo "Array contains the given item."; } else { echo "Array doesn't contain the given item."; } ?> |
[CS Wikipedia] Symplektická varieta
Symplektická varieta je pojem z matematiky, přesněji z diferenciální geometrie. Formalizuje v rámci matematiky fyzikální pojem fázového prostoru. Definice Dvojici nazveme symplektická varieta, pokud je (hladká) varieta a je tzv. symplektická diferenciální forma na , tj. pro každé je... | null | null | null |
null | Build a linear regression model using python. | import pandas as pd
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error
# Read data
data = pd.read_csv('data.csv')
X = data[['x']]
y = data['y']
# Create a linear regression model
model = LinearRegression()
model.fit(X,y)
# Make predictions
predictions = model.predict(X... | |
null | Create a Python class that encodes a given number using the Base58 algorithm. | number = 123456789 | class Base58Encoder: '''This class encodes numbers using the Base58 algorithm''' def __init__(self,number): self.number = number def encode(self): encoded = "" alphabet = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" while self.number > 0: remainder = self.number % 58 self.number = self.number // 58 enco... |
[DE Wikipedia] Rainer Schumann
Rainer Schumann (* 5. Mai 1964 in Hannover) ist ein deutscher Schlagzeuger und ist Mitglied der Rockband Fury in the Slaughterhouse. Leben 1987 gründete Schumann zusammen mit den Brüdern Kai und Thorsten Wingenfelder, Christof Stein-Schneider und Hannes Schäfer die Rockband Fury in the S... | null | null | null |
null | Code a program in Python to calculate the mean from a dataset | [0.07, 0.69, 0.29, 0.17, 0.11, 0.51, 0.5] | def calculate_mean(numbers):
total = 0
for num in numbers:
total += num
return total / len(numbers)
dataset = [0.07, 0.69, 0.29, 0.17, 0.11, 0.51, 0.5]
mean = calculate_mean(dataset)
print(mean) # Output: 0.3542857142857143 |
[HI Wikipedia] ऋग्वेद
सनातन धर्म का सबसे आरम्भिक स्रोत है। इसमें १० मण्डल, १०२८ सूक्त और वर्तमान में १०,४६२ मन्त्र हैं, मन्त्र संख्या के विषय में विद्वानों में कुछ मतभेद है। मन्त्रों में देवताओं की स्तुति की गयी है। इसमें देवताओं का यज्ञ में आह्वान करने के लिये मन्त्र हैं। यही सर्वप्रथम वेद है। ऋग्वेद को इतिहासकार हिन... | null | null | null |
null | Compare two objects and return 0 if the objects are equal, greater than 0 if the first object is larger, and less than 0 if the second object is larger. | Object 1 - [name: John, age: 30] Object 2 - [name: Jane, age: 28] | int compareObjects(Object obj1, Object obj2) { if (obj1.name == obj2.name) { return obj1.age - obj2.age; } else { return obj1.name.compareTo(obj2.name); } } |
[CS Wikipedia] Thérèse Schwartze
Thérèse Schwartze (20. prosince 1851, Amsterdam – 23. prosince 1918, Amsterdam) byla nizozemská malířka a litografka. Převážnou část její tvorby tvoří portréty. Život Mládí a studia Narodila se do umělecké rodiny, její otec Johann Georg Schwartze byl malíř a byl prvním, kdo jí dával le... | null | null | null |
null | Write an SQL query to count the number of records with age greater than 25 from a given table. | SELECT COUNT(*) FROM table WHERE age > 25; | |
null | Can you create a program for web scraping using Python? | import requests
from bs4 import BeautifulSoup
# Send a request to the URL
res = requests.get("https://www.example.com")
# Parse the response
soup = BeautifulSoup(res.text, 'html.parser')
# Extract the data
data = soup.find_all('div') | |
[HI Wikipedia] पाकिस्तान
इस्लामी जम्हूरिया पाकिस्तान () या पाकिस्तान इस्लामी गणतंत्र या सिर्फ पाकिस्तान भारत के पश्चिम में स्थित एक इस्लामी गणराज्य है। 21 करोड़ की आबादी के साथ ये दुनिया का पाँचवी बड़ी आबादी वाला देश है। पाकिस्तान में दुनिया की दूसरी सबसे बड़ी मुस्लिम आबादी है। यह 8,81,913 वर्ग किलोमीटर (3,40,509 वर्ग... | null | null | null |
null | Rewrite the following code in Python to print a 5x5 matrix of random integers between 0 and 4. | Not applicable | import numpy as np
x = np.random.randint(0,5,(5,5))
print(x) |
null | Using PHP, write a program to check if a string contains only alphabets. | <?php function checkAlphabetical($str) { $len = strlen($str); // Traverse the given string, check // for every character for ($i = 0; $i < $len; $i++) { // If the string contains any // non-alphabetical character if((ord($str[$i]) > 64 && ord($str[$i]) < 91) || (ord($str[$i]) > 96 && ord($str[$i]) < 123)) { return true... | |
null | Write a function to generate the nth Fibonacci number. | < noinput > | def fib(n): if n == 0: return 0 elif n == 1: return 1 else: return fib(n-2) + fib(n-1) |
null | Determine whether a given string is a palindrome using stack data structure. | string = "racecar" | """ Determine whether a given string is a palindrome using stack data structure. """ def is_palindrome(string): # reverse the string stack = [] for char in string: stack.append(char) rev_string = "" while stack: rev_string = rev_string + stack.pop() # compare reversed string with original string if rev_string == string... |
null | Generate an HTML page to display text | The text to be displayed: "Hello World" | <html> <head> <title>Hello World</title> </head> <body> <h1>Hello World</h1> </body> </html> |
[HI Wikipedia] बिर्ख खड़का डुबर्सेली
'बिर्ख खड़का डुबर्सेली का जन्म 1 अक्तूवर 1954 को कटलगुड़ी, जलपाईगुड़ी (डुवर्स) पश्चिम बंगाल में हुआ था। ये हिन्दी और नेपाली के समानान्तर लेखक व अनुवादक हैं। सन्दर्भ नेपाली साहित्यकार 1954 में जन्मे लोग जीवित लोग | null | null | null |
null | Summarize the given article using the Gensim summarizer. | [Article about Gensim summarizer](https://gensim.readthedocs.io/en/latest/summarization.html) | Gensim summarizer uses text preprocessing, tokenization, and summarization to generate extracted summaries from the given text. It supports manual summarization, latent semantic analysis, Latent Dirichlet Allocation, baseline summarization, and phrases-based summarization. Gensim summarizer provides a variety of ways t... |
null | Write Python code to find the maximum distance between two elements in a given array | x = [2, 4, 8, 11, 13, 18, 19, 21] | def maxdistance(x):
# Initialize max distance
max_distance = 0
for i in range(0, len(x)):
for j in range(i + 1, len(x)):
# Find the current distance between two elements
d = abs(x[i] - x[j])
# Update the maximum distance
if max_distance < d:
... |
null | Write a Python program for calculating the sum of a given array of numbers. | [2, 3, 4, 5] | def calculateSum(arr): sum = 0 for num in arr: sum += num return sum print(calculateSum([2, 3, 4, 5])) |
null | Create a Python program that shuffles the elements of an array. | arr = ["A", "B", "C", "D"] | import random
def shuffleArray(arr):
n = len(arr)
for i in range(n-1, 0, -1):
j = random.randint(0, i)
arr[i], arr[j] = arr[j], arr[i]
return arr
arr = ["A", "B", "C", "D"]
shuffleArray(arr)
print(arr) |
null | Write a code snippet to replace the given character in a string with another given character. | str = "This is a string" old_char = 's' new_char = 'x' | str = str.replace(old_char, new_char) |
[CS Wikipedia] Pascal (jednotka)
Pascal (značka Pa) je jednotka tlaku. Udává, jak velká síla (v newtonech) působí na jednotkovou plochu (1 m²), tzn. je ekvivalentní N/m² nebo také kg·m−1·s−2. Jednotka byla pojmenována po francouzském matematikovi a fyzikovi Blaise Pascalovi (1623–1662). Hektopascal (hPa) je jednotka, ... | null | null | null |
null | Write a python program to calculate the longest increasing subsequence of an array. | def longest_increasing_subsequence(arr):
n = len(arr)
# Declare the list (array) for LIS and
# initialize LIS values for all indexes
lis = [1]*n
# Compute optimized LIS values in bottom up manner
for i in range (1 , n):
for j in range(0 , i):
if arr[i] > arr[j] ... | |
null | Write a Pub/Sub program in Python for a simple chatroom application. | Not applicable | import zmq
import sys
import threading
# define constants
HOST = "127.0.0.1"
PORT = 6680
context = zmq.Context()
# Socket 1
pub = context.socket(zmq.PUB)
pub.bind("tcp://%s:%s" % (HOST, PORT))
# Socket 2
sub = context.socket(zmq.SUB)
sub.connect("tcp://%s:%s" % (HOST, PORT))
sub.setsockopt_string(zmq.SUBSCRIBE, ''... |
[CS Wikipedia] Somatochlora
Somatochlora je rod vážek z čeledi lesklicovitých. Česky je rod pojmenovaný lesklice, stejně jako rody Antipodochlora, Cordulia, Epitheca a Oxygastra. Na celém světě existuje asi 42 druhů tohoto rodu. V Česku se vyskytují 4 druhy, lesklice horská, lesklice jižní, lesklice severská, lesklice... | null | null | null |
[HI Wikipedia] खेरवाड़ा तहसील
खेरवाड़ा तहसील भारत के राजस्थान राज्य के उदयपुर जिले की एक तहसील है। जनसांख्यिकी 2011 के सेन्सस अनुसार तहसील की कुल जनसँख्या 206777 है जिसमें से 7581 शहरी है व 199196 ग्रामीण है। सन्दर्भ उदयपुर जिले की तहसीलें | null | null | null |
null | Create a selector for a page element with the id "main-heading". | const mainHeading = document.getElementById('main-heading'); | |
null | Create a function in Python that takes a list and returns the first two elements that adds up to 0. | [1, 5, 2, -7, 3] | def zero_sum_pair(list): # loop through the list for i in range(len(list)): for j in range(i + 1, len(list)): if list[i] + list[j] == 0: return [list[i], list[j]] return None |
null | Create a Python program to predict the sentiment of user reviews using a Naive Bayes classifier. | User Reviews:
1. 'The food was amazing!'
2. 'I was not happy with the customer service.'
3. 'The quality of the food was fantastic!' | import nltk
from nltk.classify import NaiveBayesClassifier
# Define the training set
reviews_train = [('The food was amazing!', 'positive'),
('I was not happy with the customer service.', 'negative'),
('The quality of the food was fantastic!', 'positive')]
# Train Naive Bayes Classifier
classifier = NaiveBayesClass... |
null | Create a function in Python to calculate the power of a number. | def power(num, pow):
return num**pow | |
null | Calculate the maximum sum of a subarray of length k. | Array: [1, 3, 4, 5, 20, 32] K: 3 | The maximum sum of a subarray of length 3 is 51 (20 + 5 +26). |
null | Develop a Python program to calculate the largest sum of a consecutive sequence of n numbers given in an array. | array = [1, 2, -5, 4, 5, 7, -8] | def max_consecutive_sum(array):
max_val = 0
cur_man = 0
for x in array:
cur_man = max(cur_man + x, 0)
max_val = max(cur_man, max_val)
return max_val |
null | Build a Python command-line program that takes in a string and encrypts it with a password. | import hashlib
def encrypt_string(string, password):
md5_string = hashlib.md5(string.encode()).hexdigest()
password_string = hashlib.md5(password.encode()).hexdigest()
result = ""
for i in range(32):
result += md5_string[i] + password_string[i]
return result
string = "Hello World!"
pas... | |
null | Suggest a SQL query to get the average order total from last year's orders. | SELECT AVG(total) FROM orders WHERE YEAR(order_date) = YEAR(CURDATE()) - 1 | |
null | Generate a complete python code to print the output shown. | I love Python | print("I love Python") |
null | Create a basic HTML form with two text inputs, one for email and one for a password. | <form> <input type="email" name="email" placeholder="Email" /> <input type="password" name="password" placeholder="Password" /> <input type="submit" value="Submit" /> </form> | |
null | Generate a function in Python to compute the maximum of two numbers without using any comparison operator. | def maximum(x, y):
# subtract two numbers
# and return the sign of the result
s = (x - y) >> 63
# return x if s = 0
# else return y
return x - s * (x - y) | |
[CS Wikipedia] Historie esperanta
Historie esperanta začíná nápadem Ludvíka Lazara Zamenhofa na vytvoření mezinárodního jazyka. Vznik esperanta Zamenhof se narodil se v Bělostoku, v městě národnostně velmi smíšeném. Obyvatelstvo žilo ve stálém nepřátelství, společenské a národnostní rozbroje byly na denním pořádku. To... | null | null | null |
null | Implement a recursive method to find the sum of all numbers from 1 to n. The method should take an integer n as its argument. | 4 | def sumNums(n): if n == 0: return 0 else: return n + sumNums(n-1) # Driver Code n = 4 print(sumNums(n)) |
null | Given a two-dimensional array, write a code to sum the values in each row. | A = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] | row_sum = [] for row in A: row_sum.append(sum(row)) print(row_sum) # prints [6, 15, 24] |
[CS Wikipedia] Canon EOS M
Canon EOS M je první bezzrcadlovka systému EOS společnosti Canon. Podle periodika DPReview se jedná de facto o lehčí verzi zrcadlovky Canon EOS 650D. Design Fotoaparát má 18megapixelový senzor typu CMOS velikosti 22,3 × 14,9 mm (APS-C), závit pro objektivy EF-M (na nějž jdou i typy EF a EF-S... | null | null | null |
[DE Wikipedia] Leonhard Horowski
Leonhard Horowski (* 1972 in Berlin) ist ein deutscher Historiker, Buchautor und Publizist. Über Fachkreise hinaus bekannt wurde er 2017 mit seinem Buch Das Europa der Könige über die höfische Gesellschaft des 17. und 18. Jahrhunderts, das für den Sachbuchpreis der Leipziger Buchmesse ... | null | null | null |
[EN Wikipedia] Kęstutis Andziulis
Kęstutis Andziulis (born January 20, 1948, in Jieznas) is a Lithuanian artist and art restorer. Life In 1973 he graduated from the Lithuanian Art Institute. Since 1973, he has contributed to the restoration of cultural monuments in Vilnius and since 1981, a Kaunas artist. In 1978, he ... | null | null | null |
null | Develop a Python program which will take a string and print out the total number of characters in it. | def num_chars(string):
char_count = 0
for i in string:
char_count += 1
print("The number of characters in the string is", char_count) | |
null | Write an array filter to remove any element with the value 0. | [0,1,2,3,4,0,6] | const result = arr.filter(item => item !== 0); // result will be [1,2,3,4,6] |
null | Use the input to generate a loop in JavaScript to print an increasing count starting from the given number. | num = 5 | for (let i = num; i < num + 10; i++) { console.log(i); } # Output # 5 # 6 # 7 # 8 # 9 # 10 # 11 # 12 # 13 # 14 |
null | Write a function to find the path from a source point to a destination point in a given 2D array. | Array: [[0, 1, 0, 0, 0], [0, 1, 0, 1, 0], [1, 0, 0, 1, 0], [0, 0, 0, 1, 0]] Source Point: [0, 0] Destination Point: [3, 4] | def find_path(array, source, dest): path = [source] sx, sy = source while path[-1] != dest: dx, dy = path[-1] if dx > 0 and array[dx - 1][dy] == 0: path.append([dx-1, dy]) elif dy > 0 and array[dx][dy-1] == 0: path.append([dx, dy-1]) elif dx < len(array)-1 and array[dx + 1][dy] == 0: path.append([dx+1, dy]) elif dy < l... |
null | Create a program which calculates the median of an array. | [3, 5, 4, 1, 7] | """ Create a program which calculates the median of an array """ def median(arr): n = len(arr) arr.sort() if n % 2 == 0: return (arr[n//2] + arr[n//2-1])/2 else: return arr[n//2] if __name__ == '__main__': print(median([3, 5, 4, 1, 7])) |
[EN Wikipedia] Gmina Magnuszew
Gmina Magnuszew is a rural gmina (administrative district) in Kozienice County, Masovian Voivodeship, in east-central Poland. Its seat is the village of Magnuszew, which lies approximately north-west of Kozienice and south-east of Warsaw. The gmina covers an area of , and as of 2006 its ... | null | null | null |
null | Develop an algorithm to sort a list of numbers from low to high inPython. | [5, 7, 1, 6, 10, 4, 2] | def sort_numbers(nums):
for i in range(len(nums)):
for j in range(i+1, len(nums)):
if nums[i] > nums[j]:
temp = nums[j]
nums[j] = nums[i]
nums[i] = temp
return nums
print(sort_numbers([5, 7, 1, 6, 10, 4, 2])) |
null | Write a JavaScript code to pop up a window that says "Hello, World!" when you open up the webpage. | <script> window.onload = function(){ alert("Hello, World!"); } </script> | |
[EN Wikipedia] Arvydas Bagdžius
Arvydas Bagdžius (23 November 1958, in Vilnius, Lithuania – 2 June 2008) was a Lithuanian painter. See also List of Lithuanian painters References 1958 births 2008 deaths Artists from Vilnius 20th-century Lithuanian painters | null | null | null |
null | Write a script for filtering out records who are older than 18 years old. | [ { "name": "John Doe", "age": 20 }, { "name": "Jane Smith", "age": 16 }, { "name": "Dan Roberts", "age": 25 } ] | const data = [ { "name": "John Doe", "age": 20 }, { "name": "Jane Smith", "age": 16 }, { "name": "Dan Roberts", "age": 25 } ]; let filteredRecords = data.filter(record => { return record.age > 18; }); console.log(filteredRecords); |
null | Create a Python loop that iterates for 10 times. | for i in range(10): ... | |
null | Calculate the mean of the following list of numbers: 4, 6, 8, 10. | mean = (4 + 6 + 8 + 10) / 4 = 7.5 | |
null | Write a Python program to generate a random integer between 0 and 9. | """
Generate a random integer between 0 and 9
"""
import random
def generate_random_integer():
# Generate a random number in the range [0, 9]
x = random.randint(0,9)
return x
if __name__ == '__main__':
print(generate_random_integer()) | |
null | Design a program using Python to scrape data from a website. | The target website is https://www.amazon.com/. | import requests
from bs4 import BeautifulSoup
URL = 'https://www.amazon.com/'
page = requests.get(URL)
soup = BeautifulSoup(page.content, 'html.parser')
#find all products
products = soup.find_all('span', class_ = 'a-size-medium a-color-base a-text-normal')
# iterate through products
for product in products:
# ... |
[EN Wikipedia] Acir Gurgacz
Acir Marcos Gurgacz (born February 5, 1962) is a Brazilian politician and journalist. He has represented Rondônia in the Federal Senate since 2009. He is a member of the Democratic Labour Party. References Living people 1962 births Brazilian people of Polish descent Members of the Federal S... | null | null | null |
null | Write a C program to implement a simple calculator that adds two numbers. | #include <stdio.h> int main() { double x, y, sum; printf("Enter two numbers: "); scanf("%lf%lf", &x, &y); sum = x + y; printf("Sum of the entered numbers: %lf", sum); return 0; } | |
null | Write a PHP script that creates a MySQL database table with three fields: "ID", "name", and "age". | <?php $servername = "localhost"; $username = "username"; $password = "password"; $dbname = "myDB"; // Create connection $conn = new mysqli($servername, $username, $password, $dbname); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } // sql to create table $sql = "CREA... | |
null | Represent the function y = 3x + 4 in JavaScript. | y = 3*x + 4; | |
null | Generate a Python class for an online store item that includes fields for ID, name, price, and description. | Not applicable | class StoreItem:
def __init__(self, item_id, name, price, description):
self.item_id = item_id
self.name = name
self.price = price
self.description = description
def __str__(self):
return f'{self.name}, ${self.price}'
def to_dict(self):
return {
... |
null | Fill in the below code to extract specific data from the given JSON object. | const jsonObj = { 'name': 'John Doe', 'locations': ['Los Angeles', 'New York', 'Las Vegas'], 'qualifications': {'degree': 'Master', 'university': 'Stanford'} } | const name = jsonObj['name']; const locations = jsonObj['locations']; const degree = jsonObj['qualifications']['degree']; const university = jsonObj['qualifications']['university']; |
[EN Wikipedia] Pariwhakaoho River
The Pariwhakaoho River is a river of the Tasman Region of New Zealand's South Island. It flows northeast from sources within Kahurangi National Park to reach Golden Bay 10 kilometres northwest of Tākaka. See also List of rivers of New Zealand References Rivers of the Tasman District K... | null | null | null |
null | Design the algorithm to perform a depth-first search on given binary tree | def DFS(root): s = Stack() s.push(root) while (s.size() > 0): node = s.pop() # Do something with the node if (node.left != NULL): s.push(node.left) if (node.right != NULL): s.push(node.right) | |
null | Write JavaScript code to add the following data to the web page. | [ { name: "John", age: 25 }, { name: "Rob", age: 27 }, { name: "Mia", age: 22 } ] | let data = [ { name: "John", age: 25 }, { name: "Rob", age: 27 }, { name: "Mia", age: 22 } ]; let table = document.createElement("table"); table.setAttribute("id", "personTable"); let thead = document.createElement("thead"); let tr = document.createElement("tr"); let th = document.createElement("th"); th.innerText = "N... |
null | Create a function to extract the top 10 keywords from a given text. | text = "This is some text that I am using to test the extractKeywords function." | import nltk def extractKeywords(text): tokens = nltk.word_tokenize(text) tags = nltk.pos_tag(tokens) keywords = [word for word,pos in tags if (pos == 'NN' or pos == 'NNP' or pos == 'NNS' or pos == 'NNPS')] freqs = nltk.FreqDist(keywords) top_ten = freqs.most_common(10) return top_ten if __name__ == "__main__": text = "... |
null | Create a Python program that takes a string as input and prints all permutations of it in lexicographical order. | ABC | def permutations(string):
if len(string) == 0:
return
else:
first_char = string[0]
remainder = string[1:]
permutations(remainder)
for perm in permutations(remainder):
for i in range(len(perm)+1):
result = perm[:i] + first_char + perm[i:]
print(result)
permutations("ABC") #run the code
# Output
ABC
ACB
BAC
... |
null | Write a code to fetch the last ten news headlines from HackerNews using their API. | """ Fetch the last ten news headlines from HackerNews using their API """ import requests def get_headlines(): url = "https://hacker-news.firebaseio.com/v0/topstories.json" ids = requests.get(url).json() headlines = [] for id in ids[:10]: item = requests.get(f"https://hacker-news.firebaseio.com/v0/item/{id}.json").json... | |
[CS Wikipedia] Oisemont
Oisemont je francouzská obec v departementu Somme v regionu Hauts-de-France. V roce 2010 zde žilo 1 189 obyvatel. Vývoj počtu obyvatel Související články Seznam obcí v departementu Somme Externí odkazy Reference Obce v departementu Somme | null | null | null |
null | Edit the output of a C program so that the last line prints "Hello World!" | #include <stdio.h> int main() { printf("Hello!"); return 0; } | #include <stdio.h> int main() { printf("Hello!"); printf("Hello World!"); return 0; } |
null | Implement a python class named 'Temperature' that ranks a temperature value as cold, warm, or hot given a threshold value of 30. | class Temperature: def __init__(self, value, threshold=30): self.value = value self.threshold = threshold def rank(self): if self.value < self.threshold: return "cold" elif self.value == self.threshold: return "warm" else: return "hot" | |
null | Publish an article to Medium using the Medium Python SDK. | No input | import medium
# Create a client
client = medium.Client(
application_id="YourApplicationID",
application_secret="YourApplicationSecret",
)
# Log in to your account
client.access_token = "<YourAccessToken>"
# Create a post to publish
post = medium.Post(
title="Article Title",
content="This is the article conte... |
null | Create a Python program that takes a list of numbers, and finds a pair of numbers in the list whose sum equals the given number | [2, 3, 4, 5], 5 | def find_pair_with_sum(nums, target):
seen = set()
for num in nums:
if target - num in seen:
return [target - num, num]
seen.add(num)
print(find_pair_with_sum([2, 3, 4, 5], 5)) |
null | Identify which elements in an array are even numbers. | nums = [1, 2, 3, 4, 5] | def is_even_num(nums): result = [] for num in nums: if num % 2 == 0: result.append(num) return result |
null | Design a Python class to accommodate a stack of characters. | class Stack():
def __init__(self):
self.items = []
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def isEmpty(self):
return self.items == []
def peek(self):
if not self.isEmpty():
return self.items[-1] | |
null | Write a C# script to print the string "Hello, World!" three times | for (int i=0; i < 3; i++) { Console.WriteLine("Hello, World!"); } | |
null | Given a dictionary, write a Python function to print all the key-value pairs in the dictionary. | def print_dict_key_value(dic): for key, value in dic.items(): print(f"{key}: {value}") | |
null | What is the purpose of the method in line 4 of the code? | def random_number_generator(min, max):
"""Return a random number between the given range."""
rng = random.range(min, max)
return rng | The purpose of the method in line 4 is to generate a random number within the given range of min and max. It uses the Python's random.range() method which returns a random integer from the range of min to max, inclusive. |
[DE Wikipedia] Sven Brajer
Sven Brajer (* 1984 in Löbau) ist ein deutscher Historiker, Museologe und Journalist. Leben Brajer wuchs in der Oberlausitz auf. Er lernte zunächst Einzelhandelskaufmann. An der Technischen Universität Dresden studierte er Geschichte, Soziologie und Politikwissenschaft. Brajer beschäftigt si... | null | null | null |
null | Identify the endpoint of a given API request. | Request: GET https://www.example.com/1 | The endpoint of this API request is https://www.example.com/1. |
null | Write a SQL statement to get all records from a table which has id between 5 and 10. | SELECT * FROM table_name WHERE id BETWEEN 5 AND 10; | |
[EN Wikipedia] 1934–35 Hovedserien season
The 1934–35 Hovedserien season was the first season of ice hockey in Norway. Seven teams participated in the league, and Ski- og Fotballklubben Trygg won the championship. Regular season External links Norwegian Ice Hockey Federation Nor Eliteserien (ice hockey) seasons 1934–3... | null | null | null |
null | What is the name of the attribute for creating a hover effect for an element in CSS? | The attribute used in CSS to create a hover effect for an element is the ':hover' pseudo-class. | |
null | Create a function in Python that takes three numerical inputs and returns the maximum value. | def max_value(num1, num2, num3): max_num = max(num1, num2, num3) return max_num | |
null | Sort a list of dictionaries in Python by a given key. | [{'food': 'apple', 'color': 'red'}, {'food': 'banana', 'color': 'yellow'}, {'food': 'pear', 'color': 'green'}] | list_of_dicts = [{'food': 'apple', 'color': 'red'}, {'food': 'banana', 'color': 'yellow'}, {'food': 'pear', 'color': 'green'}]
# Sort list by given key
sorted_list = sorted(list_of_dicts, key=lambda item:item['color'])
print(sorted_list) |
[DE Wikipedia] Becco di Filadonna
Der Becco di Filadonna (2.150 m) ist der östlichste Gipfel im Höhenzug zwischen Etschtal und Valsugana, südöstlich von Trient (italienisch: Trento) und westlich der Hochebene von Lavarone. Er ist ein besonderer Aussichtsberg mit fast 360 Grad Rundumblick von der Brentagruppe über den ... | null | null | null |
[CS Wikipedia] Blind Before I Stop
je páté studiové album amerického rockového zpěváka Meat Loafa. Vydáno bylo v září roku 1986 prostřednictvím společnosti Atlantic Records v Severní Americe a společnosti Arista Records ve zbytku světa. Nahrávání alba proběhlo během ledna téhož roku v německém studiu Far Studios s pro... | null | null | null |
null | What is the time complexity for this for loop? | nums = [1,2,3,4,5] for num in nums: print(num) | The time complexity for this loop is O(n) where n is the length of the list. |
null | Edit a given Python program to use regex to extract the phone numbers from the text. | import re
txt = "My number is 666-111-1111 and my office number is 888-666-1234." | import re
txt = "My number is 666-111-1111 and my office number is 888-666-1234."
phone_numbers = re.findall(r'\d{3}-\d{3}-\d{4}', txt)
print(phone_numbers) # output: ['666-111-1111', '888-666-1234'] |
null | Read the given date string in the specified format and print out the day of the week. | Date String: 03/02/2020 Format: mm/dd/yyyy | Thursday |
[CS Wikipedia] Rochdale
Rochdale je město v severozápadní Anglii. Je součástí stejnojmenného metropolitního distriktu a metropolitního hrabství Velký Manchester. Leží na úpatí jižních Pennin necelých 16 km severovýchodně od centra Manchesteru a 8 km severozápadně od města Oldham. Historie Název města pochází od řeky R... | null | null | null |
null | Write a Python program to calculate the average monthly temperature of a given city for the last 10 years. | City: Los Angeles, California
10 year average temperature from 2010 to 2020 | import csv
def avg_month_temp(city):
result = 0
counter = 0
temperatures = csv.reader(open('weatherdata.csv'))
for row in temperatures:
if row[1] == city:
result += float(row[2])
counter += 1
return result/counter |
null | In the given CSS stylesheet, change all the h1 heading text to purple. | h1 { font-size: 3rem; font-weight: bold; color: #b0b0b0; } | h1 { font-size: 3rem; font-weight: bold; color: #9100ff; } |
[EN Wikipedia] Taylor River (New Zealand)
The Taylor River is one of the two rivers that flow across the Wairau Plain into Blenheim, New Zealand, where it joins the Ōpaoa River. It arises near Taylor Pass to the south of the Wither Hills and flows north-east and north. The river and pass were named for Joseph Taylor, ... | null | null | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.