Snippets Collections
from pydantic import BaseModel, Field
from uuid import UUID, uuid4

class item(BaseModel):
    name : str
    price : float
    item_id : UUID = Field(default_factory = uuid4)


items = []

for i in range(3):
    items.append(item(name = 'test', price = 20))


print(items)
# Analyzing Clicks A Python Function for Extracting Weekly Stats

users_data = [
    {'day': 0, 'clicks': 100}, {'day': 1, 'clicks': 10},
    {'day': 2, 'clicks': 150}, {'day': 3, 'clicks': 1000},
    {'day': 4, 'clicks': 100}, {'day': 5, 'clicks': 190},
    {'day': 6, 'clicks': 150}, {'day': 7, 'clicks': 1000}
]

def get_stats(day):
    # -1 to start from day 0 because day in date is 1
    return users_data[day - 1: day + 7]

print(get_stats(1))
import sqlite3

# Connect to the database
con = sqlite3.connect('database.db')

# Create a cursor object
cursor = con.cursor()

# Define the data to be inserted as a list of tuples
data = [
    ('John Doe', 'johndoe@example.com'),
    ('Jane Smith', 'janesmith@example.com'),
    ('Mike Johnson', 'mikejohnson@example.com')
]

# Use executemany() to insert the data into the "users" table
cursor.executemany("INSERT INTO users (name, email) VALUES (?, ?)", data)

# Commit the changes
con.commit()
import sqlite3

# Connect to the database
con = sqlite3.connect('database.db')

# Create a cursor object
cursor = con.cursor()

# Update user name based on ID
user_id = 2
new_name = "John Doe"

cursor.execute("UPDATE users SET name = ? WHERE id = ?", (new_name, user_id))

# Commit the changes
con.commit()
import sqlite3

# Connect to the database
con = sqlite3.connect('database.db')

# Create a cursor object
cursor = con.cursor()

# Fetch all data from the "users" table
cursor.execute("SELECT * FROM users")
data = cursor.fetchall()

# Print the retrieved data
for row in data:
    print(row)
import sqlite3

# Connect to the database
con = sqlite3.connect('database.db')

# Create a cursor object
cursor = con.cursor()

# Delete user based on ID
user_id = 123

cursor.execute("DELETE FROM users WHERE id = ?", (user_id,))

# Commit the changes
con.commit()
import sqlite3

# Connect to the database
con = sqlite3.connect('database.db')

# Create a cursor object
cursor = con.cursor()

# Fetch data based on the ID filter
cursor.execute("SELECT * FROM users WHERE id = ?", (123,))
data = cursor.fetchall()

# Print the retrieved data
for row in data:
    print(row)

import sqlite3

# Connect to the database
con = sqlite3.connect('database.db')

# Create a cursor object
cursor = con.cursor()

# Create a cursor object
cursor = con.cursor()

# Insert a new user
cursor.execute("INSERT INTO users (name, email) VALUES (?, ?)", ("John Doe", "johndoe@example.com"))

# Commit the changes
con.commit()

from docx import Document
import pandas as pd

df = pd.read_csv('out.csv').to_dict()
word_doc = Document()

table_head = list(df.keys())

table_head_len = len(table_head)
tables_rows_len = len(df['name'])

# create tabel
table = word_doc.add_table(cols = table_head_len, rows = tables_rows_len)

# add the first row in the table
for i in range(table_head_len):
    table.cell(row_idx = 0, col_idx = i).text = table_head[i]


# add rows for name col
for i in range(1, tables_rows_len):
    table.cell(row_idx = i, col_idx = 0).text = df['name'][i]


# add rows for age col
for i in range(1, tables_rows_len):
    table.cell(row_idx = i, col_idx = 1).text = str(df['age'][i])


