content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def matching_poss(poss_1, poss_2):
"""Count how many rows the possibilities have in common.
Arguments:
poss_1 {np.array} -- possibilities 1
poss_2 {np.array} -- possibilities 2
Returns:
int -- the count/matches
"""
matches = 0
for row_2 in poss_2:
for row_1 in p... | 096214d8e2115afd21cbd76b28cafa54574cdfb1 | 3,656,043 |
from collections import Counter
def unk_emb_stats(sentences, emb):
"""Compute some statistics about unknown tokens in sentences
such as "how many sentences contain an unknown token?".
emb can be gensim KeyedVectors or any other object implementing
__contains__
"""
stats = {
"sents": 0... | 221b88e2124f3b8da2976a337476a11a7276a470 | 3,656,044 |
from typing import List
async def search_dcu(
ldap_conn: LDAPConnection, dcu_id: str = None, uid: str = None, fullname: str = None
) -> List[DCUUser]:
"""
Seach DCU AD for user
Args:
ldap_conn: LDAP connection to use for searching
uid: Usersname to search for
dcu_id: dcu stude... | 32444b30f1463332f51720eef3167c3495deeaec | 3,656,046 |
def jump(inst_ptr, program, direction):
"""Jump the instruction pointer in the program until matching bracket"""
count = direction
while count != 0:
inst_ptr += direction
char = program[inst_ptr]
if char == '[':
count += 1
elif char == ']':
count -= 1
... | 76c6c4dcf4dbc452e9f2b252522871fcca95c75d | 3,656,047 |
def center_image(IM, method='com', odd_size=True, square=False, axes=(0, 1),
crop='maintain_size', verbose=False, center=_deprecated,
**kwargs):
"""
Center image with the custom value or by several methods provided in
:func:`find_origin()` function.
Parameters
----... | 7b9793d720228a246df07c08a2aeda861108f92e | 3,656,049 |
def get_mapping(mapping_name):
"""
Reads in the given mapping and returns a dictionary of letters to keys. If the given mapping is a dictionary,
does nothing an returns the mapping
mpaping_name can be a path to different file formats
"""
# read in mapping
if type(mapping_name) =... | 1e4f99d14b242ba4e8760fafecd83cd32932a92c | 3,656,051 |
def evaluate(model, reward_gen, n_steps=1000000, delta=1):
"""Evaulate the regrets and rewards of a given model based on a given reward
generator
Args:
model (TYPE): Description
n_steps (int, optional): Description
delta (int, optional): Number of steps for feedback delay
re... | a326e905156f6ac195eeb993878ae651a13a306e | 3,656,052 |
def get_photo_from_response(response: dict):
"""
parse json response and return an Photo
Keyword arguments:
response -- meetup api response in a dict
return -> get or create Photo
"""
photo, create = Photo.objects.get_or_create(meetup_id=response["id"])
# add optional fields
if "... | 9f0aeee796c1131424a7f4292a2b712d2bf0158e | 3,656,053 |
from typing import Union
from typing import List
from typing import Tuple
def composition_plot(adata: AnnData, by: str, condition: str, stacked: bool = True, normalize: bool = True,
condition_sort_by: str = None, cmap: Union[str, List[str], Tuple[str]] = None,
**kwds) -> hv.c... | f2e588c0ce6d195201754885bbd90aae83b49ba7 | 3,656,054 |
def region_of_province(province_in: str) -> str:
"""
Return the corresponding key in ITALY_MAP whose value contains province_in
:param province_in: str
:return: str
"""
region = None
for r in ITALY_MAP:
for p in ITALY_MAP[r]:
if province_in == p:
region = ... | 1aa29235d569929a0cfbbc4258d45ba4f0171f3c | 3,656,055 |
def filter_stopwords(words:list)->iter:
"""
Filter the stop words
"""
words = filter(is_not_stopword, words)
return words | a5516886be0ce5c8671ef259baf38b04d61c511f | 3,656,056 |
def numpy_jaccard(box_a, box_b):
"""计算两组矩形两两之间的iou
Args:
box_a: (tensor) bounding boxes, Shape: [A, 4].
box_b: (tensor) bounding boxes, Shape: [B, 4].
Return:
ious: (tensor) Shape: [A, B]
"""
A = box_a.shape[0]
B = box_b.shape[0]
box_a_x1y1 = np.reshape(box_a[:, 2:], ... | 1c0aed3c354a9253c5f9278109cd13365941846c | 3,656,057 |
import uuid
def test_get_rule(client_rule_factory, client_response_factory, registered_rule):
"""Check request data that client uses to get a rule.
1. Create a subclass of the abstract client.
2. Implement send request so that it checks the request parameters.
3. Invoke the get_rule method.
4. Ch... | 62b8368072cebf0591137357167980a6d710a1f0 | 3,656,058 |
import colorsys
def summaryhsl(all_summaries, summary):
"""
Choose a color for the given system summary to distinguish it from other types of systems.
Returns hue, saturation, and luminance for the start of the range, and how much the hue can be randomly varied while staying distinguishable.
"""
... | 1e874aaa359a5d8bb566809fc2be212df2890885 | 3,656,059 |
def _get_cached_values(instance, translated_model, language_code, use_fallback=False):
"""
Fetch an cached field.
"""
if not appsettings.PARLER_ENABLE_CACHING or not instance.pk or instance._state.adding:
return None
key = get_translation_cache_key(translated_model, instance.pk, language_co... | e650eabbfde8b877519b9456dba9021dfa0f78e6 | 3,656,060 |
def tensor_index_by_list(data, list_index):
"""Tensor getitem by list of int and bool"""
data_shape = F.shape(data)
indexes_types = hyper_map(F.typeof, list_index)
if const_utils.judge_indexes_types(indexes_types, mstype.int_type + (mstype.bool_,)):
sub_tuple_index = const_utils.transform_sequen... | 99702ca58ebd7f316d83687804f09ac0639e3f17 | 3,656,061 |
def sample_ingridient(user, name='Salt'):
"""Create and return a sample ingridient"""
return Ingridient.objects.create(user=user, name=name) | 8904f11164a78959eb8073b80fa349155c1ae185 | 3,656,062 |
def remove_duplicates_from_list(params_list):
"""
Common function to remove duplicates from a list
Author: [email protected]
:param params_list:
:return:
"""
if params_list:
return list(dict.fromkeys(params_list))
return list() | 885b2e048ec672bd2d24fabe25066bc2df3ea8a8 | 3,656,063 |
from typing import Sequence
def _scale_and_shift(
x: chex.Array,
params: Sequence[chex.Array],
has_scale: bool,
has_shift: bool,
) -> chex.Array:
"""Example of a scale and shift function."""
if has_scale and has_shift:
scale, shift = params
return x * scale + shift
elif has_scale:
as... | 68c7128ff7c1788cd77e3737adff293f488e190e | 3,656,066 |
import math
def get_distance_metres(aLocation1, aLocation2):
"""
Returns the ground distance in metres between two LocationGlobal objects
:param aLocation1: starting location
:param aLocation2: ending location
:return:
"""
dlat = aLocation2.lat - aLocation1.lat
dlong = aLocation2.lon... | 5f1428c099f79ba8b41177f87e6a3bffed13e00b | 3,656,067 |
import scipy
def merge_components(a,c,corr_img_all_r,U,V,normalize_factor,num_list,patch_size,merge_corr_thr=0.6,merge_overlap_thr=0.6,plot_en=False):
""" want to merge components whose correlation images are highly overlapped,
and update a and c after merge with region constrain
Parameters:
---------... | e2e15c208ae71ba20cc84d8c0501485c04e41a90 | 3,656,068 |
def RenderSubpassStartInputAttachmentsVector(builder, numElems):
"""This method is deprecated. Please switch to Start."""
return StartInputAttachmentsVector(builder, numElems) | 484ba9746f278cfcc7d50a282605ebc9a3a4fb2b | 3,656,069 |
def GetCLInfo(cl_info_str):
"""Gets CL's repo_name and revision."""
return cl_info_str.split('/') | d077216b2804c249a7d0ffdbff7f992dde106501 | 3,656,070 |
def acyclic_run(pipeline):
"""
@summary: 逆转反向边
@return:
"""
deformed_flows = {'{}.{}'.format(flow[PWE.source], flow[PWE.target]): flow_id
for flow_id, flow in pipeline[PWE.flows].items()}
reversed_flows = {}
while True:
no_circle = validate_graph_without_circle(... | 535edb2a7ccd1c0995fe46bff8a931175c353e51 | 3,656,071 |
def TextAreaFieldWidget(field, request): # pylint: disable=invalid-name
"""IFieldWidget factory for TextWidget."""
return FieldWidget(field, TextAreaWidget(request)) | 0d2431b1274e34978a6869efed0014982aaaa2e2 | 3,656,072 |
def s_wexler(T_K):
"""
Calculates slope of saturation vapor pressure curve over water at each temperature
based on Wexler 1976, with coefficients from Hardy 1998 (ITS-90).
Args:
T_K (np.ndarray (dimension<=2), float, list of floats) : Air or Dewpoint Temperatures [K]
Returns:
s : n... | b27b713b6c609115fa36f458c7f72358c001fbd5 | 3,656,074 |
from importlib import import_module
def get_additional_bases():
"""
Looks for additional view bases in settings.REST_EASY_VIEW_BASES.
:return:
"""
resolved_bases = []
for base in getattr(settings, 'REST_EASY_VIEW_BASES', []):
mod, cls = base.rsplit('.', 1)
resolved_bases.append... | 485c2f0d4778399ff534f40e681706419c3c923a | 3,656,075 |
from pathlib import Path
import warnings
def load_mask_from_shp(shp_file: Path, metad: dict) -> np.ndarray:
"""
Load a mask containing geometries from a shapefile,
using a reference dataset
Parameters
----------
shp_file : str
shapefile containing a polygon
metad : dict
r... | fd8178919b2afec71f69a8a7a00e1b2f224d2509 | 3,656,076 |
def est_corner_plot(estimation, settings=None, show=True, save=None):
"""Wrapper to corner plot of `corner <https://corner.readthedocs.io/en/latest/>`_ module;
visualisation of the parameter posterior distribution by all 2-dimensional and
1-dimensional marginals.
Parameters
----------
estimatio... | 87f9eda0dc3bf61f66d4ee28f693dad4ef383f24 | 3,656,077 |
def voigt_peak_err(peak, A, dA, alphaD, dalphaD):
"""
Gives the error on the peak of the Voigt profile. \
It assumes no correlation between the parameters and that they are \
normally distributed.
:param peak: Peak of the Voigt profile.
:type peak: array
:param A: Area under the Voigt p... | 52d3fbb7fabe5dfe2e5ab67bcd498d5434f7afc7 | 3,656,078 |
import typing
def discord_api_call(method: str, params: typing.Dict, func, data, token: str) -> typing.Any:
""" Calls Discord API. """
# This code is from my other repo -> https://gtihub.com/kirillzhosul/python-discord-token-grabber
# Calling.
return func(
f"https://discord.com/api/{method}"... | 84ea201c88dd4260bbc80dbd45654c01cb5a36ee | 3,656,080 |
import logging
def get_startup(config: Config) -> Startup:
"""Extracts and validates startup parameters from the application config
file for the active profile
"""
db_init_schema = config.extract_config_value(
('postgres', 'startup', 'init_schema'),
lambda x: x is not None and isinstan... | daa3809ed4f8be6c991796c8bbc11ee7b1434ee5 | 3,656,081 |
def new_request(request):
"""Implements view that allows users to create new requests"""
user = request.user
if user.user_type == 'ADM':
return redirect('/admin')
if request.method == "POST":
request_type = request.POST.get('requestType')
if request_type == 'SC' and user.user... | d90f72d5f299282709ed8a925569512a81d60591 | 3,656,082 |
def get_slice_test(eval_kwargs, test_kwargs, test_dataloader, robustness_testing_datasets):
"""
Args:
test_dataloader:
test_kwargs:
eval_kwargs (dict):
test_dataloader (Dataloader):
robustness_testing_datasets (dict):
Returns:
"""
slice_test = None
if '... | b995ff26fd743f106115c5d5958dd0654e0d4645 | 3,656,083 |
def transform_config(cfg, split_1='search:', split_2='known_papers:'):
"""Ugly function to make cfg.yml less ugly."""
before_search, after_search = cfg.split(split_1, 1)
search_default, papers_default = after_search.split(split_2, 1)
search, paper_comment = '', ''
for line in search_default.splitli... | 78d079b6b06c8426be2b65307782129c414a42c4 | 3,656,084 |
def filter_coords(raw_lasso, filter_mtx):
"""Filter the raw data corresponding to the new coordinates."""
filter_mtx_use = filter_mtx.copy()
filter_mtx_use["y"] = filter_mtx_use.index
lasso_data = pd.melt(filter_mtx_use, id_vars=["y"], value_name="MIDCounts")
lasso_data = lasso_data[lasso_data["MIDC... | fce1159db2a2bdb75acbe9b7ccb236af8bade627 | 3,656,085 |
def compute_threshold(predictions_list, dev_labels, f1=True):
"""
Determine the best threshold to use for classification.
Inputs:
predictions_list: prediction found by running the model
dev_labels: ground truth label to be compared with predictions_list
f1: True is using F1 score, F... | 230824c1454978cbe7c5f50ee43fba7b16754922 | 3,656,086 |
import torch
def color2position(C, min=None, max=None):
"""
Converts the input points set into colors
Parameters
----------
C : Tensor
the input color tensor
min : float (optional)
the minimum value for the points set. If None it will be set to -1 (default is None)
max : f... | 809d8cfd6f24e6abb6d65d5b576cc0b0ccbc3fdf | 3,656,087 |
def is_empty_parsed_graph(graph):
"""
Checks if graph parsed from web page only contains an "empty" statement, that was not embedded in page
namely (<subjectURI>, <http://www.w3.org/ns/md#item>, <http://www.w3.org/1999/02/22-rdf-syntax-ns#nil>)
:param graph: an rdflib.Graph
:return: True if graph co... | bf66271bc23f078669bc478a133b67c715fd8fdf | 3,656,088 |
def fillinNaN(var,neighbors):
"""
replacing masked area using interpolation
"""
for ii in range(var.shape[0]):
a = var[ii,:,:]
count = 0
while np.any(a.mask):
a_copy = a.copy()
for hor_shift,vert_shift in neighbors:
if not np.any(a.mask): break
a_shifted=np.roll(a_copy,shift=hor_shift,axi... | a8ffc34dac72cbd4ecdbbc9ad02270a457b0b8d9 | 3,656,089 |
from plistlib import loads, FMT_BINARY
from bplistlib import loads
def parse_plist_from_bytes(data):
"""
Convert a binary encoded plist to a dictionary.
:param data: plist data
:return: dictionary
"""
try:
return loads(data, fmt=FMT_BINARY)
except ImportError:
return loads(... | b9f96ef749af88bdb950d8f3f36b584f6766661d | 3,656,090 |
def projection_standardizer(emb):
"""Returns an affine transformation to translate an embedding to the centroid
of the given set of points."""
return Affine.translation(*(-emb.mean(axis=0)[:2])) | 65686636caeac72a16198ac6c7f603836eaedc53 | 3,656,091 |
def forward_imputation(X_features, X_time):
"""
Fill X_features missing values with values, which are the same as its last measurement.
:param X_features: time series features for all samples
:param X_time: times, when observations were measured
:return: X_features, filled with last measurements in... | ea0a41bfef02752338dc5384ce7fcd447c95f8c7 | 3,656,092 |
def calc_mlevel(ctxstr, cgmap, gtftree, pmtsize=1000):
"""
Compute the mean methylation level of promoter/gene/exon/intron/IGN in each gene
"""
inv_ctxs = {'X': 'CG', 'Y': 'CHG', 'Z': 'CHH'}
ign = defaultdict(list)
mtable = defaultdict(lambda: defaultdict(lambda: defaultdict(float)))
counter... | 59b3a36e09e6ea0dd3608da0cf04f14f4d487182 | 3,656,093 |
def _get_service(plugin):
"""
Return a service (ie an instance of a plugin class).
:param plugin: any of: the name of a plugin entry point; a plugin class; an
instantiated plugin object.
:return: the service object
"""
if isinstance(plugin, basestring):
try:
(plugin... | a3433521b40861926d9ac3efa6a693d926a7fc94 | 3,656,094 |
def taiut1(tai1, tai2, dta):
"""
Wrapper for ERFA function ``eraTaiut1``.
Parameters
----------
tai1 : double array
tai2 : double array
dta : double array
Returns
-------
ut11 : double array
ut12 : double array
Notes
-----
The ERFA documentation is below.
... | c7f9490a5af86de98c89af37cb6ca1bcb92d107a | 3,656,095 |
from SPARQLWrapper import SPARQLWrapper, JSON
def fetch_ppn(ppn):
"""
"""
ENDPOINT_URL = 'http://openvirtuoso.kbresearch.nl/sparql'
sparql = SPARQLWrapper(ENDPOINT_URL)
sqlquery = """
SELECT ?collatie WHERE {{
kbc:{ppn} dcterms:extent ?formaat, ?collatie .
FILTER (?forma... | fd974eccc7f4c099320c50a20b678d36cea7b899 | 3,656,096 |
def prepare_link_title(
item: feedparser.FeedParserDict) -> feedparser.FeedParserDict:
"""
Для RSS Item возвращает ссылку, заголовок и описание
:param item:
:return:
"""
result = None
if item:
assert item.title, 'Not found title in item'
assert item.link, 'Not found link ... | 445eccd9855484b65b726a4ee12a3dfa9a9de375 | 3,656,097 |
def api_docs_redirect():
""" Redirect to API docs """
return redirect('/api/v1', code=302) | d7ed10aa264d1403325f0b044b4c7b8b20b5989f | 3,656,098 |
from typing import List
def print_topics(model, vectorizer, top_n: int=10)-> List:
"""Print the top n words found by each topic model.
Args:
model: Sklearn LatentDirichletAllocation model
vectorizer: sklearn CountVectorizer
top_n (int): Number of words you wish to return
... | c0477c19c6806c2eaacb4165d332291dc0ba341b | 3,656,099 |
def create_logistic_vector(input_vector, cutoff):
"""
Creates a vector of 0s and 1s based on an input vector of numbers with a cut-off point.
"""
output_vector = np.zeros(len(input_vector))
n = 0
for i in range(len(input_vector)):
if input_vector[i] > cutoff:
output_vector[i... | bb4756f745f56fae7d8d4f0b1a1758ef6d70fb5a | 3,656,102 |
def profile(username):
""" user profile """
user = User.query.filter_by(username=username).first_or_404()
return render_template("user/profile.jinja.html", user=user) | 31e2a1b108c0652356cea92f32e9077105733726 | 3,656,103 |
def action_rescale(action):
"""Rescale Distribution actions to exp one"""
return np.array([0 if abs(a) < 0.5 else 10 ** (a-3) if a > 0 else -(10 ** (-a - 3)) for a in action * 3]) | 534509b76410eaeadee599e1ac510def8243e7ba | 3,656,104 |
def multi_knee(points: np.ndarray, t1: float = 0.99, t2: int = 3) -> np.ndarray:
"""
Recursive knee point detection based on the curvature equations.
It returns the knee points on the curve.
Args:
points (np.ndarray): numpy array with the points (x, y)
t1 (float): coefficient of determ... | ee44d9f51c843a0fb8e18f10057b5c6510dd8f3a | 3,656,105 |
def parse_dotted_path(path):
"""
Extracts attribute name from dotted path.
"""
try:
objects, attr = path.rsplit('.', 1)
except ValueError:
objects = None
attr = path
return objects, attr | 4685fad6461286b957a8d0056df2146fdd0f2e55 | 3,656,106 |
def resource_media_fields(document, resource):
""" Returns a list of media fields defined in the resource schema.
:param document: the document eventually containing the media files.
:param resource: the resource being consumed by the request.
.. versionadded:: 0.3
"""
media_fields = app.confi... | b54bc5f7fd35626866d70ce6d46bf0b84b9cf1b8 | 3,656,107 |
from typing import List
from typing import Tuple
def _parse_moving(message: List[str]) -> Tuple[Actions, str]:
"""Parses the incoming message list to determine if movement is found.
Args:
message: list of words in the player message
Returns: a tuple of the action and direction
"""
short... | 9785cbeb39dbc9ba980f605b648fb77855fe863d | 3,656,109 |
def _Net_forward_all(self, blobs=None, **kwargs):
"""
Run net forward in batches.
Take
blobs: list of blobs to extract as in forward()
kwargs: Keys are input blob names and values are blob ndarrays.
Refer to forward().
Give
all_outs: {blob name: list of blobs} dict.
"""
... | f5b6acf347e4fb85e0148d2d176042559f93b6a1 | 3,656,110 |
def email_members_old(request, course_prefix, course_suffix):
"""
Displays the email form and handles email actions
Right now this is blocking and does not do any batching.
Will have to make it better
"""
error_msg=""
success_msg=""
form = EmailForm()
if request.metho... | eeafa4d9c4ca0b0ad1b7ffaecceb03c188e02813 | 3,656,111 |
def Padding_op(Image, strides, offset_x, offset_y):
"""
Takes an image, offset required to fit output image dimensions with given strides and calculates the
padding it needs for perfect fit.
:param Image:
:param strides:
:param offset_x:
:param offset_y:
:return: Padded image
"""
... | d3f046069a597f2d7e3204b543f1f60c8e1e5b23 | 3,656,112 |
def area_triangle(point_a: array_like, point_b: array_like, point_c: array_like) -> np.float64:
"""
Return the area of a triangle defined by three points.
The points are the vertices of the triangle. They must be 3D or less.
Parameters
----------
point_a, point_b, point_c : array_like
... | 0c21ca96f8a6fd4d088cf0fa47a260b3bc582966 | 3,656,113 |
def test_valid(line):
"""Test for 40 character hex strings
Print error on failure"""
base_error = '*** WARNING *** line in torrent list'
if len(line) != 40:
print(base_error, 'incorrect length:', line)
elif any(char not in HEX for char in line):
print(base_error, 'has non-hex digits... | ca6517a8dd622b07703b30af7842685b9b6d5865 | 3,656,115 |
def custom_formatter(code, msg):
""" 自定义结果格式化函数
:param code: 响应码
:param msg: 响应消息
"""
return {
"code": code,
"msg": "hello",
"sss": "tt",
} | 59a7e3f9f03f9afc42b8faec6ebe23f5373d0bf0 | 3,656,117 |
def get_sampler_callback(rank, num_replicas, noniid=0, longtail=0):
"""
noniid: noniid controls the noniidness.
- noniid = 1 refers to completely noniid
- noniid = 0 refers to iid.
longtail: longtail controls the long-tailness.
- Class i takes (1-longtail) ** i percent of data.
... | 05e526ba903ebd834f248d965253344136e8a8a8 | 3,656,118 |
def alloc_bitrate(frame_nos, chunk_frames, pref_bitrate, nrow_tiles, ncol_tiles):
"""
Allocates equal bitrate to all the tiles
"""
vid_bitrate = []
for i in range(len(chunk_frames)):
chunk = chunk_frames[i]
chunk_bitrate = [[-1 for x in range(ncol_tiles)] for y in range(nrow_tiles)]
chunk_weight = [[1. for ... | 1883f480852d49e63c0408c9ef0daeba9e50db6b | 3,656,119 |
from typing import Collection
from typing import Any
def file_filter(extensions: Collection[str]) -> Any:
"""Register a page content filter for file extensions."""
def wrapper(f):
for ext in extensions:
_file_filters[ext] = f
return f
return wrapper | bef1a304497ffaac3f294607d8a393e505c1eb19 | 3,656,120 |
def epc_calc_img_size(reg_dict):
"""
Calcalute the output image size from the EPC660 sensor
Parameters
----------
reg_dict : dict
Returns
----------
int
The number of rows
int
The number of columns in the image
"""
col_start, col_end, row_start, row_end ... | 698b6ae6a99f8f9621c40ffaee2ab5ea5e584ce1 | 3,656,121 |
def simple_url_formatter(endpoint, url):
"""
A simple URL formatter to use when no application context
is available.
:param str endpoint: the endpoint to use.
:param str url: the URL to format
"""
return u"/{}".format(url) | 74f3e68fe10f7cc6bf8bfe81a7349a995bb79fa3 | 3,656,122 |
from typing import List
def generate_service(
name: str,
image: str,
ports: List[str] = [],
volumes: List[str] = [],
dependsOn: List[str] = [],
) -> str:
"""
Creates a string with docker compose service specification.
Arguments are a list of values that need to be added to each section... | 581e37e69d73ab5b6c0ac533bd91e7b5cb5187d9 | 3,656,123 |
def read_integer(msg=None, error_msg=None):
"""
Asks the user for an integer value (int or long)
:param msg: The message, displayed to the user.
:param error_msg: The message, displayed to the user, in case he did not entered a valid int or long.
:return: An int or a long from the user.
"""
... | c3067b436f57583b89ca02bff5e01802845ebf69 | 3,656,124 |
def percError(predicted, observed):
"""Percentage Error
Parameters
==========
predicted : array-like
Array-like (list, numpy array, etc.) of predictions
observed : array-like
Array-like (list, numpy array, etc.) of observed values of scalar
quantity
Returns
=======
... | 168affcb5af47563c15d27c6e662b0cf6411eca2 | 3,656,126 |
def _dict_eq(a, b):
"""
Compare dictionaries using their items iterators and loading as much
as half of each into a local temporary store. For comparisons of ordered
dicts, memory usage is nil. For comparisons of dicts whose iterators
differ in sequence maximally, memory consumption is O(N). Exec... | 68292489e4f6f8f213f4d17cf799052cb99ece37 | 3,656,127 |
from typing import Dict
from typing import List
def avoid_snakes(my_head: Dict[str, int], snakes: List[dict], possible_moves: List[str]) -> List[str]:
"""
my_head: Dictionary of x/y coordinates of the Battlesnake head.
e.g. {"x": 0, "y": 0}
snakes: List of dictionaries of x/y coordinates for e... | dcdd80522486ec1c6001aa8990f2bfaf88235ec1 | 3,656,128 |
def m_unicom_online_time2_0(seq):
"""
获取联通手机在网时长所对应的code
:param seq: 联通在网时长区间
:return: code
example:
:seq: [0-1]
:return 1
"""
if not seq:
return []
if seq[0] in ["[0-1]", "(1-2]", "[3-6]"]:
seq = ["(0_6)"]
elif seq... | 4a242d76f3d2708b5ad590830156a44fd22e7267 | 3,656,130 |
def convert_config_gui_structure(config_gui_structure, port, instance_id,
is_port_in_database, conf):
"""
Converts the internal data structure to a dictionary which follows the
"Configuration file structure", see setup.rst
:param config_gui_structure: Data structure used... | 3f46a621261ba097918fb5b5d27bd7611910a623 | 3,656,131 |
def message_similarity_hard(m1, m2):
"""
Inputs: One dimension various length numpy array.
"""
return int(np.all(m1==m2)) | 8f649a295853c34d692fb96a0a7facbc82d67ddb | 3,656,132 |
def identity_block(input_tensor, kernel_size, filters, stage, block):
"""
The identity_block is the block that has no conv layer at shortcut
Arguments
input_tensor: input tensor
kernel_size: defualt 3, the kernel size of middle conv layer at main path
filters: list of integers, the n... | 38a898a3b52f12490584206dfa6ea6b9819a1240 | 3,656,133 |
def convert_to_squad(story_summary_content, question_content, set_type):
"""
:param story_summary_content:
:param question_content:
:param category_content:
:param set_type:
:return: formatted SQUAD data
At initial version, we are just focusing on the context and question, nothing more,
... | 5b884ef521af4d5835fef25f01cb1f11d68cfafb | 3,656,134 |
def check_conditions(conditions, variable_dict, domain_dict, domain_list):
"""A function that checks if the generated variables pass the conditions and generates new ones until they do.
:param conditions: The conditions of the template.
:param variable_dict: List of variables.
:param domain_dict: the do... | fffd9889d3c149f56041753522aee245135cf0ee | 3,656,136 |
def set_pin_on_teaching_page(request,
section_label,
pin=True):
"""
if pin=True, pin the section on teaching page
if pin=False, unpin the section from teaching page
@except InvalidSectionID
@except NotSectionInstructorException
@except Us... | 385940e3adc286a923a94a3205b56c3817ee6284 | 3,656,137 |
from typing import Any
def inject_python_resources() -> dict[str, Any]:
"""
Inject common resources to be used in Jinja templates.
"""
return dict(
isinstance=isinstance,
zip=zip,
enumerate=enumerate,
len=len,
str=str,
bool=bool,
int=int,
... | 98fb7fbf39f20b9972ef5c0d35ae12b2864580b2 | 3,656,138 |
def get_feature_subsets_options(study, data_types):
"""Given a study and list of data types, get the relevant feature
subsets
"""
feature_subsets = ['custom']
if 'expression' in data_types:
try:
feature_subsets.extend(study.expression.feature_subsets.keys())
except Attrib... | d9310f00ff001f5ddc643998c7544df6ba5382b5 | 3,656,139 |
import json
def possibilities(q=0, *num):
"""
:param q: Número de quadrados a considerar
:param num: Em quantos quadrados a soma do nº de bombas é 1
:return:
pos -> Possibilidade de distribuição das bombas
tot -> Número de quadrados nos quais só há uma bomba
i -> Início da contagem dos qua... | 94c126a1bacf5bb242ad2935f949ab146f847001 | 3,656,140 |
import re
def parse_page_options(text):
"""
Parses special fields in page header. The header is separated by a line
with 3 dashes. It contains lines of the "key: value" form, which define
page options.
Returns a dictionary with such options. Page text is available as option
named "text".
... | b90b1adb7d5d6f8716b9d4e00b0e4b533393f725 | 3,656,141 |
def _read_16_bit_message(prefix, payload_base, prefix_type, is_time,
data, offset, eieio_header):
""" Return a packet containing 16 bit elements
"""
if payload_base is None:
if prefix is None:
return EIEIO16BitDataMessage(eieio_header.count, data, offset)
... | b552d06b314d47ee3ae928ebcee678c65bd24f84 | 3,656,142 |
def test_linear():
""" Tests that KernelExplainer returns the correct result when the model is linear.
(as per corollary 1 of https://arxiv.org/abs/1705.07874)
"""
np.random.seed(2)
x = np.random.normal(size=(200, 3), scale=1)
# a linear model
def f(x):
return x[:, 0] + 2.0*x[:, 1... | 6e716d6505162aa49507b026672455d357ab7c2b | 3,656,143 |
def csm_shape(csm):
"""
Return the shape field of the sparse variable.
"""
return csm_properties(csm)[3] | a74357086a9d7233cabed1c6ddc14fdbdbe0b41f | 3,656,144 |
def hyperlist_to_labellist(hyperlist):
"""
:param hyperlist:
:return: labellist, labels to use for plotting
"""
return [hyper_to_label(hyper) for hyper in hyperlist] | 9587694d783ccbd122b58894a2d80ee5e58dc900 | 3,656,145 |
import json
def _pretty_print_dict(dictionary):
"""Generates a pretty-print formatted version of the input JSON.
Args:
dictionary (dict): the JSON string to format.
Returns:
str: pretty-print formatted string.
"""
return json.dumps(_ascii_encode_dict(dictionary), indent=2, sort_k... | 17e94d18f824253540fd968c726721542f25a95e | 3,656,146 |
def _bivariate_kdeplot(x, y, filled, fill_lowest,
kernel, bw, gridsize, cut, clip,
axlabel, cbar, cbar_ax, cbar_kws, ax, **kwargs):
"""Plot a joint KDE estimate as a bivariate contour plot."""
# Determine the clipping
if clip is None:
clip = [(-np.inf, n... | ecb60ec3ffdc746f40b89158ef3c5b3a03e85bfc | 3,656,147 |
def unified_load(namespace, subclasses=None, recurse=False):
"""Provides a unified interface to both the module and class loaders,
finding modules by default or classes if given a ``subclasses`` parameter.
"""
if subclasses is not None:
return ClassLoader(recurse=recurse).load(namespace, subcla... | 62f5f4e17d3d232bfa72090a836f89f782068b53 | 3,656,149 |
def generate_free_rooms(room_times: dict) -> dict:
"""
Generates data structure for getting free rooms for each time.
"""
# create data format
free_rooms = {'M': {},
'Tu': {},
'W': {},
'Th': {},
'F': {}
}
#... | e60df355acd84e60c08ba34a45a2131d8d4519b4 | 3,656,150 |
def code_parse_line(li, pattern_type="import/import_externa"):
"""
External Packages
"""
### Import pattern
if pattern_type == "import":
if li.find("from") > -1:
l = li[li.find("from") + 4 : li.find("import")].strip().split(",")
else:
l = li.strip().split("impor... | 347b3d0c3192978beb4c26a1950d86482812310b | 3,656,151 |
def get_high(pair, path="https://api.kraken.com/0/public"):
""" Get the last 24h high price of `pair`.
Parameters
----------
pair : str
Code of the requested pair(s). Comma delimited if several pair.
path : str
Path of the exchange to request.
Returns
-------
float or d... | 8443ad24450e8f7bd2b6fac339e5e2b9149685c1 | 3,656,152 |
def SIx():
"""
Reads in future LENS SI-x data
Returns
----------
leafmean : array leaf indices (ens x year x lat x lon)
latmean : array last freeze indices (ens x year x lat x lon)
lat : array of latitudes
lon : array of longitudes
lstfrz : list last freeze indices
"""
... | 0ac033577d73c6567ebef10437a7e44e51bf5c79 | 3,656,153 |
import scipy
def make_truncnorm_gen_with_bounds(mean, std, low_bound, hi_bound):
"""
low_bound and hi_bound are in the same units as mean and std
"""
assert hi_bound > low_bound
clipped_mean = min(max(mean, low_bound), hi_bound)
if clipped_mean == low_bound:
low_sigma = -0.01 * std
... | 8e957d99141a56f804bebf931098fa147d066bb8 | 3,656,154 |
from invenio_app_ils.ill.api import BORROWING_REQUEST_PID_TYPE
from invenio_app_ils.ill.proxies import current_ils_ill
from invenio_app_ils.items.api import ITEM_PID_TYPE
from invenio_app_ils.proxies import current_app_ils
from invenio_app_ils.errors import UnknownItemPidTypeError
def resolve_item_from_loan(item_pid)... | f58ea857a445f2e6e01f426656f87a2032ea8306 | 3,656,155 |
def delta(s1, s2):
""" Find the difference in characters between s1 and s2.
Complexity: O(n), n - length of s1 or s2 (they have the same length).
Returns:
dict, format {extra:[], missing:[]}
extra: list, letters in s2 but not in s1
missing: list, letters in s1 but not in s2... | e439b5a4cf634f5e53fbf845b5774342cedeb404 | 3,656,157 |
def mean_predictive_value(targets, preds, cm=None, w=None, adjusted=False):
"""
:purpose:
Calculates the mean predictive value between a discrete target and pred array
:params:
targets, preds : discrete input arrays, both of shape (n,)
cm : if you have previously calculated a confus... | 9e7b7047d0dcf79509e544ca8bb0d621d1ce283d | 3,656,158 |
def delta(phase,inc, ecc = 0, omega=0):
"""
Compute the distance center-to-center between planet and host star.
___
INPUT:
phase: orbital phase in radian
inc: inclination of the system in radian
OPTIONAL INPUT:
ecc:
omega:
//
OUTPUT:
distance center-to-center, doubl... | 797d84618ade3e84b63a1a40e7728de77d5465ca | 3,656,159 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.