content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def do_tagging(text, config, model):
"""Apply the tagging model.
Args:
text (str): the input paragraph
config (dict): the model configuration
model (PredictionModel): the model in pytorch
Returns:
list of list of str: the tokens in each sentences
list of list of int... | 5,296,300 |
def _extent(x, y):
"""Get data extent for pyplot imshow.
Parameters
----------
x: list
Data array on X-axis.
y: list
Data array on Y-axis.
Returns
-------
[float, float, float, float]
X and Y extent.
"""
dx, dy = .5 * (x[1] - x[0]), .5 * (y[1] - y[0])
... | 5,296,301 |
def run_job(config: Config, job_id: str) -> None:
"""
export tables, apply visibilities, set job status to complete
:param config:
:param job_id:
:return:
"""
job = None
try:
if not is_valid_config(c):
msg = f'Config is invalid, stopping job: {c}'
logger.e... | 5,296,302 |
def OverrideConfigForTrybot(build_config, options):
"""Apply trybot-specific configuration settings.
Args:
build_config: The build configuration dictionary to override.
The dictionary is not modified.
options: The options passed on the commandline.
Returns:
A build configuration dictionary wit... | 5,296,303 |
def get_random_string(length=12,
allowed_chars='abcdefghijklmnopqrstuvwxyz'
'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'):
"""
Returns a securely generated random string.
The default length of 12 with the a-z, A-Z, 0-9 character set returns
a random s... | 5,296,304 |
def fetch_incidents_command(client: Client, params: Dict):
"""
Wrapper function that calls client fetch_incidents function with last run and demisto params.
Updates the new run, and uploads incidents to Demisto.
Args:
client (Client): The client to perform Nutanix API request and fetch incidents... | 5,296,305 |
def load_cfg(cfg_path):
"""Load config file"""
# Remove a (possible) trailing file-extension from the config path
# (importlib doesn't want it)
cfg_path = os.path.splitext(cfg_path)[0]
try:
sys.path.append(os.path.dirname(os.path.realpath(cfg_path)))
cfg = import_module(os.path.basen... | 5,296,306 |
def chunk_average(epochs):
"""
Because the number of trials is hugee, ~ 5000, I don't have the patience to
wait for the process and the cluster does not have the memory to process
such a huge dataset, so I will average every 10 trials to boost the
signal-to-noise ratio and decrease the number of t... | 5,296,307 |
def getField(statefile, fieldname):
""" Get field from MITgcm netCDF output
statefile : string with /path/to/state.0000000000.t001.nc
fieldname : string with the variable name as written on the netCDF file ('Temp', 'S','Eta', etc.)"""
StateOut = Dataset(statefile)
Fld = StateOut.variables[fieldname][:... | 5,296,308 |
def test_normalize():
"""Test the normalize function.
This test creates some random vectors and normalizes them. Afterwards,
the results are checked.
"""
for _ in range(20):
vec = random_non_unit_vector()
unit = tf.normalize(vec)
# check that vector is modified
as... | 5,296,309 |
def get_stations_with_n_docks(num: int, stations: List['Station']) -> List[int]:
"""Return a list containing the station ids for the stations in
stations that have at least num docks available, in the same order
as they appear in stations.
Precondition: num >= 0
>>> get_stations_with_n_docks(2, SA... | 5,296,310 |
def apply_corrections(fluxes, filters, pd_corrections):
"""Apply pd correctionst to the fluxes by fitler."""
return np.array([flux*pd_corrections.get(filt, 1)
for flux, filt in zip(fluxes, filters)]) | 5,296,311 |
def read_sim_file(file_path):
"""Read a sim file.
Parameters
----------
file_path : str
Path of the file.
Returns
-------
str, dict, pandas.DataFrame
The name, the header and the lcs of the simulation.
"""
file_path, file_ext = os.path.splitext(file_path)
if f... | 5,296,312 |
def get_posts_details(rss=None):
"""
Take link of mrss feed as argument
"""
if rss is not None:
# import the library only when url for feed is passed
import feedparser # type: ignore
# parsing partner feed
partner_feed = partner_feed = feedparser.parse(rss)
# getting lists of partner entries vi... | 5,296,313 |
def _is_json(data):
"""
Test, if a data set can be expressed as JSON.
"""
try:
json.dumps(data, cls=BlenderEncoder)
return True
except:
print_console('DEBUG', 'Failed to json.dumps custom properties')
return False | 5,296,314 |
def better_repr(v, version):
"""Work around Python's unorthogonal and unhelpful repr() for primitive float
and complex."""
if isinstance(v, float):
# float values 'nan' and 'inf' are not directly
# representable in Python before Python 3.5. In Python 3.5
# it is accessible via a libr... | 5,296,315 |
def test_twospin_v_Lz(v, Lz):
"""Tests to see what combinations of argument types cause which errors.
Different errors for: both ndarray; one ndarray and one COO; both COO.
See: https://github.com/pydata/sparse/issues/499
"""
H = sparse.tensordot(v, Lz, axes=1)
if not isinstance(H, np.ndarray):... | 5,296,316 |
def XYZ2Shp(filecsv, t_srs="EPSG:4326", fileout=None):
"""
XYZ2Shp
"""
driver = ogr.GetDriverByName('ESRI Shapefile')
fileout = forceext(filecsv, "shp") if not fileout else fileout
remove(fileout)
layername = juststem(fileout)
print layername
dataset = driver.CreateDataSource(fileout... | 5,296,317 |
def __transform_dataframe_to_event_stream_new(dataframe, stream_post_processing=False, compress=False):
"""
Transforms a dataframe to an event stream
Parameters
------------------
dataframe
Pandas dataframe
stream_post_processing
Boolean value that enables the post processing to... | 5,296,318 |
def backward_selection(g, n_, k_=None):
"""For details, see here.
Parameters
----------
g : function
n_ : int
k_ : int, optional
Returns
-------
s_star_bwd : list, shape(k_, 1:k_)
"""
if k_ is None:
k_ = n_
# Step 0: Initialize
s_star_backw... | 5,296,319 |
def auc_score(y_true, y_pred):
"""Gets the auc score of labels and predictions.
Parameters
----------
y_true : torch.tensor
The true labels.
y_pred : torch.tensor
The prediction.
Returns
-------
numpy.ndarray
The auc score.
"""
y_true, y_pred = prepare... | 5,296,320 |
def _get_node_names():
"""
returns the list of nodes in the cluster
:return: the list of nodes in the cluster
:rtype: list[str]
"""
nodes = _get_nodes()
node_list = []
for n in nodes:
node_list.append(n['name'])
return node_list | 5,296,321 |
def defaultdict():
"""defaultdict(...): Dictionary with a value for missing keys."""
kart = collections.defaultdict(lambda: 'unknown')
kart['speed'] = 66
return "kart specs are {}".format(''.join(
'{} -> {}'.format(key, kart[key]) for key in ('speed', 'sound'))) | 5,296,322 |
def execute_cast_datetime_to_integer(op, data, type, **kwargs):
"""Cast datetimes to integers"""
return pd.Timestamp(data).value | 5,296,323 |
def ferret_result_limits(efid):
"""
Abstract axis limits for the shapefile_writeval PyEF
"""
return ( (1, 1), None, None, None, None, None, ) | 5,296,324 |
def containment(lower_forecast, upper_forecast, actual):
"""Expects two, 2-D numpy arrays of forecast_length * n series.
Returns a 1-D array of results in len n series
Args:
actual (numpy.array): known true values
forecast (numpy.array): predicted values
"""
with warnings.catch_war... | 5,296,325 |
def _normalize_newlines(text: str) -> str:
"""Normalizes the newlines in a string to use \n (instead of \r or \r\n).
:param text: the text to normalize the newlines in
:return: the text with the newlines normalized
"""
return "\n".join(text.splitlines()) | 5,296,326 |
def set_db(db_obj):
"""
Receive fgAPIServerDaemon database object
:param db_obj: database object
"""
global fgapisrv_db
fgapisrv_db = db_obj
logging.debug("Receiving database object") | 5,296,327 |
def getAxlib(libPath=None):
"""Return the handle to the axon library (CLibrary instance).
If libPath is specified, then it must give the location of the AxMultiClampMsg.dll
file that should be loaded. Otherwise, a predefined set of paths will be searched.
Note: if you want to specify the DLL file usin... | 5,296,328 |
def get_parsers():
"""Yield valid TAP parser commands."""
for parser, command in PARSER_CMDS.items():
if not subprocess.call(['which', shlex.quote(parser)]):
yield command | 5,296,329 |
def test_login_view_request_timeout(cloud_client):
"""Test request timeout while trying to log in."""
with patch('homeassistant.components.cloud.auth_api.login',
side_effect=asyncio.TimeoutError):
req = yield from cloud_client.post('/api/cloud/login', json={
'email': 'my_usern... | 5,296,330 |
def create( # pylint: disable=too-many-arguments
project_id,
identifier,
metadata_json,
host,
email,
password,
api_key,
): # pylint: disable=line-too-long
"""Sets up periodic import of BaseSpace projects (their Biosamples) whose name contain the identifer
to a project in Gencove. O... | 5,296,331 |
def create_stanford_article_level_model(rnn_type, embedding_matrix, sentence_size, hidden_size, dense_size, trainable=False, use_dropout=True, dropout=0.5):
"""
Create RNN model
:param rnn_type:
:param hidden_size:
:param dense_size:
:return:
"""
# Model
model = Sequential()
# E... | 5,296,332 |
def backdoor(request, userid=None, view=None, list=None):
"""Provide simple client interface in Django backend."""
if not userid:
user = None # perhaps there is no user yet
username = request.GET.get('user', 'test001') # default: test001
originname = request.GET.get('origin', 'UOS') ... | 5,296,333 |
def read_words(f, count=100, encoding="utf-8"):
"""Reads the given number of words from the specified open file."""
result = []
while len(result) < count:
line = wrapped_readline(f, encoding=encoding).strip()
words = [w.strip() for w in line.split(" ")]
# remove empty words
w... | 5,296,334 |
def deal_card(find_dict):
"""
@param find_dict: 传递了card_dict实参
"""
# print(find_dict)
action_str = input("请选择要执行的操作 "
"[1]修改"
"[2]删除"
"[0]返回上级菜单: " )
if action_str == "1":
find_dict["name"] = input_card_info(find_dict[... | 5,296,335 |
def create_tvshow_tiles_content(tvshows):
""" The HTML content for this section of the page
"""
content = ''
for tvshow in tvshows:
# Extract the youtube ID from the url
youtube_id_match = re.search(r'(?<=v=)[^&#]+', tvshow.trailer_youtube_url)
youtube_id_match = youtube_id_match... | 5,296,336 |
def train(net, train_data, val_data, eval_metric, ctx, args):
"""Training pipeline"""
net.collect_params().reset_ctx(ctx)
trainer = gluon.Trainer(
net.collect_params(), 'sgd',
{'learning_rate': args.lr, 'wd': args.wd, 'momentum': args.momentum})
# lr decay policy
lr_decay = float(ar... | 5,296,337 |
def dump_interfaces_config(nics=None, tag=None):
"""Dumps ifcfg files data and route metric"""
if not nics:
msg = 'The "nics" dict should hold ifaces macs. Currently empty.'
logger.info(msg)
raise ValueError(msg)
iface_dump = []
iface_content = {}
data_path = args.nics_data_... | 5,296,338 |
def pick_from_greatests(dictionary, wobble):
"""
Picks the left- or rightmost positions of the greatests list in a window
determined by the wobble size. Whether the left or the rightmost positions
are desired can be set by the user, and the list is ordered accordingly.
"""
previous = -100
is... | 5,296,339 |
def resolve_sources(directory: str, sources: Sources) -> Iterable[str]:
"""
Returns an iterable of absolute paths to the files specified by the sources
object. Files are not guaranteed to exist.
"""
filesystem = get_filesystem()
result = {os.path.join(directory, file) for file in sources... | 5,296,340 |
def replace_layer(model, layer_name, replace_fn):
"""Replace single layer in a (possibly nested) torch.nn.Module using `replace_fn`.
Given a module `model` and a layer specified by `layer_name` replace the layer using
`new_layer = replace_fn(old_layer)`. Here `layer_name` is a list of strings, each string
... | 5,296,341 |
def create_html_output(json_docs):
"""Create html output for the playbook by converting the docs to markdown and then converting to html."""
markdown_docs = create_markdown_output(json_docs)
return markdown.markdown(markdown_docs) | 5,296,342 |
def main():
"""Program entry point"""
measure_arp_latency(sys.stdin.buffer) | 5,296,343 |
def has_name_pf(name_p, ignore_case=True):
"""
Predicate factory, returns true if the element name matches the pred parameter
* **name_p**: something that can be converted into a string compare predicate
* **ignore_case**: should the comparison be case sensitive (default: ignore case)
* **return**:... | 5,296,344 |
def genInvSBox( SBox ):
"""
genInvSBox - generates inverse of an SBox.
Args:
SBox: The SBox to generate the inverse.
Returns:
The inverse SBox.
"""
InvSBox = [0]*0x100
for i in range(0x100):
InvSBox[ SBox[i] ] = i
return InvSBox | 5,296,345 |
def get_unassigned(values:dict, unassigned:dict):
"""
Select Unassigned Variable
It uses minimum remaining values MRV and degree as heuristics
returns a tuple of:
unassigned key and a list of the possible values
e.g. ('a1', [1, 2, 3, 4, 5, 6, 7, 8, 9])
"""
values_sort = dict() # em... | 5,296,346 |
def movefiles(files, destdir, confirm=True, verbose=True, copy=True):
"""
Move a set of files to a a destination directory tree,
but let the original complete path be reflected in the
destination tree.
files list of filenames
destdir root of destination directory tree
... | 5,296,347 |
def verify_property_names(names):
"""Check credential property names for syntax-compliance.
Parameters
----------
names: iterable
Raises
------
ValueError
When any non-compliant property names were found
"""
invalid_names = [
k for k in names
if not Credential... | 5,296,348 |
def countvec():
"""
对文本进行特征值化
:return: None
"""
# 实例化CountVectorizer
vector = CountVectorizer()
# 调用fit_transform输入并转换数据
# res = vector.fit_transform(["life is short,i like python","life is too long, i dislike python"])
res = vector.fit_transform(["人生苦短,我喜欢python","人生漫长,不用python"])... | 5,296,349 |
def get_auth_token_ssh(account, signature, appid, ip=None):
"""
Authenticate a Rucio account temporarily via SSH key exchange.
The token lifetime is 1 hour.
:param account: Account identifier as a string.
:param signature: Response to challenge token signed with SSH private key as a base64 encoded... | 5,296,350 |
def is_superset_of(value, superset):
"""Check if a variable is a superset."""
return set(value) <= set(superset) | 5,296,351 |
def _poll_for_status(client_id, device_code):
"""Polls API to see if user entered the device code
This is the second step of the Device Flow. Returns an access token, and
also writes the token to a file in the user's home directory.
"""
header = {"Content-Type": "application/json", "Accept": "appl... | 5,296,352 |
def datetime_to_year(dt: datetime) -> float:
"""
Convert a DateTime instance to decimal year
For example, 1/7/2010 would be approximately 2010.5
:param dt: The datetime instance to convert
:return: Equivalent decimal year
"""
# By Luke Davis from https://stackoverflow.com/a/42424261
y... | 5,296,353 |
def read_track(chunk):
"""Retuns a list of midi events and tempo change events"""
# Deviations: The running status should be reset on non midi events, but
# some files contain meta events inbetween.
# Offset and time signature are not used.
tempos = []
events = []
deltasum = 0
status ... | 5,296,354 |
def bisect_good(commit):
"""Mark a commit as good.
The same disclaimer as for `bisect_bad` applies.
"""
# alternative: `git bisect--helper bisect-write`
rev_parsed = git.rev_parse(commit)
git.update_ref(f"refs/bisect/good-{rev_parsed}", commit)
bisect_append_log(f"# good: {git.rev_pretty(co... | 5,296,355 |
def are_adjacent_empty(positions, seats):
"""Check if all seats from the positions are not OCCUPIED."""
return all(
seat != OCCUPIED
for seat in get_seats(positions, seats)
) | 5,296,356 |
def one_component_ejecta_relation(time, redshift, mass_1, mass_2,
lambda_1, lambda_2, kappa, **kwargs):
"""
Assumes no velocity projection in the ejecta velocity ejecta relation
:param time: observer frame time in days
:param redshift: redshift
:param mass_1: mass ... | 5,296,357 |
def uhs500_msg_parsed() -> Message:
"""Expected :class:`~tslumd.messages.Message` object
matching data from :func:`uhs500_msg_bytes`
"""
data = json.loads(MESSAGE_JSON.read_text())
data['scontrol'] = b''
displays = []
for disp in data['displays']:
for key in ['rh_tally', 'txt_tally',... | 5,296,358 |
def brute_force_matchings(graph: Graph, partial_matchings: List[Matching]) -> List[Matching]:
"""Recursive algorithm for brute force maximum matching search"""
if len(graph.get_edges()) == 0:
return partial_matchings
updated_matchings = []
for edge in graph.get_edges():
incremented_match... | 5,296,359 |
def status_check(request):
"""
JSON response for health checks.
"""
# because the argument is framework we will ignore
# pylint: disable=unused-argument
resp = {'status': 'up'}
return JsonResponse(resp) | 5,296,360 |
def ek_R56Q(cell):
"""
Returns the R56Q reversal potential (in mV) for the given integer index
``cell``.
"""
reversal_potentials = {
1: -96.0,
2: -95.0,
3: -90.5,
4: -94.5,
5: -94.5,
6: -101.0
}
return reversal_potentials[cell] | 5,296,361 |
def _get_schema(cur: pyodbc.Cursor, table_name: str):
"""Get schema and table name - returned as tuple
"""
t_spl = table_name.split(".")
if len(t_spl) > 1:
return t_spl[0], ".".join(t_spl[1:])
else:
return _get_default_schema(cur), table_name | 5,296,362 |
def poincare_tiling(p, q, nlayers, center):
"""
produce poincare regular tiling
p : number of edges per face
q : number of faces meeting at a vertex
nlayers : number of layers or rings of faces
"""
max_faces = count_faces(p, q, nlayers)
edges_out = []
verts_out = []
faces_out =... | 5,296,363 |
def magenta_on_white(string, *funcs, **additional):
"""Text color - magenta on background color - white. (see sgr_combiner())."""
return sgr_combiner(string, ansi.MAGENTA, *funcs, attributes=(ansi.BG_WHITE,)) | 5,296,364 |
def prepare_entangled(alpha, beta):
"""Construct a circuit that prepares the (not necessarily maximally) entangled state in terms of alpha and beta
Do not forget to normalize.
Args:
- alpha (float): real coefficient of |00>
- beta (float): real coefficient of |11>
"""
norm_beta = b... | 5,296,365 |
def build(directory, name):
"""
Build an image using a Dockerfile at a specific path using the full name to
tag the resulting image.
Arguments:
directory (str): The directory containing the Dockerfile for the
distribution.
name (str): The full name of the resulting image inc... | 5,296,366 |
def NEG(cpu_context: ProcessorContext, instruction: Instruction):
""" Negate """
operands = instruction.operands
opvalue1 = operands[0].value
result = -opvalue1
width = operands[0].width
mask = utils.get_mask(width)
cpu_context.registers.cf = int(result & mask != 0)
cpu_context.register... | 5,296,367 |
def command_validate(opts):
"""Check a .zs file for errors or data corruption.
Usage:
zs validate [-j PARALLELISM] [--] <zs_file>
Arguments:
<zs_file> Path or URL pointing to a .zs file. An argument beginning with
the four characters "http" will be treated as a URL.
Options:
-j PARALLELISM ... | 5,296,368 |
def deriv_activation_func(func_type, z):
"""
Implements the different kind of derivated activation functions including:
line - linear function
sigm - sigmoidal
tanh - hyperbolic tangent
ptanh - smothly hyperbolic tangent
relu - Rectfied
step - Heavside (bi... | 5,296,369 |
def createStringMacroseismicHeader(header):
"""
Function that creates NordicMacroseismic list with values being strings
:param str header: string from where the data is parsed from
:return: NordicMacroseismic object with list of values parsed from header
"""
nordic_macroseismic = [None]*22
... | 5,296,370 |
def code_search(ea, val):
"""Search forward for the next occurance of val. Return None if no match."""
res = idc.FindBinary(ea, idc.SEARCH_DOWN, val)
if res == idaapi.BADADDR:
return None
else:
return res | 5,296,371 |
async def ping(request):
"""driver health check."""
client, error = _get_client(request)
raise NotImplementedError | 5,296,372 |
def buffer_input(data, buffer, input_data):
"""Repeats last search with 'input_data' as regexp."""
try:
cmd_grep_stop(buffer, input_data)
except:
return WEECHAT_RC_OK
if input_data in ('q', 'Q'):
weechat.buffer_close(buffer)
return weechat.WEECHAT_RC_OK
global search... | 5,296,373 |
def read_input_files(input_file: str) -> list[Seat]:
"""
Extracts a list of valid passwords from the input file.
"""
with open(input_file) as input_fobj:
seats = [Seat.from_binary_partition(line.strip()) for line in input_fobj]
return seats | 5,296,374 |
def setup(client, blueprint_dir):
"""
Create all the boilerplate to spin up the service, and the service itself.
"""
logger.info("Running setup to test: %s", blueprint_dir)
state = get_state(blueprint_dir)
if state:
raise DisallowedOperationException(
"Found non empty state f... | 5,296,375 |
def mediapackage_channel_mediapackage_endpoint_ddb_items():
"""
Identify and format MediaPackage channel to MediaPackage endpoint connections for cache storage.
"""
items = []
package_key = re.compile("^(.+)Package$")
try:
# get mediapackage channels
mediapackage_ch_cached = cach... | 5,296,376 |
def reinsert_star(seq, gapped_seq):
"""
Reinserts '*' at end of gapped alignment to make finding the end of
the aligned portion more accurate
"""
length = len(seq)
count = 0
for i in range(len(gapped_seq)):
if gapped_seq[i] == seq[count] and count == 0:
start = i
... | 5,296,377 |
def _functional_groups_stable(geo, thy_save_fs, mod_thy_info):
""" look for functional group attachments that could cause
molecule instabilities
"""
# Initialize empty set of product graphs
prd_gras = ()
# Check for instability causing functional groups
gra = automol.geom.graph(geo)
... | 5,296,378 |
def get_table_reader() -> Callable[[Engine, Table], List[dict]]:
"""
When syncing from a relational database, currently MySQL or Postgres, the database has only a single concept of
state, that is the current state. We simply capture this state by reading out all the data in the database.
:return:
"... | 5,296,379 |
def scene_to_raster(scene):
"""Convert scene to a integer array height x width containing color codes.
"""
pixels = simulator_bindings.render(serialize(scene))
return np.array(pixels).reshape((scene.height, scene.width)) | 5,296,380 |
def _GetGitOrigin(path):
"""Returns the URL of the 'origin' remote for the git repo in |path|. Returns
None if the 'origin' remote doesn't exist. Raises an IOError if |path| doesn't
exist or is not a git repo.
"""
section = None
for line in open(os.path.join(path, '.git', 'config'), 'rb'):
m = _GIT_CONF... | 5,296,381 |
def test_missingsym():
"""Tests read a GAF with missing (required) DB_Symbol text."""
# Original gaf file (mgi.gaf) was reduced
fin_gaf = "tests/data/gaf_missingsym.mgi"
# Test that gene products that are missing the required DB_Symbol are ignored
gene2gos = read_gaf(os.path.join(REPO, fin_gaf))
... | 5,296,382 |
def gtk_menu_position(event, *args):
"""
Create a menu at the given location for an event. This function is meant to
be used as the *func* parameter for the :py:meth:`Gtk.Menu.popup` method.
The *event* object must be passed in as the first parameter, which can be
accomplished using :py:func:`functools.partial`.
... | 5,296,383 |
def mm2cm(v):
"""
Converts value from mm to cm
Parameters
----------
v: value
input value, mm
returns:
value in cm
"""
if np.isnan(v):
raise ValueError("mm2cm", "Not a number")
return v * 0.1 | 5,296,384 |
def plotCentroidLocation(col, row, **kwargs):
"""Add a point to the a plot.
Private function of `generateDiffImgPlot()`
"""
ms = kwargs.pop("ms", 9)
clr = kwargs.pop("color", "g")
mec = kwargs.pop("mec", "white")
mew = kwargs.pop("mew", "1")
marker = kwargs.pop("marker", "o")
#plt.... | 5,296,385 |
def ssim(x, y):
"""Calculate ssim value of x (3D) in respect to y (3D).
:param x: preprocessed predicted tensor (3D)
:type x: torch.Tensor
:param y: preprocessed groundtruth tensor (3D)
:type y: torch.Tensor
"""
# pre-computation
C1 = (0.01 * 255) ** 2
C2 = (0.03 * 255) ** 2
fla... | 5,296,386 |
def draw_star (im, yc, xc, radius, npoints, inner_radius=None,
v=max_image_value, fast=False, fill=False):
"""
Draw an npoints-pointed star of radius r centred at (yc, xc).
Arguments:
im image upon which the text is to be written (modified)
yc y-value (row) of t... | 5,296,387 |
async def songdb(timeout: int = config.TIMEOUT) -> Any:
"""
返回 ``song_id`` - 歌名(en|jp) 的字典表
"""
async with websockets.connect(config.ESTERTION_URI, timeout=timeout) as ws:
await ws.send('constants')
r = await ws.recv()
await ws.close()
return json.loads(brotli.decompress(... | 5,296,388 |
def imagenet_resnet_v2_generator(block_fn, layers, num_classes, data_format=None):
"""Generator for ImageNet ResNet v2 models.
Args:
block_fn: The block to use within the model, either `building_block` or
`bottleneck_block`.
layers: A length-4 array denoting the number of blocks to include in each
... | 5,296,389 |
def get_api_url(request_object, production=False):
""" Get api URL and PORT
Usefull to handle https and similar
unfiltering what is changed from nginx and container network configuration
Warning: it works only if called inside a Flask endpoint
"""
api_url = request_object.url_root
if pro... | 5,296,390 |
def get_group_of_dependent_blocks(blocks: List[BuildingBlock]) -> Dict[int, int]:
"""
Building blocks can be categorized into groups. Blocks that follow each other in the graph
(that is, they are connected by one edge) belong to the same group.
:param: List of building blocks.
:return: Dictionary w... | 5,296,391 |
def eval_data(dataset):
"""
Given a dataset as input returns the loss and accuracy.
"""
# If dataset.num_examples is not divisible by BATCH_SIZE
# the remainder will be discarded.
# Ex: If BATCH_SIZE is 64 and training set has 55000 examples
# steps_per_epoch = 55000 // 64 = 859
# num_ex... | 5,296,392 |
def console(node, display, **kwargs):
"""
console for node
"""
server = VIRLServer()
client = get_cml_client(server)
skip_types = ["external_connector", "unmanaged_switch"]
current_lab = get_current_lab()
if current_lab:
lab = safe_join_existing_lab(current_lab, client)
... | 5,296,393 |
def list_blobs(bucket_name):
"""Lists all the blobs in the bucket."""
# bucket_name = "your-bucket-name"
storage_client = storage.Client()
# Note: Client.list_blobs requires at least package version 1.17.0.
blobs = storage_client.list_blobs(bucket_name)
return [i.name for i in blobs]
# for... | 5,296,394 |
def write_vocab(vocab, filename):
"""Writes a vocab to a file
Writes one word per line.
Args:
vocab: iterable that yields word
filename: path to vocab file
Returns:
write a word per line
"""
with open(filename, "w") as f:
for i, word in enumerate(vocab):
... | 5,296,395 |
def valid_header(header: BlockHeader, difficulty: int) -> bool:
"""Check if block hash matches header data."""
h = hash.hash(header['timestamp'] +
header['previous_hash'] +
header['nonce'] +
header['merkle_root'])
return (header['this_hash'] == h and
... | 5,296,396 |
def insert_initial_state(
initial_state,
mol_entries,
initial_state_db,
factor_zero = 1.0,
factor_two = 1.0,
factor_duplicate = 0.5
):
"""
initial state is a dict mapping species ids to counts.
"""
rn_con = sqlite3.connect(initial_state_db)
rn_cur = r... | 5,296,397 |
def test_name_init(generic_task):
"""Test if initial name is default."""
assert generic_task.get_name() == 'OBjEcT' | 5,296,398 |
def poisson_gamma(data, sum_w, sum_w2, a=1, b=0):
"""
Log-likelihood based on the poisson-gamma mixture. This is a Poisson likelihood using a Gamma prior.
This implementation is based on the implementation of Austin Schneider (aschneider@icecube.wisc.edu)
-- Input variables --
data = data histo... | 5,296,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.