content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def argmax(seq, func): """ Return an element with highest func(seq[i]) score; tie goes to first one. >>> argmax(['one', 'to', 'three'], len) 'three' """ return max(seq, key=func)
897dac0d922e369fb14107ef10a14916089d4702
658,808
def get_input_size(dataset_name): """ Returns the size of input """ dataset_name = dataset_name.lower() mapping = { 'mnist': 28 * 28, 'adult': 6, 'pums': 4, 'power': 8 } if dataset_name not in mapping: err_msg = f"Unknown dataset '{dataset_name}'. Ple...
307843635d264a14c472a09be85a19a7d3bf53be
658,816
def quote(string: str) -> str: """ Wrap a string with quotes iff it contains a space. Used for interacting with command line scripts. :param string: :return: """ if ' ' in string: return '"' + string + '"' return string
460b394ddc3223bf3ff7b6fc9b7893802fd7e1b9
658,817
import math def dunn_individual_word(total_words_in_corpus_1, total_words_in_corpus_2, count_of_word_in_corpus_1, count_of_word_in_corpus_2): """ applies Dunning log likelihood to compare individual word in two counter objects :pa...
54594190fa72c5a410fbb128b29ca08a9d9f5031
658,821
def evg_project_str(version): """Return the evergreen project name for the given version.""" return 'mongodb-mongo-v{}.{}'.format(version.major, version.minor)
39aa0021bec397b6a340ce9c2f755f6d4cebf28b
658,822
def rdkitSubstrMatches(targetRdkitMol, refRdkitMol, *args, **kwargs): """ Matches two rdkit mol object graphs with each other. Outputs a list of tuples of corresponding atoms indices. Arguments: ---------- targetRdkitMol : object target rdkit molecule object refRdkitMol : object ...
e443d1060847c17b3033faeb0b373f803c2cb909
658,825
import re def get_jump_pattern(stripped, function_name): """ Return regexp pattern used to identify jump assembly lines. Support for stripped and non-stripped versions. Need to match non-stripped lines: '0x00007ffff7fbf124 <+68>: jmp 0x7ffff7fbf7c2 <test_function+1762>' and stripped lines: ...
642ba2c00fc739f5bc338ad37c481b2056c95412
658,826
def vo_from_fqan(fqan): """ Get the VO from a full FQAN Args: fqan: A single fqans (i.e. /dteam/cern/Role=lcgadmin) Returns: The vo + group (i.e. dteam/cern) """ components = fqan.split('/')[1:] groups = [] for c in components: if c.lower().startswith('role='): ...
eb0b8fed163fd4c49750d71a0a0b568b39525322
658,829
import torch def array_to_tensor(array, device): """Convert numpy array to tensor.""" return torch.FloatTensor(array).to(device)
1ef9df3bdf1a77bcbc846926a28d7ef8fe29315c
658,830
def math_expression_type(text): """ Custom Type which expects a valid math expression :param str text: the text which was matched as math expression :returns: calculated float number from the math expression :rtype: float """ return float(eval(text))
81d038bce4c39add28b24a690b7e55b3dd2e7b2f
658,831
def overlaps(region_1, region_2): """ Find if two regions overlaps a region is defined as dictionary with chromosome/contig, start- and end position given Args: region_1/region_2(dict): dictionary holding region information Returns: overlapping(bool)...
0ec48814f9200666db82bba29ff2de7915e7e19f
658,833
def preprocess_prediction_data(data, tokenizer): """ It process the prediction data as the format used as training. Args: data (obj:`List[List[str, str]]`): The prediction data whose each element is a text pair. Each text will be tokenized by jieba.lcut() function. ...
8389ef9e6d69ebfa976d7763c8d358a850746959
658,839
def _himmelblau(coord): """See https://en.wikipedia.org/wiki/Himmelblau%27s_function.""" x, y = coord[..., 0], coord[..., 1] return (x**2 + y - 11)**2 + (x + y**2 - 7)**2
314168360f6a2bfafe4fe15aff37e82b3eaea7f9
658,843
def approx_Q_top(A, B, T, sigma=1, C=None): """ Approximate expression for the (a)symmetric top partition function. The expression is adapted from Gordy and Cook, p.g. 57 equation 3.68. By default, the prolate top is used if the C constant is not specified, where B = C. Oblate case can also be specified...
d79c6dbf4cb00db05279bcf7d4cd4eb2bb9edcb4
658,844
def check_items_exist(res) -> bool: """Checks whether any product returned.""" return True if len(res['hits']['hits']) > 0 else False
f5adc0b88570b728571551fa4dc111d4fc72246c
658,847
import re def obj_check_attr(obj, attr, dict): """ Return True/False if attr (namespace/scene) is to be included in import/export obj: Namespace or Scene object attr: Which attribute to check ('namespace' or 'scene') dict: Dictionary of namespace or scene from config """ if obj[attr] in di...
af8c874da41ceaa94da260c4cccca0b84383da4d
658,848
def classes(*names, convert_underscores=True, **names_and_bools): """Join multiple class names with spaces between them. Example ------- >>> classes("foo", "bar", baz=False, boz=True, long_name=True) "foo bar boz long-name" Or, if you want to keep the underscores: >>> classes("foo", "bar...
5054c2973d3495c6796974fae13f06832d1eae51
658,852
def format_image_results(registry_response_dict): """ Response attribute content is formatted correctly for the Images :param response: response object with content attribute :return: dict of various images """ if not isinstance(registry_response_dict, dict): raise TypeError('registry_r...
141c5d6cae8d7d7dbfa1051ac9fd4927f2a47fe3
658,860
def datetime_to_int(datetime): """Convert datetime to 17 digit integer with millisecond precision.""" template = ( '{year:04d}' '{month:02d}' '{day:02d}' '{hour:02d}' '{minute:02d}' '{second:02d}' '{millisecond:03d}' ) priority = int( templ...
ded2579fd21f3c0a3c7639e3654757a389b994a1
658,862
def ComputeLabelX(Array): """Compute label x coordinate""" X = min(Array)+ (max(Array)-min(Array))/2 return X
4e8e3fa5ab4558e6c2762caa025566e75805cdc6
658,864
def str2re(s): """Make re specific characters immune to re.compile. """ for c in '.()*+?$^\\': s = s.replace(c, '['+c+']') return s
d22ee77640a34ae7aa43d913edc8132ab20452b1
658,865
def int_to_bytes(x): """ 32 bit int to big-endian 4 byte conversion. """ assert x < 2 ** 32 and x >= -(2 ** 32) return [(x >> 8 * i) % 256 for i in (3, 2, 1, 0)]
954112ca5ef4b48f1563cdff12eb5699e1609d14
658,867
import imp import unittest def skipIfModuleNotInstalled(*modules): """Skipping test decorator - skips test if import of module fails.""" try: for module in modules: imp.find_module(module) return lambda func: func except ImportError: return unittest.skip("Test skipp...
97171016735c54336602282878d9052f1091b2e1
658,871
def voter_address_retrieve_doc_template_values(url_root): """ Show documentation about voterAddressRetrieve """ required_query_parameter_list = [ { 'name': 'api_key', 'value': 'string (from post, cookie, or get (in that order))', # boolean, integer, long, ...
29c57a36f3be535cd6c79de2508102693478f239
658,872
def _arrow_to_numpy(arrow_table, schema): """Helper function that converts an Arrow Table to a dictionary containing NumPy arrays. The memory buffers backing the given Arrow Table may be destroyed after conversion if the resulting Numpy array(s) is not a view on the Arrow data. See https://arrow.ap...
ff2de73450162c66fb690162eee18360ee835f47
658,873
def delay_feedback_gain_for_t60(delay_samp, fs, t60): """ Calculate the gain needed in a feedback delay line to achieve a desired T60 Parameters ---------- delay_samp : int The delay length in samples fs : float Sample rate t60 : float The desired T60 [seconds] ...
281eacb60e453dd2c38b94d0a6446ea4093974c3
658,875
def get_test_mode_user(prefix='', rconn=None): """Return user_id of test mode, or None if not found""" if rconn is None: return try: test_user_id = int(rconn.get(prefix+'test_mode').decode('utf-8')) except: return return test_user_id
894f8c1eeff85471864876491acad5ac59f9781a
658,876
def query_create_fact_table() -> str: """[this returns the query used for creating fact table. It uses the immigration and temperature tables' view.] Returns: str: [query to extract fact table.] """ # defining query for creating fact table by joining temperature and immigration data query =...
36a5ba7f305d4695f479191684a8b34b14f80459
658,883
import shutil def get_free_space_bytes(folder): """ Return folder/drive free space (in bytes) """ try: total, _, free = shutil.disk_usage(folder) return total, free except: return 0, 0
5ae19815e953ba25053a7f9236b4e5c1f86d4875
658,884
def filter_df(df,col,word): """Filters out any entries that do not have word(string regex) in the columns specified (col)""" return df[df[col].str.contains(word,na=False)]
327eea8c751db9021e89c4a038ddef06af0f9e6e
658,889
def difference(list_1, list_2): """ Deterministically find the difference between two lists Returns the elements in `list_1` that are not in `list_2`. Behaves deterministically, whereas set difference does not. Computational cost is O(max(l1, l2)), where l1 and l2 are len(list_1) and len(list_2), respe...
4b263ac97a203f2fc148b5b178e2d14c456b1bf7
658,890
def scale_dimensions(width, height, longest_side): """ Calculates image ratio given a longest side returns a tupple with ajusted width, height @param width: integer, the current width of the image @param height: integer, the current height of the image @param longest_side: the longest side of t...
957a87747476bdf4325edad786a99f05a27917d3
658,896
def xorNA(x): """Return x if x is not None, or return 'NA'.""" return str(x) if x is not None else 'NA'
9df8db1bfe91ffdc8795d2886b4823a3f6840b07
658,897
def update_dcid(dcid, prop, val): """Given a dcid and pv, update the dcid to include the pv. Args: dcid: current dcid prop: the property of the value to add to the dcid val: the value to add to the dcid Returns: updated dcid as a string """ val_dcid = val.split(":")[-...
c61136ee6e93a73ea269396fb0f71fd3d161b101
658,899
def genderint_to_string(dataframe, gender_integer_map): """Transforms gender encoded as an integer to a string INPUT: dataframe: DataFrame that includes gender encoded as an integer gender_integer_map: Dictionary that describes the mapping of a ...
3c64f862e5418aed6850cb232d95611dec6b7eb3
658,900
def _create_index_for_annotation_row(row): """Parse the row from annotation file to get chrom and positions. Parameters ---------- row: pd.DataFrame row Row of annotation dataframe Returns ------- index: array_like Array of 1-based positions on chromosome """ co...
e76c38a62fa3e237acfa97092f182739244d6081
658,904
def to_list(obj): """Convert a list-like object to a list. >>> to_list([1, 2, 3]) [1, 2, 3] >>> to_list("a,b,c") ['a', 'b', 'c'] >>> to_list("item") ['item'] >>> to_list(None) [] """ if isinstance(obj, (list, tuple)): return obj elif isinstance(obj, str): ...
8c24c7bd3dae4eca58dae03fa60e3b4f204f7bbb
658,906
def stock_payoff(S,PP): """This function takes Spot price range(S), and purchase price(PP) of the stock as inputs and returns stock payoff """ return (S-PP)
199d492d98d47f457de8ef41b2c910aa3fcbdb58
658,907
import math def log(a,b): """ Returns the logarithm of a to the base b. """ return math.log(a,b)
c0f139d9881a80d78abf427d1ca33e7d611c7a10
658,908
def get_max_score(scores): """ gets maximum score from a dictionary """ max_value = 0 max_id = -1 for i in scores.keys(): if scores[i] > max_value: max_value = scores[i] max_id = i return max_id
93a70e6ec5c002617aed96f588b9d36a7471799e
658,909
def select_files(flist, pattern): """ Remove fnames from flist that do not contain 'pattern'. """ return [fname for fname in flist if pattern in fname]
797cc2f0ff27f1527cf37581d03aa43d1d39808f
658,910
import logging def _build_stream_formatter() -> logging.Formatter: """Default formatter for log messages. Add timestamps to log messages.""" return logging.Formatter( fmt="[%(levelname)s %(asctime)s] %(output_name)s: %(message)s", datefmt="%m-%d %H:%M:%S", )
7d004696fd1db895f843cc02c6d885f90c2a99c0
658,923
import math def tdewpoint_from_relhum(t, h): """Compute the Dewpoint temperature. Parameters ---------- t: array temperature [C]. h : array relative humidity [%]. Returns ------- array Dewpoint temperature at current timestep. Example ------- tdewpoint_from_relhum(20,50) == 9.27...
d8a6212f44dd1dd602908bfd00d9fa2a7559b912
658,924
def label_seq(data): """ Input: data: dictionary of text, begin_sentences, end_sentences Output: a sequence of labels where each token from the text is assiciated with a label: regular token --> O begin sentences token --> BS end sentences token --> ES ...
aebfe545599f185f09f342f4bef622453db3115f
658,932
import inspect def get_classes_in(__module, predicate=None, return_name=False): """Gets all class symbols stored within a Python module. :param __module: The module to get the classes from. :type __module: :class:`types.ModuleType` :param predicate: A callable to pass to inspect.getmembers to filter ...
4405687d254878e83ae1d68dce34867beeabb713
658,934
def data_storage_account_settings(conf): # type: (dict) -> str """Retrieve input data storage account settings link :param dict conf: configuration object :rtype: str :return: storage account link """ return conf['storage_account_settings']
91ff0d940daf60f6a6880eba31db12828f6af058
658,935
def from_datastore(entity): """Translates Datastore results into the format expected by the application. Datastore typically returns: [Entity{key: (kind, id), prop: val, ...}] This returns: {id: id, prop: val, ...} """ if not entity: return None if isinstance(entity...
d2db543cfd918488f6da795a7858f96e5cd061c8
658,937
def calc_gsd_cross(altitude, focal_length, pixel_dim_cross): """ ground sample distance (gsd) is the distance between pixel centers measured on the ground. https://en.wikipedia.org/wiki/Ground_sample_distance Returns ------- double : meters per pixel ...
97dbb18341684d4727e31378343896a2c6e6e47b
658,939
def set_lat_lon_attrs(ds): """ Set CF latitude and longitude attributes""" ds["lon"] = ds.lon.assign_attrs({ 'axis' : 'X', 'long_name' : 'longitude', 'standard_name' : 'longitude', 'stored_direction' : 'increasing', 'type' : 'double', 'units' : 'degrees_east', ...
fe95bbd7bd698b7cc0d5d1a60713477ab36e909a
658,940
def afill(start, end, ntries): """A function that fill evenly spaced values between two numbers""" step = (end-start)/float(ntries+1) if ntries > 0 else 0 final_list = [float(start) + (i+1)*step for i in range(ntries)] return(final_list)
32d66e2fa01dd8750ffefc52d82c86696f4336dd
658,942
def overwrite_tags_with_parameters(tagged_lines,parameter_strings): """ Takes tagged lines and the respective options and creates a valid Python source file. ---Inputs--- tagged_lines : {list} list of all lines making up the tagged source code of the user's solver (all lines included...
b22b8d2de1f10e70e9ac2758b31b75f0e11a8e6a
658,944
from datetime import datetime def to_epoch(ogtime): """Convert formatted time to Unix/epoch time.""" fstr = '%Y-%m-%dT%H:%M:%S.%fZ' epoch = datetime(1970, 1, 1) finaltime = (datetime.strptime(ogtime, fstr) - epoch).total_seconds() return finaltime
0d4714dd15296d677f60f5f24b077d6991597f72
658,946
def fetch(field, *source_records, **kwds): """Return the value from the first record in the arguments that contains the specified field. If no record in the chain contains that field, return the default value. The default value is specified by the "default" keyword argument or None. If keyword argument ...
e177e703462e4c67d78bc524a23cccd767140b3f
658,954
import re def truncate_html_words(s, num, end_text='...'): """Truncates HTML to a certain number of words. (not counting tags and comments). Closes opened tags if they were correctly closed in the given html. Takes an optional argument of what should be used to notify that the string has been truncat...
6995b4bce78670884508e08521da78d2d88fd5bc
658,957
def Square(x, a, b, c): """Second order polynomial Inputs: ------- ``x``: independent variable ``a``: coefficient of the second-order term ``b``: coefficient of the first-order term ``c``: additive constant Formula: -------- ``a*x^2 + b*x + c`` """ r...
5180bc3769d331c04b384bf5c5cb1bf65bf71b0a
658,958
def insert_row(table_name, values): """Inserts a row in 'table_name' with values as 'values'""" query = f'INSERT INTO {table_name} VALUES (' no_attrs = len(values) # Add values to query for i in range(0, no_attrs - 1): query += f'{values[i]}, ' # Add semicolon for last value query...
9f0bde3aeddbbe0bbd33ac04a9dedfab7faae17d
658,961
def rank_models(ckpt_path2dfs, metric, maximize_metric): """Rank models according to the specified metric. Args: ckpt_path2dfs (dict): mapping from ckpt_path (str) to (pred_df, gt_df) metric (function): metric to be optimized, computed over two DataFrames, namely the predictions and...
ca5857685c382e10de1a0781d82baf76bc468457
658,962
import six def convert_to_unicode(text): """Converts `text` to Unicode (if it's not already), assuming utf-8 input.""" if six.PY3: if isinstance(text, str): return text elif isinstance(text, bytes): return text.decode("utf-8", "ignore") else: raise V...
8e587d7e28e17c3883fe9077bcf9984dbc17e8d4
658,963
def assemble_replace_dict(command, use_gpu, additions, queue, time, ngpu): """Create dictionary to update BASH submission script for torque. Parameters ---------- command : type Command to executer through torque. use_gpu : type GPUs needed? additions : type Additional c...
63665247b592210fe15f027cbb171475278094cd
658,966
def _annotate_table(data_table, keyword_dict, num_sources, product="tdp"): """Add state metadata to the output source catalog Parameters ---------- data_table : QTable Table of source properties keyword_dict : dict Dictionary containing FITS keyword values pertaining to the data pr...
3b9221a24d83e9e9c3473e05a7db20f96c84c4f0
658,968
import itertools def cycle(collection): """:yaql:cycle Makes an iterator returning elements from the collection as if it cycled. :signature: collection.cycle() :receiverArg collection: value to be cycled :argType collection: iterable :returnType: iterator .. code:: yaql> [1, 2]...
b2e7b60d2e6bef14a42c675fa59ce692d4d75ab7
658,970
def boolean_content_matcher(string_array: str, substring: str): """Returns a list of tuples containing True/False if the substring is found in each element in the array. Examples: >>> text_list = ['lambda functions are anonymous functions.', ... 'anonymous functions dont have a name.', ...
1de5e5d81f5b88f0283ff2931de464b10df4c009
658,974
import requests def perform_post_request(session, url, data=None, headers=None, encoding=None): """ Performs post request. :param session: `Request` session :param url: URL for `Request` object :param data: (optional) Dictionary, list of tuples, bytes, or file-like object to send in the bod...
db5d934cdf7930cd66b90ce161ce4ad4b9344256
658,977
def apply_first(seq): """Call the first item in a sequence with the remaining sequence as positional arguments.""" f, *args = seq return f(*args)
0f7353b66ea677e4b4090dc2824556952daaa7c9
658,980
import warnings def multichain(self, *others): """Makes self inherit from multiple prototypes. Any relationship with previous parent prototypes will be removed. When the parent prototypes share attributes with the same name, the parent prototype that is first in the list of prototypes will provid...
6cb784493677d8603d52a0d2cb96b31795b6ebb9
658,982
from typing import List def _transform_body_for_vscode(body: str) -> List[str]: """snippetのbodyをvscode用に変換する. 改行区切りのlist, space4つをtabに変換. :param body: string of a snippet body :return body_for_vscode: vscode-snippet形式のbody """ body_list = body.split('\n') body_for_vscode = [b.replace(' ...
1261efcedb87848fdfd9fee3ebed36c956db0019
658,983
def name_eq(name): """add a 'name' attribute (a string most likely) to a function""" def wrapper(f): f.name = name return f return wrapper
a95fe0f0c3c8fb2dd097086af216e3c27e1a473c
658,985
def get_voc_abb(vocation: str) -> str: """Given a vocation name, it returns an abbreviated string""" vocation = str(vocation) abbrev = {'none': 'N', 'druid': 'D', 'sorcerer': 'S', 'paladin': 'P', 'knight': 'K', 'elder druid': 'ED', 'master sorcerer': 'MS', 'royal paladin': 'RP', 'elite knight'...
5ef42ed160fc8b1ba39e2ee47fe9bb52d46acb8a
658,986
def isWikiTable(tag): """Filter for determining if a given element is a WikiMedia table entry """ return tag.name == 'table' and 'class' in tag.attrs and 'wikitable' in tag.attrs['class']
ee89111fed9423f5faf8948de25fa8cb23e70484
658,989
def get_file_contents(filename): """ Given a filename, return the contents of that file """ try: with open(filename, 'r') as f: # It's assumed our file contains a single line, # with our API key return f.read().strip() except FileNotFoundError: ...
9c09c0d705f3fb36e5c687a5dc0a0dbaad9ad8d8
658,990
def close_ring(coordinates): """ Makes sure the ring is closed; if it is not, then closes the ring. :param coordinates: a collection of coordinates representing a polygon :return: a closed ring """ if coordinates[0] != coordinates[-1]: coordinates.append(coordinates[0]) return coord...
8197a1c70b566d69746c2f6ffd2fa756cbf601e5
658,999
def fracval(frac): """Return floating point value from rational.""" if frac.find("/") == -1: return float(frac) else: x = frac.split("/") return float(x[0]) / float(x[1])
4a6161479cd06cc6ebef64a7255d8974fea05ac7
659,008
def is_record(path: str) -> bool: """ Is filename a record file? :param (str) path: User-supplied filename. :return: True if filename is valid record file; otherwise False. :rtype: bool """ return path.find("..") == -1
be4779214518bc22fda8bb304f4b2bcbda56d53d
659,011
def _read_creds( filename: str ) -> tuple: """Read credentials and home latlong from login.conf file.""" creds_dict = {} with open(filename) as f: for line in f: (key, val) = line.split() creds_dict[key] = val return ( creds_dict['email'], creds_dict['password...
b58d31cfa79d91c294540d26ef29c52ea05c203e
659,018
def count_neighbors_wrap_around(grid2count, posInRow, posInCol, row_Count, col_Count): """returns number of ALIVE neighbors from a given position on a given grid using wrap around approach""" count = 0 for x in range(-1, 2): for y in range(-1, 2): if grid2count[(posInRow + x) % row_Coun...
524947c49cdbb56bbf7067057afa81a00099f765
659,020
from typing import Sequence from typing import Optional from typing import List def build_tree( tree_structure: Sequence, multiline_pad: int = 1, pad_depth: Optional[List[int]] = None, _indent_data: Optional[list] = None, ) -> str: """ Build a tree graph from a nested list. Each item in t...
381ab26c517aa49e18e3e1b7de989ce98453924f
659,023
import re def add_pre_main_init(startup: str) -> str: """Add pw_stm32cube_Init call to startup file The stm32cube startup files directly call main(), while pigweed expects to do some setup before main is called. This could include sys_io or system clock initialization. This adds a call to `pw_st...
489272ae676a2edcb80e6e08246c5b25a4952b79
659,027
from typing import List def open_uniform_knot_vector(count: int, order: int, normalize=False) -> List[ float]: """ Returns an open (clamped) uniform knot vector for a B-spline of `order` and `count` control points. `order` = degree + 1 Args: count: count of control points order: ...
4dba197dfd9714d9354fcd40469b92200f99b3b5
659,028
def getsymbol(tree): """Get symbol name from valid ``symbol`` in ``tree`` This assumes that ``tree`` is already examined by ``isvalidsymbol``. """ return tree[1]
36b4d038370bac45b89934ae1b80418da48384a0
659,029
def __reconstruct_spectrum(theta, sig_matrix): """ Reconstruct the spectrum using the estimated mixture proportions of the reference signatures and the signature matrix. :param theta: estimated mixture proportions (numpy.array) :param sig_matrix: The matrix containing the weights of each mutational ty...
c3f40ac2a80e135ffba93800d5d420a7a05b1662
659,030
def unlock(server_id, **kwargs): """Unlock server.""" url = '/servers/{server_id}/action'.format(server_id=server_id) req = {"unlock": None} return url, {"json": req}
e98dde30943c12ca390e4f7a099e24d6e4a0a66f
659,031
import re def mk_rule_fn(rule, name): """Test helper for converting camelCase names to underscore_function_names and returning a callable rule fn.""" parts = re.sub('(?!^)([A-Z][a-z]+)', r' \1', name).split() parts.insert(0, 'with') fn_name = '_'.join(map(lambda x: x.lower(), parts)) retur...
e6ba5e1c409077911e2b67878dba078dc2890c38
659,032
def _ParseTaskId(task_id): """Parses a command ID from a task ID. Args: task_id: a task ID. Returns: (request_id, command_id) """ if task_id is None: raise ValueError("task_id cannot be None") ids = task_id.split("-", 2) if len(ids) == 3: return ids[0], ids[1] return None, ids[0]
7de34c957ffcbb6e549ea7a301aee66f1241fa3a
659,034
from bs4 import BeautifulSoup def get_wiki_from_spotlight_by_name(spotlight, name): """Given the spotlight output, and a name string, e.g. 'hong kong' returns the wikipedia tag assigned by spotlight, if it exists, else '-'.""" actual_found = 0 parsed_spotlight = BeautifulSoup(spotlight.text, 'lxml') ...
911538367813fa6e80cd73c35f744d1055390248
659,040
def twos_complement(n: int, w: int = 16) -> int: """Two's complement integer conversion.""" # Adapted from: https://stackoverflow.com/a/33716541. if n & (1 << (w - 1)): n = n - (1 << w) return n
859c925fbaf642d9365680230bd7b297f64d4c7a
659,043
def get_end_index_of_a_paragraph_from_string(text, start=0): """ :param text: a string :param start: the index of the start position :return: the index of the new line character or the last character """ return min(len(text) - 1, text.find('\n', start))
25d0918749477029b2103b560be3d2556a9bb2ac
659,049
def assign_labels_colors(labels, colors): """ Takes a list of labels and colors and assigns a unique label to each color. Returns a color_list of length(labels). The colors will loop around if the number of unique labels are more than the number of unique colors :param labels: :param colors: :re...
79984b3de57a7c5782282f30a87564dd139a346f
659,051
from typing import Union from pathlib import Path def path_resolver(f: Union[str, Path], *, touch: bool = True) -> Path: """Resolve a path. Parameters ---------- f : Union[str, Path] File whose path needs to be resolved. touch : bool Create file is not already existent. Default: T...
df3caefaec5ded71658f0f99686008e2a1a27272
659,052
def format_timestamp(time_stamp): """Create a consistent datetime string representation based on ISO 8601 format. YYYY-MM-DDTHH:MM:SS.mmmmmm for unaware datetime objects. YYYY-MM-DDTHH:MM:SS.mmmmmm+HH:MM for aware datetime objects :param time_stamp: value to convert :type time_stamp: datet...
eec7386c898da42bfee9e22d19f015ba1ce398b3
659,055
import hashlib def get_sha1_hash(password): """For a given password string, utf-8 encode it and hash it with SHA1.""" encoded = password.encode('utf8') hashed = hashlib.sha1(encoded).hexdigest() return hashed
a7155cd1da31930fbc2f7a24875b75f3b444354c
659,059
import json def read_lane_stats( lane_file ): """ Read RUN001_Lxxx.stats.json file created in bbi-sciatac-demux pipeline run. These files are in the demux_out/fastqs_barcode directory. The run is always RUN001 and the Lxxx denotes the results for each lane; that is, L001, ... """ lane_stats = json.load( l...
be161f2c64f87a22092b6528928053f89b0d8f93
659,062
def mysql_old_passwd(password, uppercase=True): # prior to version '4.1' """ Reference(s): http://www.sfr-fresh.com/unix/privat/tpop3d-1.5.5.tar.gz:a/tpop3d-1.5.5/password.c http://voidnetwork.org/5ynL0rd/darkc0de/python_script/darkMySQLi.html >>> mysql_old_passwd(password='testpass', uppe...
bdc589d119193ec03f3152d6e65b0ec241528eca
659,065
def key(name): """Extracts the filename key.""" dot = name.rfind(".") if -1 != dot: return name[0:dot] return ""
22e52edec1e3ea4a021881da1085f8d812ab59bf
659,066
def test_names_list(test_suite): """Build a list containing all the test names of a test suite.""" test_names = [] for test in test_suite.test_cases(): test_names.append(test.description) return test_names
3418cf021cb9c1de1ef0f2b007de4ee6efbd9d8f
659,083
def model_device(model): """Determine the device the model is allocated on.""" # Source: https://discuss.pytorch.org/t/how-to-check-if-model-is-on-cuda/180 if next(model.parameters()).is_cuda: return 'cuda' return 'cpu'
a827a48a5f71bf0a6a3f264de6016248f0a1f0ce
659,089
import math def binomial_coefficient(n: int, k: int) -> int: """Calculate Binomial coefficient""" n_fac = math.factorial(n) k_fac = math.factorial(k) n_minus_k_fac = math.factorial(n - k) return round(n_fac/(k_fac*n_minus_k_fac))
b15da267b67d09df0fd93ac65d088ee739a0d9c0
659,091
import string import random def randstr(nchars=10): """Creates a random string identifier with the given number of chars""" chars = string.ascii_letters + string.digits ret = ''.join([random.choice(chars) for i in range(nchars)]) return ret
7576805a9f3474758ae1237c6efea14ef90bfff8
659,092
def _format_function(func_name): """Provide better context for a "function" of the caller. """ if func_name is None: return "" elif func_name == "<module>": return " (top level stmt)" else: return " in " + func_name
c4699a2e2e49f461f469a85f1af85fffc408d104
659,100
def reformat_tract_code(tract: str, state_code: str, county_code: str) -> str: """Helper function to return GEOIDs compatible with those in deep-dive data files. Parameters ---------- tract : A string An unformatted tract code, e.g. '53.38' state_code : A string The FIPS code for th...
4b96694b47e91f3d400f7987ee690b7af0fb9573
659,101
def _safe_mesos_dns_taskname(task_name): """Converts a potentially slash-delimited task name to one that works for '.mesos' task names Mesos DNS task names handle folders like this: /path/to/myservice => myservice-to-path""" elems = task_name.strip("/").split("/") elems.reverse() return "-".join(ele...
71189da614287f835448be4709c9e120ba16e725
659,105