dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def create_type_to_descendants(self):
# Create a dictionary from type to all of its descendants
type_to_descendants = {}
for t in self.t.get_descendants('biolink:NamedThing',formatted=True):
try:
type_to_descendants[t] = self.t.get_descendants(t,formatted=True)
... | The code initializes a Descender class to load data either from Redis (if an rc is provided) or from a local method (bmt). It sets attributes like pq_to_descendants, type_to_descendants, and partial patterns, either by loading from Redis (with placeholder comments) or generating them via local methods. If using Redis, ... | def __init__(self,rc = None):
"""Descender can be loaded from redis (r) or if no redis is provided, it will load from bmt.
When we load from redis, we also pull in the s and o partial patterns which are used to filter at q time.
If you are creating descender with an rc, you also need to call set... |
def Get_Fe_EW(self, fe_pp, conti_pp):
"""Calculate the Fe EW within [4434.,4684.] and [2250.,2651.]
fe_pp = Fe_uv_norm, Fe_uv_FWHM, Fe_uv_shift, Fe_op_norm, Fe_op_FWHM, Fe_op_shift,
conti_pp = PL_norm, PL_slope, poly_a, poly_b, poly_c """
xval_uv = np.arange(2250.,2651.1)
... | This function performs Monte Carlo error estimation for continuous parameters by simulating $n\_trails$ trials. It adds random noise to input data, fits a model iteratively, and computes statistical uncertainties (standard deviations and 68% confidence intervals) for fitted parameters, Fe EW, and continuum luminosities... | def _conti_mc(self, x, y, err, pp0, pp_limits, n_trails, iif_dump_MC_result):
"""Calculate the continual parameters' Monte carlo errrors"""
all_para = np.zeros((len(pp0), n_trails))
all_Fe_EW = np.zeros((2, n_trails))
all_L = np.zeros((4, n_trails))
n_Fe_flux = np.array(self.Fe_... |
def F_poly_conti(self, xval, pp):
"""Fit the continuum with a polynomial component account for the dust reddening with a*X+b*X^2+c*X^3"""
xval2 = xval-3000.
yval = 0.*xval2
for i in range(len(pp)):
yval = yval+pp[i]*xval2**(i+1)
return yval
def Smooth(self, y, box_pts... | The main task of the code is to fit the continuum of an astronomical spectrum using models like PL, Polynomial, UV/optical FeII, and Balmer continuum. It applies constraints, rejects outliers, computes luminosity, Fe EW, and FeII flux, and returns results including parameters, uncertainties, and model components. The f... | def _DoContiFit(self, wave, flux, err, ra, dec, plateid, mjd, fiberid):
"""Fit the continuum with PL, Polynomial, UV/optical FeII, Balmer continuum"""
global fe_uv, fe_op
fe_uv = np.genfromtxt(self.path+'fe_uv.txt')
fe_op = np.genfromtxt(self.path+'fe_optical.txt')
# do continuu... |
def _do_tie_line(self, linelist, ind_line):
"""Tie line's central"""
# --------------- tie parameter-----------
# so far, only four groups of each properties are support for tying
ind_tie_v1 = np.where(linelist['vindex'][ind_line] == 1., True, False)
ind_tie_v2 = np.where(linelis... | The main task of the code is to fit emission lines in a spectrum using Gaussian profiles. It processes line complexes, applies rejection criteria to exclude absorption features, performs simultaneous Gaussian fits with tied parameters, calculates statistical results (chi2, dof), and stores derived parameters (FWHM, EW,... | def _DoLineFit(self, wave, line_flux, err, f):
"""Fit the emission lines with Gaussian profile """
# remove abosorbtion line in emission line region
# remove the pixels below continuum
# read line parameter
linepara = fits.open(self.path+'qsopar.fits')
linelist = linepa... |
def data_read():
with open("PTB/ptb.train.txt") as f:
file = f.read() # read the file
train = file[1:].split(' ') # remove the first space and split the file into words
with open("PTB/ptb.valid.txt") as f:
file = f.read() # read the file
valid = file[1:].split(' ') # remove the f... | The main task of the code is to train an LSTM model for language modeling using provided datasets. It reads training, validation, and test data, constructs a vocabulary, batches the data with specified parameters, initializes an LSTM model, and trains it using the batched data. The model handles unknown words via the <... | def main():
# The vocab is built from the training data
# If a word is missing from the training data, it will be replaced with <unk>
train, valid, test, vocab_size = data_read()
params.vocab_size = vocab_size
train_batchwise_x_y_pairs = batchify(train, params.batch_size, params.seq_length)
vali... |
def _open_url(self, url: str, select_url:bool=False, backspace:bool=False, open_tab: bool=False) -> bool:
'''Open new url'''
try:
if open_tab:
self._stay_loade_page()
logger.info('Open new Tab')
with pyautogui.hold('ctrl'):
... | The code automates logging into nike.com by opening the login URL, entering the email and password, and submitting the sign-in form. | def login(self, login_url:str) -> None:
'''Login in nike.com'''
self._open_url(url=login_url, open_tab=True)
self._enter_write_edittext('password', self._dir, self.password)
self._enter_write_edittext('email', self._dir, self.email)
self._enter_button('sign_in', self._dir) |
def _open_url(self, url: str, select_url:bool=False, backspace:bool=False, open_tab: bool=False) -> bool:
'''Open new url'''
try:
if open_tab:
self._stay_loade_page()
logger.info('Open new Tab')
with pyautogui.hold('ctrl'):
... | This code automates the checkout process on an e-commerce site by navigating through cart pages, entering payment details (CVV, card info, name), and submitting the order. It handles both pre-filled credit card data (if enabled) and manual input for card details, ensuring seamless purchase confirmation through a series... | def _cart(self, url_cart:str) -> None:
'''Go cart and confirm buy'''
self._open_url(url=url_cart, select_url=True, backspace=True)
self._enter_button(name='member_checkout', _dir=self._dir, upload_url=True)
self._enter_button(name='continue', _dir=self._dir, upload_url=True)
self... |
def _open_json(self, _dir_json:str) -> json.JSONDecoder | None:
try:
with open(_dir_json, 'r') as file:
load = json.load(file)
return load
except Exception:
return None
def _square_date(self, date_no_parse:str) -> bool:
date_now = datetime.date... | This code automates purchasing items from a website by processing a JSON list of items with dates. It navigates URLs, checks availability, clicks 'buy' buttons, adds items to a cart, and takes screenshots if enabled. The loop iterates through items, removes processed ones, and updates the JSON file. | def buy(self, data_json:str, shoe_size:str, url_cart:str, screenshot:bool=False) -> bool:
download_json = self._open_json(_dir_json=path.join(self._dir_config, data_json))
logger.info(download_json)
upload_json = download_json.copy()
while upload_json:
download_json ... |
def read_graph(filename):
lines = [line.strip() for line in open(filename)]
return lines
def part1(graph):
distances = [[9999 for _ in range(len(graph[0]))] for _ in range(len(graph))]
next_coords, distances = find_start(graph, distances)
while next_coords:
next_coords, distances, letter = f... | The main task of the code is to read a graph from a specified file and execute two analysis functions, `part1` and `part2`, on the graph. The results of both functions are then returned as a tuple. This structure allows for modular processing of graph data, where each part handles distinct tasks related to the graph's ... | def main(filename):
graph = read_graph(filename)
return part1(graph), part2(graph) |
def user_act(self):
try:
user_input = Prompt.ask("You")
if self.termination_re:
while not self.termination_re.match(user_input):
user_input += input()
# remove the termination character
user_input = user_input[:-1]
... | This code initiates a chat loop where the system continuously collects user input via self.user_act() until the user enters a predefined stop string (self.stop_str). If the input isn't the stop string, it triggers the assistant's response (self.assistant_act()) and automatically saves the session state (self._autosave(... | def _start_chat(self):
user_input = ""
while self.stop_str != user_input:
user_input = self.user_act()
if (self.stop_str != user_input):
self.assistant_act()
self._autosave() |
def user_act(self):
try:
user_input = Prompt.ask("You")
if self.termination_re:
while not self.termination_re.match(user_input):
user_input += input()
# remove the termination character
user_input = user_input[:-1]
... | This function runs a chat loop where the assistant processes user inputs, generates responses, identifies and executes actions, gathers observations, and autosaves progress. The loop continues until the user inputs a predefined stop string, at which point the function exits. | def _chat_with_actions(self):
"""
Runs a chat loop with actions until the stop string is entered
by the user
"""
user_input = ""
while self.stop_str != user_input:
user_input = self.user_act()
if self.stop_str != user_input:
assista... |
def _print_connected_message(self):
self._print_system_message(f"{self.character} is connected...")
def _start_chat(self):
user_input = ""
while self.stop_str != user_input:
user_input = self.user_act()
if (self.stop_str != user_input):
self.assistant_act(... | The code's main task is to manage a chat session by printing connection status messages, initiating the chat, and saving the chat history. It starts by displaying a connected message, executes the chat process, prints a disconnected message, and stores the interaction history for future reference. | def __call__(self):
# if self.conversation:
# self.messages = load_conversation(self.conversation)
self._print_connected_message()
self._start_chat()
self._print_disconnected_message()
self._save_chat_history() |
def _print_connected_message(self):
self._print_system_message(f"{self.character} is connected...")
def _chat_with_actions(self):
"""
Runs a chat loop with actions until the stop string is entered
by the user
"""
user_input = ""
while self.stop_str != user_input:
... | This method initiates a chat session by printing a connection message, executing chat actions, printing a disconnection message, and saving the chat history. It orchestrates the lifecycle of a chat interaction, ensuring messages are logged and history is preserved. | def start_chat_with_actions(self):
self._print_connected_message()
self._chat_with_actions()
self._print_disconnected_message()
self._save_chat_history() |
def _stopEvent (self, key, modes=None):
"""
Stops, or rather stops repeating, events which rely on the
given key being active.
A list of modes (eg. const.LED_*s) can be supplied, otherwise
the current mode-state of the device will be used.
"""
remap = self._remap
if modes is None:
modes = self._m... | This function manages key event handling by mapping input keys to outputs based on current modes. It checks existing key states, updates output when changes occur, and handles both single-key actions and multi-key combinations. It stops prior outputs if they differ from new ones, starts new outputs, and tracks key stat... | def _startEvent (self, key, modes=None):
"""
Starts whatever needs to be started with the additional
key given.
A list of modes (eg. const.LED_*s) can be supplied, otherwise
the current mode-state of the device will be used.
"""
remap = self._remap
if modes is None:
modes = self._modes
# Out... |
def _startEvent (self, key, modes=None):
"""
Starts whatever needs to be started with the additional
key given.
A list of modes (eg. const.LED_*s) can be supplied, otherwise
the current mode-state of the device will be used.
"""
remap = self._remap
if modes is None:
modes = self._modes
# Out... | The function processes input events from devices, mapping them to keys based on their type (e.g., key presses, relative/absolute movements, LED changes). It handles keydown/up events, remapped relative events, and absolute events with held states, relaying unknown events. Returns True if processed, False if unhandled (... | def receive (self, event):
"""
Will process the given event (most likely, but not necessarily,
from a device node) in the most suitable manner.
Returns whether or not the event was processed
"""
try:
stringCode = const.CODES[event.type][event.code]
key = mapping.Key(stringCode, event.value, event.v... |
def testAll(strHostedRootDir) -> list:
arrReturn = []
strCurrentDirectory = os.path.abspath(os.getcwd())
strTestDir = os.path.join(strCurrentDirectory, "testAll_Output/")
if os.path.exists(strTestDir) != True: os.system(f"mkdir {strTestDir}")
for i in range(1,TOTALDOWNLOADMETHODS+1):
strFile... | The function `generateList` processes file download tasks based on the specified method. It either tests all files in a hosted directory or reads a list of filenames from a provided file. For each file, it constructs download links, determines remote file paths, and executes the chosen download method, logging progress... | def generateList(strMethod: str, strHostedRootDir: str, strDestinationFolder: str, strFileWithFilenames: str="") -> list:
if strMethod == "testAll":
return testAll(strHostedRootDir)
elif strFileWithFilenames != "":
arrFiles = readFile(strFileWithFilenames).split()
while [] in arrFi... |
def process_img(img):
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
img, center, scale = resize_align_multi_scale(img, config.inp_size, 1, 1)
# print(center)
# print(scale)
img = pre_process(img)
img = img[None,...]
# compare(img, 'image.pkl')
img = torch.from_numpy(img).cuda()
return img, center, scale
def get_... | This code processes an input image through a pose estimation pipeline using a model. It generates heatmaps, detects key points, refines their positions, and returns final coordinates, scores, and relationships. | def run_pipeline(inputimg, model, hmap_generator=None, vid_idx=None, frame_idx=None):
img, center, scale = process_img(inputimg)
if hmap_generator is None:
inputhmap = None
else:
scale_hmap = img.shape[2] / inputimg.shape[0]
inputhmap = hmap_generator.get_hmap(vid_idx, frame_idx, config.base_sigma, img.shape[... |
def init_class_variables(self, cart_id, score):
self.cart_id = cart_id
self.score = score
def get_code_id_corresponding_to_score(self, shop):
return db.get_coupon_id_webshop(shop, self.score)
def get_coupon_for_cart_id(self, coupon_code_id):
generated_coupon = check_cart_id_for_coupon(se... | The code processes a POST request to handle a coupon for a shopping cart. It initializes variables, retrieves shop-specific OAuth credentials, authenticates with an API, fetches a coupon using a cart ID, and validates it. If successful, it returns the coupon validation result; otherwise, it returns an error message wit... | def post(self, shop, cart_id, score):
self.init_class_variables(cart_id, score)
shop_info = self.get_code_id_corresponding_to_score(shop)
if shop_info is not None:
self.shop_id, res_owner_key, res_owner_secret, client_key, client_secret, coupon_code_id = shop_info
self.m2... |
def stop_check(self, rng=1, direction=np.array([1,0])):
for i in self.tetrimino.squares:
x, y = self.focus + np.array(i) + rng * direction
if x < 0 or x > 23 or y < 0 or y > 9 or [x, y] in self.coral:
return True
return False
def solidify_tetrimino(self):
... | The `tick` method manages the game's core loop by checking if the current tetrimino has stopped, solidifying it if so, checking for game over, clearing completed rows, and spawning a new tetrimino. If the tetrimino hasn't stopped, it applies gravity to move it downward. This handles game state updates, collision detect... | def tick(self):
stop = self.stop_check()
if stop:
self.solidify_tetrimino()
if self.game_over_check(): sys.exit(f'Game Over!\n\nFinal Score: {self.score}')
self.row_check()
self.set_tetrimino(random.choice(DEFAULTS)())
else:
self.gravit... |
def jump(self, vector):
i = 0
while not self.stop_check(rng=i+1, direction=vector):
i += 1
self.move_tetrimino(i * vector)
def stop_check(self, rng=1, direction=np.array([1,0])):
for i in self.tetrimino.squares:
x, y = self.focus + np.array(i) + rng * direction
... | This code handles user input to control a tetrimino in a game, enabling movement (left/right), rotation (clockwise/counterclockwise), jumping (down), and resetting. It checks for valid moves/collisions before updating the tetrimino's position or rotation, ensuring game mechanics like piece rotation and movement adhere ... | def controls(self, inp, shift=False, control=False):
delta = 2 if shift else 1
if control:
if inp == 'w':
self.jump(np.array([-1, 0]))
elif inp == 'a':
self.jump(np.array([0,-1]))
elif inp == 's':
self.jump(np.array([1, ... |
def _create_database(path: str):
try:
os.remove(path)
except:
pass
return _open_database(path)
def _create_tables(db_connection: sqlite3.Connection, dimensions: Sequence[Dimension]):
_create_info_table(db_connection)
_create_location_table(db_connection)
_create_dimension_table(d... | The function `generate_gwfvis_db` creates a database at the specified path, initializes tables based on dimensions from the `options` object, populates the tables with data derived from the `options`, and commits the transaction to finalize the database structure and content. | def generate_gwfvis_db(path: str, options: Options):
db_connection = _create_database(path)
_create_tables(db_connection, options.dimensions)
_fill_tables(db_connection, options)
db_connection.commit() |
def create_url(server: str, path: str, *queryparts: str) -> str:
"""Convenience function to build URL for querying a server."""
sp = f"{server}{path}"
query = "&".join([urllib.parse.quote(qp, safe=":=") for qp in queryparts])
url = sp if not query else f"{sp}?{query}"
return url
def query(self, url:... | This function retrieves all timeseries in a Belvis portfolio by querying an API with the provided portfolio ID. It extracts timeseries IDs from API responses, fetches their corresponding names via metadata, stores the mapping (name → ID) in a dictionary, caches the result for future use, and returns the dictionary. The... | def all_ts(self, pfid: str) -> Dict[str, int]:
"""Use API to find all timeseries in a Belvis portfolio and store in cache. May
take a long time if portfolio has many timeseries.
Parameters
----------
pfid : str
Id (= short name) of Belvis portfolio.
Returns
... |
def metadata(self, tsid: int) -> Dict:
"""Get information about timeseries.
Parameters
----------
tsid : int
Belvis id of timeseries.
Returns
-------
dict
Metadata about the timeseries.
"""
url = create_url(
se... | This function retrieves a time series from the Belvis system using a specified ID and time interval, processes the data by handling missing values, and returns it as a pandas Series with appropriate units and timestamp frequency. | def series(
self,
tsid: int,
ts_left: pd.Timestamp | dt.datetime,
ts_right: pd.Timestamp | dt.datetime,
*,
leftrange: str = "exclusive",
rightrange: str = "inclusive",
missing2zero: bool = True,
blocking: bool = True,
) -> pd.Series:
""... |
def _fetch_series(self, ts_tree: TsTree, ts_left, ts_right, **kwargs) -> None:
if isinstance(ts_tree, Ts):
ts = ts_tree
if ts.tsid is None:
ts.tsid = self.api.find_tsid(ts.pfid, ts.name)
print_status(f"{ts.tsid} | {ts.pfid} | {ts.name} | [{ts_left}-{ts_right}]... | The main task of the code is to retrieve and process portfolio-specific volume/price time series data from Belvis, converting it into a structured `PfLine` object. It fetches data for a specified portfolio ID and time range, handles missing values, and returns either raw time series data (as series) or a processed port... | def general_pfl(
self,
pfid: str,
tsname: str,
ts_left: pd.Timestamp,
ts_right: pd.Timestamp,
missing2zero: bool = True,
output_as_series: bool = False,
) -> pf.PfLine:
"""Retrieve a portfolio line with portfolio-specific volume and/or price data
... |
def _fetch_series(self, ts_tree: TsTree, ts_left, ts_right, **kwargs) -> None:
if isinstance(ts_tree, Ts):
ts = ts_tree
if ts.tsid is None:
ts.tsid = self.api.find_tsid(ts.pfid, ts.name)
print_status(f"{ts.tsid} | {ts.pfid} | {ts.name} | [{ts_left}-{ts_right}]... | The main task of the code is to retrieve and process portfolio line data (volume/price) from Belvis, handling missing values and time ranges. It fetches time-series data for specified portfolios/lines, converts it to structured formats, and returns either raw time-series data or a consolidated `PfLine` object represent... | def portfolio_pfl(
self,
pfid: str,
pflineid: str,
ts_left: pd.Timestamp,
ts_right: pd.Timestamp,
missing2zero: bool = True,
*,
output_as_series: bool = False,
) -> pf.PfLine:
"""Retrieve a portfolio line with portfolio-specific volume and/or p... |
def _fetch_series(self, ts_tree: TsTree, ts_left, ts_right, **kwargs) -> None:
if isinstance(ts_tree, Ts):
ts = ts_tree
if ts.tsid is None:
ts.tsid = self.api.find_tsid(ts.pfid, ts.name)
print_status(f"{ts.tsid} | {ts.pfid} | {ts.name} | [{ts_left}-{ts_right}]... | The function retrieves a portfolio line with price data from Belvis, fetching time-series data for a specified price ID and delivery period. It handles missing values by replacing them with 0 or NaN, depending on the 'missing2zero' flag. If 'output_as_series' is True, it returns raw time-series data as a structured for... | def price_pfl(
self,
priceid: str,
ts_left: pd.Timestamp,
ts_right: pd.Timestamp,
missing2zero: bool = True,
*,
output_as_series: bool = False,
) -> pf.PfLine:
"""Retrieve a portfolio line with portfolio-UNspecific price data from Belvis.
Para... |
def available_pfids(self, original_only: bool = False) -> Iterable[str]:
"""All available portfolio ids.
Parameters
----------
original_only : bool, optional (default: False)
If True, only return the ("original") portfolio ids that are present in belvis,
and omit... | The function `tstree_pfline` retrieves the required timeseries names (`TsTree`) for a specified portfolio (`pfid`) and portfolio line (`pflineid`). It validates the existence of `pfid` and `pflineid`, applies predefined corrections if available, or defaults to standard mappings. The result is a structured timeseries na... | def tstree_pfline(self, pfid: str, pflineid: str) -> TsTree:
"""Timeseries that must be fetched to get the wanted pflineid for a given pfid.
Parameters
----------
pfid : str
Id of portfolio. Must be original.
pflineid : str
Id of portfolio line.
... |
def daterange(start_date, end_date):
for n in range(int(int((end_date - start_date).days)/15)):
yield start_date + timedelta(n*15)
def build_github_query(language=None, stars=None, forks=None, last_commit=None, start_date=None, end_date=None, fork=None):
"""
Build a GitHub search query based on prov... | (The main task of the code is to fetch GitHub repositories based on user-defined filters (language, stars, forks, last commit date) and save results in a CSV file. It uses command-line arguments for parameters, creates a directory for outputs, iterates over date ranges, constructs search queries, and writes repository ... | def main():
# Define command-line arguments for filter parameters
parser = argparse.ArgumentParser(description='Fetch GitHub repositories based on filters.')
parser.add_argument('--language', default='Python', help='Filter by programming language')
parser.add_argument('--stars', type=int, default=20, he... |
def read_repository_urls_from_csv(input_csv_file):
print("Processing input filename: ", input_csv_file)
with open(input_csv_file, 'r') as input_file:
reader = csv.reader(input_file)
# Skip the header row
next(reader, None)
repo_urls = [row[6] for row in reader]
return repo_ur... | The main task of the code is to analyze GitHub repositories listed in a CSV file by applying two sets of patterns (from "patterns.csv" and "patterns2.csv") to each repository URL. It generates output CSV files named with the host IP and current date, storing analysis results for each repository. The process involves re... | def main():
# Generate the output file name with the specified prefix and IP address
host_ip = socket.gethostbyname(socket.gethostname())
date = datetime.date.today().strftime("%m%d%Y")
# Define the input CSV file name
input_csv_file = os.path.join(root_dir, f"github_repositories_{host_ip}.csv")
... |
def get_business():
if not config.get('DEFAULT','Business',fallback='') or not yes_no("\nYou have a default business configured. Do you want to use it for this bank account?"):
businesses = query_business()
retval = print_menu(businesses,'name')
print('Which business do you want to use? ')
... | The main task of the code is to present a menu for updating financial accounts or business information, handle user selection, and execute corresponding update functions (e.g., updating business, checking accounts, income/expense accounts) based on the choice. It allows cancellation and returns control after processing... | def update_wave():
menu_options = {
0: "Update selected Wave business",
1: "Update checking/credit card/cash/loan account",
2: "Update income account",
3: "Update expense account"}
r = print_menu(menu_options)
r = menu_select(r)
if r == -1:
print("\nCancel.")
return
... |
def C_Ceros(self,tabla):
filas =len(tabla)
colum=len(tabla[0])
ceros=0
for i in range(filas):
for j in range(colum):
if tabla[i][j]==0:
ceros+=1
return ceros
def vertabla(self,tabla):
filas=len(tabla)
colum=len(tabla... | This function attempts to solve a Sudoku puzzle by iteratively filling in immediate possible values until no more cells can be filled. It tracks the number of empty cells ("ceros"), prints the initial and final states of the board, and indicates if the puzzle couldn't be solved, suggesting potential input errors. The l... | def SolucionaSudoku(self,tabla):
ceros = self.C_Ceros(tabla)
bajando = 1
contador =0
print("\nEstado inicial de la tabla")
self.vertabla(tabla)
print ("\nInicialmente hay",ceros,"ceros.")
while ceros>0 and bajando==1:
self.RellenaInmediatos(tabla)
... |
def C_Ceros(self,tabla):
filas =len(tabla)
colum=len(tabla[0])
ceros=0
for i in range(filas):
for j in range(colum):
if tabla[i][j]==0:
ceros+=1
return ceros
def RellenaInmediatos(self,tabla):
actuado = 0
filas=len(t... | The code fills a table's cells by iteratively applying methods to identify and fill cells with possible values, starting with immediate solutions and progressing to cells with 2-7 possible options, until no more zeros remain or a maximum iteration limit is reached. | def RellenaPosibilidades(self,tabla):
filas=len(tabla)
colum=len(tabla[0])
contador=0
while self.C_Ceros(tabla)!=0 and contador<=200:
contador+=1
while self.RellenaInmediatos(tabla)==1:
print ("rellenada inmediatos")
if self.RellenaUnaC... |
def format_error(message):
print(RED + "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" + RESET)
print(message)
print(RED + "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" + RESET)
def format_positinal_sizing_output(last, high, low, ticker, positinal_sizing):
print(RED + "---------------------------------" + RESET)
print(ra... | The main task of the code is to route requests based on input type: if `value` is a list, it calculates position sizing for stock symbols and formats results; if not, it retrieves stock data within specified date ranges. It handles validation and error formatting for invalid symbols. | def request_router(value, start_date, end_date):
if type(value) is list:
data = calculate_position_sizing(value[0], value[1])
if not data:
format_error(f"{value[0]} is not a valid stock symbol")
return
format_positinal_sizing_output(**data)
else:
get_st... |
def calculate_start_and_end():
today = datetime.today()
delta = timedelta(days=20)
result = today - delta
return result.strftime('%Y-%m-%d'), today.strftime('%Y-%m-%d')
def validate_input(user_input):
if user_input == 'exit':
return True
def check_for_digits(input_string):
return any(cha... | The main task of the code is to process user input for stock data requests. It validates input, checks for digits, and routes queries to appropriate handlers. The loop accepts stock tickers, processes them, and uses start/end dates for data retrieval, exiting on invalid input. | def main():
exit_flag = False
start_date, end_date = calculate_start_and_end()
while True:
value = input("Enter stock tick here: ")
exit_flag = validate_input(value)
if exit_flag:
break
value = value.upper().strip()
if check_for_digits(value):
... |
def prepare_image(img_name, denoise):
angle_flt = 0
angles_float = []
try:
rgb = cv2.imread(img_name, 1)
except:
print("\nCan't open file:", img_name)
if denoise == 1:
print("\033[94m" + " page "+str(curent_page+1)+"/"+str(total_page)+":" + "\033[0m"+"\033[93m"+" denoisi... | This code searches for a target in a PDF by converting each page to an image, processing it with denoise, rotating, and recognizing the content. If found, it returns the page number and coordinates; otherwise, returns an empty tuple. | def search_in_pdf(pdf_name, target, denoise):
global curent_page, total_page
position = ()
print("\033[94m" + "File:", pdf_name, "\033[0m")
print("\033[94m" + " Converting file ..." + "\033[0m", end=' ', flush=True)
try:
pdf_pages = im.convert_from_path(pdf_name, 300)
print("\03... |
def prepare_image(img_name, denoise):
angle_flt = 0
angles_float = []
try:
rgb = cv2.imread(img_name, 1)
except:
print("\nCan't open file:", img_name)
if denoise == 1:
print("\033[94m" + " page "+str(curent_page+1)+"/"+str(total_page)+":" + "\033[0m"+"\033[93m"+" denoisi... | This function searches for a target in an image by preparing it with denoising, rotating it if necessary, and using recognition. If the target is found, it returns a position tuple (1,0,0); otherwise, an empty tuple. It prints status messages for file processing and detection results. | def search_in_image(image_name, target, denoise):
global curent_page, total_page
position = ()
curent_page = 0
total_page = 1
print("\033[94m" + "File:", image_name, "\033[0m")
binary = prepare_image(image_name, denoise)
if cv2.countNonZero(binary) != 0:
binary = rotate_image(binary)... |
def server_print(msg):
current_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
print(f'[{current_time}] {msg}')
logger.debug(msg)
def log_on_client(self, client_socket):
root_ca = RootCA(read_config("RootCA", "root.cert"), read_config("RootCA", "crl"))
# -- get client cert and pubkey --
... | The main task of the code is to listen for incoming client connections, validate client certificates, and spawn threads to handle each connected client concurrently. It maintains a listening socket, accepts connections in a loop, checks certificate validity, and initiates a dedicated thread for processing each client u... | def waiting_for_client(self):
try:
server_print('Listening for connection...')
self.socket.listen(10)
while True:
client_socket, client_address = self.socket.accept()
server_print(f'Connection from {client_address} accepted.')
... |
def send_all_clients(self, current_client):
message = '\nList of all users:\n'
receiver = self.get_alias_by_socket(current_client)
for alias in self.clientsInfo.keys():
message += f'#{alias}\n'
pkl_data = self.prepare_data(sender="server", receiver=receiver, message=message)... | This function handles client communication by receiving and processing encrypted data, executing commands like sending user lists, keys, and managing private chats, while handling direct messages and properly closing connections upon termination or errors. | def handle_client(self, client_socket, client_address):
try:
data_encrypted = client_socket.recv(2048)
while data_encrypted:
data = pickle.loads(data_encrypted)
logger.debug(f"Received data: {data}")
if data["type"] == "command":
... |
def log(self, output_str):
print(output_str)
def _load_bundle_map(self):
'''
Return a map of all bundles in the Clarify app that have an external_id set for them.
The bundles with external_ids set are assumed to be the ones we have inserted from Brightcove.
The external_id contai... | This function synchronizes video bundles by creating/updating metadata for existing videos and deleting bundles for missing videos. It uses dry_run to avoid modifications, tracks stats (created/deleted), and supports confirmation callbacks for deletions. The process involves fetching video data, mapping to bundles, and... | def sync_bundles(self, delete_bundles=True, update_metadata=True, confirm_delete_fun=None, dry_run=False):
self.dry_run = dry_run
self.sync_stats.clear()
if dry_run:
self.log('-----------------------------------')
self.log('DRY RUN - not modifying any bundles')
... |
def create_zones_lookup(self, field, items, field_ids):
"""
Creates a lookup table for 'Zones' based on the extracted data.
:param field: The name of the field to create a lookup table for.
:param items: A list of items to create lookup rows for.
:param field_ids: A list of IDs f... | This function generates lookup tables for database fields not already present. It creates rows based on the field type (e.g., Zones, Layers) using specific methods, handling special cases like default entries for 'RenderedScenes'. It accumulates these lookup rows in a dictionary under the corresponding field name for l... | def make_lookup_tables(self, field, items_not_in_map, field_ids):
"""
Creates lookup tables for shared fields that are not already in the database.
:param field: The name of the field to create a lookup table for.
:param items_not_in_map: A list of items not already in the database.
... |
def extract_shared_fields(self):
"""
Extracts shared fields from the render pass data and creates lookup tables.
"""
for field in self.shared_fields:
if field in self.render_pass_df.columns:
unique_items = self.render_pass_df[field].dropna().unique().tolist()
... | The main task of the code is to normalize extracted data by extracting shared fields, updating the render pass table with references, and finalizing shared fields dataframes. This involves creating lookup tables for consistent data handling and ensuring render pass information is accurately referenced and structured fo... | def normalize_data(self):
"""
Normalizes the extracted data by creating lookup tables and updating the render pass table.
"""
self.extract_shared_fields()
self.update_render_pass_table_with_references()
self.finalize_shared_fields_dfs() |
def clear_messages(self):
os.system('clear')
def log_in(self):
patient_last_name = input('Provide your last name: ')
ss_num = input('Provide your Social Security number: ')
try:
patient = self.db.select_patient(ss_num)
except Exception as e:
print(f'Couldn... | This code handles a menu-driven system by executing actions based on user input. It processes commands like logging in, registering patients, managing visits, and controlling stress tests. Conditional checks ensure actions like registering visits require prior login. The 'Q' command stops the stress test and deactivate... | def execute(self, action):
self.clear_messages()
self.menu_msg = str()
if action.isalpha():
action = action.upper()
if action == '1':
self.log_in()
elif action == '2':
self.register_patient()
elif action == '3':
if self.ss_... |
def isgameover(self):
'''
Based on the type of game, determine whether the current game has completed.
'''
if (self.endgametype == 'wb2'):
# in a win by two game, the game will be over if one player has a number of points larger
# than the end game score, and... | The main task of the code is to update scores and server status based on rally outcomes and scoring rules. It initializes scores, iterates through rallies to increment scores according to 'par' or 'old' scoring logic, checks game/end conditions, appends new score entries if needed, and triggers server updates. It handl... | def __updatescore(self):
'''
Each time a rally ends, or a change is made to the score
call this function to update the scores and server
'''
self.score=[[0,0]]
for i in range (len(self.rallies)):
if self.rallies[i].winner is not None:
... |
def ismatchover(self):
'''
Based on the match end type, determine whether the match has finished
'''
if (self.endmatchtype == 'none'):
# none implies free play, and no end to the match
return False
elif (self.endmatchtype == 'normal'):
... | This function records the outcome of a completed rally by validating the winner, updating the rally's details, adjusting the score, and initiating the next rally if the match is not over. It raises errors for invalid winners or attempts to add rallies after the match concludes. | def rallycomplete(self, winner=None, extra=None):
'''
Call this function each time a rally finishes, specifying who
won the rally, as well as any other applicable info.
'''
if not (winner in squash_match.validplayers):
raise GameError("invalid player assigned... |
def __getMeanIntensity(self, use_device):
# Returns the mean intensity of image
if use_device=='host':
meanIntensity = []
for channel in range(3):
channel_mean = np.average(self.image[:, :, channel])
meanIntensity.append(round(channel_mean, 5))
... | The function `getFeatureVector` extracts image features including mean/std intensity, RGB histogram, and Hu moments, concatenates them into a single list, and returns it as a NumPy array. | def getFeatureVector(self, use_device):
""" Return a python list of complete feature vectors
Extracts Statistics, 3-D Histogram, HuMoments from image and appends into single list
"""
featureVectors = []
meanIntensity = self.__getMeanIntensity(use_device)
stdIntensity = se... |
def lightIss(pointArray):
tle = updateIssTleData()
line1 = tle[0]
line2 = tle[1]
line3 = tle[2]
iss = ephem.readtle(line1, line2, line3)
iss.compute()
isslong = iss.sublong / degree
isslat = iss.sublat / degree
logging.debug("Iss: %s %s" % (isslat, isslong))
# getClosestPoints(isslat, isslong, point... | This code controls an LED strip by setting pixel colors based on different modes (0-4). It populates a lightsArray with coordinates and colors from functions like lightIss, lightSun, and lightMoon. Mode 4 triggers a rainbow effect instead. After clearing all pixels, it applies the lightsArray colors to the strip. If in... | def runMode(self, strip):
isplottable = True
plottraillength = 0
self.lightsArray = []
if (int(self.mode) == 0):
# print("0iss")
plottraillength = 35
for i in lightIss(self.ledcoords):
self.lightsArray.append(i)
elif (int(self.mode) == 1):
# print("1sun")
for i ... |
def lightIss(pointArray):
tle = updateIssTleData()
line1 = tle[0]
line2 = tle[1]
line3 = tle[2]
iss = ephem.readtle(line1, line2, line3)
iss.compute()
isslong = iss.sublong / degree
isslat = iss.sublat / degree
logging.debug("Iss: %s %s" % (isslat, isslong))
# getClosestPoints(isslat, isslong, point... | This function controls an LED strip to display different light sources (ISS, Sun, Moon) based on the selected mode. It initializes light arrays, updates pixel colors, and optionally plots debug data. Mode 0-3 enable specific light sources, while mode 4 triggers a rainbow effect. Changes in light arrays trigger color up... | def runMultiMode(self, strip):
#oldstrip = strip.getPixels()
isplottable = True #remove later
issplottraillength = 0
oldlightarray = self.lightsArray
self.lightsArray = []
self.isslightsArray = []
self.sunlightsArray = []
self.moonlightsArray = []
self.showIss = self.showSun = self.s... |
def lineBoundary(content):
print('-' * 40)
print(content)
print('-' * 40)
def read_digit(p_fp):
# read entire digit (inlude linefeeds)
bits = p_fp.read(NUM_ROWS * (NUM_COLS + 1))
if bits == '':
return -1,bits
# convert bit string as a list
# This list contains all the index for "... | The code reads a file containing digit data, predicts each digit using a KNN algorithm based on feature vectors, stores the predictions in a list, and prints the results. It processes each line of the input file, extracts features, applies the KNN model to determine the most common class, and displays the predicted dig... | def predict(p_filename = DATA_PREDICT):
#create the title "Prediction"
title = ' '*12 + 'Prediction'
#show the title "Prediction" in the terminal
lineBoundary(title)
#create a list to store all the results of prediction
predicts = []
#append each result of prediction to the list
with ope... |
def read_digit(p_fp):
# read entire digit (inlude linefeeds)
bits = p_fp.read(NUM_ROWS * (NUM_COLS + 1))
if bits == '':
return -1,bits
# convert bit string as a list
# This list contains all the index for "1" in each digit
vec = [int(bit) for bit in range(0,len(bits)) if bits[bit] == '1'... | The code validates a classification model by testing it on a dataset, counting correct and incorrect classifications. It reads digits from a file, uses a KNN algorithm (`knn_by_most_common`) to predict each digit's value, compares predictions to actual values, and logs results in `g_test_good` (correct) and `g_test_bad... | def validate(p_filename = DATA_TESTING):
global g_test_bad, g_test_good
g_test_bad = defaultdict(int)
g_test_good = defaultdict(int)
#record the starting time of testing
start = datetime.now()
#test each digit in the testing file
with open(p_filename) as f:
while True:
va... |
def read_digit(p_fp):
# read entire digit (inlude linefeeds)
bits = p_fp.read(NUM_ROWS * (NUM_COLS + 1))
if bits == '':
return -1, bits
# convert bit string as digit vector
vec = [int(b) for b in bits if b != '\n']
val = int(p_fp.readline())
return val, vec
def knn_by_most_common(p_v... | (The code reads a file containing digit data, applies a KNN algorithm to predict each digit's value, and prints the predictions. It processes each digit vector, determines the most common label using KNN, and outputs the results sequentially.) | def predict(p_filename=DATA_PREDICT):
predicts = []
with open(p_filename) as f:
while True:
val, vec = read_digit(f)
if val == -1:
break
predict = knn_by_most_common(vec)
predicts.append(predict)
linesDividing(g_spaces_title*' '+'Predic... |
def read_digit(p_fp):
# read entire digit (inlude linefeeds)
bits = p_fp.read(NUM_ROWS * (NUM_COLS + 1))
if bits == '':
return -1, bits
# convert bit string as digit vector
vec = [int(b) for b in bits if b != '\n']
val = int(p_fp.readline())
return val, vec
def knn_by_most_common(p_v... | The code validates a KNN classifier's performance on a test dataset by comparing predicted labels with actual labels. It reads input data, uses `knn_by_most_common` for predictions, tracks correct (`g_test_good`) and incorrect (`g_test_bad`) classifications, and measures execution time. Results are displayed via `show_... | def validate(p_filename=DATA_TESTING):
global g_test_bad, g_test_good
g_test_bad = defaultdict(int)
g_test_good = defaultdict(int)
start = datetime.now()
with open(p_filename) as f:
while True:
val, vec = read_digit(f)
if val == -1:
break
... |
def Initial_solution(solution):
bin_capacity = solution.problem.capacity
flag_newBin = False
# This is for sorting items
sorted_items = copy.deepcopy(solution.problem.items)
sorted_items.sort(key=lambda item: item.weight) # sort items from small-size to large-size
current_bin = Bin(bin_capacity... | This function implements a Variable Neighbourhood Search (VNS) algorithm to minimize the number of bins used in a bin packing problem. It iteratively explores neighborhoods of increasing size, compares solutions, and updates the best solution. If a worse solution is found, it increments the neighborhood size. After exh... | def Variable_Neighbourhood_Search(problem):
current_solution = Solution(problem)
current_solution = Initial_solution(current_solution)
best_solution = copy.deepcopy(current_solution)
nb_space = 1
maxSpace = 2
while nb_space < maxSpace + 1:
n_best_solution = copy.deepcopy(best_solution)
... |
def readfile(filename):
"""
read the file and build the problem class
"""
f = open(filename,"r")
pro_num = f.readline()
problist = []
for i in range(int(pro_num)):
title = f.readline()
title = title.strip('\n')
title = title.strip(" ")
info = f.readline()
... | The main task of the code is to optimize container allocation for a list of problems by iteratively applying heuristic methods like shaking, grouping, and best-fit algorithms. It aims to minimize extra containers, checking for optimal solutions and recording results. The process includes timing each problem's execution... | def main():
totaltime = 0
filename = sys.argv[2]
problist = readfile(filename)
probslnlist = []
for prob in problist:
flag = False
startT = time.time()
bestFit(prob)
best_prob = copy.copy(prob)
prob.resetcontainers()
for i in range(30):
if ... |
def chooseTwoType(problem:Problem,type1,type2):
"""
choose two types of items and change the items between the bins
"""
copy_problemopy = copy.copy(problem)
bins_without_type1 = []
bins_with_type1 = []
for bin in copy_problemopy.bins:
if bin.isFull():
continue... | The main task of the code is to implement a neighbourhood search algorithm that modifies a problem instance by selecting specific item types, maintaining extra bins, fitting additional items, and optimizing the best solution through iterative adjustments. It processes the problem through steps like `chooseTwoType`, `ma... | def neighbourhood(problem:Problem,best_problem:Problem):
"""
neighbourhood search algorithm
it is composed of low level function combine algorithm and best fit the extra items
"""
problem = chooseTwoType(problem,"VLarge","Large")
problem = maintain_extra_bins(problem)
problem = fit_extraitem... |
def chooseTwoType(problem:Problem,type1,type2):
"""
choose two types of items and change the items between the bins
"""
copy_problemopy = copy.copy(problem)
bins_without_type1 = []
bins_with_type1 = []
for bin in copy_problemopy.bins:
if bin.isFull():
continue... | The function combines and optimizes two problem configurations by applying type-specific selection, maintaining extra bins, fitting additional items, and refining the best solution through checks and adjustments, returning both the modified problem and optimized best problem. | def lowlevelcombine(problem, best_problem):
"""
low level function combine algorithm
"""
problem = chooseTwoType(problem,"Large","Mid")
problem = maintain_extra_bins(problem)
problem = chooseTwoType(problem,"VLarge","Large")
problem = fit_extraitem(problem)
best_problem = checkResult(pro... |
def lambda_step(self):
F = self.plan.data_discrepancy / (2 * self.plan.sigmas[None, :])
Fj = np.sort(F, axis=0)
FJ = Fj[0:self.plan.J]
summed_FJ = np.sum(FJ, axis=0)
lambdas = 1 / 2 * self.plan.J0 * self.plan.n ** ((2 + 2 * self.plan.eta) / 5) * (
Fj[self.plan... | The main task of the code is to perform iterative optimization steps in an algorithm, updating parameters like lambda, rotations, and volume. It updates data discrepancies, computes squared errors, executes lambda, rotations, and volume update steps, appends cost values, and optionally saves intermediate parameters. Th... | def step_solver(self):
# Update data discrepancy
logger.info("Update data_discrepancies")
self.plan.data_discrepancy_update()
# Compute squared errors so we can use it for both weight update and sigma update
# if self.experiment is None:
if self.plan.J is not None:
... |
def find_offset(vec, real_angle):
north_angle = angle_to(vec)
return reg_angle(real_angle-north_angle)
def pixel_coords(h_angle, dist, x_buff, w=1920, h=1080, cam_height=6):
#equirectangular linearly spaces angles from -pi to pi. map to pixel coord:
x = int((h_angle/(2*np.pi) + .5) * w + x_buff)
b =... | The code generates a line image from a given path data, processes coordinates and angles to draw a blue line with rounded ends, handles edge cases for insufficient path points, and saves the resulting transparent PNG image with specified dimensions and line properties. | def draw_line(ppath, save_path, w=1920, h=1080, cam_height=6, linew=25):
name = "line"
for node in ppath:
name += "_" + node["name"]
#no path to draw:
if(len(ppath)) <= 1:
line_image = Image.new("RGBA", [w, h], (0,0,0,0))
line_image.save(save_path+name+'.png')
return
... |
def assess_agent(player, agent, game, y_axis):
""" :param player: 'X' or 'O'
:param agent: Agent object
:param game: Game object
:param y_axis: list of integers
Function assesses agent's performance after a given training epoch. Plays 10 games against random agent
a... | The main task of the code is to train a reinforcement learning agent (using Q-learning) to play a game (likely Tic-Tac-Toe) against itself. It initializes a game and agent with hyperparameters (learning rate, discount factor, exploration rate), trains the agent over multiple epochs by playing games, adjusts exploration... | def main():
# Initialize instance of the Game and Agent objects
game = Game()
agent = Agent(eta=0.5, gamma=0.9, epsilon=0.1)
# Set hyperparameters
num_epochs = 10
stop = 10000
epsilon_increase = 0.05
m = 5000 # The amount of games played before it's time to increase epsilon
# Used... |
def setDictionaryStrategy(self):
for keys, values in self.boardStatus.items():
if values[0] == 0:
values[4] = "N/A"
elif values[0] - values[2] == values[3]:
values[4] = "NeighborsAreBombs"
elif values[0] == values[2]:
values[4] ... | The main task of the code is to initialize game pieces on a board by iterating through board statuses. It applies different strategies: flagging pieces if their neighbors are bombs, or revealing neighbors if they are safe. This function processes each cell's state to set flags or reveal adjacent cells based on predefin... | def initializePieces (self) :
for keys, values in self.boardStatus.copy().items():
self.setDictionaryStrategy()
if values[4] == "NeighborsAreBombs":
piece = self.getPiece(keys)
self.setAllFlag(piece)
elif values[4] == "NeighborsAreSafe... |
def setDictionaryStrategy(self):
for keys, values in self.boardStatus.items():
if values[0] == 0:
values[4] = "N/A"
elif values[0] - values[2] == values[3]:
values[4] = "NeighborsAreBombs"
elif values[0] == values[2]:
values[4] ... | The main task of the code is to initialize game pieces based on their status in the board. It iterates through the board's dictionary, applying different actions: flagging pieces if their status indicates neighboring bombs, or revealing neighbors if safe. This sets initial game state logic for Minesweeper-like mechanic... | def initializePieces (self) :
for keys, values in self.boardStatus.copy().items():
self.setDictionaryStrategy()
if values[4] == "NeighborsAreBombs":
piece = self.getPiece(keys)
self.setAllFlag(piece)
elif values[4] == "NeighborsAreSafe... |
def _bottom_up_without_spacing(self, available_edges=None,
min_spacing=4,
max_spacing=8,
max_it=None,
show_progress=True):
threshold = self.threshold
if max_it is N... | This method performs a bottom-up process to determine optimal spacing parameters. If spacing guessing is enabled, it first identifies the best spacing using _bottom_up_without_spacing, then uses this spacing in a subsequent _bottom_up_with_spacing call. If spacing guessing is disabled, it directly applies _bottom_up_wi... | def bottom_up(self, available_edges=None, show_progress=True):
if self.guess_spacing:
info = self._bottom_up_without_spacing(available_edges,
self.min_spacing, self.max_spacing,
show_progress=show_p... |
def get_spatial_reference_system(self, srid: int) -> SpatialReference:
wkt = self._fetch_coord_ref_system(srid=srid)
if wkt:
return SpatialReference(
origin=Origin.EPSG_REGISTRY,
srs_input=wkt,
srs_type="wkt",
extent=self.get_ex... | This function retrieves a SpatialReference object for a given SRID by checking three sources: a cache, a remote EPSG API, and a local GDAL registry. If cached, it returns the stored reference; otherwise, it fetches from the remote API or falls back to GDAL. The result includes the spatial reference data and extent, pri... | def get(self, srid: int) -> SpatialReference:
"""Return the SpatialReference object by given srid from three different origins.
1th: cache is uses to lookup a cached spatial reference
2th: remote epsg api is fetched to lookup the remote spatial reference
3th: fallback to the local gdal r... |
def setup_axes(self):
axes = self.get_three_d_axes(include_labels=True)
# axes.add(axes.input_plane)
axes.scale(1)
# axes.center()
axes.shift(axes.axes_shift)
self.add(axes)
self.axes = axes
def get_surface(self,axes, func, **kwargs):
config = {
... | The code visualizes the 3D surface $z=xy$ using Manim, setting up axes, camera angles, and boundary curves ($y=x^2$ and $y=x$) with labels. It animates the scene with ambient rotation, renders the surface, and adjusts the camera view for a dynamic 3D graph display. | def construct(self):
self.setup_axes()
self.set_camera_orientation(
distance=30,
phi=75 * DEGREES,
theta=20 * DEGREES,
)
fn_text=TextMobject("$z=xy$").set_color(BLUE).scale(1.5)
fn_text.to_corner(UR,buff=2)
self.add_fixed_in_f... |
def _get_storage_stores() -> Any:
global _classes
if _classes is not None:
return _classes
class CollectionStore(BaseModel):
"""Collection store."""
__tablename__ = "langchain_storage_collection"
name = sqlalchemy.Column(sqlalchemy.String)
cmetadata = sqlalchemy.Co... | The main task of the code is to initialize a data store by retrieving storage classes (ItemStore, CollectionStore), assigning them to instance attributes, and creating necessary database tables/collections. This ensures the storage system is properly set up for data operations. | def __post_init__(
self,
) -> None:
"""Initialize the store."""
ItemStore, CollectionStore = _get_storage_stores()
self.CollectionStore = CollectionStore
self.ItemStore = ItemStore
self.__create_tables_if_not_exists()
self.__create_collection() |
def get_card_id(line):
return int(line.split(": ")[0].strip().replace("Card", "").strip())
def get_card_winning_numbers(card):
c = parse_line(card)
card_id = get_card_id(card)
if card_id in lookup:
return lookup[card_id]
winning_numbers = len(c[0].intersection(c[1]))
return winning_numbers | The function calculates the total number of child cards by recursively processing each card's winning numbers, summing the count of subsequent cards and their descendants. It uses a lookup dictionary to store winning numbers, slices the input lines based on these numbers, and aggregates the total through recursive call... | def get_total_child_cards(card, lines):
next_cards = []
card_id = get_card_id(card)
winning_numbers = get_card_winning_numbers(card)
if not card_id in lookup:
lookup[card_id] = winning_numbers
next_cards = lines[card_id:card_id + winning_numbers]
total = 0
for card in next_cards:
total = tot... |
def magnitude(root):
if not isinstance(root, list):
return root
return 3 * magnitude(root[0]) + 2 * magnitude(root[1])
def add_vals(a, b):
c = [a, b]
reduced = True
while reduced:
reduced = explode_list(c) or split(c)
return c
def deep_copy(x):
if not isinstance(x, list):
... | The code computes the maximum magnitude resulting from adding every possible pair of elements in the input list `lines`, considering both orderings of each pair (i.e., `lines[i] + lines[j]` and `lines[j] + lines[i]`). It iterates through all unique pairs, calculates their magnitudes using helper functions, and updates ... | def solution2(lines):
max_val = 0
for i in range(len(lines)):
for j in range(i+1, len(lines)):
mag = magnitude(add_vals(deep_copy(lines[i]), deep_copy(lines[j])))
max_val = max([mag, max_val])
mag = magnitude(add_vals(deep_copy(lines[j]), deep_copy(lines[i])))
... |
def calc_abs_freq(num_list):
nj_dict = {}
for i in num_list:
nj_i = num_list.count(i)
nj_dict[i] = nj_i
return(nj_dict)
def calc_rel_freq(nj_dict):
fj_dict = {}
N = 0
for v in nj_dict.values():
N += v
for k, v in nj_dict.items():
fj_dict[k] = round((v / N), 3)... | The function generates a statistical overview of input data, calculating absolute/relative/cumulative frequencies, central tendency measures (mean, mode), quartiles, variability metrics (variance, coefficient of variation), skewness (Fisher index), and box plot thresholds (Li/Ls) for outlier detection, then prints form... | def give_overview_box_plot(nums_copy):
if isinstance(nums_copy, list):
nums_copy.sort()
nums_abs_freq = calc_abs_freq(nums_copy)
nums_rel_freq = calc_rel_freq(nums_abs_freq)
nums_cum_freq = calc_cum_freq(nums_rel_freq)
media = calc_avg(nums_abs_freq)
moda = calc_moda(nums_abs_freq)
... |
def Find_Nearest_Facility(demand: Demand, facility_list: list) -> tuple:
# base case if facility_list is still empty (1. iteration).
if len(facility_list) == 0:
return (10000, None)
norm = [Euclidean_Norm(demand.position, facility.position) for facility in facility_list]
return (np.min(nor... | The code implements an online facility location algorithm that probabilistically decides whether to open a new facility or assign a demand to an existing one. For each demand, it finds the nearest facility, calculates an opening probability based on distance and cost, and uses a coin flip to either open a new facility ... | def Meyerson_Algorithm_Online(demand_list: list, facility_cost: int = 1) -> list[Facility]:
facilities_list = []
for demand in demand_list:
# calculate the relevent values
norm, next_facility = Find_Nearest_Facility(demand, facilities_list)
probability_facility = q_Get_Probability(1, nor... |
def Find_Nearest_Facility(demand: Demand, facility_list: list) -> tuple:
# base case if facility_list is still empty (1. iteration).
if len(facility_list) == 0:
return (10000, None)
norm = [Euclidean_Norm(demand.position, facility.position) for facility in facility_list]
return (np.min(nor... | The code implements an online facility location algorithm where, for each demand, it probabilistically decides to either open a new facility or assign the demand to the nearest existing one. The decision uses a probability derived from the input parameter `q`, the distance to the nearest facility, and a fixed facility ... | def q_Meyerson_Algorithm_Online(q: float, demand_list: list, facility_cost: int = 1) -> list[Facility]:
facilities_list = []
for demand in demand_list:
# calculate the relevent values
norm, next_facility = Find_Nearest_Facility(demand, facilities_list)
probability_facility = q_Get_Probab... |
def Randomize_Center(area: tuple) -> tuple:
return (rd.randint(0, area[0]), rd.randint(0, area[1]))
def Center_Range(demand_set_size: int) -> int:
return int(np.sqrt(demand_set_size))
def Find_Nearest_Center(demand: Demand, centers: list) -> tuple:
distances = [Euclidean_Norm(demand.position, center) for cen... | The code implements Lloyd's clustering algorithm to assign demands to facilities. It initializes random centers, iteratively clusters demands by proximity, updates center positions, and returns the final facility-demand assignments. | def Lloyd_Clustering(area: tuple, demand_list: list, iteration: int = 5) -> list[Facility]:
centers = [Randomize_Center(area) for i in range(0, Center_Range(len(demand_list)))]
for i in range(0, iteration):
clusters = [[] for center in centers]
for demand in demand_list:
nearest_ce... |
def Sample_Size(area: tuple, frac: float = 0.1) -> int:
upper_bound = Round((area[0] * area[1])*frac, 0)
if upper_bound <= 2:
upper_bound = 2
return rd.randint(1, upper_bound)
def Meyerson_Algorithm_Online(demand_list: list, facility_cost: int = 1) -> list[Facility]:
facilities_list = []
for... | The `Test_Algorithm` function evaluates clustering/facility-location algorithms (Meyerson, q-Meyerson, Lloyd) by running them over multiple iterations. For each iteration, it generates synthetic data streams, applies the selected algorithm to compute facilities, calculates associated costs, and logs results. It optiona... | def Test_Algorithm(iterations: int, area: tuple, costs: int, option: str = "meyerson", q: float = 0.5, timing: bool = False) -> list:
# options = ["meyerson", "q_meyerson", "lloyd"]
if timing: start = perf_counter()
results_alg = []
# creating the instances
for i in range(0, iterations):
if ... |
def Sample_Size(area: tuple, frac: float = 0.1) -> int:
upper_bound = Round((area[0] * area[1])*frac, 0)
if upper_bound <= 2:
upper_bound = 2
return rd.randint(1, upper_bound)
def Meyerson_Algorithm_Online(demand_list: list, facility_cost: int = 1) -> list[Facility]:
facilities_list = []
for... | The function `Compare_Algorithms` evaluates and compares three clustering algorithms (Meyerson, q-Meyerson, Lloyd) across multiple iterations. For each iteration, it generates synthetic data streams, applies the algorithms to compute facility placements, calculates associated costs, and records results. If timing is en... | def Compare_Algorithms(iterations: int, area: tuple, costs: int, q: float = 0.5, timing: bool = False) -> list:
if timing: start = perf_counter()
results_alg = []
# start of the simulation
for i in range(0, iterations):
if timing: iter_start = perf_counter()
# generate test case.
... |
def generate_real_images(dataset, n_samples):
ix = randint(0, dataset.shape[0], n_samples)
X = dataset[ix]
y = ones((n_samples, 1))
return X, y
def generate_fake_images(g_model, latent_dim, n_samples):
x_input = generate_latent_points(latent_dim, n_samples)
X = g_model.predict(x_input)
y = z... | This function trains a GAN by alternatingly updating the discriminator on real/fake images and the generator via the GAN model. It iterates over epochs and batches, generating real/fake data, training discriminator separately, then training generator using combined GAN model. Progress is printed periodically, and model... | def train(g_model, d_model, gan_model, dataset, latent_dim, n_epochs=300, n_batch=256):
bat_per_epo = int(dataset.shape[0] / n_batch)
half_batch = int(n_batch / 2)
for i in range(n_epochs):
for j in range(bat_per_epo):
X_real, y_real = generate_real_images(dataset, half_batch)
... |
def advance(self):
self.token_idx += 1
if self.token_idx < len(self.tokens):
self.current_tok = self.tokens[self.token_idx]
return self.current_tok
def expression(self):
return self.bin_op(self.term, (TokenType.PLUS, TokenType.MINUS)) | This code parses expressions by handling unary operators, numbers, and parentheses. It recursively processes tokens to build an abstract syntax tree (AST), returning nodes like UnaryOpNode, NumberNode, or expression results, while validating syntax and raising errors for invalid inputs. | def factor(self):
res = ParseResult()
tok = self.current_tok
if tok.type in (TokenType.PLUS, TokenType.MINUS):
res.register(self.advance())
factor = res.register(self.factor())
if (res.error): return res
return res.success(UnaryOpNode(tok,... |
def substitute_string(string, df, locale="en"):
"""Replace placeholders in the string with values from the DataFrame."""
pattern = r"\{\$([^\}]+)\}"
columns_to_substitute = re.findall(pattern, str(string))
for column in columns_to_substitute:
string = string.replace(
f"{{${column}}}... | The function generates visual charts (VALUE, PIE, LINES, BARS) based on a specification and datasets. It connects to SQLite databases, extracts data, substitutes placeholders with actual values, and creates charts using specialized functions, adding them to a dashboard. The process handles dynamic column references and... | def create_charts(spec, datasets, dashboard, locale="en"):
"""Create charts based on the given specification and datasets, and add to the dashboard."""
for idx, row in enumerate(spec["Rows"]):
if not row["DATA"]:
continue
# Fetch data from SQLite database
with sqlite3.conne... |
def get_identifiers(sdmx_url):
"""Retrieve agency and dataflow IDs from the SDMX URL."""
agency_id = get_agency_id(sdmx_url)
dataflow_id = get_dataflow_id(sdmx_url)
return agency_id, dataflow_id
def extract_data_from_message(message):
"""Extract data from the message payload."""
return list(mess... | The code loads SDMX data from a URL, extracts identifiers, processes metadata (if not raw), generates a structured dataframe, processes the database, and updates permissions/metadata, returning a table instance. | def load_database(sdmx_url, dataset_instance=None, is_raw_url=False):
# Extract main data and identifiers
message = read_sdmx(sdmx_url)
agency_id, dataflow_id = get_identifiers(sdmx_url)
data = extract_data_from_message(message)
concepts_name = {}
if not is_raw_url:
# Get the required w... |
def get_clustering_obj(method, clusters):
if "kmeans" in method:
return KMeans(
n_clusters=clusters,
random_state=42,
n_init=20,
n_jobs=-1,
max_iter=1000,
tol=1e-5,
)
elif method == "spectral":
return SpectralCluster... | The code performs clustering on sentences using specified methods (e.g., k-means, hierarchical, nearest neighbor), incorporating ICF terms for enhanced clustering. It processes sentence embeddings, combines them with ICF embeddings, reduces dimensions, assigns cluster labels, and computes a combined evaluation score (s... | def run_clustering(
method,
clusters,
sentences,
sentence_vectors,
base_path,
config,
pre_config,
save_path,
annotated_data,
sentence_annotations,
):
clustering_obj = get_clustering_obj(method, clusters)
icf_raw_sents = None
icf_labels = None
icf_sent_embeddings =... |
def get_binary_experimental_setup():
# Items
train_items, valid_items = extract_examples("items")
# Domains
train_domains, valid_domains = extract_examples("domains")
# Regroup items and domains together
train_examples = train_items + train_domains
valid_examples = valid_items + valid_doma... | This code fine-tunes a SentenceTransformer model using multi-task learning with four loss functions: binary contrastive loss, MSE loss, cosine similarity loss, and softmax classification loss. It prepares separate datasets for each task, combines them during training with weighted contributions, and saves the optimized... | def main(model_name, batch_size):
model = SentenceTransformer(model_name)
teacher_model = SentenceTransformer(model_name)
# Binary loss setting
binary_train_examples, evaluator = get_binary_experimental_setup()
binary_dataset = SentencesDataset(binary_train_examples, model)
binary_dataloader = ... |
def create_folder_for_config(config, pre_config, base_path):
save_path = base_path
for key, val in pre_config.items():
save_path = os.path.join(save_path, f"{key}::{val}")
for key, val in config.items():
save_path = os.path.join(save_path, f"{key}::{val}")
if os.path.isdir(save_path):... | The function `launch_from_config` processes text data by reducing sentence embeddings' dimensionality, applying clustering (based on config method), saving results, and updating the configuration. It returns the updated config and clustering score. Key steps include: creating a save path, dimensionality reduction, clus... | def launch_from_config(
config,
pre_config,
base_path,
vocab,
sents,
sent_embeddings,
annotated_data,
sentence_annotations,
):
save_path = create_folder_for_config(config, pre_config, base_path)
sent_embeddings = reduce_dim(
sent_embeddings, config["reduced_dim"], apply=... |
def load_all_domains():
return load_all_csv_rows("Full data domains.csv", encoding="ISO-8859-1")
def get_annotated_data(set):
with open(f"expert_annotations/{set}/all.pck", "rb") as f:
annotated_data = pickle.load(f)
return annotated_data
def get_hparams():
hparams = OrderedDict()
hparams[... | The code performs domain clustering by preprocessing text data, aligning annotated domains with processed text, and evaluating clustering results using various configurations. It cleans and normalizes domain strings, maps annotated domains to indices, generates hyperparameter combinations, computes sentence embeddings,... | def domains_clustering():
domains = load_all_domains()
annotated_domains = get_annotated_data("domains")
sents = [sent.replace('"', "") for sent in domains]
sents = [sent.replace(",", " ") for sent in sents]
sents = [sent.replace("/", " / ") for sent in sents]
sents = [sent.replace(".-", " .- "... |
def load_all_items():
items = load_all_csv_rows("Full data items.csv", encoding="Windows-1252")
items = [item for item in items if len(item.split()) > 2]
return items
def get_annotated_data(set):
with open(f"expert_annotations/{set}/all.pck", "rb") as f:
annotated_data = pickle.load(f)
ret... | The code processes and normalizes text data, clusters items using annotated datasets, and evaluates clustering configurations by generating embeddings and parallel computations, ultimately saving results for analysis. | def items_clustering():
items = load_all_items()
annotated_items = get_annotated_data("items")
sents = [sent.replace('"', "") for sent in items]
sents = [sent.replace(",", " ") for sent in sents]
sents = [sent.replace("/", " / ") for sent in sents]
sents = [sent.replace(".-", " .- ") for sent i... |
def _sign_up(self, request: Request):
if self.awaiting_file:
raise RuntimeError("got registration message in file phase")
if request.payload_size != MAX_USER_NAME_LEN:
raise RuntimeError("wrong payload size in registration")
username = ClientHandler._bytes_to_string(requ... | This function processes incoming client messages by determining the request type (e.g., sign-up, file transfer) and invoking the corresponding handler method. It updates the client's last active time, validates the request code, and handles errors by sending an error response if processing fails. | def handle_message(self):
"""Handle a message from the client."""
if not self.active:
raise RuntimeError(f"got message on inactive client {self.client_id}")
self.last_active_time = time.time()
try:
buffer = self.sock.recv(MAX_REQUEST_LENGTH)
request =... |
def set_text(fonts, string, coordx, coordy, fonttype, screenblit, align="no align",color=(255,255,255)): #Function to set text
font = fonts[fonttype]
#(0, 0, 0) is black, to make black text
text = font.render(string, True, color)
textRect = text.get_rect()
w = textRect.width
h = textRect.height... | The function `draw_menu` renders game UI menus (main, play, about, stats) by drawing titles, buttons, sliders, and dynamic content based on the `menu_type` parameter. It updates UI elements like statistics, sound status, and navigation arrows, returning modified button/slider lists and positions for interaction in the ... | def draw_menu(screenblit, menu_type, fonts,btn_list,slider_list,grid_expansions,player_count,tiles_covered,title_h,stats_view,stats_dict,reset_confirmed,copied,sound):
arr_rect_r = pg.Rect((-100,-100),(0,0))
arr_rect_l = pg.Rect((-100,-100),(0,0))
screen_w, screen_h = screenblit.get_size()
btn_w = roun... |
def _is_escaped(self, string, index):
escaped = False
while index > 0 and string[index-1] == '\\':
index -= 1
escaped = not escaped
return escaped
def _find_start_index(self, string, start, end):
while True:
index = string.find('{', start, end) - 1
... | This function identifies the start and end indices of a variable in a string, handling escaped characters. It locates the last '}' as the end, checks for escaping, then finds the corresponding start index. If either end or start is missing, it raises errors. The result is a tuple of start and end positions for the vari... | def _find_variable(self, string):
max_end_index = string.rfind('}')
if max_end_index == -1:
raise ValueError('No variable end found')
if self._is_escaped(string, max_end_index):
return self._find_variable(string[:max_end_index])
start_index = self._find_start_inde... |
def _no_signatures_arg_spec(self):
# Happens when a class has no public constructors
return self._format_arg_spec()
def _single_signature_arg_spec(self, signature):
varargs, kwargs = self._get_varargs_and_kwargs_support(signature.args)
positional = len(signature.args) - int(varargs) - in... | This function determines the appropriate method to process function signatures based on their count: returning no-signature handling if empty, single-signature processing for one item, or multi-signature handling for multiple items. | def _get_arg_spec(self, signatures):
if not signatures:
return self._no_signatures_arg_spec()
elif len(signatures) == 1:
return self._single_signature_arg_spec(signatures[0])
else:
return self._multi_signature_arg_spec(signatures) |
def _raise_invalid_spec(self, error):
raise DataError('Invalid argument specification: %s' % error)
def _is_kwargs(self, arg):
raise NotImplementedError
def _add_kwargs(self, kwargs, result):
result.kwargs = self._format_kwargs(kwargs)
def _is_varargs(self, arg):
raise NotImplementedErro... | This function parses a list of arguments into an ArgumentSpec object, validating their order and structure. It handles varargs (*), kwargs (**), and default values, ensuring varargs/kwargs appear only once and defaults don't precede non-default arguments. It raises errors for invalid specifications, then returns the co... | def parse(self, argspec, name=None):
result = ArgumentSpec(name, self._type)
for arg in argspec:
if result.kwargs:
self._raise_invalid_spec('Only last argument can be kwargs.')
if self._is_kwargs(arg):
self._add_kwargs(arg, result)
... |
def build_single_gpu_model(init_model, fc_size, num_classes, args):
""" Build a regular model """
model = load_pretrained_model(init_model, fc_size, num_classes, args.optimizer)
print(model.summary())
return model
def log_distrib_model_params(model, wandb_config, args):
""" Extract params of interest about th... | The code trains a large model using Keras with data augmentation, distributed GPU support, and wandb tracking. It initializes generators for training/validation data, builds a single or parallel GPU model based on args, and trains the model with specified epochs, batch size, and callbacks. | def test_large_model(args):
wandb.init(project="estuary")
K.clear_session()
# data generator from Keras finetuning tutorial
# TODO: consider modifying data augmentation strategy--more or less variety
train_datagen = ImageDataGenerator(
rescale=1. / 255,
shear_range=0.2,
zoom_range=0.2,
horizon... |
def IJsq(RI,RJ):
"""
Compute the square of the distance between two points.
(Handout 4, Eq 6)
"""
return sum( (RI[i]-RJ[i])**2 for i in (0,1,2) )
def N(a,l,m,n):
"""
Calculate the normalization factors.
(Handout 4, Eq. 9)
"""
N = (4*a)**(l+m+n)
#N /= misc.factorial2(2*l-1,exact=True) * misc.facto... | The function computes the overlap integral matrix S between atomic orbitals by iterating over all basis function pairs, calculating Gaussian primitive overlaps using contraction coefficients, normalization constants, and the Sxyz integral formula. It accumulates results into the KxK matrix S, applying exponential decay... | def buildS(basis, S):
"""
Pass in an empty KxK overlap integral matrix, S.
Calling the function (Sxyz) to calculate each Gaussian primitive overlap integral,
compute all elements of the S = (A|B) 2-dimensional matrix.
(Handout 4, Eq. 1)
"""
for A, bA in enumerate(basis): # retrieve atomic orbital A fro... |
def gaussianProduct(a,RA,b,RB,g):
"""
The product of two Gaussians is a third Gaussian.
(Handout 4, Eq. 5)
"""
P = []
for i in range(3):
P.append( (a*RA[i]+b*RB[i])/g )
return P
def IJsq(RI,RJ):
"""
Compute the square of the distance between two points.
(Handout 4, Eq 6)
"""
return sum( (RI... | The main task of the code is to compute the integral of four Gaussian functions (from atomic orbitals) over all space, involving angular momentum components (l, m, n) and their products. It uses nested loops to evaluate contributions from different quantum number combinations, computes the Boys function for the integra... | def Gxyz(lA,mA,nA,lB,mB,nB,lC,mC,nC,lD,mD,nD,a,b,c,d,RA,RB,RC,RD):
"""
Calling intermediate function gi to calculate individual x,y,z components,
calculate integrals over primitives.
(bracketed part of Handout 4, Eq. 18)
"""
gP = a + b
gQ = c + d
delta = 1/(4*gP) + 1/(4*gQ)
RP = gaussianProduct(a,RA... |
def IJsq(RI,RJ):
"""
Calculate the square of the distance between two points.
(Handout 4, Eq. 6)
"""
return sum( (RI[i]-RJ[i])**2 for i in (0,1,2) )
def N(a,l,m,n):
"""
Calculate the normalization factors.
(Handout 4, Eq. 9)
"""
N = (4*a)**(l+m+n)
#N /= misc.factorial2(2*l-1,exact=True) * misc.fa... | The code computes the overlap integral matrix $ S $ for Gaussian basis functions by iterating over all pairs of atomic orbitals (A, B). For each pair, it loops through their Gaussian primitives, calculates the exponential term, normalization constants, and the $ S_{xyz} $ integral using the given formula. The result is... | def buildS(basis, S):
"""
Pass in an empty KxK overlap integral matrix, S.
Calling the function (Sxyz) to calculate each Gaussian primitive overlap integral,
compute all elements of the S = (A|B) 2-dimensional matrix.
(Handout 4, Eq. 1)
"""
for A, bA in enumerate(basis): # retrieve atomic orbital A fro... |
def IJsq(RI,RJ):
"""
Compute the square of the distance between two points.
(Handout 4, Eq 6)
"""
return sum( (RI[i]-RJ[i])**2 for i in (0,1,2) )
def N(a,l,m,n):
"""
Calculate the normalization factors.
(Handout 4, Eq. 9)
"""
N = (4*a)**(l+m+n)
#N /= misc.factorial2(2*l-1,exact=True) * misc.facto... | This function constructs the kinetic energy integral matrix T by iterating over basis functions, calculating integrals using Kxyz, and accumulating results with exponential terms, normalization factors, and basis function parameters. | def buildT(basis, T):
"""
Build the kinetic energy integral matrix.
Call on function Kxyz to calculate integrals over primitives.
(part of Handout 4, Eq. 10)
"""
for A, bA in enumerate(basis):
for B, bB in enumerate(basis):
for a, dA in zip(bA['a'],bA['d']):
for b, dB in zip(bB['a'],bB['... |
def IJsq(RI,RJ):
"""
Calculate the square of the distance between two points.
(Handout 4, Eq. 6)
"""
return sum( (RI[i]-RJ[i])**2 for i in (0,1,2) )
def N(a,l,m,n):
"""
Calculate the normalization factors.
(Handout 4, Eq. 9)
"""
N = (4*a)**(l+m+n)
#N /= misc.factorial2(2*l-1,exact=True) * misc.fa... | The function `buildT` constructs the kinetic energy integral matrix by iterating over all pairs of basis functions and their primitives. It calculates each matrix element using the `Kxyz` function, incorporating exponential terms, normalization factors, and contraction coefficients from the basis set. The result is acc... | def buildT(basis, T):
"""
Build the kinetic energy integral matrix.
Call on function Kxyz to calculate integrals over primitives.
(part of Handout 4, Eq. 10)
"""
for A, bA in enumerate(basis):
for B, bB in enumerate(basis):
for a, dA in zip(bA['a'],bA['d']):
for b, dB in zip(bB['a'],bB['... |
def readUnsignedbyte(self):
return struct.unpack('B', self.get(1))[0]
def readByte(self):
return struct.unpack('b', self.get(self.BYTE_SIZE))[0]
def readUnsignedShort(self):
return struct.unpack('>H', self.get(self.SHORT_SIZE))[0] | This code reads an IPv4 address and port from binary data by parsing four octets as a hostname, converting them to a dotted-decimal string, then reading an unsigned short as the port. It returns the hostname, port, and IP version (4) as a tuple, or raises an exception if the IP version is not 4. | def readAddress(self):
ipv = self.readUnsignedbyte()
if ipv == 4:
hostname_parts = []
for part in range(4):
hostname_parts.append(str(~self.readByte() & 0xff))
hostname = ".".join(hostname_parts)
port = self.readUnsignedShort()
... |
def __find_usersecrets_id(path: Path = None, iter: int = 0) -> str:
if(iter > 2):
return None
if(path is None):
path = Path.cwd()
user_secrets_path = path.joinpath(".usersecrets")
if(user_secrets_path.exists()):
return user_secrets_path.read_text("utf-... | This function adds and merges configuration settings from .NET user-secrets into the current configuration. It accepts an optional ID parameter, defaults to finding the ID via `__find_usersecrets_id()`, validates the ID, loads the configuration using `__load_configuration_from_usersecrets()`, and merges it with `__add_... | def add_user_secrets(self, id: str = None) -> None:
""" Add and merge configuration from dotnet user-secrets"""
if(id is None):
id = self.__find_usersecrets_id()
if(id is None or id == ""):
print("File `.usersecrets` with id not found")
return
loaded_c... |
def show_info_page(**options):
return ShowInfoPage(**options).show_info_page()
def show_convert_page():
maxValue = sum([len(files) for r, d, files in os.walk(EVTX_LOGS_PATH)])
convert_progress_bar = ShowProgressBarPage(maxValue=maxValue,
title='Convert Process ... | This function handles keyboard input in a menu interface. It updates focus on menu items using arrow keys and triggers actions when Enter is pressed. If 'Exit' is selected, it exits the program. Other options like 'Info', 'Convert', 'Analyse', and 'Visualise' display respective pages and reset the interface. The core t... | def welcome_key_event_handler(self):
self.win.refresh()
key = self.win.getch()
if key == curses.KEY_UP and self.focus[1] != 0:
self.focus[1] -= 1
elif key == curses.KEY_DOWN and self.focus[1] != len(self.menu) - 1:
self.focus[1] += 1
elif key == o... |
def get_dataset(name: str, use_lcc: bool = True, homophily=None):
"""
:param name: the name of the graph dataset.
:param use_lcc: whether to use the largest connected component of the graph.
:param homophily: whether to assume homophily in the graph.
:return: the dataset and evaluator.
"""
... | The function fills missing values in a dataset (either graph or tabular) by propagating features through edges. For graph data, it uses existing edges; for tabular data, it generates edges. It applies feature propagation with a mask to impute missing values, then combines the filled features with labels and returns the... | def fill_data(data_name):
"""
this method takes the name of the dataset, then gets the missing values mask, and then fill the data accordingly.
:param data_name: the dataset name (tabular or graph).
:return: the data with filled values.
"""
# case 1: graph dataset, hence we have edges.
if d... |
def get_dataset(name: str, use_lcc: bool = True, homophily=None):
"""
:param name: the name of the graph dataset.
:param use_lcc: whether to use the largest connected component of the graph.
:param homophily: whether to assume homophily in the graph.
:return: the dataset and evaluator.
"""
... | The code's main task is to handle missing data in datasets by first removing a specified proportion of values and then filling them using a propagation method. It processes both graph and tabular datasets, applying z-score normalization, generating missing value masks, and employing FeaturePropagation with KNN edges fo... | def remove_and_fill(data_name, missing_rate: float = 0.1,):
"""
this method takes the name of the dataset, then removes the missing values, and then fill the data accordingly.
:param data_name: name of the dataset.
:param missing_rate: the rate of missing values.
:return: the data after filling with... |
def query(self, method: str = 'get', data=None, headers=None, iri: str = None):
if headers is None:
headers = {}
if data is None:
data = {}
http_method = getattr(self.client, method)
response = http_method(self.build_url(self.resource_name, iri), data=data, heade... | This method handles GET requests by preparing data and headers. It initializes empty dictionaries if inputs are None, serializes data to JSON, constructs headers, and invokes self.query with these parameters to execute the request. | def get(self, data=None, headers=None):
if headers is None:
headers = {}
if data is None:
data = {}
return self.query(method="get", data=json.dumps(self.serialize(data)), headers=self.build_headers(headers)) |
def query(self, method: str = 'get', data=None, headers=None, iri: str = None):
if headers is None:
headers = {}
if data is None:
data = {}
http_method = getattr(self.client, method)
response = http_method(self.build_url(self.resource_name, iri), data=data, heade... | This method handles POST requests by preparing data and headers, serializing data to JSON, and invoking a query method with the specified parameters. | def post(self, data=None, headers=None):
if headers is None:
headers = {}
if data is None:
data = {}
return self.query(method="post", data=json.dumps(self.serialize(data)), headers=self.build_headers(headers)) |
def query(self, method: str = 'get', data=None, headers=None, iri: str = None):
if headers is None:
headers = {}
if data is None:
data = {}
http_method = getattr(self.client, method)
response = http_method(self.build_url(self.resource_name, iri), data=data, heade... | This method handles a PUT request by preparing data and headers, serializing the data to JSON, and invoking a query method to execute the request. It defaults to empty dictionaries if no data or headers are provided, ensuring proper formatting and header construction before sending the PUT operation. | def put(self, data=None, headers=None):
if data is None:
data = {}
if headers is None:
headers = {}
return self.query(method="put", data=json.dumps(self.serialize(data)), headers=self.build_headers(headers)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.