word_doc.save('word_doc.docx')
Feeling anxious about online exams? Get valuable online exam help with MyAssignmentHelp.Co.Uk! Learn tips, strategies, and discover resources to maximize your preparation and boost your confidence on exam day.
myData = [
    {'a': 1},
    {'a': 1},
    {'b': 1},
    {'b': 1},
    {'c': 1},
    {'c': 1},
]

# Use a set to track seen tuples of items (key-value pairs as tuples)
seen = set()
unique_data = []

for d in myData:
    # Convert each dictionary to a tuple of its items, then convert to frozenset
    # to make it hashable and suitable for use in a set
    dict_items = frozenset(d.items())
    
    # Check if the frozenset of items is already in the set
    if dict_items not in seen:
        # If not seen, add to both set and result list
        seen.add(dict_items)
        unique_data.append(d)

print(unique_data)
import pandas as pd

dict_data = {
    'users': ['user_123', 'user_abc'],
    'tasks': ['test1', 'test2']
}

df = pd.DataFrame.from_dict(dict_data)
df.to_html('out.html')
import pandas as pd

dict_data = {
    'users': ['user_123', 'user_abc'],
    'tasks': ['test1', 'test2']
}

df = pd.DataFrame.from_dict(dict_data)
df.to_pickle('out.pkl')

# read pkl file
print(pd.read_pickle('out.pkl'))
import pandas as pd

# All arrays must be of the same length
dict_data = {
    'users': [{'name': 'test'}, {'name': '123'}], 
    'tasks': [{'name': 'test123'}, {'name': '45456'}]
}

df = pd.DataFrame.from_dict(dict_data)
df.to_json('out.json', indent = 4)
from random import randint
from faker import Faker
from datetime import date
import pandas as pd

f = Faker()

s_date = date(2018, 5, 1)
e_date = date(2018, 5, 30)

dict_data = {'date': [], 'email': [], 'money': []}

for _date in pd.date_range(start = s_date, end = e_date):
    dict_data['date'].append(_date)
    dict_data['email'].append(f.email())
    dict_data['money'].append(randint(1, 100) * 0.99)

df = pd.DataFrame.from_dict(dict_data)
df.to_csv('out.csv', index = 0)
from human_readable.files import file_size
import os

print(file_size(value = os.stat('test.txt').st_size))
import pause

def test():
    print('done')

def run_after(func, amount_of_time):
    pause.milliseconds(amount_of_time)
    func()

run_after(test, 10000)
from textblob import TextBlob

text = 'how are you'

blob = TextBlob(text)

if blob.polarity > 0:
    print('Positive')
elif blob.polarity < 0:
    print('Negative')
else:
    print('Neutral')
users_db = [
    {'id': '2313', 'coins': 50},
    {'id': '8213', 'coins': 20},
    {'id': '9989', 'coins': 0},
    {'id': '4654', 'coins': 1},
    {'id': '7897', 'coins': 3},
    {'id': '9898', 'coins': 60}
]

users_db.sort(key = lambda user: user['coins'])
print(users_db)
users_db = [
    {'id': 'ax123', 'money': 5},
    {'id': 'z5541', 'money': 0}
]

def get_user_by_id(user_id):
    for user in users_db:
        if user['id'] == user_id:
            return user
        
def send_money(from_id, to_id, amount):
    from_user_a = get_user_by_id(from_id)
    to_user_b = get_user_by_id(to_id)

    if from_user_a and to_user_b:
        if from_user_a['money'] >= amount:
            from_user_a['money'] -= amount
            to_user_b['money'] += amount
        else:
            print('the amount of money is large than your balance')
        
    

send_money('ax123', 'z5541', 2)
send_money('ax123', 'z5541', 2)
print(users_db)
from faker import Faker
from random import randint, choice

f = Faker()
payment_methods = ['paypal', 'bitcoin']

for _ in range(20):
    money = randint(1, 100) * 0.99
    pyment_method = choice(payment_methods)
    user_email = "*****" + f.email()[6:]
    print(f'{money}$ --- {user_email} --- {pyment_method}')
