content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import cmath
def op_phase(x):
"""Returns the phase of a complex number."""
if isinstance(x, list):
return [op_phase(a) for a in x]
else:
return cmath.phase(x) | e1a3b37c91bd4726ce0f14c9b9eb0fd007a4e0d2 | 45,990 |
def compute_brightness(brightness):
"""Return the hex code for the specified brightness"""
value = hex(int(brightness))[2:]
value = value.zfill(4)
value = value[2:] + value[:2] # how to swap endianness
return "57" + value | dab3ec94d9b39342491130074966fc6b7a988aca | 45,991 |
def ln_like(theta, event, parameters_to_fit):
""" likelihood function """
KCT01 = 0
Spitzer = 9
for (key, val) in enumerate(parameters_to_fit):
# *** NEW ***
# Some fluxes are MCMC parameters
if val[0:] == 'f':
if val == 'fsKCT01':
event.datasets[KCT01].source_flux = theta[key]
elif val == 'fsSpitzer':
event.datasets[Spitzer].source_flux = theta[key]
else:
setattr(event.model.parameters, val, theta[key])
# *** END NEW ***
return -0.5 * event.get_chi2() | 83f2a0f161c150aa166bcf02a75be96bd3ce305e | 45,992 |
import ast
def prep_function_def_from_node_for_return(function_node: ast.FunctionDef) -> str:
"""
Returns a string representation of the function definition with an empty return type
"""
return "def " + function_node.name + "(" + ast.unparse(function_node.args) + ") ->" | 7b1bfe4e4597b76333a7a2262be0e74c735a8bb2 | 45,993 |
from typing import get_origin
from typing import Union
from typing import get_args
def is_optional_type(type_annotation) -> bool:
""" Determines if a type is Optional[XXX]
:param type_annotation: A type annotation, e.g Optional[float] or float
:return: Whether the type annotation is an optional
"""
if get_origin(type_annotation) is Union:
args = get_args(type_annotation)
return len(args) == 2 and type(None) in args # pylint:disable=unidiomatic-typecheck
return False | 2ef9fb8a536dbe489c2039a95ae1f8f185515d61 | 45,994 |
def splitList(initialList, chunkSize, only=None):
"""This function chunks a list into sub lists
that have a length equals to chunkSize.
Example:
lst = [3, 4, 9, 7, 1, 1, 2, 3]
print(chunkList(lst, 3))
returns
[[3, 4, 9], [7, 1, 1], [2, 3]]
taken from http://stackoverflow.com/questions/312443\
/how-do-you-split-a-list-into-evenly-sized-chunks-in-python
answer Feb 28'15 by Ranaivo
"""
if only:
filteredList = []
for c in initialList:
if c.find(only) >= 0:
filteredList = filteredList + [c]
else:
filteredList = initialList
finalList = []
for i in range(0, len(filteredList), chunkSize):
finalList.append(filteredList[i:i + chunkSize])
return finalList | d620405933749ab4eab54d6ff7d5202ef56aa2d1 | 45,995 |
def leiaint(msg):
"""
--> Função que faz a validação da entrada de dados do tipo inteiro (int)
:param msg: Mensagem para entrada de dados do usuário
:return: retorna o valor digitado, caso este tenha sido um número inteiro
:print: Escreve uma mensagem de erro na tela, caso o valor digitado não seja do tipo inteiro
"""
while True:
n = str(input(msg)).strip()
if n.replace('-', '').isnumeric():
return int(n)
else:
print(f'\033[0;31mErro! Digite um número inteiro válido.\033[m') | 29b96b26055d965e987bf1e39a96b1924751f56c | 45,996 |
def convert_format(ori_list: list) -> dict:
"""
设输入列表长度为n
时间复杂度 O(n) 遍历两次list,
1. 构建辅助字典, 实现通过子节点查找父节点时间复杂度为O(1); 初始化子节点
2. 不断将子节点追加到父节点
空间复杂度: 需要构建辅助节点dict, 和返回结果dict, 空间复杂度是 O(n)
"""
tree = {"root": {}}
revert_dict = dict()
for n in ori_list:
# 构造反向键值字典
revert_dict[n["name"]] = n.get("parent")
# 初始化子节点
tree[n["name"]] = {}
for ele in ori_list:
name = ele["name"]
parent = revert_dict.get(name) or "root"
# 子节点追加到父节点
tree[parent].update({name: tree.get(name)})
return tree["root"] | 02deadf4c1e6ceaabfabf93fd09d49e1e4e87ddd | 45,997 |
import inspect
def get_fn_parameters(fn):
""" return the number of input parameters of the fn , None on error"""
param_len = len(inspect.getfullargspec(fn).args)
if inspect.ismethod(fn):
param_len -= 1
return param_len | cf90737655367422a96929d1f935aea4db620a41 | 45,998 |
def box_it(X, L):
"""X is a vector of x and y coordinates of a hard disk"""
"""L is a vector of Lx and Ly, such that the box has size Lx X Ly"""
return [X[0]%L[0], X[1]%L[1]] | b377f7b75562490ca5048ca5ea8692c616a5327a | 46,000 |
import math
def correlation (cf):
"""Returns the correlation metric given a confusion matrix."""
p = cf[0][0]
n = cf[0][1]
P = p + cf[0][1]
N = n + cf[1][1]
return (p*N - P*n) / math.sqrt(P*N*(p+n)*(P-p+N-n)) | 1ab13a83c8451eb0e7a9f4e5621657d13f21e21f | 46,001 |
import os
def frame_id(fname):
"""
fname: x.jpg
returns: int(x)
"""
return int(os.path.basename(fname).split('.')[0]) | 66a9a5853da60fca54bc9abdb9b45e9c691e1c19 | 46,002 |
def non_colinearity(read_start_cigar,read_end_cigar,aln_start,mate_interval_start,mate_interval_end):
"""Input a read and the mate interval in the graph. The function checks whether the alignment would be linear (splicing)
or colinear. Will return false, in order to not attemp realignment. This is mainly thought for skipping deletions and
RNA splicing"""
#check left soft-clipped
if read_start_cigar == 4:
#graph needs to be upstream or looping to itself
if int(mate_interval_start) > aln_start:
return (True)
elif aln_start < int(mate_interval_end):
#looping to itself
return (True)
else:
return (False)
#check right softclipped
if read_end_cigar == 4:
# graph needs to be downstream or looping to itself
if int(mate_interval_end) < aln_start:
return (True)
elif aln_start > int(mate_interval_start):
#looping to itself
return (True)
else:
return (False) | 90a206867e0561b54a3c663395cf8ea6a1062997 | 46,005 |
def parse_accept(headers):
#-------------------------
"""
Parse an Accept header and return a dictionary with
mime-type as an item key and 'q' parameter as the value.
"""
return { k[0].strip(): float(k[1].strip()[2:])
if (len(k) > 1 and k[1].strip().startswith('q=')) else 1
for k in [ a.split(';', 1)
for a in headers.get('Accept', '*/*').split(',') ] } | 43e2698695f3484d47284cb8e0d1e278b33b322d | 46,006 |
import six
import os
def fill_remote(cur, find_fn, is_remote_fn):
"""Add references in data dictionary to remote files if present and not local.
"""
if isinstance(cur, (list, tuple)):
return [fill_remote(x, find_fn, is_remote_fn) for x in cur]
elif isinstance(cur, dict):
out = {}
for k, v in cur.items():
out[k] = fill_remote(v, find_fn, is_remote_fn)
return out
elif (isinstance(cur, six.string_types) and os.path.splitext(cur)[-1] and not os.path.exists(cur)
and not is_remote_fn(cur)):
remote_cur = find_fn(cur)
if remote_cur:
return remote_cur
else:
return cur
else:
return cur | 50fe45d32cd1974b3fe3e9a3850cd92cd088d19a | 46,007 |
def get_x_y_set(mt, type="test"):
"""Gets data set from ModelTuning object
Parameters
----------
mt : ModelTuning object
ModelTuning object used
type : str, default="test"
specifies which set to return ('train'/'test'/'val')
Returns
----------
X_data, y_data : ndarray
"""
if type == "val":
return mt.get_validation_set()
if type == "train":
return mt.get_train_set()
if type == "test":
return mt.get_test_set() | 6a423e93d85e4f18057550b6d3de3d3fe3c80766 | 46,008 |
def mbToBytes(byte_data: int) -> int:
"""Convert byte number data and this convert to mb"""
return byte_data * 1048576 | ff165f89c3c3067dd30532b5f0043a4e36fd141e | 46,009 |
from itertools import tee
def nwise(iterable, n=2):
"""
Adapted from more_itertools
s, 2 -> (s0,s1), (s1,s2), (s2, s3), ..."
s, 3 -> (s0,s1,2), (s1,s2,s3), (s2,s3,s4), ..."
"""
parts = tee(iterable, n)
to_zip = []
while(parts):
to_zip.append(parts[0])
parts = parts[1:]
for p in parts:
next(p, None)
return zip(*to_zip) | 1b73f4a565243b5aeeea4ac85ba5e6f0f83864ee | 46,010 |
import sys
def get_file_size(file):
"""
Returns a string with the file size and highest rating.
"""
byte_size = sys.getsizeof(file)
kb_size = byte_size / 1024
if kb_size == 0:
byte_size = "%s Bytes" % (byte_size)
return byte_size
mb_size = kb_size / 1024
if mb_size == 0:
kb_size = "%s KB" % (kb_size)
return kb_size
gb_size = mb_size / 1024 % (mb_size)
if gb_size == 0:
mb_size = "%s MB" %(mb_size)
return mb_size
return "%s GB" % (gb_size) | 9a90c4fa480423d82bc3790a4a8b3c8a39d5235e | 46,011 |
def read_mesh_off(path, scale=1.0):
"""
Reads a *.off mesh file
:param path: path to the *.off mesh file
:return: tuple of list of vertices and list of faces
"""
with open(path) as f:
assert (f.readline().split()[0] == 'OFF'), 'Not OFF file'
nv, nf, ne = [int(x) for x in f.readline().split()]
verts = [tuple(scale * float(v) for v in f.readline().split()) for _ in range(nv)]
faces = [tuple(map(int, f.readline().split()[1:])) for _ in range(nf)]
return verts, faces | e65a78cc457dd251c8e604b24096776b54cae33c | 46,012 |
def mean(li):
"""
Calculate mean of a list.
>>> mean([0.5,2.0,3.5])
2.0
>>> mean([])
"""
if li:
return sum(li) / len(li)
return None | 249d71615f0b671e6ad0e9be127d5eedacee0a64 | 46,014 |
import os
from pathlib import Path
def make_directory(directory_name):
"""Create a directory if it does not exist.
Returns: A string of the created path name.
"""
path_name = os.path.join(os.getcwd(), 'audio_data', directory_name)
Path(path_name).mkdir(parents=True, exist_ok=True)
return path_name | fa70c303f1ba420d2ef07a2e1386c271102cf4f4 | 46,015 |
import re
def fixup_generated_snippets(content):
"""
Adjust the expanded code snippets that were generated
by mdsnippets, to improve rendering by Sphinx
"""
# Remove lines like: <!-- snippet: verify_exception_message_example -->
content = re.sub(
r"<!-- snippet: .* -->\n",
r"", content)
# Remove lines like: <a id='snippet-verify_exception_message_example'/></a>
content = re.sub(
r"<a id='snippet-.*'/></a>\n",
r"", content)
# Remove 'snippet source' links from all code snippets
content = re.sub(
r"<sup><a href='([^']+)' title='Snippet source file'>snippet source</a> ",
r"(See [snippet source](\1))", content)
# Remove 'anchor' links from all code snippets
content = re.sub(
r"\| <a href='#snippet-[^']+' title='Start of snippet'>anchor</a></sup>",
'', content)
content = content.replace('<!-- endsnippet -->\n', '')
return content | 81c58f83058c1eb91d6846e026b9e2c7a757189b | 46,016 |
def vnfd_update(vnfd):
"""
Implement VNFD updater here
"""
vnfd['vnfd:vnfd-catalog']['vnfd'][0]['version'] = '2.5'
return vnfd | 925d1e4eb89e339dda8cc746eb26ba2158eefe30 | 46,017 |
def order_cols_by_nunique(df, cols):
"""
Reorder columns in cols according to number of unique values in the df.
This can be used to have a cleaner grouped (multi-level) x-axis where
the level with the least unique values is at the bottom.
Note: alternatively you could remove cols that have only 1 unique value
:param df: pandas DataFrame
:param cols: list of columns to reorder
:return:
"""
unique_count = df[cols].nunique().sort_values()
re_ordered_cols = list(unique_count.index.values)
return re_ordered_cols | ccc6b4208182add8f43ea7cfdeb5bad048ddf26e | 46,018 |
def southOf(x, y, xy0, xy1):
"""
Returns 1 for point south/east of the line that passes through xy0-xy1, 0 otherwise.
"""
x0 = xy0[0]; y0 = xy0[1]; x1 = xy1[0]; y1 = xy1[1]
dx = x1 - x0; dy = y1 - y0
Y = (x-x0)*dy - (y-y0)*dx
Y[Y>=0] = 1; Y[Y<=0] = 0
return Y | cd7d903b60eec70f580bccc6f8dcd9a05734f161 | 46,019 |
def get_info_for_country(data, country):
"""Получает информацию о пользователе из результатов запроса.
Parameters:
data (list): список словарей, содержащий все
записи, полученные из запроса
country (str): значение country, запрошенной страны
Returns:
country_count (int): количество игроков заданной страны.
"""
country_count = sum([1 if user['country'] == country else 0
for user in data])
return country_count | 60b5b68cda918a54b3f2edc310bb987fc4a6e1af | 46,020 |
def sanitize_document(document, fields=[]):
"""
Removes sensitive fields from a MongoDB document.
Args:
document: The MongoDB document to sanitize.
fields: An array of fields to check against. Each field is treated as a substring
of keys within the MongoDB document.
Returns:
A sanitized version of the document.
"""
# document['mongo_id'] = document.pop('_id')
for field in fields:
[document.pop(key, None) for key in document.keys() if field in key]
return document | a9040f12e1b5dea601c7f6266663097338ce33da | 46,021 |
import json
def to_json(wad_data):
"""
Output statistics as raw data.
"""
return json.dumps(wad_data, indent=2) | 1747208e30c2d23183f79b905a0583cd44b9d95e | 46,022 |
def scrubber_criteria(bit_counts):
"""Bit criteria for CO2 scrubber rating."""
return '0' if bit_counts['0'] <= bit_counts['1'] else '1' | 3851bf60b239110fb2676996d4af14243bbfac68 | 46,023 |
def ignore_topics_list():
"""
A list of headings or topics to be ignored by the plagiarism checker
"""
return [
'references',
'citations',
'references and citations',
'citations and references'
] | 77d65dc57c820fbab3c97399f38b20d2acd37e53 | 46,024 |
def get_action_value(mdp, state_values, state, action, gamma):
""" Computes Q(s,a) as in formula above """
return sum(
prob * (mdp.get_reward(state, action, state_dash) + gamma * state_values[state_dash])
for state_dash, prob in mdp.get_next_states(state, action).items()
) | 082fe8b979e6ceaca218db5de5084c9040fbe34c | 46,028 |
import argparse
def parse_args():
"""
parse input args
"""
parser = argparse.ArgumentParser()
parser.add_argument("--model_path", type=str, help="model .pb input path")
parser.add_argument(
"--output_path", type=str, help="tf saved model output path")
parser.add_argument(
"--input_node",
type=str,
default="input/input_data:0",
help="tf model input node")
parser.add_argument(
"--output_node",
type=str,
default="pred_sbbox/concat_1:0",
help="tf model output node")
return parser.parse_args() | 0b868b21021ccf461da803576aaaeddc7b753169 | 46,030 |
def ParseSubversionPropertyValues(props):
"""Parse the given property value which comes from [auto-props] section and
returns a list whose element is a (svn_prop_key, svn_prop_value) pair.
See the following doctest for example.
>>> ParseSubversionPropertyValues('svn:eol-style=LF')
[('svn:eol-style', 'LF')]
>>> ParseSubversionPropertyValues('svn:mime-type=image/jpeg')
[('svn:mime-type', 'image/jpeg')]
>>> ParseSubversionPropertyValues('svn:eol-style=LF;svn:executable')
[('svn:eol-style', 'LF'), ('svn:executable', '*')]
"""
key_value_pairs = []
for prop in props.split(";"):
key_value = prop.split("=")
assert len(key_value) <= 2
if len(key_value) == 1:
# If value is not given, use '*' as a Subversion's convention.
key_value_pairs.append((key_value[0], "*"))
else:
key_value_pairs.append((key_value[0], key_value[1]))
return key_value_pairs | 9874d2a308f66ec4dc4aa14292370977685c6e5e | 46,033 |
import math
def distance(coordinate_tuple):
"""Intake a coordinate tuple, return the distance between points"""
x1 = coordinate_tuple[0]
y1 = coordinate_tuple[1]
x2 = coordinate_tuple[2]
y2 = coordinate_tuple[3]
dist = math.sqrt((x2-x1)**2 + (y2-y1)**2)
return dist | f93e505aa267c0d4011f7e94e8a0996478c75058 | 46,035 |
def is_trunk_revision(rev):
"""Return True iff REV is a trunk revision.
REV is a CVS revision number (e.g., '1.6' or '1.6.4.5'). Return
True iff the revision is on trunk."""
return rev.count('.') == 1 | 96da375c93b166502bd3f30171dd127815f10a5f | 46,037 |
def find_duplicates(l: list) -> set:
"""
Return the duplicates in a list.
The function relies on
https://stackoverflow.com/questions/9835762/find-and-list-duplicates-in-a-list .
Parameters
----------
l : list
Name
Returns
-------
set
Duplicated values
>>> find_duplicates([1,2,3])
set()
>>> find_duplicates([1,2,1])
{1}
"""
return set([x for x in l if l.count(x) > 1]) | f5c3ce0949996865935182028b7782c13eb0998a | 46,038 |
def gw_get(object_dict, name=None, plugin=None):
"""
Getter function to retrieve objects from a given object dictionary.
Used mainly to provide get() inside patterns.
:param object_dict: objects, which must have 'name' and 'plugin' as attribute
:type object_dict: dictionary
:param name: name of the object
:type name: str
:param plugin: plugin name, which registers the object
:return: None, single object or dict of objects
"""
if plugin is not None:
if name is None:
object_list = {}
for key in object_dict.keys():
if object_dict[key].plugin == plugin:
object_list[key] = object_dict[key]
return object_list
else:
if name in object_dict.keys():
if object_dict[name].plugin == plugin:
return object_dict[name]
else:
return None
else:
return None
else:
if name is None:
return object_dict
else:
if name in object_dict.keys():
return object_dict[name]
else:
return None | ee441ec56e55bd962e35079e8e87cf281b6f6948 | 46,040 |
def shuf_key(shuf):
""" return an index to sort shuffles in this order. """
return ["none", "edge", "be04", "be08", "be16", "smsh", "dist", "agno", ].index(shuf) | d3379daddb499fa9a1132782d4d65ce817ded8b9 | 46,041 |
import html
def unescape(text):
"""Replace HTML entities and character references."""
return html.unescape(text) | 075821e15ee6a8bd9a924c5db20f0596de64ad1b | 46,042 |
def dump_flags(flag_bits, flags_dict):
"""Dump the bits in flag_bits using the flags_dict"""
flags = []
for name, mask in flags_dict:
if (flag_bits & mask) != 0:
flags.append(name)
if not flags:
flags = ["0"]
return "|".join(flags) | a8d28c023c3f33823cf2bcce47a9414e80164164 | 46,043 |
def save_dataframe(df):
"""Save dataframe to file object, with streamlit cache."""
return df.to_csv().encode('utf-8') | 342732712cf0707726e5215e7400cba1cf737c89 | 46,045 |
def get_mu_input_fixed_indegree(K, gamma, g, w, mu):
"""returns mean input for given connection statistics and presynaptic
activity
"""
return (gamma - (1. - gamma) * g) * K * w * mu | d4594085031e840648f587ad0c04399452d35870 | 46,047 |
import json
def amplify_by_instrument(sounds, amplification_factors):
"""
Amplify the signals with different gain based on the instrument
"""
print("Amplifying sounds by instruments...")
print(json.dumps(amplification_factors, indent=2))
for sound in sounds:
if sound['instrument'] in amplification_factors:
amplification_factor = amplification_factors[sound['instrument']]
if amplification_factor:
sound['audio_segment'] = sound['audio_segment'].apply_gain(amplification_factor)
return sounds | 9fd5fdcf6923bb38099084f56cb9c2615b9ee4d0 | 46,048 |
import os
def _preprocess_path(path):
"""The path can either be a path to a specific optimizer or to a whole testproblem.
In the latter case the path should become a list of all optimizers for that testproblem
Args:
path(str): Path to the optimizer or to a whole testproblem
Returns:
A list of all optimizers.
"""
path = os.path.abspath(path)
pathes = sorted([_path for _path in os.listdir(path) if os.path.isdir(os.path.join(path, _path))])
if 'num_epochs' in pathes[0]: # path was a path to an optimizer
return path.split()
else: # path was a testproblem path
return sorted([os.path.join(path, _path) for _path in pathes]) | 99dd33fb3c1cf652cfcb330ad4b9ba9734590e34 | 46,049 |
import re
def extract_mc_url(re_pattern: str, msg: str) -> str:
"""
return extracted mixed content url as string if found else empty string
"""
if "Mixed Content:" in msg:
results = re.search(re_pattern, msg)
if results and (len(results.group()) > 1):
return results.group(1)
else:
return "Error parsing message for mc url"
else:
return "" | 3cfc8238431942facd65983ccfa34304a50a068c | 46,051 |
def _parse_line(line):
"""Parse poolq Quality file lines."""
if not line == "\n":
parsed_line = line.strip("\n").split("\t")
if not parsed_line[0].startswith("Read counts"):
return parsed_line | 56cf059dd75e329303054f683bc6b360641ae6e5 | 46,052 |
def hub_balance(m, i, j, co, t):
"""Calculate commodity balance in an edge {i,j} from/to hubs. """
balance = 0
for h in m.hub:
if (h, co) in m.r_in_dict:
balance -= m.Epsilon_hub[i,j,h,t] * m.r_in_dict[(h, co)] # m.r_in = 1 by definition
if (h, co) in m.r_out_dict:
balance += m.Epsilon_hub[i,j,h,t] * m.r_out_dict[(h, co)]
return balance | 239ba38223661a3dcbb3b9fa8bf793b6e32156c1 | 46,053 |
import sys
import os
def current_path(*names):
"""Return the path to names relative to the current module."""
depth = 0 if __name__ == '__main__' else 1
frame = sys._getframe(depth)
try:
path = os.path.dirname(frame.f_code.co_filename)
finally:
del frame
if names:
path = os.path.join(path, *names)
return os.path.realpath(path) | bf118459258a041137a373bf0fd18dee897b7672 | 46,055 |
def _new_object(cls):
"""Helper function for pickle"""
return cls.__new__(cls) | f9a0cef73d0f53932ea7955f1aa85234faf6a1eb | 46,058 |
def get_form_prepro(vocab, id_unk):
"""Given a vocab, returns a lambda function word -> id
Args:
vocab: dict[token] = id
Returns:
lambda function(formula) -> list of ids
"""
def get_token_id(token):
return vocab[token] if token in vocab else id_unk
def f(formula):
formula = formula.strip() #.split(' ')
# formula = formula.split(' ')[0]
return map(lambda t: get_token_id(t), list(formula))
return f | a5c7a375b894550fbb978cff7bc6262d7338fc99 | 46,060 |
def isCSERelative(uri : str) -> bool:
""" Check whether a URI is CSE-Relative. """
return uri is not None and uri[0] != '/' | 98cfc2e74e7cb5e1561dec2e40e8076f6eb966e4 | 46,062 |
import json
import requests
def containerMyFolder(apikey,state=None,groupid=None):
"""
returns a short list of your own folders filtered by state (if passed as parameter).
Please note every Object child of the container-Node starts with a trailing _.
apikey: Your ApiKey from FileCrypt
state(optional): filter by state of your folders. Allowed values: "unchecked", "ok", "uncheckable", "error", "offline", "partial"
groupid(optional): filter for specified group
"""
data={"api_key":apikey,"fn":"containerV2","sub":"myfolder"}
if state != None:
data["state"] = state
if groupid != None:
data["group"] = str(groupid)
return json.loads(requests.post("https://filecrypt.cc/api.php",data=data).text) | 074f2f55335a4084f5f509b754cb17ffe036d451 | 46,063 |
from typing import Dict
from typing import Any
def build_validation(validator) -> Dict[str, Any]:
"""Builds and returns a fake validator response object."""
if validator == "sql":
metadata = {"sql": "SELECT user_id FROM users"}
elif validator == "content":
metadata = {
"field_name": "view_a.dimension_a",
"content_type": "dashboard",
"space": "Shared",
}
elif validator == "assert":
metadata = {"test_name": "test_should_pass"}
else:
metadata = {}
return {
"validator": validator,
"status": "failed",
"tested": [
dict(model="ecommerce", explore="orders", passed=True),
dict(model="ecommerce", explore="sessions", passed=True),
dict(model="ecommerce", explore="users", passed=False),
],
"errors": [
dict(
model="ecommerce",
explore="users",
message="An error occurred",
metadata=metadata,
)
],
} | a344d97b2f80486a0c826099bc47fe4bdd60989a | 46,064 |
def combine_channel_number(major: int, minor: int) -> str:
"""Create a combined channel number from its major and minor."""
if minor == 65535:
return str(major)
return "%d-%d" % (major, minor) | 7eee6911546e62b25db05a3c099de75c382e7081 | 46,065 |
import torch
def batch_log_matvecmul(A, b):
"""For each 'matrix' and 'vector' pair in the batch, do matrix-vector
multiplication in the log domain, i.e., logsumexp instead of add,
add instead of multiply.
Arguments
---------
A : torch.Tensor (batch, dim1, dim2)
Tensor
b : torch.Tensor (batch, dim1)
Tensor.
Outputs
-------
x : torch.Tensor (batch, dim1)
Example
-------
>>> A = torch.tensor([[[ 0., 0.],
... [ -1e5, 0.]]])
>>> b = torch.tensor([[0., 0.,]])
>>> x = batch_log_matvecmul(A, b)
>>> x
tensor([[0.6931, 0.0000]])
>>>
>>> # non-log domain equivalent without batching functionality
>>> A_ = torch.tensor([[1., 1.],
... [0., 1.]])
>>> b_ = torch.tensor([1., 1.,])
>>> x_ = torch.matmul(A_, b_)
>>> x_
tensor([2., 1.])
"""
b = b.unsqueeze(1)
x = torch.logsumexp(A + b, dim=2)
return x | 116d6f5713c2bc7dc6b39fb784ee4f6f6c5ba852 | 46,066 |
def constant_check(array):
"""
Checks to see numpy array includes a constant.
Parameters
----------
array : array
an array of variables to be inspected
Returns
-------
constant : boolean
true signifies the presence of a constant
Example
-------
>>> import numpy as np
>>> import pysal.lib
>>> from pysal.lib import examples
>>> import diagnostics
>>> from ols import OLS
>>> db = pysal.lib.io.open(examples.get_path("columbus.dbf"),"r")
>>> y = np.array(db.by_col("CRIME"))
>>> y = np.reshape(y, (49,1))
>>> X = []
>>> X.append(db.by_col("INC"))
>>> X.append(db.by_col("HOVAL"))
>>> X = np.array(X).T
>>> reg = OLS(y,X)
>>> diagnostics.constant_check(reg.x)
True
"""
n, k = array.shape
constant = False
for j in range(k):
variable = array[:, j]
varmin = variable.min()
varmax = variable.max()
if varmin == varmax:
constant = True
break
return constant | aadbc430b0843d6ca63c643adcad1090aca05400 | 46,067 |
def _do_overlap(rect_1,
rect_2):
"""
Determines whether the two rectangles have overlap.
Args:
rect_1: Tuple :code:`(lat_min, lon_min, lat_max, lon_max) describing
a rectangular tile.
rect_2: Tuple :code:`(lat_min, lon_min, lat_max, lon_max) describing
a rectangular tile.
Returns:
True if the two rectangles overlap.
"""
lat_min_1, lon_min_1, lat_max_1, lon_max_1 = rect_1
lat_min_2, lon_min_2, lat_max_2, lon_max_2 = rect_2
lat_min = max(lat_min_1, lat_min_2)
lon_min = max(lon_min_1, lon_min_2)
lat_max = min(lat_max_1, lat_max_2)
lon_max = min(lon_max_1, lon_max_2)
return (lat_min < lat_max) and (lon_min < lon_max) | 74379617ceca1bce4237acdbd9800ba1583e781e | 46,068 |
import os
def model_state_exists(weight_file_path):
"""
Check for model version weights based on file name
:param weight_file_path: Name of the file
:return: bool True if the file exists
"""
return os.path.isfile(weight_file_path) | cb98e28231df1fa486cb7f23f48b5f03045a7a8f | 46,070 |
def symbol(data):
"""
Get the feature symbol.
"""
return data["marker_symbol"] | 2efca500e061818e62405e58107d6d6883950761 | 46,071 |
import hashlib
def uuid_hash(uuid):
"""Return SHA1 hash as hex digest of an uuid.
Requirement from VAC team : You should apply SHA1 hashing over the data as
a text. More specifically you should have the text data as a UTF8 encoded
string then convert the string to byte array and digest it into a SHA1
hash. The resulting SHA1 hash must be converted to text by displaying each
byte of the hashcode as a HEX char (first byte displayed leftmost in the
output). The hash must be lowercase.
No checks are made to determine if the input uuid is valid or not. Dashes
in the uuid are ignored while computing the hash.
:param str uuid: uuid to be hashed
:returns: SHA1 hash as hex digest of the provided uuid.
"""
uuid_no_dash = uuid.replace('-', '')
m = hashlib.sha1()
m.update(bytes(uuid_no_dash, 'utf-8'))
return m.hexdigest() | eb26bfa75cf2d694218adc9782181532c50fb13f | 46,072 |
import pytz
from datetime import datetime
def determine_current_datetime(**args) -> tuple:
"""
Return args['today_date'] as a timezone aware python datetime object
"""
tz = pytz.timezone('America/Vancouver')
args['today_date'] = datetime.now(tz)
return True, args | cd31a44133955da015f9fce2794d89dc4351ca6e | 46,073 |
def get_node_flow(flow_net, node):
"""
Returns the sum of the flow into minus the sum of the flow out from the
node.
In a maximum flow network, this function returns 0 for all nodes except
for the source (wich returns -max_flow) and drain (wich returns max_flow).
"""
flow = 0
n = len(flow_net)
for i in range(n):
flow += flow_net[i][node]
flow -= flow_net[node][i]
return flow | c58518dff13658b15c4b2adebe2f4c4efe2a914e | 46,075 |
def gene_tsne_list(tsne_df):
"""
return data dic
"""
tSNE_1 = list(tsne_df.tSNE_1)
tSNE_2 = list(tsne_df.tSNE_2)
Gene_Counts = list(tsne_df.Gene_Counts)
res = {"tSNE_1": tSNE_1, "tSNE_2": tSNE_2, "Gene_Counts": Gene_Counts}
return res | 4dc3832e8bf78476630585d70afe692bb5526563 | 46,076 |
def num_to_text(num):
# Make sure we have an integer
"""
Given a number, write out the English representation of it.
:param num:
:return:
>>> num_to_text(3)
'three'
>>> num_to_text(14)
'fourteen'
>>> num_to_text(24)
'twenty four'
>>> num_to_text(31)
'thirty one'
>>> num_to_text(49)
'fourty nine'
>>> num_to_text(56)
'fifty six'
>>> num_to_text(156)
'one hundred and fifty six'
>>> num_to_text(700)
'seven hundred'
>>> num_to_text(999)
'nine hundred and ninety nine'
>>> num_to_text(123456)
'one hundred and twenty three thousand four hundred and fifty six'
>>> num_to_text(123456789)
'one hundred and twenty three million four hundred and fifty six thousand seven hundred and eighty nine'
>>> num_to_text(123456789000)
'one hundred and twenty three billion four hundred and fifty six million seven hundred and eighty nine thousand'
>>> num_to_text(12000000000000000)
'twelve million billion'
>>> num_to_text(12000000000000000000000)
'twelve thousand billion billion'
>>> num_to_text(-79)
'negative seventy nine'
"""
num = int(num)
BASE_CASES = {i: word for i, word in enumerate(['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven',
'eight', 'nine', 'ten', 'eleven', 'twelve', 'thirteen'])}
BASE_CASES.update({15: 'fifteen', 20: 'twenty', 30: 'thirty', 50: 'fifty', 80: 'eighty'})
def rem_zero(str_):
if str_.endswith(' and zero'):
return str_[:-9]
elif str_.endswith(' zero'):
return str_[:-5]
else:
return str_
# Handle negative numbers
if num < 0:
return 'negative {}'.format(num_to_text(- num))
name = BASE_CASES.get(num)
if name is not None:
return name
numstr = str(num)
if len(numstr) == 2:
# Teens are special case
if numstr[0] == '1':
return num_to_text(numstr[1]) + 'teen'
elif numstr[1] == '0':
# We're not a teen and we're not a base case, so we must be x0 for x in [4, 6, 7, 9]
return num_to_text(numstr[0]) + 'ty'
else:
return num_to_text(numstr[0] + '0') + ' ' + num_to_text(numstr[1])
if len(numstr) == 3:
return rem_zero('{} hundred and {}'.format(num_to_text(numstr[0]), num_to_text(numstr[1:])))
# Sort out the thousands and billions
if len(numstr) > 9:
return rem_zero(num_to_text(numstr[:-9]) + ' billion ' + num_to_text(numstr[-9:]))
elif len(numstr) > 6:
return rem_zero(num_to_text(numstr[:-6]) + ' million ' + num_to_text(numstr[-6:]))
elif len(numstr) > 3:
return rem_zero(num_to_text(numstr[:-3]) + ' thousand ' + num_to_text(numstr[-3:]))
return 'ERROR' | aedc20c49dc8bca3996e834944998a6cb338f3a5 | 46,081 |
import random
def normalRandomInt(max_val, spread, skew=0):
"""Returns a random integer from a normal distribution whose parameters may be
tweaked by setting max_val, spread and skew. The value is clipped to
the range [0, max_val].
Args:
max_val {number} A positive number. All returned values will be less than
this.
spread {float} Should be a value between 0 and 1. The standard deviation of
the normal distribution will be set to this value times max_val.
skew {float} Should be value between -1 and 1. The mean of the normal
distribution will be set to max_val * 0.5 * (1 + skew).
Returns:
{int} A random integer in the range [0, max_val].
"""
mu = max_val * 0.5 * (1.0 + skew)
sigma = max_val*spread
x = int(random.normalvariate(mu, sigma))
# Ensure the value is in the range [0, max_val]
return max(0, min(x, max_val)) | 4bbe790dc86a0308700d10a65179288f0d3c2674 | 46,082 |
def get_dot(dic, key, default=None):
""" Similar to dict.get(), but key is given with dot (eg. foo.bar) and
result is evaluated in generous way. That is, get_dot(dic, 'foo.bar.vaz')
will return dic['foo']['bar'] if both dic['foo'] and dic['foo']['baz'] exists,
but return default if any of them does not exists.
"""
keys = key.split('.')
res = dic
for k in keys:
if not isinstance(res, dict):
return default
elif k in res:
res = res[k]
else:
return default
return res | cc764debf77b6982733226ec5547e26e2394cd89 | 46,083 |
import json
def load_json(json_path = "folder_tree.json"):
"""
Loads in memory a structured dictionary saved with `create_json`
:param json_path: Path of JSON file with the dictionary
:type json_path: str
:return: Loaded JSON file
:rtype: dict
"""
with open(json_path, "r") as json_file:
files_index = json.load(json_file)
# Check number of users loaded
return files_index | c8c6f683c1622e340a479904b625b14f37ab5525 | 46,084 |
import glob
import os
def get_file_paths(mtrack_list, data_path):
"""Get the absolute paths to input/output pairs for
a list of multitracks given a data path
"""
file_paths = []
for track_id in mtrack_list:
input_path = glob.glob(
os.path.join(data_path, 'inputs', "{}*_input.npy".format(track_id[:-4]))
)
output_path = glob.glob(
os.path.join(
data_path, 'outputs', "{}*_output.npy".format(track_id[:-4])
)
)
if len(input_path) == 1 and len(output_path) == 1:
input_path = input_path[0]
output_path = output_path[0]
file_paths.append((input_path, output_path))
return file_paths | df3c6757bf3059168f06a484fcd677bf40cfda02 | 46,085 |
import numpy
def convert_to_array(pmap, nsites, imtls):
"""
Convert the probability map into a composite array with header
of the form PGA-0.1, PGA-0.2 ...
:param pmap: probability map
:param nsites: total number of sites
:param imtls: a DictArray with IMT and levels
:returns: a composite array of lenght nsites
"""
lst = []
# build the export dtype, of the form PGA-0.1, PGA-0.2 ...
for imt, imls in imtls.items():
for iml in imls:
lst.append(('%s-%s' % (imt, iml), numpy.float64))
curves = numpy.zeros(nsites, numpy.dtype(lst))
for sid, pcurve in pmap.items():
curve = curves[sid]
idx = 0
for imt, imls in imtls.items():
for iml in imls:
curve['%s-%s' % (imt, iml)] = pcurve.array[idx]
idx += 1
return curves | 93d0dced847f9ebe796aa6695b0b62e587f130c3 | 46,087 |
def mark_cards(cards, number):
"""Go through cards list marking off number whenever it appears."""
for card in cards:
for row_index, row in enumerate(card):
card[row_index] = [x if x != number else None for x in row]
return cards | 048314b6aa2416770ceb1942136fc187c726527b | 46,088 |
def band_sample(sample):
"""
Fixture which returns a bands sample file.
"""
return sample('silicon_bands.hdf5') | fa9ebb5e180ef1e2c67adb7d2ead4a8c21d1f815 | 46,090 |
def predict_model(grid, input_train_fs, target_train, input_test_fs):
"""
Validate the best grid model based on training and crossvalidation.
Parameters
----------
grid: Object
GridSearchCV object
input_train_fs: 2D-list
target_train: 2D-list
input_test_fs: 2D-list
"""
model = grid.best_params_['clf']
model.fit(input_train_fs, target_train)
predict = model.predict(input_test_fs)
return model, predict | 63b7715309fdcc2ac8d69995d65ad587bd438cd0 | 46,091 |
def _refine_index_filename(filename):
""" get the current file name for CSV index
"""
return f"{filename}.index" | 819b2587a2a823d57a604dfd981ea4bcc65e1a0d | 46,094 |
import re
def convert_to_abgeno(geno_df, lookup_table):
"""Use lookup table to convert genotypes to AB genotype
representation. This function assumes lookup table has alleles
corresponding to A and B alleles in columns 2 and 3."""
abgeno_df = geno_df
for snp_col in abgeno_df.columns:
if snp_col in list(lookup_table.keys()):
tmp_rep = []
for i in range(0, len(abgeno_df[snp_col])):
tmp_rep1 = re.sub(lookup_table[snp_col][1], 'A',
abgeno_df[snp_col][i])
tmp_rep2 = re.sub(lookup_table[snp_col][2], 'B', tmp_rep1)
tmp_rep.append(tmp_rep2)
# In place replacement of column containing AB genotypes
abgeno_df[snp_col] = tmp_rep
else:
continue
return(abgeno_df) | 5ea37adb48a374f940217a8eddde041a73e51be9 | 46,095 |
def skip_django_trace(func):
"""disable tracing on a django view function"""
func.__skip_trace__ = True
return func | 8583f9ab8338c597f02ac074b75157c70aef8baa | 46,096 |
def expandDims(samweb, dimensions):
""" Expand the given dimensions """
result = samweb._callDimensions('/files/expand_query', dimensions)
return result.json() | 0cd6f5f67d00b2edc375ecc6370061a62ec37d9f | 46,097 |
def fmtf(format):
"""
Returns a function that formats strings.
>>> f = fmtf("%.2f")
>>> f(0.5)
'0.50'
"""
return lambda x: format % x | 9e8d1960aca7bbe69b72cd61c6374f88e0ff5e7b | 46,098 |
def distance_to_greater_value(arr: list, allow_equal: bool) -> list:
"""Creates array where each value indicates distance from arr[i] to a value in arr greater than arr[i].
In order to avoid counting multiple maximums in a given subarray we count the distance to a strictly greater value
in one direction and a greater or equal value in the opposite.
For each value arr[i] we search for a value that is greater (or equal), if found we store its distance from i,
otherwise we store the length of the array.
:param arr: Array from which to determine sum of subarray maximums.
:param allow_equal: Bool. If True, the index of values equal or greater than arr[i] are stored.
:return:
"""
next_greater_value = [0] * len(arr)
stack = []
for idx, num in enumerate(arr):
if len(stack) == 0:
stack.append(idx)
elif num < arr[stack[-1]] or (allow_equal and num == arr[stack[-1]]):
stack.append(idx)
else:
while len(stack) > 0 and ((allow_equal and num > arr[stack[-1]]) or
(not allow_equal and num >= arr[stack[-1]])):
idx2 = stack.pop()
next_greater_value[idx2] = idx
stack.append(idx)
while len(stack) > 0:
idx2 = stack.pop()
next_greater_value[idx2] = len(arr)
return next_greater_value | bd08e7f34783c8ea221b03184e3533778be354ea | 46,101 |
from typing import List
from pathlib import Path
def glob_file_from_dirs(dirs: List[str], pattern: str) -> List[str]:
"""Return a list of all items matching `pattern` in multiple `dirs`."""
return [next(Path(d).glob(pattern)).as_posix() for d in dirs] | c8815e2a39e2722d45fcab4b81d6c81b53566b18 | 46,102 |
def _get_default_route(version, subnet):
"""Get a default route for a network
:param version: IP version as an int, either '4' or '6'
:param subnet: Neutron subnet
"""
if subnet.get('gateway') and subnet['gateway'].get('address'):
gateway = subnet['gateway']['address']
else:
return []
if version == 4:
return [{
'network': '0.0.0.0',
'netmask': '0.0.0.0',
'gateway': gateway
}]
elif version == 6:
return [{
'network': '::',
'netmask': '::',
'gateway': gateway
}] | f039b70bf24ffcac1f31a6ffb9de570606fb55dd | 46,103 |
def contents(filename):
"""The contents of FILENAME, or the empty string if the file does not
exist or is unreadable."""
try:
with open(filename) as inp:
return inp.read()
except:
return '' | 043d154ed2ef01536b9c9bc0ad88a6de596a39d1 | 46,105 |
from sys import platform
def font_name():
"""
苹果系统和微软系统需要不同的字体文件
"""
if platform == "darwin":
return 'Arial Unicode'
elif platform == "win32":
return 'SimHei'
else:
print('not support') | 32dcaeb945f2d45b52281d94747bf9acb33dcaad | 46,106 |
import json
def hello(event, _):
"""
Simple helloworld endpoint which gives back the event to check things
"""
body = {
"message": "Go Serverless v1.0! Your function executed successfully!",
"input": event
}
return {
"statusCode": 200,
"body": json.dumps(body)
} | 1f55e8e389cce72427f0c658e4d698b01216d9ec | 46,107 |
import socket
def end_processes(msg_socket, run_event):
"""
Shuts down socket connection, end threads
"""
print("shutting down..")
run_event.set()
msg_socket.shutdown(socket.SHUT_RDWR)
print("socket shutted down")
return [] | dc411466590ffadd44c82134a66e9dab3dac8871 | 46,109 |
def getMenuLabel(menuPar):
"""
Return menuPar's currently selected menu item's label
"""
try:
return menuPar.menuLabels[menuPar.menuIndex]
except IndexError:
raise
except:
raise TypeError("getMenuLabel: invalid menu par " + repr(menuPar)) | 162c2e6158696c9f306012fa1cba16e5d3af62ea | 46,110 |
def email_event_event(event_d):
"""Event part of a new/deleted event email"""
output = "Event:\n"
output += "* eventId: %i\n" % event_d['eventId']
output += "* Rule name: %s\n" % event_d['rulename']
output += "* Severity: %s\n" % event_d['severity']
output += "* attackerAddress: %s\n" % event_d['attackerAddress']
# Keep only relevant fields
fields = {}
for i in event_d:
if i not in ['_state', 'id', 'eventId', 'rulename', 'severity', 'attackerAddress']:
if event_d[i] != None:
fields[i] = event_d[i]
for i in fields:
output += "* %s: %s\n" % (i, fields[i])
output += "\n"
return output | 73b32c12a89d4115205a97caf25c8588db4cc0ba | 46,115 |
def get_user(keystone, name):
""" Retrieve a user by name"""
users = [x for x in keystone.users.list() if x.name == name]
count = len(users)
if count == 0:
raise KeyError("No keystone users with name %s" % name)
elif count > 1:
raise ValueError("%d users with name %s" % (count, name))
else:
return users[0] | de66d6397ff4a40716acd67cea432eaaeedc76e9 | 46,116 |
import re
def filter_invalid_urls(files_and_urls_dict, regex_pattern):
"""
Filters out the URLs that need to be removed based on a regular
expression pattern.
:param files_and_urls_dict: files' path and their respective URLs.
:type files_and_urls_dict: dict
:param regex_pattern: regular expression pattern for URL filtering
:type regex_pattern: str
:return: filtered URLs per file
:rtype: dict
"""
filtered_dict = {}
for file_path in files_and_urls_dict.keys():
filtered_urls_list = filter(
lambda x: re.search(regex_pattern, x),
files_and_urls_dict[file_path],
)
filtered_dict[file_path] = filtered_urls_list
return filtered_dict | d8cf7626571b3f9cc54961b2584731e248a87174 | 46,117 |
import decimal
import random
def get_random_decimal() -> str:
"""
Returns random decimal number
"""
number = str(decimal.Decimal(random.randrange(155, 389)) / 100)
return number | 4f34c4fcaec3612f2fa0572962b1fc6e554b516e | 46,118 |
def test_summary(root, printerror=False):
"""Verifies if there are problems with the Lattes CV summary parsed
in the argument root.
Args:
root: the Lattes CV that has been parsed with the ElementTree
language.
flag: if 0, there is a summary. If 1, the summary is absent.
printerror: if True, shows the errors in the command window.
"""
summaryflag = 0
#get the summary information from lattes cv
try:
desc = root[0][0].attrib['TEXTO-RESUMO-CV-RH']
except:
desc = ""
if printerror: print('Resumo não encontrado.')
summaryflag = 1
return summaryflag | 746b577862e83208598b4fbabb1b78fa0a7435af | 46,119 |
def space_out_camel_case(stringAsCamelCase):
"""
Note to self: There has to be a better way.
"""
part = []
parts = [part]
for this, next in zip(stringAsCamelCase, stringAsCamelCase[1:] + "#"):
part.append(this)
if this.islower() != next.islower():
part = []
parts.append(part)
parts = ["".join(p) for p in parts if p]
new_parts = []
for this, next in zip(parts[::2], parts[1::2] + [""]):
new_parts.append(this + next)
return "_".join(s.lower() for s in new_parts) | 362b51ef774c09dfe9d0ec5106a3771f80ef7f19 | 46,120 |
def valid_attribute(view, pos):
"""attribute in valid scope"""
if view.match_selector(pos, "source.python comment"):
return False
# match f-string
if view.match_selector(pos, "source.python meta.interpolation.python"):
return True
# match common string
if view.match_selector(pos, "source.python meta.string"):
return False
return True | cbac18bb63e2a0304f91ef45d394778b4f9fab0d | 46,122 |
def find(arr, fkt):
"""find a specific element in the given array"""
for el in arr:
if fkt(el):
return el | ee949a92267d1fcf8717586abad0664a1010b708 | 46,123 |
def mask_peptides(peptides, max_len, pad_aa='Z',
pre_pad=True):
"""
Mask and pad for an LSTM (can be used without calling from instance of Dataset)
"""
num_skipped = 0
num_total = 0
padded_peptides = []
original_peptides = []
#for residues that we are not sure about and we don't have encoding for, we replace them with X
aa_replace={'J':'X','B':'X','U':'X'}
for peptide in peptides:
if len(peptide) > max_len:
num_skipped += 1
print('Skipping ' + peptide + ' > ' + str(max_len) + ' residues')
continue
peptide=peptide.upper()
# determine and apply padding
original_peptides.append(peptide) #keep track of the original and in register with the padded version
# clean up the peptides if there is residues that we don't have encoding for
pep_list=list(peptide)
pep_clean_list=[aa_replace[p] if p in aa_replace else p for p in pep_list]
peptide=''.join(pep_clean_list)
num_pad = max_len - len(peptide)
if pre_pad:
peptide += pad_aa * num_pad
else:
peptide = pad_aa * num_pad + peptide
padded_peptides.append(peptide)
print("Number of peptides skipped/total due to length", num_skipped, '/', num_total)
return padded_peptides, original_peptides | d0ebf8650e3d5575a6081a59a209a35dfb55bf70 | 46,124 |
import os
import re
def get_files(directory, regex, files_to_exclude):
"""Finds files matching the regex in the specified directory except for those in the exclusion list. Returns a list of file paths."""
files = []
for dirpath, dirnames, filenames in os.walk(directory):
for f in filenames:
if re.search(regex, f) and f not in files_to_exclude:
files.append(dirpath + "/" + f)
print(f"Number of texts found: {len(list(files))}")
return files | 88a4045298a770edcc28425486bda9140e59fe9a | 46,125 |
import os
import sys
def get_binary_path(testname, build_dir):
""" Returns full path to test executable."""
base_path = os.path.abspath(
os.path.join(os.path.dirname(os.path.abspath(__file__)), '..'))
binary_name = testname
if sys.platform == 'win32':
binary_name += '.exe'
build_path = os.path.normpath(build_dir)
binary_path = os.path.join(base_path, build_path, binary_name)
return binary_path | 1c0387f2972eb206ba86a0f4b7fbdd03cbad30e9 | 46,127 |
import requests
import time
def get_with_retry(uri, max_retry=5):
"""Wrapper for requests.get() to retry
Args:
uri (str): URI to request
max_retry (int): number of retries to make
Returns:
the requests response
"""
r = requests.get(uri)
k = 0
while r.status_code != 200:
if k == max_retry:
print(f"{uri} failed.")
break
time.sleep(1)
r = requests.get(uri)
k += 1
return r | 1351e138b02e409434c5058f033a53a742ba0204 | 46,128 |
def _check_solve_output(out, err):
"""
Verify from shell output that the Radia solve completed satisfactorily.
Will print any output from the shell.
:param out: (bytes) STDOUT piped from shell
:param err: (bytes) STDERR piped from shell
:return: (bool) True if STDERR is empty. False if STDERR is non-empty.
"""
if err:
print("Error occurred during Radia solve procedure:")
print(out.decode())
print(err.decode())
return False
else:
print("Solve finished")
print(out.decode())
return True | 56fc1d5ffd5d361a4f4090703393dbb19ce11c23 | 46,130 |
def get_pix_offsets_for_point(ds, lng, lat):
"""
Given a raster datasource (from osgeo.gdal)
and lng/lat coordinates, return the x and y
pixel offsets required to get the pixel that
point is in.
Note - this assumes that the point is within the datasource bounds
"""
top_left_x, pix_width, _, top_left_y, _, pix_height = ds.GetGeoTransform()
x_distance = lng - top_left_x
x_offset = int(x_distance * 1.0 / pix_width)
y_distance = lat - top_left_y
y_offset = int(y_distance * 1.0 / pix_height) #pix_height is negative
return x_offset, y_offset | ebfe9bfd92baa71ef1e5aa931b893ad822ce7e06 | 46,131 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.