dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def categorize_alignment(read, genome):
# Alignment endgaps are assumed to be meaningless
# check if homopolymer
if len(set(read.replace('-', ''))) == 1:
return 'homopolymer'
if 'N' in read:
return 'hasN'
'''
Detect PCR recombination within context (should be rare).
Only anticipated for g... | The code processes a file containing alignment data, categorizing each alignment into indel types (e.g., deletions/insertions) using `categorize_alignment`. It adjusts sequences for potential shifts in deletion/insertion positions via `shift_single_deletion` or `shift_single_insertion`. Valid alignments are then stored... | def remaster_aligns(inp_fn, data):
# timer = util.Timer(total = util.line_count(inp_fn))
with open(inp_fn) as f:
for i, line in enumerate(f):
if i % 4 == 0:
header = line.strip()
if i % 4 == 1:
read = line.strip()
if i % 4 == 2:
genome = line.strip()
if i % 4 == ... |
def filename_handler(filename: str = list_to_str_serializer(args.filename)) -> load_workbook:
if not check_xlsx_format(filename):
dir, tail = os.path.split(filename)
if not dir:
dir = None
_filename = "".join([file for file in os.listdir(dir) if not os.path.isdir(file) and tail =... | The main task of the code is to parse Excel files (single or multiple), handle workbook/worksheet data via filename/filepath handlers, serialize contents into dictionaries, and return a flattened list of dictionaries by combining all parsed data while removing nested array structures. | def run_parser() -> list[dict]:
if args.filename and (workbook := filename_handler()):
return workbook_serializer(workbook)
excel_files = filepath_handler()
if isinstance(excel_files, Workbook):
return workbook_serializer(excel_files)
worksheets: list[Workbook] = [filename_handler(wb) fo... |
def _resolve_annotation(annotation, attr: str) -> Any:
if inspect.isclass(annotation) and isinstance(annotation, DualBaseModelMeta):
return getattr(annotation, attr)
elif isinstance(annotation, GenericAlias):
return GenericAlias(
get_origin(annotation),
tuple(_resolve_ann... | This function generates alternative classes with dynamic suffixes for request, response, and patch operations. It constructs a request class using a metaclass, then lazily initializes response and patch request classes by wrapping them in lambda functions. These classes are built with resolved base classes and modified... | def _generate_alternative_classes(
self, name, bases, attrs, request_suffix, response_suffix, patch_request_suffix, kwargs
):
request_bases = tuple(_resolve_annotation(b, REQUEST_ATTR) for b in bases)
request_class = ModelMetaclass(
name + request_suffix,
request_base... |
def showActiveSubscriptions(subscription_id=None, is_verbose=False):
# ==============================================
# get the latest access token
accessToken = rdpToken.getToken()
category_URL = "/message-services"
endpoint_URL = "/file-store/subscriptions" if subscription_id is None else "/file... | The code processes command-line arguments to manage file notification subscriptions, performing actions like showing, deleting, creating, polling, modifying, checking queue attributes, or recovering messages. It validates required parameters, executes corresponding functions, and logs errors or input parameters. If inv... | def read_args():
try:
# Read arguments from command line
args = parser.parse_args()
args_dict = vars(parser.parse_args())
app_logger.info("input parameter = {}".format(args_dict))
if args.get:
if args.subscriptionId:
showActiveSubscriptions(args.... |
def yell(self, s):
print(f'[Grile] {s}')
def at_server(self):
hostname = socket.gethostname()
for mach in self.machines:
machine = self.machines[mach]
if machine.name == hostname:
return True
return False
def get_data_dir(self):
if self.at_... | The function transfers a file from a source path to a server-specific destination directory based on simulation data, using a provided key. It verifies the simulation is ended, checks if the key is valid, copies the file, and optionally deletes the source file. It logs transfer and deletion actions. | def transfer_file(self, key, src_path, delete=False):
if not self.ended:
self.yell('Please end the simulation before writing any files.')
if self.at_server() and (not self.simulation is None):
if key in self.simulation.data:
filename = self.simulation.data[key]['f... |
def at_server(self):
hostname = socket.gethostname()
for mach in self.machines:
machine = self.machines[mach]
if machine.name == hostname:
return True
return False
def yell(self, s):
print(f'[Grile] {s}')
def get_path(self, machine, group='', simul... | The main task of the code is to create a simulation by loading configuration data from an "info.json" file, initializing a Simulation object, ensuring the simulation directory exists, and creating a log file if necessary. It returns the Simulation instance if executed on the server, otherwise returns None. | def create_simulation(self):
if self.at_server():
mainpath = pathlib.Path(__main__.__file__).absolute()
info_file = str(mainpath.parent.absolute()) + '/info.json'
self.yell(f'Simulation created using {info_file}')
with open(info_file, 'r') as f:
in... |
def at_server(self):
hostname = socket.gethostname()
for mach in self.machines:
machine = self.machines[mach]
if machine.name == hostname:
return True
return False
def get_path(self, machine, group='', simulation='', sim_id='', filename=''):
if no... | The code writes a log dictionary to a JSON file on the server if executed at the server, using a constructed path from machine, group, and simulation parameters. If executed on a client, it raises an error indicating log writing is restricted to servers. | def write_log(self, machine, group, simulation, log):
if self.at_server():
logpath = self.get_path(machine, group, simulation) + '/log.json'
with open(logpath, 'w+') as f:
ujson.dump(log, f, indent=4)
else:
self.yell('Cannot write log at client') |
def at_server(self):
hostname = socket.gethostname()
for mach in self.machines:
machine = self.machines[mach]
if machine.name == hostname:
return True
return False
def get_path(self, machine, group='', simulation='', sim_id='', filename=''):
if no... | The function retrieves log data from a server by constructing a file path using provided parameters, reading the JSON file if on the server side, and returning its content. If not on the server, it alerts and returns None. | def retrieve_log(self, machine, group, simulation):
if self.at_server():
logpath = self.get_path(machine, group, simulation) + '/log.json'
with open(logpath, 'r') as f:
return ujson.load(f)
else:
self.yell('Cannot retrieve log from client')
... |
def at_server(self):
hostname = socket.gethostname()
for mach in self.machines:
machine = self.machines[mach]
if machine.name == hostname:
return True
return False
def yell(self, s):
print(f'[Grile] {s}')
def retrieve_log(self, machine, group, simu... | This method deletes a simulation by verifying its existence on the server, confirming user intent, updating the log, and moving the simulation directory to a hidden location while maintaining data integrity and user confirmation steps. | def delete(self, machine, group, simulation, sim_id):
simpath = \
f'{group}/{simulation}'
if self.at_server():
if socket.gethostname() != machine:
self.yell('Unable to delete file from remote server')
return
else:
log = sel... |
def get_path(self, machine, group='', simulation='', sim_id='', filename=''):
if not machine in self.machines:
self.yell(f'{machine} is not in the list of registered servers')
return None
path = ''
if self.get_current_machine().name == machine:
path = self.m... | This code assigns a unique ID to a simulation by checking existing directories, creates a new directory for the simulation, writes key data files to it, and updates the simulation log with the assigned ID. It ensures uniqueness by incrementing IDs until an unused one is found, handles directory creation/overwriting, an... | def finalize(self, sim):
simdir = self.get_path(self.get_current_machine().name, sim.group, sim.name)
existing = os.listdir(simdir)
sim_id = 0
while True:
if str(sim_id) not in existing:
break
sim_id += 1
self.yell(f'This simulation has bee... |
def requester_and_soup_maker(self,link):
# print("in request&soup_maker")
response = requests.get(link)
soup = BeautifulSoup(response.content, 'html.parser')
links = soup.find_all('li', class_='app-c-topic-list__item')
links = ["https://www.gov.uk" + link.a['href'] for link in li... | The code recursively crawls data from the UK government website by fetching links from a base URL, then iterating through each level of sub-links. It uses a helper method to request pages and parse HTML, then extracts data from each page using a data_crawler method. The primary task is to systematically scrape and gath... | def __init__(self):
base_url = "https://www.gov.uk/topic"
links = self.requester_and_soup_maker(base_url)
for each in links:
sub_links = self.requester_and_soup_maker(each)
for each in sub_links:
sub_sub_links = self.requester_and_soup_maker(each)... |
def stateMatrix(text: str) -> list:
"""
Converts the given text to a 4x4 matrix in column major order
args: text: str - the text to convert. It is assumed that the text is 128 bits.
If the text is less than 128 bits, it is padded with 0s. If it is greater than 128 bits,
it is truncated to 128 bits.
"""... | This function encrypts a 128-bit plaintext block using AES with provided round keys. It validates input size, initializes a state matrix, applies the initial round key, executes 9 rounds of substitution, row shifting, column mixing, and key addition, followed by a final round omitting column mixing. The resulting state... | def aesEncryptOneBlock(plainText: str, keys: list) -> str:
"""
Performs the AES cipher on the given text with the given keys. The provided plain text and key texts are assumed to be 128 bits of hex values.
args: plainText: str - the text to encrypt
keys: list - the list containing the round keys
ret... |
def convertToBlockSize(text: str) -> str:
"""
Converts the given key to 128 bits
"""
if len(text) > BLOCK_SIZE_BYTES:
return text[:BLOCK_SIZE_BYTES]
elif len(text) < BLOCK_SIZE_BYTES:
return text + "0" * (BLOCK_SIZE_BYTES - len(text))
return text
def textToMatrix(text: str) -> list:
"""
Convert... | The main task of the code is to generate all 10 round keys required for a cryptographic algorithm (likely AES) by iteratively applying the `roundKey` function to an initial key matrix, starting from a block-sized input text. It converts the input text to a matrix, then computes subsequent round keys based on the previo... | def createAllKeys(text: str) -> list:
"""
Generates all round keys from the initial key
"""
text = convertToBlockSize(text)
keys = [textToMatrix(text)]
for i in range(10):
keys.append(roundKey(i+1, keys[i]))
return keys |
def pad(text: str) -> str:
"""
Pads the text to be a multiple of block size with the number of bytes added
"""
padLength = BLOCK_SIZE_BYTES - len(text) % BLOCK_SIZE_BYTES
if padLength == 0 or padLength == BLOCK_SIZE_BYTES:
return text
return text + chr(padLength) * padLength
def createAllKeys(text: st... | The main task of the code is to perform AES encryption on a given plaintext using a specified key. It converts inputs to strings, logs plaintext and key details in ASCII/hex formats, pads the plaintext, generates encryption keys, and processes the text in blocks. Each block is encrypted using a block-specific AES funct... | def aesEncrypt(plainText: str, keyText: str) -> str:
"""
Performs the AES cipher on the given text with the given key
args: plainText: str - the text to encrypt
keyText: str - the key to use for encryption
returns: cipherText: str - the encrypted text
"""
# convert plain text and key text to strin... |
def createAllKeys(text: str) -> list:
"""
Generates all round keys from the initial key
"""
text = convertToBlockSize(text)
keys = [textToMatrix(text)]
for i in range(10):
keys.append(roundKey(i+1, keys[i]))
return keys
def aesDecryptOneBlock(cipherText: str, keys: list) -> str:
"""
Performs the A... | This function decrypts AES-encrypted text using a provided key. It processes the ciphertext in blocks, generates necessary keys, decrypts each block, unpads the result, and logs the decrypted output in hex and ASCII formats before returning the plain text. | def aesDecrypt(cipherText: str, keyText: str) -> str:
"""
Performs the AES cipher on the given text with the given key
args: cipherText: str - the text to decrypt
keyText: str - the key to use for decryption
returns: plainText: str - the decrypted text
"""
# convert plain text and key text to stri... |
def friend_play(b):
print()
name1= input("Great, what's the name of player 1(X)?"+'\n')
name2 = input("And what's the name for player 2? (O)"+'\n')
p1 = Player("X",name1)
p2 = Player("O",name2)
play(p1,p2,b)
def random_play(b):
print()
name1= input("Great, what's your name player 1(X)?"+... | The main task of the code is to initialize a Connect 4 game by prompting users for board dimensions, opponent type (friend/random AI/intelligent AI), and routing gameplay to corresponding functions while validating inputs. It sets up game parameters and directs execution based on user choices. | def main_connect_4():
print("Welcome to Connect 4")
print()
height = int(input("How many rows do you want to play with? (usually it is 6)"+'\n'))
print()
width=int(input("How many columns? (usually it is 7)"+'\n'))
b= Board(height,width)
print()
choice = int(input("Would you like t... |
def generateSourceCode(problemSize, dir, export):
dsIndex = -1
ssIndex = -1
dssIndex = -1
codeHeader = "#include \"vecNormTrans.h\"\n//------------------------------------------------------------------------\n// vecNormTrans\n//------------------------------------------------------------------------\n//... | The code evaluates multiple design configurations by checking synthesis, cosimulation, and implementation results from log files. It collects hardware metrics (LUTs, DSPs, timing) and computes throughput. It generates a table summarizing success/failure status and metrics, identifies optimal values, and visualizes trad... | def evaluateDesign(size, dir, threads, visualize, problemSize):
path, dirs, files = next(os.walk(dir))
dirCount = len(dirs) - 1
ssIndex, dsIndex, dssIndex = generateSourceCode(size, dir, False)
print("SS = "+str(ssIndex)+", DS = "+str(dsIndex)+", DSS = "+str(dssIndex))
# estimateLoss = evaluateSour... |
def confirm():
# raw_input returns the empty string for "enter"
yes = {'yes','y', 'ye'}
no = {'no','n'}
choice = input().lower()
while choice not in yes and choice not in no:
print("Please respond with 'y' or 'n'")
choice = input().lower()
if choice in yes:
return True
... | The main task of the code is to orchestrate a workflow for hardware design and evaluation, allowing users to control code generation, synthesis, cosimulation, post-synthesis analysis, and result evaluation through command-line options. It supports running individual tasks or all steps from scratch, with options for deb... | def main():
optparser = OptionParser()
optparser.add_option("-v", "--visualize", action="store_true", dest="visualize",
default=False, help="Visualize results in tikz images")
optparser.add_option("-o", "--output", dest="dir",
default="./staticSelection... |
def expand(code):
char = ''
code = search_funcs(code)
check_loop()
code = list(code)
ret = []
c = 0
while c < len(code):
if code[c].isdecimal():
num = is_decimal(code, c)
del code[c:num[1]]
if int(num[0], 10) == 0:
del code[c - 1]
... | The code simulates a path on a 3x3 grid based on movement commands ('F', 'L', 'R'), expanding the grid when the path reaches edges. It tracks direction and position, updates the grid with '1's for each move, adjusts direction, and formats the final grid state into a string with rows separated by line breaks. | def execute(code):
func.clear()
ex_code = expand(code)
grid = np.zeros((3, 3))
grid[1][1] = '1'
cur_dir = 0
cur_pos = [1, 1]
for c in ex_code:
if c == 'F':
if cur_dir == 0:
grid[cur_pos[0]][cur_pos[1] + 1] = 1
cur_pos[1] += 1
if... |
def read_yml(path):
return yaml.load(stream=read_text(path=path), Loader=yamlcore.CoreLoader)
def check_github_workflows_test(test_yml):
res_dir = get_resources_dir()
expected_test_yml = read_yml(
path=os.path.join(res_dir, "github_workflows_test.yml")
)
diff = dictdiffer.diff(first=expect... | This function checks the presence and structure of GitHub Actions workflows in a specified package directory. It verifies the existence of the `.github/workflows` directory and required YAML files (`test.yml` and `release.yml`). If any are missing, it returns an error. If present, it reads the YAML content and passes t... | def check_github_workflows(pkg_dir):
github_dir = os.path.join(pkg_dir, ".github")
out = {}
if not os.path.isdir(github_dir):
print("E-1BBF: ./.github directory is missing.")
return out
workflows_dir = os.path.join(github_dir, "workflows")
if not os.path.isdir(workflows_dir):
... |
def check_gitignore(pkg_dir):
gitignore_path = os.path.join(pkg_dir, ".gitignore")
if not os.path.isfile(gitignore_path):
print("E-930D: ./.gitignore file is missing.")
return
res_dir = get_resources_dir()
exp_filename = "gitignore_commit_8e67b94_2023-09-10"
exp_path = os.path.join... | The code validates a Python package's structure, files, and metadata. It checks Gitignore, pyproject.toml, requirements.txt, Black formatting, license, setup.py, README badges (GitHub Actions/PyPI), GitHub workflows, and test files. It ensures directory names, package names, and references match, reporting errors for d... | def check_package(pkg_dir):
expected_requires = []
check_gitignore(pkg_dir=pkg_dir)
check_pyproject_toml(pkg_dir=pkg_dir, expected_requires=expected_requires)
check_requirements_txt(
pkg_dir=pkg_dir, expected_requires=expected_requires
)
check_all_python_files_are_black(pkg_dir=pkg_dir)
... |
def extract_panels_demo():
# Extract panelists demographic info
panels_demos = pd.read_csv(os.path.join(BASE_PATH, "ads demos12.csv"))
# Drop these columns as those are supposed to be removed or not helpful
panels_demos.drop(['HH_LANG', 'MICROWAVE', 'device_type', 'ALL_TVS', 'CABL_TVS', 'Hispanic Flag'... | The code extracts and saves panelist demographic data, purchase history, and item information into CSV files, then merges purchase data with item details using a common identifier, storing the combined dataset for further analysis. | def extract_data():
cleaned_path = os.path.join(BASE_PATH, 'cleaned_data')
if not os.path.isdir(os.path.join(cleaned_path)):
os.makedirs(cleaned_path)
print("Extracting panelists demography...")
panels_demos = extract_panels_demo()
panels_demos.to_csv(f"{cleaned_path}/panels_demos.csv", ind... |
def feedback_vw(self, pose):
pose_relative = self.PoseRelative(self.target_pose, pose)
dr = math.sqrt(pose_relative[0]**2 + pose_relative[1]**2)
if (dr<0.0001):
return 0,0
sigma = self.mod_angle(math.atan2(pose_relative[1], pose_relative[0]))
theta = self.mod_angle(si... | This code predicts a robot's trajectory and control inputs (velocity/rotation) over time until reaching a target. It iteratively calculates next states using feedback control, appends results to lists, and stops when proximity to the target is within a threshold distance. | def predict(self, t = 0.1):
self.trajectory_predict = []
self.control_predict = []
temp_pose = self.current_pose
for i in range(1000):
temp_v, temp_w = self.feedback_vw(temp_pose)
current_x,current_y,current_angle = self.predict_onestep(temp_v,... |
def find_new_path(self):
d_path = self.find_path()
grid = self.__continuous_graph.grid
c_path = []
for point in d_path:
x, y = point
c_path.append((float(x)*grid + 0.5*grid, float(y)*grid + 0.5*grid))
self.__residual_path = c_path
print('new path'... | The code updates a path by checking if a residual path exists. If not, it finds a new path; if it exists, it checks safety and replaces it if unsafe. It then smooths the residual path and prints 'BUMPED' if the path has only one element, indicating a collision or abrupt stop. | def update(self):
if not self.__residual_path:
self.find_new_path()
else:
self.find_residual_path()
if not self.residual_path_is_safe():
self.find_new_path()
self.find_residual_path()
self.smooth_path()
if len(self.__residual_pa... |
def validate_selected_record_for_modification(self) -> Optional[str]:
"""Validates if a record is selected
for modification and returns its ID."""
purchase_id = self.view.tree.focus()
if not purchase_id:
showinfo("Info", "You must select a record to modify.")
self... | The code's main task is to prepare a form for modifying a selected record by validating the record's existence, loading its data into the form, and handling errors such as invalid data or unexpected exceptions, which trigger error messages and cancel the operation if necessary. | def modify(self) -> None:
"""Prepares the form for modifying the selected record."""
try:
purchase_id = self.validate_selected_record_for_modification()
if purchase_id is None:
self.cancel()
return
self.load_data_into_form(purchase_id)... |
def filter_complaint_data(zone_set="North Manhattan") -> DataFrame:
# Grab taxi data of a specific zone
complaint_data: DataFrame = global_complaint_data.copy()
# Sort data on datetime
complaint_data = complaint_data.sort_values("Created Date")
return complaint_data
def determine_outliers(datafram... | The main task of the code is to generate and update a time pattern plot of complaint data based on selected zones, days, and outlier detection. It highlights outliers by adjusting trace opacity, allows user interaction to emphasize specific lines, and caches the updated figure for reuse. The function filters data, iden... | def selected_day_of_week(
selected_day, selected_zoneset, number_of_neighbors, selected_lines
):
if selected_day is None or selected_zoneset is None or number_of_neighbors is None:
raise PreventUpdate()
ctx = dash.callback_context
# Check if the callback was triggered by selecting a marker
... |
def filter_complaint_data(zone_set="North Manhattan") -> DataFrame:
dates_to_match = []
# Grab taxi data of a specific zone
complaint_data: DataFrame = global_complaint_data[
global_complaint_data["zone set"] == zone_set
].copy()
mask = complaint_data["Closed Date"].dt.year == YEAR_SELECTO... | The function `adjusted_input_parameters` processes complaint and traffic data to identify outliers using LOF (Local Outlier Factor) for each day of the week. It filters data, computes daily outliers, combines results into a structured dataframe, generates line and violin plots for visualization, and saves outlier data ... | def adjusted_input_parameters(
selected_zoneset, number_of_neighbors_complaints, number_of_neighbors_traffic
):
if (
selected_zoneset is None
or number_of_neighbors_complaints is None
or number_of_neighbors_traffic is None
):
raise PreventUpdate()
global NUMBER_NEIGHBORS... |
def filter_complaint_data(zone_set="North Manhattan") -> DataFrame:
dates_to_match = []
for week_number in range(1, last_week_of_a_year(2018) + 1):
dates_to_match.extend(dates_of_particular_week(2018, week_number))
# Grab taxi data of a specific zone
complaint_data: DataFrame = global_complain... | The main task of this code is to generate and update a time-series line plot visualizing complaint data for selected zones and days, highlighting outliers using LOF analysis. It handles user interactions like marker clicks to dynamically adjust line emphasis, filters data based on inputs, and caches the updated figure ... | def selected_day_of_week(
selected_day, selected_zoneset, number_of_neighbors, selected_lines
):
if selected_day is None or selected_zoneset is None or number_of_neighbors is None:
raise PreventUpdate()
ctx = dash.callback_context
# Check if the callback was triggered by selecting a marker
... |
def _parse_orders_csv(self):
"""Parse the orders.csv file into a dataframe
Returns
-------
pandas.DataFrame
The DataFrame containing the relevant data from orders.csv
"""
# Storage variables
order_ids = []
customer_ids = []
ve... | The main task of the code is to retrieve and parse data from multiple CSV files into structured formats. It extracts order data into a DataFrame, fetches corresponding order lines using order IDs, and parses commissions, product promotions, and general promotions into dictionaries for subsequent processing and analysis... | def _get_data(self):
"""Retrieve the neccessary data from the files"""
self.order_csv_df = self._parse_orders_csv()
self.order_lines_csv_df = self._parse_order_lines_csv(list(self.order_csv_df['order_id'].values))
self.commissions_dict = self._parse_commissions_csv()
self.produc... |
def show_all_connections(filename: Path) -> None:
"""Display all database connections found in shared.xml."""
if filename.exists():
connections = read_shared_xml(filename)
table = Table(
"Connection Name",
show_header=True,
header_style=show_style,
... | This function displays information about a shared.xml file. It can list all database connections, show details of a specific connection, or display the file's path. The task involves parsing command-line arguments to determine which action to perform and executing the corresponding operations like validation or data re... | def shared(
filepath: Optional[Path] = typer.Option(
default_path,
"--path",
show_default=True,
help="Path to your shared.xml file",
),
list_connections: bool = typer.Option(
False,
"--list-connections",
is_flag=True,
help="Display list of all ... |
def manage_health(self, cell):
entity = cell.entity
nutrient = cell.nutrient
pos = cell.pos
if entity.health < 100:
needed_nutrients = entity.size
if nutrient:
new_level = nutrient.nutrient_level - needed_nutrients
#self.logger.in... | This function manages an entity's progression by checking maturity, finding a new position, and attempting breeding or movement. It updates the land and processed rows if the entity moves, ensuring valid conditions like nutrient availability and neighbor counts are met. The function returns the resulting child entity i... | def post_entity_progress(self, cell, neighbor_cells):
pos = cell.pos
entity = cell.entity
child = None
self.manage_health(cell)
neighbors = list(Cell.extract_entity_cells(neighbor_cells))
if len(neighbors) < 4 and entity.age >= entity.mature_age:
new_pos = s... |
def boot_up(self):
self.user_home_dir = os.path.expanduser("~")
if os.name == 'nt': # Windows
self.windows_boot()
elif os.name == 'posix':
# TODO : add Mac OS support
pass
else:
pass
self.last_update = StringVar()
self.las... | This code initializes a GUI application using Tkinter, setting up a window with specific dimensions and position. It defines event handlers, initializes UI components like progress bars and treeviews, and prepares the application's structure through boot_up(), build(), and post_build() methods before launching the main... | def __init__(self):
self.events_we_need = [
'Scan', 'FSSAllBodiesFound', 'FSSDiscoveryScan',
'FSDJump', 'ApproachBody'
]
self.last_load_label: Label = None
self.last_update = None
self.journal_tree_scroll: Scrollbar = None
self.user_home_dir = Non... |
def a_star_planner(self, goal: np.ndarray, start=np.array([0, 0]), debug=False) -> None:
"""
This function will generate a path from location start to location goal. It will generate a plan
that avoids obstacles by planning over the provided map in self.map
self.map is a 2D matrix provi... | The code processes odometry data to navigate a drone through predefined waypoints using a PD controller. It initializes hover, plans paths with A* algorithm, adjusts velocity based on position errors, and manages height control. The drone follows planned paths, updates waypoints upon reaching targets, and handles orien... | def odom_callback(self, msg: any) -> None:
"""
this callback function will take in the odometry to determine where we are in space. We will use
these to set the actuations in a PD controller for x, y, and z position
# Considerations: We now have height data. Do we control of the given h... |
def _user_has_chosen_deck(self, mouse_pos):
width, height = CARD_SIZE
x, y = mouse_pos.x, mouse_pos.y
fits_y = DECK_POSITION.y - height // 2 < y < DECK_POSITION.y + height // 2
fits_x = DECK_POSITION.x - width // 2 < x < DECK_POSITION.x + width // 2
return fits_y and fits_x
def... | The main task of the code is to handle user input during their turn in a game. It checks mouse movements to determine if the user is clicking on the deck to draw a card, selecting a playable card, or pressing the skip button. The function updates game state flags (e.g., card availability, turn progression) based on val... | def _check_user_input(self):
rel = pg.mouse.get_rel() # we need these three lines, so that if we click mouse once it won't make 100 events of it
if math.fabs(rel[0]) < 1 and math.fabs(rel[1]) < 1:
return
if self.current_player_move == USER:
mouse_pos = Point(*pg.mouse.g... |
def _ai_find_best_sequence_to_cover_six(self, six_suit):
max_sequence = self._ai_find_max_rank_sequence(six_suit)
for card in self.deck.agent_cards:
if card.rank == Rank.six and card.suit != six_suit:
new_best_sequence = self._ai_find_max_rank_sequence(card.suit)
... | This method determines if the AI can play additional cards ("through up") alongside the current card. If the current card is a six, it identifies the best sequence to cover it. Otherwise, it selects the highest-value card of the same rank as the current card to play, or ends the move if no matching cards exist. The goa... | def _ai_through_up_all_possible_cards(self):
"""
This method checks if we can through up any cards, and if not finishes the Agent move.
By through up, I mean put additional cards, like:
I have three cards: 9 spades 9 diamonds and 9 hearts, so I can make a move with 9 spa... |
def _ai_get_all_possible_moves(self):
moves = []
for card in self.deck.agent_cards:
if self.can_make_move(card):
if card.rank != Rank.six or self._ai_can_cover_six(card.suit): # if we have a Six, but we have nothing to "cover" it, we won't through this Six
... | This function determines the AI agent's next move by checking available moves. If none exist and a new card can be drawn, it does so recursively. If still no moves, it finishes. Otherwise, it evaluates all possible moves, selects the highest-value one using a scoring function, and executes it. | def _ai_decide_which_move_to_make(self):
"""
The function, that decides which move Agent is going to make.
"""
ai_has_any_moves = len(self._ai_get_all_possible_moves()) # checking if there are any moves Agent can make
if self.can_get_new_card and not ai_has_any_moves:
... |
def _check_if_game_is_over(self):
if len(self.deck.agent_cards) == 0 or len(self.deck.user_cards) == 0:
self._draw_game_over(self.current_player_move)
self.game_is_over = True
def _check_user_input(self):
rel = pg.mouse.get_rel() # we need these three lines, so that if we click ... | The main task of the code is to run a game loop that checks game status, processes user input, updates animations, renders game elements (cards, sprites, buttons), and manages AI decisions for the agent's moves, ensuring smooth gameplay and display updates at a set FPS. | def main_loop(self):
while True:
self._check_if_game_is_over()
self.is_animating = len(self.sprite_moves) != 0
for event in pg.event.get():
if event.type == pg.QUIT:
exit()
elif not self.is_animating and event.type == pg.MO... |
def parse_to_operation_tree(tree_data):
root_id = min(list(tree_data.keys()))
return parse_operation_node(tree_data, root_id)
def serialize_operation_tree(operation_tree_node):
out = {}
if operation_tree_node.node_type == 'operation':
out[operation_tree_node.operation] = {}
for i, operan... | The code processes a JSON file containing operation tree data, parsing it into an operation tree structure. Depending on the specified method (--optree or --smt), it either serializes the tree to JSON or generates an SMT formula, printing the result. The script validates input arguments and raises exceptions for invali... | def main(args):
if len(args) < 2:
raise Exception('Expected arguments: (--optree | --smt) path')
method = args[0]
tree_path = Path(args[1])
with open(tree_path, 'r') as tree_f:
tree_data = json.loads(tree_f.read())
operation_tree = parse_to_operation_tree(tree_data)
if method == ... |
def ntid_th(list_peaks, value_peaks, meas_window=[1.3,2.90],
delta=0.1, main_peak_factor=10):
'''
Identifies possible chiralities for a given list of peaks in
a fixed measurement window, based on Kataura predictions.
Uses only the first two peaks. Uses only the first peak if the second is
... | The function `ntid_exp` identifies potential chiralities by comparing theoretical peak predictions (from Kataura plots) with experimental data. It filters candidates generated by `ntid_th`, ensuring all expected transitions from experimental data fall within a specified measurement window and match detected peaks withi... | def ntid_exp(list_peaks, value_peaks, meas_window=[1.3,2.9],
delta_th=0.1, delta_exp=0.05, main_peak_factor=10):
'''
Identifies possible chiralities for a given list of peaks
in a fixed measurement window, based on kataura predictions,
then compares with the experimental data from
h... |
def new_article_check(latest_article):
print("Checking for new article")
check_source = urllib.request.urlopen('https://playoverwatch.com/en-us/blog/').read()
check_soup = BeautifulSoup(check_source, 'html5lib')
check_article = check_soup.find(class_='link-title')
if latest_article != check_article:... | The main task of the code is to continuously monitor for new updates from a source (e.g., a Telegram bot), check for new articles, and process them. It initializes a database, sets up a scheduler to run the article-checking function hourly, and uses a loop to poll for updates every 0.5 seconds, updating the last proces... | def main():
db.setup()
last_update_id = None
new_article_check(latest_article)
scheduler = BackgroundScheduler()
scheduler.add_job(lambda: new_article_check(latest_article), 'interval', seconds=3600)
scheduler.start()
while True:
print ("Getting updates...")
updates = get_upd... |
def load_movie(self):
movie_filename = filedialog.askopenfilename(initialdir=self.__initialdir_movie,
title="Select the movie to play",
filetypes=(("AVI files", "*.AVI"),
... | This method constructs a GUI widget with a main panel, progress bar, and control buttons based on the 'setup' dictionary. It creates a black-themed interface with video/image controls (play, pause, stop, camera, load image), an algorithm execution button, and a frame counter. The layout includes a resizable canvas for ... | def _build_widget(self, parent: ttk.Frame=None, setup: dict=dict):
if parent is None:
self.master.geometry("700x500+0+0")
self.main_panel = Frame(self.master, relief=SUNKEN)
self.main_panel.place(relx=0.1, rely=0.1, relwidth=0.8, relheight=0.8)
else:
sel... |
def fillHashandBloom(self):
for x in range(self.n_items_to_generate):
self.hashTable.set(self.word_present[x], self.word_present[x])
random_address = self.randomizeAddresses(x)
self.add2Bloom(self.word_present[x], random_address)
self.add_to_multi_instance_bloom(s... | The code runs a test to evaluate Bloom filter (BF) and hash table (HT) performance by checking word presence, calculating metrics like false positives, load factors, bit array sizes, and hash counts, then returns a dictionary with results including elements found in BF/HT, multi-BF statistics, and system properties. | def run_test(self):
"""
run the test with respect to class properties
:param self:
:return:
"""
res_dict = dict()
# res_dict["Word Length"] = self.word_length
res_dict["Items Num"] = self.n_items_to_generate
# res_dict["Bits Num"] = self.bfluf_m_addre... |
def pre_process_data() -> Tuple[np.ndarray, np.ndarray]:
# unpickle all of the CIFAR data and convert to numpy arrays
X_train, y_train, X_test, y_test, X_val, y_val = get_cifar_10_data(validation_size = 0.20)
print('## Numpy Array Shapes ##')
print('Train data shape: ', X_train.shape)
print('Train ... | This code benchmarks a machine learning model by evaluating its performance on training, validation, and test datasets. It loads a pre-trained model, processes data, generates ROC curves and PR curves for multi-class classification, and saves visualizations. The script uses command-line arguments to specify the model p... | def main():
parser = argparse.ArgumentParser()
parser.add_argument('--model_folder', required = True, type = Path,
help = 'The folder for the model you want to benchmark.')
parser.add_argument('--save_plot_path', required = False, type = Path,
help = 'Path for... |
def create_model_name_and_dir(self):
"""Create a directory for new trained model and associated files."""
self.model_path = utils.create_dir(
self.config["min_rep"], self.config["min_num_inst"],
self.config["num_hidden_layers"], self.config["regularizers"],
self.times... | This code trains the NVC model by creating embedding/label matrices, configuring callbacks (metrics, early stopping), splitting data (with cross-validation or conventional splits), building/compiling the model, training via Keras' fit(), saving the model, and evaluating performance. It supports class weighting, cross-v... | def train(self, inspect_concept=False):
"""Train the NVC model.
Args:
inspect_concept: bool or str
Inspect a given concept with all instances.
"""
self.create_model_name_and_dir()
# create two matrices: one for the instances and one... |
def get_table_sql(table_name, schema, wrds_id=None,
fpath=None, drop=None, keep=None, rename=None,
return_sql=True,
alt_table_name=None, col_types=None, sas_schema=None):
if not alt_table_name:
alt_table_name = table_name
... | This function imports data from WRDS into PostgreSQL, creating schemas/roles if needed. It generates SQL to drop/recreate tables, handles data transformations (fixing missing/CR issues), and loads data via WRDS processes. Parameters control schema, table names, data fixes, and permissions. | def wrds_to_pg(table_name, schema, engine, wrds_id=None,
fpath=None, fix_missing=False, fix_cr=False,
drop=None, obs=None, rename=None, keep=None, where=None,
alt_table_name = None, encoding=None, col_types=None, create_roles=True,
sas_schema=None, sas_encodi... |
def get_table_comment(table_name, schema, engine):
if engine.dialect.has_table(engine.connect(), table_name, schema=schema):
sql = f"""SELECT obj_description('"{schema}"."{table_name}"'"""
sql += "::regclass, 'pg_class')"
with engine.connect() as conn:
res = conn.execute(text(sq... | The function `wrds_update` updates a PostgreSQL table using WRDS SAS data, handling parameters for database connection, data transformation (e.g., dropping/renaming variables), and permissions. It checks if the WRDS data is newer, imports it into PostgreSQL, sets metadata, and manages roles for access control. Optional... | def wrds_update(table_name, schema,
host=os.getenv("PGHOST"),
wrds_id=os.getenv("WRDS_ID"),
dbname=os.getenv("PGDATABASE"),
engine=None,
force=False,
fix_missing=False, fix_cr=False, drop=None, keep=None,
... |
def get_pq_file(table_name, schema, data_dir=os.getenv("DATA_DIR")):
data_dir = os.path.expanduser(data_dir)
if not os.path.exists(data_dir):
os.makedirs(data_dir)
schema_dir = Path(data_dir, schema)
if not os.path.exists(schema_dir):
os.makedirs(schema_dir)
pq_file = ... | The function updates a local Parquet file from a WRDS SAS table by downloading data, converting it to Parquet, and saving it, with options to control processing steps like fixing missing values, specifying variables to keep/drop, and handling encoding. It checks if an update is needed based on timestamps and forces upd... | def wrds_update_pq(table_name, schema,
wrds_id=wrds_id,
data_dir=os.getenv("DATA_DIR"),
force=False,
fix_missing=False,
fix_cr=False, drop=None, keep=None,
obs=None, rename=None,
wh... |
def get_modified_str(table_name, sas_schema, wrds_id=wrds_id,
encoding=None, fpath=None):
contents = proc_contents(table_name, sas_schema, wrds_id, fpath, encoding)
if len(contents) == 0:
print(f"Table {sas_schema}.{table_name} not found.")
return None
modified = "... | The function updates a local gzipped CSV file from a WRDS table, ensuring it matches the latest WRDS SAS data. It checks if the local file is current, downloads updates if needed, and allows customization via parameters like variable filtering, renaming, encoding, and schema settings. Returns True if the CSV was update... | def wrds_update_csv(table_name, schema,
wrds_id=os.getenv("WRDS_ID"),
data_dir=os.getenv("CSV_DIR"),
force=False, fix_missing=False, fix_cr=False,
drop=None, keep=None, obs=None, rename=None,
where=None, alt_table_nam... |
def _match_anime(self, episode: Episode, results) -> dict:
title = episode.fmt_str(include_episode_number=False, delimiter=" ")
sequence_matcher = SequenceMatcher(
isjunk=None,
a=None,
b=self._prepare_string_for_comparison(title),
)
for anime in result... | The main task of the code is to update an episode object with AniList data by querying the AniList GraphQL API. It searches for an anime matching the episode's title, retrieves details, and links the episode to the corresponding AniList entry. If no match is found, it falls back to TMDB to search for entries, construct... | def update_episode_with_anilist_data(self, episode: Episode):
query = """
query ($search: String) {
anime: Page(perPage: 2) {
results: media(type: ANIME, search: $search) {
id
title {
romaji
... |
def clean_extracted_dir() -> None:
clean_dir(EXTRACTED_DIR)
def extract_file(path: Path) -> None:
path = path.as_posix()
if (not is_zipfile(path)):
raise ValueError("Bad argument passed, expected path to zip file")
with ZipFile(path, "r") as zip:
zip.extractall(EXTRACTED_DIR)
def sanitiz... | This function processes a file by verifying its existence, cleaning and extracting its contents, building LaTeX dependencies, and generating a PDF using the 'laton' tool, handling errors and outputs during the process. | def process_file(path: Path) -> None:
if (not path.exists()):
raise FileNotFoundError("No such file found")
clean_extracted_dir()
extract_file(path)
sanitize_extracted_dir()
dependency_chain = build_latex_dependency_chain(EXTRACTED_DIR)
# print(dependency_chain)
args = shlex.split(f"... |
def das(self):
das_request = self.trimmed_requestline() + '.das'
ret = requests.get(das_request)
return ret.text
def trimmed_requestline(self):
request_line = self.opendap_request_line()
request_line = request_line.replace('.citation', '')
request_line = request_line.repl... | The main task of the code is to generate a plain text citation by creating a Citation object, populating it with data from `self.das()`, adding metadata like a URL derived from the request line, incorporating subset parameters, and returning the formatted citation text. | def citation(self):
cherrypy.response.headers['Content-Type'] = 'text/plain'
citation = Citation()
citation.from_das(self.das())
citation.meta['url'] = self.trimmed_requestline() + '.html'
citation.add_subset_param_dict(self.subset_params())
return citation.as_text() |
def fetch_opendap_response(self):
opendap_url = self.opendap_request_line()
ret = requests.get(opendap_url)
return ret
def set_opendap_url(self):
opendap_url = cherrypy.request.params['opendap_url']
cherrypy.session['opendap_url'] = opendap_url
def fullpage(self):
... | This code handles HTTP GET requests to serve data, HTML, or citations based on URL parameters and query strings. It checks file extensions, redirects for citations, processes OpenDAP URLs, and returns appropriate responses like ASCII, DODS, or citation data. It uses CherryPy for routing and session management, ensuring... | def GET(self, *args, **kwargs):
"""
Overwrites the GET method.
Returns either citation, html or data
Keyword arguments:
param args: arguments before '?' (separated by '/')
param kwargs: arguments after '?' (separated by ';')
"""
ex... |
def _attribute_cell(self, var_doc):
# Construct the label
label = var_doc.name
type_descr = (self._type_descr(var_doc) or
self._type_descr(var_doc.value))
if type_descr: label += ': %s' % type_descr
# Get the URL
try: url = self.linker.url_for(var_do... | The main task of the code is to generate an HTML label for a node, incorporating its class name, context, attributes, operations, and qualifiers. It dynamically constructs the label by truncating long lists, handling collapsed states, and formatting elements using templates. The output includes background color, contex... | def _get_html_label(self):
# Get the class name & contextualize it.
classname = self.class_doc.canonical_name
if self.context is not None:
classname = classname.contextualize(self.context.canonical_name)
# If we're collapsed, display the node as a single box.
if self... |
def get_dot_version():
global _dot_version
if _dot_version is None:
try:
out, err = run_subprocess([DOT_COMMAND, '-V'])
version_info = err or out
m = _DOT_VERSION_RE.match(version_info)
if m:
_dot_version = [int(x) for x in m.group(1).split... | The `to_html` method generates HTML code to display a graph with a client-side image map, enabling interactive elements. It constructs the HTML by combining an image URL, a map of clickable regions (cmapx), and formatting elements like titles and captions. The method adapts to different versions of the `dot` tool, ensu... | def to_html(self, directory, center=True, size=None):
"""
Return the HTML code that should be uesd to display this graph
(including a client-side image map).
:param image_url: The URL of the image file for this graph;
this should be generated separately with the `write()` me... |
def get_dot_version():
global _dot_version
if _dot_version is None:
try:
out, err = run_subprocess([DOT_COMMAND, '-V'])
version_info = err or out
m = _DOT_VERSION_RE.match(version_info)
if m:
_dot_version = [int(x) for x in m.group(1).split... | This function generates a visual hierarchy graph of Python packages and their submodules using the `DotGraph` format. It constructs nodes for each module, connects them with edges representing submodule relationships, and applies styling options like layout direction and spacing. The graph can be rendered in UML style ... | def package_tree_graph(packages, linker, context=None, **options):
"""
Return a `DotGraph` that graphically displays the package
hierarchies for the given packages.
"""
if options.get('style', 'uml') == 'uml': # default to uml style?
if get_dot_version() >= [2]:
return uml_packag... |
def _add_class_tree_superclasses(graph, classes, mknode, mkedge, linker,
context, options, cls2node):
exclude = options.get('exclude', ())
# Create nodes for all bases.
for cls in classes:
for base in cls.mro():
# Don't include 'object'
if ba... | This function generates a class hierarchy graph by adding superclasses, subclasses, and inheritance edges using customizable node/edge creation callbacks. It configures graph direction, tracks truncated subclasses, and leverages helper functions to build the visual tree structure representing class relationships accord... | def _class_tree_graph(graph, classes, mknode, mkedge, linker,
context, options, cls2node):
"""
A helper function that is used by both `class_tree_graph()` and
`uml_class_tree_graph()` to draw class trees. To abstract over
the differences between the two, this function takes two ca... |
def prepare_output_directory(output_directory: str) -> None:
""" Ensures an empty output directory is available"""
if os.path.exists(output_directory):
shutil.rmtree(output_directory)
os.makedirs(output_directory)
def __local_file(self):
"""Downloads file if at a remote URL
"""
... | The code processes a MIDI file by converting it to WAV tracks, generating MP3s from the WAVs, and optionally cleaning up temporary files based on configuration settings. | def split(self):
output_directory = self.config["output_directory"]
prepare_output_directory(output_directory)
converted_midifile_path = check_format(
self.__local_file(), output_directory
)
self.__separate_tracks_into_wavs(converted_midifile_path)
create_mp3s... |
def increment():
for i in range(n):
for j in range(n):
m[i][j] += 1
def find_flash():
for i in range(n):
for j in range(n):
if m[i][j] is not None and m[i][j] >= 10:
return (i, j)
return None
def flash(x, y):
m[x][y] = None
for (i, j) in neighb... | The main task of the code is to count the number of flashes detected by repeatedly calling find_flash() until none are found, incrementing a counter each time a flash is processed, then resetting the system and returning the total count. | def step():
increment()
stop = False
c = 0
while True:
r = find_flash()
if r is None:
break
flash(r[0], r[1])
c += 1
reset()
return c |
def inc(self):
if (self.index < (self.numFrames - 1)):
self.index = self.index + 1
def dec(self):
if self.index >= 1:
self.index = self.index - 1
def update_win_adsr(self):
self.draw()
routeWin.draw()
# if a (slider) control just moved that would change AD... | This code handles mouse motion events to adjust parameters based on cursor movement. It increments or decrements values (via self.inc() and self.dec()) depending on vertical/y-axis movement, and modifies a 'fraction' value for specific controls (Feedback, Freq, Ratio) based on horizontal/x-axis movement. It updates the... | def motion(self, event):
newFrame = False
ctrl = self.keyname.split(':')[1]
if event.y < self.prevy:
diff = self.prevy - event.y
for n in range(diff):
self.inc()
newFrame = True
if event.y > self.prevy:
diff = event.y - se... |
def inc(self):
if (self.index < (self.numFrames - 1)):
self.index = self.index + 1
def dec(self):
if self.index >= 1:
self.index = self.index - 1
def update_win_adsr(self):
self.draw()
routeWin.draw()
# if a (slider) control just moved that would change AD... | This function handles mouse button clicks to modify values and update a UI element. Left-click (event.num=1) increments a value, while right-click (event.num=3) either decrements a value or toggles a character index (adding/subtracting 100). If changes occur, it triggers an update to the ADSR window display through `up... | def button_click(self, event):
update = False
if event.num == 1:
self.inc()
update = True
if event.num == 3:
ctrl = self.keyname.split(':')[1]
if ctrl[:3] != "chr":
# right click on most controls is decrement by 1
se... |
def inc(self):
if (self.index < (self.numFrames - 1)):
self.index = self.index + 1
def dec(self):
if self.index >= 1:
self.index = self.index - 1
def update_win_adsr(self):
self.draw()
routeWin.draw()
# if a (slider) control just moved that would change AD... | This code handles mouse wheel events to adjust values: scrolling up increments a value (self.inc()), scrolling down decrements it (self.dec()), and triggers an update of ADSR parameters (self.update_win_adsr()) when either action occurs. The delta value determines direction, with positive values indicating upward scrol... | def mouse_wheel(self, event):
# by inspection I have found that event.delta=120 for one wheel move up and -120 for one down
# but the 120 thing is apparently Windows only so actually just treat +ve as up and -ve as down...
update = False
if event.delta > 0:
self.inc()
... |
def inc(self):
if (self.index < (self.numFrames - 1)):
self.index = self.index + 1
def dec(self):
if self.index >= 1:
self.index = self.index - 1
def update_win_adsr(self):
self.draw()
routeWin.draw()
# if a (slider) control just moved that would change AD... | The code handles a Shift-MouseWheel event to adjust a 'fraction' parameter horizontally. Depending on the 'ctrl' value (Feedback, Freq, Ratio, etc.), it increments/decrements the fraction within specific bounds. If the fraction changes, it triggers an update to the ADSR window via `update_win_adsr()`, enabling dynamic ... | def mouse_wheelx(self, event):
# This is the Shift-MouseWheel event which is horizontal and will be used for fractions
newFrame = False
ctrl = self.keyname.split(':')[1]
if event.delta > 0:
if ctrl == "Feedback":
if self.fraction < 9:
self.... |
def run_step(self, batch, cond, is_valid=False):
losses = self.forward_backward(batch, cond, is_valid)
took_step = self.mp_trainer.optimize(self.opt, self.step + self.resume_step)
if took_step:
self._update_ema()
self._anneal_lr()
if self.lr_anneal_steps == 0:
... | The code implements a training loop for a machine learning model, iterating over data batches to compute losses, validate performance, update model parameters, and manage early stopping based on patience. It logs metrics, saves checkpoints at intervals or on best performance, generates and logs sample images, and termi... | def run_loop(self, sampler_fn=None, sample_params=None):
with tqdm(total=self.max_train_steps - self.resume_step) as pbar:
while (
not self.lr_anneal_steps
or self.step + self.resume_step < self.lr_anneal_steps
) and self.patience > 0:
batc... |
def policyEvaluation(policy, U):
while True:
nextU = [[0, 0, 0, 1], [0, 0, 0, -1], [0, 0, 0, 0], [0, 0, 0, 0]]
error = 0
for r in range(NUM_ROW):
for c in range(NUM_COL):
if (r <= 1 and c == 3) or (r == c == 1):
continue
nextU[r... | The code performs policy iteration for a reinforcement learning problem, iteratively evaluating the policy to update utility values (U) and improving the policy by selecting the optimal action for each state. It skips specific terminal states, updates the policy if a better action is found, and repeats until the policy... | def policyIteration(policy, U):
print("During the policy iteration:\n")
while True:
U = policyEvaluation(policy, U)
unchanged = True
for r in range(NUM_ROW):
for c in range(NUM_COL):
if (r <= 1 and c == 3) or (r == c == 1):
continue
... |
def move_peon_jump_diagonal_rigth(self, jumpPeonsDiagonalRigthValid):
#Function that diagonal jump an enemy peon and select
#the closest peon to opponent's frontier
if self.requestData["data"]["side"] == "N":
sideIsNorth = True
else:
sideIsNorth ... | The function validates diagonal jumps for a player's peons by checking wall positions and opponent/ally pieces, filtering valid right/left diagonal moves, and returning the appropriate jump method or falling back to vertical movement validation if no diagonal jumps are possible. | def valid_diagonal_jump(self, myPeons, enPeons, jumpPeonsDiagonal, freePeonsVertical, wallsH, wallsV):
#Validations of the diagonal jumps movements
if self.requestData["data"]["side"] == "N":
sideIsNorth = True
else:
sideIsNorth = False
jumpPeon... |
def move_peon_jump_diagonal_up(self, jumpPeonsDiagonalUpValid):
if self.requestData["data"]["side"] == "N":
sideIsNorth = True
else:
sideIsNorth = False
from_row = jumpPeonsDiagonalUpValid[0][0]
from_col = jumpPeonsDiagonalUpValid[0][1]
t... | The function validates diagonal jumps for a peon based on the player's side (North or not), checking if target positions are unoccupied and not blocked by horizontal walls. It separates valid upward and downward diagonal moves, adjusts lists by removing invalid positions, and prioritizes upward jumps. If invalid, it de... | def valid_diagonal_jump(self, myPeons, enPeons, jumpPeonsDiagonal, freePeonsHorizontal, wallsH, wallsV):
if self.requestData["data"]["side"] == "N":
sideIsNorth = True
else:
sideIsNorth = False
jumpPeonsDiagonalUpValid = []
jumpPeonsDiagonalDownV... |
def valid_diagonal_jump(self, myPeons, enPeons, jumpPeonsDiagonal, freePeonsVertical, wallsH, wallsV):
#Validations of the diagonal jumps movements
if self.requestData["data"]["side"] == "N":
sideIsNorth = True
else:
sideIsNorth = False
jumpPeon... | The code validates vertical jump moves for game pieces, checking for wall collisions and enemy positions. It distinguishes between valid vertical jumps and diagonal jumps, prioritizing jumps over regular moves. If no valid jumps exist, it delegates to diagonal validation or standard vertical movement functions. | def valid_vertical_jump(self, myPeons, enPeons, jumpPeonsVertical, freePeonsVertical, wallsH, wallsV):
#Validations of the vertical jumps movements
if self.requestData["data"]["side"] == "N":
sideIsNorth = True
else:
sideIsNorth = False
... |
def valid_diagonal_jump(self, myPeons, enPeons, jumpPeonsDiagonal, freePeonsHorizontal, wallsH, wallsV):
if self.requestData["data"]["side"] == "N":
sideIsNorth = True
else:
sideIsNorth = False
jumpPeonsDiagonalUpValid = []
jumpPeonsDiagonalDownV... | This function validates horizontal jumps for a game piece, checking if a move is possible without hitting walls or other pieces. It separates valid horizontal jumps from diagonal ones, prioritizing jumps over moves. If no valid horizontal jumps exist, it delegates to diagonal validation or standard horizontal movement. | def valid_horizontal_jump(self, myPeons, enPeons, jumpPeonsHorizontal, freePeonsHorizontal, wallsH, wallsV):
if self.requestData["data"]["side"] == "N":
sideIsNorth = True
else:
sideIsNorth = False
jumpPeonsHorizontalValid = []
jumpPeonsDiagonal ... |
def generationPioson(self,n):
for i in range(n):
x, y = self.generationXY()
self.poison.append(Object(x,y,"POISON",POISON))
def generationWalls(self,n):
for i in range(n):
x, y = self.generationXY()
self.walls.append(Object(x,y,"WALL",WAll))
def generation... | The code's main task is to initialize a game environment by generating poison, walls, bots, and food elements using provided parameters. It calls four methods—generationPioson, generationWalls, generationBots, and generationFood—to place these objects on a grid, likely for a simulation or game. Each method processes it... | def generationAll(self,poison,walls,bots,food):
self.generationPioson(poison)
self.generationWalls(walls)
self.generationBots(bots)
self.generationFood(food) |
def new_record():
add_date()
add_event()
add_distance()
add_time()
add_pace()
add_elevation()
add_equipment()
while True:
confirm_record()
if verify.upper() == 'Y':
add_new_record(list)
break
else:
edit_record()
cont... | The main task of the code is to display a styled menu for managing records (add, edit, delete, view, exit) and handle user selections by calling corresponding functions to perform database operations. It uses a loop for persistent menu access, color formatting for visual clarity, and conditional logic to route actions ... | def home_menu():
while True:
print(
Fore.CYAN+Style.BRIGHT +'''
+------------------------+
|'''+Fore.WHITE+''' HOME MENU '''+Fore.CYAN+Style.BRIGHT+'''|
+-----+------------------+
|'''+Fore.WHITE+''' 1 '''+Fore.CYAN+Style.BRIGHT+'''|'''+Fore.WHITE+''' ADD A RE... |
def get_puntata(client: gspread.Client, number: int) -> Puntata:
puntate = get_puntate(client)
puntate_filtered = [puntata for puntata in puntate if puntata.numero == number]
return puntate_filtered.pop() if len(puntate_filtered) == 1 else None
def _worksheet_loader(client: gspread.Client, worksheet_title:... | The function retrieves and constructs a `ConcorrentePuntata` object by fetching data from a Google Sheet. It uses the provided `concorrente` and `puntata` to load status flags (eliminated/suspended) and bonus/malus details from worksheet rows, then compiles them into a structured object. The function reuses an existing... | def get_puntata_concorrente(client: gspread.Client, concorrente: Concorrente, puntata: int | Puntata,
wl_concorrente: WorksheetLoader = None) -> ConcorrentePuntata:
"""
Load a ConcorrentePuntata object, given a concorrente and a puntata number
:param client:
:param concorrent... |
def get_puntate(client: gspread.Client) -> list[Puntata]:
wl = _worksheet_loader(client, SHEET_PUNTATE, table_mode=True)
puntate_records = wl.as_records()
return [Puntata.from_sheet(record) for record in puntate_records]
def _worksheet_loader(client: gspread.Client, worksheet_title: str, table_mode: bool =... | The main task of the code is to retrieve and filter all transmitted puntate (betting data) for a specific concorrente (competitor), using a worksheet loader to access their dedicated sheet. It processes each puntata, returning a list of concorrente-specific puntata objects that have been marked as transmitted (is_trasm... | def get_puntate_concorrente(client: gspread.Client, concorrente: Concorrente) -> list[ConcorrentePuntata]:
"""
Load all puntate objects for a given concorrente
:param client:
:param concorrente:
:return:
"""
puntate = get_puntate(client)
wl_concorrente = _worksheet_loader(client, SHEET_... |
def print_version() -> None:
print("git clog version {}".format(__version__))
def gen_git_log() -> Iterator[str]:
master_fd, slave_fd = pty.openpty()
git_log_process = subprocess.Popen(
["git", "--no-pager", "log", "--color=always", "--all", "--graph", "--format=%C(auto)%h%d %s %G?"],
stdout... | The code's main task is to handle command-line arguments, specifically checking for a version flag (-V/--version) to print the version and exit. If no valid argument is provided, it generates a Git log, applies colorization, and prints the result. Errors during log generation or display trigger exits with appropriate c... | def main() -> None:
if len(sys.argv) > 1:
if sys.argv[1] in ("-V", "--version"):
print_version()
sys.exit()
else:
print('Unknown command line argument "{}"'.format(sys.argv[1]))
sys.exit(1)
try:
git_log_generator = gen_git_log()
col... |
def consume(self, expected_token_type, node=None, loc0=None, loc1=None):
if self.current_token is not None and self.current_token.token_type == expected_token_type:
if node != None:
self.add_node(node, loc0, loc1)
self.advance()
return True
else:
... | This code parses a "write" statement by consuming tokens, validates variables, handles parameters, and constructs a node with parsed elements. It checks for syntax correctness, ensures variables are integers, and builds a list representing the write command's structure, including brackets and commas. | def write(self):
self.consume(Token_type.write, 'write statement', 3, -1)
write_list = ['write']
if self.consume(Token_type.open_bracket):
write_list.append('(')
while True:
if self.current_token.token_type == Token_type.string:
if self.consume(Tok... |
def consume(self, expected_token_type, node=None, loc0=None, loc1=None):
if self.current_token is not None and self.current_token.token_type == expected_token_type:
if node != None:
self.add_node(node, loc0, loc1)
self.advance()
return True
else:
... | This code parses a 'readln' statement, validates variable declarations, and constructs a syntax tree node. It checks for the 'readln' keyword, handles parentheses, ensures variables are not redeclared, and records the variable as a string type. If errors occur (e.g., redeclaration), it triggers an error. Otherwise, it ... | def readln(self):
self.consume(Token_type.readln, 'read statement', 3, -1)
read_list = ['readln']
if self.consume(Token_type.open_bracket):
read_list.append('(')
if self.current_token.lex in self.dict_variables.keys():
self.error_found(3)
else:
... |
def consume(self, expected_token_type, node=None, loc0=None, loc1=None):
if self.current_token is not None and self.current_token.token_type == expected_token_type:
if node != None:
self.add_node(node, loc0, loc1)
self.advance()
return True
else:
... | This code parses a 'readint' statement by validating the variable name, ensuring it's undeclared, and constructing a syntax node with the parsed elements including the variable and parentheses, while error-checking and updating the variable dictionary with the new integer-type variable. | def readint(self):
self.consume(Token_type.readint, 'read statement', 3, -1)
read_list = ['readint']
if self.consume(Token_type.open_bracket):
read_list.append('(')
if self.current_token.lex in self.dict_variables.keys():
self.error_found(3)
else:
... |
def consume(self, expected_token_type, node=None, loc0=None, loc1=None):
if self.current_token is not None and self.current_token.token_type == expected_token_type:
if node != None:
self.add_node(node, loc0, loc1)
self.advance()
return True
else:
... | This function parses a 'readchar' statement by validating syntax, checking variable existence, and constructing a syntax tree node. It consumes tokens for 'readchar', handles parentheses, verifies the variable is undeclared, assigns it as a char type, and builds a node with parsed elements like 'readchar', '(', 'Variab... | def readchar(self):
self.consume(Token_type.readchar, 'read statement', 3, -1)
read_list = ['readchar']
if self.consume(Token_type.open_bracket):
read_list.append('(')
if self.current_token.lex in self.dict_variables.keys():
self.error_found(3)
else:
... |
def consume(self, expected_token_type, node=None, loc0=None, loc1=None):
if self.current_token is not None and self.current_token.token_type == expected_token_type:
if node != None:
self.add_node(node, loc0, loc1)
self.advance()
return True
else:
... | This code parses a statement by validating variable types, handling arithmetic and relational operators, and constructing a statement list. It ensures all variables in the statement share the same type, checks for correct operator usage, and builds an abstract syntax tree node for the parsed statement. | def statements(self):
type_list = []
statement_list = []
flag = False
while True:
if self.current_token.token_type == Token_type.integer:
type_list.append(Token_type.integer)
self.consume(Token_type.integer)
statement_list.appen... |
def consume(self, expected_token_type, node=None, loc0=None, loc1=None):
if self.current_token is not None and self.current_token.token_type == expected_token_type:
if node != None:
self.add_node(node, loc0, loc1)
self.advance()
return True
else:
... | This code parses a list of values enclosed in parentheses, separated by commas, and verifies that the collected values match an expected list stored in `self.dict_identifiers` for a given `clause_ident`. If they do not match, it raises an error. The function also consumes expected syntax tokens like `(`, `)`, and `.` d... | def value_list(self, clause_ident):
self.consume(Token_type.open_bracket, '(', 3, -1)
value_list = []
value_list.append(self.values())
while self.current_token.token_type == Token_type.And:
self.consume(Token_type.And, ',', 3, -1)
value_list.append(self.values())
... |
def consume(self, expected_token_type, node=None, loc0=None, loc1=None):
if self.current_token is not None and self.current_token.token_type == expected_token_type:
if node != None:
self.add_node(node, loc0, loc1)
self.advance()
return True
else:
... | The main task of the code is to parse and validate a list of values enclosed in parentheses, separated by 'And' tokens, against a predefined set of identifiers. It consumes tokens, collects values into a list, and checks if the list matches the expected identifiers for the given goal. If not, it raises an error. | def goal_value(self, goal_ident):
self.consume(Token_type.open_bracket, '(', 5)
value_list = []
value_list.append(self.values())
while self.current_token.token_type == Token_type.And:
self.consume(Token_type.And, ',', 5)
value_list.append(self.values())
se... |
def consume(self, expected_token_type, node=None, loc0=None, loc1=None):
if self.current_token is not None and self.current_token.token_type == expected_token_type:
if node != None:
self.add_node(node, loc0, loc1)
self.advance()
return True
else:
... | This method parses a logical implication body by consuming tokens, handling 'And'/'Or' separators, executing write/read operations, and processing variable statements, ending with a '.' token consumption. | def body(self):
self.consume(Token_type.imply, ':-', 3, -1)
while True:
if self.current_token.token_type == Token_type.And:
self.consume(Token_type.And, ',', 3, -1)
elif self.current_token.token_type == Token_type.Or:
self.consume(Token_type.Or, ';... |
def consume(self, expected_token_type, node=None, loc0=None, loc1=None):
if self.current_token is not None and self.current_token.token_type == expected_token_type:
if node != None:
self.add_node(node, loc0, loc1)
self.advance()
return True
else:
... | This function parses a predicate declaration by extracting the predicate name, registering it in a symbol table, and processing its parameters if an open bracket is encountered. It consumes the identifier token, adds a 'Predicate ID' node, and triggers parameter list parsing when a bracket is detected. | def predicate_declaration(self):
predicate_name = self.current_token.lex
self.dict_identifiers[predicate_name] = []
if self.consume(Token_type.identifier, 'Predicate Declaration', 1):
self.add_node(['Predicate ID'], 1)
if self.current_token is not None and self.current_token.... |
def consume(self, expected_token_type, node=None, loc0=None, loc1=None):
if self.current_token is not None and self.current_token.token_type == expected_token_type:
if node != None:
self.add_node(node, loc0, loc1)
self.advance()
return True
else:
... | This code parses a goal section in a formal language by validating the presence of a 'Goal' token, checking if the identifier exists in a dictionary, handling parameters within brackets, and ensuring correct syntax with error checks for invalid structures or unexpected tokens. | def section_goal(self):
if self.consume(Token_type.goal, 'Goal'):
self.add_node(['goal'])
goal_ident = self.current_token.lex
if goal_ident not in self.dict_identifiers.keys():
self.error_found(5)
self.consume(Token_type.identifier, 'Predicate ID', 5)
if s... |
def consume(self, expected_token_type, node=None, loc0=None, loc1=None):
if self.current_token is not None and self.current_token.token_type == expected_token_type:
if node != None:
self.add_node(node, loc0, loc1)
self.advance()
return True
else:
... | This code parses clauses in a logical language, constructing a syntax tree by consuming tokens. It handles facts (with open brackets and values) and rules (with implications and bodies), validating identifiers and adding nodes for each structure. The loop processes tokens until a 'goal' is encountered, ensuring proper ... | def section_clauses(self):
if self.consume(Token_type.clauses, 'Clauses'):
self.add_node(['clauses'])
while self.current_token != None and self.current_token.token_type != Token_type.goal:
clause_ident = self.current_token.lex
if clause_ident not in self.dict_identifi... |
def consume(self, expected_token_type, node=None, loc0=None, loc1=None):
if self.current_token is not None and self.current_token.token_type == expected_token_type:
if node != None:
self.add_node(node, loc0, loc1)
self.advance()
return True
else:
... | This function parses the 'Predicates' section of a knowledge base by consuming the 'Predicates' token, adding a 'predicates' node, and repeatedly processing predicate declarations until encountering the 'clauses' token. It handles all predicate definitions in sequence, ensuring proper structure before transitioning to ... | def section_predicates(self):
if self.consume(Token_type.predicates, 'Predicates'):
self.add_node(['predicates'])
while self.current_token != None and self.current_token.token_type != Token_type.clauses:
self.predicate_declaration() |
def handleField(self, parent, fieldName, required, root, indent):
field = root.find('fields/field[@name=\'' + fieldName + '\']')
self.createRow(parent, "fixField", "td",
indent + " " + field.get('number'),
field.get('name'),
field.get('type'),
required )
d... | This function processes XML nodes recursively, generating structured output by handling fields, components, and groups. It creates UI elements with indentation, processes component definitions from the root, and manages nested structures by adjusting indentation levels for proper hierarchy visualization. | def handleNode(self, parent, root, node, indent):
for child in node:
if child.tag == 'field':
fieldName = child.get('name')
self.handleField(parent, fieldName, child.get('required'), root, indent)
elif child.tag == 'component':
componentNam... |
def createFullWidthRow(self, parent, rowClass, text, tagType="td"):
tr = self.createRow(parent, rowClass)
td = etree.SubElement(tr, tagType)
td.set("colspan", "4")
td.text = text
return tr
def createRow(self, parent, rowClass, tagType="td", *cellText):
row = etree.SubElem... | The main task of the code is to parse a FIX message definition from an XML file, extract its structure based on a specified message type, and generate an HTML table representation with headers, fields, and footers. It processes configuration parameters, navigates the XML hierarchy, and dynamically constructs a structur... | def run(self, parent, blocks):
block = blocks.pop(0)
# Parse configuration params
m = self.RE.search(block)
msgtype = m.group('msgType')
dd_path = m.group('path')
logging.info(os.getcwd())
root = etree.parse(dd_path).getroot()
message = root.find('messa... |
def get_bot_response(self, message):
ints = self.predict_class(message)
res = self.get_response(ints, self.intents)
return res
def store_message(self, sender, message):
with open(self.chat_history_file, 'a') as file:
timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
... | This function handles sending and displaying user-bot messages in a chat interface. It inserts user messages with "You:" formatting, triggers bot responses, and displays them with "Bot:" tags. Messages are added to a text box, entry fields are cleared, and the interface scrolls to new content. It also stores messages f... | def send_message(self, sender="user", message=None):
if message is not None and message.strip() != "":
if sender == "user":
user_message = f"You: {message}\n"
self.text_box.configure(state='normal')
self.text_box.insert(tk.END, user_message, 'user_mess... |
def get_bot_response(self, message):
ints = self.predict_class(message)
res = self.get_response(ints, self.intents)
return res
def store_message(self, sender, message):
with open(self.chat_history_file, 'a') as file:
timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
... | The code handles sending and displaying messages in a chat interface. It inserts user messages, triggers bot responses, and updates the text box with formatted user/bot messages, scrolls to the latest content, and stores messages. | def send_message(self, sender="user", message=None):
if message is not None and message.strip() != "":
if sender == "user":
user_message = f"You: {message}\n"
self.text_box.configure(state='normal')
self.text_box.insert(tk.END, user_message, 'user_mess... |
def generate_all_keyword_query(keyword: str) -> KeywordQuery:
return generate_search_query_element('all', '%22' + '+'.join(keyword.split(' ')) + '%22')
def generate_categories_query(categories: CategoryList) -> CategoriesQuery or None:
if categories is None or len(categories) == 0:
return generate_categ... | The function `generate_search_query` constructs a search query by combining a keyword-based query and a category-based query using an AND operator, then returns the result as a formatted string starting with 'search_query='. | def generate_search_query(keyword: str, categories: CategoryList) -> QueryElement:
keyword_query = generate_all_keyword_query(keyword)
categories_query = generate_categories_query(categories)
return 'search_query=' + generate_and_query(keyword_query, categories_query) |
def get_safest_route(self, point_from, point_to):
"""
Returns the safest path from point_from to point_to in
the NYC streets network.
Call `get_route` using `risk` as weigth
See get_route(self, point_from, point_to, weight=weight) for more information.
"""
retu... | The code generates multiple routes between two points based on specified criteria (e.g., safest, shortest, most dangerous) by calling corresponding methods for each route type in the input list. It compiles valid routes into a dictionary mapping route types to their respective paths and returns this dictionary. | def get_routes(self, point_from: tuple, point_to: tuple, route_types: list):
routes = {}
for route_type in route_types:
route = None
if route_type == "safest":
route = self.get_safest_route(point_from, point_to)
elif route_type == "shortest":
... |
def create_coins_dict(lst):
"""receive a list of tuples for coin and exchanges, create a dict with indices
such that accessing dct['BTC'] will give the appropriate symbol from the tuple"""
return {value[0]: value[1] for value in lst}
def create_coin_designates(exchange_to=DEFAULT, trade_stables=False, ignor... | The code writes close price data of a user-selected cryptocurrency into a text file, including formatted datetime, Unicode time, and close price. It checks for existing files, handles overwriting, and uses functions to fetch and format data. The output is a structured `.txt` file for further analysis or processing. | def write_data_to_file(plot=False):
"""Creates a file with the relevant data (close prices) for a coin chosen by the user.
File is written as a txt file, contains rows of the format: FormattedDateTime, UnicodeIntTime, ClosePrice"""
# used to check if file exists. verify compatibility, also possible to impor... |
def get_initial_state(pos, token):
return params["wte"][token] + params["wpe"][pos]
def do_gpt2_block(block_inputs, pos, block):
x = block_inputs
block_params = params["block"][block]
x_ln1 = normalize(x, block_params["ln1_w"], block_params["ln1_b"])
x_ln1_attn = do_attention(x_ln1, pos, block)
... | This function generates logits for a GPT-2 model at a specific position in a sequence. It initializes hidden states, processes each transformer block, applies layer normalization, and computes final output logits using the language model head weights. The core task is performing a forward pass through the GPT-2 archite... | def do_gpt2_pos(pos, token):
if len(prev_states) < pos + 1:
prev_states.append([{"k": None, "v": None} for block in range(n_blocks)])
state = get_initial_state(pos, token)
for block in range(n_heads):
state = do_gpt2_block(state, pos, block)
state = normalize(state, params["lnf_w"], para... |
def _combine_rows(image: PIL_Image):
"""
Combine two rows into one line.
"""
tmp: list[list[_RGBA]] = np.array(image).tolist()
return [
zip(row, tmp[index + 1])
for index, row in enumerate(tmp)
if _is_even(index)
]
def _convert_to_even_height_rgba(image: PIL_Image):
"... | The main task of the code is to convert a PIL image into ASCII pixel art by first normalizing its dimensions, processing rows of pixels, mapping each pixel pair to an ASCII character, and combining them into a text-based representation of the image. | def pixelize(image: PIL_Image):
combined = _combine_rows(_convert_to_even_height_rgba(image))
return "".join([
"".join([
_convert_to_ascii(*pixel_x2)
for pixel_x2 in row
]) + "\n"
for row in combined
])[:-1] |
def get_handled_alerts(self, alerts_info: List[AlertInfo]):
handled_alerts = set()
for alert_info in alerts_info:
try:
for note_info in self.edr_proxy.get_notes(alert_info.alert_id):
if note_info.text.startswith('Intezer Analyze'):
... | This method continuously processes EDR alerts by fetching, analyzing, and reporting them in a loop. It resets counters, handles exceptions, sends summaries, and enforces a cooldown period between runs to avoid over-processing. | def handle_alerts(self):
while True:
self.handled_alerts_count = 0
self.finished_analyses_count = 0
self._exceptions = []
start_time = datetime.datetime.utcnow()
try:
alerts_info = self.edr_proxy.fetch_latest_alerts(self.latest_edr_aler... |
def _do_first_interaction(self) -> None:
self._prefix_help()
console.print(
'This is your first interaction with the World.',
'Would you like to enable assitant?'
)
expect = ('yes', 'no')
self._prefix_help()
query = console.input('')
while ... | The code processes user input to handle interactions in a game or application, parsing commands like 'talk', 'go', 'exit', etc. It manages first-time interactions, retries on input errors, validates commands, provides feedback for invalid inputs, and executes corresponding actions, returning relevant objects or None ba... | def interaction(self) -> Character | Location | None:
if self._first_interaction:
self._do_first_interaction()
return None
query = ''
while not query:
try:
self._prefix()
query = console.input('')
except KeyboardInte... |
def update_acceleration(self):
if self.traffic_model is None:
return
self.acceleration = self.traffic_model.calculate_acceleration(self, self.next_vehicle)
def update_velocity(self, delta_t):
self.velocity = max(0, self.velocity + delta_t * self.acceleration)
def update_position(sel... | The code updates an object's state over time by first calculating acceleration, then updating velocity using the time delta, and finally adjusting the position based on the updated velocity and delta_t, typically used in physics simulations or animations. | def update(self, delta_t):
self.update_acceleration()
self.update_velocity(delta_t)
self.update_position(delta_t) |
def _init_gaussians(self, x):
# Initialise Gaussian distributions randomly
# Mean - random sample from X
# Covariance - common for all classes
num_samples = np.shape(x)[0]
self.priors = (1/self.num_clusters) * np.ones(self.num_clusters)
for i in range(self.num_clusters):
... | (The code fits a Gaussian Mixture Model (GMM) by estimating parameters (means, covariances, cluster weights) using the Expectation-Maximization (EM) algorithm. It initializes Gaussian distributions, iteratively performs E-step (calculating responsibilities) and M-step (updating parameters), and terminates early if conv... | def fit(self, x):
"""Fit parameters (mean, covariance, cluster weights)
"""
# Initialise Gaussian distributions
self._init_gaussians(x)
# Run EM algorithm till convergence
for _ in range(self.max_iterations):
# Expectation step
self._expectation(x... |
def parse_tree(top_level_file):
items = {}
# track inclusions
# map filename to group
inclusions = {}
directory = "/".join(top_level_file.split("/")[:-1])
top_level_filename = top_level_file.split("/")[-1]
to_process = [top_level_filename]
in_top_level = True
top_level_node = None... | The main task of the code is to convert an ALH file into a Phoebus configuration file by parsing the input file, constructing a tree structure, and generating the corresponding XML output file with a configuration name derived from the output filename. | def convert_alh_to_phoebus(input_filename, output_filename):
config_name = output_filename.split("/")[-1].replace(".xml", "")
items, top_level_node = parse_tree(input_filename)
tree = build_tree(items, top_level_node)
build_config_file(tree, config_name, output_filename)
return True |
def _clear(self):
self._tree = None
self._root = None
self._nodes = []
def _handle_group_parse(self, group, parent_idx):
# add group
data = self._build_data(group)
self._nodes.append([data, parent_idx])
group_idx = len(self._nodes) - 1
for child in group... | The code parses an XML configuration file, initializes a tree structure by clearing existing data, extracts the root element's name, and populates a node list with components and PVs by recursively processing child elements. It returns the constructed tree as a list of nodes, with each node containing a label and assoc... | def parse_config(self, filename):
"""
Parses a configuration file
"""
#clear
self._clear()
# parse filename
self._tree = ET.parse(filename)
self._root = self._tree.getroot()
if self._root.tag == "config":
self._config_name = self._roo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.