text
stringlengths
141
2.89k
⌀
instruction
stringlengths
19
1.5k
⌀
input
stringlengths
0
800
⌀
output
stringlengths
1
2.5k
⌀
[EN Wikipedia] Cymolomia phaeopelta Cymolomia phaeopelta is a moth of the family Tortricidae. It is found in Vietnam, Thailand, India, western Java and eastern Borneo. References Moths described in 1921 Olethreutini Moths of Asia Moths of Indonesia Insects of Borneo Taxa named by Edward Meyrick
null
null
null
[DE Wikipedia] Håkon Evjen Håkon Evjen (anglisiert: Haakon Evjen; * 14. Februar 2000 in Narvik) ist ein norwegischer Fußballspieler, der seit Januar 2023 beim dänischen Erstligisten Brøndby IF unter Vertrag steht. Der Flügelspieler ist seit November 2020 norwegischer Nationalspieler. Karriere Verein Evjen begann mit d...
null
null
null
null
Compose a Python program that reads in a string and finds the position of the longest alphabetical substring
"abcbcd"
def longest_alphabet(string): max_length = 0 start_pos = 0 for x in range(len(string)): current_start_pos = x current_length = 0 for y in range(x, len(string)): if string[y] >= string[y-1]: current_length += 1 else: break ...
null
Generate a new Python List containing all of the even numbers from a given list.
my_list = [2, 3, 4, 5, 6, 7, 8, 9]
my_list = [2, 3, 4, 5, 6, 7, 8, 9] even_list = [x for x in my_list if x % 2 == 0] print(even_list)
null
Write a code block to return a random value from a given list
[1, 4, 8, 12]
#Return a random value from a given list import random def get_random_value(lst): n = random.randint(0, len(lst) - 1) return lst[n] test_list = [1, 4, 8, 12] random_value = get_random_value(test_list) print('Random value:', random_value)
null
Create a dictionary with three items of your choice
{ 'apple': 'fruit', 'carrot': 'vegetable', 'sugar': 'sweetener' }
null
Suggest a way to improve the C++ program.
#include <iostream> int main() { std::cout << "Hello, World!" << std::endl; return 0; }
#include <iostream> int main() { std::cout << "Hello, World!" << std::endl; std::cout << "This is a C++ program." << std::endl; return 0; }
null
Create an optimization function in Python that takes in a list of integers and finds the smallest number that is greater than all of the other numbers in the list.
[1, 2, 3, 4]
def optimize(arr): smallest = None for num in arr: if (smallest is None) or (num > smallest): smallest = num return smallest + 1 x = [1, 2, 3, 4] result = optimize(x) print(result) # 5
null
Create a function in C++ that capitalizes the first letter of every word in a given string.
#include <iostream> #include <string> std::string capitalize(std::string s) { std::string result; for (int i = 0; i < s.length(); i++) { if (i == 0 || s[i - 1] == ' ') result += toupper(s[i]); else result += s[i]; } return result; }
[EN Wikipedia] Tiger Mask W is a Tiger Mask anime series which premiered on October 2, 2016, with 38 episodes. It has a mix of 2D and 3D CGI animation. It is a sequel of the original anime, whereas Tiger Mask II is only considered a parallel universe. Plot Over forty years since Naoto Date mysteriously vanished after ...
null
null
null
null
Generate a Python script for analyzing a given dataset. The script should output the number of rows and columns, the data type of each column, the average of all numeric columns, and the count of unique values present in the dataset.
Input Titanic Dataset PassengerId, Survived, Pclass, Name, Sex, Age, SibSp, Parch, Ticket, Fare, Cabin, Embarked 1,0,3,"Braund, Mr. Owen Harris",male,22,1,0,A/5 21171,7.25,,S 2,1,1,"Cumings, Mrs. John Bradley (Florence Briggs Thayer)",female,38,1,0,PC 17599,71.2833,C85,C 3,1,3,"Heikkinen, Miss. Laina",female,26,0,0,...
import pandas as pd # Read the dataset df = pd.read_csv('dataset.csv') # Get the number of rows and columns num_rows, num_cols = df.shape print('Number of rows: {}'.format(num_rows)) print('Number of columns: {}'.format(num_cols)) # Get the data type of each column data_types = df.dtypes.tolist() print('Data type of...
null
Construct a SQL query to find all customers with a first name of "John" and a city of "New York".
SELECT * from customers WHERE first_name = 'John' AND city = 'New York';
null
Develop a SQL query to count the number of people who are born before 1992.
SELECT COUNT(*) FROM people WHERE year_of_birth < 1992;
null
Write a python code to insert a new node at the head of a linked list
# Node class class Node: # Function to initialise the node object def __init__(self, data): self.data = data # Assign data self.next = None # Initialize next as null # Linked List class class LinkedList: # Function to initialize head def __init__(self): self.head = None # Function to insert a new node at the beginning ...
null
Construct a JSON structure from its respective python dictionaries
a = { "name": "John", "age": 32 } b = { "cars": ["Ford", "BMW", "Fiat"] }
import json data = {**a, **b} json_data = json.dumps(data)
null
Edit the given code to add a function that calculates the area of a circle given its radius.
def circumference(r): '''Calculates the circumference of a circle given its radius''' return 2* PI * r
def circumference(r): '''Calculates the circumference of a circle given its radius''' return 2* PI * r def area(r): '''Calculates the area of a circle given its radius''' return PI * r * r
null
Write a JavaScript function to validate a given URL.
function isValidURL(url) { const regex = /^(?:http(s)?:\/\/)?[\w.-]+(?:\.[\w\.-]+)+[\w\-\._~:/?#[\]@!\$&'\(\)\*\+,;=.]+$/; return regex.test(url); }
[CS Wikipedia] Eönwë Eönwë je postava J. R. R. Tolkiena objevující se především v knize Silmarillion. Eönwë je jedním z Maiar, a jedním z těch, kteří dobrovolně vstoupili na Ardu. Jako takový je společně s Ilmarë největší valinorský Maia, a jeho sílu ve zbrani nikdo v Ardě nepřekoná. Je praporečníkem Manwëho. Jeho nej...
null
null
null
null
Based on the following list, create a dictionary of each name and their corresponding birth date.
names = ["John", "Mary", "James", "Susan"] birth_dates = ["1992-12-24", "1979-05-17", "1995-08-15", "1985-04-10"]
name_birthdate_dict = dict(zip(names, birth_dates)) print(name_birthdate_dict) # Output: {'John': '1992-12-24', 'Mary': '1979-05-17', 'James': '1995-08-15', 'Susan': '1985-04-10'}
[CS Wikipedia] Štěpán Leška Štěpán Leška, (* 21. října 1757 Vrbovce – 25. února 1818 Kiskőrös) byl evangelický duchovní, superintendent, filolog, spisovatel a žurnalista. Život Po studiích působil jako varhaník a učitel evangelického sboru v Bratislavě. Roku 1784 odešel do Čech, kde působil jako farář sboru augsburské...
null
null
null
null
Using Python, write a program to calculate the sum (full addition) of two decimal numbers.
3.4, 2.6
def addDecimals(a, b): return a + b x = 3.4 y = 2.6 print (addDecimals(x, y)) # 6.0
null
Create an Oracle SQL statement for finding the average cost of a product.
SELECT AVG(cost) FROM product;
[EN Wikipedia] Matelo Ferret Jean Pierre "Matelo" Ferret (1918 – 24 January 1989) (also spelled Matelot, Matlo and Matlow, surname also later spelled Ferré on occasion) was a French musette and gypsy jazz guitarist and composer. He was an associate of Django Reinhardt and the youngest brother of guitarists Baro and Sa...
null
null
null
null
Edit the code to delete the element with value 6 from the array.
int arr[] = {2, 4, 6, 8, 10}
// remove element at index 2 for (int i=2; i< arr.length-1; i++) arr[i] = arr[i+1]; // Reduce size of array by 1 int len = arr.length -1; int[] newarr = new int[len]; for (int i=0; i<newarr.length; i++) newarr[i] = arr[i];
null
Make an API call that fetches the user details and stores it in a DB.
// URL: '/users/fetch' // Parameters: username, password
const request = require('request'); function fetchUser(username, password) { const url = `/users/fetch?username=${username}&&password=${password}`; request.get(url, (err, res) => { if (err) { console.log('Failed to fetch user', err); return; } const userData = JSON.parse(res.body); // insert userData into database }); ...
null
Create a Python script to filter a list and return all elements which are divisible by a given number (i.e. create a filter function).
num_list = [1, 2, 3, 4, 5, 6] divisor = 2
def filter_list(num_list, divisor): return list(filter(lambda n: n % divisor == 0, num_list)) num_list = [1, 2, 3, 4, 5, 6] divisor = 2 divisible_nums = filter_list(num_list, divisor) print(divisible_nums) # [2, 4, 6]
null
Explain what the expression "variadic functions" means.
A variadic function is a function that can accept a variable number of arguments. It is a type of function in which the number of arguments that is passed to the function can vary, thus giving it more versatility than a function with a fixed number of arguments.
[EN Wikipedia] Old Sloatsburg Cemetery The Old Sloatsburg Cemetery is located at the end of Richard Street in Sloatsburg, New York, United States. It began as the Sloat family cemetery with the burial of Revolutionary War casualty John Sloat in 1781. After a half-century of inactivity, it gradually was expanded to inc...
null
null
null
[DE Wikipedia] Die letzte Metro Die letzte Metro (Originaltitel: Le Dernier Métro) ist ein französisches Filmdrama von François Truffaut aus dem Jahr 1980 mit Catherine Deneuve und Gérard Depardieu in den Hauptrollen. Handlung Zu Fotografien und kurzen Ausschnitten aus zeitgenössischen Filmdokumenten führt ein aus dem...
null
null
null
null
Create a Python script for creating an Excel spreadsheet with 2 sheets, one with a list of expenses and another one with a chart showing the total expenses.
Not applicable
import openpyxl def createSpreadsheet(name): # Create an Excel workbook workbook = openpyxl.Workbook() # Set up the first sheet with the list of expenses expenseSheet = workbook.active expenseSheet.title = 'Expenses' expenseSheet.cell(row=1, column=1).value = 'Item' expenseSheet.cell(row=1, column=2).va...
null
Generate a program to reverse a string in python.
def reverse_string(string): return string[::-1]
null
Write a Python code snippet to calculate the average of the given numbers.
[5, 10, 15, 20, 25]
def calc_avg(nums): total = 0 for n in nums: total += n return total/len(nums) avg = calc_avg([5, 10, 15, 20, 25]) print(avg)
[EN Wikipedia] Austin K5 The Austin K5 was a British heavy military truck built by Austin for use during the Second World War. The K5 was used with open body and cab for carrying the Ordnance QF 6 pounder anti-tank gun portee in the North African Campaign or with an enclosed cab for General Service (GS). Enclosed body...
null
null
null
null
Edit the code to add each item to a dictionary.
def add_to_dict(input_dict, key, value): return
def add_to_dict(input_dict, key, value): if key in input_dict: input_dict[key].append(value) else: input_dict[key] = [value] return input_dict
null
Write a JavaScript function to filter all numbers in an array and return a new array containing only the even numbers.
arr = [1, 2, 3, 4, 5, 6]
function evenNumbers(arr) { return arr.filter(num => num % 2 === 0); } evenNumbers(arr) # returns [2, 4, 6]
null
Write a Python function to display the current time, formatted such that it will read "It is currently 11:15am".
import time def display_time(): time_string = time.strftime('%I:%M%p', time.localtime()) return f'It is currently {time_string}'
null
Implement a thread pool in Java.
import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class ThreadPool { private ExecutorService executor; public ThreadPool(int size) { this.executor = Executors.newFixedThreadPool(size); } public void submit(Runnable task) { this.executor.execute(task); } public void shutdown() { ...
null
Design a web scraper using Python's BeautifulSoup library that extracts data from HTML sites.
Not applicable
#Import libraries import requests from bs4 import BeautifulSoup #Make a request to the url url = 'http://www.example.com' r = requests.get(url) soup = BeautifulSoup(r.content, 'html.parser') #Extract data data = [] for x in soup.find_all('div', class_="data-cell"): data.append(x.text.strip()) #Print the ...
null
What is the workflow of a deep learning project?
The workflow of a deep learning project typically consists of the following steps: 1. Data Collection, Preparation and Analysis: Collecting and preparing the data for the project, including data exploration, feature engineering, and data cleaning. 2. Model Design & Training: Designing the architecture of the deep learn...
null
Use the following HTML to create an unordered list.
<ul><li>First item</li> <li>Second item</li> <li>Third item</li></ul>
<ul> <li>First item</li> <li>Second item</li> <li>Third item</li> </ul>
null
Write a Python program to parse incoming JSON data and store it in a database.
{ "name": "John", "age": 30, "job": "Software Engineer" }
import json import sqlite3 data = {'name': 'John', 'age': 30, 'job': 'Software Engineer'} with sqlite3.connect("database.db") as con: cur = con.cursor() cur.execute("CREATE TABLE IF NOT EXISTS people(name TEXT, age INTEGER, job TEXT)") cur.execute("INSERT INTO people (name, age, job) VALUES (?, ?, ?)", (data['name...
[DE Wikipedia] Prowers County Das Prowers County ist ein County im Osten des US-Bundesstaats Colorado. Der Verwaltungssitz (County Seat) ist die größte Stadt des Countys, Lamar. Geographie Das County liegt im Südosten Colorados an der Grenze zum US-Bundesstaat Kansas. Im Norden grenzt das Kiowa County, im Süden Baca C...
null
null
null
null
Suggest a way to debug these lines of code.
// code int i = 0; while (i<10) { i++; System.out.println("Something is wrong!"); }
One way to debug these lines of code is to add print statements before and after the loop to print the value of "i" both before and after the loop. Then, inside the loop, you can print out the value of "i" just before the ``println`` statement and you can also print out the value of ``i`` after the loop is exited. This...
null
Evaluate the following Python program and determine its output.
arr = [20, 35, 10, 47]
[20, 35, 10, 47]
null
Use the requests library to write a Python program that sends an HTTP GET request.
url = "http://example.com"
import requests response = requests.get(url)
null
Develop a Python class for handling the API calls.
class APIHandler: def __init__(self, base_url, api_key): self.base_url = base_url self.api_key = api_key def get(self, endpoint): response = requests.get(self.base_url + endpoint) return response def post(self, endpoint, data): headers = {'Authorization': 'Bearer ' + self.api_key} response = requests.post(self.base_url...
null
Generate a machine learning model in Python to predict prices from the provided dataset.
# Load data import pandas as pd df = pd.read_csv('data.csv') # Extract features and target X = df.drop('price', axis=1).values y = df['price'].values # Split into train and test from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=...
null
Create a list comprehension in Python that takes a list of numbers and squares each number in the list.
[1, 2, 3, 4, 5]
[x**2 for x in [1, 2, 3, 4, 5]]
[DE Wikipedia] Grundwasserwerk Lobau Das Grundwasserwerk Lobau in der Unteren Lobau in Wien wurde zwischen 1964 und 1966 errichtet und wird zur Abdeckung von Verbrauchsspitzen in der Trinkwasserversorgung eingesetzt. Das Wasserwerk Lobau ist in der Lage, 80.000 Kubikmeter Trinkwasser pro Tag zu liefern. Vorgeschichte ...
null
null
null
null
Create a function that returns the maximum element of a given list.
Given List: [3, 12, 2, 6, -9]
def max_val(list): max_val = list[0] for i in range(len(list)): if list[i] > max_val: max_val = list[i] return max_val
null
Create a code to rotate an array to the right by k steps.
arr = [1,2,3,4,5], k = 3
""" Function rotate array to the right by k steps """ const rotateArray = (arr, k) => { let rotatedArray = [...arr] // Create a shallow copy of the array for (let i = 0; i < k; i++) { let lastElement = rotatedArray.pop() rotatedArray.unshift(lastElement) } return rotatedArray } console.log(rotateArray(arr, k)) // [3,4,...
null
Create a MySQL query to get the item names and their respective prices from the table "Orders".
SELECT ItemName, ItemPrice FROM Orders;
null
What is a state machine in software engineering?
A state machine in software engineering is a model of computation used to design programs and algorithms that have an input, a process, and an output. A state machine is built from a set of states, any of which can be the current state at any given time, and it transitions from one state to another in reaction to event...
null
You should write a MySQL command to count how many records in the table "users".
SELECT COUNT(*) FROM users;
[CS Wikipedia] Greta Johanssonová Anna Teresa Margareta „Greta“ Johanssonová (9. ledna 1895 Stockholm, Švédsko – 28. ledna 1978 San Mateo, Kalifornie, USA) byla švédská reprezentantka ve skocích do vody a plavání. V roce 1912 se na olympijských hrách ve Stockholmu stala vítězkou ve skocích z desetimetrové věže. Na ste...
null
null
null
null
Build a Naive Bayes classifier in Python.
import numpy as np class NaiveBayesClassifer(): def __init__(self, x, y): self.x = x self.y = y self.classes = np.unique(y) def fit(self): n_samples, n_features = self.x.shape self.class_priors = np.zeros(len(self.classes)) self.means, self.stds = [], [] ...
null
Make an executable Bash shell script to print the factorial of a given number.
#!/bin/bash # Print factorial of a given number echo "Please enter a number:" read num factorial=1 for (( i=1; i<=num; i++ )) do factorial=$[ $factorial * $i ] done echo "$num!=$factorial"
null
This program needs an array containing the first 10 numbers of the Fibonacci sequence.
let fibonacci = [0, 1]; let x = 0; let y = 1; for (let i = 1; i < 10; i++) { let z = x + y; x = y; y = z; fibonacci.push(z); }
null
Suggest a suitable language for developing iOS mobile applications.
A suitable language for developing iOS mobile applications is Swift. Swift is an Apple-developed language which is optimized for performance, and is capable of providing a great user experience on iOS devices.
null
Create a Python script to calculate the Fibonacci numbers up to a given number.
def Fibonacci(n): if n==0: return 0 if n==1: return 1 else: return Fibonacci(n-1)+Fibonacci(n-2)
null
Write a Python function to return an array of adjacent (horizontal and vertical) numbers of a given two-dimensional array.
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
def adjacent_numbers(array): # Create a set of all possible adjacent numbers # and add each array element to the set adjacent_set = set() for sublist in array: for element in sublist: adjacent_set.add(element) # Iterate over each array element and its neighbours for i in range(len(array)): for j in range(len(array[0]))...
null
Create a program in Python that prints the Fibonacci Series up to N terms, where N is a user-input number.
def fibonacci_series(N): a = 0 b = 1 if N < 0: print("Incorrect input") elif N == 0: print("Series up to 0 terms: ") else: print("Series up to", N,"terms:") for i in range(0, N): print(a, end=" ") c = a + b a = b b = c N = int(input...
null
Write a SQL query that returns all the distinct values in a given table.
table: Employees
SELECT DISTINCT * FROM Employees;
[DE Wikipedia] Hélène Huby Hélène Huby (* 2. Hälfte des 20. Jahrhunderts) ist eine französische Unternehmerin auf dem Gebiet der Raumfahrt. Leben Huby studierte Mathematik und Wirtschaftswissenschaft an der École normale supérieure. Huby arbeitete zunächst im Politik- und Mediensektor. Sie war stellvertretende Leiteri...
null
null
null
null
Build an AI assistant in Python for playing the game "Tic-Tac-Toe".
# Define the board size BOARD_SIZE = 3 # Define the player moves PLAYER_X = 'X' PLAYER_O = 'O' # Define the empty cell EMPTY = ' ' # Create a list to represent the board board = [] for i in range(BOARD_SIZE): row = [EMPTY] * BOARD_SIZE board.append(row) # Function to check the game status def chec...
null
Create an algorithm to determine if two strings are rotations of each other.
"abcde", "eabcd"
def is_rotation(str1, str2): return len(str1) == len(str2) and str2 in str1+str1
[EN Wikipedia] Deuce Carter Deuce Carter (born 28 September 1990) is a Jamaican athlete competing in the sprint hurdles. He represented his country at the 2016 Summer Olympics reaching the semifinals. His personal best in the 110 metres hurdles is 13.20 seconds (+0.2 m/s) set in Kingston in 2016. Competition record Re...
null
null
null
null
Rewrite the following JavaScript code in Python: for (let i = 1; i <= 10; i++) { console.log(i); }
Not applicable
for i in range(1, 11): print(i)
null
Given a list of numbers, write a Python program to compute the average of all numbers.
[10, 20, 45, 60]
def compute_average(numbers): sum = 0 for number in numbers: sum += number return sum/len(numbers) numbers = [10, 20, 45, 60] result = compute_average(numbers) print(result) # Output: 31.25
null
Write a code in Python for computing the edit distance between two strings.
def edit_distance(str1, str2): m = len(str1) n = len(str2) dp = [[ 0 for x in range(n+1)] for x in range(m+1)] for i in range(m+1): for j in range(n+1): if i == 0: dp[i][j] = j elif j == 0: dp[i][j] = i elif str1[i-1] == str2[...
null
Create a variable in Python and assign it the value 15.
num = 15
null
Write code to find the powers of two in a given range.
Range: 0 to 20
def powers_of_two(start, end): powers = [] current_power = 1 while current_power < end: if current_power >= start: powers.append(current_power) current_power *= 2 return powers
null
Optimize a Python algorithm to find the greatest 2 numbers from a 10000 integers list.
myList = [1, 5, 3, 7, 4, 7, 8, 9, 2, 10, 6, 8]
def get_greatest_2(items): max1 = max2 = float('-inf') for item in items: if item > max1: max1, max2 = item, max1 elif item > max2: max2 = item return max1, max2 myList = [1, 5, 3, 7, 4, 7, 8, 9, 2, 10, 6, 8] print('The greatest 2 numbers from the array:', get_greatest_2(myList)) Output: The greatest 2 numbers...
null
Write a Java program to read in a list of integers and separate them into two lists of even and odd numbers.
[1, 4, 6, 7, 8, 10, 12]
List even = [4, 6, 8, 10, 12] List odd = [1, 7]
[HI Wikipedia] दक्षिण कोरिया दक्षिण कोरिया (कोरियाई: 대한민국 (देहान मिंगुक), 大韓民國 (हंजा)), पूर्वी एशिया में स्थित एक देश है जो कोरियाई प्रायद्वीप के दक्षिणी अर्धभाग को घेरे हुए है। 'शान्त सुबह की भूमि' के रूप में ख्यात इस देश के पश्चिम में चीन, पूर्व में जापान और उत्तर में उत्तर कोरिया स्थित है। देश की राजधानी सियोल दुनि...
null
null
null
null
Reverse a string using the built-in function in R programming language.
rev_string <- function(string) { rev_string <- paste(rev(strsplit(string, "")[[1]]), sep = "") return(rev_string) }
null
Create an array with 3 elements of your choice.
my_array = ["John", 25, True]
null
Write a function in Python to shuffle an array.
[1, 2, 3, 4, 5, 6]
import random def shuffleArray(arr): # Create a copy of the array temp_arr = arr.copy() # Iterate through the array and randomly # swap elements for i in range(len(temp_arr)): j = random.randint(0, len(temp_arr)-1) temp_arr[i], temp_arr[j] = temp_arr[j], temp_arr[i] return temp_arr
null
Given a string of words, generate the n-grams of the string.
String: "Dogs are the best pet" Gram size: 2
['Dogs are', 'are the', 'the best', 'best pet']
null
Write a C++ program that prints the following pattern to the screen:
#include <iostream> int main() { // Print the pattern using nested for loop for (int i=0; i<5; i++) { for (int j=0; j<i+1; j++) std::cout << "*"; std::cout << std::endl; } return 0; } /* Output * ** *** **** ***** */
null
Create a bash script that prints out the days in a month.
#!/bin/bash for day in {1..31}; do echo "$day" done
null
Translate the following words into Spanish: "Hello", "Thank You", and "Goodbye".
Hello = Hola Thank You = Gracias Goodbye = Adiós
[HI Wikipedia] ROOT (सॉफ्टवेयर) रूट (अंग्रेजी: ROOT) सर्न द्वारा विकसित किया गया एक कम्प्यूटर अनुप्रयोग और लाइब्रेरी है। यह मूलतः कण भौतिकी के आँकड़ों के विश्लेषण के लिए तैयार किया गया था और इस क्षेत्र के कई विशेष गुण रखता है, लेकिन यह खगोल शास्त्र और डाटा माइनिंग जैसे अन्य अनुप्रयोगों में भी उपयोग होता है। विवरण रूट ...
null
null
null
null
Create a function which takes an array and removes all duplicates using a set.
[1, 2, 3, 3, 4, 4, 5]
# Create a function which takes an array and removes all duplicates using a set def remove_duplicates(arr): return list(set(arr)) arr = [1, 2, 3, 3, 4, 4, 5] new_arr = remove_duplicates(arr) print(new_arr) # [1, 2, 3, 4, 5]
null
Create a function called check_restaurant_availability that returns True if a restaurant is open and False if it's closed.
restaurant_status = { "monday": "closed", "tuesday": "open", "wednesday": "closed", "thursday": "open", "friday": "closed", "saturday": "open", "sunday": "closed" }
def check_restaurant_availability(restaurant_status): day = datetime.date.today().strftime("%A").lower() return restaurant_status[day] == "open"
null
This code is a Python module for image manipulation. To use it, import the module and create an instance of the ImageHelper class. The module provides several methods for image manipulation, including comparison, loading, cropping, bordering, resizing, colorizing, and saving. To manipulate an image, call the manipulate...
# -*- coding: utf-8 -*- import tempfile from dp_tornado.engine.helper import Helper as dpHelper class ImageHelper(dpHelper): def compare(self, i1, i2, error=0): i1 = self.load(i1) i2 = self.load(i2) if not i1 or not i2: return None s1 = i1.size s2 = i2.size...
null
What is data serialization?
Data serialization is the process of transforming data structures into a format that can be stored, transmitted, or parsed. It is commonly used to send and receive data between different types of systems. The application programming interface of a system can determine which data is serialized and deserialized.
null
Edit the following html code by bolding and italicizing the "Hello World" text.
<h1>Hello World</h1>
<h1><b><i>Hello World</i></b></h1>
null
Create a function in Python that takes two integers and returns the larger with the smaller one as its divisor.
Input integers: 10, 20
def get_larger_number_divisible_by_smaller(num1, num2): max_num = max(num1, num2) min_num = min(num1, num2) return max_num if max_num % min_num == 0 else None result = get_larger_number_divisible_by_smaller(10, 20) print(result) # 20
[EN Wikipedia] Lever (surname) Lever is a surname. Notable people with the surname include: Sir Arthur Lever, 1st Baronet (1860–1924), British politician Arthur Lever (footballer) (1920–2004), Welsh professional footballer and Wales international Asbury Francis Lever (1875–1940), member of the United States House of R...
null
null
null
null
What is a syntax error in programming?
A syntax error is an error in writing code which causes the code to be incorrect according to the programming language's syntax rules. This type of error prevents the code from being executed and can be identified by the compiler or interpreter. Examples of syntax errors include: putting a string in the wrong form, for...
[HI Wikipedia] रामायण रामायण (संस्कृत : रामायणम् = राम + आयणम् ; शाब्दिक अर्थ : 'राम की जीवन-यात्रा'), वाल्मीकि द्वारा रचित संस्कृत महाकाव्य है जिसमें श्रीराम की गाथा है। इसे आदिकाव्य तथा इसके रचयिता महर्षि वाल्मीकि को 'आदिकवि' भी कहा जाता है। संस्कृत साहित्य परम्परा में रामायण और महाभारत को इतिहास कहा गया है और दोनों...
null
null
null
null
Edit the following HTML form to add the required attribute.
<form> <input type="text" name="name"> <input type="submit" value="Submit" /> </form>
<form> <input type="text" name="name" required> <input type="submit" value="Submit" /> </form>
null
Edit the following code snippet to display the data in a structured table
data = {'name': ['John', 'Smith', 'Adam'], 'age' : [23, 45, 56]}
<table> <thead> <tr> <th>Name</th> <th>Age</th> </tr> </thead> <tbody> {% for item in data %} <tr> <td>{{ item.name }}</td> <td>{{ item.age }}</td> </tr> {% endfor %} </tbody> </table>
[CS Wikipedia] BNP Paribas Open 2018 – ženská čtyřhra Ženská čtyřhra BNP Paribas Open 2018 probíhala v první polovině března 2018. Do deblové soutěže indianwellského tenisového turnaje nastoupilo třicet dva dvojic. Obhájcem titulu byl tchajwansko-švýcarský pár Latisha Chan a Martina Hingisová, jehož členky nestartoval...
null
null
null
null
Create a Python program that uses a sentiment analysis library like TextBlob to analyze reviews provided as input and classify each review as either positive or negative.
"The product is good quality and well made."
import textblob review = "The product is good quality and well made." testimonial = textblob.TextBlob(review) sentiment = testimonial.sentiment.polarity if sentiment > 0: print("Review is positive.") elif sentiment == 0: print("Review is neutral.") else: print("Review is negative.")
null
Write a function to find the closest pair of points in a given array of points.
def find_closest_pair(points): min_dist = float('inf') closest_pair = None for i in range(len(points)): for j in range(i + 1, len(points)): dist = ((points[i][0] - points[j][0])**2 + (points[i][1] - points[j][1])**2)**0.5 if dist < min_dist: min_dist = dist closest_pair = (points[i], points[j]) return closest_pair
null
Change the given Python code to an equivalent expression using list comprehension.
mylist = [] for x in range(1, 10): mylist.append(x*x)
mylist = [x*x for x in range(1, 10)]
null
Given two strings, return True if either of the strings appears at the very end of the other string, ignoring upper/lower case differences.
str1 = "Strawberry", str2 = "berry"
def check_case_ignore(str1, str2): return str1.lower().endswith(str2.lower()) print(check_case_ignore('Strawberry', 'berry')) Output: True
null
Write a JavaScript function to find the longest common subsequence between two given sequences.
sequence1 = [1, 5, 9, 3, 2] sequence2 = [8, 2, 5, 7]
function longestCommonSubsequence(sequence1, sequence2) { let dp = []; for(let i=0; i<=sequence1.length; i++) { dp.push([]); for(let j=0; j<=sequence2.length; j++) { dp[i][j] = 0; } } for(let i=1; i<=sequence1.length; i++) { for(let j=1; j<=sequence2.length; j++) { if(sequence1[i-1] == sequence2[j-1]) { dp[i][j] =1+ dp...