content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
from core.profile import Profile
from core.yml import write_yml
from core.exceptions import ProfileTypeError
def update_profile(profile=None):
""" Take a Profile Object and write his data in type.yml file.
:param: profile: a Profile object
:type: profile: Profile Object
:return: True if s... | 38ddeb72a81e32ff360789a23bb94f2b8b8a0b4e | 3,606,800 |
def time_table(period: str, start_time: str = None) -> Table:
"""Creates a table that adds a new row on a regular interval.
Args:
period (str): time interval between new row additions
start_time (str): start time for adding new rows
Returns:
a Table
Raises:
DHError
... | 56d8bdc3188683eab59d5cdaa293ec74b7b9f751 | 3,606,801 |
def get_topk_typos(pw, k=10):
"""
Returns top k typos of the word pw
"""
pw_key_str = STARTSTR + KB.word_to_keyseq(pw) + ENDSTR
E = sorted(allowed_edits(pw_key_str), key=lambda x: x[1]*len(x[0][0]),
reverse=True)
tt = defaultdict(float)
s = float(sum(x[1] for x in E))
# pr... | dc2449e411411bd75d98a600e56b1fa6a7cb1ab9 | 3,606,802 |
from typing import Optional
from typing import Union
from typing import List
import logging
import csv
def tocsy(bmrb_ids: Optional[Union[str, List[str], int, List[int]]] = None,
input_file_names: Optional[Union[str, List[str]]] = None,
entry_objects: Optional[Union[pynmrstar.Entry, List[pynmrstar... | 55441a5f94ec20b6edf0ab2d59326a4f7d44b8d8 | 3,606,803 |
import tarfile
import pathlib
def _strip_paths(tarinfo: tarfile.TarInfo) -> tarfile.TarInfo:
"""Ensure source filesystem absolute paths are not reflected in tar file."""
original_path = pathlib.Path(tarinfo.name)
tarinfo.name = f"{original_path.name}"
return tarinfo | 06e262f93b3c5d0b8beab36b2ae7320a2464ad5b | 3,606,804 |
def eval_attr(utt, history, next_post, attr):
"""
Given a conversational history and an utterance, compute the requested
sentence-level attribute for utt.
Inputs:
utt: string. The utterance, tokenized and lowercase
history: list of string. This represents the conversation history.
... | 28b94d3b3d442605fd741a2ca33dd322c8cdeccf | 3,606,805 |
from aiida.common.links import LinkType
def get_pseudos_of_calc(calc):
"""Return a dictionary of pseudos used by a given (pw.x, cp.x) calculation.
This returns a dictionary ``pseudos`` that can be set in a builder as ``builder.pseudo = pseudos``.
:param calc: a pw.x or cp.x calculation.
:return: a d... | 928e6b2505a550791fbd41c275d21c94baeafd1d | 3,606,806 |
def get_optim(optimizer_params, model_parameters):
"""
Returns optimizer.
:param optimizer_params: Parameters used to configure the optimizer.
:param model_parameters: Parameters of the network.
:return:
"""
if optimizer_params.kind == "adam":
return optim.Adam(model_parameters, lr=o... | 0e02a1f023cd54efa98065545c6619fcf3276dc1 | 3,606,807 |
def matrix_to_adjacency(source: Matrix) -> Adjacency:
"""Converts adjacency matrix to an adjacency list."""
matrix = source[0]
names = source[1]
name_mapping = dict(zip(range(len(matrix)), names))
raw_adjacency = {
i: [j for j, adjacent in enumerate(row) if adjacent]
for i, row in e... | f927b2551cf6cc346ceaf6fae6c93e4cae12c71a | 3,606,808 |
from scipy import sparse
def combine_adjacency(*structure):
"""Create a sparse binary adjacency/neighbors matrix.
Parameters
----------
*structure : list
The adjacency along each dimension. Each entry can be:
- ndarray or sparse matrix
A square binary adjacency matrix for... | 3cd3404c5cc81c4fc29d1641ff80a48feb7ce8e3 | 3,606,809 |
def find_best_merge(text_dir, ids_files, emb_models, ext='txt', workers=1, processes=1):
"""
Find the best pair to merge
ids_files: list of (id, f) pairs, where ids are in chronical order and
each file f contains a text from one period in consecutive order
emb_models: list of word em... | a439d167f1857b985548d23cd0bdc7eaaa33d114 | 3,606,810 |
def listise(arg):
"""Convert arg into a list.
:Param arg:
This may be a list, tuple, non-string iterable or single value.
"""
return list(iterize(arg)) | 48c75ba8026398725a2516aa9e8e0db2dedfdeda | 3,606,811 |
def sequentially_executed(nb):
"""Return True if notebook appears freshly executed from top-to-bottom."""
exec_counts = [
cell["execution_count"]
for cell in nb.get("cells", [])
if (
cell["source"]
and cell.get("execution_count", None) is not None
)
]
... | d4d6f24f966726c6a6521888bea6fe13f57d1a21 | 3,606,812 |
def router_ref(conn, id_, required=True):
"""Fetch reference dict of Router identified by ID `id_`. Use
OpenStack SDK connection `conn` to fetch the info. If `required`,
ensure the fetch is successful.
Returns: the ref dict, or None if not found and not `required`
Raises: openstack's ResourceNotFo... | f0f38e073b305a5c339c0697b642d74c560d3d4d | 3,606,813 |
def GetCareMap(which, imgname):
"""Returns the care_map string for the given partition.
Args:
which: The partition name, must be listed in PARTITIONS_WITH_CARE_MAP.
imgname: The filename of the image.
Returns:
(which, care_map_ranges): care_map_ranges is the raw string of the care_map
RangeSet; ... | 849c96492014da14433d052f7f8ca49cdad95d0a | 3,606,814 |
def my_func_3(x, y):
"""
Возвращает возведение числа x в степень y.
Именованные параметры:
x -- число
y -- степень
(number, number) -> number
>>> my_func_3(2, 2)
4
"""
if y < 0:
r = 1.0
for _ in range(abs(y)):
r *= x
r = 1 / r
return... | fd9f4d5dc31b530cef2ee495b16c5781f74530b5 | 3,606,815 |
def matrix_to_timeseries(image, matrix, mask=None):
"""
converts a matrix to a ND image.
ANTsR function: `matrix2timeseries`
Arguments
---------
image: reference ND image
matrix: matrix to convert to image
mask: mask image defining voxels of interest
Returns
-------
AN... | 822f01e6306e3b10ee6cf955935725f9a78d0200 | 3,606,816 |
from datetime import datetime
def webfinger(request):
"""An implementation the webfinger protocol (http://tools.ietf.org/html/draft-ietf-appsawg-webfinger-12)
in order to provide information about up and downstream metadata available at this pyFF instance.
Example:
.. code-block:: bash
# curl h... | 5c78467b854f39c0ef597e8a1e913dedf24b938c | 3,606,817 |
def outdated(package, version):
"""Determine if version +version+ of +package+ is supported but not latest.
Returns True if it is; False otherwise.
"""
# versions = all()[package]
# Ignore anything with only 1 version available.
# if len(versions) == 1:
# return False
return numbe... | a55f3784b0781fee15f65ad0601981c4abfbe2b4 | 3,606,818 |
def flavors_ram(nova):
"""Get a dict of flavor IDs to the RAM limits.
:param nova: A Nova client.
:return: A dict of flavor IDs to the RAM limits.
"""
return dict((str(fl.id), fl.ram) for fl in nova.flavors.list()) | 796be050d98dac01a36da15a9de41466ebfbd75d | 3,606,819 |
def backupjob_update(context, backupjob_id, values):
"""
Set the given properties on a backupjob and update it.
Raises NotFound if backupjob does not exist.
"""
return IMPL.backupjob_update(context, backupjob_id, values) | 675dfc9e1ade1fa7abe1d008dcc27f2f3f9b22f7 | 3,606,820 |
def valuetable(items, columns='', enumeration=False):
"""
Common template tag to show a table with columns in detail pages.
:param enumeration: Show enumerations, see ``valuelist`` template tag.
"""
columns = columns.split(',')
letters = alphabet_enumeration(len(items))
records = []
f... | 03a28597746caece75c095137aadff617d02217f | 3,606,821 |
from datetime import datetime
def now():
"""Returns timezoned now date."""
return datetime.utcnow().replace(tzinfo=utc) | 8894674dc1a3d2880ed0c200eda730599fc50afc | 3,606,822 |
import tqdm
import collections
import six
def convert_examples_to_features(examples, tokenizer, max_seq_length,
doc_stride, max_query_length, return_answers, skip_no_answer,
verbose=False, save_with_prob=False, msg="Converting examples"):
"""Loads ... | 44a42ad38123aa0c973a83560899bd6773ee36e0 | 3,606,823 |
def mutate(individual, threshold, genePool):
"""
Mutates a solution by picking a random point along the solution, and
generating a new valid path from that point onwards.
Mutations will depend on a threshold, which is between 0 and 1. This
roughly translates to the likihood of a mutation occu... | 99bad7b745b88813c04f333555857147c30288f5 | 3,606,824 |
import re
def address_to_zipcode(text):
"""
Return the departement number from any text which contains any zip code
"""
for line in text.splitlines():
zipcode_match = re.search(r"(?<!TSA)(?<!BP)(?<!B.P.)(?<!CS)(?:[^\d]|^)(?<!TSA)(?<!BP)(?<!B.P.)(?<!CS)(?P<zipcode>\d{2}\s?\d{3})\s*([^\d\s]|$)"... | 250aa46091b74731977cefe4c6d80a4f4361b729 | 3,606,825 |
def crs(cov_array):
"""Calculate cumulative read sum """
vert_array = np.insert(np.ediff1d(cov_array), [0], 0)
vert_sum_array = np.cumsum(np.absolute(vert_array))
if max(vert_sum_array) == 0:
vert_sum_norm_array = ['NA']
else:
vert_sum_norm_array = vert_sum_array / max(vert_sum_array)
return vert_sum_norm_arr... | 8bd46a447a77acbf8bd13d75c91b838845b430bb | 3,606,826 |
def environment(
combined_challenge,
domain,
task,
log_output = None,
environment_kwargs = None):
"""RWRL environment."""
env = rwrl_envs.load(
domain_name=domain,
task_name=task,
log_output=log_output,
environment_kwargs=environment_kwargs,
combined_challenge=combi... | c9ecefec96ef48c3d048f82e6446a3e24ffe7f1f | 3,606,827 |
import re
def re_cap(*regexes):
"""
Capture first of the supplied regex
:param regexes: list or regex strings
:return: captured string | None
"""
def go(string):
for reg in regexes:
matches = re.search(reg, string)
if matches:
return matches.grou... | 8029a2d475c43b0873e676ba4049e970a2077664 | 3,606,828 |
def Enumerate(evidence):
"""Uses dfVFS to enumerate partitions in a disk / image.
Args:
evidence: Evidence object to be scanned.
Raises:
TurbiniaException if source evidence can't be scanned.
Returns:
list[dfVFS.path_spec]: path specs for identified partitions
"""
options = volume_scanner.Vol... | 9152a038757ec20b5c5538e65896337be8d21f19 | 3,606,829 |
def NgramAnalyzer(minsize, maxsize=None):
"""Composes an NgramTokenizer and a LowercaseFilter.
>>> ana = NgramAnalyzer(4)
>>> [token.text for token in ana(u"hi there")]
[u"hi t", u"i th", u" the", u"ther", u"here"]
"""
return NgramTokenizer(minsize, maxsize=maxsize) | LowercaseFilter() | edc3d66d2bf4ba7eb393d90cafa696d42c2249d9 | 3,606,830 |
from sirepo import uri_router
def authorize(simulation_type, app, oauth_type):
"""Redirects to an OAUTH request for the specified oauth_type ('github').
If oauth_type is 'anonymous', the current session is cleared.
"""
oauth_next = '/{}#{}'.format(simulation_type, flask.request.args.get('next') or ''... | 880994adbedd8e75412518a344bd7b8af240733a | 3,606,831 |
def prepare_create_transaction(*,
signers,
recipients=None,
asset=None,
metadata=None):
"""
Prepares a ``"CREATE"`` transaction payload, ready to be
fulfilled.
Args:
signe... | 894c69e4e13438dc50baae718b603fe50a00a812 | 3,606,832 |
def render_to_json(templates, response_kwargs, context, request):
"""
Generate a JSON HttpResponse with rendered template HTML.
"""
html = render_to_string(
templates,
response_kwargs,
RequestContext(request, context)
)
_json = simplejson.dumps({
"html": html
... | 7aae13d13f3588330549450a3c431d086c48ea6e | 3,606,833 |
def SQuAD2(*args, **kwargs):
""" Defines SQuAD2 datasets.
Examples:
>>> train, dev = torchtext.experimental.datasets.raw.SQuAD2()
"""
return _setup_datasets(*(("SQuAD2",) + args), **kwargs) | dcb5ac4815dbb978837ac2b0c9b8fb77d56c24ea | 3,606,834 |
import dateutil
def _DiscardResultsBeforeDate(results, date):
"""Return a list of results that occur after the given date.
Args:
results: Results parsed from a raw JSON file into list of dicts
date: A date of type datetime.datetime
Returns:
List of results whose date_taken value comes after the gi... | 2dbebeece75ff33e53f8c6e0ee24b308338c81e4 | 3,606,835 |
def downloadPage(url, downloadTo, **kw):
"""Request and download it directyl to disk..
Similar to twisted.web.dowloadPage.
Arguments:
url -- A URL str OR an instance of URLPath OR an instance of Request
pathOrStream --
A file path (str) or object (file) to which the respon... | 98a299a7fa5df23e45f8c2c0603a4dfa62c98c59 | 3,606,836 |
from typing import Dict
import json
import os
import requests
def predict_response(request: Dict):
"""Execute a prediction."""
try:
data = json.dumps(request)
headers = {'Content-type': 'application/json'}
url = os.environ.get('MLFLOW_ENDPOINT')
post_response = requests.post(ur... | 0309a27b11c0d9b0b614bd5774d6d4a9098b9b47 | 3,606,837 |
def webhook():
"""Метод обрабатывающий обновления от Телеграма"""
ptb = current_app.ptb
data = request.get_json(force=True)
try:
ptb.logger.debug('Retrieving update object')
update = Update.de_json(data, current_app.ptb.bot)
ptb.logger.debug(update)
ptb.dispatcher.process... | a3f4faf44431a1916b69cc083568a71d1047bd19 | 3,606,838 |
def score2act(score):
"""
Convert the Z-score predicted by PADDLE to a fold-activation value.
Only useful as a rough reference for activation in S. cerevisiae, as the
fold-activation will vary between different experimental conditions.
"""
return 1.5031611623938073**score | 044cf53813623e5427e7bda2e69afba47f435af0 | 3,606,839 |
import os
def download_objects(s3_client, bucket, s3_keys, local_dir, verbose=False):
"""Downloads multiple objects from s3 to a local directory.
Args:
s3_client (obj): a low-level client of AWS S3.
bucket (str): the bucket name.
s3_keys (list[str]): the path to the s3 object along wit... | 9bd3eecadc801c190ed1f5655ef3be3664cac78f | 3,606,840 |
def required(value, context=None):
"""validates that a field exists in the input"""
if value:
return value
if value == 0:
return value
raise ValidationException('This field is required') | af95022bc9960da7678323ecb96120f39ef26b22 | 3,606,841 |
def get_mask_pallete(npimg, dataset='detail'):
"""Get image color pallete for visualizing masks"""
# recovery boundary
if dataset == 'pascal_voc':
npimg[npimg == 21] = 255
# put colormap
out_img = Image.fromarray(npimg.squeeze().astype('uint8'))
if dataset == 'ade20k':
out_img.pu... | 7130945b6a8ba8d1379753e93b1ec9ee9b429ade | 3,606,842 |
def quadratic_max(xs, ys):
"""
Find the maximum from a list, using a quadratic interpolation.
Note: REQUIRES (and `assert`s) that the xs grid is uniform.
"""
delta = xs[1] - xs[0]
assert np.allclose(xs[1:] - xs[:-1], delta), "quadratic_max: not uniform grid!"
ii = np.nanargmax(ys)
if ii ... | 3f9fe5747055e39f94e39f44ec2a6c6bbe06a6e0 | 3,606,843 |
def convert_blackhurst_data_to_gal_per_employee(df_wsec, attr, method):
"""
Load BLS employment data and use to transporm original units to gallons per employee
:param df_wsec: dataframe that includes sector columns
:param attr: attribute data from fba method yaml
:param method: The name of the fba ... | f79503c3ddb597697beac648200359d7d747189d | 3,606,844 |
import urllib
def get_label_like(current_row):
"""Get labels, OBO synonyms (and possibly more) from submitted ontology/IRI pairs"""
global ols_session
anything_useful = []
once = urllib.parse.quote(current_row['iri'], safe='')
twice = urllib.parse.quote(once, safe='')
term_retr_base = 'https:/... | 2e737c089bdf5194988ddef300e6069ee27a9550 | 3,606,845 |
def get_metadata(estimator_name):
"""Get init annotations for estimator.
Parameters
----------
estimator_name : str
Name of estimator
Returns
-------
metadata: dict
"""
annotations = _ALL_ANNOTATIONS[estimator_name]
try:
return {
"parameters": annota... | 9d767f0b55500cc41a8be52b05db7e45544e3d45 | 3,606,846 |
def get_linked_lengths(frames, linker, *args, **kw):
"""Track particles and return the length of each trajectory."""
linked = link(frames, linker, *args, **kw)
return linked.groupby('particle').x.count() | fe0db1aa38db99fbdd9a22c3ce39adc7f7d268ee | 3,606,847 |
def rotate2(degs, header):
"""Return a rotation matrix for counterclockwise rotation by ``deg`` degrees."""
rads = np.radians(degs)
s = np.sin(rads)
c = np.cos(rads)
return np.array([[c*header['CDELT1'], -s*header['CDELT2']],
[s*header['CDELT1'], c*header['C... | ef2cea6c8990a0032eaebcaec528c7c5ad4fa051 | 3,606,848 |
from typing import Dict
import os
def generate_hash(db: Dict[str, str]) -> str:
"""
Create a unique 3 characters long hash for the current directory.
"""
cwd = os.getcwd()
full_hash = string_to_md5(cwd)
my_hash = full_hash[:3]
while my_hash in db.values():
lst = shuffled(list(full_... | 36cddcf2c8f25c3b5b1f9e2321824179fbba07cb | 3,606,849 |
import os
import shutil
def make_saliency_dir(date_time: str) -> str:
"""Make directories for saving saliency map result."""
save_dir = f"./data/saliency_map/{date_time}"
if os.path.exists(save_dir):
shutil.rmtree(save_dir)
os.makedirs(save_dir)
os.makedirs(f"./data/saliency_map/{date_time... | 84a2e493002263385911fb6f9967796e24cfda5e | 3,606,850 |
def restore_project(c):
"""
Restore latest version of project files.
"""
file_name = f'{c.config.data.backup_path}/{c.config.project.name}.last.tar.gz'
result = c.run(f'stat {file_name}', hide=True)
if not result.ok:
print(f'{RED}Could not find project backup: {file_name}{COL_END}')
... | 5c838113f5a8977295a4d1dfe348883a68d5d32d | 3,606,851 |
def import_module(path):
"""
import module from string
:param str funcpath: the string of absolute path a module
"""
try:
if "." in path:
modpath, hcls = path.rsplit('.', 1)
mod = __import__(modpath, None, None, [''])
mod = getattr(mod, hcls)
... | 125b846e489572008708052ab8a14d0fbd4f582e | 3,606,852 |
import time
def train(train_loader, model, optimizer, scheduler, epoch, args, device, streams=None, scaler=None, blackbox=None):
"""training function"""
batch_time = metric.AverageMeter('Time', ':6.3f')
data_time = metric.AverageMeter('Data', ':6.3f')
avg_ce_loss = metric.AverageMeter('ce_loss', ':.4e... | 29ba425bfef3af348c0d533b145360a0fc23656a | 3,606,853 |
def generate_verify_email_url(user):
"""
生成邮箱激活链接
:param user: 当前登录用户
:return: token
"""
s = Serializer(settings.SECRET_KEY, constants.VERIFY_EMAIL_TOKEN_EXPIRES)
data = {'user_id': user.id, 'email': user.email}
token = s.dumps(data)
return settings.EMAIL_VERIFY_URL + '?token=' + tok... | 1c86ea85b32660e85022ce461b9b073d978735aa | 3,606,854 |
def unpooling_3d(voxel_tensor_batch, reuse, name='unpooling_3d'):
"""Unpooling 3D. Only upsamples by a factor of 2 in every spatial dimension.
Args:
voxel_tensor_batch: [batch, x, y, z, channel].
"""
with tf.variable_scope(name, reuse=reuse):
# Use fixed batch size
batch_shape =... | b4acec3f547594770c4fe9884ecfa7cfb34bce24 | 3,606,855 |
import os
import time
def intro():
"""intro screen, self explanatory"""
os.system('clear')
print("\n\n Welcome to the grand game of 'Mushroom Picking'!\n\n")
time.sleep(1)
print("""'Tales border on the thin line between reality and myth' - Mc' Dingus\n\n
You wake up in your wooden shed, t... | 84a4ce483ab714495facd962f6b3e589a36d9f90 | 3,606,856 |
def make_grpc_unary_method(channel, service_name, method_descriptor, symbol_database_instance):
# type (Channel, str, MethodDescriptor, Any) -> Callable
"""Make grp callable on the channel.
Args:
channel: grpc channel
service_name: name of service
method_descriptor: method descripto... | 7d3d6b3708185f7f243756804a2030db12fc1daf | 3,606,857 |
import os
import re
def prepared_test_build_base(request, bitbake_variables, latest_sdimg):
"""Base fixture for prepared_test_build. Returns the same as that one."""
build_dir = os.path.join(os.environ['BUILDDIR'], "test-build-tmp")
def cleanup_test_build():
run_verbose("rm -rf %s" % build_dir)
... | aa80b4b3c5d480dd72505e0887f686d70207f0dc | 3,606,858 |
def log_decorator(func):
""" decorator to capture logging and exceptions """
@wraps(func)
# Use functools.wrap to preserve the function signatures
def log_wrapper(*args, **kwargs):
erp_logger.debug(f'Entering {func.__qualname__}, {args}, {kwargs}')
try:
out = func(*args, **kw... | 10e249745e9382a313c24dedb38ba20410c40045 | 3,606,859 |
def set_crs(gdf, crs):
"""
Set CRS in GeoDataFrame when current projection is not defined.
Parameters
----------
gdf : geopandas.GeoDataFrame
the geodataframe to set the projection
Returns
-------
gdf : geopandas.GeoDataFrame
the ge... | 77fc8f303882116fb450149c61332879fb28f6db | 3,606,860 |
def make_train_graph(target_dist,
model,
batch_size,
eval_batch_size,
lr,
eval_num_samples=1000):
"""Code for the TRS, SNIS, and HIS training loops."""
train_batch = target_dist.sample(batch_size)
eval_batch =... | 2de40d1f7d847a5ad4ec09e1a124a694b4e62df3 | 3,606,861 |
def svn_wc_restore(*args):
"""
svn_wc_restore(svn_wc_context_t * wc_ctx, char const * local_abspath, svn_boolean_t use_commit_times,
apr_pool_t scratch_pool) -> svn_error_t
"""
return _wc.svn_wc_restore(*args) | 5e402322b3930ffb44e278d81d5a8b67ee450239 | 3,606,862 |
from typing import List
from typing import Dict
from typing import Any
def get_enclosed_containers() -> List[Dict[str, Any]]:
"""Return all object definitions that have 'enclosed_areas' whose value is a non-empty list."""
global _ENCLOSED_CONTAINERS
if _ENCLOSED_CONTAINERS is None:
all_defs = get_... | fe6afe40617de4779f218387c85259e75e870954 | 3,606,863 |
def get_format_string_from_puid(puid):
"""Return file format and version info for a PUID or None
:param puid: PUID (str)
:returns: "File format (version)", "File Format", or None.
"""
file_with_puid = File.query.filter_by(puid=puid).first()
if file_with_puid is None:
return None
tr... | a7ace597dd6bb3b137001fb6b88434f0032f7b93 | 3,606,864 |
def dataset_type(dataset):
"""
Parameters
----------
dataset : dataset script object
Returns
-------
str : The type of dataset.
Example
-------
>>> for dataset in reload_scripts():
... if dataset.name=='aquatic-animal-excretion':
... print(dataset_type(datas... | 4a63021ce725c116b0ed23c851da5983df5c79b5 | 3,606,865 |
def orient2d(
point: Point,
projection: Point,
from_vert: Point,
to_vert: Point
) -> float:
"""Calculate the orientation and offset distance of a point from a line
Parameters:
point: point for which we want to determine orientation left or right of a line
projection: point of pr... | da5f92cb7f63901dc7ec5b7b0ffbf67c20d894e6 | 3,606,866 |
def GetDistinguishableNames(keys, delimiter, prefixes_to_remove):
"""Reduce keys to a concise and distinguishable form.
Example:
GetDistinguishableNames(['Day.NewYork.BigApple', 'Night.NewYork.BigMelon'],
'.', ['Big'])
results in {'Day.NewYork.BigApple': 'Day.Apple',
... | 13cc78b172d0ae074fa3bfa3d9ff93f5877c557d | 3,606,867 |
def sabr_receivers_swaption_value(
init_swap_rate,
option_strike,
swap_annuity,
option_maturity,
alpha,
beta,
rho,
nu):
"""sabr_receivers_swaption_value
calculate european reciever's swaption value.
This value is calculated by put-call parity.
... | 95f01a7d05601393715d5427a0a6afcd4266a5b3 | 3,606,868 |
def format_filing_path(**kwargs):
"""
"If at first you don\'t succeed, don\'t try skydiving."
That makes about as much sense as a docstring as the workaround below.
It\'s... horrifying what I\'ve done here.
So lemme splain the what and why.
We want a conf file that is useful for paths and whate... | e61a98762952afc9a815ec8bdfadf2de2586e111 | 3,606,869 |
import random
def randomized_parameter_test(
egg_data: pd.DataFrame,
param: str,
t1: str,
t2: str,
save_pic_flags: dict,
figs_dir: str,
permutation_total: int = 1000,
plot_stuff: bool = False,
verbose: bool = False,
):
"""
Conducts a randomization-based hypothesis test of w... | f86e6f0f6f140afa3fb3922daa77aff926788129 | 3,606,870 |
def Create(environment_ref, flags, is_composer_v1):
"""Calls the Composer Environments.Create method.
Args:
environment_ref: Resource, the Composer environment resource to create.
flags: CreateEnvironmentFlags, the flags provided for environment creation.
is_composer_v1: boolean representing if creatio... | 9c7c258a76e1912a512887ee79f957aab12f1ee6 | 3,606,871 |
def uu_get_industries():
"""
按照行业分类获取行业列表
:param :name: 行业代码, 取值如下:
"sw_l1": 申万一级行业
"sw_l2": 申万二级行业
"sw_l3": 申万三级行业
"jq_l1": 聚宽一级行业
"jq_l2": 聚宽二级行业
"zjw": 证监会行业
:rtype :pandas.DataFrame
:return:index: 行业代码
name: 行业名称... | 56cafe1bc0afbd82a5a7ff3c49d3ffcf90a6b362 | 3,606,872 |
import torch
def load_single_op(model_name):
"""Given a model name, returns a single-operator model in eval
mode as well as an example input."""
model = getattr(single_op, model_name)().float().eval()
input_shape = [1, 3, 224, 224]
input_data = torch.rand(input_shape).float()
return model, inp... | 490eb4a09d00d1f189ffac18549211ab9dac9e48 | 3,606,873 |
import binascii
import re
def humanhexlify(data, n=-1):
"""Hexlify given data with 1 space char btw hex values for easier reading for humans
:param data: binary data to hexlify
:param n: If n is a positive integer then shorten the output of this function to n hexlified bytes.
Input like
'ab\x... | 883323524ecc8b9f55138d290a38666e5c06bac3 | 3,606,874 |
import re
def yes_workload_no_snippet_target_line(patterns, painted_lines, split_text):
"""Find line to use for scan process in yes workload, no code snippet use case"""
faultable_line_list = []
faultable_line_number_list = []
for line_number in painted_lines:
detected_parts_list_line = split... | bcfdee07500c564c3b2bd82e2fefa24533e06e67 | 3,606,875 |
def make_arc_consistent(Xj, Xk, csp):
"""Make arc between parent (Xj) and child (Xk) consistent under the csp's constraints,
by removing the possible values of Xj that cause inconsistencies."""
# csp.curr_domains[Xj] = []
for val1 in csp.domains[Xj]:
keep = False # Keep or remove val1
f... | 12f75686cf18fdb9b976f36c7e985593bc0aaf10 | 3,606,876 |
import sys
def task_batch_local():
"""Run batch mode locally"""
return {
'basename': 'batchLocal',
'actions': ["%s -m surround_tensorboard_example --mode batch" % sys.executable]
} | b578760a2a5732d6c59c92bf674fbee9b7812af0 | 3,606,877 |
from functools import reduce
def deal_edge(the_sample_train, the_dat_edge):
"""
提取出每一个用户的“流出”特征: 向量长度、times之和、times的中位数、最小值、最大值
weight之和、weight的中位数、最小值、最大值,这样就用9个特征提取出了“流出”特征
"""
col_names = (['length', 'unique_count', 'times_sum', 'weight_sum']
+ ['dup_ratio_left', 'dup_ratio_1',... | d21933bcde6ed6cf05090b6b15b2974f3e0299b8 | 3,606,878 |
def encode_pixel(pixel, bit):
"""Encodes given bit in given pixel luma value.
Args:
pixel: tuple representing pixel's rgb/rgba values
bit: bit to encode
Returns:
tuple: tuple representing encoded pixel's rgb/rgba values
"""
pix_ycc = _ycc(*pixel)
sec = pix_ycc[0]
se... | 83c8044ff7b64f7b290826172e13005adc2c4288 | 3,606,879 |
def get_subfiles(root_path, is_recursive=False):
"""
Returns all files (non-directory) in the given root_path.
:param root_path: The path of the folder from which we will begin traversing.
Remember that if this is not a folder, an error will be thrown.
:param is_recursive: If true, w... | 5c20d73f9332a4839bce5e18e546982f9f8f64ed | 3,606,880 |
import os
def make_bin_path(base_path, middle=None):
"""Creates a path to the data binaries."""
if base_path[-1] == "/":
base_path = base_path[:-1]
if middle is None:
base_path = os.path.join(f'{base_path}-bin')
else:
base_path = os.path.join(f'{base_path}-bin', middle)
ret... | 817fe8e9d9d564333b47511ea0675972d0f04fad | 3,606,881 |
import math
def resolveToJamoIndex(syllable):
"""
음절로부터 자보 배열을 생성한다.
:param syllable:
"""
code = syllable.charCodeAt(0) - 0xAC00
choseong = math.floor(((code - code % 28) / 28) / 21)
jungseong = math.floor(((code - code % 28) / 28) % 21)
jongseong = code % 28
def isValid(n):
... | ac65b58e02a5190f087a34db3efb2656726a6c77 | 3,606,882 |
def page_body_class(context):
"""
Get the CSS class for a given resolved URL.
"""
try:
return "url-{}".format(context.request.resolver_match.url_name)
except AttributeError:
return "404" | ec998cc7c4710837944e72130a3e7e761290cdde | 3,606,883 |
from pathlib import Path
def exclude_files(fileset, run_stata):
"""List all files that we know will not get updated or don't want to check:
1) Ignore all files in ``source_data/indiv``
2) Ignore all files in ``models/projections/raw``
3) SITable2.xlsx is created manually
4) ED figures 5, 8, and 9 ... | 66202601b01c51df7c35244fab58f463a5fac4fd | 3,606,884 |
from re import T
from re import M
def get_search_request_filter(folder_ids, subject=None, sender=None, body=None, int_msg_id=None, restriction=None, email_range="0-10"):
"""
Link for Restriction node
https://msdn.microsoft.com/en-us/library/office/aa563791(v=exchg.150).aspx
Link for the FieldURI's
... | 14ba6d398a41bc602cdaf7673ba5f60c9fe19d0c | 3,606,885 |
async def upload_file(
request: web.Request,
upload_token,
uploaded_file
) -> web.Response:
"""Uploading of a specified file from a local computer.
:param request:
:type request: web.Request
:param upload_token: Upload token associated with a given file for Archive uploading as ... | e8b11960dac7fd5bdd7413711a32a6ec1bd7be3f | 3,606,886 |
def hier_softmax(true_dict=None, pred_dict=None,
hier_graph=None, weight_mode="exp",
criterions=None, verbose=0):
""" Returns weighted softmax loss for hierarchical clf results.
Inputs:
* true_dict: dict containing pairs of (classes, preds) for every level
... | 3f611c3a255f2cd6cc7deec9bf26ede829daead7 | 3,606,887 |
def do_full_tree(md_trees, subsystem_id, compact):
"""
Merge each tree in md_trees and generate the full landscape product tree
"""
full_tree = Tree()
node0 = Product('full_' + subsystem_id, # 1 (0 is self)
'Full ' + subsystem_id + ' Tree', # 2
... | 71fe9e06b86d1ca8ed5b51bfe62c2970cdf6c2cb | 3,606,888 |
import os
import yaml
def get_requirements(test_repo: bool = False) -> list:
"""
Lists the pip requirements for the builtin folder modules
"""
output = []
field = "pip-requirements" if not test_repo else "pip-test-requirements"
for node in os.listdir(MODULE_FOLDER):
if node == "__pyca... | 3203956d4d7fba17191f9f1731fa50539ab74eda | 3,606,889 |
def mirror(p, pa, pb):
""" compute the image of p wrt the segment (pa,pb)
Parameters
----------
p : numpy.ndarray
point to image
pa : numpy.ndarray
segment tail
pb : numpy.ndarray
segment head
Returns
-------
M : numpy.ndarray
Examples
--------
... | f739ebced7ab4728b218d0c2e6e8b00de081edca | 3,606,890 |
def list_versions(schema_type):
"""
Lists all current JSON schema versions.
"""
if schema_type == "input":
return list(_input_version_list)
elif schema_type == "output":
return list(_output_version_list)
elif schema_type == "molecule":
return list(_molecule_version_list)
... | e3f0e5165c6229d4d7f29adc99af071d882ad2e4 | 3,606,891 |
import collections
def readUncertainties(root, nodeTag, paramsDict):
"""
Read xml node "Uncertainties" in the input file
@ In, root, xml.etree.ElementTree.Element, root xml element node
@ In, nodeTag, str, node tag that is used to find the node
@ In, paramsDict, dict, paramsDict returned by readPara... | 85d707cdc110f5561028de52a5ab47da57c59d9f | 3,606,892 |
import json
def load_class_map(file_path):
""" Returns class names map. """
if file_path is not None and exists(file_path):
with open(file_path, 'r') as input_stream:
data = json.load(input_stream)
class_map = dict(enumerate(data))
else:
class_map = None
retur... | f5a6b0086b50860cf446ba5457b3a36e71f0b646 | 3,606,893 |
def csvfile_out(csvfile):
"""Returns a function that will write out connections from a {_ConnectionKey->{key->value}}
dictionary (where their keys are the properties of the connection).
The function is used as a callback for writing 'buckets'. Note that prior to using that
function, the passed ... | fc82fb038d6d70ef12f455dcb1bc923b3c02042b | 3,606,894 |
def vstack_maps(obj, nfm):
"""
Stack the feature maps vertically.
"""
assert obj.shape[1] % nfm == 0
return np.vstack(np.hsplit(obj, nfm)) | 279537b34c930bd1bd33bdc8ae686ae8279e312b | 3,606,895 |
def custom_connect(hook_point, module_path, original_connect, *args, **kwargs):
""" Replacement to the connect function of a DBApi2 module. It will
instantiate a connection via the original connect function and proxy it
via CustomConnection defined earlier.
"""
def wrapper(*args, **kwargs):
... | 75224bc76e1849287adc1c68dc7de3a9e76ac1d7 | 3,606,896 |
def CreateHTMLStringBody(pre_HTML_d):
"""
Inputs:
pre_HTML_d: (dict)
MultiCodes_reports_list: (list) Each element is a MC_report_d:
MC_report_d: (dict)
fastq_fp: The path to the fastq file
nReads: i
nOff: d
... | db116bff0d8c15d12121ec57251b75732cb85f40 | 3,606,897 |
from datetime import datetime
def add(investor_id, amount, frequency=TransferFrequency.NOW,
start_date=None, end_date=None):
"""
Add fund to the account
:param investor_id: int - the investor account id
:param amount: float - amount to withdraw
:param frequency: member of lendingclub2.con... | f07912c5d810ae0adb3b8984fcc15cc36a314233 | 3,606,898 |
def determine_next_openstack_release(release):
"""Determine the next release after the one passed as a str.
The returned value is a tuple of the form: ('2020.1', 'ussuri')
:param release: the release to use as the base
:type release: str
:returns: the release tuple immediately after the current on... | 71c06182781a3c6287f2636f2ce9f81489d8f54f | 3,606,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.