text
stringlengths
141
2.89k
⌀
instruction
stringlengths
19
1.5k
⌀
input
stringlengths
0
800
⌀
output
stringlengths
1
2.5k
⌀
null
Write a Python program to create a dictionary containing the given list of numbers and their squares as values.
[1,2,3,4,5]
my_list = [1,2,3,4,5] squares_dictionary = {} for x in my_list: squares_dictionary[x] = x**2 print(squares_dictionary)
null
Create a sorting algorithm in Python to organize a given array of numbers.
Array of numbers: [3, 5, 4, 1, 6]
def bubbleSort(nums): for i in range(len(nums)-1): for j in range(0, len(nums)-i-1): if nums[j] > nums[j+1] : nums[j], nums[j+1] = nums[j+1], nums[j] return nums arr = [3, 5, 4, 1, 6] print (bubbleSort(arr))
null
Create a function in Python to delete an element from a linked list given its position.
def deleteNode(head, position): # If linked list is empty if head == None: return # Store head node temp = head # If head needs to be removed if position == 0: head = temp.next temp = None return head # Find previous node of the node to be deleted for i in range(position-1...
null
Write a SQL query to select the top 3 highest salaries in a employees table.
SELECT TOP 3 salary FROM employees ORDER BY salary DESC;
[EN Wikipedia] Pararrhaptica subsenescens Pararrhaptica subsenescens is a moth of the family Tortricidae. It was first described by Lord Walsingham in 1907. It is endemic to the Hawaiian islands of Molokai and Hawaii. External links Archipini Endemic moths of Hawaii Biota of Hawaii (island) Biota of Molokai
null
null
null
null
Create a function to parse the given HTML and return an array containing the text content of all the <p> tags.
html: <html> <head> <title>Parsing HTML</title> </head> <body> <h1>Parsing HTML</h1> <p>This is the first paragraph.</p> <p>This is the second paragraph.</p> </body> </html>
def get_p_tags(html): soup = BeautifulSoup(html,"html.parser") p_tags = soup.find_all('p') content = [] for tag in p_tags: content.append(tag.get_text()) return content html = """ <html> <head> <title>Parsing HTML</title> </head> <body> <h1>Parsing HTML</h1> <p>This is the first paragraph.</p> <p>This is the second par...
null
Query an API and display its results.
URL = "http://ip-api.com/json"
import requests response = requests.get(url) data = response.json() print(data)
null
Create a Python program to classify emails as either spam or non-spam.
Not applicable
import numpy as np import pandas as pd from sklearn.preprocessing import LabelEncoder from sklearn.model_selection import train_test_split from sklearn.naive_bayes import MultinomialNB # Load dataset df = pd.read_csv('dataset.csv') # Encode labels le = LabelEncoder() X = df.drop(['label'],axis=1).values y = le.fit_tr...
null
Design an algorithm in Python for linear search on an array of integers.
def linearSearch(arr, x): for i in range(len(arr)): if arr[i] == x: return i return -1
null
Develop a program to spell a given word.
"Hello"
def spellWord(word): words = list(word) for i in range(len(words)): print(words[i])
[DE Wikipedia] Vestec Vestec ist der Name mehrerer Orte in Tschechien Gemeinde im Okres Náchod, siehe Vestec u Hořiček Gemeinde im Okres Nymburk, siehe Vestec nad Mrlinou Gemeinde im Okres Praha-západ, siehe Vestec u Prahy Vestec, Ortsteil von Běstvina, Okres Chrudim Vestec, Ortsteil von Chocerady, Okres Benešov Veste...
null
null
null
null
Design a PHP code for displaying the current URL.
<?php $url = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']; echo $url; ?>
null
Embed a machine learning model into a web page.
Python Machine Learning model file
# Imports from flask import Flask, render_template, request from sklearn.externals import joblib # App app = Flask(__name__) # Load the model model = joblib.load(Python Machine Learning model file) # Routes @app.route('/', methods=['GET', 'POST']) def predict(): # Get the data from the POST request. data...
null
Create a function in Python which takes a list and finds the second highest number in it.
arr = [2, 3, 1, 5, 4]
def second_highest_num(arr): arr.sort() return arr[-2]
null
Create a Python program to calculate day of the week for a given date.
(2020, 05, 22)
import datetime day, month, year = (2020, 05, 22) weekdays = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"] inpDate = datetime.date(year, month, day) dayOfWeek = inpDate.weekday() print(weekdays[dayOfWeek])
null
Implement a 'closest to zero' algorithm in Python, which returns the closest to 0 value from a given array.
[-2, 4, -5, - 1]
def closest_to_zero(arr): closest_val = 0 closest_diff = float('inf') for val in arr: if abs(val) < abs(closest_diff): closest_diff = val closest_val = val return closest_val arr1 = [-2, 4, -5, -1] result = closest_to_zero(arr1) print(result)
null
Create a python script that extracts the first ten words from a given text.
The quick brown fox jumps over the lazy dog
import re text = "The quick brown fox jumps over the lazy dog" # Extract words using a regular expression words_list = re.findall(r"[\w']+", text) # Print the first ten words print(words_list[:10])
null
Write a Python script to generate a random linear sequence.
import random # generate the sequence sequence_length = 10 sequence = [] for i in range(sequence_length): sequence.append(random.randint(1, 10)) print(sequence)
null
Create a class "Person" in Kotlin with first name, last name, and age as its fields.
class Person( var firstName: String, var lastName: String, var age: Int )
null
Write a SQL query to print out the names of employees in the Employees table who are older than 25.
Employees table is defined as: (employee_id int, first_name varchar(255), last_name varchar(255), age int).
SELECT first_name, last_name FROM Employees WHERE age > 25;
null
Parse the string "Hello[1]World[4]123[3]" into a list.
string = "Hello[1]World[4]123[3]"
my_list = string.split('[') my_list = [item.replace(']', '') for item in my_list] my_list = [int(item) for item in my_list[1::2]]
null
Create a function to convert a given decimal number to its corresponding hexadecimal value.
def dec2hex(n): return hex(n)[2:]
null
Create a Node.js script to read from a MongoDB database.
const MongoClient = require('mongodb').MongoClient; // Connection url const url = 'mongodb://localhost:27017'; // Database Name const dbName = 'myproject'; // Connect using MongoClient MongoClient.connect(url, function(err, client) { // Create a collection we want to drop later const col = client.db(dbName).collection(...
null
Implement a function to remove all occurrences of string t from string s.
s = 'The quick brown fox jumps over the lazy dog.' t = 'the'
def remove_string(s, t): if t not in s: return s s = s.lower() t = t.lower() indices = [] start = 0 while True: index = s.find(t, start) if index == -1: break indices.append(index) start = index + 1 offset = 0 for index in indices: s = s[:index - offset] + s[index - offset + len(t):] offset += len(t) return s
[DE Wikipedia] Doki Doki Morning Doki Doki Morning (jap. , Doki Doki Mōningu, wörtlich „herzklopfender Morgen“, geschrieben Doki Doki ☆ Morning) ist ein Lied der japanischen Metal-Band Babymetal. Es ist das erste Lied der Gruppe und wurde am 22. Oktober 2011 in Japan als DVD-Single veröffentlicht. Doki Doki Morning is...
null
null
null
null
How would you print the sum of all elements in a 2-dimensional array?
array=[[1,2], [3,4], [5,6]]
sum=0 for i in range(len(array)): for j in range(len(array[i])): sum+= array[i][j] print(sum)
null
Create a Python script to output the maximum number from a set of user-inputted numbers.
def find_max_number(numbers): maximum = numbers[0] for i in numbers: if i > maximum: maximum = i return maximum
null
Create a class in Python to represent a book and include a method for getting the name of the book.
class Book: def __init__(self, name): self.name = name def get_name(self): return self.name
null
Create a looping statement in Python to print the alphabet in lowercase.
for letter in "abcdefghijklmnopqrstuvwxyz": print(letter)
null
Write an algorithm to check if a number is even or not without using modulus (%) operator
def is_even(num): if num & 1 == 0: return True else: return False
[EN Wikipedia] Rimantas Šulskis Rimantas Šulskis (1943–1995) was a Lithuanian sculptor and painter. See also List of Lithuanian painters References Lithuanian sculptors 1943 births 1995 deaths 20th-century Lithuanian sculptors 20th-century Lithuanian painters
null
null
null
null
Create an Artificial Neural Network in Python to classify flower colors from a given input.
""" Creating an Artificial Neural Network in Python to classify flower colors from a given input """ import numpy as np import keras from keras.models import Sequential from keras.layers import Dense, Dropout # Create the input data and labels X_train = np.array([ [0], [1], [2], [3], [4], [5]...
null
Using Python, design an algorithm that takes a string as an input and reverses it.
"Hello World!"
def reverseString(str): s = "" for i in str: s = i + s return s print(reverseString('Hello World!')) # Output: !dlroW olleH
null
Build a Keras model to predict whether a patient has cancer.
model = keras.Sequential([ keras.layers.Dense(64, activation='relu', input_shape=(len(features.keys()),)), keras.layers.Dense(32, activation='relu'), keras.layers.Dense(1, activation='sigmoid') ]) model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
null
Write a Python script to determine how many lowercase letters are in a given string.
string = "Hello World!"
""" Python script to determine how many lowercase letters are in a given string """ # Initialize a variable to count the lowercase letters lowercase_letter_count = 0 # Loop through each character in the string for char in string: # Check if the character is a lowercase letter if char.islower(): # If yes, then increment...
null
Create an exponential moving average function in R.
library(zoo) exponential_moving_average <- function(x, n, beta) { EMA <- 0 for (i in 1:length(x)) { if (i == 1) { EMA[i] <- x[i] } else { EMA[i] <- ((beta * x[i]) + ((1 - beta) * EMA[i - 1])) } } ma_x <- as.numeric(rollapply(EMA, n, mean, fill = NA, align = "right")) return(ma_x) }
null
Generate a 5-element tuple of random numbers between 5 and 15 using Python.
import random random_tuple = tuple(random.randint(5, 15) for _ in range(5))
null
Design a data structure to store the details of a student (Name, Age, Course).
struct Student { name: String, age: u32, course: String, }
[CS Wikipedia] Rychlost světla Rychlost světla (nebo jiného elektromagnetického záření) ve vakuu (stručně též „světelná rychlost“ bez nutnosti uvádět ještě „ve vakuu“) je definována jako fázová rychlost postupného elektromagnetického vlnění ve vakuu. V soustavách jednotek založených na metrickém systému (tedy i SI) má...
null
null
null
null
Using the given dictionary, write a program in Python to find the most frequent word.
sample_dict = {'electron':10, 'atom':3, 'chemistry':2, 'quantum':15}
def most_frequent(sample_dict): key = max(sample_dict, key=sample_dict.get) return key print(most_frequent(sample_dict)) # Outputs: "quantum"
[EN Wikipedia] Kenneth M. Baird Kenneth MacClure Baird (January 23, 1923 – April 18, 2022) was a Canadian physicist, metrologist and inventor, born of Canadian parents in China in 1923. Biography He received his Bachelor of Science in physics at the University of New Brunswick, Canada in 1943, and joined the Canadian ...
null
null
null
null
Replace all vowels in a given string with the character "X" in C++.
"Hello World!"
#include<iostream> #include<string> using namespace std; int main() { string s = "Hello World!"; for (int i=0; s[i]!='\0'; i++) { if (s[i] == 'A' || s[i] == 'a' || s[i] == 'E' || s[i] == 'e' || s[i] == 'I' || s[i] == 'i' || s[i] == 'O' || s[i] == 'o' || s[i] == 'U' || s[i] == 'u') s[i] = 'X'; } cout << s; return 0; }
[EN Wikipedia] Axiom An axiom, postulate, or assumption is a statement that is taken to be true, to serve as a premise or starting point for further reasoning and arguments. The word comes from the Ancient Greek word (), meaning 'that which is thought worthy or fit' or 'that which commends itself as evident'. The prec...
null
null
null
[EN Wikipedia] American National Standards Institute The American National Standards Institute (ANSI ) is a private nonprofit organization that oversees the development of voluntary consensus standards for products, services, processes, systems, and personnel in the United States. The organization also coordinates U.S...
null
null
null
null
Write a SQL query to find the average price for all products in the Products table.
SELECT * FROM Products
SELECT AVG(Price) FROM Products;
null
Create a Python program to display a user's profile. The program should take a JSON object as an input and should output the user's name, age and email address.
{ "name":"John Smith", "age":32, "email":"john.smith@example.com" }
import json profile_data = { "name":"John Smith", "age":32, "email":"john.smith@example.com" } data = json.loads(profile_data) print("Name: {}".format(data["name"])) print("Age: {}".format(data["age"])) print("Email: {}".format(data["email"])) # Output: # Name: John Smith # Age: 32 # Email: john.smith@exampl...
null
Write a class to define a complex number
class ComplexNumber{ double real; double imaginary; public ComplexNumber(double real, double imaginary){ this.real = real; this.imaginary = imaginary; } public double getReal(){ return real; } public double getImaginary(){ return imaginary; } }
null
Design a web application in Python that reads a web page and counts the total number of words in the page.
import requests from bs4 import BeautifulSoup import re # Fetch the web page page = requests.get("THE_WEBPAGE_URL") # Parse the content of the page soup = BeautifulSoup(page.content, 'html.parser') # Find all visible text in the page text = soup.find_all(text=True) # Remove text inside scripts and style tags fo...
null
Design a program that produces the following output: . . . . . . . . . . . . . . . . . . . . .
#include <iostream> int main() { for (int i=0; i<17; i++) { std::cout << "."; } std::cout << std::endl; return 0; }
[DE Wikipedia] Kullana Kulturali Kullana Kulturali (maltesisch; „Kulturelle Halskette“) ist eine Enzyklopädie zu Malta bzw. den Maltesischen Inseln in maltesischer Sprache, die in den Jahren von 1999 bis 2006 in Malta im Verlag Pubblikazzjonijiet Indipendenza (PIN) in Pièta auf Malta erschien. Sie umfasst 72 Bände. Si...
null
null
null
null
Create a web application in Python that displays a directory structure tree for a given path.
/home/myUser/myFolder
import os def make_tree(path): files = os.listdir(path) for f in files: full_path = os.path.join(path, f) if os.path.isdir(full_path): print(f) make_tree(full_path) else: print(" -" + f) path = '/home/myUser/myFolder' make_tree(path)
[DE Wikipedia] Adolf Becker (Politiker) Adolf Heinrich August Becker (* 30. Juli 1848 in Rostock; † 18. April 1922 ebenda) war ein deutscher Jurist in der Kommunalverwaltung. Von 1907 bis 1919 war er Bürgermeister von Rostock. Leben Adolf Becker wuchs in Rostock auf und besuchte hier die Schule. Nach dem Abitur begann...
null
null
null
null
Given a list of integers, write a Python program to print the latest 3 largest numbers.
[5, 1, 10, 25, 74, 17, 2]
def print_largest_three_numbers(numbers): numbers.sort(reverse=True) print(*numbers[:3], sep = ", ") print_largest_three_numbers([5, 1, 10, 25, 74, 17, 2]) Output: 74, 25, 17
[EN Wikipedia] 68 Whiskey 68 Whiskey is an American military comedy-drama television series created by Roberto Benabib. Based on the Israeli television series Charlie Golf One (known as Taagad in ), it premiered on January 15, 2020 on the Paramount Network. In September 2020, the series was canceled after one season. ...
null
null
null
[DE Wikipedia] Hildegund Menzel-Rogner Hildegund Menzel-Rogner, geb. Rogner (* 2. März 1910 in Breslau; † 6. Februar 1945 in Berlin) war eine deutsche Philosophin und Wissenschaftlerin. Leben Die Tochter eines Volksschullehrers lernte als Heranwachsende den Jugendstilkünstler Melchior Lechter (1865–1937) kennen, der s...
null
null
null
null
Implement a REST API endpoint with Python and Flask to POST user data including username, email, and password.
{ "username": "scott_pilgrim", "email": "scott@pilgrim.com", "password": "ferriswheel" }
import flask from flask import Flask, request, jsonify app = Flask(__name__) @app.route('/users', methods=['POST']) def create_user(): data = request.get_json() username = data['username'] email = data['email'] password = data['password'] # Insert into database return jsonify({"message": "User created successf...
[CS Wikipedia] Encyklopedie Encyklopedie ( okružní + výchova) je strukturované, zpravidla objemné dílo, které se pokouší zevrubně představit lidské poznání týkající se jednoho, více, anebo všech oborů. Řeckého pojmu poprvé užil v 5. století př. n. l. Hippias z Elidy, který jim označoval všeobecné vzdělání. Obecná char...
null
null
null
null
In a Python class, create a method to compute the average of n numbers without using the average function.
class AverageCalculator: def average(self, nums): sum = 0 for i in range(len(nums)): sum += nums[i] return sum / len(nums)
null
Write a blank Python program to convert celsius to fahrenheit.
def celsius_to_fahrenheit(celsius): """ This function converts the given celsius value to its corresponding fahrenheit value """ fahrenheit = (celsius * (9/5)) + 32 return fahrenheit
null
Create a for loop for copying an array.
arr = [1, 2, 3, 4, 5]
arr_copy = [] for i in arr: arr_copy.append(i)
null
Write a Python program to combine the elements of two lists of equal length into a dictionary.
list1 = ['a', 'b', 'c'] list2 = [1, 2, 3]
dict = {} for i in range(len(list1)): dict[list1[i]] = list2[i] print(dict)
null
Construct a Markov chain using Python to predict the next word in a sentence.
Not applicable
import random # Build the Markov chain def build_chain(data): chain = {} for i in range(len(data)-2): key = (data[i], data[i+1]) value = data[i+2] if key in chain: chain[key].append(value) else: chain[key] = [value] return chain # Generate the output def generate_output(chain...
[CS Wikipedia] Richard Chaves Richard John Chaves (* 9. října 1951 Jacksonville, Florida) je americký herec. Jedná se o veterána vietnamské války, podle které má základy autorské kritika v divadelní hře Tracers (Stopaři). I když hrál v několika filmech, výrazněji se neprosadil. Jeho nejznámější rolí je role Poncha ve ...
null
null
null
null
Create a Python program that converts a list of numbers into a dictionary, where the key is the number and the value is the corresponding difference between two immediate numbers in the list.
[1, 2, 4, 7, 11]
def diff_in_list(input_list): """This function takes a list of integers and returns a dictionary with the input number as key and the difference between two immediate numbers as value.""" output_dict = {} # Iterate over the list and create a dictionary with the # input number as key and the dif...
null
Create a SQL statement to select all carts with more than 10 items in them.
SELECT * FROM carts WHERE items > 10;
null
Edit the following code so that it prints the sum of all elements of given array
arr = [1,5,8,4,2] def sumArray(arr): for i in len(arr): print(arr[i])
arr = [1,5,8,4,2] def sumArray(arr): total = 0 for i in arr: total += i print(total)
null
Create a MySQL query to update the salary field of the employee
Table - employee Field - salary
UPDATE employee SET salary = 2000 WHERE employee_id = 1
null
Change the following code snippet to generate a random integer from 0 to 10.
import random random_int = random.randint(0, 10)
null
Create a python script that parses a CSV and generates a new CSV that adds the total number of rows, total number of columns, and total amount of the data for each attribute.
""" Parses a CSV and generates a new CSV that adds the total number of rows, total number of columns, and total amount of data for each attribute. """ import csv def parse_csv(filename): with open(filename) as csv_file: reader = csv.DictReader(csv_file) rows =0 cols = 0 data_total...
null
How does the Fibonacci number sequence work?
The Fibonacci sequence is a sequence of numbers where each number in the sequence is the sum of the two numbers preceding it. The first two numbers in the sequence are 0 and 1. The sequence starts with 0 and 1 and continues by adding the two previous numbers to get the next number in the sequence. For example, the firs...
null
Create a Python script that does linear regression on a given dataset.
Not applicable
import numpy as np import pandas as pd from matplotlib import pyplot as plt import statsmodels.api as sm # Load the data data = pd.read_csv('data.csv') # Add constant to the dataset data = sm.add_constant(data) # Fit the model results = sm.OLS(data['x'], data[['const','y']]).fit() # Get the fitted parameters para...
null
Design a Python program to convert a list of Fahrenheit temperatures to a list of Celsius temperatures.
[150, 160, 170, 180, 190]
def Fahrenheit_to_Celsius(Fahrenheit_Temps): Celsius_Temps = [] for temp in Fahrenheit_Temps: Celsius = (temp - 32) * 5 / 9 Celsius_Temps.append(Celsius) return Celsius_Temps Fahrenheit_Temps = [150, 160, 170, 180, 190] Celsius_Temps = Fahrenheit_to_Celsius(Fahrenheit_Temps) print("C...
null
Write an SQL query to find the highest population of any country from the table of countries.
Table: countries Columns: Name (string), Population (int)
SELECT Name, MAX(Population) FROM countries;
[CS Wikipedia] Termodynamický děj Termodynamický děj (též tepelný děj) je děj, při kterém se mění stav tělesa (mění se některé ze stavových veličin). Kruhový děj Pokud termodynamická soustava projde řadou změn a nakonec se vrátí do původního stavu, pak říkáme, že soustava vykonala kruhový (cyklický) děj (zkráceně cykl...
null
null
null
null
Create an HTTP request to get the data from the given API and parse it into a JSON object.
https://example.com/api/getData
import requests url = "https://example.com/api/getData" response = requests.get(url) data = response.json()
null
Identify the type of object-oriented programming pattern used in the following code snippet.
public class Animal { public void eat() { // eat logic } public void move() { // move logic } public void sleep() { // sleep logic } }
The code snippet is an example of the Template Method pattern. It provides a template method (eat, move, and sleep) that can be used by subclasses. The template method is defined in a superclass and the subclasses can override the methods to provide custom implementations.
null
Create a Python web crawler to collect data from web page.
import requests import bs4 def web_crawler(url): # make request to the specified url and retrieve the response response = requests.get(url) # since this page is regular HTML page, we need to use the html parser soup = bs4.BeautifulSoup(response.text, 'html.parser') # extract the data from the parsed web pa...
null
Create a Python function that returns the index of the nth occurrence of a substring in a given string.
("Hello World", "l", 3)
def find_nth_occurrence(string, substring, n): index = -1 while n > 0: n -= 1 index = string.find(substring, index+1) if index == -1: return None else: return index if __name__ == "__main__": result = find_nth_occurrence("Hello World", "l", 3) print(result)
null
Write a Python program to sort a list of tuples according to its second parameter in ascending order.
list = [("yellow", 28), ("blue", 30), ("black", 25), ("pink", 45)]
def sort_tuples(list): """Function to sort tuples according to their second parameter""" list.sort(key = lambda x : x[1]) return list #Example: print(sort_tuples(list))
null
Create a program that prints out a list of all numbers from 0 to 10, except for five.
for num in range(11): if num != 5: print(num)
null
Using a dictionary, write a program in Python to categorize each list item into a group of the same type.
items = [1, 2, ‘a’, ‘b’, 4, 5, ‘c’, ‘d’, 7, 8]
def categorize(items): groups = { 'numbers': [], 'strings': [] } for item in items: if type(item) == int or type(item) == float: groups['numbers'].append(item) else: groups['strings'].append(item) return groups
null
Use a Python library to visualize a Gaussian normal distribution with the mean set to 5 and the standard deviation set to 1.
import matplotlib.pyplot as plt import numpy as np mean = 5 std = 1 x = np.linspace(mean - 3*std, mean+3*std, 100) plt.plot(x, 1/(np.sqrt(2*np.pi*std**2)) *np.exp(-(x-mean)**2/(2*std**2))) plt.show()
null
Create a code to calculate the area of the triangle with given side lengths.
a=3 b=4 c=5
# Python Program to find the area of triangle a = 3 b = 4 c = 5 # calculate the semi-perimeter s = (a + b + c) / 2 # calculate the area area = (s*(s-a)*(s-b)*(s-c)) ** 0.5 print('The area of the triangle is %0.2f' %area)
[DE Wikipedia] Luzon-Waldratte Die Luzon-Waldratte (Bullimus luzonicus) ist ein auf den nördlichen Philippinen endemisches Nagetier in der Gattung der Philippinen-Moosmäuse. Das Typusexemplar stammt von den Hängen des Mount Data. Merkmale Dieses Nagetier ist groß und erreicht ohne Schwanz eine Länge von 234 bis 267 mm...
null
null
null
[EN Wikipedia] Royal Moroccan Judo Federation The Royal Moroccan Judo Federation is a sports association founded in 1959 in Morocco, replacing the Moroccan Judo League, created in 1951. Its role is to promote judo in the kingdom and to represent the colors of Morocco in international competitions. RMJF has been affili...
null
null
null
null
Print the following string in HTML.
"Welcome to my website!"
<html> <head> <title>Welcome to my website!</title> </head> <body>Welcome to my website!</body> </html>
null
Combine the following two items in an array.
Item1: 2 Item2: [3, 4, 5]
[2, 3, 4, 5]
[CS Wikipedia] Jason Alexander Jason Alexander, rodným jménem Jay Scott Greenspan (* 23. září 1959, Newark, New Jersey, USA) je americký herec, muzikálový zpěvák a tanečník, držitel americké divadelní ceny Tony. Vybraná filmografie 2005 – Chrise nemá rád nikdo (TV seriál) 2002 – 101 dalmatinů II: Flíčkova londýnská do...
null
null
null
[EN Wikipedia] Adrienn Kocsis Adrienn Kocsis de Carulla (born 14 May 1973) is a retired Peruvian badminton player who initially played for Hungary but later moved on to represent Perú. Kocsis won Hungarian national championship and Peruvian national championship many times. Most notably, she won two bronze medals at 1...
null
null
null
null
Generate a random string with the a capital letter followed by two lower case letters.
import string import random def random_string(): capitalletter = random.choice(string.ascii_uppercase) lowercaseletter1 = random.choice(string.ascii_lowercase) lowercaseletter2 = random.choice(string.ascii_lowercase) return capitalletter + lowercaseletter1 + lowercaseletter2
[CS Wikipedia] František Lorenc František Lorenc, v Brazílii psáno Lorenz (24. prosince 1872 Zbyslav – 24. května 1957 Porto Alegre), byl český profesor a esperantista žijící po desetiletí v Brazílii. Je autorem první učebnice esperanta pro Čechy, která vyšla v roce 1890 tři roky po vyjití Zamenhofovy knihy přezdívané...
null
null
null
null
Create a GPT-2 model to generate text given a seed phrase.
from transformers import GPT2Tokenizer, GPT2LMHeadModel tokenizer = GPT2Tokenizer.from_pretrained('gpt2') model = GPT2LMHeadModel.from_pretrained('gpt2') def generate_text(seed_phrase): input_ids = torch.tensor(tokenizer.encode(seed_phrase)).unsqueeze(0) output_ids = model.generate( input_ids=input_ids, max_length=100,...
[EN Wikipedia] KJYL KJYL is a Christian radio station licensed to Eagle Grove, Iowa, broadcasting on 100.7 MHz FM. KJYL serves the Fort Dodge, Iowa area. The station is owned by Minn-Iowa Christian Broadcasting, Inc. Translators KJYL is also heard locally in Newell, Iowa, through a translator on 96.3 FM. References Ex...
null
null
null
null
Write a code to get the current weather information for a given city.
city = "New York"
import requests import json def get_weather_information(city): url = 'http://api.openweathermap.org/data/2.5/weather?q={},<APIKEY>'.format(city) response = requests.get(url) data = json.loads(response.text) return data if __name__ == '__main__': print(get_weather_information("New York"))
null
Generate a method for a Python class that returns the most commonly used words in a text document.
Not applicable
def most_common_words(self): words = {} words_list = self.text.split(' ') for word in words_list: if word in words.keys(): words[word] += 1 else: words[word] = 1 return sorted(words, key=words.get, reverse=True)[:10]
null
Create a Swift program that reads in three values from the user and prints out the maximum value.
import Foundation var a = 0 var b = 0 var c = 0 print("Enter 3 values:") if let aInput = readLine() { if let aInt = Int(aInput) { a = aInt } } if let bInput = readLine() { if let bInt = Int(bInput) { b = bInt } } if let cInput = readLine() { if let cInt = Int(cInput) { c = cInt } } var maximum = max(max(a, b), c) print...
null
Fix the bug in the following code that causes the output to be incorrect.
def calculate_sum(numbers): total = 0 for num in numbers: total += num return total numbers = [2, 3, 5] result = calculate_sum(numbers) print(f'Sum of {numbers} is {result}')
def calculate_sum(numbers): total = 0 for num in numbers: total += num return total numbers = [2, 3, 5] result = calculate_sum(numbers) print(f'Sum of {numbers} is {result}.')
null
Develop a SQL query to find all the records that have modified within a given time range.
SELECT * FROM Table WHERE ModifiedTime BETWEEN '<start-time>' AND '<end-time>';
null
How can you change the given string 'Hello World' to 'World Hello'?
string = "Hello World" string = string.split() string = string[1] + ' ' + string[0] print(string) # World Hello
null
Write Python code to reverse the letters in the string "hello".
def reverseString(s): return s[::-1] print(reverseString('hello'))