# Quotes API
from fastapi import FastAPI, Request
from slowapi.util import get_ipaddr
from slowapi.errors import RateLimitExceeded
from slowapi import Limiter, _rate_limit_exceeded_handler

import json

def get_quotes():
    return json.load(open('quotes.json', 'r'))

app = FastAPI()
limiter = Limiter(key_func = get_ipaddr)
app.state.limiter = limiter
app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler)

@app.get('/')
@limiter.limit('10/minute')
def home(request: Request):
    return {'msg': 'Hello, World'}


@app.get('/quotes')
@limiter.limit('10/minute')
def quote(request: Request):
    return get_quotes()
from fastapi import FastAPI


db = [
 {'api_key': '437af89f-38ba-44f1-9eda-924f370193d4',
  'tokens': 3,
  'user_id': '6ddf9779-4be7-449c-a70d-51e81c19dd0b'},
 {'api_key': '48762b59-e968-459e-b28d-50e7a1ad37a4', 
  'tokens': 3,
  'user_id': 'daf36850-68ab-40fc-86af-e6093b6797dd'},
 {'api_key': 'dabbd875-acbd-4b98-a47f-a526075d41b4', 
  'tokens': 3,
  'user_id': '5750957f-a246-4290-a35e-2dec83bcfcea'},
 {'api_key': '604d5fe2-f7ce-4560-8137-eeae32091738',
  'tokens': 3,
  'user_id': '2d4ac462-b118-48d7-897e-163c2e8327aa'},
 {'api_key': '8540cbef-de3e-4cbd-83bc-f66297a7f407',
  'tokens': 3,
  'user_id': 'bb435e7e-b5da-4a8c-b860-e43a8e765f67'}
]



app = FastAPI()

def update_tokens_for_user(user_id, api_key):
    for user in db:
        if user['user_id'] == user_id and user['api_key'] == api_key:
            tokens = user['tokens']
            if tokens > 0:
                tokens = tokens - 1
                user['tokens'] = tokens

                return {'tokens': tokens}
            
            else:
                return {'tokens': tokens, 'msg': 'you need to get more tokens'}


@app.get('/test')
def test(user_id : str, api_key: str):
    result = update_tokens_for_user(user_id, api_key)
    if result:
        return result
    else:
        return {'msg': 'api key or user id is not found'}
import pprint

data = {'email': 'test@test.com', 'password': '123'}

print(data, type(data))

# convert dict to str
result = pprint.pformat(data)

print(result, type(result))
from peewee import Model, SqliteDatabase, CharField, IntegerField, UUIDField
from uuid import uuid4
from faker import Faker
from random import randint

fake = Faker()

db = SqliteDatabase('mydb.db')

class User(Model):
    name = CharField(max_length = 25)
    email = CharField(max_length = 25)
    age = IntegerField()
    password = CharField(max_length = 100)
    user_id = UUIDField(primary_key = True, default = uuid4)

    class Meta:
        database = db


db.connect()
db.create_tables([User])

for i in range(20):
    new_user = User.create(**{
        'name': fake.name(),
        'email': fake.email(),
        'age': randint(12, 45),
        'password': fake.password()
    })

    new_user.save()

db.commit()
myLists = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

def to_one_list(myLists):
    myList = []
    for _list in myLists:
        for l in _list:
            myList.append(l)

    return myList

print(to_one_list(myLists = myLists))
<p>TopHomeworkHelper.com offers comprehensive programming help for students, covering various programming languages like Java, Python, C++, and more. Services include assignment help, coding assistance, and debugging support. With 24/7 availability and experienced tutors, the platform ensures timely and reliable solutions for all programming-related academic needs.<br /><br />Source:&nbsp;<a href="https://tophomeworkhelper.com/programming-help.html" target="_blank" rel="noopener">Programming Homework Help</a></p>
<p>&nbsp;</p>
from random import randint
from PIL import Image
from os import listdir, path, mkdir
from uuid import uuid4
import moviepy.editor as mp

