content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def write_vcf(lines, vcf):
"""Create a file from the provided list"""
with open(vcf, "w") as vcf_handle:
vcf_handle.write('\n'.join(lines))
return vcf | 4013d0934faede1ca2cab25c133b3f485d9dea29 | 606,154 |
import random
import string
def generate_random_filename_safe_text(length: int = 4) -> str:
"""
Generates a (not cryptographically safe) random filename-safe string.
Args:
length:
Length of the random text.
Returns:
Generated text.
"""
return "".join([
ran... | f333fb715e0e2834c263271c1b7f25e1ddcb80dd | 606,155 |
def reconstruct_path(came_from, start, goal):
"""Reconstruct a shortest path from a dictionary of back-pointers"""
current = goal
path = [current]
while current != start:
current = came_from[current]
path.append(current)
path.append(start) # optional
path.reverse() # optional
... | 5038543c9a14798a004764c5a182c6c68476d693 | 606,157 |
import ipaddress
import socket
def _matches_machine_hostname(host: str) -> bool:
"""Indicates whether ``host`` matches the hostname of this machine.
This function compares ``host`` to the hostname as well as to the IP
addresses of this machine. Note that it may return a false negative if this
machine... | 93a4111028aeb5d2341511d455c14c45e7161813 | 606,167 |
def AnyInSet(operator):
"""
Apply an operator to all elements in a set and check if any of them return true
"""
return lambda elem, val: any(map(lambda item: operator(item, val), elem)) | 3d305b3d8268e3b7cd77d95a5bcf00f310316d7b | 606,170 |
import re
def extract_jump(message, args, pipeline_data):
"""
Extracts a jump command from the data, and proceeds to the next step.
Jump commands have the same syntax as Go To Anything
e.g.:
@ to jump to a symbol
: to jump to a line
# to jump to an instance of the text
NOT... | d1950bb2e001b602b1223c57b8c74ba02373d8b2 | 606,173 |
from typing import Counter
def parse(filename):
"""Parse the input file into Python objects.
Input file has lines like this:
sdfsjdfk sjdkf lfke ljrl (contains dairy, soy)
Parameters:
filename (str): the name of the input file to open
Returns:
candidates (Dict[str, Set[s... | bd2ca6dcd3c843d462a4d3faf507c47fb49b8984 | 606,175 |
def standardize_severity_string(severity):
"""
Returns the severity string in a consistent way.
Parameters
----------
severity : str
The severity string to standardize.
Returns
-------
severity : str
The standardized severity string.
"""
return severity.title() | a52e3f0b299d25d56425f2c5cdd69bb43825e8c3 | 606,176 |
import copy
def get_output_tensors(sub_graph):
""" Get all output tensor names of a sub_graph.
Args:
sub_graph: A SubGraph instance.
Returns:
A set contains all output tensor names of the sub_graph.
"""
output_tensors = copy.deepcopy(sub_graph.output_ops)
for name in sub_graph.output_subgraphs:
... | e306c008b7e9def31ec887dd3ab03e3f3f80333c | 606,179 |
def nmea2deg(nmea):
""" convert nmea angle (dddmm.mm) to degree """
w = float(nmea) / 100.0
d = int(w)
return d + (w-d) * 100 / 60.0 | dd09240ab274a773ba8758bd19721210bd9d91b5 | 606,185 |
from typing import Any
def _is_atomic(obj: Any) -> bool:
"""
Returns True for objects which are iterable but should not be iterated in
the context of indexing an OrderedSet.
When we index by an iterable, usually that means we're being asked to look
up a list of things.
However, in the case o... | d925ade85cd16e0330163583a9ce4843b578c2d4 | 606,190 |
def cluster_kubeconfig(name, server, ca_data):
"""Generate and return a cluster kubeconfig object."""
return {
"name": name,
"cluster": {
"server": server,
"certificate-authority-data": ca_data,
},
} | 4801c8967d42da0591d93c7d216827b9fe077f7f | 606,199 |
import functools
def memoize(f):
"""Decorator that can be applied to a method to memoize the results.
Args:
f - The function to decorate with memoization. The first argument of
the function should be self - the instance of the class. The
function can take an arbitrary amount of additional positio... | 53033e66e5e9aa0f9817118b54bb83ab3b982b45 | 606,200 |
def _partition_products_by_language(products):
""" Partitions the given product models into language buckets of product id's.
:param products: a list of product models.
:returns: a map {language: set of product_id's}.
"""
products_by_language = {}
for product in products.values():
... | a6b4a98141626ee3cb64857e01de68ffe7a8d69d | 606,201 |
from tokenize import NEWLINE, INDENT, DEDENT, tokenize
import io
def get_list_representation(cflow_output):
"""Return a list object representation of the output from cflow
Example:
If cflow_output is:
main() <int () at main.c:18>:
f() <int () at main.c:4>:
malloc()
pri... | 0a27066cda33e45c2b3f676a283bc3dd60cddc5e | 606,204 |
def numel_(a):
"""
function which returns the number of elements of a
"""
return a.size | 3561a203a2611d1fe49f96beb376f04283bea094 | 606,208 |
import math
def is_prime(n):
"""
Check whether the given number is prime
:param n: the given number
:type n: int
:return: whether the given number is prime
:rtype: bool
"""
for i in range(2, int(math.sqrt(n))):
if n % i == 0:
return False
return n > 1 | 56a88fb1303e3810ad5edfcaddf25f2f4b67343b | 606,211 |
from typing import Dict
def get_cache(config) -> Dict[str, list]:
"""Prepare a cache dictionary
Args:
config (ColocationConfig): configuration file
Returns:
Dict[str, list]: cache dict
"""
cache: Dict[str, list] = {}
if config.plot_fitness_density:
cache['fitnesses']... | aed4888ad0f02a064b4f304223de2a688c60f4fc | 606,215 |
def extract_action_list_from_path(path_list):
"""
Converts a block idx path to action list.
Args
path_list: <list> list of block idx from source block to dest block.
Returns
action_list: <list> list of string discrete action commands (e.g. ['movesouth 1', 'movewest 1', ...]
"""
... | 735a78c77e9100d64b83f3b6d031381fc4de5586 | 606,216 |
import time
def timeit(f):
"""
time a function by applying a decorator
Parameters
----------
f: function
Returns
-------
a decorated function
"""
def new_f(*args, **kwargs):
bt = time.time()
r = f(*args, **kwargs)
et = time.time()
print("tim... | 63923c976ea3f1d1583dd8d3661e148784dbd83b | 606,218 |
from typing import Iterable
import itertools
def groupby(key, iterable: Iterable):
"""
Получение словаря, сгруппированного по ключу
из неупорядоченной последовательности словарей
>>> users = [{'gender': 'female', 'age': 33}, {'gender': 'male', 'age': 20}, {'gender': 'female', 'age': 21}]
>>> group... | b26566316ca5c9890c7be7a4424551b6e16e25e9 | 606,219 |
def min_first(iterable):
"""Returns the smallest value of all items in the iterable, compared by their zeroth elems."""
return min(iterable, key=lambda element: element[0]) | c7a9eea54011ddf8993313de9e07b8d704dd338c | 606,223 |
import json
def match_epi_fmaps(bold_pedir, epi_fmap_one, epi_fmap_params_one,
epi_fmap_two=None, epi_fmap_params_two=None):
"""Parse the field map files in the data configuration and determine which
ones have the same and opposite phase-encoding directions as the BOLD scan
in the curr... | 8c076deb95c7c7a4c619e6b24396874402a29b6a | 606,224 |
def mpg(start, end, gal):
"""This function takes a starting odometer reading,
an ending odometer reading, and a volume of gas burned
to traverse the difference, and returns mpg."""
return (end-start)/gal | d322ac57789a9cbcb6f39667e716015816158e3b | 606,226 |
import io
import json
def read_from_json(json_file_path):
"""Function to read json file (annotation file)"""
with io.open(json_file_path, "r", encoding="utf-8-sig") as myfile:
data = json.load(myfile)
return data | 4aa6c1efdcc634b88a7f831e78cb28d13742d7b8 | 606,229 |
def outline_gcp_project(project_index, project, zone, key_file_path):
"""Return a summary of a GCP project for logging purpose.
Arguments:
project_index (int): Project index.
project (Resource): GCP Resource object of the project.
zone (str): Name of the zone for the project.
ke... | e01730c49c7879a38ac54cbf28aa9a55546cb7b4 | 606,231 |
def getRange(xs, ys, xMin, xMax):
"""
Return the Ys for the range of points where the Xs
is at or between the given min/max limits
"""
rangeYs = []
for i in range(len(ys)):
x = xs[i]
if(x >= xMin and x <= xMax):
rangeYs.append(ys[i])
if len(rangeYs) == 0:
... | decd0e65175fae625e50720b860680b313004ddf | 606,233 |
def is_valid_channel_name(name):
"""
Return True if the given name is a valid channel name.
"""
# Check channel name length
if len(name) == 0 or len(name) > 50:
return False
# Check if channel name is valid
valid = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789`~!@#... | fd4db526972746d0f4fda9d8055e58c93da131c3 | 606,234 |
import re
def exclude(images, excludes, verbose):
"""Return the images that don't match the regexes in the excludes list."""
remaining_images = images.copy()
regexes = [re.compile(r) for r in excludes]
# pylint: disable=invalid-name
for (Id, image) in images.items(): # noqa: N806
for tag ... | 9c9d84e2eae5facaeb98daa6eca3a045e3d31ef2 | 606,236 |
import unittest
def requires_attr(obj, attr):
"""Decorator used to skip tests if an object does not have the required
attribute.
"""
try:
getattr(obj, attr)
return lambda func: func
except AttributeError:
return unittest.skip('Required attribute "{}" not found on {}'.forma... | 3728cbd17e83c85f6595e62fce962cf7cb4992c2 | 606,240 |
def Identity(X):
"""
Identity fuction is the basic activation function
It return the same input value as output.
Parameters:
- X: int ,-Inf to +Inf
Returns:
X , -Inf to +Inf
"""
return X | 1b7d1f912e04fed5b503960a0ecd9bf9811ab19b | 606,243 |
import socket
import fcntl
import struct
def get_ip(iface='eth0'):
"""
Use Linux SIOCGIFADDR ioctl to get the IP for the interface.
ref http://code.activestate.com/recipes/439094-get-the-ip-address-associated-with-a-network-inter/
"""
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
re... | 6ec4bf3f5e4b49fc7441f2e33d151a39d9b3fa7b | 606,244 |
import torch
def extract_into_tensor(arr, timesteps, broadcast_shape):
"""Extract values from a 1-D numpy array for a batch of indices.
Args:
arr: the 1-D numpy array.
timesteps: a tensor of indices into the array to extract.
broadcast_shape: a larger shape of K dimensions with the batch dimension
... | 2c3d1d34edff499cfc8b3c55d6bc5fc5b6c741cb | 606,245 |
def iscircular(linked_list):
"""
Determine whether the Linked List is circular or not
Args:
linked_list(obj): Linked List to be checked
Returns:
bool: Return True if the linked list is circular, return False otherwise
"""
if linked_list.head is None:
return False
slow... | 3a195f57de0da335acf20fbbdaf23af028ecd4b8 | 606,247 |
def default_timeout(variables):
""" Default page timeout """
return variables.get('default_timeout', 10) | a2fa0c05ec252dc3baaf3804e496c1ed27c48271 | 606,248 |
def get_fips(geocode):
"""
Return and array of FIPS6 codes which identify the county regions
effected by the weather alert.
FIPS6 is a code which uniquely identifies counties in the United States.
For more info: https://en.wikipedia.org/wiki/FIPS_county_code
FIPS returned by NWS alerts can b... | 05e292d8b2237d06a8379b488cff290ec4fcf656 | 606,249 |
def binaryToInt(string):
"""
Convert binary string to integer
"""
return int(string[::-1], 2) | 19d4a55578859982ee2457c8053a34d761b08271 | 606,250 |
import torch
def weighted_mpjpe(predicted, target, w):
"""
Weighted mean per-joint position error (i.e. mean Euclidean distance)
"""
assert predicted.shape == target.shape
assert w.shape[0] == predicted.shape[0]
return torch.mean(w * torch.norm(predicted - target, dim=len(target.shape) - 1)) | a3b5caf97f1b97f363dfaac19af60a216624f0e9 | 606,253 |
def get_E2K_subdict(the_dict, main_key, sub_key):
"""Returns the subdictionary specified by main_key
and sub_key, returning an empty dictionary if any is missing.
This is for use in the post-processing functions."""
return the_dict[main_key].get(sub_key, {}) \
if the_dict.get(main_key) else {} | 498ad7f9d6a471d90efd509333f764d9f39f21c8 | 606,254 |
def solution(A):
"""
On the face of it this is quite simple, until you factor in negative
numbers.
Approach is very simple:
1. Sort array in descending order (or ascending if you like)
2. Take the max value in between the sum of the head of the array and the first
element of the array c... | ad8b58e8bb9fe9959afed7b95f7abdbe05742a11 | 606,258 |
def format_user_results(user: dict):
"""
Formats and truncates the user result from the Slack API
Args:
user: The user response retrieved from the Slack API
Returns:
Formatted and truncated version of the result which is context safe.
"""
return {
'name': user.get('name'... | 1c44bfd46e73357ff78f7411255d39b536a4735a | 606,263 |
import random
def random_int(from_: int = 0, to: int = 10) -> int:
"""Generate random int within range from_, to
Arguments:
from_ {int} -- lower limit, default 0
to {int} -- upper limit
Returns:
int -- random number
"""
return random.randint(from_, to) | a2f463783df6c4763ba1cd03d48eda4780406802 | 606,265 |
def initial_value_count(input_list):
"""
Args:
input_list (list[int]): A non empty list of python integers
Returns:
Tuple[int, int]: Returns the first value of input_list, and
the number of times it consecutively appears in the list
from the beginning.
"""
assert l... | 495fa5dcccf3d109579c4d80f650ff1d9d496b00 | 606,267 |
def head2pres(head, z, rref, grav, psurf):
"""
Compute pressures from head.
Parameters
----------
head : Numpy array
One/Two/Three dimensional array of equivalent head values.
z0 : float
z-variables of model, same dimension as head-array.
rref : float
Reference den... | c3c2b37cdcc62c151d1ff43393b12ce6ac54ef5f | 606,268 |
import calendar
def datetime_to_timestamp(utc_dt):
"""Returns UTC datetime as a POSIX timestamp (seconds since epoch).
Args:
utc_dt: a datetime.datetime object storing a UTC date and time.
Returns:
The UTC date and time as whole seconds since epoch. Leap seconds
(utc_dt.second > 5... | eb2f30a5958eb3c7a6902a022e53ba54bec96b3c | 606,269 |
def crop(im, r, c, sz):
""" crop image into a square of size sz, """
return im[r:r + sz, c:c + sz] | 1127fc439193d8c4cffb4412d1cf694c24c6ef76 | 606,270 |
def euclidean_dist(p1, p2):
"""
Returns the euclidean distance between points (p1, p2)
in n-dimensional space.
Points must have the same number of dimensions.
"""
if len(p1) != len(p2):
raise ValueError("Points must have the same number of dimensions.")
return sum((d1 - d2) ** 2 for... | 3f2ff5da253e14765074b97e322bc3042fbe58b9 | 606,272 |
def getChapterStatus(dic):
"""Returns the current status of the relevant chapter.
dic -- Dictionary from the JSON with all values.
"""
return str(dic["content"]["$t"]).split(',')[5].split(':')[1].strip() | 53389005737e11728b4b7be366497c1925a0b449 | 606,276 |
def int_to_smile(array, indices_token, pad_char):
"""
From an array of int, return a list of
molecules in string smile format
Note: remove the padding char
"""
all_mols = []
for seq in array:
new_mol = [indices_token[int(x)] for x in seq]
all_mols.append(''.join(new_mol).re... | 2175358b9eb6c1a1b8ea24f6938ecfe7160aa351 | 606,277 |
def custom_score(word, opt):
"""Make your custom word score. Just put in a dictionary each letter being assigned a score.
Args:
word: the word to get the score of
opt: the options to use.
Retuns:
The word in the score opt gave.
Raises:
Exception: if opt is not a dict
... | 5e5ff0331be2b59d83a28c5f4399520811a2befa | 606,285 |
import math
def next_pow2(value):
"""Returns next power of 2 for a number"""
return float(1 << int(math.ceil(math.log2(value)))) | 7d65c1e5ce73cbe44cc65a9d34073077170323e8 | 606,290 |
def check_observing(survey, pick, program):
"""
Based on programs that have selected a given target, this will figure out which
observing method requires the most observing time and then scales other program's
costs based on that.
Parameters
----------
survey : survey.Survey
class o... | b0efa82a0ed4c8b0302b2a86a5e9baf072962f16 | 606,293 |
def compose(*values):
"""
Compose the specified 8-bit *values* into a single integer.
"""
result = 0
for i, value in enumerate(values):
result |= value << (i * 8)
return result | b5bff39c39b9b880a3e769833afef3ee98f1a2eb | 606,301 |
def absmin_diff(current, prevs):
"""Min of differences between current sample and all previous samples.
Given more than one min, use the last one detected which is probably a
newer value. Returns (difference, prev used)
"""
diffs = [abs(current-prev) for prev in prevs]
smallest_pos = 0
small... | 712da3fc013f9f06cc55bed230634de5dfda8e85 | 606,303 |
import torch
def psd_safe_cholesky(A, upper=False, out=None, jitter=None):
"""Compute the Cholesky decomposition of A. If A is only p.s.d, add a small jitter to the diagonal.
Args:
:attr:`A` (Tensor):
The tensor to compute the Cholesky decomposition of
:attr:`upper` (bool, optional... | e58a0601b321451d2a194133869697c61572e79e | 606,307 |
from pathlib import Path
def non_existing_file(tmp_path):
"""Returns a path to a non existing file"""
return Path(tmp_path).joinpath('usermapping') | 1607cd2022731e8b77ecf044cf5dada8832a6a32 | 606,326 |
def get_group_policy_names(iam_client, groups):
"""
Returns the group policy names of the current user
Args:
iam_client (obj): IAM client obj
groups (list): User groups
Returns:
policy_names (list): List of group policy names the current user has
"""
policy_names = []
... | d0bde09f346a8ea5e5fd2993f7fca712389f081b | 606,328 |
def eliminate(problem, location, listOfLocations):
"""
Given a list of locations, eliminate from the problem the number that is
present at the `location`.
:param list problem: Two-dimensional list of sets
:param tuple location: Location with the number to be removed
:param list<tuple> listOfLoc... | 0172fd3c98e31e1ff1c4db37b41feb322c49491e | 606,330 |
def prompt(prompt,valid):
"""
Returns the choice from a given prompt.
This function asks the user a question, and waits for a response. It checks
if the response is valid against a list of acceptable answers. If it is not
valid, it asks the question again. Otherwise, it returns the player's answe... | a83388fd2f8a4b047a08e643299c32619252cb65 | 606,331 |
def __get_auto_sample(ndim, gradient):
""" Decode which sampling method to use
Arguments:
ndim: int (dimensionality)
gradient: (None or function/true)
Returns: sampler string
"""
if ndim < 10:
sample = 'unif'
elif 10 <= ndim <= 20:
sample = 'rwalk'
else:
if g... | 84085b00e4dad0291e015657d756fc10904e62a8 | 606,332 |
import networkx
from typing import Counter
def make_debruijn_graph(kmers):
"""Constructs a de Bruijn graph from a list of kmers.
Parameters
----------
kmers: list of str
Returns
-------
dbg: networkx.DiGraph
In this graph, multi-edges are collapsed into a single edge.... | db7d88457a04afac541091efc95fdd105ecc043a | 606,336 |
import logging
def remediate_iam_policy(sa_iam_policy, sa_resource_name, risky_roles):
"""Remove risky IAM roles from the service account IAM policy.
Args:
sa_iam_policy ([dict]): The IAM policy attached to the sa_resource_name.
sa_resource_name ([str]): The GCP service account full resource ... | f5de29116a4f25dd49c2a8b48a64e44b9cdb9794 | 606,338 |
def _get_test_by_name(tests, name):
""" Returns the test with the specified name, or None if none match. """
for test in tests:
if test.name == name:
return test
return None | 695e1703a8c21bfc15ac12e8b97e660cbdd3cf56 | 606,342 |
def _unpad(
s: str,
) -> str:
"""Unpads a string that was previously padded by _pad().
:param s: The string to unpad
:type s: bytes
:returns: The unpadded string
:rtype: str
"""
last_character = s[len(s) - 1:]
bytes_to_remove = ord(last_character)
return s[:-bytes_to_remove] | 900646bde6c6bbd8f021bf8108bf8eb1083454d6 | 606,347 |
def getStats(cm):
"""Return the usual stats for a confusion matrix."""
measures = {}
measures['recall'] = cm['TP'] / (cm['TP'] + cm['FN'])
measures['specificity'] = cm['TN'] / (cm['TN'] + cm['FP'])
measures['FPR'] = cm['FP'] / (cm['FP'] + cm['TN'])
measures['FNR'] = cm['FN'] / (cm['TP'] + cm['... | 74837b85f6e045384e7708fc2ba3efb9a18edeaa | 606,351 |
def get_frame_from_json(frame):
"""Get/sanitize raw frame from JSON of frame from `tshark -x -T json ...`
Args:
frame (dict): A dict of a single packet from tshark.
Returns:
(str): The ASCII hexdump value of a packet
"""
if not isinstance(frame, dict):
print('frame is type',... | 52696cdceb4bc8ace8b541eb4d4e2224745865d0 | 606,355 |
def get_key_from_val(dict_, val, unknown=None):
"""
dict_ = {'aa':123}
val = 123
get_key_from_val(dict_, val)
> 'aa'
"""
list_vals = list(dict_.values())
if val in list_vals:
return list(dict_.keys())[list_vals.index(val)]
else:
return unknown | b79b9d07d8dcbba571e90d1d1807001c6c1227e1 | 606,356 |
def sklearn_method(estimator):
"""
A helper to turn a scikit-learn estimator into a spaCy extension.
Just in case you *really* wanted to do it manually.
```python
import spacy
from spacy.tokens import Doc
from sklearn.pipeline import make_pipeline
from sklearn.feature_extraction.text ... | 67f98cc2095da255fa33d797e1bbc309504f5ed6 | 606,358 |
def decorate(message: str, symbol: str = '+', line_width: int = 79) -> str:
"""Вывести текст в обрамлении символов
:param message: оригинальное сообщение
:param symbol: каким символом написать строки
:param line_width: какую ширину заполнить символами
:return: оформленное текстовое сообщение в виде... | 2b533902b621b4063f7019315f07bb0a962566ea | 606,360 |
def convert(text):
"""Convert digits to alphanumeric text"""
if text.isdigit():
return int(text)
else:
return text | d10db96ca87896a5b670a1f0ca4c3e7122e9b90d | 606,363 |
def sort_by_to_damage_state_desc(damage_state):
"""Sort the damage states with the highest first."""
return damage_state.to_state * -1 | 7bdc8a0bac26dfc89a874583d8ed6f380740114e | 606,367 |
def set_policy(crm_service, project_id, policy):
"""Sets IAM policy for a project."""
policy['version'] = 3
return (
crm_service.projects()
.setIamPolicy(resource=project_id, body={"policy": policy})
.execute()
) | 926d46f225774ab4db2c691580c308ff7ac12534 | 606,369 |
def _flatten_cluster_node(obj):
"""Flatten the structure of the cluster node into a single dict
"""
data = {
'id': obj.id,
'name': obj.name,
'private_ip': obj.status.private_ip,
'public_ip': obj.status.floating_ip,
'status': obj.status.status,
'flavor': obj.sp... | 7409a75ab4651827de92895535c111318aaf098b | 606,370 |
def move(position, instruction):
"""
Take a position and offset it based on instuction, or raise an error on invalid instruction.
Keyword arguments:
position --- current position as a tuple (x,y)
Instruction --- single-character instruction to move in ["^", "v", ">", "<"]
"""
if instruction == "^":
... | 78e2b20b232d4df50f2dd2dfd9860b13486f7078 | 606,374 |
def list_to_json(source_list):
"""
Serialise all the items in source_list to json
"""
result = []
for item in source_list:
result.append(item.to_json())
return result | 85fab1d2aecac08ff53ba25123fcfc0deb14bcc0 | 606,377 |
import random
def split_sets(wav_list, split_ratio):
"""Randomly splits the wav list into training, validation, and test lists.
Note that a better approach is to make sure that all the classes have the
same proportion of samples (e.g, spk01 should have 80% of samples in
training, 10% validation, 10% t... | 09e8891651abe21c4923300fc4362ee9841fdbe1 | 606,383 |
def to_flags(
supply_mutable: bool,
transferable: bool,
levy_mutable: bool
) -> int:
"""Convert 3 binary values to sequential bit flags"""
flags: int = 0
if supply_mutable:
flags |= 1
if transferable:
flags |= 2
if levy_mutable:
flags |= 4
return flags | 4d330a6601440e60c80473b3636afb552149a86f | 606,385 |
import re
def add_example_ino_library_include(input_text):
"""Makes sure the example includes the header that loads the library."""
return re.sub(r'#include ', '#include <TensorFlowLite.h>\n\n#include ',
input_text, 1) | 53699bfe4e2580a16bb7fd19929a153e486ac5cd | 606,386 |
def is_relative(s):
"""Indicate if a given 'from s' import location is a relative import."""
return s.startswith(".") | ca3b4fd79ee2b0ecc18de5b82113815e9ac2ead0 | 606,387 |
def area(square):
"""Get area of a rectangle"""
return square.get('width') * square.get('height') | e6b6d944fe237096d138ef571d2bc43be9c20e7e | 606,389 |
def inet_ntoa(addr):
"""
Do the reverse of inet_aton, return the quad notation of 'addr'
which is a long containing the network address
"""
quad = [0,0,0,0]
for i in (0,1,2,3):
quad[i] = (addr >> (8*(3-i))) & 0xFF
return "%u.%u.%u.%u" % tuple(quad) | 844cad7bcd29821a681586f611605d0f68cf3685 | 606,391 |
def series_sort(elem):
"""
This is a helper function that will be used in key argument of sorted()
in order to sort the list of series by series number
"""
# return int(elem.split("_")[-1]) # USE THIS IF %SeriesDescription_%SeriesNumber
return int(elem.split("_")[0]) | 5ae0a80c5877a3dda8697181ad1292872d5aba57 | 606,392 |
import math
def underlined(text, chars='=-'):
"""Underlines a text with extra chars
:param text: The text to underline
:param chars: The chars used for underlining. They will be
repeated as often as necessary to fit the length of
the text.
:return: a list containi... | cb9b6fb71869025871b21d5143aa0a6a8ab8a5fb | 606,396 |
import torch
def stack(tensors, *args, **kwargs):
"""
Concatenates a sequence of tensors along a new dimension.
Examples::
>>> import torch
>>> import treetensor.torch as ttorch
>>> t1 = torch.randint(10, 30, (2, 3))
>>> t1
tensor([[17, 15, 27],
[1... | 315641608a901d8110edddcb3eb52445bc962297 | 606,397 |
import json
def get_fluid_path(in_scene):
"""Extract the path to the fluid model that is used in a SPlisHSPlasH scene file.
Args:
in_scene: Path to a SPlisHSPlasH scene file
Returns:
The path to the fluid model file.
"""
with open(in_scene,"r") as f:
scene = json.load(f)
... | ce566975d158a6ad0e81eb87bc700464909a1086 | 606,400 |
import bisect
def takeAdjacent(myList, myNumber, left):
"""
Assumes myList is sorted.
Returns closest value to myNumber on the left or right.
"""
if left:
pos = bisect.bisect_left(myList, myNumber)
else:
pos = bisect.bisect_right(myList, myNumber)
if pos == 0: # first item ... | 976cea61c3a10e7fc4464b5c362a80d10e328a94 | 606,401 |
def make_gram(summary: str, n: int) -> set:
"""
Extracts the ngrams of a text
Args:
summary: A `str` corresponding to a summary we want the ngrams from.
n: An `int` giving the length of the ngrams.
Returns:
A `set` of `str` corresponding to the ngrams of the summary.
"""
... | 1dba952d43ceb9f2b09100eba219b2f14383d608 | 606,402 |
import math
def week_of_month(dt):
""" Returns the week of the month for the specified date.
"""
first_day = dt.replace(day=1)
dom = dt.day
adjusted_dom = dom + first_day.weekday()
return int(math.ceil(adjusted_dom / 7.0)) | 416120eace7dbf2b8790d07781d99824bee4998d | 606,408 |
def is_xpath_selector(selector):
"""
A basic method to determine if a selector is an xpath selector.
"""
if (
selector.startswith("/")
or selector.startswith("./")
or selector.startswith("(")
):
return True
return False | d668aca75f11a45d7a845b3c5aec93ff4380bf2e | 606,409 |
def _read_file(path):
"""Reads a file into a string.
Args:
path: The path to a file.
Returns:
The contents of the file.
"""
with open(path) as f:
return f.read() | 36d14a6491878e09742c658846c1e8d7b2876007 | 606,410 |
def d2_coords(i, j, width=1):
"""
given the (i,j) get the coords of the neighbouring cells within `width`
"""
d2 = [(x, y) for x in range(i - width, i + width + 1) for y in range(j - width, j + width + 1)]
return d2 | 5552df8f72504df65d516f4d6151d847945e04b0 | 606,416 |
def retry_argument_spec(spec=None):
"""Creates an argument spec for working with retrying"""
arg_spec = (dict(
retries=dict(type='int'),
retry_pause=dict(type='float', default=1),
))
if spec:
arg_spec.update(spec)
return arg_spec | cfc3c0e08679f5bf618852bd1dd7043b15ce34a7 | 606,419 |
def r2h(rgb):
"""
Convert an RGB-tuple to a hex string.
"""
return '#%02x%02x%02x' % tuple(rgb) | b9a6c0d5fda41d2824d9f99b22851def4ba0903a | 606,424 |
import re
def truncate_fastq_to_pair_suffix(fn: str) -> str:
"""
Turn a XXXBLAFOO_R1.fastq.gz filename into XXXBLAFOO_R1.
"""
extensions = [
r"_001\.fastq\.gz$", # Default Illumina
r"\.fastq\.gz$", # ENA/SRA
r"\.fasta\.gz$", # occasionally we get FASTA format reads
r... | 8d6df2b90b56ce45bee78e3d237824719dc724f4 | 606,426 |
def CommaSeparatedList(value_list, is_quoted=False):
"""Concatenates a list of strings.
This turns ['a', 'b', 'c'] into a single string 'a, b and c'. It optionally
adds quotes (`a') around each element. Used for logging.
"""
if is_quoted:
value_list = ["`" + value + "'" for value in value_list]
if le... | f0056c8279bfc89ac3025eeba2c60185f00ead8f | 606,430 |
def lowercase_first_string_letter(v:str):
"""Transform a string to lowercase first letter.
Args:
v (str): String value to convert
Returns:
str: Lowercase first letter of v
"""
return v[0].lower() + v[1:] | d236503de5786dd12c9289c776f436408716b08e | 606,436 |
import re
def is_valid_password(password):
"""
Return if a password is valid or not.
A valid password should have its length greater than 8, contain at least one
digit, one uppercase letter, one lowercase letter and one special character.
"""
try:
is_valid = True
is_valid &= ... | fccb67a407661b487d588e3ddb12b9ac72c6a59e | 606,437 |
def introduce(person) -> str:
"""
Introduces a dictionary representation of a person
"""
return f'Hello my name is {person["name"]} and I am {person["age"]} years old.' | 3fff6fec4b72fdd4e57799245e2b5d314078376d | 606,439 |
def safe_int(num):
"""Transform a string into int type with safety."""
# this function is mainly designed for elasticsearch
# since there are lots of bad int types
num = num.strip()
if '.' in num:
# when the num is something like: `88.`
return int(float(num))
return int(num) | 824104b885444ecdb93efa3bdf24d6d64f55ed96 | 606,443 |
def build(cfg, registry, key='name'):
"""Build a module from config dict.
Args:
cfg (dict): Config dict. It should at least contain the key.
registry (XXX): The registry to search the type from.
key (str): the key.
Returns:
obj: The constructed object.
"""
assert isi... | 56c77163d34b8747cfeeab80992f18b8c5f68f20 | 606,444 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.