content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def my_dice_metric_hemp(label, pred):
""" Converts dice score metric to tensorflow graph, only hemp
Args:
label: ground truth mask [batchsize, height, width, classes]
pred: prediction mask [batchsize, height, width, classes]
Returns:
dice value as tensor
"""
return tf... | 8c170ebde9002e4c8ea832f4310a0d1247617f73 | 31,898 |
def largest_second_derivative_2d(gxx, gxy, gyy):
"""This function determines the largest eigenvalue and corresponding eigen vector of an image based on Gaussian
derivatives. It returns the direction and magnitude of the largest second derivative. For lines, this direction
will correspond to the normal vecto... | de054fa7a3e2d47c25c6e7f8756c624add5d1cf8 | 31,899 |
def schema_to_entity_names(class_string):
"""
Mapping from classes path to entity names (used by the SQLA import/export)
This could have been written much simpler if it is only for SQLA but there
is an attempt the SQLA import/export code to be used for Django too.
"""
if class_string is None or ... | c7a6aabde74e3639f39b8e56ad5f82c6684dd2ba | 31,900 |
def csm_data(csm):
"""
Return the data field of the sparse variable.
"""
return csm_properties(csm)[0] | c0f6993f9fb005f5659539deb89b459039801ea1 | 31,901 |
def plot_hypnogram(resampled_hypno, cycles=None, label="", fig=None, ax=None):
"""
Plot an aesthetically pleasing hypnogram with optional cycle markers.
Parameters
----------
resampled_hypno : pd.DataFrame
Hypnogram resampled to epoch time units.
cycles : cycles : pd.DataFrame, optional... | 5c9be12d2aa9553d4a0084fd6734e5847eabcb57 | 31,902 |
from typing import Callable
def _scroll_screen(direction: int) -> Callable:
"""
Scroll to the next/prev group of the subset allocated to a specific screen.
This will rotate between e.g. 1->2->3->1 when the first screen is focussed.
"""
def _inner(qtile):
if len(qtile.screens) == 1:
... | e778b6ef8a07fe8609a5f3332fa7c44d1b34c17a | 31,903 |
def _gate_altitude_data_factory(radar):
""" Return a function which returns the gate altitudes. """
def _gate_altitude_data():
""" The function which returns the gate altitudes. """
try:
return radar.altitude['data'] + radar.gate_z['data']
except ValueError:
retur... | 2a13cd44a6c50e6cbe7272e5628926aa4e76c71b | 31,904 |
from typing import Callable
import pathlib
def test_posix_message_queue_ee(
monkeypatch: pytest.MonkeyPatch,
is_dir: bool,
ee_support: bool,
engine: str,
generate_config: Callable,
):
"""Confirm error messages related to missing ``/dev/mqueue/`` and ``podman``.
Test using all possible com... | 7dddd24953261324b982da0ed7adbf632cf47779 | 31,905 |
import random
def RandHexColor(length=6):
"""Generates a random color using hexadecimal digits.
Args:
length: The number of hex digits in the color. Defaults to 6.
"""
result = [random.choice(HEX_DIGITS) for _ in range(length)]
return '#' + ''.join(result) | 7e196fa2b0666dc9aee67bcac83d0186812d9335 | 31,906 |
def _backtest2(prediction, price, acct_num,):
"""
Cal daiy return in % form
:param prediction:
:param price:
:param acct_num:
:return:
"""
# starting net val for trading account
mat = np.ones((acct_num, len(price)))
# liquidate or build position time
_idx = np.arange(len(pric... | 09e230945daf2f745b39523e5fba676e88629e09 | 31,907 |
def check_players(instance):
""" Checks to see if any of the starting players have left.
Args:
instance: The GameInstance model for this operation.
If a player has left the game, they are invited back and
a ValueError is raised.
Raises:
ValueError if a player has left the game.
"""
if len(insta... | d3a31f17cf5d3dee2e3fd075cea2e31d8a806952 | 31,908 |
def list_descendant(input_list):
"""Function that orders a list on descendant order using insertion sort
Args:
input_list ([type]): List with the values that we want to order
Returns:
list: The ordered list
"""
for i in range(1, len(input_list)):
j = i-1
next_elemen... | 8d2c452a513ccf67c4b179bf989fac5cc0108d09 | 31,909 |
from io import StringIO
import csv
async def chargify_invoices_csv(request: Request):
"""
Output Chargify invoices data.
"""
output = StringIO()
writer = csv.writer(output)
if not request.app['chargify_invoices_data']:
raise Exception("data not loaded yet")
writer.writerows(reque... | 5558b1b885f52edccc45a3819cab0353f84578fa | 31,910 |
def generate_base_reference(header,waveform="cosine",period=24,phase=0,width=12):
"""
This will generate a waveform with a given phase and period based on the header,
"""
ZTs = header
tpoints = np.zeros(len(ZTs))
coef = 2.0 * np.pi / float(period)
w = float(width) * coef
for i,ZT in... | b1178e07d9d628654902b6198acac1f791ba2064 | 31,911 |
def from_string(dlstr):
"""Factory method taking the string as appearing in FIELD input"""
input_key = dlstr.split()[0].lower()
for subcls in Interaction.__subclasses__():
if subcls.key == input_key:
return subcls.from_string(dlstr)
raise ValueError("No interaction available for ... | 875eb21e3773f47fdc77d3177a5f5253d0656546 | 31,912 |
def assign_cat(plugin):
"""Assigns `fonts` module keywords to the `Warp` plugin."""
meta = [
[KEYWORD_MATHCAL, "Script (or calligraphy): 𝒜ℬ𝒞𝒶𝒷𝒸𝒜𝒞𝒶𝒷𝒸"],
[KEYWORD_MATHBB, "Double-struck: 𝔸𝔹ℂ𝕒𝕓𝕔𝟙𝟚𝟛𝔸𝔹𝕒𝕓𝕔𝟙𝟚𝟛"],
[KEYWORD_MATHFRAK, "Fraktur: 𝔄𝔅ℭ𝔞𝔟𝔠𝔄𝔅𝔞𝔟𝔠"],
... | a1168624fa330ce19a3c8e78346bb7a893bb74e3 | 31,913 |
def get_holidays(startYear = 2018, endYear = 2025, countryCode = 'ZA'):
"""
Takes in a start and end date, and start and end year.
Produces a dataframe with a daily date and columns:
holiday - 'Y' for holiday
holidayName - name of the holiday if holiday is 'Y'
Returns a dataframe
"... | 6d7d83389bee2a83c6cc2d565f7c04b8d131555a | 31,915 |
import struct
def _testHeadCheckSum(header, tableDirectory):
"""
>>> header = dict(sfntVersion="OTTO")
>>> tableDirectory = [
... dict(tag="head", offset=100, length=100, checkSum=123, data="00000000"+struct.pack(">L", 925903070)),
... dict(tag="aaab", offset=200, length=100, checkSum=456)... | 4391c4d6dd6c3fedf99315a2d6995962251ca10f | 31,916 |
def svn_ra_do_status(*args):
"""
svn_ra_do_status(svn_ra_session_t session, svn_ra_reporter2_t reporter,
void report_baton, char status_target, svn_revnum_t revision,
svn_boolean_t recurse, svn_delta_editor_t status_editor,
void status_baton,
apr_pool_t pool) -> svn_error_t
... | 30d2d310bf2e047653c99ba4add68b3e2d07ee00 | 31,918 |
def clear_spaces(comp):
"""
'A + D' -> 'A+D'
"""
r = ''
for c in comp:
if c != ' ':
r += c
return r | cf8f28cf3633eb31d0c934dd9fc3035b3c1539f4 | 31,919 |
def _load_metabolite_linkouts(session, cobra_metabolite, metabolite_database_id):
"""Load new linkouts even ones that are pointing to previously created universal
metabolites.
The only scenario where we don't load a linkout is if the external id and
metabolite is exactly the same as a previous linkout.... | cda0a2fef212b091d39b45d2c8603eedc0f3b99a | 31,920 |
import random
def gen_ascii_captcha(symbols, length=6, max_h=10, noise_level=0, noise_char="."):
"""
Return a string of the specified length made by random symbols.
Print the ascii-art representation of it.
Example:
symbols = gen_ascii_symbols(input_file='ascii_symbols.txt',
... | b6f6f02bbbe3cbdfce007ea13e26836c21e20ef2 | 31,921 |
def get_app_name_cache_file(file_path: str) -> str:
"""Returns path to app name cache file"""
return f'{file_path}.{APP_NAME_FILE_EXTENSION}' | 16bdfe57e28eb5ea97e317fea98285af494ff0a9 | 31,922 |
def make_matrix_A(x_r, simulations, ξ, Δ_t=1, λ=1):
"""
Equation (9) from paper
:param x_r: reference output
:param simulations: simulation outputs
:param t_Δ: the intervals between each observation (series or constant)
:param ξ: squash control parameter
:return: the position/trend matr... | f4cb5e4dd5f79385ee4c945b4b7982200f2fa474 | 31,923 |
def generate_markov_content(content):
""" Generate Markov Content
Parameters
----------
content : str
Corpus to generate markov sequences from
"""
# Build the model.
text_model = markovify.Text(content, state_size=3)
# return randomly-generated sentence of no more than 280 chara... | c0503dca553712f8563c53676d3216f8206808ab | 31,924 |
def _quadratic_system_matrix(x):
"""
Create system matrix of a model with linear, quadratic and 1st-order 2-way interaction terms
Parameters
----------
x : array_like, shape (n, m)
Explanatory variable of n data points and m variables
Returns
-------
A : ndarray, shape (n, 1 + ... | 6d958cccaf5127fdc9f3fc6bcc472ceafd2947d6 | 31,925 |
def pytest_pycollect_makeitem(collector, name, obj):
"""A pytest hook to collect curio coroutines."""
if collector.funcnamefilter(name) and curio.meta.iscoroutinefunction(obj):
item = pytest.Function.from_parent(collector, name=name)
if "curio" in item.keywords:
return list(collector... | 95d18bc4575fc31c938dae6d487cf4cd058d89c4 | 31,926 |
def eta_hms(seconds, always_show_hours=False, always_show_minutes=False, hours_leading_zero=False):
"""Converts seconds remaining into a human readable timestamp (e.g. hh:mm:ss, h:mm:ss, mm:ss, or ss).
Positional arguments:
seconds -- integer/float indicating seconds remaining.
Keyword arguments:
... | db85099a0a1c19391ed8abc1ea2bcf4b867a93af | 31,927 |
def apply_Hc(C, A_L, A_R, Hlist):
"""
Compute C' via eq 16 of vumps paper (132 of tangent space methods).
"""
H, LH, RH = Hlist
A_Lstar = np.conj(A_L)
A_C = ct.rightmult(A_L, C)
to_contract = [A_C, A_Lstar, A_R, np.conj(A_R), H]
idxs = [(4, 1, 3),
(6, 1, -1),
(5, ... | ae43b1fe1484ee70b2245474f03a3e9676b44929 | 31,928 |
import ipywidgets as ipyw
def make_basic_gui(container):
"""Create a basic GUI layout.
Parameters
----------
container : RenderContainer
Returns
-------
ipywidgets.GridspecLayout
"""
element_controls = [
ipyw.HTML(value="<b>Elements</b>", layout=ipyw.Layout(align_self="... | 5a01c70304910b1b20193c507a348ec90dd6a514 | 31,929 |
def parse_middleware_mkdir_response(mkdir_resp):
"""
Parse a response from RpcMiddlewareMkdir.
Returns (mtime in nanoseconds, inode number, number of writes)
"""
return (_ctime_or_mtime(mkdir_resp),
mkdir_resp["InodeNumber"],
mkdir_resp["NumWrites"]) | 17336084895bbad579785e7e918674e4367f05c6 | 31,932 |
import torch
def decorate_batch(batch, device='cpu'):
"""Decorate the input batch with a proper device
Parameters
----------
batch : {[torch.Tensor | list | dict]}
The input batch, where the list or dict can contain non-tensor objects
device: str, optional
'cpu' or 'cuda'
... | a0bd4a5dff0b5cf6e304aede678c5d56cb93d1dd | 31,933 |
import yaml
def get_config(filename: str = CONFIG_FILENAME) -> dict:
"""
Get config as a dictionary
Parameters
----------
filename: str
The filename with all the configuration
Returns
-------
dict
A dictionary containing all the entries from the config YAML
"""
... | 79572679204c53f6ecdf91a120bb6a08ced9afd1 | 31,934 |
def partition_trace(vtrace):
"""partition a trace based on its types """
partition = {}
for v in vtrace:
vty = get_vt_type(v)
if vty not in partition:
partition[vty] = []
partition[vty].append(v)
return partition | 6fa30f6180a122cc6cb74bf7dcdfbbfa2b4a8627 | 31,935 |
def test_text_justify_bottom_right_and_top_left(region, projection):
"""
Print text justified at bottom right and top left.
"""
fig = Figure()
fig.text(
region=region,
projection=projection,
x=1.2,
y=0.2,
text="text justified bottom right",
justify="BR... | a8b1735e002f2c310226142bfcbde9bd1fea9f95 | 31,936 |
from pathlib import Path
def get_bench(
lx: tuple[int, int, int], data_dir: Path, tests: list[str], comp_lvls: list[int]
) -> dict[str, pd.DataFrame]:
"""get writing benchmark HDF5 files to pandas dataframe"""
data = {
"write_dr": pd.DataFrame(index=comp_lvls, columns=tests),
"read_dr": p... | d135f58a3793cf161f338118060b16106bd6c96a | 31,937 |
def custom_token(deploy_tester_contract, custom_token_params):
"""Deploy CustomToken contract"""
return deploy_tester_contract(
CONTRACT_CUSTOM_TOKEN,
[],
custom_token_params
) | 175f8b49545e422ae691631b361f7bb62e9f62f5 | 31,938 |
def parse_values(reports, criteria1, criteria2, steps, crit1_name, crit2_name, first=False, cpus=1):
"""
Description: Parse the 'reports' and create a sorted array
of size n_structs following the criteria chosen by the user.
"""
info_reports = [ retrieve_report_data(report) for report i... | 9d22756ecdfe50f7e5563a4fa855ddb5a3a4cd21 | 31,939 |
import io
def read_bytes(n: int, reader: io.IOBase) -> bytes:
"""
Reads the specified number of bytes from the reader. It raises an
`EOFError` if the specified number of bytes is not available.
Parameters:
- `n`: The number of bytes to read;
- `reader`: The reader;
Returns the bytes rea... | bb3d00fc7667839864f4104a94a26e682f058fdc | 31,940 |
import json
def _format_full_payload(_json_field_name, _json_payload, _files_payload):
"""This function formats the full payload for a ``multipart/form-data`` API request including attachments.
.. versionadded:: 2.8.0
:param _json_field_name: The name of the highest-level JSON field used in the JSON pay... | feacd27be3e6fcbd33f77fa755be513a93e3cdeb | 31,941 |
def convert_rows (rows):
"""Read a two-element tuple from a string.
rows should be a string containing two integers separated by a
comma, blank, or colon. The numbers may be enclosed in parentheses
or brackets, but this is not necessary. Note: the row numbers
are one indexed and inclusive, e.g. rows = "480, 544"... | e2d5a8e68459d6cb7a2fa044baa6d25dab46511c | 31,942 |
import numpy
def prepare_data(hsi_img=None, gnd_img=None, window_size=7, n_principle=3,
batch_size=50, merge=False, ratio=[6, 2, 2]):
"""
Process the data from file path to splited train-valid-test sets; Binded in
dataset_spectral and dataset_spatial respectively.
Parameters
... | b54d174cdfc99bc1ba74e7b8cc09661d6bf18f9c | 31,943 |
def mvresnet152(**kwargs):
"""Constructs a MVResNet-101 model.
"""
model = MVResNet(Bottleneck, [3, 8, 36, 3], **kwargs)
return model | 86b579e5f3a80b87677d0aa0c075d4e3eeb81d46 | 31,945 |
def _wer_compute(errors: Tensor, total: Tensor) -> Tensor:
"""Compute the word error rate.
Args:
errors: Number of edit operations to get from the reference to the prediction, summed over all samples
total: Number of words overall references
Returns:
Word error rate score
"""
... | c7a2ea912e27d1867f771b135cb0c8bd9fd7729e | 31,946 |
def get_coordinator():
"""Creates a coordinator and returns it."""
workflow_queue = Queue.Queue()
complete_queue = Queue.Queue()
coordinator = WorkflowThread(workflow_queue, complete_queue)
coordinator.register(WorkflowItem, workflow_queue)
return coordinator | 24fa3b52803f1cebae246be8b3988b9568965e6d | 31,947 |
from typing import Any
from typing import Union
import torch
def tocuda(vars: Any) -> Union[str, torch.Tensor]:
"""Convert tensor to tensor on GPU"""
if isinstance(vars, torch.Tensor):
return vars.cuda()
elif isinstance(vars, str):
return vars
else:
raise NotImplementedError("i... | b7be275fe7e909fa54fc62ed9e5fbe61d3ff4863 | 31,948 |
from typing import Union
from typing import NewType
from typing import Any
from typing import Tuple
from typing import Optional
def _maybe_node_for_newtype(
typ: Union[NewType, Any],
overrides: OverridesT,
memo: MemoType,
forward_refs: ForwardRefs
) -> Tuple[Optional[schema.nodes.SchemaNode], MemoType... | 5cce0197a44ebc2517c509211746a996d6e0235c | 31,950 |
def read_slug(filename):
"""
Returns the test slug found in specified filename.
"""
with open(filename, "r") as f:
slug = f.read()
return slug | e1882d856e70efa8555dab9e422a1348594ffcaf | 31,951 |
def boolean_value(value):
"""Given a Value, returns whether the object is statically known to be truthy.
Returns None if its truth value cannot be determined.
"""
if isinstance(value, KnownValue):
try:
return bool(value.val)
except Exception:
# Its __bool__ thre... | c4f971b474943f44c2d5b85def14d91901244e72 | 31,952 |
def _convert_to_dict(tracked_dict):
"""
Recursively convert a Pony ORM TrackedDict to a normal Python dict
"""
if not isinstance(tracked_dict, orm.ormtypes.TrackedDict):
return tracked_dict
return {k: _convert_to_dict(v) for k, v in tracked_dict.items()} | 40a31ebc96f3010618c3b091e2618d2d6809b82d | 31,956 |
def sky_coords(cluster):
"""Get the sky coordinates of every star in the cluster
Parameters
----------
cluster : class
StarCluster
Returns
-------
ra,dec,d0,pmra,pmdec,vr0 : float
on-sky positions and velocities of cluster stars
History
-------
2018 - Writt... | 26a17879a6c2cc84dbf250d9250014f8554fbb9e | 31,957 |
import time
import requests
import json
def macro_cons_silver_volume():
"""
全球最大白银 ETF--iShares Silver Trust 持仓报告, 数据区间从 20060429-至今
:return: pandas.Series
"""
t = time.time()
res = requests.get(
JS_CONS_SLIVER_ETF_URL.format(
str(int(round(t * 1000))), str(int(round(t * 10... | 1a806095e935ea5e6065dec4dc412775ebaa2b22 | 31,958 |
def preprocess_img(img):
"""Preprocessing function for images."""
return img/255 | 11651a809288d5c3aa776b318099b7eb750d28ec | 31,961 |
def get_apitools_metadata_from_url(cloud_url):
"""Takes storage_url.CloudUrl and returns appropriate Apitools message."""
messages = apis.GetMessagesModule('storage', 'v1')
if cloud_url.is_bucket():
return messages.Bucket(name=cloud_url.bucket_name)
elif cloud_url.is_object():
generation = int(cloud_url... | c8ec4dd6c6019467129c03d367c6dd58963d334f | 31,963 |
def branch(ref=None):
"""Return the name of the current git branch."""
ref = ref or "HEAD"
return local("git symbolic-ref %s 2>/dev/null | awk -F/ {'print $NF'}"
% ref, capture=True) | 8597a9b38f2a6372aa9dba911163bdb44d4db1f2 | 31,964 |
def fit_anis(celldmsx, Ex, ibrav=4, out=False, type="quadratic", ylabel="Etot"):
"""
An auxiliary function for handling fitting in the anisotropic case
"""
if out:
print (type+" fit")
if type=="quadratic":
a, chi = fit_quadratic(celldmsx, Ex, ibrav, out, ylabel)
eli... | 25f88d62876696d1d9e95e1c11c5b687a59cea7b | 31,965 |
def solicitacao_incluir(discente, sugestao_turma):
"""
Inclui uma Solicitação de interesse do Discente na Sugestão de Turma.
:param discente: Um objeto da classe @Discente
:param sugestao_turma: Um objeto da classe @SugestaoTurma
:return: Um objeto da classe @SolicitacaoTurma e um booleano informand... | f346058717a62d6007ea99347043512f4770950d | 31,966 |
def _evolve_trotter_gates(psi,
layers,
step_size,
num_steps,
euclidean=False,
callback=None):
"""Evolve an initial wavefunction psi via gates specified in `layers`.
If the evolution is... | e1319a01434b0de0c4d90db3881a5a1e3b22d491 | 31,967 |
from tvm.tir.analysis import _ffi_api as _analysis_ffi_api
import logging
def test_tuning_gpu_inherits_pass_context(target, dev):
"""Autotvm tuner inherits PassContexts but also adds a gpu verification pass by default.
Test that using PassContext inherits passes properly but also runs gpu verification pass.
... | 8c62f18293b24601a8ee5296f2e4984bed7c20e4 | 31,971 |
def make_scae(config):
"""Builds the SCAE."""
# return: model 应该是整个的要训练的model了吧
# 这个好像是要transform 训练集
# canvas & template size 都有什么用呢 在这里?
img_size = [config.canvas_size] * 2
template_size = [config.template_size] * 2
# 这个只是part encoder的一部分, 用的是卷积,直接就是4个卷积层了 padding可以自动, snt NB!!
'''
Sequential(
(... | 415ab9d12806f250fa786872b0a3a2d6ecd82f72 | 31,972 |
import requests
def get_materialization_versions(dataset_name, materialization_endpoint=None):
""" Gets materialization versions with timestamps """
if materialization_endpoint is None:
materialization_endpoint = analysisdatalink.materialization_endpoint
url = '{}/api/dataset/{}'.format(mater... | 32d6976e864a9926f6b2e51ec7a65c33e2b86832 | 31,973 |
import scipy
def WilcoxonRankSum(tpms):
"""May be very slow for large datasets."""
wrs = tpms[['SMTSD', 'ENSG']].copy().drop_duplicates().sort_values(by=['SMTSD', 'ENSG'])
wrs.reset_index(drop=True, inplace=True)
wrs['stat'] = pd.Series(dtype=float)
wrs['pval'] = pd.Series(dtype=float)
for smtsd in wrs.SM... | 89733a49bc8e0e0a1d492b21ad6310746e4d23fe | 31,974 |
def filter_image(image, filter_DFT):
"""
Just takes the DFT of a filter and applies the filter to an image
This may optionally pad the image so as to match the number of samples in the
filter DFT. We should make sure this is greater than or equal to the size of
the image.
"""
assert image.dtype == 'float... | 0c6d2e46640fbfd7757231eb398c90fea0ca0a65 | 31,975 |
def _create_diff_matrix(n, order=1):
"""Creates n x n matrix subtracting adjacent vector elements
Example:
>>> print(_create_diff_matrix(4, order=1))
[[ 1 -1 0 0]
[ 0 1 -1 0]
[ 0 0 1 -1]]
>>> print(_create_diff_matrix(4, order=2))
[[ 1 -1 0 0]
... | 0d241d37075e37d342e2601fc307277dd92b180f | 31,977 |
def fourier_frequencies_from_times(times):
"""
Calculates the Fourier frequencies from a set of times. These frequencies are in 1/units, where
`units` is the units of time in `times`. Note that if the times are not exactly equally spaced,
then the Fourier frequencies are ill-defined, and this returns th... | 4976483355af4652eafe28c955b2ca847bc140af | 31,978 |
import copy
def fission(candidate_seed, pop, n, max_seed_area):
"""
In fusion, we use the convention of putting one seed on
the left and the other seed on the right, before we fuse
the two seeds. In fission, we assume that fission will
split the left part from the right part. Find the most
sparse colum... | f056c90f68f91ba1b3f81f76c3599f8f7a3aee51 | 31,979 |
def iou(box, clusters):
"""
Calculates the Intersection over Union (IoU) between a box and k clusters.
param:
box: tuple or array, shifted to the origin (i. e. width and height)
clusters: numpy array of shape (k, 2) where k is the number of clusters
return:
numpy array of shape (... | d181cf7234602f4b3f7d5b6c0a25cd9e15c2b5ed | 31,980 |
def munge_av_status(av_statuses):
"""Truncate and lowercase availability_status"""
return [a[20:].lower() for a in av_statuses] | 52a00fc6733015c3618a2a394371ea9387d92fc0 | 31,981 |
def cdf(vals, reverse=False):
"""Computes the CDF of a list of values"""
vals = sorted(vals, reverse=reverse)
tot = float(len(vals))
x = []
y = []
for i, x2 in enumerate(vals):
x.append(x2)
y.append((i+1) / tot)
return x, y | 3cc64dcb8876f7620f02da873e29569e77477823 | 31,982 |
def user_document_verification(request, document_id):
"""Display user's document information request.
Args:
request: URL request
document_request_id: document ID in firebase
Returns:
Render user document verification view.
"""
# Document Data
document_ref = db.collection("d... | 6610d21e1a0e35aaf3203814c20687a5b48e5d96 | 31,983 |
def bulk_records(
name: str,
bulk: TextClassificationBulkData,
common_params: CommonTaskQueryParams = Depends(),
service: TextClassificationService = Depends(
TextClassificationService.get_instance
),
datasets: DatasetsService = Depends(DatasetsService.get_instance),
current_user: Us... | aa82e779b5bd9286bd1b456f151f3b0679b3582b | 31,986 |
def environment_list(p_engine, p_username, format, envname):
"""
Print list of environments
param1: p_engine: engine name from configuration
param2: format: output format
param3: envname: environemnt name to list, all if None
return 0 if environment found
"""
ret = 0
enginelist = ... | bf1ca059f0fd919445df4ee931450c7a07619707 | 31,987 |
def loss(logits, labels, weight_decay_factor, class_weights = None):
"""
Total loss:
----------
Args:
logits: Tensor, predicted [batch_size * height * width, num_classes]
labels: Tensor, ground truth [batch_size, height, width, 1]
weight_decay_factor: float, factor with which... | 91fae015aeb5bed4c73cf2aa4d6e62a5c1d4580c | 31,988 |
def negative(num):
"""assumes num is a numeric
returns a boolean, True if num is negative, else False"""
return num < 0 | dc8b789b6dbd4d158482de6d4af26f48f9e8cc5b | 31,989 |
def readSudokus(filename):
"""
Returns the n first sudokus of the file with given name
"""
f = open(filename)
res = None
txt = f.readline().strip()
if txt != "":
res = [[int(txt[i + j * 9]) for i in range(9)] for j in range(9)]
f.close()
return np.array(res) | 564da1dd1fc035ec692986eaa8955985acd5b1ce | 31,990 |
from flask.cli import ScriptInfo
def script_info(base_app):
"""Get ScriptInfo object for testing a CLI command.
Scope: module
.. code-block:: python
def test_cmd(script_info):
runner = CliRunner()
result = runner.invoke(mycmd, obj=script_info)
assert result.e... | 5c5298fcd816538e4890a1d46d51aea6d73702e6 | 31,991 |
def measured_points(idf, return_periods, interim_results=None, max_duration=None):
"""
get the calculation results of the rainfall with u and w without the estimation of the formulation
Args:
idf (IntensityDurationFrequencyAnalyse): idf class
return_periods (float | np.array | list | pd.Ser... | ba0e1cbddf6fd7e23abbfba4954683ada69cea2f | 31,992 |
def get_charpixel():
""" Render a single charpixel """
if options.table == 'input':
c = getch()
if c in ['\n','\t']:
print(c)
else:
c = choice( CHARTABLES[ options.table ] )
return c.encode('utf-8') | deb0475dac66c10c1d9edea45cce1cedffbafd1d | 31,993 |
def test_custom_fixer():
""" Test custom ParseFixer
Verify that read_csv uses custom ParseFixer
"""
class fix_pi(ParseFixer):
def __init__(self):
super().__init__()
# augment existing method, simple fix float
def fix_illegal_cell_value(self, vtype, value):
... | c137e190dffef686b04b2f515c6c65ecd2d50879 | 31,994 |
def context_factory(policy, name):
"""Factory function for creating context objects."""
if not isinstance(name, qpol.qpol_context_t):
raise TypeError("Contexts cannot be looked-up.")
return Context(policy, name) | a528978876bdbaa0d2e249f70a056d49fc894349 | 31,995 |
import email
def decode_mail_header(value, default_charset='us-ascii'):
"""Decode a header value into a unicode string."""
try:
headers = decode_header(value)
except email.errors.HeaderParseError:
return value.encode(default_charset, 'replace').decode(default_charset)
else:
for... | 657a45da883bd35d99642af7cfa1ff5ed9200fbe | 31,996 |
def xyz2xyzr(xyz: np.ndarray, *,
axis: int=None,
illuminant: Illuminant=get_default_illuminant(),
observer: Observer=get_default_observer()) -> np.ndarray:
"""
Convert XYZ to normalized XYZ reflectance
:param xyz: the raw xyz values
:param axis: the axis that the X... | 76e0b3c095ac48a44b31349efe259b70a427cfc0 | 31,997 |
import time
def last_updated(a):
"""
Check the time since file was last updated.
"""
return time.time() - op.getmtime(a) | 653eb5b68e00c57165b413d1de1ed0d8afee41f0 | 31,998 |
import functools
def lstm_acd_decomposition(inp, model):
"""
inp: tf.Tensor(dtype=np.int32, shape=(1, -1)) tokenized input
model: tf.keras.Model or equivalent
"""
l = inp.numpy().size
e, k, rk, b, dw, db = model.weights
embed_inp = tf.nn.embedding_lookup(params=e, ids=inp)
return ac... | 51d55fe155290b3ec1bc7f3b67b562e4b6ae4c23 | 31,999 |
import pyarrow as pa
def ST_IsValid(geos):
"""
Check if geometry is of valid geometry format.
:type geos: Series(dtype: object)
:param geos: Geometries in WKB form.
:rtype: Series(dtype: bool)
:return: True if geometry is valid.
:example:
>>> import pandas
>>> import arctern... | 466f29367dbdc7c09581f7bedda72fe729bdd73d | 32,000 |
import time
def get_framerate(has_already_started,
start_time,
frame_counter,
frame_rate,
frame_num=5,
decimal_round_num=2):
""" Returns current framerate of video based on
time elapsed in frame_num frames.
Works in... | 61db421be9e8d5a0e810a79875eac2b776be99ca | 32,002 |
def check_for_solve(grid):
""" checks if grid is full / filled"""
for x in range(9):
for y in range(9):
if grid[x][y] == 0:
return False
return True | 5fc4a8e7a2efaa016065fc0736aa5bdb7d4c92f8 | 32,003 |
def Sn(i, length):
"""Convert an int to a binary string."""
s = ''
while i != 0:
digit = i & 0xff
i >>= 8
s += chr(digit)
if len(s) > length:
raise Exception("Integer too big to fit")
while len(s) < length:
s += chr(0)
return s | 607c2b8e82379db091505d7422edc17ea121bc3f | 32,004 |
def parse_args():
"""Parse command line arguments"""
parser = ArgumentParser(
description='Print contents of a parsed config file',
formatter_class=ArgumentDefaultsHelpFormatter,
)
parser.add_argument(
'pipeline', metavar='CONFIGFILE',
nargs='?',
default='settings... | 67462f2078ede7dfb9d9e0956b32f1eb09b2a747 | 32,006 |
import copy
def _normalize_annotation(annotation, tag_index):
"""
Normalize the annotation anchorStart and anchorEnd,
in the sense that we start to count the position
from the beginning of the sentence
and not from the beginning of the disambiguated page.
:param annotation: Annotation object
:param tag_inde... | a7da5810711ada97a2ddcc308be244233fe813be | 32,007 |
def read_lc(csvfile, comment='|'):
"""
Read a light curve csv file from gAperture.
:param csvfile: The name of the csv file to read.
:type csvfile: str
:param comment: The character used to denote a comment row.
:type comment: str
:returns: pandas DataFrame -- The contents of the csv fi... | 74e53cbfe902e9d23567569ec0f4c5ef5ef75baa | 32,008 |
def check_cutoffs(cutoffs):
"""Validates the cutoff
Parameters
----------
cutoffs : np.ndarray or pd.Index
Returns
----------
cutoffs (Sorted array)
Raises
----------
ValueError
If cutoffs is not a instance of np.array or pd.Index
If cutoffs array is empty.
... | db0a3a477b27883aa1d29486083cf3e6c993e021 | 32,009 |
def hook(images, augmenter, parents, default):
"""Determines which augmenters to apply to masks."""
return augmenter.__class__.__name__ in MASK_AUGMENTERS | 0e1e6589bc37d90b0ac8249e11dee54140efd86a | 32,010 |
def _get_videos(course, pagination_conf=None):
"""
Retrieves the list of videos from VAL corresponding to this course.
"""
videos, pagination_context = get_videos_for_course(
str(course.id),
VideoSortField.created,
SortDirection.desc,
pagination_conf
)
videos = li... | 21774a476424b8f68f67c368fb72343fb9cfd552 | 32,011 |
import torch
def sample_stacking_program(num_primitives, device, address_suffix="", fixed_num_blocks=False):
"""Samples blocks to stack from a set [0, ..., num_primitives - 1]
*without* replacement. The number of blocks is stochastic and
can be < num_primitives.
Args
num_primitives (int)
... | f5927edc11b2e20fcfb4b19b6ecddd92ba911841 | 32,012 |
def get_mmr_address(rn, m0m1):
"""Return address of an memory-mapped register and its size in bits.
"""
mmr_map = { 0b00 : 0xf0400,
0b01 : 0xf0500,
0b10 : 0xf0600,
0b11 : 0xf0700 }
address = mmr_map[m0m1] + (rn * 0x4)
size = get_register_size_by_addres... | 53b92051d7ac64f5e288a121dae7e764166c9d2e | 32,013 |
import re
def number_of_a_char(element: Element):
"""
get number of linked char, for example, result of `<a href="#">hello</a>world` = 5
:param element:
:return: length
"""
if element is None:
return 0
text = ''.join(element.xpath('.//a//text()'))
text = re.sub(r'\s*', '', text... | 9d1394552b740844aadacc3fe3b2f802b698c18a | 32,016 |
def preprocessing_fn(batch):
"""
Standardize, then normalize sound clips
"""
processed_batch = []
for clip in batch:
signal = clip.astype(np.float64)
# Signal normalization
signal = signal / np.max(np.abs(signal))
# get pseudorandom chunk of fixed length (from SincN... | 25ce4a077027239126d02b62e93ca0a3bcb15b5e | 32,017 |
def elast_quad9(coord, params):
"""
Quadrilateral element with 9 nodes for classic elasticity
under plane-strain
Parameters
----------
coord : coord
Coordinates of the element.
params : list
List with material parameters in the following order:
[Young modulus, Poisso... | c27bae77ca54a3a370ccdac5b5550f73cb121d9a | 32,018 |
from typing import Union
from pathlib import Path
def peek(audio_file_path: Union[str, Path], output: str = "np"):
"""
Returns a tuple of audio data and its sampling rate
The audio data can be a numpy array or list
"""
data, sr = sf.read(audio_file_path, dtype="float32")
data = data.transpose(... | 30b47c77ab92cf0a544d84605204261c899f9e9a | 32,019 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.