content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def dustSurfaceDensitySingle(R, Rin, Sig0, p):
"""
Calculates the dust surface density (Sigma d) from single power law.
"""
return Sig0 * pow(R / Rin, -p) | 441466f163a7b968cf193e503d43a1b014be7c5d | 32,136 |
def rightToPurchase(
symbol="", refid="", token="", version="", filter="", **timeseries_kwargs
):
"""Right to purchase up-to-date and detailed information on all new announcements, as well as 12+ years of historical records.
Updated at 5am, 10am, 8pm UTC daily
https://iexcloud.io/docs/api/#right-to-pu... | 8897902c7b729642cdd5e89658f62b70bccf2133 | 32,137 |
def compute_edits(old, new):
"""Compute the in-place edits needed to convert from old to new
Returns a list ``[(index_1,change_1), (index_2,change_2)...]``
where ``index_i`` is an offset into old, and ``change_1`` is the
new bytes to replace.
For example, calling ``compute_edits("abcdef", "qbcdzw"... | f729addf84207f526e27d67932bb5300ced24b54 | 32,138 |
def gpx_to_lat_lon_list(filename):
"""
Summary: takes a .gpx file and turns the latitude and longitudes into a list of tuples
Returns: list of tuples (latitude, longitude).
"""
gpx_file = open(filename, "r")
gpx = gpxpy.parse(gpx_file)
latlonlist = []
if len(gpx.tracks) > 0:
... | 4d413a5894a30bb176a103b8a3933685490f30fe | 32,139 |
def pre_order(size):
"""List in pre order of integers ranging from 0 to size in a balanced
binary tree.
"""
interval_list = [None] * size
interval_list[0] = (0, size)
tail = 1
for head in range(size):
start, end = interval_list[head]
mid = (start + end) // 2
if mid ... | 45ab688c627c19cd0b9c1200830a91b064d46bda | 32,140 |
def LockPrefix():
"""Returns the lock prefix as an operand set."""
return set([Operands(disasms=('lock',))]) | d4f84027494ad176efcb8c01f14876474aaca57f | 32,141 |
def distance(pt, pts):
"""Distances of one point `pt` to a set of points `pts`.
"""
return np.sqrt((pts[:,0] - pt[0])**2 + (pts[:,1] - pt[1])**2) | 06512472ac6c0e58182ad58190c82fa619d66d40 | 32,142 |
def prepare_rw_output_stream(output):
"""
Prepare an output stream that supports both reading and writing.
Intended to be used for writing & updating signed files:
when producing a signature, we render the PDF to a byte buffer with
placeholder values for the signature data, or straight to the provid... | af1afe87e5de12cad9eb72b93da069327c1fffb5 | 32,143 |
from pathlib import Path
def add_references(md, tmp_dir, args):
"""
Remember that this function is run for main, review, and editor.
"""
citations_to_do = tmp_dir / 'citations.json'
biblio = Path(args.library).with_suffix('.json')
_prepare_node_input(md, citations_to_do)
_check_citation_... | 5c4319720a809c9e6543ef078598b7a3539c3492 | 32,144 |
from pandas import Timestamp
def timestamp_now() -> Timestamp:
"""Returns a pandas timezone (UTC) aware Timestamp for the current time.
Returns:
pandas.Timestamp: Timestamp at current time
"""
return timestamp_tzaware(Timestamp.now()) | 545b0cb72691d3db127ccfc847295a4bc4902004 | 32,146 |
def readFlat4D(fn,interp=None):
"""
Load in data from 4D measurement of flat mirror.
Scale to microns, remove misalignments,
strip NaNs.
Distortion is bump positive looking at surface from 4D.
Imshow will present distortion in proper orientation as if
viewing the surface.
"""
#Get xp... | 8443ab4943bb571d1ead1f8f4342efec8e426139 | 32,147 |
def inner_product(D1, D2):
"""
Take the inner product of the frequency maps.
"""
result = 0.
for key in D1:
if key in D2:
result += D1[key] * D2[key]
return result | 95efb9f63d6a379e1c5f7c8f6ad4bfd4061e2032 | 32,148 |
def list_launch_daemons():
"""
Return an array of the files that are present in /Library/LaunchDaemons/
and /System/Library/LaunchDaemons/
"""
files = list_files_in_dir("/Library/LaunchDaemons/")
files += list_files_in_dir("/System/Library/LaunchDaemons/")
return files | 8e1f0ab1bb78a9121f5c00f032a5c8dc089f39b0 | 32,149 |
import struct
def us_varchar_encode(text):
"""
encode with utf-16-le
UShort *Varchar
:param str text:
:return:
"""
if not text:
return '\x00\x00'
length = len(text)
return struct.pack('<H', length) + text.encode('utf-16-le') | 07b232cd83e023d770fc4e7cd63250ad746aae19 | 32,151 |
from typing import List
def graph_to_diagonal_h(n: int, nodes: List[int]) -> np.ndarray:
"""Construct diag(H)."""
h = [0.0] * 2**n
for node in nodes:
diag = tensor_diag(n, node[0], node[1], node[2])
for idx, val in enumerate(diag):
h[idx] += val
return h | 5c73d4b4a98465f3f03d9a423f867479b48da8fe | 32,152 |
def condensational_heating(dQ2):
"""
Args:
dQ2: rate of change in moisture in kg/kg/s, negative corresponds
to condensation
Returns:
heating rate in degK/s
"""
return tf.math.scalar_mul(tf.constant(-LV / CPD, dtype=dQ2.dtype), dQ2) | 55d5ec36bf1f4a217e239e35fb95e14060b07fb8 | 32,153 |
def collect_stats(cube, store, datasets=None):
"""
Collect statistics for given cube.
Parameters
----------
cube: Cube
Cube specification.
store: simplekv.KeyValueStore
KV store that preserves the cube.
datasets: Union[None, Iterable[str], Dict[str, kartothek.core.dataset.Da... | 526405128e95e13fb6f011300ddcda922ebe8582 | 32,154 |
def post_move_subject(subject_uuid: SubjectId, target_report_uuid: ReportId, database: Database):
"""Move the subject to another report."""
data_model = latest_datamodel(database)
reports = latest_reports(database)
source = SubjectData(data_model, reports, subject_uuid)
target = ReportData(data_mode... | 405be11279fe3fa2a65b75ac46518cdaabcb5e90 | 32,155 |
def open_instrument(instr_type):
"""open_visa_instrument implements the public api for each of the drivers for discovering and opening a connection
:param instr_type:
The abstract base class to implement
A dictionary containing the technical specifications of the required equipment
:return:
A i... | 1741b94a527a0283efee7466ccc15be09abe1622 | 32,157 |
import jinja2
from datetime import datetime
def thisyear():
"""The current year."""
return jinja2.Markup(datetime.date.today().year) | 3de970398e1fb55f98a968c0c83411d18e8cd423 | 32,158 |
from unicodedata import east_asian_width
def display_width(str):
"""Return the required over-/underline length for str."""
try:
# Respect &ambiwidth and &tabstop, but old vim may not support this
return vim.strdisplaywidth(str)
except AttributeError:
# Fallback
result = 0
... | ebeedd159de5c31ea435d44a88fe6fe16ccbcb54 | 32,159 |
def get_short_int(filename, ptr):
"""Jump to position 'ptr' in file and read a 16-bit integer."""
val = get_val(filename, ptr, np.int16)
return int( val ) | 42377a73df1dfbff2593fa43e571e3d269db6449 | 32,160 |
def u32_from_dto(dto: U32DTOType) -> int:
"""Convert DTO to 32-bit int."""
check_overflow(0 <= dto <= U32_MAX)
return dto | 066ab2c2ed70d69ac8e37515ea815e1305574eea | 32,161 |
def diagonal_basis_commutes(pauli_a, pauli_b):
"""
Test if `pauli_a` and `pauli_b` share a diagonal basis
Example:
Check if [A, B] with the constraint that A & B must share a one-qubit
diagonalizing basis. If the inputs were [sZ(0), sZ(0) * sZ(1)] then this
function would return Tr... | b95ac0cfe22233432df3a0e0f814c4e0e7af6d0f | 32,162 |
def cost_using_SigmoidCrossEntropyWithLogits(logits, labels):
"""
Computes the cost using the sigmoid cross entropy
Arguments:
logits -- vector containing z, output of the last linear unit (before the final sigmoid activation)
labels -- vector of labels y (1 or 0)
Note: What we've bee... | 7990ee4cb4b4ebfc7b5f1f580be2315ee6667fa5 | 32,163 |
def clone_to_df(clone):
"""Convert a clone to a pandas.DataFrame."""
number_of_mutations = clone.deltas.shape[0]
clone_stats = pd.DataFrame(
np.stack([clone.frequencies for _ in range(number_of_mutations)]),
columns=clone.frequencies.index,
index=clone.deltas.index
)
clone_st... | e383241b024d5deef7022be3d04b36f4ffcee587 | 32,164 |
def reorder_kernel_weight(torch_weight):
""" Reorder a torch kernel weight into a tf format """
len_shape = len(torch_weight.shape)
transpose_target = list(range(len_shape))
transpose_target = transpose_target[2:] + transpose_target[:2][::-1]
return torch_weight.transpose(transpose_target) | 2e289d768d31d3ed875fbb3613ec0e3061b65cd9 | 32,166 |
def make_windows(x, window_size, horizon):
"""
Creates a window out of
"""
# Create a window of specific window size
window_step = np.expand_dims(np.arange(window_size+horizon), axis=0)
# Create a 2D array of multiple window steps
window_indices = window_step + np.expand_dims(np.arang... | 4e226e2ee2c3951cd2dfe6cb4a92b9d66e9376bf | 32,167 |
def interpolate(arr_old, arr_new, I_old, J_old):
# deprecated 2013-08-26
"""
input: array, i, j
output: value
(int(x),
int(y)+1)
+ + (int(x)+1, int(y)+1)
(x,y)
+ + (int(x)+1, int(y))
(int(x),
int(y))
be careful - floor(x)=ceil(x)=x for intege... | bcb34c33ca462c43390ff0dd8802d05dc0512dd3 | 32,168 |
def point_seg_sep(ar, br1, br2):
"""Return the minimum separation vector between a point and a line segment,
in 3 dimensions.
Parameters
----------
ar: array-like, shape (3,)
Coordinates of a point.
br1, br2: array-like, shape (3,)
Coordinates for the points of a line segment
... | a036f4ea9e9c308002e18e75111aed4408d75cf4 | 32,170 |
from typing import Callable
def shd(node_1: BinaryTreeNode,
node_2: BinaryTreeNode,
hd: Callable[[BinaryTreeNode, BinaryTreeNode], float]) -> float:
"""Structural Hamming distance (SHD)
:param node_1:
:param node_2:
:param hd:
:return:
"""
if node_1 is None or node_2 is No... | c6aef0189d41887fc4e63991d0176a27b0e1dd8a | 32,172 |
import numpy
def movmeanstd(ts, m=0):
"""
Calculate the mean and standard deviation within a moving window passing across a time series.
Parameters
----------
ts: Time series to evaluate.
m: Width of the moving window.
"""
if m <= 1:
raise ValueError("Query length must be long... | 8a9e56db4f26862bff972a3dbfac87f6ea5b8c35 | 32,173 |
def importing_regiondata():
"""
Loads the regiondata
Should convert the year column to proper year
Should immediately create geopandas dataframe
Returns: a dataframe
"""
regiondata = pd.read_stata("data/regiondata.dta")
return regiondata | 132e4076e941f4451b6bb52c5d81c5895dde0154 | 32,174 |
def rotationFromQuaternion(*args):
"""rotationFromQuaternion(float pA, float pB, float pC, float pD) -> Rotation"""
return _almath.rotationFromQuaternion(*args) | e418bf864246ef209291d970e9cf33f0edc3fe8f | 32,176 |
import re
def get_username(identifier):
"""Checks if a string is a email adress or not."""
pattern = re.compile('.+@\w+\..+')
if pattern.match(identifier):
try:
user = User.objects.get(email=identifier)
except:
raise Http404
else:
return user.use... | de5eb0db99b9580cd210f733cd2e829c84593573 | 32,177 |
def halo_particles(mock_dm_halo):
"""Spherical mock halo."""
def make(N_part=100, seed=None):
random = np.random.RandomState(seed=seed)
mass_dm, pos_dm = mock_dm_halo(N_part=N_part)
vel_dm = random.random_sample(size=(N_part, 3))
return mass_dm, pos_dm, vel_dm
return make | 36c980c0d81c4a1edf09feec9aafcf1605968bb3 | 32,178 |
def get_sec (hdr,key='BIASSEC') :
"""
Returns the numpy range for a FITS section based on a FITS header entry using the standard format
{key} = '[{col1}:{col2},{row1}:row2}]'
where 1 <= col <= NAXIS1, 1 <= row <= NAXIS2.
"""
if key in hdr :
s = hdr.get(key) # WITHOUT CARD COMMENT
ny = hdr['NAXIS2']
sx = ... | 3927e6f5d62818079fa9475976f04dda1824e976 | 32,180 |
import numpy
def _fetch_object_array(cursor, type_tree=None):
"""
_fetch_object_array() fetches arrays with a basetype that is not considered
scalar.
"""
arrayShape = cursor_get_array_dim(cursor)
# handle a rank-0 array by converting it to
# a 1-dimensional array of size 1.
if len(ar... | b4e262ec7fc4dba943ab2f8420add12f59aed4eb | 32,181 |
import pickle
def load_training_batch(batch_id, batch_size):
"""Load the Preprocessed Training data and return them in batches of <batch_size> or less"""
filename = 'data/cifar_pickle/' + 'batch_' + str(batch_id) + '.pkl'
features, labels = pickle.load(open(filename, mode='rb'))
return batch_features_... | 4aa762a80dde638d71076a888613606a1ee11a48 | 32,182 |
import logging
import json
def get_record(params,record_uid):
"""Return the referenced record cache"""
record_uid = record_uid.strip()
if not record_uid:
logging.warning('No record UID provided')
return
if not params.record_cache:
logging.warning('No record cache. Sync down ... | 7fce71c2f90387272a9c9b0a61ad4cccabf830f5 | 32,185 |
def get_probabilities(path, seq_len, model, outfile, mode):
"""
Get network-assigned probabilities
Parameters:
filename (str): Input file to be loaded
seq_len (int): Length of input DNA sequence
Returns:
probas (ndarray): An array of probabilities for the test set
true ... | a75bc11704538d082ecf91a61765f4412ec2c75d | 32,186 |
from azure.mgmt.sql import SqlManagementClient
from azure.cli.core.commands.client_factory import get_mgmt_service_client
def get_sql_management_client(_):
"""
Gets the SQL management client
"""
return get_mgmt_service_client(SqlManagementClient) | 6f67408fdecbe9b1a70ffbc34a4871c796e0f9f6 | 32,188 |
def string_to_gast(node):
"""
handles primitive string base case
example: "hello"
exampleIn: Str(s='hello')
exampleOut: {'type': 'str', 'value': 'hello'}
"""
return {"type": "str", "value": node.s} | a3dcd89e893c6edd4a9ba6095cd107bb48cc9782 | 32,189 |
def ed25519_generate_key_pair_from_secret(secret):
"""
Generate a new key pair.
Args:
secret (:class:`string`): A secret that serves as a seed
Returns:
A tuple of (private_key, public_key) encoded in base58.
"""
# if you want to do this correctly, use a key derivation function... | 25b8c18289c4cf8f09a7ba937fc8f9645406e9f2 | 32,190 |
from typing import List
import math
def align_tiles_naive(request: AlignNaiveRequest,
tiles: List[TileModelDB]) -> List[AlignedTiledModel]:
"""
performs a naive aligning of the tiles simply based on the given rows and method.
does not perform any advanced stitching or pixel c... | b279273d800a6884ad95f43f0a6a6f3be1ac3243 | 32,191 |
def estimate_operating_empty_mass(mtom, fuse_length, fuse_width, wing_area,
wing_span, TURBOPROP):
""" The function estimates the operating empty mass (OEM)
Source: Raymer, D.P. "Aircraft design: a conceptual approach"
AIAA educational Series, Fourth edition (2006)... | 5b9bed8cef76f3c10fed911087727f0164cffab2 | 32,192 |
def var_gaussian(r, level=5, modified=False):
"""
Returns the Parametric Gaussian VaR of a Series or DataFrame
"""
# compute the Z score assuming it was Gaussian
z = norm.ppf(level/100)
if modified:
# modify the Z score based on observed skewness and kurtosis
s = skewness(r)
... | 18d3b1ee2228fafaaf977b216245c8217e77396b | 32,193 |
def grid_search_serial(data, greens, misfit, grid):
"""
Grid search over moment tensors. For each moment tensor in grid, generates
synthetics and evaluates data misfit
"""
results = np.zeros(grid.size)
count = 0
for mt in grid:
print grid.index
for key in data:
... | fa0a2c19cfbfa685d59f3effea7b3f7478999f88 | 32,194 |
def getSqTransMoment(system):
"""//Input SYSTEM is a string with both the molecular species AND the band "system"
// Electronic transition moment, Re, needed for "Line strength", S = |R_e|^2*q_v'v" or just |R_e|^2
// //Allen's Astrophysical quantities, 4.12.2 - 4.13.1
// // ROtational & vibrational constants for... | 19c5311f7d8fde4bb834d809fd2f6ed7dd2c036e | 32,195 |
def volumes(assets,
start,
end,
frequency='daily',
symbol_reference_date=None,
start_offset=0,
use_amount=False):
"""
获取资产期间成交量(或成交额)
Parameters
----------
assets (int/str/Asset or iterable of same)
Identifiers ... | e2e0a7d6bd8b659e070299d00699d8cae6ed3c9f | 32,196 |
def qipy_action(cd_to_tmpdir):
""" QiPy Action """
return QiPyAction() | 7c6d828c4baf29d2f457f02b0b54e6c967d96cb3 | 32,198 |
def vectorized_range(start, end):
""" Return an array of NxD, iterating from the start to the end"""
N = int(np.max(end - start)) + 1
idxes = np.floor(np.arange(N) * (end - start)[:, None] / N + start[:, None]).astype('int')
return idxes | cef2304639dbac3c1a1dfbd9ae928f813bd65b05 | 32,200 |
import random
def stratified(W, M):
"""Stratified resampling.
"""
su = (random.rand(M) + np.arange(M)) / M
return inverse_cdf(su, W) | 4f1ceb6840240178df312fee266fe612abb3193f | 32,201 |
def is_configured():
"""Return if Azure account is configured."""
return False | 5662656b513330e0a05fa25decc03c04b5f367fa | 32,202 |
def box_strings(*strings: str, width: int = 80) -> str:
"""Centre-align and visually box some strings.
Args:
*strings (str): Strings to box. Each string will be printed on its own
line. You need to ensure the strings are short enough to fit in the
box (width-6) or the results wi... | b47aaf020cf121b54d2b588bdec3067a3b83fd27 | 32,203 |
import traceback
def exceptions(e):
"""This exceptions handler manages Flask/Werkzeug exceptions.
For Renku exception handlers check ``service/decorators.py``
"""
# NOTE: Capture werkzeug exceptions and propagate them to sentry.
capture_exception(e)
# NOTE: Capture traceback for dumping it ... | 574c97b301f54785ae30dbfc3cc5176d5352cb82 | 32,204 |
import torch
def top_k_top_p_filtering(logits, top_k, top_p, filter_value=-float("Inf")):
"""
top_k或top_p解码策略,仅保留top_k个或累积概率到达top_p的标记,其他标记设为filter_value,后续在选取标记的过程中会取不到值设为无穷小。
Args:
logits: 预测结果,即预测成为词典中每个词的分数
top_k: 只保留概率最高的top_k个标记
top_p: 只保留概率累积达到top_p的标记
filter_value: ... | 74cf4a6cf4622ad1c9b124089cd84ddb07bdb7be | 32,205 |
def get_alb(alb_name, aws_auth_cred):
"""
Find and return loadbalancers of mentioned name
Args:
alb_name (str): Load balancer name
aws_auth (dict): Dict containing AWS credentials
Returns:
alb (dict): Loadbalancer details
"""
client = get_elbv2_client(aws_auth_cred)
... | a31ae3067d96008622b43c57ffd1b0de74eceaa0 | 32,206 |
def align_left_position(anchor, size, alignment, margin):
"""Find the position of a rectangle to the left of a given anchor.
:param anchor: A :py:class:`~skald.geometry.Rectangle` to anchor the
rectangle to.
:param size: The :py:class:`~skald.geometry.Size` of the rectangle.
:param alignment: T... | 2af1c6175960313958cc51d0180ebc4f6ed9dc41 | 32,207 |
def quickdraw_to_linestring(qd_image):
"""Returns a Shapely MultiLineString for the provided quickdraw image.
This MultiLineString can be passed to vsketch
"""
linestrings = []
for i in range(0, len(qd_image["image"])):
line = zip(qd_image["image"][i][0], qd_image["image"][i][1])
lin... | 39957b9a36a59b33a2fb5abc91f7479c946515a2 | 32,208 |
import functools
def build(image_resizer_config):
"""Builds callable for image resizing operations.
Args:
image_resizer_config: image_resizer.proto object containing parameters for
an image resizing operation.
Returns:
image_resizer_fn: Callable for image resizing. This callable always takes
... | 75df1c37397e88322113aa8822d60053ae54981d | 32,210 |
from typing import Optional
from typing import Tuple
def plotly_protein_structure_graph(
G: nx.Graph,
plot_title: Optional[str] = None,
figsize: Tuple[int, int] = (620, 650),
node_alpha: float = 0.7,
node_size_min: float = 20.0,
node_size_multiplier: float = 20.0,
label_node_ids: bool = Tr... | 4aae1ce763daa06627fe43e31780fa61cd1886a4 | 32,211 |
def mag_scale_rel_to_hazardlib(mag_scale_rel, use_default=False):
"""
Returns the magnitude scaling relation in a format readable by
openquake.hazardlib
"""
if isinstance(mag_scale_rel, BaseMSR):
return mag_scale_rel
elif isinstance(mag_scale_rel, str):
if not mag_scale_rel in SC... | 7db46083d4c05e3f53b4a5d064c923937bb5fe2a | 32,213 |
import regex
import tokenize
def __get_words(text, by_spaces):
"""
Helper function which splits the given text string into words. If by_spaces is false, then text like
'01-02-2014' will be split into 3 separate words. For backwards compatibility, this is the default for all
expression functions.
:... | 289d7cc58d165355a4e5a25db016dbe2e6aa74ec | 32,215 |
from typing import Any
def gera_paragrafo(data: pd.DataFrame) -> pd.DataFrame:
"""docstring for gera_paragrafo"""
data[["div_sup", "par"]] = data.location.str.split(".", n=1, expand=True)
data.dropna(inplace=True)
j: Any = data.groupby(["author", "text", "file", "div_sup", "par", "genero"]).agg(
... | 04285d5df307e87b8adc389cf2f03d9ef9b44276 | 32,216 |
def _parse_boolean(xml_boolean):
"""Converts strings "true" and "false" from XML files to Python bool"""
if xml_boolean is not None:
assert xml_boolean in ["true", "false"], \
"The boolean string must be \"true\" or \"false\""
return {"true": True, "false": False}[xml_boolean] | 6d9d1b617f8935d1684bd24bbea06d00ca2a5b4a | 32,217 |
def to_heterogeneous(G, ntypes, etypes, ntype_field=NTYPE,
etype_field=ETYPE, metagraph=None):
"""Convert a homogeneous graph to a heterogeneous graph and return.
The input graph should have only one type of nodes and edges. Each node and edge
stores an integer feature as its type ID
... | f1792d78e4b94c5f3d4f72ef6cfcbcb14c7d1158 | 32,218 |
def Solution(image):
"""
input: same size (256*256) rgb image
output: the label of the image
"l" -> left
"m" -> middle
"r" -> right
"o" -> other(NO target)
if no target detected, return "o", which is the initial value
"""
#initial two point for locatate the ... | 11fb49c96cb7cbfdfb522d6794f148cd6354dcf9 | 32,219 |
def index_to_tag(v, index_tag):
"""
:param v: vector
:param index_tag:
:return:
"""
idx = np.nonzero(v)
tags = [index_tag[i] for i in idx[0]]
return ' '.join(tags) | ebf30632bbf8a7b399461b191c33f345f04c4cc2 | 32,220 |
def first_phrase_span(utterance, phrases):
"""Returns the span (start, end+1) of the first phrase from the given list
that is found in the utterance. Returns (-1, -1) if no phrase is found.
:param utterance: The utterance to search in
:param phrases: a list of phrases to be tried (in the given order)
... | f3be7bd976c60467bcf51edfb15d3736e00568a8 | 32,222 |
from datetime import datetime
def parse_date(value):
"""Parse a string and return a datetime.date.
Raise ValueError if the input is well formatted but not a valid date.
Return None if the input isn't well formatted.
"""
match = date_re.match(value)
if match:
kw = {k: int(v) for k, v i... | b32cc64bab460e1384492b7cb694b8263431625f | 32,223 |
import scipy
def construct_Dfunc(delays, plot=False):
"""Return interpolation functions fD(t) and fdD(t).
fD(t) is the delay between infection and reporting at reporting time t.
fdD(t) is its derivative.
Parameter:
- delays: tuples (time_report, delay_days)
- plot: whether to generate a plo... | ee6acbc265d8020815ac2e9cd77fe74a6ff9d5f7 | 32,224 |
def deimmunization_rate_80():
"""
Real Name: b'deimmunization rate 80'
Original Eqn: b'Recovered 80/immunity time 80'
Units: b'person/Day'
Limits: (None, None)
Type: component
b''
"""
return recovered_80() / immunity_time_80() | 9221343889ba05d93671102e72ef70a5efd40a5a | 32,225 |
def connect_to_lightsail():
"""
Uses Paramiko to create a connection to Brendan's instance. Relies on authetication information from a JSON file.
:return SFTP_Client:
"""
return open_sftp_from_json(JSON_PRIVATE_DIR / 'lightsail_server_info.json') | fb0f74fe58e5a99ca93737415b931018be4d67d7 | 32,226 |
def coleman_operator(c, cp):
"""
The approximate Coleman operator.
Iteration with this operator corresponds to time iteration on the Euler
equation. Computes and returns the updated consumption policy
c. The array c is replaced with a function cf that implements
univariate linear interpolatio... | dee76b425b5a81799fd1677f2b9ca9889f4a813c | 32,227 |
def generate_scanset_metadata( image_set_dictionary, html_base_path, session_id ):
"""This is passed a set of NII images, their PNG equilvalents, and an html base path, and then it generates the metadata needed """
cur_subj_info = {}
"""need to think through the data structure a bit more.... but can always adjust l... | 4fa326018fc64f9ef2f7974d850256fdfa30f8f6 | 32,228 |
def read_error_codes(src_root='src/mongo'):
"""Define callback, call parse_source_files() with callback, save matches to global codes list."""
seen = {}
errors = []
dups = defaultdict(list)
skips = []
malformed = [] # type: ignore
# define validation callbacks
def check_dups(assert_loc... | 46f64798fd3e7010a96e054600557464cf99eade | 32,229 |
def filter_check_vlan_number(value):
"""
Function to check for a good VLAN number in a template
:param value:
:return:
"""
error = f'{value} !!!! possible error the VLAN# should be between 1 and 4096!!!!'
if not value: # pylint: disable=no-else-return
J2_FILTER_LOGGER.info('filter_c... | 6c9e060b13f49048f056b72a6def2d1d15241a74 | 32,230 |
def _sanitize(element) -> Gst.Element:
"""
Passthrough function which sure element is not `None`
Returns `Gst.Element` or raises Error
"""
if element is None:
raise Exception("Element is none!")
else:
return element | f07062474dcf2671cb1c3d13a7e80d9ee96b9878 | 32,231 |
import pytz
def mean(dt_list):
"""
.. py:function:: mean(dt_list)
Returns the mean datetime from an Iterable collection of datetime objects.
Collection can be all naive datetime objects or all datatime objects with tz
(if non-naive datetimes are provided, result will be cast to UTC).
However,... | 2d56eeea44d2afbf752672abb6870d7045745a0f | 32,232 |
from typing import Optional
from typing import Dict
def win_get_nonblocking(name: str, src_weights: Optional[Dict[int, float]] = None,
require_mutex: bool = False) -> int:
""" Passively get the tensor(s) from neighbors' shared window memory into
local shared memory, which cannot be acc... | a641f963ac3434ece7ded8a642c7833fc8a2b30c | 32,233 |
def parse(file, beautifulsoup=None, makeelement=None, **bsargs):
"""Parse a file into an ElemenTree using the BeautifulSoup parser.
You can pass a different BeautifulSoup parser through the
`beautifulsoup` keyword, and a diffent Element factory function
through the `makeelement` keyword. By default, t... | 5ccf2bfc8f1d6ec4f83200b250755ab149fd60dd | 32,234 |
def get_L_dashdash_b1_d(L_dashdash_b1_d_t):
"""
Args:
L_dashdash_b1_d_t: 1時間当たりの浴槽水栓湯はり時における太陽熱補正給湯負荷 (MJ/h)
Returns:
1日当たりの浴槽水栓湯はり時における太陽熱補正給湯負荷 (MJ/d)
"""
return np.sum(L_dashdash_b1_d_t.reshape((365, 24)), axis=1) | aa541c5f82aa94c33c65ac264f2df420020ca443 | 32,235 |
def split_df(df, index_range, columns, iloc=False):
"""Split a data frame by selecting from columns a particular range.
Args:
df (:class:`pd.DataFrame`): Data frame to split.
index_range (tuple): Tuple containing lower and upper limit of the
range to split the index by. If `index_ra... | 84e77e60a0f9c73ff3147c3648310875e5b58228 | 32,236 |
def basemap_to_tiles(basemap, day=yesterday, **kwargs):
"""Turn a basemap into a TileLayer object.
Parameters
----------
basemap : class:`xyzservices.lib.TileProvider` or Dict
Basemap description coming from ipyleaflet.basemaps.
day: string
If relevant for the chosen basemap, you ca... | ccaf3430294216e7015167dad3ef82bee8071192 | 32,237 |
def sms_count(request):
"""Return count of SMSs in Inbox"""
sms_count = Messaging.objects.filter(hl_status__exact='Inbox').count()
sms_count = sms_count if sms_count else ""
return HttpResponse(sms_count) | c445b7c5fd54f632fc6f7c3d0deaeca47c1dd382 | 32,239 |
from pathlib import Path
import yaml
def deserializer(file_name: Path) -> Deserializer:
"""Load and parse the data deserialize declaration"""
with open(file_name) as f:
return Deserializer(yaml.load(f, Loader=SafeLoader)) | 5df5de579e359e7d1658dd00cf279baacb844f1f | 32,240 |
def p2db(a):
"""Returns decibel of power ratio"""
return 10.0*np.log10(a) | 5177d9ca5ca0ec749e64ebf3e704cf496fa365db | 32,242 |
def buildDictionary(message):
"""
counts the occurrence of every symbol in the message and store it in a python dictionary
parameter:
message: input message string
return:
python dictionary, key = symbol, value = occurrence
"""
_dict = dict()
for c in message:
if ... | 71b196aaccfb47606ac12242585af4ea2554a983 | 32,243 |
import tensorflow as tf
from tensorflow.keras.callbacks import TensorBoard, ModelCheckpoint
import tensorflow.keras.backend as be
def model_fit(mb_query: str, features_dict: dict, target_var: str, model_struct_fn, get_model_sample_fn,
existing_models: dict, batch_size: int, epochs: int, patience: int, v... | add35320ef1d9f6474f3712f3222d9a5fdbb3185 | 32,245 |
def classify_subtrop(storm_type):
"""
SD purely - yes
SD then SS then TS - no
SD then TS - no
"""
if 'SD' in storm_type:
if 'SD' in storm_type and True not in np.isin(storm_type,['TD','TS','HU']):
return True
if 'SS' in storm_type and True not in np.isin(storm_type,['TD',... | abfc8e002e798e5642e2ab4ae38fe0882259d708 | 32,246 |
def overridden_settings(settings):
"""Return a dict of the settings that have been overridden"""
settings = Settings(settings)
for name, dft_value in iter_default_settings():
value = settings[name]
if value != dft_value and value is not None:
settings.update(name, value)
... | ec76feb90dbc97012f84f9ebc75b41131dc925fe | 32,247 |
def ScaleImageToSize(ip, width, height):
"""Scale image to a specific size using Stephans scaler"""
smaller = ip.scale( width, height );
return smaller | 9e2ee47ab30bfca70417eafbddd84958cd582618 | 32,248 |
import types
def retrieve_parent(*, schema: types.Schema, schemas: types.Schemas) -> str:
"""
Get or check the name of the parent.
If x-inherits is True, get the name of the parent. If it is a string, check the
parent.
Raise InheritanceError if x-inherits is not defined or False.
Args:
... | 4f6fc55af7b998e02b108d1bc5fea61f2afe82f1 | 32,249 |
from .translation.vensim.vensim2py import translate_vensim
def read_vensim(mdl_file, data_files=None, initialize=True,
missing_values="warning", split_views=False,
encoding=None, **kwargs):
"""
Construct a model from Vensim `.mdl` file.
Parameters
----------
mdl_fi... | 28d062ebb234cf991dcef164d5151e1ab62e08f7 | 32,250 |
import typing
def get_feature_importance(
trained_pipeline: sklearn.pipeline.Pipeline,
numeric_features: typing.List[str]
) -> pd.Series:
"""
Get feature importance measures from a trained model.
Args:
trained_pipeline (:obj:`sklearn.pipeline.Pipeline`): Fitted model pipeline
... | cd303af5a0b343a18fb42a3cd562998ecec96423 | 32,251 |
from typing import Any
import json
def json_loads(json_text: str) -> Any:
"""Does the same as json.loads, but with some additional validation."""
try:
json_data = json.loads(json_text)
validate_all_strings(json_data)
return json_data
except json.decoder.JSONDecodeError:
raise _jwt_error.JwtInval... | d123054612a0a3e29f312e1506181ca3f9bed219 | 32,252 |
def weights(layer, expected_layer_name):
"""
Return the kernels/weights and bias from the VGG model for a given layer.
"""
W = vgg_layers[0][layer][0][0][2][0][0]
b = vgg_layers[0][layer][0][0][2][0][1]
layer_name = vgg_layers[0][layer][0][0][0][0]
#to check we obtained the correct laye... | 5271f932bd9a870bd7857db50632cd51d91b60a9 | 32,253 |
import textwrap
def alert(title: str, text: str, *, level: str = "warning", ID: str = None):
"""
Generate the HTML to display a banner that can be permanently hidden
This is used to inform player of important changes in updates.
Arguments:
text: Main text of the banner
title: Title o... | 90ff85c228dc70318deee196bdd512e5be90a5ad | 32,254 |
def get_stim_data_df(sessions, analyspar, stimpar, stim_data_df=None,
comp_sess=[1, 3], datatype="rel_unexp_resp", rel_sess=1,
basepar=None, idxpar=None, abs_usi=True, parallel=False):
"""
get_stim_data_df(sessions, analyspar, stimpar)
Returns dataframe with rela... | 5a352a66ad06ed70b04db3ca3e26073fb412cccd | 32,255 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.