dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def load_and_upscale(path):
# read all points
points, labels, instances = load_ascii_cloud(path)
# just copy some random points... if needed
points, labels, instances = upscale(points, labels, instances)
return points, labels, instances
def mapInstance(points, labels, instances):
instances = i... | The code processes a list of files to load, upscale, and optionally downscale point cloud data. It maps instances, splits data into chunks if exceeding a point limit, and returns processed point clouds, semantic labels, and instance labels as NumPy arrays for further use in tasks like 3D object detection or segmentatio... | def prepareData(filelist):
random.seed(1337)
point_list = []
semantic_label_list = []
instance_label_list = []
i=0
while i < len(filelist):
points, labels, instances = load_and_upscale(filelist[i])
points, labels, instances = mapInstance(points, labels, instances)
poin... |
def _create_cells(self):
for i in range(self.num_rows):
for j in range(self.num_cols):
top_left_x = self.x1 + self.cell_size_x * j
top_left_y = self.y1 + self.cell_size_y * i
bottom_right_x = self.x1 + self.cell_size_x * (j + 1)
bottom_... | This code initializes a maze generator by setting up a grid of cells with specified dimensions and sizes, creating and drawing the maze structure, breaking walls to form paths, setting entrance/exit points, resetting visited flags, and solving the maze using a recursive algorithm. | def __init__(
self,
x1, y1,
num_rows, num_cols,
cell_size_x, cell_size_y,
window=None, seed = None
):
random.seed(seed)
self.window = window
self.x1 = x1
self.y1 = y1
self.num_rows = num_rows
self.num_cols = num_cols
sel... |
def get_user_name():
while True:
s = input("What's your name: ").strip()
if name := validate_user_name(s):
break
return name
def init_vendor_machine():
entrylist = []
with open("inventory.csv","r") as file:
reader = csv.DictReader(file)
for row in reader:
... | The main task of the code is to simulate a vending machine purchase game where a user buys items using a wallet balance. The loop continues until the machine is sold out or the wallet balance is insufficient. It tracks purchased items, updates the wallet balance, and displays UI elements like available items, balance, ... | def main():
start_balance = 50
bought_items=[]
user = get_user_name()
ui.show_loading("Loading")
ui.show_vendor_machine_title()
vendor = init_vendor_machine()
wallet = Wallet(start_balance)
while not vendor.is_soldout and wallet.balance > vendor.get_cheapest_price():
ui.show_ve... |
def moveHorse(self, targetSquare, currentSquare = None):
if currentSquare:
currentSquare.changeColour(self.draw.colour__already_used)
currentSquare.redraw()
targetSquare.changeColour(self.draw.colour__current)
targetSquare.drawHorse()
self.currentSquare = targetSq... | This code initializes a Pygame window for a game, setting up the display, generating a game board, positioning a knight piece at a starting square, calculating and marking available moves, and launching the game loop to handle interactions and rendering. | def __init__(self):
logging.debug("Setuping pygame module")
pygame.init()
self.screen = pygame.display.set_mode(self.res)
self.screen.fill((153,255,51))
pygame.display.set_caption(self.title)
self.draw = Draw(self.screen)
self.squares = self.draw.generateBoard()
... |
def is_authorized(cookies: List[str]) -> bool:
for cookie in cookies:
log.debug(f"Trying to authorize {cookie}")
if cookie and cookie.startswith("byst="):
try:
log.debug(f"Checking cookie authorization for {cookie}")
return check_cookie_is_authorized(cooki... | The code handles S3 or API Gateway events by transcoding video files into keyframes, checking authorization for API calls, validating input, managing FFMPEG dependencies, and writing metadata. It processes video paths, disables transcoding if configured, logs metrics, and returns structured responses for success or err... | def handle(event, context):
"""
Handle an S3 event or API Gateway event integration
"""
_ = context
log.debug(f"Transcoding event: {event}")
uniq_id = "nani"
is_s3_event = event.get("Records") != None
is_test_event = event.get("video") != None
is_api_call = not is_test_event and no... |
def integration_response(
status_code: int,
message: Optional[str] = None,
error: Optional[str] = None,
json_data: Optional[str] = None,
) -> Dict:
"""
Returns:
API Gateway integration response
"""
_response = {"statusCode": status_code}
if message:
_response["body"] ... | This code handles a video listing request by validating authorization, parsing query parameters, and returning video data. It checks for required parameters, enforces API version rules, and uses different backend methods (v2_list_videos or list_videos) based on the API version. Errors like missing auth, invalid paramet... | def handle(event, context):
"""
ListVideosQueryParameters:
camera=Cameraname
period=7
step=2
date=YYYYMMDD
utcoffset=HH
start=YYYYMMDDHHMMSS
[end=YYYYMMDDHHMMSS] | Now
Returns:
API Gateway integration response with CORS headers
"""
_ = ... |
def getBathymetry(filename,undef=np.nan):
"""
Reads a HYCOM bathymetry file (e.g., regional.depth.a)
and return the bathymetry field.
Will get dims from regional.grid.a.
"""
import numpy as np
if os.path.dirname(filename) == '':
jdm,idm = getDims('regional.grid.b')
else:
... | The code converts NetCDF z-level data from HYCOM into binary [ab] files for hybrid layer remapping. It reads multiple NetCDF files (SSH, temperature, salinity, currents), interpolates data to a regional grid if specified, masks variables with bathymetry, computes layer thickness, and writes output to ".a" (binary data)... | def ncz2ab(filename,baclin=60,interp=True):
"""
Convert NetCDF z level data from hycom.org in to binary [ab] files
so they can be used with "remaph" to generate hybrid layer data.
filename can be any of the files, the function will use the path to search
for a set of file like this:
hycom_g... |
def getDims(filename):
"""
Returns HYCOM domain dimensions for a given
archive or regional.grid .a file.
NOTE: This does NOT work for regional.depth files.
"""
f = getTextFile(get_b_filename(filename))
#
idmFound = False
jdmFound = False
for line in f:
if 'idm' in line:
... | The function calculates mixed layer depth (MLD) from temperature and salinity profiles using specified thresholds (delT, delS). It computes MLD for temperature (mldt) and salinity (mlds), then returns the minimum of the two as the primary MLD, along with both values. Input includes a file path and reference depth; outp... | def getMixedLayerDepth(filename, delT=0.2, delS=0.03, ref_depth=10):
"""
One definition of mixed layer depth is first level when the temperature
or salinity difference is greater than a threshold, relative to a reference depth.
This function first calculates the temperature and salinity based
mixed ... |
def git_setup():
proc = subprocess.run(["git", "config", "--global", "init.defaultBranch", "main"], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
print(str(proc.stdout, "utf-8"))
proc = subprocess.run(["git", "config", "--global", "user.email", "pqhbg@example.com"], stdout=subprocess.PIPE, stderr=subpro... | This function executes the 'godin_year' task for a specified year (default 2023) with an additional parameter 4. If 'doGit' is True, it performs Git setup and pushes changes with a commit message. It measures and prints execution time, including Git operations if enabled. | def local_run_year(year: int = 2023, doGit: bool = False):
cloud_run_start: float = time.time()
if doGit:
git_setup_start: float = time.time()
git_setup()
print(f"git_setup completed: {time.time() - git_setup_start}s")
godin_year(year, 4)
if doGit:
git_push_start: floa... |
def check_file_format(self, file, file_format):
item_list = list()
# test PSL file format
if file_format == 'PSL':
with open(file, 'r') as psl:
psl_entries = csv.reader(psl, delimiter=',')
try:
for row in psl_entries:
... | The code generates PSL entries by processing MSL files and seeds, combining TSL object data with QCAS outputs to create formatted strings for each seed, then returning a list of these entries. | def generate_PSL_entry(self, blnk_file, TSL_object):
psl_entry = ''
psl_entry_list = list()
msl_file_list = [self.MSLfile, self.nextMonth_MSLfile]
for msl_file in msl_file_list: # Check both months
msl = self.check_file_format(msl_file, 'MSL')
s... |
def check_file_format(self, file, file_format):
item_list = list()
# test PSL file format
if file_format == 'PSL':
with open(file, 'r') as psl:
psl_entries = csv.reader(psl, delimiter=',')
try:
for row in psl_entries:
... | This function generates a PSL entry string by formatting game data from a TSL object, processing a blank file with a seed to compute a hash, and concatenating the result with specific fields including game name, MID, date, SSAN, and a processed hash value in uppercase hexadecimal format. | def generate_PSL_entry_one_seed(self, blnk_file, TSL_object, seed, random_seed_idx):
psl_entry = ''
psl_entry_list = list()
msl = self.check_file_format(self.MSLfile, 'MSL')
psl_entry = "%(game_name)-30s,%(mid)02d,%(year)4s,%(month)02d,%(ssan)010d," % {'game_name': TSL_obje... |
def play_sudoku(self):
if self.current_puzzle=="":
self.msg.setText("Please, Select puzzle")
return
self.game_state="play"
self.play.setStyleSheet('background-color: blue;color:white')
def load_puzzle(self,row):
if self.game_state=="play":
ret... | The code configures a Sudoku UI by translating text and tooltips for elements like buttons and labels, connecting their actions to functions such as loading puzzles, restarting, and solving. It links 81 Sudoku cells to handle user input and associates number selectors with value-setting logic, ensuring interactive func... | def retranslateUi(self, sudoku_board):
_translate = QtCore.QCoreApplication.translate
sudoku_board.setWindowTitle(_translate("sudoku_board", "SUDOKU"))
self.load.setToolTip(_translate("sudoku_board", "Load sudoku puzzle"))
self.load.setText(_translate("sudoku_board", "LOAD"))
sel... |
def is_trading_day(self):
return now().weekday() in [0, 1, 2, 3, 4]
def time_to_trade_open(self):
d = now()
if d.hour >= 21:
return now().replace(hour=14, minute=30, second=0, microsecond=0) + timedelta(days=1) - now()
return now().replace(hour=14, minute=30, second=0, micro... | This code checks if the current day is a business day. If not, it logs a message and waits 30 minutes before exiting. On business days, it initializes a set to track purchased stocks, monitors stocks for selling opportunities, watches stock data, and identifies stocks meeting predefined criteria for further action. The... | def run(self):
if self.run_on_business_days and not self.is_trading_day():
trade_open = self.time_to_trade_open()
logger.info("%s is not a business day, we are going to sleep, trade will open in %s", now(), trade_open)
time.sleep(60 * 30)
return None
alr... |
def preprocess_image(image_path):
image = cv2.imread(image_path)
return image
def extract_text(image):
reader = easyocr.Reader(['en'])
result = reader.readtext(image, detail=1)
lines = concatenate_same_line_text(result)
return lines
def transform_response(response):
text, box = response
... | The code processes an image by preprocessing it, extracting text, transforming each word in the text using a function, printing the transformed list, and returning it. | def get_image_from_text(image_path):
preprocessed_image = preprocess_image(image_path)
text = extract_text(preprocessed_image)
let = [transform_response(word) for word in text]
print(let)
return let |
def getInt(self,i):
k = 0
for n in self.bytes[self.itr:self.itr+i]:
k = (k << 8) + n
self.itr += i
return k
def log(self,*arg):
for s in range(len(arg)):
try:
self.midiRecord.write(str(arg[s]) + " ")
except:
self.midiRecord.write("[?] ")
self.midiRecord.write("\n")
def readMidiTrackEvent(se... | This method reads a MIDI track chunk (MTrk) by first extracting its length from the file, logging the length, then passing it to a helper function to process the track's events. The core task is parsing MIDI track data for subsequent event processing in a MIDI file reader. | def readMTrk(self):
length = self.getInt(4)
self.log("MTrk len",length)
self.readMidiTrackEvent(length) |
def checkStartSequence(self):
for i in range(len(self.startSequence)):
if(len(self.startSequence[i]) == self.startCounter[i]):
return True
return False
def readMThd(self):
self.headerLength = self.getInt(4)
self.log("HeaderLength",self.headerLength)
self.format = self.getInt(2)
self.tracks = self.get... | The code parses MIDI events by scanning the byte stream for 'MThd' or 'MTrk' sequences. It resets counters, increments them on matching bytes, and triggers `readMThd()` or `readMTrk()` when a full 4-byte sequence is detected. The loop advances the index (`self.itr`) until a valid event header is found, enabling sequent... | def readEvents(self):
while(self.itr+1 < len(self.bytes)):
#Reset counters to 0
for i in range(len(self.startCounter)):
self.startCounter[i] = 0
#Get to next event / MThd / MTrk
while(self.itr+1 < len(self.bytes) and not self.checkStartSequence()):
for i in range(len(self.startSequence)):
... |
def initLabels(self):
# creating the entry labels
self.rateLabelVar = tk.StringVar()
self.rateLabelVar.set(f"Fuel Economy ({self.rateUnit.type})")
self.distanceLabelVar = tk.StringVar()
self.distanceLabelVar.set(f"Distance ({self.distanceUnit.type})")
self.priceLabelVar... | This code initializes a GUI interface for a unit conversion or calculation tool, setting up input fields, unit selectors, and a "Check" button to trigger calculations. It configures the layout, binds the Enter key to the submit action, and prepares components for user interaction to compute results based on input value... | def __init__(self, master):
# initializes the gui
self.f = tk.Frame(master)
self.f.pack(padx=10, pady=10)
self.rateUnit = rateUnit()
self.distanceUnit = distanceUnit()
self.priceUnit = priceUnit()
self.initLabels()
self.initEntries()
self.f.grid... |
def get_ngrok_id():
spinner = Halo(text="Loading", spinner="dots")
spinner.start()
if not os.path.isfile(config_file):
with open(config_file, "w+") as f:
try:
data = {}
data["debug"] = (True,)
data["entry_file"] = "main.py"
... | The code defines a command-line interface using argparse to execute different functions based on the provided type argument, such as initializing ngrok, deploying code, processing tasks, or starting a Jupyter kernel. It handles invalid commands by displaying an error message. | def main():
parser = argparse.ArgumentParser(description="Commands")
parser.add_argument(
"type",
help="init: Initiate ngrok and secret key\n deploy: Deploy your code to colab instance",
)
args = parser.parse_args()
if args.type == "init":
get_ngrok_id()
elif args.type ==... |
def create_naive_graph(segments):
"""
creates a naive graph representation from the set of text segments
:param segments: a list of segments, where each segment is a list of the words that make up that segment
:return: g: a graph made up of nodes representing each distinct word used throughout all the s... | The code processes text segments by correcting case, splitting into words, and generating three graph representations (naive, lemma, POS) to extract linguistic features. It computes metrics for each graph, normalizes features based on word count, and returns a dictionary of features for analysis. | def extract_graph(df_c, feats):
"""
:param segments: List of text segments. Each segment is a string.
:return: feats: Dictionary mapping feature names to values
"""
df_c = df_c.fillna(value={'transcriptions':' '})
segments = [x.replace('<comma>', ',').replace('<filler>', ' ') for x in list(df_c[... |
def build_trie(text):
root = Node((-1,-1))
m = len(text)
for ix in range(len(text)-1,-1,-1):
suffix = text[ix:]
poundString = False
dollarString = True
if '#' in suffix:
poundString = True
dollarString = False
node = root
if node.edge[0] > -1:
nodeEdge = text[node.edge[0]... | The code constructs a hybrid string from inputs p and q, builds a suffix tree (trie), extracts unique substrings from it, and optionally visualizes the tree. The main task is to identify all unique substrings of the combined string using a suffix tree structure. | def solve (p, q):
hybrid = q+"#"+p+"$"
suffix_tree = build_trie(hybrid)
result = get_unique_substrings(suffix_tree,hybrid)
if GRAPHICS:
gr_tree(suffix_tree,'suffix tree',hybrid)
return result |
def generate_moves(self, color):
moves = []
for row in range(8):
for col in range(8):
piece = self.board[row][col]
if piece != "--" and piece.startswith(color):
if "-rook" in piece:
moves.extend(self.generate_rook_... | This method validates and executes a chess move by checking if the move is in the list of possible moves generated for the current player's color. If valid, it ensures the move does not leave the king in check, handles castling if applicable, and updates the board state. If invalid, it returns False and prints an error... | def move_piece(self, start, end):
start_row, start_column = start
end_row, end_column = end
piece = self.board[start_row][start_column]
# Generate all possible moves for the current color
all_moves = self.generate_moves("white" if self.white_to_move else "black")
# Chec... |
def get_tron_data(wallet_address, token_type, contract_address, limit):
url = f"https://api.trongrid.io/v1/accounts/{wallet_address}/transactions/{token_type}?&contract_address={contract_address}&only_confirmed=true&limit={limit}"
try:
response = requests.get(url)
respon... | This code executes a TRON blockchain data search by validating user inputs, fetching transaction data via an API, handling rate limits, processing results, and displaying sender/receiver transactions in UI tables. It ensures input constraints, alerts users to errors or rate limits, and populates tables with parsed tran... | def run_search(self):
wallet_address = self.address_input.text()
token_type = self.token_type_combo.currentData()
contract_address = self.contract_combo.currentData()
api_limit = self.api_limit_input.text()
try:
limit = int(api_limit)
if not 1 <= limit <=... |
def order_encode_variables(self):
self._px = [[Bool(f"px_{i+1}_{e}") for e in range(self.W)] for i in range(self.n)]
self._py = [[Bool(f"py_{i+1}_{f}") for f in range(self.H)] for i in range(self.n)]
self._lr = [[Bool(f"lr_{i+1}_{j+1}") for j in range(self.n)] for i in range(self.n)]
se... | The code determines if a given strip's dimensions can accommodate rectangles using SAT order encoding with symmetry breaking. It sets up variables, applies domain-reducing and ordering constraints, enforces non-overlapping rules (with symmetry-breaking if enabled), checks SAT solvability, and returns positioned rectang... | def solve(self):
"""
Find out if a strip of given width and height is satisfiable using SAT order encoding.
By default, symmetry breaking is used. The broken symmetries are:
- LR: Reducing the possibilities for placing large rectangles
- SR: Breaking symmetries for same-sized rec... |
def get_king_cords_by_color(board, color: Colors) -> (int, int):
if color == Colors.neutral:
raise ValueError("Error while trying to find king position, King can be either black or white")
for col in range(8):
for row in range(8):
piece = board[col][row]
if is_king(piece... | This function checks if a player's king is in stalemate by verifying if the king isn't under attack and has no legal moves. It first confirms the king isn't under attack. Then, it iterates through all the player's pieces' positions and checks if any move is legal. If any legal move exists, it returns False (no stalemat... | def is_stale_mated(self, color: Colors) -> bool:
kings_cords = get_king_cords_by_color(self.board, color)
under_check = is_square_under_attack(kings_cords, self.board, color)
# If king is not under attack can't be mated
if under_check:
return False
list_of_players_s... |
def get_king_cords_by_color(board, color: Colors) -> (int, int):
if color == Colors.neutral:
raise ValueError("Error while trying to find king position, King can be either black or white")
for col in range(8):
for row in range(8):
piece = board[col][row]
if is_king(piece... | This function checks if a player's king is in checkmate. It verifies if the king is under attack and whether any legal moves exist to escape. If no valid moves are found and the king is attacked, it returns True (checkmate); otherwise, False. | def is_mated(self, color: Colors) -> bool:
kings_cords = get_king_cords_by_color(self.board, color)
under_check = is_square_under_attack(kings_cords, self.board, color)
# If king is not under attack can't be mated
if not under_check:
return False
list_of_players_squ... |
def display_welcome(self):
print("Welcome to Rock Paper Scissors Lizard Spock.")
sleep(1.5)
print("Each match will be best of three games.")
sleep(1)
def how_many_players(self):
play_game = False
while play_game is False:
self.num_of_players = input('How many ... | The code's main task is to initialize and start a game by displaying a welcome message, determining the number of players, and selecting the game type based on the `type_of_game` attribute. It orchestrates the initial setup流程 through three key methods: `display_welcome()` for greetings, `how_many_players()` for player ... | def run_game(self):
self.display_welcome()
self.how_many_players()
self.decide_on_game(self.type_of_game) |
def preprocess(g):
if g.max_density == -1:
LP(g)
max_density = g.max_density
g_ = copy.deepcopy(g)
while g_.node_number > 0:
stop_flag = True
for i in g_.node_list:
if i == None:
continue
if len(i.neighbor) < max_density:
g_... | The code iteratively identifies and refines the densest subgraph of a given graph `g` by removing or enhancing nodes. It preprocesses the graph, then repeatedly selects the densest node, attempts its removal or enhancement, and updates the subgraph based on the larger resulting subset. This continues until no further r... | def find_minimal(g):
g_ = preprocess(g)
# LP(g_)
h = g_
max_density = g_.max_density
while True:
u = h.densest_set[0]
# print(" ".join(h.densest_set))
h1 = try_remove(u, h)
h2 = try_enhance(u, h)
if h1 == None:
# print(h2)
return h.subg... |
def hotspot_read(path):
g = Graph()
with open(path) as f1:
for n, i in enumerate(f1):
if n == 0:
continue
i = i.split()
g.add_edge((i[0], i[2]), i[4])
return g
def preprocess(g):
if g.max_density == -1:
LP(g)
max_density = g.max_den... | The code identifies all minimal subgraphs with maximum density from a given graph by iteratively finding and removing them, then saving the collected node IDs to a file for the specified PDB ID. | def find_all_minimal(PDB_id):
g = hotspot_read("../data/SKEMPI/graph_hotspot_o_ring/{}.txt".format(PDB_id))
g_ = preprocess(g)
# LP(g_)
result = []
max_density = g_.max_density
while True:
temp_result = find_minimal(g_)
if not approximate_equal(temp_result.max_density, max_densit... |
def miniForwardOnline(f, transition, outcomeSpace):
"""
argument
`f`, dictionary of factors (in the previous state of the chain) asociated with the state_variable
`transition`, transition probabilities from time t-1 to t.
`outcomeSpace`, dictionary with the domain of each variable.
Returns a new... | The main task of the code is to perform a forward update in a probabilistic model, updating the state factors using transition probabilities and incorporating observed emission evidence if provided. It computes the current state's factor by joining with emission probabilities, marginalizing over the emission variable, ... | def forwardOnlineEmission(f, transition, emission, stateVar, emissionVar, emissionEvi, outcomeSpace):
"""
argument
'state_variable'(string), state variable whose factor is going to be calculated
`f`, dictionary of factors (in the previous state of the chain) asociated with the main state variable
`t... |
def forwardOnlineEmission(f, transition, emission, stateVar, emissionVar, emissionEvi, outcomeSpace):
"""
argument
'state_variable'(string), state variable whose factor is going to be calculated
`f`, dictionary of factors (in the previous state of the chain) asociated with the main state variable
`t... | The main task of the code is to determine optimal light control actions (on/off) using probabilistic inference on sensor data, incorporating electricity price adjustments and robot observations. It updates room states via emission/transition probability models, applies reliability-weighted decisions, and returns action... | def get_action(sensor_data):
global actions_dict
global tran_prob_table
global emis_prob_table_varstate
global outcomeSpace
global state
global previous_state
global sens_rooms
global urel_sens_loc
global rel_sens_loc
global door_sens_loc
global previous_G
global offset
... |
def get_backup_name(backup_name: str) -> str:
current_time_string = get_current_time_string()
backup_filename: str = f"{backup_folder}/BACKUP-{backup_name}-{current_time_string}.db"
counter = advanced_existing_backup_lookup(backup_name)
if (counter != 0):
backup_filename = f"{backup_folder}/BAC... | The main task of the code is to create a database backup by copying the database file into a backup folder, prefixing it with "BACKUP-", appending a timestamp, and handling existing backups by iteratively renaming them with a counter like Windows does. It also logs the backup creation with parsed filename details. | def create_backup(name: str):
"""
Copies the current database into the backups folder, then prefixes that file with BACKUP-, and suffixes it with the current time (YY-MM-DD-SS).
Additionally, if the specified backup already exists, instead of overwriting it,
it will iteratively change its name similar ... |
def train_boston(param_in):
data = datasets.load_boston()
X = scale(data.data)
dtrain = xgb.DMatrix(X, label=data.target)
param = {}
param.update(param_in)
bst = xgb.train(param, dtrain, num_rounds)
xgb_pred = bst.predict(dtrain)
check_ElasticNet(X, data.target, xgb_pred, 1e-2,
... | This function tests the accuracy of a specified linear updater in machine learning by generating all parameter combinations from `variable_param`, configuring them into a base parameter set, and validating performance across multiple datasets (e.g., Boston, Diabetes) using training functions. It ensures the updater beh... | def assert_updater_accuracy(linear_updater, variable_param):
param = {'booster': 'gblinear', 'updater': linear_updater, 'eta': 1.,
'top_k': 10, 'tolerance': 1e-5, 'nthread': 2}
names = sorted(variable_param)
combinations = it.product(*(variable_param[Name] for Name in names))
for set in co... |
def get_zwift_id(html):
# It appears in a few places, but this is easy enough. There's a bunch of
# data defined in javascript in the head.
js_data = '\n'.join(script.string for script in html.select('head script'))
match = re.search(r'\bzwift_id *: *[\'"](\d+)[\'"]', js_data)
if not match:
... | The code parses a HTML file at the given path to extract a Zwift user's ID, Zwift Power points, and aliases. It uses BeautifulSoup to read the HTML, calls helper functions to retrieve specific data, and returns the results in a dictionary. Exceptions during parsing trigger a ValueError with the error details. | def parse_profile(path):
try:
with open(path, 'rb') as f:
html = BeautifulSoup(f.read(), 'html.parser')
id = get_zwift_id(html)
zp_points = get_zp_points(html)
aliases = get_aliases(html)
except Exception as e:
raise ValueError(f'Unable to parse {path}: {e}'... |
def cross_entropy(self, y, probs):
return -1 * np.mean(y * np.log(probs))
def predict_(self, X):
pre_vals = np.dot(X, self.weights.T).reshape(-1,len(self.classes))
return self.softmax(pre_vals)
def evaluate_(self, X, y):
return np.mean(np.argmax(self.predict_(X), axis=1) == np.argmax(y, ... | This code trains a model using stochastic gradient descent (SGD) by iteratively updating weights based on batch data, cross-entropy loss, and specified regularization (Ridge, Lasso, or Elastic Net). It stops when weight updates fall below a threshold or after a set number of epochs, optionally printing training accurac... | def fit_data(self, X, y, batch_size, lr, verbose):
"""
Fit the data using stochastic gradient descent.
"""
i = 0
while (not self.epochs or i < self.epochs):
# Compute and store the cross-entropy loss.
self.loss.append(self.cross_entropy(y, self.predict_(X)... |
def get_best_split(self, dataset, num_samples, num_features):
''' function to find the best split '''
# dictionary to store the best split
best_split = {}
max_info_gain = -float("inf")
# loop over all the features
for feature_index in range(num_features)... | This function recursively builds a decision tree by splitting the dataset based on the best feature and threshold that maximize information gain. It continues splitting until stopping conditions (minimum samples or maximum depth) are met, then creates internal nodes with splits or leaf nodes with predicted values. | def build_tree(self, dataset, curr_depth=0):
''' recursive function to build the tree '''
X, Y = dataset[:,:-1], dataset[:,-1]
num_samples, num_features = np.shape(X)
# split until stopping conditions are met
if num_samples>=self.min_samples_split and curr_dept... |
def add_bias(self,X):
return np.insert(X, 0, 1, axis=1)
def one_hot(self, y):
return np.eye(len(self.classes))[np.vectorize(lambda c: self.class_labels[c])(y).reshape(-1)]
def fit_data(self, X, y, batch_size, lr, verbose):
"""
Fit the data using stochastic gradient descent.
"""
... | The code trains a classification model using stochastic gradient descent (SGD). It initializes weights, preprocesses data by adding a bias term and one-hot encoding labels, then performs SGD via the `fit_data` method. The training uses a specified batch size, learning rate, and seed for reproducibility, storing loss va... | def train(self, X, y, batch_size=64, lr=1e-3, seed=11, verbose=False):
"""
Train the model using stochastic gradient descent.
"""
# Set seed for reproducibility.
np.random.seed(seed)
# Define the unique classes and their corresponding indices.
self.class... |
def try_open_image_if_it_exists(path: str) -> ImageClass:
try:
return Image.open(path)
except FileNotFoundError:
print(f'Error: File not found at "{path}"')
except UnidentifiedImageError:
print(f'File at "{path}" is not an image')
sys.exit(1)
def resize_image_in_order_to_fit_in_... | The code converts an image to ASCII art for terminal display by opening the image, resizing it to fit the terminal using a font ratio, generating an ASCII representation with a specified color palette and character coloring function, and printing the result. The function supports random character selection and adjusts ... | def print_ascii_image(
image_path: str,
character_coloring_function: CharacterColoringFunction,
palette: str,
fontratio: float,
random_char: bool,
):
image: ImageClass = try_open_image_if_it_exists(image_path)
image = resize_image_in_order_to_fit_in_terminal(image, fontratio)
ascii_rep... |
def try_open_image_if_it_exists(path: str) -> ImageClass:
try:
return Image.open(path)
except FileNotFoundError:
print(f'Error: File not found at "{path}"')
except UnidentifiedImageError:
print(f'File at "{path}" is not an image')
sys.exit(1)
def reduce_image_and_compensate_font... | This function converts an image into ASCII art by reducing its size, generating a character-based representation using a specified palette and coloring method, and saving the result to a file. It adjusts the image proportions based on font ratio and reduction factors, then writes the ASCII output to the specified path. | def write_ascii_image(
image_path: str,
output_file_path: str,
character_coloring_function: CharacterColoringFunction,
palette: str,
random_char: bool,
fontratio: float,
reduction_factor: float,
):
image: ImageClass = try_open_image_if_it_exists(image_path)
image = reduce_image_and_... |
def tokenize(sentence):
return nltk.word_tokenize(sentence.lower())
def stem(word):
return nltk.PorterStemmer().stem(word.lower())
def bag_of_words(tokenized_sentence , all_words):
tokenized_sentence = [stem(w) for w in tokenized_sentence]
bag = np.zeros(len(all_words), dtype=np.float32)
for idx, w ... | The main task of the code is to load a JSON file containing intents and patterns, process text by tokenizing, stemming, and creating a bag-of-words representation, then generate training data (X_train, y_train) with corresponding labels, unique words (all_words), and intent tags (tags) for a machine learning model. | def dataloader(file):
file_extension = file.split('.')[-1].lower()
if file_extension == 'json':
with open(file) as f:
intents = json.load(f)
else:
raise Exception('File format not supported')
all_words = []
tags = []
xy = []
for intent in intents['intents']:
... |
def BN(name=""):
return BatchNormalization(momentum=0.95, name=name, epsilon=1e-5)
def residual_short(prev_layer, level, pad=1, lvl=1, sub_lvl=1, modify_stride=False):
prev_layer = Activation('relu')(prev_layer)
block_1 = residual_conv(prev_layer, level,
pad=pad, lvl=lvl, sub_lv... | The main task of the code is to construct a ResNet model with either 50 or 101 layers, using residual blocks. It initializes feature extraction with convolutional layers, applies max pooling, and stacks residual blocks (with varying numbers depending on the specified depth) to process input data through progressively d... | def ResNet(inp, layers):
# Names for the first couple layers of model
names = ["conv1_1_3x3_s2",
"conv1_1_3x3_s2_bn",
"conv1_2_3x3",
"conv1_2_3x3_bn",
"conv1_3_3x3",
"conv1_3_3x3_bn"]
# Short branch(only start of network)
# "conv1_1_3x3_s... |
def my_conv_preprocess(inp,regularizer):
conv1 = Conv2D(64, 3, activation = 'relu', padding = 'same', kernel_regularizer = regularizer, kernel_initializer = 'he_normal')(inp)
conv1 = BatchNormalization(axis=-1)(conv1)
pool1 = MaxPooling2D(pool_size=(2, 2))(conv1)
conv2 = Conv2D(128, 2, activation = 're... | This code constructs a PSPNet model for semantic segmentation using a custom encoder instead of ResNet, incorporating a pyramid pooling module to capture multi-scale contextual features. It processes input images through convolutional layers, batch normalization, dropout, and a final 1x1 convolution for class predictio... | def pspnet_small(num_classes, input_shape , resnet_layers=50, regularizer = None):
"""Build PSPNet."""
print("Building a PSPNet based on custom encoder expecting inputs of shape %s and predicting %i classes" % (
input_shape, num_classes))
inp = Input((input_shape[0], input_shape[1], input_sha... |
def entropy(data, outcome_name):
"""
Compute entropy of assuming the outcome is binary
data: a pandas dataframe
outcome_name: a string corresponding to name of the outcome varibale
"""
# compute p(Y=1)
proba_Y1 = np.mean(data[outcome_name])
# check if entropy is 0
if p... | The function recursively builds a decision tree by selecting the best feature and threshold to split data, creating internal nodes with left/right children. Base cases terminate recursion when all outcomes are uniform or max depth is reached, returning leaf nodes with majority class predictions (0 or 1). The tree is co... | def _build_tree(self, data, outcome_name, curr_depth=0):
"""
Recursive function to build a decision tree. Refer to the HW pdf
for more details on the implementation of this function.
data: pandas dataframe
outcome_name: a string corresponding to name of the outcome varibale
... |
def move_obstacles(self):
for obstacle in self.obstacles:
speed = random.randint(1, 5)
direction = Vec2d(1, 0).rotated(self.car_body.angle + random.randint(-2, 2))
obstacle.velocity = speed * direction
def move_cat(self):
speed = random.randint(20, 200)
self.c... | This code handles car movement based on actions (turn left/right), updates obstacles/cat positions, renders game elements (segments, circles, polygons), checks collisions, calculates sonar readings, normalizes sensor data, determines reward (penalty for crashing, reward for open space), and returns the reward and state... | def frame_step(self, action):
if action == 0: # Turn left.
self.car_body.angle -= .2
elif action == 1: # Turn right.
self.car_body.angle += .2
# Move obstacles.
if self.num_steps % 100 == 0:
self.move_obstacles()
# Move cat.
if self... |
def _raise_for_invalid_filing_type(filing_type: Optional[str]):
if not filing_type:
raise ValueError("Filing type is empty.")
elif filing_type not in VALID_FILING_TYPES:
raise ValueError(
f"Filing type was {filing_type}. Expected: {VALID_FILING_TYPES}"
)
def is_item_title(tit... | This function extracts narrative text elements under a specified section heading by analyzing document elements, without relying on the table of contents. It identifies section boundaries using title checks, collects NarrativeText/ListItem elements within the section, and returns them as a list. The implementation avoi... | def get_section_narrative_no_toc(self, section: SECSection) -> List[NarrativeText]:
"""Identifies narrative text sections that fall under the given section heading without
using the table of contents."""
_raise_for_invalid_filing_type(self.filing_type)
# NOTE(robinson) - We are not skipp... |
def _raise_for_invalid_filing_type(filing_type: Optional[str]):
if not filing_type:
raise ValueError("Filing type is empty.")
elif filing_type not in VALID_FILING_TYPES:
raise ValueError(
f"Filing type was {filing_type}. Expected: {VALID_FILING_TYPES}"
)
def get_table_of_cont... | This function extracts narrative text from a document section by locating its start and end points using the table of contents (TOC). It handles edge cases like missing TOC entries or sections not found, ensuring it only returns text within the specified section's boundaries, avoiding unnecessary data retrieval. | def get_section_narrative(self, section: SECSection) -> List[NarrativeText]:
"""Identifies narrative text sections that fall under the given section heading"""
_raise_for_invalid_filing_type(self.filing_type)
# NOTE(robinson) - We are not skipping table text because the risk narrative section
... |
def unchecked_move(self, move):
start, end = move
self.set(end, self.get(start))
self.set(start, None)
self.get(end).move(end)
def get_attacked_squares(self):
squares = []
for piece in self.get_pieces():
if piece.color != self.current_color:
sq... | The function `safe_move` validates a move, executes it if valid, switches the current player's turn, updates attacked squares, checks if the king is in check, generates new available moves, identifies check-causing pieces, and resets the check status. It ensures game state consistency after each move while enforcing ru... | def safe_move(self, move):
# If the entered move is a valid move.
if move in self.moves:
# perform the physical move.
self.unchecked_move(move)
# change the current color flag.
self.current_color *= -1
# get the squares the enemy is attacki... |
def get(self, position):
return self.board[position[1]][position[0]]
def is_safe(self, pos):
for enemy_attack in self.enemy_moves:
if pos == enemy_attack[1]:
return False
return True
def get_pieces_causing_check(self):
return [s for (s, e) in self.enemy_moves ... | This function determines if a move gets the king out of check by checking if the destination is safe, if the move captures the attacking piece, or if it blocks the attacker's path to the king. | def moves_out_of_check(self, move):
piece = self.get(move[0])
# If the piece to move is a king.
if isinstance(piece, King):
# Make sure the king is not moving into an attacked square.
return self.is_safe(move[1])
# Get the pieces causing check.
enemies... |
def get_king_pos(self):
for piece in self.get_pieces():
if isinstance(piece, King) and piece.color == self.current_color:
return piece.pos
def is_safe(self, pos):
for enemy_attack in self.enemy_moves:
if pos == enemy_attack[1]:
return False
... | The function `moves_into_check` checks if a move would expose the king to check. If the move involves the king, it verifies the new position's safety. For other pieces, it checks if the path between the king and the moving piece is clear, then examines the extended line for obstacles. It ensures no friendly pieces bloc... | def moves_into_check(self, move):
k_pos = self.get_king_pos()
# If a king make sure we move into a safe square only.
if move[0] == k_pos:
return not self.is_safe(move[1])
# If the king and the piece are directly connected.
if self.path_clear((k_pos, move[0])):
... |
def move_in_bounds(self, move):
return self.in_bounds(move[0]) and self.in_bounds(move[1])
def empty(self, position):
return self.get(position) == None
def valid_move_journey(self, move):
p1 = self.get(move[0])
p2 = self.get(move[1])
return p1.valid_target(p2) and self.path_clear... | This function validates a chess move by checking if it is within bounds, starts with a piece, has a valid path, doesn't leave the king in check, and doesn't move the king into check. It returns True if all conditions are met, otherwise False. | def valid_move(self, move):
# If the start and end of the move are not in bounds.
if not self.move_in_bounds(move):
return False
# If the position of the start doesnt contain a piece.
if self.empty(move[0]) == None:
return False
# If the desination and ... |
def sphere_sample(num_interps, mag=1):
#define two orthogonal unit vec u, v
u = np.random.normal(size = dim_z)
u *= mag/np.linalg.norm(u)
v = np.random.normal(size = dim_z)
v -= v.dot(u) * u
v *= mag/np.linalg.norm(v)
alphas = np.linspace(0, math.pi * 2, num_interps)
z = np.array([math.... | The code generates multiple image sequences by looping through specified iterations, creating twisted sphere samples, and producing movies. It samples latent vectors, applies twisting transformations, generates images with a session, saves them, and compiles them into movies, printing the output paths. | def n_loops(sess, num_loops, num_frames, num_twists=1, mag=1, angle=1):
for i in range(num_loops):
z = sphere_sample(num_frames, mag=mag)
for n in range(num_twists):
z = twist_z(angle, z)
y = random.randint(0,1000)
ims = sample(sess, z, y, truncation=1., batch_size=1)
path = save_sequence(im... |
def wakeup():
r=sr.Recognizer()
with sr.Microphone() as source:
print("Listening for wake up...")
audio=r.listen(source)
try:
statement=r.recognize_google(audio,language='en-in')
print('Wake up ' + statement)
except Exception as e:
print('No vo... | The code defines a voice assistant that listens for commands, performs actions like telling time, insults, compliments, weather, and answering questions, and exits when told "power down," continuously offering further help unless the session ends. | def main ():
command = ''
while True:
command = wakeup()
if command.count(WAKE) > 0:
speech("I am ready")
while command != "power down":
command = listening()
if "time" in command:
cur_time()
elif "insult... |
def filling_phase_dynamic_matrix(self, t):
"""
:param t: time (s)
:return: A matrix for filling phase
"""
el = self.elastance(t)
del_dt = self.elastance_finite_difference(t)
return [[del_dt/el - el/self.R2, el/self.R2, 0, 0],
[1/(self.R2*self.C2),... | The code computes the time derivatives of cardiac state variables (ventricular pressure, atrial pressure, arterial pressure, aortic flow) using a phase-dependent dynamic matrix A₁(t). The matrix is selected based on the current physiological phase: filling (atrial > ventricular pressure), ejection (positive aortic flow... | def get_derivative(self, t, x):
"""
:param t: time
:param x: state variables [ventricular pressure; atrial pressure; arterial pressure; aortic flow]
:return: time derivatives of state variables = A_1(t)x
"""
if x[1] > x[0]:
#filling
A_1 = self.fill... |
def get_min_index_and_value_in_b(standard_form: StandardForm) -> tuple:
b = standard_form.get_b()
min_value = float('Inf')
min_index = 0
for index in range(len(b)):
if b[index] < min_value:
min_value = b[index]
min_index = index
return ... | The code initializes a simplex method for solving a linear programming problem in standard form. It constructs a slack form, checks feasibility by ensuring all right-hand side values (b) are non-negative. If not, it creates an auxiliary problem with an artificial variable (x0), performs pivoting to eliminate negative b... | def initialize_simplex(self, standard_form: StandardForm):
b = standard_form.get_b()
min_value, min_index = self.get_min_index_and_value_in_b(standard_form)
A = standard_form.get_A()
c = standard_form.get_c()
N = []
for i in range(len(c)):
N.append(i + 1)
... |
def initialize_simplex(self, standard_form: StandardForm):
b = standard_form.get_b()
min_value, min_index = self.get_min_index_and_value_in_b(standard_form)
A = standard_form.get_A()
c = standard_form.get_c()
N = []
for i in range(len(c)):
N.append(i + 1)
... | The code implements the simplex algorithm to solve a linear programming problem in standard form. It first checks feasibility using `initialize_simplex`; if infeasible, it exits. Otherwise, it runs `simplex_main` to find an optimal solution. If unbounded, it prints "unbounded." Otherwise, it extracts and prints the opt... | def simplex(self, standard_form: StandardForm):
number_of_vars = len(standard_form.get_c())
# first call the initialize_simplex procedure
result = self.initialize_simplex(standard_form)
# if initialize_simplex returns "infeasible", return.
if result == "infeasible":
p... |
def identity_mat(m):
p=zeromatrix(m,m)
for i in range(m):
p[i][i] = 1
return(p)
def gauss_seidel(A, B, eps=1.0e-4):
# Check: A should not have zero on diagonals
for i in range(len(A)):
if A[i][i] == 0:
return ("Main diagonal should not have zero!"... | This code computes the inverse of matrix A using the Gauss-Seidel method. It iteratively solves Ax = e_i for each standard basis vector e_i, constructing the inverse matrix column-by-column. The function returns the computed inverse matrix and the final residue from the last iteration, with a specified tolerance (eps). | def gauss_seidel_inverse(A,eps=1.0e-4):
I=identity_mat(len(A))
for i in range(len(A)):
I[i],residue=gauss_seidel(A,transpose(I[i]),eps)
A_inv=zeromatrix(len(A),len(A))
for i in range(len(A)):
for j in range(len(A)):
A_inv[i][j]=I[i]... |
def mat_mult(a,b):
if len(a[0])==len(b):
p=zeromatrix(len(a),len(b[0]))
for i in range(len(a)):
for j in range(len(b[0])):
for x in range(len(b)):
p[i][j]+=(a[i][x]*b[x][j])
... | The code implements the **power method** to compute the **dominant eigenvalue** and its corresponding **eigenvector** of a matrix `A`. Starting with an initial vector `x0`, it iteratively applies matrix-vector multiplication, normalizes the result, and updates the eigenvalue estimate using the Rayleigh quotient (`dotU/... | def power_method(A, x0 = [[1],[1],[1]], eps=1.0e-4):
i = 0
lam0 = 1
lam1 = 0
while abs(lam1-lam0) >= eps:
#print("error=",abs(lam1-lam0))
if i != 0:
lam0 = lam1
Ax0 = mat_mult(A,x0)
AAx0 = mat_mult(A,Ax0)
#print("Ax0=",Ax0)
#print("AAx... |
def mat_mult(a,b):
if len(a[0])==len(b):
p=zeromatrix(len(a),len(b[0]))
for i in range(len(a)):
for j in range(len(b[0])):
for x in range(len(b)):
p[i][j]+=(a[i][x]*b[x][j])
... | The code implements the Conjugate Gradient method to solve a system of linear equations $Ax = B$, starting from an initial guess $x_0$. It iteratively updates the solution $x_k$ by computing residuals $r_k$, search directions $d_k$, and step sizes $\alpha$ and $\beta$, halting when the residual's norm falls below the t... | def conjugate_gradient(A, B, x0 , eps=1.0e-4):
#r0 = make_matrix(len(A), 1)
xk = [i for i in x0]
#r0=b-Ax0
Ax0 = mat_mult(A, x0)
rk = matrix_substraction(B, Ax0)
#print("rk",rk)
dk = [i for i in rk]
#print("dk",dk)
i=0
while conju_norm(rk)>=eps and i in range(len(A)):
... |
def matrix_multiplication_on_the_fly(Afn,B):
n = int(math.sqrt(len(B)))
#print('B',len(B))
#print('n',n)
m = zeromatrix(len(B),1)
for i in range(len(B)):
for j in range(len(B)):
m[i][0] = m[i][0] + (Afn(i,j,n) * B[j][0])
#print('m',m)
return m
def matrix_substraction(A, B... | The code implements the Conjugate Gradient (CG) method to solve a linear system $ Ax = B $ iteratively, where $ A $ is not explicitly formed but accessed via a function $ Afn $. It computes an approximate solution $ x_k $ starting from an initial guess $ x_0 $, updating the residual $ r_k $ and search direction $ d_k $... | def conjugate_gradient_on_the_fly(Afn, B, eps):
x0 = []
a=[1]
for i in range(len(B)):
x0.append(a)
#print('x01',x0)
import copy
xk = copy.deepcopy(x0)
#r0=b-Ax0
Ax0 = matrix_multiplication_on_the_fly(Afn, x0)
#print("Ax0",Ax0)
rk = matrix_substraction(B, Ax0)
... |
def node_creation(self, x, y, current_node): # intended to handle new nodes and existing nodes no forces, both cases work
print(f"Number of nodes in backend list is {self.number_of_nodes} and current node number is {current_node} from gui.")
# so node number doesn't exist in list of nodes
... | This function creates or updates nodes and their associated forces in a system. If the node is new, it generates both the node and force. For existing nodes, it updates their positions and forces based on input parameters, ensuring forces are initialized or modified appropriately. The function handles four scenarios: n... | def node_creation_with_force(self, x, y, number_of_node, force, angle): # to handle new nodes and existing node, with new or existing with forces
# Node is completely new with new force, doesn't exist in list of nodes, need to create both
if number_of_node > self.number_of_nodes:
s... |
def createInfoLabel(self, message):
self.noteContainer = QFrame() # To get outline of note
self.noteContainer.setFixedHeight(100) # On frame min and max
self.noteLayout = QVBoxLayout() # Add things up to down
self.noteLayout.setSpacing(0)
self.note = QLabel("Note:") # look at ma... | The code creates a GUI window with a horizontal layout containing a node management section. It sets up a scrollable area for inputting node positions, symmetry flags, and delete options, along with an "Add Node" button. Widgets include labels, text fields, checkboxes, and radio buttons organized in grouped layouts to ... | def createWindow(self):
# region Window Widget and Layout Creation
#&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
self.canvas = QWidget() # a blank widget that will only hold the main layout for widgets, gets color from stylesheet
self.mainLayout = QHBoxLayout() # As we add stuff it will... |
def createInfoLabel(self, message):
# region Info Label Widget and Layout Creation
#(((((((((((((((((((())))))))))))))))))))
self.noteContainer = QFrame() # To get outline of note
self.noteContainer.setFixedHeight(100) # On frame min and max
self.noteLayout = QVBoxLayout() # Add ... | The code creates a GUI window with two columns: one for managing nodes (positions, symmetry) and another for forces (magnitude, angle). It sets up scrollable input areas, labels, and buttons to dynamically add entries, using QHBoxLayout and QVBoxLayout for layout management, with QScrollArea for handling dynamic conten... | def createWindow(self):
# region Window Widget and Layout Creation
#&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
self.canvas = QWidget() # a blank widget that will only hold the primary layout for widgets
self.mainLayout = QHBoxLayout() # As we add stuff it will be placed horizatonal... |
def createInfoLabel(self, message):
# region Info Label Widget and Layout Creation
#(((((((((((((((((((())))))))))))))))))))
self.noteContainer = QFrame() # To get outline of note
self.noteContainer.setFixedHeight(100) # On frame min and max
self.noteLayout = QVBoxLayout() # Add ... | The code creates a GUI window for inputting structural elements and supports. It sets up two main sections: "Elements" (for coordinate inputs with scrollable entries) and "Supports" (for roller/pin inputs). Each section includes labels, editable fields, delete options, and buttons to add entries or calculate results. T... | def createElementWindow(self):
# region Window Widget and Layout Creation
#&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
self.canvas = QWidget() # a blank widget that will only hold the primary layout for widgets
self.mainLayout = QHBoxLayout() # As we add stuff it will be placed hori... |
def get_position(player):
return str(fantasy_pros_ids[fantasy_pros_ids["name"]==player]['position'].iloc[0])
def get_player_weekly_stats(player, year=current_season):
player = format_name(player)
url = f"https://www.fantasypros.com/nfl/games/{player}.php?scoring=PPR&season={year}"
data = scrape_table(ur... | This function calculates projected fantasy points for a player using Z-scores, comparing their historical performance to league-wide points against data. It combines current and previous season stats if needed, then projects future games by adjusting the player's average points based on opponent strength. The output in... | def get_z_score_projections(player, points_against_dfs, year=current_season):
teams_database=get_abbreviations()
position = get_position(player)
points_against_df = points_against_dfs[position]
player_df = get_player_weekly_stats(player, year)
teams_mean = points_against_df["FPts"].mean()
teams_... |
def haversine(lon1, lat1, lon2, lat2):
"""
Calculate the great circle distance in kilometers between two points
on the earth (specified in decimal degrees)
"""
lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2])
dlon = lon2 - lon1
dlat = lat2 - lat1
a = sin(dlat / 2) ** 2 + c... | The code identifies valid flight segments from a list of route points by calculating distances and velocities between consecutive points. It filters segments with velocities between 250–1800 km/h, discards low-speed segments 40 km/h), and ensures each flight has non-zero distance and duration. It merges flights, remove... | def identify_flights(routes):
flights = []
flight = []
for i in range(1, len(routes)):
# calculate distance and time difference
distance = haversine(routes[i - 1]['longitude'], routes[i - 1]['latitude'], routes[i]['longitude'],
routes[i]['latitude'])
tim... |
def read_location_history(file):
with open(file) as f:
data = json.load(f)
return data['locations']
def get_routes(locations):
routes = []
for location in locations:
timestamp = parse(location['timestamp'])
latitude = location['latitudeE7'] / 1E7
longitude = location['lon... | The main task of the code is to process location data from a JSON file, identify flight segments, calculate their duration, distance, and speed, and print detailed flight information including start/end times, airports, and travel metrics. | def main():
file = 'Records.json'
locations = read_location_history(file)
routes = get_routes(locations)
flights = identify_flights(routes)
for flight in flights:
start_time = flight[0]['timestamp']
end_time = flight[-1]['timestamp']
duration = end_time - start_time
d... |
def handleCD(path: list, dir: str) -> list:
if dir == "/":
return ['/']
elif dir == "..":
path.pop()
return path
elif dir == ".":
return path
else:
path.append(dir)
return path
def getStdout(inputList: list, index: int):
stdout = []
for i in range(... | The main task of the code is to parse a list of shell commands (cd/ls) and construct a file system structure (`fs`) by updating directory hierarchies and file listings. It tracks the current path via `handleCD` for `cd` commands and processes `ls` outputs with `handleLS` to populate directory contents, returning the fi... | def puzzle1(inputList: list):
fs = [{"name": "/",
"subDirs": [],
"files": [],
"parent": -1,
"type": "dir"}, ]
path = []
i = 0
while i < len(inputList):
cmd = inputList[i].split(" ")
if cmd[1] == "cd":
path = handleCD(path, cmd[2])
... |
def Select(self, node, state):
# Handle timeout
if time.time() - self.start_time >= self.time_limit:
return False
# If there is no child for the current node, choose this node
if len(node.child) == 0:
return node, state
else:
# Init
... | The code implements a Monte Carlo Tree Search (MCTS) algorithm to determine the optimal move in a game. It iteratively selects, expands, simulates, and backpropagates results through a tree of game states, updating node scores based on simulated outcomes. The process continues until the time limit is reached, after whi... | def MCTS(self, game_state):
root = TreeNode(None, None, self.id)
while time.time() - self.start_time < self.time_limit:
deepcopy_board = deepcopy(game_state)
# Select
select_ans = self.Select(root, deepcopy_board)
if select_ans is False:
r... |
def Select(self, node, state):
# Handle timeout
if time.time() - self.start_time >= self.time_limit:
return False
# If there is no child for the current node, choose this node
if len(node.child) == 0:
return node, state
else:
# Init
... | The code implements Monte Carlo Tree Search (MCTS) to determine the optimal move in a game. It iteratively selects, expands, simulates, and backpropagates results through a tree of game states, using time constraints to limit iterations. The algorithm evaluates possible outcomes, calculates rewards based on game outcom... | def MCTS(self, game_state):
count = 0
root = TreeNode(None, None, self.id)
while time.time() - self.start_time < self.time_limit:
count += 1
deepcopy_board = deepcopy(game_state)
# Select
select_ans = self.Select(root, deepcopy_board)
... |
def FilterAction(self, actions):
outer_corner = {(0, 0), (0, 7), (7, 0), (7, 7)}
inner_corner = {(1, 1), (1, 6), (6, 1), (6, 6)}
# Find whether the candidate actions contains the outer corner
sub_actions = list(set(actions).intersection(outer_corner))
if len(sub_actions) > 0:
... | This code selects an action in a game by exploring possible moves using BFS within a time limit. It prioritizes stable actions, uses random choices when applicable, and evaluates paths by simulating opponent moves to maximize scores. The function tracks exploration depth and game-ending states, returning the optimal ac... | def SelectAction(self, actions, game_state):
self.select_time += 1
# Init
start_time = time.time()
self.game_rule.agent_colors = game_state.agent_colors
queue = deque([(game_state, [])])
max_score = 0
count = 0
# Random choose
random_actions = sel... |
def displayOpeningScreen():
""" Displays the program introduction.
The user clicks the "Start" button to start using the program.
"""
window = GraphWin("Productivity Visualization", WINDOW_WIDTH, WINDOW_HEIGHT)
window.setBackground('azure')
welcomeText = Text(Point(WINDOW_WIDTH/2, 1... | The code's main task is to manage a productivity tracking system through a menu-driven interface. It allows users to input and visualize daily or weekly productivity data, using color-coded courses. The program loops to offer repeated options, handling user selections to either input data for a specific day/week or dis... | def main():
displayOpeningScreen()
userName, numCourse, courseToColorDict, userDataFile = displayAccountScreen()
continueUsingProgram = True
while continueUsingProgram:
userChoice = displayMenuScreen(userName)
if userChoice == "Daily Productivity Visualization":
wee... |
def get_num(atm:str):
num = ''
for alp in atm:
if alp.isdigit():
num+= alp
return int(num)
def fixvar_compare(fixvar1, fixvar2):
file1 = open(fixvar1,'r').readlines()
file2 = open(fixvar2,'r').readlines()
equals ={'name':[fixvar1.split('\\')[-1],fixvar2.split('\\')[-1]]}
... | The code compares structural poses between two molecular structures (struc1 and struc2) using specified parameters (lims), generating metrics like stability, hydrogen bonds, and intra-hydrogen bonds. It creates an Excel file with sheets for each parameter set, comparing matched poses and handling unmatched poses with '... | def homogeneous_comparison(struc1, fixvar1, struc2, fixvar2,lims):
Exhaustive = 'N'
#Get all pose folder names from both sides first
folder_list1, folder_list2 = {}, {}
for pose in os.listdir(struc1.Master_folder):
if pose.startswith('Pose_') and os.stat(struc1.Master_folder+'\\'+ pose... |
def plot_data(x_df, y_df,features):
X = x_df.values
plt.figure(figsize=(10,10))
plt.title("Price Distribution")
plt.hist(y_df, bins=30)
plt.show()
#cols = x_df.columns()
fig, ax = plt.subplots(1, len(features), sharey=True, figsize=(20,5))
plt.title("Relationship between different input ... | The main task of the code is to switch from the Boston housing dataset to the California housing dataset, perform data exploration, remove outliers, preprocess data, train either an SVM or MLP model based on user selection, and evaluate the best model's performance on the test dataset. | def main():
# Get data
### To Do Assignment: try changing the data from Boston housing to California housing dataset
### You can load the datasets as follows::
### from sklearn.datasets import fetch_california_housing
### housing = fetch_california_housing()
### Refer this link for more... |
def currlist(n=1000):
while len(CURRLIST) < n:
c = random_currency()
if c not in CURRLIST:
CURRLIST.append(c)
assert len(CURRLIST) == n
CURRLIST.sort()
return (CURRLIST)
def now():
return datetime.datetime.now()
def ms_since(start):
elapsed = now() - start
ms = el... | The main task of the code is to concurrently create multiple currencies using asynchronous tasks and measure the time taken. It initializes a currency list, spawns asynchronous creation tasks for each currency, executes them in parallel via asyncio, and prints the number of currencies processed along with the elapsed t... | def test_create_currencies():
currlist()
start = now()
tasks = [create_currency(c) for c in CURRLIST]
loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.wait(tasks))
elapsed = ms_since(start)
print(f"Sent {len(CURRLIST)} currencies to bankware in {elapsed} ms") |
def str_para_tabuleiro(s):
estados=('0','1')
nana=('[',']')
i=0
aux=[] # vetor auxiliar para guardar os valores a converter em tabuleiro
if isinstance(s, str):
for i in range(len(s)):
if s[i] in estados:
if s[i-1]=='-': #se encontrar o 1 e tiver um menos an... | The code simulates a quantum game where the player applies quantum gates (X, Z, or H) to qubits (left or right) to transform an initial board into a target configuration within a limited number of moves. The function parses input parameters for maximum moves and the target board, then iteratively prompts the user to se... | def hello_quantum(arg):
moves=int(arg[-1:])#guarda o numero de jogadas maximas a realizar
res=str_para_tabuleiro(arg[:-2])#guarda o tabuleiro final
tabuleiro=tabuleiro_inicial()#guarda o tabueliro de jogo
count=0 # contador para nao ultrapassar as jogadas maximas
print('Bem-vindo ao Hello Quantum!')... |
def combine_primary_tables(data_dir, output_dir):
"""
Build all the primary tables, i.e., tables that require no joins,
and return them in a dictionary.
@param data_dir: [`string`] The file path to read the PSet tables
@param output_dir: [`string`] The file path to write the final tables
@retur... | The main task of the code is to aggregate all PSet tables from the input directory into unified PharmacoDB tables, combining primary, secondary, and experiment data through sequential joins. The result is a dictionary of consolidated tables stored in the output directory, enabling subsequent database operations and joi... | def combine_all_pset_tables(data_dir, output_dir):
"""
Combine all PSet tables into the final PharmacoDB tables.
@param data_dir: [`string`] The file path to read the PSet tables
@param output_dir: [`string`] The file path to write the final tables
@return: [`dict(string: datatable.Frame)`] A dicti... |
def quit_check(self) -> None:
if self._player.lives == 0:
self.quit(message=f'Game over\nScore: {self._player.score}')
for event in pg.event.get():
if event.type == pg.QUIT:
self.quit()
def background(self):
offset = pg.time.get_ticks() // 100 % WIDTH
... | This method runs the game loop, continuously checking for exit events, rendering the background and game objects, displaying the player's score and lives on the screen, and maintaining a consistent frame rate using a clock. It updates the display repeatedly to create the illusion of motion in the game. | def game_loop(self) -> None:
while True:
self.quit_check()
self.background()
self.objects()
score = self._font.render(f'Score: {self._player.score}', True, (255, 255, 255))
lives = self._font.render(f'Lives: {self._player.lives}', True, (255, 255, 255)... |
def search_once(self):
path_list = []
best_length = float('inf')
best_path = None
for i in range(self.n_ants):
path = self._ant_go()
length = self._calc_path_length(path)
path_list.append((length, path))
if length < best_length:
... | The code performs iterative optimization to find the shortest path, tracking the best solution found, logging progress if enabled, and plotting results at specified intervals. It returns the optimal path length and path after completing the maximum number of iterations. | def search(self, max_iter=200, verbose=None, plot_interval=None):
best_length = float('inf')
best_path = None
length_list = []
for i in range(1, max_iter + 1):
length, path = self.search_once()
length_list.append(length)
if length < best_length:
... |
def _log(self, iter_time, length, path):
print(f'Iterate: {iter_time}, Length: {length:.4f}, Path: {path}')
def _plot_path(self, iter_time, length, path):
for i in range(-1, self.n_cities - 1):
x = [self.cities[path[i]][0], self.cities[path[i + 1]][0]]
y = [self.cities[path[i]][1... | This function evolves a population of 'Gene' objects to find the optimal path by iteratively improving solutions over a set number of iterations. It initializes genes, tracks the best path, and updates it if a shorter length is found. Optional logging and plotting occur at specified intervals. After iterations, it retu... | def evolve(self, max_iter, verbose=None, plot_interval=None):
self.genes = [Gene(self.distance, self.alpha)
for i in range(self.n_genes)]
best_gene = max(self.genes, key=lambda x: x.length)
best_length, best_path = best_gene.length, best_gene.path
length_list = [bes... |
def find_communities(X, pp_method = None, method = 'tani', nbr_num = 10, n_threads = None, verbose = False, keep_temp_files = False, temp_name = '', partition_type = la.RBConfigurationVertexPartition, resolution = 0.8, seed = None, local = False, **kwargs):
"""_summary_
Parameters
----------
X : numpy... | (The code performs clustering on input data `X` using platform-specific methods. On Linux, it directly applies `find_communities`; otherwise, it preprocesses `X` with `pp()` and uses `bc()` for clustering. Parameters like `nbr_num`, `method`, and `seed` control the process, ensuring cross-platform compatibility for com... | def clustering(X, nbr_num = 10, seed = None, local = False, method = 'tani', pp_method = None, **kwargs):
if sys.platform.startswith("linux"):
return(find_communities(X, nbr_num=nbr_num, seed = seed, local = local, method = method, pp_method = pp_method, **kwargs))
else:
X = pp(X)
retur... |
def energy(image):
#image = cv2.GaussianBlur(image, (5, 5), 5)
sobelx = np.abs(cv2.Sobel(image, cv2.CV_64F, 1, 0, ksize = 3))
sobely = np.abs(cv2.Sobel(image, cv2.CV_64F, 0, 1, ksize = 3))
grad_mag = np.clip(sobelx + sobely, 0, 255).astype(np.uint8)
return grad_mag
def get_energy_DP(e):
h, w = ... | The main task of the code is to perform seam carving on an uploaded image. It converts the image to grayscale, calculates energy maps, identifies low-energy seams using dynamic programming, and removes these seams to resize the image. The process displays the original image, gradient energy map, and final output while ... | def main():
#img = image.copy()
#h,w = image.shape[:2]
#if len(image.shape) == 3:
uploaded_file = st.file_uploader("Choose an image...", type="jpg")
if uploaded_file is not None:
i = Image.open(uploaded_file)
image = np.array(i)
st.write("<h3 style='color: bl... |
def get_energy_DP(e):
h, w = e.shape
DP = np.zeros_like(e, dtype = np.uint32)
DP[h - 1] = e[h - 1].astype(DP.dtype)
for x in range(h - 2, -1, -1):
for y in range(w):
_min = DP[x + 1][y]
if y - 1 >= 0:
_min = min(_min, DP[x + 1][y - 1])
if... | The code processes an uploaded image using a pre-trained neural network model to predict and modify the image. It normalizes the input, applies the model to generate a gradient map, computes energy for seam carving, identifies seams, and applies seam carving to reduce image dimensions. The original and modified images ... | def main():
uploaded_file = st.file_uploader("Choose an image...", type="jpg")
if uploaded_file is not None:
i = Image.open(uploaded_file)
image = np.array(i)
st.image(image,caption="ORIGINAL IMAGE")
imagelocation = st.empty()
if st.button("Run"):
tf.c... |
def draw_board(canv):
for i in range(8):
for j in range(8):
x1 = j * 50
y1 = i * 50
x2 = x1 + 50
y2 = y1 + 50
fill = "white" if (i+j) % 2 == 0 else "black"
canv.create_rectangle(x1, y1, x2, y2, fill=fill)
def reset(canv, txt, root):
... | The main task of the code is to create a graphical chess game interface using Tkinter. It initializes a window with a chessboard canvas, displays turn instructions, adds a reset button, and renders chess pieces. The interface allows user interaction for selecting pieces and making moves, while updating the status label... | def main():
root = Tk()
root.geometry("500x550")
root.title("Chess")
canv = Canvas(root, width = 401, height = 401, highlightthickness=0)
canv.pack()
draw_board(canv)
# make a general label that will go under the canvas and display the
# current turn and check/checkmate status
txt = ... |
def precision_at_k(y_true, y_pred, k):
tp, fp, = 0, 0
for triples_true, triples_pred in zip(y_true, y_pred):
# Filter out triples below k
triples_pred = set([triple for conf, triple in triples_pred if conf >= k])
for triple in triples_pred:
if is_in(triple, triples_true):
... | The function `classification_report` calculates and returns precision@k, recall@k, F1@k, and PR-AUC metrics for evaluating predicted triples against true triples. It computes these metrics using helper functions and prints them for clarity. The input parameters include true and predicted triples, along with a cutoff va... | def classification_report(true_triples, pred_triples, k):
""" Computes precision@k, recall@k, F1@k and PR-AUC over gold
triples and predictions.
:param true_triples:
:param pred_triples:
:param k:
:return:
"""
precision = precision_at_k(true_triples, pred_triples, k)
recall = re... |
def startPreview(self):
self._foundThisPass = self.foundThisPass
for row in self.cells:
for cell in row:
cell.takeSnapshot()
self._inPreview = True
self._lookahead = 10
def setCell(self, cell:Cell, value: int):
logging.info("setCell: value={}".format(v... | This function tests if a value can be placed in a cell by temporarily applying it, checking for conflicts. If successful, it commits the value; if conflicts arise, it removes the value from the cell's potentials and triggers group updates. Returns True if the value was invalid and requires adjustment, False otherwise. | def trialValue(self, cell: Cell, value: int) -> bool:
logging.info("Trialing {} in {}".format(value, cell))
self.startPreview()
initialCount = self.foundThisPass
try:
self.setCell(cell, value)
except LookAheadExceeded:
pass
except PuzzleSolved:
... |
def setCell(self, cell:Cell, value: int):
logging.info("setCell: value={}".format(value))
if not cell.isPotentialValue(value):
raise BadPuzzleState("Trying to set value for a cell that is not allowed")
cell.setValue(value)
self.flashCellValues(cell)
self.foundThisPass... | The code solves a Sudoku puzzle by initializing potential values for each cell, solving cells with unique values first, then iteratively applying strategies like group processing, row/column constraints, pair/triple identification, and backtracking to resolve remaining cells when stuck. | def solve(self):
# Set the potential values
logging.info("Set the inital potential values")
initiallySolved = []
for row in self.cells:
for cell in row:
if cell.complete():
continue
cell.potentialValues = [x for x in range(1... |
def extract_config_info(proj_dir):
"""Read Cargo.toml and filesystem to get the name of rust source files and binary names
"""
if not os.path.isdir(proj_dir):
raise RuntimeError(f"Given project directory is not a directory: {proj_dir}")
toml_path = os.path.join(proj_dir, "Cargo.toml")
if no... | The code generates a call graph for a Rust project by extracting configuration details, updating source code information, executing a call stack analysis, and converting the result into JSON format for output. | def generate_call_graph(args):
rust_file, bin_name = extract_config_info(args.proj_dir)
file_class = RustFileDetails(rust_file, args.proj_dir)
update_source_code(file_class)
dot_data = execute_call_stack(args.proj_dir, args.compiler, bin_name)
if not args.output_path:
output_path = os.path.j... |
def load_data():
df_train = pd.read_csv('../input/train.csv')
df_train.sort_values('time', inplace=True)
df_test = pd.read_csv('../input/test.csv')
ninety_percent_mark = int(df_train.shape[0]*0.9)
df_valifold = df_train[ninety_percent_mark:].copy()
df_trainfold = df_train[:ninety_percent_mark]... | The main task of the code is to load and prepare datasets, configure parallel processing and optimization parameters via environment variables, then execute a grid search/optimization process using `iterate_over_grid`, with optional Bayesian per-bin optimization based on environment settings. | def main():
train_data, test_data, trainfold, valifold = load_data()
for x in (train_data, test_data, trainfold, valifold):
prepare_data(x)
if 'NJOBS' in os.environ:
njobs = int(os.environ['NJOBS'])
else:
njobs = 1
if 'IJOB' in os.environ:
ijob = int(os.environ['IJ... |
def direct_hit():
print('Request sent to Master -', master_public_ip, '\n')
return master_public_ip
def random_hit():
slave = get_random_slave(slaves_public_ip)
print('Request sent to Slave', slaves_public_ip.index(slave) + 1, '-', slave, '\n')
return slave
def customized_hit():
fastest_slave =... | The function handles a gatekeeper request by selecting a backend node based on the provided strategy (direct, random, or customized), executing the query on the chosen node, and returning the result as JSON. It extracts the strategy from request parameters, determines the target IP using strategy-specific logic, forwar... | def handle_gatekeeper_request():
# Extract the strategy from the parameters
strategy = request.args.get('strategy')
# Extract the query from the request data
query = request.get_data(as_text=True)
if strategy == "direct":
ip = direct_hit()
elif strategy == "random":
ip = random... |
def get_fastq_stats(fastqfile):
stats = {}
number_reads = 0
longest_read = 0
total_bases = 0
with open(fastqfile, 'r') as fh:
i = 0
for line in fh:
i += 1
if(i % 4 == 0):
number_reads += 1
elif(i % 2 == 0):
bases = l... | The main task of the code is to analyze insertion sites in genomic sequences by assembling contigs from an input assembly, performing BLAST searches against reference sequences and target DNA, mapping reads back to the assembly, and generating visualizations and summaries. It processes fastq reads, identifies insertion... | def analyse_insertion_assembly(lineid, fastqfile, tdnafile, allfasta, outdir, webdir, assembly):
if not (os.path.isdir(outdir)):
os.mkdir(outdir)
statistics= {}
fastq_stats = get_fastq_stats(fastqfile)
statistics["fastq_stats"] = fastq_stats
#run BLAST
blastfile = os.path.join(outdir, li... |
def get_fastq_stats(fastqfile):
stats = {}
number_reads = 0
longest_read = 0
total_bases = 0
with open(fastqfile, 'r') as fh:
i = 0
for line in fh:
i += 1
if(i % 4 == 0):
number_reads += 1
elif(i % 2 == 0):
bases = l... | The function `analyse_insertion` processes sequencing data to analyze insertions by filtering reads, assembling contigs with Canu, annotating contigs via BLAST, mapping reads back to assemblies, and generating visualizations. It collects statistics, creates HTML summaries, and returns assembly and annotation files. Key... | def analyse_insertion (lineid, fastqfile, tdnafile, allfasta, outdir, webdir, filter_reads = None):
if not (os.path.isdir(outdir)):
os.mkdir(outdir)
statistics= {}
fastq_stats = get_fastq_stats(fastqfile)
statistics["fastq_stats"] = fastq_stats
#run BLAST
blastfile = os.path.join(outdir,... |
def arguments():
parser = argparse.ArgumentParser()
parser.add_argument("file", help="data file")
parser.add_argument("process", help="encode or decode", choices=['encode', 'decode'])
return parser.parse_args()
def inputs(text: str) -> (list, list):
with open(text, 'r') as file:
text = file.... | The main task of the code is to perform Huffman encoding on input text. It reads a file, calculates character frequencies, constructs a binary tree, generates encoded data, and writes the encoded result to 'text_test.txt'. The process involves frequency analysis, tree creation, binary encoding, and text replacement wit... | def main():
args = arguments()
file = args.file
process = args.process
list_unique, prob = inputs(file)
list_unique, prob, tree_dict = starting(list_unique, prob)
tree = binary_tree(tree_dict)
tree, result = replace_binary(list_unique, prob, tree)
final = replace_text(file, result)
w... |
def preprocess(docs, samp_size=None):
print('Preprocessing raw texts ...')
if not samp_size:
samp_size = 100
n_docs = len(docs)
sentences = [] # sentence level preprocessed
token_lists = [] # word level preprocessed
idx_in = [] # index of sample selected
samp = np.random.choice(n_... | The code performs topic modeling on academic abstracts using LDA-BERT, extracting 2 topics from a sample of 100 entries in 'MAIN.csv'. It preprocesses text, trains a topic model, visualizes results, and generates word clouds for each topic to represent key themes. | def main():
method = "LDA_BERT"
samp_size = 100
ntopic = 2
data = pd.read_csv('MAIN.csv')
rws = data.abstract
sentences, token_lists, idx_in = preprocess(rws,samp_size=samp_size)
tm = Topic_Model(k=ntopic, method=method)
print('hello1')
tm.fit(sentences, token_lists)
get_topi... |
def _is_scope_subset(self, needle_scope, haystack_scope):
needle_scope = set(needle_scope.split()) if needle_scope else set()
haystack_scope = (
set(haystack_scope.split()) if haystack_scope else set()
)
return needle_scope <= haystack_scope
def is_token_expired(self, token_i... | The function retrieves a cached Spotify authentication token from a file, validates its scope and expiration, and refreshes it if necessary. If the cache path is unset, it uses a username-based default path or raises an error. It returns the token info if valid, or None if the scope doesn't match or the token is expire... | def get_cached_token(self):
""" Gets a cached auth token
"""
token_info = None
if not self.cache_path and self.username:
self.cache_path = ".cache-" + str(self.username)
elif not self.cache_path and not self.username:
raise SpotifyOauthError(
... |
def get_cached_token(self):
""" Gets a cached auth token
"""
token_info = None
if not self.cache_path and self.username:
self.cache_path = ".cache-" + str(self.username)
elif not self.cache_path and not self.username:
raise SpotifyOauthError(
... | The main task of the code is to retrieve an access token using an authorization code, either by fetching a cached token (with optional refresh) or making a new OAuth request. It returns the token as a dictionary or string, issuing deprecation warnings for future format changes. | def get_access_token(self, code=None, as_dict=True, check_cache=True):
""" Gets the access token for the app given the code
Parameters:
- code - the response code
- as_dict - a boolean indicating if returning the access token
as a token_in... |
def crackRSA(e, n):
pqArray = findPrimeFactors(n)
phiN = calculatePhiN(pqArray[0], pqArray[1])
d = getPrivateKey(e, phiN)
return d
def rsaEncrypt(P, e, n):
C = (P ** e) % n
return C
def rsaDecrypt(C, d, n):
P = (C ** d) % n
return P | The main task of the code is to test RSA encryption/decryption by comparing expected vs actual results. It calculates the private key `d` using `crackRSA`, encrypts plaintext, decrypts ciphertext, and prints test case results including `d`, ciphertext, and decrypted plaintext against expected values for validation. | def testCase(testCaseNo, n, e, dExpected, plaintext, ciphertextExpected):
# For Test Case X -----------------------------------------------------------
# Calculate Necessary Values
d = crackRSA(e, n)
ciphertext = rsaEncrypt(plaintext, e, n)
plaintextDecrypted = rsaDecrypt(ciphertext, d, n)
# Pr... |
def getDateStr( fpath, whichList='Confirmed' ):
fname = os.path.basename( fpath )
if whichList=='Confirmed':
prefix = 'PS_'
elif whichList=='TOIs':
prefix = 'TOI_'
elif whichList == 'Predicted':
prefix = 'Predicted'
n = len( prefix )
ix0 = n+fname.rfind( prefix )
ix1 ... | This function processes confirmed exoplanet data from a file, either by loading precomputed values or processing raw data to calculate key properties like TSM, ESM, eclipse depth, and transit signals. It adds missing insolation, units, and gravitational parameters, then returns processed data, missing entries, and a da... | def readConfirmedNExScI( fpath, readExisting=False ):
dateStr = getDateStr( fpath, whichList='Confirmed' )
zRaw = readRawConfirmedNExScI( fpath, readExisting=readExisting )
#if not forceDownload:
if readExisting==True:
if 'allVals' in zRaw:
z = pickle.load(open('confirmedProperties.p... |
def generateAxisScatter( xlim=[0,3100], ylim=[0,26], wideFormat=False, \
whichType='RpTeq', titleStr='', DecStr='', \
showLegend=True ):
fig, ax, axLegend, axc = generateAxes( wideFormat=wideFormat, whichType=whichType, \
s... | This function generates a scatter plot of exoplanets on a (Teq, Rp) graph, plotting equilibrium temperature vs. planet radius. It customizes visual elements like star color coding, TESS indicators, SM significance thresholds, and annotations for solar system planets, stellar tracks, and planetary radii. The plot's appe... | def plotTeqRpScatter( plDict, SMFlag, ms=8, alpha=1, \
starColors=True, applySMcuts=False, survey={}, \
showGrid=True, indicateTESS=False, showSolarSystem=False, \
showStellarTrack=False, showNeptuneRadius=True, \
showJupiterRadius=... |
def generateAxisGrid( xlim=[0,3100], ylim=[0,26], wideFormat=False, whichType='RpTeq', \
RADecStr='', titleStr='', showLegend=True, HeatMap=False ):
if HeatMap:
fig, ax, axLegend, axc = generateAxes( wideFormat=wideFormat, whichType=whichType, \
... | The main task of the code is to generate a grid plot visualizing planets and TOIs based on their equilibrium temperature (TeqK) and radius (RpRE), with options for heatmaps, grid lines, and annotations. It handles different data subsets (e.g., TESS-discovered planets, best-in-class candidates) and includes features lik... | def plotTeqRpGrid( plDict, SMFlag, cgrid=None, titleStr='', \
RADecStr='', dateStr='', wideFormat=True, survey={}, \
TOIGrid=False, bestInClass=False, \
ASCII=False, HeatMap=True, extraNotes=None ):
"""
Plots grid of planets and TOIs by TeqK and RpRE
... |
def readPredictedProperties( SMFlag='TSM', source='Kunimoto2022' ):
if source=='Kunimoto2022':
z = readPredictedProperties_Kunimoto2022( SMFlag=SMFlag )
elif source=='Barclay2018':
z = readPredictedProperties_Barclay2018( SMFlag=SMFlag )
return z
def plotTeqRpScatter( plDict, SMFlag, ms=8, a... | The main task of the code is to generate and save plots visualizing predicted TESS exoplanets using radius-temperature scatter diagrams. It filters stellar data, creates multiple plot configurations with adjustable parameters (e.g., solar system tracks, Neptune/Jupiter radii, formatting), and saves figures in different... | def transmissionPredictedTESS( showSolarSystem=True, wideFormat=False, \
surveyModule='ACWG', showGrid=True, \
showStellarTrack=True, showNeptuneRadius=True, \
showJupiterRadius=True, crossHair=None, \
... |
def readTOIProperties( ipath='toiProperties.pkl', SMFlag='TSM' ):
"""
"""
ifile = open( ipath, 'rb' )
z0 = pickle.load( ifile )
ifile.close()
z = z0['allVals']
z = Utils.fixAnomalousRpRs( z )
planetName = z['planetName']
RA = z['RA_deg']
RAhr = RA*(24/360.)
Dec = z['Dec_deg']... | The main task of the code is to generate a "Best in class" grid plot of exoplanet candidates by combining confirmed planets and TOIs (Transiting Exoplanet Survey Satellite candidates), applying survey-specific filters, and visualizing the top-ranked planets in each radius-temperature cell. The function processes input ... | def gridBestInClass( ipaths={ 'Confirmed':'', 'TOIs':''}, \
wideFormat=True, addSignature=False, survey={}, \
RAMin_hr=None, RAMax_hr=None, \
DecMin_deg=None, DecMax_deg=None, \
SMFlag='TSM', onlyPCs=True, ASCII=False, HeatMap=False ):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.