content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
from typing import Tuple
def http(func: str, arg: Tuple[str]) -> int:
"""Summary.
Args:
func (str): Path to a function.
arg (Tuple[str]): Description
Returns:
int: Description
"""
return ERGO_CLI.http(func, *list(arg)) | 1e46eefa4101ff63d2d3851bacbfd472e1d3c7ce | 3,640,752 |
import time
def isMWS_bhb(primary=None, objtype=None,
gaia=None, gaiaaen=None, gaiadupsource=None, gaiagmag=None,
gflux=None, rflux=None, zflux=None,
w1flux=None, w1snr=None, maskbits=None,
gnobs=None, rnobs=None, znobs=None,
gfracmasked=None, rfra... | 1a4f4287263ee64497ebdf882cbe3b782840b8f3 | 3,640,753 |
def bernpoly(n, z):
"""
Evaluates the Bernoulli polynomial `B_n(z)`.
The first few Bernoulli polynomials are::
>>> from sympy.mpmath import *
>>> mp.dps = 15
>>> for n in range(6):
... nprint(chop(taylor(lambda x: bernpoly(n,x), 0, n)))
...
[1.0]
... | 60da6461246e48f8b5ff7172f7d244c59b9ad7ed | 3,640,754 |
def sort(obs, pred):
"""
Return sorted obs and pred time series'
"""
obs = obs.sort_values(ascending=True)
pred = pred.sort_values(ascending=True)
return obs,pred | 11c44c1fd605611a2722321b3c3d58a822b9c643 | 3,640,755 |
import random
def random_point_of_triangle(vertices):
"""Compute a random point of the triangle with given vertices"""
p, q, r = vertices
pq = q-p
pr = r-p
while True:
x = random.random()
y = random.random()
if x + y <= 1:
return p + pq*x + pr*y | ba3bf9183ddae4a16561a06b6f2455ce0ede6c8f | 3,640,756 |
import time
def get_minutes(hour:str) -> int:
""" Get total number of minutes from time in %H:%M .
Args:
hour (str): String containing time in 24 hour %H:%M format
Returns:
int: Returns total number of minutes
"""
t = time.strptime(hour, '%H:%M')
minutes = t[3] * 60 + t[4]
... | 069835bdb6b0919d6206e0379a1933986ad2d5bd | 3,640,757 |
from typing import Tuple
import logging
def get_rotation_scale_from_transformation(matrix: np.array) -> Tuple[np.array,np.array] :
"""
This function breaks the given transformation matrix into a Rotation matrix and a Scale matrix
as described in "As-Rigid-As-Possible Shape Interpolation" by Alexa et al
... | c48ed5d1e880c7caf79e009bfeb84c95de8007e3 | 3,640,758 |
def calc_check_digit(number):
"""Calculate the check digit."""
weights = (7, 9, 8, 6, 5, 4, 3, 2)
check = sum(w * int(n) for w, n in zip(weights, number)) % 11
return str((10 - check) % 9 + 1) | eec82a1e6cec8baf513db16e672294df79ce4b9f | 3,640,759 |
import json
def leave_studygroup(request):
"""
Remove a student from the list of participants of a study group.
"""
body = json.loads(request.body)
group_id = body['id']
token = body['token']
rcs = Student.objects.get(token=token).rcs
group = Studygroup.objects.get(id=group_id)
p... | 705c63640c11485dc68ce69d7757642a84c5798c | 3,640,760 |
def list_revisions_courses(request_ctx, course_id, url, per_page=None, **request_kwargs):
"""
List the revisions of a page. Callers must have update rights on the page in order to see page history.
:param request_ctx: The request context
:type request_ctx: :class:RequestContext
:param c... | c6ef2cd08b1a98c5204dd0e6a52b55ef57dbc78a | 3,640,761 |
def snr2Ivar(flux, snr):
"""
Estimate the inverse variance given flux and S/N.
Parameters
----------
flux : scalar or array of float
Flux of the obejct.
snr : scalar or array of float
Signal to noise ratio
"""
return 1.0 / ((flux / snr) ** 2.0) | 91c76cd942a8f37f57a227ccb35cf4968a16193b | 3,640,762 |
def revision_to_cashflows(rev, end_date):
"""Converts a revision to a list of cashflows
end_date -- the date from which we want to stop computing
"""
if rev.end_date is not None:
end_date = next_month(rev.end_date)
result = []
for first_of_month in first_of_month_range(rev.start_date, en... | 51778e5c389420101d3ef6afab0e28b6aa708689 | 3,640,763 |
def filter_verified_user(path, community_user_dataFrame,verified_user_file,sep = ',',header = None):
"""
根据已经认证的用户文件,过滤到保留社区中的认证用户。
:param path:认证用户文件的保存路径。
:param community_user_dataFrame:社区用户数据框,两列,列名(user_id, community_id)。
:param verified_user_file:认证用户的文件,为CSV文件,格式为(user_id, is_verified, name),... | a571f72000e0a52e8f5aa0d5ae61cd07e2d7189d | 3,640,764 |
from datetime import datetime
def calculate(series):
"""
:param series: a list of lists of [[(),()], [(),()]] for every swc tube in the pixel
:return:
"""
# gets every dates tuple in the list
dates = [t for t, v in series]
# define the dates as a set
ds = set(dates[0])
# get the i... | 136fa5fd72bad6c1cb2938e25adc44d768caf43b | 3,640,765 |
from typing import Tuple
def load_dataset(filename: str) -> Tuple[np.ndarray, np.ndarray]:
"""
Load dataset for comparing the Gaussian Naive Bayes and LDA classifiers. File is assumed to be an
ndarray of shape (n_samples, 3) where the first 2 columns represent features and the third column the class
... | 15b6c7422fa397e13fc19de2a1e7681b73e3638c | 3,640,766 |
import csv
def readCSV(name,shape = [None], delimiter = ","):
""" Lectura de archivo csv name
Devuelve matriz con los datos y cabecera
"""
data = []
with open(name, 'r') as f:
reader = csv.reader(f,delimiter = delimiter)
for row in reader:
data.append(row[slice(*sha... | 789341daf51b2f1e92086a42698ea0fef1130505 | 3,640,767 |
from gdata.media import Category
def build_category(category):
"""Build a single-item list of a YouTube category.
This refers to the Category of a video entry, such as "Film" or "Comedy",
not the atom/gdata element. This does not check if the category provided
is valid.
Keyword arguments:
category: St... | 6906e30fcf1d72d7842ec5d7381a12842a9ded3e | 3,640,768 |
def all(event, context):
""" retrieves all experiment results from redis
params:
- namespace (optional)
- scope (optional, comma-separated list of experiments)
"""
r = _redis()
namespace = event.get('namespace', 'alephbet')
scope = event.get('scope')
if scope:
... | 583cc6a0101fbb6ef1ca12d6ddcfe76626bdd8dd | 3,640,769 |
def check_submodule_update(job, position):
"""
Checks to see if certain submodules have been updated and post a comment to the PR if so.
"""
output = get_output_by_position(job, position)
modules = find_in_output(output, "CIVET_CLIENT_SUBMODULE_UPDATES")
if not modules:
return False
... | ca6772b516fca899d6196cea47aa4185d958ec48 | 3,640,771 |
def _compute_subseq_errors_direct(series, weights):
"""
Subsequence errors (using one pass formulation)
:param Array{Float64,1} series
:param Array{Float64,1} weights
The subsequence errors is:
$$\begin{align}
E[i,j] &= Q[i,j] - \frac{S[i,j]^2}{W[i,j]}
\end{align}$$
Were W, S, ... | d8083b2b19102d51ee10baf2907890663f1d2b82 | 3,640,772 |
def preprocess_dataframe(data):
"""Helper method to preprocess the dataframe.
Creates new columns for year,month,recalls and percentage change.
Limits the date range for the experiment (these data are trustworthy)."""
data['recalls'] = data['doc_count'] + 1
data.drop(columns=['product', 'Unnam... | f6670cac1319108c88ee9ee409ce0ecdd1eca746 | 3,640,773 |
def is_solution(x:int, y:int) -> bool:
"""Returns try if (x, y) is a solution."""
# x and y are the values in a sequence of 15 terms of the following form:
# xxxxyxxxxxyxxxx
# x must be a positive integer
if x <= 0:
return False
# y must be a negative integer
if y >= 0:
re... | 5e620fc390f6a79fd25d00c8c8b51d0af788d48c | 3,640,774 |
def load_crl(file):
# type: (AnyStr) -> CRL
"""
Load CRL from file.
:param file: Name of file containing CRL in PEM format.
:return: M2Crypto.X509.CRL object.
"""
with BIO.openfile(file) as f:
cptr = m2.x509_crl_read_pem(f.bio_ptr())
return CRL(cptr, 1) | d711503c78edbb722189d7a06340ab9f719f853f | 3,640,775 |
def clean_and_lemmatize(text):
"""
Clean and lemmatize the text of a Tweet
Returns:
cleaned_text (string): The cleaned and lemmatized text.
"""
wnl = WordNetLemmatizer() # NLTK lemmatizer
converted_tweet = clean_and_tokenize(
text) # cleans the text and tokenize it
... | 0635e08aca69191d77ad652dcf752254fbfc2ea6 | 3,640,776 |
def conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1):
"""3x3 convolution with padding
Arguments:
in_planes {int} -- Number of channels in the input image
out_planes {int} -- Number of channels produced by the convolution
Keyword Arguments:
stride {int or tuple, option... | 1f55153bb35dd56b7cca2b00e13a0f4e5a963248 | 3,640,777 |
def task_finish(request, pk):
"""タスクを完了するAPI
:param request:
:param pk:
:return:
"""
task = get_object_or_404(models.Task, pk=pk)
prev_task = task.get_prev_task()
if prev_task is None or prev_task.can_continue():
task.status = '99'
task.updated_user = request.user
... | b995edd022e27b6101c9c79874af4fc78a01afe2 | 3,640,778 |
def fine_tune():
"""recreates top model architecture/weights and fine tunes with image augmentation and optimizations"""
# reconstruct vgg16 model
model = Sequential()
model.add(ZeroPadding2D((1, 1), input_shape=(3, img_width, img_height)))
model.add(Convolution2D(64, 3, 3, activation='relu', ... | 69982c739927fca8f1c8e3779a7358a7fc646a5f | 3,640,780 |
def normalize(a, seqlength=None, rv=None):
"""
Normalize the VSA vector
:param a: input VSA vector
:param seqlength: Optional, for BSC vectors must be set to a valid.
:param rv: Optional random vector, used for splitting ties on binary and ternary VSA vectors.
:return: new VSA vector
"""
... | ef8ec307add55a56be5991bb13579bc989726d3c | 3,640,781 |
def MACD(df, n_fast, n_slow):
"""Calculate MACD, MACD Signal and MACD difference
:param df: pandas.DataFrame
:param n_fast:
:param n_slow:
:return: pandas.DataFrame
"""
EMAfast = pd.Series(df['Close'].ewm(span=n_fast, min_periods=n_slow).mean())
EMAslow = pd.Series(df['Close'].ewm... | 368f80feb27bd67a387b0b9abb652d53205d22ac | 3,640,782 |
def ecef2map(xyz, spatialRef):
""" transform 3D cartesian Earth Centered Earth fixed coordinates, to
map coordinates (that is 2D) in a projection frame
Parameters
----------
xyz : np.array, size=(m,3), float
np.array with 3D coordinates, in WGS84. In the following form:
[[x, y, z], ... | f7177912c931cfe6c2cee5737ed6bd2afedeba08 | 3,640,783 |
def dis2speed(t, dis):
"""
Return speed in distance travelled per hour.
Args:
t (datetime64[ms]): 1D array with time.
dis (float ): 1D array with distance travelled.
Returns:
float: 1D array with speed data.
"""
# divide by one hour (=3600 x 1... | 4dae87509ad44604949f1d3f925f3b28947b9952 | 3,640,784 |
def default_context(plugin, context):
"""
Return the default context for plugins rendered with a template, which
simply is a single variable named ``plugin`` containing the plugin
instance.
"""
return {"plugin": plugin} | 5f7a88c02b6c11a150197e50a5be1847cba422b0 | 3,640,785 |
def get_model_from_key(model_name):
"""
Gets the model from a given key.
param:
model_name: name of model
return:
object
"""
_known_models = {}
#populate
for klass in Model.__subclasses__():
_known_models[klass.__name__] = klass
for sub in klass._... | 488c52635bfdf10c79936b0f33b84d0222d1ae5b | 3,640,786 |
def default_fields(
coll_id=None, type_id=None, entity_id=None,
width=12, **kwargs):
"""
Returns a function that accepts a field width and returns a dictionary of entity values
for testing. The goal is to isolate default entity value settings from the test cases.
"""
def_label = kwar... | 1670f95a8e95f84ca5f08aab8ee0a8effb1e6f76 | 3,640,787 |
import traceback
def predict_using_broadcasts(feature1, feature2, feature3, feature4):
"""
Scale the feature values and use the model to predict
:return: 1 if normal, -1 if abnormal 0 if something went wrong
"""
prediction = 0
x_test = [[feature1, feature2, feature3, feature4]]
try:
... | 4f766002e11fbe34f3479769db752c0df08b2df5 | 3,640,788 |
import torch
def make_positions(tensor, padding_idx, left_pad):
"""Replace non-padding symbols with their position numbers.
Position numbers begin at padding_idx+1.
Padding symbols are ignored, but it is necessary to specify whether padding
is added on the left side (left_pad=True) or right side (left... | 8e65c68daae2e40710c777d6e74f048b8b0ad547 | 3,640,789 |
def teq(state, *column_values):
"""Tag-Equals filter. Expects, that a first row contains tags and/or metadata
Tag row is ignored in comparison, but prepended to the result (in order to maintain the first row in the results).
Accepts one or more column-value pairs. Keep only rows where value in the column eq... | 7fd2786dcbe8705b48081c6bc96dcdc7452e35d3 | 3,640,790 |
def adjust_labels(data_y, dataset, pred_type='actions'):
"""
Transforms original labels into the range [0, nb_labels-1]
:param data_y: numpy integer array
Sensor labels
:param pred_type: string, ['gestures', 'locomotion', 'actions', 'tasks']
Type of activities to be recognized
:retu... | 1d201a20a8865cd505c0ee6b5385622a0ae28817 | 3,640,791 |
def is_str_or_bytes(x):
""" True if x is str or bytes.
This doesn't use rpartial to avoid infinite recursion.
"""
return isinstance(x, (str, bytes, bytearray)) | ff4bf19177ffe62f24713e077824e48ec45f8587 | 3,640,792 |
def _type_convert(new_type, obj):
"""
Convert type of `obj` to `force`.
"""
return new_type(obj) | fc47c100508d41caa7ffc786746b58e3d6f684e2 | 3,640,793 |
def create_tokenizer(corpus_file, vocab_size):
"""Create a tokenizer from a corpus file
Args:
corpus_file (Pathlib path): File containng corpus i.e. all unique words for
vocab_size (int): Vocabulary size of the tokenizer
Returns:
hugging_face tokenizer: Byte pair tokenizer used to ... | 6de30b057d920d650f065af0f9083130fbb6df77 | 3,640,794 |
def get_readings(tag):
"""Get sensor readings and collate them in a dictionary."""
try:
enable_sensors(tag)
readings = {}
# IR sensor
readings["ir_temp"], readings["ir"] = tag.IRtemperature.read()
# humidity sensor
readings["humidity_temp"], readings["humidity"] =... | 481aae840d9ab41995086e3ef98c500abf4ec82e | 3,640,795 |
import binascii
def digita_gw(request):
"""
Digita GW endpoint implementation
"""
identifier = request.data['DevEUI_uplink']['DevEUI']
apsen = core.models.apartment_sensor_models.ApartmentSensor.objects.get_or_create(identifier=identifier)[0]
payload = binascii.unhexlify(request.data['DevEUI_u... | e6bf45c92ea61278dd47e52ed945e91aa514d21b | 3,640,796 |
def resize_img(_img, maxdims=(1000, 700)):
"""
Resize a given image. Image can be either a Pillow Image, or a NumPy array. Resizing is done automatically such
that the entire image fits inside the given maxdims box, keeping aspect ratio intact
:param _img:
:param maxdims:
:return:
"""
tr... | 54716e4ce030a675a0655b06d7121d4c38bd7c43 | 3,640,797 |
def natural_key(s):
"""Converts string ``s`` into a tuple that will sort "naturally"
(i.e., ``name5`` will come before ``name10`` and ``1`` will come
before ``A``). This function is designed to be used as the ``key``
argument to sorting functions.
:param s: the str/unicode string to convert.
... | d0eb51bdd3e7c6caa5b13c38269bc9c07e3834d2 | 3,640,798 |
def SetDocTimestampFrequency(doc:NexDoc, freq:float):
"""Sets the document timestamp frequency"""
return NexRun("SetDocTimestampFrequency", locals()) | dceb766792b6ca34d5f5759b0079acc5b70da5a9 | 3,640,800 |
def rsqrt(x:np.ndarray):
"""Computes reciprocal of square root of x element-wise.
Args:
x: input tensor
Returns:
output tensor
Examples:
>>> x = np.array([2., 0., -2.])
>>> rsqrt(x)
<tf.Tensor: shape=(3,), dtype=float32,
numpy=array([0.707, inf, nan], dtyp... | f219ae71b5136bc1b34a2bb06ec76dcdb7ee20bb | 3,640,801 |
def is_card(obj):
"""Return true if the object is a card."""
return obj in CARDS_SET | 21f155feadde94d652e120224a2712f2470a9926 | 3,640,802 |
def plot_lines(
y: tuple,
x: np.ndarray = None,
points: bool = True,
x_axis_label: str = 'Index',
y_axis_label: str = 'Value',
plot_width: int = 1000,
plot_height: int = 500,
color: tuple = None,
legend: tuple = None,
title: str = 'Graph li... | b938151b90005bc23bb9ed2f795dbf4620b26251 | 3,640,803 |
import re
def obtain_csrf(session):
"""
Obtain the CSRF token from the login page.
"""
resp = session.get(FLOW_LOGIN_GET_URL)
contents = str(resp.content)
match = re.search(r'csrfToken" value="([a-z0-9\-]+)"', contents)
return match.group(1) | a091ca33b6b0a43608261e46c54c7ae164a9d3af | 3,640,804 |
def get_distance_curve(
kernel,
lambda_values,
N,
M=None,
):
""" Given number of elements per class, full kernel (with first N rows corr.
to mixture and the last M rows corr. to component, and set of lambda values
compute $\hat d(\lambda)$ for those values of lambda"""
d... | e085ea6b2122b052625df1c7b60115552112ffab | 3,640,805 |
def _process_labels(labels, label_smoothing):
"""Pre-process a binary label tensor, maybe applying smoothing.
Parameters
----------
labels : tensor-like
Tensor of 0's and 1's.
label_smoothing : float or None
Float in [0, 1]. When 0, no smoothing occurs. When positive, the binary
... | 5a71ded8ac9d3ef4b389542814a170f35ef18fdd | 3,640,806 |
def guess_digit(image, avgs):
"""Return the digit whose average darkness in the training data is
closest to the darkness of ``image``. Note that ``avgs`` is
assumed to be a defaultdict whose keys are 0...9, and whose values
are the corresponding average darknesses across the training data."""
... | 055a0d31f85ce6f5786d6bd6dfaed75bdb3ff5d6 | 3,640,807 |
import time
def multiple_writes(self,
Y_splits,
Z_splits,
X_splits,
out_dir,
mem,
filename_prefix="bigbrain",
extension="nii",
... | b2a7048628c54bf8976f9b3182fe4cecc18468e7 | 3,640,808 |
def new_parameter_value(data, parameter_key: str):
"""Return the new parameter value and if necessary, remove any obsolete multiple choice values."""
new_value = dict(bottle.request.json)[parameter_key]
source_parameter = data.datamodel["sources"][data.source["type"]]["parameters"][parameter_key]
if sou... | 41160804aba582ce0c588762bb1a96ea53e258df | 3,640,809 |
from typing import Sequence
from typing import Optional
def rotate_to_base_frame(
pybullet_client: bullet_client.BulletClient,
urdf_id: int,
vector: Sequence[float],
init_orientation_inv_quat: Optional[Sequence[float]] = (0, 0, 0, 1)
) -> np.ndarray:
"""Rotates the input vector to the base coordinat... | 5651e0183cd61555f90fe6af1e5c5dc2bec6e8b5 | 3,640,810 |
def show_page_map(label):
"""Renders the base page map code."""
return render('page_map.html', {
'map_label': label.replace('_', ' '),
}) | 623d47c4de57c1810c07475a70e501d55ee5e9ae | 3,640,811 |
def create_clf_unicycle_position_controller(linear_velocity_gain=0.8, angular_velocity_gain=3):
"""Creates a unicycle model pose controller. Drives the unicycle model to a given position
and orientation. (($u: \mathbf{R}^{3 \times N} \times \mathbf{R}^{2 \times N} \to \mathbf{R}^{2 \times N}$)
linear_velo... | 4d75c85079ca5350473c058019ae6f4763fdd97b | 3,640,812 |
from typing import Tuple
def stft_reassign_from_sig(sig_wf: np.ndarray,
frequency_sample_rate_hz: float,
band_order_Nth: float) -> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray, np.ndarray,
np.ndarr... | 90aa2b019ace90500c38feb5e643a8ca3c02360a | 3,640,814 |
from typing import List
def download(*urls, zip: str=None, unzip: bool=False, **kwargs) -> List[File]:
"""
Download multiple zippyshare urls
Parameters
-----------
*urls
Zippyshare urls.
zip: :class:`str`
Zip all downloaded files once finished.
Zip filename will be tak... | a1197d264fa3305fb545a60e5963be2fc326aa5d | 3,640,815 |
def pop_arg(args_list, expected_size_after=0, msg="Missing argument"):
"""helper function to get and check command line arguments"""
try:
value = args_list.pop(0)
except IndexError:
raise BadCommandUsage(msg)
if expected_size_after is not None and len(args_list) > expected_size_after:
... | 90b1f1ae596a9257d15cc189e87223b166252c9a | 3,640,816 |
def d4s(data):
"""
Beam parameter calculation according to the ISO standard D4sigma integrals
input: 2D array of intensity values (pixels)
output:
xx, yy: x and y centres
dx, dy: 4 sigma widths for x and y
angle: inferred rotation angle, radians
"""
gg = data
dimy, dimx = np.sha... | f10c0792a2e200c980ccd6ffb286bdfabc90bb32 | 3,640,817 |
from astropy.utils import iers
import warnings
import six
def checkWarnings(func, func_args=[], func_kwargs={},
category=UserWarning,
nwarnings=1, message=None, known_warning=None):
"""Function to check expected warnings."""
if (not isinstance(category, list) or len(catego... | 58a40594f48b1f47350e9b6a1ca1d956dfd63d04 | 3,640,818 |
from omas.omas_utils import list_structures
from omas.omas_utils import load_structure
def extract_times(imas_version=omas_rcparams['default_imas_version']):
"""
return list of strings with .time across all structures
:param imas_version: imas version
:return: list with times
"""
times = []... | 2b13361dc713d90a946554383b556a8ced24ac55 | 3,640,819 |
import json
def load_appdata():
"""load application data from json file
"""
try:
_in = open(FNAME)
except FileNotFoundError:
return
with _in:
appdata = json.load(_in)
return appdata | afb3a69a5abf72cd14a8ae0c8c99ccc3350899a1 | 3,640,820 |
def compute_couplings(models_a, models_b):
"""
Given logistic models for two multiple sequence alignments, calculate all
intermolecular coupling strengths between residues.
The coupling strength between positions i and j is calculated as the 2-norm
of the concatenation of the coefficient submatrices... | 761c1987a7e230f70e123ce8d1746881b1b26cae | 3,640,821 |
def update_checkout_line(request, checkout, variant_id):
"""Update the line quantities."""
if not request.is_ajax():
return redirect("checkout:index")
checkout_line = get_object_or_404(checkout.lines, variant_id=variant_id)
discounts = request.discounts
status = None
form = ReplaceCheck... | 9394699c50bc3724ac253f288e23cc77eac05a3a | 3,640,822 |
from typing import Optional
def merge_df(
df: Optional[pd.DataFrame], new_df: Optional[pd.DataFrame], how="left"
):
"""
join two dataframes. Assumes the dataframes are indexed on datetime
Args:
df: optional dataframe
new_df: optional dataframe
Returns:
The merged dataframe
... | 783111942086a23fbb13b1e96f2d098c7db0f963 | 3,640,823 |
def _is_leaf(tree: DecisionTreeClassifier, node_id: int) -> bool:
"""
Determines if a tree node is a leaf.
:param tree: an `sklearn` decision tree classifier object
:param node_id: an integer identifying a node in the above tree
:return: a boolean `True` if the node is a leaf, `False` otherwise
... | bdc5affe82c1c7505668e0f7c70dbb548170b6e1 | 3,640,825 |
async def commission_reset(bot, context):
"""Resets a given user's post cooldown manually."""
advertisement_data = await _get_advertisement_data(bot, context.guild)
deleted_persistence = data.get(
bot, __name__, 'recently_deleted', guild_id=context.guild.id, default={})
user_id = context.argumen... | 06666421569b92fdf8a943351058e3f53c7d0777 | 3,640,826 |
def test_sample_problems_auto_1d_maximization(max_iter, max_response, error_lim, model_type, capsys):
"""
solve a sample problem in two different conditions.
test that auto method works for a particular single-covariate (univariate) function
"""
# define data
x_input = [(0.5, 0,
... | 3db394c4b1cccb276d3efe80ff7561830fc82b7a | 3,640,827 |
def heatmap_numeric_w_dependent_variable(df, dependent_variable):
"""
Takes df, a dependant variable as str
Returns a heatmap of all independent variables' correlations with dependent variable
"""
plt.figure(figsize=(10, 5.5))
figure = sns.heatmap(
df.corr()[[dependent_variable]].sort_v... | 46919deb37ee1f641983761a81ffeb830dac8217 | 3,640,829 |
def numpy2seq(Z, val=-1):
"""Appends the minimal required amount of zeroes at the end of each
array in the jagged array `M`, such that `M` looses its jagedness."""
seq = []
for z in t2n(Z).astype(int):
i = np.where(z==val)[0]
if i.size == 0:
seq += [z.tolist()]
else... | b46f6379a3eba0c5754c1a824dc28a43a10dc742 | 3,640,831 |
def winner(board):
"""Detirmine the game's winner."""
WAYS_TO_WIN = ((0, 1, 2),
(3, 4, 5),
(6, 7, 8),
(0, 3, 6),
(1, 4, 7),
(2, 5, 8),
(0, 4, 8),
(2, 4, 6))
for row in WAYS_TO_WIN:
if board[row[0]] == board[row[1]] == board[row[2]] != EMPTY:
winner = board[row[0]]
return winner
if EMPTY not i... | 6adb31e668c1d7e2723df7d65ab34246748c3249 | 3,640,832 |
def compute_inv_propensity(train_file, A, B):
"""
Compute Inverse propensity values
Values for A/B:
Wikpedia-500K: 0.5/0.4
Amazon-670K, Amazon-3M: 0.6/2.6
Others: 0.55/1.5
"""
train_labels = data_utils.read_sparse_file(train_file)
inv_propen = xc_metri... | df8f45cf48f056cee6f3f9026f546dcea0f9ee75 | 3,640,833 |
def tanh(x):
"""
Returns the cos of x.
Args:
x (TensorOp): A tensor.
Returns:
TensorOp: The tanh of x.
"""
return TanhOp(x) | bef86675a70714f3e33a6828353e1f71958c3057 | 3,640,834 |
def importBodyCSVDataset(testSplit: float, local_import: bool):
"""Import body dataset as numpy arrays from GitHub if available, or local dataset otherwise.
Args:
testSplit (float, optional): Percentage of the dataset reserved for testing. Defaults to 0.15. Must be between 0.0 and 1.0.
"""
asse... | 411d8c1aa3e1d741e2b169f1a4c3065af8f5e82c | 3,640,835 |
def mvstdtprob(a, b, R, df, ieps=1e-5, quadkwds=None, mvstkwds=None):
"""
Probability of rectangular area of standard t distribution
assumes mean is zero and R is correlation matrix
Notes
-----
This function does not calculate the estimate of the combined error
between the underlying multi... | 2b15e3ce209d01e4790391242cbd87914a79fa5d | 3,640,836 |
import re
def dropNested(text, openDelim, closeDelim):
"""
A matching function for nested expressions, e.g. namespaces and tables.
"""
openRE = re.compile(openDelim, re.IGNORECASE)
closeRE = re.compile(closeDelim, re.IGNORECASE)
# partition text in separate blocks { } { }
spans = [] ... | dd77b86533dd43bcecf2ef944a61b59c4150aaae | 3,640,839 |
def update_service(
*, db_session: Session = Depends(get_db), service_id: PrimaryKey, service_in: ServiceUpdate
):
"""Update an existing service."""
service = get(db_session=db_session, service_id=service_id)
if not service:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,... | 0471c4bd496004a9c1cc5af4d806bd8109f62ca7 | 3,640,844 |
def import_flow_by_ref(flow_strref):
"""Return flow class by flow string reference."""
app_label, flow_path = flow_strref.split('/')
return import_string('{}.{}'.format(get_app_package(app_label), flow_path)) | c2f9fe0b9ccc409b3bd64b6691ee34ca8d430ed6 | 3,640,845 |
def _escape_value(value):
"""Escape a value."""
value = value.replace(b"\\", b"\\\\")
value = value.replace(b"\n", b"\\n")
value = value.replace(b"\t", b"\\t")
value = value.replace(b'"', b'\\"')
return value | b58a3236c0686c7fb6a33859986123dc2b8089cc | 3,640,846 |
from typing import Iterable
def find(*objects: Iterable[object]):
"""Sometimes you know the inputs and outputs for a procedure, but you don't remember the name.
methodfinder.find tries to find the name.
>>> import methodfinder
>>> import itertools
>>> methodfinder.find([1,2,3]) == 6
sum([1, 2... | fcfc3c4d0e6d72b6d9f1d7b7bfd46146d8bbf027 | 3,640,847 |
def join_returns(cfg, arg_names, function_ast=None):
"""Joins multiple returns in a CFG into a single block
Given a CFG with multiple return statements, this function will replace the
returns by gotos to a common join block.
"""
join_args = [ir.Argument(function_ast, info=n, name=n) for n in arg_na... | 0a89c2c6df39e0693597358f01704619cbd1d0bd | 3,640,848 |
def get_all():
"""
Returns list of all tweets from this server.
"""
return jsonify([t.to_dict() for t in tweet.get_all()]) | a8803f46ca4c32ea3a0f607a7a37d23a5d97c316 | 3,640,849 |
from carbonplan_trace.v1.glas_preprocess import select_valid_area # avoid circular import
def proportion_sig_beg_to_start_of_ground(ds):
"""
The total energy from signal beginning to the start of the ground peak,
normalized by total energy of the waveform. Ground peak assumed to be the last peak.
"""... | 73fbbd90c8511433bcdae225daea5b7cba9e8297 | 3,640,850 |
import requests
def post_file(url, file_path, username, password):
"""Post an image file to the classifier."""
kwargs = {}
if username:
kwargs['auth'] = requests.auth.HTTPBasicAuth(username, password)
file = {'file': open(file_path, 'rb')}
response = requests.post(
url,
fi... | b615e5a766e6ca5d0427bfcdbd475e1b6cd5b9bb | 3,640,851 |
def bias_init_with_prob(prior_prob):
""" initialize conv/fc bias value according to giving probablity"""
bias_init = float(-np.log((1 - prior_prob) / prior_prob))
return bias_init | 533f777df5e8346ab2eadf5f366a275bab099aec | 3,640,852 |
def parse_number(s, start_position):
"""
If an integer or float begins at the specified position in the
given string, then return a tuple C{(val, end_position)}
containing the value of the number and the position where it ends.
Otherwise, raise a L{ParseError}.
"""
m = _PARSE_NUMBER_VALUE.ma... | 854e9290b5853e525ea1ba3f658f59cea37b117c | 3,640,853 |
def training_data_provider(train_s, train_t):
"""
Concatenates two lists containing adata files
# Parameters
train_s: `~anndata.AnnData`
Annotated data matrix.
train_t: `~anndata.AnnData`
Annotated data matrix.
# Returns
Concatenated Annota... | 35016ecb6f57e2814dacc6e36408882025311bb9 | 3,640,854 |
import warnings
def _build_trees(base_estimator, estimator_params, params, X, y, sample_weight,
tree_state, n_trees, verbose=0, class_weight=None,
bootstrap=False):
""" Fit a single tree in parallel """
tree = _make_estimator(
_get_value(base_estimat... | 43259d71a5d666e371c90e15c1ca61241fbee8e0 | 3,640,855 |
def select_privilege():
"""Provide a select Privilege model for testing."""
priv = Privilege(
database_object=DatabaseObject(name="one_table", type=DatabaseObjectType.TABLE),
action=Action.SELECT,
)
return priv | 721f8edd0b6777a082682e377a80c73f8dc2bb00 | 3,640,856 |
def getLinkToSong(res):
"""
getLinkToSong(res): link to all songs
:param: res: information about the playlist -> getResponse(pl_id)
:returns: list of links to each song
"""
return res['items'][0]['track']['external_urls']['spotify'] | e59fe598ed900a90dcf5376d265eedfc51d8e0a7 | 3,640,858 |
def entropy_sampling(classifier, X, n_instances=1):
"""Entropy sampling query strategy, uses entropy of all probabilities as score.
This strategy selects the samples with the highest entropy in their prediction
probabilities.
Args:
classifier: The classifier for which the labels are to be ... | ffc465a3e8a517e692927f051dea0162d3191cf9 | 3,640,859 |
def browser(browserWsgiAppS):
"""Fixture for testing with zope.testbrowser."""
assert icemac.addressbook.testing.CURRENT_CONNECTION is not None, \
"The `browser` fixture needs a database fixture like `address_book`."
return icemac.ab.calexport.testing.Browser(wsgi_app=browserWsgiAppS) | a256b814a08833eec88eb6289b6c5a57f17e7d84 | 3,640,860 |
def parse_playing_now_message(playback):
"""parse_playing_now_message
:param playback: object
:returns str
"""
track = playback.get("item", {}).get("name", False)
artist = playback.get("item", {}).get("artists", [])
artist = map(lambda a: a.get("name", ""), artist)
artist = ", ".join(l... | 88d7c35257c2aaee44d1bdc1ec06640603c6a286 | 3,640,861 |
import requests
def load_remote_image(image_url):
"""Loads a remotely stored image into memory as an OpenCV/Numpy array
Args:
image_url (str): the URL of the image
Returns:
numpy ndarray: the image in OpenCV format (a [rows, cols, 3] BGR numpy
array)
"""
respo... | a760e76df679cc15788332df02e5470ec5b60ec2 | 3,640,863 |
def evlt(inp : str) -> int:
""" Evaluates the passed string and returns the value if
successful, otherwise raises an error """
operand = [] # stack for operands
operator = [] # stack for operators + parentheses
i = 0 # loop variable, cannot do range because have to increment dynamically
if i... | 2c0ea8781e969f44fa0575c967366d69a19010eb | 3,640,864 |
def _create_preactivation_hook(activations):
"""
when we add this hook to a model's layer, it is called whenever
it is about to make the forward pass
"""
def _linear_preactivation_hook(module, inputs):
activations.append(inputs[0].cpu())
return _linear_preactivation_hook | 7f4cc10f7e051ed8e30556ee054a65c4878f6c0f | 3,640,866 |
import importlib
def import_by_path(path):
"""
Given a dotted/colon path, like project.module:ClassName.callable,
returns the object at the end of the path.
"""
module_path, object_path = path.split(":", 1)
target = importlib.import_module(module_path)
for bit in object_path.split("."):
... | 939b3426f36b3a188f7a48e21551807d42cfa254 | 3,640,867 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.