dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def get_n_bodies(s):
return s.shape[-1] // 7
def xpp(s, i, G=G):
num_bodies = get_n_bodies(s)
other_indices = list(range(num_bodies))
other_indices.remove(i)
return G * sum([x_accel(s, i, j) for j in other_indices])
def ypp(s, i, G=G):
num_bodies = get_n_bodies(s)
other_indices = list(range(... | The function `F` constructs a concatenated array by combining segments of the input array `s` and computed accelerations for each body in a gravitational system. It zeros out a specific segment of `s`, appends position and velocity data, then adds acceleration components calculated by `xpp`, `ypp`, and `zpp` functions,... | def F(s, t, G=G):
num_bodies = get_n_bodies(s)
return np.concatenate(
(
np.zeros_like(s[4 * num_bodies : 5 * num_bodies]),
s[4 * num_bodies : 5 * num_bodies],
s[5 * num_bodies : 6 * num_bodies],
s[6 * num_bodies : 7 * num_bodies],
[xpp(s, i, G=... |
def updateMovieList(file_name):
try:
query_movies = readWriteFile.readFile(file_name)
new_query_movies = queryMovies()
new_titles = []
titles_list = []
for movie in new_query_movies:
titles_list.append(movie['title'])
for movie in ... | The main task of the code is to update multiple lists (movie, ID, rating/votes) from a specified file, sort the updated data, and print a completion message. The function calls four sub-functions to handle specific updates, then sorts the final list and confirms the process is done. | def uptadeTilesList(file_name):
updateMovieList(file_name)
updateIDList(file_name)
updateRatingVotesList(file_name)
sortList(file_name)
print('-'*100)
print("Completed Process") |
def nameFunction(self):
#pprint(self.definition)
schema=self.definition['schema']
# parameters = ['{} {}'.format(param,self.definition['parameters'][param]) for param in self.definition['parameters']]
name = self.definition['name']
name = '{}({})'.format(name, ','.join(self.getPa... | This code initializes a Postgres API script generator by converting an API definition into a function. It sets up parameters, validates inputs, assembles data logic, creates the function structure, switches to the required role, and grants privileges. The main task is to transform a given API definition into a structur... | def __init__(self, method, apiDefinition):
# convert to Postgres API Script
# definition is a single function definition
self.method = method
self.definition = apiDefinition
#self.parameterList = ['{} {}'.format(param,self.definition['parameters'][param]) for param in self.defini... |
def create_client_resource (service, type):
"""
Description:
Returns AWS client or AWS resource
Arguments:
Service: str, service that you want to use
Type: str, client or resource
Return:
Client or Resource:
client to provide low level AWS service access o... | This code provisions an AWS Redshift cluster by creating IAM clients, an IAM role with attached policies, configuring the Redshift cluster, waiting for its availability, documenting the endpoint and ARN, and opening TCP access via EC2. The main task is to securely set up and configure a Redshift cluster with proper IAM... | def main():
print("Create clients for IAM, EC2, and Redshift")
ec2 = create_client_resource('ec2', 'resource')
iam = create_client_resource('iam', 'client')
redshift = create_client_resource('redshift', 'client')
print("Create IAM role")
create_iam_role(iam)
print("Attach policy ... |
def access_token_is_valid(self):
if self.AUTH_COOKIE_NAME not in flask.request.cookies:
return False
access_token = flask.request.cookies[self.AUTH_COOKIE_NAME]
try:
self._signer.unsign(
access_token,
max_age=self.config['permissions_cach... | The main task of the code is to add an access token cookie to a Flask response if it lacks a valid one, ensuring authentication remains "sticky" for subsequent requests. It converts string responses to Flask Response objects, generates a signed token when needed, and sets cookies for username and user data if available... | def add_access_token_to_response(self, response):
"""
Add an access token cookie to a response if it doesn't
already have a valid one. (To be called if auth succeeds to make
auth "sticky" for other requests.)
:param (flask.Response|str|unicode) response
:rtype: (flask.Re... |
def output_blob(self, content: bytes):
"""
Output a blob object
Parameters:
content: The content of the blob, as bytes
"""
self.output.write(b"blob\n")
blob_ref = self.write_next_mark()
self.output_data(content)
return blob_ref
def write_s... | This function converts a wiki revision into a git commit, handling different edit types (page update, rename, delete, attachment) by generating appropriate commit messages and modifying the git repository's state with the corresponding changes (add, modify, delete entries). It uses the revision's metadata to set author... | def add_wiki_revision(
self,
revision: MoinEditEntry,
content: bytes,
):
"""
Add a wiki revision as a git commit
Parameters:
revision: A wiki revision object
content: The content of the wiki object, after translation, as bytes
""... |
def get_M(self,ctrl,tgt,drive_frequency,pulse_shape,t,args = None):
'''
Generates propagator in the computational subspace by
evolving vectors only in the computational subspace.
Arguments
---------
ctrl, tgt: int
Indices of ... | This method calibrates a CNOT gate by measuring the target qubit's rotation angles for varying drive strengths (E_list) and pulse lengths (t_list). It computes the propagator matrix for each parameter combination, extracts rotation angles using optimization or analytical methods, and returns dictionaries (phi0, phi1) m... | def calibrate_cnot_phi(self,ctrl,tgt,drive_frequency,pulse_shape,args,E_key = 'Emax',t_key = 'tp',E_list = np.arange(3,90,3),t_list = np.arange(50,150,25), use_optimizer = True, use_zero_initial_values = False):
'''
Method to extract angle of rotation of target for varying drive strengths a pulse le... |
def get_M(self,ctrl,tgt,drive_frequency,pulse_shape,t,args = None):
'''
Generates propagator in the computational subspace by
evolving vectors only in the computational subspace.
Arguments
---------
ctrl, tgt: int
Indices of ... | This method calibrates the X rotation gate by determining the rotation angle (phi) for varying drive strengths (E_list) and pulse lengths (t_list). It iterates over these parameters, computes the propagator matrix for each combination, and extracts phi using either optimization or analytical methods. The result is a di... | def calibrate_X_phi(self,tgt,drive_frequency,pulse_shape,args,E_key = 'Emax',t_key = 'tp',E_list = np.arange(3,90,3),t_list = np.arange(50,150,25), use_optimizer = True, use_zero_initial_values = False):
'''
Method to extract angle of rotation of target for varying drive strengths a pulse lengths.
... |
def get_M(self,ctrl,tgt,drive_frequency,pulse_shape,t,args = None):
'''
Generates propagator in the computational subspace by
evolving vectors only in the computational subspace.
Arguments
---------
ctrl, tgt: int
Indices of ... | This function calculates the fidelity of an X rotation gate on a specified target qubit using an analytical method. It computes the interaction matrix M based on drive frequency, pulse shape, and time array, derives the ideal X gate matrix U_X, and evaluates fidelity via get_f_np. Parameters include target qubit index,... | def get_F_X(self,tgt,drive_frequency, pulse_shape, t, args = None):
'''
Finds the X Rotation Gate Fidelity on a specific target qubit,
for a given drive frequency and pulse
Uses the Analytical Method
Arguments
---------
ctr... |
def get_M(self,ctrl,tgt,drive_frequency,pulse_shape,t,args = None):
'''
Generates propagator in the computational subspace by
evolving vectors only in the computational subspace.
Arguments
---------
ctrl, tgt: int
Indices of ... | The function `get_F` calculates the fidelity of a controlled gate (CR gate) between a control and target qubit. It uses a propagator matrix $ M $ derived from the drive frequency, pulse shape, and time array. Depending on `use_optimizer`, it either optimizes or analytically determines the closest unitary $ U_{CR} $ to ... | def get_F(self,ctrl,tgt,drive_frequency, pulse_shape, t, args = None, use_optimizer = True, use_zero_initial_values = False):
'''
Finds the CR Gate Fidelity between a specified control and target,
for a given drive frequency and pulse
Arguments
------... |
def get_U_CR_optimizer(self,M, use_zero_initial_values = False):
'''
Function to create the closest matrix in the CR family to the propagator
Arguments
---------
M: Qobj
Propagator of the gate, projected into the computational ... | The function calculates the error budget for a CR gate in a computational subspace by decomposing total error into components: conditional phase (E_CP), target rotation (E_T), control rotation (E_C), spectator rotations (E_specs), and leakage (E_leak). It compares the input propagator M against optimized or analyticall... | def get_new_error_budget(self,M, use_optimizer = True, use_zero_initial_values = False):
'''
Function to get error budget of a given propagator in the computational subspace, as per new definitions
For the CR Gate
Arguments
---------
M: Qobj
... |
def get_U_RX_optimizer(self,M, use_zero_initial_values = False):
'''
Function to create the closest matrix in the RX family to the propagator
Arguments
---------
M: Qobj
Propagator of the gate, projected into the computational ... | This function calculates the error budget for an RX quantum gate by decomposing the fidelity of a given unitary propagator into distinct error components: conditional phase error (E_CP), target rotation error (E_T), spectator rotation errors (E_specs), and leakage errors (E_leak). It compares the input propagator again... | def get_new_error_budget_RX(self,M, use_optimizer = True, use_zero_initial_values = False):
'''
Function to get error budget of a given propagator in the computational subspace, as per new definitions
For the RX Gate
Arguments
---------
M: Qobj
... |
def H_diag(dim, w1, w2, del1, del2, g12):
u_op = U(dim, w1, w2, del1, del2, g12)
u_op_dag = np.asmatrix(u_op).getH()
matrix1 = np.matmul(u_op_dag, red_h(dim, w1, w2, del1, del2, g12))
dressed_ham = np.matmul(matrix1, u_op)
return dressed_ham
def HA(dim, wd):
a1 = qt.tensor(qt.destroy(dim), qt.qe... | The code computes a total Hamiltonian matrix by combining diagonal terms, a static term, and a driven term, then applies a basis permutation to rearrange specific states (swapping indices 3 and 4) in the Hilbert space, returning the transformed matrix. | def tot_H_rwa(dim, w1, w2, del1, del2, g12, amp1, phase1, amp2, phase2, wd):
H_tot = (H_diag(dim, w1, w2, del1, del2, g12) - HA(dim, wd)
+ drive_rwa(dim, w1, w2, del1, del2, g12, amp1, phase1, amp2, phase2))
#change of order in the basis in the form (00, 01, 10, 11, rest)
d_hs = binomial(dim + no_of_qu... |
def is_goal(current, goal):
dt = dist((current.x, current.y), (goal.x, goal.y))
if dt < 0.25:
return True
else:
return False
def action_model(rpm1, rpm2):
actions = [[rpm1, 0], [0, rpm1], [rpm1, rpm1], [0, rpm2], [rpm2, 0], [rpm2, rpm2], [rpm1, rpm2], [rpm2, rpm1]]
return actions
d... | The code implements the A* algorithm to find a path from a start node to a goal node in a robot navigation problem. It uses a priority queue to explore nodes, generates valid moves based on RPMs and clearance, calculates costs, and updates node states. The algorithm checks for goal reachability, manages open/closed nod... | def Astar_algorithm(start_node, goal_node,RPM1,RPM2,r,clearance):
if is_goal(start_node, goal_node):
return 1,None,None
N_list = []
S_list = []
open_nodes = {}
open_nodes[(start_node.x * 2000 + start_node.y)] = start_node
closed_nodes = {}
theta_threshold = 15
open_nodes_list =... |
def fetch_articles(api_key, keyword, from_date, to_date, page_size):
print(f"Fetching articles for '{keyword}' from {from_date} to {to_date}...")
base_url = "https://content.guardianapis.com/search"
params = {
'api-key': api_key,
'q': keyword,
'page-size': page_size,
'show-fi... | The main task of the code is to fetch news articles via an API using user-specified keywords and dates, then analyze their content with TF-IDF and LDA to extract keywords/topics. It aggregates sentiment rankings, visualizes results interactively, and allows users to repeatedly search or exit. The program handles input ... | def main():
api_key = '2ce72283-ccba-4b1a-92da-2f702366b61c'
while True:
print("\nOptions:")
print("1: Start searching")
print("2: Exit Program")
choice = input("Enter your choice: ")
if choice == '1':
keyword = input("Enter the keyword to search for: ")
... |
def test_exists(self):
self.checked=check_db('phonebook.db')
if self.checked:
return True
else:
return False
def test_getdb(self):
self.test_exists()
if self.checked:
connected=getdb('phonebook.db')
if connected:
sel... | The code defines a method `runtests` that executes and prints the results of four test methods: `test_exists`, `test_getdb`, `test_databaseEmpty`, and `test_tablesEmpty`. Its main task is to run a series of tests, likely validating database-related functionalities such as existence checks, database retrieval, and empti... | def runtests(self):
print(self.test_exists())
print(self.test_getdb())
print(self.test_databaseEmpty())
print(self.test_tablesEmpty()) |
def phi_1(R, p):
cnf = []
for k in range(1, p+1):
for i in range(len(R[k])):
for j in range(i+1, len(R[k])):
cnf.append([-1 * h(R[k][i][0], R[k][i][1]), h(R[k][j][0], R[k][j][1])])
cnf.append([h(R[k][i][0], R[k][i][1]), -1 * h(R[k][j][0], R[k][j][1])])
# ... | The code solves a constraint satisfaction problem using a SAT solver (Glucose3). It processes input matrices (CG, CC, CR) to model constraints, constructs clauses via helper functions (phi_1, phi_2, phi_3), and checks feasibility. If constraints are violated (e.g., CR[i] > N, CC[j] > M), it returns an error. Otherwise,... | def solve(M, N, CG, CC, CR):
# print(CG)
global m
global n
m = M
n = N
MaxT = 0
for i in range(len(CG)):
MaxT = max(MaxT, max(CG[i]))
R = [[] for _ in range(MaxT+1)]
for i in range(M):
for j in range(N):
R[CG[i][j]].append((i, j))
for i in range(M)... |
def get_random_height(self, num_samples):
return 2 *np.log2(num_samples)+0.8327
def _recursive_build(self, data, depth_limit, lof=0, hash_func_index=0):
n_samples = len(data)
center = np.sum(data, axis=0) / n_samples
if n_samples == 0:
return None
if n_samples == 1 or... | The code builds a data structure using Locality-Sensitive Hashing (LSH). It initializes parameters like sample count and depth limit, formats input data, recursively constructs a tree-like structure with a root node, and computes average branch factor and path length metrics for efficient similarity search or retrieval... | def build(self, data):
self._n_samples = len(data)
self._depth_limit = self.get_random_height(self._n_samples)
data = np.array(data)
data = self._lsh.format_for_lsh(data)
self._root = self._recursive_build(data, self._depth_limit)
self._branch_factor = self._get_avg_branc... |
def compare_filesize(session, file_path, data_object_path):
"""
Compare the size of a local file and a file in iRODS
The function returns True in case both sizes match.
It returns False in case the sizes don't match,
or the data object doesn't exist
Arguments
---------
session: obj
... | This function synchronizes a local directory to an iRODS system, recursively uploading files and subdirectories. It checks if existing files in iRODS need updating using size or checksum verification. It tracks succeeded, skipped, and failed files, along with total uploaded data size, returning a summary dictionary. | def sync_directory(
session, source, destination, verification_method="size", post_check=False
):
"""
Synchronize a directory to iRODS
Arguments
---------
session: obj
An iRODSSession object
source: str
The path of a local directory.
Please provide a full path
... |
def memory_evaluate(self):
self.screen = self.screen.replace("M", self.memory)
self.evaluate()
def evaluate(self):
try:
self.screen = str(eval(self.screen))
self.memory = self.screen
self.update_memory()
except:
self.screen = "Syntax ERROR... | This method handles input addition to a calculator's screen, evaluating expressions, managing memory functions, and updating the display based on the input value and current screen state. | def __iadd__(self, value):
if self.screen == "Syntax ERROR":
self.screen = value
elif any(memory_functions in self.screen for memory_functions in ("M-", "M+")) and value == "=":
self.memory_evaluate()
elif value == "=":
self.evaluate()
elif value in se... |
def get_infinite_batches(data_loader):
while True:
for i, (images) in enumerate(data_loader):
yield images
def D_train_step(self, data_batch, d_num, back, print_bo):
self.G.eval()
for _k in range(d_num):
self.D_forward[_k].train()
self.D_backward[_k].trai... | The code trains a GAN (Generative Adversarial Network) with multiple discriminators and generators. It initializes parameters, sets up data loaders, and alternates between updating discriminators (via `D_train_step`) and generators (via `G_train_step`). It tracks losses, normalizes multipliers, saves checkpoints period... | def train(self, train_loader):
self.t_begin = t.time()
iterator = []
for i in range(len(train_loader)):
iterator.append(get_infinite_batches(train_loader[i]))
one = torch.tensor(1, dtype=torch.float)
mone = one * -1
if self.cuda:
one = one.cuda(se... |
def get_all_at_depth(self):
gene_per_depth = set()
for pair, depth in self.distance_pairs:
gene_a, gene_b = pair
gene_per_depth.update({(gene_a, depth), (gene_b, depth)})
return list(gene_per_depth)
def _get_neighbours_at_depth(self, gene_index, n, visited):
gene_... | This function retrieves neighbors for each gene at specified depths from a graph, saving results as CSV files in the given output folder. It iterates through gene-depth pairs, fetches neighbors using _get_neighbours_at_depth, maps gene indices to string IDs, and writes formatted neighbor data to depth-specific CSV file... | def get_all_neighbours_at_depth(self, output_folder):
gene_and_depth = self.get_all_at_depth()
i = 0
for gene_index, depth in gene_and_depth:
print(f"{i} of {len(gene_and_depth)}")
print(f"getting enpoints for {gene_index} at depth {depth}")
neighbours = self.... |
def input_digit():
answer = input(">>> ")
# Check if answer is a number
try:
answer = int(answer)
return answer
except ValueError:
print("[+] Invalid input. Please enter a number.")
return input_digit()
def all_records():
cursor.execute("SELECT * FROM students")
result = cursor.fetchall()
... | The main task of the code is to provide a menu-driven system for managing records (CRUD operations) after a successful login. It allows users to view all records, add new entries, delete, update, or view specific records by roll number, with input validation and an exit option. The loop continues until the user selects... | def main():
if LOGIN:
# print("\033c")
print("\n[+] Logged in successfully.")
print("[+] Please select an option:")
print("(1) View all records")
print("(2) Add a new record")
print("(3) Delete a record")
print("(4) Update a record")
print("(5) View a record")
print("(6) Exit\n")
... |
def minmax(player_turn, wolf_pos, sheep_pos, d):
'''
Explores game tree
:param player_turn: 'w' or 's'
:param wolf_pos: V(x, y)
:param sheep_pos: [V(x1, y1), V(x2, y2), ...]
:param d: search depth
:return new state:
'''
randomness = 0.1
# if state is terminal (end of recursion)
... | The code simulates a turn-based game between a wolf and sheep using a min-max algorithm with depth `d`. It tracks game states in `history`, alternating turns. The wolf wins by reaching row 8 or blocking sheep; sheep win by blocking the wolf. The function returns the sequence of game states until a win condition is met. | def play_game(wolf_pos, d):
'''
:param wolf_pos: wolf starting position
:param d: search depth for min-max algorithm
:return moves_history: history of game states
'''
global origin_d
origin_d = d
turns = ['w', 's']
player_turn = 'w'
move = 0 # moves counter
sheep_pos = [V(... |
def subsample(dataset, ratio):
"""
Creates a random subsample from the dataset with replacement
:param dataset:
:param ratio:
:return:
"""
sample = list()
n_sample = round(len(dataset) * ratio)
while len(sample) < n_sample:
index = randrange(len(dataset))
sample.appen... | The code implements a Random Forest algorithm by creating multiple decision trees using subsampled training data. Each tree is built with specified depth, minimum size, and feature selection parameters. Predictions are aggregated via bagging (averaging) across all trees to improve accuracy and reduce overfitting. | def random_forest(train, test, max_depth, min_size, sample_size, n_trees, n_features):
"""
Performs Random Forest Algorithm
:param train: train dataset
:param test: test dataset
:param max_depth:
:param min_size:
:param sample_size:
:param n_trees:
:param n_features:
:return: pre... |
def computer_level_easy(game):
# computer randomly choose the (col,pop)
cpu_level_easy_col = randint(0, game.cols - 1)
cpu_level_easy_pop = bool(randint(0, 1))
# check validity of the move generated
while not check_move(game, cpu_level_easy_col, cpu_level_easy_pop):
cpu_level_easy_col = rand... | The function `computer_move` determines the computer's strategy in a game based on the specified difficulty level. It selects between three predefined strategies (`computer_level_easy`, `computer_level_medium`, or `computer_level_difficult`) and returns a tuple `(col, pop)` representing the column and pop action for th... | def computer_move(game, level):
if level == 1:
(col, pop) = computer_level_easy(game)
if level == 2:
(col, pop) = computer_level_medium(game)
if level == 3:
(col, pop) = computer_level_difficult(game)
return (col, pop) |
def computer_level_easy(game):
cpu_level_easy_col = randint(0, game.cols - 1)
cpu_level_easy_pop = randint(0, 1)
try_to_think()
while not check_move(game, cpu_level_easy_col, cpu_level_easy_pop):
cpu_level_easy_col = randint(0, game.cols - 1)
cpu_level_easy_pop = randint(0, 1)
apply_... | The function `computer_move` determines the computer's strategy in a game based on the specified difficulty level. It delegates the move selection to level-specific functions: `computer_level_easy`, `computer_level_medium`, or `computer_level_difficult`, each implementing distinct logic for generating the computer's ne... | def computer_move(game,level):
if level==1:
computer_level_easy(game)
if level==2:
computer_level_medium(game)
if level==3:
computer_level_difficult(game) |
def computer_level_easy(game):
cpu_level_easy_col = randint(0, game.cols - 1)
cpu_level_easy_pop = randint(0, 1)
while not check_move(game, cpu_level_easy_col, cpu_level_easy_pop):
cpu_level_easy_col = randint(0, game.cols - 1)
cpu_level_easy_pop = randint(0, 1)
return (cpu_level_easy_co... | The function `computer_move` determines the computer's move in a game based on the specified difficulty level. It delegates the decision to level-specific functions (`computer_level_easy`, `computer_level_medium`, or `computer_level_difficult`) depending on the input `level` parameter. These functions calculate the opt... | def computer_move(game,level):
#ask for the computer to make a move for a certain game
#level represents the level of the computer opponent
if level==1:
(col,pop)=computer_level_easy(game)
if level==2:
(col,pop)=computer_level_medium(game)
if level==3:
(col,pop)=computer_leve... |
def add_mode():
mode = input('PvP or PvC?: Please enter 1 for PvP mode, 2 for PvC mode')
if mode == '1':
mode = 0
elif mode == '2':
print('Which difficulty level do you choose?(easy:1,medium:2,difficult:3):')
mode = int(input())
if mode < 1 or mode > 3:
print('Inv... | The code's main task is to configure a game by obtaining and validating user inputs for rows, columns, and win conditions, then initializing the game state with a randomly assigned turn. It alternates between human and computer moves (based on mode), updates the game board, and checks for a win after each move until th... | def menu():
game = Game()
game.rows = input("How many rows?")
while not (game.rows.isdigit() == True and int(game.rows) >= 3):
# In addition to obtaining integers, this checking also requires a value not less than 3 to ensure the game is normally played.
print('Your input value is invalid! P... |
def add_mode():
mode = input('PvP or PvC?: Please enter 1 for PvP mode, 2 for PvC mode')
if mode == '1':
mode = 0
elif mode == '2':
print('Which difficulty level do you choose?(easy:1,medium:2,difficult:3):')
mode = int(input())
if mode<1 or mode >3:
print('Invali... | The main task of the code is to handle user input validation for game parameters (rows, columns, wins), initialize a game board, and start a turn-based game loop that alternates between human and computer moves, checking for a win condition after each move. | def menu():
game = Game()
game.rows = input("How many rows?")
while not (game.rows.isdigit()==True and int(game.rows)>=3):
print('Your input value is invalid! Please enter again')
game.rows = input()
else: game.rows=int(game.rows)
game.cols = input("How many columns?:")
while not... |
def add_mode():
mode = input('PvP or PvC?: Please enter 1 for PvP mode, 2 for PvC mode')
if mode == '1':
mode = 0
elif mode == '2':
print('Which difficulty level do you choose?(easy:1,medium:2,difficult:3):')
mode = int(input())
if mode<1 or mode >3:
print('Invali... | The code initializes a game by prompting the user to input valid integers for rows, columns, and win conditions, ensuring values meet minimum thresholds. It sets up the game board, randomly assigns the starting player, and enters a loop where players or the computer take turns making moves until a win condition is met,... | def menu():
game = Game()
game.rows = input("How many rows?")
while not (game.rows.isdigit()==True and int(game.rows)>=3):
# In addition to obtaining integers, this checking also requires a value not less than 3 to ensure the game is normally played.
print('Your input value is invalid! Please en... |
def check_ref_type(self, ref, allowed_types):
"""
Validates the object type of ref against the list of allowed types. If it passes, this
returns True, otherwise False.
Really, all this does is verify that at least one of the strings in allowed_types is
a substring of the ref obje... | This function retrieves FASTA sequence data from either a genome or assembly reference. It checks the input type and delegates to the appropriate method: `fetch_fasta_from_genome` for KBaseGenomes.Genome references, or `fetch_fasta_from_assembly` otherwise. The primary task is to fetch nucleotide sequences in FASTA for... | def fetch_fasta_from_genome_or_assembly (self, genome_or_assembly_ref):
"""
Fetches fasta from an assembly or genome
"""
if self.check_ref_type(genome_or_assembly_ref, ['KBaseGenomes.Genome']):
return (self.fetch_fasta_from_genome(genome_or_assembly_ref))
else:
... |
def can_make_trip(
self, start_position: Position, packages: List[Package], charge: float
) -> bool:
total_trip_distance = get_total_trip_distance(
start_position=start_position, packages=packages
)
active = total_trip_distance * self.active_battery_consume
numbe... | The main task of the code is to deliver the next package to a customer by moving towards their location, managing battery swaps if needed, updating delivery statuses, and removing serviced customers from the list. If no packages remain, the drone returns to the home truck. | def deliver_next_package(self, unserviced_customers: List[Customer]):
"""
Move towards the next customer in our list.
If we have no more customers to deliver to we go_to_home_truck()
"""
# Here we check if the drone is active. If so, we add 1 second to its active time
# A... |
def select_any_package_for_customer(
self, customer: Customer, packages: List[Package]
) -> Optional[Package]:
for package in packages:
if package.customer == customer:
return package
return None
def get_euclidean_distance(position1: Position, position2: Position)... | The function selects the next package for a drone to deliver, prioritizing remaining packages from the same customer if available. If not, it sorts packages by proximity to the last customer's location. Using the "mpa" strategy, it avoids disrupting optimal delivery by skipping certain packages, otherwise selecting the... | def get_next_package(
self,
last_assigned_package: Package,
packages: List[Package],
strategy: str,
drone: Drone,
) -> Package:
# If we have just loaded a customer's package and that same customer still has more packages then we will load them...
any_customer... |
def load_initial_package(self, drone: Drone, strategy: Strategy):
package: Package = self.select_initial_package(strategy=strategy)
if package is None:
raise ValueError("Initial package is None")
if not drone.can_make_trip(
start_position=self.position, packages=[package... | This function assigns packages to a drone based on a specified strategy, ensuring the drone's capacity isn't exceeded. It starts by loading an initial package, then iteratively adds packages from the current cluster if the drone can complete the trip with them. Packages are removed from the cluster and added to the dro... | def load_drone_package(self, drone: Drone):
"""
In this function we assign packages to a drone according the strategy we have specified in self.strategy.
"""
# The only thing different between the strategies is how we assign the initial drone. everything else is the same.
if len... |
def create_checker_board_layout(self):
self.checker_board_layout = QGridLayout()
self.checker_board_layout.setSpacing(0)
self.checker_board_layout.setAlignment(Qt.AlignLeft | Qt.AlignTop)
self.buttons = np.zeros_like(BACKGROUND, dtype="O")
n_rows, n_cols = BACKGROUND.shape
... | This code initializes a chess game GUI, setting up the window, player vs computer logic, board layout, captured pieces display, and history tracking. It configures UI elements, assigns colors, creates game instances, and arranges components using Qt layouts for a functional chess interface with optional computer oppone... | def __init__(self, play_against_computer: bool):
"""View initializer."""
super().__init__()
# Set some main window's properties
self.setWindowTitle("Chess")
self.setWindowIcon(QIcon("static/img/chess_pieces/black_knight.png"))
self.play_against_computer = play_against_c... |
def select_piece(self, piece: Piece):
self.selected_piece = piece
self.valid_moves = [
coords_to_np_coords(move.get_new_coords(piece.coords))
for move in piece.get_valid_moves(self.game.board)
]
def select_move(self, i, j):
if (i, j) in self.valid_moves:
... | This method handles cell selection in a game, selecting pieces if they match the current player's turn, managing piece deselection, validating moves, updating the UI, and displaying end-game messages if the game is finished. | def select_cell(self, i, j):
loc = coords_to_loc(np_coords_to_coords(i, j))
piece = self.game.board.get_piece(loc)
if piece and piece.color == self.game.turn:
self.select_piece(piece)
elif self.selected_piece is not None:
(ip, jp) = coords_to_np_coords(self.s... |
def _get_selected_value():
for o in range(5):
for s in range(18):
if "selected" in state.board[o][s]:
return state.board[o][s]
def _drop(orbit, sector, fall):
of = orbit - fall
if of >= 0:
final = state.board[of][sector]
if "#" in final:
_drop(of, sector, 1)
state.board[of][sector] = state.board[or... | This function processes different hit types by determining the object type and triggering corresponding drop actions. If the type is "flag", it drops 3 items at the given orbit/sector. For "bomber", it sequentially drops 1 item per orbit level downward. "Sweeper" uses a dedicated handler, while "fighter" drops 1 item. ... | def _process_hit(orbit, sector):
type = _get_selected_value().split()[0].split("#")[1]
if type == "flag":
_drop(orbit, sector, 3)
elif type == "bomber":
for i in range(orbit + 1):
_drop(orbit - i, sector, 1)
elif type == "sweeper":
_process_sweeper_hit(orbit, sector)
elif type == "fighter":
_drop(orbi... |
def _move_selected_to(orbit, sector):
type = ""
oi = -1
si = -1
for o in range(5):
for s in range(18):
if "selected" in state.board[o][s]:
type = state.board[o][s].split()[0].split("#")[1]
oi = o
si = s
break
state.board[orbit][sector] = state.board[oi][si]
state.board[oi][si] = "start"
... | This function processes attack actions in a game based on the state of the specified board position. It handles "start" attacks by moving selected pieces and resetting markers, processes "canHit" attacks to execute hits and switch turns, skips to the next turn for "selected" states, and displays an error for invalid at... | def _process_attack(orbit, sector):
attack = state.board[orbit][sector]
if attack == "start":
_move_selected_to(orbit, sector)
_clear_marker("selected")
_clear_marker("start")
_clear_marker("canHit")
_clear_marker("willFall")
_process_select(orbit, sector)
elif "canHit" in attack:
_process_hit(orbit,... |
def _get_selected_value():
for o in range(5):
for s in range(18):
if "selected" in state.board[o][s]:
return state.board[o][s]
def _project_flag_attacks(orbit, sector):
can_attack = False
if _project_flag_attacks_toward(orbit, sector, 0, 1): can_attack = True
if _project_flag_attacks_toward(orbit, sector... | The function `_project_attacks` determines if an attack can be projected based on the selected unit type (flag, bomber, sweeper, or fighter) by delegating to corresponding helper functions. It retrieves the unit type from a selected value, checks the type, and calls the appropriate attack projection function. The resul... | def _project_attacks(orbit, sector):
can_attack = False
type = _get_selected_value().split()[0].split("#")[1]
if type == "flag":
can_attack = _project_flag_attacks(orbit, sector)
elif type == "bomber":
can_attack = _project_bomber_attacks(orbit, sector)
elif type == "sweeper":
can_attack = _project_sweep... |
def _move_selected_to(orbit, sector):
type = ""
oi = -1
si = -1
for o in range(5):
for s in range(18):
if "selected" in state.board[o][s]:
type = state.board[o][s].split()[0].split("#")[1]
oi = o
si = s
break
state.board[orbit][sector] = state.board[oi][si]
state.board[oi][si] = "start"
... | This function processes a move in a game by checking if a selected piece can move. If valid, it moves the piece, initiates an attack phase, and updates the game state. If the move matches the current player's color, it clears selection markers and processes the selection. Otherwise, it sets an invalid move prompt. | def _process_move(orbit, sector):
move = state.board[orbit][sector]
if "canMove" in move:
_move_selected_to(orbit, sector)
_project_attacks(orbit, sector)
state.prompt = ATTACK_PROMPT
state.phase = "attack"
_clear_marker("canMove")
elif _get_current_color_prefix() in move:
_clear_marker("selected")
_... |
def _process_select(orbit, sector):
state.prompt = INVALID_SELECT_PROMPT #Assume the selection is invalid unless proven valid.
selection = state.board[orbit][sector]
if _get_current_color_prefix() in selection: #If the selection is a piece which belongs to the active player...
type = selection.split("#")[1]
if _... | The code processes a game state by updating a global 'state' variable and delegating actions to phase-specific helper functions (_process_select, _process_move, _process_attack) based on the 'phase' attribute of the game_state. It handles game phases like selection, movement, and attack by passing 'orbit' and 'sector' ... | def process(game_state, orbit, sector):
if isinstance(game_state, State):
global state
state = game_state
if state.phase == "select":
_process_select(orbit, sector)
elif state.phase == "move":
_process_move(orbit, sector)
elif state.phase == "attack":
_process_attack(orbit, sector) |
def initialize_weights(n_x, n_h1, n_h2, n_y):
W1 = np.random.randn(n_h1,n_x) * (2/n_x)
b1 = np.zeros((n_h1,1))
W2 = np.random.randn(n_h2,n_h1) * (2/n_h1)
b2 = np.zeros((n_h2,1))
W3 = np.random.randn(n_y,n_h2) * (2/n_h2)
b3 = np.zeros((n_y,1))
parameters = {"W1": W1,
"b... | This function trains a neural network with two hidden layers using gradient descent, iterating over epochs to update parameters via forward and backward propagation. It computes training and validation costs, misclassification rates, and returns parameters along with performance metrics for both training and validation... | def neural_net(X, Y, n_h1, n_h2, num_epoch, X_valid, Y_valid):
n_x = np.size(X[:,0],0)
n_y = 1
iterations = np.size(Y,0)
parameters = initialize_weights(n_x, n_h1, n_h2, n_y)
costs = []
valid_costs = []
misclsss_rate = []
valid_misclass_rates = []
#Neural network start... |
def preproc_inputs(self, obs, g):
obs_norm = self.o_norm.normalize(obs)
g_norm = self.g_norm.normalize(g)
# concatenate the stuffs
inputs = np.concatenate([obs_norm, g_norm])
inputs = torch.tensor(inputs, dtype=torch.float32).unsqueeze(0)
if self.args.cuda:
in... | The code trains a reinforcement learning agent by iteratively collecting trajectories through environment interaction, either via random actions (initially) or the learned policy. It stores episodes in a buffer, normalizes data, and updates the neural network parameters using collected samples. The agent evaluates expl... | def learn(self):
"""
train the network
"""
for epoch in range(self.args.n_epochs):
explore_success = []
stats = {'Q1': [], 'Q2': [], 'LogPi': [], 'LossPi': [], 'LossQ': []}
for _ in range(self.args.n_cycles):
mb_obs, mb_ag, mb_g, mb_ac... |
def check_dice_increment(self): # TODO: rename
def check_criteria_passed():
return self.epoch % self.args.increment_freq == 0 and self.epoch > 0
if self.args.increment_dice:
if check_criteria_passed() and self.env.num_dice + self.args.increment_dice <= self.args.max_dice:
... | The code trains a reinforcement learning agent by interacting with an environment over multiple epochs. It collects trajectories through rollouts, using random actions initially and transitioning to learned policies. Episodes are stored in a buffer, and neural networks are updated via experience replay. The agent balan... | def learn(self):
"""
train the network
"""
# start to collect samples
for epoch in range(self.args.n_epochs):
self.epoch = epoch
self.check_dice_increment()
explore_success, loss_q, loss_pi = [], [], []
for _ in range(self.args.n_c... |
def reduce(self, inSeq): ##takes a sequence and reducer as input, returns reduced sequence. NOTE: aAlpha still has leading '-'...
returnSeq = list(inSeq)
with open(self.reduxName) as kFile:
for line in kFile:
aAlpha = []
bAlpha = []
cAlpha = []... | The code calculates the average effects of two mutations (m1 and m2) on a set of sequences. It filters sequences containing both mutations, processes them to compute delta values (delta2, m1, m2, m1m2), sums these values, and outputs their averages to a file. The task involves mutation analysis in biological sequences,... | def mutateAverageOf3(self,seqList):
##Search for sequences that have mutated
delta2sum = 0
m1Sum = 0
m2Sum = 0
m1m2Sum = 0
ctr = 0
mutList = self.posTuples
print(mutList)
m1Idx = mutList[0][1]
m2Idx = mutList[1][1]
for seq in seqLi... |
def reduceMutations(self):
ctr = 0
with open(self.reduxName) as kFile:
for line in kFile:
if ctr == self.mutation1[0]:
line = line.strip()
insertArr = line.split()
aAlpha = list(insertArr[1])
bAl... | This function processes a sequence by reducing mutations and calculating energy-related values (ddSum, d12Sum, d1Sum, d2Sum). It combines these results with formatted mutation identifiers and input name into an array for output. | def calcOneToOutput(self,seq,name):
self.reduceMutations()
seq = self.reduceSequence(seq)
calcArray = self.calcEnergies2(seq)
ddSum = calcArray[0]
d12Sum = calcArray[1]
d1Sum = calcArray[2]
d2Sum = calcArray[3]
headerName = self.formattedMutation1 + '-' +... |
def reduceMutations(self):
ctr = 0
with open(self.reduxName) as kFile:
for line in kFile:
if ctr == self.mutation1[0]:
line = line.strip()
insertArr = line.split()
aAlpha = list(insertArr[1])
bAl... | This function calculates and prints consensus and energy values for a given sequence. It reduces mutations and sequences, computes consensus metrics (dd, d1, d2, d12), prints them, then calculates energy sums (ddSum, d12Sum, d1Sum, d2Sum) and prints these values alongside the input sequence name and mutation data. | def calcOne(self,seq,name):
self.reduceMutations()
seq = self.reduceSequence(seq)
consensusArr = self.calcConsensus()
ddConsensus = consensusArr[0]
d1Consensus = consensusArr[1]
d2Consensus = consensusArr[2]
d12Consensus = consensusArr[3]
pri... |
def searchSequences(self):
ctr = 0
for seq in self.totalSeq:
if (seq[self.mutation1[0]] in self.mutation1[2]) and (seq[self.mutation2[0]] in self.mutation2[2]):
self.foundSeqs.append(seq)
ctr+=1
if (len(self.foundSeqs) == 0):
print("no sequenc... | The code computes average energy values (DDelta, Delta12, Delta1, Delta2) from found sequences by summing and dividing by the sequence count. It also calculates consensus energy values and prints both averages and consensus results, along with the number of sequences processed. The method relies on prior sequence reduc... | def calcAverage(self):
ddSum = 0
d1Sum = 0
d2Sum = 0
d12Sum = 0
if self.searchSequences() == -1:
return
self.reduceFoundSeqs()
self.reduceMutations()
len = 0
for seq in self.foundSeqs:
calcArray = self.calcEnergies(... |
def calcEnergySequence(self,seq,name,mutationArray):
defaultEnergy = self.getEnergy(seq) ##works
m1Energy = self.getEnergy(self.mutateSequence1Consensus(seq, mutationArray[0]))
m2Energy = self.getEnergy(self.mutateSequence1Consensus(seq, mutationArray[1]))
m1m2Energy = self.getE... | The code analyzes mutation data to categorize interactions into rescue, compensate, or antagonistic types based on calculated energy differences and comparisons. It processes each sequence in the value stack, evaluates deviations from consensus interactions, and classifies entries into lists. The function returns these... | def getInteractionsAndDifference(self,mutationData):
mutPair = mutationData[0]
valueStack = mutationData[1]
rescue = []
compensate = []
antag = []
##pdb.set_trace()
#get consensus interaction
consensusData = self.calcEnergySequence(self.consensus,"conse... |
def strangeLoad(self):
with open("src/mutationNames.json") as ifile:
return json.load(ifile)
def mutPairToString(self,mutationPair):
string1 = self.arrToString(mutationPair[0])
string2 = self.arrToString(mutationPair[1])
return string1 + "-" + string2
def getInteractionsAndD... | This function compares mutation data against a consensus by processing imported stacks, sorting interactions (rescue, compensate, antag) by distance metrics, generating consensus rows, and saving results to JSON/CSV files for each mutation. It also creates directories, prints mutation comparisons, and handles interacti... | def compareToConsensus(self,loadValueStacks):
##gets values: [[mutation,computed stack values],[mutation,computed stack values],...]
sequenceCalculations = []
for valueStack in self.importedStacks:
sequenceCalculations += valueStack
##sequenceCalulations: [[mutat... |
def findClosestPlace(latitude, longitude):
min_distance = float('inf')
closest_place_id = None
for coords, place in COMPLETE_COORDINATE_LIST.items():
# print(place)
place_lat, place_lon = coords
distance = haversineDistance(latitude, longitude, place_lat, place_lon)
if dista... | The function `process_data` processes route data by geocoding source and destination locations, determining the optimal path based on day and time, and calculating traffic metrics. It computes total distance, travel time, average speed, and traffic density for each segment along the route. Results are aggregated into a... | def process_data(data):
source = data[0]
destination = data[1]
day = data[2]
time = data[3]
# print('the details are ', source, destination)
geolocator = Nominatim(user_agent="MyApp")
S = geolocator.geocode(source,timeout=10000)
Slat, Slon = S.latitude, S.longitude
# print('f... |
def normal(self, model, skip_fuse_bn):
"""
paremeters:
model -- The onnx model
skip_fuse_bn -- whether skip fuse bn
return:
The optimized onnx model
Before simplifying, use this method to generate value_info, which is used in `forward_all`
Afte... | This code optimizes an ONNX model by removing unnecessary nodes, replacing unsupported operations, and simplifying constants. It deepcopies the model, applies optimizations, checks validity, eliminates redundant constant nodes via forward passes, and restores modified nodes. Final re-optimization ensures compatibility,... | def __call__(self, base, check=3, skip_fuse_bn=True):
"""
base -- OnnxModel
"""
model_original = base.model
model = copy.deepcopy(base.model)
# normal optimization
model = self.normal(model, skip_fuse_bn)
onnx.checker.check_model(model)
... |
def getWords(content: str, withPunctuation: bool):
words = []
tempWord = ""
for i, char in enumerate(content):
if not isPunctuation(char) and not isWhitespace(char):
tempWord += char
elif withPunctuation and (isPunctuation(char) or isWhitespace(char)):
if isEllipses(i... | This function estimates the number of syllables in a given text by counting vowels and consonant patterns, with special handling for the word "the" and silent 'e's at word endings. It iterates through each character in each word, incrementing syllable counts based on vowel positions and adjacent consonants, excluding t... | def getNumSyllables(content: str) -> int:
words = getWords(content, False)
syllables = 0
for word in words:
for i, char in enumerate(word):
# If the first letter is a vowel, we're starting a syllable.
if i == 0 and isVowel(char):
syllables += 1
# A... |
def getSentences(content: str):
sentences = []
tempSentence = ""
words = getWords(content, True)
for i, word in enumerate(words):
# Verify that the sentence contains at least one word
tempSentence = tempSentence + " " + word
if containsEndingPunctuation(word) and word[0] != '.':
... | The code calculates the Flesch Reading Ease score for a given text by analyzing the average number of syllables per word and the average number of words per sentence. It uses the formula: 206.835 - 84.6*(syllables/words) - 1.015*(words/sentences), returning a readability index that indicates text complexity. | def getFleschIndex(content: str) -> float:
sentences = getSentences(content)
words = getWords(content, False)
return 206.835 - 84.6 * (getNumSyllables(content)/len(words)) - 1.015 * (len(words)/len(sentences)) |
def over40():
with open('pokemonTrain.csv', 'r') as file:
next(file)
reader = csv.reader(file)
firetot = 0
over40fire = 0
for row in reader:
if float(row[2])>=40 and row[4]=='fire':
over40fire+=1
firetot+=1
else:
... | The main task of the code is to execute four functions sequentially: checking values over 40, generating a new CSV file, mapping types to personalities, and calculating averages of HP values over 3. These steps likely process and analyze data, transforming or filtering it for further use. The code orchestrates data han... | def main():
over40()
generate_new_csv()
type_to_personality()
avg_hp_over3() |
def convert_seconds_to_minutes(duration):
minutes = math.floor(duration / 60)
seconds = pad(math.floor(duration - minutes * 60))
return f"{minutes}:{seconds}"
def get_items_from_folderid(access_token, folder_id, only_folders):
if only_folders:
q = (
"'"
+ folder_id
... | The function uploads an audio file to Google Drive, extracting metadata if enabled, creating a "All Songs" folder if missing, and setting file properties. It uses API requests to create the file and upload its content, returning the API response. | def upload_file_to_drive(
access_token,
content,
audioname,
folder_id,
getmetadata,
artist,
trackTime,
imgurl,
videoId=None,
parent_name="All Songs"
):
if getmetadata:
try:
audmeta = audio_metadata.loads(content)
trackTime = convert_seconds_to_... |
def fSet_Difficulty():
class Difficulty:
def __init__(self, name, refNum, coloursUsed, guessesAllowed, pegsUsed, blnRestrictSingle):
self.name = name # Difficulty name
self.refNum = refNum # Single Digit number for player to input to refer... | The code runs a game where players guess a color combination, with feedback on hits and nears. It initializes game settings, generates a secret answer, and processes player guesses in a loop. Each turn updates the game state, checks for a win/loss condition, and displays the board. The game ends when the player correct... | def fMainGameCode():
#-----Set Game Difficulty
fSet_Difficulty()
#-----Define Before Loop Starts
bln_is_game_still_going = True
iTurn_Number = 0
#-----Game Starts (Functions to Run Once Only)
fGameStart01_ColoursThatCanBeUsed() #Up to 10 Colours selected depending on players input
fGa... |
def existBid(itemID, username): #checks if user has done a bid with that specific item
connection = sqlite3.connect("AuctionDB.db")
cursor = connection.execute("SELECT * FROM Bids WHERE itemID=:itemID AND username=:username", {"itemID": itemID, "username": username})
result = False
for row in cursor:
... | The main task of the code is to allow a user to place or update a bid on an auction item. It checks if the user already has a bid, validates the new maxPrice against the current item price, and updates or inserts the bid in the database. The function returns True on success (valid bid placement/update) or False if the ... | def newBid(itemID, username, maxPrice): #this will place a new bid the user makes
bidExist = existBid(itemID, username)
preBid = maxUserBid(itemID, username)
currentPrice = finalPrice(itemID)
maxPrice = int(float(maxPrice) * 10) / 10 #this will not allow single pences
if maxPrice < float(currentPric... |
def parse_from_sgml(datadir, split='ModApte'):
"""
Parse Reuters news articles in SGML format.
We are using the Modified Apte train/test split:
* Training Set (9,603 docs): LEWISSPLIT="TRAIN"; TOPICS="YES"
* Test Set (3,299 docs): LEWISSPLIT="TEST"; TOPICS="YES"
Args:
datadir: director... | The main task of the code is to load and preprocess text data for topic classification. It checks for pre-processed pickle files; if absent, it parses SGML files, saves them as pickles, and groups articles by topics. It then extracts tasks, shuffles data deterministically, and returns lists of documents and correspondi... | def load_data(mode, datadir, topics, num_articles):
"""
Load data.
Args:
mode: train or test
datadir: directory containing SGML files
Returns:
List of documents and list of topic labels
"""
if not os.path.isfile(os.path.join(datadir, 'train_set.pkl')) or not os.pat... |
def handleRequest(self, number, char):
if (len(self.password) == 20): return
res = self.sendRequest(str(number), char)
if self.isExpectedResult(res, "Welcome back!"):
print({number, char})
json_obj = {
"position": number,
"character": char
... | The code generates potential password combinations by iterating through characters in `self.array` and numbers 1-20, invoking `handleRequest` for each pair. It then sorts the resulting password using `bubbleSortByPosition`, converts it to a character array, and writes the final result to a text file. | def findPass(self):
for char in self.array:
for number in range(21):
if (number == 0):
continue
self.handleRequest(number, char)
self.password = self.bubbleSortByPosition(self.password)
passwordArray = self.convertToCharArr(self.pas... |
def get_object(self, request: Request) -> tp.Union[dict, Call]:
"""Return an object requested in ``request``
:param request: Request of an object
:type request: :py:class:`df_script_parser.utils.namespaces.Request`
:return: Object requested in a ``request``
:rtype: dict
... | The main task of the code is to validate the arguments provided to an actor, ensuring the 'script' is a valid structure (either a dictionary or a Python object that resolves to a dictionary), and that 'start_label' and 'fallback_label' are properly formatted tuples referencing existing nodes in the script. It raises er... | def check_actor_args(self, actor_args: dict):
"""Checks :py:class:`~df_engine.core.actor.Actor` args for correctness
:param actor_args: Arguments of the :py:class:`~df_engine.core.actor.Actor` call
:type actor_args: dict
:return: None
"""
script = actor_args.get("script"... |
def start(self):
self.browser.get(self.URL)
self.wait.until(EC.presence_of_element_located((By.ID, self.WEB_AUTH_ID)))
logging.debug('Going to %s' % self.URL)
def login(self) -> bool:
username_elem = self.browser.find_element_by_id(self.USERNAME_ID)
password_elem = self.browser.f... | The main task of the code is to automate reserving a resource by launching a Firefox browser, logging in, navigating to a calendar, checking available days for a specific city and month, and reserving the first available day. It uses Selenium for browser automation, saves screenshots, handles waits, and exits upon succ... | def start_a_new_browser_to_reserve(self, city_id: str, month_id: str, day_range: list = None):
self.browser.save_screenshot('./success.png')
dir_path = os.path.dirname(os.path.realpath(__file__))
self.browser = webdriver.Firefox(executable_path=dir_path + '/geckodriver')
self.wait = WebD... |
def check_city_month(self, city_id: str, month_id: str, day_range: list = None) -> list:
initial_cal = self.get_calendar_for_city(city_id)
if initial_cal is None:
return []
month_cal = self.get_calendar_for_month(initial_cal, month_id)
if month_cal is None:
return... | The main task of the code is to check for available reservation days in a specified city and month, reserve the first available day if found, and initiate a new browser session for booking. If no availability is detected, it logs a wait period and pauses for a random duration before retrying. The function handles loggi... | def reserve_if_available(self, city_name: str, month_id: str, day_range: list = None):
logging.info('Checking %s %s' % (city_name, month_id))
city_id = self.CITY_BTN_MAP[city_name]
days = self.check_city_month(city_id, month_id, day_range)
if days:
logging.warning(
... |
def request_data(set_name: str, mode: str, output: str, function, params, opt_params=None):
if opt_params is None:
opt_params = {}
stat = {
"found": 0,
"skipped": 0,
"not found": 0
}
params_sets = get_params(params)
proc_bar = tqdm(params_sets,
b... | This code processes League of Legends data by fetching and structuring information about summoners, match IDs, and game details using API requests. It conditionally handles five modes: entries, summoners, games IDs, games data, and extended summoners. The script uses a ChiefWatcher object to interact with the Riot Game... | def process(entries_mode, entries_output,
summoners_mode, summoners_output,
games_ids_mode, games_ids_output,
games_mode, games_output,
extended_summoners_mode, extended_summoners_output):
chief = ChiefWatcher(*[LolWatcher(i) for i in const.api_keys])
if os.path.... |
def add_BB_node_init(self, title, url):
self.result = self.session.run("Create (b:BBProgram {title: $title, url: $url }) return b", title = title, url = url)
self.result = self.session.run("Create (b:scope {data: \"all\"}) return b")
self.result = self.session.run("MATCH (b:BBProgram {title: $ti... | The main task of the code is to create a Burp Suite project configuration by prompting the user for a target name and URL, initializing a BB node, updating the program, and optionally importing scope from a JSON file. If the user declines the import, the program aborts. Otherwise, it imports the scope and closes. | def create_BB_program(self):
target = typer.prompt("\n Target Name ? \n")
url = typer.prompt("\n Target Url ? \n")
self.add_BB_node_init(target, url)
self.update_bb_program(target)
delete = typer.confirm("\n Import all scope from json for Burp Suite Project Configuration File... |
def get_all_BB_node(self):
self.result = self.session.run("MATCH (n:BBProgram) RETURN n")
def create_BB_program(self):
target = typer.prompt("\n Target Name ? \n")
url = typer.prompt("\n Target Url ? \n")
self.add_BB_node_init(target, url)
self.update_bb_program(target)
... | The main task of the code is to initialize a database by presenting the user with options to either create a new BB program, select an existing one from retrieved results, or exit. It dynamically generates a menu based on existing BB nodes, processes user input, and executes corresponding actions like creating, updatin... | def init_db(self):
ask_user = """Choose your BB Program ? 🎯\n\n
y) Create a new target \n
n) Exit \n
\n\n Select your BBprogram :\n
"""
self.get_all_BB_node()
results = [record for record in self.result.data()]
for x in range(len(results)):
ask_user += str(x) + ") " + res... |
def choose_words(m_words, f_words, m_scores, f_scores, nwords=-1):
n = np.min([len(m_words), len(f_words)] + ([nwords] if nwords >= 0 else []))
m_scores = np.array(m_scores)
f_scores = np.array(f_scores)
m_topn_indices = m_scores.argsort()[::-1][:n]
f_topn_indices = f_scores.argsort()[::-1][:n]
... | This code loads word embeddings (Word2Vec or FastText), filters gender-associated attributes, processes clusters of words from a file, separates them into male/female lists based on gender scores, performs statistical tests (WEAT, Cohen's d) to assess gender bias, and writes results to an output file. | def main(args):
if args.type == 'w2v':
wv = gensim.models.KeyedVectors.load_word2vec_format(args.vectors, binary=True, unicode_errors='ignore')
elif args.type == 'ft':
wv = gensim.models.fasttext.load_facebook_vectors(args.vectors)
else:
raise ValueError("Unsupported Word Embedding t... |
def argparser():
'''Define arguments'''
parser = argparse.ArgumentParser(
formatter_class=argparse.RawDescriptionHelpFormatter,
description='Run parameter fitting code')
parser.add_argument('--ntuple_repo', '-nr', type=str, dest='ntuple_repo',
default='/mnt/lustre/s... | The main task of the code is to execute different data processing or analysis steps based on the input argument 'step'. It routes execution to specific functions like handling accidentals, cutting datasets, scaling reactor tuples, generating PDFs, performing fits, or combining fits, depending on the provided mode. If a... | def main():
# read in argument
args = argparser()
if args.step == 'accidentals':
get_accidentals_and_BiPos(args)
elif args.step == 'cut':
cutNtuples(args)
elif args.step == 'scale':
scale_reactorNtuples(args)
elif args.step == 'pdf':
makePDFs(args)
elif args.... |
def __validate(self):
""" Verifies that attributes are set appropriately and updates as
appropriate
Raises:
ValidationError
"""
# Skip validation if paused
if self.__validation_paused():
return None
#
valid_data_typ... | The code generates a comparison report of fairness measures across all available models by collecting results from each model's `measure_model` method, consolidating them into a pandas DataFrame with model names as columns. It disables validation temporarily for efficiency, re-enables it afterward, and returns the aggr... | def compare_measures(self):
""" Generates a report comparing fairness measures for all available
models
Returns:
a pandas dataframe
"""
self.__validate()
if len(self.models) == 0:
print("No models to compare.")
return pd.DataFr... |
def get_login_info():
""" Get info from customer."""
acct_num = ""
pin = ""
acct_num = input("Please enter your account number: ")
check = isinstance(acct_num, str) and len(acct_num) == 8 and acct_num[2] == '-' and acct_num[:2].isalpha() and acct_num[3:8].isdigit()
while(not check):
... | The main task of the code is to manage an ATM session by authenticating a user's credentials via a server connection, handling login validation responses, and processing customer transactions if valid. It terminates the session upon successful validation or invalid attempts, sending "END" signals appropriately. | def run_atm_core_loop(sock):
""" Given an active network connection to the bank server, run the core business loop. """
acct_num, pin = get_login_info() #asks customer to log in
validated = login_to_server(sock, acct_num, pin) #try to log in
if validated == "0":
print("Thank you, your credentia... |
def get_interesting_words(self, number_following=4):
"""
Finds words with >= number_following types (Nouns, Verbs etc.) of following words.
:param number_following: Int - minimum number required of following word kinds.
:return: List of Strings representing interesting words.
"""... | This method exports context data of the most common interesting words to a CSV file. It retrieves interesting words, identifies the most frequent ones, gathers their contextual information from sentences, formats the data for CSV, and saves the output. | def export_interesting_words_as_csv(self):
interesting_words = self.get_interesting_words(number_following=self._number_following)
most_common_10 = WordCounter.most_common_words(self._word_tokens, interesting_words, self._most_common_number)
contexts = WordContextFinder.get_word_contexts(self._s... |
def _build_layers(self):
self.conv1 = nn.Conv2d(3, 32, 3, stride=1, padding=1, bias=True)
self.pool1 = nn.MaxPool2d(2)
self.conv2 = nn.Conv2d(32, 32, 3, stride=1, padding=1, bias=True)
self.pool2 = nn.MaxPool2d(2)
self.conv3 = nn.Conv2d(32, 64, 3, stride=1, padding=1, bias=True... | This code initializes a neural network model (DecompNet) by building layers, configuring decomposition parameters (layers, group sizes, bottleneck dimensions), and loading weights. It handles three scenarios: initializing a fused model, initializing a decomposed model, or loading a pre-trained model based on configurat... | def __init__(self, cfg, load_path=None, load_model=True):
super(DecompNet, self).__init__()
self._build_layers()
self._init_weights()
self.decomposable_layers = cfg.MODEL.DECOMPOSABLE_LAYERS
self.decompose_group_sizes = cfg.MODEL.DECOMPOSE_STRUCTURE
self.bottle_dims = cf... |
def sum_row(self):
sum_row = [sum(x) for x in self.field]
return sum_row
def sum_column(self):
mt = self.get_columns()
sum_col = [sum(x) for x in mt]
return sum_col
def sum_field(self):
sum_fd = sum(self.sum_column())
return sum_fd
def value_digits(self):
vdig = {}
for i in self.field:
for x, j in ... | The code defines the `__str__` method to generate a human-readable summary of an object's key properties by concatenating formatted strings representing row sum, column sum, total span sum, value per digit, and calculated span, returning them as a multi-line string. | def __str__(self):
lines = []
lines.append("Row sum: {}".format(self.sum_row()))
lines.append("Column sum: {}".format(self.sum_column()))
lines.append("Total sum of spans: {}".format(self.sum_field()))
lines.append("Value per digit: {}".format(self.value_digits()))
lines.append("calc span: {}".format(self.c... |
def get_gini_value_of_decision_attributes(source_table, verbose: bool = False):
last_column = get_column_at_index(matrix_2d=source_table, idx=-1)
decision_attribute_probabilities = get_attribute_probabilities(last_column, verbose=verbose)
gini = product(decision_attribute_probabilities.values())
if verb... | This function constructs a set of decision rules for a decision tree using the Gini index. It calculates Gini scores for attributes, identifies those with maximum Gini gain, recursively splits the dataset based on these attributes, and aggregates rules. The process involves shrinking the dataset iteratively, handling l... | def construct_decision_rules_set(source_table: list[list] = None, tree_root_attributes: list = None):
all_rules = []
if not source_table:
source_table = sample_tree
if not tree_root_attributes:
tree_root_attributes = []
print('Starting Creating Decision Tree by Gini Score')
# Decisio... |
def printlog(*args, **kwargs):
global FILE_LOG
print(*args, **kwargs)
if FILE_LOG:
kwargs['file']=FILE_LOG
print(*args, **kwargs)
def read_firmware_from_device(chip, port, baud, read_efuses=True):
global FIRMWARE_CHIP, FIRMWARE_ESP
initial_baud = min(esptool.ESPLoader.ESP_ROM_BAUD, ... | The main task of the code is to analyze ESP32 firmware by loading it from a file or device, parsing the bootloader, partition table, and application partitions, then exporting parsed data (including NVS partitions) to files. It supports command-line arguments for chip selection, board configurations, and handles firmwa... | def main():
global FIRMWARE_CHIP, FIRMWARE_ESP, FILE_LOG
#### globally accessed bins and pased data
FIRMWARE_FULL_BIN = None
FIRMWARE_PARTITIONS_BIN = None
FIRMWARE_PARTITIONS_TABLE = None
FIRMWARE_PARTITIONS_FNAMES = []
BOOTLOADER_IMAGE = None #parsed
BOOTLOADER_IMAGE_BIN = None ... |
def process_mocap(mocap_file, phase_file, mirror=False, height_offset=0):
motion = bvh.load(mocap_file)
motion = MotionWithVelocity.from_motion(motion)
motion.compute_velocities()
phase = np.loadtxt(phase_file)[:, :]
matrix = motion.to_matrix(local=False)[:, :, :, :]
local_matrix = motion.to_matrix(local=True)[:,... | The code initializes a KD tree-based environment for reinforcement learning by processing and concatenating motion capture (Mocap) data from multiple BVH files. It combines linear/angular velocities, bone orientations, and phases from mirrored and non-mirrored datasets, constructs a unified dataset for RL training, and... | def __init__(self, num_envs):
print("KD tree Env created.")
self.num_envs = num_envs
self.starting_frame = 320
self.pick_and_place = False
#build initial dataset
self.root_linear_vel, self.root_angular_vel, self.store_data, self.local_matrix, self.features, self.bone_orientation, self.phase, self.bone_velo... |
def freeze_feature_parameters(model):
for param in model.parameters():
param.require_grad = False
for param in getattr(model, "classifier", "fc").parameters():
param.require_grad = True
def evaluate(model, val_loader):
with torch.no_grad():
model.eval()
outputs = [valida... | The main task of the code is to train a neural network model for image classification using transfer learning. It parses input arguments, prepares data loaders, builds a pre-trained model with specified architecture and hidden units, configures training hyperparameters, evaluates the model on validation data before tra... | def main():
history = []
# get input args
input_args = parse_train_args()
if input_args.gpu:
print(f"Switching to GPU")
if not torch.cuda.is_available():
print(f"--gpu flag is used with no available gpu, reverting to cpu for training")
else:
print(f"Using cpu... |
def init_result_list(self):
"""
Initialise the result list
"""
self.result_list = [] # initialise the list of results
return 0
def process(self, rw_data):
"""
Split the string into substrings based on spaces
"""
rw_data = str(rw_data) # be... | The code processes input data from a controller by first initializing a result list, then processing the input data. It iterates over each element of the processed data (if it's a list) or treats it as a single element, creating a list of results using `create_list`. Finally, it returns the compiled result list for the... | def take_in(self, rw_data):
"""
takes in the data from the controller
sends it to be processed
reads through each element of the processed_data
creates the list of results
returns the list of results for the controller to do whatever it needs
"""
self.in... |
def playTurn(self, column, human):
if column < 0 or column > self.width - 1:
if human:
print('Not a viable turn')
return
fill = self.column_counts[column]
if fill > self.height - 1:
if human:
print('Column is already filled... | This function manages a single-player game loop where the human player and bot alternate turns inserting pieces into a column. It checks for a win after each move and continues until the game ends, then announces the winner. | def play1Player(self):
while not self.gameOver:
if(self.turn == 1):
column = input('Enter column to insert piece:')
column = int(column)
self.playTurn(column, True)
self.checkWin()
else:
print('Bot Turn')
... |
def resize_prop_rect(src, img_size=SIZE_0):
MAX_SIZE = (img_size, img_size)
xscale = MAX_SIZE[0] / src.shape[0]
yscale = MAX_SIZE[1] / src.shape[1]
scale = min(xscale, yscale)
if scale > 1:
return src
dst = cv2.resize(src, None, None, scale, scale, cv2.INTER_... | The main task of the code is to find and validate matches between two images using SuperGlue, returning whether the matches are relevant and their scores. It processes input images, extracts keypoints, filters valid matches, checks their relevance, and optionally saves a visualization of the matches for debugging. | def find_matches_superglue(self, second_img, debug=True,start_time=None,index_element=None):
self.matching.index_element=index_element
if second_img is not None:
self.gray_second = self.resize_prop_rect(second_img, img_size=SIZE_1)
print("gray2", self.gray_second.shape)
... |
def daysBetweenDates(year1, month1, day1, year2, month2, day2):
"""Returns the number of days between year1/month1/day1
and year2/month2/day2. Assumes inputs are valid dates
in Gregorian calendar."""
# program defensively! Add an assertion if the input is not valid!
assert not dateIsBefore(yea... | The main task of the code is to test the correctness of date-related functions, including calculating days between dates, determining the next day, and checking leap years. It uses assert statements to verify expected outputs for various date scenarios, ensuring accurate handling of edge cases like leap years and month... | def test():
assert daysBetweenDates(2013, 1, 1, 2013, 1, 1) == 0
assert daysBetweenDates(2013, 1, 1, 2013, 1, 2) == 1
assert nextDay(2013,1,1) == (2013,1,2)
assert nextDay(2013,4,30) == (2013,5,1)
assert nextDay(2012,12,31) == (2013,1,1)
assert nextDay(2013,2,28) == (2013,3,1)
assert nextDay(2013,9... |
def _parse_dict(self, obj):
# all top level objects are added as variables to this object
for key, value in list(obj.items()):
if value is None:
continue
key = self._parse_string(key)
print("_parse_dict key %s value %s"%(key,value))
setatt... | This code parses input values by delegating to type-specific helper methods: _parse_dict for dictionaries, _parse_string for strings, and _parse_list for lists. If the value doesn't match these types, it returns the original value unchanged. | def parse(self, value):
if isinstance(value, dict):
return self._parse_dict(value)
if isinstance(value, basestring):
return self._parse_string(value)
if isinstance(value, list):
return self._parse_list(value)
return value |
def getArgs():
parser = argparse.ArgumentParser(description = "Export and import Grafana dashboards")
parser.add_argument("--api-key", required = True,
help = "The Grafana API key. Can be Generated in Grafana at: Configuration -> API Keys")
parser.add_argument("--url", default ="http://grafana:3000/",
help = ... | The main task of the code is to export or import Grafana dashboards based on command-line arguments. If the `--export` flag is used, it retrieves dashboards from a Grafana instance, formats them as JSON with metadata, and prints the result. If the `--import` flag is used, it reads JSON input from stdin and imports the ... | def main():
args = getArgs()
#print(args) # Debug
# Double-slashes don't play nice with Grafana.
url = args.url.rstrip("/")
if args.export:
dashboards = export(url, args.api_key)
output = {"dashboards": dashboards}
output["meta"] = {"app": "Grafana Playground"}
print(json.dumps(output))
elif args.__di... |
def effective_lines_of_code(filename):
file = open(filename, "r")
lines = file.readlines()
return len(lines)
def kilo_lines_of_code(filename):
return effective_lines_of_code(filename) / 1000
def assignments_branches_conditionals(cursor):
assignments = branches = conditionals = 0
# find_toke... | The code's main task is to calculate and print various software metrics for a given source file. It uses a library (e.g., Clang's CIndex) to parse the file, extracting metrics like effective lines of code (ELOC), kilo-lines of code (KLOC), Halstead program length (N), vocabulary (n), volume (V), and token count (TC), a... | def print_all():
# Create
index = ci.Index.create()
tu = index.parse(sys.argv[1])
filename = tu.spelling
print(f"ELOC: {effective_lines_of_code(filename)}")
print(f"KLOC: {kilo_lines_of_code(filename)}")
print(f"ABC: {assignments_branches_conditionals(tu.cursor)}")
print(f"N: {hals... |
def fix_nulls(self, s):
for line in s:
yield line.replace('\0', '')
def create_book(self, name, author_first, author_last, publication_year, edition, tags_name_list):
queryBook = Book.objects.filter(title=name) #add more later
#print(queryBook)
if (len(queryBook) == 0):
... | The code reads a CSV file named 'init.csv' from a specific directory, processes each row by splitting author names and tags, and creates book entries using the `create_book` method. It handles potential null values and ensures the file exists before processing. If the file is missing, it prints an error message. | def load_csv(self):
path = os.path.join(os.getcwd(), "data", "raw", "init.csv")
if os.path.exists(path):
with open(path, newline='') as csvfile:
tag_reader = csv.reader(
self.fix_nulls(csvfile), delimiter=',')
for row in tag_reader:
... |
def complete_interval(self, fixed, initial, final, flag):
current_interval = [initial, final]
tot_fin = final
direction = np.sign(final-initial)
# print(current_interval)
count=0
while direction*current_interval[0] != direction*final and count<1000:
# if count... | This code processes time-dependent load and moisture changes by iterating through sequences, calculating differences, and adjusting model intervals. It calls `complete_interval` for moisture or load variations, updates the model state, and breaks if all local elements are non-intact. The main task is simulating dynamic... | def run(self):
# print(self.time_sequence)
for time_index, time_value in enumerate(self.time_sequence):
self.current_time = time_value
self.current_load = self.load_sequence[time_index]
self.current_moist = self.moist_sequence[time_index]
prev... |
def user_exists(self) -> bool:
conn, cur = get_connection()
cur.execute("SELECT * FROM User WHERE handle = ?", (self.handle,))
if len(cur.fetchall()) > 0:
return True
else:
return False
def acquire_user(self):
if not self.user_exists():
raise K... | The code initializes a user object with a handle. If the user exists, it retrieves their data; otherwise, it creates a new user. It sets up attributes like user_id, name, and unique identifier, handling both existing and new user scenarios. | def __init__(self, handle):
if type(handle) is str:
self.user_id = None # User's database key
self.fname = None # User's first name
self.lname = None # User's last name
self.handle = handle # User's tag visible to all
self.user_hash =... |
def Image_Gen():
Input_img = Input(shape=(inputsize, inputsize, 3))
x1 = Conv2D(64, (3, 3), activation='relu', padding='same', kernel_regularizer=regularizers.l1(10e-10))(Input_img)
x2 = Conv2D(64, (3, 3), activation='relu', padding='same', kernel_regularizer=regularizers.l1(10e-10))(x1)
x3 = MaxPool2D... | The code defines and trains a Generative Adversarial Network (GAN) for image generation. It initializes a generator (Image_Generator) and discriminator, loads training/test datasets, configures Adam optimizers, and uses a pre-trained VGG16 model for perceptual loss. The GAN trains for 100 epochs, leveraging dataset bat... | def run():
Image_Generator = Image_Gen()
discriminator = make_discriminator_model()
discriminator.summary()
patch_size = (inputsize,inputsize)
vgg = tf.keras.applications.VGG16(
include_top=False, weights="imagenet", input_shape=(*patch_size, 3)
)
loss_model = tf.ker... |
def load_jsonlines(path:str) -> pd.DataFrame:
"""Loads 1 or more .jsonl files into a dataframe"""
if path.endswith(".jsonl"):
return pd.read_json(path, lines=True)
else:
dfs = [pd.read_json(file, lines=True) for file in Path(path).glob("*.jsonl")]
return pd.concat(dfs).reset_index(dr... | The function `from_jsonlines` processes jsonlines files or directories to generate a DataFrame of stylistic feature vectors for documents. It extracts document and author IDs, applies feature configurations, optionally includes word2vec embeddings (with a warning), and structures the output with documents as rows and f... | def from_jsonlines(path:str,
config:Optional[Dict]=None,
include_content_embedding=False) -> pd.DataFrame:
"""
Given a path to either a jsonlines file OR directory of jsonlines files, creates a stylistic feature
vector matrix. Document IDs and author IDs are included... |
def prepare_params(params):
parameters = Parameters()
for i, value in enumerate(params):
if i == 0:
min_val, max_val = 0, 10000
else:
min_val, max_val = -5000, 5000
parameters.add(f'c{i}', value=value, min=min_val, max=max_val)
return parameters
def wavelengt... | This function computes a wavelength calibration by iteratively fitting parameters to map pixel positions in an arc spectrum to known lamp wavelengths, using minimization with outlier rejection via sigma clipping. It returns optimized parameters for the wavelength-solution function, optionally plots results, and saves t... | def quick_wavelength_solution(arc_pixels, lamp_wave, params=None, sigmas=None, func='chebyshev', k=3, niter=3,
sigclip=2.5, plot_solution=False,
data=None):
"""Finds a wavelength solution with a simple fit.
Parameters
----------
params: array-... |
def start_level(self):
fade = pygame.Surface((WIDTH, HEIGHT))
fade.fill(('Black'))
for alpha in range(255, 0, -1):
fade.set_alpha(alpha)
self.draw()
self.screen.blit(fade, (0, 0))
for event in pygame.event.get():
if event.type == py... | The code executes a game loop that initializes the level on first run, handles input (QUIT, ESCAPE, R keys), calculates delta time for smooth updates, processes game objects (coins, obstacles, player), checks for level completion, and renders the game state. It maintains timing for animations and physics, restarts the ... | def run(self):
if self.first_run:
self.start_level()
self.first_run = False
self.prev_time = time.time() # Due to fade, removing this could lead to a bug
# Check for ball in hole, if so, delete all objects and set highscore
if self.end:
return se... |
def user_input(self, mouse_buttons):
if mouse_buttons[0] and not self.in_move and self.in_collision and not self.click_pos:
self.click_pos = pygame.mouse.get_pos()
if self.click_pos and not mouse_buttons[0]:
self.hit(pygame.mouse.get_pos())
def draw_vector(self):
if sel... | The code updates a game object's movement, applying gravity, checking collisions with obstacles and players, handling user input, and updating animations. It iterates multiple times to refine movement and collision checks, ensuring realistic physics and interaction within the game environment. | def update(self, obstacle_group, player_group, delta_time, mouse_buttons, end):
self.user_input(mouse_buttons)
self.draw_vector()
self.check_movement()
self.collide(obstacle_group, player_group)
if self.in_move:
self.gravity()
for i in range(self.iteration... |
def __CheckFilterId(self, filterId):
# The requested filter ID must match the specification of between 5 and 45 alphanumeric or underscore characters
if filterId == None or not re.match('^[A-Z0-9_]{5,45}$', filterId, re.I):
return 'The filter identifier must be between 5 and 45 characters lo... | The main task of the code is to retrieve details of a specific economic filter from a Datastream API. It validates the filter ID, checks authentication tokens, sends a request to the API endpoint, processes the JSON response, and returns a structured filter response object. The method also handles errors, logs activiti... | def GetFilter(self, filterId):
""" GetFilter returns the details for an individual filter
Example usage:
# first logon with your credentials. Creating an EconomicFilters instance with your credentials automatically logs on for you
econFilterClient = EconomicFilters(None, 'Y... |
def __VerifyEconomicFilter(self, econFilter, updateAction, isCreate):
# must be a DSEconomicsFilter and the filer ID and constituents must be valid
if not isinstance(econFilter, DSEconomicsFilter):
return 'EconomicFilters CreateFilter or ModifyFilter methods require a valid DSEconomicsFilter... | The main task of the code is to create a custom economic filter by validating input parameters, sending a request to a server via the CreateFilter endpoint, and returning the response. It checks filter validity, logs details, handles token renewal, processes server responses, and formats output including error handling... | def CreateFilter(self, newFilter):
""" CreateFilter allows you to create a custom filter
Example usage:
# first logon with your credentials. Creating an EconomicFilters instance with your credentials automatically logs on for you
econFilterClient = EconomicFilters(None, 'Yo... |
def __VerifyEconomicFilter(self, econFilter, updateAction, isCreate):
# must be a DSEconomicsFilter and the filer ID and constituents must be valid
if not isinstance(econFilter, DSEconomicsFilter):
return 'EconomicFilters CreateFilter or ModifyFilter methods require a valid DSEconomicsFilter... | The main task of the code is to update an existing custom economic filter by sending its details and an update action to a server API. It validates the filter, checks authentication, sends the request, processes the response, and returns results including success/failure status, updated filter data, or error details. | def UpdateFilter(self, filter, updateAction):
""" UpdateFilter allows you to update an existing custom filter
Example usage:
# first logon with your credentials. Creating an EconomicFilters instance with your credentials automatically logs on for you
econFilterClient = Econ... |
def __CheckFilterId(self, filterId):
# The requested filter ID must match the specification of between 5 and 45 alphanumeric or underscore characters
if filterId == None or not re.match('^[A-Z0-9_]{5,45}$', filterId, re.I):
return 'The filter identifier must be between 5 and 45 characters lo... | The main task of the code is to delete an existing custom filter by its ID. It validates the filter ID, checks authentication token validity, sends a deletion request to the API, and returns the response status. The function handles errors like invalid IDs, logs actions, and ensures proper token renewal before making t... | def DeleteFilter(self, filterId):
""" DeleteFilter allows you to delete an existing custom filter
Example usage:
# first logon with your credentials. Creating an EconomicFilters instance with your credentials automatically logs on for you
econFilterClient = EconomicFilters(... |
def post_user_request(self, tickers, fields=None, start='', end='', freq='', kind=1, retName=False):
""" This function helps to form requests for get_bundle_data.
Each request is converted to JSON format.
Args:
tickers: string, Dataypes
fields... | The function `get_data` retrieves financial data from a web service (DSWS) by processing a JSON request, converting the response into a Python DataFrame. It accepts parameters like tickers, date ranges, frequency, and output format. It authenticates using a token, handles errors, and returns structured data or raises e... | def get_data(self, tickers, fields=None, start='', end='', freq='', kind=1):
"""This Function processes a single JSON format request to provide
data response from DSWS web in the form of python Dataframe
Args:
tickers: string, Dataypes
fields: Lis... |
def Check_Token(self):
if not self.IsValid():
raise Exception("You are not logged on. Please recreate this client object supplying valid user credentials.")
# A function called before every query to check and renew the token if within 15 minutes of expiry time or later
timeRenew = da... | This function processes multiple JSON data requests to retrieve data from DSWS web, converting the response into a Python DataFrame. It handles token validation, constructs bundled requests, and formats the JSON response. If `retName` is True, it includes metadata like instrument and datatype names. Errors are logged a... | def get_bundle_data(self, bundleRequest=None, retName=False):
"""This Function processes a multiple JSON format data requests to provide
data response from DSWS web in the form of python Dataframe.
Use post_user_request to form each JSON data request and append to a List
to pass... |
def validate(k,n, N):
a = 16*k**2
b = -4*N**2
c = 3*n**2*N**2
x1,x2 = solveq(a,b,c)
a1,a2=sqrt(x1), sqrt(x2)
b1,b2 = N*sqrt(3)/4/a1, N*sqrt(3)/4/a2
cos1, cos2 = 2*b1*n/N, 2*b2*n/N
assert(abs(cos1)<=1)
assert(abs(cos2)<=1)
print(f"k={k:5} n={n:5} a1={a1:.3f},b1={b1:.3f},cos1={cos... | The code calculates a count based on trigonometric and integer conditions for pairs (k, n) within a range. It checks if products of k and n exceed a threshold, validates trigonometric values, and verifies if specific expressions are integers. When conditions are met, it increments the count. Finally, it returns twice t... | def alt(N):
count = 0
for k in range(1, N):
if k==0: continue
for n in range(1, N):
#if n==k: continue #parallel??
if abs(k*n) > N/2/sqrt(3): break
cos1,cos2 ,sin1,sin2, b1, b2= validate(k,n, N)
#f travel_check(b1/cos1, n, k)==True: count += 1
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.