content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import base64 def base64url_encode(data): """ Url safe version of urlsafe_b64encode with stripped `=` sign at the end. :param data: input data :return: Base64 URL safe encoded string """ return to_string(base64.urlsafe_b64encode(to_bytes(data)))
002c975239fce8b64915ea4296d83e2f0be4b8e5
58,828
def _get_hub_by_entity_id(hass: HomeAssistant, entity_id: str) -> HmHub | None: """ Get ControlUnit by device address """ for control_unit in hass.data[DOMAIN].values(): if control_unit.hub.entity_id == entity_id: return control_unit.hub return None
b6503c060b54701dccf8ab2243c8a8cc8fa4fcd4
58,829
def pressure2dBSPL (p, pRef=20e-6): """ Convert sound pressure (p [Pa]) to sound pressure level (L [dB]). Parameters ---------- p : ndarray-like or scalar Array or scalar containing the sound pressure in Pa pRef : Sound pressure reference in the medium (air:20e-6 ...
3bdf675db331aab5e4b502a07b44238243f0ebd7
58,830
def info(): """Returns the challenge name and site.""" init() challenge = get_challenge() return "Challenge name : %s @ %s" % (challenge.name, challenge.domain)
d598fe046ab9de0d86f8188b9df0ddfb46a23377
58,831
import json def create_mapping_dict(total_parsed_results, type_field): """ Create a {'field_name': 'fields_properties'} dict to be used as mapping schemas. Args: total_parsed_results: list. the results from the splunk search query type_field: str. the field that represents the type of the ...
3dd29abbd986a42a2c3a2cab8cd5e40b0b6a65ca
58,832
def metric_fn(config, metrics, eval_fn_inputs): """Computes the loss and accuracy of the model.""" d = eval_fn_inputs metrics["masked_lm_accuracy"].update_state( y_true=tf.reshape(d["masked_lm_ids"], [-1]), y_pred=tf.reshape(d["masked_lm_preds"], [-1]), sample_weight=tf.reshape(d["ma...
450bb814c93b3eb260e81e0c10135cc5e3ed37fd
58,833
import csv import numpy def read_file(input_filename, parm): """ Read the given parameter from the given file and return array of data """ # print('Reading', input_filename) infile = open(input_filename) reader = csv.DictReader(infile) vals = [] for row in reader: vals.append(f...
af9417ae42a582aae69b5209d6bf73f7e890dc4a
58,834
def not_safe_gerone(a, b, c): """ Compute triangle area from valid sides lengths :param float a: first side length :param float b: second side length :param float c: third side length :return: float -- triangle area >>> not_safe_gerone(3, 4, 5) 6.0 """ p = (a+b+c)/2 return ...
499cf398158d170363ea22096b44ea16e402a23a
58,835
def shelf_pwlin(r): """ Ocean followed by continental slope, continental shelf, and beach. The ocean is flat, the slope, shelf, and beach are linear. """ z = z0_shore + slope_of_beach * r # beach z = where(r<x0_beach, z0_shelf + slope_of_shelf*(r-x0_shelf), z) z = where(r<x0_shelf, z0_ocea...
99bfff14129bd634376395bbe346b52eb169ec1f
58,836
def generate_symmetric_group(configuration, symmetry): """ For a particular configuration and list of sublattices with symmetry, generate all the symmetrically equivalent configurations. Parameters ---------- configuration : tuple Tuple of a sublattice configuration. symmetry : list...
12883715b424347468c638fe58d2b52f571ce48f
58,837
import sympy def r_per_amplitude(m, theta_i): """ Calculate the reflected amplitude for perpendicular polarized light. Args: m : complex index of refraction [-] theta_i : incidence angle from normal [radians] Returns: reflected fraction of perpendicular field [-]...
96a278c908282e16b29e724c2bfae954395f83b6
58,838
def is_iterable(an_object, include_strings=True): """ Returns True if an object is iterable, False otherwise. Iterable types include lists, tuples, dicts, strings, numpy arrays, etc. If include_strings is False, then strings are not considered iterable. This is useful because often we use is_iterable()...
7b9f531e3cf69d7fa90d8b9d17188c07f8d7e2da
58,839
from keras.applications.vgg19 import preprocess_input def preprocess_VGG19(img): """ Preprocess image for use with VGG19 Parameters ---------- img : ndarray Raw image as a numpy array Returns ------- img : ndarray Preprocessed image as a numpy array """ return...
aa18c5f92b82e8d7059b7060a67ca40a4326794d
58,840
def quote_text(text): """Quote text and normalize it in sonic protocol context. Arguments: text str -- text to quote/escape Returns: str -- quoted text """ if text is None: return "" return '"' + text.replace('"', '\\"').replace('\r\n', ' ').replace('\n', ' ') + '"'
530042874e8d7531ed14ef8d348211d8d5907902
58,841
def noiseReductionUsingGaussian(image, Kx = 5, Ky = 5) : """ Performs Gaussian Blurring Parameters ---------- image : (M,N) ndarray Input image Kx : Int Kernel size in X direction Ky : Int Kernel size in Y direction Returns ------- image : (M, N) ...
fde36d4ba0b1df67f9ae75fea630c04f0fbfc8bf
58,842
def compName(n1, n2): """ Compare names: n1 n2 strings, blankspace separated names return value between -1 (mismatch) and 1 (match) return None if any of n1, n2 is empty can be used on names, normalised names """ if (not n1) or (not n2): return None nn1 = n1.strip().split() n...
7a37261779f38040e0baa3bf99bbaf66569d6962
58,843
def add(cm_response, **data): """ Creates template of VM. Template has a name and some description. It defines VM's hardware parameters: CPU and memory. It also defines number of points utilized by VM created of it (per hour and overly). @clmview_admin_cm @cm_request_transparent{user.add()} ...
ff8b29ccb0fa288c018275d09208a0b3cfddfce0
58,844
def z_tf(u, H): """ discrete-time transfer function u - the input signal H - the transfer function """ def get_zm1_coeff(L): numcf = L.num[0][0] dencf = L.den[0][0] N = len(dencf)-1 M = len(numcf)-1 # convert to normalized z^...
8a87bce5f3968916d67706e1ac4ce4d137ab7927
58,845
def find_fixed_point(arr): """ Returns i such that arr[i] = i (or -1, if no such i exists). """ #--------------------------------------------------------------------------- # Easier Version: Assume that all integers are distinct (binary search). #-------------------------------------------------...
6697a83cb923e228bbf46c9da49f5f4da1732b4c
58,846
def EventGrain(src_id_or_meta=None, flow_id_or_data=None, origin_timestamp=None, creation_timestamp=None, sync_timestamp=None, rate=Fraction(25, 1), duration=Fraction(1, 25), event_type='', topic='', ...
04207a6fb517e608450a0d40e31d9dcf60cf0c8a
58,849
from typing import Optional from typing import List def tall_info_card( box: str, name: str, title: str, caption: str, label: Optional[str] = None, icon: Optional[str] = None, image: Optional[str] = None, image_height: Optional[str] = None, categ...
2596b739df78b87b20d7cf236b41f087e6cf38d0
58,850
def _func(coeffs, *labels): """ Takes the dot product of coefficients vec & labels vector Parameters ---------- coeffs: np.ndarray the coefficients on each element of the label vector *labels: np.ndarray label vector Returns ------- dot product of coeffs vec and lab...
b445df24f1137f0c43de469cf9270f43115710c9
58,851
def make_object(n): """Take a list of pairs and create a dict NOTE: run through make_array to transform the results to an array """ return dict(make_array(n))
a96403a493809d3be6ed5391f41e2d431769d9cf
58,852
def load_image(test_data, shape): """Load calibration images.""" test_np = np.fromfile(test_data, dtype=np.float32) test_shape = (-1,) + tuple(shape[1:]) test_np = np.reshape(test_np, test_shape) calib_num = 32 if test_np.shape[0] > calib_num: return test_np[:calib_num] else: ...
c91ff785c8b466e573f990fd51a56665742db152
58,853
def ssl_loss_pi_model(labels_x, logits_x, logits_teacher, logits_student): """ Computes two cross entropy losses based on the labeled and unlabeled data. loss_x is referring to the labeled CE loss and loss_u to the unlabeled CE loss. Args: labels_x: tensor, contains labels corresponding t...
e1d013366d3e13ae13ec4fc5e7362ff36faa0f95
58,854
from typing import Tuple from typing import Optional import urllib def parse_netloc(netloc: str) -> Tuple[str, Optional[int]]: """ Return the host-port pair from a netloc. """ url = build_url_from_netloc(netloc) parsed = urllib.parse.urlparse(url) return parsed.hostname, parsed.port
4f24482b60f38e880d9748d4e42361265d0b7964
58,856
def glcm_features(image, distances, orientations, properties): """ Compute properties of the Grey-Level Co-occurance Matrix for an image :param image: image to compute the GLCM for :param distances: distances to compute the GLCM across :param orientations: angles to computes the orientations over :...
63196a13f257aab56f43deb1156a2391b42f3089
58,857
def darknet53(**kwargs): """ DarkNet-53 'Reference' model from 'YOLOv3: An Incremental Improvement,' https://arxiv.org/abs/1804.02767. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.torch/models' ...
8d88394ec127ac376df02d69ffb51af74649bc60
58,858
import numpy def draw_mandelbrot(width, height, left, right, top, bottom, iterations, z0): """Returns a PIL.Image representing the given portion of the set.""" x, y = numpy.meshgrid(numpy.linspace(left, right, width), numpy....
af01deddb80917bf577b757b6a5d552e148109aa
58,860
from typing import List def make_field_dimensions_cartesian(mask: List[int] = None) -> FieldDimensions: """ Create FieldDimensions of cartesian type :param mask: mask to identify which cartesian dimensions are legal (default is [1, 1, 1]) """ if mask is None: mask = [1, 1, 1] assert len...
618e158ac4e6052de42be76b916f51ff2a9006a4
58,861
def change_config(set_attr): """ 因为每次更改属性都要刷新托盘菜单,并且写到配置文件中, 所以定义一个装饰器,以简化代码 :param set_attr: 更改属性的函数 :return: 装饰过的函数 """ def wrapper(plugin, option_text): f = set_attr(plugin, option_text) plugin.save_config() plugin.root.refresh_menu() return f return w...
0f497fb83007dbcd353f44a684c5be995821b424
58,862
def matrix_determinant(M, check=True): """Calculates the determinant of a square matrix M. Parameters ---------- M : list[list[float]] A square matrix of any dimension. check : bool If True, checks if the matrix is square. Raises ------ ValueError If the matrix ...
fc9aa8222274cecb3e32c008c664348392351423
58,863
def get_kubeconfig_current_cluster_name(_kc_model=None): """ :param _kc_model: Internally used to cache kubeconfig info. :return: Returns the cluster associated with the current context. """ kc = _get_kubeconfig_model(_kc_model=_kc_model) current_context_name = get_kubeconfig_current_context_nam...
8198b0ed906fefc0ffaf1f0b67042f0d390accba
58,864
from pathlib import Path def find_artefacts(base_dir:str, type="models", target_file="model.py", target_string="mantraml"): """ Find a Mantra artefacts directory :param base_dir: Base directory to look at :param type: Can be `models`, `data`, `tasks` :param target_file: File use to identify the a...
520e2b18e27c20e4f1aa81a471ea940a9e2b6d8b
58,865
def make_allocation(patient,**kwargs): """ Allocation based on facility preference """ print('allocating',patient) if(patient.group.category == Group.FAMILY): family = patient.group.person_set.all() else: family = [patient] allocated = True for i in range(len(fami...
18bb76f802a79dc533f3d98cdb7320f55413ecc3
58,866
def is_container_flag( df, watersource_col="mhm_WaterSourceType", bit_col="mhm_IsWaterSourceContainer", inplace=False, ): """ Creates a bit flag: `mhm_IsWaterSourceContainer` where 1 denotes if a watersource is a container (e.g. ovitrap, pots, tires, etc.) and 0 denotes the contrary. Parame...
bce47480feb0e3bbc2562d246c4796bc8a822b9b
58,868
from prettytable import PrettyTable def format_term_rankings( term_rankings, labels = None, top = 10 ): """ Format a list of multiple term rankings using PrettyTable. """ # add header header = ["Rank"] if labels is None: for i in range( len(term_rankings) ): header.append("C%02d" % (i+1) ) else: for la...
37682b3c8d8535e73181da4c8daaf4fb1ee79617
58,869
def get_request_user(request): """ 获取请求user (1)如果request里的user没有认证,那么则手动认证一次 :param request: :return: """ user: AbstractBaseUser = getattr(request, 'user', None) if user and user.is_authenticated: return user try: user, tokrn = JWTAuthentication().authenticate(request...
8dcb6d61821d8a546c0b36a1baa0829425d84cdc
58,870
def test_paper_page_end(root, printerror=False): """Verifies if the papers declared in the Lattes CV parsed in the argument root contain a declared end page. Args: root: the Lattes CV that has been parsed with the ElementTree language. flag: if 0, then all papers in the Lattes CV hav...
40b083fa8b2b38211e74e590033c4029cc57b09d
58,871
from sage.matrix.constructor import matrix def lfun_eta_quotient(scalings, exponents): """ Return the L-function of an eta-quotient. INPUT: - scalings -- a list of integers, the scaling factors - exponents -- a list of integers, the exponents EXAMPLES:: sage: from sage.lfunctions....
d77a37f0259d82f25263914a187f373bed6e4057
58,872
from typing import List def add_option(poll: Poll, text: str, added_options: List[str], is_date: bool): """Parse the incoming text and create a single option from it. We allow option descriptions after an `--` or `—` delimiter. `added_options` is a list of names of options that have already been a...
fbdbf35696c45938c2fc8e85bb27ec04a53f1c00
58,873
def test_gen_moving_timeseries_forecast_with_regressors(): """Test for `gen_moving_timeseries_forecast` with regressors""" data = generate_df_for_tests(freq="1H", periods=1000) df = data["df"] df["x"] = 40 # A simple train-forecast function which always uses last available # value, then adds th...
bb22353aa67e97c06d73160773af03f28895202b
58,874
import re from bs4 import BeautifulSoup import requests def mediafire(url: str) -> str: """ MediaFire direct link generator """ try: link = re.findall(r'\bhttps?://.*mediafire\.com\S+', url)[0] except IndexError: raise DirectDownloadLinkException("No MediaFire links found\n") page = Be...
3a79fc7c42a0531b1e3acc56252873b1d3ec7f21
58,875
from typing import List def _add_outputs_of_onnx_model(model, output_nodes: List[str]): """ Add output nodes of onnx model. Args: model (ModelProto): ONNX model. output_nodes (list[str]): Output nodes list. Returns: ModelProto, edited ONNX model. """ onnx = import_mod...
4170d36d9d18ee023a550a72209d769ca182c64d
58,876
def get_pane_working_directory(session: str, window: int, pane: int): """ Get the working directory of a given pane Parameters ---------- session : str Name of the session window : int Window number of pane pane : int Pane index in the window """ return get_t...
f5b469ddbd5efc483be944dc09ac539256cc9f93
58,877
def export_report(id: str, report: str, filename: str) -> bool: """Exports a report summary to a file. Args: id: An extension identifier string. report: A string of the report summary. filename: The chosen filename as a string. Returns: A boolean result for exporting the re...
682694ce9eb0bae2e7f56b4afcdad0d13f6d54ff
58,878
import pickle def simulation(*vars): """ Evaluate a dam hazard potential 'simulation' with a given set of spatial parameters and random forest hyperparameters :param vars: tuple A set of spatial and nonspatial parameters :return: tuple Objective values "...
e949876d60e7cc1fada727a7279ccff562b29d3b
58,879
def GetInfoForCountry(country_name_or_code): """Get code, name, lat and lon for a given country name or code.""" match = False partial_match = False if not country_name_or_code: return None if len(country_name_or_code) == 2: country_code = country_name_or_code.upper() country_name = False els...
db773274d73e210bac2ed237ff0704d923973562
58,880
def sqs_lookup_url(session, queue_name): """Lookup up SQS url given a name. Args: session (Session) : Boto3 session used to lookup information in AWS. queue_name (string) : Name of the queue to lookup. Returns: (string) : URL for the queue. Raises: (boto3.ClientError):...
4f7bfb98d10a372b3b07f270e2a25e3227732f41
58,881
def calcstat(iv, ev, base, level, nature_stat): """Calculate the battle stat of a Pokémon. Note that some stats may be off by one compared to the "official" PKM data. I've only found this to be true on a specific FAL2010 Mew file, but it's worth mentioning. If you would like to be safe, deposit the...
facaeeb2f054a1b091f7383b6342dc624317fed2
58,882
import typing def interpret_target(raw_target: str) -> tuple[typing.Callable, str]: """Determine saving function and target string from input target""" HELP = "Target must be u/username or r/subreddit" SAVERS = {"u": save_user, "r": save_subreddit} assert "/" in raw_target, HELP raw_target = raw...
370680104db88f1cecf66001ea31797efd32d146
58,883
def split_dataset(data, keys, p=[ .6, .2, .2 ]): """ This procedure splits a dataset, with split_percentage, and filters it keeping only specified keys, :param data: dictionary with all datat in (key, sentences) format :param keys: list of required keys :param p: percentage of the test_set set, what is ...
d2775be2563d97f11d1f7f1a2e7466365e433ed5
58,885
def get_image_array(self, image_id=None, ann_id=None): """ Retrieves the array associated with the image_id or ann_id """ image_pil = self.get_image_pil(image_id=image_id, ann_id=ann_id) return np.asarray(image_pil)
ca7a6202b2c690790bfd94683ab64d8a13486301
58,886
from datetime import datetime import traceback async def login_post(request): """ Server login page for the browser :param request: :return: """ try: try: post_data = await request.json() except Exception as _e: print(f'Cannot extract json() from req...
c873796744b944fdf033e94e3696db97da724470
58,888
def getMSDP(obdm): """ This function takes the time dependent obdm matrix and finds the time evolution of the momentum space density profile (MSDP) OUTPUTS: msdp[time idx][p idx] """ msdp = np.zeros((len(obdm), numpts), dtype=np.complex_) # to evaluate this integral we need...
35d01cd77dbca2cc6a36dbf39cb310a20c81ef68
58,889
def get_government_factions(electoral_term): """Get the government factions for the given electoral_term""" government_electoral_term = { 1: ["CDU/CSU", "FDP", "DP"], 2: ["CDU/CSU", "FDP", "DP"], 3: ["CDU/CSU", "DP"], 4: ["CDU/CSU", "FDP"], 5: ["CDU/CSU", "SPD"], ...
cfd502f81ebb0536432da4974ab9f25724dc83df
58,890
def lognormal(mean=0.1, std=0.5, shape=1, z=0): """Draw burst from lognormal distribution. Args: shape (tuple): Required array shape z (array): Redshift of pulses Returns: type: Description of returned object. """ w_int = gd.lognormal(mean, std, shape).astype(np.float32) ...
26c1d6d06da01699fb6afa44824d98670d4ef86f
58,892
def krisciunas_schaefer_free(obs_zenith, moon_zenith, separation_angle, moon_phase, vband_extinction, C_R, C_M0, C_M1, M0, M1, M2): """Calculate the scattered moonlight surface brightness in V band. Based on Krisciunas and Schaefer, "A model of the brightness of moonlight", PASP, vo...
867b4b148e4e76b73aa02bfcc88f1b61bf7d87ae
58,893
from typing import List def _ipv6_address_validator(address: str, strict: bool = True) -> bool: """Validates the address part of an IPv6 address""" valid = True segments = [] empty_segment = f'{IPV6_MIN_SEGMENT_VALUE}' * IPV6_NUMBER_BIT_COUNT # Split on zero-skip, if any try: left, *...
91f6035b98e35fefd594af4b0e6d83b78f6da83c
58,894
def bam_read_count(bamfile, samtools_path="samtools"): """ Return a tuple of the number of mapped and unmapped reads in a BAM file """ p = Popen([samtools_path, 'idxstats', bamfile], stdout=PIPE) mapped = 0 unmapped = 0 for line in p.stdout: rname, rlen, nm, nu = line.rstrip().split() ...
914bf5ff14c7e267937f33b14cfaec563f7519b4
58,895
import logging import tqdm import gc def train_survci_info(model, x_train, y_train, e_train,W_train, x_valid, y_valid, e_valid,W_valid, n_iter=1, lr=1e-3, elbo=True, bs=100): #bs=100 """Function to train the torch instance of the model.""" #bs = 100 (ACTG-SYNT...
c0be3c0678c6671f187488c2070c13833007d287
58,896
def run_model(mod, params=None, opts=None): """Run model. Paramters --------- mod: Module The relay module. params: Parameters The model parameters. opts: Dict The compiler options. Returns ------- out: Data The output data. """ with transf...
f173fe3b2388177d53c25e6016b2f89e8cf382aa
58,897
def VectorVector_scalar(vectorA, vectorB): """ N diemnsional. Return a float as a scalar resulting from vectorA * vectorB""" result = 0 for i in range(0, len(vectorA)): result += vectorA[i] * vectorB[i] return result
c7f0448a05573b8ddba63ed7a8262072ffcda38f
58,898
def artifact_removal(X, n_components=None, check_result=True): """Remove artifacts from data. The artifacts are detected via Independent Component Analysis (ICA) and subsequently removed. To plot the results, use :func:`gumpy.plot.artifact_removal` Args: X (array_like): Data to remove arti...
59d15348ad3eb4744f3c364331d6d6e5f453f66e
58,899
def _get_rnn_cell(mode, num_layers, input_size, hidden_size, dropout, weight_dropout, var_drop_in, var_drop_state, var_drop_out, skip_connection, proj_size=None, cell_clip=None, proj_clip=None): """create rnn cell given specs Parameters ---------- m...
05e17f105a847a07bfd8ffae2c704606d8ce3f56
58,900
def fn_init(Kernel, Ker_weights, range, device): """ this function simply set the args for our main 'fn' function. """ def fn_with_specified_args(inputs, val): return rkhs_fn(inputs, val, Kernel, Ker_weights, range, device) return fn_with_specified_args
ce0e8b21b0d4f9f03a74009ef344e22ca5f3466d
58,902
def show(tr: TraceLike, fix_width=False): """show a trace""" get_value = lambda v: v if isinstance(v, Tensor) else v.value ten_show = lambda v: tensor_utils.show(get_value(v), fix_width=fix_width) return "{" + "; ".join([f"'{k}'-➢{ten_show(v)}" for k, v in tr.items()]) + "}"
f5e4ed26b57e978a4dc8047821a4f4ea97216862
58,903
def describeTreeProductions(tree, links, offset=0): """ Write out the PCFG node productions """ s = "%s ->" % tree.node for ch in tree: s += " %s" % ch.node return s
8f0ec7db35316684441863c8475b6089da0c7e98
58,904
def orlib_load_instance(instance_name, reader, formulation): """ Parameters ---------- instance_name: str Name of instance file reader: function (file) -> params: tuple Takes a file-like object and returns the read parameters formulation: function (params: tuple) -> scip.model ...
aad7d6c2bc0a67e351946ba87e71ca31613f71db
58,905
from re import T def correlation(i, kn=4, kp=4): """Feature selection based on pairwise correlation Args: i (int): index of the country we are modeling tao (float): critical value (default = 0.4) Returns: JH (array): An array with the regressors (incl. self) """ corr_i = ...
e6cb33bed38dd12ec06d1266ecde52485ada7541
58,906
def bumped(repo, subset, x): """``bumped()`` Mutable changesets marked as successors of public changesets. Only non-public and non-obsolete changesets can be `bumped`. """ # i18n: "bumped" is a keyword getargs(x, 0, 0, _("bumped takes no arguments")) bumped = obsmod.getrevs(repo, 'bumped') ...
80b2bce462d7feb6815741ecf68b0c2196899d55
58,907
def discovery_info_from_headers_and_request( info_with_req: CaseInsensitiveDict, ) -> dict[str, str]: """Convert headers and description to discovery_info.""" info = {DISCOVERY_MAPPING.get(k.lower(), k): v for k, v in info_with_req.items()} if ATTR_UPNP_UDN not in info and ATTR_SSDP_USN in info: ...
fbe8f135c032615b27e84a06f56562266b85b86f
58,908
def findH(g_h, cs, Q, S, rh): """ Calculates discharge difference for a given height of water. The minimum of this function is the height of water with a prescribed discharge. Parameters ---------- g_h : guess height [m] cs : cross-section Q : discharge [m^3/s] S : slope rh : roughness height (z_0) [m] Re...
692ee492334c467f0dfb2a5438710e5594438106
58,909
def nextditem(s): """Tries to guess the next item on the sequence 's' by using a table of divisions. This method will fail if the sequence doesn't provide enough information, and will assume that the latest sequence should remain constant""" ds = getdivs(s) r = ds[-1][-1] for i in r...
12f2208e493f8de1bfaec053d54c725306e480aa
58,910
from typing import Optional import itertools def ensure_sequence_of_iterables(obj, length: Optional[int] = None): """Ensure that ``obj`` behaves like a (nested) sequence of iterables. If length is provided and the object is already a sequence of iterables, a ValueError will be raised if ``len(obj) != len...
b073c6a287d5068fd292ee969bac6725aed4747d
58,913
def eval_shift_distance(shift, reg_matches): """ Compute the distance in characters a match has been shifted over. "reg_matches" is the set of regular matches as returned by find_regular_matches(). The distance is defined as the number of characters between the shifted match and the closest regula...
aceb705d0f89cacb6f7738667e6dfaf803bed85c
58,914
import unittest def require_tf(test_case): """ Decorator marking a test that requires TensorFlow, graphviz and pydot. These tests are skipped when TensorFlow, graphviz and pydot are installed. """ if not is_tf_available() or not is_pydot_available() or not is_graphviz_available(): return...
df3dac459eba4d6350cb292085ae4e69d2baef9e
58,915
def get_common_basename(paths): """ Return common "basename" (or "suffix"; is the last component of path) in list "paths". Or return None if all elements in paths do not share a common last component. Generate an error if any path ends with a slash.""" if len(paths) == 0: return None # get...
e2189244ef556038caea24ba6aa85792f34868db
58,917
def get_recent_safe_block(time, sta, chan, margin_seconds=10, preferred_len_seconds=120, min_len_seconds=60, arrival_window_seconds=1200): """ Get a block of time preceding the specified time, and ending at least margin_seconds before that time, for which waveform data exists, and during which there are no recorded...
c7aa93b7c978f90d19baca20a16f0a32a8dad16d
58,918
def f_punct(w_list): """ :param w_list: word list to be processed :return: w_list with punct and number filter out """ return [word for word in w_list if word.isalpha()]
7cf7c4b812fffa6b7c77a96b53995366519232c5
58,919
from typing import Optional from typing import Union from typing import Tuple import torch def max_mpc( x: MPCTensor, dim: Optional[Union[int, Tuple[int]]] = None, keepdim=False, ) -> Union[MPCTensor, Tuple[MPCTensor, MPCTensor]]: """Compute the maximum value for an MPCTensor. Args: x (MP...
278bfd975ca816712c0cf4f80c91d577c14abe8b
58,920
def even(n: int) -> bool: """ Check that given number is even. >>> [(n, even(n)) for n in range(5)] [(0, True), (1, False), (2, True), (3, False), (4, True)] """ return n % 2 == 0
b96403b1b250560b29aafc253aaa1883f4018002
58,921
def is_owner(org): """ Function for checking if a user's org has ownership rights SINCE WE ARE KEEPING ACCESS CONTROL SIMPLE, WE ARE DEFAULTING THIS TO TRUE :param str org: An organization :return bool: whether the organization matches the current user or the group of admins """ return True ...
ba326c4524cd30038e5a8a1f88aa6b8f80b9a57f
58,922
def linear_model_loss_regularized_dx_lp(w, x, y, reg_coeff, norm_type): """Penalize by ||dL/dx||.""" loss_and_dloss_dx_f = jax.value_and_grad(linear_model_loss, argnums=1) loss, dloss_dx = loss_and_dloss_dx_f(w, x, y) reg = norm_f(dloss_dx, norm_type) return loss + reg_coeff * reg
c307eca6bec9d8788937a46301d0ed729b31ffe0
58,925
def cross_covariance(y, ym, z, zm, b): """ Computes the cross-covariance matrix between the rows of matrix `y` with those of matrix `z`. The method of Overlap Batch Mean (OBM) is employed with blocks of size `b`. """ Sy = _SumOfDeviationsPerBlock(y, ym, b) Sz = _SumOfDeviationsPerBlock(z, zm, b...
35ea390be9aff91e5b2531dbba3087b9044beef7
58,926
def api_get_logs(log_type, num_lines): """API to return the logs of appropriate type and logging window based on user selection. Args: log_type (str): Log type attribute name pointing to the log file location. Defined in the constants file. num_lines (int): Number...
35eb306cbc0ec74e72b3298f7e1473711c1cb9da
58,928
import random def sample_contact_points(contact_points, num_samples, get_idx=False): """Sampling contact points for the specified number Parameters ---------- contact_points : list[list[list[float], list[float]]] num_samples : int Returns ------- contact_points : list[list[list[float...
688d45a3653dae0ebb2a9261ced47684645d3d2d
58,930
import logging def get_messages_from_folder(folder, message_id, **kwargs): """Return list of messages matching message id in the given folder.""" _logger = kwargs.get("logger") or logging message_id = check_message_id_format(message_id) # We want to use filter WITHOUT conditional QuerySet queries... ...
485e56e658d66f9bea3b8afca7862d9fe916f737
58,931
def IsUUID(uuid: str) -> bool: """Verifies a string has the following valid RFC UUID format: 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'. Args: uuid (str): value that needs to be verified. Return: (boolean): true or false to if the value is valid. """ if len(uuid) ...
d6f948115076b8b995ce2c2d25015f875e254bf1
58,932
from astropy.io import fits def ref_from_image(input_image, reffile_lookup): """ Return a list of reference filenames, as defined in the primary header of the given input image, necessary for calibration. Parameters ---------- input_image : str FITS image to extract info from. re...
2e1898b47a1a41580e8fcb975963837d2a954a91
58,933
def shufflelr(x, width, dataset='mpii'): """ flip coords """ if dataset == 'mpii': matchedParts = ( [0,5], [1,4], [2,3], [10,15], [11,14], [12,13] ) elif dataset == 'h36m': matchedParts = ( [1,4], [2,5], [3,6], [11,14], ...
869e255230b9d0b56c070d2e4e9ac8257cab4842
58,934
def _compute_hal9000_md5(observable: Observable) -> str: """Given an Observable, return the hexdigest of the MD5 computation used for hal9000.""" md5_hasher = md5() md5_hasher.update(observable.type.encode('utf-8', errors='ignore')) md5_hasher.update(observable.value.encode('utf-8', errors='ignore')) ...
4b9c84e792a6ddda2e36a659612d08d8c8041e40
58,935
import json def get_context(): """ Retreive the URL parameters from the current request context """ args = request.args int_or_none = lambda x: int(x) if x is not None else None dict_or_none = lambda x: json.loads(x) if x is not None else None try: context = RequestContext( i...
a72c921943da281aefda1bd8ebd8c0d56ad7643f
58,936
def log_decoding_CanonLog3( clog3: FloatingOrArrayLike, bit_depth: Integer = 10, in_normalised_code_value: Boolean = True, out_reflection: Boolean = True, ) -> FloatingOrNDArray: """ Defines the *Canon Log 3* log decoding curve / electro-optical transfer function. Parameters -------...
66a1dffa9fe25763b1cefd15a6eb76c91d65f338
58,937
def line_intersection(A, B, C, D): """Assumes line segments AB vs. CD actually cross (must determine this separately), where points A - D have fields 'x' and 'y' e.g. a Point2D object. Uses algorithm from: http://www.bryceboe.com/2006/10/23/line-segment-intersection-algorithm/ and http://pa...
992996c805fe8623f50181dd265509cfd6b5ade8
58,938
def get_project_list_from_layout(request, layout_id): """ Return project ids, names and get-branch-list url """ if request.method != 'GET': return res.get_only_get_allowed({}) layout = BluesteelLayoutEntry.objects.filter(id=layout_id).first() if layout is None: return res.get_response(4...
8fa4c3c63fa117f16eb800b214cddfb50662637e
58,939
def percent_yield(actual_yield, theoretical_yield): """Finds theoretical_yield\n actual_yield:\n\tThe yield given in the equation\n theoretical_yield:\n\tThis yield can be calculated with the theoretical_yield() function""" yielded = (actual_yield / theoretical_yield) * 100 return yielded
ceef481ebae8be223bdb9b9c1f2c8a0c8713fcca
58,940
def name_propagation_inside_basic_block(ctx: FrozenBuildContext, instructions: list[Instruction]) -> tuple[list[Instruction], bool]: """ ``` x = L.message1 M.print_flush(y) ``` ⇓ ``` M.print_flush(L.message1) ``` """ basic_blocks, _cfg = _make_control_flow_graph(instructions)...
e7f9cf1c5ec66a00f64e681bdb58d5e6c16f861a
58,941
def is_na(value): """ Return True if value is None or NaN """ return value is None or is_nan(value)
90e23e7aeea018dc69f11e97fd4ae290ddb7d282
58,942
def url_auth_split(url): """extract authentication information from the given URL >>> url_auth_split('/path/to.git') == ('file:///path/to.git', None, None) True >>> result = ('ssh://git.example.com:2222/path/to.git', None, None) >>> url_auth_split('ssh://git.example.com:2222/path/to.git') == result...
d9bf66bbff7f09556509b9580e510204f903964c
58,943