content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def clean_nginx_git_tag(tag): """ Return a cleaned ``version`` string from an nginx git tag. Nginx tags git release as in `release-1.2.3` This removes the the `release-` prefix. For example: >>> clean_nginx_git_tag("release-1.2.3") == "1.2.3" True >>> clean_nginx_git_tag("1.2.3") == "1...
232da3ae24987fd921f5fcc9273f6218fc3a0371
688,207
def get_page(data): """Determines the page number""" try: page = int(data.get('page', '1')) except (ValueError, TypeError): page = 1 return page
98b1ab41d9166dc544239d88e5e6da18f16bcfc7
688,208
def check_for_running_sfn(session, arn): """Check if a downsample step function already running Args: session (boto3.session): arn (str): Step function arn Returns: (bool) """ client = session.client('stepfunctions') resp = client.list_executions(stateMachineArn=arn, st...
49e01f8109642d31d36a4c1d2e280e046771ae15
688,209
def NoOpGroupCondition(): """Always returns None Returns: (None) """ return None
ddb019eec15b3f9fc1fc26fd126d76df5390985f
688,210
def has_usable_review_ui(user, review_request, file_attachment): """Returns whether a review UI is set and can be used.""" review_ui = file_attachment.review_ui return (review_ui and review_ui.is_enabled_for(user=user, review_request=review_request, ...
fc97f8d7cc2a6ad9b1689341510eeae20c6e4c8d
688,212
import os def get_QC_dirpath(cli_args, subject=None): """ :param cli_args: Dictionary containing all command-line arguments from user :param subject: String, ID of subject to get the QC .tsv file path for :return: String, the full path to a directory with QC .tsv files, either for all sub...
08d0cfbeea35c9a4212ffd43b68f58c6a208d7cb
688,213
def capitalize(text): """ Python 3 primitive stub version of text capitalization. Actually it does nothing serious since NLTK is not ported to Python 3 yet. """ return text
e2623d25a8e12a1514938e6541be4c286712164b
688,214
def to_binary(number: int) -> str: """Convert a decimal number to a binary numbers. :param number: The number to convert to binary :return: The binary representation of the number """ return bin(number)[2:]
8638930cb711fefd3732d65db632e7f24e597291
688,215
def get_redis_conf(*args): """Get requested parameters from the configuration""" with open("/etc/redis/redis.conf") as fd: content = fd.read().splitlines() cfg = {} for line in content: parts = line.split() if not parts: continue if parts[0] not in args: ...
5ca624875eb4a2c06e84a42e3050eea3155f18f9
688,217
def char_color(s,front=50,word=32): """ # 改变字符串颜色的函数 :param s: :param front: :param word: :return: """ new_char = "\033[0;"+str(int(word))+";"+str(int(front))+"m"+s+"\033[0m" return new_char
b6e54a4b46d09a03de06eb6d4ea01db9986fd63c
688,218
def kruskal(edges, extension, fLOG=None): """ Applique l'algorithme de Kruskal (ou ressemblant) pour choisir les arcs à ajouter. @param edges listes des arcs @param extension résultat de l'algorithme de Bellman @param fLOG logging function @return a...
a0e67cae0e463d6dbae90eaba5f881862a3ee09c
688,219
import base64 def base64_encode(string): """ base64's `urlsafe_b64encode` uses '=' as padding. These are not URL safe when used in URL parameters. Removes any `=` used as padding from the encoded string. """ encoded = base64.urlsafe_b64encode(string) return encoded.rstrip(b"=")
b660feeba6cf17f5be6b49d406951277af8403ce
688,220
def parallelize(df, fingerprint_function, predict_function, models): """Parallelize the running of fingerprinting and property prediction. Args: df (pd.DataFrame): Polymers to fingerprint and predict on Returns: dataframe with all generated polymers """ fingerprint_...
b62df52428ad07075db67ce9e5f6170307712866
688,221
def handler(value, **kwargs): """Split the supplied string on the given delimiter, providing a list. Format of value: <delimiter>::<value> For example: Subnets: ${split ,::subnet-1,subnet-2,subnet-3} Would result in the variable `Subnets` getting a list consisting of: ["sub...
700321db3f92bf87c9a6ecc8dc38d4dd2ad14229
688,222
import base64 def rc4_decrypt(msg: str, key: str) -> str: """rc4解密程序""" def rc4_init(): # 没管秘钥小于256的情况,小于256不断重复填充即可 box_array = list(range(256)) j = 0 for i in range(256): j = (j + box_array[i] + ord(key[i % len(key)])) % 256 box_array[i], box_array[j]...
8ce3dd122b0199721dd7388cd835fa71fa494b03
688,223
import torch def quaternion_log_to_exp(quaternion, eps=1e-8): """ Applies exponential map to log quaternion. The quaternion should be in (x, y, z, w) format. """ if not quaternion.shape[-1] == 3: raise ValueError( "Input must be a tensor of shape (*, 3). Got {}".format( ...
52df90f460c131459a99f60b7a342065d62ef0aa
688,224
def replace_string_in_list(str_list: list, original_str: str, target_str: str): """ Replace a string in a list by provided string. Args: str_list (list): A list contains the string to be replaced. original_str (str): The string to be replaced. target_str (str): The replacement of st...
31649c8c7171518598f6b3fe4d5db1b46e5cd573
688,225
def _wait_before_serving(seconds): """Tell the server not to write to this socket for the specified time.""" def _helper(ps, soc): ps.delay_writing_for(seconds * 1000, soc) return _helper
df3a4c969b1d094f0ac7fe07c967980ab8500fc0
688,226
import argparse import os def parse_arguments(): """ Parses arguments and checks if they are valid """ parser = argparse.ArgumentParser(description='Postprocesses tracking results') parser.add_argument('--challenge', type=str, help='The Challenge like MOT15, MOT17 or MOT20') parser.add_argument('--wor...
94b4309f99bfb812df697eead4486666b1d5a918
688,227
def test_stability(v1, v2, precision=10e-3): """tests if two lists of lists of floats are equal but a certain precision Args: v1 (list[list[float]]): first list containing ints v2 (list[list[float]]): second list containing ints precision (float, optional): the precision after which...
07b12bd7255a7f88cff630b3b6f79513752b2cb3
688,228
def dummy_json() -> str: """Completely bogus JSON data.""" return '{ \ "syncToken": "1575592390", \ "createDate": "2019-12-06-00-33-10", \ "prefixes": [ \ { \ "ip_prefix": "127.0.0.1", \ "region": "local-west-1", \ "service": "MYTEST" \ } \ ]...
c0ec23df006054b219f501bb0616449f74b58039
688,229
def box_lengths(dimensions): """Return list of dimension ints""" return sorted([int(i) for i in dimensions.split('x')])
df0dabe4fc8a586d3df4398dfbb6448cd5b7a106
688,231
def cast_elements_to_string(cast_list): """ This function casts the top level elements of a list to strings. Note that it does not flatten lists before doing so, so if its elements contain lists, it will cast these lists to strings. Apply flatten_list() before applying cast_elements_to_string() if you...
8e34768a8fd9f159a9770562ce20d637b94de0b0
688,232
def padding_input(sents, pad_token="<pad>", tgt_len=-1): """ padding the token sequence to max length Args: sents: pad_token: tgt_len: Returns: """ if tgt_len == -1: tgt_len = max(len(s) for s in sents) batch_size = len(sents) seqs = [] for i in rang...
335bdf6fce7c0ba3128c7cca81a6930f7c0d0e4c
688,233
import torch def test_observe_get_and_verify_response_input_unit(tmp_observe_class, method, tmp_val, monkeypatch): """ test that _get_and_verify_response_input works for self.sampling["method"] = "iteratuve" or "functions". Leverage monkeypatching and create false class to mock that greattunes._observe wi...
a5b0d9bcb4ad7d893498e88395d297e84d7212b2
688,234
def no_walk_revctrl(dirname=''): """Return empty list. """ # Returning a non-empty list prevents egg_info from reading the # existing SOURCES.txt return ['']
7b6e7a09f9a131c13774a328eee38e24c7f49f29
688,235
def cal_efficient(s): """ :param s: :return: """ count = 0 for i in range(len(s)): if s[i] != '-': count += 1 return count
090f316cce98c933e0ed0522a059d82597e3ffac
688,236
def get_rm(g): """Return membrane resistivity in Ohm*m^2 g -- membrane conductivity in S/m^2 """ return 1/g
803d4f05e702776053640280e25ca6656790cdc9
688,237
def load_md(path: str) -> list: """ Loads an existing file into a list. :param path: path where the file is stored :return: list with the lines from the file """ with open(path, "r", encoding="UTF-8") as mdfile: return mdfile.readlines()
b2977ff137de15e0a32dd2898f0dafd9a5ba9663
688,238
def power_set(elements): """ bitwise version """ subsets = [] n = len(elements) for i in range(1<<n): subset = [] for j in range(n): print('i=', i, '; j=', j, ';; i >> j =', i >> j, ';; (i >> j) % 2 = ', (i >> j) % 2) if (i>>j) &...
7a91cc9ec529f040804334fba47cf94bf3a8926b
688,239
def clean_name(name): """ Cleans a proposed character name. """ new_name = ''.join(ch for ch in name if ch.isalpha()) new_name = new_name.title() return new_name
8aa0d8c9b2e352d867d70248f1a1b0500561e401
688,240
def word2features(sent, i): """ Extract features of a node in the "sent" list for a CRF Keyword arguments: sent -- a list of triples <word, PoS tag, label> i -- index of the node to extract the featues """ word = sent[i][0] postag = sent[i][1] features = { 'bias': 1.0, ...
827cd686a02f7b2e5e2d52a4a747801e452b4e52
688,242
def merge_dicts(*dicts, **kwargs): """Merge all dicts in `*dicts` into a single dict, and return the result. If any of the entries in `*dicts` is None, and `default` is specified as keyword argument, then return `default`.""" result = {} for d in dicts: if d is None and "default" in kwargs: ...
e42717a86d9f92f8a4924dd1317e7fcc23ef0f97
688,243
def create_mappack(data, map_name, map_type): """Match the map data to faces.""" pack= {} def color_pointmap(map): for fi in range(len(data.pols)): if fi not in pack: pack[fi]= [] for pnt in data.pols[fi]: if pnt in map: pa...
32296461147aa281f80f96608ef988bd0bb4a4aa
688,244
import hashlib def get_md5(arg) -> str: """ 生成md5 :param arg: :return: """ md5 = hashlib.md5() md5.update(arg.encode(encoding='utf-8')) return md5.hexdigest()
d1685637e4209a2f13fae43c12749e0b9b19368b
688,245
import os def get_file_byte(file_path): """Generates the binary of the provided file.""" # Guard statement to ensure that the file provided is a valid file if not os.path.isfile(file_path): raise FileNotFoundError("The provided file " + str(file_path) + " is not a valid file" ) # Open the spe...
f17deb1ebb48c52a98f5122b7e6cb449552a1a94
688,247
from typing import Optional def category_to_tracking_name(category_name: str) -> Optional[str]: """ Default label mapping from nuScenes to nuScenes tracking classes. :param category_name: Generic nuScenes class. :return: nuScenes tracking class. """ tracking_mapping = { 'vehicle.bicycl...
cf7bb53b94955d9d1dbf813e5e4907f407f4e013
688,248
def calc_median(values_list): """calculates the median of the list in O(n log n); thus also returns sorted list for optional use""" median = 0.0 sorted_list = sorted(values_list) n = len(sorted_list) if n == 0: return median, sorted_list, n half = n >> 1 if n % 2 == 1: media...
f6f77eb3b99b946b5d09acef3fc08756527af134
688,249
def squirrel_play(temperature : int, winter : bool) -> bool: """return the temperature with the int and the winter is bool which is not yes. The variable is temperature and the winter. >>>squirrel_play(70, False) False >>>squirrel_play(95, False) False >>>squirrel_play(95, True) Fa...
086d3c1664c163141dfa155e6b5321d34cf715f3
688,250
def jsonKeys2int(some_dict): """ Json can't use integers as keys, so user_id writes as a string. This function converts every string key in dict to an integer(if it can). """ if isinstance(some_dict, dict): try: return {int(k): v for k, v in some_dict.items()} except Valu...
8802e336c3a02f6a401efa322bda39a6ae1843c1
688,251
import json def json_pp(json_object): """ Helper method to convert objects into json formatted pretty string :param json_object: The object to be converted into pretty string :return: A pretty formatted string """ formatted_json = json.dumps(json_object, sort_ke...
74e11e736d512137bfdfebef3230c66e48edce2f
688,252
import argparse def parseArgs(): """Configuration of command line arguments. """ parser = argparse.ArgumentParser(description='Cremon - Crypto exchange monitoring') parser.add_argument('--apikey', help='API key', required=True) parser.add_argument('--seckey', help='Secret key', required=True) return vars(pars...
8d71d86c14a0d59354b19cb85862bf85707dbcd5
688,254
import os def get_pager_cmd(pager_cmd=None): """Return a pager command. Makes some attempts at finding an OS-correct one. """ if os.name == 'posix': default_pager_cmd = 'less -r' # -r for color control sequences elif os.name in ['nt','dos']: default_pager_cmd = 'type' if pag...
549f2a1ca0ad39b9372a494fbb93fed1c69f710d
688,255
def deriv_1(f, x, h=0.001): """ Calcula la primera derivada de f en el punto x """ return (f(x+h) - f(x-h))/(2*h)
bfd9708a69617f350fbe8e933002f271e495a6af
688,256
def sources(capacity_factor: bool = True): """ This function provides the links to the sources used for obtaining certain information. The arguments can either be set to the appropriate boolean based on the sources required. Parameters: ----------- capacity_factor: bool This arg...
1585194ad263c58d2603bb47deb2762f75e75f82
688,257
def get_input(): # pragma: no cover """ Get Input Abstraction """ return input()
77b59f0f9c9833ff2a03917e2e9ae4b549f8e668
688,258
import string def flow_key(flow): """Model a flow key string for ``ovs-ofctl``. Syntax taken from ``ovs-ofctl`` manpages: http://openvswitch.org/cgi-bin/ovsman.cgi?page=utilities%2Fovs-ofctl.8 Example flow dictionary: flow = { 'in_port': '1', 'idle_timeout': '0', 'act...
ef27317827587778315d10b0e55f75554c748c13
688,259
import configparser def load_config(): """ Helps construct ConfigParser object pertaining default url for the sawtooth validator. Returns: type: ConfigParser ConfigParser object with default url. """ config = configparser.ConfigParser() config.set("DEFAULT", "url"...
e568f03f0d5b0e98467350cfa22e53d070a4de6a
688,261
import torch def one_hot(label, depth=10): """ One-hot encode """ out = torch.zeros(label.size(0), depth) idx = torch.LongTensor(label).view(-1, 1) out.scatter_(dim=1, index=idx, value=1) return out.long()
c3f27de8c5bdbb54edc667397b2b5e587727b1af
688,263
import numpy def _assign_labels_array(X, sample_weight, x_squared_norms, centers, labels, distances): """Compute label assignment and inertia for a dense array Return the inertia (sum of squared distances to the centers). """ n_clusters = centers.shape[0] n_samples = X.sha...
ed784200128e0832f1caea6477e32ab728fee541
688,264
def cleanup_decorator(func): """Decorator which runs cleanup before and after a function""" def clean_before_after(self, *args, **kwargs): # pylint: disable=missing-docstring # pylint only complains about a missing docstring on py2.7? self.cleanup() result = func(self, *args, **kwargs)...
e993a1476f561284a8f85f2aee4dd91dba573bb9
688,265
def formatUintHex64(value): """ Format an 64 bits unsigned integer. """ return u"0x%016x" % value
af82b7b6dd138333f09cf93e9d7990be286333fd
688,266
def get_account_id(sts_client): """Retrieve the AWS account ID for the authenticated user or role""" response = sts_client.get_caller_identity() return response['Account']
670961b88b978387c9c8a7dcffe364caae218bf6
688,268
def get_model_meta(model): """ Simply fetches the meta attribute of the model, so PEP8 checks will stop screaming at me so much """ return model._meta
a96ac196c8c1f4ae4b6cba71c75ec81365b543f5
688,269
def bull_engulf(Open, high, low, close, t=4): """ Identifies if prices is a Bullish Engulfing Pattern of not Param: Open: array of open prices (5-day) high: array of high prices (5-day) low: array of low prices (5-day) close: array of close prices (5-day) t: int ...
375500d7517b866d8e738a52165ecc40b8931258
688,270
def _fit_one_ovo(bin_clf_idx, multi_ovo, dataset, verbose): """Fit the OVO classifier given an index. This method fits a one-vs-one classifier wrt the positive and negative labels taken from the list clf_pair_idx at the index bin_clf_idx. Parameters ---------- bin_clf_idx : int Ind...
31d8e6ce66e3f40a243777f80ce416c9309f4a1e
688,271
def gen_addrmap(regmap): """ Collect all addresses as keys to the addrmap dict. Values are the names. """ addrmap = dict() for key, item in regmap.items(): if "base_addr" in item: addr = item["base_addr"] aw = item["addr_width"] addri = int(str(addr), 0) ...
661fdd9b83ebde252b00c8fefe04234cc55ba137
688,272
def loadfiledict(path): """ in : a file to convert in dict out : a dict as d[ls[0]]=float(ls[1]) """ f=open(path,"r") d=dict() l=f.readline() while l: ls=l.split() d[ls[0]]=float(ls[1]) l=f.readline() f.close() return d
866893d0dd1193da04fd33a8d1f5b1324dff18b2
688,273
def required(flag=True): """When this flag is True, an exception should be issued if the related keyword/element is not defined. Returns "R" or False. >>> required(True) 'R' >>> required(False) False """ return "R" if flag else False
907fcb0a981eb8f34669bdf3acf6809b9218ee86
688,274
def get2dgridsize(sz, tpb = (8, 8)): """Return CUDA grid size for 2d arrays. :param sz: input array size :param tpb: (optional) threads per block """ bpg0 = (sz[0] + (tpb[0] - 1)) // tpb[0] bpg1 = (sz[1] + (tpb[1] - 1)) // tpb[1] return (bpg0, bpg1), tpb
9024bab4ccb6496622aef0e7e4c25b71a3057fc6
688,276
import torch def pitchVocabularyFmt(X, vocab_col): """ Produces the tensors for training with a pitch vocabulary encoding. """ pitch = torch.tensor(X[:, vocab_col], dtype=torch.long) score_feats = torch.cat([torch.tensor(X[:, :vocab_col], dtype=torch.float), torch.tenso...
df846df0ec36ecc770f6afa032d3d1433a7497c8
688,277
def loss_asr(lst_fn): """compute objective value of ASR (i.e., WER). Args: lst_fn (list): list of filenames of anonymized audio Returns: score (float): WER Note: This function itself does not contain ASR. Please use your own ASR system and revise this function to obtain WER. """ wer = 0.2 # 0...
e55842a38985a57a1b885214fae49ef3bdaefcc9
688,278
import os import subprocess def _get_num_nvidia_gpus(): """Get the number of NVIDIA GPUs by using CUDA_VISIBLE_DEVICES and nvidia-smi Returns: Number of GPUs available on the node Raises: RuntimeError if executing nvidia-smi failed """ try: return len(os.environ['CUDA_VISIBLE_DEVICES'].split(',...
3dbe60fd50d5a501701a66bc9ced9d8b03f690ef
688,279
import os import re def collect_version_input_from_fallback(meta_file='metadata.py'): """From *meta_file*, collect lines matching ``_version_{key} = {value}`` and return as dictionary. """ cwd = os.path.dirname(os.path.abspath(__file__)) res = dict(re.findall("__version_([a-z_]+)\s*=\s*'([^']+)'"...
a869e209e15c43802d785b2b1f7df34a0c78ad6f
688,280
def IsSimulator(target_cpu): """Returns whether the |target_cpu| corresponds to a simulator build.""" return not target_cpu.startswith('arm')
3abb2d1a6051c12cd3b1a9d54448352165378595
688,281
import argparse def parse_args(): """ Parse input arguments """ parser = argparse.ArgumentParser(description='Build flow-location dataset') parser.add_argument('--set', dest='set', help='image set', default='train', type=str) parser.add_argument('--output_dir', ...
ee95a530b02eb9f462b9bc876f674944d2e66501
688,282
import requests def get_content(start_date, end_date, search_term=''): """ Handles the primary work of downloading from NIOSHTIC and getting the raw content. @param start_date: month/year string in the style '01-2017' @param end_date: month/year string in the style '12-2017' @return gigantic string containi...
bcefb7305a573185d100cca5317126f9bc1b2fe6
688,283
import uuid def generate_unique_name(name_prefix, reservation_id=None): """ Generate a unique name. Method generate a guid and adds the first 8 characteres of the new guid to 'name_prefix'. If reservation id is provided than the first 4 chars of the generated guid are taken and the last 4 of the r...
93d14ea0b2b89df1c2d11d97c5b628422e9a95d4
688,284
import socket import struct def ipv6_to_long(ip): """Return the IPv6 address string as a long >>> ipv6_to_long("2001:db8::1") 42540766411282592856903984951653826561L >>> ipv6_to_long("::1") 1L """ ip_bytes_n = socket.inet_pton(socket.AF_INET6, ip) ip_parts = struct.unpack('!QQ', ip_by...
1c9f324dba9be791f6ec0fae9693047b06759b6d
688,285
import functools def join(*expressions): """ Convenient function for joining many expressions in series using ``ObserverExpression.then`` Parameters ---------- *expressions : iterable of ObserverExpression Returns ------- new_expression : ObserverExpression Joined expression....
1e14369a7fa471b0b586287c7647980a789c6e6c
688,286
def ssh_auth(username, address): """Render username and address part.""" if username: return '{}@{}'.format(username, address) return '{}'.format(address)
2e44302f9d9e0048bfbc2c2013a9d170a9c38fce
688,287
def round_int(value): """Cast the specified value to nearest integer.""" if isinstance(value, float): return int(round(value)) return int(value)
13522aa76ff75baa2f0e10e9840bc981c9e5d30b
688,289
import os import json import csv def jsonld2csv(fp: str, verbose: bool = True) -> str: """ 读入 jsonld 文件,存储在同位置同名的 csv 文件 Args: fp (String): jsonld 文件地址 verbose (bool): 是否打印日志 Return: fp_new (String):文件地址 """ data = [] root, ext = os.path.splitext(fp) fp_new = r...
9d7af3c311ca7596c605f449172dafbc3724a259
688,290
def can_view_item(context, item): """Check permission for a link or sublinks, only return True if allowed.""" request = context["request"] # If there's a url, then we look up the matching permission if item.get("url"): perms = item.get("permissions", []) if perms == []: retur...
22bb158da8284689f9165b3dde38d5763cc478db
688,292
def accel_within_limits(v, a, v_range): """ Accelerate the car while clipping to a velocity range Args: v (int): starting velocity a (int): acceleration v_range (tuple): min and max velocity Returns: (int): velocity, clipped to min/max v_range """ v = v + a ...
0ed6da91424149c04e6d793a740d13b3ec9728ec
688,293
import math def DCG(label_list): """ DCG """ dcgsum = 0 for i in range(len(label_list)): dcg = (2 ** label_list[i] - 1) / math.log(i + 2, 2) dcgsum += dcg return dcgsum
86f138ecef00fbaf5009570913259c96cdd8d679
688,294
import tempfile def setup_csv_fixture(): """Create an empty file which can be written to by CSV creation command """ with tempfile.NamedTemporaryFile() as f: f.write(b"") return f.name
20bf33ee3ae71f809815dbedb093dddf06f14a50
688,295
import typing import pickle def serialize(tar: typing.Any) -> str: """ 对象序列化保存为字节字符串:None -> b'\x80\x04N.' """ b = pickle.dumps(tar) return b.__str__()
0bfb64125d8ef1b1d655f9df0c3efc98a75b66d8
688,296
import math def sin(angle): """Retorna el seno de un angulo""" return math.sin(math.radians(angle))
fe290e2ecfbb61051a4a5ef69582a95ab31e889f
688,297
def welcome(): """List all available routes""" return ( f"Available Routes:<br/>" f"<br/>" f"/api/v1.0/precipitation<br/>" f"- List of last years precipitation from all stations.<br/>" f"<br/>" f"/api/v1.0/stations<br/>" f"- List of Stations.<br/>" ...
d79c8f40b513a49a8c4ce6a5933f7175996103c0
688,298
from typing import Iterable def check_type(data): """ Check type of an object. Return False if it is dictionary or list, True - otherwise. """ if isinstance(data, str): return True elif isinstance(data, Iterable): return False return True
9a614c33215c0217af8a491bd9164d5220307ced
688,299
def get_ap_vel(df, time_step, scaling_factor): # Calculates 'angular persistence', 'velocity', and 'directed velocity' """ Primary function called by "get_chemotaxis_stats" and "get_chemotaxis_stats_by_interval". Calculates the 'Angular_persistence', 'Velocity', and 'Directed_velocity' for each timepoin...
6982c7628b82c286a825cbc767d4cf39cb31f783
688,300
def _num_tokens_of(rule): """Calculate the total number of tokens in a rule.""" total = len(rule.get("tokens")) for _ in ("prev_classes", "prev_tokens", "next_tokens", "next_classes"): val = rule.get(_) if val: total += len(val) return total
eafebe556ee28fe1ab4699894266b47b4c1ed63b
688,301
def connectChunk(key, chunk): """ Parse Card Chunk Method """ upLinks = [] schunk = chunk[0].strip().split() for idx in range(4, len(schunk)): upLinks.append(schunk[idx]) result = {'link': schunk[1], 'downLink': schunk[2], 'numUpLinks': schunk[3], ...
5c264bc070979de3ed63e20b00672fa2ef4b2aa4
688,303
import sys def to_dictionary(pw, print_list): """ - convert list of comparisons to dictionary - print list of pidents (if requested) to stderr """ pairs = {} for p in pw: a, b, pident = p if a not in pairs: pairs[a] = {a: '-'} if b not in pairs: ...
e5b3675798a5cd7006840bb3026f677829e00e84
688,304
def custom_formatwarning(msg, *args, **kargs): """ Custom warning formatter. Returns: str: warning message """ return "UserWarning: " + str(msg) + '\n'
31db1ed25e5c512898f76343764707be3efe88ce
688,305
def sort_dataframe(dataframe, sort_column, order='ascending', nulls_position='last', inplace=True): """ Sort the dataframe by the sort column Arguments are the dataframe and column that you want to sort by Optional arguments are: - order (default ascending, can be ascending or descending) which dete...
a4d87ef0ff18d38b0caa747b885194e4820cac77
688,306
def job_id() -> str: """Returns a mock job ID.""" return "00000000-0000-0000-0000-000000000000"
038d5035a5e5f78e5f04b9535423bd594fa7ed3f
688,307
import re def _split_text_by_opening(pattern, text): """ Splits text into parts identified by opening that matches `pattern`. For example, --pattern='\n\nCHAPTER \\d+\n\n' may be used to split text into chapters. """ openings = re.findall(pattern, text) if len(openings) == 0: prin...
2082f62b35b96173159bab0d8935ac849bb14d42
688,309
import numpy as np def pack_XTrans_me(bayer_2d): """ input a 2d xtrans raw image, pattern like this:\n [0, 2, 1, 2, 0, 1],\n [1, 1, 0, 1, 1, 2],\n [1, 1, 2, 1, 1, 0],\n [2, 0, 1, 0, 2, 1],\n [1, 1, 2, 1, 1, 0],\n [1, 1, 0, 1, 1, 2]\n return a 9d image\n R-0,4d G-1,5,6,7,8d B-1,...
e5e89fc7e30493e599f099d5fdc29c0e02380945
688,310
import json def format_json(data, default=None): """ Pretty print JSON. Arguments: data (dict): JSON blob. Returns: str: Formatted JSON """ return json.dumps( data, sort_keys=True, indent=2, separators=(",", ": "), default=default )
1ff400089ccac98cc4199a537e1dd5633d2d27b4
688,311
def oo_split(string, separator=','): """ This splits the input string into a list. If the input string is already a list we will return it as is. """ if isinstance(string, list): return string return string.split(separator)
833270146c2661005a8733cb400c3ba203a8fdd0
688,312
import numpy def spectral_energy(spectrum): """ Computes the total energy (sum of squares) in a series. Arguments: spectrum -- the points to analyze """ return numpy.sum(numpy.square(spectrum))
f6184df4eada50623cb509fad772ac252120e991
688,313
def get_load_balancer(oneandone_conn, load_balancer, full_object=False): """ Validates the load balancer exists by ID or name. Return the load balancer ID. """ for _load_balancer in oneandone_conn.list_load_balancers(): if load_balancer in (_load_balancer['name'], ...
8cdb954b2940f7662d719263df0502a16024251a
688,314
import argparse def parse_arguments(args): """ Parse the arguments from the user """ parser = argparse.ArgumentParser( description= "Demultiplex files using barcodes and index (sequences no longer include barcodes)\n", formatter_class=argparse.RawTextHelpFormatter) parser.add_argument...
b72a2f1a48c7a93fb43991ee4952cc14cdc23be4
688,315
import requests def object_store_get_attachment(api_key, object_id, object_type, attachment_field, attachment_id, attachment_type): """ Generic function for downloading attachments from Crawl Runs/Extractors. :param api_key: Import.io API key :param object_id: CrawlRun...
012a9f91c1a2230e921f03c314e2cfcd2f14b41e
688,317
def set_remove_missing(): """ >>> sorted(set_remove_missing()) Traceback (most recent call last): KeyError: 4 """ s = set([1,2,3]) s.remove(4) return s
b55cb11048eb14cacd362e8c9b768b2367940c96
688,319
import shlex import re def future_shlex_join(sequence): """Simple replacement for the shlex.join() function (introduced in Python 3.8) if it is not available yet. """ try: return shlex.join(sequence) except AttributeError: pass # output_sequence = [] for item in sequenc...
9eb0cb4068da908cb66c747dff74f3e56502ee14
688,320
def construct_feed_dict(features, support, labels, labels_mask, placeholders): """Construct feed dictionary.""" feed_dict = dict() feed_dict.update({placeholders['labels']: labels}) feed_dict.update({placeholders['labels_mask']: labels_mask}) feed_dict.update({placeholders['features']: features}) ...
c3d7beba9780ed1211be5b9520121a2c3c9d2ac6
688,321
from functools import reduce import operator def MergeDicts( *dicts ): """Construct a merged dictionary from the given dicts. If two dicts define the same key, the key from the dict later in the list is chosen.""" return dict( reduce( operator.add, map( dict.items, dicts ) ) )
185cd5d082c3bf97a40cb8ad4d9e1197f25d1e1f
688,322