Skip to content

Commit

Permalink
2025-02-12 17:13:21.654078 new snippets
Browse files Browse the repository at this point in the history
  • Loading branch information
eduardocerqueira committed Feb 12, 2025
1 parent c4bf01b commit 9e047fd
Show file tree
Hide file tree
Showing 23 changed files with 6,156 additions and 416 deletions.
37 changes: 37 additions & 0 deletions seeker/report.txt
Original file line number Diff line number Diff line change
@@ -1,3 +1,40 @@
--------------------------------------------------------------------------------
2025-02-12 17:13:21.654078
--------------------------------------------------------------------------------
On branch main
Your branch is up to date with 'origin/main'.

Changes not staged for commit:
(use "git add/rm <file>..." to update what will be committed)
(use "git restore <file>..." to discard changes in working directory)
deleted: snippet/get-vscode-commands.sh
deleted: snippet/install_v7.sh
modified: snippet/main.py
deleted: snippet/query.java
deleted: snippet/replace_network_id.sh
deleted: snippet/terraform-module-mover.sh
deleted: snippet/testzep.py
deleted: snippet/wol

Untracked files:
(use "git add <file>..." to include in what will be committed)
snippet/DICT_char_count.py
snippet/LIST_output_string.py
snippet/crawler.py
snippet/electron_patcher.py
snippet/enemy.py
snippet/firefox-bookmarks-to-obsidian.py
snippet/food.py
snippet/homework.py
snippet/manage_pack_resources.py
snippet/pacman.py
snippet/practic_basic.py
snippet/sample_pipeline.py
snippet/segmentio_consumer_lag.go
snippet/snake_game.py

no changes added to commit (use "git add" and/or "git commit -a")

--------------------------------------------------------------------------------
2025-02-11 17:13:16.853057
--------------------------------------------------------------------------------
Expand Down
11 changes: 11 additions & 0 deletions seeker/snippet/DICT_char_count.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
#date: 2025-02-12T16:54:11Z
#url: https://api.github.com/gists/a292f93a0b84f4ac1fa83837197d5b35
#owner: https://api.github.com/users/idenise

stri = "what can I do"
char_d={}
for c in stri:
if c not in char_d:
char_d[c] = 0
char_d[c] = char_d[c] + 1
print(char_d)
7 changes: 7 additions & 0 deletions seeker/snippet/LIST_output_string.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
#date: 2025-02-12T16:50:00Z
#url: https://api.github.com/gists/4f80890574f6a5cd7b8a91bd5783176d
#owner: https://api.github.com/users/idenise

str1 = "OH THE PLACES YOU'LL GO"
output = str1.split()
print(output)
140 changes: 140 additions & 0 deletions seeker/snippet/crawler.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
#date: 2025-02-12T16:58:29Z
#url: https://api.github.com/gists/c6db3798f9cb0b8c1dd104063e40e5d5
#owner: https://api.github.com/users/zedr

import sys
import time
import json
from pathlib import Path

import pandas as pd
import requests
from bs4 import BeautifulSoup

# Creo un set: https://docs.python.org/3/tutorial/datastructures.html#sets
# Questo mi permette di aggiungere in tempo O1 (nei casi pratici)
# e verificare la presenza di una chiave sempre in tempo 01.
# Posso fare lo stesso usando i dict, mentre le liste sono
# molto meno efficienti (On per la verifica)
ignored = {
"index.html",
"https://books.toscrape.com/index.html",
}

# L'URL da cui partire
base_url = "https://books.toscrape.com/"

financial_keys = (
'Price (excl. tax)',
'Price (incl. tax)',
'Tax'
)
numerical_keys = (
"Number of reviews",
)

data = []


def get_parent_url(url):
"""Get the parent of the given URL
e.g. https://www.example.com/abc/cde.html -> https://www.example.com/abc/
"""
*parent_parts, _ = url.split("/")
return "/".join(parent_parts)


def rows_to_dict(rows):
"""Convert a sequence of rows of an HTML table to a dict"""
rows_data = {el.th.text: el.td.text for el in rows}
for key, val in rows_data.items():
if key in financial_keys:
# Correggi il dato e lo trasformo in decimale
# '£51.77' -> 51.77
# Per farlo escludo i primi due caratteri
rows_data[key] = float(val[2:])
if key in numerical_keys:
# Converti il dato in un numero intero
rows_data[key] = int(val)
return rows_data

