content
stringlengths 39
9.28k
| sha1
stringlengths 40
40
| id
int64 8
710k
|
---|---|---|
def line_value(line):
"""Return the value associated with a line (series of # and . chars)"""
val = 0
for char in line:
val <<= 1
val += char == "#"
return val
|
d48adf92b3ba92077377da8f14168c838ee10300
| 197,770 |
import importlib
def get_command(all_pkg, hook):
"""
Collect the command-line interface names by querying ``hook`` in ``all_pkg``
Parameters
----------
all_pkg: list
list of package files
hook: str
A variable where the command is stored. ``__cli__`` by default.
Returns
-------
list
"""
ret = []
for r in all_pkg:
module = importlib.import_module(__name__ + '.' + r.lower())
ret.append(getattr(module, hook))
return ret
|
921bc4d8d3829fa35ceacaec741cde172dda175a
| 461,116 |
import re
def url_to_filename(url: str) -> str:
"""Converts url to a filename by removing invalid filename characters
Note that this will not always work since windows has very particular file
naming rules.
"""
# Replace "*", used as geography wildcard, with "all"
url = url.replace("*", "all")
# Remove the beginning of the call since it is always the same
url = url.replace("https://api.census.gov/data/", "")
# Remove the api key if present
key_index = url.find("key")
if key_index != -1:
url = url[:key_index]
# Only keep letters, numbers, or _, ., -
return "".join(re.findall("[a-zA-Z0-9_.-]*", url))
|
6abf9891786e493c97a0fc63ecfacf6477859298
| 358,631 |
def join_strings(lst):
"""Join a list to comma-separated values string."""
return ",".join(lst)
|
fbbc195a53d2d4b15012861251d676dbf9369cde
| 35,688 |
def son1(ind1,ind2):
""" son1 : one half of the first and second half of the second
2 individual to create one child
:param ind1:
:param ind2:
:return: a new individual
"""
return ind1[:len(ind1)//2]+ind2[len(ind1)//2:]
|
aa7da58a9ca9d33783670eefd9d6066c4ab7db0a
| 268,759 |
def sum_divisible_by(n: int, limit: int) -> int:
"""Computes the sum of all the multiples of n up to the given limit.
:param n: Multiples of this value will be summed.
:param limit: Limit of the values to sum (inclusive).
:return: Sum of all the multiples of n up to the given limit.
"""
p = limit // n
return n * (p * (p + 1)) // 2
|
1a68e3d77a98f4c3a5f05dbee935c8791c316063
| 403,874 |
def collection_id(product: str, version: str) -> str:
"""Creates a collection id from a product and a version:
Args:
product (str): The MODIS product
version (str): The MODIS version
Returns:
str: The collection id, e.g. "modis-MCD12Q1-006"
"""
return f"modis-{product}-{version}"
|
d6a8df291210a2644904447a1687b75b2b614fc3
| 84,935 |
def _func_worker_ranks(workers):
"""
Builds a dictionary of { (worker_address, worker_port) : worker_rank }
"""
return dict(list(zip(workers, range(len(workers)))))
|
2efff27857c573f0c68fe725b74c6f04e16b4ec4
| 456,801 |
import torch
def generate_sparse_one_hot(num_ents, dtype=torch.float32):
""" Creates a two-dimensional sparse tensor with ones along the diagnoal as one-hot encoding. """
diag_size = num_ents
diag_range = list(range(num_ents))
diag_range = torch.tensor(diag_range)
return torch.sparse_coo_tensor(
indices=torch.vstack([diag_range, diag_range]),
values=torch.ones(diag_size, dtype=dtype),
size=(diag_size, diag_size))
|
3a71c72acfca4fe9fbfe1a6848519e9726fe72d9
| 46,237 |
def any_in_string(l, s):
"""
Check if any items in a list is in a string
:params l: dict
:params s: string
:return bool:
"""
return any([i in l for i in l if i in s])
|
413f26353595ad92bd6803043f7c926845c6a063
| 434,714 |
def _random_subset_weighted(seq, m, fitness_values, rng):
"""
Return m unique elements from seq weighted by fitness_values.
This differs from random.sample which can return repeated
elements if seq holds repeated elements.
Modified version of networkx.generators.random_graphs._random_subset
"""
targets = set()
weights = [fitness_values[node] for node in seq]
while len(targets) < m:
x = rng.choices(list(seq), weights=weights, k=m-len(targets))
targets.update(x)
return list(targets)
|
438b72a0d36e529ec554e33357b7ad6dc37aaea5
| 668,659 |
def engine_version(connection):
"""
Return string representation of oVirt engine version.
"""
engine_api = connection.system_service().get()
engine_version = engine_api.product_info.version
return '%s.%s' % (engine_version.major, engine_version.minor)
|
ac038ee0d812cde0d4d50e34510e0c8004562ecf
| 586,340 |
import textwrap
def format_ordinary_line(source_line, line_offset):
"""Format a single C++ line with a diagnostic indicator"""
return textwrap.dedent(
f"""\
```cpp
{source_line}
{line_offset * " " + "^"}
```
"""
)
|
504f23b9ac2026ff59cd3d1ab184d9ad236fca96
| 625,340 |
from typing import List
def is_func_name_to_ignore(
func_name: str,
ignore_func_name_prefix_list: List[str]) -> bool:
"""
Get boolean value of function name which should be ignored.
Parameters
----------
func_name : str
Target function name.
ignore_func_name_prefix_list : list of str
A prefix list of function name conditions to ignore.
Returns
-------
result_bool : bool
The boolean value of function name which should be ignored.
"""
for ignore_func_name_prefix in ignore_func_name_prefix_list:
if func_name.startswith(ignore_func_name_prefix):
return True
return False
|
7d4a6465f1d5220c5c7233a5b3af9e4c2692926c
| 220,848 |
def role_vars(host):
"""Loading standard role variables."""
defaults_files = "file=./defaults/main.yml name=role_defaults"
vars_files = "file=./vars/main.yml name=role_vars"
ansible_vars = host.ansible("include_vars", defaults_files)["ansible_facts"]["role_defaults"]
ansible_vars.update(
host.ansible("include_vars", vars_files)["ansible_facts"]["role_vars"]
)
return ansible_vars
|
19a874a46ff75de0513c2539d45597aeab2e8941
| 50,640 |
def compile_toc(entries, section_marker='='):
"""Compiles a list of sections with objects into sphinx formatted
autosummary directives."""
toc = ''
for section, objs in entries:
toc += '\n\n%s\n%s\n\n' % (section, section_marker * len(section))
toc += '.. autosummary::\n\n'
for obj in objs:
toc += ' ~%s.%s\n' % (obj.__module__, obj.__name__)
return toc
|
61c7df461c473a318e5ea08902535e2cc0a9ad8f
| 532,491 |
import requests
def fetch_json_package(url, host, referer, encoding):
"""
JSON抓包函数
:param url: AJAX API地址
:param host: 目标服务器
:param referer: header的引用页
:param encoding: 编码
:return: 字典格式的JSON数据包
"""
kv = {'user_agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) '
'Chrome/80.0.3987.132 Safari/537.36',
'host': host,
'referer': referer
}
r = requests.get(url, headers=kv)
r.raise_for_status()
r.encoding = encoding
return r.text
|
c8d21f955fb4a92bfdb466c72bb0dccf27090c27
| 622,902 |
def encode_datetime(dt):
"""Converts provided datetime object into ISO 8601/RFC3339-compliant string
:param datetime.datetime dt: datetime object
:return: string representation of dt
:rtype: str
"""
s = dt.isoformat()
if s.endswith('+00:00'):
s = s[:-6] + 'Z'
if dt.tzinfo is None:
# Treat datetimes with no tzinfo as UTC
s += 'Z'
return s
|
609daac917cccd4f42b96852352d412e8bde34ca
| 607,404 |
def is_student(user):
"""
Method to determine if user has a student role
:param user: User making the request
:return: True if user has a student role
"""
return user.role == "student"
|
0aa9fc7724cf2e1d95e71e9ffd76e86ae2b77945
| 213,528 |
import random
def basic_rand_sampler(seq, sample_len):
"""
Basic random text sampler.
If sample_len is greater than the length of the seq, the seq is returned.
"""
seq_len = len(seq)
if seq_len > sample_len:
start_idx = random.randint(0, min(seq_len,seq_len - sample_len))
end_idx = start_idx+sample_len
return seq[start_idx:end_idx]
else:
return seq
|
edf37fd201f15f7ff10efb1253fa3d6258790f1a
| 550,728 |
def chunker(df, size):
"""
Split dataframe *df* into chunks of size *size*
"""
return [df[pos:pos + size] for pos in range(0, len(df), size)]
|
ea96315f9963551f4870d6732570d0ae375bd3c3
| 29,418 |
def factor(n):
"""
分解质因数,非递归解法
:param n: 正整数
:return 质因数列表
"""
result = []
while n > 1:
for i in range(2, n + 1):
if n % i == 0:
n //= i
result.append(i)
break
return result
|
41ceccfaf90dffa39c6ce25988165f9779e1a011
| 517,372 |
def comma(text):
"""Split a string into components by exploding on a comma"""
components = (el.strip() for el in text.split(','))
return tuple(filter(bool, components))
|
ebfd1d0fe7be436a93973e4ee14f7565414cd5f3
| 24,084 |
def _fold_change(df, cond1, cond2):
"""Linear fold-change calculation. Assumes non-log-transformed values as input."""
return df[cond2] / df[cond1]
|
12306f5019f86497ca86901078aba8b85e5215f8
| 361,114 |
def analyse_qa(stats_per_subjects, stats_across_subjects, column_names):
"""
Analyse the subjects and flag warning
Parameters
----------
stats_per_subjects : DataFrame
DataFrame containing the stats per subjects.
stats_across_subjects : DataFrame
DataFrame containing the stats across subjects.
column_names : array of strings
Name of the columns in the summary DataFrame.
Returns
-------
warning : dict
Dictionnary of warning subjects for each metric.
"""
warning = {}
for metric in column_names:
warning[metric] = []
std = stats_across_subjects.at['std', metric]
mean = stats_across_subjects.at['mean', metric]
for name in stats_per_subjects.index:
if stats_per_subjects.at[name, metric] > mean + 2 * std or\
stats_per_subjects.at[name, metric] < mean - 2 * std:
warning[metric].append(name[0])
return warning
|
b46a8fd0c2ce753a73a2f525a2f4235226ceacac
| 332,394 |
def ToCppStringLiteral(s):
"""Returns C-style string literal, or NULL if given s is None."""
if s is None:
return 'NULL'
if all(0x20 <= ord(c) <= 0x7E for c in s):
# All characters are in ascii code.
return '"%s"' % s.replace('\\', r'\\').replace('"', r'\"')
else:
# One or more characters are non-ascii.
return '"%s"' % ''.join(r'\x%02X' % c for c in s.encode('utf-8'))
|
c6c9cd3728b026f094c101480dd0e9d580b4f2da
| 175,331 |
def asymptotic_relation_radial(enn,numax,param):
"""
Compute the asymptotic frequency for a radial mode.
Parameters
----------
enn : int
The radial order of the mode.
numax : float
The frequency of maximum oscillation power
param : array_like
Collection of the asypmtotic parameters in the order `[dnu, epsilon,
alpha]`.
Returns
-------
freq_asymp : float
The radial asymptotic frequency of given radial order `enn`.
"""
freq_asymp = param[0]*(enn + param[1] + param[2]/2.*(enn - numax/param[0])^2)
return freq_asymp
|
8575c62b3ff5a54fa831b033d1578dfa40cf018e
| 672,089 |
def to_type_key(dictionary, convert_func):
"""Convert the keys of a dictionary to a different type.
# Arguments
dictionary: Dictionary. The dictionary to be converted.
convert_func: Function. The function to convert a key.
"""
return {convert_func(key): value
for key, value in dictionary.items()}
|
98f43eab980358644f9a631759bd2c70904bae91
| 246,972 |
import re
import string
def _sanitize_name(name):
"""Sanitize content of an H2 header to be used as a filename
"""
# replace all non-aplhanumeric with a dash
sanitized = re.sub('[^0-9a-zA-Z]+', '-', name.lower())
# argo does not allow names to start with a digit when using dependencies
if sanitized[0] in string.digits:
sanitized = 'section-' + sanitized
return sanitized
|
4e9b68e0cb1fb40de4285cff920bfb0475c41ce9
| 376,839 |
def parse_line(line, names, types):
"""
parse line with expected names and types
Example:
parse_line(line, ['dt', 'ntstep', 'nbunch'], [float, int,int])
"""
x = line.split()
values = [types[i](x[i]) for i in range(len(x))]
return dict(zip(names, values))
|
1fc900601e29b44938536d7d4ca9c1b6fb67ff1b
| 391,866 |
import logging
def ReadLines(filename, dut=None):
"""Returns a file as list of lines.
It is used to facilitate unittest.
Args:
filename: file name.
Returns:
List of lines of the file content. None if IOError.
"""
try:
if dut is None:
with open(filename, encoding='utf-8') as f:
return f.readlines()
else:
return dut.ReadSpecialFile(filename).splitlines(True)
except Exception:
logging.exception('Cannot read file "%s"', filename)
return None
|
719594b32a7bfb853375635873b08b33397e4833
| 328,649 |
def s2d_orthographic(sph):
"""Converts coordinates on the unit sphere to the disk, using
the orthographic projection.
"""
return sph[..., 0] + 1j*sph[..., 1]
|
7f1c0373be8534d8d162cac9a64bd6197de583f2
| 287,553 |
def is_array_sequence(obj):
""" Return True if `obj` is an array sequence. """
try:
return obj.is_array_sequence
except AttributeError:
return False
|
753cf959a9c3d18980b57bcc2477784e76400711
| 429,291 |
def set_to_bounds(i_s, i_e, j_s, j_e, low=0, high=1):
"""
Makes sure the given index values stay with the
bounds (low and high). This works only for 2 dimensional
square matrices where low and high are same in both
dimensions.
Arguments:
i_s : Starting value for row index
i_e : Ending value for row index
j_s : Starting value for column index
j_e : Ending value for column index
low : Minimum value for index possible
high : Maximum value for index possible
Returns:
Values within bounds for given index positions
"""
if i_s < low:
i_s = low
if i_e > high:
i_e = high
if j_s < low:
j_s = low
if j_e > high:
j_e = high
return i_s, i_e, j_s, j_e
|
765fb315238159111bb2423444b9575ff04382af
| 121,409 |
def draw_rectangle(image=None, coordinates=None,
size=None, color=None):
"""
Generate a rectangle on a given image canvas at the given coordinates
:param image: Pillow/PIL Image Canvas
:param coordinates: coordinate pair that will be the center of the rectangle
:param size: tuple with the x and y sizes of the rectangle
:param color: color of the rectangle
:returns: image rectangle return or False
:raises TypeError: none
"""
if image \
and coordinates \
and size \
and color:
corner0 = (coordinates[0] - size[0] // 2, coordinates[1] - size[1] // 2)
corner1 = (coordinates[0] + size[0] // 2, coordinates[1] + size[1] // 2)
box_paint = [corner0, corner1]
# print('road box_coords: ', box_paint)
# pprint(box_paint)
drawn_rectangle = image.rectangle(box_paint, fill=color, outline=color)
return drawn_rectangle
else:
return False
|
ff492e256594ef562d58a8d9fdce0c1b6b10e99b
| 678,591 |
import math
def blen(n):
"""Length of n in bytes. Also handles non-numeric data."""
try:
return int(math.ceil(n.bit_length() / 8.0))
except AttributeError:
return len(n)
|
0bc8e12b3b07be9290821091548edee4b9f015c0
| 346,222 |
def is_registered_path(tmod, pin, pout):
"""Checks if a i/o path is sequential. If that is the case
no combinational_sink_port is needed
Returns a boolean value
"""
for cell, ctype in tmod.all_cells:
if ctype != "$dff":
continue
if tmod.port_conns(pin) == tmod.cell_conn_list(
cell, "D") and tmod.port_conns(pout) == tmod.cell_conn_list(
cell, "Q"):
return True
return False
|
c5c35a1f2928dc8b6862bc4ebbfdac69fcb3eba9
| 87,583 |
def delete_keys_from_dict(dict_del, the_keys):
"""
Delete the keys present in the lst_keys from the dictionary.
Loops recursively over nested dictionaries.
"""
# make sure the_keys is a set to get O(1) lookups
if type(the_keys) is not set:
the_keys = set(the_keys)
for k, v in dict_del.items():
if k in the_keys:
del dict_del[k]
if isinstance(v, dict):
delete_keys_from_dict(v, the_keys)
if isinstance(v, list):
for item in v:
if isinstance(item, dict):
delete_keys_from_dict(item, the_keys)
return dict_del
|
12ef9f75679a470ae2d33db550c05e50991c18de
| 144,247 |
def add_branch(tree, vector, value):
"""Recursively update dictionary given a vector containing the path of
the branch. Useful for directly adding a value at a specified key path.
Source: https://stackoverflow.com/a/59634887/6654930
"""
key = vector[0]
if len(vector) == 1:
tree[key] = value
else:
tree[key] = add_branch(tree[key] if key in tree else {}, vector[1:], value)
return tree
|
95f054cc69ea5786e21961c409575fd214dd26eb
| 391,643 |
def _invert(d):
"""Invert a dictionary."""
return dict(zip(d.values(), d.keys()))
|
43f8173e5c41aca480abf2710dd03a550e91ac6f
| 517,211 |
import re
def is_valid_domain(domain):
"""Checks if a domain is syntactically valid and returns a bool"""
if domain[-1] == ".":
domain = domain[:-1]
if len(domain) > 253:
return False
fqdn_re = re.compile("(?=^.{1,63}$)(^(?:[a-z0-9_](?:-*[a-z0-9_])+)$|^[a-z0-9]$)", re.IGNORECASE)
return all(fqdn_re.match(d) for d in domain.split("."))
|
2b533646a10160f2172e1a1e1cb51c39ead3c89a
| 428,220 |
def islambda(func):
""" Test if the function func is a lambda ("anonymous" function) """
return getattr(func, 'func_name', False) == '<lambda>'
|
e76b699023b23909f7536e0b3513201ceaebef5c
| 127,000 |
def __update_count(count, max_count):
"""
Updating count for next permutation. If all permutations are
done, return -1 as stoping criteria.
:param max_count: list
:param count: list
:return: list
"""
n = len(count)
for i in range(n):
if (count[n-i-1]) < max_count[n-i-1]:
count[n-i-1] += 1
break
elif count == max_count:
count = -1
break
else:
count[n-i-1] = 0
return count
|
d211665652084f3efd6aa9124330854581d0df2d
| 453,078 |
import glob
def FindMaxVtuId(project, extensions = [".vtu", ".pvtu"]):
"""
Find the maximum Fluidity vtu ID for the supplied project name
"""
filenames = []
for ext in extensions:
filenames += glob.glob(project + "_?*" + ext)
maxId = None
for filename in filenames:
id = filename[len(project) + 1:-len(filename.split(".")[-1]) - 1]
try:
id = int(id)
except ValueError:
continue
if maxId is None:
maxId = id
else:
maxId = max(maxId, id)
return maxId
|
02b4c1e17e40e18c120bb803790191ff8be592b6
| 230,822 |
def traverse_table(time_step, beam_indx, back_pointers, elems_table,
format_func=None):
"""
Walks back to construct the full hypothesis by traversing the passed table.
:param time_step: the last time-step of the best candidate
:param beam_indx: the beam index of the best candidate in the last time-step
:param back_pointers: array [steps]
:param elems_table: array of elements to traverse [steps, elements_count],
e.g. vocabulary word ids
:param format_func: a function to format elements
:return: hypothesis list of the size 'time_step'
"""
hyp = []
for j in range(len(back_pointers[:time_step]) - 1, -1, -1):
elem = elems_table[j + 1][beam_indx]
elem = elem if format_func is None else format_func(elem)
hyp.append(elem)
beam_indx = back_pointers[j][beam_indx]
elem = elems_table[0][beam_indx]
elem = elem if format_func is None else format_func(elem)
hyp.append(elem)
return hyp[::-1]
|
e91e38e26f94862e8e676b78c7a2c39876153dd3
| 424,094 |
def find_prepositions(chunked):
""" The input is a list of (token, tag, chunk)-tuples.
The output is a list of (token, tag, chunk, preposition)-tuples.
PP-chunks followed by NP-chunks make up a PNP-chunk.
"""
n = len(chunked) > 0 and len(chunked[0]) or 0
for i, chunk in enumerate(chunked):
if chunk[2].endswith("PP") and i<len(chunked)-1 and chunked[i+1][2].endswith("NP"):
chunk.append("B-PNP")
for ch in chunked[i+1:]:
if not ch[2].endswith("NP"):
break
ch.append("I-PNP")
# Tokens that are not part of a preposition just get the O-tag.
for chunk in filter(lambda x: len(x) < n+1, chunked):
chunk.append("O")
return chunked
|
5c86abcceef92cf445b817e64d08a208bbff76c3
| 414,447 |
from typing import Dict
def lower_booleans(value: str, meta: Dict) -> str:
"""
Lower boolean string values to the format expected by the DBMS server.
e.g.
`True` -> `true`
`False` -> `false`
Arguments
---------
value : str
The DBMS server argument value
meta : Dict
Dictionary of meta-information available to all preprocessors
Returns
-------
The preprocessed server argument value
"""
assert value is True or value is False, "Input must be a first-class boolean type."
return str(value).lower()
|
0604fa1f45972086345c09eb488db8312aece7b6
| 456,268 |
import lzma
def decompress_lzma(lzma_data):
"""Decompresses LZMA data.
Args:
lzma_data: lzma compressed data as bytes.
Returns:
Decompressed data as bytes.
"""
return lzma.LZMADecompressor().decompress(lzma_data)
|
52f0e2a5de419df5a29b9a429d2b8632d58a44ef
| 139,757 |
def circle_line_intersection(center, radius, line_start, line_end):
"""
Determines whether or not a circle and line intersect
:param center: The center of the circle as a tuple (x,y)
:param radius: The radius of the circle
:param line_start: The start point of a line as a tuple (x,y)
:param line_end: The end point of a line as a tuple (x,y)
:return: a boolean of whether not the circle intersects the line
"""
dx = line_end(0) - line_start(0)
dy = line_end(1) - line_start(1)
# start calculating the variables for the quadratic used in determining whether or not there is an intersection
a = dx ** 2 + dy ** 2
b = 2 * (dx * (line_start(0) - center(0)) + dy * (line_start(1) - center(0)))
c = (line_start(0) - center(0)) ** 2 + (line_start(1) - center(1)) ** 2 - radius ** 2
# calculate the determinant to see if there is an intersection
det = b ** 2 - 4 * a * c
if det < 0:
return False
else:
return True
|
5d641d30987a32347b4834dc2b46cb40c8a59dec
| 187,866 |
import random
def _randomly_negate(v):
"""With 50% prob, negate the value"""
return -v if random.random() > 0.5 else v
|
dd08e186b97afac1b6eb617e90be383e83b749bd
| 69,725 |
def is_bottom(module_index):
"""Returns True if module is in the bottom cap"""
return ( (module_index>=600)&(module_index<696) )
|
88b778141776190fecaaa813e6ffcfd418abfd5f
| 79,117 |
def is_unknown_license(lic_key):
"""
Return True if a license key is for some lesser known or unknown license.
"""
return lic_key.startswith(('unknown', 'other-',)) or 'unknown' in lic_key
|
cb3a9446d556f85bc828a8dc24a4041ada7256af
| 582,183 |
def residcomp(z1, z0, linelength=1):
"""
Residual Compensation Factor Function.
Evaluates the residual compensation factor based on the line's positive and
zero sequence impedance characteristics.
Parameters
----------
z1: complex
The positive-sequence impedance
characteristic of the line, specified in
ohms-per-unit where the total line length
(of same unit) is specified in
*linelength* argument.
z0: complex
The zero-sequence impedance characteristic
of the line, specified in ohms-per-unit
where the total line length (of same unit)
is specified in *linelength* argument.
linelength: float, optional
The length (in same base unit as impedance
characteristics) of the line. default=1
Returns
-------
k0: complex
The residual compensation factor.
"""
# Evaluate Z1L and Z0L
Z1L = z1 * linelength
Z0L = z0 * linelength
# Calculate Residual Compensation Factor (k0)
k0 = (Z0L - Z1L) / (3 * Z1L)
return k0
|
398cff9b5a65785ed574e94945cfc7461f5e7bb5
| 153,765 |
def get_attack_rate(df, location):
"""
Get the attack rate for the location.
Args:
df (pd.DataFrame) : pandas DataFrame with attack rates for this scenario
location (str) : name of the location
Returns:
float: Attack rate as a fraction from SIR model, values between 0 and 1.
"""
return df.loc[df['location'] == location]['artotal'].values[0]
|
05e27abfd3046a6b455d1a1606ad1591d637e50f
| 658,281 |
def _pop_highest(lst):
""" pop the highest value from the list
return a tuple (new list, popped value)"""
highest = lst.pop(lst.index(max(lst)))
return highest
|
2d52af7dcec5c499cf24ac9b5d7137cacb7cb402
| 167,614 |
import asyncio
import functools
async def run_blocking_func_in_executor(func, *args, **kwargs):
"""
Run a blocking function in a different executor so that it won't stop
the event loop
"""
return await asyncio.get_event_loop().run_in_executor(None, functools.partial(func, *args, **kwargs))
|
1b7bd8d0680eb1f81aa0fd03f39e20356522105a
| 213,435 |
def get_ngrams(sent, n=2, bounds=False, as_string=False):
"""
Given a sentence (as a string or a list of words), return all ngrams
of order n in a list of tuples [(w1, w2), (w2, w3), ... ]
bounds=True includes <start> and <end> tags in the ngram list
"""
ngrams = []
words=sent.split()
if n==1:
return words
if bounds:
words = ['<start>'] + words + ['<end>']
N = len(words)
for i in range(n-1, N):
ngram = words[i-n+1:i+1]
if as_string: ngrams.append('_'.join(ngram))
else: ngrams.append(tuple(ngram))
return ngrams
|
9259a07f43a0d17fdddd2556004acf7317d517e8
| 487,163 |
def get_list_nodes_from_tree(tree, parameters=None):
"""
Gets the list of nodes from a process tree
Parameters
---------------
tree
Process tree
parameters
Parameters
Returns
---------------
list_nodes
List of nodes of the process tree
"""
if parameters is None:
parameters = {}
list_nodes = []
to_visit = [tree]
while len(to_visit) > 0:
node = to_visit.pop(0)
for child in node.children:
to_visit.append(child)
list_nodes.append(node)
return list_nodes
|
0d0178407d7675d3b245965606462c23ead232b7
| 662,342 |
def truncate(text, length=30, truncate_string='...'):
"""
Truncates ``text`` with replacement characters
``length``
The maximum length of ``text`` before replacement
``truncate_string``
If ``text`` exceeds the ``length``, this string will replace
the end of the string
"""
if not text: return ''
new_len = length-len(truncate_string)
if len(text) > length:
return text[:new_len] + truncate_string
else:
return text
|
5815cc0e77ace83d73c2714e59b60c6b7111a306
| 376,885 |
def docker_PIDS(container_id):
"""
Determines the number of processes within the docker container.
:param container_id: The full ID of the docker container.
:type container_id: ``str``
:return: Returns the number of PIDS within a dictionary.
:rtype: ``dict``
"""
with open('/sys/fs/cgroup/cpuacct/docker/' + container_id + '/tasks', 'r') as f:
return {'PIDS': len(f.read().split('\n')) - 1}
|
efba710f37c4a241415a82f10bdd9d028ae7e38f
| 222,907 |
def try_func(func):
"""
Sandbox to run a function and return its values or any produced error.
:param func: testing function
:return: results or Exception
"""
try:
return func()
except Exception as e:
return e
|
5d25af78685d89747202e50f227e33b383a8d3d1
| 436,230 |
def compare_flavors(flavor_item):
"""
Helper function for sorting flavors.
Sorting order: Flavors with lower resources first.
Resource importance order: GPUs, CPUs, RAM, Disk, Ephemeral.
:param flavor_item:
:return:
"""
return (
flavor_item.get("Properties", {}).get("Accelerator:Number", "0"),
flavor_item.get("VCPUs"),
flavor_item.get("RAM"),
flavor_item.get("Disk"),
flavor_item.get("Ephemeral"),
)
|
a0e167ee1c7a4f93cc3533064a801b1a29211b7d
| 646,658 |
def get_test_result_publish_data(args):
""" Get the data needed to publish the results, from the args. """
publish_env = args.get("publish_results")
publish_username = args.get("publish_username")
publish_password = args.get("publish_password")
return publish_env, publish_username, publish_password
|
ed93fd7667d829dca0bbfb51d204eb2b4b7abfb6
| 464,522 |
def validate_overlap(periods, datetime_range=False):
"""
Receives a list with DateRange or DateTimeRange and returns True
if periods overlap.
This method considers that the end of each period is not inclusive:
If a period ends in 15/5 and another starts in 15/5, they do not overlap.
This is the default django-postgresql behaviour:
https://docs.djangoproject.com/en/dev/ref/contrib/postgres/fields/#daterangefield
"""
periods.sort()
no_overlap = [True]
for each in range(0, len(periods) - 1):
latest_start = max(periods[each].lower, periods[each + 1].lower)
earliest_end = min(periods[each].upper, periods[each + 1].upper)
delta = earliest_end - latest_start
if datetime_range:
no_overlap.append(max(0, delta.total_seconds()) == 0)
else:
no_overlap.append(max(0, delta.days) == 0)
return False if all(no_overlap) else True
|
bae96eb890063e4d27af0914e7fcd1348d1340a7
| 10,898 |
def compare_polys(poly_a, poly_b):
"""Compares two polygons via IoU.
Input:
poly_a: A Shapely polygon.
poly_b: Another Shapely polygon.
Returns:
The IoU between these two polygons.
"""
intersection = poly_a.intersection(poly_b).area
union = poly_a.union(poly_b).area
jaccard = intersection/union
return jaccard
|
86e50bee10291b5363838a29bdef86dad6605235
| 610,077 |
def channel_squeeze(x,
channels_per_group):
"""
Channel squeeze operation.
Parameters:
----------
x : NDArray
Input tensor.
channels_per_group : int
Number of channels per group.
Returns:
-------
NDArray
Resulted tensor.
"""
return x.reshape((0, -4, channels_per_group, -1, -2)).sum(axis=2)
|
ffd1ae27925f4531b8fe61d48a7054d3f3b5f0ce
| 444,202 |
def parse_version(vers_string):
"""Parse a version string into its component parts. Returns a list of ints representing the
version, or None on parse error."""
vers_string = vers_string.strip()
vers_parts = vers_string.split('.')
if len(vers_parts) != 4:
return None
try:
major = int(vers_parts[0])
minor = int(vers_parts[1])
patch = int(vers_parts[2])
build = int(vers_parts[3])
except ValueError:
return None
return [major, minor, patch, build]
|
46d96c48e03ab9e68362cfb850ba49ecf54ba49d
| 631,301 |
def partition(list_, indices):
"""Partitions a list to several parts using indices.
:param list_: The target list.
:param indices: Indices to partition the target list.
"""
return [list_[i:j] for i, j in zip([0] + indices, indices + [None])]
|
0718abf3da142eeb0ba2817422f1a25a2705bf3a
| 271,195 |
import json
def read_json(file_path):
"""Convenience method for reading jsons"""
return json.load(open(file_path))
|
585aa6133e6901c9b62e97c700fd10c712a58f7a
| 328,767 |
def ilen(iterator):
"""
Counts the number of elements in an iterator, consuming it and making it
unavailable for any other purpose.
"""
return sum(1 for _ in iterator)
|
8111982f0eebcec475588105ab3edebf6ed8677d
| 292,619 |
def parameter(name, **kwargs):
"""
Function decorator used to provide additional information for your
function's parameter when it is converted to command.
Parameters
----------
name : str
Name of the parameter.
kwargs :
Keyword arguments to pass to ArgumentParser's add_argument() method.
"""
def decorator(func):
if hasattr(func, 'parameter'):
func.parameter[name] = kwargs
else:
func.parameter = {name: kwargs}
return func
return decorator
|
374b6a5eab717bde2267937f7a5363ede548f454
| 270,883 |
def _encode_structure_parts(local_target):
"""
Encodes the design task, to distinguish between struture and wequence domains.
Args:
A sequence that may contain structure or sequence parts.
Returns:
A list representation of the sequence with all structure sites and None else.
"""
encoding = [None] * len(local_target)
for index, site in enumerate(local_target):
if site in ['.', '(', ')', 'N']:
encoding[index] = site
return encoding
|
deb185b439f7b75b6081ca61e57547bdb87aa981
| 627,960 |
def gcd_r(x, y):
"""
求x和y的最大公约数,递归实现方式
欧几里得的辗转相除法:gcd(x,y)=gcd(y,x%y)
:param x: 正整数
:param y: 正整数
:returns: x和y的最大公约数
"""
return x if y == 0 else gcd_r(y, x % y)
|
bad82bb0d36e8151ffcbf5fe20ae27c288f7a925
| 119,280 |
import pickle
def read_ds(path):
"""Read the data structure from the path."""
with open(path, 'rb') as ds_file:
ds = pickle.load(ds_file)
return ds
|
3f5f1d0c52855b2ad4bcca6c498997a5fcc91877
| 107,752 |
def _check_var(
var,
varname,
types=None,
default=None,
allowed=None,
excluded=None,
):
""" Check a variable, with options
- check is instance of any types
- check belongs to list of allowed values
- check does not belong to list of excluded values
if None:
- set to default if provided
- set to allowed value if only has 1 element
Print proper error message if necessary, return the variable itself
"""
# set to default
if var is None:
var = default
if var is None and allowed is not None and len(allowed) == 1:
if not isinstance(allowed, list):
allowed = list(allowed)
var = allowed[0]
# check type
if types is not None:
if not isinstance(var, types):
msg = (
f"Arg {varname} must be of type {types}!\n"
f"Provided: {type(var)}"
)
raise Exception(msg)
# check if allowed
if allowed is not None:
if var not in allowed:
msg = (
f"Arg {varname} must be in {allowed}!\n"
f"Provided: {var}"
)
raise Exception(msg)
# check if excluded
if excluded is not None:
if var in excluded:
msg = (
f"Arg {varname} must not be in {excluded}!\n"
f"Provided: {var}"
)
raise Exception(msg)
return var
|
ff548db83107661e0fcc7cf25575ec7b107a7041
| 291,955 |
import re
def _parse_version_plus_build(v_plus_b):
"""This should reliably pull the build string out of a version + build string combo.
Examples:
>>> _parse_version_plus_build("=1.2.3 0")
('=1.2.3', '0')
>>> _parse_version_plus_build("1.2.3=0")
('1.2.3', '0')
>>> _parse_version_plus_build(">=1.0 , < 2.0 py34_0")
('>=1.0,<2.0', 'py34_0')
>>> _parse_version_plus_build(">=1.0 , < 2.0 =py34_0")
('>=1.0,<2.0', 'py34_0')
>>> _parse_version_plus_build("=1.2.3 ")
('=1.2.3', None)
>>> _parse_version_plus_build(">1.8,<2|==1.7")
('>1.8,<2|==1.7', None)
>>> _parse_version_plus_build("* openblas_0")
('*', 'openblas_0')
>>> _parse_version_plus_build("* *")
('*', '*')
"""
parts = re.search(r'((?:.+?)[^><!,|]?)(?:(?<![=!|,<>~])(?:[ =])([^-=,|<>~]+?))?$', v_plus_b)
if parts:
version, build = parts.groups()
build = build and build.strip()
else:
version, build = v_plus_b, None
return version and version.replace(' ', ''), build
|
95d0bdcaa76364d22426cfe86957d64a6f9dfa8d
| 464,935 |
import json
def get_string(data):
"""Convert data dict to valid json string."""
return ''.join(json.dumps(data).split())
|
591caf9dcf7e7375d9e347eeb13e50bcde28e0bc
| 347,287 |
def rebase_path(from_root_path, to_root_path, path):
"""
Rebase the path to a new root path.
:type path: pathlib.Path
:type from_root_path: pathlib.Path
:type to_root_path: pathlib.Path
:rtype: pathlib.Path
>>> source = Path('/tmp/from/something')
>>> dest = Path('/tmp/to')
>>> rebase_path(source, dest, Path('/tmp/from/something/test.txt'))
PosixPath('/tmp/to/test.txt')
>>> rebase_path(source, dest, Path('/tmp/other.txt'))
PosixPath('/tmp/other.txt')
>>> rebase_path(source, dest, Path('other.txt'))
PosixPath('other.txt')
>>> dest = Path('/tmp/to/something/else')
>>> rebase_path(source, dest, Path('/tmp/from/something/test.txt'))
PosixPath('/tmp/to/something/else/test.txt')
"""
if from_root_path not in path.absolute().parents:
return path
relative_path = path.absolute().relative_to(from_root_path)
return to_root_path.joinpath(relative_path)
|
d143d3d72524523d709bea6e0e132b347ef1cdee
| 255,037 |
import pytz
def _ToTimeZone(t, tzinfo):
"""Converts 't' to the time zone 'tzinfo'.
Arguments:
t: a datetime object. It may be in any pytz time zone, or it may be
timezone-naive (interpreted as UTC).
tzinfo: a pytz timezone object, or None (interpreted as UTC).
Returns:
a datetime object in the time zone 'tzinfo'
"""
if pytz is None:
return t.replace(tzinfo=tzinfo)
elif tzinfo:
if not t.tzinfo:
t = pytz.utc.localize(t)
return tzinfo.normalize(t.astimezone(tzinfo))
elif t.tzinfo:
return pytz.utc.normalize(t.astimezone(pytz.utc)).replace(tzinfo=None)
else:
return t
|
b4c47b19a2fc2766565a97523f8a5781c6a69bbe
| 427,789 |
def getNamesFromSEGResIDBase(dfSegsNodesNDataDpkt
,SEGResIDBase):
"""
Returns tuple (DIVPipelineName,SEGName) from SEGResIDBase
"""
df=dfSegsNodesNDataDpkt[dfSegsNodesNDataDpkt['SEGResIDBase']==SEGResIDBase]
if not df.empty:
return (df['DIVPipelineName'].iloc[0],df['SEGName'].iloc[0])
|
bc8ecd69916af18b99ad6b8f2db8661ce09a4f4f
| 297,674 |
def _normalize_block_name(block_name):
"""Implements Unicode name normalization for block names.
Removes white space, '-', '_' and forces lower case."""
block_name = ''.join(block_name.split())
block_name = block_name.replace('-', '')
return block_name.replace('_', '').lower()
|
eead462770a826e8d0c6f6c03a0da00cd94b7bf3
| 77,680 |
import sqlite3
def connect_to_db(db_name='rpg_db.sqlite3'):
"""
This is a function that takes in the file name and connect to the DB using sqlite3
:param db_name:takes in the name of the database
:return: connect object
"""
return sqlite3.connect(db_name)
|
2293db12461980cd78f1b114b16d7ea4c233f256
| 54,207 |
import pathlib
def is_sub_path(path1: str, path2: str) -> bool:
"""Given two paths, return if path1 is a sub-path of path2."""
return pathlib.Path(path2) in pathlib.Path(path1).parents
|
cda13f48049a95b993083721f29b31d4e1a6a195
| 193,122 |
def _find_pkgs_with_dep(packages, search_dep):
""" Return a list of packages which have a given dependency """
pkgs_with_dep = []
for info in packages.values():
for dep in info.get('depends', []):
if dep.startswith(search_dep):
pkgs_with_dep.append(info)
return pkgs_with_dep
|
41d9ae263f863303962b3caaa75d1f42851424ce
| 269,854 |
def rpmul(a,b):
"""Russian peasant multiplication.
Simple multiplication on shifters, taken from "Ten Little Algorithms" by
Jason Sachs.
Args:
a (int): the first variable,
b (int): the second vairable.
Returns:
x (int): result of multiplication a*b.
"""
result = 0
while b != 0:
if b & 1:
result += a
b >>= 1
a <<= 1
return result
|
b5df4c2d71df87207248f15384f67161be8fc5d7
| 261,291 |
def human_delta(tdelta):
"""
Takes a timedelta object and formats it for humans.
Usage:
# 149 day(s) 8 hr(s) 36 min 19 sec
print human_delta(datetime(2014, 3, 30) - datetime.now())
Example Results:
23 sec
12 min 45 sec
1 hr(s) 11 min 2 sec
3 day(s) 13 hr(s) 56 min 34 sec
:param tdelta: The timedelta object.
:return: The human formatted timedelta
"""
d = dict(days=tdelta.days)
d['hrs'], rem = divmod(tdelta.seconds, 3600)
d['min'], d['sec'] = divmod(rem, 60)
if d['min'] is 0:
fmt = '{sec} sec'
elif d['hrs'] is 0:
fmt = '{min} min {sec} sec'
elif d['days'] is 0:
fmt = '{hrs} hr(s) {min} min {sec} sec'
else:
fmt = '{days} day(s) {hrs} hr(s) {min} min {sec} sec'
return fmt.format(**d)
|
c15cdfcc8cc8594e10b08d6cc5180d08d8460053
| 61,900 |
import requests
import json
def get_pushshift_submissions(query, sub):
"""
Retrieves Reddit submissions matching query term over a given interval
Parameters
----------
query : str
Query term to match in the reddit submissions
sub : str
Submission match query
Returns
-------
Dictionary with submissions data
"""
url = 'https://api.pushshift.io/reddit/search/submission/?q='+str(query)+'&size=1000'+'&subreddit='+str(sub)
print(url)
r = requests.get(url)
data = json.loads(r.text)
return data['data']
|
5f29854d90f0cd568cc525164ef25bbf6a2b2c50
| 655,765 |
import torch
def horners_method(coeffs,
x):
"""
Horner's method of evaluating a polynomial with coefficients given by coeffs and
input x.
z = arr[0] + arr[1]x + arr[2]x^2 + ... + arr[n]x^n
:param coeffs: List/Tensor of coefficients of polynomial (in standard form)
:param x: Tensor of input values.
:return z: Tensor of output values, same shape as x.
"""
z = torch.empty(x.shape, dtype=x.dtype, device=x.device).fill_(coeffs[0])
for i in range(1, len(coeffs)):
z.mul_(x).add_(coeffs[i])
return z
|
ee850e3ae1c7452db56ded1938431e38f275b473
| 373,905 |
from typing import List
def remove_punc(sentences: List[List[str]]) -> List[List[str]]:
"""
Remove punctuation from sentences.
Parameters
----------
sentences:
List of tokenized sentences.
"""
return [
[
"".join([c for c in word if c.isalpha()])
for word in sentence
if len(word) > 0
]
for sentence in sentences
]
|
de574fea31b9e89909656c9255b6ed1f891abb07
| 98,227 |
import itertools
def perm_parity(input_list):
"""
Determines the parity of the permutation required to sort the list.
Outputs 0 (even) or 1 (odd).
"""
parity = 0
for i, j in itertools.combinations(range(len(input_list)), 2):
if input_list[i] > input_list[j]:
parity += 1
return parity % 2
|
ae6a1feb170b26e0c5f1b580584889d2ecdea867
| 128,053 |
def search_for_vowels(phrase: str) -> set:
"""Returns set of vowels found in 'phrase'."""
return set('aeiou').intersection(set(phrase))
|
b7006216d00b9ab0529c9b41c4fa9533cd9fb78a
| 543,123 |
def merge(dicts):
"""Merge an iterable of dictionaries into one."""
d = {}
for d_ in dicts:
d.update(d_)
return d
|
f7b562549d91a4f451835ee126d9520842e75d89
| 467,004 |
def get_line_equation_coefficients(location1, location2):
"""
Get line equation coefficients for:
latitude * a + longitude * b + c = 0
This is a normal cartesian line (not spherical!)
"""
if location1.longitude == location2.longitude:
# Vertical line:
return float(0), float(1), float(-location1.longitude)
else:
a = float(location1.latitude - location2.latitude) / (location1.longitude - location2.longitude)
b = location1.latitude - location1.longitude * a
return float(1), float(-a), float(-b)
|
e4ea043a2818ffa6ccb03c07737c0f7c14f5f4c6
| 456,715 |
def euc_2d(n1, n2):
"""
The euclidean distance for 2D cartesian nodes
:param n1: first node
:type n1: Node
:param n2: second node
:type n2: Node
:return: the euclidean distance between first node and second node in 2D space
:rtype: float
"""
return ((n1.x - n2.x)**2 + (n1.y - n2.y)**2)**0.5
|
fc7370c09c6e000e7fe984aa1ea663f561fe59db
| 449,638 |
def build_flags(flags):
"""Convert `flags` to a string of flag fields."""
return "\n".join([" flag: '" + flag + "'" for flag in flags])
|
fdd8e6d2caee31ebe9956cf6248e9ef85e6cec6e
| 621,557 |
def hwc2chw(hwc):
"""Change the format of `hwc` from `(height, width, channels)` to `(channels, height, width)`
Args:
hwc (furry.Tensor): An image tensor with format `(height, width, channels)`.
Returns:
furry.Tensor: An image tensor with format `(channels, height, width)`.
"""
return hwc.permute(2, 0, 1)
|
75ff29e2371d38535cd0333c96992c36cba72be2
| 245,907 |
def make_transcript_PET_dict(infile):
""" Given a bedtools intersect file, this function creates a dictionary
mapping each transcript_ID to a set containing the RNA-PET IDs that
it matched to. """
transcript_2_pet = {}
with open(infile, 'r') as f:
for line in f:
line = line.strip()
entry = line.split("\t")
transcript_ID = entry[3]
rna_pet_ID = entry[9]
if transcript_ID in transcript_2_pet:
transcript_2_pet[transcript_ID].add(rna_pet_ID)
elif rna_pet_ID != "-1":
transcript_2_pet[transcript_ID] = set()
transcript_2_pet[transcript_ID].add(rna_pet_ID)
else:
transcript_2_pet[transcript_ID] = set()
return transcript_2_pet
|
2f7cbb1157142235dbf757a41a2197063ecd2a20
| 381,731 |
import importlib
def class_from_dotted_path(dotted_path):
"""Loads a Python class from the supplied Python dot-separated class path.
The class must be visible according to the PYTHONPATH variable contents.
Example:
``"package.subpackage.module.MyClass" --> MyClass``
Args:
dotted_path (str): the dot-separated path of the class
Returns:
a ``type`` object
"""
tokens = dotted_path.split('.')
modpath, class_name = '.'.join(tokens[:-1]), tokens[-1]
class_ = getattr(importlib.import_module(modpath), class_name)
return class_
|
4888ea47ffe3395452550fe2109df53d500f75f9
| 639,057 |
def request_url(lat, lon, maxpoints=0):
"""
Convert lat and lon to a url query string.
Converts lat and lon to a query string using osrm router.
Parameters
----------
lat : list
ordered list of all latitudes
lon : list
ordered list of all longitudes
maxpoints: int
maximum number of points to be included, defaults to all
Returns
-------
url : string
query url to be used for osrm routing
"""
# set maxpoints to len lat if added
if maxpoints == 0:
maxpoints = len(lat)
# how many points should we include? can we include all of them?
baseurl = 'http://router.project-osrm.org/match/v1/walking/'
options = '?overview=full&annotations=true'
coords = ''
# pick every nth coordinate up to maxpoints
npoints = len(lat) % maxpoints
point_interval = int(len(lat) / max(npoints, 1))
for i in range(npoints):
coords += str(lon[i * point_interval]) + ',' + str(lat[i * point_interval]) + ';'
return baseurl + coords[:-1] + options
|
491e990cc793bb771c9af3fdf50e8e7a78b245a4
| 427,100 |
def expose_header(header, response):
"""
Add a header name to Access-Control-Expose-Headers to allow client code to access that header's value
"""
exposedHeaders = response.get('Access-Control-Expose-Headers', '')
exposedHeaders += f', {header}' if exposedHeaders else header
response['Access-Control-Expose-Headers'] = exposedHeaders
return response
|
049383730da4fbc5a6286ed072655c28ea647c1e
| 48,768 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.