dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def Read_Data():
global BottomLeftPoint
global indexOfBottomLeftPoint
f = open("puncte.txt", "r+")
i = 0
for line in f.readlines():
if i < 1:
e = line.split()
setNoOfPoints(e[0])
else:
a, b = line.split()
c = float(a)
d = fl... | The code processes geometric data by reading, translating, and classifying points into convex, concave, and principal categories. It then prints these classifications and generates a graphical visualization of the points using a drawing function. | def Main():
Read_Data()
translatePoints()
setPrincipalSign()
DecideConvexConcavePoints()
DecidePrincipalsPoints()
PrintConvexesConcaves()
PrintPrincipalsNotPrincipals()
# Partea grafica
map_points()
drawing = Drawing(drawing_points)
drawing.draw() |
def _check_events(self):
"""respond to keypress and mouse events"""
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.KEYDOWN:
self._check_keydown_events(event)
elif event.type == pygame.KEYUP:
self._check_keyup_events(event)
def _update_bullets... | The code defines a `run_game` method that starts the game's main loop, continuously checking events, updating the player's ship, bullets, and alien positions, and rendering the screen to maintain real-time gameplay. | def run_game(self):
"""Start the main loop of the game"""
while True:
self._check_events()
self.ship.update()
self.bullets.update()
self._update_bullets()
self._update_aliens()
self._update_screen() |
def decryptionkey(x):
l0 = x[:64]
r0 = x[64:]
k1 = xor2(l0,r0)
dec_key = r0+k1
return dec_key
def decryptionkeygenerator(key):
DecKeys = keygenerator(key)
DecryptionRoundKeys = []
DecryptionRoundKeys.append(DecKeys[4])
DecryptionRoundKeys.append(DecKeys[0])
DecryptionRoundKeys.ap... | The code decrypts data (text/image) using a custom decryption algorithm. It reads encrypted info from a file, generates decryption keys, processes binary/hex conversions, and renders decrypted results in a Django template. Text is decrypted directly, while images are decoded from base64 binary data and saved as files. | def decrypt(request):
#deleteallfiles()
f = open("C:\\Users\\madhv\\Desktop\\VSC\\Django\\Mini project\\Sender\\miniproject\\Encrypted.txt", "r", encoding='utf-8')
lines = f.readlines()
print(lines)
x2 = lines[1].strip()
enc = lines[2].strip()
dk = decryptionkey(x2)
DecryptionRoundKeys =... |
def decryptionkey(x):
l0 = x[:64]
r0 = x[64:]
k1 = xor2(l0,r0)
dec_key = r0+k1
return dec_key
def decryptionkeygenerator(key):
DecKeys = keygenerator(key)
DecryptionRoundKeys = []
DecryptionRoundKeys.append(DecKeys[4])
DecryptionRoundKeys.append(DecKeys[0])
DecryptionRoundKeys.ap... | The main task of the code is to simulate a bit-flipping attack on encrypted data. It reads an encrypted text or image, flips a single random bit in the ciphertext, decrypts both the original and modified ciphertexts, and calculates the percentage of differences in the decrypted plaintext. The results are rendered in HT... | def bitflipattack(request):
f = open("C:\\Users\\madhv\\Desktop\\VSC\\Django\\Mini project\\Sender\\miniproject\\Encrypted.txt", "r", encoding='utf-8')
lines = f.readlines()
print(lines)
x2 = lines[1].strip()
enc = "".join(lines[2:]).strip()
etext = enc
dk = decryptionkey(x2)
DecryptionR... |
def decryptionkey(x):
l0 = x[:64]
r0 = x[64:]
k1 = xor2(l0,r0)
dec_key = r0+k1
return dec_key
def decryptionkeygenerator(key):
DecKeys = keygenerator(key)
DecryptionRoundKeys = []
DecryptionRoundKeys.append(DecKeys[4])
DecryptionRoundKeys.append(DecKeys[0])
DecryptionRoundKeys.ap... | The code performs a dictionary attack by decrypting an encrypted file using keys from an uploaded text file. It converts keys to binary, attempts decryption with each key, and checks if the result is a valid image or text. If successful, it saves the decrypted data and returns the correct key; otherwise, it logs failed... | def dictionaryattack(request):
dictionary = request.FILES['file']
keys = dictionary.readlines()
keys = [key.strip() for key in keys]
keys = [key.decode() for key in keys]
print(keys)
x2s = []
for i in range(len(keys)):
y = keys[i]
temp = ''
for j in y:
tem... |
def deleteallfiles():
folder = 'C:\\Users\\madhv\\Desktop\\VSC\\Django\\Mini project\\Sender\\miniproject\\uploads'
for filename in os.listdir(folder):
file_path = os.path.join(folder, filename)
try:
if os.path.isfile(file_path) or os.path.islink(file_path):
os.u... | The code encrypts uploaded image or text files using a custom algorithm involving key generation, binary conversion, and hexadecimal encoding. It handles both file types by converting them into binary strings, applying encryption rounds with generated keys, and saving the encrypted output as an image or text file. The ... | def forenc(request):
try:
imageselected = request.FILES['file']
deleteallfiles()
ext = imageselected.name.split(".")
if(ext[1] == 'jpg' or ext[1] == 'png'):
with open(getfilepath(imageselected, 'image'), 'rb') as image_file:
image_data = image_file.read()
... |
def CreateShift(inShift, inList, inDebug):
if inShift >= len(inList):
if inDebug: print("- LEN[->] pSHF["+str(inShift)+"] MOD["+str(inShift) + "-INT("+str(inShift) + "/" +
str(len(inList)) + ")] SHF[" + str(inShift % len(inList)) + "]")
inShift = inShift % len(inList)
else:
... | The code generates and stores public/private key pairs using a custom cryptographic process involving Caesar cipher shifts, password-based rotation, and modular arithmetic. It confirms user intent, creates keys with a password, computes secure keys via prime math, and saves them to files. | def generateNewKeys():
SanityCheck = input("Are you sure you want to generate Rotator Key Pairs, This will overwrite any other Keys (Yes or No): ")
if SanityCheck.lower() != "yes": sys.exit()
Password = input("\n\nPlease Enter a Key Password: ")
print("\nGenerating Rotator Key Pairs:")
WordList = "... |
def SyntaxInformation():
print("""SYNTAX: MScipher <args> <passcode> <text>
{-s} or {--shift} Sets MScipher shift value.
{-d} or {--decipher} Puts MScipher into a Decipher Mode.
{-j} or {--justify} Sets MScipher into what Method to Shift Key List,
Followed by {"... | This function parses command-line arguments for a cipher tool, configuring options like debug mode, encryption/decryption mode, character sets, shift values, password handling, and key pair management. It processes input data from arguments or stdin, validates parameters, and returns the input text for further cryptogr... | def CmdLineParser():
global Debug
global Convert
global DeCipher
global Infile
global Justify
global KeyPair
global KeyPairName
global Leap
global Outfile
global PassSet
global Password
global Shift
global WordList
inData = ''
if len(sys.argv) ... |
def construct_input_ref_pair(text, ref_token_id, sep_token_id, cls_token_id, device, tokenizer):
text_ids = tokenizer.encode(text, add_special_tokens=False)
# construct input token ids
input_ids = [cls_token_id] + text_ids + [sep_token_id]
# construct reference token ids
ref_input_ids = [cls_toke... | The code predicts text classes using a model, identifies important words via attribution methods, and generates color-coded visualizations to explain predictions. It cleans input text, constructs model inputs, computes predictions, and derives saliency maps to highlight influential words for each predicted class, retur... | def predict(text, model_, tokenizer_, device_):
# cleaning data so as to ensure data is in string type
source_text = " ".join(text.split())
global device
global tokenizer
global ref_token_id
global sep_token_id
global cls_token_id
global model
ref_token_id = tokenizer_.pad_token_id... |
def query_history(client: object, user_query: str, time_stamp: str):
"""
Queries history database for closest two vectors relating to the user's query. Also logs query into database.
:param client: Redis client object
:param user_query: User query message
:param time_stamp: Timestamp of chat message... | The code generates a chatbot response by combining historical conversation data, relevant query information, and a user's current question into a structured prompt for a language model. It uses Redis clients to retrieve past interactions and data, constructs a system message with this context, and runs the model to pro... | def chat(chat_client, data_client, user_query: str, time_stamp: str):
"""
Chatbot with history
:param chat_client: Redis chat client object
:param data_client: Redis information client object
:param user_query: User query message
:param time_stamp: Timestamp of chat message session
:return: ... |
def connect_redis_information():
"""
Connects to the information vector database
:return: Redis client object
"""
client = redis.Redis(host=REDIS_INFORMATION_HOST, port=REDIS_INFORMATION_PORT, password=REDIS_INFORMATION_PASSWORD,
decode_responses=True)
return client
def ... | The main task of the code is to demonstrate a sample chat query system. It initializes Redis clients, creates vector indexes, and executes a chat query about embeddings using a predefined question. The function connects to Redis, prepares the query context, and retrieves a chat response, showcasing the integration of v... | def sample_chat():
"""
Sample chat query
:return: None
"""
time_stamp = str(1705166849)
# sample_data = [
# "What is an embedding?",
# "I still don't understand, could you simply it?",
# "What benefit do embeddings have for machine learning?"
# ]
sample_query = "W... |
def _get_output_folder(self) -> Path:
output_folder = MesaJob.get_project_directory()
output_folder /= Path(self.relative_output_folder)
return output_folder
def _get_timestamp_from_file(self, file_name) -> datetime.datetime:
return datetime.datetime.fromtimestamp(
file_name.... | The main task of the code is to update a job's status based on file existence and PID checks, determining whether the job is queued, running, complete, or not started. It examines timestamp files (started, running, complete) in an output folder, checks if associated processes are active, and adjusts the job's status an... | def update_status(self, status=None) -> str:
if not status:
# status = MesaJob.MESA_JOB_STATUS_NOT_STARTED
status = self.status
all_checks_job = MesaJob.objects.filter(name=MesaJob.MESA_JOB_ALL_CHECKS_NAME)[0]
output_folder = self._get_output_folder()
... |
def initialize_tensorBoard(self):
"""
Setup the variables that will be used in Tensorboard to view the
network training performance.
"""
regularization_losses = tf.get_collection(
tf.GraphKeys.REGULARIZATION_LOSSES)
regularization_constant = 0.01
... | The main task of the code is to train a neural network model using TensorFlow. It initializes a session, processes training data in batches, updates model parameters via the optimizer, logs training metrics with TensorBoard, displays periodic loss/accuracy, saves the trained model checkpoint, and evaluates the model po... | def train(self):
self.initialize_tensorBoard()
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
summary_writer = tf.summary.FileWriter(self.logs_path,
graph=tf.get_default_graph())
saver = tf.... |
def get_random_subset_of_features(n_features: int, random_state: Optional[int] = None) -> np.ndarray:
"""
Generates a random subset of Features. Answer taken from https://stackoverflow.com/a/47942584/7058363
:param n_features: Total number of features
:param random_state: Random state to replicate exper... | This function implements the Binary Black Hole Algorithm (BBHA) for feature selection and classification on a Spark cluster. It initializes stars with random feature subsets, evaluates their fitness in parallel, and iteratively updates stars based on a 'black hole' (best solution) using event horizon logic. The algorit... | def binary_black_hole_spark(
n_stars: int,
n_features: int,
n_iterations: int,
fitness_function: Callable[[np.ndarray], CrossValidationSparkResult],
sc: SparkContext,
use_load_balancer: bool,
number_of_workers: int,
parameters: Optional[SVMParameters], # ... |
def _process_pixels(self):
'Set the transparent pixels to the color 0.'
self._transparent_pixels = set(
idx for idx, alpha in enumerate(
self._img_rgba.getchannel(channel='A').getdata())
if alpha <= self._alpha_threshold)
def _process_palette(self):
"""
... | The code processes an RGBA image by converting it to a palette-based (mode 'P') image. It adjusts pixel data and the color palette, then sets transparency and background info to 0, returning the modified palette image. | def process(self) -> Image:
'Return the processed mode `P` `Image`.'
self._img_p = self._img_rgba.convert(mode='P')
self._img_p_data = bytearray(self._img_p.tobytes())
self._palette_replaces = dict(idx_from=list(), idx_to=list())
self._process_pixels()
self._process_palet... |
def need_explode(depths):
return np.any(np.array(depths) >= 4)
def explode(numbers, depths):
idx = 0
exploded = False
while idx < len(numbers) and not exploded:
if depths[idx] >= 4:
if idx > 0:
numbers[idx - 1] += numbers[idx]
if idx < len(numbers) - 2:
... | The code processes a list of lines representing nested numbers (like a JSON-like structure) to calculate their magnitude. It tracks depth levels while parsing numbers, then repeatedly applies "explode" and "split" operations (to handle nested values) until no more are needed. Finally, it returns the computed magnitude ... | def add_lines(lines):
depth = -1
numbers = []
depths = []
for line in lines:
for i, depth in enumerate(depths):
depths[i] += 1
if len(depths) != 0:
depth = 0
for _, character in enumerate(line):
if "," == character:
continue
... |
def get_csv_data(file_location):
df = pd.read_csv(file_location)
return df
def dataCleansing(df):
col_available, col_status = availableCols(df)
newData = {}
for col in col_available:
temp = list(map(lambda x: str(x).strip(), df[col]))
temp = remove_nan(temp)
if len(temp) < 1:... | The code's main task is to load data from a CSV file, cleanse it (e.g., handle missing values, duplicates), assess column relevance using `dataInfo`, and return the cleaned dataset along with selected columns. It streamlines data preparation by automating cleaning and feature selection. | def getCleanData(file_location):
df = get_csv_data(file_location)
cleanData, column_status = dataCleansing(df)
column2choose = dataInfo(column_status)
return cleanData, column2choose |
def calibration_update_mic_plotdata():
"""This is called to update and roll the global plotdata1 array.
Data is collected from the queue, downsampled and added to the end of the
plotdata1 array.
Typically, audio callbacks happen more frequently than plot updates,
therefore the queue tends to contai... | The main task of the code is to calibrate a system by recording 5-second audio and spiker data during eye movement and sound production tasks, then determining a microphone threshold and electrode orientation for alignment with training data. | def begin_calibration(banner = False):
banner = """
██████╗ █████╗ ██╗ ██╗██████╗ ██████╗ █████╗ ████████╗██╗ ██████╗ ███╗ ██╗
██╔════╝██╔══██╗██║ ██║██╔══██╗██╔══██╗██╔══██╗╚══██╔══╝██║██╔═══██╗████╗ ██║
██║ ███████║██║ ██║██████╔╝██████╔╝███████║ ██║ ██║██║ ██║██╔██╗ ██║
██║ ██╔══██... |
def port_exists(cport):
""" Finds if the port cport currently exists in the list of ports. """
# current list of ports
ports = ListPorts.comports()
output = False
# if any port matches cport, return true
for port, desc, hwid in sorted(ports):
if cport == port:
output = True
... | The code presents a menu for user interaction, handling calibration, game initiation, and exit options. It initializes a serial port for hardware communication, checks port validity, and ensures calibration before allowing game play. The menu loops until the user quits, with global variables storing calibration data an... | def welcome_menu(show_banner = False):
banner = """
██╗ ██╗███████╗██╗ ██████╗ ██████╗ ███╗ ███╗███████╗
██║ ██║██╔════╝██║ ██╔════╝██╔═══██╗████╗ ████║██╔════╝
██║ █╗ ██║█████╗ ██║ ██║ ██║ ██║██╔████╔██║█████╗
██║███╗██║██╔══╝ ██║ ██║ ██║ ██║██║╚██╔╝██║██╔══╝
╚███╔███╔╝██████... |
def _input_fn(file_pattern: List[Text],
tf_transform_output: tft.TFTransformOutput,
is_train: bool = False,
batch_size: int = 200) -> tf.data.Dataset:
"""Generates features and label for tuning/training.
Args:
file_pattern: List of paths or patterns of input tfrecord fi... | The code trains a Keras model in two phases: first freezing the backbone to train only the classifier, then unfreezing part of the backbone for joint fine-tuning. It uses TensorFlow Transform for preprocessing, compiles the model with RMSprop, and logs training metrics via TensorBoard. After training, it converts the m... | def run_fn(fn_args: FnArgs):
"""Train the model based on given args.
Args:
fn_args: Holds args used to train the model as name/value pairs.
Raises:
ValueError: if invalid inputs.
"""
tf_transform_output = tft.TFTransformOutput(fn_args.transform_output)
train_dataset = _input_fn(
fn_args.train... |
def parse_file(f):
sources = ""
with open(f, 'r') as i:
i.readline()
for line in i:
if '"""' in line:
break
sources += line
return yaml.safe_load(sources)
def __execute_sources(self, sources, config):
if not sources:
return []
... | The code processes a task by parsing its trigger file, executing the parsed sources with the task's configuration, and invoking the corresponding trigger plugin. If the trigger condition is met, it iterates through the task's actions, executing each with its options and configuration, and stores the results in a waiter... | def __run_task(self, task):
sources = parse_file(task["trigger_file"])
data = self.__execute_sources(sources, task["config"])
trigger = shercon.triggers.plugins[task["trigger"]]
if trigger.run(*data, starg=task["args"], config=task["config"]):
for action, options in task["ac... |
def _conv_layer(net, num_filters, filter_size, strides, relu=True):
"""
Convolution wrapper.
This function contains convolution, batch normalization and relu operation
Arg: net - The tensor object of previous layer
num_filters - The number of filter in convolution... | This code defines a residual encoder-decoder neural network for image processing. It processes input images through convolutional layers, residual blocks (for feature learning), transposed convolutions (upsampling), and outputs refined images using tanh activation. The architecture aims to reconstruct or enhance images... | def net(image, base_filter = 32):
"""
Return the architecture of original residual encoder-decoder
Arg: image - The image placeholder
base_filter - The base number of filter
Ret: The dict object with the tensors of graph
"""
conv1 = _conv_layer(image, base... |
def _conv_layer_incept(net, num_filters, filter_size, strides, relu=True):
"""
Convolution wrapper. (Inception version)
This function contains convolution, batch normalization and relu operation
The convolution is decomposed as three part: shrinking, working and expanding
* To be not... | The code defines a neural network architecture for an inception-style residual encoder-decoder. It processes an input image through convolutional layers with increasing filters, followed by multiple residual blocks to capture features. Transposed convolutions upsample the features, and a final convolution generates out... | def small_net(image, base_filter = 16):
"""
Return the architecture of inception version residual encoder-decoder
Arg: image - The image placeholder
base_filter - The base number of filter
Ret: The dict object with the tensors of graph
"""
conv1 = _conv_la... |
def get_config(config_path: Path) -> dict:
if not config_path.exists():
logging.warning("Config file not found, prompting user for default config")
return prompt_for_config()
else:
logging.info("Config found at location %s", config_path.as_posix())
with config_path.open("r") as f... | The main task of the code is to monitor a password file, check for new passwords not previously recorded, crack them using a specified username, send notifications via a webhook when new passwords are found, and maintain a record of discovered passwords in a JSON file. | def run():
logging.basicConfig(level=logging.INFO)
config = get_config(Path("config.json"))
potfile = Potfile(Path(config["potfile"]["potfile_path"]))
webhook = Webhook(config["webhook"]["url"])
username = config["username"]
passwords = potfile.read().split("\n")
found_passwords = load_passw... |
def select_line(self, x, y):
for i, j in self.instance.edges:
x1, y1 = self.coordinates[i]
x2, y2 = self.coordinates[j]
if point_on_line(x, y, x1, y1, x2, y2, self.eps, self.EPS):
return i, j
return None
def select_vertex(self, x, y):
for i, (x... | This code handles vertex and edge selection in a graphical interface. It checks if a click lands on an edge or vertex, updates selections, and manages face/edge creation. If a vertex is clicked, it may add it to a face, deselect existing selections, or connect it to the current selection. The logic ensures proper inter... | def select(self, x, y):
self.e_sel = self.select_line(x, y)
# If we clicked on an edge, select it
if self.e_sel is None:
i, x, y = self.select_vertex(x, y)
if self.faceQ:
self.add_vertex_to_face(i)
# If we clicked on the selected vertex, de-se... |
def select(self, x, y):
self.e_sel = self.select_line(x, y)
# If we clicked on an edge, select it
if self.e_sel is None:
i, x, y = self.select_vertex(x, y)
if self.faceQ:
self.add_vertex_to_face(i)
# If we clicked on the selected vertex, de-se... | This code handles mouse click events in a plot. Left-click selects or deselects elements, while right-click moves selected vertices or deselects edges. It updates selection states and triggers a redraw to reflect changes in the plot. | def mouse_click(self, event):
if event.inaxes is None:
return
elif event.button == MouseButton.LEFT:
if self.e_sel is not None:
self.e_sel = None
else:
self.select(event.xdata, event.ydata)
elif event.button == MouseButton.RIG... |
def load_config(self):
"""
Loads or reloads config from file specified in 'config_path' attribute.
"""
self.config.load_config_and_spec(self.config_path)
config_id = self.config.id.lower()
if config_id == '/default':
self.client_id = 'copter' + str(random.ran... | (The main task of the code is to reload configuration settings, initialize a notifier socket, and enter an infinite loop that repeatedly reconnects to a server and processes connections. The loop runs indefinitely until interrupted by a keyboard signal, at which point it logs an exit message and closes the selector. Th... | def start(self):
"""
Reloads config and starts infinite loop of connecting to the server and processing said connection. Calling of this method will indefinitely halt execution of any subsequent code.
"""
self.load_config()
logger.info("Starting client")
messaging.Notifi... |
def reset(self, filepath, config):
self.id = None
self.original_frames = []
self.transformed_frames = []
self.static_begin_index = 0
self.takeoff_index = 0
self.route_index = 0
self.land_index = 0
self.static_end_index = 0
self.output_frames = []
... | The function `on_animation_update` resets the animation using a specified configuration and CSV file, loads data, and triggers a configuration update if original frames exist, ensuring the animation aligns with the latest settings. | def on_animation_update(self, filepath="animation.csv", config=None):
if config is None:
config = self.config
self.reset(filepath, config)
self.load()
if self.original_frames:
self.on_config_update(self.config) |
def draw_graph(self, window: pygame.Surface):
for node in self.algo.get_graph().get_all_v().values():
x = int(node.get_pos()[0])
y = int(node.get_pos()[1])
pygame.draw.circle(window, node.get_tag(), (node.get_pos()[0], node.get_pos()[1]), 15)
id_srf = FONT.render(... | The main task of the code is to render a game's visual elements by drawing the background, game graph, agents, and Pokémon onto the window. It loads a background image, blits it to the window, and calls methods to draw additional game components, updating the display with all elements for visualization. | def draw_everything(self, game: Game):
back_ground = pygame.image.load("Images/background.png")
self.window.blit(back_ground, 0, 0)
self.draw_graph(self.window)
self.draw_agents(game)
self.draw_pokemons(game) |
def empGrids(self):
"""This function resets all the grids to white"""
for i in range(self.ROWS):
for j in range(self.COLS):
self.grid[i][j] = WHITE
def drawArr(self,arr,colour,delay=-1):
"""This function draws the given array on pygame screen"""
for i in range... | This function visualizes array sorting in real-time using Pygame by highlighting elements with colors (RED/GREEN) as they are processed, updating the display incrementally with delays to show changes. It clears the grid, draws the array, and animates index movements based on array values, resetting the grid afterward. | def dispSort(self,arr,l,m=-1,fstDispIndex=-1):
"""This function displays realtime changes in array on pygame screen"""
k1 = k2 = self.COLS-1
self.empGrids()
self.drawArr(arr,PURPLE)
if fstDispIndex != -1:
self.fastDisp(arr,fstDispIndex)
pygame.display.update()... |
def answer(self, event):
self.check_answer()
self.update_status()
self.next_question()
def update_status(self):
remaining = self.total_questions - (self.correct + self.wrong)
self.statusvar.set("Remaining: {} Correct: {} Wrong: {}".format(remaining, self.correct,
... | This code initializes a GUI for a timed math speed test application, setting up the interface with a question display, answer input, timer, and result tracking. It configures event handlers for user input, updates the timer, and prepares to generate questions using the provided generator. The interface includes buttons... | def __init__(self, parent, question_generator, total_questions, timeout_seconds, on_close):
print("{} {}".format(question_generator, timeout_seconds))
self.screen = parent
self.screen.geometry(SCREEN_GEOMETRY)
self.screen.title("Maths speed test")
self.frame = Frame(parent, width... |
def printok(s):
print("\033[0;32;40m"+s+"\033[0m")
def rmdirf(s):
for root, dirs, files in os.walk(s, topdown=False):
for name in files:
os.remove(os.path.join(root, name))
for name in dirs:
os.rmdir(os.path.join(root, name))
os.rmdir(s)
def updatesrc():
print("[R... | The main task of the code is to download and validate a configuration template, update source files, and handle legacy C++ files by prompting user confirmation for deletion and backup. It creates a directory, retrieves a YAML config, checks its validity, and optionally removes old files after backup. | def createenv():
printok("Now, start to download the latest template from server")
try:
rmdirf('qtemplate/')
except FileNotFoundError as e:
printok("Create 'qtemplate' Dir")
os.mkdir('qtemplate')
if not updatesrc():
return False
print("[RECV] ver.yaml ...",end='',flush=Tr... |
def get_article_meta_data(article: dict) -> dict:
return dict(
authors=article["authors"],
date_download=datetime.fromisoformat(article["date_download"])
if article["date_download"]
else None,
date_publish=datetime.fromisoformat(article["date_publish"])
if article["da... | This function processes unprocessed downloaded articles by reading their JSON files, extracting metadata, authors, domain-country info, and storing them in a document database, then marking them as processed in the database. | def add_new_articles2tables():
new_articles = crud.article.filter(
filters=dict(article_processed=False, downloaded=True)
)
articles_dir = config["articles_dir"]
for article_id in tqdm(new_articles["id"], total=len(new_articles)):
try:
fp = articles_dir / f"{article_id}.js... |
def get_technical_table():
query = "select * from technical" # Create query
column_names = ['ticker', 'date', 'open', 'close', 'high', 'low', 'adjclose', 'volume'] # Specify column names for dataframe that will be created
prices = postgresql_to_dataframe(query, column_names) # Retrieve dataframe from db
... | The code creates a comprehensive dataset for machine learning by integrating technical, news, and macroeconomic data for a given stock ticker. It processes data by filtering, calculating indicators, aggregating news, merging tables, adding lagged features, splitting into training/test sets based on dates, and standardi... | def create_basetable(tck, start_independent=date(2020, 3, 22), end_independent=date(2020, 12, 31),
start_dependent=date(2021, 1, 1), end_dependent=date(2021, 3, 22), standardize=True):
# Retrieve technical analysis data from database
techn_df = get_technical_table()
# Filter stock data... |
def checkConn(self):
sq = "SELECT NOW()"
try:
self.mycursor.execute( sq )
except mysql.connector.Error as e:
if e.errno == 2006:
self.mycursor, self.database = self.connectToDatabase()
else:
print ( "No connection with database.... | This method retrieves reviews for a specified recipe, allowing users to choose whether to filter by a minimum rating. It validates inputs, queries the database, and displays reviews with ratings and comments, or informs the user if no reviews exist. | def getReviewsForRecipe(self, recipeID):
self.checkConn()
yesOrNoReviews = input("\nWould you like to view Reviews for this Recipe? (Y/N): ")
yesOrNoReviews = self.inputValidater(yesOrNoReviews, ['Y', 'N', 'y', 'n'])
if (yesOrNoReviews == "Y" or yesOrNoReviews == "y"):
filter... |
def checkConn(self):
sq = "SELECT NOW()"
try:
self.mycursor.execute( sq )
except mysql.connector.Error as e:
if e.errno == 2006:
self.mycursor, self.database = self.connectToDatabase()
else:
print ( "No connection with database.... | This function allows a logged-in user to submit a review for a specified recipe. It validates user input for review intent, checks login status, collects a 1-5 rating and comments, updates the recipe's review count in the database, and increments the user's review tally in the Users table. | def submitReview(self, recipe_id):
self.checkConn()
getReviewsResponse = input("\nWould you like to leave a review for this recipe? (Y/N): ")
getReviewsResponse = self.inputValidater(getReviewsResponse, ['Y','y','N','n'])
if(getReviewsResponse == "N" or getReviewsResponse == "n"):
... |
def inputValidaterInt(self, userInput, validInput):
for x in validInput:
if (userInput == x):
return userInput
else:
continue
reenterInput = int(input("\nPlease enter a valid input. Choose from {}: ".format(validInput)))
return sel... | The main task of the code is to allow a logged-in user to view their submitted recipes, select one, and edit its details (name, ingredients, instructions, and timings) by updating the database. It validates user input, retrieves recipe data, and handles database operations to modify recipe information while maintaining... | def showUsersRecipes(self):
if(not self.loggedIn):
print("\nYou are not logged in. Please restart the app and sign in/sign up")
return
else:
self.mycursor.execute("SELECT recipe_name, recipe_id From CleanRecipes WHERE author = '{}';".format(self.username))
... |
def checkConn(self):
sq = "SELECT NOW()"
try:
self.mycursor.execute( sq )
except mysql.connector.Error as e:
if e.errno == 2006:
self.mycursor, self.database = self.connectToDatabase()
else:
print ( "No connection with database.... | This code handles user sign-up by validating the username, sanitizing input, inserting new user credentials into a database, retrieving the associated profile ID, and setting the user's login status to authenticated. | def performSignUp(self):
self.checkConn()
getUsername = input("\nPlease enter a username: ")
newUsername = self.doesUsernameExist(getUsername)
getPassword = input("Please enter a password: ")
getUsername = self.replaceApostrophe(getUsername)
getPassword = self.replaceApos... |
def checkConn(self):
sq = "SELECT NOW()"
try:
self.mycursor.execute( sq )
except mysql.connector.Error as e:
if e.errno == 2006:
self.mycursor, self.database = self.connectToDatabase()
else:
print ( "No connection with database.... | This code searches for recipes by name in a database, lists matching recipes for user selection, retrieves details of the chosen recipe, and handles ingredient/instruction data and reviews. It validates user input and interacts with a database to fetch and display recipe information. | def findRecipeByName(self, recipeName):
self.checkConn()
recipeName = self.replaceApostrophe(recipeName)
self.mycursor.execute("SELECT recipe_name, recipe_id From CleanRecipes WHERE recipe_name like '%{}%';".format(recipeName))
myresult = self.mycursor.fetchall()
if (le... |
def checkConn(self):
sq = "SELECT NOW()"
try:
self.mycursor.execute( sq )
except mysql.connector.Error as e:
if e.errno == 2006:
self.mycursor, self.database = self.connectToDatabase()
else:
print ( "No connection with database.... | The main task of the code is to search for recipes based on user-provided ingredients, display matching recipes, allow the user to select one, and then retrieve its ingredients, instructions, reviews, and enable review submission. It handles database queries, user input validation, and recipe data presentation. | def findRecipeByIngredients(self):
self.checkConn()
getIngredients = input("\nPlease enter your ingredients separated by commas. (For eg: eggs, milk, sugar): ")
ingredients = []
ingredients = getIngredients.split(",")
like = self.likeClauseForIngredients(ingredients)
sel... |
def checkConn(self):
sq = "SELECT NOW()"
try:
self.mycursor.execute( sq )
except mysql.connector.Error as e:
if e.errno == 2006:
self.mycursor, self.database = self.connectToDatabase()
else:
print ( "No connection with database.... | The main task of this code is to allow users to search for recipes based on a specified maximum total time, display the filtered recipes, let the user select one, and then retrieve its ingredients, instructions, and reviews. It validates user input, interacts with a database, and handles recipe selection and data retri... | def findRecipeByTotalTime(self):
self.checkConn()
getMaxTime = int(input("\nPlease enter the maximum amount of time in minutes: "))
self.mycursor.execute( "SELECT recipe_name, recipe_id FROM CleanRecipes where total_time <= {};".format(getMaxTime) )
myresult = self.mycursor.fetchall()
... |
def checkConn(self):
sq = "SELECT NOW()"
try:
self.mycursor.execute( sq )
except mysql.connector.Error as e:
if e.errno == 2006:
self.mycursor, self.database = self.connectToDatabase()
else:
print ( "No connection with database.... | The main task of the code is to present a list of recipes to the user, validate their selection, and retrieve associated recipe details (ingredients, reviews) and allow review submission for the chosen recipe. It maps recipes to IDs, ensures input validation, and orchestrates data retrieval and user interaction for rec... | def getRecipesFromDataframe(self, recipes):
self.checkConn()
recipesWithID = [] # add each recipe along with it's ID over here and present these to the user
print("\nPick a recipe from the following list:\n")
i = 0
validValues = []
for index, x in recipes.iterrows():
... |
def checkConn(self):
sq = "SELECT NOW()"
try:
self.mycursor.execute( sq )
except mysql.connector.Error as e:
if e.errno == 2006:
self.mycursor, self.database = self.connectToDatabase()
else:
print ( "No connection with database.... | The main task of the code is to search for recipes based on user-provided criteria (recipe name, ingredients, and maximum time), retrieve matching recipes from a database, display them to the user, and fetch detailed information (ingredients, instructions, reviews) for the selected recipe, allowing the user to submit a... | def fullSearchRecipes(self):
self.checkConn()
getRecipeName = input("\nPlease input the name of the recipe. Enter 'Any' to skip this: ")
getRecipeName = self.replaceApostrophe(getRecipeName)
getIngredients = input("\nPlease enter your ingredients separated by commas. Enter 'Any' to skip... |
def getRobotHandles(clientID):
# Robot handle
_,rbh = sim.simxGetObjectHandle(clientID, 'Pioneer_p3dx',
sim.simx_opmode_blocking)
# Motor handles
_,lmh = sim.simxGetObjectHandle(clientID, 'Pioneer_p3dx_leftMotor',
sim.simx_opmode... | This code connects to a remote API server to control a simulated robot. It reads sonar sensor data, processes it to determine movement speeds, and continuously updates the robot's motion in a loop. The program handles connection setup, sensor input, decision-making, and client cleanup, using command-line arguments for ... | def main():
print('### Program started')
print('### Number of arguments:', len(sys.argv), 'arguments.')
print('### Argument List:', str(sys.argv))
sim.simxFinish(-1) # just in case, close all opened connections
port = int(sys.argv[1])
clientID = sim.simxStart('127.0.0.1', port, True, True, 20... |
def resources_left(self):
return self.number_evaluations < self.max_evaluations - 2 * (
self.max_local_search_evaluations + 1
)
def select(self, node, final=False): # selection
if not node.children:
return node
selected_node = self.best_child(node, final=final)
... | This code implements Monte Carlo Tree Search (MCTS) to find an optimal sequence with high similarity and structure. It iteratively selects unvisited nodes, performs rollouts to evaluate similarity and structure, backpropagates results, and decays exploration parameters. If a sequence with similarity ≥1 is found, it ret... | def run(self):
"Runs MCTS, returns sequence, similarity, structure, number of function evaluations"
while self.resources_left(): # tot target sequence is found]
leaf = self.select(self.root, final=False) # leaf = unvisited node
similarity, sequence, predicted_structure = self.r... |
def get_gen_adversarial_loss_ada(real_X, disc_Y, gen_XY, adv_criterion, augment_probability=None, augmentpipe=None):
fake_Y = gen_XY(real_X)
fake_Y_disc_pred = run_disc_ada(disc_Y, fake_Y, augment_probability=augment_probability, augmentpipe=augmentpipe)
adversarial_loss = adv_criterion(fake_Y_disc_pred, to... | The function computes the generator's total loss in a CycleGAN-like framework, combining adversarial losses from both domains, identity preservation losses, and optional detection/cross-domain losses. It aggregates adversarial (from discriminators), identity (self-reconstruction), detection (if enabled), and cross-doma... | def get_gen_loss_aug(real_A, real_B, gen_AB, gen_BA, disc_A, disc_B, adv_criterion, identity_criterion, cycle_criterion,
det_net=None, label_A=None, params=None, update_det=False, lambda_identity=0.1,
lambda_det=1.0, use_crossdomain=False, det_net_A=None, cross_domain_criterion=None, lambda_crodom=1.0,
augm... |
def scale2d_inv(sx, sy, **kwargs):
return scale2d(1 / sx, 1 / sy, **kwargs)
def rotate2d_inv(theta, **kwargs):
return rotate2d(-theta, **kwargs)
def translate2d_inv(tx, ty, **kwargs):
return translate2d(-tx, -ty, **kwargs)
def translate3d(tx, ty, tz, **kwargs):
return matrix(
[1, 0, 0, tx],
... | This code applies geometric and color transformations to input images (and optionally labels/fake images) using probabilistic parameters. It constructs 2D/3D transformation matrices for operations like flips, rotations, scaling, translations, brightness/contrast adjustments, and hue/saturation changes, then applies the... | def forward(self, images, labels=None, fake_images=None, debug_percentile=None):
assert isinstance(images, torch.Tensor) and images.dim() == 4
batch_size, num_channels, height, width = images.shape
device = images.device
self.p = torch.as_tensor(self.p, dtype=torch.float32, device=device... |
def removeIgnorableWhitespace(node):
rem = []
for n in node.childNodes:
if n.nodeType == xml.dom.Node.ELEMENT_NODE:
removeIgnorableWhitespace(n)
if n.nodeType != xml.dom.Node.TEXT_NODE:
continue
if re.match('^\s*$', n.nodeValue):
rem.append(n)
for n in rem:
node.removeChild(n)
de... | The main task of the code is to parse an XML input stream and output "prettified" XML with adjusted indentation, collapsed whitespace, and optional syntax highlighting. It handles parsing errors based on the `strict` flag, normalizes attributes, and writes formatted XML to the output file-like object, returning success... | def prettify(input, output, strict=True, indentString=' ', color=False,
encoding=DEFAULT_ENCODING):
'''
Converts the input data stream `input` (which must be a file input
like object) to `output` (which must be a file output like object)
by parsing the stream as XML and outputting "prettified"
X... |
def set_speed(self, speed, update=True):
if speed > 4096 or speed < 0:
print('Invalid speed, please use values between 0 and 4096, inclusive')
else:
self._speed = speed
if update:
self.update()
def set_direction(self, direction, update=True):
if direct... | The main task of the code is to set multiple properties (speed, direction, decay) of an object individually if provided, using their respective setter methods with `update=False` to avoid immediate updates. If the `update` parameter is `True`, it triggers a final update after all property assignments. This allows condi... | def set_all(self, speed=None, direction=None, decay=None, update=True):
if speed is not None:
self.set_speed(speed, False)
if direction is not None:
self.set_direction(direction, False)
if decay is not None:
self.set_decay(decay, False)
if update:
... |
def set_speed(self, speed, update=True):
if speed > 4096 or speed < 0:
print('Invalid speed, please use values between 0 and 4096, inclusive')
else:
self._speed = speed
if update:
self.update()
def set_direction(self, direction, update=True):
if direct... | The `set_all` method updates multiple properties (speed, direction, decay) of an object conditionally based on provided inputs, calling individual setter methods with `False` to avoid immediate updates. If `update` is `True`, it triggers a final update after all properties are set, likely for efficiency or synchronizat... | def set_all(self, speed=None, direction=None, decay=None, update=True):
if speed is not None:
self.set_speed(speed, False)
if direction is not None:
self.set_direction(direction, False)
if decay is not None:
self.set_decay(decay, False)
if update:
... |
def act_annotate(in_dir, out_dir, DG, inv_num):
CG = DG.copy()
cdfg_fsm_dict = get_cdfg_fsm_dict(in_dir)
node_act_dict, edge_act_dict, overall_latency = act_trace(in_dir, out_dir, inv_num)
####################
for nodeid in CG.nodes:
opcode = CG.nodes[nodeid]['opcode']
latency = flo... | This function processes a directed graph by annotating nodes/edges with activity data, computing features like fan-in/out and hardware metrics, trimming edges, ensuring consistency, and saving the enhanced graph structure and features to files for further analysis or visualization. | def feature_embed(in_dir, out_dir, inv_num):
DG = nx.DiGraph(nx.drawing.nx_pydot.read_dot('{}/DG.dot'.format(in_dir)))
CG, node_act_dict, edge_act_dict = act_annotate(in_dir, out_dir, DG, inv_num)
fan_in_out_compute(CG)
sum_hd_compute(CG)
load_bypass(CG)
select_edge_trim(CG)
edge_act_consist... |
def _name_to_rgb(self, name):
"""
Convert a color name to a 3-tuple of integers suitable for use in
an ``rgb()`` triplet specifying that color.
The color name will be normalized to lower-case before being
looked up, and when no color of that name exists in the given
spec... | This function determines RGB color values based on input parameters. It converts color names (including "random" for random generation) or hex codes to RGB, defaults to black on error, and remaps values to a specified range. It returns the final RGB tuple after processing inputs and error handling. | def _determine_rgb(self, red=0, green=0, blue=0, name=None, hex=None):
try:
if name:
# Special case for name="random"
if name is "random":
red = randint(0, 255)
green = randint(0, 255)
blue = randint(0, 255)... |
def rectangle(self, x1, y1, x2, y2, r, g, b):
"""
Draw a rectangle with it's corners at x1:y1 and x2:y2
@type x1: int
@param x1: the x1 location in the matrix for first corner of the rectangle
@type y1: int
@param y1: the y1 location in the matrix for first corner of the... | This function renders a 3x5-pixel digit (0-9) at coordinates (x,y) using specified RGB color, drawing lines and setting individual pixel colors to form the digit's shape. Each digit (0-9) has a unique pattern of horizontal/vertical lines and colored pixels to represent its form in a 3x5 grid. | def number(self, x, y, n, r, g, b):
"""
Render a 3x5 number n at location x,y and r,g,b color
@type x: int
@param x: the x location in the matrix (left of the number)
@type y: int
@param y: the y location in the matrix (top of the number)
@type n: int
@pa... |
def _determine_rgb(self, red=0, green=0, blue=0, name=None, hex=None):
try:
if name:
# Special case for name="random"
if name is "random":
red = randint(0, 255)
green = randint(0, 255)
blue = randint(0, 255)... | The function morphs a specified LED channel's color to a target color over a given duration using a linear gradient. It calculates intermediate RGB values between the current and target color, applies each step with a delay, and smoothly transitions the color. Parameters allow specifying the target via RGB, CSS names, ... | def morph(self, channel=0, index=0, red=0, green=0, blue=0, name=None, hex=None, duration=1000, steps=50):
"""
Morph to the specified color.
@type red: int
@param red: Red color intensity 0 is off, 255 is full red intensity
@type green: int
@param green: Green color in... |
def _verify_tag_exists(tag: str):
# Connect to the SQLite database
conn = sqlite3.connect(db_file)
# Create a cursor object to interact with the database
cursor = conn.cursor()
# Check if tag exists
cursor.execute("SELECT * FROM tags WHERE tag = ?", (tag,))
tag_exists = cursor.fetchone()
... | This function inserts a new command into an SQLite database, generating a unique ID and timestamp. It checks if the command or tag already exists, updating if necessary. If new, it inserts the command and links it to a tag via the commands_tags table. The function handles database connections, executes SQL operations, ... | def insert_command_db(command: str, description: str, tag: str = ""):
# Connect to the SQLite database
conn = sqlite3.connect(db_file)
# Create a cursor object to interact with the database
cursor = conn.cursor()
command_uuid = str(uuid.uuid4())
tag_uuid = ""
creation_date = datetime.date... |
def getAllPythonFilesinRepo(path2dir):
valid_list = []
for root_, dirnames, filenames in os.walk(path2dir):
for file_ in filenames:
full_path_file = os.path.join(root_, file_)
if( os.path.exists( full_path_file ) ):
if (file_.endswith( PY_FILE_EXTENSION ) and (checkIfParsablePython( full_path_file ) ) ... | The main task of the code is to identify and print Python files in a given repository that contain logging imports, along with their associated log statements. It first retrieves all Python files, filters those with logging imports, and then prints each file's name, its log statements, and a separator line for clarity.... | def printLogOps(repo_path):
valid_py_files = getAllPythonFilesinRepo( repo_path )
log_py_files = [x_ for x_ in valid_py_files if hasLogImport( x_ ) ]
for py_file in log_py_files:
print(py_file)
print(getLogStatements( py_file ) )
print('='*50) |
def group_parser():
parser = reqparse.RequestParser()
parser.add_argument("group_ids", type=int, location='args', action='append')
return parser.parse_args()
def is_permitted(self, obj=None, **kwargs):
return obj
def validate(self, form_class, obj=None, adjust_func=None):
if ... | This code handles POST requests for creating, updating, or performing sub-methods on resources. It determines the action based on obj_id and resource_name: creating when obj_id is absent, updating when obj_id is present, sub-methods when both are provided, and bulk updates when group_ids are present. It validates data,... | def post(self, obj_id=None, resource_name=None):
""" Execute a post request based on criteria given by the above parameters.
If obj_id isn't passed. It implies a create function call. If there's an obj_id, it implies and update.
if resource_name is passed, it implies a sub update method ... |
def is_valid_move(board, col):
if col < COLS and col >= 0:
return board[0][col] == '-'
return False
def make_move(board, col, player):
for row in range(ROWS - 1, -1, -1):
if board[row][col] == '-':
board[row][col] = player
return True
return False
def min... | The function determines the best move for an AI player using the minimax algorithm with alpha-beta pruning. It evaluates all valid moves on the board, simulates each move, and selects the column with the highest minimax value, ensuring optimal decision-making in turn-based games like Connect Four. | def find_best_move(board):
best_val = float('-inf')
best_move = -1
for col in range(COLS):
if is_valid_move(board, col):
new_board = copy.deepcopy(board)
make_move(new_board, col, AI_PLAYER)
move_val = minimax(new_board, 4, float('-inf'), float('inf'), False)
... |
def get_roster_soup(roster_url: str):
roster_res = requests.get(roster_url)
roster_soup = BeautifulSoup(roster_res.text, "html.parser")
return roster_soup
def get_roster_info_df(soup: BeautifulSoup):
player_info_df_entry_list = []
# Get player info, ignoring table header
player_info_soup_list = ... | The main task of the code is to scrape roster data from a webpage using `get_roster_soup`, convert the extracted information into a structured DataFrame with `get_roster_info_df`, and save the DataFrame as a CSV file using `write_df_to_csv`. This workflow automates retrieving and storing roster details from a specified... | def main():
soup = get_roster_soup(RK9_ROSTER_URL)
df = get_roster_info_df(soup)
write_df_to_csv(df) |
def _clustering(self, sv, min_cluster_size, eps):
labels, min_cluster_size = self._entry_exit_clustering3D(
sv, min_cluster_size=min_cluster_size, eps=eps
)
centroids = self._create_centroids(sv, labels)
return (labels, centroids)
def _merge_labels(self, labels, cluster_id, s... | This function performs clustering on input data (sv) by recursively applying a clustering algorithm, handling noise points (labeled -1), and merging results. It updates cluster labels and centroids, tracks changes via boolean flags (B, bools), and ensures consistent labeling. If initial labels are provided, it refines ... | def _main_clustering(
self, sv, min_cluster_size, eps, labels=None, centroids=None, bools=None
):
B = False
if labels is None:
labels, centroids = self._clustering(sv, min_cluster_size, eps)
sub_sv = sv[labels == -1]
sub_labels, sub_centroids = self._clust... |
def _best_hosting_cluster(self, item, centroids, labels):
m = 100000000
host_clust_id = None
if isinstance(item, int):
U0, UN, Ualt, U_evol = self._get_vect(centroids[item])
for k in range(len(centroids)):
if k != item:
dist = self._get... | This function iteratively merges clusters by checking if a cluster can be hosted in another (via _best_hosting_cluster). If valid, it merges clusters (via _fusion), updates labels/centroids, and repeats until no more merges occur. The loop continues until all clusters are optimally hosted, refining the clustering struc... | def _fusion_loop(self, centroids, sv, labels):
B = True
count = -1
while B:
count += 1
B = False
nb_cluster = max(labels) + 1
d = {}
for i in range(nb_cluster):
j = self._best_hosting_cluster(i, centroids, labels)
... |
def _main_clustering(
self, sv, min_cluster_size, eps, labels=None, centroids=None, bools=None
):
B = False
if labels is None:
labels, centroids = self._clustering(sv, min_cluster_size, eps)
sub_sv = sv[labels == -1]
sub_labels, sub_centroids = self._clust... | The code performs hierarchical clustering on trajectory data, starting with initial clustering using DBSCAN-like parameters, followed by recursive sub-clustering to refine clusters. It then merges overlapping clusters and filters out small clusters based on size thresholds, updating labels and centroids iteratively to ... | def fit(self, X):
self.interp_points_num = X.shape[1]
# 1st level clustering
logging.info("Clustering...")
min_cluster_size = int(X.shape[0] * self.min_cluster_size_ratio)
labels, centroids, b, bools = self._main_clustering(
X, min_cluster_size, self.eps
)
... |
def grid_forget_buttons(self):
for button in self.buttons:
button.grid_forget()
def grid_buttons(self, how_much):
for i in range(how_much):
self.buttons[i].grid(row=2, column=i, ipady=10)
def config_clients_hand(self, my_hand, row=1, initial_column=1):
self.my_hand = my_h... | This function processes incoming server messages to update the UI in a game. It checks message types (int, Hand) to adjust buttons, hands, and turn status. If it's the user's turn, it updates their hand or buttons; otherwise, it updates dealer's hand or displays messages. It also tracks turn changes and updates the int... | def get_staff_from_server(self):
recved = self.socket.recv_message()
if self.my_turn and recved.__class__.__name__ == "int": # need to change the buttons
self.grid_forget_buttons()
self.grid_buttons(recved)
elif self.my_turn and recved.__class__.__name__ == "Hand": # ... |
def send_broadcast(self, message):
for client in self.clients_ready:
client.send_message(message)
def start_round(self):
self.start = True
dealers_hand = Hand(0, cards=[0])
dealers_hand.add_card()
hands = {} # {client: hand}
# the actual game
for c... | The code manages client readiness in a game room. It differentiates between admin and regular clients, waits for game start signals, broadcasts when ready, starts rounds, handles client logouts, and recursively waits for game progression. It ensures clients are added to ready lists, waits for game initiation, and proce... | def waiting_room(self, client):
# wait till the game starts
if client is self.clients_connected[0]: # The admin client
ready = client.get_answer(True) # is admin
client.send_message("Connected successfully!")
if ready:
self.send_broadcast(True) # s... |
def feed_forward_cffn(model, anchor, positive, negative, margin, device):
# List of image forward passes
image_fs = []
# Iterate over each image
for image in (anchor, positive, negative):
# Fit the image to the device
image = image.to(device)
# Generate the output of the model
... | The main task of the code is to validate phase 1 of a model by computing triplet accuracy on a validation dataset. It processes batches of anchor, positive, and negative samples, calculates triplet accuracy using a margin, aggregates results, and logs metrics. The final average accuracy across all validation batches is... | def phase1_val(
model,
val1_loader,
margin,
device,
):
# Aggregate metrics
total_accuracy = 0
# Validation step -- fine-tuning the learning rate hyperparameter
for anchor, positive, negative in val1_loader:
# Forward propagation
_, image_fs = feed_forward_cffn(
... |
def feed_forward_cffn(model, anchor, positive, negative, margin, device):
# List of image forward passes
image_fs = []
# Iterate over each image
for image in (anchor, positive, negative):
# Fit the image to the device
image = image.to(device)
# Generate the output of the model
... | The code evaluates a model's performance in phase 1 testing using triplet accuracy metrics. It processes anchor, positive, and negative image triplets from the test loader, computes accuracy for each batch via forward propagation, accumulates results, and logs both per-batch and final average accuracy. The primary task... | def phase1_test(model, test1_loader, margin, device):
# Testing Step -- monitoring metrics
total_accuracy = 0
for anchor, positive, negative in test1_loader:
# Forward propagation
_, image_fs = feed_forward_cffn(
model, anchor, positive, negative, margin, device
)
... |
def check_epoch(total, split):
if os.path.exists(epoch_filename):
with open(epoch_filename, "r") as f:
epoch = int(f.read())
else:
epoch = 0
if epoch < 0:
epoch = 0
if epoch == 0:
epoch = total - split
with open(epoch_filename, "w") as f:
... | The function trains a model in phase 1 using triplet loss on anchor-positive-negative samples, performing backpropagation, scheduler steps, and periodic validation. It logs accuracy/loss metrics, saves model checkpoints every 5 epochs, and exits after validation. The training aggregates metrics across batches and adjus... | def phase1_train(
model, train1_loader, optimizer, margin, device, p1_epochs, scheduler, val1_loader
):
# Separation between training and validation sets
split = len(train1_loader) // p1_epochs
for epoch in range(p1_epochs):
# Aggregate metrics
total_accuracy = 0
# Scheduler gati... |
def usage():
print('Usage: '+sys.argv[0]+' [options] dir/file')
print("\nIf argument is a directory, all source files below that directory")
print("will be included in the graph.")
print("\n -h/--help : prints this message")
print(" -o/--output file : saves the DOT output in the specified file")
... | The code processes command-line arguments to locate Lean/HLean files in a directory or as a single file, collects their dependencies, and generates output using `lean_deps`, handling input validation and user options like output file specification. | def main(argv):
oname = "deps"
try:
opts, args = getopt.getopt(argv, "ho:", ["help","output="])
except getopt.GetoptError as err:
print(str(err))
usage()
sys.exit(2)
for opt, arg in opts:
if opt in ("-h", "--help"):
usage()
sys.exit()
... |
def __get_lowest (self) -> State:
assert(len(self.open_list) > 0)
# helper function for sorting to return the f value of the passing state.
def get_f (state: State):
return state.f
self.open_list.sort(reverse=True, key = get_f)
return self.open_list.pop()
def __put_to... | This function implements a best-first search algorithm to find a path from the start to the goal state. It repeatedly selects the state with the lowest priority (p) from the open list, adds it to the closed list, checks if it's the goal, and generates successors. If the goal is reached, it backtraces and prints the pat... | def find_path (self):
# If OPEN is empty, output “DONE” and stop.
if len(self.open_list) == 0:
print("Done, no path found")
return
# Find and remove the item [s,p] on OPEN having lowest p.
lowest_p :State = self.__get_lowest()
# Put [s,p] on CLOSED.
... |
def _redraw_x(self, *args):
font_size = self.font_size
if self.xlabel:
xlabel = self._xlabel
if not xlabel:
xlabel = Label()
self.add_widget(xlabel)
self._xlabel = xlabel
xlabel.font_size = font_size
for k, ... | This function updates the mesh structure for axis ticks by recalculating vertices and indices based on major/minor x/y tick points, then prepares the mesh for rendering by initializing vertex data and index lists for subsequent graphical display. | def _redraw_all(self, *args):
# add/remove all the required labels
xpoints_major, xpoints_minor = self._redraw_x(*args)
ypoints_major, ypoints_minor = self._redraw_y(*args)
mesh = self._mesh_ticks
n_points = (len(xpoints_major) + len(xpoints_minor) +
len(ypoi... |
def config(filepath=None):
def decoder(obj_dict: dict) -> namedtuple:
return namedtuple('X', obj_dict.keys())(*obj_dict.values())
with open(filepath or os.path.dirname(os.path.realpath(__file__)) + '/smcdog.conf', 'r') as f:
return json.loads(f.read(), object_hook=decoder)
def get_current_speed... | The function `manage_speed` adjusts the system's current speed to match a target speed defined in the configuration. It checks if the target speed differs from the current speed; if so, it logs the change and updates the speed. Finally, it returns the current speed after any adjustments. | def manage_speed() -> int:
target_speed = config().speed
if target_speed != get_current_speed():
to_log('Change to: %s' % target_speed)
change_speed(target_speed)
return get_current_speed() |
def loss_fn(mse_loss, psi, o_t, o_tm1, iteration, train=True):
# losses
baseline_loss = mse_loss(o_tm1[:, -3:, :, :], o_t)
baseline_loss = baseline_loss.mean()
loss = mse_loss(psi, o_t.unsqueeze(1).repeat(1, FLAGS.bottleneck_size, 1, 1, 1))
loss = loss.view(loss.shape[0], loss.shape[1], -1)
... | The code trains a neural network model using a custom loss function combining baseline, action, and contrastive losses. It processes mini-batches, performs forward/backward passes, logs training metrics, validates periodically, and saves checkpoints. The model learns to predict actions and embeddings while optimizing m... | def train(model, optimizer, epoch, device, train_loader, val_loader,
train_writer, val_writer, iteration, num_actions, scheduler):
np.set_printoptions(precision=3, suppress=True)
model.train()
print_every = 20
val_every = 2000
save_every = 5000
train_loss, train_act_loss, train_base... |
def get_candidate(self,r,c):
idx = self.sub2ind(r,c)
if self.grid[idx] == 0:
row = self.get_row(r)
col = self.get_col(c)
box = self.get_box(r,c)
not_candidate = set(row+col+box)
possible = {i for i in range(1,self.max_num+1)}
candid... | The function `get_uniq_candidate` identifies the unique possible value for a Sudoku cell at position (r,c) by checking its row, column, and 3x3 box. It retrieves candidate numbers and checks if exactly one value is uniquely constrained in any of the three regions. If so, it returns that value; otherwise, it returns the... | def get_uniq_candidate(self,r,c):
# if only k same num in k cells, in a row/col/box they are fixed
# TODO https://youtu.be/jU_W53M5aMQ?t=150
# TODO https://youtu.be/jU_W53M5aMQ?t=204
# TODO https://youtu.be/jU_W53M5aMQ?t=225
candidate = self.get_candidate(r,c)
... |
def check_mode(self, ):
if self.keep_non_params and self.common_structure:
raise RuntimeError("keep_non_params can't be used will common_structure. The common structure only contains parameter nodes.")
if self.common_structure:
if self.mapping is None:
raise Runti... | The main task of the code is to generate and display a structured graph representation of a neural network model's modules in the command line. It constructs a tree-like structure using parameters to control visibility of non-parameter modules, parameter details, and common structure mapping. The function builds, prune... | def structure_graph(self,
rootname="root",
expand_params=False,
keep_non_params=False,
common_structure=False,
mapping=None,
only_common=False,
pr... |
def subsample(dataset, ratio):
sample = list()
n_sample = round(len(dataset) * ratio)
while len(sample) < n_sample:
index = randrange(len(dataset))
sample.append(dataset[index])
return sample
def build_tree(train, max_depth, min_size, n_features):
#Building the tree involves creating the root node and
roo... | The code implements a random forest algorithm by generating multiple decision trees from bootstrapped samples of the training data. Each tree is built with specified depth, minimum size, and feature subset. Predictions are aggregated via bagging, combining outputs from all trees to improve accuracy and reduce overfitti... | def random_forest(train, test, max_depth, min_size, sample_size, n_trees, n_features):
trees = list()
for i in range(n_trees):
sample = subsample(train, sample_size)
tree = build_tree(sample, max_depth, min_size, n_features)
trees.append(tree)
predictions = [bagging_predict(trees, row) for row in test]
return... |
def create_source_datadir(self,
overwrite:bool=None):
"""create the source data directory to which we download and unzip the original data
:param overwrite: whether or not to delete the target dir and recreate it
:type overwrite: bool
:return:... | The main task of the code is to download, unzip, combine, and clean source data into a single cleaned DataFrame. It handles data acquisition, file consolidation, missing value correction, and outputs a cleaned CSV file, which is then loaded into memory and returned as a pandas DataFrame for further analysis. | def download_and_clean(self):
"""convenience function to download, unzip, combine and clean the source data
:return: clean source data dataframe
:rtype: pd.DataFrame
"""
# download and unzip the data
self.create_source_datadir()
self.download_zip_file()
... |
def set_date_limits(self,
min_date=None,
max_date=None):
"""choose only rows specified by the date
* selection operates on the member df_original_clean
* result of the selection is saved to the member df_selection_categorical_undiscretized_locatio... | The function `create_training_data` generates a balanced training dataset by selecting positive samples within specified date ranges and location discretization, then drawing negative samples using a multiplier. It combines these samples into a dataframe, ensures uniqueness, computes statistical metrics like `beta`, an... | def create_training_data(self,
min_date:str=None,
max_date:str=None,
n_cuts:int=10,
N_positive_samples_to_draw:int=-1,
Neg_Multiplier:int=1):
"""create a training data... |
def trigger_item_clicked(self, index):
item = self.get_item_widget(index)
item.clicked.emit(item)
def select_up(self):
self.currentSelectedIndex += 1
if self.currentSelectedIndex >= self.count():
self.currentSelectedIndex = self.count() - 1
self.reset_selection()
... | This method handles keyboard events for navigation and selection in a UI component. It triggers item selection on Enter, and reverses standard navigation: Down key moves up, Up key moves down, likely for inverted control behavior. | def keyPressEvent(self, event: QKeyEvent) -> None:
# keys handle are reversed
if event.key() == Qt.Key.Key_Return:
self.trigger_item_clicked(self.currentSelectedIndex)
if event.key() == Qt.Key.Key_Down:
self.select_up()
if event.key() == Qt.Key.Key_Up:
... |
def gaussian_kernel(size, sigma):
""" Implementation of Gaussian Kernel.
This function follows the gaussian kernel formula,
and creates a kernel matrix.
Args:
size: int of the size of output matrix.
sigma: float of sigma to calculate kernel.
Returns:
kernel: numpy array of... | The code implements the Canny edge detection algorithm to identify edges in a binary image. It applies Gaussian smoothing, computes gradients, performs non-maximum suppression, thresholds edges, and links weak edges to strong ones to produce a final edge map. | def canny(img, kernel_size=5, sigma=1.4, high=20, low=15):
""" Implement canny edge detector by calling functions above.
Args:
img: binary image of shape (H, W).
kernel_size: int of size for kernel matrix.
sigma: float for calculating kernel.
high: high threshold for strong edge... |
def exists_db(c_session,url,db):
db_url = url + '/' + db
get_response = get_with_retries(c_session,db_url,10,None)
if get_response is None:
logging.warn("Check Exists DB Session get error: No response")
elif get_response.status_code == 404:
data = get_response.json()
if 'error' in d... | The main task of the code is to create a database (if it doesn't exist) by sending a PUT request to a specified URL, handling potential errors (no response or high status code), and configuring permissions and index settings for the database. It returns True on success or existing database, or False on creation failure... | def create_db(c_session,url,db,adminuser):
if not exists_db(c_session,url,db):
url_enc = url + '/' + db
dbcreate_response = c_session.put(url_enc,
headers={'content-type': 'application/json'})
if dbcreate_response is None:
print("Error creating db [" + db +"] : No response from cluster")
... |
def get_groupcriteria(granularity,scope):
groupcriteria = ['mtime','mtime_epoch']
if granularity == 'all':
groupcriteria = ['mtime','mtime_epoch']
if scope == 'endpoint' :
groupcriteria = ['cluster','loghost','database','verb','endpoint']
elif scope == 'verb' :
groupc... | The function processes log data to generate statistical and event-based performance metrics, applying filters and thresholds. It organizes data by time ranges and granularity, outputs results in specified formats (JSON or files), and logs progress/errors. | def execute_collect(scope,s_url,s_credentials,s_username,s_password,p_url,certverif,inputlogfile,thresholdsfile,\
eventsexclusionsfile,statsexclusionsfile,fromtime,totime,granularity,performercount,resultslocation,resultsid,outputformat,loghost,cluster_url):
try:
logging.warn("{cloudant performance a... |
def repl():
multiline_repl(PROMPT1, PROMPT2, ERROR_MARK)
def env_from_args(args: Sequence[str]) -> Environment:
env = Environment()
for arg in (a for a in args if '=' in a):
parts = arg.split('=')
if len(parts) != 2 or not all(parts):
continue
name, val = parts
tr... | The code processes command-line arguments to either launch a REPL (if one argument) or execute a script file with an environment derived from additional arguments. It handles undefined symbols by prompting users to define them via command-line options, ensuring proper symbol resolution during script execution. Your ret... | def main(args: list[str]) -> None:
if len(args) == 1:
repl()
else:
arg_env = env_from_args(args[1:])
with open(args[1]) as source_file:
try:
run_file(source_file, arg_env)
except UndefinedSymbol as exc:
key = exc.args[0]
... |
def karatsuba(x, y, threshold=1):
# print(x,y)
if len(str(x)) <= threshold or len(str(y)) <= threshold:
return naive_gradeschool(x,y)
else:
m = max(len(str(x)),len(str(y)))
m2 = m // 2
a = x // 10**(m2)
b = x % 10**(m2)
c = y // 10**(m2)
d = y % 10**(... | The code benchmarks the Karatsuba and naive multiplication algorithms by measuring their average execution times across varying input sizes. It identifies the threshold input size where Karatsuba's performance surpasses the naive method, then visualizes the time comparisons along with the threshold. | def naive_vs_karatsuba():
karat_time = []
naive_time = []
input_size = []
for i in range(1, 300):
print(i)
input_size.append(i)
t1_list = []
t2_list = []
num_repeat = 25
for j in range(num_repeat):
x = random.randint(10**(i), 10**(i+1))
... |
def run_experiment(n_times, num_index, threshold):
time_array = []
for _ in range(n_times):
x = random.randint(10**(num_index), 10**(num_index+1))
y = random.randint(10**(num_index), 10**(num_index+1))
t = timeit.timeit(lambda: karatsuba(x,y,threshold), number=1)
time_array.appe... | The main task of the code is to run experiments with varying thresholds (1–199) and parameters (1–49), record execution times, compute total time sums, identify the threshold minimizing total time, and plot results. It also includes commented-out logic for analyzing per-parameter minimum indices and calculating an expe... | def karat_threshold_exp_2():
t_exp = defaultdict(list)
x_axis = []
time_sum = []
for threshold in range(1,200):
x_axis.append(threshold)
# print(threshold)
tmp = 0
cnt = 0
for i in range(1,50):
cnt += 1
print(threshold, i)
t =... |
def switch_to_failedlist(self):
self.log_debug("listing failed files")
maincontent = self.query_one("#main-container")
for child in maincontent.children:
child.remove()
failedList = FileList()
failedList.setFilePath(self.failed_path)
maincontent.mount(failedL... | This code defines an event handler for button presses, routing actions based on the button's ID. It switches screens, processes files, verifies structures, moves files, or exits the app depending on the pressed button, using a match-case structure for delegation. | def on_button_pressed(self, event: Button.Pressed) -> None:
"""Event handler called when a button is pressed."""
button_id = event.button.id
match button_id:
case "list_failed":
self.switch_to_failedlist()
case "process":
self.process_all_f... |
def timestamp():
return datetime.datetime.now().strftime("%Y-%m-%d-%H-%M-%S")
def update_metadata(metadata):
global METADATA
METADATA.update(metadata)
with open(os.path.join(DIRNAME, "metadata.yml"), 'w') as metadata_file:
metadata_file.write(yaml.dump(METADATA))
def run():
configure_kernel()
get_system... | (The main task of the code is to parse command-line arguments, load system and workload configurations, set Docker credentials, construct backend service/database mappings, create directory structures for logs and configs, initialize experiment metadata, save configuration files, and execute a benchmark experiment work... | def main():
# Parse command-line arguments.
parser = argparse.ArgumentParser(description="Run a BuzzBlog experiment")
parser.add_argument("--description", required=True, action="store",
type=str, help="Experiment description")
parser.add_argument("--system_conf", required=True, action="store",
type=... |
def run_prep(model_name):
# Remove directory from previous run
remove_dir = subprocess.Popen("rm -rf " + MOM6DIR + "/ocean_only/" + model_name,
shell=True)
remove_dir.wait()
# copy start directory into a new directory
create_dir = subprocess.Popen("cp -r double_gyr... | The code runs multiple iterations of the MOM6 model by altering a specified parameter (KH) incrementally. For each model in the list, it adjusts the parameter by a percentage that increases per iteration, updates the run name, prepares the simulation, writes parameter overrides, and executes the model with a specified ... | def run_multiple_configurations(model_list, percent_alteration, num_alters, num_proc):
"""Runs multiple iterations of the MOM6 model.
Each iteration a parameter is altered by percent alteration
percent_alteration is increase each time by step
Each model is run for a number of times specified by... |
def processBmsCellLevelVotage( self ):
#clear bmsCellLevelVotage data structure each time this function is called
#because we using the list.append() which will keep adding to the bmsCellVoltage data
self.bmsCellLevelVolages = []
#find cell level voltages at index 19 to 56( 14s battery b... | The main task of the code is to process Battery Management System (BMS) parameters by extracting raw data from specific byte ranges, calculating key metrics like cell voltages, current, cycles, bank voltage, bus voltage, and SOC, and storing them for further use. It uses helper methods to parse data, perform calculatio... | def processAllBmsParameters( self ):
#clear bmsCellLevelVotage data structure each time this function is called
#because we using the list.append() which will keep adding to the bmsCellVoltage data
#self.bmsCellLevelVolages = []
#find cell level voltages at index 19 to 56( 14s battery b... |
def create_parser():
#Handle user input with argparse
parser = argparse.ArgumentParser(description="matched detection flags and options from user")
parser.add_argument('-i', '--input',
default = 'flux_list.txt',
metavar = 'flux images',
type=str,
... | The code processes astronomical images to construct point spread functions (PSFs), performs PSF-based correlations on the images, generates a signal-to-noise ratio (SNR) image using inverse variance weighting, and saves intermediate results as FITS files. It handles GPU/CPU selection, loads data, creates PSFs, applies ... | def main():
#parse arguments
# read in command line arguments
parser=create_parser()
args=parser.parse_args()
#print arguments
if(args.verbose):
print_arguments(args)
#choose a correlation library
if(args.gpu):
import cusignal.convolution as sg
else:
impor... |
def halign(s,t):
"""Align two strings by Hamming distance."""
slen = len(s)
tlen = len(t)
minscore = len(s) + len(t) + 1
for upad in xrange(0, len(t)+1):
upper = '_' * upad + s + (len(t) - upad) * '_'
lower = len(s) * '_' + t
score = hamming(upper, lower)
if score... | The code processes linguistic data for languages by extracting transformation rules from training files, applying these rules to development data, and evaluating accuracy. It supports specifying input paths, generating output files, and handling prefix/suffix biases in morphological analysis, primarily for English and ... | def main(argv):
options, remainder = getopt.gnu_getopt(argv[1:], 'ohp:', ['output','help','path='])
OUTPUT, HELP, PATH = False, False, './../all/'
for opt, arg in options:
if opt in ('-o', '--output'):
OUTPUT = True
elif opt in ('-h', '--help'):
HELP = True
el... |
def _recent_info(self, stock , mvs = [20,50,100,200], names:tuple = ('OPEN','CLOSE','LOW','HIGH')):
'''
Get recent info about the data having it's Moving Averages Values, Candle Patterns, RSI, ATR, Bollinger etc
args:
stock: DataFrame of stock or the Name
interval: Rollin... | The function retrieves and analyzes recent stock data for a specified Nifty index or custom stock list, calculating technical indicators like SMA crossings, momentum, MACD, RSI, and Ichimoku signals. It compiles results into a structured DataFrame, storing it for future use and returning it for analysis. | def get_recent_info(self, nifty:int=200, custom_list:tuple = None, col_names:tuple = ('DATE','OPEN','CLOSE','LOW','HIGH'), **kwargs):
'''
Get Recent Info for all of the stocks and sort them accordingaly
args:
nifty: Nifty Index to check
custom_list: Names of Stocks which ... |
def setupFrequencyControls(self,frame):
freqFrame = self.frequencyFrame(frame)
self.dayOfWeekMenu(freqFrame)
self.dayOfMonthControls(freqFrame)
self.frequencyDecider(freqFrame)
def titleLabel(self, frame):
titleText = "Press 'Compile Report' to get started."
labelText = L... | The main task of the code is to initialize and configure UI widgets within a given frame, including frequency controls, title labels, a compile button, "please wait" status text, and a "finished" label. It sets up the interface for a frequency-related application, though some methods like `chooseFrequency` and `nextRep... | def setupWidgets(self, frame):
self.setupFrequencyControls(frame)
# frequencyFrame = self.frequencyFrame(frame)
self.titleLabel(frame)
# self.chooseFrequency(frequencyFrame)
# self.nextReportLabel(frame)
self.compileButtonMethod(frame)
self.pleaseWaitLabel(frame)
... |
def getData(self):
tprColumn = 'TPR\nPrior'
self.dateColumnName = 'TPR To'
tprPriority = 99
columnsToUse = "B,C,D,F,G,H,I,J,K,T"
columnRenaming = {'Description': 'Item Description',
'Reg\nPM': ' ',
'Reg\nPrice': 'Regu... | The `createReport` method orchestrates generating a report by retrieving data, configuring files, creating spreadsheet sheets, finalizing the report writer, performing post-processing tasks, and marking the report as completed. It systematically executes these steps to produce and finalize a structured report. | def createReport(self):
self.getData()
self.setupFiles()
self.createSheets()
self.reportWriter.close()
self.postProcessing()
self.completedReports() |
def createWindow(self):
window = Tk()
window.title("TPR Report")
window.geometry("400x300")
return window
def comboBoxVariables(self):
self.dayOfWeek = StringVar()
self.dayOfMonth = StringVar()
self.reportFrequency = StringVar()
def setupWidgets(self, frame):
... | The main task of the code is to create and configure a GUI window by initializing a main window, adding a frame widget, setting up combo boxes, arranging widgets within the frame, and returning the configured main window for display. | def setupDisplay(self):
mainWindow = self.createWindow()
mainFrame = Frame(mainWindow)
self.comboBoxVariables()
self.setupWidgets(mainFrame)
mainFrame.pack()
return mainWindow |
def parse_main():
"""Process base commands from the CLI."""
parser = argparse.ArgumentParser(description="Upload PUDL data archives to Zenodo")
parser.add_argument(
"--noop",
action="store_true",
default=False,
help="Review changes without uploading",
)
parser.add_arg... | The main task of the code is to manage Zenodo deposition archives via a CLI, allowing users to initialize new deposits, update existing ones, or simulate actions. It selects files, compares local/remote states, and executes uploads using Zenodo tokens (sandbox or production). Key features include handling metadata, dat... | def main():
"""A CLI for the PUDL Zenodo Storage system."""
args = parse_main()
if args.sandbox:
zenodo_upload_token = os.environ["ZENODO_SANDBOX_TOKEN_UPLOAD"]
else:
zenodo_upload_token = os.environ["ZENODO_TOKEN_UPLOAD"]
zenodo = ZenodoStorage(
key=zenodo_upload_token,
... |
def prompt_for_inventory_option(self, inventories):
# The options are rename inventory, modify inventory or create a new one
options = []
descriptions = []
for inventory in inventories:
options.append(('modify', inventory))
descriptions.append('Modify %s' % inven... | The code's main task is to let a user either rename an existing inventory or create a new one, then open a menu to modify the selected inventory. It retrieves player inventories, prompts for an action, executes the chosen operation, and launches an inventory modification interface. | def run(self):
print("Creating an inventory!")
inventories = Inventory.get_for_player(self.connection, self.player.username)
option, inventory = self.prompt_for_inventory_option(inventories)
if option == 'rename':
self.rename_inventory(inventory)
else:
i... |
def clear_file_list(self):
"""Empty the file list
"""
self.filenames = []
self.update_currentfiles()
self.checks = []
self.checkboxes = []
if self.pyanactrl is not None :
self.pyanactrl.quit_pyana()
self.pyanactrl.close()... | This code sets a run number from user input, searches for matching files using a filename pattern, updates the file list with found files, and triggers a quick scan of their contents. | def set_runnumber(self):
print("calling set_runnumber")
try:
self.runnumber = int(self.lineEditRun.text())
fileNamePattern = "e*-r%04d-*.xtc"%(self.runnumber)
except:
# ignore if not an integer
print("Didn't find any number in the box")
... |
def displayPlayerBoard(self) -> None:
"""
Function to display the current status of the player's board and determine if the player has lost the game.
:return: None
"""
lost: bool = True
output: str = ""
for i in range(10):
output: str = output + self._... | The code initializes a 'Controller' object by setting up the user interface, configuring label background colors (cyan for most, tan for 'rules' and 'fire' button), creating game board structures (__boardtop, __spaces, __rows, __playerboard, __computerboard), displaying both boards, and linking the 'fire' button to the... | def __init__(self, *args, **kwargs) -> None:
"""
Function to initialize the 'Controller' object by setting up the user interface, setting every label except the 'rules' label's background colors to cyan, setting the 'rules' label's and 'fire' push button's background colors to tan, creating a '__boardto... |
def load_pars_data(train_path, test_path,n_pars):
train_data = np.load(train_path)
X_train = train_data["name1"]
y_train = train_data["name2"]
test_data = np.load(test_path)
X_test = test_data["name1"]
y_test = test_data["name2"]
X_test_shape = X_test.shape
# shuffle
test_data_shufel... | The code implements a genetic algorithm to evolve neural network models on the Hoda dataset. It loads training/test data, initializes model populations with random weights/biases, evaluates accuracy across generations, selects top-performing models, and iteratively creates new generations through mutation. The process ... | def main(args):
# sample of read_hoda_dataset class to read and save resized matrix of data and write images before resize
mat_data_files_path = ["../Hoda_dataset/hoda_npz_files/HODA_MAT_DATA_TRAIN.npz", "../Hoda_dataset/hoda_npz_files/HODA_MAT_DATA_TEST.npz"]
X_train, y_train, X_test, y_test, n_classes, n... |
def download_file(url: str):
if not os.path.exists("sowpods.txt"):
r = requests.get(url=url)
with open("sowpods.txt", "w") as f:
f.write(r.text)
def get_data_from_file(filename: str) -> list[str]:
with open(filename) as f:
lines = f.readlines()
return lines
def pick_word(... | The main task of the code is to run a word guessing game by downloading a word list, selecting a random word, and prompting the user to guess it. The code retrieves words from a file, picks one randomly, and initiates a game where the user attempts to identify the chosen word. | def main():
download_file("http://norvig.com/ngrams/sowpods.txt")
lines = get_data_from_file("sowpods.txt")
word = pick_word(lines).strip().lower()
print(f"you have to guess the word: {word}")
guessing_game(word) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.