content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def find_revert_op(input_state_index: int): """Looks in the Cayley table the operation needed to reset the state to ground state from input state_tracker :param input_state_index: Index of the current state tracker :return: index of the next Clifford to apply to invert RB sequence """ for i in rang...
cba4a4f764f02abbfb14527cff4f1470d0c6ff3a
3,634,200
def _column_number_to_letters(number): """ Converts given column number into a column letters. Right shifts the column index by 26 to find column letters in reverse order. These numbers are 1-based, and can be converted to ASCII ordinals by adding 64. Parameters ---------- number : int...
c9a68bcd32c8f254af322bc61e447cfae61cb6d2
3,634,201
import gurobipy as gb def toGRBFromStr(): """ Module for program-wide constant maps (e.g., dicts that should never change) """ return {"=": gb.GRB.EQUAL, "le": gb.GRB.LESS_EQUAL, "ge": gb.GRB.GREATER_EQUAL}
7fb8a522d787716d3006722511d7afb3c5378d3a
3,634,202
def _generate_mea_comment(obj: GamObject, object_module: GamObject): """ Check whether the object has a module, then generate the measurement comment and update the object ID to add the measurement to. Args: obj (GamObject): The object. object_module (GamObject): The object module, if t...
89a119a542c14e5edc745878127503b0f996007e
3,634,203
def master_do(func, *args, **kwargs): """Help calling function only on the rank0 process id ddp""" try: rank = dist.get_rank() if rank == 0: return func(*args, **kwargs) except AssertionError: # not in DDP setting, just do as usual func(*args, **kwargs)
befe0d157591c10cb6e590a82e5c3f5253fe4663
3,634,204
def news_msg(result): """ Interface Function for news intent """ campus_publication = "" news_result = [] try: campus_publication = result.parameters['club'] campus_publication = campus_publication.lower() except BaseException: campus_publication = "" return "I couldn...
a60df1affbfda2ec68c1d4c27daaa495002e5780
3,634,205
def init_aws_client(): """Initializes and returns AWS boto3 client object""" client = boto3.client("network-firewall") return client
28d06097d97e4a364beff767cc0177922a3aff88
3,634,206
def verify_file_integrity(fchunk): """ @TODO: implement """ logger.debug("Verify md5sum...{}".format(fchunk)) return True
1b5925799eeb00b7710dc3f8f3d6371a6bb5f53b
3,634,207
def _chunk_member_lag(chunk, repl_member_list, primary_optimedates, test_run_indices): """Helper function to compute secondary lag from values in a chunk :param collection.OrderedDict chunk: FTDC JSON chunk :param list[str] repl_member_list: list of all members in the replSet :param str primary: which ...
115ba53505d5bcbb9e0c1cdf0eab675fae73e568
3,634,208
def graph_build_split(X, edge_index, node_mask: np.array): """ subgraph building through spliting the selected nodes from the original graph """ row, col = edge_index edge_mask = (node_mask[row] == 1) & (node_mask[col] == 1) ret_edge_index = edge_index[:, edge_mask] return X, ret_edge_index
45b62a79b6c35ceda181e15d7a4a00dda8146fc6
3,634,209
def get_pagination_class(): """ Returns custom pagination class, set in settings """ pagination_class = LIKES_REST_PAGINATION_CLASS if pagination_class: try: return import_string(pagination_class) except ImportError: pass return api_settings.DEFAULT_PAGI...
57c12519b1f4a6a2a4e5533176e9901e3f468bf9
3,634,210
def get_us_presidents_gender(president): """Given the name of a US President, return his gender, or None if not found. """ data = load('us_president_gender') for row in data: if row['president'] == president: return row['gender'] return None
46bca2773092fa31a53ebb774cbcca6d8863d1a8
3,634,211
import warnings def ProtoFromTfRecordFiles(files, max_entries=10000, features=None, is_sequence=False, iterator_options=None): """Creates a feature statistics proto from a set of TFRecord files. Args: ...
d0891996a1f1889b575cd042a78eb0b17a95b4c5
3,634,212
def smallest_evenly_divisible(min_divisor, max_divisor, minimum_dividend=0): """Returns the smallest number that is evenly divisible (divisible with no remainder) by all of the numbers from `min_divisor` to `max_divisor`. If a `minimum_dividend` is provided, only dividends greater than this number will ...
fa23d9a413a0909bfc05d7eb928aec8ade4cb06f
3,634,213
def pct75(input_tensor, weights_tensor): """Compute the 75th percentile of a given tensor.""" del weights_tensor return tfp.stats.percentile(input_tensor, 75)
8c447827559841d50e02a68b99da6d7abf422fda
3,634,214
import copy def get_bad_sequences(GoodSequenceList, Bad1st_list, BadOther_list): """Take each good sequence and implant a codec error at any possible byte position. RETURNS: List of bad sequences. """ result = [] for sequence in GoodSequenceList: # Implement a couple of bad sequences ...
52ce3a1c9ee468c7b2c39d5113d783667884deba
3,634,215
def factorial(n): """ Returns the factorial of n Parameters ---------- n : int denotes the non-negative integer for which factorial value is needed """ if(n<0): raise NotImplementedError( "Enter a valid non-negative integer" ) if(n==0 or n==...
fe0b7100e1292d1e96daf18545d9fdfb931f9f74
3,634,216
import time def check_redis(*args, **kwargs): """Checks if configured Redis instance is pingable.""" try: r = StrictRedis.from_url(current_app.config['CACHE_REDIS_URL']) t1 = time.time() res = r.ping() t2 = time.time() return 'redis', res, {'time': t2 - t1} except (...
10ba4595b869747def8592b901125a197f794fea
3,634,217
def Divide(a, b): """Returns the quotient, or NaN if the divisor is zero.""" if b == 0: return float('nan') return a / float(b)
3ed0b07949bb802177e52bf8d04e9dfde92ab2de
3,634,218
import os def craft_item(): """Get craft item from environ varriable""" return os.environ.get('CRAFT_ITEM', None)
2f6f940ad83023dc21f68c2212c98c0e13d8d0e4
3,634,219
def guess_typecode(value): """Guess Gwyddion typecode for `value`.""" if np.isscalar(value) and hasattr(value, 'item'): # Seems to be a numpy type -- convert value = value.item() if isinstance(value, GwyObject): return 'o' elif isinstance(value, string_types): if len(valu...
3440c8008596d479d084e8fe68ca941ab6b23c17
3,634,220
from typing import Dict from typing import Any def create_region(entity: Entity, author: Identity) -> Identity: """Create a region""" custom_properties: Dict[str, Any] = {"x_opencti_location_type": "Region"} return Location( created_by_ref=author, name=entity.value, region=entity....
c1c21da1568f030b9b1a84263ddc3547226233b2
3,634,221
def post(post_id): """ 实例化一个评论表单,并将其传入post.html :param post_id: :return: """ post = Post.query.get_or_404(post_id) form = CommentForm() if form.validate_on_submit(): comment = Comment(comment_body=form.comment_body.data, post=post, ...
6b209ef5fd464ffbc0fa71c259d4105dbeb4f79d
3,634,222
def noisify(chse, dE, dt, dU): """ Create a nosified chain Parameters chse : Chain instance cE: float spread in on-site energies dt: float spread in hoppings dU: float spread in interaction """ dEs = np.zeros((chse.N,)) dts = np.zeros((chse.N,)) dUs =...
7e4e1d4c2872e081fbc50536bda7883bb50cce35
3,634,223
def kepio(keplcfile): """Read in a Kepler LC file and return the time, flux, and error""" with fits.open(keplcfile) as hdu: print(hdu.info()) t = hdu[1].data["TIME"] f = hdu[1].data["SAP_FLUX"] e = hdu[1].data["SAP_FLUX_ERR"] return t,f,e
2bfc458200a2c4a04715eebd2306368e8f3581c2
3,634,224
def camera_matrix(K: np.ndarray, R: np.ndarray, t: np.ndarray) -> np.ndarray: """Derive the camera matrix. Derive the camera matrix from the camera intrinsic matrix (K), and the extrinsic rotation matric (R), and extrinsic translation vector (t). Note that this uses the matlab convention, such tha...
274ca0736397850eb82a155000fd8265196315aa
3,634,225
import ntpath def path_leaf(path): """ Extract the file name from a path. If the file ends with a slash, the basename will be empty, so the function to deal with it Parameters ---------- path : str Path of the file Returns ------- output : str The name of the ...
58930f081c2366b9084bb279d1b8b267e5f93c96
3,634,226
from typing import Union import ast from pathlib import Path from typing import Set import os def expand_import_star( node: Union[ast.ImportFrom, _nodes.ImportFrom], path: Path ) -> Union[ast.ImportFrom, _nodes.ImportFrom]: """Expand import star statement, replace the `*` with a list of ast.alias. :param...
a07640ff2d9fbf151423dd0338311cf732122d53
3,634,227
import torch def hoi2result(instance_labels, verb_scores, bboxes, sub_ids, obj_ids, max_per_img=100, valid_hois=None): """Convert detection hois to a list of numpy arrays. Used in QPIC. Args: valid_hois (): max_per_img (): obj_ids (): sub_ids (): verb_scores (): ...
1af569ef31a27bfcca135d75e42cd7df26cecea5
3,634,228
def focus_metric(data, merit_function='vollath_F4', **kwargs): """Compute the focus metric. Computes a focus metric on the given data using a supplied merit function. The merit function can be passed either as the name of the function (must be defined in this module) or as a callable object. Additional...
c8f571e11202d39d8f331fca5fc93333aeb71e62
3,634,229
def get_canonical_import(import_set): """Obtain one single import from a set of possible sources of a symbol. One symbol might come from multiple places as it is being imported and reexported. To simplify API changes, we always use the same import for the same module, and give preference to imports coming from...
ae53ca4d271ab543a7a13f1ce8240ce6eb328bbb
3,634,230
def additive_white_gaussian_noise(signal, noise_level): """ Add gaussian white noise to audio signal. :param signal: Audio signal to permute. :param noise_level: standard deviation of the gaussian noise. """ # SNR = 10 * log((RMS of signal)^2 / (RMS of noise)^2) # RMS_s = np.sqrt(np.mean(si...
c4705b2fa67ce319609677a91bb7efa3e9c427b7
3,634,231
import torch from typing import Iterable def _tensor_in(tensor: torch.Tensor, iterable: Iterable[torch.Tensor]): """Returns whether `tensor is element` for any element in `iterable` This function is necessary because `tensor in iterable` does not work reliably for `Tensor`s. See https://discuss.pytorch.o...
84ac8a129440c9c8d7785029b04bd403514a3bb9
3,634,232
def flip(a, dim=0): """ Flip an array along a dimension. Parameters ---------- a : af.Array. Multi dimensional array. dim : optional: int. default: 0. The dimension along which the flip is performed. Returns ------- out : af.Array The output after flippin...
1c006acae6d6bfccb92a519da197fa6e3792e2c8
3,634,233
def get_cnn_model(params): """ Load base CNN model and add metadata fusion layers if 'use_metadata' is set in params.py :param params: global parameters, used to find location of the dataset and json file :return model: CNN model with or without depending on params """ input_tensor = Inp...
c87ee7d11439adf5fd7bc98e3d70398c32421089
3,634,234
def is_development_mode(registry): """ Returns true, if mode is set to development in current ini file. :param registry: request.registry :return: Boolean """ if 'mode' in registry.settings: return registry.settings['mode'].lower() == 'development' return False
af1b11fa69231a455406247b593f8ff49855bc3f
3,634,235
def run_summarizer(parser, sentences, language='english'): """ :params parser: Parser for selected document type :params sentences: Maximum sentences for summarizer. :returns summary: Summarized page. """ summarizer = Summarizer(Stemmer(language)) summarizer.stop_words = get_stop_words(lan...
9dd61447df7612b005b825c2e21fc3943596ab12
3,634,236
def mk_input(ctx, name, type): """ mk_input(Int_ctx ctx, char const * name, Int_type type) -> Int_net Parameters ---------- ctx: Int_ctx name: char const * type: Int_type """ return _api.mk_input(ctx, name, type)
05cba1813f9fb81ea132dac653073466862e4db0
3,634,237
def coo_fromdense_mhlo(mat, *, nnz, data_dtype, index_dtype, index_type): """COO from dense matrix.""" mat_type = ir.RankedTensorType(mat.type) rows, cols = mat_type.shape buffer_size, opaque = _hipsparse.build_coo_fromdense_descriptor( data_dtype, index_dtype, rows, cols, nnz) ...
c8cf5db1d05e9fcaf6d383f1d6cd9cfa2fe55ae8
3,634,238
def __get_wight(last_link: Link, end_link: Link, end_fraction, weight_function): """ Calculate the wight of the end_link. :param last_link: Needed to determine from which direction you comes :param end_link: Link from which the weight is calculated :param end_fraction: fraction as Number (1 >= fract...
e80a82fa830d08890a51398f6f9e5ba69482405a
3,634,239
def float_fraction(trainpct): """ Float bounded between 0.0 and 1.0 """ try: f = float(trainpct) except ValueError: raise Exception("Fraction must be a float") if f < 0.0 or f > 1.0: raise Exception("Argument should be a fraction! Must be <= 1.0 and >= 0.0") return f
8eb28dcaa0ed9250f4aa68d668ad424b5b5eded5
3,634,240
def handle_internal(msg): """Process an internal message.""" internal = msg.gateway.const.Internal(msg.sub_type) handler = internal.get_handler(msg.gateway.handlers) if handler is None: return None return handler(msg)
0f5cae49cf5d36a5e161f88902c46af931fd622a
3,634,241
def _lower_bound_grad(op, grad): """Gradient for `lower_bound` if `gradient == 'identity_if_towards'`. Args: op: The op for which to calculate a gradient. grad: Gradient with respect to the output of the op. Returns: Gradient with respect to the inputs of the op. """ inputs, bound = op.inputs ...
907ef212759f6a45ff32b78bcfede6222d978996
3,634,242
from rascil.processing_components.visibility import msv2 def list_ms(msname, ack=False): """ List sources and data descriptors in a MeasurementSet :param msname: File name of MS :param ack: Ask casacore to acknowledge each table operation :return: sources, data descriptors For example:: ...
0b12e59eead973c0b2e5370e1e0c98ac1ffc4ae8
3,634,243
def obv(s_interval: str, df_stock: pd.DataFrame) -> pd.DataFrame: """On Balance Volume Parameters ---------- s_interval: str Stock data interval df_stock: pd.DataFrame Dataframe of stock prices Returns ------- pd.DataFrame Dataframe with technical indicator ...
36d3cd371bb37fa5ee74f10b774ae4408a9164d2
3,634,244
from typing import Dict import requests def get_cultural_hotspots(url: str, params: Dict) -> pd.DataFrame: """Get cultural hotspots within city boundaries.""" package = requests.get(url, params=params).json() ch_locations = package["result"]["resources"][0]["url"] ch_locs_dir_path = "data/raw/cultural...
1a073998c51eca3f6a714462b864fa7d6c142e76
3,634,245
import optparse def setopts(): """ Setup all possible command line options.... """ usage = 'USAGE: %s [options]' % (NAME) version = NAME + " " + __version__ parser = optparse.OptionParser(usage=usage, version=version) parser.add_option("-v", "--voicefile", ...
af8efe810da81af1a20747b4fcc9aa8f244ed1fc
3,634,246
def f_test(df, ann): """Pre-select features without difference between types of dataset Parameters ---------- df : pandas.DataFrame A pandas DataFrame whose rows represent samples and columns represent features. ann : pandas.DataFrame DataFrame with annotation of samples. Th...
77b60abe9c09ff674f0af687552bacd75e8b75c4
3,634,247
from typing import Union def _is_group(cli_obj: Union[Group, Command, MultiCommand]) -> bool: """Detects if cli obj is a Group or not""" return isinstance(cli_obj, Group) and hasattr(cli_obj, "commands")
d262824ea8aabdd0e24740c2cbd0a9e0e4209ba1
3,634,248
import codecs import json def _get_input_json(input_path): """ A really basic helper function to dump the JSON data. This is probably a leftover from when I was iterating on different reduce() functions. """ # Read in the input file. input_file = codecs.open(input_path, encoding="utf-8", mode=...
5c91e77b2224435dbf17fcfc2351c574c173c6aa
3,634,249
import re import urllib def urn_from_member_name(member, base_urn): """Returns a URN object from a zip file's member name.""" member = utils.SmartUnicode(member) # Remove %xx escapes. member = re.sub( "%(..)", lambda x: chr(int("0x" + x.group(1), 0)), member) # This is an absolut...
f87a5f13aa3ae1fe840caa9d28c375295a730c82
3,634,250
def create_data_set(): """ 创建数据集 :return: """ data_set_ = [ [1, 1, 'yes'], [1, 1, 'yes'], [1, 0, 'no'], [0, 1, 'no'], [0, 1, 'no'] ] labels_ = ['no surfacing', 'flippers'] return np.array(data_set_), np.array(labels_)
e4c7cf3200d3acec618529a35196ec2f080d071b
3,634,251
from typing import Dict from typing import Any def get_text(xml: bytes, context: Dict[str, Any]) -> TablesList: """Xml as a string to a list of cell strings. :param xml: an xml bytes object which might contain text :param context: dictionary of document attributes generated in get_docx_text :returns:...
c6d1197b07cc1e07e0cb299b455d243c9ee023d0
3,634,252
from typing import Any def day(query: int, field_name: str, object: Any) -> bool: """ Checks if value of object is equal to query """ return query == getattr(object, field_name).day
b24fc0de6c01b355633dfbd240a760c1f51bfa6f
3,634,253
import glob import tqdm def glob_read(path, read_fun, stop_i=None, show_bar=False): """read all files in path by glob Args: path (str): absolute path read_fun ([type]): different read function based on file type stop_i (int, optional): stop read at file i. Defaults to None. s...
6932cda5ae27c72cf9db1a5360c1c130b5cea6ed
3,634,254
def argument(*name_or_flags, **kwargs): """Convenience function to properly format arguments to pass to the subcommand decorator. """ return list(name_or_flags), kwargs
7f1ba4d4005168f3c634840ddd20d6fbb73182f5
3,634,255
import math def conv_float2negexp(val): """Returns the least restrictive negative exponent of the power 10 that would achieve the floating point convergence criterium *val*. """ return -1 * int(math.floor(math.log(val, 10)))
562ccf7d34f8034a25cabfb471e7fc2ab9c0feb6
3,634,256
def pick_wm_class_2(tissue_class_files): """Returns the white matter tissue class file from the list of segmented tissue class files Parameters ---------- tissue_class_files : list (string) List of tissue class files Returns ------- file : string Path to segment_seg_2.nii...
a30809d94a57d12084fb1747cf1854163361c50d
3,634,257
def collect_datasets(data_type, varnames, list_of_ds, labels, **kwargs): """ Concatonate several different xarray datasets across a new "collection" dimension, which can be accessed with the specified labels. Stores them in an xarray dataset which can be passed to the ldcpy plot functions (Call thi...
bd5c67d61571f9a3ab41eafb88bfe6367462e052
3,634,258
def split_tiles(image, tile_size): """Splits the image into tiles of size `tile_size`.""" # The copy is necessary due to the use of the memory layout. if image.ndim == 2: image = image[..., None] image = np.array(image) image = make_divisible(image, tile_size).copy() height = width = tile_size nrows, ...
be3d48e4fd926d0a8d2226990dac01315dc0437a
3,634,259
from bs4 import BeautifulSoup import requests def get_insider_activity(ticker: str) -> pd.DataFrame: """Get insider activity. [Source: Business Insider] Parameters ---------- ticker : str Ticker to get insider activity data from Returns ------- df_insider : pd.DataFrame G...
97beab7bfc2ef90f74204777f0ef90c455fa0293
3,634,260
def resolve_dependencies(dependencies): """Resolve a set of dependencies to a specific versions or Unspecified. You can find more for the syntax of Debian dependencies relationships here https://www.debian.org/doc/debian-policy/ch-relationships.html Args: dependencies (str): string with depend...
bbc5335eaf93de0c72c7dde6272f39f75c941b71
3,634,261
def sampler(img_target, pose, intrinsics, rng, options): """ Given a single image, samples rays """ pose_target = pose[:3, :4] ray_origins, ray_directions = get_ray_bundle( intrinsics.height, intrinsics.width, intrinsics.focal_length, pose_target ) coords = jnp.stack( jnp.m...
e02907dbdef7f532ee6f843ff8fc367dc7a3ff56
3,634,262
from typing import List def sanitize_gpu_ids(gpus: List[int]) -> List[int]: """ Checks that each of the GPUs in the list is actually available. Raises a MisconfigurationException if any of the GPUs is not available. Args: gpus: list of ints corresponding to GPU indices Returns: u...
b6f3f7da19fc7f26c6229ffb80fbed3ed6dfe363
3,634,263
from typing import Type def gauge(name: str, documentation: str, labels: tuple = ()) -> Type[Gauge]: """Builds a gauge with configured namespace / subsystem.""" return Gauge( name, documentation, labelnames=labels, namespace=s.PROMETHEUS_NAMESPACE, subsystem=s.PROMETHE...
8267cfcbbd7bdef9e3d7b6dbe8db759c2f148f40
3,634,264
def uniform_scaling(weights, prune_ratio, prec_layers, succ_layers): """Better prune method Arguments: weights (OrderedDict): unpruned model weights prec_layers (dict): mapping from BN names to preceding convs/linears succ_layers (dict): mapping from BN names to succeeding convs/linears...
5a50dfd64bf9733ffbef957b184c3f88279338b1
3,634,265
def find_port(master_class_name, masters, output, opts): """Finds a triplet of free ports appropriate for the given master.""" try: master_class = getattr(Master, master_class_name) except AttributeError: raise ValueError('Master class %s does not exist' % master_class_name) used_ports = set() for m ...
a5616fdefac44e450a9135d0d11563b88a84a9dc
3,634,266
def find_match(good_message, bad_message): """ Makes the hash of the bad message match that of the good one. Args: good_message: The good message we want to match. bad_message: The bad message we want to make match. Returns: Variations of the good and bad messages that have the same hash. """ # Gene...
723683de6b24d651bc2ebab43b7ccd758de1c4de
3,634,267
import logging def query_by_date_after(**kwargs): """ 根据发布的时间查询,之后的记录: 2020-06-03之后,即2020-06-03, 2020-06-04, ...... :param kwargs: {'date': date} :return: """ session = None try: date = kwargs['date'].strip() + config.BEGIN_DAY_TIME session = get_session() ret = ses...
867faba9e835a8bbb539349ad316f5a594a6ead0
3,634,268
def split_data(im_in, dim, squeeze_data=True): """ """ # backwards compat return split_img_data(src_img=im_in, dim=dim, squeeze_data=squeeze_data)
e45e32e3654198e63597b0e813f3e929af11fc60
3,634,269
import csv import os import numpy def execute(args): """This function invokes the SDR model given URI inputs of files. It may write log, warning, or error messages to stdout. args - a python dictionary with at the following possible entries: args['workspace_dir'] - a uri to the di...
86a328f5f00fd55398b2128233a65fe646a93540
3,634,270
def user_groups(username, htgroup_fn, strict=True): """ Returns a list of group names for the given user """ groups = [] for group_name, users in read_groups(htgroup_fn, strict=strict).items(): if username in users: groups.append(group_name) return groups
adc452c60c25e672829d3efa99a0c4bf41213e64
3,634,271
def uffangle(i,j,k,boij,bojk,theta): """ Return the UFF parameters for an angle interaction in Gromacs units (degrees, kJ mol^-1 rad^-2). Not used for the nebterpolator but I decided to keep this code. i = Element symbol (string) j = Element symbol for the middle atom (string) k = Element s...
f57527c0adbff255d64304c11623cb706b3dc784
3,634,272
import random def img_get_random_patch(img,w,h): """Get a random patch of a specific width and height from an image""" # Note that for this function it is the user's responsibility to ensure # the image size is big enough. We'll do an asertion to help but... # Figure out the maximum starting point w...
41ce199eb5ab8eb136f740eb2e1b495226510690
3,634,273
def list_to_dict(items): """Create dictionary from a parenthesized list of attribute/value pairs :param items: list :return: dict """ if not items: items = [] # minimal # dict(zip(items[0::2], items[1::2]) def recursive(item): """Check value of parenthesized list and i...
a58ed6efe88592f0fa9af1c2daf9a132272e633f
3,634,274
def AVERAGEIF(avg_list, condition_list, condition): """Find the average of a list based on a specfic condition in another list. Parameters ---------- avg_list : list or array list or array that you will take the average of. Length must match condition_list. condition_list : list or array ...
1f34d34612626d500e534512eb493086ec19bce0
3,634,275
def fresnel_ts(n0, n1, theta0, theta1): """Compute the "t sub s" fresnel coefficient. This is associated with transmission of the s-polarized electric field. Parameters ---------- n0 : `float` refractive index of the "left" material n1 : `float` refractive index of the "right" ...
faf68134372ad5df8c31107e7ff8b006ee7a1f66
3,634,276
def get_client_id_from_access_token(aws_region, aws_user_pool, token): """ Pulls the client ID out of an Access Token """ claims = get_claims(aws_region, aws_user_pool, token) if claims.get('token_use') != 'access': raise ValueError('Not an access token') return claims.get('client_id')
6ce2d5771b863e4bf8da367284486f5618d09473
3,634,277
def bgloop(tag, *iterables, runner=None): """Run a loop in a background thread.""" if runner is None: runner = run_thread def decorator(func): if tag in bg_instances and bg_instances[tag].running: raise RuntimeError("Already running loop") bg_instances[tag] = Object() ...
553e650ecc0b640e0cea3ad4c714cb3d66d327b4
3,634,278
from typing import AnyStr from typing import List from typing import Dict def get_metrics_rating(start: AnyStr, end: AnyStr, tenant_id: AnyStr, namespaces: List[AnyStr]) -> List[Dict]: """ Get the rating for metrics. :start (AnyStr) A t...
852ce6a21f03b02691748d6d9a654edf10b7ed54
3,634,279
from typing import List def calculate_previous_risk_score_weightings() -> List[float]: """ Creates a risk score weighting distribution of size MAX_PREVIOUS_INCIDENTS such that the distribution is a decreasing linear series that sums to 1. For example, with MAX_PREVIOUS_INCIDENTS == 3, this function re...
6064c345973335026c49522aada829eec67a5ba6
3,634,280
import torch def warp(x, flo, device): """ warp an image/tensor (im2) back to im1, according to the optical flow x: [B, C, H, W] (im2) flo: [B, 2, H, W] flow """ B, C, H, W = x.size() # mesh grid xx = torch.arange(0, W).view(1, -1).repeat(H, 1) yy = torch.arange(0, H).view(-1, 1).r...
d009beeab36a84ba2659d87d22dc98ad0b20bf52
3,634,281
import os def expand_path(filename: str) -> str: """ Expands variables (user and environment) in a file name. :param filename: File name, possibly containing variables. :return: File name with variables expanded. """ return os.path.expandvars(os.path.expanduser(filename))
b6dae3491edbaa00a5f73959b2227ad2fe6f506e
3,634,282
def FindVolumeClose(hSearch): """Close a search handle opened by FindFirstVolume, typically after the last volume has been returned. """ if kernel32.FindVolumeClose(hSearch) == 0: return error(x_kernel32, "FindVolumeClose")
48a8c4629d9bc10b4a8befa33f399ed1a3727347
3,634,283
import os import logging def load_loggers(debug, persistent_storage): """ Loads all the loggers :param debug: is Debug enabled :param persistent_storage: is persistent storage enabled :return logger: main logger of the application :return storage_loggers: loggers for the persistent data engin...
6bbfc68cdd31c47d7d4f8f5388a71e82b116f342
3,634,284
def authenticated(method): """ Decorate methods with this to require that the Authorization header is filled. On failure, raises a 401 or 403 error. Raises: :py:class:`tornado.web.HTTPError` """ @wraps(method) async def wrapper(self, *args, **kwargs): if not self.current_...
bf64966f14d76b0f755f1d17672540a361c99c35
3,634,285
def _calculate_f1(conf_matrix): """ Calculate classification macro F1 score. Parameters ---------- conf_matrix : pandas.DataFrame DataFrame of confusion matrix. Returns ------- f1_total : float Total classification macro F1 score including detection FP and FN. f1_ta...
9dded3affbc164487020898cb46765e5c1dc8553
3,634,286
def prepare_wiki_content(content, indented=True): """ Set wiki page content """ if indented: lines = content.split("\n") content = " ".join(i + "\n" for i in lines) return content
14daea5cdb509b333c2aead6dcb453a82e73ce8d
3,634,287
def get_user_args(): """ **get_user_args** fetches user arguments from arguments""" display_name = request.args.get('display_name') email = request.args.get('email') email_verified = request.args.get('email_verified') uid = request.args.get('uid') cell = request.args.get('cell') provider_dat...
679836f40c441a6b61ef05bf9f96ef328c4751a4
3,634,288
def calculate_camera_center(P: np.ndarray, K: np.ndarray, R_T: np.ndarray) -> np.ndarray: """ Returns the camera center matrix for a given projection matrix. Args: - P: A numpy array of shape (3, 4) representing the projection matrix Retur...
6bec2422af375cd1b0c6570a38f6afe60c7f927e
3,634,289
def __need_local_verify(ins:VerifyTokenLocal=None): """ ins 是否存在,是否 VerifyTokenLocal 对象 :param ins: :return: """ if ins is None: return False # 为 None, 不需要本地验证 if not isinstance(ins, VerifyTokenLocal): # 有值,但是不是 VerifyTokenLocal 实体,抛出异常 raise WrongLocalVerifyTokenInsErr...
b418cedc53e49dfdc93d25e822b6b8803e080d17
3,634,290
import sys import os import time import subprocess def blaster(counts, database, outname = "output"): """ Takes a list of counts in the format [[sequence, total reads, unique],...] then blasts each sequence against the RNASeqList (fasta formatted). Top match is appended to the end of each member of the co...
4b13528c21ac6eb4c6a994457f9a7511890805aa
3,634,291
def average_spectra(spec_data, t_avg, h_avg, **kwargs): """ Function to time-height average Doppler spectra :param spec_data: list of xarray data sets containing spectra (linear units) :param t_avg: integer :param h_avg: integer :param kwargs: 'verbosity' :return: list of xarray data sets co...
071fca747555fdfaebc717a3e1caf98e326c89d6
3,634,292
import argparse import logging def parse_args(args): """Parse command line parameters Args: args ([str]): command line parameters as list of strings Returns: :obj:`argparse.Namespace`: command line parameters namespace """ parser = argparse.ArgumentParser(description="Sync Gitlab Iss...
9f0534e0c38fe55ee1d9006da06245916a0a1753
3,634,293
def get_db_dot_fmt_strings(db_list, config, query_extension="fasta"): """ Return a list of strings that are "{db}.{format}". Where db is the name of the database and format is the extension generated by the search (eg lastx, or tbl). There is a special case for fragmented HMM dbs where we need to add ".dbatch" ...
d5ef3640f131189917966149bbcc50e530b1727c
3,634,294
import numpy def colormap(exps, colorby, definedinEM, annotation=None): """Generate the self.colors in the format which compatible with matplotlib""" if definedinEM: if colorby == "reads": color_res = [] for i in exps.get_readsnames(): c = exps.get_type(i, "colo...
d777fb19b52b097b569fff0f315d63115c8e2231
3,634,295
def wfs_25d_point(omega, x0, n0, xs, xref=[0, 0, 0], c=None, omalias=None): """Point source by 2.5-dimensional WFS. :: ____________ (x0-xs) n0 D(x0,k) = \|j k |xref-x0| ------------- e^(-j k |x0-xs|) |x0-xs|^(3/2) """ x0 = util.asarray_o...
87fbf4dc467e0c0b7a9259d80f69125326dbf86d
3,634,296
def load_labels(fn, delimiter=',', id_col=0, label_col=1): """ Load ID list with label IDs e.g. use to load segment label, or synapse label """ d = np.genfromtxt(fn, delimiter=delimiter, dtype=int) label_to_id = {} id_to_label = {} for i in range(d.shape[0]): push_dict(label_to_i...
001dc4c3da6b9614e8c87471b86697fabad3299e
3,634,297
import os import json def write_data(): """ Write any json data received, to a temporal folder. This data will be, later on, read by other services. :return: """ with open('/tmp/{}'.format(os.environ.get('PAYLOAD_FILENAME', 'data.json')), 'a') as out: out.write(json.dumps(json.loads(reques...
1a50fd2e87eadebc0ba440753d7373a186fdb642
3,634,298
def flatten_with_joined_string_paths(structure, separator='/'): """Replacement for deprecated tf.nest.flatten_with_joined_string_paths.""" return [(separator.join(map(str, path)), item) for path, item in tree.flatten_with_path(structure)]
36b814752f5879996fb135904bb619a909ab302b
3,634,299