dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def get_dataset(datasets, data_dir, tokenizer, split_name, recompute_features):
dataset_dict = None
dataset_name=''
for dataset in datasets:
dataset_name += f'_{dataset}'
dataset_dict_curr = util.read_squad(f'{data_dir}/{dataset}')
dataset_dict = util.merge(dataset_dict, dataset_dict... | The code trains a model using either a baseline approach or MAML (Model-Agnostic Meta-Learning), depending on the `run_name` argument. For "baseline," it loads training and validation datasets, creates data loaders, and trains using `_train_baseline`. For "maml," it prepares multiple task-specific data loaders, compute... | def train(self, tokenizer):
args = self.args
if args.run_name == "baseline":
print("Preparing training data...")
train_dataset, _ = get_dataset(args.train_datasets, args.train_dir, tokenizer, 'train', args.recompute_features)
train_loader = DataLoader(train_dataset, b... |
def clear_tree(self):
children_count = 1
try:
while True:
for x in self.treeview.get_children(children_count):
self.treeview.delete(x)
children_count += 1
except Exception:
pass
def checkRadiobutton(self):
if sel... | The code's main task is to perform file scanning based on user-selected modes (quick, deep, or default), measure scan duration, update UI elements with results, and check admin status. It clears the tree view, initiates scans via the scanner object, records timing, displays scan time, inserts scanned files into a tree ... | def scanButtonActions(self):
self.clear_tree()
scan = scanner.Scanner()
if self.checkRadiobutton() == 1:
scan.setPath(self.entry.get())
timer1 = timer.Timer()
timer1.startTimer()
files = scan.get_scanning("quick")
self.files_Global =... |
def browseButtonActions(self):
folder_selected = filedialog.askdirectory()
if len(folder_selected) > 0:
self.entry.delete('0',END)
self.entry.insert('0',folder_selected)
def scanButtonActions(self):
self.clear_tree()
scan = scanner.Scanner()
if self.che... | The code initializes a user interface for a security scanning tool, configuring the main window, scan type options, file browsing, scan execution, report display, and file category visualization. It sets up GUI elements like buttons, radio buttons, tabs, a treeview for file categories, and a text box for reports, enabl... | def initialize_user_interface(self):
#Configuring root object of the application
self.root.title("Open-Source Security Check")
self.windowWidth = 1465
self.windowHeight = 840
self.screenWidth = self.root.winfo_screenwidth()
self.screenHeight = self.root.winfo_screenheight... |
def _most_common_label(self, y):
counter = np.bincount(y)
most_common = np.argmax(counter)
return most_common
def _best_split(self, X, y, n_samples, n_features):
# best criteria
best_feature = None
best_threshold = None
best_info_gain = -1
# to avoid the ... | This function recursively builds a decision tree by selecting the best split based on information gain, creating left and right child nodes, and stopping when maximum depth is reached, all labels are the same, or samples are insufficient. It returns a Node object representing the tree structure with split parameters an... | def _grow_tree(self, X, y, depth=0):
n_samples, n_features = X.shape
n_labels = len(np.unique(y))
# stopping criteria
if (
depth >= self.max_depth
or n_labels == 1
or n_samples < self.min_samples_split
):
leaf_value = self._most_co... |
def create_ax_experiment(self):
self.create_ros_param_clients()
self.convert_params_to_ax()
self.ax.create_experiment(
name=self.experiment_name,
parameters=self.parameters_setup,
objective_name=self.objective_name,
minimize=True, # Optional, defa... | The main task of the code is to run an optimization experiment using Ax, which involves setting up and evaluating trials, handling the status quo (if provided), iterating through a specified number of trials to find optimal parameters, logging trial outcomes, and finally reporting the best parameters and their performa... | def run_experiment(self):
self.create_ax_experiment()
# Run status quo
if self.status_quo is not None:
self.parameters, trial_index = self.ax.attach_trial(parameters=self.status_quo)
self.setup_trial()
self.invoke_trial()
self.ax.complete_trial(tri... |
def _get_pile(self, click: tuple) -> int:
if click[1] <= 113 and click[1] >= 16:
if click[0] >= 283 and click[0] <= 356:
return 0
if click[0] >= 372 and click[0] <= 445:
return 1
if click[0] >= 461 and click[0] <= 534:
return 2
... | This code handles card release logic in a game, validating moves between piles by checking suit/rank compatibility. It updates game state, transfers cards between stacks, manages visual displays, and checks for win conditions by updating pile counts and image positions. | def onRelease(self, event):
click_result = self._get_pile(self.click)
# drop card over top 4 piles
if click_result != None and len(self.game.transfer_list) == 1: #check transfer list equaling 1 good
if self._check_suit(click_result):
if sel... |
def get_pianoroll(midi_file: Path, fs: int) -> np.ndarray:
pianoroll = get_notes(midi_file, fs)
for i, _ in enumerate(pianoroll):
for j, _ in enumerate(pianoroll[i]):
if pianoroll[i, j] != 0:
pianoroll[i, j] = 1
return pianoroll
def pianoroll_to_histogram_per_bar(pianorol... | This function converts a MIDI file into a compressed histogram representation by first generating a pianoroll, then creating a per-bar histogram, squashing octaves, and saving the result as a pickle file. | def midi_to_histo_oct(samples_per_bar: int, semitones_in_octave: int, fs: int, midi_file: Path, histogram_path: Path) -> None:
pianoroll = get_pianoroll(midi_file, fs)
histogram_per_bar = pianoroll_to_histogram_per_bar(pianoroll, samples_per_bar)
histogram_per_bar_squashed_octaves = squash_octaves(histogram... |
def process_input_urls(work_dir, urls=[], recent_only=False):
print(f'[==] Processing {len(urls)} URLs:')
failed_urls = []
failed_urls.extend(
sync_urls(urls, work_dir=work_dir, recent_only=recent_only))
failed_file = ConfigHandler.getFailedFile()
if len(failed_urls) > 0:
write_pla... | The main task of the code is to process command-line arguments and environment variables to handle media content operations (e.g., URL input, file processing, playlist generation, scanning). It configures directories, proxy settings, and ABCM parameters, then executes scripts based on input modes like "full," "photo," ... | def real_main(argv):
print('=====XCHINA2=====')
global THIS_CMD
THIS_CMD = ' '.join(argv)
global DOWNLOAD_COMMON_ARG
global ABCM
conf_dir = os.path.abspath(os.environ.get('XCHINA2_CONF_DIR', './'))
work_dir = os.path.abspath(os.environ.get('XCHINA2_DATA_DIR', './'))
exe_scripts = os.env... |
def _read_difficulty(version_data: Dict[str, Any]) -> Dict[str, Dict[Difficulty, int]]:
# https://textage.cc/score/scrlist.js get_level
difficulties_by_textage_id: Dict[str, Dict[Difficulty, int]] = {}
for key in version_data.keys():
difficulties_by_textage_id[key] = {}
spl = version_data[ke... | The code builds a dictionary of song metadata by processing input data (version_data, song_titles, song_list) to extract and organize song details like title, artist, genre, version, and difficulty-specific information (BPM ranges, note counts, levels) into structured SongMetadata objects for each track. | def _build_song_metadata_dict(
version_data: Dict[str, Any],
song_titles: Dict[str, Any],
song_list: Dict[str, List[str]],
) -> Any:
all_difficulties = _read_difficulty(version_data)
all_bpms, all_note_counts = read_notes_and_bpm()
variable_bpms = get_variable_bpms()
version_list = get_texta... |
def get_textage_version_data() -> Dict[str, Any]:
def __convert_version_bitfield_to_json(bitfield: str) -> str:
key, values = bitfield.split(":", maxsplit=1)
if key == "'__dmy__'":
return ""
values = re.sub("A", "10", values)
values = re.sub("B", "11", values)
val... | The main task of the code is to retrieve and filter Infinitas-specific song metadata. It gathers version data and song titles, identifies songs exclusive to Infinitas, and constructs a dictionary mapping song titles to their corresponding metadata. This involves fetching data, filtering relevant entries, and organizing... | def get_infinitas_song_metadata() -> Dict[str, SongMetadata]:
version_data = get_textage_version_data()
song_titles = get_textage_song_titles()
infinitas_only_songs = filter_infinitas_only_songs(version_data, song_titles)
return _build_song_metadata_dict(version_data, song_titles, infinitas_only_songs) |
def get_textage_version_data() -> Dict[str, Any]:
def __convert_version_bitfield_to_json(bitfield: str) -> str:
key, values = bitfield.split(":", maxsplit=1)
if key == "'__dmy__'":
return ""
values = re.sub("A", "10", values)
values = re.sub("B", "11", values)
val... | The function retrieves current version song data and filters out songs not present in Infinitas, then constructs and returns a dictionary of metadata for these unique songs by comparing key sets and applying filtering functions. | def get_current_version_song_metadata_not_in_infinitas() -> Dict[str, SongMetadata]:
version_data = get_textage_version_data()
song_titles = get_textage_song_titles()
current_version_songs = filter_current_version_songs(version_data, song_titles)
infinitas_only_songs = filter_infinitas_only_songs(versio... |
def get_textage_version_data() -> Dict[str, Any]:
def __convert_version_bitfield_to_json(bitfield: str) -> str:
key, values = bitfield.split(":", maxsplit=1)
if key == "'__dmy__'":
return ""
values = re.sub("A", "10", values)
values = re.sub("B", "11", values)
val... | The function `get_all_song_metadata` retrieves and validates song metadata by cross-referencing song titles with version data, filtering out invalid entries, and constructing a dictionary of validated `SongMetadata` objects using a helper function. | def get_all_song_metadata() -> Dict[str, SongMetadata]:
version_data = get_textage_version_data()
song_titles = get_textage_song_titles()
validated_songs = {}
for textage_id, title_version_metadata in song_titles.items():
if textage_id not in version_data:
log.warning(f"could not fin... |
def check_for_bound_exception(self):
# if we have upperBound-lowerBound=1 then pyecore cannot get set of elements, so we will temporarily
# add 1 to upperBound
exp_ref = []
for e_class in self.mm_root.eClassifiers:
if e_class.eClass.name == "EClass":
for ref i... | This code loads a metamodel and model file using PyEcore, processes their structure by extracting classes/objects, generates an adjacency matrix, creates triple files for knowledge graphs, and prepares data for decoding. It handles error cases where XMI parsing fails due to invalid element ordering. | def load_model(self, metamodel_name, model_name):
"""
:param model_name:
:param metamodel_name:
:return:
"""
rset = ResourceSet()
resource = rset.get_resource(URI('../input/' + metamodel_name))
self.mm_root = resource.contents[0]
exp_refs = self.ch... |
def upload_media(self, filepath, media_key):
path = filepath + os.sep + media_key
try:
filename = glob.glob(path + '.*')[0]
except:
logger.info('[INFO] no media for ' + media_key)
return None
with open(filename, 'rb') as f:
image_data = f.read()
content = base64.b64encode(image_data).decode('utf-8... | The main task of the code is to process a list of tweets by uploading their associated media files using a specified path, extract media syntax information from the upload responses, and compile this data into a payload along with the date and tweets. The function returns a structured payload containing media metadata ... | def create_entry(self, date, tweets, media_path):
medias = {}
for tweet in tweets:
if 'attachments' in tweet.keys() and 'media_keys' in tweet['attachments'].keys():
for media_key in tweet['attachments']['media_keys']:
filepath = media_path
media_entry = self.upload_media(filepath, media_key)
i... |
def exit_game(self):
self.log.close()
print("Have a nice day")
sys.exit(0)
def get_ending_room(self):
self.ending_room = None
for r in self.rooms:
if r.room_type == 2:
self.ending_room = r
break
if self.ending_room == None:
... | The main task of the code is to load a game by initializing rooms, current room, and turns from a saved game, check for loading errors, set up the game state, and start the game loop if successful. It logs progress, handles errors by exiting if invalid, and transitions to the game loop upon success. | def load_game(self):
self.log.write(1, "Loading Game...")
self.rooms, self.current_room, self.turns = self.generate_game.load_game()
if self.current_room == None:
EP.print_error(37)
self.exit_game()
self.get_ending_room()
self.game_over = False
... |
def get_starting_room(self):
self.current_room = None
for r in self.rooms:
if r.room_type == 1:
self.current_room = r
break
if self.current_room == None:
EP.print_error(37)
sys.exit(0)
def get_ending_room(self):
self.end... | The code initializes a new game by generating rooms, setting starting/ending points, resetting game state variables, saving progress, and launching the game loop. It logs game creation steps and prepares the game environment for player interaction. | def new_game(self):
self.log.write(1, "Creating New Game")
self.turns = 0
self.rooms = self.generate_game.new_game()
self.get_starting_room()
self.get_ending_room()
self.game_over = False
self.generate_game.save_game(self.rooms, self.current_room, self.turns)
... |
def df2matrix(df, nrows, ncols, column_name="rating"):
""" Returns a sparse matrix constructed from a dataframe
This code assumes the df has columns: MovieID,UserID,Rating
"""
values = df[column_name].values
ind_movie = df['movieId'].values
ind_user = df['userId'].values
return sparse.c... | The code implements gradient descent with momentum (0.9) to train user and movie embeddings by minimizing a cost function over iterations. It updates embeddings using gradients computed from the input data, applies momentum to stabilize learning, and prints training/validation costs every 50 iterations. The trained emb... | def gradient_descent(df, emb_user, emb_movie, iterations=100, learning_rate=0.01, df_val=None):
""" Computes gradient descent with momentum (0.9) for a number of iterations.
Prints training cost and validation cost (if df_val is not None) every 50 iterations.
Returns:
emb_user: the trained use... |
def cat_count(path: str) -> int:
"""Return the total amount of CATIA (.CAT*) files in the directory."""
cats, total = 0, 1
def process_zip(zipfile: zf.ZipFile):
"""Add all .CAT* files in the zipfile."""
nonlocal cats, total
for name in zipfile.namelist():
total += 1
... | The code initiates a data-mining process by searching for .CAT* files in a directory, logging progress via a progress bar, and converting them. It prints an ASCII art banner, counts target files, and executes the conversion through `_dir_crawl()`. Error handling for interruptions and exceptions is included, with gracef... | def begin(self) -> None:
"""Commence the data-mining process once setting are in place, if applicable."""
# start printing to the log
text_art = textwrap.dedent(r"""
_ _
___ __ _ | |_ _ __ ___ (_) _ __ ___ _ __
... |
def query_uuids(self, data, limit = None, offset = None):
uuids = []
#get result of query
data = self.query_data(data, limit = limit, offset = offset)
#list uuids from matching records
for record in data:
uuids.append(record["uuid"])
return uuids
def create(se... | This function checks for duplicate records using specified key fields. If no duplicates are found, it creates a new record. If duplicates exist, it replaces the first match (or all matches, depending on the mode) or skips with a warning. It handles multiple matches by either replacing, deleting, or raising an error, ba... | def create_check_duplicates(self, data, key_fields, replace = True, multiple_match_mode = MultipleMatchMode.ERROR):
key_data = {
"name": data["name"],
}
for field in key_fields:
key = "value.%s" % field
key_data[key] = data["value"][field]
uuids = sel... |
def createData(pickup, deliv, vehicle, currentAdd):
data = {}
data['API_key'] = 'dui73udj8anps6ahj7d39ue76wbwbeoi'
data['addresses'] = []
# set rider's location in addresses
current = currentAdd.replace(" ", "+")
current = current.replace("#", '%23')
data['addresses'].append(current)
f... | The function processes pickup and delivery location data, generates a distance matrix, optimizes routes for vehicle operations, and returns the optimized route details via JSON. It handles input from AJAX requests, manipulates data structures, computes distances, and stores results in Firebase. | def optimiseData():
# receive address from ajax in js
list1 = request.form['pickupJS']
list2 = request.form['deliveryJS']
temp = request.form['num']
currenttemp = request.form['currentJS']
pickup = json.loads(list1)
delivery = json.loads(list2)
num = int(json.loads(temp))
current ... |
def generatePrefix(coherenceSymmetry):
global maincode
global hostcode
global remotecode
global devicecode
maincode += "/*AUTOMATICALLY GENERATED CODE*/\n/*Coherence symmetry mode: "
maincode += coherenceSymmetry + "*/\n\n#include <simgrid/s4u.hpp>\n\nXBT_LOG_NEW_DEFAULT_CATEGORY(s4u_app_ma... | The code generates and analyzes graph partitions for a distributed system with coherence symmetry, using smart partitioning and PageRank algorithms. It evaluates vertex/edge distribution across host, remote, and device partitions, tracking recurrence counts and outputting metrics like shared vertices, destinations, and... | def main():
global hostrecurcount
global remoterecurcount
global devicerecurcount
SMART_PARTITION = True
RANDOMIZE = False
#coherenceSymmetry = "none"
#coherenceSymmetry = "sym" #--------------
####coherenceSymmetry = "asym_host"
coherenceSymmetry = "asym_dev" #---------------
... |
def in_ndc(self):
return self._in_ndc
def get_principal_point(self, **kwargs) -> np.ndarray:
"""
Return the camera's principal point
Args:
**kwargs: parameters for the camera extrinsics can be passed in
as keyword arguments to override the default values
... | This function computes a 3D transformation converting camera projection space (screen or NDC) to NDC space. If the camera is already in NDC, it returns an identity transform. For screen-space cameras, it adjusts the principal point (from image coordinate system: +X right, +Y down) to match PyTorch3D's convention (+X le... | def get_ndc_camera_transform(self, **kwargs) -> Transform3d:
"""
Returns the transform from camera projection space (screen or NDC) to NDC space.
If the camera is defined already in NDC space, the transform is identity.
For cameras defined in screen space, we adjust the principal point c... |
def get_full_projection_transform(self, **kwargs) -> Transform3d:
"""
Return the full world-to-camera transform composing the
world-to-view and view-to-camera transforms.
If camera is defined in NDC space, the projected points are in NDC space.
If camera is defined in screen spac... | This function transforms 3D points from world/camera coordinate systems to normalized device coordinates (NDC) using projection and camera transforms. It applies a composite transformation matrix to input points (..., 3) following +X left, +Y up conventions, outputting NDC coordinates with origin at image center while ... | def transform_points_ndc(self, points, **kwargs) -> np.ndarray:
"""
Transforms points from world/camera space to NDC space.
Input points follow the coordinate system conventions: +X left, +Y up.
Output points are in NDC space: +X left, +Y up, origin at image center.
Args:
... |
def transform_points(
self, points, **kwargs
) -> np.ndarray:
"""
Transform input points from world to camera space.
If camera is defined in NDC space, the projected points are in NDC space.
If camera is defined in screen space, the projected points are in screen space. ... | This function transforms 3D points from world/camera space to 2D screen space, converting coordinate systems from (+X left, +Y up) to (+X right, +Y down) with origin at top-left. It first converts input points to normalized device coordinates (NDC) using `transform_points`, then applies a screen-space transformation ma... | def transform_points_screen(
self, points, **kwargs
) -> np.ndarray:
"""
Transforms points from world/camera space to screen space.
Input points follow the coordinate system conventions: +X left, +Y up.
Output points are in screen space: +X right, +Y down, origin at top left ... |
def clean_data(*args):
dfs = [df.set_index(pd.to_datetime(df.index)).dropna() for df in args]
intersection_index = reduce(lambda x, y: x.intersection(y), (df.index for df in dfs))
dfs = [df.loc[intersection_index] for df in dfs]
return dfs
def get_notional_exposure_per_contract(unadj_prices : pd.DataFr... | The function 'aggregator' processes financial data to compute optimal positions and risk metrics. It cleans input data, calculates notional exposure and contract weights, and uses an iterator to apply constraints (e.g., leverage, risk buffers, costs) to determine adjusted positions. The goal is to balance portfolio ris... | def aggregator(
capital : float,
fixed_cost_per_contract : float,
tau : float,
asymmetric_risk_buffer : float,
unadj_prices : pd.DataFrame,
multipliers : pd.DataFrame,
ideal_positions : pd.DataFrame,
covariances : pd.DataFrame,
jump_covariances : pd.DataFrame,
open_interest : pd.... |
def process_arguments():
# Read serialized arguments from stdin
serialized_args = [sys.stdin.buffer.read() for _ in range(16)] # Adjust the range based on the number of arguments
# Deserialize arguments
capital, tau, asymmetric_risk_buffer, fixed_cost_per_contract, instrument_weight, IDM, \
maximu... | The main task of the code is to optimize portfolio positions by aggregating and processing input parameters (e.g., capital, risk constraints, cost penalties) and financial data (e.g., prices, covariances, open interest) through an `aggregator` function. It returns `optimized_positions`, which represent the dynamically ... | def main():
# Step 1: Process arguments
capital, tau, asymmetric_risk_buffer, fixed_cost_per_contract, instrument_weight, IDM, \
maximum_forecast_ratio, maximum_portfolio_risk, maximum_jump_risk, maximum_position_leverage, \
maximum_correlation_risk, maximum_portfolio_leverage, max_acceptable_pct_of_ope... |
def is_logout(self, response):
if not self.check_logout:
return False
response_cookies = _response_cookies(response)
if self.auth_cookies and response_cookies is not None:
auth_keys = {c['name'] for c in self.auth_cookies if c['value']}
response_keys = {
... | The main task of the code is to automatically re-login and retry requests when a logout is detected in the response. It checks if the request requires auto-login, creates a retry request with updated cookies, and manages logout count limits to prevent infinite retries. If logout limits are exceeded, it raises an error;... | def process_response(self, request, response, spider):
""" If we were logged out, login again and retry request.
"""
if request.meta.get('_autologin') and self.is_logout(response):
autologin_meta = request.meta['_autologin']
if isinstance(autologin_meta['request'], dict):... |
def _irpy_alloca(amount):
ptr = len(_irpy_stack)
_irpy_stack.extend(bytes(amount))
return (ptr, amount)
def store_i64(v, p):
write_mem(p, struct.pack("q", v))
def store_f64(v, p):
write_mem(p, struct.pack("d", v))
def load_f64(p):
return struct.unpack("d", read_mem(p, 8))[0]
def load_i64(p):
... | The code implements the Mandelbrot set algorithm by iterating complex numbers and counting iterations until divergence. It initializes variables, performs arithmetic operations (addition, multiplication, division), and uses conditional blocks to manage iteration limits and escape criteria. The function returns the iter... | def mandelbrot():
_irpy_prev_block = None
_irpy_current_block = 'mandelbrot_block0'
while True:
if _irpy_current_block == "mandelbrot_block0":
num = 0
alloc_count = _irpy_alloca(8)
addr_count = alloc_count[0]
store_i64(num, addr_count)
num_... |
def __filter_nodes(ui_tree: dict, node_condition, parent_only: bool = True) -> list[dict]:
"""
Collect the subtrees, which satisfies the node_condition, from the root ui_tree. By default, the function only
returns the parent subtrees, then stops searching their children. When parent_only is False, the funct... | This function retrieves the color of an icon sprite from a dictionary node. It filters nodes to find the first entry with the name 'iconSprite', then extracts and returns its color using __get_color_from_node. If no such node exists, it returns None. | def __get_entry_icon_color(object_icon_node: dict) -> Optional[ColorPercentages]:
sprite = __filter_nodes(object_icon_node, lambda node: __get_text_from_dict_entries(node, NAME) == 'iconSprite')
return __get_color_from_node(sprite[0]) if sprite else None |
def __filter_nodes(ui_tree: dict, node_condition, parent_only: bool = True) -> list[dict]:
"""
Collect the subtrees, which satisfies the node_condition, from the root ui_tree. By default, the function only
returns the parent subtrees, then stops searching their children. When parent_only is False, the funct... | This function extracts the background color from a specified node in a data structure. It filters nodes of type 'Fill', then searches for a node named 'bgColor' within them, returning its color value if found, otherwise None. | def __get_background_color(entry: dict) -> Optional[ColorPercentages]:
fill_nodes = __filter_nodes(entry, lambda node: node[TYPE_NAME] == 'Fill')
bg_color_nodes = __filter_nodes(
fill_nodes[0], lambda node: __get_text_from_dict_entries(node, NAME) == 'bgColor') if fill_nodes else None
return __get_c... |
def __filter_nodes(ui_tree: dict, node_condition, parent_only: bool = True) -> list[dict]:
"""
Collect the subtrees, which satisfies the node_condition, from the root ui_tree. By default, the function only
returns the parent subtrees, then stops searching their children. When parent_only is False, the funct... | The code parses UI elements from an overview window into structured data entries. It extracts text by aligning entry and header regions, maps headers to entry texts, processes icons for indicators (e.g., hostile, attacking), and collects color data. Each parsed entry is structured as an `OverviewEntry` with text info, ... | def __parse_overview(overview_window: dict) -> list[OverviewEntry]:
parsed_entries = []
scroll = __filter_nodes(overview_window, lambda node: 'scroll' in node[TYPE_NAME].lower())[0]
header = __filter_nodes(scroll, lambda node: 'headers' in node[TYPE_NAME].lower())[0]
entries = __filter_nodes(overview_w... |
def __filter_nodes(ui_tree: dict, node_condition, parent_only: bool = True) -> list[dict]:
"""
Collect the subtrees, which satisfies the node_condition, from the root ui_tree. By default, the function only
returns the parent subtrees, then stops searching their children. When parent_only is False, the funct... | This function parses user entities from a chat UI node by filtering 'userlist' nodes, extracting user entry nodes, and creating ChatUserEntity objects with the longest name text and standing icon from each entry. | def __parse_user_lists_from_chat(chat_ui_node: dict) -> list[ChatUserEntity]:
user_list_nodes = __filter_nodes(
chat_ui_node, lambda node: 'userlist' == __get_text_from_dict_entries(node, NAME))
user_entities = []
if user_list_nodes:
user_list_node = user_list_nodes[0]
user_entry_no... |
def __filter_nodes(ui_tree: dict, node_condition, parent_only: bool = True) -> list[dict]:
"""
Collect the subtrees, which satisfies the node_condition, from the root ui_tree. By default, the function only
returns the parent subtrees, then stops searching their children. When parent_only is False, the funct... | The function parses drone data from a dictionary, extracting entries with 'DroneEntry' type. It retrieves text and health percentages (shield, armor, structure) from each entry, creating Drone objects. Drones are categorized into 'in_bay' or 'in_space' lists in a DroneList based on their type name, then returned. | def __parse_drones_window(drones_window: dict) -> DroneList:
drone_entries = __filter_nodes(
drones_window, lambda node: node[TYPE_NAME].startswith('Drone') and node[TYPE_NAME].endswith('Entry'))
drones = DroneList()
for entry in drone_entries:
entry_texts = __get_all_contained_text(entry)... |
def __filter_nodes(ui_tree: dict, node_condition, parent_only: bool = True) -> list[dict]:
"""
Collect the subtrees, which satisfies the node_condition, from the root ui_tree. By default, the function only
returns the parent subtrees, then stops searching their children. When parent_only is False, the funct... | The main task of the code is to parse a chat window from a node stack by filtering XmppChatWindow nodes, extracting the chat name and user list, and returning a ChatWindow object if found, otherwise None. | def __parse_chat_window(chat_window_stack: dict) -> Optional[ChatWindow]:
chat_window_nodes = __filter_nodes(chat_window_stack, lambda node: node[TYPE_NAME] == 'XmppChatWindow')
return ChatWindow(
name=__get_text_from_dict_entries(chat_window_nodes[0], NAME),
user_list=__parse_user_lists_from_c... |
def __get_ship_capacitor(ship_ui: dict) -> Optional[float]:
capacitor_container_nodes = __filter_nodes(ship_ui, lambda node: node[TYPE_NAME] == 'CapacitorContainer')
p_marks = __filter_nodes(
capacitor_container_nodes[0],
lambda node: __get_text_from_dict_entries(node, NAME) == 'pmark') if capac... | The main task of the code is to parse a dictionary containing ship UI data into a structured `ShipUI` object. It extracts specific attributes like capacitor percentage, speed text, HP percentages, and module buttons using helper functions, then initializes a `ShipUI` instance with these parsed values to organize and re... | def __parse_ship_ui(ship_ui: dict) -> ShipUI:
return ShipUI(
capacitor_percentage=__get_ship_capacitor(ship_ui),
speed_text=__get_ship_speed(ship_ui),
hp_percentages=__get_ship_hit_points(ship_ui),
module_buttons=__parse_module_buttons(ship_ui)
) |
def get_value_of_state(self, state_index):
"""
Getter to get value of state from Value Function
:param state_index: index of target state
:return: value of state as given by the value function
"""
return self._value_table[state_index]
def compute_value(self, state_index)... | The code performs Value Iteration on a simple MDP environment to compute the optimal value function. It iteratively updates state values using Bellman equations, considering transition probabilities, rewards, and discount factor (gamma). The process continues until the maximum value change (delta) between iterations fa... | def train(self, env_random_probability, largest_value_change, gamma):
"""
Perform Value Iteration on the simple MDP environment
:param env_random_probability: desired probability of transitioning to an unexpected state.
:param largest_value_change: Largest value at which the change can o... |
def complexity(dstrfs, batch_size=8):
"""
Measure general complexity of dSTRF function.
Arguments:
dstrfs: tensor of dSTRFs with shape [time * channel * lag * frequency]
Returns:
complexity: nonlinear function complexity, tensor of shape [channel]
"""
tdim, cdim, ldim, fdim... | This function computes four measures of nonlinearity (complexity, gain change, temporal hold, shape change) from dSTRF models stored in specified files. It loads each model, calculates the metrics using batch processing, aggregates results across files, applies optional reduction (mean/median), and returns a dictionary... | def nonlinearities(paths, reduction='none', batch_size=8, device='cpu', verbose=0):
nonliniearity = {
'complexity': [],
'gain change': [],
'temporal hold': [],
'shape change': []
}
if isinstance(paths, str) and os.path.isdir(paths):
paths = sorted(glob.glob(os.pa... |
def get_bounding_boxes(path_masked):
# assumes image is masked
img_orig = cv2.imread(path_masked)
# plt.imshow(img_orig)
img = cv2.cvtColor(img_orig, cv2.COLOR_BGR2RGB)
# plt.imshow(img)
contours = find_contours(img)
# print(len(contours))
contours = contours[1:]
boxes = []
fo... | The code segments original and masked images using bounding boxes derived from the masked image. It reads both images, extracts regions based on the bounding boxes, and saves the segmented parts to the specified output path, returning paths for both segmented masked and original image segments. | def segment(path_masked, path_original, output_path):
img_orig_masked = cv2.imread(path_masked)
img_masked = cv2.cvtColor(img_orig_masked, cv2.COLOR_BGR2RGB)
img_orig = cv2.imread(path_original)
img_original = cv2.cvtColor(img_orig, cv2.COLOR_BGR2RGB)
bounding_boxes = get_bounding_boxes(path_maske... |
def get_account_id():
sts_client = boto3.client('sts')
response = sts_client.get_caller_identity()
account_id = response['Account']
return account_id
def gen_api_headers(key, secret):
token = create_auth_token(key, secret)
req_header = {
'Authorization': f"Bearer {token}",
'date'... | This function configures AWS CloudTrail for an account by interacting with the Uptycs API. It reads API credentials from a file, constructs a request to link a specified S3 bucket in a given region to the account's CloudTrail, and returns success/failure status. The task involves securely authenticating, formatting API... | def account_cloudtrail_handler(api_config_file, bucket_name, bucket_region):
with open(api_config_file) as api_config_file:
uptycs_api_params = json.load(api_config_file)
account_id = get_account_id()
# uptycs_api_params = get_ssm_parameter(UPTYCS_API_PARAMETER_STORE)
domain = uptycs_api_params.... |
def get_account_id():
sts_client = boto3.client('sts')
response = sts_client.get_caller_identity()
account_id = response['Account']
return account_id
def gen_api_headers(key, secret):
token = create_auth_token(key, secret)
req_header = {
'Authorization': f"Bearer {token}",
'date'... | This function handles AWS account registration, deregistration, and updates with Uptycs via API. It reads credentials/config from a file, constructs API requests using IAM roles/external IDs, and executes actions like creating (POST with role ARN), deleting (deregistering), or updating (placeholder) AWS account integra... | def account_registration_handler(action, api_config_file, role_name, external_id=None):
with open(api_config_file) as api_config_file:
uptycs_api_params = json.load(api_config_file)
account_id = get_account_id()
# uptycs_api_params = get_ssm_parameter(UPTYCS_API_PARAMETER_STORE)
domain = uptycs_... |
def gen_api_headers(key, secret):
token = create_auth_token(key, secret)
req_header = {
'Authorization': f"Bearer {token}",
'date': datetime.datetime.utcnow().strftime("%a, %d %b %Y %H:%M:%S GMT"),
'Content-type': "application/json"
}
return req_header
def gen_cloudaccounts_api_u... | The main task of the code is to verify the validity of API credentials by reading configuration parameters, generating authentication headers, constructing a cloud account API URL, and checking if an HTTP GET request returns a 200 status code, indicating successful authentication. | def check_apikeys(config):
print("Checking api credentials")
with open(config) as api_config_file:
uptycs_api_params = json.load(api_config_file)
req_header = gen_api_headers(uptycs_api_params['key'], uptycs_api_params['secret'])
uptycs_api_url = gen_cloudaccounts_api_url(uptycs_api_params['dom... |
def get_account_id():
sts_client = boto3.client('sts')
response = sts_client.get_caller_identity()
account_id = response['Account']
return account_id
def check_for_existing_role(role_name):
iam_client = boto3.client('iam')
try:
role = iam_client.get_role(RoleName=role_name)
retur... | The main task of the code is to manage AWS CSPM integration with Uptycs by parsing command-line arguments to either check, create, or delete IAM roles and CloudFormation templates. It updates the External ID and IAM Role ARN in Uptycs via API, validates CloudTrail configurations, and handles AWS resource creation/delet... | def main():
"""
Main function to parse arguments and call Uptycs Web API to update External ID and IAM Role ARN in AWS CSPM integration
"""
parser = argparse.ArgumentParser(
description='Creates a cloudformation template to Integrate Uptycs with this account'
)
parser.add_argument('--act... |
def validate_args(args):
# Check if either --secret or --config is provided
if not args.secret and not args.config:
print("Error: You must provide either --secret or --config.")
sys.exit(1)
# Additional validation for 'Create' action
if args.action == 'Create':
required_args = [... | This script integrates Uptycs with AWS CloudFormation by handling three actions: 'Create' (to deploy a CloudFormation stack with Uptycs integration, validating parameters and API secrets), 'Check' (to validate configuration files and verify existing CloudTrail/trail data), and 'Delete' (to remove the CloudFormation sta... | def main():
parser = argparse.ArgumentParser(
description='Script to integrate Uptycs with CloudFormation.'
)
parser.add_argument('--action', choices=['Check', 'Create', 'Delete'], required=True,
help='The action to perform.')
parser.add_argument('--config', help='Path t... |
def seed_prefix(seed_type):
if seed_type == 'standard':
return SEED_PREFIX
elif seed_type == 'segwit':
return SEED_PREFIX_SW
elif seed_type == '2fa':
return SEED_PREFIX_2FA
elif seed_type == '2fa_segwit':
return SEED_PREFIX_2FA_SW
raise Exception(f"unknown seed_type: ... | This function generates a secure mnemonic seed by creating entropy with specified parameters, ensuring it meets entropy requirements, and validating it against BIP39 checksums and prefix checks to avoid accidental compatibility. It iterates to find a valid seed that can be decoded back to the original entropy and isn't... | def make_seed(self, *, seed_type=None, num_bits=None) -> str:
if seed_type is None:
seed_type = 'segwit'
if num_bits is None:
num_bits = 132
prefix = seed_prefix(seed_type)
# increase num_bits in order to obtain a uniform distribution for the last word
bpw... |
def create_display_frame(self):
frame = tk.Frame(self.window, height=221, bg=LIGHT_GRAY)
frame.pack(expand=True, fill='both')
return frame
def create_display_labels(self):
total_label = tk.Label(self.display_frame, text=self.total_expression,
anchor=tk.E, ... | This code initializes a calculator GUI using Tkinter, setting up the main window, display frames for expressions, and button layouts for digits and operators. It configures the window size, title, and creates interactive elements for arithmetic operations, ensuring a responsive grid layout for buttons. | def __init__(self):
self.window = tk.Tk()
self.window.geometry('375x667')
self.window.resizable(0, 0)
self.window.title('Calculator')
self.operations = {'/': '\u00F7', '*': '\u00D7', '-': '-', '+': '+'}
self.total_expression = ''
self.current_expression = ''
... |
def subranges(job: env.Job):
"""
Divide the search range [C_min, C_max] into a list of subranges and return it.
"""
bklgs = sorted([site.estimated_bklg_size for site in job.available_sites])
c_min = C_min(job)
c_max = C_max(job)
# `smallest` is the smallest index on which the element is lar... | The code implements the OBTA algorithm to solve an integer linear programming (ILP) problem for task assignment in a job. It iterates over subranges of a cost variable $ c $, formulating constraints to ensure task groups are processed by available sites while respecting site capacities and backlog limits. The algorithm... | def obta(job: env.Job, solution):
"""
The OBTA algorithm to obtain the assignment solution for the given job.
"""
estimated = -1
ranges = subranges(job)
solved = False
# Get the coefficient matrix
A = create_coeff_matrix(job)
for r in ranges:
# ----------------------------... |
def get_random(self, num):
print('random select ........')
if self.args.search_mode == 'iteration' or self.args.reallocate:
cand_iter = self.stack_random_cand(self.get_random_cand)
else:
cand_iter = self.stack_random_cand(self.get_random_cand_without_reallocate)
w... | The code performs a search for optimal neural network configurations using random, evolutionary, or force-based strategies. It evaluates candidates by their scores and parameters, iteratively refining intervals and maintaining top candidates. Results are stored in `interval_cands` and saved to a file or JSON, depending... | def search(self, out_file_name=None):
print('searching...')
if not self.args.block_score_method_for_mlp == 'deeper_is_better' or not self.args.block_score_method_for_head == 'deeper_is_better':
self.head_mlp_scores = self.score_maker.get_block_scores(self.model, self.args, self.choices)
... |
def get_args():
parser = argparse.ArgumentParser(description='Converts osu! beatmaps or beatmapsets to label file for custom nothing glyph tools\nThis is a second version of osu to glyph converter')
parser.add_argument('--osz', help='Path to the osz file', type=str, metavar='osz_file')
parser.add_argument('... | The main task of the code is to generate labeled output from a map based on command-line arguments. It retrieves input parameters, processes a map using specified modes ('np1' or 'np2'), converts the map to labels with a defined note size and seed, and writes the resulting labels to a specified output file. The code va... | def main():
args = get_args()
map = get_map(args)
mode = 'np2' if args.np2 else 'np1'
label = map_to_label(map, args.note_size, args.seed, mode)
if args.output == None:
print("Error: specify the --output argument")
return
else:
open(args.output, 'w', encoding='utf-8').wri... |
def update_action(self, new_action: str):
self.logger.debug(f"player.update_action({new_action})")
if new_action not in self.sprites.actions:
raise ValueError(f"action must be one of {self.sprites.actions}")
if new_action != self._action:
self._action = new_action
... | The code plays a death animation by updating the character's action state, updating the animation frame, adjusting the image's position, and rendering it on the screen. | def death_animation(self, screen):
self.update_action("death")
self.update()
self.rect = self.image.get_rect(bottomleft=self.rect.bottomleft)
self.draw(screen) |
def execute_ldap_command(current_dict, pending_dict):
"""
Executes the ldap command to verify user credentials.
Args:
current_dict (dictionary): Dictionary containing current credentials
pending_dict (dictionary): Dictionary containing pending credentials
Returns:
ldap_creds_succ... | The function creates a secret in AWS Secrets Manager if it doesn't already exist for the given token. It checks for an existing secret, generates a new random password if none is found, updates the provided dictionary with the new password and LDAP DN (if configured), and stores the secret with the specified ARN and to... | def create_secret(secrets_manager_client, arn, token, current_dict):
"""Create the secret # noqa: E501
This method first checks for the existence of a secret for the passed in token. If one does not exist, it will generate a
new secret and put it with the passed in token.
Args:
secrets_manager_c... |
def execute_ldap_command(current_dict, pending_dict):
"""
Executes the ldap command to verify user credentials.
Args:
current_dict (dictionary): Dictionary containing current credentials
pending_dict (dictionary): Dictionary containing pending credentials
Returns:
ldap_creds_succ... | The function updates a user's password in Directory Services using the pending credentials, ensuring the new password is set. However, it does not update the Secret Manager label, leaving a temporary mismatch between AWSCURRENT and Directory Services. The function checks if the new credentials are already active to avo... | def set_secret(current_dict, pending_dict):
"""Set the secret # noqa: E501
This is the second step, where Directory Services is actually updated.
This method does not update the Secret Manager label.
Therefore, the AWSCURRENT secret does not match the password in Directory
Services as the end of thi... |
def get_secret_dict(secrets_manager_client, arn, stage, token=None):
"""
Gets the secret dictionary corresponding for the secret arn, stage,
and token
This helper function gets credentials for the arn and stage passed in and
returns the dictionary
by parsing the JSON string. You can change the d... | This code handles the rotation of a LDAP user's password using AWS Secrets Manager. It processes events with steps like 'createSecret', 'setSecret', 'testSecret', and 'finishSecret' to generate new credentials, update LDAP, verify access, and finalize rotation. It validates secret versions, ensures proper staging (AWSP... | def lambda_handler(event, context):
"""Secrets Manager Rotation LDAP # noqa: E501
Rotates a password for a LDAP user account. This is the main lambda entry point.
This rotation lambda expects the secret in the secrets manager to include at least the user and password.
You can also update your user "dist... |
def _process_pixels(self):
"""Set the transparent pixels to the color 0."""
self._transparent_pixels = set(
idx for idx, alpha in enumerate(
self._img_rgba.getchannel(channel='A').getdata())
if alpha <= self._alpha_threshold)
def _process_palette(self):
""... | The code processes an RGBA image by converting it to a palette-based (mode 'P') image, adjusts pixel data and palette entries, sets transparency and background information, and returns the modified image. | def process(self) -> Image:
"""Return the processed mode `P` `Image`."""
self._img_p = self._img_rgba.convert(mode='P')
self._img_p_data = bytearray(self._img_p.tobytes())
self._palette_replaces = dict(idx_from=list(), idx_to=list())
self._process_pixels()
self._process_p... |
def tag_create(repo, name, object_id, type, msg=''):
if type=="lightweight":
# Create lightweight -- plain ref to a commit
# Create a file of given name at .git/refs/tags
path = repo.file('refs', 'tags', name)
with open(path, 'w') as f:
# Write commit id into file
... | This function creates or lists Git tags. If a name is provided, it generates an annotated or lightweight tag for a specified object, using an optional message. If no name is given, it lists all existing tags in the repository. | def cmd_tag(args):
repo = GitRepository.repo_find()
object_id = GitObject.object_find(repo, args.object)
if args.name:
# TODO: Need to pass in args.msg optionally into tag_create
tag_create(repo, args.name, object_id, type="annotated" if args.create_tag_object else "lightweight", msg = args... |
def shutdown_mysql(self):
# Shut Down MySQL
print("####################################################################################################")
print("Shutting Down MySQL server: - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -#")
print("################... | The main task of the code is to copy backup data back to restore a MySQL server. It sequentially executes shutdown_mysql(), move_datadir(), and copy() methods. If all succeed, it prints a success message and returns True; otherwise, it prints an error. The function ensures data restoration by validating each critical s... | def copy_back(self):
if self.shutdown_mysql():
if self.move_datadir():
if self.copy():
print("####################################################################################################")
print("All data copied back successfully your ... |
def check_mysql_uptime(self):
statusargs = '%s %s status' % (self.backup_class_obj.mysqladmin, self.backup_class_obj.myuseroption)
statusargs = shlex.split(statusargs)
myadmin = subprocess.Popen(statusargs, stdout=subprocess.PIPE)
if not ('Uptime' in str(myadmin.stdout.read())):
... | The main task of the code is to verify the MySQL environment's readiness by sequentially checking prerequisites such as MySQL uptime, service status, administrative tools, configuration files, backup directories, and user permissions. If all checks pass, it returns `True` with a success message; otherwise, it returns `... | def check_all_env(self):
env_result = False
if self.check_mysql_uptime():
if self.check_mysql_mysql():
if self.check_mysql_mysqladmin():
if self.check_mysql_conf():
if self.check_mysql_backuptool():
if ... |
def simpleSolve(self, trace):
cycle = 0
stuck = 0
while not self.board.isSolved() and stuck < STUCK_LIMIT and cycle < CYCLE_LIMIT:
if self.run(trace) > 0:
stuck = 0
if trace:
print(self.board)
else:
stuck... | The code implements a backtracking algorithm to solve a constraint satisfaction problem (e.g., Sudoku) using heuristics. It prioritizes cells with the smallest domain (MRV) and applies the least constraining value (LCV) heuristic. The algorithm attempts a simple solution first; if unsuccessful, it iteratively explores ... | def backTrackingSolve(self, cycle = 0):
backtrack = Stack()
while not self.board.isSolved() and cycle < CYCLE_LIMIT:
# try a simple solution first
try:
simp = self.simpleSolve(False)
cycle += abs(simp)
if simp > 0:
... |
def stem(x, filters, kernel_size=(3,3), padding="same", strides=1):
conv = Conv2D(filters, kernel_size, padding=padding, strides=strides)(x)
conv = conv_block(conv, filters, kernel_size=kernel_size, padding=padding, strides=strides)
shortcut = Conv2D(filters, kernel_size=(1,1), padding=padding, strides... | The code defines a ResUNet model for image segmentation. It constructs an encoder with residual blocks to extract hierarchical features, a bridge to transition between encoder and decoder, and a decoder with upsampling and residual blocks to reconstruct segmented output. The model uses skip connections and a sigmoid ac... | def ResUNet():
f = [16, 32, 64, 128, 256]
inputs = Input((IMAGE_SIZE, IMAGE_SIZE, 3))
# ENCODER
e0 = inputs
e1 = stem(e0, f[0])
e2 = residual_block(e1, f[1], strides=2)
e3 = residual_block(e2, f[2], strides=2)
e4 = residual_block(e3, f[3], strides=2)
e5 = residual_block(e4, f[4]... |
def immuneSupport(self, cell:HelperImmuneCell):
# boosts immune cell proliferation and reduces infected
# cell's infection probability
localCells = self.getLocalCells(cell.x, cell.y)
if len(localCells) == 0: return 0
for _cell in localCells:
if _cell.infected: _cell.b... | This method determines an immune cell's action by evaluating attack, move, and pass utilities. If immune, it deactivates helper cells, compares utility values, and executes the highest-priority action: attacking, moving (randomly or to a calculated position), or suppressing. Returns specific status codes (-1, 0, or fun... | def immuneAct(self, cell):
if cell.immune:
if cell.helper: cell.suppress = cell.support = False
if cell.activated: cell.activated = False
attackUtil = cell.util("ATTACK",cell,self)
passUtil = cell.util("PASS",cell,self)
moveUtil, pos = cell.util("MOVE"... |
def reproduceCell(self, cell):
#reproduces cell if random number is less than reproduction probability
sample = bernoulli.rvs(cell.repro_prob)
if sample == 1:
neighs = self.getEmptyNeighbors(cell.x, cell.y)
if len(neighs) > 0:
newCoords = rand.choice(neigh... | The `step` function simulates a cellular process by iterating through each cell, decrementing counters, and triggering actions like reproduction, infection, immune activation, and death. It tracks counts of these events (e.g., infections, reproductions, immune responses) and verifies cell consistency between lists and ... | def step(self):
_numActivated = 0
_numMoved = 0
_numInfected = 0
_numReproduce = 0
_numBoosted = 0 # helper boosts
_numSuppressed = 0 # helper supresses
_numKilled = 0 # immune attacks
_numDied = 0
for cell in self.cells:
cel... |
def getNumRows(self) -> int:
pass
def whatsAtPos(self, pos) -> str:
pass
def checkHorizWin(self, pos, player) -> bool:
r = pos.getRow()
c = pos.getColumn()-1
count = 1
#Searches to the left of the last token
while c > -1:
temp = BoardPosition(r, c)
... | This function checks if placing a piece in the specified column results in a win by iterating from the bottom row upward. For each non-empty position, it checks horizontal, vertical, and diagonal win conditions starting from the cell above. If any win condition is met, it returns True; otherwise, it returns False after... | def checkForWin(self, col) -> bool:
for i in range(self.getNumRows()-1, -1, -1):
temp = BoardPosition(i, col)
if self.whatsAtPos(temp) == ' ':
pos = BoardPosition(i+1, col)
player = self.whatsAtPos(pos)
if self.checkHorizWin(pos, player):
... |
def _init(self):
self._waypoint_planner = RoutePlanner(4.0, 50)
self._waypoint_planner.set_route(self._plan_gps_HACK, True)
self._command_planner = RoutePlanner(7.5, 25.0, 257)
self._command_planner.set_route(self._global_plan, True)
self._route_planner = RoutePlanner(4.0, 50.0)
self._route_planner.set_ro... | The main task of the code is to generate vehicle control commands (steer, throttle, brake) in a CARLA simulation using a policy network, incorporating path planning, collision avoidance, and random exploration. It initializes the system, processes input data, runs planners for navigation, executes the policy for action... | def run_step(self, input_data, timestamp):
if not self.initialized:
self._init()
self.step += 1
if self.step < 20:
control = carla.VehicleControl()
control.steer = 0.0
control.throttle = 0.0
control.brake = 0.0
self.last_control = control
return control
if self.step % 2 != 0:
return ... |
def _run_openscenario(self):
"""
Run a scenario based on OpenSCENARIO
"""
# Load the scenario configurations provided in the config file
if not os.path.isfile(self._args.openscenario):
print("File does not exist")
self._cleanup()
return False
... | The code's main task is to execute scenarios based on command-line arguments. It checks for flags like `openscenario` or `route`, running the corresponding method (`_run_openscenario` or `_run_route`), or defaults to `_run_scenarios` if no flags are set. It returns the result of the executed scenarios and exits after p... | def run(self):
"""
Run all scenarios according to provided commandline args
"""
result = True
if self._args.openscenario:
result = self._run_openscenario()
elif self._args.route:
result = self._run_route()
else:
result = self._r... |
def get_indent(self, line):
"""Get the indent of a line"""
comp = re.compile(r"^ *")
return len(comp.findall(line)[0])
def determine(self, line):
"""Determine a line type"""
if line.split(" ")[1] == "<-":
self.set_variable(line)
if line.startswith("OUTPUT"):... | This code interprets a custom scripting language by parsing lines of content, checking syntax validity, handling variable assignments, control flow (IF/ELSE), and output commands. It skips comments and empty lines, processes indentation for block structures, and executes commands sequentially while validating syntax ru... | def compile(self):
"""Interpreter"""
if not self.content:
return "No content"
for i, line in enumerate(self.content.splitlines()):
if len(line.split(" ")) == 1 and line == "" or line.startswith("//"):
continue
try:
if self.con... |
def sort_cue(self, current_floor, cue):
cue_up = []
cue_down = []
for i in cue:
if i >= current_floor:
cue_up.append(i)
else:
cue_down.append(i)
sorted_cue = sorted(cue_up) + sorted(cue_down, reverse=True)
return sorted_cue
... | The code processes an elevator's movement by sorting target floors, moving to the next target (up/down), opening doors when arriving, and recursively continuing until all cues are addressed. | def run_elevator(self):
if len(self.cue) == 0:
return
else:
self.cue = self.sort_cue(self.current_floor, list(set(self.cue)))
next_target_floor = self.cue[0]
if next_target_floor == self.current_floor:
print("The Elevator %s is on floor %s.... |
def wait_and_rerender_hands(self):
time.sleep(GameHandler.WAIT_BETWEEN_TURNS)
self.rerender_hands()
def player_draws_card(self, player):
player.add_card_to_hand(self.deck.draw_card())
def make_bids(self):
for player in self.players:
player.is_his_turn = True
self.... | The main task of the code is to initialize a card game by dealing cards to the dealer and players, updating the UI after each card draw, and transitioning to the bidding phase. It handles sequential card distribution with visual feedback, ensuring proper rendering after each action to maintain game state visibility. | def setup_game(self):
self.screen_builder.with_header("handing out cards..")
self.wait_and_rerender_hands()
self.player_draws_card(self.dealer)
self.wait_and_rerender_hands()
for player in self.players:
self.player_draws_card(player)
self.wait_and_rerender... |
def setup_game(self):
self.screen_builder.with_header("handing out cards..")
self.wait_and_rerender_hands()
self.player_draws_card(self.dealer)
self.wait_and_rerender_hands()
for player in self.players:
self.player_draws_card(player)
self.wait_and_rerender... | The main task of the code is to execute the complete game lifecycle by sequentially initializing the game with `setup_game()`, starting the game with `start_game()`, and concluding the game with `finish_game()`. This method orchestrates the game's initialization, execution, and termination phases in a structured manner... | def play_game(self):
self.setup_game()
self.start_game()
self.finish_game() |
def trainset_process(filename, flag, stop_words):
questions = extract_questions(filename)
# print("Number of Questions",np.shape(questions))
# print([question for question in questions if 'California' in question])
words = extract_allwords(filename)
### Maybe because of set() the order of the voc... | The code processes training and test data for text classification, using a logistic regression model. It parses command-line arguments, preprocesses text (removing stop words and punctuation), extracts features from training data, and applies the model to predict labels on the test set. The main task is to classify tex... | def main():
args = sys.argv
flag = args[1]
filename = args[2]
testfile = args[3]
stop_words = set(["´´", "``", "the", "in", "of", "is", "a", "s", "'s", "d", "ll", "m", "o", "re", "ve", "y", "n't"] + list(punctuation))
question_categories = set(["how", "who", "when", "where", "what", "which"])... |
def _determine_starting_weapon(self, level: Optional[str] = None) -> dict:
weapon_list = self.all_weapons
if level:
weapon_list = self.weapons_by_level[level]
# pick random starting weapon and set for later slot data
random_weapon = self.random.choice(weapon_list)
s... | The code's main task is to assign weapons and ammo to locations by matching weapons to their designated groups, ensuring each weapon is used once. It selects random weapons from predefined groups, queues swaps for both weapons and ammo, and removes matched items from the pool to prevent reuse, finally applying all swap... | def match(self):
random_weapon = self._determine_starting_weapon('light') # match starting weapon level too
self._queue_swap(self.starting_ammo_name, random_weapon['ammo'], "Ammo")
weapons = self._get_weapons_from_locations()
for weapon in weapons:
for key in self.we... |
def _determine_starting_weapon(self, level: Optional[str] = None) -> dict:
weapon_list = self.all_weapons
if level:
weapon_list = self.weapons_by_level[level]
# pick random starting weapon and set for later slot data
random_weapon = self.random.choice(weapon_list)
s... | This function randomly swaps weapons and optionally their ammo between locations, starting with a random weapon. If include_ammo is True, it also swaps ammo. It ensures each weapon is used only once by removing matched weapons from the list, then executes all queued swaps at designated locations. | def full(self, include_ammo: Optional[bool] = True):
random_weapon = self._determine_starting_weapon()
if include_ammo:
self._queue_swap(self.starting_ammo_name, random_weapon['ammo'], "Ammo")
weapons = self._get_weapons_from_locations()
for weapon in weapons:
... |
def _get_weapons_from_locations(self):
weapons = []
for loc in self._get_weapon_locations():
original_item = loc.get("original_item", None)
original_item = self.world.item_name_to_item.get(original_item, {})
if original_item.get("type") == "Weapon" and original_item... | The code's main task is to modify weapon locations in a game by replacing non-starting weapons with "Wooden Boards" and tracking randomly selected weapons. It excludes the starting weapon, selects two random weapons, updates forced/original items in locations to "Wooden Boards" if they don't match the selected weapons,... | def troll(self):
# self.all_ammo() is called during processing of options, and self.troll() is specifically called after upgrades, gunpowder, etc.
weapons = [w for w in self._get_weapons_from_locations() if w['name'] != self.world.starting_weapon[self.world.player]]
only_weapons = [self.world.i... |
def _get_weapons_from_locations(self):
weapons = []
for loc in self._get_weapon_locations():
original_item = loc.get("original_item", None)
original_item = self.world.item_name_to_item.get(original_item, {})
if original_item.get("type") == "Weapon" and original_item... | This function categorizes and distributes ammo types (light, medium, heavy) based on weapon levels in a game. It identifies weapons at locations, maps required ammo per level, filters ammo locations to avoid overlaps between levels, and evenly assigns ammo types to locations. The result ensures each weapon level's ammo... | def _split_ammo_by_level(self, level: Optional[str] = None):
levels = self.weapons_by_level.keys()
if level:
levels = [level]
else:
self.world.replacement_ammo[self.world.player] = {} # if we're splitting all ammo by level, this includes starting, so remove it and anythi... |
def _get_weapons_from_locations(self):
weapons = []
for loc in self._get_weapon_locations():
original_item = loc.get("original_item", None)
original_item = self.world.item_name_to_item.get(original_item, {})
if original_item.get("type") == "Weapon" and original_item... | The function randomly assigns ammo types to weapon locations in a game, ensuring each required ammo type is used at least once. It collects all placed weapons and their ammo needs, deduplicates the list, then replaces each ammo location with a random selection from the deduplicated list, updating the game world's ammo ... | def _split_ammo_randomly(self):
self.world.replacement_ammo[self.world.player] = {} # all ammo is completely random, so skip starting listing(s) too
placed_weapons = [self.world.item_name_to_item.get(w.get('name')) for w in self._get_weapons_from_locations()]
starting_weapon = self.world.item_n... |
def _determine_starting_weapon(self, level: Optional[str] = None) -> dict:
weapon_list = self.all_weapons
if level:
weapon_list = self.weapons_by_level[level]
# pick random starting weapon and set for later slot data
random_weapon = self.random.choice(weapon_list)
s... | This function assigns weapons to locations by randomly replacing base weapons with unique selections from a pool, ensuring no duplicates. It queues swaps, updates game state locations, and logs replacements. If include_ammo is True, it also splits ammo by level. The process ensures each weapon is placed once, maintaini... | def all(self, include_ammo: Optional[bool] = True):
self._determine_starting_weapon()
weapons = self._get_weapons_from_locations()
# replace the base weapons...
for weapon in weapons:
matched = self.random.choice(self.all_weapons)
self._queue_swap(weapon['name'],... |
def skip_space_sequence(parsers: tuple[StrParser[Any, Any]]) -> StrParser[Any, Any]:
ret_parsers = []
for p in parsers:
ret_parsers.append(p)
ret_parsers.append(take_while(lambda c: c in " \t\n"))
return parser_map(sequence(tuple(ret_parsers)), lambda x: x[::2])
def parser_times() -> StrPars... | This function parses arithmetic expressions with + and - operators, handling left associativity. It uses `parser_map` to combine terms parsed by `parser_times()` with sequences of alternating +/− operators, skipping spaces, and applies `assoc_left` to resolve operator precedence and associativity for left-associative o... | def parser_plus_minus() -> StrParser[list[Plus | Minus], str]:
return parser_map(
skip_space_sequence(
(
parser_times(),
many0(skip_space_sequence((alt((tag("+"), tag("-"))), parser_times()))),
)
),
lambda x: assoc_left(x[0], x[1]),
... |
def skip_space_sequence(parsers: tuple[StrParser[Any, Any]]) -> StrParser[Any, Any]:
ret_parsers = []
for p in parsers:
ret_parsers.append(p)
ret_parsers.append(take_while(lambda c: c in " \t\n"))
return parser_map(sequence(tuple(ret_parsers)), lambda x: x[::2])
def parser_name() -> StrParse... | This function parses a string into a tuple containing a name and a value, skipping spaces. It uses `parser_map` to combine parsers for the name, equals sign, and value, then extracts the first and third elements of the parsed result to form the output tuple. | def parser_bind() -> StrParser[tuple[str, Value]]:
return parser_map(
skip_space_sequence((parser_name(), tag("="), parser_value())),
lambda x: (x[0], x[2]),
) |
def skip_space_sequence(parsers: tuple[StrParser[Any, Any]]) -> StrParser[Any, Any]:
ret_parsers = []
for p in parsers:
ret_parsers.append(p)
ret_parsers.append(take_while(lambda c: c in " \t\n"))
return parser_map(sequence(tuple(ret_parsers)), lambda x: x[::2])
def parser_plus_minus() -> St... | The code defines a parser for expressions involving operators and tags, handling whitespace and combining parsed elements with left associativity using `assoc_left`, structured to process sequences of operators and `<`-tagged components. | def parser_lt() -> StrParser[Lt, str]:
return parser_map(
skip_space_sequence(
(
parser_plus_minus(),
many0(skip_space_sequence((tag("<"), parser_plus_minus()))),
)
),
lambda x: assoc_left(x[0], x[1]),
) |
def parser_let() -> StrParser[Let, str]:
return parser_map(
skip_space_sequence(
(tag("let"), parser_name(), tag("="), parser_expr, tag("in"), parser_expr)
),
lambda x: Let(key=x[1], e1=x[3], e2=x[5]),
)
def parser_letrec() -> StrParser[LetRec, str]:
return parser_map(
... | The code defines a parser function `parser_expr` that attempts to parse a string `s` using alternative parsers for different expression types (let, letrec, fun, if, lt). It returns a parser result containing either a parsed expression or the remaining string if no parser matches. | def parser_expr(s: str) -> StrParserResult[Expr, str]:
return alt(
[
parser_let(),
parser_letrec(),
parser_fun(),
parser_if(),
parser_lt(),
]
)(s) |
def is_open_now(opening_hours) -> bool:
"""Return True if the restaurant is open now, False otherwise.
Args:
opening_hours (list): The opening hours of the restaurant
Returns:
bool: True if the restaurant is open now, False otherwise
"""
if len(opening_hours) == 1 and opening_hours... | The main task of the code is to extract and format restaurant data from a database, including its current operational status (with Open/Closed indicators), Google Maps link, website, and human-readable opening hours. It processes JSON data to determine business status, checks opening hours for real-time availability, a... | def get_gmaps_info(current_page) -> list[str]:
"""Return open status, link to google maps link, and the website, if available.
open status: identical to the business status on google maps if the restaurant is
permanently closed or temporarily closed. Otherwise, current open status based on ope... |
def create_manual_embed(current_page) -> tuple:
"""Creates manual embeds for restaurants that require special formatting.
Such restaurants are defined in MANUAL_EMBED_RESTAURANTS.
Args:
current_page (int): The current page of PaginationView.
Returns:
(discord.File, discord.Embed): A t... | The function generates a Discord embed with restaurant details for a pagination interface, using either manual data or dynamic info like address, price range, tier, and Google Maps data. It includes specific website links for certain restaurants and returns the embed along with a thumbnail file. | def create_restaurants_embed(current_page) -> tuple:
"""Creates individual restaurant embeds for PaginationView.
Args:
current_page (int): The current page of PaginationView.
Returns:
(discord.File, discord.Embed): A tuple of the thumbnail file and the embed for the restaurant.
"""
... |
def wait_until_element_displayed(self, data: str):
target = self.process_data(data)
if type(target) == list:
target = target[0]
return self._waite.until(lambda display: target.is_displayed())
def _assertion_and_click(self, data, tag_str: str = None):
if type(data) == list:
... | This function waits for a web element to be displayed using provided data, processes the data, performs an assertion, and then clicks the element. The 'tag' parameter is optional and may be used in the assertion logic. The core task is to ensure an element is visible and interactable before clicking it, with data proce... | def click_element(self, data, tag: str = None):
self.wait_until_element_displayed(data)
self._assertion_and_click(self.process_data(data), tag) |
def translation(self,l,color,tx,ty):
input("Translation (Press Enter)")
l = self.add_padding(l)
translation_matrix = [[1,0,0],[0,1,0],[-tx,-ty,1]]
resultant_matrix = self.matrix_multiply(l,translation_matrix)
resultant_matrix = self.remove_padding(resultant_matrix)
return... | The main task of the code is to scale a polygon using a scaling matrix (sx, sy) while applying translation transformations (tx, ty) before and after scaling. It translates the polygon, draws it, applies the scaling matrix, removes padding, redraws the scaled result, and finally translates it back to its original positi... | def scalling(self,l,color,tx,ty,sx,sy):
l = self.translation(l,color,tx,ty)
self.draw_polygon(l,color)
input("Scalling (Press Enter)")
self.draw_polygon(l,"gray")
self.set_axis(-400,-400,400,400)
l = self.add_padding(l)
scalling_matrix = [[sx,0,0],[0,sy,0],[0,0,1]... |
def draw_polygon(self,l,color):
x0,y0 = l[0][0],l[0][1]
x1,y1 = x0,y0
i=1
while(i<len(l)):
x2,y2 = l[i][0],l[i][1]
self.draw_line(x1,y1,x2,y2,color)
x1,y1 = x2,y2
i+=1
self.draw_line(x2,y2,x0,y0,color)
def set_axis(self,xvmin,yvmin,xvmax,yvmax):
l = Line(Point(xv... | The main task of the code is to rotate a polygon's coordinates by a specified angle using a rotation matrix. It converts the angle to radians, applies the rotation matrix to each point in the padded input list, and returns the transformed coordinates after removing padding. The function handles user input, coordinate s... | def main_rotation(self,l,color,x,y,angle):
input("Rotation (Press Enter)")
self.draw_polygon(l,"gray")
self.set_axis(-400,-400,400,400)
angle = (math.pi*angle/180)
l = self.add_padding(l)
rotation_matrix = [[math.cos(angle),math.sin(angle),0],[-math.sin(angle),math.cos(an... |
def draw_polygon(self,l,color):
x0,y0 = l[0][0],l[0][1]
x1,y1 = x0,y0
i=1
while(i<len(l)):
x2,y2 = l[i][0],l[i][1]
self.draw_line(x1,y1,x2,y2,color)
x1,y1 = x2,y2
i+=1
self.draw_line(x2,y2,x0,y0,color)
def add_padding(self,l):
for i in l:
i.append(1)
... | The function rotates a polygon's coordinates by a specified angle using a rotation matrix. It converts the angle to radians, adds padding to the coordinate list, applies matrix multiplication with the rotation matrix, and removes padding before returning the rotated coordinates. | def main_rotation(self,l,x,y,angle):
self.draw_polygon(l,"gray")
angle = (math.pi*angle/180)
l = self.add_padding(l)
rotation_matrix = [[math.cos(angle),math.sin(angle),0],[-math.sin(angle),math.cos(angle),0],[0,0,1]]
resultant_matrix = self.matrix_multiply(l,rotation_matrix)
... |
def translation(self,l,color,tx,ty):
input("Translation (Press Enter)")
l = self.add_padding(l)
translation_matrix = [[1,0,0],[0,1,0],[-tx,-ty,1]]
resultant_matrix = self.matrix_multiply(l,translation_matrix)
resultant_matrix = self.remove_padding(resultant_matrix)
return... | The code rotates a polygon around a specified point (x,y) by applying translation, rotation, and reverse translation. It draws the original, rotated, and gray-scaled versions, sets axes, and returns the final rotated coordinates. | def rotation(self,l,color,x,y,angle):
l = self.translation(l,color,x,y)
self.draw_polygon(l,color)
resultant_matrix = self.main_rotation(l,color,x,y,angle)
self.draw_polygon(resultant_matrix,color)
input("Press Enter")
self.draw_polygon(resultant_matrix,"gray")
se... |
def translation(self,l,color,tx,ty):
input("Translation (Press Enter)")
l = self.add_padding(l)
translation_matrix = [[1,0,0],[0,1,0],[-tx,-ty,1]]
resultant_matrix = self.matrix_multiply(l,translation_matrix)
resultant_matrix = self.remove_padding(resultant_matrix)
return... | The function performs a reflection of a polygon by translating it, rotating, applying a reflection matrix (mirroring over the y-axis), then reversing the rotation and translation. It visualizes each transformation step, including drawing the polygon in color and gray, adjusting axes, and returning the final transformed... | def reflection(self,l,color,x,y,angle):
l = self.translation(l,color,x,y)
self.draw_polygon(l,color)
input("Press Enter")
self.draw_polygon(l,"gray")
self.set_axis(-400,-400,400,400)
l = self.main_rotation(l,color,x,y,angle)
self.draw_polygon(l,color)
inpu... |
def translation(self,l,tx,ty):
l = self.add_padding(l)
translation_matrix = [[1,0,0],[0,1,0],[-tx,-ty,1]]
resultant_matrix = self.matrix_multiply(l,translation_matrix)
resultant_matrix = self.remove_padding(resultant_matrix)
return resultant_matrix
def main_rotation(self,l,x,y,an... | The main task of the code is to reflect a matrix `l` around a specified point `(x, y)` with a given angle. It achieves this by translating the matrix to the origin, rotating it, applying a reflection transformation using a 3x3 reflection matrix, reversing the rotation, and translating back to the original coordinate sy... | def reflection(self,l,x,y,angle):
l = self.translation(l,x,y)
l = self.main_rotation(l,x,y,angle)
l = self.add_padding(l)
reflection_matrix = [[-1,0,0],[0,1,0],[0,0,1]]
resultant_matrix = self.matrix_multiply(l,reflection_matrix)
resultant_matrix = self.remove_padding(res... |
def _read_configuration(self):
with open(self._cfg_path) as file:
props = dict(line.strip().split('=', 1) for line in file)
for k, v in props.items():
value = v
param_type, name = k.split(".")
if name == 'RepositoryName':
self._repository_n... | The main task of the code is to execute a deployment process by reading configuration, building a Docker image (unless skipped), retrieving the image path, and handling stack changes, while logging errors if exceptions occur during execution. | def run_cmd(self):
try:
self._read_configuration()
if not self.skip_build:
self.build_image()
else:
self._logger.info(f"$$> Skipping building image")
self.get_image_path()
self._handle_stack_change()
except Excep... |
def _get_project_info(self, api_key):
'''Get the project info from the API based on the project ID'''
r = requests.get(self.project_url, headers={"X-TrackerToken": api_key})
if r.ok:
self.project_info = r.json()
print(self.project_info['name'])
else:
... | The main task of the code is to retrieve project information and paginated activity data from an API using the provided API key, populate the Project object with this data, and parse stories if they are not already present. The function handles potential exceptions during API calls and ensures the Project object is ful... | def get_project_data(self, api_key):
''' Retrieve content from the API and populate the Project object '''
try:
self._get_project_info(api_key)
self._get_paginated_activity(api_key)
if self.stories == {}:
self._parse_stories()
except:
... |
def hist_points(pid, duration_limit=None):
'''Show a histogram of duration of stories colored by estimate'''
if pid in projects.keys():
p = projects[pid]
else:
return
project_name = p.project_info['name']
data = clean_df(pid, duration_limit)
if not data.empty:
data = d... | The main task of the code is to generate a project overview by creating visualizations: a histogram showing delivery times grouped by estimate, a boxplot analyzing story durations, and a timeline of story creators. These plots help analyze project efficiency, story complexity distribution, and contributor activity over... | def tell_me_about(pid, duration_limit=None):
'''Generate an overview of a project'''
# Histogram of how long it took to deliver stories broken up by estimate
hist_points(pid, duration_limit)
# Boxplot of stories and durations
show_boxplot(pid, duration_limit)
# Stories created by person over ... |
def Get_Mail():
#Getting user mail and perfroming specified operations(Add,remove etc)
# Making the variables global to access them inside this function
global body
Check_Mail = 0 #condition to train pickle
global image_dir
# specifying login credentials
SERVER = 'imap.gmail.com'
# connect ... | The main task of the code is real-time face recognition using a pre-trained model (train1.pkl) to identify known individuals from camera input. It captures video, detects faces, compares encodings with known data, labels unknown faces, saves unidentifiable images, and triggers email alerts for unknown faces. The system... | def main():
#Main part of the program.
#Run on bootup.
#Define variables
Encodings=[]
Names=[]
Check_Unkown=1 # 1 if only unknown,0 if known
global Image_Id_Number
global No_Enc_Count
#Train known images.
#print("here2")
#Train_Pickle()
#print("here3")
#Open already existin... |
def process_documents(documents):
for document in documents:
words = document.split() # Assuming documents are provided as strings of words
for i, word in enumerate(words):
# Define the context window
context_start = max(0, i - C)
context_end = min(len(words), i ... | The code processes text data in chunks from a CSV file, computes context vectors for specific terms, and calculates cosine similarities and Euclidean distances between these vectors to analyze semantic relationships between words like 'ruling', 'verdict', 'seizure', and 'capture'. | def main():
#df, df_tfidfvect = generate_vocabulary_and_word_matrix()
# load directly
#true = pd.read_csv('dataset/ISOT/True.csv')
#fake = pd.read_csv('dataset/ISOT/Fake.csv')
#df = pd.concat([true, fake])
#df.to_csv('dataset/ISOT/True_Fake.csv')
chunksize = 50
with pd.read_csv('dataset/... |
def extract(self, V, name='all'):
assert (V is not None and (name == 'T' or name == 'L' or name == 'P' or name == 'all'))
if name == 'all':
return self.extract(V, 'T'), self.extract(V, 'L'), self.extract(V, 'P')
size = int(self.trains * self.stations)
(start, end) = (0, size)... | This function validates that computed values for trains and stations in a solution meet non-negative constraints. It extracts variables T, L, P from Vsol, then iterates over all trains and stations to assert that minimum and maximum valid values for L, T, P are ≥ 0, ensuring solution feasibility. | def assert_results2(self, Vsol):
Tsol, Lsol, Psol = self.extract(Vsol)
for i in range(self.trains):
for j in range(self.stations):
assert (self.min_valid_L(Vsol, i, j) >= 0 and self.max_valid_L(Vsol, i, j) >= 0)
assert (self.min_valid_T(Vsol, i, j) >= 0 and se... |
def get_current_station(self, train):
return self.states[train].station + (self.states[train].state == states.MOVING)
def calc_period_till_boarding(self, train, station):
return self.calc_waiting_time(train)+self.calc_arriving_time(train, station)\
+ self.calc_alighting_time(train, station)
... | The code calculates the estimated departure time of a train from its current station by summing the current time, the time until boarding begins, and the duration required for boarding passengers. It retrieves the current station, computes the boarding start time and duration, then returns the total as the estimated de... | def calc_est_depart_time(self, train):
station = self.get_current_station(train)
# calculating time until train is start boarding passengers:
period_till_boarding = self.calc_period_till_boarding(train, station)
boarding_time = self.calc_boarding_time(train, station, period_till_boarding... |
def extract(self, V, name='all'):
assert (V is not None and (name == 'T' or name == 'L' or name == 'P' or name == 'all'))
if name == 'all':
return self.extract(V, 'T'), self.extract(V, 'L'), self.extract(V, 'P')
size = int(self.trains * self.stations)
(start, end) = (0, size)... | The function `L_rule` computes the difference between the value at position `(i, j)` in matrix `L` and the result of subtracting the sum of `alight_amount` and `board_amount` from `load_before_alight`, all derived from the extracted parameters `T`, `L`, and `P` from input `V`. This likely represents a rule for adjustin... | def L_rule(self, V, i, j):
T, L, P = self.extract(V)
return L[i, j] - (
self.load_before_alight(L, i, j) - self.alight_amount(L, i, j) + self.board_amount(L, P, i, j)) |
def extract(self, V, name='all'):
assert (V is not None and (name == 'T' or name == 'L' or name == 'P' or name == 'all'))
if name == 'all':
return self.extract(V, 'T'), self.extract(V, 'L'), self.extract(V, 'P')
size = int(self.trains * self.stations)
(start, end) = (0, size)... | The function `P_rule` calculates the difference between the value at position `(i, j)` in matrix `P` and the sum of arriving amounts and prior block amounts, returning this difference. It uses extracted data `T`, `L`, `P` from input `V`, checks if `i` is zero to determine prior block counts, and applies this to compute... | def P_rule(self, V, i, j):
T, L, P = self.extract(V)
was_before = 0 if i == 0 else self.block_amount(L, P, i - 1, j)
return P[i, j] - (self.arrive_amount(T, i, j) + was_before) |
def extract(self, V, name='all'):
assert (V is not None and (name == 'T' or name == 'L' or name == 'P' or name == 'all'))
if name == 'all':
return self.extract(V, 'T'), self.extract(V, 'L'), self.extract(V, 'P')
size = int(self.trains * self.stations)
(start, end) = (0, size)... | The function calculates the difference between a time value T[i,j] and the sum of arrival time, stay time, alight time, and boarding time, returning the result as a time difference or remaining time. | def T_rule(self, V, i, j):
T, L, P = self.extract(V)
t_stay = self.S[i, j]
return T[i, j] - (
self.t_arrive_to_station(T, i, j) + t_stay + self.t_alight(L, i, j) + self.t_board(L, P, i, j)) |
def food(position, button_height, cube):
while True:
food_x = random.randrange(0, display_width / cube) * cube
food_y = random.randrange(int(button_height / cube), display_height / cube) * cube
if [food_x, food_y] not in position:
break
return food_x, food_y
def move... | This code implements a snake game where the player controls a snake to move on a grid, avoid collisions with walls and itself, eat food to grow, and reset the game. It handles input, movement logic, collision detection, food generation, and rendering using Pygame. | def main():
gameExit = False
cube = 20
action = 0
init_snake_length = 3
button_height = 2 * cube
snake_x_change = 0
snake_y_change = 0
key = 1
speed = 0.1
position = []
snake_x = random.randrange(int((display_width / cube) * 0.25), int((display_width / cube) * 0.75)) * ... |
def read_data():
f = open("data/validationDataset.txt", "r")
fData = f.readlines()
lData = []
for sIter in fData:
if (sIter[-1] == "\n"):
sIter = sIter[:-1]
if (sIter == ""):
continue
lData.append(sIter.split(","))
return lData
def create_dictionary(l... | The code processes data by reading input, creating dictionaries, applying star reduction with a condition, building a star tree, and generating cuboid values for star cubing. It initializes a cuboid list with wildcards and executes the starcubing algorithm on the tree structure, though some variables like 'lKeys' are u... | def main():
nIcebergCondn = 2
lData = read_data()
lDicts = create_dictionary(lData)
lData1 = star_reduction(lData, lDicts, nIcebergCondn)
star_tree = create_star_tree(lKeys)
lCuboidValList = ["*"] * (len(lData[0]) + 1)
starcubing(star_tree, star_tree, 0, lCuboidValList) |
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):
self._node_count += 1
n_samples = len(data)
if n_samples == 0:
return None
if n_samples == 1 or hash_func_index ... | The code builds a tree structure using Locality-Sensitive Hashing (LSH) to process high-dimensional data. It sets parameters like sample count and depth limit, formats input data, recursively constructs a tree with a specified depth, calculates average branch factor, and stores reference path length for efficient neare... | def fit(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_branch_... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.