content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def autoCall(f, *args, stack:list=None, commands:list=None):
""" Utility function to invoke dynnamic functions """
result = f(*args)
return result if result else args[0] | 8bc2357ddb4b567a72e2046b9b40f6f90fa5dd27 | 3,605,114 |
def xw_plus_b(x, w, bias=None, transW=True, out=None):
"""Compute *matmul(x, w) + bias.*``
Parameters
----------
x : dragon.vm.torch.Tensor
The x.
w : dragon.vm.torch.Tensor
The w.
bias : dragon.vm.torch.Tensor, optional
The bias.
transW : boolean
Whether to ... | 4f41bb3095e593ff346944ac779cbfbd58a1b9a3 | 3,605,115 |
def _bytes_feature(value):
"""
Returns a bytes_list from a string / byte.
"""
return tf.train.Feature(
bytes_list=tf.train.BytesList(value=[value])
) | a3b9ddc82c52fc5b8afac18618701283b75f19d6 | 3,605,116 |
def anum(self, num="", type_="", xhot="", yhot="", **kwargs):
"""Specifies the annotation number, type, and hot spot (GUI).
APDL Command: /ANUM
Parameters
----------
num
Annotation number. ANSYS automatically assigns the lowest
available number. You cannot assign a higher number ... | be3acd32deffcd31a3a83758b64d0d6950bbd791 | 3,605,117 |
def ADMM(A, y):
"""Alternating Direction Method of Multipliers
This is a python implementation of the Alternating Direction
Method of Multipliers - a method of constrained optimisation
that is used widely in statistics (http://stanford.edu/~boyd/admm.html).
This is simplified version, specifically... | 39bc4ae16d286a97bc1b9c5f7f94412db74ef2ad | 3,605,119 |
def main():
"""Manages the application root"""
return ('', 404) | cf1d676fc24d1db79c567d6d37d7d6660aaca977 | 3,605,120 |
def parse_params_arg(params_arg):
""" Parse Params Arg """
params = dict()
args = params_arg.split(',')
for arg in args:
keyvalue = arg.split('=')
params[keyvalue[0]] = keyvalue[1]
return params | 2e5673b2bbe552cb751b1250161745d7913df1be | 3,605,121 |
def nfft(ht, sampling_frequency):
"""
performs an FFT while keeping track of the frequency bins
assumes input time series is real (positive frequencies only)
ht = time series
sampling_frequency = sampling frequency
returns
hf = single-sided FFT of ft normalised to units of strain / sqrt(Hz... | e165e3845b9d51ecc283619e300b706c0997f940 | 3,605,122 |
def get_coords(doctype, filters, type):
"""Get a geojson dict representing a doctype."""
filters_sql = get_coords_conditions(doctype, filters)[4:]
coords = None
if type == "location_field":
coords = return_location(doctype, filters_sql)
elif type == "coordinates":
coords = return_coordinates(doctype, filters_... | ae926180a5d86a7e334378607369c4623b189230 | 3,605,123 |
def sign_adaptation(control: 'FloatNest',
output: 'FloatTensor',
set_point: 'FloatTensor',
adaptation_rate: 'FloatTensor' = 0.01) -> 'FloatNest':
"""A function to do simple sign-based control of a variable.
```
control = control * (1. + adaptation_rate)... | 168dc8024e30fe4c5f36da80872bfbe385336708 | 3,605,124 |
def _grouprule_compute(columns, conditions, having, df):
"""
Computes the metric result.
:param columns:
:type columns: list
:param conditions:
:type conditions: list
:param having:
:type having: list
:param df:
:type df: DataFrame
:return: Result of the metric.
:rtype: f... | 11403688664a786d8557b5cb834ee96d78b87005 | 3,605,126 |
def make_master_assignment_table(list_of_assignment_paths, min_probability=0.0, full=False):
"""Create a master assignment table from a list of assignment paths
:param list_of_assignment_paths: list of all paths to assignment.tsv files to concat
:param min_probability: minimum probabilty to keep
:retur... | e359e59679acfc246606820a4400f2f036165a80 | 3,605,127 |
def _convert_to_parser_rule(rule, terminals_to_ids, nonterminals_to_ids,
rule_idx):
"""Convert Rule to CFGRule."""
rhs = []
for token in rule.rhs.split(" "):
if token.startswith(NON_TERMINAL_PREFIX):
symbol_idx = nonterminals_to_ids[token[len(NON_TERMINAL_PREFIX):]]
rhs... | a11a80a2807d354f0e06fd992b636d51bc40d3c1 | 3,605,129 |
def login_authentication(request):
"""RBAC login API
:param request:
:return:
"""
feedback = {
'permission': True
}
data = request.data
username = data.get('username', None)
password = data.get('password', None)
try:
if username is None:
feedback['... | 1888a717dd0550a8abbe63807264f7d71db49092 | 3,605,130 |
def map_ensembl_ids(ensembl_ids):
"""Return references based on a list of Ensembl IDs."""
refs = []
for ensembl_id in ensembl_ids:
ref = {'HGNC_SYMBOL': None, 'HGNC': None, 'UP': None,
'ENSEMBL': ensembl_id}
ensembl_id = ensembl_id.split('.', maxsplit=1)[0]
hgnc_id = h... | 71e1304f14d4647ddea732636831f9c04ac965ff | 3,605,131 |
def nthUglyNumber(n: int) -> int:
"""
书中的解法
"""
q = [1]
t2, t3, t5 = 0, 0, 0
for i in range(n-1):
a2, a3, a5 = q[t2]*2, q[t3]*3, q[t5]*5
to_add = min(a2, a3, a5)
q.append(to_add)
if a2 == to_add:
t2 += 1
if a3 == to_add:
t3 += 1
... | a24806c1ff94ec1291c19bb1f1a8596e20c809b6 | 3,605,132 |
def livb_annotation():
"""Returns an annotation with species entities (LIVB) identified.
"""
annotation = {"ents": [{"text": "mouse", "label": "LIVB", "start": 0, "end": 0},
{"text": "human", "label": "LIVB", "start": 0, "end": 0}],
"text": "mouse and human",
... | 78de25feab620347e08c8bc74ecf467db3bb477a | 3,605,133 |
def check_authors_from_papers(papers,authors,silent=False,mute=False):
""" Check the given papers against a list of authors.
The authors can either be in a text file or in a list.
Returns a list of papers that contain the authors in either their
title, abstract, or author list."""
return check_keywo... | a35c4def80e36713120174f84f892c2f57ee6e4c | 3,605,134 |
def sentence_to_token_ids(sentence, vocabulary,
tokenizer=None, normalize_digits=True, normalize_name=False):
"""Convert a string to list of integers representing token-ids.
For example, a sentence "I have a dog" may become tokenized into
["I", "have", "a", "dog"] and with vocabulary {"... | 0b77631be2a4f566e619bb646c58930b0700934c | 3,605,135 |
def generate_networks(network_graph, root_ids):
"""
Parameters
----------
network_graph : DirectedGraph
graph facing upstream
root_ids : pandas.Series
Series of root IDs (downstream-most ID) for each network to be created
"""
segments = pd.Series(
network_graph.desce... | cc080248da938269aa76f64b0baef8982bb9bf4e | 3,605,136 |
def discretizer(df_list, names, method_list):
"""
Parameters
----------
df_list: pd.DataFrame type, the dataframe need to split.
names: list of column names
method_list: a dictionary contains the methods as key, and parameters as values.
key must in ['isometric','quantile','kmeans']
Like... | d84c720e6578a17a756cd4b121e05b5a953f36dd | 3,605,137 |
def stft(sig, frameSize, overlapFac=0.75, window=np.hanning):
""" short time fourier transform of audio signal """
win = window(frameSize)
hopSize = int(frameSize - np.floor(overlapFac * frameSize))
samples = np.array(sig, dtype='float64')
# cols for windowing
cols = int(np.ceil((len(samples) - ... | 9ddeff11913f64d303be916208e5e90e4ff0ae2c | 3,605,138 |
def ontology_term_parser(cell_value: str = None):
"""
Parse a line string and convert it into a dictionary {key -> value}
:param cell_value: String line
:return:
"""
term = {}
values = cell_value.split(";")
if len(values) == 1 and '=' not in values[0]:
term[TERM_NAME] = values[0]... | 222ebc183f61ef415aa2afc1b24c9f1bcbd64571 | 3,605,139 |
def fringe_to_nm(idx):
"""Convert Fringe Z to (n, m) two-term index."""
m_n = 2 * (np.ceil(np.sqrt(idx)) - 1) # sum of n+m
g_s = (m_n / 2)**2 + 1 # start of each group of equal n+m given as idx index
n = m_n / 2 + np.floor((idx - g_s) / 2)
m = (m_n - n) * (1 - np.mod(idx-g_s, 2) * 2)
return in... | c3ca0206463491455b22c84d91337fb72bc49017 | 3,605,140 |
def catalyze_one_step_reversible(enzyme, substrate, product, klist):
"""
Create fwd and reverse rules for catalysis of the form::
E + S -> E + P
P -> S
Parameters
----------
enzyme, substrate, product : Monomer or MonomerPattern
E, S and P in the above reactions.
kli... | 43988e67933f716a3eb6d59022f9314db777f5ba | 3,605,141 |
import typing
def build_async_client(resource: LegionCloudResourceUpdatePair,
async_edi_client: AsyncRemoteEdiClient
) -> typing.Optional[object]:
"""
Build client for particular resource (e.g. it builds ModelTrainingClient for ModelTraining resource)
:param ... | 86cc3f235a220ad69b0a1c32df3db4433c085432 | 3,605,143 |
import math
def get_horizon(sub_height):
"""Get horizon distance."""
return math.sqrt(2 * EARTH_RADIUS_KM * 1000 * sub_height + sub_height ** 2) | fc0b034b27679952f2e87511662db306d054da6c | 3,605,144 |
def distance(p1, p2):
"""
Returns distance between the two points
"""
return mag(p1 - p2) | bf9ac1c19e361985749774b84a00ea93bc0a1b0a | 3,605,145 |
import collections
def _get_type_info(initialize_tree, before_broadcast, after_broadcast,
before_aggregate, after_aggregate):
"""Returns type information for an `tff.utils.IterativeProcess`.
This function is intended to be used by
`get_canonical_form_for_iterative_process` to create the expe... | 633843bd16afd74d5f3686dcafa6862d411999c9 | 3,605,146 |
import math
from re import M
def path3(x, y, phi):
"""
Formula 8.3: C|C|C
"""
r, theta = R(x, y)
phi = deg2rad(phi)
path = []
xi = x - math.sin(phi)
eta = y - 1 + math.cos(phi)
rho, theta = R(xi, eta)
if rho <= 4:
A = math.acos(rho / 4)
t = M(theta + math.pi/2... | 4aad4248cf478997b045aa4e2a2ce70d725f2a8f | 3,605,147 |
def compose():
""" Compose a pop song
This is currently a mock-up code.
"""
chords = [Chord("C"), Chord("F"), Chord("G"), Chord("C")]
chord_track = ChordTrack()
for i, chord in enumerate(chords):
event = ChordEvent(time_=Time(measure=i + 1), duration=Time(measure=1), chord=chord)
... | 62ff2bf66ace950c97d94a78c2f1b217d6c73806 | 3,605,148 |
import json
def featureset_table(meth, obj_id=None):
"""This method displays a FeatureSet gene list
along with functional annotation in a table.
:param obj_id: FeatureSet workspace object identifier.
:type obj_id: kbtypes.KBaseSearch.FeatureSet
:return: Rows for display
:rtype: kbtypes.Unicod... | afe34859ecb4c503cd0a12dafc56ec70d2c1e8b5 | 3,605,150 |
def _to_int(parsed):
"""
Transforms the received parsed value into an integer.
:param parsed: the parsed value
:return: an integer created from the value
"""
if len(parsed) > 0:
return int(parsed[0])
else:
return None | 1701648c7e42232c8be0c7451d19ffe43f322118 | 3,605,151 |
import requests
from bs4 import BeautifulSoup
import json
def get_current_cryptocurrency_price(num_pages=5, currency="EUR") -> pd.DataFrame:
"""
Scrape current price of cryptocurrencies from https://www.coinmarketcap.com/ and convert it to Euro.
:param num_pages: Each page holds 100 cryptos with highest c... | 3d0e99519a633688df173890ffe20b7b1a756031 | 3,605,153 |
def _single_iteration_random_selection(
nb_attributes, nb_targets, fraction_missing, potential_targets
):
""" Select random combination of descriptive + target parameters for the model
Args:
nb_attributes: total number of attributes
nb_targets: number of targets
fraction_missing... | c93ee571363b2dcd3f073633672546fabc62a28a | 3,605,154 |
def ExtractSubpopulations(gList, gListClosure):
"""
Method to extract subpopulation information from results of
recursive graph segmentation
:param gList:
:param gListClosure:
:return:
"""
# Rebuild gList from all the partitions
# gList, gListClosure, iterBinPartList, iter... | 520735b97f994606e0eeb04136d2443fa82fc6c2 | 3,605,155 |
import pytz
def to_param(m):
""" Converts testkit parameter format to driver (python) parameter
"""
data = m["data"]
name = m["name"]
if name == "CypherNull":
if data["value"] is not None:
raise ValueError("CypherNull should be None")
return None
if name == "CypherS... | 7f342f4c2e32607a83bbd11c25f9de17968854f1 | 3,605,156 |
def SaveToErrLog(*args):
"""
SaveToErrLog(char const * MsgCStr)
Parameters:
MsgCStr: char const *
"""
return _snap.SaveToErrLog(*args) | a4eb3cae22750a0f1ac57e48306e47fd5a0c6389 | 3,605,158 |
def get_listener_options(listener_name):
"""
Returns the options for a specified listenername from the database outside
of the normal menu execution.
"""
try:
listener_options = (
Session()
.query(models.Listener.options)
.filter(models.Listener.name == li... | 514578b7a555253f69bc892be60bdd183b95b186 | 3,605,159 |
from typing import List
def waypoints() -> List[Waypoint]:
"""Get a list of example Waypoints."""
return [
Waypoint(Point(1, 2, 3), CriticalPoint.XY_CENTER),
Waypoint(Point(4, 5, 6))
] | 739da2c33d310d20de510209560ed7cdf884ef14 | 3,605,160 |
def get_model_string(model):
"""
:param model: model
:returns: <app_label>.<model_name> string representation for the model
"""
return "{app_label}.{model_name}".format(app_label=model._meta.app_label, model_name=model._meta.model_name) | d54323680c4a15cc99bbbcea09cf319c571ff9cf | 3,605,161 |
def app_base_handlers(request, app, async_db):
"""
Fixture modifies application handlers adding base API handlers and creates table for test models
"""
app.add_handlers(".*$", [(r'^/test/api_test_model/?$', ApiListTestHandler)])
app.add_handlers(".*$", [(r'^/test/api_test_model/([^/]+)/?$', ApiItemT... | 5d81046a4df673895a15db2544533ee928f2076a | 3,605,162 |
def make_discord_object(id: int, **kwargs):
"""Make :class:`discord.Object` instance with given attributes."""
obj = discord.Object(id)
for k, v in kwargs.items():
setattr(obj, k, v)
return obj | 6340d2b4073bac311bab69e622deb46e8e2318b6 | 3,605,163 |
import torch
def get_sift_pooling_kernel(ksize=25):
"""
Returns a weighted pooling kernel for SIFT descriptor
"""
ks_2 = float(ksize) / 2.0
xc2 = ks_2 - (torch.arange(ksize).float() + 0.5 - ks_2).abs()
kernel = torch.ger(xc2, xc2) / (ks_2**2)
return kernel | 4576e97eaab4eba86c9a68edd67c00a2ede0db3f | 3,605,164 |
def default_trees():
"""
Provides a default tree to be used in testing the
putil.tree.TreeNode() class
"""
#
# Tree1 Tree2 Tree3 Tree4
# t1l1 (*) t2l1 (*) t3l1 (*) root
# ├t1l2b1 (*) ├t2l2b1 (*) ├branch1 (*)
# │├t1l... | 31bba9e6da83545d5c8768aef607e0095aaf3f82 | 3,605,165 |
from core import FS
def template():
""" RESTful CRUD controller """
s3.filter = FS("master") == "event_sitrep"
s3db.dc_template.master.default = "event_sitrep"
return crud_controller("dc", "template", rheader=s3db.dc_rheader) | e4bf62e756d4ae921b015ed435fc797a33555837 | 3,605,166 |
def check_overscan(xstart, xsize, total_prescan_pixels=24,
total_science_pixels=4096):
"""Check image for bias columns.
Parameters
----------
xstart : int
Starting column of the readout in detector coordinates.
xsize : int
Number of columns in the readout.
t... | 934d7683a710e9fe88d488398a9ad9e769470460 | 3,605,167 |
async def create(params: SwagTierCreate, db: AsyncSession = Depends(with_db)):
"""
Create a new swag tier
"""
tier = SwagTier.from_orm(params)
try:
db.add(tier)
await db.commit()
except IntegrityError:
raise HTTPException(
status_code=HTTPStatus.CONFLICT,
... | e88ff83aefe66028f852f4c12dec88ac362f6056 | 3,605,169 |
def hex_to_pixel(row, col, hex_edge_length):
"""Get pixel on surface from position of a hexagon in a grid"""
x = hex_edge_length * 3 / 2 * col
y = hex_edge_length * sqrt(3) * (row + 0.5 * (col & 1))
return x, y | d4513dbda194877bb0c9dc48c89a55f3c9ae2b8c | 3,605,170 |
import time
def pillage() -> Response:
"""Claim all unclaimed networks."""
counter = 0
t = time.time()
for network in manager.session.query(Network):
if network.report is not None:
continue
res = _help_claim_network(network, current_user)
if res:
coun... | 76f4fe577a6c245ce0f699b22ad46233dcc042b8 | 3,605,171 |
def periodic_wrap_corner(dist_arr, length, verbose=False):
"""For a box with lower left vertex at the origin."""
if verbose:
print(dist_arr)
dist_arr = dist_arr - np.around(dist_arr / length) * length
if verbose:
print(dist_arr)
return dist_arr | b65333f4e0046307557bb15388f43b24f8513f18 | 3,605,172 |
import warnings
def get_deconv_dla(base_network, pretrained=False, ctx=cpu(), scale=4.0, use_dcnv2=False, **kwargs):
"""Get resnet with deconv layers.
Parameters
----------
base_network : str
Name of the base feature extraction network.
pretrained : bool
Whether load pretrained ba... | 17118011750e5c21fe416a6f57478653fce05f92 | 3,605,173 |
def is_python(view):
"""Cosmetic sugar."""
return view.score_selector(0, 'source.python') > 0 | 18c6f14db5b24130e0fb04718e3d81ff7749a526 | 3,605,176 |
def _helperfunction(segment, array) -> geo.Shape:
"""Calculate a shape from input.
Input segment of successive segments as strings.
Input array of the points in the correct sequence. e.g.:
array = [[x-values], [y-values]]
Parameters
----------
segment :
list of String, segment name... | 4f2a1a35bad4f80a2065a972504030bd78dc94d0 | 3,605,177 |
def get_t_neighbors(g, x, y):
"""Returns possible members of conditioning set for x---y edge consideration"""
t = set([])
all_y_neighbors = set(nx.all_neighbors(g, y))
for z in all_y_neighbors:
if has_undir_edge(g, z, y):
if adjacent(g, z, x):
continue
t.... | 340077e5a7585a4e679668c0adcac1dd21cfca90 | 3,605,178 |
def _hurst_exp_compute_rs(x):
"""Utility function for :func:`compute_hurst_exp`.
Parameters
----------
x : ndarray, shape (n_seqs, n_times)
Returns
-------
output : ndarray, shape (n_seqs, n_times - 1)
"""
n_seqs, n_times = x.shape
rs = np.zeros((n_seqs, n_times - 1), dtype=x.d... | 93605138383c8279e448f0af0fdbbfc430820c24 | 3,605,179 |
def suggestTransitionSets(mat, e0=20.0):
"""suggestTransitions(mat, e0=20.0)
Suggest a list of XRayTransitionSet objects for the specified material."""
mat = dtsa2.material(mat)
fams = ("Ka", "Kb", "La", "Lb", "Ma", "Mb")
res = []
for elm in mat.getElementSet():
for fam in fams:
... | 50a6ad2eb1a3709b908284d011c4111b41c83733 | 3,605,180 |
def get_double_grgrid_index(address_double, D_diag, PS=None):
"""Return grid point index of a double-grid address
(Generalized-regular-grid version)
Parameters
----------
address_double : array_like
Double-grid address.
shape=(3,), dtype='int_'
D_diag : array_like
Diago... | 53875965ffec52b45f59d535045e8cdf6e231be0 | 3,605,181 |
from typing import Iterable
from typing import Optional
def rows_to_layout(rows: Iterable[list[str]]) -> Layout:
"""
Takes rows (e.g., from a TSV file), and creates a well-formatted layout
file.
"""
layout: Layout = []
max_row_length = len(max(rows, key=len))
for raw_row in rows:
... | b8790995e9c6f8bb908cc0d1daeb0275f5ca2a0b | 3,605,182 |
def is_same_identifier(issuer_a: str, issuer_b: str) -> bool:
"""
check if 2 issuers string have the same identifier
:param issuer_a: issuer string a
:param issuer_b: issuer string b
:return: True if identifier are the same else False
"""
return issuer_a.split(ISSUER_SEPARATOR)[0] == issuer_... | d3aa9a1b62d9fac208c69e86808cba3ebe5f1ca8 | 3,605,183 |
import re
def is_card(content, cards):
"""
Checks whether the current line contents is a data card starting string.
"""
card = None
for icards in cards:
actual_card = icards[0]
card_regex = re.compile(icards[1])
if card_regex.match(content) is not None:
card = ... | 6c07ea6d76a77b87288903584d295e4b26220f9c | 3,605,184 |
from app.global_handlers import global_handlers
from bll.membership import register_membership
from bll.reports import register_dblogger
def setup_app(**config_overrides):
"""
This is normal setup code for a Flask app, but it's possible
to provide override configurations so that in testing, a differen... | 263063dfd80aa048c9900e3c9edc82fba5cb42ed | 3,605,185 |
def setting_check_file_read(setting_name):
"""
Wrapper to check the case of a file we just need to read.
Setting must be a non-blank string. File must exist, be a regular
file or a symlink to one, and be readable.
Dependencies:
config settings: (contents of setting_name)
globals: cf... | 779dfa65eedafb50d83536f9c0b750146e51bc66 | 3,605,186 |
import string
def unregister():
"""Unregister device for GCM
"""
if request.method == 'POST':
regID = request.form['regID']
regID = string.replace(regID, '\'', '\\\'')
regIDModel = db.GqlQuery("SELECT * FROM RegIDModel WHERE regID ='" + regID)
regIDModel.run()
regI... | 98e5e8ee5f40f083ab04b3d33e7775b225105653 | 3,605,187 |
def compose(color1, color2, blend, operator, non_seperable):
"""Blend colors using the specified blend mode."""
# Get the color coordinates
csa = util.no_nan(color1.alpha)
cba = util.no_nan(color2.alpha)
coords1 = util.no_nan(color1.coords())
coords2 = util.no_nan(color2.coords())
# Setup ... | 544e7cf4b848e656665024fd31dc0adf754c75c2 | 3,605,188 |
def gather_memories(memory_dict, gather_coordinates):
""" Gathers layer-wise memory tensors corresponding to top sequences from the provided memory dictionary
during beam search. """
# Initialize dicts
gathered_memories = dict()
# Get coordinate shapes
coords_dims = get_shape_list(gather_coordin... | f8d7ed41344c5f674d1b2568132e0ec4123a4520 | 3,605,189 |
def extract_revision_ordered_review_requests_for_documents_and_replaced(review_request_queryset, names):
"""Extracts all review requests for document names (including replaced ancestors), return them neatly sorted."""
names = set(names)
replaces = extract_complete_replaces_ancestor_mapping_for_docs(names)... | fd7437452e1401c8992da3946844794b1bbbd87f | 3,605,190 |
import logging
def retry_with_instance_list(instance_list):
"""Decorator for running an Integ test with an instance_list and
break on first success
Args:
instance_list (list): List of Compute instances for integ test.
Usage:
@retry_with_instance_list(instance_list=["ml.g3.2", "ml.g2"]... | c0a9e15b5eb60803d68cdf23189dba50587a8141 | 3,605,191 |
def _get_mode(filename):
"""
Returns the mode (from modes) with which the tarball should be read/written as
"""
ext = splitext(filename)[-1]
for key, val in modes.items():
if ext in val:
return key
raise ValueError(f"{ext} is not supported.") | 3f0f2b043bc62dc7a5194e0f82346b0a5a215e07 | 3,605,192 |
import random
def create_build_ids(dtime, count, randomness=True):
"""Returns a range of valid build ids, as integers and based on a datetime.
See Build's docstring, "Build key" section.
"""
# Build ID bits: "0N{43}R{16}V{4}"
# where N is now bits, R is random bits and V is version bits.
build_id = int(_... | 5c7e9dd88243b3eb1d11065fe5705ab1d6a7e0cf | 3,605,193 |
def vec_reverse(a):
"""
Reverses a vector
Parameters
----------
a: list[]
A vector of scalar values
Returns
-------
list[]
The reversed vector
"""
return a[::-1] | b22e13746de1fe8de60d774b1e20f5c5528507ff | 3,605,194 |
import builtins
def ensure_4d(
array: npt.NDArray[miot.DType], *, num_spatial_dims: builtins.int | None = None
) -> npt.NDArray[miot.DType]:
"""for PyTorch"""
num_dimensions = array.ndim
if num_dimensions == 4:
pass
elif num_dimensions == 5: # hope (W, H, D, 1, C)
if array.shape[-... | 6cbd515cdf6e4ee57791af5622f058f7bca046ca | 3,605,195 |
def select_environment(env_name):
""" Selects an environment.
Args:
env_name: Name (string) of the environment on which the experiment is to
be executed. Can be `HalfCheetah`.
Returns:
The class of an environment
Raises:
ValueError: If the string env_name is unknow... | 9378ac7592aecee614a42df9dcd8bd119d06be66 | 3,605,196 |
def t04_ValueDNE(C, pks, crypto, server):
"""Checks that values not stored at the server return None."""
score = 0
alice = C("alice")
score += alice.download("a") is None
score += alice.download("b") is None
score += alice.download("c") is None
alice.upload("d", "e")
score += alice.downl... | af42da60a48d407ad16da6801e847417dbcc69e9 | 3,605,197 |
def _create_ldtconfig_lsm_target(nmme_model, currentdate):
"""Create name of new ldt.config file."""
lc_nmmemodel = nmme_model.lower()
ldtconfig_nameconv_lsm = \
f"ldt.config_{_LSM_NAME}_nmme_{lc_nmmemodel}"
print("[INFO] Processing LDT ensemble restart file for " + \
f"{ldtconfig_name... | 0aebb6675faa8064635893cea9fe660e67d8825e | 3,605,198 |
import collections
def residual_experimental(model_id, sess, is_training, dimx, dimy):
"""Convolutional embedding of stimulus and response.
Args:
model_id : The variant of convolutional model to train.
sess : Tensorflow session.
is_training : Either training or evaluation mode.
dimx: X dimension ... | 69bdaf62fae4d0f5b818568a4af20df0c5e825e7 | 3,605,199 |
def temp(input_temp):
"""
Formats input temperature with "+" or "-" sign
:param input_temp:
:return: formated temperature
"""
decimal = 0
temp2 = float(input_temp)
if temp2 < 0:
temp_sign = ''
elif temp2 > 0:
temp_sign = '+'
else:
temp_sign = ''
de... | 9ce3be3ec362761c2a6aa43e4ae4191c7a471667 | 3,605,200 |
import time
def listarNoticias(api_obj: object, portais: tuple or list, qntd: int) -> list:
"""
Chama a função raspar_noticias() para cada conta em portais
Args:
api_obj: Objeto criado pelo tweepy, necessário para realizar ações na API do twitter.
portais: Lista contendo t... | b6edf7fae2d88de0c5cdf2314c7694421b64b536 | 3,605,202 |
from typing import Union
def INCREASING(x: Union[float, np.ndarray]) -> Union[float, np.ndarray]:
"""
Linearly increasing function over interval [0, 1].
"""
return 2 * x | 99a960ce687d031ef60f3e76f528dd089ca50284 | 3,605,203 |
def deposit_preview(submission_id: int) -> Response:
"""Deposit a preview PDF for a submission."""
stream = request.stream
data, code, head = controllers.deposit_preview(submission_id, get_body())
response: Response = make_response(jsonify(data), code, head)
return response | 634539d9e536c8a0c5f08fadad843a61e988e9c1 | 3,605,204 |
def parse_reads(reads, chromosome_name, fasta_handler):
"""
Given a set of pysam read objects, generate data for matches/mismatches/inserts/deletes and contig size/position for
each read
:param reads: pysam aligned segment objects
:param chromosome_name:
:param fasta_handler: fasta_handler objec... | e70a10ff4e03e13e5938bff2129100b790632a3e | 3,605,205 |
from datetime import datetime
def get_utc():
"""Basic function to get Datetime in Zulu"""
return "%sZ" % (datetime.datetime.utcnow().isoformat("T")) | 600e00f5719ec6b2ac1c131bc1b5c2db8ff2bf0f | 3,605,206 |
def send_ui(path = 'index.html'):
"""Send static content (HTML/CSS/JS/images/...)."""
log_request(request)
return flask.send_from_directory('html', path) | 8a462e49250de143bd2a6e195f3ca7d1f13dc0ac | 3,605,207 |
def extract_html(response):
"""Extracts an html page from the response.
"""
return htmlpage_from_response(response).body | eef1d5cce0e461d0b4f1f4de4e7bfc70459ddb81 | 3,605,208 |
from tayph.vartests import typetest
import time
def end(start,id='',silent=False):
"""
Short-hand for ending a timing measurement and printing the elapsed time.
Parameters
----------
start : float
Generated by time.time()
id : str
Description or numeral to identify the clock ... | b692086cc85ce303adb8aa55bed2919607ef534b | 3,605,210 |
def epsilon_greedy_sample(nested_dist, eps=0.1):
"""Generate greedy sample that maximizes the probability.
Args:
nested_dist (nested Distribution): distribution to sample from
eps (float): a floating value in [0,1], representing the chance of
action sampling instead of taking argmax.... | 913f7bea99e866c2b697f64951317857fa9dfe9e | 3,605,211 |
import logging
def parse(line, app_name, source, dyno):
"""
return: exit: boolean. If true, we can stop this parser thread
"""
# Validate if the line matches the source and dyno
if source not in line or dyno not in line:
return False
root = app_name + settings.SEPERATOR + source + se... | 62a9e663ef41f4e257a89c880893bdfb3250556a | 3,605,212 |
def find_pattern(pattern, text):
"""
Find all the occurrences of the pattern in the text
and return a list of all positions in the text
where the pattern starts in the text.
"""
S = "".join([pattern, "$", text])
s = prefixFunction(S)
result = []
for i in range(len(pattern)+1, len(S))... | 6cb65af8bb1bb49d3db4ab214648982b27311a01 | 3,605,213 |
def exclude(*arg):
"""
excludes all HOSTLIST args from first HOSTLIST
:param: nodelist: The hostlist string.
:param: node: The node to be excluded.
:return: The resulting hostlist string without the nodes specified.
"""
nodelist = arg[0]
len_nodes = arg[1:]
for node in len_nodes:
... | 2fa61fad0f9743c70e6c42a39b7a81f7c60da34e | 3,605,214 |
def generateOldLibraryEntry(data):
"""
Return a list of values used to save entries to the old-style RMG
thermo database based on the thermodynamics object `data`.
"""
if isinstance(data, ThermoData):
return '{0:9g} {1:9g} {2:9g} {3:9g} {4:9g} {5:9g} {6:9g} {7:9g} {8:9g} {9:9g} {10:9g} {11:9... | b6c8d3c4e3c5d3c2d2466ef9b95baf2285b093f5 | 3,605,215 |
def get_cell_values(queries, subjects, key=len, attr=None):
"""Generates the values of cells in the binary matrix.
This function calls some specified key function (def. max) against all
values of a specified attribute (def. None) from Hits inside Subjects which
match each query. By default, this functi... | 4725a4c9f9dc291ff0e8595bb25f51c4612f747d | 3,605,216 |
def form_CheckboxRequired(request):
"""
Simple Boolean Checkbox with a required validator. Add an empty value if you want to force the user to add a tick
"""
schema = schemaish.Structure()
schema.add('checkbox', schemaish.Boolean(validator=validatish.Required()))
form = formish.Form(schema, 'fo... | f5a885826846e9effa4643777a094e73df45d746 | 3,605,217 |
def PointCloudObject(name,**kw):
"""
This function create a polygon representing the atom as point (vertex of the polygon).
@type name: string
@param name: name of the pointCloud
@type kw: dictionary
@param kw: dictionary of arg options, ie :
'vertices' array of coordinates ;
... | afdf1b716d6b57ae0a18c4b3cee81f9d0d47ab0c | 3,605,218 |
import curses
def scrolled_menu(window, datas: list, tag: str):
"""menu
cursesを使って引数のリストを表示してユーザーに選択を促す。
Args:
window: リストを表示/操作するcurses.Windowクラス
datas: 列挙する内容1つづつをdictとして保持したリスト
tag: datasのデータ1つの中で、表示する内容のkey
Returns:
int: ユーザーがリストの何番目を選択したのか値
"""
window.era... | f7ce97dbafdf7736a42a0da1e640788662be27d9 | 3,605,219 |
from typing import Union
import pathlib
import scipy
def read_matlab(input_file: Union[str, pathlib.Path]) -> dict:
"""
Read data from MATLAB file while performing some checks.
**Parameters**
- `input_file`: str or pathlib
Path to the input file.
**Returns**
- `res`: dict
... | 834fb52c4c8c6e93bd8f12d6b59e2dcba0ac525e | 3,605,220 |
import io
def load_poi_points(path: str) -> PoiPoints:
"""Load :py:obj:`PoiPoints` from a file.
Args:
path (str): The path to the file.
Returns:
:py:obj:`PoiPoints`: The data loaded.
"""
data = io._load(path)
return PoiPoints(data) | a1ddae115582d8a9ddad62edb612e4ce2b9f707e | 3,605,221 |
import requests
def get_yield():
"""A function that retrieves current Treasury Bond rates from the US Treasury website.
:return: Dictionary containing all the T-Bond terms as keys (strings) and their rates as values (floats).
"""
# Formatting of XML to Python Dict
curve = requests.get(GOV_YIELD_U... | a1eea5d1e022398cb099575b4b9f179b5c40b72c | 3,605,222 |
def ParseDate(date, messages, fmt='%Y-%m-%d'):
"""Convert to Date Type."""
datetime_obj = times.ParseDateTime(date, fmt=fmt)
return messages.GoogleTypeDate(
year=datetime_obj.year, month=datetime_obj.month, day=datetime_obj.day) | 941b707b6c9fd1e3cc4f114d0d1c4bb6db638840 | 3,605,223 |
def and_(fst, snd):
"""Wraps the logical and function."""
return fst and snd | c03f2cb9178aa2863e2da58e4fe2741f4a98ea79 | 3,605,225 |
def AttenLogitsRPE(query, key, abs_pos_emb):
"""Attention logits from ...
https://arxiv.org/pdf/1803.02155.pdf with trainable rel position emb.
Notice padding is supposed to be masked by the caller of this function.
B: batch size
T: sequence length
N: num of attention heads.
H: per-head attention dimen... | 404b6288fc4df90edcfc45aacababb23671a4427 | 3,605,226 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.