content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import click
def country_currency(code, country_name):
"""Gives information about the currency of a country"""
_data = return_country(currency_data, country_name)
if _data:
_, currency_name, the_code, symbol = _data
else:
return click.secho('Country does not exist. Perhaps, write the... | e576a5a1b6d06ef180c4cb648aecf54005501bc8 | 3,636,105 |
import numpy
import math
def decompose_matrix(matrix):
"""Return sequence of transformations from transformation matrix.
matrix : array_like
Non-degenerative homogeneous transformation matrix
Return tuple of:
scale : vector of 3 scaling factors
shear : list of shear factors for x... | c4ec66342720f91c1ec4dbe24c2a89d0b9e7e3f7 | 3,636,106 |
def GetMaxHarmonic( efit ):
"""Determine highest-order of harmonic amplitudes in an ellipse-fit object"""
# We assume that columns named "ai3_err", "ai4_err", "ai5_err", etc.
# exist, up to "aiM_err", where M is the maximum harmonic number
momentNums = [int(cname.rstrip("_err")[2:]) for cname in efit.colNames
... | e11645efa40ce3995788a05c8955d0d5a8804955 | 3,636,107 |
import math
def quaternary_tournament(population, scores, next_gen_number, random_seed=42):
"""Selects next generation using quaternary tournament selection for
single objective.
This function implements quaternary tournament selection to select a
specific number of members for the next generation.
... | e59311977358be3a28baeedc8a2e91e8f979eeeb | 3,636,108 |
def empty_list():
"""An empty list"""
return [] | 9d803d40be4c7aa7a6a07e94c19495582ab96154 | 3,636,109 |
def snapshot():
"""Creates a default initialized startup snapshot.
deno_core requires this, although it does not document this outside of a
few random mentions in issues.
"""
return Runtime(will_snapshot=True).snapshot() | 4a9b4be37b5f31c87897e7c3daa9e4cc6884584c | 3,636,110 |
def sample_user(email='riti2874@gmail.com', password='Riti#2807'):
"""Createing a smaple user"""
return get_user_model().objects.create_user(email, password) | 6bf20a2566070cd724bfac66b4591c45b858aef3 | 3,636,111 |
def is_chinese_prior_leap_month(m_prime, m):
"""Return True if there is a Chinese leap month on or after lunar
month starting on fixed day, m_prime and at or before
lunar month starting at fixed date, m."""
return ((m >= m_prime) and
(is_chinese_no_major_solar_term(m) or
is_chin... | c196a5135e79b9f3efa6cfcefa5b5f9b1dd175f5 | 3,636,112 |
import yaml
import json
def read_config_file(fname):
"""Reads a JSON or YAML file.
"""
if fname.endswith(".yaml") or fname.endswith(".yml"):
try:
rfunc = partial(yaml.load, Loader=yaml.FullLoader)
except AttributeError:
rfunc = yaml.load
elif fname.endswith(".js... | b86d61ee6d0d8027e325a9e436a031f9e171959d | 3,636,113 |
def plot_wo(wo, legend=True, **plot_kwargs):
"""Plot a water observation bit flag image.
Parameters
----------
wo : xr.DataArray
A DataArray containing water observation bit flags.
legend : bool
Whether to plot a legend. Default True.
plot_kwargs : dict
Keyword argum... | 5c756248d0bcc4dfb42e69a0a4e50c6321ed7023 | 3,636,114 |
def int_list_data():
"""Item data with an in list. [1, 2, 3, 4, 5, 6]"""
return easymodel.ListItemData([1, 2, 3, 4, 5, 6]) | 3306a7694d22e2ae9d8de64f3e1a01c27789d818 | 3,636,116 |
from typing import Dict
from typing import Any
from typing import Optional
def check_transaction_threw(receipt: Dict[str, Any]) -> Optional[Dict[str, Any]]:
"""Check if the transaction threw/reverted or if it executed properly by reading
the transaction receipt.
Returns None in case of success and t... | b79300c45fdb3c598d450cdf42ce2758e2cf8451 | 3,636,117 |
from typing import Callable
from typing import Coroutine
import functools
def button(style: ButtonStyle, label: str, **kwargs) -> Callable[..., Button]:
"""A decorator used to create buttons.
This should be decorating the buttons callback.
Parameters
----------
style: :class:`.ButtonStyle`
... | 6f5877f32aabcb921f835ecbe6158bd9cc4964d3 | 3,636,118 |
def AuxSource_Cast(*args):
"""
Cast(BaseObject o) -> AuxSource
AuxSource_Cast(Seiscomp::Core::BaseObjectPtr o) -> AuxSource
"""
return _DataModel.AuxSource_Cast(*args) | 10e149a342e9181636371f11152dc05e3942bd08 | 3,636,119 |
def to_byte_array(int_value):
"""Creates a list of bytes out of an integer representing data that is
CODESIZE bytes wide."""
byte_array = [0] * CODESIZE
for i in range(CODESIZE):
byte_array[i] = int_value & 0xff
int_value = int_value >> 8
if BIG_ENDIAN:
byte_array.reverse()
... | a44f952acd2d0525eed3dbe36b86ae1b305f6c37 | 3,636,120 |
def no_op(loss_tensors):
"""no op on input"""
return loss_tensors | 317474aa2ed41668781042a22fb43834dc672bf2 | 3,636,121 |
def get_example_two_cube(session, varcodes, selected_year=None):
""" Create 2D cube of flight routes per selector variable description, per date selector. """
cubes_api = aa.CubesApi(session.api_client)
# If no selected year, no underlying base query
if selected_year is None:
query = create_que... | 5c01f5d48910953fd6238fb987f284a3bfe4fad4 | 3,636,122 |
def svd_reduce(imgs, n_jobs):
"""Reduce data using svd.
Work done in parallel across subjects.
Parameters
----------
imgs : array of str, shape=[n_subjects, n_sessions]
Element i, j of the array is a path to the data of subject i
collected during session j.
Data are loaded ... | b8aaf939487a183bc0cb8498c6fa41ebc5c3b131 | 3,636,123 |
from typing import Tuple
from typing import List
def parse_project(record: Record, add_info: dict) -> Tuple[Pair, List[Pair], List[Pair]]:
"""Parse the project record in airtable to Billinge group format.
Return a key-value pair of the project and a list of key-value pairs of the people doc and institution d... | a999bd2d5ecc8742739f0143f8df939ff5906a04 | 3,636,124 |
def forbidden_handler_exc(message):
"""More flexible handling of 403-like errors. Used by raising ForbiddenError.
Args:
message (str) - Custom message to display
"""
return render_template('errors/403.html', message=message), 403 | 7a9d6280ac129496c4b50241453aba259812f10e | 3,636,125 |
import unittest
def run_test():
"""Runs the unit tests without test coverage."""
tests = unittest.TestLoader().discover('./tests', pattern='test*.py')
result = unittest.TextTestRunner(verbosity=2).run(tests)
if result.wasSuccessful():
return 0
return 1 | ae567c1821a83cde68f23c1bb51325ea02dcc15b | 3,636,126 |
def resnet34(num_classes: int = 1000, class_type: str = "single") -> ResNet:
"""
Standard ResNet 34 implementation;
expected input shape is (B, 3, 224, 224)
:param num_classes: the number of classes to classify
:param class_type: one of [single, multi] to support multi class training;
defau... | e0006ac140dd2969f140bcddebe7fd80b9609766 | 3,636,127 |
def linspace(start, stop, num=50):
"""
Linspace with additional points
"""
grid = list(np.linspace(start, stop, num))
step = (stop - start) / (num - 1)
grid.extend([0.1 * step, 0.5 * step, stop - 0.1 * step, stop - 0.5 * step])
return sorted(grid) | f416f3b86f062fca09b3be669a1651351621ad8a | 3,636,128 |
def strip_html(markdown):
"""
Strip HTML tags from a markdown string.
Entities present in the markdown will be escaped.
Parameters:
markdown: A :term:`native string` to be stripped and escaped.
Returns:
An escaped, stripped :term:`native string`.
"""
class Parser(HTMLParse... | 4d8c913a362f9e377b2dcd4172adadf378ffbff3 | 3,636,129 |
def find_character_occurences(processed_txt):
"""
Return a list of actors from `doc` with corresponding occurences.
"""
total_len = len(processed_text)
characters = Counter()
index = 0
for ent in processed_txt.ents:
if ent.label_ == 'PERSON':
characters[ent.lemma_] +... | e3407d1ae5055eb1e43438cde0e467b9f3cc48e1 | 3,636,130 |
import random
def parents_similarity(subject1, subject2, values):
"""
This function creates two new subjects by comparing the bits of the binary encoded provided subjects (the
parents). If both parents have the same bit in a certain location, the offspring have a very high probability
of having the sa... | 6fe49a5bb31b37abf49255534d6f6ae9a8301a59 | 3,636,131 |
import torch
def generic_fftshift(x,axis=[-2,-1],inverse=False):
"""
Fourier shift to center the low frequency components
Parameters
----------
x : torch Tensor
Input array
inverse : bool
whether the shift is for fft or ifft
Returns
-------
shifted array
"""
... | 8b5f84f0ed2931a3c1afac7c5632e2b1955b1cd5 | 3,636,132 |
def eval_ner(gold, sen, labels):
"""
evaluate NER
"""
if len(gold) != len(sen):
print(len(gold), len(sen))
raise "lenghts not equal"
tp = 0
#tn = 0
fp = 0
fn = 0
list_en = ["LOC", "MISC", "ORG", "PER"]
for en in list_en:
g = list_entities(gold, labels["... | 78daab9ca81466f4f66e5bb542abc9d7a747a44a | 3,636,133 |
def generate_data(m: int = 1000, n: int = 30, sigma: int = 40):
"""Generates data for regression.
To experiment with your own data, just replace the contents of this
function with code that loads your dataset.
Args
----
m : int
The number of examples.
n : int
The number of ... | 10763c3da63874b35a3173a5473f468edc6ff159 | 3,636,134 |
import logging
def read_datafile(path: str):
""" read a flight data file and unpack it """
with open(path, 'rb') as fp:
data = fp.read()
if len(data) != altacc_format.size:
logging.warning(f"invalid data file length, {len(data)} bytes!")
fields = altacc_format.unpack(data)
fligh... | 5683db563d2ece768c6efc66aab60d2cbe84b4aa | 3,636,135 |
def get_compiler_option():
""" Determines the compiler that will be used to build extension modules.
Returns
-------
compiler : str
The compiler option specificied for the build, build_ext, or build_clib
command; or the default compiler for the platform if none was
specified.
... | 944f4352255a83552164bf42dbcd9a976d43d1a8 | 3,636,136 |
def create_output_from_files(data_file_path:str, sheet_name:str, yaml_file_path:str, wikifier_filepath:str, output_filepath:str =None, output_format:str ="json"):
"""A convenience function for creating output from files and saving to an output file.
Equivalent to calling KnowledgeGraph.generate_from_files follo... | 6be2fb0ea1c57fd10c9a487756ed97615a76675d | 3,636,137 |
def make_new_images(dataset, imgs_train, imgs_val):
"""
Split the annotations in dataset into two files train and val
according to the img ids in imgs_train, imgs_val.
"""
table_imgs = {x['id']:x for x in dataset['images']}
table_anns = {x['image_id']:x for x in dataset['annotations']}
keys... | d5851974ad63caaadd390f91bdf395a4a6f1514d | 3,636,138 |
def test_similarity_sample_multiprocess(pk_target):
"""Test similarity cutoff filter"""
def weight(T):
return T ** 4
_filter = SimilaritySamplingFilter(sample_size=10, weight=weight)
pk_target.react_targets = True
pk_target.filters.append(_filter)
pk_target.transform_all(processes=2, g... | 41c6f370480a83c40598adbe3d3660fd4e09878f | 3,636,139 |
def compute_maximum_ts_map(ts_map_results):
"""
Compute maximum TS map across a list of given ts maps.
Parameters
----------
ts_map_results : list
List of `~gammapy.image.SkyImageCollection` objects.
Returns
-------
images : `~gammapy.image.SkyImageCollection`
Images (t... | c1ab40286d1db40f9d1b3a015871ac88dc7b5198 | 3,636,140 |
import gc
def compute_dist(array1, array2, type='euclidean'):
"""Compute the euclidean or cosine distance of all pairs.
Args:
array1: numpy array with shape [m1, n]
array2: numpy array with shape [m2, n]
type: one of ['cosine', 'euclidean']
Returns:
numpy array with shape [m1, m2]
... | a1bc531a5d640598f8eeb097b91daf66ec64b0df | 3,636,141 |
def timer(step, callback, *args):
"""定时器"""
s = internet.TimerService(step, callback, *args)
s.startService()
return s | b32ad6064e59937f46424ea4672d4ad86e5fcfcb | 3,636,142 |
import tkinter as tk
from tkinter import filedialog
def select_file(title: str) -> str:
"""Opens a file select window and return the path to selected file"""
root = tk.Tk()
root.withdraw()
file_path = filedialog.askopenfilename(title=title)
return file_path | 59fdb7945389c2ba75d27e1fe20b596c4497bac1 | 3,636,143 |
import ctypes
def drdpgr(body, lon, lat, alt, re, f):
"""
This routine computes the Jacobian matrix of the transformation
from planetographic to rectangular coordinates.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/drdpgr_c.html
:param body: Body with which coordinate system is associ... | 2224edb6413b9d7b3e56b748c1390299e7cea338 | 3,636,144 |
def data_context_topology_context_topologyuuid_nodenode_uuid_node_rule_groupnode_rule_group_uuid_inter_rule_groupinter_rule_group_uuid_cost_characteristiccost_name_get(uuid, node_uuid, node_rule_group_uuid, inter_rule_group_uuid, cost_name): # noqa: E501
"""data_context_topology_context_topologyuuid_nodenode_uuid_... | 34ac66f8d0317770df96a35b698cbb24551996ab | 3,636,145 |
from typing import List
async def joinUserChannel(cls:"PhaazebotTwitch", Message:twitch_irc.Message, Context:TwitchCommandContext) -> None:
"""
allowed user and admin to like phaaze to a channel
"""
alternative_target:str = ""
UserPerm:TwitchPermission = TwitchPermission(Message, None)
if UserPerm.rank >= Twit... | 072d14e3c2254b1d40f97261e4c22d9559896e52 | 3,636,146 |
import traceback
def copy_inputs(paths,
file_list):
""".. Create copies to inputs from list of files containing copying instructions.
Create copies using instructions contained in files of list ``file_list``. Instructions are `string formatted <https://docs.python.org/3.4/library/string.html... | c638e5c09490667f6aa376dbcc2668d152aafabe | 3,636,148 |
from typing import Tuple
from typing import List
def agaricus_lepiota() -> Tuple[np.ndarray, np.ndarray, np.ndarray, List[ALFeature]]:
"""
Source:
https://archive.ics.uci.edu/ml/datasets/Mushroom
The function requires the file 'agaricus-lepiota.data' to be in the current
folder.
Retu... | 35afd833171846eb2f6bf1424c12c63e3d9576b2 | 3,636,149 |
def patch286() -> PatchDiscriminator:
"""
Patch Discriminator from pix2pix
"""
return PatchDiscriminator([64, 128, 256, 512, 512, 512]) | 5a563d5fa1976ab24831c16846bc5ea91d78f581 | 3,636,151 |
def prefix(m):
"""Given a NFA `m`, construct a new NFA that accepts all prefixes of
strings accepted by `m`.
"""
if not m.is_finite():
raise ValueError('m must be a finite automaton')
f = set(m.get_accept_states())
size = None
while len(f) != size:
size = len(f)
for t... | dc0cba3a5060ea4dbf5a3d51fa42db2ca20383fc | 3,636,152 |
def _predict_k_neighbors(estimator, X):
"""Predict using a k-nearest neighbors estimator."""
X = estimator._validate_data(X, reset=False)
neigh_dist, neigh_ind = estimator.kneighbors(X)
neigh_Y = estimator._y[neigh_ind]
neigh_weights = _get_weights(neigh_Y, neigh_dist, estimator.weights)
retu... | b705c0c84cb3ebf5f3faf0db4e053dfb295527ea | 3,636,153 |
def _loop_over(var):
""" Checks if a variable is in the form of an iterable (list/tuple)
and if not, returns it as a list. Useful for allowing argument
inputs to be either lists (e.g. [1, 3, 4]) or single-valued (e.g. 3).
Parameters
----------
var : int or float or list
Variable to che... | 254143646416af441d3858140b951b7854a0241c | 3,636,154 |
def _get_servings_rest():
"""
Makes a REST request to Hopsworks to get a list of all servings in the current project
Returns:
JSON response parsed as a python dict
Raises:
:RestAPIError: if there was an error with the REST call to Hopsworks
"""
method = constants.HTTP_CONFIG.H... | 215c425ed0b2dd95e897de48ed5aed629f6eaa4f | 3,636,155 |
from typing import Any
from typing import List
from typing import Dict
def transform_database_account_resources(
account_id: Any, name: Any, resource_group: Any, resources: List[Dict],
) -> List[Dict]:
"""
Transform the SQL Database/Cassandra Keyspace/MongoDB Database/Table Resource response for neo4j... | dac566a1e09e1e395ff6fb78d6f8931a2bca58cb | 3,636,156 |
def jacsim(doc1, doc2, docsAsShingleSets,sign_matrix):
""" Jaccard Similarity.
:param doc1: First doc to be compared
:param doc2: Second doc to be comapred
:param docsAsShingleSets: Document wise shingles
:param sign_matrix: The Signature matrix
:return: The jaccard similarity value
"""
... | 78871ce8c2bf6fe0f975bc399c3a7baa74ef3b32 | 3,636,157 |
def symplot(b,
max_m = 20,
max_n = 20,
ymin = None,
sqrts = False,
log = True,
B0 = True,
helical_detail = False,
legend_args = {"loc":"best"},
**kwargs):
"""
Plot the radial variation of all the Fourier ... | 7d6b65f9cb3a95ea3b660b4181c76affc0b35a3b | 3,636,161 |
import struct
def get_arp_info(pkt):
"""
Break the ARP packet into its components.
"""
if len(pkt) < 8:
raise ARPError("ARP header too short")
ar_hrd, ar_pro, ar_hln, ar_pln, ar_op = struct.unpack("!HHBBH", pkt[0:8])
pkt_len = 8+(2*ar_hln)+(2*ar_pln)
if len(pkt) < pkt_len:
... | d45a64fc2a78c64a2cf730f1c605461f7f31a806 | 3,636,163 |
def update_ref_point(ref_point, fy):
"""
Update the reference point by an offspring
parameter
----------
ref_point: 1D-Array
the position of original reference point
fy: 1D-Array
the fitness values of the offspring
return
----------
1D-Array
the position of the up... | d821c765992a3d4474dec09b837be99c00d22be3 | 3,636,164 |
from typing import Any
def parse(grm: util.PathLike,
datum: str,
**kwargs: Any) -> interface.Response:
"""
Parse sentence *datum* with ACE using grammar *grm*.
Args:
grm (str): path to a compiled grammar image
datum (str): the sentence to parse
**kwargs: additi... | 37d004cb82c7b5b0a26b69402ad269636927862c | 3,636,165 |
import re
def ansyArticle(data):
"""分析错误日志"""
ids=[]
with open(data,'r') as fp:
i=0
for line in fp.readlines():
i+=1
if i%5==1:
m=re.search('view_(\d+)\.aspx',line)
ids.append(m.group(1))
else:
continue
return ids | 5c32ca500a4f94f5ab6b38ebc9ca8ab4521f8d8d | 3,636,168 |
def climb_stairs(n):
""" Number of paths to climb n stairs if each move comprises of climbing 1
or 2 steps.
Args:
n integer
Returns:
integer
Preconditions:
n >= 0
"""
return fib(n) | f54645e53d5ed001e023ba368f9e0c0c72d090d3 | 3,636,169 |
def randomInt(bit_length, seed):
"""Returns a random integer."""
s = randomHexString((bit_length + 3) / 4, seed)
return int(s, 16) % (1 << bit_length) | 9e226d189114ef6809b119f50f416fe3fd16beae | 3,636,170 |
import tqdm
import warnings
def best_fit_distribution(data, bins=200, ax=None):
"""Find the best fitting distribution to the data"""
# Get histogram of original data
y, x = np.histogram(data, bins=bins, density=True)
x = (x + np.roll(x, -1))[:-1] / 2.0
# Distributions to check
DISTRIBUTIONS =... | c13525e36b2ccd2e74fb4d3e3c5393ae3a623e72 | 3,636,171 |
def cumulative_completion_rate(completion_times, inc, top):
"""
Gets the cumulative completion rate data from an array of completion times.
Starting from zero, time is incremented by `inc` until `top` is reached
(inclusive) and the number of timestamps in `completion_times` under the
current time is... | e12659c30e4edca1e852f626c6eb54d2a5d95120 | 3,636,172 |
def sbol_empty_space (ax, type, num, start, end, prev_end, scale, linewidth, opts):
""" Built-in empty space renderer.
"""
# Default options
zorder_add = 0.0
x_extent = 12.0
# Reset defaults if provided
if opts != None:
if 'zorder_add' in list(opts.keys()):
zorder_add = o... | 81574119b6ecb1ece556ad02c9e78a6096a2dad5 | 3,636,174 |
def find_max_1(array: list) -> int:
"""
O(n^2)
:param array: list of integers
:return: integer
"""
overallmax = array[0]
for i in array:
is_greatest = True
for j in array:
if j > i:
is_greatest = False
if is_greatest:
overallm... | 9bab28c3d72062af75ac5c2e19c1e9d87e6fc468 | 3,636,175 |
def radec2xy(hdr,ra,dec):
"""Transforms sky coordinates (RA and Dec) to pixel coordinates (x and y).
Input:
- hdr: FITS image header
- ra <float> : Right ascension value in degrees
- dec <float>: Declination value in degrees
Output:
- (x,y) <tuple>: pixel coordinates
"""
wcs = wcs.WCS(hdr)
skycrd = n... | af829688cbbe72429042c5cb6c5e64f1efb47e57 | 3,636,176 |
def getStepsBySerialNoAndProcessID(SerialNo, ProcessID):
"""
根据流水号和表单ID获取该表单的所有的步骤
:param SerialNo:流水号
:param ProcessID:表单ID
:return:返回{"name":步骤名称,"value":步骤ID,"state":步骤状态}
"""
raw = Raw_sql()
raw.sql = "SELECT a.StepID as value, b.StepName as name, Finished as state FROM RMI_TASK_PROCESS_STEP a WITH(NOLOCK) ... | 5b6c31a9ff1225db20e8423add9804941bf15f73 | 3,636,177 |
def _split_train_dataset(y, tx, jet_num_idx=22):
"""Split the given training dataset into three distinct datasets.
Datasets are split depending on the value of the 'PRI_jet_num' column,
since this column dictates the -999 values for all the columns containing
the latter (except for the 'DER_mass_MMC' c... | b5ab9efff0655f03290c345d14a6f9bd5263a116 | 3,636,178 |
def bear(
transitions=None,
# Common settings
discount_factor=0.99,
# Adam optimizer settings
lr_q=1e-3,
lr_pi=1e-3,
lr_enc=1e-3,
lr_dec=1e-3,
# Training settings
minibatch_size=100,
polyak_rate=0.005,
# BEAR settings
... | 24a0ec3e0d8a2ce7074c019d93dcd424b5d967a8 | 3,636,179 |
def benchmark(setup=None, number=10, repeat=3, warmup=5):
"""A parametrized decorator to benchmark the test.
Setting up the bench can happen in the normal setUp,
which is applied to all benches identically, and additionally
the setup parameter, which is bench-specific.
Parameters
----------
... | 9ae9cbd0053e1485209881f4cac36241c33fe9d6 | 3,636,180 |
def make_dummy_protein_sequence(
n_supporting_variant_reads,
n_supporting_variant_sequences,
n_supporting_reference_transcripts,
n_total_variant_sequences=None,
n_total_variant_reads=None,
n_total_reference_transcripts=None,
gene=["TP53"],
amino_acids="MKH... | 8836afe5a4724779a58e78c5ba064ef63248f20f | 3,636,181 |
from typing import Optional
from typing import Tuple
def InlineEditor(item: Item, view, pos: Optional[Tuple[int, int]] = None) -> bool:
"""Show a small editor popup in the diagram. Makes for easy editing without
resorting to the Element editor.
In case of a mouse press event, the mouse position (relative... | f810e6721acb91bbe8f64a71bdab2442dd5b696f | 3,636,185 |
def getMetrics(trueLabels, predictedLabels):
"""Takes as input true labels, predictions, and prediction confidence scores and computes all metrics"""
MSE = sklearn.metrics.mean_squared_error(trueLabels, predictedLabels, squared = True)
MAE = sklearn.metrics.mean_absolute_error(trueLabels, predictedLabels)
... | 141ccca0342bea1ef5a69851b1514fc8bfeda091 | 3,636,186 |
from datetime import datetime
def create_data(feed_slug):
"""Post Data
Post a data point to a feed
---
tags:
- "Data Points"
parameters:
- name: feed_slug
in: path
type: string
required: true
- name: value
in: body
schema:
... | 99d8d8cc9ba6762ea3767d91204604282b1a10ce | 3,636,187 |
from typing import Optional
async def get_hitokoto(*, c: Optional[str] = None) -> Result.TextResult:
"""获取一言"""
url = 'https://v1.hitokoto.cn'
params = {
'encode': 'json',
'charset': 'utf-8'
}
if c is not None:
params.update({'c': c})
headers = HttpFetcher.DEFAULT_HEAD... | 00a5c498e1a27b96c35b0ec239e2d4e776edfda7 | 3,636,188 |
def img_unnormalize(src):
"""
Unnormalize a RGB image.
:param src: Image to unnormalize. Must be RGB order.
:return: Unnormalized Image.
"""
img = src.copy()
img *= NORMALIZE_VARIANCE
img += NORMALIZE_MEAN
return img.astype(np.uint8) | 2194a7c9c5cce225d61845093d51ad46d2ffc771 | 3,636,189 |
def upilab5_9_6() :
"""5.9.6. Exercice UpyLaB 5.26 - Parcours bleu rouge
Une matrice M = \{m_{ij}\} de taille {n}\times{n} est dite antisymétrique lorsque, pour toute paire d’indices i, j, on
a m_{ij} = - m_{ji}.
Écrire une fonction booléenne antisymetrique(M) qui teste si la matrice M reçue est antisymétrique.
Exe... | 0e082a94ae5c4c88ea5340679368ff07e3b30a56 | 3,636,190 |
def info(request):
"""provide readable information for *request*."""
qs = request.get('QUERY_STRING')
aia = IAdditionalInfo(request, None)
ai = aia and str(aia)
return (request.get('PATH_INFO', '')
+ (qs and '?' + qs or '')
+ (ai and (' [%s] ' % ai) or '')
) | 03ed0981ac758b090545225d3b6b4adfdce6c691 | 3,636,191 |
def put(entity_pb, **options):
"""Store an entity in datastore.
The entity can be a new entity to be saved for the first time or an
existing entity that has been updated.
Args:
entity_pb (datastore_v1.types.Entity): The entity to be stored.
options (Dict[str, Any]): Options for this re... | f7b6c9e7599f43d316999120fe49d22b57dfc5ea | 3,636,192 |
def get_country_flag(country):
"""Returns the corresponding flag of a provided country."""
with nation_flag_info as flag_path_info:
# Validate the provided nation string.
if country.title().replace('_', ' ') not in flag_path_info.keys() and \
country.title().replace(' ', '_') not in flag_path... | 21a2b4ed69e5963eb57e7de3f393cd6344184a1b | 3,636,193 |
def create_graph_to_decode_and_normalize_image():
"""See file docstring.
Returns:
input: The placeholder to feed the raw bytes of an encoded image.
y: A Tensor (the decoded, normalized image) to be fed to the graph.
"""
image = tf.placeholder(tf.string, shape=(), name='encoded_image_bytes')
with tf.n... | e7b72a4ff17db70248b6c08ca1a6565938935d99 | 3,636,194 |
def bilinear_upsample(x, scale=2):
"""Bilinear upsample.
Caffe bilinear upsample forked from
https://github.com/ppwwyyxx/tensorpack
Deterministic bilinearly-upsample the input images.
Args:
x (tf.Tensor): a NHWC tensor
scale (int): the upsample factor
Returns:
tf.Tenso... | b7b04ef1d6caf957ba96ad36b27e1efb96129db7 | 3,636,195 |
from typing import OrderedDict
def _generate_simplifiers_and_detailers():
"""Generate simplifiers, forced full simplifiers and detailers."""
simplifiers = OrderedDict()
forced_full_simplifiers = OrderedDict()
detailers = []
def _add_simplifier_and_detailer(curr_type, simplifier, detailer, forced=... | cd26bd70e0030077cfec9d60592b1848b50bcb09 | 3,636,196 |
def read_machine_def():
"""
Reads the machine definition file.
"""
return read_yaml_file(machine_def_file) | 35f55ee4d05337de656788724254626bea1706f8 | 3,636,197 |
import array
import scipy
def read_libsvm_format(file_path: str) -> 'tuple[list[list[int]], sparse.csr_matrix]':
"""Read multi-label LIBSVM-format data.
Args:
file_path (str): Path to file.
Returns:
tuple[list[list[int]], sparse.csr_matrix]: A tuple of labels and features.
"""
de... | 3c960b1ae2cbb56791c4d17164c7d491e2e47acf | 3,636,198 |
def cristal_load_motor(datafile, root, actuator_name, field_name):
"""
Try to load the CRISTAL dataset at the defined entry and returns it.
Patterns keep changing at CRISTAL.
:param datafile: h5py File object of CRISTAL .nxs scan file
:param root: string, path of the data up to the last subfolder ... | 9815c44965dce0a58de02a4d34b1fed7177baa57 | 3,636,199 |
def trackPlot(mat, fig=None, groups=None, ratios=None, labels=None, cmap=None, norm=None, is2D=False, xticks=False):
"""
This function takes a matrix and generates a track figure with several panel according to a group structure that groups
several rows/cols of the matrix into one panel. This can be done fo... | 9b59507cb46d5ff4196e43311771357d5b2826a2 | 3,636,200 |
def split_at(n, coll):
"""
Returns a tuple of ``(take(n, coll), drop(n coll))``.
"""
if n <= 0:
return [], coll
if coll is None:
return [], []
# Unfortunately we must consume all elements for the first case because
# unlike Clojure's lazy lists, Python's generators yield th... | 7c97e3ad7910b116e01c70925888ea371be11c72 | 3,636,202 |
def clip(x: ArrayLike, lo: ArrayLike = None, up: ArrayLike = None) -> ShapeletsArray:
"""
Element-wise, limits the values in an array
Parameters
----------
x: ArrayLike
Input array expression
lo: Optional ArrayLike (defaults: None)
Low values
up: Optional ArrayLike (defa... | 48c70dad730574a31b018c94c54cc785c680d6a1 | 3,636,203 |
def determineNewest(uid, homeType):
"""
Construct a query to determine the modification time of the newest object
in a given home.
@param uid: the UID of the home to scan.
@type uid: C{str}
@param homeType: The type of home to scan; C{ECALENDARTYPE},
C{ENOTIFICATIONTYPE}, or C{EADDRESS... | 88cfcd264639c6dc76807b4155592321e3a899b3 | 3,636,204 |
def get_data(limit = None, filename = "C:/Users/Marcel/OneDrive/Python Courses/Machine Learning/train.csv"):
"""
Reads the MNIST dataset and outputs X and Y.
One can set a limit to the number of rows (number of samples) by editing the 'limit'
"""
print("Reading in and transforming data...")
data... | 00933eb2b42180abbd8cf0e326d6e3b0c336131a | 3,636,205 |
def file_size(value, fmt="{value:.1f} {suffix}", si=False):
"""
Takes a raw number of bytes and returns a humanized filesize.
"""
if si:
base = 1000
suffixes = ("B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB")
else:
base = 1024
suffixes = ("B", "KiB", "MiB", "GiB"... | 272250966c0d301a86a136a7e84af6049e9fe47f | 3,636,207 |
def login():
"""
This method logs the user into the account.
It checks the username and the password in the database.
---
Args: None
Returns: If log in is successful redirects the user to account page
"""
if request.method == 'POST':
email = request.form.get('email')
pas... | 02ebd2b43b2f32465544efc8b8b5ff1684877fa8 | 3,636,208 |
def index_select_op_tensor(input, dim, index):
"""
input.index_select(dim, index) -> Tensor
See :func:`oneflow.index_select`
"""
return index_select_op(input, dim, index) | 8049ec1541c9120d505e07d1bd944fdeaf05d4ef | 3,636,209 |
def cull(dsk, keys):
""" Return new dask with only the tasks required to calculate keys.
In other words, remove unnecessary tasks from dask.
``keys`` may be a single key or list of keys.
Examples
--------
>>> d = {'x': 1, 'y': (inc, 'x'), 'out': (add, 'x', 10)}
>>> dsk, dependencies = cull... | b583f52835bc813e11092515aedb4d9943c7637c | 3,636,210 |
import torch
def validate_coot(config, model,
val_loader,
epoch,
constrastive_loss,
cmc_loss,
writer,
logger,
use_cuda=True):
"""Validate COOT model
Args:
model: COOT model
... | b6abd4fc6c6cb60ab1a82682754fd5f514c41ccf | 3,636,211 |
def iniStressProfile((z,dz),(zMin,zMax),ma):
"""initial acoustic stress profile
\param[in] z z-axis
\param[in] dz axial increment
\param[in] zMin start of new tissue layer
\param[in] zMax end of new tissue layer
\param[in] ma absorption coefficient
... | 60cfe2f240ea30bb278164b7211d6acaf7d4f778 | 3,636,212 |
def OpenCredentials(cred_path: str):
"""
Opens and parses an AWS credentials file.
:param cred_path: Path to the file containing the credentials
:return: A dict containing the credentials
"""
with open(cred_path) as file:
keys, values = map(lambda s: s.strip().split(','), file)
cred... | 2f224a92b6c3999a45f6d73bb90504663614a1ac | 3,636,213 |
def get_follow_users():
"""
Get all the users stored in the cookie
"""
follow_users = []
if "follow" in request.cookies:
follow_users = request.cookies["follow"]
follow_users = follow_users.split(delim)
return follow_users | df212f387af02938e4afc6baac24692598dd0f7f | 3,636,214 |
def generate_user_agent(os=None, navigator=None, device_type=None):
"""
Generates HTTP User-Agent header
:param os: limit list of os for generation, possible values:
"win", "linux", "mac", "android", "ios", "all"
:type os: string or list/tuple or None
:param navigator: limit list of browser... | cc5b4c251b088d61f00255c148c32a508c77dd1a | 3,636,215 |
def list_upcoming_assignments_calendar_events(request_ctx, **request_kwargs):
"""
Returns the current user's upcoming events, i.e. the same things shown
in the dashboard 'Coming Up' sidebar.
:param request_ctx: The request context
:type request_ctx: :class:RequestContext
:return: Li... | 2c7380eabe82f7180da3777a8cebc75a20345a32 | 3,636,216 |
def mse_loss(y,loc):
""" Mean squared error loss function
Use mean-squared error to regress to the expected value
Parameters:
loc: mean
"""
loss = (y-loc)**2
return K.mean(loss) | 9a3a1dc45680cf3ad8434d24c511041f7f054750 | 3,636,217 |
def _get_license_key_outputs(session):
"""Returns the account id and policy ARN for the license key secret if they exist"""
global __cached_license_key_nr_account_id
global __cached_license_key_policy_arn
if __cached_license_key_nr_account_id and __cached_license_key_policy_arn:
return __cached_... | a04aad32d9b192987462396023b117ecda91ea14 | 3,636,218 |
def get_sample_untransformed(shape, distribution_type, distribution_params,
seed):
"""Get a distribution based on specification and parameters.
Parameters can be a list, in which case each of the list members is used to
generate one row (or column?) of the resulting sample matrix. Ot... | 4b5a69920b8501ef4f57c9802dcea997c5df8587 | 3,636,219 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.