content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def get_confusion_noise_robson19(f, t_obs=4 * u.yr): """Calculate the confusion noise using the model from Robson+19 Eq. 14 and Table 1 Also note that this fit is designed based on LISA sensitivity and so it is likely not sensible to apply it to TianQin or other missions. Parameters ---------- ...
f58dcf51c1cb499d5bf04155c38d12263179b277
3,626,170
def default(): """ Simply calls :func:`get` for the default endpoint. """ return get()
45ed6b65d6d3191688d1f21556500dfe5bb14c48
3,626,171
import torch def direct_1d(x, x_s, dx, dt, c, f): """Use the 1D Green's function to determine the wavefield at a given location due to the given source. """ r = torch.abs(x - x_s).item() t_shift = (r / c) / dt u = dx * dt * c / 2 * torch.Tensor(np.cumsum(shift(f, t_shift))) return u
6eaf3754b95ad0202cbd6ef5bbdeda86acfa8ef9
3,626,172
def test_basic_state_transition(circuit): """Test the basic FSM function.""" class B123(edzed.FSM): STATES = 'S1 S2 S3'.split() EVENTS = [ ('step', ['S1'], 'S2'), ['step', None, 'S3'], # default rule has lower precedence ('step', 'S3', 'S1') # single stat...
47e9ad590e03515ac2c790a8e4b8fda071179c6e
3,626,173
def home(): """ Home Page """ print("### Home Page Loaded ###") return render_template('index.html', page="Home")
21e47410da3113ecc56a3211a7f855c39a82cac7
3,626,174
import math import torch def read_alignment( filename, format=None, *, max_taxa=math.inf, max_characters=math.inf ): """ Reads a single alignment file to a torch tensor of probabilites. :param str filename: Name of input file. :param str format: Optional input format, e.g. "nexus" or "fasta". ...
dc6d724fc9a8ece4ac9d6a06394d01310a9fa5bc
3,626,176
def auto_load_processed(path): """Load processed BEEP .json files regardless of their class. Enables loadfn capability for legacy BEEP files, since calling loadfn on legacy files will return dictionaries instead of objects or will outright fail. Examples: auto_load_processed("maccor_file_...
322c501719e7c6d33b9509cb357651bec4254f55
3,626,177
def grating_linear_dispersion( spec_inclusion_angle, spec_focal_length, spec_focal_length_tilt, spec_grooves_per_mm, spec_central_wavelength, spec_order, number_of_pixels, pixel_width, calibration_pixel, ): """ Parameters ---------- spec_inclusion_angle : float ...
589044391cebea828a28927810e0c9ed15121456
3,626,178
from functools import reduce def merge_columns_starting_positions(starting_positions, strict=True): """merging all lines starting positions""" starting_positions = tuple(set(starting_positions)) # If only one is provided, or all equals, return it if len(starting_positions) == 1: return starti...
dc2830816ea00fc93ff4c68844500b4663acc743
3,626,179
def fin_FoM_optbd(n,d,bc,a,b,cini=None,imprecision=10**-2,bdlmax=100,alwaysbdlmax=False,lherm=True): """ Optimization of FoM over SLD MPO and also check of convergence in bond dimension. Function for finite size systems. Parameters: n: number of sites in TN d: dimension of local Hilbert spa...
32ccaf247614d8a5a1ec98fbc6b5bf1b616b93fd
3,626,180
def create_cylinder(position, radius, height, orientation=(0,0,0), color=None, texture=None, mass=1, friction=0.1, client=0, isCollision=True): """ create cylinder in physical scene. ---------------------- position[3-element tuple]: Center position of the cylinder orientation[3-element tuple]: Euler...
413bdc1a5fcc74df2b2b04cecdfafcf1a88bd5fd
3,626,181
def read_maze(file_name): """ Reads a maze stored in a text file and returns a 2d list containing the maze representation. """ try: with open(file_name) as fh: maze = [[char for char in line.strip("\n")] for line in fh] num_cols_top_row = len(maze[0]) for row ...
373e121a9dc827307fc6b56350f8b19247115651
3,626,182
def format(number): """Reformat the number to the standard presentation format.""" number = compact(number) return (number[:-7] + '.' + number[-7:-4] + '.' + number[-4:-1] + '-' + number[-1])
c4bb448ee035c99bdbd3148be4bfef129209bd3c
3,626,184
def user_register(**kwargs): """ swagger_from_file: Swagger/user/register.yml """ data = kwargs['data'] data['password'] = UserInfo.generate_hash(data['password']) try: obj = dynamic_modify(UserInfo(), data).create() except Exception as e: return response(ResponseEnum.INVALID...
c1340fca05349ce94143ca7c6f9c875c755b62c2
3,626,185
def _check(sample, data): """Get input sample for each chip bam file.""" if dd.get_chip_method(sample).lower() == "atac": return [sample] if dd.get_phenotype(sample) == "input": return None for origin in data: if dd.get_batch(sample) in dd.get_batch(origin[0]) and dd.get_phenotyp...
47c17783b852ece100e5f7c9d04e9a0f6bb69650
3,626,186
def step_update(x, P, a, b, sd): """ Apply 'observation' of form a'x = b + N(0, sd^2) to obtain new x, P, useful for building priors :param x: n_k, n :param P: n_k, n, n :param a: n :param b: n_k, :param sd: :return: """ PCt = P @ a # n_k, n CPC_Q = PCt @ a + sd ** 2...
91e52a0c2696e1561c558f761e8d318ca51e64b8
3,626,187
def validate_single_message(schema, input_file, verbose): """Validate single message stored in input file.""" processed = 0 valid = 0 invalid = 0 error = 0 try: payload = load_json_from_file(input_file, verbose) processed = 1 validate(schema, payload, verbose) va...
1ef1854c9873e4df9ff6c61303a1a8d9e35e98d4
3,626,188
def sns_certificate(*args): """ Mock requests to retrieve the SNS signing certificate """ with open('tests/files/certificate.pem') as cert_file: cert = cert_file.read() return cert
6d1198c7ea3c29be28dbecf6affe5c31ab51267a
3,626,189
from scipy.spatial import cKDTree as KDTree def kldivergence(x, y): """Compute the Kullback-Leibler divergence between two multivariate samples. Parameters ---------- x : 2D array (n,d) Samples from distribution P, which typically represents the true distribution. y : 2D array (m,d) ...
55a512b6d720d065f32aa4a1877f10a8f9e03168
3,626,190
def get_municipio_near_geo(geo_points, max_meters=15e+3): """ Parameters ----------- geo_points: list List containing (latitude, longitude) coordinates. max_meters: int, float Max. number of meters from the geo_points to the municipio centroid used to filter municipios. ...
5c16ff7174eb65639ab130b0b796c770c3ef9a5e
3,626,192
def replace_text_in_tables(page): """ Replace <p> tags with their contents because `html2text` has troubles with p tags inside tables. """ tables = page.find('body').find_all('table') has_colspan = False for table in tables: rows = table.find_all(["th", "tr"]) for row in rows...
eae9ba731b21bae36b018c80450d5060ed69fc35
3,626,193
def get_mirror_table (left, right, miraxis='x'): """ Return a mirror table between two object on chosen axis :param str left: object to compare to slave :param str right: object to compare to master :param str miraxis: 'x'(default) chosen world axis on wich mirror is wanted :return: list: return...
c35cb05282ac4486338916dfccf248e6531f30d2
3,626,194
def work_callback(ctx, param, value): """ Load correct work plugin and add it into the context """ plugin_name = plugin_callback(ctx, param, value) plugin_cls = get_work_plugins()[plugin_name] plugin = plugin_cls(config=ctx.obj["config"]) ctx.obj[param.name] = plugin return plugin
89c0a8f129c3ce450bb0d4e4534c482fea4f68c9
3,626,195
import numpy as np import math def wmh( flair, t1, t1seg, mmfromconvexhull = 12 ) : """ Outputs the WMH probability mask and a summary single measurement Arguments --------- flair : ANTsImage input 3-D FLAIR brain image (not skull-stripped). t1 : ANTsImage input 3-D T1 brain image (not skull-st...
70eba2400fde4bb8faa25b2ab85ce55a03ae3f2c
3,626,196
def translate_delta(mat, dx, dy): """ Return matrix with elements translated by dx and dy, filling the would-be empty spaces with 0. I feel this method may not be the most efficient. """ rows, cols = len(mat), len(mat[0]) # Filter out simple deltas if (dx == 0 and dy == 0): return m...
38492c874bc7bbd59787f4b2d94c2ea0150e69f8
3,626,197
def upscale_x( inputs, scale=4, scope='upscale_x' ): """mimic the tensorflow bilinear-upscaling for a fix ratio of x.""" with tf.variable_scope(scope): size = tf.shape(inputs) b = size[0] h = size[1] w = size[2] c = size[3] p_inputs = tf.concat((inputs, inputs[:, -1:, :, :]), ax...
f967d74db805d1aa04e96ef406caa56818df4080
3,626,198
import logging import json def audio_rttm_map(manifest): """ This function creates AUDIO_RTTM_MAP which is used by all diarization components to extract embeddings, cluster and unify time stamps input: manifest file that contains keys audio_filepath, rttm_filepath if exists, text, num_speakers if kno...
b7828393b5571c7b8ed67748ef9b188c00f90731
3,626,199
def extract_slices(img): """ Extract slices from images shapes Parameters ----------- imgs: list of n_sessions arrays of shape\ (n_voxels, n_timeframes) Returns -------- slices: list of slices """ slices = [] t_i = 0 for i in range(len(img)): n_voxels, n...
28376eb45e7efa19991879c9d6e4a615b6851a4c
3,626,200
def _generate_meta(): """ Generate Meta information for export """ d = {'root_url': request.url_root} return d
8f34c42183e12b36c5ae656e06d7b10b0f3d1715
3,626,201
def u2(vector): """ This function calculates the utility for agent 2. :param vector: The reward vector. :return: The utility for agent 2. """ utility = vector[0] * vector[1] return utility
93b9210db00ee9a3ddca4cd9b447a7348f63a659
3,626,202
from typing import Any from typing import Type from typing import Optional from typing import TypeGuard def assert_isinstance( instance: Any, cls: Type[TYPE], message: Optional[str] = None ) -> TypeGuard[TYPE]: """ A TypeGuard function that is equivalent to `assert instance, cls, message` that hides n...
c81390f0a409667ad1fef26e49cfb6623c8521ba
3,626,203
def build_url(url): """Build the actual URL to use.""" f = furl(url) return f.url
f5d2abdfc8bcb6b9d118d23c98bad371b3b7a3ed
3,626,204
def create_input_file(recipe=None, input_file=None, recipe_input=None, file_name='my_test_file.txt', media_type='text/plain', file_size=100, file_path=None, workspace=None, countries=None, is_deleted=False, data_type='', last_modified=None, source_started=None, source_ended=N...
7ed13eeac1edf5078fac8a1a9ab763fd2667e336
3,626,205
def mask_and_mean_loss(input_tensor, binary_tensor, axis=None): """ Mask a loss by using a tensor filled with 0 or 1 and average correctly. :param input_tensor: A float tensor of shape [batch_size, ...] representing the loss/cross_entropy :param binary_tensor: A float tensor of shape [batch_size, ...] ...
099976441be4e50dbbd6a8fedb7a51f769c6b872
3,626,206
def counting_sort_integers(values, max_val=None, min_val=None, inplace=False): """ Sorts an array of integers using counting_sort. Let n = len(values), k = max_val+1 """ if len(values) == 0: return values if inplace else [] #Runs in O(n) time if max_val is None or min_val is None if...
d53b00b8753d8adc1782e5941b4b6dcce7c80ca3
3,626,207
def xfun(p,B,pv0,f): """ Steady state solution for x without CRISPR """ return f/(B*p-p/pv0)
874d7d5a1d0d485aafa6f7298e1d214ca86ea90e
3,626,209
from onnx.helper import make_node def convert_npi_max(node, **kwargs): """Map MXNet's min operator attributes to onnx's ReduceMin operator and return the created node. """ name, input_nodes, attrs = get_inputs(node, kwargs) mx_axis = str(attrs.get("axis", 'None')) axes = convert_string_to_lis...
feda0ad9c4a301581f3c97f615214b37b558d1d9
3,626,210
def pattern_matching(pattern, genome): """Find all occurrences of a pattern in a string. Args: pattern (str): pattern string to search in the genome string. genome (str): search space for pattern. Returns: List, list of int, i.e. all starting positions in genome where pattern appea...
86ae704586fbac937e044f41a8831f2669c4e7dc
3,626,211
import glob def findLblWithoutImg(pathI, pathII): """ :param pathI: a glob path. example: "D:/大块煤数据/大块煤第三次标注数据/images/*.jpg" :param pathII: a glob path. example: "D:/大块煤数据/大块煤第三次标注数据/labels/*.txt" :return: num of image which not has label """ num = 0 pathI = glob.glob(pathI) pathII = g...
30edbff244acb0014b54cf3c85d86a47d779d226
3,626,212
import math def lcf_float(val1, val2, tolerance): """Finds lowest common floating point factor between two floating point numbers""" i = 1.0 while True: test = float(val1) / i check = float(val2) / test floor_check = math.floor(check) compare = floor_check * test if...
b4bef1a63984440f43a1b0aa9bf9805cb4bfd466
3,626,213
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Unload a config entry.""" if await hass.config_entries.async_unload_platforms(entry, PLATFORMS): hass.data[DOMAIN].pop(entry.entry_id) return True return False
8f7e1a24098033294078d6bec2fcf768c080a398
3,626,214
def check_num_row(data): """ @param df: dataframe @return: return 1 if checking condition is true """ return data.shape[0] > 10
0761c4d31bc3a14132d6c1547d03149bd10013c5
3,626,216
def blog_post_feed_richtext_filters(request, format, **kwargs): """ Blog posts feeds - maps format to the correct feed view. """ try: return {"rss": PostsRSSRichtextFilters, "atom": PostsAtomRichtextFilters}[format](**kwargs)(request) except KeyError: raise Http404()
bb6798d1b2113d8d0205d5dc47b96b0fb6aae6b6
3,626,217
def _convert_text_to_logs_format(text: str) -> str: """Convert text into format that is suitable for logs. Arguments: text: text that should be formatted. Returns: Shape for logging in loguru. """ max_log_text_length = 50 start_text_index = 15 end_text_index = 5 return...
4f7ff95a5cd74bdccd41559f58292cc9b1003ba2
3,626,218
def force_langston_contact_agent_agent(r_tot, d, n, v, t, mu, kappa, damping): """Frictional contact force between agent and agent (Helbing, 2000).""" return mu * (r_tot - d) * n + kappa * (r_tot -d) * dot2d(v, t) * t + damping * dot2d(v, n) * n
b04500bf0ecc2c4e97803a3bca1b7f7bbc0aa435
3,626,219
def glossary(): """Generates glossary data""" data = [] for item in sorted(reference.ACRONYMS.items()): data.append({ "type": "Acronym", "code": item[1], "definition": item[0] }) for item in sorted(reference.ABBREVIATIONS.items()): data.appen...
7172c6f727ee1e9a6fe035d185f0e0e03537f65a
3,626,220
import random def generate_random_slug(length=40, prefix=None): """ This function is used, for example, to create Coupon code mechanically when a customer pays for the subscriptions of an organization which does not yet exist in the database. """ if prefix: length = length - len(prefix...
add5e68d0ed6d3831993410afc5ec7900eb212c4
3,626,221
import re def get_easy_variables(website_rules, url, settings): """Stuff that can be found without parsing the DOM -- its easy""" website_variables = {} website_variables["URL"] = { 'content': url.full_url, 'strength': 'high', 'type': 'attr' } website_variables["DOMAIN"] =...
9bec73093c3408c0616269054ce511239b15f4cd
3,626,222
def order_of_magnitude(x): """Determine the order of magnitude of the numeric input (`int`, `float`, :meth:`numpy.array` or :meth:`pandas.Series`). Examples -------- >>> order_of_magnitude(11) array(1.) >>> order_of_magnitude(234) array(2.) >>> order_of_magnitude(1) array(0.) >>...
f8a5a8f0dad2fc86c2cb00c4af6f9c970cd99fce
3,626,223
def lines_of_words(S, W, text_words): """Convert index of first words to list of lines Take the "S" that's computed by a line breaking algorithm and converts it to a list of lines, where each line is a list of words. """ assert sorted(S.keys()) == list(range(1, 1+max(S.keys()))), [ sort...
07d3adfcf0e6cb292e30fd829ded2fafd80ebe50
3,626,224
def digits_to_num(L, reverse=False): """Returns a number from a list of digits, given by the lowest power of 10 to the highest, or the other way around if `reverse` is True""" digits = reversed(L) if reverse else L n = 0 for i, d in enumerate(digits): n += d * (10 ** i) return n
1648073d46411fd430afea4f40f7fa9f4567793c
3,626,226
def dynamics(q, u, p): """ Returns state derivative qdot. Takes current state q, motor input torque u, and disturbance torque p. See <http://renaissance.ucsd.edu/courses/mae143c/MIPdynamics.pdf> (rederived with incline). """ # Angle of pendulum in incline frame ang = q[2] - incline # M...
9d36bdb0218b15f91d6d49a489dd39cc2785becd
3,626,227
def escape_and_join(args): """Creates a shell-escaped string from a list of arguments.""" escaped = [] for x in args: if x.startswith("$"): # This is a hack because a rule in //fpga/defs.bzl wants to pass # $XCELIUM_PATH as an argument, and have the shell expand it correctly....
0b11fe4268ed3b2e6b7756faeaeace8dcfd248dd
3,626,229
import torch def mean_shift_smart_init(X, kappa, num_seeds=100, max_iters=10, metric='cosine'): """ Runs mean shift with carefully selected seeds @param X: a [n x d] torch.FloatTensor of d-dim unit vectors @param dist_threshold: parameter for the von Mises-Fisher distribution @param num_s...
a4661dbad7c415a75aa5ba06a2f1a69df5b79a97
3,626,230
def mergesort(*tables, **kwargs): """ Combine multiple input tables into one sorted output table. E.g.:: >>> import petl as etl >>> table1 = [['foo', 'bar'], ... ['A', 9], ... ['C', 2], ... ['D', 10], ... ['A', 6], ...
724fb395f77e680b0641d3f953d926e41a0fe7c9
3,626,231
def _normalizeGlifPointAttributesFormat2(element): """ - Follow same rules as Format 1, but allow an identifier attribute. """ attrs = _normalizeGlifPointAttributesFormat1(element) identifier = element.attrib.get("identifier") if identifier is not None: attrs["identifier"] = identifier ...
60e7411c84cf45c255116d12e56ef449ee2aac37
3,626,232
def fetch_account_balance(pubKey: str = REWARD_PUBLIC_KEY) -> float: """ Returns the balance of the given account available to be send """ try: acc = server.accounts().account_id(pubKey).call() except Exception as e: print(f"Specified account ({pubKey}) does not exists:", e) ...
c1283b9d3e079a1168286ca6e5f4e73a22dca9f9
3,626,233
def identify_formation_channels(seeds, file): """Identify the formation channel that produced each seed. We consider 5 main channels: classic, only stable, single core CEE, double core CEE and other. We define the channels as follows (the numbers are what is put in the ``channels`` output): Classic...
d245f08a6d3192ea56117f9e2a9440029ce60f66
3,626,234
def _read_stimtime_FSL(stimtime_files, n_C, n_S, scan_onoff): """ Utility called by gen_design. It reads in one or more stimulus timing file comforming to FSL style, and return a list (size of [#run \\* #condition]) of dictionary including onsets, durations and weights of each event. Pa...
d83c27a3e3f1b80c224ec4b93c514a82eced6964
3,626,235
import collections def parse_map(map_file): """ Parse a given map file (compilation output). """ sections = [ "Preamble", "Allocating common symbols", "Discarded input sections", "Memory Configuration", "Linker script and memory map", "OUTPUT", ...
2aec206820540445e476cb4d4333e95e5b76d7e4
3,626,236
def parse_sge_script(local_script_path): """ Parse the SGE script :returns: A dictionary of the options for constructing AiiDAJobFirework """ with open(local_script_path) as handle: lines = handle.readlines() options = { 'stdout_fname': '_scheduler-stdout.txt', 'stderr...
df130f5af9d46dd2803cf04b833500aabb276856
3,626,237
from typing import Union from pathlib import Path from typing import Tuple from unittest.mock import Mock import unittest def run_using_a_configuration_file( configuration_path: Union[Path, str], file_to_lint: str = __file__ ) -> Tuple[Mock, Mock, Run]: """Simulate a run with a configuration without really la...
0d66f10f0b8cbe176aeca6c3ec4fdd04e0bc6cfb
3,626,238
import re from pathlib import Path def get_gromacs_version(gmx: str = "gmx") -> int: """ Gets the GROMACS installed version and returns it as an int(3) for versions older than 5.1.5 and an int(5) for 20XX versions filling the gaps with '0' digits. Args: gmx (str): ('gmx') Path to the GROMACS ...
0a1760ecd50ffb7fc0838e6eb7d0c82b10cb3c07
3,626,239
def StepToGeom_MakeConic2d_Convert(*args): """ :param SC: :type SC: Handle_StepGeom_Conic & :param CC: :type CC: Handle_Geom2d_Conic & :rtype: bool """ return _StepToGeom.StepToGeom_MakeConic2d_Convert(*args)
96e7da2ba814bdc2123217fff24784978eabe476
3,626,240
def AllNames(): """(read-only) Array of all Monitor Names""" return get_string_array(lib.Monitors_Get_AllNames)
86ae2263d6ded5a376da48288f40170801f32e5f
3,626,241
def k2_mean(success_tag, ms_results): """ Returns the expectation of k2, the rate constant for the unimolecular step of a resting-set reaction. """ success_kcolls = np.ma.array(ms_results['kcoll'], mask=(ms_results['tags']!=success_tag)) success_t2s = np.ma.array(ms_results['times'], mask=(ms_results['tags']!=s...
b328bd479c81412a86a902d8c4899240b9ae5ad9
3,626,242
def json_network(user, raw=True, callback=None): """ callback=NAME wrap the object definition in a function call NAME(...) ?raw a raw JSON object is returned, instead of an object named Delicious.posts """ url = 'http://del.icio.us/feeds/json/network/' +...
3f0598180b0865ea1624c3cb1cae591022700475
3,626,243
def implode(space, w_arg1, w_arg2=None): """Join array elements with a string.""" if w_arg2 is None: if w_arg1.tp != space.tp_array: space.ec.warn("implode(): Argument must be an array") return space.w_Null else: w_arr = w_arg1 string = "" else...
90e78c0f2266b3396606eec50cf5378b2079fba6
3,626,246
def fill_matrix(X: np.ndarray, mixture: GaussianMixture) -> np.ndarray: """Fills an incomplete matrix according to a mixture model Args: X: (n, d) array of incomplete data (incomplete entries =0) mixture: a mixture of gaussians Returns np.ndarray: a (n, d) array with completed data...
18318c0b781706966a787a2a0d53e52714d43628
3,626,247
import torch import tqdm def get_pseudo(t_model, unlabeled_dataset): """ params: t_model: teacher model unlabeled_dataset: unlabeled dataset return: pseudo_label: ndarray[N, C], N=len(dataloader), C for num of class, dim C is output of softmax """ t_model.eval() device ...
fdb880925be00da5007b921ee8e8e0dbdb0caddc
3,626,248
def CountDictCall(keyfunc): """ Decorator for counting memoizer hits/misses while accessing dictionary values with a key-generating function. Like CountMethodCall above, it wraps the given method fn and uses a CountDict object to keep track of the caching statistics. The dict-key fun...
537a7595eb9cd1752e80e2a4694ec694ef569440
3,626,250
def _group_map_list(_data, _f, *args, _keep=False, **kwargs): """List version of group_map""" return list( regcall( group_map, _data, _f, *args, **kwargs, _keep=_keep, ) )
7c28ddc689b896d96c31898c790e23da1c0ad302
3,626,252
def clean_zeros(a, b, M): """ Remove all components with zeros weights in a and b """ M2 = M[a > 0, :][:, b > 0].copy() # copy force c style matrix (froemd) a2 = a[a > 0] b2 = b[b > 0] return a2, b2, M2
3e2def6e88a7ac5a67b9849a9dcd2f5f5156fb00
3,626,253
def compare(gene, classes): """ Compare the distribution of two or more groups and automatically selects the proper statistical test Args: gene (string): feature to be compared. classes (list of pandas dataframe): list of groups (classes) to compare. Re...
0aae0446b75be80d3b63eb1411599297bf5bba54
3,626,254
def get_powersph_errorbars(k, psph, params): """ Calculate the error bars on spherically-averaged P(k) (1-sigma uncertainty) as a function of k. This is a convenience method, which calls the internal method. Parameters ---------- k : 1D array Values of k at which to calculate error bar...
6ba2e75bbe7245e423cefe80addf313e8b868a98
3,626,255
from typing import List def sum_poly_areas(lop: List[shapely.geometry.Polygon],) -> float: """ Returns a float representing the total area of all polygons in 'lop', the list of polygons. """ sum_acc = 0 for poly in lop: sum_acc += poly.area return sum_acc
643df866d4a6548af85811549dcf895d50e09fcc
3,626,256
def build_importer_component_spec( importer_base_name: str, input_name: str, input_type_schema: pipeline_spec_pb2.ArtifactTypeSchema, ) -> pipeline_spec_pb2.ComponentSpec: """Builds an importer component spec. Args: importer_base_name: The base name of the importer node. dependent_task: The tas...
f3fc23129c4e68599032115c62405ed2bdadeca2
3,626,257
import types def hpat_pandas_series_max(self, axis=None, skipna=None, level=None, numeric_only=None): """ Intel Scalable Dataframe Compiler User Guide ******************************************** Pandas API: pandas.Series.max Limitations ----------- Parameters ``axis``, ``level`` and ``n...
c5a88afb0baead19c950de46eb0694b467fb1bb7
3,626,258
def train_predictor(predictor, train_data, train_target, hyperparameter, metric='accuracy', n_folds=5): """ Cross validation training in order to find best parameter. :param predictor: :param train_data:...
8109d76d246388e30265da24f7ea64281777f146
3,626,259
from typing import Callable def make_vector_laplace(bcs: Boundaries) -> Callable: """make a discretized vector laplace operator for a cylindrical grid {DESCR_CYLINDRICAL_GRID} Args: bcs (:class:`~pde.grids.boundaries.axes.Boundaries`): {ARG_BOUNDARIES_INSTANCE} Returns: ...
dcb126a941fab660c0fae209df8959fbb9ed1e3c
3,626,260
import hashlib def extract_keys(key: bytes) -> str: """Derive a key1,key2, key3 from a password str and returns a hex tuple (key1, key2, key3) """ digest = hashlib.sha256(key).digest() key1 = hexlify(digest) key2 = hashlib.sha256(digest).hexdigest() key3 = hashlib.sha256(hashlib.sha256(digest).dig...
085c889c979949d92f6f887e1cddf4f3e2587041
3,626,261
def add_user(user): """ Add a user in the database return Boolean """ try: with session_scope() as session: u = User(**user) session.add(u) return True, None except exc.IntegrityError as e: return False, str(e)
1dfb33feda4ec68d7e4518229334da137806621e
3,626,262
def _port_speed_prices_table(port_speeds, prices=False): """Shows Server Port Speeds prices cost and capacity restriction. :param [] port_speeds: List of Hardware Server Port Speeds. :param prices: Create a price table or not """ if prices: table = formatting.Table(['Key', 'Speed', 'Hourly'...
50b437041d83606ccd547c56fa5898b6a38079a5
3,626,263
def conversion(pid, offset, sequences, directory, file_count): """ This function calls all functions required for the full latex to png conversion for a subset of the sequences. It is meant to be called for a single process. The respective subset depends on the given offset. :param pid: The identifier ...
a9cc2efbc0f99c240e59af336c08192ef06d2bb2
3,626,264
def conv_nested(image, kernel): """A naive implementation of convolution filter. This is a naive implementation of convolution using 4 nested for-loops. This function computes convolution of an image with a kernel and outputs the result that has the same shape as the input image. Args: ima...
92f88cd82370de680ea10ebe3e50355e2be6e1d1
3,626,265
import re def get_cheque_code(cheque: str): """Get code""" if ( re.search(r'BTC_CHANGE_BOT\?start=', cheque) or not re.search(r'BTC_CHANGE_BOT\?start=', cheque) and re.search(r'Chatex_bot\?start=', cheque) ): return re.findall(r'c_\S+', cheque)[0] elif re.se...
97d0b3cadfb6010b48ed6fb148083060c50720ff
3,626,266
def findKthLargest(nums, k): """ :type nums: List[int] :type k: int :rtype: int """ # sol 1 # nums.sort() # return nums[-k] # sol 2 # return select(nums, 0, len(nums)-1, k) # sol 3 return search(nums,k)
af5af39c4f0634f57ad4f9c26b8022611bd2ee9e
3,626,267
def check_round_change(fromBlock, toBlock): """Checks for round initilized txs between blockOld and block. If an event exists, get the blocknumber of this tx and the round number """ round_filter = w3.eth.filter({ "fromBlock": fromBlock, "toBlock": toBlock, "address": ROUND_MANAGER_PROX...
b5e2033918dd22b5ecf59ca131a32bc7cbdde53f
3,626,268
def dice_coef_loss(target, prediction, axis=(1,2,3), smooth=1.0): """ Sorenson Dice loss Using -log(Dice) as the loss since it is better behaved. Also, the log allows avoidance of the division which can help prevent underflow when the numbers are very small. """ intersection = tf.reduce_sum(...
4bf384be1e9fe2073f412a7682f89f18403ccd2c
3,626,270
def option_names_not_in_cfg(cfg, options): """ Returns names of *options* not seen in the *cfg* dictionary, typically parsed from an external configuration file. Parameters ---------- cfg : dict options : :py:class:`~enrich2.plugins.options.Options` Returns ------- `list` ...
30f707d8420cef4d2021cf305e0065fe9649ea22
3,626,271
def fit_mgauss(x, y, x0, n, c=(-np.inf, np.inf), thresh=-1, ftol=1e-4, xtol=1e-4, scale=0, maxiter=100, verbose=False): """ Fit a symmetric multigauss to the provided 1-D data. *Arguments*: - x = x values of data to fit. - y = y values of data to fit. - x0 = the initial guess as a stacked (1...
9b67725a9c61be0c8cc06cb7d5347f591109469f
3,626,273
def list_files_with_extension(root_path, extension, full_path=True, recursively=True): """List all files paths in a folder, filtered by a given suffix. Parameters ---------- root_path : Path Top level folder, start search here. extension : str Extension...
5bd9d44573250c84ce7bcafb7c90b68fcd57d896
3,626,274
import torch def get_power_online(signal: ComplexTensor) -> torch.Tensor: """Calculates power for `signal` Args: signal : Single frequency signal with shape (F, C, T). axis: reduce_mean axis Returns: Power with shape (F, ) """ power = signal.real ** 2 + signal...
f7c1ad0dbdee60b7a0db14ea1d87fadeb8778f9e
3,626,275
def transform(model, pretrained=False, gamma=0.9, mem=False): """Return the MomentumNet counterpart of the model Parameters ---------- model : a torchvision model The resnet one desires to turn into a momentumnet pretrained : bool (default: False) Whether using a pretrained resnet ...
849c076b25ceb27ae17dbf9f2743c5b0cfe1c5be
3,626,276
def getListArrayDim(self, ainput, dim=0): """ get the dimension of a list returns -1 if it is no list at all, 0 if list is empty and otherwise the dimensions of it """ if isinstance(ainput, (list, np.ndarray)): if ainput == []: return dim dim = dim + 1 dim =...
c1c336b66f7a9412ed22877f1ac683c617f58280
3,626,277
def exp_two(arg1, arg2): """ (float, float) -> float Exponentiates two numbers (arg1 ** arg2) Returns the exponent """ try: return arg1 ** arg2 except TypeError: return 'Unsupported operation: {0} ** {1} '.format(type(arg1), type(arg2))
ec63d4d8d4e45590918a53ddc8654bc93bd4a435
3,626,278
def parse_problems(lines): """ Given a list of lines, parses them and returns a list of problems. """ return [len(p) for p in lines]
83747e57bddf24484633e38ce27c51c7c8fce971
3,626,280
def standard_lv(env_name, remove_q=True, static_feeds_new=None, clear_loads_sgen=False, clear_gen=True, battery_locations=None, percent_battery_buses=0.5, batteries_on_leaf_nodes_only=True, init_soc=0.5, energy_capacity=20.0, gen_locations=None, gen_p_max=0.0, gen_p_min=-50.0, ...
dbe1d0cf30cc6c677daae0c74016e9841ac1a323
3,626,282
from .authorize import oauth from typing import Callable from typing import Any def oauth_require_read_schema_scope(f: 'Callable[..., Any]'): """(User以外の)メタデータを読むだけのScopeデコレータ. :param Callable f: Function """ return oauth.require_oauth(CRScope.SCHEMA_R.value, CRScope.SCHEMA_RW.value)(f)
908818816d696177ce761f453e0893d4777d241a
3,626,283
import urllib3 import certifi def load_content(site, host, links): """Tests a site.""" # Security: Verified HTTPS with SSL/TLS http = urllib3.PoolManager( cert_reqs='CERT_REQUIRED', # Force certificate check. ca_certs=certifi.where(), # Path to the Certifi bundle. ) start_page_sea...
5a599579133297c2e6ab3231b466f1b6184d22cc
3,626,284