content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import itertools import functools import copy def render_with_cache(seq_collection, fuzzing_pool, checkers, generation, global_lock, seq_rendering_cache): """Render sequences one by one, caching valid prefixes and re-using previously valid renderings if found. For brevity we skip arguments and return types...
52284dfada9b4dfe815fa93f93f5539e684a5b54
63,900
def _get_app_module_with_cache(cc_biz_id, username): """获取业务下的模块列表,按名字排序""" cc_result = bk.cc.get_modules_by_property(app_id=cc_biz_id) if not cc_result.get('result', False): raise APIError(cc_result.get('message', 'call component sdk error')) cc_data = cc_result['data'] data = sorted(cc_dat...
b74d5d2ce89eeb2288d8dd080079e89d22646036
63,901
def normalizeData(trainIn, trainOut, valIn, valOut): """Normalizes the training and validation data to improve network training. The output data is normalized by taking its log and then scaling according to its normal distribution fit. The input data is normalized by scaling it down to [-1,1] using...
51bf954ec77abc8e792602aed3c2fd6e16c1dab4
63,902
def get_config_dict(robustness_tests, base_config_dict): """ Combines robustness_test and train_config_dict into a single config_dict. Args: robustness_tests (dict): robustness test config dict base_config_dict (dict): train/data/eval/model/hyperparam config dict Returns: confi...
593a2307849fa27b895f18d8b9eacd679eeab04a
63,903
import typing from typing import Type def sequence_type(typeinfo: typing.Type[typing.List]) -> Type: """Return the type of a sequence, e.g. typing.List""" try: return typeinfo.__args__[0] # type: ignore except AttributeError: # Python 3.5.0 return typeinfo.__parameters__[0]
2d53197bce19f80aa1b33df97d836568def72cfc
63,904
def distance_vector_between(point_1, point_2): """Compute and return the vector distance between two points.""" return [point_2[0] - point_1[0], point_2[1] - point_1[1]]
397d3191cc4c214bb0d4b474db2efe7c63e8a10f
63,905
import torch def prepare_model(): """Main training program.""" #print('Generate Samples') # Disable CuDNN. torch.backends.cudnn.enabled = False # Timer. timers = Timers() # Arguments. args = set_args() #print(args) args.mem_length = args.seq_length + args.mem_length - 1 ...
24d2f0913165f2ed2ef5c30826a08ab6a0560d70
63,906
def htmlReadFd(fd, URL, encoding, options): """parse an XML from a file descriptor and build a tree. """ ret = libxml2mod.htmlReadFd(fd, URL, encoding, options) if ret is None:raise treeError('htmlReadFd() failed') return xmlDoc(_obj=ret)
c14fd1aacc6b2d64da04a669dee505ad42b8c27d
63,907
def execute_get_credentials_with_varying_input(tmp_path, monkeypatch): """First, reset global variable of Ahjo's credential_handler module. If this is not done, tests will affect one another. Second, create username/password files with given content and store file paths to list created_records. ...
2dbb84fbd2cbd3a59c08a7898b02a6065faaa9e5
63,908
def saveableMenu(cls: type) -> type: """A decorator registering a ReactionMenu subclass as saveable. Once applied, instances of your class will automatically save their toDict representation to SQL on creation, and the instance will be reconstructed on bot restart with your provided fromDict implementation....
919c5ba9e1ffa23b10e0b26a90c2e1d38a3048e0
63,909
import os import shutil def copy(src: str, dst: str, clobber: bool = True) -> str: """Copy file from source to destination :param src: source path :param dst: destination path :param clobber: Should we overwrite (defaults to `True`) :raises ChoreSkippedException: If there is missing inputs. :...
7a601bf2d614286a5f9c86470a27e56c35d0676c
63,910
import torch def top_p_filter(logits: TensorType[..., "vocab"], threshold: float = 0.9): """ Nucleus sampling """ sorted_logits, sorted_indices = torch.sort(logits, descending=True) cum_probs = torch.cumsum(F.softmax(sorted_logits, dim=-1), dim=-1) sorted_indices_to_remove = cum_probs > (1 - ...
6d3318ee58d64f3f502627146bb168253f2e69e0
63,911
def get_mod_name(part_family_name): """Get the module name for full part. Args: part_family_name (str): A key in the RM_ALL_PART_FAMILY_NAMES. Returns: str: A value from RM_ALL_PART_FAMILY_NAMES. """ try: mod_name = _RM_PART_FAMILY_MAP[part_family_name] except KeyError:...
050b0248de2bb24ae5b64f627c22ad7cbd93af58
63,912
def perm_add_replicas(issuer, kwargs): """ Checks if an account can add replicas. :param issuer: Account identifier which issues the command. :param kwargs: List of arguments for the action. :returns: True if account is allowed, otherwise False """ rse_id = str(kwargs.get('rse_id', '')) ...
fcc9c0b5687aca7c16ae3ac3a1d0c69056f3e1e0
63,913
import functools def admin_required(f): """Decorator to require admin for a method.""" @functools.wraps(f) def wrapper(*args, **kwargs): try: if not flask.g.admin: app.logger.error( 'Attempt by non-admin to access ' '@adm...
dfd6a5777cd0ed2a3d0de3ab4fb7458ade4714bc
63,914
def print_consensus(genomes): """ print consensensus sequences for each genome and sample """ # generate consensus sequences cons = {} # cons[genome][sample][contig] = consensus for genome, contigs in list(genomes.items()): cons[genome] = {} for contig, samples in list(contigs.it...
0b49c5709af71f017e9114ac403ff86b41fe0478
63,915
from typing import Set import types def get_categorical_features(schema: schema_pb2.Schema ) -> Set[types.FeaturePath]: """Gets the set containing the names of all categorical features. Args: schema: The schema for the data. Returns: A set containing the names of all catego...
e143b36a0016968c93cbf831fab8850508380764
63,916
def calc_language_vectors_URIEL(features_sets): """Returns the combined URIEL language vectors for given feature sets. Args: features_set (list of str): The name of the feature sets. Returns: list of (list of float): The language-property matrix. Languages are indices, properties are columns. list of str: T...
ceeeab15342d61ca0f8a684db77b6f348cef84e7
63,917
def get_dataset( name, num_samples_per_class=None, class_ids=None, load_fn=tfds.load, data_dir=None): """Get the subset of the MNIST dataset containing the selected digits. Args: name: name of the dataset. Currently support mnist and cifar10. num_samples_per_class: number of samples for each class....
eb75bfb57c3963e341995b9a314dfaf46b01ea7d
63,918
def true_score_variance(human_scores, variance_errors_human=None): """ Compute variance of true scores for multiple raters. Parameters ---------- human_scores : array-like of shape (n_samples, n_ratings) Human ratings for each response. variance_errors_human : f...
ff55300b7767662b194b62bc53306b5fc219b749
63,919
def fiabilite2(v1 : float, v2 : float, v3 : float , epsilon : float) -> float: """ ... cf. ci-dessus ... """ if egal_eps(v1, v2, epsilon): if egal_eps(v1, v3, epsilon): if egal_eps(v2, v3, epsilon): return 1 else: return 2/3 ...
4567377c538c60229ea32875524e776f2e16a936
63,920
import math def matrixToEuler(mat): """ code from 'http://www.euclideanspace.com/maths/geometry/rotations/conversions/' notes : this conversion uses conventions as described on page: 'http://www.euclideanspace.com/maths/geometry/rotations/euler/index.htm' Coordinate System: right hand Positiv...
c79def074aec61023d7914319e7adafaaf42b5d3
63,921
def var_Y(y_vector): """ Args: no array Output: variance as float """ m=y_vector.mean() diff_v=0 for i in range(len(y_vector)): diff_v+=(y_vector[i]-m)**2 res= diff_v /len(y_vector) return(res)
80847d75ffac23b43e75e1727caab910b7856dbc
63,922
def m2Lambda_to_vMh2(m2, Lambda, C): """Function to numerically determine the physical Higgs VEV and mass given the parameters of the Higgs potential.""" try: v = (sqrt(2 * m2 / Lambda) + 3 * m2**(3 / 2) / (sqrt(2) * Lambda**(5 / 2)) * C['phi']) except ValueError: v = 0 ...
f999c82b4a74c0d11e6735870a33c9add9fb1ee7
63,923
def StoreEnclosedBoundaries(Spaces, WallInfo, OpeningsDict): """ Add the id's of included space boundaries to their related space boundaries """ for sp in Spaces: for b in sp.Boundaries: if b.RelatedBuildingElement in WallInfo.keys() and (len(b.GapsProfile)>0 or len(b.Profile)>4): ...
f75b2ac6a502d23a4622d83dabf53586feb0ec0e
63,924
def cache_get_names(connection: 'Connection', query_id=None) -> 'APIResult': """ Gets existing cache names. :param connection: connection to Ignite server, :param query_id: (optional) a value generated by client and returned as-is in response.query_id. When the parameter is omitted, a random value...
e1ba6bdd2e0fdda6aad304df1aaab73af3a7f0be
63,925
def _show(app_id, version): """Show details of a Marathon application. :param app_id: The id for the application :type app_id: str :param version: The version, either absolute (date-time) or relative :type version: str :returns: process return code :rtype: int """ client = marathon...
47779307b66c20aa4be5652f3b5ead9df051b679
63,926
def bootstrap_conf(runs, significance=0.01): """ THIS NEEDS TO BE UPDATED Gets the bootstrap confidence interval of the distribution of mean return per episode for a single hyperparameter setting. Note that this function assumes that there are an equal number of episodes for each run. This is...
2a5229782ee96a6dc169cc06603fb1683ea9da50
63,927
import requests import json import time def get_impress_entity_by_id( impress_api_url: str, impress_type: str, impress_id: str, retries=0 ): """ :param impress_api_url: :param impress_type: :param impress_id: :param retries: :return: """ api_call_url = "{}/{}/{}".format(impress_ap...
8dae44bbba66d013dededb892ae186bc42999905
63,928
def are_coords_majority_overlap_in_read(c0, c1, min_overlap_ratio=0.5): """Return True if majority of two coords overlap with each other in read coordinates. """ min_read_len = min(c0[READ_END]-c0[READ_START], c1[READ_END]-c1[READ_START]) # min read length overlap = min(c0[READ_END], c1[READ_END]) -...
f2db92b1765c2d809798795f87100011237776bc
63,929
def modify_expansion(tokens: Expansion, diff: Diff) -> Expansion: """ Modify tokens according to the diff: keep and strip regex from the ones in diff.included, and remove the ones in diff.excluded. For example, match_tokens(['"hi"', 'x?', 'my name is', 'y?', 'z?'], Diff(['x?'], ['z?'])) returns ...
87944ec8bbfdf5d1078a4d4dd2d53ec251c64d5b
63,930
from typing import Optional import math def plot_ts_analysis( df: pd.DataFrame, y_col: str = None, time_col: str = None, nfft: int = 1024, acf_n_lags: int = None, pacf_n_lags: int = None, alpha: float = 0.1, show: bool = True, title: str = None, ) -> Optional[BaseFigure]: """ ...
4e27442bf5dbf976e16ac02340888cefd04e04cd
63,931
def split_names(data, names, fosa_types, drop): """Separates facility type prefix from facility name inputs data: data frame containing source data from IASO names: column name to split fosa_types: list of facility types drop: list of prefixes indicating row should be dropped fro...
4842756abd8b332d22548382f56a7c03d43609c2
63,932
from typing import Iterator def bind(app: Flask = None, device: str = None, batch_size: int = None, model_file: str = None, formatter_class: Formatter = None, tokenizer: Tokenizer = None, allow_origin: str = None, route_path: str= "/", headers=None) -> Flask: """ Binds default value ...
2f93d6c38a449824837ba22044d3d659086668fe
63,933
def populate_workflow_request_body(data): """ Populate request body according to the API specification :param data: item data from manifest files :return: populated request :rtype: dict """ request = { "runId": "", "executionContext": { "a...
3d043d5645dd15a78bac32de7a676ec56cb4f169
63,934
def recall_at_k(ranks, k): """Compute recall at K args: ranks (list): list of rankings of positive pairs k (int): k """ return 100.0 * len(np.where(ranks < k)[0]) / len(ranks)
b4b780933ab578e2642575038413f31c9f6a4328
63,935
def TVD(Sw,N, mio, miw, j, porosity, deltt, deltx, delty): """This simulator is different from the previous 'First_TVD' because the is a 'reverse copy' of all the math, this means that, while the for makes the simulator advance from 0 to N, there are the same math doing from N to 0, using the opos...
4b5b94bdba8ef6bee28e183b0585742331d18d1d
63,936
def gsl_finite(*args, **kwargs): """gsl_finite(double const x) -> int""" return _gslwrap.gsl_finite(*args, **kwargs)
5eab8a6edd8048e9d990d88c327965c9f8a4710c
63,937
from Levenshtein import distance def distance(str_one, str_two): """ Return the absolute levenshtein distance of two strings, or None if the Levenshtein package isn't available. """ try: return distance(str_one, str_two) except ImportError: return None
1cadb1200eb3e2683e45d2a40ccfff9cbe609bfc
63,938
import os def dirtests(d): """Finds all of the test files in a directory.""" files = os.listdir(d) filenames = [] for file in files: if not file.endswith('.py'): continue if TESTNAME_RE.match(file) is None: continue filenames.append(file[:-3]) return...
47df1a354900201e08955a2aedf93984878d1128
63,939
def kolsmi(dist, fit_result, data): """Perform a Kolmogorow-Smirnow-Test for goodness of fit. This tests the H0 hypothesis, if data is a sample of dist Args: dist: A mle.Distribution instance fit_result: The solution dict, returned by the Distribution.fit method data: ...
3d1dedab1d3d8222777c4dab4b22ea483efe9e1d
63,940
def _GetModelDeploymentResourceType(model_ref, client): """Gets the deployment resource type of a model. Each model resource belongs to exactly one supported deployment resource type. The value is the first item in the list, the length of which must be one. Args: model_ref: a model resource object. cl...
cff2c3ff693e7756a0cae44682ba34aac2c4422e
63,941
def pull_package(title, version, url, json=False): """ :param title: :param version: :param url: :param json: :return: """ return _pull(''.join([url, '(Id=\'', title, '\',Version=\'', version, '\')']), json=json)
d548c88ec2bdde704b8c675f02ccc00373c6f0d8
63,942
import sqlite3 import numpy def get_random_song(): """ returns a random completed song """ with sqlite3.connect(past_games_db) as c: game_ids = c.execute('''SELECT rowid FROM games''').fetchall() random_id = game_ids[numpy.random.randint(0, len(game_ids))][0] song = c.execut...
1b0f7feb92949de6f6aa111bf9b2a018cc056f56
63,943
def _NamesNotIn(names, mapping): """Returns a list of the values in |names| that are not in |mapping|.""" return [name for name in names if name not in mapping]
ec91dcb6e29b0a9c1aa66f04e1b61d715ded3266
63,944
def get_user(user_id: int) -> JSONType: """ GET /users/{user_id} :raises: backend.errors.UnauthorizedError (HTTP error 401) backend.errors.ForbiddenError (HTTP error 403) backend.errors.NotFoundError (HTTP error 404) """ result = user_service.get_user_by_id(user_id) ...
dd3490a15c719fc7fc25bbcd7901e097e7a87f4b
63,945
from typing import Sequence from typing import Any import copy def baseline_replacement_by_patch(arr: np.array, patch_slice: Sequence, perturb_baseline: Any, **kwargs) -> np.array: """Replace a single patch in an array by given baseline.""" if len(patch_slice) != arr.ndim: ...
fa64a5e12b36199d8048289f7ab18665355ecb47
63,946
import re def natural_sort(l): """ Takes in a list of strings and returns the list sorted in "natural" order. (e.g. [test1, test10, test11, test2, test20] -> [test1, test2, test10, test11, test20]) Source: https://stackoverflow.com/questions/4836710/is-there-a-built-in-function-for-string-natural-sor...
7db22ee5f75703f52b25eecd888847eb35590e65
63,947
def dict_indexable(*iterables): """Make arrays indexable for cross-validation. Checks consistent length, passes through None, and ensures that everything can be indexed by converting sparse matrices to csr and converting non-interable objects to arrays. Parameters ---------- *iterables : l...
739dba44b4cfcb5c65c296633c7d35f55d37e9f2
63,948
def get_extensions(list_of_files): """Function take a list of Path file objects and adds the file extenstion/suffix to a set. The set of extensions is returned""" extensions = set() for file in list_of_files: if len(file.suffix) < 6: extensions.add((file.suffix).lstrip('.')) ret...
654b893c148535a99dd112dc3711ea9005ae96b7
63,949
def get_object(sts_creds, req_header): """ Retrieve objects from NoSQL (DynamoDB) based on {tenant_id, user_id} as partition key :param sts_creds: :param req_header: :return: 200 - Success 400 - Bad Request, 401 - Unauthorized 500 - Error, 503 - Unav...
d063e0d24a99f610085ba759a5b583762edac5ae
63,950
from typing import Dict from typing import List from typing import Tuple import binascii def extract_ct_body(params: Dict[str, List[str]]) -> Tuple[str, bytes]: """ Extract the content type and body from a list of get parameters. :param params: A dictionary of key/value of parameters as provided by ur...
b377ddd894c7b24eb0ba8b81cc5e40ec70bf71bf
63,951
def sample_nu_free_free(numba_plasma, shell): """ Attributes ---------- nu_ff_sampler : float Frequency of the free-free emission process """ T = numba_plasma.t_electrons[shell] zrand = np.random.random() return -K_B * T / H * np.log(zrand)
f09b0add007937f4ccc8ce5c6fb5506246aeb23d
63,952
def softmax_func(y): """Numerically stable softmax.""" b = y - np.max(y, axis=1, keepdims=True) expb = np.exp(b) softmax = expb / np.sum(expb, axis=1, keepdims=True) return softmax
ef0b9d528129a9e524b9046fee9b7f6a8fccccfe
63,953
def GetASTSummary(ast): """ Summarizes an AST field Flags: P - AST_PREEMPT Q - AST_QUANTUM U - AST_URGENT H - AST_HANDOFF Y - AST_YIELD A - AST_APC L - AST_LEDGER B - AST_BSD K - AST_KPERF M - AST_MACF C - AST_CHUD ...
8438255d9fea96c6051da5cbec57bef6949e49d6
63,954
from typing import Any def parse_program(tokens: list[Token]) -> list[NodeBase] | None: """Return a parse tree from list of tokens""" _parser_check() if not tokens: return None nodes: list[Any] = [] index: int = 0 while index < len(tokens): node, j = _parse_statement(tokens[ind...
1384a55d7e66d492702c8d6872eb71f3f3af0357
63,955
from typing import Tuple from typing import Iterator def test_run_hill_climbing(): """Tests for run_hill_climbing().""" S = Tuple[int, int] # grid (row, col) A = str # up, down, left, right def _grid_successor_fn(state: S) -> Iterator[Tuple[A, S, float]]: arrival_costs = np.array([ ...
486c655f166dda641ac514caa8b1a989abbd2613
63,956
def make_rankfile(offset,nnodes,npn,d,logger=None): """ Create rankfile, which is required in Fujitsu FX100 when plural jobs are to be running in one submission, into the directory specified by `d`. The rankfile should be like, :: (0) (0) ... (1) (1) ... ...
5d590e8903230961928974bf76bb855f423d3edb
63,957
def compute_biases(X, beta=0, inplace=False): """Row and column centering from csr matrices Parameters ---------- X: csr-matrix (n_samples, n_features) Data matrix inplace: boolean, Perform centering on the input matrix Returns --------- X: csr-matrix (n_samples, n_fea...
29f500e913b8977e42a1a416a2baa93c82798ab8
63,958
def get_area( info, lb, ub, min_val, max_val, goal, time, timeout, values, check ): """ Returns the solving area. """ if info == 'unk': return timeout if info in ['uns', 'unb']: return time scaled_vals = sorted([ (t, scale(v, lb, ub, min_val, max_val, goal)) for (t, v) in values.items() ]) ...
84dfd8d1e096fae14e56f6afec50042b37d3e93a
63,959
from aiida.engine.utils import instantiate_process from aiida.manage.manager import get_manager from aiida.plugins import CalculationFactory def generate_calc_job(): """Fixture to construct a new `CalcJob` instance and call `prepare_for_submission` for testing `CalcJob` classes. The fixture will return the `C...
fd649d3a9a254d707fde374d69a63667a3177837
63,960
def _theme_less(filename): """ Render LESS files. """ return static_app.less(filename, 'theme')
d4d875f575cb516bf1dbf9e229133a32e66c80bc
63,961
def none_fn(*fs): """Constructs a predicate, which holds when none of fs hold.""" return compose(none, ijuxt(*fs))
2689a5078f46a4849bf8be41034c4bd5c31cb81f
63,962
def pyobj_role(make_node, name, rawtext, text, lineno, inliner, options=None, content=None): """Include Python object value, rendering it to text using str. Returns 2 part tuple containing list of nodes to insert into the document and a list of system messages. Both are allowed to be empty. :para...
8563cad97d62d11d0103a2d810eb974e0fd705bf
63,963
from typing import Sequence from typing import Mapping import asyncio import math async def target_distribution( assets: Sequence[trader.Asset], value_asset: trader.Asset, client: binance.BinanceClient, period_ms: int, window: binance.Interval, beta: float, ) -> Mapping[trader.Asset, float]: ...
f5178de0dddb4d2d76e900a779e6d34c31bb454a
63,964
def sharedreposource(repo): """Returns repository object for source repository of a shared repo. If repo is not a shared repository, returns None. """ if repo.sharedpath == repo.path: return None if util.safehasattr(repo, b'srcrepo') and repo.srcrepo: return repo.srcrepo # the...
756f035f8bbce249b3d4e593bf43819ca3b29961
63,965
def make_emailchange_token(user_id, email): """Generate an email change confirmation token. """ return _make_token({ 'user': user_id, 'email': email, }, 'dp.net.user.emailchange')
eedb89825fe4d78b0f8a8f5eeebce88816d314a7
63,966
def coin_list_to_symbol_list( coin_list, currency='USD', strict=False ): """convert list of crypto currencies to HitBTC symbols Args: coin_list (str or :obj:`list`): list of coins to convert currency (str, optional): currency to FOREX against strict (bool, option...
b05e718c44be3af9c50e982b7e260f9234be8f85
63,967
def Compute10(geometry, area, firstMoments, secondMoments, productMoments, multiple=False): """ Computes the AreaMassProperties for a collection of geometric objects. At present only Breps, Surfaces, Meshes and Planar Closed Curves are supported. Args: geometry (IEnumerable<GeometryBase>): Obje...
e10ead6338c105572cfcf043e317fc22bd9d2721
63,968
def __x_product_aux (property_sets, x_product_seen, x_product_used, feature_space): """ Implementation of __x_product. """ result = [] if property_sets: p = feature.split (property_sets [0]) else: p = [] f = set.difference (get_grist (p), feature.free_features ()) ...
542d5b719aa0617d54d9699b65a9d3d188597160
63,969
def calc_baseflow(data, measurements_per_day=1): """ Calculates the 5 day baseflow after Gustard et al 1992, p. 21 See: Report No. 108, Low flow estimation in the United Kingdom, . Gustard, A. Bullock December 1992 and J. M. Dixon" http://nora.nerc.ac.uk/id/eprint/6050/1/IH_108.pdf :par...
5e22e0446afabb3d9df40fc4333433ef4cbe176f
63,970
def pnorm(x: Tensor, p: int = 2) -> Tensor: """ Returns the p-norm of a vector. :param x: Vector of shape [*, N, 1]. :param p: Order of the norm. :return: P-Norm of the vector of shape [*, 1, 1]. """ assert x.shape[-1] == 1 return x.pow(exponent=p).sum(dim=-2, keepdim=True)
f4f9172e59daada6077602cf9afe8dddc57fef44
63,971
def EventTypeFromTypeString(source_crds, type_string): """Returns the matching event type object given a list of source crds.""" for crd in source_crds: for event_type in crd.event_types: if type_string == event_type.type: return event_type raise exceptions.EventTypeNotFound( 'Unknown even...
9b5b88601d49a438eb5164173e078dec310064e2
63,972
def params_verify(pars_str: str): """ 装饰器-参数校验装饰器 旨在校验函数调用时pars_str中的各参数不可空,逗号分隔; 即使字典形的有默认入参的,调用时也不可省略 * 注:1:此类调用,仍不允许 # ---define----- @params_verify("a") def func_a(a, **kwargs): pass # ---use----- # *error func_a('',a=1) # *ok ...
78faf501150b61d3b7ce165ba32da3174aa739dc
63,973
def _include_fullname_in_traceback(f): """ `Doc.__repr__` should not raise, but it may raise if we screwed up. Debugging this is a bit tricky, because, well, we can't repr() in the traceback either then. This decorator adds location information to the traceback, which helps tracking down bugs....
cb551726da58cbb71eeab0ff9a5d4afa46fbc8b0
63,974
def days_without_holidays(days_of_week, holiday_list): """ Given a tuple for the two lecture days of the week, returns a list of valid dates, removing any that clash with holidays """ sanitized_holidays = [] for h in holiday_list: sanitized_holidays.append(parse(h)) sanitized_dates...
167fe1f2b6b0b737aec3e171f9a1787aedc93c24
63,975
def is_valid_part1(line): """ >>> is_valid_part1('1-3 a: abcde') True >>> is_valid_part1('1-3 b: cdefg') False >>> is_valid_part1('2-9 c: ccccccccc') True """ first, second, letter, password = extract(line) count_letter = password.count(letter) return first <= count_letter <=...
9a8f3f08f0152727545d213db4d97e162a540389
63,976
from typing import Optional from typing import Dict def update_code( existing_code: Optional[str], input_type_dict: Dict[str, DataType], output_type_dict: Dict[str, DataType], component_name: str, description: str, category: str, ) -> str: """Generate and update component code Tries t...
6ad7c31cfc9a2c0873a7f0e94d58c27d1323f4da
63,977
def convert_list_array(A, opt: str): """Change from list to array or from array to list""" # change to list if opt == 'list': if not isinstance(A, np.ndarray): B = False else: B = A.tolist() # change to array elif opt == 'array': if not isinstance(A, l...
de2ac7367220f25d4cf610a9586c01952670cab4
63,978
import torch def collate_fn(batch): """单条样本格式:[CLS]篇章[SEP]答案[SEP]问题[SEP] """ batch_token_ids, batch_segment_ids = [], [] for (p, q, a) in batch: p_token_ids, _ = tokenizer.encode(p, maxlen=max_p_len + 1) a_token_ids, _ = tokenizer.encode(a, maxlen=max_a_len) q_token_ids, _ = to...
ef609e70a2bd96c58c0f555c0cdc934c71b5660f
63,979
def is_sequence_list(sequence_list): """Judge the sequence list is within the scope of alphabet and change the lowercase to capital.""" count = 0 new_sequence_list = [] for e in sequence_list: e = e.upper() count += 1 res = is_under_alphabet(e,ALPHABET) if res is not Tru...
baee6d66559395289f96a8299eda2b5b334f38ff
63,980
def phase_difference(Q): """get displacement from phase plane through neighbouring vector difference find slope of the phase plane through local difference of the pahse angles Parameters ---------- Q : np.array, size=(m,n), dtype=complex normalized cross spectrum ...
ea7a38ba554038c88fde5dbc8e38c1e6cdb09ee2
63,981
from typing import Tuple def m_step( rngs: PRNGSequence, actor_optimizer: optim.Optimizer, actor_target_params: FrozenDict, eps_mu: float, eps_sig: float, mu_lagrange_optimizer: optim.Optimizer, sig_lagrange_optimizer: optim.Optimizer, max_action: float, action_dim: int, state:...
f033751cfaf1ba262c3c9fae98b4ae3cfc93639a
63,982
from re import split def do_set_varable(parser,token): """ Set new value in the context of template. Usage: {% set category_list category.categories.all %} {% set dir_url "../" %} {% set type_list "table" %} {% include "category_list.html" %} """ bits = split(r'\s+...
1c639dcdc3367312547732354631a35950aeb4dc
63,983
def highlight_fires(filename): """ :param filename: str, allow users to input a file path :return: SimpleImage, return an image (a SimpleImage object) back to users """ img = SimpleImage(filename) for pixel in img: avg = (pixel.red + pixel.green + pixel.blue) // 3 # When the red...
54e1da580dc7df4df9c4ae13699bfc1303b14d6b
63,984
def file_download(object_id, input_params={}, always_retry=True, **kwargs): """ Invokes the /file-xxxx/download API method. For more info, see: https://documentation.dnanexus.com/developer/api/introduction-to-data-object-classes/files#api-method-file-xxxx-download """ return DXHTTPRequest('/%s/down...
c1250b2509f2e1b52f64fad5d4495bdf049ab3d1
63,985
def create_machine_learning_workflow( name="CreateEdgeProbabilityMap", resample=True, plugin_args=None ): """ This function... :param name: :param resample: :param plugin_args: :return: """ workflow = Workflow(name) input_spec = Node( IdentityInterface( [ ...
014ff3cffc0bef91d46d114cc5f7fd3a3a451dad
63,986
from typing import Counter def get_distance(url): """Given an URL, parse content and get Cosine distance from given list of keywords """ text = get_text_from_url(url) keywords = get_keywords_vectors(text) k_counter = Counter(keywords) st_k_counter = Counter(standard_keywords) dis = cou...
463a84a659314151535b33153260218f34dbaac0
63,987
from typing import Any import ast import inspect def get_function_def(obj: Any) -> ast.FunctionDef: """Get FunctionDef object from living object. This tries to parse original code for living object and returns AST node for given *obj*. """ try: source = inspect.getsource(obj) if so...
27b28b1f1b9fa1999b295bf524dcfa91d7a9ad58
63,988
import six import ctypes def sg_get_opcode_sa_name(cdb_byte0, service_action, peri_type): """ Command name given opcode (byte 0), service action and peripheral type. If no service action give 0, if unknown peripheral type give 0 or -1 . """ if isinstance(cdb_byte0, six.integer_types): cdb_...
e0d91a6df492c7c1d38a4b122d69bd83a1dfeaa7
63,989
from typing import List from typing import Dict def remove_video_before_db(examples: List[Dict]) -> List[Dict]: """Remove (heavy) "video" and "pictures" key from examples before saving to Prodigy database Parameters ---------- examples : list of dict Examples. Returns ------- examp...
204375589e2bdc9e21cb9e1e71a3b8fb35cffd17
63,990
from pathlib import Path def resolve(path): """Return the fully resolved path even if it does not exist. Args: path (Path): the Path object to resolve. Returns: Path: fully resolved ``Path`` object. """ try: resolved = path.resolve() except FileNotFoundError: ...
4bedea0d2a542f4c019074d1d3f5ad461cb2f3d0
63,991
def org_rm_payload(org_default_payload): """Provide an organization payload for removing a member.""" rm_payload = org_default_payload rm_payload["action"] = "member_removed" return rm_payload
e976396f6fe5de1073f2235aac36b300f129867a
63,992
def run_unary_modules_sample(modules, cur, hparams, k): """Run modules, sampling k.""" selection_weights = create_selection_weights( "selection", ("softmax_topk", k), shape=[len(modules)], inv_t=100.0 * common_layers.inverse_exp_decay( hparams.anneal_until, min_value=0.01)) all_res = [...
9fe4da2c47992c7aa690a68ce7389410d77cee7d
63,993
from typing import Optional def wrap_middleware( middleware: Optional[HttpMiddlewareCallback], handler: HttpRequestCallback ) -> HttpRequestCallback: """Optionally wrap a handler with middleware""" if middleware is None: return handler else: return make_middleware_chain(mid...
947cde83f30854d68039934757422cbc31ed4af0
63,994
def bin2complement2(binary): """Convert decimal into binary two's compliment Args: binary (str): [description] Returns: str: [description] """ binmap = map(lambda i: '1' if i == '0' else '0', list(binary)) binstr = "".join(list(binmap)) intFromBin = int(bi...
6614ce4bad3c9f15d5d9d25c1a695b8c0bd10158
63,995
def getAll( stmt ): """return all results from an SQL statement. """ return execute(stmt).fetchall()
30b8cac8970f3087a81b94f941f5f7cdef65272f
63,996
def catalog_r(cat): """Reverse a dict of a catalog into a dict.""" out = {} for i,j in cat.items(): delveset(out,*i,value=j) return out
b0a31e8c6481c3b837b9521e39bce4cb2cb641f7
63,997
def most_recent_verification(photo_id_verifications, sso_id_verifications, manual_id_verifications, most_recent_key): """ Return the most recent verification given querysets for photo, sso and manual verifications. This function creates a map of the latest verification of all types and then returns the ear...
a1272eb45a03ed6c9627852692591deb5ba45c33
63,998
def get_sa_values(ground_motion, gm_periods, site_idx, bldg_t, sim_idx): """ Identifies the relevant Sa(T) for the building by interpolating from the response spectra for each scenario Parameters ---------- ground_motion: numpy array contains the simulated ground motions [n_ruptures, n_site...
be8a7b1ad4bf7b27fa2011ca34aa3b3bac150bc2
63,999