content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def convert_to_bool(x) -> bool:
"""Convert string 'true' to bool."""
return x == "true" | bd207408f71559d7ee6f6df0adf4435a661eacdc | 684,985 |
from typing import OrderedDict
def json_decoder(ob):
""" method to decode an object into it's real python representation """
if isinstance(ob, dict):
t = ob.get("__type__", None)
if t is not None:
if t == "__tuple__":
return tuple([json_decoder(v) for v in ob["__ite... | 2f8539268bdd4fb01f9ec83bf6c9a880b569e837 | 684,986 |
def _stretch_string(string, length):
"""Stretch the game title so that each game takes equal space.
:param string: the string to stretch
:type string: str
:param length: the length that the string needs to be stretched to
:type length: int
:return: the stretched string
:rtype: ... | 91cf22f4fbe5dbf251b11da86b08cbc9ae12ff56 | 684,987 |
import json
def load_json_file(jfile):
"""
Load json file given filename
"""
with open(jfile) as handle:
j = json.load(handle)
return j | b86153750eea0dbd9013fe718087dca6a5ce8426 | 684,988 |
from typing import List
import subprocess
def get_output_of_command(command: List[str], description: str) -> str:
"""
subprocess.check_output wrapper that returns string output and raises detailed
exceptions on error.
Parameters
----------
command: list of strings creating a full command
... | f50081e6f19ec913f4e52e444b1a565f3fa36c79 | 684,989 |
def isentropic_compressibility(tab, spec, *XYf):
"""Isentropic compressibility"""
return 1./(tab.q['beta_s', spec](*XYf)) | 3829ef9df6d44925d1ba4c7d19e40ce062ca7ba2 | 684,991 |
def is_vowel(char: str) -> bool:
"""
returns True if the character is vowel else False
>>> is_vowel('A')
True
>>> is_vowel('e')
True
>>> is_vowel('f')
False
"""
vowels = ["A", "E", "I", "O", "U", "a", "e", "i", "o", "u"]
# Check for empty string
if not char:
retur... | 44d5fa1f5030496daf8dccafaffff03cb8e1d21c | 684,992 |
def bisect_map(mn, mx, function, target):
"""
Uses binary search to find the target solution to a function, searching in
a given ordered sequence of integer values.
Parameters
----------
seq : list or array, monotonically increasing integers
function : a function that takes a single integer... | 549a8be718f9cb8fbcb750fd4e8d59d5ddefdee3 | 684,993 |
import time
def some_func(one, two):
"""This takes time to compute"""
time.sleep(25)
return one + two | 24b59f292362e61da7eb845b5f39283485023185 | 684,994 |
def b(s):
"""
bytes/str/int/float -> bytes
"""
if isinstance(s, bytes):
return s
elif isinstance(s, (str,int,float)):
return str(s).encode("utf-8")
else:
raise TypeError(s) | ea017005461b1c559ab7b1efe82315a7f7cb8f71 | 684,995 |
def checkNotNull(params):
"""
Check if arguments are non Null
Arguments:
params {array}
"""
for value in params:
if value == None:
return False
return True | 02a91ac330b2529fa66968094ede11e0be9c8f53 | 684,996 |
import os
def _add_executable_extension_windows(file_name):
"""
Adds the Windows .exe file extension for an executable if it isn't there already.
:param file_name: The name of an executable.
:return: The name of an executable with the .exe extension.
"""
root, extension = os.path.splitext(fi... | 400fb2d29280f2dc0c2a626ba3fb398127d789ee | 684,997 |
def p2q(plist, do_min=1, verb=1):
"""convert list of p-value to a list of q-value, where
q_i = minimum (for m >= i) of N * p_m / m
if do min is not set, simply compute q-i = N*p_i/i
return q-values in increasing significance
(i.e. as p goes large to small, or gets more signific... | 2b54f520adfa57452fbe232bd1707d88eaf52e7c | 684,998 |
import os
def restore_path(table):
"""Restore resource's path and name from storage's table.
Parameters
----------
table: str
Returns
-------
(path: str, name: str)
"""
name = None
splited = table.split('___')
path = splited[0]
if len(splited) == 2:
name = sp... | af5841581204a49ca67345b4e7109e11d90520f4 | 685,000 |
from pathlib import Path
def get_packages(package):
"""
Return root package and all sub-packages.
"""
return [str(path.parent) for path in Path(package).glob("**/__init__.py")] | 6c568fc47122be49ed1a47325465deaf95056bff | 685,001 |
def iterate(E, func0, func1, func2, func3):
""""Produce the next value of E.
Parameters
----------
E : eccentric anomaly
func0 : function to zero
funcN : N-th derivative of function
"""
f0 = func0(E)
f1 = func1(E)
f2 = func2(E)
f3 = func3(E)
d1 = -f0 / f1
d2 = -f... | 1286c03ad59dbd7aeb10ce9888b8e073c34895bb | 685,002 |
import math
def rotateAboutZAxis(x, theta):
"""
Rotates matrix about z-axis.
: param x: matrix to be rotated.
: param theta: angle of rotation.
:return rotated matrix
"""
cosTheta = math.cos(theta)
sinTheta = math.sin(theta)
xRot = [x[0]*cosTheta - x[1]*sinTheta,
x[0]*... | be6955d75245da17b2ad627aff2bc159d24ef5b4 | 685,003 |
import base64
def to_base64(full_path):
"""
Return the base64 content of the file path
:param file_path: Path to the file to read
:type file_path: str
:return: File content encoded in base64
:rtype: str
"""
with open(full_path, "rb") as bin_file:
return base64.b64encode(bin_f... | 2d56464c8a886a4ad9240570fceeb9724762cc64 | 685,004 |
import time
def get_timestamp(length=13):
""" get current timestamp string
>>> len(str(int(get_timestamp(10))))
10
:param length: length of timestamp, can only between 0 and 16
:return:
"""
if isinstance(length, int) and 0 < length < 17:
return int("{:.6f}".format(time.time()).re... | d9658e8fd93cceef5345fdaa1a7a6dffbd40d454 | 685,006 |
def clear_faulty_data(files):
"""
Removes the None rows from the generated stroke statistics.
:param files: An n by 5 array containing stroke statistics,
with possibility of several Nan rows.
:return: The same array, without the Nan rows.
"""
corrected_files = []
for file in files:
... | 062cde808d78e515e98859ecc7f88be0c87e8148 | 685,007 |
import subprocess
def getDimensions(filePath) :
"""Returns dimensions of image in a tuple."""
x,y = subprocess.check_output(['identify', '-format', '%[w]x%[h]', filePath], timeout=3).decode('utf8').strip().split('x')
return int(x), int(y) | 53576f1560f1b3733ea8206c7a6ee0ce5966bc0f | 685,008 |
def find_sum(root, desired_sum, level=0, buffer_list=None, result=[]):
"""
You are given a binary tree in which each node contains a value
Design an algorithm to print all paths which sum up to that value
Note that it can be any path in the tree - it does not have to start at the root
"""
if not... | 2ca82d2dc5ac5684da564be8b6cc1ed89c18ba05 | 685,009 |
def get_gqx_cyvcf(record, sample_idx):
"""
Get GQX value from a cyvcf2 record
:param record: the record
:param sample_idx: sample index
:return: float
"""
try:
gq_arr = record.format("GQ")
except KeyError:
if record.QUAL is not None:
return record.QUAL
... | 6cafcc839609ebc9dd90fc8d920b0d45e468279c | 685,010 |
def construct_user_data(user=None):
"""Return dict with user data
The returned keys are the bare minimum: username, first_name, last_name
and email. No permissions or is_superuser flags!
"""
user_data = {}
for key in ["username", "first_name", "last_name", "email"]:
user_data[key] = ge... | 62c409750c596aa07ee3fbd3003d2e7646deb84b | 685,011 |
from unittest.mock import Mock
def set_default_error_handling(handler_fn):
"""Set a function to be called when an uncaught exception occurs. If set to None, a pop-up will appear letting the user know that an error has occurred."""
return Mock() | 6f95fcd46295a18435128ccafa34ce6b11a49490 | 685,013 |
def get_multiple_cases(root):
""" Counts number of entries with multiple genes """
entries = []
for child in root:
if (child.attrib["type"] == "gene"):
child_name = child.attrib["name"]
if (child_name.startswith("hsa:")):
split = child_name.split()
if(len(split) > 1):
entries.append(child)
retu... | e668f9998f88335a0c4ac328256960aaca28871c | 685,014 |
def rmSelf(f):
"""f -> function.
Decorator, removes first argument from f parameters.
"""
def new_f(*args, **kwargs):
newArgs = args[1:]
result = f(*newArgs, **kwargs)
return result
return new_f | d4339536eb43ac1b37a0860b0565d57997629ddd | 685,015 |
def get_books_by_author(args, books):
"""
Get books whose author name contains the arguments
:param args: args object containing all arguments
:param books: A list of book objects read from csv file
:return: A dictionary with matched authors' names as key and a list of their
book object... | 462004ebf3bd5979a43c126f7871364e715b18f1 | 685,016 |
def parse_clusters(cluster_file):
"""
expects one line per cluster, tab separated:
cluster_1_rep member_1_1 member 1_2 ...
cluster_2_rep member_2_1 member_2_2 ...
"""
cluster_dict = {}
with open(cluster_file) as LINES:
for line in LINES:
genes = line.strip()... | 88243b7a142224e755eb2046c11a90b352d5835d | 685,017 |
import subprocess
def get_usage(namespace):
"""Return usage for a namespace, uses heapster"""
return subprocess.run(['kubectl', 'top', 'pod', '--namespace=%s' % namespace],
stdout=subprocess.PIPE).stdout.decode('utf-8') | 93dd745241211b6d6900162bbabd4de80b74b88b | 685,018 |
def _new_array(ctype, size):
"""Create an ctypes.Array object given the ctype and the size of array."""
return (size * ctype)() | 4cd327f800cd2f296ce7881b4d6545edd5fffc27 | 685,019 |
import json
def to_json(**kwargs):
"""Convert input arguments to a formatted JSON string
as expected by the EE API.
"""
return {'jsonRequest': json.dumps(kwargs)} | 28142eacc3617d1f9d793e0d6b813855b7284c2d | 685,021 |
def perc_dir_from_data(data):
"""
Returns the percentage of prevalence for each sector given raw wind data.
Arguments
---------
data: list of float
The raw wind directions for every 10 min. Float with precision of 1.
Returns
-------
wind_dir_percent: dict
Dictionary of ... | 3a51f96daa69207e7d03f711a44ff18625bc2463 | 685,022 |
def _masked_loss(loss, mask, eps=1e-8):
"""
Average the loss only for the visible area (1: visible, 0: occluded)
"""
return (loss * mask).sum() / (mask.sum() + eps) | 98159a19e560f62c702ad2f5ab6c632c68d94c84 | 685,023 |
import os
def fetch_local_files(local_file_dir):
"""Create list of file paths."""
local_files = os.walk(local_file_dir)
for root, dirs, files in local_files:
return [f'{root}/{file}' for file in files] | 6fe386358af8cdfc33730186ddbd664aeb508dc1 | 685,024 |
def _roundn(num, n):
"""Round to the nearest multiple of n greater than or equal to the
given number. EMF records are required to be aligned to n byte
boundaries."""
return ((num + n - 1) // n) * n | 908617c1422e9c7b47cfe473a048bf31c8fed024 | 685,025 |
import os
import pickle
def load_configuration():
"""load the address of github repository and the path of local repository"""
config_file = './config/config.pkl'
if not os.path.exists(config_file):
return ' '*100, ' '*100
with open(config_file, 'rb') as rf:
config = pickle.load(rf)
... | 1767dbc744b6539511ab2ddc1e5d71dc2de4a933 | 685,026 |
import re
def _split_by_punctuation(chunks, puncs):
"""Splits text by various punctionations
e.g. hello, world => [hello, world]
Arguments:
chunks (list or str): text (str) to split
puncs (list): list of punctuations used to split text
Returns:
list: list with split text
... | ee05fab4ea30ab20da65c68bd2d68cd0d2a5ae85 | 685,027 |
def filename_from_path(full_path):
"""
given file path, returns file name (with .xxx ending)
"""
for i in range(len(full_path)):
j = len(full_path) - 1 - i
if full_path[j] == "/" or full_path[j] == "\\":
return full_path[(j + 1):] | ee06d5fbb9b8cd6631295d9920e2c131e336d710 | 685,028 |
def url_from_resource(namespace: str, path: str) -> str:
"""Convert resource path to REST URL for Kubernetes API server.
Args:
namespace: The K8s namespace of the resource
path: The part of the resource path that starts with the resource type.
Supported resource types are "pods" and... | a6f0fac530845a7c6ff24aeb289e2ed779e9b999 | 685,029 |
import os
def munge_name(file_name, status, output_dir):
"""Return the file name to use for processed results.
file_name is the name as it appears in the Doxygen logs. This will be
an absolute path. We strip off the path to the Chaste root (i.e. make
the name relative) and convert os.path.sep to '-... | 5d0577e55d7e6b46e1a1513f9090d5a3af3efc80 | 685,030 |
def type_or_none(default_type):
"""
Convert the string 'None' to the value `None`.
>>> f = type_or_none(int)
>>> f(None) is None
True
>>> f('None') is None
True
>>> f(123)
123
"""
def f(value):
if value is None or value == 'None':
return None
retu... | 151a972c040581d94ac56f944d18a9a262343c89 | 685,031 |
import random
import string
def random_string() -> str:
""" Generate a random string """
k = random.randint(5, 10)
return ''.join(random.choices(string.ascii_letters + string.digits, k=k)) | a0323d92764096f22033b11d842ae95c59ca07a5 | 685,032 |
import os
def _GetLargePdbShimCcPath():
"""Returns the path of the large_pdb_shim.cc file."""
this_dir = os.path.dirname(__file__)
lib_dir = os.path.join(this_dir, '..')
large_pdb_shim_cc_rel = os.path.join(lib_dir, 'buildtime_helpers', 'large-pdb-shim.cc')
large_pdb_shim_cc = os.path.abspath(large_pdb_shim... | d0c5be941e00525630a55a311b45740d238437f2 | 685,034 |
def _normalize_axis(axis: int, ndim: int) -> int:
"""Validates and returns positive `axis` value."""
if not -ndim <= axis < ndim:
raise ValueError(f'invalid axis {axis} for ndim {ndim}')
if axis < 0:
axis += ndim
return axis | 8aaa75ee921e398ea5dba683034dcb0d228085d6 | 685,035 |
def quicksort(arr):
"""
this is not an inplace implementation
"""
if len(arr) <= 1:
return arr
else:
pivot=arr[-1]
lesser, equal, greater = [], [], []
for iter in arr:
if iter < pivot:
lesser.append(iter)
elif iter == pivot:
... | 5d7370d27cd6c17ad4f729c15a2179af83b26cf1 | 685,036 |
def _get_config(path, value):
"""
Create config where specified key path leads to value
:type path: collections.Sequence[six.text_type]
:type value: object
:rtype: collections.Mapping
"""
config = {}
for step in reversed(path):
config = {step: config or value}
return config | e157fd27bc9e30a5ed4b5ed2d6063a1cfcd70445 | 685,037 |
from typing import Counter
import logging
def build_dict(sentences,win=None, max_words=50000):
"""
Build a dictionary for the words in `sentences`.
Only the max_words ones are kept and the remaining will be mapped to <UNK>.
"""
word_count = Counter()
for sent in sentences:
for ... | 020c42f387445c67e03d8a6115a1fb0214fe9467 | 685,038 |
def get_dev_raw_data_source(pipeline_builder, raw_data, data_format='JSON', stop_after_first_batch=False):
""" Adds a 'Dev Raw Data Source' stage to pipeline_builder and sets raw_data, data_format and
stop_after_first_batch properties of that stage. Returns the added stage"""
dev_raw_data_source = pipeline... | 4ce08a20bb1b40b666ffdee519c04b358b1f4632 | 685,039 |
import colorsys
import random
def random_colors(N, bright=False):
"""
Generate random colors.
To get visually distinct colors, generate them in HSV space then
convert to RGB.
"""
brightness = 1.0 if bright else 0.7
hsv = [(i / N, 1, brightness) for i in range(N)]
colors = list(map(... | 3be6bdea2f2b3b3aab8a934aea369250eaaab1ae | 685,040 |
import random
def generate_trips(num_trips, num_users):
"""Generates a list of trips to be inserted into the database.
Keyword arguments:
num_users -- number of users being created by the script
num_trips -- number of trips being created by the script
Returns:
trips -- a list of stri... | 5520c6d6bf36720fb5dfa85171229a71773fb9b0 | 685,042 |
def WriteToFile(path, string):
"""\
Write content to file
"""
f = open(path, 'wb')
f.write(string.encode())
f.close()
return True | ee4755c42901ccbf1b6e5c7e5ac1f1e3ace561fd | 685,043 |
def clean(s):
"""
Attempt to render the (possibly extracted) string as legible as possible.
"""
result = s.strip().replace("\n", " ")
result = result.replace("\u00a0", " ") # no-break space
result = result.replace("\u000c", " ") # vertical tab
while " " in result:
result = result.... | e831dc186517ed9e2a46a03b675a71ff73c0686f | 685,044 |
def compute_Obj(Y, A, K): # main objective
""" sum_{j=2}^K of (Y_{:,j})^TA(Y_{:,j}) / ((Y_{:,j})^T(Y_{:,j})) """
num, de = 0, 0
for i in range(K-1):
num += (Y[:,i+1].T).dot(A.dot(Y[:,i+1]))
de += Y[:,i+1].T@Y[:,i+1]
return (num / de) | 087c10c6a4585d8f58e48c3f21dc75afe1ebda2a | 685,045 |
def indexOfLargestInt(listOfInts):
"""
return index of largest element of non-empty list of ints, or False otherwise
That is, return False if parameter is an empty list, or not a list
parameter is not a list consisting only of ints
By "largest", we mean a value that is no smaller than any other
... | d3beea294099cfb13cfcf814612db0d4fc06b3f0 | 685,046 |
from typing import Optional
from pathlib import Path
def relative_example_path(example_id: str, data_name: Optional[str] = None):
"""
Returns the relative path from a train or test directory to the data file for the
given example_id and data_name.
"""
prefix = data_name + "_" if data_name else ""
... | 7a9d1c70d459496bca1994ee5360ceef09741d20 | 685,047 |
def rshift(val, n):
"""
Python equivalent to TypeScripts >>> operator.
@see https://stackoverflow.com/questions/5832982/how-to-get-the-logical-right-binary-shift-in-python
"""
return (val % 0x100000000) >> n | 5bdaf75adc159843836acd8850ca9f40a023b386 | 685,048 |
def is_sale(this_line):
"""Determine whether a given line describes a sale of cattle."""
is_not_succinct = len(this_line.split()) > 3
has_price = '$' in this_line
return has_price and is_not_succinct | ee8e88fb6f79b11579534f815d54a6c401859f00 | 685,049 |
import torch
def _create_lin_filter(sample_rate, n_fft, n_filter, f_min=0.0, f_max=None, dtype=torch.float32):
"""Create linear filter bank.
Based on librosa implementation (https://gist.github.com/RicherMans/dc1b50dd8043cee5872e0b7584f6202f).
"""
if f_max is None:
f_max = float(sample_rate) ... | 9638c3a17735e84f5473203db63a0d32139fc58d | 685,050 |
import itertools
def sparse_dict_from_array(array, magnitude_threshold=0):
"""Converts a array to a dict of nonzero-entries keyed by index-tuple."""
ret = {}
for index_tuple in itertools.product(*(map(range, array.shape))):
v = array[index_tuple]
if abs(v) > magnitude_threshold:
ret[index_tuple] =... | 26774934744c927f1625caedffbeb17203af68ea | 685,051 |
def is_corrupt(val: str) -> str:
""" Return unexpected character if corrupt, else empty string """
expected = {')': '(', '}': '{', ']': '[', '>': '<'}
opened = []
for char in list(val):
if char in '({[<':
opened.append(char)
elif char in ')}]>':
if opened and ope... | 000dcb0cab9635b58d6614d2809f62acf8ffba19 | 685,052 |
def iterate_revert_string(s: list) -> list:
"""
revert list iterate method
"""
i = 0
j = len(s) - 1
while i < j:
s[i], s[j] = s[j], s[i]
i += 1
j -= 1
return s | bf676a5a3735e748ab824e5a3ff02bf56a448c2e | 685,053 |
from typing import Literal
import unicodedata
def unicode(text: str, *, form: Literal["NFC", "NFD", "NFKC", "NFKD"] = "NFC") -> str:
"""
Normalize unicode characters in ``text`` into canonical forms.
Args:
text
form: Form of normalization applied to unicode characters.
For exa... | d854dc73c78bd37064557a496bd8704ffc9a7a34 | 685,055 |
import os
def decode_predictions(preds, top=5):
"""Decodes the prediction of an ImageNet model.
# Arguments
preds: Numpy tensor encoding a batch of predictions.
top: integer, how many top-guesses to return.
# Returns
A list of lists of top class prediction tuples
`(class_... | 59c3b1b536307998556769613962b5cebc89c831 | 685,056 |
def without_duplicates(args):
"""
Removes duplicated items from an iterable.
:param args: the iterable to remove duplicates from
:type args: iterable
:return: the same iterable without duplicated items
:rtype: iterable
:raise TypeError: if *args* is not iterable
"""
if hasattr(args,... | 02eed8fbe9138ffc4483170571562dfa29ae210e | 685,057 |
def set_default_vale(filed, configger, default_value, is_bool=False):
"""
the function is perform the params value setting, if the set_value is None or '' then will retrun default_value
:param configger: the configger object
:param filed: the filed name of param
:param default_value: the defaul... | 3325b08be95b73b9049cf50b36152d54a0cf6a58 | 685,058 |
import subprocess
def subprocess_wrapper(cmd_list, raise_error=True):
"""Wrapper to execute subprocess including byte to string conversion conversion."""
proc = subprocess.Popen(cmd_list, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
std_out, std_err = proc.communicate()
(std_out, std_err) = (std_ou... | 6fd1d86b4443f9a47181fec9f1595770c364be85 | 685,059 |
def create_vulnerability_dictionary(qid, title,
ip, name, category, severity,
solution, diagnosis, consequence):
"""
Creates a vulnerability dictionary.
:param qid: integer Qualys ID of the vulnerability.
:param title: string, title... | de5fb8a917d5aa22e1060bd987361062afbefa9c | 685,060 |
import argparse
def get_user_args():
""" Gets user supplied arguments.
Returns arg.parse dictionary
"""
parser = argparse.ArgumentParser(description='Arguments for getting worker node IPs from a cluster')
parser.add_argument('-t', '--tenancy', help="name of tenancy used in your ~/.oci/config", re... | a44bfc55dfb0591d3c1e9b80a4bb624c823d7d3a | 685,061 |
def __get_rxn_rate_dict(reaction_equations, net_rates):
"""
makes a dictionary out of the two inputs. If identical reactions are encountered,
called duplicates in Cantera, the method will merge them and sum the rate together
"""
rxn_dict = {}
for equation, rate in zip(reaction_equations, net_rat... | e1b5396d4a7895ff7e79d8bc19bc63165c66a1ee | 685,062 |
import os
def Get_name(archive):
"""strip path and extension to return the name of a file"""
return os.path.basename(archive).split('.')[0] | 10a099f9d6e9e8d22298c5a42c100b7d1c6b17c9 | 685,063 |
import os
def path_getrootdir(path):
"""
Extract rootdir from path in a platform independent way.
POSIX-PATH EXAMPLE:
rootdir = path_getrootdir("/foo/bar/one.feature")
assert rootdir == "/"
WINDOWS-PATH EXAMPLE:
rootdir = path_getrootdir("D:\\foo\\bar\\one.feature")
a... | 8d5a5a1885107592250f3996bd14ec8f0479871f | 685,064 |
def get_page_text(soup):
"""Return all paragraph text of a webpage in a single string.
"""
if soup is None:
return ''
paragraphs = [para.text for para in soup.select('p')]
text = '\n'.join(paragraphs)
return text | da9de4683fb6611d3bfc703fe491a2b7139252a3 | 685,065 |
import pickle
def read_pickle(file_name):
""" Reads a data dictionary from a pickled file.
Helper function for curve and surface ``load`` method.
:param file_name: name of the file to be loaded
:type file_name: str
:return: data dictionary
:rtype: dict
"""
# Try opening the file for ... | b1406ed56c2294a691d7958c63cd2fd35095fc3a | 685,066 |
import os
def is_safe_path(safe_root, check_path):
"""Detect Path Traversal."""
safe_root = os.path.realpath(os.path.normpath(safe_root))
check_path = os.path.realpath(os.path.normpath(check_path))
return os.path.commonprefix([check_path, safe_root]) == safe_root | 7def2f125c14acbb3863a4d7ccaf5391baa68b2f | 685,067 |
def get_appliance_dns(
self,
ne_id: str,
cached: bool,
) -> dict:
"""Get DNS server IP addresses and domain configurations from Edge
Connect appliance
.. list-table::
:header-rows: 1
* - Swagger Section
- Method
- Endpoint
* - dns
- GET
... | 4b401effd8e4e5b89be75128cdeacda9ed852975 | 685,068 |
def cli(ctx, toolShed_id):
"""Get details of a given Tool Shed repository as it is installed on this Galaxy instance.
Output:
Information about the tool
For example::
{'changeset_revision': 'b17455fb6222',
'ctx_rev': '8',
'owner': 'aaron',
'status'... | 1106743da59251a0b939a78e0413fd7b7a043f2b | 685,069 |
import numpy
def get_fixed_range(limits):
"""Return minimum and maxmium limits
"""
# this wont work if we have the larger value on the bottom
assert numpy.all([a[0] <= a[1] for a in limits]), 'Constraint error disordered list {}'.format(limits)
a = min((a[0] for a in limits))
b = max((a[1] for... | 100012e2631a2de99f9ea46a294232e3150b137b | 685,070 |
import subprocess
import logging
from subprocess import CalledProcessError
def check_output(command_args):
""" Wrapper for subprocess.checkoutput with logging of the error of the failed command """
try:
output = subprocess.check_output(command_args, stderr=subprocess.STDOUT)[:-1] # [:-1] removes the ... | 58bb81f92c8ec4db75f88530e5729cc2001d4e39 | 685,071 |
from pathlib import Path
def get_filesize(pathname: Path) -> int:
"""
Returns the size of a file in bytes.
Parameters
----------
pathname : Path
Returns
-------
int
"""
return pathname.stat().st_size | cec1f8b64efbf2bf58a4f1798b789ebb87251e40 | 685,072 |
import hashlib
def SimpleMerkleRoot(hashes, hash_function=hashlib.sha256):
"""
Return the "Simple" Merkle Root Hash as a byte blob from an iterable
ordered list of byte blobs containing the leaf node hashes.
Works by recursively hashing together pairs of consecutive hashes to
form a reduced set o... | d9e7bef38e332f674301b49a5d8f2af98bcd7c68 | 685,073 |
def round_robin_list(num, to_distribute):
"""Return a list of 'num' elements from 'to_distribute' that are evenly distributed
Args:
num: number of elements in requested list
to_distribute: list of element to be put in the requested list
>>> round_robin_list(5, ['first', 'second'])
['fi... | 69837d38dd131658280d5fee21524a090044990d | 685,074 |
import collections
def _stat_class(dataset_y, multi_label=False):
""" 统计标签集合的结果
"""
if not multi_label:
dataset_res = collections.Counter(dataset_y).most_common()
stat_result = dict()
for item in dataset_res:
stat_result.update({item[0]: [item[1], item[1] / len(dataset... | 733e3c242e16e5ae9f417ddeb1c1d44575d1c2e9 | 685,075 |
import re
def check_password_strength(password):
"""
Password should be 8 character long
Contain special character
Has an Integer
Has a capital letter
"""
length_regex = re.compile(r'.{8,}')
length = True if length_regex.search(password) is not None else False
uppercase_regex = re... | 8ba3ee7800c084fd20201a285e0bdd682a2989a8 | 685,076 |
def clone_with_translations(instance, forced_version_date=None):
"""
Clones the given instance and it's relations
Expects a TranslatableModel
"""
new_instance = instance.clone(forced_version_date)
for translation in new_instance.translations.all():
translation.pk = None
translat... | ec4c34442a6e8fc93cd21f7563887423b885b853 | 685,077 |
import math
def get_total_time(intervals):
"""
>>> get_total_time([])
0.0
>>> get_total_time([(1, 3)])
2.0
>>> get_total_time([(1, 3), (4, 5)])
3.0
"""
return math.fsum([(interval_end - interval_start) for (interval_start, interval_end) in intervals]) | 12647f98c1e496266163abd0ddbfe535c8146863 | 685,078 |
import tempfile
def new_temp_path(**kwargs):
"""A new temporary path."""
handle = tempfile.NamedTemporaryFile(**kwargs)
path = handle.name
handle.close()
return path | 4c9b6f4255b2bb43ac540c590b0fef87fde05866 | 685,079 |
def metadata(long_name: str, units: str, topic: str):
"""For fields(metadata=metadata(...))"""
return dict(long_name=long_name, units=units, topic=topic) | a3d0e950062d6038f18ce082964d6c9a2f080ca3 | 685,080 |
def inline(sconf):
"""
Return config in inline form, opposite of :meth:`config.expand`.
Parameters
----------
sconf : dict
Returns
-------
dict
configuration with optional inlined configs.
"""
if (
'shell_command' in sconf
and isinstance(sconf['shell_co... | 6498d6711248f38032bcbdf1e694858542984704 | 685,081 |
import hashlib
def md5sum(data):
"""
Return md5sum of data as a 32-character string.
>>> md5sum('random text')
'd9b9bec3f4cc5482e7c5ef43143e563a'
>>> md5sum(u'random text')
'd9b9bec3f4cc5482e7c5ef43143e563a'
>>> len(md5sum('random text'))
32
"""
return hashlib.md5(data).hexdig... | b99b07105596289fd29335bbb0e2f9dc91e4e253 | 685,082 |
import numpy
def trim(x, s):
"""
Remove additional layers.
"""
s = numpy.array(s) - 1
s /= 2
slices = [slice(s[i], -s[i]) for i in range(len(s))]
return x[slices] | 1d654fc14b8cd230c3bfc5622ceba47260153a62 | 685,083 |
def parse_team_stats(stat_obj: dict) -> str:
"""
Currently, individual team's stats look like this from Dynamo:
"Hotshots": {
"GA": "25",
"GF": "27",
"GP": "7",
"L": "3",
"OTL": "0",
"PTS": "8",
"SOL": "0",
"T": "0",
"W": "4"
}
we turn these into a nice human read... | 7ee324c0bcdda2903be2fd82679dae7c7d46ed75 | 685,084 |
from typing import List
def is_asset_blacklisted(name: str, blacklist: List[str]) -> bool:
"""
Check whether an asset must be filtered
:param name
:param blacklist
:returns bool
"""
return any(map(lambda x : name.endswith(x), blacklist)) | 4bd86742bd68d3a603caa64d5672b4f84d9c4d08 | 685,085 |
def get_body_length(htc_struc, body):
"""Get the length of a body from htc structure, given string name"""
body_contents = htc_struc.get_subsection_by_name(body).c2_def.contents
last_key = next(reversed(body_contents))
length = abs(body_contents[last_key].values[-2])
return length | b2f6df3659d359974f982c8a56f8a3c70ed584da | 685,087 |
def get_tcp_udp_port_data(self) -> dict:
"""Get list of TCP, UDP ports and their applications
.. list-table::
:header-rows: 1
* - Swagger Section
- Method
- Endpoint
* - spPortal
- GET
- /spPortal/tcpUdpPorts
:return: Returns dictionary of p... | 5120bc8189cc903ac00267841754603aeb1013ee | 685,088 |
import time
def find_newest_message(all_messages):
"""
Takes in a list of messages
and returns the most recent message object.
Message keys correspond to the gmail message payload keys,
with additional keys for 'id', 'datetime',
and 'msg' <-- the entire message object
(needed for retrievin... | 9dc5fe79de02caecf89022b95a8fe40889f8fa75 | 685,089 |
import math
def calculate(a, b, c):
"""
Solve quadratic equation and return the value of x
Parameters:
a (float): Value a, not equal to zero
b(float): Value b
c(float): Value c
Returns:
float:Returning value
"""
discriminant = b ** 2 - 4 * a * c
i... | 8137ef45e29a4878dbfde61c32b51bc7b76391b6 | 685,090 |
def _RemoteSteps(api, app_engine_sdk_path, platform):
"""Runs the build steps specified in catapult_build/build_steps.py.
Steps are specified in catapult repo in order to avoid multi-sided patches
when updating tests and adding/moving directories.
This step uses the generator_script; see documentation at
gi... | de6ee15783ca75582e57e55dea58c4a9c3706870 | 685,091 |
def ce(actual, predicted):
"""
Computes the classification error.
This function computes the classification error between two lists
:param actual : int, float, list of numbers, numpy array
The ground truth value
:param predicted : same type as actual
The pr... | 10be7d124c56e888c674112e768050c2f9bbd5f6 | 685,092 |
from datetime import datetime
def vota(anoN):
"""
=> Avalia condição de voto de uma pessoa
:param anoN: ano de nascimento da pessoa
:return: string com condiçõa do voto
"""
anoA = datetime.today().year
idade = anoA - anoN
cond = f'Com {idade} ano(s): '
if idade < 16:
cond +... | f37a88c33c771e63b2d141b5973a6a80d29dda52 | 685,094 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.