content stringlengths 39 9.28k | sha1 stringlengths 40 40 | id int64 8 710k |
|---|---|---|
from typing import Union
from typing import Tuple
from typing import List
def get_subdomain(
x: int, y: int, subdomains: Union[str, Tuple[str], List[str]] = "abc"
) -> str:
"""
Returns a subdomain based on the position.
Subdomains help supporting more simultaneous tile requests.
https://github.com... | e68046572c28c6bdf7f240772a11e37137890a44 | 235,286 |
def boxes_iou(box1, box2):
"""
Returns the IOU between box1 and box2 (i.e intersection area divided by union area)
"""
# Get the Width and Height of each bounding box
width_box1 = box1[2]
height_box1 = box1[3]
width_box2 = box2[2]
height_box2 = box2[3]
# Calculate the area of th... | 22735591c906af9592ce13fb76d7baa0a243c673 | 333,758 |
def non_empty(title: str, value: str, join_with: str = " -> ", newline=True) -> str:
"""
Return a one-line formatted string of "title -> value" but only if value is a
non-empty string. Otherwise return an empty string
>>> non_empty(title="title", value="value")
'title -> value\\n'
>>> non_empty... | fa7b2c332d72acf1f8b2196152504448b574d384 | 658,690 |
import time
import random
def printer(message: str) -> str:
"""
Prints a string to the stdout.
"""
# Use a random sleep to force printing order to be random, unless seq() is used.
time.sleep(random.random())
print(message)
return message | 0fe3972819aeb8999383b420cc8ea5c4933b9e91 | 233,764 |
import json
def get_inputs(sat: str):
"""Extacts arguments past the first from a function string
def f(a: Dict[int, str], b=12):
test
"""
sat = sat.replace(" -> bool", "")
first_line = sat.split("\n")[0].strip()
if "#" in first_line:
first_line = first_line[:first_line.index("#"... | 5114e068aa69e2d444b58d08747ca55a5cfbc6d9 | 517,392 |
import json
def format_errors(errors: dict) -> str:
""" Flattens a django validation error dictionary into a json string. """
messages = []
for field, field_errs in errors.items():
messages.extend([err["message"] for err in field_errs])
return json.dumps({"errors": messages}) | 70101c6d0458824b612ba2cd16a439c7aa35861b | 542,261 |
import torch
def top_k_accuracy(output, target, k=3):
"""
Function to calculate the top k accuracy of the model output.
Parameters
----------
output : multiple
Output of the neural network model
target : multiple
Ground truth value
k ... | e834d4f3d9576ea334f9564999a0bc3c1bc55df1 | 323,358 |
def extract_data(stdout):
"""Extract data from youtube-dl stdout.
Args:
stdout (string): String that contains the youtube-dl stdout.
Returns:
Python dictionary. For available keys check self._data under
YoutubeDLDownloader.__init__().
"""
data_dictionary = dict()
if n... | f34475135b006d57a6e5dcdc88a1277eaa20b81e | 448,132 |
def bit_bitlist_to_str(ordlist):
"""Given a list of ordinals, convert them back to a string"""
return ''.join(map(chr, ordlist)) | 7e36a2f5fa4e28ddb4bb909ce11c47761312fa27 | 358,367 |
def findMissing(aList, aListMissingOne):
"""
Ex)
Given aList := [4,12,9,5,6] and aListMissingOne := [4,9,12,6]
Find the missing element
Return 5
IDEA:
Brute force! Examine all tuples.
Time: O(n*m) and Space: O(1)
Smarter: Use a hashMap, instead!
Time: O(n+m) and Space: O(m... | df9241d0595831ac00e617b3bde023f341d1ea84 | 521,843 |
def filter_by_suffix(l, ignore, filter_dotfiles=True):
"""
Returns elements in `l` that does not end with elements in `ignore`,
and filters dotfiles (files that start with '.').
:param l: List of strings to filter.
:type l: list
:param ignore: List of suffix to be ignored or filtered out.
... | 9455c2514df1a53ac71d44e357ca944b3aecd8e7 | 490,324 |
from typing import Dict
from typing import Iterable
from typing import Any
def check_dictionary_keys(dictionary: Dict, required_keys: Iterable[Any], verbose: int = 0) -> bool:
"""
Check a dictionary for keys given an iterable of keys to check
Parameters
----------
dictionary : dict
The di... | 215dd9acc9c15d7fae7e862528de5917e5b08c0c | 306,463 |
def behavior_get_required_inputs(self):
"""Return all required Parameters of type input for this Behavior
Note: assumes that type is all either in or out
Returns
-------
Iterator over Parameters
"""
return (p for p in self.get_inputs() if p.property_value.lower_value.value > 0) | 13063f7708d518928aed7556ca9da7a851de6622 | 691,091 |
def is_unauthorized_response(response):
"""Checks if a response is unauthorized."""
if response.status_code == 401:
response_content = response.json()
message = 'Authorization has been denied for this request.'
if 'message' in response_content:
if response_content['message'] ... | 89359b32fa276a3fc14f0565cc91d73b22602a2d | 416,752 |
def prev(n, r):
"""The player after n."""
return (n - 1) % r.nPlayers | bdd1e398f6901c80b43c7e0f86668ca8870490f0 | 577,034 |
def map_to_range(min_1:float, max_1:float, min_2:float, max_2:float, value:float):
"""
This function maps a number of one range to that of another range.
Arguments:
min_1 : float/int : The lowest value of the range you're converting from.
max_1 : float/int : The highest value of the range you're converting ... | a70a1149390b49443a75283e9bfaa65981712ab6 | 291,995 |
def subsample_fourier(x, k):
"""Subsampling in the Fourier domain
Subsampling in the temporal domain amounts to periodization in the Fourier
domain, so the input is periodized according to the subsampling factor.
Parameters
----------
x : tensor
Input tensor with at least 3 dimensions, w... | 54c4af979f3fe2f8e439fa425b94dac7763ba76f | 117,344 |
def count_matching_pairs(arr, k):
"""
given a unique sorted list, count the pairs of elements which sum to equal k.
an element cannot pair with itself, and each pair counts as only one match.
:param arr: a unique sorted list
:param k: the target sum value
:return: the number of elements which su... | 5a566fba6bb5544056a2769a1ad4ca94c4ec07de | 344,077 |
from typing import Union
import re
def regex_iterator(text: str, regexes: Union[tuple, list]):
"""
Check a text string against a set of regex values
Parameters
----------
- text (str): a string to test
- regexes (Union[tuple, list]): a tuple/list of regexes
"""
result = None
... | 93b62b1bf4343c701cfa05f72accd453c4d38d0a | 152,456 |
def get_first_syl(w):
"""
Given a word w, return the first syllable and the remaining suffix.
"""
assert len(w) > 0
a = w[0]
n = 0
while n < len(w) and w[n] == a:
n = n + 1
return ((a, n), w[n:]) | a84c033582f89d1b4ec06983981696e17bdbefa6 | 92,213 |
def to_str(text, session=None):
"""
Try to decode a bytestream to a python str, using encoding schemas from settings
or from Session. Will always return a str(), also if not given a str/bytes.
Args:
text (any): The text to encode to bytes. If a str, return it. If also not bytes, convert
... | 74bcec023a7a8afea69c24a3dc2d7ae41247f461 | 627,731 |
import itertools
def itail(iterable):
"""Returns an iterator for all elements excluding the first out of
an iterable.
:param iterable:
Iterable sequence.
:yields:
Iterator for all elements of the iterable sequence excluding
the first.
"""
return itertools.islice(iterable, 1, None, 1) | df7f0ddabc493a3c9ae84b13e82208d7d05ef2e3 | 590,200 |
def scale(val, src, dst):
"""
Scale the given value from the scale of src to the scale of dst.
"""
return int(((val - src[0]) / float(src[1] - src[0])) * (dst[1] - dst[0]) + dst[0]) | c80aebd6a1b0162546eebd409cccb3d4cd073d9f | 538,392 |
from typing import List
from typing import Type
def validate_objects(elements: List, element_class: Type) -> bool:
"""
Check if all the elements are instance of the element_class.
Args:
elements: List of objects that should be instance of element_class.
element_class: class of the objects... | cd913ef4005d5360f8c2053ae30a72173e41d886 | 36,381 |
import re
def GetBackgroundColorTypeTagForTableValue(Color, ColorType):
"""Setup color type tage for setting background of a table value."""
ColorTypeTag = "class" if re.match("^colorclass", ColorType, re.I) else "bgcolor"
return ColorTypeTag | 6df7cb31b66ff38a228e618ee914281eee2da5b7 | 95,606 |
def _retrieve_start_nodes(net, mc):
"""
retrieve nodes with in_degree == 0 as starting points for main path analysis
args:
net: a CitationNetwork object
mc: minimum citations
returns:
list of start nodes in net
"""
return [node for node in net.nodes if (net.in_degree(node... | ff31c50a16a24efa37fbe53f0ba4b7bd9195cb0d | 51,167 |
def inventory(testdir):
"""
Create minimal ansible inventory file (such file contains just
single line ``localhost``).
"""
inventory = testdir.makefile(".ini", "localhost")
return inventory | 8544e81fd960fc400eee51fd07d6434fa4c16175 | 544,580 |
def get_primary_key(model):
"""
Return primary key name from a model. If the primary key consists of multiple columns,
return the corresponding tuple
:param model:
Model class
"""
mapper = model._sa_class_manager.mapper
pks = [mapper.get_property_by_column(c).key for... | 54daa5cde947d27b9b223d2b57062d44aea8d444 | 125,075 |
def to_rational(s):
"""Convert a raw mpf to a rational number. Return integers (p, q)
such that s = p/q exactly."""
sign, man, exp, bc = s
if sign:
man = -man
if bc == -1:
raise ValueError("cannot convert %s to a rational number" % man)
if exp >= 0:
return man * (1<<exp),... | 3dccd2acc324d8b748fe95290c49d961f1c636e1 | 28,957 |
def list_ids(txtfile: str) -> set[str]:
"""
Return a set containing the identifiers presented in a file,
line by line, starting with ">"
"""
identifiers = set()
with open(txtfile, 'r') as fi:
for line in fi:
line = line.strip()
identifiers.add(str(line).replace(... | 888ca238b57350c25c10e16880d1b8e9d9066788 | 499,573 |
from typing import Iterable
from typing import Union
from functools import reduce
from operator import mul
def get_product_of_iterable(
_iterable: Iterable[Union[float, int]]
) -> Union[float, int]:
"""Method to get the product of all the enteries in an iterable"""
return reduce(mul, _iterable, 1) | 73416ac38d503d66e1e2e6c5e6ab9cd6ab735549 | 261,689 |
def get_uncert_dict(res):
"""
Gets the row and column of missing values as a dict
Args:
res(np.array): missing mask
Returns: uncertain_dict (dict): dictionary with row and col of missingness
"""
uncertain_dict = {}
for mytuple in res:
row = mytuple[0]
col = mytuple[... | 336eebcd2fc64294ffe70a03988906eb29fca78c | 690,911 |
def select_from_view(view, targets):
"""
Identify the fragments of the view that contain
at least one of the targets
Args:
view (dict): if present, identifies the fragments that contain the
relevant units
targets (list): list of the fragments to search in the view
Return... | bb870cd4e3f57c2d626f4878f374cfedef2bba48 | 547,130 |
def single_dimensional_fitness(individual):
"""A simple single-dimensional fitness function."""
return pow(individual, 2) | 08e1573f8e7bed1f11fffedfdcbc1d69afc2a776 | 238,394 |
def join_with_last(items, sep=',', last_sep=' and '):
"""Join a sequence using a different separator for the last two items."""
if not items:
return ''
if len(items) == 1:
return items[0]
return ''.join([sep.join(items[:-1]), last_sep, items[-1]]) | fb52e35882dd4845cfe09b508063056ed4ccbbe8 | 317,639 |
def constant(connector, value):
"""the constraint that connector=value"""
constraint = {}
connector["set_val"](constraint, value)
return constraint | 36ff5a5da9be907b56b00bb10fa8a0817893913f | 349,705 |
def inject(variables=None, elements=None):
"""
Used with elements that accept function callbacks.
:param variables: Variables that will be injected to the function arguments by name.
:param elements: Elements that will be injected to the function arguments by name.
"""
def wrapper(fn):
... | 9b7ad2679acb4e1a3e01b0191d0af96fb88cc2de | 684,564 |
def char_to_float(c: int, f_min: float = -100., f_max: float = 50.) -> float:
"""Translates char number ``c`` from -128 to 127 to float from ``f_min`` to ``f_max``.
Parameters
----------
``c`` : int
value to translate
``f_min`` : float, optional
(default is -100)
``f_max`` :... | 4db07af994a4819495a10e274343aa5a0ed24a06 | 409,044 |
def expectation_description(expect = None, expect_failure = None):
"""Turn expectation of result or error into a string."""
if expect_failure:
return "failure " + str(expect_failure)
else:
return "result " + repr(expect) | 0a6944cbe83fbc14723526fd145ab816b86d2f0a | 642,839 |
def _check_state(monomer, site, state):
""" Check a monomer site allows the specified state """
if state not in monomer.site_states[site]:
args = state, monomer.name, site, monomer.site_states[site]
template = "Invalid state choice '{}' in Monomer {}, site {}. Valid " \
"state... | 8f61c91ddae5af378503d98377401446f69c37db | 695,914 |
def crop_size(height, width):
"""
Get the measures to crop the image
Output:
(Height_upper_boundary, Height_lower_boundary,
Width_left_boundary, Width_right_boundary)
"""
## Update these values to your liking.
return (1*height//3, height, width//4, 3*width//4) | 67e98e069585e6bc73beff47ae984861a850b89b | 421,481 |
def get_bounds(points):
"""
Returns the min and max lat and lon within an array of points
"""
min_lat = float("inf")
max_lat = float("-inf")
min_lon = float("inf")
max_lon = float("-inf")
for point in points:
min_lat = point["lat"] if point["lat"] < min_lat else min_lat
... | 5689e401ec8d51c88a38b0c0a3cbc334b305392b | 165,272 |
def gaussian_pdf(x: str = 'x', mean: str = r'\mu', variance: str = r'\sigma^2') -> str:
"""
Returns a string representing the probability density function for a Gaussian distribution.
**Parameters**
- `x`: str
The random variable.
- `mean`: str, optional
The mean of the random v... | f5da3be1ee4676fadb32e9da989ff83d1b8114ef | 87,110 |
import hashlib
def sha3_384(s):
"""Compute the SHA3 384 of a given string."""
return hashlib.sha3_384(s.encode("utf-8")).hexdigest() | 8ab13d08fd01d8377d0bd283af338ce1a93dc3f6 | 430,804 |
def getanmval(pvec, B, Y, W):
"""
Return the SHD for a single time-frequency bin
:param pvec: Vector containing M-channel STFTs of a single time-frequency bin
:param B: Response equalisation matrix
:param Y: SHD matrix
:param W: Cubature matrix
:return: SHD for a single time-frequency bin; ... | 3f00b26829a0d54fcec8b1d206ff2879625ba32f | 367,705 |
def fixBadHtml(source):
"""
Takes bad html lists and puts closing tags on the end of each line
with a list tag and no closing tag.
"""
# process each line on it's own
source = source.split('\n')
newSource = []
for line in source:
line = line.strip()
# check if its a... | 90085bc27269ada821c30f5675f5a147c55e9539 | 351,679 |
def cyclomatic_complexity(control_flow_graph):
"""Computes the cyclomatic complexity of a function from its cfg."""
enter_block = next(control_flow_graph.get_enter_blocks())
new_blocks = []
seen_block_ids = set()
new_blocks.append(enter_block)
seen_block_ids.add(id(enter_block))
num_edges = 0
while ne... | 5620c6715cb867c84b42128b0a15bdf7b6e2c7a7 | 460,100 |
import re
def get_cv_params(std_text):
"""accepts stdout generated by cross-validate, returns the "Best Model" Objects
for each validated fold as a list of lists of ints
Example output for a cv with four folds and s=24 might be
[[2, 0, 3, 2, 1, 0, 24],
[2, 0, 1, 2, 1, 0, 24],
[3, 0, 3, 0,... | c2d89ca99621ee2ce02a9026eafe4926a97876b1 | 385,121 |
import json
def read_ij_intensity (file):
"""Read a file that was written by the save_background.py ImageJ script.
Args:
file (str): Full path to .json file written by save_background.py
Returns:
intensity_data (dict): All data stored in the data file
"""
with op... | c7a9296dc97d5e0329d647bb184a68afe6298bfa | 179,772 |
def _load_alphabet(filename):
"""
Load a file containing the characters of the alphabet.
Every unique character contained in this file will be used as a symbol
in the alphabet.
"""
with open(filename, 'r') as f:
return list(set(f.read())) | c1088ffbb558bd2e244b145bcc4fa29fa96d6234 | 264,641 |
def comma_separated_arg(string):
""" Split a comma separated string """
return string.split(',') | 5e4626501e72efe0edaf33b81ef334ecc73dbc5f | 284,265 |
import json
def dumps_tree(tree, duplicate_action = 'list', **kwargs):
"""
Dumps a Tree as json.dumps.
First converts to_python using duplicate_action.
Additional kwargs are sent to json.dumps.
"""
obj = tree.to_python(duplicate_action = duplicate_action)
return json.dumps(obj, **kwargs) | 3419ef28cce2c77605ec9fedca173dcbc7ed6b8b | 629,433 |
def does_need_adjust(change, next_value, limit):
"""Check if change of the next_value will need adjust."""
return change and (next_value - 1 < 0 or next_value + 1 >= limit) | 07dccd9e7af67dda38043b57acc8c6923f5db1fa | 474,721 |
import random
def sample_without_replacement(mylist: list):
"""
Pick a random name from a list
return the name and the list without that name
Args:
mylist (list): list of items to pick from
Returns:
name (str): random item from the list
mylist_copy(list): mylist with name... | 2651135632ce1e072bbba076ca96f172981dc0ad | 602,663 |
import hashlib
import yaml
def det_hash(x):
"""Deterministically takes sha256 of dict, list, int, or string."""
return hashlib.sha384(yaml.dump(x).encode()).digest()[0:32] | 103c9844c1f59e085ae2747da49c505e166416d5 | 472,309 |
def doc_key(locale, doc_slug):
"""The key for a document as stored in client-side's indexeddb.
The arguments to this function must be strings.
"""
return locale + '~' + doc_slug | 39e9a794c0b8239b946d4c2e461fbd4949a8d171 | 498,923 |
import importlib
def import_module(module, package=None):
"""Protected import of a module
"""
try:
ret = importlib.import_module(module, package=package)
except ModuleNotFoundError:
if package is not None:
raise ModuleNotFoundError("Requested module/package '{}/{}' not foun... | bfc215aed80575c5802759fcbce4b2d48b4a6505 | 573,820 |
def tmp_working_directory_path(tmp_path) -> str:
"""
Return a path to a temporary working directory (different path for each test).
"""
destination = tmp_path.joinpath("obfuscation_working_dir")
destination.mkdir()
return str(destination) | 44a155ebc3b0c3bfe36b951dcdfb84180f108b79 | 626,492 |
import re
def get_job_details(job):
"""Given a Nomad Job, as returned by the API, returns the type and volume id"""
# Surveyor jobs don't have ids and RAM, so handle them specially.
if job["ID"].startswith("SURVEYOR"):
return "SURVEYOR", False
# example SALMON_1_2323
name_match = re.matc... | 21afd0ac3fcdc1c320eefd9a84ee05a8a1f56ee7 | 139,763 |
def map_coords_to_scaled_float(coords, orig_size, new_size):
"""
maps coordinates relative to the original 3-D image to coordinates corresponding to the
re-scaled 3-D image, given the coordinates and the shapes of the original and "new" scaled
images. Returns a floating-point coordinate center where t... | f5e1e1523366a9e1e37f9d1a304d9deea8d53e00 | 9,346 |
from typing import List
from typing import Dict
def _missing_required_keys(
required_keys: List[str], found_keys: List[str]
) -> Dict[str, str]:
"""Computes an error message indicating missing input keys.
Arguments:
required_keys: List of required keys.
found_keys: List of keys that were ... | e62adfd5be46a41728b83e944b56ea8c37063c49 | 391,759 |
def filter_keys(d, key_whitelist):
"""
Removes keys from a dictionary that are not
in the provided whitelist.
Args:
d: The dictionary to update.
key_whitelist: The list of allowed keys.
Returns:
The updated dictionary.
"""
for key in d.keys():
if key not... | 60c7892bd9582aca0f753b0feb8c9e4a20cffd7b | 439,942 |
def check_diagonal_winner(input_list, size):
"""
Check the winner number in diagonal direction.
Arguments:
input_list -- a two dimensional list for checking.
size -- the length for winning.
Returns:
winner -- the winner player number, if no winner return None.
"""
for row_... | 01e87dcf163f3705238d554f36f92631da2175d9 | 279,189 |
def global_max_pool2d_check(expr):
"""Check if the nn.global_max_pool2d can be executed in BNNS"""
attrs, args = expr.attrs, expr.args
data_typ = args[0].checked_type
rank = len(data_typ.shape)
if rank < 3 or rank > 4 or data_typ.dtype != "float32":
return False
if attrs.layout != "NCHW"... | d418dbc98b5a01327f90bec63b5bface10951ed8 | 380,216 |
def comp_slope_value(qvec):
"""
Returns the fixed point increment per unit increase in binary number.
"""
frac_width = qvec[1]
return 2.**(-frac_width) | 99c3699a9ac47d41e389e5544c0b6f2355c54bb7 | 468,913 |
def bool_to_string(bool):
""" Converts True / False into 'Yes' / 'No'
Returns:
string: 'Yes' or 'No'
"""
return 'Yes' if bool else 'No' | bce695263aaeccf5123c0d059dbdad336023bd1e | 552,939 |
def __hash_combine(h1, h2):
"""
Combine two hash values to create a new hash value
:param h1: int
:param h2: int
:return: int
"""
h1 = h1 ^ (h2 + 0x9e3779b9 + (h1 << 6) + (h2 >> 2))
return h1 | c388d03c9cf6f70096331f3e74c38716f192d23a | 211,640 |
def get_media_stream(streams):
"""Returns the metadata for the media stream in an MXF file,
discarding data streams."""
found = None
for stream in streams:
# skip 'data' streams that provide info about related mxf files
if stream['codec_type'] == 'data':
continue
if f... | 563ef35c2be3e9787340d7527e7fd0f27b6db036 | 694,879 |
def isolate_path_filename(uri):
"""Accept a url and return the isolated filename component
Accept a uri in the following format - http://site/folder/filename.ext and return the filename component.
Args:
uri (:py:class:`str`): The uri from which the filename should be returned
Returns:
... | 5b04e36bc8a1b47c8b7af3892d083f73528e7391 | 584,425 |
import torch
def make_one_hot(position: int, length: int) -> torch.Tensor:
"""
Makes a 1D one hot vector of length l with a one at index position, rest all zeroes
Arguments:
position (int): index at which the one hot vector would have one
l (int): length of the one hot vector
Returns... | 84c38438df4310a4c0c5cb7bcc830a49c142c221 | 173,788 |
def check_ascii_compliance(plaintext):
"""Returns true if all the characters of plaintext are ASCII compliant (ie are in the ASCII table)."""
return all(c < 128 for c in plaintext) | b8c3328793387baf78b8ce5b9a00499d51a37c1e | 587,075 |
def get_elapsed(begin, end):
"""
Return the number of minutes that passed between the specified beginning
and end.
"""
return (end - begin).total_seconds() / 60 | 08bfa2e3d0bfa63fca62d693894b6021f9092755 | 187,894 |
def footer(id1, id2 = None):
"""
Build SMT formula footer
Args:
id1 (str): ID of policy 1 in SMT formula
id2 (str, optional): ID of policy 2 in SMT formula. Defaults to None.
Returns:
str: SMT footer
"""
smt = '(assert {}.allows)\n'.format(id1)
if id2:
smt... | c9af2ad7453282e1611e7b2010f4269ca8ac0bc0 | 46,252 |
def _convert_sensor_enabled_flag_11_2(byte):
"""Convert the old sensor enabled flags to the new one."""
conversion_map = {0x01: 0x02, 0x02: 0x10, 0x04: 0x08, 0x08: 0x80} # gyro # analog # baro # temperature
# always enable acc for old sessions:
out_byte = 0x01
# convert other sensors if enable... | f2f01f8756fa3f6ec8c766f85373fa9f977bd7db | 461,614 |
import re
def escape_regex(regex):
"""
Escape regex metachars so user does not have to backslash them on command line
:param regex: The regular expression to backslash metachars in
:return: Properly backslashed regular expression metachars in regex
"""
# src: https://stackoverflow.com/quest... | e5cd00fb7fe57c3c1343dc870f7c1ed24888839b | 463,849 |
from typing import Optional
from typing import List
def _check_str_input(var, input_name: str, valid_options: Optional[List[str]] = None) -> str:
"""
_check_str_input
Convenience function to check if an input is a string. If argument valid_options is given, this
function will also check that var is a... | 357a8516fe65dddb35b7799ddc68b892da75ea02 | 147 |
def get_chunks(lo, hi, size, overlap=500):
"""
Divides a range into chunks of maximum size size. Returns a list of
2-tuples (slice_range, process_range), each a 2-tuple (start, end).
process_range has zero overlap and should be given to process_chromosome
as-is, and slice_range is overlapped and sho... | 1a0ddf94eef86127e260d1985dc7bbada973da47 | 425,208 |
def parse_mode(mode_data):
""" Takes in a mode string and parses out which are to be added and which
are to be removed.
>>> mode_data = "+ocn-Ct"
>>> parse_mode(mode_data)
('ocn', 'Ct')
"""
add = remove = ""
directive = "+"
for char in mode_data:
if char... | e1893c1293807f78acb4a45767f1f4f8564e932b | 348,149 |
def get_info_or_create(source_dict, key, default_value):
"""
This returns the value of the key if it exists
else it creates the key with the default value and returns it
"""
try:
info = source_dict[key]
return info
except KeyError:
info = source_dict[key] = default_value
return info | 78c2e1768afac425fa04b533697ad70fa95f737c | 426,305 |
def get_func_pos_args_as_kwargs(func, pos_arg_values):
"""Get the positional function arguments as keyword arguments given their values"""
pos_arg_names = func.__code__.co_varnames[
1 : func.__code__.co_argcount
] # without the `step` argument
kwargs = dict(zip(pos_arg_names, pos_arg_values))
... | e12b78f78715a54589fa6be366144e2e6980d118 | 243,704 |
from functools import reduce
def _bigint_bytes_to_int(x):
"""Convert big-endian bytes to integer"""
return reduce(lambda o, b: (o << 8) + b if isinstance(b, int) else ord(b), [0] + list(x)) | 83d1b34b4e40b5e8a084eb0685020900adba88da | 365,891 |
def merge_caption(marker_dict):
"""Treat first value as a caption to the rest."""
values = list(marker_dict.values())
if not values:
return ''
elif len(values) == 1:
return values[0]
else:
return '{}: {}'.format(values[0], ' '.join(values[1:])) | 9e471fe7e161f1a8ff0f8051bc06398758c7c40d | 156,519 |
def add(number_1: int, number_2: int) -> int:
"""Adds two numbers together."""
return number_1 + number_2 | 65e730a7dea68324e9ec7e2d56238d84ab93158d | 486,142 |
def cmyk2rgb(C, M, Y, K):
"""CMYK to RGB conversion
C,M,Y,K are given in percent.
The R,G,B values are returned in the range of 0..1.
"""
C, Y, M, K = C / 100., Y / 100., M / 100., K / 100.
# The red (R) color is calculated from the cyan (C) and black (K) colors:
R = (1.0 - C) * (1.0 - K)
... | 47d076f90578ed76fd5e153690f3042b0eba3bc7 | 180,972 |
def rgb2bgr(x):
"""
Convert clip frames from RGB mode to BRG mode.
Args:
x (Tensor): A tensor of the clip's RGB frames with shape:
(channel, time, height, width).
Returns:
x (Tensor): Converted tensor
"""
return x[[2, 1, 0], ...] | c5672fe1290d641fede5395184be7b8d86e08d8f | 224,116 |
def a_r(P,R,M,format='days'):
"""
function to convert period to scaled semi-major axis.
Parameters:
----------
P: Period of the planet.
R: Radius of the star in units of solar radii.
M: Mass of star in units of solar masses
format: Unit of P (str). Specify "days" or "... | 880bf9d2da6908f599a906c547ede016100aa080 | 247,721 |
def _maybe_parse_as_library_copts(srcs):
"""Returns a list of compiler flags depending on whether a `main.swift` file is present.
Builds on Apple platforms typically don't use `swift_binary`; they use different linking logic
(https://github.com/bazelbuild/rules_apple) to produce fat binaries and bundles. T... | 02d96244f892b7a68731e8bc9c451727dfa1636b | 465,151 |
import ast
def replace_fields(node, **kwds):
"""
Return a node with several of its fields replaced by the given values.
"""
new_kwds = dict(ast.iter_fields(node))
for key, value in kwds.items():
if value is not new_kwds[key]:
break
else:
return node
new_kwds.upd... | bc37c0a6b24ffc1d2a2bcbd055efe26234909466 | 657,720 |
def warn_config_absent(sections, argument, log_printer):
"""
Checks if the given argument is present somewhere in the sections and emits
a warning that code analysis can not be run without it.
:param sections: A dictionary of sections.
:param argument: The argument to check for, e.g. "files".... | a0c65f455a03624f69b2fd1b026ba88933226501 | 342,932 |
def yes_no_checker(string):
"""Gets user input, if yes returns True,
else if no, returns false"""
yes_list = ['yes', 'y', '1']
no_list = ['no', 'n', '0']
while True:
try:
answer = input(string)
if answer.lower() not in yes_list and answer.lower() \
... | c6e0c221d354cfe6a93f8b9bd09a776b1aeb9b4b | 571,188 |
from io import StringIO
import tokenize
def should_quiet(source: str) -> bool:
"""
Should we suppress output?
Returns ``True`` if the last nonwhitespace character of ``code`` is a semicolon.
Examples
--------
>>> should_quiet('1 + 1')
False
>>> should_quiet('1 + 1 ;')
True
>>... | b4070a293c1cee002743c3ee2b79ccf1fdda99fc | 166,098 |
import re
def parse_country(text: str) -> list:
"""
Get covid data of each countries in the world
:param text: text to be parsed
:return: (country_name, confirmed, suspected, cured, dead, timestamp)
"""
pattern = re.compile(
r',\"provinceName\":\".*?\",.*?'
r'\"confirmedCount\"... | c2a66092b617def6e221a2dc09c987c22ef050e0 | 341,236 |
def built_before(building, timestamp, player):
"""Get list of buildings constructed before a given time."""
result = []
for item in player['build']:
if item['building'] == building and item['timestamp'] < timestamp:
result.append(item)
return result | 4d7dd2fce525ad79713034c458bf2ef78459a27e | 612,601 |
def _is_dunder(function_name: str) -> bool:
"""Checks if a function is a dunder function."""
return function_name.startswith("__") and function_name.endswith("__") | c61a8d47a2e66acaf2c9dd9660cb758ef5959720 | 440,868 |
def attrs(m, first=[], underscores=False):
"""
Given a mapping m, return a string listing its values in a
key=value format. Items with underscores are, by default, not
listed. If you want some things listed first, include them in
the list first.
"""
keys = first[:]
for k in m.keys():
... | 6c37a33233730c10ada96c162885f1277d1e38e6 | 519,104 |
def parse_raw_intervals(str_list):
"""Decode serialized CCDS exons.
Accepts a formatted string of interval coordinates from the CCDS
row and turns it into a more manageable list of lists with
(start, end) coordinates for each interval (exon).
.. code-block:: python
>>> parse_raw_intervals('[11-18, 25-3... | 9172297ff177d29c08a18d56aff5b40bd6ba5b2c | 316,637 |
def parseUnits(value, units):
"""
Parses a value with a unit and returns it in the base unit.
:param value: str The value to parse
:param units: list of tuples of unit names and multipliers
:return: int
"""
n = len(value)
for i, c in enumerate(value):
if c.isalpha():
n = i
break
numberStr = value[:n]... | e920ac498231e05cb05e312a6b9746d26aeebe6f | 271,167 |
def atomic_mass(a):
""" Atomic mass of atom """
return a.GetMass() | 02e66d924ecfa6918562f839cf6549de13ce698c | 215,408 |
def filterResultsByRunsetFolder(runSets, form):
"""
Filters out results that don't have the specified runsetFolder name
"""
ret = []
for runset in runSets:
if runset.runsetFolder == form['runset'].value:
ret.append(runset)
return ret | a9416fa8f96aa2dc370c23260f65bfb53114e09a | 694,760 |
def total_heat_sum_error(spf_heat_data):
"""Total values for heating and overall heating spf.
Uses heating operational data. Calculate total heat extracted from
ground and absolute error. Also calculates spf and fractional error.
Parameters
----------
spf_heat_data : pd.Dateframe
Heatp... | c15c07c984a11b2732ee7ed47c6263db18156e10 | 647,073 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.