content
stringlengths
22
815k
id
int64
0
4.91M
def page_not_found(e): """whatever you are looking for we don't have. Sorry""" return 'no, it is not here', 404
5,306,200
def read_pointmatchers(wfile): """ Read a file of PointMatcher definition lines, and return an ordered dict of (matcher, string2) pairs, where string2 is the rest of the line. """ import collections rtn = collections.OrderedDict() #< need to preserve order with open(wfile) as wf: for...
5,306,201
def analyze_two(group1_data, group2_data, n_samples: int = 2000, **kwargs) -> BestResultsTwo: """Analyze the difference between two groups This analysis takes about a minute, depending on the amount of data. (See the Notes section below.) This function c...
5,306,202
def runBacktesting(strategyClass, settingDict, symbol, startDate, endDate, slippage, rate, size, priceTick): """运行单标的回测""" engine = BacktestingEngine() engine.setBacktestingMode(engine.BAR_MODE) engine.setDatabase(MINUTE_DB_NAME, symbol) engine.setStartDate(st...
5,306,203
def format_kvps(mapping, prefix=""): """Formats a mapping as key=value pairs. Values may be strings, numbers, or nested mappings. Nested mappings, e.g. host:{ip:'0.0.0.1',name:'the.dude.abides'}, will be handled by prefixing keys in the sub-mapping with the key, e.g.: host.ip=0.0.0.1 host.name=the....
5,306,204
def load_input(filename): """ :param filename: A string representing a text. :return: A set of words representing the text. """ text = filename.lower().replace('?', ' ').replace('!',' ').replace('.',' ').replace('-',' ').replace(':',' ').replace(';',' ').replace(',',' ').replace('(',' ').replace(')',' ').replace('...
5,306,205
def _get_merged_mapping( to_keep_ids: np.ndarray, label_rule_masks: Iterable[np.ndarray], number_of_labels: int, make_sparse: bool ) -> np.ndarray: """ Creates a rule-to-label mapping matrix according to the rules selected for reduction. Returns: Mapping array of shape M (depends of #labels affected by ...
5,306,206
def test_duration_progress_duration_done(progressbar): """We have a duration of 1 but then terminate immediately So we have a bar.next() call, then we update as we're done early and then `if not is_done()` is not called so func terminates """ duration_progress('activity', 1, lambda: True) ...
5,306,207
def success_popup(): """ Creates a popup window containing the words 'Successfully Downloaded!' when the processing of data is complete. """ parentgui = Tk() root.title("Oil Database query tool") maingui = ttk.Frame(parentgui,width=300,height=100) maingui.grid() quadrant_lbl = ttk.Label...
5,306,208
def get_projection_profile(binary_image): """ Parameters ---------- binary_image: numpy.ndarray The binary image to be projected. Returns ------- projection_profile: numpy.ndarray A binary image representing the projection_profile. """ chunk_percentage = 0.05 chu...
5,306,209
def make_postfix_public(): """Make sure postfix accepts connections from outside. Takes care to - restart postfix if necessary - document all the changes in the changelog """ with quiet(): current_setting = run("postconf -h inet_interfaces") if current_setting == 'loopback-only': ...
5,306,210
def test_overwrite_rogue_tag_multiple_remotes(cli, tmpdir, datafiles): """When using multiple remotes in cache (i.e. when using aliases), we need to make sure we override tags. This is not allowed to fetch tags that were present from different origins """ project = str(datafiles) repofiles = o...
5,306,211
def project(meta_weights, P, Q): """ project meta_weights to sub_weights Args: meta_weights: a 4-D tensor [cout, cin, k, k], the meta weights for one-shot model; P: a 2-D tensor [cout, cout_p], projection matrix along cout; Q: a 2-D tensor [cin, cin_p], projection matrix along cin; Return: proj_we...
5,306,212
def make_move(board, player, alpha, beta, depth, idepth): """ :param board: A simplified version of the current board :param player: The player the algorithm is playing as (Can only be an instance of Player) (Note: the function maximises for the computer and minimises for the play...
5,306,213
def _endx(parents, n_gene): """Extended Normal Distribution Xover""" ALPHA = (1.-2*0.35**2)**0.5/2. BETA = 0.35/(n_gene-1)**0.5 child = np.empty(n_gene+1) t1 = (parents[1, :n_gene]-parents[0, :n_gene])/2. t2 = np.random.normal(scale=ALPHA)*(parents[1, :n_gene]-parents[0, :n_gene]) t3 = np....
5,306,214
def main(): """Console script for condastats.""" parser = argparse.ArgumentParser() subparsers = parser.add_subparsers(dest='subparserdest') parser_overall = subparsers.add_parser('overall') parser_overall.add_argument("package", help="package name(s)", ...
5,306,215
def query_handler(update: Update, ctx: CallbackContext) -> None: """ Handler responsible to call list function when buttons are pressed """ query = update.callback_query.data [cmd, *args] = query.split(" ") if cmd == "list": task_lister(update, ctx, args)
5,306,216
def AddClientNameAndVersionFlags(parser): """Add flags for specifying the client name and version annotations.""" parser.add_argument( '--client-name', hidden=True, help="Name of the client handling the deployment. Defaults to ``global'' " 'if this and --client-version are both unspecified.'...
5,306,217
def Trappist1PlanetPorbSample(planet, size=1, **kwargs): """ Sample Trappist1 system planet Porbs from Gaussian distributions based on Gillon+2017, Luger+2017 measurements. """ # Light preprocessing of planet name name = str(planet).lower() ret = [] for ii in range(size): if na...
5,306,218
def apply_stat_changes(unit, stat_changes: dict): """ Assumes stat changes are valid! """ old_max_hp = unit.get_max_hp() old_max_mana = unit.get_max_mana() # Actually apply changes for nid, value in stat_changes.items(): unit.stats[nid] += value current_max_hp = unit.get_max_hp...
5,306,219
def com_in_limb_effector_frame_constraint(Robot, transform, limbId): """ Generate the inequalities constraints for the CoM position given a contact position for one limb :param Robot: :param transform: Transformation to apply to the constraints :param limbId: the Id of the limb used (see Robot.limbs...
5,306,220
def test_point_not_in_room(rectangle, big_area): """ Test that contains point returns false when point is not in room """ new_room = Room(rectangle, 0, 1, 1, big_area, 'bathroom') point = (0, 15, 15) assert new_room.contains_point(point[0], point[1], point[2]) is False
5,306,221
def test_update_recipe_multiple_fields(client): """Test updating multiple fields of a recipe""" id=2 update = {"title": "Marmalade Cake", "marketing_description": "A modern take on sponge cakes", "calories_kcal": 10000} update_field(client, id, update)
5,306,222
def get_weth(account=None): """Mints WETH by depositing ETH.""" print(f'Active network: {network.show_active()}') my_wallet_address = (account if account else accounts.add(config["wallets"]["from_key"])) my_balance = my_wallet_address.balance() print(f'My wallet address: {my_wallet_address}') p...
5,306,223
def _data_block(mode, names_and_jsons, output_dir, include_gene_sets=True, organism="human"): """ """ data_block = [] if mode == "directory": (output_dir / "data").mkdir(exist_ok=True, parents=True) for name, json in names_and_jsons: (output_dir / "data" / f"{name}.js").wr...
5,306,224
def lj_sanity_test(): """Sanity test to make sure we even have the plugin fixtures installed.""" return "sanity"
5,306,225
def randomString(length, chrs=None): """Produce a string of length random bytes, chosen from chrs.""" if chrs is None: return getBytes(length) else: n = len(chrs) return ''.join([chrs[randrange(n)] for _ in range(length)])
5,306,226
def generateResidueTemplate(molecule, residue_atoms=None, normalize=True, gaff_version='gaff'): """ Generate an residue template for simtk.openmm.app.ForceField using GAFF/AM1-BCC. This requires the OpenEye toolkit. Parameters ---------- molecule : openeye.oechem.OEMol The molecule to ...
5,306,227
def getImage(update, context): """Download image sent by user""" logging.debug(f'Step 1: enter function') data = update.to_dict() try: photo = data['message']['photo'][-1] file_id = photo['file_id'] logging.debug(f'Step 1: file_id {file_id}') url = f'https://api.telegram...
5,306,228
def test_exact_num_points_for_chunks(num_chunks, chunk_size): """Checks that the chunk generation works well with just enough points.""" labels = gen_labels_for_chunks(num_chunks, chunk_size) constraints = Constraints(labels) chunks = constraints.chunks(num_chunks=num_chunks, chunk_size=chunk_size, ...
5,306,229
def test_eigenvals( configure_with_daemon, # pylint: disable=unused-argument sample, get_tbmodels_process_builder ): """ Test that the eigenvals calculation creates a bands output. """ builder = get_tbmodels_process_builder('tbmodels.eigenvals') builder.tb_model = DataFactory('singlefi...
5,306,230
def compute_vertex_normals(points, trilist): """ Compute the per-vertex normals of the vertices given a list of faces. Parameters ---------- points : (N, 3) float32/float64 ndarray The list of points to compute normals for. trilist : (M, 3) int16/int32/int64 ndarray The list...
5,306,231
def clean_up(lines): """ Get rid of all non-text lines and try to combine text broken into multiple lines """ new_lines = [] for line in lines[1:]: if has_no_text(line): continue elif len(new_lines) and is_lowercase_letter_or_comma(line[0]): #combine with previous line new_lines[-1...
5,306,232
def create_spark(): """ Method to create Spark Context Returns: ----- sc : pyspark.SparkContext """ conf = SparkConf()\ .setAppName(APP_NAME)\ .setMaster("local[4]")\ .set("spark.executor.memory", "4g")\ .set("spark.executor.cores", "4")\ .set...
5,306,233
def misc_computations(fsu): """ I forgot what these were for """ fsu['nb_tails'] = fsu.groupby('TAIL')['id'].transform('size') fsu['earliest_dep'] = fsu.groupby('TAIL')['SCH_DEP_TMZ'].transform('min') st.write(fsu[['id','nb_tails']]) # It appears that the first flight of each tail is an inbo...
5,306,234
def main(): """ User give 3 inputs (a, b, and c) for a quadratic equation: ax^2 + bx + c = 0. Coder will find the solutions of x for that quadratic equation. """ print('stanCode Quadratic Solver!') # ax^2 + bx + c = 0 a = float(input('Enter a: ')) b = float(input('Enter b: ')) c = float(input('Enter c: ')) # ...
5,306,235
def get_saved_posts_subreddits(in_dictofposts): """ loop thru a given list or dict of posts, return a dict of those posts unique subreddits where key is subreddit name, value is subreddit object""" subreddits = dict() for post_id,post in in_dictofposts.items(): # post.subreddit_id will look somethin...
5,306,236
def win_mutex(name: str, for_self=False, ranks: Optional[List[int]] = None): """ A win object implemented mutex context manager. Note, there are N distributed mutex over N corresponding processes. Args: name: Used to get the mutex for the window that registered by name. ranks: The mutex ass...
5,306,237
def binary_size(pull_request, log, metrics_service_url, access_token): """Produces and uploads binary size reports.""" gradle.run('assembleAllForSmokeTests') affected_artifacts, all_artifacts = _parse_artifacts() artifacts = affected_artifacts if pull_request else all_artifacts sdks = ','.join(artifacts) ...
5,306,238
def process_polygon_dictionary(polygon_dict, load_license_plates=False): """Processes and mutates the polygon_dict, this function will convert and remove the objects field to result in the following format after execution: polygon_dict = { "imgHeight" : (int:...
5,306,239
def _is_not_blank(line): """Return true if `line` is not blank.""" return len(line.split())>0
5,306,240
def onMayaDroppedPythonFile(*args, **kwargs): """ This function is only supported since Maya 2017 Update 3 """ pass
5,306,241
def main(): """The main function of this module.""" file_count = len(sys.argv) - 1 if file_count < 1: sys.stderr.write('Usage: %s file1 [file2 ...]\n' % sys.argv[0]) sys.exit(1) for i in range(file_count): filename = sys.argv[i + 1] print('File: %s' % filename) ...
5,306,242
def list_replicas_to_delete(pointers, host="metadata", port=6379): """ List the blocks that match the given threshold Args: pointers(int): The minimum number of documents pointing to a block for the block to be considered for scrubbing host(str, optional): The host met...
5,306,243
def tstRGB_HSV_RGB(): """ RGB to HSV back to RGB full range test """ report.write("\n*** RGB->HSV->RGB test ***") nberr = nbt = 0 random_pick = unit_tests.RandPickInRange(100000, 500000) for rtst, gtst, btst in itertools.product(range(256), range(256), range(256)): nbt += 1 colHSV = ...
5,306,244
def _is_route_exists(dst): """Return True if destination (IP address/network prefix length, e.g. "10.1.0.1/30") belongs to any network configured on the OS interfaces.""" route_list = _ipr.get_routes(family=socket.AF_INET) for route in route_list: edst = "%s/%d" % (route.get_attr("RTA_DST")...
5,306,245
def residue_reduce(a, d, DE, z=None, invert=True): """ Lazard-Rioboo-Rothstein-Trager resultant reduction. Given a derivation D on k(t) and f in k(t) simple, return g elementary over k(t) and a Boolean b in {True, False} such that f - Dg in k[t] if b == True or f + h and f + h - Dg do not have an ...
5,306,246
def apply_l2_weight_decay( learning_rate_fn: optax.Schedule, l2_regularizer_weight: Optional[float] = 0. ) -> ShardedGradientTransformation: """Applies L2 weight decay. Args: learning_rate_fn: An optax schedule that infers the lr given the step. l2_regularizer_weight: Weight for L2 regularization. ...
5,306,247
def map_click(cube, index=2.03, figsize=(12, 6), lon_min=0, lon_max=360, lat_min=-90, lat_max=90, bg='VIMS_ISS', ): """Interactive equirectangular projected map.""" pixels = [] fig, ax = plt.subplots(1, 1, figsize=figsize) fig.subplots_adjust(righ...
5,306,248
def overlaps(box1, box2): """ Checks whether two boxes have any overlap. Args: box1: (float, float, float, float) Box coordinates as (x0, y0, x1, y1). box2: (float, float, float, float) Box coordinates as (x0, y0, x1, y1). Returns: bool ...
5,306,249
def process_data(data): """ This function processes the data in the data dictionary """ for c_idx in range(10): for b_idx in range(BMAX): data[c_idx][b_idx]["st_means"] = [] for station in data[c_idx][b_idx]: # Calculate the mean per station ...
5,306,250
def hashInt(bytebuffer): """ Map a long hash string to an int smaller than power(2, 31)-1 """ import binascii hex_dig = binascii.hexlify(bytebuffer) return int(hex_dig, 16) % 2147483647
5,306,251
def scatter_(mat: T.Tensor, inds: T.Tensor, val: T.Scalar) -> T.Tensor: """ Assign a value a specific points in a matrix. Iterates along the rows of mat, successively assigning val to column indices given by inds. Note: Modifies mat in place. Args: mat: A tensor. inds: ...
5,306,252
def _ts_ema(x1, d: int): """exponential moving average (EMA)""" alpha = 2 / (d + 1) return __rolling(pd.Series(x1), d, function=__scalar_ema, alpha=alpha)
5,306,253
def write_files(directory, entries, organize): """Write a list of file entries to a directory.""" # (filename, data) bad_entries = [] # Get absolute path, just in case working directory changes. directory = os.path.abspath(directory) # Make top-level. os.makedirs(directory, exist_ok=True) ...
5,306,254
def vs_code(): """报名表下载页面""" if request.method == 'GET': return render_template("vs_code.html") elif request.method == 'POST': form = request.form valid_code = form.get("valid_code") ad = Admin.query.filter_by(name="admin").first() if ad.valid_code == valid_code: ...
5,306,255
def nm_004448_coding_dna_delins(erbb2_context): """Create test fixture for NM_004448.4:c.2326_2327delinsCT.""" params = { "id": "normalize.variation:NM_004448.4%3Ac.2326_2327delinsCT", "type": "VariationDescriptor", "variation_id": "ga4gh:VA.eMxxAEjNduAvg5U3eBZxf0nLtfcMNxqy", "va...
5,306,256
def extend(dst, *args): """Recursively update a dictionary. Parameters ---------- dst : `dict` Dictionary to update. *args : `dict` Returns ------- `dict` Updated dictionary. Examples -------- >>> extend({'x': {'y': 0}}, {'x': {'z': 1}}) {'x': {'y': 0, ...
5,306,257
def list_saved_reply_ids(wrapped): """ Decorator for handling API calls that take as input a list of saved reply ids. Calls the wrapped function with the parsed saved reply ids selected by the API user. """ @wraps(wrapped) def decorated(request, *args, **kwargs): if 'savedreplyids' i...
5,306,258
def update_subscribers_for_bloodtype( context: CallbackContext, diffs, bloodtype: str, current_time ): """ For specific updates on specific bloodtypes. Don't send them this update if they are already subscribed to "any" """ diffs_str = diffs_with_bloodtype_to_str(diffs, bloodtype, current_time) ...
5,306,259
def test_predict_response(): """ Tests POST request response for predict function when successful against a sample """ data = { 'age': 38, 'fnlgt': 15, 'education_num': 1, 'capital_gain': 0, 'capital_loss': 0, 'hours_per_week': 5 } resp...
5,306,260
def main(cifs, centres, **kwargs): """ Process all supplied cif files using options supplied as kwargs (or defaults). Returns phases : Dict Dictionary of Crystal objects (containing ellipsoid results), keyed by CIF name. plots : dict or dicts, optional Diction...
5,306,261
def _compute_bleu(reference_corpus, translation_corpus, max_order=4, smooth=False): """Computes BLEU score of translated segments against one or more references. Args: reference_corpus: list of lists of references for each translation. Each reference should be tokenized into a list of tokens...
5,306,262
def poly_area(x,y): """ vectorized implementation of shoelace formula. inputs x (ndarray) : x coordinates of polygon y (ndarray) : y coordinates of polygon type : 'green' or 'shoe' indicating either using greens theorem or the shoelace formula returns area (float) : area of...
5,306,263
def print_table(rules, table_style='unicode', local_address=[], hide_src=False, hide_dst=False, hide_nats=False, hide_filters=False, projection=[], aliases={}): """Print a list of rules into a table, dividing filters and nats and optionally hiding local addresses""" def ...
5,306,264
def fixture_environment(template_loader: jinja2.BaseLoader) -> jinja2.Environment: """Setup an environment similar to what Salt does. See https://github.com/saltstack/salt/blob/master/salt/utils/templates.py#L406-L476 """ env = jinja2.Environment( loader=template_loader, extensions=[ ...
5,306,265
def test_multi_round_trip(potcar_family, tmp_path): """Write multiple POTCAR potentials to a file and recover the nodes stored in the db.""" test_dir = tmp_path / 'round_trip' test_dir.mkdir() potcar_cls = get_data_class('vasp.potcar') multi = MultiPotcarIo(potcar_cls.get_potcars_dict(elements=POTCA...
5,306,266
def try_import_tvm(): """Try import tvm at runtime. Returns ------- tvm module if found. Raise ImportError otherwise """ msg = "tvm is required, for installation guide, please checkout:\n \ https://tvm.apache.org/docs/install/index.html" return try_import('tvm', msg)
5,306,267
def make_combined_table(array_rows): """ Build a table of tables Args: array_rows (list(list)): Array of tables rows to combine Returns: str: string representing table """ if IS_NOTEBOOK: # compute the size for each col col_size = str(int(100 / len(array_rows)) - 5)...
5,306,268
def apply_precession(ra, dec, years) : """ see DESI-4957 Equator and zero longitude point glide westward at 0.0139 deg/year, so.. Star ecliptic longitudes increase +0.0139 deg/year from combined lunar and solar torques on the Earth. To precess any sta'’s {RA,DEC}: 1. Convert to ecliptic coordina...
5,306,269
def fourier_basis(freq): """ sin and cos Formula for Fourier drift The Fourier basis consists of sine and cosine waves of given frequencies. Parameters ---------- freq : sequence of float Frequencies for the terms in the Fourier basis. Returns ------- f : Formula Exam...
5,306,270
def get_gene_sets(species, use_kegg_ids=False, use_name=True): """Gets mapping from gene ids to pathways as genesets. Args: species (str): Name of the species to query. Use or example 'hsa' for human or 'mmu' for mouse. use_kegg_ids (bool): Whether to return gene ids as entrez ...
5,306,271
def guardarImagen(nameFile, img): """Save an image""" cv2.imwrite(nameFile, img)
5,306,272
def registration(request): """Render the registration page""" if request.user.is_authenticated: # User is already registered, so no point to be on registration page. return redirect(reverse('index')) if request.method == "POST": # Check of the method is post. If so instantiate the ...
5,306,273
def likelihood(grid_pred, timed_points, minimum=1e-9): """Compute the normalised log likelihood, :math:`\frac{1}{N} \sum_{i=1}^N \log f(x_i)` where the prediction gives the probability density function :math:`f`. :param grid_pred: An instance of :class:`GridPrediction` to give a predict...
5,306,274
def get_data_iters(dataset, batch_size, opt): """get dataset iterators""" if dataset == 'mnist': train_data, val_data = get_mnist_iterator(batch_size, (1, 28, 28), num_parts=kv.num_workers, part_index=kv.rank) elif dataset == 'cifar10': train...
5,306,275
def to_sendeable_block_original_bus(array_of_msgs): """Given an array of msgs return it in the format panda.can_send_many expects. Input looks like: [(512, bytearray(b'>\x80\x1c'), 0), ...] Output looks like: [(512, '>\x80\x1c', 0), ...] """ new_arr = [] for msg in array_of_msgs: ne...
5,306,276
def _get_support(parts): """Retrieve supporting information for potentially multiple samples. Convert speedseqs numbering scheme back into sample and support information. sample_ids are generated like 20 or 21, where the first number is sample number and the second is the type of supporting evidence. ...
5,306,277
def extractColorRamp(color_ramp): """Make a curve from color ramp data""" # for uniformity looks like a glTF animation sampler curve = { 'input' : [], 'output' : [], 'interpolation' : ('STEP' if color_ramp.interpolation == 'CONSTANT' else 'LINEAR') } for e in color_ramp.ele...
5,306,278
async def test_status_failure(mock_datagram_client): """Test the wifi_status command failing.""" with mock_datagram_client: with pytest.raises(CommandError) as err: async with Client("192.168.1.100") as client: _ = await client.wifi.status() assert str(err.value) == ...
5,306,279
def DNSServiceEnumerateDomains( flags, interfaceIndex = kDNSServiceInterfaceIndexAny, callBack = None, ): """ Asynchronously enumerate domains available for browsing and registration. The enumeration MUST be cancelled by closing the returned DNSServiceRef when no more domains are ...
5,306,280
def _ring_fgroup_union(mol, tagged_rings, tagged_fgroups, wbo_threshold=1.2): """ This function combines rings and fgroups that are conjugated (the bond between them has a Wiberg bond order > 1.2) Parameters ---------- mol: OpenEye OEMolGraph tagged_rings: dict map of ringsystem indices...
5,306,281
def pytest_run(config, opts): """ Locally activate virtualenv and run tests with pytest """ testpath = config.test_where(opts.suite) command = ( '. ./{}/bin/activate && pytest {} {}'.format( config.venv_name(), testpath, opts.options ) ) ru...
5,306,282
def tokenize(text: str) -> List[str]: """Токенизация текста, пустые строки отбрасываются""" punctuation = "\\" + "\\".join(list("[](){}!?.,:;'\"\\/*&^%$_+-–—=<>@|~")) words = "[a-zA-Zа-яА-ЯёЁ]+" compounds = f"{words}-{words}" scr = "\\.{3}" tokenize_re = re.compile(f"({scr}|{compounds}|{words}|...
5,306,283
def pca(data, n_components = None, copy = True, whiten = False, svd_solver = "auto", tol = 0.0, iterated_power = "auto", random_state = None): """ Performs a principle component analysis on the input data. reference: https://scikit-learn.org/stable/modules/generated/sklearn.decomposition.PCA.html parameters: data...
5,306,284
def interpolate_cosine_single(start, end, coefficient): """ Cosine interpolation """ cos_out = (np.cos(np.pi*coefficient) + 1) / 2.0 return end + (start - end) * cos_out
5,306,285
def get_taken_books(): """ Get list of taken books :return: All books """ result = [] try: limit = int(request.args['pageSz']) except StandardError, err: app.logger.warning("get_books()->['pageSz' arg]: " + str(err)) limit = 0 try: page_num...
5,306,286
def solve(array): """ For less than 3 elements, just return the lenght of the array Else, solve the problem """ if len(array) < 3: return len(array) return longest_zigzag(array)
5,306,287
def process(url): """ Fetches news items from the rss url and parses them. Returns a list of NewsStory-s. """ feed = feedparser.parse(url) entries = feed.entries ret = [] for entry in entries: guid = entry.guid title = translate_html(entry.title) link = entry.link...
5,306,288
def show_toelichting(): """Generate footer """ st.subheader ("TOELICHTING") st.write ("This model is a very, very simplified version of the RIVM model,") st.write ("'Unique' of this model is that it has agegroups, keeps in account the contact rates between groups and the relative suspceptibility/in...
5,306,289
def test_entity_signal_then_call(): """Tests that a simple counter entity outputs the correct value after a sequence of operations. Mostly just a sanity check. """ # Create input batch batch = [] add_to_batch(batch, name="add", input_=3) add_to_batch(batch, name="get") context_builder =...
5,306,290
def build_feed_index(feed_objects, directory, header=None, hostname=None, port=70, sort=None, plug=True): """ Build a gophermap file in the specified directory, which presents an index for all the feeds in feed_objects. """ if not hostname: hostname = socket.getfqdn() decorated_m...
5,306,291
def _get_cfg(): """Gets the configuration for the resnet101 yaml file. Arguments: None Returns: cfg (config object): a configuration for the resnet """ _, fstrrcnn_dir = _set_dirnames() cfg_file = osp.join(fstrrcnn_dir, "cfgs", "res101.yml") return cfg_from_file(cfg_file)
5,306,292
def test_spdx_report() -> None: """Check there are no adverse findings on a well-covered package.""" from valiant.plugins.reports.spdx import SpdxLicenseReportPlugin from valiant.reports import FindingLevel from valiant.repositories.pypi import PyPiPackageMetadata from .data.basic_package import PA...
5,306,293
def server_cmd( ctx, host, port, output_path, prune, verbosity, extra_flags, build_flags, browse ): """The server command will launch a local server for development. Lektor's development server will automatically build all files into pages similar to how the build command with the `--watch` switch ...
5,306,294
def create_distance_callback(data, manager): """Creates callback to return distance between points.""" distances_ = {} index_manager_ = manager # precompute distance between location to have distance callback in O(1) for from_counter, from_node in enumerate(data['locations']): distances_[fro...
5,306,295
def JSONDataset(filenames, columns=None): """Start with JSON parser in python to add tests.""" jsondataset = [] jsondataset = JSONParser(filenames, columns) return tf.data.Dataset.from_tensor_slices(jsondataset)
5,306,296
def send_data_block(s, data): """Writes the given data to the given socket as a data block.""" message = b''.join([struct.pack("!I", len(data)), data]) #log.debug("sending data block length {} ({})".format(len(message), message[:64])) s.sendall(message)
5,306,297
def max_sub_array(nums): """Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.""" max_sum = float("-inf")# unbounded lower value # https://stackoverflow.com/questions/34264710/what-is-the-point-of-floatinf-in-python ...
5,306,298
def validate_vm_name(vm_name) -> bool: """ Checks that the vm name is valid. Args: vm_name: the name of the vm to check Returns: True if valid, else false. """ # we minus 3 for max length because we generate the rg using: "{vm_name}-rg" if len(vm_name) < 1 or len(vm_name) > (64 - 3): ...
5,306,299