dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def isSorted(matrix, numtubes):
for i in range(numtubes):
if isHomogenous(matrix, i):
continue
elif isEmpty(matrix, i):
continue
else: return False
return True
def allPossyMoves(matrix:List[List[int]], numtubes):
possibleMoves =[]
topBalls =[]
for i in... | This function implements A* search to find an optimal path from a start state to a sorted state in a puzzle. It maintains a frontier of states to explore, selecting the one with the lowest combined cost and heuristic. It generates possible moves, creates new states, and updates the frontier/closed list to avoid cycles.... | def astForSolver(startState: State, tubenum):
closed, frontier = [], []
frontier.append(startState)
currentState = startState
expandthNum = 1
#goal test
if isSorted(currentState.state, tubenum):
return currentState
while frontier:
leastCost= frontier[0]
for e ... |
def _check_keydown_events(self, event):
if event.key == pygame.K_RIGHT:
self.wolf.moving_right = True
self.wolf.bg_scrolling_left = True
self.wolf.wolf_look_left = False
elif event.key == pygame.K_LEFT:
self.wolf.moving_left = True
self.wolf.bg... | This method handles Pygame events: exits on quit, processes key presses/releases, and detects mouse clicks to check button interactions. It then calculates background positions based on the wolf's horizontal position relative to the screen width, ensuring seamless tiling by adjusting first_bg and second_bg values. | def _check_events(self):
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.KEYDOWN:
self._check_keydown_events(event)
elif event.type == pygame.KEYUP:
self._check_keyup_events(ev... |
def _check_events(self):
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.KEYDOWN:
self._check_keydown_events(event)
elif event.type == pygame.KEYUP:
self._check_keyup_events(ev... | The code runs a game loop that continuously checks for events, updates game elements (wolf movement, background scrolling, boar behavior), handles collisions between the wolf and boars/meat, and renders the screen when the game is active, maintaining gameplay flow until stopped. | def run_game(self):
while True:
self._check_events()
if self.game_active:
self.wolf.update()
self.wolf.scrolling_bg()
self._boars_run()
self._check_wolf_boar_collisions()
self._check_wolf_meat_collisions()
... |
def GetLineSize(line_tuples):
line_size = 0
for tmp_tuple in line_tuples:
line_size += tmp_tuple[1] - tmp_tuple[0]
return line_size
def write_log(fmt_str):
if not log_on:
return 0
try:
log_fd.write(fmt_str)
return 0
except:
# print("Fail to write log file\n... | This function calculates and logs key I/O performance factors from distributed system data. It computes total read/write IO times, extracts global statistics using ExtractFactors, and identifies top IO consumers via CalSweeplineFactors if sweep lines exist. The results help analyze I/O bottlenecks and resource distribu... | def ExtractContriFactors(ds_rank_stat_dict, ds_glb_dict,\
ds_file_stat_dict, wr_sweep_line_set,\
r_line_tuples, w_line_tuples,\
wr_line_tuples, ds_rank_io, \
line_point = None):
ds_tot_iotime = GetLineSize(w... |
def generate_edges(graph):
edges = []
for node in graph:
for neighbour in graph[node]:
if (node,neighbour) and (neighbour, node) not in edges:
edges.append((node,neighbour))
return edges
def start_subsets(set_, k):
curr_subset = []
res = []
generate_subsets(s... | The code implements a brute-force algorithm to find a minimal vertex cover in a graph. It generates all possible subsets of vertices starting from size 1, checks each subset to see if it covers all edges, and returns the first valid subset found. The result is stored in the 'res' list. | def vertex_cover_brute(graph, res):
vertices = list(dict(graph).keys())
k = len(vertices)
edges = generate_edges(graph)
for i in range(1, k):
subsets_ = start_subsets(vertices, i)
for s in subsets_:
if verify_vertex_cover(s, edges) == True:
res.append(s)
... |
def second_save():
image=Image.fromarray(img1)
canny_pics=cv2.Canny(img1,100,40)
file="/home/pi/ROSA---i/train_images/folderA/img_black_02"+".jpg"
cv2.imwrite(file,canny_pics)
def twodone():
bt2=Button(window,image=donesym1)
bt2.place(relx=0.11,rely=0.47,relwidth=0.06,rel... | This code creates a button (bt2) with a specific image, no border, white background, and assigns a lambda function as its command. When clicked, the button triggers three actions: saving data with second_save(), marking a step as complete with twodone(), and navigating to the third photo function with third_photo(). Th... | def second_photo():
bt2=Button(window,image=two1,border=0,bg="white",command=lambda :[second_save(),twodone(),third_photo()])
bt2.place(relx=0.11,rely=0.47,relwidth=0.06,relheight=0.08) |
def secondphoto_second():
image=Image.fromarray(img1)
canny_pics=cv2.Canny(img1,100,40)
file="/home/pi/ROSA---i/train_images/folderB/img_black_02"+".jpg"
cv2.imwrite(file,canny_pics)
def twodone():
bt2=Button(window,image=donesym1)
bt2.place(relx=0.11,rely=0.47,relwidth=0... | The code defines a function `second_button()` that creates a GUI button with a specific image, no border, white background, and a command to execute three functions: `secondphoto_second()`, `twodone()`, and `third_button()` upon clicking. The button is positioned at (0.11, 0.47) with a size of 0.06x0.08 relative to the... | def second_button():
bt2=Button(window,image=two1,border=0,bg="white",command=lambda :[secondphoto_second(),twodone(),third_button()])
bt2.place(relx=0.11,rely=0.47,relwidth=0.06,relheight=0.08) |
def secondphoto_third():
image=Image.fromarray(img1)
canny_pics=cv2.Canny(img1,100,40)
file="/home/pi/ROSA---i/train_images/folderC/img_black_02"+".jpg"
cv2.imwrite(file,canny_pics)
def twodone():
bt2=Button(window,image=donesym1)
bt2.place(relx=0.11,rely=0.47,relwidth=0.... | The function `second_snap()` creates a GUI button with a specific image, white background, and no border. When clicked, it triggers three actions: `secondphoto_third()`, `twodone()`, and `third_snap()`. The button is positioned at coordinates (0.11, 0.47) with a size of 0.06x0.08 relative to the window. Its main task i... | def second_snap():
bt2=Button(window,image=two1,border=0,bg="white",command=lambda :[secondphoto_third(),twodone(),third_snap()])
bt2.place(relx=0.11,rely=0.47,relwidth=0.06,relheight=0.08) |
def secondphoto_fourth():
image=Image.fromarray(img1)
canny_pics=cv2.Canny(img1,100,40)
file="/home/pi/ROSA---i/train_images/folderD/img_black_02"+".jpg"
cv2.imwrite(file,canny_pics)
def twodone():
bt2=Button(window,image=donesym1)
bt2.place(relx=0.11,rely=0.47,relwidth=0... | This code creates a Tkinter button in a GUI application. The button, placed at specific coordinates, triggers three functions upon clicking: `secondphoto_fourth()` (likely displaying an image), `twodone()` (marking a step as completed), and `third_snap4()` (advancing to the next step). It uses an image `two1` with no b... | def second_snap4():
bt2=Button(window,image=two1,border=0,bg="white",command=lambda :[secondphoto_fourth(),twodone(),third_snap4()])
bt2.place(relx=0.11,rely=0.47,relwidth=0.06,relheight=0.08) |
def first_save():
image=Image.fromarray(img1)
canny_pics=cv2.Canny(img1,100,40)
file="/home/pi/ROSA---i/train_images/folderA/img_black_01"+".jpg"
cv2.imwrite(file,canny_pics)
def onedone():
donesym1=PhotoImage(file="doonesymbol.png")
btt1=Button(window,image=donesym1)
... | The code defines a function `folder1_path()` that creates and positions two buttons on a GUI window. The first button (bt_1) displays a camera capture image, while the second button (bt1) triggers three actions—`first_save()`, `onedone()`, and `second_photo()`—when clicked. The buttons are styled with no border, white ... | def folder1_path():
bt_1=Button(window,image=capture_camera,border=0,bg="white")
bt_1.place(relx=0.11,rely=0.21,relwidth=0.07,relheight=0.099)
bt1=Button(window,image=one1,border=0,bg="white", command=lambda:[first_save(),onedone(),second_photo()])
bt1.place(relx=0.11,rely=0.34,relwidt... |
def firstphoto_second():
image=Image.fromarray(img1)
canny_pics=cv2.Canny(img1,100,40)
file="/home/pi/ROSA---i/train_images/folderB/img_black_01"+".jpg"
cv2.imwrite(file,canny_pics)
def onedone():
donesym1=PhotoImage(file="doonesymbol.png")
btt1=Button(window,image=donesy... | The code defines a function `folder2_path()` that creates and places two buttons on a GUI window using Tkinter. The first button (`bt_1`) is positioned with specific coordinates and dimensions but lacks a command. The second button (`bt1`) is linked to a lambda function that triggers three actions: capturing a photo, m... | def folder2_path():
bt_1=Button(window,image=capture_camera,border=0,bg="white")
bt_1.place(relx=0.11,rely=0.21,relwidth=0.07,relheight=0.099)
bt1=Button(window,image=one1,border=0,bg="white", command=lambda:[firstphoto_second(),onedone(),second_button()])
bt1.place(relx=0.11,rely=0.34,... |
def firstphoto_third():
image=Image.fromarray(img1)
canny_pics=cv2.Canny(img1,100,40)
file="/home/pi/ROSA---i/train_images/folderC/img_black_01"+".jpg"
cv2.imwrite(file,canny_pics)
def onedone():
donesym1=PhotoImage(file="doonesymbol.png")
btt1=Button(window,image=donesym... | The code defines a function `folder3_path()` that creates two buttons in a GUI. The first button (bt_1) displays a camera capture image, while the second button (bt1) triggers three actions: capturing a photo, marking it as done, and taking a second snapshot. Both buttons are positioned using relative coordinates and d... | def folder3_path():
bt_1=Button(window,image=capture_camera,border=0,bg="white")
bt_1.place(relx=0.11,rely=0.21,relwidth=0.07,relheight=0.099)
bt1=Button(window,image=one1,border=0,bg="white", command=lambda:[firstphoto_third(),onedone(),second_snap()])
bt1.place(relx=0.11,rely=0.34,rel... |
def firstphoto_fourth():
image=Image.fromarray(img1)
canny_pics=cv2.Canny(img1,100,40)
file="/home/pi/ROSA---i/train_images/folderD/img_black_01"+".jpg"
cv2.imwrite(file,canny_pics)
def onedone():
donesym1=PhotoImage(file="doonesymbol.png")
btt1=Button(window,image=donesy... | The code defines a function `folder4_path()` that creates two buttons on a GUI window. The first button (bt_1) displays a camera capture image without a command. The second button (bt1) triggers three actions—`firstphoto_fourth()`, `onedone()`, and `second_snap4()`—when clicked, likely handling photo capture, processin... | def folder4_path():
bt_1=Button(window,image=capture_camera,border=0,bg="white")
bt_1.place(relx=0.11,rely=0.21,relwidth=0.07,relheight=0.099)
bt1=Button(window,image=one1,border=0,bg="white", command=lambda:[firstphoto_fourth(),onedone(),second_snap4()])
bt1.place(relx=0.11,rely=0.34,r... |
def buttonHandler(buttonIndex, buttonState):
try:
# TODO: Identify hotkeys or macros to use
if (buttonState == 1):
if (buttonIndex == 1):
print("Previous track")
win32api.keybd_event(VK_MEDIA_PREV_TRACK, 0, KEYEVENTF_EXTENDEDKEY, 0)
elif (butto... | The function `processSerial` processes incoming serial data by splitting it into components and routing actions to specific handlers based on the first token. It calls `buttonHandler`, `switchHandler`, `rotaryEncoderHandler`, or `potentiometerHandler` depending on whether the data starts with "s", "t", "re", or "p", re... | def processSerial(data):
try:
dataSplit = data.split(" ")
if (dataSplit[0] == "s"):
buttonHandler(int(dataSplit[1]), int(dataSplit[2]))
elif (dataSplit[0] == "t"):
switchHandler(int(dataSplit[1]), int(dataSplit[2]))
elif (dataSplit[0] == "re"):
rot... |
def switchHandler(switchIndex, switchState):
global previousMute
try:
switches = switchState.split(" ")
for i in range(len(switches) - 1):
if (int(switches[i]) != previousMute[i]):
previousMute[i] = int(switches[i])
setMute(switches[i], apps[i])
ex... | The function processes serial data by splitting it into components, checks for changes compared to previous data, and routes each component to specific handlers (switch, rotary encoder, potentiometer) based on its prefix. It updates the global `previousData` variable and handles exceptions by printing errors. | def processSerial(data):
try:
global previousData
if (data != previousData):
previousData = data
dataSplit = data.split("|")
for i in range(len(dataSplit)):
split = dataSplit[i].split(":")
if (split[0].__contains__("S ")):
... |
def find_ucs_rout(source, target):
'call function to find path, and return list of indices'
def f(node): return node.path_cost
paths = best_first_graph_search(Routing_Problem(roads, source, target), f)
# converts each link to its source index, and adds target at the end
path_indices = list(map(lambd... | The code's main task is to determine and print the shortest path between two nodes (`source` and `target`) using a specified pathfinding algorithm. It accepts command-line arguments: the algorithm type (`ucs`, `astar`, or `idastar`) and the source/target node IDs. Based on the algorithm, it calls the corresponding rout... | def dispatch(argv):
from sys import argv
source, target = int(argv[2]), int(argv[3])
if argv[1] == 'ucs':
path = find_ucs_rout(source, target)
elif argv[1] == 'astar':
path = find_astar_route(source, target)
elif argv[1] == 'idastar':
path = find_idastar_route(source, target)... |
def findNeighbourAggregation(data):
# using 5 nearest neighbour + one self
# denominatior = sqrt(|N(v)|*|N(u)|) = 5
# numerator = summation of neighbours
totalRows, totalCols = data.shape
finalAgg = []
for i in range(totalRows):
row1 = data[i]
dist = []
idx = [] # store the 5 index which a... | The code trains a Graph Convolutional Network (GCN) for multiple labels by aggregating neighborhood features from training and test data. For each label, it collects features, normalizes them, performs neighborhood aggregation, trains the GCN, computes accuracy, and saves aggregated features and scores into pickle file... | def start_training(l1, l2, file):
train_agg = []
test_agg = []
score_res = {}
test_scores = []
train_scores = []
mx = 1001
for l in range(l1,l2+1):
print ("Training for label " + str(l))
trainFeatures = []
trainLabels = []
testLabels = []
c = 0
... |
def __check_robot(self, robot):
if not isinstance(robot, Robot):
raise ValueError("{} must be a Robot instance.".format(robot))
if not robot in self.robots:
raise ValueError("{} is not in the Voronoi diagram.".format(robot))
def __sense_neighbors(self):
if len(self.robots... | This function computes a bounded Voronoi diagram for a robot and its neighbors, adjusting regions to fit the robot's perimeter. It generates mirrored points, calculates intersections between Voronoi edges and the perimeter, collects valid points, sorts them, and creates a polygon representing the bounded Voronoi cell f... | def __local_voronoi(self, robot):
"""
Bounded Voronoi Computation
"""
# Setups
self.__check_robot(robot) # To check if the robot is valid
self.__sense_neighbors() # To sense the neighbors of the robot
perimeter = self.__compute_perimeter(robot) # To compute the pe... |
def bn(x):
return tf.layers.batch_normalization(x)
def relu(x):
return tf.nn.relu(x)
def seblock(x, in_cn):
squeeze = Global_Average_Pooling(x)
with tf.variable_scope('sq'):
h = dense(squeeze, in_cn//16, activation_fn=None)
excitation = relu(h)
with tf.variable_scope('ex'):
... | This code defines a residual block with two convolutional layers, batch normalization, ReLU activation, and a squeeze-and-excitation (SE) block. It computes a shortcut connection by adding the original input to the output of the SE block, enabling residual learning to improve gradient flow and model performance. | def residual_block(x, cn, scope_name):
with tf.variable_scope(scope_name):
shortcut = x
x1 = bn(relu(conv2d(x, cn, kernel_size=(5, 5), stride=(1, 1), padding='SAME', activation_fn=None)))
x2 = bn(relu(conv2d(x1, cn, kernel_size=(5, 5), stride=(1, 1), padding='SAME', activation_fn=None)))
... |
def relu(x):
return tf.nn.relu(x)
def bn(x):
return tf.layers.batch_normalization(x)
def residual_block(x, cn, scope_name):
with tf.variable_scope(scope_name):
shortcut = x
x1 = bn(relu(conv2d(x, cn, kernel_size=(5, 5), stride=(1, 1), padding='SAME', activation_fn=None)))
x2 = bn(rel... | This code defines a convolutional neural network with an encoder-decoder architecture, incorporating residual blocks. The encoder downsamples input through convolutional layers with increasing filters, the residual section refines features via multiple residual blocks, and the decoder upsamples back to original dimensi... | def network(gen_inputs):
with tf.variable_scope('encoder'):
x1 = relu(bn(conv2d(gen_inputs, 16, kernel_size=(5, 5), stride=(1, 1), padding='SAME', activation_fn=None)))
x2 = relu(bn(conv2d(x1, 32, kernel_size=(5, 5), stride=(2, 2), padding='SAME', activation_fn=None)))
x3 = relu(bn(conv2d(... |
def get_move(self, cell):
moves = self.map.get_valid_moves(cell)
values = []
for move in moves:
new_cell = self.map.move(cell, move)
values.append(self.values[new_cell.id])
max_value = max(values)
max_values_index = [index for index,value in enumerate(val... | This function updates the robot's movement, tracks steps and rewards, checks termination conditions (win or max steps), and handles episode reset or statistics saving. It returns whether the maximum iterations were reached. | def update(self) -> bool:
direction = self.get_move(self.robot.current_cell)
win, reward = self.robot.step(direction)
self.steps_number += 1
self.episode_reward += reward
last_iteration = self.iteration_number > self.max_iteration
if last_iteration:
self.calc... |
def get_move(self, cell) -> Directions:
legal_moves = self.map.get_valid_moves(cell)
values = []
for move in legal_moves:
new_cell = self.map.move(cell, move)
values.append(self.q_values[self.directions.index(move)][new_cell.id])
max_value = max(values)
m... | The code updates the robot's movement, tracks steps and rewards, checks termination conditions (win or max steps), resets episodes if needed, and handles final statistics and plotting when the maximum number of games is reached. It returns whether the current iteration is the last one. | def update(self) -> bool:
direction = self.get_move(self.robot.current_cell)
win, reward = self.robot.step(direction)
self.steps_number += 1
self.game_reward += reward
last_iteration = self.game_number > self.max_games
if last_iteration:
self.calculate_... |
def segments_from_csv(filename) -> Iterable[Segment]:
return map(Segment._make, csv_rows(filename))
def segment_to_anki_card_reqs(
segment: Segment, video_path: str, video_id: str, video_title: str, video_url: str
) -> AnkiCardReqs:
start_frame, end_frame, polish, english = segment
fps = 30
start_... | This code processes video segments from a CSV file, generates Anki card data using video metadata from an INI file, and writes the cards to an output CSV. It reads configuration details, transforms each segment into Anki card requests, converts them to card objects, and exports them with headers and rows to the specifi... | def main(video_path, video_ini_path, input_file, output_file):
config = configparser.ConfigParser()
config.read(video_ini_path)
video_id = config["video"]["id"]
video_title = config["video"]["title"]
video_url = config["video"]["url"]
segments = segments_from_csv(input_file)
anki_card_reqs ... |
def frame_generator(video: cv2.VideoCapture) -> FrameGenerator:
while True:
ret: bool
frame_color: Optional[Frame]
ret, frame_color = video.read()
if ret:
frame_bw = cv2.cvtColor(frame_color, cv2.COLOR_BGR2GRAY)
yield frame_bw
else:
break
d... | The code processes a video to segment it into meaningful parts based on caption similarity thresholds, extracts and averages textual content from each segment, filters out short segments, and writes the resulting segments (with start/end frames and averaged text) to a CSV file for further analysis or storage. | def main(
video_path: str,
caption_video_similarity_cutoff: float,
caption_text_similarity_cutoff: int,
outfile: str,
) -> None:
video: cv2.VideoCapture = cv2.VideoCapture(video_path)
fps: float = video.get(cv2.CAP_PROP_FPS)
frame_gen: FrameGenerator = frame_generator(video)
frame_pair... |
def kx(self, phi, r):
return 1 - 0.00347 * (phi - 30) - 0.978 * ((1 / r) - 0.05)
def Fx(self, v, e ,l):
return 303 * self.x2x(v, e, l)
def fcx(self, e, icd, v, l):
return (0.210 * self.td(e, icd)) * (1 + 0.2 * self.x2x(v, e, l)) | The function computes a value by multiplying the result of `self.kx(phi, r)` with the difference between `self.Fx(v, e, l)` and the product of `self.fcx(e, icd, v, l)` and `QcX`, returning the final result. | def c(self, v, e, l, r, icd, phi, QcX):
return self.kx(phi, r) * (self.Fx(v, e, l) - self.fcx(e, icd, v, l) * QcX) |
def classify(self, y):
data = Counter(y)
return data.most_common(1)[0][0]
def find_split(self, X, y):
best_gain = -1
best_thresh = 0
best_feature = 0
for i in range(X.shape[1]): # number of features in dataset
total = np.unique(X[:, i]) # getting all unique ... | The function recursively builds a decision tree by splitting the dataset based on the best feature and threshold, creating internal nodes with left/right subtrees or leaf nodes with class labels when stopping conditions are met (max depth, pure class, or sample limit). | def build_tree(self, X, y, current_depth):
if (current_depth == self.mx_depth) or (len(np.unique(y)) == 1) or (len(y) <= self.mx_samples):
val_label = self.classify(y)
return Node(label=val_label)
else:
best_feature, best_thresh, best_gain = self.find_split(X, y)
... |
def logout():
print("*************************")
print("Thank you!!")
print("*************************")
exit()
def newac():
print('Welcome to RBank')
t=str(input("Pls enter ur name: "))
d=int(input("Deposit an amount of: "))
p=str(input("Enter a password: "))
rp=str(input("Re-enter ... | The code's main task is to present a menu for RBank users to either create a new account or access account services. It validates user input, handles authentication for existing accounts, and directs users to appropriate functions (newac() or services()) based on their choice. Error handling ensures only valid options ... | def main():
print("**************************")
print("Welcome to RBank")
print("**************************")
print("1. Create new account")
print("2. Account Services")
print("Choose to proceed")
try:
t=int(input())
except:
print("Choose between 1 and 2 only")
lo... |
def _run_tool_on_document(
document: workspace.Document,
use_stdin: bool = False,
extra_args: Sequence[str] = [],
) -> utils.RunResult | None:
"""Runs tool on the given document.
if use_stdin is true then contents of the document is passed to the
tool via stdin.
"""
if utils.is_stdlib_f... | The function formats a document using an external tool, adjusts line endings, and returns LSP text edits if the formatted content differs from the original. It logs output when tracing is enabled, trims trailing line endings in notebook cells, and avoids edits if no changes are needed. | def _formatting_helper(document: workspace.Document) -> list[lsp.TextEdit] | None:
result = _run_tool_on_document(document, use_stdin=True)
if result and result.stdout:
if LSP_SERVER.lsp.trace == lsp.TraceValues.Verbose:
log_to_output(
f"{document.uri} :\r\n"
... |
def _run_tool(extra_args: Sequence[str], settings: Dict[str, Any]) -> utils.RunResult:
"""Runs tool."""
code_workspace = settings["workspaceFS"]
cwd = settings["cwd"]
use_path = False
use_rpc = False
if len(settings["path"]) > 0:
# 'path' setting takes priority over everything.
... | The function checks the version of a code formatter (e.g., autopep8) in each workspace against a minimum required version. It runs the formatter's `--version` command, parses the output, and logs whether the installed version meets the minimum. If not, it raises an error. It also detects missing dependencies like `type... | def _log_version_info() -> None:
for value in WORKSPACE_SETTINGS.values():
try:
from packaging.version import parse as parse_version
settings = copy.deepcopy(value)
result = _run_tool(["--version"], settings)
code_workspace = settings["workspaceFS"]
... |
def _get_settings_by_document(document: workspace.Document | None):
if document is None or document.path is None:
return list(WORKSPACE_SETTINGS.values())[0]
key = _get_document_key(document)
if key is None:
# This is either a non-workspace file or there is no workspace.
key = os.fs... | This function performs linting on a document by running a tool with version-specific arguments, logs the output, parses it into diagnostics based on settings, and returns them. It handles errors by displaying messages and returns an empty list if no output or errors occur. | def _linting_helper(document: workspace.Document) -> list[lsp.Diagnostic]:
try:
extra_args = []
code_workspace = _get_settings_by_document(document)["workspaceFS"]
if VERSION_TABLE.get(code_workspace, None):
major, minor, _ = VERSION_TABLE[code_workspace]
if major ==... |
def _run_tool(extra_args: Sequence[str], settings: Dict[str, Any]) -> utils.RunResult:
"""Runs tool."""
code_workspace = settings["workspaceFS"]
cwd = settings["cwd"]
use_path = False
use_rpc = False
if len(settings["path"]) > 0:
# 'path' setting takes priority over everything.
... | The function `_log_version_info` checks the version of a linter (e.g., pylint) for each workspace by running `--version`, parses the output, compares it against a minimum required version, and logs whether the version is supported. It stores the parsed version in a table and raises errors if the linter version is outda... | def _log_version_info() -> None:
for value in WORKSPACE_SETTINGS.values():
try:
from packaging.version import parse as parse_version
settings = copy.deepcopy(value)
result = _run_tool(["--version"], settings)
code_workspace = settings["workspaceFS"]
... |
def log_to_output(
message: str, msg_type: lsp.MessageType = lsp.MessageType.Log
) -> None:
"""Logs messages to Output > autopep8 channel only."""
LSP_SERVER.show_message_log(message, msg_type)
def _workaround_for_autopep8_reload_issue():
# workaround for reload issue with autopep8
# https://github.... | The main task of the code is to handle an LSP (Language Server Protocol) initialization request by logging environment/config details, updating global/workspace settings from provided parameters, and applying workarounds. It captures the current working directory, Python path, PYTHONPATH, and initialization options, th... | def initialize(params: lsp.InitializeParams) -> None:
"""LSP handler for initialize request."""
log_to_output(f"CWD Server: {os.getcwd()}")
paths = "\r\n ".join(sys.path)
log_to_output(f"sys.path used to run Server:\r\n {paths}")
_workaround_for_autopep8_reload_issue()
log_to_output(f"PYTH... |
def log_to_output(
message: str, msg_type: lsp.MessageType = lsp.MessageType.Log
) -> None:
"""Logs messages to Output > Pylint channel only."""
LSP_SERVER.show_message_log(message, msg_type)
def update_sys_path(path_to_add: str, strategy: str) -> None:
"""Add given path to `sys.path`."""
if path_to... | The main task of the code is to initialize an LSP server by configuring the environment, updating Python's sys.path with project-specific and global settings, applying initialization options from the client, and logging critical runtime information like working directory, settings, and path configurations for debugging... | def initialize(params: lsp.InitializeParams) -> None:
"""LSP handler for initialize request."""
log_to_output(f"CWD Server: {os.getcwd()}")
import_strategy = os.getenv("LS_IMPORT_STRATEGY", "useBundled")
update_sys_path(os.getcwd(), import_strategy)
GLOBAL_SETTINGS.update(**params.initialization_op... |
def enter_dis_sleep(self, seconds, phase='', freq=15):
self.logger.log_event_info('Entering {} sleep'.format(phase))
while seconds > 0:
start_time = time.time()
rejoin_button = self.driver.find_elements_by_xpath(REJOIN_BUTTON)
if rejoin_button:
self.fi... | This function automates attendance scanning by taking screenshots at intervals, detecting presence via image processing, and posting attendance messages if detected. It manages timing within a specified window, handles chat button interactions, and logs events. It returns whether a message was successfully posted. | def attendance_suspend(self, class_running_time, class_name, window=600, freq=15):
logger = self.logger
# driver = self.driver
if window >= class_running_time:
return
self.enter_dis_sleep(class_running_time - window, 'initial')
logger.log_event_info('Starting attendan... |
def take_screenshot(self, filepath, enabled=1):
if enabled:
self.driver.save_screenshot(filepath)
def attendance_suspend(self, class_running_time, class_name, window=600, freq=15):
logger = self.logger
# driver = self.driver
if window >= class_running_time:
return... | The main task of the code is to automate leaving a class session by interacting with a web application, handling potential errors (e.g., element not found, uninteractable elements), taking screenshots, calculating time intervals, and notifying Discord of the class exit. It attempts to click buttons to return to the hom... | def leave_class(self, class_name, start_time, end_time):
# now schedule leaving class
driver = self.driver
logger = self.logger
'''
cross_button = driver.find_elements_by_css_selector(MIC_MUTED_CROSS)
if cross_button:
cross_button[0].click()
'''
... |
def take_screenshot(self, filepath, enabled=1):
if enabled:
self.driver.save_screenshot(filepath)
def final_join_proc(self, k=3, rejoin=0):
driver = self.driver
logger = self.logger
while k >= 0:
try:
if rejoin:
driver.find_elem... | The main task of the code is to automatically join a specified online class session using Selenium, with retry logic and error handling. It searches for the class channel, clicks to join, handles exceptions like missing elements or interactability issues, and logs status updates. If unsuccessful after retries, it attem... | def join_class(self, class_name, start_time, end_time):
driver = self.driver
logger = self.logger
discord_message = lambda status: (self.ign, class_name, status, start_time, end_time)
k = 3
while k >= 0:
try:
channel_found = False
time... |
def load(image_file):
image = tf.io.read_file(image_file)
image = tf.image.decode_jpeg(image)
w = tf.shape(image)[1]
w = w // 2
real_image = image[:, :w, :]
input_image = image[:, w:, :]
input_image = tf.cast(input_image, tf.float32)
real_image = tf.cast(real_image, tf.float32)
r... | The function `load_image_train` processes an input image file for training by loading the image, applying random jitter for data augmentation, normalizing pixel values, and returning the processed input and real images. | def load_image_train(image_file):
input_image, real_image = load(image_file)
input_image, real_image = random_jitter(input_image, real_image)
input_image, real_image = normalize(input_image, real_image)
return input_image, real_image |
def wait_until_found(image_name, confidence=1, timeout_seconds=None, check_interval=0.5):
print(f"Looking for {image_name}")
total_seconds = 0
while timeout_seconds is None or total_seconds < timeout_seconds or timeout_seconds == 0:
location = pyautogui.locateCenterOnScreen(settings.images_folder + ... | This function locates an image on the screen using specified confidence, waits up to timeout_seconds to find it, moves the mouse to the image's center, clicks it after a brief delay, and returns True if successful or False if the image isn't found. | def find_and_click(image_name, confidence=1, timeout_seconds=None, check_interval=0.5):
if timeout_seconds == 0:
location = pyautogui.locateCenterOnScreen(settings.images_folder + image_name, confidence=confidence)
else:
location = wait_until_found(image_name, confidence, timeout_seconds, check_... |
def move_mouse(destination_x, destination_y):
mouse_speed_min = MOUSE_SPEED_RANDOM_MIN
mouse_speed_max = MOUSE_SPEED_RANDOM_MAX
x_start, y_start = pyautogui.position() # current position
x, y = pyautogui.position() # current position
angle_curve = ANGLE_OVERALL_CURVE * (1 if random.random() > 0.5 ... | The function searches for a specified image by moving the mouse in a grid pattern around a starting point. It calculates grid steps based on window height, iterates through rows/columns within a 3-grid-size radius, moves the mouse to each position, checks for the image with 80% confidence, and clicks if found. Returns ... | def find_with_mouse(point, image_name):
grid_size = math.floor(count_run.window.height * 0.1)
# Maximum distance from the starting point
max_distance = 3 * grid_size
# Loop through rows
for i in range(-max_distance, max_distance + grid_size, grid_size):
# Loop through columns
for j... |
def printMethodDetails():
print("Select a number from options listed below!")
print("1. Get user details.")
print("2. Get all countries details.")
print("3. Check if a number is prime.")
print("4. Get your current location.")
def selectAndExecuteMethod():
functionNumber = input("Enter the functi... | The main task of the code is to execute a sequence of operations: print method details, allow user selection and execution of a method, and then close resources without forcing termination. The function orchestrates initialization, interaction, and cleanup in a structured workflow. | def main():
printMethodDetails()
selectAndExecuteMethod()
close(False) |
def parse_obj_file(obj_file_name) -> ParsedObjData:
obj_file_path, obj_file_name = path.split(obj_file_name)
if not obj_file_name.endswith(".obj"):
raise RuntimeError(f"Can't load '{obj_file_name}', because it is not an .obj file")
positions = []
texture_positions = []
normals = []
fa... | This function parses an OBJ file, optionally normalizes vertex positions, and binds the resulting mesh data into a usable format for 3D rendering or processing. | def parse_and_bind_obj_file(obj_file_name, should_normalize_positions=True):
obj_data = parse_obj_file(obj_file_name)
if should_normalize_positions:
normalize_positions(obj_data)
return bind_mesh_data(obj_data) |
def createHearts():
for i in range(3):
heart = GameObject(
Transform(
position=glm.vec3(-8.0, -4.0 + i * 3.0, 0.0),
parent=hearts_parent.transform,
),
obj_data=hearth_obj,
)
heart.leave_set(GameObject.WithObjData)
he... | This function handles keyboard inputs to control a cube's rotation and game actions. It exits on ESC, resets the game on spacebar (if life is 0), and toggles rotation directions (horizontal/vertical/none) for keys d/w/a/s, updating display and collision checks accordingly. | def keyboard_input(key, x, y):
if key == b'\x1b':
sys.exit()
if key == b' ':
if cube.life == 0:
gl.glClearColor(0.2, 0.2, 0.2, 0)
createHearts()
createPlayground()
cube.life = 3
makeInitialFallEffect()
if key == b'd':
if cube.ro... |
def extract_content(self, event_data):
image_ndarray = self.get_event_data_image_ndarray(event_data)
prediction = self.model.predict_caption(image_ndarray)
return prediction
def enrich_event_data(self, event_data, model_result):
self.logger.debug('Enriching event data with model result')... | The code processes event data by first delegating to the parent class's method. If successful, it extracts content, enriches the event data with this content, and forwards the updated data to the next destinations in the processing pipeline. | def process_data_event(self, event_data, json_msg):
if not super(EncoderCaptionService, self).process_data_event(event_data, json_msg):
return False
model_result = self.extract_content(event_data)
event_data = self.enrich_event_data(event_data, model_result)
self.send_to_next... |
def _update_confidence(self):
new_confidence = np.copy(self.confidence)
front_positions = np.argwhere(self.front == 1)
# print("front position :",len(front_positions), front_positions)
for point in front_positions:
patch = self._get_patch(point)
# print('patch:',... | The main task of the code is to update the priority value by combining three factors—confidence, data, and H_p—using a weighted sum (3/5 confidence + 1/5 data + 1/5 H_p), then multiplying the result by the front factor. This involves calling helper methods to update confidence, compute gradient data, and process the st... | def _update_priority(self): # priority function
self._update_confidence()
gradient = self._update_data()
self._structure_tensor(gradient)
# self.priority = self.confidence * self.data * self.front
self.priority = (3/5 * self.confidence + 1/5 * self.data + 1/5 * self.H_p) * self.f... |
def displayAllUsers():
users = mysql.getAllInfo()
data = [list(item) for item in users]
users_ID = [item[0] for item in users]
headers = ["ID", "Unique ID", "First Name", "Last Name", "Description", "IP-address", "MAC-address", "Blocked websites"]
table = tabulate(data, headers=headers, tablefmt="f... | This code provides a menu-driven interface for managing user operations, including displaying all users, adding, editing, or deleting users. It handles user input through a loop, offering options to navigate back to the main menu, view help, or refresh the screen, with specific functions called based on user choices. | def users():
header()
print(users_options)
while True:
choice = inputTxt("Users")
match choice:
case "1":
header()
displayAllUsers()
print(users_options)
case "2":
addUser()
... |
def scrape(outlookemail, password, imap_url, username):
try:
# Connect to the IMAP server using the provided credentials
mail = imaplib.IMAP4_SSL(imap_url)
mail.login(outlookemail, password)
# Select the mailbox you want to fetch emails from
mailbox = "INBOX"
mail.se... | This code creates an email configuration GUI window with fields for entering email credentials, IMAP URL, and buttons to submit data, display records, and search emails. It uses CTk components, stores user input, and triggers functions for data processing and retrieval. | def open_email_configuration_window(username):
global email_config_window
email_config_window = ctk.CTkToplevel(root)
email_config_window.geometry("700x550")
frame = ctk.CTkFrame(master=email_config_window)
frame.pack(pady=20, padx=60, fill="both", expand=True)
email_config_window.title("Emai... |
def connect_to_db():
return mysql.connector.connect(
host="localhost",
user="root",
password="",
database="caa"
)
def get_usertype(username):
# Connect to the MySQL database and fetch the userID based on the username
# Modify this part to fit your database schema and quer... | The main task of the code is to authenticate a user by verifying their username and password against a MySQL database. If valid, it retrieves the user's type (Staff/Admin), updates global variables, and opens corresponding interfaces (email config or admin dashboard). It handles database connections, error reporting, a... | def authenticate_user():
global logged_in_user_id
global logged_in_usertype
username = entry_username.get()
password = entry_password.get()
try:
# Connect to the MySQL database
connection = connect_to_db()
cursor = connection.cursor()
# Execute a query to check if t... |
def format(patient):
print(patient)
depart = "Department: " + patient.department + "\n"
name = "Name: "+ patient.name + "\n"
birth = "Date of Birth: " + patient.birth + "\n"
social = "SSN: " + patient.social + "\n"
symptom = "Symptoms: " + patient.symptom + "\n"
pre = "Prescription: "+patien... | The code handles selection of a patient from a list, displays their information in a new window, and provides options to record, delete, or cancel the action. It retrieves the selected item, creates a popup window with formatted data, and adds buttons for further actions. If no selection is made, it shows a warning mes... | def selection(event):
select = event.widget.curselection()
cur = list(patient_list)
patient = cur[select[0]]
print(cur[select[0]])
if select:
msgbox = Toplevel(root)
msgbox.title("Patient's information")
msgbox.geometry('400x400')
msgbox.resizable(height=False, w... |
def format(patient):
return "Department: " + patient.department + "\nName: " + patient.name + "\nDate of birth: " + patient.birth + "\nSSN: " + patient.social + "\nSymptoms: " + patient.symptom
def prescribe(msgbox, patient):
pre_button = Button(msgbox, text = "Prescribe", command = lambda:prescribe_popup(msgbo... | The main task of the code is to display selected patient information in a new window when a user chooses a patient from a list. It retrieves the patient data, creates a non-resizable popup window with formatted details, disables editing, and triggers a prescription function. If no selection is made, it warns the user t... | def selection(event):
select = event.widget.curselection()
#way to index a dictionary (patient list)
curpatient = list(patient_obj.values())
#make sure user is selecting a patient in a list
if select:
msgbox = Toplevel(root)
msgbox.title("Patient's information")
msgbox.geome... |
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument("--stage", type=str, choices=["mine_actions", "simplify_actions", "refine", "baseline_mcq", "baseline_gqa", "pearl"])
parser.add_argument("--prompt-plan-file", type=str, default="")
parser.add_argument("--prompt-plan-invalid-file",... | The main task of the code is to execute different processing stages based on the input argument `args.stage`, including mining actions, simplifying actions, refining, running baseline models for MCQ/GQA evaluation, and executing the PEARL method, with specific splits and evaluation types for each stage. | def main():
args = parse_args()
if args.stage == "mine_actions":
mine_actions(args)
elif args.stage == "simplify_actions":
simplify_actions(args)
elif args.stage == "refine":
load_actions()
refine(args)
elif args.stage == "baseline_mcq":
baseline_mcq(args, ... |
def keywords_forward(client, message, keyword):
source = makeMessageDescription(message)
client.send_message(
keywords_chat_id, '#{} {}'.format(keyword, source))
message.forward(keywords_chat_id)
client.mark_chat_unread(keywords_chat_id)
def mentions_forward(client, message):
source = makeMe... | The main task of the code is to process incoming messages by checking for specific keywords, handling mentions, and forwarding messages from followed users. It uses regular expressions to detect keywords in text, triggers keyword-based forwarding if matches are found, checks for mentions to handle tagged messages, and ... | def notmyHandler(client, message):
# print(message)
# process keywords
if message.text and not str(message.chat.id) in excluded_chats:
# maybe search -> findall and mark all keywords?
keyword = re.search("|".join(keywords),
message.text, re.IGNORECASE)
if ... |
def log(msg):
print(f'[datadeps] {msg}')
def read_subreddits(path):
assert_exists(path)
df = pd.read_csv(path)
# Just get the subreddit column as a list of strings...
# The `[0]` is a dirty hack and should be replaced
return df[['subreddit']].values.reshape((1, -1)).tolist()[0]
def write(path, ... | The main task of the code is to generate and save subreddit data and a matrix, either by fetching new data or using existing files. It checks command-line flags to determine if the matrix should be refetched or reused, creates the output directory if needed, reads subreddit lists, and stores data in pickle files or CSV... | def main():
output_dir = f'{rel}/{OUTPUT_DIR}'
output_dir_exists = os.path.exists(output_dir)
refetch_matrix = '-fetchNewMatrix' in sys.argv
always_retry = refetch_matrix or '-retry' in sys.argv
if not always_retry and output_dir_exists:
log('Nothing to do.')
return
log('Gener... |
def get_value_locations(board):
""" It returns a list of all the valid locations on the board
:param board: The current board state
:return: The column number of the first empty space in the board.
"""
valid_locations = []
for col in range(7):
if is_valid_location(board, col):
... | This function implements the Minimax algorithm with Alpha-Beta pruning to determine the optimal move in a two-player game. It evaluates possible board states recursively, alternating between maximizing and minimizing players. For each valid move, it simulates the game state, scores positions, and prunes suboptimal bran... | def minmax(board, depth, alpha, beta, maxplayer):
""" A function that takes in a board, depth, alpha, beta, and maxplayer. It then creates a list of possible moves and then
chooses a random column from that list. It then loops through the list of possible moves and creates a copy of the
board.
:param bo... |
def preorder_print(self, start, traversal):
#Root -> Left -> Rigth
if start:
traversal += (str(start.value) + " - ")
traversal = self.preorder_print(start.left, traversal)
traversal = self.preorder_print(start.right, traversal)
return traversal
def inorder_pri... | The main task of the code is to perform a tree traversal based on the specified type (preorder, inorder, or postorder) by calling corresponding methods and printing the result. If an unsupported traversal type is provided, it prints an error message. | def print_tree(self, traversal_type):
if(traversal_type == "preorder"):
return print(self.preorder_print(self.root, ""))
elif (traversal_type == "inorder"):
return print(self.inorder_print(self.root, ""))
elif (traversal_type == "postorder"):
return print(self... |
def get_connection(self):
"""Returns SQLAlchemy engine used to connect to database
Parameters:
None
Returns:
con (sqlalchemy.engine.base.Engine) :: Connection to the database
"""
url = f"postgresql://{self.user}:{self.password}@db.worldpop.org:5432/maxar"
con = create_engine(url)
try:
con.conne... | The main task of the code is to execute a database query using provided geometries, extract building footprint data for each geometry, and compile the results into a single GeoDataFrame. The function retrieves geometries, iterates through them to extract data, concatenates individual GeoDataFrames, and returns a unifie... | def execute_query(self):
"""Returns gdf of data returned from query defined in instantiation
Parameters:
geoms (list) :: List of shapely geoms
Returns:
gdf (gpd.GeoDataFrame) :: Geodataframe of building footprints
"""
con = self.get_connection()
geoms = self.get_geoms()
gdf_all = []
for geom in ... |
def __clear_plot_axes(self, ts, gyro, ax0, ax1, ax2, window):
if ts.shape[0] < window:
ax0.clear()
ax0.plot(ts, gyro[:, 0], color="tab:blue", label=r"$\omega_x$")
ax0.legend(loc="upper right")
ax1.clear()
ax1.plot(ts, gyro[:, 1], color="tab:blue", labe... | This function stops data recording by disconnecting the start button, halting animations, and terminating the receiving thread. It processes gyroscope and accelerometer data to perform an extrinsic calibration plausibility check. If valid, it updates plots with sensor data, displays calibration results, and enables the... | def __on_click_bt1(self, event):
logger.info("Stop recording")
self.bt1.disconnect(self.cidbt1) # Disable "Start Recording"
if self.anim is not None:
self.anim.event_source.stop()
self.anim = None
try:
self.stop_event.set()
self.rcv_thread... |
def __estimate_misalignment(self, gyro):
def fun(args, gyro):
alpha, beta = args
rot_align = CamToWorld.rotMat(alpha, beta, 0) # tr.euler_matrix(alpha, beta, 0)[:3, :3]
gyro_aligned = (rot_align @ gyro.transpose()).transpose()
err = np.linalg.norm(gyro_aligned[:,... | The code estimates sensor misalignment by processing gyroscope data, applying rotation matrices to align the data, calculating RMSE for accuracy, updating VPU extrinsic calibration parameters, and visualizing results via plots. It checks alignment plausibility, enables a "Save to VPU" button if valid, and displays stat... | def __on_click_bt2(self, event):
logger.info("Estimate misalignment")
self.bt2.disconnect(self.cidbt2) # Disable "Estimate Misalignment"
gyro = np.array([[x, y, z] for x, y, z in zip(self.gyro_x, self.gyro_y, self.gyro_z)])
alpha, beta = self.__estimate_misalignment(gyro)
rot_al... |
def processing_regardless(self):
for idx, breakdown in enumerate(breakdowns_regardless):
FIND_KEYWORDS = breakdown['FOR THE WORD']
if idx == 0:
CORRESPONDING_KEYWORDS = breakdown['RUN SENTIMENT ANALYSIS']
OPPOSITE_WORDS = breakdown['OPPOSITE WORDS']
for find_keywords_index, fin... | This method processes data based on the label type by calling specific functions (processing_type_1-4) or a default function (processing_regardless). It adds "otherwise" keywords if none are found and adjusts keywords for the 'consistency and texture' label by checking text matches and removing specific keywords if con... | def processing(self):
# label_type = 0 => not run
if self.label_type == 0:
self.processing_regardless()
return
if self.label_type == 1:
self.processing_type_1()
elif self.label_type == 2:
self.processing_type_2()
elif self.label_type == 3:
self.processing_type_3()
... |
def get_options():
parser = argparse.ArgumentParser(description='Count motifs in a fasta file.',
prog='countMotifs')
parser.add_argument('--fasta', help='Input fasta file', required=True)
parser.add_argument('--motif', help='Motif to search for', required=... | The main task of the code is to search for a specified DNA motif within a genome sequence. It reads command-line arguments, loads a FASTA-formatted genome, converts the motif to uppercase for case-insensitive matching, and uses a search function to locate the motif in the sequence. The result is then printed. The code ... | def main():
args = get_options()
seq = readGenome(args.fasta)
motif = args.motif.upper()
print(searchForMotif(seq, motif)) |
def search_parks(term):
all_parks = Park.query.all()
parks_list = []
terms = get_search_terms(term)
for park in all_parks:
for search_term in terms:
if park.search(search_term):
parks_list.append(park)
break
parks_dict = create_parks_dict(parks_lis... | The main task of the code is to aggregate results from multiple search functions (`search_parks`, `search_states`, `search_campgrounds`, `search_visitor_centers`) into a single dictionary by updating it sequentially with each function's output for a given `term`, then returning the consolidated dictionary. | def search_instances(term):
instances_dict = search_parks(term)
instances_dict.update(search_states(term))
instances_dict.update(search_campgrounds(term))
instances_dict.update(search_visitor_centers(term))
return instances_dict |
def _findCommonStrings(self, s2:str):
"""
find the all common strings between s2 and T
Returns:
results: [[idxB, length, idxA's list]]
"""
# results;
index = 0
results = []
while index <= len(s2) - 1:
starts, length = self._select_... | This function identifies common strings between input `s2` and a reference set `T`, filters them using dynamic programming via `_select_dp`, and returns the processed results along with a metric. It first retrieves potential matches with `_findCommonStrings`, converts multiple matches to a single representation via `_m... | def _select_CommonStrings(self, s2:str):
"""
select the compatible common strings between s2 and T
"""
results = self._findCommonStrings(s2)
if results == []: return [], 0
return self._select_dp(self._multi_To_one(results)) |
def check_product_id_set_to_none(product_id):
if product_id is not None:
raise IdException(ID_NONE_WHEN_ADD)
def check_product_name(product_name):
if product_name is None or type(product_name) is not str:
raise NameException(NAME_NOT_STRING)
def check_quantity(product_quantity):
if product_q... | This code adds a product to a database after validating its attributes. It checks the product's ID, name, quantity, and ensures the name doesn't already exist. Then, it inserts the product's name and quantity into the 'Products' table via a database connection, commits the transaction, and closes the connection to safe... | def add_product(self, product: Product):
check_product_id_set_to_none(product.id)
check_product_name(product.name)
check_quantity(product.quantity)
self.check_name_already_exist(product.name)
conn = get_db_connection(test=self.test)
conn.execute("""Insert into Products (... |
def calulateWeights(W,alpha,y,pred):
newWeights=[]
for i in range(len(y)):
newWeights.append(W[i] * np.exp(-1 * alpha * y[i] * pred[i]))
return np.array(newWeights/sum(newWeights)).reshape([len(y),1])
def calulateDic(X):
retGt={}
for i in range(X.shape[1]):
retGt[i]=[]
for j in range(X.shape[0]):
tem... | The code implements the AdaBoost algorithm to iteratively train weak classifiers (decision stumps) on weighted data. It initializes equal weights for the first iteration, updates weights based on error rates, calculates boosting coefficients (alpha), and combines predictions with these coefficients to improve accuracy.... | def adaboost_train(X,Y,M):
X = np.array(X)
Y = np.array(Y)
W={}
alpha={}
pred={}
for i in range(M):
W.setdefault(i)
alpha.setdefault(i)
pred.setdefault(i)
for i in range(M):
#for the first iteration,initial W
if i == 0:
W[i]=np.ar... |
def emptyCells(self, board):
emptyC = []
for x in range(3):
for y in range(3):
for z in range(3):
if board[x][y][z] == 0:
emptyC.append([x, y, z])
return emptyC
def setMove(self, board, x, y, z, currentPlayer):
boar... | The code implements an AI move selection for a 3D Tic-Tac-Toe game. If the board is empty, it randomly picks a move. Otherwise, it uses the MiniMax algorithm with Alpha-Beta pruning to determine the optimal move, then updates the board and returns it. | def AI_MOVE(self, board, currentPlayer):
if len(self.emptyCells(board)) == 27:
x = choice([0, 1, 2])
y = choice([0, 1, 2])
z = choice([0, 1, 2])
self.setMove(board, x, y, z, currentPlayer)
return board
else:
result = self.MiniMaxAB... |
def emptyCells(self, board):
emptyC = []
for x in range(3):
for y in range(3):
for z in range(3):
if board[x][y][z] == 0:
emptyC.append([x, y, z])
return emptyC
def setMove(self, board, x, y, z, currentPlayer):
boar... | The function AI_MOVE2 selects a move for the AI in a 3D tic-tac-toe game. If the board is empty (27 cells), it randomly chooses a starting position. Otherwise, it uses the MiniMaxAB algorithm with alpha-beta pruning to determine the optimal move (depth 5) and updates the board accordingly. The function returns the modi... | def AI_MOVE2(self, board):
if len(self.emptyCells(board)) == 27:
x = choice([0, 1, 2])
y = choice([0, 1, 2])
z = choice([0, 1, 2])
self.setMove(board, x, y, z, -1)
return board
else:
result = self.MiniMaxAB(board, 5, -1, 1, -1)
... |
def emptyCells(brd):
# print(brd)
emptyC = []
for x, sqr in enumerate(brd):
for y, row in enumerate(sqr):
for z, col in enumerate(row):
if brd[x][y][z] == EMPTY:
emptyC.append([x, y, z])
return emptyC
def setMove(brd, x, y, z, player):
# print... | The main task of the code is to determine the AI's move in a 3D Tic-Tac-Toe game. If exactly two cells are empty, it randomly selects a move. Otherwise, it uses the MiniMaxAB algorithm with alpha-beta pruning to evaluate optimal moves, then applies the best move for the AI (XPLAYER) and updates the board. The function ... | def AIMove(brd, player):
# print('here')
# print('here in 1')
if len(emptyCells(brd)) == 2:
x = choice([0, 1, 2])
y = choice([0, 1, 2])
z = choice([0, 1, 2])
# print(brd, x, y, z, OPLAYER)
setMove(brd, x, y, z, XPLAYER)
printBoard(brd)
else:
# pri... |
def emptyCells(brd):
# print(brd)
emptyC = []
for x, sqr in enumerate(brd):
for y, row in enumerate(sqr):
for z, col in enumerate(row):
if brd[x][y][z] == EMPTY:
emptyC.append([x, y, z])
return emptyC
def setMove(brd, x, y, z, player):
# print... | The function AI2Move selects the next move for the AI player (OPLAYER) in a game. If only two empty cells remain, it randomly chooses a move. Otherwise, it uses the MiniMax algorithm with alpha-beta pruning to determine the optimal move, updates the board, and prints it. | def AI2Move(brd):
if len(emptyCells(brd)) == 2:
x = choice([0, 1, 2])
y = choice([0, 1, 2])
z = choice([0, 1, 2])
setMove(brd, x, y, z, OPLAYER)
printBoard(brd)
else:
# print(brd, len(emptyCells(brd)), -inf, inf, OPLAYER)
# ERROR IS HERE! IN THE THIS BELO... |
def boardFull(self, board):
if len(self.emptyCells(board)) == 0:
return True
return False
def gameWon(self, board):
return self.winningPlayer(board, +1) or self.winningPlayer(board, -1)
def AI_MOVE(self, board, currentPlayer):
if len(self.emptyCells(board)) == 27:
... | The code's main task is to execute a game loop alternating between player and AI turns, updating the game state, checking for win/loss conditions, and returning the final board state and winner. It initializes the board, switches turns, uses AI_MOVE for computer decisions, and exits on completion or interruption. | def play_game(self):
"""Primary game loop.
Until the game is complete we will alternate between computer and
player turns while printing the current game state.
"""
try:
board = self.np_board
print(board)
if(self.player_1_turn):
... |
def conditionToBranch(X, Y, remainingX, features, maxDepth):
if maxDepth <= features-len(remainingX) or len(remainingX) <= 0:
return False
ig = igOfAllProvided(X, Y)
if max(ig) == 0:
return False
return ig
def binaryBranching(X, Y, remainingX):
ig = igOfAllProvided(X, Y)
branchIn... | This function recursively constructs a decision tree by selecting the feature with maximum information gain to split the dataset, creating branches for each subset. If splitting is possible, it recursively builds left and right subtrees; otherwise, it returns the majority class label from the target variable Y. | def createBranch(X, Y, remainingX, features, maxDepth):
condition = conditionToBranch(
X, Y, remainingX, features, maxDepth)
if condition:
indexOfMaxIg = np.argmax(condition)
featureToBranchOn = remainingX[indexOfMaxIg]
branchingStep = binaryBranching(X, Y, remainingX)
re... |
def boardFull(brd):
if len(emptyCells(brd)) == 0:
return True
return False
def gameWon(brd):
# print('winning game',winningPlayer(brd, XPLAYER) or winningPlayer(brd, OPLAYER))
return winningPlayer(brd, XPLAYER) or winningPlayer(brd, OPLAYER)
def makeMove(brd, player):
print('Loading fin... | This code simulates a turn-based AI vs AI game. It alternates between two players (represented by XPLAYER and its inverse) making moves on a board until the game ends (either a win or draw). The loop continues until the board is full or a player wins, then prints the result. The core task is to automate gameplay betwee... | def AIvsAI():
currentPlayer = XPLAYER
# count = 0
# board = np.zeros((3, 3, 3), dtype=int)
# print(board)
# print(board)
# for x in range(2):
# clearBoard(board)
while not (boardFull(board) or gameWon(board)):
makeMove(board, currentPlayer)
currentPla... |
def conditionToBranchRealValues(X, Y, maxDepth, depth):
if maxDepth <= depth:
return False
positionOfX, branchOfX, maxIG = dataForMaxIG(X, Y)
if maxIG == 0:
return False
else:
return ([positionOfX, branchOfX])
def getBranchingSteps(X, Y, positionOfX, branchOfX):
xForXGreater ... | This function recursively partitions real-valued data into branches based on feature thresholds. It checks splitting conditions, creates left/right sub-branches if valid, and returns the maximum frequency class in Y when splitting isn't possible. The process continues until max_depth is reached, building a tree structu... | def createBranchForRealValues(X, Y, max_depth, depth):
condition = conditionToBranchRealValues(X, Y, max_depth, depth)
if condition:
positionOfX = condition[0]
branchOfX = condition[1]
branching_step = getBranchingSteps(
X, Y, positionOfX, branchOfX)
return {"positi... |
def get_date_time():
"""
get the full date along with the hour of the search, just for
completeness. Allows us to solve for of the original post
date.
"""
now = datetime.datetime.now()
month = str(now.month) if now.month > 9 else '0' + str(now.month)
day = str(now.day) if now.da... | This function navigates through job search result pages using Selenium, scraping job postings by iterating through each page. It handles pagination, clicks on job links, extracts data with delays, and stops when results are exhausted. The code processes 25 jobs per page, checks for page exhaustion, and logs progress. | def navigate_search_results(self):
"""
scrape postings for all pages in search results
"""
driver = self.driver
search_results_exhausted = False
results_page = self.results_page
delay = 60
date = get_date_time()
# css elements to view job pages
... |
def load_arrays(converted=True):
instances = os.listdir("nparrays")
result = {}
for i in instances:
print(f"Loading <{i}>")
instance_path = os.path.join("nparrays", i)
inputs = load_inputs(os.path.join(instance_path, "inputs.bin"))
target = numpy.load(os.path.join(instance_pa... | The main task of the code is to iteratively run a game simulation over multiple rounds, compute average scores for each board configuration, update a history of averaged scores using a moving average, and periodically save the results. The infinite loop processes each round, aggregates scores, and maintains a running a... | def main():
history = load_arrays()
while 1:
board2scores = {}
for i in range(ROUND):
save_game(board2scores)
results = {}
for k, v in board2scores.items():
avg_score = sum(v) / len(v)
history[k] = (history.get(k, avg_score) + avg_score) / 2
... |
def get_score(self, flipped):
p_score = 0
for p in self.bpieces:
if self.bpieces_alive[p.index]:
p_score += p.score
for p in self.wpieces:
if self.wpieces_alive[p.index]:
p_score -= p.score
white_moves = self.get_all_moves(True)
... | The code implements the minimax algorithm with alpha-beta pruning to determine the optimal move in a board game. It evaluates possible moves recursively, considering the current depth, player color, and game state conditions (e.g., check status). The function explores all valid moves, simulates each move, and prunes br... | def minimax(self, depth, color, alpha, beta, flipped, checked, max_depth):
random_choice = True
opponent_pieces_alive = self.bpieces_alive if color else self.wpieces_alive
if depth >= max_depth:
return self.get_score(flipped), None
best = []
moves = self.get_real_move... |
def get_ai_move(self, model, color):
moves = self.get_real_moves(color)
output = model.predict(self.get_moves_input(moves), verbose=0)
output = [x[0] if color else -x[0] for x in output]
if DEBUG:
print(output)
output = [(b, a) for a, b in enumerate(output)]
m... | This function simulates a two-player game between AI models `model1` and `model2`, alternating turns. Each model generates a move using `get_ai_move`, executes it, and checks for checkmate. If checkmate occurs, it returns a result with the winner's color, turn count, and piece scores. If the game exceeds 200 turns, it ... | def run_game_ava(self, model1, model2):
color = True
turn = 0
while 1:
turn += 1
if color:
move = self.get_ai_move(model1, color)
piece, square = move
self.move(piece, *square)
else:
move = self.... |
def get_test_pairs(pair_str):
existing_pairs = instrument.Instrument.get_instruments_dict().keys()
pairs = pair_str.split(",")
test_list = []
for p1 in pairs:
for p2 in pairs:
p = f"{p1}_{p2}"
if p in existing_pairs:
test_list.append(p)
return test_l... | The code evaluates currency pairs using historical data from H4 and M5 timeframes. It generates trades from H4 data, scores each pair by comparing trades with M5 data, accumulates total scores, and prints individual and overall results. | def run():
currencies = "GBP,EUR,USD,CAD,JPY,NZD,CHF"
test_pairs = get_test_pairs(currencies)
grand_total = 0
for pairname in test_pairs:
i_pair = instrument.Instrument.get_instruments_dict()[pairname]
h4_data = pd.read_pickle(utils.get_his_data_filename(pairname, "H4"))
m5_dat... |
def add_ns1_children(invoice):
"""
Add all children with ns1 prefix to invoice.
:param invoice: The invoice xml in elementtree.
:return: the elementtree.
"""
add_customization_id(invoice)
add_profile_id(invoice)
change_invoice_type_code(invoice)
change_document_currency_code(invoice)... | The function processes an invoice XML elementtree by adding 'ns1' namespace prefixes to elements, converting specific nodes like supplier/customer parties, delivery, payment means, tax totals, and invoice lines using helper functions, and returns the modified elementtree. | def create_invoice_elementtree(invoice, kbo_number):
"""
Create an elementtree from an invoice xml.
:param invoice: The invoice xml in elementtree.
:return: The elementtree.
"""
# Add all children with ns1 prefix to invoice.
invoice = add_ns1_children(invoice)
invoice = convert_supplier_... |
def initialize_subsys(args):
epanet_toolkit.open(ph, args.input_filename, args.report_filename, args.binary_filename)
epanet_toolkit.settimeparam(ph, epanet_toolkit.HYDSTEP, args.hstep)
epanet_toolkit.setstatusreport(ph, epanet_toolkit.NORMAL_REPORT)
check_units()
def add_leak():
global pipe_length ... | The main task of the code is to run an EPANET hydraulic simulation with configurable parameters (input file, time step, pipe index), model leak scenarios by iteratively adjusting leak sizes on a specified pipe, and record simulation results (pressure, flow) to CSV files. It initializes the EPANET system, applies leak m... | def main():
print("INFO: in main")
# parse all arguments
parser = argparse.ArgumentParser(description='Run an EPANET simulation.')
parser.add_argument('input_filename', nargs='?', default='net1.inp',
help='An EPANET input file describing the system.')
parser.add_argument('rep... |
def compute_flat_qkv(self, x, dk, dv, Nh):
qkv = self.qkv_conv(x)
N, _, H, W = qkv.size()
q, k, v = torch.split(qkv, [dk, dk, dv], dim=1)
q = self.split_heads_2d(q, Nh)
k = self.split_heads_2d(k, Nh)
v = self.split_heads_2d(v, Nh)
dkh = dk // Nh
q *= dkh ... | The code implements a hybrid convolutional and self-attention mechanism. It processes input through a convolutional layer, computes multi-head self-attention with optional relative positioning, applies softmax to derive attention weights, and combines attention outputs with convolutional features. The final output conc... | def forward(self, x):
# Input x
# (batch_size, channels, height, width)
# batch, _, height, width = x.size()
# conv_out
# (batch_size, out_channels, height, width)
conv_out = self.conv_out(x)
batch, _, height, width = conv_out.size()
# flat_q, flat_k, fl... |
def pretrain(self):
tr = 0
self.model_global.train()
if self.args.dataset == "mnist":
self.optimizer = optim.SGD(self.model_global.parameters(), lr=0.1, momentum=0.5, weight_decay=0.00005)
else:
self.optimizer = optim.SGD(self.model_global.parameters(), lr=0.0005,... | The code implements federated learning training with client selection, parallel updates, and aggregation. It pretrains if specified, selects clients per round, tracks adversarial overlap, performs parallel client updates using threading, aggregates models via weighted averaging, evaluates performance, and saves model s... | def train(self):
if self.args.pretrainingR>0:
self.pretrain() # pretrain over the watermarking dataset.
initial = time.time()
for rounds in range(self.T): #total number of rounds
if self.C == 0: # If C = 0 we set number of clients participating in current round to 1.
... |
def d_query(key):
"""
Returns a dictionary object from a query
"""
return json.loads(t_query(key))
def parse_general_forecast(g):
forecast = emojify(g['forecast'])
t = g['temperature']
rh = g['relative_humidity']
wind = g['wind']
w_speed = wind['speed']
txt = f"24hr Forecast: {f... | The function `forecast_24hr` retrieves 24-hour weather data via `d_query('24hr')`, extracts general forecast details and periodic intervals from the response, parses them into text using helper functions, and concatenates the results into a formatted string for return. | def forecast_24hr():
d = d_query('24hr')
status = d['api_info']['status']
items = d['items'][0]
general = items['general']
periods = items['periods']
txt = parse_general_forecast(general)
txt += "\n" + parse_periods(periods, by_period=False)
return txt |
def now_cast():
d = d_query('2hr')
# print(d['items'][0])
if len(d['items'][0]) == 0:
print(f'2 hour query returns: {d}')
return 'Now: no forecast'
area_metadata, forecasts = parse_2hr(d)
x = [ float(LATITUDE),
float(LONGITUDE) ]
place, dist = get_nearest_loca... | The main task of the code is to process command-line arguments to fetch and display weather-related data. Depending on the `args.key` value, it retrieves either current weather (`2hr`), 24-hour forecast (`24hr`), PM2.5 forecast (`pm25`), or PSI forecast (`psi`). For unrecognized keys, it queries data via `d_query`, for... | def main(args):
if args.key == '2hr':
txt = now_cast()
elif args.key == '24hr':
txt = forecast_24hr()
elif args.key == 'pm25':
txt = forecast_pm25()
elif args.key == 'psi':
txt = forecast_psi()
else:
d = d_query(args.key)
d_pprint(d)
print(txt) |
def process_raw_data_files(path='./data'):
# Process raw csv files to right format
# Load csv files
load_files = glob.glob(path + "/load_*.csv")
# Gen csv files
gen_files = glob.glob(path + "/gen_*.csv")
# Process the csvs into one csv
load_df, load_m = combine_csvs(load_files, True)
gen... | The main task of the code is to process and clean raw data from input files, preprocess the cleaned data, and save the final processed dataset to an output file. The function combines data handling, cleaning, preprocessing, and storage steps into a streamlined workflow for data preparation. | def main(input_file, output_file):
# Combine created csv files and clean them
df_clean = process_raw_data_files(path=input_file)
# Preprocess the data
df_processed = preprocess_data(df_clean)
save_data(df_processed, output_file) |
def _try_fetch(self):
if self._samples_since_last_fetch < self._fetch_every:
return
self._samples_since_last_fetch = 0
try:
worker_id = torch.utils.data.get_worker_info().id
except:
worker_id = 0
eps_fns = sorted(self._replay_dir.glob('*.npz'),... | This function samples a single transition from an episode, computes n-step cumulative reward and discount, and returns (obs, action, reward, discount, next_obs). It increments a counter for samples since the last fetch, handles errors during data fetching, and calculates multi-step rewards by iterating over self._nstep... | def _sample(self):
try:
self._try_fetch()
except:
traceback.print_exc()
self._samples_since_last_fetch += 1
episode = self._sample_episode()
# add +1 for the first dummy transition
idx = np.random.randint(0, episode_len(episode) - self._nstep + 1) ... |
def CanonicalCollection(self):
C = []
s0 = self.closure( { ('S^','','.',self.grammar.starting) } ) # enriched grammar S^
C.append(s0) # add initial state to the collection
finished = False
while not finished:
finished = True
for state in C:
... | The main task of the code is to construct an LR(0) parsing table by analyzing each state in the canonical collection of LR(0) items. It determines actions (shift, reduce, accept, error) for each state, identifies reductions, checks for conflicts, and populates shift transitions for terminals/non-terminals. The table en... | def buildLR0Table(self):
canonicalCollection = self.CanonicalCollection()
self.printCanonicalCollection(canonicalCollection)
idx = 0
for state in canonicalCollection:
entry = TableEntry()
entry.stateIndex = idx
action = ""
for item in sta... |
def tokenizeLine(self, line):
# line = re.sub(' +', ' ', line) # remove multiple spaces
comment_pos = line.find("//")
if comment_pos != -1:
line = line[:comment_pos]
initial_tokens = line.split()
tokens = []
temp_str = None
for t in initial_tokens:
... | The code performs lexical analysis on a given program file by tokenizing each line, classifying tokens into keywords, identifiers, or constants using finite automata, and storing them in a Symbol Table (ST) and Parsing Intermediate File (PIF). It skips comments and empty lines, reports lexical errors for invalid tokens... | def runScanner(self, programFile):
# run lexical analyzer
with open(programFile, "r") as f:
lineNo = 0
correct = True
for line in f:
lineNo += 1
line = line.strip()
if line.startswith("//") or len(line) == 0:
... |
def __get_representative_subgraph_nodes(self):
edge_length = int(self.__node_number**(1/2.))
i = int(edge_length / 2)
j = int(round(edge_length/2.+0.1))
return [jj+ii*edge_length for ii in range(i) for jj in range(j)]
def __find_hamiltonian_paths(self, start, visited):
# Stoppin... | This method computes all Hamiltonian paths in a graph by first iterating over representative sub-nodes (reducing computation time by 4x) and multiplying the found paths by 4. It then separately computes paths starting from the graph's central node, enhancing efficiency and coverage of potential paths in the graph struc... | def find_all_hamiltonian_paths(self):
self.__found_paths = 0
# Compute Hamiltonian Paths starting from only representative sub-nodes of the graph
# (it reduce by 4 the computation time)
for i in self.__get_representative_subgraph_nodes():
visited = [False] * self.__node_numb... |
def extract_txs(height):
rawblock = get_block_by_height(height, 'json', api_key)
txids = []
for tx in rawblock['tx']:
txid = tx['hash']
txids.append(txid)
return txids
def genmerkleproof(height, txhash):
txs = extract_txs(height)
#print(txs)
srcmerkleroot = extract_merkleroot... | The function generates a Merkle proof for a transaction at a specified block height by combining the transaction hash, Merkle proof data, and the block's Merkle root into a hexadecimal string. It converts this string to bytes using big-endian encoding and returns the result, enabling compact verification of the transac... | def genmerkleproof_relay(height, txhash):
txs = extract_txs(height)
data = []
data.append(txhash)
if len(txs) > 1:
merkleproofdata = genmerkleproof(height, txhash)
srcmerkleroot = extract_merkleroot(height)
data.extend(merkleproofdata)
data.append(srcmerkleroot)
datas... |
def insert_node(self, node):
"""
Insert node with specific type.
Arguments:
- node: a dict of node attribute
{
(mandatory) name: str,
(mandatory) type: str, (api | handle | module)
(optional)...
... | The main task of the code is to process a Cuckoo report's behavior data, extract relevant processes and API calls, construct a graph with nodes (processes, APIs, modules, handles) and edges representing interactions, and save the structured data and visualizations. It filters APIs by category, skips duplicates/errors, ... | def encode_report(self, behavior, report_name, label, log_dir, report_cut_out_dir, nx_png_out_dir, dot_out_dir, render_svg) -> bool:
"""
Process the data extracted from the report and save to data.json.
Arguments:
- behavior: extracted from cuckoo .json report, 'behavior' tag
... |
def reset(self) -> None:
"""
Reset graph attribute and everything, to construct other graph.
Call this before constructing any graph
"""
self.apis = [] #? store all apis that are considered
#? keep track of current working report / current graph (use graph_name (= {labe... | The main task of the code is to convert Cuckoo malware analysis reports into GraphViz graph representations. It resets internal state, reads the report's behavioral data, and if valid, encodes it into a graph structure while saving outputs like PNGs, DOT files, and SVGs to specified directories. The function returns th... | def r2g(self, report_file_path, label, log_dir=None, report_cut_out_dir=None, nx_png_out_dir=None, dot_out_dir=None, render_svg=False):
"""
Main function for converting from Cuckoo reports to GraphViz graph.
- Reset
- Read report
- Encode report
"""
self.reset()
... |
def filter_samplewise_chimeras(files, minh, mindiff, mindiv, min_chimeric_samples):
all_seqs = []
asvs = defaultdict(lambda: 0)
nonchims = []
for uchimeout in tqdm(files, unit=" files", desc="Reading chimera results"):
uchime_res = read_uchime(uchimeout)
# If empty input, skip to next fi... | The code processes chimera detection results from UCHIME, handling either multiple files (samplewise mode) or a single file (batchwise mode). It filters potential chimeras using parameters like minh, mindiff, and mindiv, then applies additional filters based on shared sample counts and fractions. Finally, it outputs no... | def main(args):
if len(args.uchimeout) > 1:
# Run samplewise chimera detection
sys.stderr.write(f"Found {len(args.uchimeout)} chimera result files\n")
sys.stderr.write(
f"Running in samplewise mode using: minh={args.minh}, mindiff={args.mindiff}, mindiv={args.mindiv}, min_chimeri... |
def read_asv_clusters(files):
"""
Read cluster files
"""
res = pd.DataFrame()
for f in files:
_ = pd.read_csv(f, sep="\t", index_col=0, dtype=str)
# Only take first ASV/cluster combination. There shouldn't be more
# than one but just in case
_ = _.groupby(level=0).fir... | The code processes taxonomic assignments of ASVs, filters unassigned entries, merges with clustering results, and calculates precision, recall, homogeneity, and completeness metrics for taxonomic clustering evaluation. It also optionally outputs order-level statistics. | def main(args):
# Read taxonomies
asv_taxa = pd.read_csv(args.taxfile, sep="\t", index_col=0)
sys.stderr.write(f"#{asv_taxa.shape[0]} ASV taxonomies loaded\n")
# Remove ASVs without assignments for args.rank
sys.stderr.write(f"#Removing ASVs without assignments for {args.rank}\n")
asv_taxa = asv... |
def executeCmd(msg, text, txt, msg_id, receiver, sender, to):
#print(to)
if txt == ".hi":
reply(msg,"Hi too !")
elif txt == ".restart":
reply(msg,"restart will begin")
restartProgram()
elif txt == ".speed":
start = time.time()
reply(msg,"Testing ...")
elapse ... | The code processes operations in a messaging app, handling friend requests, message content (text, images, videos), media downloads, and profile updates (picture, cover, video). It executes commands, updates user profiles, manages settings, and replies to users with error handling for exceptions like network issues or ... | def executeOp(op):
try:
#print ('++ Operation : ( %i ) %s' % (op.type, OpType._VALUES_TO_NAMES[op.type].replace('_', ' ')))
if op.type == 5:
client.findAndAddContactsByMid(op.param1)
client.sendMentionV2(op.param1,"Thanks for add me as your friend @!", [op.param1])
if... |
def blands_rule_entering(self):
# Go through variables looking for the smallest non-basic
for var in self.variables:
if not var.is_in_basis() and self.dictionary[0][var.get_col()] > 0:
self.entering = var
break
def basic_leaving(self):
is_unbounded = F... | This method selects pivot variables in a linear programming algorithm. It applies Bland's Rule if degeneracy is detected (3+ consecutive pivots), otherwise uses "Largest Increase" rule when specified, or defaults to largest coefficient rule. The entering and leaving variables are determined based on the chosen pivot st... | def set_pivot_variables(self):
# Use Bland's Rule if degenerate for several pivots
if self.degeneracy_counter >= 3:
self.blands_rule_entering()
self.basic_leaving()
# The largest increase pivot rule can be run using the same method
elif self.pivot_rule == "Large... |
def handle_optimal(self):
self.status = "optimal"
self.optimal = self.dictionary[0][0]
for var in self.variables:
# if the variable is a point, set the constant if it is in the basis
# Otherwise, set zero
if var.is_point():
if var.is_i... | The main task of the code is to execute the simplex algorithm iteratively: check for optimality, handle unboundedness, track degeneracy, and perform pivots until an optimal solution is found or unboundedness is detected. It manages the simplex method's core steps, including selecting entering/leaving variables, detecti... | def run_simplex(self):
while(True):
# Check for Optimal
if Dictionary.is_optimal(self.dictionary):
self.handle_optimal()
return
# Set the entering and leaving variable depending on criteria
self.set_pivot_variables()
... |
def manipulation(self):
df_signal = self.create_df(self.input_file)
df_isosbestic = self.create_df(self.isos_name)
signal = self.create_signal_vec(df_signal)
signal_isosbestic = self.create_signal_vec(df_isosbestic)
time_vector = self.create_time_vec(df_signal)
len_df = m... | This code initializes a class to prepare for parsing an input file, setting up parameters like region, frame rate, and baseline window, while processing the file into time and signal vectors. It computes Z-scores, normalized signals, and control data, then generates a filename for saving results. The main task is to re... | def __init__(self, path_file, input_file: str, region, isos_name, result_dir, tags_array_len, tags_per_second=15,
poly_degree=3,
baseline_window_in_minute=2) -> None:
"""Gets ready to parse the input file.
Args:
input_file (typing.TextIO): input file.
... |
def update_one(y):
img_comp['text'] = y
def update_two(x):
img_player['text'] = x
def winner(p, c):
if p == c:
update_msg("This round is drawn")
elif p == "rock":
if c == "paper":
update_msg("Computer wins this round!!!")
update_Csc... | The code updates two choices (one from a selection and one from input 'a') to uppercase strings using update_one and update_two, then determines the winner between them using the winner function. | def update_choice(a):
choice_comp = choice(select)
if choice_comp == "rock":
update_one("ROCK")
elif choice_comp == "scissor":
update_one("SCISSOR")
elif choice_comp == "paper":
update_one("PAPER")
elif choice_comp == "lizard":
upda... |
def begin(content, arg=None):
"""
Generate LaTeX code for the "\begin" tag, and an optional additional
argument.
Parameters
----------
content : str
Content to be put inside the "\begin" command braces.
arg : str or None, optional
Additional argument to be added after the "\... | The main task of the code is to generate LaTeX code by encapsulating given content within specified environments, handling parameters like environment name, additional arguments, centering, captions, labels, and newline formatting. It constructs a LaTeX string by combining prefix (\begin with options), content, and suf... | def encaps(env, content, arg=None, center=False, caption=None,
capt_pos="bottom", ref=None, addl_newline=False):
r"""
Encapsulate the given content within "\begin" and "\end" commands of the
specified environment.
Parameters
----------
env : str
Name of the LaTeX environment ... |
def _complain_if_str_passed_as_tokens(tokens):
if isinstance(tokens, str):
raise ValueError("passed a string. you should pass a list of tokens instead.")
def check_missing_vocab(self, tokens):
_complain_if_str_passed_as_tokens(tokens)
missed_words = [token for token in tokens if (token not i... | This function checks if a given list of tokens can be parsed successfully by verifying input type, checking for missing vocabulary, and ensuring a valid parse exists. It returns True if parsing is possible, False otherwise. | def can_parse(self, tokens):
_complain_if_str_passed_as_tokens(tokens)
try:
self.check_missing_vocab(tokens)
return self.get_most_probable_parse(tokens) is not None
except ValueError:
return False |
def create_rem():
st.title("Create New Reminder")
reminder = st.text_input("What you want to remined")
date = str(st.date_input("Select a date"))
time= str(st.time_input("Select a time slot"))
new_reminder = {"reminder": reminder,
"date": date,
"time": time
... | This code creates a Streamlit dashboard with a sidebar menu offering options to create/view reminders, chat, or logout. Based on user selection, it navigates to corresponding functions (create_rem(), view_rem(), chatting()) or logs out by resetting the session state. If no option is selected, it displays a default mess... | def dashboard():
with st.sidebar:
selected = option_menu(None, ["Create Reminder", "View Reminders", "Chat", "Logout"], icons = ["📝", "📋", "💬", "🔓"] )
if selected == "Create Reminder":
create_rem()
elif selected == "View Reminders":
view_rem()
elif selected == "Chat":
chatting(... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.