content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def hilbert(x, N=None, axis=-1): """ Compute the analytic signal, using the Hilbert transform. The transformation is done along the last axis by default. Parameters ---------- x : array_like Signal data. Must be real. N : int, optional Number of Fourier components. Default:...
483127445b3c482bb28b00be7d9c0a5055f6ca25
52,631
async def peer_detail(request): """ --- description: Show current peers, if {level} is set, include logs for {id} tags: - peers produces: - application/json parameters: - in: path name: peer_id description: peer id required: true type: string responses: ...
56f3aff3d6f809c1a614842427384e56dbe055c6
52,632
def interruptable_task(coro, loop=None): """ Turn the given coroutine into an interruptable task by turning it into an InterruptableFuture and returning it. :param coro: the coroutine that should be made interruptable :param loop: the event loop in which to run the coroutine, by default uses tornado.io...
784d352ae84a13c5e5d28c0a4d11b9570f0e77f1
52,633
def STALTA_picker_refraction(st, nsta=1e-3, nlta=4e-2, fc=50, nc=2, noise_mag=1e-25, SNR_window=5e-3): """The STA/LTA picker provides a first order good estimate of the arrival times for both the P- and S- wave. The STA/LTA picker uses :py:class:`obspy.signal.trigger.recursive_sta_lta`. :param st: ...
67b5ca6eb0cdeafdc9f2d85010b07b44f47bb297
52,634
def Roleta(): """Faz a parte da roleta. possibilidades: 100 a 950, de 50 em 50. dois 1000; duas 'passa a vez'; duas 'perdeu tudo', os resultados são equiprováveis; perdeu tudo == 0 passa a vez == 1 none -> int""" possibilidades = [0, 0, 1, 1, 1000, 1000] for i in range(100, 951, 50): # Ad...
69daff5fcc11b126c57733a400a38bbe60b3b4ef
52,635
import re def parse_trace_collection_time_range(collection, time_range, gmt=False, handles=None): """Parse a time range string, using a trace collection to disambiguate incomplete dates. Args: collection (TraceCollection): a babeltrace TraceCollection ...
64eaa8c904b94696d5bd9f8e4d5bd09532416d11
52,636
def lgr_validate_label(lgr, label, udata): """ Validate a label for an LGR. :param lgr: The LGR to use for variant generation. :param label: Label to validate. :param udata: The associated Unicode database. :return: CSV containing the label validation output. """ return _validate_label_...
1c71e77ecd87272fdf1c1d1a4b6ce90fd54cd6c1
52,637
def encodeDNA(seq_vec, maxlen=None, seq_align="start"): """Convert the DNA sequence into 1-hot-encoding numpy array # Arguments seq_vec: list of chars List of sequences that can have different lengths maxlen: int or None, Should we trim (subset) the resulting sequence. ...
6ef075f450aac10ea55a067e1e45252f4314621e
52,638
def sortedWrite(inTree): """ Write out a GLM from a tree, and order all tree objects by their key. Sometimes Gridlab breaks if you rearrange a GLM. """ sortedKeys = sorted(list(inTree.keys()), key=int) output = '' try: for key in sortedKeys: output += _dictToString(inTr...
e37e81e39c6c7212a1c046a7d6adae9ad16f9f0f
52,639
import string def callback(): """ 修改记录 """ # 检查用户权限 _common_logic.check_user_power() content = web_helper.get_form('content', '内容', is_check_special_char=False) # 防sql注入攻击处理 content = string_helper.filter_str(content, "'") # 防xss攻击处理 content = string_helper.clear_xss(content) ...
6ce2d9e6fbbb33d33639f6916d6dda91babbc435
52,640
def validate_cypher(statement, raise_exception=False, exc_class=ValidationError): """ Checks if ``statement`` is a valid Cypher statement. :param statement: Cypher statement to parse. :type statement: str :param raise_exception: Raise ValidationError if not valid. :type raise_exception: boo...
b9c480a07e45b893e7396549d93c6e9b84a360f5
52,642
def strip_newlines(base): """Strip newlines from a string""" return base.replace("\n", "")
aad3fed8a66076cb5ed9c413af319f8aef60a42e
52,643
def fixture_log_output(): """Capture structlog log output for testing. Reference: https://www.structlog.org/en/stable/testing.html """ return structlog.testing.LogCapture()
2a6af8d42a1dafb48d9e73c41ba54bed9b6a4418
52,644
import numpy as np def calculate_g(lat): """calculate the gravitational acceleration with lat in degrees""" g0 = 9.780325 nom = 1.0 + 0.00193185 * np.sin(np.deg2rad(lat)) ** 2.0 denom = 1.0 - 0.00669435 * np.sin(np.deg2rad(lat)) ** 2.0 g = g0 * (nom / denom)**0.5 return g
41c3e4bfd1678279c2e39529cae0ab7a5602d10a
52,645
from scipy.stats import rankdata def weighted_correlation_rank(x, y, wt): """Calculatees the weighted spearman rank correlation""" x = rankdata(x) y = rankdata(y) return weighted_correlation(x, y, wt)
f4381084a2ccd84aeb76efef5b7417ff64fe29ea
52,646
from typing import cast def riFromCSI(csi: str) -> str: """ Get the ri from an CSEBase resource by its csi. """ if (res := resourceFromCSI(csi)) is None: return None return cast(str, res.ri)
a14d83a476bc64b96038d071a78d9b6d81d25faa
52,648
def solr(request): """ Displays ils view for the MARC Batch App """ APP['view'] = 'solr' return direct_to_template(request, 'marc_batch/solr.html', {'app':APP, 'institution':INSTITUTION})
7fd4ab7b66ee6406f903c310b72e1e1d7508bd54
52,649
def process_failed(returncode, stdout): """Return True if the process failed.""" if returncode != 0: return True if 'badly_formatted' in stdout: return True return False
2d3c84872acf3bf6592316aa95c39e41a6da849e
52,650
def find_co_double_bonds(atoms, mol): """ looking for R | C=O | R """ CO_list = [] for _ in range(len(atoms)): name = atoms[_].get_atom_name() if name != 'C': continue nghs_c = atoms[_].get_ngh() nums_c, nghs_list_c = pa...
b0a1479da6cca778c7e58b3acf4c4f12ee347f51
52,651
def p2b_list_point2D(pylist, dtype): """ Converts a python list of feature descriptors stored in 64bit floats into a BoofCV compatible format :param pylist: Python list of 2d points :type pylist: list[(float,float)] :return: List of 2d points in BoofCV format """ java_list = gateway.jvm.java...
ec4b4cb3da04bed662c29472ce91d8c31e5750be
52,652
def transform_coords(c1, c2, out=None): """Return Coordinates by applying c1 to c2 from the left Parameters ---------- c1 : skrobot.coordinates.Coordinates c2 : skrobot.coordinates.Coordinates Coordinates c3 : skrobot.coordinates.Coordinates or None Output argument. If this valu...
719f8ff44f56ca624aee121cc21b0601fd6f2198
52,653
import difflib import tempfile import webbrowser def compare_fiff(fname_1, fname_2, fname_out=None, show=True, indent=' ', read_limit=np.inf, max_str=30, verbose=None): """Compare the contents of two fiff files using diff and show_fiff. Parameters ---------- fname_1 : str ...
bb68539693d318913f64acedef364e183c58e696
52,654
def interp1(x, xdata, ydata, silent=0): # --DC """DETERMINES y AS LINEAR INTERPOLATION OF 2 NEAREST ydata""" SI = argsort(xdata) # NEW numpy's take IS ACTING FUNNY # NO DEFAULT AXIS, MUST BE SET EXPLICITLY TO 0 xdata = xdata.take(SI, 0).astype(float).tolist() ydata = ydata.take(SI, 0).astype(fl...
111f9079b93d86d862861c144f99ef8c4841ab4d
52,655
from typing import Any from typing import Sequence def wrap_in_list(maybe_sequence:Any) -> Sequence: """ If `maybe_sequence` is not a sequence, then wrap it in a list See :func:`pyllars.validation_utils.is_sequence` for more details about what counts as a sequence. Parameters ---------- ...
1feecb4715c9c3278bacbea9332f1d3091f6e9d2
52,656
def evaluate_quadratic(J, g, s, diag=None): """Compute values of a quadratic function arising in least squares. The function is 0.5 * s.T * (J.T * J + diag) * s + g.T * s. """ if s.dim() == 1: Js = J.mv(s) q = Js.dot(Js) if diag is not None: q += s.dot(s * diag) e...
cde6067f22ef3a146b80fb5324c0c1a8ce2e65a4
52,657
def all_in_any(a, b): """return true if every item of 'a' is found inside 'b' else return false """ if len([x for x in a if x in b]) == len(a): return True else: return False
b9fa2ff3396d07a9c3a6c96bb82c047f8902fce9
52,658
import importlib def _get_upgrader_impl(service): """ Instantiate the MagmaUpgrader implementation to be used for magmad, as specified in the service YML config. Args: service (MagmaService): magmad service Returns: magma.magmad.upgrade.upgrader.Upgrader: specified upgrader insta...
580f09f49c723becbcd8c2b179f7e56d934ad5c9
52,659
from typing import Optional from typing import Union async def check_name_and_abbreviation( db, ref_id: str, name: Optional[str] = None, abbreviation: Optional[str] = None ) -> Union[bool, str]: """ Check is a otu name and abbreviation are already in use in the reference identified by `ref_id`. Returns a ...
9810fb23b5933b6cdf84a169173f3221adbf3f5d
52,661
def get_test_data(suite): ############################################################################### """ For a given suite, returns (inherit, time, share, tests) """ raw_dict = _ALL_TESTS[suite] for key in raw_dict.keys(): expect(key in ["inherit", "time", "share", "tests"], "Unexpected...
4705152df2b863342163c077a99add064aca5c29
52,662
def slafbfiles(date): """Observation file locator stub .. note:: User-specified stub :param date: The verification date in string format ``'%Y%m%d'`` :returns: List of files """ files = ['slafb.nc'] return files
9a8476edc9694cc61466995c21c82b94b921f3fb
52,663
def expansionhunter_unclear_expected(): """:return: Returns dictionary with expected results for ExpansionHunter - UNCLEAR.""" return { "AR": ( "Unclear - repeat AR observed outside defined ranges (34/37). " "Normal range: 9 - 35. Expansion range: 38 - 62." ), "FM...
0e5f60482694b4ed3d9ceac573795194e8cac541
52,664
def create_temporay_element_type(name, attrs=()): """ """ if not attrs: bases = (TemporarySingleValueInternalElement,) else: if 'codeinfo' not in attrs: attrs = tuple((*attrs, 'codeinfo')) bases = (namedtuple(f'_{name}Base', attrs), TemporaryInternalElement) retur...
e97f25fa3c5713c2c8ff67a54355b024adef37a2
52,665
import urllib def enrich_url(base_url, client_doc) -> str: """ Add payment form API parameters for this client. """ url = base_url params = '' cl_name = make_client_name(client_doc, include_title=False) cl_street = client_doc.get('address', {}).get('street', ' ') cl_city = client_doc.g...
1fed11679ad838802c951715f8c1d056de7a2ac2
52,666
from typing import Callable def bind_raw(func: Callable[[bytes], HTTPHandler]) -> HTTPHandler: """Executes passed `func` on request body. Args: func (Callable[[bytes], HTTPHandler]): to run on request body. """ @handler def _handler(nxt: HTTPFunc, ctx: HTTPContext) -> Future[HTTPContext ...
bc685baec7dbe4f499f5928d0fe718a2af2eb435
52,668
def GetTask(task_guid, service_guid): """ Retrieve the detail of a task It is handler for GET /services/<service_guid>/task_list/<task_guid> """ return handlers.GetTaskHandler(task_guid, service_guid)
d2ae029581ca8d6f7017afa7f11c897900d54eef
52,669
def check_lowercase_prefix(node: ir.Node, module_prefixes: ModulePrefixLookup) -> bool: """check that node starts with the lower-case module prefixed followed by an underscore.""" if node.Name: for file in containing_modules(node): if file in module_prefixes: if not node....
d76c8829f9d9765c2061134bac8f6af1f8de29c1
52,671
def count_params(text): """Return number of parameters.""" return len(parse.parse_qs(text))
e1e87ad8a85f5d5db5d4128466b7e06765d97d20
52,672
import functools def GetJobDirFlag(upload_help=True, allow_local=False): """Get base.Argument() for `--job-dir`. If allow_local is provided, this Argument gives a str when parsed; otherwise, it gives a (possibly empty) ObjectReference. Args: upload_help: bool, whether to include help text related to obj...
7f85586119862b103a6e5a10bacf2144e943a607
52,673
def get_cl_source(name): """Get the source code for a openCL source file located in the chroma cuda directory at src/[name].""" with open('%s/%s' % (srcdir, name)) as f: source = f.read() return source
3f57d3dd55b410c9553f9a959e9d1a69aa0670a1
52,674
def beam2pix(header): """ Calculate the beam to pixel conversion ratio, which is used to convert between Jy/beam and Jy. Parameters ---------- header : fits header The header of the data. Returns ------- b2p : float The ratio of the beam size to the pixel size. ...
0e063438acec1ee808a43d82250ffa4e368d76e9
52,675
def add_user_favorites(itemid): """ Add item to user's favorite list. Args: itemid (int) – item id Status Codes: 201 Created – when favorite successfully created """ path = '/users/{}/favorites'.format(userid()) data = {'itemid': itemid} return post(path, data, auth=Tr...
1cc8a2c7fca39aa34f40dfeb9c882ee8b8c6f7ac
52,676
def decode_varint(stream: BytesIO) -> int: """ Decode bytes into int """ shift = 0 result = 0 while True: i = _read_one(stream) result |= (i & 0x7F) << shift shift += 7 if not (i & 0x80): break return result
31210521a8fce5815d43ca547d196c8a96accd1d
52,677
def get_linguist_projects(args, default_all=False): """ Get Linguist Projects """ worktree = get_linguist_worktree(args) project_args = args.projects pml_paths = list() project_names = list() for arg in project_args: if arg.endswith(".pml"): pml_paths.append(qisys.sh.to_nativ...
84f9659f50b76c04c6f5cf8e3e7fc9038f8e4941
52,678
import gettext def bucketcall(queryfield="", name="", title="", sortby="", lastnamefirst=False, infotext="", description="", query="", alphabetical=False, insert_entries=None, page_url=""): """Bucket call helper.""" q_data = {"buckets": "%s.bucket" % queryfield} if query: ...
00fd3dff1e18dfc202230930788c764087c08183
52,680
def brute_force_mscs(seq: list) -> tuple: """Brute-force approach to compute the sum of all subsequences of seq. There are n + (n - 1) + (n - 2) + ... + 1 different subsequences. Time complexity: O(n³).""" _sum = _max = seq[0] start = end = 0 for i in range(0, len(seq)): for j in ran...
4b2aad5e443be80c65cb384cb6e1ba27dc63688a
52,681
def with_metaclass(meta, *bases): """Create a base class with a metaclass.""" # This requires a bit of explanation: the basic idea is to make a # dummy metaclass for one level of class instantiation that replaces # itself with the actual metaclass. Because of internal type checks # we also need to make sure that ...
ccdd730769527a2839af9031c4fdfbf4eb87b796
52,682
from typing import List from pathlib import Path from typing import Union def expand_files( files: List[Path], extension: Union[str, List[str]] = ".sql", base_path: Path = Path("."), ) -> List[Path]: """ Expands the list of files or folders, with all SQL files in a folder as seperate files. ...
8243b80a7afaae0426308a1b447f4813eeb5f0c7
52,683
def f1_score_missing(y_true, y_pred, individual=False, micro=False): """ Compute the f1 score, accounting for missing labels in `y_true`. """ assert not (individual and micro) assert y_true.shape == y_pred.shape assert len(y_true.shape) == 2 if micro: # average over attributes usi...
71145d714e594943d31fb3486e2b355d2adc9469
52,685
def run(connection, reporter, object_list): """Run the reporter :class Reporter: for the give object list :class CheckObjectList:""" xml = Marshal().serialize(object_list) resp = connection.execute('POST', object_list.objtype.basepath, accept=CheckReportList.objtype.mimetype,...
e9e7f6e1e673de9dda1686f366084b4f755d1dae
52,687
def horizontal_flip(image_data, output_encoding=PNG): """Flip the image horizontally. Args: image_data: str, source image data. output_encoding: a value from OUTPUT_ENCODING_TYPES. Raises: Error when something went wrong with the call. See Image.ExecuteTransforms for more details. """ ima...
7c9bde12bea232c4e365daa1762b6a44a4334972
52,688
def split_page(encoded_inputs, max_seq_len=512): """ truncate is often used in training process """ for key in encoded_inputs: encoded_inputs[key] = paddle.to_tensor(encoded_inputs[key]) if encoded_inputs[key].ndim <= 1: # for input_ids, att_mask and so on encoded_inputs[key...
fda8e86d0e0c5cabb0fbbcca7f979f65eb3a223c
52,689
def _intToColor(color_number): """ legacy color support for converting integers to color objects based on the cadnano 2 file format Args: color_number (int): integer value of a RGB color Returns: Color: the :class:`Color` object """ return Color('#%0.6x' % (color_number))
b3873fb8ad54b6d120d4b1409550dc4139705286
52,690
def test_points(): """Test points of different styles with/without label and different label positions""" coordinate_system = cartesius.CoordinateSystem(bounds=(-.5, 5, -.5, 5)) # Without labels: coordinate_system.add(elements.Point((1, 4), style='.')) coordinate_system.add(elements.Point((2, 4), s...
849fcd43f7dcdb524aed7ee07b836fa604f649de
52,691
def obter_todas(possui_oferta: bool = None) -> dict: """Consulta a lista de todas as categorias que possuem ofertas dos lojistas parceiros da Lomadee. Parameters ---------- possui_oferta: bool, optional Quando "true" retorna apenas categorias que possuem ofertas. Returns ------- di...
d65523047a322e6bcf909a95df5995b2c0417045
52,692
def construct_M_h(tsp,H,dt,Stim): """ Performs preliminary processing of the spike trains, and returns the matrix corresponding to the post-spike filter. Parameters ---------- Stim : array_like Stimulus. tsp : array_like Spike ti...
379b1aaf9b57f66ef0d10580644ad97df44eccce
52,693
def vdowham(eta, vel_entrain, e_eff, r_eff): """ Calculate the velocity parameter of the contact problem according to Dowson-Hamrock. Parameters ---------- eta: ndarray, scalar The dynamic viscosity of the lubricant. vel_entrain: ndarray, scalar The entrainment velocity of ...
e8abfcc3d312ffce0c192a3b890fe8f3a6785e76
52,694
def rotate(set_of_points, pivot, rotation_matrix): """ set_of_points: numpy.matrix pivot: tuple(x, y, z) rotation_matrix: numpy.matrix """ return kb.translate(kb.translate(set_of_points, [-i for i in pivot])*rotation_matrix, pivot)
658e8e7d4c79d5a7df86aa3ce3e0a536a81512eb
52,695
def model_fn_builder(config): """Build the model for training.""" def model_fn(features, labels, mode, params): """Build the model for training.""" model = PretrainingModel(config, features, mode == tf.estimator.ModeKeys.TRAIN) print("Model is built!") tvars = tf.traina...
24f99a9bc14662c7d5c1a6e3f6ca5be0fa692b96
52,697
def set_content_type(headers, name): """根据文件名在headers里设置Content-Type。如果headers中已经存在Content-Type,则直接返回。""" headers = headers or {} if 'Content-Type' in headers: return headers content_type = content_type_by_name(name) if content_type: headers['Content-Type'] = content_type retu...
715650add69b91b1db6d506d20cd663c0626cc4f
52,698
def split_folds(X_train, y_train, num_folds): """Split up the training data into `num_folds` folds. The goal of the functions is to return training sets (features and labels) along with corresponding validation sets. In each fold, the validation set will represent (1/num_folds) of the data while the tr...
81cdbb17e2d9feeb536a26ac3bb8066a36aad375
52,699
def compute_convergence(output, output_prev): """ Compute the convergence by comparing with the output from the previous iteration. The convergence is measured as the mean of a XOR operation on two vectors. Parameters ---------- output, output_prev : np.ndarray Current and previous...
7ea1e931598ed8dcf8466fb4df327391943187c1
52,700
def disconnect_rest_handler(remote, *args, **kwargs): """Handle unlinking of remote account.""" _disconnect(remote, *args, **kwargs) redirect_url = current_app.config['OAUTHCLIENT_REST_REMOTE_APPS'][ remote.name]['disconnect_redirect_url'] return response_handler(remote, redirect_url)
8ed09f0e60688fd20383c7c4d98e307872356a6e
52,701
import sqlite3 def viewData(): """ displays data from the database """ con = sqlite3.connect("library.db") cur = con.cursor() cur.execute("SELECT * FROM book") row = cur.fetchall() con.close() return row
2717b438fce5986078cfe6ca798d05499465cb57
52,702
from typing import List from typing import Dict def get_sites(vs30_values: List, rrup_values: Dict): """Creates a dictionary pair of a different Vs30 and Sites Parameters ---------- vs30_values: List list of Vs30s rrup_values: Dict dictionary of Rrups np.ndarray """ # ...
8ae4f419ebc40c41f907e7e7a637625388ceed5a
52,703
def part_2(): """ Returns either a bool or an int. The bool is returned if no end is found in the instructions. The int is the value in the accumulator before termination. """ found_end = False for i, instruction in enumerate(INSTRUCTIONS): if instruction[0] == "nop": INSTRUC...
a0d6a9d24bbb44e881a1933b292ce7e6b0918563
52,705
def _get_school_options_for_a_b_for_most(): """Get the educ_options starting March 15th until April 5th. Situation: - BY: - source: https://bit.ly/3lOZowy - <50 incidence: normal schooling - 50-100 incidence: A/B schooling - >100 incidence: distance for all except graduatio...
49b9f7eaffb6a670b3f2696f2ac3bb934ecfba27
52,706
def pad_dataset_normal(tokenizer_fn): """We will pad the data. Based on name of the dataset, we will pad it accordingly Args: tokenizer_fn ([type]): [A function which returns dict of list of list] Returns: [type]: [description] """ @wraps(tokenizer_fn) def pad_fn(*args, **...
d03352e26d8315aae573075edba72195360ffebc
52,707
from typing import Optional def add_comment( post: k_models.KookaburraPost, content: str, author: settings.AUTH_USER_MODEL ) -> Optional[k_models.KookaburraComment]: """ Add a comment to a post, doing some checks beforehand. """ # Check that the post is allowed to comment if not post.commentin...
65b372bf058a721faa3f672e322f43f1fcd137e7
52,708
import json def get_profile_name(host, network): """ Get the profile name from Docker A profile is created in Docker for each Network object. The profile name is a randomly generated string. :param host: DockerHost object :param network: Network object :return: String: profile name ""...
37128df21074c75e53e9567c51301c76578947f2
52,709
def S7_parabola(M,S,gamma): """ Computes the intial conditions for the disrupting galaxy. """ R1 = -55 R2 = 25-(R1**2)/100 vR = np.sqrt((2*gamma*(M+S))/np.linalg.norm([R1,R2])) if R1 == 0: vR1,vR2 = vR,0 else: theta = np.arctan(abs(R1/50)) if R2 > 0: ...
ef975c4e4c1a9d129cd7cf1af7efb1d9088367e0
52,710
def create_compression_joint(joint, end_parent, description, point_constraint = False): """ joint need to be a joint with a child joint. Child joint is automatically found. """ end_joint = cmds.listRelatives(joint, c = True, type = 'joint') parent_transform = cmds.listRelatives(joint, p = True)...
49c97c12ef22bd954a40241e7d1ec68889abb63e
52,712
def get_simple (ftype, data, alphabet=features.DNA, sparse=False): """Return SimpleFeatures. @param ftype Feature type, e.g. Real, Byte @param data Train/test data for feature creation @param alphabet Alphabet for feature creation @param sparse Is feature sparse? @return Dict with SimpleFeatures train/test """ ...
3029746b834c09b616627e19a1f4f6d6fd64a9a3
52,713
import functools def checker(func, options=None): """Checks for producers methods. Print: * Alteration in objects hash. * Numpy errors. """ if options is None: options = [] @functools.wraps(func) def wrapper(*args, **kwargs): self = args[0] if hasattr(self,...
f65982d4450ddecd7ccdc16f44a8d8e5752432ea
52,714
def _absolute_path(repo_root, path): """Converts path relative to the repo root into an absolute file path.""" return repo_root + "/" + path
bae7013db933e58343f0d6b3f90dfa100de74b7e
52,715
def run_all(): """Default function that is called by the runner if nothing else is specified""" return _make_runner(['test_fails', 'test_skipped', 'test_passes'])
d20576564b01296da29985177517813e36c9cc00
52,716
def psnr(x, y, vmax=-1): """ psnr - compute the Peack Signal to Noise Ratio p = psnr(x,y,vmax); defined by : p = 10*log10( vmax^2 / |x-y|^2 ) |x-y|^2 = mean( (x(:)-y(:)).^2 ) if vmax is ommited, then vmax = max(max(x(:)),max(y(:))) Copyright (c) 2014 ...
e00baca3ad9ba3cc323b6e8c2f82ec8307d188fa
52,717
def srpc(*params, **kparams): """Method decorator to tag a method as a remote procedure call. See :func:`spyne.decorator.rpc` for detailed information. The initial "s" stands for "static". In Spyne terms, that means no implicit first argument is passed to the user callable, which really means the m...
2f03d3b53359d19ec2fa76ece08e95a972afc087
52,718
from typing import Any from typing import Tuple def get_block_header_munger(module: Any, block_hash: Hash32) -> Tuple[HexStr]: """ Normalizes the inputs JSON-RPC endpoints that take a 2-tuple of `(ContentKey, bytes)` """ return (encode_hex(b"\x01" + block_hash),)
8f71406ba6517e4ecab8e5759d9b67f5bb272cb1
52,719
def latlng_to_region(latlng_str): """Get region from latlng.""" lat, _, lng = latlng_str.partition(',') lat_lng = (float)(lat), (float)(lng) return geodata.get_latlng_regions(lat_lng)
4826e44485a21eb0781ba5f24d76f857158b11bc
52,720
import types def truncated_normal(shape, mean=0.0, stddev=1.0, dtype=types.float32, seed=None, name=None): """Outputs random values from a truncated normal distribution. The generated values follow a normal distribution with specified mean and standard deviation, except that values whose m...
d68103b50a2785a2cccd90fdd96cb2f890626628
52,721
import glob def task_pot(): """Re-create .pot .""" return { "actions": ['pybabel extract -F locales/babel-mapping.ini -o jackalify.pot jackalify'], "file_dep": glob.glob('**/*.py', recursive=True), "targets": ['jackalify.pot'], "clean": True, }
7b6996691535f0468887e61942deb1415cc09ca1
52,722
def track_timing(collector): """Decorator to track statistics on a function's execution time. Parameters ---------- collector : TimerStatsCollector """ def wrap(func): def timed_(*args, **kwargs): return _timed_func(collector, func, *args, **kwargs) return timed_ ...
0d6fee74271f40d5fb355a136a2a0a29e41f6edd
52,723
def aic(L, k): """ Akaike information criterion. :param L: maximized value of the negative log likelihood function :param k: number of free parameters :return: AIC """ return 2*(k + L)
159a02cc19d2b4eab30dd13c1cd2b802777277ad
52,725
def hanging_node_threshold_comparison(pred_tactics, predprob_tactics, pred_techniques, predprob_techniques, known_pred_techniques, permutations): """ Using different combinations of thresholds retrieve all the F0.5 score macro-averaged between the post-processed predictions and the true labels. """ f05list = [] f...
727cc90fe2da1b6f9df8de83e7854efd2dd39470
52,726
def identity(x): """Return x.""" return x
260605c9434bb3a1de37b019b998a1cbd7e581d6
52,728
def get_columns(invoice_list): """return columns based on filters""" columns = [ _("Company") + ":Company:120", _("Trans. Group") + ":Data:180", _("Invoice Type") + ":Data:90", _("Acct. Head") + ":Data:160", _("Stock No.") + ":Link/Item:120", _("Vim Number") + ":Data:150", _("Details") ...
033c8249e2bed97c52155764257e407f31c22afb
52,730
import re def contains_domain(address, domain): """Returns True if the email address contains the given domain in the domain position, false if not.""" domain = r'[\w\.-]+@'+domain+'$' if re.match(domain,address): return True return False
10181053b162701546b9c8e775812022f1572b43
52,731
def pycond(cond, *a, **cfg): """ condition function - for those who don't need meta infos """ return parse_cond(cond, *a, **cfg)[0]
e0b78e939f5391fbdc0e6f868481d2986fe4999d
52,732
def list_dir(path): """列出某个目录下的文件 :param path: 相对于resources目录的路径,用于查找文件夹 :type path: str :returns :返回一个包含资源目录下所有文件或者文件下的绝对路径的list """ return _current_resmgr_session().list_dir(path)
2c023cb106af58a8928f6bf210af9ef8969f2842
52,733
def prepare_update_sql(list_columns, list_values, data_code=100): """ Creates a string for the update query :param list_columns: columns that are in need of an update :param list_values: values where the columns should be updated with :param data_code: data code to add to the columns :return: st...
cc3f3c548623bdeb4d2e4e12cc3205baf0a9e9ba
52,734
from typing import Any from typing import List from pathlib import Path async def enum_coercer( result: Any, info: "ResolveInfo", execution_context: "ExecutionContext", field_nodes: List["FieldNode"], path: "Path", enum_type: "GraphQLEnumType", ) -> Any: """ Computes the value of an en...
75bf091fc360de34bf22f1043d1ca62b1a2c2e70
52,735
def db(request): """Session-wide test database.""" # create a SQLite DB in memory _db.engine = create_engine("sqlite://") # setup models in DB Base.metadata.create_all(_db.engine) return _db
2678a6e147d6bf56b497f6821b8b76ab5ca703e6
52,736
import torch def inference_detector_with_probs(model, img, score_thresh = None): """Inference image with the detector. Args: model (nn.Module): The loaded detector. img (str): image file. Returns: """ cfg = model.cfg cfg.model.test_cfg.rcnn.max_per_img = 50 device = n...
615d63b0bd515757c3815b0cd4c451d1169847f8
52,737
def translate(points, x, y, z): """Takes a set of coordinates and translates them in three dimensional space. The points must be a list (or tuple, or any collection really) of coordinates in the form ``(x, y, z)``, *or* a list (etc.) of objects with x(), y() and z() methods. An example would b...
8dc16aeb28f5b292daf375249bf600e5d2a641ca
52,740
def tversky_index(y_true, y_pred, smooth = 1, alpha = 0.7): """ Links 1. https://arxiv.org/pdf/1810.07842.pdf """ y_true, y_pred = y_cast(y_true, y_pred) tp = reduce_sum(y_true * y_pred) fn = reduce_sum(y_true * (1 - y_pred)) fp = reduce_sum((1 - y_true) * y_pred) return reduce...
20dc0e960441635139f1ce959e1dc6fca3d3ab7a
52,742
def resnet51q(pretrained=False, **kwargs): """ """ return _create_byobnet('resnet51q', pretrained=pretrained, **kwargs)
5a08258ea9f63c7e2ede41e55731b9e39ed610aa
52,743
def _feature_correlation_num(X, y, feature, n_bins=-1, return_prob=False, model=None): """Calculate proportion of true label and distribution predicted probability for a numerical feature using binning """ bin_avg = [] probs = [] # Calculating average prob requires model if return_prob and mode...
c5c915b28fc88006082f6985913a1da965a87afa
52,744
async def list_logs( hub, ctx, name, container_group, resource_group, tail=None, **kwargs ): """ .. versionadded:: 3.0.0 Get the logs for a specified container instance in a specified resource group and container group. :param name: The name of the container instance. :param container_group: ...
863676ceae0a1affd9ef60019afe2836069a7c8a
52,745
def en(s): """Returns `s` as an English location string.""" return owlready2.locstr(s, lang='en')
b5627034be8e5aa3ba0956a3bc9cbcad05d99adb
52,746
def onBoard(top, left=0): """Simplifies a lot of logic to tell if the coords are within the board""" return 0 <= top <= 9 and 0 <= left <= 9
2b2007ae2e3acdbb9c04c3df1397cffce97c6717
52,749