content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import torch
def compute_loss(
nn: NNApproximator, x: torch.Tensor = None, verbose: bool = False
) -> torch.float:
"""Compute the full loss function as interior loss + boundary loss
This custom loss function is fully defined with differentiable tensors therefore
the .backward() method can be applied ... | ada043f979e80dbbd5f2a37dd0d1dee62ee91bfd | 42,027 |
import typing
import copy
def wikifier_for_ethiopia_dataset(input_dataset: d3m_Dataset) -> typing.Tuple[bool, d3m_Dataset]:
"""
wrapped version for d3m dataset
"""
res_id, input_dataframe = d3m_utils.get_tabular_resource(dataset=input_dataset, resource_id=None)
wikifiered_dataframe = wikifier_... | 2fcd8ff9bfe59e790a34035b4f8109fd4e060214 | 42,028 |
def load_unknown(filepath):
"""Load any TSPLIB file.
This is particularly useful when you do not know in advance
whether the file contains a problem or a solution.
:param str filepath: path to a TSPLIB problem file
:return: either a problem or solution instance
"""
return load(filepath) | 91f651114b603587f84f7114723e5aa2735d4242 | 42,030 |
def admin_field_generator(verbose_name, function_changer=None, path_to_field=None, html=False,
boolean=False, limit=-1, wrap_white_space=True):
"""
This function generates admin_get decorators for being used in admin.py field methods.
:param function_changer: this function holds th... | cbbf9b9bfdf4ef2f16722f7a996a80db1fc39ecc | 42,031 |
import collections
def get_mbc_objectives(doc):
"""Return dict of MBC results."""
objectives = collections.defaultdict(set)
for rule in rutils.capability_rules(doc):
if not rule["meta"].get("mbc"):
continue
mbcs = rule["meta"]["mbc"]
if not isinstance(mbcs, list):
... | a67ea5aa6fe4b933b781bcaa8152be8787ab8749 | 42,034 |
def combine_histograms(histograms):
"""Takes a list of histograms and returns a new Histogram object that sums
the values in each bin.
All histograms in the list must be identical except for the count.
Parameters
----------
histograms: sequence
A lst of Histogram objects to combine.
... | 211d83a885397baa806422a7c7e27fd6d6a806dc | 42,035 |
def stick_module():
"""
@api {post} /v1/interfacemodule/stick InterfaceModule_置顶模块
@apiName interfaceModuleStick
@apiGroup Interface
@apiDescription 置顶模块
@apiParam {int} id 模块id
@apiParam {string} projectName 项目名称
@apiParamExample {json} Request-Example:
{
"id": 27,
"... | 4938de0d704674d6963412d8698425329964d4d5 | 42,036 |
def int_to_float(value: int) -> float:
"""Converts a uniformly random [[64-bit computing|64-bit]]
integer to uniformly random floating point number on interval <math>[0, 1)</math>.
"""
fifty_three_ones = 0xFFFFFFFFFFFFFFFF >> (64 - 53)
fifty_three_zeros = float(1 << 53)
return (value & fifty_thr... | 7619ec8d0987d9cac06655cab4e2d0787f1e3232 | 42,037 |
def load_attributes_from_hdf5_group(group, name):
"""Loads attributes of the specified name from the HDF5 group.
This method deals with an inherent problem
of HDF5 file which is not able to store
data larger than HDF5_OBJECT_HEADER_LIMIT bytes.
Args:
group: A pointer to a HDF5 group.
name: A nam... | 02913eb7966bb82e6d81ecee83dd51dc63de591a | 42,038 |
import json
def login():
""" Login to user's account """
# Get login and password
login = request.authorization["username"]
password = request.authorization["password"]
# Do some check in the database
if True:
# Set username/password in the response
session["username"] = logi... | aacd87c8cbded34d08e7bdf8aeb3a16c19179038 | 42,039 |
def rank_mols(data, feature):
"""Ranks (or clusters) the molecules according to specified feature which must a column name of data
is pIC50
:param data: dataframe with processed data. Outputted by read_mols
:type data: :class:`pandas.DataFrame` with columns (minimally) ['mol','atag','btag',feature]
... | 441c02d6dc466257366658b6b71471cc407b5ab3 | 42,040 |
import re
def linux_ipv4_addr_get_from_console(target, ifname):
"""
Get the IPv4 address of a Linux Interface from the Linux shell
using the *ip addr show* command.
:param tcfl.tc.target_c target: target on which to find the IPv4
address.
:param str ifname: name of the interface for which w... | cafb08f6bb5504896573287cb920337aece2f880 | 42,041 |
def translate(bboxes, x, y):
"""Map bboxes from window coordinate back to original coordinate.
Args:
bboxes (np.array): bboxes with window coordinate.
x (float): Deviation value of x-axis.
y (float): Deviation value of y-axis
Returns:
np.array: bboxes with original coordina... | 412ab4561407e2823a1fc63d855c9c18658177a4 | 42,043 |
def position_encoding(sentence_size, embedding_size):
"""
Position Encoding described in section 4.1 [1]
"""
encoding = np.ones((embedding_size, sentence_size), dtype=np.float32)
ls = sentence_size+1
le = embedding_size+1
for i in range(1, le):
for j in range(1, ls):
enc... | be5819d38c1611f329f80097ef7e465d0fa54d2e | 42,044 |
def import_(path):
"""
Import string format module, e.g. 'uliweb.orm' or an object
return module object and object
"""
if isinstance(path, str):
v = path.split(':')
if len(v) == 1:
x = path.rsplit('.', 1)
if len(x) == 2:
module, func = x
... | 70327d474a10f1860012cad0de1bbe934840d9b2 | 42,045 |
def animate(i):
"""
Animation function. Paints each frame. Function for Matplotlib's
FuncAnimation.
"""
img.set_data(mod_psis[i]) # Fill img with the modulus data of the wave function.
img.set_zorder(1)
return img, | 825b062d85f9c5bcb8abe0709ad77ba7b1c74750 | 42,046 |
def linear(input_, output_size, stddev=0.02, bias_start=0.0, activation_fn=None, name='linear'):
"""
Fully connected linear layer
:param input_:
:param output_size:
:param stddev:
:param bias_start:
:param activation_fn:
:param name:
:return:
"""
shape = input_.get_shape().a... | 3e1bf3ca4affe6f07300961f05a1bc4d37a8726b | 42,047 |
def aupr(preds, labels):
"""Calculate and return the area under the Precision Recall curve using unthresholded predictions on the data and a binary true label.
preds: array, shape = [n_samples]
Target scores, can either be probability estimates of the positive class, confidence values, or non-thresh... | d4ecd587cefc5b632490308ae45fc457c961509f | 42,048 |
def read_elementtree(xml_file):
"""Creates an ElementTree from an XML file"""
return ET.parse(xml_file) | 17d51576a568f6672249ed5c9476c5c706b89f4a | 42,050 |
import hashlib
def make_node() -> Node:
"""Make a dummy node."""
bel = f'p(HGNC:{n()})'
return Node(type=PROTEIN, bel=bel, md5=hashlib.md5(bel.encode('utf-8')).hexdigest(), data={}) | 55f9513efb5353369a96033ceb944fdea9566b09 | 42,052 |
def cryptoBook(symbol, token="", version="stable", filter="", format="json"):
"""This returns a current snapshot of the book for a specified cryptocurrency. For REST, you will receive a current snapshot of the current book for the specific cryptocurrency. For SSE Streaming, you will get a full representation of the... | 5291ecbb05d050a65b29d03cc425e6f3749c718e | 42,053 |
def noConsecDups(theList):
"""
noConsecDups is a function that takes a list of items or
a string and returns a copy of that string list with no
consecutive duplicates
produces: the same list with any consecutive duplicates remove
example: noConsecDups([2,3,3,3,4,4,5,6,6,2,2,1,5,3,3,2]
produ... | 3469b43ca2c661a6a6eaae8099f93c5af9f9384a | 42,054 |
def apply_repro_analysis_analysis(dataset, thresholds=[3.0], method = 'crfx'):
"""
perform the reproducibility analysis according to the
"""
nsubj, dimx, dimy = dataset.shape
func = np.reshape(dataset,(nsubj, dimx*dimy)).T
var = np.ones((dimx*dimy, nsubj))
xyz = np.reshape(np.indices(... | 706e99449f3181e65f070ddace26e4d88a409996 | 42,055 |
def run(config, Rs, Ts, cloud, tracks, masks):
"""
Entry point function for bundle adjustment. Parses input, feeds it to optimizes and parses the result back to same format
:param config: config object. See config.py for more information
:param Rs: list of R matrices
:param Ts: list of T vectors
... | b03ffee0bb8c74235176b7a7fbc25ba09878a1ad | 42,056 |
def get_notice(xml):
"""
Get NOTICE_DATA Information: some general information related to the
notice, or information which is extracted from the notice
:param xml:
:return: dictionary:
- NO_DOC_OJS: Notice number in TED
- ORIGINAL_NUTS: Region code(s) of the place of performance
... | 9a6677915a4a8527c6149731de95cea05c91b1a6 | 42,057 |
def dQ_dX(time):
"""Derivative of transformation matrix for nutation/presession with regards to the X coordinate of CIP in GCRS
"""
# Rotation matrices
R3_E = R3(E(time))
R3_s = R3(s(time))
R2_md = R2(-d(time))
R3_mE = R3(-E(time))
dR3_s = dR3(s(time))
dR3_E = dR3(E(time))
dR3_mE... | 0cec44bac5af7b69df25912afb87541c4ac5e68f | 42,058 |
def gcn(request, userDefinedListNumber):
"""Create a text only Discovery ATel list"""
userDefinedListRow = get_object_or_404(TcsObjectGroupDefinitions, pk=userDefinedListNumber)
listHeader = userDefinedListRow.description
initial_queryset = WebViewUserDefined.objects.filter(object_group_id = userDefin... | 983c95add2616b6831b98683c074b86d248b8161 | 42,059 |
def feature_action_values(feature, action, timestamp=None, request=None, response=None):
"""
**Recupero dello stato corrente per una specifica azione di una specifica feature**"""
return features_actions_values(feature, action, timestamp, request=request, response=response) | b2e624298c8194d471a8ad4d39b7a15215ce1c9a | 42,060 |
def compute_ctf(freqs,rots,akv,cs,wgh,dfmid1f,dfmid2f,angastf,dscale,bfactor=None):
""" Evaluate the CTF at a set of frequences, rotated by a certain amount """
av = akv * 1e3 # Convert kilovots to volts
cs = cs * 1e7 # Convert spherical aberation from mm to A
# wavelength of electrons
elambda... | 418371e9420e2ef399d9fbd3b5c0b18ea5f225da | 42,061 |
def sens_all(d_in, var, param_name, figure, func="mean"):
"""Plot seasonal sensitivity to a parameter."""
sens_out = {}
fig, axis = figure
cols_nh = ['2o', '3o', '2.', '1v']
cols_sh = ['2o', '0x', '1v', '2.']
param_vals = d_in[param_name]
nh_seas = d_in['{}_nh'.format(var)]
sh_seas = d_... | 5a6eb816efea372d3524fdb9e8f334387309128c | 42,062 |
def validate(value, ceiling):
"""
Checks if val is positive and less than the ceiling value.
:param value: The value to be checked (usually an int)
:param ceiling: The highest value "val" can be. (usually an int)
:return: True if val is less than ceiling and not negative
"""
value = int(val... | 0736674f74a38e0a583eeb2fae2ee1f441c1fda7 | 42,063 |
def tab_in_leading(s):
"""Returns True if there are tabs in the leading whitespace of a line,
including the whitespace of docstring code samples."""
n = len(s)-len(s.lstrip())
if not s[n:n+3] in ['...', '>>>']:
check = s[:n]
else:
smore = s[n+3:]
check = s[:n] + smore[:len(sm... | 84377a0e4737c1336d15b83d8011e4c2c054f365 | 42,064 |
def config_resolve_class_sorted(cookie, class_id, in_filter, in_size, in_hierarchical=YesOrNo.FALSE):
""" Auto-generated UCSC XML API Method. """
method = ExternalMethod("ConfigResolveClassSorted")
meta_class_id = coreutils.find_class_id_in_mo_meta_ignore_case(class_id)
if meta_class_id is not None:
... | 8d14ae5884185566e601603e50b6643d86a17b63 | 42,065 |
def mean_encoding(data: pd.DataFrame) -> Output(output_data=pd.DataFrame):
"""Mean encoding of categorical columns.
Args:
data: pd.DataFrame
"""
try:
data_processor = DataProcessor()
data = data_processor.mean_encoding(data)
return data
except ValueError:
log... | a6f9a7e7a1403a860321804a81ab1e11cb9b42f1 | 42,066 |
def erratum_check(agr_data, value):
"""
future: check a database reference has comment_and_corrections connection to another reference
:param agr_data:
:param value:
:return:
"""
# when comments and corrections loaded, check that an xref is made to value e.g. PMID:2 to PMID:8
return 'S... | f05b6835db3410b6e3705aab226571d916948594 | 42,067 |
def filter_features(ex):
"""Filters example features, keeping only valid model features."""
return {k: v for k, v in ex.items() if k in _MODEL_FEATURES} | 3f3ca6e8f018b44d694efcd1cb0cfc288863de54 | 42,068 |
def longestConsecutive3(list,missing=1):
""" assume list is a list
budget missing """
if len(list) == 0:
return 0
longest = 0
# print(range(len(list)-1))
starts = [ x for x in range(len(list)) ]
# print(starts)
for sindex in starts:
currentlen = 0
allow = missing
... | 52420837ee40be40e8d8d6ea9a6f25372bed8d55 | 42,069 |
def ComputeAncillaryFiles(cluster, redist):
"""Compute files external to Ganeti which need to be consistent.
@type redist: boolean
@param redist: Whether to include files which need to be redistributed
"""
# Compute files for all nodes
files_all = set([
pathutils.SSH_KNOWN_HOSTS_FILE,
pathutils.CO... | 09c4ada99162742ec62bd92557c2508624e88b0f | 42,070 |
def GhostNet(annotation_type, fixed_positions=None, memory_demanding=False):
"""
Get the GhostNet pipeline which will crop the face :math:`112 \\times 112` and
use the :py:class:`GhostNet` to extract the features
.. warning::
If you are at Idiap, please use the option `-l sge-gpu` while runnin... | 72557f01d312d656d0edf16a459bda2ac1b97109 | 42,072 |
import math
def TrainBaumWelsch(init_start, transitions, emissions, weights, observations, mutrates):
"""
Trains the model once, using the forward-backward algorithm.
"""
fractorials = np.zeros(len(observations))
for i, obs in enumerate(observations):
fractorials[i] = np.log(math.factori... | 9a0067fc53af2ef604f196abd10a2a19c2151649 | 42,073 |
def locale_switcher(current_locale=None):
"""Locale dropdown to switch user locale on localizer pages."""
return {
'current_locale': current_locale,
'locales': settings.AMO_LANGUAGES + settings.HIDDEN_LANGUAGES,
'languages': product_details.languages,
} | 99d3295d187fb632634bacad7f0cbaf92bf9c5bd | 42,074 |
def gen_vocab_dict(train_data):
"""
generate dict from training set's caption file (txt)
format of txt file:
id1 video_id1 caption1
id2 video_id2 caption2
...
"""
vocab = {}
inv_vocab = {}
vocab[''] = len(vocab)
inv_vocab[len(vocab) - 1] = ''
for line in train_data:
... | 56e7e596f20e2da81f1e40a059fca1bc80d21bde | 42,075 |
def fork_count(self, repo_group_id, repo_id=None):
"""
Returns the latest fork count
:param repo_group_id: The repository's repo_group_id
:param repo_id: The repository's repo_id, defaults to None
:return: Fork count
"""
if not repo_id:
fork_count_SQL = s.sql.text("""
SE... | c468499c19fb4db8ad7974ad303a09de07f05344 | 42,076 |
import urllib
import json
import time
def get_cards():
"""Download card data"""
params = "?" + urllib.parse.urlencode({"q": consts.card_query, "order": "released"})
next_page = consts.api_root + consts.search_endpoint + params
total_cards = None
cards = {
"last_updated": time_now().strfti... | 32681a886c4383c242d79fad9a0b1cbb55ceffcf | 42,077 |
import itertools
def select_workloads(argv, # type: Iterable[str]
batch_size=None, # type: Optional[Union[Iterable[TBatchSize], TBatchSize]]
batch_num=None, # type: Optional[Union[Iterable[int], int]]
executor=None # type: Optional[Unio... | 40a60afeba55a19e82b840e4a0bc58a6b33a9e1f | 42,078 |
from typing import Dict
def calculate_frequency(lst: list) -> Dict[str, int]:
"""Calculate the frequency from a list."""
frequencies = {}
for item in lst:
if item in frequencies:
frequencies[item] += 1
else:
frequencies[item] = 1
return frequencies | b38deeddca3d57a9e4545a51feec0c245adce9b8 | 42,079 |
def return_on_equity(stock, date=None, lookback_period: timedelta = timedelta(days=0), period: str = 'FY'):
"""
The return on equity ratio measures how efficiently a company is using its equity to generate profit
:param stock: ticker(s) in question. Can be a string (i.e. 'AAPL') or a list of strings (i.e. ... | 026f8f7f62a85a38df75816161b30862d6fa67c4 | 42,080 |
def test_dataset_registry_registered_new_dataset() -> None:
"""
test, that the new generated dataset component "TestDataset" can be registered and retrieved from registry
"""
@dataset_registry.register("testdata")
class TestDataset(DatasetBase):
"""
TestDataset
"""
... | 04f3c49807e3210b9d459fd70b89c51959fb6ae5 | 42,082 |
from typing import Dict
from typing import Union
def adjust_match_start_offset(text: Dict[str, any], match_string: str,
match_offset: int) -> Union[int, None]:
"""Adjust the start offset if it is not at a word boundary.
:param text: the text object that contains the candidate ma... | 0ac326410d9a69be5613fea7acb176fcc8b94982 | 42,083 |
def val2str(val):
"""
Converts a float to the string format required for loading the CRRL models.
:param val: Value to convert to a string.
:type val: float
:returns: The value of val represented as a string in IDL double format.
:rtype: string
:Example:
>>> val2str(200)
... | 61121bc352fc286bda6eed61dc151d8f73143715 | 42,084 |
import dateutil
def get_sale_date(link):
"""Return the date of the livestock sale."""
sale_date = dateutil.parser.parse(link, fuzzy=True)
return sale_date | dfad936713a58ce46890380792e372fe911afc18 | 42,085 |
def count_tiles_amount(product_id, product_version, core):
"""
This method counting actual amount transferred and exists on storage
:param product_id: str -> resource id of the layer to sync
:param product_version: version of discrete
:param core: "A" [send] | "B" [received]
:return: int -> tota... | 21d13935335220ad67135a1c91aba6310b5acef5 | 42,087 |
import numpy
def getelts(nda, indices):
"""From the given nda(ndarray, list, or tuple), returns the list located at the given indices"""
ret = [];
for i in indices:
ret.extend([nda[i]]);
return numpy.array(ret); | 91383b0b40d33f3c197bcb5b9d20900ae963cc47 | 42,088 |
def get_template_attribute(template_name, attribute):
"""Loads a macro (or variable) a template exports. This can be used to
invoke a macro from within Python code. If you for example have a
template named `_cider.html` with the following contents:
.. sourcecode:: html+jinja
{% macro hello(na... | 3af1f85cd2b7465ff6dda167b1737d1450360bea | 42,089 |
def _RoundTowardZero(value, divider):
"""Truncates the remainder part after division."""
# For some languanges, the sign of the remainder is implementation
# dependent if any of the operands is negative. Here we enforce
# "rounded toward zero" semantics. For example, for (-5) / 2 an
# implementation may give ... | 2c9d70c30d135684b3016584ab9c61aad32b3f7d | 42,090 |
from typing import Optional
def check_args(method, args) -> Optional[BoundArguments]:
"""Checks if arguments are suitable for given method.
Returns BoundArguments, or None on failure.
"""
try:
bound_args = signature(method).bind(*args)
bound_args.apply_defaults()
for name, par... | 01d860d240de60c0e0d962647d9063abaf54d773 | 42,091 |
import torch
def prepare(img, label=False):
"""
:param img: img(3d) or lab(2d), np
:param label: whether label
:return:
"""
if not label:
img = norm(img.copy())
img = torch.FloatTensor(img).cuda().float()
img = img.transpose(1,2).transpose(0,1)
return img.unsqueeze(0)
else:
lab = im... | ba61e075ca5904e170a59f34d199cd0c3a60b5ac | 42,092 |
def rebin(bins):
"""
Take in an array of bin edges and convert them to bin centers.
"""
bins = np.array(bins)
result = np.zeros(bins.size - 1)
for i, element in enumerate(result):
result[i] = (bins[i] + bins[i + 1]) / 2.
return result | f3a28fafdaa1a3d54515091e4455b28ee60a3b43 | 42,093 |
from typing import List
def __load_exported_activities() -> List[DiscoveredActivities]:
"""
Extract metadata from actions and probes exposed by this extension.
"""
activities = []
activities.extend(discover_actions("chaosazure.machine.actions"))
activities.extend(discover_probes("chaosazure.ma... | 84dc18e43bb76d34e45b6e0938aefe6234ded081 | 42,094 |
def shuffling_MI(symbol_counts, number_of_bins_d):
"""
Estimate the mutual information between current and past activity
in a spike train using the shuffling estimator.
To obtain the shuffling estimate, compute the plug-in estimate and
a correction term to reduce its bias.
For the plug-in esti... | c656a8b84845816a052c897b74ab868ba9f4f43d | 42,095 |
def determine_component_investment_cost(component, eM):
"""ex post determination method of roi"""
return value(investment_cost(component, eM)) | b2a000ee1b9f9ad0f509f3c8da4334edc3b398ad | 42,096 |
def income_quintile(households):
"""
Household income quintile at the MSA level.
"""
return pd.Series(
pd.qcut(
households['income'], 5, [1, 2, 3, 4, 5]),
index=households.index
) | 593ce1d4f65f67358ffae0dd2d28eab06f35c1bd | 42,098 |
from pyhomee.const import ATTRIBUTE_TYPES_LOOKUP
def get_attr_type(attr):
"""get attribute name by its type"""
return ATTRIBUTE_TYPES_LOOKUP.get(attr.type, ATTRIBUTE_TYPES_LOOKUP[0]) | b00e00af269b523d3340d3d6661f2b1725ebf28e | 42,099 |
def get_step_name(monitoring_info_proto):
"""Returns a step name for the given monitoring info or None if step name
cannot be specified."""
# Right now only metrics that have a PTRANSFORM are taken into account
return monitoring_info_proto.labels.get(PTRANSFORM_LABEL) | e211465455d2f173ba00b17bd8603d6de7468679 | 42,100 |
def field_isomorphism(a, b, *, fast=True):
"""Construct an isomorphism between two number fields. """
a, b = sympify(a), sympify(b)
if not a.is_AlgebraicNumber:
a = AlgebraicNumber(a)
if not b.is_AlgebraicNumber:
b = AlgebraicNumber(b)
if a == b:
return a.coeffs()
n =... | 2c5cd6b635883caa9d344542e03c139da8ae4685 | 42,101 |
def first_dup(s):
"""
Find the first character that repeats
in a String and return that character.
:param s:
:return:
"""
for char in s:
if s.count(char) > 1:
return char
return None | 300d9c60123bbceff8efde84be43c26f527f2fc0 | 42,102 |
def SegRename(ea, name):
"""
Change name of the segment
@param ea: any address in the segment
@param name: new name of the segment
@return: success (boolean)
"""
seg = idaapi.getseg(ea)
if not seg:
return False
return idaapi.set_segm_name(seg, name) | 95d2ed2d15b5329be881e4bcec2afff80af4bf06 | 42,103 |
def clean_df(df):
"""what it does: cleans the consolidated dataframe
arguments: takes a dataframe as argument
returns: the cleaned dataframe"""
df['published_date'] = pd.to_datetime(df['published_date'], errors='coerce')
# Convert list of authors to one single str of authors
authors... | f34362353cbb817ee605f9dd3c0796ddf2920ef4 | 42,104 |
def type_check(tags):
"""Perform a type check on a list of tags"""
if type(tags) in (list, tuple):
single = False
elif tags == None:
tags = []
single = False
else:
tags = [tags]
single = True
if len([t for t in tags if type(t) not in (str,bytes)]) == 0:
valid = Tr... | 519fb2bcf0b8c8792465cc2e057e3dea8f611841 | 42,105 |
from typing import Union
def open_pdf(file_name: str,
parent: QWidget) -> (Union[Doc, None], bool):
"""
open pdf file and return a fitz object if applied
:param file_name: pdf file name
:param parent: parent
:return (doc, bool)
"""
try:
doc = Doc(file_name)
except... | c28f8bc29f5986fe90010cd252ca8505eecd40a6 | 42,106 |
async def upload_complete(
request: Request,
uuid: str,
user: domain.User = Depends(dep.get_current_user),
config: Config = Depends(dep.config),
response_class=HTMLResponse,
):
"""Page that advises user to wait after upload."""
details = infra.parse.details_from_params(
... | 08a6decbf0175cd06e279a3ed2b3234c49e8c3f4 | 42,107 |
def load_Ttree(tree):
"""load TTree as dict"""
ret = {}
for i in tree.keys():
arr = tree.get(i).array()
if isinstance(arr, np.ndarray):
ret[i.decode()] = arr
return ret | d14a6446d6d469f33036b08c80d794427ff37855 | 42,108 |
def traducir_resultados(i: dict) -> None:
"""
Traducir resultados // Translate results
#### Parametros:
* @param i: Diccionario con el resultado // Dictionary with the results
#### Returns:
* return _bTranslated: True: si fue traducido, False: si no // True: if it was translated, False: if not
"""
_bTransl... | 5d26235978fd19002ee6b9f20925cc47ae103584 | 42,109 |
def get_type_for_model(model):
"""
Return type name for a given model class.
"""
opts = model._meta.concrete_model._meta
return camelcase_to_underscore(opts.object_name) | bc16a5fe4e4b8b285814017f00b9d3e016740a97 | 42,110 |
def trace_plot_all_clusters(processed_neurons, clus_df, time_arr, label_col, ix_col, color_palette = None,
max_ix= None, clus_num_list = None, **kwargs):
"""
Wrapper function to make a list of bokeh figures containing the distribution of traces
for visualization of clustering results.
Params
-------
proce... | f04adb46e482ae334bd54c3f66bc21338bede416 | 42,111 |
def get_OUT_port(port: str) -> int:
""" Get number of OUT port, or None if 'port' is not a valid value. """
return get_port_nr(port, "OUT") | 2c657143b6384341314e25d94fa3189814dd5e68 | 42,113 |
def input_position():
"""
input the position option for pasted QR code
"""
option = input('Please select the position (1:left-top, 2:right-top, 3:left-bottom, 4:right-bottom, 5:left-middle, 6:right-middle) for QR code: ')
if option == '':
pos = 1
print(' Use the default position, ... | 80e2b69d04991781515790c4fd0fbb6719d3e6d4 | 42,114 |
from datetime import datetime
def tow_to_datetime(tow, week):
"""
Convert a GPS Week and Time Of Week to Python datetime object.
Does *not* convert from GPST to UTC.
Fractional seconds are supported.
Parameters
----------
tow : time of week in seconds
weeks : gps week
Returns
... | e22a3d90184edc7ded540de89a12ffe262fa3080 | 42,115 |
def Helheim_map(service='ESRI_Imagery_World_2D', epsg=3413, xpixels=2000):
"""Function using Basemap to plot map for only Helheim Glacier
"""
m = Basemap(projection='npstere', boundinglat=70, lon_0=315, epsg=epsg, llcrnrlon=320.3, llcrnrlat=66.1, urcrnrlon=322.4, urcrnrlat=67.6, resolution='h')
plt... | 07e0291e158e7e8acbd2f43f0bbb91d65f26f3a8 | 42,118 |
def return_countries():
"""
Get the countries available
:return: country JSON
"""
with open("country.json", "r") as country:
return country.read() | b927b6b4b6797a76fd047ed88c2809b66df206b9 | 42,119 |
def outer_product(a: Vector, b: Vector) -> Matrix2d:
"""
Given vectors a = (a1, a2, ..., an),
b = (b1, b2, ..., bm)
Returns a matrix of shape NxM
A = [ a1b1, a1b2, ..., a1bm,
.
.
.
anb1,... | 386c48e59967651b03ae10f706c37382adba14b5 | 42,120 |
def epsilon_greedy_policy(Qs, nA, i_episode, epsilon=None):
"""epsilon greedy policy
env: Gym environment
s: state
i_episode: index of current episode -> epsilon should reduce when i increase
eps: customized epsilon
"""
epsilon = 1 / i_episode if epsilon is None else epsilon
... | 22ff8762da5df54ac2ebd60e471abfa7397b8af0 | 42,121 |
from datetime import datetime
def BJtime(mergeTime):
"""
utc时间转换北京时间
"""
mergeTime = mergeTime.replace('T', ' ').replace('Z', '')
mergeTime = datetime.datetime.strptime(mergeTime, '%Y-%m-%d %H:%M:%S')
mergeTime = mergeTime + datetime.timedelta(hours=8)
mergeTime = datetime.datetime.strftim... | d0929ec8988a41148b2e5bdc63c13ad6f6434a64 | 42,122 |
def make_simple_templating_function(template):
"""Factory for making a templating function that applies the context object to the given template to create a
string.
Arguments:
template -- Templated string, whose values will be filled at run-time from the passed context.
For example, the... | e562c9d217ca892467b60c30f4806987eeffa4d4 | 42,123 |
def flatten_to_single_ndarray(input_):
"""Returns a single np.ndarray given a list/tuple of np.ndarrays.
Args:
input_ (Union[List[np.ndarray],np.ndarray]): The list of ndarrays or
a single ndarray.
Returns:
np.ndarray: The result after concatenating all single arrays in input_.... | 37f0aa6272b421481bef044f87a8bfe2ab1bb134 | 42,124 |
def get_pbs_node_requirements(sys_settings,node_count):
"""Get the cpu and memory requirements for a given number of nodes
Args:
sys_settings (dict): System settings dict, as supplied from config_manager
node_count (int): Number of whole nodes on target system
Returns:
dict... | f4fd12dee6608a87e6c8b0f2f56e245e6be7c0fc | 42,125 |
from unittest.mock import Mock
def api_fixture():
"""Define a fixture for simplisafe-python API object."""
api = Mock()
api.refresh_token = "token123"
api.user_id = "12345"
return api | 2270391b02dd02de71a312ed6d6edd780c5bdff2 | 42,126 |
def checkArray(comment,check,expected,tol=1e-7):
"""
This method is aimed to compare two arrays of floats given a certain tolerance
@ In, comment, string, a comment printed out if it fails
@ In, check, list, the value to compare
@ In, expected, list, the expected value
@ In, tol, float, optional, ... | 99b79234df19d3fb69a245f6e52e7d24967e599f | 42,127 |
import numpy
def classificationModel(model,dataFrame,predictors,outcome,nFolds:int):
"""
Method for computing accuray and cross-validation based upon given model
"""
if dataFrame is None:
return None
model.fit(dataFrame[predictors],dataFrame[outcome])
predictions=model.predict(dataFram... | 30c3bdeef0c499d535313917938eeefc9297a6f9 | 42,129 |
def simu_abstract_div_stutter(ts):
"""Compute the coarsest divergent stutter bisimulation abstraction for a Finite Transition System.
@param ts: input finite transition system, the one you want to get
its abstraction.
@type ts: L{FTS}
@return: the abstraction, and the corresponding... | 03e38bcebc3058fd794cd84563947803431e683b | 42,130 |
def runtime_error(exception):
"""Handle a runtime error, e.g., an unresponsive server.
:param exception: Exception caught.
:return: constants.EXIT_CODE_ERR
"""
parser.print_error(msg=exception)
return constants.EXIT_CODE_ERR | 96abf6998e2619356410ec32d4d24b3a523c6471 | 42,131 |
def donchian(candles: np.ndarray, period=20, sequential=False) -> DonchianChannel:
"""
Donchian Channels
:param candles: np.ndarray
:param period: int - default: 20
:param sequential: bool - default=False
:return: float | np.ndarray
"""
if not sequential and len(candles) > 240:
... | dc2d345e93fa892d0b963ef907811f6c309d8b47 | 42,132 |
def genball(npt, ndim, rstate=None):
""" Simulate points in ndim ball """
# use Barthe2005
x = rstate.standard_normal(size=(npt, ndim))
y = rstate.exponential(0.5, size=npt)
x1 = x / np.sqrt((y + (x**2).sum(axis=1)))[:, None]
return x1 | c73fba269e7c7a06af0a6ed9555166cfaf5cd17b | 42,133 |
def autoenc_quantize(x, nbits, nmaps, do_training, layers=1):
"""Autoencoder into nbits vectors of bits, using noise and sigmoids."""
enc_x = tf.reshape(x, [-1, nmaps])
for i in xrange(layers - 1):
enc_x = tf.layers.dense(enc_x, nmaps, name="autoenc_%d" % i)
enc_x = tf.layers.dense(enc_x, nbits,... | eab1e7df449246c22577ab72bab3696a1e6c0d49 | 42,134 |
def ndcg_at_k(
rating_true,
rating_pred,
col_user=DEFAULT_USER_COL,
col_item=DEFAULT_ITEM_COL,
col_rating=DEFAULT_RATING_COL,
col_prediction=PREDICTION_COL,
relevancy_method="top_k",
k=DEFAULT_K,
threshold=DEFAULT_THRESHOLD,
):
"""Normalized Discounted Cumulative Gain (nDCG).
... | b4529260aa2be6619735497daaca5a733ea09e20 | 42,136 |
def select_table_value_from_page(**params):
"""从画面上选择出一个列表的数据"""
return """\
with open('../script_lib/parse_table_value.js', encoding='utf-8') as file:
script = file.read()
header = driver.execute_script(script, '{header_selector}')[0]
result = driver.execute_script(script, '{data_selector}')
... | d9e5087b50188b6c4e4125bfa396ae2e9b02a6db | 42,137 |
def create_canvas(height, width):
"""Creates blank canvas given height and width. Returns Canvas object."""
new_canvas = Canvas(height, width)
return new_canvas | 759d9194d1391e8852729593f4a8dcbad3ee390f | 42,138 |
def families_lens():
"""."""
return ['Lens', 'LensRev'] | dd1c39ca606f100fc3efbf22be2a402507d262de | 42,139 |
async def jobs_list(
db=Depends(get_db),
):
"""
Get all jobs
"""
try:
return get_jobs(db)
except Exception as e:
return JSONResponse(status_code=status.HTTP_400_BAD_REQUEST, content=f'{str(e)}') | 0ace5eed845161f43da78c54986934d094a148c3 | 42,140 |
def load_training_data(direc: str = 'data/training/training_articles.csv', size: int = 50):
"""
opens text file with sample articles to train and tokenizes
"""
with open(direc) as f:
return [prepare_text_for_lda(line) for line in f] | 33fb765dc6aa1a022b2faba236c891c53139c50c | 42,141 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.