dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def initialize_pdf(PDF_PATH):
pytesseract.pytesseract.tesseract_cmd = TESSERACT_PATH
return pdfplumber.open(PDF_PATH)
def gather_all_font_data(PDF_PATH):
font_data = []
print("[INFO] Gathering font data from PDF...")
for page in extract_pages(PDF_PATH):
text_elements = [e for e in page if i... | The main task of the code is to process a PDF by extracting and structuring its textual content. It initializes the PDF, gathers font metadata, applies k-means clustering to categorize text sections, processes each page to identify headings, subheadings, and content, and structures the extracted data into a JSON file. ... | def main():
print("[INFO] Starting main execution...")
# Open the specified PDF file in binary mode
with open(PDF_PATH, "rb") as pdfFileObj:
# Initialize a PDF reader object to manipulate the PDF
pdfReader = PyPDF2.PdfReader(pdfFileObj)
print("[DEBUG] Initializing PDF...")
... |
def initialize_pdf(PDF_PATH):
pytesseract.pytesseract.tesseract_cmd = TESSERACT_PATH
return pdfplumber.open(PDF_PATH)
def gather_all_font_data(PDF_PATH):
font_data = []
print("[INFO] Gathering font data from PDF...")
for page in extract_pages(PDF_PATH):
text_elements = [e for e in page if i... | The main task of the code is to process a PDF document by analyzing font statistics, extracting and structuring page content, and saving structured data to JSON. It initializes the PDF, calculates font size metrics, processes each page to identify headings/content, cleans temporary files, and logs counts of headings, s... | def main():
print("[INFO] Starting main execution...")
with open(PDF_PATH, "rb") as pdfFileObj:
pdfReader = PyPDF2.PdfReader(pdfFileObj)
print("[DEBUG] Initializing PDF...")
pdf = initialize_pdf(PDF_PATH)
text_per_page = {}
print("[DEBUG] Gathering all font data...")
... |
def initialize_pdf(PDF_PATH):
pytesseract.pytesseract.tesseract_cmd = TESSERACT_PATH
return pdfplumber.open(PDF_PATH)
def gather_all_font_data(PDF_PATH):
font_data = []
print("[INFO] Gathering font data from PDF...")
for page in extract_pages(PDF_PATH):
text_elements = [e for e in page if i... | The code processes a PDF by extracting text and font data from each page, organizing the content into a structured dictionary, and saving the processed data to a JSON file. It also handles temporary files and logs execution steps for debugging and tracking progress. | def main():
print("[INFO] Starting main execution...")
with open(PDF_PATH, "rb") as pdfFileObj:
pdfReader = PyPDF2.PdfReader(pdfFileObj)
print("[DEBUG] Initializing PDF...")
pdf = initialize_pdf(PDF_PATH)
text_per_page = {}
print("[DEBUG] Gathering all font data...")
... |
def es_two_events(query, conditional_query, condition, time_limit, gps_bounds, return_extra_filter=False, share_info=False):
print("Share info:", share_info)
global multiple_pairs
if not time_limit:
time_limit = "1"
else:
time_limit = time_limit.strip("h")
if isinstance(query, str):... | This function processes event queries to find and combine 'before' and 'after' events within specified time windows and GPS bounds, scoring them and returning top 21 event pairs. It handles time normalization, filters events using Elasticsearch, merges scores, and sorts results by combined relevance scores. | def es_three_events(query, before, beforewhen, after, afterwhen, gps_bounds, share_info=False):
global multiple_pairs
if not afterwhen:
afterwhen = "1"
else:
afterwhen = afterwhen.strip('h')
if not beforewhen:
beforewhen = "1"
else:
beforewhen = beforewhen.strip('h')
... |
def get_template(self) -> List[TemplateAttribute]:
pass
def get_comparison_positions(self) -> List[str]:
pass
def get_data_dict(self, data):
specific_data = self._specific_position_impl(data)
data_dict = {
"Player": data[fb.PLAYER.N].tolist(),
"Team": data[fb.TEAM... | The main task of the code is to retrieve and process player sports statistics from a database, adjusting for possession factors, normalizing data to a per-90-minute basis, and formatting the output with metadata like age, team, and league names. It filters data by league, season, and player, merges adjusted metrics, an... | def impl_get_data(
self, player_name: str, leagues: List[str], team: str, season: int, use_all_minutes: bool = False
) -> pd.DataFrame:
template = self.get_template()
all_template_columns = [attr.columns_used for attr in template]
all_template_columns = [item for sublist in all_templ... |
def get_template(self) -> List[TemplateAttribute]:
return TeamTemplate
def _get_shots_data(self, leagues, season):
leagues_str = "'" + "','".join(leagues) + "'"
conn = Connection("M0neyMa$e")
data = conn.query(
f"""
SELECT
T1.squad,
T1.xg... | This function retrieves and processes football match data for a specific team across given leagues and seasons. It queries a database for match statistics, aggregates data by team and opponent, merges shot data, decorates league/team names, and returns a filtered DataFrame with combined statistics and metadata for the ... | def impl_get_data(self, season: int, leagues: List[str], team: str) -> pd.DataFrame:
conn = Connection("M0neyMa$e")
template = self.get_template()
all_template_columns = [attr.columns_used for attr in template]
all_template_columns = [item for sublist in all_template_columns for item in... |
def read_in_audio_files(self, file_directory):
audio_files=[]
for file in os.scandir(file_directory):
new_audio_file = AudioFile()
new_audio_file.set_file_name(file.name)
new_audio_file.set_file_directory(file_directory)
audio_files.append(new_audio_file)
... | This code generates a musical piece by randomly selecting and playing audio clips from a directory. It uses threads to manage tracks, pauses between clips based on specified intervals, and stops when the total duration falls within a defined range. The process continues until the piece's length meets the minimum and ma... | def perform(self, parameters):
audio_files = self.read_in_audio_files(parameters.get_directory_for_files())
tracks_threads = self.create_tracks_threads(parameters.get_number_of_tracks())
done = False
time_tracker = TimeTracker(parameters.get_minimum_length_of_piece(),
... |
def get_local_driver_version(self):
"""
Get the version of locally installed ChromeDriver.
Returns:
str: The local ChromeDriver version, or None if not found.
"""
try:
chromedriver_executable = os.path.join(
self.driver_directory, self.obt... | The main task of the code is to check the local ChromeDriver version against the latest online version, download the latest driver if it's missing, or update it if the versions mismatch. It ensures the correct driver is available for use by creating a directory, retrieving local and online versions, and triggering an u... | def check_driver(self):
"""
Check local ChromeDriver version and update if necessary.
Returns:
None
"""
Path(self.driver_directory).mkdir(parents=True, exist_ok=True)
self.base_directory = os.getcwd()
local_driver_version = self.get_local_driver_versi... |
def EOM_dark_radiation_temperature_dot(self):
# factor = (2 * self.parameter['Nc']**2 - 1) * (np.pi**2 / 30)
sigma = (2 * np.pi**5 * self.constant.k**4) / \
(15 * self.constant.c**2 * self.constant.h**3)
return - self.H() * self.temperature + self.get_Upsilon() * self.phi_field_dot**... | This code simulates the time evolution of a physical system involving dark radiation, scalar fields, and fermionic interactions. It updates temperature, phi-field dynamics, nR (radiation density), and N-field quantities using derived equations over iterations. The simulation records state variables, terminates when the... | def run(self, dt=-1e-10, iteration: int = 10):
for _ in range(iteration):
self.t += dt
self.temperature += self.EOM_dark_radiation_temperature_dot() * dt
self.phi_field_dot_dot = - 3 * self.H() * self.phi_field_dot \
- self.get_Gamma_sph... |
def EOM_dark_radiation_temperature_dot(self):
factor = (2 * self.parameter['Nc']**2 - 1) * (np.pi**2 / 30)
return - self.H * self.dark_radiation_temperature + self.get_Upsilon() * self.phi_field_dot**2 / (4 * self.dark_radiation_temperature**3 * factor)
def get_Gamma_sph(self): # maybe need modificatio... | This code numerically simulates the time evolution of cosmological parameters, updating dark radiation temperature, scalar field dynamics (phi), and fermionic density (nR) using Euler integration over a specified number of iterations. It calculates Hubble parameter H, updates field equations, enforces energy conservati... | def run(self, dt=-1e-10, iteration: int = 10):
for _ in range(iteration):
self.t += dt
self.H = self.a_dot / self.a
self.dark_radiation_temperature += self.EOM_dark_radiation_temperature_dot() * dt
self.temperature = self.dark_radiation_temperature
s... |
def fetch_and_validate_solution(self, query):
logging.info("Fetching and validating solution...")
full_solution = self.determine_task(query)
logging.debug(f"Full solution: {full_solution}")
if self.validate_extracted_code(full_solution):
return full_solution
else:
... | The main task of the code is to process a user query by fetching and validating code, generating required files, detecting and installing dependencies, executing the code, handling execution errors, and cleaning up temporary files, ultimately returning the execution result or error status. | def process_query(self, query):
logging.info("Processing the user query...")
code_to_run = self.fetch_and_validate_solution(query)
other_files = self.generate_other_files(code_to_run)
detected_dependencies = self.detect_dependencies(code_to_run)
dependencies_status = self.ensure_... |
def speak(word):
engine.say(word)
engine.runAndWait()
def work(z
):
x = z.lower()
if "open youtube" in x:
webbrowser.open("youtube.com")
#what()
elif "wikipedia" in x:
speak("search in wikipedia")
x = x.replace("wikipedia", "")
result = wikipedia.summa... | The main task of the code is to listen for user voice input via a microphone, recognize it using Google's speech recognition API, and either process the recognized text or request repetition if an error occurs. It returns the recognized query or "none" on failure, with recursive retries for invalid input. | def hearing():
speak("I am ready")
r = sr.Recognizer()
with sr.Microphone() as mic:
r.pause_threshold = 1
audio = r.listen(mic)
try:
print("recognizing")
query = r.recognize_google(audio)
print(query)
speak(query)
work(que... |
def help(Nick_Name,command):
Name = Account[Nick_Name]
if command is None:
Name.send(Command.encode(FORMAT))
else:
if command == 'list':
Name.send('\nCommand: $list\n'.encode(FORMAT))
Name.send('Arguments: none\n'.encode(FORMAT))
Name.send('Description: The list of rooms on server and thier details are ... | This code processes chat commands like $help, $list, $join, $leave, $personal, $switch, and $quit. It executes corresponding actions such as displaying help, managing room memberships, sending messages, and broadcasting. If no valid command is detected, it broadcasts user messages to their current room. | def Commands(nick, Message, args, Name):
if '$help' in Message:
help(args[0], ' '.join(args[2:]))
elif '$list' in Message:
R_Details_Record(args[0])
elif '$join' in Message:
Room_Join(args[0], ' '.join(args[2:]))
elif '$leave' in Message:
Leave_Room(args[0])
elif '$pe... |
def evaluate_board(self, game: 'Game') -> float:
current_player = game.get_current_player()
opponent_player = 1 - current_player
# Check if the current player has won
if game.check_winner() == current_player:
return 100.0
# Check if the opponent player has won
... | This code implements the minimax algorithm with alpha-beta pruning to determine the optimal move for a player in a game. It recursively evaluates legal moves, maximizing or minimizing the board's heuristic value based on the current player, and returns the best move along with its evaluation score. | def minimax(self, game: 'Game', depth: int, alpha: float, beta: float, maximizing_player: bool) -> tuple[tuple[int, int], float]:
#print(f'DEPTH: {depth}')
if depth == 0 or game.check_winner() != -1:
#print(f'EVAL: {self.evaluate_board(game)}')
#print(f'BOARD: {game.get_... |
def find_all_codons(sequence, start_codon, stop_codons, min_length):
frames = get_all_frames(sequence)
codons = [find_codons_in_frame(frame, start_codon, stop_codons, min_length) for frame in frames]
return [item for sublist in codons for item in sublist]
def find_codon_frequency(sequence, amino_acid_dict):... | The code processes multiple FASTA files in a folder to calculate codon and dicodon frequency matrices. It computes pairwise Euclidean distances between these matrices for all file pairs, normalizing by divisors n and m. Results are saved as text files containing distance matrices, with each row labeled by sequence name... | def process_files(folder, files, amino_acid_dict, start_codon, stop_codons, min_length):
codon_frequencies = []
dicodon_frequencies = []
codon_distance_matrix = []
dicodon_distance_matrix = []
for file in files:
filepath = os.path.join(folder, file)
if not os.path.exists(filepa... |
def set_initial_vars(self):
#INITIALIZE VARIABLES THAT ARE USED AT MANY PLACES THROUGHOUT THE CODE
self.dtype_dict = {}
self.idx2col = {}
self.col2idx = {}
self.columns = []
self.types = []
self.set_cols()
self.set_labels()
self.index()
self.set_types()
self.make_type_dict()
def handle_nans(self)... | The code's main task is to clean and preprocess data by initializing variables, handling missing values, converting categorical variables, sorting columns based on dependencies, and performing one-hot encoding. Repeated calls to `set_initial_vars()` suggest dynamic adjustments to data structure during processing, ensur... | def clean_data(self):
#SET_INITIAL_VARS SETS THE VALUES OF VARIABLES USED THROUGHOUT THE CODE. THIS FUNCTION HAS BEEN CALLED MULTIPLE TIMES
#WHENEVER NUMBER OF COLUMNS OR VALUES CHANGE
self.set_initial_vars()
self.handle_nans()
self.set_initial_vars()
self.convert_cat()
self.sort_with_dependencies()
s... |
def squareUnderAttack(self, row, col):
self.whiteToMove = not self.whiteToMove # switch to opponent's point of view
opponents_moves = self.getAllPossibleMoves()
self.whiteToMove = not self.whiteToMove
for move in opponents_moves:
if move.endRow == row and move.endCol == col:... | This function generates valid castling moves for a king if not in check and castling rights are enabled. It checks for kingside/queenside castling permissions based on the current player's turn and adds corresponding moves to the provided list. | def getCastleMoves(self, row, col, moves):
if self.squareUnderAttack(row, col):
return # can't castle while in check
if (self.whiteToMove and self.currentCastlingRights.wks) or (
not self.whiteToMove and self.currentCastlingRights.bks):
self.getKingsideCastleMove... |
def checkForPinsAndChecks(self):
pins = [] # squares pinned and the direction its pinned from
checks = [] # squares where enemy is applying a check
in_check = False
if self.whiteToMove:
enemy_color = "b"
ally_color = "w"
start_row = self.whiteKingLoc... | This function generates all valid moves for the current player, considering checks, pins, and castling. It handles scenarios where the king is in check by filtering moves to either block the check or move the king, and adds castling moves when applicable. It also determines checkmate or stalemate if no valid moves exis... | def getValidMoves(self):
temp_castle_rights = CastleRights(self.currentCastlingRights.wks, self.currentCastlingRights.bks,
self.currentCastlingRights.wqs, self.currentCastlingRights.bqs)
# advanced algorithm
moves = []
self.isInCheck, self.pins, ... |
def standard_options():
global dialog
dialog.AddGrid()
dialog.AddControlToGrid("Separator1", "SeparatorControl", "Job Description", 0, 0, colSpan=2)
dialog.AddControlToGrid("NameLabel", "LabelControl", "Job Name", 1, 0, "The name of your job. This is optional, and if left blank, it will default to 'Unt... | The main task of the code is to create and display a dialog for submitting a job to Deadline, a rendering management system. It initializes the dialog with a title, adds standard and plugin-specific options, configures buttons, and then shows the dialog to the user for interaction. | def __main__():
global dialog
dialog = DeadlineScriptDialog()
dialog.SetTitle("Submit Noice Job to Deadline")
standard_options()
plugin_options()
buttons()
dialog.ShowDialog(True) |
def text_cleaner(self, sentence):
sentence = sentence.lower()
translation_table = str.maketrans("", "", string.punctuation)
sentence = re.sub(r"(?<!\d)[- \'](?!\d)", ' ', sentence)
sentence = sentence.translate(translation_table)
return sentence
def Encoder(self, sentence, langua... | This code translates an input sentence from one language to another using a neural machine translation model. It cleans the input text, encodes it with an encoder, predicts output logits with a trained model, converts logits to the target language's text, and returns the cleaned translated sentence. | def predict(self, in_sentence, in_language='EN', out_language='FR', Max_Length=21):
in_sentence = self.text_cleaner(in_sentence)
X = self.Encoder(in_sentence, in_language, Max_Length)
Y = np.ravel(np.argmax(self.model.predict(X, verbose=0), axis=2))
out_sentence = self.logits_to_text(Y, ... |
def get_encoded_features(self, features_data):
df = pd.read_csv(features_data)
features_list = df[self.feature_type].parallel_apply(lambda x: self.give_list(x))
return features_list
def get_ner_reader(data):
# 'fields' contains 4 lists
# The first list is the list of words... | The code reads input data (either a string or DataFrame) and processes it along with encoded features. It parses each instance into tensors (tokens, masks, tags, features) and stores them in `self.instances`, limiting the number of instances if specified. The function handles both file-based and in-memory data, using p... | def read_data(self, data, features_data):
dataset_name = data if isinstance(data, str) else 'dataframe'
print("Obtaining {} from {}".format(self.feature_type, features_data))
features_list = self.get_encoded_features(features_data)
print("Reading file {}".format(dataset... |
def estimates_value(b):
time, position = load_data_from_file(b)
c_max = max(position)
# c_max_time = max(time)
c_initial = position[0]
# c_initial_time = time[0]
c_final = position[-1]
# c_final_time = time[-1]
return time, position, c_max, c_initial, c_final
def estimate_char(a):
t... | The code analyzes data from a file to extract system parameters and performance metrics. It retrieves time, position, and damping-related values, calculates rise time, peak time, overshoot, settling time, and mass, then determines spring constant and damping factor. The results are stored in a dictionary, sorted, and p... | def analyze_data(filename):
time, position, c_max, c_initial, c_final = estimates_value(filename)
time_r, time_p, overshoot_p, time_s, mass = estimate_char(filename)
mass, spring_constant, damping_factor = get_system_params(overshoot_p, time_s)
dict1 = {"c_initial": c_initial, "c_final": c_final, "c_max... |
def estimates_value(path):
# Take time and position from load data function
time, position = load_data_from_file(path)
# Determine initial, maximum, final position
c_initial = position[0]
c_max = max(position)
c_final = position[-1]
return time, position, c_initial, c_max, c_final
def estima... | The main task of the code is to analyze system data from a given file path, extract key performance metrics (rise time, peak time, overshoot, settling time) and system parameters (mass, spring constant, damping coefficient), and return them as an unsorted dictionary for further processing or analysis. | def analyze_data(path):
time, position, c_initial, c_max, c_final = estimates_value(path)
t_r, t_p, percent_overshoot, T_s = estimate_char(path)
k, c, m = get_system_params(percent_overshoot, T_s)
unsorted_dict = {'c_initial': c_initial, 'c_max': c_max, 'c_final': c_final, 'rise_time': t_r,
... |
def sort_lines(self):
"""Helper function to perform page-level cleaning on line-level data.
Manipulates the page buffer and clears the line buffer.
"""
sorted_lines = sorted(
self.line_buffer,
key=lambda x: (-float(x[1]), float(x[0])),
)
self.line_... | This code processes the end of XML elements during document parsing. It sorts lines when a "page" ends, handles "textbox" and "text" elements by recording text content or triggering specific data processing (like "Hours Distribution by Time Code"), and updates state flags (in_textbox, in_text) to manage parsing context... | def endElement(self, name):
if name=="page":
self.sort_lines()
elif not self.in_figure and not self.in_hours_distribution:
if name=="textbox":
handled = self.handle_header_footer_end()
if not handled:
text = self.pop_buffer()
... |
def initial_solution(self):
cur_node = random.choice(self.nodes)
solution = [cur_node]
free_nodes = set(self.nodes)
free_nodes.remove(cur_node)
while free_nodes:
next_node = min(free_nodes, key=lambda x: self.dist(cur_node, x))
free_nodes.remove(next_node... | This code implements a simulated annealing algorithm to optimize a solution, likely for a traveling salesman problem. It initializes a solution, iteratively generates candidate solutions by reversing random subsegments, evaluates them, and updates the best solution. The temperature (T) decreases exponentially, controll... | def anneal(self):
self.cur_solution, self.cur_fitness = self.initial_solution()
print('Initialized solution:', self.best_fitness)
plot_graph([self.cur_solution], self.coordinates, self.path, 'Initialized Solution')
while self.T >= self.stopping_temperature and self.iteration < self.sto... |
def find_random():
all_themes = []
for song_themes_and_scores in list_of_themes:
for theme in song_themes_and_scores:
all_themes.append(theme[0])
num_to_select = 10 # set the number to select here.
list_of_random_items = random.sample(all_themes, num_to_select)
return(list_... | The main task of the code is to handle search queries for songs by either text content or themes. It retrieves search terms from URL parameters, processes them using literal or boolean theme searches, extracts song details (title, author, lyrics, themes, link) from matched documents, and renders the results in an HTML ... | def search():
#Get query from URL variable
query = request.args.get('query')
themes_query = request.args.get('themes_query')
random_themes = []
random_themes = find_random()
#Initialize list of matches
boolean_matches = []
matches = []
list_of_matches = []
#If query exists (i.e... |
def taylorbreak(x,d):
q,r = np.divmod(x,d)
if r == 0:
return q*d, r
return (q+1)*d, d-r
def apprphiFT(x,d = dt):
q, r = taylorbreak(x,d)
ftaylor = rphi(q)-roundeps(r*roundeps(dphi(q)))
#print(x,q,r,ftaylor)
return ftaylor
def phi(x):
return np.log2(1-2**x)
def dphi(x):
retur... | The function computes an enhanced approximation of a function phi using Taylor series expansion and error correction. It combines a Taylor approximation (apprphiFT) with an error term derived from ratios of computed errors (emaxx, emaxp, eqp), adjusting the result to improve accuracy. The correction factor (erat) scale... | def apprphiEC(x,d = dt, c = const, dp = dtb):
q, r = taylorbreak(x,d)
ftaylor = apprphiFT(x,d)
c = -c * dt
emaxx = -phi(q) + dt*dphi(q) + phi(q-dt)
emaxp = -phi(c) + dt*dphi(c) + phi(c-dt)
qp, rp = taylorbreak(r,dp)
eqp = -phi(c) + qp*dphi(c) + phi(c-qp)
erat = roundeps(eqp/emaxp)
e... |
def breakdown(x,da,db,dc):
if x>= -db:
return [1,x,0,0]
if x>= -dc:
rb, ra = divf(x,db)
return [2,ra,rb,0]
rc, rab = divf(x,dc)
rb, ra = divf(rab,db)
return [3, ra,rb,rc]
def rphi(x,e=eps):
return roundeps(phi(x),eps)
def apprphiFT(x,d = dt):
q, r = taylorbreak(x,d)
... | The code computes a transformed value of input x using conditional logic based on a breakdown into variables ra, rb, rc. It applies the rphi() function directly for case=1, combines x with adjusted rphi() values for case=2, and uses nested apprphiFT() operations with rphi() adjustments for other cases, returning a comp... | def cotransphiFT(x):
case, ra, rb, rc = breakdown(x,da,db,dc)
if case == 1:
return rphi(ra)
if case == 2:
k = x + rphi(ra) - rphi(rb)
return apprphiFT(k)+ rphi(rb)
k1 = rb - ra + rphi(ra) - rphi(rb)
k2 = x + rphi(rb) - rphi(rc) + apprphiFT(k1)
return apprphiFT(k2) + r... |
def breakdown(x,da,db,dc):
if x>= -db:
return [1,x,0,0]
if x>= -dc:
rb, ra = divf(x,db)
return [2,ra,rb,0]
rc, rab = divf(x,dc)
rb, ra = divf(rab,db)
return [3, ra,rb,rc]
def rphi(x,e=eps):
return roundeps(phi(x),eps)
def apprphiEC(x,d = dt, c = const, dp = dtb):
q, ... | The code computes a value based on different cases by combining results from helper functions `rphi` and `apprphiEC`. It uses conditional logic to handle three scenarios: returning `rphi(ra)` for case 1, a transformed value involving `apprphiEC` for case 2, and a recursive-like computation for other cases, ultimately r... | def cotransphiEC(x):
case, ra, rb, rc = breakdown(x,da,db,dc)
if case == 1:
return rphi(ra)
if case == 2:
k = x + rphi(ra) - rphi(rb)
#print(k,apprphiEC(k) )
return apprphiEC(k)+ rphi(rb)
k1 = rb - ra + rphi(ra) - rphi(rb)
k2 = x + rphi(rb) - rphi(rc) + apprphiEC(k1) ... |
def copy_file_obj_measure_speed(*args, **kwargs) -> Generator[
Tuple[int, int, int, Optional[int]], None, None]:
"""
Refer to `copy_file_obj` for details of the parameters. This generator
yields additional data in comparison with the `copy_file_obj` function,
as it will yield the total downloade... | This function provides a verbose file copy operation, displaying a progress bar, download speed, ETA, and total size. It extends `copy_file_obj` with parameters for progress visualization, requiring `max_bytes` to show the bar. It calculates speed, converts units, updates the progress dynamically, and prints results to... | def verbose_copy_file_obj(*args, print_file: IO = sys.stdout,
progress_bar_length: int = 50,
**kwargs):
"""
A verbose version of `copy_file_obj`, where a progress bar is shown along
with the current speed and total amount of bytes. The described parameters... |
def ious_combined_graph(test_results, input_sequence):
"""generation of graph of ious from all passes
"""
plt.figure()
ious = pd.concat([test['iou'] for test in test_results],
axis=1, join='inner')
mean = ious.mean(axis=1)
colors = cm.get_cmap('Pastel1')(np.linspace(0.0, 1.0... | The main task of the code is to generate a policy test report by rendering an HTML template with test results, statistical tables (stopwatch and IoU), and visualizations (graphs). It processes input images, computes metrics, creates graphs, saves images to a directory, and writes the final HTML summary report with dyna... | def generate(
name,
test,
link,
test_results,
tests_input_path,
stopwatch_test,
outdir):
env = Environment(
loader=PackageLoader("vot_report_generator", "templates"))
template = env.get_template("policy_test.html")
input_sequence_path = tests_... |
def duration(start_time):
current_time = time.perf_counter()
if current_time < start_time:
return (current_time + (sys.float_info.max - start_time)) * 1000
return (current_time - start_time) * 1000
def readSerial(ser):
bytesToRead = ser.inWaiting() # Take data from buffer
return (bytesToRea... | This function manages serial communication with an MCU to read sensor data based on a specified period and sensor type. It handles state transitions between NORMAL and WAIT_DATA, processes incoming messages, resends requests on errors, and sends ACK/NAK responses. It also manages timeouts, retries, and data uploading t... | def ReadData(self, period, sensorType, qos=0):
if not self.enable:
return
global seq
global feed_names
try:
if self.state == NORMAL:
if duration(self.start_time) < period * 1000:
# Check re-send request from MCU
... |
def get_souped_page_from_url(url_path, code):
full_url = ethnologue_base + url_path.format(code)
page_string = get_page_as_string(full_url)
return BeautifulSoup(page_string, "html.parser")
def scrape_indiv_lang(page):
name = page.select_one('#page-title').text
rows = page.select('.view-content > div... | The function retrieves and processes language data by fetching a webpage using a language abbreviation, extracting raw data, and adding an image to the data before returning it. | def ethno_by_lang_abrv(lang_abr):
page = get_souped_page_from_url("/language/{}", lang_abr)
raw_data = scrape_indiv_lang(page)
return add_language_image(raw_data) |
def scrape_country_main_page(country_data, country_code):
page = get_souped_page_from_url("/country/{}", country_code)
name, labels, contents = extract_main_page_data(page)
for label, content in zip(labels, contents):
country_data["Data"][label] = content
country_data["Meta"]["fields"] = labels
... | The main task of the code is to construct a comprehensive country data structure by scraping and aggregating information from various sources. It initializes a dictionary with metadata and data fields, then populates it by scraping the country's main page, status page, maps, and adding profile images, all tied to the p... | def build_country_data(country_code):
country_data = {"Meta": {"country_code": country_code}, "Data":{}}
scrape_country_main_page(country_data, country_code)
add_status_profile_image(country_data, country_code)
scrape_country_status_page(country_data, country_code)
scrape_country_maps(country_data, ... |
def draw_grid_lines(grid_size, screen_width, screen_height, screen):
# Draw grid lines
for i in range(1, grid_size):
pygame.draw.line(screen, (0, 0, 0), (screen_width / grid_size * i, 0), (screen_width / grid_size * i, screen_height), 5)
pygame.draw.line(screen, (0, 0, 0)... | This code implements a multiplayer Connect Four-style game using Pygame. It initializes a grid, handles user input for placing pieces, checks for a winning condition, displays the board, and resets the game upon a win. The loop processes events, updates the board state, and cycles through player turns until the user qu... | def main():
# Height and width of the screen
SCREEN_WIDTH = 500
SCREEN_HEIGHT = 500
# Grid size
GRID_SIZE = 10
# Amount needed in a row to win
WIN_AMOUNT = 4
# Number of players
NUM_PLAYERS = 5
# Store the board state as a 2D array
... |
def __syncServiceOutput(self):
try:
with open(self.__serviceOutputFP, "r") as soFile:
soCpltString = soFile.read()
self.__serviceOutputObj = json.loads(soCpltString)
except:
self.__addErrorLog('Sync Service Output', 'Service output reading method e... | The main task of the code is to run an infinite loop in a thread, synchronizing service outputs and inputs when conditions allow. It checks if the service can run, performs output synchronization, and triggers input synchronization if needed. The loop continues until `__loopRunning` is stopped, ensuring thread-safe ope... | def __mainJApiLoop(self):
print("#JAPI> Thread started!")
while self.__loopRunning:
if self.canRun:
self.__syncServiceOutput()
#self.__cleanOrders()
if self.__serviceInputNeedSync:
self.__syncServiceInput()
... |
def create_directories(dst: str, language: str) -> None:
"""
Creates the necessary directories for storing the translated mod files.
:param dst: str, the destination directory.
:param language: str, the target language code.
"""
os.makedirs(dst, exist_ok=True)
os.makedirs(os.path.join(dst,... | The main task of the code is to translate game mod files from English to a specified target language. It creates destination directories, logs the translation process, and iterates through source files, translating each mod file individually using a designated method. Parameters include source and destination paths, al... | def translate_mod_files(self, src: str, dst: str, language: str):
"""
Translates the game mod files from English to the target language.
:param src: str, the source directory containing the mod files.
:param dst:
str, the destination directory to store the translated mod fil... |
def ToyModel(choice,shape,alpha,numPoints,noise,crack,h, K_app, geo,Sep,PS, DC):
###############################################################################################
### Build a random initial config by apply the known displacement to a random set of points ###
###################################... | The code `SIF_projection` estimates crack tip locations and computes stress intensity factors (K-field) using three methods: geometric analysis, separable pattern search, and displacement correlation. It processes either synthetic data or provided displacement data, applying domain-specific parameters (e.g., domain siz... | def SIF_projection(synData = 1, shape = 3, domainSize=10000,r2 = 50,alpha=1.5,noise = 0,
K_app = [0.8, 0, 0], coords = [], coords_ref =[],config = 0,guess = [10, 10],
crack = [0,0], h=5,geo = 0,Sep = 1, DC = 0, PS = 1, constants = []):
global R1, R2, boxsize, tip... |
def startMenu(canvas: pygame.Surface):
clock = pygame.time.Clock()
pygame.display.set_caption("Start Menu")
looping = True
while looping:
clock.tick(60)
mouse = pygame.mouse.get_pos()
titleText = get_font(75).render("ACM Rhythm", True, "#FFFFFF")
titleRect = titleText.ge... | The code initializes a Pygame rhythm game, sets the window title, creates a display surface, and sequentially runs the start menu, game loop, and end menu functions to manage game flow and user interaction. | def main():
pygame.init()
pygame.display.set_caption("Rhythm Game")
canvas = pygame.display.set_mode((width, height))
startMenu(canvas)
gameLoop(canvas)
endMenu(canvas) |
def meanX(cdtm1):
rowsum=0
rowsum=rowSum(cdtm1)
meanx=0
for i in range(0,81):
meanx=meanx+i*rowsum[i]
return meanx
def meanY(cdtm1):
columnsum=columnSum(cdtm1)
meanY=0
for i in range(0,81):
meanY=meanY+i*columnsum[i]
return meanY
def STdevX(cdtm1):
rowsum=rowSum(c... | The code calculates the Pearson correlation coefficient between two variables represented in a matrix. It computes the covariance by iterating over all matrix elements, adjusting each by their indices and subtracting the product of means, then normalizing by dividing by the product of standard deviations. The result is... | def correlation(cdtm1):
meanx=meanX(cdtm1)
meany=meanY(cdtm1)
stdX=STdevX(cdtm1)
stdY=STdevY(cdtm1)
correlation=0
for i in range(81):
for j in range(81):
correlation=correlation+((i*j)*cdtm1[i][j]-meanx*meany)/(stdX*stdY)
return correlation |
def validate_deps(self):
"""Validates required packages are installed."""
_error = False
try:
import twine
except ImportError:
self.status('Please `pip install twine` to use upload command.')
_error = True
try:
import bumpversion
... | The code automates a Python package release process: validates dependencies, runs tests, checks for version updates, bumps the version if needed, builds source/wheel distributions, uploads to PyPI via Twine, and provides installation instructions, aborting on any failure. | def run(self):
self.validate_deps()
self.validate_dirty()
if not self.skip_tests:
self.status('Testing build...')
res = os.system('{0} setup.py test'.format(sys.executable))
if res != 0:
self.abort()
current_version = read_current_ve... |
def player_fight_menu(self, enemy):
#gives player options to inspect, check inventory, and fight. eventually player has to choose fight
while True:
print("""
| fighting {}!
-------------------------------------------
| ~o p t i o n s~ ... | This code simulates a turn-based combat between a player and an enemy. It alternates attacks, reduces health, checks for death, and handles rewards (potions/weapons) if the enemy is defeated. If the player dies, it triggers a game over. The loop ends when either the player or enemy's health drops to zero, with appropri... | def fight(self, enemy):
while self.health > 0 and enemy.health > 0:
#players turn: calls the fight menu.
self.player_fight_menu(enemy)
print("fighting {}...".format(enemy.name)) #fighting... display damage and minus health from enemy
print("{}'s HP: {} --> {} ".fo... |
def distribution_module(supplier_code):
distribute_item = True
while distribute_item:
distribution_process(supplier_code)
continue_ask_confirm = True
while continue_ask_confirm:
break_process = input("Want to distribute next item? [0-no 1-yes]: ")
if break_proce... | This function displays a supplier-specific menu with options to distribute stock, track inventory, update profiles, or log out. It validates numeric input (1-4) and routes to corresponding modules based on the selected option, using the supplier's code for data handling. | def supplier_menu(supplier_name, supplier_code):
print("-" * 50)
print("Inventory System")
print("-" * 50)
print("---Welcome {}, Code: {}---".format(supplier_name, supplier_code))
print("1. Distribute Stock to Hospital")
print("2. Inventory Tracking")
print("3. Profile Update")
print("4.... |
def filter_atom_arrays(_all_atoms, _symbols):
""" Filters an array via various techniques
Parameters:
_all_atoms (ndarray): an array of atom positions (vectors)
Returns:
surface_atoms (ndarray): an array of surface atoms within a particular range of z
all_atoms (ndarray): an array of all a... | The code processes a PDB file to compute a bond order parameter (QL) for each frame. It reads atomic coordinates, filters surface atoms, calculates nearest neighbor vectors, and computes QL using angular momentum harmonics. Results are stored and output, with timing metrics provided. The task involves analyzing molecul... | def main():
""""""
directory = "/home/armandpj/Work/Hydrates/examples"
#file_name = input("Enter file name: ")
file_name = "hydrate.pdb"
input_path = Path(directory)/file_name
if not input_path.exists():
print(f"The path {input_path} does not exist!")
sys.exit(1)
#... |
def denoise_preserving_edge_from(image, epsilon=0.01, neighborhood_pixels=3):
if is_colored(image):
cv.ximgproc.guidedFilter(image, image, neighborhood_pixels, epsilon, image)
else:
cv.ximgproc.guidedFilter(image, image, neighborhood_pixels, epsilon, image, -1)
return image
def crop_by_landm... | The main task of the code is to preprocess an image by extracting and combining specific facial regions (left eye, nose, right eye) for glasses processing. It denoises the image, detects facial landmarks, crops and resizes key areas, concatenates them horizontally, and returns a cleaned upper-face image. If errors occu... | def preprocessing_glasses(image, detector, predictor):
try:
image = denoise_preserving_edge_from(image)
rect = detector(image)[0]
sp = predictor(image, rect)
landmarks = np.array([[p.x, p.y] for p in sp.parts()])
# Lid sx
range_face = [37, 38, 39, 40]
landma... |
def unknown(message):
set_rc(UNKNOWN_RC)
messages.append('UNKNOWN: ' + message)
def get_stats(container):
content, _ = get_url(daemon + '/containers/{container}/stats?stream=0'.format(container=container))
return content
def evaluate_numeric_thresholds(container, value, thresholds, name, short_name,
... | The function `check_memory` evaluates a container's memory usage against specified thresholds by adjusting for memory cache, converting usage to a percentage or specified unit, and validating against limits before invoking threshold evaluation logic. | def check_memory(container, thresholds):
if not thresholds.units in unit_adjustments:
unknown("Memory units must be one of {}".format(list(unit_adjustments.keys())))
return
inspection = get_stats(container)
# Subtracting cache to match what `docker stats` does.
adjusted_usage = inspec... |
def get_container_info(name):
content, _ = get_url(daemon + '/containers/{container}/json'.format(container=name))
return content
def evaluate_numeric_thresholds(container, value, thresholds, name, short_name,
min=None, max=None, greater_than=True):
rounder = lambda x: round(... | The code calculates a container's uptime in seconds since its start time, then evaluates if this uptime value meets specified thresholds using a numeric evaluation function, checking whether the uptime is within a defined range (0 to 2 seconds) with 's' as the unit. | def check_uptime(container, thresholds):
inspection = get_container_info(container)['State']['StartedAt']
only_secs = inspection[0:19]
start = datetime.strptime(only_secs, "%Y-%m-%dT%H:%M:%S")
start = start.replace(tzinfo=timezone.utc)
now = datetime.now(timezone.utc)
uptime = (now - start).tota... |
def get_container_info(name):
content, _ = get_url(daemon + '/containers/{container}/json'.format(container=name))
return content
def get_image_info(name):
content, _ = get_url(daemon + '/images/{image}/json'.format(image=name))
return content
def evaluate_numeric_thresholds(container, value, thresholds... | The function `check_image_age` calculates the age of a container's image in days and evaluates whether this age meets specified thresholds, returning the result of this evaluation. | def check_image_age(container, thresholds):
container_image = get_container_info(container)['Image']
image_created = get_image_info(container_image)['Created']
only_secs = image_created[0:19]
start = datetime.strptime(only_secs, "%Y-%m-%dT%H:%M:%S")
start = start.replace(tzinfo=timezone.utc)
now... |
def get_container_info(name):
content, _ = get_url(daemon + '/containers/{container}/json'.format(container=name))
return content
def evaluate_numeric_thresholds(container, value, thresholds, name, short_name,
min=None, max=None, greater_than=True):
rounder = lambda x: round(... | The code checks a container's restart count against specified thresholds. It retrieves the container's restart count, then evaluates if it meets predefined limits using a numeric threshold evaluation function, likely for monitoring or alerting purposes. | def check_restarts(container, thresholds):
inspection = get_container_info(container)
restarts = int(inspection['RestartCount'])
graph_padding = 2
evaluate_numeric_thresholds(container=container, value=restarts, thresholds=thresholds, name='restarts',
short_name='re', mi... |
def get_container_info(name):
content, _ = get_url(daemon + '/containers/{container}/json'.format(container=name))
return content
def get_stats(container):
content, _ = get_url(daemon + '/containers/{container}/stats?stream=0'.format(container=container))
return content
def calculate_cpu_capacity_precen... | The code monitors a container's CPU usage by retrieving its information and statistics, calculating the CPU capacity percentage, and evaluating it against specified thresholds. It sets the maximum threshold to 100% and checks if the usage meets the defined limits, providing a numeric evaluation for CPU performance moni... | def check_cpu(container, thresholds):
info = get_container_info(container)
stats = get_stats(container=container)
usage = calculate_cpu_capacity_precentage(info=info, stats=stats)
max = 100
thresholds.units = '%'
evaluate_numeric_thresholds(container=container, value=usage, thresholds=thresho... |
def _set_config_opts(config_file, verbose=False):
global ST2_USERNAME
global ST2_PASSWORD
global ST2_API_KEY
global ST2_AUTH_TOKEN
global ST2_API_BASE_URL
global ST2_AUTH_BASE_URL
global ST2_SSL_VERIFY
global UNAUTHED
global IS_API_KEY_AUTH
if not os.path.exists(config_file):
... | The main task of the code is to configure settings using a provided config file, register with StackStorm (ST2), and post an event to ST2 with a given payload. The `verbose` parameter controls detailed logging. | def main(config_file, payload, verbose=False):
_set_config_opts(config_file=config_file, verbose=verbose)
_register_with_st2(verbose=verbose)
_post_event_to_st2(payload, verbose=verbose) |
def normalize_state(status_info):
# Ugh, docker used to report state in as silly way then they figured out how to do it better.
# This tries the simpler new way and if that doesn't work fails back to the old way
# On new docker engines the status holds whatever the current state is, running, stopped, pause... | The main task of the code is to check whether a container's current state matches a specified desired state. It normalizes both states to lowercase for case-insensitive comparison. If they differ, it logs a critical error message; if they match, it logs a confirmation message. The function ensures state consistency by ... | def check_status(container, desired_state):
normized_desired_state = desired_state.lower()
normalized_state = normalize_state(get_state(container)).lower()
if normized_desired_state != normalized_state:
critical("{} state is not {}".format(container, desired_state))
return
ok("{} status ... |
def get_state(container):
return get_container_info(container)['State']
def ok(message):
set_rc(OK_RC)
messages.append('OK: ' + message)
def critical(message):
set_rc(CRITICAL_RC)
messages.append('CRITICAL: ' + message)
def unknown(message):
set_rc(UNKNOWN_RC)
messages.append('UNKNOWN: ' + m... | The code checks a container's health status by retrieving its state, evaluates the "Health" and "Status" fields, and logs alerts (ok, critical, unknown) based on the status. If no health data exists, it reports the absence. | def check_health(container):
state = get_state(container)
if "Health" in state and "Status" in state["Health"]:
health = state["Health"]["Status"]
message = "{} is {}".format(container, health)
if health == 'healthy':
ok(message)
elif health == 'unhealthy':
... |
def get_container_image_id(container):
# find registry and tag
inspection = get_container_info(container)
return inspection['Image']
def unknown(message):
set_rc(UNKNOWN_RC)
messages.append('UNKNOWN: ' + message)
def get_container_image_urls(container):
inspection = get_container_info(container)... | The code verifies if a container's local image version matches its registry-digest. It retrieves the container's image ID, checks for valid repository URLs, normalizes the registry URL, fetches the remote digest, and compares it to the local ID. Errors handle connectivity issues or mismatched versions, logging warnings... | def check_version(container, insecure_registries):
image_id = get_container_image_id(container)
logger.debug("Local container image ID: {}".format(image_id))
if image_id is None:
unknown('Checksum missing for "{}", try doing a pull'.format(container))
return
image_urls = get_container_i... |
def perform_checks(raw_args):
args = process_args(raw_args)
global parallel_executor
parallel_executor = futures.ThreadPoolExecutor(max_workers=args.threads)
global serial_executor
serial_executor = futures.ThreadPoolExecutor(max_workers=1)
global unit_adjustments
unit_adjustments = {key: ... | (The main task of the code is to execute parallel checks using threads, collect their results, handle exceptions, print outcomes, and exit with a status code. It first runs checks with command-line arguments, waits for thread results, catches exceptions to log errors, prints results, then exits with a return code.) | def main():
try:
perform_checks(argv[1:])
# get results to let exceptions in threads bubble out
[x.result() for x in futures.as_completed(threads)]
except Exception as e:
traceback.print_exc()
unknown("Exception raised during check': {}".format(repr(e)))
print_resul... |
def getPairsOfMatchedNodes(modelObject, nodePairs,Names):
"""
Pair up nodes for imposition of periodic constraints.
Inputs:
modelObject - The mdb model object
nodePairs - List of pairs (list) of assembly-level nodeset names to be constrained.
The first item... | This function applies periodic boundary conditions (PBCs) to a representative volume element (RVE) in a finite element model. It processes node pairs, creates surface elements with linear/quadratic types, assigns sections, generates reference points, and defines pinned nodes. The core task involves configuring PBC cons... | def applyMechanicalPBC(Model,pairsOfNodesetNames,Names):
"""
Applies periodic boundary conditions to an RVE
Inputs:
Model - A model object from a Model Database
"""
userDefinedNodesetPairs = []
originallySlavedNodes = []
previouslySlavedNodes = []
pairedNodes, periodicit... |
def addDepth(d,vertices):
points = vertices
for _ in range(d):
points = addMidPoints(points)
return points
def find_by_intersection(p1,p2,radius=r_f,z_c=a3,y_c=0.0):
line_start = np.array([p1[1],p1[2]])
line_end = np.array([p2[1],p2[2]])
circle_center = np.arr... | This function processes geometric vertices by adding depth to specified structures ("hex" and "outer"), computes intersection points to form a "circle" path, and cleans the resulting vertices by removing original entries. It returns both the cleaned and modified vertex dictionaries for further processing. | def pipeLineAddingDepth(depth, prevVertices_dic):
keys = ['hex','outer']
newVertices_dic = {}
for k in keys:
v = prevVertices_dic[k]
newVertices_dic[k] = addDepth(depth,v)
x_c, y_c = prevVertices_dic['origin']
newVertices_dic['origin'] = prevVertices_dic['... |
def is_learnt(self, obs):
return self.l[obs] > self.thresh_l
def bootstrap(self, t: Transition):
q_next = 0. if t.a_d else self.max_action_value(t.s_p)[1]
target = t.r_p + self.gamma * q_next
self.q[t.a][t.s] += self.alpha * (target - self.q[t.a][t.s])
def max_action_value(self, obs):
q_values = sel... | The code updates the model by either bootstrapping from learned states or storing transitions in a trajectory. If the next state is learned or a terminal action is taken, it initializes a value estimate and performs a Monte Carlo update to refine the model's value predictions. | def do_update(self, t: Transition):
if self.is_learnt(t.s) and self.is_learnt(t.s_p):
self.bootstrap(t)
else:
self.traj.append(t)
if t.a_d or self.is_learnt(t.s_p):
G_init = 0. if t.a_d else self.max_action_value(t.s_p)[1]
self.monte_carlo(G_init) |
def _get_margin_affinity(top_percentage: int, all_files: List[Path]) -> float:
affinity = 0
for i, f in enumerate(all_files):
logger.info(f'{i + 1} files read.')
df = pd.read_csv(f, header=None, names=['origin', 'ligand', 'smi', 'affinity'])
df = df.sort_values(by=['affinity'], ascending... | The code aggregates results from multiple `output.txt` files in a directory, filters the top entries based on a percentage threshold (affinity margin), and merges them into a single sorted output file, limited by a specified number of items. It deletes existing output files, calculates a margin for filtering, selects f... | def collect(input: str, output: str, limit: int, percentage: int):
input_path = Path(input)
output_path = Path(output)
all_files = list(input_path.rglob("**/output.txt"))
logger.info(f'{len(all_files)} files found')
if len(all_files) < 1:
logger.info('No output files to collect results from... |
def generate(width, height, S):
# https://courses.cs.washington.edu/courses/cse326/00wi/projects/voronoi.html
C = [
((-width, -height), [
[width/2, height/2, width/2, -10*height],
[width/2, -10*height, -10*width, height/2],
[-10*width, height/2, width/2, height/2]
]),
((2*width, -height), [
[width/... | The main task of the code is to generate a map with randomized walls and cells based on given density, site count, and screen size. It creates random sites, generates cells, checks if edges are in bounds, and constructs a map with unique edges and indexed cell points. The output includes all points, edge indices, and a... | def genMap(DENSITY, COUNT, SCREEN_SIZE):
sites = []
for i in range(COUNT):
sites.append((random.randint(0,SCREEN_SIZE[0]), (random.randint(0,SCREEN_SIZE[1]))))
cells = generate(SCREEN_SIZE[0], SCREEN_SIZE[1], sites)
inBounds = lambda x,y : x > 0 and y > 0 and x < SCREEN_SIZE[0] and y < SCREEN_SIZE[1]
edges = [... |
def get_errors(station):
errors = []
for component_object in Component.objects.filter(station=station.id):
for error_object in Error.objects.filter(component=component_object.id):
errors.append({
'id' : error_object.id,
'component' : component_object.name,
... | The function updates a station's status based on its last update time, errors, and warnings. It checks if the station is disconnected, has errors, or issued warnings, then sets the appropriate status. If the new status severity is higher than the previous, it notifies maintainers with relevant warnings. Finally, it sav... | def update_status(station):
previous_status = station.status
warnings_issued = []
if (timezone.now() - station.last_updated).total_seconds() // 3600 > DISCONNECTED_HOURS:
status = Status.objects.get(name="Disconnected")
elif len(get_errors(station)) > 0:
status = Status.objects.get(name=... |
def handle_meta_data(model: PyTorchForecast):
"""A function to init models with meta-data
s
:param model: A PyTorchForecast model with meta_data parameter block in config file.
:type model: PyTorchForecast
:return: Returns a tuple of the initial meta-representationf
:rtype: tuple(PyTorchForecast... | This function trains a PyTorchForecast model using specified parameters, including data loading, optimizer setup, loss computation, validation, and early stopping. It iterates through epochs, logs training/validation metrics, evaluates on test data, and saves the trained model. The process supports probabilistic models... | def train_transformer_style(
model: PyTorchForecast,
training_params: Dict,
takes_target=False,
forward_params: Dict = {},
model_filepath: str = "model_save") -> None:
"""Function to train any PyTorchForecast model
:param model: A properly wrapped PyTorchForecast model... |
def _identify_locations(self, image_x, image_y):
try:
green_loc = self._calculate_moment(image_x, image_y, GREEN_MASK)
self.last_green_success = green_loc
except:
print(f"yellow detection failed. reverting to {self.last_yellow_success}")
yellow_loc = self.... | The code calculates joint angles (JA1, JA3, JA4) of a robotic arm using marker positions (green, yellow, blue, red) from images. It converts pixel distances to meters, computes angles via geometric relationships, adjusts signs based on marker positions, and returns the angles along with the end-effector's position. The... | def _detect_angles(self, image_x, image_y):
green_loc, yellow_loc, blue_loc, red_loc = self._identify_locations(image_x, image_y)
# used to calculate position of end effector in meter space for forward kinematics problem.
dist_red_green = self._scale_to_meter(green_loc, red_loc, LOWER_LINK_LEN... |
def getDataHeader(self, protoFile: FileDescriptorProto) -> list[str]:
''' Gets the first few lines to start a file containing one or many
messages/enums. '''
if self.swift:
return [
"import " + str(self.sharedModule),
"",
]
else... | This function processes messages and enums from a Protocol Buffers file, generating code files. It creates one Swift file per proto file, or separate Kotlin files per message/enumeration. It handles code generation by processing each enum and message, appending generated content, and adding appropriate headers/footers.... | def processMessagesAndEnums(self, protoFile: FileDescriptorProto,
response: CodeGeneratorResponse):
''' Processes messages and enums in protoFile. In Swift there is
one output file, in Kotlin there is one per message/enum. '''
protoName = self.packageName
... |
def getServiceHeader(self, protoFile: FileDescriptorProto,
serv: ServiceDescriptorProto) -> list[str]:
''' Gets the start of a service definition eg a class. '''
lines = self.getServiceImports(protoFile, serv)
servName = self.getServiceName(protoFile, serv)
lines... | This function generates code lines for a gRPC service by combining a service header, individual method implementations, and a service footer. It collects these components into a list of strings for output. | def processService(self, protoFile: FileDescriptorProto,
serv: ServiceDescriptorProto) -> list[str]:
''' Processes a grpc service. '''
lines = self.getServiceHeader(protoFile, serv)
for method in serv.method:
lines.extend(self.getServiceMethod(protoFile,
... |
def processService(self, protoFile: FileDescriptorProto,
serv: ServiceDescriptorProto) -> list[str]:
''' Processes a grpc service. '''
lines = self.getServiceHeader(protoFile, serv)
for method in serv.method:
lines.extend(self.getServiceMethod(protoFile,
... | The code processes each service in the provided proto file, generating output files for each. It constructs filenames using the service name, package, and client variation, then adds the generated content to the response. | def processServices(self, protoFile: FileDescriptorProto,
response: CodeGeneratorResponse):
''' Processes services in protoFile. There is one service per
output file. '''
for serv in protoFile.service:
content = self.processService(protoFile, serv)
... |
def getResultCallbackInLieuOfReturn(self, protoFile: FileDescriptorProto,
method: MethodDescriptorProto) -> list[str]:
''' For methods using callbacks, gets the final parameter used to
return the result. If the callback receives success and failure
both null, it means a... | The main task of the code is to generate a return clause for a method, including the closing brace and return type. It handles language-specific formatting (e.g., Swift uses callbacks instead of direct returns), converts the output type name, and adjusts for server-streaming methods by wrapping types in "Flow<...>". Th... | def getReturn(self, protoFile: FileDescriptorProto,
method: MethodDescriptorProto) -> list[str]:
''' Gets a return clause for a method: the closing brace and return
type. When using callbacks, override and forward to
getResultCallbackInLieuOfReturn instead (this is automatic fo... |
def loadOptions(self, protoFile: FileDescriptorProto):
''' Assigns self.options etc read from protoFile . '''
self.packageName = self.typeNameCase(protoFile.package)
lines = str(protoFile.options).strip().split("\n")
options = (l.split(": ") for l in lines)
kvs = ((i[0], i[1].rep... | The code processes a .proto file by loading its options, then generates output files for messages, enums, and services, adding them to the response. Its main task is to parse proto definitions and produce corresponding code or output files based on the specified options. | def processProtoFile(self, protoFile: FileDescriptorProto,
response: CodeGeneratorResponse):
''' Processes each proto file, adding a new set of output files to the
response. It first sets self.options to a dict of the options read
from protoFile. '''
self... |
def getSuspendKeyword(self) -> str:
''' This is only useful for Kotlin, Swift should return "". '''
return "" if self.swift else "suspend "
def convertTypeName(self, name: str) -> str:
''' Strips any leading qualifier (includes aren't currently supported),
applies self.typeNameCase. ... | The function generates a method signature as a list of strings, handling server/client streaming, callbacks, and formatting. It constructs parameters, return types, and adjusts for suspend keywords, collapsing lines if configured. | def getMethodSignature(self, protoFile: FileDescriptorProto,
serv: ServiceDescriptorProto,
method: MethodDescriptorProto,
withCallbacks = False) -> list[str]:
''' Gets a method signature (without opening brace). If
self... |
def display_board():
print(board[0] + " | " + board[1] + " | " + board[2])
print(board[3] + " | " + board[4] + " | " + board[5])
print(board[6] + " | " + board[7] + " | " + board[8])
def handle_turn(player):
not_valid = True
print(player + "'s turn.")
# There may a case that the person who pla... | The code defines a function `play_game()` that manages a turn-based game loop. It displays the board, handles player turns, checks for win/tie conditions, and switches players until the game ends. If a player wins, it announces the winner; otherwise, it declares a tie. | def play_game():
# it's obvious that we display first, right?
display_board()
global game_is_not_over
while game_is_not_over:
handle_turn(current_player)
check_if_game_is_over()
flip_player()
if winner == "X" or winner == "O":
print(str(winner) + " won.")
e... |
def parse_args_list(required_config_keys):
'''Parse standard command-line args.
Parses the command-line arguments mentioned in the SPEC and the
BEST_PRACTICES documents:
-c,--config Config file
-s,--state State file
-d,--discover Run in discover mode
-p,--properties Properties fil... | The main task of the code is to parse command-line arguments, determine if discovery mode is enabled, generate or use a catalog, expand configuration paths with environment variables, and execute a sync operation using the parsed arguments, catalog, and global state dictionary. | def main():
# Parse command line arguments
args_list = parse_args_list(required_config_keys=REQUIRED_CONFIG_KEYS)
global_state_dict = args_list[0].state
for args in args_list:
# If discover flag was passed, run discovery mode and dump output to stdout
if args.discover:
catal... |
def readLangs(lang1, lines):
# Split every line into pairs and normalize
pairs = [[normalizeString(s) for s in str(l).split('\t')] for l in lines] #here ?
input_lang = Lang(lang1)
return input_lang, pairs
def filterPairsQuestion(pairs):
s = range(len(pairs))
return [pair for pair in pairs if fil... | The function prepares language data by reading and filtering sentence pairs (either questions or answers) from input lines. It processes pairs, adds them to a language object, counts words, and returns the language model, filtered pairs, and indices for further use in training or processing tasks. | def prepareData(lang1, lines, questions = True):
indices = []
if questions:
input_lang, pairs = readLangs(lang1, lines)
pairs, indices = filterPairsQuestion(pairs)
else:
input_lang, pairs, = readLangsAnswers(lang1, lines)
pairs = filterPairs(pairs)
for pair in pairs:
... |
def updated_collatz_dict_with_sequence_starting_at(starting_num, collatz_dict):
"""
Generate the collatz sequence for a given starting number.
Add any unknown values to the collatz_dict and return it.
"""
assert 1 in collatz_dict
collatz_queue = []
gen = gen_collatz_number(starting_num)
... | The function `find_longest_collatz_sequence_under` identifies the starting number below a given `max_number` that generates the longest Collatz sequence. It builds a dictionary mapping starting numbers to their sequence lengths, updating entries iteratively. For each number, if unprocessed, it calculates its sequence l... | def find_longest_collatz_sequence_under(max_number):
"""Return the starting number below the given max_number that has the most terms in its collatz sequence."""
# starting num : sequence count
# must pre-populate for updated_collatz_dict_with_sequence_starting_at to work right.
collatz_dict = {1: 1}
... |
def _reset(self):
self.click = 0
self.helper.setText("New Round")
self.helper.setStyleSheet("background-color: #87ceeb;" "border: 7px solid black;" "color: black")
#Sets 3 cards at top back to blank cards.
pixmap = QPixmap('Cards/blue_back.png')
pixmap = pixmap.scaledToH... | This function manages a card game's interaction logic, handling user guesses and game state transitions. It checks the click count to determine if it's the first or second guess, draws cards, compares values, and triggers win/loss outcomes or hints. When the user loses (click=6), it increments the game counter and rese... | def _controller(self, value):
#If click is 6 this means all 3 cards have been shown and two guess for each card have happened
#This is how the user loses and this will reset the dealer's hand
if self.click == 6:
self.games = self.games + 1
self._reset()
#If the cl... |
def get_orientation(self, line):
orientation = math.atan2(abs((line[3] - line[1])), abs((line[2] - line[0])))
return math.degrees(orientation)
def merge_lines_into_groups(self, lines):
groups = [] # all lines groups are here
# first line will create new group every time
groups.a... | The code categorizes lines into horizontal and vertical based on orientation, sorts them, merges overlapping segments into groups, and returns the merged lines as a numpy array for structured data processing. | def process_lines(self, lines):
lines_horizontal = []
lines_vertical = []
for line_i in [l[0] for l in lines]:
orientation = self.get_orientation(line_i)
# if vertical
if 45 < orientation <= 90:
lines_vertical.append(line_i)
else:
... |
def get_client_info(proposal_account_id, request=None):
query = f"Select name, OwnerId from Account where id = '{proposal_account_id}'"
response = sf_api_call(
f'/services/data/{settings.SF_API_VERSION}/query/',
{'q': query},
request=request,
sf_object='Account'
)['records'][... | The function retrieves the author's information (name, email, phone, and photos) from Salesforce using the OwnerId from the client data associated with the given proposal account ID. It combines this user data with the client's name and returns the result. | def get_proposals_creator(proposal_account_id, request=None):
"""Getting proposal author info.
:param request: Request.
:param proposal_account_id: Account__c from 'get_proposal's response.
:return: Author info.
"""
client = get_client_info(proposal_account_id, request)
user_id = client['O... |
def s3_file_exists(file_name, file_belonging):
if file_belonging == 'dynamic':
file_prefix = settings.KWP_S3_PROPOSAL_DOCS
elif file_belonging == 'static':
file_prefix = settings.KWP_S3_RESOURCES
try:
s3_client.head_object(
Bucket=settings.KWP_S3,
Key=f'{file_... | This function ensures a file exists locally and in an S3 bucket. If the local file is missing, it checks S3; if absent, it retrieves the file via a document link, writes it locally, and uploads it to S3. It returns True if the file is successfully handled, False otherwise. | def get_single_dynamic_file(document_id, file_name, document_path, request=None):
if not os.path.isfile(document_path):
if s3_file_exists(file_name, 'dynamic'):
s3_download_file(file_name, 'dynamic')
else:
document_link = get_document_link(document_id, request)
by... |
def create_sf_session_record(
proposal_id,
proposal_account_id,
contact_id,
device,
ip_address,
ip_geolocation,
):
"""Creating an session record in Salesforce.
:param ip_geolocation: User geolocation.
:param ip_address: User ip address.
:param device: Use... | The function `additional_confirmation` captures the client's IP address, creates a Salesforce session record, checks if a proposal is published, and either raises a 404 error if unpublished or creates a `Session` model entry with metadata like IP, geolocation, and device info. It stores the session ID in the request se... | def additional_confirmation(request, is_contactcreated, proposal, proposal_id):
# client_ip = request.META['REMOTE_ADDR']
client_ip = request.META['HTTP_X_FORWARDED_FOR'].split(',')[0].strip()
if client_ip != '127.0.0.1':
request.session['sf_session_id'] = create_sf_session_record(
propo... |
def get_user_email_information(proposal_account_id, request=None):
"""Getting information corresponding to the provided proposal.
:param request: Request.
:param proposal_account_id: Account__c value from 'get_proposal' requests response.
:return: Info relevant to email address.
"""
query = f"... | The function validates a user's email against authorized domains and existing contacts. It checks if the email matches an authorized entry, returns existing contact details if found, or creates a new contact if validation passes. If no match, it returns False. | def user_email_validation(proposal_account_id, email, request=None):
"""User email validation
:param request: Request.
:param proposal_account_id: Account__c value from 'get_proposal' requests response.
:param email: Provided email address of the user.
:return: contact_id and contact_account_id co... |
def get_trusted_emails():
trusted_emails_records = User.objects.filter(backdoor=True, is_active=True)
trusted_emails = []
if trusted_emails_records.exists():
trusted_emails = trusted_emails_records.values_list('email', flat=True)
return trusted_emails
def create_case_record(
message,
... | This function creates event records in both Django and Salesforce systems by modifying event names based on parameters like time spent or messages, then storing them in Django's SessionEvent model. If the email isn't trusted, it generates a case in Salesforce, linking event details with case IDs. It handles various eve... | def create_event_record(
session_id,
sf_session_id,
event_type,
proposal_name,
contact_account_id,
event_name,
email,
request=None,
contact_id=None,
time_spent=None,
message=None,
document_name=None
):
"""Creating an eve... |
def get_trusted_emails():
trusted_emails_records = User.objects.filter(backdoor=True, is_active=True)
trusted_emails = []
if trusted_emails_records.exists():
trusted_emails = trusted_emails_records.values_list('email', flat=True)
return trusted_emails
def user_email_validation(proposal_account_i... | The function verifies user email authorization for proposal access, logs unauthorized attempts with client details, and redirects to confirmation. It checks session emails against trusted lists or validation, records session data if invalid, and ensures proper access control. | def additional_email_verification(request, proposal_id):
client_ip = request.META['HTTP_X_FORWARDED_FOR'].split(',')[0].strip()
# client_ip = request.META['REMOTE_ADDR']
try:
email = request.session['email']
trusted_emails = get_trusted_emails()
if email in trusted_emails:
... |
def date_string_to_object(str_date):
str_date = str_date.split('-')
date = datetime(year=int(str_date[0]), month=int(str_date[1]), day=int(str_date[2]))
return date
def get_first_flight(self):
limit = 100000
radius = 1000000
latitude = self.latitude
longitude = self.longitude... | The main task of the code is to plan a trip by booking flights within a budget, ensuring timely return home. It starts with the first flight, iteratively adds as many flights as possible within the flight budget, appends a return flight, transfers remaining flight funds to the hotel budget, and books hotels for each ci... | def plan_trip(self):
print("start")
current_day = self.inbounddate
obj_inbounddate = date_string_to_object(current_day)
first_flight = self.get_first_flight()
print("first flight")
if(first_flight != None):
self.tracker.flights.append(first_flight)
e... |
def drac_sysinfo_update(ip, drac_user, drac_pass):
child = pexpect.spawn('/opt/dell/srvadmin/bin/idracadm7 -r ' + ip + ' --nocertwarn -i getsysinfo', timeout=300)
child.expect('UserName: ')
child.sendline(drac_user)
child.expect('Password: ')
child.sendline(drac_pass)
child.expect(pexpect.EOF)
... | The main task of the code is to check and apply BIOS updates on Dell servers via DRAC, parsing command-line arguments for IP and password, retrieving system information, verifying chassis support, checking for pre-scheduled updates on R640 models, determining the next BIOS version, and executing the upgrade if supporte... | def main():
arguments = sys.argv[1:]
drac_pass = ''
drac_ip = ''
try:
opts, _ = getopt.getopt(arguments,"d:p:")
except getopt.GetoptError:
print('Usage:', sys.argv[0], '-d <DRAC IP> -p <read password from file (optional)>')
sys.exit(2)
for opt, arg in opts:
if op... |
def drac_sysinfo_update(ip, drac_user, drac_pass):
child = pexpect.spawn('/opt/dell/srvadmin/bin/idracadm7 -r ' + ip + ' --nocertwarn -i getsysinfo', timeout=300)
child.expect('UserName: ')
child.sendline(drac_user)
child.expect('Password: ')
child.sendline(drac_pass)
child.expect(pexpect.EOF)
... | The code parses command-line arguments to obtain a DRAC IP and optional password file, retrieves system information from a DRAC device, checks if the chassis model is supported for firmware upgrades, identifies the next required DRAC firmware version, and performs the upgrade. It includes error handling for missing inp... | def main():
arguments = sys.argv[1:]
drac_pass = ''
drac_ip = ''
try:
opts, _ = getopt.getopt(arguments,"d:p:")
except getopt.GetoptError:
print('Usage:', sys.argv[0], '-d <DRAC IP> -p <read password from file (optional)>')
sys.exit(2)
for opt, arg in opts:
if op... |
def handler_init(event):
logger.debug('Received event: %s' % json.dumps(event, default=json_serial))
physical_resource_id = None
manifest_file = None
create_kubeconfig(event['ResourceProperties']['ClusterName'])
if 'HttpProxy' in event['ResourceProperties'].keys() and event['RequestType'] != 'Delet... | The main task of the code is to create a Kubernetes resource using a manifest file, process its output, and stabilize a job if it's a batch resource (non-cronjob). It returns the resource's selfLink. | def create_handler(event, _):
physical_resource_id, manifest_file = handler_init(event)
if not manifest_file:
return physical_resource_id
outp = run_command("kubectl create --validate=false --save-config -o json -f %s" % manifest_file)
helper.Data = build_output(json.loads(outp))
if helper.... |
def handler_init(event):
logger.debug('Received event: %s' % json.dumps(event, default=json_serial))
physical_resource_id = None
manifest_file = None
create_kubeconfig(event['ResourceProperties']['ClusterName'])
if 'HttpProxy' in event['ResourceProperties'].keys() and event['RequestType'] != 'Delet... | The code updates a Kubernetes resource by applying a manifest file using `kubectl apply`, parses the JSON output, and returns the resource's selfLink. If no manifest is provided, it returns the physical resource ID. | def update_handler(event, _):
physical_resource_id, manifest_file = handler_init(event)
if not manifest_file:
return physical_resource_id
outp = run_command("kubectl apply --validate=false -o json -f %s" % manifest_file)
helper.Data = build_output(json.loads(outp))
return helper.Data["selfL... |
def heuristic_wrapper(curr_state, agent_id):
is_final = gge.is_final_state(curr_state)
#print(is_final)
if is_final is not None:
if (int(is_final)-1) == agent_id:
return WON
else:
return LOSE
return smart_heuristic(curr_state,agent_id)
def Probability_Func(self, s... | This function implements an Expectimax algorithm with depth limit L to evaluate game states, returning the optimal value and move. It alternates between maximizing the agent's choices (when turnFlag=0) and calculating expected values from chance events (when turnFlag=1), using heuristics for terminal states or depth ex... | def rb_expectimax_L(self, curr_state, agent_id,L):
if gge.is_final_state(curr_state) or L == 0:
return (heuristic_wrapper(curr_state, agent_id)+L, None)
turnFlag = 1
if agent_id == curr_state.turn:
turnFlag = 0
neighbors= curr_state.get_neighbors()
if turn... |
def _get_max_wire_amps(self, diameter_millimeters: float) -> float:
return self.battery_voltage / self.calculate_resistance_ohms(diameter_millimeters, self.coil_turns)
def force(self, distance_meters: float, current_amps: float, diameter_meters: float) -> float:
return (self.coil_turns*current_amps)**2 ... | The code simulates electromagnetic force calculations for varying coil and wire parameters (voltage, diameter, turns, distance, current) to find configurations producing force exceeding a threshold. It iterates through combinations, writes valid results to a CSV file, and uses tqdm for progress tracking. The goal is to... | def find_optimal_values(self, path: str):
with open(path, "w+") as f:
f.write(
"Current (Amps),Coil Diameter (Millimeters),Wire Diameter,Distance (Millimeters),Turns,Voltage,Force (Newtons)\n")
for voltage in [7.4, 9, 110, 220]:
print(f"Now doing {voltage}... |
def _get_max_wire_amps(self, diameter_millimeters: float) -> float:
return self.battery_voltage / self.calculate_resistance_ohms(diameter_millimeters, self.coil_turns)
def force(self, distance_meters: float, current_amps: float, diameter_meters: float) -> float:
return (self.coil_turns*current_amps)**2 ... | This function checks if an electromagnetic coil produces sufficient force. It calculates maximum allowable current based on wire diameter, compares input current against this limit, computes electromagnetic force using coil parameters, and checks if the resulting force exceeds a predefined threshold. It outputs "Suffic... | def see_if_em_produces_required_force(self, current_amps, coil_diameter_millimeters, wire_diameter_millimeters, turns, voltage, distance_millimeters=10):
self.battery_voltage = voltage
self.coil_diameter_millimeters = coil_diameter_millimeters
self.coil_turns = turns
max_amps = int(self.... |
def get_names(self, soup: BeautifulSoup) -> list[str]:
return self.get_class_text(soup, "chartlist-name")
def get_artists(self, soup: BeautifulSoup) -> list[str]:
return self.get_class_text(soup, "chartlist-artist")
def get_timestamps(self, soup: BeautifulSoup) -> list[datetime]:
return list(
map(
... | The main task of the code is to extract and return five distinct data categories—names, artists, timestamps, albums, and epochs—from an HTML page parsed by BeautifulSoup, using specialized helper methods. It consolidates these extracted lists into a single tuple for structured output. | def get_page_data(
self, soup: BeautifulSoup
) -> tuple[list[str], list[str], list[datetime], list[str], list[str]]:
return (
self.get_names(soup),
self.get_artists(soup),
self.get_timestamps(soup),
self.get_albums(soup),
self.get_epochs(soup),
) |
def get_single_list_page_soup(self, page_num: int) -> BeautifulSoup:
return BeautifulSoup(self.get_page(page_num), "html.parser")
def merge_data(
self,
names: list[str],
artists: list[str],
timestamps: list[datetime],
albums: list[str],
epochs: list[str],
) -> list[dict]:
return [
... | The main task of the code is to retrieve and merge song data from multiple pages, handling caching and delays, then return a flattened list of song dictionaries. | def get_songs(self, pages: list[int]) -> list[dict]:
songs = []
for page_num in pages:
if not is_cached(page_num, self.cache_folder):
sleep(self.delay)
soup = self.get_single_list_page_soup(page_num)
songs.append(self.merge_data(*self.get_page_data(soup)))
return flatten_list(son... |
def cross_validated_lasso_regression(data, dependentVar, factorNames, options):
'''cross_validated_lasso_regression takes in a dataset and returns the factor loadings using lasso regression and cross validating the choice of lambda
INPUTS:
data: pandas df, data matrix, should constain the date column an... | The function `relaxed_lasso_regression` performs a hybrid LASSO and OLS regression to estimate factor loadings. It first fits a LASSO model (with cross-validation if specified) to select non-zero coefficients. If all coefficients are zero, it returns a null model. Otherwise, it runs OLS on the non-zero LASSO features, ... | def relaxed_lasso_regression(data, dependentVar, factorNames, options):
'''cross_validated_lasso_regression takes in a dataset and returns the factor loadings using lasso regression and cross validating the choice of lambda
INPUTS:
data: pandas df, data matrix, should constain the date column and all of... |
def linear_regression(data, dependentVar, factorNames, options):
'''linear_regression takes in a dataset and returns the factor loadings using least squares regression
INPUTS:
data: pandas df, data matrix, should constain the date column and all of the factorNames columns
dependentVar: string, n... | The function `run_factor_model` executes a specified regression model (e.g., OLS, LASSO, CVLASSO) using provided data and hyperparameters. It accepts a pandas DataFrame, dependent variable name, list of independent variable names, a method string, and an options dictionary. The function standardizes options and dispatc... | def run_factor_model(data, dependentVar, factorNames, method, options):
'''run_Factor_model allows you to specify the method to create a model, returns a model object according to the method you chose
INPUTS:
data: pandas df, must contain the columns specified in factorNames and dependentVar
dep... |
def make_X(df):
"""
takes Pandas dataframe where first column is PatientSeqID, all other columns are encodings and returns a numpy
array of just data; order preserved
"""
# assuming the vectorized dataframes are all constructed with only column 0, PatientSeqID,
# to be removed from the values
... | The function `make_clusters` performs clustering (DBSCAN, Hierarchical, KMeans) on input data using PCA or UMAP for dimensionality reduction. It processes the dataframe by removing NaNs, extracts features, and applies clustering algorithms. Results are stored in a dataframe, optionally visualized, and saved as CSV if s... | def make_clusters(curr_df, output_path, save_csv=True, visualize=True):
"""
takes dataframe and output path and finds clusters using DBScan, Hierarchical, KMeans clustering with PCA or UMAP
dimensionality reduction
:param curr_df: data to be clustered in dataframe
:param output_path: where to save t... |
def get_driver(url: str) -> WebDriver:
try:
from webdriver_manager.chrome import ChromeDriverManager
exc_path = ChromeDriverManager().install()
service = ChromeService(exc_path)
driver = webdriver.Chrome(service=service)
driver.get(url)
except Exception as exc:
lo... | The main task of the code is to automate logging into a website using provided credentials, retrieve and structure class schedule data based on a timezone, optionally serialize and cache the data to a file if specified, and ensure proper cleanup by closing the browser driver. It handles exceptions during execution and ... | def main(save_cache=False):
driver = None
try:
config = get_config()
driver = get_driver(config['url'])
login(driver, config['username'], config['password'])
class_table = build_class_table(driver, config['timezone'])
if save_cache:
conf_dir = get_config_locat... |
def bump_clock_w_event(
self,
customer_request_id: int,
interface: str,
comment: str,
incoming_clock: int = None):
"""Bumps the internal to the next logical tick tracking the event"""
self.___bump_clock(incoming_clock)
self.write_logica... | This method processes incoming customer events by updating logical clocks, logging event details, and handling three event types (QUERY, DEPOSIT, WITHDRAW) with appropriate business logic, returning transaction responses while maintaining distributed system consistency through event propagation and clock synchronizatio... | def MsgDelivery(self,request, context):
"The message handler"
if request.customer_id == self.id:
self.bump_clock_w_event(
request.customer_request_id,
branch_pb2.event_type_enum.Name((request.event_type)), # pylint:disable=no-mem... |
def _ensure(self):
if not os.path.isdir(self.__configdir__):
os.makedirs(self.__configdir__, mode=0o755)
if not os.path.isfile(self.__configfile__):
with open(self.__configfile__, "wb") as config:
config.write(bson.dumps({}))
def _read(self):
with open(sel... | The code initializes a configuration system for an expense tracker by setting up a configuration directory and file path, ensuring the directory exists, reading the configuration file, initializing default configurations if missing (with test data in debug mode), and ensuring current month data is present. | def __init__(self):
super(Configuration, self).__init__()
self.__configdir__ = os.path.join(
os.environ.get("HOME"), ".config", "expense_tracker"
)
self.__configfile__ = os.path.join(self.__configdir__, "expense_tracker.conf")
self.__config__ = None
self._ensu... |
def getDb():
if not __db.is_connected():
__db.reconnect()
return __db
def get_tax(product_id):
'''Returns the tax of a product'''
__db = getDb()
cursor = __db.cursor()
query = f"SELECT price FROM Products WHERE id = {product_id}"
cursor.execute(query)
price = cursor.fetchone()
tax = price[0]*0.08... | This function creates an order transaction by checking product stock availability, validating quantity against stock, inserting order details into the database, updating product stock, and committing the transaction. It returns stock-related messages if insufficient stock exists, otherwise processes the order with calc... | def create_order_transaction(product_id,customer_id,quantity,payment_type,order_date):
'''Creates an order transaction'''
__db = getDb()
cursor = __db.cursor()
query_check_stock=f"SELECT Stock FROM Products WHERE id = {product_id}"
cursor.execute(query_check_stock)
stock=cursor.fetchone()
if stock[0]==0... |
def exist(state):
if(os.path.isfile('./'+savfiles[state])):
return False
else:
return True
def loadCsv(filename):
file = open(filename, "r")
lines = csv.reader(file)
dataset = list(lines)
for i in range(len(dataset)):
dataset[i] = [float(x) for x in dataset[i]]
ret... | The code's main task is to load and split datasets for different states, train a classification model by summarizing training data, predict test set outcomes, calculate accuracy, and handle state-specific model retrieval and evaluation. It checks if a state exists, processes data, trains or retrieves precomputed summar... | def main(state):
if exist(state):
filename = modelfiles[state]
splitRatio = 0.9
dataset = loadCsv(filename)
trainingSet, testSet = splitDataset(dataset, splitRatio)
# prepare model
summaries[state] = summarizeByClass(trainingSet)
saving(summaries[state],state)... |
def exist(state):
if(os.path.isfile('./'+savfiles[state])):
return False
else:
return True
def loadCsv(filename):
file = open(filename, "r")
lines = csv.reader(file)
dataset = list(lines)
for i in range(len(dataset)):
dataset[i] = [float(x) for x in dataset[i]]
ret... | The code's main task is to load and process a dataset based on a given 'state', split it into training and test sets, train a model by summarizing class distributions, evaluate model accuracy on test data, and handle existing or non-existing states by retrieving or generating summaries. It prints accuracy metrics, pred... | def main(state):
if exist(state):
filename = modelfiles[state]
splitRatio = 0.9
dataset = loadCsv(filename)
trainingSet, testSet = splitDataset(dataset, splitRatio)
# prepare model
summaries[state] = summarizeByClass(trainingSet)
saving(summaries[state],state)... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.