Add calculator and weather API scripts in JavaScript and Python

This commit is contained in:
vista-man
2025-01-27 18:04:20 +01:00
parent aeb58e9cb0
commit f829630017
8 changed files with 251 additions and 0 deletions

View File

@@ -0,0 +1,50 @@
const readline = require("readline");
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
function calculator() {
rl.question("Enter operation (add, subtract, multiply, divide): ", (operation) => {
rl.question("Enter the first number: ", (first) => {
const num1 = parseFloat(first);
rl.question("Enter the second number: ", (second) => {
const num2 = parseFloat(second);
let result;
switch (operation.toLowerCase()) {
case "add":
result = num1 + num2;
break;
case "subtract":
result = num1 - num2;
break;
case "multiply":
result = num1 * num2;
break;
case "divide":
if (num2 !== 0) {
result = num1 / num2;
} else {
console.error("Error: Division by zero is not allowed.");
rl.close();
return;
}
break;
default:
console.error("Invalid operation. Please enter add, subtract, multiply, or divide.");
rl.close();
return;
}
console.log(`Result: ${result}`);
rl.close();
});
});
});
}
calculator();

84
Python/api/api.py Normal file
View File

@@ -0,0 +1,84 @@
import requests
import time
import sys
# Class to handle logging to multiple files
class Tee:
def __init__(self, *files):
# Initialize with a list of file objects to write to
self.files = files
def write(self, obj):
# Write the given object to all files and flush the output
for f in self.files:
f.write(obj)
f.flush()
def flush(self):
# Flush the output for all files
for f in self.files:
f.flush()
def close(self):
# Close all files
for f in self.files:
f.close()
# Function to get the latitude and longitude of a city using OpenWeatherMap API
def get_coordinates(city_name):
api_key = 'cf2b92cba5cdb89baccb2fe05cacb3a5' # API key for OpenWeatherMap
base_url = 'http://api.openweathermap.org/geo/1.0/direct' # Base URL for geocoding API
params = {
'q': city_name, # City name to query
'appid': api_key # API key parameter
}
response = requests.get(base_url, params=params) # Make a GET request to the API
if response.status_code == 200:
data = response.json() # Parse the JSON response
if data:
# Return the latitude and longitude of the first result
return data[0]['lat'], data[0]['lon']
else:
# Print an error message if the city is not found
print(f"City {city_name} not found.")
return None, None
else:
# Print an error message if the API request fails
print(f"Failed to get coordinates for city {city_name}. Error code: {response.status_code}")
return None, None
# Function to get the weather data for given coordinates using OpenWeatherMap API
def get_weather(lat, lon):
api_key = 'cf2b92cba5cdb89baccb2fe05cacb3a5' # API key for OpenWeatherMap
base_url = 'https://api.openweathermap.org/data/2.5/weather' # Base URL for weather API
params = {
'lat': lat, # Latitude parameter
'lon': lon, # Longitude parameter
'appid': api_key, # API key parameter
'units': 'metric' # Units parameter to get temperature in Celsius
}
response = requests.get(base_url, params=params) # Make a GET request to the API
if response.status_code == 200:
data = response.json() # Parse the JSON response
# Print the weather information
print(f"Weather at coordinates ({lat}, {lon}):")
print(f"Temperature: {data['main']['temp']}°C")
print(f"Weather: {data['weather'][0]['description']}")
else:
# Print an error message if the API request fails
print(f"Failed to get weather data for coordinates ({lat}, {lon}). Error code: {response.status_code}")
# Main function to get city name input from the user and fetch weather data
if __name__ == "__main__":
with open('py.log', 'w') as log_file:
tee = Tee(sys.stdout, log_file)
sys.stdout = tee
city_name = input("Enter city name: ") # Prompt the user to enter a city name
lat, lon = get_coordinates(city_name) # Get the coordinates of the city
if lat is not None and lon is not None:
get_weather(lat, lon) # Get the weather data for the coordinates
# Sleep for 5 seconds before exiting to ensure all logs are written
time.sleep(5)
tee.close() # Close the Tee object to ensure all files are properly closed

3
Python/api/py.log Normal file
View File

@@ -0,0 +1,3 @@
Enter city name: Weather at coordinates (50.87489555, 6.05938669638836):
Temperature: 11.28°C
Weather: scattered clouds

View File

@@ -0,0 +1 @@
print("Deez"[::-1]) # Output: "olleh"

View File

@@ -0,0 +1,11 @@
def is_palindrome(word):
return word == word[::-1]
# Vraag de gebruiker om een woord in te voeren
input_word = input("Voer een woord in: ")
# Controleer of het woord een palindroom is en geef het resultaat weer
if is_palindrome(input_word):
print(f"{input_word} is een palindroom.")
else:
print(f"{input_word} is geen palindroom.")

