content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
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
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 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
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
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 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
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
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
def chi2(observed, expected): """ Return the chi2 sum of the provided observed and expected values. :param observed: list of floats. :param expected: list of floats. :return: chi2 (float). """ if 0 in expected: return 0.0 return sum((_o - _e) ** 2 / _e ** 2 for _o, _e in zip(o...
6050e98a823671de4a518d584a6e39bc519fa610
3,647,502
import math def range_bearing(p1: LatLon, p2: LatLon, R: float = NM) -> tuple[float, Angle]: """Rhumb-line course from :py:data:`p1` to :py:data:`p2`. See :ref:`calc.range_bearing`. This is the equirectangular approximation. Without even the minimal corrections for non-spherical Earth. :param p1...
68860efbea6d8f1b36ff9e7b91a2a3779a57e611
3,647,503
import json import logging def cf_model_to_life(first_best, update_prod=False, pr_cache=False): """ We simulate the response of several variables to a shock to z and x. We fixed the cross-section distribution of (X,Z) and set rho to rho_start We apply a permanent shock to either X or Z, and fix the em...
131fd2a0edb202adacafd9a6416fecb7a1f77dc7
3,647,504
def kde_interpolation(poi, bw='scott', grid=None, resolution=1, area=None, return_contour_geojson=False): """Applies kernel density estimation to a set points-of-interest measuring the density estimation on a grid of places (arbitrary points regularly spaced). Parameters ---------- poi : GeoDat...
f0473e459e42075a3ad4070325aecb229b6b2d89
3,647,505
def nums2tcrs(nums): """Converts a list containing lists of numbers to amino acid sequences. Each number is considered to be an index of the alphabet.""" tcrs_letter=[] n=len(nums) for i in range(n): num=nums[i] tcr='' for j in range(len(num)): tcr+=alphabet[num[j]] ...
3f366e0bd593b799c7e88c84d583e7c6aeee066f
3,647,506
def extract_columns(data): """ EXTRACTS COLUMNS TO USE IN `DictWriter()` """ columns = [] column_headers = data[0] for key in column_headers: columns.append(key) return columns
6df143107612d311ab3c8870b9eccd3528ac3802
3,647,507
import numpy def cylindric_grid(dr, dz, origin_z=None, layer=False, material="dfalt"): """ Generate a cylindric mesh as a radial XZ structured grid. Parameters ---------- dr : array_like Grid spacing along X axis. dz : array_like Grid spacing along Z axis. origin_z : scala...
bf710bc212068ec76eb19edce3e8493689535697
3,647,508
import urllib def get_clip_preview_feedback(program, event, classifier, start_time, audio_track, reviewer): """ Gets the feedback provided by a user for a Segment's clip Returns: Feedback if present. Empty Dictionary of no feedback exists. """ event = urllib.parse.unquote(event) prog...
578952869606951057b8b8797698c320a02d1d00
3,647,509
import ast import numpy def interp(specStr, t): """Return the current value of t using linear interpolation. <specStr> is a string containing a list of pairs e.g. '[[0,20],[30,65],[60,50],[90,75]]' The first element of each pair is DAYS. The second is a NUMBER. <t> is time in seconds""" ...
bc60affe122f2d17044e01a01509231e71eda47d
3,647,510
from bs4 import BeautifulSoup def time_is(location): """ Retrieves the time in a location by parsing the time element in the html from Time.is . :param location: str location of the place you want to find time (works for small towns as well). :return: time str or None on failure. """ if Beauti...
e8f6675199f070fcad7eead98187683b48417757
3,647,511
import logging def _generate_template_context(arguments: PackagingResourceArguments, manifest: OdahuProjectManifest, output_folder: str) -> DockerTemplateContext: """ Generate Docker packager context for templates """ logging.info('Building...
e973a44949d6d2df8bfcbf0be42b8214d1c95352
3,647,512
def get_records(fname): """ Read the records of an IRAF database file into a python list Parameters ---------- fname : str name of an IRAF database file Returns ------- A list of records """ f = open(fname) dtb = f.read() f.close() recs = dtb.split('b...
a1eb4500afcd1379db1efe8674c1ff256f2861b5
3,647,513
from typing import List def get_all_clips_matching_filter(fid: int) -> List[Clip]: """ gets all te clips that is part of the project and matches the filter :param fid: The filter the clips should match :return: A list of all clips that is part of the project and matches the filter """ filter ...
eb69bf40ad397e970d85b425d4c2c0b25ee345fc
3,647,514
def get_gushim(): """ get gush_id metadata """ detailed = request.args.get('detailed', '') == 'true' gushim = helpers._get_gushim(fields={'gush_id': True, 'last_checked_at': True, '_id': False}) if detailed: # Flatten list of gushim into a dict g_flat = dict((g['gush_id'], {"gush...
93a941090f515bb726e305856ec6e0ea644b5a34
3,647,515
def dump_source(buf, id): """Dump BASIC source.""" if id == ID_SP5030: line_end_code = 0x0d src_end_code = 0x0000 kind = "SP-5030" elif id == ID_SBASIC: line_end_code = 0x00 src_end_code = 0x0000 kind = "S-BASIC" elif id == ID_HUBASIC: line_end_co...
598fe1d9dd4be6f1c651be4f81bc9f8290496c3a
3,647,516
def dense_layers(sequences, training, regularizer, initializer, num_layers=3, activation=tf.nn.relu): """ Create a chain of dense (fully-connected) neural network layers. Args: sequences (tf.Tensor): Input sequences. training (bool): Whether the mode is training or not. ...
72cebd7eb6487555c3efe8e6c14954dc2886e0c3
3,647,517
def apply_cst(im, cst): """ Applies CST matrix to image. Args: im: input ndarray image ((height * width) x channel). cst: a 3x3 CST matrix. Returns: transformed image. """ result = im for c in range(3): result[:, :, c] = (cst[c, 0] * im[:, :, 0] + cst[c, 1] * im[:, :, 1] + ...
7c63d07413bad5fcebf2dfe5f83f205d16280957
3,647,518
from typing import Tuple import torch def show_binary_classification_accuracy(best_m: nn.Module, local_loader: data_utils.DataLoader, chatty = False) -> Tuple: """ Given the model and dataloader, calculate the classification accuracy. Returns true_positives, true_negatives, false_positives, false_negative...
7743c51a8f64c46c625ccc3b8737b9553f79334f
3,647,519
def block_device_mapping_destroy(context, bdm_id): """Destroy the block device mapping.""" return IMPL.block_device_mapping_destroy(context, bdm_id)
2ad0fcc50721fe30e4d48f691420393748bf9df3
3,647,522
def feedback(olsys,H=1): """Calculate the closed-loop transfer function olsys cltf = -------------- 1+H*olsys where olsys is the transfer function of the open loop system (Gc*Gp) and H is the transfer function in the feedback loop (H=1 for unity feedback).""" ...
ca78d05196068746a225038c0f401faad24c5f65
3,647,523
from typing import List def get_sigma_grid( init_sigma: float = 1.0, factor: int = 2, n_grid_points: int = 20 ) -> List[float]: """Get a standard parameter grid for the cross validation strategy. Parameters ---------- init_sigma : float, default=1.0 The initial sigma to use to populat...
33e49127bb2e116b8c209446ad1f614c44e5e128
3,647,524
def parse_csv(value_column): """Parses a CSV file based on the provided column types.""" columns = tf.decode_csv(value_column, record_defaults=DEFAULTS) features = dict(zip(ALL_COLUMNS, columns)) label = features.pop(LABEL_COLUMN) classes = tf.cast(label, tf.int32) - 1 return features, classes
11d0f0508fd369ab50df45f71340d8336da676c0
3,647,525
def on_over_limit(): """ This is called when the rate limit is reached """ return jsonify(status='error', error=[_('Whoa, calm down and wait a bit before posting again.')])
f954abb1de5746ca49bbdff02894c1fe75fed106
3,647,526
def comment(strng,indent=''): """return an input string, commented out""" template = indent + '# %s' lines = [template % s for s in strng.splitlines(True)] return ''.join(lines)
42386b7ed8de9127d7224481a5f5315d39b6ae97
3,647,527
def square(number): """ Calculates how many grains were on each square :param number: :return: """ if number <= 0 or not number or number > 64: raise ValueError(ERROR) return 2**(number - 1)
dd8d6f9dc95632effaf7bc8a705ffddd1de6c825
3,647,528
def health_check() -> ControllerResponse: """ Retrieve the current health of service integrations. Returns ------- dict Response content. int HTTP status code. dict Response headers. """ status = {} for name, obj in _getServices(): logger.info('Ge...
1915deb5283aac2c0ced935c66dbd3d1f5564e33
3,647,530
from openpype.scripts import publish_filesequence def _get_script(): """Get path to the image sequence script""" try: except Exception: raise RuntimeError("Expected module 'publish_deadline'" "to be available") module_path = publish_filesequence.__file__ if modu...
8efa4f24ed070b859a8e406275feb1c989d6fb6c
3,647,532
def residual_unit(data, nchw_inshape, num_filter, stride, dim_match, name, bottle_neck=True, workspace=256, memonger=False, conv_layout='NCHW', batchnorm_layout='NCHW', verbose=False, cudnn_bn_off=False, bn_eps=2e-5, bn_mom=0.9, conv_algo=-1, fuse_bn_relu=False, fus...
a67edaf2a40a75619b389a6de8e8d20397b4df20
3,647,533