def crawl(url):
"""Crawl the page at the given URL
Any tables will be added as dicts to the
module-level name "data".
Perform the crawl using the breadth-first
algorithm (BFS).
"""

# Prendo la URL base
parent_url = get_parent_url(url)

# Invio una chiamata GET usando l'URL
response = requests.get(url)

status_code = response.status_code
if status_code != 200:
raise Exception(f"Il server ha risposto con uno status code inaspettato: {status_code}")

# Faccio il parsing del HTML della pagina
soup = BeautifulSoup(response.text, features="html.parser")

# Cerco tutti gli element tr (table row) nella pagina (se ci sono)
rows = soup.find_all("tr")

# Se li trovo, li converto in un dict e li aggiungo ai dati
row_data = rows_to_dict(rows)
if row_data:
data.append(row_data)
# Aspetto un secondo prima di proseguire
# in modo da non caricare troppo il server
time.sleep(1)

# Ora cerco tutti i link all'interno della prima sezione della pagina
links = soup.find_all("section")[0].find_all("a")
print(f"Crawled: {url} and found {len(links)} new links and {len(rows)} table rows.", file=sys.stderr)
for link in links:
# Prendo il link (nell'attributo HREF)
link_rel = link.attrs["href"]

# Ignora i link che tornano indietro
if ".." in link_rel:
continue

# Se non è un link assoluto (che comincia con "http")...
if not link_rel.startswith("http"):
# ... lo rendo assoluto usando la URL base
url = "/".join([parent_url, link_rel])
else:
url = link_rel

# I link esterni vanno ignorati
if not url.startswith(base_url):
continue

# Se ho già incontrato il link, lo ignoro
if url in ignored:
continue

# Aggiungo la URL alla lista da ignorare
ignored.add(url)

# Chiamata ricorsiva
crawl(url)


# Faccio partire il crawl
try:
crawl(base_url)
except KeyboardInterrupt:
pass

# Creo e stampo il dataframe
df = pd.DataFrame(data)
print(df)

# Salvo i dati JSON in un file per poterli utilizzare dopo
with open("books.json", "w") as fd:
fd.write(json.dumps(data))
114 changes: 114 additions & 0 deletions seeker/snippet/electron_patcher.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
#date: 2025-02-12T16:56:39Z
#url: https://api.github.com/gists/7373d551ebb11c38a6f7cb8702998dc3
#owner: https://api.github.com/users/matthew-mclaren

"""
electron_patcher.py: Enforce 'use-angle@1' in Chrome and Electron applications
Version 1.0.1 (2025-02-12)
"""

import enum
import json

from pathlib import Path


class ChromiumSettingsPatcher:

class AngleVariant(enum.Enum):
Default = "0"
OpenGL = "1"
Metal = "2"

def __init__(self, state_file: str) -> None:
self._local_state_file = Path(state_file).expanduser()


def patch(self) -> None:
"""
Ensure 'use-angle@1' is set in Chrome's experimental settings
"""
_desired_key = "use-angle"
_desired_value = self.AngleVariant.OpenGL.value

if not self._local_state_file.exists():
print(" Local State missing, creating...")
self._local_state_file.parent.mkdir(parents=True, exist_ok=True)
state_data = {}
else:
print(" Parsing Local State file")
state_data = json.loads(self._local_state_file.read_bytes())


if "browser" not in state_data:
state_data["browser"] = {}
if "enabled_labs_experiments" not in state_data["browser"]:
state_data["browser"]["enabled_labs_experiments"] = []

for key in state_data["browser"]["enabled_labs_experiments"]:
if "@" not in key:
continue

key_pair = key.split("@")
if len(key_pair) < 2:
continue
if key_pair[0] != _desired_key:
continue
if key_pair[1] == _desired_value:
print(f" {_desired_key}@{_desired_value} is already set")
break

index = state_data["browser"]["enabled_labs_experiments"].index(key)
state_data["browser"]["enabled_labs_experiments"][index] = f"{_desired_key}@{_desired_value}"
print(f" Updated {_desired_key}@{_desired_value}")

if f"{_desired_key}@{_desired_value}" not in state_data["browser"]["enabled_labs_experiments"]:
state_data["browser"]["enabled_labs_experiments"].append(f"{_desired_key}@{_desired_value}")
print(f" Added {_desired_key}@{_desired_value}")

