content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def runline(y, n, dn):
"""Perform local linear regression on a channel of EEG data.
A re-implementation of the ``runline`` function from the Chronux package
for MATLAB [1]_.
Parameters
----------
y : np.ndarray
A 1-D array of data from a single EEG channel.
n : int
Length o... | f1ab5b972004e838ee34f6e2bb1e43335eddd73e | 3,617,164 |
def ConsecutiveArrays(arr, step=1):
"""
Finds consecutive subarrays satisfying monotonic stepping with step in array.
Returns on each array element the island index (starting from 1).
:param list colors: colors to be included in the colormap
:param string name: name the colormap
:returns: f... | e9bb07ac1b3c3d527136b19bf9db8f2e5b33dd6c | 3,617,165 |
def normalize(X : np.ndarray, feature_axis = 1) -> np.ndarray:
"""
对数据进行归一化 \n
:param feature_axis: 各特征所在的维度 \n
feature_axis = 1 表示每列是不同的特征 \n
"""
if not feature_axis:
X = X.T
_sum = np.sum(X, axis = 0)
for j in range(len(_sum)):
if _sum[j] > 1e-100:
X[:, j] /= _sum[j]
else:
X[:, j] = 1 / X.s... | 47cd365d4a112d1cc2d014374bb7a1b24c8f425c | 3,617,166 |
import io
def table_to_image(
data: pd.DataFrame, titile: str = ""
) -> io.BytesIO:
"""Create image with rate table.
"""
dia = data.plot()
if titile:
ax.set_title(titile)
buffer = io.BytesIO()
img = dia.get_figure()
img.savefig(buffer)
buffer.seek(0)
return buffer | bd308fbd916cf6f3285c52403302c22d986b57c4 | 3,617,167 |
def update_item(id: str,
item_update: ItemUpdate = Body(
..., example=ItemFactory.updated_mock_item)):
"""
update an item
"""
item = item_service.get_item(id)
if not item:
raise HTTPException(status_code=404, detail="Item not found.")
return item_servi... | 60edc4b33eb7d1661e0c9e94e5cab0ba0f7dd91a | 3,617,168 |
from bs4 import BeautifulSoup
import requests
def fetch_events_ldi(base_url='https://ldi.upenn.edu'):
"""
Fetch events from Leonard & Davis Institute, https://ldi.upenn.edu
"""
events = []
page_soup = BeautifulSoup(requests.get(
urljoin(base_url, '/events')).content, 'html.parser')
tr... | 599bf4284ddc039c70daa4ae16b71456bb764e66 | 3,617,169 |
def splitdata_n_max(data, n_max):
""" split N into n_max - sized bins """
data = np.array(data).flatten()
N = len(data)
data_splited = []
for i in range(np.int64(np.ceil(N/n_max))):
start = i*n_max
stop = np.min([(i+1)*n_max, N])
data_splited.append(data[start:stop])
ret... | 9054ad90d632cc256e18ad90d0e02591cfc59ca3 | 3,617,170 |
def comments_search(posts,comments):
"""
:param posts1:Список со словарями, в которых данные публикаций
:param comments:Список со словарями, в которых данные комментариев
:return:Измененные список posts, с комментариями к постам с статусом sponsored
"""
for post in posts:
post['comms'] ... | e5d57854693de563b9a5beb7ca5f5e40b8d68d5a | 3,617,171 |
import torch
def update_weights(batch, batch_dic):
"""
Readjust weights so they sum to 1.
Args:
batch_dic (dict): Dictionary with extra conformer
information about the batch
batch (dict): Batch dictionary
Returns:
new_weights (torch.Tensor): renormalized weights
... | 90131e119e9d2cb849b79346fd2f5f86411f652b | 3,617,172 |
def scaled_dot_product_attention(q, k, v, mask):
"""Calculate the attention weights.
q, k, v must have matching leading dimensions.
k, v must have matching penultimate dimension, i.e.: seq_len_k = seq_len_v.
The mask has different shapes depending on its type(padding or look ahead)
but it must be br... | 2c239f141ac7aad901c2f2e597f228af4f0e4838 | 3,617,173 |
def get_client_lease_status_raw(client_row=None):
"""list the raw status of client leases."""
theRawLeaseStatus = u'UNKNOWN'
try:
# should probably move to config file
filepath = str("/var/lib/misc/dnsmasq.leases")
if (utils.xisfile(filepath) is True):
theRawLeaseStatus = utils.readFile(filepath)
except Ex... | ae139d824103ef2e96b0eb4f19814d8502c30fa1 | 3,617,174 |
def __edfdv__(fp, e, kv, dt):
"""
:param fp:
:param e:
:param kv:
:param dt:
:return:
"""
return np.exp(-1j * kv * dt * e[:, None]) * fp | 0ceff5470440e8fdc2d49b4b8d9824a3f5ccd660 | 3,617,175 |
def design_pts_from_ranges(ranges: np.ndarray,
thetas: np.ndarray):
"""
Args:
ranges (np.ndarray, shape=(C,), dtype=np.float32): range per camera ray
thetas (np.ndarray, shape=(C,), dtype=np.float32): in degrees and in increasing order in [-fov/2, fov/2]
... | 667c4afa9f8546caaabf8414ddc116f36d020a5d | 3,617,176 |
import inspect
def _dict_as_called(function, args, kwargs):
""" return a dict of all the args and kwargs as the keywords they would
be received in a real function call. It does not call function.
"""
names, args_name, kwargs_name, defaults = inspect.getargspec(function)
# assign basic args
... | e4d3ce1f1190b3a72d79235a6aa42ae0605d6737 | 3,617,177 |
import torch
def idcst2(x, expk0, expk1):
"""compute inverse discrete cosine-sine transformation
This is equivalent to idxct(idxst(x)^T)^T
"""
if x.is_cuda:
output = dct_cuda.idcst2(x.view([-1, x.size(-1)]), expk0, expk1)
else:
output = dct_cpp.idcst2(x.view([-1, x.size(-1)]), expk... | c5eacfc656a879d902e062d3fc0ff218616c0155 | 3,617,178 |
from typing import Any
def is_match(pattern: Any, expr: Expr) -> bool:
"""Returns whether or not an expression matches a pattern."""
if isinstance(pattern, Star):
raise ValueError('`Star` pattern must be inside of a sequence.')
for _ in matcher(pattern)(expr, {}, id_success):
return True
return False | 6bf59437256fdf260c38a06dad8ad0cc71ffb13c | 3,617,179 |
def add(a, b):
"""The add function.
Args:
a (Union[:class:`~taichi.lang.expr.Expr`, :class:`~taichi.lang.matrix.Matrix`]): A number or a matrix.
b (Union[:class:`~taichi.lang.expr.Expr`, :class:`~taichi.lang.matrix.Matrix`]): A number or a matrix.
Returns:
sum of `a` and `b`.
"... | 514592483910ee75730b2636e78c6b50a7b18125 | 3,617,180 |
def create_authy_user(email, country_code, phone):
"""
Creates a user with the Authy API
:param email: email to be associated with the user.
Used by the API for account recovery
:param country_code: country code for the phone number
:param phone: national format phone number
:returns: ... | fb551badbe633bf839eee687c052806e093abcd6 | 3,617,182 |
import urllib
def check_remote_vcs():
"""
Check if the vcs-url is reachable.
Returns
-------
check_result: bool
Result for the remote vcs to check.
"""
try:
status = urllib.request.urlopen(VCS_SETTINGS['url']).getcode()
check_result = True if status == 200 else Fal... | 7c37a99d8630be680ba3ec28caefc2a3865afae9 | 3,617,183 |
import json
def jsonify(*args, **kwargs):
"""Improved json response factory"""
indent = None
status = kwargs.pop('_status', 200)
mime = kwargs.pop('_mime', 'application/json')
# Check for an argument passed, otherwise dict() the kwargs
data = args[0] if args else dict(kwargs)
# Format... | 49a5eb2d2df4ea8af62df8ae6e721b9c870d4c1b | 3,617,184 |
def pull_data_for_tickers(
tickers,
tiingo_api_key,
start_date=None,
end_date=None,
save_to='',
check_existing=True,
):
"""
Persist all the available data for each of the ticker in ticker_list
"""
n_tickers = len(tickers)
bar = progressbar.ProgressBar(
maxval=n_ticke... | 024e55db0be03375ecf8cc4fb9dcde9c5089c9ac | 3,617,185 |
def edmonds_karp(graph, source, destination):
"""Find maximum flow between two vertices in a weighted graph.
Args:
graph: Undirected or directed graph where every edge has property
'capacity' that indicates how many units may flow through it.
source: Source vertex.
destinati... | 80e1397004a676c6ef1673b66d90d6000724df7a | 3,617,186 |
import ast
def _get_all_names(tree):
"""
Return list of all words.
:param tree: _ast.Module object
:return: list with words
"""
return (node.id for node in ast.walk(tree) if isinstance(node, ast.Name)) | 2b7f39af8bbe0c253d0206bcc86a8a0d05c7686e | 3,617,187 |
def rot_mat2rot_angle(rot_mat):
""" Return the angle corresponding to the given 2D rotation matrix."""
return np.arctan2(rot_mat[1, 0], rot_mat[0, 0]) | 770eb09b0124d5ca20cc08721e5cbd96a1df7785 | 3,617,189 |
def normalize(array):
"""
Normalize a 1d numpy array between [0,1]
Parameters
----------
array: ndarray
the array to normalize
Returns
-------
ndarray
the normalized array
"""
ptp = np.ptp(array)
if ptp != 0:
return (array - np.min(array)) / np.ptp(... | 96ebf4326938026191e857f1da8495dcae84c465 | 3,617,190 |
def heatmap(matrix, highlight_index=None, labels_left=None, labels_right=None, path=None):
"""
:param matrix: (n x n)
:param highlight_index: (n x 2)
:return:
"""
fig, ax = plt.subplots()
ax = sns.heatmap(matrix, ax=ax, linewidths=.5, cbar=False,
yticklabels=["%.1f" % l ... | ef1dbfff0791bed94b27f6f84542cb9c943a7628 | 3,617,191 |
def get_dataset(config, key, *,
num_tasks):
""""Get dataset."""
if config.env.name == 'gym' or config.env.name == 'random':
return MDPDataset(config, key, num_tasks=num_tasks)
elif config.env.name == 'pw':
return DistributedSampleDataset(config, key, num_tasks=num_tasks)
else:
raise ... | c5597c81e6e4021601dbb87fac1adae21c92892f | 3,617,193 |
def km2_by_state(list_of_park_dicts):
"""
This function takes a list of national park data (e.g. the returned value from
<read_csv_file>), and returns a new dictionary that contains the summed
area (in kilometers squared) of national parks in each state. The output
dictionary should have the format:... | d513f4b46944964cd52ad3c751a4022606182704 | 3,617,194 |
def getRuleCount( lstRules, policy_name ):
"""
This function return the rule count for a given policy
indicated by policy_name
Parameters:
- IN : 1. List containing all the rules
2. Name of the policy
- Out: # of rules in the policy.
"""
count = 0
for x in lstRules:
if x.split(',')[0] == poli... | b4956b0a5af91f1834ee4d463414df2cc02c8796 | 3,617,195 |
def send_format(catfact):
"""
Format's the catfact into a the message to send content string
"""
return """
Thank you for subscribing to CatFacts™
Did you know:
```
{}```
Type "UNSUBSCRIBE" to unsubscribe from future catfacts.
""".format(catfact) | 208605f35db4505bb0037cae23088c89e6b1475f | 3,617,196 |
def build_d_layer(flow, name, num_outputs=3):
"""
arXiv:1703.10593v1
d64
"""
with tf.variable_scope(name):
weights_initializer = tf.truncated_normal_initializer(stddev=0.02)
flow = tf.contrib.layers.convolution2d(
inputs=flow,
num_outputs=num_outputs,
... | 472a904141af6dde2ec762ccc0580e351a5920ca | 3,617,198 |
import logging
def drop_infreq_labels(seqs, labels):
"""Filter out infrequent labels."""
label_vocab, label_counts = np.unique(labels, return_counts=True)
is_dropped = {}
for i in xrange(len(label_vocab)):
logging.info('Found label %s, with count %d.', label_vocab[i],
label_counts[i])
... | 4f4567c03f84c92aab7d173c8d446eb857e361da | 3,617,199 |
def show_function_info(func):
"""関数情報表示用デコレータ関数
:param func: 対象関数
:return: wrappaer関数
"""
@wraps(func)
def wrapper(*args, **kwargs):
"""内部ラッパー関数
"""
print('--------------------------------------------------------------')
print(f'Name: {func.__name__}')
pri... | ac5e4ad9bdb09a9aed02aabae7589dda6b6b2a26 | 3,617,200 |
def datacite_format_contributors(contributors):
""" Format a list of contributors to match the datacite schema
:param contributors_list: list of OSFUsers to format
:return: formatted json for datacite
"""
creators = []
for contributor in contributors:
name_identifiers = [
{
... | 39f8be1e83c5bc0b3fccd568c16206e093878f39 | 3,617,201 |
def get_drought_stress_days(culture_id, trial_dates, climate_data, soilVolume,
availMoistCap, precipitation, irrigation,
stress_threshold=10.0, flowerDate='2012-07-01'):
"""
calculates the number of drought stress days before and after the flowering
da... | bc91a456a8bd28219c8e79d8519e8696be516d54 | 3,617,202 |
import torch
import time
def ppo(env_fn, actor_critic=MLPActorCritic, ac_kwargs=dict(), seed=0,
steps_per_epoch=4000, epochs=50, gamma=0.99, clip_ratio=0.2, pi_lr=3e-4,
vf_lr=1e-3, train_pi_iters=80, train_v_iters=80, lam=0.97, max_ep_len=1000,
target_kl=0.01, logger_kwargs=dict(), save_freq=1... | 68d67eb84c013864b218fd5375ab13e557571c07 | 3,617,203 |
def errorhandler(e):
"""Handle error"""
return apology(e.name, e.code) | 5e45b0a36f3d2b1b8c8b87c9e23802c490d73d63 | 3,617,204 |
from google.colab import output
def _detect_light_colab_theme() -> bool:
"""Detect if it's light theme in Colab."""
try:
get_ipython # type: ignore
except NameError:
return False
ipython = get_ipython() # noqa: F821
if "google.colab" in str(ipython.__class__):
try:
... | e4f2f6096bb65ad6d67accf3f9d4b6130203c93c | 3,617,206 |
def effect_from_model(model, ref, ref_rc, alt, alt_rc, methods, mutation_positions, out_annotation_all_outputs,
extra_args=None, **argv):
"""Convenience function to execute multiple effect predictions in one call
# Arguments
model: Keras model
ref: Input sequence with the ... | 27c528da568d257d129ae219f504ecf4f23b93f2 | 3,617,207 |
def list_semantic_shift_tokens(snapshot_emb):
"""
Check which tokens have undergone a continuous semantic shift over time (ignoring new words).
Inputs:
- snapshot_emb [dict: {str: SimplePretrainedEmbeddings}]: embedding snapshots for all snapshot dates (as computed with compute_emb_snapshots)
... | 528d0054d152c094ae1f42870cc8499ae39fe44b | 3,617,208 |
from typing import Concatenate
def inception_resnet_block(x, scale, block_type, block_idx, activation='relu'):
"""Inception-ResNet block.
"""
if block_type == 'block35':
branch_0 = conv2d_bn(x, 32, 1)
branch_1 = conv2d_bn(x, 32, 1)
branch_1 = conv2d_bn(branch_1, 32, 3)
bra... | 67f13c601b54f68a4c09366832d68b91c9a22244 | 3,617,209 |
def get_frame_acc(seconds_fr,num_frame,fs,samples_per_channel_in_frame,list_acc_frontiers,acc_time):
"""
Returns the index of the accumulation period corresponding to this frame, the relative number of the frame into the acc period,
and the seconds corresponding to the first sample.
Parameters
... | f829b889f1f42d1cf4184c7c2761bff6a64aec09 | 3,617,210 |
def Search_Form():
"""Render the search form"""
return render_template("search.html") | ce1a6c5c0c6c61fae36b10472f635c2ab7be85d4 | 3,617,211 |
def function_mask_wrapper(func, x0, mask, arg, kwarg, x):
"""
Wrapper function for Python function using a mask.
To be used with partial:
`obj = partial(function_mask_wrapper, func, x0, mask, arg, kwarg)`
This allows then calling obj with only the non-masked parameters:
`fx = obj(x)`
... | da49cbede225ab6b457893a7d5aba6bbe5f06d26 | 3,617,212 |
def filt_velocity_boundary(
x, y, melt=None, blon=186, blat=-82.68, dlon=13, dlat=0.06, return_index=False
):
"""
params for 3km grid: blon=186, blat=-82.68, dlon=13, dlat=0.06
"""
X, Y = np.meshgrid(x, y)
lon, lat = transform_coord(3031, 4326, X, Y)
lon[lon < 0] += 360
(ii, jj) = np.whe... | 3dea3c764f07cef71f151b860b0739bfe6e7f41f | 3,617,213 |
def generateRules(L, supportData, minConf=0.7):
"""
Generate rules of (k)-itemset implied by (k-1)-itemset
:param L: list of all Lk
:param supportData: dict of support data value
:param minConf: minimum confidence of rule interested in
:return: list of all the rules implied by L
"""
rule... | a0d4a1e0d36f7e7bb5ef6efe2577926394ea255b | 3,617,214 |
def get_pronoun(pronoun, gender='MALE', sep='_'):
""" Gets the correct gender pronoun
Arguments:
pronoun {str} -- HE_SHE pronoun that needs to be converted
Keyword Arguments:
gender {str} -- [description] (default: {'MALE'})
sep {str} -- [description] (default: {'_'})
... | a9f3d7aa3f09af305ac110e1cc8c9ac977051d8b | 3,617,215 |
def is_fill_compute_el(obj):
"""Object contains executable methods 'fill' and 'compute'."""
return hasattr(obj, 'fill') and hasattr(obj, 'compute') \
and callable(obj.fill) and callable(obj.compute) | 18f1825947852f6dd307e0a2ab07c8d95f213151 | 3,617,216 |
def addstr(str1, str2):
"""Concatenate strings str1 & str2"""
return str(str1) + str(str2) | 209c932bca262a458013afcafd6899e6cf02b3b6 | 3,617,217 |
def ampfitfn1_1d(coeffs,x):
""" PN inspired ampitude fit a0 + a1*nu**a2"""
a0, a1, a2 = coeffs[:3]
nu = gwtools.q_to_nu(x)
return a0 + a1*nu**a2 | 0894211f617746aaddcc0e8975495969204ef817 | 3,617,218 |
def Ve_correct(Ve, Ig, Ic, Rprotect):
"""Because we use a resistor connected in a serries on the emitter circuit
in order to stabilize emission current, we need to correct voltage dropping
at the resistor, which is called as "Protection Resistor" or somthing like that.
Inputs -- Ve, Ig, Ic, Rprotect
... | 377122accd5cb173daef7487abfdbf86353a7819 | 3,617,219 |
def getSph2CartTransfArr(r):
"""(Array version) Compute the transformation matrix from a spherical basis to a Cartesian
basis at the field point given by the input 'r'.
The output 'transf_sph2cart' is defined such that:
[[v_x], [v_y], [v_z]]=transf_sph2cart*matrix([[v_r], [v_phi], [v_theta]])."""
... | e46efc25cd733bd49b6cf18add85754107263d2f | 3,617,221 |
def plot_pauli_transfer_matrix(ptransfermatrix, ax, labels, title):
"""
Visualize the Pauli Transfer Matrix of a process.
:param numpy.ndarray ptransfermatrix: The Pauli Transfer Matrix
:param ax: The matplotlib axes.
:param labels: The labels for the operator basis states.
:param title: The ti... | 1dc8d7ff2ef85d66d7718e38993f3f0625b8f160 | 3,617,222 |
def group_anagrams1(words : list[str]) -> list[str]:
"""
O(N logN ) solution.
Args:
words (list[str]): words
Returns:
list[str]: sorted by anagrams
"""
def get_word_value(word):
value = 0
for letter in word.lower():
if letter == ' ': c... | d55679c1d04f18ae29daade739e97bed98e9fc40 | 3,617,223 |
def create_camera_ray_frame(K, T, size=0.1, color=[0, 0, 1]):
"""
K: 3x3
T: 4x4
"""
T, K, color = np.asarray(T), np.asarray(K), np.asarray(color)
sanity.assert_T(T)
sanity.assert_K(K)
sanity.assert_shape_3(color, "color")
# Pick 4 corner points
# Assumes that the camera offset i... | a8695c502a43d16b7ed4b6e151e45fa269e2a02d | 3,617,224 |
import difflib
def get_name_similarities(name_pairs):
"""Get char LCS similarity for each signature pair."""
return [difflib.SequenceMatcher(None, sig1, sig2).ratio() for sig1, sig2 in name_pairs] | a124e36387d4a72968985967fde0c48dc4d3b21d | 3,617,225 |
def _get_resource_image_registry_namespace(resource_type):
"""
Get image_registry_namespace by resource type.
:param resource_type: Type of resource (job, function, model, stream)
:return: str default name prefix by resource type when resource type is defined, else None
"""
if... | e0aa13acf0f12e12593a7cda3e6239bb17190519 | 3,617,227 |
import ast
from typing import List
from typing import Tuple
def _get_sim203(node: ast.UnaryOp) -> List[Tuple[int, int, str]]:
"""
Get a list of all calls where an unary 'not' is used for an in-check.
"""
errors: List[Tuple[int, int, str]] = []
if (
not isinstance(node.op, ast.Not)
... | c4577fac32d4b3bd88092464ea993aa4cd5d02ea | 3,617,228 |
def _get_key_and_value(field_string):
""" Extracts the key and value from a Java Thrift field string.
For example: "ids:[1,2,3]" --> "ids", [1,2,3]
:param field_string: the Java Thrift field string
:type field_string: str
:returns: a tuple of key and value of the represented field
:rtype: tupl... | be87277bc5dadb49ecb82d217d7774102a4b3296 | 3,617,229 |
def RemoveOutliers( array, max_deviations ):
"""
Function used to remove outliers from an array.
Args:
array (numpy.array): the interested array.
max_deviations (int): the maximum number of std.
Returns:
numpy.array: the array without outliers.
Testing:
>>>... | 5c123104b6fe337e967196407c82d24d637472b5 | 3,617,231 |
def to_spark(spark_session):
"""Convert pandas df to spark."""
def _(df: pd.DataFrame, *args, **kwargs):
return spark_session.createDataFrame(df, *args, **kwargs)
return _ | 04b4045f01dc0cc84f62df64e62627ea87e23138 | 3,617,232 |
def nonconserved_bond_stereo_keys(ste_tsg, check=True):
""" Determine bond stereo centers which are not conserved by the reaction.
This includes bonds which are stereogenic for the products but not for the
reactants ("created" stereo centers) and bonds which are stereogenic for
the reactants but not fo... | 3138553045dc4cbc00fd696b58cc59478b895f82 | 3,617,233 |
def available_classifier_paths(*restrictions):
"""Returns all classifier paths with given restrictions.
Args:
restrictions: Strings that should be included in the paths as :class:`str`.
Returns:
The path of the classifiers as :class:`list` of :class:`pathlib.Path`.
"""
paths = list... | 0a40adcdbd57e4c9eb361b21389059484bbffbee | 3,617,235 |
def createHTMLTable(matrix, batches, groups, caption=None, base_indent=8, indent=4, column_labels=None, skip_base_column=False):
"""
Givena a matrix, and a suitable column and row names, create an HTML table of the data
values in the matrix.
"""
if column_labels is None:
column_labels = {}
... | cf814a21c21276481ac14db87129206cb72aaf91 | 3,617,236 |
from typing import Union
from typing import List
from typing import Iterable
def get_matched_headers(
headers: CaseInsensitiveDict, match_headers: Union[ParamList, bool]
) -> List[str]:
"""Get only the headers we should match against as a list of ``k=v`` strings, given an optional
include list.
"""
... | 4a0efbf77e808827dd44b6abe4a9e1f90fb86cc3 | 3,617,237 |
def parse_predictions_dict(predictions, num_growths):
"""Parses predictions dictionary to remove graph generated suffixes.
Args:
predictions: dict, predictions dictionary directly from SavedModel
inference call.
num_growths: int, number of model growths contained in export.
Ret... | fbb1789cf317e7c4d0015271bf8690ea4bddf0ef | 3,617,238 |
def normalized(a, axis=-1, order=2):
"""Utility function to normalize the rows of a numpy array."""
l2 = np.atleast_1d(np.linalg.norm(a, order, axis))
l2[l2==0] = 1
return a / np.expand_dims(l2, axis) | 69530dab7190dd35a132cbf398abf668d854e62e | 3,617,239 |
import pathlib
def allowed_task_name(name: str) -> bool:
"""Determine whether a task, which is a 'non-core-OSCAL activity/directory is allowed.
args:
name: the task name which is assumed may take the form of a relative path for task/subtasks.
Returns:
Whether the task name is allowed or ... | 11d1a65ef21439919e728557e72af9ae6e22dc94 | 3,617,242 |
async def get_run_command(
commandId: str,
engine_store: EngineStore = Depends(get_engine_store),
run: Run = Depends(get_run_data_from_url),
) -> PydanticResponse[SimpleBody[pe_commands.Command]]:
"""Get a specific command from a run.
Arguments:
commandId: Command identifier, pulled from ro... | f09dc35f1bef2701f4c4065da6c297122d229022 | 3,617,244 |
def is_fully_paid(cart: Cart, taxes, discounts):
"""Check if checkout is fully paid."""
payments = [
payment for payment in cart.payments.all() if payment.is_active]
total_paid = sum([p.total for p in payments])
cart_total = cart.get_total(discounts=discounts, taxes=taxes).gross.amount
retur... | c6fb68ddc65462a7fb6d8b7ed2b263d973a5e8f7 | 3,617,245 |
def rescale_bbox(annot: namedtuple) -> namedtuple:
"""Return rescaled coordinates of bbox in the image size.
YOLO requires the bounding box coordinates should be
(relative_center_x, relative_center_y, relative_w, relative_h)
:param namedtuple annot: holds each vertex absoulte positions.
:ret... | 476117ebe8650c12819e8887f173fc06b04b3551 | 3,617,246 |
def uu_get_price():
"""
(可拿到当天数据)
获取股票历史交易数据,可以通过参数设置获取日k线、分钟k线数据。获取数据的基本属性如下
:param :security: 一支股票代码或者一个股票代码的list
start_date: 字符串或者[datetime.datetime]/[datetime.date]对象, 开始时间, 默认是’2015-01-01’. 注意:
当取分钟数据时, 时间可以精确到分钟, 比如: 传入 datetime.datetime(2015, 1, 1, 10, 0, 0) 或者 '2015-01-01... | c2b9af1352edda21c542ec9476102eac5d70c49f | 3,617,247 |
def profile_article(document):
"""
Temporary, profile the article by folder names in test data set
In real code we still want this to return the same values
"""
soup = parser.parse_document(document)
# elife id / doi id / manuscript id
fid = parser.doi(soup).split(".")[-1]
# volume
... | 12904080aecae79f37bbef8db38ee23a11ae2a44 | 3,617,248 |
def get_distribution(dataframe, target_column):
"""
method to find the distribution of a certain column in a given dataframe.
Shows the generated visualization to the user.
:param dataframe:
:param target_column: column upon which the distribution needs to be applied
:return: dictionary of uniqu... | 65b71aa375bb7b1ca4af6ddd03322cdd672e98d0 | 3,617,249 |
from typing import Union
def high_pass_2_pole(candles: np.ndarray, period: int = 48, source_type: str = "close", sequential: bool = False) -> \
Union[
float, np.ndarray]:
"""
(2 pole) high-pass filter indicator by John F. Ehlers
:param candles: np.ndarray
:param period: int - defa... | ec2765b8537f1fb47c52d2f82946c05514191505 | 3,617,250 |
def watchlist(request, listing_id):
"""Add on watch list, when watch list button is click"""
if request.method == "POST":
listing = get_object_or_404(Listing, pk=listing_id)
request.user.watch_listing.add(listing)
return HttpResponseRedirect(reverse("watchlist_view"))
return render(r... | c0912735510b18741646db491248a7201c439e0b | 3,617,252 |
def stat(hdfs_url):
"""
stat the hdfs URL, return None if does not exist.
Returns a dictionary with keys
filename: base name of file
blocks: number of blocks
block_size: size of each block
mod_date: last modification
replication: number of copies in hdfs
"""
... | 76edcdb4dac9646f7c790df69fd9e5e8c0a4c02b | 3,617,253 |
def lerp(a, b, x):
"""Linear interpolation."""
return a + x * (b - a) | 6f82114a774ed4e9c8da90649fe0c67c996754bb | 3,617,254 |
from typing import List
def create_feeds(length: int = 10) -> List[Feed]:
"""
Generate list of dummy feeds
:param length: length of list
:return: list of dummy feeds
"""
return rands(Feed, length) | fe26576c2c3f5df1942593bdef767a217c03ada0 | 3,617,255 |
import json
def render_template(handler):
"""Render a set of templates against a dataframe and formhandler actions on it."""
orgdf = get_original_df(handler)
payload = json.loads(handler.request.body.decode('utf8'))
fh_args = payload['args']
templates = payload['template']
df = pd.DataFrame.fr... | 17fea9d133b18f50d18e9ae738c9d5c95b160a48 | 3,617,257 |
def logbeta(*args):
"""
Log multivariate beta function.
args
----
*args : arguments
returns
-------
float
"""
return loggamma(args).sum() - loggamma(sum(args)) | 1c8e93906fed2421c63289a883aca7baa6e4cf3c | 3,617,258 |
def a3() -> rank.Arborescence:
"""Get the third SA of case in [camerini1980ranking]."""
g = nx.DiGraph()
g.add_edge("b1", "b4", label="e2", weight=1)
g.add_edge("b3", "b2", label="e4", weight=10)
g.add_edge("b4", "b3", label="e6", weight=8)
res = rank.Arborescence(g)
return res | 8456001acd74d62d812362ccd2ada3869ac62661 | 3,617,259 |
import torch
def _softmax(x, implicit=False):
"""Safe softmax (with implicit class)"""
if implicit:
x = _pad_zero(x)
x = torch.softmax(x, dim=1)
return x | f79c556b9910a96a615b3533d365639fca4f5b6c | 3,617,261 |
def get_word_pattern(word: str) -> str:
""" Get word pattern.
This pattern is useful to break substitution cipher.
:param word: Word to get pattern for.
:return: Word pattern.
"""
# There is no ordered set type in Python, but we can get that behaviour using
# dict keys because since python... | ce81624bd3690c2037c5b570e19ba2340907a24a | 3,617,262 |
def noll_to_zern(j):
"""
Convert from linear Noll index to a tuple of Zernike indicies.
:param int j: Linear Noll Index
"""
if (j < 0):
raise ValueError("Noll indices start at 0. j={:d}".format(j))
n = np.ceil((-3 + np.sqrt(9 + 8*j))/2)
m = 2*j - n*(n+2)
if not int... | 4006426f5d367318c1ab5256e5882fa8198a348d | 3,617,264 |
import time
def print_menu(main_list_of_contacts, p_id_number_itterate): # this takes as a parameter "main_list_of_contacts", which is an instance of the class ContactList.
"""The main interface where the user interacts with their contact list. Allowable actions are add, edit, delete, or list."""
user_selec... | 786366840992a01980f48c1a8337a268d522011b | 3,617,265 |
def LF_radiograph_view(c):
"""
Check if the term view occurs between the pain and anatomy mentions
in a candidate
:param c: pain-anatomy candidate
:return: -1 if True, 0 otherwise
"""
between_tokens = list(get_between_tokens(c))
between_phrase = ' '.join(between_tokens)
v = 'view'... | 9f7b8bd027945ddc1a3b1127edb54c0702cc7405 | 3,617,266 |
def compute_centroids(x_mat: ndarray, idx_vec: ndarray):
"""
根据之前的聚类中心下标和样本,计算移动后的平均聚类中心值。
:param x_mat: 特征向量组,行数 m 表示样本数,列数 n 表示特征数
:param idx_vec: 聚类中心下标
:return: 新的聚类中心
"""
x_mat = __t.r2m(x_mat)
idx_vec = __t.c2r(idx_vec)
m, n = x_mat.shape
k = np.max(idx_vec) + 1
cent... | 5a6b059738e4364c7dbc5821c6d01dcea6e99158 | 3,617,267 |
def R_hill2(rho_p, P,e=0):
"""
compute hill radius of a planet from its density rho_p in g/cm3 and period in days.
Returns
--------
R-hill: array-like;
radius of hill sphere in unit of planetary radius
"""
G = 498.23383
return (1-e)*(G*rho_p*P**2/(9*np.pi))**(1/3) | 467ea02f4ad21afbeb28dd4dd209c30ce9a750d5 | 3,617,268 |
def dir_checked():
"""The absolute path of the checked homeworks.
This path is valid on the storer machine."""
return abspath('checked') | 52fdfcdf55860cd7bb1ee325384f2c60d6c258a7 | 3,617,269 |
def color_diff(rgb1, rgb2):
"""
Calculate distance between two RGB colors. See discussion:
http://stackoverflow.com/questions/8863810/python-find-similar-colors-best-way
- for basic / fast calculations, you can use dE76 but beware of its problems
- for graphics arts use we recommend dE94 and perha... | 056f0354d102802f612e3fa090df45d7d2d9e1b4 | 3,617,270 |
def clientid_to_accountid(clientid):
"""
Transform Clientid To Accountid
Parameters:
clientid : int
Returns:
None
"""
for i in _ba.get_game_roster():
if i['client_id'] == clientid:
return i['account_id']
return None | 4ee4ffe92fedf078b73138b4d7382982ef4459eb | 3,617,271 |
def get_cube(ds, edge_um=1000, lev=0, center_yt=None):
"""
Extract a cube of raw data from 3D FLASH yt dataset.
Uses yt's "covering grid" method to ensure losslessness.
Replaces get_magnetic_field. This will take the center, edge length,
AMR Level, and data set, and it will return a co... | efd286d8b0b80976f2f6a8a15e343459b94577aa | 3,617,272 |
def tf2ss(sys_):
"""
Convert transfer function model to state space model.
:param sys_: the system
:type sys_: TransferFunction
:return: corresponded transfer function model
:rtype: StateSpace
"""
try:
nump = np.poly1d(sys_.num)
denp = np.poly1d(sys_.den)
except Att... | 7296d5896ff55402c7cb9aa4bfc2262be86a0823 | 3,617,273 |
def get_c_phi(rule,parses,psg,bigrams=None,start='S'):
"""wrapper
Arguments
rule : (lhs,rhs)
parses : list of (operation string, bigram string) pairs
psg : operations PSG
bigrams: bigram markhov chain
start : start category
"""
# get the charts and bigrams from the parses
... | d8e9d6b4b454e9304572920b5c5032e3a8927992 | 3,617,274 |
def softmax_2D(x, use_float64=False):
"""Compute softmax values for each row in x.
Parameters:
-----------
x: a 2D matrix
each row represents a set of entries over which a softmax
should be applied
Returns:
-------
normalized softmax entries, where each row is normalized usin... | e8d221a7073e1902d521cea3555f981176b2a665 | 3,617,275 |
def _run_op_1(task):
"""Test function using the function decorator."""
return task.run() | b2d3b220dcd1371f9140859b4ffe025f8231b4da | 3,617,276 |
from typing import Type
from typing import Optional
from typing import Union
def _wrap(
native_estimator: Type[T_NativeEstimator] = None,
*,
name: Optional[str] = None,
base_wrapper: Optional[Type[EstimatorWrapperDF[T_NativeEstimator]]] = None,
native_estimator_bound: Optional[type] = None,
ba... | a056b5f6a5509354e9b56b8837f700548d171bd3 | 3,617,278 |
import typing
def create_local_gateway_routes_for_peers(
client: VNS3Client, local_network: str, peer_ips: typing.List[str]
):
"""Create route to local underlay gateway for IPs. This is commonly done for explicit routes
to VNS3 peers.
Arguments:
client {VNS3Client}
local_network {s... | 0a24202f6f38b5577be12b12afeb2efa48499e76 | 3,617,279 |
def bagnet9(**kwargs):
"""
BagNet-9 model from 'Approximating CNNs with Bag-of-local-Features models works surprisingly well on ImageNet,'
https://openreview.net/pdf?id=SkfMWhAqYQ.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
... | 83c9eaaee3100fc54c369958d70aa9d19bd6ba53 | 3,617,280 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.