def generate_video(folder):
    if not path.exists(folder):
        mkdir(folder)

    # generate video frames
    for i in range(20):
        img = Image.new(
            mode = 'RGB',
            size = (500, 250),
            color = (0, 0, 0)
        )

        for x in range(img.size[0]):
            for y in range(img.size[1]):
                r, g, b = randint(0, 255), randint(0, 255), randint(0, 255)
                img.putpixel((x, y), value = (r, g, b))

        img.save(f'{folder}/{i}.png')
    
    # create video
    images = [f'{folder}/{img}' for img in listdir(folder)]
    clips = [mp.ImageClip(img).set_duration(0.08) for img in images]
    video = mp.concatenate_videoclips(clips, method = 'compose')
    video.to_videofile(f'{str(uuid4())}.mp4', fps = 24)


generate_video('test')
from uuid import uuid4
import random

extintions = ['zip', 'exe', 'txt', 'py', 'mp4', 'mp3', 'png']

def generate_files(files_len, folder):
    for i in range(files_len):
        file_name = f'{folder}/{str(uuid4())}.{random.choice(extintions)}'
        file_size = (1024 * 1024) * random.randint(1, 10)
        file = open(file_name, 'wb')
        file.write(b'\b' * file_size)
        file.close()

generate_files(20, 'test')
from fastapi import FastAPI, Request
from slowapi.util import get_remote_address
import uvicorn


app = FastAPI()

@app.get('/')
def home(req : Request):
    return {'ip': get_remote_address(request=req)}
from peewee import SqliteDatabase, Model, UUIDField, CharField, IntegerField
from uuid import uuid4

db = SqliteDatabase('mydb.db')

# Create user Model
class User(Model):
    userId = UUIDField(primary_key = True, default = uuid4)
    name = CharField(max_length = 10)
    age = IntegerField()

    class Meta:
        database = db

# Connect to db
db.connect()
db.create_tables([User])
db.commit()

# Add new user to database
user = User.create(name = 'user123', age = 20)
user.save()

# Get all users
for user in User.select():
    print(user.name, user.userId)
from selenium import webdriver
from selenium.webdriver.common.by import By
from dotenv import load_dotenv

# https://pypi.org/project/2captcha-python/
from twocaptcha import TwoCaptcha


import time
import sys
import os

# https://github.com/2captcha/2captcha-python

sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__))))


url = 'https://accounts.hcaptcha.com/demo'

driver = webdriver.Chrome()

driver.get(url=url)

time.sleep(2)

site_key = driver.find_element(
    by = By.XPATH, 
    value = '//*[@id="hcaptcha-demo"]').get_attribute('data-sitekey')




load_dotenv()

# create account in 2captcha from here : https://bit.ly/3MkkuPJ
# make deposit at least 3$
# https://2captcha.com/pay

# create env file or you can put your API key direct in TwoCaptcha function


api_key = os.getenv('APIKEY_2CAPTCHA')


api_key = os.getenv('APIKEY_2CAPTCHA', 'YOUR_API_KEY')

solver = TwoCaptcha(api_key)

try:
    result = solver.hcaptcha(
        sitekey=site_key,
        url=url,
    )

    code = result['code']
    print(code)

    

    driver.execute_script(f"document.getElementsByName('h-captcha-response')[0].innerHTML = '{code}'")
    
    # submit
    driver.find_element(by = By.ID, value = 'hcaptcha-demo-submit').click()
    

except Exception as e:
    sys.exit(e)



