content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import random
def integer(start, end, steps=1):
"""
Function integer
Return a random integer
Inputs:
- start: minimum allowed value
- end: maximum allowed value (inclusive)
- steps: the interval from which to select the random integers
Output: a string con... | 99333decb006a547229eaf7b950a803cc8a450b0 | 30,315 |
import re
def cleanlines(lines):
"""Remove comments and blank lines from splitlines output."""
# Clean comments.
matchRE = re.compile('(.*?)(//|%|#)')
for i in range(len(lines)):
line = lines[i]
match = matchRE.match(line)
if match is not None:
lines[i] = match.group(1)
# Clean blank lines... | 2971936b5b7098983aad3af40c82d337f998f5a1 | 30,317 |
import torch
def apply_trans(x, trans):
"""Apply spatial transformations to input
Attributes:
x (torch.Tensor): Input Tensor
trans (torch.nn.Module): Spatial Transformer module
Returns:
torch.Tensor: Output Tensor
"""
x = x.transpose(2, 1)
x = torch.bmm(x, trans)
... | 152210b5f544d524aff94039ca1cb33dfdf1f9f5 | 30,318 |
import zlib
def _adler32(fname):
"""Compute the adler32 checksum on a file.
:param fname: File path to the file to checksum
:type fname: str
"""
with open(fname, 'rb') as f:
checksum = 1
while True:
buf = f.read(1024*1024*8)
if not buf:
brea... | 7e7b37d39cdd7dbd1795aa25b48460350e121dae | 30,319 |
def event_is_virtual(event):
""" Determine if event is virtual. Produces a boolean."""
return 'location' in event and \
'@type' in event['location'] and \
event['location']['@type'] == "VirtualLocation" | 6fb246f65ff87e38fc19a7f619b7f1a521f49060 | 30,320 |
def time_str_from_datetime_str(date_string: str) -> str:
"""
Extracts the time parts of a datetime.
Example:
2019-12-03T09:00:00.12345 will be converted to:
09:00:00.12345
:param date_string:
:return:
"""
return date_string.split('T')[1] | cd08fc6cb55854cacf1620aea4b02692b7925cd7 | 30,322 |
def create_regcontrol_settings_commands(properties_list, regcontrols_df, creation_action='New'):
"""This function creates a list of regcontrol commands, based on the properties list and regcontrol dataframe passed
Parameters
----------
properties_list
regcontrols_df
creation_action
Returns... | 5095ad7a3aa5ee1e8ada5f7e9333f5a7008511ca | 30,323 |
def _getProfile(APIConn, screenName=None, userID=None):
"""
Get data of one profile from the Twitter API, for a specified user.
Either screenName string or userID integer must be specified, but not both.
:param APIConn: authenticated API connection object.
:param screenName: The name of Twitter us... | d41f48197c741a4a4f69dad47fc50c2f28fc30ee | 30,325 |
def slicer(shp, idxs, var=None):
"""Obtain a list of slicers to slice the data array according to the
selected data
Parameters
----------
shp : tuple
Data shape
idxs : iterable
Indexes of the selected data
var : int, optional
Data to be selected, in case of multidime... | cbe0d3ab7d376a97206dfe899550fd5345a30df4 | 30,328 |
def extract_features_in_order(feature_dict, model_features):
"""
Returns the model features in the order the model requires them.
"""
return [feature_dict[feature] for feature in model_features] | adc067d35ae61cdd4b5bf0a4199662a6d94ce6f9 | 30,330 |
def _IndentString(source_string, indentation):
"""Indent string some number of characters."""
lines = [(indentation * ' ') + line
for line in source_string.splitlines(True)]
return ''.join(lines) | f85c2e18448497edcd764068ae9205ec4bbaec5d | 30,335 |
def create_success_response(return_data):
""" Creates a standard success response used by all REST apis.
"""
count = 1
if isinstance(return_data, list):
count = len(return_data)
return {
'meta': {
'error': False,
'count': count
},
'data': retu... | 0e1252317ebd838b03d680125b22ce1bf67c2c66 | 30,338 |
def GetMissingOwnerErrors(metrics):
"""Check that all of the metrics have owners.
Args:
metrics: A list of rappor metric description objects.
Returns:
A list of errors about metrics missing owners.
"""
missing_owners = [m for m in metrics if not m['owners']]
return ['Rappor metric "%s" is missing ... | 97deb68f1412b371ca1055e8a71a53408d8915d1 | 30,342 |
import torch
def generate_batch(batch):
"""
Since the text entries have different lengths, a custom function
generate_batch() is used to generate data batches and offsets,
which are compatible with EmbeddingBag. The function is passed
to 'collate_fn' in torch.utils.data.DataLoader. The input to
... | c33bd4c78f4715ef08fc18c1eb9f78540301138b | 30,343 |
def make_name(image):
"""Format output filename of the image."""
return image['name'][:-4] | ab51f714052528c7dc16cd68b80c1c9b889adaea | 30,351 |
def is_quoted(str):
""" whether or not str is quoted """
return ((len(str) > 2)
and ((str[0] == "'" and str[-1] == "'")
or (str[0] == '"' and str[-1] == '"'))) | b079bd4a7f3ac8814250faf522d9e38718fce986 | 30,353 |
from typing import List
from typing import Dict
def track_path_to_header(
book_id: int, book_url: str, book_title: str, gpx_name: str
) -> List[Dict]:
"""
Format the header breadcrumbs - refer to templates/layout.html.
Args:
book_id (int): Book ID based on the 'shelf' database table.
... | 28c478da73d73fdf089c169e3d8bd570cabcf58d | 30,358 |
def calcFallVelocity(rho_s, D_s):
"""
Calculates fall velocity of sediment.
Paramters
---------
rho_s : sediment density [kg/m^3]
D_s : sediment diameter [m]
Returns
-------
w - fall velocity of sediment [m/s]
Notes
-----
Equation used is from Ferguson and Church [2004]. C1 and C2
values correspond to f... | 74f07f6e3448d36f9adf0feb196605f86d70f1bd | 30,363 |
def total_duration_parser(line):
"""
Parses lines of the following form:
Total duration: 5248.89s
:param line: string
:return: float containing total duration in seconds
"""
try:
return float(line.rstrip('s')[len('Total duration:'):].strip())
except:
return 0. | 30cc8da46293654b8d4001dbd708160ba208bacb | 30,367 |
from typing import Callable
def newton_step(f: Callable[[float], float], f_prime: Callable[[float], float], x_0: float) -> float:
"""
Performs a single iteration of Newton's Method
Parameters
----------
f
The function to determine the root of.
f_prime
... | b877d0a70ba8557b79f1ae99ef4e1b815d0778ff | 30,369 |
def lucas(n):
"""Function that provides the nth term of lucas series."""
x, y = 2, 1
for i in range(n - 1):
x, y = y, x + y
return x | 6d40e67ce8dd682bb26f9bd16d2dd34d3d1bf541 | 30,381 |
def gas_constant(R, mu):
"""
Gas constant of natural gas, J/(kg*K)
:param R: (float) Universal gas constant, J/(kmole*K)
:param mu: (float) Molar mass of natural gas, kg/kmole
:return: (float) Gas constant of natural gas, J/(kg*K)
"""
return R / mu | 05587e637635ea6262541347966ec18e05bf6fba | 30,383 |
def engine_options_from_config(config):
"""Return engine options derived from config object."""
options = {}
def _setdefault(optionkey, configkey):
"""Set options key if config key is not None."""
if config.get(configkey) is not None:
options[optionkey] = config[configkey]
... | 9ece915beba58b080ad330f75197c466246fdfe2 | 30,387 |
def df_variables_info(df):
"""
This function gives information about the df: number of observations, variables, type and number of variables
params: df is a dataframe from which we want the information
return: NONE
"""
# Number of variables
print('Number of variables:', df.shape[1])
... | b766299931398b4973f4bed2a8280b55397203aa | 30,392 |
def _delete_duplicates(l, keep_last):
"""Delete duplicates from a sequence, keeping the first or last."""
seen=set()
result=[]
if keep_last: # reverse in & out, then keep first
l.reverse()
for i in l:
try:
if i not in seen:
result.append(i)
... | fa3d8bc3ef32899bcfedcff1376e3ecb75b5600d | 30,395 |
def rindex(list, value):
"""Find the last-occurring index of `value` in `list`."""
for i in range(len(list) - 1, 0, -1):
if list[i] == value:
return i
return -1 | f4b91f3d8ae531f610806c68054b1075c73b0dcf | 30,399 |
import math
def atan_deg(value):
""" returns atan as angle in degrees """
return math.degrees(math.atan(value) ) | ad7f79e4ebbfc364bddb5f20afd01b8cf70f9c08 | 30,400 |
def _add_extension_assets(client, customer_id, language_code):
"""Creates new assets for the hotel callout.
Args:
client: an initialized GoogleAdsClient instance.
customer_id: a client customer ID.
language_code: the language of the hotel callout feed item text.
Returns:
a ... | bc213f9be915845b9ebb977a8b10ec941a640089 | 30,402 |
import math
def subtended_angle(size, distance):
"""
Return the subtended angle angle of a sphere with certain size and distance:
https://en.wikipedia.org/wiki/Subtended_angle. Used to determine the size of
the bounding box located at a certain position in the image.
"""
angle = math.fabs(size... | 46b74d3fa14321e3f7004ec0fdcc6b8875abc50e | 30,405 |
import csv
def read(path):
"""
Returns list of dictionaries.
All returned values will be strings.
Will assume that first row of file contains column names.
"""
file = open(path, 'r', encoding = 'utf-8')
reader = csv.reader(file, delimiter = '\t', quotechar = '', quoting = csv.QUOTE_NONE)
result ... | 0506a59d28c9ee750dd6045217319097bfa9c662 | 30,406 |
def lab_monthly(dataframe):
"""
Extract monthly data from a labstat file
Parameters:
dataframe (dataframe): A dataframe containing labstat data
Returns:
dataframe
"""
dataframe['month'] = dataframe['period'].str[1:].copy().astype(int)
dataframe['value'] = dataframe['value'... | 440c8502558c7b3746814706b2c4267b87e9d399 | 30,410 |
def find_empty_square(board):
"""
Return a tuple containing the row and column of the first empty square
False if no squares are empty
"""
for i, row in enumerate(board):
for j, square in enumerate(row):
if square == 0:
return (i, j)
return False | 98b4b50527a33abec3134a22c5a9cff5a874b171 | 30,412 |
def user_can_edit_setting_type(user, model):
""" Check if a user has permission to edit this setting type """
return user.has_perm("{}.change_{}".format(
model._meta.app_label, model._meta.model_name)) | cfc2cde620718635493374ef62966539f25ba362 | 30,418 |
def verify_notebook_name(notebook_name: str) -> bool:
"""Verification based on notebook name
:param notebook_name: Notebook name by default keeps convention:
[3 digit]-name-with-dashes-with-output.rst,
example: 001-hello-world-with-output.rst
:type notebook_name: str
:returns: Return if... | 87a839ddffc32613d74775bf532953c8263093cd | 30,421 |
import json
def str_to_json(s):
"""
Deserialize JSON formatted string 's' to a dict.
Args:
s: JSON string to be deserialized
Examples:
>>> str_to_json('{}')
{}
>>> str_to_json('{"a": 1, "c": {"d": 3}, "b": 2}') == {u'a': 1, u'c': {u'd': 3}, u'b': 2}
True
>>> str_to_json('... | 95feed74f9ddda9f3db8b5e03d52bf19fe1538fe | 30,423 |
import re
def valid_mac(mac=None):
"""Validates Ethernet MAC Address
:param: mac address to validate
:type: str
:return: denotes true if MAC proper format else flase
:rtype: bool
"""
if mac is None or mac.strip() == "":
return False
mac = mac.strip()
return re.match("^([0-... | 356f8ce8e16fb25271aa2f1dea845febd19864cb | 30,426 |
def hasmethod(obj, methodname):
"""Does ``obj`` have a method named ``methodname``?"""
if not hasattr(obj, methodname):
return False
method = getattr(obj, methodname)
return callable(method) | a71dcdac40d97de91bc789068a885cab467a6f48 | 30,429 |
def _batch_name(split_name, offset, dataset):
"""Returns the file name for a given batch.
Args:
split_name: "train"|"test"
offset: batch index (0-indexed)
dataset: "cifar10"|"cifar100"
"""
if dataset == 'cifar10':
if split_name == 'train':
return 'data_batch_%d' % (offset + 1) # 1-inde... | b360268ef38bb5fee5fa02b36b19c7d0ae6a1ab7 | 30,432 |
from typing import Dict
from typing import List
def create_dirs_list(all_confs: Dict[int, Dict[str, list]]) -> List[dict]:
"""Creates required directories for a project.
Uses the information provided by `config_info()`
to create directories according to the user's configuration
file.
Args:
... | 3ca08e48a5e27bfcb9c3d0d751cf7efc553ea34b | 30,435 |
from datetime import datetime
def parse_time(line):
"""
All logging lines begin with a timestamp, parse it and return the datetime it represents.
Example: 2016-04-14 14:50:33,325
:param line: the log line containing time
:return: native datetime
"""
return datetime.strptime(line[:19], '%y... | 40d0e755693bd93a0d1ecf1969b39a5c001b1cca | 30,438 |
from typing import List
from typing import Dict
def construct_rows(header: list, rows: list) -> List[Dict]:
"""Construct a list of csv row dicts.\n
Arguments:
header {list} -- csv header\n
rows {list} -- csv contents\n
to warp if there is only a single row, e.g. [row]\... | 771b2dfde99a8b517331695d160eb9f809e4933c | 30,447 |
import requests
import zipfile
import io
def get_zip_file(url):
"""
Get zip file from provided URL
"""
with requests.get(url, stream=True) as f:
z = zipfile.ZipFile(io.BytesIO(f.content))
return z | 2db522396d4ffde212c858b3544cfaa99b03bba0 | 30,452 |
def parse_rule(l, cats):
"""Parses a sound change rule or category.
Given a line l with the format 'a > b / c_d ! e_f', produces a dict of
the form
{
'from': 'a',
'to': 'b',
'before': 'c',
'after': 'd',
'unbefore': 'e',
'unafter': 'f'
}.
If l is o... | db9239fcf8d13d8884dd57a351e312de4caf2c61 | 30,455 |
import re
from typing import Counter
def get_term_frequencies(series, min_str_len=1, ngram=1):
"""
Get number of occurence of each term in the given pandas series
Parameters
----------
series: pandas series
Series to extract the term frequencies from
min_str_len: int, optional (defaul... | 560247a4fa3a6a1321caf9eadd45ba889eb517cc | 30,456 |
from typing import List
from typing import Dict
def ids_to_models(model_ids: List[str]) -> Dict[str, List[str]]:
"""
Convert model IDs (MODEL_NAME-MODEL_VERSION) to a dictionary with its keys being
the model names and its values being lists of the associated versions for each given model name.
"""
... | 5a2b3bdc1361954a78630ca8bac4ebd0aefe8293 | 30,459 |
def _flatten(list_of_lists):
"""
Turns a nested list of lists ([a,[b,c]]) into a flat list ([a,b,c]).
"""
out = []
if type(list_of_lists) is int:
return [list_of_lists]
for item in list_of_lists:
if type(item) is int:
out.append(item)
elif type(item) is list:
... | 8b2489d18a277e15e6f8c67baad70ff874c6e2bf | 30,460 |
def get_nested(dct, key_pattern):
""" Get value(s) from a nested dict
Args:
dct: dict having str keys and values which may be other `dct`s
key_pattern: str giving dotted key
Returns the value. Note that if key_pattern does not go to full depth then a dict is ret... | 4e7de6f56a6bcc62fc41b377f9ba2b144ac5627d | 30,462 |
def sw_update_strategy_db_model_to_dict(sw_update_strategy):
"""Convert sw update db model to dictionary."""
result = {"id": sw_update_strategy.id,
"type": sw_update_strategy.type,
"subcloud-apply-type": sw_update_strategy.subcloud_apply_type,
"max-parallel-subclouds":
... | 93e8da29292998a37d031d6087bb0afba73fc995 | 30,468 |
def is_decimal_amount(string: str) -> bool:
"""Checks if string is a decimal amount (e.g. 1/2, 1/4, etc..)
Args:
string: string to be checked.
Returns:
True if string is a decimal amount, False otherwise.
"""
if "/" not in string or len(string.split("/")) != 2:
return False
... | 5b820eb8586b0eee94c9b122a20f0a7442111777 | 30,470 |
def std_input(text, default):
"""Get input or return default if none is given."""
return input(text.format(default)) or default | d0b38f828dec28cd9ae7d251fcb3bb0bbf324264 | 30,471 |
def institutions(cur):
"""Returns prototype and agentids of institutions
Parameters
----------
cur: sqlite cursor
sqlite cursor
Returns
-------
sqlite query result (list of tuples)
"""
return cur.execute('SELECT prototype, agentid FROM agententry '
'W... | e02233b997cba0a14f1bdcfcecf720deb9b4a494 | 30,474 |
def format_string(indices):
"""Generate a format string using indices"""
format_string = ''
for i in indices:
format_string += ', %s' % (i)
return format_string | 5bc61727f74b97648961e7b9ccf8299a9680648b | 30,479 |
def element_wise_product(X, Y):
"""Return vector as an element-wise product of vectors X and Y"""
assert len(X) == len(Y)
return [x * y for x, y in zip(X, Y)] | e01ec3720ac6b2fa06cca1186cf1a5a4d8703d38 | 30,480 |
def get_schedule_config(config):
"""Get all the config related to scheduling this includes:
- Active Days
- Start Time
- End Time
It will also convert the hours and minute we should start/end in to ints.
Args:
config (ConfigParser): ConfigParser object used to get the config.
Ret... | d362a44e80f5ae8bca5ab5ac7fe164777beae1ed | 30,486 |
def p_empty_or_comment(line, comment='#'):
"""Predicate matching strings that are not empty and don't start
with a comment character. For best results, the line should no
longer contain whitespace at the start."""
return len(line) and not line.startswith(comment) | d0eef18237b0cac9f019d866d48d02813b1c2e95 | 30,489 |
def rowcol_to_index(row, col, width):
"""Convert row major coordinates to 1-D index."""
return width * row + col | cc9bce2ba17337025e9982865abdc63f4ad90658 | 30,490 |
def accuracy_boolean(data, annotation, method, instance):
"""
Determine whether method output is correct.
Parameters
----------
data: color_image, depth_image
annotation: Annotation from blob_annotator
method: function[instance, data] -> BoundingBox
instance: instance of benchmark
... | c28ef0b521895d4eef2a996e376cf0853b4a809a | 30,491 |
import random
def dummy_decision(board):
""" make a random dummy move
"""
legal_moves = list(board.legal_moves)
return random.choice(legal_moves) | 8c44acf1aff245ed532e48c35e440440b6ddcaef | 30,493 |
def leia_int(txt):
"""
-> Verifica se o valor digitado é numérico
:param txt: mensagem a ser mostrado para o usuário
:return: retorna o valor digitado pelo o usuário, caso seja um número
"""
while True:
num = input(txt)
if num.isnumeric():
break
else:
... | f6a1c7104706e5a181a73aacd43f91a75df3e3f1 | 30,496 |
def address_column_split(a):
"""
Extracts city and state in an address and provides separate columns for each
"""
asplit = a.split(",")
city = asplit[0].split()[-1]
state = asplit[1].split()[0]
return city, state | 539123969beb28f2623466db193077f4351d04cb | 30,502 |
def derivative(f, h):
"""(function, float) -> function
Approximates the derivative of function <f> given an <h> value.
The closer <h> is to zero, the better the estimate
"""
return lambda x: (f(x + h) - f(x)) / h | 1dbb4035580f0bbb16339ee38ba863a2af144b63 | 30,503 |
def nextDWord(offset):
"""
Align `offset` to the next 4-byte boundary.
"""
return ((offset + 3) >> 2) << 2 | 4c51fdf80b2f684645fee85755549c46208361ae | 30,510 |
import math
def dist(p1, p2):
"""
Returns distance between two any-dimensional points given as tuples
"""
return math.sqrt(sum([(i - j)**2 for i, j in zip(p1, p2)])) | 6c57680ae32ea33aba591ab2fb75aabe41af1df5 | 30,512 |
def range_count(start, stop, count):
"""Generate a list.
Use the given start stop and count with linear spacing
e.g. range_count(1, 3, 5) = [1., 1.5, 2., 2.5, 3.]
"""
step = (stop - start) / float(count - 1)
return [start + i * step for i in range(count)] | 41d4e73e1cf85655a0df06c976d9187c9964dc59 | 30,524 |
def dens(gamma, pres, eint):
"""
Given the pressure and the specific internal energy, return
the density
Parameters
----------
gamma : float
The ratio of specific heats
pres : float
The pressure
eint : float
The specific internal energy
Returns
-------
... | ae37519718d3019546a4775cf65ca6697397cf5f | 30,527 |
def dodrawdown(df):
"""computes the drawdown of a time series."""
dfsum = df.cumsum()
dfmax = dfsum.cummax()
drawdown = - min(dfsum-dfmax)
return drawdown | e45dbdd19238e04975d5d14beb6348b0a744ada9 | 30,531 |
def check_mol_only_has_atoms(mol, accept_atom_list):
"""Checks if rdkit.Mol only contains atoms from accept_atom_list."""
atom_symbol_list = [atom.GetSymbol() for atom in mol.GetAtoms()]
return all(atom in accept_atom_list for atom in atom_symbol_list) | 472f0c263df1c5306176a5e40e321513f72e7697 | 30,535 |
import re
def apply_and_filter_by_regex(pattern, list_of_strings, sort=True):
"""Apply regex pattern to each string and return result.
Non-matches are ignored.
If multiple matches, the first is returned.
"""
res = []
for s in list_of_strings:
m = re.match(pattern, s)
if m ... | 26aa766dbd211ca04ec33ace5d0823b059005690 | 30,536 |
def merge_shapes(shape, merged_axis: int, target_axis: int) -> list:
"""
Merge two axes of a shape into one, removing `merged_axis` and multiplying the size of the `target_axis` by the size
of the `merged_axis`.
:param shape: The full shape, tuple or tf.TensorShape.
:param merged_axis: The index of... | d2ca4f91f7a99f9cef232d163c36ccac0e89fa18 | 30,537 |
def is_on_border(bbox, im, width_border):
"""
Checks if object is on the border of the frame.
bbox is (min_row, min_col, max_row, max_col). Pixels belonging to the
bounding box are in the half-open interval [min_row; max_row) and
[min_col; max_col).
"""
min_col = bbox[1]
max_col = bbox[... | 815dab6682f0c977ec2ad86522d41ec086423971 | 30,542 |
from datetime import datetime
def get_rate_limit_info(headers):
""" Get Rate Limit Information from response headers (A Dictionary)
:returns: Dictionary of 'remaining' (int), 'limit' (int), 'reset' (time)
"""
ret = {}
ret['remaining'] = int(headers.get('x-rate-limit-remaining'))
ret['limit'] =... | 2478b21d71bff0021d102a78fa6a4149ff4b2d6c | 30,545 |
def mysum(a, b):
"""
Add two numbers together.
Parameters
----------
a, b : Number
Numbers to be added together.
Returns
-------
Number
The sum of the two inputs.
"""
return a + b | a64083ac9524cd20875967adbe2b378604be0187 | 30,546 |
def list_usage(progname, description, command_keys, command_helps, command_aliases):
"""
Constructs program usage for a list of commands with help and aliases.
Contructs in the order given in command keys. Newlines can be used for
command sections by adding None entries to command_keys list.
Only on... | 3246c509eaea33e271b1dc3425a1cc49acb943a3 | 30,547 |
from typing import List
def dromedary_to_pascal_case(text: str) -> str:
"""Convert from dromedaryCase to PascalCase."""
characters: List[str] = []
letter_seen = False
for char in text:
if not letter_seen and char.isalpha():
letter_seen = True
characters.append(char.upp... | 50b735ff1f44c30faa27251f85d902f1d2459ea6 | 30,551 |
def get_spaceweather_imagefile(if_path, if_date, if_filename, if_extension, \
verbose):
"""Returns a complete image filename string tailored to the spaceweather
site string by concatenating the input image filename (if) strings that
define the path, date, filename root, and the filename extension
... | 52fab5c964e28287c8cdd1f30208bc74a3e99d34 | 30,552 |
from pathlib import Path
def find_lab(directory, utt_id):
"""Find label for a given utterance.
Args:
directory (str): directory to search
utt_id (str): utterance id
Returns:
str: path to the label file
"""
if isinstance(directory, str):
directory = Path(directory)... | c3ca69e436456284b890b7de3aff665da756f044 | 30,553 |
from typing import Callable
from typing import Iterable
def multiply(func: Callable, *args, **kwargs):
"""
Returns a function that takes an iterable and maps ``func`` over it.
Useful when multiple batches require the same function.
``args`` and ``kwargs`` are passed to ``func`` as additional argument... | 97cab2f739d39ab2e933b11a84814df8ecc811cf | 30,562 |
def upload_file_to_slack(slack_connection, file_name, channel_name, timestamp):
"""
Upload a file to Slack in a thread under the main message.
All channel members will have access to the file.
Only works for files <50MB.
"""
try:
file_response = slack_connection.files_upload(
... | 1922bf8d357881325fd861bc76827961c7ac4db8 | 30,566 |
def bitstr_to_int(a):
""" Convert binary string to int """
return int(a, 2) | 1188a2ff24b1bf6c70db9a458d39f08f44f006e8 | 30,567 |
def average(number1, number2, number3):
"""
Calculating the average of three given numbers
Parameters:
number1|2|3 (float): three given numbers
Returns:
number (float): Returning the statistical average of these three numbers
"""
return (number1 + number2 + number3) / 3.0 | 04102ee8646b6e5d2cfa9265771c4f4bdbe45d45 | 30,570 |
import ast
def _convert_string_to_native(value):
"""Convert a string to its native python type"""
result = None
try:
result = ast.literal_eval(str(value))
except (SyntaxError, ValueError):
# Likely a string
result = value.split(',')
return result | eaeec2eda520e6342ee6b5f3ac523d44b1c06d53 | 30,575 |
def cmp(x, y) -> int:
"""
Implementation of ``cmp`` for Python 3.
Compare the two objects x and y and return an integer according to the outcome.
The return value is negative if ``x < y``, zero if ``x == y`` and strictly positive if ``x > y``.
"""
return int((x > y) - (x < y)) | 2609f78797ad778e0d0b9c40a568a3f03153dd2c | 30,579 |
def update_taxids(input, updatedTaxids):
""" Updates a map of sequenceIDs to taxIDs with information from merged.dmp
Some of NCBI's taxonomy IDs might get merged into others. Older sequences
can still point to the old taxID. The new taxID must be looked up in the
merged.dmp file in order to be able to ... | be6fe1579d83e8915712c8ea79baaf76ce0a8c9d | 30,580 |
def parse_slice(useslice):
"""Parses the argument string "useslice" as the arguments to the `slice()`
constructor and returns a slice object that's been instantiated with those
arguments. i.e. input useslice="1,20,2" leads to output `slice(1, 20, 2)`.
"""
try:
l = {}
exec("sl = slice... | 471b31a6774127a68eca6619d36df8e0bee66f18 | 30,581 |
def predict_multiclass(model, x, *extra_xs):
"""
Predict a class (int in [0...(n classes - 1)]) for each input (first dim of `x`) using the classifier `model`.
Args:
model: multiclass classifier module that outputs "n classes" logits for every input sequence.
x: input tensor.
extra_... | c351d672d2177cb668a67b6d81ac166fde38daa2 | 30,586 |
import torch
def convert_2Djoints_to_gaussian_heatmaps_torch(joints2D,
img_wh,
std=4):
"""
:param joints2D: (B, N, 2) tensor - batch of 2D joints.
:param img_wh: int, dimensions of square heatmaps
:param st... | 26607acb1f756b840a8b970ade0ccdf01bf286e9 | 30,587 |
import string
import random
def random_string(length=50):
"""Return a string of random letters"""
chars = string.ascii_letters
r_int = random.randint
return "".join([chars[r_int(0, len(chars) - 1)] for x in range(length)]) | b337045cc724d450f578fc890042dd5e4c849580 | 30,594 |
def istamil_alnum( tchar ):
""" check if the character is alphanumeric, or tamil.
This saves time from running through istamil() check. """
return ( tchar.isalnum( ) or tchar.istamil( ) ) | 605fc9c82b688e314201ba2be3a3cf9d06fb256d | 30,595 |
def diff_lists(list_a, list_b):
"""
Return the difference between list_a and list_b.
:param list_a: input list a.
:param list_b: input list b.
:return: difference (list).
"""
return list(set(list_a) - set(list_b)) | 3fac6e456827d567900d1c8dd14cb3fe7e4af0b7 | 30,597 |
from urllib.parse import urlparse
def deluge_is_url( torrent_url ):
"""
Checks whether an URL is valid, following `this prescription <https://stackoverflow.com/questions/7160737/python-how-to-validate-a-url-in-python-malformed-or-not>`_.
:param str torrent_url: candidate URL.
:returns: ``True`` ... | 4a4817dddb89800f8e9db7f80e31f58bff698c5b | 30,600 |
def to_dict(block,
keys=['hash', 'start', 'end', 'blockSize', 'version', 'prevHash',
'merkleRootHash', 'time', 'timestamp', 'nBits', 'nonce',
'nTransactions']):
"""
Return block attributes as dict
Similar to block.__dict__ but gets properties not just attribu... | aa594edc52500347fb515c81c9abe8308c81ce04 | 30,604 |
def popcount(x):
"""
Count ones in the binary representation of number x
Parameters
----------
x: Integer
The number to be counted
Returns
-------
cnt: Integer
The number of ones in the binary representation of number x
"""
cnt = 0
while x:
x -= x & ... | 2198546d57be313268ba5f2700a8f7bb9b13518d | 30,606 |
def origin(current, start, end, cum_extents, screen, moving):
"""Determine new origin for screen view if necessary.
The part of the DataFrame displayed on screen is conceptually a box which
has the same dimensions as the screen and hovers over the contents of the
DataFrame. The origin of the relative... | c679db7f9c68b28ce7c89069f267dc7013e8bdf6 | 30,607 |
def _swap_on_miss(partition_result):
"""
Given a partition_dict result, if the partition missed, swap
the before and after.
"""
before, item, after = partition_result
return (before, item, after) if item else (after, item, before) | 2cbf8ae30bc4b9efb449e0b0f63c78781cd09fd3 | 30,609 |
from operator import truediv
def distances_from_average(test_list):
"""Return a list of distances to the average in absolute terms."""
avg = truediv(sum(test_list), len(test_list))
return [round(float((v - avg) * - 1), 2) for v in test_list] | e59e404e824e35d99dbf8fb8f788e38b7a19cc03 | 30,611 |
def byte_display(size):
"""
Returns a size with the correct unit (KB, MB), given the size in bytes.
"""
if size == 0:
return '0 KB'
if size <= 1024:
return '%s bytes' % size
if size > 1048576:
return '%0.02f MB' % (size / 1048576.0)
return '%0.02f KB' % (size / 1024.0... | 35766e6ec839de9d928f8acf965e60de3a66b5cb | 30,613 |
def load_element_single(properties, data):
"""
Load element data with lists of a single length
based on the element's property-definitions.
Parameters
------------
properties : dict
Property definitions encoded in a dict where the property name is the key
and the property data type ... | cc82704592cd2c5e98864cf59b454d2d7551bba0 | 30,618 |
def get_preresolution(file: str) -> int:
"""
Read pre file and returns number of unknowns
:param file: pre file
:return: number of unknowns
"""
with open(file) as f:
content = f.readlines()
ind = [idx for idx, s in enumerate(content) if '$DofData' in s][0]
tmp = content[ind + 5]... | 8084c37792246bef5f6fc9da43e30da9f4902cbc | 30,623 |
def is_recovered(alleles_in_probands, alleles_in_pool):
"""True if all the variants found in the proband(s) are also found in the pool.
This tends to result in multi-alleleic sites not getting filtered in many cases.
alleles_in_probands, alleles_in_pool: iterable consisting of items that can be compared in... | 68e978f63bcfc899a0a8c278d17d418d6423d674 | 30,624 |
from typing import Union
import json
def load_json_from_file(path: str) -> Union[dict, list, str, int]:
"""Load JSON from specified path"""
with open(path, 'r', encoding='utf-8') as infile:
return json.load(infile) | c8ba755c62ea4ab6fe74b4571034967ce610afdf | 30,626 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.