dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def verifyAccessToken(token):
current_time = int(time.time())
try:
# check token structure
if len(token.split(".")) != 3:
print (0)
return returnJWTCheckerResponse(isAuthorized=False, other_params={})
except Exception as e:
print (1)
ret... | Your return
The code validates an access token and generates an IAM policy to control API Gateway method access. It checks the token's scope (e.g., "read," "write") to dynamically permit or deny specific resources/verbs. If unauthorized, it denies all methods; otherwise, it grants permissions based on the token's sco... | def lambda_handler(event, context):
"""Do not print the auth token unless absolutely necessary """
#print("Client token: " + event['authorizationToken'])
print("Method ARN: " + event['methodArn'])
"""validate the incoming token"""
"""and produce the principal user identifier associated with the... |
def load_config(path):
with open(path) as f:
return json.loads(f.read())
def get_playlist_tracks(uid, playlist_id):
url = re.sub("uid", str(uid), PLAYLIST_URL)
url = re.sub("playlist_id", str(playlist_id), url)
data = json.loads(requests.get(url).text)
tracks = []
for track in data["resu... | The code processes multiple music playlists by fetching tracks from each, shuffling them, and combining them into a single mixed playlist. It uses a configuration file to authenticate and specify source/destination details, then uploads the shuffled tracks to a target playlist, returning the final list of track names. | def process_config(config_path):
config = load_config(config_path)
music_oauth_headers = {"Authorization": "OAuth " +
config["destination"]["music_oauth_token"]}
destination_uid = config["destination"]["uid"]
destination_playlist_id = config["destination"]["playlist_id"]
... |
def import_agents(dir):
return SampleAgents
next_id = 0
agent_list = {}
for file in os.listdir(dir):
try:
next_agent = ReadInAgent(next_id, file)
agent_list[next_id] = next_agent
next_id += 1
except:
continue
return agent_list
def run_c... | The main task of the code is to execute a competition between imported agents, either with or without noise, based on configurations specified in a text file. It reads agent modules from "./agents/", loads parameters from "config.txt", and runs either `run_competition` (if noise is 0) or `run_noisy_competition` (with n... | def main():
agents = import_agents("./agents/")
config = eval(open("config.txt").read())
if config["noise"] == 0:
run_competition(agents, config["rounds"])
else:
run_noisy_competition(agents, config["rounds"], config["noise"]) |
def get_children(self):
if self.state == GateNode.STATE_INITIATED:
return self.neighbours
elif self.state == GateNode.STATE_ELECTING:
return [child for child in self.neighbours if child != self.parent]
else:
self.handle_error('Unexpected state')
def has_all_an... | This function processes an 'election_started' message by transitioning the node to an electing state, notifying children, and initiating self-vote if no children exist. It handles state-specific responses, sending 'election_voted' messages with appropriate leader information or errors for invalid states. | def process_election_started(self, message):
if self.state == GateNode.STATE_IDLE:
self.state = GateNode.STATE_ELECTING
self.parent = message.sender
self.leader = None
self.answers = {}
for child in self.get_children():
yield NetworkM... |
def has_all_answers(self):
return all(child in self.answers for child in self.get_children())
def get_best_answer(self):
child_answers = [
self.answers[child]
for child in self.get_children()
if self.answers[child] is not None
]
# select node with the... | This method processes election results by collecting leader responses from children nodes, determining the optimal leader, updating the node's state (to waiting or idle), and propagating the elected leader to neighbors via network messages, while handling errors for unexpected states. | def process_election_voted(self, message):
leader = message.payload['leader']
if self.state in (GateNode.STATE_ELECTING, GateNode.STATE_INITIATED):
self.answers[message.sender] = leader
if self.has_all_answers(): # all children have responded now
leader = self.g... |
def __check_before_work(self,keys:List[str]):
for key in keys:
if key not in self.__dict__:
raise ValueError('{} is Missing in Wrapper instance')
def __trans_np_to_tensor(self,item:Sequence[Any]):
wordset, attention_mask, waiting_word, labels = item
F = lambda x: torc... | (Training a model over multiple epochs using a training data loader, computing loss and metrics (accuracy, precision, recall, F1) during training, validating model performance if a validation data loader exists, updating the best model based on F1 score, and yielding training/validation metrics and cluster evaluation r... | def train_(self):
self.__check_before_work(['dev_dataloader','train_dataloader'])
self.model.to(self.device)
t = range(self.start_epoch, self.epoches)
all_step = len(self.train_dataloader)
validation_flag = True if self.dev_dataloader is not None else False
for epoch in t... |
def translate(var_type,var,new_type):#To give the numerical id of a location from its name, or vice-versa, or even from its map_coords
search_term = var
return_val = None
if var_type == "MAP_COORD":
search_term = Game_Map[var[0]][var[1]]
var_type = "NAME"
for key in range(len(Location_Di... | This function processes a command string associated with a location, executes corresponding actions (e.g., printing text, handling user input, renaming the player, or navigating locations), and returns a result based on the command's outcome. It parses the input string to extract commands and parameters, interacts with... | def Find_Execute_Command(loc_name,str):
retval = None
print()
location_id = translate("NAME",loc_name,"ID")
current_location = location_list[location_id]
command = str[str.index("|")+1:str[str.index("|")+1:].index("|")+str.index("|")+1]
current_player = player_list[-1]
... |
def stage_raw(packets):
for packet in packets:
btatt = get(packet, '_source/layers/btatt')
op = get(btatt, 'btatt.opcode')
cmd = {
'0x12': 'write req',
'0x13': 'write res',
'0x52': 'write',
'0x0a': 'read req',
'0x0b': 'read res',
... | The code processes input files (JSON or TXT) by parsing their contents and applying transformation stages based on command-line options. If the input is JSON, it uses `stage_raw`; for TXT, it splits lines. Depending on flags like `--hex` or `--json`, it applies `stage_hex` or `stage_json`, or outputs raw parsed data. T... | def main(opts):
was_raw = None
if opts.file[0].endswith('.json'):
was_raw = True
# packet capture?
packets = json.loads(Path(opts.file[0]).read_bytes())
parsed = stage_raw(packets)
elif opts.file[0].endswith('.txt'):
# raw parsed
parsed = Path(opts.file[0]).re... |
def complete_test(self, assignment):
for num in assignment:
if num == -1:
return False
return True
def select_unassigned_variable(self, csp, assignment, mrv, degree):
# if no heuristics return first unassigned variable
if not (mrv or degree):
for i... | The main task of the code is to implement a backtracking algorithm for solving constraint satisfaction problems (CSPs), using variable selection heuristics (MRV, degree), value ordering (LCV), and optional arc consistency (AC-3). It recursively assigns values to variables, checks consistency, updates domains, and backt... | def backtrack(self, assignment, csp, mrv, degree, lcv, ac3):
self.nodes_visited += 1 # for each recursive call, increment nodes visited
if self.complete_test(assignment): # if assignment is complete then return assignment
return assignment
# grab unassig... |
def build(control=None):
pic_select = pygame.image.load(r'resources/background.jpg')
pic_select = pygame.transform.scale(pic_select, (WIDTH, HEIGHT))
screen.blit(pic_select, [0, 0])
# These images came from this URL: https://scribblenauts.fandom.com/wiki/Miner
# We do not take credit for the male a... | The code defines an interface for interacting with a tree structure using Pygame. It handles keyboard inputs to navigate nodes, pan the view, insert new nodes, and reset the tree. The loop continues until the user quits or the node count exceeds the limit, updating the display with `build(True)` for real-time rendering... | def interface():
global LAST
inter = True
while inter is True and m.nodecount <= NUM_OF_NODES:
build(True)
for event in pygame.event.get():
if event.type == QUIT:
quit()
elif event.type == KEYDOWN:
if event.key in [K_q, K_ESCAPE]:
... |
def create_root_node():
root = Node(depth=0)
root.type = "root"
add_new_node(root, 0)
return root
def insert_both(root, depth):
insert_node_left(root, depth)
insert_node_right(root, depth)
def insert_node_right(node, depth):
# print("insert_node_right \nnode.rect: ", node.rect)
node.righ... | The main task of the code is to construct a tree structure by creating and inserting nodes with specific depth-based operations, navigate through the tree to position nodes, and prepare the tree for rendering by setting rectangular boundaries, finally returning the root node of the constructed tree. | def tree1():
root = create_root_node()
m.selection = root
insert_both(root, root.depth)
insert_node_right(root.right, root.right.depth)
insert_both(root.left, root.right.depth)
m.selection = root.left
m.selection = m.selection.right
insert_node_left(m.selection, m.selection.depth)
wh... |
def create_root_node():
root = Node(depth=0)
root.type = "root"
add_new_node(root, 0)
return root
def insert_both(root, depth):
insert_node_left(root, depth)
insert_node_right(root, depth)
def insert_node_right(node, depth):
# print("insert_node_right \nnode.rect: ", node.rect)
node.righ... | The function constructs a specific tree structure by creating nodes and inserting them at designated positions based on depth. It sets the selection to the root, inserts nodes on both sides, navigates through left and right branches, adds child nodes to specific branches, adjusts the selection, and sets all rectangles ... | def tree2():
root = create_root_node()
m.selection = root
insert_both(root, root.depth)
insert_both(root.right, root.right.depth)
insert_node_right(root.left, root.left.depth)
m.selection = root.left
insert_node_left(m.selection.right, m.selection.right.depth)
m.selection = root.right
... |
def build_single_root():
root = create_root_node()
m.selection = root
set_all_rects()
return root
def insert_both(root, depth):
insert_node_left(root, depth)
insert_node_right(root, depth)
def set_all_rects():
arrayOfCoords = []
for layer in m.nodelist:
for node in layer:
... | The code creates a tree structure with a root node, sets the root as the selected node, inserts two children at the root's depth, updates all node rectangles, and returns the root node for further processing. | def parent_with_two_children():
root = build_single_root()
m.selection = root
insert_both(root, root.depth)
set_all_rects()
return root |
def build(control=None):
pic_select = pygame.image.load(r'resources/background.jpg')
pic_select = pygame.transform.scale(pic_select, (WIDTH, HEIGHT))
screen.blit(pic_select, [0, 0])
draw(control)
pygame.display.flip()
def quit():
print("QUIT")
pygame.quit()
sys.exit()
def build_tree():
... | This code defines an interactive interface for navigating and modifying a tree structure using keyboard inputs. It handles events like quitting, resetting the tree, panning the view, selecting nodes, and inserting new nodes. The loop updates the display, adjusts node positions, and maintains user interaction until the ... | def interface():
global LAST
inter = True
while inter is True and m.nodecount <= NUM_OF_NODES:
build(True)
for event in pygame.event.get():
if event.type == QUIT:
quit()
elif event.type == KEYDOWN:
if event.key in [K_q, K_ESCAPE]:
... |
def build_single_root():
root = create_root_node()
m.selection = root
set_all_rects()
return root
def insert_both(root, depth):
insert_node_left(root, depth)
insert_node_right(root, depth)
def set_all_rects():
arrayOfCoords = []
for layer in m.nodelist:
for node in layer:
... | The main task of the code is to construct a tree structure with a root node and two children by calling `build_single_root()` to create the root, using `insert_both()` to add two child nodes, updating node positions with `set_all_rects()`, and finally returning the root node for further processing or rendering. | def parent_with_two_children():
root = build_single_root()
m.selection = root
insert_both(root, root.depth)
set_all_rects()
return root |
def create_root_node():
root = Node(depth=0)
root.type = "root"
add_new_node(root, 0)
return root
def insert_both(root, depth):
insert_node_left(root, depth)
insert_node_right(root, depth)
def set_all_rects():
arrayOfCoords = []
for layer in m.nodelist:
for node in layer:
... | The main task of the code is to construct a specific tree structure by navigating through nodes, inserting elements at defined depths, and updating associated rectangles. It starts by creating a root node, traverses left and right children, inserts nodes recursively, adjusts the selection pointer, and finally calls `se... | def build_full_tree():
root = create_root_node()
m.selection = root
insert_both(root, root.depth)
root = root.left
insert_both(root, root.depth)
root = root.parent
root = root.right
insert_both(root, root.depth)
root = root.left
insert_both(root, root.depth)
root = m.selectio... |
def create_root_node():
root = Node(depth=0)
root.type = "root"
add_new_node(root, 0)
return root
def insert_both(root, depth):
insert_node_left(root, depth)
insert_node_right(root, depth)
def set_all_rects():
arrayOfCoords = []
for layer in m.nodelist:
for node in layer:
... | The code constructs a tree structure by navigating through nodes, inserting them into a data structure using insert_both(), and setting up their rectangular properties. It manipulates the tree by moving left/right from the root, updating the selection, and finally returns the root node after setting all rectangles. | def build_comp_tree():
root = create_root_node()
m.selection = root
insert_both(root, root.depth)
root = root.left
insert_both(root, root.depth)
root = m.selection
root = root.right
insert_both(root, root.depth)
root = m.selection
root = root.left
root = root.left
insert_... |
def create_root_node():
root = Node(depth=0)
root.type = "root"
add_new_node(root, 0)
return root
def insert_both(root, depth):
insert_node_left(root, depth)
insert_node_right(root, depth)
def set_all_rects():
arrayOfCoords = []
for layer in m.nodelist:
for node in layer:
... | The code constructs a perfect binary tree by navigating through nodes, inserting them with specific depth values, and adjusting selections. It moves between left and right children, updates the root, and calls `insert_both` and `set_all_rects` to define the tree structure and layout, ultimately returning the root node. | def build_perfect_tree():
root = create_root_node()
m.selection = root
insert_both(root, root.depth)
root = root.left
insert_both(root, root.depth)
root = m.selection
root = root.right
insert_both(root, root.depth)
root = m.selection
root = root.left
root = root.left
inse... |
def toss_and_choose(self):
self.current_batting_team = random.choice([self.team1, self.team2])
self.current_bowling_team = self.team1 if self.current_batting_team == self.team2 else self.team2
def simulate_innings_pair(self, team1, team2):
self.simulate_innings(team1, team2)
self.switch_... | The code's main task is to initialize and manage a cricket match by selecting team captains, setting batting and bowling orders for both teams, conducting a toss to determine innings sequence, simulating the innings, and concluding the match. It orchestrates the entire match process from setup to completion. | def start_match(self):
self.team1.select_captain()
self.team2.select_captain()
self.team1.set_batting_order()
self.team2.set_batting_order()
self.team1.set_bowling_order()
self.team2.set_bowling_order()
self.toss_and_choose()
self.simulate_innings_pair(sel... |
def parse(argv=None):
path = "config"
config_name = None
dat = docopt.docopt(__doc__, argv)
if dat["start"]:
action = "start"
config_name = dat["<configname>"]
args = {"pull_images": dat["--pull"]}
options = {}
if dat["--hintr-branch"] is not None:
opt... | The main task of the code is to parse command-line arguments, load a configuration, initialize an object, and execute actions like managing user interactions, upgrades, starting/stopping services, and handling configurations based on the provided action parameter, with data loss verification and configuration persisten... | def main(argv=None):
path, config_name, action, args, options = parse(argv)
config_name, cfg = load_config(path, config_name, options)
obj = hint_constellation(cfg)
if action == "user":
hint_user(cfg, **args)
elif action == "upgrade_hintr":
hint_upgrade_hintr(obj)
elif action == ... |
def generateMidiData(sampling):
#number of samples per second
fs = sampling
#only gets the slice from 30 seconds to 90 seconds
start = 30*fs
end = 90*fs
#Stores sequence length for tensorflow
sequence_length = end-start
#Makes an empty array of all the note matrices for all midis
... | The code trains an RNN model for music genre classification using TensorFlow. It splits MIDI data into training/test sets, defines an RNN with softmax output, uses Adam optimizer with gradient clipping, and evaluates accuracy on test data after training for 40 steps with batch size 1. | def main():
#Splits the data randomly into testing and training
fs = 20
midi_note, midi_label = generateMidiData(fs)
decimal_split = 0.85
train_x, test_x, train_y, test_y = train_test_split(midi_note, midi_label, decimal_split)
# Training Parameters
learning_rate = 0.0015 #0.002
... |
def split_cm_weights_gain(self, weights):
weight_index = 0
# split gains for fc
def split_and_reshape_fc(weights, weight_index, shape_gain):
length_gain = shape_gain
fc_gain = weights[weight_index:weight_index+length_gain].reshape(shape_gain)
weight_index = ... | This function processes input `y` through a neural network, handling three cases: (1) loading context modulation (CM) weights if provided, (2) loading KNet weights if specified, or (3) using trainable KNet weights. It ensures proper weight initialization, device placement, and enforces constraints like mutual exclusivi... | def forward(self, y, weights_knet = None, weights_cm_gain = None, weights_cm_shift = None):
y = y.to(self.device)
# case: hypernet generate CM weights
if weights_cm_gain is not None or weights_cm_shift is not None:
assert(weights_cm_gain is not None and weights_cm_shift is not None)... |
def wait_on_network(metadata):
# Determine whether we need to wait on the network coming online.
wait_on_ipv4 = False
wait_on_ipv6 = False
if WAIT_ON_NETWORK in metadata:
wait_on_network = metadata[WAIT_ON_NETWORK]
if WAIT_ON_NETWORK_IPV4 in wait_on_network:
wait_on_ipv4_val ... | The code initializes network configuration by retrieving host information, updates metadata with network details, and persists instance data if supported, ensuring network interfaces are ready for subsequent processes. | def setup(self, is_new_instance):
"""setup(is_new_instance)
This is called before user-data and vendor-data have been processed.
Unless the datasource has set mode to 'local', then networking
per 'fallback' or per 'network_config' will have been written and
brought up the OS at... |
def load(data):
'''
load first attempts to unmarshal the provided data as JSON, and if
that fails then attempts to unmarshal the data as YAML. If data is
None then a new dictionary is returned.
'''
if not data:
return {}
try:
return json.loads(data)
except:
return... | The main task of the code is to load metadata from guestinfo data, process network configuration by decoding it if an encoding is specified, restructure the network data into a 'config' key, and return the modified metadata dictionary. | def load_metadata():
'''
load_metadata loads the metadata from the guestinfo data, optionally
decoding the network config when required
'''
data = load(guestinfo('metadata'))
LOG.debug('loaded metadata %s', data)
network = None
if 'network' in data:
network = data['network']
... |
def get_data_access_method():
if os.environ.get(VMX_GUESTINFO, ""):
return VMX_GUESTINFO
if VMWARE_RPCTOOL:
return VMWARE_RPCTOOL
return None
def load_metadata():
'''
load_metadata loads the metadata from the guestinfo data, optionally
decoding the network config when required
... | The main task of the code is to retrieve metadata, user data, and vendor data from a VMware guest environment using guestinfo. It checks data access methods, loads metadata, fetches user/vendor data, cleans up guestinfo keys if specified, and returns True if any data is present, otherwise False. | def get_data(self):
"""
This method should really be _get_data in accordance with the most
recent versions of cloud-init. However, because the datasource
supports as far back as cloud-init 0.7.9, get_data is still used.
Because of this the method attempts to do some of the same ... |
def _send_to_worker(self, worker_index, document_path):
data = {
"exit": False,
"document_path": document_path
}
self.comm.send(data, dest=worker_index, tag=AWAITING_DATA_TAG)
def _exit_worker(self, worker_index):
data = {"exit": True}
self.comm.send(data,... | This function coordinates parallel document processing using MPI. The main thread distributes files to worker processes, tracks progress, and aggregates results, while workers handle individual document extraction tasks. It uses MPI for communication, sends files to workers, monitors completion, and logs progress, ensu... | def _extract_mpi(self, document_dir, num_papers=None):
from mpi4py import MPI
if self.is_main_thread:
all_start_time = datetime.datetime.now()
index = 0
n_finished = 0
filenames = [filename for filename in os.listdir(document_dir) if filename[0] != '.' an... |
def make_records(given_records):
top_level_models = set(MODELS)
streamlined_models_ = streamlined_models(top_level_models)
all_records = {}
for model in streamlined_models_:
all_records[model.__name__] = []
for record_type, dict_records in given_records.items():
model_class = None
... | The main task of the code is to synchronize records by parsing incoming JSON data, updating a database with new records, deleting specified entries, and organizing records into a structured dictionary grouped by model type, ensuring no duplicates by checking unique `_id` fields. | def sync_records():
given_data = json.loads(request.data)
given_records = given_data["records"]
paper_name = given_data["paperName"]
db_root_name = given_data["dbName"]
deleted_records = given_data["deletedRecords"]
print(deleted_records)
db_name = os.path.join(db_root_name, paper_name)
... |
def will_start_extraction(self):
if self.use_wandb:
if wandb.run is None:
self.create_wandb_run()
else:
print("EXISTING RUN", wandb.run)
for file in self.wandb_save_files:
wandb.save(file)
def _extract_single_threaded(self, doc... | This method determines whether to perform document extraction using a single thread or MPI-based parallel processing. It checks flags like `use_mpi` and thread count, then calls either `_extract_single_threaded` for serial processing or `_extract_mpi` for distributed execution, ensuring efficient handling of document b... | def extract(self, document_dir, num_papers=None):
if not self.use_mpi or self.is_main_thread:
self.will_start_extraction()
if not self.use_mpi or self.size == 1:
self._extract_single_threaded(document_dir, num_papers)
else:
self._extract_mpi(document_dir, num... |
def simulate(self, tower):
"""
Controls simulations and extracts trace
"""
return simulate(tower, self.frames)
def direction(self, initial, final):
""" Determines the direction that the tower falls.
Defined in Battalgia 2013 as the average final
positions of all ... | The code analyzes a tower's stability by simulating its behavior, calculating directional angle and magnitude from initial and final positions, determining instability, and returning these metrics along with the simulation trace in a dictionary. | def analyze(self, tower):
""" Returns the stability statistics for a given tower.
Args:
tower : a `blockworld.towers.Tower`.
Returns:
A `dict` containing several statistics.
"""
# original configuration
trace = self.simulate(tower)
pos = trace[... |
def _sasl_start_jwt(self, conn: Connection) -> Mapping[str, Any]:
access_token = self._get_access_token()
conn.oidc_token_gen_id = self.token_gen_id
cmd = self._get_start_command({"jwt": access_token})
return self._run_command(conn, cmd)
def _is_auth_error(self, err: Exception) -> bool:
... | The function authenticates a machine using a cached access token via SASL. If authentication fails with error code 18, it invalidates the token, fetches a new one, and retries. Other errors are raised to the user. If no cached token exists, it directly attempts SASL authentication. | def _authenticate_machine(self, conn: Connection) -> Mapping[str, Any]:
# If there is a cached access token, try to authenticate with it. If
# authentication fails with error code 18, invalidate the access token,
# fetch a new access token, and try to authenticate again. If authentication
... |
def _sasl_start_jwt(self, conn: Connection) -> Mapping[str, Any]:
access_token = self._get_access_token()
conn.oidc_token_gen_id = self.token_gen_id
cmd = self._get_start_command({"jwt": access_token})
return self._run_command(conn, cmd)
def _is_auth_error(self, err: Exception) -> bool:
... | The function authenticates a user using cached access or refresh tokens via JWT, retrying after invalidating tokens on error code 18. If tokens are absent, it initiates a new SASL authentication flow by requesting IdpInfo and proceeding with JwtStepRequest. | def _authenticate_human(self, conn: Connection) -> Optional[Mapping[str, Any]]:
# If we have a cached access token, try a JwtStepRequest.
# authentication fails with error code 18, invalidate the access token,
# and try to authenticate again. If authentication fails for any other
# reas... |
def _invalidate(self, conn: Connection) -> None:
# Ignore the invalidation if a token gen id is given and is less than our
# current token gen id.
token_gen_id = conn.oidc_token_gen_id or 0
if token_gen_id is not None and token_gen_id < self.token_gen_id:
return
self.... | The main task of the code is to reauthenticate a connection by invalidating its existing token and initiating either machine-based or human-based authentication, depending on the presence of a callback property. The function returns authentication details as a dictionary or None, ensuring secure revalidation of the con... | def reauthenticate(self, conn: Connection) -> Optional[Mapping[str, Any]]:
"""Handle a reauthenticate from the server."""
# Invalidate the token for the connection.
self._invalidate(conn)
# Call the appropriate auth logic for the callback type.
if self.properties.callback:
... |
def get_suggestions(self, account) -> list:
self._suggestions = list(Server.getSuggestions(account));
return self._suggestions;
def refresh(self):
try:
for n in range(3):
if self.read > len(self._suggestions):
print("That's all... for now");
... | This function displays a user menu for interacting with a social media platform, allowing the user to upload moments ('U'), refresh content ('R'), or log out ('Q'). It continuously prompts the user for input, executing corresponding actions like uploading, refreshing, or logging out until the user selects 'Q' to exit. | def prompt_user(self):
option = '';
read = 0;
print('Hello! ', self._accountName, \
', Check what\'s happening right now!', \
'\n-----Press \'U\' to upload your own moments!----',
'\n-----Press \'R\' to refresh the page!----',
'\n-----Press... |
def get_option(self, valid_opts:tuple):
opt = input('Your choice:');
while not opt in valid_opts:
opt = input('Invalid option! Please do it again:');
return opt;
def log_in(self, acc, pwd) -> bool:
if not Server.checkAccounts(acc):
print("No such account!");
... | The code defines a main menu interface for a news application, allowing users to log in, register, or exit. It validates input options and handles actions like authentication, user registration, and debug commands to display server data. The loop continues until the user chooses to quit, ensuring interactive control ov... | def prompt_main(self):
option = '';
while option != '3':
print('======Welcome to daily news!=========', \
'Pick an action:', '1) Log in', '2) Register', \
'3) Quit the program', '(Please call our hotline if \
you want to report a bug or have any problems.\... |
def orgenize_dims(x):
n,h,w,c = x.shape
x = tf.reshape(x, shape=(n,h,c,w))
x = tf.transpose(x,perm = (0,2,1,3))
x = tf.reshape(x, shape = (n, h*w*c))
return x
def train_q_net(self,states, next_states, actions, rewards, dones):
with tf.GradientTape(watch_accessed_variables = False) as tape:
... | The main task of the code is to perform a training iteration for a reinforcement learning agent. It retrieves a minibatch of experiences from the replay memory, processes state dimensions, computes the Q-network loss using current and target states, actions, rewards, and done flags, trains the policy network (mu) to op... | def train(self):
s, a,r, s_tag, dones = self.replay_memory.get_minibatch()
s = orgenize_dims(s)
s_tag = orgenize_dims(s_tag)
q_loss = self.train_q_net(states = s,
next_states = s_tag,
actions=a,
... |
def compute_traj_backbone_states(traj, buffered=True):
"""
Computes the backbone structural states for a single trajectory
"""
phi_angles, psi_angles, res_names, res_ids, atom_names = get_backbone_angles(traj)
n_angles = phi_angles.shape[1]
first_times = np.zeros(n_angles)
last_times = np.z... | The function computes backbone (phi, psi) and sidechain (chi) dihedral angles for a molecular trajectory, concatenates them into a matrix, and returns the combined structural states along with residue identifiers for backbone and sidechain angles. | def compute_all_struc_states(traj, buffered=True):
"""
For a single trajectory, computes both backbone and sidechain dihedrals
and concatenates them into a single matrix. This matrix is the output
"""
#assign states using already existing methods
phi_states, phi_dynstates, psi_states, psi_dynst... |
def compute_traj_backbone_states(traj, buffered=True):
"""
Computes the backbone structural states for a single trajectory
"""
phi_angles, psi_angles, res_names, res_ids, atom_names = get_backbone_angles(traj)
n_angles = phi_angles.shape[1]
first_times = np.zeros(n_angles)
last_times = np.z... | The function computes dynamic states for all dihedral angles (phi, psi, chi) in a molecular trajectory, combining backbone and sidechain states into a single matrix. It returns the concatenated dynamic states matrix, along with atom IDs, time ranges, and the total number of angles, enabling analysis of conformational d... | def compute_all_dihedral_dynStates(traj, buffered=True):
"""
For a single dihedral, computes the disordered states for all dihedrals.
"""
#obtain all states and methods
phi_states, phi_dynstates, psi_states, psi_dynstates = compute_traj_backbone_states(traj, buffered)
phi, psi, names, phi_ids, ... |
def collect_all_dihedral_struc_states(trajlist, buffered=True, prot_name="blact_prot_masses.pdb"):
"""
Given a list of ALL the trajectory files to load, this method loads
in each trajectories structural states for ALL dihedrals over time (as
individual matrices).
The final output is a list where ... | This function processes multiple simulation trajectories to compute and assign dynamic states (ordered/disordered) based on dihedral angles. It calculates average ordered/disordered times across trajectories, then uses these thresholds to classify each trajectory's states, returning dynamic states, phi, and chi dihedra... | def collect_allTrajs_DynStates(trajlist, prot_name, buffered=True):
"""
Given the list of all simulation trajectory files, this method computes
the disordered states for all of them and collects them into a single
list object.
"""
#Given the number of structural state matrices
n_trajs = ... |
def get_first_free_drive():
"""
Get the first available drive letter that is not being used on this computer
Returns
-------
first_free : str
The first free drive letter that should be safe to use with colon
appended
"""
if sys.platform == "win32":
first_free = get_f... | The code initializes a session manager by configuring database and network drive settings, logging parameters, and session tracking variables. It sets up paths, drive letters, user information, and generates a unique session ID. Logging verbosity levels determine output detail, and Windows-specific drive checks are per... | def __init__(self, config, verbosity=0, user=None):
"""
Parameters
----------
config : dict
verbosity : int
-1: 'ERROR', 0: ' WARN', 1: ' INFO', 2: 'DEBUG'
user : str
The user to attach to this record
"""
self.log_text = ""
... |
def log(self, to_print, this_verbosity):
"""
Log a message to the console, only printing if the given verbosity is
equal to or lower than the global threshold. Also save it in this
instance's ``log_text`` attribute (regardless of verbosity)
Parameters
----------
... | The main task of the code is to mount a network share containing a database to a local drive letter on Windows or macOS, using the server's IP address instead of a domain name due to Windows limitations. It checks for existing mounts, reuses them if available, and constructs platform-specific commands with credentials ... | def mount_network_share(self, mount_point=None):
"""
Mount the path containing the database to the first free drive letter
found using Windows `cmd`. Due to some Windows limitations,
this requires looking up the server's IP address
and mounting using the IP rather than the actual... |
def check_exit_queue(self, thread_queue, exit_queue):
"""
Check to see if a queue (``exit_queue``) has anything in it. If so,
immediately exit.
Parameters
----------
thread_queue : queue.Queue
exit_queue : queue.Queue
"""
if exit_queue is not None... | The main task of the code is to unmount a network share holding the database during teardown. It updates a thread queue with progress/status, logs operations, handles errors by capturing exceptions, and returns a boolean indicating success/failure. The core action is calling `umount_network_share()` after notifying the... | def db_logger_teardown(self, thread_queue=None, exit_queue=None):
"""
teardown routine
1) unmount network share.
"""
try:
if thread_queue:
thread_queue.put(('Unmounting the database network share',
self.progress_num))... |
def log(self, to_print, this_verbosity):
"""
Log a message to the console, only printing if the given verbosity is
equal to or lower than the global threshold. Also save it in this
instance's ``log_text`` attribute (regardless of verbosity)
Parameters
----------
... | The main task of the code is to configure a database logger by mounting a network share, verifying the database's existence, and retrieving instrument information (PID, schema name). It logs progress, handles errors via thread queues, and returns True on success or False if any step fails, such as missing files or data... | def db_logger_setup(self, thread_queue=None, exit_queue=None):
"""
setup routine:
1) mount network share.
2) check db exists.
3) get instrument info (pid, schema name).
"""
self.log('username is {}'.format(self.user), 1)
self.log('computer name is {}'.for... |
def convert_free_var(self):
'''Convert free variables to nonnegative variables.'''
for i, domain in list(enumerate(self.domain))[::-1]:
if domain == 'R':
self.tableau = np.hstack([
self.tableau[:, :(i+1)],
-self.tableau[:, [i]],
... | The main task of the code is to canonicalize a linear programming problem by converting free variables to nonnegative variables, transforming inequalities into equalities using slack/surplus variables, adjusting equations with negative right-hand side coefficients, and adding artificial variables if needed for Phase I.... | def canonize(self):
'''Canonize the linear programming problem.'''
# (1) Free variables
# Convert 'R' variables to difference of '>=0' variables
print(self.tab + 'Converting free variables to nonnegative variables...', end='')
self.convert_free_var()
print(' Done.')
... |
def move_problem(self):
'''Move the problem due to initial solution.'''
# Move the tableau values
for i in range(self.tableau.shape[0]):
self.tableau[i, -1] -= np.dot(self.tableau[i, :-1], self.initial_solution)
for i, var in enumerate(self.domain):
if var == '>=0... | The code optimizes a linear programming problem using the simplex algorithm. It first checks for an initial solution, moves the problem if needed, canonizes the problem into standard form, applies the simplex method, and adjusts the final solution by adding the initial solution if provided. The process includes status ... | def optimize(self):
'''Optimize the linear programming problem.'''
if self.initial_solution is not None:
print(self.tab + 'Moving the linear programming problem due to the initial solution...', end='')
self.move_problem()
print(' Done')
print(self.tab + 'Canon... |
def get(obj: str, name: str = None, namespace: str = None,
labels: str = None, all_namespaces: bool = False, ) -> dict:
"""Get or list resource(s) (similar to 'kubectl get')
:param obj: resource type
:param name: resource name
:param namespace: namespace
:param labels: kubernetes labels
... | This function creates or updates a Kubernetes resource (like 'kubectl apply') by checking if the resource exists using 'get'. If it doesn't exist, it calls 'create'; otherwise, it applies a 'patch'. The 'dry_run' parameter allows simulating the operation without making changes. The function returns JSON data similar to... | def apply(body: dict, dry_run: bool = False) -> dict:
"""Create/Update a resource (similar to 'kubectl apply')
:param body: kubenetes manifest data in JSON format
:param dry_run: dry-run
:returns: data similar to 'kubectl apply' in JSON format"""
name = body['metadata']['name']
namespace = body[... |
def _find_container(name: str, namespace: str, container: str = None):
api = kubernetes.client.CoreV1Api()
containers = []
resp = api.read_namespaced_pod(name=name, namespace=namespace).to_dict()
if resp['spec']['containers']:
containers += [ctn['name'] for ctn in resp['spec']['containers']]
... | This function copies files/directories between a local system and a Kubernetes pod (or within pods), ensuring one source/destination is local and the other remote. It uses Kubernetes API to execute 'tar' commands, stream data, and handle directory structures, returning a boolean indicating success. Raises exceptions fo... | def cp(source: str, destination: str,
namespace: str = None, container: str = None) -> bool:
"""Copy a file/directory from/to a pod (similar to 'kubectl cp')
:param source: source (pod:path if remote)
:param destination: destination (pod:path if remote)
:param namespace: namespace
:param cont... |
def load_dataset(filename, delimiter=','):
""" Load dataset formatted in a .csv file.
Parameters
----------
filename : str
Absolute path to data file.
delimiter : str
Type of delimiter that separates data columns; typically space (' ') or comma (',').
... | The function performs multi-class classification using various models on provided datasets, applying preprocessing, dimensionality reduction (PCA), and evaluating metrics like accuracy, F1 score, and ROC AUC. It iterates through classifiers, computes results, optionally visualizes predictions on an image, and saves out... | def classify(filename_dict, params, preprocess_type, dataset_params, pca_params=None, downsample=True,
use_validation=False, verbose=False, save=False):
""" Perform classification with all selected models.
Parameters
----------
filename_dict : dict
Dictionary with t... |
def confirmIntersection(var, array): #Check for an intersection between passed variable and array, then return boolean result.
if var in array: #If statement to check for true result
return True
else:
return False
def failedIntersection(var, array, var_name, array_name): #See summary below regar... | The function `solutionsImporter` imports platform-specific solution arrays (apple, android, windows) based on the input variable `var`. It first checks if `var` intersects with `array`; if not, it triggers an error and retries. If valid, it selects the corresponding module's `solutions()` method, returns the array for ... | def solutionsImporter(var, array, var_name, array_name): #See summary below regarding passed parameters
int_cond = confirmIntersection(var, array) ##START of Second and last intersection check prior to setting the solutions array
if int_cond == False:
failedIntersection(var, array, var_name, array_name)... |
def init():
#Define and Setup Modules
warnings.filterwarnings("ignore") #Disables Python warnings within the Python CLI. Disable for debugging.
ID = generic.generateID() #Calls the generateID function from the custom generic module. See module for further information.
#Initial Main Menu Interface
pr... | The main task of the code is to process a user's device issue query by initializing system modules, identifying the brand and issue type via selection functions, retrieving relevant solutions, and generating responses. It formats input, uses selectors to determine brand/issue, imports brand-specific solutions, and call... | def Main():
ID = init() #Sets the ID variable based on the returned variable from the init() sub procedure. While also setting up other modules and providing a CLI in the process.
print("Case Number: {0}".format(ID)) #Print the Case ID, using a built-in format function.
query = str(input("Enter your query: ... |
def main(model, dataset, train_pairs, qrels_train, valid_run, qrels_valid, model_out_dir=None):
'''
Runs the training loop, controlled by the constants above
Args:
model(torch.nn.model or str): One of the models in modelling.py,
or one of the keys of MODEL_MAP.
da... | The code trains and evaluates a GNN-based ranking model (GNNRanker) on the Robust dataset using cross-validation. It loads pre-trained weights, processes query/document data, trains the model on fold-specific pairs, validates, and tests using TREC P@20 metrics. Results are saved as runs and evaluated for average P@20 p... | def main_cli():
parser = argparse.ArgumentParser('LGRe training and validation')
parser.add_argument('--fold', type=int, help='an integer for the flod')
args = parser.parse_args()
model = MODEL_MAP["GNNRanker"]()
model.return_rep = True
fold = args.fold #1 2 3 4 5
model.load(os.path.join("c... |
def user_choice():
print("Our options are as follows:" + "\n")
print("1. United States locations.")
print("2. Locations from Around the World.")
print("3. Random Location.")
def choice_option():
while True:
try:
user_option = input("Which option would you like to choose?" +... | The code's main task is to prompt the user whether they want to retrieve weather data for another location or exit. It loops indefinitely, checking the user's input: if 'y', it recursively calls functions to process the new request; if 'n' or 'd', it terminates with a farewell message. Invalid inputs trigger error hand... | def run_again():
while True:
try:
more_weather = input("Would you like to get information about a different location?" + "\n")
# Runs the program again if the user chooses so
if more_weather[0].lower() == 'y':
user_choice()
... |
def intro():
print("Hello, welcome to the Wonderful Weather App!")
print("We are currently offering weather details using zipcodes or city/state combinations within the United States.")
print("As well as weather information from around the globe, using a city and country combination.")
print("Example: L... | The main task of the code is to orchestrate a program flow by introducing the user, handling their choices, executing selected options, and determining if the program should run again. It utilizes global variables (zippy, city, state) for data persistence across functions and sequentially calls `intro()`, `user_choice(... | def main():
global zippy
global city
global state
intro()
user_choice()
choice_option()
run_again() |
def draw_detections(self, frame, detections):
for roi, attribute in zip(*detections[0]):
self.draw_detection_roi(frame, roi, attribute)
for roi, license in zip(*detections[1]):
self.draw_licence_detection_roi(frame, roi, license)
def display_interactive_window(self, frame):
... | This method processes video streams by reading frames from input, applying center cropping if specified, detecting objects using a frame processor, drawing detection results, writing processed frames to output, and optionally displaying them interactively. It also tracks FPS and frame count, terminating when input ends... | def process(self, input_stream, output_stream):
self.input_stream = input_stream
self.output_stream = output_stream
while self.input_stream.isOpened():
has_frame, frame = self.input_stream.read()
if not has_frame:
break
if self.input_crop is n... |
def moveToRight(self,r,c,moves):
if r >= 0 and c-1 >= 0 and r < self.col_row and c-1 < self.col_row:
move = self.indexMove((r, c-1), (r, c)), 'Right'
moves.append(move)
def moveToLeft(self,r,c,moves):
if r >= 0 and c+1 >= 0 and r < self.col_row and c+1 < self.col_row:
... | This function generates all possible moves for the zero tile in a puzzle by checking right, left, up, and down directions from its current position, appending valid moves to a list which is then returned. | def actions2(self):
moves = []
#r,c=self.get0Index(self.array)
co=self.zeroindex
self.moveToRight(co[0],co[1],moves)
self.moveToLeft(co[0],co[1],moves)
self.moveToUP(co[0],co[1],moves)
self.moveToDown(co[0],co[1],moves)
return moves |
def is_gameset(self):
if self.blank_count<=0:
return True
if self.two_pass_count==2:
return True
if self.blank_count*self.white_count==0:
return True
return False
def one_turn(self,player='human'):
assert player=='human' or player=='com', "the ... | The code manages a game loop that repeatedly displays the board, shows player counts, indicates the current turn, and allows the current player to take their turn until the game ends. It cycles through players, increments the turn counter, and finalizes the game state upon completion. | def play(self):
turn_num=0
while not self.is_gameset():
super().show_board()
print(f"●: {self.black_count}, ○: {self.white_count}")
print(f"turn: {'○' if self.turn==1 else '●'}")
self.one_turn(player=self.__player_list[turn_num%2])
turn_num+=1
... |
def can_put(self,col,row):
if not self.is_in_board(col,row):
return False
if self.board_arr[row][col]!=blank:
return False
if not self.can_reverse(col,row):
return False
return True
def reverse_stones(self,col,row):
for d in self.__directions:
... | The main task of the code is to place a stone on the board at the specified position if valid, update stone counts, reverse opponent's stones, switch turns, and return True for success or False for invalid moves. | def put_stone(self,col,row):
if self.can_put(col,row):
self.board_arr[row,col]=self.turn
if self.turn==-1: self.black_count+=1
else: self.white_count+=1
self.blank_count-=1
self.reverse_stones(col,row)
self.turn_change()
return ... |
def create_folder():
folder_name = 'output'
exists = os.path.exists(folder_name)
if not exists:
os.makedirs(folder_name)
print(f'folder {folder_name} is created')
def histogram(source_img):
# img = cv2.imread(source_img_path)
b_channel ,g_channel, r_channel = cv2.split(source_img)
... | The main task of the code is to perform image encryption and decryption using a key, compute histograms of the image channels, evaluate encryption quality via PSNR, MSE, NPCR, and UACI metrics, and store results in a text file. It reads an image, splits its BGR channels, encrypts/decrypts them, reconstructs the decrypt... | def main(image_source,kunci):
create_folder()
# read and save histogram image source
source_img = cv2.imread(image_source)
# bgr
b_channel,g_channel,r_channel = histogram(source_img)
# enkripsi and dekripsi
r_channel_encrypted,g_channel_encrypted,b_channel_encrypted,encrypted_img = enkripsi... |
def classify_train_data(self):
for i, target in enumerate(self.XTrain):
if self.yTrain[i] not in self.classes:
self.classes[self.yTrain[i]] = list()
self.classes[self.yTrain[i]].append(target)
def handle_features(self, class_data):
temp = list()
for i in ... | The code trains a Naive Bayes classifier by storing training data, computing class probabilities, and calculating feature statistics (count, mean, standard deviation) for each class. It organizes results in dictionaries and prints class probabilities and feature distributions for model readiness. | def fit(self, XTrain=None, yTrain=None):
self.XTrain = XTrain
self.yTrain = yTrain
self.trained = dict()
self.classes = dict()
self.classify_train_data()
for key, value in self.classes.items():
self.trained[key] = self.handle_features(value)
print("N... |
def __get_gateway_id(self, gateway_uuid):
"""
Private function that gets the database row table id for the gateway that
is needed for further filtering in this class, given the gateway's UUI
(MAC address)
:param gateway_uuid: The UUID of the module (MAC address) to search the ID... | This function processes sensor module messages by validating and inserting sensor data into a database. It checks if the gateway and sensor module exist, adds them if necessary, and stores the measurement with the provided or current timestamp. It returns success or error status along with descriptive messages. | def process_sensor_module_message(self, module_uuid, gateway_uuid, sensor_type, value, timestamp):
"""
The main message processing function of this class that should be called
by the front end receiving the raw messages.
It bundles the ID lookup functions into a complete message parsing ... |
def get_vectors(self, sessions):
vectors = []
for s in sessions:
features_dict = self.calculate_features_dict(s)
vector = np.zeros(len(self.features))
for i in range(len(self.features)):
vector[i] = features_dict.get(self.features[i], 0.0)
... | This code processes input sessions by extracting feature vectors, normalizing them, handling categorical features via one-hot encoding, and concatenating all transformed features into a unified matrix for machine learning tasks. | def fit_transform(self, sessions):
X = self.get_vectors(sessions)
self.mean = X.mean(axis=0)
self.std = X.std(axis=0)
self.std[self.std == 0] = 0.01
if self.normalize:
X = self._normalize(X)
if len(self.categorical_features) > 0:
cat_vectors = self... |
def get_vectors(self, sessions):
vectors = []
for s in sessions:
features_dict = self.calculate_features_dict(s)
vector = np.zeros(len(self.features))
for i in range(len(self.features)):
vector[i] = features_dict.get(self.features[i], 0.0)
... | The code transforms session data into a feature matrix by extracting vectors, applying normalization if enabled, encoding categorical features if present, and concatenating them with the original vectors to produce a combined feature representation. | def transform(self, sessions):
X = self.get_vectors(sessions)
if self.normalize:
X = self._normalize(X)
if len(self.categorical_features) > 0:
X_cat = self.encoder.transform(self.get_categorical_vectors(sessions))
X = np.concatenate((X, X_cat), axis=1)
... |
def _open_input_stream(path):
"""Returns an open stream for iterating over lines in the given path.
Args:
path (str): url or local file path
Return:
iter: iterator over file handle
"""
if not isinstance(path, basestring):
raise ValueError("Unexpected path type: %s" % type(pa... | This function converts an OBO ontology file to a TSV table, optionally filtering terms by a specified root ID and adding a 'category' column for top-level categories. It reads the input OBO file, processes records, computes statistics, and writes the TSV output to a file or standard output. | def convert_obo_to_tsv(input_path, output_path=None, root_id=None, add_category_column=False):
"""Main entry point for parsing an .obo file and converting it to a .tsv table.
Args:
input_path (str): .obo file url or local file path
output_path (str): path where to write the .tsv file. Defaults ... |
def stat_from_id(self, _id):
if _id in range(1, 7):
return self.get_stats()[('strengthMod', 'dexterityMod', 'constitutionMod',
'intelligenceMod', 'wisdomMod', 'charismaMod')[_id - 1]]
return 0
def pact_slots_by_level(level):
return {
1: 1,
... | The code generates a spellbook for a character by calculating spell slots, spell DC, and attack bonus based on class levels and abilities, then compiling all learned spells into a structured dictionary. | def get_spellbook(self):
if self.character is None: raise Exception('You must call get_character() first.')
spellbook = {'spellslots': {},
'spells': [],
'dc': 0,
'attackBonus': 0}
spellcasterLevel = 0
castingClasses = 0
... |
def get_stats(self):
"""Returns a dict of stats."""
if self.character is None: raise Exception('You must call get_character() first.')
if self.stats: return self.stats
character = self.character
stats = {"strength": 10, "dexterity": 10, "constitution": 10,
"wisdo... | The code compiles a character sheet dictionary containing attributes, calculated values (like HP and armor), skills, resistances, spellbook data, and metadata. It aggregates stats, levels, and derived properties into a structured format, ensuring required data is fetched first. The result includes versioning, race/back... | def get_sheet(self):
"""Returns a dict with character sheet data."""
if self.character is None: raise Exception('You must call get_character() first.')
character = self.character
stats = self.get_stats()
levels = self.get_levels()
hp = character['overrideHitPoints'] or \... |
def get_stats(self):
"""Returns a dict of stats."""
if self.character is None: raise Exception('You must call get_character() first.')
if self.stats: return self.stats
character = self.character
stats = {"strength": 10, "dexterity": 10, "constitution": 10,
"wisdo... | This function calculates attack statistics (bonus and damage) for various attack types like actions, custom actions, items, and unarmed strikes, using character stats, item properties, and game rules. It returns a structured list of dictionaries containing attack details like name, bonus, damage, and description, handl... | def get_attack(self, atkIn, atkType):
"""Calculates and returns a list of dicts."""
if self.character is None: raise Exception('You must call get_character() first.')
stats = self.get_stats()
prof = stats['proficiencyBonus']
out = []
attack = {
'attackBonus': ... |
def add_custom_objects_spec(spec):
with open(CUSTOM_OBJECTS_SPEC_PATH, 'r') as custom_objects_spec_file:
custom_objects_spec = json.loads(custom_objects_spec_file.read())
for path in custom_objects_spec.keys():
if path not in spec['paths'].keys():
spec['paths'][path] = custom_objects... | The function processes a Swagger specification by adding custom objects, stripping tags from operation IDs, removing watch operations, eliminating model prefixes like 'io.k8s', and inlining primitive models based on the specified client language, ultimately returning the transformed spec for client compatibility. | def process_swagger(spec, client_language):
spec = add_custom_objects_spec(spec)
apply_func_to_spec_operations(spec, strip_tags_from_operation_id)
operation_ids = {}
apply_func_to_spec_operations(spec, lambda op, _: operator.setitem(
operation_ids, op['operationId'], op))
try:
app... |
def process_swagger(spec, client_language):
spec = add_custom_objects_spec(spec)
apply_func_to_spec_operations(spec, strip_tags_from_operation_id)
operation_ids = {}
apply_func_to_spec_operations(spec, lambda op, _: operator.setitem(
operation_ids, op['operationId'], op))
try:
app... | The code downloads an OpenShift API Swagger specification from a GitHub URL, processes it using custom functions to modify the spec and update a code generation ignore file, then saves the transformed JSON to a specified output file. It uses command-line arguments for version and output path, handles HTTP requests, and... | def openshift_main():
import sys
import json
import codecs
import urllib3
from collections import OrderedDict
pool = urllib3.PoolManager()
reader = codecs.getreader('utf-8')
spec_url = 'https://raw.githubusercontent.com/openshift/origin/' \
'%s/api/swagger-spec/openshift-... |
def _check(self):
"""
Validates the input data.
Returns:
bool: True if the data is valid, False otherwise.
"""
if self.filedata == None:
self.filedata = self.readFile()
data = self.filedata
data = [list(map(int, line.split())) for line in data... | This method checks data validity, converts valid data to binary, and writes it to a new file. It uses _check() to validate data, _binary() for conversion, and _2_newfile() for saving. If validation fails, no action is taken. The new file's name is provided as input, excluding the extension. | def _2_newfile_with_check(self, newfilename='outlab5'):
"""
Checks the data, converts it to binary, and writes it to a new file if the data is valid.
Args:
newfilename (str): The name of the new file (without extension).
"""
filename = newfilename
bools = self._c... |
def deal_downloading_torrent(self):
temp_data = Source.find_by_status(session=SessionLocal(), status="DOWNLOADING_TORRENT")
if temp_data:
for torrent in temp_data:
self.check_torrent(data=torrent)
def deal_send_encode(self):
temp_data = File.find_by_status(session=Ses... | The main task of the code is to process torrent files through a sequence of operations: handling downloading torrents, sending data for encoding, performing encoding tasks, uploading processed data, and finalizing the source. This workflow manages torrent lifecycle stages from download to completion, ensuring proper en... | def get_torrents(self):
self.deal_downloading_torrent()
self.deal_send_encode()
self.deal_encoding()
self.deal_upload()
self.handle_finish_source() |
def run_with_python(args, is_interactive):
delim = rbql.normalize_delim(args.delim) if args.delim is not None else '\t'
policy = args.policy if args.policy is not None else get_default_policy(delim)
query = args.query
convert_only = args.convert_only
input_path = args.input
output_path = args.ou... | This function runs an interactive loop where users input SQL-like RBQL queries. It processes each query using `run_with_python`, displays a preview of the output table if successful, and exits after the first successful execution. The loop handles empty input (Ctrl-D) to break gracefully. | def run_interactive_loop(args):
while True:
print('\nInput SQL-like RBQL query and press Enter:')
sys.stdout.write('> ')
sys.stdout.flush()
query = sys.stdin.readline()
if not len(query):
print()
break # Ctrl-D
query = query.strip()
arg... |
def show_error(msg, is_interactive):
if is_interactive:
full_msg = '{}Error:{} {}'.format(u'\u001b[31;1m', u'\u001b[0m', msg)
print(full_msg)
else:
eprint('Error: ' + msg)
def get_default_policy(delim):
if delim in [';', ',']:
return 'quoted'
elif delim == ' ':
re... | The function `start_preview_mode` previews a table's data by detecting or using a specified delimiter, sampling records, and displaying a formatted preview. It handles errors like missing input or undetectable delimiters, warns about quoting issues, sets default output paths if unspecified, and initiates an interactive... | def start_preview_mode(args):
input_path = args.input
if not input_path:
show_error('Input file must be provided in interactive mode. You can use stdin input only in non-interactive mode', is_interactive=True)
return
if args.delim is not None:
delim = rbql.normalize_delim(args.delim)... |
def find_schema_idx(db_seq, table_items, column_items, new_mapping, init_idx=0):
seq_lst = db_seq.split(" ")
special_token = ["|", ':', ',', 'schema:', '(', ')']
table_idx_lst = []
column_idx_lst = []
schema_items = [item.lower() for item in table_items + column_items]
schema_elements = " ".join... | The function generates a subword-level matrix representing relationships between database schema elements (tables/columns) using a tokenizer. It maps schema items to subword tokens, constructs a matrix where each entry corresponds to relationships between these subwords, and returns the matrix along with mappings, proc... | def schema_subword_matrix(db_sep, init_idx, tables, tokenizer, table_items=None, column_items=None, new_mapping=None):
schema_items = table_items + column_items
struct_in = "schema: {} | *".format(db_sep)
# normalize struct_in:
struct_in = re.sub(' +', ' ', struct_in)
table_idx_lst, column_idx_lst,... |
def get_token():
auth_string = client_id + ':' + client_secret
auth_bytes = auth_string.encode('utf-8')
auth_base64 = str(base64.b64encode(auth_bytes), 'utf-8')
url = 'https://accounts.spotify.com/api/token'
headers = {
'Authorization': 'Basic ' + auth_base64,
'Content-Type': 'appli... | The main task of the code is to retrieve Spotify data based on a search query and type. For 'artist' searches, it fetches top tracks, albums, and related artists; for 'track' searches, it retrieves specific track details. The function returns structured data or None if no results are found. | def get_spotify_data(search_query, search_type):
token = get_token()
if search_type == 'artist':
result = search_for_artist(token, search_query)
if result:
artist_id = result['id']
top_tracks = get_songs_by_artist(token, artist_id)
albums = get_albums_by_arti... |
def set_seed(args):
random.seed(args.seed)
np.random.seed(args.seed)
torch.manual_seed(args.seed)
if args.n_gpu > 0:
torch.cuda.manual_seed_all(args.seed)
def simple_accuracy(preds, labels):
preds[preds >= 0.5] = 1
preds[preds < 0.5] = 0
avg_p, avg_r, avg_f1, _ = precision_recall_fsc... | The code trains a model using a specified dataset, optimizer, and scheduler. It configures batch sizes, handles multi-GPU training, initializes AdamW with linear warmup/decay, supports mixed precision (fp16), and performs gradient accumulation. The loop computes loss, updates weights, logs metrics, saves checkpoints, a... | def train(args, train_dataset, model, tokenizer):
""" Train the model """
args.train_batch_size = args.per_gpu_train_batch_size * max(1, args.n_gpu)
train_sampler = RandomSampler(train_dataset)
train_dataloader = DataLoader(train_dataset, sampler=train_sampler, batch_size=args.train_batch_size)
if ... |
def set_seed(args):
random.seed(args.seed)
np.random.seed(args.seed)
torch.manual_seed(args.seed)
if args.n_gpu > 0:
torch.cuda.manual_seed_all(args.seed)
def load_and_cache_examples(args, task, tokenizer, evaluate=False, test=False):
processor = processors[task](args.encode_type)
# Load... | The code defines a training and evaluation pipeline for a machine learning model. It parses command-line arguments for model configuration, data paths, and training parameters. The script loads a pre-trained model, prepares data, and performs training, evaluation, or prediction based on flags. It supports multiple mode... | def main():
parser = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
"--encode_type",
default=None,
type=str,
required=True,
help="",
)
parser.add_argument(
"--data_dir",
default=None,
type=str,
required=Tr... |
def read_json(self):
f = open(self.path, 'rb')
page_json = json.load(f)
self.raw_content = page_json['content']
ind = page_json['url'].find("#")
if ind != -1:
self.url = page_json['url'][:ind]
else:
self.url = page_json['url']
self.encoding... | The code processes JSON data by reading, extracting words, standardizing them, handling special tags if needed, and outputting results to a specified file path, while catching and reporting errors during execution. | def run(self, output_path_prefix: str, output_file_name: str):
try:
self.read_json()
self.extract_word()
if not self.standardize_words():
self.handle_special_tags()
self.output(output_path_prefix, output_file_name)
except Exception:
... |
def lambdaDotValue(lam, betapH, alphaH):
return lambdaDotConst3 \
* (3 * s.twoRh * alphaH + betapH**2 \
+ 3 * rh2 \
* (lambdaDotConst1 + lam * (lambdaDotConst2 + rh2 * lam)))
def betaDotValue(lam, beta, dbeta, betap, alpha):
betaDot = beta.copy()
betaDot[... | The code implements a fourth-order Runge-Kutta (RK4) method to numerically solve a system of differential equations. It updates the variables `lam`, `beta`, and their derivatives (`dbeta`) using intermediate stages (l1-l4, b1-b4) computed with weighted averages of the state variables and their time derivatives. The fin... | def RungeKutte4(lam, beta, dbeta, betap, alpha):
l1 = dt * lambdaDotValue(lam, betap[-1], alpha[-1])
b1 = dt * betaDotValue(lam, beta, dbeta, betap, alpha)
tempLam = lam + l1 / 2
tempBeta = beta + b1 / 2
tempDbeta = dot(i.D, tempBeta)
l2 = dt * lambdaDot(tempLam, tempBeta, tempDbeta)
b2 = dt... |
def lambdaDotValue(lam, betapH, alphaH):
return lambdaDotConst3 \
* (3 * s.twoRh * alphaH + betapH**2 \
+ 3 * rh2 \
* (lambdaDotConst1 + lam * (lambdaDotConst2 + rh2 * lam)))
def betaDotValue(lam, beta, dbeta, betap, alpha):
betaDot = beta.copy()
betaDot[... | This function implements the 4th-order Adams-Bashforth multistep method for numerical integration. It updates state variables lam, beta, and dbeta using previous derivative values (lambdaDot, betaDot) shifted in a circular buffer. For the first three steps, it uses Runge-Kutta 4 (RK4) for initialization. Subsequently, ... | def AdamsBashforth4(lam, beta, dbeta, betap, alpha):
AdamsBashforth4.lambdaDot[-3] = AdamsBashforth4.lambdaDot[-2]
AdamsBashforth4.lambdaDot[-2] = AdamsBashforth4.lambdaDot[-1]
AdamsBashforth4.lambdaDot[-1] = AdamsBashforth4.lambdaDot[0]
AdamsBashforth4.lambdaDot[0] = lambdaDotValue(lam, betap[-1], alph... |
def lambdaDotValue(lam, betapH, alphaH):
return lambdaDotConst3 \
* (3 * s.twoRh * alphaH + betapH**2 \
+ 3 * rh2 \
* (lambdaDotConst1 + lam * (lambdaDotConst2 + rh2 * lam)))
def betaDotValue(lam, beta, dbeta, betap, alpha):
betaDot = beta.copy()
betaDot[... | This function implements the Adams-Moulton three-step implicit method for numerical integration. It updates lambda and beta derivatives using shifted arrays, applies Runge-Kutta 4 for initial steps, and computes next-state values using weighted sums of previous derivative estimates. The method combines predictor-correc... | def AdamsMoulton3(lam, beta, dbeta, betap, alpha):
AdamsMoulton3.lambdaDot[-3] = AdamsMoulton3.lambdaDot[-2]
AdamsMoulton3.lambdaDot[-2] = AdamsMoulton3.lambdaDot[-1]
AdamsMoulton3.lambdaDot[-1] = AdamsMoulton3.lambdaDot[0]
AdamsMoulton3.lambdaDot[0] = lambdaDotValue(lam, betap[-1], alpha[-1])
Adams... |
def proposeForcedStep(pos,stepsize,T):
'''
Takes in an array of particle positions of size (N,2), generates
displacements according to parameter stepsize in the direction given
by the force on the particle, another stochastic step, and projects
the new positions back into the circl... | The code simulates the movement of N charged particles using a simulated annealing approach. It initializes particles on a circular path, iteratively proposes new positions, and accepts/rejects them based on temperature (T) and a cooling schedule (T *= 0.95). The process tracks particle positions over iterations and vi... | def main():
# parameters
N = 22 #charges
iterations = 50
T = np.e**10 #temperature
T0=T
r = 0.01
history = np.empty((iterations,N,2))
# set initial positions of particles as circle of radius r
pos = np.array([[r*np.cos(2*k*pi/N),r*np.sin(2*k*pi/N)] for k in range(N)])
h... |
def insrtButton(red, green, blue, text, rect, xCord, yCord):
white = (255, 255, 255)
incolor = (red, green, blue)
font = pygame.font.SysFont('Arial', 30)
pygame.draw.rect(screen, incolor, rect)
screen.blit(font.render(text, True, white), (xCord, yCord))
def chooseSong():
click = False
runnin... | This code displays a menu with two buttons ("Play song" and "Free Play") using Pygame. It detects mouse hover and left-click events to trigger corresponding game modes (chooseSong() or freeGame()), handles quit/escape commands, and continuously updates the screen with the "Pyano" title and background image. | def menu():
click = False
while True:
screen.blit(pyth_img, (0, 0))
screen.blit(pygame.font.SysFont('Arial', 70).render("Pyano", True, (0, 0, 0)), (300, 100))
mouseX, mouseY = pygame.mouse.get_pos()
buttonSong = pygame.Rect(300, 450, 150, 35)
insrtButton(51, 208, 255, "P... |
def analyzeRepo(repo,num_contributors,num_commits = None):
contribtors = sendRequest(repo['contributors_url'],perPage = num_contributors)
names = []
ids = []
logging.info("There are " + str(len(contribtors)) + " Contributors")
for contributor in contribtors:
name = sendRequest(contributor['u... | The main task of the code is to analyze the RxJava GitHub repository by filtering commits, identifying those containing program elements, and saving the processed commit data to a text file and a pickle file for further analysis. | def test():
#shutil.rmtree('./RxJava')
#repoName = "fizzerle/TISSFeedbacktool"
#repoName = "airbnb/lottie-android"
#repoName = "elastic/elasticsearch"
repoName = "ReactiveX/RxJava"
testRepo = {'full_name': repoName.replace('/','-'), 'contributors_url' :'https://api.github.com/repos/'+repoName+'... |
def read_blog(self, path, article_path):
"""Read in blog entries into lists.
Parameters
----------
path : string
Website's path to blog.
article_path
Name of article directory.
Returns
-------
entries : list of dict
List of ... | The main task of the code is to generate a static blog by rendering entries, tags, and date-based pages from source files, creating navigation links, and saving HTML output. It processes blog data, copies assets, renders templates with dynamic options, and ensures proper linking between posts while handling errors duri... | def generate_blog(self, blog):
"""Generate blog."""
import shutil
print('Loading {title} from {path}'.format(**blog))
entries, drafts, others = self.read_blog(
blog['path'], blog['article-path'])
opts = {}
opts['blog_nav'] = self.blog_navigation(blog, entr... |
def create_slider_group(self, rest_or_hyp, range_from=None, range_to=None):
if range_from is None or range_to is None:
x_lower, x_upper = self.plot_pressure.getAxis('bottom').range
range_from = ((x_upper - x_lower) * 0.20) + x_lower
range_to = ((x_upper - x_lower) * 0.25) + x... | This code toggles a button's active state, changes its background color, and triggers creation or destruction of associated UI elements (sliders/markers) based on the button clicked. It then performs calculations with save=True. | def click_button(self, btn):
if btn.slider_active:
btn.slider_active = False
btn.setStyleSheet(f"background-color: 'red'")
else:
btn.slider_active = True
btn.setStyleSheet(f"background-color: 'green'")
if btn is self.button_rest:
self.c... |
def load_cph(filename):
if os.path.exists(filename):
with open(filename, 'rb') as f:
return pickle.load(f)
else:
# Save file not found
return {}
def plot_txtsdyFile(self):
pg.setConfigOptions(antialias=True)
self.GraphicsLayout = pg.Gr... | The main task of the code is to load saved label configurations from a `.cph` file, update UI elements (checkboxes, sliders, markers) with these settings, and adjust data parsing/visualization if parameters change. It retrieves values like `pa`, range, and marker positions, applies them to the UI, and triggers re-parsi... | def load_saved_labels(self):
cph_path = f"{self.TxtSdyFile.studypath}.cph"
saved_cph = self.load_cph(cph_path)
pa = saved_cph.get('pa', True)
range_rest = saved_cph.get('range_rest', None)
range_hyp = saved_cph.get('range_hyp', None)
notch_rest = saved_cph.get('notch_rest... |
def plot_txtsdyFile(self):
pg.setConfigOptions(antialias=True)
self.GraphicsLayout = pg.GraphicsLayout()
self.GraphicsLayout.setSpacing(0)
self.GraphicsLayout.setContentsMargins(0., 0., 0., 0.)
self.graphicsView_.setCentralItem(self.GraphicsLayout)
self.graphicsView_.sho... | This method loads and processes either a .txt or .sdy file by initializing data structures, configuring UI elements with patient metadata, and triggering plotting and calculations. It determines the file type, creates corresponding objects (TxtFile/SDYFile), updates interface components, and handles potential file not ... | def load_txtsdyFile(self):
self.studyFolderPath = None
self.studyData = dict()
self.TxtSdyFile = None
self.calculations = dict()
self.plot_pressure, self.plot_flow, self.plot_pressure_ratios = None, None, None
self.plot_resistances, self.plot_ensemble_rest, self.plot_ens... |
def get_tasks():
data = read_data_set("../predictionFiles/task.csv", ";")
urs_split = split_by_user(data, 1)
split_separate = separate_data(urs_split)
return split_separate
def get_trainers():
data = read_data_set("../predictionFiles/train.csv", ";")
trn_split = split_by_user(data, 1)
trn_se... | The main task of the code is to process training data by reading a CSV file, transforming it twice with label position adjustments, and threading tasks with trainers to connect results, likely for machine learning model training or data processing workflow. | def main():
tasks = get_tasks()
trainers = get_trainers()
train_data = read_data_set("../predictionFiles/train.csv", ";")
train_data_transform_format = transform_data(train_data, label_pos=2)
train_data_transform_format_2 = transform_data(train_data_transform_format, label_pos=3)
threads(tasks=t... |
def read_data_set_cf(input_file, delimiter):
retrieved_data = []
data_in = open(input_file, "r")
for f in data_in:
spl = f.rstrip('\n').split(delimiter)
type_arr = type_changer(spl)
retrieved_data.extend([[x for x in type_arr]])
return retrieved_data
def get_trainers():
data ... | The main task of the code is to train a regression model using features extracted from a movie label dataset, derive parameters for trainers, prepare training data, and predict scores for given tasks. It reads data, processes features, trains models, and writes predicted scores to a submission file. | def main():
labels = read_data_set_cf("../predictionFiles/movie_labels.csv", ";")
train = get_trainers()
tasks = get_tasks()
features_no = 1
users_parameters = get_parameters(train, features_no)
features_arr = get_features(labels, features_no)
data_for_regress = data_to_train(train, features... |
def read_data_set(input_file, delimiter):
retrieved_data = []
data_in = open(input_file, "r")
for f in data_in:
spl = f.rstrip('\n').split(delimiter)
type_arr = type_changer(spl)
retrieved_data.extend([[x for x in type_arr]])
return retrieved_data
def get_trainers():
data = r... | The main task of the code is to process movie label data, configure training tasks, execute them in parallel threads, and aggregate results. It reads labels from a CSV file, determines the maximum genre length, initializes trainers/tasks, runs threaded processing, and connects final outputs. | def main():
global max_labels_len
labels = read_data_set("../predictionFiles/movie_labels.csv", ";")
train = get_trainers()
tasks = get_tasks()
max_labels_len = max_genres_len(labels, label_pos=2)
threads(tasks, train, labels)
connect_results() |
def urlCheck(self):
# Extract the domain with protocol from the provided url
self.domain = urllib.parse.urlparse(self.url).scheme + '://' + urllib.parse.urlparse(self.url).netloc
try:
print("Checking Remote Server Health")
if self.proxies:
ret = requests.get(self.domain, headers=fetchUA(), proxies=fetch... | The code performs security checks (directory traversal, headers, filters, cookies) via threads and executes log poisoning checks. If `attempt_shell` is True, it triggers an autopwn method using results from these checks to attempt shell exploitation, bypassing threading for log poisoning to prevent conflicts. | def Attack(self, attempt_shell=False, mode=0, force=False):
if not force and not self.urlCheck():
return
dirThread = threading.Thread(target=self.dirTraversalCheck, args=[])
dirThread.start()
headerres = threading.Thread(target=self.headerCheck, args=[])
headerres.start()
filterThread = threading.Thread(... |
def generate_date_range(start_date, end_date):
start = datetime.datetime.strptime(start_date, "%m-%d-%Y")
end = datetime.datetime.strptime(end_date, "%m-%d-%Y")
return [start + datetime.timedelta(days=x) for x in range(0, (end - start).days)]
def navigate_to_date(date):
driver.find_element(By.XPATH, '//... | The main task of the code is to scrape NBA betting data from "oddsshark.com" for a specific season (2017-2018), parse game scores and betting odds, and store the extracted data into an SQL database. It automates navigating through dates, checking game availability, extracting relevant information, and persisting result... | def main():
# start_date, end_date = "10-28-2014", "04-16-2015" # 2014-2015 NBA season
# start_date, end_date = "10-27-2015", "04-14-2016" # 2015-2016 NBA season
# start_date, end_date = "10-25-2016", "04-13-2017" # 2016-2017 NBA season
start_date, end_date = "10-17-2017", "04-12-2018" # 2017-2018 N... |
def retrieve_season_info(home_team, away_team, game_date, season):
home_stats = retrieve_stats(home_team, game_date, season, "home")
away_stats = retrieve_stats(away_team, game_date, season, "away")
return home_stats, away_stats
def calculate_recent_four_factors(team, game_date, season):
sql_query_strin... | The main task of the code is to generate training data for machine learning by aggregating season statistics, recent performance metrics, and betting information from NBA game boxscores into a structured database table, enabling predictive modeling of game outcomes. | def create_training_data():
sql_query_string = """SELECT * FROM boxscores;"""
db_cursor.execute(sql_query_string)
boxscores = db_cursor.fetchall()
for game in tqdm(boxscores):
home_season_stats, away_season_stats = retrieve_season_info(game[0], game[3], game[2], game[38])
home_recent_st... |
def get_size(self):
return len(self.agents)
def get_fitness(self, measure="basic", base_fitness=0):
# Fitnesses always should be >0
# Base fitness=0, harsh fitness run
# Base fitness=1, payoffs doesn't matter at all
if measure == "basic":
payoffs = self.get_payoffs()
... | This function regenerates a population by selecting agents based on fitness, randomly replacing some with mutated or copied agents, and resetting their states. It adjusts population size using parameters n/r, applies mutation if specified, and transitions to the next generation. | def regenerate(self, n=None, r=None, base_fitness=0, mutation_rate=0, type="moran"):
if n is None and r is None:
print("No moran death date(r) or number (n) specified. Taking r=0.5")
r=0.5
n = round(self.get_size() * r)
elif not (n is None) and (not r is None):
... |
def key_schedule(key):
key_schedule = [key[0]]
l = [key[1], key[2], key[3]]
for i in range(ROUNDS - 1):
l[i % 3] = ((key_schedule[i] + rot64(l[i % 3], -8)) & MAX64) ^ i
key_i = rot64(key_schedule[i], 3) ^ l[i % 3]
key_schedule.append(key_i)
return key_schedule
def speck_encrypt... | The code implements a Counter (CTR) mode encryption using the Speck block cipher. It processes the plaintext in 2-byte blocks, encrypts a nonce with the key using `speck_encrypt`, XORs the result with the plaintext, increments the nonce, and returns the ciphertext. The `key_schedule` generates subkeys, and `add1` updat... | def speck_ctr(pt, key, nonce):
out = [0] * len(pt)
local_nonce = [nonce[0], nonce[1]]
keys = key_schedule(key)
for i in range(0, len(pt), 2):
pad = speck_encrypt(local_nonce, keys)
out[i] = pt[i] ^ pad[0]
out[i + 1] = pt[i + 1] ^ pad[1]
add1(local_nonce)
return out |
def draw_buttons(self) -> None:
self._WINDOW.fill(BACKGROUND_COLOR)
self._btn_restart.draw(self._WINDOW, font_size=30)
self._btn_quit.draw(self._WINDOW, font_size=30)
def draw_init_fields(self) -> None:
for x in range(10):
for y in range(10):
self._player_fiel... | This method manages a game loop using Pygame, handling user input for restart/quit actions, player/computer field interactions, setup configuration, and win conditions. It returns status messages ('RESTART', 'QUIT', win messages) along with boolean flags, updating the display dynamically while processing events and gam... | def start(self) -> Tuple[str, bool]:
run = True
clock = pygame.time.Clock()
click = False
setup_horizontal = False
while run:
clock.tick(FPS)
mouse_coords = pygame.mouse.get_pos()
if self._btn_restart.is_mouse_over(mouse_coords) and click:
... |
def set_up_pose_detection_model():
mp_drawing = mp.solutions.drawing_utils
mp_drawing_styles = mp.solutions.drawing_styles
mp_pose = mp.solutions.pose
return mp_pose, mp_drawing
def get_video_writer(image_name, video_path):
basename = os.path.basename(video_path)
filename, extension = os.path.sp... | The code processes a video to detect human pose landmarks, calculates joint angles for each frame, tracks the maximum right angle, saves processed frames as images, writes the output video, and returns a list of angles along with the maximum detected angle. | def get_frames_angles(image_name: str, video_path: str) -> tuple:
mp_pose, mp_drawing = set_up_pose_detection_model()
cap = cv2.VideoCapture(video_path)
out = get_video_writer(image_name, video_path)
img_count = 0
output_images = []
frames = []
max_angle_right = 0
with mp_pose.Pose(
... |
def prepare_pair(self,pool=None,mode="train", epoches_size=1,sess=None,model=None):
df = self.data
samples=[]
for user in df["uid"].unique():
pos_items_time_dict=self.user_item_pos_rating_time_dict.get(user,{}) # null
if len(pos_items_time_dict)==0... | This function generates batches of training data by either loading preprocessed samples from a pickle file or preparing new ones. It handles shuffling, processes user/item sequences (including sparse tensors), and yields batches in a format suitable for model training, with variations based on pairwise settings and spa... | def getBatchFromSamples_pair(self,pool=None,dns=True,sess=None,model=None,fresh=True,mode="train", epoches_size=1,shuffle=True):
pickle_name = "tmp/samples_"+ ("dns" +str(self.conf.subset_size)+"_" if dns else "uniform") + ("_pair" if self.conf.pairwise else "") +("_sparse_tensor_" if self.conf.sparse_tensor e... |
def read_fsp_file(self, filename):
with open(filename) as f:
content = f.readlines()
# Extract number of jobs and machines from the second line
header = list(map(int, ' '.join(content[1].split()).split()))
n_jobs, m_machines = header[0], header[1]
# Extract the proc... | (The main task of the code is to perform Bayesian Optimization for a permutation-based scheduling problem using a Gaussian Process. It reads FSP (Flexible Job Shop Scheduling Problem) data, configures a BayesianOptimizer with a PermutationKernel, iterates to find optimal solutions via Upper Confidence Bound (UCB) acqui... | def execute_kalimero(self, file, seed, it=1000, alpha=2.5, kappa=2.5, xi=0.0):
self.n_jobs, self.m_machines, self.p = self.read_fsp_file(file)
target_results = []
points_results = []
# Bounds of each variable
pbounds = self.generate_bounds(self.n_jobs)
# Bayesian Optimi... |
def read_fsp_file(self, filename):
with open(filename) as f:
content = f.readlines()
# Extract number of jobs and machines from the second line
header = list(map(int, ' '.join(content[1].split()).split()))
n_jobs, m_machines = header[0], header[1]
# Extract the proc... | This code performs Bayesian Optimization with a Gaussian Process to minimize a black-box function for scheduling problems. It reads job/machine data, sets variable bounds, initializes a BayesianOptimizer with a permutation kernel, and iteratively suggests parameters to optimize the target function. Results are tracked,... | def execute(self, file, seed, it=1000, rep=0, alpha=2.5, kappa=2.5, xi=0.0):
self.n_jobs, self.m_machines, self.p = self.read_fsp_file(file)
target_results = []
points_results = []
# Bounds of each variable
pbounds = self.generate_bounds(self.n_jobs)
# Bayesian Optimiz... |
def read_fsp_file(self, filename):
with open(filename) as f:
content = f.readlines()
# Extract number of jobs and machines from the second line
header = list(map(int, ' '.join(content[1].split()).split()))
n_jobs, m_machines = header[0], header[1]
# Extract the proc... | This code performs Bayesian Optimization using a Gaussian Process with a permutation kernel to solve a Flexible Job Shop Scheduling Problem (FJSP). It iteratively suggests job permutations, evaluates their makespan via a black-box function, and tracks the best results. The optimization uses Upper Confidence Bound (UCB)... | def execute_enhanced(self, file, seed, it=1000, rep=0, alpha=2.5, kappa=2.5, xi=0.0):
self.n_jobs, self.m_machines, self.p = self.read_fsp_file(file)
target_results = []
points_results = []
# Bounds of each variable
pbounds = self.generate_bounds(self.n_jobs)
# Bayesia... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.