dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def get_arguments(self):
parser = argparse.ArgumentParser()
parser.add_argument("--init_image", type=str, default="", help="a source image to edit")
parser.add_argument("--mask", type=str, default="", help="a mask to edit the image")
parser.add_argument(
"--invert_mask",
... | This code initializes a model for image generation/editing by loading a pre-trained latent diffusion model, configuring device settings (GPU/CPU), preparing input images and masks, and reconstructing background samples from a dataset. It sets up parameters, loads model weights, processes image/mask inputs, and prepares... | def __init__(
self,
verbose: bool = False,
):
self.opt = self.get_arguments()
config = OmegaConf.load("configs/latent-diffusion/txt2img-1p4B-eval.yaml")
self.device = (
torch.device(f"cuda:{self.opt.gpu_id}")
if torch.cuda.is_available()
el... |
def predict(self, Xs):
'''Returns the model predictions (output of the last layer) for the given "Xs".'''
predictions = []
num_samples = Xs.shape[0]
for i in range(num_samples):
sample = Xs[i,:].reshape((1,self.input_shape))
sample_prediction = self.forward_pass(s... | The code evaluates a model's performance on a given dataset by calculating accuracy and cross-entropy loss between predicted and true labels, then returns these metrics along with the predictions. | def evaluate(self, Xs, Ys):
'''Returns appropriate metrics for the task, calculated on the dataset passed to this method.'''
pred = self.predict(Xs)
acc = self.accuracy(pred, Ys)
loss = self.cross_entropy_loss(pred, Ys)
return acc,loss,pred |
def forward_pass(self, input_data):
'''Executes the feed forward algorithm.
"input_data" is the input to the network in row-major form
Returns "activations", which is a list of all layer outputs (excluding input layer of course)
What is activation?
In neural network you have inpu... | This code trains a neural network model using gradient descent by iterating over the dataset for a specified number of epochs. It performs forward and backward passes on each sample, updates weights via backpropagation, and records loss and accuracy metrics after each epoch. The function returns a list of losses per ep... | def fit(self, Xs, Ys, epochs, lr=1e-3):
'''Trains the model on the given dataset for "epoch" number of itterations with step size="lr".
Returns list containing loss for each epoch.'''
history = []
for epoch in range(epochs):
num_samples = Xs.shape[0]
for i in ran... |
def satML(P:np.array, ML:np.array) -> float:
sat = 0
for ml in ML:
if P[ml[0]] == P[ml[1]]:
sat += 1
return sat/ML.shape[0]
def norm_sil(data:np.array, P:np.array) -> float:
return (silhouette_score(data,P) + 1)/2
def satCL(P:np.array, CL:np.array) -> float:
sat = 0
for cl in... | The function calculates a weighted combination of two averaged scores: one from ML and norm_sil, the other from CL and NH, using ALPHA as the weight. It returns a float representing the blended result of these components. | def satC_ML_CL_split(data:np.array,P:np.array,ML:np.array,CL:np.array) -> float:
return ALPHA*((satML(P,ML)+norm_sil(data,P))/2) + (1-ALPHA)*((satCL(P,CL) + NH(data,P))/2) |
def satC(P:np.array, ML:np.array,CL:np.array) -> float:
sat = 0
for ml in ML:
if P[ml[0]] == P[ml[1]]:
sat += 1
for cl in CL:
if P[cl[0]] != P[cl[1]]:
sat += 1
return sat/(len(ML) + len(CL))
def NH(data:np.array, P:np.array) -> float:
COM = coAssociation_matri... | The function `satC_muli_comb` computes a composite value by multiplying three components: `satC(P, ML, CL)` (likely a saturation or capacity metric), `NH(data, P)` (possibly a normalization or helper function), and `norm_sil(data, P)` (likely a normalized signal or similarity measure). The result is a single float repr... | def satC_muli_comb(data:np.array,P:np.array,ML:np.array,CL:np.array) -> float:
return satC(P, ML, CL) * NH(data, P) * norm_sil(data,P) |
def satML(P:np.array, ML:np.array) -> float:
sat = 0
for ml in ML:
if P[ml[0]] == P[ml[1]]:
sat += 1
return sat/ML.shape[0]
def satCL(P:np.array, CL:np.array) -> float:
sat = 0
for cl in CL:
if P[cl[0]] == P[cl[1]]:
sat += 1
return sat/CL.shape[0]
def NH(d... | The function computes a weighted combination of two components: a product of satML and satCL functions scaled by ALPHA, and the average of NH and norm_sil functions scaled by (1-ALPHA), returning a float result. | def sat_split_NH_sil(data:np.array,P:np.array,ML:np.array,CL:np.array) -> float:
return ALPHA*satML(P,ML)*satCL(P,CL) + (1-ALPHA)*((NH(data,P) + norm_sil(data,P))/2) |
def satML(P:np.array, ML:np.array) -> float:
sat = 0
for ml in ML:
if P[ml[0]] == P[ml[1]]:
sat += 1
return sat/ML.shape[0]
def NH(data:np.array, P:np.array) -> float:
COM = coAssociation_matrix(P)
dis_mat = euclidean_distances(data, data)
COM = 1 - COM
coef = np.corrcoef... | This function computes a weighted average of two saturation metrics, satML and satCL, combined with NH and norm_sil factors. It prioritizes the larger array (ML or CL) by conditionally scaling their contributions, returning a blended score that balances saturation and normalization values based on input dimensions. | def sat_split_multi_comb(data:np.array,P:np.array,ML:np.array,CL:np.array) -> float:
if ML.shape[0] > CL.shape[0]:
return (satML(P,ML)*NH(data,P)*norm_sil(data,P) + satCL(P,CL))/2
else:
return (satCL(P,CL)*NH(data,P)*norm_sil(data,P) + satML(P,ML))/2 |
def satC(P:np.array, ML:np.array,CL:np.array) -> float:
sat = 0
for ml in ML:
if P[ml[0]] == P[ml[1]]:
sat += 1
for cl in CL:
if P[cl[0]] != P[cl[1]]:
sat += 1
return sat/(len(ML) + len(CL))
def norm_sil(data:np.array, P:np.array) -> float:
return (silhouette_... | This function computes a weighted combination of two terms: a product of ALPHA, satC(P,ML,CL), and norm_sil(data,P), plus (1-ALPHA) multiplied by NH(data,P), returning a float. It blends saturation-related calculations with normalization and NH parameters, likely for modeling or analysis tasks involving data arrays and... | def satC_sil_pNH(data:np.array,P:np.array,ML:np.array,CL:np.array) -> float:
return ALPHA*satC(P,ML,CL)*norm_sil(data,P) + (1-ALPHA)*NH(data,P) |
def satC(P:np.array, ML:np.array,CL:np.array) -> float:
sat = 0
for ml in ML:
if P[ml[0]] == P[ml[1]]:
sat += 1
for cl in CL:
if P[cl[0]] != P[cl[1]]:
sat += 1
return sat/(len(ML) + len(CL))
def norm_sil(data:np.array, P:np.array) -> float:
return (silhouette_... | The function calculates a weighted average of two components: the product of `satC` (a saturation-related metric) and `norm_sil` (a normalized signal integrity measure), and `NH` (possibly a noise or harmonic term), both derived from input arrays. It returns the mean value of these combined terms, likely for evaluating... | def satC_NH_sil_add(data:np.array,P:np.array,ML:np.array,CL:np.array) -> float:
return (satC(P,ML, CL)*norm_sil(data,P) + NH(data,P))/2 |
def satC(P:np.array, ML:np.array,CL:np.array) -> float:
sat = 0
for ml in ML:
if P[ml[0]] == P[ml[1]]:
sat += 1
for cl in CL:
if P[cl[0]] != P[cl[1]]:
sat += 1
return sat/(len(ML) + len(CL))
def NH(data:np.array, P:np.array) -> float:
COM = coAssociation_matri... | The function `satC_mComb` computes a weighted sum of two components: a saturation concentration term scaled by `ALPHA` and a product of normalized data features `NH` and `norm_sil`, scaled by `(1-ALPHA)`. It combines these terms to model a hybrid concentration metric using input arrays `data`, `P`, `ML`, and `CL`, retu... | def satC_mComb(data:np.array,P:np.array,ML:np.array,CL:np.array) -> float:
return ALPHA*satC(P, ML, CL) + (1-ALPHA)*NH(data,P)*norm_sil(data,P) |
def satC(P:np.array, ML:np.array,CL:np.array) -> float:
sat = 0
for ml in ML:
if P[ml[0]] == P[ml[1]]:
sat += 1
for cl in CL:
if P[cl[0]] != P[cl[1]]:
sat += 1
return sat/(len(ML) + len(CL))
def NH(data:np.array, P:np.array) -> float:
COM = coAssociation_matri... | The function `satC_comb` computes a weighted average of two components: a scaled saturation value `satC(P, ML, CL)` and the average of `NH(data, P)` and `norm_sil(data, P)`. The result is a float, combining the weighted contributions of saturation and normalized signal/noise metrics, controlled by the parameter `ALPHA`... | def satC_comb(data:np.array,P:np.array,ML:np.array,CL:np.array) -> float:
return ALPHA*satC(P,ML,CL) + (1-ALPHA)*((NH(data,P) + norm_sil(data,P))/2) |
def read_in_level(self, level_number):
filepath = os.path.join("levels", self.levels[level_number])
with open(filepath, "r") as f:
csv_reader = csv.reader(f, delimiter=';')
self.level_array = list(csv_reader)
self.level_array = [x for x in self.level_array if x != []]... | The main task of the code is to initialize and run a game loop for a level-based application. It loads a predefined level file, maintains a game loop with a 30 FPS cap, processes keydown events, updates game state, and renders frames. The loop continues until `keep_looping` is set to False, handling input, logic, and r... | def main(self):
#Level names are stored in a list
self.levels = ['demolvl.txt']
#Call read_in_level with the index of the level that should be loaded.
self.read_in_level(self.level_number)
while self.keep_looping:
self.clock.tick(30)
... |
def read_in_level(self, level_number):
self.scanned_tiles.clear()
if level_number < 0:
random_level = RandomLevel(self.level_number, self.levels)
self.level_array = random_level.level_array
else:
filepath = os.path.join("levels", self.levels[level_number])
... | This code updates the game state by handling level restarts, processing key inputs, and redrawing the game surface. It clears scanned tiles, reloads the level if needed, updates surface/time variables, triggers key events (if not reset), and redraws the scene. The core task is maintaining game state consistency during ... | def update(self, surface, key, time_tick):
if (self.flag_restart == 1):
self.scanned_tiles.clear()
self.flag_restart = 0
self.read_in_level(self.level_number)
self.surface = surface
self.time_tick = time_tick
if not self.reset:
self.keydow... |
def display_board(game):
print("\n*********Game Board*********\n")
print(game.mat)
def check_victory(game):
board = game.mat
for y in range(game.col):
for x in range(game.row - 3):
if board[x][y] == 1 and board[x+1][y] == 1 and board[x+2][y] == 1 and board[x+3][y] == 1:
... | The code implements a Connect Four game menu and core gameplay loop, allowing users to set board dimensions, choose game mode (human vs. human or human vs. computer), and difficulty level. It manages turn-based moves, validates player/column inputs, applies moves, checks for wins/draws, and alternates turns, with compu... | def menu():
print ("Welcome to Connect Four!\n\nPlease enter the number of rows and columns for your board")
r = input("Rows: ")
c = input("Cols: ")
com = -1
while not (com == 1 or com == 2):
print("\nPlease select your game mode:\n1. Human vs. Human\n2. Human vs. Computer\n")
com =... |
def display_board(game):
print("\n*********Game Board*********\n")
#Flip the board on y-axis and print
for x in range(game.rows):
for y in range(game.cols):
print(str(int(game.mat[game.rows -1 -x][y])) + "\t"),
print ("\n")
def check_victory(game):
board = game.mat
#Check... | The code sets up and manages a Connect Four game, allowing users to configure the board size, select game mode (human vs. human or human vs. computer), and handle player turns with insert/pop actions. It validates inputs, enforces game rules, and checks for wins/draws, with computer moves determined by selected difficu... | def menu():
game = Game()
print ("Welcome to Connect Four!\n\nPlease enter the number of rows and columns for your board")
rows = input("Rows: ")
cols = input("Cols: ")
wins = -1
while wins < 0:
wins = input("Please enter the number of pieces to win: ")
if wins > m... |
def tx_sync(self):
"""Send a sync."""
if not 0 < self.tx_proto < len(PROTOCOLS):
_LOGGER.error("Unknown TX protocol")
return False
return self.tx_waveform(PROTOCOLS[self.tx_proto].sync_high,
PROTOCOLS[self.tx_proto].sync_low)
def tx_l0(self... | The main task of the code is to transmit a binary code by iterating over each bit, sending '0' or '1' using `tx_l0()`/`tx_l1()` based on the input, with synchronization checks before and after each transmission. It repeats the process `tx_repeat` times and returns `True` on success or `False` if any transmission step f... | def tx_bin(self, rawcode):
"""Send a binary code."""
_LOGGER.debug("TX bin: " + str(rawcode))
for _ in range(0, self.tx_repeat):
if self.tx_proto == 6:
if not self.tx_sync():
return False
for byte in range(0, self.tx_length):
... |
def create_chassispart(chassisname): #this function creates chassis part of the config, which is called by create_and_run_func
global TEXTTOEDIT
CHASSIS = chassisConfig.objects.get(name =chassisname)
TEXTTOEDIT = CHASSIS.config.configPart #we derive a part of config to edit
create_part_of_config(CHASSIS... | This function creates configuration parts for a chassis and neighborhood, retrieves a specified test configuration, generates the test's config components, and executes the test while recording results. | def create_and_run_test(test,testname,chassisname,neighborhoodname): #this is "main" function - it calls functions which creates all parts of config and runs
global TEXTTOEDIT
create_chassispart(chassisname)
create_neighborhoodpart(neighborhoodname)
TEST = test.objects.get(name=testname)
TEXTTOEDIT ... |
def init_malmo(self):
"""
Initialize new malmo mission.
"""
my_mission = MalmoPython.MissionSpec(self.get_mission_xml(), True)
my_mission_record = MalmoPython.MissionRecordSpec()
my_mission.requestVideo(800, 500)
my_mission.setViewpoint(1)
max_retries = 3... | The code resets the environment for a new episode by reinitializing Malmo, tracking episode metrics (returns, steps), resetting agent state variables (damage, air level), updating metadata logs, and returning a flattened initial observation array. | def reset(self):
"""
Resets the environment for the next episode.
Returns
observation: <np.array> flattened initial obseravtion
"""
# Reset Malmo
world_state = self.init_malmo()
# Reset Variables
self.returns.append(self.episode_return)
... |
def init_malmo(agent_host):
"""
Initialize new malmo mission.
"""
my_mission = MalmoPython.MissionSpec(GetMissionXML(), True)
my_mission_record = MalmoPython.MissionRecordSpec()
my_mission.requestVideo(800, 500)
my_mission.setViewpoint(1)
max_retries = 3
my_clients = MalmoPython.Cli... | The code trains a DQN agent in the Malmo environment using experience replay. It initializes Q-networks, an optimizer, and a replay buffer. The agent interacts with the environment, collects observations, selects actions (with epsilon-greedy), and stores transitions. Periodically, it samples batches to update the Q-net... | def train(agent_host):
"""
Main loop for the DQN learning algorithm
Args:
agent_host (MalmoPython.AgentHost)
"""
# Init networks
q_network = QNetwork((2, OBS_SIZE, OBS_SIZE), len(ACTION_DICT))
target_network = QNetwork((2, OBS_SIZE, OBS_SIZE), len(ACTION_DICT))
target_network.lo... |
def read_word_frequencies_from_csv(csv_file):
"""
Read word frequencies from a CSV file and return a dictionary.
Parameters:
- csv_file (str): Path to the CSV file containing word frequencies.
Returns:
- dict: Dictionary containing word frequencies.
"""
word_frequencies = {}
# Op... | The code optimizes a touchscreen keyboard layout using the Metropolis algorithm. It reads word frequencies from a CSV file, calculates transitional frequencies, and iteratively adjusts the keyboard layout to minimize Fitts’ law movement time. The function returns the optimized layout and a sequence of movement time val... | def optimization(a, b, k, T, N, keyboard_layout):
"""
Parameter
1. a = 0.083 ( Touchscreen keyboarding - Fitts’ law parameter )
2. b = 0.127 ( Touchscreen keyboarding - Fitts’ law parameter )
3. k : k is a coefficient, input your value in main.py
4. T : T is temperature, input your value in main... |
def _check_rx_handler_serial_or_ethernetclient(self, interface):
'''
This method will check to see if the rx handler is resetting the send counter to 0. if not it will create a new rx handler and assign it to the interface
:param interface:
:return:
'''
print('_check_rx_h... | This function handles sending data through a network interface, tracking send counters, checking connection status, and managing disconnection logic. It prints debug info, increments send counters only when connected, and triggers a logical disconnect if send limits are exceeded. If connected, it invokes the user-defin... | def new_send(*args, **kwargs):
print('new_send args={}, kwargs={}'.format(interface, args, kwargs))
if interface in self._debugInterfaces:
oldPrint(
'new_send args={}, kwargs={}'.format(args, kwargs),
', new_send send_c... |
def _check_rx_handler_serial_or_ethernetclient(self, interface):
'''
This method will check to see if the rx handler is resetting the send counter to 0. if not it will create a new rx handler and assign it to the interface
:param interface:
:return:
'''
print('_check_rx_h... | This function handles sending data via a communication interface, tracks send counters, checks for disconnect limits, executes the wrapped send method, logs debug info, handles exceptions by disconnecting if needed, and resets counters on successful sends. It ensures proper error logging, connection state updates, and ... | def new_send_and_wait(*args, **kwargs):
print('new_send_and_wait args={}, kwargs={}'.format(args, kwargs))
if interface in self._debugInterfaces:
oldPrint(
'new_send_and_wait args={}, kwargs={}'.format(args, kwargs),
',... |
def _check_connection_handlers(self, interface):
print('UCH._check_connection_handlers')
# if the user made their own connection handler, make sure our connection handler is called first
if interface not in self._connected_handlers:
self._connected_handlers[interface] = None
... | This method initializes send counters for a given interface, verifies required connection components, and sets the connection status for SerialInterface instances to 'Connected' via ControlScript2, ensuring proper client-side logical connection handling. | def _add_logical_connection_handling_client(self, interface):
print('_add_logical_connection_handling_client')
# Initialize the send counter to 0
if interface not in self._send_counters:
self._send_counters[interface] = 0
self._check_connection_handlers(interface)
s... |
def update_processors_usage(current_time: int, parameters: list):
for processor in processors:
for process in processor.current_processes:
if current_time >= process.arrival_time + process.waiting_time + process.burst_time:
processor.complete_process(process)
hand... | This code simulates a process scheduling system with resource management, tracking processor usage, handling process migrations, and visualizing average usage over time. It initializes parameters, processes arrival times, updates usage data, and generates plots to analyze system performance, including migration counts ... | def start(title: str, max_attempts: int, max_usage: float, max_migrations=0):
processors_usages = np.ndarray([processes_amount + 10, processors_amount])
logs = 0
parameters = [max_attempts, max_usage, max_migrations, 0, 0]
[i.reset() for i in processors]
[i.reset() for i in processes]
avg_usage... |
def _update_canvas_size(self):
''' Update the size of the canvas.
Change the canvas size based on the scale attribute.
'''
self.canvas_size = tuple([x * self.scale for x in self.image.shape[:2][::-1]])
def _update_text_locs(self):
''' Update the text locations.
Update ... | The main task of the code is to initialize a GUI with specified scaling factors and parameters. It sets up the window, adjusts scaling based on image size, initializes variables for canvas/text updates, and configures keyboard input handling. The function creates an OpenCV window, enforces scale limits, and prepares GU... | def _init_gui(self, scale, text_scale, shuffle_colors=True, refresh=100):
''' Initializes the GUI
Takes in the scaling factor and keyboard input delay. In addition,
this function creates the window, names it, and updates the
canvas and text.
Parameters
----------
... |
def _update_canvas(self):
''' Update the canvas
Make a canvas, draw in text, lines, and points over
the existing window.
'''
self._update_canvas_size()
self._update_text_locs()
self._init_canvas()
self._draw_text()
self._draw_lines()
sel... | The code runs a program by creating an OpenCV window, handling mouse and keyboard inputs, and continuously updating the canvas. It loops, checking for hotkeys and exit conditions, then closes the window upon exit. | def run(self):
''' Run the program.
Runs the program by continually calling for hotkeys function
defined in the subclasses.
'''
cv2.namedWindow(self.window_name)
cv2.setMouseCallback(self.window_name,
_mouse_click,
... |
def set_window_title_icon(self):
title_icon = QIcon()
title_icon.addFile(u":/file_open/icons/icons8-template-80.png", QSize(), QIcon.Normal, QIcon.Off)
self.setWindowIcon(title_icon)
def initialize_connections(self):
self.ui.xlsRawFilePathBrowse_Button.clicked.connect(self.open_xls_raw_f... | This code initializes a main window for an Excel data parsing application. It sets up UI components, initializes variables to store Excel file paths and data, configures the initial interface state (showing the raw Excel import page), and connects UI elements to functionality. The commented-out code suggests planned cu... | def __init__(self):
super(MainWindow, self).__init__()
self.saved_parsed_excel_path = None
self.raw_excel_df = None
self.raw_xls_chosenColumn = ""
self.raw_xls_filepath = ""
self.ui = Ui_Parser_UI()
self.ui.setupUi(self)
# Access the titlebar_frame as a ... |
def parse_bracket_c(self):
if self.cur() != '(':
raise ValueError("( expected")
self.skip()
val = self.parse_c(True)
if self.cur() != ')':
raise ValueError(") expected")
self.skip()
return val
def cur(self):
if self.c < len(self.input):
... | The function parses a bracket-enclosed list recursively. It starts by parsing an element via `parse_bracket_c()`, then checks for a null terminator (`chr(0)`). If found, it returns a list containing the parsed element. Otherwise, it recursively parses the remaining list, prepends the current element to the result, and ... | def parse_bracket_list(self):
f = self.parse_bracket_c()
if self.cur() == chr(0):
return [f]
else:
rest = self.parse_bracket_list()
rest.insert(0, f)
return rest |
def fitData(cases_df, fipslist):
"""
Takes in list of fips and slices the dataframe given
Then fits to logLinearModel and exponentModel and reports Squared Errors
"""
cases_sliced = cases_df[cases_df["fips"].isin(fipslist)]
xdata = cases_sliced["days_from_start"]
logydata = cases_sliced["l... | The main task of the code is to solve an optimization problem using dynamic programming by recursively partitioning a set of combinations (`comboSets`) into `nLines` groups, minimizing a model-specific error metric (e.g., SEExp/SELog). It memoizes results in `LookupTable`, tracks optimal solutions in `OptTable`, and re... | def problem(self, comboSets, nLines, model):
"""
recursive DP for solving the problem
"""
# Already solved before
if self.LookupTable[model][repr(comboSets)][nLines]:
return self.OptTable[model][repr(comboSets)][nLines]
# Empty set assigned
if len(com... |
def login(self):
self.driver.get('https://www.instagram.com/')
x_username = r'//*[@id="loginForm"]/div/div[1]/div/label/input'
x_password = r'//*[@id="loginForm"]/div/div[2]/div/label/input'
self.wait(By.XPATH, x_username)
username_input = self.driver.find_element_by_xpath(x_use... | The main task of the code is to log in and repeatedly like social media posts until a specified maximum number of likes (self.max_like) is reached. It processes posts, increments a counter with each like, and prints progress updates. The loop terminates once the target number of likes is completed, ensuring automated e... | def start(self):
self.login()
num_processed = 0
while num_processed < self.max_like:
self.get_posts()
num_processed += self.like_util()
print('Number processed:', num_processed)
print('Completed:', num_processed) |
def makeDistanceMatrix(leafs):
distanceMatrix =[[0 for c in range(len(leafs))] for r in range(len(leafs))]
distanceMatrixMax = [0 for c in range(len(leafs))]
for i in range(len(leafs)):
for j in range(len(leafs)):
if (i==j):
distanceMatrix[i][j] =None
dist... | The code performs multiple sequence alignment (MSA) using a tree-based approach. It reads input sequences, constructs a tree by iteratively merging the closest pairs of sequences based on a distance matrix, updates the matrix after each merge, and finally generates the MSA. The alignment is scored and printed, with the... | def __main__():
# print (global_align('HVLIP','HVLP',1,-1,-2))
seqnumber = int(input())
# seqnumber = 4
sequenses = []
# sequenses = ['HVLIP','HMIP','HVLP','LVLIP']
for i in range(seqnumber) :
sequenses.append(input())
# print (sequenses)
leafs = []
for seq in sequens... |
def distancebetween (a, b):
#return the nearest integer distance between two points
return int(math.sqrt((a[0] - b[0])**2 + (a[1] - b[1])**2))
def mst(c, e):
#initialization
taken_edges = []
edge_index = 0
#while we have not found #vert-1 edges,
while len(taken_edges) < len(c)-1:
#1. choose smallest next... | The code reads coordinates from a file, generates all possible edges between them, calculates edge distances, sorts edges by weight, computes a Minimum Spanning Tree (MST), and outputs the selected edges, total weight, and vertex coverage. It processes input data to construct and analyze a graph's MST. | def run(filename):
#open and read from file
with open(filename, "r") as f:
readlines = f.read().splitlines()
f.close()
#get count - first line
count = readlines[0]
#now we know the lines
lines = readlines[1:int(count) + 1]
#generate coordinate list
coords = [[int(y) for y in x.split(" ")] for x in lines]... |
def _check_result_exists(self, model_id, data_id, train_ids, test_ids, tag, seed):
"""check if result already exists"""
filename = self._get_res_filename(model_id, data_id, train_ids, test_ids, tag, seed)
my_file = Path(filename)
if my_file.is_file():
return pd.read_csv(filen... | The function performs machine learning predictions using a specified model on provided or loaded data. It checks for existing results, loads training/test data, fits the model, executes prediction, processes outputs into a DataFrame, and saves results if enabled. It handles both user-provided data and file-loaded data,... | def qpredict(self, model_id, data_id, data=None, ids=None, tag='',
save_result=True, save_model=False, force=False, filename=None, seed=1000, Y_test=None):
if ids is not None:
train_ids, test_ids = ids
res = self._check_result_exists(model_id, data_id, train_ids, test_id... |
def __is_in_time_constraints(self, time) -> bool:
if not self.__event_buffer:
if self.__read_start_time == -1:
return False
previous_time = self.__read_start_time
else:
previous_time = self.__event_buffer[-1].time
delta = time - previous_time
... | The main task of the code is to validate time constraints. If the current time does not meet the constraints, it attempts to execute buffered text data. If execution fails, it stops further reading to prevent invalid or incomplete data processing. | def __validate_time_constraints(self):
if not self.__is_in_time_constraints(now()):
if not self.__try_execute(self.__txt_buffer):
self.__stop_reading() |
def open_dl_dialog(self):
"""
Open the download dialog from the search result interface.
"""
# should wait for the search result to be ready
sleep(1)
open_dl_link = self.browser \
.find_element(By.XPATH, "//a[text()='Scarica']")
self.wait_and_click(ope... | The function iterates over date blocks to download datasets by opening a download tab, selecting date ranges, initiating downloads, and polling the download page to confirm completion. It loops until all date intervals are processed, adjusting dates by the block size (in days) each iteration. Parameters define the bloc... | def download_iteration(self, block_size: int):
"""
This function contains the main function that performs the iteration over
the blocks and downloads the datasets.
First of all, it opens another tab containing the download page
(`about:downloads`) and focuses back to the previou... |
def load_user_config():
""" loads user configuration json file into dictionary """
# gonna let the json error checking take care of itself
with open("user_config.json", 'r') as conf_file:
user_configs = json.load(conf_file)
return user_configs
def load_rate_limit_file(rate_limit_thing, file_na... | The main task of the code is to process user input (IP/domain) by validating it, applying rate limits, and querying APIs like abuseIPDB, IP geolocation, and malware bazaar. It loads configurations, manages rate-limiting contexts, and conditionally executes API calls based on input type. The loop handles input validatio... | def main():
""" gets user input and calls all the other functions """
print("loading user configurations...")
user_configs = load_user_config()
print("configurations loaded successfully")
# ip abuse db 1000 req per day
ip_abuse_rate_limiter = rate_limit(1000, 86400)
# ip abuse db report 10... |
def parse_roadtype(fp,weglist):
while True:
line=fp.readline().rstrip(' \n')
if not line:
break
if (line[0]!='#'):
pri_dbg(line)
s=line.split(' ')
pa=punt()
pi=punt()
pb=punt()
if (line[1]=='d'):
get_one_roadpos(s[0],s[1],pa) # position
add_r... | This function processes a GPX track list by assigning road surface types from an external file. It reads road type data, matches it to track points within 0.5 units distance, and updates the track's RoadSurface attributes. The process ensures all track segments have valid surface types, defaulting to SIMULATION_OFF if ... | def add_roadtype1(gpx_list,wfn):
if (wfn==None):
return
weglist=wegpunten()
if (path.exists(wfn)):
fp = open(wfn, 'r')
parse_roadtype(fp,weglist)
gpx_list.roadsurface_changes=weglist
fp.close()
pri_dbg("Add road type1...")
p1=None
for wl in weglist:
pa=wl.pa
pi=wl.pi
pb=wl.... |
def get_user_input(self, message):
return input(message)
def add_user(self):
# Get all the attributes for users
name = self.get_user_input('What is the user\'s name? ')
address = self.get_user_input('What is the user\'s address? ')
phone = self.get_user_input('What is the user\'s... | This method processes user menu selections by routing input to corresponding actions like adding users, filtering, saving/loading data, or exiting. It retrieves input, checks for valid options (1-7), and executes associated methods. Invalid inputs re-display the menu, maintaining an interactive loop until the user choo... | def process_menu_options(self):
user_input = self.get_user_input('What would you like to do? ')
# Process the user's input into methods
if user_input == '1':
self.add_user()
elif user_input == '2':
self.filter_users()
elif user_input == '3':
s... |
def move_right(self, grid):
# to move right we just reverse
# the matrix
new_grid = self.reverse(grid)
# then move left
new_grid, changed = self.move_left(new_grid)
# then again reverse matrix will
# give us desired result
new_grid = self.re... | This code executes a game step by applying a movement action (left/right/up/down) to the game grid. It checks if the action causes a change: if not, it penalizes with -10. If changed, it updates the grid, adds a new tile, and returns the new state and reward. If the game is lost, it ends the episode with the final rewa... | def step(self, action):
action_dict = {0:self.move_right(self.state),1:self.move_left(self.state),2:self.move_down(self.state),3:self.move_up(self.state) }
if not self.loss():
new_grid, changed = action_dict[action] # takes action
if not changed:
return self.sta... |
def reward(self):
"""
Fonction reward qui calcule le reward donne a chaque mouvement.
Verification si le mouvement est valide, si vicotire arrete, si victoire ou perte ou matche nul
+ Nombre de couts joue (empeche de tourner a jamais)
Args:
action (Int): Case jouee
... | The main task of the code is to handle a single step in a turn-based game where the AI (player) takes an action, checks for a win, updates the game state, and then simulates the opponent's move (CPU or random). It returns the updated game state, reward value, whether the game is done, and additional info. The function ... | def step(self, action): #player
"""
Fonction utilise a chaque etape
1. Verifcation du mouvement
2. Calcul du "reward" pour le mouvement fait
3. Faire le mouvement + verification si victoire
4. Calcul du mouvement de l'adverssaire
5. Verification de victo... |
def _prepare_sheet_id(start_location: str) -> str:
"""
This method prepares the sheet id for the Google Sheet API
:param start_location: start location IATA code
:return: Ready to use sheet id for application e.g. 'FROM_GDA'
"""
return f'FROM_{start_location}'
def _prepar... | This method retrieves flight data from a Google spreadsheet using the Sheets API, processes it into a dictionary mapping IATA codes to their lowest prices, and returns the result. It prepares the spreadsheet range, reads values, filters valid rows, and constructs the dictionary with IATA codes as keys and integer price... | def _read_flights(self, start_location: str) -> dict:
"""
This method reads all flights data from the connected Google spreadsheet
:param start_location: start location IATA code
:return: dictionary of flights data {'iataCode1': 'lowestPrice1', 'iataCode2': 'lowestPrice2'}
"""
... |
def _prepare_sheet_id(start_location: str) -> str:
"""
This method prepares the sheet id for the Google Sheet API
:param start_location: start location IATA code
:return: Ready to use sheet id for application e.g. 'FROM_GDA'
"""
return f'FROM_{start_location}'
def _prepar... | The main task of the code is to retrieve a list of destination airport IATA codes from a Google spreadsheet for a given start location IATA code. The method prepares the spreadsheet range, reads data via the Sheets API, extracts the first column (destinations), and returns them as a list. | def get_destination_airports(self, start_location: str) -> list:
"""
This method reads all destinations for given start location from the connected Google spreadsheet
:param start_location: start location IATA code
:return: list of destinations IATA codes
"""
self._logger... |
def _prepare_sheet_id(start_location: str) -> str:
"""
This method prepares the sheet id for the Google Sheet API
:param start_location: start location IATA code
:return: Ready to use sheet id for application e.g. 'FROM_GDA'
"""
return f'FROM_{start_location}'
def _prepar... | The main task of the code is to retrieve the number of flights from a Google spreadsheet using the Sheets API, based on a given start location's IATA code. It prepares the sheet ID and range, reads flight data, and returns the count of flights. | def _get_flights_amount(self, start_location: str) -> int:
"""
This method reads the amount of flights from the connected Google spreadsheet
:param start_location: start location IATA code
:return: amount of flights
"""
self._logger.debug(f'Reading flights amount for {sta... |
def _check_if_sheet_exists(self, sheet_id: str) -> bool:
"""
This method checks if the sheet exists in the connected Google spreadsheet
:param sheet_id: Sheet id to be checked e.g. 'Sheet1'
:return: True if a sheet exists, False otherwise
"""
status = False
self.... | This function updates flight data in a Google Sheet by checking if the new price is lower than the existing one. If the destination airport doesn't exist in the sheet, it adds the flight. If the price is lower, it updates the sheet and returns 0; otherwise, it returns 1. It also creates new sheets for origin airports i... | def update_flight(self, flight: FlightData) -> int:
"""
This method updates the flight data in the connected Google sheet
:param flight: See FlightData class for more information.
:return: status code (0 - updated with lower price, 1 - not updated)
:raises ValueError: if error oc... |
def get_lesson_number_at_time(time):
lesson_time = get_lesson_time()
for _, row in lesson_time.iterrows():
if row['start'] <= time <= row['end']:
return row['lesson number']
return 0
def get_lesson_duration(lesson_number: int):
lesson_time = get_lesson_time()
row = lesson_time[le... | This function determines if a lesson occurs at a specific time by checking each minute offset in the input list. It adjusts the given time by each minute, checks for a lesson, and verifies if the current time falls within the lesson's start time window. If valid, it returns the lesson details and number; otherwise, ret... | def get_lesson_in_minutes(today, week, time, minutes):
for minute in minutes:
lesson_number = get_lesson_number_at_time(time+datetime.timedelta(minutes=minute))
if lesson_number:
start, _ = get_lesson_duration(lesson_number)
if (datetime.timedelta(minutes=0, hours=0) < time -... |
def find_frequent_items(transactions, threshold):
"""
Create a dictionary of items with occurrences above the threshold.
"""
items = {}
for transaction in transactions:
for item in transaction:
if item in items:
items[item] += 1
... | This code initializes an FP-tree for frequent pattern mining. It identifies frequent items from transactions using a threshold, constructs a header table for item frequencies, and builds the FP-tree structure with the given root value and count. The tree is prepared to support efficient mining of frequent itemsets from... | def __init__(self, transactions, threshold, root_value, root_count):
"""
Initialize the tree.
"""
self.frequent = self.find_frequent_items(transactions, threshold)
self.headers = self.build_header_table(self.frequent)
self.root = self.build_fptree(
transaction... |
def createFolder(foldername):
"""
Will create this folder if it does not exist at the moment
"""
if (path.exists(foldername)):
return
try:
os.makedirs(foldername)
except OSError as err:
if err.errno != errno.EEXIST:
raise
def getFileContent(filename):
content = None
if path.exists(filename):
f = ope... | This function scrapes Reddit posts and their comments from a specified subreddit within a given time range, saving data to a JSON file. It handles existing files by appending new data, uses rate-limiting (2s delays), and optionally stores results in a folder. The process includes retrieving posts first, then their comm... | def scrape(subreddit, startTime, reddit, endTime=None, filename=None, foldername=None, quiet=1):
"""
Main scrape function, get all posts first, do so one week at
a time. At the start of each iteration go from the first one that
has no comment values, in case the last iteration failed.
Then go through one post ever... |
def parse_y_dist(y):
""" Checks if y is binary; else assumes it is continuous """
n = y.shape[0]
if np.unique(y).shape[0] == 2:
return "binomial"
elif np.unique(y).shape[0] == n:
return "gaussian"
else:
warnings.warn("Treating y data as continuous even though it may be discre... | The function `fit` computes variable importance using cross-validated Lasso coefficients or Lasso path statistics for feature selection, supporting group knockoffs. It fits (group) Lasso models on design matrix `X`, knockoffs `Xk`, and response `y`, calculates importance measures (`zstat`), and combines them via antisy... | def fit(
self,
X,
Xk,
y,
groups=None,
zstat="coef",
use_pyglm=True,
group_lasso=False,
antisym="cd",
group_agg="avg",
cv_score=False,
debias=False,
Ginv=None,
... |
def swap_feature_importances(self, features, y):
"""
Given a model of the features and y, calculates feature importances
as follows.
For feature i, replace the feature with its knockoff and calculate
the relative increase in the loss. Similarly, for knockoff i,
replace th... | The function trains a model using original and knockoff features, computes feature importances via swap statistics, and aggregates them into group-level statistics. It permutes features to avoid FDR violations, trains the model with combined data, calculates Z statistics based on specified importance methods, and combi... | def fit(
self,
X,
Xk,
y,
groups=None,
feature_importance="swap",
antisym="cd",
group_agg="avg",
**kwargs,
):
"""
Trains the model and creates feature importances.
Parameters
--... |
def detect_system():
""" utility method, its trying to recognize the host machine
"""
global system
# sys.platform.startswith('darwin') is required for mac-os. this os is out of support till now.
if sys.platform.startswith('win'):
system ='windows'
elif sys.platform.startswith('linux'):
... | This code trains a stroke prediction model by loading and preprocessing a dataset, handling missing values and outliers, normalizing data, building a predictive model, saving it for future use, and preparing a GUI for predictions. It checks system compatibility and ensures required libraries are available. | def main():
print("============================ Program v1.0.0 ==============================")
current_time_str = datetime.datetime.now().strftime(time_string_format)
print("Up Time:", current_time_str)
# detect the running operating system. If operating system is unknown, then exit
detect_system(... |
def create_tech_popup(self , step_text_widget1):
tech_popup = QDialog()
tech_popup.setWindowTitle("tech_Popup")
tech_popup_layout = QVBoxLayout()
tech_popup_text = QLabel("What Technology do you want to use?")
tech_popup_input = QLineEdit()
tech_popup_button = QPushButton... | The code creates a GUI widget for a step-by-step project guide, using QToolBox with editable text areas and action buttons for each step. It integrates a chatbot interface with message display, input field, and TTS controls, along with an instruction submission panel. The widget is styled with custom layouts, padding, ... | def create_guide_widget(self, screen_height, screen_width):
guide_widget = QWidget()
guide_layout = QVBoxLayout()
guide_widget = QWidget()
guide_layout = QVBoxLayout(guide_widget)
step_area_layout = QHBoxLayout()
step_area_layout.setSpacing(20)
step_area... |
def update_theme(self):
self.setStyleSheet(f"background-color: {primary_color}; color: {secondary_color};")
def resource_path(relative_path):
if hasattr(sys, '_MEIPASS'):
return os.path.join(sys._MEIPASS, relative_path)
return os.path.join(os.path.abspath("."), relative_path)
def create_guide_wi... | The main task of the code is to initialize a full-screen ProDev.AI application UI with a header containing a logo and navigation bar (Guide/History/Settings). It sets up a stacked widget to dynamically switch between three pages, using custom styles and mouse event handlers for navigation, while ensuring responsive lay... | def init_ui(self):
self.setWindowTitle('ProDev.AI')
screen_height = self.app.desktop().screenGeometry().height()
screen_width = self.app.desktop().screenGeometry().width()
self.setFixedSize(screen_width, screen_height)
self.update_theme()
self.showMaximized()
# M... |
def resource_path(relative_path):
if hasattr(sys, '_MEIPASS'):
return os.path.join(sys._MEIPASS, relative_path)
return os.path.join(os.path.abspath("."), relative_path)
def init_ui(self):
self.setWindowTitle('ProDev.AI')
screen_height = self.app.desktop().screenGeometry().height()
... | This code initializes a GUI application window titled "ProDev.AI" with a dark theme, sets up the user interface, initializes a Gemini AI component, and configures text-to-speech (TTS) parameters including speed, voice, and threading. It also sets the window icon, links to an app instance, and prepares TTS functionality... | def __init__(self):
super().__init__()
self.setWindowTitle("ProDev.AI")
self.setWindowIcon(QIcon(resource_path("")))
self.app = app
self.theme = "dark"
self.init_ui()
self.show()
self.initGemini()
self.tts_enabled = False
self.tts_thread = ... |
def check_weight(ssh):
cmd = "md5sum {} | cut -d ' ' -f1"
local_file = '%s/bin/aarch64/%s'%(config.project_dir, get_config('net_weights_file'))
remote_file = config.remote_dir+config.target_dir+get_config('net_weights_file')
md5_local = os.popen(cmd.format(local_file)).read().strip()
md5_remote = ss... | The function compresses files in the 'aarch64' directory into a tar.gz archive named per config, first removing a specified weight file if it exists. It constructs a shell command to navigate to the directory, create the compressed file, and move it, then executes this command via run_cmd. | def compress_files(ssh):
if check_weight(ssh):
os.remove('%s/bin/aarch64/%s'%(config.project_dir, get_config('net_weights_file')))
cmd = 'cd %s/bin/aarch64; tar zcf %s *; cd ..; mv aarch64/%s %s'%(config.project_dir,\
config.compress_file_name, config.compress_file_name, config.compress_file_nam... |
def listGenerator(rangeA1):
start_time = process_time_ns()
allArrays = np.array([])
for i in range (0, generateMaxN(rangeA1)):
allArrays = np.append(allArrays, [generateArray(rangeA1, i)])
return allArrays.reshape(generateMaxN(rangeA1),len(rangeA1)).astype(int)
end_time = process_t... | The code verifies if all elements in an array (generated by listGenerator) meet two conditions checked by verif1 (element-specific) and verif2 (index-specific). It returns False if any element fails either check, otherwise True. | def verifAll(rangea):
newArray = np.array(listGenerator(rangea))
for i in range (0, len(newArray)):
if (verif1(newArray[i], rangea) == False) or (verif2(i, rangea) == False):
return False
return True |
def generateAllArrays(rangeA1):
allArrays = np.array([])
for i in range (0, generateMaxN(rangeA1)):
allArrays = np.append(allArrays, [generateArray(rangeA1, i)])
return allArrays.reshape(generateMaxN(rangeA1),len(rangeA1)).astype(int)
def verif1(array, rangea):
if (np.array_equal(array,addressTo... | The main task of the code is to verify all generated arrays within a specified range by checking each array against two conditions using `verif1` and `verif2`. It returns `True` only if all arrays pass both checks, otherwise `False`. | def verifAll(rangea):
newArray = np.array(generateAllArrays(rangea))
for i in range (0, len(newArray)):
if (verif1(newArray[i], rangea) == False) or (verif2(i, rangea) == False):
return False
return True |
def unkify(data, w_vocab, c_vocab):
result = Counter()
for parts, value in data.items():
new_parts = [
UNK if (i == 0 and part not in w_vocab) or part not in c_vocab else part
for i, part in enumerate(parts)
]
result[tuple(new_parts)] += value
return result
de... | The code trains a probabilistic model (log-linear or conditional) for language modeling using word vectors and specified data, supporting unigram/bigram structures, regularization, and unknown word handling. It initializes, trains, and saves the model based on input configurations. | def main(vectors_filename,
train_filename,
dev_filename=None,
test_filename=None,
vocab=None,
tie_params=False,
softmax=False,
no_encoders=False,
include_unk=False,
seed=None,
finetune=Fal... |
def draw_line(a,b,c, color='black', linewidth=2.0, linestyle='solid', starting=0, ending=3):
# Plotting the line ax + by + c = 0
x = np.linspace(starting, ending, 1000)
plt.plot(x, -c/b - a*x/b, linestyle=linestyle, color=color, linewidth=linewidth)
def total_error(weights, bias, X, y):
total_error = 0
... | This code implements a perceptron algorithm for linear classification. It initializes weights and bias, iteratively updates them using the perceptron trick on random data points, tracks total error over epochs, and visualizes the decision boundary and error progression. The goal is to find a linear separator for the in... | def perceptron_algorithm(X, Y, learning_rate = 0.01, epochs = 200):
weights = [1.0 for i in range(len(X.loc[0]))]
bias = 0.0
errors = []
for i in range(epochs):
draw_line(weights[0], weights[1], bias, color='grey', linewidth=1.0, linestyle='dotted')
errors.append(total_error(weights, bia... |
def total_log_loss(weights, bias, X, y):
total_error = 0
for i in range(len(X)):
total_error -= log_loss(weights, bias, X.loc[i], y[i])
return total_error
def lr_trick(weights, bias, features, label, learning_rate = 0.01):
pred = lr_prediction(weights, bias, features)
for i in range(len(weig... | The code implements linear regression using stochastic gradient descent. It initializes weights and bias, iteratively updates them via random sample selection and the lr_trick (gradient descent step), tracks log loss over epochs, visualizes the decision boundary and error curve, then returns the final weights and bias. | def lr_algorithm(features, labels, learning_rate = 0.01, epochs = 200):
weights = [1.0 for i in range(len(features.loc[0]))]
bias = 0.0
errors = []
for i in range(epochs):
#draw_line(weights[0], weights[1], bias, color='grey', linewidth=1.0, linestyle='dotted')
errors.append(total_log_lo... |
def getName(self):
return self.name
def getClips(self, recursive = False):
return self.clips
def hasClip(self, clip):
hasClip = False
for childClip in self.getBin().GetClipList():
if childClip.GetMediaId() == clip.GetMediaId():
hasClip... | The code synchronizes a media bin with a folder's contents by importing new files, managing subfolders, and cleaning up old files and bins. It handles zip archives, skips ignored files, imports unimported media, creates missing subfolders, and removes unused files or empty bins based on configuration settings. | def syncBinWithFolder(self, folder, recursive = True):
ignoredFileExtensions = ['.' + x for x in c.ignoredFileExtensions.get().split(',') if x]
importedFiles = []
indexedChildBins = []
if not folder:
return
for root, dirs, files in os.walk(folder... |
def _is_post_url(self):
if not self.driver.current_url.startswith('https://pikabu.ru/story/'):
return False
# Ignore sponsor/ad posts
elements = self.driver.find_elements(By.CLASS_NAME, 'story__sponsor')
return len(elements) == 0
def _expand_comments(self):
# First bu... | The code parses a post's comments by first checking if the URL is valid, expanding comments, extracting post activity, locating the comments container, and recursively extracting all comments. It handles missing elements by logging warnings and exiting early. | def parse(self):
if not self._is_post_url():
return
self._expand_comments()
activity = self._extract_post_activity()
try:
root_level = self.driver.find_element(
By.CLASS_NAME, 'comments__container')
except NoSuchElementException:
... |
def radix10Interface():
### VARIABLES ###
array1 = [] # input array
done = False # loop condition
### PROCESS - Obtain valid integers 0 - 999 from user. If valid integer is entered, add to list
while not done:
try:
number = int(input("Please enter a numb... | The code defines a menu-driven program that allows users to select between different sorting and searching algorithms (Radix Sort with 10/1 auxiliary lists, Merge Sort, Binary Search) or exit. It validates user input and executes the corresponding function based on the selection, providing a structured interface for te... | def menu():
done = False # loop condition
print("************* Welcome to the Search and Sort Program **************\n\n")
### PROCESS ###
while not done:
# Print menu selections
print("SELECTION MENU")
print("(1) - Radix Sort with 10 Auxiliary Lists")
... |
def _most_common_label(self, y):
counter = Counter(y)
most_common = counter.most_common(1)[0][0]
return most_common
def _best_criteria(self, X, y, feat_idxs):
best_gain = -1
split_idx, split_threshold = None, None
for feat_idx in feat_idxs:
X_column = X[:, fea... | This function recursively builds a decision tree by selecting the best feature and threshold to split the data, creating left and right subtrees until stopping conditions (max depth, purity, or sample count) are met, then returning a node with the split information or a leaf node with the most common label. | def _grow_tree(self, X, y, depth=0):
n_samples, n_features = X.shape
n_labels = len(np.unique(y))
if depth >= self.max_depth or n_labels == 1 or n_samples < self.min_samples_split:
leaf_value = self._most_common_label(y)
return Node(value = leaf_value)
feat_idxs ... |
def word_shuffle(x, l, params, rng=None):
"""
Randomly shuffle input words.
"""
if params.word_shuffle == 0:
return x, l
# define noise word scores
noise = rng.uniform(0, params.word_shuffle, size=(x.size(0) - 1, x.size(1)))
noise[0] = -1 # do not move start sentence symbol
as... | This function introduces noise to encoder inputs by sequentially applying word shuffling, word dropout, and span masking to text data, enhancing robustness for tasks like language modeling. It modifies word sequences and their lengths using randomization parameters, returning the augmented inputs. | def add_noise(words, lengths, params, max_vocab, rng=None, torch_rng=None):
"""
Add noise to the encoder input.
"""
if rng is None:
rng = np.random.RandomState()
words, lengths = word_shuffle(words, lengths, params=params, rng=rng)
words, lengths = word_dropout(words, lengths, params, rn... |
def calc_delta(S, K, T, r, sigma, is_call):
if is_call:
return norm.cdf(d1(S, K, T, r, sigma))
else:
return norm.cdf(-d1(S, K, T, r, sigma))
def calc_gamma(S, K, T, r, sigma, is_call):
return 1 / (S * sigma * sqrt(T)) * nPrime(d1(S, K, T, r, sigma))
def calc_theta(S, K, T, r, sigma, is_call)... | The code updates the Greeks (delta, gamma, theta, vega) for each financial contract in CONTRACTS by calculating their sensitivity to price, volatility, and time using the latest SPY price, strike price, time-to-maturity, and volatility. It processes each contract to store these risk measures in self.greeks for option p... | def update_greeks(self):
for asset in CONTRACTS[1:]:
lcp = self.history.iloc[-1]["SPY"]
parse = asset.split("SPY", 1)[1]
strike = np.float64(parse[:-1])
is_call = parse[-1] == "C"
time_to_maturity = ((900 - self.tick) / 10) / 252
u_volatili... |
def move_to_search():
pyautogui.moveTo(search_region_coords.get('x'), search_region_coords.get('y'))
pyautogui.click()
def type_name_enter(card):
name = replace_non_ascii_with_space(card.get('name'))
pyautogui.write(name)
pyautogui.press("enter")
time.sleep(S_TIME + 1.5)
def search_card_exists(c... | The function processes a list of filtered card information, checking each card's existence, retrieving ownership finish details if it exists, or setting default values if it doesn't. It logs defects when cards are not found and compiles updated card data with ownership status, finish types, and dismantling eligibility ... | def get_card_owned_info(filtered_card_info):
card_owned = []
for card in filtered_card_info:
move_to_search()
type_name_enter(card)
card_exists, defect_type = search_card_exists(card)
new_card = card.copy()
if card_exists:
basic_finish_owned, glossy_finish_... |
def is_on_curve(point):
"""Returns True if the given point lies on the elliptic curve."""
if point is None:
# None represents the point at infinity.
return True
x, y = point
return (y * y - x * x * x - curve.a * x - curve.b) % curve.p == 0
def point_neg(point):
"""Returns -point.""... | This function performs elliptic curve scalar multiplication by computing k * point using the double-and-add algorithm. It handles negative scalars by negating the point, iteratively adds and doubles the point based on binary decomposition of k, and returns the resulting point on the curve, or None for edge cases like k... | def scalar_mult(k, point):
"""Returns k * point computed using the double and point_add algorithm."""
assert is_on_curve(point)
if k % curve.n == 0 or point is None:
return None
if k < 0:
# k * point = -k * (-point)
return scalar_mult(-k, point_neg(point))
result = None
... |
def is_on_curve(point):
"""Returns True if the given point lies on the elliptic curve."""
if point is None:
# None represents the point at infinity.
return True
x, y = point
return (y * y - x * x * x - curve.a * x - curve.b) % curve.p == 0
def point_neg(point):
"""Returns -point.""... | (The function performs elliptic curve scalar multiplication using the double-and-add algorithm, computing k * point. It handles edge cases like k=0 or negative values, iterates through k's binary digits, and applies point addition/doubling to accumulate the result. The output is validated to ensure it lies on the curve... | def scalar_mult(k, point):
"""Returns k * point computed using the double and point_add algorithm."""
assert is_on_curve(point)
if k % curve.n == 0 or point is None:
return None
if k < 0:
# k * point = -k * (-point)
return scalar_mult(-k, point_neg(point))
result = None
... |
def hash_message(message):
"""Returns the truncated SHA256 hash of the message."""
message_hash = hashlib.sha256(message).digest()
e = int.from_bytes(message_hash, 'big')
# FIPS 180 says that when a hash needs to be truncated, the rightmost bits
# should be discarded.
if e.bit_length() > curve.... | This function generates an ECDSA (Elliptic Curve Digital Signature Algorithm) signature for a message using a private key and a nonce `k`, returning the signature components `(r, s)`. It hashes the message, computes elliptic curve point multiplication, and derives `r` and `s` using modular arithmetic. However, the "ins... | def sign_message_insecurely(private_key, message, k):
z = hash_message(message)
r = 0
s = 0
while not r or not s:
x, y = scalar_mult(k, curve.g)
r = x % curve.n
s = ((z + r * private_key) * inverse_mod(k, curve.n)) % curve.n
return (r, s) |
def hash_message(x):
h = SHA256.new()
h.update(x)
d = h.digest()
return int.from_bytes(d, 'big')
def scalar_mult(k, point):
"""Returns k * point computed using the double and point_add algorithm."""
assert is_on_curve(point)
if k % curve.n == 0 or point is None:
return None
if ... | The main task of the code is to generate a digital signature for a given message using the Elliptic Curve Digital Signature Algorithm (ECDSA). It computes a cryptographic signature (r, s) by hashing the message, generating a random nonce $ k $, performing elliptic curve scalar multiplication, and applying modular arith... | def sign_message(private_key, message):
z = hash_message(message)
r = 0
s = 0
while not r or not s:
k = random.randrange(1, curve.n)
x, y = scalar_mult(k, curve.g)
r = x % curve.n
s = ((z + r * private_key) * inverse_mod(k, curve.n)) % curve.n
return (r, s) |
def my_random(n):
ret = 0
while ret == 0:
ret = secrets.randbelow(n)
return ret
def scalar_mult(k, point):
"""Returns k * point computed using the double and point_add algorithm."""
assert is_on_curve(point)
if k % curve.n == 0 or point is None:
return None
if k < 0:
... | The code generates ECDSA keys, creates and signs two device provisioning files with a fixed structure, and stores the public keys, signatures, and encoded files in a dictionary. It computes Montgomery-form coordinates of ECDSA keys, signs data insecurely, and encodes results in base64 for storage. | def setup_ecdsa(everything, CHIPID):
ecdsa_mont_R = (2**256) % curve.p
ecdsa_privk = my_random(curve.n)
ecdsa_randk = my_random(curve.n)
everything['ecdsa_privk'] = ecdsa_privk
everything['ecdsa_randk'] = ecdsa_randk
ecdsa_pubk = scalar_mult(ecdsa_privk, curve.g)
print("Public key (Not Montg... |
def setup_rsa(tmpdir, everything, CHIPID):
# Run openssl to generate key
subprocess.run(['openssl', 'genrsa', '-out', tmpdir + '/' + 'rsapriv.pem', '2048'], check=True)
with open(tmpdir + '/' + 'rsapriv.pem', 'r') as f:
rsapriv_pem = f.read()
# print(rsapriv_pem)
everything['rsa_privk'] = r... | The code provisions a device via a serial port by retrieving its chip ID, generating cryptographic keys (RSA, ECDSA, AES, XOR), and creating a JSON record. It sends these keys and data (RNG seed, examples, binaries) to the device through the serial connection, verifying responses. Finally, it transmits hardcoded answer... | def main():
if len(sys.argv) < 2:
print("Usage: {} con_serport".format(sys.argv[0]))
sys.exit(1)
everything = {}
con_serport = sys.argv[1]
# outdata_fn = sys.argv[2]
conser = serial.Serial(con_serport, 115200, timeout=1)
conser.write(b'__provision\n')
expected_reply = b'__... |
def check_fleet_edges(sett, aliens):
#Respond appropriately if any aliens have reached an edge."""
for alien in aliens.sprites():
if alien.check_edges():
check_fleet_direc(sett, aliens)
break
def check_aliens_bottom(sett, stats, screen, roc, aliens, bullets):
#"""Check if any aliens ... | The function updates alien positions, checks for collisions with the player's ship, and handles bottom-of-screen impacts. It first checks if aliens reach screen edges, updates their positions, then detects if any aliens hit the screen bottom or collide with the player's ship, triggering appropriate responses like game ... | def update_alien(sett,stats,screen,roc,aliens,bullets):
#Check if the fleet is at an edge,
#and then update the postions of all aliens in the fleet.
check_fleet_edges(sett, aliens)
aliens.update()
# Look for aliens hitting the bottom of the screen.
check_aliens_bottom(sett, stats, screen, roc, aliens,... |
def addLabels(root):
BMILabel(root, "Height (cm)", 0)
BMILabel(root, "Weight (kg)", 1)
BMILabel(root, "BMI", 2)
def addEntries(root):
height = BMIEntry(root, 0)
weight = BMIEntry(root, 1)
bmi = BMIEntry(root, 2)
bmi.setRO()
entries.extend([height, weight, bmi])
height.focus()
def add... | The main task of the code is to create a BMI calculator GUI application using Tkinter. It initializes a non-resizable window with a title, sets its dimensions, and integrates components like labels, input fields, buttons, and keyboard shortcuts through helper functions. The `mainloop()` starts the GUI event loop to dis... | def main():
root = Tk()
root.title("BMI Calculator")
root.geometry("320x180")
root.resizable(False, False)
addLabels(root)
addEntries(root)
addButtons(root)
addShortCuts(root)
root.mainloop() |
def check_disclaimer(self) -> bool:
return True
def route(self, path: str):
pass
def decode_param(self, value: str) -> str:
try:
return base64.urlsafe_b64decode(value).decode("utf-8")
except:
return value
def render_rss(self, path: str, url: str, limit=0, offse... | The main task of the code is to process URL parameters and route requests based on specified keys. It checks a disclaimer, decodes query parameters, and directs execution to either `render_rss` (for RSS feeds with limit/offset), `play_latest` (for playback), or a default route. The function handles dynamic routing and ... | def handle(self, argv: 'list[str]') -> None:
path = urllib.parse.urlparse(argv[0]).path.replace("//", "/")
url_params = urllib.parse.parse_qs(argv[2][1:])
if not self.check_disclaimer():
self.route("/", dict())
return
self.params = {key: self.decode_param(
... |
def design_partial_grover_circuit(n, m, vector_j, state):
grover_circuit = QuantumCircuit(n + 1, n)
grover_circuit = initialize_s(grover_circuit, range(n))
return partial_grover_circuit(n, m, vector_j, state, grover_circuit)
def QPSA_stats(qcircuit, partial_state, n, simulator, measure_first=True, execution... | The function `design_and_test_two_stage` designs and evaluates a two-stage quantum circuit using Grover's algorithm. It first constructs a partial Grover circuit (`first_stage_circuit`) and computes its theoretical/actual success probabilities, selectivity, and depth. Then, it builds a second-stage circuit (`second_sta... | def design_and_test_two_stage(n, m1, vector_j1, m2, vector_j2, state, simulator, execution_parameters=None):
first_stage_circuit = design_partial_grover_circuit(n, m1, vector_j1, state)
partial_state = state[:(n - m1)]
(P_theoretical_first, P_actual_first, S_first, depth_first, _) = QPSA_stats(first_stage_c... |
def add_team(self,octane_id, name, image,region=None):
print(f"Unknown Team Found {name}")
team = Team(
octane_id = octane_id,
name = name,
image = image,
region = region,
)
self.db_insert(team)
return team
def db_insert(self,o... | The function imports game data and player statistics from an API into a database. It retrieves all teams, fetches their games, and creates or updates team and game records in the database. For each game, it processes player data, linking players to their respective teams and games, ensuring existing entries are updated... | def import_games_and_scoreboard_stats(self):
## get players
teams = Team.query.all()
for team in teams:
request = self.api.get_games(team=team.octane_id)
for game in request['games']:
blue = game['blue']
orange = game['orange']
... |
def venv_hash_check(self, req_file: Path) -> bool:
"""
Check if the hash of the requirements file match.
"""
if req_file.name not in self.venv_hash:
return False
if req_file not in self.req_files:
# Should not happen but better be safe
self.re... | This function installs Python packages from a requirements file using pip, ensuring the file hasn't been previously processed by checking a hash. If valid, it updates the hash and returns True; otherwise, returns False. | def venv_apply_req_file(self, req_file: Path) -> bool:
"""
Install requirements file with pip.
"""
if not req_file.exists():
return False
if self.venv_hash_check(req_file):
return False
self.run_pip_install_file(req_file)
# update hash
... |
def venv_create(self) -> None:
"""
Create the venv if it does not exist already.
"""
if self.venv_dir.exists():
return
venv.create(self.venv_dir, with_pip=True)
def venv_install_self(self) -> None:
"""
Install this package in the venv.
We nee... | The main task of the code is to update a virtual environment (venv) by creating it, installing the package, applying requirement files, and updating a hash file if changes are detected. It returns True if updates occurred, False otherwise. | def venv_update(self) -> bool:
"""
Update the venv if needed.
Returns:
bool: True if updated, False if not changed
"""
self.venv_create()
self.venv_install_self()
dir_req_file_updated = self.venv_apply_req_file(self.dir_req_filename)
file_re... |
def show(e):
return ttutils.showExprs(e)
def aggregateBy(exprs,
sortf=lambda e : e,
groupf=lambda e : e,
name='',
debug=False):
"""Generic aggregation function"""
sortByShow = lambda e : show(sortf(e))
results = []
if debug:
pri... | The code generates a structured natural language statement from multiple models, ensuring consistent conclusions. It aggregates shared evidence as bullet points and unique evidence as inline alternatives, formatting them into a formalized output with the conclusion, shared conditions, and disjunctive unique conditions. | def nlgModels(models):
concls = [m[0] for m in models]
evidence = [m[1:] for m in models]
if all(x == concls[0] for x in concls):
conclusion = concls[0]
else:
raise Exception("nlgModels: expected identical conclusions, got", show(concls))
allEvidence = [e for es in evidence for e in... |
def getInfo(self, ch):
# wait till other communication is done
while self.communicating:
time.sleep(0.01)
self.communicating = True
# getting wavemetere info
if self.chName[str(ch)][9] == 1:
try:
self.freqCh = float(self.wlm.getFrequency... | This code manages locking mechanisms for a system by adjusting current and piezo (PZT) outputs based on channel parameters. It checks conditions for drift, triggers scans, updates reference data, and handles hardware communication. The function ensures stable operation by evaluating frequency differences, maintaining l... | def locking(self, ch):
self.communicating = True
self.wlm.keepChannel(0)
self.wlm.keepChannel(1)
self.communicating = False
self.iCurrVal = self.IParam[ch][2]
self.pztCurrVal = self.PztParam[ch][2]
# scan_range = 30
if self.chName[ch][2] == 1:
... |
def get_breeders_from_generation(self,guesses, take_best_N=10, take_random_N=5, verbose=False, mutation_rate=0.1):
"""
This sets up the breeding group for the next generation. You have
to be very careful how many breeders you take, otherwise your
population can explode. These two, plus t... | This function evolves a population of guesses over multiple generations by selecting top performers and random individuals to breed, generating new children each time. It tracks fitness scores across generations and returns the fitness history and the best guess after evolution. Parameters control selection, mutation, ... | def evolve_to_solve(self,current_generation, max_generations, take_best_N, take_random_N,
mutation_rate, children_per_couple, print_every_n_generations, verbose=False):
"""
Takes in a generation of guesses then evolves them over time using our breeding rules.
Continue thi... |
def __need_download(self, path_in_repo, local_file):
if path_in_repo and os.path.isfile(local_file):
local_file_checksum = self.__get_sha1_of_local_file(local_file)
remote_file_checksum = ''
# noinspection PyBroadException
try:
remote_file_checksum... | The code downloads a file from a repository to a local path, using 'axel' for accelerated transfers. It constructs the download URL, prints progress/status, validates the download, and retries if validation fails. The loop ensures successful download before exiting. | def download(self, path_in_repo: str, local_file: str, progress=""):
path_in_repo = os.path.join(self.repo_path, path_in_repo)
download_url = "{}/{}/{}".format(self.repo_url, self.repo_name, path_in_repo)
star_count = 50
print("#" * star_count)
print("# {} {}".format(progress, pa... |
def f1(x, y):
return sin(x) * y * y + x
def f2(x, y):
dydx = f1(x, y)
return 2 * y * sin(x) * dydx + y * y * cos(x) + 1
def f3(x, y):
dydx = f1(x, y)
d2ydx2 = f2(x, y)
return 2 * sin(x) * pow(dydx, 2) + 2 * y * (
sin(x) * d2ydx2 + 2 * cos(x) * dydx) - sin(x) * y * y | The function performs a third-order Taylor series method to numerically approximate the solution of a system of differential equations. It iteratively updates the solution (x, y) using the first, second, and third derivatives of y with respect to x, applying the Taylor expansion up to the third-order term for each step... | def ord3_taylor(f1, f2, f3, x0, y0, h, N):
x = x0
y = y0
print(x, y)
for _ in range(N):
dydx = f1(x, y)
d2ydx2 = f2(x, y)
d3ydx3 = f3(x, y)
x += h
y += h * dydx + h * h / 2 * d2ydx2 + h * h * h / 6 * d3ydx3
print(x, y)
return x, y |
def parse_arguments(args_hook=lambda _: _):
parser = argparse.ArgumentParser(
description=
'Read license plates from images and output the result as JSON or CSV.',
epilog="""Examples:
Process images from a folder:
python plate_recognition.py -a MY_API_KEY /path/to/vehicle-*.jpg
Use the Sna... | The main task of the code is to process multiple input files using a recognition API, configured with specified parameters like regions, API key, and engine settings. It reads each file, sends it to the API for analysis, collects results, and either saves them to an output file or prints them as formatted JSON. The cod... | def main():
args = parse_arguments(custom_args)
paths = args.files
results = []
engine_config = {}
if args.engine_config:
try:
engine_config = json.loads(args.engine_config)
except json.JSONDecodeError as e:
print(e)
return
for path in paths:... |
def init(self):
self.state = [t.MachineState()]
self.playing = False
self.loaded = False
self.halted = False
self.current = 0
self.memsize = 0
self.asm = list[str]()
def load_by(self, f: Callable[[str], tuple[list[str], list[bytes]]]):
self.init()
... | The code initializes a GUI application demonstrating the Tomasulo Algorithm, setting up a window with controls (prev, next, auto-play, reset), displays for registers, memory, Branch Target Buffer (BTB), assembly code, Reorder Buffer (ROB), and reservation stations. It binds the autospeed parameter to control simulation... | def __init__(self, autospeed: int = 200) -> None:
self.init()
self.autospeed = autospeed
window = tk.Tk()
window.geometry("1920x1080")
window.title("Demonstration of Tomasulo Algorithm")
window.grid_columnconfigure(0, weight=1)
self.window = window
butt... |
def controller_identity(text, sentence_obj, controller_id):
if controller_id != '' and controller_id in text:
checker.set_S('Controller identity')
def contact_details(text, sentence_obj):
email = re.findall('\S+@\S+', text)
phone_number_clean = re.findall('^\\+?[1-9][0-9]{7,14}$', text)
phone_n... | This function processes a list of sentences by analyzing their semantic roles, named entities, and extracting relevant information. It uses models for semantic role labeling (SRL), named entity recognition (NER), and a controller to identify contact details. Each sentence is checked for length, processed into objects, ... | def sentence_reciever(filename, sentences, controller_id, app_title, template_representations, output_folder, sbert_model,nlp_model, SRL_predictor_model, evaluation):
global templates_rep
global sbert
global checker
global nlp
checker = analyzer(output_folder)
nlp = nlp_model
sbert = sbert... |
def calculate_n(Z, Q):
z_classes = len(set(list(Z)))
q_classes = len(set(list(Q)))
N = len(Z)
n = np.zeros((z_classes, q_classes))
for i in range(N):
z = Z[i] - 1
q = Q[i] - 1
n[z, q] += 1
return n
def R(S, D, N):
return 2*(S+D) / (N*(N-1))
def J(S, D, N):
r... | The code calculates and prints clustering evaluation metrics (Rand Index, Jaccard similarity, MI, NMI) between two clusterings Z and Q using a confusion matrix n. It computes pairwise agreements (S) and disagreements (D) to derive these metrics, which quantify the similarity and mutual information between the clusterin... | def compare(Z, Q):
n = calculate_n(Z, Q)
# if confusion matrix given, put it in the matrix n below and uncomment
# n = np.array([[114, 0, 32],
# [0, 119, 0],
# [8, 0, 60]])
N = np.sum(n)
n_z = n.sum(axis=1)
n_q = n.sum(axis=0)
S = sum([n_km*(n_km -1)... |
def get_secret(secret_file: Path=Path('SECRET_openai.txt')) -> str:
"""Load an API secret from a file.
"""
secret = os.getenv("OPENAI_API_KEY")
if secret is None:
if not secret_file.exists():
raise ValueError(f'{secret_file=} does not exist')
with open(secret_file, 'r') as f:... | The function `main` executes multiple OpenAI queries using a base prompt and demographic substitutions, saving results to timestamped JSON files. It checks a provided previous query file for completeness, resuming or reusing it if valid. Prompts are generated, repeated, and saved, while responses are collected and stor... | def main(base_query: str=BASE_PROMPT, query_options: PromptOptionsType=PROMPT_OPTIONS, model_params: Optional[dict]=None,
query_repeats: int=1, previous_query_file: Optional[Path]=None
) -> tuple[Path, Path, list[openai.openai_object.OpenAIObject]]:
"""Run OpenAI queries using the `base_query` string and `query... |
def load_query_config(config_path: Path) -> tuple[str, list[str], RetainPoliciesType, int, int, Optional[str]]:
"""Parse the json config file and return the base_query, ces_demos, ces_policies, query_repeats, and previous_query_file
"""
with open(config_path, 'r') as f:
config = json.load(f)
jso... | The main task of the code is to parse CES data, query and analyze it using configured parameters, transform the data into structured formats, generate comparative visualizations (bar plots, scatter plots, histograms) across issues and demographics, and save results as CSV files. It processes datasets, maps issues to ca... | def main(query_config: Path):
"""Parse CES data, query
"""
LOGGER.info('Begin query_and_analyze')
base_prompt, demos, ces_policies, n_per_query, query_repeats, previous_query_file = load_query_config(query_config)
outfile, ces_df, gpt_df, issue_map, issue_map_invert, prompt_options = get_data(
... |
def record_matches_cip(self, name: str, zone: str) -> bool:
return self.find_record_in_zone(name, zone)["content"] == self.current_ip
def find_record_in_zone(self, name: str, zone: str) -> Any:
records = self.retrieve_dns_records(zone)
resp_record = next(
(record for record in recor... | The main task of the code is to update a DNS record's content to the current IP address if it does not already match. It checks if the existing record matches `self.current_ip` for Dynamic DNS; if not, it retrieves the record's identifier, constructs an API payload with the new IP, and sends a PUT request to update the... | def update_record(self, record: str, zone: str) -> Tuple:
"""
A method that checks if a record matches an expected value.
In this instance, it is only used for checking against self.current_ip
for Dynamic DNS.
"""
if self.record_matches_cip(record, zone):
retu... |
def load_all(self):
"""
Loads all of the grammars and aliases.
"""
self.aliases = self.load_aliases()
self.load_grammars()
def set_mode(self, mode):
"""
Populates self.mode_grammar with each grammar specified by the mode.
"""
if mode in modes.modes... | The code's main task is to load grammars, set the default mode, log progress, and read input. It initializes the system by loading all necessary grammars, configures the operation mode, logs completion, and prepares to process input data. | def interpret(self):
utilities.log("Loading grammars...")
self.load_all()
self.set_mode(config.DEFAULT_MODE)
utilities.log("Loading complete.")
self.read_input() |
def parse_args():
global RECEIVER_ADDR
global RECEIVER_PORT
global SENDER_ADDR
global SENDER_PORT
global TIMEOUT_INTERVAL
global WINDOW_SIZE
global FILE
global send_timer
RECEIVER_ADDR = sys.argv[1]
RECEIVER_PORT = int(sys.argv[2])
SENDER_ADDR = "127.0.0.1"
SENDER_PORT =... | The main task of the code is to send a file over a network using UDP sockets. It initializes a sender socket, configures parameters like window size and timeout, prints connection details, and transmits the file name and data to a receiver. The code binds the socket, prepares transmission settings, and uses custom func... | def main():
parse_args()
senderS = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
senderS.bind((SENDER_ADDR, SENDER_PORT))
print("Receiver IP address: " + RECEIVER_ADDR)
print("Window size: " + str(WINDOW_SIZE))
print("Timeout (sec): " + str(TIMEOUT_INTERVAL))
print("File name: " + FILE )
... |
def _reinit(self):
self._first_state = None
self._last_state = None
def resume(self, tag: Optional[str] = None):
"""
resume the energy Trace (if no energy trace was launched, start a new one
:param tag: sample name
:raise EnergyMeterNotStoppedError: if the energy meter i... | The code generates idle energy consumption values for each sample in an energy trace by measuring the energy consumed during the duration of each sample. It initializes the system, pauses for each sample's duration (converted from nanoseconds to seconds), stops, and collects the recorded energy values. The result is a ... | def gen_idle(self, trace: EnergyTrace) -> List[Dict[str, float]]:
"""
generate idle values of an energy trace
for each sample, wait for the duraction of a sample and measure the energy consumed during this period
:return: the list of idle energy consumption for each sample in the trace
... |
def lowpassfilter (self):
self.ui.fig2.clear()
self.ui.fig2.clf()
self.u.axes = self.ui.fig2.gca()
original=np.fft.fft2(self.img_gray)
centered_Img=np.fft.fftshift(original)
LP_centered_shifted= centered_Img *self.idealFilterLP(50,self.img.shape)
LowPass_shifted =... | This code updates available filters based on the selected domain (e.g., frequency, spatial, RGB) and applies the chosen filter by calling corresponding methods like lowpass/highpass filters, Sepia/Emboss/Sobel effects, or RGB-specific processing. It dynamically modifies the UI filter list and triggers the appropriate i... | def choose(self):
if self.ui.choosedomain.currentIndex()==1:
self.ui.choosefilter.setItemText(1," Low Pass Filter")
self.ui.choosefilter.setItemText(2, " High Pass Filter")
self.ui.choosefilter.setItemText(3, " ")
if self.ui.choosefilter.cu... |
def replace_by_lev(word):
"""
Replaces a 'wrong' word with another word from the postinglist.
The postingslist contains every indexed word from the tweets database.
dict(term: tup(mininum_lev, occurrences))
:param word:
:return:
"""
minimum_lev = -1
results = {}
it =... | The code implements a Twitter search engine variant that retrieves tweets matching at least one of two search terms, ordered by their TF-IDF scores. It uses precomputed data structures (`postings`, `db`, `tweets`) to efficiently find matching tweets, corrects terms via Levenshtein distance if needed, calculates TF-IDF ... | def main():
"""
Programming exercise: take the Twitter-search-engine from the last few weeks
as a starting point. Implement a variant which takes two search terms and then
returns all tweets which match at least one of the search terms. Add the tf-idf
score of each document. Order the returned docum... |
def replace_by_lev(word):
"""
Replaces a 'wrong' word with another word from the postinglist.
The postingslist contains every indexed word from the tweets database.
dict(term: tup(mininum_lev, occurrences))
:param word:
:return:
"""
minimum_lev = -1
maximum_jac = 0.0
... | The code implements a Twitter search system with spell correction. If a query term has no results, it finds the closest valid term using Levenshtein distance. It uses three data structures: `db.pickle` (term-tweet position mappings), `tweets.pickle` (tweet details), and `postinglist.pickle` (term-tweetID mappings). Whe... | def main():
"""
Twitter Search with spell correction. On the basis of programming exercise 4 of week 1.
Adapt the Twitter query system as follows. If there are no hits for the given query term,
adapt the query so that it uses a query term that is very close to the original query term
(e.g, a query t... |
def RunApp(self, CoreNumber, freq, MemoCtrl):
os.system(SET_SPEED+' -a -f '+ str(freq))
os.system("sudo -E numactl --interleave=0-"+str(MemoCtrl-1) +
" --physcpubind=0-"+str(CoreNumber-1)+" "+self.CommandLine+" &")
self.CurCore = CoreNumber
def GetFeedback(self, config):
print("[... | The code's main task is to optimize system performance and power consumption by adjusting core numbers and frequencies through a multi-phase decision process. It uses binary search algorithms to determine optimal configurations based on feedback from different hardware settings, ensuring power stays within limits while... | def Decision(self):
self.RunApp(8, 1000, 2)
if self.phase == 0:
self.CurConfig = (8, 1000, 2)
self.PerfDictionary[self.CurConfig], self.PwrDictionary[self.CurConfig] = self.GetFeedback(
self.CurConfig)
if self.PwrDictionary[self.CurConfig] > self.PwrCa... |
def RunApp(self,CoreNumber, freq, MemoCtrl):
if CoreNumber <33:
os.system(SET_SPEED+' -S '+str(16-freq))
#os.system(POWER_MON+" start")
print("sudo -E numactl --interleave=0-"+str(MemoCtrl-1)+" --physcpubind=0-"+str(CoreNumber-1)+" "+self.CommandLine+" &")
os.syst... | The main task of the code is to determine an optimal core number configuration by evaluating performance metrics across multiple predefined settings, comparing results, and applying binary search on specific ranges to select the best-performing configuration, all within a decision-making phase of a system. | def Decision(self):
self.RunApp(8,16,2)
if self.phase == 0:
self.CurConfig = (8,16,2)
self.PerfDictionary[self.CurConfig],self.PwrDictionary[self.CurConfig] = self.GetFeedback(self.CurConfig)
self.CurConfig = (1,16,2)
self.PerfDictionary[self.CurConfig],se... |
def RunApp(self,CoreNumber, freq, MemoCtrl):
if CoreNumber <33:
os.system(SET_SPEED+' -S '+str(16-freq))
#os.system(POWER_MON+" start")
for commandline in self.CommandLine:
print("sudo -E numactl --interleave=0-"+str(MemoCtrl-1)+" --physcpubind=0-"+str(CoreNu... | The code evaluates multiple hardware configurations by collecting performance and power feedback, then uses conditional comparisons and binary search (PerfBSearch) to determine the optimal core number range for a given system state, aiming to select the most efficient configuration based on performance metrics. | def Decision(self):
self.RunApp(8,16,2)
if self.phase == 0:
self.CurConfig = (8,16,2)
self.PerfDictionary[self.CurConfig],self.PwrDictionary[self.CurConfig] = self.GetFeedback(self.CurConfig)
self.CurConfig = (16,16,2)
self.PerfDictionary[self.CurConfig],s... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.