content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
import re def is_ssh_destination(string) -> bool: """Check if string is a (more or less) valid SSH address (user@host:...).""" return bool(re.match(r'([^\s]+)@([^\s]+):(.*)', string))
06a85c7a25c9c9f40cbd7498402a92d0b89e0d78
635,144
def manual(path, value): # pylint: disable=W0613 """ Dummy function that returns it's input For tools that cannot be read automatically use a value from the toolkit file Parameters ---------- path : str Ignored value : str The value to return Returns ------- ...
86f03be0fb9af76a6a441db146e3f3ce8e6bb048
635,145
def uppercase(s: str) -> str: """ Convert a string to uppercase. Args: s (str): The string to be converted. Returns: str: The converted uppercase string. Example: >>> uppercase('completely different') == 'COMPLETELY DIFFERENT' True """ return s.upper()
f1ecb6e412ea3ce6e46531174881ad230bed3802
635,148
def get_text_hv(angle): """Returns (ha, va) text horizontal and vertical alignment for line label. This makes the line label text inside its area, assuming areas closed CW. Args: angle (float): line normal vector in degrees, between 180 and -180 """ horiz, vert = ('', '') if abs(angle)...
f52819fb02b1248279de58e312a8fe9b77b16ab6
635,152
def _incrementResourceVersion(version): """ Pyrsistent transformation function which can increment a ``v1.ObjectMeta.resourceVersion`` value (even if it was missing). :param version: The old version as a ``unicode`` string or ``None`` if there wasn't one. :return unicode: The new version, ...
d1d3675c0761b6818f05b2fd5174c367f76264f6
635,156
def load_words(file_name): """ file_name (string): the name of the file containing the list of words to load Returns: a list of valid words. Words are strings of lowercase letters Depending on the size of the word list, this function may take a while """ print("Loading word list from file.....
54dd92f86b843d01bc2e7fb29002c9adf70c809e
635,157
import yaml def load_yaml(file_path): """ Load a yaml file. Handles doc separation by loading all and combining into common dict. """ docs = yaml.load_all(open(file_path,'r',encoding='utf-8'),Loader=yaml.SafeLoader) data = {} for doc in docs: for key in doc: if key not in data: data[key] = doc[key] e...
a8ccd378e2b6e497e03d7111dffe58161b3c14c9
635,162
def calc_frip(bamfile, ftfile, frip_func, pipeline_manager, aligned_reads_key="Aligned_reads"): """ Calculate the fraction of reads in feature file. Use the given function and data from an aligned reads file and a features file, along with a PipelineManager, to calculate. :param str...
b8f80799ed5fffb9eae886aa5651af7c53316c25
635,167
def binconv(fp, fp_len): """ Converts 0 to -1 in the tokens' hashes to facilitate merging of the tokens' hashes later on. input : 1001...1 output : [1,-1,-1, 1, ... , 1] """ vec = [1] * fp_len for indx, b in enumerate(fp): if b == '0': vec[indx] = -1 return vec
6f856cad0fe1441d34d295b607fbda550aae1c8c
635,170
import re def remove_stop_words(stop_words, text): """ Description Parameters: ---------------- stop_words: list List of strings to remove text: string String to process Returns: ---------------- filtered: string String with stop words removed """ ...
6e76afea3a001d56ba552280fd20c50ff31dc9aa
635,171
def get_modified_fields(old_values, new_values): """ Return all fields that have been modified from original fields """ field_changes = {} for key, value in new_values.items(): try: original_value = old_values[key] except KeyError: """If there are addtional ...
deab00eb56ad13c02d7233e924f5cd1377872cba
635,174
def tokenize(text, nlp): """Word tokenize a single string. Parameters ---------- x: str A piece of text to tokenize. nlp: spacy tokenizer, e.g. spacy.lang.en.English By default, a spacy tokenizer with a small English vocabulary is used. NER, parsing, and tagging are disabled...
bb1106ea8f445329bd6e93bd91174948595d4ec8
635,177
def load_dfa(path_to_dfa_file): """ This function reads the DFA in the specified file and returns a data structure representing it. It is up to you to choose an appropriate data structure. The returned DFA will be used by your accepts_word function. Consider using a tuple to hold the parts o...
cfe38e804bda028a142006d2f49ae8152f88ca1b
635,178
def test_mask_none(dqarr, bitmask): """ Probes 'dqarr' to see whether NONE OF the bits in the specified mask are raised. :Parameters: dqarr: numpy array which represents a dq plane (or part of it). bitmask: integer A bit mask specifying any of the bits...
ebbe5996bafefebee5eaf89c5d7b4c1aa35ee55c
635,184
def get_layer_set(layer: str) -> str: """Layers in the same layer set share a config. Args: layer: Full name of the layer. This will be the PyTorch or Opacus name of the layer in lower case (e.g. linear, rnn, dprnn), prefixed with gsm_ (e.g. gsm_linear, gsm_dprnn) if DP is enabled. Mult...
3cef6d812bbc1951174f4e0da15308e239949eab
635,187
def get_context(token_ids, target_position, sequence_length=128): """ Given a text containing a target word, return the sentence snippet which surrounds the target word (and the target word's position in the snippet). :param token_ids: list of token ids (for an entire line of text) :param target_po...
dca93971d2376efabf79b54263edfdca67236cfd
635,193
def get_optional_option(config, section, option): """Return an option from a ConfigParser, or None if it doesn't exist.""" if config.has_option(section, option): return config.get(section, option) return None
e4a7567a66075f19c71dd9175694c8e1ea758bc7
635,195
def collect_subset_scores(scorer_list, metric_name, tag_list, reset=False): """ Get the scorer measures of each tag. This function is only used by tasks that need evalute results on tags, and should be called in get_metrics. Parameters: scorer_list: a list of N_tag scorer object met...
4b7cf901b651b1e8e86c3708765b63418c4cbcbe
635,201
def _blocks_changed(block1, block2): """ Compare two Block objects Args: block1: The first block to compare block2: The second block to compare Returns: True if the provided blocks are different, False otherwise """ if block1.name != block2.name: return True ...
62366f781024f719bd4e7370eb59fb8acb206754
635,202
import copy import collections def stringify_keys(dictionary: dict): """ This helper function will stringify all keys in the given dictionary. For example: > from apps.authentication.models.user import Jobs > data = { Jobs.PTA: True } > stringify_keys(data) { "PTA": Tr...
db5a08fc106ce01ef90d37e896a24db2d143ce13
635,207
def fiber_packages(packages): """ Retrieve all packages of type 'Fibra' :param: list of packages """ lista = [] for pacote in packages: if pacote['tipo'] == 'Pacotes Fibra': lista.append(pacote) return lista
40669cfe3c134dbb82c8237bf8c18f62f8ad77df
635,209
import torch def gaussian_discrete_erf(window_size, sigma): """ Discrete Gaussian by interpolating the error function. Adapted from: https://github.com/Project-MONAI/MONAI/blob/master/monai/networks/layers/convutils.py """ device = sigma.device if isinstance(sigma, torch.Tensor) else None...
0bbfd1c3fee5d5eeca6c83d2ee281301a57ce35a
635,213
def get_id(vmfObject, idPropName='id'): """ Returns the ID of the given VMF object. """ return int(vmfObject[idPropName])
ffed36fe64194c5d9aeb5f154639b9f321b33a7d
635,215
import collections def build_toc_item(title, path=None, sub_items=None): """Create an item in the TOC. Args: title (str) - Title for this item. path (str) - Path to the page for this item. sub_items (list) - Items to place in a collapsible subsection. """ item = collections.OrderedD...
47f05ff4b7f63ff1dbcf52f0e87e19ddffab7d7c
635,217
import importlib def load_class(str_full_type): """ Load a python class given full qualified name. """ type_s = str_full_type.split('.') mod = importlib.import_module('.'.join(type_s[:-1])) cls = getattr(mod, type_s[-1]) return cls
b443517e67462c78129adc509f1c0e0282228a79
635,221
def convert_hex_to_rgb_255(hex_str): """Convert hex color to rgb in range 0-255.""" hex_color = hex_str.lstrip("#") n = len(hex_color) rgb = list(int(hex_color[i : i + int(n / 3)], 16) for i in range(0, int(n), int(n / 3))) return rgb
f9034e0ad00f678226ed40afaa560ee27b416220
635,224
from typing import List def nd_slice(d: int, dim: int = 0, start: int = 0, end: int = 1) -> List[slice]: """Create a multi-dimensional slice. Args: d (int): number of dimensions dim (int, optional): target dimension that will be sliced. Defaults to 0. start (int, optional): start inde...
c80d27ac36f714504435746fd6c71ed4387fb9d5
635,228
def filter_interface_conf(c): """Determine if an interface configuration string is relevant.""" c = c.strip() if c.startswith("!"): return False if c.startswith("version "): return False if c.startswith("interface"): return False if not c: return False return ...
997f2dc0729185d533e7069c1379c8fa9a4be646
635,229
import torch def assemble_recon_data(heldin, heldin_forward, heldout, heldout_forward): """Combines heldin/heldout and observed/forward data into a single tensor. Parameters ---------- heldin : torch.Tensor A BxTxN tensor. heldin_forward : torch.Tensor A BxT_FWDxN tensor. ...
98708f51f624c4c8c7f11363aa20afd63836f86e
635,231
def _quote(filename, protect = "="): """Quote the filename, by escaping = by \\= and \\ by \\\\""" return filename.replace("\\", "\\\\").replace(protect, "\\" + protect)
8b1605f7ff7a0948bf99f47dbcff5c4587ab03b5
635,240
def fully_qualified_name(type_: type) -> str: """Construct the fully qualified name of a type.""" return getattr(type_, '__module__', '') + '.' + getattr(type_, '__qualname__', '')
d7a8f2313ca6db3fd9baaf1f275c8f404f7ac091
635,244
def is_passed_counting_roi(current_point, first_point, roi_polygon, roi_outside, is_enter): """ will check if the point passed the counting roi. if the current location in the roi and the first location not in the roi - it passed if the current location not in the roi and the first location in the roi - it ...
d48a158db0251a4ef64ec472d024029cf5f8ef8d
635,245
def _capped_double_heads(num_heads, cap=16): """Calculate the number of heads for the attention layers with more heads. The number of heads will be twice the normal amount (num_heads), until it reaches |cap| heads. Args: num_heads: the num_heads hparam for the model. cap: the maximum number of heads |...
b61bcb1a4fba933c1b17e7320cc73eeabb35dc59
635,246
def is_only_preceded_by(string: str, to_find: str, preceded: str) -> bool: """ check if an element in a string is only preceded by the indicated character, even multiple times. Raise an ValueError if to_find is not found :param string: the string to search in :param to_find: the string to searc...
0e2d576c7250a58b139802c8058669112e514a69
635,248
def sub_block_values(config, key): """Extract set of values associated with a sub block key Parameters ---------- config : str Path of the config file. key : str Sub block key (e.g. "SubCategory") Returns ------- set(str) Unique values of the given key """ ...
3e52aeeae05ef8f57dac1a2a85de055cec10afac
635,257
import hashlib def _get_file_sha256_hash(file_path): """ Takes a file and returns the SHA 256 hash of its data Args: file_path (str): path of file to hash Returns: (str) """ sha256hash = hashlib.sha256() chunk_size = 8192 with open(file_path, "rb") as f: while True: ...
34db2c1a35bb34dd192f3ea8ac22b475d987619e
635,258
def chrome_options(chrome_options, create_tmp_dir): """Set configuration to run Chrome with specific options.""" prefs = {"download.default_directory": create_tmp_dir, "download.prompt_for_download": False} chrome_options.add_experimental_option("prefs", prefs) return chrome_options
bd1a25192bff87f54da62794aec9288c1497f488
635,267
from typing import Dict def solve_part2(identified: Dict[str, str]) -> str: """ identified: 'eggs': 'hn', 'fish': 'dgsdtj', 'nuts': 'kpksf', 'peanuts': 'sjcvsr', 'sesame': 'bstzgn', 'shellfish': 'kmmqmv', 'soy': 'vkdxfj', 'wheat': 'bsfqgb' Solution: hn,dgsdtj,kpksf,s...
a1842b78c6ff08cfb7c8a7d7c4ebaf59e16c4f14
635,269
def _list_info(candidate_element): """Log element id, title or placeholder """ outer_html = candidate_element.get_attribute('outerHTML') if outer_html != '' or outer_html is not None: return "OuterHTML: {}".format(outer_html) return candidate_element
c400126e927c399beb99aac699c276a7e1ffb3aa
635,272
def parse_cdk_file(file): """ Function to parse CDK output Parameters ---------- file : str file to parse the chemical descriptors from Returns ------- dict dictionary containing the chemical descriptor name and the chemical descriptor value """ cdk_file...
aa4c541af2163c546c9dada91020a929ff3f16f0
635,280
def _normalise(s): """ Normalise the supplied string in the following ways: 1. String excess whitespace 2. cast to lower case 3. Normalise all internal spacing :param s: string to be normalised :return: normalised string """ if s is None: return "" s = s.strip().lower()...
f89b219e04e83d3e8fc9feae1aad6a00d24d525b
635,283
import six def inclusion_only_unlimited_args_from_template(*args): """Expected inclusion_only_unlimited_args_from_template __doc__""" return { "result": "inclusion_only_unlimited_args_from_template - Expected result: %s" % ( ', '.join(six.text_type(arg) for arg in args) ) }
4ebce01c95457e7f063a52b70097a0c23cbf65e9
635,285
import warnings def no_of_events(tweet_file, t_observation, t_prediction, time_factor=1): """ calculate the number of retweets at the observation time (=t_observation) and at the final time of prediction (=t_prediction) :param tweet_file: data file :param t_observation: observation time :param t_p...
ee198f820503e29aa2b3733811e49302a76e61b5
635,291
def option_str_list(argument): """ An option validator for parsing a comma-separated option argument. Similar to the validators found in `docutils.parsers.rst.directives`. """ if argument is None: raise ValueError("argument required but none supplied") else: return [s.strip() fo...
e198f0351dc67d9b90826f9d597e6e6e4c23d6c6
635,295
def discard_empty(s: str) -> bool: """Return true if the provided string is non-empty.""" if s: return True return False
fa647606297b2fb0d67f610d88681d98363c8f32
635,297
def calcDistance(ent1, ent2): """ Calculate the distance between two entities """ dimensionDelta = (ent1.dimension-ent2.dimension) * 1000 deltaPos = [ent1.pos[a]-ent2.pos[a] for a in (0, 1)] return (deltaPos[0]**2 + deltaPos[1]**2)**0.5 + dimensionDelta
6940f9332656677c42a79a4470e715acb1a9de16
635,298
import torch def create_batch_from_data_list(data_list): """Given a list of datapoints, create a batch. Args: data_list (list): List of items returned by SceneRenderDataset. """ imgs = [] azimuths = [] elevations = [] for data_item in data_list: img, render_params = data_i...
416777a8ee3fffd8fb572707408e1bd34e2e597c
635,299
import io def _encode_image(image_array, fmt): """encodes an (numpy) image array to string. Args: image_array: (numpy) image array fmt: image format to use Returns: encoded image string """ from PIL import Image # pylint: disable=g-import-not-at-top pil_image = Image.fromarray(image_array) ...
9fa65e7f158b766e670bd5bd10120be22d39485c
635,300
from typing import AnyStr def detect_space_after(txt: AnyStr, end: int): """Given text and an end index returns True if there is a space after the end index, false otherwise. Parameters ---------- txt : str the text itself. end : int the end index of the token. Returns ...
ed64cb63ec77cdca92b2e312852f6f21f7fdd4ee
635,301
def split_file_name(file_absolute_name): """ Splits a file name into: [directory, name, extension] :param full_name_template: :return: """ split_template = file_absolute_name.split('/') [name, extension] = split_template[-1].split('.') directory = "/".join(split_template[0: len(split_te...
f3144b0f75cbde26c8a8244cb8d8eda712e8edfa
635,306
import socket from contextlib import closing def check_socket(port): """Check whether the given port is open to bind""" with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as sock: try: sock.bind(('', port)) except: #Port is not open res = False...
93bce5290e0b1774c18c1ecdc592af3dd80f976d
635,310
import json import hashlib def get_hash(block): """ Creates a SHA-256 hash of a Block :param block: Block """ # We must make sure that the Dictionary is Ordered, or we'll have inconsistent hashes block_string = json.dumps(block, sort_keys=True).encode() return hashlib.sha256(block_string)...
7b3c7f1f7c7ec566199f6742bdcc67d2f0e99d9a
635,311
def return_ttl(name: str) -> int: """ **return_ttl** returns ttl for cache depending on long, short, and medium :param name: string -> period = short, medium, long :return: int -> time to live """ cache_ttl_short: int = 1800 # (60*60 * 0.5) 30 minutes cache_ttl_medium: int ...
cdedc8617c86828ee6fb00965a5ceb2b206c7537
635,319
import json def get_filtered_keys_from_map(key_map, payload): """ Filter the payload for the given keylist and return the filtered dict :param key_list: a json old_key:new_key map in string format :param payload: dict payload which needs to be filtered :return: dict with new_key, value pair based ...
e5476d352c7969606a52b7c4260aea0877756cf6
635,322
def chunk_string(input_str, length): """ Splits a string in to smaller chunks. NOTE: http://stackoverflow.com/questions/18854620/ :param input_str: str the input string to chunk. :param length: int the length of each chunk. :return: list of input str chunks. """ return list((input_str[...
77d6d04bae52429f5a31de96baf1b761e224dd43
635,324
def transform_table(table): """ Unsqueeze keys aligning with values Args: table: table defining key-value pairs Returns: - unsqueezed key-value dict """ keys, values = [], [] for sample in table: ks, vs = [], [] for k, vals in sample.items(): ks....
08b232af802d4b4d79051470b20bd51753d5931b
635,327
def line_from_2_points(x1, y1, x2, y2): """ Gets the coefficients of a line, given 2 points :param x1: :param y1: :param x2: :param y2: :return: """ a = y1 - y2 b = x2 - x1 c = x1 * y2 - x2 * y1 return a, b, c
c0ce5d3963a1dcd6ef83b09edcef4a08a2e4faed
635,328
def is_pandigital(n): """Tests if n is a 1-9 pandigital""" if len(str(n)) != 9: return False if "0" in str(n): return False return len(str(n)) == len(set(str(n)))
404595a3cd75829cc4c4f324a0b8bfe86884d6a5
635,329
def mulrowcol(row, col, K): """ Multiplies two lists representing row and column element-wise. Gotcha: Here the column is represented as a list contrary to the norm where it is represented as a list of one element lists. The reason is that the theoretically correct approach is too expensive. This p...
448aec2928b314cabe707f19f69bfd687b8fe31c
635,331
import base64 def load_wrap(filename, attach=False): """ Encodes a load or attach command as valid Python code. INPUT: - ``filename`` - a string; the argument to the load or attach command - ``attach`` - a boolean (default: False); whether to attach ``filename``, instead of loading ...
563b48d56d121d5df87d5f577390b4cd5a6a0abc
635,332
def bool_to_bin(bool_value): """ Helper function to map a boolean value to a binary value. :param bool_value: boolean boolean value [bool] :return: binary value [int] """ if bool_value: return 1 else: return 0
4d05f6644d434fe8eb99743f17f2fd1b472cbdb5
635,333
def _has_tag(Estimator, tag): """Check whether an Estimator has the given tag or not. Parameters ---------- Estimator : Estimator class tag : str An Estimator tag like "skip-inverse-transform" Returns ------- bool """ # Check if tag is in all tags return Estimator._...
ceb580cbcb89a208a290080e0efe429e2ecb1e95
635,335
import logging def get_lower_level(l0, l1): """Compare logging levels and return the lower level.""" if isinstance(l0, (str)): l0 = logging.getLevelName(l0) if isinstance(l1, (str)): l1 = logging.getLevelName(l1) return l0 if l0 < l1 else l1
c9bde5945ad5d88729e0181e46b2a14576f94d1f
635,337
import string import re def clean_text_round3(text): """ Clean up text data. Do what clean_text_round1 does, adding: Remove pontuations, except accents. Remove words if less than 3 letters Remove some special chars commom in papers """ remove = string.punctuation remove = remove.r...
a9897ace93ec564a50cfb32718fa4753f06e6334
635,340
def model_snowdepthtrans(Sdepth = 0.0, Pns = 100.0): """ - Name: SnowDepthTrans -Version: 1.0, -Time step: 1 - Description: * Title: snow cover depth conversion * Author: STICS * Reference: doi:http://dx.doi.org/10.1016/j.agrformet.2014.05.002 ...
c5b9a471a8a3a860cd305af58a5c4b4614fc1918
635,343
def match_path(path, partial_paths): """Does the given path contain any of the stubs in partial_paths?""" return any(partial_path in str(path) for partial_path in partial_paths)
54d69378ac4f03848a1bed331f9eebdbc426ea24
635,344
import click def atomic_to_global_desc_options(f): """Create common options for global descriptors constructed based on atomic fingerprints """ f = click.option('--reducer_type', '-r', help='type of operations to get global descriptors from the atomic soap vectors, e.g. \ ...
5765d98445134a0e5795dd1d87d44eb02e3eefc4
635,353
def get_aa_at_gene_pos(row, ref_aa_seq_dict): """ Helper function to apply on every row of a data frame to find the reference amino acid at given a gene and amino acid position. Parameters: ============== - row: dict Row of dataframe in dict form. Should have fields aa_pos (1-based aa po...
d237e7a29d6b2cd2eb39b58e6a88106fedfb2a6e
635,357
def lower_text(text: str) -> str: """ Given ``text`` str, transform it into lowercase Parameters ---------- text : string Returns ------- string """ return text.lower()
d90308073617a3e7884edb4253aa5ac221f3b672
635,358
from datetime import datetime def get_current_datetime() -> datetime: """ Generate datetime in UTC timezone. Returns: datetime: datetime. """ return datetime.utcnow()
f93af05b4660306545e2e505c50a7fd016ec2773
635,359
def _extract_match_id(match_json): """ Extract the match_id from json response. { "matches": [ { "id": "0000...", "match_id": 1313, "similarity": "001000" } ] } """ matches = match_json.get('matches', []) ...
60109a70aceae4f5074338b268f498da56af65f0
635,362
def ascii_encodable(text): """ Return True if the given TEXT can be losslessly encoded in ASCII. Otherwise, return False. """ return all(ord(char) < 128 for char in text)
1defb4b6453445bf26650bd0169045b70b8f053e
635,363
import time def allow_retries(retry_on=[], wait=time.sleep, retries=3, delay=2): """ A general purpose decorator that allows a given function to be retried after certain failures. **Example** Suppose we have a function that occasionally throws errors if it doesn't get its way. In that case we ca...
453f8ef0af44dad4347bef21d09ff63f226a4e1a
635,369
import socket def ping_command(ping_binary, address, version=socket.AF_INET, count=1, payload_size=None): """Generate a ping shell command for Popen""" args = [ping_binary] if version == socket.AF_INET6: args.append('-6') else: args.append('-4') # ping interval args.append('-i...
6401db8a5052bcecf6eb256d9a3b9c094a7bc6dd
635,370
def df2geojson(df, lat='latitude', long='longitude', remove_coords_properties=True): """ Convert um dataframe, com colunas de latitude e longitude, em um objeto geojson de pontos https://notebook.community/gnestor/jupyter-renderers/notebooks/nteract/pandas-to-geojson # Usage feature_collection = da...
cb4ffc75e84f0a201ff10ba60ec4b82ab1c8e683
635,372
def google_map(context): """ Dependencies for google_map gizmo. """ return ('tethys_gizmos/js/tethys_map.js',)
036f03be322b10b03a3233eb4c47b8db1eaa4c88
635,375
def pipe_Do(Di, WT): """Calculate pipe outer diameter, given the pipe inner diamater and wall thickness. """ Do = Di + 2 * WT return Do
2c044187e3b8700cc3c7524d8b0524639a93c5dd
635,380
def compute_asdp_size(manifest): """ Computes the total size of the ASDP from the manifest entires Parameters ---------- manifest: list list of dicts containing the manifest entries Returns ------- asdp_size: int the total size in bytes associated with "asdp," "validate...
ff92053b5c8022e76ff9973be928a9e32a678e90
635,381
def general_acquisition_info(metadata): """General sentence on data acquisition. This should be the first sentence in the MRI data acquisition section. Parameters ---------- metadata : :obj:`dict` The metadata for the dataset. Returns ------- out_str : :obj:`str` Outpu...
6836afb1670c22bb718f34e75bc11c24a45ad0aa
635,386
def get_bulb(zid, bulbs): """Retrieve a bulb by its zid from a list of Bulb objects.""" for bulb in bulbs: if bulb.zid == zid: return bulb return None
19e579e2394cbbc30553f1a9432e1e1871c3bbc6
635,389
def _get_proto_name(proto): """Get the value of a proto's name field or return the proto type name. Args: proto: Proto to query. Returns: Human readable name of the proto. """ if 'name' in proto.DESCRIPTOR.fields_by_name: return proto.name return proto .DESCRIPTOR.name
dafd11d1b42c86a29bf273fe22b02b9257b74fcf
635,393
import torch def gpu_mem_allocate_mbs(n, fatal=False): """ Try to allocate n MBs on the current device. Return the variable holding it on success, None on failure. fatal=True will throw an exception on failure to allocate (default is False). """ # don't try to allocate less than 6MB as it'd...
ad44279b4e01c614057f680cea2527442bbd4107
635,397
from typing import Sequence def wrap_with_any_of(schemas: Sequence): """Take multiple JSON schemas and combine them using the `anyOf` JSON schema notation""" if len(schemas) == 1: return schemas[0] else: return {"anyOf": schemas}
6379b991dad8f4c989d40879e496e45573bd57e1
635,402
def get_neighbours(x, y): """Get neighbours for an x, y location Args: x (int): x coord y (int): y coord Returns: List: list of tuples with x,y coords """ neighbours = [] neighbours += [(x-1, y)] neighbours += [(x, y-1)] neighbours += [(x, y+1)] neighbours += ...
f39155b3ab26a757c802fdefb6237f3115c57836
635,403
def get_roots(pred_calls, sort_key = str): """Returns list of all roots of the given predicate calls. >>> aststs = functools.partial(ast, sts) >>> preds = list(map(aststs, [sl.tree("x"), sl.list("h"), sl.tree("a"), sl.list.seg("h", "t")])) >>> get_roots(preds) [a, h, x] >>> get_roots(preds, str...
01e3ade08c4b4937c08688e812ea8f44fd7b567e
635,404
def get_index_dictionary(filepath, delimiter='\n'): """Generates a dictionary of words to their respective indices. Args: filepath (str): File path. delimiter (str, optional): Delimiter separating words. Defaults to '\n'. Returns: Dictionary mapping words to their indices. """ ...
687cd9d7996ddff3a9223373b013249fec0574ab
635,405
def qname_and_mate(qname): """ Removes mate sequence from qname. qname: original qname Return value: tuple (qname, mate sequence, which could be empty) """ split_name = qname.split('\x1d') mate = split_name[1].rpartition(':') split_name[1] = mate[0] + ':' return ('\x1d'.join(sp...
c55d4b4ca4814c17bd39fac98bc916025697114b
635,411
def flow_number_poly(cappa): """Calculate flow number for a given pump's typical number. The polynomial has been calculated applaying the curve fitting at nodes cappa .2 .3 .4 .5 .6 .7 .8 .9 1.0 1.1 1.2 phi .080 .093 .100 .110 .120 .130 .140 .150 .160 .165 .170 weights ones(cappa)...
56dcf6cfee4a8a6110f6b29a934e8acfb35b20b5
635,413
def is_missing_atom_map(molecule): """ Checks if any atom in molecule is missing a map index. If even only one atom is missing a map index will return True Parameters ---------- molecule: oechem.OEMOl Returns ------- bool """ MISSING_ATOM_MAP = False for atom in molecule.Ge...
617b4fb51c777daf89d4ce0c8b6ba71752306dad
635,414
def stringify(hitObject): """Turns a TaikoObject into a string that TITaiko understands""" ret = str(int(hitObject.offset)) + ':' + str(hitObject.objType.value) # Add a third parameter if the object is a long note if (hitObject.length != None): ret += ':' + str(int(hitObject.length)) return ret
1fbd8d57377fe30975c1535cc4c6a3b9b31438d9
635,417
import torch def encode(matched, priors, variances): """Encode the variances from the priorbox layers into the ground truth boxes we have matched (based on jaccard overlap) with the prior boxes. Args: matched: (tensor) Coords of ground truth for each prior in point-form Shape: [num_pri...
9e8b8b413cc0a7ff5b5d9054b1c1a2e33e2d0815
635,418
def product(l): """Multiply together the elements of a list.""" prod = 1 for x in l: prod *= x return prod
1f0a8ddbff84b5fc01ff4e974b39b3b0b5f8695d
635,423
def expected_errors(snippets): """Get and normalize expected errors from snippet.""" out = snippets.pop(0) assert out.startswith("[GraphQLError(") return " ".join(out.split()).replace("( ", "(").replace('" "', "")
57ff4693779ef221daf400d0b2fef68bfbd4d581
635,424
def avoids(w, s): """ Check if the word contains any of the characters specified in a string. Return True if it does not """ for l in w: if l in s: return False return True
fc0bcc308cac9c7abef00c66116e3698f55afbfa
635,430
import time def dateToDBFmt(strVal, fromFmt="%m/%d/%Y"): """Convert a date from the specified fromFmt (a string accepted by time.strptime) to "yyyy-mm-dd", the format used by databases. """ try: dateTuple = time.strptime(strVal, fromFmt) except ValueError: raise ValueError("%s not ...
38acc3f2c66b803050dd63ef77408623fa51b7ae
635,434
def has_test(args): """Returns if some kind of test data is given in args. """ return (args.test_set or args.test_source or args.test_dataset or args.test_stdin or args.test_datasets)
bb773c87f4bc3e046e50a49a1003714fe10a2cf2
635,439
def is_tachycardic(age, heart_rate): """Determines if a given heart rate indicates tachycardia Every time a new heart rate is added to the server, it is necessary to ensure that the given heart rate does not indicate tachycardia in that given patient. This function reads in an age and a heart rate,...
bb7227b3ebcceb014cb064710a23001f3b7e8a50
635,441
def suppress_value(valuein: int, rc: str = "*", upper: int = 100000000) -> str: """ Suppress values less than or equal to 7, round all non-national values. This function suppresses value if it is less than or equal to 7. If value is 0 then it will remain as 0. If value is at national level it will ...
fd453134fe64d913a5c54d34982aa8c4d0c05d69
635,444
from typing import Optional import click def _get_delimiter(item: str) -> Optional[str]: """ Returns the delimiter found in the item if any. It may raises an error if delimiter starts or ends and item or if there is more than one delimiter in the item. :param item: the item to determine delimiters. ...
d7408bf52ac48a595c0f46f53c9c95b11c4cae19
635,449
def _route2url(route): """Convert host from openshift route to https:// url""" return f"https://{route['spec']['host']}"
4690d8900f251e5badf8a742a309d51b576be52b
635,450