print(" Writing to Local State file")
self._local_state_file.write_text(json.dumps(state_data, indent=4))


def main():
# Patch all Electron applications
for directory in Path("~/Library/Application Support").expanduser().iterdir():
if not directory.is_dir():
continue

state_file = directory / "Local State"
if not state_file.exists():
continue

print(f"Patching {directory.name}")
patcher = ChromiumSettingsPatcher(state_file)
patcher.patch()

# Patch all Chrome variants
if Path("~/Library/Application Support/Google").expanduser().exists():
for directory in Path("~/Library/Application Support/Google").expanduser().iterdir():
if not directory.is_dir():
continue

state_file = directory / "Local State"
if not state_file.exists():
continue

print(f"Patching {directory.name}")
patcher = ChromiumSettingsPatcher(state_file)
patcher.patch()

# Patch Microsoft Teams
teams_path = Path(
"~/Library/Containers/com.microsoft.teams2/Data/Library/Application Support/Microsoft/MSTeams/EBWebView/Local State"
).expanduser()

if teams_path.exists():
print("Patching Microsoft Teams")
patcher = ChromiumSettingsPatcher(teams_path)
patcher.patch()


if __name__ == "__main__":
main()
68 changes: 68 additions & 0 deletions seeker/snippet/enemy.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
#date: 2025-02-12T17:02:37Z
#url: https://api.github.com/gists/8230fe747a806b0d092da288f3f92073
#owner: https://api.github.com/users/zoeburke

#ENEMY.PY
import pygame #Importing the pygame module
import random #Importing the random module to be used in the relocate function
#--------------------------------------------------------------------------------
class Enemy: #Creating the Enemy class, which takes self, x and y coordinates, radius, colour of the enemy and the speed
def __init__(self, x, y, radius, colour, speed):
self._x = x
self._y = y
self._radius = radius
self._colour = colour
self._speed = speed

def __str__(self): #This is a string representation of the object, which can be called to check the position and colour of the object
return f"Enemy at ({self._x}, {self._y}) with colour {self._colour}"

def draw(self, display): #This function will draw the enemy as a circle, it takes the parameters of self and display (self having colour, coordinates and radius)
pygame.draw.circle(display, self._colour, [self._x, self._y], self._radius)

def move(self, direction, display_width=None, display_height=None): #This function moves the enemy based on the direction specified and the speed of the enemy
if direction == "UP": #If the direction is up, the y coordinate decreases by the speed
self._y -= self._speed
if self._y - self._radius < 0: # Move to bottom if it goes beyond the top
self._y = self._radius
elif direction == "DOWN": #If the direction is down, the y coordinate increases by the speed
self._y += self._speed
if display_height and self._y + self._radius > display_height: # Move to top if it goes beyond the bottom
self._y = display_height - self._radius
elif direction == "LEFT": #If the direction is left, the x coordinate decreases by the speed
self._x -= self._speed
if self._x - self._radius < 0: # Move to right edge if it goes beyond the left
self._x = self._radius
elif direction == "RIGHT": #If the direction is right, the x coordinate increases by the speed
self._x += self._speed
if display_width and self._x + self._radius > display_width: # Move to left edge if it goes beyond the right
self._x = display_width - self._radius

def relocate(self, display_width, display_height): #This function relocates the enemy to a random position on the screen, by setting the x and y coordinates to random integers.
self._x = random.randint(self._radius, display_width - self._radius)
self._y = random.randint(self._radius, display_height - self._radius)

'''
The functions below are getters, which return the coordinates and radius so that they can be used within the main file.
'''
def get_x(self):
return self._x

def get_y(self):
return self._y

def get_radius(self):
return self._radius

#--------------------------------------------------------------------------------
#CODE SUMMARY
'''
We created this file to contain the Enemy class, which is used to create an enemy object.
The enemy object has attributes such as x and y coordinates, radius, colour and speed.
The class contains methods such as draw, move, relocate and getters for the x and y coordinates and radius.
The draw method is used to draw the enemy as a circle on the screen.
The move method is used to move the enemy in a specified direction with a specified speed.
The relocate method is used to relocate the enemy to a random position on the screen.
The getters are used to get the x and y coordinates and radius of the enemy object.
'''
#--------------------------------------------------------------------------------
Loading

0 comments on commit 9e047fd

Please sign in to comment.