content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def remote_results():
"""
A successful remote CMIP6 ESGF query reorganised as a list of dictionaries
"""
results = [
# mod1 has both pr and tas for r1 but not for r2 version is always v1
# I'm putting here only the fields that are relevant to the matching function
{'filenames': ['tas.nc'], 'source_... | 448aa34183c2ddc279c7f8d2e0799646dae51d7f | 643,207 |
def weighted_sample(self, dim=None):
"""
Samples a single value across dimension `dim` with weights corresponding
to the values in `self`
Returns the sample and the one-hot index of the sample.
Examples::
>>> encrypted_tensor = MPCTensor(torch.tensor([1., 6.]))
>>> index = encrypt... | b441750bcf53e517c4e8cb7771aeccaae93fe098 | 643,208 |
from typing import List
def handle_wildcard(sequence) -> List:
"""Construct PostgreSQL friendly wildcard string."""
if "N" in sequence:
# Wildcard(s) found, use wildcard notation
return [f"%{sequence.replace('N', '_')}%"]
else:
# No wildcard(s) found, use standard notation
... | b75c15fd8d0213b936dc23f93f74a6d3a45f24dd | 643,209 |
def get_user_parameters():
"""This method provide the parameters required for the ansible
storage volume module on VPLEX"""
return dict(
state=dict(type='str', required=True,
choices=['present', 'absent']),
cluster_name=dict(type='str', required=True),
storage_volu... | 1d5a8ab25dfd4d0ca12b807a6966ad5b9155fbc7 | 643,210 |
def get_strand_color(is_rev):
"""
Get color for forward and reverse reads
:param is_rev: True if read is reversed
:return:
"""
if is_rev == 240.0:
return 1
else:
return 0 | b306eefe724ad35b7738240ec04e9fb4b12e1b57 | 643,211 |
def _make_dssp_dict(handle):
"""Return a DSSP dictionary, used by mask_dssp_dict (PRIVATE).
DSSP dictionary maps (chainid, resid) to an amino acid,
secondary structure symbol, solvent accessibility value, and hydrogen bond
information (relative dssp indices and hydrogen bond energies) from an open
... | 023b3e887ea86964a92aaf6fc5d8e0a54c68fcd8 | 643,213 |
def factorial(number):
"""Computes the factorial"""
number = int(number)
if (number == 0) or (number == 1):
return 1
else:
return number * factorial(number-1) | 82566a098ac3b8dd1659d88dafd605e0d87937e8 | 643,214 |
def to_bytes(url):
"""to_bytes(u"URL") --> 'URL'."""
# Most URL schemes require ASCII. If that changes, the conversion
# can be relaxed.
# XXX get rid of to_bytes()
if isinstance(url, str):
try:
url = url.encode("ASCII").decode()
except UnicodeError:
raise Uni... | 0a688d6062e50e5014c9adc5d8e9538e19a9fd80 | 643,215 |
import math
def define_cutoff(max_freq, passing_freq, high_pass):
""" # Define Cutoff Value
Args:
max_freq (int): the max frequency allowed
passing_freq (int): the cutoff value
high_pass (bool): if is a high pass filter
Returns:
float: the cutoff value to subtitute wc
... | ad87b730e2659fcd75b6d014249012a89978d62d | 643,216 |
def process_salary(all_salary: dict, salary: list) -> dict:
"""
Функция обработки списка с зарплатой
:param all_salary - словарь с результатами парсинга всех страниц
salary: элемент списка с зарплатой
"""
if salary:
all_salary[salary[0]] = [all_salary[salary[0]][0] + salary[1... | db80df8819a4f935397c12abe1cbbdfb8e97f952 | 643,217 |
def clean_text(txt):
"""
Function to clean out any problematic or illegal characters
Arguments:
txt: List of character strings
Returns: List of character strings
@ author: Christopher Olsen, ConocoPhillips
"""
if isinstance(txt, str):
txt = [txt]
txt = [x.lower() fo... | 46086def090dcce0be814efaa69a08ad0902d210 | 643,218 |
import numpy
def FormCorrelationMatrix(mat):
""" form and return the covariance matrix
"""
nVars = len(mat[0])
N = len(mat)
res = numpy.zeros((nVars,nVars),'d')
for i in range(nVars):
x = mat[:,i]
sumX = sum(x)
sumX2 = sum(x*x)
for j in range(i,nVars):
y = mat[:,j]
sumY = s... | 8263b2245b912632cc5bb86906f5522edcaa163a | 643,220 |
import argparse
def parse_args(args):
""" Parse cmdline args """
parser = argparse.ArgumentParser()
parser.add_argument("-l", "--log-file", help="log file name to be created",
default="test-db-{:%Y%m%d}.log")
parser.add_argument("args", nargs='*')
return parser.parse_args(a... | 15a0418c631bb310eb2f03d0f1cb6dc40dab843c | 643,222 |
import types
def is_object_module(obj):
"""
Test if the argument is a module object.
:param obj: Object
:type obj: any
:rtype: boolean
"""
return isinstance(obj, types.ModuleType) | b9dc22543b19be02f0cd2ac396370affcd0e3aeb | 643,223 |
def calculate_change_number_dyn(sum_to_form: int, denominations: list) -> int:
"""
Calculate the minimum number of 'denominations' required to make 'sum'
:param sum_to_form: a sum to form
:param denominations: possible denominations ("steps")
:return: a total amount of denominations to use to reach ... | a9af0661da2dddbeab6e6a03e3ac537d19ddb893 | 643,224 |
import logging
import sys
def get_logger():
"""
Get the default logger for this module and set default settings.
:return: the logger
:rtype: logging.Logger
"""
lgr = logging.getLogger('neurone_loader')
lgr.setLevel(logging.INFO)
fmt = logging.Formatter(fmt='%(asctime)s [%(name)s.%(mod... | 8562a0f69b931dd56f1c0ae064828754c2fde5d6 | 643,226 |
import re
def tag_repeated_characters(tweet):
"""
Marks words with repeating characters in tweet.
Repetition needs to be greater or equal than three.
INPUT:
tweet: original tweet as a string
OUTPUT:
tweet with words with repeating characters marked
"""
def tag_repeated(word... | 38fdbecb25d198091df7a1f35cf3ae9d5bfd726e | 643,227 |
def mattrgetter(*attrs):
"""
获取某对象的多个属性,不存在时返回None
:param attrs: 各属性值,str
:return: function
"""
return lambda obj: {attr: getattr(obj, attr, None) for attr in attrs} | 23e096c819fe16655716c6000378cfaebdc2a954 | 643,228 |
def registrar(registry, name="entry"):
"""
Creates and returns a register function that can be used as a decorator
for registering functions into the given registry dictionary.
:param registry: Dictionary to add entry registrations to.
:param name: Name to give to each entry. "entry" is used by def... | 9ca990c262133d26659fb92823f0b12b867424db | 643,229 |
def kineticEnergy(mass,velocity):
"""1 J = 1 N*m = 1 Kg*m**2/s**2
Usage: Energy moving an object"""
K = 0.5*mass*velocity**2
return K | 2cba0fd2ad18f9cc56ad4c778f7b9be7fc3d2787 | 643,230 |
def normalize_db_entry(line, files_table, vs_parts_table, vs_info_table, fs_info_table, objects_table, reports_table):
""" Make testing more consistent and reasonable by doctoring certain db entries.
Args:
line: a String, the line to remove the object id from.
files_table: a map from object ids... | af7e677a534926e801b0c9fb4b303fd1b8ba58d7 | 643,231 |
def properly_decorated_test_class_with_steps():
"""A Python class decorated with the 'test_case_with_steps' mark which designates it as a test case with steps. The
class is also decorate with the required 'test_id', 'jira' marks.
Named formatters:
test_name: Name of decorated class. (Test case nam... | 795d6ecf2a8ac31e5f3e7d514db60ec774470d1b | 643,232 |
from datetime import datetime
def make_datetime_pretty_md(DateTime: datetime):
"""pretty print DateTime for use in Markdown
Args:
DateTime (datetime): DateTime to pretty print, format: 2020-09-05 17:30:00
Returns:
str: pretty printed DateTime, in markdown syntax
"""
return DateT... | 5e337258554af5f8d0678ab0d4ba384753a9e906 | 643,233 |
import time
def format_brewery_results(results, term):
"""
Formats brewery results for Slack
:param results:
:param term:
:return:
"""
out = [{
"color": "#36a64f",
"author_name": "BeerBot",
"title": "There are {length} brewery results for {term}".format(length=res... | b2b11efd1ff98786625676a6cc48e4ac1a16a747 | 643,234 |
def string_to_array(string):
"""Convert a string to array, even if empty."""
if string == "":
return [""]
return string.split() | c601c7966fc11477e32dbd5ccbd12fb0e212ebc0 | 643,235 |
def _get_row(testdata):
"""Get row or rownum or row_num from in testdatafile"""
keys = ["row", "row_num", "rownum"]
value = ""
for key in keys:
td_row = testdata.get(key, None)
if td_row is None:
continue
else:
value = td_row
break
return ... | eef74624f53080d209fce0eb5ca5a91de69a12ac | 643,236 |
def times_two(a):
"""
>>> times_two(2)
4
>>> times_two('bee')
beebee
"""
return a * 2 | d7b9c24c630cc3be1e009d16c5c320e11e0464ab | 643,237 |
def hist(data,bins=42,stacked=True,**kwargs):
""" Figure: Histogram(s) of Series or DataFrame. """
return data.plot.hist(bins=bins,stacked=stacked,**kwargs) | b94f5955c12c77ab70bfd4263a0b0df18e5794ec | 643,238 |
import os
def get_environment_variable(name):
""" Try to get the environment variable """
variable = None
try:
variable = os.environ[name]
except KeyError:
pass
return variable | eda299a2e105b4b2a4a31c549e152107b1779282 | 643,240 |
import os
def find_first_file(arg_file, alternatives):
"""Because of http://stackoverflow.com/questions/12397681,
parser.add_argument(type= or action=) on a file can not be used
"""
found = None
file_locs = [arg_file] + alternatives
for loc in file_locs:
if loc is not None and os.acces... | 5e09dfa01f46b2ccf034479eeccd8eaeeae9c7f8 | 643,241 |
def senhas_nao_iguais(senha, senha2):
"""Verifica se as senhas digitadas não são iguais"""
return senha != senha2 | 6e6391749da3c2e2bc84cf52e56e0e81efaed777 | 643,242 |
def quote_stripped(value: str) -> str:
"""
Strip out a single level of single (') or double (") quotes.
"""
single, double = "'", '"'
if (value.startswith(single) and value.endswith(single)) or\
(value.startswith(double) and value.endswith(double)):
return value[1:-1]
return value | b7016bc484948d053635795b8617b962535b46c6 | 643,243 |
def decorate(func):
"""
Function to decorate the output
:param func: the function to wrap the output of
:return: nested func
"""
def inner(self, *args, **kwargs):
print("~" * 60)
func(self, *args, **kwargs)
print("~" * 60)
return inner | 366fa90a0423706f11151798d54635dfde90ef10 | 643,244 |
def reorder_cats(cats):
"""
try:
cat0 = Table(cats[0], names=header[0])
except TypeError:
cat0 = cats[0]
except ValueError:
cat0 = cats[0]
"""
if len(cats[0].colnames) <= len(cats[1].colnames):
cat_base = cats[0]
cat_modf = cats[1]
else:
cat_ba... | e9eaeae3af85db4b8ad854899211a77c62098d45 | 643,248 |
def twos_complement(dec):
"""
Convert decimal integer number to U2
:param dec: Number to change
:type dec: int
:return: Number in U2
:rtype: string
"""
if dec >= 0:
binint = "{0:b}".format(dec)
if binint[0] == "1": binint = "0" + binint
else:
dec2 = abs(dec ... | 2f6a33aa4c282f6386cccf473e3809df89f919cc | 643,249 |
import logging
def get_ssl_policy(project_id, ssl_policy, compute_client):
"""
Gets the minimum TLS version for the SSL policy.
"""
# Get the SSL Policy metadata
try:
ssl_description = compute_client.sslPolicies().get(project=project_id, sslPolicy=ssl_policy).execute()
except:
... | 71ba194c5dc8aa93097aab7707f4d713ab6cef13 | 643,250 |
def load_communities(communities_path):
"""
load community list.
:param communities_path:
:return:
"""
communities = []
with open(communities_path, "r") as f:
for line in f.readlines():
communities.append([int(x) for x in line.split(" ")[:-1]])
return communities | 72f39b0764257a93c7db41545d7ed2800b88664d | 643,251 |
import six
def ensure_str(s, encoding='utf-8', errors='strict'):
"""Coerce *s* to `str`.
For Python 2:
- `unicode` -> encoded to `str`
- `str` -> `str`
For Python 3:
- `str` -> `str`
- `bytes` -> decoded to `str`
"""
if not isinstance(s, (six.text_type, six.binary_type)):
... | 37cb0d03e17603b4a3461476d4f20b12383de14c | 643,252 |
def get_cell_value_list(id, row_list) -> list:
"""[指定した商品idの価格をリストへ格納し、リストを返す]
Args:
id ([int]): [商品id]
row_list ([list]): [価格記録sheetの2行以降のデータ]
Returns:
list: [指定した商品idの価格リスト]
"""
return [cell[2].value for cell in row_list if cell[0].value == id] | 42c5498e4f955f58e635099821c26732b4189eba | 643,254 |
def code_block(text, language=""):
"""Return a code block.
If a language is specified a fenced code block is produced, otherwise the
block is indented by four spaces.
Keyword arguments:
language -- Specifies the language to fence the code in (default blank).
>>> code_block("This is a simple c... | 3f530bf9027340b46d4724020f2285c5e74813f7 | 643,255 |
import re
def _fix_timex_val(date):
"""Rather simplistic way to add in hyphens. There are probably a lot
of cases it does not deal with."""
match = re.compile("^(\d\d\d\d)(\d\d)(\d\d)(.*)").match(date)
if match:
(year, month, days, rest) = match.groups()
return "%s-%s-%s%s" % (year, mo... | 3f203d7f85b0f2463d0e301d89b5ac62a90b7d09 | 643,256 |
def le16_bytes_to_list(bstr):
"""Convert 16bit little-endian bytes to list"""
i = iter(bstr)
return [lb + 256*next(i) for lb in i] | 32aaa6830bb917ff0e3d5a1aa24f96fbecff55e6 | 643,257 |
import copy
import random
def generate_redundant_parameters(hyper_params, gridable_parameters, gridable_defaults, error_number):
"""
This function will randomly choose a set of hyper_params and make a dict out of it so we can
duplicate the parameter specification in both the model and grid search.
:p... | e71af20760f37397dbe4f3cb0d275287dd523613 | 643,258 |
import subprocess
def _have_git():
"""Can we run the git executable?"""
try:
subprocess.check_output(["git", "--help"])
return True
except subprocess.CalledProcessError:
return False
except OSError:
return False | e9d841d796395613d1bf11652017732da6a77ea8 | 643,259 |
from typing import Dict
import os
def create_login_dictionary(num_accounts: int) -> Dict[str, str]:
"""
Creates the login dictionary.
:param num_accounts: number of accounts to create (based on set_usernames_passwords())
:return: dictionary with keys as usernames and values as passwords, to log into t... | d9b878af4a3851cb5c44b4519ac5f767da7c3440 | 643,260 |
def get_displacement_vector(molecule, start_atom, end_atom):
"""
Get the displacement vector between `start_atom` and `end_atom`.
"""
position1, position2 = (
molecule.get_atomic_positions((start_atom, end_atom))
)
return position2 - position1 | a15e6dfcc701660979889d004b12d188fc629664 | 643,261 |
def xor_swap(i, j):
"""Swap with exclusive or"""
i = i ^ j
j = i ^ j
i = i ^ j
return i, j | 0ce0d09d8fdf94c3f81a4c0343cfe92aa992d3f9 | 643,262 |
from typing import Dict
def is_directory_entry(entry: Dict) -> bool:
"""Return if given entry is for directory."""
return "directory" == entry["type"] | 948ca602171be307e132a370e33ec77767d110de | 643,263 |
def count_companies(client, db_rid=None, company_identifier=None, company_name=None, status=None, zip=None,
phone_number=None, fax_number=None, website=None, verbose=False):
"""
Counts Companies with a particular set of optional conditions.
:param client: Pass the authorised connectwise c... | 6a6da13e8e5f63d0b4f22b5365b0946fcebb6260 | 643,264 |
import six
def FuzzyBool(value):
"""Returns value as a boolean with special handling for false-like strings."""
if (isinstance(value, six.string_types) and
value.strip().lower() in ('false', 'no', '0')):
return False
return bool(value) | ee29b901e8acbfc8249dc26f744a3768a39861e9 | 643,265 |
def _get_saml_user_data_property(request, prop_slug):
"""
Shortcut for getting samlUserData properties generated by python3-saml.
These can sometimes manifest as lists or strings.
:param request: HttpRequest
:param prop_slug: string (property slug)
:return: string or None
"""
value = req... | 28cf482cfe2c71e5afebd8fae96c0b9b6739b120 | 643,266 |
from typing import List
def generate_sequence(number: int, steps: int, reverse: bool) -> List[int]:
"""Generate a bottle sequence which will count bottles a number of times
with the given step length."""
if reverse:
return [min(i, number) for i in range(0, number + steps, steps)]
else:
... | 9c231cafc309b035ffbf5de7d074513150654534 | 643,267 |
def requires_grad(m):
""" If `b` is not set `requires_grad` on all params in `m`, else return `requires_grad` of first param """
ps = list(m.parameters())
if not ps:
return None
return ps[0].requires_grad | 987e6df847f9d4b3e21c48cb1afec964d0ff5d39 | 643,268 |
import shutil
def post_input2LVzipf(INDIR, FUNCTION, OUTDIR, ARGS, intranet):
"""
Saves L,V of pieces and L,V,Zipf of authors and Zipf of total corpus.
"""
# INPUT PARAMETERS
At, threshold, TYPE = ARGS[1], ARGS[2], ARGS[3]
output_LVpieces = "LV_pieces_{0}_{1:0.2f}_{2:0.4f}".format(TYPE, At, threshold).replace("... | 84740f5237cddf4910e31c29fa24e18850d47da5 | 643,270 |
def rect_from_sides(left, top, right, bottom):
"""Returns list of points of a rectangle
defined by it's `left`, `top`, `right`, and `bottom`
coordinates, ordered counter-clockwise."""
return [
(left, bottom),
(right, bottom),
(right, top ),
(left, top ),
] | 083676ce815b97afe16cd53ffedb75212f3f03c1 | 643,271 |
def ixor(f,g):
""" f and g are ISPs given as [on,off["""
## fb = inot(f)
## gb = inot(g)
## y1 = iand(fb,g)
## y2 = iand(f,gb)
## return ior(y1,y2)
## res =ior(iand(inot(f),g),iand(f,inot(g)))
## res = [(f[0]&~g[1])|(~f[1]&g[0]),(f[0]&g[0])|(~f[1]&~g[1])]
res = [(f[0]&g[1])|(f[1]&g[0]),(f[0... | a02ce12cddbde9958d645955ae1622c6fbda3e60 | 643,272 |
def img2windows(img, h_split, w_split):
"""Convert input tensor into split stripes
Args:
img: tensor, image tensor with shape [B, C, H, W]
h_split: int, splits width in height direction
w_split: int, splits width in width direction
Returns:
out: tensor, splitted image
""... | 1580c818bf4ba2d0a13d0c039f4d4028dc113061 | 643,273 |
def get_payment_id_from_tx_extra_nonce(extra_nonce):
"""
Extracts encrypted payment id from extra
:param extra_nonce:
:return:
"""
if 33 != len(extra_nonce):
raise ValueError("Nonce size mismatch")
if 0x0 != extra_nonce[0]:
raise ValueError("Nonce payment type invalid")
r... | 1007c3d1d94484ccc7dd6c17fa5cc87c1f0e4724 | 643,274 |
def tcl_findprd_prepcuref(center, tail, noprefix=False, key2mode=False):
"""
Prepare candidate PRD.
:param center: PRD-center-tail.
:type center: str
:param tail: PRD-center-tail.
:type tail: int
:param noprefix: Whether to skip adding "PRD-" prefix. Default is False.
:type noprefix: ... | af19ccf44a5ef9eb8492ce9a44a4775703e5841b | 643,275 |
from typing import List
from typing import Callable
import inspect
def find_scrapers(module) -> List[Callable]:
"""
Build a list of 'scraper' functions contained in a module.
These consist of every function public function (i.e., does not begin with_)
that is defined, but not imported, in the module
... | 7f6c3ebdf41f16a5998b4cba679b895b05d491da | 643,276 |
import random
def pseudosample(x):
"""
draw a bootstrap sample of x
"""
#
BXs = []
for k in range(len(x)):
ind = random.randint(0, len(x) - 1)
BXs.append(x[ind])
return BXs | 4561b322c419faa2fbadb6957466bacbdde4c0ca | 643,277 |
def _sanitize_vmr(df):
"""Filters entries with '511' error, impossibly high speed, abnormally
high vessel width, as well as singletons (only one entry) from vessel
movement DataFrame.
Args:
df: Vessel movement DataFrame.
Returns:
Sanitized vessel movement report DataFrame.
"""
... | 1cd2828e427e0d10f52c30d2464ca4cefb2297eb | 643,278 |
def has_numbers(string):
"""Returns true if there are digits in the string"""
return any(char.isdigit() for char in string) | 27d741316aac6c0d0125cd35028bf589febea9a8 | 643,279 |
import argparse
def time_interval(arg):
"""Function for checking validity of command line arguments."""
if int(arg) < 0:
raise argparse.ArgumentTypeError
return arg | 333f161ebd88e80e021764fd29db222a410137ae | 643,280 |
def process_line(log_line):
"""Process a single full log string"""
splt = log_line.split(maxsplit=5)
folder_list = splt[-1].split("/")
return [f.strip() for f in folder_list] | c1fca9367380e865b0766a7beecd958137a3d17f | 643,281 |
def is_melceplogf0_evaluator(evaluator_keys):
"""Are these evaluator keys from MelCepLogF0 evaluator?"""
return (len(evaluator_keys) == 2 and
evaluator_keys[0] == 'max_mel_cep_distortion' and
evaluator_keys[1] == 'max_log_f0_error') | 253ae0bd5b71b536466f58414a3040f6ea6aade5 | 643,282 |
from warnings import warn
def _deprecated_getitem_method(name, attrs):
"""Create a deprecated ``__getitem__`` method that tells users to use
getattr instead.
Parameters
----------
name : str
The name of the object in the warning message.
attrs : iterable[str]
The set of allowe... | d6521c46120ce8bcbde62b1e73735e0218773ba8 | 643,283 |
def _to_utf8_string(s):
"""Encodes the input csv line as a utf-8 string when applicable."""
return s if isinstance(s, bytes) else s.encode('utf-8') | af7eeae024a48df61f56851e2fe78596b70b5fac | 643,284 |
import click
def show(obj):
"""Display the content of the configuration file."""
if obj.temporary:
click.secho("This is a temporary config file. Please create a "
"proper config file using `quickci config create`.",
fg="red")
click.echo(obj.show())
retur... | e4c0ca97a17577c493809d95a0c6736e37073bb4 | 643,285 |
from typing import Iterable
from typing import Any
def contains_class_type(l: Iterable, cls: Any) -> bool:
"""Return if the given list contains a class with the given type"""
for e in l:
if isinstance(e, cls):
return True
return False | e74d14f2365ddbbc9153048af6977220be4db4f8 | 643,286 |
import os
def get_frequency_norms(path_to_norms=None):
"""Parameters:
path_to_norms : optional, string. Full path, including filename, of the frequency norms.
Return dictionary of SUBTL frequencies, keys = words, values = list of norms."""
if path_to_norms is not None:
source_norms ... | 7f56a3fcbe8535ff8b8055f368d8c46aba0933b1 | 643,288 |
def extract_uuidlist_from_record(uuid_string_list):
"""Extract uuid from Service UUID List
"""
start = 1
end = len(uuid_string_list) - 1
uuid_length = 36
uuidlist = []
while start < end:
uuid = uuid_string_list[start:(start + uuid_length)]
start += uuid_length + 1
uui... | f6f4acdbdbfdf9aac909669d7ea3ad8492bed685 | 643,289 |
def get_exchange_trading_pair(table_name):
"""Function to get exchange and trading_pair bc coinbase_pro has an extra '_' """
# for coinbase_pro
if len(table_name.split('_')) == 4:
exchange = table_name.split('_')[0] + '_' + table_name.split('_')[1]
trading_pair = table_name.split('_')[2] + ... | d6516142e4c987c087e4cba278f356f003575020 | 643,290 |
def pygame_likelihood_sampler_paint(sampler):
"""The paint function for visualisation
:param sampler: the sampler to be visualised
"""
def get_vector_alpha_parameters(vector):
"""
:param vector:
"""
_max_prob = vector.max()
_min_prob = vector.min()
_d... | 58edb5796125c5f99b7095c3211fef69f935cd78 | 643,291 |
def parse_did(did):
"""Takes a did and returns the run number, dtype, hash"""
scope, name = did.split(':')
number = int(scope.split('_')[1])
dtype, h = name.split('-')
return number, dtype, h | de7e9727877f968e2a7ce5b37146b229f6b04663 | 643,292 |
def add_five(num):
"""Add five to num"""
num += 1
num += 1
num += 1
num += 1
num += 1
return num | 430d5a19a5f2a47f03f19ffaa77a68e737864470 | 643,293 |
import string
def hex_to_decimal(hex_val):
"""Converts hex value(str) to decimal(int)"""
reversed_hex = hex_val[::-1] # reverse so power(of 16) = index
decimal = 0 # keep track of sum
hex_conversion = string.hexdigits # access letters a-f
for i, value in enumerate(reversed_hex): # index = powe... | 0a3fdcfb1ac072b114c22c4d3979f41ca6ef7c8f | 643,294 |
import math
def find_roots_of_1(n):
"""Find complex n-roots of 1."""
return [complex(math.cos(i * 2 * math.pi / n), math.sin(i * 2 * math.pi / n)) for i in range(n)] | ebd495cf6ecffd9ac3570bed288c1695699d7086 | 643,295 |
def standard2natural(mu, sigma):
"""
Converts standard parameterisation of a 1-D Gaussian to natural
parameterisation.
:param mu: The mean, (*, D).
:param sigma: The standard deviation, (*, D).
:return: np1, np2, (*, D), (*, D).
"""
assert mu.shape[-1] == sigma.shape[-1], "mu (*, D), sig... | c80158dc0122579e55ead6bcd83cf5a411dd214b | 643,296 |
def calculate_mae(predictions, ground_truth):
"""Calculate MAE in a colab friendly way."""
if not predictions or len(predictions) != len(ground_truth):
raise ValueError(
'Predictions and Ground Truth should be of equal length and non-empty')
error = 0.
for i in range(len(predictions)):
error +=... | ec01c6d0731da8da9e486c3dc8d9ea2936316556 | 643,297 |
import yaml
def load_config(config_file="./config.yaml"):
"""
Load config and secrets
"""
with open(config_file) as cyaml:
config = yaml.load(cyaml, Loader=yaml.FullLoader)
return config | 0dd42a5dad62cc739a2d79023dc71584f97ee8da | 643,298 |
import os
def check_existence(tag):
"""Checks if model exists, then asks for user input. Returns True for overwrite, False for load.
:param tag: [description]
:type tag: [type]
:raises SystemExit: [description]
:raises AssertionError: [description]
:return: True for overwrite, False for load
... | f1188742a38153eacc5740e27dd87f20d9bde894 | 643,299 |
import re
def restrip(string, mode = "a"):
"""Strips leading and/or trailing whitespace from a given string.
Args:
string: The string to be stripped.
mode: Optional; All, leading, or trailing whitespace will be stripped
depending on whether mode is equal to a, l, or r.
Returns:
... | 3a28cd2d38ec4c5ea21a3c42a94ed8039e404cb5 | 643,300 |
import json
def config(filename: str = "configuration"):
""" Get default configuration file """
try:
with open(f"{filename}.json", encoding='utf8') as data:
return json.load(data)
except FileNotFoundError:
raise FileNotFoundError("Could not find JSON file.") | c03f76e2baf82092bc986e7ed8393676bda9f10f | 643,301 |
import argparse
def get_parser():
"""Función para obtener el parseador de argumentos que se le pasa al programa por línea de comando
Returns
-------
parser
objecto del tipo `ArgumentParser`
"""
parser = argparse.ArgumentParser(
prog='gmaps-db',
usage='gmaps-db -c <db_o... | 3d5cb4adb0d2c6c056a3fb18e7783d2a3c058197 | 643,303 |
def collapse_axes(xlab, ylab):
"""Return X/Y labels for unique X positions"""
_xlab, _ylab, pos = [xlab[0]], [ylab[0]], [0]
for i in range(1, len(xlab)):
if xlab[i] != xlab[i-1]:
_xlab.append(xlab[i])
_ylab.append(ylab[i])
pos.append(i)
return _xlab, _ylab, po... | 4bf4ae99b8addaa0ea4973446e81f1d5701c4889 | 643,305 |
def set_ids(g):
""" Set missing `id` property of all g vertices to the mtg id """
ids = g.property('id')
for vid in g:
ids.setdefault(vid,vid)
return ids | 3e3abe63380e6d8457118f22a608e65f43b2bc6a | 643,306 |
def check_filters_enabled(params):
""" Check if filters are enabled
"""
tab = params.tab
filters = tab.get('filters', None)
if tab is None:
return False
if not filters or not filters.get('items', None) or not filters.get('conjunction', None):
return False
return True | fcd86f63e3bf6a182eeabb3d2986feb98bd0b9b6 | 643,308 |
def get_percentile_values(cycle_time_dataframe, percentiles):
"""
Get percentile values for cycle times from cycle time data frame.
"""
return tuple([cycle_time_dataframe.Cycle_time.quantile(p/100.0) for p in percentiles]) | b6eb5b30562959984f327b9b8616f3c3abb1cae9 | 643,309 |
import argparse
import pkg_resources
def get_parser(parse_this=None) -> argparse.ArgumentParser:
"""Get parser for user command line arguments."""
parser = argparse.ArgumentParser(
prog='cryptosteganography',
description="""
Cryptosteganography is an application to save or retrieve... | 03a6ae6ec0385c2ca8bf95427c3bf820d254de8a | 643,310 |
def aggregate_teams(players):
"""Compute aggregate stats for each team for the tournament."""
# stats to sum
stats = {'kills', 'deaths'}
# don't sum these stats
dont_sum = {'n', 'duration (s)'}
# compute base stats (aggregated)
teams = {}
for p in players:
t = p['team']
... | 6dbb0fd49acaa1b1acce891f4cf099626ea157ad | 643,311 |
def compare_bits(mem_entry, mem_idx, test_bit):
"""Compare a memory entry to the expected bit value for that entry"""
valid_entry = True
for bit_idx, bit in enumerate(reversed(mem_entry)):
valid_entry = False
assert int(bit) == test_bit, (
"Incorrect bit @ index {} of mem entry #... | 4afa92b95331f6134aac63833da8fb3aade93f8c | 643,312 |
def node_uct(self):
""" return the best node to explore based on uct """
huct = -1000
bn = None
for m in self.t:
u = self.t[m].uct(self.N_playout)
if u == -1:
return self.t[m]
if u > huct:
bn = self.t[m]
huct = u
return bn | a145bd0ce8b723492ec26130d5af35222b3f270b | 643,313 |
def hitTest( a, b ):
"""Circular collision test. Assumes x, y, and radius members on both objects."""
r = a.radius + b.radius
x = abs( a.x - b.x )
y = abs( a.y - b.y )
if x <= r and y <= r and x*x + y*y <= r*r:
return 1
return 0 | 98285d71f6ab73501cff7a3d4cd56891b00e25bc | 643,314 |
def validateCPE(cpe):
"""
Returns None if CPE text is valid, validation error string otherwise.
"""
if not cpe.startswith("cpe:"):
return 'CPE must start with "cpe:"'
return None | 8f7beaf75b2cff6e8a2efb0456e872bf968807fe | 643,315 |
def bold(text: str):
"""Return bolded text"""
return f"**{text}**" | 56adc60296db01de3bd63b0b5383cc3ed4dc90be | 643,316 |
def ask_yes_or_no(question):
"""Primpts a yes or no question to the user.
Args:
question: the question to asked.
Returns:
boolean representing yes or no.
"""
while(True):
reply = str(input(question+' (y/n): ')).lower().strip()
if reply:
if reply[0] == 'y... | cf6628f7e93e962151daaa0d1b5133e4bb07c405 | 643,317 |
def too_many_locals_function(): # [too-many-locals]
"""pylint will complains about too many local variables"""
args0 = 0
args1 = args0 * 1
args2 = args1 * 2
args3 = args2 * 3
args4 = args3 * 4
args5 = args4 * 5
args6 = args5 * 6
args7 = args6 * 7
args8 = args7 * 8
args9 = arg... | 2c7d11522af12d29a53c6ae643b4cae3be40a767 | 643,318 |
import re
def _compose_comment(remote: str, sha: str, git_log: str) -> str:
"""Composes a comment describing the original (triggering) commit.
Arguments:
remote {str} -- a link to the remote git repo
sha {str} -- the hash of the commit
git_log {str} -- the git log for the commit
... | d6aac13cbf23db2b5ea94e0b6cfe9600f1900283 | 643,319 |
def CountWordOccurences(wordArray):
"""Returns a dictionary containing each word in the array and how often it occurs"""
dict = {}
for word in wordArray:
# If the dictionary does not contain the word, add it to the dictionary with 1 occurence
if not word in dict:
dict[word] = 1
... | 7b964dd16a3826043f7730df642f51b0cdbcdadd | 643,320 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.