content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import operator def operator_index(idx): """ Convert `idx` into an integer index using `__index__()` or raise `TypeError`. This is the same as `operator.index()` except it disallows boolean types. This is a slight break in NumPy compatibility, as NumPy allows bools in some contexts where `__...
da31876fc3e1f41115d57d7a60ca42fc88eea262
59,762
def calc_events(N: pd.Series, S: pd.Series) -> pd.Series: """ The Kaplan-Meier estimator of survival function is given by S(t) = product_{i:t_i<=t}(1 - D_i / N_i) Where S is event-free probability, D is number of events, and N is number of observations Assume S(t+10) = S(t) * ((N(t+10) - D(t+10)) / ...
a21f4e64cb38c9c51a80975bf8b68afe110c4419
59,763
def cashflow_data(terminal, element): #(Terminal, element): """Place cashflow data in element dataframe Elements that take two years to build are assign 60% to year one and 40% to year two.""" # years years = terminal.modelframe #years = list(range(Terminal.startyear, Terminal.startyear + Terminal...
27e4b5488d1b726e7c77bc51d85733f2703877ae
59,764
def rainbow_network(num_actions, num_atoms, support, network_type, state): """The convolutional network used to compute agent's Q-value distributions. Args: num_actions: int, number of actions. num_atoms: int, the number of buckets of the value function distribution. support: tf.linspace, the support o...
4b881ce064412e9b358b6cd21e526263984b30b7
59,765
from scipy.spatial import ConvexHull def constructOutlines(x,y,clusterlabels): # compute convex hull, one per cluster label """Construct the convex hull (outline) of points in (x,y) feature space, Parameters ---------- x, y : seq (e.g. tuple,list,1-d array) Location of points in (x,y) featu...
2b1c0810210229fa0cd156fdf3fb6cc873409a6c
59,766
import collections def list_sims(product=None, yyyymmdd=None): """List available simulation results. Each simulation is represented as a dictionary describing product type, simulation date, and whether all expected files are present, and it also includes a list of filenames, e.g. {'product': 'lon...
6f9372c770eada26a8c3917634a552628bb5b79c
59,767
import torch def masked_log_softmax(vector, mask=None, dim=-1): """ This performs a log-softmax on just the non-masked portions of `vector` (see https://github.com/allenai/allennlp/blob/main/allennlp/nn/util.py#L286-L314) """ if mask is not None: mask = mask.float() while mask.dim(...
9fd966cd381355c6117c72348f5bcab845ef1f00
59,768
def bprop_bool_and(x, y, out, dout): """Backpropagator for primitive `bool_and`.""" return C.zeros_like(x), C.zeros_like(y)
47a3ee91573807d50d6f9f04cd6540aedd60eadb
59,769
def prop_has_qualifiers(ents_dict, qid, pid, i): """ Checks if the property has qualifiers """ return "qualifiers" in get_prop(ents_dict=ents_dict, qid=qid, pid=pid)[i].keys()
52364577b26ec6b90546da557563247cc2cc3d9a
59,770
import csv def read_txt_detV2(textpath): """ read det.txt to a dict :param textpath: text path, String :return: a dict with key = frameid and value is a list of lists [x1, y1, x2, y2] in the frame, dict """ # line format : [frameid, personid, x, y, w, h ...] with open(textpath) as f: ...
e3a11ea640cbbd9074155eab5bb5af77f2f4877e
59,771
def proof_of_work(last_proof): """ Simple Proof of Work Algorithm: - Find a number p' such that hash(pp') contains leading 4 zeroes, where p is the previous p' - p is the previous proof, and p' is the new proof """ proof = 0 while valid_proof(last_proof, proof) is False: proof += ...
d9eade72b1ca2f58adda5966119a5fd3d1499bea
59,772
def bincount(map_bins, map_weights=None, length=None) : """Wrapper for numpy.bincount with protection of weights and alattening numpy arrays """ weights = None if map_weights is None else map_weights.flatten() return np.bincount(map_bins.flatten(), weights, length)
aff130a625b786fff4fb7a1d3ed0ebab8fbbe7d6
59,774
def lazy_method(fn): """Decorator that makes a method lazy-evaluated.""" attr_name = '_lazy_' + fn.__name__ def _lazy_method(self,*args, **kw): if not hasattr(self, attr_name) or kw.get("new_process",False): setattr(self, attr_name, fn(self,*args, **kw)) return getattr(self, att...
cad299288b5b02a061605f661e806f92d269f333
59,775
def dist_node(n1, n2, nelx, nely, nelz, dof): """ Returns the distance between two nodes. Used to define which active elements are associated to which loads. """ p1 = node2point(n1, nelx, nely, nelz, dof) p2 = node2point(n2, nelx, nely, nelz, dof) return np.linalg.norm(np.asarray(p1) - np.a...
e983f3661db2e7ef6dce718b33ab57b0fe1e1989
59,777
def check_vehicle_accident_suppression(check_df, project_id, post_deid_dataset, pre_deid_dataset=None, mapping_dataset=None): """Run motor vehicle accident suppression check Parameters ---------- check_df: pd.DataFrame Dataframe containing the checks that need to be done project_id: str...
67fb47115820ee66c78be4aa32c635ae697d4424
59,778
def player_died_bullet(playerx, playery, rect_enemy): """this function cheks if player died by enemies bullet""" pos_player = playerx, playery if rect_enemy.collidepoint(pos_player): return True else: return False
073482e3da88e0aa448d30f2c0dd71e6cd7fe6e3
59,779
import torch def topk(vec, k): """ Return the largest k elements (by magnitude) of vec""" # on a gpu, sorting is faster than pytorch's topk method # topkIndices = torch.sort(vec**2)[1][-k:] # however, torch.topk is more space efficient # topk on cuda returns what looks like uninitialized memory i...
d0b0830aca482758c833769c661ee7d19ae63438
59,780
def create_member_account_discovery_role(servicenow_url, parent_account, member_account_discovery_role, assume_role_external_id): """ Creates entry in the cloud service account assume role table for master account to setup r...
1e4d1c198f104bfb28ed2238a361f05b79486b5e
59,781
def setup_js_tag_helper(app, pagename, templatexname, context, doctree): # type: (Sphinx, unicode, unicode, Dict, nodes.Node) -> None """Set up js_tag() template helper. .. note:: This set up function is added to keep compatibility with webhelper. """ pathto = context.get('pathto') def js_tag(...
2458fc514a1bc6e6ff1ad95df6fe7a4c0bd41ae2
59,782
def text2number(text: str) -> str: """ Convert an English short-scale **text** to it's numerical value. The function attempts to parse **text** and return a numeric string containing the corresponding value. The number(s) in the string will be in scientific notation. The function returns a pse...
1e46fe17bb852c65d90fd3fe402669f9e1a03dea
59,783
from typing import Optional def build_matrixstore( application: FastAPI, config: Config, user_service: LoginService, service: Optional[MatrixService] = None, ) -> MatrixService: """ Matrix module linking dependency Args: application: flask application config: server config...
5ed18ef98fdb3b080326c658b4558c96a92bee62
59,784
def rev(repo, subset, x): """Revision with the given numeric identifier. """ # i18n: "rev" is a keyword l = getargs(x, 1, 1, _("rev requires one argument")) try: # i18n: "rev" is a keyword l = int(getstring(l[0], _("rev requires a number"))) except (TypeError, ValueError): ...
00cafa7df962e4b93dcac5df558b2da7c18fcc64
59,785
import requests def request_insee(url: str): """ Call an INSEE api with token regeneration if needed. """ connector = INSEEConnector() response = requests.get(url, headers=connector.header()) if response.status_code == 401: connector.generate_token() response = requests.get(ur...
427ba86051e8cfb2a45244f10ff30c6549cce5a2
59,786
def suffstats(func): """decorate func with ff.suffstats if you have several ffs that share some underlying computation func will be run once for each hypothesis before any actual scorer is called""" _SUFFSTATS_.append(func) return func
707d8d2bf3f704b7bc27a6a23227e910c3f6803e
59,787
import re def parse_metadata(e, patterns): """Parse heading metadata Arguments: e (HtmlElement): html element containing header text patterns (dict): dictionary with as keys the 'class' attribute value the patterns apply to, and as values tuples, containing a ...
d16e6ef20eb9e344da645ba4acdd47d8a2471e7a
59,788
import importlib import inspect def get_module_docs(module_string): """ Returns docs dictionary that contains docs data form module-level variables, functions and classes for given module string (e.g. "package1.package2....packageN.module"). """ if not module_string: return None module...
51bc5af9821058c07490b2e92cc2c9ccb2842590
59,790
def create_some_config_by_shop_id(shop_id: int): """ 为店铺创建一些奇奇怪怪的设置 :param shop_id: :return: """ config_info = {"id": shop_id} some_config = SomeConfig(**config_info) some_config.save() return some_config
afa1300e89adf5a2864112d8366e5f203a16ce30
59,791
def delete_baselines_by_ids(baseline_ids): """ delete a list of baselines given their ID """ _validate_uuids(baseline_ids) account_number = view_helpers.get_account_number(request) query = SystemBaseline.query.filter( SystemBaseline.account == account_number, SystemBaseline.id.in_(baseli...
267a836336fd9a12e0cdbee89249c7306ed41191
59,792
def _char_array(size: int, doc: str) -> Field: """ Character string, zero padded to next multiple of 4 bytes. Args: doc: DocString for this parameter Returns: Field for the dataclass parameter. """ return _param(bytes, f"{size}s{-size % 4}x", doc)
98f934af62249328f30df1593174b05941ef9ec7
59,793
def op(params,ops): """ Operator for sites in center of lattice """ # Collect needed operators X = ops.X I = ops.I Z = ops.Z # Interaction with field op = -0.25*params[0]*quick_op(X,I) op += -0.25*params[0]*quick_op(I,X) # Interaction between spins op += -params[1]*quick_...
c68a9a787b2f82e110f83a3305e441863aa79ff4
59,795
import math def jump_search(arr, search): """Takes in a sorted array arr and a value to search for""" interval = int(math.sqrt(len(arr))) for i in range(0, len(arr), interval): if arr[i] < search: low = i elif arr[i] == search: return i else: bre...
d1aac70dca9d3f92c05f9e9da37de3786ae75460
59,796
import json def _loadCredentials(): """Loads stmp credentials from a json file. File format: { "hostname": "smtp.gmail.com", "port": 587, "user": "gmail address", "password": "gmail password" } """ with open(_CREDENTIALS_PATH, 'r') as f: return json.loads(f.read())
58524e0b9d5d3139dbc95a948b8f5a923ef18e82
59,797
def deep_merge(source: dict, destination) -> dict: """Deep merge for dictionaries Args: source (dict): Dict to merge destination (Any): hm... Returns: dict: hm... """ for key, value in source.items(): if isinstance(value, dict): node = destination.setdef...
a429dbfe9860384cd9ace95ed70cf7bd0ab32b14
59,798
from typing import Optional def multilabel_confusion_matrix(y_true: np.ndarray, y_pred: np.ndarray, *, sample_weight: Optional[np.ndarray] = None, labels: Optional[np.ndarray] = None, samplewise: bool = False)\ ...
90cb96bf387a3e78d2783517ecc621283b4125cb
59,799
def add_data_args(parser: HyperOptArgumentParser) -> HyperOptArgumentParser: """ Functions that parses dataset specific arguments/hyperparameters. :param hparams: HyperOptArgumentParser obj. Returns: - updated parser """ parser.add_argument( "--data_type", default="csv",...
1b9b9310489554928a338d6d08cedc3bd54d1a0c
59,800
def manage_static_blocks(request): """Dispatches to the first static block or to the add static block form. """ try: sb = StaticBlock.objects.all()[0] url = reverse("lfs_manage_static_block", kwargs={"id": sb.id}) except IndexError: url = reverse("lfs_manage_no_static_blocks") ...
40d0260ea94fd37f8a890100bbe5f1c00d0379a1
59,802
import warnings def modcpppxd(mod, exceptions=True, ts=None): """Generates a cpp_*.pxd Cython header file for exposing a C/C++ module to other Cython wrappers based off of a dictionary description of the module. Parameters ---------- mod : dict Module description dictonary. exceptions...
0ed08446465956220e6922bf9f611dc51172ed1a
59,803
def prepare_grant_uri(uri, client_id, response_type, redirect_uri=None, scope=None, state=None, **kwargs): """Prepare the authorization grant request URI. The client constructs the request URI by adding the following parameters to the query component of the authorization endpoint URI ...
fbca0e5a62f2f5b1371d4d21a7665493fbea948a
59,804
import unicodedata import re def slugify(name): """ Slugify a column header for use as a name. Adapted from Django. """ slug = name slug = unicodedata.normalize('NFKD', unicode(slug)).encode('ascii', 'ignore') slug = unicode(re.sub('[^\w\s-]', '', slug).strip().lower()) slug = re.sub(...
8865a1b6dda6bc3e9a3b1711058d6bb26cc324e4
59,805
import random def get_challenge(): """Prime game Q&A generation. generate random Number and check if a Number is Prime Returns: question{str} : Number; answer{str} : Prime status """ num = random.randint(MIN_NUM, MAX_NUM) answer = 'yes' if is_prime(num) else 'no' question...
a72d73ef9cf005f75f12e76475657b548b026f36
59,806
def dashboard_get_for_rendering(id): """Get a dashboard with its definition, and current settings necessary for rendering. """ dashboard = database.DashboardRecord.query.get_or_404(id) dash = _set_dashboard_hrefs(dashboard.to_json(True)) return { 'dashboard' : dash, 'preferences' : ...
60d1351e45c0e83d45c2a4732aa33f871eef6a0a
59,807
def page_dirs_to_page_name(page_dirs): """ [カテゴリ1,カテゴリ2,ページ]というディレクトリの配列状態になっているページパスを 「カテゴリ1/カテゴリ2/ページ」というファイル名に変換する。 :param page_dirs: :return: """ page_name = "" for page_dir in page_dirs: if page_dir: page_name = page_name + page_dir + "/" page_name = page_na...
0254fb2cab146fd8054de23d27b485094513447f
59,808
def include_paths_for_include(source, include, headers): """Estimate include paths for single include in source file and mapped header file.""" database = defaultdict(list) up_reference_count = 0 ambiguous_paths = list() # Find if include in source_file could be mapped to some internal header # ...
857f0a49f2c59ef6d9afae91de433d3eeca7f6eb
59,809
from math import erfc def _phi_real(zs,rs,R,alpha, Rc): """Finds the real space portion of the ewald summation. Args: zs (list of int): The amount of charge on each nucleus. rs (list of list of float): Each entry contains the position of an atom. R (list of list of float): The lattice...
3c02f161daa6c049e60ae60bcb48df0cab59f093
59,810
def _IsServicingPrivilegedRequest(): """Checks whether the request is considered privileged.""" try: request = webapp2.get_request() except AssertionError: # This happens in unit tests, when code gets called outside of a request. return False path = getattr(request, 'path', '') if path.startswith(...
69fce1fc56ed6b7958eda05055fa367f9b00cdf3
59,811
def get_team_slug_name(project_name, role): """ Get the team name and team slug based on GitHub's naming scheme. By convention, teams are named in a well-defined . team name schema CT: <project name> <role, pluralized> team slug schema ct-<project_name_slug>-<role_slug> @param project...
8c830659eca6e35d0483ed3dad3b797eb91bbc25
59,812
def norm_weight(nin, nout=None, scale=0.01, ortho=True): """ Get a (orthogonal) Gaussian weight matrix W, scaled if desired (and not orthogonal). :param nin: :param nout: :param scale: :param ortho: :return W: """ logger.warn('Norm weight with range: +/-{}'.format(scale)) if ...
d993eb9660fc512274685ebd93b7126e3a0d9afb
59,813
def validate_signature(uri, nonce, signature, auth_token=''): """ Validates requests made by Plivo to your servers. :param uri: Your server URL :param nonce: X-Plivo-Signature-V2-Nonce :param signature: X-Plivo-Signature-V2 header :param auth_token: Plivo Auth token :return: True if the req...
3ea7589f957391674ed05632e3188cd8338282e4
59,814
def DecryptAlgo(EncryptData,PayloadSize,StartKey,Keys): """ IN: Encrypted Data, PayloadSize,StartKey and Dictionary of keys OUT: Bytearray of decrypted data Description: This function is the PlugX crypto routine used in compressed PlugX samples """ key0=StartKey&0xFFFFFFFF key1=StartKey...
05f802399b4485743609522f40b0e8f962f3332e
59,815
from typing import Tuple def compute_voronoi_density( traj_data: pd.DataFrame, measurement_area: pygeos.Geometry, geometry: Geometry, cuf_off: float = None, num_edges: int = 40, ) -> Tuple[pd.DataFrame, pd.DataFrame]: """Compute the voronoi density of the trajectory per frame inside the given ...
89ef38f8037ab0df6f3a6d069bf030794a5fce5f
59,816
def psalfromasal(s_gkg,lon0,lat0,p_dbar): """Convert absolute salinity to practical salinity. Convert salinity in practical salinity units (PSU) to absolute salinity. :arg float s_gkg: Absolute salinity in g/kg. :arg float lon0: Reference longitude in degrees East. :arg float lat0: Ref...
6e00ebef75ca2746066e1b9f580983dbab18cba5
59,817
def prepare_maxmind_database(license_key, database_edition, storage_dir): """Downloads, extracts and caches a maxmind geoip database for offline use.""" checksum = download_maxmind_database_checksum(license_key, database_edition) archive_path = download_maxmind_database_archive(license_key, database_edition...
7324058c6b13038110a8d1d9ae62b66788018448
59,818
def read_csv( file_path: str, delim: str, header_rows: int, footer_rows: int, encod: str, ) -> pd.DataFrame: """ Read a specified CSV file into a Dataframe. :param file_path: Path to CSV file :type file_path: str :param delim: CSV separator :type delim: str :param header...
c84374ca3d1a0a3e9c37c498dde4f8e6bc122689
59,820
def reproject_raster_dataset(src_ds, **kwargs): """Reproject/Resample given dataset according to keyword arguments Parameters ---------- src_ds : :py:class:`gdal:osgeo.gdal.Dataset` raster image with georeferencing (GeoTransform at least) Keyword Arguments ----------------- spacing...
291403b2433ba1c0bf73830cc449a2dddf75bb82
59,821
def np_onehot(data, num_class=None): """Numpy based one-hot encoding in the last dimmension""" if num_class is not None: num_class = np.max(data) + 1 onehot_data = np.eye(num_class)[data] return onehot_data
942dc6fe319feb24ea2938f12c3777a7dda03161
59,822
def camera_connected(): """Return the list of connected camera compatible with gPhoto2. """ if hasattr(gp, 'gp_camera_autodetect'): # gPhoto2 version 2.5+ cameras = gp.check_result(gp.gp_camera_autodetect()) else: port_info_list = gp.PortInfoList() port_info_list.load() ...
89bba43ca7de8a8a74af7c0ed65adba3f952c3f6
59,823
import copy def get_action_movement(movement, annotation, data_config): """ Get movement of actions before and after the screen time. There essentially will be two actions for each player in the annotation. Parameters ---------- movement: pandas.DataFrame sportvu movement data dat...
10508f10a05d9a43b7125293d14c2eac8b277963
59,824
def make_grpc_stub(url: str, port: int) -> ChupacabraServerStub: """Make a stub for the GRPC server.""" location = '{}:{}'.format(url, port) channel = grpc.insecure_channel(location) stub = ChupacabraServerStub(channel) return stub
c4bb0b39cd9b1843980261262e4b917da12d7a4d
59,825
def build_gaussian_layer(mean, standard_deviation, step=1, len=8, sharpness=0.2): """ copy from blog.csdn.net """ # scaled_size = int(len / sharpness) scaled_size = len center_point = (scaled_size, scaled_size) x = np.arange(-scaled_size + 1, scaled_size, step) * (sharpness**2) y = np.ar...
59358f0ef4907e2d8e5d92159c5cd8cb73985e0d
59,826
def getLogs(d, rho, v, usingT=True): """ Function to make plotting convenient """ dpth, rholog = getPlotLog(d, rho) _, vlog = getPlotLog(d, v) zlog = getImpedance(rholog, vlog) rseries, _ = getReflectivity(d, rho, v, usingT) return dpth, rholog, vlog, zlog, rseries
ce36fa820105d014d79c93e98202833ad7407811
59,827
def parse_raw(output): """Just return `output` as a single string assigned to dict key '_' for reference in assertion expressions. Returns {'_': output} """ return dict(_=output)
7fe463b997687bedad6d77d4bca4718037f18069
59,828
def to_list(gen_out): """Generation output handler that converts to the rev 1.0 format.""" if isinstance(gen_out, list) and len(gen_out) == 1: out = [c['cf_mean'] for c in gen_out[0].values()] if isinstance(gen_out, dict): out = [c['cf_mean'] for c in gen_out.values()] return out
51dc2e93e3bc741d51a19bacd4b2200fb0e6b3f7
59,829
import scipy.linalg import numpy def sift_keypoints (fn): """ Return the SIFT keypoints of an image. Two arrays are returned, the first giving the locations (and corresponding scales and orientations) of the feature points found, while the second contains the associated descriptors. Argument...
5881512f2b58a18fce5bb48bad51306c903ba97d
59,830
from functools import reduce def chinese_remainder(n: int, a: int) -> int: """Chinese remainder theorem in Python shamelessly stolen from https://rosettacode.org/wiki/Chinese_remainder_theorem#Python_3.6 """ sum = 0 prod = reduce(lambda a, b: a * b, n) for n_i, a_i in zip(n, a): p...
daf0806c6b1801bef24e69634ad06422f06166fa
59,831
def sample_word_language_model_family_cfg(seed): """Sample a word language model config.""" rng = np.random.RandomState(seed) cfg = {} cfg["embed_dim"] = utils.sample_log_int(rng, 8, 128) cfg["w_init"] = utils.sample_initializer(rng) cfg["vocab_size"] = utils.sample_log_int(rng, 1000, 30000) cfg["core"] =...
4f5d48e91717048f598aa9cdaef3043c506b802d
59,832
def ask_yes_no(prompt, default=None): """Asks a question and returns a boolean (y/n) answer. If default is given (one of 'y','n'), it is used if the user input is empty. Otherwise the question is repeated until an answer is given. An EOF is treated as the default answer. If there is no default, an ...
54c238df04e593b4cbea239ee970345f1305738d
59,833
from typing import Callable def make_vector_gradient(bcs: Boundaries) -> Callable: """make a discretized vector gradient operator for a cylindrical grid {DESCR_CYLINDRICAL_GRID} Args: bcs (:class:`~pde.grids.boundaries.axes.Boundaries`): {ARG_BOUNDARIES_INSTANCE} Returns: ...
c19259d3d6f9cfa76bb4d3e227fd5e365cd986af
59,834
def _kl_dirichlet_dirichlet(d1, d2, name=None): """Batchwise KL divergence KL(d1 || d2) with d1 and d2 Dirichlet. Args: d1: instance of a Dirichlet distribution object. d2: instance of a Dirichlet distribution object. name: Python `str` name to use for created operations. Default value: `None` (i...
66719bf0d1517dfe44ddba696cfe4fb6e60a4beb
59,835
def _resolve_fork_relationships(workflow): """ Requires proper workflow structure. Fork must come before a join. """ def helper(workflow, node, last_fork): if isinstance(node, Fork): join = None children = node.get_children() for child in children: join = helper(workflow, child.g...
24d34fb786e66f67db06d691c3fb372d281d427c
59,836
def max_neighbors(G,f,column,n=1): """ Adds a column to the dataframe f with the maximum value of its neigbors feature. G: a networkx graph. f: a pandas dataframe. column: the column to which the mean is applied. n: neighbourhood order. """ if not(set(f.name) == set(G.nodes()) and len(f....
4a483d9a90cce6e9bfa6c0d20797395239387972
59,837
def _c_helper_fieldaccess_expr(prefix, field=None): """ turn prefix, which is a list of tuples (name, separator, Type obj) into a string representing a valid field-access-expression in C (based on the context) if field is not None, append access to the field as well. "separator" is one of the C-ope...
dcc3a9b3063040426f450eb8fee27278ddbee206
59,838
def rivers_by_station_number(stations, N): """Given a list of station objects, and a value N, this function returns a list of tuples with the N rivers with the largest number of stations. If there is more than one river with the same number of stations as the Nth river, they will be included as well""" ...
3dcd1207f28f27a8cdb4a6e502b4b6dbfe143cf4
59,839
def getOrbitalElements(_parVec:list) -> OrbitElem: """ Returns all Orbital Elements and the Period, packed into a data class Parameters ---------- _parVec : list Parameter Vector for current orbit Returns ------- OrbitalElem Object """ Pars = ParVecToParams(_parVec) ...
0f09718d9595e089d821af3678370e58427dfc8a
59,840
def request_passes_test(test_func, redirect_url=None, redirect_field_name=REDIRECT_FIELD_NAME): """ Decorator for views that checks that the request passes the given test, redirecting to the redirect url if necessary. The test should be a callable that takes the request and retur...
057348b67d929e17d01801b6916dd86dd6ebb648
59,843
def curve_fit(f, x, y, p0): """Fits an arbitraty function to data (x,y). This part comes from: http://projects.scipy.org/scipy/browser/trunk/scipy/optimize/minpack.py :param f: :type f: :param x: :type x: :param y: :type y: :param p0: :type p0: :returns: :rtype: ...
58a769a77c9052a29a1d1151bc89e0d638daa2f5
59,844
def pole_from_endpoints(coord1, coord2): """Compute the pole from a great circle that connects the two specified coordinates. This assumes a right-handed rule from coord1 to coord2: the pole is the north pole under that assumption. Parameters ---------- coord1 : `~astropy.coordinates.SkyCo...
975def501cbdaf0065ca62c3370d7f06ddac29b1
59,845
from random import random from phenum.msg import verbosity from tqdm import tqdm from random import randrange def add_arrows(col,agroup,dim, translations, accept=None,nested=False,num_wanted=None, small=False, supers = False): """Finds the unique arrangements of arrows for a given configuration. Args: ...
d8ee5e65f68e9c3f4709c17edeb6f2b387b1a3fa
59,846
def calc_reference_quantiles(prcp: pd.DataFrame) -> pd.DataFrame: """Composition of calc_reference_station and reference_quantiles.""" # This makes sure that we do not use the reference dataset directly, just the quantiles ref = calc_reference_station(prcp) q = reference_quantiles(ref) return q
c14e0a1e4f07d7a6f2c0e66c078594cdd5537bd0
59,848
def CalculateChannelSlope(pts_array, slope_window_size=5): """ Clubb 2019 - JGR:ES Modified from: https://github.com/UP-RS-ESP/river-clusters/blob/master/clustering.py """ grad = np.empty(len(pts_array)) slicer = (slope_window_size - 1)/2 for index, x in enumerate(pts_array): start...
f6c31ad36446d35d1dca07343dfcac4dbfb123d5
59,849
def get_regulon(hp, parent=None, layers=None): """Build a subgraph to replace a node.""" num_layers = safe_sample(hp.min_layers, hp.max_layers) M = nx.MultiDiGraph() ids = [] for layer_number in range(num_layers): n_nodes = safe_sample(hp.min_nodes, hp.max_nodes) log(f"add layer {lay...
8837dfc60637426fcc028719a5f76b5b1d689b30
59,850
def inference_on_image(model, image, network_dim, obj_thresh, letterbox=False, show_img=False): """ ---------- Author: Damon Gwinn (gwinndr) ---------- - Similar to inference except takes in an image as input (simpler to use) - Performs all needed pre and post processing - Returned detection...
6924a4e747d292127ab86bcf083204424ac9306d
59,851
import re def http_header_link_regex(relation_type): """Create a regex matching the http header links of the given type.""" return re.compile(r'.*;+\s*rel="{}"\s*(;.*)?'.format( re.escape(relation_type)))
4085e9258c0f6d5d1de33f82318aa9006fbe40bc
59,853
from datetime import datetime def _get_new_end_time(latest_time): """ Helper function to move the end time to the next 9am. Args: latest_time: the time in ms Returns: the new time in ms """ time_9am = datetime.time(9,0,0) end_datetime = datetime.datetime.fromti...
13c2b7357a9d5f79002628a61b8b6cdad7b5e3af
59,854
def trial_reshape_spectral(positions, spectrum, trial_inds): """ reshapes the spectral data if the data is trial type Args: positions (np.ndarray): point positions spectrum (np.ndarray): spectrogram array trial_inds (np.ndarray): array of the trial indices Returns: resh...
3471a1f7d7d8d944b48ac5c3fd823c275646e9c8
59,855
from typing import Iterable def none_of(elements: Iterable[Element]) -> CNF: """Forces exclusion of matching rows on a truth table""" return Q(elements) == 0
2d0789f3c00da27ee56c4db4b2b82dcef01861ca
59,856
def rolling_count(arg, window, **kwargs): """ Rolling count of number of non-NaN observations inside provided window. Parameters ---------- arg : DataFrame or numpy ndarray-like window : int Size of the moving window. This is the number of observations used for calculating the ...
386dbfdc2b41519b58f6dad344c480abbf317994
59,857
def softmax_backward(Y, softmax_out): """ Y: labels of training data. shape: (vocab_size, m) softmax_out: output out of softmax. shape: (vocab_size, m) """ dL_dZ = softmax_out - Y assert(dL_dZ.shape == softmax_out.shape) return dL_dZ
c814b04d864953318b16140d8c348fb3d7275c89
59,858
def inp(): """ For taking integer inputs. """ return(int(input()))
2d776b703c9825a33ae80f7e966f00a4aa9c2289
59,859
import colorcet def _get_from_colorcet(name): """ import colormap from colorcet definition """ try: except ModuleNotFoundError: return None color_strings = colorcet.palette[name] color_list = [] for hex_str in color_strings: if hex_str[0] != '#': continue if len(hex_str...
ecb31a880a0e433b4e48cb39b9dabc703deb0bfb
59,860
def D(n): """" Convert n to decimal """ if n is None: return None return Decimal(str(n))
d1d2a3cac9facc67c50f69eac20d1849dec26beb
59,861
def reorient(in_file, newpath=None): """Reorient Nifti files to LPS.""" out_file = fname_presuffix(in_file, suffix='_lps', newpath=newpath) to_lps(nb.load(in_file)).to_filename(out_file) return out_file
cb186c1317c36da26a35bff55ffc806364951437
59,862
def term_op(): """Parser for symbolic operators >>> pstream(term_op(),'PRIM_TERM_OP_CONTROLSEQ { TERM } {TERM }') Etok(cs_brace,prim_term_op_controlseq,'PRIM_TERM_OP_CONTROLSEQ { TERM } { TERM }') """ return first(get_lookup_parse('prim_term_op') , cs_brace(get_lookup_parse('prim_te...
f79a6ca7c8f34751771a0e96ae0e8e02572cf86e
59,863
def PARAM_writer(input_dictionary): """Return the PARAM section Parameters ---------- input_dictionary : dictionary Dictionary with the defined parameter information Returns ------- str string : string containing PARAM section """ string="PARAM----1----*----2----*----3----*----4----*----5----*----6---...
71c3b63298a397723f3c59a381e382dd856cec5e
59,864
def squares_within_unit_list(s, unit_type): """Returns a list of the squares within the same unit as s. unit_type can be 'row', 'column', or 'unit3x3' """ assert unit_type in unit_types if unit_type == 'row': return (units[s][0]) elif unit_type == 'column': return (units[s][1]) ...
78876de8aaa16f850049e531be229ffa9934bde0
59,865
def optimalLocationRectangularDistance(D_filtered: pd.DataFrame, latCol: str, lonCol: str, weightCol: str): """ this function returns the optimal location based on rectangular distances Args: D_filtered (pd.DataFrame): Input dataframe. latCol (str): Column name containing latitude. ...
27244d1880f99259f4614d2d0dca95392ff6e871
59,866
def assemble(inputs, outputs, dataset, seed=None): """Assemble the HyperBlocks based on the dataset and input output nodes. # Arguments inputs: A list of InputNode. The input nodes of the AutoModel. outputs: A list of HyperHead. The heads of the AutoModel. dataset: tf.data.Dataset. The ...
b57490b17cb69a593fa25357c6b29c7dbb5d3264
59,867
def read_txt(path): """Read a mass spectrum from a text file. Args: path (str): Path to the spectrum. Returns: tuple: Lists with m/z and intensities. """ mz = [] i = [] with open(path) as f: for line in f: line = line.split() mz.appen...
e0efe8549596ec2bf312967ecf265d8eb8b3372c
59,868
import requests def latest_branch_commit(user: str, repo: str, branch: str) -> str: """ Grabs the latest commit for a specific branch. Args: user: (`str`) The account name. repo: (`str`) The repo name. branch: (`str`) The branch name. Retur...
a4e0f3a7f61a404d64bd38cc9fd662e6a9242919
59,869
import json def model_to_dictionary(obj): """ Given a model instance `obj`, return a dictionary that represents it. E.g. something like { 'pk': 15, 'model': 'audit.auditorstaffmember', 'auditor_firm': 15, 'user': 934 } For _simple_ use from templates, th...
a12c9906de39486846ee8e51571d75578334aa6f
59,870
def get_back_labels(node,root): """given a node, return a list of back tip labels""" all_labels = get_front_labels(root) front_labels = get_front_labels(node) return set(all_labels) - set(front_labels)
afca33f9954125d076cdca74bb5005a9c93413e2
59,871