dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def get_html_files_list(self):
self.html_files = clerk.get_all_files_of_type(self.__dir_path, "html")
return self.html_files
def get_html_requirements_list(self):
h_req_list = []
# create a flag to switch On when in the HTML section and off
# when that section is over (### CSS)
... | The main task of the code is to generate a report by collecting HTML files, validating requirements, structuring nested elements, applying stylesheets, analyzing results, and publishing the final output. It orchestrates data gathering, validation, formatting, and result dissemination in a systematic workflow. | def generate_report(self):
self.get_html_files_list()
self.get_html_requirements_list()
self.get_html_level()
self.get_validator_goals()
self.set_required_nested_elements()
self.get_required_nested_elements()
self.ammend_required_elements()
self.set_linked... |
def redraw_and_clear(self):
self.canvas.delete('all')
# draw the board in the background
if len(self.frame_stack) and self.frame < len(self.frame_stack):
player_to_move = 1 if self.frame % 2 == 0 else -1
model_inputs = game_state_to_model_inputs(self.frame_stack[self.frame][0], player_to_move)
model_in... | This code initializes a Go game interface with a 9x9 board, sets up a Tkinter GUI with a canvas for rendering, configures game state variables, loads a neural network model for AI gameplay, binds keyboard controls, and prepares to replay stored games. The main tasks include GUI setup, board initialization, model loadin... | def __init__(self):
self.edge = 9
self.board = Board(self.edge)
self.game = 0
self.game_stack = []
self.frame = 0
self.frame_stack = []
self.wstep = WIDTH / float(self.edge)
self.hstep = HEIGHT / float(self.edge)
Frame.__init__(self)
self.master.title('Go!')
self.master.rowconfigure(0, weight... |
def set_travel_queue(self, queue):
if len(self.travel_queue) > 30:
p(f'Pac({self.id}) travel queue too long')
p(f'{self.travel_queue}')
self.travel_queue = []
self.set_travel_queue(self.con.strategy(self))
return
if self.accepting_commands:
... | This function determines the next cell in a path-traversal queue, handling speed-based movement logic. It initializes a new path if the queue is empty, advances 1 or 2 steps based on speed status, and dynamically extends the queue when nearing the end. Debug logging is included for tracking decisions, and it manages st... | def get_next_cell_old(self):
if not self.travel_queue:
new_queue = self.con.simple_greedy_edge(self)
self.set_travel_queue(new_queue)
if self.debug: p(f'Game start, no next cell to fetch, new queue: {new_queue}')
current_index = self.get_current_index()
if ... |
def reverse_travel_queue(self):
self.set_travel_queue(list(reversed(self.travel_queue)))
def _move(self, x, y):
return f'MOVE {self.id} {x} {y}'
def get_next_cell(self):
if self.accepting_commands and self.recursion_counter >= 4:
p(f'Pac({self.id}) hit recursion in get_next_cell')
... | The code tracks if the entity is stuck by comparing current and previous positions. If stuck, it reverses the travel queue; otherwise, it updates position tracking. It then moves to the next cell in the queue and returns the result of that movement. | def follow_travel_queue(self):
""" If self in mid of current travel queue, follow it
Otherwise, request a new travel queue from controller
"""
if (self.last_x, self.last_y) == (self.x, self.y):
self.stuck_counter += 1
else:
self.stuck_counter = 0
... |
def get_coord(self, x, y, dir):
if dir == 'l':
if x == 0:
return x + self.w - 1, y # Wrap around the left edge
else:
return x - 1, y
elif dir == 'r':
if x == self.w - 1:
return 0, y # Wrap around the right edge
... | The code creates an Edge object connecting a given node to a new node by traversing in a specified direction. It appends the current node's coordinates to the Edge's path, iteratively moves in the direction, and checks for existing nodes. If found, it updates the Edge's path, links it to the new node, and sets reverse ... | def _create_edge(self, node, dir):
# Creates Edge object connecting `node` to a new node found by traversing along the `dir` direction
# Stores the Edge in self.edges
# New Edge creation
e = Edge(self.edge_count, node, dir)
self.edges[self.edge_count] = e
self.edge_count... |
def get_available_dirs(self, x, y):
available_dirs = list()
for dir in self.dirs:
if self.check_way(x, y, dir):
available_dirs.append(dir)
return available_dirs
def check_way(self, x, y, dir):
return self.is_floor(*self.get_coord(x, y, dir))
def get_coord(self... | The main task of the code is to collect all visible cells in a maze starting from coordinates (x, y). It initializes a list with the starting cell, then iterates through available directions, moving step-by-step along each path while the way is clear, appending each reachable cell to the list. The function returns the ... | def get_visible_cells(self, x, y):
# Get visible cells from (x, y) in maze
visible_cells = list()
visible_cells.append((x, y))
for dir in self.get_available_dirs(x, y):
x0, y0 = x, y
while self.check_way(x0, y0, dir):
x0, y0 = self.get_coord(x0, y... |
def stay(self):
return self._move(self.x, self.y)
def p(*args, **kwargs):
return print(*args, **kwargs, file=sys.stderr)
def _switch(self, type):
return f'SWITCH {self.id} {type.upper()}'
def reverse_travel_queue(self):
self.set_travel_queue(list(reversed(self.travel_queue)))
def follow_trav... | The code determines a Pac's response to nearby enemies by evaluating their type, position, and the Pac's current environment (edges, nodes). It decides to stay, reverse paths, switch types, or follow queues based on scenarios like being outmatched, encountering enemies on critical paths, or exploiting weaknesses. The l... | def enemy_routine(self, en_pacs):
""" Decide what to do if an enemy is in 2 distance vicinity """
# If surrounded by more than 2 enemy pacs, stay
# WIP: Write a better approach
if len(en_pacs) > 1:
self.stay()
en_pac, en_dist = list(en_pacs.keys())[0], list(en_pacs.... |
def p(*args, **kwargs):
return print(*args, **kwargs, file=sys.stderr)
def _speed(self):
return f'SPEED {self.id}'
def enemy_routine(self, en_pacs):
""" Decide what to do if an enemy is in 2 distance vicinity """
# If surrounded by more than 2 enemy pacs, stay
# WIP: Write a better ... | The code implements a defensive strategy for a game agent, deciding movement based on enemy proximity and collision avoidance. It checks nearby enemy pacs, prioritizing speed or evasion routines if enemies are close. If friendly pacs occupy diagonal cells, it avoids collisions by yielding or following queues. Otherwise... | def play(self):
""" Follows a mostly defensive strategy returning the next command """
en_cell_dict = {}
if self.en_pacs:
en_pac_locs = [(pac.x, pac.y) for _, pac in self.en_pacs.items()]
# Get 2 distance squares in each available dir
dist = 0
en_... |
def trace_lines(instrs) -> list:
pfrom = (0, 0)
lines = []
for ins in instrs:
new_line = Line(pfrom, ins)
pfrom = new_line.pto
lines.append(new_line)
return lines
def intersections(ls1, ls2):
intersections = []
for l1 in ls1:
for l2 in ls2:
if (point :... | The code reads two wire paths from a file, traces their routes, identifies intersections, calculates the nearest intersection using Manhattan distance, and determines the minimum combined steps required for both wires to reach that point. It returns 0 upon completion. Your return | def main(filename) -> int:
with open(filename) as f:
(w1str, w2str) = list(f)
wire1 = map(lambda s: Instruction(s), w1str.split(","))
wire2 = map(lambda s: Instruction(s), w2str.split(","))
lines1 = trace_lines(wire1)
lines2 = trace_lines(wire2)
inters = intersections... |
def iterativeFunc(dataC, dataN, clusterC, clusterN, iteramax, dc):#do the iterative work input:data and cluster,iterative max times output:the clusterlabel and the clusterArray
dn = 1-dc
clusterLabel = []
clusterLabelOld = []
clusterCNew = copy.deepcopy(clusterC)
clusterNNew = copy.deepcopy(clusterN... | The code evaluates and visualizes the accuracy of three clustering methods (OCIL, Iterative weight, Overall weight) by varying the weight of categorical attributes. It computes accuracy rates for each method across a range of weights, then plots these accuracies against the weight values to compare their performance. | def accuracyFigure(dataC, dataN, clusterC, clusterN, iteramax, start, stop, step, targetLabel, h):#draw the accuracy figure by modifing the dc, using the step between start and stop
accuracyRate = []
improvedAccuracyRate = []
improvedMEAccuracyRate = []
clusterlabel = []
improvedClusterlabel = []
... |
def iterativeFunc(dataC, dataN, clusterC, clusterN, iteramax, dc):#do the iterative work input:data and cluster,iterative max times output:the clusterlabel and the clusterArray
dn = 1-dc
clusterLabel = []
clusterLabelOld = []
clusterCNew = copy.deepcopy(clusterC)
clusterNNew = copy.deepcopy(clusterN... | The main task of the code is to evaluate and compare the accuracy of three clustering algorithms (original, improved, and ME variants) by calculating their label prediction accuracy against target labels. It computes accuracy rates for each method, generates a bar chart visualizing these rates, and prints error rates. ... | def barFigure(dataC, dataN, clusterC, clusterN, iteramax, targetLabel, dc, h, sign):
accuracyRate = []
clusterLabel = []
clusterCN = copy.deepcopy(clusterC)
clusterNN = copy.deepcopy(clusterN)
clusterCN, clusterNN, clusterLabel = iterativeFunc(dataC, dataN, clusterC, clusterN, iteramax, dc)
sumn... |
def make_type_odiney(type_str: str) -> str:
if type_str in _type_aliases:
return _type_aliases[type_str]
return strip_imgui_branding(type_str)
def peek_named_type(type_desc) -> str:
if type_desc["kind"] == "Builtin": return type_desc["builtin_type"]
elif type_desc["kind"] == "User": return type_desc["name"]
e... | The function `parse_type_desc` converts a type description dictionary into a formatted string representing the type. It handles built-in types, user-defined types, pointers (with alias checks and recursive parsing), and arrays (adjusting formatting based on function context, e.g., using `^` for pointer decay). It recur... | def parse_type_desc(type_desc, in_function=False) -> str:
kind = type_desc["kind"]
if kind == "Builtin":
return make_type_odiney(type_desc["builtin_type"])
elif kind == "User":
return make_type_odiney(type_desc["name"])
elif kind == "Pointer":
named_type = peek_named_type(type_desc["inner_type"])
if name... |
def _chomp(prefix: str, string: str) -> [str, bool]:
if string.startswith(prefix):
return [string.removeprefix(prefix), True]
return [string, False]
def _chomp_until(until: str, string: str) -> [str, str, bool]:
pos = string.find(until)
if pos == -1:
return [string, "", False]
return [string[pos:], string[:po... | This function evaluates a conditional expression involving defined macros, checking if each macro is defined (or not, if negated by '!') and combining results with logical ANDs, returning False if any part fails the check. | def condition_if(expression_str) -> bool:
# This is hardcoded for the path where we have [optional !, defined(, some_def, ), optional &&] and repeat
while len(expression_str) > 0:
[expression_str, invert] = _chomp("!", expression_str)
[expression_str, ok] = _chomp("defined(", expression_str)
assert ok
[expres... |
def condition_ifdef(condition_str) -> bool:
return _ifdef(condition_str)
def condition_if(expression_str) -> bool:
# This is hardcoded for the path where we have [optional !, defined(, some_def, ), optional &&] and repeat
while len(expression_str) > 0:
[expression_str, invert] = _chomp("!", expression_str)
[expr... | This function checks if all conditionals in a given structure meet their specified conditions. It returns True if no conditions fail or if no conditionals exist. For each conditional, it evaluates 'ifdef', 'ifndef', 'if', or 'ifnot' rules, returning False if any check fails. Unexpected condition types trigger an error ... | def passes_conditionals(thing_with_conditionals) -> bool:
if not "conditionals" in thing_with_conditionals: return True
for conditional in thing_with_conditionals["conditionals"]:
condition_kind = conditional["condition"]
expression = conditional["expression"]
if condition_kind == "ifdef":
if not condition... |
def write_section(file: typing.IO, section_name: str):
write_line(file)
write_line(file, "////////////////////////////////////////////////////////////")
write_line(file, "// " + section_name.upper())
write_line(file, "////////////////////////////////////////////////////////////")
write_line(file)
def passes_condit... | This function processes and writes user-defined macros from a file, filtering based on conditions, checking validity, and formatting them into aligned fields for output. It ensures defines are allowed, not duplicated, and properly structured before writing them to the specified file. | def parse_and_write_defines(file: typing.IO, defines):
write_section(file, "Defines")
aligned = []
for define in defines:
if not define["name"] in _defines_to_process: continue
is_user_define = not define["source_location"]["filename"].endswith("imgui.h")
if not passes_conditionals(define): continue
if is_... |
def passes_conditionals(thing_with_conditionals) -> bool:
if not "conditionals" in thing_with_conditionals: return True
for conditional in thing_with_conditionals["conditionals"]:
condition_kind = conditional["condition"]
expression = conditional["expression"]
if condition_kind == "ifdef":
if not condition... | The function `write_enum_as_flags` generates code representing an enum as bit flags or combinations in a target language (likely Odin). It processes enum elements, categorizing them into single-bit flags or composite values, and writes aligned fields to a file. It handles edge cases like invalid entries, ensuring prope... | def write_enum_as_flags(file, enum, enum_field_prefix, name):
aligned_enums = []
aligned_flags = []
for element in enum["elements"]:
if not passes_conditionals(element): continue
element_entire_name = element["name"]
element_value = element["value_expression"]
element_name = enum_parse_field_name(element_... |
def write_line_with_comments(file: typing.IO, str: str, comment_parent, indent = 0):
comment = comment_parent.get("comments", {})
for preceding_comment in comment.get("preceding", []):
write_line(file, preceding_comment, indent)
attached_comment = ""
if "attached" in comment:
attached_comment = " " + comment["... | This function generates constant definitions for an enum type in a specified file. It processes each enum element, applies naming conventions with a prefix, evaluates value expressions, and formats them as distinct constants. If values require splitting or branding removal, it handles those cases. The result is written... | def write_enum_as_constants(file, enum, enum_field_prefix, name):
write_line_with_comments(file, f'{name} :: distinct c.int', enum)
aligned = []
for element in enum["elements"]:
if not passes_conditionals(element): continue
field_base_name = element["name"]
field_name = enum_parse_field_name(field_base_name... |
def write_line(file: typing.IO, line: str = "", indent = 0):
file.writelines(["\t" * indent, line, "\n"])
def passes_conditionals(thing_with_conditionals) -> bool:
if not "conditionals" in thing_with_conditionals: return True
for conditional in thing_with_conditionals["conditionals"]:
condition_kind = conditional... | This function generates a C-style enum definition from a Python data structure, writing each element's name and value to a file. It applies a field name prefix, validates identifiers, and conditionally skips elements. When encountering a specified 'stop_after' element, it adds a comment about self-referential enum issu... | def write_enum(file: typing.IO, enum, enum_field_prefix: str, name: str, stop_after: str):
write_line(file, f'{name} :: enum c.int {{')
stop_comment = ""
for element in enum["elements"]:
if not passes_conditionals(element): continue
field_base_name = element["name"]
# SEE: _imgui_enum_stop_after
if field_... |
def write_section(file: typing.IO, section_name: str):
write_line(file)
write_line(file, "////////////////////////////////////////////////////////////")
write_line(file, "// " + section_name.upper())
write_line(file, "////////////////////////////////////////////////////////////")
write_line(file)
def passes_condit... | This function writes enum definitions to a file, filtering and formatting them based on conditions. It skips excluded enums, handles "Flags" enums differently (as constants or flags), and writes standard enums with optional stopping points. | def write_enums(file: typing.IO, enums):
write_section(file, "Enums")
for enum in enums:
if not passes_conditionals(enum): continue
# enum_field_prefix is the prefix expected on each field
# name is the actual name of the enum
entire_name = enum["name"]
[enum_field_prefix, name] = enum_parse_name(entire_na... |
def collect_url_text(url: str, headers: Dict[str, str] = None) -> Tuple[bool, List[str]]:
"""
collects text from all html tags within body tag
args:
url: str - url of page to collect data from
headers: dict[str, str], default None - chrome headers to avoid 403 forbidden.
returns:
... | The code fetches text from a URL, splits it into words, normalizes them, counts frequencies in a dictionary, sorts the result in descending order, and returns the status along with the sorted word count or original text if fetching fails. | def word_count_dict(url, headers=None):
status, text_list = collect_url_text(url, headers=headers)
if status:
corpus = {}
for elm in text_list:
for w in split_words(elm):
norm = normalize(w)
if norm != '' and corpus.get(norm):
corpu... |
def split_colons(s):
tokens=[]
cur=0
token=''
while s:
if s[0]=='\\':
s=s[1:]
if not s:
raise FatalError("'\\' at end of line")
token+=s[0]
s=s[1:]
elif s[0]==':':
if token:
tokens.append(token)
token=''
s=s[1:]
else:
token+=s[0]
s=s[1:]
if token:
tokens.append(token)
re... | The main task of the code is to process command-line arguments, validate input/output paths, handle macro definitions, parse source text, and generate output files. It ensures correct argument formatting, checks for redefined macros, processes input text with defined macros, and writes the final output to a specified f... | def main():
global path, SRC
SRC={}
if '--help' in sys.argv[1:]:
print(HELP_MESSAGE)
sys.exit(0)
# Handle arguments
try:
args, argf, argd=common.parse_args(sys.argv[1:], ['-o', '-D', '-b'], ['-D'])
except ValueError as x:
raise FatalError(
'no value provided for key: %s' % x.args[1])
except KeyError... |
def get_cf(cf: dict[str, Any]) -> str:
return f'Name: {cf["name"]}, type: {cf["type"]}, file "{cf["file"]}", line {cf["line"]}\n'
def get_callstack_entry(call: dict[str, Any], text_info: TextInfo) -> str:
return f' File "{call["file"]}", line {call["line"]}, in {call["name"]}\n' \
f' {text_info.c... | The function `report_error` generates error reports by formatting templates (`templates_map`) based on an error code. It extracts specific data from the `error` dictionary, replaces placeholders (e.g., `$cf_name`, `$callstack_entry`) with dynamic values using helper functions, and writes the resulting message to `outpu... | def report_error(
output_file: TextIO,
templates_map: dict[str, str],
text_info: TextInfo,
error: dict[str, Any]
) -> None:
error_code = error['error_code'][4:6] # getting an error number
match int(error_code): # react according to what error it is exactly
case 1:
... |
def match_exp(exp1, exp2):
# normalize temp variables
exp1 = normalize_exp(exp1)
exp2 = normalize_exp(exp2)
return exp1 == exp2
def node_not_found(old_node):
logging.warn('Node Not found {}'.format(old_node))
return (old_node + '-OLD')
def same_function(old_node, new_node):
return old_node.s... | The function `select_node` identifies the most appropriate matching node in `node_set` for a given `old_node` by progressively applying filters based on command type matching, function similarity, parent/child relationships (with/without normalization), and ambiguity handling. It returns the unique match if found, logs... | def select_node(old_node, old_node_info, new_node_info, node_set):
logging.debug("Ambiguous0: {} -> {}".format(old_node, node_set))
old_info = old_node_info['nodes'][old_node]
filtered_node_set = set()
# stronger matching
for candidate in node_set:
new_info = new_node_info['nodes'][candidate... |
def node_to_location(node, node_info):
elements = node_info['nodes'][node]['loc'].split(':')
return (elements[0], int(elements[1]))
def trans_location(location, line_matching):
if location in location_cache:
return location_cache[location]
changed_files = line_matching['changed_files']
added... | The main task of the code is to transform a node from an old structure to a new structure by checking caches, line mappings, or location transformations. If direct mappings fail, it generates a fallback node with '-OLD' suffix, caches results, and ensures uniqueness by tracking taken nodes. | def trans_node(node, old_node_info, new_node_info, line_matching, second=False):
if second:
if node.endswith('-OLD') and node.replace('-OLD', '') in node_cache:
return node_cache[node.replace('-OLD', '')]
else:
return node
if node.endswith('-ENTRY') or node.endswith('-EXI... |
def most_common_class(y):
if(len(y) == 0): return 0
counter = Counter(y)
most_common = counter.most_common(1)[0][0]
return most_common
def _find_best_split_criteria(self, X, y, features_idxs):
best_gain = -1
best_feature, best_threshold = None, None
for features_idx in features... | This function recursively builds a decision tree by selecting the best feature and threshold to split data, creating left and right subtrees. It checks base cases for leaf nodes (single class, min samples, max depth) and returns a leaf with the most common class. If not a leaf, it splits data, recurses on subsets, and ... | def _build_decision_tree(self, X,y, depth=0):
n_samples, n_features = X.shape
n_classes = len(np.unique(y))
# step 1: have a base case !
# -> there is only one class in the given sample for a node
# -> there are less than the minimum number of samples in the node... |
def moveValid(self, destination):
piece = self.board.board[self.selectedPiece]
if piece < 16 and self.turn == Piece.Black:
return False
if piece > 16 and self.turn == Piece.White:
return False
if destination in self.validMoves[self.selectedPiece]:
self... | This method handles selecting and moving a chess piece. It checks if a piece at the given position belongs to the current player, selects it if valid, calculates legal moves, and attempts to move it if the destination is valid. It also manages highlighting moves and deselecting if invalid. | def select(self, pos):
destination = None
self.highlightMoves = False
currentKingPos = self.board.whiteKingPosition if self.turn == Piece.White else self.board.blackKingPosition
print(self.board.turn)
if self.selectedPiece is None or self.board.board[self.selectedPiece] == 0:
... |
def _create_board(self):
board = [
[0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0],
[0,0,0,0,0,0,0,0],
[0,0,0,0,0,0... | This code solves a board puzzle by navigating through predefined patterns (squares and diamonds). It initializes a board, tracks moves starting from a given position, and iteratively checks the current position against four distinct patterns. When a match is found, it applies a pattern-solving method, increments a coun... | def solve(self):
self._board = self._create_board()
self._length = len(self._board)
solved = 0
moves = []
moves.append(self._start)
self._board[self._start.get_row()][self._start.get_col()] = "X"
while solved < 4:
current = moves[len(moves) - ... |
def active_edges(g, weight_attr = 'w'):
return [
edge
for edge
in g.edges(data=True)
if np.random.random() <= edge[2][weight_attr]
and not quarantined(g, edge)
]
def traced_contacts(g, active_edges, history, t):
contact_history = dict()
for edge in active_edges:
... | This function simulates a disease spread process on a network graph. It updates the graph's state by calculating active edges, tracing contacts, infecting nodes, progressing disease stages, determining symptomatic status, and clearing tests. Parameters like beta_hat (transmission rate), alpha (progression rate), gamma ... | def loop(params, g, history, t, copy = True):
if copy:
g = g.copy()
history = history.copy()
ae = active_edges(g)
tc = traced_contacts(g,
ae,
history,
t)
g = infections(g,
t,
... |
def traced_edges(g):
edges = g.edges(data=True)
te = 0
te_d = 0
cs = sum([square_distance(e, g.graph['N'], g.graph['M']) for e in edges if e[2]['c'] > 0.5])
for e in edges:
if adoption(g, e) and g.edges[(e[0],e[1])]['c'] > 0.5:
te += 1
if 'K' in g.graph: # Watts-S... | The function `data_from_result` computes and aggregates network and adoption metrics from a graph, including traced edges, adoption rates by group, effective parameters, and infection ratios. It returns a dictionary with timestamps, parameters, graph properties, node counts, final adoption states, adjacency ratios, and... | def data_from_result(
t,
params,
g,
history,
s_count
):
te, te_d = traced_edges(g)
aei, aeii = effective_parameters(g)
group_0_adopters = len(
[n for n in g.nodes(data=True)
if n[1]['group'] == 0 and n[1]['adopter'] == 1])
group_1_adopters = len... |
def get_infected(g):
return [n
for n
in g.nodes(data=True)
if n[1]['epi-state'] == 'Infectious']
def susceptible(g):
return [n
for n
in g.nodes(data=True)
if n[1]['epi-state'] == 'Susceptible']
def loop(params, g, history, t, copy = True):
... | This function simulates an infection spread process on a network graph. It iterates until no nodes are infected or a time limit is reached, tracking susceptible node counts and updating the network state using parameters. The loop prints progress at intervals, records the simulation history, and returns a structured re... | def simulation_process(g_live, params, i, time_limit = float("inf")):
t = 0
#g_live = g.copy()
#initialize(g_live,params)
history = {}
s_count = []
while len(get_infected(g_live)) > 0 and t < time_limit:
if t != 0 and t % len(g_live.nodes()) / 100 == 0:
print("Trial %d hits... |
def _next_state(self, from_state, afnd: AFND, char):
to_state = []
for st in from_state:
visited = []
for s in afnd.transitions[(st, char)]:
visited = self._dfs(afnd.transitions, s, visited, "_")
for v in visited:
if v not in to_state:
... | This method constructs the transition connections of an automaton by iterating over each character in the alphabet, determining the next state for each transition, and recursively adding new states and their transitions to the automaton. | def _construct(self, state, a: AFND):
for char in self.alphabet:
s = self._next_state(state, a, char)
self.new_connection(to_str(state), char, to_str(s))
if s not in self.states:
self._update(a, s)
self._construct(s, a) |
def _get_init_state(self, afnd: AFND):
init = self._dfs(afnd.transitions, afnd.init_state, [], "_")
init.sort()
return init
def _update(self, a: AFND, state_to):
self.states.append(state_to)
if a.end_states[0] in state_to:
self.add_end_state(state_to)
def _construct(s... | The code initializes an automaton by setting its initial state from the given AFND, updates internal state data using the AFND, and constructs the automaton's structure starting from the initial state. The main task is to convert or initialize an automaton (likely a NFA/DFA) based on the input AFND's configuration, pre... | def from_afnd(self, a: AFND):
self.init_state = self._get_init_state(a)
self._update(a, self.init_state)
self._construct(self.init_state, a) |
def get_2D(self):
'''
Loads 2D structure in MOL2 format
'''
if 'mol2D' not in self.data_refs:
return
r = requests.get(self.data_refs['mol2D'])
if r.ok:
self.mol2D = r.text
def get_3D(self):
'''
Loads 3D structure in MOL2 format
... | The code's main task is to load structural (2D/3D) and spectroscopic data by calling `get_2D()`, `get_3D()`, and `get_all_spectra()`, aggregating all available data types into the object. | def get_all_data(self):
'''
Loads available structural and spectroscopic data
'''
self.get_2D()
self.get_3D()
self.get_all_spectra() |
def handleHebrewQuotations(text: str):
i = 0
c = text[i]
whitespace = ""
hasNewLine = False
while c.isspace():
if i == len(text):
break
hasNewLine = hasNewLine or c == '\n' or c == '\r'
whitespace += c
i += 1
c = text[i]
if hasNewLine and isHeb... | The code processes input text by replacing substrings using a database, handling Hebrew quotation marks, and formatting punctuation. It iterates through characters, builds strings for replacement, and inserts paragraph breaks when encountering line breaks or specific punctuation, returning the transformed text. | def buildFixedText(text: str) -> str:
entries = {e.word: e for e in DB_Entry.query.all()}
out = ""
prev = None
c = None
i = -1
curStr = ""
while i < len(text)-1:
i += 1
prev = c
c = text[i]
if prev is not None and prev.isspace() and (c == '-' or c == '–'):
... |
def prime_num():
global public_k
global private_k
primes = [i for i in range(15, 1000) if RSA.is_prime(i)]
n = random.choice(primes)
n2 = random.choice(primes)
if n2 == n:
while n2 == n:
n2 = random.choice(primes)
public_k, private_k = RSA.keys(n, n2)
def login():
ll... | The main task of the code is to initialize a program by generating prime numbers, handling user login, and launching a background thread to retrieve messages concurrently while maintaining a graphical user interface (GUI) window using `window.mainloop()`. The `encryption_rsa()` function is commented out and not execute... | def main():
prime_num()
login()
# encryption_rsa()
get_msg_thread = Thread(target=lambda: get_msg())
get_msg_thread.start()
window.mainloop() |
def genome_parse(self):
genome_order = []
if os.path.exists(self.reference_genome):
with open(self.reference_genome, "r") as reference:
for row in reference:
if row[0] == ">":
genome_order.append(row[1:].strip())
else:
... | The main task of the code is to merge genomic data, compute normalized weighted averages and statistical metrics (e.g., standard deviation, read counts), filter out low-quality samples, and export detailed gene/sample analysis results into a structured CSV file, including per-sample statistics and cross-replicate aggre... | def main(self):
# want to write all the merged files into a csv file
self.geneNames = self.genome_parse() # has sRNA in order from reference genome
merged, order = self.merge()
print("data merged.")
print("Analyzing data")
self.set_gene_dict(self.geneNames) # easy acces... |
def toggle_state(self, *args):
if self.audio_file is None:
self.load_song_from_server(0)
if self.is_loading:
return
else:
self.set_state(State.PAUSE if self.state is State.PLAY else State.PLAY)
ClientManeger.log.write("Action - PlayPause")
def un... | The code's main task is to handle skipping to the next song by unloading the current audio, incrementing the song index, loading the next track from the server, and logging the "NextSong" action, while checking loading states and toggling the player's state if no audio is currently loaded. | def skip(self, *args):
if self.audio_file is None:
self.toggle_state()
if self.is_loading:
return
else:
self.unload()
self.song_index += 1
self.load_song_from_server(self.song_index)
ClientManeger.log.write("Action - NextS... |
def toggle_state(self, *args):
if self.audio_file is None:
self.load_song_from_server(0)
if self.is_loading:
return
else:
self.set_state(State.PAUSE if self.state is State.PLAY else State.PLAY)
ClientManeger.log.write("Action - PlayPause")
def un... | The code handles the "previous song" action by decrementing the song index, unloading the current song, and loading the previous one from the server, while logging the action. It checks if an audio file is loaded or if loading is in progress to decide whether to toggle state or proceed with unloading and reloading. | def back(self, *args):
if self.audio_file is None:
self.toggle_state()
if self.is_loading:
return
else:
self.unload()
self.song_index -= 1
self.load_song_from_server(self.song_index)
ClientManeger.log.write("Action - PrevS... |
def is_semantic_of_borough(x):
boroughs = ('BROOKLYN', 'MANHATTAN', 'BRONX', 'QUEENS', 'STATEN ISLAND')
return determine_type_of(x) == 'TEXT' and x in boroughs
def is_semantic_of_premises(x):
premises = ('INSIDE', 'FRONT OF', 'OPPOSITE OF', 'REAR OF', 'OUTSIDE')
return determine_type_of(x) == 'TEXT' and... | This function classifies input values into semantic categories based on their data type and value ranges. For integers, it distinguishes between crime codes, coordinates, IDs, and invalid numbers. Floats map to geographic coordinates, dates/time to crime timestamps, and text to categories like boroughs, locations, or c... | def determine_semantic_of(x, dtype):
if dtype == 'INTEGER':
value = int(x)
if value < 1000:
return 'Crime Code'
if value < 100000000:
return 'Coordinate Code'
if value > 100000000 and value < 999999999:
return 'Compliant ID'
return 'Non-sen... |
def is_semantic_of_borough(x):
boroughs = ('BROOKLYN', 'MANHATTAN', 'BRONX', 'QUEENS', 'STATEN ISLAND')
return determine_type_of(x) == 'TEXT' and x in boroughs
def is_semantic_of_premises(x):
premises = ('INSIDE', 'FRONT OF', 'OPPOSITE OF', 'REAR OF', 'OUTSIDE')
return determine_type_of(x) == 'TEXT' and... | This code determines the semantic meaning of a data value based on its type. For integers, it classifies values into categories like 'Crime Code', 'Coordinate Code', or 'Compliant ID' based on numerical ranges. For floats, it identifies them as 'Latitude or Longitude'. Dates and times are labeled as crime-related times... | def determine_semantic_of(x, dtype):
if dtype == 'INTEGER':
value = int(x)
if value < 1000:
return 'Crime Code'
if value < 100000000:
return 'Coordinate Code'
if value > 100000000 and value < 999999999:
return 'Compliant ID'
return 'Non-sen... |
def determine_type_of(x):
if is_typeof_integer(x):
return 'INTEGER'
if is_typeof_float(x):
return 'FLOAT'
if is_typeof_date(x):
return 'DATE'
if is_typeof_time(x):
return 'TIME'
return 'TEXT'
def determine_semantic_of(x, dtype):
if dtype == 'INTEGER':
valu... | The function `get_metadata_of` generates a formatted string containing the input value `x`, its determined data type, semantic meaning, and value. It combines these elements into a structured representation, returning a string like `"x dtype 'dsemantic' dvalue"` to encapsulate metadata attributes of `x`.) | def get_metadata_of(x):
dtype = determine_type_of(x)
dsemantic = determine_semantic_of(x, dtype)
dvalue = determine_value_of(x, dtype, dsemantic)
return ('%s %s \"%s\" %s' % (x, dtype, dsemantic, dvalue)) |
def determine_type_of(x):
if is_typeof_integer(x):
return 'INTEGER'
if is_typeof_float(x):
return 'FLOAT'
if is_typeof_date(x):
return 'DATE'
if is_typeof_time(x):
return 'TIME'
return 'TEXT'
def determine_semantic_of(x, dtype):
if dtype == 'INTEGER':
valu... | The function generates metadata for a given input value `x` by determining its data type, semantic meaning, and value. If `x` is empty or 'UNDEFINED', it returns a standardized NULL format. Otherwise, it uses helper functions to derive type, semantics, and value, then constructs a formatted string combining these attri... | def get_metadata_of(x):
base_type = 'INTEGER'
base_semantic = 'Crime Code'
if x == '' or x == 'UNDEFINED':
return ('%s %s \"%s\" %s' % (x, base_type, base_semantic, 'NULL'))
dtype = determine_type_of(x)
dsemantic = determine_semantic_of(x, dtype)
dvalue = determine_value_of(x, dtype, ds... |
def validate_password(self):
if self.ids.new_password_input.text == self.ids.new_password_confirm_input.text:
self.insert_into_db()
else:
self.alert_check_password()
def alert_email_invalid(self):
if not self.dialog_email_invalid:
self.dialog_email_invalid = M... | The main task of the code is to validate user registration form fields by checking name, username, password length constraints, and email format using regex. It sets error states and feedback messages for invalid inputs, ensuring all fields meet specified criteria before proceeding to password validation. | def validate_field(self):
name = len(self.ids.new_name_input.text)
user = len(self.ids.new_username_input.text)
email = self.ids.new_email_input.text.lower()
password = len(self.ids.new_password_input.text)
pattern = "[a-z 0-9]+[\._]?[a-z 0-9]+[@]\w+[.]\w{2,3}$"
if na... |
def init_nodes(nodes,names):
# In initial state, all nodes are disconnected
for node in nodes:
for name in names:
if node.name != name:
node.routingTable[name] = ["",math.inf]
return nodes
def remove_duplicated_LSDB(LSDB):
if len(LSDB) > 1:
new = LSDB[-1]
... | The code reads a network topology from input, processes node names and link states, updates link state databases (LSDB), and manages routing tables for nodes. It handles dynamic updates, initializes new nodes, and displays specific node details when optional parameters are provided. | def read_topology():
LSDB = []
nodes = []
names = []
# NAME
name = input()
while name != "LINKSTATE":
if name != "":
nodes.append(Node(name))
names.append(name)
name = input()
nodes = init_nodes(nodes,names)
link = input()
# LINKSTATE
... |
def getSecondDerivAtT(self, t, point):
""" generated source for method getSecondDerivAtT """
p = self.get(t)
d1 = self.get(t, 1)
d2 = self.get(t, 2)
x_a = p.x - point.x
y_a = p.y - point.y
z_a = p.z - point.z
return 2 * (d1.x * d1.x + x_a * d2.x + d1.y * d... | The code finds the closest point on a spline to a given input point using numerical methods. It iterates over discrete steps along the spline, applying Newton's method to refine the parameter `t` by minimizing the distance between the spline point and the target point. The function adjusts `t` based on first and second... | def findClosestPointOnSpline(self, point, steps=50, iterations=5):
""" generated source for method findClosestPointOnSpline_0 """
cur_dist = float("inf")
cur_min = 0
i = 0
while i <= 1:
cur_t = i
i += 1. / steps
if se... |
def create_examples(df, labels_available=True):
"""Creates examples for the training and dev sets."""
examples = []
for (i, row) in enumerate(df.values):
guid = row[0]
text_a = row[1]
if labels_available:
labels = row[2:]
else:
labels = [0,0,0,0,0,0]
... | The main task of the code is to train a BERT-based classifier using TensorFlow Estimator. It processes training data into TFRecord format, configures model parameters, initializes a BERT model with pretrained weights, and executes training for a specified number of epochs. The function calculates training steps, sets u... | def train_classifier():
train_examples = create_examples(x_train)
num_train_steps = int(len(train_examples) / BATCH_SIZE * NUM_TRAIN_EPOCHS)
num_warmup_steps = int(num_train_steps * WARMUP_PROPORTION)
train_file = os.path.join('./working', "train.tf_record")
#filename = Path(train_file)
if not o... |
def create_examples(df, labels_available=True):
"""Creates examples for the training and dev sets."""
examples = []
for (i, row) in enumerate(df.values):
guid = row[0]
text_a = row[1]
if labels_available:
labels = row[2:]
else:
labels = [0,0,0,0,0,0]
... | The code evaluates a classifier model using a validation dataset by converting examples to TFRecord format, running the estimator's evaluation, and logging results to a text file. It prepares evaluation data, executes the model on the dataset, and stores metrics like accuracy and loss in 'eval_results.txt'. | def eval_classifier():
eval_file = os.path.join('./working', "eval.tf_record")
#filename = Path(train_file)
if not os.path.exists(eval_file):
open(eval_file, 'w').close()
eval_examples = create_examples(x_val)
file_based_convert_examples_to_features(
eval_examples, MAX_SEQ_LENGTH, token... |
def pickle_create(filename,data):
with open(filename, 'wb') as handle:
pickle.dump(data,handle, protocol=2)
def corpus_dict_pos(que_tokens,que_distinct_words):
nd={}
nb=len(que_tokens)
mk=[]
fl=[]
dp=[]
for i in range(0,nb):
for k1 in que_tokens[i]:
fl=[]
... | The code processes text data to generate a synonym dictionary and indexed corpus. It combines intent data from questions and answers, extracts distinct words, creates synonym mappings, and builds an index for efficient synonym lookup. The output includes pickle files storing synonym lists, phrases, and an indexed dicti... | def get_words_synonyms():
doc=[]
doc.extend(pd.read_pickle('que_intents_pos_t.pickle'))
doc.extend(pd.read_pickle('ans_intents_pos_t.pickle'))
pickle_create('doc_t.pickle',doc)
doc=pd.read_pickle('doc_t.pickle')
corpus_dist=pd.read_pickle('corpus_distinct_words_t.pickle')
corpus_dist=li... |
def merge_duplicate_docs():
que_documents=pd.read_pickle('questions_t.pickle')
res_documents=pd.read_pickle('responses_t.pickle')
q=[] #stores distinct questions
for i in que_documents:
if i not in q:
q.append(i)
values=np.array(que_documents)
qindex=[]
for i in range(l... | The code tests a chatbot's performance on a dataset of questions by comparing its generated responses against expected answers. It tracks correct and incorrect answers, identifies problematic question indices, and handles various query types (e.g., entity-based, intent-based) to evaluate accuracy. The test processes ea... | def test_chatbot(): #testing on all database questions
correct_count = 0
wrong_count = 0
wrong_indices=[]
spell_time=0
abbrev_time=0
phrase_time=0
entity_time=0
que_list,ans_list,q,r=merge_duplicate_docs()
print('\n\n')
print('\n\n--------TESTING ON ALL THE DATASET QUES... |
def abbreviation_check(abbreviations,user_query):
import re
y=user_query.split()
for j in y:
l={}
for k in abbreviations.keys():
if k.lower()==j or k==j:
d=abbreviations[k]
for m in d.keys():
... | The code tests a chatbot's ability to handle "twisted" questions by evaluating its responses against a dataset. It processes each question through phrase replacement, entity extraction, intent detection, and response generation using rules or TF-IDF. It compares generated responses to expected answers, tracking correct... | def test_chatbot_twisted(): #testing on twisted questions
correct_count = 0
wrong_count = 0
wrong_indices=[]
spell_time=0
abbrev_time=0
phrase_time=0
entity_time=0
test_data=pd.read_csv(test_data_file)
test_questions=list(test_data['questions'])
test_responses=list(test_... |
def abbreviation_check(abbreviations,user_query):
import re
y=user_query.split()
for j in y:
l={}
for k in abbreviations.keys():
if k.lower()==j or k==j:
d=abbreviations[k]
for m in d.keys():
... | The code processes user input to generate responses using NLP techniques, handling greetings, fullform queries, entity-based answers, and intent recognition. It selects appropriate replies via TF-IDF, entity matching, or predefined responses, manages conversation flow, and logs response time. | def run_chatbot(usertext): #function that starts chatbot
flag=True
print('\n\n ------- CHATBOT STARTED --------\n')
print("BOT : Hey Hi! I am here to answer your queries. For acronyms, type 'fullform'. Type 'bye' to end conversation")
# while(flag==True):
user_input=usertext
start_time=date... |
def create_files(corpus): # create required files
print('--------Building Chatbot--------')
print('Please wait until all the required files are generated!')
if os.path.exists('questions_t.pickle')==False or os.path.exists('responses_t.pickle')==False:
print('creating question files and respons... | The code executes a TF-IDF-based chatbot system by loading preprocessed data (questions, responses, entities, TF-IDF vectors), initializing linguistic resources (synonyms, abbreviations, dictionaries), and testing the chatbot's performance on standard and twisted questions. It measures execution time for both testing p... | def tfidf_run():
global corpus_file
corpus_file='QuestionsResponsesISRO.csv' #file name of original corpus
start_time=datetime.now()
create_files(corpus_file)
end_time=datetime.now()
print('time(minutes):',(end_time-start_time).total_seconds()/60)
print('\n--------READY TO TEST THE CHATBOT-... |
def get_vocab(self, vocab_file, data_raw):
if os.path.exists(os.path.join(os.path.join('preprocessed_data', self.dump_data_path), 'vocab.pkl')):
vocab = pkl.load(open(os.path.join(os.path.join('preprocessed_data', self.dump_data_path), 'vocab.pkl'), 'rb'), encoding='latin1')
print ('read... | This code initializes a data processor for image-concept clustering, loading preprocessed data, building vocabularies, handling GloVe embeddings, and configuring device settings. It merges data, filters stopwords, constructs cluster mappings, and prepares attributes/image concept embeddings for subsequent processing. | def __init__(self, split, image_dir, preprocessed_data_dir, preprocessed_data_file, dump_data_path, vocab_file, cluster_file,
attributes_glove_emb_file, image_concepts_glove_emb_file, gpu_ids, cluster_classify, shuffle_data, sort_by):
self.split = split
self.sort_by = sort_by
se... |
def get_vocab(self, vocab_file, data_raw):
if os.path.exists(os.path.join(os.path.join('preprocessed_data', self.dump_data_path), 'vocab.pkl')):
vocab = pkl.load(open(os.path.join(os.path.join('preprocessed_data', self.dump_data_path), 'vocab.pkl'), 'rb'), encoding='latin1')
return vocab... | This code initializes a data processor for machine learning tasks, loading preprocessed data, vocabulary, and cluster embeddings. It sets up GloVe-based embeddings for attributes and image concepts, constructs cluster embedding matrices, validates input parameters, and prepares datasets for training/evaluation. The cod... | def __init__(self, split, image_dir, preprocessed_data_dir, preprocessed_data_file, dump_data_path, vocab_file, cluster_file,
attributes_glove_emb_file, image_concepts_glove_emb_file, gpu_ids, cluster_classify, shuffle_data, sort_by):
self.split = split
self.sort_by = sort_by
se... |
def choose_parrent(self):
competencies = self.competency_chromosomes(self.population)
if (self.parrent_choice == "best"):
return competencies[len(competencies) - self.parrent_number:]
if (self.parrent_choice == "weigthed"):
p = []
sum = 0
... | This code runs an evolutionary algorithm for k generations, tracking the best, worst, and average competency values of the population at each step. It selects parents, generates offspring via recombination and mutation, updates the population, evaluates chromosome competencies, and returns these metrics alongside a sol... | def Run(self, k=10):
best_competency = []
worst_competency = []
average_competency = []
for i in range(k):
parrent_population = self.choose_parrent()
childeren_population = self.recombination_and_mutation_population()
self.make_popula... |
def init(n: int) -> None:
global p, r
p = [-1] * n
r = [1] * n
def unite(x: int, y: int) -> None:
x = find(x)
y = find(y)
if(x == y): return
if(r[x] > r[y]): x, y = y, x
if(r[x] == r[y]): r[y] += 1
p[x] = y
def find(x: int) -> int:
if(p[x] == -1): return x
p[x] = find(p[x])
... | The main task of the code is to process a series of union and connectivity queries on a Disjoint Set Union (DSU) data structure. It initializes the DSU with `n` elements, then performs `q` operations: either merging two sets (command 0) or checking if two elements belong to the same set (command 1), outputting 1 if con... | def main():
n, q = map(int, input().split())
init(n)
for _ in range(q):
com, x, y = map(int, input().split())
if(com == 0):
unite(x, y)
if(com == 1):
if(find(x) == find(y)): print(1)
else: print(0) |
def count_vectorizer(data, train_data, test_data):
count_vector = CountVectorizer(analyzer = 'word', token_pattern = r'\w{1,}')
count_vector.fit(data['text'])
train_data_count = count_vector.transform(train_data['text'])
test_data_count = count_vector.transform(test_data['text'])
return train_data_... | The main task of the code is to perform leave-one-out cross-validation on a dataset, evaluating multiple classifiers (Decision Tree, Random Forest, Naive Bayes, SVM, Logistic Regression) with three feature representations (count vectors, TF-IDF, word embeddings). It iterates through each data point as a test set, train... | def loo_validation(data):
result = {}
result['test_dt_count'], result['test_dt_tfidf'], result['test_dt_we'] = 0, 0, 0
result['test_rf_count'], result['test_rf_tfidf'], result['test_rf_we'] = 0, 0, 0
result['test_nb_count'], result['test_nb_tfidf'], result['test_nb_we'] = 0, 0, 0
result['test_svm_co... |
def load_rentals_from_database_screen1(self):
try:
rental_requests = self.get_all_rentals()
#(rental_requests)
for rental in rental_requests:
rented_car_name = rental[1]
rented_by_who = rental[3]
rented_car_image = self.get_car_... | The code defines the `load_screen1` method to initialize a UI layout for a car rental management system. It creates frames, buttons, labels, and scrollable areas to display requested car rentals, admin login options, and user login forms. The "Delete All" button triggers deletion of all requests, and the layout dynamic... | def load_screen1(self):
self.main_login_frame = QtWidgets.QFrame(self.main_widget)
self.main_login_frame.setEnabled(True)
self.main_login_frame.setGeometry(QtCore.QRect(0, 70, 961, 641))
self.main_page_admin_login = QtWidgets.QPushButton(self.main_login_frame)
self.main_page_adm... |
def load_cars_from_database_screen3(self):
cars = self.get_all_cars()
if cars != []:
for car in cars:
car_name = (car[1] + " " + car[2])
car_color = car[3]
car_year = car[4]
car_rent = car[5]
car_plate = car[6]
... | The code defines the `load_screen3` method, which initializes and configures a car rental management UI. It creates frames, labels, text boxes, spin boxes, buttons, and scroll areas to display car details, apply filters (price, color, year, name), and manage rental requests. The UI includes interactive elements for fil... | def load_screen3(self):
self.main_book_rental_frame = QtWidgets.QFrame(self.main_widget)
self.main_book_rental_frame.setGeometry(QtCore.QRect(0, 69, 961, 641))
self.car_show_frame = QtWidgets.QFrame(self.main_book_rental_frame)
self.car_show_frame.setGeometry(QtCore.QRect(640, 10, 321, 6... |
def find_log(epochs, num_pools, num_channels, pool_type, pool_stride, skip_connections, avg_radius, sigma_back):
''' Check whether we have already logged this configuration. '''
if not os.path.exists(LOG_PATH):
return None
log_df = pd.read_csv(LOG_PATH)
skip_str = stringify_skips(skip_connection... | The function `run_unet` executes a U-Net algorithm with specified parameters (e.g., pooling layers, channels, skip connections), checks for pre-existing results in a log file, trains the model on a dataset, evaluates it on a test set, computes the Intersection over Union (IoU) score, and updates the log with the new re... | def run_unet(num_pools, num_channels, skip_connections, avg_radius, sigma_back, epochs=50, verbose=True):
''' Run the U-Net algorithm with the given parameters and store IoU in log file. '''
# Check if configuration was already run; if so, return its IoU score
match_idx = find_log(epochs, num_pools, n... |
def _get_all_tasks(self):
"""Gets all tasks from Ticktick."""
self._get_ticktick_data()
raw_active_tasks = self.ticktick_data["syncTaskBean"]["update"]
if raw_active_tasks == self._cached_raw_active_tasks:
return
self._cached_raw_active_tasks = raw_active_tasks
... | The main task of the code is to process daily logs by categorizing tasks: moving inbox tasks to day logs, tagging tasks based on their creation date, and marking tasks created over three days ago as complete. It iterates through all-day logs, applies specific actions like tag replacement, project movement, and completi... | def _process_daily_logs(self):
"""Processes the daily logs."""
self._get_all_tasks()
for task in self.all_day_logs.copy():
if task.project_id == get_ticktick_ids()[tik.LIST_IDS.value][tfK.INBOX_TASKS.value]:
self._replace_tags_in_highlight_log(task)
s... |
def loadPosTagEmbedding(self, bufferSet):
embedDataPath = self.openConfigurationFile("wordEmbeddingPath")
self.PRETRAINED_GLOVE_EMBEDDING = KeyedVectors.load_word2vec_format(embedDataPath,binary=True)
for token in bufferSet:
bufferArray = np.array([])
if token in... | The main task of the code is to read and process training data from a file, parsing structured features into a dictionary and set for embedding mapping. It validates data consistency, prepares instance labels, loads positional embeddings, maps features to embeddings, and splits data for cross-validation, ensuring unifo... | def readTrainingResourceData(self,fileDataPath):
tier1BufferDict = {}
tier1BufferSet = set()
with open(fileDataPath, "r") as bufferFile:
currentData = bufferFile.readline()
index=0
while len(currentData)!=0:
currentData = str(currentDa... |
def openConfigurationFile(self,jsonVariable):
path = os.path.dirname(sys.argv[0])
tokenMatcher = re.search(".*ICONRepClassification_Py\/", path)
if tokenMatcher:
configFile = tokenMatcher.group(0)
configFile="".join([configFile,"config.json"])
jsonVa... | The main task of the code is to load test and training resources by reading configuration files, populate test instance data into a dictionary, read training data, and perform cross-validation splitting to prepare datasets for model evaluation and training. | def loadResource(self):
testDataPath = self.openConfigurationFile("corpusTestInstanceFile")
testInstanceDict = self.readTestResource(testDataPath)
repTestDataPath = self.openConfigurationFile("corpusIconTestPath")
self.readTestResourceData(repTestDataPath, testInstanceDict)
... |
def openConfigurationFile(self,jsonVariable):
currPath = os.path.dirname(sys.argv[0])
if currPath == '':
currPath = sys.path[0]
print(currPath)
configPath = 'config.json'
updatePath = []
for pathMatch in re.split("\/", currPath):
... | The main task of the code is to load and process training/test data by reading raw resources, generating a vocabulary tokenizer, converting instances into structured data (x/y pairs), and preparing cross-validation splits for machine learning model training and evaluation. | def loadResource(self):
repTestDataPath = self.openConfigurationFile("corpusIconTestPath")
testInstanceDict, testInstanceList = self.readRawResource(repTestDataPath)
self.generateInstanceMap(testInstanceDict, testInstanceList)
repTrainDataPath = self.openConfigurationF... |
def ref_inletx(self, chip):
chip_numb = chip
if chip_numb in ('1', '9'):
chip_numbs = 0
elif chip_numb in ('2', '10'):
chip_numbs = 1
elif chip_numb in ('3', '11'):
chip_numbs = 2
elif chip_numb in ('4', '12'):
chip_numbs = 3
... | The main task of the code is to execute a pressure test on a chip's inlet lanes by calling a series of methods to configure inlet positions and perform a pressure measurement. The function initializes chip parameters, sets inlet coordinates, and returns the result of a lane loop pressure test for the specified chip. | def test_gui(self, chip):
chip_numb = chip
self.ref_inletx(chip=chip_numb)
self.chip_inlet_x(chip=chip_numb)
self.chip_inlet_y(chip=chip_numb)
x = self.lane_loop_pressure_test(chip=chip_numb)
return x |
def yamlToJson(inputyaml):
data = {}
st = {}
with open(inputyaml) as inputyaml:
filecontent = yaml.load(inputyaml, Loader=yaml.FullLoader)
return(filecontent)
def getVduList(f):
vdu = []
properties =f["vnfd"]["vdu"]
for i in properties:
vdu.append(i["id"])
return vdu
def ... | The main task of the code is to convert VNFD YAML files into structured output files (YAML/JSON) for deployment, validating input paths, generating directory structures, and creating assembly/resource definitions based on deployment location type. It processes VNFD data, transforms it into JSON, produces YAML outputs f... | def main():
parser = argparse.ArgumentParser()
parser.add_argument("--inputpath","-i", type=str, help="Input path for vnfd file. eg: /sol006-vnfd-handler/resources/input/packages/example/")
parser.add_argument("--outputpath","-o", type=str, help="Output path for vnf package")
parser.add_argument("-... |
def get_gmail_service():
path_to_pickle = "google-creds/token.pickle"
s3client = boto3.client('s3')
response = s3client.get_object(Bucket=os.environ['BUCKET_NAME'], Key=path_to_pickle)
body = response['Body'].read()
creds = pickle.loads(body)
service = build('gmail', 'v1', credentials=creds)
... | The main task of the code is to send an email notification to the BI team about unrefreshed Tableau production server resources. It retrieves unrefreshed data, uploads it to S3, attaches the file to an email, and sends it via Gmail API with details on the number of outdated resources and the S3 file path. | def run_tableau_refresh_validation():
service = get_gmail_service()
sender = "qegju@example.com"
user_id = "me"
message = MIMEMultipart()
message_text = 'Greetings, BI Team'
message['to'] = 'toopv@example.com'
message['cc'] = 'fejzt@example.com,qegju@example.com,kijdy@example.com,ihkje@examp... |
def seed_player(self):
os.system('clear')
input_check = False
while input_check == False:
print('Welcome to Blackjack. Please enter your starting money amount')
money = input()
if money == 'q':
exit()
try:
money = float(money)
self.player.money = money
input_check = True
os.syste... | This code simulates a card game where a player bets money, plays hands against a dealer, and updates their funds based on win/loss outcomes. The loop continues until the player's money reaches zero. The game handles regular wins, losses, blackjack payouts (1.5x), and pushes (ties). | def play_game(self):
self.seed_player()
while self.player.money >= 1:
bet = self.place_bet()
winner, bet, insurance = self.play_hand(bet)
if winner == 'player':
self.player.win_money(bet, insurance=insurance)
elif winner == 'dealer':
self.player.lose_money(bet, insurance=insurance)
elif winne... |
def user_ID():
UID = input("Enter your UID: ")
while UID in nothing or ord(UID[0]) in invalid_char_array:
print(invalid_input)
UID = input("Enter your UID: ")
return UID
def questions(UID):
scores = []
num_q = Posts.find({"OwnerUserId": UID, "PostTypeId": "1"})
numberOfQuestions... | The code connects to a MongoDB database, handles user login/authentication, retrieves user statistics (questions, answers, votes), allows users to post questions with tags, and search for posts. It manages document IDs, queries data, and provides a menu-driven interface for interactions like posting, searching, or exit... | def main():
# successfully entered the main function and entered the database
# counters/ids for the below fields
question_Id = 0
votes_Id = 0
answers_Id = 0
tags_Id = 0
Posts.create_index([("Id", 1)])
print("Database connected") # print if connection successfull
print("MongoDB MINI... |
def add_node_to_path(list_index, new_node):
global pathList
# Initialize the list at list_index if it doesn't exist
while list_index >= len(pathList):
pathList.append([])
pathList[list_index].append(new_node)
def delete_all_nodes():
global pathList
pathList = []
def add_path_to_list(n... | This code implements the Rapidly-exploring Random Tree (RRT) algorithm to find a collision-free path from a start point to a goal within a 2D environment. It uses Pygame for visualization, handles obstacles, and iteratively generates paths while avoiding them. The algorithm returns the best path found after a specified... | def RRT(start, goal, obstacles, width, height, search_radius=75, max_iter=1000):
pygame.init()
# Set up display
width, height = 800, 600
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption('Random Node Placement')
# Colours
# Start Node
startNode = np.array(st... |
def initialize_weights(self):
return [0] * self.num_weights
def score(self, X, y):
predictions = self.predict(X)
num_correct = len([1 for prediction, target in zip(predictions, y) if prediction == int(target)])
return round(num_correct / len(y), 2)
def _run_epoch(self, X, y):
shu... | The code trains a model by iteratively adjusting weights to minimize misclassification. It runs epochs until weight changes fall below a threshold (SIGMA) or completes a specified number of rounds. It tracks misclassification rates and weight changes for monitoring, returning the trained model with updated parameters. | def fit(self, X, y, initial_weights=None, numRounds=0):
self.num_epochs = 0
self.misclass = []
self.num_weights = X.shape[1]
self.weights = self.initialize_weights() if not initial_weights else initial_weights
self.recent_changes.append(np.array(self.weights))
if (numRou... |
def _is_leaf(self):
# if the target data is homogenous, or we're out of attributes
return len(self.target_data) == 0 or np.all(self.target_data == self.target_data[0]) or len(self.attributes_already_split) == self.instance_data.shape[1]
def _save_prediction(self):
if len(self.target_data) == 0:
... | This method splits a decision tree node by checking if it's a leaf (saving prediction and returning if so), otherwise selecting a feature to split data, creating child nodes, and recursively splitting each child to build the tree structure. | def split(self):
if self._is_leaf():
self._save_prediction()
return
attribute_to_split, split_instance_data, split_target_data = self._create_split()
self._create_children(attribute_to_split, split_instance_data, split_target_data)
for child in self.children:
... |
def initialize_weights(self, default_val=None):
weights = []
layer_widths = self.hidden_layer_widths.copy() if self.hidden_layer_widths is not None else [2 * self.num_inputs]
layer_widths.insert(0, self.num_inputs)
layer_widths.append(self.num_outputs)
num_layers = len(layer_widt... | The code implements a training loop for a neural network, performing gradient descent with backpropagation. It initializes weights, tracks training/validation metrics (MSE, accuracy), and supports both fixed-epoch training or adaptive training with early stopping based on validation performance. The model shuffles data... | def fit(self, X, y, initial_weights=None, default_weight=None, numEpochs=None, num_outputs=None, validation_size=0.2):
self.num_inputs = X.shape[1]
self.num_outputs = y.shape[1] if num_outputs is None else num_outputs
self.weights = self.initialize_weights(default_val=default_weight) if not init... |
def remove_images_without_object(ra, dec):
if not os.path.exists('unused'):
os.mkdir('unused')
images = get_raw_image_filenames(raw_directory='.')
for image in images:
if not image_includes_coordinate(image, ra, dec):
shutil.move(image, 'unused/')
def copy_raw_data():
if not... | The code processes astronomical image data by aligning HST and ground reference images, generating a template, extracting sources with SEP, creating catalogs, calculating offsets, and running Dolphot for photometric analysis. It standardizes data, applies corrections, and prepares outputs for further analysis, includin... | def run(center=None, ground_reference=None, options=None):
if options is None:
options = {}
# Make sure the position of interest is in the raw frame
remove_images_without_object()
# Copy the raw files into the raw directory
copy_raw_data()
# Download the reference images
download_... |
def printIntro():
print("This program simulates a game of racquetball between two")
print('players called "A" and "B". The ability of each player is')
print("indicated by a probability (a number between 0 and 1) that")
print("the player wins are the point when serving. Player A always")
print("has t... | The main task of the code is to simulate a series of games between two players (A and B) with specified probabilities of winning each game. It first prints an introduction, retrieves input values (probabilities and number of games), simulates the games, and then outputs a summary of the results, showing how many games ... | def main():
printIntro()
probA, probB, n = getInputs()
winsA, winsB = simNGames(n, probA, probB)
printSummary(winsA, winsB) |
def printIntro():
print("This program simulates a game of volleyball between two")
print('players called "A" and "B". The ability of each player is')
print("indicated by a probability (a number between 0 and 1) that")
print("the team wins a rally is awarded a point.")
def getInputs():
a = float(inpu... | The main task of the code is to simulate a series of games between two players (A and B) with given winning probabilities, calculate the number of wins for each player over `n` games, and output the results. It first prints an introduction, retrieves user inputs for probabilities and game count, simulates the games, th... | def main():
printIntro()
probA, probB, n = getInputs()
winsA, winsB = simNGames(n, probA, probB)
printSummary(winsA, winsB) |
def seams_removal(im, num_remove, vis=False, rot=False):
for _ in range(num_remove):
seam_idx, boolmask = get_minimum_seam(im)
if vis:
visualize(im, boolmask, rotate=rot)
im = remove_seam(im, boolmask)
return im
def seam_insertion(im, num_add, vis = False, rot = False):
s... | The function `seam_carve` resizes an image by adjusting its width and height through seam removal or insertion. It uses `seams_removal` (for reducing size) or `seam_insertion` (for expanding size) based on `dx` and `dy` values. For vertical adjustments (`dy`), it rotates the image, applies seam operations, then rotates... | def seam_carve(im, dy, dx, vis=False):
im = im.astype(np.float64)
h, w = im.shape[:2]
# print(h,w)
output = im
if dx < 0:
output = seams_removal(output, -dx, vis)
elif dx > 0:
output = seam_insertion(output, dx, vis)
if dy < 0:
output = rotate_image(output, True)
... |
def backward_energy(im):
xgrad = ndi.convolve1d(im, np.array([1, 0, -1]), axis=1, mode='wrap')
ygrad = ndi.convolve1d(im, np.array([1, 0, -1]), axis=0, mode='wrap')
grad_mag = np.sqrt(np.sum(xgrad ** 2, axis=2) + np.sum(ygrad ** 2, axis=2))
return grad_mag
def forward_energy(im):
"""
Forward ... | This code performs seam carving on an image to resize it by removing specified numbers of vertical (dx) and horizontal (dy) seams. It calculates energy maps using either forward or backward methods, removes seams iteratively, and computes the percentage of content loss relative to the original image's energy sum. The o... | def seam_carve(im, dy, dx, vis=False, fn="Backward"):
im = im.astype(np.float64)
h, w = im.shape[:2]
# print(h,w)
if fn == "Backward":
M = backward_energy(im)
elif fn == "Forward":
M = forward_energy(im)
content = np.sum(M)
output = im
if dx < 0:
output = seam... |
def resize(image, width = None, height = None):
if width:
dim = None
h, w = image.shape[:2]
dim = (width, int(h * width / float(w)))
return cv2.resize(image, dim)
if height:
h, w = image.shape[:2]
dim = (int(w*height/float(h)), height)
return cv2.resize(im... | The main task of the code is to resize and carve an image based on specified dimensions and algorithm. It loads an image, adjusts its size if needed, applies seam/column/pixel carving or cropping depending on the 'algo' parameter, and returns the processed image as a buffer. The function handles input validation, resiz... | def carve_main(image,height,width, algo):
IMAGE = image
OUTPUT = "out.jpeg"
try:
im = imutils.url_to_image(IMAGE)
h, w = im.shape[:2]
if SHOULD_DOWNSIZE and algo in [0,1]:
if w > DOWNSIZE_WIDTH:
im = resize(im, width=DOWNSIZE_WIDTH)
h,w ... |
def accept_connection(self, sock_):
try:
sock_, addr = sock_.accept()
self.report(f"New Connection from {addr} Has ben Established!", 1)
return sock_
except:
self.report(f_exc(), 5)
def receive_data(self, socket_, buffer_limit="default", on_none=None):
... | The code's main task is to manage an ongoing server loop that handles incoming client connections and data. It uses I/O multiplexing (via `select`) to monitor sockets, accepts new connections, receives HTTP request headers, and spawns executors to process requests with corresponding response objects. The loop continues... | def start(self):
if not self.is_started:
self.report("Server is not running yet!", 3)
while self.is_started:
fd_pointer = 0
try:
for incoming_socket in select_sock(self.sockets_list, self.sockets_list, self.sockets_list):
if not in... |
def screen_clear():
"""Clears the screen of the console."""
if os.name == 'posix':
_ = os.system('clear')
else:
_ = os.system('cls')
def create_tenants(obj_item):
"""Creates a new Tenant"""
screen_clear()
obj_dict = {}
random_int = random.randint(1000, 9999)
first_name = ... | This function provides a menu-driven interface for tenant management, allowing users to create tenants, view tenant lists, or return to a previous menu. It validates user input and recursively re-displays the menu if invalid input is detected, with delays for screen updates and user interaction. | def access_tenants(obj_item):
"""Initiates the landlord Tenant cli"""
screen_clear()
print("""
1. Create Tenant
2. Tenants
3. Go back
""")
value = input("Enter value: ")
if value == "1":
create_tenants(obj_item)
if value == "2":
get_tenants(obj_item)
if value ... |
def display_board():
bright_yellow = "\033[0;93m" # This is a variable used for calling the colour.
green = "\033[0;32m"
print(green + ' | |')
print(green + '7: ' + bright_yellow + board[7] + green +' |8: '+ bright_yellow + board[8] + green +' |9: '+ bright_yellow + board[9])
pr... | The code defines a Tic-Tac-Toe game loop that displays the board, alternates turns between 'X' and 'O', checks for a win/draw after each move, and declares the result once the game ends. It manages player input, game state tracking, and outcome determination through function calls. | def play_game():
#print('Welcome To Tic-Tac-Toe!')
# Display initial board - display the board (each square called from board[]).
display_board()
#While the game continues..... - a While loop calling each function until a winner or draw is declared.
while game_continues:
# ... |
def display_board():
bright_yellow = "\033[0;93m"
green = "\033[0;32m"
print(green + ' | |')
print(green + '7: ' + bright_yellow + board[7] + green +' |8: '+ bright_yellow + board[8] + green +' |9: '+ bright_yellow + board[9])
print(green + ' | |')
print(green + '--------... | The code runs a Tic-Tac-Toe game by displaying the board, handling player turns, checking for win/tie conditions, and declaring the winner or a tie once the game ends. | def play_game():
#print('Welcome To Tic-Tac-Toe!')
# Display initial board
display_board()
#While the game continues.....
while game_continues:
# Handle the turn of the current player
handle_turn(current_player)
# Check if the game is over
chec... |
def gtf_file_exists(self):
return self.gtf_file.exists()
def gtf_to_df(self):
df = pl.read_csv(
self.gtf_file,
has_header=False,
separator="\t",
skip_rows=self.gtf_count_header_lines(),
new_columns=[
"seqname",
"... | The code initializes a class to process a GTF file by checking its existence, converting it into a DataFrame, filtering gene entries, sorting by coordinates, adding row numbers, and extracting Ensembl IDs for structured analysis. | def __init__(self, gtf_file):
self.gtf_file = gtf_file
self.df = None
if self.gtf_file_exists():
self.gtf_to_df()
self.filter_only_genes()
self.sort_df_by_coordinates()
self.add_rownumbers_to_df()
self.extract_ensembl_ids() |
def is_letter_with_marks(codepoint, table):
"""Returns true for letters combined with one or more marks."""
# See https://www.unicode.org/reports/tr44/tr44-14.html#General_Category_Values
# Letter may have no combining characters, in which case it has
# no marks.
if len(codepoint.combining_ids) == ... | (The code processes Unicode character decomposition data from 'UnicodeData.txt', identifying characters with combining marks or ligatures. It maps these to their base forms, filters unique entries, and optionally includes CLDR Latin-ASCII transliterations. The result is a sorted list of character mappings for display, ... | def main(args):
# https://www.unicode.org/reports/tr44/tr44-14.html#Character_Decomposition_Mappings
decomposition_type_pattern = re.compile(" *<[^>]*> *")
table = {}
all = []
# unordered set for ensure uniqueness
charactersSet = set()
# read file UnicodeData.txt
with codecs.open(
... |
def quit(self):
pg.quit()
sys.exit()
def showMenu(self):
running = True
params = {'planet':False,'rocket':False}
current_param = 0
while running:
last_update = pg.time.get_ticks()
stats = self.planetStats[self.selectedPlanet]
self.move_... | This method handles end-game key events by quitting the game on window close (QUIT) or ESC key, and restarting the game on ENTER key by resetting game states, removing sprites, and reinitializing entities. | def process_keys_end_game(self):
for event in pg.event.get():
if event.type == pg.QUIT:
self.quit()
if event.type == pg.KEYDOWN:
if event.key == pg.K_ESCAPE:
self.quit()
if event.key == pg.K_RETURN:
... |
def showMenu(self):
running = True
params = {'planet':False,'rocket':False}
current_param = 0
while running:
last_update = pg.time.get_ticks()
stats = self.planetStats[self.selectedPlanet]
self.move_background(menu = True)
self.draw_text("N... | This code runs a game loop that initializes game elements, handles user input, updates game state, and renders graphics at 60 FPS. It checks for quit events, manages rocket movement, and transitions to game over processing when applicable. The loop continues until the player exits or the game ends. | def run(self):
self.playing = True
self.showMenu()
self.init_entities()
while self.playing:
if self.afterMenu == True:
#Number of miliseconds from last farme
self.dt = self.clock.tick(60) / 1000
for event in pg.event.get():
... |
def get_accuracy(self, data: np.ndarray) -> float:
'''
Gets the accuracy of the network for the given data (in %).
Parameters
----------
data : np.ndarray
An array with all the data.
Returns
-------
float
The percentage.
'... | (The main task of the code is to train a neural network using gradient descent via backpropagation on provided training data. It processes data in batches, iterates over epochs, adjusts weights with a specified learning rate, and optionally reports accuracy on testing data each epoch. If enabled, it saves the trained n... | def train(self, training_data: np.ndarray, epochs: int = 10, batch_size: int = 100, learn_rate: float = 0.25,
save: bool = False, filename: str = "trained_nn", testing_data: np.ndarray = np.array([]), verbose: bool = True) -> None:
'''
Trains the neural network using gradient descent.
... |
def read_alignment(input_file, read_all=False, region_name=""):
"""
"""
imgt_fields = ["accession_number",
"allele",
"species",
"functionality",
"region",
"start_and_end_positions_IMGT/LIGM-DB_accession_number",
"number_of_nucleotides",
"codon_start",
"number_nucl... | The main task of the code is to read, format, and combine V and J gene alignments from FASTA files for immunoglobulins (IGs) and T-cell receptors (TRs) across species and chain types. It processes alignments for V-REGION and J-REGION, formats them, and generates putative germline sequences. The code writes formatted al... | def main():
"""
Read in the raw v and j alignments
Format them and combine the sequences
"""
print("\nFormatting alignments\n")
valignments, jalignments = {},{}
all_valignments, all_jalignments = {},{}
#ccalignments, c1alignments, c2alignments, c3alignments = {}, {}, {}, {}
print("I... |
def printWelcome():
menu = """
Welcome to 'Tic-Tac-Toe'
Please, choose your character/symbol.
Menu:
1. Choice X
2. Choice O
3. Random
4. Input
"""
print(menu)
choice = 0
while not (choice == 1 or choice == 2 or choice == 3 or choice == 4):
choice = int(input('')) ... | This code implements a tic-tac-toe game where a player competes against a bot. It alternates turns, checks for wins/draws after each move, and allows replay. The game initializes a board, determines who starts, and handles player input and bot moves until a win, draw, or exit. | def main():
while True:
theBoard = [' '] * 10
playerLetter, botLetter = printWelcome()
turn = whoGoesFirst()
print('\n' + turn + ' goes first.')
gameIsPlaying = True
while gameIsPlaying:
# code for playing
if turn == 'Player':
... |
def _EvenDPG(self, d, *args, **kwargs):
"""Grows G by DPG-adding new node with even degree d"""
try:
M = Matching(self, d//2)
except Exception:
raise DPGfeasibilityError(d)
dpg_node = self._newNodeName()
self._DPGJoin(M, dpg_node)
return self
def h... | The code implements the Degree-based Preferential Growth (DPG) algorithm to expand a graph by adding a node with a specified degree `d`. It handles even and odd degrees differently: even degrees use `_EvenDPG`, while odd degrees check for an auxiliary node to determine whether to use `_OddDPGWithAux` or `_OddDPGWithout... | def DPG(self, d: int):
"""Grows graph G by adding node with degree d using DPG"""
if d < 0:
raise ValueError(f"Degree ({d}) must be non-negative integer.")
if (d % 2) == 0:
return self._EvenDPG(d)
else: # odd degree
if self.hasAuxNode():
... |
def functional_dependency(self, fd):
'''
Converts A->BCD form into A->B, A->C, A->D
and then stores it in an array
'''
fd = [i.replace(' ', '') for i in fd]
fd = [i.split('->') for i in fd]
arr_fd = {}
for i in range(len(fd)):
fd[i][0] = "".... | The code initializes a database normalization analyzer by processing attributes and functional dependencies. It identifies candidate keys, prime/non-prime attributes, closure sets, and determines the normal form (e.g., 1NF, 2NF) of a relational schema. The class computes left/right characters, checks dependencies, and ... | def __init__(self, attr, fd):
self.attributes = {}
for i in attr:
self.attributes[i] = 1
self.fd = self.functional_dependency(fd)
self.children_database = {}
self.prime_attributes = ""
self.non_prime_attributes = ""
self.closures = {}
self.ca... |
def if_2nf(self):
errors = {}
flag = -1
for fd in self.fd:
flag = 1
if fd not in self.candidate_keys:
for key in self.candidate_keys:
if fd in key:
if self.fd[fd] not in self.prime_attributes:
... | The main task of the code is to decompose a database table into Second Normal Form (2NF) by identifying and eliminating partial dependencies. It checks if the table is already in 2NF, identifies functional dependencies causing partial dependencies, generates new tables for each dependency, and recursively converts them... | def convert_to_2nf(self, c = 0):
'''
Converts to 2NF
'''
if c == 0:
print("[Converting the table to 2NF]")
self.children_database = {}
normal_form, errors = self.if_2nf()
if normal_form == "2NF" and c==0:
print("[Table already in 2NF]")
... |
def if_3nf(self):
errors = {}
flag = -1
for fd in self.fd:
flag = 0
for key in self.candidate_keys:
if key in fd:
flag = 1
break
if flag == 0:
if self.fd[fd] in self.prime_attributes:
... | This function decomposes a database into Third Normal Form (3NF) by recursively identifying and splitting tables with violations. It checks for 3NF compliance, computes attribute closures, isolates problematic dependencies, and creates child databases for each violating set. The process repeats until all tables meet 3N... | def convert_to_3nf(self, c=0):
'''
Converts to 3NF
'''
# if c == 3:
# exit(0)
if c == 0:
print("[Converting the table to 3NF]")
self.children_database = {}
normal_form, errors = self.if_3nf()
if normal_form == "3NF" and c == 0:
... |
def if_bcnf(self):
errors = {}
flag = -1
for fd in self.fd:
flag = 0
for key in self.candidate_keys:
if key in fd:
flag = 1
break
if flag == 0:
errors[fd] = self.fd[fd]
... | The main task of the code is to decompose a database table into Boyce-Codd Normal Form (BCNF) by recursively identifying violating functional dependencies, creating child tables for each violation, and ensuring all resulting tables meet BCNF requirements through recursive decomposition. | def convert_to_bcnf(self, c=0):
'''
Converts to BCNF
'''
if c == 0:
print("[Converting the table to BCNF]")
self.children_database = {}
normal_form, errors = self.if_bcnf()
if normal_form == "BCNF" and c == 0:
print("[Table already in BCNF]... |
def computeSingletonPartitions(listofcols):
global data2D
global dictpartitions
for a in listofcols:
dictpartitions[a]=[]
for element in list_duplicates(data2D[a].tolist()): # list_duplicates returns 2-tuples, where 1st is a value, and 2nd is a list of indices where that value occurs
... | The code identifies functional dependencies (FDs) from a CSV file. It reads the data, initializes global variables, computes partitions, iteratively discovers FDs using a level-wise approach, prunes redundant dependencies, and organizes the results into a dictionary mapping determinants to their dependent attributes. T... | def find_fd_from_csv(infile):
global dictCplus
global finallistofFDs
global listofcolumns
global totaltuples
global dictpartitions
global tableT
global data2D
data2D = read_csv(infile)
totaltuples = len(data2D.index)
listofcolumns = list(data2D.columns.values) # returns ['A', '... |
def red(self, mode):
self.__interpret_command__(mode, 0x11, 0x21, 0x41)
def yellow(self, mode):
self.__interpret_command__(mode, 0x12, 0x22, 0x42)
def green(self, mode):
self.__interpret_command__(mode, 0x14, 0x24, 0x44)
def buzzer(self, mode):
self.__interpret_command__(mode, 0x18, 0x28... | The main task of the code is to deactivate all specified components by setting them to "OFF" state, including red, yellow, green lights, and a buzzer, likely resetting a system or stopping all active outputs in a device control context. | def clear_all(self):
self.red("OFF")
self.yellow("OFF")
self.green("OFF")
self.buzzer("OFF") |
def load_taxonomy():
# load in initial taxonomy and aliases
taxonomy_rows = []
with open(TAXONOMY_PATH, encoding="utf8") as _csv_file:
csv_reader = csv.reader(_csv_file, delimiter=',')
for i, row in enumerate(csv_reader):
if i == 0:
continue
else:
... | The code processes grocery lists by extracting noun chunks, mapping them to canonical terms using a taxonomy, counting matches and mismatches, and generating a report on identified vs. unidentified items. | def main():
canonical_to_aliases, alias_to_canonical = load_taxonomy()
grocery_lists = load_grocery_lists()
noun_chunked = [list(NLP(li).noun_chunks) for li in tqdm(grocery_lists)]
item_counter = defaultdict(Counter)
unidentified_counter, to_span_map = exact_match(noun_chunked, item_counter, canon... |
def extract_dob(doc):
dob = []
'''
=== your code goes here ===
'''
# extract date of birth for entity from the abstract
for ent in doc.ents:
if ent.label_ == "DATE":
formatted_text = dob_formatter(ent.text)
if formatted_text == "0-0-0":
continue
... | The function extracts entity-related information (date of birth, nationality, alma mater, awards, workplaces) from an input CSV file using spaCy's NER model, then saves the extracted data into a structured CSV file with specified headers. It processes each entity's abstract text, applies NLP-based extraction functions,... | def your_extracting_function(input_file, result_file):
'''
This function reads the input file (e.g. input.csv)
and extracts the required information of all given entity mentions.
The results is saved in the result file (e.g. results.csv)
'''
with open(result_file, 'w', encoding='utf8') as f... |
def run_process(self, command, arguments, output_file=None, input_file=None, timeout=TEST_CASE_TIMEOUT_DEFAULT):
"""
Execute a shell command and return exit code.
command: string
arguments: list of strings
output_file: file to write output
"""
try:
if ... | The code executes a test by running a specified test suite in different modes (exe, spim, logisim), capturing actual output, comparing it with expected output, checking for errors (exit status, segmentation faults, memory leaks via Valgrind), and returning pass/fail status, error flags, diff results, and output content... | def execute_test(self, test_suite_name, test_num, args, is_valgrind, diff_type, filter_type, timeout=None):
"""
Execute a test, get output and calculate score.
"""
executable_file_name = None
if self.force_suite_filename:
executable_file_name = self.force_suite_filena... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.