text
stringlengths
141
2.89k
⌀
instruction
stringlengths
19
1.5k
⌀
input
stringlengths
0
800
⌀
output
stringlengths
1
2.5k
⌀
null
Write a Python script to scrape website text content
import requests from bs4 import BeautifulSoup url = "example.com" response = requests.get(url) html_response = response.content soup = BeautifulSoup(html_response, "html.parser") text_content = soup.find_all("p") for text in text_content: print(text.text)
[EN Wikipedia] Dřevčice Dřevčice is a municipality and village in Prague-East District in the Central Bohemian Region of the Czech Republic. It has about 800 inhabitants. References Villages in Prague-East District
null
null
null
null
Generate a loop to iterate through each character of a string in Python.
""" Generate a loop to iterate through each character of a string """ # Define a string string = 'Example string' # Iterate through the characters of the string for char in string: # Print each character print(char)
null
Create a k-Nearest Neighbors (k-NN) classifier in Python to predict whether an individual earns more or less than $50,000 per year.
[[44, 'M', 17, 0, 0, 'high school', 44000], [38, 'M', 9, 4, 0, 'Bachelor's degree', 55000], [30, 'F', 12, 2, 0, 'Master's degree', 48000]]
import numpy as np class KNNClassifier: def __init__(self, k): self.k = k def fit(self, X, y): self.X_train = X self.y_train = y def predict(self, X): predictions = [] for row in X: distances = [] for train_row in self.X_train: distances.append(np.linalg.norm(row - train_row)) sorted_distances = np....
null
Construct a python program that randomly swaps two elements within a list of numbers.
[1, 2, 3, 4, 5]
import random # input list data_list = [1, 2, 3, 4, 5] # choose two random indices i, j = random.sample(range(len(data_list)), 2) # store the values before swapping a = data_list[i] b = data_list[j] # swap two elements in a list data_list[i] = b data_list[j] = a # print the list after swapping print(data_list)
[CS Wikipedia] Corriebaatar Corriebaatar je jediným dosud známým rodem čeledi Corriebaataridae, skupiny vyhynulých multituberkulátních savců. Jediný druh rodu, C. marywaltersae byl popsán v roce 2009 paleontologem Thomasem Richem a kolegy a představuje dosud jediného známého zástupce australských multituberkulátů. Dro...
null
null
null
null
Scan through the following code in JavaScript and replace the placeholders with appropriate code.
var numbers = [1, 2, 3, 4]; for(___){ console.log(___); }
var numbers = [1, 2, 3, 4]; for(var i = 0; i < numbers.length; i++){ console.log(numbers[i]); }
[HI Wikipedia] कला कला (आर्ट) शब्द इतना व्यापक है कि विभिन्न विद्वानों की परिभाषाएँ केवल एक विशेष पक्ष को छूकर रह जाती है। कला का अर्थ अभी तक निश्चित नहीं हो पाया है, यद्यपि इसकी हजारों परिभाषाएँ की गयी है। भारतीय परम्परा के अनुसार कला उन सारी क्रियाओं को कहते हैं जिनमें कौशल अपेक्षित हो। यूरोपीय शास्त्रियों ने भी कला...
null
null
null
null
Write a SQL query to find the first name of all students enrolled in course "CSCI-203"
SELECT firstName FROM students WHERE courseName = 'CSCI-203';
null
Create a software application in Python for predicting heart failure from cardiac data.
Not applicable.
import pandas as pd from sklearn.model_selection import train_test_split from sklearn.linear_model import LogisticRegression from sklearn.metrics import accuracy_score # Load the data data = pd.read_csv('heart_data.csv') # Split the data into features (X) and the labels (Y) X = data.drop('chd', axis=1) Y = data['chd'...
null
Rewrite a provided Python function to a more Pythonic version.
def add_numbers(x, y): total = 0 for i in range(x, y): total = total + i return total
def add_numbers(x, y): return sum(range(x, y))
null
In Python, use the re module to remove the HTML tags from a given string.
String: <b>This is a bold string</b>
import re string = "<b>This is a bold string</b>" clean_string = re.sub(r'<[^>]*>', '', string) print(clean_string)
[DE Wikipedia] Lusche Lusche steht für: Lusche (Kartenspiel), Spielkarte ohne Zählwert Lusche, niederdeutsch für Pfütze Lusche, deutscher Name von Luže, Ort im Okres Chrudim, Tschechien Lusche ist der Familienname folgender Personen: Ulrich Lusche (* 1968), deutscher Rechtsanwalt und Politiker (CDU) Siehe auch: Morgen...
null
null
null
[HI Wikipedia] स्वामी विवेकानन्द {{Infobox Hindu leader |name= स्वामी विवेकानन्द | image = Swami Vivekananda-1893-09-signed.jpg |caption= <small> स्वामी विवेकानन्द शिकागो (1893) में swami Vivekananda ek nastik vyakti the. विvek ने अंग्रेजी भाषा में लिखा !: "एक असीमित, पवित्र, शुद्ध सोच एवं गुणों से परिपूर्ण उस परमात्म...
null
null
null
null
Write a C++ function that takes in a linked list and a value, and inserts the value as the head node of the list.
list = [7, 8, 10] value = 5
Node* insertFront(Node* head, int value) { Node* tmp = new Node; tmp->data = value; tmp->next = head; head = tmp; return head; }
null
Create a Regular Expression to match URLs
^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$
null
Generate a function in Python that takes an integer value from a dictionary and returns its value as a string.
{"number1": 8, "number2": 16, "number3": 20}
def get_string_value(input_dict): """Return string value in the input dictionary""" output_value = "" for key, value in input_dict.items(): output_value = str(value) return output_value
[DE Wikipedia] Home Nations Championship 1884 Die Ausgabe 1884 des Turniers Home Nations Championship in der Sportart Rugby Union (das spätere Five Nations bzw. Six Nations) fand vom 5. Januar bis 12. April statt. Turniersieger wurde England, das mit Siegen gegen alle anderen Teilnehmer die Triple Crown schaffte. Teil...
null
null
null
[HI Wikipedia] जिब्राल्टर बंदरगाह प्राधिकरण जिब्राल्टर बंदरगाह प्राधिकरण () एक जिब्राल्टर सरकार के आधीन एक स्वतंत्र संस्था है। मूल जिब्राल्टर बंदरगाह प्राधिकरण की स्थापना वर्ष 1806 में हुई थी। परन्तु निवर्तमान प्राधिकरण की स्थापना 2005 में जिब्राल्टर पोर्ट अथोरिटी एक्ट (जिब्राल्टर बंदरगाह प्राधिकरण अधिनियम) के तहत हुई...
null
null
null
null
Given a string of text, write a python script to remove all non-alphanumeric characters.
def remove_non_alphanumeric_chars(input_string): return ''.join(c for c in input_string if c.isalnum())
null
Find the average salary of the given table.
Table structure: Employee_ID Name Department Salary
SELECT AVG (Salary) FROM Employee ;
[HI Wikipedia] चम्बा, हिमाचल प्रदेश चंबा भारत के हिमाचल प्रदेश प्रान्त का एक नगर है। हिमाचल प्रदेश का चंबा अपने रमणीय मंदिरों और हैंडीक्राफ्ट के लिए सर्वविख्यात है। रवि नदी के किनारे 996 मीटर की ऊँचाई पर स्थित चंबा पहाड़ी राजाओं की प्राचीन राजधानी थी। चंबा को राजा साहिल वर्मन ने 920 ई. में स्थापित किया था। इस नगर का न...
null
null
null
null
Using Python, design an algorithm to summarize a given text.
text = "This is a piece of text, that needs to be summarized. To summarize, you need to condense the information into a shorter form, while still conveying the main points of the text. You also need to make sure that the summary retains the meaning of the original text."
def summarize(text): sentences = text.split('.') # Create a dictionary to store the number of occurrences of each word in the input word_occurrences = {} for sentence in sentences: for word in sentence.split(): if word not in word_occurrences: word_occurrences[wo...
null
Implement a text classification model in Python using the Keras library. The model should be able to classify a sentence as expressing positive or negative sentiment.
corpus = ["It is a wonderful day today","the weather is extremely bad today"] labels = [1, 0]
import numpy as np from keras.preprocessing.text import Tokenizer from keras.preprocessing import sequence from keras.models import Sequential from keras.layers import Dense, Embedding, LSTM corpus = ["It is a wonderful day today", "the weather is extremely bad today"] labels = np.array([1, 0]) # tokenize corpus tok...
[HI Wikipedia] पश्चिम बंगाल पश्चिम बंगाल () भारत के पूर्वी भाग में स्थित एक राज्य है। इसके पड़ोस में नेपाल, सिक्किम, भूटान, असम, बांग्लादेश, ओडिशा, झारखण्ड और बिहार हैं। इसकी राजधानी कोलकाता है। इस राज्य में 23 जनपद है। यहाँ की मुख्य भाषा बांग्ला है। बंगाल का इतिहास बंगाल पर इस्लामी शासन 13वीं शताब्दी से प्रारम्भ हुआ ...
null
null
null
null
Identify the most used programming language in the following data.
Java: 30%, Python: 40%, C++: 20%, JavaScript: 10%
most_used_language = "Python"
[EN Wikipedia] Surf's Up 2: WaveMania Surf's Up 2: WaveMania is a 2017 animated comedy film directed by Henry Yu. It is the sequel to the 2007 film Surf's Up. Produced by Sony Pictures Animation and WWE Studios with animation from Rainmaker Entertainment, the film received a direct-to-video release on January 17, 2017...
null
null
null
null
Write a code snippet to get the name of the planet which is the fifth planet from the sun.
name_planets = ["Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune"] fifth_planet = name_planets[4] print(fifth_planet)
null
Write a Python program to print out the current time.
Not applicable
from datetime import datetime # get the current time and print it out now = datetime.now() print(now)
[EN Wikipedia] Harry Marshall William Henry Marshall (16 February 1905 – 9 March 1959) was an English footballer who played at inside-forward. He scored 71 goals in 276 league appearances in the Football League, playing for Nottingham Forest, Southport, Wolverhampton Wanderers, Port Vale, Tottenham Hotspur, and Rochda...
null
null
null
null
Develop a Python script which extracts data from a given website.
URL: https://www.example.com
import requests from bs4 import BeautifulSoup url = "https://www.example.com" page = requests.get(url) soup = BeautifulSoup(page.content, 'html.parser') # Extract all Anchor Tags links = soup.find_all('a') # Extract all the contents of Anchors for link in links: print(link.text, link.get('href'))
null
Explain what the following code is doing.
import random def generate_random_number(): return random.randint(1, 10)
The code is defining a function called "generate_random_number" which will generate a randomly chosen integer between 1 and 10 using the randint() function from the random library.
null
Write a PHP script to print the current week number
<?php echo 'Current week number: ' . date('W'); ?>
null
Create a list comprehension in Python to extract all the even numbers from a given list.
list = [3,4,5,6,7,8]
evens_list = [num for num in list if num % 2 == 0]
null
Create a class in Python that can be used to store the details of a student.
class Student: def __init__(self, name, age, gender): self.name = name self.age = age self.gender = gender def set_details(self, name, age, gender): self.name = name self.age = age self.gender = gender def get_details(self): return f'Name: {self.name}, Age: {self.age}, Gender: {self.gender}'
[DE Wikipedia] ATP Challenger Tour 2022 In der folgenden Tabelle werden die Turniere der professionellen Herrentennis-Saison 2022 der ATP Challenger Tour dargestellt. Sie bestand aus 184 Turnieren mit einem Preisgeld zwischen 37.520 und 159.360 US-Dollar. Es war die 46. Ausgabe des Challenger-Turnierzyklus und die vie...
null
null
null
null
Write a HTML code to display a hyperlink with the text "GitHub" and point it to the github.com website.
<a href="https://github.com/">GitHub</a>
null
You need to generate an array of strings of length 5 to 10 characters.
import string import random def generate_string_array(length): # This function will generate an array of strings array_of_strings = [] for _ in range(length): new_string = ''.join(random.choice(string.ascii_lowercase) for _ in range(random.randint(5,10))) array_of_strings.append(new_string) return array_of_strings
null
Convert the given algorithm written in pseudo code to Python.
Input: Array A 1. from i=1 to i=length[A] 2. j=i 3. min = A[i] 4. for j = i+1 to length[A] 5. if min > A[j] 6. min = A[j] 7. swap A[i] with A[j]
def selection_sort(A): for i in range(len(A)): minimum = i for j in range(i+1, len(A)): if A[minimum] > A[j]: minimum = j A[i], A[minimum] = A[minimum], A[i]
[EN Wikipedia] Badminton at the 2011 SEA Games – Men's singles These are the results of the men's singles competition in badminton at the 2011 SEA Games in Jakarta. Medal winners Draw Top half Bottom half Finals References Results Badminton at the 2011 SEA Games
null
null
null
[DE Wikipedia] VfL Bergen 94 Der VfL Bergen 94 ist ein deutscher Mehrspartenverein aus Bergen auf Rügen. Heimstätte des Vereins ist das Ernst-Moritz-Arndt-Stadion, welches 4000 Zuschauern Platz bietet. Verein (Fußball) Der VfL Bergen wurde 1938 als Einheit Bergen gegründet. Nach der 1945 erfolgten Auflösung wurde der ...
null
null
null
[CS Wikipedia] Překlad Překlad (translace) je písemný převod (zpravidla také psaného) originálního textu z jednoho jazyka do druhého provedený překladatelem. Rozlišuje se přitom především obor originálu, zda jde o text umělecký, odborný, populárně-naučný, administrativní, náboženský, návod na použití přístroje apod. N...
null
null
null
null
Develop a numerical optimization algorithm in Python to minimize the cost of a given function.
The function to be minimized is f(x) = x^2 + 2x + 3
# Import the required libraries import numpy as np # Define the objective function def f(x): return np.square(x) + 2*x + 3 # Define the optimization algorithm def opt(f, x0, lr, n_iter): x = x0 for i in range(n_iter): x_prev = x grad = 2 * x + 2 x = x - lr * grad if np.abs(x - x_prev) < 1e-5: break # Print t...
null
Create a Python class to represent a person and its details.
class Person: def __init__(self, name, age): self.name = name self.age = age def describe_person(self): print(f"Name: {self.name}, Age: {self.age}")
[HI Wikipedia] पी॰ वी॰ नरसिम्हा राव पामुलापति वेंकट नरसिंह राव (जन्म- 28 जून 1921, मृत्यु- 23 दिसम्बर 2004) भारत के 09 वें प्रधानमंत्री के रूप में जाने जाते हैं। 'लाइसेंस राज' की समाप्ति और भारतीय अर्थनीति में खुलेपन उनके प्रधानमंत्रित्व काल में ही आरम्भ हुआ। ये आन्ध्रा प्रदेश के मुख्यमंत्री भी रहे। इनके प्रधानमंत्री ...
null
null
null
[CS Wikipedia] Mechanika tuhého tělesa Mechanika tuhého tělesa (mechanika dokonale tuhého tělesa, popř. také stereomechanika) je část mechaniky, která se zabývá pohybem tuhého tělesa a silami na ně působícími. Skutečná pevná tělesa jsou soubory atomů a molekul vázaných jistými vnitřními silami, které je možné vnější s...
null
null
null
null
Create a Python script that accesses a website's HTML.
# Import the requests library import requests # Get the website's content r = requests.get('https://www.example.com/') # Get the webpage's HTML html = r.text # Print the HTML print(html)
null
Write a Python script for combining two dictionaries.
dict1 = { "a" : 1, "b" : 2 } dict2 = { "c" : 3, "d" : 4 }
def combine_dicts(dict1, dict2): new_dict = dict1.copy() new_dict.update(dict2) return new_dict dict1 = { "a" : 1, "b" : 2 } dict2 = { "c" : 3, "d" : 4 } print(combine_dicts(dict1, dict2))
null
Given a list of integers, find the lengthiest common substring of the list.
[1, 2, 3, 4, 5, 3, 2, 6]
The longest common substring of the list [1, 2, 3, 4, 5, 3, 2, 6] is "3, 2". The length of the common substring is 3.
[HI Wikipedia] रवीन्द्रनाथ ठाकुर की कृतियाँ रवीन्द्रनाथ ठाकुर का सृष्टिकर्म काव्य, उपन्यास, लघुकथा, नाटक, प्रबन्ध, चित्रकला और संगीत आदि अनेकानेक क्षेत्रों में फैला हुआ है। उपन्यास {| class="wikitable" |- ! उपन्यास ! रचनाकाल ! अन्य तथ्य ! हिन्दी अनुवाद |- | करुणा | १८८० | रवीन्द्रनाथ ठाकुर का पहला (लघु) उपन्यास। इसके ...
null
null
null
null
Calculate the running average of a given array of data.
[1,6,3,5,2,7,8]
def calculate_running_average(arr): running_sum = 0 for i in range(len(arr)): running_sum += arr[i] arr[i] = running_sum / (i+1) return arr arr = [1, 6, 3, 5, 2, 7, 8] calculate_running_average(arr) # Returns [1.0, 3.5, 3.0, 3.75, 3.2, 4.16, 4.43]
null
Modify the following program to output the 3 most frequency words.
words = 'It is very important to be pythonic when writing python code.' word_dict = {} for word in words.split(): if word in word_dict: word_dict[word] += 1 else: word_dict[word] = 1
words = 'It is very important to be pythonic when writing python code.' word_dict = {} for word in words.split(): if word in word_dict: word_dict[word] += 1 else: word_dict[word] = 1 sorted_words = sorted(word_dict, key = lambda x: word_dict[x], reverse = True) print("The three most frequent w...
null
Create a dictionary with two keys and a list of values assigned to each key.
my_dict = { "key1": [1, 2, 3], "key2": [4, 5, 6] }
[HI Wikipedia] सुवर्णरेखा नदी सुवर्णरेखा या स्वर्णरेखा भारत के झारखण्ड, पश्चिम बङ्गाल और ओड़िशा राज्यों में बहने वाली एक नदी है। विवरण यह राँची नगर से 16 किलोमीटर दक्षिण-पश्चिम में स्थित नगड़ी गाँव में रानी चुआं नामक स्थान से निकलती है और उत्तर पूर्व की ओर बढ़ती हुई मुख्य पठार को छोड़कर प्रपात के रूप में गिरती है। इस ...
null
null
null
[CS Wikipedia] Kazatelská stanice Českobratrské církve evangelické ve Velké Lhotě u Dačic Kazatelská stanice Českobratrské církve evangelické ve Velké Lhotě u Dačic je kazatelskou stanicí Farního sboru Českobratrské církve evangelické v Telči. Kazatelská stanice vznikla roku 2016 přeměnou dosavadního Farního sboru Čes...
null
null
null
null
Design a program in Python to search a tree using a Breadth-First Search.
def BFS(tree, item): # Create an empty queue for BFS queue = [] # Enqueue the root of tree queue.append(tree) # Do till the queue is empty while(len(queue) > 0): # Dequeue an item from queue item = queue.pop(0) # If the dequeued item is the item we are looking for t...
null
How can you validate a credit card number using JavaScript?
You can validate a credit card number using JavaScript with the Luhn algorithm. The Luhn algorithm is a simple checksum formula that can be used to validate various identification numbers, such as credit card numbers, National Provider Identifier (NPI) numbers, and Canadian Social Insurance Numbers (SINs).
[CS Wikipedia] Zapp Zapp (Zapp Band, Zap & Roger) je funková hudební skupina, založená v roce 1978 bratry Lesterem, Larrym, Rogerem, Tonym a Terrym Troutmanovými. Jejich hity jako "More Bounce to the Ounce", "Dance Floor, Part 1" či "Computer Love", pomohl ve vývoji West coast hip hopu a G-funku. především díky použit...
null
null
null
null
Amend the following Python function to calculate the sum of all even numbers in the given range.
def sum_even_numbers(n): '''This function will calculate the sum of all numbers in the given range.''' total = 0 for i in range(n): total += i return total
def sum_even_numbers(n): '''This function will calculate the sum of all even numbers in the given range.''' total = 0 for i in range(n): if i%2==0: total += i return total
[EN Wikipedia] Luís de Almeida (diplomat) Luís de Almeida served as the Angolan government's top diplomat to Europe during the 1980s. A career ambassador, he represented Angola in France, West Germany, Morocco, the Netherlands, and the Community of Portuguese-Speaking Countries. Early life Born in Gabela-Amboim, provi...
null
null
null
null
Generate a function in Python to calculate the total price of an online order. The function should take an array of items and item prices as input and return the total price as output.
Input array of items: ["T-shirt","Jeans","Shoes"], item prices: [30,45,100]
def calculate_total_price(items, prices): total = 0 for i in range(len(items)): total += prices[i] return total total = calculate_total_price(["T-shirt","Jeans","Shoes"], [30,45,100]) print("The total price is:", total)
[HI Wikipedia] माशेरब्रुम माशेरब्रुम पाक अधिकृत कश्मीर के बल्तिस्तान क्षेत्र में स्थित काराकोरम पर्वतों के माशेरब्रुम पर्वत समूह का सबसे ऊँचा पर्वत है। ७,८२१ मीटर (२५,६५९ फ़ुट) की बुलंदी के साथ यह विश्व का २२वाँ सबसे ऊँचा और पाकिस्तान-नियंत्रित क्षेत्रों का ९वाँ सबसे ऊँचा पहाड़ है। इसे के१ (K1) भी बुलाया जाता है क्यों...
null
null
null
null
Suppose we have a dictionary with keys (1,2,3). Create a function to return the values of the dictionary.
d = {1: "one", 2: "two", 3: "three"}
def get_values(d): return list(d.values())
null
Build an AI chatbot using Python and Dialogflow.
Not applicable
import os import json #import the packages from flask import Flask, request #initialization app = Flask(__name__) @app.route('/webhook', methods=['GET', 'POST']) def webhook(): #handle user message req = request.get_json(silent=True, force=True) user_input = req["queryResult"]["queryText"] result = { "fulfill...
null
Write a Python program to group a given list of integers into sublists of given size.
list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], size = 3
def group_list(mylist, n): newlist = [] # create a list of indices for sublists indices = list(range(0, len(mylist), n)) # create sublists too for start in indices: end = start + n newlist.append(mylist[start:end]) return newlist ...
null
An array of integers is given, write a function to print the second largest element of the array.
def secondLargest(arr): first = 0 second = 0 for i in range(len(arr)): if arr[i] > first: second, first = first, arr[i] elif (arr[i] > second and arr[i] < first): second = arr[i] return second
null
Generate a python code to print out all prime numbers between 1 to 100.
for num in range(2, 101): for i in range(2,num): if (num % i) == 0: break else: print(num, end=' ') # Output : 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
null
Write a function in Java to check if the length of a string is greater than 5.
String str = "Hello World!"
public static boolean isStringLongerThan5(String str) { return str.length() > 5; }
null
Create a program to determine if a number is divisible by another number
def is_divisible(n, m): if n % m == 0: return True return False
null
Edit the sentence using the correct punctuation.
The apple is red
The apple is red.
null
Generate a valid syntax to remove the last element of a list
my_list.pop()
null
Load the given JSON data using Javascript.
{ "name": "John", "age": 30 }
var data = { "name": "John", "age": 30 }; var jsonData = JSON.parse(data); console.log(jsonData);
null
Create a code snippet in Python to find the missing number in an array of length n-1 when all numbers from 1 to n are present.
[7, 5, 6, 4, 2]
def missing_number(nums): full_list = list(range(1,len(nums)+1)) return (set(full_list) - set(nums)).pop() nums = [7, 5, 6, 4, 2] result = missing_number(nums) print('Missing number is', result)
[EN Wikipedia] Tāngarākau River The Tāngarākau River is a river of the Manawatū-Whanganui region of New Zealand's North Island. It flows south for from its source west of Ōhura in the King Country to reach the Whanganui River. State Highway 43, known as the Forgotten World Highway, travels through the Tāngarākau Gorge...
null
null
null
null
Generate code that implements a method to compare two strings.
def compare_strings(str1, str2): if len(str1) != len(str2): return False for i in range(len(str1)): if str1[i] != str2[i]: return False return True
null
Create a Python program that generates lyrics for a song.
Not applicable
import random # A list of words, that the program can use to generate lyrics words = ["Love", "Life", "Dreams", "Happiness", "Joy", "Home", "Friends", "Family", "Success", "Believe", "Magic", "Laughter", "Together", "Memories", "Adventure", "Appreciate", "Peace", "Passion", "Courage", "Forever"] # Generate a song wit...
null
Write a function in JavaScript that returns the longest item in the array.
["a", "ab", "abc", "abcd"]
function longestItem(arr) { // Initializing the longest item to the first item in the array for comparison let longest = arr[0]; for (let item of arr) { // Comparing the length of each item to the longest if (item.length > longest.length) { longest = item; } } return longest; } console.log(longestItem(["a", "ab", "abc"...
null
Write a query to extract data from a table called "inventory" which contains the columns: id, item, quantity
SELECT id, item, quantity FROM inventory
[HI Wikipedia] पटना संग्रहालय पटना म्यूजियम बिहार की राजधानी पटना में स्थित है। इसका निर्माण १९१७ में अंग्रेजी शासन के समय हुआ था ताकि पटना और आसपास पाई गई ऐतिहासिक वस्तुओं को संग्रहित किया जा सके। स्थानीय लोग इसे 'जादू घर' कहते हैं। मुगल-राजपूत वास्तुशैली में निर्मित पटना संग्रहालय को बिहार की बौद्धिक समृद्धि का प्रत...
null
null
null
null
Using Python, build a dictionary containing the numbers from 1 to n as the key and the square of each number as the value.
n = 10
my_dict = {} for i in range(1,n+1): my_dict[i] = i**2 print(my_dict)
null
How can you make a dictionary key iterable in Python?
A dictionary in Python can be made iterable using a for loop. To iterate over the keys of a dictionary, we can use the ``dict.keys()`` method which returns an iterable object of the keys in the dictionary. This iterable can then be used to iterate over the keys of the dictionary.
[CS Wikipedia] Jessica Barden Jessica Barden (* 21. července 1992 Northallerton, Severní Yorkshire) je britská herečka. Mezi její nejznámější role patří Alyssa v seriálu The End of the F***ing World a Justine v Penny Dreadful. Životopis Narodila se v Northallertonu v Severním Yorkshiru a v roce 1995 se s rodiči přestě...
null
null
null
[CS Wikipedia] Ida B. Wells Ida Bell Wells-Barnett (16. července 1862 Holly Springs – 25. března 1931 Chicago), spíše známá jako Ida B. Wells, byla africko-americká novinářka, muckrakerka, sufražetka, feministka, zastánkyně georgismu a vůdkyně Afroamerického hnutí za občanská práva. V roce 1909 založila National Assoc...
null
null
null
null
Write a PHP script to get the length of a string.
string = "Hello World!"
<?php $string = "Hello World!"; echo strlen($string); ?>
[DE Wikipedia] Baschir Schihab II. Baschir Schihab II. (; geb. 2. Januar 1767; gest. 1850) war ein libanesischer Emir, der in der ersten Hälfte des 19. Jahrhunderts den osmanischen Libanon regierte. Er war der erste Herrscher, der vom sunnitischen Islam, der Religion der früheren schihabischen Emire, zur maronitischen...
null
null
null
null
Create an array of four different colors in JavaScript.
let colors = ["red", "green", "blue", "yellow"];
null
Edit the given code to limit the output to only the 30 most recent entries in the database.
entries = db.execute_query("SELECT * FROM users")
entries = db.execute_query("SELECT * FROM users ORDER BY id DESC LIMIT 30")
null
Multiply two vectors of the same size.
Vector1 = [1, 2, 3] Vector2 = [4, 5, 6]
resultantVector = [4, 10, 18]
[DE Wikipedia] Edelgard Huber-von Gersdorff Edelgard Ida Valeska Huber-von Gersdorff (* 7. Dezember 1905 in Gera, als Edelgard Ida Valeska von Gersdorff; † 9. April 2018 in Karlsruhe) war eine Supercentenarian und zeitweise die älteste lebende deutsche Frau. Sie war am Tag ihres Todes 112 Jahre und 123 Tage alt und ge...
null
null
null
[CS Wikipedia] Ileana Silaiová Ileana Silaiová (* 14. října 1941, Kluž) je bývalá rumunská atletka, běžkyně, halová mistryně Evropy v běhu na 1500 metrů. Sportovní kariéra Startovala celkem na čtyřech olympijských hrách. Největšího úspěchu dosáhla hned při premiéře v Mexiku, kde získala stříbrnou medaili v běhu na 800...
null
null
null
null
Write a function in Python to generate random numbers within a desired range.
import random # define a function to generate random numbers def generate_random(start, end): return random.randint(start, end) # generate a random number in the given range start = 10 end = 15 print(generate_random(start, end))
[DE Wikipedia] Liste der Naturdenkmale in Roigheim Die Liste der Naturdenkmale in Roigheim nennt die verordneten Naturdenkmale (ND) der im baden-württembergischen Landkreis Heilbronn liegenden Gemeinde Roigheim. In Roigheim gibt es insgesamt vier als Naturdenkmal geschützte Objekte, davon zwei flächenhafte Naturdenkma...
null
null
null
null
Create a PoS tagging tool with Python and NLTK which takes a sentence as an input and tags each word with its part-of-speech (POS) category.
The quick brown fox jumps over the lazy dog
from nltk.tokenize import word_tokenize from nltk.tag import pos_tag sentence = "The quick brown fox jumps over the lazy dog" words = word_tokenize(sentence) print(pos_tag(words)) Output: [('The', 'DT'), ('quick', 'JJ'), ('brown', 'NN'), ('fox', 'NN'), ('jumps', 'VBZ'), ('over', 'IN'), ('the', 'DT'), ('lazy', 'JJ')...
null
Write a RegEx to extract text inside tags
<div>This is a test</div>
\<div\>(.*?)\</div\>
null
Create a program that implements a Stack (LIFO) using an array
class Stack: def __init__(self): self.stack = [] def push(self, item): self.stack.append(item) def pop(self): if self.is_empty(): return None return self.stack.pop() def is_empty(self): return len(self.stack) == 0
null
Construct a Java program for sorting a given array in ascending order.
public class ArraySort { public static int[] sortArray(int[] arr) { int n = arr.length; for (int i = 0; i < n - 1; i++) { int min_idx = i; for (int j = i + 1; j < n; j++) if (arr[j] < arr[min_idx]) min_idx = j; int temp = arr[min_idx]; arr[min_idx] = arr[i]; arr[i] = temp; } return arr; } }
null
Generate a Python code snippet for sorting an array of strings in ascending alphabetical order.
["apple", "banana", "orange", "kiwi"]
def sort_words(words): # Sort the list in ascending alphabetical order. sorted_words = sorted(words) # Return the sorted list. return sorted_words words = ["apple", "banana", "orange", "kiwi"] sorted_words = sort_words(words) print(sorted_words)
[CS Wikipedia] Setrvačnost Setrvačnost je vlastnost hmotných těles (těles s hmotností), která se snaží setrvat ve stavu před vnějším fyzikálním působením, tj. v případě, že na těleso nepůsobí žádná vnější síla. Jinými slovy, jedná se o odpor tělesa vůči změně jeho rychlosti. V mechanice můžeme setrvačnost popsat jako ...
null
null
null
null
Create a feature for predicting a customer's subscription plan based off their purchase history.
The customer has purchased 2 shirts, 1 hat, and 3 pairs of jeans in the past month.
The prediction feature should calculate the customer's current subscription plan by taking into account the items they have purchased. It could use factors such as item types, quantity of items purchased, time since purchase, cost of items, sale promotions, combinations of items, and so forth. The feature should use a ...
null
How would you insert an element into a pre-existing array using JavaScript?
An element can be inserted into a pre-existing array using the JavaScript Array.prototype.push() method. The push() method takes a single element as an argument and appends it to the end of the array. For example, to insert the value 7 into an array, you could use the following syntax: array.push(7);