dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def get_utxo(txid_string: str, index: int, fin_name: str) -> (bytes, bytes):
"""
Gets a UTXO from the chainstate identified by a given transaction id and index.
If the requested UTXO does not exist, return None.
(inspired from https://github.com/sr-gi/bitcoin_tools)
:param txid_string: Transaction... | This function removes a specific UTXO (unspent transaction output) identified by a transaction ID and output index from a LevelDB blockchain database. It replaces the UTXO with an "anyone can spend" output to prevent forks when blocks reference it. The process involves retrieving the UTXO data, modifying it to allow un... | def erase_utxo(txid_string: str, index: int, fin_name: str):
"""
Erase one UTXO, represented by a txid:index pair, from the chainstate database.
(Replacing it with an "anyone can spend" output to avoid forks on blocks
spending from that output.)
:param txid_string: Transaction ID that identifies th... |
def _convert_pertinent_columns_to_timestamps(
self, metadata: pd.DataFrame
) -> pd.DataFrame:
for key in metadata.columns:
if "date" in key[0] and "Date" in key[1]:
metadata[key] = pd.to_datetime(
metadata[key], format="%Y-%m-%d %H:%M:%S"
... | The main task of the code is to parse input content into a pandas DataFrame, extract metadata by removing questions, and convert relevant columns to timestamps. It uses helper methods to select columns before the first question and transform pertinent data into timestamp format, ultimately returning a structured DataFr... | def parse_metadata(self, content: str) -> pd.DataFrame:
"""Strip questions and return only parsed metadata."""
return self._convert_pertinent_columns_to_timestamps(
self._select_columns_before_first_question(self.parse(content))
) |
def _add_partial_ids_to_header(self, question_data: pd.DataFrame) -> pd.DataFrame:
columns = question_data.columns.to_frame()
columns[["group_id", "question_id", "answer_id"]] = [
(
lambda ids: [
ids["group"],
ids["question"],
... | The main task of the code is to parse raw content into a structured pandas DataFrame by selecting relevant questions, adding a header row with answers, and appending partial IDs to the header. This transformation organizes data for further analysis or processing. | def parse_questions(self, content: str) -> pd.DataFrame:
"""Parse the main bulk of the data related to the actual questions."""
return self._add_partial_ids_to_header(
self._add_header_row_with_answer(
self._select_questions(self.parse(content))
)
) |
def path_leaf(file_path):
rootdir, file = ntpath.split(file_path)
return file or ntpath.basename(rootdir)
def get_json(file, chartname):
print(chartname)
with open(file) as chart:
chart = json.load(chart)
print(chart['options'])
options = chart['options']
template = chart['template']
options = extend_di... | The code processes a file by extracting its name and extension. If the file is a JSON, it generates a Highcharts chart configuration using the file's base name as a div ID and stores the chart code in a global variable. The function prints the file path and name, then constructs a Highcharts script string with the char... | def process_files(file_path):
print(file_path)
file = path_leaf(file_path)
print(file)
ext = os.path.splitext(file)[-1].lower()
chartname = os.path.splitext(file)[0].lower()
if ext == '.json':
options = get_json(file_path, chartname)
global divId
divId = div_id(chartname)
global chart
chart = 'Hig... |
def getIdentifiers(output,output_all,output_dir=None,endpoint="https://oscar.wmo.int:443/oai/provider",max_pages=500,metadata_prefix="wmdr",set_spec=None):
identifiers, resumption_token, completeListSize, cursor = getIdentifiersFirstPage(output=output,endpoint=endpoint,metadata_prefix=metadata_prefix,set_spec=set_s... | This function performs bulk download of WMDR records from an OAI web service based on specified actions: fetching identifiers, records, or parsing files. It validates parameters, saves results to an output directory, and uses helper functions for each action. Error checks ensure correct inputs, with actions including '... | def harvest(self,action,output,set_spec,endpoint,identifier,metadata_prefix,file_pattern):
"""
Bulk download WMDR records from OAI web service
ACTION is the action to perform. Options are
- identifiers: request record identifiers.
- records: request records.
- record: re... |
def parseAndEvaluateFiles(file_pattern,output_dir=None,selected_kpi : int=None,skip_schema_eval=False,return_results=False):
files = glob.glob(file_pattern)
if not len(files):
print("Error: no files matched the pattern")
return
results = []
for file in files:
try:
res... | This function processes evaluation tasks based on the 'action' parameter. If 'evaluate', it parses files, computes metrics, and saves/results to JSON if 'compute_metrics' is True. If 'metrics', it retrieves existing evaluations, outputs them as JSON (or saves if 'compute_metrics' is True). It handles metric calculation... | def metrics(self,action,path,output_dir,compute_metrics,kpi,skip_schema_eval):
if action == "evaluate":
if compute_metrics:
results = parseAndEvaluateFiles(path,output_dir=output_dir,selected_kpi=kpi,skip_schema_eval=skip_schema_eval,return_results=True)
if results is not None:
... |
def generateRandomExpressionBool(maxDepth):
if random() < 0.1 or maxDepth < 0:
return ['True', 'False'][randint(0,1)]
elif random() < 0.5:
operator = OperatorsBoolBool[randint(0, len(OperatorsBoolBool)-1)]
if NumberOfArguments[operator] == 1:
return "(%s %s)" % (operator,
... | The main task of the code is to generate a random program in a custom L language grammar. It recursively constructs valid expressions by randomly selecting between returning a number, a boolean expression, or an "if" statement with two sub-programs. The maxDepth parameter limits recursion depth, ensuring termination an... | def generateRandomProgram(maxDepth = 10):
# generates a string that is a legal sentence in the grammar of our L language
if random() < 0.1 or maxDepth < 0:
return str(randint(0, 100))
elif random() < 0.3:
return generateRandomExpressionBool(maxDepth - 1)
elif random() < 0.3:
retu... |
def prettyPrint(expression, index, depth = 0):
# takes a parse tree and prints it out to prettyPrintCorrect.txt
with open(PATH + 'prettyPrintCorrect.txt', 'a') as file:
if depth == 0:
file.write("Index: %d" % (index) + "\n")
file.flush()
if isinstance(expression, int):
... | The code reads a file line by line, processes each line using the `parse` function, and prints the result with `prettyPrint`. It handles exceptions during parsing by printing errors with the line index. The function tracks each line's position using an incrementing index. | def readFile(fileName):
fil = open(PATH + fileName)
fileLines = fil.readlines()
index = 0
for f in fileLines:
try:
prettyPrint(parse(f), index, 0)
except Exception as error:
errorPrint(error, index)
index +=1 |
def read_project_structure(absolute_path_to_project: str) -> Project:
project = Project()
for (dirpath, dirnames, filenames) in os.walk(absolute_path_to_project):
for filename in filenames:
if filename.endswith(".py"):
relative_dirpath = dirpath
project.files[... | The code generates a comprehensive graph representing a project's structure, including file, class, function relationships, dependencies, and inheritance. It processes the project's call graph, fixes naming inconsistencies, adds parent packages, dependencies, and annotations, then exports the result as a JSON file for ... | def create_complete_graph(absolute_path_to_project: str, should_annotate: bool = True) -> Graph:
absolute_path_to_project = os.path.normpath(absolute_path_to_project)
project: Project = read_project_structure(absolute_path_to_project)
entry_points = project.files.keys()
call_graph = CallGraphGenerator(
... |
def log(message):
_now = datetime.datetime.now()
print(f'[{_now}] {message}')
def get_page(self, page):
if self.req >= 30:
self.req = 0
self.log(f'\t --> self throttling requests (max 30req/sec) waiting 1s')
time.sleep(1)
self.log(f'\t --> requesting q... | The main task of the code is to collect and store data from multiple pages by checking a database for existing entries. If data for a page is not found, it retrieves page content, extracts owners, questions, answers, and queries, then stores them. The process logs progress, skips pages with existing data, and processes... | def get_data(self):
self.log(f'collecting data for pages {self.start_page} up to {self.end_page}')
page_index = self.start_page - 1
cursor = self.db.cursor()
for page in range(self.start_page, self.end_page + 1):
page_index += 1
owners, questions, answers, queries... |
def fileExists(file_path):
if os.path.exists(file_path) and os.path.isfile(file_path):
return True
return False
def askFileMode(file_path):
choice = input('\nWhat do you wish to do? Enter the number against the choice.\n1 read the file\n2 delete the file and start over\n3 append the file\n4 replace ... | The main task of the code is to prompt the user for a file name, construct its path, check if the file exists, and either call a function to handle the file's mode or another to input data based on existence. It manages user interaction for file operations, branching logic based on file existence. | def ask4File():
file_name = input("Please enter the file name:\n")
file_path = "./" + file_name + ".txt"
if fileExists(file_path):
askFileMode(file_path)
else:
askFileInput(file_path) |
def filter(self, data):
self._filter(data, self.type_hints)
def convert(self, data):
return self._convert(data, self.type_hints)
def update(self, data):
self.config = self.__update(self.config, data) | The code's main task is to save configuration data by optionally filtering and converting input data, updating internal state, and writing the resulting configuration to a JSON file, then returning the processed data. | def save(self, data=None):
if data is not None:
self.filter(data)
data = self.convert(data)
self.update(data)
with open(self.config_file, 'w') as outfile:
json.dump(self.config, outfile)
return data |
def processData(self):
data_frame = self.loadText()
text_list = list()
for index, item in data_frame.iterrows():
if isinstance(item['target'], float):
item['target'] = ''
text = item['target'].replace(".", " .").replace(
",", " ,").replace(... | This code initializes a vocabulary with predefined tokens (PAD, F, /F, H, /H, EOS, UNK) and processes data. If `make_embeddings` is True, it loads GloVe embeddings, creates an embedding matrix, converts it to a PyTorch tensor, and saves it to a file. The main task is setting up token mappings and optionally generating/... | def __init__(self, make_embeddings=False):
# Word dicts
self.word2index = {"PAD": PAD_token, 'F': FURHAT_start, '/F': FURHAT_stop,
'H': HUMAN_start, '/H': HUMAN_stop, "EOS": EOS_token, "UNK": UNK_token}
self.word2count = {"PAD": 0, "F": 0, "/F": 0,
... |
def _computeValueActionPairFromQValues(self, state):
legalActions = self.env.getPossibleActions(state)
if len(legalActions) == 0:
return (0.0, None)
else:
qVals = [self.getQValue(state, action) for action in legalActions]
return max(zip(qVals, legalActions))
d... | This code updates the weights of a reinforcement learning agent using a variant of Q-learning. It calculates the target Q-value for the next state, computes the learning rate (alpha) based on the frequency of the (state, action) pair, and adjusts the weights by multiplying the feature vector with the difference between... | def update(self, state, action, nextState, reward):
"""
Should update your weights based on transition
"""
maxQ = self._computeValueActionPairFromQValues(nextState)[0]
self.qaCount[(state, action)] += 1
alpha = 1. / self.qaCount[(state, action)]
multiplier = al... |
def get_api(args):
config = get_config(args.api_account)
if config.API_KEY is None:
raise Exception("use your own credential")
auth = tweepy.OAuthHandler(config.API_KEY, config.API_SEC_KEY)
auth.set_access_token(config.ACCESS_TOKEN, config.ACCESS_TOKEN_SEC)
return tweepy.API(auth, wait_on_... | The code's main task is to crawl or update Twitter conversations for multiple users. It checks if existing conversation data exists for a user; if so, it retrieves the last 50 pages, otherwise it crawls as many pages as possible. It processes each user's data using Twitter API credentials, saves results to files, and h... | def main(args):
"""
if conversations for a user already crawled we only retrieve last 50 pages (update_conversation_for_user_id)
otherwise we crawl conversations as much as possible (crawl_conversations_for_user_id).
"""
# list of users to crawl
user_ids = get_user_ids(args.user_id)
user_ids... |
def is_better_solution(self, new_solution):
new_solution_full = set()
for i in new_solution:
new_solution_full.add(i[1])
if self.best_solution is None:
self.full_boxes_best_solution = len(new_solution_full)
self.best_solution = new_solution
return... | This function implements a backtracking algorithm to solve a bin packing problem by recursively trying all possible placements of items into bins. It checks if a complete solution is valid, updates the best solution if improved, and visualizes the process with GUI updates. The algorithm backtracks by removing items fro... | def solve_backtracking(self, index, current_solution):
if index == len(self.item_sizes_var):
if self.is_better_solution(current_solution):
self.best_solution = current_solution.copy()
self.solution_found = True
return
for bin_index in range(self.n... |
def shift_pipes(chromosome):
# add distinct bins to a set
distinct_bins = set()
for item in chromosome:
distinct_bins.add(item[1])
# transfer it to a list and then sort it
list_of_set = list(distinct_bins)
list_of_set.sort()
# map every index to the lowest available index
idx =... | This function performs a crossover operation in a genetic algorithm for bin packing. It creates child solutions by swapping segments of parent bin configurations, corrects duplicates, reinserts unassigned items, and ensures valid bin capacity compliance through shifting and insertion steps. | def crossover(parent1, parent2, num_bins, bin_capacity):
# Create clones of parents
child1 = parent1.copy()
child2 = parent2.copy()
child1 = shift_pipes(child1) #[(3,1),(5,2)||,(4,3)] [(3,1),(5,2),(4,3),|||(4,4) ( 5, 6 ) , (8,7,)]
child2 = shift_pipes(child2) #( 5, 6 ) , (8,7,) ,(3,1),... |
def shift_pipes(chromosome):
# add distinct bins to a set
distinct_bins = set()
for item in chromosome:
distinct_bins.add(item[1])
# transfer it to a list and then sort it
list_of_set = list(distinct_bins)
list_of_set.sort()
# map every index to the lowest available index
idx =... | The code mutates an encoded list by randomly removing three elements, shifting remaining items, and reinserting unassigned items while respecting bin capacity constraints. This process modifies the encoded solution for optimization, likely in bin packing or scheduling problems, by disrupting and reconfiguring assignmen... | def mutate(encoded, num_bins, bin_capacity):
mutated = encoded.copy()
for i in range(3):
mutated.remove(mutated[random.randint(0, len(mutated)-1)])
mutated = shift_pipes(mutated)
unassigned = get_unassigned_items(encoded, mutated)
mutated = insert_unassigned_items(mutated, unassigned, bin_ca... |
def process_inputs(item_sizes, items_number, bin_capacity, num_bins):
if len(item_sizes) < items_number:
CTkMessagebox(title="Error", message=f"items number is {items_number} while there are {len(item_sizes)} items",
icon="cancel")
return False
elif len(item_sizes) > items... | The main task of the code is to collect user inputs for bin packing problem parameters (item count, bin count, capacity, item sizes), validate inputs, generate colored item representations, initialize data structures for tracking bin states and solutions, and trigger a backtracking algorithm to solve the bin packing pr... | def get_values(self):
self.num_items_var = int(self.num_items_var_entry.get())
self.num_bins_var = int(self.num_bins_var_entry.get())
self.bin_capacity_var = int(self.bin_capacity_var_entry.get())
self.item_sizes_var = []
heightOfItemsFromUser = list(map(int, self.item_sizes_var_... |
def process_inputs(item_sizes, items_number, bin_capacity, num_bins):
if len(item_sizes) < items_number:
CTkMessagebox(title="Error", message=f"items number is {items_number} while there are {len(item_sizes)} items",
icon="cancel")
return False
elif len(item_sizes) > items... | The code implements a genetic algorithm to solve a bin packing problem. It retrieves user inputs for item counts, bin capacities, and item sizes, validates them, then runs the genetic algorithm to find an optimal bin arrangement. The best solution is printed, visualized in the GUI, and displayed with an animation. | def solve_genetic(self):
self.num_items_var = int(self.num_items_var_entry.get())
self.num_bins_var = int(self.num_bins_var_entry.get())
self.bin_capacity_var = int(self.bin_capacity_var_entry.get())
heightOfItemsFromUser = list(map(int, self.item_sizes_var_entry.get().split(',')))
... |
def get_blk(self, i):
"""
Get the five blocks in the TinySSD based on the index.
(i.e. 0. base_net, 1-3. downsampling blocks, 4. downsampling block using global maxpool)
Args:
i: An integer use to indicate the index of the block.
Example usage:
get_blk(... | The code initializes the TinySSD object detection model by setting up anchor box parameters (sizes, aspect ratios), defining multi-scale feature blocks, and attaching classification/bounding box predictors to each block. It configures 5 feature levels with varying anchor scales and ratios, creating prediction heads for... | def __init__(self, number_classes, **kwargs) -> None:
super(TinySSD, self).__init__(**kwargs)
self.number_classes = number_classes
self.sizes = [[0.2, 0.272], [0.37, 0.447], [0.54, 0.619], [0.71, 0.79], [0.88, 0.961]]
self.ratios = [[1, 2, 0.5]] * 5
self.num_anchors = len(self.si... |
def randomSampling(X,N,step_size=1e-4):
n = X.shape[0]
nIter = 5000
fArray = np.zeros((nIter,))
lambd = np.ones((n,))/n
fArray[0] = f(X,lambd)
for step in range(nIter):
lambd_tild = np.exp(np.log(lambd)-step_size*df(X,lambd))
lambd = lambd_tild/np.sum... | The function `runExperiment` evaluates three methods (random sampling, greedy, and Frank-Wolfe) for a given problem size `N` by generating multivariate normal data with covariance matrix scaled by `sigmaSq = np.linspace(1,d,d)**(-a)`. It tests each method on increasing sample sizes (`nArray`) and returns their performa... | def runExperiment(a,N,d):
sigmaSq = np.linspace(1,d,d)**(-a)
# Randomly generate X from N(0,sigmaSq)
X = np.random.multivariate_normal(np.zeros((d,)), np.diag(sigmaSq), size=(10 + 2**10,))
nArray = (2**np.linspace(1,10,10) + 10).astype(int)
methodNArr = np.zeros((3,nArray.shape[0]))
... |
def getGOpt(self,arms,N=1000):
"""
Compute a G-optimal design vector for arms.
Parameters
----------
arms : list
List of indices of the arms for which we will generate the G-Optimal design.
Returns
-------
pi : np array
A probabil... | The code implements a bandit algorithm using G-optimal design and elimination. It iteratively computes G-optimal arm allocations, executes pulls based on computed frequencies, updates the bandit's state, and eliminates suboptimal arms after each phase. The loop continues until the horizon is reached, with final array t... | def play(self):
"""
Play the bandit using G-optimal design and elimination.
Returns
-------
None.
"""
while self.t <= self.horizon:
# Compute the G-optimal design for current action set
pi = self.getGOpt(self.actionS... |
def bench_submit(max_workers):
with title(f"submit(sum, {NUMBERS}) max_workers={max_workers} times={BIG_AMOUNT}:"):
with bench(futures.ThreadPoolExecutor(max_workers)) as tpe:
for _ in range(BIG_AMOUNT):
tpe.submit(tpe.submit(sum, NUMBERS))
with bench(threadlet.ThreadPoo... | The main task of the code is to execute three benchmarking phases for values 1–4: first submitting tasks, then waiting for all tasks to complete, and finally submitting and waiting for all tasks in a combined operation, likely testing asynchronous processing performance across different scenarios. | def main():
for n in range(1, 5):
bench_submit(n)
for n in range(1, 5):
bench_wait_all(n)
for n in range(1, 5):
bench_submit_and_wait_all(n) |
def setup(self):
pass
def send_message_to_server(self):
message_to_send = self.mqtt_topic.get_message_to_send()
for msg in message_to_send:
self.send_on_socket(msg)
self.mqtt_topic.clear_message_to_send()
def notify_client(self, topic_str, message):
topic = self.mqtt_... | The code sets up MQTT subscriptions, initializes components, and processes incoming socket data. It maps topics to callback methods, handles message routing, and sends/receives data between clients and servers. The loop continuously listens for data, parses topics/payloads, and triggers callbacks or server notification... | def run(self):
self.mqtt_topic.environment.date_time.subscribe()
self.mqtt_topic.simulation.verbose.subscribe()
self.setup()
if self.subscribe_with_method_name:
for name in self.mqtt_topic.message_dictonary:
try:
method_name = name.replace(... |
def reset_start_time():
global start_generation_time, start_rock_generation_time, \
start_recovery_generation_time, t_start, h_start,start_time
start_generation_time = time.time()
start_rock_generation_time = time.time()
start_recovery_generation_time = time.time()
t_start = time.time()
h_st... | The code manages a game loop that controls music playback and game status transitions. It initializes music tracks for different states (start, background, fall, pause), checks the current game status (start, running, over), and plays/stops appropriate music. It also calls game logic functions and resets game elements ... | def game_run(screen,clock):
global start_generation_time,start_rock_generation_time,\
start_recovery_generation_time,t_start,h_start,start_time
getready = Game_Music(setting.get_ready)
Game_status = Game_Status(screen)
background_music = Game_Music(setting.background_music)
start_music = Game_... |
def make_frequency_dict(self, text):
frequency = {}
for char in text:
if not char in frequency:
frequency[char] = 0
frequency[char] += 1
return frequency
def min_heapify_dict(self, frequency):
heap = []
for key in frequency:
nod... | The code encodes input text using Huffman coding: it builds a frequency dictionary, constructs a min-heap, merges nodes into a Huffman tree, generates binary codes from the tree, and converts the text into an encoded binary string. The function returns the encoded text and the Huffman tree for later decoding. | def encode(self, text):
if text == "":
return "", None
frequency_dict = self.make_frequency_dict(text)
min_heap = self.min_heapify_dict(frequency_dict)
merged_heap = self.merge_nodes(min_heap)
tree = heapq.heappop(merged_heap)
codes = self.make_codes(tree)
... |
def enum_value_t(consts):
yield "enum value_t {"
for const in consts:
yield f"{const.name},"
yield "};"
def bits_to_mask(bits) -> str:
start, end = bits_start_end(bits)
mask = bits_mask_literal(bits, start, end)
return f"0b{mask} << {start}"
def enum_consts_to_value(namespace_name, enum_... | This code generates C++ struct code for an enum, including value storage, constructors for initializing from values or codes, a bitmask calculation, and helper functions to map constants to values and their bit representations. It creates a strongly-typed enum wrapper with conversion capabilities and bitmask operations... | def enum_struct(namespace, enum):
yield f"struct {enum.name}_t {{"
yield from enum_value_t(enum.consts)
yield ""
yield "const value_t value;"
yield ""
yield f"constexpr {enum.name}_t(value_t value)"
yield " : value(value) {}"
yield ""
yield f"constexpr {enum.name}_t(uint32_t code)"
... |
def sort_events(events):
enums = []
structs = []
namespace = None
def do_yield():
nonlocal enums, structs, namespace
yield namespace
#yield from sorted(enums, key=lambda e: e.name)
yield from enums
assert structs, structs
yield from structs
#yield... | The main task of the code is to generate a header file by parsing input data, sorting events, and rendering necessary includes and namespaces into the output. It processes a file via command-line arguments, parses and sorts events, initializes a renderer, generates includes and header namespaces, and returns the compil... | def generate_header():
events = list(sort_events(parse(read(sys.argv[1]))))
render, out = renderer()
render(generate_includes())
render(generate_header_namespaces(events))
return out |
def CreateEvolutionHistoryFile(self):
"""
Create a file to store the evolution history of the swarm
Insert header line
"""
history_file_path = os.path.join(self.Output, "EnsembleEvolutionHistory.dat")
assert not os.path.isfile(history_file_path), "Ensemble evolution file... | This code runs optimization/sampling for all swarms by evolving them iteratively while the ContinueCondition holds. It manages periodic checkpoints, saves evolution data if enabled, prints status updates, and ensures hierarchical steps are checked. Finally, it saves the results after completing the process. | def Run(self):
"""
Run optmisation/sampling for all swarms
"""
if self.SaveEvolution and self.EvolutionCounter==0:
self.CreateEvolutionHistoryFile()
self.SaveEnsembleEvolution()
while self.ContinueCondition() and (self.swarm_stepping_done == False):
... |
def merkle_tree(self,list_transact):
keys = list(list_transact.keys())
values=list(list_transact.values())
t1=keys[0]+values[0]
t2=keys[1]+values[1]
t3=keys[2]+values[2]
t4=keys[3]+values[3]
t5=keys[4]+values[4]
t6=keys[5]+values[5]
t=[t1,t2,t3,t4,... | The code mines a new block by generating a Merkle root from transaction data, creating a block with incremented nonce and previous hash, performing proof-of-work, validating the block, and appending it to the blockchain if valid. | def insert_block(self, data):#Mine a new Block with six transactions from mempool
merkle_root=self.merkle_tree(data)
newNode=Block(merkle_root)
newNode.data=data
prev_block=self.get_prev_block()
nonce=str(int(prev_block.nonce)+1)
newNode.nonce=nonce
newNode.prev_h... |
def step(self):
for o in self.objects:
o.step()
if o.has_left():
self.objects.remove(o)
if len(self.objects) < self.max_object:
tries = 0
while tries < 1:
self.add_new_object()
tries += 1
def draw(self, wait... | The code generates training data for a neural network by creating input tensors from a map, classification targets (object locations), and regression targets (object parameters like position, orientation, velocity). It processes objects in the scene, maps their properties to tensors, applies noise, and scales outputs t... | def __getitem__(self, idx):
# each time a sample is drawn, advance one step and draw the map
self.step()
self.draw()
### define matching tensor and regression target tensor (full map width)
# fill with ignore tensor (just draw boxes filled)
# then fill closest cell to ea... |
def get_map_limits(map):
max_y = len(map) - 1
max_x = len(map[0]) - 1
end = [max_x, max_y]
min_best = max_x + max_y - 1
max_best = max_x * max_y
return end, min_best, max_best
def update_dist_map(dist_map, loc, walls, steps):
dist_map[walls][str(loc)] = steps
return dist_map
def explore(... | This code calculates the maximum number of steps required to navigate from the start position [0,0] to the end in a grid-based map, considering walls. It initializes a distance map, updates it with initial values, and uses an exploration function to determine the longest valid path. The result is the 'max_best' value f... | def solution(map):
end, min_best, max_best = get_map_limits(map)
dist_map = {0:{}, 1:{}, 'min_best': min_best, 'max_best': max_best}
loc = [0, 0]
steps = 1
walls = 0
dist_map = update_dist_map(dist_map, loc, walls, steps)
explore(loc, steps, walls, end, dist_map, map)
dist = dist_map['m... |
def get_stats_files(data_dir):
files = glob('{0}/*Stats*.dat'.format(data_dir))
if len(files) == 0:
raise ValueError('No refs files in {0}. Your refs files should end with "Stats<number>.dat". example: "S400_T30_C_2refs_LinearStats5.dat"'.format(data_dir))
return sorted(files)
def get_fit_files(data... | The code generates a Jupyter notebook summarizing statistical analysis results from input files. It processes data from specified directories, parses statistics and fit files, and creates a structured notebook with sections for each scenario, including summaries, visualizations, and hyperlinks. The tool handles command... | def main():
parser = argparse.ArgumentParser()
parser.add_argument('data_dir')
parser.add_argument('--limit-scenarios', default=20)
parser.add_argument('--overwrite', action='store_true', default=False)
parser.add_argument('--merge', action='store_true', default=False)
args = parser.parse_args(... |
def csvExists():
if os.path.exists('database/time-spent.csv'):
return True
return False
def updateData(creds, date_from, to_date = date.today()):
try:
service = build('calendar', 'v3', credentials=creds)
startTime = date_from + "T00:00:00Z" #str(date_from.strftime('%Y-%m-%d'))
... | The main task of the code is to fetch calendar events from Google Calendar API using provided credentials, either updating an existing CSV file with new data from the last recorded date to a specified end date, or creating a new CSV file containing all events from a start date to the end date. The function handles date... | def fetchAndStoreData(creds, to_date = date.today()):
try:
service = build('calendar', 'v3', credentials=creds)
print(to_date)
# If a df exists, overwrite from the day we have data from.
if csvExists():
with open('database/time-spent.csv', 'r') as csv:
... |
def generate_point_pairs(self, point_coordinates: Union[List[List[float]], npt.NDArray[np.float64]]) \
-> List[List[int]]:
"""
Generates pairs of point IDs which form a line
Args:
point_coordinates (Union[List[List[float]], npt.NDArray[float]]): A list of geometry points... | The code generates a 2D or 3D mesh using Gmsh based on input point coordinates, extrusion depth, and mesh size, creating a geometry model, synchronizing it, and exporting mesh data. It optionally saves the mesh to a file or opens the Gmsh GUI for visualization, handling both 2D and 3D geometries through separate intern... | def generate_gmsh_mesh(self, point_coordinates: Union[List[List[float]], npt.NDArray[np.float64]],
extrusion_length: Union[List[float], npt.NDArray[np.float64]], mesh_size: float, dims: int,
name_label: str, mesh_name: str, mesh_output_dir: str, save_file: bool = Fa... |
def get_prices():
prices = client.get_orderbook_tickers()
prepared = defaultdict(dict)
for ticker in prices:
pair = ticker['symbol']
ask = float(ticker['askPrice'])
bid = float(ticker['bidPrice'])
if ask == 0.0:
continue
for primary in PRIMARY:
... | The code's main task is to download price data, compute potential arbitrage opportunities (triangles), and display them sorted by profit. If no triangles are found, it recursively restarts the process. | def main():
start_time = time()
prices = get_prices()
prices_time = time()
print(f"Downloaded in: {prices_time - start_time:.4f}s")
triangles = list(find_triangles(prices))
print(f"Computed in: {time() - prices_time:.4f}s")
if triangles:
for triangle in sorted(triangles, key=itemg... |
def fGenDict(self) -> dict:
ret_d = deepcopy(self.default)
chars = deepcopy(self.chars)
for k in self.default.keys():
c = choice(chars)
chars.remove(c)
ret_d[k] = c
# If somone messes up big time
if len(chars) > 0:
raise NotImplemen... | The code generates encryption and decryption functions. It creates a dictionary `d`, its reverse `rd`, and keys `k`. Using these, it defines `encrypt` (to encrypt messages) and `decrypt` (to decrypt text), returning both functions for secure data transformation. | def fGenFuncs(self, *for_keys):
d = self.fGenDict()
rd = self.fReverseDict(d)
k = self.fGenKeys(*for_keys)
encrypt = lambda msg: self.fEncryptKeys(msg, d, k)
decrypt = lambda txt: self.fDecryptKeys(txt, rd, k)
return encrypt, decrypt |
def parseArgs():
parser = argparse.ArgumentParser()
parser.add_argument("-m", "--mount", action="store_true",
help="Mount an auto-detected usb.")
parser.add_argument("-e", "--autoeject", action="store_true",
help="Eject the last mounted usb.")
parser.add_a... | The main task of the code is to handle USB device mounting/unmounting based on command-line arguments. It parses flags like `--mount`, `--autoeject`, and `--eject`, executing corresponding operations with timeout/timerange parameters, and handling success/failure cases with `either()` for error reporting or silent exit... | def main():
args = parseArgs()
if args.mount:
return automount_usb(args.timeout, args.timerange)\
.either(print_pair,
print_error("No usb found!"))
elif args.autoeject:
return autounmount_usb()\
.bind(lambda x: Just(x) if x == 0 else Nothing())\
... |
def copy_to_temp_dir(dest_dir):
# Copy project to temp dir.
src_dir = (Path(__file__).parents[1] / 'chapter_20'
/ 'deploying_learning_log')
shutil.copytree(src_dir, dest_dir)
def modify_requirements(request, dest_dir):
"""Modify requirements.txt based on --django-version."""
# Unpin req... | This function tests a Django project by setting up a temporary environment, configuring dependencies, creating a virtual environment, running migrations, validating the setup, executing end-to-end tests, and displaying Python/Django versions used during testing. | def test_django_project(request, tmp_path, python_cmd):
"""Test the Learning Log project."""
# Copy project to temp dir.
dest_dir = tmp_path / 'learning_log'
copy_to_temp_dir(dest_dir)
# All remaining work needs to be done in dest_dir.
os.chdir(dest_dir)
# Process --django-version CLI arg... |
def filename(reverse, obj):
filename = ''
if reverse:
filename += 'reverse_'
filename += obj
return filename
def batch2TrainData(voc, pair_batch, reverse):
if reverse:
pair_batch = [pair[::-1] for pair in pair_batch]
pair_batch.sort(key=lambda x: len(x[0].split(" ")), reverse=Tru... | The code trains a sequence-to-sequence model with attention for language translation, using preloaded or generated training data. It initializes encoder/decoder networks, optimizers, and iteratively trains the model over specified iterations, calculating loss and perplexity. Periodic checkpoints save model states, opti... | def trainIters(corpus, reverse, n_iteration, learning_rate, batch_size, n_layers,
hidden_size, print_every, save_every, dropout, loadFilename=None,
attn_model='dot', decoder_learning_ratio=5.0):
voc, pairs = loadPrepareData(corpus)
# training data
corpus_name = os.path.... |
def bitmap(self,size,row=None,col=None):
"""
Creates a Tensor bitmap board and inserts True on the (row,col) position
:param size:
:param row:
:param col:
:return:
"""
board_state = torch.zeros(size,size,dtype=torch.bool)
if row is not None and col... | This function computes valid movement options for an ant on a board when self.level is 0. It calculates neighboring positions by removing the ant's current position from the board, then updates a moves bitmap with available directions. If self.level is not 0, it returns None. | def _moves_ant(self, board_all):
"""
:param board_all:
:return:
"""
if self.level == 0:
origo = (self.y + 1, self.x + 1)
moves = self.bitmap(board_all.shape[0])
board = board_all.clone()
board[origo[0], origo[1]] = False
... |
def hive_player(self):
return self.hive_white if self.whites_turn else self.hive_black
def level_pieces(self, x_org, y_org, x_dst, y_dst):
"""
This routine shifts all piece levels up 1 in (x_org,y_org) to a maximum of 0,
and shifts every level down 1 in (x_dst,y_dst).
This routin... | The code moves a specified game piece within a hive structure by updating its coordinates, calculates overlapping pieces if the piece is a 'b' type, executes the move in the hive, and transitions to the next player's turn. | def move_piece(self,idx:int,x:int,y:int):
hive = self.hive_player()
piece = hive[idx]
if str(piece).lower() == 'b':
piece.pieces_under = self.level_pieces(piece.x,piece.y,x,y)
hive.move_piece(idx,x,y)
self.next_player() |
def hive_player(self):
return self.hive_white if self.whites_turn else self.hive_black
def hive_opp(self):
return self.hive_black if self.whites_turn else self.hive_white
def generate_bitmap_board_state(self,default_state=False):
if default_state:
board_state = torch.ones(self.board_... | This function generates legal moves for a player in a board game (likely Hive) by analyzing the current board state, determining spawn locations for unplaced pieces, calculating movable positions using graph traversal, and assigning valid moves to each piece based on game rules. It handles queen placement logic, piece ... | def generate_legal_moves(self):
hive_player = self.hive_player()
hive_opp = self.hive_opp()
# board_state_player = self.generate_clean_board_state()
board_state_player = self.generate_bitmap_board_state()
board_state_opp = self.generate_bitmap_board_state()
#First we gen... |
def get_timeaxis(self):
timeaxis=[]
iaxis=[]
for i in range(self.npts):
timeaxis.append(self.starttime + i*self.dtime)
iaxis.append(i*self.dt)
self.timeaxis=timeaxis
self.times=iaxis
def get_w_T(self, regphase=365, startmod=365*2,DYfac=2 ):
"""
... | This code generates synthetic data by initializing a random number generator, computing time axes, applying phase-specific transformations (get_w_T), and synthesizing data (get_syndata), with parameters controlling temporal phases, scaling, and randomness. | def run(self, regphase=365, startmod=365*2,DYfac=2 ):
self.prng = np.random.RandomState(self.randseed)
self.get_timeaxis()
self.get_w_T(regphase, startmod,DYfac)
self.get_syndata() |
def read_in():
sensordata = sys.stdin.readlines()
#Since our input would only be having one line, parse our JSON data from that
return json.loads(sensordata[0])
def organize_all_sensor_data(attributes, frequency, sensorIds, start_time, end_time,
annual_data, monthly_data, daily... | The main task of the code is to process sensor data across different time granularities (annual, monthly, daily, hourly), organize it into structured formats, generate visualization data (bar graphs, heatmaps, histograms), and output the results in JSON format for downstream use, such as visualization or analysis in a ... | def main():
# print('in man function');
# print("hi from python")
# #get our data as an array from read_in()
data = read_in()
frequency = data[0]
attributes = data[1]
sensor_sets = data[2];
start_time = data[3];
end_time = data[4]
annual_data = data[5]
monthly_data = data[6... |
def check_environment():
check_program("base64")
check_program("curl")
check_program("kubectl")
check_program("skupper")
def _apply_standard_steps(skewer_data):
notice("Applying standard steps")
for step_data in skewer_data["steps"]:
if "standard" not in step_data:
continue
... | The main task of the code is to execute a series of predefined steps from a YAML file (`skewer_file`), using provided kubeconfig files for each site. It sets up a temporary working directory, applies standard steps, runs each step in the workflow (skipping "cleaning_up"), and handles errors by printing debug output if ... | def run_steps(skewer_file, *kubeconfigs, debug=False):
check_environment()
skewer_data = read_yaml(skewer_file)
work_dir = make_temp_dir()
for i, site in enumerate(skewer_data["sites"].values()):
site["kubeconfig"] = kubeconfigs[i]
_apply_standard_steps(skewer_data)
try:
for ... |
def stop():
global server_socket
if server_socket:
server_socket.close()
server_socket = None
def print_scr(text, fg, bg):
tft.fill(bg)
messages.append(text)
a = len(messages) - 12
b = len(messages)
if (len(messages) < 12):
a = 0
b = len(messages)
for i i... | The code sets up a web server on an ESP device to handle WiFi configuration. It initializes an access point (AP) with a specified SSID/password, listens for client connections, and processes HTTP requests to manage device configuration or serve content. The server switches to station mode upon successful connection, di... | def start(port=80):
global server_socket
addr = socket.getaddrinfo('0.0.0.0', port)[0][-1]
stop()
wlan_sta.active(True)
wlan_ap.active(True)
wlan_ap.config(essid=ap_ssid, password=ap_password, authmode=ap_authmode)
server_socket = socket.socket()
server_socket.bind(addr)
server_... |
def print_scr(text, fg, bg):
tft.fill(bg)
messages.append(text)
a = len(messages) - 12
b = len(messages)
if (len(messages) < 12):
a = 0
b = len(messages)
for i in range(a, b):
tft.text(
small,
messages[i],
8,
... | This function establishes a Wi-Fi connection using stored profiles. It checks for an existing connection, scans for networks, attempts to connect to known encrypted/open networks with stored passwords, and starts a web server for configuration if needed. It returns the connected WLAN instance or None upon failure. | def get_connection():
"""return a working WLAN(STA_IF) instance or None"""
# First check if there already is any connection:
if wlan_sta.isconnected():
print_scr("WiFi connection already established", s3lcd.WHITE, s3lcd.BLACK)
return wlan_sta
connected = False
try:
# ESP conn... |
def color_match(reference_hist, uncategorized_hist, histogram_cutoff, comparison_method):
# compute whether the two images have similar histograms
# if they do not, return False
match_score = cv2.compareHist(reference_hist, uncategorized_hist, comparison_method) # compute the histogram match score between t... | The code categorizes images by fractal shape using histogram and EMD (Earth Mover's Distance) analysis. It supports three modes: `-all` (group all images via histograms and EMD), `-one` (find images matching a reference), and `-specific` (compare two images). It processes image folders, resizes images, detects shapeles... | def main():
# Read in command line arguments
num_args = len(sys.argv)
if num_args < 4:
# Error
print("ERROR: Program usage: python3 combination.py (-all, -one, or -specific) (image folder name) [specific flag parameters] (x-resolution) (y-resolution)")
return -1
# Determine pro... |
def _rk4_step(cls, state, force, dt, k1=None):
point, vector = state
if k1 is None:
k1 = cls.compose(point, vector)
l1 = force(point, vector)
k2 = cls.compose(point + dt / 2 * k1, vector + dt / 2 * l1)
l2 = force(point + dt / 2 * k1, vector + dt / 2 * l1)
k3 =... | This code implements a geometric integration method called 'pole ladder' for parallel transport on a manifold. It computes the transported vector along a curve defined by base_point, using tangent vectors tan_a and tan_b, with n_rungs steps. The method applies a sequence of Runge-Kutta steps (RK4) and symmetry operatio... | def pole_ladder(self, tan_a, tan_b, base_point, n_rungs=1, **kwargs):
dt = 1 / n_rungs
current_shoot, _ = self._rk4_step(
(base_point, self.compose(self.inverse(base_point), tan_a)),
self.lie_acceleration, dt)
left_angular_vel = self.compose(self.inverse(base_point), tan_... |
def midpoint(self, point_1, point_2, **kwargs):
return self.exp(
1. / 2 * self.log(point_1, point_2, **kwargs), point_2, **kwargs)
def symmetry(self, point, base_point, **kwargs):
return self.exp(- self.log(point, base_point, **kwargs), base_point,
**kwargs)
def log(
... | This function performs a pole ladder step for parallel transport on a manifold. It computes the midpoint between points, calculates the symmetric point of the base vector relative to the midpoint, derives a transported vector via logarithmic mapping, and exponentiates it at the next point to obtain the transported vect... | def _pole_ladder_step(self, base_point, next_point, base_shoot, **kwargs):
midpoint_ = self.midpoint(next_point, base_point, **kwargs)
first_sym = self.symmetry(base_shoot, midpoint_, **kwargs)
transported_vec = - self.log(first_sym, next_point, **kwargs)
next_shoot = self.exp(transporte... |
def midpoint(self, point_1, point_2, **kwargs):
return self.exp(
1. / 2 * self.log(point_1, point_2, **kwargs), point_2, **kwargs)
def symmetry(self, point, base_point, **kwargs):
return self.exp(- self.log(point, base_point, **kwargs), base_point,
**kwargs)
def log(
... | The function computes a step in Schild's ladder for parallel transport on a manifold. It calculates the midpoint between `next_point` and `base_shoot`, reflects `base_point` across this midpoint to get `first_sym`, and computes the logarithm of `first_sym` relative to `next_point` as the transported vector. Returns bot... | def _schild_ladder_step(self, base_point, next_point, base_shoot, **kwargs):
midpoint_ = self.midpoint(next_point, base_shoot, **kwargs)
first_sym = self.symmetry(base_point, midpoint_, **kwargs)
transported_vec = self.log(first_sym, next_point, **kwargs)
return transported_vec, first_sy... |
def sectional_curvature(self, x, y):
"""
< R(x, y)x, y> for x, y orthogonal. This is compensated if not
"""
num = self.metric(y, self.curvature(x, y, x))
denom = self.metric(x, x) * self.metric(y, y) - self.metric(x, y) ** 2
condition = gs.isclose(denom, 0.)
retur... | This function computes the sectional curvature of two tangent vectors at a specified base point on a manifold. If no base point is provided, it calculates the curvature at the identity. It transforms the tangent vectors to the identity using the inverse of the base point and then computes the sectional curvature of the... | def sectional_curvature_at_point(
self, tangent_vec_a, tangent_vec_b, base_point=None):
if base_point is None:
return self.sectional_curvature(tangent_vec_a, tangent_vec_b)
tan_a_at_id = self.compose(self.inverse(base_point), tangent_vec_a)
tan_b_at_id = self.compose(self... |
def nabla_curvature(self, x, y, z, t):
r"""
(\nabla_x R)(y, z)t
"""
return self.nabla(x, self.curvature(y, z, t)) - self.curvature(
self.nabla(x, y), z, t) - self.curvature(y, self.nabla(x, z),
t) - self.curvature(
... | The function computes the curvature of a connection (nabla) at a specified base point using four tangent vectors. If no base point is provided, it calculates the curvature directly. Otherwise, it translates tangent vectors to the identity element via the inverse of the base point, computes the curvature at the identity... | def nabla_curvature_at_point(
self, tangent_vec_a, tangent_vec_b, tangent_vec_c, tangent_vec_d,
base_point=None):
if base_point is None:
return self.nabla_curvature(
tangent_vec_a, tangent_vec_b, tangent_vec_c, tangent_vec_d)
tan_a_at_id = self.compose... |
def PrepareDF(df):
## split to x and y
X = df.drop([cl[10]] ,axis=1)
Y = df[cl[10]]
# replace F and M to 1 and 0
dictGender = {
'F':0,
'M':1,
'f':0,
'm':1
}
# replace am or pm to 1 and 0
dictTime = {
'AM':0,
'PM':1,
'am':0,
'pm':1
}
CityinData,CityI... | The main task of the code is to train and save three machine learning models (Logistic Regression, K-Nearest Neighbors, and Decision Tree) using a provided dataset. It splits the data into training/test sets, converts features/labels to NumPy arrays, trains all models (with Logistic Regression commented out), and saves... | def Train(Tdata : pd.DataFrame):## params = panada.df goal = to train model
X,Y = PrepareDF(Tdata)
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.2, random_state=42)
X_train = X_train.values
X_test = X_test.values
Y_train = Y_train.values
Y_test = Y_test.values
Logi... |
def parse_metadata(metadata, args):
if "sshs_model_hash" in metadata:
items = parse(metadata)
# TODO if we are missing this value, they may not be saving the metadata
# to the file or are missing key components. Should evaluate if we need
# to do more in the case that this is missin... | The function processes a SafeTensor file by extracting metadata, determining the data type from weight keys, parsing metadata with arguments, and optionally handling weights/tags. It returns a dictionary containing file info, parsed metadata, and processed data based on input arguments. | def process_safetensor_file(file: Path, args) -> dict[str, Any]:
with safe_open(file, framework="pt", device="cpu") as f:
metadata = f.metadata()
filename = os.path.basename(file)
print(file)
parsed = {}
if metadata is not None:
for key in f.keys():
... |
def get_relation_subtype(lmap, line_string):
usages = [
lanelet.attributes['subtype'] for lanelet in lmap.laneletLayer.findUsages(line_string)
]
if 'crosswalk' in usages:
return 'crosswalk'
elif 'road' in usages:
return 'road'
elif 'walkway' in usages:
return 'walkway... | This function extracts and labels lanelet polylines from a map within a region of interest (ROI). It filters line strings by type, converts them to local coordinates, applies ROI size filtering, and normalizes coordinates if specified. The result is a collection of labeled polylines for use in autonomous driving or map... | def extract_lanelets(self, lanelet2_map, roi_size, pose, normalize) -> LabeledPolylines:
distance = np.max(roi_size) / 2
labeled_polylines = LabeledPolylines()
for line_string in lanelet2_map.lineStringLayer:
# Check if the line type is of interest
way_type = line_string... |
def open_pred(filename):
'''
Input: .gtf file
Output: df with additional columns for protein ids and gene ids.
'''
df = pd.read_csv(filename, sep='\t', index_col=False, names=[
'Seqid', 'Source', 'Type', 'Start', 'End', 'Score', 'Strand', 'Frame', 'Suppl'])
df = df[df['Type'... | The main task of the code is to process protein prediction data by filtering supported proteins based on tissue-specific peptide evidence and transcript scores, then generating a structured output (TSV and GTF files) containing these validated proteins. It involves loading data, deduplicating sequences, mapping tissue ... | def main(argv):
file_prediction = argv[0]
file_tx_scores = argv[1]
file_gene_spec_pept = argv[2]
file_output_gtf = argv[3]
# prediction
df = open_pred(file_prediction)
prot_all = list(set(df['protein'].values.tolist()))
print('Number of all proteins:', len(prot_all))
# dict with seq... |
def get_pickle_joint_data(file):
'''Pull pickled data'''
# file_name = re.search('(.*)(?:[.])', file).group(1)
with open (file, 'rb') as fp:
raw_data = pickle.load(fp)
'''Load picked data into numpy.
Bounding box values are: 'xyxy' = (left, top, right, bottom)
Key Point values are: (n... | The function loads and converts joint data from four pose estimation models (HRNet, PoseNet, OpenPose, WRNCH) into pandas DataFrames for analysis. It retrieves raw data from pickle files, processes each using `raw_data_to_dataframe`, and returns four structured DataFrames containing pose estimation results. The WRNCH d... | def get_hrnet_posenet_wrnch_dfs(file, width, height):
'''Loads target file into data frames for further analysis'''
hrnet_raw_data = get_pickle_joint_data(f'work_dirs/tumeke_testing/pickle_files/{file}.p')
posenet_raw_data = get_pickle_joint_data(f'work_dirs/tumeke_testing/posenet_pickle_files/{file}.p... |
def _print_intrudoctions(self) -> None:
"""
Displays introductory messages for the user.
"""
rospy.loginfo("[WELCOME]: ACCELEROMETER CALIBRATION TOOL\n")
rospy.loginfo("Explanation:")
rospy.loginfo("Press 'm' to start measurement")
rospy.loginfo("Press 's' to save... | This code defines the main execution loop of an accelerometer calibration tool. It manages a state machine handling user input, measurement collection, data saving, and shutdown processes. The loop runs until ROS shuts down or maximum samples are collected, transitioning between WAIT_FOR_INPUT, MEASUREMENT, SAVE, and Q... | def run(self) -> None:
"""
Main entry point for the accelerometer calibration tool.
"""
self._print_intrudoctions()
self.state = State.WAIT_FOR_INPUT
while not rospy.is_shutdown() and len(self.samples) < self.MAX_SAMPLES:
if self.state is State.WAIT_FOR_INPUT... |
def check(self, tokentype: TokenType):
if self.is_at_end():
return False
return self.peek().tokentype == tokentype
def advance(self):
if not self.is_at_end():
self.current += 1
return self.previous()
def error(self, token: Token, message: str):
ErrorHand... | This method consumes a token of the specified type by checking if the current token matches `tokentype`. If it does, it advances the parser and returns the consumed token; otherwise, it raises an error with the provided message and the current token. The core task is to validate and consume tokens during parsing, ensur... | def consume(self, tokentype: TokenType, message: str):
if self.check(tokentype):
return self.advance()
raise self.error(self.peek(), message) |
def advance(self):
if not self.is_at_end():
self.current += 1
return self.previous()
def is_at_end(self):
return self.peek().tokentype == TokenType.EOF
def previous(self):
return self.tokens[self.current - 1]
def peek(self):
return self.tokens[self.current] | This method advances through tokens to find the start of a new statement, returning when encountering an end-of-line token or reaching the input's end. It skips tokens until a valid statement boundary is identified, ensuring synchronization with the input stream. | def synchronize(self):
# TODO: This is where we should try to
# find the start of a new statement.
self.advance()
while not self.is_at_end():
if self.previous().tokentype == TokenType.EOL:
return
if self.peek().tokentype in []:
re... |
def bollinger_bands(ratio_lst, window_size, num_sd=1.4):
ratio = pd.DataFrame(ratio_lst)
moving_average, moving_average_lst = get_moving_average(ratio_lst, window_size)
moving_sd = ratio.rolling(window=window_size).std()
moving_sd_lst = moving_sd.values.tolist()
upper_band = (moving_average + (movin... | The code determines a trading case and multiplier based on the position of a short-term moving average relative to Bollinger Bands. If the short-term average is below the lower band, it sets case=2 and calculates a negative multiplier via the z-score. If above the upper band, case=1 with a positive z-score multiplier. ... | def trade_moving(ratio, stock1, stock2, index, window_size=20, short_window_size=5):
case = 0
multiplier = 1
moving_average, moving_sd, upper_band, lower_band = bollinger_bands(ratio, window_size)
moving_average_short, moving_average_short_lst = get_moving_average(ratio, short_window_size)
if (movin... |
def trade_simple(ratio, stock1, stock2, index):
cur_score = z_score(stock1[index], stock2[index], ratio)
case = 0
if (cur_score > 1):
case = 1
if (cur_score < -1):
case = 2
cur_score = max(cur_score, -1 * cur_score)
return case, cur_score
def trade_moving(ratio, stock1, stock2, i... | The code simulates a trading strategy using two stocks, where the model (simple or moving average-based) determines buy/sell decisions. It tracks portfolio value, stock holdings, and transaction times/prices. After processing all data, it calculates final portfolio value, plots stock prices with buy/sell markers, and o... | def testing(start,ratio, stock1, stock2, model, starting_amount, const): # const should be >5
portfolio_value = starting_amount
stock1_owned = 0
stock2_owned = 0
case = 0
cur_score = 0
buy_time = []
buy_price = []
sell_time = []
sell_price = []
for i in range(start, len(ratio)):
... |
def docker_network(
action: Annotated[DockerNetworkAction, typer.Argument(..., help="Action to perform", case_sensitive=False)],
name: Annotated[str, typer.Option("-n", "--name", help="Network name")] = "network-observability",
driver: Annotated[str, typer.Option(help="Network driver")] = "bridge",
subn... | The code deploys a lab environment using containerlab and Docker by creating a network, deploying a topology file, and starting services. It accepts parameters like scenario, topology path, network name, subnet, and sudo flag. The function logs deployment progress and ensures the lab is ready for the specified scenario... | def lab_deploy(
scenario: Annotated[
NetObsScenarios, typer.Option("--scenario", "-s", help="Scenario to execute command", envvar="LAB_SCENARIO")
],
topology: Annotated[Path, typer.Option(help="Path to the topology file", exists=True)] = Path(
"./containerlab/lab.yml"
),
network_name... |
def docker_stop(
scenario: Annotated[
NetObsScenarios, typer.Option("--scenario", "-s", help="Scenario to execute command", envvar="LAB_SCENARIO")
],
services: Annotated[Optional[list[str]], typer.Argument(help="Service(s) to show")] = None,
verbose: Annotated[bool, typer.Option(help="Verbose mo... | The main task of the code is to rebuild Docker containers for specified services within a lab scenario. It stops existing containers, rebuilds them with updated configurations, and restarts them. The function supports rebuilding all services or specific ones, using Docker commands for each step, and logs the process wi... | def lab_rebuild(
services: Annotated[list[str], typer.Argument(help="Service(s) to rebuild")],
scenario: Annotated[
NetObsScenarios, typer.Option("--scenario", "-s", help="Scenario to execute command", envvar="LAB_SCENARIO")
],
):
"""Rebuild the service(s) of a lab scenario.
[u]Example:[/u]... |
def get_ds(config):
ds_raw = load_dataset("opus_books", f"{config['lang_src']}-{config['lang_tgt']}", split="train")
tokenizer_src = get_or_build_tokenizer(config, ds_raw, config["lang_src"])
tokenizer_tgt = get_or_build_tokenizer(config, ds_raw, config["lang_tgt"])
train_ds_size = int(0.9 * len(ds_raw... | This code trains a neural machine translation model using a transformer architecture. It loads datasets, initializes the model, sets up an optimizer, and performs training with mixed precision support. The loop processes batches, computes loss, updates weights, and saves checkpoints. Validation is run after each epoch,... | def train_model(config):
print("config used: ", config)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print("Using device: ", device)
Path(config['model_folder']).mkdir(parents=True, exist_ok=True)
train_loader, val_loader, tokenizer_src, tokenizer_tgt = get_ds(config)
mo... |
def set_up_interventions(args):
syn_intervention = ImageIntervention(
'syn_aug',
args.syn_strategy,
phase='test',
not_single=args.comp_aug
)
real_intervention = ImageInte... | The code trains a distilled machine learning model using distributed computing, focusing on knowledge distillation and curriculum learning. It initializes data loaders, sets up a Distill model for training, and manages distributed training with PyTorch's DDP. The model is optimized using Adam/Adabelief/Lamb, with dynam... | def main_worker(gpu, ngpus_per_node, args):
global best_acc1, best_loss1
best_acc1 = 0
best_loss1 = 1000
args.gpu = gpu
if args.gpu is not None:
print("Use GPU: {} for training".format(args.gpu))
if args.distributed:
if args.dist_url == "env://" and args.rank == -1:
... |
def make_concatenated_dataset():
"""
Reads all used CSV files and returns the concatenated dataset with the used format.
:return: DataFrame with the used format
"""
adapted = []
user_id = 1
for sleep_cycle_file in [
'../data/sd1.csv',
'../data/sd2.csv',
'../data/sd3.... | The main task of the code is to generate and save multiple versions of a sleep data dataset. It first creates a concatenated dataset using `make_concatenated_dataset()`, then classifies it into two distinct formats via `make_classified()` and `make_classified_2()`. Each processed dataset is exported as a CSV file to th... | def main():
concatenated = make_concatenated_dataset()
concatenated.to_csv('../data/sleepdata.csv', index=False)
classified = make_classified(concatenated)
classified.to_csv('../data/sleepdata_classified.csv', index=False)
classified2 = make_classified_2(concatenated)
classified2.to_csv('../da... |
def records_rmse(expected, actual):
return np.sqrt(np.mean((expected - actual) ** 2))
def records_mae(expected, actual):
return np.mean(np.abs(expected - actual))
def records_aoc_n(expected, actual):
return records_aoc(expected=expected, actual=actual) / len(expected) | The code calculates evaluation metrics (RMSE, MAE, AOC-N) by comparing expected and actual values, returning them in an EvaluationResults object for performance analysis. | def get_evaluation_results(expected, actual):
return EvaluationResults(
rmse=records_rmse(expected, actual),
mae=records_mae(expected, actual),
aoc_n=records_aoc_n(expected, actual)
) |
def gaussian_blur(image, kernel_size):
kernel = gaussian_kernel(kernel_size, -1)
return filter_2d(image, kernel)
def sobel_edge_detection(image, convert_to_degree=False):
"""
Sobel Edge Detection
--------------------
image : ndarray
convert_to_degrees : False by default
returns -> gradie... | This code implements the Canny edge detection algorithm by applying Gaussian blur to reduce noise, Sobel edge detection to compute gradient magnitude and direction, non-max suppression to thin edges, thresholding with hysteresis to identify strong and weak edges, and finally returning the refined edge map. | def canny_detector(image, low, high):
blurred_image = gaussian_blur(image, kernel_size=9)
grad_mag, grad_dir = sobel_edge_detection(blurred_image, convert_to_degree=True)
narrowed = non_max_suppression(grad_mag, grad_dir)
t_image = threshold(narrowed, low, high, weak=50)
return hysteresis(t_image, w... |
def n_FOM1(x,*p):
mu=p[0]
sigma_phi_t = p[1]
n0=1;
return n0*np.exp(-sigma_phi_t*np.exp(-mu*x))
def IDX(e,i,j):
ind = np.searchsorted(self.P,self.idP0(e,i)[j])
return ind
def n_FOM2(x, *p):
f = p[2] # f = Dose rate / D_c*tB
n_i = n_FOM1(x, *p)
return (n_i-1)... | This function computes a weighted combination of different FOM (Feature of Model) functions based on the input parameter 'e'. For e=1 to 5, it selects corresponding n_FOM1-n_FOM5 functions, extracts specific parameters from *q using self.IDX, and returns r + (1-r)*FOM_result. The weight 'r' determines the contribution ... | def function(data,i,e, *q):# not all parameters are used here, r is shared
if e== 1:
return r+(1-r)*n_FOM1(data,*np.array([q[self.IDX(e,i,1)],q[self.IDX(e,i,2)]]))
if e== 2:
return r+(1-r)*n_FOM2(data,*np.array([q[self.IDX(e,i,1)],q[self.IDX(e... |
def n_FOM1_unp(x,*p):
mu=p[0]
sigma_phi_t = p[1]
n0=1;
return n0*unp.exp(-sigma_phi_t*unp.exp(-mu*x))
def IDX(e,i,j):
ind = np.searchsorted(self.P,self.idP0(e,i)[j])
return ind
def n_FOM2_unp(x, *p):
f = p[2] # f = Dose rate / D_c*tB
n_i = n_FOM1_unp(x, *p)
... | This function computes a weighted combination of different FOM functions (n_FOM1 to n_FOM5) based on the parameter 'e'. It dynamically selects parameters from the input tuple 'q' using self.IDX to construct the required argument array for each FOM variant, then returns r + (1-r)*FOM_result, where FOM_result depends on ... | def function_unp(data,i,e, *q):# not all parameters are used here, r is shared
if e== 1:
return r+(1-r)*n_FOM1_unp(data,*np.array([q[self.IDX(e,i,1)],q[self.IDX(e,i,2)]]))
if e== 2:
return r+(1-r)*n_FOM2_unp(data,*np.array([q[self.IDX(e,i,1)],... |
def visual_modulator(guide_image, model_params, scope='osmn', is_training=False):
"""Defines the visual modulator
Args:
guide_image: visual guide image
model_params: parameters related to model structure
scope: scope name for the network
is_training: training or testing
Returns:
Tensor o... | This code tests a model for image segmentation using a pre-trained checkpoint. It processes each frame from the test dataset, computes predictions with the model, and saves binary masks and scores. The model integrates guide, gb, and input images, utilizing a visual modulator if enabled. Results are stored in the speci... | def test(dataset, model_params, checkpoint_file, result_path, batch_size=1, config=None):
tf.logging.set_verbosity(tf.logging.INFO)
assert batch_size == 1, "only allow batch size equal to 1 for testing"
# Input data
guide_image = tf.placeholder(tf.float32, [batch_size, None, None, 3])
gb_image = tf.... |
def upload_handling(request, context):
uploaded_file = request.FILES.get('file')
library_id = request.POST.get('library_id')
new_file = InputTextFile(file = uploaded_file, library_id = library_id)
new_file.save()
request.session.modified = True
f = new_file.file.open('r')
context['form']= Up... | Your return The `main_view` function handles HTTP requests for a web application, managing file uploads, library interactions, and file operations. It populates a context dictionary with session data and form objects, then routes requests: POST with files triggers upload handling, POST with library choices invokes libr... | def main_view(request, file_list = None):
context = {}
context['file_list'] =request.session.get('file_list', '')
print(request.session.get('file_list'))
context['form']= UploadFileForm
context['library'] = {}
if request.method == 'POST' and request.FILES:
return upload_handling(request,... |
def latexHeader(title: str, authors: list[str], date: str=None) -> str:
header: str = "\\documentclass{article}\n\\usepackage{mathtools}\n\\allowdisplaybreaks\n\n"
header += "\\title{" + title + "}\n"
header += "\\author{\n"
for index, author in enumerate(authors):
header += author
head... | The code generates a LaTeX document evaluating points of the Mandelbrot set. It writes a header with title and authors, generates a coordinate plane grid, processes the grid to produce LaTeX content for visualization, and appends a closing LaTeX tag. The output is saved in "mandelbrot.tex" for academic or visual repres... | def _test():
with open("mandelbrot.tex", "w") as file:
file.write(latexHeader("Evaluating Points of the Mandelbrot Set", ["Nair, N.", "Medjamia, Z."]))
coordinates: list[list[complex]] = generatePlane([-1.8, 1.8 + 0.08], [-1.8, 1.8 + 0.08], 0.08)
file.write(showWorkFromCoordinatePlane(coordi... |
def walk_relations(term, pre, post, extra, steps):
url = get_resp(URL_WIKI_SEARCH + term).url
urls = {url}
seen = set()
data = tuple()
new = urls - seen
if not steps:
steps = float("inf")
while new and (steps > 0):
steps -= 1
seen |= urls
print(f"C... | The main task of the code is to process command-line arguments, canonicalize URLs, build a graph of nodes based on pre/post relations, and output the ancestor and descendant hierarchy of a root node, avoiding cycles. It compiles regex patterns, walks through relations, maps canonical URLs, constructs a lookup of nodes,... | def main(args):
for attr in ("pre", "post", "extra"):
x = getattr(args, attr)
if x:
setattr(args, attr, re.compile(x))
root, data = walk_relations(
args.term, args.pre, args.post, args.extra, args.steps
)
canon = dict()
for dct in data:
canon[dct["url"]]... |
def _get_explored_nodes(self, sudoku):
explored = copy.deepcopy(sudoku)
for (i, j), x in np.ndenumerate(explored):
if x == 0:
explored[i, j] = False
else:
explored[i, j] = True
return explored
def _get_constraints(self, sudoku):
con... | The code performs Monte Carlo Tree Search (MCTS) to solve a Sudoku puzzle by exploring possible moves, conducting rollouts to evaluate paths, and selecting the most promising move. It initializes the Sudoku state, determines search order, creates tree nodes, and iteratively expands the tree. If a solution is found duri... | def __call__(self, sudoku_state, n=1500):
"""
Run the monte carlo tree search.
:param n: The number of roll-outs to be performed
:return:
"""
self.sudoku = sudoku_state
self.explored_nodes = self._get_explored_nodes(sudoku_state)
self.constraints = self._... |
def middleGame():
global DEPTH, MIDDLEGAME
# pieceTable = {}
pieceTable["K"] = [
[-50, -40, -30, -20, -20, -30, -40, -50],
[-40, -20, -10, 0, 0, -10, -20, -40],
[-30, -10, 20, 30, 30, 20, -10, -30],
[-30, -10, 30, 30, 30, 30, -10, -30],
[-30, -10, 30, 30, 30, 30, -10,... | This function determines the best chess move using the NegaMax algorithm with alpha-beta pruning. It adjusts search depth based on game phase (endgame/middle game) and piece count, shuffles valid moves, and returns the optimal move after evaluating positions. Depth is reduced if no queens remain, prioritizing efficienc... | def findBestMove(gs, validMoves):
global nextMove, counter, DEPTH
nextMove = None
counter = 0
random.shuffle(validMoves)
pieces = 0
for row in gs.board:
for col in row:
if col != "--":
pieces += 1
if pieces < 15 and not MIDDLEGAME and not ENDGAME:
... |
def cnt_freq(filename):
try:
file=open(filename,'r')
except:
raise(FileNotFoundError)
freqlist=[0]*256
for character in file.read():
ASCII=ord(character)
freqlist[ASCII]+=1
if max(freqlist)==0:
file.close()
return None
file.close()
return (freq... | The code encodes the content of an input file using Huffman coding. It reads character frequencies, constructs a Huffman tree, generates binary codes for each character, and writes the encoded data along with a header containing frequency information to an output file. The process involves creating a header, mapping ch... | def huffman_encode(in_file, out_file):
create_file=open(out_file,'w')
frequency_list=cnt_freq(in_file)
if frequency_list==None:
create_file.close()
return
#HuffmanTree=create_huff_tree(frequency_list)
#code_list=create_code(HuffmanTree)
code_list=create_code(create_huff_tree(freq... |
def player(state):
xs = state.count("X")
os = state.count("O")
if os > xs:
return "O"
return "X"
def actions(state):
a = []
for i in range(len(state)):
if state[i] == "*":
a.append(i)
return a
def result(state, action):
a = list(state)
a[action] = pla... | The function `next_move` determines the optimal next action in a game (like Tic-Tac-Toe) using a minimax algorithm. It evaluates all possible moves, prioritizes immediate winning actions, and selects the move with the best minimax value for the current player, favoring maximizing scores for "X" and minimizing for "O". | def next_move(state):
best_value = None
best_action = None
current_player = player(state)
act = actions(state)
act.sort()
for action in act:
new_state = result(state, action)
new_value = minimax(new_state)
if score(new_state) == (1 if current_player == "X" else -... |
def _init_a(D):
"""Initial guess for Dirichlet alpha parameters given data D
Parameters
----------
D : (N, K) shape array
``N`` is the number of observations, ``K`` is the number of
parameters for the Dirichlet distribution.
Returns
-------
(K,) shape array
Crude gues... | This function estimates Dirichlet distribution parameters via alternating mean/precision maximization. It filters zero-observations, initializes parameters, then iteratively updates mean (a) and precision (s) until log-likelihood changes fall below tolerance, returning the estimated Dirichlet parameters a. | def _meanprecision(D, tol=1e-7, maxiter=None):
"""Mean/precision method for MLE of Dirichlet distribution
Uses alternating estimations of mean and precision.
Parameters
----------
D : (N, K) shape array
``N`` is the number of observations, ``K`` is the number of
parameters for the Di... |
def checkDockerContainerStatus(name):
client = docker.from_env()
container_list=(client.containers())
for con_data in container_list:
if str(con_data['Names']).find(name)==3:
return (con_data['Id'])
return False
def init_json(container_name, container_id):
data={}
data['data... | The main task of the code is to check the status of a Docker container using its name, retrieve its ID if found, and then process/display associated JSON data. It handles errors by catching exceptions, prints container details, and uses functions like `checkDockerContainerStatus`, `init_json`, and `get_json` to manage ... | def main():
try:
container_name = str(sys.argv[1])
container_id = checkDockerContainerStatus(container_name)
if container_id:
pass
else:
msg = "Not found"
print(msg)
... |
def dBP(counts):
"""
Parameters: 1-D array_like, int Vector of counts.
Returns: double
"""
counts = _validate_counts_vector(counts)
return counts.max() / counts.sum()
def dF(counts):
"""
Parameters : 1-D array_like, int Vector of counts.
Returns: double
"""
counts = _validate... | The code calculates seven biodiversity indices (dBP, dF, dKT, dMg, eM, dMn, dSW) from input data by converting it to a numpy array, flattening it, applying each index function, converting results to 32-bit floats, and returning them as a list. | def biodiversity(data):
data = np.array(data)
dBP_index = np.float32(dBP(data.flatten()))
dF_index = np.float32(dF(data.flatten()))
dKT_index = np.float32(dKT(data.flatten()))
dMg_index = np.float32(dMg(data.flatten()))
eM_ndex = np.float32(eM(data.flatten()))
dMn_index = np.float32(dMn((dat... |
def is_airborne():
global stats_before_airborne
if global_situation['g_distance_valid'] and global_situation['g_distance'] >= DISTANCE_START_DETECTED:
stats_before_airborne += 1
if stats_before_airborne >= STATS_FOR_SITUATION_CHANGE:
stats_before_airborne = 0
return True... | This function evaluates flight statistics by tracking drone status transitions (run-up, start, obstacle clearance, landing, stop) using global variables. It detects key events like takeoff, obstacle clearance, landing, and stopping, logs relevant data, and updates flight phases. When a complete flight cycle is detected... | def evaluate_statistics(latest_stat):
global statistics
global fly_status
global runup_situation
global start_situation
global obstacle_up_clear
global landing_situation
global obstacle_down_clear
global stop_situation
if fly_status == 0: # run up
if is_airborne():
... |
def create_train_state(
model_name,
model_cls,
rng,
in_dim=1,
bsz=128,
seq_len=784,
lr=1e-3,
lr_schedule=False,
total_steps=-1,
):
model = model_cls(training=True)
init_rng, dropout_rng = jax.random.split(rng, num=2)
params = model.init(
{"params": init_rng, "drop... | The main task of the code is to train a machine learning model (e.g., S4, DSS, or others) on a specified dataset with configurable hyperparameters like d_model, batch size, and learning rate. It includes data loading, model initialization, training loop with validation, checkpoint saving, and optional logging with Weig... | def example_train(
model,
dataset,
d_model=128,
bsz=128,
epochs=10,
ssm_n=64,
lr=1e-3,
lr_schedule=False,
n_layers=4,
p_dropout=0.2,
suffix=None,
use_wandb=True,
wandb_project="s4",
wandb_entity=None,
):
# Set randomness...
print("[*] Setting Randomness...... |
def filter_undocumented(params):
for param in params:
if not param.undocumented:
yield param
def pname(p):
return getattr(p, 'argument_name', p.display_name)
def _parse_help(self):
self.header, self.footer = self._parse_func_help(self.subject.func)
for wrapper in wrappers(sel... | This code organizes command-line parameters into structured sections (positional, optional, alternate) by filtering undocumented parameters, sorting named parameters alphabetically, and grouping them in an OrderedDict. It prepares data for help display by populating sections and reordering the alternate section to the ... | def prepare(self):
super(ClizeHelp, self).prepare()
s = self.sections = util.OrderedDict((
(LABEL_POS, util.OrderedDict()),
(LABEL_OPT, util.OrderedDict()),
(LABEL_ALT, util.OrderedDict()),
))
self.after = {}
for p in filter_undocumented(se... |
def table_exists(self, table: str):
self.snow_cursor.execute(f"select count(*) from information_schema.tables where table_name ilike '{table}'")
return self.snow_cursor.fetchone()[0] >= 1
def load_table(self, table, schema_file, create_table=True, drop_table=False):
csv_dir = self.parent.csv_dir... | This function merges CSV data into a Snowflake table using a schema file, creating the table if allowed. It checks for existing tables, stages compressed CSV files, and executes MERGE operations to update or insert records based on primary keys, archiving processed files afterward. | def merge_table(self, table:str, schema_file:str, allow_create=False):
if not self.table_exists(table):
if allow_create:
return self.load_table(table, schema_file, create_table=True)
else:
raise RuntimeError(f"Table {table} does not exist in Snowflake")
... |
def table_exists(self, table: str):
self.snow_cursor.execute(f"select count(*) from information_schema.tables where table_name ilike '{table}'")
return self.snow_cursor.fetchone()[0] >= 1
def load_table(self, table, schema_file, create_table=True, drop_table=False):
csv_dir = self.parent.csv_dir... | This function synchronizes data between Snowflake and Clickhouse by checking table existence, validating schema, and performing incremental updates or upserts based on primary keys. It handles schema dumping/loading, ensures single primary key, filters records using max values from Snowflake, and executes upserts or lo... | def update_table(self, table: str, schema_file: str, upsert=False, last_modified: str = None, allow_create=False):
if not self.table_exists(table):
if allow_create:
self.parent.extract(table, {})
return self.load_table(table, schema_file, create_table=True)
... |
def table_exists(self, table: str):
rows = self.client.execute(f"SHOW TABLES LIKE '{table}'")
return len(rows) > 0
def load_table(self, table, schema_file, create_table=True, drop_table=False, csv_dir: str=None):
if csv_dir is None:
csv_dir = self.parent.csv_dir(table)
if not... | This function updates a Clickhouse table by synchronizing it with PostgreSQL data, using either incremental updates (based on primary key/max value) or full reloads. It checks schema validity, creates tables if allowed, and applies filters to extract only new/updated records from PostgreSQL before loading them into Cli... | def update_table(self, table: str, schema_file: str, upsert=False, last_modified: str = None, allow_create=False):
if not self.table_exists(table):
if allow_create:
self.parent.extract(table, {})
return self.load_table(table, schema_file, create_table=True)
... |
def __check__keydown__events(self,event):
#respond to keypresses.
if event.key == pygame.K_RIGHT:
# Move the ship to the right.
self.ship.moving_right = True
elif event.key == pygame.K_LEFT:
self.ship.moving_left = True
elif event.key==pygame.K_q:
... | This method processes Pygame events: exits on quit, handles key presses/releases by calling private methods, and checks mouse clicks to detect a play button interaction. It centralizes event handling for game input and user interface interactions. | def __check__events(self):
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__eve... |
def __check__events(self):
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__eve... | The code runs a game loop that continuously checks for events, updates game elements (ship, bullets, aliens) if the game is active, and renders the screen to maintain gameplay and user interaction. | def run_game(self):
while True:
self.__check__events()
if self.stats.game_active:
self.ship.update()
self._update_bullets()
self._update_aliens()
self.__update__screen() |
def plot_canvas(self):
self.ax.clear()
self.ax.set_xlabel('Step Nr.')
self.ax.set_ylabel('Quality')
self.fig.tight_layout()
self.myCanvas.draw()
self.master.update()
return
def get_cam_exposure(self,cam_server_adress):
client = socket.socket(socke... | This function optimizes signal parameters (hexy, hexz, wangle, vangle) within specified ranges using a maximization algorithm. It adjusts camera exposures, performs optimization, updates GUI elements with results, and plots the optimal signal value on a graph. The process includes retrieving user inputs, executing opti... | def search_for_signal(self):
self.draw_counts = 0
self.plot_canvas()
#get measurement range from gui
self.var.set('Messages: optimising')
self.findsignalupdatemessage.set('In progress')
self.master.update()
r_hexy = float(self.e_hexy.get())
r_hex... |
def noeudRecherche(self,node,n):
return self.recherche(node,n)[1]
def complet(self,node):
if node.size==self.U:
return True
else:
return False
def scinder(self,node):
m = (node.size-1)//2
if node.leaf:
node.parent.ad... | This code inserts a value into a node of a tree structure, splitting nodes when full to maintain balance. It checks if the target node has space; if not, it splits the node into two, redistributing values and children. Recursive splitting propagates upward if parents are also full, ensuring the tree remains balanced by... | def insertion(self,node,n):
"""
insert a value n in the node
param node:(Noeud) the node
param n: (int) the value to insert
return:None
"""
debut=self.noeudRecherche(node,n)
if not self.complet(debut):
debut.add(n)
... |
def init_source_files(parent):
global id_file
for file_name in os.listdir(parent):
if file_name.endswith(".txt"):
source_files[id_file] = "".join((parent, "/", file_name))
id_file += 1
else:
current_path = "".join((parent, "/", file_name... | The code initializes metadata by setting up source files, reading their contents, and preparing the data for search functionality. | def init_meta_data():
init_source_files("data/technology_texts")
read_from_files()
init_data_for_search() |
def maxmin_time_cost(
rmeasurement: RemoteMeasurement,
) -> Tuple[_MaxTimeCost, _MinTimeCost]:
max_cost_d, min_cost_d = maxmin_time_cost_data(rmeasurement)
return max_cost_d.time_cost, min_cost_d.time_cost
def the_most_happened_error_type(rmeas: RemoteMeasurement) -> Optional[Tuple[str, int]]:
countings... | The function `capture_measurement` processes a `RemoteMeasurement` to generate a `MeasurementSnapshot` containing key metrics: time range, response/success rates, average/max/min time costs, and the most frequent error type with its occurrence rate. It aggregates these values for analysis or reporting. | def capture_measurement(rmeas: RemoteMeasurement) -> MeasurementSnapshot:
max_time_cost, min_time_cost = maxmin_time_cost(rmeas)
the_most_happened_error_result = the_most_happened_error_type(rmeas)
if the_most_happened_error_result:
the_most_happened_error: Optional[str] = the_most_happened_error_re... |
def preprocess_chessresults_html(html):
"""Preprocessing needed for broken HTML tags on chess-results site"""
html = html.replace(b'<div class="FarbewT"/></div>', b'<div class="FarbewT"></div>')
html = html.replace(b'<div class="FarbesT"/></div>', b'<div class="FarbesT"></div>')
return html
def parse_te... | The main task of the code is to parse chess tournament data from URLs or local files, extracting event details and player information. It handles different sources like chess-results.com (HTML/Excel) and 4NCL results, processing data via BeautifulSoup or openpyxl, identifying team/individual players, merging round resu... | def parse(source, rounds=None):
url = source
if not url.startswith("http"):
# local file. Only for CR individual result right now
with open(url, "rb") as f:
data = f.read()
data = preprocess_chessresults_html(data)
soup = bs4.BeautifulSoup(data, 'html.parser'... |
def load_config(config_file):
if not os.path.exists(config_file):
print(f"Config file {config_file} does not exist")
exit(1)
with open(config_file) as f:
config = f.read()
return config
def get_bearer_token(appd_controller_url, appd_client_id, appd_client_secret):
appd_account = ... | The script configures AppDynamics agents (Java/.NET) by adding/removing them for specified applications. It parses command-line arguments, loads credentials from a config file, authenticates via a bearer token, and updates application settings on the AppDynamics controller. It supports bulk operations for "ALL" applica... | def main():
parser = argparse.ArgumentParser(description="AppDynamics Configuration Script")
parser.add_argument("-a", "--application", required=True, help="Application Name|ALL|file containing application names")
parser.add_argument("-c", "--config", default="appdynamics-configuration.sh", help="Config fil... |
def isSorted(matrix, numtubes):
for i in range(numtubes):
if isHomogenous(matrix, i):
continue
elif isEmpty(matrix, i):
continue
else: return False
return True
def allPossyMoves(matrix:List[List[int]], numtubes):
possibleMoves =[]
topBalls =[]
for i in... | This code implements Uniform Cost Search (UCS) to find the minimum-cost path to sort a state, starting from a given initial state. It maintains a frontier of unexplored states, selects the lowest-cost state, expands it to generate new states, and avoids revisiting states by checking against a closed list. The algorithm... | def ucsForSolver(startState: State, tubenum):
closed, frontier = [], []
frontier.append(startState)
currentState = startState
expandthNum = 1
#goal test
if isSorted(currentState.state, tubenum):
return currentState
while frontier:
leastCost= frontier[0]
fo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.