content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def fmt_uncertainty(x, dx, sn=None, sn_cutoff=8, unit=None):
"""Format uncertainty for latex."""
n_decimals = -int(np.floor(np.log10(np.abs(dx))))
leading_magnitude = np.abs(dx)/10**-n_decimals
if leading_magnitude <= 1.5:
n_decimals += 1
if sn is None:
if np.abs(x) >= 10**sn_cutoff ... | bcfbd5f22adc6a6afac1a659afe62b893ad34f1b | 19,300 |
def seed_test_input(clusters, limit):
"""
Select the seed inputs for fairness testing
:param clusters: the results of K-means clustering
:param limit: the size of seed inputs wanted
:return: a sequence of seed inputs
"""
i = 0
rows = []
max_size = max([len(c[0]) for c in clusters])
... | 03462327a6554c966d58d1e1982b40bd396e88c9 | 19,301 |
import numpy
def calc_senescence_water_shading(
aglivc, bgwfunc, fsdeth_1, fsdeth_3, fsdeth_4):
"""Calculate shoot death due to water stress and shading.
In months where senescence is not scheduled to occur, some shoot death
may still occur due to water stress and shading.
Parameters:
... | d45fbeaa24138b46fd88caa815f5e15c4098a7e5 | 19,302 |
def hello(friend_name: float = None) -> str:
"""Function to greet the user, takes a string and return Hello, 'string'"""
if not isinstance(friend_name, str):
raise TypeError("this function expects a string as input")
return f'Hello, {friend_name}!' | 9e5ab340fdeb1bed2cd48758bab8a0815ae6f75c | 19,303 |
def flatten(lst):
"""Shallow flatten *lst*"""
return [a for b in lst for a in b] | 203e971e43aea4d94bfa0ffa7057b416ef0bf545 | 19,304 |
def _transform_org_units(metadata: dict) -> pd.DataFrame:
"""Transform org units metadata into a formatted DataFrame."""
df = pd.DataFrame.from_dict(metadata.get("organisationUnits"))
df = df[["id", "code", "shortName", "name", "path", "geometry"]]
df.columns = ["ou_uid", "ou_code", "ou_shortname", "ou_... | a90532e5d5b09aeb2a85addad518c54301710141 | 19,305 |
def post_process(done_exec, temp_file):
"""For renaissance, `temp_file` is a path to a CSV file into which the
results were written. For other suites, it is `None`."""
if done_exec.suite == "renaissance":
assert temp_file is not None
return post_process_renaissance(done_exec, temp_file)
... | 615098d2ddc3806984fbc448bca377933c87973f | 19,306 |
def freeze(regex_frozen_weights):
"""Creates an optimizer that set learning rate to 0. for some weights.
Args:
regex_frozen_weights: The regex that matches the (flatten) parameters
that should not be optimized.
Returns:
A chainable optimizer.
"""
return scale_selected_parameters(regex_frozen_w... | bc4c511a1b6a03b1dd08c63d12fb5af55e177b62 | 19,307 |
def store_sourceip_telemetry():
"""
route to handle inbound telemetry from daemonset ip collector agents
"""
# load up some context so we can append to it
context = SourceIpTelemetry.get_instance()
if context.data:
telemetry = context.get()
else:
telemetry = {}
payload = ... | d14a33d31a64ae40abc86e6d613792e6d3ea359b | 19,308 |
def sep_num(number, space=True):
"""
Creates a string representation of a number with separators each thousand. If space is True, then it uses spaces for
the separator otherwise it will use commas
Note
----
Source: https://stackoverflow.com/questions/16670125/python-format-string-thousand-separ... | ee7dfbb60fb01bb7b6bb84cbe56ec50dfab4b339 | 19,309 |
def raw_smooth_l1_loss(diff, delta=1.0, max_val=10.0):
"""
Creates smooth L1 loss. The regular version is sometimes unstable so here what we do is if the difference
is > some value, we will return the log instead.
So it's then
0.5 * x^2 if |x| ... | 0f82ebdb72d27c1dc5e961d6905d1488d56e46b2 | 19,310 |
import os
from sys import path
import pathlib
import re
def model_f2_statistics(mode_path, val_index=1, save_dir=None, save_file=None):
"""
对model目录下的所有包含"evaluate"字段的文件进行统计,分别得到all-label、one-label统计
:param mode_path: 需要统计的目录
:param save_file: 输入文件
:return:
"""
evaluate_files = []
for ... | 22e766151827531d7a2e42ff6d114fed1c5a6cdc | 19,311 |
def read_parameters(request, view_kwargs):
"""
:param request: HttpRequest with attached api_info
:type request: HttpRequest
:type view_kwargs: dict[str, object]
:rtype: dict[str, object]
"""
params = {}
errors = {}
for param in request.api_info.operation.parameters:
try:
... | fb21c7a01fa4902e9e5adcb676731ee324438226 | 19,312 |
import requests
import zipfile
import os
def handler(body, archiveFile=None):
""" Execute the SED-ML files in a COMBINE/OMEX archive.
Args:
body (:obj:`dict`): dictionary with schema ``SimulationRun`` with the
specifications of the COMBINE/OMEX archive to execute and the simulator to exec... | c54a6d06406a4564b3a328932f3ba32f562358b9 | 19,313 |
import getpass
def get_passwd():
"""Prompt user for a password
Prompts user to enter and confirm a password. Raises an exception
if the password is deemed to be invalid (e.g. too short), or if
the password confirmation fails.
Returns:
Password string entered by the user.
"""
passw... | 214f6078e07259eea55aa9bd6269cfc7742f7edc | 19,314 |
def _render_footnote_block_open(self, tokens, idx, options, env):
"""Render the footnote opening without the hr tag at the start."""
html = mdit_py_plugins.footnote.index.render_footnote_block_open(
self, tokens, idx, options, env
)
lines = html.split("\n")
if lines[0].strip().startswith("<h... | 56c3e6bfaada2bf5c4ea1fa48ebe4e5cd53dbea0 | 19,315 |
def remove_shot_from_scene(scene, shot, client=default):
"""
Remove link between a shot and a scene.
"""
scene = normalize_model_parameter(scene)
shot = normalize_model_parameter(shot)
return raw.delete(
"data/scenes/%s/shots/%s" % (scene["id"], shot["id"]),
client=client
) | ca6db744a60be7ee287aa95ba647f53b6afff42e | 19,316 |
def all_results_failed(subsystems):
"""Check if all results have failed status"""
for subsystem in subsystems.values():
if subsystem['subsystemStatus'] == 'OK':
# Found non-failed subsystem
return False
# All results failed
return True | 6612397c5b1605ad3e623e3c47264869c93cd47d | 19,317 |
from src.praxxis.sqlite import connection
def get_scene_id(current_scene_db):
"""gets the scene ID from the scene db"""
conn = connection.create_connection(current_scene_db)
cur = conn.cursor()
get_scene_id = 'SELECT ID FROM "SceneMetadata"'
cur.execute(get_scene_id)
id = str(cur.fetchone()[0... | 95c7a6ab2ef9484205fab57540ac71da22734428 | 19,318 |
def compile_playable_podcast1(playable_podcast1):
"""
@para: list containing dict of key/values pairs for playable podcasts
"""
items = []
for podcast in playable_podcast1:
items.append({
'label': podcast['title'],
'thumbnail': podcast['thumbnail'],
'path... | faf5e03aa4472a20564df9b0872ce58ffa8bce79 | 19,319 |
import math
def mouseclick(pos):
"""
Define "mouse click" event handler; implements game
"state" logic. It receives a parameter; pair of screen
coordinates, i.e. a tuple of two non-negative integers
- the position of the mouse click.
"""
# User clicks on a "card" of the "deck" (gri... | d283e9f9dd8581cf3d1daf997ff72af01e8d32cc | 19,320 |
def __get_ip_udp_int_pkt(ip_pkt):
"""
Retrieves the INT UDP packet
:param ip_pkt:
:return:
"""
logger.info('Obtaining INT data')
udp_pkt = UDP(_pkt=ip_pkt.payload)
logger.debug('UDP packet dport - [%s]', udp_pkt.dport)
if udp_pkt.dport == trans_sec.consts.UDP_INT_DST_PORT:
lo... | 7c87b33b26eb650a7e64a211aa229dbe9f433ee6 | 19,321 |
def fixture_version_obj(bundle_data: dict, store: Store) -> models.Version:
"""Return a version object"""
return store.add_bundle(bundle_data)[1] | 4088df55621dc5cf43aefca07e8f34b8bfdf5e42 | 19,322 |
def ranges_compute(x, n_bins):
"""Computation of the ranges (borders of the bins).
Parameters
----------
x: pd.DataFrame
the data variable we want to obtain its distribution.
n_bins: int
the number of bins we want to use to plot the distribution.
Returns
-------
ranges:... | 28c0fcb61bc5a6417430e7b44972ba9e57a3914c | 19,323 |
def creation(basis_size: int, state_index: int) -> spr.csc_matrix:
"""
Generates the matrix of the fermionic creation operator for a given single particle state
:param basis_size: The total number of states in the single particle basis
:param state_index: The index of the state to be created by the oper... | 7967aa861a1366a4187a70dad31c32625410fd3d | 19,324 |
def LowercaseMutator(current, value):
"""Lower the value."""
return current.lower() | 7fed0dc4533948c54b64f649e2c85dca27ee9bc5 | 19,325 |
def gtf2gff(gtfname,gffname, memt=True):
"""Convert GTF to GFF.
Args:
gtfname: path to GTF file
gffname: path for converted GFF file
memt: only select multiexon, multitranscript
Returns:
Pandas.DataFrame containing converted GFF data
"""
eids = read_gtf(gtfname,
... | 710af0ed2222c98e9c5cc27cb32a9100143fa26e | 19,326 |
import collections
def write_predictions(all_examples, all_features, all_results, n_best_size,
max_answer_length, do_lower_case, verbose_logging, logger):
"""Write final predictions to the json file."""
example_index_to_features = collections.defaultdict(list)
for feature in all_fea... | a8ecc1eda5b7fc8b780f2d207e3d09d2b20f11ca | 19,327 |
def setup_view(view, request, *args, **kwargs):
"""Mimic ``as_view()``, but returns view instance.
Use this function to get view instances on which you can run unit tests,
by testing specific methods.
See https://stackoverflow.com/a/33647251 and
http://django-downloadview.readthedocs.io/en/latest/t... | 156710acfdb383c23d844fe8de4f78a1190193d9 | 19,328 |
from textwrap import dedent
def get_density(molecule_name, temperature=273.15, pressure=101325,
cycles=5000, init_cycles="auto",
forcefield="CrystalGenerator"):
"""Calculates the density of a gas through an NPT ensemble.
Args:
molecule_name: The molecule to test for ad... | c36e236c98d3f99a19979701c287e740543c909f | 19,329 |
def is_node_up(config, host):
"""
Calls nodetool statusbinary, nodetool statusthrift or both. This function checks the output returned from nodetool
and not the return code. There could be a normal return code of zero when the node is an unhealthy state and not
accepting requests.
:param health_che... | 4a80198ea8fede538f78f700f7d451dd65e8f435 | 19,330 |
def audits(program):
"""Create 2 audits mapped to the program"""
return [rest_facade.create_audit(program) for _ in xrange(2)] | 2fc7392c53cc0726dcba38b8eb44475fa5cb9ad8 | 19,331 |
def _create_run(uri, experiment_id, work_dir, entry_point):
"""
Create a ``Run`` against the current MLflow tracking server, logging metadata (e.g. the URI,
entry point, and parameters of the project) about the run. Return an ``ActiveRun`` that can be
used to report additional data about the run (metric... | 1ae9d084927423d88e0a737098b2567f940fbe11 | 19,332 |
def convertBoard(board):
"""
converts board into numerical representation
"""
flatBoard = np.zeros(64)
for i in range(64):
val = board.piece_at(i)
if val is None:
flatBoard[i] = 0
else:
flatBoard[i] = {"P": 1, "N" : 2, "B" : 3, "R" : 4, "Q" : 5... | 2ad05a0b1561b38332cb3b92686f903c8bd0f260 | 19,333 |
from typing import Dict
from typing import Any
from typing import MutableMapping
import logging
def merge_optional(default_dict: Dict[str, Any], update_dict: Dict[str, Any], tpe: str):
"""
Function to merge dictionaries to add set parameters from update dictionary into default dictionary.
@param default_d... | 32e52e58604b01061b6c5a3122287c0e5d8a9a84 | 19,334 |
def reference_pixel_map(dimensions, instrument_name):
"""Create a map that flags all reference pixels as such
Parameters
----------
dimensions : tup
(y, x) dimensions, in pixels, of the map to create
instrument_name : str
Name of JWST instrument associated with the data
Return... | 6800971d43ba481f3a62fce31eac21d93a36d42b | 19,335 |
import json
def geocode(value, spatial_keyword_type='hostname'):
"""convenience function to geocode a value"""
lat, lon = 0.0, 0.0
if spatial_keyword_type == 'hostname':
try:
hostname = urlparse(value).hostname
url = 'http://ip-api.com/json/%s' % hostname
LOGGER... | a2f94854a0881e5cb9041d0b134b0c4f811b132d | 19,336 |
def deploy_contract(w3, document_page_url, secret_key):
"""
TDeploy the contract
:param w3: the w3 connection
:param document_page_url: the document page url
:param secret_key: the operator secret key
:return: a pari tx_receipt, abi
"""
# 1. declare contract
document_sc = w3.eth.cont... | f295d263aba4929d84897da4dfc6af08fab7e808 | 19,337 |
from datetime import datetime
def format_date(format_string=None, datetime_obj=None):
"""
Format a datetime object with Java SimpleDateFormat's-like string.
If datetime_obj is not given - use current datetime.
If format_string is not given - return number of millisecond since epoch.
:param forma... | ea72af8ad5d3ba1999d9c05cd87203d59651bcc3 | 19,338 |
import pathlib
def testdata(request):
"""
If expected data is required for a test this fixture returns the path
to a folder with name '.testdata' located in the same director as the
calling test module
"""
testdata_dir = '.testdata'
module_dir = pathlib.Path(request.fspath).parent
retu... | 5d9a440b178aca00635f567420aaa9c406a1d7d2 | 19,339 |
def set_price(location, algo, order, price):
"""
https://api.nicehash.com/api?method=orders.set.price&id=8&key=3583b1df-5e93-4ba0-96d7-7d621fe15a17&location=0&algo=0&order=1881&price=2.1
:param location:
:param algo:
:param order:
:param price:
:return:
"""
resp = query('orders.set.p... | d8b90329c57e26a2a26f4aa134c66b9e1fd8b2c9 | 19,340 |
def jaccard_coef_loss(y_true, y_pred):
"""
Loss based on the jaccard coefficient, regularised with
binary crossentropy
Notes
-----
Found in https://github.com/ternaus/kaggle_dstl_submission
"""
return (-K.log(jaccard_coef(y_true, y_pred)) +
K.binary_crossentropy(y_pred, y_t... | 4c3d1def3ce650e9f7cd87e1a5d645d3a022f7a6 | 19,341 |
def __apply_rule_to_files_dataset_grouping(datasetfiles, locks, replicas, source_replicas, rseselector, rule, preferred_rse_ids=[], source_rses=[], session=None):
"""
Apply a rule to files with ALL grouping.
:param datasetfiles: Dict holding all datasets and files.
:param locks: Dict... | 621a3ef773afc8b2081b5505ac10a262db4ec374 | 19,342 |
import time
def call_webhook(event, webhook, payload):
"""Build request from event,webhook,payoad and parse response."""
started_at = time()
request = _build_request_for_calling_webhook(event, webhook, payload)
logger.info('REQUEST %(uuid)s %(method)s %(url)s %(payload)s' % dict(
uuid=str(ev... | 9abeacc76401ce07129d9abaeae496301b9e29d7 | 19,343 |
def safe_str(obj):
""" return the byte string representation of obj """
try:
return str(obj)
except UnicodeEncodeError:
# obj is unicode
return unicode(obj).encode('unicode_escape') | 74d3c75b03f38b0b151ff135a6a2ab3738822629 | 19,344 |
def default_user_agent():
"""Return a string representing the default user agent."""
return f'airslate/{__version__} ({__url__})' | 3de3e0adcf766a00b89479d8e8b00369a3f884a8 | 19,345 |
def join_complementary_byteblocks(block) -> int:
"""
join_complementary_byteblocks used to combine low bit data and high bit data
as the representation of complementary code
Parameters
----------
block : list
Low Digit Block -> int
High Digit Block -> int
Returns
------... | 0e86b132663f0d0517db9188a91443d698b74889 | 19,346 |
import numpy
def seed(func):
""" Decorator to seed the RNG before any function. """
@wraps(func)
def wrapper(*args, **kwargs):
numpy.random.seed(0)
return func(*args, **kwargs)
return wrapper | 3f1f563213d2e9175928e2f7fb5ddc90367ea0a6 | 19,347 |
def trim_bandstructure(
energy_cutoff: float, band_structure: BandStructure
) -> BandStructure:
"""
Trim the number of bands in a band structure object based on a cutoff.
Args:
energy_cutoff: An energy cutoff within which to keep the bands. If the system
is metallic then the bands t... | 3f3a0ead00657d4ceb32a5303823c7d9c538222f | 19,348 |
import os
def color_text(text: str, *colors: str):
"""
Applies color to a specific string and appends the color code to set the
text to normal. Text can be various colors by adding more args for colors.
Parameters
----------
text: str
String to color
colors: Tuple[str]
Any... | 21534c6b64c1acafbc7fd8f94bd2d611adc201c5 | 19,349 |
def _run_command(c: InvokeContext, cmd: str) -> CommandResult:
"""
Command runner.
:argument c: InvokeContext
:argument cmd: str the command to run
"""
try:
result = c.run(cmd)
return CommandResult(
exit_code=result.exited,
message=result.stdout,
... | 9b6e90f894099c1534b63e6171863a5430be3146 | 19,350 |
def get_proto_messages(protocol: str) -> list:
""" Get messages of a protocol. """
db = MetaDB()
rows = db.get_all_meta()
db.close_conn()
messages = set(row[1] for row in rows if row[0] == protocol)
return messages | 586b7f32b7ef1e713cacd31bdbb36d8f514e882d | 19,351 |
def TokenAMarkdownReference(href, reference, title=None):
"""
[link text][1]
[1]: <https://example.com> "Title"
<a href="https://example.com" title="Title">link text</a>
"""
title = ' "%s"' % title if title else ""
data = "[%s]: %s%s" % (reference, href, title)
token = {
"type"... | 48077864db045b841efa517a0136cf56a5d9ec8b | 19,352 |
import math
def inverse_document_frequency(word_occurrence, num_texts):
"""Takes in a word (string) and texts (list of lists and calculates the
number of texts over number of texts where the word occurs"""
try:
IDF = float(num_texts) / float(word_occurrence)
return math.log(IDF)
except... | a64e84b3c7d378e61765a84d3f4405e77b2ffd40 | 19,353 |
def bip32_mprv_from_seed(seed: octets, version: octets) -> bytes:
"""derive the master extended private key from the seed"""
if isinstance(version, str): # hex string
version = bytes.fromhex(version)
assert version in PRIVATE, "wrong version, master key must be private"
# serialization data
... | 2837bb9accc050e2defa3f38781d17d6f4917193 | 19,354 |
def create_menu_node(context: WxRenderingContext) -> WxNode:
"""Creates node from xml node using namespace as module and tag name as class name"""
inst_type = get_type(context.xml_node)
args = get_attr_args(context.xml_node, 'init', context.node_globals)
inst = inst_type(**args)
return WxNode(inst, ... | 3b3a215b917c980eb273f19f9f6dc9587df6874f | 19,355 |
def attach_calibration_pattern(ax, **calibration_pattern_kwargs):
"""Attach a calibration pattern to axes.
This function uses calibration_pattern to generate a figure.
Args:
calibration_pattern_kwargs: kwargs, optional
Parameters to be given to the calibration_pattern function.
Retur... | 935c3f9d3651162963c10580fdcfe94e11627a0f | 19,356 |
import base64
def alignplot(align_data, en_tokens = None, es_tokens = None, annot = False):
"""
plot the align data with tokens in both language
:params: annot: whether give annot on each element in the matrix
:params: align_data: attention matrix, array-like
:params: en_tokens: english tokens (li... | 52cf41491e70c8340a40fb16a6fdd4ffbcd68345 | 19,357 |
import sys
def GetModuleObjectAndName(globals_dict):
"""Returns the module that defines a global environment, and its name.
Args:
globals_dict: A dictionary that should correspond to an environment
providing the values of the globals.
Returns:
_ModuleObjectAndName - pair of module object & modul... | 99ea8e9b3c88da83b2ba20d1e610180958f5a01d | 19,358 |
from datetime import datetime
def to_datetime(timestamp: str) -> datetime.datetime:
"""Converts a timestamp string in ISO format into a datatime object.
Parameters
----------
timstamp : string
Timestamp in ISO format
Returns
-------
datetime.datetime
Datetime object
"... | 16a2a1ac36e2d1988ddf41ec05fbc59a9a596dff | 19,359 |
from typing import Any
from typing import Union
from typing import Callable
async def handle_arg(
ctx: SlashContext,
key: str,
value: Any,
type_: Union[Callable, commands.Converter]
) -> Any:
"""
Handle an argument and deal with typing.Optional modifiers
Parameters
----------
ctx ... | 21808304b4d194cfd13d705469babd7ec8c20c20 | 19,360 |
import argparse
def parse_command_arguments():
"""Returns parsed command arguments"""
parser = argparse.ArgumentParser(description="svg-to-swift converter")
parser.add_argument("--input_file", required=True, help="SVG file to convert.")
parser.add_argument("--output_file", default="svg.swift", help="F... | c01ed5e6c1f5ca116e87da4e686d866a67876daa | 19,361 |
def get_module_source_path(modname, basename=None):
"""Return module *modname* source path
If *basename* is specified, return *modname.basename* path where
*modname* is a package containing the module *basename*
*basename* is a filename (not a module name), so it must include the
file extension: .p... | b212713a53a14deb0fcd1a1518d2665bef03091f | 19,362 |
def drop_useless_columns(data):
"""Drop the columns containing duplicate or useless columns."""
data = data.drop(
labels=[
# we stay in a given city
"agency_id",
"agency_name",
"agency_short_name",
# we stay on a given transportation network
... | 7a47625a5df7e9fa66cefe2f326af3f0b9f59b79 | 19,363 |
from typing import Any
from typing import Optional
def arg_to_timestamp(arg: Any, arg_name: str, required: bool = False) -> Optional[int]:
"""Converts an XSOAR argument to a timestamp (seconds from epoch)
This function is used to quickly validate an argument provided to XSOAR
via ``demisto.args()`` into ... | 00fa81b041746be0e3f2e6a3c0545b72ab86fe3b | 19,364 |
import math
def expfloats (floats):
"""Manipulates floats so that their tiles are logarithmic sizes
large to small"""
return [math.exp(i) for i in floats] | 3943b8f8eedd4195693e0bace2223819f3728bb2 | 19,365 |
def typeChecker(obj, *types, error=True):
"""
Check type(s) of an object.
The first type correlates to the first layer of obj and so on.
Each type can be a (tuple that holds) type, string or literal object such as `None`.
:param obj: Generic obj, iterable or not
:param types: lists or tuples if... | 8ced14861295dd29bcbe2558d18a77d616cfec91 | 19,366 |
def post_profile_identifier_chunks_token(identifier, token):
"""
Updates a public chunk.
"""
chunk = models.Chunk.get_by_token(identifier, token)
if not chunk:
raise errors.ResourceNotFound('That chunk does not exist')
stream_entity = chunk.key.parent().get()
others = filter(lambda p... | 7a285df6eb2d41fc28d73b3c5da0621037808735 | 19,367 |
import logging
def get_latest_checkpoint(checkpoint_dir: str) -> int:
"""Find the episode ID of the latest checkpoint, if any."""
glob = osp.join(checkpoint_dir, 'checkpoint_*.pkl')
def extract_episode(x):
return int(x[x.rfind('checkpoint_') + 11:-4])
try:
checkpoint_files = tf.io.gfile.glob(glob)
... | 13677352d0d942bbc5348003ee449e27ea9f0371 | 19,368 |
def lazy(f):
"""A decorator to simply yield the result of a function"""
@wraps(f)
def lazyfunc(*args):
yield f(*args)
return lazyfunc | 5b44d01e0b982a8c36e8ce6aab2f9590e96509e6 | 19,369 |
def build_source_test_raw_sql(test_namespace, source, table, test_type,
test_args):
"""Build the raw SQL from a source test definition.
:param test_namespace: The test's namespace, if one exists
:param source: The source under test.
:param table: The table under test
:... | 2603081c3e36b9cdb3ca4e0c2381cbb5f34b3df4 | 19,370 |
from typing import List
from typing import Tuple
from typing import Optional
def get_random_word(used_words: List[int]) -> Tuple[Optional[str], List[int]]:
"""Select a random word from a list and pass on a list of used words.
Args:
used_words (list): A list of the indexes of every already used word.
... | bac4ebbf81cafef6fb615b8b4de7e74b848e794a | 19,371 |
def _generate_image_and_label_batch(image, label, min_queue_examples,
batch_size, height, shuffle, channels_last=True):
"""Construct a queued batch of images and labels.
Args:
image: 3-D Tensor of [height, width, 3] of type.float32.
label: 1-D Tensor of type.int32
... | 262d9ab1cace40ceb08b5bd1d8a4dd33f7fc151d | 19,372 |
def riskscoreci(x1, n1, x2, n2, alpha=0.05, correction=True):
"""Compute CI for the ratio of two binomial rates.
Implements the non-iterative method of Nam (1995).
It has better properties than Wald/Katz intervals,
especially with small samples and rare events.
Translated from R-package 'PropCI... | f1a976b744d7fca5f3e2005da952808db0d618ad | 19,373 |
def blend(a, b, alpha=0.5):
"""
Alpha blend two images.
Parameters
----------
a, b : numpy.ndarray
Images to blend.
alpha : float
Blending factor.
Returns
-------
result : numpy.ndarray
Blended image.
"""
a = skimage.img_as_float(a)
b = skimage.... | 2a3a6f68f48b7f6e3f5a51352082b40e63577955 | 19,374 |
def GetWsdlMethod(ns, wsdlName):
""" Get wsdl method from ns, wsdlName """
with _lazyLock:
method = _wsdlMethodMap[(ns, wsdlName)]
if isinstance(method, ManagedMethod):
# The type corresponding to the method is loaded,
# just return the method object
return method
elif... | 00892aa048f53d35b39184d1e72ff08e6e36b51a | 19,375 |
def plot_feature_wise(indicators, plot=False, show=True, ax=None, nf_max=40):
"""Plot the statistics feature-wise."""
n_mv_fw = indicators['feature-wise']
n_rows = indicators['global'].at[0, 'n_rows']
if show:
with pd.option_context('display.max_rows', None):
print(
... | 603839a5d3c78ae09d4212500e12fea92620169d | 19,376 |
import re
def normalize(string: str) -> str:
"""
Normalize a text string.
:param string: input string
:return: normalized string
"""
string = string.replace("\xef\xbb\xbf", "") # remove UTF-8 BOM
string = string.replace("\ufeff", "") # remov... | 2adaeffb60af598dad40bd6f5cd7e61e6b238123 | 19,377 |
def get_images(image_dir: str, image_url: str = DEFAULT_IMAGE_URL):
"""Gets image.
Args:
image (str): Image filename
image_url (str): Image url
Returns:
str: Output image filename
"""
images = list_images(image_dir)
if not images and image_url is not None:
print... | 3229d08606dabef04d43251f85c3b24c02ea9d93 | 19,378 |
import string
def generate_key(length=128):
"""Generate a suitable client secret"""
rand = SystemRandom()
return "".join(
rand.choice(string.ascii_letters + string.digits + string.punctuation)
for x in range(length)
) | 084d691c424f08d97aeefdd6dddff1012b009bc8 | 19,379 |
import logging
import os
def export(mv_file, idx_file, dst_path, start=0, end=0, max_workers=5):
"""
:param mv_file: mv所在目录
:param idx_file: idx所在目录
:param dst_path: 结果存放目录
:param start:
:param end:
:param max_workers:
:return:
"""
mv_op = resolvemv_ope(mv_file, idx_file) # 实... | b08a778b9c345e4e93091cee5f6a2dfb90dac9de | 19,380 |
def upload_tosca_template(file): # noqa: E501
"""upload a tosca template description file
upload and validate a tosca template description file # noqa: E501
:param file: tosca Template description
:type file: werkzeug.datastructures.FileStorage
:rtype: str
"""
res = tosca_template_servic... | b1f62613acda7f0e2abf2df0d3a19792dc5cd029 | 19,381 |
def extract_data(mask, dra, ddc, dra_err, ddc_err, ra_rad, dc_rad, ra_dc_cor=None):
"""Get a clean sample based on mask
Parameters
----------
mask : array of boolean
mask for extract data
dra/ddc : array of float
R.A.(*cos(Dec.))/Dec. differences
dra_err/ddc_err : array of float... | 70286c6134fb19833f6033c827bb2ab2cd26afb1 | 19,382 |
def holes_filler(arr_segm_with_holes, holes_label=-1, labels_sequence=(), verbose=1):
"""
Given a segmentation with holes (holes are specified by a special labels called holes_label)
the holes are filled with the closest labels around.
It applies multi_lab_segmentation_dilate_1_above_selected_label unti... | d008553591f1f1634aa1cf584c6639a12e8343a6 | 19,383 |
def isAbsolute(uri : str) -> bool:
""" Check whether a URI is Absolute. """
return uri is not None and uri.startswith('//') | 8597efe69ce82e80ee81beb9eb39754e90fcec28 | 19,384 |
from typing import Iterable
def token_converter(tokens: Iterable[str]) -> Iterable[str]:
"""Convert tokens."""
def convert(token: str) -> str:
return token.lower().replace("-", "_")
return map(convert, tokens) | 93bf2436c81091ec55b6a7a4d6d3fc728a68e093 | 19,385 |
def update_instance(instance, validated_data):
"""Update all the instance's fields specified in the validated_data"""
for key, value in validated_data.items():
setattr(instance, key, value)
return instance.save() | 2f4d5c4ec9e524cbe348a5efad9ecae27739b339 | 19,386 |
import scipy
def pupilresponse_nnls(tx, sy, event_onsets, fs, npar=10.1, tmax=930):
"""
Estimate single-event pupil responses based on canonical PRF (`pupil_kernel()`)
using non-negative least-squares (NNLS).
Parameters
-----------
tx : np.ndarray
time-vector in milliseco... | afa8e02d5f5d566c9ed287c039cae16a97f3e0bf | 19,387 |
def _eval_expression(
expression,
params,
x,
ind_var="x",
aux_params=None,
domain=DEFAULT_DOMAIN,
rng=DEFAULT_RANGE,
):
"""Evaluate the expression at x.
Parameters
----------
expression : string
The expression that defines the calibration function.
params : array... | 2a636268412346b8f55dce8b951cff97d12410eb | 19,388 |
def negative_frequency(P_m):
"""get the negative probability"""
sample_num = []
sample_prob = []
for key, value in P_m.items():
sample_num.append(key)
sample_prob.append(value)
return sample_num, np.array(sample_prob)/sum(sample_prob) | ad761b49b759ef28f721162e537419a1fe3fe40d | 19,389 |
import pipes
def _ShellQuote(command_part):
"""Escape a part of a command to enable copy/pasting it into a shell.
"""
return pipes.quote(command_part) | 31ccd5bd64de657cd3ac5c36c643e9f2f09f2318 | 19,390 |
import logging
def LogLEVEL(val):
"""
Return a sane loglevel given some value.
"""
if isinstance(val, (float, int)):
return int(val)
if isinstance(val, basestring):
return getattr(logging, val.upper())
return val | 5d6f096f5d9b8ac319ab3a8b73b978cb99775a9c | 19,391 |
def decoMakerApiCallChangePosToOptArg(argPos, argName):
""" creates a decorator, which change the positional argument ARGPOS into
an optional argument ARGNAME.
argPos=1 is the first positional arg
"""
# for understanding, what we are doing here please read
# # see http://sta... | 5f189c70efc45b9fa4b06f7eb650ad4b245cbf51 | 19,392 |
def wrangle_address_dist_matrix(ba_rel, ba_asso):
""" Get all buffer level derived variables based on "AH, Relatives and Associates" file
Note: we have some participants that list relatives but no associates (or vice versa), so we have to fill NA values
Keyword Arguments:
- ba_ba_comparison:
... | 5e586b5c8225f130868f1bce2586043f07c0c660 | 19,393 |
import math
def circlePoints(x, r, cx, cy):
"""Ther dunction returns the y coordinate of a
circonference's point
:x: x's coordinate value.
:r: length of the radius.
:cx: x coordinate of the center.
:cy: y coordinate of the center."""
return math.sqrt(math.pow(r,2) - math.pow(x-c... | c2cc14a845dccbcf62a38be3af69808024289adc | 19,394 |
import re
def get_thread_info():
"""
Returns a pair of:
- map of LWP -> thread ID
- map of blocked threads LWP -> potential mutex type
"""
# LWP -> thread ID
lwp_to_thread_id = {}
# LWP -> potential mutex type it is blocked on
blocked_threads = {}
output = gdb.execute("info t... | 36eecd0fc0fb7fc062035e087ef503d007c2c8cc | 19,395 |
def _maybe_convert_labels(y_true):
"""Converts binary labels into -1/1."""
are_zeros = math_ops.equal(y_true, 0)
are_ones = math_ops.equal(y_true, 1)
is_binary = math_ops.reduce_all(math_ops.logical_or(are_zeros, are_ones))
def _convert_binary_labels():
# Convert the binary labels to -1 or 1.
return ... | bfd37162587fe3cf7cd0fd311304e70042ebd626 | 19,396 |
import json
def create_plot(feature="bar"):
"""provided random generated plots"""
if feature == "bar":
N = 40
x = np.linspace(0, 1, N)
y = np.random.randn(N)
df = pd.DataFrame({'x': x, 'y': y}) # creating a sample dataframe
data = [
go.Bar(
... | 0d2d41e8b2a07f6a4aa3d1ade2311cea02c5a63b | 19,397 |
import torch
def get_gram_matrix(tensor):
"""
Returns a Gram matrix of dimension (distinct_filer_count, distinct_filter_count) where G[i,j] is the
inner product between the vectorised feature map i and j in layer l
"""
G = torch.mm(tensor, tensor.t())
return G | ad86f06768c07d6fe1ff509d996991f786ea1ffa | 19,398 |
def calc_stat_moments(ds, dim_aggregator='time', time_constraint=None):
"""Calculates the first two statistical moments and
the coefficient of variation in the specified dimension.
Parameters:
-----------
ds : xr.Dataset
dim_aggregator : str
coordinate to calculate the stati... | 67a18691b183803ab9f9b20f02e2e36397648f6f | 19,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.