dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def Login():
username = st.text_input("username")
password = st.text_input("Password")
data = loadfile()
alluser = data["users"]
if st.button("Login"):
for everyusr in alluser:
if username == everyusr["username"] and password == everyusr["password"]:
st.sess... | The main task of the code is to manage user authentication and navigation in a Streamlit app. It checks the user's session state: if "Guest," it displays a sidebar menu for Login, Signup, or testing; if "User," it redirects to a dashboard. The code routes users to appropriate functions based on their role, ensuring acc... | def main():
if st.session_state["users"] == "Guest":
with st.sidebar:
selected = option_menu("Menu", ["Login", "Signup", "testing"], icons = ["house", "person"])
if selected == "Login":
Login()
elif selected == "Signup":
Signup()
elif selecte... |
def get_s3_object_as_string(key):
"""Retrieves the S3 object as a string"""
return s3.get_object(Bucket=bucket_name, Key=key)['Body'].read()
def restore_zones(timestamp, zones, dryrun):
"""Restores the zones"""
restored = 0
for zone in zones:
if (zone := create_zone_if_not_exist(zone)) is No... | The code restores AWS Route 53 zones and health checks from a specified or latest S3 backup timestamp, filtering excluded zones by ID/name from the event. It returns a status message indicating restored counts, with dryrun support for simulation. | def handle(event, context):
"""Handles the restore"""
if event.get('from', False):
timestamp = event['from']
else:
timestamp = get_s3_object_as_string('latest_backup_timestamp').decode()
zones = json.loads(get_s3_object_as_string(f'{timestamp}/zones.json'))
if zone_ids := event.get... |
def create_canvas(self, bridge: BridgeCalculator):
(min_x, min_y, max_x, max_y) = bridge.get_enclosing_rectangle()
vertical_span = max_y - min_y
horizontal_span = max_x - min_x
scale_factor_vertical = vertical_span ** -1 * BridgeGUI.HEIGHT_TARGET
scale_factor_horizontal = horizo... | The code's main task is to render a bridge structure by creating a canvas, drawing its beams, and visualizing external forces. It orchestrates the rendering process by sequentially invoking methods to set up the drawing area, depict structural elements, and illustrate applied forces, likely for analysis or visualizatio... | def draw_bridge(self, bridge: BridgeCalculator):
self.create_canvas(bridge)
self.draw_beams(bridge)
self.draw_external_forces(bridge) |
def generate_separable_psi(n, n_states):
n_qubits = []
psi = [] # the total n-qubit state psi to be returned
states = [] # the list of all component states, order is from LSB to MSB
index_tool = [] # a binary operation tool used to generate psi
temp_sum = 0
n_qubit_upper = n - n_s... | The code evaluates the accuracy of a separability detection algorithm on random quantum states. It runs multiple trials, generates separable states, prepares them, and checks if they are correctly identified as separable. It calculates accuracy, execution time, and records valid state configurations for analysis. | def main():
start = time.time()
n = 10 # The total number of qubits
n_states = 3 # The total number of component states
n_trials = 50 # The total number of trials
acc = 0
separable_states = [] # List of state configurations that have been CORRECTLY IDENTIFIED to be separable
# psi = ... |
def generate_random_state(n_qubit): # generate a random normalized state of n_qubit qubits
state = []
for _ in range(2 ** n_qubit):
state.append(complex(random.randint(-10, 10), random.randint(-10, 10)))
return normalize(state)
def multiply(state1, state2): # given two component states, where ... | The code evaluates the accuracy and efficiency of an algorithm for separating quantum states across various qubit partitions. It runs multiple trials for each partition, measuring success rate (accuracy) and time taken, then visualizes results with dual-axis bar charts comparing accuracy and efficiency. | def test(n_trials=50):
situations = [[1, 1], [1, 2], [1, 3], [2, 2], [1, 4], [2, 3], [1, 5], [2, 4], [3, 3], [1, 6], [2, 5], [3, 4],
[1, 7], [2, 6], [3, 5], [4, 4], [1, 8], [2, 7], [3, 6], [4, 5], [1, 9], [2, 8], [3, 7], [4, 6], [5, 5]] # situations to be tested
accuracies = []
time... |
def determine_raid_date(input):
date_regex = r'^(([0-9])|([0-2][0-9])|([3][0-1]))\-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\-2[0-2]{1}$'
find_date = re.match(date_regex, input.strip())
if find_date:
return {
"raid_date_provided": True,
"raid_date": datetime... | The main task of the code is to validate and parse user-provided raid parameters to create a structured raid event. It checks input format, extracts date/time, ensures logical validity (e.g., future datetime), separates title/location via '@', and stores creator details. If any validation fails, it returns errors; othe... | def create_raid(raid_params, chat_id, raid_creator_id, raid_creator_username):
# Stage 1: Validate Raid Params.
# a) At a very basic level the raid params must be at least 10 chars.
if len(raid_params) < 10:
return { "error": "Correct format is as follows (note: date is optional)\n/newraid... |
def add_node(self, node_id: int, pos: tuple = (0, 0, 0), org_nodes=None, outer_edges=None) -> bool:
if outer_edges is None:
outer_edges = []
if org_nodes is None:
org_nodes = []
node_src = self.nodes.get(node_id)
# check that the node is not in the graph
i... | This code initializes a graph structure by loading nodes and edges from a JSON file. It processes node positions, adding nodes with coordinates from the JSON or defaulting to (0,0,0) if missing. Edges are added if not already present. If no JSON file is provided, it generates random node locations. | def __init__(self, jsonfile: str = None):
self.nodes: dict[int, Node] = {}
self._numOfEdges = 0
self._mc = 0
if jsonfile is not None:
with open(jsonfile, 'r') as jsonFile:
json_object = json.load(jsonFile)
jsonFile.close()
# read th... |
def set_location(self):
dict_min_max = self.caclulate_minmax()[0]
for i in self.nodes.values():
if i.geolocation == (0, 0, 0):
# check if the given min and max values are correct
if (dict_min_max[0] != sys.maxsize and dict_min_max[1] != sys.maxsize
... | The main task of the code is to visualize a graph using Pygame by plotting nodes and edges based on their geolocation data. It scales coordinates to fit the screen, draws lines between connected nodes with distinct colors for matching nodes, and labels each node with its identifier. The loop handles user input to close... | def graph_plot(self):
pygame.init()
scr = pygame.display.set_mode((900, 650))
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
scr.fill((255, 255, 255))
sel... |
def findExposed(self):
self.exposed.clear()
for node in self.graph.nodes.values():
if node.match is None or node != node.match.match:
self.exposed.append(node)
def resetNodes(self):
for node in self.graph.nodes.values():
node.parent = None
node... | This code implements a maximum matching algorithm using BFS to find augmenting paths. It iteratively searches for paths to improve the matching by alternating edges, distracts blossoms when paths are found, and updates exposed nodes. The loop continues until no more augmenting paths exist or only one exposed node remai... | def findMatching(self):
augmentingPathFound = True
self.findExposed()
# we check for augmenting path until no such path exist from each exposed node or if only one exposed node left
while augmentingPathFound and len(self.exposed) > 1:
augmentingPathFound = False
f... |
def run_analysis(actual_gw_dir, pred_gw_dir, grace_csv, out_dir, input_gmd_file=None, use_gmds=True,
actual_gw_pattern='GW*.tif', pred_gw_pattern='pred*.tif', generate_plots=True, gmd_train=False,
input_train_shp_file=None, rev_train_test=False, gmd_exclude_list=None, load_gmd_train_te... | The function performs model analysis to compare actual and predicted groundwater levels against GRACE TWSA data across multiple use cases. It processes input directories, generates time series data, and creates visualization plots (either general or GMD-specific) to evaluate predictive accuracy. The analysis aggregates... | def run_analysis2(actual_gw_dir, pred_gw_dir_list, grace_csv, out_dir, input_gmd_file=None, use_gmds=True,
actual_gw_pattern='GW*.tif', pred_gw_pattern='pred*.tif'):
"""
Run model analysis to get actual vs predicted graph along with GRACE TWSA variations for different use cases
:param actu... |
def first_move(self, turn: int) -> None:
"""
1) predict all winning plays depending on the first play
2) fill the tree with all winning plays
"""
for i in range(3):
for j in range(3):
if self.board[i][j] == 0:
next_turn = 1 if turn ... | The main task of the code is to determine and return the best move by invoking `first_move`, `proba`, and `best_move` methods, then resetting the `tree` and `probabilities` data structures for 9 positions before returning the computed best move. | def move(self) -> int:
"""
call the others functions and reset needed values
"""
self.first_move(self.num)
self.proba()
best = self.best_move()
self.tree = [[] for _ in range(9)]
self.probabilities = [[] for _ in range(9)]
return best |
def process(formula):
formula = reformat(formula)
items = formula.split(' ')
if len(items) == 1:
return [None, [], items[0]]
return mainConnective(items)
def generate(vars):
values = [0, 1]
command = ""
count = 0
for i in vars:
for j in range(count):
command =... | The code generates a truth table for logical expressions by processing each property, substituting variable values from generated combinations, evaluating results, and compiling them into a table with variable assignments and outcomes. | def ttable(self):
stacks = []
for i in self.props:
stack = process(i)
stacks.append(stack)
rows = generate(self.vars)
self.table = []
for row in rows:
bl = {}
for i in range(len(self.va... |
def createLogger(name):
dir_path = 'tests/'
logger = logging.getLogger(name)
logger.setLevel(logging.DEBUG)
file_handler = logging.FileHandler(dir_path+name)
formatter = logging.Formatter('%(asctime)s: %(levelname)s %(message)s')
file_handler.setFormatter(formatter)
logger.addHandler(file_... | The main task of the code is to run end-to-end tests on an application, including corner case tests, performance tests (evaluating generator functions across varying input sizes), and common error tests (repeating operations to detect frequent issues). It logs test results, counts errors, and reports performance and co... | def end_to_end(app, n):
print("Running tests...")
data_path = "data/"
logger = createLogger("log")
runCornerCaseTests(app, data_path, logger)
perf_errors = 0
gen_logger = createLogger("gen_log")
print(" Perfomance tests...")
for _, val in generators.__dict__.items():
if cal... |
def get_quadrant_index_of_position(line: int, column: int) -> int:
quadrant_line = int(line / 3)
quadrant_column = int(column / 3)
quadrant_index = quadrant_column + (quadrant_line * 3)
return quadrant_index
def position_is_in_quadrant(line: int, column: int, quadrant_index_of_position: int) -> bool:
... | This function checks if placing a number in a specific Sudoku cell would block other cells in the same row, column, or quadrant by iterating through potential conflicts in those regions. It evaluates if the number's placement violates constraints by checking for existing numbers in the row, column, or quadrant, returni... | def blocking_numbers_in_line_or_column(number: int, line: int, column: int, sudoku_to_work_on: array) -> bool:
quadrant_index_of_position: int = get_quadrant_index_of_position(line, column)
line_quadrantrelative = line % 3
column_quadrantrelative = column % 3
for current_column in range(0, 9):
i... |
def get_quadrant_index_of_position(line: int, column: int) -> int:
quadrant_line = int(line / 3)
quadrant_column = int(column / 3)
quadrant_index = quadrant_column + (quadrant_line * 3)
return quadrant_index
def same_number_in_line_or_column(number: int, sudoku_to_work_on: array, line_index=None, column... | The function checks if a given number can be placed in a specific Sudoku cell by verifying there are no duplicates in the same row, column, or 3x3 quadrant, and no blocking numbers that would invalidate the placement. It returns True if valid, False otherwise. | def determine_if_number_fits_in_field(number: int, line: int, column: int, sudoku_to_work_on: array) -> bool:
quadrant_index = get_quadrant_index_of_position(line, column)
if (same_number_in_line_or_column(number, sudoku_to_work_on, line, column)
or number_is_in_quadrant(number, quadrant_index, sudoku_to_w... |
def yo_from_glycs(spectrum, glycan_data, tol = 0.01):
"""
Returns list of probable Y0 peaks in spectrum by subtracting known possible glycan masses from raw peptide mass of the spectrum
Keyword Arguments
spectrum -- Spectra object to search
glycan_data -- List of glycan masses
tol -- m/z error ... | The function identifies probable Y0 glycopeptide candidates by validating mass differences between spectral peaks and known glycan masses (e.g., HexNAc, Fucose). It prioritizes candidates based on charge states (1–4+), peak chain length, and specific glycan validation rules. The algorithm iterates through peaks, checks... | def glycan_traverse_and_validate(spec, glycan_data, tol = 0.01):
"""
Returns probable Y0 candidate ---------
Keyword Arguments
spec -- Spectra object to search
glycan_data -- List of glycan masses
tol -- m/z error tolerance for mass matching
Optimisations
- Prioritise picking: Leng... |
def set_terr(self):
''' Lets the user add territories. '''
lines = self.box.get("1.0","end-1c").splitlines()
lines = [x for x in lines if x != '']
if len(lines) != 0:
# Makes dict to hold territories and their states
self.controller.set_territories({key: [] for ke... | This code initializes a GUI page for entering territory names via a text box, with "Next" and "Use Default Territories" buttons to proceed, and a "Cancel" button that hides when user inputs text. It sets up labels, input fields, and event handlers for navigation and data entry. | def __init__(self, parent, controller):
PageLayout.__init__(self, parent)
self.controller: tkinterApp = controller
# Instructions, Territory box and Next button
self.instructions = ttk.Label(self, text="Enter territory names, each on their own line", font=("Times", 15))
self.in... |
def make_nursing_home_sheets(frame: gui.SheetsPage, df, outpath):
''' Makes the nursing home sheets based on options chosen by the user. Saves them to a folder chosen by the user. '''
if TESTING:
print("------- USING TEST VALUES FOR NURSING HOME -------")
# Update the screen
frame.instructions.c... | The main task of the code is to generate output sheets from three healthcare datasets (NursingHomes, HomeHealth, LongTermCare) by creating dedicated folders for each dataset in the specified output path and calling specialized functions to process the corresponding dataframes with a GUI frame. | def make_sheets(frame: gui.SheetsPage, nursing_home_df, home_health_df, long_term_care_df, outpath):
''' Calls all functions that make sheets. '''
# Make a folder for each dataset.
datasets = ["NursingHomes", "HomeHealth", "LongTermCare"]
for dataset in datasets:
folder_path = f"{outpath}/{data... |
def isNegated(tok):
negations = {"no", "not", "n't", "never", "none"}
for dep in list(tok.lefts) + list(tok.rights):
if dep.lower_ in negations:
return True
return False
def getSubsFromConjunctions(subs):
moreSubs = []
for sub in subs:
# rights is a generator
righ... | This function extracts all subject tokens related to a given verb `v` in a linguistic analysis. It checks for negation, identifies direct subjects (excluding determiners), and extends results with conjunctive subjects if none are found. It returns the list of subjects and the negation status for further processing. | def getAllSubs(v):
verbNegated = isNegated(v)
subs = [tok for tok in v.lefts if tok.dep_ in SUBJECTS and tok.pos_ != "DET"]
if len(subs) > 0:
subs.extend(getSubsFromConjunctions(subs))
else:
foundSubs, verbNegated = findSubs(v)
subs.extend(foundSubs)
return subs, verbNegated |
def getAllSubs(v):
verbNegated = isNegated(v)
subs = [tok for tok in v.lefts if tok.dep_ in SUBJECTS and tok.pos_ != "DET"]
if len(subs) > 0:
subs.extend(getSubsFromConjunctions(subs))
else:
foundSubs, verbNegated = findSubs(v)
subs.extend(foundSubs)
return subs, verbNegated
... | The code extracts subject-verb-object (SVO) triples from a list of tokens, identifying verbs (excluding auxiliaries), their subjects, and objects. It checks for negation in verbs or objects, appending negation markers if present. The result is a list of SVO tuples with negated verbs marked, capturing syntactic relation... | def findSVOs(tokens):
svos = []
verbs = [tok for tok in tokens if tok.pos_ == "VERB" and tok.dep_ != "aux"]
for v in verbs:
subs, verbNegated = getAllSubs(v)
# hopefully there are subs, if not, don't examine this verb any longer
if len(subs) > 0:
v, objs = getAllObjs(v)
... |
def getAllSubs(v):
verbNegated = isNegated(v)
subs = [tok for tok in v.lefts if tok.dep_ in SUBJECTS and tok.pos_ != "DET"]
if len(subs) > 0:
subs.extend(getSubsFromConjunctions(subs))
else:
foundSubs, verbNegated = findSubs(v)
subs.extend(foundSubs)
return subs, verbNegated
... | The code extracts subject-verb-object (SVO) triples from tokenized text, identifying verbs, their subjects, and objects with adjectives. It handles negation markers for verbs and objects, normalizes terms, and constructs SVO triples with negation indicators when present, returning a list of formatted triples. | def findSVAOs(tokens):
svos = []
verbs = [tok for tok in tokens if tok.pos_ == "VERB" and tok.dep_ != "aux"]
for v in verbs:
subs, verbNegated = getAllSubs(v)
# hopefully there are subs, if not, don't examine this verb any longer
if len(subs) > 0:
v, objs = getAllObjsWith... |
def findSVAOs(tokens):
svos = []
verbs = [tok for tok in tokens if tok.pos_ == "VERB" and tok.dep_ != "aux"]
for v in verbs:
subs, verbNegated = getAllSubs(v)
# hopefully there are subs, if not, don't examine this verb any longer
if len(subs) > 0:
v, objs = getAllObjsWith... | The code processes incoming Twitter data by cleaning and normalizing tweet text, extracting key phrases using NLP (spaCy), analyzing sentiment with TextBlob, and updating MongoDB and Firebase databases with volume/sentiment statistics. It also stores raw tweets in MongoDB and daily JSON files, while handling retweets a... | def on_data(self, data):
try:
#This is where we start getting tweets
client=MongoClient(MONGO_HOST)
db=client.twitterdb
print(type(data))
ok=json.loads(data)
print(type(ok))
db.tweets.insert(ok)
i=ok
... |
def create_output_doc():
columns = ['Title', 'Link', 'Summary', 'Analyst(s)', 'Published', 'Doc ID']
dataframe = pd.DataFrame(columns=columns)
return dataframe
def create_url(url_str, page_num, search_term):
search_term = search_term.replace(" ", "%20")
url_str = url_str.replace('<Search_Term>', sea... | The code scrapes Forrester's website using provided search terms, collects document links, extracts data from these documents, and exports the aggregated results into a CSV file. It generates URLs, parses web pages, filters relevant reports, and compiles findings into a structured DataFrame before saving it as 'forrest... | def get_csv(search_terms):
results_df = create_output_doc()
url_str = 'https://www.forrester.com/search?tmtxt=<Search_Term>&searchOption=10001&page=<Page_Num>&dateRange=2'
link_list = []
for search_term in search_terms:
search_url = create_url(url_str, '1', search_term)
search_soup = g... |
def create_output_doc():
columns = ['Title', 'Link', 'Summary', 'Analyst(s)', 'Published', 'Doc ID']
dataframe = pd.DataFrame(columns=columns)
return dataframe
def create_url(url_str, page_num, search_term):
search_term = search_term.replace(" ", "+")
url_str = url_str.replace('<Search_Term>', searc... | The code's main task is to search for documents using multiple search terms on a specified website, extract relevant document links, scrape data from these documents, compile the results into a DataFrame, and save the collected data as a CSV file named 'idc.csv'. The function returns the populated DataFrame after expor... | def get_csv(search_terms):
results_df = create_output_doc()
url_str = 'https://www.idc.com/search/advanced/perform_.do?page=<Page_Num>&hitsPerPage=25&sortBy=RELEVANCY&lang' \
'=English&srchIn=ALLRESEARCH&src=&athrT=10&aq=<Search_Term>&aq=&aq=&aq=&op=ALL&op=ANY&op=EXCLUDE&op=EXACT' \
... |
def create_output_doc():
columns = ['Title', 'Link', 'Summary', 'Analyst(s)', 'Published', 'Doc ID']
dataframe = pd.DataFrame(columns=columns)
return dataframe
def create_url(url_str, page_num, search_term):
search_term = search_term.replace(" ", "%20")
url_str = url_str.replace('<Search_Term>', sea... | The code scrapes Gartner's website to collect document links based on input search terms, processes the links to extract relevant reports, gathers data from each report page, appends results to a DataFrame, and exports the compiled data as a CSV file named 'gartner.csv' | def get_csv(search_terms):
results_df = create_output_doc()
url_str = 'https://www.gartner.com/en/search?keywords=<Search_Term>&page=<Page_Num>'
link_list = []
for search_term in search_terms:
search_url = create_url(url_str, '1', search_term)
search_soup = get_soup(search_url)
... |
def get_instance_type(region_name="us-east-1"):
# Create a Boto3 EC2 client
ec2_client = boto3.client("ec2", region_name=region_name)
# Get information about the current instance using the instance metadata service
instance_id_url = "http://169.254.169.254/latest/meta-data/instance-id"
instance_id_... | The main task of the code is to benchmark a machine learning model on AWS Neuron instances by loading a pre-trained model, compiling it for specific hardware (inf1/inf2), and evaluating its performance with sample inputs. It handles model compilation, device placement (CUDA/Neuron), and executes inference without gradi... | def main():
instance_type = get_instance_type("us-west-2")
batch_size = 1
num_neuron_cores = 2
is_neuron = True
# define sequence lengths to benchmark
sequence_lengths = [8]
for sequence_length in sequence_lengths:
# load tokenizer and model
tokenizer_class, model_class =... |
def show_percolation_diagram(size, bins, start):
"""
Shows diagram of percolational phase transition - size of the biggest cluster as a function of average degree.
Args:
size: size of considered net
bins: number of histogram's bins
start: optional variable to figures numbering
"... | The function `show_diagrams` generates and displays multiple diagrams (percolation, fluctuations, cluster size distribution, and average cluster size) for a given network size. It uses specified bin counts for visualizations, optionally prints fitted parameters, and handles missing files by notifying the user. The task... | def show_diagrams(size, print_parameters=True, start=0, percolation_diagram_bins=200, fluctuations_diagram_bins=200):
"""
Shows all diagrams.
Args:
size: size of considered net
print_parameters: if is True prints chi^2 and values with errors of fitted C and alpha parameters
start: o... |
def handle_game_launch():
state.frg.image = assets.image_assets["img_start_screen_C"]
state.game_level = 0
def handle_start_screen():
if key_handler[key.RIGHT]:
state.frg.image = assets.image_assets["img_start_screen_D"]
if key_handler[key.LEFT]:
state.frg.image =... | The code updates the game state by handling level transitions, detecting collisions between game objects, updating object positions, managing object spawning/removal, tracking virus counts, updating UI elements, and checking for player death to transition to game over. | def update(dt):
if state.game_level == -1:
handle_game_launch()
elif state.game_level == 0:
handle_start_screen()
elif state.game_level == -2: # game over
handle_level_change()
elif state.game_level > 0 and state.game_level < 5 and state.time_counter... |
def agent_calculate_difference(self):
return(self.move_calculate_difference(self.x, self.y))
def get_possible_moves(self):
# empty list for possible moves
possible_moves = []
if self.x > 0:
possible_moves.append([self.x-1, self.y])
if self.x < roo... | The code's main task is to determine if the agent can improve its position by evaluating possible moves. It calculates the current difference, checks each possible move's potential new difference, and updates the agent's coordinates if a move reduces the difference. If no improvement is found, it returns False. | def move(self):
current_difference = self.agent_calculate_difference()[2]
possible_moves = self.get_possible_moves()
if current_difference > 0.5:
for move in possible_moves:
new_difference = self.move_calculate_difference(move[0],move[1])
... |
def agent_calculate_difference(self):
return(self.move_calculate_difference(self.x, self.y))
def get_possible_moves(self):
possible_moves = []
# create local variables from methods to reuse
w = room.get_width()
h = room.get_height()
# get 9 possible locat... | The code determines whether an agent should move by evaluating possible moves to minimize a calculated difference. It checks if the current difference is below a threshold, retrieves valid moves, calculates their potential differences, selects the move with the smallest difference, and updates the agent's position if i... | def move(self):
current_difference = self.agent_calculate_difference()[2]
# margin of error for difference
if current_difference <= 0.5:
return False
move_list = self.get_possible_moves()
# if no valid moves exit
if len(move_list) == 0:
re... |
def setup_db_conn():
# create a connection to the PostgreSQL database
engine = create_engine('postgresql://postgres:system@localhost:5432/spotevent')
return engine
def import_prep_data(username, engine):
# select all songs matching user and filter for ones with a popularity over 45 and genre
song_da... | The main task of the code is to recommend events to a user based on their preferences, including mapped music genres, preferred venues, and price range. It imports and processes user data, generates event recommendations, scores them, and returns the top 20 event IDs along with their details. The code also prints inter... | def main(username):
# Setup database connection
engine = setup_db_conn()
# song_data, artist_data, event_data, user_quiz_venues, user_quiz_genres, events, min_price, max_price, user_saved_recommendations, unique_combined_genres = import_prep_data(username, engine)
# Import and prepare data
all_use... |
def read_train_data(args, tokenizer, logger):
if args.debug:
args.train_batch_size = 8
train_path = os.path.join(args.data_dir, args.train_file)
train_set = read_absa_data(train_path)
train_examples = convert_absa_data(dataset=train_set, verbose_logging=args.verbose_logging)
train_features ... | The code defines a script for fine-tuning a BERT model for aspect-based sentiment classification or similar NLP tasks. It parses command-line arguments for model configuration, training settings, and data paths. The script loads a pre-trained BERT model, prepares training/evaluation data, trains the model using specifi... | def main():
parser = argparse.ArgumentParser()
## Required parameters
parser.add_argument("--bert_config_file", default="/data/bert-large-uncased/bert_config.json",
type=str,
required=False,
help="The config json file corresponding to ... |
def get_static_metrics(self, function_ea):
"""
The function calculates all supported metrics.
@function_ea - function address
@return - function metrics structure
"""
f_start = function_ea
f_end = idc.find_func_end(function_ea)
function_metrics = Metrics_f... | The main task of the code is to perform static metrics analysis on functions within the ".text" segment of a binary. It iterates through each function, skips library/thunk functions and already analyzed ones, collects specified metrics using `get_static_metrics`, stores them in `self.functions`, and aggregates total me... | def start_analysis(self, metrics_used):
"""
The function starts static metrics analysis.
@metrics_used - a dictionary of metrics used in the following format {metrics_list element:1 or 0}
PTAL metrics_list global list and args_parser routine
@return - None
"""
sel... |
def handle_li(self):
# check list stack to determine style and depth
list_depth = len(self.tags['list'])
if list_depth:
list_type = self.tags['list'][-1]
else:
list_type = 'ul' # assign unordered if no tag
if list_type == 'ol':
list_style = ut... | This code processes HTML start tags during document conversion, mapping them to DOCX elements. It handles tags like <span>, <ol>, <br>, <hr>, <hX>, <img>, and <table>, appending attributes, creating paragraphs/runs, applying styles, and managing bookmarks. Special logic handles line breaks, horizontal rules, headings, ... | def handle_starttag(self, tag, attrs):
if self.skip:
return
if tag == 'head':
self.skip = True
self.skip_tag = tag
self.instances_to_skip = 0
return
elif tag == 'body':
return
current_attrs = dict(attrs)
if... |
def print_board(board):
for row in board:
print(" | ".join(row))
print("-" * 9)
def human_move(board):
while True:
try:
row = int(input("Enter the row (0, 1, or 2): "))
col = int(input("Enter the column (0, 1, or 2): "))
if board[row][col] == " ":
... | The main task of the code is to implement a tic-tac-toe game where a human player competes against an AI. The game alternates turns, with the human choosing moves and the AI using the best_move function for its decisions. The loop continues until a player wins or the board fills with a tie, displaying results and updat... | def play_game():
board = [[" " for _ in range(3)] for _ in range(3)]
current_player = "X"
while True:
print_board(board)
if current_player == "X":
row, col = human_move(board)
else:
print("AI is making a move...")
row, col = best_move(board)
... |
def _init_players(players, num_players):
for i in range(num_players):
player = player_class.Player(id=i + 1)
players.append(player)
def ante_up(players, ante, pot):
for player in players:
print("Player " + str(player.id) +
". Please press enter to confirm your ante of " + s... | The code simulates a multi-player poker game. It initializes players, collects antes, shuffles and deals cards, facilitates a betting round, and summarizes the round. The main task is to manage a poker game flow with ante contributions, card dealing, betting mechanics, and result summarization for multiple players. | def play_game(num_players):
deck = deck_class.Deck()
players = []
pot = 0
ante = 2
_init_players(players, num_players)
print("Welcome. You are playing a " + str(num_players) +
"player game of poker where everyone starts with 20 chips. We'll start by ante-ing up.")
#ante, shuffle
... |
def mainTester():
tourValueTest()
swapHeuristicTest()
twoOptHeuristicTest()
greedyTest()
def mainEuclidianTester():
# both graphs will be smaller than the cities50 example
nodes1 = random.randint(5, 10)
print("--- RESULTS FOR FIRST EUCLIDIAN GRAPH ---")
print("Number of nodes: ", nodes1)... | The main task of the code is to execute a series of test functions—`mainTester`, `mainEuclidianTester`, `mainMetricTester`, and `mainNonMetricTester`—likely to evaluate or compare different algorithms, metrics, or methodologies, such as Euclidean distance calculations, metric properties, and non-metric behaviors. The `... | def main():
mainTester()
mainEuclidianTester()
mainMetricTester()
mainNonMetricTester() |
def tourValue(self):
total_cost = 0
for i in range(len(self.perm)):
# consider the special case where the whole list has been explored
if i == len(self.perm) - 1:
# add the 'wraparound' edge to the total cost
total_cost = total_cost + self.dists[se... | This function solves the Traveling Salesman Problem (TSP) using a greedy heuristic with follow-up distance optimization. It iterates through all possible starting nodes, constructs a path by selecting the next closest unexplored node, and prioritizes nodes with minimal subsequent distances. After generating a candidate... | def ownSolverTSP(self, n):
for start in range(self.n):
# copy the contents of self.perm
copy_perm = [i for i in range(self.n)]
# and remove 0 (the first node in self.perm)
copy_perm.remove(start)
# we begin from index 1, since we first explore node 0
... |
def __categorize_words(string, language="en"):
"""
Categorize a string if it contains one of the words in the
categories dictionary based on the language. If the string
doesn't contains any of that words, the string will not be modified.
:param string: the string that can be categorized.
:param... | The function processes an ingredient string to extract individual ingredient words by removing numbers, special characters, punctuation, stopwords, adjectives, and extra whitespaces. It lowercases the input, strips quotes, and applies optional stemming. If categorization fails, it sequentially removes non-essential ele... | def process_ingredients(ing, stem=True, language="en"):
"""
Process all the ingredients string in order to retrieve only the word
correspond to the single ingredients, without number, special charachters,
punctuation, stopwords, adjectives and multiple whitespaces.
:param ing: the string correspond... |
def _format_validation_response(result: bool, formatted_sql: str, last_statement: str, error: str) -> Dict:
return {"result": result, 'sql': formatted_sql, 'last_statement': last_statement, 'error': error}
def _validate_statement_type(self, statement: str) -> Optional[str]:
unsupported_statements = self... | This code validates the last SQL statement in provided input by checking for unsupported statement types and expressions. It formats the SQL, splits into statements, and ensures the final statement is supported. If unsupported elements are found, it returns a validation response with details. Otherwise, it attempts to ... | def validate(self, data: Dict) -> Dict:
sql = data.get('data', '')
formatted_sql = sqlparse.format(sql, strip_comments=True)
statements = sqlparse.split(formatted_sql)
if not statements:
return self._format_validation_response(False, formatted_sql, None, "No SQL statement f... |
def file_mode():
array_mod = []
array_exponent = []
array_congr = []
for i,n in enumerate(args.n):
N,E = extract_pubkeyInfo(parse_der_pubkey(read_pubkey_from_file(n)))
array_mod.append(N)
array_congr.append(read_message_from_file(args.c[i]))
array_exponent.append(E)
if not array_exponent.count(array_expone... | The code solves a system of congruences using the Chinese Remainder Theorem (CRT), verifies pairwise coprimality of moduli, computes the global congruence solution, and checks if the result is a valid RSA-encrypted message by verifying its e-th root. It handles input via command-line arguments or files, outputs the dec... | def main():
if not len(args.n) == len(args.c):
print("Modulus or congruence relation missing")
exit()
if args.files:
array_mod,array_congr,pubexp = file_mode()
else:
array_mod = args.n
array_congr = args.c
if not check_coprimes_all(array_mod,len(array_mod)):
print("Modulus integer set must be pairwise... |
def find_loops(begin: FlowNode, graph: FlowGraph, depth_limit: int = 100) -> list[list[Address]]:
"""Returns a list of cycles in a function graph starting from a node given by 'begin'."""
cycles = []
queue: deque[tuple[Address, list[Address]]] = deque() # use BFS with a path of previously traversed nodes
... | This function generates assembly code from a control flow graph (FlowGraph), writing output to specified files. It processes branch/jump tables, assigns memory regions, creates address labels, and outputs MIPS64 assembly with headers, jump tables, and metadata. Optional loop reduction and randomization are applied base... | def generate_code_from_graph(graph: FlowGraph, out: TextIO, branch_data: BinaryIO, jump_data: BinaryIO, ram_table: TextIO,
reduction_type: str, reduction_factor: int, name: str = "", seed: int = 0,
trace_path: str = "") -> None:
"""
TODO: write a docstri... |
def _handle_signal(self, signal: ParseSignal):
if signal.sig == SignalType.RESTART:
self._reset(signal.data)
else:
raise Exception(f'Unknown ParseSignal of type {signal.sig}')
def _handle_metric(self, metric: MetricData):
if metric.type == MetricType.LOADSTORE_ADDRESS:
... | The main task of the code is to construct a control flow graph (CFG) by processing trace data. It iterates through parsed lines, handling signals/metrics, tracking instruction flow (e.g., branches, delay slots), updating nodes/edges in the graph, managing state transitions (like reset/pending operations), and applying ... | def build(self) -> FlowGraph:
for line in self.trace_parser:
if isinstance(line, ParseSignal):
self._handle_signal(line)
continue
elif isinstance(line, MetricData):
self._handle_metric(line)
continue
num, pc, i... |
def get_child_nodes(self, string, checker):
self.main_board.from_string(string)
# checker = "O"*(checker == "X") + "X"*(checker == "O")
child_nodes = []
for i in range(self.width):
if self.main_board.can_add_to(i):
self.main_board.add_checker(checker, i)
... | This code performs a tree search using a neural network to evaluate nodes, updating node values iteratively. It loads a neural network model, initializes a search tree, and applies the UCB1 algorithm to select the optimal move. The process iterates to refine node evaluations, ultimately choosing the best child node bas... | def run_tree_search_with_neural_network(self, filename):
child_directory = {}
with open(filename, 'rb') as loads:
NN = pickle.load(loads)
nodes = {}
board = self.first_board.to_string()
child_directory[board] = self.get_child_nodes(board, self.checker)
nodes[b... |
def plot_forceX(self,start_time, end_time, smooth = 0):
start = int(start_time * 100)
end = int(end_time * 100)
if(start <0 or start > self.bio_data.shape[0]):
print("start time out of range")
elif(end <0 or end > self.bio_data.shape[0]):
print("end time out of ra... | This function calculates average peak values for forces (X, Y, Z), torques (X, Y, Z), and normal force/torque over a specified time range. It processes positive and negative peaks separately, computes their means, and returns two lists: one with average positive peaks and another with average negative peaks across all ... | def plot_all_in_range(self,start_time, end_time, smooth = 0):
x_peaks, x_neg_peaks = self.plot_forceX(start_time, end_time, smooth = smooth)
y_peaks, y_neg_peaks = self.plot_forceY(start_time, end_time, smooth = smooth)
z_peaks, z_neg_peaks = self.plot_forceZ(start_time, end_time, smooth = smoot... |
def get_access_token(user_id):
return jwt.encode({
'exp': datetime.datetime.utcnow() + datetime.timedelta(seconds=get_config('api', 'jwt.exp')),
'user_id': user_id
}, get_config('api', 'jwt.secret'), algorithm='HS256')
def guess_user_data(data):
if 'username' not in data:
data['usern... | This function handles OAuth registration or login by checking if a user exists via GitHub or email. If not, it creates a new user, adjusts data like username, removes passwords, and returns an access token and user object. | def oauth_register_or_login(data, provider):
authed_user = User.select().where(User.github == data['github']).first()
if not authed_user:
if 'email' in data:
authed_user = User.select().where(User.email == data['email']).first()
if authed_user.exists():
query = {}... |
def _get_scfermi(self, file_efrom):
"""
read formation energies of defects, POSCAR, totdos
"""
self.scfermi = Scfermi.from_file(file_efrom)
def _run_scfermi(self, Tanneal, Tfrozen):
"""
run scfermi
1. calculate equilibrium concentrations of defects at Tanneal
... | The code calculates the Shockley-Read-Hall (SRH) recombination rate by retrieving SCFERMI data, running SCFERMI with specified temperatures, reading trap information, and computing R_SRH using the Vs parameter. | def calculate_SRH(self):
self._get_scfermi(tlc.SCFERMI_FILE)
self._run_scfermi(self.Tanneal, self.T)
self._read_traps()
self.R_SRH = self.__get_R_SRH(self.Vs) |
def eval_bisection(xl, xu, epislon, iterations, equation):
iterator = 1
e_a = 10000.0
flag = True
table = tk.Toplevel(project1)
table.geometry("500x500")
table.title("result")
iteration_label1 = tk.Label(table, text="#")
iteration_label1.grid(row=0, column=0)
iteration_label2 = tk.La... | The code creates a GUI window for the bisection method, allowing users to input lower/upper bounds, iterations, and tolerance. It includes text fields for parameters and buttons to retrieve values or execute the method. The "Evaluate" button triggers a function with these inputs, while the "Enter" button likely capture... | def bisection():
bisectionW = tk.Toplevel(project1)
bisectionW.geometry("300x150")
bisectionW.title("Bisection")
xl_label = tk.Label(bisectionW, text="Enter Lower Bound:")
xl_label.grid(row=0, column=0)
xl = tk.Text(bisectionW, height=1, width=21)
xl.grid(row=0, column=1)
xu_label = tk.L... |
def get_bucket_location(bucket_name: str):
result = regional_retryable_s3_client(lambda x: x.get_bucket_location(Bucket=bucket_name))
return result.get('LocationConstraint')
def is_bucket_public_accessible(bucket_name: str):
grants = get_bucket_acl(bucket_name)
return len(list(
filter(lambda gra... | The code checks an S3 bucket's properties by retrieving its location, determining if it's publicly accessible, and listing public objects. It compiles this information into a dictionary, appending it to the provided result list for reporting or further processing. | def check_bucket(bucket_name: str, result):
print(f"checking bucket {bucket_name}")
bucket_location = get_bucket_location(bucket_name)
is_bucket_public = is_bucket_public_accessible(bucket_name)
public_accessible_object_keys = get_public_accessible_objects_in_bucket(bucket_name, bucket_location)
re... |
def update_marked_text_for_rule(textfile, rules):
try:
f = open(textfile)
text = f.read()
except:
print('Could not open textfile ' + textfile)
exit(1)
for rule in orwell.ALL_RULES:
print('Checking ' + rule + '...')
if rule not in rules:
start = orwell.start_tag_with_rule(rule, True)
end = orwell.e... | The code compares human and computer-generated text annotations using specified rules. It processes two input files, applies the rules to generate marked texts, and evaluates their lengths and accuracy by comparing the outputs. | def main():
marked_file = sys.argv[1]
unmarked_file = sys.argv[2]
rules = sys.argv[3].split(',')
human_marked = update_marked_text_for_rule(marked_file, rules)
computer_marked = export_marked_textfile(unmarked_file, rules)
print('Human len: ' + str(len(human_marked)))
print('Comp len: ' + str(len(computer_marke... |
def create_regex_strings():
stopwords_regex = "("
# print(stopwords.words('english'))
for word in stopwords.words('english'):
stopwords_regex = stopwords_regex + word + "|"
stopwords_regex = stopwords_regex[:-1] + "|an)"
# print(stopwords_regex)
punctuation_regex = r"[“”!\"#$%&'\(\)*+,-.... | The code identifies metaphor trigrams in a text by matching them with possible stopwords and punctuation, records their positions, and returns non-overlapping ranges of these matches for highlighting. | def rule1m_ranges_in_text(article):
article = article.lower()
word_list = ''
highlight_bucket = []
tag_list = []
stopwords_regex, punctuation_regex = create_regex_strings()
metaphor_list = read_article_for_metaphor(article)
for trigram in metaphor_list:
# print(trigram)
tri... |
def aggregate_similes_candidates(input_dir):
fList=os.listdir(input_dir)
# Create a list of file names with full path, eliminating subdirectory entries
fList1 = [os.path.join(input_dir, f) for f in fList if os.path.isfile(os.path.join(input_dir, f))]
#max_files = 1000 #remove to get the entire c... | The function `train` processes simile data by aggregating candidates from an input directory, training a frequency-sorted corpus, and saving top similes. It filters candidates by minimum frequency, initializes a corpus for matching, and stores the result as a pickle file. The outputs are the raw candidates and sorted f... | def train(input_dir, min_simile_freq):
similes_candidates = aggregate_similes_candidates(input_dir)
count_dict, sorted_counts = train_similes_corpus(similes_candidates)
# create actual corpus and save
top_similes_corpus = init_corpus_2match([(-1, item[0].split(' ')) for item in count_dict.items() if ... |
def create_regex_strings():
stopwords_regex = "("
# print(stopwords.words('english'))
for word in stopwords.words('english'):
stopwords_regex = stopwords_regex + word + "|"
stopwords_regex = stopwords_regex[:-1] + "|an)"
# print(stopwords_regex)
punctuation_regex = r"[“”!\"#$%&'\(\)*+,-.... | This function identifies and tags specific ngrams in a text using a pre-trained classifier, extracting their positions after processing for stopwords, punctuation, and overlapping regions. It tokenizes the input, generates bigrams, predicts relevant terms, and returns non-overlapping tag ranges indicating their locatio... | def rule5_ranges_in_text(article):
clf = joblib.load('static/linear_jargon_classifier.pkl')
mngram_list_by_sent = []
manual_list = []
stopwords_regex, punctuation_regex = create_regex_strings()
sentences = nltk.sent_tokenize(article)
words = nltk.word_tokenize(article)
ngram_list = []
... |
def setObjectsByBboxes(self, bboxes):
self.objects = [self.convertBboxToObject(b) for b in bboxes]
def findNewObjects(self, bboxes):
new_objs = []
for n in bboxes:
exist = False
for o in self.objects:
if not compare(o.bbox, n, self.center_distance_threshol... | This code processes input bounding boxes to update a list of tracked objects. It converts input bboxes to a list, initializes objects if empty, identifies new objects, merges existing ones, removes outdated objects, and extends the object list with newly detected objects. The main task is to maintain and update a dynam... | def run(self, bboxes):
if isinstance(bboxes, np.ndarray):
bboxes = bboxes.tolist()
if not self.objects:
self.setObjectsByBboxes(bboxes)
return
new_objs = self.findNewObjects(bboxes)
self.mergeObjects(bboxes)
self.removeObjects()
se... |
def resolve_base_dir(base_dir: Path | None = None) -> Path:
if base_dir is not None:
return base_dir.resolve()
elif base_directory is not None:
return base_directory.resolve()
else:
raise ValueError("Unknown base directory")
def mod_exists(mod_id: str, base_dir: Path | None = None) -... | This function identifies the latest version of a mod by first resolving its base directory, verifying its existence, then filtering and sorting available versions by date and subversion to return the most recent date and subversion pair, or None if no versions exist. | def select_latest_version(mod_id: str,
base_dir: Path | None = None) -> tuple[str, str] | None:
real_base_dir = resolve_base_dir(base_dir)
if not mod_exists(mod_id, real_base_dir):
raise ValueError("Mod {mod_id} does not exist")
versions = get_mod_versions(mod_id, real_base... |
def get_mod_ids(base_dir: Path | None = None) -> list[str]:
real_base_dir: Path = resolve_base_dir(base_dir)
mod_dirs = list(filter(lambda p: p.is_dir(), (real_base_dir / 'mods').iterdir()))
mod_ids = list(map(lambda d: d.parts[-1], mod_dirs))
return mod_ids
def is_mod_active(mod_id: str, base_dir: Pat... | This function identifies file conflicts between active mods by mapping shared files to the set of mods involved. It collects active mod directories, tracks files in each mod, groups paths by mod sets, and filters out non-conflicting entries before returning the result. | def parse_mod_conflicts() -> dict[frozenset[str], set[Path]]:
mod_dirs: set[Path] = set()
for mod_id in get_mod_ids():
if not is_mod_active(mod_id):
continue
version_tuple = select_active_version(mod_id)
if version_tuple is None:
continue
date, sub = versi... |
def __create_maze(self) -> None:
# start values of x,y
y, x = 1, 1
stack = Stack()
stack.push((y, x))
while True:
if stack.is_empty():
# all of points were visited
break
y, x = stack.top()
# mark current poin... | This method generates a maze by creating its structure, setting start and end points, marking it as created, and initializing the maze's visited status. | def create(self) -> None:
"""This method generates a maze."""
self.__create_maze()
self._set_start_and_stop_elems()
self._is_created = True
self.__set_maze_as_not_visited() |
def get_joined_bagfiles(path):
bagfiles = list()
for root, directories, files in os.walk(path):
for file in files:
if file.endswith('joined.bag'):
bagfiles.append(os.path.join(file))
bagfiles.sort()
return bagfiles
def get_travel_loggers(path):
travel_loggers = li... | The code processes ROS bagfiles by updating travel loggers with data from each bagfile, saving logger history and dynamic obstacle data to text files, and moving processed bagfiles to a designated directory. It handles unindexed bagfiles by skipping the move operation and logs exceptions. The process involves retrievin... | def process():
bagfiles = get_joined_bagfiles(MERGED_BAGFILES_DIR)
for bagfile in bagfiles:
print("Processing bagfile: ", bagfile)
move = True
travel_loggers = get_travel_loggers('config/maps/')
try:
update_travel_logger(bagfile, travel_loggers)
except rosb... |
def move(shape, offset):
return [(x + offset[0], y + offset[1]) for x, y in shape]
def max_height_total(rocks):
return max([y for x, y in rocks], default=0)
def move_wind(shape, wind, wind_index, rocks):
if wind[wind_index] == ">":
return try_move(shape, (1, 0), rocks), (wind_index + 1) % len(wind)
... | The code simulates falling rock shapes in a wind environment, tracking their positions and calculating the maximum height after 2022 iterations. It uses wind input to move shapes, drops them until they rest on existing rocks, and updates the rock set. The final output is the maximum height of the accumulated rocks. | def main():
wind = util.get_input(17)[:-1]
#wind = ">>><<><>><<<>><>>><<<>>><<<><<<>><>><<>>"
wind_index = 0
rocks = {(x, 0) for x in range(7)}
i = 0
while i < 2022:
shape = shapes[i % len(shapes)]
shape = move(shape, (2, max_height_total(rocks) + 4))
shape_start = shap... |
def move(shape, offset):
return [(x + offset[0], y + offset[1]) for x, y in shape]
def max_height_total(rocks):
return max([y for x, y in rocks], default=0)
def move_wind(shape, wind, wind_index, rocks):
if wind[wind_index] == ">":
return try_move(shape, (1, 0), rocks), (wind_index + 1) % len(wind)
... | This function simulates dropping a rock shape into a grid, applying wind movement, and settling it when it can no longer fall. It retrieves the next shape, positions it above existing rocks, applies wind displacement, and repeatedly moves the shape downward until it collides with existing rocks. The settled shape is th... | def drop_rock(rocks, shape_gen, wind, wind_index):
shape = next(shape_gen)
shape = move(shape, (2, max_height_total(rocks) + 4))
shape, wind_index = move_wind(shape, wind, wind_index, rocks)
while all(s not in rocks for s in move(shape, (0, -1))):
shape = move(shape, (0, -1))
shape, ... |
def drop_rock(rocks, shape_gen, wind, wind_index):
shape = next(shape_gen)
shape = move(shape, (2, max_height_total(rocks) + 4))
shape, wind_index = move_wind(shape, wind, wind_index, rocks)
while all(s not in rocks for s in move(shape, (0, -1))):
shape = move(shape, (0, -1))
shape, ... | This code simulates falling rocks in a wind pattern, tracking their positions and heights. It detects repeating cycles of rock configurations and wind indices to calculate the height increase per cycle. Using this, it extrapolates the final height after 1e12 rocks by combining precomputed cycles with remaining iteratio... | def main2():
wind = util.get_input(17)[:-1]
wind = ">>><<><>><<<>><>>><<<>>><<<><<<>><>><<>>"
wind_index = 0
rocks = {(x, 0) for x in range(7)}
#rocks = leaky_set(1000, rocks)
one_cycle = len(wind) * len(shapes)
shape_gen = itertools.cycle(shapes)
rock_sets = []
rocks_fallen_per_cyc... |
def multiply_size_by_orientation(item,n,m,orientation):
if orientation == ORIENTATION_VERTICAL:
n,m = m,n
w = n * item.width
h = m * item.height
return w,h
def visible_base(img,hflip=False,vflip=False,name="VisibleBase"):
'''copy visible to layer, then flip horizontally and/or vertically'''
... | The code generates a mirrored image of the input based on the specified orientation by resizing the image, creating a mirrored layer, flipping it, and merging it into the original image using GIMP's Python API. | def reflect(img,orientation):
'''abut visible with its mirror image'''
w,h = multiply_size_by_orientation(img,2,1,orientation)
img.resize(w,h,0,0)
nextlayer = visible_base(img,name="Mirror")
nextlayer = flip_orient(nextlayer,orientation)
pdb.gimp_image_merge_down(img,nextlayer,0) |
def scale_to_fibonacci(img,squareflag):
'''
rescale img so that its pixel counts in horiz and vertical dimension are
successive (or if img is square, equal) Fibonacci numbers.
if squareflag is set, then make img square first, so scaled is also square
'''
if squareflag:
scale_to_square(im... | This function generates a Fibonacci spiral pattern on an image by creating and positioning layers according to Fibonacci sequence growth. It adjusts for square/rectangular aspects, rotates layers, applies blend/opacity settings, and manages layer merging. The spiral is built by iteratively scaling, rotating, and offset... | def fibonacci_spiral(img,aspect,q_turn,blend,opacity,merge_down):
'''
Third attempt at a fibonacci spiral, with new options,
and ability to work with landscape, portrait, or square images
img: image
aspect: 1 for square, 0 for rectangle
q_turn: number of quarter-turns per new layer
blend: ... |
def visible_base(img,hflip=False,vflip=False,name="VisibleBase"):
'''copy visible to layer, then flip horizontally and/or vertically'''
## copy visble to layer
layer = pdb.gimp_layer_new_from_visible(img,img,name)
img.add_layer(layer,-1)
## and flip if needed
layer = flip(layer,hflip,vflip)
... | This code generates a jagged border on an image by creating and manipulating layers with selections, inversions, and blending modes. It adjusts the border shape (horizontal, vertical, or elliptical), applies blur, handles white/black border color, adds a one-pixel border if specified, and fills interior islands. The pr... | def jagged_border_run(img,layer,border_shape,border_white,border_size,
thresh,fill_islands,one_pixel_border):
## add two new layers
tmp_layer = visible_base(img,name="tmp")
cpy_layer = visible_base(img,name="border")
## black layer
pdb.gimp_edit_fill(tmp_layer,WHITE_FILL)
pdb.... |
def visible_base(img,hflip=False,vflip=False,name="VisibleBase"):
'''copy visible to layer, then flip horizontally and/or vertically'''
## copy visble to layer
layer = pdb.gimp_layer_new_from_visible(img,img,name)
img.add_layer(layer,-1)
## and flip if needed
layer = flip(layer,hflip,vflip)
... | This code transforms a high-aspect-ratio image into a horizontal figure-eight shape by padding, resizing, dividing the image into four sections, applying transformations (flipping, rainbow effects), repositioning layers, and adding a background. It ensures layer alignment and offsets to minimize artifacts, creating a s... | def infinity(img,bkg_color,pad_degrees=0,vfix=0):
'''bend a high-aspect ratio image into a horizontal figure-eight'''
pad = pad_degrees/(720-2*pad_degrees)
if pad > 0:
pixpad = int(pad*img.width)
new_width = img.width + 2*pixpad
img.resize(new_width,img.height,pixpad,0)
## make ... |
def __authorize(self, headers: dict, force: bool = False) -> dict:
logger.debug("Trying to authorize request")
id_token = None
if self.__id_token and not force:
logger.debug("Using cached ID token for request authentication")
id_token = self.__id_token
elif ... | The main task of the code is to send an authorized POST request to the SpaceKnow API with provided data, handle potential JWT token expiration by reauthorizing and retrying the request, and return the JSON response. It includes logging status codes, checking for error messages indicating expired tokens, and recursively... | def request(self, api_url: str, data: dict) -> json:
"""Send authorized request to the spaceknow api endpoint
Args:
api_url (str): Api url endpoint
data (dict): Data to send
Returns:
json: Response data json
"""
request_headers = {
... |
def binarify(e):
'reduces products with more than two terms in binary product'
e=sympify(e)
f=e.func
ar=e.args
if f==sympy.core.power.Pow:
f=sympy.core.mul.Mul
ar=(ar[0],)*ar[1]
if ar==():
return e
e1=binarify(ar[0])
if len(ar)==1:
return f(e1,evaluate=Fal... | The function `iterateStream` computes the first $ N $ coefficients of the unique stream solution $ \sigma $ for a system of differential equations $ F $, given initial conditions $ \rho $. It processes the equations using `binarify` and `horner`, initializes a dictionary to track subterms, and iteratively updates it to... | def iterateStream(F,xlist,rho,N):
'''
Computes first N=10 coefficients of the unique stream solution sigma of E s.t. sigma(0)=r0
Args:
- F: system of stream differential equations.
- xlist: variables appearing in system F.
- rho: initial condition for system F.
- N: numb... |
def send_error(self, code, message=None, explain=None):
"""Send and log an error reply."""
try:
shortmsg, longmsg = self.responses[code]
except KeyError:
shortmsg, longmsg = '???', '???'
if message is None:
message = shortmsg
if explain is None... | This method processes a single HTTP request by reading the request line, checking for URI length limits, parsing the request, and sending a response. It handles errors like excessively long URIs (414) and timeouts (408), logging issues and closing connections when necessary. If parsing succeeds, it triggers `_respond()... | def handle_one_request(self):
"""Handle a single HTTP request."""
try:
self.raw_requestline = self.rfile.readline(65537)
if len(self.raw_requestline) > 65536:
self.requestline = ''
self.request_version = ''
self.command = ''
... |
def load_tokenizer(args):
tokenizer = AutoTokenizer.from_pretrained(args.model_name)
return tokenizer
def get_training_validation_set(args, logger, tokenizer, r_state, has_val, num_classes):
# sanity check: args.gen_val is used when there is no validation set
if has_val:
assert not args.gen_val
... | The code prepares datasets for a text classification task with injected noise. It loads training, validation, and test data using a tokenizer, creates `TextBertDataset` instances with noisy labels for training/validation and clean labels for testing, and returns these datasets along with placeholder variables for unlab... | def prepare_data(args, logger, r_state, num_classes, has_val, has_ul):
# used for experiments with injected noise
tokenizer = load_tokenizer(args)
tr_data, val_data = get_training_validation_set(args, logger, tokenizer, r_state, has_val, num_classes)
test_data = load_and_cache_text(args, tokenizer, log... |
def prepare_empty_input(self, data):
img_meta = data['img_meta']
img_shape = img_meta.data['pad_shape'] \
if isinstance(img_meta, DC) else img_meta[0].data['pad_shape']
user_inputs = [[np.zeros(img_shape[:2], dtype=np.float64)] for _ in range(len(self.CLASSES))]
r... | The code processes user inputs by generating points, drawing them on images, combining with original data, and preparing ground truth information for model training. It initializes points, modifies image tensors, extracts labels, and ensures sufficient user input data for subsequent tasks. | def prepare_user_input(self, data, idx):
user_inputs, img_shape = self.prepare_empty_input(data)
points_list, userinput_bbox_list = self.init_points_list(data)
user_inputs, userinput_bbox_list = self.draw_points(data, points_list, img_shape, user_inputs, userinput_bbox_list)
use... |
def prepare_empty_input(self, data):
img_meta = data['img_meta']
img_shape = img_meta.data['pad_shape'] \
if isinstance(img_meta, DC) else img_meta[0].data['pad_shape']
user_inputs = [[np.zeros(img_shape[:2], dtype=np.float64)] for _ in range(len(self.CLASSES))]
r... | This function prepares and modifies input data for a model by initializing or updating user inputs and bounding box information. It handles cases based on iteration count, processes bounding box coordinates to derive centers, fills insufficient user inputs, and combines processed user inputs with image data. The output... | def prepare_noc(self, data, idx):
user_inputs, img_shape = self.prepare_empty_input(data)
if idx not in self.points:
self.points[idx] = []
if self.iter != 0:
user_inputs = self.prepare_noc_point(data, user_inputs, idx, img_shape)
points_list = self.points[i... |
def arg_parser() -> argparse.ArgumentParser:
"""Create argparser for CLI arguments."""
parser = argparse.ArgumentParser(description="Kubernetes workspace manager")
parser.add_argument(
"--user",
help="Username to use. Defaults to the current OS username",
)
parser.add_argument(
... | The code runs a CLI tool that processes command-line arguments, configures an API client using SSH keys and configuration files, and executes actions like starting, connecting, or stopping services based on the provided subcommand. It validates inputs, handles SSH key paths, and interacts with an API to perform operati... | def run() -> None:
"""Run the CLI."""
parser = arg_parser()
namespace = parser.parse_args()
assert isinstance(namespace.subcommand, str)
args = Args(
namespace.subcommand,
namespace.user,
namespace.ssh_key_path,
namespace.api,
namespace.config,
)
fil... |
def title_screen(screen):
start_button = UIElement(
center_position=(240, 250),
font_size=30,
bg_rgb=BLUE,
text_rgb=WHITE,
text='Start',
action=GameState.SELECT_LEVEL
)
quit_button = UIElement(
center_position=(240, 310),
font_size=30,
... | The code manages a Pygame-based game loop with state transitions, handling a title screen, level selection, gameplay (via `play_level` with `Board` objects), game over screen, and quit functionality. It initializes the display, processes game states, and switches between screens or levels based on user input, ultimatel... | def main():
pygame.init()
screen = pygame.display.set_mode((8 * TILE_SIZE, 8 * TILE_SIZE + 100))
game_state = GameState.TITLE
while True:
if game_state == GameState.TITLE:
game_state = title_screen(screen)
if game_state == GameState.NEWGAME_0:
board = Board()
... |
def check_remaining_files(bucket_name,target_name=None):
resp=s3_client.list_objects_v2(Bucket=bucket_name)
print("checking for remaining files:")
#print(resp)
unload_file=None
invalid_file=None
unload_table=None
countvalid=0
countinvalid=0
if 'Contents' in resp:
print("ther... | The code's main task is to load data from an S3 bucket into a MySQL database, ensuring no duplicate processing by checking file existence and prior load status. It creates temporary tables, loads data, and upserts into permanent tables. If the file is split, it handles it from a backup bucket. Post-successful loading, ... | def lambda_handler(event, context):
stage =0
loading_status=0
reload=False # reload if there is successful loading within a fixed time
report=False # reporting process is not started by default
report2=False # if there is a second series of reports
# after the loading lambda is invoked by l... |
def hasSelection(self):
if not self.isValid():
return False
if self.hasMultiLines():
return True
return self._beginPos != self._endPos
def beginLine(self):
return min(self._beginLine, self._endLine)
def endLine(self):
return max(self._beginLine, self._end... | The code checks if a given line number falls within the currently selected range of lines. It returns True if the line is between the start and end lines of the selection, and False otherwise. The method first verifies if a selection exists; if not, it immediately returns False. | def within(self, line):
if not self.hasSelection():
return False
if line >= self.beginLine() and line <= self.endLine():
return True
return False |
def hasSelection(self):
if not self.isValid():
return False
if self.hasMultiLines():
return True
return self._beginPos != self._endPos
def beginLine(self):
return min(self._beginLine, self._endLine)
def beginPos(self):
if self._beginLine == self._endLine:... | This function adjusts the selection's start and end positions to avoid selecting spaces and ensure valid byte selection. It modifies `beginCol` and `endCol` based on modulo 3 checks, handling both normal and reversed selections. Adjustments ensure at least one byte is selected, aligning positions to exclude spaces whil... | def _fixSelection(self, r, c):
if not self.hasSelection():
return
beginCol = self._beginPos
endCol = self._endPos
isRevert = self.beginLine() == r and self.beginPos() == c
if isRevert:
# select one byte at least
if beginCol % 3 == 1 and (begin... |
def contentOffset(self):
if not self._data:
return QPointF(0, 0)
x = self.horizontalScrollBar().value()
return QPointF(-x, -0)
def rowForPos(self, pos):
y = max(0, pos.y())
r = int(y / self._lineHeight)
r += self.firstVisibleLine()
rows = self.lineCo... | The main task of the code is to render a hex editor's viewport by drawing hexadecimal data and corresponding ASCII characters within the specified event area. It calculates visible line ranges, draws vertical separators, handles text selection highlighting, and iterates through data bytes to display hex values and ASCI... | def paintEvent(self, event):
if self._data is None:
return
painter = QPainter(self.viewport())
painter.setFont(self._font)
offset = self.contentOffset()
eventRect = event.rect()
if eventRect.isValid():
startLine = self.rowForPos(eventRect.topLef... |
def _invalidateSelection(self):
if not self._cursor.hasSelection() and \
not self._cursor.isValid():
return
begin = self._cursor.beginLine()
end = self._cursor.endLine()
x = 0
y = (begin - self.firstVisibleLine()) * self._lineHeight
w = self.... | This method handles left mouse clicks to update the cursor position and selection. It checks if data exists, validates the mouse button, maps the click position, determines the cursor location in ASCII view, moves the cursor, starts a timer, and emits a selection changed signal after invalidating the selection. | def mousePressEvent(self, event):
if self._data is None:
return
if event.button() != Qt.LeftButton:
return
self._invalidateSelection()
pos = self.mapToContents(event.pos())
inAsciiView = pos.x() >= self._asciiPosX
r, c = self.rowColForPos(pos, i... |
def _invalidateSelection(self):
if not self._cursor.hasSelection() and \
not self._cursor.isValid():
return
begin = self._cursor.beginLine()
end = self._cursor.endLine()
x = 0
y = (begin - self.firstVisibleLine()) * self._lineHeight
w = self.... | This method handles mouse movement events for left-click selection in a widget. It updates the cursor position based on the mouse location, invalidates the current selection, calculates the corresponding row/column in the data, and emits a selectionChanged signal to notify listeners of the new selection. | def mouseMoveEvent(self, event):
if self._data is None:
return
if event.buttons() != Qt.LeftButton:
return
self._invalidateSelection()
pos = self.mapToContents(event.pos())
r, c = self.rowColForPos(pos, self._cursor.inAsciiView())
self._cursor.se... |
def read_words(path: str):
with open(path, 'r') as file:
words = [word.strip().lower() for word in file.readlines() if not word.isspace()]
return words
def parse_dict(path: str) -> List[Dict]:
dict_text = ''
with open(path, 'r') as file:
dict_text = file.read()
text_entries = dict_... | The main task of the code is to build a dictionary from a list of words, either by appending new entries to an existing dictionary file or creating a new one. It reads words from a source file, checks for existing entries if appending is enabled, filters out duplicates, constructs the dictionary entries, sorts them alp... | def build_and_write_dict(args):
src_path = args['src']
dest_path = args['dest'] if args['dest'] else src_path
words = read_words(src_path)
entries = []
if args['append']:
existing_entries = parse_dict(dest_path)
existing_words = [entry['word'] for entry in existing_entries]
... |
def find_levels(candles):
levels = []
size_mean = np.mean(candles['high']-candles['low'])
for i in range(2,len(candles)-2):
if is_support(candles,i):
val = candles['low'][i]
if is_far_from_levels(val,size_mean,levels):
levels.append(val)
elif is_resist... | The main task of the code is to update a financial chart and associated UI elements with real-time stock data, including price, volume, market cap, and technical levels. It fetches historical candle data, calculates support/resistance levels, updates price indicators, and renders interactive candlestick and volume char... | def update_chart(self):
end_date = datetime.now()
days = 120
start_date = end_date - timedelta(days=days)
candles = pd.DataFrame()
levels = []
tickertxt = self.ticker_text.text().strip().upper()
print("Tickertxt:",tickertxt)
try:
ticker = yq.Ti... |
def create_buy_form(self):
self._buy_form_group = QGroupBox("Buy")
layout = QFormLayout()
self.trade_limit_text = QLineEdit("150")
self.trade_limit_text.textChanged.connect(self.update_limit)
self.ticker_text = QLineEdit()
self.ticker_text.setText("BBBY")
self.set... | The code initializes a UI component by creating a news list table with double-click functionality to open links, setting up a buy form, info box, and chart. It arranges these elements using QHBoxLayout and QVBoxLayout, placing the buy form and info box side-by-side at the top, followed by the chart below, ensuring a st... | def __init__(self):
super().__init__()
self.news_tab = NewsListTable()
self.news_tab.cellDoubleClicked.connect(self.news_tab.open_link)
self.create_buy_form()
self.create_info_box()
self.create_chart()
self.layout = QVBoxLayout(self)
top_part = QHBoxLayou... |
def validate(job):
if isinstance(job, dict):
for k in job_keys:
if k in job:
return True
return False
def Prime(n):
"""
Miller-Rabin primality test.
A return value of False means n is certainly not prime. A return value of
True means n is very likely a prime.
"""
if n!=int(n):
return False
n=int... | (Handle) The code validates a job configuration, initializes a process with `Fact.start()`, executes specific operations (`Prime`, `Memory`, `IO`, `Idle`) based on job keys, and finalizes with `Fact.done()`. It returns errors for invalid jobs or missing required parameters. | def Handle(falco,job,context ):
if not validate(job):
return {"error":"job not defined correctly"}
Fact.start(context, job)
if "prime" in job:
Prime(int(job["prime"]))
elif "memory" in job:
Memory(job["memory"])
elif "IO" in job:
IO(job["IO"])
elif "idle" in job:
Idle(int(job["idle"]))
else:
return... |
def checkLetterCount(self, givenWord):
if '$' in givenWord:
return False
alphaLetter = self.mkAlphabet(self.newLetters)
alphaWord = self.mkAlphabet(givenWord)
for char in alphaLetter:
if alphaWord[char] > alphaLetter[char]: return False
else: return Tr... | This function validates if a set of letters forms a valid word on a board by checking: 1) if letters are in the player's hand, 2) if selected cells are empty, 3) if letters are connected, 4) if they attach to the board, and 5) if permutations match rules. It returns True with valid permutations if all conditions pass, ... | def checkFinalCombination(self, newLetters, allCells, currBoard, filledCells, connected, letters):
if self.checkLetterCount(newLetters):
printStatement = 'All letters are in hand.'
if checkIfFilled(allCells, filledCells):
printStatement = 'Spaces chosen are empty!'
... |
def complete(self, assignment):
"""
Returns True if sudoku is solved and correct. False otherwise.
"""
assignment_board = self.assignment_board(assignment)
for row in assignment_board:
for value in row:
if value not in range(... | The `backtrack` function solves a Sudoku puzzle using recursive backtracking. It checks if the current assignment is complete; if so, it returns the solved board. Otherwise, it selects an unassigned cell, iterates through its domain values, and assigns each value while checking for conflicts. If a valid assignment is f... | def backtrack(self, assignment):
"""
Searches through all possible board states and backtracks if conflict is found
"""
# sudoku complete -> return sudoku as array
if self.complete(assignment):
return self.assignment_board(assignment)
# select cell yet unass... |
def threshold_filter(image, threshold):
func = lambda i: 0 if i < threshold else i
result = list([list(map(func, i)) for i in image])
return np.array(result, dtype='uint8')
def crop_image(image, margin):
"""
Cropping image to the bounds of sudoku
"""
non_zeros_x... | The code overlays solved Sudoku numbers onto an input image, returning the modified image. It reads the image, processes it with thresholding and cropping, maps solved numbers to cell coordinates, and draws them in green using PIL. The result is saved as "output.png" and returned. | def draw_solved(input_image, solved_board):
"""
Draws the completed sudoku onto input image, returns array
"""
input_image = cv.imread(input_image, 0)
input_image = threshold_filter(input_image, 60)
input_image = crop_image(input_image, 0)
solved_board = np.ndarray.flatten(np.array(solved_bo... |
def prefill_assignment(self, assignment=dict()):
"""
If Sudoku happens to have prefilled cells, add them to the assignment
"""
for i in range(self.i):
for j in range(self.j):
if self.sudoku[i][j] != None:
assignment[i,j] = self.sudoku[i][j... | The code solves a Sudoku puzzle by first prefilling the initial assignment, then applying constraint propagation via AC3 to narrow domains. It uses backtracking to explore possible assignments, returning the solution or None if unsolvable. The core task combines AC3 for domain reduction and backtracking for exhaustive ... | def solve(self):
"""
Solve Sudoku Instance.\n
Returns None if no solution.
"""
assignment = self.prefill_assignment()
self.preset_domains()
self.ac3()
return self.backtrack(assignment) |
def add(tasks):
try:
name, text = task()
if name in tasks:
raise exceptions.ExistsException("Task already exists")
tasks[name] = text
deadline.set(name)
print(f"Task '{name}' added.")
except exceptions.ExistsException as e:
print(f"Error: {e}")
def edi... | This code provides a menu-driven interface for managing a task list, allowing users to add, mark, edit, delete, print, sort, clear tasks, or return. It validates user input and handles errors, using external functions for specific operations like marking or sorting tasks. | def menu(name_list, selected_list):
while True:
try:
print(f"\nTask list '{name_list}'\n1. Add task\n2. Mark task\n3. Edit task\n4. Delete task\n5. Print tasks\n6. Sort tasks\n7. Clear tasks\n8. Back")
user_choice = int(input("Select: "))
if user_choice < 1 or user_ch... |
def parse_annot(annot):
fn = annot[0].decode('utf-8')
class_name = annot[1].decode('utf-8')
train_subset_class = annot[2].decode('utf-8')
return fn, class_name, train_subset_class
def is_skip(annot_part):
x1, y1, x2, y2 = rect_coord(annot_part)
_, _, wid, hgt = center_wid_hgt(x1, y1, x2, y2)
... | The function processes training annotations by cropping logos from images and applying data augmentations (shifting, scaling, rotating). It skips invalid images, counts file occurrences, and saves processed images with corresponding metadata. | def crop_and_aug(annot_train):
cnt_per_file = defaultdict(int)
for annot in annot_train:
# for generating a file name
fn, _, _ = parse_annot(annot)
cnt_per_file[fn] += 1
# skip if width or height equal zero
if is_skip(annot[3:]):
print('Skip: ', fn)
... |
def _angle_between_points(point_a, point_b):
return math.atan2((point_b.y - point_a.y), (point_b.x - point_a.x))
def _are_angles_equal(angle_a, angle_b, tolerance):
return (abs(angle_a - angle_b) < tolerance) or (abs(_normalize_rad(angle_a) - _normalize_rad(angle_b)) < tolerance)
def _deg_to_rad(deg):
retur... | This code aligns a robot's orientation toward a target location by spinning until its angle matches the target's direction within a 5-degree tolerance. It then moves the robot forward toward the target at a specified speed while maintaining alignment, using helper functions for spinning, moving, and stopping. The proce... | def move_forward(target, move_speed, spin_speed, pos_tolerance, func_dict):
target_theta = _angle_between_points(func_dict["current"](), target)
while not _are_angles_equal(func_dict["current"]().theta, target_theta, _deg_to_rad(5)):
spin_func(spin_speed, _is_spin_clockwise(func_dict["current"]().theta,... |
def _get_url(self, path):
return '%s%s' % (self._url, path)
def _get_plugin_name(self, name, version = None):
if not version:
version = 'latest'
return '%s@%s' % (name, version)
def _use_crumbs(self):
config = self._get_config()
return 'useCrumbs' in config and config... | This function installs a specified plugin by sending a POST request with the plugin's name and version. It constructs the request URL, generates an XML payload, handles authentication crumbs if enabled, and verifies the response status to ensure successful installation. | def _install_plugin(self, name, version):
url = self._get_url('/pluginManager/installNecessaryPlugins/json')
plugin = self._get_plugin_name(name, version)
payload = '<install plugin="%s"/>' % plugin
headers = {'Content-Type': 'application/xml'}
if self._use_crumbs():
... |
def benchmark_task(args, writer=None):
graphs = io_utils.read_graphfile(
args.datadir, args.bmname, max_nodes=args.max_nodes
)
print(max([G.graph["label"] for G in graphs]))
if args.graph_feat == "node-feat" and "feat_dim" in graphs[0].graph:
print("Using node features")
input_d... | The code's main task is to execute different tasks based on command-line arguments, including benchmarking, processing pickle files, or running dataset-specific analyses. It handles GPU/CPU configuration, initializes logging, and routes execution to appropriate functions like benchmark_task, pkl_task, or syn_taskX, the... | def main():
prog_args = configs.arg_parse()
path = os.path.join(prog_args.logdir, io_utils.gen_prefix(prog_args))
writer = SummaryWriter(path)
if prog_args.gpu:
os.environ["CUDA_VISIBLE_DEVICES"] = prog_args.cuda
print("CUDA", prog_args.cuda)
else:
print("Using CPU")
#... |
def pre_process_source_image(self, camera):
self.logger.tick('pre_process source image')
src = self.source_image.copy()
gauss_blur = utils.gaussian_blur(src, (13, 13))
self.preprocessed_image = utils.adaptive_thresh(gauss_blur)
cv.imshow("adapt", self.preprocessed_image)
... | This function processes an input image to detect and solve a Sudoku puzzle. It converts the image to grayscale, preprocesses it, identifies the Sudoku board, extracts individual cells, solves the puzzle, and optionally displays the result. Debugging features log processing time and visualize the solution if enabled. | def feed(self, image, show_result_image=False, real_board=None, camera=False):
self.logger.tick('frame time', force_print=True)
self.color_source_image = image
self.source_image = cv.cvtColor(self.color_source_image, cv.COLOR_BGR2GRAY)
self.pre_process_source_image(camera)
self.g... |
def image2lap_pyramid(X,levs, requires_grad=True, detach=True):
pyr = []
cur = X
for i in range(levs):
cur_x = cur.size(2)
cur_y = cur.size(3)
x_small = F.interpolate(cur, (max(cur_x//2,1), max(cur_y//2,1)), mode='bilinear', align_corners = True)
x_back = F.interpolate(x_sm... | The code performs neural style transfer by iteratively optimizing a Laplacian pyramid representation of an image to match the content of a source image and the style of a target image. It computes content and style losses using feature maps from a pre-trained network, combines them with weighted coefficients, and updat... | def style_transfer(self, pastiche_image, moment_weight, content_weight, lr=2e-3, num_iterations=250):
lap_pyramid = image2lap_pyramid(pastiche_image, 5, requires_grad=True, detach=True)
optimizer = optim.RMSprop(lap_pyramid, lr=lr)
for i in tqdm(range(num_iterations)):
o... |
def encode_alt_modes(alt, bit13):
mbit = False
qbit = True
encalt = int((int(alt) + 1000) / 25)
if bit13 is True:
tmp1 = (encalt & 0xfe0) << 2
tmp2 = (encalt & 0x010) << 1
else:
tmp1 = (encalt & 0xff8) << 1
tmp2 = 0
return (encalt & 0x0F) | tmp1 | tmp2 | (mbit ... | This function encodes position data into a DF17 ADS-B message format, handling even/odd CPR (Compact Position Reporting) latitude/longitude encoding. It processes inputs like altitude, time, coordinates, and ICAO address, constructs byte sequences with specific bitfields, computes CRC checksums, and returns two byte ar... | def df17_pos_rep_encode(ca, icao, tc, ss, nicsb, alt, time, lat, lon, surface):
format = 17
enc_alt = encode_alt_modes(alt, surface)
#print "Alt(%r): %X " % (surface, enc_alt)
#encode that position
(evenenclat, evenenclon) = cpr_encode(lat, lon, False, surface)
(oddenclat, oddenclon) = cpr_... |
def add_person(people_table, edit_person=None):
# This method saves the person to the file.
def save_person(edit):
global INDICES, PEOPLE
person_name = name_input.get()
person_email = email_input.get()
person_phone = phone_input.get()
person_address = address_input.get("... | The main task of the code is to create a GUI frame containing a table to display people's information (name, phone, email) and buttons for adding, searching, viewing, and deleting entries. The frame is configured with a Treeview table, labeled columns, and action buttons linked to respective functions, returning the po... | def get_frame(window):
frame = Frame(window, name="people")
# Table to display the people.
people_table = table.Treeview(frame)
people_table.grid(row=0, column=0, columnspan=4)
people_table["columns"] = ["name", "phone", "email"]
people_table["show"] = "headings"
people_table.heading("name"... |
def convert_format(text_response):
ls_word = []
if ('textAnnotations' in text_response):
for text in text_response['textAnnotations']:
boxes = {}
boxes['label'] = text['description']
boxes['x1'] = text['boundingPoly']['vertices'][0].get('x',0)
boxes['y1']... | This code extracts and structures data from a text response into a standardized KTP (Indonesian ID card) format. It processes fields like identity number, name, birth details, address, and more, applying cleaning, validation, and normalization (e.g., gender mapping, marital status correction). It checks for required fi... | def extract_ktp_data(text_response,debug_mode=False):
ktp_extract = pd.DataFrame(columns=['province','city','identity_number','fullname','birth_place','birth_date','nationality','occupation','gender','marital_status',
'blood_type','address','rt_rw','kel_desa','kecamatan','re... |
def balanced_pos(num_pieces):
board = [[0] * 8 for i in range(8)]
num_rolls = num_pieces - 2
maxm = len(rolls) - 1
minm = 0
# occupied board spaces
occupied = []
assign_kings(occupied, board)
start = random.randint(0, 1)
side = 1 if start == 0 else -1
i = 0
while i < num_rolls:
num = rol... | The main task of the code is to generate a valid, balanced chess position with a specified number of pieces. It repeatedly creates positions using `balanced_pos`, converts them to FEN strings, and checks if they are legal, not game-over, and have a reasonable material evaluation (avoiding extreme values). The loop ensu... | def gen_board(num_pieces):
pos = balanced_pos(num_pieces)
fen = fen_from_board(pos)
board = chess.Board(fen)
board, legal = legal_pos(board)
fen = board.fen()
while board.is_game_over() or not board.is_valid() or evaluate(fen) > 300 or evaluate(fen) < -300:
pos = balanced_pos(num_pieces)
fen = fe... |
def gen_board(num_pieces):
pos = balanced_pos(num_pieces)
fen = fen_from_board(pos)
board = chess.Board(fen)
board, legal = legal_pos(board)
fen = board.fen()
while board.is_game_over() or not board.is_valid() or evaluate(fen) > 300 or evaluate(fen) < -300:
pos = balanced_pos(num_pieces)
fen = fe... | The main task of the code is to generate multiple chess positions with a specified number of pieces, evaluate them, and append analysis results to a CSV file. It validates input arguments, creates chess boards, prints position details, and writes gameplay outcomes using a `play_board` function, while handling depth and... | def main(args):
# pos = random_pos_weighted(num_pieces)
# fen = fen_from_board(pos)
# board = chess.Board(fen)
# print(f'Weighted:\n\n{board}')
if len(args) != 4:
print(f'Usage: py analysis.py <num_positions> <num_pieces> <depth> <time in seconds>')
return
for i in range(3):
try:
args... |
def play_opening(board, movelist, player_color):
ai_has_moved = False
while not movelist or len(movelist) < OPENING_LENGTH:
# go first if white or skip player turn and let ai go
if (board.turn and player_color.lower() == 'white') or ai_has_moved:
move = get_player_move(board, mov... | The code implements a command-line chess interface where a player competes against an AI. It validates the player's color (White/Black), initializes a chess board, and alternates turns between the player and AI. The AI uses MinMax with PST in regular phases and Stockfish in endgame (≤12 pieces). The game tracks moves, ... | def start():
"""
Start the command line user interface.
"""
player_color = input("Enter color: ")
while player_color not in ['White', 'Black']:
player_color = input("Please enter valid color (White, Black; case sensitive): ")
user_side = (
chess.WHITE if player_color == "White"... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.