content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import json
def app_durations():
"""Generate JavaScript for appDurations."""
return 'appDurations = ' + json.dumps(supported_durations) | 3be9ecc801cd650a5cd1a3c4db1c50957ccfa1c0 | 3,648,229 |
def generic_cc(mag=10,dmag=8,band='K'):
"""Returns a generic contrast curve.
Keyword arguments:
mag -- magnitude of target star in passband
dmag -- can currently be either 8 or 4.5 (two example generic cc's being used)
band -- passband of observation.
"""
if dmag==8:
return fpp.Con... | 04ca148c2a5b8d9eb2d0c60a0d6ad8e177901c5f | 3,648,230 |
from typing import Any
def read_routes(*, db: Session = Depends(deps.get_db),data_in: schemas.DictDataCreate,current_user: models.User = Depends(deps.get_current_active_user)) -> Any:
"""
Retrieve Mock Data.
"""
db.add(models.Dict_Data(**jsonable_encoder(data_in)))
return {
"code": 20000,
... | 09e575a8262a0818c7904e4e077d86f492f3407e | 3,648,231 |
def get_companies_pagination_from_lagou(city_id=0, finance_stage_id=0, industry_id=0, page_no=1):
"""
爬取拉勾公司分页数据
:param city_id: 城市 id
:param finance_stage_id: 融资阶段 id
:param industry_id: 行业 id
:param page_no: 页码
:return: 拉勾公司分页数据
:rtype: utils.pagination.Pagination
"""
url = co... | 7a82e0dd7ad8ab960dbabb749e68867607b70878 | 3,648,232 |
def is_quant_contam(contam_model):
"""Get the flag for quantitative contamination"""
# the list of quantitative models
quant_models = ['GAUSS', 'FLUXCUBE']
# set the default value
isquantcont = True
# check whether the contamination is not quantitative
if not contam_model.upper() in quant_... | 8a88609857ac8eb61bfddfa8d8227ffa237d2641 | 3,648,233 |
def nms_wrapper(scores, boxes, threshold = 0.7, class_sets = None):
"""
post-process the results of im_detect
:param scores: N * K numpy
:param boxes: N * (K * 4) numpy
:param class_sets: e.g. CLASSES = ('__background__','person','bike','motorbike','car','bus')
:return: a list of K-1 dicts, no b... | 7f6a260811a1c20da40e41cc179488440bfc5164 | 3,648,234 |
def Rbf(
gamma: float = 1.0) -> InternalLayer:
"""Dual activation function for normalized RBF or squared exponential kernel.
Dual activation function is `f(x) = sqrt(2)*sin(sqrt(2*gamma) x + pi/4)`.
NNGP kernel transformation correspond to (with input dimension `d`)
`k = exp(- gamma / d * ||x - x'||^2) = e... | c7c44f6227d0d337da40a1afe8eff359ccaebbf5 | 3,648,235 |
def create_returns_tear_sheet(returns, positions=None,
transactions=None,
live_start_date=None,
cone_std=(1.0, 1.5, 2.0),
benchmark_rets=None,
bootstrap=False,
... | 5d01bb52ed3bd642ed8c7743ee41b4d57f732c2f | 3,648,237 |
def vectorize_text(text_col: pd.Series,
vec_type: str = 'count',
**kwargs):
"""
Vectorizes pre-processed text. Instantiates the vectorizer and
fit_transform it to the data provided.
:param text_col: Pandas series, containing preprocessed text.
:param vec_type: ... | fd1b720c5eee83d788684a49f5fe7ad26e955016 | 3,648,238 |
def creation_LS(X,y,N):
"""Generates a random learning set of size N from the data in X
(containing the input samples) and in y (containing the corresponding
output values).
Parameters
----------
X: array containing the input samples
y: array conta... | fdcf5fe96082a75b096b43747f940b8cf46f326b | 3,648,239 |
def print_summary(show="all",
blocks=False, cid=True, blobs=True, size=True,
typ=False, ch=False, ch_online=True,
name=True, title=False, path=False,
sanitize=False,
start=1, end=0, channel=None, invalid=False,
r... | 6888917bd6a944c6e91c0d9796383b279db68315 | 3,648,240 |
import logging
def load_embeddings(path):
"""
Load embeddings from file and put into dict.
:param path: path to embeddings file
:return: a map word->embedding
"""
logging.info('Loading embeddings...')
embeddings = dict()
with open(path, 'r') as f:
for line in f:
li... | 3e7e05cc9131dfb9d06c4c220d5e13d6965180b7 | 3,648,243 |
def format_component_descriptor(name, version):
"""
Return a properly formatted component 'descriptor' in the format
<name>-<version>
"""
return '{0}-{1}'.format(name, version) | 2edb92f20179ae587614cc3c9ca8198c9a4c240e | 3,648,245 |
import sqlite3
def dbconn():
"""
Initializing db connection
"""
sqlite_db_file = '/tmp/test_qbo.db'
return sqlite3.connect(sqlite_db_file, detect_types=sqlite3.PARSE_DECLTYPES|sqlite3.PARSE_COLNAMES) | b0c6dd235490cee93ada20f060d681a319b120f0 | 3,648,246 |
import hashlib
def md5(fname):
"""
Compute the md5 of a file in chunks.
Avoid running out of memory when hashing large files.
"""
hash_md5 = hashlib.md5()
with open(fname, "rb") as f:
for chunk in iter(lambda: f.read(4096), b""):
hash_md5.update(chunk)
return hash_md5.h... | 9e0bfbd625df6a46d5bff4cd0e9f065d1eaf8a4b | 3,648,247 |
def get_r(x, y, x1, y1):
"""
Get r vector following Xu et al. (2006) Eq. 4.2
x, y = arrays; x1, y1 = single points; or vice-versa
"""
return ((x-x1)**2 + (y-y1)**2)**0.5 | 424408f86e6e3301ee6eca72e2da7da5bf1f8140 | 3,648,248 |
import re
def replace_empty_bracket(tokens):
"""
Remove empty bracket
:param tokens: List of tokens
:return: Fixed sequence
"""
merged = "".join(tokens)
find = re.search(r"\{\}", merged)
while find:
merged = re.sub(r"\{\}", "", merged)
find = re.search(r"\{\}", merged)
... | fd2c9f2f1c2e199056e89dbdba65f92e4d5834eb | 3,648,249 |
def presentation():
"""
This route is the final project and will be test
of all previously learned skills.
"""
return render_template("") | c592ae4b28c5c9b89592c3842e73c0e76cc4bd66 | 3,648,250 |
def extra_credit(grades,students,bonus):
"""
Returns a copy of grades with extra credit assigned
The dictionary returned adds a bonus to the grade of
every student whose netid is in the list students.
Parameter grades: The dictionary of student grades
Precondition: grades has netids as keys, i... | 334a9edb3d1d045832009e20c6cba7f24e5c181d | 3,648,251 |
def get_geo_signal_combos(data_source):
"""
Get list of geo type-signal type combinations that we expect to see.
Cross references based on combinations reported available by COVIDcast metadata.
"""
meta = covidcast.metadata()
source_meta = meta[meta['data_source'] == data_source]
# Need to ... | 90d030372b3e7d9ed2de0d53b6aa42fdf3723355 | 3,648,252 |
def absolute_(x, track_types = True, **kwargs):
"""Compute the absolute value of x.
Parameters
----------
x : :obj:`xarray.DataArray`
Data cube containing the values to apply the operator to.
track_types : :obj:`bool`
Should the operator promote the value type of the output object, based
... | b88c6662890832b0d54f752e59c97c9a9ca9ceb5 | 3,648,253 |
def any_input(sys_, t, input_signal=0, init_cond=None, *, plot=True):
"""
Accept any input signal, then calculate the response of the system.
:param sys_: the system
:type sys_: TransferFunction | StateSpace
:param t: time
:type t: array_like
:param input_signal: input signal accepted by th... | fc6d72b5c22d585a4ba7c5be895b1266e72e70dd | 3,648,254 |
from .mnext import mnext
def mnext_mbv2_cfg(pretrained=False,in_chans=3,drop_rate=0.2,drop_connect_rate=0.5,bn_tf=False,bn_momentum=0.9,bn_eps=0.001, global_pool=False, **kwargs):
"""Creates a MNeXt Large model. Tensorflow compatible variant
"""
model = mnext(**kwargs)
return model | 5f8fcdcaa6abf4047b4fc06ea7dcb92f6fbeade7 | 3,648,256 |
def _embeddings_from_arguments(column,
args,
weight_collections,
trainable,
output_rank=2):
"""Returns embeddings for a column based on the computed arguments.
Args:
column: the column nam... | 30c305bfbf20d48af48dd25aa32c1648f8f95fce | 3,648,257 |
def stuw_laagstedoorstroombreedte(damo_gdf=None, obj=None, damo_doorstroombreedte="DOORSTROOMBREEDTE",
damo_kruinvorm="WS_KRUINVORM"):
"""
als LAAGSTEDOORSTROOMHOOGTE is NULL en WS_KRUINVORM =3 (rechthoek) dan LAAGSTEDOORSTROOMBREEDTE = DOORSTROOMBREEDTE
"""
return damo... | 534d917326222ef77fc0a8022ed84ea08bb0be0a | 3,648,258 |
def manage_categories():
"""
Display all categories to manage categories page (admin only)
"""
# Denied user access to manage_categories page
if session["user"] != "admin":
return redirect(url_for('error', code=403))
# query for all categories from categories collection
manage_categ... | 5002375f904240f2274aa8040b426da8515122a7 | 3,648,259 |
def callback(id):
"""
获取指定记录
"""
# 检查用户权限
_common_logic.check_user_power()
_positions_logic = positions_logic.PositionsLogic()
# 读取记录
result = _positions_logic.get_model_for_cache(id)
if result:
# 直接输出json
return web_helper.return_msg(0, '成功', result)
else:
... | 3451cc1ebb18004f46847f6538c751afd86bdf74 | 3,648,260 |
def sort_cluster(x: list, t: np.ndarray) -> list:
"""
sort x according to t
:param x:
:param t:
:return:
"""
return [x[i] for i in np.argsort(t)] | a2bcd57bb9c402aa19f12483e792f1e4379c4481 | 3,648,262 |
def gettof(*args):
"""gettof(flags_t F) -> ushort"""
return _idaapi.gettof(*args) | d377fc28b7515a45112083fc38c722b82caee0b9 | 3,648,263 |
def generate(temp):
"""
Wrapper that checks generated names against the base street names to avoid a direct
regurgitation of input data.
returns list
"""
is_in_dict = True
while is_in_dict:
result = textgen.generate(temperature=temp, return_as_list=True)
str = ' '.join(result... | 2bfc6d366d0543d6ada762539c0c6cb301d729a8 | 3,648,264 |
import re
def __create_pyramid_features(backbone_dict,
ndim=2,
feature_size=256,
include_final_layers=True,
lite=False,
upsample_type='upsamplelike',
... | 956a04a1ebe14e11061de009894b27e7c2640cb2 | 3,648,265 |
def graphviz(self, filename=None, directory=None, isEdge=False,showLabel=True, **kwargs):
"""Return graphviz source for visualizing the lattice graph."""
return lattice(self, filename, directory, isEdge, showLabel, **kwargs) | 1c7426efe0f0379822c4c9c0a765a615f26f04a1 | 3,648,266 |
def get_rectangle(origin, end):
"""Return all points of rectangle contained by origin and end."""
size_x = abs(origin[0]-end[0])+1
size_y = abs(origin[1]-end[1])+1
rectangle = []
for x in range(size_x):
for y in range(size_y):
rectangle.append((origin[0]+x, origin[1]+y))
retu... | 36badfd8aefaaeda806215b02ed6e92fce6509a3 | 3,648,267 |
def corr_list(df, target, thresh=0.1, sort=True, fill=True):
"""
List Most Correlated Features
Returns a pandas Series with the most correlated features to a certain
target variable. The function will return features with a correlation value
bigger than some threshold, which can be adjusted.
P... | d9562d1bbc7947338cf87ddc6703ef54a21554e0 | 3,648,268 |
def compute_epsilon(steps):
"""Computes epsilon value for given hyperparameters."""
if FLAGS.noise_multiplier == 0.0:
return float('inf')
orders = [1 + x / 10. for x in range(1, 100)] + list(range(12, 64))
sampling_probability = FLAGS.batch_size / NUM_TRAIN_EXAMPLES
rdp = compute_rdp(q=sampling_probabilit... | 9819cafafeec66cd29b13a916432c839e4365ded | 3,648,269 |
def get_native_includes(object):
"""
After method association, check which native types an object uses
and return a corresponding string list of include file
This will also add the include needed for inheritance
"""
includes = set()
for proc in object.procs:
for argname,arg in proc.... | 0c09d39bd61b5a711bd718dcb38fab7e4e1e01bf | 3,648,270 |
import torch
def dice_coeff(input, target):
"""Dice coeff for batches"""
if input.is_cuda:
s = torch.FloatTensor(1).to(device_f).zero_()
else:
s = torch.FloatTensor(1).zero_()
for i, c in enumerate(zip(input, target)):
s = s + DiceCoeff().forward(c[0], c[1])
return s / (i... | da390729d2e1d8e2ae53814f8ac398a6c7e5380a | 3,648,272 |
def group_error_rates(labels, predictions, groups):
"""Returns a list containing error rates for each protected group."""
errors = []
for jj in range(groups.shape[1]):
if groups[:, jj].sum() == 0: # Group is empty?
errors.append(0.0)
else:
signed_labels_jj = 2 * labels[groups[:, jj] == 1] - 1... | 0b390dfde16910332f10afacaa2f9031c04d846a | 3,648,273 |
def get_emails_by_user_names(user_names):
"""Get emails by user names."""
emails_service = emails_digest_service.DailyEmailsService()
emails_service.open_emails_digest()
user_emails_dict = dict.fromkeys(user_names)
for user_name in user_names:
user_emails_dict[user_name] = emails_service.get_email_by_user... | 331d5799bac79c08240770260306ba84bf2f568b | 3,648,274 |
def inbound_and_outbound_node_sets(C, CT):
"""
Returns the set of nodes that can reach an event and can be reached by an event,
and the difference between those sets (outbound / inbound).
"""
inbound = defaultdict(set)
for node, event in zip(*np.nonzero(C)):
inbound[event].add(node)
outbound = defaultdic... | 517746700a7a978a49a597237db362eee98d91b6 | 3,648,275 |
def policy(Q):
"""Hard max over prescriptions
Params:
-------
* Q: dictionary of dictionaries
Nested dictionary representing a table
Returns:
-------
* policy: dictonary of states to policies
"""
pol = {}
for s in Q:
pol[s] = max(Q[s].items(), key=lambda... | e69f66fba94b025034e03428a5e93ba1b95918e8 | 3,648,276 |
def fft(series):
"""
FFT of a series
Parameters
----------
series
Returns
-------
"""
signal = series.values
time = series.index
dt = np.mean(np.diff(time))
#n = 11*len(time)
n = 50000
frequencies = np.fft.rfftfreq(n=n, d=dt) # [Hz]
dft = np.abs(np.fft.rf... | a6d1f7cfa45d504a86b434702a49eafa08737006 | 3,648,277 |
def local_variance(V, tsize=5):
""" local non-linear variance calculation
Parameters
----------
V : numpy.array, size=(m,n), dtype=float
array with one velocity component, all algorithms are indepent of their
axis.
Parameters
----------
sig_V : numpy.array, size=(m,n), dtyp... | e7e10f8c73f01b20a27ad06813defdd406bf977a | 3,648,278 |
def get_virtual_device_configuration(device):
"""Get the virtual device configuration for a PhysicalDevice.
Returns the list of VirtualDeviceConfiguration objects previously configured
by a call to `tf.config.experimental.set_virtual_device_configuration()`.
For example:
>>> physical_devices = tf.config.ex... | 49a99c17c2859bb40a7bfbbac840bf82310428e1 | 3,648,279 |
def user_directory_path(instance, filename):
"""Sets path to user uploads to: MEDIA_ROOT/user_<id>/<filename>"""
return f"user_{instance.user.id}/{filename}" | 84be5fe74fa5059c023d746b2a0ff6e32c14c10d | 3,648,280 |
def setup(app):
"""Setup the Sphinx extension."""
# Register builder.
app.add_builder(BeamerBuilder)
# Add setting for allowframebreaks.
app.add_config_value("beamer_allowframebreaks", True, "beamer")
# Add setting for Beamer theme.
app.add_config_value("beamer_theme", "Warsaw", "beamer")
... | cc5f48eeff65876a2d052dad285a77bc76e115c0 | 3,648,281 |
def extract_text(arg: Message_T) -> str:
"""
提取消息中的纯文本部分(使用空格合并纯文本消息段)。
参数:
arg (nonebot.typing.Message_T):
"""
arg_as_msg = Message(arg)
return arg_as_msg.extract_plain_text() | 06d19c9ca4e907edf433f910600161d142ca914e | 3,648,282 |
def dtw(x, y, dist, warp=1):
"""
Computes Dynamic Time Warping (DTW) of two sequences.
:param array x: N1*M array
:param array y: N2*M array
:param func dist: distance used as cost measure
:param int warp: how many shifts are computed.
Returns the minimum distance, the cost matrix, the accum... | a30a492d816e5234590d9fadfbba722db0ae9f72 | 3,648,283 |
def format_line_count_break(padding: int) -> str:
"""Return the line count break."""
return format_text(
" " * max(0, padding - len("...")) + "...\n", STYLE["detector_line_start"]
) | 2fe4d4b8195468787f31b3407d32a4e039f7bb6c | 3,648,284 |
from typing import Tuple
from typing import get_args
def identify_generic_specialization_types(
cls: type, generic_class: type
) -> Tuple[type, ...]:
"""
Identify the types of the specialization of generic class the class cls derives from.
:param cls: class which derives from a specialization of gene... | 3932062a5a4543b280ebc8601126e10d11136717 | 3,648,285 |
def Metadata():
"""Get a singleton that fetches GCE metadata.
Returns:
_GCEMetadata, An object used to collect information from the GCE metadata
server.
"""
def _CreateMetadata(unused_none):
global _metadata
if not _metadata:
_metadata = _GCEMetadata()
_metadata_lock.lock(function=_Crea... | 096ac4f0278e0048944d5a10c4153be7c60aae88 | 3,648,286 |
def pa11y_counts(results):
"""
Given a list of pa11y results, return three integers:
number of errors, number of warnings, and number of notices.
"""
num_error = 0
num_warning = 0
num_notice = 0
for result in results:
if result['type'] == 'error':
num_error += 1
... | 346c1efe0cae5934e623a8643b0f23f85300181d | 3,648,287 |
def parse_properties(df, columns_to_integer=None, columns_to_datetime=None, columns_to_numeric=None, columns_to_boolean=None, columns_to_string = None, dt_unit = 'ms', boolean_dict = {'true': True, 'false': False, '': None}):
"""
Parse string columns to other formats. This function is used in hubspot routine, it... | a162397308d98faac6ab24f07aceee439aa32095 | 3,648,288 |
import requests
def http_request(method, url, headers, data=None):
"""
Request util
:param method: GET or POST or PUT
:param url: url
:param headers: headers
:param data: optional data (needed for POST)
:return: response text
"""
response = requests.request(method, url, headers=hea... | 6d0453be79b3ae0f7ed60b5a8759b9295365dd6c | 3,648,289 |
def parse_title(line):
"""if this is title, return Tuple[level, content],
@type line: str
@return: Optional[Tuple[level, content]]
"""
line = line.strip()
if not line.startswith('#'):
return None
sharp_count = 0
for c in line:
if c == '#':
sharp_count += 1
... | 7c170f417755c878d225b780b8475a379501c19f | 3,648,291 |
import typing
def issubtype(cls: type, clsinfo: type) -> bool:
"""
Return whether ``cls`` is a subclass of ``clsinfo`` while also considering
generics.
:param cls: the subject.
:param clsinfo: the object.
:return: True if ``cls`` is a subclass of ``clsinfo`` considering generics.
"""
i... | 942d5760c3de4d63bcd9c3f5934fcc89727dc958 | 3,648,292 |
def delete_status(id):
"""Delete an existing status
The status to be deleted should be posted as JSON using
'application/json as the content type. The posted JSON needs to
have 2 required fields:
* user (the username)
* api_key
An example of the JSON::
{
"user": "r1ck... | d6a9ebbc787283f3ac247935f3fe5ad9080d2bd0 | 3,648,293 |
def process_data(data):
""" Change labels, group by planner and format for latex."""
data = data.replace(
{
"grid_run_1": "Grid",
"prm_run_1": "PRM A",
"prm_run_2": "PRM B",
"prm_run_3": "PRM C",
}
)
data = data.rename(
columns={"n... | 24ac1c2ee872c5051eccc9774943f922671267b1 | 3,648,294 |
def detect_outlier(TS, samples_wind=60, order=3):
"""Find outliers in TS by interpolate one sample at a time, measure diff.
between rec. sample and interpolated, and getting the peaks in the int diff
across recording.
Parameters
-------------
TS : array (x, y) x n_samples
Times ser... | 91515770554155ddb0da507e94e4cffc611202d9 | 3,648,295 |
def postprocess(backpointers, best_tag_id):
"""Do postprocess."""
best_tag_id = best_tag_id.asnumpy()
batch_size = len(best_tag_id)
best_path = []
for i in range(batch_size):
best_path.append([])
best_local_id = best_tag_id[i]
best_path[-1].append(best_local_id)
for b... | 5be856610a3c81453c11c584507dcb4ad0e4cf61 | 3,648,296 |
def carnatic_string_to_ql_array(string_):
"""
:param str string_: A string of carnatic durations separated by spaces.
:return: The input string converted to a quarter length array.
:rtype: numpy.array.
>>> carnatic_string_to_ql_array('oc o | | Sc S o o o')
array([0.375, 0.25 , 0.5 , 0.5 , 1.5 , 1. , 0.25 , ... | 19386ac13233c3f5cc70eea7f75d287784f6a969 | 3,648,297 |
def login_redirect(request: HttpRequest) -> HttpResponse:
"""
Redirects the user to the Strava authorization page
:param request: HttpRequest
:return: HttpResponse
"""
strava_uri = get_strava_uri()
return redirect(strava_uri) | 80eb714ab8f1fde25f2a3ce57bdc540a5a7a980d | 3,648,299 |
def f(p, x):
"""
Parameters
----------
p : list
A that has a length of at least 2.
x : int or float
Scaling factor for the first variable in p.
Returns
-------
int or float
Returns the first value in p scaled by x, aded by the second value in p.
Examples
... | 3a5e464e7599b6233086e3dddb623d88c6e5ccb6 | 3,648,300 |
def get_contributors_users(users_info) -> list:
"""
Get the github users from the inner PRs.
Args:
users_info (list): the response of get_inner_pr_request()
Returns (list): Github users
"""
users = []
for item in users_info:
user = item.get('login')
github_profile =... | 1a7bdb6608600c2959ec3961dfd9567cf674f471 | 3,648,301 |
def euler2mat(roll, pitch, yaw):
"""
Create a rotation matrix for the orientation expressed by this transform.
Copied directly from FRotationTranslationMatrix::FRotationTranslationMatrix
in Engine/Source/Runtime/Core/Public/Math/RotationTranslationMatrix.h ln 32
:return:
"""
angles = _TORAD ... | 2b635f50bb42f7a79938e38498e6e6fefd993d0f | 3,648,302 |
def remove_articles(string: str, p: float = 1.0) -> str:
"""Remove articles from text data.
Matches and removes the following articles:
* the
* a
* an
* these
* those
* his
* hers
* their
with probability p.
Args:
string: text
p: probability of removin... | af2b9f61dc36159cb027eae03dbf1b645e48be62 | 3,648,303 |
import collections
import re
def _get_definitions(source):
# type: (str) -> Tuple[Dict[str, str], int]
"""Extract a dictionary of arguments and definitions.
Args:
source: The source for a section of a usage string that contains
definitions.
Returns:
A two-tuple containing... | a97fe58c3eb115bff041e77c26868bae3bc54c88 | 3,648,305 |
import requests
def pairs_of_response(request):
"""pairwise testing for content-type, headers in responses for all urls """
response = requests.get(request.param[0], headers=request.param[1])
print(request.param[0])
print(request.param[1])
return response | f3a67b1cbf41e2c2e2aa5edb441a449fdff0d8ae | 3,648,306 |
def setup():
""" The setup wizard screen """
if DRIVER is True:
flash(Markup('Driver not loaded'), 'danger')
return render_template("setup.html") | 1c13ba635fcdd3dd193e511002d2d289786980a3 | 3,648,307 |
def ldns_pkt_set_edns_extended_rcode(*args):
"""LDNS buffer."""
return _ldns.ldns_pkt_set_edns_extended_rcode(*args) | 3fed71706554170d07281a59ff524de52487244d | 3,648,308 |
def sim_spiketrain_poisson(rate, n_samples, fs, bias=0):
"""Simulate spike train from a Poisson distribution.
Parameters
----------
rate : float
The firing rate of neuron to simulate.
n_samples : int
The number of samples to simulate.
fs : int
The sampling rate.
Ret... | 853a16ae50b444fad47dcbea5f7de4edf58f34b5 | 3,648,309 |
def getHausdorff(labels, predictions):
"""Compute the Hausdorff distance."""
# Hausdorff distance is only defined when something is detected
resultStatistics = sitk.StatisticsImageFilter()
resultStatistics.Execute(predictions)
if resultStatistics.GetSum() == 0:
return float('nan')
# E... | 933206c551f2abd6608bf4cdbb847328b8fee113 | 3,648,310 |
import re
def _filesizeformat(file_str):
"""
Remove the unicode characters from the output of the filesizeformat()
function.
:param file_str:
:returns: A string representation of a filesizeformat() string
"""
cmpts = re.match(r'(\d+\.?\d*)\S(\w+)', filesizeformat(file_str))
return '{... | c9811120a257fda8d3fe6c3ee1cd143f17fc4f6e | 3,648,311 |
import math
def radec_to_lb(ra, dec, frac=False):
"""
Convert from ra, dec to galactic coordinates.
Formulas from 'An Introduction to Modern Astrophysics (2nd Edition)' by
Bradley W. Carroll, Dale A. Ostlie (Eq. 24.16 onwards).
NOTE: This function is not as accurate as the astropy conversion, no... | 85156dae81a636f34295bcb8aab6f63243d9c2b3 | 3,648,312 |
from typing import Counter
from datetime import datetime
def status_codes_by_date_stats():
"""
Get stats for status codes by date.
Returns:
list: status codes + date grouped by type: 2xx, 3xx, 4xx, 5xx, attacks.
"""
def date_counter(queryset):
return dict(Counter(map(
... | e56491e32a774f2b3399eb252bc5c7660539d573 | 3,648,313 |
def r8_y1x ( t ):
"""
#*****************************************************************************80
#
#% R8_Y1X evaluates the exact solution of the ODE.
#
# Licensing:
#
# This code is distributed under the GNU LGPL license.
#
# Modified:
#
# 30 August 2010
... | b6146173c09aede82fab599a9e445d3d062bf71a | 3,648,314 |
def get_target_model_ops(model, model_tr):
"""Get operations related to the target model.
Args:
* model: original model
* model_tr: target model
Returns:
* init_op: initialization operation for the target model
* updt_op: update operation for the target model
"""
init_ops, updt_ops = [], []
for v... | 0967e754e2731140ca5d0d85c9c1b6cff7b2cbd2 | 3,648,315 |
import itertools
import functools
def next_count(start: int = 0, step: int = 1):
"""Return a callable returning descending ints.
>>> nxt = next_count(1)
>>> nxt()
1
>>> nxt()
2
"""
count = itertools.count(start, step)
return functools.partial(next, count) | 299d457b2b449607ab02877eb108c076cb6c3e16 | 3,648,316 |
def show_locale(key_id: int):
"""Get a locale by ID"""
return locales[key_id] | 6bce0cc45e145a6bdfb5e84cdde8c6d386525094 | 3,648,317 |
def refresh():
"""Pull fresh data from Open AQ and replace existing data."""
DB.drop_all()
DB.create_all()
update_db()
DB.session.commit()
records = Record.query.all()
return render_template('aq_base.html', title='Refreshed!', records=records) | a1f138f92f8e7744d8fc5b659bb4d99fc32341e9 | 3,648,318 |
def get_similar_taxa():
"""
Get a list of all pairwise permutations of taxa sorted according to similarity
Useful for detecting duplicate and near-duplicate taxonomic entries
:return: list of 2-tuples ordered most similar to least
"""
taxa = Taxon.objects.all()
taxon_name_set = set([t.name f... | cb94efad4103edc8db0fe90f0e2bad7b52bf29f5 | 3,648,319 |
import json
def make_img_id(label, name):
""" Creates the image ID for an image.
Args:
label: The image label.
name: The name of the image within the label.
Returns:
The image ID. """
return json.dumps([label, name]) | 4ddcbf9f29d8e50b0271c6ee6260036b8654b90f | 3,648,320 |
def col2rgb(color):
""" Convert any colour known by matplotlib to RGB [0-255] """
return rgb012rgb(*col2rgb01(color)) | 075dbf101d032bf1fb64a8a4fd86407ec0b91b2d | 3,648,321 |
from typing import List
import random
def quick_select_median(values: List[tuple], pivot_fn=random.choice, index=0) -> tuple:
"""
Implementation quick select median sort
:param values: List[tuple]
:param pivot_fn:
:param index: int
:return: tuple
"""
k = len(values) // 2
return qui... | a2977424a9fc776b2448bed4c17eea754003242c | 3,648,322 |
import time
import hashlib
def get_admin_token(key, previous=False):
"""Returns a token with administrative priviledges
Administrative tokens provide a signature that can be used to authorize
edits and to trigger specific administrative events.
Args:
key (str): The key for generating admin t... | 6f92378676905b8d035bd201abe30d1d951a7fc0 | 3,648,323 |
def vulnerability_weibull(x, alpha, beta):
"""Return vulnerability in Weibull CDF
Args:
x: 3sec gust wind speed at 10m height
alpha: parameter value used in defining vulnerability curve
beta: ditto
Returns: weibull_min.cdf(x, shape, loc=0, scale)
Note:
weibull_min.pdf... | 4bb36643b483309e4a4256eb74bc3bbd7b447416 | 3,648,325 |
def _find_best_deals(analysis_json) -> tuple:
"""Finds the best deal out of the analysis"""
best_deals = []
for deal in analysis_json:
if _get_deal_value(analysis_json, deal) > MINIMUM_ConC_PERCENT:
best_deals.append(deal)
best_deals.sort(key=lambda x: _get_deal_value(analysis_jso... | 5415f7104ec01a56249df9a142ff3c31b2964c42 | 3,648,326 |
def deserialize(s_transform):
"""
Convert a serialized
:param s_transform:
:return:
"""
if s_transform is None:
return UnrealTransform()
return UnrealTransform(
location=s_transform['location'] if 'location' in s_transform else (0, 0, 0),
rotation=s_transform['rotatio... | 13daf861e84545d2f50b10617ece6d23976eacf0 | 3,648,327 |
def spectrum(x, times=None, null_hypothesis=None, counts=1, frequencies='auto', transform='dct',
returnfrequencies=True):
"""
Generates a power spectrum from the input time-series data. Before converting to a power
spectrum, x is rescaled as
x - > (x - counts * null_hypothesis) / sqrt(co... | 5a847f75eaa3fda0bc2906e14d56f7870da1edfa | 3,648,328 |
def CalculatePercentIdentity(pair, gap_char="-"):
"""return number of idential and transitions/transversions substitutions
in the alignment.
"""
transitions = ("AG", "GA", "CT", "TC")
transversions = ("AT", "TA", "GT", "TG", "GC", "CG", "AC", "CA")
nidentical = 0
naligned = 0
ndifferent... | 84d67754d9f63eaee5a172425ffb8397c3b5a7ff | 3,648,329 |
def render_ellipse(center_x, center_y, covariance_matrix, distance_square):
"""
Renders a Bokeh Ellipse object given the ellipse center point, covariance, and distance square
:param center_x: x-coordinate of ellipse center
:param center_y: y-coordinate of ellipse center
:param covariance_matrix: Nu... | 8f26a9a41a8f179f87925f0a931fbc81d2d8549b | 3,648,330 |
def flow_to_image(flow):
"""Transfer flow map to image.
Part of code forked from flownet.
"""
out = []
maxu = -999.
maxv = -999.
minu = 999.
minv = 999.
maxrad = -1
for i in range(flow.shape[0]):
u = flow[i, :, :, 0]
v = flow[i, :, :, 1]
idxunknow = (abs(u... | 301ef598b2e6aeda2e2f673854850faf0409e0e8 | 3,648,331 |
def joint_dataset(l1, l2):
"""
Create a joint dataset for two non-negative integer (boolean) arrays.
Works best for integer arrays with values [0,N) and [0,M) respectively.
This function will create an array with values [0,N*M), each value
representing a possible combination of values from l1 and l... | 6ba767739793f7c188d56e24e6e07d6e594c775e | 3,648,332 |
import uuid
def parse(asset, image_data, product):
""" Parses the GEE metadata for ODC use.
Args:
asset (str): the asset ID of the product in the GEE catalog.
image_data (dict): the image metadata to parse.
product (datacube.model.DatasetType): the product information from the ODC ind... | 815da17849b240a291332a695ca38374bb957d8a | 3,648,333 |
def scale(pix, pixMax, floatMin, floatMax):
""" scale takes in
pix, the CURRENT pixel column (or row)
pixMax, the total # of pixel columns
floatMin, the min floating-point value
floatMax, the max floating-point value
scale returns the floating-point value that
corresp... | 455d0233cbeeafd53c30baa4584dbdac8502ef94 | 3,648,334 |
def most_distinct(df):
"""
:param df: data frame
:return:
"""
headers = df.columns.values
dist_list = [] # list of distinct values per list
for idx, col_name in enumerate(headers):
col = df[col_name]
col_list = col.tolist()
# if len(col_list) == 0:
# dist... | f21ba5ffd2bfcf5262ffbbe30f24a77522a10bb0 | 3,648,335 |
def make_set(value):
"""
Takes a value and turns it into a set
!!!! This is important because set(string) will parse a string to
individual characters vs. adding the string as an element of
the set i.e.
x = 'setvalue'
set(x) = {'t', 'a', 'e', 'v', 'u', 's', 'l'}
make_set(x) ... | c811729ea83dc1fbff7c76c8b596e26153aa68ee | 3,648,336 |
def _get_parent_cache_dir_url():
"""Get parent cache dir url from `petastorm.spark.converter.parentCacheDirUrl`
We can only set the url config once.
"""
global _parent_cache_dir_url # pylint: disable=global-statement
conf_url = _get_spark_session().conf \
.get(SparkDatasetConverter.PARENT_... | 34abb96b64ab5338a6c9a5ef700a6fbb00f3905f | 3,648,337 |
def make_variable(data, variances=None, **kwargs):
"""
Make a Variable with default dimensions from data
while avoiding copies beyond what sc.Variable does.
"""
if isinstance(data, (list, tuple)):
data = np.array(data)
if variances is not None and isinstance(variances, (list, tuple)):
... | a712800df05c8c8f5f968a0fee6127919ae56d8f | 3,648,338 |
def dt642epoch(dt64):
"""
Convert numpy.datetime64 array to epoch time
(seconds since 1/1/1970 00:00:00)
Parameters
----------
dt64 : numpy.datetime64
Single or array of datetime64 object(s)
Returns
-------
time : float
Epoch time (seconds since 1/1/1970 00:00:00)
... | f7cdaf44312cb0564bf57393a5fde727bc24e566 | 3,648,339 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.