content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def check_results(results): """Examines a list of individual check results and returns an overall result for all checks combined. """ if CheckResults.SCALE_UP in results: return CheckResults.SCALE_UP if all(r == CheckResults.SCALE_DOWN for r in results): return CheckResults.SCALE_DOW...
a7a18caca42c9a6f555110418b96b5cc6b9d203c
21,700
import os def disk_usage(path): """returns disk usage for a path""" total = os.path.getsize(path) if os.path.isdir(path): for filename in os.listdir(path): child_path = os.path.join(path, filename) total += disk_usage(child_path) print(f"{total:<10} {path}") return ...
0c4901f94d562d7def81afcef4ffa27fe48c106c
21,701
def edit_route(link_id): """edit link""" link = dynamo.tables[TABLE_NAME].get_item(Key={'id': link_id})['Item'] form = LinkForm(link=link['link'], tags=','.join(link['tags'])) if form.validate_on_submit(): link, tags = form.parsed_data() dynamo.tables[TABLE_NAME].update_item( ...
b20f22345d3de2b474e04821bdfbee5391f1d493
21,702
def build_empty_pq(): """Build empty pq.""" return PriorityQ()
a18dc1ac16ceb2475f47e1f55e0617957c1e0cad
21,703
def add_flags(flags): """Add KZC flags""" def f(test, way): test.args += flags return f
58c6db2bb46c321ce3e3592ac8be2ee6d1feecb6
21,704
import os import subprocess def RunProcess(cmd, stdinput=None, env=None, cwd=None, sudo=False, sudo_password=None): """Executes cmd using suprocess. Args: cmd: An array of strings as the command to run stdinput: An optional sting as stdin env: An optional dictionary as the environment ...
6b1f599b6fe601ea8e3ce85757f76ca7b4f707b2
21,705
def public_jsonp_service(view): """ More explicitly named to call attention to the extra little p """ return _json_service_wrapper(JSONPResponse, view)
76588ade3d537a102dc6ca3bf540bc32da928e30
21,706
def manage_data(xls_file: str) -> list: """ 转换xls手动标注的数据为待处理的格式 :param xls_file: 目标文件路径 :return: 转换后的字典列表 """ f = pd.read_excel(xls_file, index=False) cnt = 0 result = [] while cnt < len(f) - 1: if f.text[cnt] == f.text[cnt + 1]: temp_dic = {'text': f.text[cnt], '...
3198013b713f50b650bc5b3542905d1e860a6871
21,707
def get_arrival_times(inter_times): """Convert interevent times to arrival times.""" return inter_times.cumsum()
7197fc6315d3eaca118ca419f23aed7c0d7cd064
21,708
def generate_custom_background(size, background_color, nb_blobs=3000, kernel_boundaries=(50, 100)): """ Generate a customized background to fill the shapes Parameters: background_color: average color of the background image nb_blobs: number of circles to draw ker...
782883d29cf67dbb33662fbb22b457783320101d
21,709
def rotate_z(domain, nrot=4): """take BoxCollection and return equivalent CylinderCollection by rotating about the second axis. thus, transform coordinates of points like (x, z) --> (x, 0, z).""" return rotate(domain, d=1, nrot=nrot)
ca1b197d758a18b86675a14be952065055dea05f
21,710
def filter_roi(roi_data, nb_nonzero_thr): """Filter slices from dataset using ROI data. This function filters slices (roi_data) where the number of non-zero voxels within the ROI slice (e.g. centerline, SC segmentation) is inferior or equal to a given threshold (nb_nonzero_thr). Args: roi_data...
9e325f77436e152377bee84d7e82d3f80424f288
21,711
def from_numpy(shape, dt): """ Upcast a (shape, dtype) tuple if possible. >>> from_numpy((5,5), dtype('int32')) dshape('5, 5, int32') """ dtype = np.dtype(dt) if dtype.kind == 'S': measure = String(dtype.itemsize, 'A') elif dtype.kind == 'U': measure = String(dtype.item...
249701a885dc01d13fe356ce4117300e79d803a5
21,712
import optparse def ParseArgs(): """Parse the command line options.""" option_parser = optparse.OptionParser() option_parser.add_option( '--from', dest='sender', metavar='EMAIL', help='The sender\'s email address') option_parser.add_option( '--to', action='append', metavar='EMAIL', dest='rec...
eb1ee1c5fb66f76882aef0787e2c4716146526f4
21,713
def pyramidnet110_a84_cifar100(classes=100, **kwargs): """ PyramidNet-110 (a=84) model for CIFAR-100 from 'Deep Pyramidal Residual Networks,' https://arxiv.org/abs/1610.02915. Parameters: ---------- classes : int, default 100 Number of classification classes. pretrained : bool, default ...
f005c26e80e87536b5032685f27944560e5d8fc7
21,714
def contains_vendored_imports(python_path): """ Returns True if ``python_path`` seems to contain vendored imports from botocore. """ # We're using a very rough heuristic here: if the source code contains # strings that look like a vendored import, we'll flag. # # Because Python is dynamic, t...
90ed6939d7f43cac29eb66c3e27e911b9cc62532
21,715
def filter_uniq(item): """Web app, feed template, creates unique item id""" detail = item['item'] args = (item['code'], item['path'], str(detail['from']), str(detail['to'])) return ':'.join(args)
914fa4e3fcdf6bc7e6a30b46c8f33eecd08adcf1
21,716
import joblib import time import logging import warnings import pickle def load_pickle(filename, verbose=2, use_joblib=False): """ Note: joblib can be potentially VERY slow. """ with open(filename, 'rb') as file: if verbose >= 2: start = time.time() logging.info(f'L...
680c4b72e47efeb58ec1bd93e4899a3ae6b99709
21,717
from typing import Match async def make_match(*args, register=False, **kwargs) -> Match: """Create a Match object. There should be no need to call this directly; use matchutil.make_match instead, since this needs to interact with the database. Parameters ---------- racer_1_id: int The DB...
67346038696558f19b08a65cf45e88646b1186e4
21,718
def is_anonymous(context: TreeContext) -> bool: """Returns ``True`` if the current node is anonymous.""" # return context[-1].anonymous tn = context[-1].tag_name return not tn or tn[0] == ':'
0169a93cada0d371b3b4628ff3fabbbef6ef60f2
21,719
def expand_to_beam_size(tensor, beam_size): """Tiles a given tensor by beam_size.""" tensor = tf.expand_dims(tensor, axis=1) tile_dims = [1] * tensor.shape.ndims tile_dims[1] = beam_size return tf.tile(tensor, tile_dims)
e38adceceeecdab737f89f246125674ac87e4702
21,720
import ipdb def get_vignettes( h5_file, bed_file, tmp_dir=".", importance_filter=True, rsid_to_genes=None, ensembl_to_hgnc=None): """get the example indices at the locations of interest """ # prefix (scanmotifs) dirname = h5_file.split("/")[-2] print...
396d2a5b908c99fd74427f74babc50323820fa36
21,721
def delete_cluster(access_token, project_id, cluster_id): """删除集群""" url = f"{BCS_CC_API_PRE_URL}/projects/{project_id}/clusters/{cluster_id}/" params = {"access_token": access_token} return http_delete(url, params=params)
f48d7f8a6278e528792601938817d883751d7a41
21,722
def modifMail(depute, mail = MAIL): """ modifMail renvoit une chaine de caractères d'un mail personnélisé pour chaque députés des comissions choisies Prend en entrée : infoDeput : un tableau de tableau avec les données des députés. mail : l'adresse d'un fichier txt remp...
0ade624e356bd0cc94fc3312ee1746a8771cb6a4
21,723
def atoi(s, base=None): # real signature unknown; restored from __doc__ """ atoi(s [,base]) -> int Return the integer represented by the string s in the given base, which defaults to 10. The string s must consist of one or more digits, possibly preceded by a sign. If base is 0, it is chos...
420c9a68c1fe829a665eaba830df757114a81b47
21,724
def gzip_requested(accept_encoding_header): """ Check to see if the client can accept gzipped output, and whether or not it is even the preferred method. If `identity` is higher, then no gzipping should occur. """ encodings = parse_encoding_header(accept_encoding_header) # Do the actual co...
a07ca3d77095467791fc97d1a525ee878715e929
21,725
import logging def create_logger(name="dummy", level=logging.DEBUG, record_format=None): """Create a logger according to the given settings""" if record_format is None: record_format = "%(asctime)s\t%(levelname)s\t%(message)s" logger = logging.getLogger("modbus_tk") logger.setLevel(level) ...
d7662fa035d7f096820c54b6e3b8403a77ce5769
21,726
def precip_units(units): """ Return a standardized name for precip units. """ kgm2s = ['kg/m2/s', '(kg/m^2)/s', 'kg/m^2/s', 'kg m^-2 s^-1', 'kg/(m^2 s)', 'kg m-2 s-1'] mmday = ['mm/day', 'mm day^-1'] if units.lower() in kgm2s: return 'kg m^-2 s^-1' elif units.lower() in...
e5f94c3dd41b68d2e7b6b7aa1905fd5508a12fab
21,727
from typing import Union from typing import List def enumerate_quantities( df: pd.DataFrame, cols: Union[List[str], None] = None, qty_col: str = "quantity" ) -> pd.DataFrame: """Creates new dataframe to convert x,count to x*count.""" if not cols: raise ValueError("parameter cols must be an iterabl...
0defc1575ead9b70f658be5ed6795b22c3b39ac7
21,728
def calcul_acc(labels, preds): """ a private function for calculating accuracy Args: labels (Object): actual labels preds (Object): predict labels Returns: None """ return sum(1 for x, y in zip(labels, preds) if x == y) / len(lab...
3dc22c8707c181dda50e2a37f2cd822b2a31590d
21,729
def makeMolFromAtomsAndBonds(atoms, bonds, spin=None): """ Create a new Molecule object from a sequence of atoms and bonds. """ mol = Molecule(pybel.ob.OBMol()) OBMol = mol.OBMol for atomicnum in atoms: a = pybel.ob.OBAtom() a.SetAtomicNum(atomicnum) OBMol.AddAtom(a) ...
570dafe641bbade0d070942ea8e708d7e454e011
21,730
import sys def alpha_040(enddate, index='all'): """ Inputs: enddate: 必选参数,计算哪一天的因子 index: 默认参数,股票指数,默认为所有股票'all' Outputs: Series:index 为成分股代码,values为对应的因子值 公式: ((-1\* rank(stddev(high, 10)))\* correlation(high, volume, 10)) """ enddate = to_date_str(enddate) ...
3c9ac15f617a44699ce568fda2a175b11350c43b
21,731
def get_preprocessor(examples, tokenize_fn, pad_ids): """ Input: examples: [List[str]] input texts tokenize_fn: [function] encodes text into IDs Output: tf input features """ def generator(): for example in examples: tokens = tokenize_fn(example) yield pad...
0b2fb2217e04183fee027faedd163a8f8a048e9a
21,732
def is_propositional_effect(eff: BaseEffect): """ An effect is propositional if it is either an add or a delete effect. """ return isinstance(eff, (AddEffect, DelEffect))
be440b2192dd6b89fcaff5756e774e7543f408cf
21,733
def read_user(msg): """Read user input. :param msg: A message to prompt :type msg: ``str`` :return: ``True`` if user gives 'y' otherwhise False. :rtype: ``bool`` """ user_input = input("{msg} y/n?: ".format(msg=msg)) return user_input == 'y'
662e95002130a6511e6e9a5d6ea85805f6b8f0f5
21,734
import scipy def frechet_distance(real, fake): """Frechet distance. Lower score is better. """ n = real.shape[0] mu1, sigma1 = np.mean(real, axis=0), np.cov(real.reshape(n, -1), rowvar=False) mu2, sigma2 = np.mean(fake, axis=0), np.cov(fake.reshape(n, -1), rowvar=False) diff = mu1 - mu2 ...
55ed2a4f21b8987925083c925e7df6de7b305c06
21,735
import requests def get_tenants(zuul_url): """ Fetch list of tenant names """ is_witelabel = requests.get( "%s/info" % zuul_url).json().get('tenant', None) is not None if is_witelabel: raise RuntimeError("Need multitenant api") return [ tenant["name"] for tenant in requ...
97944d2de2a8dfc2dd50dbea46a135a184e7aa37
21,736
def ant(): """Configuration for MuJoCo's ant task.""" locals().update(default()) # Environment env = 'Ant-v2' max_length = 1000 steps = 2e7 # 20M return locals()
1b99dba9f38b735056055c564e1143c5eb77401a
21,737
def docker_run(task, image, pull_image=True, entrypoint=None, container_args=None, volumes=None, remove_container=True, **kwargs): """ This task runs a docker container. For details on how to use this task, see the :ref:`docker-run` guide. :param task: The bound task reference. :type...
6ddc61d47c7b78bf532195a8cddd37f3c730b675
21,738
def get_accuracy(pred, target): """gets accuracy either by single prediction against target or comparing their codes """ if len(pred.size()) > 1: pred = pred.max(1)[1] #pred, target = pred.flatten(), target.flatten() accuracy = round(float((pred == target).sum())/float(pred.numel()) * 100, 3...
f30e57602e4a06b0a0e3cd131bf992cf8f9b514e
21,739
import numpy def ifourier_transform(F,dt,n): """ See Also ------- fourier_transform """ irfft = numpy.fft.irfft shift = numpy.fft.fftshift return (1.0/dt)*shift(irfft(F,n=n))
d068cdbbe95f58d4210d2e799dfaee878fb9bf98
21,740
def preprocess_labels(labels, encoder=None, categorical=True): """Encode labels with values among 0 and `n-classes-1`""" if not encoder: encoder = LabelEncoder() encoder.fit(labels) y = encoder.transform(labels).astype(np.int32) if categorical: y = np_utils.to_categorical(y) ...
3d92ce70f6ae7f713b27f5a31e92f0aab919584b
21,741
def import_minimal_log(path, parameters=None, variant=DEFAULT_VARIANT_LOG): """ Import a Parquet file (as a minimal log with only the essential columns) Parameters ------------- path Path of the file to import parameters Parameters of the algorithm, possible values: ...
530f60799318b90c90d08d427965041e4bda6dba
21,742
def get_input_assign(input_signal, input_value): """ Get input assignation statement """ input_assign = ReferenceAssign( input_signal, Constant(input_value, precision=input_signal.get_precision()) ) return input_assign
9b3e372423d323af3a718ab909c26f2ba42bfea6
21,743
def prune_repos(region: str=None, registry_prefix: str=None, repo: str=None, current_tag: str=None, all_tags: str=None): """ Pull the image from the registry if it doesn't exist locally :param region: :param registry_prefix: :param repo: :param current_tag: :param all_tags: :return: ...
d5d21230f4440e4909a9ff0288a794471b5fb016
21,744
def convert_size_bytes_to_gb(size_in_bytes): """:rtype: float""" return float(size_in_bytes) / GB
7d3946dc431aa6a531fa11ef8e5391279f8b553a
21,745
def merge_swab(survey_df, swab_df): """ Process for matching and merging survey and swab result data. Should be executed after merge with blood test result data. """ survey_antibody_swab_df, none_record_df = execute_merge_specific_swabs( survey_df=survey_df, labs_df=swab_df, ...
38253b473c45a967dc1aeccdd61e94566014a347
21,746
def confirm_space(environ, start_response): """ Confirm a spaces exists. If it does, raise 204. If not, raise 404. """ store = environ['tiddlyweb.store'] space_name = environ['wsgiorg.routing_args'][1]['space_name'] try: space = Space(space_name) store.get(Recipe(space.public...
aff453f96bb85895115dff9796387bc223151c81
21,747
def find_ppp_device_status(address=None, username=None): """Find device status node based on address and/or username. This is currently only used by the web UI. For the web UI this is the best guess for identifying the device related to a forced web forward; which allows the web UI to default username...
71d44185a5df8f72b1281102faef66ea4f8a1de1
21,748
def get_L_dash_prm_bath_OS_90(house_insulation_type, floor_bath_insulation): """主開口方向から時計回りに90°の方向の外気に面した浴室の土間床等の外周部の長さ (m) Args: house_insulation_type(str): 床断熱住戸'または'基礎断熱住戸' floor_bath_insulation(str): 床断熱住戸'または'基礎断熱住戸'または'浴室の床及び基礎が外気等に面していない' Returns: float: 主開口方向から時計回りに90°の方向の外気に面した浴...
13362e5f035865b38ea6562aa7a836ce95298590
21,749
import os def init(): """Authorize twitter app using tweepy library""" # ensure environment variables are set if not os.environ.get("consumer_key"): raise RuntimeError("consumer_key not set") if not os.environ.get("consumer_secret"): raise RuntimeError("consumer_secret not set") ...
fc53f0fe47a689d7a90a43cb1400d69f909c5ded
21,750
import json def generate_books(request, form): """ Returns a list of books. """ list_of_books = Book.generate_existing_books(form.cleaned_data['part']) return HttpResponse(json.dumps(list_of_books), content_type='application/json')
d75deab68c4cb4cdc9f14e4a313ffd060ab01004
21,751
def window_reverse_4d(windows, window_size, H_q, W_q, H_s, W_s): """ Args: windows: (num_windows*B, window_size, window_size, window_size, window_size, C) window_size (int): size of window H_q (int): Height of query image W_q (int): Width of query image H_s (int): Height ...
8ef2743ec15c140807a9c269680f8bd3810703a3
21,752
import argparse def parse_arguments(): """ Function to parse command line arguements from the user Returns ------- opts : dict command line arguements from the user """ info = 'Divides pdb info files for parallelization' parser = argparse.ArgumentParser(description=info) ...
8bdc260c1dcb779c7b30927651e26c05a9c0d5f5
21,753
def numeric(symbols, negative, value): """Implement the algorithm for `type: numeric`.""" if value == 0: return symbols[0] is_negative = value < 0 if is_negative: value = abs(value) prefix, suffix = negative reversed_parts = [suffix] else: reversed_parts = [] ...
4eb41904f1ead6e6f8f6d6a5a7855d917a0029b7
21,754
from typing import Dict def scale_value_dict(dct: Dict[str, float], problem: InnerProblem): """Scale a value dictionary.""" scaled_dct = {} for key, val in dct.items(): x = problem.get_for_id(key) scaled_dct[key] = scale_value(val, x.scale) return scaled_dct
f7ad0cf51129d7abfb85fdba8d64f1c69bba2bad
21,755
import json def get_and_log_environment(): """Grab and log environment to use when executing command lines. The shell environment is saved into a file at an appropriate place in the Dockerfile. Returns: environ (dict) the shell environment variables """ environment_file = FWV0 / "gear_environ.j...
2b91378184a442a3a21c8b94a4667dc9ab90290a
21,756
def green(string: str) -> str: """Add green colour codes to string Args: string (str): Input string Returns: str: Green string """ return "\033[92m" + string + "\033[0m"
b6bdefe3e467e88c044b9289ea26a59ccf564f1a
21,757
def from_6x6_to_21x1(T): """Convert symmetric second order tensor to first order tensor.""" C2 = np.sqrt(2) V = np.array([[T[0, 0], T[1, 1], T[2, 2], C2 * T[1, 2], C2 * T[0, 2], C2 * T[0, 1], C2 * T[0, 3], C2 * T[0, 4], C2 * T[0, 5], C2 * T[1, 3], C2 ...
177d766ee251dfb52396f88b4e77d101956afe79
21,758
def post_add_skit_reply(): """ removes a skit if authored by the current user """ email = is_authed(request) if email and csrf_check(request): # same as args, form data is also immutable request.form = dict(request.form) request.form['email'] = email p_resp = proxy(RUBY, requ...
17b64bba949bb2df57cbdf796c0b895387672018
21,759
from datetime import datetime def register(request): """Register new account.""" token_int = int(datetime.datetime.strftime( datetime.datetime.now(), '%Y%m%d%H%M%S%f')) token = short_url.encode_url(token_int) if (not request.playstore_url and not request.appstore_url and not reques...
649c413011ec76bdb2244bbbfe7f4810230d3202
21,760
def stringify_parsed_email(parsed): """ Convert a parsed email tuple into a single email string """ if len(parsed) == 2: return f"{parsed[0]} <{parsed[1]}>" return parsed[0]
6552987fe6a06fdbb6bd49e5d17d5aadaae3c832
21,761
import math def standard_simplex_vol(sz: int): """Returns the volume of the sz-dimensional standard simplex""" result = cm_matrix_det_ns(np.identity(sz, dtype=DTYPE)) if result == math.inf: raise ValueError(f'Cannot compute volume of standard {sz}-simplex') return result
1b0d806312ee722f3251e1099e604a18d4e762a7
21,762
def all_saveable_objects(scope=None): """ Copied private function in TF source. This is what tf.train.Saver saves if var_list=None is passed. """ return (tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope) + tf.get_collection(tf.GraphKeys.SAVEABLE_OBJECTS, scope))
4c0b8ec0dd65160a113d4e6151a1a5b6d8454926
21,763
def base_to_str( base ): """Converts 0,1,2,3 to A,C,G,T""" if 0 == base: return 'A' if 1 == base: return 'C' if 2 == base: return 'G' if 3 == base: return 'T' raise RuntimeError( 'Bad base: %d' % base )
f1c98b7c24fae91c1f809abe47929d724c886168
21,764
import argparse def parse_args(args): """ function parse_args takes arguments from CLI and return them parsed for later use. :param list args : pass arguments from sys cmd line or directly :return dict: parsed arguments """ parser = argparse.ArgumentParser() required = parser.add_argument...
e3783dc173696b5758d8fc90bc810841e043be0a
21,765
def attr(accessing_obj, accessed_obj, *args, **kwargs): """ Usage: attr(attrname) attr(attrname, value) attr(attrname, value, compare=type) where compare's type is one of (eq,gt,lt,ge,le,ne) and signifies how the value should be compared with one on accessing_obj (so compare=gt me...
8b3944ee8ef64938314766cc21e893ccbf48d9e1
21,766
def group_connected(polygon_map, mask=None): """Group all connected nodes.""" # Wrap :c:`group_connected()` from ``polygon_map.c``. polygon_map = mask_polygon_map(polygon_map, mask) queue = Queue(len(polygon_map) + 1) group_ids = np.full(len(polygon_map), -1, np.intp, order="C") groups_count:...
2239feab1ef914156e01ab430f0c561609de0b18
21,767
def dictmask(data, mask, missing_keep=False): """dictmask masks dictionary data based on mask""" if not isinstance(data, dict): raise ValueError("First argument with data should be dictionary") if not isinstance(mask, dict): raise ValueError("Second argument with mask should be dictionary")...
d18f6effb4367628ba85095024189d0f6694dd52
21,768
import subprocess import time from pathlib import Path def connect(file=None, port=8100, counter_max=5000): """Open libreoffice and enable conection with Calc. Args: file (str or pathlib.Path, optional): Filepath. If None, a new Calc instance will be opened. port (int, optional): ...
a82386b0eff1c8665f056d705a8a65913beecdf4
21,769
from dallinger.config import default_keys from dallinger.config import Configuration def stub_config(): """Builds a standardized Configuration object and returns it, but does not load it as the active configuration returned by dallinger.config.get_config() """ defaults = { u'ad_group': u'T...
57820943883411f7e1081d1ff39ac5677d91f41d
21,770
def _prepare_policy_input( observations, vocab_size, observation_space, action_space ): """Prepares policy input based on a sequence of observations.""" if vocab_size is not None: (batch_size, n_timesteps) = observations.shape[:2] serialization_kwargs = init_serialization( vocab_size, observatio...
9799357e00453a1259551c3af1b5bf5b58603186
21,771
def RGB2raw(R, G, B): """Convert RGB channels to Raw image.""" h, w = R.shape raw = np.empty(shape=(2*h, 2*w), dtype=R.dtype) raw[::2, ::2] = R raw[1::2, 1::2] = B raw[1::2, 0::2] = G raw[0::2, 1::2] = G return raw
7adb2ccef65c85c7e5d1ac223f397ef2f90dd9d3
21,772
def get_algs_from_ciphersuite_name(ciphersuite_name): """ Return the 3-tuple made of the Key Exchange Algorithm class, the Cipher class and the HMAC class, through the parsing of the ciphersuite name. """ tls1_3 = False if ciphersuite_name.startswith("TLS"): s = ciphersuite_name[4:] ...
cc2ab3fcae87feeb7877bad091446fb2d20be6b0
21,773
def centroid(window): """Centroid interpolation for sub pixel shift""" ip = lambda x : (x[2] - x[0])/(x[0] + x[1] + x[2]) return ip(window[:, 1]), ip(window[1])
e1cf0398261637f682c74340f99566d19e342b66
21,774
def _format_warning(message, category, filename, lineno, line=None): """ Replacement for warnings.formatwarning that disables the echoing of the 'line' parameter. """ return "{}:{}: {}: {}\n".format(filename, lineno, category.__name__, message)
8267150c5890759d2f2190ccf4b7436ea8f55204
21,775
from typing import List def precision_at_k(predictions: List[int], targets: List[int], k: int = 10) -> float: """Computes `Precision@k` from the given predictions and targets sets.""" predictions_set = set(predictions[:k]) targets_set = set(targets) result = len(targets_set & predictions_set) / float(...
4c6e566db7c488416139545f5f845ff80b7af434
21,776
def wordify_open(p, word_chars): """Prepend the word start markers.""" return r"(?<![{0}]){1}".format(word_chars, p)
8b267aaca897d6435a84f22064f644727ca6e83c
21,777
def Mt_times_M(M): """Compute M^t @ M Args: M : (batched) matrix M Returns: tf.Tensor: solution of M^t @ M """ if isinstance(M, tf.Tensor): linop = tf.linalg.LinearOperatorFullMatrix(M) return linop.matmul(M, adjoint=True) elif isinstance(M, (tf.linalg.LinearOper...
cfb8023711186821faf0ff8bfa1277d6585d40de
21,778
import typing def make_values(ints: typing.Iterable[int]): """Make datasets. """ return [ ('int', ints), ('namedtuple', [IntNamedTuple(i) for i in ints]), ('class', [IntObject(i) for i in ints]), ]
700bbd4a43bff38a0154bbc595c1cd10cc2ec9d9
21,779
import collections def attach_trans_dict(model, objs): """Put all translations from all non-deferred translated fields from objs into a translations dict on each instance.""" # Get the ids of all the translations we need to fetch. try: deferred_fields = objs[0].get_deferred_fields() except...
933e87b050eac0dfbead141c0c3c56a2add9751f
21,780
def list_known_protobufs(): """ Returns the list of known protobuf model IDs """ return [k for k in proto_data_structure]
a4b80f948792a4d2a965eac507a118719fa106f5
21,781
def hash_value(*args): """ hash_value(NodeConstHandle t) -> std::size_t hash_value(BufferConstHandle t) -> std::size_t hash_value(FileConstHandle t) -> std::size_t """ return _RMF.hash_value(*args)
c85277fec7f329eeba26d053a43205bf1eda0662
21,782
import re def read_examples(input_file): """Read a list of `InputExample`s from an input file.""" examples = [] unique_id = 0 # with tf.gfile.GFile(input_file, "r") as reader: with open(input_file, "r") as reader: while True: line = tokenization.convert_to_unicode(reader.readli...
82380f9409bd91e16fc4324fc345d335fa9e96dc
21,783
from datasets import load_dataset def get_finance_sentiment_dataset(split: str='sentences_allagree') -> list: """ Load financial dataset from HF: https://huggingface.co/datasets/financial_phrasebank Note that there's no train/validation/test split: the dataset is available in four possible ...
9f83d4c501ed16e5e617c32090787d1377ec70fd
21,784
def list_databases(): """ List tick databases and associated aggregate databases. Returns ------- dict dict of {tick_db: [agg_dbs]} """ response = houston.get("/realtime/databases") houston.raise_for_status_with_json(response) return response.json()
d2ba438a0496f5863ad1c16cb8e694b54276d01e
21,785
def nice_range(bounds): """ Given a range, return an enclosing range accurate to two digits. """ step = bounds[1] - bounds[0] if step > 0: d = 10 ** (floor(log10(step)) - 1) return floor(bounds[0]/d)*d, ceil(bounds[1]/d)*d else: return bounds
66f538649b8f1c55d301b2a0e293a4968b3665d9
21,786
def connect_to_portal(config): """ The portal/metadata schema is completely optional. """ if config.portal_schema: return aws.connect_to_db(**config.rds_config, schema=config.portal_schema)
2aa76ae2ad8d9ea16ea7ba227627f02d3c044d70
21,787
import json def get_words_for_source(): """ Gets JSON to populate words for source """ source_label = request.args.get("source") source = create_self_summary_words(source_label) return json.dumps(source)
2a2fc02a6f77cd109f3e0fded026676109ae014c
21,788
def raster(event_times_list): """ Creates a raster plot Parameters ---------- event_times_list : iterable a list of event time iterables color : string color of vlines Returns ------- ax : an axis containing the raster plot """ color='k' ax = plt.gca() for ith...
3c5b485bdc3992602a7c7bb227329b2e74c611d9
21,789
def FindOneDocument(queryDocument, database='NLP', collection="Annotations", host='localhost', port='27017'): """ This method returns the first document in the backing store that matches the criteria specified in queryDocument. :param queryDocument: [dict] A pymongo document used to query the MongoDB insta...
fb5f683f4451144ae3cbe374162bef36918130ba
21,790
def user_info(context, **kwargs): """ Отображает информацию о текущем авторизованом пользователе, либо ссылки на авторизацию и регистрацию Пример использования:: {% user_info %} :param context: контекст :param kwargs: html атрибуты оборачивающего тега :return: """ request = co...
20321056fd5fdf8f51e79fb66d335272e85ada0d
21,791
from functools import reduce from datetime import datetime def transactions(request): """Transaction list""" tt = TimerThing('transactions') # Get profile profile = request.user.profile characters = Character.objects.filter( apikeys__user=request.user, apikeys__valid=True, ...
46585859baa2a665f30d6abd48455c9abefa1c1e
21,792
def to_bytes(val): """Takes a text message and return a tuple """ if val is NoResponse: return val val = val.replace('\\r', '\r').replace('\\n', '\n') return val.encode()
9f5a45d9c69a18eec22c85c6691f8b3d46742af4
21,793
def _create_fake_data_fn(train_length=_DATA_LENGTH, valid_length=50000, num_batches=40): """ Creates fake dataset Data is returned in NCHW since this tends to be faster on GPUs """ logger = _get_logger() logger.info("Creating fake data") data_array = _create_data(_BATCHSIZE, num_batches, (_HEI...
33533cc4b1d43aaeba48db8470c93cbc058ad3dc
21,794
def watershed(src): """ Performs a marker-based image segmentation using the watershed algorithm. :param src: 8-bit 1-channel image. :return: 32-bit single-channel image (map) of markers. """ # cv2.imwrite('{}.png'.format(np.random.randint(1000)), src) gray = src.copy() img = cv2.cvtColo...
6915b6a924e64d12340e02b28085290685dddc9b
21,795
def sub(x, y): """Returns the difference of compositions. Parameters ---------- x : NumPy array, shape (n,) or (k,n) The composition that will be subtracted from. y : NumPy array, shape (n,) or (k,n) The composition to be subtracted. Returns ------- z : NumPy array, sha...
c9e1fb31abb22a6efb9903c6e9f7cdc06cc110d0
21,796
def _broadcast_concatenate(arrays, axis): """Concatenate arrays along an axis with broadcasting.""" arrays = _broadcast_arrays(arrays, axis) res = np.concatenate(arrays, axis=axis) return res
5032ec0a90dde25d74906dbf661248086c785485
21,797
def get_final_bmi(data_dic, agex_low, agex_high, mrnsForFilter=[], filter=True): """ Function to get the distinct bmi percentile readings for predictions. Returns outcome percentiles and labels #### PARAMETERS #### data_dic: dictionary of patient data agex_low: low age range for outcome predicti...
e9793adf7470a695bd730f66817b735451df71a2
21,798
import sqlite3 def add_group_sub(uid:int, group_id:int) -> bool: #添加订阅信息 """ 向已存在的表中插入群记录, 如果群已经存在则什么都不做 :param uid: 唯一标识用户的数字uid :param group_id: 监听该用户的群id """ connection = sqlite3.connect(DB_PATH) cursor = connection.cursor() success = True group_exist = cursor.execute( f...
de71f03aa56bf4ae963877281e7e70876f5e72ff
21,799