dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def read_raw_network_data(trafo_id, depth=1, colab=False): """ Reads all csv files from a given transformer stations. Depth is number of parent filders to get to GraphVolt folder. """ #get parent dir of cwd parent_dir = os.getcwd() #print(parent_dir) for _ in range(depth): parent_dir...
The function reads and preprocesses raw network data for graph representation, normalizes measurements and edge data, and encodes datetime features into sine/cosine. It prepares nodes/edges, merges static node data, and returns normalized data with mean/std for PyTorch Geometric temporal use.
def read_and_prepare_data(trafo_id, depth=1, colab=False): """ Reads raw data and prepares it for use as graph with measurements. Now data is ready to be transformed to pytorch geometric temporal data format. """ data, _ = read_raw_network_data(trafo_id, depth=depth, colab=colab) data = fill_dat...
def _read_data(self): dataset, self.mean_and_std = read_and_prepare_data(self._trafo_id, colab=self.colab) # save in self.mean_and_std self._df_edges = dataset["edges_static_data"] self._df_measurments = dataset["measurements"] self.is_pmo = np.array(self._df_measurments.groupby("node_id...
This code initializes a class for processing time-series data, setting parameters like transformer ID, input/output timesteps, and collaboration mode. It reads data, extracts edges with weights/features, and prepares targets/features for model training or analysis, likely for a forecasting or graph-based machine learni...
def __init__(self, trafo_id, num_timesteps_in, num_timesteps_out, colab=False): self._trafo_id = trafo_id self._num_timesteps_in = num_timesteps_in self._num_timesteps_out = num_timesteps_out self.colab = colab self._read_data() self._get_edges_and_edge_weights_and_edge_f...
def validBF(code): cnt = 0 # check if parens are matched. for v in code: if v == '[': cnt += 1 if v == ']': cnt -= 1 if cnt < 0: return False return cnt == 0 def test(prog, constraints): for v in constraints: if v[1] != evaluate(prog, v[0].copy()): return False ...
The code generates a valid Brainfuck-like string by iteratively transforming an initial symbol ('.') using a predefined substitution map (`symbhash`). It checks each generated string against constraints and validity conditions (`validBF`, `test`). The goal is to find a string that satisfies all constraints through symb...
def mine(): # ur constraints here constraints = [ [ [5,1], [1] ], [ [1,6], [7] ], [ [1,1], [6] ], ] # think of it base 8.. symbhash = {'.' : ',', ',' : '[', '[' : ']', ']' : '<', '<' : '>', '>' : '+', '+' : '-', '-' : '.' } curr = ["."] while True: # flush c...
def largeScan(self): self.log.append("ALSN") deltaX = [0, 0, 0, 1, -1, 1, -1, 1, -1, 0, 0, 2, -2, 1, 1, -1, -1, 2, 2, -2, -2, 2, 2, -2, -2] deltaY = [0, 1, -1, 0, 0, 1, -1, -1, 1, 2, -2, 0, 0, 2, -2, 2, -2, 1, -1, 1, -1, 2, -2, 2, -2] for index in range(len(deltaX)): x = sel...
The code executes the agent's next move by either initializing with a first hint (on turn 0) or generating a random hint, updating logs, verifying bitmaps, and checking end conditions. It processes the move recursively and returns whether the end condition is met.
def agentNextMove(self): if (self.turn == 0): self.hints.append(self.hintFactory.firstHint()) self.log.append(self.hints[-1]["log"]) # HINT self.largeScan() if (self.endCondition()): return True self.processAgentNextMove() else:...
def endCondition(self): if (len(self.log) and self.log[-1].split(" ")[0] == "ENDG"): return True if (self.pirateCoord == self.T): self.log.append("ENDG LOSE") return True if (self.playerCoord == self.T): self.log.append("ENDG WIN") retu...
The code simulates a turn-based game where the pirate and agent take turns moving, with specific conditions for revealing coordinates and ending the simulation. It logs each turn, pirate movements, and agent actions, updating the game state until an end condition is met.
def simulate(self): self.log.append("ASPW {}".format(self.playerCoord)) while (not self.endCondition()): self.log.append("TURN {}".format(self.turn + 1)) # TURN SEQUENCE NUMBER if (self.turn == self.r): self.log.append("RVEL {}".format(self.pirateCoord)) # PIRATE ...
def insert_stanford_javascript(tree_width=1200, tree_height=400, tree_node_radius=10): import_javascript(join(SCRIPT_DIR, "c3.min.js")) import_javascript(join(SCRIPT_DIR, "d3.min.js")) import_javascript(join(SCRIPT_DIR, "sentree.min.js")) import_javascript(join(SCRIPT_DIR, "sentrees.min.js"), { "treeWidth":tre...
This code initializes a sentiment tree visualization by configuring dimensions (width, height, node radius), injecting Stanford NLP-related JavaScript and CSS styles, and creating a container div for rendering tree structures. It sets up the foundational elements required to display sentiment analysis results as intera...
def insert_sentiment_markup(tree_width=1200, tree_height=400, tree_node_radius=10): insert_stanford_javascript( tree_width=tree_width, tree_height=tree_height, tree_node_radius=tree_node_radius ) insert_stanford_styles() import_tag("div", className='trees')
def redrawWindowPlay(win, background, ServerButton, ClientButton, BackButton): win.fill((255, 255, 255)) win.blit(pygame.transform.scale(background, (width, height)), [0, 0]) ServerButton.draw(win, (0, 0, 0)) ClientButton.draw(win, (0, 0, 0)) BackButton.draw(win, (0, 0, 0)) font = pygame.font.Sy...
The code defines a fullscreen menu interface with interactive buttons for "Server," "Client," and "Back" using Pygame. It handles mouse hover effects, plays sounds on interaction, and transitions to respective sub-menus or exits the loop when buttons are clicked. The main task is to display a navigation menu for select...
def menuPlay(): run = True BackButton = button((255, 255, 255), width / 2 - width / 15, height / 3 * 2, width / 10, height / 10, "Back") ServerButton = button((255, 255, 255), width / 2 - width / 15, height / 3, width / 10, height / 10, "Server") ClientButton = button((255, 255, 255), width / 2 - width ...
def redrawWindow(win, background, PlayButton, QuitButton, OptionButton): win.fill((255, 255, 255)) win.blit(pygame.transform.scale(background, (width, height)), [0, 0]) PlayButton.draw(win, (0, 0, 0)) QuitButton.draw(win, (0, 0, 0)) OptionButton.draw(win, (0, 0, 0)) font = pygame.font.SysFont('c...
The code defines a menu interface with Play, Quit, and Options buttons using Pygame. It handles user interactions like mouse clicks and hovers, playing sounds and transitioning to different game states (e.g., starting gameplay or exiting). The loop updates the display, checks for events, and adjusts button visuals base...
def menu(): run = True PlayButton = button((255, 255, 255), width / 2 - width / 15, height / 3, width / 10, height / 10, "Play") QuitButton = button((255, 255, 255), width / 2 - width / 15, height / 3 * 2, width / 10, height / 10, "Quit") OptionButton = button((255, 255, 255), width / 2 - width / 15, he...
def Omega_B(self,x): """The baryonic density parameter at redshift ``x``. Parameters ---------- x : Quantity-like ['e-folds'], array-like, or `~numbers.Number` Input e-folds. Returns ------- Omega_B : ndarray or float The Baryonic ...
The function `Omega_Tot` computes the total density parameter (relative to the critical density) at a given number of efolds `x` by summing contributions from six components: baryonic matter (`Omega_B`), cold dark matter (`Omega_CDM`), gamma radiation (`Omega_Gamma`), neutrinos (`Omega_Nu`), dark energy (`Omega_DE`), a...
def Omega_Tot(self,x): """The total density parameter at efolds ``z``. Parameters ---------- x : Quantity-like ['efolds'], array-like, or `~numbers.Number` Input efolds. Returns ------- Otot : ndarray or float The total density rel...
def get_cached_package_descriptor(): print(f"👀\t{COL_WHT}Checking{COL_END} if package descriptor cache exist on S3...") if key_exist(PACKAGES_DESCRIPTOR_S3_KEY): print("✅\tRemote packages descriptor found!") s3.Bucket(APP_BUCKET).download_file(PACKAGES_DESCRIPTOR_S3_KEY, PREVIOUS_PACKAGES_DESCR...
The code prepares application dependencies and distributions by checking if dependencies or code have changed since the last build. It fetches and packages dependencies if changes are detected, then packages the application. It returns whether dependencies or code changed, enabling conditional rebuilds.
def build(): """ Prepare dependencies and application distributions :return: True if dependencies changed """ deps_changed = True # CHECK IF FIRST BUILD OR DEPENDENCIES HAVE BEEN CHANGED found_cache = get_cached_package_descriptor() if found_cache: deps_changed = application_dep...
def build(): """ Prepare dependencies and application distributions :return: True if dependencies changed """ deps_changed = True # CHECK IF FIRST BUILD OR DEPENDENCIES HAVE BEEN CHANGED found_cache = get_cached_package_descriptor() if found_cache: deps_changed = application_dep...
The main task of the code is to execute a Continuous Integration (CI) workflow for a serverless function. It displays status information, checks for changes in code and dependencies, and triggers deployment/publishing actions if changes are detected. The process includes building, pushing updates, deploying Lambda laye...
def ci(): logo = f"""{COL_YEL} __ ___ __ _______ ____ ___ __________ / / / | / |/ / __ )/ __ \/ | / ____/ _/ / / / /| | / /|_/ / __ / / / / /| | / / / / / /___/ ___ |/ / / / /_/ / /_/ / ___ | / /____/ / ...
def drop_tables(tables = registered_tables) -> None: for table_name in tables: _drop_table(table_name) def create_tables(tables = registered_tables) -> None: for table in tables: _create_table(tables[table]) def read_inputs(inputs = registered_inputs) -> dict: data = dict() for tabl...
The main task of the code is to initialize a database by dropping existing tables, creating new ones, reading input data, parsing it according to predefined schemas, and inserting records into tables while skipping primary keys. This function sets up database structure and populates it with structured input data accord...
def bootstrap(self) -> None: # start with clean tables drop_tables(registered_tables) create_tables() # get the input data data = read_inputs(registered_inputs) for table_name in data: # use the registered table fields for the given table ...
def prepareBack(self): self.startSearching() self.view.goBack() def openLibrary(self): self.listAll() self.view.switchTo(1) def edit(self): self.view.enableAddEdit() def confirmEdit(self): self.view.disableAddEdit() software = Software(self.view.addEditTeam.text()...
This code initializes a GUI controller by connecting UI elements (buttons, input fields, lists) to corresponding functions. It links menu buttons to navigation/actions, search fields to search functions, and list interactions to data display. It sets up event handlers for editing, confirming/canceling changes, and disp...
def __init__(self, model, view, parent=None): self.model = model self.view = view for buttons in self.view.menuButtons: buttons[0].clicked.connect(lambda: self.prepareBack()) buttons[1].clicked.connect(lambda: self.view.switchTo(0)) buttons[2].clicked.connect...
def gen_nopeek_mask(length): """ Returns the nopeek mask Parameters: length (int): Number of tokens in each sentence in the target batch Returns: mask (arr): tgt_mask, looks like [[False, True, True], ...
The code trains a model using a training and validation loader, performing forward and backward passes over multiple epochs. It tracks training and validation losses, logs metrics with MLflow, and retains the best model based on validation performance. After training, it quantizes and compresses the best model, evaluat...
def train( train_loader, valid_loader, model, optim, criterion, num_epochs, device, trial, vocab_size, max_seq_length, run_id, ): model.train() lowest_val = 1e9 best_model = model train_losses = [] val_losses = [] total_step = 0 for epoch in range...
def load_best_model(): model_uri = "models:/transformer-translation@champion" version = client.get_model_version_by_alias("transformer-translation", "champion") # run_id = client.get_model_version_by_alias( # "transformer-translation", "champion" # ).run_id model_path = mlflow.artifacts.down...
The main task of this code is to process input text through a language model, splitting it into sentences, predicting outputs for each sentence, and returning the detokenized result along with metadata like version, timestamp, and execution time. It also handles model loading, input validation, error responses, and log...
def predict_endpoint(): st = time.time() global model_data if model_data is None: try: model_data = load_best_model() except Exception as e: return str(e), 500 Thread(target=update_model_if_out_of_date).start() req = request.get_json() if "input" not in...
def score_answers(gold_annotation_dict, pred_dict): """Scores all answers for all documents. Args: gold_annotation_dict: a dict from example id to list of NQLabels. pred_dict: a dict from example id to list of NQLabels. Returns: long_answer_stats: List of scores for long answers. short_answer_st...
This code evaluates model predictions against gold data by loading cached or freshly read annotations and predictions, computing long/short answer statistics (F1, precision, recall), and outputting formatted metrics tables or JSON results based on the 'pretty_print' flag.
def main(_): cache_path = os.path.join(os.path.dirname(FLAGS.gold_path), 'cache') if FLAGS.cache_gold_data and os.path.exists(cache_path): logging.info('Reading from cache: %s', format(cache_path)) nq_gold_dict = pickle.load(open(cache_path, 'r')) else: nq_gold_dict = util.read_annotation( FLA...
def setInitialValues(): global turn, gold, food, naturalResources, population, running global yearsSinceIncreaseInPopulation, numMiners, maxPop global numFarmers, foodHarvestRate, numLumberjacks, resourceHarvestRate, occurrenceChance, occurenceVariable global endingTurn, displayingTree, trade, trade2,...
The main task of the code is to run a game loop that resets the canvas, initializes game values, and repeatedly updates game objects, checks collisions, and renders visuals until the player loses, then ends the game.
def runGame(): s.delete("all") setInitialValues() drawOnce() while play == True: hasLost() drawObjects() updateObjects() collisions() sleep(0.1) s.update() deleteObjects() endGame()
def mouseInsideRectangle(x1, y1, x2, y2): global xMouse, yMouse bigX = max(x1, x2) smallX = min(x1, x2) bigY = max(y1, y2) smallY = min(y1, y2) xRange = range(smallX, bigX) yRange = range(smallY, bigY) xTrue = xMouse in xRange yTrue = yMouse in yRange if xTrue == True and yTrue =...
This function handles mouse click events in a game, managing interactions like selecting difficulty, unlocking technologies, buying houses, upgrading subjects (e.g., Hunter to Farmer/Lumberjack), and progressing turns. It checks mouse positions against predefined regions, updates game state variables (resources, unlock...
def mouseClickHandler( event ): global xMouse, yMouse, turn, easy, medium, hard, running, lumberjackBought, naturalResources global endingTurn, displayTree, displayingSubjectTree, displayingTitle, displayingInstructions, displayingDifficulty global displaySubjects, subjectSelected, subjectSelectedi, selecte...
def DFS_Traversal(cost,start_point, goals): #add your parameters visited=[0]*len(cost[0]) # To keep track of visited nodes. stack=[] exception = stateExceptions(len(visited)-1,start_point,goals) if exception == -1: return [] if exception == 1: return [start_point] visite...
The code performs three traversal algorithms (DFS, UCS, A*) on a graph defined by 'cost' from 'start_point' to 'goals', collects their results in a list, and returns it.
def tri_traversal(cost, heuristic, start_point, goals): l = [] t1 = DFS_Traversal(cost, start_point,goals) #print(t1) t2 = UCS_Traversal(cost,start_point,goals) #print(t2) t3 = A_star_Traversal(cost,heuristic,start_point,goals) #print(t3) l.append(t1) l.append(t2) l.append(t3) ...
def calculate_profit(headers, cookies): statement = "" last_price = get_current_price("^NSEI", 0) perc_change, change = get_change("^NSEI") statement += f"<b>Nifty:{round(last_price)}, change:{change}({perc_change}%)</b>\n\n" current_minute = datetime.now().minute # Get the current minute allo...
The main task of the code is to handle stock/option-related operations based on user-specified actions (calculate_profit, initial_payout, track_stocks). It checks if today is a holiday to skip execution, uses HTTP headers/cookies for web requests, and routes tasks to corresponding functions like calculating profit, ini...
def main(): parser = argparse.ArgumentParser(description="Script to calculate profit and alert for stocks and options.") parser.add_argument("action", choices=["calculate_profit", "initial_payout", "track_stocks"], help="Action to perform") args = parser.parse_args() headers = { 'User-Agent': '...
def remove_improbable_entities(results, cutoff=3): """Remove improbable entities. E.g. if less than 3 characters (dm, eq, tx)""" # Should remove links from Amazon, which give amazon undue credit. new_results = [] for r in results: if len(r[0]) >= cutoff: new_results.append(r) re...
The function processes sentiment analysis results by filtering improbable entities, aggregating scores, and cross-referencing with known brands if specified, returning a ranked list of entities based on sentiment and agreement scores.
def postprocess_sentimentful_results(results, xref, known_brands): """Takes in list of (product, sentiment, agreement), processes this into a ranking by score aggregation and fuzzy-matching.""" results = remove_improbable_entities(results, cutoff=3) top_entities = get_top_entities(results) scor...
def load_interpreted_S3_data(sr, lookback_days): key = "interpreted_data/{}_{}.json".format(sr, lookback_days) s3 = boto3.resource("s3") content_object = s3.Object("crowdsourced-data-reddit", key) return json.loads(content_object.get()["Body"].read().decode("utf-8")) def load_interpreted_local_data(sr, ...
The function postprocess loads and processes keyword-related data (from S3 or local storage), filters entities, ranks them using sentiment and brand knowledge, converts results into a structured DataFrame, sorts by sentiment, rounds values, and saves the output. It returns a DataFrame with sentiment, popularity, and va...
def postprocess(keyword, xref=True, lookback_days=360, use_s3=False): """Postprocessing includes: fuzzy string matching, removing 1 and 2 letter entities, and uses a list of brands to make the final ranking.""" keyword = keyword.capitalize() if use_s3: results = load_interpreted_S3_data(keyw...
def getChordName(): if (major == True): if (augmented == True): return "aug" elif (suspended == True): if (sus2 == True): return "sus2" else: return "sus4" else: return "maj" else: return "m" def ...
The code displays major chords starting from a given base note, updating a fretboard representation for each chord in the triad. It calculates note positions using the chromatic scale, prints each note with its chord name, and introduces delays between displays. The global 'major' flag is temporarily toggled during the...
def displayMajorChords(baseNote): global major fromBaseNotePosition = 0 value = 0 print(baseNote + getChordName()) baseIndex = findIndexInChromatic(baseNote) fretBoard = updateFretBoardFromChord(getEmptyBoard(), getTriadForChord(baseNote)) time.sleep(1) #print(color[0]) for i in ra...
def findIndexInChromatic(note): for i in range(len(chromatic)): if note == chromatic[i]: return i return -1 def getChordName(): if (major == True): if (augmented == True): return "aug" elif (suspended == True): if (sus2 == True): r...
The main task of the code is to display all chords (major and minor) starting from a given base note. It calculates chord positions using a chromatic scale, adjusts for octave wrapping, prints chord names, and updates a fretboard representation for each triad. The function iterates through scale degrees, determines cho...
def displayAllChords(baseNote): global major majorOrMinorValue = 0 baseNotePos = findIndexInChromatic(baseNote) for i in range(len(majorScale)): if (majorScale[i] == 1): chordPos = i if (majorOrMinor[majorOrMinorValue] == 'major'): major = True ...
def updateFretBoardFromChord(fretBoard, chordValues): # import chord values setCapoTuning() #print(tuning) print(chordValues) notesOnFretboard = [0,0,0,0] #run a for loop to check each string for currentString in range (len(tuning)): # string...tuning[G, C, E, A] minDif...
The code's main task is to display a single chord's triad on a fretboard by updating an empty fretboard with the chord's triad notes, given a root note.
def displaySingleChord(rootNote): updateFretBoardFromChord(getEmptyBoard(), getTriadForChord(rootNote))
def getChordName(adj): if (adj[0] == True): if (adj[1] == True): return "aug" elif (adj[2] == True): return "sus" else: return "maj" else: return "m" def findIndexInList(note, lis): for i in range(len(lis)): if note == lis[i]: ...
The function `displayMajorChords` calculates and displays major triad chords starting from a given base note. It uses a chromatic scale list to determine note positions, updates a fretboard representation, and prints each chord note along with its adjusted name. The loop iterates through intervals (5, 7, 9) to find the...
def displayMajorChords(baseNote): fromBaseNotePosition = [5, 7, 9] value = 0 print(baseNote + getChordName(chordAdj)) baseIndex = findIndexInList(baseNote, chromatic) fretBoard = updateFretBoardFromChord(getEmptyBoard(), getTriadForChord(baseNote), capo) for i in range(0,3): time.s...
def findIndexInList(note, lis): for i in range(len(lis)): if note == lis[i]: return i return -1 def getChordName(adj): if (adj[0] == True): if (adj[1] == True): return "aug" elif (adj[2] == True): return "sus" else: return "maj...
The main task of the code is to generate and display all possible chords starting from a given base note, considering major and minor variations. It calculates chord positions, adjusts for scale wrapping, prints chord names, and updates a fretboard representation with corresponding triads. The loop iterates through sca...
def displayAllChords(baseNote): majorOrMinorValue = 0 baseNotePos = findIndexInList(baseNote, chromatic) for i in range(len(majorScale)): if (majorScale[i] == 1): chordPos = i if (majorOrMinor[majorOrMinorValue] == 'major'): chordAdj[0] = Tru...
def updateFretBoardFromChord(fretBoard, chordValues, capo): tuning = setCapoTuning(capo) print(chordValues) notesOnFretboard = [0,0,0,0] #run a for loop to check each string for i in range (len(tuning)): # string...tuning[G, C, E, A] ## [E, A, D, G, B, E] currentString = t...
The function `displaySingleChord` generates a guitar chord diagram for a specified root note. It initializes an empty fretboard, retrieves the triad structure for the chord, and updates the fretboard to display the chord shape, considering the capo position. The task involves creating a visual representation of a triad...
def displaySingleChord(rootNote): updateFretBoardFromChord(getEmptyBoard(), getTriadForChord(rootNote), capo)
def gtid(): """ :return: The GT ID of the student :rtype: int """ return 903641501 def experiment1()...
The main task of the code is to execute two experiments (`experiment1` and `experiment2`) after setting a random seed using `gtid()` for reproducibility. The function `test_code` serves as a testing framework to validate implementations of these experiments, ensuring consistent results across runs by initializing the r...
def test_code(): """ Method to test your code """ np.random.seed(gtid()) # do this only once # add your code here to implement the experime...
def _validate_frequencies(frequencies: FrequenciesLike) -> QuasiDistribution: """Validate frequencies.""" if isinstance(frequencies, QuasiDistribution): return frequencies # Note: issubclass(QuasiDistribution, dict) is True if isinstance(frequencies, dict): frequencies =...
The function `reckon_operator` calculates the expectation value and standard error of a quantum operator from measurement frequencies. It assumes the operator is diagonalized via prior basis rotations, enabling measurement in the computational basis. The input frequencies are validated, and the operator is processed to...
def reckon_operator( self, frequencies: FrequenciesLike, operator: OperatorType ) -> ReckoningResult: """Reckon expectation value from frequencies and operator. Note: This function assumes that the input operators are measurable entirely within one circuit execution (i.e. resulting ...
def _validate_frequencies_list( cls, frequencies_list: Sequence[FrequenciesLike] | FrequenciesLike ) -> tuple[QuasiDistribution, ...]: """Validate frequencies.""" if isinstance(frequencies_list, (Counts, QuasiDistribution, dict)): frequencies_list = (frequencies_list,) if...
The function computes the expectation value and standard error for the sum of input operators using provided frequencies from a circuit execution. It validates inputs, ensures compatibility, and returns results as a ReckoningResult object with Python-native numeric types.
def reckon( self, frequencies_list: Sequence[FrequenciesLike] | FrequenciesLike, operator_list: Sequence[OperatorType] | OperatorType, ) -> ReckoningResult: """Compute expectation value for the sum of the input operators. Note: the input operators need to be measurable entir...
def reset(self): """resets the game""" # reset the grid to empty self.grid.grid_reset() # reset the block or tetramino list self.tetraminoes = [LBlock(), JBlock(), TBlock(), IBlock(), SquareBlock(), HBlock(), HInvertBlock(), HIlongBlock(), HlongBlock(), ZBlock(), SBlock(), UBlock...
The code handles user keypress events in a game, controlling block movement (left, right, down, rotation) and game actions (reset, pause). It checks for QUIT events to exit, triggers block movement via a timer, and manages game state transitions like resetting upon game over.
def keypress(self, update): """listens for keypresses by the user/player Args: update (timer): timer for automatic dropdown of blocks """ for event in pygame.event.get(): # if player hits the x(close) button if event.type == pygame.QUIT: ...
def bgr_to_hsv(img): return cv2.cvtColor(img, cv2.COLOR_BGR2HSV) def yellow_white_filter(img): # define range of white color in HSV lower_white = np.array([0,0,0], dtype=np.uint8) upper_white = np.array([200,200,200], dtype=np.uint8) # Threshold the HSV image to get only white colors mask = cv2...
The code detects lane lines in an image by converting it to HSV, filtering for yellow/white, applying Gaussian blur, Canny edge detection, masking the region of interest, using Hough Transform to identify lines, and overlaying detected lines on the original image.
def lane_finder(image): # bgr to hsv hsv = bgr_to_hsv(image) # filitered filtered = yellow_white_filter(hsv) # gaussian blur kernel_size = 7 blur_gray = gaussian_blur(filtered, kernel_size) # canny low_threshold = 1 high_threshold = 5 edges = canny(blur_gray, low_threshol...
def bgr_to_hsv(img): return cv2.cvtColor(img, cv2.COLOR_BGR2HSV) def yellow_white_filter(img): # define range of white color in HSV lower_white = np.array([0,0,0], dtype=np.uint8) upper_white = np.array([200,200,200], dtype=np.uint8) # Threshold the HSV image to get only white colors mask = cv2...
The code processes an image to detect lane lines by converting it to HSV, filtering yellow/white regions, applying Gaussian blur, Canny edge detection, defining a region of interest (ROI), and using Hough transform to identify lines. It returns the edges image with detected lane lines overlaid.
def test_lane(img): hsv = bgr_to_hsv(img) filtered = yellow_white_filter(hsv) # gaussian blur kernel_size = 3 blur_gray = gaussian_blur(filtered, kernel_size) # canny low_threshold = 1 high_threshold = 5 edges = canny(blur_gray, low_threshold, high_threshold) # region of inte...
def _check_request_parameters(self): if self.request_data["starttime"] is None: raise LinkError("Parameter starttime is required") if self.request_data["endtime"] is None: raise LinkError("Parameter endtime is required") def _build_cli_with_arguments(self): return self._b...
The code executes a SeedLink request by validating parameters, constructing a CLI command with arguments, and running it via subprocess. It checks Python version to use `subprocess.call` (pre-3.5) or `subprocess.run` (3.5+), returns the process result.
def execute(self, **kwargs): """Execute SeedLink request.""" self._check_request_parameters() cli_with_args = self._build_cli_with_arguments() self._check_required() safe_cli_with_args = utils.stringify_parameters(cli_with_args) if sys.version_info < (3, 5): ...
def load_pdf(file_path): loader = PyPDFLoader(file_path) pages = loader.load() embed_new_docs(pages) return pages def load_microsoft_word(path): loader = Docx2txtLoader(path) pages = loader.load_and_split() embed_new_docs(pages) return pages def load_images(path): loader = Unstructur...
This function loads documents from various file formats (PDF, Word, images, CSV, Excel, etc.) by identifying the file extension and using the corresponding loader. It handles directories with a trailing slash, processes each item, and returns the loader or embedded data. If the file type is unsupported, it raises an ex...
def load_document(file_path): # Determine the file extension file_extension = file_path.split('.')[-1].lower() # Call the appropriate loader based on the file extension if file_extension == 'pdf': loader = load_pdf(file_path) elif file_extension == 'docx': loader = load_microsoft_wor...
def sample_user(email='objww@example.com', password='testpassword'): # Crreate sample user""" return get_user_model().objects.create_user(email, password) def sample_premises( owner, name='Szot', image_url='https://via.placeholder.com/350x150', city='Gdynia' ): return models....
The main task of the code is to test the creation of an OrderProduct instance by associating a sample order, product, and quantity, then verifying the linkage between the created OrderProduct and the original order through an assertion.
def test_orderproduct_create(self): owner = sample_user(email='rtyqw@example.com') order = models.Order.objects.create( status="REQUESTED", premises=sample_premises(owner=owner) ) product = sample_product() quantity = 2 orderproduct = models.OrderP...
def query_model(queries, matrix_path, model_path, verbose=False): """ Finds the top 5 similar movies to the query topics Parameters: queries: the query topics matrix_path: the path to the doc2vec matrix model_path: the path to the doc2vec model Returns: title_score: a list of the 5 similar titles and their ...
The code implements a movie search engine that interacts with users to retrieve movie information. It uses an SLM model and doc2vec (matrix_path, model_path) to process user queries, generate ratings, and display results. The loop collects topics, queries the model, and shows movie titles, scores, and keyword sentences...
def search_engine(SLM_model, matrix_path, model_path): """ Interacts with the user Parameter: SLM_model: the SLM model to generate reviews for movies matrix_path: the path to the doc2vec matrix model_path: the path to the doc2vec model """ query_topics = [] print("\n\n\n") print("Enter a movie you want to ...
def get_timesheet_by_month(self, user: User, month: str) -> dict: # print([c.json() for c in timesheets.get_results()]) return self.generator(user, 'month', month) def get_timesheet_by_date(self, user: User, date: str) -> list: return self.generator(user, 'date', date) def get_time_interval_time...
This function retrieves a user's timesheet data based on specified filters (month, date, or date range). It first checks if the user exists, then fetches relevant entries using helper methods like get_timesheet_by_month, get_timesheet_by_date, or get_time_interval_timesheet. The response includes user info, filtered en...
def retrieve_user_timesheet( self, user_id: int, month: str=None, date: str=None, start_date: str=None, end_date: str=None ) -> dict: user: User = User.all().where('user_id', user_id).first() if user is None: retur...
def lima_threshold(y_hat, y_pred, p_minus=None, n_trials=100, random_state=None, return_score=False, verbose=False): """Determine a clean-optimal decision threshold from noisy labels, using our proposal. :param y_hat: an array of noisy labels, shape (n,) :param y_pred: an array of soft predictions, shape (...
This function applies a selected thresholding method to input predictions (y_hat) and true labels (y_pred), returning thresholded results. It routes to specific thresholding implementations based on self.method, such as 'lima', 'default', 'menon', etc., using method-specific parameters. If an unsupported method is prov...
def __call__(self, y_hat, y_pred): if self.method == "lima": return lima_threshold(y_hat, y_pred, **self.method_args) elif self.method == "default": return default_threshold(y_hat, y_pred, **self.method_args) elif self.method == "menon": return menon_threshold...
def stepTitle(): calling_frame = inspect.currentframe().f_back calling_function = calling_frame.f_code.co_name total_width = 80 title_width = len(calling_function) padding = (total_width - title_width) // 2 separator = "*" * total_width empty_line = "*" + " " * (total_width - 2) title_...
The main task of the code is to start a sequence of producers by calling `startProducers` with a range of producer indices, followed by a delay using `sleep` to synchronize or pause execution. This function likely manages producer initialization in a distributed or parallel system, ensuring controlled timing between pr...
def stepStartProducers(): stepTitle() startProducers(firstProducer, firstProducer + numProducers) sleep(args.producer_sync_delay)
def stepTitle(): calling_frame = inspect.currentframe().f_back calling_function = calling_frame.f_code.co_name total_width = 80 title_width = len(calling_function) padding = (total_width - title_width) // 2 separator = "*" * total_width empty_line = "*" + " " * (total_width - 2) title_...
The code `stepTransfer()` performs a step-wise transfer process by first displaying a step title via `stepTitle()`, then initiating a random transfer operation between senders using `randomTransfer()` with parameters defining the sender range and transfer count. After a 1-second delay via `sleep(1)`, it progresses to t...
def stepTransfer(): stepTitle() randomTransfer(0, args.num_senders, 5) sleep(1)
def stepTitle(): calling_frame = inspect.currentframe().f_back calling_function = calling_frame.f_code.co_name total_width = 80 title_width = len(calling_function) padding = (total_width - title_width) // 2 separator = "*" * total_width empty_line = "*" + " " * (total_width - 2) title_...
The code registers a sequence of producers starting from 'firstProducer' up to 'firstProducer + numProducers', pauses for 1 second, then lists all registered producers. Its main task is to demonstrate or execute a step involving producer registration and enumeration in a system, likely for simulation or distributed pro...
def stepRegProducers(): stepTitle() regProducers(firstProducer, firstProducer + numProducers) sleep(1) listProducers()
def vote(b, e): for i in range(b, e): voter = accounts[i]['name'] k = args.num_producers_vote if k > numProducers: k = numProducers prods = [(3*i + 2*j) % numProducers + firstProducer for j in range(k)] prods = ' '.join(map(lambda x: accounts[x]['name'], prods)) ...
The code delegates votes from a range of voters (b to e) to a designated proxy on a blockchain, using the 'cleos' tool. It first registers the proxy, then iterates through each voter, instructing them to vote for the proxy, effectively centralizing voting power through the proxy account.
def proxyVotes(b, e): vote(firstProducer, firstProducer + 1) proxy = accounts[firstProducer]['name'] retry(getCleos(True) + 'system regproxy ' + proxy) sleep(1.0) for i in range(b, e): voter = accounts[i]['name'] retry(getCleos(True) + 'system voteproducer proxy ' + voter + ' ' + pro...
def stepTitle(): calling_frame = inspect.currentframe().f_back calling_function = calling_frame.f_code.co_name total_width = 80 title_width = len(calling_function) padding = (total_width - title_width) // 2 separator = "*" * total_width empty_line = "*" + " " * (total_width - 2) title_...
The code simulates a voting process step by first displaying a title, then initiating a vote for a range of voters (0 to args.num_voters). It pauses for 1 second, lists active producers (nodes), and waits 5 seconds, likely to mimic a blockchain consensus or coordination step. The main task is to execute a voting phase,...
def stepVote(): stepTitle() vote(0, 0 + args.num_voters) sleep(1) listProducers() sleep(5)
def run(args): print('boot.py run:', args) logFile.write(args + '\n') if subprocess.call(args, shell=True): print('boot.py: exiting because of error') sys.exit(1) def getCleos(is_random = False): port = args.http_port # if is_random: # port = random.randint(args.http_port + 1...
The code executes blockchain operations to buy RAM bytes for the 'eosio' account, then proposes, approves, and executes a multi-signature system replacement action named 'fast.unstake' using the first account in the 'accounts' list. This process involves interacting with the EOSIO blockchain via CLI commands to manage ...
def msigReplaceSystem(): run(getCleos() + 'push action eosio buyrambytes' + jsonArg(['eosio', accounts[0]['name'], 200000]) + '-p eosio') sleep(1) msigProposeReplaceSystem(accounts[0]['name'], 'fast.unstake') sleep(1) msigApproveReplaceSystem(accounts[0]['name'], 'fast.unstake') msigExecReplaceS...
def length(s): """Select the length of a arm.""" assert is_arm(s), "must call length on a arm" return s[1] def end(s): """Select the mobile or planet hanging at the end of a arm.""" assert is_arm(s), "must call end on a arm" return s[2] def is_planet(w): """Whether w is a planet.""" retu...
The code calculates torque by checking the type of the end object of an arm. If the end object is a planet, torque equals the planet's size multiplied by the arm's length. If the end object is mobile, torque equals its total weight multiplied by the arm's length.
def torque(arm): arm_length = length(arm) end_object = end(arm) if is_planet(end_object): return size(end_object) * arm_length elif is_mobile(end_object): return total_weight(end_object) * arm_length
def is_mobile(m): """Return whether m is a mobile.""" return type(m) == list and len(m) == 3 and m[0] == 'mobile' def total_weight(m): """Return the total weight of m, a planet or mobile. >>> t, u, v = examples() >>> total_weight(t) 3 >>> total_weight(u) 6 >>> total_weight(v) 9 ...
The function constructs a tree representing the total weight of a mobile structure, recursively processing its left and right ends if they are themselves mobiles, otherwise returning a tree with the total weight of a non-mobile node.
def f(m): if is_mobile(m): return tree(total_weight(m),[f(end(left(m))),f(end(right(m)))]) else: return tree(total_weight(m))
def _get_puuid_by_name(summoner_name: str, region: Region = Region.NorthAmerica) -> Union[str, None]: name = get_summoner_info_by_name(summoner_name, region) if name is not None: return name.puuid return None def _get_matches_by_puuid(puuid: str, start_game_index: int = 0, num_games: int = 100, ...
The function retrieves the latest 'n' ranked 5v5 games for a given summoner in a specified region by fetching match data in batches, using their puuid, and yields each processed match as a MatchDto object.
def get_latest_n_games_for_summoner(summoner_name: str, num_games: int, queue_type: QueueType = QueueType.Ranked5v5, region: Region = Region.NorthAmerica) -> Iterator[MatchDto]: current_game_idx = 0 num_games_at_a_time = 100 puuid = _get_puuid_by_name(summoner_name, region) if puuid is None: ret...
def tensorsFromPair(self,comment,parent_comment,pair): input_tensor = self.tensorFromSentence(comment, pair[0]) target_tensor = self.tensorFromSentence(parent_comment, pair[1]) return (input_tensor, target_tensor) def train_step(self,input_tensor, target_tensor, encoder_optimizer, decoder_optim...
The code trains an encoder-decoder model using pairs of comments and parent comments. It initializes optimizers, prepares training data, and iteratively computes loss via a training step. The loss is accumulated and printed periodically, using NLLLoss to optimize model parameters over specified iterations.
def train(self,comment, parent_comment, pairs,n_iters, print_every=1000, learning_rate=0.01): start = time.time() print_loss_total = 0 # Reset every print_every print("---------Training has begun---------") encoder_optimizer = optim.SGD(self.encoder.parameters(), lr=learning_rate) ...
def _getLogPath(directory, ending): """ Create a log file path with the given ending. :param directory: The directory to create the log file path in. :param ending: The file extension. :return: A path to a log file. """ return os.path.join(directory, strftime("%Y...
This code continuously reads GPS data from a serial connection, logs it to a binary file if specified, splits the data into lines, and parses each line for location information. It runs until the serial connection is closed or a provided `runCondition` function returns False, handling exceptions like serial read failur...
def parse(self, runCondition=None): """ Parse GPS messages from the serial connection until it is closed. :param runCondition: A function that can return False to stop the parser loop. """ buffer = b'' with nullcontext() if self._rawLogDir is None else \ ...
def validate_timestamp_type(date): """ Ensure date is either a timestamp or a format that can be converted into a timestamp """ try: timestamp = float(date) except TypeError: try: timestamp = arrow.get(date).timestamp except arrow.parser.ParserError: raise T...
The function downloads messages from all Slack channels within a specified time range by validating timestamps, generating mention regex patterns, and iterating through each channel to fetch its messages using the provided Slack and database session.
def download_messages_from_all_channels(slack, session, start_timestamp, end_timestamp): """ Validates dates and downloads all channel messages """ start_timestamp = validate_timestamp_type(start_timestamp) end_timestamp = validate_timestamp_type(end_timestamp) mention_regex_map = create_mention_rege...
def create_subexperiment_folder(dir_name): '''Create a sub experiment folder with a format name cc1_2017-05-15_11-34. Args: dir_name (string): the name of directory Return: (string): the absolute path to the created directory ''' ex_path_dir = create_folder(dir_name) datetime_str = datetime.date...
The function `save_stats` saves statistics from data and instruction translation lookaside buffers (DTLB/ITLB) into a text file and generates graphs. It creates a subexperiment directory, converts stats objects to strings, writes them along with a config file into a `.txt` file, and calls `tag_graphs` to produce visual...
def save_stats(dtlb_stats, itlb_stats, dtag, itag): '''Save the statistics into a text file and a graph Args: dtlb_stats (a list of Stats Objects) ''' print("save_stats fn") subex_path = create_subexperiment_folder(EXPERIMENT_DIR) input_filename = get_filename(INPUT_FILE) print("str_stats dtlb") ...
def overlap(basis): M = len(basis) S = np.empty((M,M),dtype=float) for i in range(M): for j in range(M): S[i,j] = basis_overlap(basis[i].alpha,basis[i].d,basis[i].R,basis[j].alpha,basis[j].d,basis[j].R) Sinv = np.linalg.inv(S) return S, Sinv def kinetic(basis): M = len(basis)...
The function performs a Hartree-Fock (HF) calculation using a given basis set and atomic coordinates. It computes the overlap matrix, kinetic energy, core potential, and two-electron integrals. It orthogonalizes the basis, constructs the Fock matrix iteratively, and calculates the total HF energy, updated molecular orb...
def perform_hf(basis,atoms): # compute overlap matrix S, Sinv = overlap(basis) # compute Hcore and twoE that are not dependent on coefficients T = kinetic(basis) V = core_potential(basis,atoms) Hcore = V + T twoE = compute_twoE(basis) # compute basis set orthogonalization transformation ...
def overlap(basis): M = len(basis) S = np.empty((M,M),dtype=float) for i in range(M): for j in range(M): S[i,j] = basis_overlap(basis[i].alpha,basis[i].d,basis[i].R,basis[j].alpha,basis[j].d,basis[j].R) Sinv = np.linalg.inv(S) return S, Sinv def kinetic(basis): M = len(basis)...
This code performs a Hartree-Fock Self-Consistent Field (SCF) calculation using a given basis set and atomic coordinates. It computes molecular orbitals, total energy, and electron repulsion integrals through iterative diagonalization of the Fock matrix, orthogonalizing basis functions and refining the solution until e...
def perform_hf_scf(basis,atoms,maxIter=20,thresh=1E-4): # compute overlap matrix S, Sinv = overlap(basis) # compute Hcore and twoE that are not dependent on coefficients T = kinetic(basis) V = core_potential(basis,atoms) Hcore = V + T twoE = compute_twoE(basis) # compute basis set orthog...
def __get_moments( next_run_getter: Callable, now: datetime, pivot: datetime, moments: Tuple[int, ...], **kwargs, ): if type(moments) is tuple: moments = range(*moments) candiates = [] for momment in moments: if type(momment) in (tuple, list, set): candiate =...
The function `get_next_second` determines the next datetime instance where the second matches a specified value. If `second` is a collection (tuple/list/set), it returns multiple moments. Otherwise, it constructs a pivot time with the given second, finds the closest valid time using `__get_closest_time`, and verifies t...
def get_next_second( now: datetime, pivot: datetime = None, second: TimeConf = None, **kwargs ) -> Tuple[datetime, ...]: if second is not None: if type(second) in (tuple, list, set): return __get_moments(get_next_second, now, pivot, second, **kwargs) else: pivot = pivot o...
def __get_moments( next_run_getter: Callable, now: datetime, pivot: datetime, moments: Tuple[int, ...], **kwargs, ): if type(moments) is tuple: moments = range(*moments) candiates = [] for momment in moments: if type(momment) in (tuple, list, set): candiate =...
This function determines the next datetime instance based on a specified minute value. If a minute is provided, it constructs a target time and finds the closest future occurrence using helper functions. If the minute is a collection, it processes multiple values. Otherwise, it defaults to finding the next second if no...
def get_next_minute( now: datetime, pivot: datetime = None, minute: Optional[TimeConf] = None, **kwargs ) -> datetime: if minute is not None: if type(minute) in (tuple, list, set): return __get_moments(get_next_minute, now, pivot, minute, **kwargs) else: pivot = pivot or ...
def __get_moments( next_run_getter: Callable, now: datetime, pivot: datetime, moments: Tuple[int, ...], **kwargs, ): if type(moments) is tuple: moments = range(*moments) candiates = [] for momment in moments: if type(momment) in (tuple, list, set): candiate =...
This function determines the next occurrence of a specified hour (or set of hours) relative to the current time or a given pivot datetime. If the provided hour is a collection, it returns multiple potential times. Otherwise, it calculates the next datetime matching the specified hour, adjusting to the next day if neces...
def get_next_hour( now: datetime, pivot: datetime = None, hour: TimeConf = None, **kwargs ) -> datetime: if hour is not None: if type(hour) in (tuple, list, set): return __get_moments(get_next_hour, now, pivot, hour, **kwargs) else: pivot = pivot or now pivot...
def __get_moments( next_run_getter: Callable, now: datetime, pivot: datetime, moments: Tuple[int, ...], **kwargs, ): if type(moments) is tuple: moments = range(*moments) candiates = [] for momment in moments: if type(momment) in (tuple, list, set): candiate =...
This function determines the next occurrence of a specified day or time, adjusting based on a pivot date. It handles multiple day formats (tuple/list/set) and returns the closest valid datetime, or None if no match. If no day is provided, it defaults to finding the next hourly interval.
def get_next_day( now: datetime, pivot: datetime = None, day: TimeConf = 0, **kwargs ) -> datetime: if day: if type(day) in (tuple, list, set): return __get_moments(get_next_day, now, pivot, day, **kwargs) else: pivot = pivot or now pivot = datetime(year=pivot...
def read_int(self, size): return int(self.read_bitstring(size), 2) def read_bitstring(self, size): val = self.peek(size) self.current_bit += size return val
This function parses binary packets by reading version and type ID. For literal packets, it aggregates 4-bit groups until a '0' prefix is encountered, then constructs a LiteralPacket with the binary value. For operator packets, it uses a length type ID to determine subpacket parsing: either by fixed length or number of...
def read_packet(self): packet_version = self.read_int(3) packet_type_id = self.read_int(3) if packet_type_id == PacketType.LITERAL: literal_bits = [] while True: prefix_bit = self.read_bitstring(1) group_bits = self.read_bitstring(4) ...
def main(window, user_text, clock, new_level, new_volume): lastScore = Score.last_score() locked_position = {} grid = Grid.create_grid(locked_position) change_piece = False run = True current_piece = Shape.get_shape() next_piece = Shape.get_shape() fall_time = 0 level_time = 0 ...
The code implements a main menu interface using Pygame, featuring a username input field, three interactive buttons (Play, Settings, Question), and dynamic hover effects. It captures user input for a name, triggers game initiation or settings when buttons are clicked, and scales button images based on mouse position. T...
def main_menu(window): # Create a "screen capture" object to capture video from the screen clock = pygame.time.Clock() color_active = pygame.Color(red) color_passive = pygame.Color(black) color_text_box = color_passive active = False user_text = '' font = pygame.font.SysFont('arial', 60...
def _log_transform_train_test_metrics(self) -> None: """ Log transform skewed metrics """ assert self.train_df is not None, "no training set available, create it first" assert self.test_df is not None, "no test set available, create it first" pd.options.mode.chained_assig...
This method splits a metrics DataFrame into training and test sets based on the 'select_test' parameter (random, single_recording, sorter, or recording). It applies log transformation, standard scaling, and data clearing, with optional verbose output. The split strategy determines how data is partitioned, ensuring prop...
def create_train_test_split( self, select_test="random", test_size=0.2, random_state=42, key=None, standard_scale=True, log_transform=True, verbose=True, ): assert self.metrics_df is not None, "compute metrics first" if select_test == "...
def speak(text): bot_chat = Label(chat_frame,text=text, bg=BOT_CHAT_BG, fg=TEXT_COLOR,justify=LEFT, wraplength=250,font=('Montserrat',12,'bold')) bot_chat.pack(anchor='w',ipadx=2,ipady=2,pady=10,padx=10) engine.say(text) engine.runAndWait() def takeCommand(first): global status_label,chat_frame ...
The main task of the code is to handle sending WhatsApp messages by checking if a contact exists in a JSON file. If the contact exists, it sends a message; if not, it prompts the user to add a new contact via a popup and then sends the message using the newly added contact name.
def handleWhatsapp(): global newContactName contactsFile = open('./userData/contacts.json','r') contacts = json.load(contactsFile) contactsFile.close() speak("Sure. Who do you want to send the message to?") person = takeCommand(False) print(contacts) if person in contacts: s...
def speak(text): bot_chat = Label(chat_frame,text=text, bg=BOT_CHAT_BG, fg=TEXT_COLOR,justify=LEFT, wraplength=250,font=('Montserrat',12,'bold')) bot_chat.pack(anchor='w',ipadx=2,ipady=2,pady=10,padx=10) engine.say(text) engine.runAndWait() def takeCommand(first): global status_label,chat_frame ...
The code handles sending emails by checking if a contact exists in a JSON file. If the contact exists, it sends the email directly; if not, it prompts the user to add the new contact via a popup and then sends the email using the newly added contact details.
def handleEmail(): global newContactName contactsFile = open('./userData/contacts.json','r') contacts = json.load(contactsFile) contactsFile.close() speak("Sure. Who do you want to send the mail to?") person = takeCommand(False) if person in contacts: sendEmail(person) el...
def train_step(self, batch_size): # Sample batch state, c_next_state, goal = self.replay_buffer.subgoal_sample(batch_size, self.subgoal_period, self.relabel_ratio) reward = get_reward(c_next_state, goal, self.env_name, self.env) state = map_goal_space(self.env_name, state) c_next...
The code trains a model for a specified number of steps (`high_total_step`), performing training iterations with a given batch size (`high_batch_size`). It logs training metrics (loss, info) at intervals (`high_log_period`) using a logger and saves model checkpoints periodically (`high_save_period`) to the specified di...
def train(self, save_dir, logger, high_batch_size, high_total_step, high_log_period, high_save_period, **kwargs): for step in range(1, high_total_step + 1): # Train loss_info, train_info = self.train_step(high_batch_size) # Log if step % high_log_period == 0: ...
def train_step(self, batch_size): # Sample batch state, action, next_state, subgoal, goal = self.replay_buffer.sample(batch_size, self.relabel_ratio, self.relabel_period) reward = get_reward(next_state, subgoal, self.env_name, self.env) critic_loss, loss_info = self.critic_loss(state, a...
The code trains a model for a specified number of steps using a low batch size, logging loss information periodically and saving the model at regular intervals. It iterates through training steps, computes loss with `train_step`, records metrics via `log` at `low_log_period` intervals, and stores checkpoints in `save_d...
def train(self, save_dir, logger, low_batch_size, low_total_step, low_log_period, low_save_period, **kwargs): for step in range(1, low_total_step + 1): # Train loss_info = self.train_step(low_batch_size) # Log if step % low_log_period == 0: self.l...
def pre_selection(df): dfout = df.loc[(df["region"] == 1) | (df["region"] == 2)] dfout = dfout.loc[dfout["regime"] == 1] dfout = dfout.loc[(dfout["nTags"] == 2)] dfout.drop(columns=["nTags", "MCChannelNumber", "region", "regime", "dEtaBB", "dPhiBB"], inplace=True) return dfout def post_process1(df):...
The function `make_dataset` processes signal and background data from CSV files, applies preprocessing, and splits them into training, validation, test, and blind datasets. It normalizes features, scales data, and prepares PyTorch tensors for machine learning. Signal masses are excluded if they match the blind mass (de...
def make_dataset(data_dict_filepath, signal_masses, blind_mass=1200, scale_norm=1, validation=True, test=True, signal_normalisation=False): # load samples signal_mass = signal_masses # [300, 420, 440, 460, 500, 600, 700, 800, 900, 1000, 1200, 1400, 1600, 2000] signal = pd.DataFrame() ...
def load_data(data_dir, session, feat_dim, normalize=True): tfrecords = [] tf_path = os.path.join(data_dir, session) if os.path.exists(os.path.join(data_dir, session, 'train')): tf_path = os.path.join(tf_path, 'train') tfrecords.extend(glob(os.path.join(tf_path, '*.tfrecord'))) print(f'Loadi...
The `recalibrate` function fine-tunes a model by iteratively processing sessions, loading historical data and pseudo-labels, normalizing current session data, and training with a rolling optimizer. It generates pseudo-labels via decoding, applies label adjustments, and performs model recalibration if enabled. The proce...
def recalibrate(self): sess_idx = self.state['current_session'] while sess_idx < len(self.sessions): print(f'Running sessions {self.sessions[sess_idx]}') # Load previous sessions' data and pseudo labels prev_data_buffer = {} pseudo_label_count = 0 ...
def socketCreate(): try: global host global port global s s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) host = '' port = 4444 except socket.error as msg: print('socket creation error: ' + str(msg[0])) def socketBind(): try: print('Bind...
The main task of the code is to initialize a server socket by creating a socket, binding it to a specific address and port, and preparing to accept incoming client connections. This sets up the foundational network communication infrastructure for a server application.
def main(): socketCreate() socketBind() socketAccept()
def adjacent_enemies(self, unit:Unit): adjacent_cells = self.adjacent(*unit.pos) return { u for u in self.units if u.alive and u.team != unit.team and u.pos in adjacent_cells } def choose_move(self, unit:Unit): blocked = self.walls | {x.pos for x in self.units if ...
The main task of the code is to process a game round by iterating through each unit, moving it if no adjacent enemies are present, attacking if enemies are nearby, and concluding the round. It ensures units only act when alive, checks for valid moves, and executes attacks or movements accordingly.
def play_round(self): for unit in self.units: if not unit.alive: continue adj_enemies = self.adjacent_enemies(unit) if not adj_enemies: move = self.choose_move(unit) if not move: continue uni...
def data_extraction_deterioration(time_window,root_dir): all_df = embedding(root_dir) all_mort = filter_deterioration_data(all_df) all_mort = all_mort[all_mort['itemoffset']<=time_window] return all_mort def normalize_data_deterioration(data, train_idx, valid_idx, test_idx): train = data[data['patie...
This code constructs training, validation, and test datasets for deterioration prediction in medical data. It extracts and normalizes time-series data, splits patient indices into training/validation/test sets, and generates batched data generators for model training and evaluation. The process includes data preprocess...
def data_construction(data_path): batch_size = 256 time_length = 48.0 data = data_extraction_deterioration(time_length, data_path) # Deterioration # data = data_extraction_rlos(time_length, data_path) # LOS data = data.reset_index(drop=True) all_idx = np.array(list(data['patientunitstayid'].uniq...
def read_file(self): """ Reads a file into memory """ logger.debug(f"[debug] reading from {self.path}") with open(self.path, "rb") as f: self.data = f.read() def check_upx(self): """ Checks if a file is UPX packed return: bool """ ...
This code unpacks a file using UPX by first checking for UPX presence. If initial unpacking fails, it fixes UPX headers, rewrites the file, and retries. If both attempts fail, it raises an error. The task involves validating UPX packing, handling unpacking errors through header fixes, and ensuring successful unpacking ...
def unpack(self, unpack_out = None): self.read_file() unpack_output = unpack_out # self.check_upx() uses a custom magic if supplied # so if not present, just die anyway if not self.check_upx(): raise NotUPXPackedErr() # first run UPX to check if it unpacks p...
def make_post_data(self, data): """ process a dictionary of {parameter names : parameter data} in order to generate appropriate post_data data to add to the REST call Args: data {parameter names : parameter data} : a dictionary representing the post_datas ...
The code retrieves asset information (aclass, altname, decimals, display_decimals) for deposit, withdrawal, trading, and staking from a cryptocurrency API. It accepts parameters `aclass` (e.g., "currency") and `asset` (default "all") to filter results. The function constructs a POST request to the `/0/public/Assets` en...
def get_assetinfo(self, aclass="", asset=""): """ Get information about the assets that are available for deposit, withdrawal, trading and staking Args: aclass : (string) asset class "currency" asset : (string) comma delimited list of assets to get info on...
def make_post_data(self, data): """ process a dictionary of {parameter names : parameter data} in order to generate appropriate post_data data to add to the REST call Args: data {parameter names : parameter data} : a dictionary representing the post_datas ...
The function retrieves tradable asset pair details from an API, returning structured data like leverage, fees, margin levels, and decimal specifications based on the specified 'info' type (e.g., 'info', 'leverage') and provided asset pairs (e.g., 'XXBTCZUSD'). It constructs a POST request using the '/0/public/AssetPair...
def get_assetpairs(self, info="", pair=""): """ Get tradable asset pairs Args: info: (string) info to retrieve "info" - default "leverage" "fees" "margin" pair:(string) Asset pairs to get data...
def make_post_data(self, data): """ process a dictionary of {parameter names : parameter data} in order to generate appropriate post_data data to add to the REST call Args: data {parameter names : parameter data} : a dictionary representing the post_datas ...
The function retrieves market data for a specified asset pair (e.g., XBTUSD) from a public API, returning a dictionary containing key metrics like price (c), volume (v), timestamp (t), and price bounds (h, l, o). It constructs a request to the '/0/public/Ticker' endpoint with the provided pair, processes the response, ...
def get_tickerinfo(self, pair=""): """ Get info of given ticker (greeks??) Note: Today's prices start at midnight UTC Args: pair: (string) asset pair to get data for ex : XBTUSD Returns: ticker pair name (string) : { a ...
def make_post_data(self, data): """ process a dictionary of {parameter names : parameter data} in order to generate appropriate post_data data to add to the REST call Args: data {parameter names : parameter data} : a dictionary representing the post_datas ...
The main task of the code is to retrieve OHLC (Open, High, Low, Close) historical price data for a specified cryptocurrency pair and time interval from a financial API. It includes the current, uncommitted data point even if a 'since' timestamp is provided. The function constructs an API request, processes the response...
def get_ohlc(self, pair, interval="", since=""): """ Note: the last entry in the OHLC array is for the current, not-yet-committed frame and will always be present, regardless of the value of 'since' Args: pair: (string) REQUIRED - Asset pair to get data for ...
def make_post_data(self, data): """ process a dictionary of {parameter names : parameter data} in order to generate appropriate post_data data to add to the REST call Args: data {parameter names : parameter data} : a dictionary representing the post_datas ...
The code retrieves and returns the order book data for a specified cryptocurrency asset pair (e.g., XBTUSD), including ask and bid prices, volumes, and timestamps. It accepts parameters for the asset pair and the maximum number of asks/bids (default 100). The function constructs an API request, processes the response, ...
def get_orderbook(self, pair, count=""): """ get order book for given asset pair Args : pair : (string) REQUIRED - asset pair to get market depth for ex: XBTUSD count : (int) maximum number of asks/bids 100 - default ...
def make_post_data(self, data): """ process a dictionary of {parameter names : parameter data} in order to generate appropriate post_data data to add to the REST call Args: data {parameter names : parameter data} : a dictionary representing the post_datas ...
This method retrieves recent trade data for a specified asset pair (e.g., XBTUSD) since a given timestamp, defaulting to the last 1000 trades. It constructs an API request using the provided pair and optional 'since' parameter, processes the response, and returns structured trade data along with a 'last' ID for future ...
def get_recenttrades(self, pair, since=""): """ gets the most recent trades of given pair since given timestamp returns the last 1000 trades by default Args: pair : (stirng) REQUIRED - asset pair to get trade data for ex: XBTUSD since : (string...
def make_post_data(self, data): """ process a dictionary of {parameter names : parameter data} in order to generate appropriate post_data data to add to the REST call Args: data {parameter names : parameter data} : a dictionary representing the post_datas ...
This function retrieves recent spread data for a specified trading pair from a cryptocurrency exchange API. It accepts a required 'pair' parameter and an optional 'since' parameter to filter data. The method constructs a POST request to a public API endpoint, processes the response, and returns structured spread data a...
def get_recentspread(self, pair, since=""): """ Args: pair : (string) REQUIRED - asset pair to get spread data for since : (string) return spread data since given id (optional. inclusive) Returns: pair name (string) : [[<price>, <volume>, <time>(int), <buy/se...
def make_post_data(self, data): """ process a dictionary of {parameter names : parameter data} in order to generate appropriate post_data data to add to the REST call Args: data {parameter names : parameter data} : a dictionary representing the post_datas ...
This method retrieves trade balance details including collateral balances, margin positions, equity, and margin levels. It fetches data via an API, processes the response, and returns metrics like equivalent balance, trade balance, unrealized profit/loss, and margin level for a specified asset, defaulting to ZUSD.
def get_tradebalance(self, asset=""): """ Retrieve a summary of collateral balances, margin position valuations, equity and margin level. Args: asset : (string) base asset used to determine balance ZUSD - default Returns: eb : equivalent balanc...
def make_post_data(self, data): """ process a dictionary of {parameter names : parameter data} in order to generate appropriate post_data data to add to the REST call Args: data {parameter names : parameter data} : a dictionary representing the post_datas ...
This function retrieves details of currently open orders from a financial API, returning structured data including order status, timestamps, trade parameters, and execution metrics. It accepts optional parameters to include trade history and filter by user reference ID, then processes the API response into a nested dic...
def get_openorders(self, trades=False, userref=""): """ Retrieve information about currently open orders. Args: trades: (bool) default = False whether or not to include trades relevant to position in output userref: (int) restrict results to given user ref...
def make_post_data(self, data): """ process a dictionary of {parameter names : parameter data} in order to generate appropriate post_data data to add to the REST call Args: data {parameter names : parameter data} : a dictionary representing the post_datas ...
Your returnThe main task of the code is to retrieve information about closed orders (filled or canceled) from an API, with options to filter by user reference, time range, and include trades. It returns up to 50 results at a time, paginated via offset, and processes the response into a structured dictionary containing ...
def get_closedorders(self, trades=False, userref="", start="", end="", ofs="", closetime="both"): """ Retrieve information about orders that have been closed (filled or cancelled). 50 results are returned at a time, the most recent by default. Note: If an order's tx ID is given for start...
def make_post_data(self, data): """ process a dictionary of {parameter names : parameter data} in order to generate appropriate post_data data to add to the REST call Args: data {parameter names : parameter data} : a dictionary representing the post_datas ...
This method retrieves detailed information about specific orders using transaction IDs (txid), with optional parameters to include trade data and filter by user reference. It constructs an API request to a private endpoint, processes the response, and returns structured order data including status, volume, cost, fees, ...
def get_orderinfo(self, txid, trades=False, userref=""): """ Retrieve information about specific orders. Args: txid: (string) REQUIRED - Comma delimited list of transaction IDs to query info about (20 maximum) trades: (bool) default = False Whether or not ...
def make_post_data(self, data): """ process a dictionary of {parameter names : parameter data} in order to generate appropriate post_data data to add to the REST call Args: data {parameter names : parameter data} : a dictionary representing the post_datas ...
This method retrieves trade/fill history data from an API, returning up to 50 results at a time. It allows filtering by trade type, inclusion of position-related trades, time ranges (via timestamps or transaction IDs), and pagination offset. The response includes structured trade details like transaction IDs, asset pai...
def get_tradeshistory(self, type="", trades=False, start="", end="", ofs=""): """ Retrieve information about trades/fills. 50 results are returned at a time, the most recent by default. Unless otherwise stated, costs, fees, prices, and volumes are specified with the precision for the asset pair ...
def make_post_data(self, data): """ process a dictionary of {parameter names : parameter data} in order to generate appropriate post_data data to add to the REST call Args: data {parameter names : parameter data} : a dictionary representing the post_datas ...
The function retrieves trade/fill information for specified transaction IDs via an API, returning details like order IDs, pairs, time, price, cost, and fees. It accepts up to 20 comma-separated txids and includes position-related trades if the 'trades' flag is set to True.
def get_tradesinfo(self, txid, trades=False): """ Retrieve information about specific trades/fills. Args: txid: (string) REQUIRED - Comma delimited list of transaction IDs to query info about (20 maximum) trades: (bool) default = False Whether or not to in...
def make_post_data(self, data): """ process a dictionary of {parameter names : parameter data} in order to generate appropriate post_data data to add to the REST call Args: data {parameter names : parameter data} : a dictionary representing the post_datas ...
The code retrieves open margin positions from an API, allowing filtering by transaction IDs (txid), inclusion of profit/loss calculations (docalcs), and consolidation by market/pair (consolidation). It constructs a request, sends it, and returns detailed position data like order IDs, time, type, cost, volume, margin, a...
def get_openpositions(self, txid="", docalcs=False, consolidation="market"): """ Get information about open margin position Args: txid : (string) Comma delimited list of txids to limit output to docalcs : (bool) whether to include P&L calculations consolidatio...
def make_post_data(self, data): """ process a dictionary of {parameter names : parameter data} in order to generate appropriate post_data data to add to the REST call Args: data {parameter names : parameter data} : a dictionary representing the post_datas ...
The function retrieves ledger entries based on parameters like asset, class, type, and time ranges, returning structured data with details such as transaction IDs, timestamps, amounts, fees, and balances, limited to 50 results per request.
def get_ledgerspread(self, asset="", aclass="", type="all", start="", end="", ofs=""): """ Retrieve information about ledger entries. 50 results are returned at a time, the most recent by default Args: asset: (string) Comma delimited list of assets to restrict output to ...
def make_post_data(self, data): """ process a dictionary of {parameter names : parameter data} in order to generate appropriate post_data data to add to the REST call Args: data {parameter names : parameter data} : a dictionary representing the post_datas ...
The code retrieves ledger entry information from an API by sending a POST request with specified ledger IDs and a flag to include trade-related data, then processes and returns the structured response containing details like transaction IDs, timestamps, types, balances, and fees.
def get_ledgerinfo(self, id="", trades=False): """ Retrieve information about specific ledger entries Args: id: (string) comma delimited list of ledger IDs to query info about (20 max) trades: (bool) default = False whether or not to include trades rel...
def make_post_data(self, data): """ process a dictionary of {parameter names : parameter data} in order to generate appropriate post_data data to add to the REST call Args: data {parameter names : parameter data} : a dictionary representing the post_datas ...
The function retrieves trade volume and fee information for a specified asset pair from a private API endpoint. It accepts a pair (single or comma-separated) and a fee_info flag. If enabled, it returns detailed fee tiers (maker/taker) including min/max fees, next thresholds, and volume tiers. The result includes curren...
def get_tradevolume(self, pair, fee_info=True): """ get the trade volume of a given pair Note: If an asset pair is on a maker/taker fee schedule, the taker side is given in fees and maker side in fees_maker. For pairs not on maker/taker, they will only be given in fees Ar...
def make_post_data(self, data): """ process a dictionary of {parameter names : parameter data} in order to generate appropriate post_data data to add to the REST call Args: data {parameter names : parameter data} : a dictionary representing the post_datas ...
The main task of the code is to request an export of trades or ledgers data from an API, specifying parameters like report type, format, fields, and time range. It constructs a POST request with provided arguments, sends it via the API, and returns the processed response. The function allows exporting data in CSV/TSV f...
def request_report(self, report, description, format="CSV", fields="all", starttm="", endtm=""): """ Request an export of trades or ledgers Args: report: (string) REQUIRED - type of data to export : "trades" "ledgers" description: (...
def make_post_data(self, data): """ process a dictionary of {parameter names : parameter data} in order to generate appropriate post_data data to add to the REST call Args: data {parameter names : parameter data} : a dictionary representing the post_datas ...
This function retrieves the status of requested data exports (e.g., trades or ledgers) by querying a private API endpoint. It constructs a POST request with the specified report type, sends it, and returns structured data including export status, timestamps, metadata, and details about each report's progress and comple...
def get_reportstatus(self, report): """ Get status of requested data exports Args: report: (string) REQUIRED - type of reports to inquire about "trades" "ledgers" Returns: [ { id : ...
def make_post_data(self, data): """ process a dictionary of {parameter names : parameter data} in order to generate appropriate post_data data to add to the REST call Args: data {parameter names : parameter data} : a dictionary representing the post_datas ...
Your returnThe main task of the code is to delete or cancel an exported trades/ledgers report via an API call. It accepts a report ID and action type ("delete" or "cancel"), validates the action against the report's status, constructs a POST request with the parameters, and returns a boolean indicating success. The fun...
def delete_report(self, id, type): """ delete exported trades/ledgers report Args: id: (string) REQUIRED - ID of report to delete or cancel type: (string) REQUIRED - delete or cancel "cancel" - can only be used for queued or processing reports ...
def make_post_data(self, data): """ process a dictionary of {parameter names : parameter data} in order to generate appropriate post_data data to add to the REST call Args: data {parameter names : parameter data} : a dictionary representing the post_datas ...
This function submits or validates a trade order to a financial API, specifying parameters like order type (market/limit), asset pair, volume, price, leverage, and conditional close rules. It constructs a POST request with user-defined flags, timing, and validation options, returning order details and a transaction ID.
def add_order(self, ordertype, type, pair, userref="", volume="", price="", price2="", leverage="", oflags="", starttm="", expiretm="", close_ordertype="", close_price="", close_price2="", trading_agreement="", validate=False): """ Args: ...
def make_post_data(self, data): """ process a dictionary of {parameter names : parameter data} in order to generate appropriate post_data data to add to the REST call Args: data {parameter names : parameter data} : a dictionary representing the post_datas ...
The main task of the code is to cancel an open order using a provided transaction ID (txid) or user reference. It constructs a POST request to the 'CancelOrder' API endpoint, sends the txid as data, and returns the count of canceled orders from the processed response. The function relies on helper methods to format dat...
def cancel_order(self, txid): """ Args: txid: (string or integer) REQUIRED - Open order transaction ID (txid) or user reference (userref) Returns: count: number of orders canceled(?) """ api_path = '/0/private/' endpoint = 'CancelOrder' d...
def make_post_data(self, data): """ process a dictionary of {parameter names : parameter data} in order to generate appropriate post_data data to add to the REST call Args: data {parameter names : parameter data} : a dictionary representing the post_datas ...
This function implements a "Dead Man's Switch" mechanism to automatically cancel all client orders if a specified timeout expires. It sends a request with a timeout value to an API endpoint, resetting or deactivating the timer. If the timer expires, all orders are cancelled, and the timer remains disabled until reactiv...
def cancel_allordersafter(self, timeout): """ CancelAllOrdersAfter provides a "Dead Man's Switch" mechanism to protect the client from network malfunction, extreme latency or unexpected matching engine downtime. The client can send a request with a timeout (in seconds), that will start a...
def make_post_data(self, data): """ process a dictionary of {parameter names : parameter data} in order to generate appropriate post_data data to add to the REST call Args: data {parameter names : parameter data} : a dictionary representing the post_datas ...
This function retrieves deposit method details for a specified cryptocurrency asset by querying an API, returning information such as available methods, deposit limits, fees, and address generation parameters.
def get_depositmethods(self, asset): """ Args: asset: (string) REQUIRED - asset being deposited Returns: method: limit: fee: gen-address """ api_path = '/0/private/' endpoint = 'DepositMethods' data = dic...
def make_post_data(self, data): """ process a dictionary of {parameter names : parameter data} in order to generate appropriate post_data data to add to the REST call Args: data {parameter names : parameter data} : a dictionary representing the post_datas ...
This function retrieves a deposit address for a specified asset and method via an API call. It generates a new address if 'new' is True, returning the address, expiration time, and new status. Parameters include asset (string), method (string), and new (bool). The function constructs a POST request to the 'DepositAddre...
def get_depositaddress(self, asset, method, new=True): """ Args: asset: (string) REQUIRED - asset being deposited method: (string) REQUIRED - name of the deposit method new: (bool) wether or not to generate a new address Returns: address: ...
def make_post_data(self, data): """ process a dictionary of {parameter names : parameter data} in order to generate appropriate post_data data to add to the REST call Args: data {parameter names : parameter data} : a dictionary representing the post_datas ...
Your return This function retrieves the status and details of the most recent deposit for a specified asset, optionally filtered by a deposit method. It constructs an API request to the 'DepositStatus' endpoint, sends parameters (asset, method), and returns parsed response data including method, asset, transaction ID, ...
def get_depositstatus(self, asset, method=""): """ Gets status and information of most recent deposit of given asset Args: asset: (string) REQUIRED - asset being deposited method: (string) name of the deposit method Returns: method: aclass:...
def make_post_data(self, data): """ process a dictionary of {parameter names : parameter data} in order to generate appropriate post_data data to add to the REST call Args: data {parameter names : parameter data} : a dictionary representing the post_datas ...
Your return The function `get_withdrawalinfo` retrieves fee information for potential cryptocurrency withdrawals. It takes parameters `asset` (coin type), `key` (withdrawal address), and `amount` to query an API endpoint. The method constructs a POST request, sends it to the specified API path, and processes the resp...
def get_withdrawalinfo(self, asset, key, amount): """ Retrieve fee information about potential withdrawals for a particular asset, key and amount. Args: asset: (string) asset being withdrawn key: (string) withdrawal key name, as set up on your account amount: ...
def make_post_data(self, data): """ process a dictionary of {parameter names : parameter data} in order to generate appropriate post_data data to add to the REST call Args: data {parameter names : parameter data} : a dictionary representing the post_datas ...
The function retrieves withdrawal fee information for a specified asset, key, and amount by sending a POST request to an API endpoint, then returns the reference ID from the response.
def withdraw_funds(self, asset, key, amount): """ Retrieve fee information about potential withdrawals for a particular asset, key and amount. Args: asset: (string) REQUIRED - asset being withdrawn key: (string) REQUIRED - withdrawal key name, as set up on your account ...