content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def author(repo, subset, x):
"""``author(string)``
Alias for ``user(string)``.
"""
# i18n: "author" is a keyword
n = encoding.lower(getstring(x, _("author requires a string")))
return [r for r in subset if n in encoding.lower(repo[r].user())] | ee7bd62d52bd0e36ab910e53ca8e029780f4d6c6 | 15,809 |
def pianoroll_plot_setup(figsize=None, side_piano_ratio=0.025,
faint_pr=True, xlim=None):
"""Makes a tiny piano left of the y-axis and a faint piano on the main figure.
This function sets up the figure for pretty plotting a piano roll. It makes a
small imshow plot to the left of the main... | dc2a43be63d77ee99230399b687e86c09570db6c | 15,810 |
def exercise(request, exercisename):
"""Show single sport and its totals."""
e = exercisename
cur_user = request.user
exercises = Exercise.objects.filter(owner=cur_user, sport=e).order_by('-date')
context = {'exercises': exercises, 'total': Stats.total(cur_user, sport=e),
'totaltime'... | 8648673d6bdb3997d9b9d38155e2cb2039ff4f1b | 15,811 |
import random
def randomBinaryMatrix(scale, type):
"""
Generates a pseudo random BinaryMatrix of a given scale(small,large) and
datatype(int).
"""
if(scale == "small" and type == "int"):
nrow = random.randint(1, 10)
ncol = random.randint(1, 10)
data = []
for i in r... | 289d266eee4f6244774f7138e9efbe18970545f4 | 15,812 |
from typing import Optional
def load_batch(server_context: ServerContext, assay_id: int, batch_id: int) -> Optional[Batch]:
"""
Loads a batch from the server.
:param server_context: A LabKey server context. See utils.create_server_context.
:param assay_id: The protocol id of the assay from which to lo... | 731d463bc1e0380107390caabae8c57c7e6cff02 | 15,813 |
def canvas_compose(mode, dst, src):
"""Compose two alpha premultiplied images
https://ciechanow.ski/alpha-compositing/
http://ssp.impulsetrain.com/porterduff.html
"""
src_a = src[..., -1:] if len(src.shape) == 3 else src
dst_a = dst[..., -1:] if len(dst.shape) == 3 else dst
if mode == COMPO... | 9d95b840f814a77077050cb43a081c01c496640b | 15,814 |
import select
async def get_timelog_user_id(
*,
user_id: int,
epic_id: int,
month: int,
year: int,
session: Session = Depends(get_session),
):
"""
Get list of timelogs by user_id, month.
Parameters
----------
user_id : str
ID of user from which to pull timelogs.
... | fe4bdcbda40c2d32b743262cb14139e89890b237 | 15,815 |
def _cross(
vec1,
vec2,
):
"""Cross product between vec1 and vec2 in R^3"""
vec3 = np.zeros((3,))
vec3[0] = +(vec1[1] * vec2[2] - vec1[2] * vec2[1])
vec3[1] = -(vec1[0] * vec2[2] - vec1[2] * vec2[0])
vec3[2] = +(vec1[0] * vec2[1] - vec1[1] * vec2[0])
return vec3 | 2958a7365908bbd38c75f79e489d136f21fcc011 | 15,816 |
def _simplex_dot3D(g, x, y, z):
""" 3D dot product """
return g[0] * x + g[1] * y + g[2] * z | fcc48153b34af7cef0811f21fc04d22e6536797a | 15,817 |
import inspect
def __get_report_failures(test_data: TestData) -> str:
"""
Gets test report with all failed test soft asserts
:param test_data: test data from yaml file
:return: str test report with all soft asserts
"""
test_id = __get_test_id()
failed_assert_reports = __FAILED_EXPECTATION... | cedb24569acedf9bd251c233f220c44a1bb05772 | 15,818 |
def initialized_sm(registrations, uninitialized_sm):
""" The equivalent of an app with commit """
uninitialized_sm.initialize()
return uninitialized_sm | 491e4366b81379b053d1dea203d338766c3afa86 | 15,819 |
def coordinateToIndex(coordinate):
"""Return a raw index (e.g [4, 4]) from board coordinate (e.g. e4)"""
return [abs(int(coordinate[1]) - 8), ("a", "b", "c", "d", "e", "f", "g", "h").index(coordinate[0])] | d3dcf6d01c4bec2058cffef88867d45ba51ea560 | 15,821 |
import re
import logging
def parse_page(url):
"""parge the page and get all the links of images, max number is 100 due to limit by google
Args:
url (str): url of the page
Returns:
A set containing the urls of images
"""
page_content = download_page(url)
if page_conten... | 5833e0092650488e8ef430de0eafd79f6e5d2ffa | 15,822 |
def json_page_resp(name, page, paginator):
"""
Returns a standardized page response
"""
page_rows = paginator.get_page(page)
return JsonResponse({'page':page, 'pages':paginator.num_pages, name:[x['json'] for x in page_rows], 'size':len(page_rows)}, safe=False) | d615cfeaa2fafdb35333eee6aa6d63e1511a1dd3 | 15,824 |
from .interpreters import ScriptRunnerPlugin
def get_script_runner():
"""
Gets the script runner plugin instance if any otherwise returns None.
:rtype: hackedit.api.interpreters.ScriptRunnerPlugin
"""
return _window().get_plugin_instance(ScriptRunnerPlugin) | 2f76f46dd502fbd6ce9bd0a5f90eb7eed8bb64ca | 15,825 |
def latest_version():
"""
Returns the latest version, as specified by the Git tags.
"""
versions = []
for t in tags():
assert t == t.strip()
parts = t.split(".")
assert len(parts) == 3, t
parts[0] = parts[0].lstrip("v")
v = tuple(map(int, parts))
ver... | 346edcc6d087ca1511411b52de20b90f1a993f3a | 15,827 |
import string
def get_age_group(df,n: int=10):
"""Assigns a category to the age DR
Parameters
----------
df : Dataframe
n : number of categories
Returns
-------
Dataset with Age_group column
"""
df["Age_group"] = pd.cut(df["Age"], n, labels = list(string.ascii_upperc... | f793316c7c494adec1bfedf8613edf6c4ed5e2e2 | 15,828 |
def transformer_encoder_layer(query_input,
key_input,
attn_bias,
n_head,
d_key,
d_value,
d_model,
d_inner_hid,... | fe300a8c72c39c7e847f400f8f874dabab80b6e6 | 15,829 |
def generate(ode, lenght=int(2e4)):
"""
Time series generation from a ODE
:param ode: ODE object;
:param lenght: serie lenght;
:return: time serie.
"""
state = ode.initial_state
data = np.zeros([int(state.shape[0]), lenght])
for i in range(5000):
state = runge_kutta(ode... | 442f5359e3225d00cf0396e710e3978d1a6e37f8 | 15,830 |
def complexFormatToRealImag(complexVec):
"""
A reformatting function which converts a complex vector into real valued array.
Let the values in the input array be [r1+j*i1,r 2+j*i2,..., rN+j*iN]
then the output array will be [r1, i1, r2, i2,..., rN, iN]
:param complexVec: complex numpy ndarray
:r... | d955f2b31581036594ca79cd4755327eaa8b2446 | 15,831 |
def displayaction(uid):
""" Display the command from the xml file
"""
tree = ET.parse(OPENSTRIATOFILE)
root = tree.getroot()
textaction = root.findall("./action[@uid='"+uid+"']")
if len(textaction) == 0:
return "This UID does not exist!"
else:
return "UID %s action: %s" % (ui... | e34133a168b20cc9b018175ee5b4363fd2ff9690 | 15,832 |
def get_parent(inst, rel_type='cloudify.relationships.contained_in'):
"""
Gets the parent of an instance
:param `cloudify.context.NodeInstanceContext` inst: Cloudify instance
:param string rel_type: Relationship type
:returns: Parent context
:rtype: :class:`cloudify.context.RelationshipSubj... | 06bc76ec55735a47a3cf26df2daa4346290671ee | 15,833 |
def _query_param(key, value):
"""ensure that a query parameter's value is a string
of bytes in UTF-8 encoding.
"""
if isinstance(value, unicode):
pass
elif isinstance(value, str):
value = value.decode('utf-8')
else:
value = unicode(value)
return key, value.encode('utf... | 9c89517afd8d1684b1bb954f66cd2072296dee82 | 15,834 |
def _create_or_get_dragonnet(embedding, is_training, treatment, outcome, split, getter=None):
"""
Make predictions for the outcome, using the treatment and embedding,
and predictions for the treatment, using the embedding
Both outcome and treatment are assumed to be binary
Note that we return the l... | 7fc7fead338ac2c33bcfa016f9d66e34d15ac59c | 15,835 |
def fit_ols(Y, X):
"""Fit OLS model to both Y and X"""
model = sm.OLS(Y, X)
model = model.fit()
return model | dcc86cab7fe15400130febd36d5aa8139a68c64f | 15,836 |
def compute_modularity_per_code(mutual_information):
"""Computes the modularity from mutual information."""
# Mutual information has shape [num_codes, num_factors].
squared_mi = np.square(mutual_information)
max_squared_mi = np.max(squared_mi, axis=1)
numerator = np.sum(squared_mi, axis=1) - max_squ... | 5c81b583c6313818da435dd367a3d53933025227 | 15,837 |
import logging
def post_new_attending():
"""Posts attending physician information to the server
This method generates the new attending physician’s
dictionary with all of his/her information, then validates
that all of the information is the correct type. If the
validation stage is satisfied, the... | 18ddcb3bfcc601a22abccac7828ed6ac36368a33 | 15,839 |
def submitFeatureWeightedGridStatistics(geoType, dataSetURI, varID, startTime, endTime, attribute, value,
gmlIDs, verbose, coverage, delim, stat, grpby, timeStep, summAttr,
weighted, wfs_url, outputfname, sleepSecs, async=False):
"""
... | ab6f1cbeee1943f75aa16c9153d2a317113d2398 | 15,840 |
def fetch_words(url):
"""
Fetch a list of words from a URL
Args:
url: the url of any text document (no decoding to utf-8 added)
Returns:
A list of strings containing the words in the document
"""
with urlopen(url) as story:
story_words = []
for line in s... | 6679425f5f3680bd0b47888d59530a55b4c23443 | 15,841 |
def generate_fgsm_examples(sess, model, x, y, X, Y, attack_params, verbose, attack_log_fpath):
"""
Untargeted attack. Y is not needed.
"""
fgsm = FastGradientMethod(model, back='tf', sess=sess)
fgsm_params = {'eps': 0.1, 'ord': np.inf, 'y': None, 'clip_min': 0, 'clip_max': 1}
fgsm_params = overr... | 7b682622f843dd2c5d421c3d52b15e3a204edb0a | 15,842 |
def s3_bucket_for(bucket_prefix, path):
"""returns s3 bucket for path"""
suffix = s3_bucket_suffix_for(path)
return "{}-{}".format(bucket_prefix, suffix) | a59145474d2965a9e5f98d4728a6ac90d0d42cdf | 15,843 |
def regrid_create_operator(regrid, name, parameters):
"""Create a new `RegridOperator` instance.
:Parameters:
regrid: `ESMF.Regrid`
The `ESMF` regridding operator between two fields.
name: `str`
A descriptive name for the operator.
parameters: `dict`
... | 1c44dbe1c4826ee566cfb6b95ac704c9af19fc30 | 15,844 |
def _decode_hmc_values(hmc_ref):
"""Decrypts any sensitive HMC values that were encrypted in the DB"""
if hmc_ref is not None:
hmc_ref = jsonutils.to_primitive(hmc_ref)
#Make sure to DeCrypt the Password after retrieving from the database
## del two lines by lixx
#if hmc_ref.get(... | 7e1b33265811d79f245853cb016e5acd45627028 | 15,845 |
import logging
def dtensor_shutdown_tpu_system():
"""Shutdown TPU system."""
@def_function.function
def _shutdown_tpu_system():
return gen_dtensor_ops.shutdown_tpu_system()
success = _shutdown_tpu_system() if context.is_tfrt_enabled() else True
if success:
logging.info("TPU system shut down.")
e... | 23140407222646fd9adb845ae5e04ca4a3a9cc5a | 15,846 |
import json
import math
def edit_comment(request):
"""
Edit an existing comment
"""
response = {"status": "success",
"data": {}}
if "char_id" in request.POST:
char_id = request.POST["char_id"]
else:
response["status"] = "fail"
response["data"]["mess... | b56f0b3f3c0d0635b4faa9a06320bc4b715ea0d1 | 15,847 |
import torch
def make_positions(tensor, padding_idx, onnx_trace=False):
"""Replace non-padding symbols with their position numbers.
Position numbers begin at padding_idx+1. Padding symbols are ignored.
"""
# The series of casts and type-conversions here are carefully
# balanced to both work with ... | e5d117d64669f514b5cab4ad08ec526dd421493e | 15,849 |
import warnings
def taubin_curv(coords, resolution):
"""Curvature calculation based on algebraic circle fit by Taubin.
Adapted from: "https://github.com/PmagPy/PmagPy/blob/2efd4a92ddc19c26b953faaa5c08e3d8ebd305c9/SPD/lib
/lib_curvature.py"
G. Taubin, "Estimation Of Planar Curves, Surfaces And Nonplana... | f3728528dbec5681b3915683af22b8e9838e73ce | 15,850 |
import hmac
def calculate_mac(mac_type, credentials, options, url_encode=False):
"""Calculates a message authentication code (MAC)."""
normalized = normalize_string(mac_type, options)
digestmod = module_for_algorithm(credentials['algorithm'])
result = hmac.new(credentials['key'], normalized, digestmod... | 0701dbe3881ab500a70f3895af64d2ca6cb2905d | 15,852 |
import math
def run():
"""
Test Case - Fbx mesh group Import scaling in Atom:
1. Creates a new level called MeshScalingTemporaryLevel
2. Has a list of 12 meshes, which it will do the following for each one:
- Create an entity and attach the mesh to it.
- Sets it with an initial offset ... | fb7c5194d755e277e14f778c6fe52f9c5d1a36be | 15,853 |
def get_prime(num_dict):
"""获取字典里所有的素数"""
prime_dict = {}
for key, value in num_dict.items():
if value:
prime_dict.update({key: key})
return prime_dict | 49c62ae43bfe5af15f191cd8d831e82ae56c766d | 15,854 |
def get_shared_keys(param_list):
"""
For the given list of parameter dictionaries, return a list of the dictionary
keys that appear in every parameter dictionary
>>> get_shared_keys([{'a':0, 'b':1, 'c':2, 'd':3}, {'a':0, 'b':1, 'c':3}, {'a':0, 'b':'beta'}])
['a', 'b']
>>> get_shared_keys([{'a':0, 'd':3}, {'a':0... | 0f6aa0df4d61ba166ac7d660be80a98fdbc29080 | 15,855 |
def labeledTest(*labels):
"""This decorator mark a class as an integrationTest
this is used in the test call for filtering integrationTest
and unittest.
We mark the difference by the usage of service dependency:
* An unittest can run without additional services.
* An integration test need additi... | 4cb5adab516b19517066104d547d8efb0ae90cbd | 15,856 |
def birth(sim):
"""Similar to create agent, but just one individual"""
age = 0
qualification = int(sim.seed.gammavariate(3, 3))
qualification = [qualification if qualification < 21 else 20][0]
money = sim.seed.randrange(20, 40)
month = sim.seed.randrange(1, 13, 1)
gender = sim.seed.choice(['... | c44323bb36b5807e4b25a12bb739150bd70e1b98 | 15,857 |
def offer_better_greeting():
"""Give player optional compliments."""
player = request.args["person"]
# if they didn't tick box, `wants_compliments` won't be
# in query args -- so let's use safe `.get()` method of
# dict-like things
wants = request.args.get("wants_compliments")
nice_things... | 9f65f9a1169262020f6ec227d44e0160a904f00f | 15,858 |
def get_trip_length(grouped_counts):
"""
Gets the frequency of the length of a trip for a customer
Args:
grouped_counts (Pandas.DataFrame): The grouped dataframe returned from
a get_trips method call
Returns:
Pandas.DataFrame: the dataframe co... | 974bb0fc7f0430d0e6605857dba22f7b036e3945 | 15,859 |
def extract_begin_end(data):
""" Finds nif:beginIndex and nif:endIndex values.
:param data: Data sent by the client.
:return: Begin index and end index, -1 if error.
"""
try:
begin = data.split("nif:beginIndex")[1].split("\"")[1]
end = data.split("nif:endIndex")[1].split("\"")[1]
... | d5f5ce211f645f10d6a0aed1c6446963f0c3fe3e | 15,860 |
def setup_parameters():
"""
Helper routine to fill in all relevant parameters
Note that this file will be used for all versions of SDC, containing more than necessary for each individual run
Returns:
description (dict)
controller_params (dict)
"""
# initialize level parameters... | 6cadf729f8f796c6b07c94bf8b74913e6a893799 | 15,861 |
def get_operation(op, inplanes, outplanes, stride, conv_type):
"""Set up conv and pool operations."""
kernel_size = Ops.ops_to_kernel_size[op]
padding = [(k - 1) // 2 for k in kernel_size]
if op in Ops.pooling_ops:
if inplanes == outplanes:
return nn.AvgPool2d(kernel_size, stride=str... | f561db9c230236f3ead248e04cae198dbd9d4415 | 15,862 |
def encode(
structure_klifs_ids, fingerprints_filepath=None, local_klifs_download_path=None, n_cores=1
):
"""
Encode structures.
Parameters
----------
structure_klifs_ids : list of int
Structure KLIFS IDs.
fingerprints_filepath : str or pathlib.Path
Path to output json file.... | 7b5d3400455bdffc25e88cc07f58292f56ac6e12 | 15,863 |
def log_like_repressed(params, data_rep):
"""Conv wrapper for log likelihood for 2-state promoter w/
transcription bursts and repression.
data_rep: a list of arrays, each of which is n x 2, of form
data[:, 0] = SORTED unique mRNA counts
data[:, 1] = frequency of each mRNA count
Not... | 8451de8f1c578c8343bd1c91d1dc0326b51cc5a3 | 15,864 |
def freq_mask(spec, F=30, num_masks=1, pad_value=0.):
"""Frequency masking
Args:
spec (torch.Tensor): input tensor of shape `(dim, T)`
F (int): maximum width of each mask
num_masks (int): number of masks
pad_value (float): value for padding
Returns:
freq masked te... | 714dac7127e4dd1e790df016296321f97cfe37c7 | 15,865 |
def prepare_file_hierarchy(path):
"""
Create a temporary folder structure like the following:
test_find_dotenv0/
└── child1
├── child2
│ └── child3
│ └── child4
└── .env
Then try to automatically `find_dotenv` starting in `child4`
... | 25b66a7bc728f8f4b90cd9d8e678c914d2d60be9 | 15,866 |
def cmd2dict(cmd):
"""Returns a dictionary of what to replace each value by."""
pixel_count = cmd[cmd.shape[0] - 1, cmd.shape[1] - 1]
scaling_dict = dict()
for i in range(0, cmd.shape[0]):
scaling_dict[cmd[i, 0]] = round(
((cmd[i, 1] - cmd[0, 1]) / (pixel_count - cmd[0, 1])) * 255
... | 17f28fdcc5497c7d8d6aa55bbc61460e988586eb | 15,867 |
def cached_part(query, cache=None):
"""Get cached part of the query.
Use either supplied cache object or global cache object (default).
In the process, query is into two parts: the beginning of the query
and the remainder. Function tries to find longest possible beginning of the query
which is cache... | c1b8d9589b12171ae11e2f49911142252f54d9cd | 15,868 |
def exist_key(bucket: str, key: str) -> bool:
"""Exist key or not.
Args:
bucket (str): S3 bucket name.
key (str): Object key.
Returns:
bool: Exist or not.
"""
try:
s3.Object(bucket, key).get()
except s3.meta.client.exceptions.NoSuchKey:
return False
... | 1e47467c85d0461d76f0d562a2ee9c7cff5dbf4e | 15,869 |
def calculate_bleu_score(candidate_file: str, reference_file: str) -> float:
"""
Calculates the average BLEU score of the given files, interpreting each line as a sentence.
Partially taken from https://stackoverflow.com/a/49886758/3918865.
Args:
candidate_file: the name of the file that contain... | 00e6f6a852171f34b92598193fe1b08c60ba328b | 15,871 |
def _read_id_not_in_dict(read_ids, read_dict):
"""Return True if all read_ids in a list are not in the read_dict keys, otherwise False"""
for read_id in read_ids:
if read_id not in read_dict.keys():
return True
return False | 3a0e0926ed33f65cc67139311af1c860f3e371ae | 15,872 |
def generate_spectra_products(dataset, prdcfg):
"""
generates spectra products. Accepted product types:
'AMPLITUDE_PHASE_ANGLE_DOPPLER': Makes an angle Doppler plot of
complex spectra or IQ data. The plot can be along azimuth or along
range. It is plotted separately the module an... | ba279b7331fda0fdcb2ef506e91d13bd11f37d2f | 15,873 |
def odds_or_evens(my_bool, nums):
"""Returns all of the odd or
even numbers from a list"""
return_list = []
for num in nums:
if my_bool:
if num % 2 == 0:
return_list.append(num)
else:
if num % 2 != 0:
return_list.append(num)
re... | 02b3b12acbaae10b2b0e05eec059f6571c576e80 | 15,874 |
import numpy
def local_mass_diagonal(quad_data, basis):
"""Constructs the elemental mass matrix, diagonal version
Arguments:
quad_data - Quadrature points and weights
basis - Basis and respective derivatives
Returns:
Mass matrix M, where m_ii = \int_k psi_i psi_i
"""
retu... | ffaf34df758e73dea0db3ecb66de658991d8de58 | 15,875 |
def create_saved_group(uuid=None):
"""Create and save a Sample Group with all the fixings (plus gravy)."""
if uuid is None:
uuid = uuid4()
analysis_result = AnalysisResultMeta().save()
group_description = 'Includes factory-produced analysis results from all display_modules'
sample_group = Sa... | 7a9929518b44f6266f32300177385040b3da41c0 | 15,876 |
import copy
def words_to_indexes(tree):
"""Return a new tree based on the original tree, such that the leaf values
are replaced by their indexs."""
out = copy.deepcopy(tree)
leaves = out.leaves()
for index in range(0, len(leaves)):
path = out.leaf_treeposition(index)
out[path] = i... | 99e4ad2aa1d318af21d934aee2128b8d7b51a99f | 15,877 |
def get_stoplist_names():
"""Return list of stoplist names"""
config = configuration()
return [name for name, value in config.items('stoplists')] | a93dec87fe840a1fab9d63527e7b54ae8a1c7cf5 | 15,878 |
def any_(criterions):
"""Return a stop criterion that given a list `criterions` of stop criterions
only returns True, if any of the criterions returns True.
This basically implements a logical OR for stop criterions.
"""
def inner(info):
return any(c(info) for c in criterions)
return in... | 600e7c1516cba6f0cd73812bcd43d5e194aa33d2 | 15,879 |
def validate_basic(params, length, allow_infnan=False, title=None):
"""
Validate parameter vector for basic correctness.
Parameters
----------
params : array_like
Array of parameters to validate.
length : int
Expected length of the parameter vector.
allow_infnan : bool, opti... | c3567a7f08656c3b815eded0a6788d904b5820a5 | 15,880 |
import torch
def unsorted_segment_sum(data, segment_ids, num_segments):
"""
Computes the sum along segments of a tensor. Analogous to tf.unsorted_segment_sum.
:param data: A tensor whose segments are to be summed.
:param segment_ids: The segment indices tensor.
:param num_segments: The number of ... | 7d8686d35afab975bff05d3cda50d1ceae537ab9 | 15,881 |
def create_parameters(address: str) -> dict:
"""Create parameters for address.
this function create parameters for having request from geocoder
and than return dictionary of parameters
Args:
address (str): the address for create parameters
Returns:
dict: takes the api key and Geoc... | 9ad1723cf2bec66e366e83b814ee746cdddf8289 | 15,882 |
import re
def standardizeName(name):
"""
Remove stuff not used by bngl
"""
name2 = name
sbml2BnglTranslationDict = {
"^": "",
"'": "",
"*": "m",
" ": "_",
"#": "sh",
":": "_",
"α": "a",
"β": "b",
"γ": "g",
" ": "",
... | 33caf35feb0c9dcc042add501a4470b1ccbd3b1c | 15,883 |
def _learning_rate_decay(hparams, warmup_steps=0):
"""Learning rate decay multiplier."""
scheme = hparams.learning_rate_decay_scheme
warmup_steps = tf.to_float(warmup_steps)
global_step = tf.to_float(tf.train.get_or_create_global_step())
if not scheme or scheme == "none":
return tf.constant(1.)
tf.log... | 4d171ef2cb13d2f103ac722be12cd594b6533c60 | 15,884 |
import re
def Register_User():
"""Validates register form data and saves it to the database"""
# Check if the fields are filled out
if not (request.form['username'] and request.form['email'] and request.form['password'] and request.form['passwordConf']):
return redirect(url_for('Register', messag... | 6a3ed4e99436845791d8025014f4fa4ddbaec86e | 15,886 |
def extreme_rank(df, col, n, bottom=True, keep=[]):
"""
Calculate the n top or bottom of a given series
"""
t = df[list(keep)+[col]].sort_values(col, ascending=bottom).iloc[:30]
count = t['NO_MUNICIPIO'].value_counts()
count.name = '#'
perc = t['NO_MUNICIPIO'].value_counts(nor... | 976395ceb26f72300cbc24b9cb849b0e47f45ba8 | 15,887 |
def ss_octile(y):
"""Obtain the octile summary statistic.
The statistic reaches the optimal performance upon a high number of
observations. According to Allingham et al. (2009), it is more stable than ss_robust.
Parameters
----------
y : array_like
Yielded points.
Returns
----... | a38256c3fa3e2d3c5d756883524d65a48b0585f5 | 15,888 |
def englishToFrench(englishText):
"""Translates English to French"""
model_id='en-fr'
fr_text = language_translator.translate(
text=englishText,
model_id=model_id).get_result()
return(fr_text['translations'][0]['translation']) | f1ebb6195d09230c1bac2b4351b0157813e6ca80 | 15,889 |
def calc_out_of_plane_angle(a, b, c, d):
"""
Calculate the out of plane angle of the A-D vector
to the A-B-C plane
Returns the value in radians and a boolean telling if b-a-c are near-collinear
"""
collinear_cutoff = 175./180.
collinear = 0
if abs(calc_angle(b, a, c)) > np.pi ... | e24c70e210cb8a454af07a1757864b9c241acaff | 15,890 |
def compute_distances(X, Y):
"""
Computes the Mahalanobis distances between X and Y, for the special case
where covariance between components is 0.
Args:
X (np.ndarray):
3D array that represents our population of gaussians. It is
assumed that X[0] is the 2D matrix contai... | da994051b2eb4cc614368ed2a035d7a8bf9dcade | 15,891 |
def op_item_info():
"""Helper that compiles item info spec and all common module specs
:return dict
"""
item_spec = dict(
item=dict(
type="str",
required=True
),
flatten_fields_by_label=dict(
type="bool",
default=True
),
... | 5bc4d3ff959e9642304dff31b910ea8a6c8a9d52 | 15,892 |
import collections
def unpack_condition(tup):
"""
Convert a condition to a list of values.
Notes
-----
Rules for keys of conditions dicts:
(1) If it's numeric, treat as a point value
(2) If it's a tuple with one element, treat as a point value
(3) If it's a tuple with two elements, tr... | c07e651031850896d46a94e6060c79a955ad10fd | 15,893 |
from aiida.common.datastructures import wf_data_types
from aiida.orm.workflow import Workflow
from aiida.backends.djsite.db import models
from aiida.djsite.db import models
def get_wfs_with_parameter(parameter, wf_class='Workflow'):
"""
Find workflows of a given class, with a given parameter (which must be a
... | 7ae1c11b9b6495341da853d67d3d38df2c7838cd | 15,895 |
def map_iou(boxes_true, boxes_pred, scores, thresholds = [0.4, 0.45, 0.5, 0.55, 0.6, 0.65, 0.7, 0.75]):
"""
Mean average precision at differnet intersection over union (IoU) threshold
input:
boxes_true: Mx4 numpy array of ground true bounding boxes of one image.
bbox format: (x1... | b33f6acf90a24ac473d36de4ceb06563bc1523f6 | 15,897 |
def draw_output_summary(model):
""" reads the data saved in the model class and depending on this data
chooses a visualization method to present the results with the help
of draw_optimization_overview """
if 'time_series' in model.log:
# no optimization has happend.
# hence... | c996bf588f0aa31f32e80d80d352e6a81203a84f | 15,898 |
def general_spline_interpolation(xs, ys, p, knots=None):
"""
NOTE: SLOW SINCE IT USES B()
xs,ys: interpolation points
p: degree
knots: If None, use p+1-regular from xs[0] to slightly past x[1]
returns cs, knots
"""
# number of interpolation points (and also control point... | fce53b173b6e8234d0c35418ec1455793a62fc61 | 15,899 |
def number_from_string(s):
"""
Parse and return number from string.
Return float only if number is not an int. Assume number can be parsed from
string.
"""
try:
return int(s)
except ValueError:
return float(s) | 50cc7defe7c60b536d184aaf91c2831ab63043e1 | 15,900 |
def ennAvgPool(inplanes,
kernel_size=1,
stride=None,
padding=0,
ceil_mode=False):
"""enn Average Pooling."""
in_type = build_enn_divide_feature(inplanes)
return enn.PointwiseAvgPool(
in_type,
kernel_size,
stride=stride,
... | ea48e911a48237dd7ba19f0515ca4cb2e02f2fa3 | 15,901 |
def acceptable(*args, acceptables):
"""
If the characters in StringVars passed as arguments are in acceptables return True, else returns False
"""
for arg in args:
for char in arg:
if char.lower() not in acceptables:
return False
return True | 607cc752fb61e8a9348bfdd889afcbb8a8ee5189 | 15,902 |
from typing import Optional
from typing import List
from typing import Union
import warnings
def get_confusion_matrix(
ground_truth: np.ndarray,
predictions: np.ndarray,
labels: Optional[List[Union[str, float]]] = None) -> np.ndarray:
"""
Computes a confusion matrix based on prediction... | e6e45bd987345c1fc773fc1d0eccf752b8ee637c | 15,903 |
def atom_explicit_hydrogen_valences(gra):
""" explicit hydrogen valences, by atom
"""
return dict_.transform_values(atom_explicit_hydrogen_keys(gra), len) | 2f37bfd890c0f15014b17c6bd32981231104055f | 15,904 |
def get_average(pixels):
"""
Given a list of pixels, finds the average red, blue, and green values
Input:
pixels (List[Pixel]): list of pixels to be averaged
Returns:
rgb (List[int]): list of average red, green, blue values across pixels respectively
Assumes you are returning in th... | 9cd694505f8d445732bc178b5d645ff273b298d1 | 15,905 |
def _leading_space_count(line):
"""Return number of leading spaces in line."""
i = 0
while i < len(line) and line[i] == ' ':
i += 1
return i | b28daa2845618df5030a79129bb7cec1167b149a | 15,906 |
def _get_marker_indices(marker, line):
""" method to find the start and end parameter markers
on a template file line. Used by write_to_template()
"""
indices = [i for i, ltr in enumerate(line) if ltr == marker]
start = indices[0:-1:2]
end = [i + 1 for i in indices[1::2]]
assert len(start)... | 4e68f6629fd94920ddc6290c75d92e8de7b467bb | 15,907 |
def get_wrapper_depth(wrapper):
"""Return depth of wrapper function.
.. versionadded:: 3.0
"""
return wrapper.__wrapped__.__wrappers__ + (1 - wrapper.__depth__) | c1c31c45a059c4ee56b39322e966d30b742ef86e | 15,909 |
def apiTest():
"""Tests the API connection to lmessage. Returns true if it is connected."""
try:
result = api.add(2, 3)
except:
return False
return result == 5 | 5d63720e78fe5e1bcecd2b1792a0f9bf6345595d | 15,910 |
from scipy import stats as dists
def get_distribution(dist_name):
"""Fetches a scipy distribution class by name"""
if dist_name not in dists.__all__:
return None
cls = getattr(dists, dist_name)
return cls | bebdb2578dd191b1d0ee1aea96e88d6be4bc144c | 15,911 |
def ece(y_probs, y_preds, y_true, balanced=False, bins="fd", **bin_args):
"""Compute the expected calibration error (ECE).
Parameters:
y_probs (np.array): predicted class probabilities
y_preds (np.array): predicted class labels
y_true (np.array): true class labels
Returns:
exp_ce (float): ... | 073d1190d71808de03002322679bb29d75a31258 | 15,912 |
def _call_or_get(value, menu=None, choice=None, string=None, obj=None, caller=None):
"""
Call the value, if appropriate, or just return it.
Args:
value (any): the value to obtain. It might be a callable (see note).
Keyword Args:
menu (BuildingMenu, optional): the building menu to pass... | b5ebf790913bbdaab980ae7f050a96748f1fd3e6 | 15,913 |
import re
def is_shared_object(s):
"""
Return True if s looks like a shared object file.
Example: librt.so.1
"""
so = re.compile('^[\w_\-]+\.so\.[0-9]+\.*.[0-9]*$', re.IGNORECASE).match
return so(s) | f6d2f5f589c468613004d06c7d213f899f31b7c4 | 15,914 |
def get_name(properties, lang):
"""Return the Place name from the properties field of the elastic response
Here 'name' corresponds to the POI name in the language of the user request (i.e. 'name:{lang}' field).
If lang is None or if name:lang is not in the properties
Then name receives the local name v... | 82bd6b0fe7e35dae39767b899b56b24ff91f01cb | 15,915 |
def get_task(name):
"""Return the chosen task."""
tasks_json = load_json('tasks.json')
return tasks_json[name] | 44e39dd9757247212e8e9923fd3f7756fd3b0b9a | 15,916 |
def aws_credentials(request: pytest.fixture, aws_utils: pytest.fixture, profile_name: str):
"""
Fixture for setting up temporary AWS credentials from assume role.
:param request: _pytest.fixtures.SubRequest class that handles getting
a pytest fixture from a pytest function/fixture.
:param aws_u... | 13d1549b74b597cf3b00f98a5012c4bae111eeeb | 15,917 |
def mean_predictions(predicted):
"""
Calculate the mean of predictions that overlaps. This is donne mostly to be able to plot what the model is doing.
-------------------------------------------------------
Args:
predicted : numpy array
Numpy array with shape (Number points to predic... | 7ee19312ad17b97b27fe74a35df43ea4fa1ec709 | 15,918 |
def find_best_classifier(data, possible_classifiers, target_classifier):
"""Given a list of points, a list of possible Classifiers to use as tests,
and a Classifier for determining the true classification of each point,
finds and returns the classifier with the lowest disorder. Breaks ties by
preferrin... | 7c3dc1f8fc0933f238b372fcd3bf3133c2958398 | 15,920 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.