content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def decode_reponse(response):
"""Return utf-8 string."""
return response.data.decode("utf-8", "ignore") | 3c2c91f08c44db4705feaea525c9c58837fa6d6c | 3,634,474 |
def add_sheet_user(session, *, cls, discord_user, start_row, sheet_src=None):
"""
Add a fort sheet user to system based on a Member.
Kwargs:
cls: The class of the sheet user like FortUser.
duser: The DiscordUser object of the requesting user.
start_row: Starting row if none inserted... | df4d9f9325769bf5f80557a33c7aac5c5bd0eab6 | 3,634,475 |
def clean_uncertain(value, keep=False):
"""
Handle uncertain values in the data.
Process any value containing a '[?]' string.
:param value: the value or list of values to process
:param keep: whether to keep the clean value or discard it
"""
was_list = isinstance(value, list)
values = ... | 982be717dec2c3872198fefcc632d86af0281bc9 | 3,634,476 |
def traceback_file_lines(trace_text=None):
""" this returns a list of lines that start with file in the given traceback
usage:
traceback_steps(traceback.format_exc())
"""
# split the text into traceback steps
return [i for i in trace_text.splitlines() if i.startswith(' File "') and ... | 939fd7e978612d891f38825898f575bc8d9b38af | 3,634,477 |
def load(year, gp, session):
"""session can be 'Qualifying' or 'Race'
mainly to port on upper level libraries
"""
day = 'qualifying' if session == 'Qualifying' else 'results'
sel = 'QualifyingResults' if session == 'Qualifying' else 'Results'
return _parse_ergast(fetch_day(year, gp, day))[0][sel... | 45d36124b16fd3f4108e6a9e01423d8df432f081 | 3,634,478 |
def pad_extents(extents: Extents, pad: float = 0.05) -> Extents:
"""Pad an Extents by a factor
Parameters:
extents: bounding extents to pad
pad: padding distance
Returns:
padded bounding extents
"""
padx = (extents.maxx - extents.minx)*0.05
pady = (extents.maxy - exten... | d5ed2b353c704fbbcb9d23e2454e9a449dcb6261 | 3,634,479 |
from typing import Set
def make_VR_model():
""" This function constructs and returns a pyomo model for the vehicle routing problem this repo is focuses on solving """
model= AbstractModel()
# model sets:
model.P = Set () # set of pick ups
model.D = Set () # set of drop offs
model.R = Set ()... | dc95d0f814ca3e9796e946e66b8b54568812ec2b | 3,634,480 |
from typing import Union
def get_image(
difficulty: Union[gd.DemonDifficulty, gd.LevelDifficulty],
is_featured: bool = False,
is_epic: bool = False,
) -> str:
"""Generate name of an image based on difficulty and parameters."""
parts = difficulty.name.lower().split("_")
if is_epic:
par... | f34f59437bfe0e97ae166f8e5ee3be2737073a0b | 3,634,481 |
import json
def jsonpify(func):
"""
Like jsonify but wraps result in a JSONP callback if a 'callback'
query param is supplied.
"""
def inner(*args, **kwargs):
data = func(*args, **kwargs)
callback = request.args.get('callback')
if callback:
response = app.make_r... | 818eb424b6f61bc7fa7f068323789c6bff1ea7c1 | 3,634,482 |
def ordered(obj):
""" Sort JSON blob by keys """
if isinstance(obj, dict):
return sorted((k, ordered(v)) for k, v in list(obj.items()))
if isinstance(obj, list):
return sorted(ordered(x) for x in obj)
else:
return obj | dba08ec9ece30cfd01d3fcdde4b32e9e42086079 | 3,634,483 |
import copy
def apply_perturbation(X, y, perturbations_info):
"""Application of the perturbations."""
perturb = perturbations_info[3](X, None, perturbations_info[1],
perturbations_info[2])
X_p, y_p = perturb.apply2features(copy.copy(X)).squeeze(2), copy.copy(y)
ret... | 2a7ba4e0286fe81f494f2e2d752532d24e895be4 | 3,634,484 |
def iris_sji_color_table(measurement, aialike=False):
"""
Return the standard color table for IRIS SJI files.
"""
# base vectors for IRIS SJI color tables
c0 = np.arange(0, 256)
c1 = (np.sqrt(c0) * np.sqrt(255)).astype(np.uint8)
c2 = (c0**2 / 255.).astype(np.uint8)
c3 = ((c1 + c2 / 2.) *... | c00dd6fc5572dfd4563079040fab48ec5d439215 | 3,634,485 |
def clipToCollection(image, featureCollection, keepFeatureProperties=True):
""" Clip an image using each feature of a collection and return an
ImageCollection with one image per feature """
def overFC(feat):
geom = feat.geometry()
clipped = image.clip(geom)
if keepFeatureProperties:
... | c42610e2164e389db17a353ca15a22d21a9cd614 | 3,634,486 |
def bbox_filter(image, bboxes, labels):
"""
Maginot Line
"""
h, w, _ = image.shape
x1 = np.maximum(bboxes[..., 0], 0.)
y1 = np.maximum(bboxes[..., 1], 0.)
x2 = np.minimum(bboxes[..., 2], w - 1e-8)
y2 = np.minimum(bboxes[..., 3], h - 1e-8)
int_w = np.maximum(x2 - x1, 0)
int_h =... | 38c8a1997e233ff1484c321559b9b7b21e0ff283 | 3,634,487 |
import json
def sign_transaction(source_address, keys, redeem_script, unsigned_hex, input_txs):
"""
Creates a signed transaction
output => dictionary {"hex": transaction <string>, "complete": <boolean>}
source_address: <string> input_txs will be filtered for utxos to this source address
keys: Lis... | 775fbccd906cbba598eb07d2b8b1f233c32c3954 | 3,634,488 |
import numpy
def CalculateBasakCIC1(mol):
"""
Obtain the complementary information content with order 1 proposed
by Basak.
"""
Hmol = Chem.AddHs(mol)
nAtoms = Hmol.GetNumAtoms()
IC = CalculateBasakIC1(mol)
if nAtoms <= 1:
BasakCIC = 0.0
else:
BasakCIC = numpy.log2(n... | ca5b2e5bea750ce029147fcea61321faa8e98629 | 3,634,489 |
from typing import Any
async def mock_nonpriviledged_user(db: Any, username: str) -> dict:
"""Create a mock user object."""
return { # noqa: S106
"id": ID,
"username": "nonprivileged@example.com",
"password": "password",
"role": "nonprivileged",
} | 23af36146a116373584930eadae9dd0633da1100 | 3,634,490 |
def idea_create(request):
"""
Endpoint to create ideas
---
POST:
serializer: ideas.serializers.IdeaCreationSerializer
response_serializer: ideas.serializers.IdeaSerializer
"""
if request.method == 'POST':
serializer = IdeaCreationSerializer(data=request.data)
if s... | d780854a33c123c33ee3e8179f5a8056bea4716c | 3,634,491 |
def blocks_to_pem(blobs, marker):
"""Convert binary blobs to a string of concatenated PEM-formatted blocks.
Args:
blobs: an iterable of binary blobs
marker: the marker to use, e.g., CERTIFICATE
Returns:
the PEM string.
"""
return PemWriter.blocks_to_pem_string(blobs, marker... | 498d63aa16990c4046f5fbd25aea17fbff72d7c3 | 3,634,492 |
def scatterList(z):
"""
scatterList reshapes the solution vector z of the N-vortex ODE for easy 2d plotting.
"""
k = int(len(z)/2)
return [z[2*j] for j in range(k)], [z[2*j+1] for j in range(k)] | 422bf448ae999f56e92fdc81d05700189122ad0e | 3,634,493 |
from pathlib import Path
def discover_workflow(path: Path) -> Workflow:
"""
Find a instance of virtool_workflow.Workflow in the
python module located at the given path.
:param path: The :class:`pathlib.Path` to the python file
containing the module.
:returns: The first instance o... | 95b67497b61f3ecf715ce677d7b2986d0817830b | 3,634,494 |
from typing import List
from typing import Mapping
from typing import Optional
def swagger_endpoint_data_to_df(
data: List[Mapping],
headers: Optional[List[str]] = None
) -> pd.DataFrame:
"""Load results from cBioPortal API endpoints to pandas DataFrame.
Parameters
----------
data : L... | 6c4e4c657131b8cc54f3827033e077edc7bb57b1 | 3,634,495 |
def compare():
"""
This path takes two inputs in multiform/data
Name of paramaters:
image1: First image
image2 : Second image
"""
if request.method == 'POST':
if 'image1' not in request.files or 'image2' not in request.files:
return make_response(jsonify("Msg: Upload an i... | e4b6625608051804222074f5972b10ee864659d8 | 3,634,496 |
def provides_facts():
"""
Returns a dictionary keyed on the facts provided by this module. The value
of each key is the doc string describing the fact.
"""
return {
"switch_style": "A string which indicates the Ethernet "
"switching syntax style supported by the device. "
"Po... | d41f97df8a24b67d929017fc6c20596a70ba18cd | 3,634,497 |
def _continuum_emission(energy_edges_keV, temperature_K, abundances):
"""
Calculates emission-measure-normalized X-ray continuum spectrum at the source.
Output must be multiplied by emission measure and divided by 4*pi*observer_distance**2
to get physical values.
Which continuum mechanisms are incl... | a9d66263f62acd58edc09f3f1b7f0a40ba5b099d | 3,634,498 |
def reorder_by_driver(driver, driven):
"""
Reorders timeseries of driver and driven variable by driver quicksort.
"""
idx_sort = np.argsort(driver, kind='quicksort')
driver = driver[idx_sort]
driven = driven[idx_sort]
return driver, driven | 772737c8918363dd6ce59eeb3c79474292d9c9a2 | 3,634,500 |
import uuid
def get_bucket_policy(s3bucket):
""" Gets S3 Bucket policy
:param s3bucket: S3 bucket to get the policy
:return: Bucket Policy Object
"""
s3_client = boto3.client('s3')
try:
bucket_policy = s3_client.get_bucket_policy(Bucket=s3bucket)
except:
bucket_policy = {u'... | 33a4f16df595b040b255ea73354d18719ccba8b5 | 3,634,502 |
def is_gregorian( y, m, d ):
"""
The `is_gregorian` function enables array input.
Documentation see the `_is_julian` function.
"""
years = np.array(y,ndmin=1)
months = np.array(m,ndmin=1)
days = np.array(d,ndmin=1)
years_count = np.size(years)
dim_check = ((years_count == np.size(mon... | 2e91330242cde9ef4a3483700d0a029a488e2bc5 | 3,634,503 |
import json
def parse(filename):
"""
Decode filename into an object
"""
template = None
template_lines = None
try:
(template, template_lines) = tf_plan_json.load(filename)
except tf_plan_json.JSONDecodeError:
pass
except json.decoder.JSONDecodeError:
# Most ... | d0dec4d63da1d8a92f6e025148ac69c6efde9234 | 3,634,504 |
def get_feature_dropping_corrections(bird_id='z007', session='day-2016-09-09', feat_type: str = 'pow', verbose=True):
""" Import the results of make_parameter_sweep
:param bird_id:
:param session:
:param verbose:
:return:
accuracy : ndarray, (bin_widths, offsets, num_folds, frequencies)
... | 1e7ee58c892673475369d0f6649cc42b96606f3a | 3,634,505 |
def build_pretraining_pipeline(
input_file,
output_dir,
output_suffix,
config,
dupe_factor,
min_num_rows,
min_num_columns,
num_random_table_bins = 1_000,
add_random_table = False,
num_corpus_bins = 1_000,
add_numeric_values = True,
):
"""Pipeline that maps interactions to T... | f8401afb557a7fdcfa9f69aa86e0c60f1807c44f | 3,634,506 |
import logging
def parse_arg_params(parser, upper_dirs=None):
""" parse all params
:param parser: object of parser
:param list(str) upper_dirs: list of keys in parameters
with item for which only the parent folder must exist
:return dict: parameters
"""
# SEE: https://docs.python.org/... | b770224cf54b7dc23896db88eb63d258c96b9da6 | 3,634,507 |
def rgb_to_hex_string(value):
"""Convert from an (R, G, B) tuple to a hex color.
:param value: The RGB value to convert
:type value: tuple
R, G and B should be in the range 0.0 - 1.0
"""
color = ''.join(['%02x' % x1 for x1 in [int(x * 255) for x in value]])
return '#%s' % color | 6449d5ecf8f3134ca320c784293d8ece44a84148 | 3,634,508 |
def view():
"""
This intercepts the /view URL get request. Displays the Page details for a application in a specific category.
It reads the query parameters given when passing in the URL
:return:
"""
application_category = request.args.get("show").upper()
result_data = application.get(sessi... | d2e62b12f2cc6e351d5b264a09c1c95a29f9baba | 3,634,509 |
def ancestors(G, x, G_reversed=None):
"""
Set of all ancestors of node in a graph, not including itself.
:param G: target graph
:param x: target node
:param G_reversed: you can supply graph with reversed edges for speedup
:return: set of ancestors
"""
if G_reversed is None:
G_rev... | 11a6930038807a677c3645d908a45b068c0f013b | 3,634,510 |
def range_to_list():
"""
This function is used to create an array of values from a dataset that's limits are given by a list lower and
upper limits. THIS IS CONFIGURED FOR MY COMPUTER, CHANGE THE DIRECTORY TO USE.
"""
dat1, filename1 = pick_dat(['t', 'm'], "RDAT_Test", "Select dataset to draw from")... | f4cd269f13a4580d43a4279a539d8b6a87a06683 | 3,634,511 |
def compute_a2b2(Q):
"""
Given the second moment matrix, compute a^2 and b^2
"""
Q11 = Q[0, 0]
Q22 = Q[1, 1]
Q12 = Q[0, 1]
a2t = 0.5 * (Q11 + Q22 + np.sqrt((Q11 - Q22) ** 2 + 4 * Q12 ** 2))
b2t = 0.5 * (Q11 + Q22 - np.sqrt((Q11 - Q22) ** 2 + 4 * Q12 ** 2))
a2, b2 = max(a2t, b2t), min... | 60d363066389d17a2d2bafa9b1c3733d884a7bcb | 3,634,512 |
def GausCV(traj,sample):
"""
returns matrix of gaussian CV's
"""
#m=7 - good
m=10
pen=0.
x = np.linspace(-5,5,m)
y = np.linspace(-5,5,m)
sigma_squared = 3.0
xx, yy = np.meshgrid(x,y)
d = m**2
#print(xx)
mu = np.concatenate((xx.reshape((-1,1)),yy.reshape((-1,1))),axis... | d366b5bc94fb1fb3b3201e0e54eaed3336067776 | 3,634,514 |
def _rgb_to_hex_string(rgb: tuple) -> str:
"""Convert RGB tuple to hex string."""
def clamp(x):
return max(0, min(x, 255))
return "#{0:02x}{1:02x}{2:02x}".format(clamp(rgb[0]),
clamp(rgb[1]),
clamp(rgb[2])) | eafd166a67ac568cfad3da1fa16bdfcd054a914a | 3,634,515 |
import math
def update_one_contribute_score(user_total_click_num):
"""
itemcf update sim contribution score by user
"""
return 1/math.log10(1 + user_total_click_num) | b6dadc87150e33e1ba2d806e18856f10fd43035a | 3,634,516 |
def NewtonRaphson(F, J, X0, eps=1e-4, mxiter=100):
"""
Solve nonlinear system F=0 by Newton's method.
J is the Jacobian of F. Both F and J must be functions of x.
At input, x holds the start value. The iteration continues
until ||F|| < eps.
Required Arguments:
-------------------
F:... | f93858c5e540d67a8d78315705a6b199e2cba365 | 3,634,517 |
def export2tf2onnx(model_onnx, opset=None, verbose=True, name=None,
rename=False, autopep_options=None):
"""
Exports an ONNX model to the :epkg:`tensorflow-onnx` syntax.
:param model_onnx: string or ONNX graph
:param opset: opset to export to
(None to select the one from the ... | 3ef4234a3e7e86634db3d7178a006789f0cac9d9 | 3,634,518 |
def default_interest_payment_date():
"""
利払日オブジェクトのデフォルト値
"""
return {
f'interestPaymentDate{index}': '' for index in range(1, 13)
} | 77d51cd5c7c76347a5c53e3d816985eeac1a568b | 3,634,519 |
from datetime import datetime
def log_message_prefix_generator(log_level: str) -> str:
"""
Parameters
----------
text: log_level
log level
e.g. "INFO", "WARN", ...
Returns
----------
str
logger prefix
e.g.
"[2020-06-17 20:21:12] [INFO]"
"""
... | 3b573632a9fce77a555531043eb3be0c92a862d5 | 3,634,520 |
from typing import Collection
def delete_beatmap(request, collection_id, beatmap_entry_id):
"""View for delete beatmap entry"""
collection = get_object_or_404(Collection, id=collection_id)
beatmap_entry = get_object_or_404(BeatmapEntry, id=beatmap_entry_id, collection=collection)
if request.user != co... | ce894b94287efa0a4b779537bde4122b78bd3378 | 3,634,521 |
import requests
def interactors_form(path, name):
"""
Parse file and retrieve a summary associated with a token
:param path: Absolute path to file to be read with custom interactor
:param name: Name which identifies the sample
:return:
"""
headers = {
'accept': 'application/json... | e193f0d8e1b9cf1fadcf4fff2668a09f755dab41 | 3,634,522 |
def _parent(child):
"""
Given a toast tile, return the address of the parent,
as well as the corner of the parent that this tile occupies
Returns
-------
Pos, xcorner, ycorner
"""
parent = Pos(n=child.n - 1, x=child.x // 2, y=child.y // 2)
left = child.x % 2
top = child.y % 2
... | 918feb49611be02c3ae686cbb0f06bf089187e92 | 3,634,523 |
from typing import List
from typing import Dict
import json
def get_all_set_list(files_to_ignore: List[str]) -> List[Dict[str, str]]:
"""
This will create the SetList.json file
by getting the info from all the files in
the set_outputs folder and combining
them into the old v3 structure.
:param... | 2f13a73d9a07e9790d23f0e6d961b6f3d058949f | 3,634,524 |
def extinction_afterglow_galactic_dust_to_gas_ratio(time, lognh, factor=2.21, **kwargs):
"""
Extinction with afterglow models and a dust-to-gas ratio
:param time: time in observer frame in days
:param lognh: log10 hydrogen column density
:param factor: factor to convert nh to av i.e., av = nh/facto... | 1d1bd28482361e5efc666f0111270c2c15500a7c | 3,634,525 |
def get_md_module(force_field):
"""
Returns the specific interface module that is referenced by
force_field.
"""
if force_field.startswith('GROMACS'):
return gromacs
elif force_field.startswith('AMBER'):
return amber
elif force_field.startswith('NAMD'):
return namd
else:
raise ValueError... | c6cc1c082f98cce3150f5e22b5cf0a6c3d654dd1 | 3,634,526 |
def select_student(database):
"""
Query student
:param database: database name
:return: student
"""
conn = create_connection(database)
with conn:
cur = conn.cursor()
cur.execute("SELECT * FROM student")
student = cur.fetchone()
conn.commit()
return student | 8ab7f01d769af28df95bd3de62634cb7148d9829 | 3,634,527 |
import torch
import copy
def clones(module, N):
"""Produce N identical layers.
"""
return torch.nn.ModuleList([copy.deepcopy(module) for _ in range(N)]) | 2def7cf89def4d598253ca48cb04e670ecb54dfd | 3,634,528 |
import json
def validate_search_results(search_results):
"""
Expects a list of mongo objects
"""
if not search_results:
return json.dumps({"Result Count": 0, "Results": []})
final_objs = format_mongo_objs(search_results)
response = {"Result Count": len(final_objs),
"Re... | 9209cf534a6553b0f1a3354a68e833dc832dc62b | 3,634,529 |
def format_command_args(args):
"""Format a command by removing unwanted values
Restrict what we keep from the values sent (with a SET, HGET, LPUSH, ...):
- Skip binary content
- Truncate
"""
length = 0
out = []
for arg in args:
try:
if isinstance(arg, (binary_typ... | 2d79adce1f4ec466f2ffc56f93a8fade8421dca5 | 3,634,530 |
import unittest
def suite() -> TestSuite:
"""You need to change the name of the test class here also."""
testSuite: TestSuite = TestSuite()
# noinspection PyUnresolvedReferences
testSuite.addTest(unittest.makeSuite(TestCoordinates))
return testSuite | ba8c21072dd6ee178ca4070b21607e95bcef3d93 | 3,634,531 |
def flow_diffusion_ode(C, X, pars):
"""
Scott's master, p. 60. X is the new Y and Z is the new X.
"""
C_N = C[-1]
C_ = C[0] - pars["alpha"] * (C[0] - pars["Cg"]) * pars["dZ"]
C_up = np.append(C[1:], C_N)
C_down = np.append(C_, C[:-1])
d2CdZ2 = (C_up - 2 * C + C_down) * pars["1/dZ**2"]
... | 8c0af7a42c3821cc6735a0971555e624c30b693f | 3,634,532 |
import math
def bl2xy(lon: float, lat: float):
""" 大地2000,经纬度转平面坐标,3度带
Param:
lon (float): 经度
lat (float): 纬度
Returns:
(x , y) : x坐标对应经度,y坐标对应纬度
"""
# 3.1415926535898/180.0
iPI = 0.0174532925199433
# 3度带
zoneWide = 3
# 长半轴
a = 6378137
# 扁率
f = 1... | 4f2166d7878998da5373a4fa6aff5fcee6f32c61 | 3,634,533 |
import numpy
def process_image(obj, img, config, each_blob=None, care_about_ar=True):
"""
:param obj: Object we're tracking
:param img: Input image
:param config: Controls
:param each_blob: function, taking a SimpleCV.Blob as an argument, that is called for every candidate blob
:return: Mask w... | e0de830cb843d6644634b08e80ace4ec911d16c5 | 3,634,534 |
def szepes_ml(local_d):
"""maximum likelihood estimator from local FSA estimates (for k=1)
:param numpy.ndarray of float local_d: local FSA estimates
:return: global ML-FSA estimate
"""
return hmean(local_d) / np.log(2) | 00dd82e634f8606c7bbde24daf2fc1c64ac8492a | 3,634,535 |
import math
def create_low_latency_conv_model(fingerprint_input, model_settings,
is_training):
"""Builds a convolutional model with low compute requirements.
This is roughly the network labeled as 'cnn-one-fstride4' in the
'Convolutional Neural Networks for Small-footprint Key... | 964be361d32e3b79e8909be4628ef6897f8d16e6 | 3,634,537 |
def sampling_from_enum_with_dirichlet_lm(enum_pool_dict_all, df_log2prob_by_syl, orig_seg_syl_df, lm_orig_dict, scale_num = 1000):
"""
get a sample lexicon with a orig language model
params:
@enum_pool_dict_all: enumerated words of all syllable lengths
(filtered to make sure that all words are ... | 94016dad1dc453ee217e57ade39f6478b670a9b5 | 3,634,538 |
def action_store(raw_val):
"""Auto type convert the value, if possible."""
if raw_val not in EMPTY_VALUES:
return auto_type_convert(raw_val)
else:
return raw_val | 3bed313c12f2a348cafd73111d3704c8c09198d9 | 3,634,539 |
def haversine_distance(coordinate: Point) -> float:
"""
Obtain the haversine distance between two cordinates points in the map
:param coordinate: shapely.geometry.point
:return: haversine distance in km:
"""
# MKAD coordinate
lat1, lon1 = 55.755826, 37.6173
# address coordi... | 6a730ec1afb9e5e131fd05be11176155c14a19b9 | 3,634,540 |
def route_home():
""" Renders the default page of the webserver, the leaderboard display"""
return render_template("home.html", data=leaderboard_manager.get_sorted_data()) | 94c44fb65615e40b67d1729d706e3e968434be71 | 3,634,541 |
def get_org_details(organization_id):
"""
Return the details for an organization
CLI Example:
.. code-block:: bash
salt-run digicert.get_org_details 34
Returns a dictionary with the org details, or with 'error' and 'status' keys.
"""
qdata = salt.utils.http.query(
"{}/or... | 4c19248b4ce0f6984e667924f481f914d8ba4fa8 | 3,634,542 |
def updatelimit():
"""Update sensorlimits."""
script_root()
print(request.form['id'])
print(request.form['value'])
#limit = SensorLimit.query.filter_by(id=request.form['id']).first()
#print(request.form['id'])
#print(limit)
#limit.value = request.form['value']
#db.session.commit(... | 46c67e995e642d84816e484017b22104b1867289 | 3,634,543 |
def trip_from_staging(conn, service, id_type = 'NUMERIC'):
"""Calculates the voronoi polygons for every active station in CitiBike and BayWheels
Parameters
----------
conn: psycopg2.extensions.connection
The connection to the database
service: str
The bike station service who... | cec99e09848f6fe828758960c5e53401a3f6116f | 3,634,544 |
def six_plot(ts, *plotargs, **plotkwds):
""" Output a matplotlib figure with full spectra, absorbance, area and
stripchart. Figure should be plotly convertable through py.iplot_mpl(fig)
assuming one is signed in to plotly through py.sign_in(user, apikey).
Parameters
-----------
title : st... | 4977eb62f7cc72c50599f5c5e64383b79881ef3f | 3,634,545 |
def woodbury_solve(vector, low_rank_mat, woodbury_factor, shift):
"""
Solves the system of equations: :math:`(sigma*I + VV')x = b`
Using the Woodbury formula.
Input:
- vector (size n) - right hand side vector b to solve with.
- woodbury_factor (k x n) - The result of calling woodbury_fa... | 92b25fe675671408c560008e4093c1e4b35d3c42 | 3,634,546 |
def get_user_by_email(email, create_pending=False):
"""finds a user based on his email address.
:param email: The email address of the user.
:param create_pending: If True, this function searches for external
users and creates a new pending User in case
... | 668230ec815c42ac48dfaffd8c79d9d8d9032fca | 3,634,549 |
def get_offset_from_var(var):
"""
Helper for get_variable_sizes)_
Use this to calculate var offset.
e.g. var_90, __saved_edi --> 144, -1
"""
instance = False
i=0
# Parse string
i = var.rfind(' ')+1
tmp = var[i:-1]
# Parse var
if tmp[0] == 'v':
tmp = tmp[4:]... | 6cf58d6dc2ffcb7a78d98ed83c2dbcf05933af76 | 3,634,550 |
def build_scoring_matrix(alphabet, diag_score, off_diag_score, dash_score):
"""
Takes as input a set of characters alphabet
and three scores diag_score, off_diag_score,
and dash_score. The function returns a dictionary
of dictionaries whose entries are indexed by pairs
of characters in alphabet plus '-'... | 703c3ef7fb6899a46a26d55dae740705b6953adb | 3,634,551 |
def _foldl_jax(fn, elems, initializer=None, parallel_iterations=10, # pylint: disable=unused-argument
back_prop=True, swap_memory=False, name=None): # pylint: disable=unused-argument
"""tf.foldl, in JAX."""
if initializer is None:
initializer = nest.map_structure(lambda el: el[0], elems)
el... | 1f876a90c25d52f52b9d0315670d68f1d58e9791 | 3,634,552 |
def MAD(a, c=0.6745, axis=None):
"""
Median Absolute Deviation along given axis of an array:
median(abs(a - median(a))) / c
c = 0.6745 is the constant to convert from MAD to std; it is used by
default
"""
a = ma.masked_where(a!=a, a)
if a.ndim == 1:
d = ma.median(a)
m... | 39762026de548a077ccb4c599ad540a04d6c508e | 3,634,553 |
import json
def save_browser_tree_state():
"""Save the browser tree state."""
data = request.form if request.form else request.data.decode('utf-8')
old_data = get_setting('browser_tree_state')
if old_data and old_data != 'null':
if data:
data = json.loads(data)
old_data =... | 6bdc8abc6c2189a6329f42f3df63f93c20aa9794 | 3,634,554 |
def prompt_yes_no(msg, default=False):
"""Prints the given message and continually prompts the user until they
answer yes or no. Returns true if the answer was yes, false otherwise."""
default_str = "no"
if default:
default_str = "yes"
result = prompt_w_default(msg, default_str, "^(Yes|yes|... | e42eb8e41c9251d0c5b046d445a6519b694cde4c | 3,634,555 |
def persistence_distance(
x: np.ndarray,
y: np.ndarray,
dimension: int=0,
persistence_feature: str="persistence_landscape"
) -> float:
"""Distances are euclidean on persistence features.
Args:
x: First datset.
y: Second dataset.
dimension: Dimension for persistence diagr... | 17f9242ae56ed1ff12111d17da3359060aaec963 | 3,634,556 |
def plot_pit_qq(pdf_ens, ztrue, qbins=101, title=None, code=None,
show_pit=True, show_qq=True,
pit_out_rate=None, outdir="", savefig=False) -> str:
"""Quantile-quantile plot
Ancillary function to be used by class Metrics.
Parameters
----------
pit: `PIT` object
... | 565aa0f3e4920f2e4e7340081d46a58647386b79 | 3,634,558 |
def rel_mole_weight(ion, ion_num, oxy_num):
"""
Calculating Relative Molecular Weight
:param ion: Each cation
:param ion_num: Number of cations per cation
:param oxy_num: The number of oxygen atoms corresponding to each cation
:return: Relative molecular weight
"""
ion_dict = {'Si':28.0... | c1d38209fb5468cac693bc90cfb333afff43100b | 3,634,559 |
def get_admin_token(chat_id):
"""
Get a administrador chat_id
"""
session = Session()
admin = session.query(Admin).\
filter_by(
chat_id=chat_id).first()
session.close()
if admin:
return admin.token
else:
return None | dca8be42237f62fc6336cb3d22637d2406aedfc6 | 3,634,560 |
import collections
import string
def index_of_coincidence(text):
"""Index of coincidence of a string. This is low for random text,
higher for natural langauge.
"""
stext = sanitise(text)
counts = collections.Counter(stext)
denom = len(stext) * (len(text) - 1) / 26
return (
sum(max... | a8a5e0f50dab24c3f3be525f30b6c5c5112a8a48 | 3,634,564 |
def get_allocations(jm_id:str) -> dict:
"""
Get Allocations
Get project allocations for user currently connected to remote system.
Parameters
----------
jm_id : str
ID of Job Manager instance.
Returns
------
allocations : dictionary
Dictionary containing informatio... | d3ad268b7f56bd48d51b1d150644e39ee6e8b7f3 | 3,634,565 |
import struct
def set_real(bytearray_: bytearray, byte_index: int, real) -> bytearray:
"""Set Real value
Notes:
Datatype `real` is represented in 4 bytes in the PLC.
The packed representation uses the `IEEE 754 binary32`.
Args:
bytearray_: buffer to write to.
byte_index: ... | bda32caab27adeae7c6710d4c26743b93533ccff | 3,634,566 |
def LogNormalAddLoc(builder, loc):
"""This method is deprecated. Please switch to AddLoc."""
return AddLoc(builder, loc) | 761522963da65b2ab05e4a687cad3ea44ebe3d1d | 3,634,567 |
def newton_raphson(x, y):
"""
The implementation of the `Newton-Raphson <https://en.wikipedia.org/wiki/Newton%27s_method>`_ optimization
procedure.
It fits the knee curve :math:`f(x)` to the :math:`y` s of the corresponding :math:`x` s by tweaking the shape
parameter :math:`c` from an initial guess.... | 6038effed89df29275123811f837f3d3e0f286a7 | 3,634,568 |
def _vx_no_BRST_check_massive_pp_zero(nhel, nsvahl):
"""
Parameters
----------
nhel: tf.Tensor, boson helicity of shape=()
nsvahl: tf.Tensor, helicity times particle|anti-particle absolute value
of shape=()
Returns
-------
tf.Tensor, of shape=(None,4) and dty... | bbe3fe72786f7944263254092da82d062310e10c | 3,634,569 |
def rst2node(data, env):
"""Converts a reStructuredText into its node"""
if not data:
return
parser = docutils.parsers.rst.Parser()
document = docutils.utils.new_document("<>")
document.settings = docutils.frontend.OptionParser().get_default_values()
document.settings.tab_width = 4
d... | 7ab3f8f80860a73e35cfb8ae2f1421c4b8a09533 | 3,634,570 |
def current_branch():
"""
Return the current branch
"""
return f'{REPO.active_branch}' | c995896fbde35b2d07a06139efb8fc9bc72dd667 | 3,634,571 |
from datetime import datetime
import hashlib
def _create_config_txn(pubkey, signing_key, setting_key_value):
"""Creates an individual sawtooth_config transaction for the given key and
value.
"""
setting_key = setting_key_value[0]
setting_value = setting_key_value[1]
nonce = str(datetime.dateti... | 5a4057657dc41c6403983d9ecded8b7194c5989e | 3,634,572 |
def round_unit(x, unit):
""" 按特定单位量对x取倍率
round_int偏向于工程代码简化,round_unit偏向算法,功能不太一样,所以分组不同
Args:
x: 原值
unit: 单位量
Returns: 新值,是unit的整数倍
>>> round_unit(1.2, 0.5)
1.0
>>> round_unit(1.6, 0.5)
1.5
>>> round_unit(7, 5)
5
>>> round_unit(13, 5)
15
"""
r... | b59f5f74fbf4622d1fa5b3fd7af6386b39eac784 | 3,634,573 |
import typing
import json
async def async_get_preference(connection, key: PreferenceKey) -> typing.Union[None, typing.Any]:
"""
Gets a preference by key.
:param key: The preference key, from the `PreferenceKey` enum.
:returns: An object with the preferences value, or `None` if unset and no default ex... | 4c3c5d4ee71d0e7dc85b7ef85075137dd639ee25 | 3,634,576 |
def index():
"""
View function for the index page.
"""
user: User = current_user
return \
"<div>" +\
f"<a href=\"{url_for('auth.logout')}\">Log out</a>" +\
f"<h1>Welcome {str(user)}</h1>" +\
"</div>" | 161d6bf4968bd3bed65d81470e33fff45a101329 | 3,634,577 |
import typing
def format_event_pull_request(data: typing.Dict[str, typing.Any]) -> str:
"""
Format a GitHub pull_request event into a string.
"""
resp = f"{format_author(data['sender'])} "
description = f"{format_issue_or_pr(data['pull_request'])} in {format_repo(data['repository'])}"
if data[... | 1c5dad5c4ca0218b14c46da6abc0615dbe7f8b6b | 3,634,579 |
def get_shape(obj):
"""
Get the shape of a :code:'numpy.ndarray' or of a nested list.
Parameters(obj):
obj: The object of which to determine the shape.
Returns:
A tuple describing the shape of the :code:`ndarray` or the
nested list or :code:`(1,)`` if obj is not an instance of ... | d02d755f4b9e4a4dbde6c87ddfe0b5729a8c158e | 3,634,582 |
import builtins
def help_ui_check_answer(capsys, r_input):
"""a function to calculate an equation from a combination
of four numbers to get 24"""
final_result = ''
with mock.patch.object(builtins, 'input', lambda _: r_input):
g_c.ui_check_answer()
out, err = capsys.readouterr()
... | 1cae7d98ef1a87c4a53416f44d5c49312fced197 | 3,634,583 |
import collections
def precision_recall(classifier, testfeats):
""" computes precision and recall of a classifier """
refsets = collections.defaultdict(set)
testsets = collections.defaultdict(set)
for i, (feats, label) in enumerate(testfeats):
refsets[label].add(i)
observed = classif... | 97a76fe595b26a9a5a307e799659fb96f1642941 | 3,634,584 |
import logging
def set_power_state_xavier(power_state: XavierPowerState) -> None:
"""Record the current power state and set power limit using nvpmodel."""
# Set power limit to the specified value
if is_xavier_agx():
platform = "xavier_agx"
elif is_xavier_nx():
platform = "xavier_nx"
... | 8b843acfff292b61dccf8ebc6433cb04446e5a7e | 3,634,585 |
from typing import Any
from typing import List
def as_list(x: Any) -> List[Any]:
"""Wrap argument into a list if it is not iterable.
:param x: a (potential) singleton to wrap in a list.
:returns: [x] if x is not iterable and x if it is.
"""
# don't treat strings as iterables.
if isinstance(x, ... | 4b1b26857d209a9f5b142908e3a35b1ce7b05be4 | 3,634,586 |
def _sort_destinations(destinations):
"""
Takes a list of destination tuples and returns the same list,
sorted in order of the jumps.
"""
results = []
on_val = 0
for dest in destinations:
if len(results) == 0:
results.append(dest)
else:
while on_val <... | 302480ef09f4b5a402a5c568c5d35d717db8c851 | 3,634,587 |
def Q8():
"""
Return the matroid `Q_8`, represented as circuit closures.
The matroid `Q_8` is a 8-element matroid of rank-4.
It is a smallest non-representable matroid. See [Oxl2011]_, p. 647.
EXAMPLES::
sage: from sage.matroids.advanced import setprint
sage: M = matroids.named_ma... | 469ca05d13655ee19618dd9ffa3001c0792982ac | 3,634,588 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.