content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def create_pipeline(pipeline_name: Text, pipeline_root: Text, data_root: Text,
beam_pipeline_args: Text) -> pipeline.Pipeline:
"""Custom component demo pipeline."""
examples = external_input(data_root)
# Brings data into the pipeline or otherwise joins/converts training data.
example_gen =... | 19,000 |
def toggleAction(*args, **kwargs):
"""A decorator which identifies a class method as a toggle action. """
return ActionFactory(ToggleAction, *args, **kwargs) | 19,001 |
def getHistograph(dataset = {}, variable = ""):
"""
Calculates a histogram-like summary on a variable in a dataset
and returns a dictionary. The keys in the dictionary are unique items
for the selected variable. The values of each dictionary key, is the number
of times the unique item occu... | 19,002 |
async def test_update_system_data_v3(
event_loop, v3_server, v3_sensors_json, v3_settings_json, v3_subscriptions_json
):
"""Test getting updated data for a v3 system."""
async with v3_server:
v3_server.add(
"api.simplisafe.com",
f"/v1/users/{TEST_USER_ID}/subscriptions",
... | 19,003 |
def p_expr_list_not_empty(p):
"""
expr_list_not_empty : expr COMMA expr_list_not_empty
| expr
"""
if len(p) == 4:
p[0] = [p[1]] + p[3]
else:
p[0] = [p[1]] | 19,004 |
def _get_client_by_settings(
client_cls, # type: Type[BaseClient]
bk_app_code=None, # type: Optional[str]
bk_app_secret=None, # type: Optional[str]
accept_language=None, # type: Optional[str]
**kwargs
):
"""Returns a client according to the django settings"""
client = client_cls(**kwargs... | 19,005 |
def watch(process):
"""Watch the log output from a process using tail -f."""
with lcd(root_dir):
local('tail -f logs/%s.log -s 0.5' % process) | 19,006 |
def create_and_configure_jinja_environment(
dirs, autoescape=True, handler=None, default_locale='en_US'):
"""Sets up an environment and gets jinja template."""
# Defer to avoid circular import.
from controllers import sites
locale = None
app_context = sites.get_course_for_current_request()
... | 19,007 |
def bootstrap_cost(target_values, class_probability_matrix, cost_function,
num_replicates):
"""Bootstraps cost for one set of examples.
E = number of examples
K = number of classes
B = number of bootstrap replicates
:param target_values: length-E numpy array of target values (in... | 19,008 |
def jdeblend_bob(src_fm, bobbed):
"""
Stronger version of jdeblend() that uses a bobbed clip to deblend.
Parameters:
clip src_fm: Source after field matching, must have field=3 and low cthresh.
clip src: Bobbed source.
Example:
src =
from hav... | 19,009 |
def ParseArgs():
"""Parse the command line options, returning an options object."""
usage = 'Usage: %prog [options] LIST|GET|LATEST'
option_parser = optparse.OptionParser(usage)
AddCommandLineOptions(option_parser)
log_helper.AddCommandLineOptions(option_parser)
options, args = option_parser.parse_args()
... | 19,010 |
def generate_table_definition(schema_and_table, column_info,
primary_key=None, foreign_keys=None,
diststyle=None, distkey=None, sortkey=None):
"""Return a CREATE TABLE statement as a string."""
if not column_info:
raise Exception('No columns sp... | 19,011 |
def gradient_descent_update(x, gradx, learning_rate):
"""
Performs a gradient descent update.
"""
# Return the new value for x
return x - learning_rate * gradx | 19,012 |
def nth_permutation(n, size=0):
"""nth permutation of 0..size-1
where n is from 0 to size! - 1
"""
lehmer = int_to_lehmer(n, size)
return lehmer_to_permutation(lehmer) | 19,013 |
def signin(request):
"""
Method for log in of the user
"""
if request.user.is_authenticated:
return_var = render(request, '/')
if request.method == 'POST':
username = request.POST['username']
password = request.POST['password']
user = authenticate(request, username=us... | 19,014 |
def PlotDensity(data_list, ax, args):
""" Plot one dimensional data as density curves.
Args:
data_list: a list of Data objects
ax: a matplotlib axis object
args: an argparse arguments object
"""
# first create density list, then pass that to PlotLineScatter
density_list = []
for data in data_li... | 19,015 |
def write_video(filename, video_array, fps, video_codec='libx264', options=None):
"""
Writes a 4d tensor in [T, H, W, C] format in a video file
Parameters
----------
filename : str
path where the video will be saved
video_array : Tensor[T, H, W, C]
tensor containing the individu... | 19,016 |
def unconfigure_ip_prefix_list(device, prefix_list_name, seq, ip_address):
""" unconfigure prefix-list
Args:
device (`obj`): device to execute on
prefix_list_name (`int`): prefix-list name
seq (`int`): Sequence number of a prefix list
ip_address (`str`): ip a... | 19,017 |
def compare_features(f1, f2):
"""Comparison method for feature sorting."""
def get_prefix(feature):
if feature.startswith('e1-'): return 'e1'
if feature.startswith('e2-'): return 'e2'
if feature.startswith('e-'): return 'e'
if feature.startswith('t-'): return 't'
return '... | 19,018 |
def set_backup_count(backup_count):
"""
Set maximum number of files of logs to rotate for rotating logging. If parameter is not an int number then the
function does not change any value.
:param backup_count: int number of how many files to keep to rotate logs.
:return: None
"""
global _back... | 19,019 |
def localized_index(lang):
"""
Example view demonstrating rendering a simple HTML page.
"""
context = make_context()
context['lang'] = lang
context['content'] = context['COPY']['content-%s' % lang]
context['form'] = context['COPY']['form-%s' % lang]
context['share'] = context['COPY']['sh... | 19,020 |
def build_output_unit_vqa(q_encoding, m_last, num_choices, apply_dropout,
scope='output_unit', reuse=None):
"""
Apply a 2-layer fully-connected network to predict answers. Apply dropout
if specified.
Input:
q_encoding: [N, d], tf.float32
m_last: [N, d], tf.floa... | 19,021 |
def coding_problem_16(length):
"""
You run a sneaker website and want to record the last N order ids in a log. Implement a data structure to
accomplish this, with the following API:
record(order_id): adds the order_id to the log
get_last(i): gets the ith last element from the log. i is guar... | 19,022 |
def _check_dimensions(n_grobs, nrow = None, ncol = None):
"""
Internal function to provide non-Null nrow and ncol numbers
given a n_number of images and potentially some information about the
desired nrow/ncols.
Arguments:
----------
n_grobs: int, number of images to be organized
nrow: ... | 19,023 |
def year_parse(s: str) -> int:
"""Parses a year from a string."""
regex = r"((?:19|20)\d{2})(?:$|[-/]\d{2}[-/]\d{2})"
try:
year = int(re.findall(regex, str(s))[0])
except IndexError:
year = None
return year | 19,024 |
def sampleDistribution(d):
"""
Expects d to be a list of tuples
The first element should be the probability
If the tuples are of length 2 then it returns the second element
Otherwise it returns the suffix tuple
"""
# {{{
import random
z = float(sum(t[0] for t in d))
if z == 0.0:... | 19,025 |
def logout():
"""
`/register` endpoint
Logs out a user and redirects to the index page.
"""
logout_user()
flash("You are logged out.", "info")
return redirect(url_for("main.index")) | 19,026 |
def convertExcelToUe():
""" Convert CSV exported file from Excel to a CSV file readable by UE4 for String Tables """
for f in csvFiles:
fName = splitext(f)[0]
try:
file = open(join(inputPath, f), "r", encoding="utf8")
fContent = file.read()
lines ... | 19,027 |
def players_season_totals(season_end_year, playoffs=False, skip_totals=False,
output_type=None, output_file_path=None, output_write_option=None, json_options=None):
"""
scrape the "Totals" stats of all players from a single year
Args:
season_end_year (int): year in which the season ends, e.g.... | 19,028 |
def array_shuffle(x,axis = 0, random_state = 2020):
"""
对多维度数组,在任意轴打乱顺序
:param x: ndarray
:param axis: 打乱的轴
:return:打乱后的数组
"""
new_index = list(range(x.shape[axis]))
random.seed(random_state)
random.shuffle(new_index)
x_new = np.transpose(x, ([axis]+[i for i in list(range(len(x.s... | 19,029 |
def cat(out_media_fp, l_in_media_fp):
"""
Args:
out_media_fp(str): Output Media File Path
l_in_media_fp(list): List of Media File Path
Returns:
return_code(int):
"""
ref_vcodec = get_video_codec(l_in_media_fp[0])
ref_acodec = get_audio_codec(l_in_media_fp[0])
ref_vsca... | 19,030 |
def get_recent_activity_rows(chase_driver):
"""Return the 25 most recent CC transactions, plus any pending
transactions.
Returns:
A list of lists containing the columns of the Chase transaction list.
"""
_goto_link(chase_driver, "See activity")
time.sleep(10)
rows = chase... | 19,031 |
def test_forecast_url_good():
"""
Test valid and invalid sets of data passed to the create forecast url
"""
assert get_noaa_forecast_url(44099) is not None | 19,032 |
def evaluate(test_loader, model, test_img_num):
"""
Evaluate.
:param test_loader: DataLoader for test data
:param model: model
"""
# Make sure it's in eval mode
model.eval()
# Lists to store detected and true boxes, labels, scores
det_boxes = list()
det_labels = list()
det... | 19,033 |
def loglikelihood(x, mean, var, pi):
"""
式(9.28)
"""
lkh = []
for mean_k, var_k, pi_k in zip(mean, var, pi):
lkh.append(pi_k * gaussian_pdf(x, mean_k, var_k))
return np.sum(np.log(np.sum(lkh, 0))) | 19,034 |
def calc_E_ST_GJ(E_star_ST):
"""基準一次エネルギー消費量(GJ/年)の計算 (2)
Args:
E_star_ST(float): 基準一次エネルギー消費量(J/年)
Returns:
float: 基準一次エネルギー消費量(GJ/年)
"""
# 小数点以下一位未満の端数があるときはこれを切り上げる
return ceil(E_star_ST / 100) / 10 | 19,035 |
def next_line(grd_file):
"""
next_line
Function returns the next line in the file
that is not a blank line, unless the line is
'', which is a typical EOF marker.
"""
done = False
while not done:
line = grd_file.readline()
if line == '':
return line, False
elif line.strip():
return l... | 19,036 |
def look_for(room, position, main, sub=None):
"""
:type room: rooms.room_mind.RoomMind
"""
if not room.look_at:
raise ValueError("Invalid room argument")
if position.pos:
position = position.pos
if sub:
return _.find(room.look_at(LOOK_FLAGS, position),
... | 19,037 |
def test_measure_simple(mcp):
"""
Asserts that the result of a measurement is a set of three bytes, and that no more than 3 bytes are returned
"""
desiredMeasurements = 1
measuredData = mcp['device'].measure()
assert_equal(len(measuredData), 3) | 19,038 |
def test_searchparam_type_date_period_le(store: FHIRStore, index_resources):
"""Handle date search parameters on FHIR data type "period"
The date format is the standard XML format, though other formats may be supported
prefix le: the range below the search value intersects (i.e. overlaps)
with the r... | 19,039 |
def grayScaleHist(image):
"""
this function will convert color image into grayscale and show the histogram for that grayscale image
"""
gray_scale = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
cv2.imshow('Grayscale Image', gray_scale)
hist = cv2.calcHist([gray_scale],[0], None, [256], [0,256])
_ = plt.figure()
_... | 19,040 |
def get_proto(proto):
"""
Returns a protocol number (in the /etc/protocols sense, e.g. 6 for
TCP) for the given input value. For the protocols that have
PROTO_xxx constants defined, this can be provided textually and
case-insensitively, otherwise the provided value gets converted to
an integer a... | 19,041 |
def f5_update_policy_cookie_command(client: Client, policy_md5: str, cookie_id: str,
cookie_name: str,
perform_staging: bool, parameter_type: str,
enforcement_type: str,
attack... | 19,042 |
def test_value_error():
""" Test value error """
with pytest.raises(ValueError):
snell_angle(0, 0, 0) | 19,043 |
def ping():
"""
Determine if the container is working and healthy. In this sample container, we declare
it healthy if we can load the model successfully.
:return:
"""
health = False
try:
health = model is not None # You can insert a health check here
except:
pass
... | 19,044 |
def random(
shape,
density=0.01,
random_state=None,
data_rvs=None,
format='coo'
):
""" Generate a random sparse multidimensional array
Parameters
----------
shape: Tuple[int]
Shape of the array
density: float, optional
Density of the generated... | 19,045 |
def file_md5_is_valid(fasta_file: Path, checksum: str) -> bool:
"""
Checks if the FASTA file matches the MD5 checksum argument.
Returns True if it matches and False otherwise.
:param fasta_file: Path object for the FASTA file.
:param checksum: MD5 checksum string.
:return: boolean indicating i... | 19,046 |
def combine_to_int(values):
"""Combine several byte values to an integer"""
multibyte_value = 0
for byte_id, byte in enumerate(values):
multibyte_value += 2**(4 * byte_id) * byte
return multibyte_value | 19,047 |
def zip_images(image_dir, out_dir, threshold=700_000, factor=0.75):
"""Shrink and rotate images and then put them into a zip file."""
os.makedirs(out_dir, exist_ok=True)
manifest = out_dir / (out_dir.name + '_manifest.csv')
with open(manifest, 'w') as out_file:
writer = csv.writer(out_file)
... | 19,048 |
def loss_fn(x, results, is_valtest=False, **kwargs):
"""
Loss weight (MCAE):
- sni: snippet reconstruction loss
- seg: segment reconstruction loss
- cont: smooth regularization
- reg: sparsity regularization
- con: constrastive loss
- cls: auxilliary classification loss <not used for MCA... | 19,049 |
def _as_uint32(x: int) -> QVariant:
"""Convert the given int to an uint32 for DBus."""
variant = QVariant(x)
successful = variant.convert(QVariant.UInt)
assert successful
return variant | 19,050 |
def svcs_tang_u(Xcp,Ycp,Zcp,gamma_t,R,m,Xcyl,Ycyl,Zcyl,ntheta=180, Ground=False):
"""
Computes the velocity field for nCyl*nr cylinders, extending along z:
nCyl: number of main cylinders
nr : number of concentric cylinders within a main cylinder
INPUTS:
Xcp,Ycp,Zcp: cartesian coo... | 19,051 |
def np_to_o3d_images(images):
"""Convert numpy image list to open3d image list
Parameters
----------
images : list[numpy.ndarray]
Returns
o3d_images : list[open3d.open3d.geometry.Image]
-------
"""
o3d_images = []
for image in images:
image = np_to_o3d_image(image)
... | 19,052 |
def compute_mse(y_true, y_pred):
"""ignore zero terms prior to comparing the mse"""
mask = np.nonzero(y_true)
mse = mean_squared_error(y_true[mask], y_pred[mask])
return mse | 19,053 |
def test_enable_caching_specific(configure_caching):
"""
Check that using enable_caching for a specific identifier works.
"""
identifier = 'some_ident'
with configure_caching({'default_enabled': False}):
with enable_caching(identifier=identifier):
assert get_use_cache(identifier=... | 19,054 |
def image2d(math_engine, batch_len, batch_width, height, width, channels, dtype="float32"):
"""Creates a blob with two-dimensional multi-channel images.
:param neoml.MathEngine.MathEngine math_engine: the math engine that works with this blob.
:param batch_len: the **BatchLength** dimension of the new blo... | 19,055 |
def error_response(error, message):
"""
returns error response
"""
data = {
"status": "error",
"error": error,
"message": message
}
return data | 19,056 |
def graph_to_text(
graph: MultiDiGraph, quoting: bool = True, verbose: bool = True
) -> str:
"""Turns a graph into
its text representation.
Parameters
----------
graph : MultiDiGraph
Graph to text.
quoting : bool
If true, quotes will be added.
verbose : bool
If... | 19,057 |
def test_has_valid_dir_structure():
"""Check if the specified dir structure is valid"""
def recurse_contents(contents):
if contents is None:
return None
else:
for key, value in contents.items():
assert(isinstance(key, str))
if value is None:
return None
... | 19,058 |
def create_user(username, password, firstname, lastname):
"""Create an user."""
pwd_hash = pwd_context.encrypt(password)
with db_conn.cursor() as cur:
cur.execute("""
INSERT INTO AdminUser (username, password, firstname, lastname)
VALUES (%s, %s, %s, %s)""", (username, pwd_ha... | 19,059 |
def getFBA(fba):
"""AC factory.
reads a fileobject and creates a dictionary for easy insertation
into a postgresdatabase. Uses Ohlbergs routines to read the files (ACfile)
"""
word = fba.getSpectrumHead()
while word is not None:
stw = fba.stw
mech = fba.Type(word)
datadic... | 19,060 |
def logtimestamp():
"""
returns a formatted datetime object with the curren year, DOY, and UT
"""
return DT.datetime.utcnow().strftime("%Y-%j-%H:%M:%S") | 19,061 |
def get_most_common_non_ascii_char(file_path: str) -> str:
"""Return first most common non ascii char"""
with open(file_path, encoding="raw_unicode_escape") as f:
non_ascii = {}
for line in f:
for char in line:
if not char.isascii():
if char... | 19,062 |
def compute_noise_from_target_epsilon(
target_epsilon,
target_delta,
epochs,
batch_size,
dataset_size,
alphas=None,
approx_ratio=0.01,
):
"""
Takes a target epsilon (eps) and some hyperparameters.
Returns a noise scale that gives an epsilon in [0.99 eps, eps].
The approximati... | 19,063 |
def cart2pol(x, y):
"""
author : Dr. Schaeffer
"""
rho = np.sqrt(x**2 + y**2)
phi = np.arctan2(y, x)
return(rho, phi) | 19,064 |
def set_seed(seed: int) -> None:
"""
Seeds various random generators.
Args:
seed: Seed to use.
"""
random.seed(seed)
np.random.seed(seed)
torch.seed(seed)
torch.cuda.manual_seed_all(seed) | 19,065 |
def requires_site(site):
"""Skip test based on where it is being run"""
skip_it = bool(site != SITE)
return pytest.mark.skipif(skip_it,
reason='SITE is not %s.' % site) | 19,066 |
def set_error_redirect(request, error_redirect):
"""
Convenience method to set the Location redirected
to after an error. Should be used at the top of
views.
You could call set_error_redirect on the interia
object directly but you need to check that the
inertia object is actually there.
... | 19,067 |
def handle_error(e):
"""
Handle errors, formatting them as JSON if requested
"""
error_type = type(e).__name__
message = str(e)
trace = None
description = None
status_code = 500
if isinstance(e, werkzeug.exceptions.HTTPException):
status_code = e.code
description = e.... | 19,068 |
def iou(bbox_1, bbox_2):
"""Computes intersection over union between two bounding boxes.
Parameters
----------
bbox_1 : np.ndarray
First bounding box, of the form (x_min, y_min, x_max, y_max).
bbox_2 : np.ndarray
Second bounding box, of the form (x_min, y_min, x_max, y_max).
Re... | 19,069 |
def _create_directory_structure_if_necessary(folders):
""" Ensure basic file structure in project. """
site_folder = folders['site']
if not env.exists(site_folder):
# base deployment folder
env.run('mkdir -p {site_folder}'.format(site_folder=site_folder,))
# set linux user group.
... | 19,070 |
def GetIntensityArray(videofile, threshold, scale_percent):
"""Finds pixel coordinates within a videofile (.tif, .mp4) for pixels
that are above a brightness threshold, then accumulates the
brightness event intensities for each coordinate,
outputting it as a 2-D array in the same size as the video frame... | 19,071 |
def test_unicode_handling(username, password):
"""
With a unicode string for the password, set and verify the
Authorization header.
"""
header_dict = {}
authorizer = BasicAuthorizer(username, password)
authorizer.set_authorization_header(header_dict)
assert header_dict["Authorization"][... | 19,072 |
def _check_data(handler, data):
"""Check the data."""
if 'latitude' not in data or 'longitude' not in data:
handler.write_text("Latitude and longitude not specified.",
HTTP_UNPROCESSABLE_ENTITY)
_LOGGER.error("Latitude and longitude not specified.")
return Fals... | 19,073 |
def get_soup(page_url):
""" Returns BeautifulSoup object of the url provided """
try:
req = requests.get(page_url)
except Exception:
print('Failed to establish a connection with the website')
return
if req.status_code == 404:
print('Page not found')
return
co... | 19,074 |
def check_energybal(ec_dataset, timeseries=None, dailyaverage=False, monthlyaverage=False, monthly_cumulative=False):
"""
:param ec_dataset: the full dataset from the EC tower
:param timeseries: a series of datetimes
:return: a plot of the energy balance closure over time for the Eddy Covariance tower.... | 19,075 |
def foreign_key_constraint_sql(table):
"""Return the SQL to add foreign key constraints to a given table"""
sql = ''
fk_names = list(table.foreign_keys.keys())
for fk_name in sorted(fk_names):
foreign_key = table.foreign_keys[fk_name]
sql += "FOREIGN KEY({fn}) REFERENCES {tn}({kc}), ".fo... | 19,076 |
def expandDimConst(term: AST.PPTerm,
ntId: int) -> Optional[AST.PPTerm]:
"""
Expand dimension constant to integer constants (Required for fold zeros)
"""
nt = ASTUtils.getNthNT(term, ntId)
if type(nt.sort) != AST.PPDimConst:
return None
subTerm = AST.PPIntConst(nt.sor... | 19,077 |
def _fit_amplitude_scipy(counts, background, model, optimizer='Brent'):
"""
Fit amplitude using scipy.optimize.
Parameters
----------
counts : `~numpy.ndarray`
Slice of count map.
background : `~numpy.ndarray`
Slice of background map.
model : `~numpy.ndarray`
Model t... | 19,078 |
def account_key__sign(data, key_pem=None, key_pem_filepath=None):
"""
This routine will use crypto/certbot if available.
If not, openssl is used via subprocesses
:param key_pem: (required) the RSA Key in PEM format
:param key_pem_filepath: (optional) the filepath to a PEM encoded RSA account key fi... | 19,079 |
def get_world_paths() -> list:
"""
Returns a list of paths to the worlds on the server.
"""
server_dir = Path(__file__).resolve().parents[1]
world_paths = []
for p in server_dir.iterdir():
if p.is_dir and (p / "level.dat").is_file():
world_paths.append(p.absolute())
retur... | 19,080 |
def xml_ff_bond_force(data, prm, ff_prefix):
"""
Add Bond Force into Element (data)
Parameters
----------
data : xml.etree.ElementTree.Element
prm : OpenMM.AmberPrmtop
ff_prefix : string
"""
bnd_k0 = prm._raw_data["BOND_FORCE_CONSTANT"]
bnd_r0 = prm._raw_data["BOND_EQUIL_VALUE... | 19,081 |
def derivative_p(α_L, α_G, ρ_G, v_L, v_G): # (1)
"""
Calculates pressure spatial derivative to be pluged into the expression for
pressure at the next spatial step (see first equation of the model). It
returns the value of pressure spatial derivative at the current time step
and, hence, t... | 19,082 |
def write_populate_schemas(writer):
"""
Writes out a __SCHEMAS dict which contains all RecordSchemas by their full name. Used by get_schema_type
:param writer:
:return:
"""
writer.write('\n__SCHEMAS = dict((n.fullname.lstrip("."), n) for n in six.itervalues(__NAMES.names))\n') | 19,083 |
def fit_sigmoid(colors, a=0.05):
"""Fits a sigmoid to raw contact temperature readings from the ContactPose dataset. This function is copied from that repo"""
idx = colors > 0
ci = colors[idx]
x1 = min(ci) # Find two points
y1 = a
x2 = max(ci)
y2 = 1-a
lna = np.log((1 - y1) / y1)
... | 19,084 |
def deprecated(func):
"""Decorator for reporting deprecated function calls
Use this decorator sparingly, because we'll be charged if we make too many Rollbar notifications
"""
@wraps(func)
def wrapped(*args, **kwargs):
# try to get a request, may not always succeed
request = get_cur... | 19,085 |
def read_file(path_file: path) -> str:
"""
Reads the content of the file at path_file
:param path_file:
:return:
"""
content = None
with open(path_file, 'r') as file:
content = file.read()
return content | 19,086 |
def absorptionCoefficient_Voigt(Components=None,SourceTables=None,partitionFunction=PYTIPS,
Environment=None,OmegaRange=None,OmegaStep=None,OmegaWing=None,
IntensityThreshold=DefaultIntensityThreshold,
OmegaWingHW=DefaultOme... | 19,087 |
def stellar_mags_scatter_cube_pair(file_pair, min_relative_flux=0.5, save=False):
"""Return the scatter in stellar colours within a star datacube pair."""
hdulist_pair = [pf.open(path, 'update') for path in file_pair]
flux = np.vstack(
[hdulist[0].data for hdulist in hdulist_pair])
noise = np.sq... | 19,088 |
def get_data_filename(relative_path):
"""Get the full path to one of the reference files shipped for testing
In the source distribution, these files are in ``examples/*/``,
but on installation, they're moved to somewhere in the user's python
site-packages directory.
Parameters
----------
r... | 19,089 |
def is_valid_webhook_request(webhook_token: str, request_body: str, webhook_signature_header: str) -> bool:
"""This method verifies that requests to your Webhook URL are genuine and from Buycoins.
Args:
webhook_token: your webhook token
request_body: the body of the request
webhook_sign... | 19,090 |
def logsigsoftmax(logits):
"""
Computes sigsoftmax from the paper - https://arxiv.org/pdf/1805.10829.pdf
"""
max_values = torch.max(logits, 1, keepdim=True)[0]
exp_logits_sigmoided = torch.exp(logits - max_values) * torch.sigmoid(logits)
sum_exp_logits_sigmoided = exp_logits_sigmoided.sum(1, kee... | 19,091 |
def multi(dispatch_fn):
"""Initialise function as a multimethod"""
def _inner(*args, **kwargs):
return _inner.__multi__.get(
dispatch_fn(*args, **kwargs),
_inner.__multi_default__
)(*args, **kwargs)
_inner.__multi__ = {}
_inner.__multi_default__ = lambda *args, *... | 19,092 |
def choose_key(somemap, default=0, prompt="choose", input=input, error=default_error,
lines=LINES, columns=COLUMNS):
"""Select a key from a mapping.
Returns the key selected.
"""
keytype = type(print_menu_map(somemap, lines=lines, columns=columns))
while 1:
try:
us... | 19,093 |
def delete_nodes(ctx, name, node_names, force):
"""Delete node(s) in a cluster that uses native Kubernetes provider."""
try:
restore_session(ctx)
client = ctx.obj['client']
cluster = Cluster(client)
result = cluster.delete_nodes(ctx.obj['profiles'].get('vdc_in_use'),
... | 19,094 |
def test_validate_err():
"""An erroneous Thing Description raises error on validation."""
update_funcs = [
lambda x: x.update({"properties": [1, 2, 3]}) or x,
lambda x: x.update({"actions": "hello-interactions"}) or x,
lambda x: x.update({"events": {"overheating": {"forms": 0.5}}}) or x... | 19,095 |
def set_api_key(token_name, api_key, m=None):
"""Sets an API key as an environment variable.
Args:
token_name (str): The token name.
api_key (str): The API key.
m (ipyleaflet.Map | folium.Map, optional): A Map instance.. Defaults to None.
"""
os.environ[token_name] = api_key
... | 19,096 |
def test_dist(ctx):
"""Test both sdist and bdist wheel and install."""
test_sdist(ctx)
test_bdist_wheel(ctx) | 19,097 |
def test_pds4_orbnum_generated_list(self):
"""Test inclusion of ORBNUM in kernel list.
Test ORBNUM file generation with automatic plan generation, when the
plan is not provided by the user.
"""
post_setup(self)
config = "../config/maven.xml"
shutil.copy(
"../data/misc/orbnum/maven_... | 19,098 |
def _ValidateFieldValues(field_values,
metadata):
"""Checks that the given sequence of field values is valid.
Args:
field_values: A sequence of values for a particular metric's fields.
metadata: MetricMetadata for the metric. The order of fields in the metadata
should match t... | 19,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.