content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import argparse def process_command_line_args(): """ Returns: tuple(str, str): Command line args for (config, output) files """ ap = argparse.ArgumentParser() ap.add_argument("-d", "--directory", required=True, help="Path to dot file directory") args = vars(ap.pars...
505e7fc47c06162fb2f1328882a59caa3b0539a2
3,616,300
def compute_coherence_values(dictionary, corpus, texts, limit, start=2, step=3): """ Compute c_v coherence for various number of topics Parameters: ---------- dictionary : Gensim dictionary corpus : Gensim corpus texts : List of input texts limit : Max num of topics Returns: --...
bcbf01aca76aea445e74ddbda9cf3facd8c44dd2
3,616,301
def on_launch(launch_request, session): """ Called when the user launches the skill without specifying what they want """ print("on_launch requestId=" + launch_request['requestId'] + ", sessionId=" + session['sessionId']) # Dispatch to your skill's launch return get_welcome_response()
9d0cd9c03b06e8b77dd702b80a7e217f1c4d2a68
3,616,302
def remove_comment(line): """Remove trailing comments from one line.""" start = 0 while True: loc = line.find('#', start) if loc == -1: return line.replace('\\#', '#') elif not (loc and line[loc - 1] == '\\'): return line[:loc].replace('\\#', '#') star...
e2ab53813efd17e00240f747709330c44c875235
3,616,303
import ee def GEEsmos(ptsFile,metric,timeStep,buf,poly,username,folderOut, scalePix = 25000,startYear = None,endYear = None): """ Calculates soil moisture at point OR mean within buffer of point if buf > 0 OR mean within polygon if poly = 1 Requires: ptsfile - file name of uploaded shapefile...
405641924be284e924285e872dd795beb9932df8
3,616,304
def sphinx_license(opts): """ Template of license.rst :param opts: mapping parameters as dictionary :return: file content as string """ template = get_template("sphinx_license") return template.substitute(opts)
b12a177497fd7b857dce04e9a59c9ccca39cb9ed
3,616,305
def entailment_internalization(df): """ new_ p = '' new_h = 'p implies that h' (1,0) new_h = 'p and h' (-1) """ contra_combine = " , " not_contra_combine = " implies that " df_not_contra = df.query("label!='contradiction'").copy() df_contra = df.query("label=='contradiction'").copy()...
502613bc15a7764e5ee9643c500ec3ada8ab5c45
3,616,306
def tcl_findprd_prepdict(prddict): """ Prepare dict of center:[ends] entries. :param prddict: Device:PRD dictionary. :type prddict: dict(str: list) """ prda = tcl_findprd_prepd_start(prddict) prdx = tcl_findprd_prepd_middle(prda) prdfinal = tcl_findprd_prepd_end(prdx) return prdfina...
9da3dfab8f44166cb353cf667ff51c2256755b78
3,616,307
def create_nn_cat(input_dim, nr_units, nr_layers, nr_classes): """Compile NN model with categories as outputs""" print('Compiling NN model with {0} layers, {1} units, input dimension {2}...'.format(nr_layers, nr_units, input_dim)) model = keras.models.Sequential() model.add(keras.layers.Dense(nr_units, ...
450fc1eb7c7c0d712da0fb803149b646970e5700
3,616,308
def augment(cls): """Add `time` to kwargs list.""" class New(cls): @staticmethod def _myfun(x, *args, time=0, **kwargs): return super(New,New)._myfun(x) return New
cf08f753ba3af3ff2d2c11ca24c5796d2b0a4c12
3,616,309
async def led(command: Command[JaegerActor], fps: FPS, level: int): """Sets the level of the FVC LED.""" fvc_ieb = FVC_IEB.create() led = fvc_ieb.get_device("LED1") raw_value = 32 * int(1023 * (level / 100)) await led.write(raw_value) await command.send_command("jaeger", "fvc status") re...
e3427b9175c079912cb48326da792bb325d776c9
3,616,310
def ReverseSequence(a, seq_lengths, seq_dim, batch_dim): """ Sequential reverse op. """ r = np.copy(a) invidxs = (len(r.shape) - 1) * [slice(None)] if seq_dim < batch_dim: invidxs[seq_dim] = slice(None, None, -1) else: invidxs[seq_dim - 1] = slice(None, None, -1) _invidxs...
ffac61cf7e793167033aff28dbfefc59e69580a0
3,616,311
def handle_none(func): """A decorator function to handle cases where partition values are `None` or "__HIVE_DEFAULT_PARTITION__" Args: func (Callable): A function registered to the singledispatch function `partition_to_py` """ def wrapper(primitive_type, value_str): if value_str is Non...
23db0c46a35f2e433735c4a863d5619bf4c3cc55
3,616,312
def distortion_score(X, labels, metric="euclidean"): """ Compute the mean distortion of all samples. The distortion is computed as the the sum of the squared distances between each observation and its closest centroid. Logically, this is the metric that K-Means attempts to minimize as it is fitting...
0e40d0b8c652309ab8a07df3ec0aa5a44dc0dc35
3,616,313
from typing import List from typing import Tuple import os import csv def get_location_replacements() -> List[Tuple[str,str]]: """Gets a list of location replacement tuples from csv""" replacements = [] with open(os.path.join(os.path.dirname(__file__), '../config/location.replacements.csv'), 'r') as infile: read...
c1e2a67ed64df8e3610ffd3150b5a5dd1982f61c
3,616,314
from datetime import datetime def encode_dexcode(dexid: str, effort: int, due: datetime.datetime, importance: int, status: str, flags: list) -> str: """ Create a dexcode from python objects which are easy to work with. Args: dexid (str): The dex ID (single letter followed by a number). ef...
cbed3d4840a8473b79345b9c38e861cf922a0424
3,616,315
def _to_kql(obj: ExpressionType, parentheses: bool = False) -> KQL: """ Convert the given expression to KQL. If this is a subexpression of a greater expression, neighboring operators might take precedence over operators included in this expression, causing an incorrect evaluation order. This might not be a ...
c03f304183876dfb0c84f181afc3dffc6987c5e6
3,616,316
import torch def sphere_mesh(n=512, radius=1.0, device="cpu"): """Return a unit sphere mesh discretization with *at least* n vertices. Initially this returns a standard uv sphere but in the future we could change it to return a more sophisticated discretization. Code adapted from github.com/caos...
c691af3b7a89da0b142bc0e9a3ef271cf22d157a
3,616,317
def asInteger(epsg): """ convert EPSG code to integer """ return int(epsg)
18a14944f5f29ec09585757f0edc912b896a12ba
3,616,318
def monitor_cb(ud, msg): """Callback for the MonitorStates, listening to /click/start_button""" # Return False when you want the MonitorState to terminate return False
34f5065aadf8ec96bbe0fb54b791f7a4385a55b5
3,616,319
def compute_dx_from_cross_dispersion_profiles(xcoef,ycoef,wavemin,wavemax, image, fibers=None, width=7,deg=2) : """ Measure x offsets from a preprocessed image and a trace set Args: xcoef : 2D np.array of shape (nfibers,ncoef) containing Legendre coefficents for each fiber to convert wavelenght to ...
e4dcfe3697c61e578319094693f43cd8a289167c
3,616,320
def email_image_attribution(request, id=None, *args, **kwargs): """ GET request with an ID in the request that links to a notification ID (or other field), and will mark that notification as having been opened. """ # mark the email mark_email_as_read(id) # create an image img = Image.n...
be678affd751a7e0f09b4710d57a7e3d3e4a941e
3,616,321
def angular_distance_fast(ra1, dec1, ra2, dec2): """ Compute angular distance using the Haversine formula. Use this one when you know you will never ask for points at their antipodes. If this is not the case, use the angular_distance function which is slower, but works also for antipodes. :param lo...
16962f59775faa928d45d802a4b77a0bacb2df6d
3,616,322
def resnet50(**kwargs): """ ResNet-50 model from 'Deep Residual Learning for Image Recognition,' https://arxiv.org/abs/1512.03385. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. ctx : Context, default CPU The context in ...
c8246e1f3302ed5be611a27fd3885d4a167e5197
3,616,323
def get_node_rb(graph, k=3, approx=np.inf): """ Get k nodes to defend based on Recalculated Betweenness (RB) Removal :cite:`holme2002attack` :param graph: an undirected NetworkX graph :param k: number of nodes to defend :param approx: number of nodes to approximate the betweenness centrality, k=0.1...
835353e8369f83e6fa7fe96b53f0c45c187ab7e2
3,616,324
def excluir_usuario(): """ Exclui um usuario com id especificado pela url """ try: if current_user.is_administrator(): cod_id = request.args.get('id') usuario = Usuario.query.filter_by(cod_usuario = cod_id).one() db.session.delete(usuario) db.session.commi...
811016c34ebcc1450fa9679bb15ee336576f9334
3,616,325
def make_model(): """ Generate the model used to make the saved test data. """ props = {'density': 1, 'magnetization': utils.ang2vec(1, 25, -10)} return [Sphere(x=-100, y=200, z=500, radius=400, props=props)]
9f7f366c8552b7079cb5201d059304de79aa4cb4
3,616,326
import subprocess def get_hrrr_mask(year = '2020', fdir = '/datadrive/hrrr/4km/'): """ Function to get the hrrr mask from interpolation. Not very elegantly coded: we compute the yearly maximum at each grid point. Assuming that every valid grid point rains, the mask is defined to exclude all grid poi...
5f6cbc7aa88f1b0431bd15d0865935d723690872
3,616,327
from sys import version def get_version(): """ Return package version as listed in env file """ if ENV_TYPE == PRD: return version + "/" + build return version + "/" + build + "/" + generate + ' (' + ENV_NAME + ')'
00e02f5b5371b3e2b5aca990af5df84e193c362e
3,616,328
def metarthunter_parse(driver: webdriver.Firefox) -> tuple[list[str], int, str]: """Read the html for hetarthunter.com""" # Parses the html of the site soup = soupify(driver) image_list = soup.find("ul", class_="list-justified2").find_all("a") images = [image.get("href") for image in image_list] ...
178db60ec8cee91505f6b6d8038788a44d52d3f8
3,616,329
def mag(initial, current): """ Calculates the magnification of a specified value **Parameters** intial: *float* initial value (magnificiation of 1) current: *float* current value **Returns** magnification: *float* the magnification of the current value """ ...
abc8d3603f11e62f57a62c47dc372b4b9ea19b0c
3,616,330
def conv2d(x, dim, stride=1, bn=True): """二维卷积 Args: x ([type]): 输入数据 dim ([type]): 维度,一般为卷积核数量,一般为输出维度 stride (int, optional): 步长. Defaults to 1. bn (bool, optional): 是否使用BN层. Defaults to True. Returns: [type]: slim.conv2d 默认pad模式是SAME ,卷积后的数据会变成和原来大小一样,比如n*m*w*h*c...
38f4d9ce1bb64bc7aba01e07d28df1deb26c8579
3,616,331
def divergence(f): """Take the divergence of a vector array Parameters ---------- f : np.ndarray Vector array whose divergence should be taken. Returns ------- out : np.ndarray Scalar array of divergence. Dimensionality one less than the vector array. """ ...
3ce65111bd6815b6597b4cb7915acd3b8d0e6f88
3,616,332
import re def capitalize(word): """Only capitalize the first letter of a word, even when written in CamlCase. Args: word (str): Input string. Returns: str: Input string with first letter capitalized. """ return re.sub('([a-zA-Z])', lambda x: x.groups()[0].upper(), word, 1)
4f254696e00c24a85a20ea74fc66a32fceb541c6
3,616,333
from pathlib import Path from re import T from datetime import datetime def read_ini(fn: Path) -> dict[str, T.Any]: """parse .ini file DEPRECATED """ fn = find.config(fn) with fn.open("rt") as f: date = list(map(int, f.readline().split()[0].split(",")))[::-1] sec = float(f.readli...
d26e4527a2eb1b12d6268da17252f9eb3424b564
3,616,334
import re def cassandra_ddl_repr(data): """Generate a string representation of a map suitable for use in Cassandra DDL.""" if isinstance(data, str): return "'" + re.sub(r"(?<!\\)'", "\\'", data) + "'" elif isinstance(data, dict): pairs = [] for k, v in data.items(): if ...
c81ad24c0185ef10646644b82399c202c2261a1a
3,616,335
import json import requests def gconnect(): """Handles the data sent by the google signin ajax""" # First validate state token to protect from CSRF if request.args.get('state') != login_session['state']: response = make_response(json.dumps('Invalid state parameter.'), 401) response.headers...
d3a5c414345be246c17daf05368519f99ba27f9b
3,616,336
from typing import List def get_errors(entries: List) -> List[str]: """Extracts error entry contents The entries argument should be a list of demisto entries Args: entries (List[List[Dict]]): multiples entries of results of demisto.executeCommand() Returns: (List[str]): Error messag...
91a83df9341c7fc033314584f66bf873e3f5e9b9
3,616,337
import itertools def primes_up_to(n, ps = None): """Prime numbers <= n.""" if ps is None: ps = mprimes() return itertools.takewhile(lambda p: p <= n, ps)
070dbd97d56583d5d7baa85467e442e1b01dcb7f
3,616,338
import time import cloudpickle import sys def addtoqueue(config_file, message_queue, expressions, environment=None, limit=None): """ Search for Datasets and enqueue Tasks into an AWS SQS Queue for later processing. """ def _push_messages(queue, messages): response = queue.send_messages(Entrie...
1fc4b686b95a8ef347233d5a5da050d8a8ec0ea6
3,616,339
import os def labels_file_reader_factory(labels_file): """A factory for generating file readers that can read label files. Args: labels_file (str): the file with the labels of the regions Returns: LabelsFileReader: the reader for the given file """ extension = os.path.splitext(la...
892cf6c1734f59ddab05f53c94ca5942d962d122
3,616,340
def _IsNestedSet(field: descriptor.FieldDescriptor) -> bool: """If this is a nested field that translates to a set.""" return _IsNestedElement(field, Schema_pb2.ColumnInfo.TYPE_SET)
4ae82bc9ccdb0c35b04135781f49119840300d0f
3,616,341
def get_unit(coordinate): """ Get the `unit` identifier of **coordinate**, if **coordinate** has a valid `unit` identifier appended, else returns `None`. """ if isinstance(coordinate, (int, float)): return None result = pattern.coordinate.match(coordinate) if result: return ...
4e16a67acd4d480761a7523046642130054d6d93
3,616,342
def GetVnodeLocksSummary(vnode): """ Internal function to get summary of advisory locks for the given vnode params: vnode - value representing the vnode object return: str - formatted output information for the summary of advisory locks """ out_str = '' if vnode: lockf_list =...
353922932696cfc0e1cc4f48a78e4c90fea2d960
3,616,343
def pct_similarity(results, map_probes_to_genes_first=False, top=None): """ Read each file in a list and return the percent overlap of their top genes. See pct_similarity_matrix_raw for calculation details :param results: a list of paths to tsv-formatted result files or a list of lists of probes for co...
1f77b14171a35e9197ab2c35f798223c0d2fba17
3,616,344
def check_lights_opposite(light_a, light_b): """ Checks if the two given lights are opposite to each other or not. """ def get_forward_vector(light): light_vector = light.get_transform().get_forward_vector() return [light_vector.x, light_vector.y, light_vector.z] light_a_vector = get_forwar...
5fb8befa1e366151c6447088c24c8218b32b4394
3,616,345
from pathlib import Path def _make_ls5_scene_datasets(geotiffs, tmpdir): """ Create directory structures like:: LS5_TM_NBAR_P54_GANBAR01-002_090_084_01 |---scene01 | |----- report.txt | |----- LS5_TM_NBAR_P54_GANBAR01-002_090_084_01_B10.tif | |----- LS5_TM...
c4f4b217b621061eefc750475da5aa881ebc73e6
3,616,346
def construct_stimulus( stim="dc", duration=6000, dt=0.1, stim_amp=0.2, stim_freq=1, stim_bias=0, n_periods=None, nostim_before=0, nostim_after=0, ): """Constructs a stimulus that can be applied to a model :param stim: Stimulation type: 'ac':oscillatory stimulus, 'dc': stimp...
21446ea1ac6dcc387fe5f3cfb4d18ac2a55f290b
3,616,347
def rsc_bounds(rsc_data): """Uses the x/y and step data from a .rsc file to generate LatLonBox for .kml""" north, south, east, west = rsc_nsew(rsc_data) return {"north": north, "south": south, "east": east, "west": west}
acc149486f75bce102b0e509371eed815665a60d
3,616,348
import tempfile def build_dir(): """Test build dir for the sphinx compiled docs.""" return tempfile.mkdtemp()
aef168b1031a9ebc15d502a3aedb89da004caffa
3,616,349
def interp_ll(x, y, left=None, right=None): """Log-log interpolation of 1D data. x and y are arrays of values. This function returns a function that can be used to find interpolated or extrapolated values. If out-of-bounds, left and right indicate the default behaviour. If they are none, extrapolate; otherwise, ...
bb0937febab8ff1e8d3a3515fc5601060cacb89a
3,616,350
def tag_edit(tag_id): """Edit Tag""" tag = Tag.get_item_by_id(tag_id) if tag is None: abort(404) else: if request.method == "POST": tag.name = request.form["name"] tag.slug = request.form["slug"] db.session.add(tag) db.session.commit() ...
365f99779d398e4269bed7e38f4ba259e49b56e2
3,616,351
def _get_project_title(): """Get project title""" title = None puts("") while not title: title = raw_input("What is the project's full title? (e.g. My awesome project) ") return title
64c3c7c66d48a519ff6ecc274e5d01234987e6aa
3,616,352
import os def pred_hist(df_results_path=f'results/{name}_results.csv', bins=500, show_results=False): """ Plot the histogram of predicted values :param df_results_path: dataframe of results, currently used path by default :param bins: number of histogram bins, 500 by default :param show_results: T...
3e2ad89e4bb3e4a4f0d06ddd64204d6da7417d12
3,616,353
import csv def read_csv_file(file_name): """ Given a CSV file, read the data into a nested list Input: String corresponding to comma-separated CSV file Output: Nested list consisting of the fields in the CSV file """ with open(file_name, newline='') as csv_file: # don't need to ...
65f9d2edb9ecf020d773a8d8516f31247fa680ed
3,616,354
def asymptomatic_duration_00(): """ Real Name: b'asymptomatic duration 00' Original Eqn: b'5' Units: b'Day' Limits: (None, None) Type: constant b'' """ return 5
8c29fa4db3c950daf5e0fb1f4cfe3a2e98d32583
3,616,355
def get_all_entries(df, pdbid, cdr): """ Get all entries of a given PDBID and CDR. :param df: dataframe.DataFrame :rtype: pandas.DataFrame """ return df[(df['input_tag'].str.contains(pdbid)) & (df['CDR'] == cdr)]
414eca4481bde0ccc5cdd6e143f7d4b06216a102
3,616,356
from tornado.ioloop import IOLoop import functools def asynchronous(method): """Wrap request handler methods with this if they are asynchronous. This decorator is for callback-style asynchronous methods; for coroutines, use the ``@gen.coroutine`` decorator without ``@asynchronous``. (It is legal for ...
7915698f8db6251b147e4299e66b0c6c07b600ab
3,616,357
def dynary(x, bases): """Represent the integer ``x`` with respect to the 'dynamical' ``bases``. Gives a way to reliably enumerate and 'de-enumerate' the combination of all different index values. Examples -------- >>> dynary(9, [2, 2, 2, 2]) # binary [1, 0, 0, 1] >>> dyna...
8d86e6af07d2b31ff56145733012d550b92580f7
3,616,358
def download_from_db() -> BytesIO: """ Возвращает байтовый буфер с таблицой бд в формате xlsx """ wb = init_wb() categories = get_categories_list() for app in get_applications(): if app[1] in categories[:3]: wb["1"].append(app) elif app[1] in categories[3:6] + cat...
c19246720f47a8d91c0a41d010bff6493ecd787f
3,616,359
def calculate_request_checksum(game, pid, sid): """Calculate checksum of payment details to pass to payment API""" secret_key = get_payment_secret() checksum_string = CHECKSUM_REQUEST_FORMAT.format(pid, sid, game.price, secret_key) return calculate_checksum(checksum_string)
00809383d925ca74379e699eefe1359dbf58a569
3,616,360
def main(source_base, binary_base, num_threads=1): """Main entry point of the script.""" print 'Executing test for razers3' print '===========================' print ph = app_tests.TestPathHelper( source_base, binary_base, 'apps/razers3/tests') # tests dir # =================...
76f0c69d73e39add509a6207d59ff11e734595b1
3,616,361
def encode(input, errors='strict'): """Encode unicode as USMARC """ if errors not in set(['strict', 'replace', 'ignore']): raise ValueError("Invalid errors argument %s" % errors) result = [] rappend = result.append uget = unicodemap.get for u in input: s = uget(u) if ...
a9956b395104d186a0d1941b0deb32b6105a7917
3,616,362
import six def has_dask_arrays(dataset): """ check whether or not a dataset contains dask arrays Parameters ---------- dataset : xarray.Dataset Returns ------- bool : True if dask arrays are found """ has_dask = False for varname, var in six.iteritems(dataset....
8870be6815555aa0cb9cd925d22de23170a99711
3,616,363
def Put(entities, **kwargs): """Store one or more entities in the datastore. The entities may be new or previously existing. For new entities, Put() will fill in the app id and key assigned by the datastore. If the argument is a single Entity, a single Key will be returned. If the argument is a list of Enti...
3d5e1bf702a4ee26864cfef4adcf91c206ff62c4
3,616,364
import os def read_multivariate_dataset(root_dir, dataset_name, shot): """ Read multivariate dataset """ X = np.load(os.path.join(root_dir, dataset_name+".npy"), allow_pickle=True) y = np.loadtxt(os.path.join(root_dir, dataset_name+'_label.txt')) y = y.astype(np.int64) dim = X[0].shape[0] ...
20504bd00f86caea4f7e4e1774c488e06332062c
3,616,365
def classify_image(interpreter, image, top_k=1): """Returns a sorted array of classification results.""" set_input_tensor(interpreter, image) interpreter.invoke() output_details = interpreter.get_output_details()[0] output = np.squeeze(interpreter.get_tensor(output_details['index'])) # If the model is quan...
65562f0b9e6224e068938d018d65df4182b1e07c
3,616,366
def _get_scheme_map(input_encoding, output_encoding): """Provides a caching layer on top of `SchemeMap` objects to allow faster access to scheme maps we've instantiated once. :param input_encoding: Input encoding. Must be defined in `SCHEMES`. :param output_encoding: Input encoding. Must be defined in ...
e1618cf38ead4493de051fe58ec9e3554706185d
3,616,367
from sys import path def collect_inst_model_pairs(start=None, stop=None, tinc=None, inst=None, user=None, password=None, model_files=None, model_load_rout=None, inst_lon_name=None, mod_lon_name=None, inst_name=[], mod_name=[], ...
20ef90d6e4472757a45c76bdb1ee93f1b6254b26
3,616,368
import os import shutil def whl_install(path, dest, *args, pip=None, extra_install_args=None, install_dependencies=False, wait_func=None, reset_modules=True, contained_modules=None, **kwargs): """Import whl or zip files and return the installed module. Args: dest (str): Destination pa...
8547a11b92a8f3f9e18d7c0d1fccc8b74b6a0ffb
3,616,369
def cooling_resource_activator(mdot_kgpers, T_sup_K, T_re_K, limits, cooling_resource_potentials, T_ground_K, prices, lca, master_to_slave_variables, config, Q_cooling_req, locator): """ :param DCN_cooling: :param Qc_available_from_lake_W: :type Qc_available_from_lake_W: ...
85034cae9835da1ed60a8cc9272b19fe46daa59a
3,616,370
import argparse def process_create_experiment_arguments(): """ Processing command line arguments for 01_create_experiment script """ # defining command line arguments parser = argparse.ArgumentParser() # general arguments parser.add_argument("-d", "--exp_directory", help="Directory where...
e6830a43ad215f03ad59a1b496140d4247aa124d
3,616,371
import glob import numpy def read_v70(fileglob): """Reads a location.pytxt sparse 70-vector that describes an extremum.""" files = glob.glob(fileglob) if len(files) != 1: raise ValueError('Got %d matches for glob %r: %r' % ( len(files), fileglob, files)) model = distillation.read_distillate_model(...
2195e4214277bd9abf0368d9323ecdcbde60bd1e
3,616,372
def merge_result(res): """ Merges all items in `res` into a list. This command is used when sending a command to multiple nodes and they result from each node should be merged into a single list. """ if not isinstance(res, dict): raise ValueError("Value should be of dict type") re...
28d21ca00316303c0e2fc0400599921154253236
3,616,373
def verify_service_identity(cert_patterns, obligatory_ids, optional_ids): """ Verify whether *cert_patterns* are valid for *obligatory_ids* and *optional_ids*. *obligatory_ids* must be both present and match. *optional_ids* must match if a pattern of the respective type is present. """ err...
a24b094d9d6bab6a705df821ace0939fab82c737
3,616,374
def point_cloud_actor(xyz, size=100, color=(0,0,0), opacity=1): """function to make a vtk.vtkActor from a set of xyz points that renders them as spheres Parameters ---------- xyz : np.array a Nx3 array of points size: float o...
dedde319dcc20391e53f52f1692608009aaa9a80
3,616,375
def Growth_factor_Linder(omega_m, z, gamma=0.55): """ Computes the unnormalised growth factor at redshift z given the present day value of omega_m. Uses the approximation from Linder2005 with fixed gamma :param omega_m: the matter density at the present day :param z: the redshift we want the matter...
e9807a639b967a94d8a44d1fcb0a9f3ec6c039bf
3,616,376
def get_redis_connection(): """ Get attribute to redis connecion object """ conn = getattr(g, "_redis_connection", None) if conn is None: url = current_app.config["REDIS_URL"] conn = g._redis_connection = redis.from_url(url) return conn
c307fa313df46875797a3942eb2c3739a3f2ab4e
3,616,377
def _parse_oid_metric(metric): # type: (OIDMetric) -> MetricParseResult """ Parse a fully resolved OID/name metric. Example: ``` metrics: - OID: 1.3.6.1.2.1.2.1 name: ifNumber ``` """ name = metric['name'] oid = OID(metric['OID']) parsed_symbol_metric = Parse...
c050959ee5a5db247177282bd4df1dffdf878ed3
3,616,378
import os def create_progressbar(message, *args, **kwargs): """Create the correct progressbar based on availability of interactive shell.""" if 'CI' in os.environ and os.environ['CI']: kwargs['poll_interval'] = 10 return progressbar.ProgressBar(*args, **kwargs) # Removing for now to see if it ...
d55f9b48932a5825e5dc9cad3e341c128f34b981
3,616,379
from pathlib import Path from typing import Dict from typing import Any def _parse_additional_json(dir_name: Path) -> Dict[str, Any]: """Parse additional json files in the directory.""" additional_json = {} for filename in dir_name.glob("*.json*"): key = filename.name.split(".")[0] if key ...
9745eaabe1169ffa52d5159782be3c88bf41c7b1
3,616,380
def load_iharm(harm_dump_name, gcov, gcon, compute_b=True): """ does what you expect """ hfp = h5py.File(harm_dump_name,"r") N1 = hfp["header"]["n1"][()] N2 = hfp["header"]["n2"][()] N3 = hfp["header"]["n3"][()] rho = hfp["prims"][:,:,:,0] UU = hfp["prims"][:,:,:,1] U = hfp["prims"][:,:,:,2:5] ...
d04e70f0afd829a9c0b73a2dac01145ddaa91bd6
3,616,381
def ensure_vacuum(structure, vacuum): """ Adds padding to a slab or 2D material until the desired amount of vacuum is reached. Args: structure (Structure): Structure to add vacuum to vacuum (float): Final desired vacuum thickness in Angstroms Returns: Structure object with v...
ffbf44a67053a3903483d7ac9acc5ce31a4a3c21
3,616,382
from functools import reduce def generateDF(keys, periods=20, amplitudes=[1, 1.5], frequencies=[1/6, 1/2], ground=0, sample_rate=1e-2): """ Генерирует таблицу со столбцами из синусоид с заданным количеством периодов, случайно изменяющейся амплитудой и случайно изменяющейся частотой. Па...
492304f1a5a1baedb1dfb1712d8bfeb26c67388c
3,616,383
def get_file_section_name(section_key, section_label=None): """Build a section name as in the config file, given section key and label.""" return section_key + (" {0}".format(section_label) if section_label else "")
01e1f46d2a949315ba2e927ddfab610064539e3b
3,616,384
from typing import Callable from typing import Any def test_benchmark_blend_images_npy(benchmark: Callable[..., Any]) -> None: """Benchmark numpy implementation of alpha blending.""" def blend_images(img0: NDArrayByte, img1: NDArrayByte, alpha: float = 0.7) -> NDArrayByte: """Alpha-blend two images t...
4ab85e194d8ca6e95d138480e74e7cebcd8d4def
3,616,385
def inf_get_cc_size_b(*args): """ inf_get_cc_size_b() -> uchar """ return _ida_ida.inf_get_cc_size_b(*args)
ec9c35adbf6c1422471dc71d4feca0bb1e83cf6b
3,616,386
def resnet18(pretrained=False, progress=True, **kwargs): """Constructs a ResNet-18 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet progress (bool): If True, displays a progress bar of the download to stderr """ return _resnet('resnet18', DistillerBasicBl...
2465471757663c00af2a6b069583386f0ed8a1eb
3,616,387
def _get_test_stats_with_mi(feature_paths): """Get stats proto for MI test.""" result = statistics_pb2.DatasetFeatureStatistics() for feature_path in feature_paths: feature_proto = text_format.Parse( """ custom_stats { name: "max_sklearn_adjusted_mutual_information" ...
0134ea6f85568da9fecdf7d50c9865e90af153e1
3,616,388
def chist(l): """Simple counting histogram. Takes a list of items and returns a list of (count,object) tuples.""" counts = {} for c in l: counts[c] = counts.get(c,0)+1 hist = [(v,k) for k,v in counts.items()] return sorted(hist,reverse=1)
ac71b1251677186b0adf4f090d1f0a10da91964f
3,616,389
import os def FindSrcDirPath(): """Returns the abs path to the src/ dir of the project.""" src_dir = os.path.dirname(os.path.abspath(__file__)) while os.path.basename(src_dir) != 'src': src_dir = os.path.normpath(os.path.join(src_dir, os.pardir)) return src_dir
d41d225fd65b3a6e934abd42bcbbe5c25a064a31
3,616,390
import requests import time def select_exercise_and_start_time(bot): """ Selects an exercise and start time, and sleeps until the time period has past. """ next_time_interval = select_next_time_interval(bot) minute_interval = round(next_time_interval / 60, 0) exercise = select_exercise(bot...
ed84d4e9c13c1ecdce165b4b0857efb349b96179
3,616,391
import random def make_random_constant(name=None, value=None, return_params=False): """Make a random Constant value.""" if name is None: name = random_identifier() if value is None: const_type = random.choice([ParamType.FLOAT, ParamType.INT]) if const_type == ParamType.FLOAT: ...
1be467740d87c45b2ff922bd0c47de548b89cc00
3,616,392
import pathlib def recursive_search(path): """Perform recursive search for supported measurements""" path = pathlib.Path(path).resolve() path_in = [] # Get all candidates cands1 = list(path.rglob("*")) + [path] # Exclude all directories with the suffix _dm that contain drymass.cfg cands2 =...
7238f03e0c214fe5b786d4a8c19847f713829766
3,616,393
def rot_y2alpha(rot_y, x, FOCAL_LENGTH): """ Get alpha by rotation_y - theta + 180 rotation_y : Rotation ry around Y-axis in camera coordinates [-pi..pi] x : Object center x to the camera center (x-W/2), in pixels alpha : Observation angle of object, ranging [-pi..pi] """ alpha = rot_y - np....
7a4b736800f6fdd13228ac2d67c5c573c1f51563
3,616,394
def psi2name(psi, scale=fine_scale): """Map single `psi` value to Wentworth bin name.""" for name, upper_psi in scale[:-1]: if psi <= upper_psi: return name return scale[-1][0]
c35fa0b0f65832cc1da168c8c36e65c0fbd4ff53
3,616,395
def download_video_files( video_metadata, local_video_directory='./videos', video_filename_extension='mp4', download_workers=4, ): """ Downloads videos from S3 to local directory tree and returns metadata with local path information added. Videos are specified as a list of dictionaries,...
50d0e29fcf485f577c233741f7a96af3b4b35186
3,616,396
def cloud_motion_fast(im1,im2,mask1=None, mask2=None,ratio=0.7, threads=1): """ Determine cloud motion Input: Images and masks for two frames Output: Cloud motion vector, and max correlation """ ####use this routine if the inputs are raw images ny,nx=im2.shape # if im1.dtype == ...
16f549276e512925758bfddc491c53f1f38a942e
3,616,397
import requests import json def get_demo_by_guid(guid): """ Retrieve a demo from the ERP system by guid. :param guid: The demo's guid. :return: An instance of the Demo. """ # Create and format request to ERP url = '%s/api/v1/Demos/findByGuid/%s' % (get_service_url('lw-erp'), g...
986a20893b0f2d1019beb4f8da3266a1d8f4aaf2
3,616,398
def preprocess_skeleton_frame(joint_collection, is_15_joint: bool, is_cad: bool = False, to_edge: bool = True, to_rotate: bool = False, is_25_joint: bool = False) -> _np.ndarray: """Applies re-ordering, orientation standardzin...
7eb511ac3a2bfef406a21f135ea0f0414701f49b
3,616,399