dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def get_traineddata(): datafile = open('data/matrix_trainedP.csv', 'r') datareader = csv.reader(datafile, delimiter=',') P = [] for row in datareader: P.append(row) datafile = open('data/matrix_trainedQ.csv', 'r') datareader = csv.reader(datafile, delimiter=',') Q = [] for row i...
The code adds a new user to a trained matrix factorization model by initializing their latent vector with random data, computes predicted ratings using existing P/Q matrices, and generates top movie recommendations for the new user via collaborative filtering.
def adduserandsolve(data_toadd): alpha = 0.0002 beta = 0.02 iterations = 1000 similarities = 2 getP, getQ = (get_traineddata()) # tempR = np.dot(getP,getQ) # R = np.vstack([R, data_toadd]) # Q = np.random.rand(tempR[0], similarities) randdata = np.random.rand(1, similarities) ge...
def get_lat_long_google_yes(Pincode, City, State, Full_Address, appl_id, req_id, inst_name, src_sys_name, product): """ Note: Address match percentage threshold is set to 85% Algorithm Flow: 1) Ping the address to google geocoding 2) Extract latitude,longitude and types...
The function `get_latlong` retrieves latitude and longitude data using specified geocoding APIs (Google, HERE, Multiple) based on input parameters like pincode, city, state, and address. It checks the `geocode_api` and `rev_geocode` flags to determine which API method to use, logs status messages, and returns a filtere...
def get_latlong(request_json): input_json = request_json Pincode = input_json.get('pincode') City = input_json.get('city') State = input_json.get('state') Full_Address = input_json.get('full_addr') geocode_api = input_json.get('geocode_api') rev_geocode = input_json.get('rev_geocode') ap...
def greet(): message(speak.greeting) speak.greet() def parse_func_type(): generate_visualization = ["generate", "visualization"] predict = ["predict"] calc_stat_figs = ["calculate", "statistical", "key", "figures"] if st.session_state["run"]: while True: intent = ask_func_ty...
This code creates a Streamlit interface for a data analysis assistant named Jarvis. It lists available datasets/models, starts/stops an interaction loop, and performs tasks like predictions, visualizations, or statistical figures based on user input. The loop runs until manually stopped, processing data and models to d...
def verbal_interaction(): st.session_state["run"] = False st.sidebar.write("# Here are the available datasets:") for item in mq.list_all_collections(): st.sidebar.write("- " + item) st.sidebar.write("# Here are the available models:") for item in ml.list_all_models(): st.sidebar.wr...
def search_audio(start_path, ext): file_paths = [] for lv1 in sorted(os.listdir(start_path)): lv1_path = os.path.join(start_path, lv1) if lv1 == PREPROCESS_NOISE_DIR: # Don't search the output folder for audio continue elif os.path.isfile(lv1_path) and lv1.endswith(ext): ...
This function generates augmented audio data by mixing speech signals with noise, creating a new wav.scp file containing SoX commands. It supports directory or single-file noise inputs, random noise selection, and outputs mixed audio with specified SNR levels. The code reads utterance lists, validates IDs, prepares noi...
def main(wavscp_path, utt2dur_path, noiseFile_path, noise_ext=None, mix_snr=None, speech_level_str=None, noise_level_str=None, mix_level=None, noise_timestamp=None, noiseROI_path=None, dry_run=False, sph2pipe=None, job_num=None): noiseWAV_path = [] if noise_ext is not None: # Directory mode n...
def designWords(words): for n in words: sys.stdout.flush() time.sleep(0.03) print(n, end="") print() def red(sentence): sentence = "\u001b[31m" + sentence + "\u001b[0m" return sentence def green(sentence): sentence = "\u001b[32m" + sentence + "\u001b[0m" return sentence d...
The code defines a Blackjack game function that welcomes the user, collects their name, plays the game to calculate a score, and offers to save the score to a highscore system. It uses input validation to handle save choices and ensures the user's data is recorded if they opt to save their score.
def blackJack(): #os function for clearing the output terminal. makes it easier for the user to play the game. os.system('cls') designWords(red("HELLO AND WELCOME TO BLACKJACK!")) designWords(red("WHAT IS YOUR NAME?: ")) #this will be used for recording the user's data name = input() #f-stri...
def _to_posix_path(name): return name.replace(os.sep, "/") def _get_key_name(self, name): if name.startswith("/"): name = name[1:] return posixpath.normpath(posixpath.join(self.settings.AWS_S3_KEY_PREFIX, _to_posix_path(name))) def meta(self, name): """Returns a dictionary of met...
This function checks if a file or directory exists in an S3 bucket. If the name ends with a slash, it treats it as a directory and checks for keys with that prefix. If not, it verifies the file's existence by fetching metadata. If metadata retrieval fails, it recursively checks if the name with a trailing slash exists,...
def exists(self, name): name = _to_posix_path(name) if name.endswith("/"): # This looks like a directory, but on S3 directories are virtual, so we need to see if the key starts # with this prefix. try: results = self.s3_connection.list_objects_v2( ...
def meta(self, name): """Returns a dictionary of metadata associated with the key.""" return self.s3_connection.head_object(**self._object_params(name)) def _object_put_params(self, name): # Set basic params. params = { "ACL": "private" if self.settings.AWS_S3_BUCKET_AUTH els...
This function synchronizes metadata for S3 objects by iterating through a bucket's contents, copying each object with updated metadata including content encoding and size information, while handling race conditions and metadata normalization issues. It yields each processed object's name.
def sync_meta_iter(self): paginator = self.s3_connection.get_paginator("list_objects_v2") pages = paginator.paginate( Bucket=self.settings.AWS_S3_BUCKET_NAME, Prefix=self.settings.AWS_S3_KEY_PREFIX, ) for page in pages: for entry in page.get("Contents"...
def __get_parent_index(self, i): """Find the index in the array of the element which is the parent of element[i] """ return (i - 1)//2 def __check_heap_property(self, index): """check heap propert is ok at index 'index' """ elt = self.elements[index] children = self.__get_childre...
This code inserts a new node into a heap structure by appending it to the end of the elements list and then maintaining the heap property through upward bubbling. It swaps the node with its parent until the heap property is satisfied, ensuring the tree remains a valid heap.
def insert(self, node): """ insert new node """ current_len = len(self.elements) # add it self.elements.append(node) index = current_len parent_index = self.__get_parent_index(index) # cheeck heap property is ok while parent_index >= 0 and not self.__check...
def get_size(self): """total size""" return len(self.elements) def __check_heap_property(self, index): """check heap propert is ok at index 'index' """ elt = self.elements[index] children = self.__get_children(index) #get the children and find ones that are wrong ...
This method removes the minimum element from a min-heap by replacing it with the last element, then restoring the heap property through a "bubble down" process. It checks for empty heap cases, swaps the root with its smallest child iteratively, and ensures the heap structure is maintained until the property is satisfie...
def remove(self): """ remove the top (min) element """ num_elements = self.get_size() if num_elements == 0: return None else: root = self.elements[0] last = self.elements[-1] self.elements[0] = last self.elements.pop() ...
def train(self, file_path=None, data_list=None, max_dnf_len=4, error_tolerance=0.00, min_match=0.00, use_approx_dnf=False, redundant_thresh=1.00, useExpanded=True, use_stochastic=False, stochastic_min_rating=0.97): # file_path: input file in tab-delimited text # data_list: list matrix da...
The main task of the code is to train and optimize a model using provided data. It splits data into training and validation sets, trains the model with specified parameters (e.g., DNF length, error tolerance), then optimizes it using either compact or standard methods on the validation set. The function prepares numeri...
def train_and_optimize(self, data_list=None, max_dnf_len=4, error_tolerance=0.00, min_match=0.00, use_approx_dnf=False, redundant_thresh=1.00, elements_count_penalty=1.0, use_compact_opt=False, cnt_out=20, useUnion=False, useExpanded=True, use_stochastic=False, stocha...
def clean_and_discretize(self, inp, by_two): inp = copy.deepcopy(inp) inp = [[Deterministic_Regressor.try_convert_to_numeric(inp[i][j]) for j in range(len(inp[i]))] for i in range(len(inp))] matrix = self.discretize_data(inp, by_two) head = matrix[0] return [head] + [[int(mm) for...
The function preprocesses continuous data for regression by clustering, splitting data into train/test sets, adding quadratic features if specified, and preparing data for regression models with parameters like max_reg, thresh, and linear_type.
def prepropcess_continous(self, whole_rows, by_two, splitter=3, max_reg=2, thresh=0.3, add_quads=False, max_vars=3, omit_similar=False, include_all=True, include_related=True, sample_limit=0, num_fit=5, use_multinomial=False, add_cluster_label=False, use_piecewise=True, linear_type="lasso...
def train(self, file_path=None, data_list=None, max_dnf_len=4, check_false=True, check_negative=False, error_tolerance=0.02, min_match=0.03, use_approx_dnf=False, redundant_thresh=1.00): # file_path: input file in tab-delimited text # check_negative: enable to check the negative conditions or not. This one is very he...
The main task of the code is to train and optimize a deterministic regressor model using provided data. It splits data into training and validation sets, trains the model with specified constraints (e.g., DNF length, error tolerance), processes validation data (numeric conversion, negative checks), and applies either c...
def train_and_optimize(self, data_list=None, max_dnf_len=4, check_false=True, check_negative=False, error_tolerance=0.02, min_match=0.03, use_approx_dnf=False, redundant_thresh=1.00, solve_method=["common", "union"], elements_count_penalty=1.0, use_compact_opt=False, ...
def compare(self): enterprise = self.__get_enterprise_data() pm = self.__get_pm_data() compare = enterprise.merge(pm, how='outer', on=['hotelCode', 'date', 'channelName', 'subChannelName'], ...
The code's main task is to execute a comparison process, save the results to an Amazon S3 bucket at a specified path, and post an SNS message to notify of completion. It logs progress at each step, including starting the comparison, saving results to S3, and sending the SNS message.
def run(self, s3_bucket, s3_base_path): logging.info(f'Running comparer') self.compare() logging.info(f'Comparison complete') self.save_to_s3(s3_bucket, s3_base_path) logging.info(f'Posted results to {self.s3_location}') self.post_message() logging.info(f'Posted s...
def read_logs(dir): ''' Read :param dir: :return: ''' lines = [] csv_file = dir + "/" + 'driving_log.csv' with open(csv_file) as csvfile: reader = csv.reader(csvfile) for line in reader: lines.append(line) return lines def checkSteeringAngle(angle): re...
The code processes images from log files, adjusting steering angles for left/right cameras, flipping images, and saving augmented images in a directory. It returns lists of processed angles and corresponding filenames for training data.
def process_all_images( dir ): lines = read_logs(dir) angles = [] filenames = [] save_dir_path = 'data/result/' for line in lines: new_images = [] # augment images and angles center_image_path = line[0].replace(" ", "") left_image_path = line[1].replace(" ", "...
def decode_h_map_112(chunk, map_name): heights = [[255 for z in range(16)] for x in range(16)] for i in range(256): heights[i % 16][i // 16] = chunk['HeightMap'][i] - 1 # default map if map_name == 'OCEAN_FLOOR': for x in range(16): for z in range(16): while ge...
The function `decode_h_map` determines the appropriate decoding method for map data based on the `data_version` parameter. If the version is less than 1451, it uses `decode_h_map_112`; between 1451–2528, it uses `decode_h_map_115`; and for versions 2529 and above, it uses `decode_h_map_116`. If no version matches, it r...
def decode_h_map(chunk, data_version, map_name): if data_version < 1451: return decode_h_map_112(chunk, map_name) if 1451 <= data_version < 2529: # the flattening - right before they changed the format again return decode_h_map_115(chunk, map_name) elif 2529 <= data_version: # new new new ...
def h_from_label(self, label=5, multiplier = 1, gen_mode = 'from_label'): #si vede qualcosa, ma non funziona super bene if gen_mode == 'from_label': lbl_vec = torch.zeros(self.Num_classes).to(self.Device) lbl_vec[label]=1*multiplier lbl_vec = lbl_vec.cpu()....
This code reconstructs images from hidden layer representations in a neural network model, visualizing the reconstruction process over multiple steps. It generates initial hidden states from labels (or user input), iteratively refine visible reconstructions via alternating Gibbs sampling, and plots results at specified...
def reconstruct_from_h(self ,nr_steps = 50, nr_print=5, generation_mode = 'from_label'): print_idx = list(range(round(nr_steps/nr_print)-1,nr_steps,round(nr_steps/nr_print))) if generation_mode == 'from_label': figure, axis = plt.subplots(self.Num_classes, nr_print+1, figsize=(3*(nr_prin...
def ReadInfo(self): self.license.SetLicenseURI( liblicense.read(os.path.join(self.dirname, self.filename)) ) self.license.SetAuthor( liblicense.read(os.path.join(self.dirname, self.filename), liblicense.LL_CREATOR) ) self.license.SetTitle( liblicense.read(os.path.join(self.dirname, self.filename...
This code initializes a MainWindow GUI for a license tagging application, setting up the window with a specified size and program name. It processes a provided license object and filepath (if given), splitting the path into directory and filename, then reads info from the file. It creates UI components, enables drag-an...
def __init__(self, license): super(MainWindow, self).__init__(None, size=(600,280)) self.programname = _('License Tagger') self.license = license #for parameter, we split the filepath into dirname and filename if filepath : pathsplit = os.path.split(filepath) ...
def askUserForFilename(self, **dialogOptions): dialog = wx.FileDialog(self, **dialogOptions) if dialog.ShowModal() == wx.ID_OK: userProvidedFilename = True self.filename = dialog.GetFilename() self.dirname = dialog.GetDirectory() self.SetTitle() # Update t...
The method `OnSaveAs` prompts the user to specify a filename for saving data, using a dialog with default options. If the user confirms the filename, it triggers the `OnSave` method to perform the actual saving operation with the provided event.
def OnSaveAs(self, event): if self.askUserForFilename(defaultFile=self.filename, style=wx.SAVE, **self.defaultFileDialogOptions()): self.OnSave(event)
def _find_latesttime(path): dir_list = os.listdir(path) time_list = [] for directory in dir_list: try: float(directory) time_list.append(directory) except: pass time_list.sort(key=float) return time_list[-1] def _make_path(path, time_name=None, na...
This code initializes a class to read and parse a FoamFile (likely from OpenFOAM simulations), handling compressed files, extracting dimensions, boundary fields, and specific data (points, faces, etc.) based on parameters. It determines file format, processes content, and structures data according to input flags like '...
def __init__( self, path, time_name=None, name=None, structured=False, boundary=None, order="F", precision=15, ): self.pathcase = path if time_name is "latestTime": time_name = _find_latesttime(path) self.path = _ma...
def register_image(fixed_image, moving_image, transformParameterMap=None, interpolator='nn', dataset=None, param_set=['translation', "affine"]): """Perform registration of the moving image to fixed image. Either learn the registra...
The main task of the code is to process medical imaging datasets by registering and resampling paired lung scans and masks using affine transformations. It reads case lists, applies intensity scaling, transforms keypoints, resamples images to uniform voxel sizes, and saves processed data in structured directories for d...
def main(): for dataset in data_dir.iterdir(): if not dataset.is_dir(): continue if 'learn2reg' in str(dataset): continue cases = [] with open(dataset/'train_cases.txt') as f: cases.extend(f.readlines()) with open(dataset/'val_cases.txt') a...
def getAsset(id): """get the details for the specified asset""" url = "/asset/" + id return doHTTPRequest(url, "") def getDevice(deviceId): """get all the devices related to a ground""" url = "/device/" + deviceId return doHTTPRequest(url, "") def getGateway(id): """get the details for the s...
The function `getOutPath` converts an asset ID into a hierarchical path structure by retrieving associated device and gateway information. It constructs a dictionary with keys 'asset', 'device', and/or 'gateway' based on the asset's relationships. If the asset belongs to a device with a gateway, it includes all three l...
def getOutPath(assetId): """converts the asset id to a path of gateway id /device name / asset name or device id / asset name""" result = {} asset = getAsset(assetId) result['asset'] = asset['name'] device = getDevice(asset['deviceId']) if device: if 'gatewayId' in device and device['gat...
def parse_file(filename): print(filename) df = pd.read_csv(filename) df = df.drop(['SC_GROUP','SC_TYPE','LAST','PREVCLOSE','NO_TRADES','NO_OF_SHRS','NET_TURNOV','TDCLOINDI'], 1) print(df.head()) print(filename[-12:]) write_to_redis(df) return filename def download_extract(d = None): glob...
The function `get_latest_file` searches for the latest existing CSV file in the "Extracted_files" directory with a name format of "EQDDMMYY.csv", decrementing the date by one day if the file is not found. If an error occurs, it triggers a download/extract process and retries. It returns the filename after locating it, ...
def get_latest_file(keys = None): print("Finding Latest File...") d = datetime.datetime.today() try: while True: filename_ = "EQ"+str(d.strftime("%d"))+str(d.strftime("%m"))+str(d.strftime("%y"))+".csv" if os.path.exists(os.path.join("Extracted_files",filename_)): ...
def get_notes(file_name): # TODO include rests down_sample = 1 sample_rate = 44100 // down_sample # fft size win_s = 512 // down_sample # hop size hop_s = 256 // down_sample s = source(file_name, sample_rate, hop_s) sample_rate = s.samplerate notes_o = notes("default", win_s, hop_s, sample_rate) ...
This code converts audio analysis data into LilyPond musical notation. It extracts notes, onsets, and BPM from an audio file, calculates note lengths using the time signature, pairs notes with their durations, and generates LilyPond output with specified clef and time signature parameters.
def gen_lily(self, clef, time_sig): file = "output.wav" n = self.get_notes(file) o = self.get_onsets(file) b = self.get_bpm(file) lengths = self.note_length(o, b, int(time_sig[2])) all_notes = self.pair_value_length(n, lengths) self.to_lily_pond(all_notes, time_sig, clef)
def get_comp_data(context): """Create list of static blender's data""" scene = context.scene aspect_x = scene.render.pixel_aspect_x aspect_y = scene.render.pixel_aspect_y aspect = aspect_x / aspect_y start = scene.frame_start end = scene.frame_end active_cam_frames = get_active_cam_for_e...
The code exports After Effects composition data to a JSX file by retrieving composition data and selection, then writing them with specified options (e.g., animations, cameras, objects) to the given filepath, finally printing a completion message and returning a finish status.
def execute(self, context): data = get_comp_data(context) selection = get_selected(context) write_jsx_file(self.filepath, data, selection, self.include_animation, self.include_active_cam, self.include_selected_cams, self.include_selected_objects, sel...
def _start_using(self): if self._pid != os.getpid(): # Looks like we forked! Have to start a new data file. self._reset() self._choose_filename() self._pid = os.getpid() if not self._have_used: self.erase() self._have_used = True def _c...
This function retrieves the plugin name associated with a file's tracer from a database. It returns the plugin name if the file exists and has a tracer, an empty string if the file was measured without a plugin, and None if the file wasn't measured. It uses a database connection to query the tracer table using the file...
def file_tracer(self, filename): """Get the plugin name of the file tracer for a file. Returns the name of the plugin that handles this file. If the file was measured, but didn't use a plugin, then "" is returned. If the file was not measured, then None is returned. """ ...
def _start_using(self): if self._pid != os.getpid(): # Looks like we forked! Have to start a new data file. self._reset() self._choose_filename() self._pid = os.getpid() if not self._have_used: self.erase() self._have_used = True def _c...
This function retrieves arcs (fromno, tono) from a database based on the provided filename and optional context. It connects to the database, checks if the file exists, constructs a query with context filtering if provided, executes the query, and returns the results as a list.
def arcs(self, filename, context=None): self._start_using() with self._connect() as con: file_id = self._file_id(filename) if file_id is None: return None else: query = "select fromno, tono from arc where file_id = ?" da...
def _start_using(self): if self._pid != os.getpid(): # Looks like we forked! Have to start a new data file. self._reset() self._choose_filename() self._pid = os.getpid() if not self._have_used: self.erase() self._have_used = True def _c...
(The main task of the code is to add per-file plugin information to a database, ensuring no conflicts with existing plugins. It iterates through a dictionary of filename-plugin pairs, checks if each file is measurable, verifies no existing conflicting plugin is registered, and inserts new plugin data into the database ...
def add_file_tracers(self, file_tracers): """Add per-file plugin information. `file_tracers` is { filename: plugin_name, ... } """ self._start_using() with self._connect() as con: for filename, plugin_name in iitems(file_tracers): file_id = self._fil...
def _start_using(self): if self._pid != os.getpid(): # Looks like we forked! Have to start a new data file. self._reset() self._choose_filename() self._pid = os.getpid() if not self._have_used: self.erase() self._have_used = True def _c...
The function `add_lines` inserts measured line data into a database. It processes a dictionary mapping filenames to line numbers, logs debug info, sets context, and uses `executemany` to insert records into the `line` table with `(file_id, context_id, lineno)`, ignoring duplicates. The core task is efficiently storing ...
def add_lines(self, line_data): """Add measured line data. `line_data` is a dictionary mapping file names to dictionaries:: { filename: { lineno: None, ... }, ...} """ if self._debug.should('dataop'): self._debug.write("Adding lines: %d files, %d lines total" %...
def _start_using(self): if self._pid != os.getpid(): # Looks like we forked! Have to start a new data file. self._reset() self._choose_filename() self._pid = os.getpid() if not self._have_used: self.erase() self._have_used = True def _c...
This function adds measured arc data from a dictionary to a database. It processes each file's arcs, converts them into database records with file and context IDs, and inserts them using bulk operations. Debug logs track the number of files and arcs added. The SQL 'insert or ignore' ensures duplicates are skipped.
def add_arcs(self, arc_data): """Add measured arc data. `arc_data` is a dictionary mapping file names to dictionaries:: { filename: { (l1,l2): None, ... }, ...} """ if self._debug.should('dataop'): self._debug.write("Adding arcs: %d files, %d arcs total" % ( ...
def _start_using(self): if self._pid != os.getpid(): # Looks like we forked! Have to start a new data file. self._reset() self._choose_filename() self._pid = os.getpid() if not self._have_used: self.erase() self._have_used = True def ha...
This function retrieves unique line numbers from a file's coverage data. It first attempts to get line numbers via arcs (if available), filtering out zero values. If arcs are unavailable, it queries a database for line numbers associated with the file (and context, if provided), returning them as a list.
def lines(self, filename, context=None): self._start_using() if self.has_arcs(): arcs = self.arcs(filename, context=context) if arcs is not None: all_lines = itertools.chain.from_iterable(arcs) return list(set(l for l in all_lines if l > 0)) ...
def _start_using(self): if self._pid != os.getpid(): # Looks like we forked! Have to start a new data file. self._reset() self._choose_filename() self._pid = os.getpid() if not self._have_used: self.erase() self._have_used = True def _f...
The `touch_file` method ensures a specified `filename` is recorded in the coverage data, creating it if necessary. It associates the file with a `plugin_name` for tracking purposes. The method checks if the data is empty and raises an error if so. It logs the action if debugging is enabled, adds the file to the interna...
def touch_file(self, filename, plugin_name=""): """Ensure that `filename` appears in the data, empty if needed. `plugin_name` is the name of the plugin resposible for this file. It is used to associate the right filereporter, etc. """ self._start_using() if self._debug.s...
def measured_files(self): """A set of all files that had been measured.""" return set(self._file_map) def _start_using(self): if self._pid != os.getpid(): # Looks like we forked! Have to start a new data file. self._reset() self._choose_filename() ...
This code merges coverage data from two sources (self and other_data), ensuring compatibility by preventing mixing of line and arc data. It maps filenames using aliases, combines line/arcs coverage, and checks for conflicts in file tracers, raising exceptions on mismatches. The task is to safely integrate coverage metr...
def update(self, other_data, aliases=None): if self._has_lines and other_data._has_arcs: raise CoverageException("Can't combine arc data with line data") if self._has_arcs and other_data._has_lines: raise CoverageException("Can't combine line data with arc data") aliases...
def _bid_msg_add(self, msg: AddMessage) -> str: if not self._order_id_count: order = Order.from_msg(msg) order_id = self._bid_order_add(order) else: order = Order.from_msg(msg, self._order_id_count) order_id = self._bid_order_add(order) self._o...
This method processes incoming add messages for orders by determining whether to add the order to the bid or ask side, or to match it against existing orders, based on the order's price relative to current market levels. For buy orders, it checks against the low ask price; for sell orders, against the high bid price.
def _process_add_message(self, msg: AddMessage): if msg.side == OrderSide.BUY: if msg.price < self._low_ask: return self._bid_msg_add(msg) else: # msg.price >= self._limit_order_book.low_ask return self._ask_match(msg) else: # msg.side == OrderSi...
def _process_add_message(self, msg: AddMessage): if msg.side == OrderSide.BUY: if msg.price < self._low_ask: return self._bid_msg_add(msg) else: # msg.price >= self._limit_order_book.low_ask return self._ask_match(msg) else: # msg.side == OrderSi...
The code processes incoming messages by routing them to specific handler methods based on their type: AddMessage, DeleteMessage, or ModifyMessage, each triggering a corresponding private method for further processing.
def process(self, msg: Message): if isinstance(msg, AddMessage): self._process_add_message(msg) elif isinstance(msg, DeleteMessage): self._process_delete_message(msg) elif isinstance(msg, ModifyMessage): self._process_modify_message(msg)
def findPrefixPath(basePat, treeNode): # treeNode comes from header table condPats = {} while treeNode != None: prefixPath = [] ascendTree(treeNode, prefixPath) if len(prefixPath) > 1: condPats[frozenset(prefixPath[1:])] = treeNode.count treeNode = treeNode.nodeLink ...
This function recursively mines frequent itemsets from an FP-tree by sorting header table items, generating candidate itemsets, and building conditional trees. It appends valid itemsets to the list, ensuring minimum support thresholds, and processes conditional patterns to discover all frequent itemsets of size ≥3.
def mineTree(inTree, headerTable, minSup, preFix, freqItemList, maxSup): bigL = [v[0] for v in sorted(headerTable.items(), key=lambda p: p[1][0])] # (sort header table) for basePat in bigL: # start from bottom of header table newFreqSet = preFix.copy() newFreqSet.add(basePat) if len(ne...
def _all_nodes(self): return [self.start_node] + [x for x in range(self.map.shape[0]*self.map.shape[1]) if x not in (self._coord_to_node_id(self.starting_point), self._coord_to_node_id(self.end_point)) ] + [self.dest_node, ] def _node_id_to_coord(self, id: int) -> Tuple[int, int]...
The code solves a vehicle routing problem (VRP) by optimizing a route through nodes to maximize/minimize profit, adhering to time constraints and avoiding subtours. It uses binary variables for node connections and continuous variables for subtour elimination (MTZ constraints). The route starts at a designated node, en...
def _compute_route(self, visited_nodes: List[int], minimize_scores) -> Tuple[List[Tuple[int, int]], float]: ip = Model("OP instance", solver_name=self.solver) x = {j: {i: ip.add_var(var_type=BINARY) for i in self._all_nodes()} for j in self._all_nodes()} u = {i: ip.add_var(var_type=CONTINUOUS) f...
def removeUsers(tweet): tweet = re.sub('(RT\s@[A-Za-z]+[A-Za-z0-9-_]+)', '', tweet) # remove re-tweet tweet = re.sub('(@[A-Za-z]+[A-Za-z0-9-_]+)', '', tweet) # remove tweeted at return tweet def removeLinks(tweet): tweet = re.sub(r'http\S+', '', tweet) # remove http links tweet = re.sub(r'bit.ly...
This function preprocesses a tweet by removing users, links, hashtags, audio/video mentions, converting text to lowercase, stripping punctuation, eliminating numbers, and tokenizing/lemmatizing the text to prepare it for NLP tasks.
def preprocessTweet(tweet): tweet = removeUsers(tweet) tweet = removeLinks(tweet) tweet = removeHashtags(tweet) tweet = removeAudioVideo(tweet) tweet = tweet.lower() # make lower case so as not to trip up the model tweet = re.sub('[' + punctuation + ']+', ' ', tweet) # strip punctuation tw...
def db_connection(): """ Connects the web application to our SQL database. If unable the function prints and error message. Authors: Jake Rounds, Bella Woliver, Joshua Wienecke, Mugdha Merchant, Sneha Dilip Parameters: N/A Returns: N/A """ try: conn = psycopg2.connect(host=...
The function identifies ingredients with usage below 10% of their 500-unit restock quantity by querying orders within a specified time frame, aggregating ingredient usage data, and comparing totals to the threshold. It returns a list of underutilized ingredients.
def get_excess_report(data): """ Querys the orders table between an inputted time frame to find which ingredients are less that 10% of their original inventory Authors: Jake Rounds, Bella Woliver, Joshua Wienecke, Mugdha Merchant, Sneha Dilip Parameters: List of smoothie specifications Returns:...
def db_connection(): """ Summary or Description of the Function # connection to database Authors: Jake Rounds, Bella Woliver, Joshua Wienecke, Mugdha Merchant, Sneha Dilip Parameters: N/A Returns: connection """ try: conn = psycopg2.connect(host="csce-315-db.engr....
The main task of the code is to retrieve menu items from a database, process their ingredients, and render them in a template. It fetches menu data, converts item names to a list, retrieves ingredient-smoothie mappings, and associates ingredients with each smoothie. The processed data, including names, prices, and ingr...
def get_menu_items(): """ Summary or Description of the Function returns server.html, displays all menu items, ingredients, price, and gives user a place to enter the quantity they want to order 1) Select all products from the table 2) Fetch the data 3) close the cursor and connection 4) co...
def smalldeleteArreas(img,diagnostics = False): (numLabels, labels, stats, centroids) = cv2.connectedComponentsWithStats(img) for i in range(1, numLabels): if stats[i, cv2.CC_STAT_AREA] < PARAMS["MIN_ROADBED_AREA"]: labels[labels == i] = 0 result = (labels > 0).astype("uint8") ...
The main task of this code is to process roadbed and lane marking binary masks to detect and fit polynomial curves to lane boundaries. It first cleans the roadbed mask, extracts left/right road edges, and uses a sliding window to fit a polynomial to lane markings. The function returns fitted parameters, success flags, ...
def simple_test(mask_mark_bin, mask_roadbed_bin ,visualisation = False,diagnostics = False): binary_roadbed = smalldeleteArreas(mask_roadbed_bin,diagnostics= diagnostics) cache = [collections.deque(maxlen = PARAMS['MAX_CACHE_LEN']), collections.deque(maxlen = PARAMS['MAX_CACHE_LEN'])] l_suc,out,l_r...
def _get_name(self, name, scopes=None): """Returns a name qualified by `name_scopes`.""" if scopes is None: scopes = self._scopes scope_strings = [] for scope in scopes: if self._is_name_scope(scope): scope_strings.append(scope) elif s...
The code retrieves the current value of a hyperparameter, considering conditional scopes and activation status. It first checks if the parameter exists directly in `self.values` and returns it if conditions are active. If not, it searches for matching parameters by removing conditional scopes, checking for active condi...
def get(self, name): """Return the current value of this HyperParameter.""" # Most common case: not attempting to access a conditional parent # or conditional child. full_name = self._get_name(name) if full_name in self.values: if self._conditions_are_active(): ...
def _check_name_is_valid(self, name): if '/' in name or '=' in name or ',' in name: raise ValueError( '`HyperParameter` names cannot contain "/", "=" or "," ' 'characters.') for scope in self._scopes[::-1]: if self._is_conditional_scope(scope): ...
This function retrieves or registers a value associated with a given name, checking validity and existing entries. If the name already exists and overwrite is False, it returns the existing value; otherwise, it registers a new one. It conditionally returns the value if active conditions are met, otherwise returns None ...
def _retrieve_helper(self, name, type, config, overwrite=False): self._check_name_is_valid(name) full_name = self._get_name(name) if full_name in self.values and not overwrite: # TODO: type compatibility check, # or name collision check. retrieved_value = sel...
def _add_validation_errors(doc): ''' >>> from pprint import pprint >>> doc = {'entity_type': 'JUST WRONG'} >>> try: ... _add_validation_errors(doc) ... except FileNotFoundError as e: ... assert 'just wrong.schema.yaml' in str(e) >>> doc = {'entity_type': 'dataset'} >>> _add...
The code transforms a complex input document by mapping fields to standardized values, adding derived data (e.g., ancestor/descendant counts, processed metadata), and handling errors during translation. It cleans, validates, and structures the document for downstream use, while logging progress and including metadata a...
def transform(doc, batch_id='unspecified'): ''' >>> from pprint import pprint >>> transformed = transform({ ... 'entity_type': 'dataset', ... 'status': 'New', ... 'group_name': 'EXT - Outside HuBMAP', ... 'origin_sample': { ... 'organ': 'LY' ... }, ... 'c...
def request_json_required(request): if not request.is_json: bad_request_error("A JSON body and appropriate Content-Type header are required") def get_target_index(request, index_without_prefix): # Case #1 and #2 target_index = INDICES['indices'][index_without_prefix]['public'] # Keys in...
The main task of the code is to handle a search request without an index parameter by using a predefined default index. It constructs the corresponding Elasticsearch URL, executes a search query against the default index, and returns the resulting JSON data. The function relies on helper functions to validate input, de...
def search(): # Always expect a json body request_json_required(request) logger.info("======search with no index provided======") logger.info ("default_index: " + DEFAULT_INDEX_WITHOUT_PREFIX) # Determine the target real index in Elasticsearch to be searched against # Use the DEFAULT_INDEX...
def request_json_required(request): if not request.is_json: bad_request_error("A JSON body and appropriate Content-Type header are required") def validate_index(index_without_prefix): separator = ',' #indices = get_filtered_indices() indices = INDICES['indices'].keys() if index_without_pref...
The function `search_by_index` processes a search request by validating the provided index, determining the corresponding Elasticsearch index and URL, and executing a search query against Elasticsearch, returning the results as a JSON string.
def search_by_index(index_without_prefix): # Always expect a json body request_json_required(request) # Make sure the requested index in URL is valid validate_index(index_without_prefix) logger.info("======requested index_without_prefix======") logger.info(index_without_prefix) # Dete...
def request_json_required(request): if not request.is_json: bad_request_error("A JSON body and appropriate Content-Type header are required") def get_target_index(request, index_without_prefix): # Case #1 and #2 target_index = INDICES['indices'][index_without_prefix]['public'] # Keys in...
The function processes a count request by determining the target Elasticsearch index, retrieving its URL, and executing a count query, returning the result as a JSON string.
def count(): # Always expect a json body request_json_required(request) logger.info("======count with no index provided======") # Determine the target real index in Elasticsearch to be searched against target_index = get_target_index(request, DEFAULT_INDEX_WITHOUT_PREFIX) # get URL for t...
def request_json_required(request): if not request.is_json: bad_request_error("A JSON body and appropriate Content-Type header are required") def validate_index(index_without_prefix): separator = ',' #indices = get_filtered_indices() indices = INDICES['indices'].keys() if index_without_pref...
The main task of the code is to count documents in a specified Elasticsearch index. It validates the input index, retrieves its configured URL, and executes an Elasticsearch _count query, returning the result as a JSON string. The function ensures proper request formatting, index validation, and uses a configuration ma...
def count_by_index(index_without_prefix): # Always expect a json body request_json_required(request) # Make sure the requested index in URL is valid validate_index(index_without_prefix) logger.info("======requested index_without_prefix======") logger.info(index_without_prefix) # Deter...
def get_user_token(request_headers, admin_access_required = False): # Get user token from Authorization header # getAuthorizationTokens() also handles MAuthorization header but we are not using that here try: user_token = auth_helper_instance.getAuthorizationTokens(request_headers) except Excep...
The main task of the code is to initiate the reindexing of a document identified by a UUID in the background using a separate thread. It retrieves a user token, initializes an indexer, and starts a thread to execute the reindex operation. The function logs progress, handles exceptions, and returns a 202 "Accepted" resp...
def reindex(uuid): # Reindex individual document doesn't require the token to belong # to the HuBMAP-Data-Admin group # since this is being used by entity-api and ingest-api too token = get_user_token(request.headers) try: indexer = init_indexer(token) threading.Thread(target=index...
def get_user_token(request_headers, admin_access_required = False): # Get user token from Authorization header # getAuthorizationTokens() also handles MAuthorization header but we are not using that here try: user_token = auth_helper_instance.getAuthorizationTokens(request_headers) except Excep...
The function `reindex_all` triggers a live reindex of all documents in a background thread, requiring an admin token for authorization. It initializes an indexer, spawns a thread to execute `reindex_all_uuids`, logs progress, and returns a 202 status indicating the request was accepted. Errors are logged and handled wi...
def reindex_all(): # The token needs to belong to the HuBMAP-Data-Admin group # to be able to trigger a live reindex for all documents token = get_user_token(request.headers, admin_access_required = True) saved_request = request.headers logger.debug(saved_request) try: indexer = init_ind...
def get_uuids_by_entity_type(entity_type, token): entity_type = entity_type.lower() request_headers = create_request_headers_for_auth(token) # Use different entity-api endpoint for Collection if entity_type == 'collection': #url = app.config['ENTITY_API_URL'] + "/collections?property=uuid" ...
The main task of the code is to synchronize Elasticsearch indexes with Neo4j data by reindexing entities (donors, samples, datasets, etc.) and removing outdated entries. It fetches UUIDs from Neo4j, compares them with Elasticsearch indices, deletes orphaned entries, and performs concurrent reindexing of entities using ...
def reindex_all_uuids(indexer, token): with app.app_context(): try: logger.info("############# Reindex Live Started #############") start = time.time() # Make calls to entity-api to get a list of uuids for each entity type donor_uuids_list = get_u...
def get_entity(self, uuid): url = self.entity_api_url + "/entities/" + uuid response = requests.get(url, headers = self.request_headers, verify = False) if response.status_code != 200: # See if this uuid is a public Collection instead before exiting try: ...
The code generates a structured document by enriching an entity with its ancestors, descendants, donor information, and origin/sample details. It retrieves related entities via API calls, identifies donors, processes hierarchical relationships, renames keys, and adds calculated fields. For datasets, it traces the sourc...
def generate_doc(self, entity, return_type): try: uuid = entity['uuid'] if entity['entity_type'] != 'Upload': ancestors = [] descendants = [] ancestor_ids = [] descendant_ids = [] immediate_ancestors = [] ...
def generate_doc(self, entity, return_type): try: uuid = entity['uuid'] if entity['entity_type'] != 'Upload': ancestors = [] descendants = [] ancestor_ids = [] descendant_ids = [] immediate_ancestors = [] ...
The main task of the code is to update or insert an entity into Elasticsearch indices based on its type. For 'Upload' entities, it targets a specific index, deleting the old entry and writing the new one. For other entities, it removes the entity from all public indices, then writes transformed (or raw) versions to bot...
def update_index(self, node): try: org_node = copy.deepcopy(node) doc = self.generate_doc(node, 'json') # Handle Upload differently by only updating it in the hm_consortium_entities index if node['entity_type'] == 'Upload': target_index = 'hm_con...
def get_public_collection(self, uuid): # The entity-api returns public collection with a list of connected public/published datasets, for either # - a valid token but not in HuBMAP-Read group or # - no token at all # Here we do NOT send over the token url = self.entity_api_url ...
This function indexes a public collection into Elasticsearch by fetching it via an API, adding datasets, renaming keys, and calculating fields. It writes transformed data to both public and private indices, deleting existing entries if reindexing is enabled. The process ensures up-to-date indexing for search and data m...
def index_public_collection(self, uuid, reindex = False): logger.debug(f"Reindex public Collection with uuid: {uuid}") # The entity-api returns public collection with a list of connected public/published datasets, for either # - a valid token but not in HuBMAP-Read group or # - no tok...
def get_entity(self, uuid): url = self.entity_api_url + "/entities/" + uuid response = requests.get(url, headers = self.request_headers, verify = False) if response.status_code != 200: # See if this uuid is a public Collection instead before exiting try: ...
This function handles uploading or re-uploading an entity document to a specific Elasticsearch index. It deletes existing data if reindexing, retrieves/upload entity details, processes datasets, renames keys, adds calculated fields, then writes/updates the document in the 'hm_consortium_entities' private index without ...
def index_upload(self, uuid, reindex = False): logger.debug(f"Reindex Upload with uuid: {uuid}") # Only add uploads to the hm_consortium_entities index (private index of the default) default_private_index = self.INDICES['indices'][self.DEFAULT_INDEX_WITHOUT_PREFIX]['private'] # Delete ...
def is_selected(self, scenario_name, leak_config_name=None): """ Helper to check, whether a config is selected using the "--selection" command line argument. If no "--selection" is given, always return True. :param scenario_name: The name of the scenario :param leak_config_name...
The main task of the code is to generate simulation jobs by iterating through scenarios and configurations, validating water networks, estimating memory usage, writing configuration files, and dynamically adjusting the number of threads based on memory constraints to ensure efficient resource utilization.
def create_job_list_and_write_configs(self): """ Iterates through the entire config and (re)writes all neccesary config files and creates simulation jobs. """ if verbose: print('Adding simulation jobs...') # Initialize job list self.job_list = [] # Keep...
def create_hole(points, triangles, hole): kept_triangles = [] removed_vertices = set() # Find the points and triangles to remove for i in range(len(triangles)): simplex = triangles[i] assert len(simplex) == 3 xs = points[simplex] remove_triangle = False for j in...
The main task of the code is to generate a synthetic 2D flow dataset by creating a Delaunay triangulated mesh with a hole, constructing a graph from the triangulation, computing topological features (Hodge Laplacian eigenvectors), and returning the graph, eigenvectors, trajectories, and labels for analysis or machine l...
def load_flow_dataset(num_points=1000, num_train=1000, num_test=1000, k=3): points = np.random.uniform(low=-0.05, high=1.05, size=(num_points, 2)) triangulation = Delaunay(points) for i in range(len(points)): assert np.sum(triangulation.simplices == i) > 0 hole = np.array([[0.4, 0.4], [0.6, 0....
def get_ngram_frequency(self, filename): ngram_frequency = {} file = open(filename, 'r') reader = csv.reader(file) headerRead = False for key, value in reader: if headerRead == False: headerRead = True continue ...
The code implements a genetic algorithm to decrypt ciphertext using n-gram frequency analysis. It initializes a population of potential keys, evaluates their fitness based on precomputed bigram/trigram frequencies, applies elitism and crossover to evolve the population, and terminates when fitness stagnates. The best k...
def solve(self, ciphertext = ''): # Defining ciphertext self.ciphertext = ciphertext # Checking if ciphertext is valid if self.ciphertext == '': message = ( '\n(GeneticSolver) Ciphertext invalid. Use solve() as such:\n' '\tsolver = Gen...
def paired_hist(x_upper, x_lower, histtype='stepfilled', paired_colors=None, **kwargs): """Wrapper for weighted_hist() that takes two arrays of data and plots paired histograms on a mirrored y-axis. **kwargs passed to weighted_hist(). Args: x_upper (array-like): data to be plotted on upper half of...
This function generates paired histograms to compare the distribution of 'error_rad' values between two datasets (data_upper and data_lower) for each unique 'set_size'. It verifies both datasets share identical set sizes, creates subplots for each size, and plots histograms side-by-side using 'paired_hist'. The output ...
def plot_paired_error_by_set_size(data_upper, data_lower, bins=90, histtype='stepfilled', figsize=(10, 3), linewidth=0, **kwargs): """Plots paired histograms of report error for each set size in provided dataframes. Args: data_upper (pandas.DataFrame): Dataframe cont...
def paired_hist(x_upper, x_lower, histtype='stepfilled', paired_colors=None, **kwargs): """Wrapper for weighted_hist() that takes two arrays of data and plots paired histograms on a mirrored y-axis. **kwargs passed to weighted_hist(). Args: x_upper (array-like): data to be plotted on upper half of...
The function plots paired histograms comparing error distributions from two datasets (`data_upper` and `data_lower`) for each response, ensuring they share the same set size. It generates subplots for each response, visualizing error_rad values using `paired_hist`, and returns the figure and axes for further customizat...
def plot_paired_error_by_response(data_upper, data_lower, bins=90, histtype='stepfilled', figsize=(10, 3), linewidth=0, subplot_fill=None, **kwargs): """Plots paired histograms of report error for each response in provided dataframes. Args: data_upper (pandas.DataFra...
def paired_hist(x_upper, x_lower, histtype='stepfilled', paired_colors=None, **kwargs): """Wrapper for weighted_hist() that takes two arrays of data and plots paired histograms on a mirrored y-axis. **kwargs passed to weighted_hist(). Args: x_upper (array-like): data to be plotted on upper half of...
The function `plot_paired_relative_distance` generates paired histograms comparing the relative angular distance between a reference response (default: 1) and all other responses in two datasets (`data_upper` and `data_lower`). It calculates relative distances using the specified variable (`'reported'` or `'presented'`...
def plot_paired_relative_distance(data_upper, data_lower, ref_response=1, var='reported', bins=90, histtype='stepfilled', figsize=(10, 3), linewidth=0, truncate_comparisons=False, **kwargs): """Plots paired histograms of relative distance to ref_...
def generate_single_cam(self, points, pc_for_project, pointsensor_sd, cam_sd): image_filename = osp.basename(cam_sd['filename']) instance_filename = 'instance_' + image_filename.replace('jpg', 'npz') instance_image = np.load(osp.join(self.cfg.mask_root, cam_sd['channel'], instance_filename))['da...
The main task of the code is to generate semantic and instance segmentation labels for LiDAR point cloud data by fusing multi-view camera projections. It processes each camera's view, projects points onto 2D images, extracts semantic/instance labels, merges them across views, refines results via SAR processing, and out...
def generate(self, sample_idx): my_sample = self.nusc.sample[sample_idx] pointsensor_token = my_sample['data']['LIDAR_TOP'] pointsensor = self.nusc.get('sample_data', pointsensor_token) pc = utils.load_pointcloud(self.nusc, pointsensor) points = torch.tensor(pc.points[:3, :].T) ...
def _cprmod(self, a, b): res = a % b if (res < 0): res = res + b return res def _NL(self, rlat): # A.1.7.2.d (page 9) NZ = 15 return np.floor( 2 * np.pi / (np.arccos( 1 - (1 - np.cos( np.pi / (2 * NZ )) ) ...
This function decodes CPR (Compact Position Reporting) data to calculate a plane's geographic position (latitude, longitude). It processes latitude and longitude values from even/odd packets based on timestamps, adjusts for 360° wrap-around, and computes corrected coordinates using modular arithmetic and predefined CPR...
def _decode_CPR(self, plane): AirDlat0 = 360.0 / 60 AirDlat1 = 360.0 / 59 lat0 = plane['lat0'] lat1 = plane['lat1'] lon0 = plane['lon0'] lon1 = plane['lon1'] j = np.floor(((59*lat0 - 60*lat1) / 131072) + 0.5) rlat0 = ...
def _message_mode(self, msgType): if ( msgType == 16 or msgType == 17 or msgType == 19 or msgType == 20 or msgType == 21): return adsb.MSG_BITS else: return adsb.SHORT_MSG_BITS def _crc(self,msg,bits,trimmed=False): for i in range(bits - len(adsb.GENERATOR)): ...
The main task of the code is to decode ADS-B (Automatic Dependent Surveillance-Broadcast) messages from aircraft data, extracting critical information such as ICAO addresses, flight numbers, geographic coordinates (latitude/longitude), and aircraft heading. It processes bitstreams to validate CRC, identify message type...
def _decode(self): for msg,msgBits in zip(self.bytes,self.bits): # Bits 1-5 are the downlink format df = int(''.join(map(str, msgBits[0:5])), 2) # Bits 6-8 are the capability ca = int(''.join(map(str, msgBits[5:8])), 2) msgLen = self._message_mode(df) ...
def _detect_to_bit(self): for dIdx,msg in enumerate(self.detects): for sIdx,samp in enumerate(msg[adsb.PREAM_LEN:-1:2]): # 2 samples per bit # If sample 1 is > than sample 2, then 1 - else 0 if samp > msg[adsb.PREAM_LEN + sIdx * 2 + 1]: ...
The code's main task is to demodulate a signal by converting detected signals into bits via `_detect_to_bit()`, grouping bits into bytes with `_bit_to_byte()`, and finally decoding the byte data using `_decode()`. This process transforms raw signal detections into interpretable information.
def demod(self): self._detect_to_bit() self._bit_to_byte() self._decode()
def authenticate(self): """Authentication Function for tweet_it class""" try: self.api.verify_credentials() return True except ConnectionRefusedError as e: return False def good_evening_tweet(self): """Good Evening Tweet Function""" day,month_n...
The main task of the code is to automate scheduled social media interactions by posting tweets and quotes at predefined intervals. After authenticating, the bot runs in a loop, posting "good evening" tweets, programming quotes, motivational quotes, "good night" messages, "good morning" tweets, and "good afternoon" upda...
def run(self): """Main function: use run function for starting Bot""" if(self.authenticate()): while True: # it can be change according to your preference self.good_evening_tweet() time.sleep(60*30) self.programming_quotes() ...
def cascade(self, board, move, player): board = board.copy() marked = set() for dir in range(8): cursor = move tile = board[IX(cursor[0], cursor[1])] # initialize possible = set() while True: # move the c...
This function applies a move to the game board if valid. It updates the board state, player turn, and checks for terminal conditions. If the move is invalid or the cascade operation fails, it returns False. Otherwise, it updates the board, player, and returns True.
def change_board(self, move): if move not in self.moves: raise NameError("move is not valid 147") p = self.c_player c = self.cascade(self.board, move, p) if c[1] > 0: self.board = c[0] self.board[IX(move[0], move[1])] = p self.update_moves...
def get_file_name(url): '''Get the name of the json file that was saved for a particular url''' file = '-'.join(url.split('/')[2:]) return './{}.json'.format(file) def set_params(kwargs, params_from_file): '''Set commandline parameters provided with the -f switch. If a parameter is provided it is u...
The main task of the code is to execute a database enumeration process for MySQL, either by loading pre-existing parameters from a JSON file or initializing new ones. It checks if a file exists, reads its data, configures a MYSQLENUM instance with parameters, populates database rows, and displays results. If no file is...
def start(*args,**kwargs): '''Main program loop''' file_read = kwargs['file_read'] args_init = dict(kwargs) del args_init['file_read'] file_name = get_file_name(kwargs['target_url']) if file_read: if os.path.isfile(file_name): with open(file_name, 'r') as f...
def select_table(self): '''Prompt for selecting a table to enumerate it's rows''' print(render_tables(self.target)) tables = self.target.DB['tables'] total_tables = len(self.target.DB['tables']) while True: table_index = int(self.get_input("Selec...
This function prompts the user to specify the number of rows to enumerate for a selected table-column pair, ensuring the input is within valid bounds. It checks if a table/column is selected, retrieves row counts, validates user input, and sets the enumeration limit.
def select_row_limit(self): '''Prompt for selecting the number of rows to enumerate for the selected table.column. Some tables may have thousands of rows. Enumerating limited number of rows is usually enough for most requirements.''' if self.table.get('selected') is None: self.selec...
def select_table(self): '''Prompt for selecting a table to enumerate it's rows''' print(render_tables(self.target)) tables = self.target.DB['tables'] total_tables = len(self.target.DB['tables']) while True: table_index = int(self.get_input("Selec...
The function prompts the user to select a long row from a table by enumerating its contents, ensuring valid input, and returns the chosen row after retrieving it from the database.
def select_long_row(self): '''Prompt for selecting the long row, to enumerate it's complete contents''' if self.table.get('selected') is None: self.select_table() if self.col.get('selected') is None: self.select_col() table = self.table['selected'] ...
def get_row_len(self, row, table, col): '''Retrieve the length of characters in a particular row from a table.column''' self.construct_vuln_field(self.get_row_len_pl.format(table_name=table,col_name=col)+self.limits.replace('~num~',row)) enum_logger.info("Querying length of row no. '{}'...
This function retrieves excessively long row data from a MySQL table by splitting it into manageable parts due to the updatexml length limitation. It calculates required iterations based on a buffer size, concatenates partial results, and appends any remaining characters to reconstruct the full row content.
def get_long_row_content(self, row, table, col): '''Some row contents retrieved are longer than the maximum length of the error message displayed by updatexml part of the mysql query. This function retrieves the entire contents part by part and then returns the complete row contents after joining them''' ...
def get_params(self): '''Construct and return a dictionary of the command line parameters provided''' params = {} params['target_url'] = self.target_url params['data'] = self.data params['request_type'] = self.request_type params['vuln_field'] = self.vuln_field ...
The code's main task is to construct a dictionary (`self.DB`) containing enumerated data from a target system. It records the current date, retrieves parameters, system info, and enumerates database tables, storing these as key-value pairs in `self.DB` for structured data collection and analysis.
def enumerate(self): '''Construct a dictionary with the various data enumerated from the target''' self.DB['date'] = str(datetime.datetime.now()) self.DB['params'] = self.get_params() self.DB['info'] = self.get_info() self.DB['tables'] = self.enumerate_tables()
def select_table(self): '''Prompt for selecting a table to enumerate it's rows''' print(render_tables(self.target)) tables = self.target.DB['tables'] total_tables = len(self.target.DB['tables']) while True: table_index = int(self.get_input("Selec...
The code's main task is to execute three selection methods (`select_table`, `select_col`, `select_row_limit`) to gather user inputs for table, column, and row limit, then return a list containing the selected table and column.
def show_prompts(self): self.select_table() self.select_col() self.select_row_limit() return [self.table, self.col]
def get_controller(self): if self._stopped is False: return self._controller else: return None def get_sensors(self): return self._sensors def handleevent(self, actionevent): motor = self.get_motorengine() if actionevent["action"] == "forward": ...
The main task of the code is to control a car's movement using sensor input and controller commands. It continuously checks an ultrasonic sensor (HCRSR04) for obstacles within 30 cm, triggering a "move back and steer right" action if detected. Otherwise, it uses the controller's input to determine actions. The car acce...
def _drive(self): self._stopped = False controller = self.get_controller() sensors = self.get_sensors() if controller.get_device(): while True and self._stopped is False: if sensors and sensors.has_sensor("HCRSR04"): HCRS04 = sensors.get_se...
def get_default_speed(self): return self._default_speed def car_move_direction(self, motors, speed, forwarddirection: bool, duration: int = 0): try: for name in motors: self.set_motor_direction(name, forwarddirection) self.set_motor_control_speed(name, speed) ...
This function controls a car's forward movement by setting its speed (using a default if unspecified) and triggering motion via the car_move_direction method, which applies the specified speed to the motors in the forward direction for a given duration.
def car_move_forwards(self, speed: int = None, duration: int = 0): if speed is None: speed = self.get_default_speed() self._current_speed = speed self.car_move_direction(self.get_motors(), speed, True, duration)
def get_default_speed(self): return self._default_speed def car_move_direction(self, motors, speed, forwarddirection: bool, duration: int = 0): try: for name in motors: self.set_motor_direction(name, forwarddirection) self.set_motor_control_speed(name, speed) ...
This function moves a car backward at a specified speed for a given duration. If no speed is provided, it uses a default value. It sets the current speed and directs the car's motors to move in reverse, utilizing the `car_move_direction` method with parameters for motors, speed, backward direction (False), and duration...
def car_move_backwards(self, speed: int = None, duration: int = 0): if speed is None: speed = self.get_default_speed() self._current_speed = speed self.car_move_direction(self.get_motors(), speed, False, duration)
def pad_key(key): # pads the key using even parity calculations if len(key) == 56: split_key = [key[i: i+7] for i in range(0, len(key), 7)] for i in range(0, len(split_key)): bit_count = 0 for j in range(0, len(split_key[i])): if split_key[i][j] == "1": ...
This code initializes a cryptographic key for a block cipher algorithm. It pads the input key, applies a permutation (PC-1), splits the key into halves (C and D), and generates subkeys for each round using the halves and the specified mode (encryption/decryption). The subkeys are stored in a dictionary for use during t...
def __init__(self, key, mode): # instantiate store key and set mode self.original_key = key key = pad_key(key) self.key = key self.permute1() # permute key as PC-1 self.c = self.key[:int(len(self.key)/2)] self.d = self.key[int(len(self.key)/2):] self.round = 1 ...
def expand(text): # input text into an e-box result = shuffle('ebox', text) return result def xor(key, text): # XOR strings containing binary together result = "" text = text.zfill(len(key)) for k, t in zip(key,text): result += str(int(k) ^ int(t)) return result def substitute(inText): #...
This function performs one round of DES encryption/decryption. It expands the right text, XORs it with a subkey (selected based on mode), applies S-box substitution, P-box permutation, and XORs the result with the left text. The round counter increments, and left/right texts are swapped for the next round.
def round_fun(self, left_text, right_text): # a round of the des encryption e_text = expand(right_text) # use the ebox if self.mode == "encrypt": result = xor(self.subkeys[str(self.round)], e_text) else: result = xor(self.subkeys[str(17-self.round)], e_text) resul...
def log(message, level='INFO'): print('[{}] [{}] | {}'.format(dt.now(), level, message)) def fetch_new_data(): latest_id = None try: with open(METADATA_FILE) as fopen: metadata = json.loads(fopen.read()) latest_id = metadata['latest_id'] log('latest_id: {}'.format(lat...
The main task of the code is to fetch new data, convert it into a DataFrame, check for its existence, log the number of new records if present, and cache the data along with the latest ID.
def pull_data(): log('pulling data...') (data, newest_id) = fetch_new_data() df = data_to_frame(data) if df is None: log('no new data') return else: log('{} new records'.format(len(df))) cache_data(df, newest_id)
def __repair(self, knapsack: List[bool], elements: List[Element], capacity: int): """ Repair knapsack Arguments: knapsack(List[bool]): list of boolean values which define if element will be pack into knapsack elements(List[Element]): list of elements to pack to knapsack ...
This code implements an evolutionary algorithm to solve the knapsack problem by iteratively generating, repairing, and optimizing populations of knapsack solutions over multiple epochs. It uses probabilities for mutation, inheritance, and negation to evolve better solutions, ultimately returning the best knapsack confi...
def run(self, elements: list, capacity: int, epochs: int = 100, M: int = None, c: float = None, i: float = None, p: float = None): """ Run algorithm for given dataset Arguments: elements(List[Element]): list of elements to pack to knapsack capacity(int): maxi...
def forward(self, y, mask): num_vectors = y.size(0) noise = self.get_noise(num_vectors, mask) samples = self.generator(torch.cat([y, noise], dim=1)) samples = self.readd_measures(samples, y, mask) return samples def adversarial_loss_generator(self, y, gens): fake_pred = t...
The code implements a training step for a GAN, alternating between training the generator and discriminator. For the generator (optimizer_idx=1), it generates reconstructions, computes adversarial and L1 losses, and logs the generator loss. For the discriminator (optimizer_idx=0), it calculates adversarial loss, gradie...
def training_step(self, batch, batch_idx, optimizer_idx): y, x, mask, mean, std, _, _, _ = batch # train generator if optimizer_idx == 1: gens = torch.zeros( size=(y.size(0), self.args.num_z_train, self.args.in_chans, self.args.im_size, self.args.im_size), ...
def get_updates(self, last_activity_date=""): try: url = "https://api.gotinder.com" + '/updates' r = requests.post(url, headers=headers, data=json.dumps({"last_activity_date": last_activity_date})) ...
The code retrieves and compiles detailed information about user matches, including personal data, interaction metrics, and media, into a structured dictionary. It iterates through match updates, extracts fields like name, ID, message count, photos, age, and distance, handles exceptions, and returns the organized match ...
def get_match_info(self): matches = self.get_updates()['matches'] now = datetime.utcnow() match_info = {} for match in matches[:len(matches)]: try: person = match['person'] person_id = person['_id'] m...
def bucket_round(questions): buckets = {} for index, row in questions.iterrows(): buckets.setdefault(get_category(row), []).append(get_question(row)) # Energy questions should be sorted by subcategory; then when pairing buckets, subcategories are paired together if Category.Energy in buckets: ...
The code generates a shuffled list of question pairs for a specific round by filtering questions, grouping them into buckets, pairing tossups with bonuses, chunking them, and shuffling to avoid category repeats across chunks.
def gen_round(question_df, round_num): # Returns a list of QuestionPairs round_qs = question_df.loc[question_df[ROUND_NUM] == round_num] tossup_buckets = bucket_round(round_qs.loc[round_qs[TYPE] == TOSSUP]) bonus_buckets = bucket_round(round_qs.loc[round_qs[TYPE] == BONUS]) paired_qs = pair_buckets(tos...
def drawNextLine(self, line): compressedLine = self.removeLineSpaces(line) return self.drawLineChunks(compressedLine, EMPTY_STRING) def accumulateNextLine(self, conwaySuite, nextLine): return self.prependSuite(conwaySuite) + nextLine
The code recursively generates a sequence by iteratively creating the next line from the current one and accumulating it into the 'conwaySuite' structure, repeating this process 'deep' times until the depth reaches zero.
def drawSuite(self, line, deep, conwaySuite): if deep == 0: return conwaySuite nextLine = self.drawNextLine(line) return self.drawSuite(nextLine, deep - 1, self.accumulateNextLine(conwaySuite, nextLine))
def _kde2D( x, y, bandwidth, gridPadding, binSize, **kwargs ): gridMin = -gridPadding gridMax = 1 + gridPadding bins = binSize * 1j * (1 + 2 * gridPadding) (xx, yy) = np.mgrid[gridMin:gridMax:bins, gridMin:gridMax:bins] xy_sample = np.vstack([yy.ravel(), xx.ravel()]).T ...
The function _getClusterContour computes a contour representation of a cluster by first calculating 2D kernel density estimates (KDE) from input points, determining an iso-level threshold for density, and then generating a contour map using these values. It takes cluster points, bandwidth, grid padding, and bin size as...
def _getClusterContour( clusterPoints, bandwidth, gridPadding, binSize, ): kdeValues = _kde2D(clusterPoints[:, 0], clusterPoints[:, 1], bandwidth, gridPadding, binSize) iso = _getIsoValue(clusterPoints, kdeValues, gridPadding, 100) return _getContour(kdeValues, is...
def getRREF(self, addition: list = None) -> "Matrix": """ Computes the Row Reduced Echelon Form of the self matrix Parameters ---------- addition: list, optional Any additional matrices/lists added to the right side of the self matrix. The integrated matr...
This function computes the column space basis of a matrix by identifying pivot columns in its Reduced Row Echelon Form (RREF). It retrieves the original columns corresponding to these pivot positions, forming a basis for the column space.
def getColBasis(self): """ Returns the columns space basis for self-matrix. Returns ------- col_basis: list List of column space basis. """ rref = self.getRREF() pivots = [] for row in rref: i = -1 ent = 0 ...
def getRREF(self, addition: list = None) -> "Matrix": """ Computes the Row Reduced Echelon Form of the self matrix Parameters ---------- addition: list, optional Any additional matrices/lists added to the right side of the self matrix. The integrated matr...
This method checks if a matrix is linearly independent by verifying that its Reduced Row Echelon Form (RREF) has a pivot in every column. It first ensures the RREF is computed, checks if rows are fewer than columns (guaranteeing dependency), then scans each column for a non-zero pivot with all other entries in the colu...
def isLinIndependent(self) -> bool: """ Identifies if the self-matrix is linearly independent or not. Returns ------- bool True if the self matrix is linearly independent and False if it is linearly dependent. """ if self.rref_matrix is None: ...
def upload_rule_to_ipfs(rg_file: str, obj_metadata: dict) -> dict: if IPFS_KEY is None: raise Exception("IPFS_KEY not set") try: rule, info = parse_rg_file(rg_file.decode('utf-8')) obj_metadata["rule"] = rule obj_metadata["info"] = info.split("\n") obj_metadata["name"] = ...
This Lambda function handles three HTTP POST endpoints: uploading security rules to IPFS, uploading code snippets to IPFS with language mapping, and analyzing code for buffer overflow vulnerabilities using regex scanning. It decodes base64 payloads, interacts with IPFS for storage, and returns analysis results or uploa...
def lambda_handler(event, context): # If the request is a POS to /upload-rule, then upload the rule to IPFS if event.get("requestContext").get('http').get("method") == 'POST' and event.get("requestContext").get('http').get("path") == '/upload-rule': # Get the rule from the body rule = event.get(...
def fix_json(json_str): print(">> Calling OPENAI for help") llm = ChatOpenAI(model_name="gpt-4", temperature=0.0) template = """ Fix the input json string to produce an output that has a valid json format. Only change things like the parenthesis, commas etc. json_input: \n{json_str}...
The code evaluates the accuracy of a language model's predictions against ground truth data by checking JSON validity, intent match, CPC name consistency, SPC count/accuracy, and variable assignment isomorphism/matching, returning a detailed metrics dictionary.
def evaluate(predicted, truth): """ Returns an evaluation json that contains various metrics input: strings obtained from the language model input: json of the ground truth """ item = {} item['truth'] = truth if isinstance(truth,str): try: item['truth'] = ast.literal...
def load_peft_model(peft_model_id, base_model_id): # Load the PEFT adapter into a model model = AutoModelForCausalLM.from_pretrained(peft_model_id, device_map="auto",load_in_4bit=True) # Load tokenizer tokenizer = AutoTokenizer.from_pretrained(base_model_id) return model, tokenizer def generate(prompt, model...
The code's main task is to run inference on a test dataset using PEFT models, generating predictions and evaluations. It loads appropriate models and datasets based on arguments, processes each item by generating outputs with a model, evaluates parsing results if applicable, and saves predictions to JSON files. The tas...
def main(args): # Load dataset print("\n>> LOADING DATASET") if not args.context: if "par" in args.type.lower(): model_names = PARSERS dataset_name = PARSING_DATA else: model_names = TRANSLATORS dataset_name = TRANSLATION_DATA else: ...
def xml_parser(self): root: et.Element = et.parse(self.xml_filepath).getroot() all_pages: et.ElementTree = root.findall('page') for page in all_pages: #populate title dict with id -> title title: str = page.find('title').text.strip().lower() id: int = int(page...
The code initializes a class to process XML data, extracting titles, documents, and words into dictionaries. It parses XML content, calculates term relevance scores, and computes PageRank values for linked documents, preparing data for analysis or ranking tasks.
def __init__(self, xml: str, title: str, docs: str, words: str): self.xml_filepath = xml self.titles_filepath = title self.docs_filepath = docs self.words_filepath = words self.n = 0 self.title_dict = {} self.docs_dict = {} self.words_dict = {} ...
def print(self, states=None): if (states == None): str = "" for i in range(self.n - 1, -1, -1): for j in range(self.m): if (i, j) == self.position: str += bcolors.OKBLUE + "X " + bcolors.ENDC elif (i, j) in s...
This code implements Q-learning to solve a maze problem. It initializes a Q-table, runs multiple episodes, and updates Q-values using the Bellman equation. Each episode navigates the maze, tracks cumulative rewards, and records states/actions. After training, it prints the average score of the last 100 episodes, the se...
def solve(self, lr, y, num_episodes): """ lr: learning_reate y: Gamma num_episodes: number of total episodes """ num_states = self.n * self.m num_actions = 4 Q = np.zeros((num_states, num_actions)) cumul_reward_list = [] actions_list = [] ...
def solveRelaxedModel(self): #Relax integer variables to continous variables self.relaxedModel = self.model.relax() var_ss = pd.Series(self.relaxedModel.getVars()) var_ss.apply(lambda x: x.setAttr('ub',GRB.INFINITY)) self.relaxedModel.optimize() def getDuals(self): return...
This function performs column generation for a vehicle routing problem using dynamic programming (DP) to iteratively generate and add routes (columns) to a relaxed model. It handles two DP modes ('ITER_M' and 'SIMUL_M'), computes dual prices, filters profitable routes, and updates the model until optimality. It logs it...
def runColumnsGeneration(self,_m_collections,_pricing_status=False, _check_dominance=True,_dominance_rule=None, _DP_ver=None,_time_limit=None,_filtering_mode=None, _bch_cond=None,_node_count_lab=None,_acc_flag=None): outer_dic...
def drawSplashScreen(app, canvas): introFontSize = 40 canvas.create_image(app.width/2, app.height/2, image=ImageTk.PhotoImage(app.splashScreen)) startButton = Button(app.width/2-75, app.height*0.57, 150, 50, 'start') creditsButton = Button(app.width/2-75, app.height*0.83, 150, 50, 'credits') setting...
The function `redrawAll` determines the current UI state (`app.currScreen`) and renders the appropriate screen (splash, game, credits, etc.) on the canvas. In the game state, it draws the game screen, pauses if needed, and renders rats. It orchestrates visual updates based on the application's state, ensuring the corre...
def redrawAll(app, canvas): if app.currScreen == 'splash': drawSplashScreen(app, canvas) elif app.currScreen == 'game': drawGameScreen(app, canvas) if app.paused == True: drawPauseScreen(app, canvas) drawRats(app, canvas) elif app.currScreen == 'credits': ...
def get_chat_filename(chat_name): out_directory = 'messages' os.makedirs(out_directory, exist_ok=True) return f'{out_directory}/{chat_name}.csv' def get_chat_id_filename(chat_name): out_directory = 'messages' os.makedirs(out_directory, exist_ok=True) return f'{out_directory}/{chat_name}.id.txt' ...
This code initializes a chatbot by downloading and processing chat data, creating a language stemmer, training a model, and loading it. It also optionally sets up an OpenAI client for GPT integration.
def __init__(self, chat_name, language, use_chat_gpt=True): chat_filename = get_chat_filename(chat_name) chat_id_filename = get_chat_id_filename(chat_name) model_filename = get_model_filename(chat_name) download_chat(chat_name, chat_filename, chat_id_filename) self.chat_id = rea...
def create_inode(self, name, path, inode_type, full_path=''): stat = self.get_stat(path) inode = Inode.create( node_type=int(inode_type), name=name, size=stat['size'], created_time=stat['created_time'], modified_time=stat['modified_time'], ...
This code indexes a directory's contents into a file system by creating inodes for files, directories, and symlinks. It checks if the directory is already indexed, prompts for a new name if needed, and ensures uniqueness. It traverses the directory tree, linking inodes with parent-child relationships, while handling er...
def index(self, path): if not os.path.isdir(path): raise ParameterException(F'{path} is not a directory') path = PurePath(os.path.abspath(path)) exist_index = Inode.select()\ .join(Directory, on=Directory.inode)\ .join(FullPath, on=(Directory.child == FullPa...
def print_separator(): term_width = shutil.get_terminal_size((50, 1)).columns print(f'{"".join(["-"] * term_width)}') def get_credetials(url): creds = CredentialCache() get_account(creds.old, url, "Old Account") get_account(creds.new, url, "New Account") return creds if creds.valid() else None ...
The code's main task is to interactively collect a Bitbucket URL, validate it, retrieve credentials and mapping data, and initiate account data migration using BitbucketMover, with optional avatar settings. It ensures URL validity through iterative prompts and prepares parameters for the migration process.
def main(): BITBUCKET_URL = None while not BITBUCKET_URL or not BitbucketMover.test_connection(BITBUCKET_URL): print_separator() BITBUCKET_URL = input('Specify Bitbucket URL: ') BITBUCKET_URL = BITBUCKET_URL[:-1] if BITBUCKET_URL.endswith('/') else BITBUCKET_URL credentials = get_c...
def get_private_repos(self, session=None): session = self.old if not session else session resp = session.get(f'users/{session.auth.user}/repos/') return [rjson['slug'] for rjson in resp.json()['values']] \ if resp.status_code in range(200, 300) else [] def set_private_repo_perm...
The function processes private repositories by adding a new user as a reader, copying permissions, and locking down the repository to prevent further changes, while skipping specified exceptions. It logs progress and errors, ensuring the new user has read access and the repo is secured post-transfer.
def _move_all_private(self, mapping, exceptions=[]): repos = self.get_private_repos() for repo in repos: if repo in exceptions: logger.debug('%s is in exceptions list. Skipping.', repo) continue logger.info('-------------------') logge...
def _reconfigure_avatars(self, set_avatar=True, gone_avatar=None): self._move_avatar() if set_avatar and gone_avatar: resp = self.set_avatar_png(gone_avatar, session=self.old) if resp.status_code in range(200, 300): logger.info("Configured deprecated avatar for ol...
This function migrates an account's data by reconfiguring avatars, relocating private data, updating reviewers, and transferring SSH keys. It handles avatar changes (adding/removing), maps data to a new structure, adjusts access permissions, and ensures secure key migration. The task focuses on comprehensive account da...
def move_account_data(self, set_avatar=True, gone_avatar=None, mapping=None): self._reconfigure_avatars(set_avatar=set_avatar, gone_avatar=gone_avatar) self._move_all_private(mapping) self._change_reviewers() self._move_ssh_keys()
def draw(self): """ draw the game""" self.display_letters() self.jumper.draw_parachute() print("\n\n^^^^^^^^") def do_inputs(self): """ Getting the letter of your guess""" guess = input("Guess a letter [a-z]: ") self.check_guess(guess) def check_game_status(self):...
The main task of the code is to run a game loop that continuously updates the game state by drawing the current state, processing user inputs, and checking the game's status while the game is running. This loop ensures real-time interaction and updates until the game stops.
def start_game(self): while self.running: self.draw() self.do_inputs() self.check_game_status()
def norm(v, axis=None): return np.sqrt(np.sum(v*v, axis=axis)) def qboxminus(q1, q2): return qlog(qmult(qinv(q2), q1)) def qboxplus(q, v): return qmult(q, qexp(v))
This code computes the geometric mean of a set of quaternions using an iterative optimization approach. It initializes a mean quaternion, then repeatedly adjusts it by averaging the box-minus differences between each input quaternion and the current mean, until the changes fall below a threshold. The result is a unit-n...
def meanOfQuat(q): n = float(q.shape[0]) mu = q[None,0,:] prev_mu = None iter = 0 while prev_mu is None or norm(qboxminus(mu, prev_mu)) > 1e-3: iter +=1 prev_mu = mu mu = qboxplus(mu, np.sum(qboxminus(q, mu), axis=0)[None,:]/n) assert np.abs(1.0 - norm(mu)) <= 1e03 re...