content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def signout(request):
"""Logs out user"""
from django.contrib.auth import logout
logout(request)
return redirect('/') | 5,321,600 |
def _get_cached_item(cache_key):
"""Returns an item from memcache if cached
"""
return memcache.get() | 5,321,601 |
def format_dnb_company_investigation(data):
"""
Format DNB company investigation payload to something
DNBCompanyInvestigationSerlizer can parse.
"""
data['dnb_investigation_data'] = {
'telephone_number': data.pop('telephone_number', None),
}
return data | 5,321,602 |
def audio_feat(id):
"""
Return audio features of a track.
search_id[0]['insert_feature_here']
id="4nb8OcZG8lpnHi5DmkEnY2" #Sample ID
audio_feat("4nb8OcZG8lpnHi5DmkEnY2")
:param id:
:return:
"""
return sp.audio_features(tracks=id) | 5,321,603 |
def get_results_dir(tomo_path):
"""Return/Create the results directory"""
res_dir = os.path.abspath(tomo_path)+"_results"
common.mkdir_p(res_dir)
return res_dir | 5,321,604 |
def params_v2_biasless(exp_name, convtype='chebyshev5', pooltype='max', nmaps=16,
activation_func='relu', stat_layer=None, input_channels=1,
gc_depth=8, nfilters=64,
const_k=5, var_k=None,
filters=None, batch_norm_output=False,
... | 5,321,605 |
def get_ccd_pos(filename, radec=None, verbose=True):
"""
Parameters
----------
"""
astrom_file = io.filename_to_guider(filename)
if len(astrom_file)==0:
if verbose:
print("No astrom file found for %s"%filename)
return [np.NaN,np.NaN]
astrom_file = astrom_file[0... | 5,321,606 |
def mode2(data,v0,v1, dmin=0.0):
""" v0..v1 (both inclusive) are channel selections
threshold on dmin
for odd number of channels, center line in mode2 will be same as mode1
@todo the frequency axis is not properly calibrated here
@todo a full 2D is slow, we only need the 1D version
... | 5,321,607 |
def learning_curve(estimator, X, y, groups=None,
train_sizes=np.linspace(0.1, 1.0, 5), cv=None, scoring=None,
exploit_incremental_learning=False, n_jobs=1,
pre_dispatch="all", verbose=0, shuffle=False,
random_state=None):
"""Learning curve.... | 5,321,608 |
def test_Image_et_fraction_elr_param(lst, ndvi, dt, elev, tcorr, tmax, elr_flag,
expected, tol=0.0001):
"""Test that elr_flag works and changes ETf values"""
output_img = default_image_obj(
lst=lst, ndvi=ndvi, dt_source=dt, elev_source=elev,
tcorr_source=tcor... | 5,321,609 |
def directed_dfs(digraph, start, end, max_total_dist, max_buildings):
"""
Finds the shortest path from start to end using a directed depth-first
search. The total distance traveled on the path must not
exceed max_total_dist, and the number of buildings on this path must
not exceed max_buildings.
... | 5,321,610 |
def zeta(z, x, beta2):
"""
Eq. (6) from Ref[1] (constant term)
Note that 'x' here corresponds to 'chi = x/rho',
and 'z' here corresponds to 'xi = z/2/rho' in the paper.
"""
return 3 * (4* z**2 - beta2 * x**2) / 4 / beta2 / (1+x) | 5,321,611 |
def getCountry(user):
"""
Returns the object the view is displaying.
"""
# get users country from django cosign module
user_countries = TolaUser.objects.all().filter(user__id=user.id).values('countries')
get_countries = Country.objects.all().filter(id__in=user_countries)... | 5,321,612 |
def test_create(km_user_factory):
"""
Test creating a profile.
"""
models.Profile.objects.create(
is_private=True, km_user=km_user_factory(), name="My Profile"
) | 5,321,613 |
def calculate_relative_enrichments(results, total_pathways_by_resource):
"""Calculate relative enrichment of pathways (enriched pathways/total pathways).
:param dict results: result enrichment
:param dict total_pathways_by_resource: resource to number of pathways
:rtype: dict
"""
return {
... | 5,321,614 |
def _import_config(config_dict, validating=False):
"""Applies a previously exported configuration to the current system.
This method only exists to decouple the import logic from the atomic transaction so that this method can be reused
for validation without making any permanent changes.
:param config... | 5,321,615 |
def clean_name(name):
"""Clean a name string
"""
# flip if in last name, first name format
tokens = name.split(',')
if len(tokens) == 2:
first, last = tokens[1], tokens[0]
else:
first, last = name.split(' ')[:2]
# remove punctuation
first_clean = first.strip().capitaliz... | 5,321,616 |
def find_prime(num_bits: int) -> int:
"""Find a prime represented with given number of bits.
Generates random numbers of given size until one of them is deemed prime by
a probabilistic primality check.
Args:
num_bits: size of the prime in terms of bits required for representing it
Return... | 5,321,617 |
def UnpackS8(buf, offset=0, endian='big'):
""" Unpack an 8-bit signed integer into 1 byte.
Parameters:
buf - Input packed buffer.
offset - Offset in buffer.
endian - Byte order.
Return:
2-tuple of unpacked value, new buffer offset.
"""
try:
return (str... | 5,321,618 |
def estimator(data):
""" Provide the estimate calulations based on that data received """
#Collect required data from data imput
impact = {}
severeImpact = {}
reportedCases = data['reportedCases']
periodType = data['periodType']
timeToElapse = data['timeToElapse']
totalHospitalBeds = data['totalHospital... | 5,321,619 |
def diff_align(dfs, groupers):
""" Align groupers to newly-diffed dataframes
For groupby aggregations we keep historical values of the grouper along
with historical values of the dataframes. The dataframes are kept in
historical sync with the ``diff_loc`` and ``diff_iloc`` functions above.
This fu... | 5,321,620 |
def numero_magico(sock):
"""Regresa un numero aleatorio a un usuario"""
numero = random.randint(1,11)
mensaje = "Tu numero magico es: {0}".format(numero)
chat(sock, mensaje) | 5,321,621 |
def args_kwargs(a, b, *args, **kwargs):
"""Function with args and kwargs"""
pass | 5,321,622 |
async def main(session):
"""
Test remote management of Docker running on a CF node.
"""
nodes = await session.call(
u'crossbarfabriccenter.mrealm.get_nodes', status=u'online')
for node_id in nodes:
node_status = await session.call(
u'crossbarfabriccenter.remote.node.get_... | 5,321,623 |
def get_usage_data(
es_client, start_date, end_date, match_terms={}, addl_cols=[], index="path-schedd-*"
):
"""Returns rows of usage data"""
default_cols = [
"Owner",
"ScheddName",
"GlobalJobId",
"RecordTime",
"RemoteWallClockTime",
"RequestCpus",
"Cp... | 5,321,624 |
def check_email_address_validity(email_address):
"""Given a string, determine if it is a valid email address using Django's validate_email() function."""
try:
validate_email(email_address)
valid_email = True
except ValidationError:
valid_email = False
return valid_email | 5,321,625 |
def _GetHostConfigs(lab_config_pool, hosts_or_clusters):
"""Get host configs for clusters.
Args:
lab_config_pool: a lab config pool
hosts_or_clusters: a list of hosts or clusters.
Returns:
a list of HostConfigs.
"""
if not hosts_or_clusters:
return lab_config_pool.GetHostConfigs()
host_conf... | 5,321,626 |
def test_argmax_single_max(depths):
"""argmax return expected indices for single max value
"""
depths = np.zeros((5, 3))
depths[1, 2] = 42
result = bathy_tools.argmax(depths)
assert result == (1, 2) | 5,321,627 |
def load_targets_file(input_file):
"""
Takes a string indicating a file name and reads the contents of the file.
Returns a list containing each line of the file.
Precondition: input_file should exist in the file system.
"""
with open(input_file, 'r') as f:
f = f.readlines()
out = [i.replace('\n','').replace('\... | 5,321,628 |
def test_upsample_in_time_drift(resample_in_time_file):
"""Test the upsample_in_time method on drift mode data"""
uv_object = resample_in_time_file
# reorder to make sure we get the right value later
uv_object.reorder_blts(order="baseline")
# save some values for later
init_data_size = uv_obje... | 5,321,629 |
def plot_avg_profile(rad_dict, ylim=[0, None]):
"""
Function for plotting up average profiles including differences
Parameters
----------
rad_dict : dict
Dictionary of objects and variables to process. See example
ylim : list
ylimits to use
Returns
-------
ax : mat... | 5,321,630 |
def localized_dt_string(dt, use_tz=None):
"""Convert datetime value to a string, localized for the specified timezone."""
if not dt.tzinfo and not use_tz:
return dt.strftime(DT_NAIVE)
if not dt.tzinfo:
return dt.replace(tzinfo=use_tz).strftime(DT_AWARE)
return dt.astimezone(use_tz).strft... | 5,321,631 |
def parse_command_line():
"""Parses the command line
"""
try:
opts, remaining_args = getopt.getopt(sys.argv[1:], "ihvosmdextn",
["input=", "help", "verbose", "version", "output=", "strict",
"dump-missed-files=", "search=", "explicit-dependencies=",
"match-exec... | 5,321,632 |
def dissolve_project_data(project_data):
"""
This functions uses the unionCascaded function to return a dissolved MultiPolygon geometry
from several Single Part Polygon geometries.
"""
multipolygon_geometry = ogr.Geometry(ogr.wkbMultiPolygon)
for item in project_data:
polygon = ogr.Crea... | 5,321,633 |
def get_visit_exposure_footprints(visit_file='j1000p0210_visits.npy', check_paths=['./', '../RAW'], simplify=1.e-6):
"""
Add exposure-level footprints to the visit dictionary
Parameters
----------
visit_file : str
File produced by `parse_visits` (`visits`, `all_groups`, `info`).
... | 5,321,634 |
def pega_salada_sobremesa_suco(items):
""" Funcao auxiliar que popula os atributos salada, sobremesa e suco do cardapio da refeicao fornecida."""
alimentos = ["salada", "suco", "sobremesa"]
cardapio = {}
for alim in alimentos:
tag = alim.upper() + ":" # tag para procurar o cardapio dos alimento... | 5,321,635 |
def close_connection(client):
"""
Parameters
----------
client : clickhouse connector. Client object of clickhouse_driver.client module
Check if connection exists. If yes, closes it.
Returns
-------
None.
"""
if len(client.execute("SELECT 1")) > 0:
client.disconne... | 5,321,636 |
async def test_download_artifact_cache(
error, spawn_job_client, pg: AsyncEngine, tmp_path
):
"""
Test that a sample artifact cache can be downloaded using the Jobs API.
"""
client = await spawn_job_client(authorize=True)
client.app["config"].data_path = tmp_path
key = "aodp-abcdefgh"
... | 5,321,637 |
def readRGBImg(datapath, driver="GTiff"):
"""
Reads image path and returns 3-D numpy matrix of RGB image.
:param datapath: Path/String
Image path that is opened by rasterio.
:param driver: String
GDAL driver for opening the image. Default: 'GTiff'.
:return: rasterio data, Ndarray
... | 5,321,638 |
def set_unw_zeros(unw_filename, ifg_filename):
"""Set areas that are 0 in the ifg to be 0 in the unw"""
tmp_file = unw_filename.replace(".unw", "_tmp.unw")
cmd = (
f"gdal_calc.py --quiet --outfile={tmp_file} --type=Float32 --format=ROI_PAC "
f'--allBands=A -A {unw_filename} -B {ifg_filename}... | 5,321,639 |
def show_hidden_word(secret_word, old_letters_guessed):
"""
:param secret_word:
:param old_letters_guessed:
:return: String of the hidden word except the letters already guessed
"""
new_string = ""
for letter in secret_word:
if letter in old_letters_guessed:
new_string = ... | 5,321,640 |
def test_run_simulation_time_to_quit(collaborator_mock):
"""Test that run_simulation works correctly if is time to quit."""
round_number = 0
collaborator_mock.get_tasks = mock.Mock(return_value=([], round_number, 0, True))
collaborator_mock.run_simulation() | 5,321,641 |
def hello_world_tensorflow():
"""This is the TensorFlow command component"""
print("Hello World!") | 5,321,642 |
def parse_args(args: list) -> dict:
"""
Create a parser for command line attributes and parses them
:param args: the arguments to parse
:return: parsed arguments
"""
parser = SmartArgumentParser(
description="Triggers some bug in listed programs", parents=[arguments.get_verbosity_parser(... | 5,321,643 |
def test_validate_address():
"""Test the is_valid_address functionality."""
account = CosmosCrypto()
assert CosmosApi.is_valid_address(account.address)
assert not CosmosApi.is_valid_address(account.address + "wrong") | 5,321,644 |
def get_cas_user(tree):
"""
Callback invoked by the CAS module that ensures that the user signing in via CAS has a valid Django User associated
with them. Primary responsibility is to create a Django User / Participant if none existed, or to associate the CAS
login id with the given User. This needs to ... | 5,321,645 |
def get_total_gap(data : np.ndarray) -> float:
"""
Computes the total gap in time units for a given dataset
:param data: datset of the lightcurve
:return: total gap in units of time
"""
values,counts,most_common = get_diff_values_counts_most_common(data)
values[values - most_common < 10**-5... | 5,321,646 |
def print_srt_line(i, elms):
"""Print a subtitle in srt format."""
return "{}\n{} --> {}\n{}\n\n".format(i, format_srt_time(elms[0]),
format_srt_time(float(elms[0]) +
float(elms[1])),
... | 5,321,647 |
def depthwise_separable_conv(inputs,
num_pwc_filters,
width_multiplier,
scope,
downsample=False):
"""Depth-wise separable convolution."""
num_pwc_filters = round(num_pwc_filters * width_multiplier)
... | 5,321,648 |
def filter_packages(packages: list, key: str) -> list:
"""Filter out packages based on the given category."""
return [p for p in packages if p["category"] == key] | 5,321,649 |
def ptlinear(x, W, b=None, b2=None, is_pre_training=False, activation=None):
"""Pre trainable Linear function, or affine transformation.
It accepts two or three arguments: an input minibatch ``x``, a weight
matrix ``W``, and optionally a bias vector ``b``. It computes
:math:`Y = xW^\top + b`.
Args... | 5,321,650 |
def cubic_bezier(pts, t):
"""
:param pts:
:param t:
:return:
"""
p0, p1, p2, p3 = pts
p0 = pylab.array(p0)
p1 = pylab.array(p1)
p2 = pylab.array(p2)
p3 = pylab.array(p3)
return p0 * (1 - t) ** 3 + 3 * t * p1 * (1 - t) ** 2 + \
3 * t ** 2 * (1 - t) * p2 + t ** 3 * p3 | 5,321,651 |
def DeleteVolume(gluster_server, volume_name):
"""Stops and deletes a Gluster volume."""
gluster_server.RemoteCommand(
'yes | sudo gluster volume stop %s' % volume_name)
gluster_server.RemoteCommand(
'yes | sudo gluster volume delete %s' % volume_name) | 5,321,652 |
def test_subject_is_not_str_exception():
"""
Provides connection_string in an invalid format, and checks if the correct exception is thrown.
"""
topic_name = 'test'
subject = 123
with override_settings(
METROID={
'subscriptions': [
{
'topi... | 5,321,653 |
def p_statement(p):
"""statement : labeled_statement
| compound_statement
| expression_statement
| selection_statement
| iteration_statement
| jump_statement
""" | 5,321,654 |
def _GetServerComponentArgs(config_path: str) -> List[str]:
"""Returns a set of command line arguments for server components.
Args:
config_path: Path to a config path generated by
self_contained_config_writer.
Returns:
An iterable with command line arguments to use.
"""
primary_config_path = ... | 5,321,655 |
def random_string(length=4):
"""Generates a random string based on the length given
Keyword Arguments:
length {int} -- The amount of the characters to generate (default: {4})
Returns:
string
"""
return "".join(
random.choice(string.ascii_uppercase + string.digits) for _ in... | 5,321,656 |
def FindBySummaryName(name):
"""
Find the first instance of a virtual machine with the specified name.
"""
vms = GetAll()
for vm in vms:
try:
summary = vm.GetSummary()
config = summary.GetConfig()
if config != None and config.GetName() == name:
return vm
... | 5,321,657 |
def setup_training(model, train_loader, valid_loader, valset, hps, test_loader):
""" Does setup before starting training (run_training)
:param model: the model
:param train_loader: train dataset loader
:param valid_loader: valid dataset loader
:param valset: valid dataset which ... | 5,321,658 |
def get_potential_trace_fields(poly,sln=2):
"""Given a minimal polynomial of a trace field, returns a list of minimal polynomials of the potential invariant trace fields."""
pol = pari(poly)
try:
return [str(rec[0].polredabs()) for rec in pol.nfsubfields()[1:] if _knmiss(rec[0].poldegree(),pol.polde... | 5,321,659 |
def get_movielens(path=None, variant="ml-25m"):
"""Gets the movielens dataset for use with merlin-models
This function will return a tuple of train/test merlin.io.Dataset objects for the
movielens dataset. This will download the movielens dataset locally if needed,
and run a ETL pipeline with NVTabular... | 5,321,660 |
def launch():
"""Initialize the module."""
return UERRCMeasurementsWorker(UERRCMeasurements, PRT_UE_RRC_MEASUREMENTS_RESPONSE) | 5,321,661 |
def settings(user):
"""
Print HTMap's current settings.
By default, this command shows the merger of your user settings from
~/.htmaprc and HTMap's own default settings. To show only your user
settings, pass the --user option.
"""
if not user:
click.echo(str(htmap.settings))
els... | 5,321,662 |
def enlarge_histogram(file = None,filename = None):
"""
Arguments:
file: an image file that is going to be processed
filename: a filename of the file to be processed
Returns:
The same input image but with its histogram enlarged.
"""
if file is None and filename... | 5,321,663 |
def task(n):
"""Return 2 to the n'th power"""
return 2 ** n | 5,321,664 |
def save_npy(object, handle):
"""Save numpy array as npy file."""
np.save(handle, object) | 5,321,665 |
def create_splits(dataframe, split_path, n_splits = 10) :
"""
Should i reset index ?
"""
length = int(dataframe.shape[0] / int(n_splits))
for i in range(n_splits) :
frame = dataframe.iloc[i*length:(i+1)*length]
if i == n_splits-1 :
frame = dataframe.iloc[i*length:]
... | 5,321,666 |
def get_relationship(context, user_object):
"""caches the relationship between the logged in user and another user"""
user = context["request"].user
return get_or_set(
f"relationship-{user.id}-{user_object.id}",
get_relationship_name,
user,
user_object,
timeout=259200... | 5,321,667 |
def test_create_all_slabs(generate_structure):
"""Test if create_all_slabs"""
from aiida_fleur.tools.StructureData_util import create_all_slabs
from aiida.orm import StructureData
structure = generate_structure()
film_strucs = create_all_slabs(structure, 2, 5)
assert len(film_strucs.keys()) ==... | 5,321,668 |
def _ts_midpoint(x1, d: int):
"""moving midpoint: (ts_max + ts_min) / 2"""
return _ts_max(x1, d) + _ts_min(x1, d) | 5,321,669 |
def maybe_delivery_mode(
v, modes=DELIVERY_MODES, default=PERSISTENT_DELIVERY_MODE):
"""Get delivery mode by name (or none if undefined)."""
if v:
return v if isinstance(v, numbers.Integral) else modes[v]
return default | 5,321,670 |
def load_pairs(path: str) -> list:
"""
Loads the pairs specified in a file in the format of "word1 word2" separated by new line.
:param path: Path to the file containing the pairs.
:return: The list of unique tuples contained in the file, but not their inverse counterpart as opposed to
load_constrai... | 5,321,671 |
def load_image_into_numpy_array(path):
"""Load an image from file into a numpy array.
Puts image into numpy array to feed into tensorflow graph.
Note that by convention we put it into a numpy array with shape
(height, width, channels), where channels=3 for RGB.
Args:
path: the file path to the i... | 5,321,672 |
def is_illumina_run(run_dir):
"""
Detects signature files in the run directory (eg RunInfo.xml) to detemine
if it's likely to be an Illumina sequencing run or not.
:param run_dir: The path to the run.
:type run_dir: str
:return: True if it looks like an Illumina run.
:rtype: bool
"""
... | 5,321,673 |
def get_data_filepath(filename):
"""Construct filepath for a file in the test/data directory
Args:
filename: name of file
Returns:
full path to file
"""
return os.path.join(os.path.dirname(__file__), 'data', filename) | 5,321,674 |
def write_menu(date, sname, name, menu, path, file):
"""Append data to output file passed as path, file"""
file_name = path + file
with open(file_name, "a") as csv_file:
writer = csv.writer(csv_file, delimiter=',')
for item, price in menu.items():
line = (date, sname, n... | 5,321,675 |
def polo_return_chart_data(currency_pair,
start_unix=None,
end_unix=None,
period_unix=14400,
format_dates=True,
to_frame=True):
"""
Returns public exchange data for the given
... | 5,321,676 |
def ergtoboatspeed(min,sec,ratio,crew,rigging,erg):
""" Calculates boat speed, given an erg split for given crew, boat, erg
"""
res = ergtopower(min,sec,ratio,crew,erg)
pw = res[0]
res = constantwatt(pw,crew,rigging)
return res | 5,321,677 |
def parse_args(args):
"""Parse command line arguments.
"""
parser = argparse.ArgumentParser(description='Generate Shadow Hashes')
parser.add_argument('-m', '--method', default='SHA512',
choices=shadow.HASH_METHODS,
help='Hashing method to use, default is S... | 5,321,678 |
def interval_range(
start=None, end=None, periods=None, freq=None, name=None, closed="right",
) -> "IntervalIndex":
"""
Returns a fixed frequency IntervalIndex.
Parameters
----------
start : numeric, default None
Left bound for generating intervals.
end : numeric , default None
... | 5,321,679 |
def get_summary_description(node_def):
"""Given a TensorSummary node_def, retrieve its SummaryDescription.
When a Summary op is instantiated, a SummaryDescription of associated
metadata is stored in its NodeDef. This method retrieves the description.
Args:
node_def: the node_def_pb2.NodeDef of a TensorSum... | 5,321,680 |
def _einsum_kronecker_product(*trans_mats):
"""Compute a Kronecker product of multiple matrices with :func:`numpy.einsum`.
The reshape is necessary because :func:`numpy.einsum` produces a matrix with as many
dimensions as transition probability matrices. Each dimension has as many values as
rows or col... | 5,321,681 |
def add_coin(user, coin):
"""
Update trade instance with coin preference
"""
trade = get_recent_trade(user)
trade.coin = str(coin)
if coin == "BTC":
trade.receive_address_id = btc_account.create_address().id
elif coin == "ETH":
trade.receive_address_id = eth_account.create_a... | 5,321,682 |
def test_find(small_ll):
"""test to find in list"""
assert small_ll.find(1) is True | 5,321,683 |
def test_sample_tracks():
""" Test the function that creates case individual tracks """
# GIVEN a case with 3 samples alignments
sample_names = ["sample1", "sample2", "sample3"]
sample_bams = ["bam1", "bam2", "bam3"]
form_data = {
"sample": ",".join(sample_names),
"align": "bam",
... | 5,321,684 |
def calc_loss_class(true_box_conf, CLASS_SCALE, true_box_class, pred_box_class):
"""
== input ==
true_box_conf : tensor of shape (N batch, N grid h, N grid w, N anchor)
true_box_class : tensor of shape (N batch, N grid h, N grid w, N anchor), containing class index
pred_box_class : tensor of shape ... | 5,321,685 |
def compileMechanismList():
"""TODO Missing documentation"""
from bpy.types import WindowManager
from bpy.props import EnumProperty
# DOCU missing some docstring
global mechanismpreviewcollection
log("Compiling mechanism list from local library...", "INFO")
try:
phobosconfig = bU... | 5,321,686 |
def checkForFiles(options):
""" If files are missing, complains and dies.
"""
lsc.verifyDirExists(os.path.join(options.rootInputDir, 'stats'))
for f in [os.path.join(options.rootInputDir, 'seq.rev'),
os.path.join(options.rootInputDir, 'annots.gff'),
os.path.join(options.par... | 5,321,687 |
def unmixGradProjMatrixNNLS(image, A, tolerance=1e-4, maxiter=100):
"""
Performs NNLS via Gradient Projection of the primal problem.
Terminates when duality gap falls below tolerance
"""
if image.ndim == 2:
(n1, n3) = image.shape
n2 = 1;
elif image.ndim == 3:
(n1, n2, n3)... | 5,321,688 |
def seismic():
"""Benchmark Seismic object."""
# coords = [{"x": np.arange(10)}, {"y": np.arange(10)}, {"z": np.arange(100)}]
coords = [("x", np.arange(10)), ("y", np.arange(10)), ("z", np.arange(100))]
cube = segyio.tools.cube("../data/test.segy")
# seis = from_segy("tests/data/test.segy")
retu... | 5,321,689 |
def sterrmean(s, n, N=None):
"""sterrmean(s, n [, N]) -> standard error of the mean.
Return the standard error of the mean, optionally with a correction for
finite population. Arguments given are:
s: the standard deviation of the sample
n: the size of the sample
N (optional): the size of the p... | 5,321,690 |
def doubleProfileBirailSurface(*args, **kwargs):
"""
The arguments are 4 cuves called "profile1" "profile2" "rail1" "rail2".
Returns: `string[]` Object name and node name
"""
pass | 5,321,691 |
def change_device_status(dispatcher, device_name, status):
"""Set the status of a device in Nautobot."""
if menu_item_check(device_name):
prompt_for_device(
"nautobot change-device-status",
"Change Nautobot Device Status",
dispatcher,
offset=menu_offset_va... | 5,321,692 |
def text_to_vector(sentences):
"""
#使用one-hot方法将文本转为向量, 例如:
Sentence1 不 知道 你 在 说 什么 。
Sentence2 我 就 知道 你 不 知道 。
词表: 不 就 你 什么 我 说 知道 在 。
S1 [1 0 1 1 0 1 1 1 1]
S2 [1 1 1 0 1 0 2 0 1]
即得到分词后的句子之后,先得到词表
每个词对应一个位置,如“不”对应第一个位置,等等
如果s1出现了不一次,就把s1的第一个位置设为1,如果没有出现就是0,
如果出现了两次“不”,那么s1的第一个位置就是2,以此类推
"""
# 先将所... | 5,321,693 |
def test_01():
"""
test
"""
file_name = pattern02.__file__
module = ast_util.create_ast(file_name)
pkg, mdn = files.get_package_moduel(file_name)
t_func = ast_util.get_function(module)[0]
calls = ast_util.get_calls(t_func)
has_return = ast_util._has_return_call(calls[0].ats, t_func)... | 5,321,694 |
def _list_valid_filenames_in_directory(
base_directory:str,
search_class:str,
white_list_formats:List[str],
split:float,
follow_links:bool,
shuffle_index_directory:str
) -> Tuple[str, List[str]]:
"""File all files in the search directory for the specified class
if shuffle_index_dir... | 5,321,695 |
def create_pull_group_ndx(ref_pdb, sel="name CA", save_as="pull_group.ndx"):
"""
Create index file for pull group.
Args:
ref_pdb (str): PDB file (after applying force field)
sel (str): selection string
save_as (str)
"""
RESID, RESNAME, ATOM, NAME = _top.parsePDB(ref_pdb, sel... | 5,321,696 |
def benchmark_memory(nb_registers, element_width, nb_elements, nb_operations, write_op=False):
"""
This method generate the P4 program to benchmark memory consumption
:param nb_registers: the number of registers included in the program
:type nb_registers: int
:param element_width: the size of each ... | 5,321,697 |
def get_custom_activations_dict():
"""
Import all implemented custom activation functions so they can be used when
loading a Keras model.
"""
from snntoolbox.utils.utils import binary_sigmoid, binary_tanh, ClampedReLU
# Todo: We should be able to load a different activation for each layer.
... | 5,321,698 |
def test_ncp_cat_input_samples(make_categories):
"""Test we are making the ncp extra samples correctly."""
x, K = make_categories
pflip = 0.5
pcats = 1. / K
pdiff = pflip * (1 - pcats)
net = (
ab.InputLayer(name='X', n_samples=1) >>
ab.NCPCategoricalPerturb(flip_prob=pflip, n_c... | 5,321,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.