dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def isInterviewFinished(self, interview_uuid):
mysql = self.__getConnAndCursor()
try:
mysql['cursor'].execute(f"SELECT was_finished FROM interviews WHERE id='{interview_uuid}';")
return bool(mysql['cursor'].fetchall()[0]['was_finished'])
except ProgrammingError as e:
... | The function `catchTest` validates `interview_data` structure, checks if an interview is ongoing, and if so, manually backs up the data by saving it to a JSON file in a designated directory. It logs success or errors and returns status codes. | def catchTest(self, interview_data):
"""
interview_data is expected to be a dictionary containg the keys ('tests', 'question_num', 'test_num', 'interviewee_answers', 'interviewee_stats', 'interviewee', 'interview', 'interviewer')
Spected reasponse format:
... |
def getBadResponse(self, msg="Server error, sorry for the inconvenience"):
"""
Used to que an standar error msg with an option to customize the msg
"""
return {
"response":"bad",
"msg":msg
}
def getUserFolder(self, user_id):
if self.isTestToken... | The main task of the code is to save a new user profile by parsing JSON input data, storing it in a JSON file within a user-specific directory, and inserting the profile details into a MySQL database. It handles JSON parsing errors and database insertion errors, logging them and returning appropriate responses. | def saveNewProfile(self, profile_data, user):
try:
profile_data = json.loads(profile_data)
except json.JSONDecodeError as e:
self.logger.log(f"An error ocurred while tying to parse profile values:\n{e}", is_error=True)
return self.getBadResponse()
if list(prof... |
def validateUserId(self, user_id):
if re.match(r"^[\d]+", str(user_id)):
return True
return False
def __getConnAndCursor(self):
"""
returns a dict with a connection object and a cursor with results as dicts
"""
conn = getConnection(self.credentials)
... | This method retrieves unfinished user interviews (was_finished=0) from the database, checks if their cached files exist, deletes entries without valid caches (based on tokenized status and test token availability), and returns a dictionary of valid cached interviews with additional metadata. It validates the user, quer... | def getCatchedInterviews(self, user_id):
"""
Gets all if any unfinished user interviews, if it finds interviews with status (in the DB)
'was_finished=0' but no cached results, then it deletes it
Spected reasponse format:
{cached:[cached_interview_... |
def createInterviewee(self, name, user_id):
"""
Used to create an interviewee with its respectiv folder
"""
mysql = self.__getConnAndCursor()
interviewee_key = self.__hasher.get_hash(name+datetime.today().strftime('%f'))
try:
data_folder = self.getUserFol... | The main task of the code is to create an interview by generating unique keys, validating test inputs, loading test content from files, inserting interview/interviewee records into a database, and returning structured JSON responses with interview details and associated tests. | def createInterview(self, name, tests, user_id, profile, is_tokenized='0'):
"""
Spected reasponse format:
{
interview_key: "the primary key of the interview",
interviewee_key: "the primary key of the interviewee",
tests:[test_content_1,test_content_2...test_co... |
def _make_parser():
def validate_file(p):
path = pathlib.Path(p)
if not path.is_file():
raise argparse.ArgumentTypeError(
f'Manifest file path does not exist: {path}'
)
return p
def validate_unlock(u):
pattern = r'^([a-f0-9]{5}-){4}[a-f... | The main task of the code is to configure and verify access to an AWS Snowball device. It parses command-line arguments, sets up Snowball credentials and an AWS CLI profile, then checks if the SnowballEdge is accessible via the specified IP address, outputting the configuration details if successful. | def main():
parser = _make_parser()
args = parser.parse_args()
snowball_profile, access_key, secret_key = setup_snowball(args.manifest, args.unlock_code, args.ip)
awscli_profile = config_awscli(access_key, secret_key)
if check_snowball_access(awscli_profile, args.ip):
print(f'SnowballEdge ... |
def display_array():
print("\n")
print(array[0] + " | " + array[1] + " | " + array[2] + " 1 | 2 | 3")
print(array[3] + " | " + array[4] + " | " + array[5] + " 4 | 5 | 6")
print(array[6] + " | " + array[7] + " | " + array[8] + " 7 | 8 | 9")
print("\n")
def player(Player):
print(Player... | The main task of the code is to run a game loop where players take turns making moves until the game ends. It displays the game state, checks for win/tie conditions after each move, switches players if the game continues, and announces the winner or a tie once the game concludes. | def Start_game():
# to display the game
display_array()
# This is simplifying the logic of game it give the O we initialize at the beginning the first turn
# than if the game is over and that is by going thru the function we defined that has win/tie
# if the game is not over the switch function wil... |
def pull_envfile(ctx, env, output=None):
output = output if output else '.env'
if os.path.exists(output):
os.unlink(output)
s3_vault_uri = 's3://build.vault'
if env == 'prod':
ctx.run('aws s3 cp {}/.env.prod {}'.format(s3_vault_uri, output))
elif env == 'staging':
ctx.run('aw... | The main task of the code is to deploy a Docker application by pulling an environment file, cloning the 'docker-compose' repository and the specified app repository, then starting the Docker containers using docker-compose. This automation streamlines setting up and running a Dockerized application in a given environme... | def deploy(ctx, env, app):
pull_envfile(ctx, env)
gitclone(ctx, 'docker-compose')
gitclone(ctx, app)
dcup(ctx) |
def get_header(self, table, check_tbl_version=True):
'''
Retrieves a DMS table header. If the table does not exist then it raises an error.
'''
if table not in self.header_cache:
root = self.retrieve_data(DMSREQUEST_HEADER % (
self.admin_url, table), check_tbl... | The function retrieves DMS table data as a list of dictionaries, each representing a row with filtered fields. It applies include/exclude parameters, processes rows using a Python filter expression, and returns structured data with metadata like time, table name, and query duration. | def collect(self, table, check_tbl_version=True, preserve_orig_header=False, include=[], exclude=[], filter=None):
'''
Retrieves the DMS table as a list of dict where a dict represents a row with fields and values.
The `include` parameter provides a list of fields that should be included in the... |
def check_out_of_bounds(x,y=None):
if(y==None): # soft overloading fn
x,y = x[0],x[1]
if x<global_grid_xmin or x>global_grid_xmax or y<global_grid_ymin or y>global_grid_ymax:
return True
return False
def direction_num(direction):
if direction=="north":
dir_num=0
elif d... | This function navigates a player to a new location by calculating the directional difference between current and target positions. It executes forward, left, or right actions based on the angular difference (in 90° increments) between current direction and required movement direction. It validates bounds, confirms succ... | def action_implementation(new_loc):
"performs action to go to the new location"
x,y= player_cur_loc[0],player_cur_loc[1]
x1,y1=new_loc[0],new_loc[1]
if check_out_of_bounds(new_loc):
print("Error, out of bounds")
cur_dir = direction_num(player_cur_direction)
new_dir = direction_num(get_di... |
def get_adjacent_blocks_coor(cur_x, cur_y, direction):
# return the coordinates of the block adjacent to the current block in that direction
if(direction == "north"):
return [cur_x,cur_y-1] # assumming north is y-1
elif(direction == "east"):
return [cur_x+1,cur_y]
elif(direction == "sou... | The function `return_back` identifies valid adjacent blocks for the player to move to by checking if they are visited, in bounds, safe, and not in dead ends or visited lists. If no valid moves are found, it adds the current position to dead ends and rechecks for alternatives. It then selects the first valid move, updat... | def return_back(cur_x,cur_y):
choices=[]
for direction in legal_directions:
next_block = get_adjacent_blocks_coor(cur_x,cur_y,direction)
if visited[next_block[0]][next_block[1]] and not(check_out_of_bounds(next_block[0],next_block[1])) and safe_loc(next_block[0],next_block[1]) and not (next_bloc... |
def get_adjacent_blocks_coor(cur_x, cur_y, direction):
# return the coordinates of the block adjacent to the current block in that direction
if(direction == "north"):
return [cur_x,cur_y-1] # assumming north is y-1
elif(direction == "east"):
return [cur_x+1,cur_y]
elif(direction == "sou... | The code navigates a player towards a target position by exploring valid paths, avoiding dead ends, and selecting the next move using Manhattan distance as a heuristic. It updates visited blocks, clears cached data if the target changes, and ensures safe, unvisited moves. | def reach_position(new_x,new_y):
# clear dead_ends if target location is changed
if(reach_cached_target_location[0] != new_x or reach_cached_target_location[1] != new_y):
reach_dead_ends.clear()
reach_visited.clear()
reach_cached_target_location[0] = new_x
reach_cached_target_lo... |
def get_adjacent_blocks_coor(cur_x, cur_y, direction):
# return the coordinates of the block adjacent to the current block in that direction
if(direction == "north"):
return [cur_x,cur_y-1] # assumming north is y-1
elif(direction == "east"):
return [cur_x+1,cur_y]
elif(direction == "sou... | The code implements a path-planning algorithm to navigate a grid, prioritizing safe, unvisited, non-dead-end locations. If no valid options exist, it marks the current position as a dead end and revisits previously safe, non-dead-end blocks. It selects the first valid move and stores alternative paths in a stack for fu... | def planner(cur_x, cur_y):
# make a list of all nearby options with always safety first then not visited
choices = []
for direction in legal_directions:
# get next direction
next_visit_block = get_adjacent_blocks_coor(cur_x,cur_y,direction)
if (safe_loc(next_visit_block[0],next_visit... |
def drop_columns(self,df:pd.DataFrame) -> None:
df = df.drop(self.columns_to_drop,axis=1)
logger.info(
f"Dropped {len(self.columns_to_drop)} columns since they are not in the test data")
return df
def _set_holidays(self,df:pd.DataFrame) -> None:
"""Filters the holiday dates f... | The main task of the code is to perform feature engineering on a DataFrame by dropping columns, generating new features, setting holidays, and creating holiday distance columns to enhance the dataset for machine learning tasks. | def transform(self, df: pd.DataFrame = None):
if not isinstance(df, NoneType):
self.df = df.copy()
assert 'Date' in self.df.columns
df = self.drop_columns(df)
self.holidays = self._set_holidays(df)
df = self.generate_columns(df)
df = self.create_holiday_distan... |
def find_optimal_tr(pList, SList, c, arr_rate, h, K, demand, demand_input):
# return the optimal price and S
profit = [[compute_profit_tr(p, c, S, arr_rate, h, K,demand, demand_input)[0] for S in SList] for p in pList]
(index1, index2) = np.where(profit == max(max(profit)))
pstar = pList[index1[0]]
Ssta... | The function `result` computes optimal pricing (`pstar`) and stock levels (`Sstar`) for a demand scenario, calculates associated profit, costs, and revenue, then determines an optimal discount (`discount`) and its impact on profit. It returns two lists: one with base-case metrics (profit, costs, etc.) and another with ... | def result(demand, demand_input, c, arr_rate, h, K, pList, SList, dList):
(pstar,Sstar) = find_optimal_tr(pList, SList, c, arr_rate, h, K, demand, demand_input)
print("result")
print("K = "+str(K))
print( (pstar, Sstar))
(profit, revenue, totalCost, HC, KC , S1, S2) = compute_profit_tr(pstar, c, Sst... |
def find_optimal_tr(pList, SList, c, arr_rate, h, K, demand, demand_input):
# return the optimal price and S that maximize the profit for the traditional selling
profit = [[compute_profit_tr(p, c, S, arr_rate, h, K,demand, demand_input)[0] for S in SList] for p in pList]
(index1, index2) = np.where(profit == ma... | The code calculates optimal pricing (pstar) and inventory (Sstar) strategies for a business model, computes associated profit, revenue, and costs, determines an optimal discount (discount), and evaluates its impact on profit and quantities. It returns key metrics for both the original and discounted scenarios, includin... | def result(demand, demand_input, c, arr_rate, h, K, pList, SList, dList):
(pstar,Sstar) = find_optimal_tr(pList, SList, c, arr_rate, h, K, demand, demand_input)
print("result")
print("K = "+str(K))
print( (pstar, Sstar))
(profit, revenue, totalCost, HC, KC , S1, S2) = compute_profit_tr(pstar, c, Sst... |
def take_action(observation):
if random.random() > epsilon:
return np.argmax([qfunction(observation, action) for action in range(env.action_space.n)])
else:
return random.randint(0, 2)
def qfunction(observation, action):
global thetas
return np.matmul(features(observation, action), theta... | The code implements a semi-gradient Sarsa algorithm for reinforcement learning, training an agent to maximize cumulative rewards in an environment. It updates Q-function parameters (thetas) using temporal difference errors, logs average rewards every 10 episodes, and visualizes the cost-to-go curve. The agent interacts... | def learn():
global thetas
global env
cost2Go = []
avg_reward = 0
env = wrappers.Monitor(env, './semi-sarsa', force=True)
for i_episode in range(2000):
observation = env.reset()
reward_total = 0
action = take_action(observation)
t = 0
while True:
... |
def color(b, g, r):
return bytes(
[int(b * 255),
int(g * 255),
int(r * 255)]
)
def glViewMatrix(self, translate=V3(0, 0, 0), rotate=V3(0, 0, 0)):
self.camMatrix = self.glCreateObjectMatrix(translate, rotate)
self.viewMatrix = np.linalg.inv(self.camMatrix)
def glViewport... | This code initializes a graphics context by setting up viewport parameters, projection matrices, and rendering attributes like clear color, active shaders/textures, and directional lighting. It configures the viewport matrix for screen mapping and prepares the rendering environment for 3D graphics operations. | def __init__(self, width, height):
self.width = width
self.height = height
self.clearColor = color(0, 0, 0)
self.currColor = color(1, 1, 1)
self.active_shader = None
self.active_texture = None
self.active_texture2 = None
self.dirLight = V3(0, 0, 1)
... |
def out_of_range(T):
return MaybeValue(T).fixed(MaybeInRange(T).out_of_range())
def not_fixed(T):
return MaybeValue(T).not_fixed()
def value(T, v):
return MaybeValue(T).fixed(MaybeInRange(T).in_range(v)) | This code evaluates the value of an object based on input sources. It checks if any source arguments are out-of-range or unfixed. If out-of-range arguments exist, it returns an out-of-range result. If unfixed arguments exist, it returns a not-fixed result. Otherwise, it computes the value using a predefined function an... | def value(self, i):
args = [source.value(i) for source in self.sources]
not_fixed_args = [arg for arg in args if arg.is_fixed == 0]
out_of_range_args = [arg for arg in args if arg.is_fixed == 1 and arg.value.is_in_range == 0]
if len(out_of_range_args) != 0:
return out_of_rang... |
def value(T, v):
return MaybeValue(T).fixed(MaybeInRange(T).in_range(v))
def out_of_range(T):
return MaybeValue(T).fixed(MaybeInRange(T).out_of_range())
def not_fixed(T):
return MaybeValue(T).not_fixed() | This method processes the next value from a source, checks if it's fixed and in range, applies a function to transform it, adds the result to a vector, and returns either the transformed value, an out-of-range signal, or a not-fixed indicator based on conditions. | def __next(self):
v = self.source.value(self.offset)
if v.is_fixed:
self.offset += 1
if v.value.is_in_range:
v2 = self.func(v.value.value)
self.vec.add(v2)
return value(self.V2, v2)
else:
return out_of_ra... |
def getAstrosourceByID(self,id):
return self.getCollection().find_one({"id":id})
def getCollection(self,collection=""):
collection = collection if collection != "" else self.__main_collection
return self.getDB()[collection]
def updateAstrosource(self,astrosource):
source = astrosource
... | This function inserts an astrosource into a MongoDB collection if it doesn't already exist, returning True upon successful insertion. If the astrosource exists, it delegates to an update method. The task involves checking existence via ID, conditional insertion, and handling database operations for astrosource data man... | def insertAstrosource(self,astrosource,collection=""):
if astrosource != None:
indb= self.getAstrosourceByID(astrosource["id"])
if indb is None:
self.getCollection(collection).insert_one(astrosource)
return True
else:
return sel... |
def step1_clean(self):
"""
Perform step 1 of preprocessing - clean the data on all DataFrames
(azdias, customers, mailout_train, mailout_test):
- drop unneeded columns,
- replace invalid values by np.nan,
- ensure consistent feature spacing,
- remove unknown value... | The code performs preprocessing on datasets through five steps: cleaning data, handling outliers and low-standard-deviation features, addressing missing values and recoding composite features, imputing missing data, and scaling the data. Each step is executed sequentially via dedicated methods, ultimately preparing the... | def process(self):
"""
Perform all preprocessing steps on the given datasets. These steps are:
- 1 cleaning
- 2 handle outliers and features with low std_dev
- 3 handle missing values and recode some features
- 4 impute
- 5 scale
:return: None
"""
... |
def makeLattice(minimaObj):
crystal = pymatgen.core.lattice.Lattice.from_parameters(a=minimaObj[0], b = minimaObj[1], c = minimaObj[2],alpha = minimaObj[3], beta = minimaObj[4], gamma = minimaObj[5])
return crystal
def makeCrystal(lat, minimaObj,buffer):
crystalStruct = pymatgen.core.structure.IStructure(lattice ... | This function predicts the critical temperature (Tc) of a material using a machine learning model. It processes crystal structure data, extracts features like volume and space group, combines them with input parameters, and uses a model to predict Tc. The output is either -Tc (for optimization) or the squared error bet... | def OptTc(self,v,numd,zas,model,optmax,target=0,typea='original'):
Lat=makeLattice(v)
numrdvolume=Lat.volume
crst=makeCrystal(lat=Lat,minimaObj=v,buffer=zas)
print(crst)
try:
numrdspace_group=pymatgen.core.Structure.get_space_group_info(crst,symprec=0.07,angle_tolerance=5)[1]
except TypeE... |
def populate_sample_ids(self):
all_sample_ids = []
full_path = os.path.realpath(self.data_input_folder)
for f in os.listdir(full_path):
if f.find(".gui") != -1:
file_name = f[:f.find(".gui")]
if os.path.isfile("{}/{}.png".format(self.data_input_folder,... | The main task of the code is to split a dataset into training and validation subsets based on a specified validation split ratio. It generates sample IDs, partitions them into training and validation sets, and returns the corresponding file paths for these subsets. The function handles dataset segmentation and path org... | def split_datasets(self, validation_split):
sample_ids = self.populate_sample_ids()
print("Total number of samples: ", len(sample_ids))
train_set_ids, val_set_ids, shuffled_sampled_ids = self.get_all_id_sets(validation_split, sample_ids)
training_path, validation_path = self.split_sampl... |
def init():
# Configure the GPIO to drive the LCD display correctly
GPIO.setmode(GPIO.BCM) # Use BCM GPIO numbers
# setup all output pins for driving LCD display
GPIO.setup(OLED_D4, GPIO.OUT) # DB4
GPIO.setup(OLED_D5, GPIO.OUT) # DB5
GPIO.setup(OLED_D6, GPIO.OUT) # DB6
... | The code's main task is to initialize GPIO and a display, sequentially show model information and IP address with 3-second delays between each, then clear the display. It automates displaying and clearing data on an embedded system's screen, likely for a Raspberry Pi project or similar hardware setup. | def main():
# Initialise GPIO port and display
init()
# Send some text
show_model()
time.sleep(3) # 3 second delay
# Send some more text
show_ip()
time.sleep(3)
clear_display() |
def get_N(dag):
return len(dag)
def get_M(dag):
m = 0
adj = dag.get_adj_v()
for adj_i in adj:
m += len(adj_i)
return m
def get_ave_k(dag):
n = get_N(dag)
m = get_M(dag)
return 2 * m / n
def get_ave_C(dag):
Cs = _get_Cs(dag)
return sum(Cs) / get_N(dag)
def get_ave_L(dag):... | The code defines a function `evaluate` that computes and returns five key metrics of a Directed Acyclic Graph (DAG): the number of nodes (`N`), edges (`M`), average degree (`ave_k`), average clustering coefficient (`ave_C`), and average path length (`ave_L`). These metrics collectively characterize the DAG's structural... | def evaluate(dag):
return get_N(dag), get_M(dag), get_ave_k(dag), get_ave_C(dag), get_ave_L(dag) |
def evaluate(dag):
return get_N(dag), get_M(dag), get_ave_k(dag), get_ave_C(dag), get_ave_L(dag)
def get_N(dag):
return len(dag)
def get_M(dag):
m = 0
adj = dag.get_adj_v()
for adj_i in adj:
m += len(adj_i)
return m
def get_ave_k(dag):
n = get_N(dag)
m = get_M(dag)
return 2 ... | The code evaluates neural network models (e.g., NASNet) by converting them into Directed Acyclic Graphs (DAGs), calculates structural metrics (N, M, <k>, C, L, coreness), and saves results to 'result1.csv'. It iterates through specified models, generates DAGs, computes metrics, and logs outputs for analysis. | def test2():
# model_classess = [InceptionResNetV2, InceptionV3, MobileNet, ResNet50, VGG16, VGG19, Xception, NASNet]
model_classess = [NASNet]
for model_class in model_classess:
model = model_class()
dag = model_to_dag(model)
with open('result1.csv', mode='a+', newline='') as f:
... |
def _tile_paths(path: da.Array, n_tiles: int, img_tiled: da.Array) -> da.Array:
"""Replicate the paths by number of tiles and append a tile index."""
max_path_chrs = max([len(p.decode("utf-8")) for p in path]) + len(str(n_tiles)) + 1 # + 1 for _
string_dtype = h5py.string_dtype("utf-8", max_path_chrs)
... | This function tiles image and label arrays from an H5 file into smaller tiles with specified overlap and target size, then saves the tiled data along with metadata (paths, EPSG, affine transforms) into a new H5 file using Dask for parallel processing. It expands input arrays to a target size, creates tiled datasets wit... | def tile_img_h5(
src_file: pathlib.Path,
dst_file: pathlib.Path,
tile_size: int,
overlap: int,
target_size: int,
chunk_size: int | None = 1,
) -> None:
"""Tile image array and provide tiled transforms for h5 files created by ukis_sat2h5.conversion.
Parameters
----------
src_file... |
def findEntry(named):
header = memory[2]
Done = False
while header != 0 and not Done:
if named == extractString(header + 3):
Done = True
else:
header = memory[header]
return header
def injectString(s, to):
global memory
i = to
for c in s:
memor... | This code defines a loop that processes user input commands. It retrieves an interpreter from memory, splits each input line into tokens, injects tokens into a specific memory address (1025), pushes this address onto a stack, and executes the interpreter. The loop terminates when the user inputs "bye". The core task is... | def run():
Done = False
Interpreter = memory[findEntry("interpret") + 1]
while not Done:
Line = input("\nOk> ")
if Line == "bye":
Done = True
else:
for Token in Line.split(" "):
injectString(Token, 1025)
stack.append(1025)
... |
def check_socket(self):
try:
data, addr = sock.recvfrom(1024)
if len(data) == 3:
self.process_instant_data(data)
if len(data) >= 8:
self.process_periodic_data(data)
if len(data) == 4:
self.process_destroy_data(data)
... | This function manages a game loop by continuously updating game state, handling shooting mechanics, and processing events. It limits the frame rate to 30 FPS, decrements a shooting counter to spawn bullets, checks network sockets, updates game elements on the screen, and handles input/events. The loop runs indefinitely... | def main_loop(self, screen, width, height, shot):
while 1:
clock.tick(30)
self.time_now = time.time()
if (self.shoot_amount > 0):
self.shoot_amount -= 1
self.bullets_list.append(bullet(-1, self.position[0], self.position[1], self.direction))
... |
def check_socket(self):
try:
data, addr = sock.recvfrom(1024)
if len(data) == 2:
self.create_new_player(addr)
if len(data) == 1:
data = int.from_bytes(data, 'big')
in_sequence_number = data >> 3 # shift right by 3 bits
... | This code initializes a game server that runs in a loop at 30 FPS, handling socket checks, player/bullet movement, collision detection, and sending periodic data every 3 seconds when players are present. It maintains game state consistency and communication. | def __init__(self):
self.next_id = 0
self.out_sequence_number = -1
print("server up")
periodic_data_time = time.time()
while True:
clock.tick(30)
time_now = time.time()
self.check_socket()
self.move_bu... |
def new_turn(self):
self.reset_turn()
self.turn += 1
def draw_marble(self):
if not self.draw_marble_is_legal():
illegal_move = True
return
self.pending_rands -= 1
col = self.get_random_hidden()
self.hidden_marbles[col] -= 1
self.inv_marbles[col] += 1
def pick(self, col):
if not self.pick_is_legal... | The `run_move` method executes game actions based on the `move` object's type, such as initiating a new turn, drawing marbles, picking, showing files, or building structures. It triggers corresponding methods like `new_turn()`, `draw_marble()`, or `build_from_file()`. If `check_illegal` is True and the move is invalid,... | def run_move(self, move, check_illegal=True):
if move.move_type == MOVE_TYPES.index('new_turn'):
self.new_turn()
elif move.move_type == MOVE_TYPES.index('draw_marble'):
self.draw_marble()
elif move.move_type == MOVE_TYPES.index('pick'):
self.pick(move.col)
elif move.move_type == MOVE_TYPES.index('file_... |
def batch_multiply(float_or_vector, tensor):
if isinstance(float_or_vector, torch.Tensor):
assert len(float_or_vector) == len(tensor)
tensor = _batch_multiply_tensor_by_vector(float_or_vector, tensor)
elif isinstance(float_or_vector, float):
tensor *= float_or_vector
else:
ra... | The function `rand_init_delta` initializes a perturbation tensor `delta` based on the specified norm (`ord`). For `ord=np.inf`, it samples uniform noise scaled by `eps`. For `ord=2`, it generates noise within `[clip_min, clip_max]`, subtracts `x`, and clamps by L2 norm. For `ord=1`, it samples Laplace noise, normalizes... | def rand_init_delta(delta, x, ord, eps, clip_min, clip_max):
if isinstance(eps, torch.Tensor):
assert len(eps) == len(delta)
if ord == np.inf:
delta.data.uniform_(-1, 1)
delta.data = batch_multiply(eps, delta.data)
elif ord == 2:
delta.data.uniform_(clip_min, clip_max)
... |
def drawInit():
global blackFlag, chessMap, endding
blackFlag = True
endding = False
chessMap = [[0 for i in range(0, MAP_HEIGHT)] for i in range(0, MAP_WIDTH)]
canvas.create_rectangle(0, 0, WIDTH, HEIGHT, fill=BG_COLOR)
canvas.create_rectangle(0, (HEIGHT - TEXT_SIZE), WIDTH, HEIGHT, fill=TXT_BG... | This code handles a game move in a turn-based strategy game. It resets the game if 'endding' is True. Otherwise, it calculates coordinates from user input, logs the move, and processes the game state. If the move is valid (r=0), the computer selects the best move via search algorithms, prioritizing the most advantageou... | def control(event):
global endding
if endding == True:
drawInit()
endding = False
else:
x = int((event.x - BORDER_SIZE) / BLOCK_SIZE + 0.5)
y = int((event.y - BORDER_SIZE) / BLOCK_SIZE + 0.5)
drawText('%s : add at (%s, %s)' % ("Black" if blackFlag == True else "White"... |
def checkValidData(key, data, dataType, optional=False, default="", coerce=False):
"""
This function takes a data dict, determines whether a key value exists
and is the right data type. Returns the data if it is, raises an
HTTP error if it isn't.
:param key: the key of the data dict
:param data: a dict of data
... | The function constructs a MongoDB query to retrieve playlists based on input filters (e.g., names, dates, music attributes) from `data`, combines results with music-related IDs, calculates relevance scores, sorts by relevance, and returns cleaned playlist data. | def makePlaylistQuery(data, playlistDB, musicDB):
print("creating query")
myPlaylist = dict()
musicList = set()
for key in ["playlist_names", "start_date", "end_date", "song_names", "artist_names", "album_names", "genre_names", "_id"]:
if key in data:
if key == "playlist_names":
# myPlaylist[key] = r"/.*"... |
def compute_window(self, label):
theta = self.cone_angle
if label == 1: #follow right wall
base_index = self.angle2index(270)
elif label == 2: #follow left wall
base_index = self.angle2index(90)
right_index = base_index + round((theta/2 - self.range_data.angle_min)/self.range_data.angle_increment)
left... | The code computes the minimum valid distance to a wall within a specified angular window. It iterates through sensor data indices, checks for finite, non-NaN distances, and returns the smallest valid distance, along with its angular position, to determine the closest wall in the given direction. | def compute_wall_distance(self, label):
left_index, right_index = self.compute_window(label)
#Init
min_distance = float("inf")
index = left_index
#Check through the window
for i in range(left_index, right_index):
raw_distance = self.range_data.ranges[i]
'''
print("label:",label)
print("Index:",... |
def check_if_transcoded(conn, video_file):
cursor = conn.cursor()
cursor.execute(
"SELECT source_modified_time FROM transcoded_videos WHERE source_file = ?", (video_file,))
result = cursor.fetchone()
if result is not None:
source_modified_time = os.path.getmtime(video_file)
retur... | The main task of the code is to transcode video files to MP4 format if they meet specific criteria: supported extensions, not already transcoded, and source file newer than existing output. It ensures efficient processing by checking modification times, avoiding redundant work, and logging errors. The function uses a d... | def process_video(video_file, source_dir, output_dir, bitrate, dev_null, conn):
try: # Convert to Path object
if not video_file.suffix.lower() in SUPPORTED_EXTENSIONS:
return
output_file = output_dir / video_file.relative_to(source_dir)
output_file = output_file.with_suffix(".m... |
def get_train_val_test(train_cities, test_cities, features, window=5, reducer_choice=None,
n_components=2, scale_choice=ScaleChoice.origin):
"""
Get train, validation set from train cities,
get test set from test cities
:param train_cities:
:param test_cities:
:param featu... | The function `run` performs hyperparameter tuning (grid search) for a CNN-based model on multi-source features from specified cities. It trains and evaluates models using cross-validation, with options for data scaling, early stopping, and feature selection. The best model is selected based on validation RMSE, and resu... | def run(train_cities, test_cities, data_param_grid, model_param_dict, window=5,
model_choice=ModelChoice.cnn, feature_choice=FeatureChoice.all, epochs=40,
scale_choice=ScaleChoice.origin, early_stopping=True,
early_stop_epoch=10, save_predict=False, test_origin=False):
"""
main entrance ... |
def _construct_endpoint_adjacency_of_valid_segments(
segment_to_point_adj: tf.Tensor, valid_segments: tf.Tensor
) -> tf.Tensor:
"""
Constructs the adjacency matrix of points connected by boundary segments
of a particular type (which we call valid segments).
Parameters
----------
segment_to_... | The function extracts valid endpoint pair combinations from a triangulation by filtering boundary segments, constructing adjacency relationships, and grouping compatible pairs by type (timelike/spacelike). It returns six tensors categorizing these combinations for current segments and new triangle types (tss, stt), ena... | def extract_endpoint_pair_combinations(
triangulation,
) -> Tuple[tf.Tensor, tf.Tensor, tf.Tensor, tf.Tensor, tf.Tensor, tf.Tensor]:
# ------------------ Get relevant data from triangulation ------------------
segment_to_point_adj = tf.sparse.to_dense(
tf.sparse.reorder(triangulation.adj(etype="segm... |
def create_keyboard_buttons(self):
row, column = 0, 0
for letter in ALPHABET:
if column == len(ALPHABET)/2:
row += 1
column = 0
self.keyboard_buttons[letter] = self.create_button(self.keyboard_frame,
... | The code initializes a game or application by setting up keyboard buttons, side buttons, binding spacebar controls, and starting the game loop. The `__init__` method calls parent class initialization, creates UI elements, assigns keybindings, and triggers the game's main functionality. This prepares the environment for... | def __init__(self):
super().__init__()
self.create_keyboard_buttons()
self.create_side_buttons()
self.keybind_space()
self.play_game() |
def show_head(self):
#display head of each dataframe
print('Dataframe Heads')
print(f'DF1 Head: {self.df1.head()}')
print(f'DF2 Head: {self.df2.head()}')
print(f'DF3 Head: {self.df3.head()}')
print(f'DF4 Head: {self.df4.head()}')
print('===========================... | The main task of the code is to display comprehensive information about dataframes by sequentially calling methods that show the head, tail, shape, columns, numeric/string columns, data types, and similarity metrics of the data. This provides an overview of the dataset's structure, content, and statistical properties i... | def show_all(self):
#display all information of the dataframes
self.show_head()
self.show_tail()
self.show_shape()
self.show_columns()
self.show_numeric_columns()
self.show_string_columns()
self.show_data_types()
self.run_all_similarity_functions() |
def makeRequest(url):
r = requests.get(url)
status = r.status_code
header = r.headers
rJson = json.loads(r.text or r.content)
return rJson
def manipulate(data):
for partner in data["partners"]:
partner["availableDates"] = remove_unconsecutive_dates(partner["availableDates"])
return... | The code processes partner data to determine the two most common available dates per country, identifies partners who can attend both dates, and constructs a JSON response listing countries with attendee counts and email lists for those who can attend the top two dates. | def main():
getJson = makeRequest(URL)
newJson = manipulate(getJson)
countryDict = {}
# Create a dictionary entry for each country found and add in the available dates
for partner in newJson["partners"]:
avDates = partner["availableDates"]
country = partner["country"]
if(cou... |
def send_rest_api_request(url, headers, data):
try:
response = requests.post(url, headers=headers, json=data)
response.raise_for_status() # Memeriksa respons HTTP untuk kesalahan
print(f"Data JSON berhasil dikirim ke {url}")
print(f"Response: {response.status_code} {response.text}")... | The main task of the code is to convert CSV file data into JSON format for a REST API by reading CSV rows, sending each entry via an API request, tracking processed data, moving the file to a processed folder upon completion, and restarting folder monitoring. It uses a counter to ensure all rows are processed before mo... | def convert_csv_to_restapi_json(file_path):
with open(file_path, "r") as file:
reader = csv.DictReader(file)
data_list = list(reader)
total_rows = len(data_list) # Menghitung jumlah total baris
for data in data_list:
send_rest_api_request(api_url, api_headers, data)
global pr... |
def last_block(self):
return self.get_block(-1)
def proofofwork(self, b, difficulty):
b.difficulty = difficulty
# print("Mining Block #"+str(b.index))
# print("Difficulty =",difficulty)
b.gen_hash()
while not int(b.hash, 16) <= 1 << (256 - difficulty): # this i... | The main task of the code is to mine a new block by checking if there are sufficient unconfirmed transactions. If so, it creates a new block with the next index, current timestamp, and proof of work. The block is validated, added to the blockchain, unconfirmed transactions are cleared, and the new block's index is retu... | def mine(self):
if len(self.unconfirmed_transactions) < blocksize: # if there arent enough transactions, dont bother
return False
last_block = self.last_block()
new_block = block(last_block.index+1, self.unconfirmed_transactions, str(time.time()), last_block.hash, miner=str(self.cli... |
def setup_alice(self):
return self.setup('alice')
def setup_bob(self):
return self.setup('bob')
def setup_eve(self):
return None
def setup_tally(self):
layouts = []
# Alice's tally
components = []
components += self.tally_array(self.alice_position('tally'),
... | The main task of the code is to generate SVG visualizations for a scenario involving parties (Alice, Bob, Eve) and their interactions. It constructs layouts for each party, creates figures with specified resolutions, combines them with tally/signal elements, and returns pixelated SVG images, handling errors gracefully. | def images(self):
content = []
# build a layout for each party
alice_layout = self.setup_alice()
bob_layout = self.setup_bob()
if alice_layout:
alice_svg = sc.Figure(*[str(r) for r in self.resolution], alice_layout)
content.append(alice_svg)
if bob... |
def invalid_syntax():
print("#####################################################\nFatal error: Invalid syntax. Printing help statement.\n#####################################################\n")
print_help()
def print_help():
with open("help.txt", "r") as helpfile:
h = helpfile.readlines()
for... | The code processes command-line arguments to handle translation requests or display help. It checks for valid flags (-h, --help) to show help, or language flags (-s, -f, -g) followed by a word to translate. If inputs are invalid, it triggers error functions. The function determines the language code (0-2) and calls a t... | def take_input(words):
acceptable_helps = ["-h", "--help"]
acceptable_langs = ["-s", "-f", "-g", "--german", "--french", "--spanish"]
german = ["-g", "--german"]
french = ["-f", "--french"]
spanish = ["-s", "--spanish"]
args = sys.argv
if len(args) == 2:
h = args[1]
if h not ... |
def mse_gen_set(output_dir: str, *packs: SealedProduct):
if os.path.exists(output_dir):
shutil.rmtree(output_dir)
os.mkdir(output_dir)
shutil.copy(
MSE_SET_SYMBOL_FILEPATH, os.path.join(output_dir, MSE_SET_SYMBOL_FILENAME)
)
with open(os.path.join(output_dir, "set"), "w", encoding=... | The main task of the code is to generate image sheets for an MSE set by taking user inputs for directory path and images per sheet, processing card data, creating and saving PNG sheets, then cleaning up temporary images. It handles user input validation, generates card images, arranges them into sheets, and ensures pro... | def images_sheets():
path = input("What is the path to where you want the MSE set directory? ")
if not path:
return
n_cards = sum(len(p) for p in packs)
ips: int = None
while ips is None:
ips_str = input(
f"How many images do you want per s... |
def mse_gen_set(output_dir: str, *packs: SealedProduct):
if os.path.exists(output_dir):
shutil.rmtree(output_dir)
os.mkdir(output_dir)
shutil.copy(
MSE_SET_SYMBOL_FILEPATH, os.path.join(output_dir, MSE_SET_SYMBOL_FILENAME)
)
with open(os.path.join(output_dir, "set"), "w", encoding=... | The main task of the code is to generate an MSE set directory, create card images, and produce MPC order XML files based on user-specified paths and pack data. It also provides manual instructions for uploading generated XMLs via MPCFill. The process involves user input for directory paths, automated file generation, a... | def mpc():
path = input("What is the path to where you want the MSE set directory? ")
if not path:
return
mse_gen_set(path, *packs)
print("MSE set generated.")
mse_gen_card_images(path)
print("Images generated into MSE set directory.")
mpc_gen_orders(p... |
def mse_gen_set(output_dir: str, *packs: SealedProduct):
if os.path.exists(output_dir):
shutil.rmtree(output_dir)
os.mkdir(output_dir)
shutil.copy(
MSE_SET_SYMBOL_FILEPATH, os.path.join(output_dir, MSE_SET_SYMBOL_FILENAME)
)
with open(os.path.join(output_dir, "set"), "w", encoding=... | The function `mpc_autofill` generates an MSE set directory at a user-specified path, creates card images, generates MPC order XMLs, and fulfills each order step-by-step. It prompts the user to input a path, confirms directory creation, generates images, creates orders, and for each order, waits for user confirmation af... | def mpc_autofill():
path = input("What is the path to where you want the MSE set directory? ")
if not path:
return
mse_gen_set(path, *packs)
print("MSE set generated.")
mse_gen_card_images(path)
print("Images generated into MSE set directory.")
orders ... |
def th_posemap_axisang(pose_vectors):
'''
Converts axis-angle to rotmat
pose_vectors (Tensor (batch_size x 72)): pose parameters in axis-angle representation
'''
rot_nb = int(pose_vectors.shape[1] / 3)
rot_mats = []
for joint_idx in range(rot_nb):
axis_ang = pose_vectors[:, joint_idx... | The code computes 3D vertices and joint positions from body pose and shape parameters using a skinned mesh model. It converts axis-angle poses to rotation matrices, applies shape deformation via betas, and computes posed vertices. It constructs global transformations for each joint, applies translations, and returns fi... | def forward(self,
body_pose,
betas=torch.zeros(1),
trans=torch.zeros(1),
h2w = None):
"""
Args:
body_pose (Tensor (batch_size x 72)): pose parameters in axis-angle representation
th_betas (Tensor (batch_size x 10)): if provi... |
def eval_at_k(model, test_interactions, k=10):
recalls = []
precisions = []
ndcgs = []
hits = []
for user in range(test_interactions.shape[0]):
user_interactions = test_interactions[user].nonzero()[1]
if len(user_interactions) == 0:
continue
scores = model.recomme... | The function evaluates an implicit recommendation model by calculating and printing key performance metrics—precision, recall, NDCG, hit rate, F1 score, and MAP—at a specified rank cutoff (k). It returns these metrics for analysis, assessing how well the model predicts user-item interactions based on implicit feedback ... | def evaluate_implicit_model(model, interactions, k=10):
precisions, recalls, ndcgs, hits = eval_at_k(model, interactions, k)
maps = map(model, interactions, k)
f1_score = f1_score_at_k(model, interactions, k)
print(f'Precision@{k}: {precisions}')
print(f'Recall@{k}: {recalls}')
print(f'NDCG@{k}:... |
def ProxyConnection():
global proxy_actual
temp = 0
f = open("Proxies.txt", "r")
list_of_lines = f.readlines()
for line in enumerate(list_of_lines):
if (line == proxy_actual):
temp += 1
continue
elif (proxy_actual == []):
proxy_actual = line
... | The code automates account creation and tasks using Selenium with Chrome, employing proxy rotation and user agent randomization. It generates emails, creates Knight of Cathena and Twitter accounts, executes missions, and manages browser tabs. Proxy connections are tested, and the script loops indefinitely with random d... | def main():
try:
###----------CHROME OPTIONS----------###
s = "C:\\WebDriver\\bin\\chromedriver.exe"
###----------GENERATE RANDOM USER AGENT----------###
#ua = UserAgent()
#userAgent = ua.random
#chrome_options = webdriver.ChromeOptions()
###----------ADD AS A... |
def beautifyJS(self, content):
return jsbeautifier.beautify(content)
def parseForLinks(self, contents):
discoveredLinks = []
outputLinks = []
# ugh lol
regex = r"[^/][`'\"]([\/][a-zA-Z0-9_.-]+)+(?!([gimuy]*[,;\s])|\/\2)"
links = re.finditer(regex, contents)
for l... | The code extracts links from JavaScript content, highlights them in the source code context, and generates an HTML report displaying each link with its line number and highlighted code snippet. It uses beautified JS for parsing, escapes characters for safety, and structures the output with divs and spans for visual for... | def fileRoutine(self, url, content):
html = ""
# beautify the JS for cleaner parsing
# note: this can be slow against large JS files and can lead to failure
prettyContent = self.beautifyJS(content)
# parse all the links out
parsedLinks = self.parseForLin... |
def recon_menu():
recon_loop = True
while recon_loop == True:
ascii_recon = pyfiglet.figlet_format("Reconnaissance")
print(ascii_recon)
print("\nPlease Select an Option Below.")
print("1. Footprinting")
print("2. Scanning")
print("3. Enumeration")
print("... | The code defines a menu-driven interface for an automated pentesting tool, allowing users to select tasks like reconnaissance, vulnerability scanning, exploitation, report generation, and database management. It loops until the user chooses to end the session, which closes database connections and exits the program. Ea... | def project_menu():
loop = True
while loop == True:
ascii_hi = pyfiglet.figlet_format("Welcome to Automated Pentesting!")
print(ascii_hi)
print("\nPlease Select an Option Below.")
print("1. Reconnaissance")
print("2. Vulnerability Scanning")
print("3. Exploitation... |
def render_personal_showcase_group_begin(width, template, title):
code_tpl = Template(template["personal_showcase_group_begin"])
return code_tpl.substitute(width=width, subsection_title=title)
def render_personal_showcase_item(template, data):
match data["type"]:
case "NameValues":
retur... | The main task of the code is to generate a formatted LaTeX section for a personal showcase by substituting dynamic data into a template. It processes groups of items, applying specified widths to each group, rendering individual items with separators, and structuring the output with LaTeX rules and group containers. | def render_personal_showcase(template, data):
section_title = data["section_title"]
src = template["personal_showcase"]
rule_str = '\\rule{1.0\\textwidth}{0.1pt}\n'
src = Template(src).substitute(section_title=section_title)
widths = [0.2, 0.35, 0.35] # width proportion to total line-width
for ... |
def detection_loop(cam, columns, rows, block_size):
scaled_width = 640
mtx = None
dist = None
# Detected points, in image spaces
detected_points = []
last_save_time = 0
while True:
ret, img = cam.read()
if not ret:
print("Failed to get a frame")
sy... | The main task of the code is to calibrate a camera using a chessboard-like pattern. It parses user inputs for camera settings, grid dimensions, block size, and output file. It initializes the camera, detects grid points via a detection loop, performs camera calibration to compute intrinsic and extrinsic parameters, and... | def main():
parser = argparse.ArgumentParser(
prog="lpe-calibrate",
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
)
parser.add_argument(
"--camera",
default=0,
type=int,
help="The index of the camera to use (according to OpenCV)",
)
parser.a... |
def load_calibration(filename):
fs = cv.FileStorage(cv.samples.findFile(filename), cv.FILE_STORAGE_READ)
mtx = fs.getNode("camera_matrix").mat()
dist = fs.getNode("distortion_coefficients").mat()
return mtx, dist
def wait_for_capture(camera, already_captured):
while True:
img = read(camera)... | The main task of the code is to capture and triangulate 3D coordinates of LED positions from camera images using camera calibration data, updating a JSON output file. It initializes a camera, loads calibration parameters, controls WLED for LED display, and processes image points to estimate world coordinates through it... | def main():
parser = argparse.ArgumentParser(
prog="lpe-capture", formatter_class=argparse.ArgumentDefaultsHelpFormatter
)
parser.add_argument(
"--camera",
default=0,
type=int,
help="The index of the camera to use (according to OpenCV)",
)
parser.add_argument(... |
def final_cost(curr_posx,curr_posy,next_posx,next_posy,goal,area_cost):
return cost_from_start(curr_posx,curr_posy,next_posx,next_posy,area_cost) + heuristic_cost(curr_posx,curr_posy,goal)
def least_cost(open_cells,area_cost):
l=[0,0,100000]
#print("open Cells: ",open_cells)
print(len(open_cells))
f... | The main task of the code is to explore valid neighboring cells around a given position in a grid, updating their parent pointers, marking them as visited, and calculating their traversal costs using a `final_cost` function. It checks boundary constraints defined by `playGround`, ensures cells are unvisited (`area_stat... | def neighbour_cells(area_state,area_parentx,area_parenty,area_cost,pos,playGround,goal):
cells=[]
#(-1-1)
if pos[0]-1 >= playGround[0] and pos[0]-1 <= playGround[1] and pos[1]-1 >= playGround[2] and pos[1]-1 <= playGround[3] and area_state[pos[0]-1][pos[1]-1] == 0:
cells.append([pos[0]-1,pos[1]-1]... |
def detected(area):
group_set(area, (10,10), (100,100))
group_set(area, (200,100),(202,400))
return area
def neighbour_cells(a,pos,playGround,area,orientation_last,cells_last):
cells=[]
orientation=[]
# print(orientation_last[0])
#(-1-1)
if pos[0]-1 >= playGround[0] and pos[0]-1 <= playG... | The code implements a pathfinding algorithm on a grid, navigating from a start position to predefined waypoints while avoiding obstacles. It uses a grid map with states (open, obstacle, closed) and dynamically updates the path using neighbor cell analysis and least-cost calculations. Real-time visualization with matplo... | def main():
playGround=[0,500,0,400]
cells_last=[[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0]]
area = [[1 for _ in range(playGround[3])] for _ in range(playGround[1])]
#print(area)
"""
0: new
1: open
-1: obstacle
2: closed
"""
plt.grid()
start = [1,1]
a=[100000,100... |
def obs_plot(x1,y1,x2,y2):
# plt.plot([x1,x2],[y1,y2],"-b")#12
# plt.plot([x2,x2],[y1,y2],"-b")#23
# plt.plot([x2,x1],[y2,y2],"-b")#34
# plt.plot([x1,x1],[y2,y1],"-b")#45
# plt.show()
a = sorted([x1, x2])
b = sorted([y1, y2])
#breakpoint()
plt.plot([a[0],a[1],a[1],a[0],a[0]],[b[0],b[... | The code implements a pathfinding algorithm on a 2D grid to navigate from a start point to multiple waypoints while avoiding obstacles. It initializes grid states, defines obstacles, and iteratively updates paths using neighbor cells. The algorithm visualizes the grid, plots waypoints, and traces the path from start to... | def main():
playGround=[0,100,0,100]
"""
0: new
1: open
-1: obstacle
2: closed
3: blocked
"""
plt.axis([0,100,0,100])
plt.grid()
start=[0,0]
waypoint=[[30,30],[20,30],[10,10]]
pos = start
a=[0,0]
area_parentx = [[0 for _ in range(playGround[3]+1)] for _ in ran... |
def init_malmo(self):
"""
Initialize new malmo mission.
"""
my_mission = MalmoPython.MissionSpec(self.GetMissionXML(), True)
my_mission_record = MalmoPython.MissionRecordSpec()
my_mission.requestVideo(800, 500)
my_mission.setViewpoint(1)
max_retries = 3
... | The code resets the environment for a new episode by reinitializing Malmo, updating tracking variables (episode returns and steps), logging if required, and returning a flattened initial observation. | def reset(self):
"""
Resets the environment for the next episode.
Returns
observation: <np.array> flattened initial obseravtion
"""
# Reset Malmo
world_state = self.init_malmo()
# Reset Variables
self.returns.append(self.episode_return)
... |
def route_pkt_datamulticast(pkt, routing_table, interface_table, sourcestr):#, rtrsocket):
#log_write("entered route_pkt_datamulticast\n")
selfid = list(routing_table.keys())[(list(routing_table.values())).index(['127.0.0.1',0,0])]
#log_write("computed selfid\n")
pkttype, seq, src, N, K, dst1, dst2, dst... | This function routes packets based on their type by calling specific handling functions. It checks the packet's type (0-5) and directs it to processes like multicast data, unicast data, centroid requests, or acknowledgments using routing and interface tables, along with the source information. The function ensures appr... | def route_packet(pkt, routing_table, interface_table, sourcestr):#, rtrsocket):
pkttype = pkt[0]
if pkttype == 0:
#log_write("pkttype == 0 \n")
route_pkt_datamulticast(pkt, routing_table, interface_table, sourcestr)#, rtrsocket)
elif pkttype == 1:
route_pkt_dataunicast(pkt, routing_t... |
def action(self) -> None:
# if enroute to a target node, keep moving
# if at target node, collect resource OR
# find new target
pass
def move(self) -> None:
"""Move to random neighboring node"""
# TODO: factor in edge type into speed
# if enroute to new... | The `step` method defines the sequence of actions performed by an entity during each local timestep, including executing an action, moving, and communicating. It orchestrates the entity's behavior, movement, and interaction in a simulated environment. | def step(self) -> None:
"""Defines what happens each local timestep"""
self.action()
self.move()
self.talk() |
def get_cms(dataset: pd.DataFrame, thresholds: np.ndarray, label: str) -> dict[float, dict[str, int]]:
# meh float as dict key is kinda bad
cms = {}
for threshold in thresholds:
eval = eval_classification(dataset, threshold)
cms[threshold] = get_confusion_matrix(eval, label, threshold)
... | The main task of the code is to determine the optimal classification threshold for a dataset by evaluating F1 scores on the test set. It splits the data, iterates through thresholds to compute confusion matrices, filters valid thresholds, identifies the threshold maximizing F1 score, and compares the best threshold's p... | def part_four(dataset: pd.DataFrame):
train, test = train_test_split(dataset, test_size=0.1, stratify=dataset["label"], random_state=42)
thresholds = np.arange(0.1, 1, 0.01)
cms = get_cms(test, thresholds, "A")
f_one_scores = []
ts = []
for t, cm in cms.items():
if cm["tp"] == 0:
... |
def calc_mcc_fone_curve(dataset: pd.DataFrame, thresholds: np.ndarray, label: str) -> set[np.ndarray, np.ndarray]:
un_mcc_scores = []
fone_scores = []
for threshold in thresholds:
eval = eval_classification(dataset, threshold)
cm = get_confusion_matrix(eval, label)
if(cm["tp"] == 0)... | The code generates and plots MCC-F1 and precision-recall curves for two datasets (A/B). It calculates scores across thresholds, visualizes trade-offs between metrics, and outputs key evaluation metrics like MCC-F1 and AUPR for each dataset. | def part_three(dataset: pd.DataFrame):
thresholds = np.arange(0.1, 1, 0.01)
fig = plt.figure(figsize=(1, 2))
for i, label in enumerate(("A", "B")):
un_mcc_scores, fone_scores = calc_mcc_fone_curve(dataset, thresholds, label)
print(f"mcc f1 score: {get_mcc_fone_score(un_mcc_scores, fone_score... |
def createCustomerTable(self, tbName):
try:
if self.checkTable(tbName):
cursor = self.tabs.cursor()
cursor.execute(Template("CREATE TABLE $table( \
`id` INT NOT NULL AUTO_INCREMENT PRIMARY kEY,\
`firstName` VARCHAR(225) NOT NULL... | The main task of the code is to register a new customer by inserting their details into the `customers` table, generating a unique account number, creating an associated account entry in the `accounts` table, initializing a deposit transaction, and returning the customer's data along with their account number. The func... | def registerCustomer(self, data, typy):
"""
CUSTOMER TABLE IS CREATED IF NOT EXISTS WITH PROVIDED DATA
"""
try:
# The following method creates the CUSTOMERS table if not created before:
self.createCustomerTable('customers')
cursor = sel... |
def train(self, n_iter=10, learning_rate=0.1):
""" Train model for n_iter iterations from scratch."""
# initialize latent vectors
np.random.seed(0)
self.user_vecs = np.random.randn(self.n_users, self.n_factors)
self.item_vecs = np.zeros((self.n_items, self.n_factors))
if... | The function `calculate_learning_curve` generates learning curves by tracking training and test Root Mean Squared Error (RMSE) at specified iteration intervals. It iterates through `iter_array`, training the model incrementally (either from scratch or via partial updates), predicting ratings, and computing RMSE for bot... | def calculate_learning_curve(self, iter_array, test=None, learning_rate=0.1):
"""
Keep track of MSE as a function of training iterations.
Params
======
iter_array : (list)
List of numbers of iterations to train for each step of
the learning curve. e.g. [1... |
def train(self, n_iter=10, learning_rate=0.1):
""" Train model for n_iter iterations from scratch."""
# initialize latent vectors
np.random.seed(0)
self.user_vecs = np.random.randn(self.n_users, self.n_factors)
self.item_vecs = np.zeros((self.n_items, self.n_factors))
if... | The code trains a model for a specified number of iterations, generates predictions, calculates root mean squared error (RMSE) for both training and test datasets using a scaler for normalization, and returns these error metrics to evaluate model performance. | def fetch_rmse(self, test, scaler, num_iter=200):
self.train(num_iter, learning_rate=self.learning_rate)
predictions = self.predict_all()
self.train_mse = get_rmse(predictions, self.ratings, scaler)
self.test_mse = get_rmse(predictions, test, scaler)
return self.train_mse, self.t... |
def _build_train_graph(self):
"""Build a training graph and savers."""
self._build_loss()
self.saver = tf.train.Saver()
# Create a saver for initializing resnet18 weights from imagenet.
vars_to_restore = [
v for v in tf.trainable_variables()
if v.op.name.s... | This code initializes a machine learning model with configurable parameters for training or inference, handling data loading, and setting up computational graphs. It accepts hyperparameters like learning rates, loss weights, image dimensions, and data augmentation flags. Depending on the 'is_training' flag, it construc... | def __init__(self,
data_dir=None,
file_extension='png',
is_training=True,
learning_rate=1e-4,
beta1=0.9,
reconstr_weight=0.85,
smooth_weight=1e-2,
ssim_weight=3.0,
bat... |
def make_get_color(color, labels):
if color:
return lambda obj_id: color
if labels:
palette = make_palette(labels.keys())
return lambda obj_id: palette[obj_id]
return lambda obj_id: 'white'
def print_results(inference_rate, objs):
print('\nInference (rate=%.2f fps):' % inferenc... | The code's main task is to perform real-time object detection using a model interpreter, sending processed images to a remote inference service via gRPC, and rendering detection results with overlays. It handles input tensor processing, model inference, result filtering, performance tracking (FPS), and dynamic overlay ... | def render_gen(args, stub):
fps_counter = utils.avg_fps_counter(30)
interpreters, titles = utils.make_interpreters(args.model)
assert utils.same_input_image_sizes(interpreters)
interpreters = itertools.cycle(interpreters)
interpreter = next(interpreters)
labels = utils.load_labels(args.labels... |
def load_trie_pickle(path):
"""
Loads Trie object from pickle file
:param path: path of file
:return: Trie object
"""
print('Started loading trie ' + path)
start = time.time()
with open(path, 'rb') as file:
trie = pickle.load(file)
# pickle.load(open(path, 'rb'))
end = ti... | The code processes an entire malicious URL dataset by evaluating how deeply each URL matches a benign trie structure. It calculates probability results and saves them as CSV files, focusing on the full malicious dataset rather than smaller subsets. The function measures processing time and stores outcomes for analysis. | def url_probability_dict_to_csv():
"""
Run probability tests on different csv sizes of malicious dataset.
Save result dictionary in csv files.
"""
# benign_trie_loaded = load_trie_pickle('Benign_1m_Trie.pickle')
benign_trie_loaded = load_trie_pickle('Benign_900k_Trie_Training_Set.pickle')
... |
def resolve_public_fns(module: ModuleType = None) -> List[FunctionType]:
if module is None:
module = sys.modules["__main__"]
# We only keep FunctionType because argspec works with those.
# This will exclude builtins and C-funtions.
fns = list(
fn
for n, fn in vars(module).items(... | (The code creates a main function that processes command-line arguments using an argument parser generated from provided functions or a module's public functions. It configures the parser with a description, resolves functions if none are given, and returns a callable that executes the parsed command, enabling CLI inte... | def make_main(
*fns: AnyCallable, module: ModuleType = None, description: str = None
) -> Callable[[Sequence[str]], Any]:
"""Creates a main method for the given module / list of functions.
The returned method expects a list of command line arguments.
"""
if module is None:
module = sys.modu... |
def get_preprocessed_data(spark: SparkSession, dt_from: dt.datetime, dt_to: dt.datetime, hdfs_dirs_input: List[str]):
# hdfs_dirs_input = [f"{_}/*.parquet" for _ in hdfs_dirs_input]
logging.info(f"Reading {hdfs_dirs_input}")
df = spark.read.schema(schema).parquet(*hdfs_dirs_input)
dt_from_extra = dt_fro... | This code processes data from HDFS using Apache Spark, filtering transactions by date ranges, and saves daily preprocessed data in Parquet format to both HDFS and S3. It initializes logging, parses command-line arguments for input/output paths, date ranges, and cloud storage configurations, then distributes processing ... | def main():
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s.%(msecs)03d %(levelname)s %(module)s - %(funcName)s: %(message)s',
datefmt='%Y-%m-%d %H:%M:%S',
)
parser = argparse.ArgumentParser()
parser.add_argument("--date_from", type=str, default=dt_today_str)
pa... |
def getMovieSchema():
genres = movieGenreRDD.map(lambda x: Row(**movieParser(x))).map(lambda x: x[1:])
genres = list(set(genres.flatMap(lambda x: x).collect()))
genres.sort()
genres = ["movieID"] + genres
schema = StructType([StructField(name, IntegerType()) for name in genres])
return schema
de... | The main task is to cluster movies by genre using Spark, vectorize features, determine optimal clusters (K=6), join with user ratings, compute average predicted ratings per user, and evaluate model performance using RMSE. The process involves data transformation, clustering, and evaluation to predict user preferences b... | def runTask1():
schema = getMovieSchema()
movieGenreWithValuesRDD = movieGenreRDD.map(lambda x: Row(**movieParser(x))).map(lambda x: fillInValues(schema, x))
df = spark.createDataFrame(movieGenreWithValuesRDD.collect(), schema)
dfVectorGenres = vectorizeFeatures(df)
dfVectorGenres.show()
# getOp... |
def createLine():
return line(.5, 0)
def readTrainingFile():
inputs = list()
outputs = list()
with open(TRAINING) as f:
lines = f.readlines()
for line in range(0, len(lines), 6):
if(lines[line].strip()=="OPINIONATED ARTICLE"):
outputs.append(1)
els... | The code's main task is to perform linear regression training and classification based on command-line input. If the argument is "yes", it trains a model using training data, saves it, and then loads the model to classify articles as opinionated or not. If "no", it skips training and directly uses the pre-trained model... | def main():
if(len(sys.argv)!=2 or (sys.argv[1]!='yes' and sys.argv[1]!='no')):
print("Error: python3 Linear_Regression -train[yes/no]")
else:
# If we want to retrain the linear regression algorithm
if(sys.argv[1]=="yes"):
ln=createLine()
trainingData, outputs=r... |
def get_or_create_board(self):
try:
resp = self.get_boards()
except ConnectionError as conn_err:
raise conn_err
try:
board_list = TrelloLists(items=resp)
except ValidationError as val_err:
raise val_err.errors()
# case I: empty lis... | The code initializes a Trello API client, retrieves or creates a board and list, and sets up predefined labels ("Maintenance," "Research," "Test," "Bug") for task categorization in a project management system. | def __init__(self):
self.__client = TrelloApi(TRELLO_APP_KEY, TRELLO_APP_TOKEN)
self.board_key = self.get_or_create_board()
self.list_key = self.get_or_create_list()
self.label_maintenance = self.get_or_create_label("Maintenance")
self.label_research = self.get_or_create_label("R... |
def _relpath(self):
"get the path to this brick relative to bblib"
return self.urlpath() / self.commit
def path(self):
return bblib() / self.urlpath() / self.commit
def url(self):
return f"{self.remote}#{self.commit}" | The code installs a BioBricks library brick by cloning a Git repository, configuring DVC with a remote and authentication, pulling required assets, and logging progress. It checks for existing bricks, sets up symlink permissions, and ensures proper DVC cache and remote configurations for data retrieval from dvc.biobric... | def install(self):
"install this brick"
logger.info(f"running checks on brick")
check_url_available(self.remote)
check_token(token())
check_symlink_permission()
if bblib(self.commit).exists():
logger.info(f"\033[91m{self.url}\033[0m already exists in BioBrick... |
def check_has_local_bblib():
if not local_bblib().exists():
raise Exception(".bb not found. run `biobricks init` first.")
def install(ref):
return Brick.Resolve(ref, force_remote=True).install()
def symlink_local_brick(brick):
check_has_local_bblib()
localpath = local_bblib() / brick.urlpath()
... | The code's main task is to add a brick by resolving it from a given reference, installing it, and creating a symbolic link to the local brick. It ensures the brick is fetched remotely if needed, checks for local dependencies, and sets up the necessary file links for usage. | def add(ref):
check_has_local_bblib()
brick : Brick = Brick.Resolve(ref, force_remote=True).install()
symlink_local_brick(brick) |
def pilihSIX():
print('''
Pilih menu :
1. Status Mahasiswa
2. Kelas
3. Control Panel
0. Sign out
''')
pilih = input("Pilih nomor menu: ")
if(not(pilih.isnumeric()) or int(pilih) < 0 or int(pilih) > 3):
clearScreen()
print("Menu tidak terdaftar! Silahkan coba lagi")
pilih = pilihSI... | The code defines a function `SIX` that acts as a menu-driven interface, repeatedly prompting the user to select options (1-3) to perform actions like checking student status, managing classes, or accessing a control panel. It uses parameters `akun`, `sudah`, `absen`, and `idx` to handle student data and operations, loo... | def SIX(akun, sudah, absen, idx):
pilih = 100
while(pilih != 0):
pilih = pilihSIX()
if(pilih == 1):
statusMahasiswa(akun, absen, idx)
elif(pilih == 2):
kelas(sudah, absen, akun, idx)
elif(pilih == 3):
controlPanel(akun, idx) |
def setup(self, password, password2):
"""
fucnction to set a master pasword
:param password: password to set
:param password2: confiirmation password
:return: None
"""
if not self.database.get_hashed_password():
if password == password2:
... | This function routes input commands to corresponding methods by checking the provided option. It executes actions like setup, login, logout, add, delete, get, aget, exit, or help based on the option's value, passing appropriate arguments to the respective methods. If the option is invalid, it sends an error message. | def parse_option(self, option, *args, **kwargs):
"""
Determine which function to run via the option provided
:return: None
"""
if option.lower() == "setup":
self.setup(args[0], args[1])
elif option.lower() == "login":
self.login(args[0])
e... |
def connect(self):
"""This method links the graph together in the gameboard config """
for i in range(self.dim):
pos = self.position(i)
n_c = [[pos[0]-1, pos[1]], [pos[0]+1, pos[1]], [pos[0], pos[1]+1], [pos[0],\
pos[1]-1], [pos[0]-1, pos[1]+1], [pos[0]+1, pos[1]-1], ... | The code initializes a grid structure with dimensions x_dim and y_dim, creating a list of linked lists for each cell. It connects these cells, sets up subgrids, edges, impassable areas, start/goal positions, and boundaries. The main task is to configure a grid-based environment for pathfinding or maze navigation, invol... | def __init__(self, x_dim, y_dim):
dim = x_dim * y_dim
self.dim = dim
self.lst = [0] * (dim)
for i in range(dim):
self.lst[i] = LinkedList(1, 1, i)
self.connect()
self.HTTx = [0] * 8
self.HTTy = [0] * 8
for i in range(8):
self.set_su... |
def textToAscii(text):
return ''.join(str(ord(c)) for c in text)
def numberToBase(n, b):
if n == 0:
return [0]
digits = []
while n:
digits.append(int(n % b))
n //= b
return digits[::-1]
def algorithm_encoding(m, p, s):
m_tuple = numberToBase(m, p)
k = len(m_tuple) + 1... | The code converts the text "hi" to ASCII, encodes it using a base-p representation, applies an encoding algorithm, generates a polynomial coefficient, decodes it, and converts the result back to ASCII to reconstruct the original text. | def main_code():
text = "hi"
ascii_text = int(textToAscii(text))
print("Text in ascii:" + f'{ascii_text}')
p = 11
m = numberToBase(ascii_text, p)
print("m:" + f'{m}')
y, k = algorithm_encoding(ascii_text, p, 1)
print("y:" + f'{y}')
z = generate_z(y, p)
print("z:" + f'{z}')
r... |
def MCTS(init_M=init_position, policy_M=policy, n_in_M=n_direction0, pn_r=0.8):#Monte Carlo tree search
bwalk = np.zeros((2, mtmax), dtype=float)#walking trajectory in MCTS
bwalk[:, 0] = init_M#initial position of a MCTS
bwalk_d = np.zeros(mtmax, dtype=int)#data of selected direction
distance_M = np.sqr... | The code simulates a random walk using Monte Carlo Tree Search (MCTS) to navigate from an initial position toward a target. It iteratively evaluates policies, updates direction counts, and adjusts movement probabilities based on distance and MCTS iterations. The walk continues until reaching within 20 units of the targ... | def random_walk(init_a=init_position, policy_a=policy, value_a=value, n_MCTS=repeat_MCTS):#Actual Walk
twalk = np.ones((2, tmax), dtype=float) * -10000
twalk[:, 0] = init_a
n_direction = n_direction0#Initialize N to [1,1,1,1] at any location
distance_a = np.sqrt(np.sum((init_a - target)**2))
pn = 0.... |
def get_site_info(vcf_row, dad_idx, mom_idx):
"""
Extract relevant data about site from VCF line.
:param vcf_row: String of site data from VCF.
:param dad_idx: The index of the dad's genotype information.
:param mom_idx: The index of the mom's genotype information.
:return: Chromosome, position, motif length (per... | This function processes a variant line to check genotype validity by analyzing read support from parental BAM files. It identifies the longest genotype, counts allele occurrences, validates support, annotates uncallable de novo mutations, and updates the row with allele support information. | def check_variant(line, dad_idx, mom_idx):
row = line.rstrip().split('\t')
if row[6] != 'PASS':
return None
chrom, pos, motif_length, motif, ref_length, dad_gt, mom_gt = get_site_info(row, dad_idx, mom_idx)
next_seq, prev_seq = get_flanking_sequences(chrom, pos, motif_length, ref_length, ref)
longest_gt = get... |
def Street(t, p , c, s, tMode):
if tMode == False:
# Print cards #
if s == 1:
# print FLOP community cards
print("*** FLOP *** [", end="")
print(' '.join([str("{}{}".format(card.rank, card.suit)) for card in c.flop]), end="")
print("]")
elif ... | The function `newHand` simulates a poker hand by dealing cards, posting blinds, managing community cards (flop, turn, river), and executing betting rounds (pre-flop, flop, turn, river). It initializes player hands, handles chip adjustments, and triggers showdowns if multiple players remain. The code also resets the tab... | def newHand(t, deck, SB, BB, tMode):
cCards = CommunityCards()
#set button relative to players left in play
btn = t.players.index(t.seats[t.button])
# print button position
if tMode == False:
print("{} - seat #{} is the button".format(t.name, t.players[btn].seat))
#print player s... |
def check_keydown_events(event, settings, screen, ship, aliens, bullets, stats, score):
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_SPACE:
fire(settings, screen, ship, bullets)
elif e... | The function `check_events` processes user inputs in a Pygame game, handling keyboard and mouse events. It exits the game on quit, triggers keydown/up actions for ship movement and shooting, and checks mouse clicks to activate the play button. Events are delegated to helper functions for specific tasks like updating sh... | def check_events(settings, screen, ship, aliens, bullets, stats, play_button, score):
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.KEYDOWN:
check_keydown_events(event, settings, screen, ship, aliens, bullets, stats, score... |
def check_edges(settings, aliens):
for alien in aliens.sprites():
if alien.check_edges():
change_direction(settings, aliens)
break
def ship_hit(settings, screen, ship, aliens, bullets, stats, score):
if stats.ship_left > 0:
stats.ship_left -= 1
score.prep_ships()
... | The function updates alien movement, checks for collisions between the ship and aliens, and verifies if aliens have reached the screen's bottom. It triggers responses like ship damage or game-over conditions when collisions or bottom-bound aliens occur, managing game state and interactions between the ship, aliens, and... | def update_aliens(settings, screen, ship, aliens, bullets, stats, score):
check_edges(settings, aliens)
aliens.update()
if pygame.sprite.spritecollideany(ship, aliens):
ship_hit(settings, screen, ship, aliens, bullets, stats, score)
check_aliens_bottom(settings, screen, ship, aliens, bulle... |
def _printProgress(self, model):
if model < 1000 and model % 200 == 0:
print(f'Collecting model: {model}', end='\r')
if model >= 1000 and model % 1000 == 0:
print(f'Collecting model: {model}', end='\r')
def _calcIntermediatesGeom(self, df, resid) -> (np.cross, np.array):
... | The code calculates dihedral angles (Alpha, Theta1, Theta2) from PDB data stored in a DataFrame. It iterates through models and residue ranges, using helper functions to extract coordinates and compute angles. Results are stored in a dictionary, then converted to a DataFrame for geometric analysis of molecular structur... | def _collectGeometry(self):
# '''Calculate dihedrals with data collected from pdb file.
# Dihedrals are stored in DataFrame object
#
# It iterates over all frames and (min + 1; max -1) residues indexes range
# It follows the same algorithm as _collectData method. Helper sunftions... |
def _typeC(self, atom):
if not atom['type'] and atom['id'] in self.backbone:
if len(atom['bonds']) == 3:
h, c, n, o = self._countELE(atom)
# print(h, c, n, o)
if o == 2 and n == 1:
# print('===TYPE C===')
atom['t... | This function determines an atom's type based on its element. It checks the 'element' key in the atom dictionary and assigns the corresponding type (e.g., 'C', 'N', 'O') by calling specialized methods like _typeC, _typeN, etc. For hydrogen atoms, it directly sets the type to 'H'. The function modifies the atom's type i... | def _update_type(self, atom):
"""Higher level function to disciminate an atomtype of atom.
Parameters:
atom (dict): a dictionary of parameters of an atom
set up in add_atom method
Returns: None
"""
# print(self.CT, self.NT, self.backbone, ... |
def _findbyID(self, id):
"""Helper function. Searches list of dictionaries to find dict by id value"""
for atom in self.atoms:
if atom['id'] == id:
return atom
def _update_type(self, atom):
"""Higher level function to disciminate an atomtype of atom.
Paramete... | The main task of the code is to parse a molecular backbone structure, updating each atom's 'type' and 'resid' parameters. It iterates through backbone atoms, increments 'resid' at 'N' type atoms, and propagates these updates via BFS traversal to connected atoms, ensuring consistent residue assignments across the struct... | def _parse(self):
"""Parsing backbone and updating its parameters.
Updating: type, resid
"""
resid = 1
for backatom in self.backbone:
backatom = self._findbyID(backatom)
if backatom['type'] == 'N':
resid += 1
# print(backatom)
... |
def _findN(self):
"""Find N elements. Those are starting points for BFS walker
in backbone finding task"""
for atom in self.atoms:
if atom['element'] == 'N':
self.Ns.append(atom['id'])
def _findCT(self):
"""Find CT atomtype. This is C-terminus of macromolecule... | The main task of the code is to execute the class's methods sequentially: `_findN()`, `_findCT()`, `_findNT()`, and `_parse()`, likely to process or analyze data by identifying elements, connections, and structures, then parsing the results. The `run()` method orchestrates these steps to fulfill the class's core functi... | def run(self):
"""Run the methods of the class"""
self._findN()
self._findCT()
self._findNT()
self._parse() |
def lin_inter(self, point):
point_before = np.trunc(point)
A_matrix = np.zeros((2**self.dimension, 2**self.dimension))
b_matrix = np.zeros((2**self.dimension, 1))
for index, bool in enumerate(itertools.product([False, True], repeat=self.dimension)):
combinations = [[1]]
... | This code performs a 1D line search using a fixed step size to find a descent direction. It increments alpha, evaluates the function at new points, and returns the bisection result when an ascent is detected, indicating a suitable interval for minimizing the function. | def descent_1D(self):
alpha = 0
step = 0
self.step_size = self.resolution/10
point = self.point
point_value = self.lin_inter(point)
while True:
step += 1
alpha += self.step_size
new_point_value = self.projection_1D(point, alpha)
... |
def gradient(self):
grad = np.zeros((self.dimension, 1))
for i in range(self.dimension):
vector = np.zeros((self.dimension, 1))
vector[i] = self.resolution
grad[i] = deriv_1st(
self.lin_inter(self.point - 2*vector),
self.lin_inter(self.... | The code implements the steepest descent algorithm to minimize a function. It iteratively updates the current point by moving in the direction of the negative gradient, scaled by a step size determined via a 1D descent method. The process repeats until the change in function value falls below a tolerance threshold or r... | def steepest_descent(self):
step = 0
tolerance = 1e-5
self.direction = -1*self.gradient()/np.linalg.norm(self.gradient())
while step < 500:
step_size = self.descent_1D()
if self.debug:
print(f'''Step {step}:
point: {np.transpose(self.point)}^T
en... |
def find_router_for_ip(routers, ip):
"""
Search a dictionary of routers (keyed by router IP) to find which
router belongs to the same subnet as the given IP.
Return None if no routers is on the same subnet as the given IP.
FOR FULL CREDIT: you must do this by calling your ips_same_subnet()
fun... | This function implements Dijkstra's algorithm to find the shortest path in a network graph between a source and destination IP. It identifies the source and destination routers using a helper function, initializes distances and parent pointers, and iteratively relaxes edges to compute the shortest path. The result is a... | def dijkstras_shortest_path(routers, src_ip, dest_ip):
"""
This function takes a dictionary representing the network, a source
IP, and a destination IP, and returns a list with all the routers
along the shortest path.
The source and destination IPs are **not** included in this path.
Note that ... |
def get_next_message(s):
#checking to make sure we have a valid word packet
if len(buffer_list[s]) >= 2:
encoded_word_length = buffer_list[s][:2]
packet_length = int.from_bytes(encoded_word_length, "big") + 2 #decode passed packet length
#check to ensure there is a full word packet i... | This code implements a multi-client server using I/O multiplexing with `select()`. It listens on a specified port, accepts incoming connections, buffers incoming data, and distributes messages to all connected clients. It handles "hello" handshake messages to assign client names and broadcasts regular chat messages. Di... | def run_server(port):
#read set storing sockets
read_set = set()
listen = socket.socket()
listen.bind(('', port))
print("Waiting for connections...")
listen.listen()
read_set.add(listen)
# main loop:
while(True):
# call select() and get the sockets that are ready t... |
def usage():
print("usage: dijkstra.py infile.json", file=sys.stderr)
def read_routers(file_name):
with open(file_name) as fp:
data = fp.read()
return json.loads(data)
def find_routes(routers, src_dest_pairs):
for src_ip, dest_ip in src_dest_pairs:
path = dijkstras_shortest_path(routers... | The code processes a router configuration file by reading JSON data, extracting router and source-destination lists, then computing routes using the `find_routes` function. It handles command-line input, validates the router file name, and returns an error if invalid. | def main(argv):
try:
router_file_name = argv[1]
except:
usage()
return 1
json_data = read_routers(router_file_name)
routers = json_data["routers"]
routes = json_data["src-dest"]
find_routes(routers, routes) |
def getusaddress(addr):
address = usaddress.parse(addr)
m = 0;street = "";city = "";state = "";pcode = ""
while m < len(address):
temp = address[m]
if temp[1].find("Address") != -1 or temp[1].find("Street") != -1 or temp[1].find('Occupancy') != -1 or temp[1].find("Recipient") != -1 or temp[1... | The code extracts healthcare provider details (NPI ID, name, addresses, taxonomy, contact info) from the NPI Profile website by scraping HTML tables, processes address data, validates addresses via external APIs, and returns structured JSON results with error handling for missing entries. | def checknpiid(npiid):
headers = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36',
'x-requested-with': 'XMLHttpRequest'}
url = 'https://npiprofile.com/npi/'
if len(npiid) < 2:
return json.dumps({'status':'... |
def _message_control(self) -> None:
response: Dict = self._read_message()
log.debug("HEARTBEAT")
if "Alive" in response.keys():
# Write it back
self._state = State.HEARTBEAT
self._send_message(response)
elif "JobConfig" in response.keys():
... | The code manages a state machine that continuously checks and processes different states. It loops while in the HEARTBEAT state, calling _message_control() for heartbeats. If the state is READ_JOB, it processes job configurations; if PROCESSING, it handles job data via callbacks. The loop ensures state-specific actions... | def _begin_state_machine(self):
# Check the message for authentication successfull
while True:
# Keep looping while heartbeating
while self._state == State.HEARTBEAT:
self._message_control()
# If it is a job config, evaluate it
if self._... |
def _connect_to_sock(self):
"""
Connects to the DCL for communications.
"""
try:
self._sock.connect(self._address)
except ConnectionRefusedError:
log.error(f"Could not connect to address: {self._address[0]}")
sys.exit(1)
log.info(f"Suc... | The main task of the code is to connect to the Sybl service by validating prerequisite parameters (access token, model ID, and callback), establishing a socket connection, authenticating the access token, and initializing a state machine for further interactions. It raises errors if required components are missing or a... | def connect(self):
"""
Connects to the Sybl service
Parametes:
None
Returns:
None
Raises:
AttributeError: raised when accesstoken or model id has not been loaded
PermissionError: raised when the access... |
def get_and_conv_data():
df = pd.read_csv('data/smaller_data/small_ratings_copy.csv',low_memory=False)
df.columns = ['User', 'Item', 'ItemRating', 'timestamp']
# print(df)
ans = df.pivot_table(values='ItemRating', index='Item', columns='User')
# print(ans.fillna(0))
print(len(ans))
return an... | The code integrates new data into an existing matrix, normalizes it, and generates top recommendations using collaborative filtering techniques. It reshapes input data, concatenates it with the matrix, applies normalization, and computes recommendations based on similarity, returning the final top recommendations. | def solve(data_to_add,M=None):
M = (get_and_conv_data())
data_to_add = np.array(data_to_add)
data_to_add = data_to_add.reshape(data_to_add.shape[0], -1)
# print(len(M[lenlast-1]),len(M))
# data_to_add.append(M)
# print(data_to_add)
altM = []
# M = np.column_stack((M,data_to_add))
# p... |
def get_and_conv_data():
df = pd.read_csv('data/smaller_data/small_ratings_copy.csv', low_memory=False)
df.columns = ['User', 'Item', 'ItemRating', 'timestamp']
# print(df)
ans = df.pivot_table(values='ItemRating', index='User', columns='Item')
# print(ans.fillna(0))
# print(len(ans))
return... | The code performs matrix factorization for collaborative filtering to predict user ratings. It initializes random matrices P and Q, updates them via iterative optimization (with parameters alpha, beta, and 5000 iterations), and computes final predicted ratings as the dot product of optimized P and Q. The result is a ma... | def solve(data_to_add):
# define constants
alpha = 0.0002
beta = 0.02
iterations = 5000
similarities = 2
R = (get_and_conv_data())
# R = np.vstack([R, data_to_add])
Q = np.random.rand(len(R[0]), similarities)
P = np.random.rand(len(R), similarities)
fP, fQ = update_factors(R, P,... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.