dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def _get_worksheet_by_columns(self):
"""Creates a dict of values in a given column of the active Excel spreadsheet"""
#https://stackoverflow.com/questions/51478413/select-a-column-by-its-name-openpyxl
col_names = {}
Current = 0
for COL in self.workbook.active.iter_cols(1, self.w... | The main task of the code is to parse an input Excel workbook by utilizing helper functions to extract requested fields, filtering criteria, sorting rules, and grouping rules. It initializes data processing by identifying relevant columns, defining field-specific parameters, and establishing organizational logic for st... | def parse_workbook(self):
"""Primary function to parse input Excel workbook. Makes use of helper functions _get_requested_fields, _get_field_filters, _get_field_comment to parse input excel workbook."""
self._get_worksheet_by_columns()
self._get_requested_fields()
self._get_sorting_rule... |
def get_ap_ids(self):
"""Loops over proposal_list to return a unique list of ap_ids."""
ap_ids = []
for proposal in self.proposal_list:
if proposal['ap_id'] not in ap_ids:
ap_ids.append(proposal['ap_id'])
self.ap_ids = ap_ids
return ap_ids
def run_rep... | This function retrieves proposal field data from an API by iterating over AP IDs, applying filters, and aggregating results. It submits requests for each AP ID, stores report IDs, fetches results, and combines them into a unified dataset stored in `self.all_proposal_data` for all proposals. | def get_all_proposal_field_reports(self, api_filters):
"""Wrapper function for handling API call to '/api/v1/report/proposal_field'. Loops over self.ap_ids to gather proposal fields for all proposals. Stores API responses in all_proposal_data. """
report_ids = []
all_proposals_w_data = []
... |
def print_help() -> None:
"""Show help screen."""
print("Usage:", os.path.basename(__file__), "[options] [PHP-EXT]...")
print(" ", os.path.basename(__file__), "-h, --help")
print()
print("This script will generate the Ansible group_vars file: .ansible/group_vars/all/mods.yml")
print("based ... | The main task of the code is to process command-line arguments, determine selected modules, resolve their dependencies, and generate outputs including module paths, dependency trees, and build order. It handles flags like -i for ignoring dependencies, validates inputs, constructs a module dependency graph, and writes t... | def main(argv: List[str]) -> None:
"""Main entrypoint."""
ignore_dependencies = False
selected_modules = []
if len(argv):
for arg in argv:
if arg in ("-h", "--help"):
print_help()
sys.exit(0)
for arg in argv:
if arg.startswith("-") ... |
def print_help() -> None:
"""Show help screen."""
print("Usage:", os.path.basename(__file__), "[options] [PHP-TOOL]...")
print(" ", os.path.basename(__file__), "-h, --help")
print()
print("This script will generate the Ansible group_vars file: .ansible/group_vars/all/work.yml")
print("based... | The main task of the code is to process command-line arguments to determine selected tools and their dependencies, resolve the build order based on dependencies, and output paths, tool directories, dependency trees, and build order. It also writes the resolved build order to a group_vars file. | def main(argv: List[str]) -> None:
"""Main entrypoint."""
ignore_dependencies = False
selected_tools = []
if len(argv):
for arg in argv:
if arg in ("-h", "--help"):
print_help()
sys.exit(0)
for arg in argv:
if arg.startswith("-") an... |
def get_tools() -> List[Dict[str, Any]]:
"""Returns a list of PHP tools."""
tools = []
with os.scandir(PHP_TOOL_PATH) as it:
for item in it:
if not item.name.startswith(".") and item.is_dir():
data = get_tool_options(item.name)
tools.append(
... | The main task of the code is to retrieve PHP tools in dependency order, generate their documentation in markdown format, and update a specified documentation file by replacing a predefined section with the newly generated markdown content. This involves printing tool paths, formatting tool data, and performing regex-ba... | def main() -> None:
"""Main entrypoint."""
# Get tools in order of dependencies
tools = get_tools()
print("#", "-" * 78)
print("# Paths")
print("#", "-" * 78)
print("Repository: ", REPOSITORY_PATH)
print("PHP Tools: ", PHP_TOOL_PATH)
print()
print_terminal(tools)
print()
... |
def SetupNewChain():
subprocess.getstatusoutput("rm -rf ~/.aether")
print("deleted previos state")
print("rebuilding binaries.....")
response = subprocess.getstatusoutput(f"make install --directory={AETHER_DIR_PATH}")
print(response[1])
print("binary re-build done ✔️")
subprocess.getstatusou... | The code validates directory paths, initializes a blockchain setup, starts a chain in a separate thread, initializes an indicator, creates state, and prompts the user to stop the chain via Ctrl+C. Key tasks include error checking, thread management, and system initialization for blockchain operations. | def main():
if not os.path.exists(HOME_DIR):
exit(f"Error - root dir not found {HOME_DIR}")
if not os.path.exists(AETHER_DIR_PATH):
exit(f"Error - invalid aether repo path {AETHER_DIR_PATH}")
SetupNewChain()
thr = threading.Thread(target=StartChain, args=(), kwargs={})
thr.start()
... |
def loadArgs(self):
ap = argparse.ArgumentParser()
ap.add_argument("-v", "--video", help="path to the (optional) video file")
ap.add_argument("-b", "--buffer", type=int, default=2, help="max buffer size")
self.args = vars(ap.parse_args())
def loadCameraImage(self):
videoSource = cv2.VideoCapture(self.args["vi... | The code initializes a robot control system by setting up image processing utilities, a robot controller, and loading parameters. It prepares a video source, initializes trajectory tracking, and启动 the main loop for real-time processing and control. | def __init__(self):
#try:
self.utils = ImageProcessingUtils()
self.utils.init()
self.robotController = RobotController()
self.trajetoriaEv3 = []
self.loadArgs()
videoSource = self.loadCameraImage()
self.loadParams()
self.running = False
self.mainLoop(videoSource) |
def update_chord(self):
"""
The chord of the pole is the line connecting its two ends.
The plug is always at the origin: (0, 0)
This function computes the unit vector on the chord facing the cap.
"""
chord = np.array([self.posx[-1], self.posy[-1]])
self.chord_len... | This function determines whether to terminate the stepping process by checking if the chord length deviation falls below a tolerance threshold after a minimum time. It updates geometric and physical properties, then returns True to stop if conditions are met, otherwise returns False to continue. | def step(self, time):
self.update_chord()
if self.L - self.chord_length < self.stopping_tol and time > 20:
return True # time to stop stepping
self.update_unit_tangent()
self.update_unit_normal()
self.update_curvature()
self.update_point_mass()
self.up... |
def help():
print(" Command: python imagetogcode.py image_filename [output_filename]\n")
def penUp():
global pen_up
gcode = ""
if (not pen_up):
gcode = pen_up_gcode
pen_up = True
return gcode
def drawPixel(pixel):
#print(pixel)
#value = numpy.mean(pixel)
value = pixel[0]
#if (value <= 0.25)... | The code converts an image into G-Code for a plotter/3D printer. It reads an input image, processes pixel data, generates G-Code commands to trace the image (alternating row directions), and writes the output to a file or console. Key steps include argument validation, image loading, pixel traversal, G-Code constructio... | def main():
argc = len(sys.argv)
print("Image to G-Code v" + version)
if (argc < 2):
help()
sys.exit(2)
image_filename = sys.argv[1]
if (not os.path.exists(image_filename)):
print("File not found: " + image_filename)
sys.exit(1)
print("Reading image file: " + image_filename)
img = matpl... |
def accept_cookies(self):
cookie_accept_xpath = '//*[@id="portlet_mscicookiebar_WAR_mscicookiebar"]/div/div[2]/div/div/div[1]/div/button[1]'
self.clickButton(cookie_accept_xpath)
time.sleep(1)
def search_for_company(self):
company_search_field_xpath = '//*[@id="_esgratingsprofile_keyword... | The code automates scraping ESG ratings data from a website by initializing a browser session, accepting cookies, searching for and selecting a company, extracting the ESG ratings' HTML content, closing the browser, and returning the extracted data. | def initializeScrapeProcess(self):
self.accept_cookies()
self.search_for_company()
self.select_company()
data = self.get_esg_ratings().get_attribute('innerHTML')
self.driver.quit()
return data |
def read_proj_file(filename):
with open(filename) as f:
return f.read()
def process_linux(s):
libs = [
"libkaldi-native-fbank-core.so",
"libncnn.so",
"libsherpa-ncnn-c-api.so",
"libsherpa-ncnn-core.so",
"libgomp-a34b3233.so.1.0.0",
]
prefix = f"{SHERPA_NCN... | The main task of the code is to generate a `.csproj` file for the `sherpa-ncnn` project by processing platform-specific templates (Linux, macOS, Windows) and substituting variables using Jinja2 templating. It reads input files, applies configuration settings, and writes the final project file with resolved paths and de... | def main():
s = read_proj_file("./sherpa-ncnn.csproj.runtime.in")
process_linux(s)
process_macos(s)
process_windows(s)
s = read_proj_file("./sherpa-ncnn.csproj.in")
d = get_dict()
d["packages_dir"] = str(SHERPA_NCNN_DIR / "scripts/dotnet/packages")
environment = jinja2.Environment()
... |
def newTreeShare(id, treeId):
print("(root will be %s)", id)
# opens DB connection
dbInfo = connect()
cursor = dbInfo[1]
cnx = dbInfo[0]
# tree traversal algorithm created by Alima
# first get the children of a root, in children we see each of childs's id and name
root_node, children_r... | The main task of the code is to share a family tree starting from a specific individual. It retrieves descendants of the starting individual, creates a new shared tree with the provided details, and updates the database to link the new tree ID to all relevant individuals. The function returns a success status code "200... | def shareWithUser(startingID,treeid, name, collaborator):
print("info sent: individual to share: %s treeid: %s name: %s collaborator: %s", str(startingID), str(treeid), str(name), str(collaborator))
print("People that would be shared")
# uses the root individual to be shared to find its descendants in a
... |
def make_qid_to_answer_type(dataset, answer_type: str):
qid_to_ans_type = {}
for article in dataset:
if answer_type not in article:
raise ValueError(f'{answer_type} is not in dataset')
qid_to_ans_type[article['id']] = not article[answer_type]
return qid_to_ans_type
def get_raw_sc... | The function evaluates model predictions or human scores on a dataset, categorizing questions by answer types (HasAns/NoAns). It computes metrics (exact match, F1, precision, recall) for overall performance and subsets of questions with/without answers. If human evaluation, it uses provided scores; otherwise, it requir... | def evaluate(eval_dataset, preds=None, data_type: str = 'eval', humans: bool = False):
if preds is None and not humans:
raise ValueError('You must give predictions if this is not human evaluation')
answer_types = [['is_impossible', 'HasAns', 'NoAns']]
qid_to_ans_type = dict()
has_ans_type_qids =... |
def combine_predictions(predictions):
"""
Create a combine dataset
:param predictions:
:return:
"""
new_predictions = collections.defaultdict(list)
final_new_predictions = collections.defaultdict(dict)
for q_j_id, pred in predictions.items():
q_id = ''.join(q_j_id.split('_')[:-1... | The main task of the code is to evaluate model predictions against a dataset by combining the input predictions and dataset, then generating statistical evaluation results using the `evaluate` function with a specified data type (e.g., 'eval'). The function returns a dictionary containing these statistics for analysis. | def model_results_evaluation(dataset, predictions, data_type: str = 'eval'):
new_predictions = combine_predictions(predictions)
new_test_data = combine_dataset(dataset)
result_prediction_statistics_dict = evaluate(new_test_data, new_predictions, data_type=data_type)
return result_prediction_statistics_... |
def formatNumber(InputNumber):
return re.sub("(?:\+)?(?:[^[0-9]*)", "", InputNumber)
def localScan(InputNumber):
global number
global localNumber
global internationalNumber
global numberCountryCode
global numberCountry
print(code_info + 'Running local scan...')
FormattedPhoneNumber = "... | The code scans a phone number by validating it, then performs checks using numverify, OVH, and osint services. It prints status messages, handles invalid numbers by exiting, and uses global variables to store number details like country code and validity. | def scanNumber(InputNumber):
print(code_title + "[!] ---- Fetching informations for {} ---- [!]".format(formatNumber(InputNumber)))
localScan(InputNumber)
global number
global localNumber
global internationalNumber
global numberCountryCode
global numberCountry
if not number:
p... |
def get_data(csvfile):
"""
analyzes the data from a csv file and returning it as a pd.DataFrame
:param csvfile: string of a path to a csv file
:return: pd.DataFrame as the file's date
"""
df = pd.read_csv(csvfile, encoding="utf-16LE", sep="\t")
df = df.replace('\"', '', regex=True)
df = ... | The function processes a CSV file to aggregate login times into a dictionary, updates a DataFrame by adding a new column with these aggregated times, and returns the updated DataFrame along with the maximum login time found. It reads CSV data, builds a time dictionary, calculates overall login times per user, checks fo... | def add_csv(file, time_dict, new_overall):
"""
adding every csv as a new column and analyzing it
:param file: string of a csv file
:param time_dict: dictionary
:param new_overall: new pd.DataFrame for the overall login time
:return: the new pd.DataFrame of the overall login time
after adding... |
def init(dirpath):
"""
initiates all parameters that are needed for the script: the dictionary of the participants, list of csv files
and the initiative pd.DataFrame
:return: pd.DataFrame, list of csv files and the dictionary of the participants
"""
time_dict = {}
csv_lst = get_files(dirpath... | This code aggregates data from multiple CSV files into a unified DataFrame. It processes each file to update the DataFrame, accumulates maximum values, sorts columns, calculates average time, adds names, and exports the final result to 'attendance.csv' | def start(my_path):
new_df, csv_files, init_dict = init(my_path)
sum_maxes = 0
for csv in csv_files:
new_df, max_row = add_csv(csv, init_dict, new_df)
sum_maxes += max_row
new_df.sort_index(axis=1, inplace=True)
new_df = add_avg_time(new_df, sum_maxes)
new_df = add_names(new_df, ... |
def initialDriver():
#path=ChromeDriverManager().install()
driver=webdriver.Chrome(r"C:\Users\amalp\.wdm\drivers\chromedriver\win32\95.0.4638.54\chromedriver.exe")
#driver.switch_to_alert().accept()
return driver
def getProjects():
dirs=getDirs()
for dir in dirs:
if(not o... | The main task of the code is to index new project directories by capturing screenshots and converting them to HTML files, ensuring they are added to a list of indexed directories. It iterates through all project directories, skips already indexed ones, handles exceptions during processing, and updates the indexed list ... | def indexFiles():
driver=initialDriver()
dirs=getProjects()
indexedDirs=getListedDirs()
for dir in dirs:
if dir not in indexedDirs:
try:
takeScreenshot(dir,driver)
toHtml(dir)
... |
def calc_dist_2_points(c1x, c1y, c2x, c2y):
"""
### Parameters
- c1x: float, in AU
- c1y: float, in AU
- c2x: float, in AU
- c2y: float, in AU
### Returns
- distance: float, in AU
"""
return (np.sqrt((c1x - c2x)**2 + (c1y - c2y)**2))
def calc_x_intersections(r1, c1x, c1y, r2, c2... | The code calculates and plots two possible transfer orbits between two planets using their positions and a specified semimajor axis. It computes distances from the Sun, intersection points, orbital parameters (semimajor/minor axes, angles), and midpoints. Using these, it generates elliptical trajectories centered on th... | def plot_transfer(planet1, planet2, semimajor_axis):
sunX = 0
sunY = 0
planet1_position = planet1.rad
planet2_position = planet2.rad
planet1_to_sun = calc_dist_2_points(planet1.x, planet1.y, sunX, sunY)
planet2_to_sun = calc_dist_2_points(planet2.x, planet2.y, sunX, sunY)
r1 = (2*semimajor... |
def f(n,e,s,p):
'''Transition function for dN/dt. n and e are microscopic variables.
s are state variables, call S, N, or E
p are parameters, call b0, d0, m0, w0, w10, Ec, or mu '''
return (fb0(s,p)+fd0(s,p)*n)*n/e**(1/3)+fm0(s,p)*n
def h(n,e,s,p):
'''Transition function for dE/dt. n and e are micro... | This code computes the unnormalized structure function for DynaMETE by exponentiating a sum of terms involving microscopic variables, lambdas, and state-dependent functions f, h, q, which are parameterized by given constants. | def R(n,e,l,s,p):
'''Unnormalized struture function for DynaMETE.
n,e are microscopic variables.
l are lambdas
s are state variables, call S, N, or E
p are parameters, call b0, d0, m0, w0, w10, Ec, or mu '''
return np.exp(-l[0]*n-l[1]*n*e-l[2]*f(n,e,s,p)-l[3]*h(n,e,s,p)-l[4]*q(n,e,s,p)) |
def nRsum(e,l,s,p):
'''Unnormalized struture function for DynaMETE multiplied by n, then summed over n.
e is a microscopic variable.
l are lambdas
s are state variables, call S, N, or E
p are parameters, call b0, d0, m0, w0, w10, Ec, or mu '''
# Define exponent for lambdas 1-4, with n=1 since w... | The function `get_means` computes normalized integrals of specific exponential powers of state variables (n, n², δn) multiplied by probability densities, essential for constraints and covariances. It calculates means over a range of exponents (e.g., -1/3, 2/3) using `quad_vec` integration, with configurable precision v... | def get_means(l,s,p,ds,alln=True):
'''
This function gets all of the needed means over R for the constraints and the covariances. This includes
n e^{0,-1/2,2/3,1} R
n^2 e^{0,-1/3,-2/3,1/3,2/3,1,4/3,5/3,2} R
delta_{n,1} e^{-1/3,-2/3,1/3,2/3} R
where
l are lambdas
s are state variables, c... |
def check_collisions(self, bubble, bubbles):
distance = self.outline_distance(bubble, bubbles)
return len(distance[distance < 0])
def center_of_mass(self):
return np.average(
self.bubbles[:, :2], axis=0, weights=self.bubbles[:, 3]
)
def collides_with(self, bubble, bubbles):
... | The code iteratively moves bubbles toward their center of mass over multiple iterations, adjusting positions to avoid collisions. For each bubble, it calculates a direction vector toward the center of mass, moves the bubble, and checks for collisions. If collisions occur, it attempts orthogonal directional adjustments.... | def collapse(self, n_iterations=50):
"""
Move bubbles to the center of mass.
Parameters
----------
n_iterations : int, default: 50
Number of moves to perform.
"""
for _i in range(n_iterations):
moves = 0
for i in range(len(self... |
def get_hull_shape(shape):
points = [ [point[0], 400-point[1]] for path in shape for point in path ]
points = np.array(points)
hull = ConvexHull(points)
envelop_points = hull.points[hull.vertices]
return envelop_points
def get_length(points):
length = 0
for ip in range(len(points)):
... | The code calculates the roundness of a shape by comparing its area to that of a circle with the same perimeter. It computes the convex hull's length and area, derives the equivalent circle's radius, and returns the ratio of the shape's area to the circle's area. | def get_roundness(shape):
from math import pi
hull_points = get_hull_shape(shape)
length = get_length(hull_points)
area = get_area(hull_points)
R = length/(2*pi)
circle_area = pi*R**2
roundness = area/circle_area
return roundness |
def approve_all(message=None):
global reddit
posts = db.get_all()
if posts != None:
for entry in posts:
submission = reddit.submission(entry.id)
print(submission.title)
if not check_post_deleted(submission):
submission.mod.approve()
... | This code runs a Reddit moderation bot using PRAW, authenticating with credentials, initializing a database, and processing subreddit submissions. It checks for new posts, skips deleted ones, handles automoderator interactions, processes messages, and cleans outdated database entries while monitoring the subreddit and ... | def main():
global reddit
global has_bot_started
print(f'{CLIENT_ID}')
try:
reddit = praw.Reddit(client_id=CLIENT_ID,
client_secret=CLIENT_SECRET,
user_agent=USER_AGENT,
username=USERNAME,
... |
def show_mem_list(self):
print("****************************************")
print("This is membership list of VM %s: " % extract_vm_num())
for _, val in self.memlist.dict.items():
print("%s [%s] [%s]" % (val["id"], State(val["state"]), val["timestamp"]))
print("***************... | The code defines a controller method that continuously accepts user commands to control an object's behavior. It processes commands like "list_mem" (to show member list), "join" (to join a group), "leave" (to exit), and "list_self" (to display the object's ID), with error handling for invalid inputs. The loop runs inde... | def controller(self):
while 1:
command = input("\nInput the command:\n\n")
if command == "list_mem":
self.show_mem_list()
elif command == "join":
self.join()
elif command == "leave":
self.leave()
elif com... |
def MovR (x,t):
global keys #8,9,6,3,2,1,4,7
global rotate
match keys[(x+(rotate*2))%len(keys)] :
case 8:
up(t)
case 9:
urr(t)
case 6:
right(t)
case 3:
drr(t)
case 2:
down(t)
case 1:
dll(... | The function `move(x)` normalizes `x` using `x % 4`, then maps the result to specific movement commands via a `match` statement. Depending on the value of `x`, it calls `MovR(n)` with varying parameters (1–8) or executes `per(.1)`/`oh(.1)` for cases 5 and 0. The task involves routing input values to predefined actions,... | def move (x):
x=x%4
match x :
case 1:
MovR(1)
case 9:
MovR(2)
case 6:
MovR(3)
case 3:
MovR(4)
case 2:
MovR(5)
case 1:
MovR(6)
case 4:
MovR(7)
case 7:
M... |
def MovR (x,t):
global keys #8,9,6,3,2,1,4,7
global rotate
match keys[(x+(rotate*2))%len(keys)] :
case 8:
up(t)
case 9:
urr(t)
case 6:
right(t)
case 3:
drr(t)
case 2:
down(t)
case 1:
dll(... | This function routes input 'x' to specific functions based on its value, calling MovR with varying parameters for cases 1-9 and invoking per() or oh() when x is 5 or 0, respectively. The primary task is to act as a dispatcher that selects and executes different movement or processing functions depending on the integer ... | def MovT(x,t):
match x :
case 8:
MovR(1,t)
case 9:
MovR(2,t)
case 6:
MovR(3,t)
case 3:
MovR(4,t)
case 2:
MovR(5,t)
case 1:
MovR(6,t)
case 4:
MovR(7,t)
case 7:
... |
def setBoard(self, row, col, val):
c = coor()
c.row = row
c.col = col
if self.isOnBoard(c) and val == self.BLACK or val == self.WHITE or \
val == self.EMPTY or val == self.LEGAL:
self.board[row][col] = val
def marker(self):
# unmark all the moves
... | This code initializes a board game UI (likely Othello/Reversi) by setting up a fixed-size window, defining game constants, initializing an 8x8 board with central starting pieces, mapping UI buttons/labels to grid positions, and connecting button clicks to handle player moves. It prepares the interface for turn-based ga... | def __init__(self) -> None:
super(Table, self).__init__()
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
self.setFixedSize(self.width(), self.height())
# passing the constants to the class
self.SIZE = 8
self.EMPTY = '-'
self.BLACK = 'B'
self.WHIT... |
def flipTiles(self, move):
isValid = False
curr = coor()
toFlip = coor()
for dir in self.DIRS:
isFlipped = False
i = 1
while(True):
# multiplying by "i" to move along the directions
curr.row = move.row + dir[0] * i
... | The code processes a player's move in a board game (e.g., Reversi). If the move is legal, it flips tiles, switches turns, updates buttons, and checks for remaining valid moves. If no moves remain, it ends the game with a delay. | def process(self, c):
# if move is legal, flip the tiles
if self.board[c.row][c.col] == self.LEGAL:
self.flipTiles(c)
# switch turn
self.switchTurn()
# update buttons before game is over
self.updateBtns()
# if the user does not have... |
def delayer(self, delay):
loop = QtCore.QEventLoop()
timer = QtCore.QTimer()
timer.setInterval(delay)
timer.setSingleShot(True)
timer.timeout.connect(loop.quit)
timer.start()
loop.exec()
def process(self, c):
# if move is legal, flip the tiles
if s... | The code's main task is to enable the CPU to play a move by generating random moves, processing them, and recursively calling itself if the turn remains the CPU's. It uses delay mechanisms to control timing and ensures continuous CPU play when the human player has no move to make. | def cpuPlays(self):
self.delayGuard = False
self.delayer(1000)
self.delayGuard = True
self.process(self.randomMoves())
# after playing if human does not have move to play, cpu will play again
if self.turn != self.humanSide:
self.cpuPlays() |
def get_db_instance(self, instance_name):
try:
client = self.get_client()
response = client.describe_db_clusters(
DBClusterIdentifier=instance_name
)
return response['DBClusters'][0]
except:
pass
def get_client(self):
cl... | This code restores a database cluster from a snapshot, creates a new DB instance under the restored cluster, and configures parameters like instance class, security groups, and parameter groups. It checks if the target cluster already exists, skips redundant steps if so, and waits for availability. The function returns... | def restore_db_snapshot(self, snapshot_identifier,
new_cluster_name, new_instance_name,
new_cluster_paremeter_group_name, new_instance_paremeter_group_name,
instance_class, parent_instance):
res = self.get_db_instance... |
def selenium_driver(account):
driver_path = Path('chromedriver.exe').as_posix()
cookies_file_path = 'cookies/' + account[0] + '.txt'
cookies_path = Path(cookies_file_path).as_posix()
options = Options()
# options.add_argument(f'user-agent={user_agent}')
options.add_argument("--disable-notificat... | The main task of the code is to automate Facebook interactions using Selenium. It logs into a Facebook account (if not already logged in), scrolls down the page, likes a post, adds a friend, likes a page, and then closes the browser. The script handles login authentication and executes predefined social media engagemen... | def main(account):
driver = selenium_driver(account)
if is_fb_logged_in(driver):
print("Already logged in")
else:
print("Not logged in. Login")
fb_login(driver, account)
# activities to perform
scroll_down(driver, 10)
like_post(driver)
add_friend(driver)
like_page... |
def git_checkout(cwd, commit: pygit2.Commit):
"""Checkout given commit."""
command = ['git', 'checkout', str(commit.id)]
return subprocess.run(command, cwd=cwd).returncode == 0
def print_clang_diagnostics(tu):
"""Prints diagnostics of translation unit. Helpful to spot missing include files."""
if tu... | The main task of the code is to recover a code location by finding a similar AST subtree in a new code version, using git commits and Clang's AST parsing. It parses the old code's AST, identifies a target node, then searches the new code's AST for a matching subtree, returning its location if found. This heuristic aids... | def recover_from_ast(diff, location, start_commit, end_commit):
"""
Heuristic to recover code location by finding a similar AST subtree in the new code version.
"""
logger.info("Try node rediscovery")
STATS[STATS_H3_USES] += 1
# find representative old subtree
git_checkout('.', start_commit)... |
def diff_contains_file(diff, file):
"""Returns true if the file is changed in the diff."""
for patch in diff:
if patch.delta.old_file.path == file:
return True
return False
def get_code_location(commit: pygit2.Commit, location: flib.feature.Location):
"""Returns code mapped by locati... | The function `estimate_new_location` tracks code element locations across Git commits using diffs. It skips irrelevant files, retrieves old code, and applies heuristics (line tracking, added-line recovery, AST-based recovery) to determine the new location. It compares recovery methods, returns the first valid result, a... | def estimate_new_location(location: flib.feature.Location, diff: pygit2.Diff, start_commit: pygit2.Commit,
end_commit: pygit2.Commit):
"""
Bundles heuristics and calls them in order.
For evaluation purposes, both recovery heuristics are compared against each other.
"""
log... |
def save_settings(settings):
# Make output directory
try:
os.mkdir(settings['save_as'])
except OSError:
print(
'Warning: job folder "%s" already created, overwriting.' %
settings['save_as'])
settingsfilename = os.path.join(settings['save_as'], 'settings.json')
... | The function runs a tracker using specified settings to process video data, adjust parameters, define regions of interest, track particle locations, form trajectories, validate results, and output tracking data including bend information. It handles stdout redirection, video analysis, region masking, and result storage... | def run_tracker(settings, stdout_queue=None):
"""
Run the tracker with the given settings.
stdout_queue can be used to redirect stdout.
"""
if stdout_queue:
sys.stdout = StdoutRedirector(stdout_queue, settings["stdout prefix"])
sys.stderr = StdoutRedirector(stdout_queue, settings["s... |
def get_app_font(self):
font = QFont()
font.setPointSize(12)
font.setFixedPitch(True)
return font
def make_charts(self, data):
sns.set_theme(style="whitegrid")
fig = plt.figure(figsize=(5, 8))
grid = fig.add_gridspec(12, 1)
# ax
ax1 = fig.add_sub... | The code initializes a GUI interface by setting the application font, generating a sample dataset, creating a central chart widget, adding a statistics dock widget on the right, and incorporating a bottom toolbar for chart navigation. | def initUI(self):
self.setFont(self.get_app_font())
# sample dataset
data = np.random.normal(loc=20, scale=5, size=100)
# Charts (center)
charts = self.make_charts(data)
self.setCentralWidget(charts)
# Statistics (right dock)
stats = self.make_stats(dat... |
def is_capture(self, move):
return not self.is_empty(move.square_t) and \
self.get_piece(move.square_f).color != self.get_piece(move.square_t).color
def is_empty(self, sq):
return isinstance(self.get_piece(sq), Empty)
def blocked(self, move):
square_f = move.square_f
dir =... | This method checks if a chess move is legal by validating the piece's type, move validity, turn alignment, capture rules, blocking conditions, and ensuring the game isn't already won. | def is_legal(self, move, piece):
can_jump = isinstance(piece, Knight)
return move.square_f != move.square_t and \
(piece.is_valid_move(move) if not isinstance(piece, Pawn)
else (piece.is_valid_move(move) and self.is_capture(move) and piece.pawn_diag(move) or
... |
def get_piece(self, sq):
return self.pieces[sq.get_index()]
def is_legal(self, move, piece):
can_jump = isinstance(piece, Knight)
return move.square_f != move.square_t and \
(piece.is_valid_move(move) if not isinstance(piece, Pawn)
else (piece.is_valid_move... | This function executes a chess move by validating its legality, updating the board state, handling captures, tracking the move history, marking king/rook movement status, checking for game over conditions, and switching turns. | def make_move(self, move):
piece = self.get_piece(move.square_f)
if not self.is_legal(move, piece):
print( 'Last State: {}, move; {}, piece {}'.format(self, move, piece))
print('last move made: {}'.format(self.moves[-1]))
assert self.is_legal(move, piece)
if (sel... |
def is_empty(self, sq):
return isinstance(self.get_piece(sq), Empty)
def get_piece(self, sq):
return self.pieces[sq.get_index()]
def is_legal(self, move, piece):
can_jump = isinstance(piece, Knight)
return move.square_f != move.square_t and \
(piece.is_valid_move(move) ... | The function generates all pseudo-legal moves for the current player by iterating through each board square, checking if the piece belongs to the current turn, and validating moves to target squares. It collects legal moves using the `is_legal` method and returns them as a list. | def generate_pseudo_legalmoves(self):
##possible = [[[None for _ in range(2) for _ in range (total_squares)] for _ in range(total_squares)]]
possible = []
for c in range(board_size):
for r in range(board_size):
f = get_square(c, r)
if (self.is_empty(f)... |
def is_hackmode():
# grab part of screen for check TECH area
image = np.array(screen.grab(id_screen_rect))
return get_id(image) == 'TECH'
def update_path():
# render clean frame
save_data([])
time.sleep(0.2)
# wait for successful recognition
path = None
while path is None:
c... | The main task of the code is to monitor and respond to changes in "hack mode" by continuously checking the mode state, logging transitions, and executing corresponding actions (e.g., updating paths in hack mode or saving data in non-hack mode). It relies on environment variables, timeouts, and external functions to man... | def main():
logging.info('Running cyberhack...')
if not cmd_file_name:
raise Exception('Env variable CMDS_FILENAME is not set')
logging.info(f'cmd file:{cmd_file_name}')
last_mode = None
while True:
is_hack_mode_enabled = is_hackmode()
if is_hack_mode_enabled == last_mode:... |
def get_value_string(node_type, key, value, deapth=0):
indent_count = STYLISH_CONST['indent_repeat'] * deapth
indent_count = STYLISH_CONST['indent_initial'] + indent_count
indent = STYLISH_CONST['indent_char'] * indent_count
if not isinstance(value, dict):
value = cast_type(value)
return f"{... | The function recursively generates a formatted string representation of a nested data structure, handling different node types (parent, changed, etc.). It indents each level based on depth, processes key-value pairs, and constructs a structured output with appropriate formatting for 'parent', 'changed' (splitting into ... | def go_deeper(node, deapth=0):
indent_count = STYLISH_CONST['indent_repeat'] * deapth
indent = STYLISH_CONST['indent_char'] * indent_count
result = "{\n"
for key, val in sorted(node.items()):
node_type = val.get('type')
if node_type == 'parent':
va... |
def in_bounds(self, coord, edge):
return self.__margin < coord and coord < edge - self.__margin
def find_cell(self, x, y):
for row in self.cells:
for cell in row:
if cell.point_in_cell(x, y):
return cell
return None
def set_current_cell(self, cel... | This method handles a cell click event by checking if the click coordinates are within the board's bounds. If valid, it sets focus on the board, identifies the clicked cell, and selects it if it's not a default cell. | def cell_clicked(self, event):
x = event.x
y = event.y
if not ( self.in_bounds(x, self.__board_width) and self.in_bounds(y, self.__board_height) ):
return
self.board.focus_set()
cell = self.find_cell(x, y)
if cell and not cell.default:
#print(ce... |
def set_info_text(self, msg, erase=False):
f_msg = '{0:%H:%M:%S}: {1}\n'.format(datetime.datetime.now(), msg)
if erase:
self.info_area['widget'].delete(0)
self.info_area['widget'].configure(state = 'normal')
self.info_area['widget'].insert(tk.INSERT,f_msg)
self.info_a... | The code validates a Sudoku board by checking rows, columns, and 3x3 squares for conflicts using a helper function. It updates UI feedback, processes invalid areas, marks erroneous cells, and handles exceptions by displaying errors before re-raising them. | def validate_board(self):
try:
self.set_info_text("Validating board...")
raw_board = self.get_raw_board()
result = sudoku_helper.validate_board(raw_board)
self.reset_invalid_flag()
self.handle_invalid_rows(result['rows'])
self.handle_invali... |
def move_cell_up(self):
if self.current_cell.row == 0:
return
new_row = self.current_cell.row-1
for i, r in enumerate(reversed(self.cells)):
if i >= (8 - new_row):
cell = next((c for c in r if c.col == self.current_cell.col and not c.default), None)
... | This function handles arrow key press events to move the current cell in the specified direction (UP, DOWN, LEFT, RIGHT). It first checks if a current cell exists; if not, it exits. Depending on the direction parameter, it calls corresponding movement methods to adjust the cell's position. | def arrow_key_pressed(self, event, dir):
if not self.current_cell:
return
if dir == 'UP':
self.move_cell_up()
elif dir == 'DOWN':
self.move_cell_down()
elif dir == 'LEFT':
self.move_cell_left()
elif dir == 'RIGHT':
self... |
def reset_cell_value(self):
self.current_cell.value = 0
self.erase_cell_value(self.current_cell)
def set_cell_value(self, value):
self.current_cell.value = value
self.draw_cell_value(self.current_cell)
def validate_board(self):
try:
self.set_info_text("Validating boar... | This code handles user input for a board cell. It resets the cell's value if the input is not 'X', increments the value for non-'X' inputs, and validates the board if the input is 'X' and the board is invalid. The function ensures proper cell updates and board validation based on input type. | def on_input_click(self, event, num):
if not self.current_cell:
return
self.reset_cell_value()
if num != 'X':
val = int(num) + 1
self.set_cell_value(val)
if self.board_invalid and num == 'X':
self.validate... |
def erase_cell_value(self, cell):
tag = '({0},{1})::value'.format(cell.row, cell.col)
self.board.delete(tag)
def set_info_text(self, msg, erase=False):
f_msg = '{0:%H:%M:%S}: {1}\n'.format(datetime.datetime.now(), msg)
if erase:
self.info_area['widget'].delete(0)
self... | This function resets all user-modified cells in a grid to their default value (0), erases their visual representation, updates the status text to "Resetting board," and validates the board. It iterates through each cell, checking if it was manually altered (non-default), then applies the reset. This ensures the board r... | def reset_all_user_values(self):
for row in self.cells:
for cell in row:
if not cell.default:
cell.value = 0
self.erase_cell_value(cell)
self.set_info_text("Resetting board.")
self.validate_board() |
def get_raw_board(self):
board = []
for row in self.cells:
board_cols = []
for cell in row:
board_cols.append(cell.value)
board.append(board_cols)
return board
def set_info_text(self, msg, erase=False):
f_msg = '{0:%H:%M:%S}: {1}\n'.fo... | The main task of the code is to solve a Sudoku board using an external helper, update the UI with the solved values (highlighting changes in green) if successful, display error messages if solving fails, and handle exceptions by showing relevant error information. | def solve_board(self):
try:
raw_board = self.get_raw_board()
result = sudoku_helper.solve_board(raw_board)
self.set_info_text("Solving board...")
if not result['board']:
self.set_info_text("Could not solve board!")
self.validate_boa... |
def draw_cell_frames(self):
length = self.__cell_width * 3
for i in range(4):
hl = self.get_frame_line_coordinates(i, length, True)
line_width = 2
# Adjust outter lines to get square edges
if i in [0, 3]:
hl.x0 -= 1
hl.x1 +... | The code initializes a game board by drawing cell frames and cells, then binds mouse and keyboard events to handle user interactions. It links left-clicks, key presses, and arrow keys to methods for processing moves and input, enabling gameplay mechanics like tile movement and collision detection in a puzzle game like ... | def init_board(self):
self.draw_cell_frames()
self.draw_cells(init=True)
self.board.bind('<Button-1>', self.cell_clicked)
self.board.bind('<Key>', self.key_pressed)
self.board.bind('<Left>', lambda event,
arg='LEFT': self.arrow_key_pressed(event, arg))
... |
def ConvertToDict (productions):
"""
Function to convert list of productions to dictionary
Args:
productions (array): list of productions
Returns:
dictionary (dict): dictionary of productions
"""
dictionary = {}
for production in productions :
if(production[0] in di... | The code eliminates epsilon (ε) productions from a context-free grammar. It processes each variable, generates new productions by removing ε from existing rules, filters out residual ε-productions, and removes any productions containing nullable variables. The result is a new set of production rules free from ε, ensuri... | def EliminateEpsilon(productions, variables):
"""
Eliminate Epsilon Production
Args:
productions (array): list of productions
variables (array): list of variables
Returns:
newProds (array) : new production
"""
prodsDict = ConvertToDict(productions)
newProds = list.c... |
def ReadGrammar(relativePath):
"""
Function to read grammar from CFG.txt
Args:
relativePath (string): relative path to txt
Returns:
terminals (array): list of terminals
variables (array): list of variables
productions (array): list of productions
"""
try:
... | This function converts a Context-Free Grammar (CFG) into Chomsky Normal Form (CNF) by reading the grammar, validating it, eliminating epsilon and unit productions, removing useless variables, and transforming remaining productions into CNF format. The result is returned as a dictionary of CNF rules. | def convertCFGtoCNF():
"""
Main Function converting CFG to CNF
Returns:
productionsFix (dictionary) : dictionary of CNF
"""
terminals, variables, productions = ReadGrammar("./CFG/CFG.txt")
for nonTerminals in variables :
if nonTerminals in variablesJar:
variablesJar.... |
def get_taf(airport_icao: str, before_timestamp: int) -> Taf | None:
before_datetime = datetime_from_timestamp(before_timestamp)
result = Taf.objects(
Q(airport_icao=airport_icao)
& Q(created_at__lte=before_datetime)
& Q(start_time__lte=before_datetime)
& Q(end_time__gte=before_... | The function retrieves wind direction and speed data from a TAF (Terminal Aerodrome Forecast) report for a specified airport and timestamp. It first fetches the TAF, then extracts wind direction and speed if available, returning them as a WindData object. If either value is missing or the TAF is unavailable, it returns... | def get_taf_wind_data(airport_icao: str, before_timestamp: int) -> WindData | None:
taf = get_taf(airport_icao, before_timestamp)
if not taf:
return
wind_direction = _get_taf_wind_direction(taf, before_timestamp)
if wind_direction is not None:
wind_speed = _get_taf_wind_speed(taf, be... |
def update_types(poke_name):
r = requests.get(
'https://pokeapi.co/api/v2/pokemon/' + poke_name, verify=False)
types = r.json()['types']
poke_id = get_id(poke_name)
for i in types:
try:
with connection.cursor() as cursor:
query = f"INSERT INTO poke_type VALUES... | The function `create_poke` fetches Pokémon data from the PokeAPI, extracts height and weight, updates type information, adds the Pokémon to a database, and updates ownership records linking it to a trainer. It integrates external data retrieval, database operations, and ownership tracking for Pokémon management. | def create_poke(poke_id, poke_name, old_poke, trainer):
r = requests.get(f"https://pokeapi.co/api/v2/pokemon/{poke_name}/", verify=False)
height = r.json()["height"]
weight = r.json()["weight"]
update_types(poke_name)
add_poke({"id": poke_id, "name": poke_name, "height": height, "weight": weight})
... |
def find_owners(pokemon_name):
try:
with connection.cursor() as cursor:
query = f"SELECT name FROM owned_by WHERE owned_by.id IN(" \
f"SELECT pokemon.id FROM pokemon WHERE name = '{pokemon_name}')"
cursor.execute(query)
rows = cursor.fetchall()
... | The code advances a Pokémon's evolutionary chain for a specified trainer by checking ownership, fetching evolution data from the PokeAPI, and creating/updating the evolved Pokémon's entry in a database if the trainer is valid and the evolution exists. | def evolve_pokemon(poke_name, poke_tranier):
owners = find_owners(poke_name)
print('owe',owners)
if poke_tranier not in owners :
return "No such an owner to that pokemon"
poke_url = "https://pokeapi.co/api/v2/pokemon/" + poke_name
r = requests.get(poke_url, verify=False)
poke_species_url... |
def generate_default_board():
# key: rtl -> rook-top-left
top = [['rt','kt','bt','Qt','Kt','bt','kt','rt'],
['pt','pt','pt','pt','pt','pt','pt','pt']]
mid = [[empty_square]*8 for _ in range(4)]
bottom = [['pb','pb','pb','pb','pb','pb','pb','pb'],
['rb','kb','bb','Qb','Kb','bb','... | The code initializes a chess board with standard dimensions and mappings, setting up piece names, movement rules, and constants for each chess piece. It defines how each piece (pawn, rook, knight, etc.) moves using specific functions and pre-defined movement patterns, preparing the board for gameplay logic. | def __init__(self):
width, height = 8, 8
self.board = generate_default_board()
self.algebraic_mapped_to_position, self.position_mapped_to_algebraic = map_algebraic_to_position(width, height)
self.width, self.height = width, height
self.piece_names = {
'p': 'p... |
def GetNode2Exclude(routing, q, qe, v, C, k, gamma, r, banlist):
DictRouFreight = dict(zip(routing,[qe[i,j,k]*r[i,j]*gamma[k] for (i,j) in routing]))
MaxCost = 0
ex = None
q_ex = None
v_ex = None
for t in routing:
if t[1] in C and t[1] not in banlist:
if DictRouFreight[t] > M... | The main task of the code is to improve an optimal routing solution by swapping nodes between vehicles (kd and ks) to reduce costs. It iteratively identifies feasible client nodes to exclude from one vehicle's route, assigns them to a satellite vehicle, recalculates freight demands, and reroutes both vehicles using a f... | def ImproveOptimalSwapKdKs(RCVd, data, cdv, cdw, DictRoutes, DictRoutesList, DictNodes, DEMS_, Q0_, q_final, qe_final, v_final, w_final, Phi_, Theta_, depots):
# Unpacking data
XY = data['XY']
F = data['F']
D = data['D']
S = data['S']
C = data['C']
P = data['P']
V_i = data['V_i']
Ph... |
def Steps1To3(data):
# Unpacking data
XY = data['XY']
F = data['F']
D = data['D']
S = data['S']
C = data['C']
P = data['P']
P_f = data['P_f']
K = data['K']
V_i = data['V_i']
DEM = data['DEM']
Lambd = data['Lambd']
Omega = data['Omega']
Phi = data['Phi']
Theta ... | This function solves a multi-echelon vehicle routing problem by optimizing routes between facilities, depots, satellites, and customers. It calculates total costs (satellite, vehicle, arc, freight) and iteratively improves the solution via vehicle swaps between depots/satellites. The goal is to minimize the overall obj... | def ExecuteMultiEchelon(data, filename = None, preplots = False):
# Unpacking data
XY = data['XY']
F = data['F']
D = data['D']
S = data['S']
C = data['C']
P = data['P']
P_f = data['P_f']
K = data['K']
V_i = data['V_i']
DEM = data['DEM']
Lambd = data['Lambd']
Omega = d... |
def ReadData(datadir, file):
# Nodes
df = pd.read_excel(os.path.join(datadir, file), sheet_name = 'Nodes')
XY = df[['X','Y']].values
F = df[df['Type'] == 'F'].index.tolist()
D = df[df['Type'] == 'D'].index.tolist()
S = df[df['Type'] == 'S'].index.tolist()
C = df[df['Type'] == 'C'].index.toli... | This function executes a multi-echelon heuristic to solve a logistics problem by processing input data, computing optimal solutions (Opt), timing execution (dt), and optionally saving visualizations (plots) and results (solution data) to specified directories. It reads data, runs the heuristic, recovers original values... | def ExecuteMultiEchelonFromData(datadir,file, plotdir = None, soldir = None):
"""
This is for executing the math heuristic for solving the multi echelon bla bla
For plotdir and soldir, give a valid directory in case you want to save the results
If you don't provide a directory for plotdir, the script wi... |
def resolveAddressAndTarget(target, symbolStr):
resolvedAddr = 0
# resolve + offset
plusSplit = symbolStr.split('+', 1)
if len(plusSplit) > 1:
symbolStr = plusSplit[0]
resolvedAddr += int(plusSplit[1], 16)
# resolve different nso target with '!' notation
targetSplit = symbolStr... | This function reads a patch file, extracts version and target variables, filters patches by version, parses address-target pairs, handles multi-line patches, and adds them to a patch list for application. | def addPatchFromFile(patchFilePath):
PATCH_VERSION_ALL = "all"
patchVars = {
"version" : None,
"target" : "main"
}
with open(patchFilePath) as patchFile:
fileLinesIter = iter(patchFile)
isInMultiPatch = False
while True:
# read next line
i... |
def check_keydown_events(event,ship,screen,ai_settings,bullets,bullet_sound):
if event.key == pygame.K_RIGHT:
ship.moving_right = True
elif event.key == pygame.K_LEFT:
ship.moving_left = True
elif event.key == pygame.K_UP:
ship.moving_up = True
elif event.key == pygame.K_DOWN:
... | The function `check_events` processes Pygame events such as quitting, key presses, and mouse clicks. It handles keyboard input for ship movement and shooting, checks mouse clicks to start the game via the play button, and updates game state accordingly. | def check_events(ai_settings,screen,stats,sb,play_button,ship,aliens,bullets,bullet_sound):
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.KEYDOWN:
check_keydown_events(event,ship,screen,ai_settings,bullets,bullet_sound)
... |
def check_fleet_edges(ai_settings,aliens):
for alien in aliens.sprites():
if alien.check_edges():
ai_settings.fleet_direction *= -1
change_fleet_direction(ai_settings,aliens)
break
def ship_hit(ai_settings,stats,sb,screen,ship,aliens,bullets,die):
if stats.ships_left ... | This function updates alien movement, checks for collisions between the ship and aliens, and verifies if aliens reach the screen bottom. It triggers responses like ship damage or game over conditions when collisions occur or aliens reach the bottom. | def update_aliens(ai_settings,stats,sb,screen,ship,aliens,bullets,die):
check_fleet_edges(ai_settings,aliens)
aliens.update()
if pygame.sprite.spritecollideany(ship,aliens):
ship_hit(ai_settings,stats,sb,screen,ship,aliens,bullets,die)
check_aliens_bottom(ai_settings,stats,sb,screen,ship,alie... |
def init_db():
db_cursor(lambda cursor: cursor.execute(CREATE_TABLE))
def load_rotten_tomatoes_movies():
print('Loading movies from Rotten Tomatoes...')
streaming_page = requests.get(STREAMING_URL)
theaters_page = requests.get(THEATERS_URL)
streaming_movies_info = BeautifulSoup(streaming_page.conte... | The main task of the code is to initialize a database, load movie data from Rotten Tomatoes, identify movies not yet downloaded, and download them from PirateBay. It orchestrates data retrieval, storage, and automated downloading of movies. | def main():
init_db()
load_rotten_tomatoes_movies()
movies = not_downloaded_movies()
download_piratebay_movies(movies) |
def Valid_Iden(Tokens_Dict):
return re.match("^[a-zA-Z][a-zA-Z0-9]*$", Tokens_Dict['Lex'])
def Valid_const(Tokens_Dict):
return re.match("^[0-9]\.?[0-9]*?$", Tokens_Dict['Lex'])
def Factor(j):
Children = []
output = dict()
if (j < len(Tokens)):
Tokens_Dict = Tokens[j].to_dict()
if ... | This function parses a sequence of factors (identifiers/constants) from a token list, recursively building a tree structure. It checks if the current token is valid, constructs a 'Factors' node with child nodes from recursive calls, and returns a dictionary containing the tree node and the last parsed index. | def Factors(j):
Children = []
output = dict()
if (j < len(Tokens)):
Tokens_Dict = Tokens[j].to_dict()
if Valid_Iden(Tokens_Dict) or Valid_const(Tokens_Dict):
Factor_Dict = Factor(j)
Children.append(Factor_Dict["node"])
Facsss_Dict = Factors(Factor_Dict["... |
def Valid_Iden(Tokens_Dict):
return re.match("^[a-zA-Z][a-zA-Z0-9]*$", Tokens_Dict['Lex'])
def Valid_const(Tokens_Dict):
return re.match("^[0-9]\.?[0-9]*?$", Tokens_Dict['Lex'])
def Factor(j):
Children = []
output = dict()
if (j < len(Tokens)):
Tokens_Dict = Tokens[j].to_dict()
if ... | The main task of the code is to parse an increment variable expression by checking if the current token is a valid identifier or constant. If valid, it constructs an AST node ("IncrementVar") with a child node from the Factor function and returns the node along with the updated index. The function returns the parsed tr... | def IncrementVar(j):
Children = []
output = dict()
if (j < len(Tokens)):
Tokens_Dict = Tokens[j].to_dict()
if Valid_Iden(Tokens_Dict) or Valid_const(Tokens_Dict):
Factor_dict = Factor(j)
Children.append(Factor_dict["node"])
else:
return
no... |
def train_process(self, epoch, train_data_engine):
self.network = self.network.train()
self.lr_rate_setting(epoch)
data = train_data_engine
train_loss = 0
correct = 0
total = 0
data.shuffle_data()
print('no of batched', data.no_batches)
for _ in ... | The function `train_model` trains a machine learning model over a specified number of epochs using provided training and validation data engines. It tracks training and validation accuracy/loss for each epoch, appending them to a metrics array (`graph`). If `save_mode` is enabled, it saves the model at each epoch based... | def train_model(self, no_epoch, train_data_engine,
valid_data_engine, save_mode = False):
graph = np.zeros((1, 4))
if self.pretrained_epoch is None:
self.pretrained_epoch = 0
else:
self.pretrained_epoch +=1
for epoch in range(self.pretrained_... |
def homeScreenKeyPressed(event, data):
pass
def playClassicKeyPressed(event, data):
if event.char == "r":
init(data)
elif event.char == "t":
data.showTrace = not data.showTrace
elif event.char == "p":
data.paused = not data.paused
def playZenKeyPressed(event, data):
if ev... | This code defines a `keyPressed` function that routes keyboard events to mode-specific handler functions. Depending on `data.mode`, it calls functions like `homeScreenKeyPressed` or `playClassicKeyPressed`, enabling context-aware key input processing in a multi-mode application. The function acts as a dispatcher, ensur... | def keyPressed(event, data):
if data.mode == "homeScreen": homeScreenKeyPressed(event, data)
elif data.mode == "playClassic": playClassicKeyPressed(event, data)
elif data.mode == "playZen": playZenKeyPressed(event, data)
elif data.mode == "playTraining": playTrainingKeyPressed(event, data)
elif data... |
def homeScreenTimerFired(data):
if data.aboutButton.loaded:
data.mode = "aboutPage"
selectList = [data.classicSelect, data.zenSelect, data.trainingSelect, data.AISelect]
modeList = ["playClassic", "playZen", "playTraining", "playAI"]
currentSelectedIndex = None
for i in range(len(selectLi... | The code's main task is to update the player's position and trail, increment the game timer, and delegate to mode-specific timer functions based on the current game state, such as home screen, play modes, or about page, ensuring appropriate game logic execution for each mode. | def timerFired(data):
data.player.updatePosition(data)
data.player.updateTrail()
data.timer += data.timerDelay
if data.mode == "homeScreen": homeScreenTimerFired(data)
elif data.mode == "playClassic": playClassicTimerFired(data)
elif data.mode == "playZen": playZenTimerFired(data)
elif data.... |
def add_spectral(self,i):
self.comb_indx[i]=self.comb_input[i].currentIndex()
if i==0:
logging.info('add spectral of image 1')
else:
logging.info('add spectral of image 2')
if self.getpath[i] !='':
x=ImageModel(self.getpath[i])
if self.comb... | This code initializes a GUI application window, sets up UI components, connects buttons and sliders to functions, configures logging, and prepares image processing options. It initializes image display areas, combo boxes for spectral options, sliders for adjustments, and disables certain UI elements. Event handlers are... | def __init__(self):
super(ApplicationWindow, self).__init__()
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
logging.basicConfig(filename='logFile.log',level=logging.INFO,format='%(levelname)s:%(message)s')
self.ui.clearb.clicked.connect(self.clear_img)
self.img_size =... |
def _get_wpa_networks(parsed):
networks = _interpret_wifi_string(parsed.wifi)
wpa_networks = ""
for connection in networks:
# EAP-secured network
if connection.username is not None:
wpa_networks += WPA_EAP_NETWORK_CONFIG.format(
cname=connection.name,
... | The function `step_setup` prepares and applies a "surgery plan" to an SD card by replacing placeholders with dynamically generated data. It checks dependencies, sanitizes sensitive parameters (e.g., Wi-Fi passwords), compiles system and configuration data, reads disk metadata, and iterates through the surgery plan to i... | def step_setup(shell, parsed, data):
# check if dependencies are met
check_program_dependency("dd")
check_program_dependency("sudo")
check_program_dependency("sync")
# make a copy of the command parameters and remove wifi passwords
params = copy.deepcopy(parsed.__dict__)
wfstr = lambda w: w ... |
def trade(self):
print("\nCards list:\n")
self.view_my_cards()
print("\nEnter Card Pokemon ID: ")
poke_ID = input()
card_found = False
for card in self.my_cards:
if card.poke_id == poke_ID:
card_found = True
message = {"type":"t... | The code processes user commands in a loop until 'exit' is entered. It splits input into parts, checks the first word against predefined commands (e.g., 'trade', 'gift', 'my_cards'), and executes corresponding methods. Unknown commands trigger error messages. The loop terminates when 'exit' sets `self.stop` to True, en... | def action(self):
while not self.stop:
user_input = input()
input_split = user_input.split(" ")
if input_split[0] == '':
continue
elif input_split[0] == 'trade':
self.trade()
elif input_split[0] == 'gif... |
def public_key_to_str(self, public_key):
return public_key.to_string().hex()
def create_genesis_block(self, pokemon_master_key, pokemon_card_id_list):
content = {"pokemon_master_key": pokemon_master_key,
"pokemon_card_id_list": pokemon_card_id_list}
block = Block(content, bloc... | The 'join' function initializes or joins a blockchain network by processing Pokémon data to create a genesis block if no members exist, or updating member records and requesting blockchain data from existing nodes. It handles member registration, socket communication, and blockchain synchronization, ensuring the node i... | def join(self):
lines = []
with open('./members.txt', "r") as f:
lines = f.readlines()
# genesis
if lines == []:
lines = []
with open("./pokemons.csv", "r") as f:
lines = f.readlines()
lines = lines[1:]
... |
def extract_features(text):
words = extract_words(text)
return [intern_feature(word) for word in words]
def score(features):
trump_prob = []
musk_prob = []
num_prob = 0
for feature in features:
if untrained(feature):
# Skip features that dont appear in training
co... | The code classifies a text as originating from Elon Musk or Donald Trump based on a score derived from extracted features. If uncertain, it leans toward Musk or Trump depending on the score range. For Musk classifications, the certainty is inverted. The result includes the assigned author and a percentage certainty. | def classify(text):
features = extract_features(text)
value = score(features) #Between 0 and 1
who = classification(value)
#I force it to have a 'hunch' on who the tweet belongs to
if who == 'unsure' and MAX_MUSK_SCORE < value < 0.5:
msg = "I'm not too sure who this tweet came from. How... |
def extract_features(text):
words = extract_words(text)
return [intern_feature(word) for word in words]
def increment_count(feature, type):
if type == 'Musk':
feature['musk_count'] += 1
elif type == 'Trump':
feature['trump_count'] += 1
else:
raise TypeError(f'Expected musk or... | The code's main task is to process input text by extracting features, increment individual feature counts associated with a specified type, and update the total count for that type. It iterates through extracted features, updates their respective counters, and returns the incremented total count for the given type, lik... | def train(text, type):
for feature in extract_features(text):
increment_count(feature, type)
return increment_total_count(type) |
def wrapper_og(s):
for phrase in re.findall('"([^"]*)"', s):
s = s.replace('"{}"'.format(phrase), phrase.replace(' ', '_'))
doc = nlp(s)
s = doc._.coref_resolved
sentences=nltk.sent_tokenize(s)
trees = []
for sentence in sentences:
trees.append((Tree.fromstring(parser.parse(sente... | The code generates multiple question types (yes/no, how many, etc.) from input text by analyzing syntactic structures and named entities. It processes each sentence, extracts entities, and applies specific functions to create questions. Valid questions are filtered and printed with formatted numbering and punctuation. | def question_generator(text, n):
trees = wrapper_og(text)
questions = {'yesno': [], 'howmany': [], 'where': [], 'when': [], 'who': [], 'why': [], 'how': [], 'what': []}
for (const_tree, sentence) in trees:
NERtags = getEntities(sentence)
q = (howMany(const_tree, NERtags))
if... |
def debug_print(str):
"""Surrounds the msg with +"""
print("+" * 80)
print(str)
print("+" * 80)
def check_type(obj):
"""Checks args type against the dataclass"""
debug_print("In function check_type")
parm = ""
for field in dataclasses.fields(obj):
value = getattr(obj, field.name)... | The function `validate` checks if the input arguments (`args`) have exactly 7 elements. If so, it attempts to create an `Arguments` object from them. If this fails (e.g., invalid types), it prints "Executed successfully" and exits with a usage message. Otherwise, it validates the argument types, prepares a query using ... | def validate(args: List[str]):
debug_print("In function validate")
if len(args) == 7: # check for argument length
try:
arguments = Arguments(*args)
except TypeError:
print("Executed successfully")
raise SystemExit(USAGE)
else:
raise SystemExit(US... |
def debug_print(str):
"""Surrounds the msg with +"""
print("+" * 80)
print(str)
print("+" * 80)
def read_and_write_execution_pointer(operation, listname, path_name=None):
# bucket = s3.Bucket(bucketname)
# TODO: Debug why the bucket does not exist
# print(f"Bucket: {bucketname}")
if oper... | The main task of the code is to execute a series of SQL queries on an Amazon Redshift cluster using a configured cluster setup. It reads a list of queries from an execution pointer, runs them, captures results, and stores outputs in CSV files if specified. It also validates test cases against expected outcomes by compa... | def create_cluster_and_execute_query(clusterconfigfile, clusterconfigparm, output):
c1 = RedshiftEphemeral(clusterconfigfile, clusterconfigparm)
# breakpoint()
# TODO: Removing create cluster option
# c1.create_cluster()
df1 = c1.extract_cluster_properties()
debug_print(f"Cluster Detils: \n{df1}... |
def debug_print(str):
"""Surrounds the msg with +"""
print("+" * 80)
print(str)
print("+" * 80)
def validate(args: List[str]):
debug_print("In function validate")
if len(args) == 7: # check for argument length
try:
arguments = Arguments(*args)
except TypeError:
... | The main task of the code is to process command-line arguments, validate them, and execute a cluster creation and query execution workflow using specified configuration files and parameters. It handles help requests, checks for required inputs, and triggers the `create_cluster_and_execute_query` function with arguments... | def main() -> None:
args = sys.argv[1:]
debug_print(f"Arguments: {args}")
if not args:
raise SystemExit(USAGE)
if args[0] == "--help":
print(USAGE)
else:
validate(args)
# breakpoint()
create_cluster_and_execute_query(
clusterconfigfile=sys.argv[6]... |
def load_config():
# Load global parameters as paths, symbols and periods to iterate through
with open(os.path.sep.join(['.','config.yaml']), 'r') as f:
config = yaml.safe_load(f.read())['merging']
# Path where every individual folder is located
config['path'] = config['src_path'] + config['lev... | This code merges multiple time-series CSV files into a single DataFrame by filtering files within a specified date range, processing timestamps, and appending relevant data. It uses configuration parameters to determine file paths, date ranges, and time intervals, then saves the consolidated dataset. | def merge():
# Set logging level
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
# Load settings and declare DF
df = pd.DataFrame()
config = load_config()
# Iterate through collection of processed data with indicators
for filename in sorted(glob.glob(config['path'] + config... |
def load_data(conf, min_time=''):
# Iterate through collection of processed data with indicators
df_full = pd.DataFrame()
for filename in sorted(glob.glob(conf['path'] + conf['filename_pattern'])):
# Extract dates from filename
aux_dates = filename.replace(conf['path'] + conf['eft']+'_(', '... | The function `run_tests_for_config` executes two sets of comparisons: first, it compares data from the current EFT configuration against other specified EFTs by loading their data and using `compare_efts`; second, it compares data at different hierarchical levels of the same EFT by adjusting the level in the config, re... | def run_tests_for_config(config):
# Load all the data for the current level and period in a Dataframe
cl_df, min_time = load_data(config)
logging.info('First part in testing, comparing to efts at same level:')
for other_eft in config['compare_efts']:
logging.info(' ///// ')
logging.in... |
def define_indicators():
# Creating a dictionary of technical indicators using TALib abstract API
indicator = {}
# Add as many indicators as necessary: see all indicators in https://mrjbq7.github.io/ta-lib/
indicator['sma'] = abstract.Function('sma') # Simple Moving Average
indicator['ema'] = abst... | The code processes financial data (EFTs) by loading configuration parameters, defining technical indicators, and generating datasets for machine learning. It unzips data if required, then iterates through time periods (years/quarters) for each EFT and level, creating training/test sets for model development. The task i... | def compute():
# Load global parameters as paths, symbols and periods to iterate through
with open('./config.yaml', 'r') as f:
config = yaml.safe_load(f.read())
# Creating a global dictionary of functions for every technical indicator
define_indicators()
# If data needs to be unzipped, do... |
def load_config():
# Load global parameters as paths, symbols and periods to iterate through
with open(os.path.sep.join(['.', 'config.yaml']), 'r') as f:
config = yaml.safe_load(f.read())['merging']
# Path where every individual folder is located
config['path'] = config['src_path'] # + config[... | The code runs multiple tests by iterating through different EFTs, time periods, and levels. It updates configuration parameters for each combination, logs the process, and executes tests using `run_tests_for_config` with the modified settings. The `gap_t+1` feature is temporarily added for testing. | def run_tests():
# Load settings and set logging config
config = load_config()
config['featureset'].append('gap_t+1') # only for testing (not merging)
set_logging(config)
log_new_execution(config)
for eft in config['efts']:
print()
print('EFT: '+str(eft))
print('------... |
def get_interfaces_mac():
interfaces_mac = {}
base_path = "/sys/class/net/"
for interface in os.listdir(base_path):
try:
with open(os.path.join(base_path, interface, 'address'), 'r') as f:
mac_address = f.read().strip()
interfaces_mac[interface] = mac_address.... | The code captures network packets using a raw socket, maps them to processes, tracks metrics (e.g., bytes per process), and manages cleanup threads. It continuously receives packets, parses their data, identifies associated processes, logs details, and updates metrics while handling timeouts. Threads monitor metrics an... | def begin_capture(writeSniff, writeProc):
global capturing
global metrics_thread_exited
global cleanup_thread_exited
s = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.ntohs(3))
s.settimeout(TIMEOUT)
interfaces = get_interfaces_mac()
capturing = True
metrics_thread_exited = Fals... |
def get_all_job_posting_links(html_page: str, page_no) -> list:
"""
Scrapes a given html page and returns links to the detail page of all job search results items
:param html_page: Weblink to the job search result page
:param page_no: search list page number from Upwork url
... | This function scrapes job postings from a webpage, checks if they meet predefined criteria, and collects up to a specified number of matching jobs. It navigates pages, clicks job links, verifies matches, avoids duplicates, and saves valid job details and links to files. The process continues until the required number o... | def get_all_jobs_that_meets_requirements(self, no_of_jobs: int):
"""
Return the first 50 jobs posting that matches a set of pre-defined requirements
:param no_of_jobs: No of matching jobs to be retrieved.
"""
page_no = 1
# Navigates to the webpage link given
... |
def is_in_manifest(repo_name, branch, path):
""" Checks if a repository is in the manifest. """
try:
lm = ElementTree.parse(f"{LOCAL_MANIFESTS_PATH}{LOCAL_MANIFESTS_FILE_NAME}")
lm = lm.getroot()
except ElementTree.ParseError:
lm = ElementTree.Element("manifest")
for local_path ... | The function `fetch_dependencies` reads a JSON dependency file from a repository, checks if each listed dependency is already in the manifest, and adds missing ones. It syncs identified repositories using `repo sync` and recursively verifies device-specific dependencies by re-calling itself on their paths. The task inv... | def fetch_dependencies(repo_path):
""" Adds repos that are in the dependency file to the manifest, and syncs them. """
syncable_repos = []
verify_repos = []
dependencies_path = f"{repo_path}/{DEPENDENCIES_FILE_NAME}"
print(f"Looking for dependencies in {repo_path}")
if os.path.exists(dependenc... |
def get_repositories():
"""
Retrieves all repositories from a project.
If there is not an API token, then requests may be rate-limited.
"""
page = 1
repositories = []
while True:
request = urllib.request.Request(
f"https://api.github.com/users/{ORGANIZATION_NAME}/repos?pa... | The main task of the code is to create a local manifest directory/file if absent, search for a specific device repository, sync it using 'repo sync' commands, and fetch dependencies. It checks for the device repository in a GitHub organization, adds it to dependencies, and ensures the local manifest is updated with the... | def main():
"""
Entry point. Creates a local manifest directory and/or local manifest file if there isn't one,
then creates a local manifest and repo syncs.
"""
if not os.path.isdir(LOCAL_MANIFESTS_PATH):
os.makedirs(LOCAL_MANIFESTS_PATH)
if not os.path.isfile(f"{LOCAL_MANIFESTS_PATH}{... |
def getHighTem(self,temGrid):
r=[]
for x in range(10):
tem=0
for y in range(19,-1,-1):
if(temGrid[x][y]!=-1):
r.append(y+1)
tem=1
break
if tem==0:
r.append(0)
return r
... | The function `next2Move` evaluates potential moves for a game piece on a grid by simulating placements, rotations, and scoring. It creates a temporary grid with an initial move, iterates through all valid positions and rotations, checks feasibility, calculates scores, and retains the highest-scoring move. If no valid m... | def next2Move(self,ix,iy,ir,ps):
#create temp grid with frist move
temGrid = [row[:] for row in self.grid]
for xx in rotations[self.piece][ir]:
temGrid[ix+xx[0]][iy+xx[1]] = self.piece
#variables
solution=[]
solPoint = float('-inf')
moveScore=float('... |
def getHigh(self):
r=[]
for x in range(10):
tem=0
for y in range(20):
if(self.grid[x][y]!=-1):
r.append(y+1)
tem=1
break
if tem==0:
r.append(0)
return r
def ifPossible(... | The code determines the optimal move in a game (likely Tetris) by evaluating all possible placements of the current piece, considering rotations, and calculating scores. It selects the top 5 highest-scoring moves, predicts subsequent scores, and chooses the move with the highest overall potential. The function then app... | def nextMove(self):
#reference variables
solPoint = float('-inf')
highs=self.getHigh()
moveScore=float('-inf')
all=[]
##check every index that is open for a possible placment
for x in range(10):
moveScore=float('-inf')
for y in range(high... |
def add_match_query_multi(field_values, query, match_type: QueryMatchType = QueryMatchType.should, search_type: SearchType = SearchType.any_words):
for field, value in field_values:
add_match_query(field, value, query, match_type, search_type)
def add_query_suggestions(query, field_values):
for field, q... | This function searches for NFTs using Elasticsearch by constructing a query based on input text and search type. It handles pagination, dynamically builds search parameters across multiple fields, and implements fallback suggestions if no results are found. The function returns paginated results including NFT data, tot... | def search_nfts(text="", search_type=SearchType.any_words, page: int = 1, size: int = 10, retrying: bool = False):
query = {
"query": {
"bool": {
"must_not": [],
"must": [],
"should": [],
}
},
"size": size,
"fro... |
def add_match_query_multi(field_values, query, match_type: QueryMatchType = QueryMatchType.should, search_type: SearchType = SearchType.any_words):
for field, value in field_values:
add_match_query(field, value, query, match_type, search_type)
def add_query_suggestions(query, field_values):
for field, q... | The function constructs an Elasticsearch query using must, should, and range clauses, incorporating match, prefix, and range filters. It adds search suggestions, handles sorting, pagination, and executes the query, returning Elasticsearch search results with combined filtering and scoring logic. | def search(es_index: str, must_query_field_values, should_query_field_values, search_type, gte_range_query_field_values, prefix_field_values: dict = {}, sort_by: str = None, page: int = 1, size: int = 10):
query = {
"query": {
"bool": {
"must_not": [],
"must": []... |
def search(es_index: str, must_query_field_values, should_query_field_values, search_type, gte_range_query_field_values, prefix_field_values: dict = {}, sort_by: str = None, page: int = 1, size: int = 10):
query = {
"query": {
"bool": {
"must_not": [],
"must": []... | This function searches for publications using specified filters (e.g., user handles, bio, content keywords) and criteria (e.g., minimum collects/mirrors/comments). It constructs Elasticsearch-like queries, handles no-result scenarios by generating suggestions and retrying searches, then returns paginated results with m... | def search_publications(text="", bio: str = None, from_users: str = None, mention_users: str = None, search_type=SearchType.any_words,
result_type: ResultType = ResultType.latest, min_collects: int = None, min_mirror: int = None, min_comments: int = None,
min_profile_fol... |
def search(es_index: str, must_query_field_values, should_query_field_values, search_type, gte_range_query_field_values, prefix_field_values: dict = {}, sort_by: str = None, page: int = 1, size: int = 10):
query = {
"query": {
"bool": {
"must_not": [],
"must": []... | The code searches for user profiles using specified criteria (owned_by, bio, min_followers, etc.), combining must-match, should-match, and range queries. If no results are found, it generates suggestions and retries. It returns paginated results with profile data, query parameters, and total counts. | def search_profiles(text: str, bio: str, owned_by: str, min_follower: int, min_posts: int, min_publications: int, min_comments: int,
page: int = 1, size: int = 10, retrying=False):
must_query_field_values = {
"ownedBy": owned_by,
"bio": bio
}
should_query_fields = ["nam... |
def _is_pure(self, obs_index):
"""
Checks whether a node is a leaf due to homogeneous dependent variable value
:param obs_index: (Index) DataFrame indices of observations to be considered
:return: (bool) Is a leaf?
"""
return len(np.unique(self.data.dependent[obs_index]))... | This function recursively builds a decision tree branch by splitting data based on the best feature-value pair, checking stopping conditions (max depth, purity, min samples), and returning either a leaf node value or a dictionary representing a decision node with child branches. It handles cases where branches must dif... | def _grow(self, obs_index, counter=0, branches_must_differ=False):
"""
Adds a branch to decision tree dictionary (self.tree_dict)
:param obs_index: absolute indices of observations to be considered
:param counter: (int) Current depth of branch
"""
data = self.data.loc[obs... |
def sources(item):
"""
iterate over sources of item
"""
if field_in_level('sources',metadata(item)):
for source in metadata(item)['sources']:
yield(source)
else:
[]
def field_in_level(field, level):
"""
true if field is in level, false otherwise
"""
return... | This function extracts and returns a list of organizational creators from each source within an item. It iterates through sources, checks for 'creators' fields, filters those with 'organization' details, and compiles them into nested lists corresponding to each source. | def sources_organizations_from_item(item):
"""
extract sources’ creators from item if organization
"""
result = []
for source in sources(item):
source_organizations = []
if field_in_level('creators', source):
for creator in creators_from_source(source):
if... |
def sources(item):
"""
iterate over sources of item
"""
if field_in_level('sources',metadata(item)):
for source in metadata(item)['sources']:
yield(source)
else:
[]
def field_in_level(field, level):
"""
true if field is in level, false otherwise
"""
return... | This function extracts creators from each source of an item who are identified as persons. It iterates through sources, checks for 'creators' fields, filters those with 'person' designation, and compiles them into a nested list structure. | def sources_persons_from_item(item):
"""
extract sources’ creators from item if person
"""
result = []
for source in sources(item):
source_persons = []
if field_in_level('creators', source):
for creator in creators_from_source(source):
if field_in_level('p... |
def sources(item):
"""
iterate over sources of item
"""
if field_in_level('sources',metadata(item)):
for source in metadata(item)['sources']:
yield(source)
else:
[]
def field_in_level(field, level):
"""
true if field is in level, false otherwise
"""
return... | This function extracts identifier types and values from an item's sources. It iterates through each source, checks for 'identifiers' fields, and collects tuples of (type, id) from valid sources. If a source lacks identifiers, it returns an empty tuple. The result is a list of lists containing these identifier pairs fro... | def sources_identifiers_from_item(item):
"""
extract values and types of identifiers from item’s sources
"""
result = []
for source in sources(item):
if field_in_level('identifiers',source):
result.append([(value_from_level('type', idx), value_from_level('id', idx))\
... |
def date_pubprint_from_item(item):
"""
extract publication date (print) from item
"""
return field_from_metadata('datePublishedInPrint', item)
def date_pubonline_from_item(item):
"""
extract publication date (online) from item
"""
return field_from_metadata('datePublishedOnline', item)
d... | This function extracts the first available date from an item by checking predefined date fields in a prioritized order. It returns the earliest valid date found using helper functions like `date_pubprint_from_item` or `date_pubonline_from_item`, or an empty string if no valid date is present. | def date_from_item(item):
"""
extract date from item
"""
if date_pubprint_from_item(item):
return date_pubprint_from_item(item)
elif date_pubonline_from_item(item):
return date_pubonline_from_item(item)
elif date_modified_from_item(item):
return date_modified_from_item(it... |
def sources_persons_from_item(item):
"""
extract sources’ creators from item if person
"""
result = []
for source in sources(item):
source_persons = []
if field_in_level('creators', source):
for creator in creators_from_source(source):
if field_in_level('p... | This function extracts structured person data from an item, returning a nested list of tuples containing person IDs, names, roles, and ID types. It processes multiple sources, each containing persons, and compiles their details into a hierarchical format for downstream use. | def sources_persons_id_from_item(item):
"""
"""
result = []
for source in sources_persons_from_item(item):
s = []
for person in source:
pers_name = persons_name_from_creator(person)
pers_role = role_from_creator(person)
pers_id, pers_id_type = persons_... |
def parse_args():
parser = argparse.ArgumentParser(
description="scans Connect apps for XSS vulnerabilities"
)
parser.add_argument("--module", required=False)
parser.add_argument("--timeout", default=10, type=int, help="how many seconds before waiting for certain elements to appear in the login ... | This script automates security testing of a web application by logging in with provided credentials, using Selenium to inject XSS payloads for vulnerability detection, and scanning for secrets/api tokens via API calls. It generates a structured vulnerability report in JSON format. | def main():
args = parse_args()
username = args.username
password = args.password
instance_url = args.url
api_token = args.api_token
output = args.out
timeout = args.timeout
options = Options()
if chrome_path := shutil.which("chromium") or shutil.which("chrome"):
options.bin... |
def draw_grid():
for y in range(GRID_SIZE):
for x in range(GRID_SIZE):
color = WHITE
if grid[y][x] == 1:
color = RED
elif grid[y][x] == 2:
color = BLUE
elif (x, y) in winning_line:
color = GREEN
pygam... | The code implements a turn-based game loop using Pygame, handling player and AI moves on a grid. It detects mouse clicks to update the grid, checks for wins, updates scores, and displays results. The loop manages game state, rendering the grid, scoreboard, and win screen, with reset functionality via a button click. | def play():
global game_over, winning_line, winner
running = True
while running:
global player_score, ai_score
screen.fill(WHITE)
draw_grid()
draw_scoreboard(player_score, ai_score)
if game_over:
draw_win_screen()
for event in pygame.event.get():... |
def draw_grid(self):
print(' ' + ' '.join(map(str, range(self.size))))
for i, row in enumerate(self.grid):
print(f'{i} ' + ' '.join(['X' if cell == 'Player' else 'O' if cell == 'AI' else '.' for cell in row]))
print()
print('Score:', self.score)
print()
def reset_gam... | The code implements a turn-based game where a player and AI alternately make moves on a grid. It handles user input for coordinates, validates moves, resets the game if needed, and ends when the AI cannot move. The final score is displayed after the game concludes. | def play_game(self):
while True:
self.draw_grid()
x = input('Enter x coordinate (or "r" to reset): ')
if x == 'r':
self.reset_game()
continue
y = input('Enter y coordinate (or "r" to reset): ')
if y == 'r':
... |
def _balance(u):
w_u = sum(i.w for i in u)
if w_u == 0:
return _create_balanced_tree(u)
curr_sum = 0
r = 0
for curr_u in u:
curr_sum += curr_u.w
if curr_sum >= w_u / 2:
break
r += 1
# balance e(r-1) t(r) e(r) balance
# ..r-2] r-1 r r+1 [r+... | The function constructs a balanced tree structure by recursively partitioning edges based on y-coordinates using a trapezoidal decomposition. It divides edges into intervals, groups nodes/edges, creates tree nodes, and balances them, returning a tree with median node as root and balanced children. | def _trapezoid(g, e, v, i):
if not v:
return None
y_med = g.nodes(True)[v[(len(v) - 1) // 2]][1]
i_i = [[min(i), y_med], [y_med, max(i)]]
t = 0
v_t_indices = {}
v_i = [[], []]
for curr_e in e:
coord_0 = g.nodes[curr_e[0]]
coord_1 = g.nodes[curr_e[1]]
for i in... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.