content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def get_initialize_cams(number_of_camera = 7,use_camera=True): """ initialize all camera Args: number_of_camera (int, optional): [description]. Defaults to 7. Returns: list : in list cap object """ cap_list=[] if use_camera: for _ in range(1,number_of_camera+1): ...
374e987647d462fbc4bc755176f1c879b15be0e8
3,647,400
def vpc_security_group_list(rds_instance): """ If VPC security group rule is open to public add to List and return. Args: rds_instance (dict): All the running rds instance on the region Returns: list: List of VPC Security Group Id's """ vpc_list = []...
02fac45e235c8820d5890ab121feaf1a78a6416f
3,647,401
def expectation_l(u_values, params_list): """ compute proba for each copula mix to describe the data :param u_values: :param params_list: :return: """ l_state = np.zeros((u_values.shape[0], len(COPULA_DENSITY))) dcopula = np.zeros((u_values.shape[0], len(COPULA_DENSITY))) for copula ...
e446fe9b20e3909ca0fb864c86b0f652faf908a2
3,647,402
import scipy def lanczosSubPixShift( imageIn, subPixShift, kernelShape=3, lobes=None ): """ lanczosSubPixShift( imageIn, subPixShift, kernelShape=3, lobes=None ) imageIn = input 2D numpy array subPixShift = [y,x] shift, recommened not to exceed 1.0, should be float Random values of ke...
c7bbf51f94ab323ae9bf15f0af7c0d3dfa11aaeb
3,647,403
def open_pdb(file_location): """ Opens PDB File. Parameters __________ file_location : str The Location for the PDB File. Returns _______ symbols : list Gives Atomic Symbols for Atoms from PDB File. coordinates: np.ndarray Gives Atomic...
25a0946aeae277f4d60cdba79c7aa4f973853027
3,647,404
def _remove_statements(evaluator, stmt, name): """ This is the part where statements are being stripped. Due to lazy evaluation, statements like a = func; b = a; b() have to be evaluated. """ types = [] # Remove the statement docstr stuff for now, that has to be # implemented with the e...
022204865e1a44aa4741e8e42acd3a3ea66a1a38
3,647,405
from typing import Tuple def transform_vector_global_to_local_frame( vector: Tuple[float, float, float], theta: float ) -> Tuple[float, float, float]: """ Transform a vector from global frame to local frame. :param vector: the vector to be rotated :param theta: the amount to rotate by :return...
57e67029dfb9b6d8242930d6227d655508ae68c3
3,647,406
import IPython import IPython import os def given_source_ids_get_tic8_data(source_ids, queryname, n_max=10000, overwrite=True, enforce_all_sourceids_viable=True): """ Args: source_ids (np.ndarray) of np.int64 Gaia DR2 source_ids ...
4560ad9dcf4701bf9fefea5f15d3b40dc1a91d10
3,647,407
from typing import List def kadane_algorithm(sequence: List[int]): """Greedy algorithm to track max sum so far - O(n) time and O(1) space""" if len(sequence) < 1: return 0 max_sum = sequence[0] curr_sum = sequence[0] for curr_index in range(1, len(sequence)): curr_sum = max(sequ...
f6096309055e52538f9a5f9b5b769b269688b068
3,647,408
from typing import Iterable def allow_domains(request: HttpRequest, domains: Iterable[str]) -> HttpResponse: """ Serves a cross-domain access policy allowing a list of domains. Note that if this is returned from the URL ``/crossdomain.xml`` on a domain, it will act as a master policy and will not per...
38de0a97734893f618903bd5133dc794521effcf
3,647,409
def get_Cs_OR(): """その他の居室の照明区画iに設置された照明設備の人感センサーによる補正係数 Args: Returns: float: Cs_OR その他の居室の照明区画iに設置された照明設備の人感センサーによる補正係数 """ return 1.0
afcbbb70ad7589aa7dace741931c39434b444ba1
3,647,410
def build_url(station, d1, d2): """ Return the URL to fetch the response record for USArray MT station identifier *station* for the time range *d1* to *d2*. """ return 'http://service.iris.edu/irisws/resp/1/query?net=EM&sta={}&loc=--&cha=*&starttime={:%Y-%m-%dT%H:%M:%S}&endtime={:%Y-%m-%dT%H:%M:%S}'...
221d5f7a321d0e9337dbbe75e419298bcd3ab5c0
3,647,411
import os import logging def FindGitSubmoduleCheckoutRoot(path, remote, url): """Get the root of your git submodule checkout, looking up from |path|. This function goes up the tree starting from |path| and looks for a .git/ dir configured with a |remote| pointing at |url|. Arguments: path: The path to s...
8954e374e1cfeaa7db159538d38a524b33898ae0
3,647,412
def get_tlinks(timeml_doc): """ get tlinks from annotated document """ root = xml_utilities.get_root(timeml_doc) tlinks = [] for e in root: if e.tag == "TLINK": tlinks.append(e) return tlinks
376136a647f6525136643e67c85925268813296a
3,647,413
from typing import Sequence from typing import Any def stack(xs: Sequence[Any], axis: int = 0) -> Any: """ Stack the (leaf) arrays from xs :param xs: list of trees with the same shape, where the leaf values are numpy arrays :param axis: axis to stack along """ return multimap(lambda *xs: np.s...
af2a7d6baf23597caf83bb4dcbb226d255c7dcbb
3,647,414
import csv def load_LAC_geocodes_info(path_to_csv): """Import local area unit district codes Read csv file and create dictionary with 'geo_code' PROVIDED IN UNIT?? (KWH I guess) Note ----- - no LAD without population must be included """ with open(path_to_csv, 'r') as csvfile: ...
bd97d888ddb58469b111b41a7ea0a5a9e0be88fd
3,647,415
def singleton(class_): """Decorator for singleton class.""" instances = {} def get_instance(*args, **kwargs): if class_ not in instances: instances[class_] = class_(*args, **kwargs) return instances[class_] return get_instance
3dbc0e9525812b2698bc3be21aed18028eb39408
3,647,416
def convert_model_to_half(model): """ Converts model to half but keeps the batch norm layers in 32 bit for precision purposes """ old_model = model new_model = BN_convert_float(model.half()) del old_model # Delete previous non-half model return new_model
3902ce122fa2fd89d7bf5d35e91fbf743b698bc7
3,647,417
def tokenize_sentences(sentences): """ Tokenize sentences into tokens (words) Args: sentences: List of strings Returns: List of lists of tokens """ # Initialize the list of lists of tokenized sentences tokenized_sentences = [] ### START CODE HERE (Replace i...
8c6b1cb4dd390051755cf17df533f3a1ff71b1a3
3,647,418
import os def verify_credential_info(): """ This url is called to verify and register the token """ challenge = session["challenge"] username = session["register_username"] display_name = session["register_display_name"] ukey = session["register_ukey"] user_exists = database.user_exist...
faf7717de5ff2bad46bf7fc1e661a162473fe6dd
3,647,419
def makeId(timestamp = 0, machine = 0, flow = 0): """ using unix style timestamp, not python timestamp """ timestamp -= _base return (timestamp<<13) | (machine << 8) | flow
29b175f07cb6e5c7ddc1f77f1fb7871514abc7df
3,647,420
def chi2Significant(tuple, unigrams, bigrams): """Returns true, if token1 and token2 are significantly coocurring, false otherwise. The used test is the Chi2-test. Parameters: tuple: tuple of tokens unigrams: unigrams dictionary data structure bigrams: bigrams dictionary...
79c55bb581ed4714c6e455d8ee85d923604fe6b6
3,647,421
def excel2schema(schema_excel_filename, schema_urlprefix, options, schema_dir=None): """ given an excel filename, convert it into memory object, and output JSON representation based on options. params: schema_excel_filename -- string, excel filename schema_urlprefix -- strin...
9d19fef99f9ca56f463a3559d7b5f5342f12067b
3,647,422
def assign_id_priority(handle): """ Assign priority according to agent id (lower id means higher priority). :param agent: :return: """ return handle
8e1b22748d263fc12749790e601a4197b5d6370e
3,647,423
def learning_rate_with_decay( batch_size, batch_denom, num_images, boundary_epochs, decay_rates): """Get a learning rate that decays step-wise as training progresses. Args: batch_size: the number of examples processed in each training batch. batch_denom: this value will be used to scale the...
8d33c30e47c27e6de974a342638e0017026be15d
3,647,424
def stepedit_SignType(*args): """ * Returns a SignType fit for STEP (creates the first time) :rtype: Handle_IFSelect_Signature """ return _STEPEdit.stepedit_SignType(*args)
d22a33dab4764924f7bd6645deee70403e6f3b39
3,647,425
def create_heatmap(out, data, row_labels, col_labels, title, colormap, vmax, ax=None, cbar_kw={}, cbarlabel="", **kwargs): """ Create a heatmap from a numpy array and two lists of labels. Arguments: data : A 2D numpy array of shape (N,M) row_labels : A list or array of len...
c060951e0c830444665c0a3c5a9b6e244ae32bb4
3,647,426
def ccw(a: complex, b: complex, c: complex) -> int: """The sign of counter-clockwise angle of points abc. Args: a (complex): First point. b (complex): Second point. c (complex): Third point. Returns: int: If the three points are not colinear, then returns the sign of ...
d6fac5f560b26299e2bf7aefef0ebabf33672323
3,647,427
def _tree_selector(X, leaf_size=40, metric='minkowski'): """ Selects the better tree approach for given data Parameters ---------- X : {array-like, pandas dataframe} of shape (n_samples, n_features) The input data. leaf_size : int, default=40 Number of points to switch to brute-...
ad0d175c17585009fb92e6f4a813b1a1ef19e535
3,647,428
def get_diff_objects(diff_object_mappings, orig_datamodel_object_list): """获取diff_objects :param diff_object_mappings: 变更对象内容mapping :param orig_datamodel_object_list: 操作前/上一次发布内容列表 :return: diff_objects: diff_objects列表 """ # 1)从diff_object_mappings中获取diff_objects diff_objects = [] fie...
d6619b289944dba9f541b1f893d0f908b9ee8b48
3,647,429
def find_lcs(s1, s2): """find the longest common subsequence between s1 ans s2""" m = [[0 for i in range(len(s2) + 1)] for j in range(len(s1) + 1)] max_len = 0 p = 0 for i in range(len(s1)): for j in range(len(s2)): if s1[i] == s2[j]: m[i + 1][j + 1] = m[i][j] + 1...
3b35307c6ab287d2088d25bb3826589d7d62be8b
3,647,430
def calculate_vertical_vorticity_cost(u, v, w, dx, dy, dz, Ut, Vt, coeff=1e-5): """ Calculates the cost function due to deviance from vertical vorticity equation. For more information of the vertical vorticity cost function, see Potvin et al. (2012) and Shapiro et a...
6abc76df0f75f827b1048cdb07d71bbb311d7ef5
3,647,431
import httpx def fetch_hero_stats() -> list: """Retrieves hero win/loss statistics from OpenDotaAPI.""" r = httpx.get("https://api.opendota.com/api/heroStats") heroes = r.json() # Rename pro_<stat> to 8_<stat>, so it's easier to work with our enum for hero in heroes: for stat in ["win", "p...
1362beaa82eeb29859df4fe1280d6ac7b1073be1
3,647,432
def test_source_locations_are_within_correct_range(tokamak_source): """Tests that each source has RZ locations within the expected range. As the function converting (a,alpha) coordinates to (R,Z) is not bijective, we cannot convert back to validate each individual point. However, we can determine wheth...
5c7c668c73403e1c5d37b852e110fcdf8a36023e
3,647,433
def GetTDryBulbFromEnthalpyAndHumRatio(MoistAirEnthalpy: float, HumRatio: float) -> float: """ Return dry bulb temperature from enthalpy and humidity ratio. Args: MoistAirEnthalpy : Moist air enthalpy in Btu lb⁻¹ [IP] or J kg⁻¹ HumRatio : Humidity ratio in lb_H₂O lb_Air⁻¹ [IP] or kg_H₂O kg...
3ea565eb338913f9c87e2e4d260606e437d30f8c
3,647,434
def calibration_runs(instr, exper, runnum=None): """ Return the information about calibrations associated with the specified run (or all runs of the experiment if no specific run number is provided). The result will be packaged into a dictionary of the following type: <runnum> : { 'calibrations...
7f5f3d274c03664e87a13946ea21978ecdd30d74
3,647,435
def fetch_eia(api_key, plant_id, file_path): """ Read in EIA data of wind farm of interest - from EIA API for monthly productions, return monthly net energy generation time series - from local Excel files for wind farm metadata, return dictionary of metadata Args: api_key(:obj:`string`): 32...
cb7543b0ceeacacfd699c94f677dd9c1200c8714
3,647,436
def calc_dist_mat(e: Extractor, indices: list) -> np.array: """ Calculates distance matrix among threads with indices specified Arguments: e : Extractor extractor object indices : list of ints list of indices corresponding to which threads are present for the distance matrix calculation """ # initiali...
9398990dd0444b6a1d3a00a9c09a08f88d752b83
3,647,437
def spitzer_conductivity2(nele, tele, znuc, zbar): """ Compute the Spitzer conductivity Parameters: ----------- - nele [g/cm³] - tele [eV] - znuc: nuclear charge - zbar: mean ionization Returns: -------- - Spitzer conductivity [cm².s⁻¹] """ lnLam = coulomb_loga...
3337515bbb989d8a7fb4994ab9e654781b2a7216
3,647,438
import re def parse_benchmark_results(benchmark_output, min_elements=None, max_elements=None): """ :type benchmark_output list[str] :type min_elements int|None :type max_elements int|None :rtype BenchmarkResults :return The parsed benchmark results file. The data member dict looks like this: ...
e4994e77e61ca67ee47677ba75573ab65199c1d4
3,647,439
import os import sys def is_doctest_running() -> bool: """ >>> if not is_setup_test_running(): assert is_doctest_running() == True """ # this is used in our tests when we test cli-commands if os.getenv("PYTEST_IS_RUNNING"): return True for argv in sys.argv: if is_doctest_in_ar...
29c1ca4973cab5b51f34800d5fb0abe026286128
3,647,440
def read_float_with_comma(num): """Helper method to parse a float string representation that has a comma as decimal separator. Can't use locale as the page being parsed could not be in the same locale as the python running environment Args: num (str): the float string to parse Returns...
ff2e65ef35ba1fded06d8abb5ed252a6bffdceaa
3,647,441
def remote_repr(arg): """Return the `repr()` rendering of the supplied `arg`.""" return arg
d284a0f3a6d08ceae198aacf68554da9cc264b1b
3,647,442
def log(pathOrURL, limit=None, verbose=False, searchPattern=None, revision=None, userpass=None): """ :param pathOrURL: working copy path or remote url :param limit: when the revision is a range, limit the record count :param verbose: :param searchPattern: - search in the limited records(by p...
ba489018ea9e1cdaec62620711421df2aa2c3617
3,647,443
def value_cards(cards: [Card], trump: Suite, lead_suite: Suite) -> (Card, int): """Returns a tuple (card, point value) which ranks each card in a hand, point value does not matter""" card_values = [] for card in cards: if vm.is_trump(card, trump): card_values.append((card, vm.trump_value...
3d89e1db3dee8a7af881a236c1328b70eb7ef2c7
3,647,444
import atexit def mount_raw_image(path): """Mount raw image using OS specific methods, returns pathlib.Path.""" loopback_path = None if PLATFORM == 'Darwin': loopback_path = mount_raw_image_macos(path) elif PLATFORM == 'Linux': loopback_path = mount_raw_image_linux(path) # Check if not loopback_...
a3923bbebb0ec20a0ed380af54942f9c69071ea0
3,647,445
import math def calculate_weights_indices(in_length, out_length, scale, kernel_width, antialiasing): """ Get weights and indices """ if (scale < 1) and (antialiasing): # Use a modified kernel to simultaneously interpolate and antialias- larger kernel width kernel_width = kernel_width /...
bdbbe2ed1b10bad70c116c99524691a450626a8d
3,647,446
def adfuller_test(series, signif=0.05, name='', verbose=False): """Perform ADFuller to test for Stationarity of given series, print report and return if series is stationary""" r = adfuller(series, autolag='AIC') output = {'test_statistic': round(r[0], 4), 'pvalue': round(r[1], 4), 'n_lags': round(r[2], 4),...
03c91c771b6f514bf614af69c3f9db607b256498
3,647,447
def datetime_to_timestring(dt_): """ Returns a pretty formatting string from a datetime object. For example, >>>datetime.time(hour=9, minute=10, second=30) ..."09:10:30" :param dt_: :class:`datetime.datetime` or :class:`datetime.time` :returns: :class:`str` """ return pad(dt_.hour)...
541adb72ee7c8cf1dc2f9755a37c90d6120189e2
3,647,448
import importlib from typing import Type def get_class_for_name(name: str, module_name: str = __name__) -> Type: """Gets a class from a module based on its name. Tread carefully with this. Personally I feel like it's only safe to use with dataclasses with known interfaces. Parameters ---------- ...
73058c179187aac277221b33f4e1e65934a49a6a
3,647,449
def get_cache_file_static(): """ Helper function to get the path to the VCR cache file for requests that must be updated by hand in cases where regular refreshing is infeasible, i.e. limited access to the real server. To update this server recording: 1) delete the existing recording 2) re-r...
44649f243322230a1a750e038d66cef725fbbc9b
3,647,450
def intervals_where_mask_is_true(mask): """Determine intervals where a 1D boolean mask is True. Parameters ---------- mask : numpy.ndarray Boolean mask. Returns ------- ranges : list List of slice intervals [(low, upp), ...] indicating where the mask has `True` valu...
77376598c0c1937a67125ecfd144bd6c50d2913a
3,647,451
def get_FAAM_mineral_dust_calibration(instrument='PCASP', rtn_values=True): """ Retrieve FAAM mineral dust calibration """ # Location and name of calibration files? folder = '{}/FAAM/'.format(get_local_folder('ARNA_data')) if instrument == 'PCASP': # NOTE: range ~0.1-4 microns f...
e9d7d9241ea7afab00d29e44404904e494141faa
3,647,452
import joblib def load_classifier(path=False): """ Load the ALLSorts classifier from a pickled file. ... Parameters __________ path : str Path to a pickle object that holds the ALLSorts model. Default: "/models/allsorts/allsorts.pkl.gz" Returns __________ allsor...
f74402cea1cb329036b9e95c8c6264ee15584c65
3,647,453
import requests import time def get_response(url: str, *, max_attempts=5) -> requests.Response: """Return the response. Tries to get response max_attempts number of times, otherwise return None Args: url (str): url string to be retrieved max_attemps (int): number of request attempts for sa...
7d5a01cd3535fbdae9bc0e502409300dd05be76c
3,647,454
def hamming_distance(lhs, rhs): """Returns the Hamming Distance of Two Equal Strings Usage >>> nt.hamming_distance('Pear','Pearls') """ return len([(x, y) for x, y in zip(lhs, rhs) if x != y])
8bf24f47c829169cfaa89af755b7722eb26155d9
3,647,455
def get_uleb128(byte_str): """ Gets a unsigned leb128 number from byte sting :param byte_str: byte string :return: byte string, integer """ uleb_parts = [] while byte_str[0] >= 0x80: uleb_parts.append(byte_str[0] - 0x80) byte_str = byte_str[1:] uleb_parts.append(byte_str[...
1e9c02dc7c191686e7d7a19d8b8c82f95044c845
3,647,456
def expired_response(): """ Expired token callback. Author: Lucas Antognoni Arguments: Response: json { 'error': (boolean), 'message': (str) } Response keys: - 'er...
1cf4ecc4ea0ee9ca51379d0990ff957f558f1557
3,647,457
def check_shots_vs_bounds(shot_dict, mosaic_bounds, max_out_of_bounds = 3): """Checks whether all but *max_out_of_bounds* shots are within mosaic bounds Parameters ---------- shot_dict : dict A dictionary (see czd_utils.scancsv_to_dict()) with coordinates of all shots in a .scancsv file...
de36f7f2a32a2a7120236d0bd5e43520de0c7ea5
3,647,458
import torch def wrap(func, *args, unsqueeze=False): """ Wrap a torch function so it can be called with NumPy arrays. Input and return types are seamlessly converted. :param func: :param args: :param unsqueeze: :return: """ # Convert input types where applicable args = list(ar...
a611458daea9b0ec780237a102b00f126370ffc4
3,647,459
from typing import Iterable from typing import Tuple from typing import Any def iter_schemas(schema: Schema, strict_enums: bool = True) -> Iterable[Tuple[str, Any]]: """ Build zero or more JSON schemas for a marshmallow schema. Generates: name, schema pairs. """ builder = Schemas(build_parameter...
a0f203d00caa74562d0ff6fa077b236b23a2946b
3,647,460
import dill def deserializer(serialized): """Example deserializer function with extra sanity checking. :param serialized: Serialized byte string. :type serialized: bytes :return: Deserialized job object. :rtype: kq.Job """ assert isinstance(serialized, bytes), "Expecting a bytes" retu...
8895a1c40eaf5e30dd10015b87a0b94da0edf9ac
3,647,461
def sym_auc_score(X, y): """Compute the symmetric auroc score for the provided sample. symmetric auroc score is defined as 2*abs(auroc-0.5) Parameters ---------- X : {array-like, sparse matrix} shape = [n_samples, n_features] The set of regressors that will be tested sequentially. y : ...
77427e57fc737a0daffe8b966b51ad0ae3602ceb
3,647,462
def visibility_of_element_wait(driver, xpath, timeout=10): """Checking if element specified by xpath is visible on page :param driver: webdriver instance :param xpath: xpath of web element :param timeout: time after looking for element will be stopped (default: 10) ...
964c2254af36361fb2390e4192208ec3e5f02a2d
3,647,463
def _read_byte(stream): """Read byte from stream""" read_byte = stream.read(1) if not read_byte: raise Exception('No more bytes!') return ord(read_byte)
767766ef0d7a52c41b7686f994a503bc8cc7fe8d
3,647,464
from directions.models import Issledovaniya import xlwt from collections import OrderedDict from operator import itemgetter import directions.models as d from operator import itemgetter from django.utils.text import Truncator import directions.models as d from operator import itemgetter import json from datetime import...
62ce2d5ab3e036fa74783e1b96169ff477bc6abd
3,647,465
import os def populate_labels(model_name: str, paths: dict) -> list: """Report full list of object labels corresponding to detection model of choice Args: model_name: name of the model to use paths: dictionary of paths from yml file Returns: labels (list(str)):...
e225afc71567c1d3fac07aff9f76d3333dba2cf2
3,647,466
def get_checkers(): """Get default checkers to run on code. :returns: List of default checkers to run. """ return [function, readability]
c4a7668e1f2ca0d8d9dc673b43274065551023b5
3,647,467
def get_token(): """ Get or create token. """ try: token = Token.objects.get(name=settings.TOKEN_NAME) except Token.DoesNotExist: client_id = raw_input("Client id:") client_secret = raw_input("Client secret:") token = Token.objects.create( name=settings.TO...
107f0dfc7148d4964f181e2f7ff14038860a56ab
3,647,468
def get_labels_from_sample(sample): """ Each label of Chinese words having at most N-1 elements, assuming that it contains N characters that may be grouped. Parameters ---------- sample : list of N characters Returns ------- list of N-1 float on [0,1] (0 represents no split) """ ...
4b21b878d1ae23b08569bda1f3c3b91e7a6c48b9
3,647,469
import warnings def _recarray_from_array(arr, names, drop_name_dim=_NoValue): """ Create recarray from input array `arr`, field names `names` """ if not arr.dtype.isbuiltin: # Structured array as input # Rename fields dtype = np.dtype([(n, d[1]) for n, d in zip(names, arr.dtype.descr)]) ...
7e041dac3f0e74f82bd36a02174edc39950030d3
3,647,470
def pad(mesh: TriangleMesh, *, side: str, width: int, opts: str = '', label: int = None) -> TriangleMesh: """Pad a triangle mesh. Parameters ---------- mesh : TriangleMesh The mesh to pad. side : str Side to pad, must be one of `left`, `right`...
7da2a20b060a6243cd3d1c4ec3192cfba833fd27
3,647,471
from desimodel import footprint from desitarget import io as dtio import time def make_qa_plots(targs, qadir='.', targdens=None, max_bin_area=1.0, weight=True, imaging_map_file=None, truths=None, objtruths=None, tcnames=None, cmx=False, bit_mask=None, mocks=False): """Make DESI...
a7dffff1273456ac387fe68e71e154f385610ac5
3,647,472
import itertools from re import I from re import X def krauss_basis(qubits): """ Helper function to return the Krauss operator basis formed by the Cartesian product of [I, X, Y, Z] for the n-qubit. :param qubits: number of qubits :type qubits: int :return: Krauss operator :rtype: np.ndar...
471ddb5dc1840f162cd8a0f64789b1d0afa2d712
3,647,473
def choose_fun_cov(str_cov: str) -> constants.TYPING_CALLABLE: """ It chooses a covariance function. :param str_cov: the name of covariance function. :type str_cov: str. :returns: covariance function. :rtype: callable :raises: AssertionError """ assert isinstance(str_cov, str) ...
1c0fd2d06456ec0765186694a9cb0e78a511859e
3,647,474
async def error_500(request, error: HTTPException): """ TODO: Handle the error with our own error handling system. """ log.error( "500 - Internal Server Error", exc_info=(type(error), error, error.__traceback__), ) return JSONResponse( status_code=500, content={ ...
dfb1d5b31e057395d5374e21b2f38ae44feb2fee
3,647,475
def log_sum_exp(x): """Utility function for computing log_sum_exp while determining This will be used to determine unaveraged confidence loss across all examples in a batch. Args: x (Variable(tensor)): conf_preds from conf layers 确定时用于计算的实用函数(log_sum_exp) 这将用于确定批处理中所有示例的不可用信心损失。 参数: x(变量(...
dc18d31b85c0c29dab39874ba4d4148fef868106
3,647,476
def session_hook(func): """ hook opens a database session do a session_hook(read or write) and closes the connection after the run() func: function that communicates with the database (e.g fun(*args, db: Session)) returns; data: The return from func error: in case of an error...
74e22a5adbfc470c3dbc068eb4b190608b2b426e
3,647,477
from datetime import datetime def float_index_to_time_index(df): """Convert a dataframe float indices to `datetime64['us']` indices.""" df.index = df.index.map(datetime.utcfromtimestamp) df.index = pd.to_datetime(df.index, unit="us", utc=True) return df
5e7d1aa8430afd22ad4e3f931dc39b8a480c3ffa
3,647,478
def correlated_hybrid_matrix(data_covmat,theory_covmat=None,theory_corr=None,cap=True,cap_off=0.99): """ Given a diagonal matrix data_covmat, and a theory matrix theory_covmat or its correlation matrix theory_corr, produce a hybrid non-diagonal matrix that has the same diagonals as the data matrix b...
0438f7bc0d5aa34506af59b74d990b21713e5e6d
3,647,479
from typing import OrderedDict def prepare_config(self, config=None): """Set defaults and check fields. Config is a dictionary of values. Method creates new config using default class config. Result config keys are the same as default config keys. Args: self: object with get_default_config m...
4876ac8900857cb3962d22f0afe99e6426d1ff5c
3,647,480
import re import math def number_to_block(number, block_number=0): """ Given an address number, normalizes it to the block number. >>> number_to_block(1) '0' >>> number_to_block(10) '0' >>> number_to_block(100) '100' >>> number_to_block(5) '0' >>> number_to_block(53) '0...
1504d79469dccc06e867fbf5a80507566efb5019
3,647,481
import matplotlib from matplotlib import pyplot import numpy def pf_active_overlay(ods, ax=None, **kw): """ Plots overlays of active PF coils. INCOMPLETE: only the oblique geometry definition is treated so far. More should be added later. :param ods: OMAS ODS instance :param ax: axes instance in...
297e4387a2b49ce8cf75e9f4ae4e665bf8ee82b8
3,647,482
import math def distance_between_vehicles(self_vhc_pos, self_vhc_orientation, self_vhc_front_length, self_vhc_rear_length, self_vhc_width, ext_vhc_pos, ext_vhc_orientation, ext_vhc_width, ext_vhc_rear_length, ext_vhc_front_length): """Only in 2-D space (...
bcd10598ff83d2ca1e2a03eb759649346151d475
3,647,483
def searchlight_dictdata(faces, nrings, vertex_list): """ Function to generate neighbor vertex relationship for searchlight analysis The format of dictdata is [label]:[vertices] Parameters: ----------- faces: nrings: vertex_list: vertex-index relationship, e.g. vertex_list[29696] = 3249...
10f89bf6981b474a202e836be0aeeb13afa5f873
3,647,484
def parse_resource_uri(resource_uri): """ Parse a resource uri (like /api/v1/prestataires/1/) and return the resource type and the object id. """ match = resource_pattern.search(resource_uri) if not match: raise ValueError("Value %s is not a resource uri." % resource_uri) return mat...
f5c6ef26b1546a5b51c290701863f60c6f518e60
3,647,485
from typing import List def foldl(func: tp.Callable, acc, lst: List): """ >>> foldl(lambda x, y: x + y, 0, Nil()) 0 >>> foldl(lambda x, y: x + y, 2, from_seq([1, 2, 3])) 8 >>> foldl(lambda x, y: x - y, 1, from_seq([3, 2, 1])) -5 """ return acc if null(lst) else foldl(func, func(acc...
397582c1fbdcad4b46f8d64960fc1562aefa9ff8
3,647,486
def generate_rules(F, support_data, min_confidence=0.5, verbose=True): """Generates a set of candidate rules from a list of frequent itemsets. For each frequent itemset, we calculate the confidence of using a particular item as the rule consequent (right-hand-side of the rule). By testing and merging ...
687b2158d5460d9993c10bbded91d01eda4cbfec
3,647,487
def cond_model(model1, model2): """Conditional. Arguments: model1 {MentalModel} -- antecedent model2 {MentalModel} -- consequent Returns: MentalModel -- the conditional model """ mental = and_model(model1, model2) mental.ell += 1 fully = merge_fullex( and_mo...
d4d923b10f6140defc59dbf10b682422ff1014a0
3,647,488
def get_pages(): """Select all pages and order them by page_order.""" pages = query_db("SELECT page_order, name, shortname, available FROM pages ORDER BY page_order") return pages
b0b3f934c0c7133a798f3d78e195c4d26dcf590b
3,647,489
def set_default_interface(etree): """ Sets the default interface that PyAMF will use to deal with XML entities (both objects and blobs). """ global types, ET, modules t = _get_etree_type(etree) _types = set(types or []) _types.update([t]) types = tuple(_types) modules[t] = et...
ed2aee2bb029a3a07d18cfea1b6887d236d5c48c
3,647,490
import pdb def atom_site(block): """Handle ATOM_SITE block. Data items in the ATOM_SITE category record details about the atom sites in a macromolecular crystal structure, such as the positional coordinates, atomic displacement parameters, magnetic moments and directions. (source: http://mmci...
cdd39d44294f9a1a1de27d8b29558a296176a407
3,647,491
from typing import Counter import base64 def return_var_plot(result, attr_name, attr_type, option=0): """Method that generates the corresponding plot for each attribute, based on the type and the selection of the user.""" aval = f'{attr_name}_value' if attr_type == 'NUMBER' or attr_type == 'DATE_TIME...
e1046bd3b41c9e7827ebf379578cc1d85396345e
3,647,492
def get_inequivalent_sites(sub_lattice, lattice): """Given a sub lattice, returns symmetry unique sites for substitutions. Args: sub_lattice (list of lists): array containing Cartesian coordinates of the sub-lattice of interest lattice (ASE crystal): the total lattice Returns:...
39d8c827cde10053dc5508cb96f0a7d0c8b9d00e
3,647,493
def cone_emline(ra, dec, radius=5, selectcol=['specObjID', 'ra', 'dec', 'z', 'zErr', 'bpt', 'Flux_Ha_6562', 'Flux_NII_6583', 'Flux_Hb_4861', 'Flux_OIII_5006']): """ box search in emissionLinesPort table ra, dec in degrees, size in arcsec. Columns described in http://skyserver.sdss.org/dr16/en/help/browser/b...
abf25a3c76f792dbf3078618652864c2012671f9
3,647,494
import torch def kld(means, var): """KL divergence""" mean = torch.zeros_like(means) scale = torch.ones_like(var) return kl_divergence(Normal(means, torch.sqrt(var)), Normal(mean, scale)).sum(dim=1)
43652b302131efc8fa97940bec9918eeb8c97bf3
3,647,495
def add(vec_1, vec_2): """ This function performs vector addition. This is a good place to play around with different collection types (list, tuple, set...), :param vec_1: a subscriptable collection of length 3 :param vec_2: a subscriptable collection of length 3 :return vec_3: a subscriptable ...
4a17a82422cef472decb37c376e8bf5259ade60a
3,647,496
from typing import Union from typing import List from typing import Any import random def generateOrnament(fromMIDINote:int, key:Key, mode:ModeNames, bpm:float) -> Union[List[Any],None]: """ Generate OSC arguments describing ornaments, with the form: [ <ornamentName> <BPM> <beatSubdivision> [<listOf...
6bbaa53cd42322474b6a8cf40c698e4edfd32497
3,647,497
def ms_to_samples(ms, sampling_rate): """ Convert a duration in milliseconds into samples. Arguments: ms (float): Duration in ms. sampling_rate (int): Sampling rate of of the signal. Returns: int: Duration in samples. """ return int((ms / 1000) ...
a2bf63ad8cca580ae3307c33daa82bb1382d742c
3,647,498
def flatten(L): """Flatten a list recursively Inspired by this fun discussion: https://stackoverflow.com/questions/12472338/flattening-a-list-recursively np.array.flatten did not work for irregular arrays and itertools.chain.from_iterable cannot handle arbitrarily nested lists :param L: A list to...
c554a01a8308341d1c9620edc0783689e75fb526
3,647,499