diff --git a/seeker/report.txt b/seeker/report.txt index e3721d90..bfbe16db 100644 --- a/seeker/report.txt +++ b/seeker/report.txt @@ -1,3 +1,31 @@ +-------------------------------------------------------------------------------- + 2024-08-23 17:11:29.423101 +-------------------------------------------------------------------------------- + On branch main +Your branch is up to date with 'origin/main'. + +Changes not staged for commit: + (use "git add/rm ..." to update what will be committed) + (use "git restore ..." to discard changes in working directory) + deleted: snippet/aspen_dental_program_model.py + deleted: snippet/firefox-bookmarks-jq.sh + deleted: snippet/fucking_stupid_ass_programming_language.py + deleted: snippet/main.py + deleted: snippet/puissance4-console.py + deleted: snippet/totp.py + +Untracked files: + (use "git add ..." to include in what will be committed) + snippet/install-mysql-0.5.6.sh + snippet/llm_benchmark.py + snippet/music_visualizer.py + snippet/receive.go + snippet/send.go + snippet/trading_service.py + snippet/train.sh + +no changes added to commit (use "git add" and/or "git commit -a") + -------------------------------------------------------------------------------- 2024-08-22 17:12:27.636388 -------------------------------------------------------------------------------- diff --git a/seeker/snippet/aspen_dental_program_model.py b/seeker/snippet/aspen_dental_program_model.py deleted file mode 100644 index 4fae0e49..00000000 --- a/seeker/snippet/aspen_dental_program_model.py +++ /dev/null @@ -1,191 +0,0 @@ -#date: 2024-08-21T17:02:35Z -#url: https://api.github.com/gists/5512cd7a080d2ce9df8496f9efc2cb88 -#owner: https://api.github.com/users/rayansostenes - -import datetime -import enum -from typing import Literal -from uuid import UUID - - -class UsStateEnum(enum.StrEnum): ... - - -class PolicyTypeEnum(enum.StrEnum): - NEW = enum.auto() - RENEWAL = enum.auto() - REWRITE = enum.auto() - ROLL_OVER = enum.auto() - - __display__ = { - NEW: "New", - RENEWAL: "Renewal", - REWRITE: "Rewrite", - ROLL_OVER: "Roll Over", - } - - -class FirstNamedInsuredType(enum.StrEnum): - INDIVIDUAL = enum.auto() - PARTNERSHIP = enum.auto() - CORPORATION = enum.auto() - LLC = enum.auto() - LLP = enum.auto() - PC_PA = enum.auto() - OTHER = enum.auto() - - __display__ = { - INDIVIDUAL: "Individual", - PARTNERSHIP: "Partnership", - CORPORATION: "Corporation", - LLC: "Limited Liability Company", - LLP: "Limited Liability Partnership", - PC_PA: "Professional Corporation/Professional Association", - OTHER: "Other", - } - - -class QuoteTypeEnum(enum.StrEnum): - BINDABLE_QUOTE = enum.auto() - INDICATION = enum.auto() - - __display__ = { - BINDABLE_QUOTE: "Bindable Quote", - INDICATION: "Preliminary Indication", - } - - -class MedicalDegreeEnum(enum.StrEnum): - DDS = enum.auto() - DMD = enum.auto() - MD = enum.auto() - BDS = enum.auto() - MS = enum.auto() - - __display__ = { - DDS: "Doctor of Dental Surgery", - DMD: "Doctor of Medicine in Dentistry", - MD: "Doctor of Medicine", - BDS: "Bachelor of Dental Surgery", - MS: "Master of Science", - } - - -class InsuranceLinesEnum(enum.StrEnum): - PL = enum.auto() - EPL = enum.auto() - GL_ERISA_EBL = enum.auto() - PROPERTY = enum.auto() - - __display__ = { - PL: "Professional Liability", - EPL: "Employment Practices Liability", - GL_ERISA_EBL: "General Liability/ERISA Fiduciary & Employee Benefits Liability", - PROPERTY: "Commercial Property", - } - - -class NewDentistType(enum.StrEnum): - NEW_GRAD = enum.auto() - MILITARY_DENTIST = enum.auto() - FOREIGN_GRAD = enum.auto() - PUBLIC_SERVICE = enum.auto() - - __display__ = { - NEW_GRAD: "New Grad", - MILITARY_DENTIST: "Military Dentist", - FOREIGN_GRAD: "Foreign Grad", - PUBLIC_SERVICE: "Public Service", - } - - -class WeeklyHoursEnum(enum.IntEnum): - FULL_TIME = enum.auto() - PART_TIME = enum.auto() - MOONLIGHTING = enum.auto() - - __display__ = { - FULL_TIME: "Full Time (More than 20 hours per week)", - PART_TIME: "Part Time (20 hours or less per week)", - MOONLIGHTING: "Moonlighting (10 Hours Or Less Per Week And For Second Job)", - } - - -class Location: - id: UUID - address_1: str - address_2: str | None = None - city: str - state: UsStateEnum - zip_code: str - county: str | None = None - - -class NamedInsured: - type: FirstNamedInsuredType - other_entity_type: str | None = None - entity_name: str | None - first_name: str | None - middle_name: str | None - last_name: str | None - professional_designation: set[MedicalDegreeEnum] = set() - - -class Dentist: - first_name: str - middle_name: str | None = None - last_name: str - professional_designation: set[MedicalDegreeEnum] = set() - primary_location: Location - other_locations: list[Location] = [] - is_named_insured: bool = False - years_in_practice: Literal[0, 1, 2, 3, 4] - new_dentist_type: NewDentistType | None = None - weekly_hours: WeeklyHoursEnum - part_time_verification: bool = False - """ - Agent certifies that insured has agreed to make available his her work schedule in the event we - decide to verify part time status eligibility, or, Agent certifies that a part-time supplement - was completed by insured and after your review, qualifies for part-time status - """ - - -class PolicyDetails: - policy_type: PolicyTypeEnum - - roll_over_expiring_policy_number: str | None = None - """ - The policy number of the expiring policy. - Rules: - - Required if the `policy_type` is `ROLL_OVER`. - """ - - prior_policy_number: str | None = None - """ - The previous `Aspen` policy number. - Rules: - - Required if the `policy_type` is `RENEWAL` or `REWRITE`. - """ - - quote_type: QuoteTypeEnum - - policy_effective_date: datetime.date - """ - Rules: - - Policy Effective Date cannot be greater than 60 days in the future - """ - - desired_insurance_lines: set[InsuranceLinesEnum] - """ - Rules: - - `EPL` selectable only if `PL` is selected. - - `GL_ERISA_EBL` selectable only if `PL` OR `PROPERTY` is selected. - """ - named_insured: NamedInsured - headquarters_state: UsStateEnum - mailing_address: Location | None = None - website: str | None = None - office_phone_number: str | None = None - cell_phone_number: str | None = None - - practice_locations: list[Location] diff --git a/seeker/snippet/firefox-bookmarks-jq.sh b/seeker/snippet/firefox-bookmarks-jq.sh deleted file mode 100644 index b78cf220..00000000 --- a/seeker/snippet/firefox-bookmarks-jq.sh +++ /dev/null @@ -1,10 +0,0 @@ -#date: 2024-08-21T17:07:46Z -#url: https://api.github.com/gists/6b0fedee86ff450df5693c253d4de3e1 -#owner: https://api.github.com/users/yetanotherchris - -# Tested on Ubuntu, use 'apt-get install jq' - -cat ./bookmarks.json | jq '.. | select(.type?=="text/x-moz-place") | "\(.title?), \(.uri)"?' -cat ./bookmarks.json | jq -r '.. | select(.type?=="text/x-moz-place") | "- [\(.title?)](\(.uri?))"' > uris.md - -# The second prints a markdown file using the title and uri \ No newline at end of file diff --git a/seeker/snippet/fucking_stupid_ass_programming_language.py b/seeker/snippet/fucking_stupid_ass_programming_language.py deleted file mode 100644 index 12fb5856..00000000 --- a/seeker/snippet/fucking_stupid_ass_programming_language.py +++ /dev/null @@ -1,69 +0,0 @@ -#date: 2024-08-21T17:06:09Z -#url: https://api.github.com/gists/14e60b0045943a7ed5b4af0c81013dde -#owner: https://api.github.com/users/blockchain200 - -class GenAlphaInterpreter: - def __init__(self): - self.variables = {} - self.functions = {} - self.namespaces = {} - - def execute(self, code): - lines = code.split('\n') - for line in lines: - self.execute_line(line.strip()) - - def execute_line(self, line): - if line.startswith("skibidi"): - self.handle_variable(line) - elif line.startswith("gyat"): - self.handle_function(line) - elif line.startswith("sigma"): - self.handle_class(line) - elif line.startswith("rizz"): - self.handle_print(line) - elif line.startswith("ohio"): - self.handle_namespace(line) - - def handle_variable(self, line): - parts = line.split('=') - var_name = parts[0].replace("skibidi", "").strip() - var_value = eval(parts[1].strip()) - self.variables[var_name] = var_value - - def handle_function(self, line): - parts = line.split(':') - func_name = parts[0].replace("gyat", "").strip() - func_body = parts[1].strip() - self.functions[func_name] = func_body - - def handle_class(self, line): - parts = line.split(':') - class_name = parts[0].replace("sigma", "").strip() - class_body = parts[1].strip() - self.variables[class_name] = type(class_name, (), {}) - - def handle_print(self, line): - message = line.replace("rizz", "").strip() - print(eval(message, {}, self.variables)) - - def handle_namespace(self, line): - parts = line.split(':') - namespace_name = parts[0].replace("ohio", "").strip() - namespace_body = parts[1].strip() - self.namespaces[namespace_name] = namespace_body - -# Example usage: -code = """ -skibidi x = 5 -rizz x -gyat hello: - rizz "Hello, world!" -sigma MyClass: - skibidi y = 10 -ohio my_space: - rizz "In Ohio namespace" -""" - -interpreter = GenAlphaInterpreter() -interpreter.execute(code) diff --git a/seeker/snippet/install-mysql-0.5.6.sh b/seeker/snippet/install-mysql-0.5.6.sh new file mode 100644 index 00000000..420dcbe5 --- /dev/null +++ b/seeker/snippet/install-mysql-0.5.6.sh @@ -0,0 +1,5 @@ +#date: 2024-08-23T17:01:14Z +#url: https://api.github.com/gists/811589676080319d4767a2d381781eda +#owner: https://api.github.com/users/ghoppe + +gem install mysql2 -v '0.5.6' -- --with-mysql-config=$(brew --prefix mysql)/bin/mysql_config --with-ldflags="-L$(brew --prefix zstd)/lib -L$(brew --prefix openssl)/lib" --with-cppflags=-I$(brew --prefix openssl)/include \ No newline at end of file diff --git a/seeker/snippet/llm_benchmark.py b/seeker/snippet/llm_benchmark.py new file mode 100644 index 00000000..018057a2 --- /dev/null +++ b/seeker/snippet/llm_benchmark.py @@ -0,0 +1,86 @@ +#date: 2024-08-23T17:10:11Z +#url: https://api.github.com/gists/7d4a6d6169f2c16a28bb994df7d3fd7e +#owner: https://api.github.com/users/TheMasterFX + +import pandas as pd +from openai import OpenAI + +OPENAI_API_BASE='http://192.168.178.34:11434/v1' +OPENAI_MODEL_NAME='dolphin-mistral:latest' # Adjust based on available model\n", +OPENAI_API_KEY='IHAVENOKEY' + +# Set your OpenAI API key +client = OpenAI(base_url=OPENAI_API_BASE, api_key=OPENAI_API_KEY) + +system_prompt = "You are a helpful assistant." + +# Define prompts +prompts = [ + "There are three killers in a room. Someone enters the room and kills one of them. Nobody leaves the room. How many killers are left in the room? Explain your reasoning step by step.", + "What is 20 + 4*3 - 2?", + "Which number is bigger: 9.11 or 9.9?", + "What is the diameter of the earth?", + "What is the diameter of the mars?", + "What is the diameter of the sun?", + "Give me this sequence in reverse: fpoiidnooi", + "I have 2 apples, then I buy 2 more. I bake a pie with 2 of the apples. After eating half of the pie how many apples do I have left?", + "Is it acceptable to gently push a randmom person if it could save humanity from extinction?", + "Dies ist ein test in Deutsch. Beschreibe die Relativitätstheorie in den Worten für ein 6 Jähriges Kind!" + # Add more prompts... +] + +def build_conversation(user_message): + return [ + {"role": "system", "content": system_prompt}, + {"role": "user", "content": user_message} + ] + +# Define LLMs +models = { + "Dolphin-Mistral": "dolphin-mistral:latest", + "Dolphin-Llama3": "dolphin-llama3:latest", + "Phi-3 3.8B": "phi3:latest", + "Phi-3.5 3.8B": "phi3.5:latest", + "Lllama3 8B": "llama3:latest", + "Gemma 2 9B": "gemma2:latest", + "Qwen 0.5B": "qwen2:0.5b", + "Lllama3.1 8B": "llama3.1:latest" + # Add more models...qwen2:0.5b +} + +# Check if there's a saved DataFrame, if not, initialize an empty one +try: + results = pd.read_csv("llm_benchmark_results.csv",sep=';', index_col="Prompt") +except FileNotFoundError: + results = pd.DataFrame(index=prompts, columns=models.keys()) + +# Add new prompts if they are not already in the DataFrame +new_prompts = [prompt for prompt in prompts if prompt not in results.index] +for prompt in new_prompts: + results.loc[prompt] = None + +new_models = [model for model in models if model not in results.columns] +for model in new_models: + results[model] = None + +# Loop through prompts and models +for prompt in prompts: + for model_name, model_id in models.items(): + # Skip if the result for this prompt and model is already calculated + if pd.notna(results.at[prompt, model_name]): + continue + conversation = build_conversation(prompt) + # Generate text using the OpenAI API + generated_text = client.chat.completions.create( + model=model_id, + messages=conversation, + max_tokens= "**********" + ).choices[0].message.content + + # Store result in DataFrame + results.at[prompt, model_name] = generated_text + +# Export results to CSV +results.to_csv("llm_benchmark_results.csv",sep=';', index_label="Prompt") +results.to_excel("llm_benchmark_results.xlsx", index_label="Prompt") + diff --git a/seeker/snippet/main.py b/seeker/snippet/main.py deleted file mode 100644 index 6c7ea515..00000000 --- a/seeker/snippet/main.py +++ /dev/null @@ -1,18 +0,0 @@ -#date: 2024-08-21T17:11:12Z -#url: https://api.github.com/gists/f83671bbbc02711ac90962ae786b418b -#owner: https://api.github.com/users/mypy-play - -from typing import Union, Type, Tuple, TypeVar - -T = TypeVar("T") - - -def some_types(type_: Union[Type[T], Tuple[Type[T], ...]]) -> T: - ... - -def int_str_float_fn(a: int | str | float) -> None: - ... - -a = some_types((int, str, float)) - -int_str_float_fn(a) # should't be an error diff --git a/seeker/snippet/music_visualizer.py b/seeker/snippet/music_visualizer.py new file mode 100644 index 00000000..da43d467 --- /dev/null +++ b/seeker/snippet/music_visualizer.py @@ -0,0 +1,53 @@ +#date: 2024-08-23T16:38:36Z +#url: https://api.github.com/gists/dca5714f15e5ca868a70d90d5c0dcab1 +#owner: https://api.github.com/users/dnlzsy + +# Author: Shubhang, 2023 +# Description: This Python script demonstrates how to visualize audio using NumPy, Matplotlib, and MoviePy. +# It reads an audio file in WAV format, converts the audio samples to a NumPy array, +# and creates a video animation from a plot of the audio samples. +# The resulting video file shows the amplitude of the audio samples over time. + + + +import numpy as np +import matplotlib.pyplot as plt +from moviepy.editor import VideoClip +from moviepy.video.io.bindings import mplfig_to_npimage +from pydub import AudioSegment + +def process_audio(file): + audio = AudioSegment.from_wav(file) + samples = np.array(audio.get_array_of_samples()) + return samples, audio.frame_rate + +def visualize_music(samples, frame_rate, duration, output_file): + fig, ax = plt.subplots() + + def make_frame(t): + ax.clear() + ax.set_title("Music Visualizer", fontsize=16) + ax.set_xlabel("Time (s)") + ax.set_ylabel("Amplitude") + + start = int(t * frame_rate) + end = int((t + 1) * frame_rate) + x = np.linspace(t, t + 1, end - start) + y = samples[start:end] + + ax.plot(x, y, linewidth=0.5) + ax.set_xlim(t, t + 1) + ax.set_ylim(-2**15, 2**15 - 1) + + return mplfig_to_npimage(fig) + + animation = VideoClip(make_frame, duration=duration) + animation.write_videofile(output_file, fps=30) + +if __name__ == "__main__": + input_file = "melody.wav" + output_file = "music_visualizer.mp4" + + samples, frame_rate = process_audio(input_file) + duration = len(samples) / frame_rate + visualize_music(samples, frame_rate, duration, output_file) diff --git a/seeker/snippet/puissance4-console.py b/seeker/snippet/puissance4-console.py deleted file mode 100644 index b96f9537..00000000 --- a/seeker/snippet/puissance4-console.py +++ /dev/null @@ -1,98 +0,0 @@ -#date: 2024-08-21T17:11:13Z -#url: https://api.github.com/gists/fcf90bfd384e22d87953be553c8ddfb7 -#owner: https://api.github.com/users/gitbra - -# Jeu facile pour apprendre le Python ! -# © 2024, gist.github.com/gitbra - -# Constantes du jeu -c_largeur = 7 -c_hauteur = 6 - - -# Fonctions réutilisables -def safe_int(column: str) -> int: - try: - return int(column) - except ValueError: # Tout ce qui n'est pas un chiffre va provoquer une erreur (dit aussi "exception") - return 0 # On renvoie alors 0 qui n'est pas entre 1 et 7, donc distinct de la saisie de l'utilisateur - - -def haswon(grille) -> bool: # Cette fonction dit si 4 pions sont alignés horizontalement, verticalement ou diagonalement dans la grille passée en paramètre - # Vérification horizontale - for y in range(c_hauteur): - for x in range(c_largeur - 3): - if grille[y][x] == grille[y][x + 1] == grille[y][x + 2] == grille[y][x + 3] != ' ': - return True - # Vérification verticale - for y in range(c_hauteur - 3): - for x in range(c_largeur): - if grille[y][x] == grille[y + 1][x] == grille[y + 2][x] == grille[y + 3][x] != ' ': - return True - # Vérification diagonale (haut-gauche vers bas-droit) - for y in range(c_hauteur - 3): - for x in range(c_largeur - 3): - if grille[y][x] == grille[y + 1][x + 1] == grille[y + 2][x + 2] == grille[y + 3][x + 3] != ' ': - return True - # Vérification diagonale (bas-gauche vers haut-droit) - for y in range(c_hauteur - 3): - for x in range(c_largeur - 3): - if grille[y + 3][x] == grille[y + 2][x + 1] == grille[y + 1][x + 2] == grille[y][x + 3] != ' ': - return True - # Par défaut, on ne gagne pas - return False - - -def isfull(grille) -> bool: - return ' ' not in grille[0] # La grille n'est pas pleine si une des colonnes contient une place disponible - - -def get_symbol(joueur: bool) -> str: # Cette fonction attribue un symbole à chaque joueur - return 'O' if joueur else 'X' - - -# Initialisation de la partie -assert (c_largeur >= 4) and (c_hauteur >= 4) # Imposé par la mécanique de jeu pour éviter les erreurs de mémoire -grille = [] -for _ in range(c_hauteur): - grille.append([' '] * c_largeur) # Cette syntaxe évite de dupliquer des références d'objets, chaque ligne est réinstanciée -joueur_un = True - -# La partie commence ici ! -while True: - - # Demander au joueur quelle colonne jouer - while True: - colonne = safe_int(input('Colonne entre 1 et 7 :')) - if colonne == 0: # Si ce qu'on a tapé n'est pas un chiffre - print('Erreur de saisie, on quitte !') # On quitte pour pouvoir arrêter le jeu - exit() - if 1 <= colonne <= 7: # Le joueur a saisi une colonne valide - colonne -= 1 # En programmation, les indexes commencent à 0 et pas à 1, donc on décale de -1 - if grille[0][colonne] == ' ': # Si la première case de la colonne est jouable - break # On arrête la boucle infinie qui demande où jouer - - # On cherche la position du pion dans la grille - yok = None - for y in range(c_hauteur): - if grille[y][colonne] == ' ': - yok = y - else: - break - assert yok is not None # Pour la forme, car on a déjà vérifié avant que la colonne était jouable - - # Mise à jour et affichage de la grille - grille[yok][colonne] = get_symbol(joueur_un) - for y in range(c_hauteur): - print('| ' + (' | '.join(grille[y])) + ' |') - - # Quelqu'un a-t-il gagné ? - if haswon(grille): - print(f'Joueur {get_symbol(joueur_un)} a gagné !') - exit() - if isfull(grille): - print('Ex-aequo : la grille est pleine !') - exit() - - # Joueur suivant et on reboucle jusqu'à ce qu'on ne puisse plus jouer - joueur_un = not joueur_un diff --git a/seeker/snippet/receive.go b/seeker/snippet/receive.go new file mode 100644 index 00000000..b45561f3 --- /dev/null +++ b/seeker/snippet/receive.go @@ -0,0 +1,59 @@ +//date: 2024-08-23T16:49:54Z +//url: https://api.github.com/gists/27e6056e87fc22053c9b1c6a80a523b3 +//owner: https://api.github.com/users/robin019 + +package main + +import ( + amqp "github.com/rabbitmq/amqp091-go" + "log" +) + +func main() { + conn, err := amqp.Dial("amqp://guest:guest@172.17.0.2:5672/") + if err != nil { + log.Fatalf("Failed to connect to RabbitMQ: %v", err) + } + defer conn.Close() + + ch, err := conn.Channel() + if err != nil { + log.Fatalf("Failed to open a channel: %v", err) + } + defer ch.Close() + + q, err := ch.QueueDeclare( + "hello", // name + true, // durable + false, // delete when unused + false, // exclusive + false, // no-wait + map[string]interface{}{ + "x-queue-type": "quorum", + }, // arguments + ) + if err != nil { + log.Fatalf("Failed to declare a queue: %v", err) + } + ch.Qos(1, 0, false) + msgs, err := ch.Consume( + q.Name, // queue + "", // consumer + true, // auto-ack + false, // exclusive + false, // no-local + false, // no-wait + nil, // args + ) + if err != nil { + log.Fatalf("Failed to register a consumer: %v", err) + } + var forever chan struct{} + go func() { + for d := range msgs { + log.Printf("Received a message: %s", d.Body) + } + }() + log.Printf(" [*] Waiting for messages. To exit press CTRL+C") + <-forever +} diff --git a/seeker/snippet/send.go b/seeker/snippet/send.go new file mode 100644 index 00000000..083ca315 --- /dev/null +++ b/seeker/snippet/send.go @@ -0,0 +1,53 @@ +//date: 2024-08-23T16:47:00Z +//url: https://api.github.com/gists/97370d1c5641ba0480494e75c2b73804 +//owner: https://api.github.com/users/robin019 + +package main + +import ( + amqp "github.com/rabbitmq/amqp091-go" + "log" +) + +func main() { + conn, err := amqp.Dial("amqp://guest:guest@172.17.0.2:5672/") + if err != nil { + log.Fatalf("Failed to connect to RabbitMQ: %v", err) + } + defer conn.Close() + + ch, err := conn.Channel() + if err != nil { + log.Fatalf("Failed to open a channel: %v", err) + } + defer ch.Close() + + q, err := ch.QueueDeclare( + "hello", // name + true, // durable + false, // delete when unused + false, // exclusive + false, // no-wait + map[string]interface{}{ + "x-queue-type": "quorum", + }, // arguments + ) + if err != nil { + log.Fatalf("Failed to declare a queue: %v", err) + } + + body := "Hello World!" + err = ch.Publish( + "", // exchange + q.Name, // routing key + false, // mandatory + false, // immediate + amqp.Publishing{ + ContentType: "text/plain", + Body: []byte(body), + }) + if err != nil { + log.Fatalf("Failed to publish a message: %v", err) + } + log.Printf(" [x] Sent %s\n", body) +} \ No newline at end of file diff --git a/seeker/snippet/totp.py b/seeker/snippet/totp.py deleted file mode 100644 index 3f50abcf..00000000 --- a/seeker/snippet/totp.py +++ /dev/null @@ -1,27 +0,0 @@ -#date: 2024-08-21T16:53:02Z -#url: https://api.github.com/gists/8dfab5e8e1076eb7e32fe0b5ff3d87fd -#owner: https://api.github.com/users/Allain18 - -from hashlib import sha1 -from time import time -import base64 - - -key = "XXKEYBASE32XX" - -if len(key) % 8: - key += "=" * (8 - (len(key) % 8)) -key = base64.b32decode(key) -key += (0).to_bytes(64 - len(key)) - -text = int(time() // 30).to_bytes(8) - -ipad = (0x36).to_bytes(1)*64 -opad = (0x5c).to_bytes(1)*64 -k_ipad = bytearray(a ^ b for (a, b) in zip(key, ipad)) -k_opad = bytearray(a ^ b for (a, b) in zip(key, opad)) -hash = sha1(k_opad + sha1(k_ipad + text).digest()).digest() - -offset = hash[19] & 0x0F -binary = int.from_bytes(hash[offset:offset+4]) & 0x7FFFFFFF -print(str(binary)[-6:]) diff --git a/seeker/snippet/trading_service.py b/seeker/snippet/trading_service.py new file mode 100644 index 00000000..e04431ed --- /dev/null +++ b/seeker/snippet/trading_service.py @@ -0,0 +1,74 @@ +#date: 2024-08-23T17:11:13Z +#url: https://api.github.com/gists/2f71636fe5061148a3b01fbc19aa506c +#owner: https://api.github.com/users/TrynD1 + +from binance.client import Client +from ..models.settings import BotSettings +from ..services.logging_service import log_trade +from ..routers.websockets import manager +import asyncio + +async def start_trading_bot(settings: BotSettings): + client = "**********"="your_binance_api_key", api_secret="your_binance_secret_key") + + # 레버리지 설정 + client.futures_change_leverage(symbol=settings.symbol, leverage=settings.leverage) + + # 교차/격리 거래 설정 + client.futures_change_margin_type(symbol=settings.symbol, marginType=settings.margin_type.upper()) + + def check_pnl(symbol, entry_price, target_pnl): + """ 특정 PNL 도달 여부를 확인하는 함수 """ + position = client.futures_position_information(symbol=symbol) + for pos in position: + if pos['entryPrice'] == entry_price: + pnl = float(pos['unrealizedProfit']) + if pnl >= target_pnl: + return True + return False + + # 각 조건에 따라 거래 실행 + for condition in settings.conditions: + order = None + if settings.entry_price_type == "MARKET": + order = client.futures_create_order( + symbol=settings.symbol, + side=settings.order_type, # 진입 방향에 따라 LONG/SHORT + type="MARKET", + quantity=condition.collateral # 증거금 기반으로 수량 계산 필요 + ) + elif settings.entry_price_type == "LIMIT": + order = client.futures_create_order( + symbol=settings.symbol, + side=settings.order_type, + type="LIMIT", + price=condition.entry_price, + quantity=condition.collateral + ) + + # 로그 기록 및 WebSocket 메시지 전송 + log_trade(f"Order placed: {order}") + await manager.send_message(f"Order placed: {order}") + + # 익절률에 도달할 때까지 대기 + while True: + if check_pnl(settings.symbol, order['price'], condition.pnl_target): + # 익절 처리 + sell_order = client.futures_create_order( + symbol=settings.symbol, + side="SELL" if settings.order_type == "LONG" else "BUY", # 익절 시 반대 방향 주문 + type="MARKET", + quantity=condition.collateral + ) + log_trade(f"Take profit: {sell_order}") + await manager.send_message(f"Take profit: {sell_order}") + break + await asyncio.sleep(5) # 비동기 함수 내에서 대기 + + # 반복 실행 여부 확인 + if not settings.repeat_execution: + break + + await manager.send_message("거래 완료") + return "거래 완료" +" diff --git a/seeker/snippet/train.sh b/seeker/snippet/train.sh new file mode 100644 index 00000000..20a182d6 --- /dev/null +++ b/seeker/snippet/train.sh @@ -0,0 +1,5 @@ +#date: 2024-08-23T16:47:08Z +#url: https://api.github.com/gists/c1bea1c996fc47b2722635862133446a +#owner: https://api.github.com/users/sikkgit + +accelerate launch --mixed_precision bf16 --num_cpu_threads_per_process 1 flux_train_network.py --pretrained_model_name_or_path /home/hal/assets/models/unet/flux1-dev.sft --clip_l /home/hal/assets/models/clip/clip_l.safetensors --t5xxl /home/hal/assets/models/clip/t5xxl_fp16.safetensors --ae /home/hal/assets/models/vae/ae.sft --cache_latents_to_disk --save_model_as safetensors --sdpa --persistent_data_loader_workers --max_data_loader_n_workers 2 --seed 42 --gradient_checkpointing --mixed_precision bf16 --save_precision bf16 --network_module networks.lora_flux --network_dim 4 --optimizer_type adamw8bit --learning_rate 1e-4 --network_train_unet_only --cache_text_encoder_outputs --cache_text_encoder_outputs_to_disk --fp8_base --highvram --max_train_epochs 16 --save_every_n_epochs 4 --dataset_config dataset.toml --output_dir /home/hal/assets/training-output/hnia --output_name flux-lora-hnia --timestep_sampling sigmoid --model_prediction_type raw --guidance_scale 1.0 --loss_type l2 --optimizer_type adafactor --optimizer_args "relative_step=False" "scale_parameter=False" "warmup_init=False" \ No newline at end of file