content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def generate_static_obj_def(name,
look,
mesh,
world_xyz=[0.0, 0.0, 0.0],
world_rpy=[0.0, 0.0, 0.0],
material='Neutral'):
"""Generate tag for a static object"""
world_transf... | 647898db8594f9ec15739897535ee7e9236fde94 | 644,359 |
def _GetColFormatString(width, align_right):
"""Returns the format string for a field.
"""
if align_right:
sign = ""
else:
sign = "-"
return "%%%s%ss" % (sign, width) | 93febf83be8cd467ac7a70acb7e8816c12068f6d | 644,360 |
def any_lowercase4(word):
"""
- Returns a True or False to the question of whether the inputted word has any lower case letters.
- Sets the default state of the answer to be false.
- Evaluates each letter in the parameter, word and determines if the previous answer or the letter is lowercase. If either ... | c892ceff7ae20cacb29d3edabd32a8ce0ebd5ae2 | 644,361 |
import re
def parse_vocab_test(text):
"""
Parse the following structure into list of vocab tokens
Input:
..
..
..
Output:
[result,
hair,
strong,
tear,
..
..
..
]
"""
text = re.sub(' ?\d+ \xef\x81\xb1 ?', '\n', text)
text = re.sub(' ?\d+ ... | 5687bc78588db37f9909946619861819452b51b0 | 644,362 |
def AddNodeVersionFlag(parser, hidden=False):
"""Adds a --node-version flag to the given parser."""
help_text = """\
The Kubernetes version to use for nodes. Defaults to server-specified.
The default Kubernetes version is available using the following command.
$ gcloud container get-server-config
"""
return ... | 33bc8311ec77d75fae77c8bbe9b4fdd324f0cd42 | 644,363 |
def get_radio_horizontalization_html(radio_label):
""" Takes a normal radio and restilizes it to make it horizontal and bigger"""
html = f"""<iframe src="resources/horizontalize-radio.html?radioText={radio_label}" style="height:0px;width:0px;"></iframe>"""
return html | a3584a167a69c4c14b57b591d7c3cd2532ded151 | 644,364 |
def cli(ctx):
"""Get the list of all forms.
Output:
Displays a collection (list) of forms.
For example::
[{u'id': u'f2db41e1fa331b3e',
u'model_class': u'FormDefinition',
u'name': u'First form',
u'url': u'/api/forms/f2db41e1fa331b3e'},
... | 5018ce4acdb9099849ee49e93e869e536b7e1d9a | 644,365 |
import torch
def pytorch_scatter(op):
"""Implementation of scatter for pytorch."""
def _impl(x, dim, index, src):
dim = dim.item()
return (torch.scatter(x, dim, index, src),)
return _impl, op.inputs[1:] | 1bf909f92aa344c7bbc7363af09d8f474728d487 | 644,366 |
import os
def convert_path(filepath):
"""Converts the slashes in `filepath` to whatever is appropriate for the current OS.
Parameters
----------
filepath : str
Filepath to be converted
Returns
-------
str
Converted filepath
"""
return os.path.normpath(fil... | a5b1d518d7b329c28f0b8e7e5b4f73b3b260bb9a | 644,367 |
def join_parser(lines, join_str=" ", chars_to_strip=" ;."):
"""return a joined str from a list of lines, strip off chars requested from
the joined str"""
# a str will not be joined
if isinstance(lines, str):
result = lines
else:
result = join_str.join(lines)
return result.strip(... | ecbc21e82b28e7c7cc7f3e2784714410bc4d8572 | 644,368 |
import os
def is_cygwin_binary(path):
"""
Detects if the given binary is located in the Cygwin /bin directory.
:param path: Windows path to the binary.
:type path: str
:returns: True if the binary belongs to Cygwin, False for native binaries.
:rtype: bool
"""
path = os.path.abspath(p... | e6cb212167fd88af7ed623aa0b46824dbbafd30e | 644,369 |
def match_keypoints(optical_flow, prev_kps):
"""Match optical flow keypoints
:param optical_flow: output of cv2.calcOpticalFlowPyrLK
:param prev_kps: keypoints that were passed to cv2.calcOpticalFlowPyrLK to create optical_flow
:return: tuple of (cur_matched_kp, prev_matched_kp)
"""
# 当前帧的角点,状态... | bd05ca28e05c2417cb774ff352ae35ed4d036f5e | 644,370 |
from datetime import datetime
def _get_datetime_for_file(msm_list):
"""
Get the datetime of the last observation that contains no null measurements
"""
# Get last measurement date
msm_list.reverse()
for msm in msm_list:
# Skip any line that contains a null value
if 'null' not i... | b81758ae10434cc148bb1d84b7a533452419b649 | 644,371 |
from pathlib import Path
def default_dataset_location(dataset_name: str) -> Path:
"""
Return the default location of a dataset.
This currently returns "~/.avalanche/data/<dataset_name>" but in the future
an environment variable bay be introduced to change the root path.
:param dataset_name: The ... | 296a5022d7e4f1542265937c104a883b1f075abc | 644,373 |
import sympy
def func_1_expr():
"""
x*sin(x) - 1 = 0
"""
x = sympy.symbols('x')
return x*sympy.sin(x)-1.0 | 6690b24384293e85e2c3b50bc0454b3bb6a26c48 | 644,374 |
import os
import pickle
def load_from_disk(path_to_disk):
""" Load a pickle from disk to memory """
if not os.path.exists(path_to_disk):
raise ValueError("File " + path_to_disk + " does not exist")
return pickle.load(open(path_to_disk, 'rb')) | 944bf9872f507f2c537cc1a77b1f3e1caa2b4af9 | 644,377 |
import json
import base64
def translate(store: dict, grib_url: str) -> dict:
"""
Translate our representation to a Kerchunk index file.
"""
refs = {}
for k, v in store.items():
k2 = k.split("/")[-1]
if k2 in {".zmetadata", ".zarray", ".zattrs", ".zgroup"}:
refs[k] = v.d... | 20de504bc27fb10efc1e5086b809d24cd40351c2 | 644,378 |
import hashlib
def generateMD5(str):
"""工具函数:md5编码"""
hl = hashlib.md5()
hl.update(str.encode(encoding='utf-8'))
return hl.hexdigest() | f6ad04ca13df67b8392844fc19abd154cb94799e | 644,379 |
import os
def check_dep_format(deps):
"""Check format of dependencies"""
assert isinstance(deps, list), f'deps is not a list'
ndep = len(deps)
for i in range(ndep):
# Each tuple must have 3 elements
assert len(deps[i]) == 3, f'deps[{i}] does not have size 3'
# Type of each elem... | fd869f80960055554303cd10f7a3b22bbd808607 | 644,380 |
def eliminateExistingImages(conn, candidate, detections, detectionsWithImages):
"""
We'd really like to avoid requesting images that we already have.
"""
imagesToRequest = []
for row in detections:
imageId = row['imageid']
ippIdet = row['ipp_idet']
if '%d_%s_%d_%d' % (candidate, row[... | 2dfee95785851bb52c1a3c7029ababe7a6c7a87c | 644,381 |
def get_km_user_image_upload_path(km_user, imagename):
"""
Get the path to upload the kmuser image to.
Args:
km_user:
The km_user whose image is being uploaded.
imagename (str):
The original name of the image being uploaded.
Returns:
str:
The... | 01b350177f9d605b508debc5c391964dffcaf5e1 | 644,382 |
def _generate_err_msg_for_nested_keys(err_msg, *args):
"""Organize error messages for system defined parameters."""
err_dict = {}
for name in args[::-1]:
if not err_dict:
err_dict.update({name: err_msg})
else:
err_dict = {name: err_dict}
return err_dict | ad977c289d89af650c694ce3711462d8891c3aab | 644,383 |
import string
import random
def noise_list(n):
"""
Return a list of n ``noise'' passwords, to get better coverage of lengths and character
"""
chars = string.ascii_letters + string.digits + string.punctuation
nchars = len(chars)
L = [ ]
for i in range(n):
w = [ ]
k = rand... | bdefa8a5c4944453d92caa01b232f302e5a274ff | 644,385 |
def peak(lst: list[int]) -> int:
"""
Return the peak value of `lst`.
>>> peak([1, 2, 3, 4, 5, 4, 3, 2, 1])
5
>>> peak([1, 10, 9, 8, 7, 6, 5, 4])
10
>>> peak([1, 9, 8, 7])
9
>>> peak([1, 2, 3, 4, 5, 6, 7, 0])
7
>>> peak([1, 2, 3, 4, 3, 2, 1, 0, -1, -2])
4
"""
# mid... | 59b6feeb91324a6caeb721756a778f52510f5c03 | 644,386 |
import json
import subprocess
def storage_get(attribute=None, storage_id=None):
"""Get storage attributes"""
_args = ['storage-get', '--format=json']
if storage_id:
_args.extend(('-s', storage_id))
if attribute:
_args.append(attribute)
try:
return json.loads(subprocess.chec... | 6784c2d811cd0f4078c1adfdc5c9b8f564464bae | 644,387 |
from typing import Any
from typing import Dict
def set_meta(instance: Any, **meta) -> Dict[str, Any]:
"""
Updates object pjrpc metadata.
"""
if not hasattr(instance, '__pjrpc_meta__'):
instance.__pjrpc_meta__ = {}
instance.__pjrpc_meta__.update(meta)
return instance.__pjrpc_meta__ | f82192ef273bd637e61835bb5f4dd7d4613db1ea | 644,388 |
def wire(nodeData, strData, mayDropOccur=False):
"""Utility deserialize function
fill Node reference across provided dictionary on Node objects
using Node identifiers stored in 2nd paramter
return the root of corresponding tree
"""
root=None
for nKey, nObj in nodeData.items():
... | 7fdc0a4ce1ce525c564b4b32f25110bb2a31e1f4 | 644,389 |
def get_country_lat_lon_extent(country):
"""
See https://data.humdata.org/dataset/bounding-boxes-for-countries/resource/aec5d77d-095a-4d42-8a13-5193ec18a6a9
Args:
country:
Returns: longitude(left) longitude(right), latitude (bottom), latitude(top)
"""
#
# 'mexico', 'south_africa', ... | d6e5d5c833f33244ee1e02b1b1aafbcad7f836a1 | 644,390 |
from pathlib import Path
import re
def test_versions(run):
"""Test versions.
config.json - contains the HASS addon version
Dockerfile - installs the specific sunsynk library from pypi
setup.py - sunsynk library on pypi
"""
def _get_version(filename, regex):
txt = Path(filename).r... | ad5bb7751272f9a62295e4526540aad6ce92a345 | 644,391 |
import hmac
import hashlib
import binascii
def _generate_signature(sig_base_string, signing_key):
"""
:param sig_base_string: result of _generate_sig_base_string
:param signing_key: result of _generate_signing_key
"""
digest = hmac.new(signing_key.encode('ascii'),
sig_base_st... | 3aacd17d8f8d0753664f1c638fabf8eeaf3fdf5b | 644,392 |
import torch
def compute_variance_treatment_effect(reward_vector, s_prime_p, s_prime_q, s_prime_obs=None):
""" Compute the variance over batch of the treatment effects """
if s_prime_obs is not None:
# In the CF case, the sampled next state under the physician policy is observed by definition.
... | cdfefd24647a3c6673bb386d2fd6add578781ccb | 644,393 |
def hdu_get_time(hdu, time_format='bmjd'):
"""
Will be used as a key function for the list.sort() or sorted() functions.
Example,
hdus.sort(key=hdu_fits_by_time)
where hdus is a list of HDU objects, will call hdu_by_time() on each element
in the list, and then sort the elements according t... | d51f06b584eb2f26ede7a002eb44dd65e331bfbd | 644,394 |
from colorama import Fore, Style, init
def print_dependencies_check(data_string: str) -> str:
"""
Prints the results of the dependencies check
"""
try:
init()
start_ok_color = Fore.GREEN
start_fault_color = Fore.RED
stop_color = Style.RESET_ALL
except ImportError as... | 45bf89721578c4ec4b3c05a11e3db527bb2854d7 | 644,395 |
def title_case(f_name, l_name):
"""
Take a first name and last name and format it
to return the title case version.
"""
if f_name == "" or l_name == "":
return "You didn't provide valid inputs"
f_name = f_name.lower()
l_name = l_name.lower()
f_name_T = ("{:s}{:s}".format(f_name[... | d8d187f8ab9dd278333027c5e42b912aa949b9b5 | 644,396 |
import random
def shuffle_filter(seq):
"""
This shuffles the sequence it is applied to.
'tis a failure of jinja2 to not provide a shuffle filter by default.
"""
try:
result = list(seq)
random.shuffle(result)
return result
except:
return seq | 51b24ecf2c969095e69871d6ae48fa7e536946c9 | 644,397 |
def is_nt_arc_present(rtn, nt_arc_label):
"""
Check if rtn contains nonterminal arc with label nt_arc_label.
:param rtn: RTN FST object
:param nt_arc_label: Nonterminal arc label
:return: Boolean
"""
nt_arc_label = int(nt_arc_label)
for state in rtn.states:
for arc in state.arc... | a51ce978f00445e11c8a91d6e51d722838729085 | 644,398 |
import heapq
def largest_export_versions(n):
"""Creates a filter that keeps the largest n export versions.
Args:
n: number of versions to keep.
Returns:
A filter function that keeps the n largest paths.
"""
def keep(paths):
heap = []
for idx, path in enumerate(paths):
if path.export_... | 7bdf48e894c7eaf7256d23b81e76d2e486e89289 | 644,399 |
def build_extracted_list(input_list, subinterval):
""" A utility function to extract a number of elements from a list, leaving only a certain subset.
Generates a new list with just the subset. Creates the subset by specifying a sub-interval.
:param input_list: The list to be extracted
:type input_l... | 8e9bf9c9ac407a7976d4ec3a16f1dd36aed8af48 | 644,400 |
def subject_destroy(client, subject_id):
"""Destroy the subject or raise if it does not exist."""
return client.subject_destroy(subject_id=subject_id) | 71f531cdf64f0758cad719022e0fac6bc08a0afa | 644,401 |
from typing import Dict
from typing import Any
def convert_drive_files_old_to_new(old: Dict[str, Any]) -> Dict[str, Any]:
"""Convert data from the original format (which had "answers-cleaned" field) to a clearer format."""
question_id = old["questionid"]
raw = old["raw-original-answers"]
clusters = {
... | 32189bbda13a129306f0d4432350e686f587f6ff | 644,402 |
def inclusion_explicit_no_context(arg):
"""Expected inclusion_explicit_no_context __doc__"""
return {"result": "inclusion_explicit_no_context - Expected result: %s" % arg} | 2e0880d3940c961f6ccc2715e7fa300f9b969787 | 644,403 |
def first_help_calculate_lp(score, avg_score):
"""
Helper function for scores calculation
"""
score = [x + y for x, y in zip(score, avg_score)]
return score | 48078a84186baee0c6721b04744d7661678c158a | 644,404 |
def measurement_id(measurement_uuid: str, agent_uuid: str) -> str:
"""
Measurement IDs used by Iris
>>> measurement_id("57a54767-8404-4070-8372-ac59337b6432", "e6f321bc-03f1-4abe-ab35-385fff1a923d")
'57a54767-8404-4070-8372-ac59337b6432__e6f321bc-03f1-4abe-ab35-385fff1a923d'
Measurement IDs used by... | 95a9c98213542b8ad21f0bbf8c015f584e9c8822 | 644,405 |
import os
def _split_all_parts_of_path(path):
"""
Splits all parts of a path. For example, the path
'../build/lib.linux-x86_64-3.8/Module/Submodule/lib.so'
will be split to the list
['..','build','lib.linux-x86_64','Module','Submodule','lib.so']
:param path: A file or directory pat... | 4e9d138e9bc47c4552a93b768a945b67d3f274e9 | 644,408 |
import os
import requests
def fetch_page(url, params):
"""
Returns a cached agency processing time page if it exists,
otherwise the function creates a cache and returns the html.
"""
filename = "html/{0}_{1}_timedata.html"
filename = filename.format(
params.get('agencyName', "all"), p... | afac00f1e73af7e7e742fee676bbea64b2a0d65a | 644,409 |
def reverse_letter(string: str) -> str:
"""This function returns reversed string with alphabetic characters."""
my_string = ''
for item in string:
if item.isalpha():
my_string += item
return ''.join(map(str, list(reversed(my_string)))) | af773bf79953184f926ec96eaefe6bfc7d6cb85d | 644,411 |
import re
import os
def indent(instr, nspaces=4, ntabs=0, flatten=False):
"""Indent a string a given number of spaces or tabstops.
indent(str,nspaces=4,ntabs=0) -> indent str by ntabs+nspaces.
Parameters
----------
instr : basestring
The string to be indented.
nspaces : int (default... | d5a0b26b8d27de9dde54464f331416577028e39a | 644,412 |
def fourier_make_response_real(response):
"""
Turn a frequency filter function into a real one (in the time domain).
Done by reflecting and complex conjugating positive frequency part to negative frequencies.
`response` is a function with a single argument (frequency), return value is a modified fu... | ba2a99e479470027a4890be3d97f9a204607afa1 | 644,413 |
def get_avatar(member):
"""Returns default avatar, if custom doesn't exist"""
if member.avatar_url:
return member.avatar_url
return member.default_avatar_url | 77b442815ac813527a8d19448601e2dcfd8aade7 | 644,414 |
import numpy
def get_npz_keys(filename):
"""Get keys of .npz file
It can be also used to check chainer model's key.
.. admonition:: Example
>>> keys = get_npz_keys('hoge.npz')
>>> print(keys)
"""
with numpy.load(filename) as f:
# import IPython; IPython.embe... | 2b36b7145730de8e90eef4489e346b5b8c312ea4 | 644,416 |
def transform_tone(tone):
"""Transforms keyword `negative`, `neutral` or `positive` into `-1`, `0` or `1`.
:param tone: string representation of tone.
:type tone: str
:return: number representation of tone.
:rtype: str
"""
if 'negative':
return '-1'
elif 'neutral':
retu... | 036a3de752bffd3f97636e132c5ce80aae7ee2c2 | 644,417 |
import math
def calc_bp(pair_list):
"""
calc_bp
"""
c_count = 0.0
r_count = 0.0
for pair in pair_list:
pred_tokens, gold_tokens = pair
c_count += len(pred_tokens)
r_count += len(gold_tokens)
bp = 1
if c_count < r_count:
bp = math.exp(1 - r_count / c_coun... | 9be729d658d536e02670351ce59bd4ab28aadf04 | 644,418 |
def update_param_grid(param_grid, sizes):
"""Update parameters of the grid search.
Args:
param_grid: current grid search dictionary
sizes: dataset.shape
Returns:
param_grid: updated grid search dictionary
"""
if 'h_units' in param_grid.keys():
# NN and simple_linear data
if sizes[1] > 1:
... | 54e40e6349dcacffa042d9a6d697319ff862ba31 | 644,419 |
def tpwv(p,r):
"""tpwvr = tpwv(p,r)
Calculates the total precipitable water vapor for a sounding
Inputs: (all vectors of same length)
p = low-level layer average pressure(s) (mb)
r = water vapor mixing ratio (kg/kg)
Outputs:
tpwv = total precipitable water vapor (cm)
RLT, 010709
"""
tpw = 0.0
n = p.... | ba8f3f9a61736acf0ae40b1492be47ade50d9a4f | 644,420 |
def _add_o_align_bam_parser_options(p):
"""Add bam as output of sorted chain"""
p.add_argument("align_bam", type=str,
help="Output BAM/SAM alignments sorted by coordinate")
return p | 7aca98e4b7c87999c50d4b5fb7ed6dcad2635304 | 644,421 |
def polynomial_mul_polynomial(a, b):
"""
Multiplication function of two polynomials.
:param a: First polynomial.
:param b: Second polynomial.
:return: The result of multiplication two polynomials
"""
number_type = type(a[0]) if a else type(b[0]) if b else float
len_a, len_b = len(a), len... | 80f3755e59f263460f1ef20d1521ca777de2169c | 644,422 |
import os
def get_item_info(item_file):
"""
get item info[title, genres]
:param item_file: iteminfo file
:return: a dict, key: itemid, value: [title, genre]
"""
if not os.path.exists(item_file):
return {}
fp = open(item_file, 'r',encoding='utf-8')
item_info = {}
for line in... | 12c7071c136f90d7bdfa4b199e56998ca102d235 | 644,423 |
import sys
def setup_py(*args):
"""Format the command to build/install the babelized package.
Returns:
list of str: The build/install command.
"""
return [sys.executable, "setup.py"] + list(args) | 408de146b9a89e601fd33ec2c1928e1b8bf13633 | 644,424 |
import torch
def context_collate(lst):
""" collate function to integrate ContextDataset with PyTorch DataLoader """
srcs, tgts, masks = [], [], []
for src, tgt, mask in lst:
srcs.append(src)
tgts.append(tgt)
masks.append(mask)
srcs = torch.stack(srcs)
tgts = torch.stack(tgt... | 643fb2cdb36275bfb77b75b6e6f4a2d2abb9906d | 644,425 |
def normalize_GSC_weights(weights_dict, rooted_tree):
"""
This is a novel (I believe) normalization scheme that I came up with to re-scale
GSC weights. It simply divides the weight for each terminal by the overall depth of that
terminal and therefore can/should(?) be thought of as a % independence.
... | 64cd87c020b376d861c4ff759e6d2e0d671be9ee | 644,426 |
import sys
import traceback
def _capture_error_info():
"""
Capture exception context into a dict.
Valid only if called from 'except' clause.
"""
exc_type, exc_value, exc_tb = sys.exc_info()
return {
'crash_tb': ''.join(traceback.format_tb(exc_tb)),
'crash_exc': traceback.format... | a19f3c41cb10f7ec1bb1ffbfb79dc808524d96dd | 644,427 |
def diff(branch=None):
"""Show the differences between the committed code and the working tree."""
return "I'm different." | 15dc8d79da4bf2f8da8dffde2a9fcb412c46db8a | 644,428 |
def global_user():
"""
A fixture is a function that returns an object
that can be used in the test
"""
user = dict(
first_name="Sebastian",
last_name="Witowski",
email="sebastian.witowski@example.com",
role="customer",
)
return user | 3a2673b83d5147d793bc62c2bc17a5dccc7d342d | 644,429 |
def get_attribute(node_id, runtime_property, deployment_id, rest_client):
""" Get a runtime property for the first node instance of a node in
a deployment.
:param node_id: The ID of a node template in a deployment.
:type node_id: str
:param runtime_property: The key of a runtime property.
:type ... | ccdcf619f6136f8889c44183594b58ab0a318745 | 644,430 |
def annualized_vol(r, periods_per_year):
"""
Annualizes the volatility of a set of returns
We should infer the periods per year
"""
return r.std() * (periods_per_year ** 0.5) | fbc971200b851e3e0217be3e79b569839e7071c4 | 644,431 |
def forcibly_purge_java_script_memory() -> dict:
"""Simulate OomIntervention by purging V8 memory."""
return {"method": "Memory.forciblyPurgeJavaScriptMemory", "params": {}} | 3576f6a2943d356b826b91fa676e27fba9c002ce | 644,432 |
def kvret_get_constructed_history_and_golden_response(usr_utterances, sys_utterances):
"""
This function construct the reversed order concat of dialogue history from dialogues from users and system.
as well as the last response(gold response) from user.
@param usr_utterances:
@param sys_utterances:
... | 59d0e31393762a070945b945f99c967411ae04f3 | 644,433 |
def _filter_points(df, labels, label):
"""Returns all rows with the specified label (using last column in df)."""
return df[df.iloc[:,-1]==label] if len(labels) > 1 else df | 545b469ddf040836d5c66f62cf18dc23989df35a | 644,435 |
import hashlib
def _HashFileHandle(fh):
"""sha1 of a file like object.
Arguments:
fh: file handle like object to hash.
Returns:
sha1 as a string.
"""
hasher = hashlib.sha1()
try:
while True:
data = fh.read(4096)
if not data:
break
hasher.update(data)
finally:
f... | feee252b4ed3eb1dcbe531eafe002168458b079b | 644,436 |
def aztec_tonalpohualli_name(date):
"""Return the name field of an Aztec tonalpohualli
date = [number, name]."""
return date[1] | 13a36db7be63ec29ea2900e02fdd65e5cc362019 | 644,438 |
def _classify_rec(rec):
"""Determine class of variant in the record.
"""
if max([len(x) for x in rec.alleles]) == 1:
return "snp"
else:
return "indel" | 8d30bbcb0eb366056f0643e911a09a991493c333 | 644,439 |
def arg(*args, **kwargs):
"""Argument packaging function for command decorator"""
return ([*args], kwargs) | 8dcc7df1b574ae486c0a51fe038d624117d01170 | 644,440 |
import os
import json
def load_config():
"""
Loads a JSON configuration file
:return: Parsed json file
"""
cwd = os.path.dirname(__file__)
config_file = os.path.join(cwd, 'bot-config.json')
config = {}
if os.path.isfile(config_file):
with open(config_file, 'r') as f:
... | 31ad92f5a4ca7026356ccd552b1ec74971ad77b2 | 644,441 |
def is_last_best(name, history, min_delta):
"""Checks whether the last element is the best score so far
by taking into account an absolute improvement threshold min_delta."""
if len(history) == 1:
# If first validation, return True to save it
return True
new_value = history[-1]
# b... | 085e9f8765ee801c0091e05101bcac45a5f0574e | 644,442 |
def curv(c1,c2,x1,x2,x3,de):
"""
Evaluates empirical curve fits used in the computation of the Vmd, sigma_T-, and sigma_T+
for estimating time variability effects as a function of the climatic region, as described
in equations (5.5) through (5.7) of of "The ITS Irregular Terrain Model, version 1.2.2:
... | a9acf0efa48fafc78c25321bd9a3f305bdb0344c | 644,443 |
def leiaInt(msg='', dado='Número', f=False):
"""
Um input que só aceita e continua a execução caso receba um número inteiro
:param msg: Mensagem que será exibida antes de pedir o input
:param dado: o tipo de valor lido para personalizar a mensagem de erro - "[!] 'dado' inválido! Digite novamente."
... | 0979f36c1b8a4cee4fc88575ab6494485a8e2123 | 644,445 |
import math
def is_heptagon(x):
"""
Checks if x is a heptagon number
"""
n = (3 + math.sqrt(40*x + 9))/10
return(n == round(n)) | 9c23cb2c4e754d6ff4d7b22e0c5c5260507b9089 | 644,446 |
def map_list(*args,**kwargs):
"""Eager version of map, returns list. May be slower or more resource hungry than builtin genrator/lazy version."""
#return list(map(func, oplist))
return list(map(*args,**kwargs)) | 15ff49df044cb5192605c88ffab20358bb4818d5 | 644,447 |
from typing import List
from typing import Dict
from typing import Any
def prepare_input_layer(
input_layer_type: str,
feats_dim: int,
blocks: List[Dict[str, Any]],
dropout_rate: float,
pos_enc_dropout_rate: float,
) -> Dict[str, Any]:
"""Prepare input layer arguments.
Args:
input... | 47e0bc7db9fb53caada243f84a0aed179de92e8d | 644,448 |
def taxidToLineage(taxid, taxdump, classificationLevel):
"""
Recursively converts an NCBI taxid to a full phylogenetic lineage.
Args:
taxid: The taxid to look up.
taxdump: The NCBI taxonomy dump as parsed by parseTaxDump
classificationLevel: The level of classification to save into ... | ce35695afa45a4f543a81d743cf37d49e0d10402 | 644,450 |
def discrete_distribution(data):
"""
Build a discrete distribution in form of { point : probability }
:param data: numpy.array, (data points, dimension)
:return: dict of distribution
"""
distr = { }
n = data.shape[0]
for point in data:
if tuple(point) in distr:
distr[... | 494e3bcb8552419d4303732a0f4e8f3c6d6e36ef | 644,452 |
import copy
import torch
def average_weights(w, arch_personalization):
"""
Returns the average of the weights.
"""
w_avg = copy.deepcopy(w[0])
arch_normal_result = {}
arch_reduce_result = {}
for key in w_avg.keys():
for i in range(1, len(w)):
w_avg[key] += w[i][key]
... | aff81c2c8cf6da0b6b0f6b3617d0fbccb6a90019 | 644,453 |
def _get_question_end_index(input_ids, sep_token_id):
"""
Computes the index of the first occurance of `sep_token_id`.
"""
sep_token_indices = (input_ids == sep_token_id).nonzero()
batch_size = input_ids.shape[0]
assert sep_token_indices.shape[1] == 2, "`input_ids` should have two dimensions"
... | fcdc7749fc42804ae78f4f1d906a867307c95f6b | 644,454 |
def round_repeats(repeats):
"""Round number of filters based on depth multiplier."""
return int(repeats) | b7ea8e957b40e4c236b01933d272ac37b760a46b | 644,455 |
def get_filename(pathname, split_char='/'):
"""
:param pathname: path name
:param split_char: Path interval character
:return: file name
"""
pathname = pathname.split(split_char)
return pathname[-1] | 11bead040c84c105ce0c0c4dc354ef04400e1b57 | 644,456 |
from typing import List
def to_indexes(input_range: str) -> List[int]:
"""
Takes a string representing some indexes and returns a list of integers containing the indexes.
>>>
>>> to_indexes('2, 5-8, 21')
[2, 5, 6, 7, 8, 21]
>>>
:param input_range: str
:return: List[int]: A list contai... | d04038141fe3fb12abf2027dc7436b875105a545 | 644,457 |
import os
import itertools
def make_file_offset_lookup(filenames):
"""Create a lookup table to convert between character offset and line
number for the list of files in `filenames`.
This is a dict of the cumulative sum of the line lengths for each file.
"""
lookup = {}
for filename in filen... | 14b2dde3b36a474f0c9fc1ccd821dccd2a7b25f5 | 644,458 |
def cache_clear_mutation(dataset_id):
"""Update the draft HEAD reference to an new git commit id (hexsha)."""
return {
'query': 'mutation ($datasetId: ID!) { cacheClear(datasetId: $datasetId) }',
'variables': {'datasetId': dataset_id}
} | 4a2297cd4d5d78335999e4e88eb9dc1b1cae5fad | 644,459 |
def version_tuple(v):
"""Creates a version tuple from a version string for consistent comparison of versions.
Conversion to tuples is needed because version '2.12.9' is higher then '2.7.8' however::
>>> '2.12.9' > '2.7.8'
False
Instead we need:
>>> version_tuple('2.12.9') > version_tuple('2.... | b665d5d0cf4bf9539e1b804adfcc1f74e73f8e0f | 644,460 |
def parse(filename):
"""Parse the input file to form two digraphs: one showing
which bags are able to be contained in which and the other
showing which bags contain what numbers of which other bags.
"""
parents = dict()
children = dict()
with open(filename, "r") as f:
lines = f.read... | 9dfc85809d644a813ef5e45f995f973eb54e1de8 | 644,461 |
import struct
def read_1(stream):
""" read 1 byte from stream """
return struct.unpack('<B', stream.read(1))[0] | 5208fdf0ede3d615d7d9dd7172f09a0be91c67d9 | 644,462 |
import torch
def collate_fn(data):
"""Pad the sequences.
This function will be used to pad the sessions to max length
in the batch and transpose the batch from
batch_size x max_seq_len to max_seq_len x batch_size.
It will return padded vectors, labels and lengths of each session (before padding)
... | 9577998d883233aea8d6cb6026b3e2c7892aa5a5 | 644,463 |
import os
def get_req_version(module=None):
"""
Read the required version of the specified module from the requirements file
:param str module: the module to be checked
:return dict | None: the required version and name of the requested module
"""
reqs_file = os.path.join(os.path.dirname(__fi... | e37620a79de6c9291f79fad90771351314e7dcb3 | 644,464 |
def points_unique(coordinates):
""" Remove duplicate points from point list. """
unique_coordinates = []
for c in coordinates:
already_in_list = False
for uc in unique_coordinates:
if c == uc:
already_in_list = True
if not already_in_list:
uniq... | 4b76690fb81edec4fc72c6ebf8cd3ffb6e15cbe0 | 644,465 |
def get_sphinx_build_command(project):
"""Builds the sphinx-build command using project properties.
"""
options = ["-b %s" % project.get_property("sphinx_builder"),
"-c %s" % project.expand_path(project.get_property("sphinx_config_path")),
project.expand_path(project.get_proper... | 13a770deb39149a02f283ed90615ae686fedb96e | 644,467 |
def get_bollinger_bands(response_df):
"""Function that returns the bollinger bands for the exchange rate in question."""
response_df['30 Day MA'] = response_df['Adj Close Price'].rolling(window=20).mean()
response_df['30 Day STD'] = response_df['Adj Close Price'].rolling(window=20).std()
response_df['Up... | df89d3f42d7428b28141058d5386ac02a1464f6a | 644,468 |
import torch
def collate_list(vec):
"""
If vec is a list of Tensors, it concatenates them all along the first dimension.
If vec is a list of lists, it joins these lists together, but does not attempt to
recursively collate. This allows each element of the list to be, e.g., its own dict.
If vec i... | a5d272fcc651a6dcbfd58d51f21e2013a4c4bfe2 | 644,469 |
def invert_dictionary(dictionary):
"""
Invert a dictionary
:param dictionary:
:return inverted_dictionary:
"""
inverted_dictionary = dict()
for k, v in dictionary.items():
inverted_dictionary[v] = k
return inverted_dictionary | dde29094a0d3d6bf97a0f943f3339aaba49dec58 | 644,471 |
def _accuracy(pred_data, ref_data):
"""compute sentence-level accuracy"""
pred_size = len(pred_data)
ref_size = len(ref_data)
if pred_size <= 0 or ref_size <= 0:
raise ValueError("size of predict or reference data is less than or equal to 0")
if pred_size != ref_size:
raise ValueErro... | 129149aa53ecd0673fe74ff7c7731ed4491f8e6b | 644,473 |
import argparse
def get_args():
""" gets args and returns them
Input:
- command line args & options
Output:
- args namespace
"""
parser = argparse.ArgumentParser(description='Simulate combat between critters')
parser.add_argument('critters',
nargs='*',
... | 30408efe4733123b0d85fc7dbb78b18a97aa6031 | 644,474 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.