dependency
stringlengths
77
854k
docstring
stringlengths
0
4.39k
main
stringlengths
29
215k
def get_avg(): sum = 0 for count, i in enumerate(range(len(parse_json))): info = parse_json[i]['PriceWithTax'] sum += info avg = sum / count avg = round(avg, 4) return avg def get_current_price(): current_time = get_time() price_now = parse_json[current_time]['PriceWithTax'...
The main task of the code is to generate a JSON structure containing current and (if available) tomorrow's spot price data, including average, current, hourly prices, and affordability comparisons. It merges today's data with tomorrow's data when prices for tomorrow are revealed, then returns the combined JSON string w...
def create_json(): spot_price_json_today = { "avg" : get_avg(), "current" : get_current_price(), "hourly" : get_hourly_prices(), "cheaper_than_avg" : is_cheaper(), "prices_for_tomorrow": spot_price_tomorrow.prices_revealed() } if spot_price_tomorrow.prices_...
def report_event(self, message, is_success=False): add_event(name="WALA", message=message, is_success=is_success, op=WALAEventOperation.Provision) def report_not_ready(self, sub_status, description): status = ProvisionStatus(status="NotReady", subStatus=sub_status, ...
The code handles provisioning by copying ovf-env.xml, detecting protocols, and executing provisioning tasks if enabled. It skips if already provisioned, logs errors on failure, and reports readiness with SSH thumbprint upon success.
def run(self): #If provision is not enabled, return if not conf.get_provision_enabled(): logger.info("Provisioning is disabled. Skip.") return provisioned = os.path.join(conf.get_lib_dir(), "provisioned") if os.path.isfile(provisioned): return ...
def add_png_to_pdf(image_name, x_pos, y_pos, image_w, image_h): if os.path.exists(image_name): pdf.image(image_name, x_pos, y_pos, image_w, image_h) else: print("File not found:", image_name) print(f"{image_name} Added") def compile_default_report(): default_report_list = [['...
The main task of the code is to generate a customized PDF report by adding a logo, selecting content based on the `report_type` (Default/Church/Cup), and saving the output as a PDF file named with the sample ID and name. It uses global variables and conditional logic to dynamically compile report sections before export...
def generate_report(): global pdf pdf = FPDF() pdf.add_page() # Add Template Graphics HL_logo_path = template_dir + "HLchemprofbanner.png" HL_logo_w, HL_logo_h = 100, 20 HL_logo_x, HL_logo_y = 10, 10 add_png_to_pdf(HL_logo_path, HL_logo_x, HL_logo_y, HL_logo_w, HL_logo_h) #...
def cairo_add_svg_to_pdf(sample_id,graphic_type,input_w,input_h,pdf_x,pdf_y): print(sample_id,graphic_type,input_w,input_h,pdf_x,pdf_y) input_path = f'{sample_id}-{graphic_type}.svg' input_png = f'{sample_id}-{graphic_type}.png' if 'Template' in graphic_type: input_path = graphic_type in...
The code generates customized PDF reports (Cup, Profile, Flush) using FPDF, embedding logos, sample data, and visual elements like charts. It dynamically selects layouts, inserts images/tables based on report type and sample ID, then saves the output to a specified directory with structured naming.
def generate_report(report_type, save_dir, section_title, s): global pdf pdf = FPDF() pdf.add_page() # Add HL Logo HL_logo_path = f"{template_dir}/HL_transparent.png" pdf.image(HL_logo_path, 10, 9, 80, 20) # Add Sample ID Banner cairo_add_svg_to_pdf(sample_id,'sample_table_name_i...
def factor1(): k = 'rocp 21 day' #creates a list of the rocp 21 day df1 = rocp(k) #fills NaN values with row average df1.fillna(df1.mean(axis=1), inplace=True) rv = df1.sum(axis=1)/n rv.name = 'Factor 1' # t = r.columns[0] # r['Date'] = dict[r]['Date'] # x = x[['Date',t]] ret...
The main task of the code is to truncate the outputs of four functions (factor1 to factor4) using the specified 'truncate' parameter, which limits the number of rows shown in each result. The function collects these truncated results into a list and returns it.
def all(truncate =None): """ Parameters: truncate takes in the number of rows to show for result Output: """ rv = [factor1(),factor2(),factor3(),factor4()] rv1 = [] y = [x for x in dict.keys()] y = y[0] for x in rv: dict.keys() x = x.truncate(after = truncate) ...
def crop_or_pad_slice_to_size(slice, nx, ny): if len(slice.shape) == 3: stack = [slice[:,:,0], slice[:,:,1], slice[:,:,2]] RGB = [] else: stack = [slice] for i in range(len(stack)): img = stack[i] x, y = img.shape x_s =...
The `prepare_data` function processes medical DICOM images (segmented and raw) from specified input folders, generates masks using color-based segmentation, applies rotations, calculates ROI parameters (center, dimensions), and resizes/crops images to standardized dimensions. It then stores the processed data (images, ...
def prepare_data(input_folder, output_file, nx, ny, paz, angle): hdf5_file = h5py.File(output_file, "w") # 1: 'RV', 2: 'Myo', 3: 'LV' addrs = [] MASK = [] IMG_SEG = [] #img in uint8 con segmentazione IMG_RAW = [] #img in float senza segmentazione #IMG_CIR = [] #img in uint8 con ...
def get_weight_variable(shape, name=None, type='xavier_uniform', regularize=True, **kwargs): initialise_from_constant = False if type == 'xavier_uniform': initial = glorot_uniform() elif type == 'xavier_normal': initial = glorot_normal() elif type == 'he_normal': initial = he_no...
This function creates a standard 2D convolutional layer with customizable parameters including kernel size, number of filters, strides, activation function, and weight initialization. It initializes weights and biases, applies convolution and bias addition, executes the activation function, and adds TensorBoard summari...
def conv2D_layer(bottom, name, kernel_size=(3, 3), num_filters=32, strides=(1, 1), activation=tf.identity, padding="SAME", weight_init='he_normal', add_bias=True): ''' Standard...
def get_weight_variable(shape, name=None, type='xavier_uniform', regularize=True, **kwargs): initialise_from_constant = False if type == 'xavier_uniform': initial = glorot_uniform() elif type == 'xavier_normal': initial = glorot_normal() elif type == 'he_normal': initial = he_no...
This function implements a standard 3D convolutional layer with customizable parameters. It creates convolutional filters, applies 3D convolution to the input tensor, adds optional bias, applies activation, and generates TensorBoard summaries. The layer accepts inputs, kernel size, filter count, strides, and initializa...
def conv3D_layer(bottom, name, kernel_size=(3, 3, 3), num_filters=32, strides=(1, 1, 1), activation=tf.nn.relu, padding="SAME", weight_init='he_normal', add_bias=True): ''' Sta...
def get_weight_variable(shape, name=None, type='xavier_uniform', regularize=True, **kwargs): initialise_from_constant = False if type == 'xavier_uniform': initial = glorot_uniform() elif type == 'xavier_normal': initial = glorot_normal() elif type == 'he_normal': initial = he_no...
This function implements a 2D transpose convolution (deconvolution) layer to upscale input tensors by a factor of 2, applying customizable filters, strides, and activation functions. It dynamically computes output dimensions, initializes weights using He normal distribution, adds bias if specified, and integrates Tenso...
def deconv2D_layer(bottom, name, kernel_size=(4, 4), num_filters=32, strides=(2, 2), output_shape=None, activation=tf.nn.relu, padding="SAME", weight_init='he_normal', ...
def get_weight_variable(shape, name=None, type='xavier_uniform', regularize=True, **kwargs): initialise_from_constant = False if type == 'xavier_uniform': initial = glorot_uniform() elif type == 'xavier_normal': initial = glorot_normal() elif type == 'he_normal': initial = he_no...
This function implements a 3D transpose convolution (deconvolution) layer for upsampling. It takes an input tensor, applies a 3D transposed convolution with specified kernel size, filters, and strides, then adds bias (optional) and ReLU activation. The output shape is determined by input dimensions and strides, with op...
def deconv3D_layer(bottom, name, kernel_size=(4, 4, 4), num_filters=32, strides=(2, 2, 2), output_shape=None, activation=tf.nn.relu, padding="SAME", weight_init='he_nor...
def get_weight_variable(shape, name=None, type='xavier_uniform', regularize=True, **kwargs): initialise_from_constant = False if type == 'xavier_uniform': initial = glorot_uniform() elif type == 'xavier_normal': initial = glorot_normal() elif type == 'he_normal': initial = he_no...
This function implements a 2D dilated convolution layer using atrous convolution to expand the receptive field without downsampling. It initializes weights/biases, applies the dilation rate, padding, and activation function (ReLU by default), and adds TensorBoard summaries. The layer increases contextual awareness in n...
def conv2D_dilated_layer(bottom, name, kernel_size=(3, 3), num_filters=32, rate=1, activation=tf.nn.relu, padding="SAME", weight_init='he_normal'...
def batch_normalisation_layer(bottom, name, training): ''' Alternative wrapper for tensorflows own batch normalisation function. I had some issues with 3D convolutions when using this. The version below works with 3D convs as well. :param bottom: Input layer (should be before activation) :param name...
This code implements a DenseNet block where each layer's output is concatenated with the input, creating dense connections. It uses bottleneck layers with 1x1 and 3x3 convolutions, grows filters via `growth_rate`, and returns concatenated features with updated filter count. The block enhances feature reuse and gradient...
def dense_block(bottom, name, training, kernel_size=(3, 3), init_filt=128, growth_rate=32, strides=(1, 1), activation=tf.nn.relu, padding="SAME", weight_init='he_normal', ...
def batch_normalisation_layer(bottom, name, training): ''' Alternative wrapper for tensorflows own batch normalisation function. I had some issues with 3D convolutions when using this. The version below works with 3D convs as well. :param bottom: Input layer (should be before activation) :param name...
This code defines a transition layer in a neural network, primarily used in architectures like DenseNet. It reduces the number of feature maps via a 1x1 convolution with a compression factor (0.5) and applies optional pooling (avg/max) to downsample spatial dimensions. The layer includes batch normalization, activation...
def transition_layer(bottom, name, training, num_filters=32, activation=tf.nn.relu, weight_init='he_normal', pool=0): ''' 0: avg pool 1: max pool compression: calculated as 1 - r...
def conv2D_layer(bottom, name, kernel_size=(3, 3), num_filters=32, strides=(1, 1), activation=tf.identity, padding="SAME", weight_init='he_normal', add_bias=True): ''' Standard...
This function applies a 2D convolutional layer with specified parameters, followed by dropout regularization, batch normalization, and activation. It processes input tensors through these operations to introduce non-linearity, reduce overfitting, and stabilize training in neural networks.
def conv2D_layer_bn_drop(bottom, name, training, kernel_size=(3, 3), num_filters=32, strides=(1, 1), activation=tf.nn.relu, padding="SAME", ...
def conv2D_dilated_layer_bn(bottom, name, training, kernel_size=(3, 3), num_filters=32, rate=1, activation=tf.nn.relu, paddi...
The code implements a selective kernel block that processes input features through multiple parallel paths with varying dilation rates, aggregates them via summation, and applies learned attention mechanisms to fuse path-specific features. It uses global average pooling, dense layers, and softmax to generate attention ...
def selective_kernel_block(bottom, name, training, num_filters=32, kernel_size=(3, 3), strides=(1, 1), activation=tf.nn.relu, paddi...
def average_cycles(self, split_col='phih', throw_unfinished=True, **kwargs): split_data = self.split_cycles(split_col=split_col, throw_unfinished=throw_unfinished, **kwargs) self.data = functools.reduce(lambda x,y: x.add(y.reset_index(drop=True), fill_value=0),split_data) self.data.iloc[0:len(sp...
This method provides a default preprocessing pipeline for data, applying transformations like averaging cycles, subtracting endpoints/means, symmetrizing, and normalizing. It merges default settings with class-specific options and keyword arguments, then renames/retains specified columns in the data. The goal is to sta...
def default_preprocess(self, **kwargs): '''This is to be overriden by child classes But provides a sensible default, so child can only set self.opts Should return self''' def_opts = {'split_col': 'phih', 'throw_unfinished': True, 'subs_cols': ['A-B...
def read_cfg(path_to_config_file, profile_name): cfg = read(path_to_config_file, loader=yaml.full_load) if profile_name is not None: cfg["profile"] = profile_name elif "AWS_PROFILE" in os.environ: cfg["profile"] = os.environ["AWS_PROFILE"] return cfg def build( src, requirements=...
The main task of the code is to upload a Lambda function to AWS S3 by bundling the project's handler module, dependencies, and local packages into a ZIP file. It reads a configuration file, constructs the deployment package, and uploads it to S3 using the specified AWS profile. The function streamlines deploying server...
def upload( src, requirements=None, local_package=None, config_file="config.yaml", profile_name=None, ): """Uploads a new function to AWS S3. :param str src: The path to your Lambda ready project (folder must contain a valid config.yaml and handler module (e.g.: service.py)....
def read_cfg(path_to_config_file, profile_name): cfg = read(path_to_config_file, loader=yaml.full_load) if profile_name is not None: cfg["profile"] = profile_name elif "AWS_PROFILE" in os.environ: cfg["profile"] = os.environ["AWS_PROFILE"] return cfg def build( src, requirements=...
This function deploys a Lambda function to AWS by packaging the source code, dependencies, and configuration into a ZIP file. It reads a config.yaml file from the source directory, builds the deployment package, and either creates a new Lambda function or updates an existing one based on the configuration. Parameters i...
def deploy( src, requirements=None, local_package=None, config_file="config.yaml", profile_name=None, preserve_vpc=False, ): """Deploys a new function to AWS Lambda. :param str src: The path to your Lambda ready project (folder must contain a valid config.yaml and handle...
def read_cfg(path_to_config_file, profile_name): cfg = read(path_to_config_file, loader=yaml.full_load) if profile_name is not None: cfg["profile"] = profile_name elif "AWS_PROFILE" in os.environ: cfg["profile"] = os.environ["AWS_PROFILE"] return cfg def build( src, requirements=...
The main task of the code is to deploy an AWS Lambda function by packaging a project's code, dependencies, and local packages into a ZIP file, uploading it to an S3 bucket, and either creating a new Lambda function or updating an existing one with the uploaded code, using a configuration file for settings and AWS crede...
def deploy_s3( src, requirements=None, local_package=None, config_file="config.yaml", profile_name=None, preserve_vpc=False, ): """Deploys a new function via AWS S3. :param str src: The path to your Lambda ready project (folder must contain a valid config.yaml and handle...
def download_ia_assets(cache_dir: Path): ia_assets = ["dbip-country-lite", "maxmind-geolite2-country"] for identifier in ia_assets: output_dir = cache_dir / identifier output_dir.mkdir(parents=True, exist_ok=True) download_all_ia_files(output_dir, identifier, ".mmdb.gz") def download_as_...
The code downloads GeoIP and AS organization databases, extracts date information from file names, downloads prefix2as data using these dates, and decompresses/preprocesses IP2Country-AS databases into usable formats.
def main(): cache_dir = Path("cache_dir") print("[+] downloading GeoIP assets") download_ia_assets(cache_dir=cache_dir) print("[+] downloading AS Organizations assets") download_as_organizations(cache_dir=cache_dir) days = [] for path in (cache_dir / "dbip-country-lite").glob("*.mmdb.gz"): ...
def print_driver_info(report: dict): for key_o, value_o in report.items(): print(f"{value_o['name']:{25}} | {value_o['car']:{25}} | {value_o['lap_time']}") def driver_info(report: dict, name: str) -> dict: return {key: val for (key, val) in report.items() if val['name'] == name} def build_report(folder_...
The code processes command-line arguments to either generate a driver-specific report or a sorted report from a given file. It uses argparse to handle options like file path, driver name, and sorting order (ascending/descending). If both file and driver are specified, it prints driver-related info; if only the file is ...
def main(argv=None): parser = argparse.ArgumentParser( usage="%(prog)s [OPTION] [FILE]...", description="Empty" ) parser.add_argument("--file") parser.add_argument("--driver") parser.add_argument("--asc", action='store_true', dest='order') parser.add_argument("--desc", action='st...
def show_inventory(self): """Print info about plates, smallest increment, barbell, etc.""" print( f"Barbell mass: {self.bb_mass}\n" f"Weight inventory:" ) for quant, mass in self.ls_tup_plates: msg = f" {quant} plates, each {mass} lbs" ...
The main task of the code is to determine and print the quantity and mass of plates required to achieve a specified desired mass by evaluating available plate combinations, using incremental adjustments and displaying inventory details.
def show_missing_plates(self, desired_mass): """Print quantity and mass of plates to achieve desired mass.""" self.show_inventory() print( f"Desired total mass: {desired_mass}\n" f"Trying to make the following weight combinations:" ) increm = self.get_...
def create_config_dir(user: str) -> bool: """Creates config directory for a specific user (in his home directory) Args: user (str): The user Returns: bool: True means the operation was successful """ cmd = "mkdir -p %s" % get_config_dir(user) return_code, stdout, stderr =...
The function creates a user-specific virtual environment by first ensuring a configuration directory exists, then executing a command to generate the venv. It returns True on success or False if the venv creation fails, logging errors with details like the command, user, and stderr/stdout output.
def create_venv_for_user(user: str) -> bool: """Creates virtual env for a specific user Args: user (str): The user Returns: bool: True means the operation was successful """ if not create_config_dir(user): return False cmd = "python3 -m venv %s" % get_venv_dir(user) r...
def get_file_name(self): files = os.listdir(self.data_directory) output = [] train = [] test = [] for file in files: numeric_part = re.findall(r'\d+', file) numeric_part = int(numeric_part[0]) if numeric_part in self.task_id: ...
This class processes the bAbI dataset for a specified task, parsing stories, queries, and answers. It constructs a vocabulary, maps words to indices, pads sequences, and converts text into one-hot encoded arrays using the Bag of Words method. The class provides train/test data as tuples of encoded stories, queries, and...
def __init__(self, data_directory='data/data/en/', task_id=[15], max_story_length=50, max_query_length=50): nltk.download('punkt') """ A class that takes the data of bAbI dataset, based on the task_id, parse its data, and embed it using Bag Of the Words method. ...
def handle_sync_request(self, rxFrame): self.SYNC_IN_PROGRESS = True txFrame = HMSFrame() txFrame.msgType = MSG_TYPES.SYNACK txFrame.dstAddr = rxFrame.srcAddr synAckPayload = SynAckPayload() synAckPayload.nodeId = self.getNextSensorIdOrSync(rxFrame)[1] now = datet...
This function processes incoming HMS frames by checking their destination address and message type. It handles ACKs, SYNC requests, UPDA data updates, and SYNACK responses. For UPDA frames, it validates node IDs, updates node data if needed, sends ACKs, and manages node tracking. If the frame isn't intended for the gat...
def process_received_frame(self, rxFrame): if rxFrame.dstAddr == 0: if rxFrame.msgType == MSG_TYPES.ACKN and rxFrame.payload != "": self.ACKS.append(rxFrame.payload.seqNumToAck) print("ACK RECEVIED") elif rxFrame.msgType == MSG_TYPES.SYNC: ...
def _input_and_click( self, element: WebElement, text: str, *, click_enter: bool = False ) -> None: logger.debug("Sending keys %s to element %s", text, element.tag_name) element.clear() element.send_keys(text) if click_enter: logger.debug("Clicking enter on elemen...
This code automates logging into an online system (likely an educational management portal) by inputting an admission number and password, executing JavaScript verification, waiting for elements, and clicking the login button. It returns the WebDriver instance after successful login, marking the process as complete.
def login(self) -> FireFoxWebDriver: logger.info("Logging in with admission number: %s", self.__admission_number) logger.debug("Getting login page %s", GU_ICLOUD_EMS_LOGIN) self.driver.get(GU_ICLOUD_EMS_LOGIN) self._input_and_click( self.driver.find_element(By.ID, config["i...
def detect(self, text): if isinstance(text, list): result = [] for item in text: lang = self.detect(item) result.append(lang) return result data = self._translate(text, dest='en', src='auto') src = '' confidence = 0.0 ...
The code translates input text to a target language, handling both single strings and lists. It detects source language, extracts translation results, pronunciation, and metadata, while managing Python 2/3 encoding differences. It returns a structured object containing original text, translation, source/destination lan...
def translate_text(self,text,dest): if isinstance(text, list): result = [] for item in text: lang = self.detect(item) result.append(lang) return result origin = text data = self._translate(text, dest, src='auto') transla...
def keep_time(): was = GLOBAL_STATE.time try: yield finally: GLOBAL_STATE.time = was def animate(which, dur, what, **kwargs): return add_SMIL_tag( "animate", href="#" + which, dur=dur, fill="freeze", attributeName=what, **kwargs ) def _...
The code animates an element's opacity from 1 to 0 (fade out), increments a counter, then animates the same element from 0 to 1 (fade in), likely for UI transitions or slide show effects.
def next(self): with keep_time(): animate(self._id(), 1, "opacity", to=0) self.showing += 1 animate(self._id(), 1, "opacity", from_=0, to=1)
def reset(self): self.open_heap = [] # element of this list is like (cost,node_d) self.open_dict = {} # element of this is like node_d:(cost,node_c,(parent_d,parent_c)) self.closed_dict = {} # element of this is like node_d:(cost,node_c,(parent_d,parent_c)) self.interp_path = () # Sto...
The code executes the Hybrid A* algorithm for pathfinding, navigating from a start to a goal position within bounded coordinates while avoiding obstacles. It initializes parameters, sets up start/goal states with orientation, manages a priority queue (open_heap) and node dictionary (open_dict) for path exploration, and...
def run(self, start_pos, goal_pos, min_x, max_x, min_y, max_y, obstacles): """Runs the Hybrid A* algorithm. obstacles is a list of pygame rect objects.""" self.min_x, self.max_x, self.min_y, self.max_y = min_x, max_x, min_y, max_y a = goal_pos # (x, y) b = (self.width, self.height) # (x,...
def add_product(self, pdt): product_exists = self.product_exists(pdt) if(not product_exists): self.rls_bld_history["products"][pdt] = {} self.rls_bld_history["products"][pdt].update({"last_maintenance_release": "pending"}) self.rls_bld_history["products"][pdt].update(...
This function adds a build entry to the 'rls_bld_history' data structure by creating nested dictionaries for product, year, quarter, and target release, then inserting the build with a timestamp. It updates the history, verifies the build's existence, and returns True if successful.
def add_build(self, pdt, year, qtr, tgtrls, bld=None): """Add a build to rls_bld_history""" retval = False self.add_product(pdt) self.add_year(pdt, year) self.add_quarter(pdt, year, qtr) self.add_target_release(pdt, year, qtr, tgtrls) self.rls_bld_history["product...
def add_product(self, pdt): product_exists = self.product_exists(pdt) if(not product_exists): self.rls_bld_history["products"][pdt] = {} self.rls_bld_history["products"][pdt].update({"last_maintenance_release": "pending"}) self.rls_bld_history["products"][pdt].update(...
This method initializes a new product by adding its details (year, quarter, target release, build) and verifies the build's existence. It sequentially adds product data, year, quarter, target release, and build, then asserts the build's presence to ensure successful creation.
def start_a_new_product(self, pdt, year=None, qtr=None, tgtrls=None, bld=None): self.add_product(pdt) self.add_year(pdt, year) self.add_quarter(pdt, year, qtr) self.add_target_release(pdt, year, qtr, tgtrls) self.add_build(pdt, year, qtr, tgtrls, bld) assert self.build_ex...
def entropy(data_list): total_sum = 0 unique_list = list(set(data_list)) for data in unique_list: total_sum = total_sum - ( (data_list.count(data) / len(data_list)) * (math.log2(data_list.count(data) / len(data_list)))) return total_sum def colToUse(data, tEntropy, tFind, colList...
The main task of the code is to recursively construct a decision tree structure by selecting the optimal feature to split on, handling both continuous (median-based) and categorical splits. It processes subsets of filtered data, checks for target class purity, and builds tree nodes/leaves, storing the resulting tree in...
def formStructure(filteredData, t_find, c_list, current_tree): # print(filteredData,c_list,current_tree, "top") total_entropy = entropy(list(filteredData[to_find])) bestCol, isMedian = colToUse(filteredData, total_entropy, t_find, c_list) # print(lastBest, bestCol, isMedian, c_list) if isMedian or i...
def numpy_mat2jBigIntegerRationalMatrix(npmat, tolerance=0): if tolerance > 0: if type(npmat) is not numpy.ndarray: # in case it is a sparse matrix npmat = npmat.toarray() jmat= DefaultBigIntegerRationalMatrix(jpype.JDouble[:](numpy.concatenate(npmat)), npmat.shape[0], np...
This function compresses a stoichiometric matrix using a specified method, handling reversibility, reaction removal, and optional row sorting. It converts the input matrix to a Java-compatible format, applies compression via StoichMatrixCompressor, and returns the compressed matrix, transformed matrix, and compression ...
def compress_rat_efmtool(st, reversible, compression_method=CompressionMethod.STANDARD, remove_cr=False, tolerance=0, remove_rxns=[]): # add keep_separate option? # expose suppressedReactions option of StoichMatrixCompressor? num_met = st.shape[0] num_reac = st.shape[1] st = numpy_mat2jBigIntegerRationalMat...
def get_bitbrasil_balance(display=False): url = "https://brasilbitcoin.com.br/api/get_balance" header = brasil_bit_header r = requests.get(url, headers=header) data = r.json() montante = float(data["brl"]) + (float(data["btc"]) * get_estimate_price("btc")) if display: for coin, quant in ...
The main task of the code is to buy Bitcoin (BTC) using the user's BRL balance from BitBrasil, subtracting 10 BRL as a buffer, by retrieving the balance, estimating the BTC price, and executing the purchase. It returns the result of the transaction.
def buy_all(): montante = get_bitbrasil_balance() price_of_one = get_estimate_price() print(montante) r = buy_BRLBTC(montante - 10) return r
def sigma(self, t): return t.neg().exp() def t(self, sigma): return -sigma.log() def eps(self, eps_cache, key, x, t, *args, **kwargs): if key in eps_cache: return eps_cache[key], eps_cache sigma = self.sigma(t) * x.new_ones([x.shape[0]]) eps = (x - self.model(x, sigma...
This function implements a fast diffusion probabilistic model (DPM) solver for sampling, performing denoising steps using variable-order methods (1st, 2nd, 3rd) based on the number of function evaluations (nfe). It handles noise injection, time-step calculations, and conditional execution based on global settings, ulti...
def dpm_solver_fast(self, x, t_start, t_end, nfe, eta=0., s_noise=1., noise_sampler=None): self.sample_data.x = x; noise_sampler = default_noise_sampler(self.sample_data.x) if noise_sampler is None else noise_sampler if not t_end > t_start and eta: raise ValueError('eta must be 0 for...
def sigma(self, t): return t.neg().exp() def t(self, sigma): return -sigma.log() def eps(self, eps_cache, key, x, t, *args, **kwargs): if key in eps_cache: return eps_cache[key], eps_cache sigma = self.sigma(t) * x.new_ones([x.shape[0]]) eps = (x - self.model(x, sigma...
This function implements an adaptive DPM (Denoising Process Model) solver using PID step size control to efficiently solve diffusion processes with specified error tolerances. It iteratively adjusts step sizes based on error estimates between low-order and high-order numerical solutions, accepting/rejecting steps to ma...
def dpm_solver_adaptive(self, x, t_start, t_end, order=3, rtol=0.05, atol=0.0078, h_init=0.05, pcoeff=0., icoeff=1., dcoeff=0., accept_safety=0.81, eta=0., s_noise=1., noise_sampler=None): noise_sampler = default_noise_sampler(x) if noise_sampler is None else noise_sampler if order not in {2, 3}: ...
def plot_posterior_contours(mean_params,logstd_params): plt.clf() logprob_adj = lambda two_params: logprob_given_two(mean_params, two_params) plot_isocontours(ax, logprob_adj, cmap='Blues') mean_2d = mean_params[contourK, [px1,px2]] logstd_2s = logstd_params[contourK, [px1,px2]] variational_contour = lambda x: mv...
The code's main task is to monitor and log variational inference progress by saving parameter visualizations, posterior contours, and model samples at regular intervals during training, while printing iteration numbers and loss values for tracking model performance.
def print_perf(var_params, iter, gradient): mean_params, logstd_params = var_params print(".", end='') if iter % 30 == 0: save_images(mean_params, 'plotmean_vi_{}.png'.format(iter % 30)) save_images(logstd_params, 'plotsgd_vi_{}.png'.format(iter % 30)) plot_posterior_contours(mean_params, logstd_params) prin...
def init_game(self): config = get_config(self.config_path) self.time = config['controller']['time'] self.graphic = get_instance(config['graphic']) self.map = get_instance(config['map']) self.players = {} for pcfg in config['player']: for it in range(pcfg['coun...
The main task of the code is to execute a turn-based game loop, managing player turns, updating game state, handling announcements, checking for a winner, and rendering the game map. It initializes the game, iterates through players, decrements time, processes turn results, updates scores, and terminates when time expi...
def run_game(self): self.init_game() # return turn_id = 0 announce_turn = random.randint(7, 11) while self.time > 0: # self.graphic.draw(self.map.get_system_view(self.get_player(turn_id)).map) # continue if announce_turn == 0: l...
def get_kfold_indices( dataset: Dataset, num_folds: int = 10, random_state: int = 42 ) -> Tuple[List[torch.Tensor], List[torch.Tensor], List[torch.Tensor]]: """ Utility Function to get indices for k-fold cross validation Args: dataset(Dataset): Dataset to split num_folds(int): Number of...
This code trains a model using k-fold cross-validation, tracking validation loss and test accuracy across folds. It performs training, validation, and testing steps for each epoch, logs metrics to wandb or console, and computes the mean and standard deviation of final test performance across folds.
def fit( self, epochs: int, batch_size: int, optimizer: torch.optim.Optimizer, verbose: bool = True, log_to_wandb: bool = False, ) -> None: """ Trains the model on the given dataset Args: epochs(int): Number of epochs b...
def checkMoveDeep(self, iPlayer1:int, iPlayer2:int, iCards1:int, iCards2:int, idCard1:int, idCard2:int): action, alllowed = self.checkMove(iPlayer1, iPlayer2, iCards1, iCards2, idCard1, idCard2) if(action == RoundController.ACTION_DROP and len(self.cards)<10) : return action, self.checkHbout(iPlayer1),...
This function handles a game move by checking authorization, executing the move, and updating the game state. It validates the move's legitimacy, ensures the user is authorized (unless bypassed), performs the internal move logic, and triggers post-move actions. It returns the action type, whether it's allowed, and whet...
def move(self,user_id, iPlayer1:int, iPlayer2:int, iCards1:int, iCards2:int, idCard1:int, idCard2:int, bypass=False) -> tuple[str, bool, bool]: action, isallowed, reason = self.checkMoveDeep(iPlayer1, iPlayer2, iCards1, iCards2, idCard1, idCard2) self.version += 1 self.abondoned.clear() ...
def setfreqsynth(synthfreq): synthfreq = int(synthfreq * 12) synth = rm.open_resource('GPIB0::21::INSTR') Command = 'FREQ '+str(synthfreq)+' Hz\n' synth.write(Command) def setsimzero(): ser.write(str.encode('CONN 1, "xyz"\n')) time.sleep(0.001) ser.write(str.encode('AMAN 0 \n')) time.sle...
The main task of the code is to adjust a system's frequency to a target value using a combination of step-based tuning and PID control. It first aligns the primary frequency (PU) to the target, engages communication modules, and then adjusts the secondary frequency (PR) with an offset. Finally, it activates PID control...
def totargetstart(target, offset): #setfreqsynth setfreqsynth(target) setsimzero() while abs(target-getrepratePU()) > 1000: steptotargetPU2(target) else: #pump lock ser.write(str.encode('CONN 1, "xyz"\n')) time.sleep(0.001) ser.write(str.encode('AMAN...
def setfreqsynth(synthfreq): synthfreq = int(synthfreq * 12) synth = rm.open_resource('GPIB0::21::INSTR') Command = 'FREQ '+str(synthfreq)+' Hz\n' synth.write(Command) def setsimzero(): ser.write(str.encode('CONN 1, "xyz"\n')) time.sleep(0.001) ser.write(str.encode('AMAN 0 \n')) time.sle...
The main task of the code is to adjust a system's frequency to a target value using iterative steps, then shift the frequency by an offset via serial communication commands, ensuring the resulting rates fall within specified tolerances. It avoids locking mechanisms, using loops to fine-tune the frequency until it meets...
def totargetstartnolocks(target, offset): #setfreqsynth setfreqsynth(target) setsimzero() while abs(target-getrepratePU()) > 1000: steptotargetPU2(target) else: #pump lock ser.write(str.encode('CONN 1, "xyz"\n')) time.sleep(0.001) ser.write(str.encod...
def setfreqsynth(synthfreq): synthfreq = int(synthfreq * 12) synth = rm.open_resource('GPIB0::21::INSTR') Command = 'FREQ '+str(synthfreq)+' Hz\n' synth.write(Command) def totarget2(target): totarget(target, 500) while abs(target-getrepratePU()) > 10: print('totarget2') totarget(...
The function `totargetstart` configures hardware by setting a frequency synthesizer to a target, sending serial commands to engage connections (CONN), adjust amplitude (AMAN), and execute target-specific functions (totarget2, totarget2PR). It sequentially initializes PID controllers (fast and slow) via serial commands,...
def totargetstart(target): #setfreqsynth setfreqsynth(target) #pump lock ser.write(str.encode('CONN 1, "xyz"\n')) time.sleep(0.001) ser.write(str.encode('AMAN 0 \n')) totarget2(target) ser.write(str.encode('AMAN 1 \n')) ser.write(str.encode('xyz\n')) time.sleep(0.001) #t...
def setfreqsynth(synthfreq): rm = visa.ResourceManager() rm.list_resources() synthfreq = int(synthfreq * 12) synth = rm.open_resource('GPIB0::21::INSTR') Command = 'FREQ '+str(synthfreq)+' Hz\n' synth.write(Command) def totarget2(target): totarget(target, 500) while abs(target-getreprate...
This function configures hardware systems by setting a frequency synthesizer, executing pump lock procedures via serial commands, adjusting target frequencies through specific connections, and engaging PID controls in both fast and slow modes to achieve precise frequency alignment and system stabilization.
def totargetstart(target): #setfreqsynth setfreqsynth(79217900) #pump lock ser.write(str.encode('CONN 1, "xyz"\n')) time.sleep(0.001) ser.write(str.encode('AMAN 0 \n')) totarget2(target) ser.write(str.encode('AMAN 1 \n')) ser.write(str.encode('xyz\n')) time.sleep(0.001) ...
def setfreqsynth(synthfreq): synthfreq = int(synthfreq * 12) synth = rm.open_resource('GPIB0::21::INSTR') Command = 'FREQ '+str(synthfreq)+' Hz\n' synth.write(Command) def setsimzero(): ser.write(str.encode('CONN 1, "xyz"\n')) time.sleep(0.001) ser.write(str.encode('AMAN 0 \n')) time.sle...
The code adjusts a frequency synthesizer to reach a target frequency by first using a loop to approach the target via coarse steps (steptotargetPU2), then locking the system via serial commands (CONN, AMAN). It then fine-tunes by adjusting to a modified target (target - offset) with another loop (steptotargetPR2), foll...
def totargetstart(target, offset): #setfreqsynth setfreqsynth(target) setsimzero() while abs(target-getrepratePU()) > 1000: steptotargetPU2(target) else: #pump lock ser.write(str.encode('CONN 1, "xyz"\n')) time.sleep(0.001) ser.write(str.encode('AMAN...
def setfreqsynth(synthfreq): synthfreq = int(synthfreq * 12) synth = rm.open_resource('GPIB0::21::INSTR') Command = 'FREQ '+str(synthfreq)+' Hz\n' synth.write(Command) def setsimzero(): ser.write(str.encode('CONN 1, "xyz"\n')) time.sleep(0.001) ser.write(str.encode('AMAN 0 \n')) time.sle...
The function adjusts a system's frequency to a target value in two stages. First, it sets the frequency synthesizer, then uses loops to adjust the rate (PU) via serial commands until within 1000 Hz of the target. Next, it shifts the target by an offset, adjusts the rate (PR) via similar commands until within 1500 Hz, a...
def totargetstartnolocks(target, offset): #setfreqsynth setfreqsynth(target) setsimzero() while abs(target-getrepratePU()) > 1000: steptotargetPU2(target) else: #pump lock ser.write(str.encode('CONN 1, "xyz"\n')) time.sleep(0.001) ser.write(str.encod...
def read_hyp_np(file): """ Read a .npy file, return it loaded. """ print('about to load file...') loaded_file = np.load(file) return loaded_file def read_freq_np(file): """ Read the frequency/wavelength data associated with a hyperspectral file in a .npy """ print('about to lo...
The main task of the code is to process hyperspectral data from 2021 and 2022 datasets by reading images, frequency data, and plot coordinates, applying geometric transformations to align data with field plots, and extracting cropped hyperspectral plots for analysis. The script iterates over folders, computes coordinat...
def main_hyperspectral_orchestrator(): plot_path_root = '/Users/alim/Documents/prototyping/research_lab/HIPS_grid/' hyp_path_local_all = '/Users/alim/Documents/prototyping/research_lab/HIPS_Hyperspectral/' local_dirs = os.listdir(hyp_path_local_all) local_dirs.remove('.DS_Store') local_dirs.sort()...
def generate_field(game_state): field = np.copy(game_state['field']) field[field == -1] = -10 for coin_position in game_state['coins']: field[coin_position[0], coin_position[1]] = 2 for bomb in game_state['bombs']: bomb_position = bomb[0] field[bomb_position[0], bomb_position[1]]...
The function `seek_coin` determines the optimal coin to pursue in a game by evaluating each coin's potential using a predictive model. It calculates the Q-value for each coin's position, avoiding obstacles, and selects the coin with the highest Q-value. If no valid coin is found, it returns `None`. Otherwise, it return...
def seek_coin(model, game_state, already_chosen_position=None): self_data = game_state['self'] self_pos = self_data[3] field = generate_field(game_state) max_q_s = -100000 selected_coin_pos = already_chosen_position if not selected_coin_pos: for coin_pos in game_state['coins']: ...
def generate_field(game_state): field = np.copy(game_state['field']) field[field == -1] = -10 for coin_position in game_state['coins']: field[coin_position[0], coin_position[1]] = 2 for bomb in game_state['bombs']: bomb_position = bomb[0] field[bomb_position[0], bomb_position[1]]...
The function selects the optimal crate to destroy using a predictive model, evaluates movement feasibility, and returns the action to reach it. It prioritizes crates with the highest Q-value prediction, checks proximity for bombing, and calculates movement paths while avoiding obstacles.
def destroy_crate(model, game_state, already_chosen_crate_pos=None): crate_positions = np.argwhere(game_state['field'] == 1) self_data = game_state['self'] self_pos = self_data[3] field = generate_field(game_state) max_q_s = -100000 selected_crate_pos = already_chosen_crate_pos if selected_c...
def generate_field(game_state): field = np.copy(game_state['field']) field[field == -1] = -10 for coin_position in game_state['coins']: field[coin_position[0], coin_position[1]] = 2 for bomb in game_state['bombs']: bomb_position = bomb[0] field[bomb_position[0], bomb_position[1]]...
The function `dodge_bomb` identifies safe positions near the player's current location to avoid imminent explosions. It uses a predictive model to evaluate and select the optimal safe position with the highest Q-value, prioritizing moves that maximize safety. If no safe position is found, it returns `None`. Otherwise, ...
def dodge_bomb(model, game_state, already_chosen_position=None): self_data = game_state['self'] self_pos = self_data[3] field = generate_field(game_state) predicted_explosions_in_map = get_obstacles_field(game_state, True) if predicted_explosions_in_map[self_pos[0], self_pos[1]]==0: return N...
def display_healthbar(self): if self.health > 0: self.healthbar = pygame.transform.scale( self.healthbar, ((self.health / 200) * self.healthbar_ogx, self.healthbar.get_height())) screen.blit(self.healthbar, (53, screen...
The code's main task is to update an object's state by displaying its health bar, animating its actions, checking for damage, determining if it's dead, and controlling its behavior if still alive.
def update(self): self.display_healthbar() self.animate() self.get_hit() self.decide_dead() if not self.dead: self.control()
def animate(self): self.current_sprite += 0.2 #cycles through sprite image list if self.current_sprite >= len(self.sprites): self.current_sprite = 0 if not self.reloading and pygame.mouse.get_pressed( )[0]: #checks to see if the user is firing to open ...
The code's main task is to update an entity's state in a game loop by animating it, checking for collisions/damage, displaying health, determining death status, and controlling movement/actions if not dead.
def update(self): self.animate() self.get_hit() self.display_health() self.decide_dead() if not self.dead: self.control()
def V_matter(d, rho, Ye=Y_e, Yn=Y_n, V_NSI=None): """ Calculate the d x d matter potential [eV^2/GeV] params: - d (int): number of neutrino flavors - rho [g/cm^3]: matter density - Ye [dimensionless]: average number of electron per nucleon - Yn [dimensionless]: average number of neutron per elec...
This function calculates the neutrino oscillation probability from flavor a to b over a distance L, considering neutrino energy E, mass values, mixing matrix U, matter potential, and non-standard interactions (NSI). It computes the transition probability using the Hamiltonian matrix derived from input parameters, handl...
def nuprobe(a, b, L, E, mass, UU, antinu=False, const_matter=True, V_NSI=None): """ Calculate the oscillation probability of neutrino of flavor a to b params: - a, b (int): transition of a neutrino from flavor a to b a = (1, 2, 3, ..., d) = (e, \mu, \tau, s_1, s_2, ..., s_{d-3}) - L [km]: the dist...
def dir(ci,cj,row,col): pass if ci%2==0 : if cj==col-1: return "DOWN" else: return "RIGHT" if ci%2!=0: if (col-cj-1)==0: return "DOWN" else: return "LEFT" def imToPaths(filename): if filename.endsw...
The code processes an image grid to generate G-code instructions for directional movement. It divides the image into tiles, updates GUI elements with progress and filenames, writes G-code to a file, and sends commands to a hardware port if enabled. The function handles tile-specific file naming, directional logic, and ...
def gridGcode(): global count,label3 img = Image.open('dir_in/result.jpg') w, h= img.size row=h//tp col=w//tp k=100/(row*col) for i in range(0,row): for j in range(0,col): if(i%2==0): fname=f"dir_out/{i}x{j}.jpg" ...
def setValue(val,m,dd,fileO): global tp,mode,file,d tp=int(val) mode=m d=dd file = open(fileO+'/output.gcode', "a") def Rsize(): img = cv2.imread('dir_in/savedImage1000x.jpg') h,w,ch= img.shape ww =w + tp - w%tp hh = h + tp - h%tp color = (255,255,255) result = n...
The function `GcodeGen` generates G-code for 3D printing based on input parameters `fileO`, `d`, and `mode`. In `mode=2`, it processes data using matrix calculations and functions like `Rsize()`, `split()`, and `gridGcode()`. In `mode=1`, it simulates progress tracking, loads an image, scales it, converts it to paths, ...
def GcodeGen(fileO,d,mode): # print('sdfsdfdsfsdf',fileO) if(mode==2): # for matrix method setValue(mt.floor(d*3.7795275591),mode,d,fileO) Rsize() split() gridGcode() clearing() elif(mode==1): # for single method global cou...
def cancel_handler(self, message): """handles /cancel command""" self.main_menu(message, "Ok") def create_markup(self, buttons, width=2, back_to_main_menu=False, cancel_cmd=False, confirm_cmd=False): """create markup for provided buttons and width this automates bot's buttons creation fo...
This function handles user requests to view map schematics. It checks input type, cancels if needed, prompts for map selection via buttons, and sends corresponding PNG images if available. If maps aren't found, it notifies the user. It manages navigation states between "map pick" and "send map" workflows, ensuring prop...
def view_map_callouts(self, message, navigation): """provide map schematics with callout names for all available maps""" typ = message.content_type if typ != 'text': output = "let's stick to buttons, ok?" msg = self.bot.reply_to(message=message, text=output) s...
def create_markup(self, buttons, width=2, back_to_main_menu=False, cancel_cmd=False, confirm_cmd=False): """create markup for provided buttons and width this automates bot's buttons creation for every submenu""" # since create_markup is inaccessible to users from telegram chat, no need to check ...
This function handles user messages in a Telegram bot, forwarding text messages to a specified author. It restricts non-text content, uses buttons for user confirmation/cancellation, and collects multi-message inputs. If text is provided, it appends to an incoming message buffer, prompting continuation until confirmati...
def contact_dev(self, message, incoming_message=None): # TODO add picture handling """forward messages to @author""" name = message.text typ = message.content_type if typ not in ('text'): output = "let's stick to just text ok?" markup = self.create_markup(buttons...
def send_help_response(self, message): """ /help command processor. Basically just lists all available commands for user. Redundant but might be useful later""" self.main_menu(message=message, text="I'll just send you back to main menu for easy navigation") def contact_dev(self, message, incomin...
The code defines a `welcome` function acting as a command handler for a bot. It processes incoming messages, checking if they match specific commands (`/help`, `/contact`, `/cancel`, `/debug`), and triggers corresponding methods like `send_help_response` or `contact_dev`. For `/debug`, it sends a predefined "nope :)" m...
def welcome(message): """command handler. Add new commands here if necessary""" if message.text == '/help': self.send_help_response(message) elif message.text == '/contact': self.contact_dev(message) elif message.text == '/cancel': ...
def initPlayerShip(ps, de): ps.base_image = pygame.image.load(str(de.gamepack['img'][ps.base_image_name])).convert_alpha() ps.base_rect = ps.base_image.get_rect() ps.floor_image = pygame.image.load(str(de.gamepack['img'][ps.floor_image_name])).convert_alpha() ps.floor_rect = ps.floor_image.get_rect() ...
The code initializes a Pygame game for a space-themed adventure, handling display setup, asset loading (images, sounds, fonts), and game state management. It features a main menu with interactive buttons, ship selection in the hangar, and gameplay elements like event handling, music playback, and rendering of planets, ...
def play(): screen_x = 1280 screen_y = 720 screen_center = (screen_x / 2, screen_y / 2) #enable framebuffer on Raspi. Might break on non-linux stuff. disp_no = os.getenv("DISPLAY") if disp_no: print("I'm running under X display = " + str(disp_no)) screen =...
def parse_conditions(config: Dict) -> Dict[str, QueryCondition]: """Parse conditions from configuration.""" condition_configs = config.get("conditions") if not condition_configs: return {} base_conditions = {} extending_conditions = {} for name, condition_config in condition_configs.ite...
The main task of the code is to parse query configurations from a given dictionary. It extracts query definitions, conditions, output selections, and display settings from the config, then constructs a dictionary of `Query` objects by processing each query configuration with supporting parsed data. The function returns...
def parse_queries(config: Dict) -> Dict[str, Query]: """Parse queries from configuration.""" query_configs = config.get("queries") if not query_configs: return {} conditions = parse_conditions(config) output_selections = parse_output_selections(config, conditions) displays = parse_displ...
def getNotFileError(request): if havePhoto(request) == False and 'photo' not in request.FILES: return "No photo uploaded !" return "" def getCropError(request): count = numberOfCropFields(request) if count == 0: return "" if 0 < count and count < 4: return "You must fill all the crop fields !" left = int(re...
The function `hasError` checks if any error messages exist related to file handling, cropping, or resizing operations. It returns `True` if `getNotFileError`, `getCropError`, or `getResizeError` yields a non-empty string, indicating an error; otherwise, it returns `False`.
def hasError(request): if getNotFileError(request) != "": return True if getCropError(request) != "" or getResizeError(request) != "": return True return False
def getNotFileError(request): if havePhoto(request) == False and 'photo' not in request.FILES: return "No photo uploaded !" return "" def getCropError(request): count = numberOfCropFields(request) if count == 0: return "" if 0 < count and count < 4: return "You must fill all the crop fields !" left = int(re...
The function `getError` checks and returns the first non-empty error message from three specific error-checking functions: `getNotFileError`, `getCropError`, and `getResizeError`. If any of these functions detect an error, the corresponding message is returned immediately. If none detect an error, it returns an empty s...
def getError(request): if getNotFileError(request) != "": return getNotFileError(request) if getCropError(request) != "": return getCropError(request) if getResizeError(request) != "": return getResizeError(request) return ""
def havePhoto(request): try: photo = Image.open("djangoTest/media/" + getName(request)) return True except: return False def hasError(request): if getNotFileError(request) != "": return True if getCropError(request) != "" or getResizeError(request) != "": return True return False def getError(request): ...
This Django view handles photo upload and editing. It manages user sessions, checks for existing photos, processes form submissions, validates inputs, saves original images, applies edits, generates new image names, and handles sharing. It displays appropriate messages for success, errors, and existing photos, renderin...
def home(request): if not request.session.session_key: request.session.create() uploadMessage = "Upload and edit your photo !" if havePhoto(request): uploadMessage = "We have your last photo ! Just for a new photo use upload !" emptyForm = EditImageForm() if request.method == 'POST': if hasError(request): ...
def exist(self): """ Is this configured? """ return f"{self.category}_MODEL" in app.config def load(self): """ Load the machine learning model into the memory """ if os.path.exists(self.name()): self.model = AutoModelForCausalLM.from_pretrained...
The code initializes a model instance with a specified category. It checks if the model exists, loads it if present, and logs a message. If the model isn't found, it issues a warning. The main task is to set up and validate a model configuration based on the given category.
def __init__(self, category): self.category = category self.model = None self.system_prompt = None if self.exist(): self.load() log.info("Started %s model for %s", self.category, self.name()) else: log.warning("%s model does not exist in config...
def __collect_name_id_list(self, path_val): all_id_name_list_temp = os.listdir(path_val) all_list = [] for i in all_id_name_list_temp: temp_list = [] if os.path.isdir(path_val) and i[0] !='.': pos = i.find('_') if pos > 0: ...
The main task of the code is to process files by collecting name-ID pairs, generating file paths, updating a label table, counting label frequencies, and ranking results. It sequentially performs data collection, table creation, statistical analysis, and ranking to organize and prioritize file content information.
def run_RSD(self): self.__collect_name_id_list(self.__file_path) self.__get_file_path_list(self.__file_path, self.__all_id_name_list) self.__show_all_file_path_flag = True print('(1)show_all_file_path_flag = True!!') print('(2)updating label table...') self.__create_label...
def extractRelevantInfoHitPredict(): #creating information for mapping names for making SQL database """ Index(['Entry', 'HitPredictID', 'Cross-reference (GeneID)', 'Entry name', 'Protein names', 'Length', 'Status', 'Sequence'], dtype='object') """ mappings = [] #tuples of uniprot id, h...
The main task of the code is to aggregate unique protein sequences from four datasets (HitPredict, HIPPIE, HuRI, and Negatome), combine them into a single list of distinct sequences, and insert these sequences into a database table named 'proteins'. The code extracts sequence data from each source, ensures uniqueness v...
def combinedSequences(): #open and combine by unique sequences for HIPPIE, HitPredict, HuRI (Scored subset), and Negatome which could be recovered #HitPredict mappings, hitPredict = extractRelevantInfoHitPredict() print (mappings) #hitPredict['Sequence'].to_list() #list of unique proteins HitPredic...
def set_defaults(options): """Add default values for missing options.""" output_file = getattr(options, 'output', None) if output_file is None: options.output = options.input if getattr(options, 'keep_entries', None) is None: options.keep_entries = (output_file is not None) def show_file...
This script processes changelog entries from a directory, merging them into an existing changelog file. It accepts input/output paths, controls file retention, and supports dry-run mode for listing files. The main task is to parse command-line arguments, configure options, and execute entry merging while respecting use...
def main(): """Command line entry point.""" parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--dir', '-d', metavar='DIR', default='ChangeLog.d', help='Directory to read entries from' ' (default: ChangeLog....
def get_tot_piece_in_row(self, row, col): return 1 + self.traverse_tot_pieces(row, col, 0, -1) + self.traverse_tot_pieces(row, col, 0, 1) def get_row_moves(self, row, col, dist): return self.traverse_possible_moves(row, col, 0, -1, dist) + self.traverse_possible_moves(row, col, 0, 1, dist) def get_tot_piece_in_col(...
The code generates all possible moves from a given board position by aggregating moves along the same row, column, and both diagonals. It calculates the total pieces in each direction, then adds moves derived from these directions to a list, returning all potential move positions.
def get_possible_moves(self, row, col): possible_moves = [(row, col)] row_move_dist = self.get_tot_piece_in_row(row, col) possible_moves += self.get_row_moves(row, col, row_move_dist) col_move_dist = self.get_tot_piece_in_col(row, col) possible_moves += self.get_col_moves(row, col, col_move_dist) diagona...
def outside_board(self, row, col): return True if row < 0 or row >= self.board.board_size or col < 0 or col >= self.board.board_size else False def get_possible_moves(self, row, col): possible_moves = [(row, col)] row_move_dist = self.get_tot_piece_in_row(row, col) possible_moves += self.get_row_moves(row, col...
This function processes a player's move in a board game. It checks if the move is valid, updates the board state, highlights possible moves, and handles turn transitions. If the move is valid, it simulates the move, visualizes the action, and returns the previous selected coordinate. Otherwise, it returns (-1, -1) for ...
def select(self, row, col): ret = (-1, -1) if self.game_over or self.outside_board(row, col): return ret if self.board.board_config[row][col] == self.turn: self.board.draw() possible_moves = self.get_possible_moves(row, col) self.board.draw_blue_circle_with_line(possible_moves) self.change_turn(...
def make_empty_settings(): settings = ' ' return settings def start_exp(self,experments_setting,traget_py_name = 'train.py'): # call train.py here string = self.phase_setting(experments_setting) #command = 'ping 192.168.1.1 ' # for debugging command = 'python ' + traget_py_name +...
The code initializes an experiment with empty settings, then enters a loop that periodically checks if the experiment is completed. It sleeps for 5 seconds between checks and exits the loop once the experiment is marked as done. The main task is to orchestrate and monitor an experiment's execution until completion.
def start(self): # init_run = make_empty_settings() self.start_exp(init_run) is_done = False while (True): time.sleep(5) is_done = self.check_reports() if is_done: break
def download_document(self, file_id): """ Downloads file from telegram api and stores it as a temporary file Returns filepath Firstly requests telegram api to find url to file Secondly downloads it to a temporary folder :param file_id: str :return: str """...
The main task of the code is to process received documents by deleting existing files, storing new ones in a temporary folder, determining their format, and routing them to appropriate processing functions (image, document, or video handling) based on the detected format, while logging errors and notifying users of uns...
def process_media(self, context): """ Processes media if document is received If a document was received firstly tries to delete the previous assigned file path Sets a new file path Downloads the document and stores it in a temporary folder Recognizes a file format and ca...
def command_start(self, context): """ Sends start answer :param context: dict :return: None """ self.send_message(context, "start") def command_formats(self, context): message = f"{self.get_answer('available_formats')}\n\n" \ f"{self.get_answer('...
The code processes user commands by checking the input text for specific command keywords (/start, /formats, /register). If a command is recognized, it calls the corresponding handler method; otherwise, it sends a "wrong_command" response. The function acts as a dispatcher for command-based interactions.
def process_command(self, context): """ Calls a necessary command function :param context: dict :return: None """ if "/start" in context["text"]: self.command_start(context) elif "/formats" in context["text"]: self.command_formats(context) ...
def convert_document(self, context, file_id): """ Converts and sends received document :param context: dict :param file_id: str :return: None """ self.send_message(context, "converting_document") file_path = self.document_converter.find_file_by_id(file_id)...
This function processes user file conversion requests. If the user is authorized and has an existing file, it checks the input text against supported formats (document, image, video) and triggers the appropriate conversion. If unauthorized or no file exists, it returns respective error messages.
def process_file_format(self, context): """ If supported format supplied and user is authorized converts document :param context: dict :return: None """ if self.database.get_authorised(telegram_id=context["from"]["id"]): prev_file_path = self.database.get_file...
def process_command(self, context): """ Calls a necessary command function :param context: dict :return: None """ if "/start" in context["text"]: self.command_start(context) elif "/formats" in context["text"]: self.command_formats(context) ...
The code processes input text by checking if it contains a command (detected via "/") and executes it using `process_command`, otherwise treats it as a conversion format request via `process_file_format`. It handles `UnsupportedFormatException` by sending an error message and logging the issue.
def process_text(self, context): """ Processes text If a command detected processes command Else treats a message as a conversion format request :param context: dict :return: None :raises: UnsupportedFormatException """ self.logger.debug("Text dete...
def process_text(self, context): """ Processes text If a command detected processes command Else treats a message as a conversion format request :param context: dict :return: None :raises: UnsupportedFormatException """ self.logger.debug("Text dete...
This code processes Telegram user messages by checking for text or media attachments. It authorizes users, handles supported media (e.g., documents ≤2MB, photos/videos), and sends appropriate responses (e.g., "file_too_big", "compressed_file"). Unsupported types or unauthorized users trigger error/permission messages. ...
def process_message(self, context): """ Processes message send by a user in telegram Recognises a message attachment and processes it accordingly :param context: dict :return: None """ try: if "text" in context: self.process_text(contex...
def get_kwargs(model_class): model_args = inspect.getfullargspec(model_class.__init__).args shell_args = args._get_kwargs() kwargs = dict(shell_args) for arg, val in shell_args: if not arg in model_args: kwargs.pop(arg) return kwargs def train(model, elogger, train_set, eval_s...
The code trains or evaluates a DeepTTE model for time-to-event prediction. It initializes the model with specified arguments, logs results, and either trains using provided datasets or loads pre-trained weights to evaluate on the test set, saving outcomes.
def run(): # get the model arguments kwargs = get_kwargs(models.DeepTTE.Net) # model instance model = models.DeepTTE.Net(**kwargs) # experiment logger elogger = logger.Logger(args.log_file) if args.task == 'train': train(model, elogger, train_set = config['train_set'], eval_set = ...
def draw_board(self): """ Updates the pygame display and prints the board. """ self.win.fill((0,0,0)) for i in range(board_size): for j in range(board_size): square_data = self.game.board[j,i,:] #printing square colour ...
This function runs a single game instance by managing the game loop, handling player moves (human or AI agents), updating the game state, and rendering the board. It alternates between players, processes move decisions based on agent types, reformats moves if needed, and terminates when the game ends, displaying the fi...
def play(self): """ Runs a single complete game. """ self.draw_board() pygame.display.update() self.playing = True while self.playing: get_printable_board(self.game.board, self.game.players[0].walls, self.game.players[1].walls) if self.g...
def coordSTRtoFLOAT(lat, lon): # called in linearInterpolation, shape (2,), lat first then lon lat = str(lat) lon = str(lon) lom = -1 if lon[-1] == 'W' else 1 lat = float(lat[:-1]) lon = float(lon[:-1]) lon = lon * lom return lat, lon def getTimeIndex(lon, lat): n = 3600 m = 72...
The code processes satellite HDF files to extract and combine multispectral and thermal bands, identifies the closest temporal match to given path data, interpolates coordinates, extracts a target area, and saves it as a NumPy file while removing the original HDF file.
def post_processing(folder, params, day): radius = 10 curr_files = glob(folder + "*.hdf", recursive = True) if len(curr_files) == 0: return curr_file = curr_files[0] print ('found ', curr_file) hdf = SD(curr_file) # first day of hurricane sandy for it in hdf.datas...
def generate_modis_url(datestr): ''' compose url using date 'YYYY.MM.DD' ''' url = 'https://e4ftl01.cr.usgs.gov/MOLT/MOD09CMG.006/'+ datestr[0:4] + '.' + datestr[4:6] + '.'+ datestr[6:8] + '/' return url def download_file(folder, url, filename): username_file = open("/home/fun/profil...
The code downloads MODIS satellite data for specific dates and coordinates from a JSON profile, ensuring daily downloads only once. It processes lat/lon values, generates URLs, retrieves files, and performs post-processing.
def download_modis(folder): json_profile = folder + '/profile.json' json_file = open(json_profile) d = json.load(json_file) current_date = None for it in d['path']: print(it) # only download once per day as modis satelite is daily if it['date'] == current_date: co...
def url_html_decoder(raw_url: str) -> str: ''' Replaces all HTML encodings with their corresponding character to give the decoded URL string Args: raw_url (str): The original full url Returns: decoded_url (str): The decoded url Examples: >>> url_html_decoder('http://e....
The code's main task is to parse a URL into structured components: protocol, domain, path, and arguments. It decodes the URL, splits it into parts, processes domains and paths (with optional token expansion or reversal), and returns them as a 4-tuple. The function handles URL normalization, tokenization, and parameter ...
def url_tokenizer(url: str, expand_tokens: bool = False, reverse_path: bool = False) -> UrlData: ''' Takes a url as a string and returns a 4-tuple of the processed protocol, domains, path and arguments. Args: url (str): Full url of webpage expand_tokens (bool): Whether...
def ask_add(): return prompt(QUESTIONS['add'], style=CLI_STYLE)['add'] == True def ask_name(): return prompt(QUESTIONS['input'], style=CLI_STYLE)['input'] def ask_type(): return prompt(QUESTIONS['type'], style=CLI_STYLE)['type'] def ask_values(): values = [] while ask_value_add(): value = as...
The main task of the code is to collect user-input questions, including their type and optional choices, and save them in a list. It repeatedly prompts the user to add questions, gathers details like name, type, and values, constructs each question using `build_question`, and stores them in the `questions` list. Finall...
def main(): questions = [] while ask_add(): name = ask_name() qtype = ask_type() if qtype == QUESTION_TYPES['choice']: values = ask_values() else: values = [] questions.append(build_question(name, qtype, values)) save(questions)
def handle_nationality(self, value): nationality = filter_string(value) self.user_data['nationality'] = nationality[0].upper() + nationality[1:].lower() auth_user = self.user_authentications() return self.response def handle_id_type(self, value): id_type = filter_string(value) ...
The code processes an entity-object by standardizing its entity name and routing it to specific handlers (e.g., nationality, ID types/numbers, OTP) based on the standardized value. It extracts 'entity' and 'value' from the input, checks their standardized form, and calls corresponding methods like `handle_nationality`,...
def handle_match(self, entity_obj): if 'entity' in self.entity_obj: entity = self.entity_obj['entity'] value = self.entity_obj['value'] else: for entity, value in self.entity_obj.items(): entity = entity value = value p...
def predict_response(self, query): prompt_template = Auth_Prompt_Template self.chain = prompting_selction(prompt_template, self.llm) return self.chain.predict(input=query) def handle_match(self, entity_obj): if 'entity' in self.entity_obj: entity = self.entity_obj['entity'] ...
The main task of the code is to process a query by generating a response, extract entities and their values from the response in dictionary format, handle entity matches, map authentication responses, and return the original generated response. It involves LLM prediction, entity extraction, error handling, and response...
def user_auth_chain(self): self.response = self.predict_response(self.query) self.llm_response.append(self.response) try: self.response_1 = self.predict_response('just extract the entity and its value in a dictionary format {"entity": , "value":, } from the following response ' + se...
def route_chain(self): self.dist = chain_selection(self.llm, self.query) self.selected_prompt = all_prompts_temp[all_prompts_names.index(self.dist)] self.entity_types.append(entity_list[all_prompts_names.index(self.dist)]) self.json_structure.append(jsons_structures[all_prompts_names.in...
The code manages user authentication and workflow progression by evaluating flags. It routes through different chains (authentication, exploration) based on OTP validation status and whether exploration has been initiated, ensuring proper sequence of operations before returning the response.
def run(self): self.query = self.query if self.query == "quit": return if self.flags['otp_vallidated'] and not self.flags['explore_chains']: self.route_chain() self.flags['explore_chains'] = True if not self.flags['otp_vallida...
def fetch_modified_node_keys(self): models = self.fetch_modified_object_keys(object_type="model") seeds = self.fetch_modified_object_keys(object_type="seed") tests = self.fetch_modified_object_keys(object_type="test") modified_node_keys = models + seeds + tests return modified_no...
The main task of the code is to generate a views file by processing modified nodes. It fetches modified node keys, parses their manifest, retrieves required references, compiles production and PR job names from these references, and finally creates the views file using these compiled names.
def main(self): modified_node_keys = self.fetch_modified_node_keys() modified_nodes = self.parse_manifest_for_nodes(modified_node_keys) refs = self.fetch_required_refs(modified_nodes) prod_names = self.compile_ref_production_names(refs) pr_names = self.compile_pr_job_names(refs, ...
def ProbData_GivenCategory(self, _category): probability = 1 category_df = self.create_subset(_category) category_df_length = len(category_df.index) for column in self.feature_columns: # test_value is the cell in the first row of the test set at the given column t...
The function calculates the conditional probabilities of each category given a test data point using maximum likelihood estimation. It computes the likelihood of the test data under each category, combines it with the category's prior probability (from the training data), and returns the resulting probabilities as a fo...
def max_liklihood_conditional_classification(self): final_string = "" GivenData_Divided_By_Alldata = 0 total_row_count = len(self.training_set.index) # get all unique categories in the category column category_col = self.category_column categories = self.training_set[c...
def gpt3_embedding(content, engine='text-embedding-ada-002'): content = content.encode(encoding='ASCII',errors='ignore').decode() response = openai.Embedding.create(input=content,engine=engine) vector = response['data'][0]['embedding'] return vector def timestamp_to_datetime(unix_time): return datet...
The main task of the code is to save user input and generated AI responses with metadata (timestamp, embeddings, etc.) into JSON files, retrieve conversation memories, summarize them, and use GPT-3 to generate a response based on the conversation history and summarized memories, then store the output similarly.
def save_longterm_memory(text): timestamp = time() vector = gpt3_embedding(text) timestring = timestamp_to_datetime(timestamp) message = '%s: %s' % ('USER',text) info = {'speaker': 'USER', 'time': timestamp, 'vector': vector, 'message': message, 'uuid': str(uuid4()), 'timestring': timestring} fi...
def _set_initial_direction(self, row, col): """ Helper Method, Determines which way to set the direction based on the starting position (to determine what conditions to use for _set_direction). These are determined by the following using the notation (row, col): - 'down' - move...
The function `shoot_ray` simulates a ray moving on a grid from an edge position, handling interactions with atoms and boundaries. It checks validity of the starting position, tracks entry/exit points, and updates the player's score based on hits, reflections, or exits. The ray moves step-by-step, adjusting direction up...
def shoot_ray(self, row, col): """ shoots a ray starting from (row, col) that moves according to the following rules: 1. a ray moves forward one step at a time in its direction until either: a. it encounters an exit point in its path b. it encounters an atom in its path -...
def UAndxFilesSelected(oneTFile): """ :param oneTFile: one T directory :return: U files and x files to be parsed """ smrFile=oneTFile+"/summary.txt" same, loopNumBeforeEq,lag,lastFileNum=parseSummaryBeforeEq(smrFile) fileAfterEqList,loopNumAfterEq=parseAfterEqFile(oneTFile) fileNumSele...
The function combines U and x data vectors from multiple files into concatenated arrays. It parses selected U files, appends their values into a single vector, and similarly combines x files using numpy's r_ concatenation. It returns the combined U vector, combined x matrix, along with parameters like 'same', 'lag', an...
def combineValues(oneTFile): """ :param oneTFile: corresponds to one temperature :return: combined values of U and x from each file, names of the parsed files """ same, retUAllFileNames,retxAllFileNames,lag,fileNumSelected=UAndxFilesSelected(oneTFile) UVecValsCombined=parseUFile(retUAllFileNa...
def input(self): events = pg.event.get() if Input.quit(events) or Input.escape(events): self.done = True pg.quit() else: new_direction = Input.direction(events, self.snake.direction) self.snake.direction = new_direction def collisions(self): ...
The main task of the code is to update the game state when active, handling input, snake movement, collision checks, and score updates. If the game is not active, it triggers the end input process. The function checks if the game is done or active to determine which actions to execute, ensuring proper game progression ...
def update(self): if self.done: return if self.active: self.input() self.snake.move() self.collisions() self.update_score() else: self.end_input()
def check2(self, a): if len(str(a['Contents'].to_list())) > (4000 - 1040): #print("checking 2") a = a.iloc[:-2] self.check2(a) return def predict_large(self, text, stress = False): '''signal.signal(signal.SIGALRM, self.signal_handler) signal.alarm(2) ...
The code processes a large dataset in chunks (size `rpq=20`) to predict emotional or stress labels recursively. It splits the input `data` into segments, applies the `predict_large` method to each chunk, and appends results to `df_list`. If processing time is under 60 seconds, it pauses to avoid overloading. The functi...
def predict_large_recurse(self, data, count = 0, df_list = [], rpq = 20, stress = False): #warnings.filterwarnings("ignore") a = None rpq = 20 '''len(data) // 20 + 1 if (rpq > 31): rpq = 31''' #print(rpq) for i in range(20): if len(data) <=...
def num_msgs(self) -> dict: nums = {channel:len(self.filter_period(channel)) for channel in self.channels.objects} return {'nums': nums, 'max': max(nums, key = nums.get)} def plot_msgs(self): df = self.daily_count() plt.figure() plt.plot(df.index, df[0]) plt.title('Mess...
The code's main task is to analyze and visualize messaging data by displaying the selected time period, listing channels, ranking messages by count, and generating plots for message counts, word clouds, and emoji frequencies. It interacts with the console to present structured data summaries and visualizations.
def analyze(self):# interacts with the console # show time perod e, l = self.period print(f"Time period of {e} to {l}.") print() # show channels print("The channels considered are the following:") print() for channel in self.channels.objects: p...
def initialize_parameters(layers_dims): parameters = {} L = len(layers_dims) for l in range(1, L): parameters['W' + str(l)] = np.random.randn(layers_dims[l], layers_dims[l-1]) * np.sqrt(2/layers_dims[l-1]) parameters['b' + str(l)] = np.zeros(shape=(layers_dims[l], 1)) return parameter...
This function implements a deep neural network with Adam optimizer, mini-batch gradient descent, and L2 regularization. It trains the network over multiple epochs, updating parameters via backpropagation, computes training cost, and evaluates test accuracy. The learning rate decays over time, and Adam's momentum terms ...
def NeuralNet(X, Y, X1, Y1, layer_dims, mini_batch_size = 128, num_epochs = 1000, learning_rate = 0.001, lambd = 0.5 ,beta1= 0.9 ,beta2 = 0.999 ,epsilon =1e-8 ): """Implements The Complete Deep Neural Network.""" test_set_len = len(Y1) t = 0 parameters = initialize_parameters(layer_dims) v, s = init...
def _generate_mushroom_units(self): """ Generate mushroom units for each player. """ for ( player_name, player, ) in self._players.items(): # Iterate over players self._output_buffer.append(f"Player {player_name} spawn units") # Sp...
The main task of the code is to initialize and configure the game board by generating mushroom units, updating their information, placing food items, and deep-copying the food data into the board's info structure for proper state management and rendering.
def populate_board(self): self._generate_mushroom_units() self.update_mushroom_units_info() self._place_food() self.info.food = copy.deepcopy(self._food)
def _move_mushroom_unit(self, command: MoveCommand) -> None: """ Move the mushroom unit of a player based on the command. Args: command (MoveCommand): The command containing the ID of the mushroom unit and the direction to move. """ mushroom_unit = self._find_mushroo...
The main task of the code is to compute the next game state by executing player commands (MoveCommand/BranchCommand) in random order, updating mushroom positions, splitting units, calculating scores, placing food, and advancing the round. It shuffles commands, processes them, updates game elements, and increments the r...
def next(self) -> None: """ Perform the actions to compute the next state for the next round. """ self._output_buffer.append(f"{self.round}") commands = list() for _, player in self._players.items(): for c in player.commands_to_perform: command...
def RatioOfNV(column): ratio = [0]*len(column) quadraticSum = 0.0 for i in range(len(column)): quadraticSum += column[i]*column[i] for j in range(len(column)): ratio[j] = column[j]/(math.pow(quadraticSum, 0.5)) return ratio def distanceValue(mu1, mu2): distanceV...
The code calculates and ranks alternatives based on four input parameters (ESCM, LCM, Cost-Benefit Ratio, Incremental Cost) using a weighted distance-based aggregation method. It computes normalized ratios for each parameter, constructs a matrix of transformed values, calculates pairwise distances, derives dynamic weig...
def alcoa(escm,lcm,cbr,ic): # column1 = [4.3817,4.0348,4.5797,4.5733,4.7176,4.4397,4.4382,4.5529,4.5990]#ESCM # column2 = [2.5490,2.5573,4.7917,2.5533,3.0298,3.8890,1.5092,0.6985,2.0626]#LCM # column3 = [0.3336,0.3712,0.2262,0.1826,0.3494,0.2594,0.2058,0.3633,0.3880]#Cost-benefit ratio # column4 = [35.5...
def rule_validation(df, rules, final_flag=False, n_cores=core_number): """Validate the rule matching performance. With test dataset, test the classification performance globally in a loop manner. Args: df: dataframe to be validated. rules: rules for sample matching. final_flag: ter...
The main task of the code is to iteratively extract, refine, and validate classification rules for detecting malicious instances in a dataset. It uses seed rules generated from labeled data, reinforces them through validation loops, and improves accuracy by re-extracting rules from unmatched samples. The process termin...
def rule_matching_evaluation(df, model, seed_num, rein_num, eval_num, label_map, refer_label, lime_flag=True, scan_flag=False , content_direction='forward', xcol_name='text', n_cores=20): """A integrated rule extraction, refinement and validation process. On the dataset, sample base...
def get_tags_from_file_name(file_name): """ :Authors: Ian Copland :param file_name: A file name. :returns: The tags in the file name, or an empty string if there isn't one. """ if file_name.count('.') > 1: first = file_name.find(".") last = file_name.rfind(".") ...
The function processes PNG files in the input directory, grouping them by "resource tags" (e.g., "low" or "high" from filenames) and generating separate texture atlases for each group. It iteratively selects files with matching tags, builds an atlas for them, and removes processed files until all PNGs are grouped and a...
def build_altases_in_directory(input_directory_path, output_directory_path, file_names): """ Builds each of the different atlases in the given directory. Different atlases are build for assets with different "resource tags", i.e Image.low.png and Image.high.png would end up on different texture atlases....
def write_header(time, planet_radius, inner_radii, outer_radii, opacities, inclination, tilt, impact_parameter, dt, limb_darkening, transverse_velocity, merge_fraction, max_ringlets, title, filename): ''' This function writes the header to a text file that will...
The `ring_fitter` function fits a ring system to a light curve by dividing a disk into increasing numbers of ringlets, optimizing their opacities, and merging them based on a merging factor. It adds noise to the light curve, iterates over specified ringlet counts, and saves results (including radii, opacities, and chi2...
def ring_fitter(noise_fraction, num_ringlet_array, time, lightcurve, planet_radius, disk_radius, initial_opacities, inclination, tilt, impact_parameter, dt, limb_darkening, transverse_velocity, merge_fraction, num_merges, extend_first, filename, title='', ...
def initialize(data): j = 9 for i in data: value(j,i) if i > 0: flag(j,1) j+=1 return True def startsolving(): i = 9 while i < 90: if not flag(i): best = getbestvalue(i,value(i)) if best: value(i,best) el...
The code processes a GET request to solve a puzzle by parsing input data, validating it with `initialize()`, executing `startsolving()`, and returning the solution as a JSON response with status and output values from 9 to 89. If invalid, it returns an error.
def solve(request): context = {} if request.method == 'GET': dataall = request.GET.getlist('data') data = dataall[0].split(',') for i in range(len(data)): data[i] = int(data[i]) print(data[i]) print(type(data[1])) if initialize(data): p...