input()
void action(){  
  turnRight(); move();
  
  if(isMableOnClam()){ /* Check if clams exist where Mable stand */
    // To pick up a clam
    pickUpClam();
  }
  else if(isMableOnDestination()){ /* Check if Mable is on a destination */
    // To put down all clams
    putDownClam();
    putDownClam();
    putDownClam();
    putDownClam();
  }
  else{ /* If there are no clams and Mable is not on the destination */
    // To move forward once
    move();
  }
  
  turnLeft(); move();

  if(isMableOnClam()){ /* Check if clams exist where Mable stand */
    // To pick up a clam
    pickUpClam();
  }
  else if(isMableOnDestination()){ /* Check if Mable is on a destination */
    // To put down all clams
    putDownClam();
    putDownClam();
    putDownClam();
    putDownClam();
  }
  else{ /* If there are no clams and Mable is not on the destination */
    // To move forward once
    move();
  }
  
  turnRight(); move();
  turnLeft(); move();
  turnRight(); move();
  
  if(isMableOnClam()){ /* Check if clams exist where Mable stand */
    // To pick up a clam
    pickUpClam();
  }
  else if(isMableOnDestination()){ /* Check if Mable is on a destination */
    // To put down all clams
    putDownClam();
    putDownClam();
    putDownClam();
    putDownClam();
  }
  else{ /* If there are no clams and Mable is not on the destination */
    // To move forward once
    move();
  }
  
  turnLeft(); move();
  
  if(isMableOnClam()){ /* Check if clams exist where Mable stand */
    // To pick up a clam
    pickUpClam();
  }
  else if(isMableOnDestination()){ /* Check if Mable is on a destination */
    // To put down all clams
    putDownClam();
    putDownClam();
    putDownClam();
    putDownClam();
  }
  else{ /* If there are no clams and Mable is not on the destination */
    // To move forward once
    move();
  }
  
  turnRight(); move();
  
  if(isMableOnClam()){ /* Check if clams exist where Mable stand */
    // To pick up a clam
    pickUpClam();
  }
  else if(isMableOnDestination()){ /* Check if Mable is on a destination */
    // To put down all clams
    putDownClam();
    putDownClam();
    putDownClam();
    putDownClam();
  }
  else{ /* If there are no clams and Mable is not on the destination */
    // To move forward once
    move();
  }
}
n=5
s=0
for i in range(1,n+1):
    # adding cube sum using pow() function
    s=s+pow(i,3)
print(s)   
def prime(x, y):
    prime_list = []
    for i in range(x, y):
        if i == 0 or i == 1:
            continue
        else:
            for j in range(2, int(i/2)+1):
                if i % j == 0:
                    break
            else:
                prime_list.append(i)
    return prime_list
 starting_range = 2
ending_range = 7
lst = prime(starting_range, ending_range)
if len(lst) == 0:
    print("There are no prime numbers in this range")
else:
    print("The prime numbers in this range are: ", lst)
def findArea(r):
    PI = 3.142
    return PI * (r*r);
 