View File

@@ -0,0 +1,19 @@
def is_prime(num):
if num <= 1:
return False
for i in range(2, int(num**0.5) + 1):
if num % i == 0:
return False
return True
def generate_primes(N):
primes = []
for num in range(2, N + 1):
if is_prime(num):
primes.append(num)
return primes
# Vraag de gebruiker om een getal N
N = int(input("Voer een getal N in: "))
priemgetallen = generate_primes(N)
print(f"Priemgetallen tot {N}: {priemgetallen}")

49
Python/scrape/scrape.py Normal file
View File

@@ -0,0 +1,49 @@
import os
import requests
import time
from bs4 import BeautifulSoup
# Vraag de gebruiker om de URL van de nieuwswebsite
url = input("Voer de URL van de nieuwswebsite in: ")
# Controleer of de URL begint met 'www.' of 'ww2.', zo niet, voeg 'www.' toe
if not (url.startswith('www.') or url.startswith('ww2.')):
url = 'www.' + url
# Controleer of de URL begint met 'https://', zo niet, voeg het toe
if not url.startswith('https://'):
url = 'https://' + url
# Haal de inhoud van de webpagina op
try:
response = requests.get(url)
response.raise_for_status() # Raise an HTTPError for bad responses
webpage = response.content
except requests.exceptions.RequestException as e:
print(f"Fout bij het ophalen van de webpagina: {e}")
exit()
# Parse de webpagina met BeautifulSoup
soup = BeautifulSoup(webpage, 'html.parser')
# Zoek alle titels van nieuwsartikelen (pas de selector aan op basis van de HTML-structuur van de website)
titles = soup.find_all('h2') # Pas deze selector aan indien nodig
# Bepaal het pad van het huidige script
script_dir = os.path.dirname(os.path.abspath(__file__))
# Bepaal het pad van het bestand titels.txt in dezelfde directory
file_path = os.path.join(script_dir, 'titels.txt')
# Controleer of er titels zijn gevonden
if not titles:
print("Geen titels gevonden. Controleer de HTML-structuur van de website en pas de selector aan.")
else:
# Open het bestand titels.txt in append-modus
with open(file_path, 'a', encoding='utf-8') as file:
# Schrijf de titels van de nieuwsartikelen naar het bestand
for title in titles:
file.write(title.get_text(separator=' ') + '\n')
print(f"De titels zijn toegevoegd aan {file_path}")
time.sleep(2) # Wacht 5 seconden voordat het script wordt afgesloten

34
Python/scrape/titels.txt Normal file
View File

@@ -0,0 +1,34 @@
Dodental van hotelbrand in Turks skioord loopt op tot 66
Ook gratie voor Capitoolbestormers die jarenlange celstraffen kregen
Driekwart gemeenten krijgt begroting niet rond, keuzes uitgesteld
Amerikaanse president heeft eigen munt: 'Best wel eng dat dit kan'
WHO-exit en rem op immigratie: de eerste decreten van Trump
Start presidentschap Trump
Streep door sancties tegen extremisten op Westoever • 915 trucks met hulpgoederen op dag 2 bestand
Gevaar in Los Angeles houdt aan door sterke wind, nieuwe branden geblust
Doden bij aardverschuivingen en overstromingen op Java en Bali
Prins Harry's rechtszaak tegen krant van mediamagnaat Murdoch begint
Formule 1-team Haas schrijft geschiedenis met eerste vrouwelijke race-engineer
Kijken
Oude Duitse oorlogsradar gaat na reparatie terug naar Terschelling
Formatie Oostenrijk in nieuwe fase, rechts-radicale bondskanselier stap dichterbij
Helft van jongvolwassenen noemt mentale gezondheid niet goed
Nieuwe wet moet einde maken aan kat-en-muisspel rond designerdrugs
NSC komt met voorstel voor referenda over nieuw pensioenstelsel
Wie is Dana White, de vechtsportbaas en vertrouweling van Donald Trump?
Alles in puin: de verwoesting in Gaza in beeld
Titelhoudster Sabalenka ontsnapt: in drie sets naar halve finales Australian Open
Pechvogel Van Baarle breekt sleutelbeen in eerste etappe van wielerseizoen
Australische regering houdt spoedberaad na antisemitische aanvallen
PSV laat zich geen crisis aanpraten: 'We hebben het heilige vuur nog steeds'
Dubbelspecialist Verbeek verrassend naar halve finales Australian Open
KNWU bezuinigt op beloften: geen Nederlandse jeugd naar WK in Rwanda
TikTok in VS niet op zwart, maar ook na ingrijpen Trump in grijs gebied
Uitgelegd
Sport
Gemist?
Collecties
Laatste nieuws
NOS informatie
Nieuws
Sport