content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def scale(data, scale_feats):
"""
Just scales feats
"""
# Create scaler
scaler = StandardScaler()
scaler.fit(data[scale_feats])
scaled = data[scale_feats].copy()
# Convert numeric features to standard units
scaled = scaler.transform(scaled)
data[scale_feats] = scaled
... | 49c4c94e057824e6fe40eafd635317a21eab1d85 | 72,200 |
from typing import Optional
def str_():
"""
Return an optional str serde.
"""
return Optional(StrSerde()) | f85a218b70aaff1f46caded15d0f719e3a922b9b | 72,201 |
def get_slice_miss(self, dimspins, x):
"""
Convenience method to get list of missing values (get_miss),
choose slice of array (get_slice), and set missing values to
NaN or np.datetime64('NaT') in slice (set_miss).
Parameters
----------
self : class
ncvue class
dimspins : list
... | 049eae51ca1ec1d72ddb1e6db14c0b0e02e777b8 | 72,202 |
def getLandmarksFromVTKFile(file):
"""
Extract each landmark point line by line from a VTK file, and return vector containing all landmarks.
For cardiac data landmark indexes:
0-2 RV insert points
1 -> RV lateral wall turning point
3 -> LV lateral wall mid-point
4 -> apex
... | 7c09876c6db6d7f6314a641944a76a570216d2ae | 72,203 |
import functools
def require_debug(func):
"""
Decorator that wraps a Django view so it's only enabled when
settings.DEBUG is True. If settings.DEBUG is False, the view will
always return a 404.
"""
@functools.wraps(func)
def wrapper(*args, **kwargs):
if not settings.DEBUG:
... | f3fe02cac8bfff60e77a7019c5004ac007e7d766 | 72,204 |
def get_arg(cmds):
"""Accepts a split string command and validates its size.
Args:
cmds: A split command line as a list of strings.
Returns:
The string argument to the command.
Raises:
ValueError: If there is no argument.
"""
if len(cmds) != 2:
raise ValueError('%s needs an argument.' % c... | a12b9402cb824748127c9a925850a10f6a9fe022 | 72,205 |
from pathlib import Path
def _resolve_ros_workspace(ros_workspace_input: str) -> Path:
"""Allow for relative paths to be passed in as a ros workspace dir."""
ros_workspace_dir = Path(ros_workspace_input).resolve()
if not (ros_workspace_dir / 'src').is_dir():
raise ValueError(
'specifie... | 45c5843a2e34a79f077ae595b100f2d58f903bae | 72,206 |
def rnd(n, s):
"""
returns positive int, within normal distribution
n = mean, s = std
"""
return int(abs(np.ceil(r.normal(n, s)))) | 09abbf79644521253785ff6eb91996cfc13a515d | 72,207 |
def distorted_bounding_box_crop(image,
bbox,
min_object_covered=0.1,
aspect_ratio_range=(0.75, 1.33),
area_range=(0.05, 1.0),
max_attempts=100,
... | ba93d39242508ea0a2d0774618f4aec8011b5f8e | 72,208 |
from typing import Dict
from typing import List
def get_blob_services(credentials: Credentials, subscription_id: str, storage_account: Dict) -> List[Dict]:
"""
Gets the list of blob services.
"""
try:
client = get_client(credentials, subscription_id)
blob_service_list = list(
... | 491b32d3592a31658618ad985cb08f74b243b80f | 72,209 |
def ordering_list(attr, count_from=None, **kw):
"""Prepares an OrderingList factory for use in mapper definitions.
Returns an object suitable for use as an argument to a Mapper relation's
``collection_class`` option. Arguments are:
attr
Name of the mapped attribute to use for storage and retrie... | 3084ce0e336f7a45832b69d58f5f659aa3516fa7 | 72,210 |
import os
import pickle
def _load_scaler_to_memory(path):
""" Load a pickle from disk to memory """
if not os.path.exists(path):
raise ValueError("File " + path + " does not exist")
return pickle.load(open(path, 'rb')) | cbc87a09ce22836ec20f971432d2aa91b584ce6b | 72,211 |
def unscale_daily_temp(mean_temp, scaled_daily_temp, scale_params):
"""scale back the daily temp"""
daily_temp = scaled_daily_temp*\
(scale_params[0] - scale_params[1]*mean_temp) + mean_temp
return daily_temp | bbb66eabbfc929d1a9099a07e31ad1bd606d20e7 | 72,212 |
import math
def transform(img, origin1, origin2, target1, target2):
"""
:param img: image parameter of 4288*2848 image
:param origin1: OD Center of the image being processed, 2d array like [1260.60227367 826.91868854]
:param origin2: Fovea Center of the image being processed, 2d array
:param tar... | 1f4613fc37625a87dd26c690ece7857da9efdb38 | 72,213 |
from typing import Union
def BM2(x: Union[float, np.ndarray]) -> Union[float, np.ndarray]:
"""
J. Wojdyła, Z. Szkutnik, "Nonparamteric confidence bands in Wicksell's problem", Statistica Sinica28(2018), 93-113
"""
return 0.45 * 111384 * (1 - x) ** 12 * x ** 5 + 0.55 * 2558160 * (1 - x) ** 7 * x ** 14 | ccfa52952042be1bb8f58354e1051ea3663be140 | 72,214 |
from typing import List
def xlsx_export(features: List[LayerResponse]):
"""
packages features into an excel workbook. Returns an HTTP response object that has the saved workbook
ready to be returned to the client (e.g. the calling http handler can return this object directly)
"""
wb = openpyxl.W... | 75020b4cc71bfaae3c5cdc9613dbf73e1fc1c9ed | 72,215 |
def _partial_dependence_num(vals, df, model, feature_column, assembler, model_type, n_samples):
"""Compute PD values for numerical feature"""
vals_df = spark.createDataFrame(list(map(lambda x: (float(x),), vals)),
schema=StructType([StructField(feature_column, DoubleType())])... | f76c75c1520db0317a963d3d6b7dd719a5b132b6 | 72,216 |
def str2date(datestring):
"""Converts a string in the format YYYY-MM-DD into a date object."""
return date(*strptime(datestring, '%Y-%m-%d')[0:3]) | 58756011b4e21a699c914cd8b2f22fca2a94c157 | 72,217 |
def transform_args(dflt_trans_func=None, /, **trans_func_for_arg):
"""
Make a decorator that transforms function arguments before calling the function.
Works with plain functions and bounded methods.
For example:
* original argument: a relative path --> used argument: a full path
* origi... | 31303a902565ea8beae86e9ea6145c07b4af730a | 72,218 |
def api_get_project_webhook_token(repo, username=None, namespace=None):
"""
Get project webhook token
-------------------------
Allow project collaborators to retrieve the project webhook token.
::
GET /api/0/<repo>/webhook/token
GET /api/0/<namespace>/<repo>/webhook/token
::
... | 4d1749c3171186120d76766fdf0417b24cf904e6 | 72,219 |
from typing import Union
import torch
def clip_encoder(
device: Union[torch.device, str] = None, name: str = "clip",
) -> nn.Module:
"""
Loads clip's image encoder module, discarding the lm component.
If the variant is a resnet model, we also remove the attention pooling.
"""
if name in ["cli... | 34e0f91d21382adeb220240b7e5a2052fdd44010 | 72,220 |
import os
def find_file(name, path):
"""File the first file within a given path.
Args:
name: Name of the file to search for.
path: Root of the path to search in.
Returns:
Full path of the given filename or None if not found.
"""
for root, dirs, files in os.walk(path):
if name in files:
... | 608727432f16725f4e334170e1412804175dacf3 | 72,221 |
def entitieses(draw, min_size=None, max_size=None, min_to_discard=None,
max_to_discard=None):
"""
An Entities object consisting only of EmptyMention objects with different
ids.
To generate more interesting scenarios, a number of Entity objects are
discarded immediately after creatio... | f8d76e3330bdccbdb81b35b26543c300a3283333 | 72,222 |
def div_roundup(a, b):
""" Return a/b rounded up to nearest integer,
equivalent result to int(math.ceil(float(int(a)) / float(int(b))), only
without possible floating point accuracy errors.
"""
return (int(a) + int(b) - 1) / int(b) | 7fa4d18f1fb54d7641906d38f9e6ced0a88394ac | 72,223 |
from pathlib import Path
def readlines_(file, remove_blank_lines=False):
"""Reading txt file (similar to builtin ``readlines``).
In addition to the standard implementation of ``readlines`` for
``_io.TextIOWrapper``, this version provides the possibility to remove
empty text lines.
Args:
... | 793add397510b52e655449d4d4e0fad7138c9358 | 72,224 |
def find_data_dims(ndvar, dims, extra_dim=None):
"""Find dimensions in data.
Raise a ValueError if the dimensions don't match, except when the ``case``
dimension is omitted in ``dims``.
Parameters
----------
ndvar : NDVar
NDVar instance to query.
dims : int | tuple of str
T... | 20142305a39ca7308867f6a83598af24ae42480a | 72,225 |
def build_model():
"""
Builds sequential model for repetitive calls
:return: model
"""
model = models.Sequential()
model.add(layers.Dense(64, activation="relu", input_shape=(train_data.shape[1],)))
model.add(layers.Dense(64, activation="relu"))
model.add(layers.Dense(1))
model.compi... | 22e8e7e9074b3b56bc73f2eaa91b0ced5f79a5ca | 72,226 |
def get_connection(retry=False):
"""
Retrieve the connection to the configured database. Makes a connection
if none already exists.
Returns:
(Connection): Database connection
"""
global context
if "db" not in context:
context.db = make_connection(retry)
return context.d... | 3ca477f48b4ae9b8faee78e6105a3a81fdcc3841 | 72,227 |
import re
def case_preserving_replace(string, old, new):
"""Replace string while preserving the case"""
def repl(match):
current = match.group()
result = ""
all_upper = True
for i, c in enumerate(current):
if i >= len(new):
break
if c.is... | bfa051c7bfb4a54241e5e10cfb37d4293babad5c | 72,228 |
from typing import Dict
from typing import Union
from typing import List
from typing import Tuple
import os
import yaml
import json
def merge_vars(var: Dict[str, Union[str, float, int, bytes]] = None, # noqa: C901
var_files: List[str] = None) -> Tuple[ConfigVars, SecretVars]:
"""
Load configur... | 54e8d82cfea4bea2e7f40735f984e7892bab4a6b | 72,229 |
def addProjectToDatabase( projectData ):
"""Adds the project to the database
Input is a dict containing: projectName, projectMISOID, projectPROID, owner,description
"""
#print "Adding project %s to the database." % projectData["projectName"]
try:
thisProject, created = Project.objec... | 289bb246ee53a2eaf338ef04f650f4c936199836 | 72,230 |
def train_input_fn(filepath, example_parser, batch_size, num_epochs, shuffle_buffer_size):
"""
deepfm模型的input_fn
Args:
filepath (str): 训练集/验证集的路径
example_parser (function): 解析example的函数
batch_size (int): 每个batch样本大小
num_epochs (int): 训练轮数
shuffle_buffer_size (inr)... | a920af891d05bb5d41a950086ff33bf0e1d29c32 | 72,231 |
def calculate_partners(data):
"""
Function to parse data, and geather all result
:param data: input data in json format
:return result: all result according to all countries
"""
countries = set()
for partner in data["partners"]:
countries.add(partner["country"])
""... | c7dfdc6d5e87f776132df91a7f00529eb126bafe | 72,232 |
def get_result_error_from_openmc_sp(filename, m):
"""
Convert the openmc flux into result, rel_err, res_tot, rel_err_tot.
Parameters:
-----------
filename : str
The OpenMC state point file name.
m : MeshTally
MeshTally for the tally.
Returns:
--------
result : numpy... | 6659b1b66c82c80ae2fff1f26f387384da2f4c40 | 72,233 |
def ball_shape(img, min_radius=30, max_radius=50):
""" This function requires images in an array and returns the coordinates
of centre and radius of the circle detected. It is used to calculate (Cx,Cy)
and radius r of the metal ball used for light calibration. It uses Hough
Transform to detect the circl... | 71975e89613033929d1ac4408ecc76834398ebcd | 72,234 |
def _magnitude_to_marker_size(v_mag):
"""Calculate the size of a matplotlib plot marker representing an object with
a given visual megnitude.
A third-degree polynomial was fit to a few hand-curated examples of
marker sizes for magnitudes, as follows:
>>> x = np.array([-1.44, -0.5, 0., 1., 2., 3., ... | cb030993c5799da9f84e9bbadb9fe30680d74944 | 72,235 |
import scipy
def train_model(X, y, X_valid, config):
"""
train_model uses the following config keys:
- learner
- use_bbsc
- undersample_to_proportion
"""
if config.undersample_to_proportion:
undersample_to_proportion = config.undersample_to_proportion
pos_count = np.sum(... | 72da26730b470d1d2a2b256261f73de281c47d90 | 72,236 |
def matmul_AT_B(a, b):
"""
Computes A.T * B, dealing automatically with sparsity and data modes.
:param a: Tensor or SparseTensor with rank 2 or 3.
:param b: Tensor or SparseTensor with rank 2 or 3.
:return: Tensor or SparseTensor with rank = max(rank(a), rank(b)).
"""
mode = modes.autodetec... | bb63ab1030f31bd542f5e99480f71ac1a166b297 | 72,237 |
def upto(limit: str, text: str) -> str:
""" return all the text up to the limit string """
return text[0 : text.find(limit)] | 0fbe1732954c225fe8d8714badb9126c8ab72a4d | 72,238 |
import torch
def generate_part_labels(
vertices, faces, cam_t, neural_renderer, part_texture, K, R, part_bins
):
"""
:param vertices: (torch tensor NVx3) mesh vertices
:param faces: (torch tensor NFx3) mesh faces
:param cam_t: (Nx3) camera translation
:param neural_renderer: renderer
:para... | 189adf5939bab026c197c84ac07bf8272abc5ca9 | 72,239 |
def check_occuring_variables(formula,variables_to_consider,allowed_variables) :
"""
Checks if the intersection of the variables in <formula> with the variables
in <variables_to_consider> is contained in <allowed_variables>
Parameters
----------
formula : list of list of integers
The formula to cons... | 16faf544cc6f4993afb1cad356037820d54225ba | 72,240 |
def tableau(y):
"""Yamanouchi word --> Young tableau"""
elist = [j+1 for _, j in sorted(list(zip(y, range(len(y)))))]
tbl = np.array(elist).reshape(max(y), len(y)//max(y))
return tbl | 1bc649e0ebe6062ca66f764f3be5c54e9b04c5e3 | 72,241 |
import warnings
def make_figure(width, height, nrows, ncols, interactive=None, **kwargs):
"""
Make a :class:`matplotlib.figure.Figure` and its axes.
:param width: Width of the figure.
:type width: int
:param height: Height of the figure.
:type height: int
:param interactive: If ``True``... | 0a4e99b695f16701ca7a8b3de08d28ee88c4119e | 72,242 |
def calculate_loss_logistic_regression(y, tx, w):
"""compute the cost by negative log likelihood."""
# Note: this function takes y with values either 0 or 1
return - np.squeeze((y.T @ np.log(sigmoid(tx @ w)) + (1 - y).T @ np.log(1 - sigmoid(tx @ w)))) | bb24ca552c16ab997ee9e107678b4ec05edffa86 | 72,243 |
from typing import Tuple
def _make_ui_window(
window: console_config.WindowType,
switchboard_inst: switchboard_base.SwitchboardBase
) -> Tuple[widgets.TextArea, widgets.Frame]:
"""Creates a text area and an enclosing frame.
Args:
window: Console window description.
switchboard_inst: Switchboard c... | 6546274ce28c1e4ef05d24018615cfc10bf83ac8 | 72,244 |
import os
import tarfile
def directory_tarball(dirname):
"""Create a tarball of a complex directory, avoiding complex secondaryFiles.
Complex secondary files do not work on multiple platforms and are not portable
to WDL, so for now we create a tarball that workers will unpack.
"""
assert os.path.... | 0d39276ca940ab793288fe278d7364cff11d7fb1 | 72,245 |
def mvn_rvs(mean, cov):
"""
Function to sample from multiple Gaussian distributions
Parameters
----------
mean : numpy.array
N_samples x N_dim
cov : numpy.array or list
(N_samples x N_dim x N_dim) or list[numpy.array(N_dim x N_dim)]
return : numpy.array
N_samples x N_... | e3bb8cb8fad7a4a30b69eaf41267c758f68cbe19 | 72,246 |
def DynFlow(con, tau, sigma, tmax=20, timestep=0.1, normed=True):
"""Returns the extrinsinc flow on a network over time for a given input.
Parameters
----------
con : ndarray of rank-2
The adjacency matrix of the network.
tau : real valued number, or ndarray of rank-1
The decay rate... | 4ea117c0f3a427fc86ca332589785e93a9e5d90f | 72,247 |
import pathlib
def _fspath(path):
"""Return the path representation of a path-like object.
If str or bytes is passed in, it is returned unchanged. Otherwise the
os.PathLike interface is used to get the path representation. If the
path representation is not str or bytes, TypeError is raised. If the
... | 39b0841ce68f698b7952eb457ac407a7fa3261e9 | 72,248 |
def generate_dataset(num_of_samples, num_of_class):
"""
The function generated a linearly separated 2D Dataset with two classes.
num_of_samples: number of samples in each classes
mean: Mean values for the distribution
cov: Covariable for the normal distribution
Functions used:
np.random... | 170fa27ee441f91d1208473ac3f2808fed5e594d | 72,249 |
import logging
import tqdm
def get_responses(responses_file: str, histories: pd.DataFrame) -> pd.DataFrame:
"""
:param responses_file: The original survey CSV file (as exported by Typeform)
see https://kite.quip.com/DgfvAoP0WOma/Windows-User-Survey
:param histories: DataFrame for the users' histor... | cc82afbc4b45216800ffc2db450e402f22c46068 | 72,250 |
def generate_metadata(bwt, ranks=None, counts=None, alphabet=None):
"""Return ranks, counts and alphabet given or deduced from given bwt"""
if alphabet is None:
alphabet = tuple(sorted(tuple(set(bwt))))
if ranks is None or counts is None:
*ranks, counts = tuple(generate_ranks(bwt))
# pri... | abf6322ec7e5bbf68c835d552a71b7359fac5509 | 72,251 |
import torch
def SOS_KNN_MOD_HOR(xa, xp, knn):
"""
Second Order Similarity KNN Modified Horizontal
:param xa: x anchor, nxd
:param xp: x positive, nxd
:param knn: int, like: 8
:return:
"""
if xa.shape[0] <= knn:
raise EmptyTensorError
assert xa.shape[0] == xp.shape[0]
n... | 3e23c3d7a8eccb3a278d095fabd110f11f2cf2e8 | 72,252 |
def classproperty(f):
"""decorator that registers a function as a read-only property of the class."""
class _ClassProperty:
def __get__(self, _, cls):
# python will call the __get__ magic function whenever the property is
# read from the class.
return f(cls)
return _ClassProperty() | de5586548b77e8c1c72176690b64df603edacf78 | 72,253 |
import time
def execute_search(
search: Search,
*,
search_terms: str = "",
user: AbstractBaseUser | None = None,
reference: str | None = "",
save: bool = True,
) -> SearchQuery:
"""
Create a new SearchQuery instance and execute a search against ES.
Args:
search: elasticsea... | 2a00a73ee74b6703e89676cecf18601dd87d59e7 | 72,254 |
import json
def prepare(dp: frictionless.package.Package, name: str):
"""
Prepare data in EnerMaps format.
Parameters
----------
dp : frictionless.package.Package
Valid datapackage
name : str
Name of the dataset (used for constructing the FID)
Returns
-------
Dat... | b34e992de80d48daafb373bd6e300be2c28b6ffb | 72,255 |
def _merge_config_dicts(dct1, dct2):
"""
Return new dict created by merging two dicts, giving dct1 priority over
dct2, but giving truthy values in dct2 priority over falsey values in dct1.
"""
return {str(key): dct1.get(key) or dct2.get(key)
for key in set(dct1) | set(dct2)} | 9d66c10438027254fbac7d8cc91185a07dd9da65 | 72,256 |
def streetgenerator(specs, CELLSIZE, grid, skipx, skipy):
"""Generate a road network. Input: size of each cell for buildings,
size of the grid, the number of streets to skip in each direction
(so not every building is bounded by four streets, looks to dense)."""
width = 5.0
separation = 1.0
ro... | e7db683433fdc441147a350020ff07daf480de19 | 72,257 |
def beatiful_font(text):
"""
Função que estiliza certas partes de um texto, de acordo com as cores e estilos
definidos pelo programador
"""
father = []
ansi = []
scala = -1
for word in text.split(">"):
start = word.find("<") + 1
color = word[start:]
tag = ""
... | 30de00ea57ec2981b898a17fac637e8545f3b7ad | 72,258 |
def is_number(number):
"""
Returns true if number is a valid number value
False otherwise
"""
try:
float(number)
return True
except (ValueError, TypeError):
return False | f5b67ba24bc30611153612f1ba73a376f533485d | 72,259 |
import subprocess
import sys
def run_adb_shell(shell_args, device_serial):
"""Runs "adb shell" with the given arguments.
Args:
shell_args: array of arguments to pass to adb shell.
device_serial: if not empty, will add the appropriate command-line
parameters so that adb targets the given device.
... | 1f481b6a65cdd458253fb35ec6b024a0a0d925f9 | 72,260 |
import warnings
def check_duplicate_cfs(data, biosphere):
"""Check that multiple substances in input data are not matched to same ecoinvent flow"""
bd = {obj.key: obj for obj in biosphere}
for ds in data:
seen = {}
for cf in ds["exchanges"]:
if not cf.get("input"):
... | 2afcd35df8d6fd891ce83988d9fcb32c72edb11d | 72,261 |
def from_list(*args):
"""
Input:
args - variable number of integers represented as lists, e.g. from_list([1,0,2], [5])
Output:
new_lst - a Python array of integers represented as strings, e.g. ['102','5']
"""
new_lst = []
for lst in args:
new_string = ''
for digi... | c3c0a2224433104a00ffabdadf612127d1b0ed3c | 72,262 |
def conv2d(x, W, b, strides=1):
"""
Add a convolution layer using ReLu as the activation function.
Args:
x: input data
W: weights
b: bias
strides: stride size (assume square stride)
Returns:
A TensorFlow convolution layer.
"""
x = tf.nn.conv2d(x, W, stri... | 30004142f9eee93d573e64cab4d0bb4a8ecbc21f | 72,263 |
async def canSend():
"""
Returns True if a command can be sent
"""
return not commandSent | 9cb1de5cf9d905b41a760133f42e749bb307ea17 | 72,264 |
def ROI(loc, dim, center=False):
"""
Slicing operator for extracting a region of interest (ROI) from a 2D array.
Eg: Accumulate src into dst at (10, 10)
dst = np.zeors(HW(100, 100))
src = np.zeors(HW(50, 50))
roi = ROI(YX(10, 10), HW(src.shape))
dst[roi] += src
"""
lo... | b21900ab74f069a06ada037b333cc487551de309 | 72,265 |
def compute_homography(src, dst):
"""computes the homography from src, to dst using inversion method."""
if src.shape[1] == 2 :
p1 = np.ones((len(src),3),'float64')
p1[:,:2] = src
elif src.shape[1] == 3 : p1 = src
if dst.shape[1] == 2 :
p2 = np.ones((len(dst),3),'... | 622da34e9a99590155582a79764fd1014a48e097 | 72,266 |
def make_embed(title, description, idx, pages):
"""Make an embed with page number footer."""
e = discord.Embed(title=title, description=description)
e.set_footer(text="Page {} of {}".format(
idx + 1, pages))
return e | 4cd6b35a020f86991739b19e0930dbe9b83142d5 | 72,267 |
def interp_shifts(coords, shifts, n=None):
"""
Interpolate shifts for all frames not in coords and create dask array
Parameters
----------
coords : (N,)
coordinates for shifts
shifts : (d, N)
list of arrays to be interpolated
n : int or None, defaults=None
final leng... | 63a4b7a79620124a390f700c8ed7479c3edc0827 | 72,268 |
import numpy
def lip2dens(
perc_lipid, dens_lipid=0.9007, dens_prot=1.34, dens_water=0.994, dens_ash=2.3
):
"""Derive tissue density from lipids
The equation calculating animal density is from Biuw et al. (2003), and
default values for component densities are from human studies collected in
the b... | f64796816713196bef104536aa88ec2de54a2b21 | 72,269 |
def get_currentID(isamAppliance, check_mode=False, force=False):
"""
Retrieve the current point of contact profile information
"""
return isamAppliance.invoke_get("Retrieve the current point of contact profile information", uri,
requires_modules=requires_modules,
... | 0269edba2692157e9fbae059ee796903c9ac566b | 72,270 |
from datetime import datetime
def create_article_id(created=None):
"""根据created参数,创建一个数字id,有可能重复,需要自己判断下"""
if not created:
created = datetime.now()
# 计算与2013-2-10相差天数
# print(created,type(created))
date_now = created.date()
date_start = date(2013, 2, 10)
days = (date_now - date_s... | 3a5535ce5d162170de972cb138658d62a5246df5 | 72,271 |
def random_crop(input_image, target_image):
"""Crop random matching portion from image and target.
Args:
input_image (tf.Tensor, dtype 'uint8', dimensions m x n x 3): Tensor
(photo) to be cropped.
target_image (tf.Tensor, dtype 'uint8', dimensions m x n x 3): Tensor
(lin... | 29a45079ce65774abd2d8fc13524f385d3381cf3 | 72,272 |
def attribute(sxpr, key, val=None):
"""Get an attribute of an sxpr.
sxpr sxpr
key attribute key
val default value (default None)
returns attribute value
"""
for x in attributes(sxpr):
if x[0] == key:
val = x[1]
break
return val | 2474e499df87a5d0c4d327a118b66d0de450abe9 | 72,273 |
def serial_corr(wave, lag=1):
"""Computes serial correlation with given lag.
wave: Wave
lag: integer, how much to shift the wave
returns: float correlation coefficient
"""
n = len(wave)
y1 = wave.ys[lag:]
y2 = wave.ys[:n-lag]
corr = corrcoef(y1, y2)
return corr | 30c49e0e2dbe49b1fbe60831966c895458d19a94 | 72,274 |
import pynvml
def mem_utilization_for(device_handle):
"""
Percent of time over the past sample period during which global (device) memory was being read or written.
"""
try:
return pynvml.nvmlDeviceGetUtilizationRates(device_handle).memory
except pynvml.NVMLError:
return None | 60f688439b991c51fb7556abf6990003d8995035 | 72,275 |
from typing import Optional
def find_short_phrase(head_word: Token, uses_exact_spacy_noun_chunk: bool = False) -> Optional[Span]:
"""This is based on scanning for a limit set of dependency edges.
This is essentially motivated by StuffIE's original algorithm,
but also relies on the `noun_chunks` function o... | dcfc90f5c133e33200b6fae7a00f73b224739f86 | 72,276 |
def jewish_dusk(date, location):
"""Return standard time of Jewish dusk on fixed date, date,
at location, location, (as per Vilna Gaon)."""
return dusk(date, location, angle(4, 40, 0)) | 2dc2c558f229cbca2970842c99932c3e0bf31f1e | 72,277 |
def perpetuity_present_value(
continuous_cash_payment: float,
interest_rate: float,
):
"""Returns the Present Value of Perpetuity Formula.
Parameters
----------
continuous_cash_payment : float
Amount of continuous cash payment.
interest_rate : float
Interest rate, yield or discount r... | 26eb398776ce4f74348b23920b99b0390c462ff9 | 72,278 |
def evaluate_deltas(e):
"""
We evaluate KroneckerDelta symbols in the expression assuming Einstein summation.
If one index is repeated it is summed over and in effect substituted with
the other one. If both indices are repeated we substitute according to what
is the preferred index. this is determ... | e031f0cba12e0989c7b78da8517ec907c84221ac | 72,279 |
def stfm(val,err):
"""
Create standard form string from value and uncertainty"
str = stfm(val,err)
Examples:
'35.25 (1)' = stfm(35.25,0.01)
'110 (5)' = stfm(110.25,5)
'0.0015300 (5)' = stfm(0.00153,0.0000005)
'1.56(2)E+6' = stfm(1.5632e6,1.53e4)
Notes:
... | f7ac3e55a8e4d701fa6a77bf07418ce0fd619b9c | 72,280 |
from typing import Dict
from typing import List
from typing import Tuple
import sys
def rag_dataset_pattern_extractor(pattern_length=8) -> Dict[int, List[Tuple[int, str]]]:
""" Gets the rag dataset onset patterns with their occurrence proportion.
The patterns returned correspond to every measure of all the s... | 837cea7cbf32307f7da39e4297c23c05b56e2af6 | 72,281 |
def plot_pca_cum_feature_contrib_3pc(
df_pca_feature_contrib: pd.DataFrame,
) -> plt.Figure:
"""Plot the cumulated feature contribution to each Principal Component Combination
individually (up to 3 different PCs).
Parameters:
===========
df_pca_feature_contrib: a DataFrame with the feature contr... | f2e60a38fb8dfe287989e8c308c69a732d50e943 | 72,282 |
import json
def delete_observers(request):
"""view is responsible for removing the room from observed"""
if request.method == 'POST' and request.is_ajax:
data = json.loads(request.body)
user = request.user
room = user.observed_rooms.filter(id=int(data['id']))
if room.count() !=... | 2111a0ce85db98ac4ee5c8c40526bd11069e85ee | 72,283 |
import subprocess
def _has_broken_dash_S(executable):
"""Detect https://bugs.launchpad.net/virtualenv/+bug/572545 ."""
# The first attempt here was to simply have the executable attempt to import
# ConfigParser and return the return code. That worked except for tests on
# Windows, where the return cod... | b7fa69b00337bbd44647f8e0bd7a48bc5d811977 | 72,284 |
def rComp(sequence):
"""Reverse complements a sequence, preserving case."""
d={'A':'T','T':'A','C':'G','G':'C','a':'t','t':'a','c':'g','g':'c','N':'N','n':'n'}
cSeq=''
for s in sequence:
cSeq+=d[s]
cSeq=cSeq[::-1]
return cSeq | 3794166fce44147917993d9963775c2a1c70dbd7 | 72,285 |
def fatorial(valor,show=False):
""" -> Calcula valor Fatorial de n
Param valor: recebe valor para calculo de fatorial
Param show: (OPCIONAL) mostra como o calculo foi realizado
return: retorna o resultado do fatorial de n
"""
fat = 1
if show == True:
#print(fat,end=' x ')... | e0dacf6102cc38c019f122dd51d25f591c1b047d | 72,286 |
def revert_patchset(request):
"""/api/<issue>/<patchset>/revert_patchset - Create an inverted changeset."""
if request.method != 'POST':
return HttpTextResponse(
'/revert_issue only supports POST.', status=403)
# Find the patches of the issue we want to revert.
original_issue = request.issue
ori... | 904a4af0aed1a5ae805b7f6e1319f2a2a195dd01 | 72,287 |
def create_example_data(design_values, missing_data_proportion=0, save_array_path=None, seed=False):
"""
Create a Pandas DataFrame of random data with a certain number of columns which
correspond to a design of a given shape (e.g., 1-way, two groups, 2-way design).
There is also an option to randomly a... | f647607790ffbaf3996c97df1a211773a3e761be | 72,288 |
from typing import List
from typing import Union
def get_input(
inputs: List[cwl.CommandInputParameter],
unbound_input: List[str],
bound_input: List[str],
) -> List[cwl.CommandInputParameter]:
"""Get bound and unbound inputs."""
for i in unbound_input:
input_name = i[1]
if "Array... | 19db772e24e47c845066f8e95fb3fbbe92c479b7 | 72,289 |
from functools import reduce
def pairwise_precision_recall_fscore(true_clus, pred_clus, test_block, strategy="cmacro"):
"""
Compute the Pairwise precision, recall and F-score.
Parameters
----------
true_clusters: Dict
dictionary with cluster id as keys and
1d array containing the ... | 4d765b6de936153c0b4f6788b2005360711d5546 | 72,290 |
def _truncate_seq_quadruplet(tokens_a, tokens_b, tokens_c, tokens_d, max_length):
"""
Truncates a sequence triplet in place to the maximum length
:param tokens_a:
:param tokens_b:
:param tokens_c:
:param tokens_d:
:param max_length:
:return:
"""
# This is a simple heuristic whic... | b9d560962d2db17d60a1648eeba326b00842c643 | 72,291 |
from datetime import datetime
def get_puffer_daily_series(dt=datetime.utcnow()):
"""
Returns the puffer data for the specified day. By default the data for today
is returned.
"""
start_date = get_start_of_day_in_utc_time(dt)
end_date = start_date + timedelta(days=1)
return Puffer.query.wit... | b2ee4ebb8f6e1199e84355ac8fdae3b6de123830 | 72,292 |
def aggregate_channels(recording_list, renamed_channel_ids=None):
"""
Aggregates channels of multiple recording into a single recording object
Parameters
----------
recording_list: list
List of BaseRecording objects to aggregate
renamed_channel_ids: array-like
If given, channel ... | f48033dc66c608a37aaf1aeb3eab672dfe1c997d | 72,293 |
def __avg__(list_):
"""Return average of all elements in the list."""
return sum(list_) / len(list_) | 3204d823e83bd43efccf9886acd3ae8b01e1d7a0 | 72,294 |
import math
def atand(v):
"""Return the arc tangent (measured in in degrees) of x."""
return math.degrees(math.atan(v)) | cc25806e7333e887f5f4cc376ec7c1f2100043fa | 72,295 |
def convert(config):
"""
Converts config to xml
@ In, config, ConfigParser, old dependencies
@ Out, xml, ET.Element, converted xml
"""
xml = ET.Element('dependencies')
addCore(config, xml)
addForge(config, xml)
addPip(config, xml)
addOptional(config, xml)
addWindows(config, xml)
addMac(c... | a6c6a3763166db87d4a7b5edd9068497523b5dad | 72,296 |
import os
import pickle
def load_file(path):
"""
Load a file
:param path: File path
:return: file
"""
fn = os.path.join(os.path.dirname(__file__), path)
return pickle.load(open(fn, 'rb')) | aa0b6e44466faf37eca38c8f55a81ac35e48c623 | 72,297 |
from typing import Optional
from typing import Union
from typing import Callable
from typing import List
def radial_proj(img: np.ndarray, x0: Optional[float] = None, y0: Optional[float] = None,
scale: float = 1, scale_axis: float = 0,
my_func: Union[Callable[[np.ndarray], np.ndarray], List[Callab... | 855d144f1975f2482ac993894735c408d83fffba | 72,298 |
import os
def download(s3, file_name, bucket, object_name):
"""Download a file from an S3 bucket
:param file_name: File to download
:param bucket: Bucket to download from
:param object_name: S3 object name.
:return: path to the downloaded photo
"""
filename_full = ""
if object_name ... | 2dd325f6b1548bf702f28b88a6d55dce45ae4c93 | 72,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.