content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def migrate(sig, tt, fsmp, lsmp, nsamp, map4d, threads):
"""
Wrapper for the C-compiled scan4d function: computes 4-D coalescence map
by back-migrating P and S onset functions.
Returns output by populating map4d.
Parameters
----------
sig : array-like
P and S onset functions
t... | 56,400 |
def deny_request( request_id ):
"""Denies a given request for slots
No request params.
"""
try:
req = SlotRequest.get( SlotRequest.id == request_id ).select().join( User ).first()
print(req)
g.user.deny_request( request_id )
rs = RadioStation.get()
send_mail( '{}... | 56,401 |
def make_env(rank, seed=0):
"""
Utility function for multiprocessed env.
:param env_id: (str) the environment ID
:param num_env: (int) the number of environments you wish to have in subprocesses
:param seed: (int) the inital seed for RNG
:param rank: (int) index of the subprocess
"""
de... | 56,402 |
def blur(img_array, blur_factor):
"""
Blur the image by Gaussian Blur,
and it has effects on every channel.
Recommend: int around 5.
"""
for i in range(3):
img_array[:, :, i] = ndimage.gaussian_filter(img_array[:, :, i], blur_factor)
return np.uint8(img_array) | 56,403 |
def add(a, b):
"""Adds two integers"""
return a + b | 56,404 |
def eprint(*args, **kwargs):
"""Print errors to stderr."""
print(*args, **kwargs, file=sys.stderr) | 56,405 |
def usmap(scenario,mode,yyyy,save='n'):
"""
scenario: 'base', 'bakken_rail_cap', 'US_midwest_pipelines', 'US_export_ban_lifted'
mode: 'Rail', 'Pipeline'
years: 2012, 2015, 2018
save: 'y', 'n'
"""
m = Basemap(width=12000000,height=7000000,
rsphere=(6378137.00,6356752.3142),\
resolution='l',area_thresh=1000.,p... | 56,406 |
def test_qubitop_to_paulisum():
"""
Conversion of QubitOperator; accuracy test
"""
hop_term = FermionOperator(((2, 1), (0, 0)))
term = hop_term + hermitian_conjugated(hop_term)
pauli_term = jordan_wigner(term)
forest_term = qubitop_to_pyquilpauli(pauli_term)
ground_truth = PauliTerm("X... | 56,407 |
def get_python_packages(Debug):
"""
Retrieves the version of the python packages installed in the system.
It retrieves the dependencies name conversion from file :file:`XICRA/config/python/module_dependencies.csv`
using function :func:`XICRA.config.extern_progs.file_list` and :func:`XICRA.scripts.functions.ma... | 56,408 |
def replace_space(string):
"""Replace all spaces in a word with `%20`."""
return re.sub(' ', '%20', string) | 56,409 |
def PRINT_NAME_VALUE(name, var):
"""
Print variable and variable name.
"""
print '{}: {}'.format(name, var) | 56,410 |
def remove(ctx, *args, **kwargs):
"""Alias for the 'delete' command"""
ctx.forward(delete) | 56,411 |
def _get_sitk_pixelid(numpy_array_type):
"""Returns a SimpleITK PixelID given a numpy array."""
if not HAVE_NUMPY:
raise ImportError('Numpy not available.')
# This is a Mapping from numpy array types to sitks pixel types.
_np_sitk = {numpy.character: sitkUInt8,
numpy.uint8: sit... | 56,412 |
def port_to_string(port):
"""
Returns clear number string containing port number.
:param port: port in integer (1234) or string ("1234/tcp") representation.
:return: port number as number string ("1234")
"""
port_type = type(port)
if port_type is int:
return str(port)
if port_typ... | 56,413 |
def get_s_macd(c: analyze.CZSC, di: int = 1) -> OrderedDict:
"""获取倒数第i根K线的MACD相关信号"""
freq: Freq = c.freq
s = OrderedDict()
k1 = str(freq.value)
k2 = f"倒{di}K"
default_signals = [
Signal(k1=k1, k2=k2, k3="DIF多空", v1="其他", v2='其他', v3='其他'),
Signal(k1=k1, k2=k2, k3="DIF方向", v1="其... | 56,414 |
def code_block(text: str, language: Optional[str] = None) -> str:
"""Creates a code block using HTML syntax. If language is given, then the code block will be
created using Markdown syntax, but it cannot be used inside a table.
:param text: The text inside the code block
:param language: The language t... | 56,415 |
def update_line_item_processing_result(
line_item_id: LineItemID, data: dict[str, Any]
) -> None:
"""Update the line item's processing result data."""
db_line_item = db.session.get(DbLineItem, line_item_id)
if db_line_item is None:
raise ValueError(f'Unknown line item ID "{line_item_id}"')
... | 56,416 |
def test_network(neural_network, input_window, input_max, test_location=None, test_class=None, submission=False):
"""Test the performance of the neural network classifier against known spikes classes."""
if submission:
# If submission flag, define the indices of submission data spikes and their classes... | 56,417 |
def not_found():
"""Page not found."""
return render_template('404.html') | 56,418 |
def run(material, simulation_config, config):
"""Runs gas loading simulation.
Args:
material_id (Material): material record.
Returns:
results (dict): gas loading simulation results.
"""
adsorbate = simulation_config["adsorbate"]
output_dir = "output_{}_{}".format(material.uuid... | 56,419 |
def generate_aes_256_key():
"""
This function generate a AES 256 bits long, using the package crypthography.
@param None
@return: (list[Key_of_AES,random_bytes_cbc,Obj_Cipher_AES]) return a 256 bytes AES key and object AES, or 0
"""
try:
key_dec_enc = os.urandom(32)
mode_vec = os.urandom(16)
backend = defau... | 56,420 |
def _histogram_binsize_weighted(a, w, start, width, n):
"""histogram_even_weighted(a, start, width, n) -> histogram
Return an histogram where the first bin counts the number of lower
outliers and the last bin the number of upper outliers. Works only with
fixed width bins.
:Stochastics:
a : a... | 56,421 |
def merge(line):
"""
Helper function that merges a single row or column in 2048
"""
result = list(line)
head = 0
i = 1
while (i < len(result)):
if (result[i] != 0):
if (result[head] == result[i]):
result[head] += result[i]
result[i] = 0
... | 56,422 |
def get_transcripts_from_tree(chrom, start, stop, cds_tree):
"""Uses cds tree to btain transcript IDs from genomic coordinates
chrom: (String) Specify chrom to use for transcript search.
start: (Int) Specify start position to use for transcript search.
stop: (Int) Specify ending position to use for tra... | 56,423 |
def parse_flattened_result_only_intent(to_parse):
"""
Parse out the belief state from the raw text.
Return an empty list if the belief state can't be parsed
Input:
- A single <str> of flattened result
e.g. 'User: Show me something else => Belief State : DA:REQUEST ...'
... | 56,424 |
def move_files(glob_search, destination_dir):
"""Moves files with 'glob_search' commonality to the directory
'destination_dir'.
Parameters
---------
glob_search : list of strings
Commonality between files you wish moved, e.g., 'png'.
Type what you normally would for a glob.glob sea... | 56,425 |
def update(*, db_session, user: DispatchUser, user_in: UserUpdate) -> DispatchUser:
"""Updates a user."""
user_data = jsonable_encoder(user)
update_data = user_in.dict(exclude={"password"}, skip_defaults=True)
for field in user_data:
if field in update_data:
setattr(user, field, upd... | 56,426 |
def cost_table(tea):
"""
Return a cost table as a pandas DataFrame object.
Parameters
----------
units : iterable[Unit]
Returns
-------
table : DataFrame
"""
columns = ('Unit operation',
'Purchase cost (10^6 USD)',
'Utility cost (10^6 USD... | 56,427 |
def test_three_commits_multiple_paths(local):
"""Test with two valid candidates and one ignored candidate.
:param local: conftest fixture.
"""
shas = {pytest.run(local, ['git', 'rev-parse', 'HEAD']).strip()}
pytest.run(local, ['git', 'checkout', 'feature'])
local.ensure('conf.py').write('pass\n... | 56,428 |
def embed_conformer(
mol, forcefield: str = "uff", num_conformer: int = 10, prune_tresh: float = 0.1
):
"""Use Riniker/Landrum conformer generator: https://pubs.acs.org/doi/10.1021/acs.jcim.5b00654"""
conf_generator = ConformerGenerator()
mol, _ = conf_generator.generate_conformers(mol)
return mol | 56,429 |
def process_command_line():
""" returns a 1-tuple of cli args
"""
parser = argparse.ArgumentParser(description='usage')
parser.add_argument('--config', dest='config', type=str, default='config.yaml',
help='config file for this experiment')
parser.add_argument('--test', dest=... | 56,430 |
def test_duration_min_inclusive004_1117_duration_min_inclusive004_1117_v(mode, save_output, output_format):
"""
TEST :Facet Schemas for string : (facet=minInclusive and
value=P1Y1MT1H and facet=maxInclusive and value=P2Y3MT2H) and document
value=P1Y2MT2H
"""
assert_bindings(
schema="msDa... | 56,431 |
def cleanup(self):
"""
Cleans up the table to gather all the cards back
"""
for player in self.players:
for card in player.hand:
self.deck.discard(card)
for card in self.table_cards:
self.deck.discard(card)
self.deck.shuffle_back()
... | 56,432 |
def setup_august(hass, config, api, authenticator, token_refresh_lock):
"""Set up the August component."""
authentication = None
try:
authentication = authenticator.authenticate()
except RequestException as ex:
_LOGGER.error("Unable to connect to August service: %s", str(ex))
h... | 56,433 |
def get_default_prms() -> dict:
""" Extract the default ampycloud parameters from the YAML configuration file. """
yaml = YAML(typ='safe')
out = yaml.load(Path(__file__).parent / 'prms' / 'ampycloud_default_prms.yml')
return out | 56,434 |
def GetEnvArgsForCommand(extra_vars=None, exclude_vars=None):
"""Return an env dict to be passed on command invocation."""
env = copy.deepcopy(os.environ)
env.update(DEFAULT_ENV_ARGS)
if extra_vars:
env.update(extra_vars)
if exclude_vars:
for k in exclude_vars:
env.pop(k)
return env | 56,435 |
def filter_row_by_data_type_audf(col_name, data_type):
"""
Filter a column using a Spark data type as reference
:param col_name:
:param data_type:
:return:
"""
data_type = parse_python_dtypes(data_type)
return abstract_udf(col_name, is_data_type, "boolean", data_type) | 56,436 |
def strip_outer_dollars(value):
"""Strip surrounding dollars signs from TeX string, ignoring leading and
trailing whitespace"""
if value is None:
return '{}'
value = value.strip()
m = re.match(r'^\$(.*)\$$', value)
if m is not None:
value = m.groups()[0]
return value | 56,437 |
def process_articles(article_results_list):
"""
Fuction that processes json result into a list
:return: a list of news articles
"""
articles=[]
for item in article_results_list:
id = item.get('id')
author = item.get('author')
title = item.get('title')
description ... | 56,438 |
async def test_http_path_is_not_escaped(mock_app):
"""
path (Unicode string) – HTTP request target excluding any query string, with percent-encoded
sequences and UTF-8 byte sequences decoded into characters.
https://asgi.readthedocs.io/en/latest/specs/www.html#websocket-connection-scope
Path is dec... | 56,439 |
def attrgetter_atom_split(tokens):
"""Split attrgetter_atom_tokens into (attr_or_method_name, method_args_or_none_if_attr)."""
if len(tokens) == 1: # .attr
return tokens[0], None
elif len(tokens) >= 2 and tokens[1] == "(": # .method(...
if len(tokens) == 2: # .method()
return ... | 56,440 |
def postgres(pg_preferred_versions, pytestconfig):
""" Starts a postgres server using `testing.postgresql \
<https://pypi.python.org/pypi/testing.postgresql/>`_ once per test session.
"""
if pytestconfig.getoption('nopg'):
yield None
return
postgres_args = ' '.join((
"-h 12... | 56,441 |
def pytest_funcarg__barcamps(request):
"""return the barcamp collection"""
config = request.getfuncargvalue("config")
return config.dbs.barcamps | 56,442 |
def stop_service(service_name):
"""Stops the given service by sending unix control signals to the process.
Waits for the process to stop before returning from the function.
Kills the process and any children processes if the process does not exit normally."""
service_pid = get_service_pid(service... | 56,443 |
def test_cancel_new_user_invalid_token(app, session):
"""Ensure the API returns an error for an invalid token."""
with app.test_client() as client:
# Register a new User
user_data = {
'email': 'test2@jadetree.io',
'password': 'aSecu43Pa55w0rd',
'name': 'Second... | 56,444 |
def test_atomic_normalized_string_enumeration_nistxml_sv_iv_atomic_normalized_string_enumeration_1_2(mode, save_output, output_format):
"""
Type atomic/normalizedString is restricted by facet enumeration.
"""
assert_bindings(
schema="nistData/atomic/normalizedString/Schema+Instance/NISTSchema-SV... | 56,445 |
def print_ofpt_flow_mod(msg):
"""
Args:
msg: OpenFlow message unpacked by python-openflow
"""
print_ofp_match(msg.match)
print_ofp_body(msg)
print_actions(msg.actions)
# Print OVS is deactivated for now
# print_ofp_ovs(msg) | 56,446 |
def add_to_path():
"""
This adds to PYTHONPATH various paths we need
If you disable this then templates would not be able to find things like 'config/python.py'
"""
add_import_of_cwd = True
add_import_of_home = True
add_import_of_shared = True
if add_import_of_shared:
folder = "/... | 56,447 |
def set_allow_shutdown(value):
"""Set if "shutdown" automatically calls the thread allow_shutdown."""
global ALLOW_SHUTDOWN
ALLOW_SHUTDOWN = value | 56,448 |
def mark_as_read(request, app_key, user_id):
"""
mark all unread notifications for that user, as read
"""
app = Application.objects.get(secret_key=app_key)
unreads = get_unread_logentry_list(app, user_id)
for log in unreads:
logentryread = LogEntryRead(app=app, log=log, user_id=user_id)
logentryread.save()
m... | 56,449 |
def build(params="parameters.json"):
"""
Creates all of the necessary directories.
Parameters
----------
`params` : `str`\n
String representation of the path to the json file containing the necessary parameters, by default `"parameters.json"`
"""
with open(params, "r") as f:
... | 56,450 |
def gauss(r, A, l):
"""Gaussian"""
return A * np.exp(-0.5 * (r / l) ** 2) | 56,451 |
def main():
""" Main point of execution."""
try:
root_sim_folder = sys.argv[1]
except Exception:
raise
else:
config = Configuration(root_sim_folder)
results = begin_all_sims(config)
save_results(results, os.path.join(root_sim_folder + 'rawResults.pkl'... | 56,452 |
def variability(model_variability, variable_list=None):
"""Perform thermodynamic variability analysis.
Determine the minimum and maximum values for the input variables (Flux, Gibbs free
energies and metabolite concentrations). if min_growth constraint is applied then
growth is maintained at given perce... | 56,453 |
def tabuleiro_inicial():
"""
tabuleiro_inicial: {} >>> tabuleiro
- Um "mirror" para a funcao "str_para_tabuleiro" com um valor especifico. Devolve sempre o mesmo tabuleiro.
"""
return str_para_tabuleiro("((-1, -1, -1), (0, 0, -1), (0, -1))") | 56,454 |
def create_processor_names_for_branch_action(processor_name, processors_to_add, seff, mapping_cache):
"""
If current seff contains a BranchAction, check if copying processor is required, if true: create corresponding
processor names and add to processors_to_add. If branch action does not require creation of... | 56,455 |
def fake_connect(self, address, port, send_trace=False):
"""
Creates fake connection.
Mocks the connection so no call would leave this environment, also makes application faster for tests.
Args:
self: the instance of the calling object
address: address used for connecting to server
... | 56,456 |
def test_valid_matrix_square_root(A_dd: np.ndarray, L_dd: np.ndarray):
"""Assert that the resulting Cholesky factor right-multiplied with its transpose
is (up to numerical imprecisions) equal to the updated matrix, i.e. that the
Cholesky factor is a valid matrix square root"""
np.testing.assert_allclose... | 56,457 |
def cast_to_scalar_tensor_of_dtype(t, dtype):
"""If not yet a tensor, casts it to a constant scalar tensor."""
if issubclass(type(t), ops.Tensor):
return t
return array_ops.constant(t, shape=[], dtype=dtype) | 56,458 |
def menu_select(title='~ Untitled Menu ~', main_entries=[], action_entries=[], prompt='Please make a selection', secret_exit=False):
"""Display options in a menu for user selection"""
# Bail early
if (len(main_entries) + len(action_entries) == 0):
raise Exception("MenuError: No items given")
... | 56,459 |
def download_sample(image_blob: str, annotation_blob: str,
sample_id: str, directory_path: str,
force_refresh: bool = False) -> None:
"""Download image and json for a given sample id"""
image_local_path = get_image_local_path(sample_id, directory_path)
json_local_path... | 56,460 |
def plot_stacked_bar_chart(data, series_labels, col_labels=None, x_label=None, y_label=None, log_scale=False):
"""
For plotting e.g. species distribution across locations.
Reference: https://stackoverflow.com/questions/44309507/stacked-bar-plot-using-matplotlib
Args:
data: a 2-dimensional numpy ... | 56,461 |
def assert_minimum_rank(inputs, rank: int):
"""Asserts the rank of the input is at least `rank`."""
if inputs.ndim < rank:
raise ValueError("Input %r must have rank >= %d" % (inputs, rank)) | 56,462 |
def check_is_admin(roles):
"""Whether or not roles contains 'admin' role according to policy setting.
"""
init()
return policy.check('context_is_admin', {}, {'roles': roles}) | 56,463 |
def merge_requirements(
requirements: Sequence[Tuple[Feature, Requirements]]
) -> Tuple[Feature, Requirements]:
"""Determine the lowest common denominator in the given requirements."""
if len(requirements) == 1:
return requirements[0][0], requirements[0][1]
first = requirements[0][1]
others... | 56,464 |
def resource_data_get_all(resource, data=None):
"""
Looks up resource_data by resource.id. If data is encrypted,
this method will decrypt the results.
"""
if data is None:
data = (model_query(resource.context, models.ResourceData)
.filter_by(resource_id=resource.id))
if... | 56,465 |
def setup_db(db, dims, measures, scale=50, bcsv=True, bdb=True):
"""
Generate CSV file and load into psotgres database
@dims list of dimension attribute names and their values [(attr, [vals...]), ...]
@measures list of attribute names, we will generate random numbers for them
@scale number of tuples per dim ... | 56,466 |
def setig():
"""The
"""
return load(_os.path.join("npc", "setig.csv")) | 56,467 |
def does_file_exist(file, proj_dir):
"""Determine if a file in our persistent data still exist.
If file is not absolute, will check if relative from the project directory exists.
Args:
file (str): Relative or absolute file path to check the existence of
proj_dir (str): Project path to resolv... | 56,468 |
def training_status(ctx, apikey, url, skill_name):
"""
Return the training status of a skill
"""
id = wa.workspace_id_from_skill_name(apikey, url, skill_name)
if not id:
click.echo('Non Existent')
else:
click.echo(wa.get_skill_status(apikey, url, id)) | 56,469 |
def all_users(request, db, user):
"""Yield all user types for the tests."""
u = user(username=request.param, account_type=request.param)
db.session.add(u)
db.session.commit()
yield u
db.session.delete(u)
db.session.commit() | 56,470 |
def serialize(model, data, fields=None, exc: Optional[set] = None, rels=None, root=None, exclude=None, functions=None,
**kwargs):
"""
This utility function dynamically converts Alchemy model classes into a
dict using introspective lookups. This saves on manually mapping each
model and all ... | 56,471 |
def interval(
value: int | datetime.timedelta | None = None,
unit: str = 's',
years: int | None = None,
quarters: int | None = None,
months: int | None = None,
weeks: int | None = None,
days: int | None = None,
hours: int | None = None,
minutes: int | None = None,
seconds: int | ... | 56,472 |
def numpy_product(quat0, quat1):
"""Returns the quaternion product of q0 and q1."""
quat = np.zeros(4)
x0, y0, z0, w0 = quat0[0], quat0[1], quat0[2], quat0[3]
x1, y1, z1, w1 = quat1[0], quat1[1], quat1[2], quat1[3]
quat[0] = w0*x1 + x0*w1 + y0*z1 - z0*y1
quat[1] = w0*y1 - x0*z1 + y0*w1 + z0*x1
... | 56,473 |
def estimate_price(mileage, theta0, theta1):
"""
Estimate price function:
"""
return theta0 + theta1 * mileage | 56,474 |
def run(dataset):
"""Task 1 - Choose the best configuration from week 2
Performs a grid search for hyperparameter selection in background
estimation with adaptive model. The criterium to choose the best model is
the highest F-score.
"""
# Hyperparameters values to test
if dataset == 'highw... | 56,475 |
def init_axis(title = '', geometry = ''):
"""
Initializes plotting area and returns a handle for plot area
:param None:
:return: Axis object
"""
fig = plt.figure()
ax = fig.add_subplot(111)
plt.axis("equal")
mngr = plt.get_current_fig_manager()
#mngr.window.setGeometry(50,100,640, 545)
mngr.window.wm_geome... | 56,476 |
def similar_date(anon, obj, field, val):
"""
Returns a date that is within plus/minus two years of the original date
"""
return anon.faker.date(field=field, val=val) | 56,477 |
def launch_request_handler(handler_input):
"""Handler for Skill Launch."""
return launch_request(handler_input) | 56,478 |
def flush(bank, key=None):
"""
Remove the key from the cache bank with all the key content.
"""
_init_client()
if key is None:
etcd_key = "{}/{}".format(path_prefix, bank)
tstamp_key = None
else:
etcd_key = "{}/{}/{}".format(path_prefix, bank, key)
tstamp_key = "{... | 56,479 |
def test_convert_to_policy_invalid(empty_nodl_path):
"""Test NoDL conversion with an invalid path."""
with pytest.raises(nodl.errors.NoDLError) as _:
policy.convert_to_policy(
nodl_description=nodl.parse(empty_nodl_path)) | 56,480 |
def tweetDiv(tweet):
"""View text of tweet"""
res = '<div class="panel"><div class="header"><img src="'
res = res + tweet['user']['profile_image_url']
res = res + '" ><div class="text">'
res = res + tweet['user']['name']
res = res + '</div></div><p><small><small>'
res = res + tweet['created_... | 56,481 |
def variable_like(inputs: Union[tf.Tensor, tf.Variable],
initializer: initializers.Initializer = initializers.Zeros(),
trainable: Optional[bool] = None,
name: Optional[str] = None) -> tf.Variable:
"""Creates a new variable with the same shape/dtype/device as the i... | 56,482 |
def make_signing_service(config, entity_id):
"""
Given configuration initiate a SigningService instance
:param config: The signing service configuration
:param entity_id: The entity identifier
:return: A SigningService instance
"""
_args = dict([(k, v) for k, v in config.items() if k in KJ... | 56,483 |
def fsum(iterable):
"""fsum(iterable)
Return an accurate floating point sum of values in the iterable.
"""
return reduce(Add, iterable) | 56,484 |
def structure_sampling_values(graph, centrality, function):
""" helper function to compute the centrality values for an edge"""
cent = centrality.get_values(graph)
edges = graph.get_edges()
left_values =cent[edges[:,0]]
right_values=cent[edges[:,1]]
values = function(left_values, right_values)
... | 56,485 |
def user_import(localpart, domain_name, password_hash, hash_scheme=app.config['PASSWORD_SCHEME']):
""" Import a user along with password hash. Available hashes:
'SHA512-CRYPT'
'SHA256-CRYPT'
'MD5-CRYPT'
'CRYPT'
"""
domain = models.D... | 56,486 |
def act_hungry():
"""Makes the puppy act hungry."""
#Replaced HURT eyes with AWAKE
ev3.screen.show_image(ImageFile.AWAKE)
#puppy sits down
left_leg_motor.run(-50)
right_leg_motor.run(-50)
wait(1000)
left_leg_motor.stop()
right_leg_motor.stop()
wait(100)
ev3.speaker.play_file(... | 56,487 |
def riglob(path: Path, pattern: str = None, regex: Union[str, PTYPE] = None, files=True, directories=True):
"""same as Path.rglob method, but instead match on given pattern or regex, case-insensitively, and filtering on
path type (file and / or directory
If a compiled regex is provided, the case-sensitivity... | 56,488 |
def convert_range(g, op, block):
"""Operator converter for range."""
start = g.get_node(op.input('Start')[0])
end = g.get_node(op.input('End')[0])
step = g.get_node(op.input('Step')[0])
out_name = op.output('Out')[0]
out_dtype = block.var(out_name).dtype
out_dtype = str(out_dtype).strip().... | 56,489 |
def nation_not_found_popup(nation_name:str):
"""
Produce a pop-up warning the end-user that the lookup was unable to find a nation with a matching name.
Args:
nation_name (str): The string
Returns:
"""
pu_title = f'Nation Not Found | "{nation_name}"'
alerting = False... | 56,490 |
def get_all(isamAppliance, check_mode=False, force=False):
"""
Get information on all existing Transactions
"""
return isamAppliance.invoke_get("Retrieving a list of transactions", "{0}".format(module_uri),
requires_modules=requires_modules, requires_version=requires_... | 56,491 |
def main():
""" main function with Traintask in localfc mode, which means each worker has a full classifier
"""
task_dir = os.path.dirname(os.path.abspath(__file__))
task = TrainTask(os.path.join(task_dir, 'train_config.yaml'))
task.init_env()
task.train() | 56,492 |
def get_naive_affinities(raw, offsets):
"""get naive pixel affinities based on differences in pixel intensities."""
affinities = []
for i, off in enumerate(offsets):
rolled = np.roll(raw, tuple(-np.array(off)), (0, 1))
dist = np.linalg.norm(raw - rolled, axis=-1)
affinities.append(di... | 56,493 |
def generallaplacian(W, G=None):
"""
Compute the general laplacian of graph.
Parameters:
- - - - -
W: float, array
weight adjacency matrix
Returns:
- - - -
L: float, sparse array
surface mesh Laplacian matrix
"""
[D, Dinv] = degree(W)
n = D.shape[0]
i... | 56,494 |
def dummy_wrapper(fn):
"""Simple wrapper used for testing"""
def _run_callable(*args, **kwargs):
return fn(*args, **kwargs)
return _run_callable | 56,495 |
def _validate_privatekey_pem(key_pem):
"""Implement private key validation.
Args:
key_pem (str): RSA PKCS#8 PEM private key (traditional OpenSSL format)
of at least 2048 bit strength.
"""
assert isinstance(key_pem, str)
# Create the cryptography package private key object and p... | 56,496 |
def integrate(func,a,b):
"""
Wrapper for definite integration using scipy.integrate.quad().
"""
## calculate integral and error
val, abserr = spint.quad(func,a,b, limit=100)
## get relative error
relerr = np.nan
if val != 0:
relerr = np.abs(abserr/val)
## warning parameters
maxrel, maxabs = 1e-4, 1e-6
## e... | 56,497 |
def get_backlinks(dictionary):
"""
Returns a reversed self-mapped dictionary
@param dictionary: the forwardlinks
"""
o = dict()
for key, values in dictionary.items():
try:
for v in values:
try:
o[v].add(key)
except KeyE... | 56,498 |
def shift_date(date_str, n):
"""
:param date_str: 日期, 'YYYYMMDD'格式的字符串
:param n: 时间跨度, int
:return: 调整后的交易日,date
"""
tc = ts.util.dateu.trade_cal()
tc = tc[tc.isOpen == 1]
tc.set_index('calendarDate', inplace=True)
if len(tc[:date_str]) < n:
return tc.iloc[0].name
else... | 56,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.