content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def Rotation_EQJ_GAL():
"""Calculates a rotation matrix from equatorial J2000 (EQJ) to galactic (GAL).
This is one of the family of functions that returns a rotation matrix
for converting from one orientation to another.
Source: EQJ = equatorial system, using the equator at the J2000 epoch.
Target:... | 3eead11002640caf1c7ae67b782b05c33d90d741 | 3,621,100 |
from pathlib import Path
import tqdm
def query_copernicus_hub(aoi, username, password, hub, **kwargs):
"""Query Copernicus Open access Hub.
:param aoi: (str) Geojson Area of interest url
:param username: (str) Username to use for API connection
:param password: (str) Password to use for API connectio... | b69e54797e2f12699a586d2e6ab9f8081fbb51d7 | 3,621,101 |
from saq.database import get_db_connection
def delete_password(key):
"""Deletes the given password from the database. Returns True if the password was deleted."""
with get_db_connection() as db:
c = db.cursor()
c.execute("DELETE FROM `encrypted_passwords` WHERE `key` = %s", (key,))
db.... | 09ac6784ddb34f42a455ce920b2589049b28d478 | 3,621,102 |
def StandardMols(mols, n_jobs=1):
"""
"""
mols = mols if type(mols) is not Chem.rdchem.Mol else [mols]
n_jobs = n_jobs if n_jobs>=1 else None
pool = Pool(n_jobs)
sm = pool.map_async(StandardMol, mols).get()
pool.close()
pool.join()
return sm | dc238cafc4b9676392fb3a38d032368a471369fb | 3,621,103 |
def af_to_maf(af):
""" Converts an allele frequency to a minor allele frequency
Args:
af (float or str)
Returns:
float
"""
# Sometimes AF == ".", in these cases, set to 0
try:
af = float(af)
except ValueError:
af = 0.0
if af <= 0.5:
return af
... | aed0361218fbb8ebda43b2abfd6638d2f9df2431 | 3,621,104 |
from lasagne import layers
from nolearn.lasagne import NeuralNet
from .shape import ReshapeLayer
import logging
def generate_nnet(feats):
"""Generate a neural network.
Parameters
----------
feats : list with at least one feature vector
Returns
-------
Neural network object
"""
# ... | 40a3a36b2100ddd15684088e991ee16568ebd55b | 3,621,105 |
import sys
def sleep(retcode=0, time=SLEEP_TIME):
"""
Sleep for {time} seconds & return code {retcode}
"""
return [
sys.executable,
'-c', 'import sys, time; time.sleep({}); sys.exit({})'.format(time, retcode)
] | 4c380b8adf7bf13f2d3b2a9588f3c52d2a2739da | 3,621,106 |
def validate_auth(config: ConfigType) -> ConfigType:
"""Validate presence of CONF_ACCESS_TOKEN when CONF_DEVICE_CLASS=tv."""
token = config.get(CONF_ACCESS_TOKEN)
if config[CONF_DEVICE_CLASS] == "tv" and not token:
raise vol.Invalid(
f"When '{CONF_DEVICE_CLASS}' is 'tv' then '{CONF_ACCES... | 7740cef5d91e33cd5f4d54fca78ab04fd3ac4268 | 3,621,107 |
def GetBuildShortBaseName(target_platform):
"""Returns the build base directory.
Args:
target_platform: Target platform.
Returns:
Build base directory.
Raises:
RuntimeError: if target_platform is not supported.
"""
platform_dict = {
'Windows': 'out_win',
'Mac': 'out_mac',
'Li... | 0bbbad4de3180c2ea51f5149cc3c2417a22b63e9 | 3,621,108 |
def build_B_from_A(A, nodes=None):
"""
Create the numpy adjacency tensor of a networkX graph.
Parameters
----------
A : list
List of MultiDiGraph NetworkX objects.
nodes : list
List of nodes IDs.
Returns
-------
B : ndarra... | 0d00cc4ae7a3d2d1de70c5703d2b457d032b7ce8 | 3,621,109 |
def get_sort_order(ds_spec):
"""
Find how quickly the spectroscopic values are changing in each row
and the order of rows from fastest changing to slowest.
Parameters
----------
ds_spec : 2D HDF5 dataset or numpy array
Rows of indices to be sorted from fastest changing to slowest
R... | 152ccc7e58f1787f1231f8793791496ef98dc07e | 3,621,110 |
import traceback
import calendar
import time
def generate_error(request, cls, e, tb, include_traceback=False):
"""
Builds an L{ErrorMessage<pyamf.flex.messaging.ErrorMessage>} based on the
last traceback and the request that was sent.
"""
if hasattr(cls, '_amf_code'):
code = cls._amf_code... | 39807433d9a43f89b09dd6c3cd575dedc779f004 | 3,621,111 |
def reads(text, ext, format_name=None,
rst2md=False, as_version=4, **kwargs):
"""Read a notebook from a string"""
if ext == '.ipynb':
return nbformat.reads(text, as_version, **kwargs)
format_name = read_format_from_metadata(text, ext) or format_name
if not format_name:
format... | 220bb2c6a9e8932858d780a87eab2a6dd8928c6d | 3,621,112 |
def make_wildcard(title, *exts):
"""Create wildcard string from a single wildcard tuple."""
return "{0} ({1})|{1}".format(title, ";".join(exts)) | 0634c450f43cc779431f61c2a060cea7e02f6332 | 3,621,113 |
def _getFields(qset=None, model=None):
"""
returns a list of fields for specified QuerySet or Model
"""
if hasattr(qset, '_meta') and getattr(qset, '_meta') != None:
fields = qset._meta.fields
elif hasattr(qset, 'model') and getattr(qset, 'model') != None:
fields = qset.model._meta.f... | 8760a802f810d49b51fcb02a087f1ea46b8b61bf | 3,621,114 |
from pathlib import Path
def dir_files(path, pattern="*"):
"""
Returns all files in a directory
"""
if not isinstance(path, Path):
raise TypeError("path must be an instance of pathlib.Path")
return [f for f in path.glob(pattern) if f.is_file()] | 5dbeeec6fe72b70381afb52dcbbea55613a37d49 | 3,621,115 |
def fix_while_loop(x):
"""Change Javascript for loop to Python for loop
for(var i = 0fi < x.length;i++){" --> "for i in range(0,len(x),1):
Args:
x (str): A string with Javascript syntax.
Returns:
[str]: Python string
Examples:
>>> from ee_extra import fix_for_loop
... | 962d9e2cb74ac62f2a5c641d2397369434c1b44a | 3,621,116 |
def io_connection_pattern(inputs, outputs):
"""Return the connection pattern of a subgraph defined by given inputs and outputs."""
inner_nodes = io_toposort(inputs, outputs)
# Initialize 'connect_pattern_by_var' by establishing each input as
# connected only to itself
connect_pattern_by_var = {}
... | 08c395de6bf8e5068ad0c9fa3c19155084441994 | 3,621,117 |
import argparse
import sys
def parse_args(args=None):
"""Parse arguments from sys.argv"""
parser = argparse.ArgumentParser()
parser.add_argument(
'-w', '--window',
default="pyqt5",
choices=find_window_classes(),
help='Name for the window type to use',
)
parser.add_... | f36fca9e647f69185edccba8076ed3c6ee8f3fa3 | 3,621,118 |
def pool_forward(A_prev, hparameters, mode = "max"):
"""
Implements the forward pass of the pooling layer.
Parameters:
-----------
A_prev: tensor of shape (m, n_H_prev, n_W_prev, n_C_prev)
Input data.
hparameters: dictionary
Contains "f" and "stride".
... | 62edf0e2696a1588878dcd4ccbb8521faf576dda | 3,621,119 |
def myDownsample(y, N) :
"""
yds = myDownsample(y,N)
yds is y sampled at every Nth index, starting with yds[0]=y[0] with y[range(0,len(y),N)]. Implementing Matlab's downsample.
Ted Golfinopoulos, 7 June 2012
"""
return y[range(0,len(y),N)] | 0d39f37f4e3a5528f087921e6a4993ea6bf2981c | 3,621,120 |
def _norm_args(norm):
"""
Returns the proper normalization parameter values.
Possible `norm` values are "backward" (alias of None), "ortho",
"forward".
This function is used by both the builders and the interfaces.
"""
if norm == "ortho":
ortho = True
normalise_idft = Fals... | e781c894c9d333fdbdf326120b1417b44dfc5181 | 3,621,121 |
import yaml
import os
def LoadConfigDict(config_paths, model_params):
"""Loads config dictionary from specified yaml files or command line yaml."""
# Ensure that no duplicate keys can be loaded (causing pain).
yaml.add_constructor(yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG,
NoDuplica... | 37a8a554d0fced7446161de97f25d4a83544d3b7 | 3,621,122 |
def get_next_point_in_trace(trace: LineString, point: Point) -> Point:
"""
Determine next coordinate point towards middle of LineString from point.
"""
coord_points = get_trace_coord_points(trace)
assert point in coord_points
if point == coord_points[-1]:
return coord_points[-2]
if p... | 07becf63ae6bdb03e3e9dc1f7982d3af3a28031a | 3,621,123 |
def reduced_quantity(a_quantity, b_quantity):
""" Returns the reduced mass of two particles.
Examples:
```
>>> reduced_quantity(1*u.kg, 1*u.kg)
<Quantity(0.5, 'kilogram')>
>>> reduced_quantity(1*u.kg, 20*u.kg).m
0.9523809523809523
>>> reduced_quantity(1, 200)... | be48533c6cfd1b2063ee149f11071496661631e0 | 3,621,124 |
def expected_value(values, state, action, discount=0.9):
"""Calculate expected value for a given action
:param state: state which value is updated
:type state: tuple
:param action: action taken in this state
:type action: int
:param discount: discount
:type discount: float
:return: new ... | 48832bf7d55fa7deb3a29e0ce9923bcfc57841f8 | 3,621,125 |
def tf(*args, **kwargs):
"""
Create a transfer function model of a system.
:param args: pass in num
:type args: TransferFunction | List[numbers.Real] |
numbers.Real
:return: the transfer function of the system
:rtype: TransferFunction
:Example:
>>> from tcontrol imp... | 4f0cec88b55c932479063a506bbeb734dd392a8c | 3,621,126 |
import torch
def all_pair_iou(boxes_a, boxes_b):
"""
Compute the IoU of all pairs.
:param boxes_a: (n, 4) minmax form boxes
:param boxes_b: (m, 4) minmax form boxes
:return: (n, m) iou of all pairs of two set
"""
N = boxes_a.size(0)
M = boxes_b.size(0)
max_xy = torch.min(boxes_a[:... | 1ca948e4a16016efa694d97c4829fcdfbc29e20d | 3,621,127 |
def get_matching_list_from_graph(graph):
"""
:param graph: nx.Graph(); each edge should have an attribute "color"
:return: List of matching; each matching is an nx.Graph() representing a sub-graph of "graph"
"""
degree = get_graph_degree(graph)
colors = [i for i in range(degree + 1)]
... | e73b2e72fe5d9ed480c52c4904564601bf890148 | 3,621,128 |
def remove_zeros(res_array):
"""
Erase all zeros in res_array and return (reduced) array without zeros.
Parameters
----------
res_array : np.array
Numpy results array
Returns
-------
res_no_zeros : np.array
Numpy results array without zeros (shorter than res_array, if z... | 5c85389f5bdaade3702b8218c793945c89ad018c | 3,621,129 |
def butter_lowpass(cutoff, fs, order=5):
"""
This is based on butter_bandpass
"""
nyq = 0.5 * fs
normal_cutoff = cutoff / nyq
b, a = ssig.butter(order, normal_cutoff, btype="low", analog=False)
return b, a | 36a456f627ee5fccd3f0d0931ae894cc40576676 | 3,621,130 |
import warnings
def instantaneous_phase_shift(analytic_sig, time_vect, carrier_frequency):
"""
For a signal $x(ray) = A * exp(i (2 pi f_0 ray + phi(ray)))$, returns phi(ray) in [-pi, pi[.
Parameters
----------
analytic_sig: ndarray
time_vect: ndarray
carrier_frequency: float
Returns
... | ffb8ae79e9f06e2c8dc30c949031d2fe4611527b | 3,621,131 |
def get_p0_gaussian(x, y):
"""Estimate (x0, dV, Tb) for the spectrum."""
if x.size != y.size:
raise ValueError("Mismatch in array shapes.")
Tb = np.max(y)
x0 = x[y.argmax()]
dV = np.trapz(y, x) / Tb / np.sqrt(2. * np.pi)
return x0, dV, Tb | 6ec338b7e441351aea21b31d526153fcc9a1422d | 3,621,132 |
def list_mendeley_accounts_user(auth):
""" Returns the list of all of the current user's authorized Mendeley accounts """
provider = MendeleyCitationsProvider()
return provider.user_accounts(auth.user) | b8373dde5015d33eabb58b21d9a052b49303f492 | 3,621,133 |
import os
def find_source_files(input_path, export_packages):
""" Get a recursive list of filenames for all Java source files within the given
directory. Only include files in packages that are exported
"""
java_files = []
input_path = os.path.normpath(os.path.abspath(input_path))
exclude_... | 6e6e6d1dbfb54464983aef6c6ecb5c9748859c1a | 3,621,134 |
import ipaddress
def _verify_address(addr):
"""Function verifies that address is valid IPv4 address
Args:
addr : address of machine
Return:
boolean value defining validity of address
"""
try:
ipaddress.ip_address(unicode(addr))
return True
except ValueError:
... | 24232851b7aa1c7d45b4d0be45a87cd5239c9917 | 3,621,135 |
import subprocess
import sys
def make_repo_ref_from_cur_dir():
"""Gets the prefix string for a git clone command dependening on the current
directories git setup. i.e. if it is https, then use https. """
try:
git_output = subprocess.check_output(['git', 'config', '--get',
'remote.origin.url'])
excep... | fccf7420f76bb55531b663a106729623ed8b1cd1 | 3,621,136 |
def output_reduce_list(path_list, force=False):
"""Generates structure file with protons from a list of structure files."""
output_paths = []
for path in path_list:
output_path = output_reduce(path, force=force)
if output_path:
output_paths.append(output_path)
return output_p... | 32d364442e623bb32aae19008e5e7d41e089d678 | 3,621,137 |
def asStructuredText(I, munge=0):
""" Output structured text format. Note, this will whack any existing
'structured' format of the text. """
r = [I.getName()]
outp = r.append
level = 1
if I.getDoc():
outp(_justify_and_indent(_trim_doc_string(I.getDoc()), level))
bases = [base
... | b28587313a825ee487bc230c1faaa105de19aa38 | 3,621,138 |
def current_distribution_by_website(site):
"""
Reads the checker framework version from the checker framework website and
returns the version of the current release
"""
print 'Looking up checker-framework-version from %s\n' % site
ver_re = re.compile(r"<!-- checker-framework-version -->(.*),")
... | a35f66ce2ddda5ecd5e851d859e3ac3e9928d830 | 3,621,139 |
import statistics
def build_card_objects(media_list: list = None) -> list:
""" Creates DB objects from S3 objects list """
logger.info("Crafting list of DB objects...")
logger.debug(
f"Context Parameters: {build_card_objects.__name__} => {build_card_objects.__code__.co_varnames}"
)
medias... | 362b59f157945c756c8c7b2e5e4232cd6e7c7e40 | 3,621,140 |
def make_hyperspherical_classification_loss(prototypes):
"""
Args:
prototypes: (num_classes, embed_dim)
"""
def _get_prototypes(labels):
return tf.tensordot(labels, prototypes, [[1], [0]])
def loss(preds, labels):
"""
Args:
preds: (Batch, embed_d... | d08cc12021eb82dbe7adf230bad52c8fbd27b9d0 | 3,621,141 |
def nz_MgCLN_Gayer(
lam: float,
T: float,
ax: str=None,
):
"""
Refractive index for MgCLN, based on Gayer et al, APB 2008
Parameters
----------
lam: wavelength (lambda) [um]
T: Temperature [Celsius Degrees]
ax: polarization
Returns
-------
nz: Refractive... | b13cd027840dd47ee20bce11e90c8789ee90f3ab | 3,621,142 |
from pathlib import Path
import logging
def export_corpora(
corpus_ids, granularity, corpora_folder, filename, no_download=False
):
"""
Generates a single JSON file with the chosen granularity for all of the
selected corpora
:param corpus_ids: IDs of the corpora that will be exported
:par... | 7a99ce5b7d1f7b8ca1a5060bf5fb02b3aa825954 | 3,621,143 |
from typing import Iterable
from re import T
from typing import Callable
from typing import Tuple
from typing import Iterator
import itertools
from typing import cast
def all_pairs_iterator(values: Iterable[T],
with_replacement: bool = True,
where: Callable[[Tuple[T, T]],... | 667f5ffe01581ac29bf26f5b2d03f08552bd3347 | 3,621,144 |
def syllable_tokenize(text):
"""
:param str text: input string to be tokenized
:return: returns list of strings of syllables
"""
syllables = []
if text:
words = word_tokenize(text)
trie = create_custom_dict_trie(custom_dict_source=syllable_dict())
for word in words:
... | 7b60885d3918c21e2d63cf48f0cc3c60a3b32c5d | 3,621,145 |
from src import bcrypt
def create_sponsor(loggedin_user):
"""
Creates a new Sponsor manually and bypasses email verification.
---
tags:
- admin
summary: Create Sponsor
requestBody:
content:
application/json:
schema:
$ref: '#/compo... | acd9c2f68131f71ca7c719eb22022eb5897f1bf5 | 3,621,146 |
def get_empty_theme():
"""Create object that contains empty theme."""
return {
'theme': {},
'background': bytearray()
} | fc129d109ef2677b41d9a0f608fd580b63c45c8e | 3,621,147 |
def random_nat(n: int) -> int:
"""
Generate a random natural number L{n} bytes long.
"""
return utils.int_from_bytes(random_bytes(n), 'big', signed=False) | bb95e603f1b252c44378b423447b939633727cc1 | 3,621,148 |
import base64
def getNumAtoms(ctab):
"""
Counts number of atoms of given compounds. CTAB is urlsafe_base64 encoded string containing single molfile or
concatenation of multiple molfiles.
cURL examples:
curl -X GET ${BEAKER_ROOT_URL}getNumAtoms/$(cat aspirin.mol | base64 -w 0 | tr "+/" "-_")
"""
dat... | 60be1d8ae075cd13a02de83f72ebf9752e89682f | 3,621,149 |
import pkg_resources
def get_requirement_version(package_name, dependency_name):
"""Get assigned version to a dependency in package requirements."""
package_name = package_name.replace('pollination.', 'pollination_')
package_name = name_to_pollination(package_name)
dependency_name = dependency_name.re... | 30a898236698ed76a8cb45fe078eb42fa7666a2e | 3,621,150 |
from typing import Counter
import math
def cosine(s1, s2):
"""
Retuns the cosine value between two strings
>>> cosine("This is a sentence", "This is a sentence")
1.0
"""
vec1 = Counter(s1.split())
vec2 = Counter(s2.split())
intersection = set(vec1.keys()) & set(vec2.keys())
nume... | c1864a986cae8ca3be43dc6a0a02afa4419217f7 | 3,621,151 |
from pathlib import Path
import typing
def generate_multiple_simulations(path_sumo_cfg: Path,
flow_configs: typing.Dict[str, typing.Dict],
n_simulation: int) -> typing.List[Path]:
"""Generate "n_simulation" configuration files while updating valu... | 44a69fcfbc0261a19e8c096d551f487a7a5b4a71 | 3,621,152 |
def get_all_types(inactive=0):
"""Get all non-deleted instance_types.
Pass true as argument if you want deleted instance types returned also.
"""
return db.instance_type_get_all(context.get_admin_context(), inactive) | 2202e99d0bac38bd89427d17a829e4e56f93fbf7 | 3,621,153 |
from typing import List
def merge_split_assoc_words(assoc_words: List[AssocWord]) -> List[AssocWord]:
"""
This function merges all groups of AssocWords, apart from when an AssocWord
with a `form' appears on the right side in which case a new group is
started again.
Conversely, if an AssocWord has... | d7b16bd1e6556e4fe6373c0ab38938d78aa4236c | 3,621,154 |
def get_predicates(rules, roles):
"""Extract predicate information from the rules"""
preds = set()
pred_names = set()
predTypes = {}
# maps places to the equivalence class they're in
ec = TypedEquivalenceClass()
for r in rules:
goal_place_types = {}
if r.get_head().get_relation() == 'goal':
score = r.get... | fa757d35d2a476456c9d114ea6511fa69a6f3483 | 3,621,155 |
def comment_dicts_to_entities(comment_dicts):
"""Converts the list of comment dicts to the list of comment entities."""
return [comment_dict_to_entity(comment_dict)
for comment_dict in comment_dicts] | 6904c1758f03c67913a3aa5629cf2f9216b0d70e | 3,621,156 |
def get_comment(id, check_author=True):
"""Get a comment and its post and its author by id.
Checks that the id exists and optionally that the current user is
the author of its post.
:param id: id of comment to get
:param check_author: require the current user to be the author
:return: the comm... | 8025ce6760c0f30d8e254dab689e1949945f4858 | 3,621,157 |
import string
def letter_extractor(raws):
"""letter_
Frequencies of 26 English letters in a given text, case insensitive.
Known differences with Writeprints Static feature "letter frequency": None.
Args:
raws: List of documents.
Returns:
Frequencies of English letters in the do... | 54dde1c58b7f5c59af313f11294483196ba917dc | 3,621,158 |
def crop_frames(frames, speaker):
"""
frames: (b h w c)
"""
if speaker == "chem" or speaker == "hs":
return frames
elif speaker == "chess":
return frames[:, 270:460, 770:1130]
elif speaker == "dl" or speaker == "eh":
return frames[:, int(frames.shape[1] * 3 / 4) :, int(fr... | 1d92d7f6ea62f26a8bfead47594681602f2051c4 | 3,621,159 |
def request_unaffiliated_research_access(request):
""" Submit request for unaffiliated research access """
name = "%s %s" % (request.user.first_name, request.user.last_name)
form = form_for_request(request, UnaffiliatedResearchRequestForm, initial={'name': name, 'email': request.user.email})
if request... | a7035d715ed70a2e356ff922edc3d6eb05ce6411 | 3,621,160 |
def builddict(fin):
"""
Build a dictionary mapping from username to country for all classes.
Takes as input an open csv.reader on the edX supplied file that lists
classname, country, and username and returns a dictionary that maps from
username to country
"""
retdict = {}
for cours... | ddf9272e0da6616abd0495b7b159807a36a83dcc | 3,621,161 |
from datetime import datetime
def get_timeseries(length, delta=datetime.timedelta(hours=1)):
"""Generate timeseries data"""
start = datetime.datetime.now()
timeseries = [start]
for i in range(length - 1):
timeseries.append(timeseries[i] + delta)
return timeseries | 7846d2237e49bc64e8e581bce6f51dc199dd234f | 3,621,162 |
def add_static_values(caomlist, statics, data_type, header_type):
""" Add entries from the statics dictionary to the caomlist by looking at
properties of data_type and header_type. The add_value_caomxml module is
used to actually create the CAOMxml objects and add them to the caomlist.
"""
caomlis... | 3597dbb0b1789b5dc5ddddeeb55299d8666d1079 | 3,621,163 |
def dict_to_stix2(stix_dict, allow_custom=False, version=None):
"""convert dictionary to full python-stix2 object
Args:
stix_dict (dict): a python dictionary of a STIX object
that (presumably) is semantically correct to be parsed
into a full python-stix2 obj
allow_custom... | 0a7167673b96b6266fc6030e656371adf8fdfb6f | 3,621,164 |
from typing import Callable
from typing import Type
def connector(schema: str) -> Callable[[Type[Connector]], Type[Connector]]:
"""
The @connector class decorator used to register the connector
to the global registry.
Parameters
----------
schema
The schema for the connector, for exam... | 5ec1429dd98356a5127d236e76e93792295d10a3 | 3,621,165 |
def resource_show(expression):
"""returns the metadata of a resource"""
url = OPENDATA_URL + "resource_show?{expression}".format(expression=expression)
return _request_json(url).get("result", dict()) | 5a92c08f3c81b87b70df06c01d7b5eaf430e5380 | 3,621,166 |
import numpy as np
def n_overlap_1 ( ri, ei, box, r, e ):
"""Takes in coordinates and orientations of a molecule and counts overlaps.
Values of box and partner coordinate array are supplied.
Fast or slow algorithm selected.
"""
# In general, r will be a subset of the complete set of simulation ... | 20b1f27677e24f42410d9821f211d781df567e02 | 3,621,167 |
def HJB_ode(y, time, b, I_func):
"""
Hamilton-Jacobi-Bellman equation
"""
u, v, w = y
dudt = cost_effort(b(T_max - time)) + b(T_max - time) * \
I_func(T_max - time) * (v - u) - vac(T_max - time) * u
dvdt = cost_infection(time) + gamma * (w - v)
dwdt = rho * (u - w)
return dudt, d... | c625d8947db0630d92698303b2390ef568062894 | 3,621,168 |
from typing import Tuple
import re
def get_contexts(pp_threshold: float, d_threshold: float, spans: int, use_qa_table_enrichment: bool,
doc_and_tables_dfs: Tuple[pd.DataFrame, pd.DataFrame]) -> Tuple[pd.DataFrame,
pd.Dat... | 9eb838245110297c343f871397e403641bf1e65a | 3,621,169 |
from typing import Union
from pathlib import Path
def _get_suffix(filepath: Union[str, Path, FSMap]) -> str:
"""Check if file type is supported."""
# TODO: handle multiple files through the same set of checks for combining files
if isinstance(filepath, FSMap):
suffix = Path(filepath.root).suffix
... | 2fbab9962107773220a026d1c4ecf9feecde8ac3 | 3,621,170 |
def decision_tree_predict(tree, testing_example, max_value_in_target_attribute):
"""
:param max_value_in_target_attribute: If we are not able to classify due to less data, we return this value when testing
:param tree: This is the trained tree which we will use for finding the class of the given instance
... | 39adeafcc247c397b6511001eeab183d1e542b05 | 3,621,171 |
def load_data(census_region: int, filepath: str = "nhts_census_updated.mat"):
"""Load the data at nhts_census.mat.
:param int census_region: the census region to load data from.
:param str filepath: the path to the matfile.
:raises ValueError: if the census division is not between 1 and 9, inclusive.
... | fc9ae6f96c8f886a1436b34d54d68d62483f1e5e | 3,621,172 |
import win32api
def getFileProperties(fname):
"""
Read all properties of the given file return them as a dictionary.
"""
propNames = (
"Comments",
"InternalName",
"ProductName",
"CompanyName",
"LegalCopyright",
"ProductVersion",
"FileDescription... | 319179b3f4528a1f92a2949b81c2168247aa0686 | 3,621,173 |
def setup_scanner(hass, config, see, discovery_info=None):
"""Set up the Volvo tracker."""
if discovery_info is None:
return
vin, _ = discovery_info
vehicle = hass.data[DATA_KEY].vehicles[vin]
def see_vehicle(vehicle):
"""Handle the reporting of the vehicle position."""
hos... | 76f930dc3ffe3cce94fa78cf26bafa24161bf2e4 | 3,621,174 |
def tvdb_get_id(sername, config):
"""
TVDB: Get SeriesID from SeriesName
"""
# Query TVDb for SeriesName
xresp = getxml(config.tvdb['mirror'] + "/api/GetSeries.php", {'seriesname': sername})
logthis("Got response from TVDb:", suffix=print_r(xresp), loglevel=LL.DEBUG2)
snorm = normalize(sern... | 26ebe36346e74ccaad90b4e88dbf764d01b6e0a7 | 3,621,175 |
def check_satisfy_program(w, program):
"""
For each rule in the program, this function checks whether the head exists if all literals(or atoms) in the body exists
in each ruler interval of the given Window ``w'' .
Args:
w (a Window instance):
program (a list of rules):
Returns:
... | 7129a21922108ed5e1fd23af16b0d4b859f48fe6 | 3,621,176 |
import pdb
def extend(start,end,vector,holevector) :
""" Extend the subgrids one point if possible, to avoid edges
"""
s=np.max([0,start-1])
e=np.min([len(vector),end+1])
hs=np.max([0,np.where(np.isclose(holevector,vector[s]))[0][0]])
he=np.min([len(holevector),np.where(np.isclose(holevector,v... | 5ec18fb1dc84a5170934fb45b2e69aa109d383e0 | 3,621,177 |
def array(obj, row_major=0):
"""Wrapper around numpy.ndarray. It gives you the option of
specifying the order of the contents. """
if not isinstance(obj, np.ndarray):
obj = np.array(obj)
if row_major == 0:
if obj.flags.f_contiguous:
return obj
else:
dim = ... | e431d744afcada334fea115bf834314ffa7138bd | 3,621,178 |
def get_reverse_depends(name, capability_instances):
"""Gets the reverse dependencies of a given Capability
:param name: Name of the Capability which the instances might depend on
:type name: str
:param capability_instances: list of instances to search for having a
dependency on the given Capab... | fda11bb01d6352b18e87365f1060f48a5c07f266 | 3,621,179 |
import random
def normal2(startt,endt,money2,first,second,third,forth,fifth,sixth,seventh,zz1,zz2):
"""
for source and destination id generation
"""
"""
for type of banking work,label of fraud and type of fraud
"""
idvariz=random.randrange(1, 100001)
idgirand... | d60ba311afc9b80e4c3c95dd97e984c184b586ff | 3,621,180 |
import collections
def node_degree_counter(g, node, cache=True):
"""Returns a Counter object with edge_kind tuples as keys and the number
of edges with the specified edge_kind incident to the node as counts.
"""
node_data = g.node[node]
if cache and 'degree_counter' in node_data:
return no... | 08c08f240e3170f4159e72bc7e69d99b69c37408 | 3,621,181 |
async def get_account_id(db, name):
"""Get account id from account name."""
return await db.query_one("SELECT find_account_id( (:name)::VARCHAR, True )", name=name) | 3dd6b46abd8726eb34eb4f8e1850dc56c3632e5c | 3,621,182 |
def params_to_payload(params, config):
"""Converts a set of parameters into a payload for a GET or POST
request.
"""
base_payload = {config['param-api-key']: config['api-key']}
return dict(base_payload, **params) | aec633ab62cf18c0acf685115d4e291cd6198cb3 | 3,621,183 |
def colorize_img(value, vmin=None, vmax=None, cmap='jet'):
"""
A utility function for TensorFlow that maps a grayscale image to
a matplotlib colormap for use with TensorBoard image summaries.
By default it will normalize the input value to the range 0..1
before mapping to a grayscale colormap.
A... | f76593bb8427bf0332fa47f9098ef11e2fe56c23 | 3,621,184 |
from typing import Mapping
import types
def evaluate_models(
models: Mapping[K, RewardModel], batch: types.Transitions
) -> Mapping[K, np.ndarray]:
"""Computes prediction of reward models."""
reward_outputs = {k: m.reward for k, m in models.items()}
feed_dict = make_feed_dict(models.values(), batch)
... | d9b7337836f72e85a443b409bc69b5079a80b13e | 3,621,185 |
import os
def check_clangxx(default="clang++"):
"""Compile a basic C++11 binary."""
executable = os.getenv("CXX", default)
return check_bin(executable,
"-x c++ -std=c++11 - -o /dev/null".split(),
what="clang++",
input="int main() { return 1; }... | dc6763af2627811c67748992741d2cb823d7ec53 | 3,621,186 |
from typing import Any
def is_a_string(v: Any) -> bool:
"""Returns if v is an instance of str.
"""
return isinstance(v, str) | f729f5784434ef255ea9b2f0ca7cdfbf726e7539 | 3,621,187 |
def wheel_speed_commands(u_ref, w_ref, d, r):
"""Converts reference speeds to wheel speed commands"""
leftSpeed = float((2 * u_ref - d * w_ref) / (2 * r))
rightSpeed = float((2 * u_ref + d * w_ref) / (2 * r))
leftSpeed = np.sign(leftSpeed) * min(np.abs(leftSpeed), MAX_SPEED)
rightSpeed = np.sig... | 262603298ec5acd948eca0b873ca7051395e1515 | 3,621,188 |
def _get_dataset_from_filename(filename_skip_take, do_skip, do_take):
"""Returns a tf.data.Dataset instance from given (filename, skip, take)."""
filename, skip, take = (filename_skip_take['filename'],
filename_skip_take['skip'],
filename_skip_take['take'],)
dat... | 0f2964a1585ad0be0729544a4451ccabba65abd8 | 3,621,189 |
def kde_normalize(arr, mask=None, modality="T1w", norm_value=1):
""" Use kernel density estimation to find the peak of the white
matter in the histogram of a skull-stripped image. Then normalize
intensitites to a normalization value.
Parameters
----------
arr: array
the input data.
... | 488093f13adcf091aa2eeaa7d8254f58b6bce11f | 3,621,190 |
import argparse
def _parse_cmd_args(args_to_parse: list[str]) -> HashableDict:
"""Parse command line arguments for the sound change applier."""
parser = argparse.ArgumentParser(
prog="sound-change-applier-v2.0",
description="A program that applies phonological rules to words.",
epilog=... | 697e7cc6b365ab6ab0a9ed715e66122ba4a0cfa4 | 3,621,191 |
def nfour_connectivity(I):
"""
Returns an image of four-connectivity for each pixel, where the pixel value
is the number of 4-connected neighbors.
"""
Ir = np.ravel(I)
edgeidcs = edge_coords(I.shape, dtype='flat')
allpix = set(np.where(Ir==1)[0])
dopix = allpix - edgeidcs... | c8763e33cf29167b99bbbbfed95d5f547080c9b9 | 3,621,192 |
def plot_bargraph(count_plot_df, plot_df):
"""
Plots the bargraph
Arguments:
count_plot_df - The dataframe that contains lemma counts
plot_df - the dataframe that contains the odds ratio and lemmas
"""
graph = (
p9.ggplot(count_plot_df.astype({"count": int}), p9.aes(x="lemma... | f0543c5cc860d5ec520521830f37ad87bc2abb25 | 3,621,193 |
def flip_labels(Y, p):
"""Returns binary class labels with proportion p randomly flipped."""
assert set(Y) == {1, 2}
Y = np.copy(Y)
for i, e in enumerate(Y):
if np.random.rand() < p:
if e == 1:
Y[i] = 2
else:
Y[i] = 1
return Y | 54abf9429add794203602b67368ede818fbb1646 | 3,621,194 |
def find_key(obj, predicate=None):
"""This method is like :func:`pydash.arrays.find_index` except that it
returns the key of the first element that passes the predicate check,
instead of the element itself.
Args:
obj (list|dict): Object to search.
predicate (mixed): Predicate applied pe... | bee0e0fe07df7a7a43a53b68527007962b125a48 | 3,621,195 |
import os
import json
import logging
def trigger_github_deployment_create(payload):
"""
Trigger the function that creates the GH deployment with the given payload
"""
response = lambda_client.invoke(
FunctionName="{}-github_deployment_create".format(
os.environ['FUNCTION_PREFIX']),... | f24e3b4eacc1612bddc17eb78649d949b6613a3d | 3,621,196 |
def reports_home(request):
"""Some default page for reports home page."""
try:
blank_date = '..' * 23
blank_time = '.' * 20
address = 'P.O Box %s' % ('.' * 30)
params, location = {}, '.' * 20
form = CaseLoad(request.user)
if request.method == 'POST':
d... | 97ef40998cdc28d6f6ec76fb518b4bdddae60dec | 3,621,197 |
def historical():
"""" Retrieve stored data from datastore. """
return {
'page': 'historical',
} | 91933b3372e2972c37aaae2d8c83696e9398c19c | 3,621,198 |
import subprocess
def run_tests(code, probid, subid, test_name):
"""
Run the code on test cases.
Assume that the code is already compiled to [probid]-[subid].
Return the error code (no_err, runtime_err, or mismatch_err) and extra info.
Note: Does not clean up the files. Need to run cleanup after... | 1f29ebac8fef164222cdb43ca13f66f207b78c13 | 3,621,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.