content
stringlengths 39
9.28k
| sha1
stringlengths 40
40
| id
int64 8
710k
|
---|---|---|
def s3_split_path(s3_path):
"""Given `s3_path` pointing to a bucket, directory path, and optionally an
object, split the path into its bucket and object remainder components.
Parameters
----------
s3_path : str
Full s3 path to a directory or object, including the bucket prefix,
e.g. s3://pipeline-outputs/batch-1/acs/j8cb010b0/process.txt
Returns
------
(bucket_name, object_name) : tuple(str, str)
e.g. ("s3://pipeline-outputs", "batch-1/acs/j8cb010b0/process.txt")
"""
if s3_path.startswith("s3://"):
s3_path = s3_path[5:]
parts = s3_path.split("/")
bucket_name, object_name = parts[0], "/".join(parts[1:])
return bucket_name, object_name
|
503079491b21e36b43411a864186dba28bde7479
| 549,626 |
from typing import List
def create_binary_list_from_int(number: int) -> List[int]:
"""Creates a list of the binary representation of a positive integer
Args:
number: An integer
Returns:
The binary representation of the provided positive integer number as a list.
"""
if number < 0 or type(number) is not int:
raise ValueError("Only Positive integers are allowed")
return [int(x) for x in list(bin(number))[2:]]
|
b795b5edc1dd502aad7896ed7c489654f673dad3
| 614,814 |
def unique(in_list: list) -> list:
"""Return a list with only unique elements."""
return list(set(in_list))
|
1e69b8db08da561b4153100c132bbce1c149e31c
| 376,833 |
def fun_as_arg(x, *args):
"""``fun_as_arg(x, fun, *more_args)`` calls ``fun(x, *more_args)``.
Use case::
fmin(cma.fun_as_arg, args=(fun,), gradf=grad_numerical)
calls fun_as_args(x, args) and grad_numerical(x, fun, args=args)
"""
fun = args[0]
more_args = args[1:] if len(args) > 1 else ()
return fun(x, *more_args)
|
615fa33fd0dbbbe8b9ef041a8c47121a69cca05d
| 273,035 |
def validate(contacts, number):
"""
The validate() function accepts the contacts array and number as arguments and checks to see if the number inputted is in the range of the contacts array. It returns a number inputted by the user within that range.
"""
while number<1 or number>len(contacts):
print()
print("Please enter a number from 1 to ", len(contacts))
number = int(input("Number: "))
return number
|
f9dc7b4287e9f0bdc7c6da8240c49e0f4438c6c8
| 675,316 |
import torch
def sample_gumbel(shape, eps=1e-10):
"""
NOTE: Stolen from https://github.com/pytorch/pytorch/pull/3341/commits/327fcfed4c44c62b208f750058d14d4dc1b9a9d3
Sample from Gumbel(0, 1)
based on
https://github.com/ericjang/gumbel-softmax/blob/3c8584924603869e90ca74ac20a6a03d99a91ef9/Categorical%20VAE.ipynb ,
(MIT license)
"""
U = torch.rand(shape).float()
return -torch.log(eps - torch.log(U + eps))
|
aef89f95c7324f30c57737ba69f50cb0e0cd4755
| 572,307 |
def parse_ucsc_file_index(stream, base_url):
"""Turn a UCSC DCC files.txt index into a dictionary of name-value pairs
"""
file_index = {}
for line in stream:
filename, attribute_line = line.split('\t')
filename = base_url + filename
attributes = {}
for assignment in attribute_line.split(';'):
name, value = assignment.split('=')
attributes[name.strip()] = value.strip()
file_index[filename] = attributes
return file_index
|
2d74bae9c7f2584ff8d859c8d2781faa3f6631b5
| 704,142 |
from typing import Sequence
def j(s: Sequence, sep=', ') -> str:
""" #### Returns string of joined sequence items.
Yes, it is just a shorter version of
`', '.join(sequence)`
"""
return sep.join(s)
|
431c8998ab16ccbd2dddd4913b8297bec21cf964
| 250,698 |
import torch
def gmof(x: torch.Tensor, sigma: float) -> torch.Tensor:
"""
Geman-McClure error function.
Args:
x (torch.Tensor): Raw error signal.
sigma (float): Robustness hyperparameter
Returns:
torch.Tensor: Robust error signal
"""
x_squared = x ** 2
sigma_squared = sigma ** 2
return (sigma_squared * x_squared) / (sigma_squared + x_squared)
|
ab4abe9fd25ed0766fd978d2c0e2d60817599018
| 395,324 |
def median(iterable):
"""
Compute the median value in the given iterable - which must be finite and non-empty.
"""
values = sorted(iterable)
le = len(values)
assert le
if le % 2 == 1:
return values[le // 2]
else:
return (values[le // 2 - 1] + values[le // 2]) / 2
|
070e0e9c2a40c01b98451dc947fc342809e0d55b
| 156,525 |
def above_freezing(celsius: float) -> bool:
"""Return True iff temperature celsius degrees is above freezing.
>>> above_freezing(5.2) True
>>> above_freezing(-2) False
"""
return celsius > 0
|
6f564672a297f19c078ff64125f11bb57b91d12f
| 481,795 |
import re
def matches_reg_ex(val: str, reg_ex: str) -> bool:
"""
Check if the provided argument matches the provided regular expression
:param val: value to check
:param reg_ex: regular expression string to compare the value to
:return: boolean flag indicating a match
"""
return bool(re.fullmatch(reg_ex, val))
|
d4e9a707b4d9f760024d928d965ae5ef4a63443c
| 541,626 |
def PO2_Calc(KO2, tO2, Kr, I, qO2):
"""
Calculate PO2.
:param KO2: oxygen valve constant [kmol.s^(-1).atm^(-1)]
:type KO2 : float
:param tO2: oxygen time constant [s]
:type tO2 : float
:param Kr: modeling constant [kmol.s^(-1).A^(-1)]
:type Kr : float
:param I: cell load current [A]
:type I : float
:param qO2: molar flow of oxygen [kmol.s^(-1)
:type qO2 : float
:return: PO2 [atm] as float
"""
try:
result = ((1 / KO2) / (1 + tO2)) * (qO2 - Kr * I)
return result
except (TypeError, ZeroDivisionError):
print(
"[Error] PO2 Calculation Failed (KO2:%s, tO2:%s, Kr:%s, I:%s, qO2:%s)" %
(str(KO2), str(tO2), str(Kr), str(I), str(qO2)))
|
425d379d6818a083cc05a905e879ffd94668c14b
| 594,163 |
def get_river_config(fileName, noisy=False):
"""
Parse the rivers namelist to extract the parameters and their values.
Returns a dict of the parameters with the associated values for all the
rivers defined in the namelist.
Parameters
----------
fileName : str
Full path to an FVCOM Rivers name list.
noisy : bool, optional
Set to True to enable verbose output. Defaults to False.
Returns
-------
rivers : dict
Dict of the parameters for each river defind in the name list.
Dictionary keys are the name list parameter names (e.g. RIVER_NAME).
"""
f = open(fileName)
lines = f.readlines()
rivers = {}
for line in lines:
line = line.strip()
if not line.startswith('&') and not line.startswith('/'):
param, value = [i.strip(",' ") for i in line.split('=')]
if param in rivers:
rivers[param].append(value)
else:
rivers[param] = [value]
if noisy:
print('Found {} rivers.'.format(len(rivers['RIVER_NAME'])))
f.close()
return rivers
|
5751456eda34c8f9fc2c134515cc420b156c2d17
| 670,378 |
def _getNextCurrControl(curr_control, res_control, max_control):
"""Compute the next possible control instruction
Args:
curr_control (list of int|str): last executed control
res_control (list of int|str): resolution control
max_control (list of int|str): maximum control
Returns:
int list: the next possible control
None: no more possible instruction
"""
new_current_control = []
for c1, c2, c3 in zip(curr_control, res_control, max_control):
new_c1 = int(c1) + int(c2)
if new_c1 > int(c3):
return
else:
new_current_control.append(new_c1)
return new_current_control
|
22d336354d55787ad5e425a46ab8cf9e08c25f11
| 575,293 |
def make_granular_marking(marking_defs, selectors):
"""
Makes a granular marking reference from STIX. This goes in the granular_markings list of an object
example result:
"granular_markings": [
{
"marking_ref": "SOME UUID THAT IS VALID BUT NOT REALLY",
"selectors": ["description", "labels"]
}
],
"""
return {"marking_ref": marking_defs, "selectors": selectors}
|
aca1e45ab17c3af6a5b8fb0093cba98693b6a535
| 69,913 |
import random
import string
def random_numeric_token(length):
"""Generates a random string of a given length, suitable for typing on a numeric keypad.
"""
return ''.join(random.choice(string.digits) for i in range(length))
|
b63ac76ff32b86d01fb3b74772340cf1ebfcc321
| 17,295 |
def to_dict(*iterables, **kwargs):
"""
Returns a dictionary that contains all passed iterables and keyword arguments
"""
data = {}
for iterable in iterables:
data.update(dict(iterable))
data.update(**kwargs)
return data
|
7b7ecf5924619eb35097234b2fce9db72b05079b
| 557,703 |
def substitute(in_str, substitutions):
"""Substitute words in a string according to a dict.
Parameters
----------
in_str : str
String to apply substitutions to.
substitutions : dict
Key-value pairs where key = word to substitute, value = new word.
Returns
-------
out_str : str
String with relevant substitutions applied.
"""
out_str = ''
# Cycle through all words in string
for word in in_str.split():
# If substitutions specifies a substitution for this word, substitute it
if word.lower() in substitutions:
out_str += substitutions[word.lower()] + ' '
# Otherwise carry over the same word
else:
out_str += word + ' '
return out_str
|
580ac8f704196002e7159357987f45871dfbe826
| 362,096 |
def total_time(boutlist):
"""Takes list of times of bouts in seconds, returns it's last item representing the total trial time."""
total_time = boutlist[-1]
return total_time
|
ef330f460522fad513acd37c115fbcd8eaf0dad6
| 600,589 |
def pad_lists(lists, pad_token=0):
""" Pads lists with trailing zeros to make them all the same length. """
max_list_len = max(len(l) for l in lists)
for i in range(len(lists)):
lists[i] += [pad_token] * (max_list_len - len(lists[i]))
return lists
|
2808d1fb39d033350ed2bfa34356e57c7f2ba9b8
| 608,078 |
def link_with_urlparameters(request, **kwargs):
"""Takes the current URL path and replaces, updates or removes url query parameters based on the passed in named arguments, an argument of None or empty string will remove the parameter from the URL. Existing parameters in the full path which are not one of the named argument will be left untouched."""
urlparams = request.GET.copy()
for parametername, value in kwargs.items():
urlparams[parametername] = value
if value in (None, ""):
del urlparams[parametername]
return request.path + (f"?{urlparams.urlencode()}" if urlparams else "")
|
50c706e06dc25836d7c84569ca79c0d2de09612d
| 528,154 |
def _extract_fields_from_row(row, element):
"""Pluck data from the provided row and element."""
row_data = []
fields = row.find_all(element)
for raw_field in fields:
field = raw_field.text.strip()
row_data.append(field)
return row_data
|
081473db76f139eab4687b60f309801b40f1c69a
| 677,035 |
import re
def parse_table(table_lines):
"""Parse lines into a table.
Table example:
```txt
ID# Name Designation IAU/aliases/other
------- ---------------------------------- ----------- -------------------
0 Solar System Barycenter SSB
1 Mercury Barycenter
```
:param table_lines: A list of strings that make up a table
:return: A list of dictionaries where the keys are the header names and the values are the stripped contents for
each table row.
"""
dash_line = table_lines[1]
matches = list(re.finditer(r"(-+\s)", dash_line))
name_line = table_lines[0]
names = []
for m in matches:
name = name_line[m.start():m.end() - 1].strip()
names.append(name)
table = []
for line in table_lines[2:]:
item = {}
for i, m in enumerate(matches):
content = line[m.start():m.end() - 1].strip()
item[names[i]] = content
table.append(item)
return table
|
7bb45501cd13ff19105d700cb90c29ee5c136cbc
| 671,124 |
import torch
def from_center_representation(center_bboxes):
"""
transform bbox from center representation to border representation
:param center_bboxes: tensor of bbox like torch.tensor([center_x, center_y, length, width])
:return: tensor of bbox like torch.tensor([left, right, bottom, top])
"""
shape = center_bboxes.shape
batch_size = center_bboxes.shape[0]
x_center = center_bboxes[..., 0]
y_center = center_bboxes[..., 1]
half_length = center_bboxes[..., 2] / 2
half_width = center_bboxes[..., 3] / 2
left = x_center - half_length
right = x_center + half_length
bottom = y_center - half_width
top = y_center + half_width
_seq = (left, right, bottom, top)
if len(shape) == 3:
return torch.cat(_seq, 1).reshape(batch_size, 4, -1).transpose(2, 1)
elif len(shape) == 2:
return torch.cat(_seq, 0).reshape(4, -1).transpose(1, 0)
else:
return torch.Tensor(_seq)
|
cf877db86fa531409c90ec884c354f41485db82f
| 316,956 |
def parseFile(input_file):
"""
Take the output from calc_gr.tcl and parse it, returning a list of series
in the file.
"""
# Read in file
f = open(input_file,'r')
contents = f.readlines()
f.close()
# Find line that contains data (it will all be on one line, with the series
# separated by { SERIES }.
start_index = contents.index("BEGIN\n") + 1
data = contents[start_index]
# Create list of series data
series_list = data.split("{")
series_list = ["".join([x for x in s if x != "}"]) for s in series_list]
series_list = [[float(x) for x in s.split()] for s in series_list]
# Strip blank first line and last "frames processed" entries
series_list.pop(0)
series_list.pop(-1)
return series_list
|
8e7691a8b910e40fe20d79151d4b809aaddd3e71
| 157,024 |
def dom_level(dns_name):
"""
Get domain level
"""
return dns_name.count(".")
|
20d54dd98378f377485149bbb9854b6d2001ab55
| 62,966 |
def _make_choices_from_int_list(source_list):
"""
Converts a given list of Integers to tuple choices.
Returns a dictionary containing two keys:
- max_length: the maximum char length for this source list,
- choices: the list of (value, value) tuple choices.
"""
_choices = []
for value in source_list:
_choices.append((value, value))
return {'max_length': len(_choices)/10+1, 'choices': tuple(_choices)}
|
49f49946512249d6fb879fc31aac49eb55cdfc2e
| 665,595 |
def __make_threephase_node_name(node_name_prefix, phase):
"""
Returns a node name with "phase" sufix and trailing whitespaces (6
characters).
"""
new_name = node_name_prefix + phase
whitespaces = 6 - len(new_name)
new_name = new_name + (" " * whitespaces)
return new_name
|
580c838dace828c4fe2d35d148ddf2da6aa57a0a
| 26,143 |
import re
def camel_case_split(text: str) -> list:
"""camel_case_split splits strings if they're in CamelCase and need to be not Camel Case.
Args:
str (str): The target string to be split.
Returns:
list: A list of the words split up on account of being Camel Cased.
"""
return re.findall(r"[A-Z](?:[a-z]+|[A-Z]*(?=[A-Z]|$))", text)
|
bcbac4f7ba01d133b84fb1275743bea278d64c4c
| 679,420 |
def set_control_user(user_id, prefix='', rconn=None):
"""Set the user who has current control of the telescope and resets chart parameters.
Return True on success, False on failure"""
if user_id is None:
return False
if rconn is None:
return False
try:
rconn.set(prefix+'view', "100.0")
rconn.set(prefix+'flip', '')
rconn.set(prefix+'rot', "0.0")
result = rconn.set(prefix+'control_user_id', user_id)
except:
return False
if result:
return True
return False
|
29fd2981f00b00f89af6220a26ac20efe5948dca
| 613,431 |
def format_password(salt, hash):
"""
Format a password entry for the SCryptPasswordHasher.
"""
algorithm = "scrypt"
Nlog2 = 15
r = 8
p = 1
return "%s$%d$%d$%d$%s$%s" % (algorithm, Nlog2, r, p, salt, hash)
|
0b627a0f77f42cdabfd4801c3a6ced9cc86d99ef
| 140,931 |
def str_is_empty_or_none(str_field: str) -> bool:
"""
Verifies whether a string is empty or None.
Args:
str_field (str): String to validate.
Returns:
bool: Evaluation result.
"""
return str_field is None or not str_field or str_field.isspace()
|
3e1a40dff415e5968669e36df61e5a50727f91db
| 648,625 |
def load_raw_image(path):
"""
Load raw image in binary format from specified path.
Also see :py:func:`.save_raw_image`.
:param str path: File path.
:return: Raw image
:rtype: str
"""
with open(path, 'rb') as f:
return f.read()
|
96ef7e9a3fca0aa7115b957c75d87d2bb9c7825f
| 128,232 |
def convert_none_to_empty_dict(value):
"""Convert the value to an empty dict if it's None.
:param value: The value to convert.
:returns: An empty dict if 'value' is None, otherwise 'value'.
"""
return {} if value is None else value
|
5eb3e82b026fc7eb95123df2a8a63bc913bb3539
| 196,127 |
def count_covered_examples(matrix, vocabulary_size):
"""Returns the number of examples whose added phrases are in the vocabulary.
This assumes the vocabulary is created simply by selecting the
`vocabulary_size` most frequent phrases.
Args:
matrix: Phrase occurrence matrix with the most frequent phrases on the
left-most columns.
vocabulary_size: Number of most frequent phrases to include in the
vocabulary.
"""
# Ignore the `vocabulary_size` most frequent (i.e. leftmost) phrases (i.e.
# columns) and count the rows with zero added phrases.
return (matrix[:, vocabulary_size:].sum(axis=1) == 0).sum()
|
c0fa756e255af8f203079a5d63b24c5b4a6f479a
| 567,079 |
def replace_headers(request, replacements):
"""
Replace headers in request according to replacements. The replacements
should be a list of (key, value) pairs where the value can be any of:
1. A simple replacement string value.
2. None to remove the given header.
3. A callable which accepts (key, value, request) and returns a string
value or None.
"""
new_headers = request.headers.copy()
for k, rv in replacements:
if k in new_headers:
ov = new_headers.pop(k)
if callable(rv):
rv = rv(key=k, value=ov, request=request)
if rv is not None:
new_headers[k] = rv
request.headers = new_headers
return request
|
4e7776081cc7b66b04ea31a55b8a62d38d13e990
| 512,285 |
def nlines_back(n):
"""
return escape sequences to move character up `n` lines
and to the beginning of the line
"""
return "\033[{0}A\r".format(n+1)
|
ad2686e8ae804b267d3d3e3922d558cefae69893
| 272,700 |
def yes_or_no(question):
"""
Ask to the user a question. Possible answer y (yes) or n (no)
:param question: str
:return: True or False depending on the choice of the user
"""
while "The answer is invalid":
reply = str(input(question+' (y/n): ')).lower().strip()
if reply[:1] == 'y':
return True
if reply[:1] == 'n':
return False
|
73bb15804509f80ad785c73d9e160e1bc43ae833
| 330,983 |
def divide_durations(d1, d2):
"""Divide one timedelta by another."""
return d1.total_seconds() / d2.total_seconds()
|
f417bc7213cf699cb9dea289e5a75bb471e5128d
| 145,841 |
def process_hour_group(df):
"""
Prepare data to make hourly plots
:param DataFrame df: Pandas DataFrame for the data to process
:return: Processed Pandas DataFrame
"""
df_hour = df.copy()
df_hour['hour'] = df.index.hour
df_hour['isweekday'] = df.index.dayofweek < 5
return df_hour
|
91bf84ea88b43a8fa4c7e5df4236827a06c9cc4b
| 373,735 |
def get_watch_key(timestamp):
"""Generates watch keyname for note"""
return "watch_%s" % timestamp
|
bcc60c24c3c9bd2830d21f1cb298535fb4ebbdd7
| 195,914 |
def enumerate_bases(bases):
"""
Convert the given tuple of multiple sequence alignment bases (any
characters) into a tuple of integers such that all rows with the same base
share the same integer based on the order each base was seen.
>>> enumerate_bases(("A", "A", "C", "C"))
(0, 0, 1, 1)
>>> enumerate_bases(("C", "C", "A", "A"))
(0, 0, 1, 1)
>>> enumerate_bases(("C", "-", "T", "C"))
(0, 1, 2, 0)
>>> enumerate_bases(("A", "C", "T", "G"))
(0, 1, 2, 3)
>>> enumerate_bases(("A", "A", "A", "A"))
(0, 0, 0, 0)
"""
current_index = 0
base_to_index = {}
integers = []
for base in bases:
if base not in base_to_index:
base_to_index[base] = current_index
current_index += 1
integers.append(base_to_index[base])
return tuple(integers)
|
df8f66314468de16823c23c3c37a4f12e35d301a
| 116,543 |
def is_upside_down_text_angle(angle: float, tol: float = 3.) -> bool:
"""Returns ``True`` if the given text `angle` in degrees causes an upside
down text in the :ref:`WCS`. The strict flip range is 90° < `angle` < 270°,
the tolerance angle `tol` extends this range to: 90+tol < `angle` < 270-tol.
The angle is normalized to [0, 360).
Args:
angle: text angle in degrees
tol: tolerance range in which text flipping will be avoided
"""
angle %= 360.
return 90. + tol < angle < 270. - tol
|
9a964dbfed0fe341b9ccb99a783e8262c0af6ca3
| 81,849 |
def sort_by_length(items, reverse=False):
"""
sorts the given list of strings by length of items.
:param list[str] items: list of strings to be sorted.
:param bool reverse: sort by descending length.
defaults to False if not provided.
:rtype: list[str]
"""
return sorted(items, key=len, reverse=reverse)
|
905b4332b5bb37041b9adb164f6383ac9adeb1e1
| 192,604 |
def identity_matrix(dim):
"""Construct an identity matrix.
Parameters
----------
dim : int
The number of rows and/or columns of the matrix.
Returns
-------
list of list
A list of `dim` lists, with each list containing `dim` elements.
The items on the "diagonal" are one.
All other items are zero.
Examples
--------
>>> identity_matrix(4)
[[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]]
"""
return [[1. if i == j else 0. for i in range(dim)] for j in range(dim)]
|
dd37f0c7df41478e23dd26df727341a37a201ec1
| 7,697 |
def deping(target: str) -> str:
"""Insert a 0-length space in target, so as not to ping people."""
if len(target) < 2:
return target
return target[:1] + '\u2060' + target[1:]
|
fa332bc2a1f54e59f047ada9a30ddfbe11a14a9f
| 174,385 |
import re
def process_ref(paper_id):
"""Attempt to extract arxiv id from a string"""
# if user entered a whole url, extract only the arxiv id part
paper_id = re.sub("https?://arxiv\.org/(abs|pdf|ps)/", "", paper_id)
paper_id = re.sub("\.pdf$", "", paper_id)
# strip version
paper_id = re.sub("v[0-9]+$", "", paper_id)
# remove leading arxiv, i.e., such that paper_id=' arXiv: 2001.1234' is still valid
paper_id = re.sub("^\s*arxiv[:\- ]", "", paper_id, flags=re.IGNORECASE)
return paper_id
|
a1c817f1ae7b211973efd6c201b5c13e1a91b57b
| 706,817 |
from typing import List
from typing import Dict
def get_required_tag_value(tag_set: List[Dict[str, str]], key: str) -> str:
"""Get a tag value from a TagSet. Raise ValueError if the key is not present.
Args:
tag_set: list of dicts, each of which contains keys 'Key' and 'Value'.
key: tag key string
Returns:
tag value string
Raises:
ValueError if key is not present in tag_set
"""
for tag in tag_set:
tag_key, tag_value = tag["Key"], tag["Value"]
if tag_key == key:
return tag_value
raise ValueError(f"Required tag key {key} not found in {tag_set}")
|
b8e62834d4ed71b29414173f058f873e4edac0cb
| 538,082 |
def convert(txt):
"""
Convert numeric elements to float or complex if possible.
success, value = convert(txt)
If txt can be converted into a number, return success = True and the
converted value in value. Otherwise return success = False, and value
contains the input argument.
"""
try:
res = float(txt)
return True, res
except:
pass
try:
res = complex(txt)
return True, res
except:
return False, txt
|
74b3e26c5081720fb01e153cf3beb3a3ba3ecfa3
| 304,432 |
from typing import Optional
import torch
def get_device(device: Optional[str] = None) -> torch.device:
"""Selects a device to perform an NST on.
Args:
device: If ``str``, returns the corresponding :class:`~torch.device`. If
``None`` selects CUDA if available and otherwise CPU. Defaults to ``None``.
"""
if device is None:
device = "cuda" if torch.cuda.is_available() else "cpu"
return torch.device(device)
|
3ca5272ff3181c855e696335b26e7105d0404080
| 577,127 |
def getBundleKey(bundlePath):
"""
Return all parts of a bundle's "key" as used in a timestamp file,
given its full filename.
>>> getBundleKey("/bundleinfo/tor-browser/win32/some-file-name.txt")
'/bundleinfo/tor-browser/win32/'
"""
# No, we can't use "os.path.directory" or "os.path.split". Those are
# OD-dependent, and all of our paths are in Unix format.
idx = bundlePath.rindex("/")
return bundlePath[:idx+1]
|
4f50ba4d87a4c2f326cf7924c71fc5da7f01d346
| 114,771 |
def read_coverage(cov_file):
"""Determine the total number of bases covered.
Reads in the given coverage file and computes the total number of
bases covered, returning that value as an int.
"""
header = cov_file.next()
footprint = 0
for line in cov_file:
(chromosome, start, end, cov) = line.split("\t")
start = int(start)
end = int(end)
footprint += end - start
return footprint
|
d0cf2dd12d4fbc768fee890aa0f0efa6182b0e15
| 452,263 |
def version_higher_or_equal(v1, v2):
""" Check if v1 is higher than or equal to v2.
"""
t1 = tuple(int(val) for val in v1.split('.'))
t2 = tuple(int(val) for val in v2.split('.'))
return t1 >= t2
|
cc1c974453b2c2b1f1dbea0da82f910f138d698c
| 314,262 |
import re
import yaml
def load_recipe_yaml_str_no_classes(recipe_yaml_str: str) -> str:
"""
:param recipe_yaml_str: YAML string of a SparseML recipe
:return: recipe loaded into YAML with all objects replaced
as a dictionary of their parameters
"""
pattern = re.compile(r"!(?P<class_name>(?!.*\.)[a-zA-Z_][a-zA-Z^._0-9]+)")
classless_yaml_str = pattern.sub(r"OBJECT.\g<class_name>:", recipe_yaml_str)
return yaml.safe_load(classless_yaml_str)
|
7b2bff3f55df84fe65da8a67397bb68fb9660ea9
| 40,552 |
def map_int(to_int) -> int:
"""Maps value to integer from a string.
Parameters
----------
to_int: various (usually str)
Value to be converted to integer
Returns
-------
mapped_int: int
Value mapped to integer.
Examples
--------
>>> number_one = "1"
>>> error_value = "will cause error"
>>> one_to_float = map_int(number_one) # will convert to 1
>>> error_to_float = map_int(error_value) # will cause exception
"""
try:
mapped_int = int(to_int)
except ValueError:
raise ValueError("Integer Value Expected Got '{}'".format(to_int))
return mapped_int
|
764c89ffe034bc6613d9edbd5c130298265918f7
| 348,596 |
import click
def confirm(text, color, *args, **kwargs):
"""
Wrapper around click.confirm that adds minor styling to the prompt.
"""
if color:
prefix = click.style(":: ", bold=True, fg="blue")
styled = click.style(text, bold=True)
else:
prefix = ":: "
styled = click.unstyle(text)
return click.confirm(prefix + styled, *args, **kwargs)
|
f225efdd080d30496dd6fa30e85c0fded6716874
| 321,190 |
def wrap(headr, data):
"""
Input:
headr -- text of html field
data -- text to be wrapped.
Returns a corresponding portion of an html file.
"""
return '<%s>%s</%s>' % (headr, data, headr)
|
d956bef0e223d930d5f8b66b76312046a0024d66
| 40,589 |
import random
def give_some_candies_or_not(tot):
"""
tot : string
trick or treat!
return:
# of candies: int (1~50) if treat
None: None if trick
"""
num_of_candies = random.randint(1, 50)
if tot == 'treat':
return num_of_candies
else:
return None
|
87653efb401b13fad90b5ad4adfd27cda4750598
| 367,792 |
def applianceSystemStoragePath(config):
"""
Returns the path to the internal appliance persistent storage.
"""
return config['storage.system.path']
|
2af2ec4ccd4a9999b00370c0cf251c293053a6eb
| 639,446 |
import networkx
def BuildGraph(aligned, cutoff, coverage_req=0):
"""Takes the BLAST output and represents it as a graph using the following rules:
Each sequence is represented as a node.
Each alignment between sequences is represented as an unweighted,
undirected edge."""
#hold=set()
#hold2=set()
graph=networkx.Graph()
for pair in aligned.keys():
query,subject=pair
if graph.has_node(subject)==False:
graph.add_node(subject)
if graph.has_node(query)==False:
graph.add_node(query)
if aligned[pair].identity>=cutoff and aligned[pair].covs>coverage_req: #aligned[pair].length>100:
graph.add_edge(subject, query)
return graph
|
a95a9eed4b20fe0e7b514965739e5a86d43e9be7
| 493,585 |
def is_age(age):
"""
A simple age validator.
Should be an integer, that is all
"""
valid = False
# Remove excess spaces
age_stripped = age.strip()
if str(int(age_stripped)) == age_stripped:
valid = True
return valid
|
ede549542942bccda8ada8354365493ad8152c06
| 540,498 |
def merge_the_tools(string, k):
"""
Takes in a string of length n and an integer k
always multiple of n, and returns k subsets with
unique characters.
Parameters
----------
string : string
Input string.
k : int
Factor of len(string) to cut into subsets.
Returns
-------
subsets : list[string]
List of k subsets.
"""
subsets = []
for i in range(k):
subsets.append(string[int(i * k) : int((i + 1) * k)])
for subset in subsets:
temp = list(dict.fromkeys(list(subset)))
subset = ""
for char in temp:
subset += char
print(subset)
return subsets
|
a91a0870b004f78bae2ef183042261c8bfd4db4b
| 270,919 |
from typing import Tuple
def is_bare_tuple(typ) -> bool:
"""
Test if the type is `typing.Tuple` without type args.
>>> from typing import Tuple
>>> is_bare_tuple(Tuple[int, str])
False
>>> is_bare_tuple(Tuple)
True
"""
return typ in (Tuple, tuple)
|
05c151cc7542f8132f9bacddae8ee574778c7c6c
| 483,459 |
def bin_to_dec( clist , c , tot=0 ):
"""Implements ordinary binary to integer conversion if tot=0
and HEADLESS binary to integer if tot=1
clist is a list of bits; read c of them and turn into an integer.
The bits that are read from the list are popped from it, i.e., deleted
Regular binary to decimal 1001 is 9...
>>> bin_to_dec( ['1', '0', '0', '1'] , 4 , 0 )
9
Headless binary to decimal [1] 1001 is 25...
>>> bin_to_dec( ['1', '0', '0', '1'] , 4 , 1 )
25
"""
while (c>0) :
assert ( len(clist) > 0 ) ## else we have been fed insufficient bits.
tot = tot*2 + int(clist.pop(0))
c-=1
pass
return tot
|
9aec0835251c52a00ad439e4ba72a7a01ced5196
| 22,442 |
def parse_comma_list(args):
"""Convert a comma-separated list to a list of floating-point numbers."""
return [float(s.strip()) for s in args.split(',')]
|
6c57db8379a2a5a4b410ca3c6509d4fc00b33b59
| 188,003 |
from typing import Sequence
def flatten(x: Sequence) -> list:
"""
Recursively flatten a list of lists (or tuples). Empty lists get replaced with "None" instead of completely vanishing.
"""
retme = []
for thing in x:
if isinstance(thing, (list, tuple)):
if len(thing) == 0:
retme.append(None)
else:
retme += flatten(thing)
else:
retme.append(thing)
return retme
|
b3c1357241e212e19faebd396b63cc199215ec89
| 222,365 |
def test_depends(func):
"""Decorator to prevent a test being executed in individual mode"""
def invalid(self, test):
if self.test_individual:
test.description = "Invalid"
return test.DISABLED("This test cannot be performed individually")
else:
return func(self, test)
invalid.__name__ = func.__name__
invalid.__doc__ = func.__doc__
return invalid
|
4b2db29fc8c0a30ec3a4ec6c3fb93ed958f0094e
| 8,113 |
def get_device(model):
"""
Function to find which device is model on
Assumption : model is on single device
:param model:
:return: Device on which model is present
"""
return next(model.parameters()).device
|
b660e88f1f8c29f0360d899af2741827ba5b8b18
| 441,522 |
import decimal
def _as_decimal(value):
"""
Converts the value to a `Decimal` if it is not already, or returns the existing value if it is a `Decimal`, or
returns `Decimal(0)` if the existing value is `None`.
:param value: The value to cast/convert
:type value: int | long | decimal.Decimal | NoneType
:return: The value as a `Decimal`
:rtype: decimal.Decimal
"""
return value if isinstance(value, decimal.Decimal) else decimal.Decimal(value or '0')
|
913fffe7fb08648b3974338e9e6a9c5b9a878452
| 428,784 |
from typing import Tuple
import math
def shear_asws(bw: float, d: float, fck: float, g_c: float, fyk: float, g_s: float, cott: float, ved: float, alpha: float) -> Tuple[float, float]:
"""Calculates the design shear reinforcement
Args:
bw (float): beam width
d (float): beam depth
fck (float): concrete compressive strength
g_c (float): concrete partial safety coefficient
fyk (float): steel strength
g_s (float): steel partial safety coefficient
cott (float): truss inclination (cot)
ved (float): design shear force
alpha (float): coefficient
Returns:
Tuple[float, float]: (shear reinforcement (Asw/s), maximum shear force Vrd.max)
"""
z = 0.9 * d
niu = 0.6*(1.0-fck/250)
vrd_max = bw * z * niu * fck / g_c * 1000.0 / (cott + 1.0/cott)
asw_s = ved / z / fyk * g_s / cott / 1000.0 if vrd_max >= ved else math.nan
return asw_s, vrd_max
|
cfb73c2f6d852af488826a92b62e8206ca5037d3
| 138,644 |
def as_dict(original_names, names):
"""Map slugs to original names {slug-name: orig-name, ...}"""
return dict(zip(names, original_names))
|
afd687185ab9d966006ab088e2ab5a63928d41cf
| 382,048 |
def get_url_attrs(url, attr_name):
"""
Return dictionary with attributes for HTML tag, updated with key `attr_name` with value `url`.
Parameter `url` is either a string or a dict of attrs with the key `url`.
Parameter `attr_key` is the name for the url value in the results.
"""
url_attrs = {}
if isinstance(url, str):
url = {"url": url}
url_attrs.update(url)
url_attrs[attr_name] = url_attrs.pop("url")
return url_attrs
|
4b341489a3f77965d257bf5c5fae15ca88b6ad68
| 370,224 |
def plusMinus(arr):
"""Function that calculates the ratio of positive, negative and 0 values
in a given array"""
l = len(arr)
p = 0
n = 0
z = 0
for val in arr:
if val > 0:
p += 1
elif val < 0:
n += 1
else:
z += 1
p_ratio = round(p/l, 6)
n_ratio = round(n/l, 6)
z_ratio = round(z/l, 6)
print(p_ratio)
print(n_ratio)
print(z_ratio)
return "Done"
|
a4ed90950b72c4f0c797a48c4ff4782c5ac608f3
| 615,110 |
import sqlite3
def cn(DB):
"""Return the cursor and connection object."""
conn = sqlite3.connect(DB)
c = conn.cursor()
return (c,conn)
|
76abbec283d45732213f8b94031242146cdb4ee0
| 1,043 |
def do_upper(s):
"""
Convert a value to uppercase.
"""
return s.upper()
|
86dd07e49aab9d6d99c3f5bd17fdcc64080fc13d
| 319,275 |
def copy_as_new(dictionary, fields):
"""
Copies the dictionary to a new one. Copies only the fields specified.
:param dictionary:
:param fields:
:return:
"""
out = {}
for f in fields:
out[f] = dictionary[f]
return out
|
47ae1c79353a1bb9b1bf035d5c6b1b792e8421b8
| 146,543 |
def roundToNearest(number, nearest):
""" Rounds a decimal number to the closest value, nearest, given
Arguments:
number: [float] the number to be rounded
nearest: [float] the number to be rouned to
Returns:
rounded: [float] the rounded number
"""
A = 1/nearest
rounded = round(number*A)/A
return rounded
|
5f3974611b529e93ae8157182ff8b7dbc100a234
| 7,354 |
from pathlib import Path
def file_ext(fname):
"""Gets file extension"""
ext = Path(str(fname)).suffix.strip("'")
return ext
|
85702a22313c59bd9f641692dc8728979f01f685
| 506,393 |
def out_name(filename_input):
"""Retrieves appropriate filename to match json file to original file
Args:
filename_input (string): name of original file (ex. folder/file.csv)
Returns:
string: filename
"""
filename_data = filename_input.split("/")[1]
return filename_data.split(".")[0]
|
0dc901e35d9149132b23fca4e9339cd8db56e2d1
| 232,778 |
import requests
import warnings
def request_fulltextXML(ext_id):
"""
Requests a fulltext XML document from the ePMC REST API. Raises a warning if this is not
possible
Parameters
----------
ext_id : String
ePMC identifier used to retrieve the relevant entry. Format is prefix of 'PMC'
followed by an integer.
Returns
-------
r : `Requests.Response <http://docs.python-requests.org/en/master/api/#requests.Response>`_
The response to the query served up by the requests package.
"""
request_url = "https://www.ebi.ac.uk/europepmc/webservices/rest/" + ext_id + "/fullTextXML"
r = requests.get(request_url)
if r.status_code == 200:
return r
else:
warnings.warn("request to " + str(ext_id) + " has failed to return 200, and has returned " + str(r.status_code))
return r
pass
|
b1979ff27c3f47597093ac07b377766756a58709
| 97,940 |
def create_multiplier_function(m):
"""Given a multiplier m, returns a function that multiplies its input by m."""
def multiply(val):
return m*val
return multiply
|
47aac306ef7b347c6ad9b0f951ee34397a960cc6
| 104,695 |
def get_linear(start, end, steps):
"""Get a list of numbers interpolated from start to end inclusively."""
step = (end - start) / (steps - 1)
return [start + i * step for i in range(steps)]
|
b35c81e6aa254f117a146cac5a093e8ab419bdf9
| 569,410 |
def default_cmdline_options(config):
"""
Return default command line options required for every run of terraform.
Args:
config: dictionary containing all variable settings required
to run terraform with
Returns:
cmdline_options: list of command-line arguments to run
all terraform commands should be run with.
"""
cmdline_options = ['-var=\'aws_region={}\''.format(config['aws_region']),
'-var-file={}'.format(config['tfvars']) ]
return cmdline_options
|
85f3e74049ae744f4a5b46eb382f293a3c9126d6
| 639,704 |
def check_if_file_exists_on_disk(filepath):
"""
Checks if the file exists on the disk.
Could use os.path.exists() but some its safer to do that following.
@param filepath: path to the file including the filename
"""
try :
with open(filepath) as f :
return True
except :
return False
|
cb1d519b906c3ec4db9ec13a248ed71394bb7985
| 582,507 |
def WalkGyp(functor, gypdata):
"""Walk |gypdata| and call |functor| on each node."""
def WalkNode(node):
ret = []
if isinstance(node, dict):
for k, v in node.items():
ret += functor(k, v)
ret += WalkNode(v)
elif isinstance(node, (tuple, list)):
for v in node:
ret += WalkNode(v)
return ret
return WalkNode(gypdata)
|
d2919910b6458f0fa2a4cc623f9ddb740f9ae531
| 335,259 |
def split_with_spaces(sentence):
"""
Takes string with partial sentence and returns
list of words with spaces included.
Leading space is attached to first word.
Later spaces attached to prior word.
"""
sentence_list = []
curr_word = ""
for c in sentence:
if c == " " and curr_word != "":
# append space to end of non-empty words
# assumed no more than 1 consecutive space.
sentence_list.append(curr_word+" ")
curr_word = ""
else:
curr_word += c
# add trailing word that does not end with a space
if len(curr_word) > 0:
sentence_list.append(curr_word)
return sentence_list
|
3eb22118fca858a39249893a23bda4be12ed97a4
| 227,629 |
def ignore_ip_addresses_rule_generator(ignore_ip_addresses):
"""
generate tshark rule to ignore ip addresses
Args:
ignore_ip_addresses: list of ip addresses
Returns:
rule string
"""
rules = []
for ip_address in ignore_ip_addresses:
rules.append("-Y ip.dst != {0}".format(ip_address))
return rules
|
3ac43f28a4c8610d4350d0698d93675572d6ba44
| 2,242 |
def align_left(msg, length):
""" Align the message to left. """
return f'{msg:<{length}}'
|
5a374b22b650a543229304c30d2ea7690cd7a85d
| 213,446 |
def flux(component):
"""Determine flux in every channel
Parameters
----------
component: `scarlet.Component` or array
Component to analyze or its hyperspectral model
"""
if hasattr(component, "get_model"):
model = component.get_model()
else:
model = component
return model.sum(axis=(1, 2))
|
b95b0aa926ee2cc2c78e90c425b47f04bc0a4d4c
| 9,127 |
def link2dict(l):
"""
Converts the GitHub Link header to a dict:
Example::
>>> link2dict('<https://api.github.com/repos/sympy/sympy/pulls?page=2&state=closed>; rel="next", <https://api.github.com/repos/sympy/sympy/pulls?page=21&state=closed>; rel="last"')
{'last': 'https://api.github.com/repos/sympy/sympy/pulls?page=21&state=closed', 'next': 'https://api.github.com/repos/sympy/sympy/pulls?page=2&state=closed'}
"""
d = {}
while True:
i = l.find(";")
assert i != -1
assert l[0] == "<"
url = l[1:i - 1]
assert l[i - 1] == ">"
assert l[i + 1:i + 7] == ' rel="'
j = l.find('"', i + 7)
assert j != -1
param = l[i + 7:j]
d[param] = url
if len(l) == j + 1:
break
assert l[j + 1] == ","
j += 2
l = l[j + 1:]
return d
|
496d7db262062516320b9812443d3946140c5b1c
| 214,855 |
from collections import OrderedDict
def _dictionize(sub_dict):
"""
Create normal dictionaries from a sub_dictionary containing orderedDicts
Parameters
----------
sub_dict : dict
a dictionary with unlimited handling structure depth and types
Returns
-------
dict
the same structure as `sub_dict` just with dicts instead of orderedDicts
"""
normalized_dict = dict()
for key in sub_dict:
if isinstance(sub_dict[key], OrderedDict):
normalized_dict[key] = _dictionize(sub_dict[key])
elif isinstance(sub_dict[key], list):
normalized_dict[key] = list()
for element in sub_dict[key]:
if isinstance(element, (list, dict, set)):
normalized_dict[key].append(_dictionize(element))
else:
normalized_dict[key] = sub_dict[key]
else:
normalized_dict[key] = sub_dict[key]
return normalized_dict
|
b3103ad08095280139585bc7353e46a0dd239083
| 403,920 |
def sort_keywords(keywords):
"""Sort keywords in the proper order: i.e. glob-arches, arch, prefix-arches."""
def _sort_kwds(kw):
parts = tuple(reversed(kw.lstrip('~-').partition('-')))
return parts[0], parts[2]
return sorted(keywords, key=_sort_kwds)
|
83e3af245e2fa7d4c48d3f3edbe7df7a2705d403
| 76,030 |
def assemble_api_url(domain, api_url, protocol_type='https'):
"""Assemble the requests api url.
Args:
domain (str): The domain of the render farm.
api_url (str): The url of the operator.
protocol_type (str, optional): The type of the protocol
Returns:
str: Assembled url address for the API.
"""
return "{}://{}{}".format(protocol_type, domain, api_url)
|
5553fb467d4442a351a6d0abcddb1e4736f9c093
| 488,640 |
def hive_table_exists(spark, database: str, table: str) -> bool:
"""Checks the Spark catalog and returns True if a table exists."""
return spark._jsparkSession.catalog().tableExists(database, table)
|
7e86846087df1c905af869bc4615170053f2e9c0
| 372,692 |
def _tags_conform_to_filter(tags, filter):
"""Mirrors Bazel tag filtering for test_suites.
This makes sure that the target has all of the required tags and none of
the excluded tags before we include them within a test_suite.
For more information on filtering inside Bazel, see
com.google.devtools.build.lib.packages.TestTargetUtils.java.
Args:
tags: all of the tags for the test target
filter: a struct containing excluded_tags and required_tags
Returns:
True if this target passes the filter and False otherwise.
"""
# None of the excluded tags can be present.
for exclude in filter.excluded_tags:
if exclude in tags:
return False
# All of the required tags must be present.
for required in filter.required_tags:
if required not in tags:
return False
# All filters have been satisfied.
return True
|
1db9528e11d1b513690af14f1d8453f8b0682d34
| 8,809 |
def get_camel_from_snake(snake: str) -> str:
"""Get a camel format string from a snake format string
>>> get_camel_from_snake('foo_bar_baz')
'fooBarBaz'
Args:
snake (str): Snake style string
Returns:
str: Camel style string
"""
return ''.join(map(
lambda t: t[1].capitalize() if t[0] > 0 else t[1],
enumerate(snake.split('_'))
))
|
3b9c2936548867bd3474a0eb28c84b803b23cc6d
| 602,853 |
def _get_char_code(string, position):
"""Return an int representation of the character of `string`
in position `position`. E.g.: string[position]. If the position
doesn't exist in the string, return -1.
:return: an integer representing a position in a string."""
return ord(string[position]) if position < len(string) else -1
|
ad34553267bcafc2e820ca696ccb71c5127d19c5
| 274,047 |
from typing import Any
def _both_none(a: Any, b: Any) -> bool:
"""Shorthand function to see if both endpoints are None."""
return a is None and b is None
|
5f56b602029414531ea78a10259f633d38ca4322
| 385,433 |
def calculate_penalty(row):
"""
Calculate penalty as `(current_amount_due + total_paid) - fine_level1_amount`
"""
# If current amount due is negative or ticket was dismissed,
# penalty is null
if float(row[14]) < 0 or row[16] == 'Dismissed':
penalty = None
else:
penalty = (float(row[14]) + float(row[15])) - float(row[12])
return penalty
|
fd22eecee718b8974cfebfb25c05c2e20e4596b2
| 453,823 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.