content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import pickle
import sys
def run(cmdfile,subsetfile=None, lookupfile=None):
""" Generate TestCases from cmdfile according to the pattern in patternfile"""
#Define the test case pattern
pattern="""class %s(basecase.%sCase):
def setUp(self):
self.obsmode="%s"
self.spectrum="%s"
s... | 6f7da74c06d46c05322d3f45ef3f83ff6adf3179 | 51,900 |
def build(func, target=None, target_host=None, params=None):
"""Helper function that builds a Relay function to run on TVM graph
runtime.
Parameters
----------
func: relay.Function
The function to build.
target : str, :any:`tvm.target.Target`, or dict of str(i.e. device/context
nam... | ab3e450297ef810450aab35cd9a5f9f3915ed7ab | 51,901 |
def handle_response(resp, headers):
"""
return TRUE = HIT, FALSE = MISS
"""
val = resp.getvalue()
head_val = headers.getvalue()
index = head_val.find("X-CACHED-MIDDLEWARE: ")
if index == -1:
return False
response = head_val[index + len(HEADER_STRING)]
return response == "H" | c6670d1ca375949a93a046d7d0baa89de66ca820 | 51,902 |
def from_settings(request):
"""
Set context variables based on settings variables
"""
return {
'ENVIRONMENT_NAME': settings.ENVIRONMENT_NAME,
'ENVIRONMENT_COLOR': settings.ENVIRONMENT_COLOR,
} | ea9b48a4f8b5fca38f4c325910a1c6a9a507fb13 | 51,903 |
from typing import Dict
def count_words(text: str) -> Dict[str, int]:
"""This is a function
to count word frequencies or
to count how many times each unique word occurs in the text.
Args:
text (str): A long string
Returns:
Dict[str, int]: A dictionary with sorted word frequenci... | 59570f77f69648b91837b1011db1a228d868828f | 51,904 |
def output_xml(data, code, headers=None):
"""Makes a Flask response with a XML encoded body"""
resp = make_response(dumps({'response': data}), code)
resp.headers.extend(headers or {})
return resp | 33627bae15ea9a033c4a4fab534effbbf911c009 | 51,905 |
def to_dict(conf):
"""Converts a Config object to a dictionary.
Args:
conf (Config): A Config object
Returns:
dict: A multi-level dictionary containing a representation ogf the configuration.
"""
return conf._xpipe_to_dict() | 6c709e04f1ffb88b5b5563defc2a03fabfafbb1e | 51,906 |
def _recode_default(x, default, out_type):
"""Get right default for recoding"""
if default is None and (
out_type is None or isinstance(_get_first(x), out_type)
):
return x
return default | 291fc8427db7d6009c9bbfd3c2ad8c5b8fc25d39 | 51,907 |
def edge_uniform_weight(edge, goal, slicevars):
"""
Return a uniform view of the edge's log-probability.
:param edge: an edge
:param goal: the goal node (gets a special treatment because there are no slice variables for it)
:param slicevars: a SliceVariable object
:returns: 1/beta.pdf(u_s; a, b)... | 71bf32915375bbf8ecb8a212c50d267f30a3219d | 51,908 |
def add_query_params(url, params):
"""
Inject additional query parameters into an existing URL. If
parameters already exist with the same name, they will be
overwritten. Parameters with empty values are ignored. Return
the modified URL as a string.
"""
def encode(s):
return force_byt... | e84eb70c1d24754592847fd4913186003d21e4b0 | 51,909 |
def np_seq_similarity(seq1, seq2, substMat, normed, asDistance):
"""Computes sequence similarity based on the substitution matrix."""
if seq1.shape[0] != seq2.shape[0]:
raise IndexError("Sequences must be the same length (%d != %d)." % (seq1.shape[0], seq2.shape[0]))
"""Similarity between seq1 and ... | d45e7b7b98c63611aeb1d8d19e0677b568dc9e82 | 51,910 |
def loadkeys(filename):
""" "
load twitter api keys/tokens from CSV file with form
consumer_key, consumer_secret, access_token, access_token_secret
"""
with open(filename) as f:
items = f.readline().strip().split(", ")
return items | 5b8d1fa6810112c6ea2c8a93b336d2fecfc9a417 | 51,911 |
def query_db(query, args=(), one=False):
"""Query the database of the current application.
Return the first row of the result if the optional argument 'one'
is true, or the whole query result if not specified.
"""
cur = get_db().execute(query, args)
rv = cur.fetchall()
cur.close()
retu... | 9152bf81cd73b4dec06266b8e37784b8fac42a43 | 51,912 |
from typing import MutableMapping
def flatten_dict(d: MutableMapping, parent_key: str = "", delimiter: str = "."):
"""Flatten a nested dict into a single level dict."""
def _flatten_dict(d, parent_key="", delimiter="."):
for k, v in d.items():
key = str(parent_key) + delimiter + str(k) if... | 35b338a40bbf00079813037776f93a9a822264db | 51,913 |
def sample_pixels(slide_path, sample_fraction=None, magnification=None,
tissue_seg_mag=1.25, min_coverage=0.1, background=False,
sample_approximate_total=None, tile_grouping=256):
"""Generates a sampling of pixels from a whole-slide image.
Useful for generating statistics or... | 7efcc44f1613d26eb0d2b7562c28ba3469a47fb4 | 51,914 |
import os
def import_yaml_folder(directory: str = '/') -> dict:
"""
Iterates through directory and looks for yaml files,
if one is found, it is imported and stored in a dictionary
with its root filename (without its extension) as the key
"""
yaml_objects = {}
for entry in os.scandir(direct... | 5dcc6ef509a313b5de0f0a9b47412a923a1cffb3 | 51,915 |
def valid_hex(value):
"""Check if the string is a valid hex number representation."""
try:
int(value, 16)
except Exception:
return False
return True | 4037b9103cd3308253f929d0a4cbbe3f37c1c219 | 51,916 |
def _get_webauthn_user_public_key_credential_descriptors(user, *, rp_id):
"""
Returns a webauthn.WebAuthnUser instance corresponding
to the given user model, with properties suitable for
usage within the webauthn API.
"""
return [
PublicKeyCredentialDescriptor(
id=base64url_t... | b3549ca3a161b1325cf0eb294fdce077d03a5270 | 51,917 |
def bert_encoder(s, no_wordpiece=0):
""" Compute semantic vector with BERT
Parameters
----------
s: string to encode
no_wordpiece: 1 if you do not use sub-word tokenization, otherwise 0
Returns
-------
np array in shape of (768,)
"""
if no_wordpiece:
words = s.split(... | c818cfabd8dbaf82b654c5b4f22d522595ae69a4 | 51,918 |
def get_mapvars(mapfile):
"""Read the sugar .map file and return a dictionary
where the key is the variable name and the value is the (start,r0,r1)
where r0 is the first ordinal and r1 is the last. Sugar uses uniary encoding."""
mapvars = {}
with open(mapfile,"r") as f:
for line in f:
... | c149270a4f1a86707b7ee5e2ed437b5736a2a986 | 51,919 |
def split_data(features, objectives, train_ratio):
"""Split data into a fitting and training set"""
assert len(features) == len(objectives)
total_envs = len(features)
training_index = int(train_ratio * total_envs)
X = np.copy(features[:training_index])
Y = np.copy(objectives[:training_index])
... | 00d35746cac588ae21dc7a1a211f3c78faea8670 | 51,920 |
from typing import Dict
import os
def get_connection_args(dbms_config: Dict) -> Dict:
"""Fill "_var"-suffixed configuration items from environment variables"""
if "options" not in dbms_config:
return {}
new_options = {}
key: str
for key, value in dbms_config["options"].items():
if ... | 7ac2f42a80a6d0f9657bf0eb0caf187fc725d27b | 51,921 |
import codecs
def _windows_31j(codec_name):
"""
Windows-31J用の検索関数。
一番近いと思われるShift_JISにマッピングする。
:param codec_name: コーデック名
:type codec_name: str
:return: Windows-31Jが指定された場合はShift_JIS、それ以外の場合はNone
:rtype: codecs.CodecInfo
"""
# Windows-31JをShift_JISにマッピングする
if codec_name.lower()... | 42b93b2b54c6bc3522a88402adc926212ad4bebb | 51,922 |
def delete(server_id, **kwargs):
"""Delete server."""
url = '/servers/{server_id}'.format(server_id=server_id)
return url, {} | ea00798b1f6adb1edc3ea025cec31ec9abdfd2d7 | 51,923 |
import re
def clean_tracklisting(string):
"""Clean tracklisting in track name: 'A1.', 'A2.', etc """
result = re.search(r'^([ABCD]{1}[1234]{0,1}\.\s?).*$', string, re.IGNORECASE)
if result is not None:
tracklisting = result.groups()[0]
string = string.replace(tracklisting, '')
return s... | 553f59de12950dc3e86f451cf263a6646938059f | 51,924 |
def T2_limit(conf_level: float = 0.95, n_components: int = 0, n_rows: int = 0) -> float:
"""Returns the Hotelling's T2 value at the given level of confidence.
Parameters
----------
conf_level : float, optional
Fractional confidence limit, less that 1.00; by default 0.95
Returns
-------... | 3c83f82e1431207e275d179a9c8b08c2421106f1 | 51,925 |
def names_limit(
names: list[str], min: int, max: int = __input_files_max__
) -> tuple[list[str], ErrMsg]:
"""清除 names 里的空字符串,并且限定其上下限。"""
temp = map(lambda name: name.strip(), names)
names = list(filter(lambda name: name != "", temp))
expected = ""
size = len(names)
if min == max and size ... | de83cdcd06ef5dc6b1407ca1f1821c38c519013b | 51,926 |
def return_plot_and_view_data(view_dict: dict, *args, **kwargs) -> tuple:
""" This function will take in a dict with 2 keys 'master' and
'primary_keys' from 'multiple_result_view'
and do the following:
1) clean up the data for unavailable and duplicate keys
2) create and returns the plot
3) calc... | d1c36a1cf20a5035b8126f48b194b665cf7bf236 | 51,927 |
def num_to_emoji(x: int) -> str:
"""Convet int to emoji."""
if x <= 20:
return {
-1: "💣",
0: "🟦",
1: "1️⃣",
2: "2️⃣",
3: "3️⃣",
4: "4️⃣",
5: "5️⃣",
6: "6️⃣",
7: "7️⃣",
8: "8️⃣",
... | a9b14e94f56b33b7f449ee46108303b99612244d | 51,928 |
import warnings
def __generate_permissions_dataframe(_permissions_dict_list):
"""This function converts a list of dictionaries containing space permissions into a pandas dataframe.
.. deprecated:: 2.0.0
The :py:func:`khorosjx.places.spaces.__generate_permissions_dataframe` function should be used.
... | ffd241c2fb948e857a134dcb807f1e8be12c14ba | 51,929 |
def is_in_period(month, period):
"""Return which months fall within a specified group of calendar months.
Parameters
----------
month : int or iterable of ints
One or a series of calendar month numbers [1..12].
period : tuple of ints
Group of calendar month numbers to match against.... | e973f1ec11ea4dc6b87834c75d6374bbbb152635 | 51,930 |
from datetime import datetime
def get_stock_quarterly_features_func(d_interval,d_offset):
""" Generates a function that returns quarterly features for a stock
Args:
d_interval: The data interval as a datetime.timedelta (e.g., 6*TIMEDELTA_QUARTER for 6 quarters of data)
d_offset: T... | 05c54d594f13424c394c6852e7cb9a2fb1e6a074 | 51,931 |
def once(f):
"""Decorator. Defer to f once and only once, caching the result forever.
Users with a functional background may recognize the concept of a `thunk`.
"""
unset = val = object()
def _helper(*args, **kwargs):
nonlocal val
if val is unset:
val = f(*args, **kwa... | 39e900779a6665155fe83770964e509ff88a12c4 | 51,932 |
def get_simulation_results(project_list, enhanced_dataframe, test_size, max_iterations, parallel, priority_queue,
disable_ignore):
"""
Applies the simulation and validation procedures to a project list.
:param priority_queue: True if the development team uses a Priority Queue, fal... | ac9b3faecf8d961b9e07e4ee76e705d617ee35a6 | 51,933 |
def load_configuration(configuration_file_path, parameters_file_path, bundles):
"""Combines the configuration and parameters and build the configuration object"""
mappings = {}
for bundle in bundles:
if hasattr(bundle, "config_mapping"):
mappings.update(bundle.config_mapping)
loader ... | 4ef108e08f7a28f64a24fc8cfab8ccb624833c9d | 51,934 |
import os
def jupy2pdf(src):
"""
"""
try:
des = src.replace(".ipynb",".pdf").replace("Xblog", "Xblog/docs").replace("notebooks", "pdfs")
ccc.note("converting " + str(src) + " to pdf")
if os.system("bash ./convert.sh {} {} Xblog/ref.bib Xblog/template.tplx".format(src, src.replace(o... | 3545938828b0dd4766e1e4e974bb270f53236137 | 51,935 |
def delete():
"""
Delete a user
---
/api/users/delete/me:
delete:
summary: Return your user data.
security:
- APIKeyHeader: []
tags:
- User
responses:
'200':
description: An Access Token API to be used in Boleto Viewer
"""
user = UserModel.get_on... | e81715db34aa152807ecf0801f1b5a5ea00d9a5f | 51,936 |
def get_cached_dirlist(sample_method, path):
"""
get the list of Samples that have already run from a sample_method (illumina or nanopore) and path (prefix/shard)
"""
return list(dirlist.find({"sample_method": sample_method, "path": path}, {"samples": 1})) | 145e0c8303a1d05c272ad5a30a7d6f9ffdef0fc6 | 51,937 |
import ot
import torch
def pairwise_align(
slice1: AnnData,
slice2: AnnData,
spatial_key: str = "spatial",
alpha: float = 0.1,
numItermax: int = 200,
numItermaxEmd: int = 100000,
device: str = "cpu",
) -> np.ndarray:
"""Calculates and returns optimal alignment of two slices.
Args:... | 1aaed9425a1bf5115119f8b0bb8ab31b57d46dd9 | 51,938 |
import re
def normalize_number(text):
"""数字1文字を0に置き換える(桁数は変わらない)"""
return re.sub(r"\d", "0", text) | 386a5ca07bedd0d52b9e06e9cbd8342295b6d77c | 51,939 |
import os
def dict_g2go(file_g2go):
"""Creates a dictionary of type {gene1:[(GO_ID, Evidence, GO_name, category),
(GO_ID, Evidence, GO_name, category), ...], }
:param file_g2go: file with relations gene to GO
:return: dict of type {gene1:[(GO_ID, Evidence, GO_name, category),
(GO_ID, Evi... | c64929e68fd0d18392b515b3726010775f1766a2 | 51,940 |
from typing import Any
def build_get_dictionary_request(**kwargs: Any) -> HttpRequest:
"""Get External Resource as a Dictionary.
See https://aka.ms/azsdk/python/protocol/quickstart for how to incorporate this request builder
into your code flow.
:return: Returns an :class:`~azure.core.rest.HttpReque... | a4f6b0d19b76b5ab456394ed3745e9f0593c7405 | 51,941 |
def gen_anchor(featuresize,scale):
"""
gen base anchor from feature map [HXW][9][4]
reshape [HXW][9][4] to [HXWX9][4]
"""
heights=[11, 16, 23, 33, 48, 68, 97, 139, 198, 283]
widths=[16,16,16,16,16,16,16,16,16,16]
#gen k=9 anchor size (h,w)
heights = np.array(heights).reshape(len(... | 6895e6b262ad9361c4ea8d94db3732ef1c13924e | 51,942 |
def shib_ds_context(context):
"""
Creates a dictionary with information:
* ServiceProvider login handler
* IdPs from cookie
"""
shib_ds = get_context(context.request)
return shib_ds | 952b844bce2fc85777f4ebd4ba8c963dc7f10d3a | 51,943 |
import warnings
def __getattr__(name): # noqa: N807
"""Get attribute."""
deprecated = __deprecated__.get(name)
if deprecated:
warnings.warn(
"'{}' is deprecated. Use '{}' instead.".format(name, deprecated[0]),
category=DeprecationWarning,
stacklevel=(3 if PY37... | 629e1981c0a000e358fcb9d8f55799c5e2302307 | 51,944 |
async def hub_pod(kube_client, kube_ns):
"""Create and return a pod running jupyterhub"""
return await create_hub_pod(kube_client, kube_ns) | b6dbb291a988a351857aa7e41b6e53324d8ecd55 | 51,945 |
import ast
from io import StringIO
import os
def parseLayoutFeatures(font):
"""Parse OpenType layout features in the UFO and return a
feaLib.ast.FeatureFile instance.
"""
featxt = font.features.text or ""
if not featxt:
return ast.FeatureFile()
buf = StringIO(featxt)
ufoPath = font... | 6b30c7ba3324f7f547d7f6806443153905a64419 | 51,946 |
import hashlib
def _hash_file(fpath, chunk_size=65535):
"""
Calculates the md5 hash of a file
:param fpath: path to the file being validated
:param chunk_size: Bytes to read at a time (leave unless large files)
:return: The file hash
"""
hasher = hashlib.md5()
with open(fpath, 'rb') ... | 9f17f13f487f95620ad705a6f2b23d57407e640e | 51,947 |
def GetIcon(name, module=None):
"""
wx.Icon GetIcon(iconName, module=None)
Get an icon from a file, possibly prepending the module's path
"""
name=modPath(name, module)
return wx.Icon(name + ".ico") | 1dec574112375ff7ec6d3a0ac4f438a3135e37dd | 51,948 |
def midpoint(start, end):
"""Find the mid-point between two points."""
x0, y0 = start
x1, y1 = end
return (x0+x1)/2, (y0+y1)/2 | dab5a66b8af759998a295d64ba3711b6e99e4c27 | 51,949 |
def scatterplot(custom_x, custom_y, xlabel=None, ylabel=None, **kwargs):
"""
Custom x-y plotting using VESIcal's built-in plot() function, built on Matplotlib's plot and scatter functions.
Parameters
----------
custom_x: list
List of groups of x-values to plot as points or lines
custom_y: list
List of group... | ca543f9c0e834a9caf353b17005e3056a9d75a3d | 51,950 |
def presale_crowdsale_miletstoned(chain, presale_fund_collector, uncapped_flatprice, presale_milestone_pricing, team_multisig):
"""ICO associated with the presale where funds will be moved to a presale.
We set a special milestone pricing that allows us to control the pricing for the presale participants.
"... | 2ae798f0e28944625fa7724218ab52132a385a20 | 51,951 |
def dict_populate_loop(pattern):
"""
Args:
pattern: array of tokens that represents the tokens.
Returns:
updated_dic: a dictionary that contains all the keywords from docstrings.
"""
updated_dic = {}
for token in pattern:
if isinstance(token, docopt_util.Branch):
... | 81f1d38eba5d1e65721c15d6f9178c8568440c83 | 51,952 |
def visualize_farm(
plane, nr_points, size_x, size_y, title="", ax=None, vmax=False):
"""
Function to plot flow-field around a wind farm.
Args:
plane (2d numpy array): Flow field of wind farm
nr_points (list or np array): List of nr of points in x and y
size_x (int): Size o... | 9c7dfa1bc211b31d5dcdd3b882b5c848a3e8c7a0 | 51,953 |
from typing import Tuple
def oov_rate(
targets: jnp.ndarray,
oov_values: Tuple[int, ...],
mask_values: Tuple[int, ...] = ()) -> MeanMetric:
"""Computes proportion of non masked tokens that are out of vocabulary.
Args:
targets: Target values of shape [batch_size, sequence_length, ...].
oov_val... | 33c35004dfbfab02b4c95d9c73b0c8d447828a19 | 51,954 |
def validation_simple(value, obj=None):
"""
Validates that at least one character has been entered.
Not change is made to the value.
"""
# TODO: Translate
if value is None or len(value) == 0:
return False, value, u'El valor digitado debe tener uno o más caracteres'
return True, valu... | 9b3a503ef36a88c06888a4215a317d175cee6e46 | 51,955 |
def multiprocess_filter_reads(in_dir, alignment_file, readdb, trim=False,
quality_threshold=7, worker_count=1, debug=False):
"""Multiprocess for filtering reads but dont move the files
:param in_dir: input directory with subdirectories assumed to have fast5s in them
:param alig... | fddfee322a743d67f15c2fe59a85066d776d4303 | 51,956 |
import pathlib
def hash_to_path(kind: str, rep: str) -> pathlib.Path:
"""Derive path from content rep hash and create any folder required."""
if kind not in KINDS.values():
raise ValueError(f'unknown {kind=} for {rep=}')
folder = DB_OUT_ROOT / kind / rep[:2]
folder.mkdir(parents=True, exist_ok... | cbe7c25a46c42711d8a77fcc034f5c1191a692fc | 51,957 |
import argparse
import sys
def get_args():
"""Get command-line arguments"""
parser = argparse.ArgumentParser(
description='Rock the Casbah',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('file1',
metavar='FILE',
... | 2859d0f536938d42595090f0fc9321e0c77680bd | 51,958 |
import mimetypes
import os
import base64
def create_message_with_attachment(sender, to, subject, message_text, file):
"""Create a message for an email.
Args:
sender: Email address of the sender.
to: Email address of the receiver.
subject: The subject of the email message.
message_text... | f10d926fbb2cc1676c12e42e227ef31ead5adaf2 | 51,959 |
def mirror_edges(img, psf=3):
"""Given a 2D image, boundaries are padded by mirroring so that
the dimensions of the image are multiples for the width of the
point spread function.
Args:
img (np.array): Image to mirror edges.
psf (int): Size of point spread function in pixels.
Retur... | 1d9d85bf32a3a5cf560c4add866a053057fb5b72 | 51,960 |
def _srg_rhs_old(s, potential, kinetic, potential_weight, weights, flow,
verbose):
"""Old implementation of SRG flow equation.
New implementation is more efficient and reflects actual form better.
Keeping this for documentation and as reference for analytic evaluation of
flow equation ... | c4ee5fdafa7a11c95d3e5d0e3c83058b862a3ba9 | 51,961 |
def compute_taproot_address(pubkey, scripts):
"""Compute the address for a taproot output with given inner key and scripts."""
tap = taproot_construct(pubkey, scripts)
assert tap.scriptPubKey[0] == 0x51
assert tap.scriptPubKey[1] == 0x20
return encode_segwit_address("bcrt", 1, tap.scriptPubKey[2:]) | 709a83f131a7de4bbdaad790a96561074d7cfdae | 51,962 |
def perplexity_w_prior(probabilites, smi, d_prior, remove_end=True):
"""
Compute the perplexity of a SMILES given a list
of probabilities.
probabilites: (list) of probabilities
smi: (str) a SMILES
d_prior: (dict) with keys: SMILES characters,
and value the prior probability to sample
the... | cfb33fa8f031c0c323cb62ca7c1639c97a2c903f | 51,963 |
def plot_model_timing(title, data_sizes, fit_scores, predict_scores, ylim=None):
"""
Generate a simple plot of the given model timing data
Parameters
----------
title : string
Title for the chart.
ylim : tuple, shape (ymin, ymax), optional
Defines minimum and maximum yvalues pl... | 3e59c3e6ee354568ae37366ded944c2646acf152 | 51,964 |
def _get_int64(data, position, dummy0, dummy1, dummy2):
"""Decode a BSON int64 to bson.int64.Int64."""
end = position + 8
return Int64(_UNPACK_LONG(data[position:end])[0]), end | 7f2d8f1939fc20848a1323aaa29210dbeaa39451 | 51,965 |
import click
def set_pin(ctx, pin, new_pin, u2f):
"""
Set or change the PIN code.
The FIDO2 PIN must be at least 4 characters long, and supports any type
of alphanumeric characters.
On YubiKey FIPS, a PIN can be set for FIDO U2F. That PIN must be at least
6 characters long.
"""
cont... | 50a4a64fa22c2b8d416bf65d1bd0e7eb5fb226c1 | 51,966 |
def verify_proof(db_contract, proof, received):
"""This queries the DB to retrieve the heartbeat, state and challenge for
the contract id, and then checks the given proof. Returns true if the
proof is valid. Can also return false if the contract is expired or if
an ip address change has been rejected
... | c0b31202425c8f0ee600e056353386f17cfbacb4 | 51,967 |
import signal
def low_pass_butter4(freqs, tod, fc):
"""4th-order low-pass filter with f3db at fc (Hz).
"""
b, a = signal.butter(4, 2*np.pi*fc, 'lowpass', analog=True)
return np.abs(signal.freqs(b, a, 2*np.pi*freqs)[1]) | df7bc610fd57c4af287bee310175e84868123ab7 | 51,968 |
def get_functions(funcset=None):
""" Return a dict of variables """
c0 = funcset in _DFUNC.keys()
if c0 is not True:
lstr = [
"\t- '{}': {}".format(k0, sorted(v0.keys()))
for k0, v0 in _DFUNC.items()
]
msg = (
"Arg varset must be a valid key to an ... | 5313ffd9768952acd16f9da503679ff537541827 | 51,969 |
from featuretools.entityset import EntitySet
import os
def description_to_entityset(description, **kwargs):
"""Deserialize entityset from data description.
Args:
description (dict) : Description of an :class:`.EntitySet`. Likely generated using :meth:`.serialize.entityset_to_description`
kwar... | 1e01f53293f12117eeab21f9ee5df64cac5aa66c | 51,970 |
import re
def replace_pair(pair, content):
"""
Uses regex to locate a pair.
First element of the tuple is the original error token.
Second element of the tuple is the replacement token.
"""
return re.sub(pair[0], ' {} '.format(pair[1]), content) | 022633d417393959a94629117a1e664709770571 | 51,971 |
def create_optimizer(loss, init_lr, num_train_steps, num_warmup_steps, hvd=None, manual_fp16=False, use_fp16=False, num_accumulation_steps=1,
optimizer_type="adam", allreduce_post_accumulation=False):
"""Creates an optimizer training op."""
global_step = tf.train.get_or_create_global_step()
... | 9a1b889cf6346fc5220c7b7c63dc20363b841765 | 51,972 |
import os
from datetime import datetime
def main(options):
"""
The main function.
"""
logger.info("Comparative Analyzer started")
print("Log file -> logs/CA.log")
ls_files = os.popen("ls -l " + FAAS_ROOT + "/data_archive/*.pkl")
archive_files = []
for line in ls_files:
archive... | 2ea51e22df635b1e40f23fa5913ef810a79795e8 | 51,973 |
def load_positions_from_timepoints_file(path):
"""Load a text file of timepoint pseudo-paths into a list of Positions.
The file is expected to be lines of pseudo-paths of the form:
/path/to/experiment_root/position_name/timepoint_name
where:
/path/to/experiment_root/position_name
is a valid pat... | 0e39b7fd2159e2b664c237920fc378a44d7c9240 | 51,974 |
import pkg_resources
import uuid
import os
def vis_network(
nodes,
edges,
physics="",
height=400,
node_size=25,
font_size=14,
filename="",
config={},
template_file="vis.html",
app=False,
):
"""Render a network with vis.js in an IFrame for use in a jupyter notebook or websit... | f6747f19176f2ad4ec5c74b621a0cfecf2144773 | 51,975 |
def trace_condition_function(condition: ConditionCheckerType) -> ConditionCheckerType:
"""Wrap a condition function to enable basic tracing."""
@ft.wraps(condition)
def wrapper(hass: HomeAssistant, variables: TemplateVarsType = None) -> bool:
"""Trace condition."""
with trace_condition(vari... | 629f6d2a17dd48167da2ce4a04747d35b47d0ee2 | 51,976 |
from datetime import datetime
import requests
def log_me_in(base_url, username=None):
"""
:param username:
:returns cookies
:param base_url:
:return:
"""
add_url = "/geo/init"
if username is None:
user_data = {"userName": "python " + str(datetime.now())}
else:
user_... | ed6e767548a61f0c7086db5fe45b12ac75df5498 | 51,977 |
from niworkflows.interfaces.reportlets.registration import (
SimpleBeforeAfterRPT as SimpleBeforeAfter,
)
from niworkflows.interfaces.reportlets.masks import ROIsPlot
from smriprep.interfaces.templateflow import TemplateFlowSelect
from smriprep.workflows.outputs import (
_fmt, _empty_report, _rpt_ma... | df39d46731213a8313b5eaa1701f302df3d14a94 | 51,978 |
from datetime import datetime
def extract_sitename_date(directory_path,
sitename_location,
datetime_location):
"""Extract sitename and datetime from directory path name.
Parameters
-----------
directory_path : string
A path to the directory ... | 86a2085ba68b234585ef9855da64fa1fdd5459ce | 51,979 |
from typing import List
from typing import Optional
def make_blanks(spans: List[Span], length: Optional[int] = None, fill: str = TokenFunction.OUTSIDE) -> List[str]:
"""Create a list of outside tags that we can populate with tags generated from spans.
Args:
spans: The list of spans that will eventual... | 36e6b225ff55da66c9192c87e6697bf75af842ad | 51,980 |
import argparse
def get_flags():
"""
Argument parser for the script
:return: Object containing flags.
:rtype: Dict
"""
parser = argparse.ArgumentParser()
parser.add_argument(
"--stats",
dest="stats",
action="store_true",
help="Run stats, need to have labels... | 46a8511135130f2de529482eb84c0713a6a28350 | 51,981 |
from datetime import datetime
def month_holidays(year, month):
"""
その月の祝日日、祝日名を返します。
"""
date = datetime.date(year, month, 1)
output = []
while date.month == month:
name = is_holiday_name(date)
if name is not None:
output.append((date, name))
date = date +... | f74bd3f6600b9c82140808ba5061e20a46619b33 | 51,982 |
def collection_test(in_dim1, in_dim2, channels, out_dim):
"""
Return a small collection of models and their names
"""
names = []
for a in range(1, 3):
for b in range(3):
n1 = a * 8
n2 = b * 8
m_str = str(n1)
if n... | d46033bc26acf02a1faacc8b37a314d2b0e58ea2 | 51,983 |
def favourites_add(request):
"""
Function to add recipe to favourites.
This function is used via AJAX.
"""
user = request.user
title = request.POST.get('title')
recipe_id = request.POST.get('recipe_id')
image_url = request.POST.get('image_url')
favourite, created = Recipe.objects.get... | 315773153f1135b7ef677a1c84d3371e9114cb5a | 51,984 |
def read_chain_header(line):
"""
Convenience wrapper to parse chain header information
:param line:
:return:
"""
_, score, tName, tSize, tStrand, tStart, tEnd, qName, qSize, qStrand, qStart, qEnd, chainid = line.strip().split()
return Chain(tName, int(tSize), tStrand, int(tStart), int(tEnd),... | f2d43234d26d61d90995a0cb8ab741734fbf1c4b | 51,985 |
async def get_host_by_slug(host_slug: constr(strip_whitespace=True)):
"""Retrieve a Host object, based on Host slug string, containing:
Host ID, name, slug string, and gender."""
try:
host = Host(database_connection=_database_connection)
host_info = host.retrieve_by_slug(host_slug)
i... | d05319f9e8224584b54210d0a78ee7649d881cca | 51,986 |
import os
import subprocess
import shlex
def python_minifiy(file):
"""Outputs a minified version of the given Python file.
Runs pyminifier on the given file. The minified filename has '.min'
added before the '.py' extension. This function is used to help code
fit under the 4k limit when uploading l... | 457016ab4f4aa9ac8d9d04dae10075114d97bb0d | 51,987 |
def cleanup_text(line: str) -> str:
"""
Args:
line: text line of the opinion
Returns:
text line where not alphabetical characters removed
"""
corrections = {""": "", "&": ""}
line_lower = line.lower()
for wrong, cor in corrections.items():
line_lower = lin... | 3414fb429ea76aabcfc06ae57aca9c2cadfcc96f | 51,988 |
def send_mail(to_mail, mail_subject, mail_body):
"""
Function to send a mail using Sendgrid API
Parameters:
arg1 (string): The recipient's email address.
arg2 (string): The subject of the mail.
arg3 (string): The body of the mail.
"""
message = Mail(
from_email=current_app.con... | c8f2a1796bbb0584ae4370af8af2d7eb7c6b5bbd | 51,989 |
def get_client_rate(client_id):
"""
End point for getting rate for a client_id.
:param client_id: str
:return: http response
"""
# How to get the actual rate from client_id?
# all_clients = get_client_rates()
# if client_id in all_clients:
# return str(all_clients[client_id]['ra... | aef35e034e5d80cc4b2f73c10e89ce9a38c542a1 | 51,990 |
from run4it.api.scripts import script_token_registry_purge as script_func
def token_cleanup():
"""Removes revoked and expired tokens from database"""
return script_func('token_cleanup') | ec2876a20cca14e271b7036ec35b7f64af8e6021 | 51,991 |
import requests
import json
def get_vlans(ip, port, username, password) -> list:
"""Gets device components /restconf/data/openconfig-platform:components"""
data = []
uri = f"https://{ip}:{port}/restconf/data/Cisco-IOS-XE-vlan-oper:vlans"
response = requests.get(uri, headers=headers, verify=False, au... | 72130eac7fb103956e97b9e8dd09e54034f9075e | 51,992 |
import time
import random
import traceback
def _run_work_order_fn(zap_id, work_order_i):
"""
Wrap the function to handle args, kwargs, capture exceptions, and re-seed RNG.
Note: This may run in the sub-process or thread and therefore should not use stdio.
"""
start_time = time.time()
try:
... | 38c2b705fc8a38d04d18670e746c0edb550c6612 | 51,993 |
def head(path, lines=10):
"""
Get the first lines of a file.
Args:
path (str): Path to the file to read.
lines (int): Number of lines to read.
Returns:
:obj:`list` of :obj:`str`: The lines found.
"""
with open(path) as f:
return list(islice(f, lines)) | 829c7c910798e967cea0d40aef43ed21ee4ff421 | 51,994 |
def ntg_collate(data):
"""Creates mini-batch tensors from the list of tuples (src_seq, trg_seq)."""
# separate source and target sequences
src_sent,tgt_sent = list(zip(*data))
# t2i
_inputs = [batch_sentences(src_sent),
batch_sentences(tgt_sent),
]
return _inputs | ea2a9900bdc3e1cdc5dc3889a8c6bfb8d8f232db | 51,995 |
def FnutoFlambda(Fnu, wavelength):
"""
Converts F_nu to F_lambda.
:param Fnu: Fnu [ers/s/cm**2/Hz]
:type Fnu: float or ndarray
:param wavelength: wavelength [AA]
:type wavelength: float or ndarray
:return: Flambda [ergs/s/cm**2/AA]
"""
return Fnu / wavelength / wavelength * C | 78b1775aa391c5cc9441684f109203be0af41ce9 | 51,996 |
import torch
def PSNR(gt, img, drange):
"""
Computes the highest PSNR by affine rescaling of x,
such that the mean squared error to gt is minimal.
:param gt: ground truth
:param img: image
:param drange: data range
:return: PSNR
"""
img = normalize_minmse(img, gt)
mse = torch.... | 69296c1b563371cf4dfc5b8a59bff50f922088b5 | 51,997 |
def get_postgres_connection_url() -> str:
""" Собирает ссылку для подключения к БД и возращает её.
"""
db = POSTGRES_DB
host = POSTGRES_HOST
port = POSTGRES_PORT
user = POSTGRES_USER
password = POSTGRES_PASSWORD
if not all([db, host, port, user, password]):
raise DatabaseSetting... | a637f5a108ec7b1a0f696a41d457d284b2a28eae | 51,998 |
def check_if_string_in_file(file_name, string_to_search): #string checker
""" Check if any line in the file contains given string """
# Open the file in read only mode
with open(file_name, 'r') as read_obj:
# Read all lines in the file one by one
for line in read_obj:
# For each ... | 9cc958279cbfab75273ef122603df378ffa55038 | 51,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.