dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def adaptive_range(A, eps=1e-7, k=50, p=50, method='qr_merging', power_iter_k=2, power_iter_p=0,
stabilize_qr_merging=True, max_p_iter=np.float('inf')):
if A.shape[0] < 10 or A.shape[1] < 10:
Q, _ = la.qr(A, mode='economic')
return Q
Q = randomized_range(A, rank=k, power_iter... | This function computes the randomized singular value decomposition (SVD) of a matrix A, returning truncated U, sigma, V matrices. It adaptively determines the rank if unspecified, using block Krylov or incremental methods. When use_id is True, it applies an ID-based approach with QR decomposition; otherwise, it compute... | def randomized_svd(A, rank=None, power_iter=2, k=50, p=50, block_krylov=True, l=0, use_id=False):
"""
:param rank: If None, adaptive range finder is used to detect the rank.
:param power_iter: Number of power iterations.
:param k: Initial estimate of rank, if adaptive range finder is used.
:param p:... |
def get_warped(self):
"""
Apply warp perspective tranformation by finding the corners of the contour to convert the
sudoku from being part of the image to the complete image itself.
"""
# get the generated white mask and the largest contour
img, max_cnt = self.get_grid()... | The main task of the code is to extract and validate a Sudoku puzzle matrix from an image. It processes each cell of the warped image, uses a pre-trained model to predict digits, and ensures the resulting matrix adheres to Sudoku rules by resolving conflicts where duplicate digits appear in the same row, column, or sub... | def get_matrix(self):
"""Returns the puzzle matrix from the image"""
# get the warped image
img, _ = self.get_warped()
# if warped image is None
if img is None:
# return None
return None
# get the dimensions for the game
self.game_size, ... |
def generate_template_readme(file_name, table):
date = datetime.today().strftime('%Y-%m-%d')
markers_dict = {}
template = MdUtils(file_name=file_name, title=f'ASCT+B Validation Reports for {table} ({date})')
template.new_header(level=1, title="Invalid terms", add_table_of_contents='y')
template.new_paragrap... | The code generates a README file by inserting reports on data issues (e.g., missing IDs, typos, label mismatches) and relationship types into a template using predefined markers. It also adds links to TSV reports for specific data categories, then compiles the final markdown file. | def generate_readme(file, data, table):
readme, markers_dict = generate_template_readme(file, table)
terms_report = generate_invalid_terms_report(data, table)
rel_report = generate_relationship_md(table)
readme.file_data_text = readme.place_text_using_marker(text=terms_report["no_found_id"], marker=markers... |
def load_data(input_tokenizer, output_tokenizer, params):
# make a bunch of datasets and dataloaders therefrom
train_dataset = BrownStyleDataset(stage='train', input_tokenizer=input_tokenizer, output_tokenizer=output_tokenizer, params=params)
train_dataloader = DataLoader(train_dataset, batch_size=params.b... | The main task of the code is to train and evaluate a BERT-based encoder-decoder model for sequence generation, coupled with a genre classifier. It uses a BERT tokenizer for input and output, adjusts special tokens, and loads data. Depending on parameters, it trains either the classifier, the autoencoder, or both togeth... | def main(params):
input_tokenizer = BertTokenizer.from_pretrained("bert-base-cased")
# # pro tip: https://huggingface.co/patrickvonplaten/bert2gpt2-cnn_dailymail-fp16
# def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):
# outputs = [self.bos_token_id] + token_ids_0 + [s... |
def booking(seat_b, cap):
width = len(seat_b[0]) - 1
length = len(seat_b) - 1
fail = 0
while True:
success = 0
incap = "number to book (seat remaining : {}) : ".format(cap)
book_seat = check_err(1, "Please insert one positive number only. !!","a", incap, [])
if book_seat ... | The main task of the code is to manage seat booking by calling the `booking` function, displaying seat arrangements, and printing booking status (success/failure counts and total money). It checks if capacity is exhausted, prompts the user to book more seats with input validation, and returns the user's choice and rema... | def main(seat, cap):
success, failure, capp, seat = booking(seat, cap)
showSeat(seat)
print("-- Status --")
print("Success =", success, ", Failure =", failure)
print("Total money : {} $ ".format(money(seat)))
print()
if capp == 0: return '', 0
while True:
re = input("Are you want... |
def send(m, p, t, **values):
data = {'type': t}
data.update(values)
return m(p.id_in_group, data)[p.id_in_group]
def get_last_puzzle(p) -> Puzzle:
puzzles = Puzzle.filter(player=p, iteration=p.iteration)
puzzle = puzzles[-1] if len(puzzles) else None
return puzzle
def get_target(z, i):
slide... | This code simulates testing a slider puzzle interaction by sending incorrect and correct values for each slider, verifying puzzle states, slider positions, and feedback responses. It tests system behavior during retries with delays, ensuring proper handling of puzzle solving progression and feedback mechanisms for each... | def live_test_normal(method, player, conf):
num_sliders = conf['num_sliders']
retry_delay = conf['retry_delay']
send(method, player, 'load')
send(method, player, 'new')
puzzle = get_last_puzzle(player)
for i in range(num_sliders):
last = (i == num_sliders-1)
target = get_targe... |
def send(m, p, t, **values):
data = {'type': t}
data.update(values)
return m(p.id_in_group, data)[p.id_in_group]
def get_last_puzzle(p) -> Puzzle:
puzzles = Puzzle.filter(player=p, iteration=p.iteration)
puzzle = puzzles[-1] if len(puzzles) else None
return puzzle
def get_target(z, i):
slide... | The main task of the code is to test the snapping functionality of a slider in a puzzle game. It sends commands to load and initialize a player's puzzle, retrieves a target value, adjusts it, applies snapping logic, and verifies the slider's expected position after the adjustment. | def live_test_snapping(method, player, conf):
send(method, player, 'load')
send(method, player, 'new')
puzzle = get_last_puzzle(player)
solution0 = get_target(puzzle, 0)
value = solution0 + 100
snapped = snap_value(value, solution0)
send(method, player, 'value', slider=0, value=value)
... |
def send(m, p, t, **values):
data = {'type': t}
data.update(values)
return m(p.id_in_group, data)[p.id_in_group]
def get_last_puzzle(p) -> Puzzle:
puzzles = Puzzle.filter(player=p, iteration=p.iteration)
puzzle = puzzles[-1] if len(puzzles) else None
return puzzle
def expect_response(r, t, **val... | This code tests the reloading functionality of a game or application by simulating user interactions. It verifies that the game state (puzzle progress, correct answers, slider positions) persists correctly after reloading. Key steps include initializing a puzzle, submitting an answer, reloading the game, and validating... | def live_test_reloading(method, player, conf):
# start of the game
resp = send(method, player, 'load')
expect(get_last_puzzle(player), None)
expect_response(resp, 'status')
expect_response_progress(resp, iteration=0)
resp = send(method, player, 'new')
puzzle = get_last_puzzle(player)
e... |
def send(m, p, t, **values):
data = {'type': t}
data.update(values)
return m(p.id_in_group, data)[p.id_in_group]
def get_last_puzzle(p) -> Puzzle:
puzzles = Puzzle.filter(player=p, iteration=p.iteration)
puzzle = puzzles[-1] if len(puzzles) else None
return puzzle
def get_target(z, i):
slide... | This function tests a system's response to excessive slider value submissions. It sends repeated valid values (v1) to a slider, then attempts an invalid value (v2) expecting a failure. The test verifies that the slider retains the last valid value (v1) after exceeding allowed submission attempts, ensuring proper error ... | def live_test_submitting_toomany(method, player, conf):
retry_delay = conf['retry_delay']
send(method, player, 'load')
send(method, player, 'new')
puzzle = get_last_puzzle(player)
target = get_target(puzzle, 0)
v1 = snap_value(100, target)
v2 = snap_value(50, target)
for _ in range(c... |
def send(m, p, t, **values):
data = {'type': t}
data.update(values)
return m(p.id_in_group, data)[p.id_in_group]
def get_last_puzzle(p) -> Puzzle:
puzzles = Puzzle.filter(player=p, iteration=p.iteration)
puzzle = puzzles[-1] if len(puzzles) else None
return puzzle
def get_target(z, i):
slide... | This code tests if submitting slider values too quickly triggers an error. It sends initial commands, sets a slider value, verifies the update, then attempts a second submission which should fail with a RuntimeError. The test ensures the slider retains its original value after the failed submission, confirming proper e... | def live_test_submitting_toofast(method, player, conf):
send(method, player, 'load')
send(method, player, 'new')
puzzle = get_last_puzzle(player)
target = get_target(puzzle, 0)
v1 = snap_value(100, target)
v2 = snap_value(50, target)
resp = send(method, player, 'value', slider=0, value=v1... |
def are_alike(x, y): return are_not_sequences(x, y) or are_both_sequences(x, y)
def is_sequence(s): return type(s) is list | This function checks if two nested structures have the same shape by recursively comparing element types and sequence lengths, ensuring corresponding elements are alike and sequences match in depth and length. | def same_structure_as(original, other):
if not are_alike(original, other):
return False
for idx, val in enumerate(original):
if other[idx] is None: # Out of bound protection
return False
other_val = other[idx]
if not are_alike(val, other_val):
return Fals... |
def validate_sources(mat_source):
valid = os.path.isfile(mat_source) or validators.url(mat_source)
return valid
def init(songname="", mat_type=""):
song_dump = get_song_dump()
songs = song_dump['songs']
song = get_curr_song(songname, songs) if songname else None
materials = get_materials(song, m... | The function `add_helper` adds a new material (tab or video) to a song's data, ensuring no duplicate sources or titles. It validates the source, checks for existing song entries, and appends the material to the appropriate list (tabs/videos). If duplicates are found, it raises exceptions. Finally, it saves the updated ... | def add_helper(songname, mat_type, mat_title, mat_source):
valid = validate_sources(mat_source)
if not valid:
raise click.ClickException('Source provided is not a valid file/url.')
song_dump, songs, song, materials = init(songname, mat_type)
mat = {"title": mat_title, "source": mat_source}
... |
def init(songname="", mat_type=""):
song_dump = get_song_dump()
songs = song_dump['songs']
song = get_curr_song(songname, songs) if songname else None
materials = get_materials(song, mat_type) if song and mat_type else None
return song_dump, songs, song, materials
def get_materials(song, mat_type):... | The function `open_all_mats` retrieves and opens tabs and videos for a given song. It checks if the song exists, fetches associated materials, and handles cases where tabs or videos are missing. If both exist, it prompts the user to select one or defaults to the first. Finally, it launches the chosen tab and video sour... | def open_all_mats(songname):
_, _, song, _ = init(songname)
if not song:
raise click.ClickException('Currently \'{}\' does not exist in your library.'.format(songname.title()))
tabs, videos = get_materials(song, 'tab'), get_materials(song, 'video')
tab_cnt, video_cnt = len(tabs), len(videos)
... |
def blossomLeaves(b):
if b < nvertex:
yield b
else:
for t in blossomchilds[b]:
if t < nvertex:
yield t
else:
for v in blossomLeaves(t):
yield v
def assignLabel(w, t, p):
b = in... | This function expands a blossom structure in a graph matching algorithm, updating vertex labels, endpoints, and edge assignments. It recursively processes child blossoms, adjusts labels for vertices and endpoints, and manages allowed edges. During expansion, it ensures proper labeling of blossom endpoints and their ass... | def expandBlossom(b, endstage):
for s in blossomchilds[b]:
blossomparent[s] = -1
if s < nvertex:
inblossom[s] = s
elif endstage and dualvar[s] == 0:
expandBlossom(s, endstage)
else:
for v in blossomLeaves(s):
... |
def calculate_air_density(altitude : float) -> float:
molar_mass_air = 0.02896#molar mass of earths air, kg/mol
R = 8.314;#the universal gas constant.
max_altitudes = [11000,20000,32000,47000,51000,71000,86000]#maximum altitude in atmospheric layers
temperature_lapse_rates = [-0.0065,0,0.001,0.0028,0,-0... | The main task of the code is to generate and display plots of aerodynamic forces (lift, induced wing drag, induced fuselage drag, parasitic drag, and lift-to-drag ratio) against angle of attack, calculated for given airspeed, altitude, and angle ranges. It computes these values iteratively for each angle, uses air dens... | def plot_lift_and_drag(self,airspeed : float,altitude : float,start_angle : float,end_angle : float,increment : float):
angles = np.arange(start_angle,end_angle+increment,increment)
angles_degrees = list(angles)
angles : list[float] = list(np.radians(angles))
lifts : list[float] = []
... |
def load_all_airports(self,airport_folder='airport_csvs'):
self.create_airport_variables() #create the variables which store airport properties
airport_filepaths = utility.get_filepaths_in_folder(airport_folder) #get every file in the airports folder
for airport_filepaths in tqdm.tqdm(airport_fi... | The main task of the code is to initialize and configure a transportation network by loading all airports, ferries, and roads, then computing airport statistics and travel demand. This setup prepares the network data for further analysis or simulation, ensuring all infrastructure components and related metrics are prop... | def setup_network(self) -> None:
self.load_all_airports()
self.load_all_ferries()
self.load_all_roads()
self.calculate_airport_statistics()
self.calculate_travel_demand() |
def openTextInput(self):
textFile = './RunningNotes.html'
textFileHandle = open(textFile, 'r')
inputText = textFileHandle.read()
self.textNotes.setText(str(inputText))
textFileHandle.close()
def shutterToggle(self, button):
if button.text() == 'Open':
if butto... | This code initializes a GUI application with matplotlib plotting, serial communication, and user interaction controls. It sets up a plotting canvas, connects buttons to functions for data generation, scanning control, and shutter/joystick toggling, while initializing state variables and hardware interfaces for real-tim... | def __init__(self, ):
super(Main, self).__init__()
self.setupUi(self)
self.fig = plt.Figure()
self.ax = self.fig.add_subplot(111)
self.canvas = FigureCanvas(self.fig)
self.openTextInput()
self.inputData = np.zeros([512,512])
self.resizedArr = np.zeros([2... |
def inRow(sud, x):
return x in getRowList(sud, getRows(sud))
def inCol(sud, y):
return y in getColList(sud, getCols(sud))
def inSquare(sud, z):
return z in getSquareList(sud, getSquare(sud))
def PrintSudoku(sud):
rows = getRows(sud)
for i in range(rows):
print(getRowList(sud, i)) | The main task of the code is to generate a valid 9x9 Sudoku puzzle by randomly placing numbers while adhering to Sudoku rules (no duplicates in rows, columns, or 3x3 squares). It tracks the number of attempts and execution time, then calculates and prints performance metrics including total time in milliseconds and att... | def main():
gt.reset()
tries = 0
# starting with just 9x9.
sudoku = [] # 1D list of all sudoku's elements.
while len(sudoku) < 81:
tries += 1
num_list = list(range(1, 10))
num = random.choice(num_list)
while inRow(sudoku, num) or inCol(sudoku, num) or inSquare(sud... |
def inRow(sud, x):
return x in getRowList(sud, getRows(sud))
def inCol(sud, y):
return y in getColList(sud, getCols(sud))
def inSquare(sud, z):
return z in getSquareList(sud, getSquare(sud)) | The code generates a valid Sudoku puzzle by randomly placing numbers 1-9 into a 1D list, ensuring each addition doesn't violate row, column, or 3x3 square constraints. It repeatedly attempts placements, resetting on conflicts, until a complete 81-element Sudoku is created. | def generateSudoku():
tries = 0 # attempts to generate a complete sudoku
sudoku = [] # 1D list of all sudoku's elements.
while len(sudoku) < 81: # while not a full sudoku
tries += 1
num_list = list(range(1, 10))
num = random.choice(num_list)
while inRow(sudoku, num) or i... |
def get_best_split(X, y, node_indices):
num_features = X.shape[1]
best_feature = -1
max_info_gain = 0
for feature in range(num_features):
info_gain = compute_information_gain(X, y, node_indices, feature)
if info_gain > max_info_gain:
max_info_gain = info_gain
... | This recursive function constructs a decision tree by splitting the dataset at each node based on the best feature. It prints the tree structure, appends splits to the tree list, and recursively processes left/right subsets until the max depth is reached. | def build_tree_recursive(X, y, node_indices, branch_name, max_depth, current_depth, tree):
if current_depth == max_depth:
formatting = " "*current_depth + "-"*current_depth
print(formatting, "%s leaf node with indices" % branch_name, node_indices)
return
best_feature = get_best_spl... |
def parse_packet_lines(data: bytes) -> List:
"""
Parse packet lines in data.
"""
packets = []
i = 0
while i < len(data):
bytes_parsed, packet = parse_packet_line(data, i)
i += bytes_parsed
if packet:
packets.append(packet)
return packets
def parse_first_re... | The main task of the code is to parse input `refs_data` into a list of reference tuples by splitting the data into packets, extracting the first reference, and processing subsequent packets to append parsed references. It uses helper functions to handle packet lines and individual references, returning a structured lis... | def parse_refs(refs_data) -> List[Tuple[str, str]]:
"""
Parse refs data from host to list of refs.
"""
packets = parse_packet_lines(refs_data)
first, _options = parse_first_ref_line(packets[1])
refs = [first]
for packet in packets[2:]:
refs.append(parse_ref(packet))
return refs |
def query_refs(host: str, repo: str) -> bytes:
"""
Request refs from repo at host.
"""
conn = http.client.HTTPSConnection(host)
conn.request("GET", f"{repo}/info/refs?service=git-upload-pack")
response = conn.getresponse()
if response.headers["Content-Type"] != f"application/x-git-upload-pa... | The function `download_pack` retrieves Git repository data from a specified host. It queries references (refs) for the given repository, parses them into a list of reference entries, extracts SHA hashes from these references, and uses them to fetch a pack file from the host. The pack is parsed and validated; if success... | def download_pack(host: str, repo: str) -> Tuple[List, List]:
"""
Download pack from host.
"""
refs_data = query_refs(host, repo)
packets = parse_packet_lines(refs_data)
first, _ = parse_first_ref_line(packets[1])
refs = [first]
for packet in packets[2:]:
refs.append(parse_ref(pa... |
def getMiniMaxMove(self, board):
"""
This method calls the minimax algorithm method to find an optimal moves.
param board: A TicTacToe object
return: True if the move is legal and false if the minimax method returns
None type for the optimal move
"""
playerMove = self.minimax(board)
if playerMove ... | The `makeMove` method selects a move strategy based on the player type: MINIMAX uses the MiniMax algorithm, RANDOM selects randomly, RL chooses the highest state value from a table, and HUMAN prompts user input. It returns True for legal moves or False if the HUMAN player quits. | def makeMove(self, board) :
"""
This method performs a move for the player. The move is
determined by the player type. If player type is MINIMAX then the
MiniMax algorithm is used to find a move. If player type is
RANDOM then a random move is made. If the player type is HUMAN
then the program ask the use... |
def parse_strawanzerin_image(self, save_path_for_pdf, path_to_new_directory):
"""Parse the strawanzerin file."""
# Get source file
src = fitz.open(save_path_for_pdf)
# Get image from first page
page = src.load_page(0)
index = "strawanzerin"
# Get image from PD... | The main task of the code is to parse a "strawanzerin" document by extracting text from its pages, combining it with image-related data, and uploading the structured metadata—including version-specific category IDs—to a WordPress backend. It processes PDFs, extracts version numbers from directory names, manages paper c... | def parse_strawanzerin(self, save_path_for_pdf, path_to_new_directory):
"""Parse the strawanzerin file."""
image_id, image_text = self.parse_strawanzerin_image(
save_path_for_pdf, path_to_new_directory
)
text = self.parse_first_page(save_path_for_pdf, path_to_new_directory)
... |
def add_head_style(document: HtmlElement):
head = document.find(".//head")
head.append(fragment_fromstring(bootstrap_email_head(document)))
def add_missing_meta_tags(document: HtmlElement):
META_TAGS = [
{
"query": 'meta[@http-equiv="x-ua-compatible"]',
"code": '<meta http-eq... | The code configures an HTML document by adding a style to the head, inserting missing meta tags, and including a version comment. It modifies the provided HtmlElement object in place and returns it after applying these enhancements to standardize or improve the document's structure and metadata. | def configure_html(document: HtmlElement):
add_head_style(document)
add_missing_meta_tags(document)
add_version_comment(document)
return document |
def compile_html(input_html: str) -> HtmlElement:
"""Transform the structure of the given HTML fragment to ensure it will render
consistently across email clients.
Args:
input_html (str): HTML fragment to compile
Returns:
HtmlElement: transformed HTML document
"""
complete_html... | The main task of the code is to convert an input HTML fragment into a complete, email-client-compatible HTML document by compiling, inlining CSS, configuring settings, and finalizing the document for consistent rendering across email clients. | def compile(input_html: str) -> str:
"""Compile the given input HTML fragment into a complete HTML
document that will render consistently across email clients."""
document = compile_html(input_html)
document = inline_css(document)
document = configure_html(document)
finalized = finalize_docume... |
def click(x, y):
win32api.SetCursorPos((x, y))
time.sleep(0.01)
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, x, y, 0, 0)
time.sleep(0.01)
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, x, y, 0, 0)
time.sleep(0.01)
def slow_keys(shell, keys):
for key in keys:
shell.SendKeys(... | The main task of the code is to automate the extraction of Tibia in-game coin trade data (buy/sell offers and amounts) by simulating user interactions, capturing screen data, and logging real-time updates with timestamps into an Excel file. It continuously checks if Tibia is the active window, performs clicks/keystroke... | def update_coin(self):
df = pd.read_excel('.\\xl\\coin.xlsx', index_col=None)
write = pd.ExcelWriter('.\\xl\\coin.xlsx', engine='xlsxwriter')
shell = win32com.client.Dispatch("WScript.Shell")
while True:
if "Tibia" in GetWindowText(GetForegroundWindow()):
cl... |
def click(x, y):
win32api.SetCursorPos((x, y))
time.sleep(0.01)
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, x, y, 0, 0)
time.sleep(0.01)
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, x, y, 0, 0)
time.sleep(0.01)
def slow_keys(shell, keys):
for key in keys:
shell.SendKeys(... | The code automates extracting Tibia game market data by interacting with the game window, capturing buy/sell offers and amounts for items listed in a DataFrame, calculating financial metrics (e.g., return percentages, profit potential), and updating the DataFrame with results before exporting it to an Excel sheet. | def check_market(self, market_df, xl_sheet):
shell = win32com.client.Dispatch("WScript.Shell")
while True:
if "Tibia" in GetWindowText(GetForegroundWindow()):
buy_offers = []
sell_offers = []
buy_amounts = []
sell_amounts = []... |
def data_split(critical):
X_train, X_val, y_train, y_val = train_test_split(critical.index.values,
critical.Label.values,
test_size=0.15,
random_state=42,... | This code trains a BERT model for sequence classification with 3 labels, using distributed training across multiple instances. It initializes the model, sets up data loaders, and implements a training loop with synchronization to a central server. The loop handles model loading, local training, validation, and progress... | def modeltraining(self, df):
# initial from the beginning
df = data_split(df)
dataset_train, dataset_val = tokenizationBERT(df)
model = BertForSequenceClassification.from_pretrained("bert-base-uncased",
num_labels=3,
... |
def store_pwd(user):
url = simpledialog.askstring("Store Password", "Website URL:")
uname = simpledialog.askstring("Store Password", "Username:")
passwd = simpledialog.askstring("Store Password", "Password:", show='*')
if url and uname and passwd:
encrypt, key = encrypt_pwd(passwd)
with ... | The code creates a Tkinter GUI for a password manager, allowing users to store, extract, delete, modify passwords/usernames, or exit. It displays a welcome message and provides buttons for each action, linking them to respective functions with the user's data. | def password_interface(user):
root = tk.Tk()
root.title("SavePass Password Manager")
label = tk.Label(root, text=f"Welcome {user.upper()}, SavePass is an open-source project to generate and store passwords")
label.pack()
options = [
("Store a Password", lambda: store_pwd(user)),
("... |
def exists_list(file_path, keyword):
lines = []
line_number = 1
with open(file_path, 'r') as file:
for line in file:
line_number += 1
if keyword in line:
lines.append(line_number)
return lines
def delete_lines(file_path, lines_to_delete):
try:
... | The code deletes a user's account and associated data from two files ('accounts.txt' and 'passman.txt') after confirming with the user. It identifies and removes specific lines containing the user's data, including surrounding lines in 'passman.txt', then displays a success message and exits the program. If canceled, i... | def delete_account(user):
inp = messagebox.askyesno("Delete Account", "You are going to lose your entire data. Continue?")
if inp:
linn = exists_list('accounts.txt', user)
y = []
for i in linn:
y.append(i - 1)
y.append(i)
delete_lines('accounts.txt', y)
... |
def exit_program():
messagebox.showinfo("Exit", f"Exiting the program at {time.strftime('%X')}...")
sys.exit(0)
def uname_exists(file_path, keyword):
line_number = 0
with open(file_path, 'r') as file:
for line in file:
line_number += 1
if keyword in line:
... | The code implements a login system that verifies user credentials against a text file. It checks for existing accounts, prompts for username/password, hashes the password, and grants access if valid. Upon successful login, it opens a GUI with options to change password, delete the account, or exit. Failed attempts decr... | def login_account():
uname = simpledialog.askstring("Login", "Username:")
if uname:
if not os.path.exists('accounts.txt'):
messagebox.showinfo("Error", "No accounts found. Please signup first!")
exit_program()
line_no = uname_exists('accounts.txt', uname)
if line_... |
def handle_slack_challenge_request(body, secret_object, env):
secret_object.slack_token = body['token']
challenge = body['challenge']
update_secrets(env, secret_object, env.secrets_arn)
return {
"statusCode": 200,
"body": challenge
}
def validate_slack_request(event, secret_object):
... | This function routes Slack events by checking the event type. It handles Slack's URL verification challenge if the event type is 'url_verification' and processes app mention events if the type is 'app_mention'. For other event types, it returns a 404 error with an unhandled message. The function validates Slack request... | def route_slack_call(event, secret_object, env):
print('in route slack call')
body = event['body']
event_type = body['type']
if event_type == 'url_verification':
return handle_slack_challenge_request(body, secret_object, env)
event_type = body['event']['type']
print(validate_slack_... |
def handle_get_conflunce_app_descriptor(event, secret_object):
return {
"statusCode": 200,
"body": json.dumps(secret_object.atlassian_connect_json)
}
def handle_confluence_installed(event, secret_object, env):
if validate_installed_request(event, secret_object):
body = event['body']
... | The function `route_call` determines the appropriate handler for incoming requests based on the URL path in the event. It routes requests to specific functions for Confluence app descriptors, Confluence installation handling, or Slack-related processing, returning a 400 error if the path doesn't match any predefined ro... | def route_call(event, secret_object, env):
path = event['path']
if '/confluence/atlassian-connect' in path:
return handle_get_conflunce_app_descriptor(event, secret_object)
elif '/confluence/installed' in path:
return handle_confluence_installed(event, secret_object, env)
elif '/slack' i... |
def load_env():
env = Env()
env.env = os.environ.get('ENV')
print(env.env)
if env.env == 'local':
with open('.local/env.json', 'r') as file:
data = json.load(file)
env.confluence_space_key = data['confluence_space_key']
env.confluence_page_title = data['conflu... | The code initializes environment (ENV) and secret (SECRET_OBJECT) variables if not already set, then routes the request using these values. It prints environment and secret details before delegating processing to route_call with the event, secrets, and environment. | def handler(event, context):
global ENV, SECRET_OBJECT
print('handler called')
if not ENV:
ENV = load_env()
if not SECRET_OBJECT:
SECRET_OBJECT = get_secrets(ENV)
print(f'{ENV.env}')
print(f'{SECRET_OBJECT.confluence_token}')
return route_call(event, SECRET_OBJECT, ENV) |
def _get_argument_with_name(arg_name: str, node: ast.FunctionDef) -> Optional[int]:
for index, arg in enumerate(node.args.args):
if arg_name == arg.arg:
return index
return None
def _check_argument_indent(
self,
arg_indent: str,
arg_name: str,
arg_index: int,
... | This function validates and documents function arguments by checking their indentation and documentation against the provided AST node. It extracts argument details from regex matches, locates the argument in the node, verifies indentation, and updates the context with the argument's position if valid. | def _check_argument_info(
self, regex_matches: re.Match, context: DocContext, node: ast.FunctionDef
) -> None:
arg_indent, arg_name, arg_type, arg_description = regex_matches.groups()
arg_index = _get_argument_with_name(arg_name, node)
self._check_argument_indent(arg_indent, arg_name... |
def _check_argument_info(
self, regex_matches: re.Match, context: DocContext, node: ast.FunctionDef
) -> None:
arg_indent, arg_name, arg_type, arg_description = regex_matches.groups()
arg_index = _get_argument_with_name(arg_name, node)
self._check_argument_indent(arg_indent, arg_name... | This method processes a docstring line based on the current section (description, arguments, return), validating formatting, checking for content, and ensuring proper indentation using regex and context tracking to enforce structured documentation rules. | def _check_doc_section(self, doc_line: str, context: DocContext, node: ast.FunctionDef) -> None:
if context.current_section == DocSection.DESCRIPTION:
if len(doc_line.strip()) > 1:
context.found_description = True
elif context.current_section == DocSection.ARGUMENTS:
... |
def _check_doc_args(self, doc_line: str, context: DocContext, node: ast.FunctionDef) -> bool:
match = self.ARGS_REGEX.match(doc_line)
if match:
if context.found_args:
self.add_problem(node=node, code="BCS012", arguments=node.name)
return False
if c... | This function validates a docstring line against a function's parameters, return values, and miscellaneous elements. If no specific check applies, it proceeds to validate the docstring section structure, ensuring compliance with documentation standards for the given Python function. | def _check_doc_line(self, doc_line: str, context: DocContext, node: ast.FunctionDef) -> None:
if self._check_doc_args(doc_line, context, node):
return
if self._check_doc_return(doc_line, context, node):
return
if self._check_doc_misc(doc_line, context, node):
... |
def _get_first_doc(node: ast.FunctionDef):
for body_node in node.body:
if isinstance(body_node, ast.Expr) and isinstance(body_node.value, ast.Str):
return body_node.value
return None
def _function_requires_documentation(node: ast.FunctionDef) -> bool:
if node.name.startswith("_"):
... | This function checks if a function has required documentation. If missing and required, it reports an error. Otherwise, it analyzes each line of the docstring using a context object to verify compliance with documentation standards, ensuring proper structure and content. | def _check_documentation(self, node: ast.FunctionDef) -> None:
doc = _get_first_doc(node)
if doc is None:
if _function_requires_documentation(node):
self.add_problem(node=node, code="BCS003", arguments=node.name)
return
doc_lines = doc.s.split("\n")
... |
def inst(a,b=True):
return isinstance(a,b)
def __assert_sample__(sample,data):
_ai_(sample,dict)
_ai_(data,dict)
if not sample or not data:
return False
for n in data:
if dict_has(sample,n):
if not inst(sample[n],type(data[n])):
raise Exception("Invalid [d... | The function retrieves data by ID via an API. It validates input structure, constructs an API endpoint using the ID from data, and performs a simple GET request with authentication. | def __get_by_id__(auth,api,data):
inst(data,dict)
sample={"id":""}
__assert_sample__(sample,data)
api = api.format(data['id'])
return __simple_get__(auth,api,data) |
def inst(a,b=True):
return isinstance(a,b)
def __assert_sample__(sample,data):
_ai_(sample,dict)
_ai_(data,dict)
if not sample or not data:
return False
for n in data:
if dict_has(sample,n):
if not inst(sample[n],type(data[n])):
raise Exception("Invalid [d... | The function `__get_retoot__` validates input data structure, constructs an API endpoint using the provided ID, and retrieves data via a GET request. It ensures `data` is a dictionary with required fields, formats the API URL, then calls `__simple_get__` to fetch results. | def __get_retoot__(auth,api,data):
inst(data,dict)
sample={"id":"","limit":0}
__assert_sample__(sample,data)
api = api.format(data['id'])
return __simple_get__(auth,api,data) |
def inst(a,b=True):
return isinstance(a,b)
def __assert_sample__(sample,data):
_ai_(sample,dict)
_ai_(data,dict)
if not sample or not data:
return False
for n in data:
if dict_has(sample,n):
if not inst(sample[n],type(data[n])):
raise Exception("Invalid [d... | The main task of the code is to fetch user following data by constructing an API endpoint with a user ID from the input dictionary, validating the data structure, and making a GET request using the formatted URL. | def __user_following__(auth,api,data={}):
inst(data,dict)
sample={"id":""}
__assert_sample__(sample,data)
api = api.format(data['id'])
return __simple_get__(auth,api,data) |
def inst(a,b=True):
return isinstance(a,b)
def __assert_sample__(sample,data):
_ai_(sample,dict)
_ai_(data,dict)
if not sample or not data:
return False
for n in data:
if dict_has(sample,n):
if not inst(sample[n],type(data[n])):
raise Exception("Invalid [d... | This function performs a POST request to an API endpoint using an ID from the input data. It first validates that the data contains an 'id' field, formats the API URL with this ID, and then executes a POST request with the provided authentication, formatted URL, and data. | def __post_by_id__(auth,api,data):
inst(data,dict)
sample={"id":""}
__assert_sample__(sample,data)
api = api.format(data['id'])
return __simple_post__(auth,api,data) |
def inst(a,b=True):
return isinstance(a,b)
def __assert_sample__(sample,data):
_ai_(sample,dict)
_ai_(data,dict)
if not sample or not data:
return False
for n in data:
if dict_has(sample,n):
if not inst(sample[n],type(data[n])):
raise Exception("Invalid [d... | The function `__notif_dismiss__` validates input data structure and sends a POST request to dismiss a notification. It ensures `data` is a dictionary, checks for required fields using `__assert_sample__`, then executes a POST call via `__simple_post__` with authentication, API endpoint, and validated data. | def __notif_dismiss__(auth,api,data={}):
inst(data,dict)
sample={"id":""}
__assert_sample__(sample,data)
return __simple_post__(auth,api,data) |
def sign(x: float) -> Literal[-1, 0, 1]:
"""
Returns the sign of x.
If x > 0, then return +1.
If x < 0, then return -1.
Otherwise return 0.
"""
if x > 0:
return 1
elif x < 0:
return -1
else:
return 0
def mean(x: float, y: float, /, order: float = 1) -> float:... | The code computes a root of a function `f` between two points `x1` and `x2` where `f(x1)` and `f(x2)` have opposite signs. It employs bracketing methods (e.g., Chandrupatla Mixed) to iteratively narrow the interval, adjusting tolerances for convergence. The solver handles edge cases like infinite bounds, NaN values, an... | def solver(
f: Callable[[float], float],
x1: float,
x2: float,
/,
*args: Any,
y1: float = nan,
y2: float = nan,
x: float = nan,
method: Union[str, BracketingMethod] = chandrupatla_mixed,
x_err: float = 0.0,
r_err: float = 4096 * epsilon,
x_tol: float = nan,
r_tol: flo... |
def sign(x: float) -> Literal[-1, 0, 1]:
"""
Returns the sign of x.
If x > 0, then return +1.
If x < 0, then return -1.
Otherwise return 0.
"""
if x > 0:
return 1
elif x < 0:
return -1
else:
return 0
def mean(x: float, y: float, /, order: float = 1) -> float:... | The code implements a **root-finding algorithm** using adaptive bracketing methods (e.g., bisection, secant, Illinois) to locate a root of a function $ f(x) $ within a given interval $[x_1, x_2]$. It dynamically switches between arithmetic/geometric means and bracketing strategies based on convergence criteria, error t... | def solver_simple(
f: Callable[[float], float],
x1: float,
x2: float,
/,
*args: Any,
y1: float = nan,
y2: float = nan,
x: float = nan,
method: Union[str, BracketingMethod] = chandrupatla_mixed,
x_err: float = 0.0,
r_err: float = 4096 * epsilon,
mean: Callable[[float, floa... |
def sign(x: float) -> Literal[-1, 0, 1]:
"""
Returns the sign of x.
If x > 0, then return +1.
If x < 0, then return -1.
Otherwise return 0.
"""
if x > 0:
return 1
elif x < 0:
return -1
else:
return 0
def mean(x: float, y: float, /, order: float = 1) -> float:... | The code implements a root-finding algorithm using bracketing methods (e.g., Chandrupatla's method) to iteratively approximate the root of a function `f(x)` within an interval `[x1, x2]`. It generates and yields successive estimates of the root, dynamically adjusting strategies (bisection, secant, Illinois) based on co... | def solver_generator(
f: Callable[[float], float],
x1: float,
x2: float,
*args: Any,
y1: float = nan,
y2: float = nan,
x: float = nan,
method: Union[str, BracketingMethod] = chandrupatla_mixed,
x_err: float = 0.0,
r_err: float = 4096 * epsilon,
x_tol: float = nan,
r_tol: ... |
def speak(audio):
printo(audio+"\n")
engine.say(audio)
engine.runAndWait()
def printo(shan):
global comtext
comtext.set(shan)
def wishMe():
hour = int(dt.datetime.now().hour)
if hour>=0 and hour<12:
speak("Good Morning! " +name)
elif hour>=12 and hour<18:
speak("Goo... | This function captures voice input from the microphone, uses Google's speech recognition API to convert it to text, and returns the recognized name as a string. If recognition fails, it handles exceptions by prompting the user to repeat their name. | def Name():
#It takes microphone input from the user and returns string output
global r,source,audio,query,name
name=" "
r = sr.Recognizer()
with sr.Microphone() as source:
speak("What is your name")
printo("Please tell me Your name\n")
printo("Listening...\n")
r.paus... |
def Commands():
global r,source,audio,query,usertext
r = sr.Recognizer()
r.energy_threshold=2500
with sr.Microphone() as source:
printo("Listening...\n")
r.pause_threshold = 1
audio = r.listen(source)
try:
printo("Recognizing...\n")
query = r.recognize_google... | The main task of the code is to execute tasks based on voice commands, such as searching on Google/Youtube/Wikipedia, opening websites/apps, playing media, sending emails, and handling user queries. It uses conditionals to trigger specific functions, interact with APIs, and manage system operations like shutdown or fil... | def reco():
query = Commands().lower()
print(query)
# Logic for executing tasks based on query
#if the user wants to search something on google
if 'search google' in query:
srch_google()
#if the user wants to search something on youtube
elif 'search youtube' in query:
... |
def _post_to_graph(self):
request_body = {'value': self.indicators_to_be_sent}
response = requests.post(GRAPH_BULK_POST_URL, headers=self.headers, json=request_body).json()
self.indicators_to_be_sent = []
self._log_post(response)
def _post_one_to_graph(self):
for indicator in sel... | This code handles post-processing tasks when exiting a context. It updates graph data (bulk or single), cleans up obsolete indicators, updates expiration dates and indicator hashes in files, prints a summary, reads Tiindicators data, and logs results to a timestamped JSON file. | def __exit__(self, exc_type, exc_val, exc_tb):
if config.targetProduct in TARGET_PRODUCT_BULK_SUPPORT:
self._post_to_graph()
else:
self._post_one_to_graph()
self._del_indicators_no_longer_exist()
self._find_indicators()
self.expiration_date_fd.seek(0)
... |
def _update_headers_if_expired(self):
if self._get_timestamp() > self.headers_expiration_time:
access_token = self._get_access_token(
config.graph_auth[TENANT],
config.graph_auth[CLIENT_ID],
config.graph_auth[CLIENT_SECRET])
self.headers = ... | This code processes an indicator by updating its expiration date, generating a hash, managing tracking lists, and batching indicators for bulk posting to a graph when the count reaches 100, with conditional handling based on the target product. | def handle_indicator(self, indicator):
self._update_headers_if_expired()
indicator[EXPIRATION_DATE_TIME] = self.expiration_date
indicator_hash = self._get_request_hash(indicator)
indicator[INDICATOR_REQUEST_HASH] = indicator_hash
self.hash_of_indicators_to_delete.pop(indicator_ha... |
def gen_cycle_chains(slow, medi, fast, plugboard_pairs, ring_setting, initial_position):
list_of_cycles, found_letters = initialize_list_of_cycles_and_found_letters()
for i in range(26):
this_char = enigma(slow, medi, fast, plugboard_pairs, ring_setting, initial_position)(int2ltr(i))[-1]
if foun... | The function `compute_signature` generates cryptographic cycles from input parameters (slow, medi, fast, plugboard_pairs, ring_setting, initial_position), combines them into chains, converts these chains into length values, sorts them, and returns the sorted lengths as a tuple. It processes permutation cycles typical i... | def compute_signature(slow, medi, fast, plugboard_pairs, ring_setting, initial_position):
list_of_cycles = gen_cycle_chains(slow, medi, fast, plugboard_pairs, ring_setting, initial_position)
cycles_list = combine_chains(list_of_cycles)
lengths_list = convert_to_lengths(cycles_list)
return tuple(merge_so... |
def freq(r):
char_count = 0
freq_dic = {'a' : 0, 'b' : 0, 'c' : 0, 'd' : 0, 'e' : 0,
'f' : 0, 'g' : 0, 'h' : 0, 'i' : 0, 'j' : 0,
'k' : 0, 'l' : 0, 'm' : 0, 'n' : 0, 'o' : 0,
'p' : 0, 'q' : 0, 'r' : 0, 's' : 0, 't' : 0,
'u' : 0, 'v' : 0, 'w' : 0... | The main task of the code is to decrypt Caesar and Vigenère ciphers using frequency analysis. It reads a reference text (Shakespeare) to determine character frequencies, then applies `breakCaesar` and `breakVigenere` to decrypt ciphertexts from `caesar.txt` and `vigenere.txt`, respectively. The decrypted results are wr... | def main():
with open('shakespeare.txt', 'r') as r:
reference_text = freq(r.read().lower())
with open('caesar.txt', 'r') as c:
ciphertext = c.read().lower()
with open('vigenere.txt', 'r') as v:
ciphertextv = v.read().lower()
with open('caeser_decipher.txt', 'w') as cd:
... |
def freq(r):
char_count = 0
freq_dic = {'a' : 0, 'b' : 0, 'c' : 0, 'd' : 0, 'e' : 0,
'f' : 0, 'g' : 0, 'h' : 0, 'i' : 0, 'j' : 0,
'k' : 0, 'l' : 0, 'm' : 0, 'n' : 0, 'o' : 0,
'p' : 0, 'q' : 0, 'r' : 0, 's' : 0, 't' : 0,
'u' : 0, 'v' : 0, 'w' : 0... | The main task of the code is to break a Vigenère cipher using frequency analysis. It reads a reference text (Shakespeare) to compute character frequencies, determines the key length from the cipher text, decrypts the cipher using the key derived from frequency analysis, and writes the decrypted result to a file. | def main():
with open('shakespeare.txt', 'r') as f:
reference_text = freq(f.read().lower())
with open('vigenere.txt', 'r') as f:
cipher_text = "".join(line for line in f)
length = vigenere_key_length(cipher_text)
key = breakVigenere(cipher_text, reference_text, length)
with open('... |
def gen_configs():
# generate all possible permutations of three out of five rotors
# generate all possible starting positions
rotor_permutations, starting_positions = gen_rotor_perms(), gen_starting_positions()
return rotor_permutations, starting_positions
def compute_sigs_for_configs(rotor_permutation... | The main task of the code is to generate all possible Enigma machine configurations, compute their cryptographic signatures, and store the mapping from signatures to configurations in a file for later lookup. This involves generating rotor permutations and starting positions, calculating corresponding signatures, and p... | def sig_to_config_dictionary():
# generate every possible configuration
rotor_permutations, starting_positions = gen_configs()
# compute the signature for every possible configuration
sig_to_config_dict = compute_sigs_for_configs(rotor_permutations, starting_positions)
# write to file
write_to_s... |
def fin():
send_packet("/quit")
client_socket.close()
exit(0)
def unwrap_packet(packet):
data = list(json.loads(packet))
if data[2] and use_encryption:
data[1] = bytes(data[1], 'utf-8')
print(type(data[1]), data[1])
decrypted = obfuscator.decrypt(data[1]).decode('utf-8')
... | This function handles incoming messages from a client socket by continuously monitoring for data. It reads message length and content, formats the message, updates a GUI list, and triggers LCD and desktop notifications for messages from other users. Error handling ensures robustness during data reception. | def message_handler():
while True:
to_read, to_write, error = select.select([client_socket], [], [])
for s in to_read:
try:
try:
length = int(s.recv(HEADERSIZE))
except Exception as e:
print(e)
fi... |
def parse(mystr):
retstr = []
for s in mystr:
if s == '.':
popped=retstr.pop()
retstr.append(popped-12)
elif s == "'":
popped=retstr.pop()
retstr.append(popped+12)
elif s==' ' or s==';':
continue
#retstr.append(swar_... | The code reads lines from a file, appends dynamic dash patterns, parses each line, composes them into a structured list using a specified parameter (8), and prints the transformed output. The main tasks involve file input, string parsing, composition logic, and formatted output generation. | def alap_main():
#read from file
strs = []
with open('bhairav.txt') as f:
strs = f.read().splitlines()
for l in range(1,length):
strs.append(['-']*l)
parsed_strs = []
for mystr in strs:
parsed_strs.append(parse(mystr))
#print(*parsed_strs, sep="\n"... |
def load_source_dr2(self):
#Load the lc assuming a DR2 style dataframe
cols = ['mjd', 'filter', 'flux', 'flux_err', 'ZP', 'flag', 'mag', 'mag_err', 'field_id', 'rcid', 'flux_offset', 'err_scale']
try:
self.lc = pd.read_csv(self.loc, usecols = cols, comment='#', delim_whitespace=True)
except: #In case somethi... | This code initializes an object by unpacking input arguments, determining a naming scheme based on the 'mode' parameter, setting up attributes like location, reference magnitudes, and save paths, and loading light curve data using mode-specific methods. It creates a directory for outputs, initializes data storage struc... | def __init__(self, args):
#Unpack args into easier to use names
self.mode = args [7]
#Naming scheme is chosen based on mode, if not recognised go with the default option
if self.mode == 'ZTFDR2':
self.name = args[0].name.rsplit('_L',1)[0]
if (('ZTF' not in self.name) & ('ztf' not in self.name)):
self.... |
def preprocess_tiles(tiles):
""" for each image in the folder this function returns a tuple of the average (R, G, B) """
return [average(tile) for tile in tiles]
def get_piece(image, upper_left, size):
""" ARGS:
image = The picture which the piece taken from(list of lists(of tuples)),
upper_left = p... | The code converts an input image into a mosaic by replacing each tile-sized section with the best-matching tile from a candidate list. It preprocesses tiles to calculate color averages, iterates through the image in tile-sized steps, identifies candidate tiles for each section, and replaces the image segment with the m... | def make_mosaic(image, tiles, num_candidates):
"""
Turns an image to a mosaic image.
Args:
image: The image that becomes a mosaic (as list of lists).
tiles: List of tiles (as list of lists).
num_candidates(int): The desired number of tiles in the list of candidates.
... |
def process_metadata():
logger.info('Log: %s', 'Processing Metadata', extra=default|{'function': 'process_metadata'})
# dict with all labels.json normalized to source format 1 with filename as key and processed image and label data as values
metadata = {}
sources = glob.glob("./sources/input_images_sour... | The code processes image metadata and associated images by analyzing label statistics (area percentage, aspect ratios), modifying images (cropping labels, padding to uniform size), saving processed images, and applying a sliding window. It also tracks execution time. | def main():
initial_time = datetime.datetime.now()
config_file_path = "./config.json"
# 1. Process metadata file
metadata = process_metadata()
# Operations on the metadata following parsing:
# Calculate percentage of the total area of the image occupied by labels.
label_perc(metadata)
... |
def is_in_turn(self):
return abs(self.get_turn_angle()) >= self.ANGLE_IS_CURVE
def get_turn_angle(self):
current_waypoint = self.closest_waypoints[0]
angle_ahead = self.get_heading_between_waypoints(self.get_way_point(current_waypoint),
se... | This function determines if an object is within a dynamically adjusted lateral corridor relative to the track centerline. It checks current/expected turn direction, then validates position (left/right of center) and distance thresholds to ensure safe lateral positioning during turns or straight paths. | def is_in_optimized_corridor(self):
if self.is_in_turn():
turn_angle = self.get_turn_angle()
if turn_angle > 0: # Turning LEFT - better be by left side
return (self.is_left_of_center == True and self.distance_from_center <= (
self.CENTERLINE_FOLLO... |
def init_self(self, params):
self.all_wheels_on_track = params['all_wheels_on_track']
self.x = params['x']
self.y = params['y']
self.distance_from_center = params['distance_from_center']
self.is_left_of_center = params['is_left_of_center']
self.is_reversed = params['is_re... | The main task of the code is to calculate a reward value for an autonomous car's performance in a track, penalizing undesirable behaviors (e.g., off-track, reversed, low speed) and rewarding optimal behaviors such as smooth steering, ideal speed, staying in an optimized corridor, and reaching targets. The reward is cap... | def evaluate(self):
self.init_self(self.params)
result_reward = float(0.001)
try:
# No reward => Fatal behaviour, NOREWARD! (out of track, reversed, sleeping)
if self.all_wheels_on_track == False or self.is_reversed == True or (self.speed < (0.1 * self.MAX_SPEED)):
... |
def welcome_menu(self, error=False):
error_text = 'Invalid Selection\n' if error else ''
message = '{}\nWelcome To Chekkit\n\n1.Verify Product\n2.Exit'.format(error_text)
return self.process_response(message=message, response_type=RESPONSE, client_state=VERIFY_PRODUCT_MENU)
def verify_product_me... | The code processes user requests by routing to specific methods based on `response_type` and `stage`. If `response_type` is `INITIATION`, it returns a welcome menu. For `RESPONSE`, it directs to verification, complaint, or location entry steps depending on the `stage`, ensuring appropriate user interaction handling. | def process_request(self):
if self.response_type == INITIATION:
return self.welcome_menu()
elif self.response_type == RESPONSE:
if self.stage == VERIFY_PRODUCT_MENU:
return self.verify_product_menu()
elif self.stage == VERIFY_PRODUCT:
... |
def get_stations():
engine = get_db()
stations = []
rows = engine.execute("SELECT * from static")
for row in rows:
stations.append(dict(row))
for station in stations:
station["title"], station["id"] = station["address"], station["address"]
station['coords'] = {'lat': stati... | The main task of the code is to retrieve station data, hourly/dayly mean values, weather information, and recent bike occupancy data, then render them into an HTML template for dynamic web display, integrating multiple data sources with a map API key for visualization. | def root():
stations = get_stations()
hour_means = get_hour_means()
day_means = get_day_means()
weather = get_weather()
recentbike = bike_occupancy()
return render_template('index.html', static_data=stations, hour_means=hour_means, day_means=day_means, recentWeather = weather, recentbike=recentb... |
def get_soup(url):
page = req.get(url)
soup = BeautifulSoup(page.content, features="lxml")
return soup
def grab_name(soup):
name = soup.find('h1').text
return name
def grab_images(soup, unique_name, config, how):
large_folder = config['large_images']
small_folder = config['small_images']
... | The function `grab_card` parses HTML content to extract structured card data, determining the source method (`refresh` or `regular`) to retrieve or read HTML. It populates a dictionary with card attributes like name, image, stats, effects, rewards, and metadata using helper functions, adapting to different HTML structu... | def grab_card(source, config, card_type='debug', how='regular'):
if how == 'refresh':
unique_name = source.split('.')[0]
with open(os.path.join(config['html_catalog'], card_type, f"{unique_name}.html"), 'r', encoding='utf8') as file:
html = file.read()
soup = BeautifulSoup(ht... |
def pull_pages(first_url):
pages = [first_url]
wait()
page_soup = get_soup(first_url)
bites = page_soup.find_all('a', {'class': 'page-numbers'})
pages = pages + [x.get('href') for x in bites]
return pages
def wait():
wait_time = uniform(2, 4)
sleep(wait_time)
def get_soup(url):
page ... | The main task of the code is to scrape card data from specified URLs, check if they exist in a MongoDB collection, and either update existing entries or insert new ones based on the 'how' parameter. It processes multiple card types, extracts URLs from paginated content, and handles both partial and full data updates by... | def dig(config, how='partial'):
collection = config['db']['cards']
for card_type, url in type_urls.items():
print(f'-----Getting all of the {card_type.title()}s-----')
page_list = pull_pages(url)
card_urls = []
for page in page_list:
wait()
page_soup = get... |
def __get_ages(self):
"""Return the age of each image"""
return np.vectorize(lambda x: re.search("(\d+)_\d_\d_\d+\.jpg.*",x))(self.files)
def __get_images_data(self,ages):
"""Create images_data, images name and age cleaned from None values and converted to int"""
# Combina images name a... | The main task of the code is to create a dataset by combining image data with ages, then generating image combinations based on a year difference and duplicate probability. If `unique_images` is True, it produces unique combinations; otherwise, it generates standard combinations. The function first retrieves ages, maps... | def __create_dataset(self,year_diff:int,duplicate_probability:float,unique_images:bool):
#Get ages for all images
ages=self.__get_ages()
# Combina images name and age
self.__get_images_data(ages)
if unique_images:
self.__get_unique_images_combinations(year_diff,dupl... |
def get_movies(self, tmdbId = None):
return self.get('/movie', tmdbId = tmdbId)
def get_queue(self, pageSize = DEFAULT_PAGE_SIZE, sortDirection = DEFAULT_SORT_DIRECTION, sortKey = DEFAULT_QUEUE_SORT_KEY, includeUnknownMovieItems = DEFAULT_INCLUDE_UNKNOWN_MOVIE_ITEMS):
return self.get_paginated_results('... | The function identifies monitored, released movies without files that aren't in the queue, then triggers a search for these "missing" movies by sending their IDs to a command endpoint, printing their titles for tracking. | def search_for_missing_movies(self):
#self.post('/command', {'name': 'MissingMoviesSearch'})
movies = self.get_movies()
queue = list(map(lambda x: x['movieId'], self.get_queue(includeUnknownMovieItems = False)))
missing = []
for movie in movies:
if movie['monitored'] ... |
def get_queue(self, pageSize = DEFAULT_PAGE_SIZE, sortDirection = DEFAULT_SORT_DIRECTION, sortKey = DEFAULT_QUEUE_SORT_KEY, includeUnknownMovieItems = DEFAULT_INCLUDE_UNKNOWN_MOVIE_ITEMS):
return self.get_paginated_results('/queue', pageSize = pageSize, sortDirection = sortDirection, sortKey = sortKey, includeU... | The main task of the code is to remove deleted movies from a queue by filtering out items without a 'movieId' key, extracting their IDs, and deleting them individually or in bulk based on the number of remaining items. | def remove_deleted_movies_from_queue(self):
queue = self.get_queue(includeUnknownMovieItems=True)
queue = list(filter(lambda x: 'movieId' not in x, queue))
queue = list(map(lambda x: x['id'], queue))
if len(queue) == 1:
self.remove_from_queue(queue[0])
elif len(queue)... |
def printBoard(board):
for i in range(len(board)):
print(board[i])
def isCellEmpty(board, i, j):
return (board[i][j] == "")
def check_winner(board, mark):
for i in range(len(board)):
if(board[i][0] == board[i][1] == board[i][2] == mark):
return True
if(board[0][i] == boar... | The code implements a turn-based Tic-Tac-Toe game where a human player competes against an AI. The human inputs row/column coordinates to place their mark, while the AI uses `findBestMove` to select its move. After each move, the board is updated and checked for a win or draw. The game ends when a player wins or the bo... | def main():
board = [["", "", ""], ["", "", ""], ["", "", ""]]
printBoard(board)
while(True):
print("Enter the position where you want to place your mark")
x = int(input("Enter the row: "))
y = int(input("Enter the column: "))
if(isCellEmpty(board, x, y)):
board[x... |
def print_board(board):
for row in board:
print(' | '.join(row))
print('---------')
def game_over(board):
return not any(EMPTY in row for row in board)
def evaluate(board):
# Check rows, columns, and diagonals for winning conditions
for row in board:
if all([cell == row[0] for ce... | This code implements a Tic-Tac-Toe game where a player competes against a computer. It initializes a 3x3 board, alternates between player and computer moves, validates inputs, updates the board with 'X' (player) and 'O' (computer), checks for game over conditions, and declares the result (win/draw) when the game ends. | def play_game():
board = [[EMPTY] * 3 for _ in range(3)]
while True:
print_board(board)
if game_over(board):
result = evaluate(board)
if result == 'draw':
print("It's a draw!")
else:
print(f"{result} wins!")
break
... |
def _NamedTempFile(contents):
"""Write a named temporary with given contents.
Args:
contents: (str) File contents.
Yields:
The temporary file object.
"""
if os.name == 'nt':
with WindowsNamedTempFile(mode='w+t') as f:
f.write(contents)
f.close()
yield f
else:
with tempfil... | The main task of the code is to deploy a Kubernetes application using Skaffold by generating local runtime files, creating temporary configuration files for Kubernetes and Skaffold, setting up the Kubernetes context and namespace, and executing Skaffold with specified parameters to ensure deployment completion. | def Run(self, args):
settings = local.Settings.FromArgs(args)
local_file_generator = local_files.LocalRuntimeFiles(settings)
kubernetes_config = six.ensure_text(local_file_generator.KubernetesConfig())
with _NamedTempFile(kubernetes_config) as kubernetes_file:
skaffold_config = six.ensure_text(
... |
def tokenize(s):
arr = []
stringTokenizer = s.split()
for i in stringTokenizer:
arr.append(i)
return arr
def concatEx(input, excluded):
s = ""
arr = tokenize(input)
for s1 in arr:
if s1 != excluded:
s += s1 + " "
return s
def buildScenario(arr):
return Sce... | The function parses feature files to extract the feature name, description, and scenarios. It skips lines starting with "Given," "When," or "Then," identifies the feature name from "Feature:" lines, collects descriptions between feature and scenario headers, and builds scenarios from "Scenario:" lines. It returns a Fea... | def buildFeature(lines):
featureName = ""
description = ""
isDescription = False
scenarios = []
tokens = []
for line in lines:
if len(line) == 0 or line.isspace():
continue
tokens = tokenize(line)
if tokens[0] == "Given" or tokens[0] == "Wh... |
def _process_incoming(self):
logger.debug("Processing incoming message from server")
msg = self._recv()
if msg.MSGID == ReqRem.MSGID:
removed_equipid = msg.originid
self._other_equipids.remove(removed_equipid)
logger.debug("Removed equipment id {}".format(rem... | The code runs an Industry 5.0 client that continuously monitors a socket for incoming data, processes it, and listens for commands via stdin. It parses and executes received commands, terminating when a completion signal is received. Error handling logs critical issues and ensures the socket is closed safely. | def run(self):
try:
logger.info("Running industry 5.0 client")
command_str = ""
while True:
incoming = select.select([self._sock], [], [],
self._SELECT_TIMEOUT)
if incoming[0]:
self.... |
def generate_contours(img: Image):
"""Given a PIL image object generate contour lines.
Function will generate contours based on vertical and horizontal table
lines.
Args:
img: PIL image object
"""
img_vh = generate_vh_lines(img)
contours, _ = cv2.findContours(
img_vh,
... | The main task of the code is to extract data from table structures in an image. It processes the input PIL image by generating contours, parsing table boundaries (outer/inner rectangles), classifying contour groups, and extracting data from each classified group using `extract_set`. The function combines contour analys... | def get_data(img: Image):
"""Given an image get all data from table structures.
This functions combines multiple methods to parse an image, determine its
table structure and extract all data from said tables.
Args:
img: PIL image object
"""
contours = generate_contours(img)
outer_... |
def find_multiple(grade_level):
multiple_course, teacher_name = get_course_id_special(grade_level, 1)
availability = multiple_course_info(teacher_name)
return [multiple_course, availability]
def find_double(grade_level):
double_course, teacher_name = get_course_id_special(grade_level, 2)
if not len(... | This code initializes an object to manage course sections and periods, setting attributes like course key, grade level, section count, and period count. It calculates multipliers based on grade level, initializes a section matrix, and updates course scheduling data (hcs) for educational planning or resource allocation. | def __init__(self, num_of_sections, num_of_period,
grade_level, course_key):
self.course_key = (
course_key # to access course_info database
)
self.grade_level = grade_level
self.num_of_sections = num_of_sections
self.num_of_period = num_of_period
... |
def get_data(self):
X, y = generate_data(self.type_of_generated_data, self.number_of_samples, self.number_of_classes)
Y = []
for idx in y:
row = np.zeros(self.number_of_classes)
row[idx] = 1
Y.append(row)
return X, Y, y
def learning_rate_slider_callbac... | The main task of the code is to initialize a GUI application for a neural network training interface using TensorFlow and Tkinter. It sets up parameters for the neural network, generates synthetic data, creates interactive sliders and controls to adjust hyperparameters (learning rate, regularization, etc.), and display... | def init_window(self):
# initialization
self.learning_rate = 0.1
self.regularization_rate = 0.01
self.epochs = 10
self.epochs_count = 1
self.batch_size = 100
self.input_dimension = 2
self.number_of_nodes_in_first_hidden_layer = 100
self.number_of_c... |
def predict(self, input_vector):
output_vector = np.dot(self.weights, input_vector)
output_vector = self.select_transfer_function(output_vector)
return output_vector
def select_learning_rule(self, input_vector, a, t):
if self.learning_rule == "Filtered Learning":
self.weights... | The main task of the code is to train a neural network model over 100 epochs using a specified learning rule. It iteratively updates weights based on predicted outputs and one-hot encoded targets, plots accuracy after each epoch, computes a confusion matrix, and calculates final accuracy from test data. The training pr... | def train(self):
print("Training started")
input_vectors = self.X_train
targets = self.Y_train
for j in range(100):
for i in range(len(targets)):
a = self.predict(input_vectors[i])
# self.delta_rule(input_vectors[i], a, targets[i])
... |
def geojson2shp(self, input_file, output_file):
directory = os.path.dirname(output_file)+"\\temp_jvmapgen_ignore\\"
unique_id = str(uuid.uuid4())
input_file_temp = directory+"output_"+unique_id+".shp"
input_file_temp_noext = "output_"+unique_id
if not os.path.exists(directory):
... | The code converts a shapefile or GeoJSON to an SVG map, using specified fields for IDs and names. It calculates SVG dimensions, processes geometry data, generates SVG content, converts it to JVM format, saves the output, and cleans up temporary files. | def run(self, in_file, out_path, id_name, name_name, width_pixel):
if(width_pixel > 0):
self.width_pixels = width_pixel
if(self.sourceformat == "geojson"):
layer, directory, input_file_temp_noext = self.geojson2shp(in_file,out_path)
else :
layer = shapefile.Re... |
def get_uuid():
return str(uuid.uuid4())
def getDataEntity(self, opKey):
sconnection = None
sschema = None
sentity = None
sentityType = None
dataFormat = None
createNewEntity = False
for i in self.operatorProperties:
if (i.name == "connection"):
... | The function creates a Source object with dynamic configuration. It generates a UUID, sets schema drift rules based on operator properties (allowing or disallowing schema changes), retrieves data entity and default configs, and initializes a Source with specified ports, data format, and schema drift settings. | def create_source(self, name, identifier, input_ports, output_ports):
key = get_uuid()
dataFormat = None
sdc = SchemaDriftConfig(missing_column_handling=SchemaDriftConfig.MISSING_COLUMN_HANDLING_ALLOW,
extra_column_handling=SchemaDriftConfig.EXTRA_COLUMN_HANDLING_... |
def get_uuid():
return str(uuid.uuid4())
def getDataEntity(self, opKey):
sconnection = None
sschema = None
sentity = None
sentityType = None
dataFormat = None
createNewEntity = False
for i in self.operatorProperties:
if (i.name == "connection"):
... | The code creates a target configuration for data processing by generating a unique identifier, applying operator properties (like data format and integration strategy), determining write mode (append/overwrite/merge), validating staging parameters, and constructing a `Target` object with these settings. It returns the ... | def create_target(self, name, identifier, input_ports, output_ports):
key = get_uuid()
dataFormat = None
is_predefined_shape = True
is_copy_fields = False
stagingDataAsset = None
stagingConnection = None
stagingBucket = None
writeMode = WriteOperationConfi... |
def read_file():
with open('elf-cleaning-sections.txt', 'r') as file:
return [line.strip() for line in file.read().split("\n")]
def check_if_double_up(pair):
elf_1_lo, elf_1_hi, elf_2_lo, elf_2_hi = get_elf_cleaning_sections(pair)
if elf_1_lo >= elf_2_lo and elf_1_hi <= elf_2_hi:
return Tru... | The code processes elf pairs to count two scenarios: (1) pairs where one elf's sections are entirely contained within the other's (double-ups), and (2) pairs with any overlapping sections. It reads input data, iterates through each pair, checks for these conditions using helper functions, and accumulates counts. The re... | def solutions():
"""
Check for elf pairs where one elf has been assigned sections that have all
been assigned to other elf.
Check for elf pairs with any overlap in assigned sections.
E.g.
2-4,6-8
2-3,4-5
5-7,7-9
2-8,3-7
6-6,4-6
2-6,4-8
"""
num_... |
def __get_the_best_cromozom(self: object) -> Cromosome:
return max(self.population, key=lambda c: c.fitness)
def __print_cromosomes_probabilities(self: object):
print('Selection probabilities:')
for c in self.population:
print(f'Probability for {c}: {self.__get_probability_for_cromoz... | The main task of the code is to select chromosomes from a population, starting with the best one, and then repeatedly adding other chromosomes until the selected list matches the population's size. It optionally prints probability distributions and selection intervals for transparency. The function returns the final li... | def select(self: object) -> list[Cromosome]:
selected = [self.__get_the_best_cromozom()]
if self.should_print:
self.__print_cromosomes_probabilities()
print()
self.__print_intervals()
print()
while len(selected) < len(self.population):
... |
def connection_cl(item):
global conn
msg1 = str(item)
conn.send(msg1.encode())
def disconnect():
global thread_num
conn.close()
thread_num -= 1
def play_game():
global conn
global board_game
# get a question from the list of questions
random.shuffle(questions) ... | The code initializes a game by asking three questions, evaluating answers to determine starting funds, letting the player choose a game stage with adjusted money, starting the game, and handling replay requests. It manages client interaction via a socket connection, adjusts game parameters based on answers, and loops f... | def begin_play(conn):
global board_game
# part 1 : answering 3 questions
n0 = 3 # num of questions
i = 0 # index for msg
answer = [] # array of the answers
correct = 0 # num of correct answers
while n0 > 0: # 3 first questions
msg = ['How many strings do a guitar have?', 'How ... |
def has_mine(self, cords):
return self.minefield[cords[0]][cords[1]]
def get_num_adj_mines(self, cords):
return self.adj_mines[cords[0]][cords[1]]
def reveal_square(self, cords):
self.hidden_squares.discard(cords)
self.flagged_squares_coordinates.discard(cords)
def reveal_empty_area(self... | This function processes a click on a Minesweeper grid. If the clicked square is hidden and contains a mine, it returns 0. Otherwise, it reveals the square if it has adjacent mines or triggers a chain reveal of connected empty squares with no adjacent mines, returning 1. The task is to handle player interactions, safely... | def click_spot(self, cords):
# We only do things if the square has not been revealed yet
if cords in self.hidden_squares:
# If we click on a mine, we just return 0, otherwise we return 1
if self.has_mine(cords):
return 0
# If there is at least one adja... |
def btf_open(self, symbol, price, volume, buy_sell, order_type = 'MKT', ex_type = 'exchange'):
try:
if order_type == 'LMT':
_type = 'exchange limit' if ex_type == 'exchange' else 'limit'
order_ref = self.btf.new_order(symbol, str(volume), str(price), buy_sell, _type)
elif order_type == 'MKT':
_type... | This function creates multiple buy/sell positions by opening CONSTRUCT_COUNTS orders with calculated amounts, logs each order's price and ID, computes the average price across all positions, updates a dataframe with position data, increments position counters, and disables overweight trading when max positions are reac... | def construct_order(self, side):
_amount = CONSTRUCT_AMOUNT/CONSTRUCT_COUNTS
_id = str(random.randint(1, 99999999))
_sum_price = 0
print('---------- Start open positions ----------')
for c in range(CONSTRUCT_COUNTS):
order_id = self.btf_open(MERCHANDISE, 1, _amount, side, O_TYPE, E_TYPE)
time.sleep(3)
... |
def btf_open(self, symbol, price, volume, buy_sell, order_type = 'MKT', ex_type = 'exchange'):
try:
if order_type == 'LMT':
_type = 'exchange limit' if ex_type == 'exchange' else 'limit'
order_ref = self.btf.new_order(symbol, str(volume), str(price), buy_sell, _type)
elif order_type == 'MKT':
_type... | The code closes multiple positions by placing opposite orders (buy/sell) in a loop, calculates the average price of these positions, records the details, and adjusts the corresponding long/short position count. It aims to liquidate a specified amount of ETH by distributing orders and logging the average execution price... | def covering_order(self, _id, side):
_amount = CONSTRUCT_AMOUNT/CONSTRUCT_COUNTS
_side = 'buy' if side == 'sell' else 'sell'
_sum_price = 0
print('---------- Start close positions ----------')
for c in range(CONSTRUCT_COUNTS):
order_id = self.btf_open(MERCHANDISE, 1, _amount, _side, O_TYPE, E_TYPE)
tim... |
def construct_order(self, side):
_amount = CONSTRUCT_AMOUNT/CONSTRUCT_COUNTS
_id = str(random.randint(1, 99999999))
_sum_price = 0
print('---------- Start open positions ----------')
for c in range(CONSTRUCT_COUNTS):
order_id = self.btf_open(MERCHANDISE, 1, _amount, side, O_TYPE, E_TYPE)
time.sleep(3)
... | This function implements a trailing stop strategy for long/short positions. It updates average price, calculates dynamic stop prices, and adjusts take-profit levels based on bid/ask prices. The code uses threading, locking, and state flags to monitor market movements, dynamically adjust trailing thresholds, and execute... | def trailing(self, side, flag):
id_tag, price = self.construct_order(side)
if side == 'buy':
self.avg_price = round((self.avg_price * (self.long_pos - 1) + price) / self.long_pos, 2)
self.stop_price = round(self.avg_price * (1 - self.stop_percent), 2)
# self.stop_percent = self.stop_percent - STOPLOSS_POIN... |
def Logs(msg):
print('[{}] {}'.format(dt.now().strftime('%F %T'), msg))
def reset_trading_para(self):
Logs('Reset trade status')
self.isMonitor = False
self.canTakeProfit = False
self.canOverweight = False
self.avg_price = 0
self.stop_price = 0
self.stop_percent = STOPLOSS
if self.trailFlag == TRAI... | This code monitors trading positions for stop loss and take profit conditions. It checks if current price crosses stop price (to trigger stop loss) or meets take profit thresholds (to close positions). When conditions are met, it logs actions, resets trading parameters, closes all positions, and updates dynamic take pr... | def monitoring(self):
while self.isMonitor:
cond1 = self.side == 'buy' and self.cur_price < self.stop_price
cond2 = self.side == 'sell' and self.cur_price > self.stop_price
if cond1 or cond2:
print('------------------------------------')
Logs('close all position by stop loss')
Logs('AP:{}, SP:{}... |
def Logs(msg):
print('[{}] {}'.format(dt.now().strftime('%F %T'), msg))
def reset_trading_para(self):
Logs('Reset trade status')
self.isMonitor = False
self.canTakeProfit = False
self.canOverweight = False
self.avg_price = 0
self.stop_price = 0
self.stop_percent = STOPLOSS
if self.trailFlag == TRAI... | The main task of the code is to close all trading positions when the initial signal changes. It checks if there are open long or short positions and if the first signal has switched to 'S' or 'B', respectively. If so, it logs the closure reason, resets trading parameters, closes all positions, and sets the trading side... | def condition_to_close(self):
cond1 = self.long_pos > 0 and (self.first_sig == 'S')
cond2 = self.short_pos > 0 and (self.first_sig == 'B')
if cond1:
Logs('close by signal change')
self.reset_trading_para()
self.close_all_pos()
self.side = 'none'
elif cond2:
Logs('close by signal change')
self... |
def update_signal(self, df):
self.ts.first_update(df)
self.first_sig = self.ts.first_sig
self.second_sig = self.ts.second_sig
def update_data(self):
self.cur_itv = pd.to_datetime(dt.strftime(self.cur_time, '%F %H'))
self.past_itv = self.marketdata.hour.tail(1).index[0]
self.marketdata.update('hour', self.cu... | The code fetches historical market data, converts it to hourly intervals, analyzes 81-hour windows to generate trading signals, and continuously updates real-time tick data to evaluate conditions for opening, closing, or adjusting positions in a trading strategy. | def run(self):
minute = self.algobank.Get_Market_his_tail(EXCHANGE, MERCHANDISE, 43200, 'min')
hour = self.marketdata.to_period(df = minute, interval = 1, unit = 'H')
self.marketdata.set_new_data('hour', hour)
for i in range(81, len(self.marketdata.hour)):
self.window_dat = self.marketdata.hour[(i-81):i]
... |
def create_remote_clients(self):
w_subject = self.get_token_subject("bootstrap", "system")
w_offset = 0
none = False
w_remote_local_id = self.get_remote_server_id()
while not none:
list_remote_server = self._manager_remote_server.get_many(
"remoteServe... | The main task of the code is to manage remote service components by creating necessary clients, analyzing service events, updating or removing components, and returning event results for further processing. | def ask_services(self):
# run create remote to create missing client
self.create_remote_clients()
# analyse move regarding service to delete some of them and create other
res = self.get_events_services()
self.raz_update_remote_component()
return res |
def connect(a_scheme, a_host, a_port):
try:
client = jsonrpclib.ServerProxy("{}://{}:{}".format(a_scheme, a_host, a_port))
client.test()
return client
except:
return None
def test_service(self):
try:
# self._client.test()
self._active = True
... | The main task of the code is to establish a connection to a service using the specified scheme, host, and port, then test the service's functionality and query its available services. This method validates the service's accessibility and operational status by initializing a client, performing a test, and retrieving ser... | def validate_ask_service(self):
self._client = connect(self._scheme, self._host, self._port)
self.test_service()
self.ask_services() |
def build_sr_gnn(self):
self.mask = tf.placeholder(dtype=tf.float32, shape=[None, None])
self.alias = tf.placeholder(dtype=tf.int32, shape=[None, None])
self.items = tf.placeholder(dtype=tf.int32, shape=[None, None])
self.targets = tf.placeholder(dtype=tf.int32, shape=[None])
sel... | This code initializes a neural network model for graph-based tasks, setting up parameters like hidden layers, embeddings, and learning rates. It creates an embedding matrix, selects a method ('ggnn' or 'ha') to build the model architecture, and configures a TensorFlow session with GPU options for training. The model in... | def __init__(self, hidden_size=100, emb_size=100, n_node=None, lr=None, l2=None,
step=1, decay=None, lr_dc=0.1, cide=0, g_node=None, n_sample=None,
dropout=0.3, method='ha', num_head=1, num_block=1, nonhybrid=False, max_len=19):
self.n_node = n_node
self.l2 = l2
... |
def save_pdf(link,csrfmiddlewaretoken,blur_img_1_path,blur_img_2_path,results,not_found_using_nlp_and_img=None):
pdf = FPDF()
pdf.add_page()
pdf.set_font("Arial","B",size=20)
pdf.rect(7,7,195,282,"D") # For Border
pdf.cell(195,20,'Analytics Report',align = 'C')
pdf.ln()
pdf.ln()
if ... | The main task of the code is to generate a report and PDF for child abuse detection analysis. It handles NLP-based or image-based results, blurs detected images, zips original images for secure storage, and saves the report with appropriate metadata. The function returns the generated PDF report, distinguishing between... | def generate_report(link,csrfmiddlewaretoken,results,is_nlp=None):
report = Report()
report.link = link
report.csrfmiddlewaretoken = csrfmiddlewaretoken
if is_nlp:
# this means it's nlp based generated report:
print("Report Generated by NLP")
report.img_1 = None
report.... |
def __adminAuthentication(self):
adminPin = input("Enter your Pin : ")
while not self.__adminPin(adminPin):
print("Incorrect pin input, try again.")
adminPin = input("Enter your Pin: ")
def __administratorMenu(self):
notExit = True
while no... | The main task of the code is to handle user choices in a main menu by authenticating admin or customer users and directing them to respective menus, or exiting the program. It uses a loop to process selections: choice 1 validates admin access, choice 2 validates customer access, and choice 3 exits with a farewell messa... | def __runMainMenu(self,choice):
notExit = True
while notExit:
if choice == 1:
if self.__adminAuthentication() == True: # Confirmation of Admin
self.__administratorMenu() # If confirmation is a success, it'll take the user to the ad... |
def wait_for_stable_state():
while not is_stable_state():
logging.info('State NOT OK, waiting...')
time.sleep(30)
logging.info('State OK')
def get_dependability_metrics(range_length):
logging.info(f'"range_length" is: {range_length}')
metrics = BackendMetrics()
metrics.availability... | The code runs a load test under chaos conditions by applying chaos via Helm, generating user traffic with Locust, collecting dependability metrics, and tracking job states, then returns the measurement results including metrics and job summaries. | def run_measurement(helm_command, locust_user_count, locust_spawn_rate, load_duration):
logging.info('Waiting for stable system state...')
wait_for_stable_state()
# Initialize measurement result
measurement_result = MeasurementResult()
# Setup Locust objects
# setup Environment and Runner
... |
def check_working_dir():
# Check if in right working dir
actual_working_dir = '/'.join(str(pathlib.Path.cwd()).split('/')[-2:])
expected_working_dir = 'kubedepend/kubedepend'
if (actual_working_dir != expected_working_dir):
raise RuntimeError(f'Working directory must be {expected_working_dir}')... | The main task of the code is to execute a series of measurements using Helm and Locust under specified fault profiles, iterating until predefined criteria (e.g., target standard deviation or measurement count limits) are met. It initializes parameters, validates the Helm chart, assembles deployment configurations, runs... | def main(nosave, fault_profile, min_measurement_count, max_measurement_count, target_std, load_duration, locust_user_count, locust_spawn_rate, cluster_type, comment):
click.echo('nosave=' + str(nosave))
click.echo('fault_profile=' + str(fault_profile))
click.echo('min_measurement_count=' + str(min_measureme... |
def cmdowHeader(raw: str) -> Dict[str,List[str]]:
"""Certain columns contain multiple words, which are separated by a space.
This function does three things:
1. It replaces the space with a hyphen in the column name.
2. It returns a list of the column names.
3. It returns a list of the column names ... | This function processes the raw output from cmdow's /p flag into a structured polars DataFrame. It splits input lines, extracts headers, creates a row pattern, processes data rows, and returns a DataFrame with cleaned columns and data. Debug flags enable intermediate output for troubleshooting. | def cmdowRawDF(raw: str, debug: Optional[bool] = False) -> pl.DataFrame:
"""
The raw DataFrame is the DataFrame that is created from the raw output
of cmdow's /p flag. It is not cleaned up or formatted in any way, except
for the removal of extra spaces and the addition of hypens to multi-word
column... |
def cmdowDF(raw: str, expr: Optional[str] = None, debug: Optional[bool] = False) -> pl.DataFrame:
"""cmdowDF is the main function for creating a DataFrame from the raw output of cmdow's /p flag.
Adds a way to filter the DataFrame by process name.
Args:
raw (str): the raw output of cmdow's /p flag
... | The function generates a DataFrame describing the layout of active windows on the screen, excluding maximized/non-active windows and optionally the taskbar, by filtering raw window data against screen dimensions and status indicators. | def cmdowLayout(
showtaskbar: Optional[bool] = False
) -> pl.DataFrame:
"""Returns a DataFrame with the layout of the currently active window.
Args:
showtaskbar (bool, optional): whether or not to include the taskbar in the output. Defaults to False.
Returns:
pl.DataFrame: the Data... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.