content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def _urlparse_qs(url):
"""
Parse a URL query string and return the components as a dictionary.
Based on the cgi.parse_qs method.This is a utility function provided
with urlparse so that users need not use cgi module for
parsing the url query string.
Arguments:
:type url: str
:param ur... | 5,288,900 |
async def viewwel(msg: Message):
""" view welcome message """
await raw_view(msg, 'Welcome', WELCOME_COLLECTION) | 5,288,901 |
def erfc_inverse(x):
""" erfc-1(x) = - 1/sqrt(2) * normal_quantile( 0.5 * x)"""
return -0.70710678118654752440 * normal_quantile(0.5 * x) | 5,288,902 |
def websocket_automation_trace_list(hass, connection, msg):
"""Summarize automation traces."""
automation_traces = get_debug_traces(hass, summary=True)
connection.send_result(msg["id"], automation_traces) | 5,288,903 |
def extract_8_statistical_features(data):
"""
Extract 8 statistical features: mean, standard deviation, length,
minimum val, first quartile, second quartile,
third quartile, maximum val
:parameter data: pandas DataFrame of the data who... | 5,288,904 |
def check_required_sections(scheduler_config):
"""
Check the sections that must be configured.
:param scheduler_config: (dict) The scheduler configuration in ../conf/scheduler.yml.
"""
for section in REQUIRED_CONFIG_SECTIONS:
if section not in scheduler_config:
LOGGER.error("sec... | 5,288,905 |
def bin_stats(x, y, xbins, stat='average'):
"""Given the variable y=f(x), and
the bins limits xbins, return the
corresponding statistics, e.g. <y(xbins)>
Options are rms, median y average
"""
nbins = len(xbins)
if stat == 'average' or stat == 'mean': func = mean
elif stat == 'median': ... | 5,288,906 |
def all_unique(lst):
"""Returns True if all elements of Sequence `lst` are unique.
False otherwise.
"""
assert isinstance(lst, Sequence)
return bool(len(set(lst)) == len(lst)) | 5,288,907 |
def ingredient_fractions_predictor() -> IngredientFractionsPredictor:
"""Build a Ingredient Fractions predictor for testing."""
return IngredientFractionsPredictor(
name='Ingredient fractions predictor',
description='Computes total ingredient fractions',
input_descriptor=formulation,
... | 5,288,908 |
def record_fuzz_target(engine, binary_name, job_type):
"""Record existence of fuzz target."""
if not binary_name:
logs.log_error('Expected binary_name.')
return None
project = data_handler.get_project_name(job_type)
key_name = data_types.fuzz_target_fully_qualified_name(
engine, project, binary_n... | 5,288,909 |
def gdal_raster_reproject(file_in, file_out, crs_out, crs_in = None):
"""wrapper around gdalwarp for reprojecting rasters
Parameters
---------
file_in: string
file path of input raster
file_out: string
file path of output raster
crs_out: string
EPS... | 5,288,910 |
def test_sample_square_part(
image: np.ndarray, internal_size: int, padding_size: int,
possible_outputs: List[np.ndarray]
) -> None:
"""Test `sample_square_part` function."""
output = dd.sample_square_part(image, internal_size, padding_size)
assert any([np.array_equal(output, arr) for arr in... | 5,288,911 |
def svm_loss(x: NPArray, y: NPIntArray) -> tuple[float, NPArray]:
"""
Computes the loss and gradient using for multiclass SVM classification.
Inputs:
- x: Input data, of shape (N, C) where x[i, j] is the score for the jth class
for the ith input.
- y: Vector of labels, of shape (N,) where y[i... | 5,288,912 |
def test_allowed_hosts_and_schemes(uri, failed_component):
"""Verify each of these fails."""
validator = (
validators.Validator()
.allow_schemes(
"https",
"ssh",
)
.allow_hosts(
"github.com",
"git.openstack.org",
)
)
... | 5,288,913 |
def make_constellation(config):
"""Builds the constellation model."""
n_caps = 3
encoder = SetTransformer(
n_layers=4,
n_heads=4,
n_dims=128,
n_output_dims=32,
n_outputs=n_caps,
layer_norm=True,
dropout_rate=0.,
)
decoder = ConstellationCapsule(
n_caps=n_caps... | 5,288,914 |
def fetch_file(remote, dirname=None):
"""Download a specific file and save it into the resources folder of the package.
Args:
remote: structure containing url, filename and checksum
dirname: absolute path where the file will be downloaded
Returns:
file_path: absolute file path
... | 5,288,915 |
def largest(min_factor, max_factor):
"""Given a range of numbers, find the largest palindromes which
are products of two numbers within that range.
:param min_factor: int with a default value of 0
:param max_factor: int
:return: tuple of (palindrome, iterable).
Iterable should conta... | 5,288,916 |
def scale_matrix(
factor: float,
origin: np.ndarray = None,
direction: np.ndarray = None
) -> np.ndarray:
"""
Return matrix to scale by factor around origin in direction.
Use factor -1 for point symmetry.
"""
if direction is None:
# uniform scaling
M = np.array(
... | 5,288,917 |
def plot_h(data, cols, wspace=.1, plot_kw=None, **kwargs):
"""
Plot horizontally
Args:
data: DataFrame of data
cols: columns to be plotted
wspace: spacing between plots
plot_kw: kwargs for each plot
**kwargs: kwargs for the whole plot
Returns:
axes for p... | 5,288,918 |
def generate_average_csv(fname, fields, trait_list):
""" Generate CSV called fname with fields and trait_list """
csv = open(fname, 'w')
csv.write(','.join(map(str, fields)) + '\n')
csv.write(','.join(map(str, trait_list)) + '\n')
csv.close()
return fname | 5,288,919 |
def skip_if_no_xpu(func):
""" oneCCL xpu tests require at least 1 XPU. Skip if this is not met"""
@wraps(func)
def wrapper(*args, **kwargs):
if not xpu_is_avaliable:
sys.exit(TEST_SKIPS["no_cuda"].exit_code)
# if torch.xpu.device_count() < int(os.environ["WORLD_SIZE"]):
#... | 5,288,920 |
def get_s2_patches_with_no_19_class_target() -> Set[str]:
"""
List all patches from the BigEarthNet-S2 dataset that
have _no_ defined classes with the 19-class nomenclature.
Note: This set still includes patches with snow, clouds, or shadows.
To re-build the file, it is necessary to use the output... | 5,288,921 |
def winnow_model(model: torch.nn.Module, input_shape: Tuple,
list_of_modules_to_winnow: List[Tuple[torch.nn.Module, List]] = None,
reshape=True, in_place=False, verbose=False):
""" This API is used to winnow a model with Conv2d modules that each have a list of channels to be winno... | 5,288,922 |
def main():
"""Go Main Go"""
hads = get_dbconn('hads')
mesosite = get_dbconn('mesosite')
hcursor = hads.cursor()
hcursor2 = hads.cursor()
mcursor = mesosite.cursor()
# look for unknown
hcursor.execute("""SELECT distinct nwsli, network from unknown
WHERE length(nwsli) = 5""")
... | 5,288,923 |
def sample_async_batch_annotate_images(
input_image_uri="gs://cloud-samples-data/vision/label/wakeupcat.jpg",
output_uri="gs://your-bucket/prefix/",
):
"""Perform async batch image annotation."""
client = vision_v1.ImageAnnotatorClient()
source = {"image_uri": input_image_uri}
image = {"source"... | 5,288,924 |
def get_expr_dict(input_tuple):
"""Returns the quantification results as a dict of dicts."""
bamfname, contig, start, stop, length, worker_ind = input_tuple
if worker_ind == None: worker_ind = 0
if contig is None:
desc_str='all_reads'
else:
desc_str='chr_'+contig
region = dict(
contig=contig,... | 5,288,925 |
def p_declaration_1(t):
"""declaration : type_specifier ID"""
t[1].id = t[2]
t[0] = t[1] | 5,288,926 |
def arg_parsing(req):
"""
:type req: class 'ow_lander.srv._Grind.GrindRequest'
"""
if req.use_defaults :
# Default trenching values
x_start = 1.65
y_start = 0.0
depth = 0.05
length = 0.6
parallel = True
ground_position = constants.DEFAULT_GROUND_HEIGHT
else :
x_start = req... | 5,288,927 |
def adjacency_lattice_square(sidelength, num_cells, search_radius, periodic_bc=False):
"""
periodic_bc: wrap around boundary condition (False default)
"""
assert num_cells == sidelength ** 2
adjacency_arr_uptri = np.zeros((num_cells, num_cells))
# build only upper diagonal part of A
for a in... | 5,288,928 |
def determine_aha_part(seg_sa, affine_sa, three_slices=False):
""" Determine the AHA part for each slice. """
# Label class in the segmentation
label = {'BG': 0, 'LV': 1, 'Myo': 2, 'RV': 3}
# Sort the z-axis positions of the slices with both endo and epicardium
# segmentations
X, Y, Z = seg_sa.... | 5,288,929 |
def _RemoveBreakpadKeys(plist):
"""Removes any set Breakpad keys."""
_RemoveKeys(plist, 'BreakpadURL', 'BreakpadReportInterval', 'BreakpadProduct',
'BreakpadProductDisplay', 'BreakpadVersion',
'BreakpadSendAndExit', 'BreakpadSkipConfirm') | 5,288,930 |
def test_close_account(
stubbed_sender, stubbed_sender_token_account_pk, stubbed_receiver_token_account_pk, test_token, test_http_client
): # pylint: disable=redefined-outer-name
"""Test closing a token account."""
create_resp = test_http_client.get_account_info(stubbed_sender_token_account_pk)
assert... | 5,288,931 |
def swap_scientific_notation_float(line: deque, precision: int) -> deque:
"""
Returns a deque representing 'pycode_as_deque' with any python floats that
will get "cut-off" by the 'precision' arg when they are rounded as being
rendered as strings in python's "e format" scientific notation.
A float ... | 5,288,932 |
def test():
"""Runs the tests."""
pytest.main() | 5,288,933 |
def count_vowels(test_string):
"""
Problem Statement-
Given test_string return the number of vowels in the string.
Input-
a. test_string: str
Normal String.
Consists of alphanumeric characters.
Output-
The function should return an integer value
after counting the number of vowels in... | 5,288,934 |
def exponential(max_iteration=1.0, min_transition=1.0, initial_radius=1.0):
"""
Return an exponential radius neighborhood function.
f(iteration) = initial_radius * (min_transition / initial_radius)^(iteration / max_iteration)
Keyword arguments:
max_iteration -- maximum count of iteration
min_t... | 5,288,935 |
def cal_newpath(dis_mat, path_new, cityNum):
"""
计算所有路径对应的距离
:param dis_mat: 城市距离矩阵 ndarray
:param path_new: 路径矩阵 ndarray
:param cityNum: 城市数量 int
:return: 动态规划最优路径 list
"""
dis_list = []
for each in path_new:
dis = 0
for j in range(cityNum - 1):
dis = dis_mat[each[j]][each[j + 1]] + dis... | 5,288,936 |
def load_input(source):
"""load the input"""
if isinstance(source, str): # pragma: no cover
with open(source, 'r', encoding='utf8') as stream:
return stream.read()
else:
data = source.read()
if isinstance(data, bytes):
return data.decode("utf8")
retur... | 5,288,937 |
def init_sqlite_db(connection=None):
"""
Initializes SQLite database.
:param connection: Database connection object
:return: Database connection object
"""
if connection is None:
raise AttributeError("Provide connection as parameter")
sql_query = '''CREATE TABLE api_keys (
... | 5,288,938 |
def _compute_dci(x_recon, x):
"""Computes score based on both training and testing codes and factors."""
scores = {}
importance_matrix, train_err = compute_importance_gbt(
x_recon, x)
assert importance_matrix.shape[0] == x_recon.shape[0]
assert importance_matrix.shape[1] == x.shape[0]
informativeness_... | 5,288,939 |
def sample_sac_params(trial: optuna.Trial,
octree_observations: bool = True,
octree_depth: int = 4,
octree_full_depth: int = 2,
octree_channels_in: int = 7,
octree_fast_conv: bool = True,
... | 5,288,940 |
def split_vertex_labels(num_vertices, proportion_censored, rng=None):
""" Adapts tensorflow dataset to produce another element in the labels dictionary
corresponding to whether the vertex is in the training or testing set.
Parameters
----------
num_vertices: The number of vertices in the graph.
... | 5,288,941 |
def copy_helper(app_or_project, name, directory, dist, template_dir, noadmin):
"""
Replacement for django copy_helper
Copies a Django project layout template into the specified distribution directory
"""
import shutil
if not re.search(r'^[_a-zA-Z]\w*$', name): # If it's not a valid direct... | 5,288,942 |
def table():
"""Display base and representative InChI."""
if request.method == "POST" and request.form.get("nmr-inchi-table-data"):
nmr_experiment_type = request.form.get("select-nmr-experiment")
generate_nmr(
nmr_experiment_type=nmr_experiment_type, records=RECORDS
)
... | 5,288,943 |
def run_spider(zap, target, api_key, cid=None, uid=None):
"""
spider the target
only spiders the target, it will not automatically kick off a active scan
"""
print('Spidering target {0}'.format(target))
zap.spider.set_option_scope_string(target, apikey=api_key)
zap.spider.set_option_max_dep... | 5,288,944 |
def PSO(
directed = False, preprocess = "auto", load_nodes = True, load_node_types = True,
load_edge_weights = True, auto_enable_tradeoffs = True,
sort_tmp_dir = None, verbose = 2, cache = True, cache_path = None,
cache_sys_var = "GRAPH_CACHE_DIR", version = "2020-05-19", **kwargs
) -> Graph:
"""Ret... | 5,288,945 |
def se_resnet152(num_classes):
"""Constructs a ResNet-152 model.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
"""
model = ResNet(SEBottleneck, [3, 8, 36, 3], num_classes=num_classes)
model.avgpool = nn.AdaptiveAvgPool2d(1)
return model | 5,288,946 |
def is_integer(mark_string):
"""Function to check if a supposed pk is an integer."""
try:
mark_id = int(mark_string)
except ValueError:
return False
return mark_id | 5,288,947 |
def update_pipeline(pipelineName=None, pipelineActivities=None):
"""
Updates the settings of a pipeline. You must specify both a channel and a datastore activity and, optionally, as many as 23 additional activities in the pipelineActivities array.
See also: AWS API Documentation
Exceptions
... | 5,288,948 |
def legend(ax):
"""
Put the legend on the axis
ax :: the subplot
"""
lines = len(OUTPUTS) * [None]
for i in range(len(lines)):
lines[i] = ax.plot([0.001, 0.01], [1, 2],
c = mpl.colors.get_named_colors_mapping()["white"],
label = "%d elements" % (N[i]))[0]
leg = ax.legend(loc = 3, ncol = 1, fra... | 5,288,949 |
def getCoordsAndSearchRadius(inputString):
"""getCoordsAndSearchRadius.
Args:
inputString:
"""
coords = {}
ra = None
dec = None
radius = None
sex = COORDS_SEX_REGEX_COMPILED.search(inputString)
decimal = COORDS_DEC_REGEX_COMPILED.search(inputString)
if decimal:
... | 5,288,950 |
def generate_404(structured_notion: dict, config: dict):
"""Generates 404 html page."""
with open(Path(config["output_dir"]) / '404.html', 'w+', encoding='utf-8') as f:
tml = (Path(config["templates_dir"] ) / '404.html').read_text()
jinja_loader = jinja2.FileSystemLoader(config["templates_dir"])... | 5,288,951 |
def _extract_command_with_args(cmd):
"""Parse input command with arguments.
Parses the input command in such a way that the user may
provide additional argument to the command. The format used is this:
command=arg1,arg2,arg3,...
all the additional arguments are passed as arguments to the target
... | 5,288,952 |
def do_network_associate_host(cs, args):
"""Associate host with network."""
cs.networks.associate_host(args.network, args.host) | 5,288,953 |
def test_bag_add_duplicate():
"""
Confirm adding the same tiddler does not lengthen bag.
"""
bag.add_tiddler(tiddlers[0])
listed_tiddlers = bag.list_tiddlers()
assert len(bag) == 2, 'the bag should be length 2 after adding same tiddler, is %s' % len(bag)
assert len(listed_tiddlers) == 2, 't... | 5,288,954 |
def sync(teams, users):
"""
Sync team leads from GitHub to admin permissions on platform
"""
# Dictionary of pennkey to list of admin permissions
content = {}
# Hub@Penn needs to be pre-populated
team_slugs = ["hub_admin"]
# Team Leads are admins of their products
for team in teams[... | 5,288,955 |
def display_gallows(wrong_guesses, max_wrong_guesses):
"""Prints the gallows and partially hung person."""
print(HANGMANPICS[wrong_guesses])
print(f'You have made {wrong_guesses} wrong guesses. ' +
f'You have {max_wrong_guesses - wrong_guesses} guesses left.') | 5,288,956 |
def filtered_secondary_files(unfiltered_secondary_files: dict) -> list:
"""
Remove unprocessed secondary files.
Interpolated strings and optional inputs in secondary files were added to
CWL in version 1.1.
The CWL libraries we call do successfully resolve the interpolated strings,
but add the ... | 5,288,957 |
def get_P_rtd_hs(q_rtd_hs, e_rtd):
"""定格消費電力 (4)
Args:
q_rtd_hs(float): 温水暖房用熱源機の定格能力 (W)
e_rtd(float): 当該給湯機の効率
Returns:
float: 定格消費電力
"""
return q_rtd_hs / e_rtd | 5,288,958 |
def registration_success(request):
"""
This view is called when the registration succeeded
"""
rcontext = RequestContext(request, {})
return render_to_response('auth/registration_success.haml', rcontext) | 5,288,959 |
def match_attr( src1, src2, attrlist=None ):
"""
extension: check that attributes listed are the same for each src
input: string <OR> dict, string <OR> dict, list
output: bool
notes: input sources can be either paths to netcdf files
or dicts {attr_name : attr_val}.
if attrlist is None t... | 5,288,960 |
def slash_validator(
epochs_ctx: EpochsContext,
state: BeaconState,
slashed_index: ValidatorIndex,
config: Eth2Config,
whistleblower_index: ValidatorIndex = None,
) -> BeaconState:
"""
Slash the validator with index ``slashed_index``.
"""
epoch = epochs_ctx.current_shuffling.epoch
... | 5,288,961 |
def read_csv_file(filename):
"""Read csv file into a numpy array
"""
header_info = {}
# Make this Py2.x and Py3.x compatible
if sys.version_info[0] < 3:
infile = open(filename, 'rb')
else:
infile = open(filename, 'r', newline='', encoding='utf8')
with infile as csvfile:
... | 5,288,962 |
def biot_savart(loop_list, fov_min, fov_max, fov_n, points=None):
"""
Creates coil profiles for arbitrary loops, for use in multichannel shim examples that do not match spherical
harmonics
Args:
centers (list): List of 3D float center points for each loop in mm
normals (list): List of 3D... | 5,288,963 |
def test_backend():
"""Tests setting and getting the backend"""
# Default should be tensorflow
assert settings.get_backend() == 'tensorflow'
# Should be able to change to pytorch and back
settings.set_backend('pytorch')
assert settings.get_backend() == 'pytorch'
settings.set_backend('tenso... | 5,288,964 |
def heatmap(data, row_labels, col_labels, ax=None, cbar_kw={}, cbarlabel="", **kwargs):
"""
Create a heatmap from a numpy array and two lists of labels.
Arguments:
data : A 2D numpy array of shape (N,M)
row_labels : A list or array of length N with the labels
for ... | 5,288,965 |
def writeTimeSeriesData(assetId,aspectName,dataList):
""" URL = /timeseries/{entityId}/{propertySetName}
Body needs to be a list of dictionaries:
[
{
"_time": "2019-02-10T23:01:00Z",
"exampleproperty0": "examplepropertyValue",
"exampleproperty0_qc": "examplepropert... | 5,288,966 |
async def test_api_key_expired(aresponses):
"""Test that the proper error is raised when the API is expired."""
aresponses.add(
"api.airvisual.com",
"/v2/nearest_city",
"get",
aresponses.Response(
text=load_fixture("error_key_expired_response.json"),
heade... | 5,288,967 |
def test_wf_3nd_ndst_4(plugin):
""" workflow with three tasks, third one connected to two previous tasks,
splitter and full combiner on the tasks levels
"""
wf = Workflow(name="wf_ndst_10", input_spec=["x", "y"])
wf.add(add2(name="add2x", x=wf.lzin.x).split("x"))
wf.add(add2(name="add2y", x=... | 5,288,968 |
def check_availability(nova_connection: NovaConnection, snapshot_image_uuid: str):
"""
Check the availability of snapshot_image_uuid
:param nova_connection: NovaConnection object
:param snapshot_image_uuid: str snapshot uuid to find
:return: bool True if is found else False
:raise: ValueError ... | 5,288,969 |
def get_request():
"""Get the current request from anywhere."""
request = request_accessor.send(None)
if request:
return request[0][1]
return None | 5,288,970 |
def get_aligned_face_and_landmarks(
im, face_cache, aligned_face_size=256, padding=(0, 0)
):
"""
get all aligned faces and landmarks of all images
:param imgs: origin images
:param fa: face_alignment package
:return:
"""
aligned_cur_shapes = []
aligned_cur_im = []
for mat, point... | 5,288,971 |
def get_createaccount(usr):
"""Ask if account should be created."""
if OPT.dbonly is not None and OPT.aconly is not None:
return
if not yesno('Create account', 1):
OPT.dbonly = 1
OPT.aconly = 0 | 5,288,972 |
def items_per_cart(customers, orders, data):
"""Return customers dataframe with an extra column containing
the average of items_per_cart for each customer."""
mapper = customers_mapper(data)
customers = customers.copy()
orders = orders.copy()
orders['customer_unique_id'] = orders['customer_id'].... | 5,288,973 |
def getParameterDefinitions():
"""Return ParameterDefinitionCollections for each appropriate ArmiObject."""
return {Block: _getBlockParams()} | 5,288,974 |
def check_fake_image_dataset(method):
"""A wrapper that wraps a parameter checker around the original Dataset(FakeImageDataset)."""
@wraps(method)
def new_method(self, *args, **kwargs):
_, param_dict = parse_user_args(method, *args, **kwargs)
nreq_param_int = ['num_images', 'num_classes', ... | 5,288,975 |
async def validation_exception_handler(request: Request, exc: RequestValidationError):
"""
Handling error in validating requests
"""
return JSONResponse(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
content=get_error_response(request, exc)
) | 5,288,976 |
def update(hostname, ip, ttl=None):
"""
Create or update desired DNS record.
Returns Synology-friendly status strings:
https://community.synology.com/enu/forum/17/post/57640?reply=213305
"""
log.debug("Updating {} to {}".format(hostname, ip))
# get zone name correctly (from hostname)
zo... | 5,288,977 |
def test_extract_data_multiple_transaction(gnucash_creator, key, outputs):
"""Testing of Extracting data from Tuples in the d dictionary used in create_example_book.
Test for Multiple Transactions in the Tuple.
"""
test_dict = {
"First": {("Transaction #1", "From"): (100, 200),
... | 5,288,978 |
def cpo(total_cost, total_transactions):
"""Return the CPT (Cost per Order).
Args:
total_cost (float): Total cost of marketing.
total_transactions (int): Total number of transactions.
Returns:
cpt (float) as total cost per order
"""
return total_cost / total_transactions | 5,288,979 |
def _check_non_negative(value: Real, arg_name: str, data_type: type) -> None:
"""
Check if the `value` of the `arg_name` is a non-negative number.
Parameters
----------
value : Union[int, float]
The value to check.
arg_name : str
The name of the variable from the original functi... | 5,288,980 |
async def test_http_client() -> None:
"""Test if the `http_client` context manager works properly."""
url = "https://httpbin.org/get"
async with HTTPClient() as client:
response = await client.get(url)
data = response.json()
assert response.status_code == 200
assert {"Host", "Referer... | 5,288,981 |
def convert_seq2seq_golds(indices, lengths, rlut, subword_fix=lambda x: x):
"""Convert indices to words and format like a bleu reference corpus.
:param indices: The indices of the gold sentence. Should be in the shape
`[B, T]`. Iterating though axis=1 should yield ints.
:param lengths: The length o... | 5,288,982 |
def brew(args, source, cwd=None, callback=None):
"""
Compile command
"""
if sys.platform == "win32":
args.append("-s")
else:
args.append("-e")
return run("coffee", args=args, source=source.encode('utf-8'), callback=callback) | 5,288,983 |
def compare_tokens(ref,dat,tol,feps,ieps):
"""
Compare two tokens taking a potential tolerance into account.
The number returned is the number of characters that are the same.
"""
tmp = str(tol)
(tr,dr,lnr,tnr) = ref
(td,dd,lnd,tnd) = dat
#result = -2*math.log10(feps)
result = 0
... | 5,288,984 |
def get_transit_gateway_multicast_domain_output(transit_gateway_multicast_domain_id: Optional[pulumi.Input[str]] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> pulumi.Output[GetTransitGatewayMulticastDomainResult]:
"""
The AWS::EC2::TransitGatewayMulticas... | 5,288,985 |
def advanced_raster_scan(ny=10, nx=10, fast_axis=1, mirror=[1, 1], theta=0, dy=1, dx=1):
"""
Generates as raster scan.
Parameters
----------
ny, nx : int
Number of steps in *y* (vertical) and *x* (horizontal) direction
*x* is the fast axis
dy, dx : float
Step size (grid... | 5,288,986 |
def test_complex_beam_hinge():
"""Test a complex structure with distributed loadings and hinges."""
a = beam(6, x0=0)
a.add_support(0, "fixed")
a.add_support(4, "hinge")
a.add_support(6, "roller")
a.add_point_moment(6, 20)
a.add_distributed_load(0, 2, "-5*x")
a.add_distributed_load(2, 4,... | 5,288,987 |
def command(func):
"""Decorator to register a fn as an available command."""
if func.__name__ not in COMMANDS:
COMMANDS.append(func.__name__)
return func | 5,288,988 |
def dendrogram(
df, method='average', filter=None, n=0, p=0, orientation=None, figsize=None, fontsize=16,
label_rotation=45, ax=None
):
"""
Fits a `scipy` hierarchical clustering algorithm to the given DataFrame's variables and visualizes the results as
a `scipy` dendrogram.
The default vertica... | 5,288,989 |
def _write_expid_links(outdir, exposures, nights=None):
"""
Write outdir/YEARMMDD/EXPID/explinks.js with info about prev/next exp
may re-sort input exposures list by NIGHT,EXPID
"""
exposures = Table(exposures)
exposures.sort(keys=['NIGHT', 'EXPID'])
if nights is None:
nights = se... | 5,288,990 |
def intervalrecordlookup(table, start='start', stop='stop', include_stop=False):
"""
As :func:`petl.transform.intervals.intervallookup` but return records
instead of tuples.
"""
tree = recordtree(table, start=start, stop=stop)
return IntervalTreeLookup(tree, include_stop=include_stop) | 5,288,991 |
def Convert2targetSeqView(
sampleName,
sampleBamName,
sampleSplitBamName,
vcfFile,
outputDir,
outputFileName):
"""This ``converts`` the Delly Vcf file having tumor normal, to tab-delimited format for input to targetSeqView
:param str sampleName: str for the name... | 5,288,992 |
async def reload(ctx, extension):
"""Use [p]reloadcog all to reload every cog or specify name to reload the specified cog."""
if extension not in extensions:
await ctx.send("Extension named {} does not exist. Please re-check spelling.".format(extension))
else:
client.reload_extension("c... | 5,288,993 |
def max_valued_dose_dependent_assertion_to_jtms(ev, s, a, ac):
""" convert this continous valued DIKB assertion to a JTMS assertion that includes the dose used in the study/experiment
@param ev:an instance of EvidenceBase containing Assertions instances
@param s:string - representation of the assertion ty... | 5,288,994 |
def create_user():
"""注册新用户"""
data = request.get_json()
if not data:
return bad_request('Please post json data.')
message = {}
if 'username' not in data or not data['username']:
message['username'] = 'Please provide a valid username.'
pattern = '^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>... | 5,288,995 |
def test_case_2():
"""
建立一个树
5
/ \
2,3 6,7,8
删除8,不会对结构有影响
"""
debug("test case 2 run")
keys = [5, 2, 3, 6, 7, 8]
tree = BTree()
for item in keys:
tree.add(item)
tree.remove(8)
assert tree.root.keys == [5]
assert tre... | 5,288,996 |
def rebin_1darray(a, shape, function='sum'):
"""Rebin an array into a new shape by making the sum or mean
"""
sh = shape,a.shape[0]//shape
if function == 'mean':
return a.reshape(sh).mean(-1)
elif function == 'sum':
return a.reshape(sh).sum(-1)
else:
print("WARNING: doing... | 5,288,997 |
def affine(src, dst, rcond=1e-6):
"""Estimate the best affine matrix by least-squares in target space.
The implementation is specific to 3-dimensional source and target spaces,
but could be generalized easily.
"""
assert src.shape[1] == dst.shape[1] == 3
flat_dst = dst.flatten(order="C") # ord... | 5,288,998 |
def get_ground_truth(obj, image, question):
"""
Get the ground truth value for the image/question combination in reader
study obj.
"""
ground_truths = obj.statistics["ground_truths"]
return ground_truths[image][question] | 5,288,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.