dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def positions_csv_to_dataframe(positions_csv_text):
'''Import CSV-formatted table of positions (and options) to a DataFrame object'''
df = None
try:
positions_list = positions_csv_text.split('\n')
positions_list[0] = positions_list[0].lower()
positions_csv_text_lowercase_column_headi... | The function validates a CSV table of astronomical positions by checking column headers, ensuring each row contains either RA/DEC coordinates or a COADD_OBJECT_ID (not both), verifying numerical parameters against predefined ranges, validating boolean flags, and checking color strings for FITS and RGB settings. It retu... | def validate_positions_table(positions_csv_text):
msg = ''
valid_column_headers = [
'ra',
'dec',
'coadd_object_id',
'xsize',
'ysize',
'colors_fits',
'rgb_stiff_colors',
'rgb_lupton_colors',
'rgb_minimum',
'rgb_stretch',
'rgb... |
def validate_config(conf):
# Cutout positions table must be present
if 'positions' not in conf or not isinstance(conf['positions'], str):
msg = 'Invalid cutout positions table'
logger.error(msg)
return False, msg
# User-defined defaults must be valid
valid, msg = validate_user_de... | The code processes astronomical cutout requests by querying a database for tile information, generating FITS and RGB image files based on configuration parameters, and managing parallel processing. It validates input, constructs cutout tables, handles coordinate and coadd ID positions, creates output directories, and l... | def run(conf):
# Configure logging
formatter = logging.Formatter('%(asctime)s - '+str(rank)+' - %(levelname)-8s - %(message)s')
logger.setLevel(logging.INFO)
logger.addHandler(logging.StreamHandler())
# Local directory where generated output files will be stored
if not conf['outdir']:
l... |
def calcul_A(x,y,z):
n = len(x)
Det_P1 = sumXY(x,z)*(n*power2sum(y)-sum(y)**2)-(sumXY(x,y)*(n*sumXY(y,z)-sum(z)*sum(y)))+(sum(x)*(sumXY(y,z)*sum(y)-sum(z)*power2sum(y)))
Det_P = (power2sum(x) * n * power2sum(y)) - (power2sum(x) * sum(y) ** 2) - (sumXY(x, y) * n * sumXY(x, y)) + ( sumXY(x, y) * sum(x) * sum(... | The code reads a file containing 3D data points, extracts x, y, z arrays, calculates regression coefficients (a, b, c) using custom functions, and computes predicted z-values (zA) via linear combination of x and y. It returns coefficients, input data, and predictions for 3D linear regression analysis. | def Regresion3D(NamFile):
with open(NamFile) as f:
array = []
for line in f: # read rest of lines
array.append([float(x) for x in line.split()])
yarray = []
for x in range(len(array)):
yarray.append(array[x][1])
xarray = []
for x in range(len(array)):
xar... |
def _exec(self,command):
self._writeline(command+b"\n")
self._expect(command+b"\n")
def _wait_for(self, text):
line = b''
while not line.startswith(text):
line = self._readline()
def _read_sample_line(self):
line = b''
while not line.endswith(b'\n'):
... | The code reads sampling data lines, decodes them using a SampleDecoder, and constructs an ScpTrack object with a single revolution containing decoded bitcell data and a fixed timestamp. It starts sampling, waits for completion, processes each line until the end marker, then returns the structured track data. | def read_track(self):
decoder = SampleDecoder()
self._exec(b"start_sampling")
self._wait_for(self.START_SAMPLING)
line = self._read_sample_line()
while not line.startswith(self.END_SAMPLING):
decoder.processLine(line)
line = self._read_sample_line()
... |
def _exec(self,command):
self._writeline(command+b"\n")
self._expect(command+b"\n")
def _expect(self, expected):
line = self._readline()
if not line.startswith(expected):
raise Exception(f"Expected bytes starting with {expected} but got {line}")
def _wait_for_prompt(self):
... | The code executes the 'home' command, verifies the success response, and waits for a prompt, likely automating a system interaction or command-line task. | def home(self):
self._exec(b"home")
self._expect(b"Success!")
self._wait_for_prompt() |
def _exec(self,command):
self._writeline(command+b"\n")
self._expect(command+b"\n")
def _expect(self, expected):
line = self._readline()
if not line.startswith(expected):
raise Exception(f"Expected bytes starting with {expected} but got {line}")
def _wait_for_prompt(self):
... | The code sends a command to seek a specific track, verifies success via response, and waits for the next prompt. | def seek_track(self,track):
self._exec(b"seek_track " + bytes(str(track), 'utf-8'))
self._expect(b"Success!")
self._wait_for_prompt() |
def home(self):
self._exec(b"home")
self._expect(b"Success!")
self._wait_for_prompt()
def seek_track(self,track):
self._exec(b"seek_track " + bytes(str(track), 'utf-8'))
self._expect(b"Success!")
self._wait_for_prompt()
def read_track(self):
decoder = SampleDecode... | The main task of the code is to read multiple tracks from a storage medium by homing the device, sequentially seeking each track, reading its data, and compiling the tracks into an SCP file format with a predefined header. The function returns a structured ScpFile object containing the collected tracks and metadata lik... | def read_side(self, total_tracks):
tracks = []
print("Homing...")
self.home()
print("reading track", end="")
for track in range(0,total_tracks-1):
print(f" {track}")
self.seek_track(track)
tracks.append(self.read_track())
... |
def get_yMax(self):
for param in self.data:
for outData in self.data[param]:
if outData != "input":
for dataType in self.data[param][outData]:
tempMax = max(self.data[param][outData][dataType])
try:
... | This code initializes an object to process and visualize sensitivity analysis data. It normalizes input data, sets up output directories, generates plots (if enabled), and exports results to CSV files. The main tasks include data normalization, plot creation, directory management, and data export for sensitivity analys... | def __init__(self, data, outFolderName, defParams, idmRatio, plot = True):
self.idmRatio = idmRatio
self.plot = plot
self.data = data
self.defParams = defParams
self.yMax = {}
self.yMax = self.get_yMax()
self.xMax = {}
self.xMax = self.get_xMax()
s... |
def XAssert(cond):
return Assert(And(cond, Int(currentframe().f_back.f_lineno)))
def is_creator():
return Txn.sender() == Global.creator_address()
def get_entry_count():
return GetByte(read_slot(SYSTEM_SLOT_INDEX), Int(0))
def inc_entry_count(prevCount):
return GlobalBlob.write(SYSTEM_SLOT_INDEX * Int(S... | The code allocates a new slot for a specific ASA by verifying the caller is the creator, checking entry count limits, incrementing the count, marking the slot as allocated, logging the action, and approving the transaction. | def alloc_new_slot():
#
# Allocates a new slot for a particular ASA.
# Argument 1 must be ASA identifier.
#
entryCount = ScratchVar(TealType.uint64)
return Seq([
XAssert(is_creator()),
entryCount.store(get_entry_count()),
XAssert(entryCount.load() <= Int(MAX_PRICE_SLOTS))... |
def XAssert(cond):
return Assert(And(cond, Int(currentframe().f_back.f_lineno)))
def is_creator():
return Txn.sender() == Global.creator_address()
def check_group_tx():
#
# Verifies that group contains expected transactions:
#
# - calls/optins issued with authorized appId (Wormhole Core).
# ... | The main task of the code is to validate and store Pyth price attestations in a smart contract. It verifies the sender's ownership, transaction group validity, and Pyth payload structure (magic header, version, attestation count). It processes each attestation by checking ASA ID-slot mappings, ensuring timestamps are u... | def store():
# * Sender must be owner
# * This must be part of a transaction group
# * All calls in group must be issued from authorized Wormhole core.
# * Argument 0 must be array of tuple (ASA ID, slot) corresponding to each of the attestations that corresponds
# to valid prices to update. If an... |
def bootstrap():
op_pool = OpPool()
return Seq(
op_pool.maximize_budget(Int(2000)),
App.globalPut(Bytes("coreid"), Btoi(Txn.application_args[0])),
GlobalBlob.zero(),
# Enable the testing-mode flag.
If(Tmpl.Int("TMPL_I_TESTING"), set_sys_flag(Int(128))),
Approve()... | This code defines a smart contract program that handles various transaction operations (create, update, delete, opt-in, no-op) by validating conditions and executing corresponding logic. It ensures transactions comply with security rules (e.g., no rekeying or closing funds) and routes NoOp transactions to specific meth... | def pricecaster_program():
handle_create = Return(bootstrap())
handle_update = Return(is_creator())
handle_delete = Return(is_creator())
handle_optin = Return(Int(1))
handle_noop = Cond(
[METHOD == Bytes("store"), store()],
[METHOD == Bytes("alloc"), alloc_new_slot()],
[METHO... |
def check(self):
self.checkKvmModule()
def setupDependencies(self):
'''
install libvirt and qemu packages
:return:
'''
setupQemu()
setupLibvirt()
pass
def startupServices(self):
Execmd("systemctl enable libvirtd && systemctl start libvirtd ").get(r... | The `provision` method's main task is to prepare a system by first checking prerequisites, then setting up required dependencies, and finally initializing and starting essential services to ensure the system is functional and ready for use. | def provision(self):
self.check()
self.setupDependencies()
self.startupServices() |
def _split_server_name(self, server_path: str) -> Tuple[str, str, str]:
service_path, server_name = server_path.rsplit("/", 1)
service_name = self._split_service_name(service_path)
return service_path, service_name, server_name
def _close_channels(self, servers: Iterable[ServerInfo]) -> None:
... | This function handles ZooKeeper node events by updating or removing service entries based on event types (CHANGED, NONE, DELETED). When a node changes or is deleted, it retrieves service/server info from the path, removes the server from the services dictionary, and closes associated channels. For data changes with val... | def data_watcher(self, data: Optional[bytes], stat: Optional[ZnodeStat], event: Optional[WatchedEvent],
path: str) -> Optional[bool]:
if event is None or event.type == EventType.CHANGED or event.type == EventType.NONE:
if stat is None:
_, service_name, server_nam... |
def parse_args() -> argparse.Namespace:
argparser = argparse.ArgumentParser()
argparser.add_argument("mode", choices=['validate', 'fix', 'releases'])
argparser.add_argument("path", help="root directory to scan for audio releases")
argparser.add_argument('--show-violations', action='store_true',
... | This script processes music releases by validating, fixing, and organizing them based on command-line arguments. It checks source/destination folders, handles invalid/duplicate releases, and uses a Last.fm cache for validation. Depending on the mode (validate/fix/releases), it either validates releases, fixes metadata,... | def main():
args = parse_args()
src_folder = os.path.abspath(args.path)
if not os.path.isdir(src_folder):
raise ValueError("Invalid source folder: {0}".format(src_folder))
dest_folder = None
if args.move_fixed:
dest_folder = os.path.abspath(src_folder)
elif args.move_fixed_to:
... |
def encoding_layer(input_data, input_size, num_rnn_nodes,
num_rnn_layers):
"""Defines the encoding layer of the seq2seq model.
Returns:
A tuple (enc_output, enc_state) containing the output and input of the
encoder. The output is a tensor of shape [batch_size, ?, 1], and the
enco... | The code defines a sequence-to-sequence (seq2seq) model using RNNs, processing input and output tensors through an encoder and decoder. The encoder extracts state from input data, while the decoder generates outputs using the encoder state, a go token, and target data. It returns training and inference decoder outputs ... | def seq2seq_model(input_data, output_data, input_size, output_size,
go_token, num_rnn_nodes, num_rnn_layers, regularizer):
"""Define the sequence to sequence model.
Args:
input_data: tensor of shape [batch_size, input_size=?, 1].
output_data: tensor of shape [batch_size, output_size=?, 1]... |
def reset_data(self):
'''Doc'''
self.previous_cordinate_x = ''
self.previous_cordinate_y = ''
self.previous_time = 0
self.registered_events = 0
self.previous_event_type = ""
self.previous_shot_distance = 0
self.previous_shot_angle = 0
self.current_... | The function processes game data for a specified model by checking if the current game ID matches the input. If not, it resets data. It retrieves raw game data, extracts team info, initializes penalty boxes, checks for new events, logs status, cleans data, and returns processed info, test data, goals, and predictions. ... | def ping_game(self, game_id, model):
'''Doc'''
if self.current_game_id != game_id:
self.reset_data()
self.current_game_id = game_id
game_raw_data = self.get_game_raw_data(game_id)
if game_raw_data != {}:
gral_info = self.get_game_gral_info(game_raw_data)
... |
def get_time_seconds(mm_ss):
'''Doc'''
minute, second = mm_ss.split(":")
period_time = ( int(minute) * 60 ) + int(second)
return period_time
def check_penalty_boxes(self, period, period_time):
'''Doc'''
time = self.to_full_time_length(period, self.to_time(period_time))
... | The main task of the code is to process sports event data (e.g., hockey plays) by mapping event types, shot types, and coordinates to encoded numerical features. It tracks previous states (position, time, event type) to calculate metrics like shot distance, angle, speed, rebounds, and penalties. The function returns a ... | def get_play_info(self, event):
'''Doc'''
mapping_events = {
'Blocked Shot': 0,
'Faceoff': 1,
'Game Official': 2,
'Giveaway': 3,
'Goal': 4,
'Hit': 5,
'Missed Shot': 6,
'Official Challenge': 7,
'Pe... |
def __delta_card(self):
return np.random.randint(1, 13)
def __bust(self, cards, hands):
if self.__score(cards, hands) > 21:
return True
else:
return False
def __score(self, cards, hands):
if self.__usable_ace(cards, hands):
return sum(hands) + 10
... | This code simulates a turn in a card game (likely Blackjack) where a player can choose to 'Hit' (draw a card) or 'Stick' (stop). If 'Hit', it checks for a bust (exceeding 21) and returns a reward. If 'Stick', the dealer draws cards until reaching 17, then compares scores with the player to determine reward. The functio... | def play(self, action):
done = False
if action == 'Hit':
k = self.__delta_card()
self.players_hand.append(self.cards_value[k])
self.players_cards.append(self.cards[k])
bust = self.__bust(self.players_cards, self.players_hand)
if bust:
... |
def compute_total_distance(road_map):
"""
Returns, as a floating point number, the sum of the distances of all
the connections in the `road_map`. Remember that it's a cycle, so that
(for example) in the initial `road_map`, Wyoming connects to Alabama...
"""
if len(road_map) > 2:
lats_lon... | The code's main task is to find the optimal route (shortest distance) by performing 10,000 iterative swaps on a given road map. It alternates between two strategies: first applying 5,000 swaps using `swap_cities`, then 5,000 using `swap_adjacent_cities`. After each swap, it updates the route and calculates the total di... | def find_best_cycle(road_map):
"""
Using a combination of `swap_cities` and `swap_adjacent_cities`,
try `10000` swaps, and each time keep the best cycle found so far.
After `10000` swaps, return the best cycle found so far.
"""
new_road_map = road_map[:]
cycle_distance = compute_total_dista... |
def read_cities(file_name):
"""
Read in the cities from the given `file_name`, and return
them as a list of four-tuples:
[(state, city, latitude, longitude), ...]
Use this as your initial `road_map`, that is, the cycle
Alabama -> Alaska -> Arizona -> ... -> Wyoming -> Alabama.
"""
... | The main task of the code is to read city data from a file, display the cities, determine the optimal travel cycle (likely solving a traveling salesman problem), and print the optimal route. The code uses functions to load the data, visualize the cities, compute the best path, and output the result. Your return | def main():
"""
Reads in, and prints out, the city data, then creates the "best"
cycle and prints it out.
"""
road_map = read_cities('data/city_data.txt')
print_cities(road_map)
optimal = find_best_cycle(road_map)
print_map(optimal[0]) |
def tree(label,branches=[]):
for branch in branches:
assert is_tree(branch),'branches must be tree'
return [label] + list(branches)
def label(tree):
return tree[0] | The function generates a binary tree representing Fibonacci numbers recursively. Each node's label is the sum of its two children's labels, with left and right subtrees corresponding to fib_tree(n-2) and fib_tree(n-1). The base case creates a leaf node with label n. The tree structure mirrors the Fibonacci sequence's r... | def fib_tree(n):
if n <= 1:
return tree(n)
else:
left,right = fib_tree(n-2),fib_tree(n-1)
return tree(label(left)+label(right),[left,right]) |
def draw(self):
screen.fill(BLACK)
title_font = pygame.font.Font('assets/fonts/font.ttf', 44)
content_font = pygame.font.Font('assets/fonts/font.ttf', 24)
title_text = title_font.render('Memory Cards Game', True, WHITE)
title_rect = title_text.get_rect(midtop=(WINDOW_WIDTH // 2... | The code's main task is to update the game state by rendering the current view, processing user inputs via event_list, and checking if the current level is completed based on the events. It orchestrates visual updates, input handling, and progress checks in a game or interactive application. | def update(self, event_list):
self.draw()
self.user_input(event_list)
self.check_level_complete(event_list) |
def map_information(data):
engine = Engine()
part_number = 1
symbol_number = 1
for y, line in enumerate(data):
start = True
number = ''
symbol = ''
for x, character in enumerate(line):
if x == 0:
start = True
if character.isdigit():... | The main task of the code is to process mechanical data by identifying engine parts based on uniqueness, summing their values, and calculating gear ratios. It maps input data to engine components, flags parts with multiple unique attributes, aggregates valid parts, and outputs their total sum alongside derived gear rat... | def main():
engine_parts, symbol_list = map_information(data)
for k,v in engine_parts.items():
if len(v["Unique"]) > 1:
engine_parts[k]["Engine_Part"] = True
else:
engine_parts[k]["Engine_Part"] = False
part_values = []
for k,v in engin... |
def get_comparison_result_filename(output_path, output_file, output_extension, _start_time):
result_file = ""
compare_prefix = f"fosslight_compare_{_start_time}"
if output_file != "":
result_file = f"{output_file}{output_extension}"
else:
if output_extension == XLSX_EXT or output_extensi... | The main task of the code is to compare two FOSSLight reports (YAML/XLSX files) by converting them to YAML if needed, then generating a comparison result. It validates file extensions, converts XLSX to YAML, compares the YAML outputs, and writes differences to a specified file. If successful, it logs the result file pa... | def run_compare(before_f, after_f, output_path, output_file, file_ext, _start_time, _output_dir):
ret = False
before_yaml = ''
after_yaml = ''
logger.info("Start compare mode")
logger.info(f"before file: {before_f}")
logger.info(f"after file: {after_f}")
before_ext = f'.{os.path.basename(be... |
def get_time_entries_from_toggle_and_structure_them(range):
start_date = calculate_start_date_from_range(range)
raw_time_entries = toggl_client.get_time_entries(start_date, YESTERDAY)
structured_entries = structure_raw_entries_by_day_and_user(raw_time_entries)
return structured_entries
def calculate_wor... | This function processes a date range to retrieve and structure time entries, calculates workdays per user for each day, and converts the result into a string format for output. | def get_workdays_for_users_per_day(range):
structured_entries = get_time_entries_from_toggle_and_structure_them(range)
workdays = calculate_workdays_for_users_per_day(structured_entries)
return convert_data_to_string_structure(workdays) |
def get_time_entries_from_toggle_and_structure_them(range):
start_date = calculate_start_date_from_range(range)
raw_time_entries = toggl_client.get_time_entries(start_date, YESTERDAY)
structured_entries = structure_raw_entries_by_day_and_user(raw_time_entries)
return structured_entries
def calculate_wor... | The main task of the code is to calculate the efficiency percentage of each user per day by comparing their effective working time against total workdays, returning the result either as a dictionary or a string-formatted structure based on the `return_dict` parameter. | def get_efficiency_percentage_per_user_per_day(range, return_dict=False):
structured_entries = get_time_entries_from_toggle_and_structure_them(range)
workdays = calculate_workdays_for_users_per_day(structured_entries)
effective_times = calculate_effective_times(structured_entries)
efficiency_per_user_pe... |
def get_efficiency_percentage_per_user_per_day(range, return_dict=False):
structured_entries = get_time_entries_from_toggle_and_structure_them(range)
workdays = calculate_workdays_for_users_per_day(structured_entries)
effective_times = calculate_effective_times(structured_entries)
efficiency_per_user_pe... | The main task of the code is to calculate the average efficiency per user over a specified range. It retrieves daily efficiency percentages for each user, computes their average efficiency within the range, and returns the result in a string-based data structure. | def get_avrg_efficiency_per_user_in_range(range):
efficiency_per_user_per_day = get_efficiency_percentage_per_user_per_day(
range, return_dict=True
)
avrg_efficiency_per_user_in_range = calculate_avrg_efficiency_per_user_in_range(
efficiency_per_user_per_day
)
return convert_data_to_... |
def get_efficiency_percentage_per_user_per_day(range, return_dict=False):
structured_entries = get_time_entries_from_toggle_and_structure_them(range)
workdays = calculate_workdays_for_users_per_day(structured_entries)
effective_times = calculate_effective_times(structured_entries)
efficiency_per_user_pe... | The function calculates and returns the daily efficiency of a specified user within a given range by retrieving efficiency data, verifying user presence, and formatting results. If the user is not found, it returns an error message. | def get_efficiency_of_set_user_per_day(range, set_user):
efficiency_per_user_per_day = get_efficiency_percentage_per_user_per_day(
range, return_dict=True
)
if check_if_user_in_entries(efficiency_per_user_per_day, set_user):
efficiency_of_set_user_per_day = calculate_efficiency_of_set_user_p... |
def get_efficiency_percentage_per_user_per_day(range, return_dict=False):
structured_entries = get_time_entries_from_toggle_and_structure_them(range)
workdays = calculate_workdays_for_users_per_day(structured_entries)
effective_times = calculate_effective_times(structured_entries)
efficiency_per_user_pe... | The code calculates the average efficiency of a specified user over a given time range by retrieving daily efficiency data, verifying user existence, computing the average, and formatting the result as a string. If the user isn't found, it returns an error message. | def get_avrg_efficiency_of_set_user_in_range(range, set_user):
efficiency_per_user_per_day = get_efficiency_percentage_per_user_per_day(
range, return_dict=True
)
if check_if_user_in_entries(efficiency_per_user_per_day, set_user):
efficiency_of_set_user_per_day = calculate_efficiency_of_set_... |
def classGivenTerm(self, _class, term):
"""
Computes P(Ci|t)
"""
denominator = self.countDocs(term)
numerator = self.countDocsPerClass(_class, term)
if (denominator == 0):
return 0
else:
return numerator/denominator
def termGivenNotClass(self, _class, term):
"""Computes P(t|~Ci)
"""
denominat... | The code computes the Distinguishing Feature Selector (DFSi) for a given class-term pair using probabilistic ratios. It calculates P(Ci|t) divided by the sum of 1, P(t|~Ci), and P(~t|Ci), returning the normalized score to assess term-class relevance. | def DFSi(self, _class, term):
""" term: string.
DFS: Distinguishing Feature Selector
DFSi(t) = P(Ci|t)
-----------------------
1 + P(t|~Ci) + P(~t|Ci)
DFS(t) = sum(DFSi(t))
"""
return self.classGivenTerm(_class, term) / (1 + self.termGivenNotClass(_class, ... |
def check_if_player_won(self):
return self.check_if_symbol_won(1)
def check_if_computer_wins_by_completing_sequence_of_three_consecutive_symbols_of_2(self):
if self.search_on_lines_sequence_of_three_consecutive_same_symbols(2) == True or \
self.search_on_columns_sequence_of_three_consecutive_sam... | The function determines the computer's move in a game by checking if it can win immediately by completing three consecutive '2's, block the player's potential win, or make a random move if neither is possible. It returns -1 if the player has already won, -2 if the computer wins, 0 if the computer blocks the player or m... | def play_computer(self):
#######################################verificam daca a castigat playerul
if self.check_if_player_won() == -1:
return -1
############daca playerul nu a castigat, verificam daca ar putea sa castige computerul acum(adica daca exista 3 elemente consecutive de 2... |
def get_scripts_path(creator_name: str, mods_dir: str, mod_name: str = "Untitled") -> str:
"""
This builds a path to the Scripts folder inside the Mod Folder
:param creator_name: Creator Name
:param mods_dir: Path to the Mods Folder
:param mod_name: Name of Mod
:return: Path to Scripts folder i... | This function creates a directory junction symlink in Windows to enable dev mode for a mod, removing any existing mod files first. It links a source directory to a mod's scripts folder, allowing real-time changes without recompilation. It prints instructions for using dev mode, reloading modules, and exiting back to no... | def symlink_create_win(creator_name: str, src_dir: str, mods_dir: str, mod_name: str = "Untitled") -> None:
"""
Creates a symlink, it first wipes out the mod that may be there. When entering devmode, you don't compile anymore,
so any compiled code needs to be removed.
:param creator_name: Creator Name
... |
def get_courses(nim, df_merged):
student_df = df_merged[df_merged['id_mhs'] == nim]
courses = student_df['kd_kuliah'].tolist()
return courses
def content_based_recommender(course, amount, sim_matrix, df_cont):
closest_title, distance_score = find_closest_title(df_cont, course)
similar_cours... | The function generates personalized course recommendations for students based on their enrolled courses using a content-based approach. It aggregates recommendations, merges duplicates by summing scores, ranks them by relevance, and returns a sorted list of top recommendations for all students matching a specific ID pr... | def generate_recommendation_content(no_ps_penyelenggara, df_merged, df_cont, sim_matrix):
list_stu = df_merged['id_mhs'].unique().tolist()
list_rec = []
for t in [x for x in list_stu if str(x).startswith(no_ps_penyelenggara)]:
list_rec_stu = []
list_exp = get_courses(t, df_merged)
fo... |
def setDictionaryStrategy(self):
for keys, values in self.boardStatus.items():
if values[0] == 0:
values[4] = "N/A"
elif values[0] - values[2] == values[3]:
values[4] = "NeighborsAreBombs"
elif values[0] == values[2]:
values[4] ... | This method initializes game pieces by iterating through the board's status. For each piece, it checks if neighbors are bombs or safe, applying flag settings or revealing neighbors accordingly. It uses strategies to handle different game states, ensuring proper piece configuration based on neighbor conditions. | def initializePieces (self) :
for keys, values in self.boardStatus.copy().items():
self.setDictionaryStrategy()
if values[4] == "NeighborsAreBombs":
piece = self.getPiece(keys)
self.setAllFlag(piece)
elif values[4] == "NeighborsAreSafe... |
def setDictionaryStrategy(self):
for keys, values in self.boardStatus.items():
if values[0] == 0:
values[4] = "N/A"
elif values[0] - values[2] == values[3]:
values[4] = "NeighborsAreBombs"
elif values[0] == values[2]:
values[4] ... | The main task of the code is to initialize game pieces on a board by setting flags or revealing neighbors based on predefined conditions. It iterates through the board's status dictionary, applying different strategies: setting flags for cells marked "NeighborsAreBombs" and revealing adjacent cells for those marked "Ne... | def initializePieces (self) :
for keys, values in self.boardStatus.copy().items():
self.setDictionaryStrategy()
if values[4] == "NeighborsAreBombs":
piece = self.getPiece(keys)
self.setAllFlag(piece)
elif values[4] == "NeighborsAreSafe... |
def get_sentences_para(paragraph):
sentences = sent_tokenize(paragraph)
words = word_tokenize(paragraph)
# Get a list of English stopwords
stop_words = set(stopwords.words('english'))
# Remove stopwords and punctuation
filtered_words = [word.lower() for word in words if word.isalnum() and word.lower() not in s... | The code summarizes a paragraph by splitting it into sentences, removing periods from each, processing them (via an undefined `get_sentence` function), recombining them into a new paragraph, and returning both the original and summarized versions in a dictionary. | def get_summerized_paragraph(paragraph):
sentences = get_sentences_para(paragraph)
best_sentences = []
for sentence in sentences:
best_sentence = get_sentence(re.sub(r'\.', '', sentence))
best_sentences.append(best_sentence)
summerized_para = create_para(best_sentences)
print(summerized_para)
return... |
def create_format_starting_value_column_request(
sheet_id: int,
starting_row: int,
starting_column: int,
ending_column: int,
show_plus_minus: bool ) -> List[dict]:
bold = True
italic = False
return create_format_value_column_request(
sheet_id,
starting_row,
star... | This function applies specific formatting to designated columns in a Google Sheet using the Google Sheets API. It identifies column indices based on headers and applies formatting rules to spread, moneyline, over/under, and movement columns. Conditional formatting for Kenpom-related columns is applied if enabled. The f... | def format_all_value_columns(
service: Resource,
spreadsheet_id: str,
sheet_id: int,
format_kenpom: bool) -> bool:
sheets = service.spreadsheets()
requests = []
starting_row = 3 # maybe?
# format starting spread, moneyline
# also apply this for the updated spread and moneyline col... |
def format_conditional_formatting(
service: Resource,
spreadsheet_id: str,
sheet_id: int) -> bool:
sheets = service.spreadsheets()
requests = []
format_conditional = create_conditional_formatting_rules_request(
sheet_id)
for request in format_conditional:
requests.append(r... | The function formats a Google Sheet by applying conditional formatting (if update is False), formatting value columns (with KenPom-specific rules if enabled), adjusting column widths automatically, and updating the "last updated" timestamp. It returns True upon completion. | def format_sheet(
service: Resource,
spreadsheet_id: str,
sheet_id: int,
sheet_name: str,
last_updated: str,
update: bool,
format_kenpom: bool) -> bool:
if not update:
format_conditional_formatting(
service,
spreadsheet_id,
sheet_id)
form... |
def get_spreadsheet_service() -> Resource:
is_service_account = True
credentials = get_credentials(
#GOOGLE_CREDENTIALS_FILE_LOCAL,
GOOGLE_SERVICE_ACCOUNT_FILE,
is_service_account,
GOOGLE_API_SCOPES)
if not credentials or (not is_service_account and not credentials.valid):
... | This function creates a spreadsheet from event data by generating sheets for each event group, adding formatted event rows, headers, and applying styles. It returns the spreadsheet ID and provides a URL for access. | def create_new_spreadsheet_from_events(
title: str,
event_groups: List[DraftKingsEventGroup]) -> str:
service = get_spreadsheet_service()
if not service or len(event_groups) == 0:
return ''
spreadsheet_id = create_new_spreadsheet(
service,
title)
for event_group in eve... |
def get_spreadsheet_service() -> Resource:
is_service_account = True
credentials = get_credentials(
#GOOGLE_CREDENTIALS_FILE_LOCAL,
GOOGLE_SERVICE_ACCOUNT_FILE,
is_service_account,
GOOGLE_API_SCOPES)
if not credentials or (not is_service_account and not credentials.valid):
... | This function updates a spreadsheet with event data from provided event groups by adding new events, updating existing ones, formatting cells, and clearing obsolete entries. It interacts with a spreadsheet service, processes event details, syncs betting choices to a database, and temporarily generates HTML visualizatio... | def update_spreadsheet_from_events(
spreadsheet_id: str,
event_groups: List[DraftKingsEventGroup]) -> bool:
service = get_spreadsheet_service()
if not service or len(event_groups) == 0:
return False
for event_group in event_groups:
sheet_name = event_group.sheet_name
even... |
def is_installed(target):
installed = get_installed()
dirname = os.path.dirname(__file__)
filters = os.path.join(dirname, "filters")
return bool(target in installed.keys() and target in os.listdir(filters))
def download_filter(target):
config = get_config()
repo = config["repo"]
url = repo +... | The code's main task is to check if a target filter is installed; if not, download it and mark it as installed. It first verifies installation status, triggers a download if absent, then updates the installation record. | def fetch_filter(target):
if is_installed(target):
print("%s is already installed" % target)
else:
download_filter(target)
update_installed(target) |
def get_config():
dirname = os.path.dirname(__file__)
path = os.path.join(dirname, "config.json")
try:
with open(path, "rb") as f:
config = f.read()
config = json.loads(config)
except FileNotFoundError:
config = dict(
hash_alg="sha256",
rep... | The code updates installed filter files by comparing their last modified timestamps and hash values with metadata. If metadata shows a newer timestamp and different hash, it downloads the updated filter and updates the installed records. | def update_filters():
config = get_config()
hash_alg = config["hash_alg"]
installed = get_installed(hash_alg)
metadata = update_metadata()
for target in installed.keys():
if target in metadata.keys():
here_data = installed[target]
there_data = metadata[target]
... |
def byrValid(byr):
return len(byr) == 4 and 1920 <= int(byr) <= 2002
def iyrValid(iyr):
return len(iyr) == 4 and 2010 <= int(iyr) <= 2020
def eyrValid(eyr):
return len(eyr) == 4 and 2020 <= int(eyr) <= 2030
def hgtValid(hgt):
units = hgt[-2:]
hgt = hgt[:-2]
if units == 'in':
if len(hgt) ... | The code processes input data split into passport blocks, validates each passport's fields (like byr, iyr, eyr, hgt, hcl, ecl, pid) using helper functions, and counts how many passports meet all validation criteria. It returns the total count of valid passports. Your return | def sol2(data):
ct = 0
data = '\n'.join(data).split('\n\n')
for pp in data:
pp = ' '.join(pp.split('\n'))
keys = {}
pairs = pp.split(' ')
for pair in pairs:
key, value = pair.split(':')
keys[key] = value
if (
'byr' in keys and byr... |
def validate_move(self, index, player=None):
if player is None:
player = self.current_player
self.check_win()
if self.game_over:
raise AttributeError("Game is over. Cannot play further moves.")
if index2player(index) != player:
raise ValueError("Inval... | The function `make_move` executes a player's turn in a board game by distributing marbles from a selected index counter-clockwise, applying Rule 3 (stealing marbles if landing in an empty hole), checking for game-ending conditions, and updating the game state. It adjusts indices, validates moves, logs actions, and swit... | def make_move(self, current_index, verbose=True, adjust_index=False):
"""
:param current_index: Index to play
:param verbose: Print what happened
:param adjust_index: Automatically flip the index (flip the board)
:return:
"""
if adjust_index:
current_i... |
def end_game(game_id):
# This function is run when a game is ended.
# It sends the log to both of the players in the Game Over message.
game = games[game_id]["game"]
usernames = [clients[client]["name"] for client in games[game_id]["users"]]
winner = game.winner
# Adjust the log so it includes ... | This function removes a user from a game, logs their departure as a "surrender" event, ends the game if active, and notifies the remaining player. It also handles edge cases like empty lobbies and sends custom messages if provided. | def kick_from_game(client, message=None):
# Kick user from game
in_game = clients[client]["current_game"]
if in_game is None:
raise AttributeError("Cannot kick a user from a game if they're not in one.")
return
clients[client]["current_game"] = None
name = clients[client]["name"]
... |
def simple_message(user, msgtype, data="", additional_args=None):
# Generate a simple message JSON and send it
if additional_args is None:
additional_args = {}
message = {
"type": msgtype,
"data": data
}
for arg in additional_args:
message[arg] = additional_args[arg]... | The code handles a client connection by registering a unique name, processing messages (normal, visible commands, private commands), managing game interactions (starting/joining games, moves, restarts), and handling errors. It validates user input, maintains game states, logs actions, and ensures proper session managem... | def handle_client(client): # Takes client socket as argument.
"""
Handles a single client connection.
This is done by first registering a valid name.
Then we handle every message, from normal, Commands everyone can see,
and commands only the user can see.
"""
try:
taken_names = [x[... |
def calc_factors_distances(self, entry, differential=0):
for order, (each_entity, factor) in enumerate(zip(entry, self.factors)):
# print(order)
# print(each_entity, factor)
# for entity, factor in zip(entry[:self.order],self.factors):
self.target_vectors[order] =... | This code calculates a gradient component for a specific factor in a descent step by multiplying three terms: the difference between observed and projected values, the derivative of the tanh function scaled by a factor, and the differential of the input entry relative to the target factor index. | def calc_descent(self, entry,target_factor_ind):
obseved_val = entry[-1]
sum_distance = self.calc_factors_distances(entry)
term1 = 2 * (obseved_val - self.projection_tanh(sum_distance))
term2 = (-self.phai) * (1 - np.tanh(sum_distance) ** 2)
term3 = self.calc_defferential_1(entry... |
def calc_descent(self, entry,target_factor_ind):
obseved_val = entry[-1]
sum_distance = self.calc_factors_distances(entry)
term1 = 2 * (obseved_val - self.projection_tanh(sum_distance))
term2 = (-self.phai) * (1 - np.tanh(sum_distance) ** 2)
term3 = self.calc_defferential_1(entry... | The function updates a specific factor in a tensor decomposition model using alternating gradient descent/ascent steps. It adjusts the factor matrix entries based on calculated gradients, Lipschitz constraints, and error metrics, iterating 10 times. Gradient descent applies when the current error exceeds a threshold, w... | def update_factor_gradient(self,target_factor_ind,optimized_entity,loss,tensor,entry):
g_w = self.l0
gradient_descent = 0
n_inner_iter = 10
for _ in range(n_inner_iter):
if g_w >= self.l0:
# gradient Descent
# setup gamma
n_v... |
def list_type_from_UID(listUID):
# Dictionary with the type of lists based on list code
type_dictionary = {
"SL": "SHOPLIST",
"TL": "TODOLIST",
"CL": "CHECKLIST"
}
list_code = listUID[:2]
try:
list_type = type_dictionary[list_code]
except:
list_type = "T... | The main task of the code is to display a specific list (shoplist, todolist, or checklist) to users if they have viewing permissions. It retrieves list data from cache or the database, checks user authentication and access rights (owner or shared status), and renders the appropriate HTML template with the list content ... | def list_viewer(request, listUID):
"""
This is the list viewer.
This page presents the lists and all of it's content (if the user has privilege to see it).
No modification can be made or saved to the list itself.
"""
element_type = list_type_from_UID(listUID)
cache_key = element_type + list... |
def list_type_from_UID(listUID):
# Dictionary with the type of lists based on list code
type_dictionary = {
"SL": "SHOPLIST",
"TL": "TODOLIST",
"CL": "CHECKLIST"
}
list_code = listUID[:2]
try:
list_type = type_dictionary[list_code]
except:
list_type = "T... | The main task of this code is to handle user access control for editing a list (adding/deleting items) and rendering the appropriate editor interface based on the list type. It checks user authentication, authorship, and sharing permissions, then displays the list editor (shoplist/todolist/checklist) or redirects to a ... | def list_editor(request, listUID):
"""
This is the list editor.
Here a user (if it has privileges) can edit a list by adding items or
deleting them.
Only the list author can change the privacy settings for the list or delete the list.
"""
#Choose the correct type of list
list_type = list... |
def load_data_v2():
top_follows = load_steamdb_ranking()
top_wishlists = load_steam_ranking()
return top_follows, top_wishlists
def load_data_v1():
top_follows = sort_by_followers()
top_wishlists = load_manual_wishlist_snapshot()
return top_follows, top_wishlists
def run_statistical_analysis(... | The main task of the code is to load data (either version 1 or 2) based on the input parameter, perform statistical analysis on the loaded data, and return True, with optional verbose output. The function handles two data-loading variants and executes analysis accordingly. | def main(version=1, verbose=True):
if version > 1:
top_follows, top_wishlists = load_data_v2()
else:
top_follows, top_wishlists = load_data_v1()
run_statistical_analysis(top_follows, top_wishlists, verbose=verbose)
return True |
def get_swapped_subpath(self, edge_a: Edge, edge_b: Edge) -> List[City]:
swapped_subpath = [edge_a.first_city]
tmp = self.get_subpath(edge_a.idx + 1, edge_b.idx)
tmp.reverse()
swapped_subpath += tmp
swapped_subpath.append(edge_b.second_city)
return swapped_subpath
def cos... | The function calculates a swapped subpath between two edges and computes the cost difference compared to the original path. It returns the swapped subpath and a 'diff' value, where smaller values indicate better improvements. The function skips swaps if edges are too close or in invalid order, ensuring only valid swaps... | def calc_swap(self, edge_a: Edge, edge_b: Edge):
"""
:param edge_a:
:param edge_b:
:return: (subpath, diff)
diff: smaller is better
"""
# Currently I don't implement former swap
if edge_a.idx > edge_b.idx:
return [], None
# Current... |
def get_city(self, idx: int) -> City:
if idx < self.size():
return self.stops[idx]
elif idx == self.size():
return self.stops[0]
else:
raise IndexError('Index of stops out of range.')
def calc_swap(self, edge_a: Edge, edge_b: Edge):
"""
:param ... | The function `try_swap` identifies the optimal subpath to swap with a given index in a list of cities, aiming to minimize cost. It evaluates potential swaps by comparing edge differences, selects the best improvement, and updates the path if a beneficial swap is found. | def try_swap(self, idx: int, cities: List[City]) -> None:
best_diff = 0
best_subpath = None
for city in cities:
target_idx = self.city_to_idx[city.id]
edge_a = Edge(idx - 1, self.get_city(idx - 1), self.get_city(idx))
edge_b = Edge(target_idx, self.get_city(ta... |
def size(self):
return len(self.stops)
def get_city(self, idx: int) -> City:
if idx < self.size():
return self.stops[idx]
elif idx == self.size():
return self.stops[0]
else:
raise IndexError('Index of stops out of range.')
def _get_neighbor_cities(self... | The code iterates through a list of cities, checking every 9th element (idx % 10 == 9). For each such city, it retrieves non-prime neighboring cities and attempts to swap the current city with one of these neighbors to optimize a path or configuration, likely in a route-planning or graph traversal algorithm. | def improve_9th(self):
for i in range(self.size()):
idx = i + 1
if idx % 10 == 9:
city = self.get_city(i)
neighbor_cities = self._get_neighbor_cities(city, filter_prime=True)
self.try_swap(idx, neighbor_cities) |
def size(self):
return len(self.stops)
def get_city(self, idx: int) -> City:
if idx < self.size():
return self.stops[idx]
elif idx == self.size():
return self.stops[0]
else:
raise IndexError('Index of stops out of range.')
def _get_neighbor_cities(self... | The main task of the code is to iteratively improve a path by swapping each city with its neighbors. It loops through each city, retrieves its neighboring cities, and attempts a swap to optimize the path. This process likely aims to enhance the efficiency of a route, such as in a traveling salesman problem, by evaluati... | def improve_one_by_one(self):
for i in range(self.size()):
idx = i + 1
city = self.get_city(i)
neighbor_cities = self._get_neighbor_cities(city, filter_prime=False)
self.try_swap(idx, neighbor_cities) |
def append_MACD(self,fastperiod=12, slowperiod=26, signalperiod=9):
macd, macdsignal, macdhist = ta.MACD(self.data['close'].to_numpy(), fastperiod=fastperiod, slowperiod=slowperiod, signalperiod=signalperiod)
self.data.loc[::,'MACD'] = macd
def append_RSI(self,period= 14):
delta = self.data['clo... | This function prepares financial data for a MultiLayerPerceptron model by appending technical indicators (MACD, RSI, WilliamsR), computing patterns, converting data to candlestick format, slicing data with an offset, and generating optimized labels for machine learning training. | def prep_MultiLayerPerceptron(self,offset=0):
self.append_MACD()
self.append_RSI()
self.append_WilliamsR()
self.compute_patterns()
self.data = self.recognize_candlesticks(self.data)
self.change_to_candlestick()
self.data = self.data[offset:]
self.get_optim... |
def append_all(self,spec=[]):
"""Append all indicators found in talib, used for feature selection
spec - a list of specific talib functions as returned by InputTrials.(selection_function) to be used to create a new dataset
"""
inputs = {
'open' : self.data['open'].astype(floa... | This function prepares data for training after feature selection by appending specified Talib features, adjusting labels with an offset, converting data to candlestick format, and optionally saving processed data to a CSV file. It slices the dataset, optimizes labels, handles missing values, and exports numerical data ... | def prep_select_features(self,features,offset=0,savedir=None):
""" function to be run after feature selection using InputTrials, will prepare data for training with newly determined features
features - list of talib function features to be appended"""
self.append_all(spec=features)
self.... |
def problem_1():
l = float(input("Enter the length of pipe: "))
k = float(input("Enter the average height of roughness: "))
Q = float(input("Enter the discharge: "))
D = float(input("Enter the diameter of pipe: "))
nu = float(input("Enter the kinematic viscosity: "))
# l = 400
# k = 0.00025
... | The main task of the code is to prompt the user for a problem number (1, 2, or 3) and execute the corresponding function (problem_1, problem_2, or problem_3) based on the input, acting as a menu-driven interface for selecting and running different problem-solving tasks. | def main():
scanf = int(input("Enter the problem number: "))
if scanf == 1:
problem_1()
elif scanf == 2:
problem_2()
elif scanf == 3:
problem_3() |
def print_board(self):
"""Print the current game board."""
for row in range(3):
print('|'.join(self._board[row]))
if row < 2:
print('-----')
def mark(self, i, j):
"""Put an X or O mark at position (i,j) for the next player's turn."""
if not (0 <= i... | The code implements a Tic Tac Toe game where the player ('X') and bot ('O') take turns making moves. It validates player input, handles invalid moves, checks for a winner or tie after each move, and declares the result when the game ends. | def play(self):
"""Start the game and play until there's a winner or a tie."""
print("Let's play Tic Tac Toe!")
print("You are 'X' and the bot is 'O'.")
print("Enter row and column numbers to make a move.")
print("Rows and columns are 0-indexed.")
while True:
... |
def usage():
"Help"
print("Usage: openstacksrv2ssh.py [options] -a | [ENV [ENV [...]]]")
print("Creates ~/.ssh/ENV.sshcfg files from OpenStack server lists.")
print("-a (or --all) iterates over all cloud configs known and also generates")
print(" ~/.ssh/openstacksrv.sshcfg referencing all non-empty ... | The main task of the code is to process cloud configurations based on command-line arguments, handling options like verbose/debug mode, and generating SSH config files. It parses flags to determine actions (e.g., process all clouds or specific ones), retrieves cloud data from environment variables if needed, processes ... | def main(argv):
"Entry point for main program"
doall = False
global DEBUG, VERBOSE, QUIET
try:
optlist, args = getopt.gnu_getopt(argv, "havdq",
("help", "all", "verbose", "debug", "quiet"))
except getopt.GetoptError as exc:
print("Error:", exc, file=sys.stderr)
re... |
def preprocess_data_playlist(
raw_data, user_playlist_file, spotify_conn, rf_model, kn_model
):
"""@raw_data: list of songs with their features from db
@user_playlist: csv with uris
@return: pre-processed set of songs incl user_song"""
playlist = pd.read_csv(user_playlist_file)
# pick random 20... | The code generates personalized music recommendations by loading a user's playlist, preprocessing Spotify data with machine learning models, applying KNN for recommendations, filtering by weather conditions, and visualizing results in a table. It integrates Spotify API, database queries, and ML models to deliver contex... | def main():
user_input_playlist = "Nishant2500.csv"
# parse configs and extablish connections to
# Spotfiy and the database
config, secrets = parser.setup()
sp = Spotify(config=config, secrets=secrets)
db = Database(config=config, secrets=secrets)
db_data = db.get_all_data("spotify")
#... |
def _compute_minimizer(z: np.ndarray, M: np.ndarray,
X: np.ndarray) -> np.ndarray:
# minimizer = np.sum(hat_vect_matrix*X.T , axis=1) <--- explicit but memory inefficient form
# vect_of_norms = (hat_vect_matrix * hat_vect_matrix).sum(axis=1)
# vect_of_norms[vect_of_norms<1e-8] = 1
... | The code performs an alternating minimization optimization algorithm to estimate parameters `u` and `v` by iteratively minimizing their gradients. It uses gradient norms (`eps_g`, `eps_params`) and iteration limits (`max_iter`) as stopping criteria. The algorithm alternates between updating `u` and `v` using `_compute_... | def fit(self,
eps_g: float = 1e-8,
eps_params: float = 1e-16,
max_iter=1000) -> np.ndarray:
grad_u = np.ones(self.u.shape[0]) * np.inf
grad_v = np.ones(self.v.shape[0]) * np.inf
theta_dim = self.u.shape[0] + self.v.shape[0]
latest_theta = np.ones(theta... |
def _compute_sparse_minimizer(hat_vect_matrix: sparse.csr_matrix,
X: sparse.csr_matrix) -> np.ndarray:
# compute numerator part of minimizer, this will yield a dense vector (size of u or v)
minimizer = (hat_vect_matrix.multiply(X)).sum(axis=1)
# divide by norm squared of masked... | The code performs iterative optimization of parameters `u` and `v` using gradient descent. It alternates between minimizing `u` and `v` with respect to a sparse matrix `M` and data matrix `X`, updating them until gradients fall below thresholds (`eps_g`, `eps_params`) or max iterations (`max_iter`) are reached. It trac... | def fit(self,
eps_g: float = 1e-8,
eps_params: float = 1e-16,
max_iter=1000) -> np.ndarray:
grad_u = np.ones(self.u.shape[0]) * np.inf
grad_v = np.ones(self.v.shape[0]) * np.inf
theta_dim = self.u.shape[0] + self.v.shape[0]
latest_theta = np.ones(theta... |
def spatial_feature_extract(
feature_results, feature_contents, offset_x_meshgrid, offset_y_meshgrid
):
"""
Extract spatial features from feature maps
:params:
feature_results: list of torch.Tensor objects
feature_contents: list of torch.Tensor objects
offset_x_meshgrid: np.array... | The code calculates a combined loss for neural style transfer by computing content loss between the result and content images, and style loss (including remd and moment components) between the result and style images. It weights these losses using content_weight and style_weight, then normalizes the total loss. The sty... | def calculate_loss(feat_result, feat_content, feat_style, indices, content_weight):
"""
Calculate the loss between the result and the content and style images.
:params:
feat_result: the feature map of the result image
feat_content: the feature map of the content image
feat_style: the... |
def get_graph(path, to_networkx=True):
read_graph = RxnGraph()
read_graph.from_file(path)
print("Total number of reactions =", len(read_graph.reactions))
print("Total number of species =", len(read_graph.species))
if to_networkx:
return read_graph.to_netwokx_graph()
else:
read_gr... | The code calculates the distribution of maximum shortest path lengths from three specific nodes ("[H]\t\n", "[O][C][O]\t\n", "*\t\n") to all string-type nodes in a graph. It counts how many nodes have each maximum distance value and prints the distribution. The main task is to analyze and report the distance distributi... | def main():
date_str = "15122021"
path = "../data/rxn_net_30112021.rxn"
G = get_graph(path, to_networkx=True)
# res = percolation_test(G, 50, 5, "../results/15122021/percolation.csv", step_size=5)
dist_d = {}
for node in G:
if type(node) is str:
dist = max(len(shortest_path(G... |
def get_graph(path, to_networkx=True):
read_graph = RxnGraph()
read_graph.from_file(path)
print("Total number of reactions =", len(read_graph.reactions))
print("Total number of species =", len(read_graph.species))
if to_networkx:
return read_graph.to_netwokx_graph()
else:
read_gr... | The code generates visualizations of reaction network properties. It loads a graph from a file, plots degree distribution, shortest path ranks, and distributions of atom counts/molar mass, saving figures in a date-specific directory. | def make_plots(date_str: str):
path = "../data/rxn_net_30112021.rxn"
image_dir = "../results/{}".format(date_str)
G = get_graph(path)
plot_degree_distribution(G, image_dir=image_dir, add_poiss=False)
analyze_covers(False)
plot_shortest_path_ranks(G, image_dir)
rxn_graph = get_graph(path, Fal... |
def key(key: str) -> bool:
return keyboard.is_pressed(key)
def loadMap(self, levelMap: list):
self.levelMap = levelMap
for i in range(100):
if self.levelMap[i] == 4:
self.xVelocity = 0
self.yVelocity = 0
self.goto(
(i % ... | This code handles player movement in a game, processing key inputs for movement and jumping, applying velocity changes with friction and gravity, clamping velocities to maximum limits, detecting collisions with environment elements like bouncy blocks, and adjusting position incrementally to handle collisions, resetting... | def movement(self, frameDelta: float):
# Detect keystrokes
if key("r"):
self.loadMap(self.levelMap)
if key("w") or key("space") or key("up"):
if self.onGround():
self.yVelocity = self.Y_MOVEMENT_PER_SECOND
if key("a") or key("left"):
... |
def key(key: str) -> bool:
return keyboard.is_pressed(key)
def loadMap(self, levelMap: list):
self.levelMap = levelMap
for i in range(100):
if self.levelMap[i] == 4:
self.xVelocity = 0
self.yVelocity = 0
self.goto(
(i % ... | This code handles player movement in a game, processing keyboard inputs for movement and jumping, applying velocity changes with frame delta, enforcing speed limits, detecting collisions with environment elements, adjusting position based on physics (gravity, friction), and managing interactions with bouncy blocks and ... | def movement(self, frameDelta: float):
# Detect keystrokes
if key("r"):
self.loadMap(self.levelMap)
if key("w") or key("space") or key("up"):
if self.onGround():
self.yVelocity = self.Y_MOVEMENT_PER_SECOND
if key("a") or key("left"):
... |
def parse_args():
"""
Parse command-line arguments
"""
parser = argparse.ArgumentParser()
parser.add_argument(
"-w",
"--write",
help="Write modified files to disk (use with caution)",
action="store_true",
default=False,
)
parser.add_argument(
"... | The code's main task is to parse and sort code in specified files using the `parso` library. It reads each file, parses its code into an abstract syntax tree, applies sorting via `sort_node`, and checks if modifications occurred. If changes are detected, it updates the file (with optional backup) or reports them. The f... | def main():
args = parse_args()
diffed_files = []
for fname in args.filename:
with open(fname) as fptr:
code = fptr.read()
tree = parso.parse(code)
root = tree.get_root_node()
sort_node(root)
modified_code = root.get_code()
if modified_code != co... |
def get_char(self):
self.char=[]
alphabet=False
for i,page in enumerate(self.pages):
if i!=0:
for paragraph in page:
if isinstance(paragraph, LTTextContainer):
for line in paragraph:
if isinstance... | The code initializes an object to process a file by extracting pages, parsing characters and root nodes, building a tree structure, and sorting the root nodes for structured document analysis or processing. | def __init__(self,file_path):
self.pages=extract_pages(file_path)
self.get_char()
self.get_root()
self.build_tree()
self.root.sort() |
def convert_coordinates_to_index(self, x, y):
'''
Method convert_coordinates_to_index:
This method convert x and y coordinates from click handler to
row and column indexes for the game board
Parameters:
self -- current game UI object
... | This code handles player clicks to select and move game pieces, updates the game state, and manages computer moves and game end conditions. It checks for valid clicks, highlights selected pieces, processes moves, switches turns, and checks for win/loss scenarios based on remaining pieces or lack of valid moves. | def click_handler(self, x, y):
'''
Function -- click_handler
Called when a click occurs.
Parameters:
x -- X coordinate of the click.
Automatically provided by Turtle.
y -- Y coordinate of the click.
A... |
def pick_cell(self):
cells = []
for y in range(self.height):
for x in range(self.width):
cell = self.rows[y][x]
if cell.is_collapsed():
continue
cells.append((x, y, cell))
if len(cells) == 0:
return (0, 0... | The main task of the code is to collapse a selected cell by assigning a random value from its domain, propagate constraints, and handle backtracking if invalid states are detected. It checks for invalid cells in the last row, retries by backtracking when necessary, adjusts tracking levels, and ensures grid validity thr... | def collapse(self):
x, y, cell = self.pick_cell()
if not cell:
print("nothing to collapse!")
last_row = self.rows[-1]
for cell in last_row:
if not cell.is_valid():
print("retrying last row!")
if self.num_rows == ... |
def _get_slab_grid(self,slab=1,verbose=False):
if slab > self.NGrids[2]:
print(("%d is lareger than %d" % (slab,self,NGrids[2])))
NxNy=self.NGrids[0]*self.NGrids[1]
gidx, = np.where(slab == self.gid/NxNy+1)
grids = []
for i in gidx:
grids.append(self.grid... | This function reads and assembles field data from multiple grids into a unified 3D/4D array. It adjusts grid dimensions based on the 'slab' parameter, handles face-centered magnetic fields with special slicing, and places data in the correct spatial positions using grid indices. The result is a combined data array that... | def read_all_data(self,field,slab=False,verbose=False):
#fm=self.grids[0]['field_map']
fm=self.domain['field_map']
dnx=np.copy(self.domain['Nx'])
if slab:
dnx[2]=self.grids[0]['Nx'][2]
grids = self._get_slab_grid(slab=slab,verbose=verbose)
else:
... |
def build_iN_constcov(data, maps, smooth="isotropic", brel=2, lsigma=500, lmin=100):
return build_iN_constcorr(data, maps, smooth=smooth, brel=brel, lsigma=lsigma, lmin=lmin, constcov=True)
def build_iN_constcorr(data, maps, smooth="angular", brel=2, lsigma=500, lmin=100, constcov=False):
if not constcov: maps = maps... | The code constructs an empirical noise matrix (nmat) based on the specified 'type' parameter. It uses different methods to compute the inverse noise matrix (iN) and applies it to generate nmat, with options for constant covariance, constant correlation, wavelet, or weighted-wavelet approaches. The function returns the ... | def build_nmat_empirical(data, noise_map, type="constcorr", smooth="angular"):
if type == "constcov":
iN = build_iN_constcov(data, noise_map, smooth=smooth)
nmat = NmatConstcov(iN)
elif type == "constcorr":
iN = build_iN_constcorr(data, noise_map, smooth=smooth)
nmat = NmatConstcorr(iN, data.ivars)
e... |
def read_data(fnames, sel=None, pixbox=None, box=None, geometry=None, comp=0, split=0, unit="flux", dtype=np.float32,
beam_rmax=5*utils.degree, beam_res=2*utils.arcsec, deconv_pixwin=True, apod=15*utils.arcmin,
ivscale=[1,0.5,0.5]):
"""Read multi-frequency data for a single split of a single component, preparing i... | The code detects and measures celestial objects in intensity and polarization maps using two passes with different noise models, combining results into a catalog and maps. It reads data, builds templates, injects signals, and applies prior/empirical matrices to detect sources, then measures their fluxes and uncertainti... | def search_maps(ifiles, sel=None, pixbox=None, box=None, templates=default_templates, cl_cmb=None, freq0=98.0,
nmat1="constcorr", nmat2="constcorr", snr1=5, snr2=4, mode="TQU", dtype=np.float32,
verbose=False, sim_cat=None):
# Read in the total intensity data
if verbose: print("Reading T from %s" % str(ifiles))
... |
def wait_for_new_data(self, f, timeout):
# Before full_chunk_expire_at, wait for a full chunk data to be ready to
# maximize throughput.
# If time exceeds full_chunk_expire_at, return True if there is any data ready.
# insufficient chunk data return before read_timeout
full_chu... | The `iter_lines` method reads lines from a file incrementally, handling buffering and timeouts. It waits for new data, reads lines using `readline`, manages incomplete lines via buffering, strips line endings if specified, and yields each complete line. It tracks the file offset and updates statistics, ensuring it resp... | def iter_lines(self, f, read_timeout):
# raise NoData for the first time
self.wait_for_new_data(f, read_timeout)
while True:
offset = f.tell()
fsize = _file_size(f)
if offset >= fsize:
break
try:
while True:
... |
def get_location_vehicle(self, world, train_step, step, dic):
# episode by episode data also the data of dataset
#group by group traffic
k = train_step%self.Group_traffic+1
if k <10:
name = '0'+str(k)
else:
name = str(k)
with open(dic+name+'_min_... | The main task of the code is to reset the simulation world by initializing vehicle positions (from dataset or generation), calculating agent-specific load values across coverage, cross, and fixed groups, and computing propagation delays and centralized control delays for the world state. This prepares the environment f... | def reset_world(self, world, train_step, step, arglist, IF_test=False, TEST_V=None):
# load of each block in region_H * region_W
if train_step > - 1:
# getting the vehcle location from the bus dataset
self.get_location_vehicle(world, train_step, step, arglist.vehicle_data_dir)
... |
def get_delay_group(self, world):
world.group_delay = np.zeros([world.agent_num, world.region_W, world.region_H])
for i, agent in enumerate(world.agents):
for x in range(world.region_W):
for y in range(world.region_H):
#gettingig llinear algerbra norm
... | This code initializes a collaborative multi-agent world by configuring agent positions, network topology, server rates, and group interactions. It processes delays, sets action dimensions, and prepares environment parameters like handover rules and observation settings for a simulation, returning the configured world o... | def make_world(self, arglist, groupnum = None):
world = World()
world.collaborative = True
# adding agenets to world
world.agents = [Agent() for i in range(world.agent_num )]
#random position of the agents
position = (np.array([(38, 29),(40, 70),(56, 34),(72.4, 73.3)])/(100/world... |
def draw_game_window(pozitii):
print(pozitii)
for i in range(len(pozitii)):
if i < 3:
win.blit(number_list[pozitii[i]], (200 * i, 0))
elif 3 <= i < 6:
win.blit(number_list[pozitii[i]], (200 * i - 600, 200))
else:
win.blit(number_list[pozitii[i]], (200 * i - 12... | This code implements a human-controlled sliding puzzle game where the player moves the empty tile (zero) using arrow keys to rearrange the puzzle pieces. It updates the game state, redraws the window after each move, and checks if the current configuration matches the target state (scop). The loop continues until the p... | def human_player(pozitii, scop):
pozitii_joc_om = pozitii.copy()
draw_game_window(pozitii)
calculator = False
run = True
pygame.event.get()
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
pygame.quit()
pygame... |
def draw_game_window(pozitii):
print(pozitii)
for i in range(len(pozitii)):
if i < 3:
win.blit(number_list[pozitii[i]], (200 * i, 0))
elif 3 <= i < 6:
win.blit(number_list[pozitii[i]], (200 * i - 600, 200))
else:
win.blit(number_list[pozitii[i]], (200 * i - 12... | The code simulates a computer player in a sliding puzzle game. It retrieves precomputed moves from a database, visualizes each move with delays, and updates the game window to show the AI's actions. The loop handles move transitions, determines direction changes, and redraws the board, creating an animated sequence of ... | def computer_player(pozitii, scop=None):
calculator = True
draw_game_window(pozitii)
run = True
list_of_moves = db.main(pozitii, scop)
first_move = list_of_moves[0].copy()
list_of_moves.pop(0)
draw_game_window(first_move)
pygame.time.delay(10)
pos_zero_ini = first_move.index(0)
x... |
def LoadAcceleration(dA):
global AAWE, AANS, Acceleration
ErrorMargin = 0.01
s = 6
y = -155
if dA[accforward] >= -ErrorMargin and dA[accforward] <= ErrorMargin:
Gyro1.delete(AANS[0],AANS[1],AANS[2])
AANS = [
Gyro1.create_polygon([0,0], outline = bg, fill = bg, wi... | This function checks a serial port for incoming data. If data is received, it processes the packet based on its first character: "A" or "R" triggers acceleration/rotation handling, "S" updates RPM and speed, "E" checks error types, and digits update temperature values. It uses helper functions to load data into variabl... | def checkSerialPort():
if serialObj.isOpen() and serialObj.in_waiting:
recentPacketString = serialObj.readline().decode('utf').rstrip('\n')
# Label(dataFrame,text=recentPacketString, bg='white').pack(anchor=W)
if recentPacketString[0]:
checkValue = recentPacketString[0]
... |
def get_template_dft() -> EntryArchive:
"""Returns a basic archive template for a DFT calculation."""
template = get_template_computation()
run = template.run[-1]
method = runschema.method.Method()
run.method.append(method)
method.electrons_representation = [
runschema.method.BasisSetCon... | This code sets up a geometry optimization simulation for silicon structures using a DFT template. It defines two silicon bulk systems with slight atomic displacement, assigns calculation energies, links them to a method, and configures a BFGS-based geometry optimization workflow with convergence criteria. The template ... | def geometry_optimization() -> EntryArchive:
template = get_template_dft()
template.run[0].system = None
template.run[0].calculation = None
run = template.run[0]
atoms1 = ase.build.bulk("Si", "diamond", cubic=True, a=5.431)
atoms2 = ase.build.bulk("Si", "diamond", cubic=True, a=5.431)
atoms2... |
def _find_options(self, strike_price: float, type_: str, long_short: str) -> List[Option]:
"""Looks if given option is owned by the AMM, if none exists return None"""
if type_ not in {'call', 'put'}:
raise ValueError
if long_short not in {'long', 'short'}:
raise ValueErro... | This code facilitates option trading by either aggregating existing options or creating new ones. It validates input parameters, checks capital sufficiency, adjusts volatility, and manages fees. If existing options exist, it consolidates them; otherwise, it issues new user and pool options. The AMM ensures proper capit... | def trade(self, strike_price: float, type_: str, long_short: str, quantity: float) -> Option:
"""
strike_price, type_, long_short - correspond TO WHAT THE USER WANTS TO DO!!!
First look if given option is owned by the AMM.
If no option is found new one is created for user and returned a... |
def find_smallest_request(self, node_cur):
possible_nodes = {}
# no previously pruned edges from this node
if node_cur not in self.pruned_edges.keys():
return None
# check if the state behind a pruned edge has a path to an accepting state
for candidate in se... | The code determines the next action in a planning process by searching for feasible transitions. It checks if the current state is accepting, otherwise iterates through possible targets and objects, applying constraints to find a valid execution point. If no path exists, it sends a request or prunes edges, returning ap... | def get_next_step(self) -> Command:
print("Searching for target transition...")
# loop until we have a target or no path to accepting states exist anymore (due to pruning infeasible edges)
target_obj = None
while True:
target_set, constraint_set, edge = self.planner.plan_step... |
def prepare_output(root_path):
"""Create the output examples.md file, populating with some header info, so it is ready for the contents of each suite being run."""
details = textwrap.dedent(
"""\
# Language and spec support for each example
For each language and spec version identified,... | This code identifies and runs specified or all available test suites by preparing output directories, determining the correct project root path, and executing each suite with given language, specification, and example parameters. | def main(suite, language, spec, example):
print(f"{bcolors.HEADER}{bcolors.BOLD}Identifying and running available examples{bcolors.ENDC}")
root_path = pathlib.Path.cwd().parent if pathlib.Path.cwd().name == "scripts" else pathlib.Path.cwd()
prepare_output(root_path)
suites_path = root_path.joinpath("s... |
def get_unique_amenities_from_listings(listings_df_clean):
"""Extract all unique amenities from the dataframe."""
unique_amenities = set()
for amenities in listings_df_clean["amenities"]:
unique_amenities.update(eval(amenities))
return unique_amenities
def match_unique_amenities(session, unique_... | The function processes and inserts unique amenities from a cleaned listings DataFrame into a database. It retrieves unique amenities, matches them using a session, and performs a bulk insert of the matched amenities. | def process_amenities(session, listings_df_clean):
unique_amenities = get_unique_amenities_from_listings(listings_df_clean)
matched_amenities = match_unique_amenities(session, unique_amenities)
bulk_insert_matched_amenities(session, listings_df_clean, matched_amenities) |
def drawBoard(mySurface, n):
x = 70
y = 70
size = 70
i = 0
j = 0
while (i != n):
while (j != n):
drawBoardCell(mySurface, WHITE, x, y, size)
x += size
j += 1
j = 0
i += 1
x = 70
y += size
def displayTeam(mySurface):
... | The code implements a game loop for an SOS game using Pygame, where two players alternately place 'S' and 'O' on a 6x6 grid. It handles mouse input to select squares, updates scores based on formed words, alternates turns, and renders the board, scores, and player indicators. The loop processes events, updates game sta... | def gameloop(n, size):
pygame.init()
mySurface = pygame.display.set_mode((width, heigth))
board = [[0] * 6 for i in range(6)]
pygame.display.set_caption('SOS')
player = 1
length = 0
scores = [0, 0]
inProgress = True
mySurface.fill(GREY)
drawBoard(mySurface, n)
displayTeam(myS... |
def T(days):
return BASE_T + DT(days)
def staking_apy(stakes, t, rew):
# Stakes is [(t, amount)]
sv = sum([pv for (_,pv) in stakes if pv > 0])
svf = sum([pv for (_,pv) in stakes])
avg_t = sum([1.0* pt * pv for (pt, pv) in stakes if pv > 0]) / sv
print('T IS ',avg_t, days(avg_t-BASE_T))
retu... | The code tests the calculation of staking Annual Percentage Yield (APY) under different scenarios by defining stake timestamps and amounts, comparing computed APY values with expected results using the `staking_apy` and `apy` functions. It verifies accuracy by printing results for varying stake configurations, such as ... | def test_stk():
stakes = [(T(0), 200)]
apy0 = staking_apy(stakes, T(365), 200)
print(f'Staking using APY 365: {apy0:.4f} vs {apy(DT(365), 100, 100)}')
stakes = [(T(365-60), 1000)]
apy0 = staking_apy(stakes, T(365), 200)
print(f'Staking using APY 60: {apy0:.4f} vs {apy(DT(60), 200, 1000):.4f}')
... |
def is_end_state(self, state):
return state[1] == 0
def actions(self, state):
actions = []
game_field = state[0]
for i in range(self.rows_number):
for j in range(self.columns_number):
if self.is_valid_move(game_field, (i, j), (i, j + 1)):
c... | This function computes the expected utility of a given state-action pair using the SARSA algorithm. It simulates a trajectory by iteratively applying actions, accumulating discounted rewards, and updating the state until reaching an end state or depth limit. The discount factor reduces future rewards' value, and random... | def generate_sarsa(self, curr_state, action):
prev_state = curr_state
depth = self.DEPTH
utility = 0
depth = 0
while (not self.is_end_state(prev_state)) and depth < self.DEPTH:
if depth != 0:
action = random.choice(self.actions(prev_state))
... |
def num_valid_moves(self, game_field):
count = 0
for i in range(self.rows_number):
for j in range(self.columns_number):
if self.is_valid_move(game_field, (i, j), (i, j + 1)) or self.is_valid_move(game_field, (i, j), (i + 1, j)):
count += 1
return c... | The function generates a feature vector for a given state-action pair by computing key attributes: minimum/maximum row indices, column alignment, valid move count, maximum deletion status, median SARSA utility, and additional state-based features. It combines these into a numpy array for use in reinforcement learning f... | def get_feature_vec(self, state, action):
min_row = min(action[0][0], action[1][0])
max_row = max(action[0][0], action[1][0])
same_col = 1 if action[0][1] == action[1][1] else 0
n_valid_moves = self.num_valid_moves(state[0])
max_delete = self.test_switch(state, action)
me... |
def is_end_state(self, state):
return state[1] == 0
def dot_product(self, a, b):
return sum(a[i] * b[i] for i in range(len(a)))
def get_feature_vec(self, state, action):
min_row = min(action[0][0], action[1][0])
max_row = max(action[0][0], action[1][0])
same_col = 1 if action[0][... | The function calculates the Q-value for a given state-action pair by returning 0 if the state is terminal, otherwise computing the dot product of the feature vector (generated from the state and action) and the model's weights, likely for reinforcement learning value estimation. | def get_q_opt(self, state, action):
if self.is_end_state(state):
return 0.
return self.dot_product(self.get_feature_vec(state, action), self.weights) |
def evaluatePredefined(self, isMax):
"""
This function implements the evaluation function for ultimate tic tac toe for predifined agent.
input args:
isMax(bool): boolean variable indicates whether it's maxPlayer or minPlayer.
True for maxPlayer, False for minPlayer
... | This function simulates a game between a human player and an AI agent, alternating turns. It tracks the game board states, best moves, and expanded nodes at each step. The human inputs moves, while the AI uses alphabeta pruning to determine optimal moves. The game continues until a terminal state (win, loss, or tie) is... | def playGameHuman(self):
"""
This function implements the processes of the game of your own agent vs a human.
output:
bestMove(list of tuple): list of bestMove coordinates at each step
gameBoards(list of 2d lists): list of game board positions at each move
winner(int): 1 ... |
def evaluatePredefined(self, isMax):
"""
This function implements the evaluation function for ultimate tic tac toe for predifined agent.
input args:
isMax(bool): boolean variable indicates whether it's maxPlayer or minPlayer.
True for maxPlayer, False for minPlayer
... | The code simulates a game between the agent (maxPlayer) and a predefined offensive agent (minPlayer), using alpha-beta pruning for decision-making. It tracks best moves, board states, and expanded nodes at each step. The function alternates turns, evaluates game-ending conditions (win/tie), and returns the sequence of ... | def playGameYourAgent(self):
"""
This function implements the processes of the game of your own agent vs predifined offensive agent.
input args:
output:
bestMove(list of tuple): list of bestMove coordinates at each step
gameBoards(list of 2d lists): list of game board pos... |
def evaluatePredefined(self, isMax):
"""
This function implements the evaluation function for ultimate tic tac toe for predifined agent.
input args:
isMax(bool): boolean variable indicates whether it's maxPlayer or minPlayer.
True for maxPlayer, False for minPlayer
... | This function simulates a game between predefined offensive and defensive agents using minimax or alpha-beta pruning. It alternates turns, tracks best moves, evaluated values, expanded nodes, and game boards. The game ends when a player wins or the board is full, returning all recorded data along with the winner. | def playGamePredifinedAgent(self,maxFirst,isMinimaxOffensive,isMinimaxDefensive):
"""
This function implements the processes of the game of predifined offensive agent vs defensive agent.
input args:
maxFirst(bool): boolean variable indicates whether maxPlayer or minPlayer plays first.
... |
def init_set(mode, path):
db = fsdb.FSDB(path)
db.connect()
scans = db.get_scans()
shots = []
for s in scans:
f = s.get_fileset('images')
list_files = f.get_files( query = {'channel':'rgb'})
#for i in range(len(list_files)):
#f0 = list_files[i]
#sprint... | This code fine-tunes a pre-trained segmentation model on a custom dataset. It loads training/validation data, applies transformations, freezes model layers, trains using Adam optimizer with a learning rate scheduler, and saves the fine-tuned weights. The task involves semantic segmentation, with data augmentation, mode... | def fine_tune_train(path_train, path_val, weights_folder, label_names, tsboard_name,
model_segmentation_name, Sx, Sy, num_epochs, scan):
num_classes = len(label_names)
trans = transforms.Compose([
transforms.CenterCrop((Sx, Sy)),
transforms.Normalize(mean=[0.485, 0.456, 0.406],
... |
def load_dxdt(file):
file_path = r"C:\Xingbo\University\McGill\Summer 2023\Research\Legrand\Code\Training data\Dynamical Systems\ x dot data"
file = open(file_path, "r")
dxdt_data_string = file.read()
count_list = dxdt_data_string.split(",")
dxdt_data = []
for i in range(len(count_list)):
... | The main task of the code is to compute a combined loss function for a physics-informed autoencoder (CAE). It integrates reconstruction error (x_hat vs original data), dynamics consistency (SINDy-based derivative matching), and regularization. The loss combines mean squared errors for predicted vs SINDy-derived derivat... | def compute_loss_CAE():
# x = FEM data
# x dot = [1, 1, 1.....]
# C is randomized with 2 coefficents
# 2 basis functions used sin and cos
#Load training data
x_data_tensor = tf.reshape(tf.cast(tf.convert_to_tensor(x_data), tf.float32), (len(x_data), 1))
#load dxdt data
dxdt_file = []
... |
def generate_description_for_clip(description):
chain=llm_initiate()
#step 1 - does similarity search
metadata = retrieve_info(description,loadfile)
#step 2 - puts the similar best practice in the chain model
response=chain.run({'description': description,'metadata': metadata})
#return response,... | The main task of the code is to recursively confirm user needs via a yes/no interaction. It appends bot replies and user inputs to a message history, generates descriptions, and adjusts parameters like 'needs' and 'num_question' based on user confirmation. The function handles initial input collection, iterative refine... | def confirm(bot_reply, needs,num_question):
messages.append({"role": "assistant", "content": bot_reply})
if 'YES' in bot_reply or num_question>1:
reply=generate_description_for_clip(needs)
print(f"ChatGPT: Can you please confirm this is what you are looking for wit... |
def update_vertical_lines(self):
# -1 0 1 2
start_index = int(-self.V_LINES_AMOUNT / 2 + 1)
for index in range(start_index, start_index + self.V_LINES_AMOUNT):
line_x = self.x_line_coord(index)
x1, y1 = self.transform(line_x, 0)
x2, y2 = self.transform(line_x,... | This code updates game elements by adjusting vertical/horizontal lines, tiles, and ship position. It checks if the ship is off-track to trigger game over, then calculates movement based on time delta (dt). If active, it updates offsets for scrolling, manages tile loops, and adjusts speed factors for continuous gameplay... | def update(self, dt):
self.update_vertical_lines()
self.update_horizontal_lines()
self.update_tile()
self.ship_update()
if not self.is_ship_on_track() and not self.is_game_over:
self.is_game_over = True
self.menu_widget.opacity = 1
time_factor = dt... |
def find_third_path(graph, found_paths, goals, frontier_dict):
missed_goals = list()
for path in found_paths:
for i in goals:
if i not in path:
missed_goals.append(i)
sorted(missed_goals)
'check both frontiers for the path'
for g in missed_goals:
pq = fron... | The main task of the code is to find the optimal path connecting all three goals by combining existing paths. If no single path contains all goals, it stitches paths with a third found path, calculates their total weights, and returns the path with the minimum weight. | def stitch_final_path(graph, found_paths, goals, frontier_dict):
final_path = None
all_paths = []
for path in found_paths.values():
found_goal_nodes = set([i for i in goals if i in path])
if len(found_goal_nodes) == 3:
final_path = path
break
if final_path is None... |
def find_third_path(graph, found_paths, goals, frontier_dict):
missed_goals = list()
for path in found_paths:
for i in goals:
if i not in path:
missed_goals.append(i)
sorted(missed_goals)
'check both frontiers for the path'
for g in missed_goals:
pq = fron... | This function identifies the shortest path covering all three goal nodes by either directly selecting a pre-found path containing all goals or combining the two shortest paths from found_paths with a third path to minimize total weight. | def stitch_final_path_1(graph, found_paths, goals, frontier_dict):
final_path = None
all_paths = dict()
for path in found_paths.values():
found_goal_nodes = set([i for i in goals if i in path])
if len(found_goal_nodes) == 3:
final_path = path
break
if final_path i... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.