# Driver method
print("Area is %.6f" % findArea(5));
def power(x, y):
     
    if y == 0:
        return 1
    if y % 2 == 0:
        return power(x, y // 2) * power(x, y // 2)
         
    return x * power(x, y // 2) * power(x, y // 2)
 
def order(x):
 
    # Variable to store of the number
    n = 0
    while (x != 0):
        n = n + 1
        x = x // 10
         
    return n
 
def isArmstrong(x):
     
    n = order(x)
    temp = x
    sum1 = 0
     
    while (temp != 0):
        r = temp % 10
        sum1 = sum1 + power(r, n)
        temp = temp // 10
 
    # If condition satisfies
    return (sum1 == x)
 
# Driver code
x = 153
print(isArmstrong(x))
 
x = 1253
print(isArmstrong(x))
import math 
 
def isPerfectSquare(x):
    s = int(math.sqrt(x))
    return s*s == x
 
 
def isFibonacci(n):
 
    # n is Fibonacci if one of 5*n*n + 4 or 5*n*n - 4 or both
    # is a perfect square
    return isPerfectSquare(5*n*n + 4) or isPerfectSquare(5*n*n - 4)
 
 for i in range(1, 11):
    if (isFibonacci(i) == True):
        print(i, "is a Fibonacci Number")
    else:
        print(i, "is a not Fibonacci Number ")
star

Sat Jun 29 2024 05:29:09 GMT+0000 (Coordinated Universal Time) https://myassignmenthelp.co.uk/onlineexam

#onlineexam #education #programming #pythonexamhelp
star

Wed Jun 19 2024 08:47:26 GMT+0000 (Coordinated Universal Time)

##python #coding #python #programming #html
star

Wed Jun 19 2024 08:45:33 GMT+0000 (Coordinated Universal Time)

##python #coding #python #programming #pickle
star

Wed Jun 19 2024 08:27:37 GMT+0000 (Coordinated Universal Time)

##python #coding #python #programming #json
star

Sun Jun 16 2024 19:07:29 GMT+0000 (Coordinated Universal Time)

##python #coding #python #programming #time
star

Sun Jun 16 2024 14:31:23 GMT+0000 (Coordinated Universal Time)

##python #coding #python #programming
star

Sun Jun 16 2024 14:15:11 GMT+0000 (Coordinated Universal Time)

##python #coding #python #programming
star

Sun Jun 16 2024 13:01:54 GMT+0000 (Coordinated Universal Time)

##python #coding #python #programming
star

Thu May 16 2024 12:33:51 GMT+0000 (Coordinated Universal Time) https://tophomeworkhelper.com/programming-help.html

#programming #html #css #mysql #python #java
star

Sun May 12 2024 17:56:50 GMT+0000 (Coordinated Universal Time)

##python #coding #python #api #programming #file
star

Sat May 11 2024 07:23:11 GMT+0000 (Coordinated Universal Time)

##python #coding #python #api #programming
star

Tue Mar 12 2024 09:47:46 GMT+0000 (Coordinated Universal Time)

#dart #programming
star

Mon Dec 19 2022 11:36:31 GMT+0000 (Coordinated Universal Time) https://www.pythonhomeworkhelp.com/python-homework-helper

#python #pythonhomework #education #programming #programminghomework #university #students
star

Mon Dec 19 2022 11:12:10 GMT+0000 (Coordinated Universal Time) https://www.pythonhomeworkhelp.com/best-python-exam-help-from-experienced-experts

#python #pythonexam #exam #education #programming #programmingexam #university #students
star

Mon Dec 19 2022 11:00:46 GMT+0000 (Coordinated Universal Time) https://www.pythonhomeworkhelp.com/do-my-python-homework

#python #pythonhomework #education #programming #programminghomework #university #students
star

Mon Dec 19 2022 10:56:34 GMT+0000 (Coordinated Universal Time) https://www.pythonhomeworkhelp.com/

#python #pythonhomework #education #programming #programminghomework #university #students
star

Fri Nov 25 2022 12:10:45 GMT+0000 (Coordinated Universal Time) https://www.solidworksassignmenthelp.com/solidworks-project-helpers/

#education #assignment #homework #student #study #university #python #programming
star

Fri Nov 25 2022 12:10:42 GMT+0000 (Coordinated Universal Time) https://www.solidworksassignmenthelp.com/do-my-solidworks-assignment/

#education #assignment #homework #student #study #university #python #programming
star

Fri Nov 25 2022 12:10:38 GMT+0000 (Coordinated Universal Time) https://www.solidworksassignmenthelp.com/do-my-solidworks-assignment/

#education #assignment #homework #student #study #university #python #programming
star

Fri Nov 25 2022 12:10:32 GMT+0000 (Coordinated Universal Time) https://www.solidworksassignmenthelp.com/solidworks-homework-help/

#education #assignment #homework #student #study #university #python #programming
star

Fri Nov 25 2022 12:04:20 GMT+0000 (Coordinated Universal Time) https://www.solidworksassignmenthelp.com/

#education #assignment #homework #student #study #university #python #programming

Save snippets that work with our extensions

Available in the Chrome Web Store Get Firefox Add-on Get VS Code extension