content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def _print_available_filters(supported_filters):
"""Prints information on available filters and their thresholds."""
widths = (20, 40, 20)
data = [("Filter", "Description", "Threshold Values"),
("------", "-----------", "----------------")]
# this is stupid
for f, (d, t, c) in supported_... | 49a769a27d2a4a0beaba1021821c8d1e551f53eb | 13,600 |
def _get_dates(i, *args, **kwargs):
"""
Get dates from arguments
"""
try:
start_date = kwargs['start_date']
except:
try:
start_date = args[i]
except:
start_date = None
try:
end_date = kwargs['end_date']
except:
try:
... | 708bc0fcc5be80ef3b3008b9569bb14a01c4bace | 13,601 |
def home_page():
"""Shows home page"""
html = """
<html>
<body>
<h1>Home Page</h1>
<p>Welcome to my simple app!</p>
<a href='/hello'>Go to hello page</a>
</body>
</html>
"""
return html | 444833ab61803d1fe52676834e211ac79e770b4e | 13,602 |
def GetPDFHexString(s, i, iend):
"""Convert and return pdf hex string starting at s[i],
ending at s[iend-1]."""
j = i + 1
v = []
c = ''
jend = iend - 1
while j < jend:
p = _re_pswhitespaceandcomments.match(s, j)
if p:
j = p.end()
d = chr(ordat(s, j))
... | 516d7c33bcd1b2237eb482e9722de4552ac79ce2 | 13,603 |
def get_edge_syslog_info(edge_id):
"""Get syslog information for specific edge id"""
nsxv = get_nsxv_client()
syslog_info = nsxv.get_edge_syslog(edge_id)[1]
if not syslog_info['enabled']:
return 'Disabled'
output = ""
if 'protocol' in syslog_info:
output += syslog_info['protoco... | 5c5ea79109b9a9053f95945a7902d9e6322a6ba6 | 13,604 |
from typing import List
def _get_rec_suffix(operations:List[str]) -> str:
""" finished, checked,
Parameters
----------
operations: list of str,
names of operations to perform (or has performed),
Returns
-------
suffix: str,
suffix of the filename of the preprocessed ecg s... | 270a1b3749342d05819eafef3fa5175da393b1ad | 13,605 |
def get_A_text(params, func_type=None):
"""
Get text associated with the fit of A(s)
"""
line1 = r'$A(s|r)$ is assumed to take the form:'
line2 = (r'$A(s|r) = s^{-1}\bigg{(}\frac{s}{\Sigma(r)}\bigg{)}^a '
r'exp\bigg{(}{-\bigg{(}\frac{s}{\Sigma(r)}\bigg{)}^b}\bigg{)}$')
a, b = params... | ec68c49a7912dc5630e3c96a09d667ce52f89914 | 13,606 |
def transform_to_dict(closest_list: list) -> dict:
"""
Returns dict {(latitude, longitude): {film1, film2, ...}, ...} from
closest_list [[film1, (latitude, longitude)], ...], where film1,
film2 are titles of films, (latitude, longitude) is a coordinates of
a place where those films were shoot.
... | e7c6fae73792a828d85db03e794bfb69c7b1fe87 | 13,607 |
def ECGDataQuality(datastream: DataStream,
windowsize: float = 5.0,
bufferLength: int = 3,
acceptableOutlierPercent: int = 50,
outlierThresholdHigh: int = 4500,
outlierThresholdLow: int = 20,
badSegmentThre... | c9c462ec688c102097ccad051cbcc1868d71565b | 13,608 |
def get_numpy_val_from_form_input(input_name):
"""Get a NumPy-compatible numerical value from the request object"""
return get_numpy_val(input_name, request.form[input_name]) | fadfbf106c82088103674e5da5f526e08e2a05ac | 13,609 |
import numpy
def load_model(model, path):
"""Load a the model parameters from a file and set them.
Parameters
----------
model : a :class:`Layer` instance
The model with unset parameters.
path : string
The file with the model parameters.
Returns
-------
a :class:`Laye... | dae27ffc78be7aa7476c645c4f021d4acaef5b44 | 13,610 |
def node_id_at_cells(shape):
"""Node ID at each cell.
Parameters
----------
shape : tuple of int
Shape of grid of nodes.
Returns
-------
ndarray :
ID of node associated with each cell.
Examples
--------
>>> from landlab.grid.structured_quad.cells import node_id... | f089f598cacc4d5ec6885477098dcca741358820 | 13,611 |
def search_media(search_queries, media, ignore_likes=True):
"""Return a list of media matching a queary that searches for a match in the comments, likes, and tags in a list of media"""
# Initialize update message
update_message = print_update_message(len(media))
update_message.send(None)
# Init... | 23ed38496310cc86c4d3d7f8aff4e1d5c61f9d69 | 13,612 |
import os
def validation_plot_thesis(show_plot=True, results_2010=None, results_2011=None, model_run="cosumnes_michigan_bar"):
"""
Hardcoded items because they're for my thesis, not meant for more general use.
:return:
"""
if results_2010 is None:
results_2010 = validate_flow_methods("{}_2010".format(model_ru... | bfe2ee71e008d0beff4c6bee203b04d448e656e1 | 13,613 |
def get_produced_messages(func):
"""Returns a list of message fqn and channel pairs.
Args:
func (Function): function object
Returns:
list
"""
result = []
for msg, channel in func.produces:
result.append((_build_msg_fqn(msg), channel))
return result | b63d9305f3af3e474beb1fb328881123d8f4ece6 | 13,614 |
from pathlib import Path
from typing import Sequence
def find_coverage_files(src_path: Path) -> Sequence:
"""
Find the coverage files within the specified src_path.
Parameters:
src_path (Path): The path in which to look for the .coverage files.
Returns:
(Sequence) The set of .cov... | 53fd9b2d2405ed6fe895718e22cc6b1ddb86f4df | 13,615 |
def get_exploration_summary_from_model(exp_summary_model):
"""Returns an ExplorationSummary domain object.
Args:
exp_summary_model: ExplorationSummary. An ExplorationSummary model
instance.
Returns:
ExplorationSummary. The summary domain object correspoding to the
given... | c6561670f976e28a3869eb89c4be3ba884808da0 | 13,616 |
def get_service(api_name, api_version, scope, key_file_location,
service_account_email):
"""Get a service that communicates to a Google API.
Args:
api_name: The name of the api to connect to.
api_version: The api version to connect to.
scope: A list auth scopes to authorize for the appl... | 6c333f43c5feb5b44128b8f592586804eba68e1e | 13,617 |
from IsabelaFunctions.langlais_coeff import glm as g
from IsabelaFunctions.langlais_coeff import hlm as h
import tqdm
def model_map(lon, lat, alt, comp, binsize = 0.1, nmax = 134, a = 3393.5):
"""
Calculates a map of one component of the crustal magnetic field field model, for a given altitude.
Param... | 9a49e4a1f31180cd7a26f2028c5e45d077103346 | 13,618 |
def parse_command(incoming_text):
"""
incoming_text: A text string to parse for docker commands
returns: a fully validated docker command
"""
docker_action = ''
parse1 = re.compile(r"(?<=\bdocker\s)(\w+)")
match_obj = parse1.search(incoming_text)
if match_obj:
docker_ac... | abe82ae2fe29014b3441889c973a412a536b78f1 | 13,619 |
def get_entities_from_tags(query, tags):
"""From a set of joint IOB tags, parse the app and system entities.
This performs the reverse operation of get_tags_from_entities.
Args:
query (Query): Any query instance.
tags (list of str): Joint app and system tags, like those
created... | 2bc2aa1d12834d9414d66710473aaf8df8ef3fab | 13,620 |
def angle_connectivity(ibonds):
"""Given the bonds, get the indices of the atoms defining all the bond
angles
A 'bond angle' is defined as any set of 3 atoms, `i`, `j`, `k` such that
atom `i` is bonded to `j` and `j` is bonded to `k`
Parameters
----------
ibonds : np.ndarray, shape=[n_bond... | 86c992a1a8ac2d3c6b1fbc5a137ef0734a3079ed | 13,621 |
def BOPDS_PassKeyMapHasher_IsEqual(*args):
"""
:param aPKey1:
:type aPKey1: BOPDS_PassKey &
:param aPKey2:
:type aPKey2: BOPDS_PassKey &
:rtype: bool
"""
return _BOPDS.BOPDS_PassKeyMapHasher_IsEqual(*args) | 8da04f1755e3d2f7d10ad3ecf5ec6b0d00ca5fcb | 13,622 |
import re
def replaceToSantizeURL(url_str):
"""
Take arbitrary string and search for urls with user and password and
replace it with sanitized url.
"""
def _repUrl(matchObj):
return matchObj.group(1) + matchObj.group(4)
# TODO: won't catch every case (But is it good enough (trade off... | c72dc459fae1918641926f2933ea3ff8c71acc38 | 13,623 |
def dms2dd(s):
"""convert lat and long to decimal degrees"""
direction = s[-1]
degrees = s[0:4]
dd = float(degrees)
if direction in ('S','W'):
dd*= -1
return dd | cb76efbf8c3b6a75bcc26593fab81a8ef3e16bbf | 13,624 |
def setna(self, value, na=np.nan, inplace=False):
""" set a value as missing
Parameters
----------
value : the values to set to na
na : the replacement value (default np.nan)
Examples
--------
>>> from dimarray import DimArray
>>> a = DimArray([1,2,-99])
>>> a.setna(-99)
di... | 6ada601dee346d5440a64ffdbf8d2642873bdb08 | 13,625 |
def hbox(*items, **config):
""" Create a DeferredConstraints object composed of horizontal
abutments for a given sequence of items.
"""
return LinearBoxHelper('horizontal', *items, **config) | cdfe16a35c73a2f8406207a0262b4210ce86146f | 13,626 |
def find_columns(clause):
"""locate Column objects within the given expression."""
cols = util.column_set()
visitors.traverse(clause, {}, {'column':cols.add})
return cols | 86b4c866a8fbe20ab1d4b0a34e4940155df00744 | 13,627 |
def _preprocess_data(smiles, labels, batchsize = 100):
"""
prepares all input batches to train/test the GDNN fingerprints implementation
"""
N = len(smiles)
batches = []
num_bond_features = 6
for i in range(int(np.ceil(N*1./batchsize))):
array_rep = utils.array_rep_from_smi... | 3456fe2059e386088d359ec0c2d54dff2d7fac25 | 13,628 |
def linear_activation_forward(A_prev, W, b, activation, keep_prob=1):
"""
Implement the forward propagation for the LINEAR->ACTIVATION layer
Arguments:
A_prev -- activations from previous layer (or input data): (size of previous layer, number of examples)
W -- weights matrix: numpy array of shape (... | 0e4d12142224bfb46af0afb547abe3dde0aa6811 | 13,629 |
import os
import io
def get_version(file, name="__version__"):
"""Get the version of the package from the given file by
executing it and extracting the given `name`.
"""
path = os.path.realpath(file)
version_ns = {}
with io.open(path, encoding="utf8") as f:
exec(f.read(), {}, version_n... | 80cc05e945eabe84c6be38461bd0e446cae93ac4 | 13,630 |
def load_image(image_path, size):
"""
Load an image as a Numpy array.
:param image_path: Path of the image
:param size: Target size
:return Image array, normalized between 0 and 1
"""
image = img_to_array(load_img(image_path, target_size=size)) / 255.
return image | 3d9a790b762f800a222c26578dc0572587b091fb | 13,631 |
import signal
def _signal_exit_code(signum: signal.Signals) -> int:
"""
Return the exit code corresponding to a received signal.
Conventionally, when a program exits due to a signal its exit code is 128
plus the signal number.
"""
return 128 + int(signum) | 050eee98632216fddcbd71e4eb6b0c973f6d4144 | 13,632 |
import csv
def make_template_matrix(msigdb_file, blacklist, checkblacklist=True):
"""
Retrieve all genes and pathways from given msigdb .gmt file
Output:
sorted gene by pathways pandas dataframe. Entries indicate membership
"""
all_db_pathways = []
all_db_genes = []
# Get a set o... | b8068089279dfbe3b3cfc8b16dee016cc0994746 | 13,633 |
def unwrap_key(
security_control: SecurityControlField, wrapping_key: bytes, wrapped_key: bytes
):
"""
Simple function to unwrap a key received.
"""
validate_key(security_control.security_suite, wrapping_key)
validate_key(security_control.security_suite, wrapped_key)
unwrapped_key = aes_key_... | 7720ad8905f6818b1a3fa4132b040560a9ae0dfa | 13,634 |
def checkOwnership(obj, login_session):
"""
This function helps to check if the current logged in user
is the creator of the given category or a given item.
This function return True if the current user owns the category,
otherwise, it will return False.
"""
# the user has logged in at ... | 851d2dafae633ed92698af525b1c717091edb2b7 | 13,635 |
from sys import path
import os
import shutil
def move() -> str:
"""Move a file."""
if not g.ledger.options["documents"]:
raise FavaAPIException("You need to set a documents folder.")
account = request.args.get("account")
new_name = request.args.get("newName")
filename = request.args.get("... | 580ad9d81ce92183ce3066a5326b4c2ce338bd55 | 13,636 |
import logging
def transform_file_name(original_file_name):
"""
Now, this is just whatever I felt like. Whee.
So in this function I could have just used 0 and 1 as my indices directly when I look at the different parts of
the file name, but it's generally better to name these sorts of things, so peop... | daa5b3be0ae7a40c9d20ac4a8aa37c51dec89c89 | 13,637 |
import pandas
def remove_overlapping_cells(graph):
"""
Takes in a graph in which each node is a cell and edges connect cells that
overlap eachother in space. Removes overlapping cells, preferentially
eliminating the cell that overlaps the most cells (i.e. if cell A overlaps
cells B, C, and D, wher... | bd133c5ddd59f950d34ba16fb7bc3ff0215f0cf2 | 13,638 |
def main_page(request) :
"""Renders main page and gets the n (matrix demension number)"""
if request.method != 'POST' :
form = InputForm()
else :
form = InputForm(data=request.POST)
if form.is_valid() :
return redirect('calculator:set_demensions')
context ... | a6131ea837c8d9b986e8579a40ada1f7a0a3bb64 | 13,639 |
def int2fin_reference(n):
"""Calculates a checksum for a Finnish national reference number"""
checksum = 10 - (sum([int(c) * i for c, i in zip(str(n)[::-1], it.cycle((7, 3, 1)))]) % 10)
return "%s%s" % (n, checksum) | f21e66cb917631797d62ecc8ba2728b18d36ae1c | 13,640 |
def COLSTR(str, tag):
"""
Utility function to create a colored line
@param str: The string
@param tag: Color tag constant. One of SCOLOR_XXXX
"""
return SCOLOR_ON + tag + str + SCOLOR_OFF + tag | abe3d9111a30ebb678d1f1a2011d3b8a3ad39a75 | 13,641 |
def get_instance_pricing(instance_types):
"""
Get the spot and on demand price of an instance type
in all the regions at current instant
:param instance_types: EC2 instance type
:return: a pandas DataFrame with columns as
region, spot price and on demand price
"""
all_regions = ... | 62dba0e3c3f46ac460178da0bc4d615869819f83 | 13,642 |
import itertools
async def get_user_groups(request):
"""Returns the groups that the user in this request has access to.
This function gets the user id from the auth.get_auth function, and passes
it to the ACL callback function to get the groups.
Args:
request: aiohttp Request object
Ret... | 9fd62d6f971c871ce290700f3abb7eb467692533 | 13,643 |
def plot_bivariate_correlations(df, path=None, dpi=150):
"""
Plots heatmaps of 2-variable correlations to the Target function
The bivariate correlations are assmebled using both the arithmatic and geometric means for
two subplots in the figure.
Parameters
----------
df: dataframe
path: ... | d5dc7da98228aa7b7865510bd4dcd6531e7049bc | 13,644 |
from torch.utils.data import DataLoader
def create_datastream(dataset_path, **kwargs):
""" create data_loader to stream images 1 by 1 """
if osp.isfile(osp.join(dataset_path, 'calibration.txt')):
db = ETH3DStream(dataset_path, **kwargs)
elif osp.isdir(osp.join(dataset_path, 'image_left')):
... | 145f8c44e8e718fea9a9bdabf5e1f9497a00241a | 13,645 |
def is_contained(target, keys):
"""Check is the target json object contained specified keys
:param target: target json object
:param keys: keys
:return: True if all of keys contained or False if anyone is not contained
Invalid parameters is always return False.
"""
if not target or not key... | 948196d4b470788199506bd7768e03554fa67b40 | 13,646 |
def map(x, in_min, in_max, out_min, out_max):
"""
Map a value from one range to another
:param in_min: minimum of input range
:param in_max: maximum of input range
:param out_min: minimum of output range
:param out_max: maximum of output range
:return: The value scaled ... | 4117af35b0061df1fd271306accf198692442dac | 13,647 |
import requests
def get_points(sess: requests.Session, console: Console, status: Status, projectID: int):
"""
Get all exisiting points in a project
"""
base_url = f"https://mapitfast.agterra.com/api/Points"
resp = sess.get(base_url, params={"projectId": projectID})
points_obj_list = list()
... | c5f1fce542b06d1680637750f51c3bd7a6e6ebc4 | 13,648 |
def calculate_discounted_returns(rewards):
"""
Calculate discounted reward and then normalize it
(see Sutton book for definition)
Params:
rewards: list of rewards for every episode
"""
returns = np.zeros(len(rewards))
next_return = 0 # 0 because we start at the last timestep
for... | 538c3d5636bc6105ddf603f0928e4e891fea774c | 13,649 |
import time
import sys
def mock_tensorboard(logdir, host, port, print_nonsense, print_nothing,
address_in_use, sleep_time):
"""Run fake TensorBoard."""
if logdir is None:
print('A logdir must be specified. Run `tensorboard --help` for '
'details and examples.')
... | 26a793264fa9561fabc9fa9d2fcb1377a6b60783 | 13,650 |
def parse_binskim_old(bin_an_dic, output):
"""Parse old version of binskim."""
current_run = output['runs'][0]
if 'results' in current_run:
rules = output['runs'][0]['rules']
for res in current_run['results']:
if res['level'] != 'pass':
if len(res['formattedRuleMe... | bd927aa972148b1171dcf2d5c60aa219cf4527b6 | 13,651 |
import operator
def binary_elementwise_compute(
ifm: te.Tensor,
ifm2: te.Tensor,
lut: te.Tensor,
operator_type: str,
ifm_scale: float,
ifm_zero_point: int,
ifm2_scale: float,
ifm2_zero_point: int,
ofm_scale: float,
ofm_zero_point: int,
ifm_channels: int,
ifm2_channels: ... | 2bbac91e8606512180b6a652538eeac23e369c7c | 13,652 |
def x_power_dependence(n, dep_keys, ctfs=list(), force_zero=None, **kwargs):
"""Returns a fit function that allows x^n depdendence on the constants
associated with each of the dep_keys
y(x) = (a0 * b0 + a1 * b1 + ...) * x^n
where each of the a's are fit parameters and each of the b's are either
... | 49b1a605001003b52f38f7f469a7c7bfafd43d6b | 13,653 |
from typing import Iterable
def get_subseqs(s, ops):
"""Returns a list of sequences given when applying the list of (ops)
on them, until a constant one is found, thus:
new[0] = next seq of s with ops[0]
new[i] = next seq of new[i-1] with op[i]
If 'ops' is not a list, then the s... | 3ad7a955c7b55596f327ae52d34368451ef79737 | 13,654 |
from pysiaf import aperture # runtime import to avoid circular import on startup
import os
from typing import OrderedDict
def read_hst_siaf(file=None):#, AperNames=None):
"""Read apertures from HST SIAF file and return a collection.
This was partially ported from Lallo's plotap.f.
Parameters
-------... | f7281b1411deefbec86dd50feb40739b59cad3d1 | 13,655 |
def update_s(C,k):
"""
Args: C: 2d array
k: 1d array
Return: 1d array
"""
if np.shape(C)[0]==0:
s = np.array([1])
else:
temp = np.dot(C,k)
s = np.append(temp,1)
return s | ce4604d71b05d328d6b8b60bea9f611d8d12f6eb | 13,656 |
def test_handler_callback_failure():
"""Test failure mode for inappropriate handlers."""
class BadHandler(object):
def handler(self, one):
return 'too many'
ob = EventTest()
handler = BadHandler()
with pytest.raises(TypeError):
ob.PublicEvent += handler.handler
... | c5d8daf4cca81ef8dee8ba5a10b9e572899bd23e | 13,657 |
def get_chord_type(chord):
"""'Parses' input for a chord and returns the type of chord from it"""
cleaned_chord = chord[1:]
cleaned_chord = cleaned_chord.replace('b', '')
cleaned_chord = cleaned_chord.replace('#', '')
mapping = {
'7': 'seven',
'9': 'nine',
'm7': 'minor7',
... | 4a753eb31f1e33340a7aa4df6942c4752b208fdd | 13,658 |
import os
import pickle
def compile_stats(path):
""" combines all items from the given folder of stats arrays """
df = pd.DataFrame()
for item in os.listdir(path):
print(item)
with open(path + '/' + item, 'rb') as file:
df1 = pickle.load(file)
# df1 = df1.loc[df1.pr... | 58a2a9f4962b2882c7da589af27ba55e9ca601ed | 13,659 |
from typing import Union
def transpile(model: Union[SympyOpt, Model]) -> SympyOpt:
"""Transpile optimization problem into SympyOpt model
Only accepts SympyOpt or Docplex model.
:param model: model to be transpiled
:raises ValueError: if the argument is of inappropriate type
:return: transpiled m... | f2b4895cb980e535166d9749eb93925722981828 | 13,660 |
def definition():
"""View of the finances with subtotals generated."""
return sql.format(source=source) | c0b9add49b9c7403328449b8989e29739be267a9 | 13,661 |
import math
def random_mini_batches(X, Y, mini_batch_size = 32, seed = 0):
"""
Creates a list of random minibatches from (X, Y)
Arguments:
X -- input data, of shape (input size, number of examples) (m, Hi, Wi, Ci)
Y -- true "label" vector (containing 0 if control, 1 if case), of shape (1, number ... | 8baa63be638a1706c49176a51013524594a59452 | 13,662 |
def file_base_features(path, record_type):
"""Return values for BASE_SCHEMA features."""
base_feature_dict = {
"record_id": path,
"record_type": record_type,
# "utc_last_access": os.stat(path).st_atime,
"utc_last_access": 1600000000.0,
}
return base_feature_dict | 12f16684002892d7af59a1e26e8a40501098ca4f | 13,663 |
def split_ref(ref):
"""
セル参照をセル文字と1ベース行番号文字に分割する。
Params:
ref(str):
Returns:
Tuple[str, str]: 列、行
"""
m = re_cellref.match(ref)
if m:
return m.group(1), m.group(2)
return None, None | 1ae8e058a47ad0410b7131d4b89061dea822ed68 | 13,664 |
def table_definition(dataset):
"""print an azure synapse table definition for a kartothek dataset"""
index_col = list(dataset.dataset_metadata.index_columns)[
0
] ##works only with one index column
cols = synapse_columns(
dataset.dataset_metadata.table_meta[dataset.table], index_col
... | 75a2f55fa31025899e9adb05e20dbc89ae8dabd4 | 13,665 |
import os
def identify_image_set(imagedir, image_names_pattern):
"""
Find all the images within the *imagedir*.
:param imagedir:
:param image_names_pattern:
:return: a list of image names that are part of the image set
"""
image_names_from_os = sorted(os.listdir(imagedir))
image_names ... | 57826e43d7d3e241ec8f61664b007d5fea2ef43f | 13,666 |
import itertools
def node_extractor(dataframe, *columns):
"""
Extracts the set of nodes from a given dataframe.
:param dataframe: dataframe from which to extract the node list
:param columns: list of column names that contain nodes
:return: list of all unique nodes that appear in the provided data... | 7a4ab889257a0f2c5ddfe18e65d0a7f5f35d8d98 | 13,667 |
def _get_bag(environ, bag_name):
"""
Get the named bag out of the store.
"""
store = environ['tiddlyweb.store']
bag = Bag(bag_name)
try:
bag = store.get(bag)
except NoBagError as exc:
raise HTTP404('%s not found, %s' % (bag.name, exc))
return bag | db4e2425f6c4d839fa091c08b524ea8ecd3c7c27 | 13,668 |
def missing_values_operation(files):
"""Will take iterable file objects and eliminate features or samples with missing values or inputing missing values if necessary"""
for i in files:
with open(i,'rw') as f:
if missing_values(f)==True:
file_data=load_data(i)
... | df5a6f6809605107db9b008b877fa913a3dc686d | 13,669 |
def _object_id(value):
"""Return the object_id of the device value.
The object_id contains node_id and value instance id
to not collide with other entity_ids.
"""
object_id = "{}_{}".format(slugify(_value_name(value)),
value.node.node_id)
# Add the instance id if... | 34c21de533a99ffdabfdabf21540492f7ce33b7f | 13,670 |
def _apply_attention_constraint(
e, last_attended_idx, backward_window=1, forward_window=3
):
"""Apply monotonic attention constraint.
**Note** This function is copied from espnet.nets.pytorch_backend.rnn.attention.py
"""
if e.size(0) != 1:
raise NotImplementedError(
"Batch atten... | 213ef514a9cff31134185e38c57d46921eba763a | 13,671 |
import time
import sys
def RetryInvocation(return_handler, exc_handler, max_retry, functor, *args,
**kwds):
"""Generic retry loop w/ optional break out depending on exceptions.
Generally speaking you likely want RetryException or RetryReturned
rather than this; they're wrappers around this ... | 3cb6e4f6793fbf2f6633efec74b7ed8495233e6c | 13,672 |
from bs4 import BeautifulSoup
import re
def parse_reolink(email):
"""Parse Reolink tracking numbers."""
tracking_numbers = []
soup = BeautifulSoup(email[EMAIL_ATTR_BODY], 'html.parser')
links = [link.get('href') for link in soup.find_all('a')]
for link in links:
if not link:
c... | cc96d35edb2ace40d83464f4cc3bed1c91480f0f | 13,673 |
def HMF(state, Delta, N):
"""Computes the result of the MF hamiltonian acting on a given state."""
#kinetic term: sum_i(eps(i)*(n_i,up + n_i,down))
kinetic_state = dict_list_sum(
[dict_prod(eps(i, N), dict_sum(number_op(state, i, 0, N), number_op(state, i, 1, N))) for i in range(N)])
#interaction term: sum_i( ... | 3c608d42a328e05fd59c55cbaeded3b6d0b4970b | 13,674 |
def calculate_probability_of_multicoincidence(ambient_size: int = 0,
set_sizes: tuple = (),
intersection_size: int = 0):
"""
Calculates the probability that subsets of a set of a given size, themselves of
prescribed ... | 1d9deb083f0a0397b067f6efa989a94d68d11b69 | 13,675 |
def check_date(option, opt, value):
"""check a file value
return the filepath
"""
try:
return DateTime.strptime(value, "%Y/%m/%d")
except DateTime.Error :
raise OptionValueError(
"expected format of %s is yyyy/mm/dd" % opt) | 3f817bf2286b459b11ded67abba33b654b090caf | 13,676 |
def no_cloud_fixture():
"""Multi-realization cloud data cube with no cloud present."""
cloud_area_fraction = np.zeros((3, 10, 10), dtype=np.float32)
thresholds = [0.265, 0.415, 0.8125]
return cloud_probability_cube(cloud_area_fraction, thresholds) | 5128c40485fdbc9c8646bec25d1949aac4cddb58 | 13,677 |
from typing import Iterable
def make_slicer_query(
database: Database,
base_table: Table,
joins: Iterable[Join] = (),
dimensions: Iterable[Field] = (),
metrics: Iterable[Field] = (),
filters: Iterable[Filter] = (),
orders: Iterable = (),
):
"""
Creates a pypika/SQL query from a lis... | 31821bdbb0ab94c8971a70d35c1165f5245d90fb | 13,678 |
def build_grid_generator(cfg, input_shape):
"""
Built an grid generator from `cfg.MODEL.GRID_GENERATOR.NAME`.
"""
grid_generator = cfg.MODEL.GRID_GENERATOR.NAME
return GRID_GENERATOR_REGISTRY.get(grid_generator)(cfg, input_shape) | 5f6edbaeece026fc56068aec0fc75549a71ce4a8 | 13,679 |
def main_page(request):
"""
This function is used to display the main page of programme_curriculum
@param:
request - contains metadata about the requested page
"""
return render(request, 'programme_curriculum/mainpage.html') | fdee3342d369112abb2560c4ecfda17a8dfe01e4 | 13,680 |
def _write_detailed_dot(graph, dotfilename):
"""Create a dot file with connection info
digraph structs {
node [shape=record];
struct1 [label="<f0> left|<f1> mid\ dle|<f2> right"];
struct2 [label="<f0> one|<f1> two"];
struct3 [label="hello\nworld |{ b |{c|<here> d|e}| f}| g | h"];
struct1:f1... | 793983b56b8fff32fde4e9dc5379a93e4edcb16e | 13,681 |
import functools
def ResidualBlock(name, input_dim, output_dim, filter_size, inputs, resample=None, he_init=True, bn=False):
"""
resample: None, 'down', or 'up'
"""
if resample=='down':
conv_shortcut = MeanPoolConv
conv_1 = functools.partial(lib.ops.conv2d.Conv2D, input_dim=inpu... | 8871553f11975edef2a1b0bbf96aff8c54417adf | 13,682 |
import pylleo
import yamlord
import os
def callback_save_poly():
"""Perform polyfit once regions selected
Globals: cal_fname, data (read-only, so no declaration)
"""
def _check_param_regions(param, regions, cal_dict):
msg = """
<b>{}</b> was not found in the calibration diction... | 2daa24b0bec9428ba6d45657e08a1ecbe5edd39f | 13,683 |
def timer(func):
"""Logging elapsed time of funciton (decorator)."""
@wraps(func)
def wrapper(*args, **kwargs):
with timing(func.__name__):
return func(*args, **kwargs)
return wrapper | eb38d9856f59328188ac24e66f3bb4f9356ebe89 | 13,684 |
def peak_ana(x, y, nb=3, plotpoints_axis=None):
""" nb = number of point (on each side) to use as background"""
## get background
xb = np.hstack((x[0:nb], x[-(nb):]))
yb = np.hstack((y[0:nb], y[-(nb):]))
a = np.polyfit(xb, yb, 1)
b = np.polyval(a, x)
yf = y - b
yd = np.diff(yf)
## d... | 1f9ea444b09684ac7764ced8ba5ca3fdbd3e8593 | 13,685 |
import os
import time
import pandas
def run_benchmarks(benchmark_params, test_root, force=False):
"""Run the benchmarks
For every row in benchmark params, run a trace on the input video
using the params specified.
benchmark_params: DataFrame with columns corresponding to keywords
to ... | 03fe6a3ae58ec73e8b85b670827ee4e7bf7f2d1d | 13,686 |
from jams.distributions import sep_fs_mean, sep_fs_std
def sample_sep01(nn, xi=1., beta=0.):
"""
Samples from the skew exponential power distribution with location zero and scale one.
Definition
----------
def sample_sep01(nn, xi=1., beta=0.):
Input
-----
... | dbeda8efa38db5d55b688c4bfc30350262c39f32 | 13,687 |
def pandas_from_feather(file: str = None) -> pd.DataFrame:
""" Load a feather file to a pandas DataFrame.
Uses pyarrow to load a csv file into a [pyarrow.Table](https://arrow.apache.org/docs/python/generated/pyarrow.Table.html) and convert to pandas format.
Args:
file (str): the feathe... | 2bd7679581690095865d9f9d2cae85cf9d736f8d | 13,688 |
import pwd
import os
def _get_user_name():
"""
Get the current user.
"""
return pwd.getpwuid(os.getuid())[0] | d25549cf12b3dd258446e4d1d7bae386f68139d0 | 13,689 |
def email_coas():
"""
Email certificates of analysis to their recipients.
"""
# Get the certificate data.
# Email links (optional attachments) to the contacts.
return NotImplementedError | b09c6650c498618b77a5e0beab0caf63a2cbf99d | 13,690 |
import random
def dropout(x, key, keep_rate):
"""Implement a dropout layer.
Arguments:
x: np array to be dropped out
key: random.PRNGKey for random bits
keep_rate: dropout rate
Returns:
np array of dropped out x
"""
# The shenanigans with np.where are to avoid having to re-jit if
# keep ... | f9686e64a11e17ca35eefacaa8f0b356cc0f065e | 13,691 |
def band_spd_spin_polarized(
folder,
output='band_spd_sp.png',
scale_factor=2,
order=['s', 'p', 'd'],
color_dict=None,
legend=True,
linewidth=0.75,
band_color='black',
unprojected_band_color='gray',
unprojected_linewidth=0.6,
fontsize=7,
annotations=['$\\uparrow$ ', '$\\d... | 4cd0ef74a2ad4ce46d28aad296a9156ec91dc301 | 13,692 |
def initial_queries(bo):
"""
script which explores the initial query points of a BayesianOptimization
instance, reports errors to Slack
Input: instance of a BayesianOptimization
"""
# loop to try a second time in case of error
errcount = 0
for i in range(2):
try:
bo.m... | 3419cd89724a23296688f321469a68c8209d2a25 | 13,693 |
import logging
import codecs
def _parse_start_test_log(start_test_log):
"""Parse start_test logfile and return results in python data structure.
:type start_test_log: str
:arg start_test_log: start_test log filename
:rtype: list of dicts
:returns: list of dicts; each dict contains info about a s... | 850f3d3da51208483955f14b29546df3ea9f746d | 13,694 |
def cell2AB(cell):
"""Computes orthogonalization matrix from unit cell constants
:param tuple cell: a,b,c, alpha, beta, gamma (degrees)
:returns: tuple of two 3x3 numpy arrays (A,B)
A for crystal(x) to Cartesian(X) transformations A*x = np.inner(A,x) =X
B (= inverse of A) for Cartesian to c... | 970acf484a701efcdb024e7cad5981ded314209e | 13,695 |
from typing import Tuple
def _parse_header(line: bytes) -> Tuple[HeaderLine, bytes]:
"""
Parse the header line of the received input.
:param line:
:return: a tuple of the parsed header and the remaining input that is not
part of the header.
"""
end_index = line.find(b"\r\n")
heade... | e68cbcdd5e25e0d4690671cc3be5b4985c8f5c2c | 13,696 |
def sendMessage(qry):
"""
Message sending handling, either update if the query suggests it otherwise send the message.
:param qry: current query
:return: Status of Message sending.
"""
try: getUserName()
except: return _skypeError()
if(qry == "skype update"):
_writeFriends()
... | c13e187170015d3e9a786ceb7cb9a364928fa8c0 | 13,697 |
def scrape_detail_page(response):
"""
get detail page info as dict type
"""
root = lxml.html.fromstring(response.content)
ebook = {
'url': response.url,
'title': root.cssselect('#bookTitle')[0].text_content(),
'price': root.cssselect('.buy')[0].text,
'content': [h3.te... | 5c3b7e743cd109fe2d05e0cc261e46884c673421 | 13,698 |
import tqdm
from pathlib import Path
import torch
def reload_from_numpy(device, metadata, reload_dir):
"""Reload the output of voice conversion model."""
conv_mels = []
for pair in tqdm(metadata["pairs"]):
file_path = Path(reload_dir) / pair["mel_path"]
conv_mel = torch.load(file_path)
... | 7cf5b2c1f12886f8fcded9072a86c53384b93760 | 13,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.