content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import operator
def map_method(*args, **kwargs):
"""
Given a method name and a sequence of models, return a sequence of values
of applying the extra positional and keyword arguments in each method.
Attr:
attr:
Method name. Dotted python names are valid.
models:
... | aa2ab34f729c41376e30c9a9b8c6536e14ba8be4 | 694,023 |
def get_cell_genes(cur,cell):
"""
Return the genes expressed in cell
Parameters
----------
cur : MySQLdb cursor
cell : str
Name of cell
"""
sql = ("select genename from WB.association "
"join WB.cells on "
"WB.association.idcell = WB.cells.idcells "
... | 03550cc6a8645b49c86d280d17032b05102b88d3 | 694,027 |
import torch
def test(model, test_loader, device=torch.device("cpu")):
"""Checks the validation accuracy of the model.
Cuts off at 512 samples for simplicity.
"""
model.eval()
correct = 0
total = 0
with torch.no_grad():
for batch_idx, (data, target) in enumerate(test_loader):
... | 2df49a192c144a9300b5cd218b347a55f79da467 | 694,032 |
def isGlideinHeldNTimes(jobInfo, factoryConfig=None, n=20):
"""This function looks at the glidein job's information and returns if the
CondorG job is held for more than N(defaults to 20) iterations
This is useful to remove Unrecoverable glidein (CondorG job) with forcex option.
Args:
jobInfo (... | e608ada46f1571b9e96531bc3cca3692f940846a | 694,035 |
import re
def prepare_whitelist(patterns):
"""Join and compile the re patterns.
Args:
patterns: regex patterns.
Return:
A compiled re object
"""
return re.compile('|'.join(patterns)) | 5c1eb91c2aa534af6b8ff5cc4165095a5eb577e7 | 694,038 |
def _GetVersionIndex(version_str):
"""Returns the version index from ycsb version string.
Args:
version_str: ycsb version string with format '0.<version index>.0'.
Returns:
(int) version index.
"""
return int(version_str.split('.')[1]) | 9c415a55a97adedb6bbc5576d7147d2164651d4e | 694,041 |
import re
def parse_ping_output(ping_output):
"""Parse ping output.
Returns a tuple with the number of packets sent and the percentage of
packet loss from a ping output."""
match = re.search(
'(\d*) packets transmitted, .* ([\d\.]*)\% packet loss',
ping_output)
return match.groups... | e3af78babdbd21dd6369f18de150a9d453fe7d21 | 694,042 |
def is_transform(str_in):
"""Determines if str_in is the name of a transformation file
"""
return '.ima' in str_in \
or '.trm' in str_in | c7f65ac6c86776c640a0027c94b0cee5afdd8cfb | 694,045 |
def process_resize_value(resize_spec):
"""Helper method to process input resize spec.
Args:
resize_spec: Either None, a python scalar, or a sequence with length <=2.
Each value in the sequence should be a python integer.
Returns:
None if input size is not valid, or 2-tuple of (height, width), deri... | 2850b1f86a62cb35611bcb89a543bb35eb8226bf | 694,046 |
def split_wrap(sql):
"""Split with \n, and strip the ' '. """
sql_list = sql.split('\n')
if sql_list[0] == '':
del sql_list[0]
if sql_list[-1] == '':
del sql_list[-1]
sql_list = list(map(lambda x: x.strip(), sql_list))
return sql_list | 7d8639b99219226b5a29da204a1c7fd8f71acc0e | 694,050 |
def fastpath_dup_rid_input(app):
"""
Access DB directly. Fetch > 1 measurements from fastpath that share the same
report_id and input
Returns (rid, input, count)
"""
sql = """
SELECT report_id, input,
from fastpath
group by report_id, input
HAVING count(*) > 1
LIMIT 1
"""... | a09e82cd84483c21722a197ab8f5becae2c1d5a6 | 694,051 |
def get_BM_data(filename):
"""Read the contents of the given file. Assumes the file
in a comma-separated format, with 6 elements in each entry:
0. Name (string), 1. Gender (string), 2. Age (int)
3. Division (int), 4. Country (string), 5. Overall time (float)
Returns: dict containing a list for e... | c3dce697ed850ed422a5d60fbd08310f04461a82 | 694,052 |
def build_B_spline_higher_degree_basis_fns(
breaks, prev_degree_coefs, degree, x):
"""Build the higer order B spline basis coefficients
N_{i,p}(x) = ((x-u_i)/(u_{i+p}-u_i))N_{i,p-1}(x) \
+ ((u_{i+p+1}-x)/(u_{i+p+1}-u_{i+1}))N_{i+1,p-1}(x)
"""
assert degree > 0
coefs = []
f... | a8b732ce519a608ea277aa1c1165be8d674e141b | 694,054 |
def circular_distance(a: int, b: int, C: int) -> int:
"""
Finds the shortest distance between two points along the perimeter of a circle.
arguments:
a: a point on a circle's circumference.
b: another point on the cicrle.
C: the total circumference of the circle.
return:
... | 1b1a54dca54edc18ef4c44a9e54f883410fb7c8f | 694,056 |
def get_proxy_list_size(proxy_list):
""" Return the current Queue size holding a list of proxy ip:ports """
return proxy_list.qsize() | 982240d8225f7c79327c661c91d6741311c1dd4e | 694,058 |
def find_toolchain(ctx):
"""Finds the first rust toolchain that is configured.
Args:
ctx (ctx): The ctx object for the current target.
Returns:
rust_toolchain: A Rust toolchain context.
"""
return ctx.toolchains["@io_bazel_rules_rust//rust:toolchain"] | 2c003b40529dec403c17cf02d7bf97f0e1d427fa | 694,059 |
def apply_function(funct, value, iterations):
"""
Example of a function that takes another function as an argument
"""
for index in range(iterations):
value = funct(value)
return value | 65836cb9b76adeb43c6e92bdc72c15d49ebf4b01 | 694,061 |
import errno
def _is_error(self, exception, *errors):
""" Determine if an exception belongs to one of the given named errno module errors. """
errors = [ getattr(errno, error, None) for error in errors ]
return exception.errno in errors | c1aab4862b721f83986b70d96a9906089c44bf5b | 694,068 |
from uuid import uuid4
def create_tmp_name(base=None):
"""Create temporary name using uuid"""
return (base + '_' if base else '') + uuid4().hex[:10] | 041e5d889029be49c50b5597166b94e1234e2c9f | 694,069 |
def _split_dataset_id(dataset_id):
"""splits a dataset id into list of values."""
return dataset_id.split("|")[0].split(".") + [(dataset_id.split("|")[1])] | 9a1c3d23af502fd21db3de9485cfcdb75d84ba6d | 694,076 |
def validate_string(str_argument, str_argument_name):
""" Validates if the given argument is of type string and returns it"""
if not isinstance(str_argument, str):
raise ValueError(f"Illegal str argument: {str_argument_name}")
return str_argument | f1e9dbcbd539aab411c4e2c134259694a8dc597b | 694,084 |
import json
def is_json(string):
"""
Helper function to determine if a string is valid JSON
"""
try:
json_object = json.loads(string)
except ValueError as e:
return False
return True | b3c70037555a38bb1e64452ab42d2e174b3be893 | 694,089 |
def uint32_tag(name, value):
"""Create a DMAP tag with uint32 data."""
return name.encode('utf-8') + \
b'\x00\x00\x00\x04' + \
value.to_bytes(4, byteorder='big') | 2842aee121d1217e2829705135fbff655ea02ab7 | 694,090 |
def get_average_mos(solution, ignore_non_served=False):
"""Returns the average MOS of a solution.
"""
smos = 0
nserved = 0
for u in solution["users"]:
if "mos" in u:
smos += u["mos"]
nserved += 1
if ignore_non_served:
# only take into account users that get some video
return smos/nse... | e75a4e7be7012e4a12dfc127119f7c2b4fc1bbb0 | 694,096 |
def clamp(value, minimum, maximum):
"""
Return clamped value between minimum and maximum.
:param float value:
:param float minimum:
:param float maximum:
"""
if maximum < minimum:
raise ValueError(f"{maximum} is smaller than {minimum}")
return max(minimum, min(value, maximum)) | de32469ad3f7b9c772ccb870a9d16520bc59f481 | 694,098 |
import getpass
def password(what):
"""Prompt the user for a password and verify it.
If password and verify don't match the user is prompted again
Args:
what (string) : What password to enter
Returns:
(string) : Password
"""
while True:
pass_ = getpass.getpass("{} Pas... | bf2328d709490333cbc68c2620ee3d0dc087e6e2 | 694,103 |
def checkListAgainstDictKeys(theList, theDict):
"""
Given a list of items, remove any items not in specified dict
:param theList: list, list of items that may not be in theDict
:param theDict: dict, dictionary against which to check (the keys)
:return:
inlist, list, items from list found in dict keys
... | 4274c48cc9e85d4632a3591e4ae1e4ecd7c236c8 | 694,104 |
def title(txt):
""" Provide nice title for parameterized testing."""
return str(txt).split('.')[-1].replace("'", '').replace('>', '') | 06104d59d4ef4770cba4e4951a4be7c1f425890c | 694,106 |
import collections
def convert_defaultdict_to_regular_dict(inputdict: dict):
"""
Recursively convert defaultdict to dict.
"""
if isinstance(inputdict, collections.defaultdict):
inputdict = {
key: convert_defaultdict_to_regular_dict(value)
for key, value in inputdict.ite... | 17d56b3ae8db0fb91bdb086b953f405a35741b4f | 694,107 |
def get_mung_locs(anc, code, output_bucket):
""" Convenience function to obtain the expected locations for munged scripts.
Parameters
----------
anc : :obj:`str`
Ancestry prefix.
code : :obj:`str`
Phenotype code.
output_bucket : :obj:`str`
The bucket in which the mugning... | b5b4d65040229797e37568ae57659aa575887bd4 | 694,110 |
def extend_empty_sets(empty: dict, grammar: dict) -> dict:
"""
Determine which nonterminals of an LL(1) grammar can be empty.
Must be applied repeatedly until converging.
:param empty: nonterminal -> bool
:param grammar: nonterminal -> [productions...]
:returns: Extended copy of ``empty``
"... | a91b18b217d3c8fee7ef86b0eba2d2bd92422ca5 | 694,111 |
import json
def json_read(path):
"""
Reads JSON file from the given path.
"""
with open(path, mode="r", encoding="utf-8") as file:
res = json.load(file)
return res | a3be51d57501a3d7833398b1763b024ba6a2f215 | 694,115 |
def cycle(counter, rule):
"""Returns True when a given forloop.counter is conforming to the
specified `rule`. The rules are given as strings using the syntax
"{step}/{scale}", for example:
* ``forloop.counter|cycle:"1/2"`` returns True for even values
* ``forloop.counter|cycle:"2/2"`` returns True ... | 0f0da401539bd97c8441f395b2bbd1962facf7cb | 694,116 |
import hashlib
def get_hash(content):
"""Return the hex SHA-1 hash of the given content."""
return hashlib.sha1(content).hexdigest() | 8b202cdffe035d039651c18b780ae0c901a7b8f1 | 694,118 |
def model_auth_fixture() -> dict:
"""Function to generate an auth dictionary with identical keys to those
returned from a get model request.
Returns:
dict: Mock auth dictionary
"""
auth = {
"asset_id": "0a0a0a0a-0a00-0a00-a000-0a0a0000000a",
"reason": "reason for access",
... | 56a05a135005b8d551a51f90f3bdef0bff672f72 | 694,121 |
def _get_secondary_status(row):
"""Get package secondary status."""
try:
return row.find('div', {'id': 'coltextR3'}).contents[1]
except (AttributeError, IndexError):
return None | faa2f280e978c574280e610453ceba6116931c41 | 694,126 |
def get_treetagger_triple(string):
"""
Split a single line from TreeTagger's output to obtain a
(word,pos,lemma) triple.
"""
elems = string.split('\t')
# Lines that don't contain exactly 2 tabs are ignored. These are
# usually lines containing a single <repdns> or <repurl> element
#... | 292abdae3b7ac1b13ffb68e5bd86ac625b9c3c03 | 694,129 |
def _basename_of_variable(varname):
"""Get the base name of a variable, without the time index.
Given a variable "FooBar_10", the last component is the time index (if present),
so we want to strip the "_10". This does no error checking. You should not be
passing in a variable whose name starts wi... | 29e36a160e6885ce4a1e6bbe9d0ebdd038574443 | 694,130 |
import time
def time_str(time_s: float) -> str:
"""Concert a timestamp to a String."""
return time.strftime("%c", time.localtime(time_s)) | f8f82cf32234b1468b4402d1f8c823448229c91a | 694,135 |
def merge_args_to_kwargs(argspec, args, kwargs):
"""
Based on the argspec, converts args to kwargs and merges them into kwargs
Note:
This returns a new dict instead of modifying the kwargs in place
Args:
argspec (FullArgSpec): output from `inspect.getfullargspec`
args (tuple): ... | 09f82f7af0adbf640f173b65cc0c656638a1ac2b | 694,136 |
def valid_url_string() -> str:
"""Return string of a valid URL."""
return "https://example.com" | c6a50483346b41582d10047cad5f25cdd5e2f986 | 694,139 |
import logging
import functools
import time
def status(status_logger: logging.Logger):
"""
Decorator to issue logging statements and time function execution.
:param status_logger: name of logger to record status output
"""
def status_decorator(func):
@functools.wraps(func)
def w... | f6e0ce2391ae3450b0ef7fbc827789cd99889d89 | 694,144 |
import zipfile
def get_parts(fname):
"""Returns a list of the parts in an OPC package.
"""
with zipfile.ZipFile(fname) as zip_archive:
parts = [name for name in zip_archive.namelist()]
return sorted(parts) | 458bd85f94df5ab78804eb1df791e6ad54c266c5 | 694,145 |
import pathlib
def _relative_if_subdir(fn):
"""Internal: get a relative or absolute path as appropriate.
Parameters
----------
fn : path-like
A path to convert.
Returns
-------
fn : str
A relative path if the file is underneath the top-level project directory, or an
... | 9efbd0e3b4585315a6c87c0fb3a6cf1082948f11 | 694,146 |
import re
def normalize(string):
"""
This function normalizes a given string according to
the normalization rule
The normalization rule removes "/" indicating filler words,
removes "+" indicating repeated words,
removes all punctuation marks,
removes non-speech symbols,
and extracts or... | 14a62512248979b7ac7ef467b0f74a5201d7e418 | 694,147 |
def user_directory_path(instance, filename):
"""File will be uploaded to MEDIA_ROOT/user_<id>/<filename>"""
return 'user_{0}/{1}'.format(instance.user.id, filename) | 7c12b39184eb358bc7c895ef6c522a6591f7ff4d | 694,148 |
def key_for_value(d, looking):
"""Get the key associated with a value in a dictionary.
Only top-level keys are searched.
Args:
d: The dictionary.
looking: The value to look for.
Returns:
The associated key, or None if no key found.
"""
found = None
for key, value i... | dd1f04f0232ec5a91556b1858a7481c481e85271 | 694,149 |
import math
def cosine(r_tokens: list, s_tokens: list) -> float:
"""Computes cosine similarity.
COS(r, s) = |r ∩ s| / sqrt(|r| * |s|)
Parameters
----------
r_tokens : list
First token list.
s_tokens : list
Second token list.
Returns
-------
Cosine similarity of r... | 234b7298e8c0c29cbb3d79d420e63518decfe4e9 | 694,152 |
def _dir(m, skip=()):
"""
Get a list of attributes of an object, excluding
the ones starting with underscore
:param m: object, an object to get attributes from
:return: list, a list of attributes as strings
"""
return [a for a in dir(m) if not a.startswith('_') and a not in skip] | 2903d4f91031fa8b7a0fbb81679d879a16af37be | 694,153 |
def networkType(host):
"""Determine if a host is IPv4, IPv6 or an onion address"""
if host.find('.onion') > -1:
return 'onion'
elif host.find(':') == -1:
return 'IPv4'
return 'IPv6' | a0d3e92764cc562c43e643cd596762bce8ccfd58 | 694,156 |
def generate_identifier(order):
"""Return a unique identifier by concatenating a lowercased stripped
version of firstname and lastname of the ninja"""
# get first and last names and convert to lowercase
first_name = order.get('Voornaam').lower()
last_name = order.get('Achternaam').lower()
#return as conc... | 219742da3cd749acd5ccd4fa75a92d673c4e194e | 694,158 |
import logging
def validate_input(key, value):
""" Validate a user input
This function ensures that the user enters a valid input
(could be username or filename). Here, the inputs are valid
if they are non-empty. The function then returns the appropriate
status code and message.
Args:
... | f678018e8cf7de6b6a7f6c17728a2e6b470ed0cb | 694,160 |
def dict_append_to_value_lists(dict_appendee, dict_new):
"""
Appends values from dict_new to list of values with same key in dict_appendee
Args:
dict_appendee: dict with value lists (as created by dict_values_to_lists function
dict_new: dict with new values that need to be appended to dict_a... | 3f39a6bca91c3429a04f0047673f6231d29336eb | 694,168 |
def super_digit(n: int) -> int:
"""Return the result of summing of a number's digits until 1 digit remains."""
ds = n % 9
if ds:
return ds
return 9 | 842e644b2a2916ca75f861e2177b2db52ef313db | 694,170 |
def load_from_lsf(script_file_name):
"""
Loads the provided scritp as a string and strips out all comments.
Parameters
----------
:param script_file_name: string specifying a file name.
"""
with open(script_file_name, 'r') as text_file:
lines = [line.strip().split(sep... | ed91b1a4b21f30e3229b71edaab71a6c7ddc33af | 694,172 |
def has_activity(destination, activity_name):
"""Test if a given activity is available at the passed destination/event/tour."""
return destination.has_activity(activity_name) if destination else False | 01fde72d29bd59deeedc18a3ab1322eb85e58fb3 | 694,173 |
def calculate_coordinates(pth):
"""
Create a set of tuples representing the coordinates that the path
traverses, with a starting point at (0,0)
"""
x = 0
y = 0
coords = set()
for instruction in pth:
direction = instruction[:1]
distance = int(instruction[1:].strip())
... | 0bba7e13ec8480104f6a96f7caae7f2bd73d3e2d | 694,174 |
def calculate_interval(pi, chrm, pos):
"""
Determines how a position is mapped to an interval number using pi.
Arguments:
pi (dict of lists of ints): the pi map
chrm (int): chromosome number
pos (int): SNP location
Returns:
The interval associated with pos on chrm if the mapping is successful, otherwise No... | 21410b17b8b125a60065b637ea182e92b98d3591 | 694,176 |
def map_to_fasttext_language(lang):
"""
Map 'zh-x-oversimplified' to 'zh' for language identification.
"""
mapping = {
'zh-x-oversimplified': 'zh'
}
return mapping.get(lang, lang) | 48890f698f42c7107b73cae46c0171e7170ff4a8 | 694,181 |
def print_args(args):
"""Convenience function for printing the current value of the input
arguments to the command line.
----------------------------------------------------------------------------
Args:
args: argparse object returned by ArgumentParser.parse_args()
Returns:
None
... | 18548ce7ad9f8683cbebf7bbda5198c97ea5dfd9 | 694,184 |
def datetime_pyxll_function_3(x):
"""returns a string description of the datetime"""
return "type=%s, datetime=%s" % (type(x), x) | e9810a137aa1a79d925059a5168d46e0adf0b0ee | 694,193 |
import torch
def get_maxprob_metric(log_probs):
"""
Computes the average max probability
"""
max_lp = log_probs.max(axis = -1).values
return torch.exp(max_lp).mean() | 83eb87ea1b85a25212dc391d2c55a1d4db285a52 | 694,199 |
def make_face_rects(rect):
""" Given a rectangle (covering a face), return two rectangles.
which cover the forehead and the area under the eyes """
x, y, w, h = rect
rect1_x = x + w / 4.0
rect1_w = w / 2.0
rect1_y = y + 0.05 * h
rect1_h = h * 0.9 * 0.2
rect2_x = rect1_x
rect2_w... | 832706e74fd9d008b68687f1cd5f5d6ee9c01cf6 | 694,202 |
import glob
def read_all_file_names(directory, extension):
"""Read all files with specified extension from given path and sorts them
based on a given sorting key.
Parameters
----------
directory: str
parent directory to be searched for files of the specified type
extension: str
... | 30217a765768d4d225ae3591037f75ffeeb8c042 | 694,210 |
def inclusion_two_params_from_template(one, two):
"""Expected inclusion_two_params_from_template __doc__"""
return {"result": "inclusion_two_params_from_template - Expected result: %s, %s" % (one, two)} | 4a81da93f96356b1e1eb370755bf7627b0cf434a | 694,211 |
import struct
def parse(data):
"""
SMP code is the first octet of the PDU
0 1 2 3 4 5 6 7
-----------------
| code |
-----------------
References can be found here:
* https://www.bluetooth.org/en-us/specification/adopted-specifications - Core specification 4.1
*... | 9d1d97f76213e4cabcc43f13d980cd658fcfae41 | 694,220 |
def wait_for_queue(handle):
"""
Read from ``sbatch`` output whether the queue is full.
:param object handle: sbatch handle
:return: ``True`` if queue is full, else ``False``
:rtype: :py:obj:`bool`
"""
for f in (handle.stdout, handle.stderr):
for line in f:
if ("maxi... | 0a1978354367be99f3fe969df81ae014ab7b2439 | 694,221 |
def object_copy(self, CopySource, ExtraArgs=None, Callback=None,
SourceClient=None, Config=None):
"""Copy an object from one S3 location to this object.
This is a managed transfer which will perform a multipart copy in
multiple threads if necessary.
Usage::
import ibm_boto3
... | 378d7143bf8649e187cba43a07df7b41df9b43c3 | 694,224 |
import re
def getMessageError(response):
"""
Extracts the error message from an ERDDAP error output.
"""
emessageSearch = re.search(r'message="(.*)"', response)
if emessageSearch:
return emessageSearch.group(1)
else:
return "" | 020a597e8b3a93a190536dd83b7dfe12d651ed07 | 694,226 |
def _from_proc_output(output: bytes) -> str:
"""
Convert proc output from bytes to str, and trim heading-
and tailing-spaces
:param output: output in bytes
:return: output in str
"""
return str(output, encoding='utf-8').strip(' \t\n') | 67013919c2f8020f5794766f7bc034e80d09eb20 | 694,227 |
from functools import reduce
def get_deep_dict_value(source: dict, keys: str, default = None):
"""
Get values from deeply nested dicts.
:source (dict): Dictionary to get data from.
:keys (str): Keys split by '|'. E.g. outerkey|middlekey|innerkey.
:default: Default return value.
"""
value ... | 40de0e150c04589040ebc3b70ae5e8e63b68901d | 694,228 |
def calculate_step_or_functional_element_assignment(child_assignments: list, sufficient_scheme=False):
"""
Assigns a step result or functional element result based of the assignments of its children. In the case of steps,
this would be functional element assignments. In the case of functional elements this ... | 9dfa5cbf0c10bd5ed848fd5f1ca6e09dcc64a8c9 | 694,230 |
def _generate_join(collection, local_id, foreign_id):
"""Make join string for query from parameters."""
text = '{{!join from={fid} to={lid} fromIndex={collection}}}'
text = text.format(
collection=collection,
lid=local_id,
fid=foreign_id)
return text | 1e831fadda22866b098b1c0e1673e73d9370dd75 | 694,231 |
def get_tomorrow(utc_now, tz, to_local=False):
"""Return an :class:`~arrow.arrow.Arrow` datetime for *tomorrow 00:00 local
time*.
The calculation is done relative to the UTC datetime *utc_start* converted
to the timezone *tz*.
By default, the result is converted back to UTC. Set *to_local* to
... | c447f52fa770f81f0da6bcbaa13fbebc8a398d67 | 694,232 |
def extract_pem_cert(tree):
"""
Extract a given X509 certificate inside an XML tree and return the standard
form of a PEM-encoded certificate.
:param tree lxml.etree: The tree that contains the X509 element. This is
usually the KeyInfo element from the XMLDsig Signature
... | 6737fd4002f9de25142291be2cd19c265465340a | 694,235 |
import re
def parseVtxIdx(idxList):
"""convert vertex index list from strings to indexes.
idxList : [u'vtx[1]', u'vtx[3]', u'vtx[6]', u'vtx[8]', u'vtx[12:13]']
return : [1,3,6,8,12,13]
"""
parseIdxList = []
for idxName in idxList:
match = re.search(r'\[.+\]', idxName)
if matc... | 32c3a40ac374865cf61d44e9834a50801c9f236d | 694,239 |
def _transpose(group):
"""
Given a list of 3-tuples from _grouper, return 3 lists.
Also filter out possible None values from _grouper
"""
a, b, c = [], [], []
for g in group:
# g can be None
if g is not None:
x, y, z = g
#if x is not None and y is not Non... | 2027c7ee84340d6758fe352058b8b8cd962e4d96 | 694,240 |
def _is_member(s, e):
"""Return true if `e` is in the set `s`.
Args:
s: The set to inspect.
e: The element to search for.
Result:
Bool, true if `e` is in `s`, false otherwise.
"""
return e in s._set_items | 810336bb16babcca3af8bc9c931da3d058b6f14f | 694,242 |
def read(f):
"""Read a file an return its content in utf-8"""
return open(f, 'rb').read().decode('utf-8') | 5d43d64392e8c8ed33cb2dfe3d64d780c6217321 | 694,244 |
def get_file_type(filename):
"""
Return the extension (if any) of the ``filename`` in lower case.
"""
return filename[filename.rfind('.')+1:].lower() | cb0487e0886d60a6d0e5f97fa7d2313293390f5d | 694,245 |
def buildParameters(obj, validList):
"""
>>> class TestClass(object):
... pass
>>> testClass = TestClass()
>>> testClass.a = 1
>>> testClass.b = "2"
>>> testClass.c = 3
>>> testClass.d = True
>>> buildParameters(testClass, ["a", "b"])
['--a', u'1', '--b', u'2']
>>> testCla... | 9504d950b3b5827e95543afdf5615a06f3fe3532 | 694,249 |
import socket
import struct
def send_tcp(data,host,port):
"""
Helper function to send/receive DNS TCP request
(in/out packets will have prepended TCP length header)
"""
sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
sock.connect((host,port))
sock.sendall(data)
response... | 51d58d7ba31af919466acde7ea19780031c70158 | 694,256 |
def arity(argspec):
""" Determinal positional arity of argspec."""
args = argspec.args if argspec.args else []
defaults = argspec.defaults if argspec.defaults else []
return len(args) - len(defaults) | f19407943f92a2a4faa4735abf678467861153e7 | 694,257 |
def fw(model, input, model_pretrain_method):
"""Call and index forward according to model type."""
output = model(input)
if model_pretrain_method == "torchvision":
return output
elif model_pretrain_method == "Swav":
return output[1]
else:
return output[0] | 6367ab0cdfb4ad1dd2e85fee5e357148ee5f5d71 | 694,259 |
import torch
def postprocess(images):
"""change the range from [-1, 1] to [0., 1.]"""
images = torch.clamp((images + 1.) / 2., 0., 1.)
return images | 37421278b26cd0913905db61379f4b979d1d2a98 | 694,260 |
def dec2sex(rain,decin,as_string=False,decimal_places=2):
"""
Converts decimal coordinates to sexagesimal.
Parameters
----------
rain : float
Input Right Ascension in decimal -- e.g., 12.34567
decin : float
input Declination in decimal -- e.g. -34.56789
as_string : bool... | 1404996c46db480183a8cb46a11986bf6c9e7531 | 694,264 |
import base64
def encode_info_basic_http_auth(username, password):
"""
Encodes the username and password to be sent in the `Authenticate`
header in http using basic authentication.
:param username: username
:param password: password
:return: encoded value for the http 'Authenticate' header
... | 9721f745cd6b38aa9c3b1c98c3eaa19c64949709 | 694,265 |
def is_new_style(cls):
"""
Python 2.7 has both new-style and old-style classes. Old-style classes can
be pesky in some circumstances, such as when using inheritance. Use this
function to test for whether a class is new-style. (Python 3 only has
new-style classes.)
"""
return hasattr(cls, '_... | a303d87a5ef790d629dff6fcd07c46d029277530 | 694,267 |
def path2FileName(path):
"""Answer the file name part of the path.
>>> path2FileName('../../aFile.pdf')
'aFile.pdf'
>>> path2FileName('../../') is None # No file name
True
"""
return path.split('/')[-1] or None | 7c7d954ae2cf436624fa6e95edac887facf27dd4 | 694,271 |
def file_search(f_name, data_str):
"""Function: file_search
Description: Search for a string in a file and return the line it was
found in a line.
NOTE: Returns only the first instance found in the file.
Arguments:
(input) f_name -> File name searching.
(input) data_str ->... | 0d5b0514165674b390c3225c48f3c3e8810b4006 | 694,275 |
def build_abstract(*args):
"""Combines multiple messages into a single abstract over multiple lines.
>>> build_abstract("test1", "test2")
'test1\\ntest2'
"""
return "\n".join([_arg for _arg in args if _arg]) | 8cc7732e8cfc052e294320f6e96185e53f73b59b | 694,276 |
import plistlib
def load_datafile(filename):
"""Load a data file and return the contents as a dictionary """
with open(filename, 'rb') as f:
data = plistlib.load(f)
return data | f57a4a38afb0d5ae9d21b712ceb28143ba695c27 | 694,277 |
import hashlib
def rgb_from_string(text, min_brightness=0.6):
""" Creates a rgb color from a given string """
ohash = hashlib.md5(text[::-1].encode("ascii")).hexdigest()
r, g, b = int(ohash[0:2], 16), int(ohash[2:4], 16), int(ohash[4:6], 16)
neg_inf = 1.0 - min_brightness
return (min_brightness + ... | feac9c8664dd96610fd9bbada578eb4d10ebfd0b | 694,279 |
def validate_key(key, keyname='Key'):
"""
Check input is valid key (Experiment id, metric name...)
"""
if not isinstance(key, str):
msg = '{} must be str, given: {}{}'
raise ValueError(msg.format(keyname, key, type(key)))
if ':' in key:
msg = '{} cannot contain colon (:): {}'... | bd2bdc070ae0e511cbf3bf1e4cac6e851cdd683e | 694,280 |
def mask_topk(x, topkk):
"""
Returns indices of `topk` entries of `x` in decreasing order
Args:
x: [N, ]
topk (int)
Returns:
array of shape [topk, ]
"""
mask = x.argsort()[-topkk:][::-1]
return mask | 9d8df1efb3152db935368c0155ddd00984030bc4 | 694,283 |
def get_col_info(datadf, colname, colsource = 'source', map='all'):
"""Search a data dictionary dataframe fror a column
return close matches
Parameters
----------
datadf : dataframe,
the dataframe that has dictionary columns.
colname : str
the column name to search for.
col... | 3b87d1705e627b6f16e129ec3a911027f17c1212 | 694,284 |
def get_consensus(out_fn, trim_margin):
""" Extract consensus sequence from output of spoa.
Parameters
----------
out_fn : str (output from spoa)
trim_margin : int (number of bp to trim on each end of the consensus, as the consensus sequence
is more likely to be erroneous on the ends)
Retu... | 833289b301d553c5f35a799fd70418d4a63889c6 | 694,285 |
def normalize_string(string):
"""
Standardize input strings by making
non-ascii spaces be ascii, and by converting
treebank-style brackets/parenthesis be characters
once more.
Arguments:
----------
string : str, characters to be standardized.
Returns:
--------
str : s... | 5e0f7850116fe2d7275674f3ff6a938689ac3c3e | 694,287 |
def stairs(N):
"""
Produces stairs array of size N
"""
stairs = []
for i in range(0,N):
# step = ''.join([str(N)]*(i+1)) + ''.join([' ']*(N-i-1))
step = '#'*(i+1) + ' '*(N-i-1)
stairs.append(step)
return stairs | 59b00a6d38d92410e9566846a1f8343f597f2400 | 694,288 |
def clip_box(box, max_width, max_height):
"""clipping a [x,y,w,h] boxes."""
x, y, w, h = box
if x + w > max_width:
w = max_width - x
w = 0.0 if w < 0 else w
if y + h > max_height:
h = max_height - y
h = 0.0 if h < 0 else h
if x > max_width:
x = max_width
if y > max_height:
y = max_... | 0468b1827b74c1878d64f8ce0ea921f7bbbd7271 | 694,290 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.