hexsha
stringlengths
40
40
size
int64
3
1.03M
ext
stringclasses
10 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
972
max_stars_repo_name
stringlengths
6
130
max_stars_repo_head_hexsha
stringlengths
40
78
max_stars_repo_licenses
listlengths
1
10
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
972
max_issues_repo_name
stringlengths
6
130
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
10
max_issues_count
int64
1
116k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
972
max_forks_repo_name
stringlengths
6
130
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
10
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
3
1.03M
avg_line_length
float64
1.13
941k
max_line_length
int64
2
941k
alphanum_fraction
float64
0
1
40cdb6d00dede9b1cde10c8048300ae6845d230b
3,288
py
Python
jina/excepts.py
abellimz/jina
010789331ce896ffcaea897402d698944f1a9d40
[ "Apache-2.0" ]
null
null
null
jina/excepts.py
abellimz/jina
010789331ce896ffcaea897402d698944f1a9d40
[ "Apache-2.0" ]
null
null
null
jina/excepts.py
abellimz/jina
010789331ce896ffcaea897402d698944f1a9d40
[ "Apache-2.0" ]
null
null
null
"""This modules defines all kinds of exceptions raised in Jina.""" class NoExplicitMessage(Exception): """Waiting until all partial messages are received.""" class ChainedPodException(Exception): """Chained exception from the last Pod.""" class MismatchedVersion(SystemError): """When the jina version info of the incoming message does not match the local Jina version.""" class ExecutorFailToLoad(SystemError): """When the executor can not be loaded in pea/pod.""" class RuntimeFailToStart(SystemError): """When pea/pod is failed to started.""" class MemoryOverHighWatermark(Exception): """When the memory usage is over the defined high water mark.""" class NoAvailablePortError(Exception): """When no available random port could be found""" class RuntimeTerminated(KeyboardInterrupt): """The event loop of BasePea ends.""" class UnknownControlCommand(RuntimeError): """The control command received can not be recognized.""" class FlowTopologyError(Exception): """Flow exception when the topology is ambiguous.""" class FlowMissingPodError(Exception): """Flow exception when a pod can not be found in the flow.""" class FlowBuildLevelError(Exception): """Flow exception when required build level is higher than the current build level.""" class BadConfigSource(FileNotFoundError): """The yaml config file is bad, not loadable or not exist.""" class BadClient(Exception): """A wrongly defined client, can not communicate with jina server correctly.""" class BadClientCallback(BadClient): """Error in the callback function on the client side.""" class BadClientInput(BadClient): """Error in the request generator function on the client side.""" class ModelCheckpointNotExist(FileNotFoundError): """Exception to raise for executors depending on pretrained model files when they do not exist.""" class PretrainedModelFileDoesNotExist(ModelCheckpointNotExist): """Depreciated, used in the hub executors. TODO: to be removed after hub executors uses ModelCheckpointNotExist """ class HubBuilderError(Exception): """Base exception to raise when :command:`jina hub build` fails.""" class BadDocType(TypeError): """Exception when can not construct a document from the given data.""" class BadRequestType(TypeError): """Exception when can not construct a request object from given data.""" class BadNamedScoreType(TypeError): """Exception when can not construct a named score from the given data.""" class BadImageNameError(Exception): """Exception when an image name can not be found either local & remote""" class BadFlowYAMLVersion(Exception): """Exception when Flow YAML config specifies a wrong version number.""" class DaemonConnectivityError(Exception): """Exception to raise when jina daemon is not connectable.""" class NotSupportedError(Exception): """Exeception when user accidentally using a retired argument.""" class ValidationError(Exception): """Raised when a certain validation cannot be completed.""" class SocketTypeError(Exception): """Raised when such socket type is not supported or does not exist.""" class RoutingTableCyclicError(Exception): """Raised when the routing graph has cycles."""
27.173554
102
0.742092
4dfd8ca5cab13273dbd085d07f4d8fdb406d2fbc
4,268
py
Python
nnunet/experiment_planning/summarize_plans.py
gasperpodobnik/nnUNet
f11906b13344db9f54e303378748a0defdea8331
[ "Apache-2.0" ]
null
null
null
nnunet/experiment_planning/summarize_plans.py
gasperpodobnik/nnUNet
f11906b13344db9f54e303378748a0defdea8331
[ "Apache-2.0" ]
null
null
null
nnunet/experiment_planning/summarize_plans.py
gasperpodobnik/nnUNet
f11906b13344db9f54e303378748a0defdea8331
[ "Apache-2.0" ]
null
null
null
# Copyright 2020 Division of Medical Image Computing, German Cancer Research Center (DKFZ), Heidelberg, Germany # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from batchgenerators.utilities.file_and_folder_operations import * from nnunet.paths import preprocessing_output_dir # This file is intended to double check nnUNets design choices. It is intended to be used for developent purposes only def summarize_plans(file): plans = load_pickle(file) print("num_classes: ", plans['num_classes']) print("modalities: ", plans['modalities']) print("use_mask_for_norm", plans['use_mask_for_norm']) print("keep_only_largest_region", plans['keep_only_largest_region']) print("min_region_size_per_class", plans['min_region_size_per_class']) print("min_size_per_class", plans['min_size_per_class']) print("normalization_schemes", plans['normalization_schemes']) print("stages...\n") for i in range(len(plans['plans_per_stage'])): print("stage: ", i) print(plans['plans_per_stage'][i]) print("") def write_plans_to_file(f, plans_file): print(plans_file) a = load_pickle(plans_file) stages = list(a['plans_per_stage'].keys()) stages.sort() for stage in stages: patch_size_in_mm = [i * j for i, j in zip(a['plans_per_stage'][stages[stage]]['patch_size'], a['plans_per_stage'][stages[stage]]['current_spacing'])] median_patient_size_in_mm = [i * j for i, j in zip(a['plans_per_stage'][stages[stage]]['median_patient_size_in_voxels'], a['plans_per_stage'][stages[stage]]['current_spacing'])] f.write(plans_file.split("/")[-2]) f.write(";%s" % plans_file.split("/")[-1]) f.write(";%d" % stage) f.write(";%s" % str(a['plans_per_stage'][stages[stage]]['batch_size'])) f.write(";%s" % str(a['plans_per_stage'][stages[stage]]['num_pool_per_axis'])) f.write(";%s" % str(a['plans_per_stage'][stages[stage]]['patch_size'])) f.write(";%s" % str([str("%03.2f" % i) for i in patch_size_in_mm])) f.write(";%s" % str(a['plans_per_stage'][stages[stage]]['median_patient_size_in_voxels'])) f.write(";%s" % str([str("%03.2f" % i) for i in median_patient_size_in_mm])) f.write(";%s" % str([str("%03.2f" % i) for i in a['plans_per_stage'][stages[stage]]['current_spacing']])) f.write(";%s" % str([str("%03.2f" % i) for i in a['plans_per_stage'][stages[stage]]['original_spacing']])) f.write(";%s" % str(a['plans_per_stage'][stages[stage]]['pool_op_kernel_sizes'])) f.write(";%s" % str(a['plans_per_stage'][stages[stage]]['conv_kernel_sizes'])) f.write(";%s" % str(a['data_identifier'])) f.write("\n") if __name__ == "__main__": base_dir = './'#preprocessing_output_dir'' task_dirs = [i for i in subdirs(base_dir, join=False, prefix="Task") if i.find("BrainTumor") == -1 and i.find("MSSeg") == -1] print("found %d tasks" % len(task_dirs)) with open("2019_02_06_plans_summary.csv", 'w') as f: f.write("task;plans_file;stage;batch_size;num_pool_per_axis;patch_size;patch_size(mm);median_patient_size_in_voxels;median_patient_size_in_mm;current_spacing;original_spacing;pool_op_kernel_sizes;conv_kernel_sizes\n") for t in task_dirs: print(t) tmp = join(base_dir, t) plans_files = [i for i in subfiles(tmp, suffix=".pkl", join=False) if i.find("_plans_") != -1 and i.find("Dgx2") == -1] for p in plans_files: write_plans_to_file(f, join(tmp, p)) f.write("\n")
53.35
226
0.638472
f717772bd33c93521c158ce38b78042fe52c2ff5
52
py
Python
subjects/__init__.py
ankit0tech/Research-Productivity-Tool
c08e39daaaa8dfa08f5eb2607986d9f6bf9f02fa
[ "MIT" ]
1
2021-12-12T04:54:05.000Z
2021-12-12T04:54:05.000Z
subjects/__init__.py
ankit0tech/Research-Productivity-Tool
c08e39daaaa8dfa08f5eb2607986d9f6bf9f02fa
[ "MIT" ]
null
null
null
subjects/__init__.py
ankit0tech/Research-Productivity-Tool
c08e39daaaa8dfa08f5eb2607986d9f6bf9f02fa
[ "MIT" ]
null
null
null
default_app_config = 'subjects.apps.SubjectsConfig'
26
51
0.846154
fa3467138c2dedfd7822639a059eb8f809d1a844
870
py
Python
Python/Algorithms/937.py
DimitrisJim/leetcode_solutions
765ea578748f8c9b21243dec9dc8a16163e85c0c
[ "Unlicense" ]
2
2021-01-15T17:22:54.000Z
2021-05-16T19:58:02.000Z
Python/Algorithms/937.py
DimitrisJim/leetcode_solutions
765ea578748f8c9b21243dec9dc8a16163e85c0c
[ "Unlicense" ]
null
null
null
Python/Algorithms/937.py
DimitrisJim/leetcode_solutions
765ea578748f8c9b21243dec9dc8a16163e85c0c
[ "Unlicense" ]
null
null
null
class Solution: def reorderLogFiles(self, logs): # special case, empty or logs with 1 log. if len(logs) < 2: return logs # bring these in local scope. digit, letter, join = ( str.isdigit, str.isalpha, " ".join ) # Split beforehand in order to not split constantly. # Build arrays of digit and letter rows. Digit rows # stay as they are. logs_tr = list(map(str.split, logs)) d_rows = [join(i) for i in logs_tr if digit(i[1][0])] l_rows = [i for i in logs_tr if letter(i[1][0])] # Sort l_rows, add identifier to end in order to act as # tiebraker if needed. l_rows.sort(key=lambda x: join([join(x[1:]), x[0]])) # Extend with d_rows and return return [*map(join, l_rows), *d_rows]
33.461538
63
0.548276
13288891f8065b5378e2bd56b45741bf481d26cd
6,269
py
Python
src/python/pants/init/extension_loader.py
bastianwegge/pants
43f0b90d41622bee0ed22249dbaffb3ff4ad2eb2
[ "Apache-2.0" ]
null
null
null
src/python/pants/init/extension_loader.py
bastianwegge/pants
43f0b90d41622bee0ed22249dbaffb3ff4ad2eb2
[ "Apache-2.0" ]
16
2022-01-13T10:40:30.000Z
2022-03-30T10:20:44.000Z
src/python/pants/init/extension_loader.py
ryanking/pants
e45b00d2eb467b599966bca262405a5d74d27bdd
[ "Apache-2.0" ]
null
null
null
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). import importlib import traceback from typing import Dict, List, Optional from pkg_resources import Requirement, WorkingSet from pants.base.exceptions import BackendConfigurationError from pants.build_graph.build_configuration import BuildConfiguration from pants.goal.builtins import register_builtin_goals from pants.util.ordered_set import FrozenOrderedSet class PluginLoadingError(Exception): pass class PluginNotFound(PluginLoadingError): pass class PluginLoadOrderError(PluginLoadingError): pass def load_backends_and_plugins( plugins: List[str], working_set: WorkingSet, backends: List[str], bc_builder: Optional[BuildConfiguration.Builder] = None, ) -> BuildConfiguration: """Load named plugins and source backends. :param plugins: v2 plugins to load. :param working_set: A pkg_resources.WorkingSet to load plugins from. :param backends: v2 backends to load. :param bc_builder: The BuildConfiguration (for adding aliases). """ bc_builder = bc_builder or BuildConfiguration.Builder() load_build_configuration_from_source(bc_builder, backends) load_plugins(bc_builder, plugins, working_set) register_builtin_goals(bc_builder) return bc_builder.create() def load_plugins( build_configuration: BuildConfiguration.Builder, plugins: List[str], working_set: WorkingSet, ) -> None: """Load named plugins from the current working_set into the supplied build_configuration. "Loading" a plugin here refers to calling registration methods -- it is assumed each plugin is already on the path and an error will be thrown if it is not. Plugins should define their entrypoints in the `pantsbuild.plugin` group when configuring their distribution. Like source backends, the `build_file_aliases`, and `register_goals` methods are called if those entry points are defined. * Plugins are loaded in the order they are provided. * This is important as loading can add, remove or replace existing tasks installed by other plugins. If a plugin needs to assert that another plugin is registered before it, it can define an entrypoint "load_after" which can return a list of plugins which must have been loaded before it can be loaded. This does not change the order or what plugins are loaded in any way -- it is purely an assertion to guard against misconfiguration. :param build_configuration: The BuildConfiguration (for adding aliases). :param plugins: A list of plugin names optionally with versions, in requirement format. eg ['widgetpublish', 'widgetgen==1.2']. :param working_set: A pkg_resources.WorkingSet to load plugins from. """ loaded: Dict = {} for plugin in plugins or []: req = Requirement.parse(plugin) dist = working_set.find(req) if not dist: raise PluginNotFound(f"Could not find plugin: {req}") entries = dist.get_entry_map().get("pantsbuild.plugin", {}) if "load_after" in entries: deps = entries["load_after"].load()() for dep_name in deps: dep = Requirement.parse(dep_name) if dep.key not in loaded: raise PluginLoadOrderError(f"Plugin {plugin} must be loaded after {dep}") if "target_types" in entries: target_types = entries["target_types"].load()() build_configuration.register_target_types(req.key, target_types) if "build_file_aliases" in entries: aliases = entries["build_file_aliases"].load()() build_configuration.register_aliases(aliases) if "rules" in entries: rules = entries["rules"].load()() build_configuration.register_rules(req.key, rules) loaded[dist.as_requirement().key] = dist def load_build_configuration_from_source( build_configuration: BuildConfiguration.Builder, backends: List[str] ) -> None: """Installs pants backend packages to provide BUILD file symbols and cli goals. :param build_configuration: The BuildConfiguration (for adding aliases). :param backends: An list of packages to load v2 backends from. :raises: :class:``pants.base.exceptions.BuildConfigurationError`` if there is a problem loading the build configuration. """ backend_packages = FrozenOrderedSet(["pants.core", "pants.backend.project_info", *backends]) for backend_package in backend_packages: load_backend(build_configuration, backend_package) def load_backend(build_configuration: BuildConfiguration.Builder, backend_package: str) -> None: """Installs the given backend package into the build configuration. :param build_configuration: the BuildConfiguration to install the backend plugin into. :param backend_package: the package name containing the backend plugin register module that provides the plugin entrypoints. :raises: :class:``pants.base.exceptions.BuildConfigurationError`` if there is a problem loading the build configuration. """ backend_module = backend_package + ".register" try: module = importlib.import_module(backend_module) except ImportError as ex: traceback.print_exc() raise BackendConfigurationError(f"Failed to load the {backend_module} backend: {ex!r}") def invoke_entrypoint(name): entrypoint = getattr(module, name, lambda: None) try: return entrypoint() except TypeError as e: traceback.print_exc() raise BackendConfigurationError( f"Entrypoint {name} in {backend_module} must be a zero-arg callable: {e!r}" ) target_types = invoke_entrypoint("target_types") if target_types: build_configuration.register_target_types(backend_package, target_types) build_file_aliases = invoke_entrypoint("build_file_aliases") if build_file_aliases: build_configuration.register_aliases(build_file_aliases) rules = invoke_entrypoint("rules") if rules: build_configuration.register_rules(backend_package, rules)
40.707792
102
0.720211
f5d5f8b676cf14f9dfddbddc2a42154aca061b02
7,752
py
Python
pipeline/templatetags/pipeline.py
mhl/django-pipeline
2f983772fa12c861cee8cb170c7f67b2a7973eff
[ "MIT" ]
null
null
null
pipeline/templatetags/pipeline.py
mhl/django-pipeline
2f983772fa12c861cee8cb170c7f67b2a7973eff
[ "MIT" ]
null
null
null
pipeline/templatetags/pipeline.py
mhl/django-pipeline
2f983772fa12c861cee8cb170c7f67b2a7973eff
[ "MIT" ]
null
null
null
import logging import subprocess from django.contrib.staticfiles.storage import staticfiles_storage from django import template from django.template.base import Context, VariableDoesNotExist from django.template.loader import render_to_string from django.utils.safestring import mark_safe from ..collector import default_collector from ..conf import settings from ..exceptions import CompilerError from ..packager import Packager, PackageNotFound from ..utils import guess_type logger = logging.getLogger(__name__) register = template.Library() class PipelineMixin(object): request = None _request_var = None @property def request_var(self): if not self._request_var: self._request_var = template.Variable('request') return self._request_var def package_for(self, package_name, package_type): package = { 'js': getattr(settings, 'JAVASCRIPT', {}).get(package_name, {}), 'css': getattr(settings, 'STYLESHEETS', {}).get(package_name, {}), }[package_type] if package: package = {package_name: package} packager = { 'js': Packager(css_packages={}, js_packages=package), 'css': Packager(css_packages=package, js_packages={}), }[package_type] return packager.package_for(package_type, package_name) def render(self, context): try: self.request = self.request_var.resolve(context) except VariableDoesNotExist: pass def render_compressed(self, package, package_name, package_type): """Render HTML for the package. If ``PIPELINE_ENABLED`` is ``True``, this will render the package's output file (using :py:meth:`render_compressed_output`). Otherwise, this will render the package's source files (using :py:meth:`render_compressed_sources`). Subclasses can override this method to provide custom behavior for determining what to render. """ if settings.PIPELINE_ENABLED: return self.render_compressed_output(package, package_name, package_type) else: return self.render_compressed_sources(package, package_name, package_type) def render_compressed_output(self, package, package_name, package_type): """Render HTML for using the package's output file. Subclasses can override this method to provide custom behavior for rendering the output file. """ method = getattr(self, f'render_{package_type}') return method(package, package.output_filename) def render_compressed_sources(self, package, package_name, package_type): """Render HTML for using the package's list of source files. Each source file will first be collected, if ``PIPELINE_COLLECTOR_ENABLED`` is ``True``. If there are any errors compiling any of the source files, an ``SHOW_ERRORS_INLINE`` is ``True``, those errors will be shown at the top of the page. Subclasses can override this method to provide custom behavior for rendering the source files. """ if settings.PIPELINE_COLLECTOR_ENABLED: default_collector.collect(self.request) packager = Packager() method = getattr(self, f'render_individual_{package_type}') try: paths = packager.compile(package.paths) except CompilerError as e: if settings.SHOW_ERRORS_INLINE: method = getattr(self, f'render_error_{package_type}') return method(package_name, e) else: raise templates = packager.pack_templates(package) return method(package, paths, templates=templates) def render_error(self, package_type, package_name, e): return render_to_string('pipeline/compile_error.html', { 'package_type': package_type, 'package_name': package_name, 'command': subprocess.list2cmdline(e.command), 'errors': e.error_output, }) class StylesheetNode(PipelineMixin, template.Node): def __init__(self, name): self.name = name def render(self, context): super(StylesheetNode, self).render(context) package_name = template.Variable(self.name).resolve(context) try: package = self.package_for(package_name, 'css') except PackageNotFound: logger.warn("Package %r is unknown. Check PIPELINE['STYLESHEETS'] in your settings.", package_name) return '' # fail silently, do not return anything if an invalid group is specified return self.render_compressed(package, package_name, 'css') def render_css(self, package, path): template_name = package.template_name or "pipeline/css.html" context = package.extra_context context.update({ 'type': guess_type(path, 'text/css'), 'url': mark_safe(staticfiles_storage.url(path)) }) return render_to_string(template_name, context) def render_individual_css(self, package, paths, **kwargs): tags = [self.render_css(package, path) for path in paths] return '\n'.join(tags) def render_error_css(self, package_name, e): return super(StylesheetNode, self).render_error( 'CSS', package_name, e) class JavascriptNode(PipelineMixin, template.Node): def __init__(self, name): self.name = name def render(self, context): super(JavascriptNode, self).render(context) package_name = template.Variable(self.name).resolve(context) try: package = self.package_for(package_name, 'js') except PackageNotFound: logger.warn("Package %r is unknown. Check PIPELINE['JAVASCRIPT'] in your settings.", package_name) return '' # fail silently, do not return anything if an invalid group is specified return self.render_compressed(package, package_name, 'js') def render_js(self, package, path): template_name = package.template_name or "pipeline/js.html" context = package.extra_context context.update({ 'type': guess_type(path, 'text/javascript'), 'url': mark_safe(staticfiles_storage.url(path)) }) return render_to_string(template_name, context) def render_inline(self, package, js): context = package.extra_context context.update({ 'source': js }) return render_to_string("pipeline/inline_js.html", context) def render_individual_js(self, package, paths, templates=None): tags = [self.render_js(package, js) for js in paths] if templates: tags.append(self.render_inline(package, templates)) return '\n'.join(tags) def render_error_js(self, package_name, e): return super(JavascriptNode, self).render_error( 'JavaScript', package_name, e) @register.tag def stylesheet(parser, token): try: tag_name, name = token.split_contents() except ValueError: raise template.TemplateSyntaxError('%r requires exactly one argument: the name of a group in the PIPELINE.STYLESHEETS setting' % token.split_contents()[0]) return StylesheetNode(name) @register.tag def javascript(parser, token): try: tag_name, name = token.split_contents() except ValueError: raise template.TemplateSyntaxError('%r requires exactly one argument: the name of a group in the PIPELINE.JAVASVRIPT setting' % token.split_contents()[0]) return JavascriptNode(name)
36.224299
163
0.658153
3892498f9a7a0da6c0cf3abf4cc6b908eb16fbfc
7,551
py
Python
darts/base_engines/fr.py
GabrielAmare/Darts
182748d821b8c1838071f3b28724d0d9b095dcf9
[ "MIT" ]
null
null
null
darts/base_engines/fr.py
GabrielAmare/Darts
182748d821b8c1838071f3b28724d0d9b095dcf9
[ "MIT" ]
null
null
null
darts/base_engines/fr.py
GabrielAmare/Darts
182748d821b8c1838071f3b28724d0d9b095dcf9
[ "MIT" ]
null
null
null
from text_engine import * from darts.commands import * from darts.constants import KW, CTX from .utils import set_parser_identifiers PNC = PlayerNameCompound.__name__ PN = PlayerName.__name__ lexer, parser, astb, engine_fr = base( # COMMANDS [Quit, match(KW.QUIT)], [SaveParty, match(KW.SAVE_PARTY)], [MainMenu, match(KW.MAIN_MENU)], [StartParty, match(KW.OK)], [SelectPartyType, match(f"{KW.GAME} in *")], [SetLang, match(KW.PASS_TO) & match(f"{KW.LANG} as lang_IETF")], [ AdjustMic, match(KW.ADJUST_MIC) & match(KW.DURING) & match("*.value as seconds") & match(KW.SECONDS), match(KW.ADJUST_MIC), ], [OpenSettings, match(KW.OPEN_SETTINGS)], [Redo, match(KW.REDO) & (match("*.value in *") & match(KW.TIMES)).optional], [Undo, match(KW.UNDO) & (match("*.value in *") & match(KW.TIMES)).optional], [AddPlayers, match(f"{PN} in players").and_repeat & match(KW.AND) & ( match(f"{PNC} in players") | match(f"{PN} in players"))], [AddPlayer, match(f"{PN} as player")], [ AddScore, match("__scores__") & match(KW.FOR) & (match(f"{PNC} as player") | match(f"{PN} as player")), (match(f"{PNC} as player") | match(f"{PN} as player")) & match(KW.HAS_DONE) & match("__scores__"), match("__scores__"), ], # OBJECTS [PlayerName, match("VAR as name")], [PlayerNameCompound, match("VAR as name1") & match("VAR as name2")], [ ScoreValue, match("*.value as factor") & match(KW.TIMES) & match("*.value as value") & match(KW.POINT).optional, match("*.value as value") & match(KW.POINT).optional, match("*.fact as factor") & match("*.value as value") & match(KW.POINT).optional, ], pattern_libs=[] ) set_parser_identifiers(parser) # KWS lexer.add_pattern(KW.AND, mode="kw", expr="et") lexer.add_pattern(KW.OK, mode="kw", expr="ok") lexer.add_pattern(KW.FOR, mode="kw", expr="pour") lexer.add_pattern(KW.POINT, mode="kw", expr=r"points?|" r"\.") lexer.add_pattern(KW.TIMES, mode="kw", expr="fois|" "x") lexer.add_pattern(KW.PLUS, mode="kw", expr=r"plus|" r"\+") lexer.add_pattern(KW.HAS_DONE, mode="kw", expr="a fait|marques?") lexer.add_pattern(KW.ADJUST_MIC, mode="kw", expr="ajuster? le micro|" "ajuster? le microphone|" "ajuster? le bruit|" "ajuster") lexer.add_pattern(KW.DURING, mode="kw", expr="pendant|" "durant") lexer.add_pattern(KW.SECONDS, mode="kw", expr="secondes?") lexer.add_pattern(KW.OPEN_SETTINGS, mode="kw", expr="paramètres|" "ouvrir les paramètres|" "changer les paramètres") lexer.add_pattern(KW.PASS_TO, mode="kw", expr="passe[rs]? en") lexer.add_pattern(KW.SAVE_PARTY, mode="kw", expr="sauvegarder la partie|" "enregistrer la partie|" "sauvegarder|" "enregistrer") lexer.add_pattern(KW.LANG, mode="kw", expr="français", value="fr-FR") lexer.add_pattern(KW.LANG, mode="kw", expr="anglais", value="en-US") # QUITTER / MENU PRINCIPAL lexer.add_pattern(KW.QUIT, mode="kw", expr="quitter") lexer.add_pattern(KW.MAIN_MENU, mode="kw", expr="menu principal") # LANCER UNE PARTIE lexer.add_pattern(KW.GAME, mode="kw", expr="301", value="301") lexer.add_pattern(KW.GAME, mode="kw", expr="cricket", value="cricket") lexer.add_pattern(KW.GAME, mode="kw", expr="around the clock", value="rtc") lexer.add_pattern(KW.GAME, mode="kw", expr="alcooliques?") lexer.add_pattern(KW.GAME, mode="kw", expr="[mM]olkky", value="molkky") # ANNULER REFAIRE lexer.add_pattern(KW.UNDO, mode="kw", expr="annuler|" "oups|" "oops") lexer.add_pattern(KW.REDO, mode="kw", expr="restaurer|" "refaire") # FACTEURS lexer.add_pattern("KW_1.value.fact", mode="kw", expr="1|" "une?", value=1) lexer.add_pattern("KW_2.value.fact", mode="kw", expr="2|" "de|" "deux", value=2) lexer.add_pattern("KW_3.value.fact", mode="kw", expr="3|" "trois", value=3) lexer.add_pattern("KW_SIMPLE.fact", mode="kw", expr="[Ss]imples?", value=1) lexer.add_pattern("KW_DOUBLE.fact", mode="kw", expr="[Dd]oubles?", value=2) lexer.add_pattern("KW_TRIPLE.fact", mode="kw", expr="[Tt]riples?", value=3) lexer.add_pattern("KW_QUADRUPLE.fact", mode="kw", expr="quadruples?", value=4) lexer.add_pattern("KW_QUINTUPLE.fact", mode="kw", expr="quintuples?", value=5) lexer.add_pattern("KW_SEXTUPLE.fact", mode="kw", expr="sextuples?", value=6) lexer.add_pattern("KW_HEPTUPLE.fact", mode="kw", expr="septuples?", value=7) lexer.add_pattern("KW_OCTUPLE.fact", mode="kw", expr="octuples?", value=8) lexer.add_pattern("KW_NINETUPLE.fact", mode="kw", expr="nonuples?", value=9) # NOMBRES lexer.add_pattern("KW_BULL.value", mode="kw", expr="[bB]ulle?s?|" "[bB]oules?", value=25) lexer.add_pattern("KW_0.value", mode="kw", expr="zéros?", value=0) lexer.add_pattern("KW_2.value", mode="kw", expr="deux", value=2) lexer.add_pattern("KW_4.value", mode="kw", expr="quatre", value=4) lexer.add_pattern("KW_5.value", mode="kw", expr="V|" "cinq", value=5) lexer.add_pattern("KW_6.value", mode="kw", expr="six?", value=6) lexer.add_pattern("KW_7.value", mode="kw", expr="sept", value=7) lexer.add_pattern("KW_8.value", mode="kw", expr="huit|" "oui", value=8) lexer.add_pattern("KW_9.value", mode="kw", expr="neuf", value=9) lexer.add_pattern("KW_17.value", mode="kw", expr="X 7", value=17) lexer.add_pattern("KW_18.value", mode="kw", expr="X 8", value=18) lexer.add_pattern("KW_19.value", mode="kw", expr="X 9", value=19) lexer.add_pattern("KW_10.value", mode="kw", expr="X|" "dix|" "dis", value=10) lexer.add_pattern("KW_15.value", mode="kw", expr="XV", value=15) lexer.add_pattern("KW_16.value", mode="kw", expr="XVI", value=16) lexer.add_pattern("KW_20.value", mode="kw", expr="XX|" "vins?|" "Vins?|" "vent|" "vans", value=20) lexer.add_pattern("KW_30.value", mode="kw", expr="trans|" "France", value=30) lexer.add_pattern("KW_70.value", mode="kw", expr="60 X", value=70) lexer.add_pattern("KW_90.value", mode="kw", expr="80 X", value=90) lexer.add_pattern("KW_300.value", mode="kw", expr="croissant", value=300) lexer.add_pattern("VAR", mode="re", expr="[A-Za-zÀ-ÖØ-öø-ÿ-]+", value=lambda content: content.lower().replace('-', ' ')) lexer.add_pattern("INT.value", mode="re", expr="[0-9]+", value=int) engine = engine_fr
48.716129
120
0.545491
48d530b993ffa1f0c3f8a879fda689d61b6cbf06
163
py
Python
Exercices/Secao04/exercicio10.py
Guilt-tech/PythonExercices
e59bffae997a1974d3e3cdcfff7700afbed65e6e
[ "MIT" ]
null
null
null
Exercices/Secao04/exercicio10.py
Guilt-tech/PythonExercices
e59bffae997a1974d3e3cdcfff7700afbed65e6e
[ "MIT" ]
null
null
null
Exercices/Secao04/exercicio10.py
Guilt-tech/PythonExercices
e59bffae997a1974d3e3cdcfff7700afbed65e6e
[ "MIT" ]
null
null
null
print('Digite uma velocidade em Km/h, que será convertido em m/s') K = float(input('Velocidade: ')) M = K / 3.6 print(f'A velocidade em m/s é: {M} e m km/h é {K}')
40.75
66
0.644172
39ee8e39291d69ae937db69dca7008ef2ef9c8db
4,054
py
Python
aiotractive/api.py
Danielhiversen/aiotractive
20fe0be6bc63b44e3fedbc25c0e2533ca39132bf
[ "MIT" ]
null
null
null
aiotractive/api.py
Danielhiversen/aiotractive
20fe0be6bc63b44e3fedbc25c0e2533ca39132bf
[ "MIT" ]
null
null
null
aiotractive/api.py
Danielhiversen/aiotractive
20fe0be6bc63b44e3fedbc25c0e2533ca39132bf
[ "MIT" ]
null
null
null
"""Low level client for the Tractive REST API.""" import asyncio import aiohttp from aiohttp.client_exceptions import ClientResponseError from yarl import URL import json from .exceptions import TractiveError, UnauthorizedError, NotFoundError class API: API_URL = URL("https://graph.tractive.com/3/") CLIENT_ID = "5f9be055d8912eb21a4cd7ba" DEFAULT_TIMEOUT = 10 TOKEN_URI = "auth/token" BASE_HEADERS = { "x-tractive-client": CLIENT_ID, "content-type": "application/json;charset=UTF-8", "accept": "application/json, text/plain, */*", } def __init__( self, login, password, timeout=DEFAULT_TIMEOUT, loop=None, session=None ): self._login = login self._password = password self._timeout = timeout self._loop = loop or asyncio.get_event_loop() self.session = session self._close_session = False if self.session is None: self.session = aiohttp.ClientSession(loop=self._loop) self._close_session = True self._user_credentials = None async def user_id(self): await self._authenticate() return self._user_credentials["user_id"] async def auth_headers(self): await self._authenticate() return {**self.BASE_HEADERS, **self._auth_headers} async def request(self, *args, **kwargs): """Perform request with error wrapping.""" try: return await self.raw_request(*args, **kwargs) except aiohttp.client_exceptions.ClientResponseError as error: if error.status in [401, 403]: raise UnauthorizedError from error if error.status == 404: raise NotFoundError from error raise TractiveError from error except Exception as error: raise TractiveError from error async def raw_request(self, uri, params=None, data=None, method="GET"): """Perform request.""" async with self.session.request( method, self.API_URL.join(URL(uri)).update_query(params), json=data, headers=await self.auth_headers(), timeout=self._timeout, ) as response: response.raise_for_status() if ( "Content-Type" in response.headers and "application/json" in response.headers["Content-Type"] ): return await response.json() return await response.read() async def _authenticate(self): """Perform authenticateion.""" # TODO: update credentials if expired if self._user_credentials is not None: return self._user_credentials async with self.session.request( "POST", self.API_URL.join(URL(self.TOKEN_URI)), data=json.dumps( { "platform_email": self._login, "platform_token": self._password, "grant_type": "tractive", } ), headers=self.BASE_HEADERS, timeout=self._timeout, ) as response: try: response.raise_for_status() if ( "Content-Type" in response.headers and "application/json" in response.headers["Content-Type"] ): self._user_credentials = await response.json() self._auth_headers = { "x-tractive-user": self._user_credentials["user_id"], "authorization": f"Bearer {self._user_credentials['access_token']}", } return self._user_credentials except ClientResponseError as error: if error.status in [401, 403]: raise UnauthorizedError from error async def close(self): """Close the session.""" if self.session and self._close_session: await self.session.close()
33.783333
92
0.578194
0a31c242db86516e5eb136cf639cba8d4e5a455c
3,471
py
Python
examplefuncsplayer-python/run.py
golfbag/bc
f16601d90b7ad5e4ba5344e00cb5f54358526bd2
[ "MIT" ]
null
null
null
examplefuncsplayer-python/run.py
golfbag/bc
f16601d90b7ad5e4ba5344e00cb5f54358526bd2
[ "MIT" ]
null
null
null
examplefuncsplayer-python/run.py
golfbag/bc
f16601d90b7ad5e4ba5344e00cb5f54358526bd2
[ "MIT" ]
null
null
null
import battlecode as bc import random import sys import traceback import time import os print(os.getcwd()) print("pystarting") #Test # A GameController is the main type that you talk to the game with. # Its constructor will connect to a running game. gc = bc.GameController() directions = list(bc.Direction) print("pystarted") # It's a good idea to try to keep your bots deterministic, to make debugging easier. # determinism isn't required, but it means that the same things will happen in every thing you run, # aside from turns taking slightly different amounts of time due to noise. random.seed(6137) # let's start off with some research! # we can queue as much as we want. gc.queue_research(bc.UnitType.Rocket) gc.queue_research(bc.UnitType.Worker) gc.queue_research(bc.UnitType.Knight) my_team = gc.team() while True: # We only support Python 3, which means brackets around print() print('pyround:', gc.round(), 'time left:', gc.get_time_left_ms(), 'ms') # frequent try/catches are a good idea try: # walk through our units: for unit in gc.my_units(): # first, factory logic if unit.unit_type == bc.UnitType.Factory: garrison = unit.structure_garrison() if len(garrison) > 0: d = random.choice(directions) if gc.can_unload(unit.id, d): print('unloaded a knight!') gc.unload(unit.id, d) continue elif gc.can_produce_robot(unit.id, bc.UnitType.Knight): gc.produce_robot(unit.id, bc.UnitType.Knight) print('produced a knight!') continue # first, let's look for nearby blueprints to work on location = unit.location if location.is_on_map(): nearby = gc.sense_nearby_units(location.map_location(), 2) for other in nearby: if unit.unit_type == bc.UnitType.Worker and gc.can_build(unit.id, other.id): gc.build(unit.id, other.id) print('built a factory!') # move onto the next unit continue if other.team != my_team and gc.is_attack_ready(unit.id) and gc.can_attack(unit.id, other.id): print('attacked a thing!') gc.attack(unit.id, other.id) continue # okay, there weren't any dudes around # pick a random direction: d = random.choice(directions) # or, try to build a factory: if gc.karbonite() > bc.UnitType.Factory.blueprint_cost() and gc.can_blueprint(unit.id, bc.UnitType.Factory, d): gc.blueprint(unit.id, bc.UnitType.Factory, d) # and if that fails, try to move elif gc.is_move_ready(unit.id) and gc.can_move(unit.id, d): gc.move_robot(unit.id, d) except Exception as e: print('Error:', e) # use this to show where the error was traceback.print_exc() # send the actions we've performed, and wait for our next turn. gc.next_turn() # these lines are not strictly necessary, but it helps make the logs make more sense. # it forces everything we've written this turn to be written to the manager. sys.stdout.flush() sys.stderr.flush()
36.925532
123
0.597234
f16f77a92d8f2c5878087e55779ac908cb9dde2a
3,024
py
Python
2020/day_05/solution_p2.py
rvaughan/AdventOfCode2017
fb9199282c0083cd0b3072c27e63ea83d866efc2
[ "MIT" ]
null
null
null
2020/day_05/solution_p2.py
rvaughan/AdventOfCode2017
fb9199282c0083cd0b3072c27e63ea83d866efc2
[ "MIT" ]
null
null
null
2020/day_05/solution_p2.py
rvaughan/AdventOfCode2017
fb9199282c0083cd0b3072c27e63ea83d866efc2
[ "MIT" ]
null
null
null
#!/usr/bin/env python """ This code holds the solution for part 2 of day 5 of the Advent of Code for 2020. """ import sys def identify_row(boarding_pass): min_row = 0 max_row = 127 for letter in boarding_pass[:-4]: # print(letter, min_row, max_row) if letter == 'F': max_row = min_row + ((max_row - min_row) // 2) else: min_row = min_row + ((max_row - min_row) // 2) + 1 # print('----->', min_row, max_row) if boarding_pass[6] == 'F': return min_row return max_row def identify_seat(boarding_pass): min_col = 0 max_col = 7 for letter in boarding_pass[-3:]: # print(letter, min_col, max_col) if letter == 'L': max_col = min_col + ((max_col - min_col) / 2) else: min_col = min_col + ((max_col - min_col) / 2) # print('----->', min_col, max_col) if boarding_pass[6] == 'L': return min_col return max_col def calc_seat_id(row, col): return (row * 8) + col def calculate_solution(boarding_passes): seats = [] for boarding_pass in boarding_passes: seats.append(calc_seat_id(identify_row(boarding_pass), identify_seat(boarding_pass))) seats.sort() last = seats[0] - 1 for seat in seats: if seat != last + 1: return seat -1 else: last = seat def run_test(test_input, expected_solution): """ Helper method for running some unit tests whilst minimising repetative code. """ result = calculate_solution(test_input) if result != expected_solution: print("Test for input {0} FAILED. Got a result of {1}, not {2}".format(test_input, result, expected_solution)) sys.exit(-1) print("Test for input {0} passed.".format(test_input)) return result # Run any tests that we've defined to help validate our code prior to # trying to solve the puzzle. boarding_pass = "FBFBBFFRLR" row = identify_row(boarding_pass) assert row == 44 col = identify_seat(boarding_pass) assert col == 5 assert calc_seat_id(row, col) == 357 boarding_pass = "BFFFBBFRRR" row = identify_row(boarding_pass) assert row == 70 col = identify_seat(boarding_pass) assert col == 7 assert calc_seat_id(row, col) == 567 boarding_pass = "FFFBBBFRRR" row = identify_row(boarding_pass) assert row == 14 col = identify_seat(boarding_pass) assert col == 7 assert calc_seat_id(row, col) == 119 boarding_pass = "BBFFBBFRLL" row = identify_row(boarding_pass) assert row == 102 col = identify_seat(boarding_pass) assert col == 4 assert calc_seat_id(row, col) == 820 print("") print("-----------------") print("All Tests PASSED.") print("-----------------") print("") # Ok, so if we reach here, then we can be reasonably sure that the code # above is working correctly. Let's use the actual captcha now. with open("input.txt", "r") as f: input_data = [line.strip() for line in f] answer = calculate_solution(input_data) print("Solution is {0}".format(answer))
24.192
118
0.640542
72077609aefe5fe08a2d0d67784d937a77cca034
10,271
py
Python
exercises/networking_selfpaced/networking-workshop/collections/ansible_collections/community/general/plugins/modules/net_tools/ldap/ldap_attrs.py
tr3ck3r/linklight
5060f624c235ecf46cb62cefcc6bddc6bf8ca3e7
[ "MIT" ]
null
null
null
exercises/networking_selfpaced/networking-workshop/collections/ansible_collections/community/general/plugins/modules/net_tools/ldap/ldap_attrs.py
tr3ck3r/linklight
5060f624c235ecf46cb62cefcc6bddc6bf8ca3e7
[ "MIT" ]
null
null
null
exercises/networking_selfpaced/networking-workshop/collections/ansible_collections/community/general/plugins/modules/net_tools/ldap/ldap_attrs.py
tr3ck3r/linklight
5060f624c235ecf46cb62cefcc6bddc6bf8ca3e7
[ "MIT" ]
null
null
null
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright: (c) 2019, Maciej Delmanowski <drybjed@gmail.com> # Copyright: (c) 2017, Alexander Korinek <noles@a3k.net> # Copyright: (c) 2016, Peter Sagerson <psagers@ignorare.net> # Copyright: (c) 2016, Jiri Tyr <jiri.tyr@gmail.com> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = { 'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community' } DOCUMENTATION = r''' --- module: ldap_attrs short_description: Add or remove multiple LDAP attribute values description: - Add or remove multiple LDAP attribute values. notes: - This only deals with attributes on existing entries. To add or remove whole entries, see M(ldap_entry). - The default authentication settings will attempt to use a SASL EXTERNAL bind over a UNIX domain socket. This works well with the default Ubuntu install for example, which includes a cn=peercred,cn=external,cn=auth ACL rule allowing root to modify the server configuration. If you need to use a simple bind to access your server, pass the credentials in I(bind_dn) and I(bind_pw). - For I(state=present) and I(state=absent), all value comparisons are performed on the server for maximum accuracy. For I(state=exact), values have to be compared in Python, which obviously ignores LDAP matching rules. This should work out in most cases, but it is theoretically possible to see spurious changes when target and actual values are semantically identical but lexically distinct. author: - Jiri Tyr (@jtyr) - Alexander Korinek (@noles) - Maciej Delmanowski (@drybjed) requirements: - python-ldap options: state: required: false type: str choices: [present, absent, exact] default: present description: - The state of the attribute values. If C(present), all given attribute values will be added if they're missing. If C(absent), all given attribute values will be removed if present. If C(exact), the set of attribute values will be forced to exactly those provided and no others. If I(state=exact) and the attribute I(value) is empty, all values for this attribute will be removed. attributes: required: true type: dict description: - The attribute(s) and value(s) to add or remove. The complex argument format is required in order to pass a list of strings (see examples). ordered: required: false type: bool default: 'no' description: - If C(yes), prepend list values with X-ORDERED index numbers in all attributes specified in the current task. This is useful mostly with I(olcAccess) attribute to easily manage LDAP Access Control Lists. extends_documentation_fragment: - community.general.ldap.documentation ''' EXAMPLES = r''' - name: Configure directory number 1 for example.com ldap_attrs: dn: olcDatabase={1}hdb,cn=config attributes: olcSuffix: dc=example,dc=com state: exact # The complex argument format is required here to pass a list of ACL strings. - name: Set up the ACL ldap_attrs: dn: olcDatabase={1}hdb,cn=config attributes: olcAccess: - >- {0}to attrs=userPassword,shadowLastChange by self write by anonymous auth by dn="cn=admin,dc=example,dc=com" write by * none' - >- {1}to dn.base="dc=example,dc=com" by dn="cn=admin,dc=example,dc=com" write by * read state: exact # An alternative approach with automatic X-ORDERED numbering - name: Set up the ACL ldap_attrs: dn: olcDatabase={1}hdb,cn=config attributes: olcAccess: - >- to attrs=userPassword,shadowLastChange by self write by anonymous auth by dn="cn=admin,dc=example,dc=com" write by * none' - >- to dn.base="dc=example,dc=com" by dn="cn=admin,dc=example,dc=com" write by * read ordered: yes state: exact - name: Declare some indexes ldap_attrs: dn: olcDatabase={1}hdb,cn=config attributes: olcDbIndex: - objectClass eq - uid eq - name: Set up a root user, which we can use later to bootstrap the directory ldap_attrs: dn: olcDatabase={1}hdb,cn=config attributes: olcRootDN: cn=root,dc=example,dc=com olcRootPW: "{SSHA}tabyipcHzhwESzRaGA7oQ/SDoBZQOGND" state: exact - name: Remove an attribute with a specific value ldap_attrs: dn: uid=jdoe,ou=people,dc=example,dc=com attributes: description: "An example user account" state: absent server_uri: ldap://localhost/ bind_dn: cn=admin,dc=example,dc=com bind_pw: password - name: Remove specified attribute(s) from an entry ldap_attrs: dn: uid=jdoe,ou=people,dc=example,dc=com attributes: description: [] state: exact server_uri: ldap://localhost/ bind_dn: cn=admin,dc=example,dc=com bind_pw: password ''' RETURN = r''' modlist: description: list of modified parameters returned: success type: list sample: '[[2, "olcRootDN", ["cn=root,dc=example,dc=com"]]]' ''' import traceback from ansible.module_utils.basic import AnsibleModule, missing_required_lib from ansible.module_utils._text import to_native, to_bytes from ansible_collections.community.general.plugins.module_utils.ldap import LdapGeneric, gen_specs import re LDAP_IMP_ERR = None try: import ldap HAS_LDAP = True except ImportError: LDAP_IMP_ERR = traceback.format_exc() HAS_LDAP = False class LdapAttrs(LdapGeneric): def __init__(self, module): LdapGeneric.__init__(self, module) # Shortcuts self.attrs = self.module.params['attributes'] self.state = self.module.params['state'] self.ordered = self.module.params['ordered'] def _order_values(self, values): """ Preprend X-ORDERED index numbers to attribute's values. """ ordered_values = [] if isinstance(values, list): for index, value in enumerate(values): cleaned_value = re.sub(r'^\{\d+\}', '', value) ordered_values.append('{' + str(index) + '}' + cleaned_value) return ordered_values def _normalize_values(self, values): """ Normalize attribute's values. """ norm_values = [] if isinstance(values, list): if self.ordered: norm_values = list(map(to_bytes, self._order_values(list(map(str, values))))) else: norm_values = list(map(to_bytes, values)) else: norm_values = [to_bytes(str(values))] return norm_values def add(self): modlist = [] for name, values in self.module.params['attributes'].items(): norm_values = self._normalize_values(values) for value in norm_values: if self._is_value_absent(name, value): modlist.append((ldap.MOD_ADD, name, value)) return modlist def delete(self): modlist = [] for name, values in self.module.params['attributes'].items(): norm_values = self._normalize_values(values) for value in norm_values: if self._is_value_present(name, value): modlist.append((ldap.MOD_DELETE, name, value)) return modlist def exact(self): modlist = [] for name, values in self.module.params['attributes'].items(): norm_values = self._normalize_values(values) try: results = self.connection.search_s( self.dn, ldap.SCOPE_BASE, attrlist=[name]) except ldap.LDAPError as e: self.fail("Cannot search for attribute %s" % name, e) current = results[0][1].get(name, []) if frozenset(norm_values) != frozenset(current): if len(current) == 0: modlist.append((ldap.MOD_ADD, name, norm_values)) elif len(norm_values) == 0: modlist.append((ldap.MOD_DELETE, name, None)) else: modlist.append((ldap.MOD_REPLACE, name, norm_values)) return modlist def _is_value_present(self, name, value): """ True if the target attribute has the given value. """ try: is_present = bool( self.connection.compare_s(self.dn, name, value)) except ldap.NO_SUCH_ATTRIBUTE: is_present = False return is_present def _is_value_absent(self, name, value): """ True if the target attribute doesn't have the given value. """ return not self._is_value_present(name, value) def main(): module = AnsibleModule( argument_spec=gen_specs( attributes=dict(type='dict', required=True), ordered=dict(type='bool', default=False, required=False), state=dict(type='str', default='present', choices=['absent', 'exact', 'present']), ), supports_check_mode=True, ) if not HAS_LDAP: module.fail_json(msg=missing_required_lib('python-ldap'), exception=LDAP_IMP_ERR) # Instantiate the LdapAttr object ldap = LdapAttrs(module) state = module.params['state'] # Perform action if state == 'present': modlist = ldap.add() elif state == 'absent': modlist = ldap.delete() elif state == 'exact': modlist = ldap.exact() changed = False if len(modlist) > 0: changed = True if not module.check_mode: try: ldap.connection.modify_s(ldap.dn, modlist) except Exception as e: module.fail_json(msg="Attribute action failed.", details=to_native(e)) module.exit_json(changed=changed, modlist=modlist) if __name__ == '__main__': main()
31.603077
112
0.628663
f65e7a9c9952517b13bec043357d167a3585e9fa
10,111
py
Python
qstkutil/qsdateutil.py
grahesh/Stock-Market-Event-Analysis
57dc06e087c29b9c134df8886c97377b3d99f05b
[ "BSD-3-Clause" ]
1
2015-12-04T14:40:33.000Z
2015-12-04T14:40:33.000Z
qstkutil/qsdateutil.py
grahesh/Stock-Market-Event-Analysis
57dc06e087c29b9c134df8886c97377b3d99f05b
[ "BSD-3-Clause" ]
null
null
null
qstkutil/qsdateutil.py
grahesh/Stock-Market-Event-Analysis
57dc06e087c29b9c134df8886c97377b3d99f05b
[ "BSD-3-Clause" ]
null
null
null
''' (c) 2011, 2012 Georgia Tech Research Corporation This source code is released under the New BSD license. Please see http://wiki.quantsoftware.org/index.php?title=QSTK_License for license details. Created on Jan 1, 2011 @author:Drew Bratcher @contact: dbratcher@gatech.edu @summary: Contains tutorial for backtester and report. # Edited on January <9>,2013 # @author: Grahesh Parkar # @summary: Editied part of code to read NSE dates # @Modified Line Nos: 34-40 ''' __version__ = "$Revision: 295 $" import datetime as dt from datetime import timedelta import time as t import numpy as np import os import pandas as pd def _cache_dates(): ''' Caches dates ''' try: # original code # filename = os.environ['QS'] + "/qstkutil/NYSE_dates.txt" # original code # modified code to read NSE dates filename = os.environ['QS'] + "/qstkutil/NSE_dates.txt" # modified code except KeyError: print "Please be sure to set the value for QS in config.sh or\n" print "in local.sh and then \'source local.sh\'.\n" datestxt = np.loadtxt(filename,dtype=str) dates = [] for i in datestxt: dates.append(dt.datetime.strptime(i,"%m/%d/%Y")) return pd.TimeSeries(index=dates, data=dates) GTS_DATES = _cache_dates() def getMonthNames(): return(['JAN','FEB','MAR','APR','MAY','JUN','JUL','AUG','SEP','OCT','NOV','DEC']) def getYears(funds): years=[] for date in funds.index: if(not(date.year in years)): years.append(date.year) return(years) def getMonths(funds,year): months=[] for date in funds.index: if((date.year==year) and not(date.month in months)): months.append(date.month) return(months) def getDays(funds,year,month): days=[] for date in funds.index: if((date.year==year) and (date.month==month)): days.append(date) return(days) def getDaysBetween(ts_start, ts_end): days=[] for i in range(0,(ts_end-ts_start).days): days.append(ts_start+timedelta(days=1)*i) return(days) def getFirstDay(funds,year,month): for date in funds.index: if((date.year==year) and (date.month==month)): return(date) return('ERROR') def getLastDay(funds,year,month): return_date = 'ERROR' for date in funds.index: if((date.year==year) and (date.month==month)): return_date = date return(return_date) def getNextOptionClose(day, trade_days, offset=0): #get third friday in month of day #get first of month year_off=0 if day.month+offset > 12: year_off = 1 offset = offset - 12 first = dt.datetime(day.year+year_off, day.month+offset, 1, hour=16) #get weekday day_num = first.weekday() #get first friday (friday - weekday) add 7 if less than 1 dif = 5 - day_num if dif < 1: dif = dif+7 #move to third friday dif = dif + 14 friday = first+dt.timedelta(days=(dif-1)) #if friday is a holiday, options expire then if friday in trade_days: month_close = first + dt.timedelta(days=dif) else: month_close = friday #if day is past the day after that if month_close < day: return_date = getNextOptionClose(day, trade_days, offset=1) else: return_date = month_close return(return_date) def getLastOptionClose(day, trade_days): start = day while getNextOptionClose(day, trade_days)>=start: day= day - dt.timedelta(days=1) return(getNextOptionClose(day, trade_days)) # original code #def getNYSEoffset(mark, offset): # original code # modified code def getNSEoffset(mark, offset): # modified code ''' Returns NSE date offset by number of days ''' mark = mark.replace(hour=0, minute=0, second=0, microsecond=0) i = GTS_DATES.index.searchsorted(mark, side='right') # If there is no exact match, take first date in past if GTS_DATES[i] != mark: i -= 1 ret = GTS_DATES[i + offset] ret.replace(hour=16) return ret # original code #def getNYSEdays(startday = dt.datetime(1964,7,5), endday = dt.datetime(2020,12,31), # timeofday = dt.timedelta(0)): # original code # modified code def getNSEdays(startday = dt.datetime(1964,7,5), endday = dt.datetime(2020,12,31), timeofday = dt.timedelta(0)): # modified code """ @summary: Create a list of timestamps between startday and endday (inclusive) that correspond to the days there was trading at the NSE. This function depends on a separately created a file that lists all days since July 4, 1962 that the NSE has been open, going forward to 2020 (based on the holidays that NSE recognizes). @param startday: First timestamp to consider (inclusive) @param endday: Last day to consider (inclusive) @return list: of timestamps between startday and endday on which NSE traded @rtype datetime """ start = startday - timeofday end = endday - timeofday dates = GTS_DATES[start:end] ret = [x + timeofday for x in dates] return(ret) # original code #def getNextNNYSEdays(startday, days, timeofday): # original code def getNextNNSEdays(startday, days, timeofday): """ @summary: Create a list of timestamps from startday that is days days long that correspond to the days there was trading at NSE. This function depends on the file used in getNYEdays and assumes the dates within are in order. @param startday: First timestamp to consider (inclusive) @param days: Number of timestamps to return @return list: List of timestamps starting at startday on which NSE traded @rtype datetime """ try: # original code # filename = os.environ['QS'] + "/qstkutil/NYSE_dates.txt" # original code # modified code filename = os.environ['QS'] + "/qstkutil/NSE_dates.txt" # modified code except KeyError: print "Please be sure to set the value for QS in config.sh or\n" print "in local.sh and then \'source local.sh\'.\n" datestxt = np.loadtxt(filename,dtype=str) dates=[] for i in datestxt: if(len(dates)<days): if((dt.datetime.strptime(i,"%m/%d/%Y")+timeofday)>=startday): dates.append(dt.datetime.strptime(i,"%m/%d/%Y")+timeofday) return(dates) # original code #def getPrevNNYSEday(startday, timeofday): # original code # modified code def getPrevNNSEday(startday, timeofday): # modified code """ @summary: This function returns the last valid trading day before the start day, or returns the start day if it is a valid trading day. This function depends on the file used in getNSEdays and assumes the dates within are in order. @param startday: First timestamp to consider (inclusive) @param days: Number of timestamps to return @return list: List of timestamps starting at startday on which NSE traded @rtype datetime """ try: # original code # filename = os.environ['QS'] + "/qstkutil/NYSE_dates.txt" # original code # modified code filename = os.environ['QS'] + "/qstkutil/NSE_dates.txt" # modified code except KeyError: print "Please be sure to set the value for QS in config.sh or\n" print "in local.sh and then \'source local.sh\'.\n" datestxt = np.loadtxt(filename,dtype=str) #''' Set return to first day ''' dtReturn = dt.datetime.strptime( datestxt[0],"%m/%d/%Y")+timeofday #''' Loop through all but first ''' for i in datestxt[1:]: dtNext = dt.datetime.strptime(i,"%m/%d/%Y") #''' If we are > startday, then use previous valid day ''' if( dtNext > startday ): break dtReturn = dtNext + timeofday return(dtReturn) def ymd2epoch(year, month, day): """ @summary: Convert YMD info into a unix epoch value. @param year: The year @param month: The month @param day: The day @return epoch: number of seconds since epoch """ return(t.mktime(dt.date(year,month,day).timetuple())) def epoch2date(ts): """ @summary Convert seconds since epoch into date @param ts: Seconds since epoch @return thedate: A date object """ tm = t.gmtime(ts) return(dt.date(tm.tm_year,tm.tm_mon,tm.tm_mday)) def _trade_dates(dt_start, dt_end, s_period): ''' @summary: Generate dates on which we need to trade @param c_strat: Strategy config class @param dt_start: Start date @param dt_end: End date ''' # original code # ldt_timestamps = getNYSEdays(dt_start, # dt_end, dt.timedelta(hours=16) ) # original code # modified code ldt_timestamps = getNSEdays(dt_start, dt_end, dt.timedelta(hours=16) ) # modified code # Use pandas reindex method instead # Note, dates are index as well as values, we select based on index # but return values since it is a numpy array of datetimes instead of # pandas specific. ts_dates = pd.TimeSeries(index=ldt_timestamps, data=ldt_timestamps) # These are the dates we want if s_period[:2] == 'BW': # special case for biweekly dr_range = pd.DateRange(dt_start, dt_end, timeRule=s_period[1:]) dr_range = np.asarray(dr_range) li_even = np.array(range(len(dr_range))) dr_range = dr_range[li_even[li_even % 2 == 0]] else: dr_range = pd.DateRange(dt_start, dt_end, timeRule=s_period) dr_range = np.asarray(dr_range) # Warning, we MUST copy the date range, if we modify it it will be returned # in it's modified form the next time we use it. dr_range = np.copy(dr_range) dr_range += pd.DateOffset(hours=16) ts_dates = ts_dates.reindex( dr_range, method='bfill' ) ldt_dates = ts_dates[ts_dates.notnull()].values #Make unique sdt_unique = set() ldt_dates = [x for x in ldt_dates if x not in sdt_unique and not sdt_unique.add(x)] return ldt_dates
29.392442
85
0.649392
da97df93883c684e17fcc6e29b8a40a2d86e4838
3,678
py
Python
tmoga/algorithm/Feature_Extraction.py
zjg540066169/tmoga
a3c3ecd0d72fc7c57fd5e5a624780e7ebf199c61
[ "Apache-2.0" ]
2
2021-10-06T04:45:52.000Z
2022-03-20T01:18:05.000Z
tmoga/algorithm/Feature_Extraction.py
zjg540066169/tmoga
a3c3ecd0d72fc7c57fd5e5a624780e7ebf199c61
[ "Apache-2.0" ]
1
2022-03-20T01:45:09.000Z
2022-03-21T15:17:21.000Z
tmoga/algorithm/Feature_Extraction.py
zjg540066169/tmoga
a3c3ecd0d72fc7c57fd5e5a624780e7ebf199c61
[ "Apache-2.0" ]
3
2021-10-09T08:08:44.000Z
2022-03-20T01:18:07.000Z
# -*- coding: utf-8 -*- """ Extract transfered feature in communities. (feature extraction) @auth: Jungang Zou @date: 2018/05/10 """ import networkx as nx from tmoga.utils.evaluation import evaluation import multiprocessing from joblib import Parallel, delayed class Clique_Discover(object): def __init__(self): pass @classmethod def clique_discover(self, G, clusters, CID = 0.8, max_num_cliques = 5): #print(G, clusters, CID) clique_list = [] num_cores = multiprocessing.cpu_count() results = Parallel(n_jobs=num_cores)(delayed(self.clique_in_community)(G, clusters[i], CID, max_num_cliques) for i in range(len(clusters))) #print(results) for i in results: if len(i) > 0: clique_list.extend(i) #print(clique_list) return sorted(clique_list, key = lambda x:len(x)) @classmethod def clique_in_community(self, G, c, CID = 0.8, max_num_cliques = 5): if len(c) <= 2: return [] if evaluation.community_CID(G, c) >= CID: return [c] cliques = [] c = sorted(c) searched = set() for i in range(len(c) - 1): #print(searched, c[i]) current_node = c[i] if current_node in searched: continue neighbor = [j for j in set(G[current_node].keys()).intersection(c) if j > current_node and j not in searched] #print(searched, c[i], neighbor) result = self.clique_search(G, set(c), set([current_node]), neighbor, current_node, CID = CID, max_num_cliques = max_num_cliques, searched = searched) if len(result) > 0: searched = searched.union(result) cliques.append(list(result)) return cliques @classmethod def clique_search(self, G, community, v_subgraph, v_candidate, current_node, edges = 0, CID = 0.8, max_num_cliques = 5, searched = []): clique_max = v_subgraph while len(v_candidate) != 0: w = v_candidate[0] v_candidate.remove(v_candidate[0]) w_neighbor = set(G[w].keys()) new_edges = edges v_candidate_new = v_candidate.copy() for n in w_neighbor: #print(n) if n in v_subgraph: new_edges += 1 #print(n) continue elif n in searched: continue elif n <= current_node: continue elif n in v_candidate: continue elif n not in community: continue else: v_candidate_new.append(n) if (new_edges * 2 / (len(v_subgraph) * (len(v_subgraph) + 1)) < CID): continue else: new_v_subgraph = v_subgraph.copy() new_v_subgraph.add(w) if len(new_v_subgraph) >= max_num_cliques: return new_v_subgraph result = self.clique_search(G, community, new_v_subgraph, v_candidate_new, current_node, new_edges, CID, max_num_cliques, searched = searched) if len(clique_max) < len(result): clique_max = result #print(clique_max) if len(clique_max)>2: return clique_max else: return []
37.151515
163
0.516041
79f2a199c8946f68a88d6fb20a518c31136e520b
2,444
py
Python
v1.0.0.test/toontown/coghq/BossbotCountryClubMazeRoom_Battle02.py
TTOFFLINE-LEAK/ttoffline
bb0e91704a755d34983e94288d50288e46b68380
[ "MIT" ]
4
2019-07-01T15:46:43.000Z
2021-07-23T16:26:48.000Z
v2.5.7/toontown/coghq/BossbotCountryClubMazeRoom_Battle02.py
TTOFFLINE-LEAK/ttoffline
bb0e91704a755d34983e94288d50288e46b68380
[ "MIT" ]
1
2019-06-29T03:40:05.000Z
2021-06-13T01:15:16.000Z
v1.0.0.test/toontown/coghq/BossbotCountryClubMazeRoom_Battle02.py
TTOFFLINE-LEAK/ttoffline
bb0e91704a755d34983e94288d50288e46b68380
[ "MIT" ]
4
2019-07-28T21:18:46.000Z
2021-02-25T06:37:25.000Z
from toontown.coghq.SpecImports import * GlobalEntities = {1000: {'type': 'levelMgr', 'name': 'LevelMgr', 'comment': '', 'parentEntId': 0, 'cogLevel': 0, 'farPlaneDistance': 1500, 'modelFilename': 'phase_12/models/bossbotHQ/BossbotMazex4_C', 'wantDoors': 1}, 1001: {'type': 'editMgr', 'name': 'EditMgr', 'parentEntId': 0, 'insertEntity': None, 'removeEntity': None, 'requestNewEntity': None, 'requestSave': None}, 0: {'type': 'zone', 'name': 'UberZone', 'comment': '', 'parentEntId': 0, 'scale': 1, 'description': '', 'visibility': []}, 110000: {'type': 'battleBlocker', 'name': '<unnamed>', 'comment': '', 'parentEntId': 0, 'pos': Point3(42.8475, 84.9249, 0), 'hpr': Point3(270, 0, 0), 'scale': Vec3(1, 1, 1), 'cellId': 0, 'radius': 10}, 110202: {'type': 'door', 'name': '<unnamed>', 'comment': '', 'parentEntId': 110001, 'pos': Point3(0, 0, 0), 'hpr': Vec3(0, 0, 0), 'scale': 1, 'color': Vec4(1, 1, 1, 1), 'isLock0Unlocked': 1, 'isLock1Unlocked': 0, 'isLock2Unlocked': 1, 'isLock3Unlocked': 1, 'isOpen': 0, 'isOpenEvent': 0, 'isVisBlocker': 0, 'secondsOpen': 1, 'unlock0Event': 0, 'unlock1Event': 110000, 'unlock2Event': 0, 'unlock3Event': 0}, 110002: {'type': 'maze', 'name': '<unnamed>', 'comment': '', 'parentEntId': 0, 'pos': Point3(-141.563, -78.8353, 0), 'hpr': Vec3(0, 0, 0), 'scale': Vec3(1, 1, 1), 'numSections': 3}, 10002: {'type': 'nodepath', 'name': 'props', 'comment': '', 'parentEntId': 0, 'pos': Point3(0, 0, 0), 'hpr': Vec3(0, 0, 0), 'scale': 1}, 110001: {'type': 'nodepath', 'name': '<unnamed>', 'comment': '', 'parentEntId': 0, 'pos': Point3(60.0276, 82.0315, 0), 'hpr': Point3(270, 0, 0), 'scale': Vec3(1, 1, 1)}} Scenario0 = {} levelSpec = {'globalEntities': GlobalEntities, 'scenarios': [ Scenario0]}
35.941176
80
0.434124
94fd1ea9cb4b9f851411121d4a8960ecfe9ad0ea
23,410
py
Python
test/functional/test_framework/test_node.py
butterkitty/buttcoin
a9ab9e2a2e2722a2364944391a343f248efdadd7
[ "MIT" ]
null
null
null
test/functional/test_framework/test_node.py
butterkitty/buttcoin
a9ab9e2a2e2722a2364944391a343f248efdadd7
[ "MIT" ]
null
null
null
test/functional/test_framework/test_node.py
butterkitty/buttcoin
a9ab9e2a2e2722a2364944391a343f248efdadd7
[ "MIT" ]
1
2021-05-19T01:58:52.000Z
2021-05-19T01:58:52.000Z
#!/usr/bin/env python3 # Copyright (c) 2017-2018 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Class for buttcoind node under test""" import contextlib import decimal import errno from enum import Enum import http.client import json import logging import os import re import subprocess import tempfile import time import urllib.parse import collections import shlex import sys from .authproxy import JSONRPCException from .util import ( append_config, delete_cookie_file, get_rpc_proxy, rpc_url, wait_until, p2p_port, ) # For Python 3.4 compatibility JSONDecodeError = getattr(json, "JSONDecodeError", ValueError) BITCOIND_PROC_WAIT_TIMEOUT = 60 class FailedToStartError(Exception): """Raised when a node fails to start correctly.""" class ErrorMatch(Enum): FULL_TEXT = 1 FULL_REGEX = 2 PARTIAL_REGEX = 3 class TestNode(): """A class for representing a buttcoind node under test. This class contains: - state about the node (whether it's running, etc) - a Python subprocess.Popen object representing the running process - an RPC connection to the node - one or more P2P connections to the node To make things easier for the test writer, any unrecognised messages will be dispatched to the RPC connection.""" def __init__(self, i, datadir, *, rpchost, timewait, bitcoind, bitcoin_cli, coverage_dir, cwd, extra_conf=None, extra_args=None, use_cli=False, start_perf=False): """ Kwargs: start_perf (bool): If True, begin profiling the node with `perf` as soon as the node starts. """ self.index = i self.datadir = datadir self.stdout_dir = os.path.join(self.datadir, "stdout") self.stderr_dir = os.path.join(self.datadir, "stderr") self.rpchost = rpchost self.rpc_timeout = timewait self.binary = bitcoind self.coverage_dir = coverage_dir self.cwd = cwd if extra_conf is not None: append_config(datadir, extra_conf) # Most callers will just need to add extra args to the standard list below. # For those callers that need more flexibility, they can just set the args property directly. # Note that common args are set in the config file (see initialize_datadir) self.extra_args = extra_args self.args = [ self.binary, "-datadir=" + self.datadir, "-logtimemicros", "-debug", "-debugexclude=libevent", "-debugexclude=leveldb", "-uacomment=testnode%d" % i, ] self.cli = TestNodeCLI(bitcoin_cli, self.datadir) self.use_cli = use_cli self.start_perf = start_perf self.running = False self.process = None self.rpc_connected = False self.rpc = None self.url = None self.log = logging.getLogger('TestFramework.node%d' % i) self.cleanup_on_exit = True # Whether to kill the node when this object goes away # Cache perf subprocesses here by their data output filename. self.perf_subprocesses = {} self.p2ps = [] def get_deterministic_priv_key(self): """Return a deterministic priv key in base58, that only depends on the node's index""" AddressKeyPair = collections.namedtuple('AddressKeyPair', ['address', 'key']) PRIV_KEYS = [ # address , privkey AddressKeyPair('mjTkW3DjgyZck4KbiRusZsqTgaYTxdSz6z', 'cVpF924EspNh8KjYsfhgY96mmxvT6DgdWiTYMtMjuM74hJaU5psW'), AddressKeyPair('msX6jQXvxiNhx3Q62PKeLPrhrqZQdSimTg', 'cUxsWyKyZ9MAQTaAhUQWJmBbSvHMwSmuv59KgxQV7oZQU3PXN3KE'), AddressKeyPair('mnonCMyH9TmAsSj3M59DsbH8H63U3RKoFP', 'cTrh7dkEAeJd6b3MRX9bZK8eRmNqVCMH3LSUkE3dSFDyzjU38QxK'), AddressKeyPair('mqJupas8Dt2uestQDvV2NH3RU8uZh2dqQR', 'cVuKKa7gbehEQvVq717hYcbE9Dqmq7KEBKqWgWrYBa2CKKrhtRim'), AddressKeyPair('msYac7Rvd5ywm6pEmkjyxhbCDKqWsVeYws', 'cQDCBuKcjanpXDpCqacNSjYfxeQj8G6CAtH1Dsk3cXyqLNC4RPuh'), AddressKeyPair('n2rnuUnwLgXqf9kk2kjvVm8R5BZK1yxQBi', 'cQakmfPSLSqKHyMFGwAqKHgWUiofJCagVGhiB4KCainaeCSxeyYq'), AddressKeyPair('myzuPxRwsf3vvGzEuzPfK9Nf2RfwauwYe6', 'cQMpDLJwA8DBe9NcQbdoSb1BhmFxVjWD5gRyrLZCtpuF9Zi3a9RK'), AddressKeyPair('mumwTaMtbxEPUswmLBBN3vM9oGRtGBrys8', 'cSXmRKXVcoouhNNVpcNKFfxsTsToY5pvB9DVsFksF1ENunTzRKsy'), AddressKeyPair('mpV7aGShMkJCZgbW7F6iZgrvuPHjZjH9qg', 'cSoXt6tm3pqy43UMabY6eUTmR3eSUYFtB2iNQDGgb3VUnRsQys2k'), ] return PRIV_KEYS[self.index] def get_mem_rss_kilobytes(self): """Get the memory usage (RSS) per `ps`. Returns None if `ps` is unavailable. """ assert self.running try: return int(subprocess.check_output( ["ps", "h", "-o", "rss", "{}".format(self.process.pid)], stderr=subprocess.DEVNULL).split()[-1]) # Avoid failing on platforms where ps isn't installed. # # We could later use something like `psutils` to work across platforms. except (FileNotFoundError, subprocess.SubprocessError): self.log.exception("Unable to get memory usage") return None def _node_msg(self, msg: str) -> str: """Return a modified msg that identifies this node by its index as a debugging aid.""" return "[node %d] %s" % (self.index, msg) def _raise_assertion_error(self, msg: str): """Raise an AssertionError with msg modified to identify this node.""" raise AssertionError(self._node_msg(msg)) def __del__(self): # Ensure that we don't leave any bitcoind processes lying around after # the test ends if self.process and self.cleanup_on_exit: # Should only happen on test failure # Avoid using logger, as that may have already been shutdown when # this destructor is called. print(self._node_msg("Cleaning up leftover process")) self.process.kill() def __getattr__(self, name): """Dispatches any unrecognised messages to the RPC connection or a CLI instance.""" if self.use_cli: return getattr(self.cli, name) else: assert self.rpc_connected and self.rpc is not None, self._node_msg("Error: no RPC connection") return getattr(self.rpc, name) def start(self, extra_args=None, *, cwd=None, stdout=None, stderr=None, **kwargs): """Start the node.""" if extra_args is None: extra_args = self.extra_args # Add a new stdout and stderr file each time bitcoind is started if stderr is None: stderr = tempfile.NamedTemporaryFile(dir=self.stderr_dir, delete=False) if stdout is None: stdout = tempfile.NamedTemporaryFile(dir=self.stdout_dir, delete=False) self.stderr = stderr self.stdout = stdout if cwd is None: cwd = self.cwd # Delete any existing cookie file -- if such a file exists (eg due to # unclean shutdown), it will get overwritten anyway by bitcoind, and # potentially interfere with our attempt to authenticate delete_cookie_file(self.datadir) # add environment variable LIBC_FATAL_STDERR_=1 so that libc errors are written to stderr and not the terminal subp_env = dict(os.environ, LIBC_FATAL_STDERR_="1") self.process = subprocess.Popen(self.args + extra_args, env=subp_env, stdout=stdout, stderr=stderr, cwd=cwd, **kwargs) self.running = True self.log.debug("buttcoind started, waiting for RPC to come up") if self.start_perf: self._start_perf() def wait_for_rpc_connection(self): """Sets up an RPC connection to the buttcoind process. Returns False if unable to connect.""" # Poll at a rate of four times per second poll_per_s = 4 for _ in range(poll_per_s * self.rpc_timeout): if self.process.poll() is not None: raise FailedToStartError(self._node_msg( 'buttcoind exited with status {} during initialization'.format(self.process.returncode))) try: rpc = get_rpc_proxy(rpc_url(self.datadir, self.index, self.rpchost), self.index, timeout=self.rpc_timeout, coveragedir=self.coverage_dir) rpc.getblockcount() # If the call to getblockcount() succeeds then the RPC connection is up self.log.debug("RPC successfully started") if self.use_cli: return self.rpc = rpc self.rpc_connected = True self.url = self.rpc.url return except IOError as e: if e.errno != errno.ECONNREFUSED: # Port not yet open? raise # unknown IO error except JSONRPCException as e: # Initialization phase # -28 RPC in warmup # -342 Service unavailable, RPC server started but is shutting down due to error if e.error['code'] != -28 and e.error['code'] != -342: raise # unknown JSON RPC exception except ValueError as e: # cookie file not found and no rpcuser or rpcassword. bitcoind still starting if "No RPC credentials" not in str(e): raise time.sleep(1.0 / poll_per_s) self._raise_assertion_error("Unable to connect to buttcoind") def generate(self, nblocks, maxtries=1000000): self.log.debug("TestNode.generate() dispatches `generate` call to `generatetoaddress`") return self.generatetoaddress(nblocks=nblocks, address=self.get_deterministic_priv_key().address, maxtries=maxtries) def get_wallet_rpc(self, wallet_name): if self.use_cli: return self.cli("-rpcwallet={}".format(wallet_name)) else: assert self.rpc_connected and self.rpc, self._node_msg("RPC not connected") wallet_path = "wallet/{}".format(urllib.parse.quote(wallet_name)) return self.rpc / wallet_path def stop_node(self, expected_stderr='', wait=0): """Stop the node.""" if not self.running: return self.log.debug("Stopping node") try: self.stop(wait=wait) except http.client.CannotSendRequest: self.log.exception("Unable to stop node.") # If there are any running perf processes, stop them. for profile_name in tuple(self.perf_subprocesses.keys()): self._stop_perf(profile_name) # Check that stderr is as expected self.stderr.seek(0) stderr = self.stderr.read().decode('utf-8').strip() if stderr != expected_stderr: raise AssertionError("Unexpected stderr {} != {}".format(stderr, expected_stderr)) self.stdout.close() self.stderr.close() del self.p2ps[:] def is_node_stopped(self): """Checks whether the node has stopped. Returns True if the node has stopped. False otherwise. This method is responsible for freeing resources (self.process).""" if not self.running: return True return_code = self.process.poll() if return_code is None: return False # process has stopped. Assert that it didn't return an error code. assert return_code == 0, self._node_msg( "Node returned non-zero exit code (%d) when stopping" % return_code) self.running = False self.process = None self.rpc_connected = False self.rpc = None self.log.debug("Node stopped") return True def wait_until_stopped(self, timeout=BITCOIND_PROC_WAIT_TIMEOUT): wait_until(self.is_node_stopped, timeout=timeout) @contextlib.contextmanager def assert_debug_log(self, expected_msgs): debug_log = os.path.join(self.datadir, 'regtest', 'debug.log') with open(debug_log, encoding='utf-8') as dl: dl.seek(0, 2) prev_size = dl.tell() try: yield finally: with open(debug_log, encoding='utf-8') as dl: dl.seek(prev_size) log = dl.read() print_log = " - " + "\n - ".join(log.splitlines()) for expected_msg in expected_msgs: if re.search(re.escape(expected_msg), log, flags=re.MULTILINE) is None: self._raise_assertion_error('Expected message "{}" does not partially match log:\n\n{}\n\n'.format(expected_msg, print_log)) @contextlib.contextmanager def assert_memory_usage_stable(self, *, increase_allowed=0.03): """Context manager that allows the user to assert that a node's memory usage (RSS) hasn't increased beyond some threshold percentage. Args: increase_allowed (float): the fractional increase in memory allowed until failure; e.g. `0.12` for up to 12% increase allowed. """ before_memory_usage = self.get_mem_rss_kilobytes() yield after_memory_usage = self.get_mem_rss_kilobytes() if not (before_memory_usage and after_memory_usage): self.log.warning("Unable to detect memory usage (RSS) - skipping memory check.") return perc_increase_memory_usage = (after_memory_usage / before_memory_usage) - 1 if perc_increase_memory_usage > increase_allowed: self._raise_assertion_error( "Memory usage increased over threshold of {:.3f}% from {} to {} ({:.3f}%)".format( increase_allowed * 100, before_memory_usage, after_memory_usage, perc_increase_memory_usage * 100)) @contextlib.contextmanager def profile_with_perf(self, profile_name): """ Context manager that allows easy profiling of node activity using `perf`. See `test/functional/README.md` for details on perf usage. Args: profile_name (str): This string will be appended to the profile data filename generated by perf. """ subp = self._start_perf(profile_name) yield if subp: self._stop_perf(profile_name) def _start_perf(self, profile_name=None): """Start a perf process to profile this node. Returns the subprocess running perf.""" subp = None def test_success(cmd): return subprocess.call( # shell=True required for pipe use below cmd, shell=True, stderr=subprocess.DEVNULL, stdout=subprocess.DEVNULL) == 0 if not sys.platform.startswith('linux'): self.log.warning("Can't profile with perf; only availabe on Linux platforms") return None if not test_success('which perf'): self.log.warning("Can't profile with perf; must install perf-tools") return None if not test_success('readelf -S {} | grep .debug_str'.format(shlex.quote(self.binary))): self.log.warning( "perf output won't be very useful without debug symbols compiled into buttcoind") output_path = tempfile.NamedTemporaryFile( dir=self.datadir, prefix="{}.perf.data.".format(profile_name or 'test'), delete=False, ).name cmd = [ 'perf', 'record', '-g', # Record the callgraph. '--call-graph', 'dwarf', # Compatibility for gcc's --fomit-frame-pointer. '-F', '101', # Sampling frequency in Hz. '-p', str(self.process.pid), '-o', output_path, ] subp = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) self.perf_subprocesses[profile_name] = subp return subp def _stop_perf(self, profile_name): """Stop (and pop) a perf subprocess.""" subp = self.perf_subprocesses.pop(profile_name) output_path = subp.args[subp.args.index('-o') + 1] subp.terminate() subp.wait(timeout=10) stderr = subp.stderr.read().decode() if 'Consider tweaking /proc/sys/kernel/perf_event_paranoid' in stderr: self.log.warning( "perf couldn't collect data! Try " "'sudo sysctl -w kernel.perf_event_paranoid=-1'") else: report_cmd = "perf report -i {}".format(output_path) self.log.info("See perf output by running '{}'".format(report_cmd)) def assert_start_raises_init_error(self, extra_args=None, expected_msg=None, match=ErrorMatch.FULL_TEXT, *args, **kwargs): """Attempt to start the node and expect it to raise an error. extra_args: extra arguments to pass through to buttcoind expected_msg: regex that stderr should match when buttcoind fails Will throw if buttcoind starts without an error. Will throw if an expected_msg is provided and it does not match buttcoind's stdout.""" with tempfile.NamedTemporaryFile(dir=self.stderr_dir, delete=False) as log_stderr, \ tempfile.NamedTemporaryFile(dir=self.stdout_dir, delete=False) as log_stdout: try: self.start(extra_args, stdout=log_stdout, stderr=log_stderr, *args, **kwargs) self.wait_for_rpc_connection() self.stop_node() self.wait_until_stopped() except FailedToStartError as e: self.log.debug('buttcoind failed to start: %s', e) self.running = False self.process = None # Check stderr for expected message if expected_msg is not None: log_stderr.seek(0) stderr = log_stderr.read().decode('utf-8').strip() if match == ErrorMatch.PARTIAL_REGEX: if re.search(expected_msg, stderr, flags=re.MULTILINE) is None: self._raise_assertion_error( 'Expected message "{}" does not partially match stderr:\n"{}"'.format(expected_msg, stderr)) elif match == ErrorMatch.FULL_REGEX: if re.fullmatch(expected_msg, stderr) is None: self._raise_assertion_error( 'Expected message "{}" does not fully match stderr:\n"{}"'.format(expected_msg, stderr)) elif match == ErrorMatch.FULL_TEXT: if expected_msg != stderr: self._raise_assertion_error( 'Expected message "{}" does not fully match stderr:\n"{}"'.format(expected_msg, stderr)) else: if expected_msg is None: assert_msg = "buttcoind should have exited with an error" else: assert_msg = "buttcoind should have exited with expected error " + expected_msg self._raise_assertion_error(assert_msg) def add_p2p_connection(self, p2p_conn, *, wait_for_verack=True, **kwargs): """Add a p2p connection to the node. This method adds the p2p connection to the self.p2ps list and also returns the connection to the caller.""" if 'dstport' not in kwargs: kwargs['dstport'] = p2p_port(self.index) if 'dstaddr' not in kwargs: kwargs['dstaddr'] = '127.0.0.1' p2p_conn.peer_connect(**kwargs)() self.p2ps.append(p2p_conn) if wait_for_verack: p2p_conn.wait_for_verack() return p2p_conn @property def p2p(self): """Return the first p2p connection Convenience property - most tests only use a single p2p connection to each node, so this saves having to write node.p2ps[0] many times.""" assert self.p2ps, self._node_msg("No p2p connection") return self.p2ps[0] def disconnect_p2ps(self): """Close all p2p connections to the node.""" for p in self.p2ps: p.peer_disconnect() del self.p2ps[:] class TestNodeCLIAttr: def __init__(self, cli, command): self.cli = cli self.command = command def __call__(self, *args, **kwargs): return self.cli.send_cli(self.command, *args, **kwargs) def get_request(self, *args, **kwargs): return lambda: self(*args, **kwargs) def arg_to_cli(arg): if isinstance(arg, bool): return str(arg).lower() elif isinstance(arg, dict) or isinstance(arg, list): return json.dumps(arg) else: return str(arg) class TestNodeCLI(): """Interface to buttcoin-cli for an individual node""" def __init__(self, binary, datadir): self.options = [] self.binary = binary self.datadir = datadir self.input = None self.log = logging.getLogger('TestFramework.bitcoincli') def __call__(self, *options, input=None): # TestNodeCLI is callable with bitcoin-cli command-line options cli = TestNodeCLI(self.binary, self.datadir) cli.options = [str(o) for o in options] cli.input = input return cli def __getattr__(self, command): return TestNodeCLIAttr(self, command) def batch(self, requests): results = [] for request in requests: try: results.append(dict(result=request())) except JSONRPCException as e: results.append(dict(error=e)) return results def send_cli(self, command=None, *args, **kwargs): """Run buttcoin-cli command. Deserializes returned string as python object.""" pos_args = [arg_to_cli(arg) for arg in args] named_args = [str(key) + "=" + arg_to_cli(value) for (key, value) in kwargs.items()] assert not (pos_args and named_args), "Cannot use positional arguments and named arguments in the same buttcoin-cli call" p_args = [self.binary, "-datadir=" + self.datadir] + self.options if named_args: p_args += ["-named"] if command is not None: p_args += [command] p_args += pos_args + named_args self.log.debug("Running buttcoin-cli command: %s" % command) process = subprocess.Popen(p_args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) cli_stdout, cli_stderr = process.communicate(input=self.input) returncode = process.poll() if returncode: match = re.match(r'error code: ([-0-9]+)\nerror message:\n(.*)', cli_stderr) if match: code, message = match.groups() raise JSONRPCException(dict(code=int(code), message=message)) # Ignore cli_stdout, raise with cli_stderr raise subprocess.CalledProcessError(returncode, self.binary, output=cli_stderr) try: return json.loads(cli_stdout, parse_float=decimal.Decimal) except JSONDecodeError: return cli_stdout.rstrip("\n")
41.070175
166
0.625288
e0b77036d8ef3df9339b7bbfc8f9d8e4c1935c9f
8,678
py
Python
ramses/acl.py
timgates42/ramses
ea2e1e896325b7256cdf5902309e05fd98e0c14c
[ "Apache-2.0" ]
178
2016-01-29T10:59:56.000Z
2021-09-17T18:28:24.000Z
ramses/acl.py
timgates42/ramses
ea2e1e896325b7256cdf5902309e05fd98e0c14c
[ "Apache-2.0" ]
35
2015-03-31T19:52:23.000Z
2016-01-11T22:44:30.000Z
ramses/acl.py
timgates42/ramses
ea2e1e896325b7256cdf5902309e05fd98e0c14c
[ "Apache-2.0" ]
24
2016-02-12T02:38:28.000Z
2020-06-20T23:35:38.000Z
import logging import six from pyramid.security import ( Allow, Deny, Everyone, Authenticated, ALL_PERMISSIONS) from nefertari.acl import CollectionACL from nefertari.resource import PERMISSIONS from nefertari.elasticsearch import ES from .utils import resolve_to_callable, is_callable_tag log = logging.getLogger(__name__) actions = { 'allow': Allow, 'deny': Deny, } special_principals = { 'everyone': Everyone, 'authenticated': Authenticated, } ALLOW_ALL = (Allow, Everyone, ALL_PERMISSIONS) def validate_permissions(perms): """ Validate :perms: contains valid permissions. :param perms: List of permission names or ALL_PERMISSIONS. """ if not isinstance(perms, (list, tuple)): perms = [perms] valid_perms = set(PERMISSIONS.values()) if ALL_PERMISSIONS in perms: return perms if set(perms) - valid_perms: raise ValueError( 'Invalid ACL permission names. Valid permissions ' 'are: {}'.format(', '.join(valid_perms))) return perms def parse_permissions(perms): """ Parse permissions ("perms") which are either exact permission names or the keyword 'all'. :param perms: List or comma-separated string of nefertari permission names, or 'all' """ if isinstance(perms, six.string_types): perms = perms.split(',') perms = [perm.strip().lower() for perm in perms] if 'all' in perms: return ALL_PERMISSIONS return validate_permissions(perms) def parse_acl(acl_string): """ Parse raw string :acl_string: of RAML-defined ACLs. If :acl_string: is blank or None, all permissions are given. Values of ACL action and principal are parsed using `actions` and `special_principals` maps and are looked up after `strip()` and `lower()`. ACEs in :acl_string: may be separated by newlines or semicolons. Action, principal and permission lists must be separated by spaces. Permissions must be comma-separated. E.g. 'allow everyone view,create,update' and 'deny authenticated delete' :param acl_string: Raw RAML string containing defined ACEs. """ if not acl_string: return [ALLOW_ALL] aces_list = acl_string.replace('\n', ';').split(';') aces_list = [ace.strip().split(' ', 2) for ace in aces_list if ace] aces_list = [(a, b, c.split(',')) for a, b, c in aces_list] result_acl = [] for action_str, princ_str, perms in aces_list: # Process action action_str = action_str.strip().lower() action = actions.get(action_str) if action is None: raise ValueError( 'Unknown ACL action: {}. Valid actions: {}'.format( action_str, list(actions.keys()))) # Process principal princ_str = princ_str.strip().lower() if princ_str in special_principals: principal = special_principals[princ_str] elif is_callable_tag(princ_str): principal = resolve_to_callable(princ_str) else: principal = princ_str # Process permissions permissions = parse_permissions(perms) result_acl.append((action, principal, permissions)) return result_acl class BaseACL(CollectionACL): """ ACL Base class. """ es_based = False _collection_acl = (ALLOW_ALL, ) _item_acl = (ALLOW_ALL, ) def _apply_callables(self, acl, obj=None): """ Iterate over ACEs from :acl: and apply callable principals if any. Principals are passed 3 arguments on call: :ace: Single ACE object that looks like (action, callable, permission or [permission]) :request: Current request object :obj: Object instance to be accessed via the ACL Principals must return a single ACE or a list of ACEs. :param acl: Sequence of valid Pyramid ACEs which will be processed :param obj: Object to be accessed via the ACL """ new_acl = [] for i, ace in enumerate(acl): principal = ace[1] if six.callable(principal): ace = principal(ace=ace, request=self.request, obj=obj) if not ace: continue if not isinstance(ace[0], (list, tuple)): ace = [ace] ace = [(a, b, validate_permissions(c)) for a, b, c in ace] else: ace = [ace] new_acl += ace return tuple(new_acl) def __acl__(self): """ Apply callables to `self._collection_acl` and return result. """ return self._apply_callables(acl=self._collection_acl) def generate_item_acl(self, item): acl = self._apply_callables( acl=self._item_acl, obj=item) if acl is None: acl = self.__acl__() return acl def item_acl(self, item): """ Apply callables to `self._item_acl` and return result. """ return self.generate_item_acl(item) def item_db_id(self, key): # ``self`` can be used for current authenticated user key if key != 'self': return key user = getattr(self.request, 'user', None) if user is None or not isinstance(user, self.item_model): return key return getattr(user, user.pk_field()) def __getitem__(self, key): """ Get item using method depending on value of `self.es_based` """ if not self.es_based: return super(BaseACL, self).__getitem__(key) return self.getitem_es(self.item_db_id(key)) def getitem_es(self, key): es = ES(self.item_model.__name__) obj = es.get_item(id=key) obj.__acl__ = self.item_acl(obj) obj.__parent__ = self obj.__name__ = key return obj class DatabaseACLMixin(object): """ Mixin to be used when ACLs are stored in database. """ def item_acl(self, item): """ Objectify ACL if ES is used or call item.get_acl() if db is used. """ if self.es_based: from nefertari_guards.elasticsearch import get_es_item_acl return get_es_item_acl(item) return super(DatabaseACLMixin, self).item_acl(item) def getitem_es(self, key): """ Override to support ACL filtering. To do so: passes `self.request` to `get_item` and uses `ACLFilterES`. """ from nefertari_guards.elasticsearch import ACLFilterES es = ACLFilterES(self.item_model.__name__) params = { 'id': key, 'request': self.request, } obj = es.get_item(**params) obj.__acl__ = self.item_acl(obj) obj.__parent__ = self obj.__name__ = key return obj def generate_acl(config, model_cls, raml_resource, es_based=True): """ Generate an ACL. Generated ACL class has a `item_model` attribute set to :model_cls:. ACLs used for collection and item access control are generated from a first security scheme with type `x-ACL`. If :raml_resource: has no x-ACL security schemes defined then ALLOW_ALL ACL is used. If the `collection` or `item` settings are empty, then ALLOW_ALL ACL is used. :param model_cls: Generated model class :param raml_resource: Instance of ramlfications.raml.ResourceNode for which ACL is being generated :param es_based: Boolean inidicating whether ACL should query ES or not when getting an object """ schemes = raml_resource.security_schemes or [] schemes = [sch for sch in schemes if sch.type == 'x-ACL'] if not schemes: collection_acl = item_acl = [] log.debug('No ACL scheme applied. Using ACL: {}'.format(item_acl)) else: sec_scheme = schemes[0] log.debug('{} ACL scheme applied'.format(sec_scheme.name)) settings = sec_scheme.settings or {} collection_acl = parse_acl(acl_string=settings.get('collection')) item_acl = parse_acl(acl_string=settings.get('item')) class GeneratedACLBase(object): item_model = model_cls def __init__(self, request, es_based=es_based): super(GeneratedACLBase, self).__init__(request=request) self.es_based = es_based self._collection_acl = collection_acl self._item_acl = item_acl bases = [GeneratedACLBase] if config.registry.database_acls: from nefertari_guards.acl import DatabaseACLMixin as GuardsMixin bases += [DatabaseACLMixin, GuardsMixin] bases.append(BaseACL) return type('GeneratedACL', tuple(bases), {})
32.74717
76
0.633326
4649e40cb56d32f9e28eb780786d15626bf91552
214
py
Python
Mundo #01/ex-035- a010 -triangulos-a010.py
freitasSystemOutPrint/Python3
e5e88fbe8e7e0c5472573d2c901844270385194b
[ "MIT" ]
1
2020-06-02T07:31:16.000Z
2020-06-02T07:31:16.000Z
Mundo #01/ex-035- a010 -triangulos-a010.py
freitasSystemOutPrint/Python3
e5e88fbe8e7e0c5472573d2c901844270385194b
[ "MIT" ]
null
null
null
Mundo #01/ex-035- a010 -triangulos-a010.py
freitasSystemOutPrint/Python3
e5e88fbe8e7e0c5472573d2c901844270385194b
[ "MIT" ]
null
null
null
n1 = float(input('Comprimento 01: ')) n2 = float(input('Comprimento 02: ')) n3 = float(input('Comprimento 03: ')) if n1 == n2 and n2 == n3: print('fomrma triangulo ! ') else: print('Não forma triangulo !')
26.75
37
0.626168
4b1fbf9b180d4cf51e99c01f4927a5bab041ed82
11,784
py
Python
roro/cli.py
Sunda001/roro-client
2d265a830b7ed2f32e46f9a9687a545a333e254e
[ "Apache-2.0" ]
1
2018-06-27T13:23:17.000Z
2018-06-27T13:23:17.000Z
roro/cli.py
Sunda001/roro-client
2d265a830b7ed2f32e46f9a9687a545a333e254e
[ "Apache-2.0" ]
3
2017-09-18T10:49:00.000Z
2018-09-27T09:06:34.000Z
roro/cli.py
Sunda001/roro-client
2d265a830b7ed2f32e46f9a9687a545a333e254e
[ "Apache-2.0" ]
2
2018-06-27T13:22:19.000Z
2019-07-01T18:12:22.000Z
from __future__ import print_function import time import itertools import click import datetime import os import sys import logging from tabulate import tabulate from . import config from . import projects from . import helpers as h from .projects import Project from . import auth from .path import Path from . import __version__ from .client import RoroClient from firefly.client import FireflyError from requests import ConnectionError class PathType(click.ParamType): name = 'path' def convert(self, value, param, ctx): return Path(value) class CatchAllExceptions(click.Group): def __call__(self, *args, **kwargs): try: return self.main(*args, **kwargs) except FireflyError as e: if e.args and e.args[0] == "Forbidden": click.echo("Unauthorized. Please login and try again.") sys.exit(2) else: click.echo('ERROR %s' % e) sys.exit(3) except Exception as exc: click.echo('ERROR %s' % exc) sys.exit(3) def setup_logger(verbose=False): level = logging.DEBUG if verbose else logging.INFO logging.basicConfig( level=level, format="%(asctime)s %(name)s [%(levelname)s] %(message)s" ) @click.group(cls=CatchAllExceptions) @click.version_option(version=__version__) def cli(verbose=False): if os.getenv("RORO_DEBUG"): setup_logger(verbose=True) @cli.command() @click.option('--email', prompt='Email address') @click.option('--password', prompt=True, hide_input=True) def login(email, password): """Login to rorodata platform. """ try: auth.login(email, password) click.echo("Login successful.") except ConnectionError: click.echo('unable to connect to the server, try again later') except FireflyError as e: click.echo(e) raise @cli.command() def version(): """Prints the version of roro client.""" cli.main(args=['--version']) @cli.command() def whoami(): """prints the details of current user. """ client = RoroClient(config.SERVER_URL) user = client.whoami() if user: click.echo(user['email']) else: click.echo("You are not logged in yet.") sys.exit(1) @cli.command(name="projects") def _projects(): """Lists all the projects. """ projects = Project.find_all() for p in projects: print(p.name) @cli.command() @click.argument('project') @click.option('--repo-url', help="Initialize the project with a git repo", default=None) def create(project, repo_url=None): """Creates a new Project. """ p = Project(project) if repo_url: task = p.create(repo_url=repo_url) click.echo("Waiting for the project to get created...") response = task.wait() click.echo(response) else: p.create() click.echo("Created project:", project) @cli.command(name="projects:delete") @click.argument('name') def project_delete(name): """Deletes a project """ p = Project(name) p.delete() click.echo("Project {} deleted successfully.".format(name)) @cli.command() def deploy(): """Pushes the local changes to the cloud and restarts all the services. """ # TODO: validate credentials project = projects.current_project(roroyml_required=True) task = project.deploy(async=True) response = task.wait() click.echo(response) @cli.command() @click.argument('src', type=PathType()) @click.argument('dest', type=PathType()) def cp(src, dest): """Copy files to and from volumes to you local disk. Example: $ roro cp volume:/dataset.txt ./dataset.txt downloads the file dataset.txt from the server $ roro cp ./dataset.txt volume:/dataset.txt uploads dataset.txt to the server """ if src.is_volume() is dest.is_volume(): raise Exception('One of the arguments has to be a volume, other a local path') project = projects.current_project() project.copy(src, dest) @cli.command() @click.option('-a', '--all', default=False, is_flag=True) def ps(all): """Shows all the processes running in this project. """ project = projects.current_project() jobs = project.ps(all=all) rows = [] for job in jobs: start = h.parse_time(job['start_time']) end = h.parse_time(job['end_time']) total_time = (end - start) total_time = datetime.timedelta(total_time.days, total_time.seconds) command = " ".join(job["details"]["command"]) rows.append([job['jobid'], job['status'], h.datestr(start), str(total_time), job['instance_type'], h.truncate(command, 50)]) print(tabulate(rows, headers=['JOBID', 'STATUS', 'WHEN', 'TIME', 'INSTANCE TYPE', 'CMD'], disable_numparse=True)) @cli.command(name='ps:restart') @click.argument('name') def ps_restart(name): """Restarts the service specified by name. """ pass @cli.command(name="config") def _config(): """Lists all config vars of this project. """ project = projects.current_project() config = project.get_config() print("=== {} Config Vars".format(project.name)) for k, v in config.items(): print("{}: {}".format(k, v)) @cli.command(name='config:set') @click.argument('vars', nargs=-1) def env_set(vars): """Sets one or more the config vars. """ project = projects.current_project() d = {} for var in vars: if "=" in var: k, v = var.split("=", 1) d[k] = v else: d[var] = "" project.set_config(d) print("Updated config vars") @cli.command(name='config:unset') @click.argument('names', nargs=-1) def env_unset(names): """Unsets one or more config vars. """ project = projects.current_project() project.unset_config(names) print("Updated config vars") @cli.command(context_settings={"allow_interspersed_args": False}) @click.option('-s', '--instance-size', help="size of the instance to run the job on") @click.argument('command', nargs=-1) def run(command, instance_size=None): """Runs the given script in foreground. """ project = projects.current_project() job = project.run(command, instance_size=instance_size) print("Started new job", job["jobid"]) @cli.command(name='run:notebook', context_settings={"allow_interspersed_args": False}) @click.option('-s', '--instance-size', help="size of the instance to run the job on") def run_notebook(instance_size=None): """Runs a notebook. """ project = projects.current_project() job = project.run_notebook(instance_size=instance_size) _logs(project, job["jobid"], follow=True, end_marker="-" * 40) @cli.command() @click.argument('jobid') def stop(jobid): """Stops a job by service name or job id. """ project = projects.current_project() project.stop(jobid) @cli.command() @click.argument('service_name') def start(service_name): """Starts the service specified by the given name. """ project = projects.current_project() project.start_service(service_name) @cli.command() @click.argument('service_name') def restart(service_name): """Restarts the service specified by the given name. """ project = projects.current_project() project.restart_service(service_name) @cli.command() @click.argument('jobid') @click.option('-s', '--show-timestamp', default=False, is_flag=True) @click.option('-f', '--follow', default=False, is_flag=True) def logs(jobid, show_timestamp, follow): """Shows all the logs of the project. """ project = projects.current_project() _logs(project, jobid, follow, show_timestamp) def _logs(project, job_id, follow=False, show_timestamp=False, end_marker=None): """Shows the logs of job_id. """ def get_logs(job_id, follow=False): if follow: seen = 0 while True: logs = project.logs(job_id) for log in logs[seen:]: yield log seen = len(logs) job = project.ps(job_id) if job['status'] in ['success', 'cancelled', 'failed']: break time.sleep(0.5) else: logs = project.logs(job_id) for log in logs: yield log logs = get_logs(job_id, follow) if end_marker: logs = itertools.takewhile(lambda log: not log['message'].startswith(end_marker), logs) _display_logs(logs, show_timestamp=show_timestamp) def _display_logs(logs, show_timestamp=False): def parse_time(timestamp): t = datetime.datetime.fromtimestamp(timestamp//1000) return t.isoformat() if show_timestamp: log_pattern = "[{timestamp}] {message}" else: log_pattern = "{message}" for line in logs: line['timestamp'] = parse_time(line['timestamp']) click.echo(log_pattern.format(**line)) @cli.command() @click.argument('project') def project_logs(project): """Shows all the logs of the process with name <project> the project. """ pass @cli.command() def volumes(): """Lists all the volumes. """ project = projects.current_project() volumes = project.list_volumes() if not volumes: click.echo('No volumes are attached to {}'.format(project.name)) for volume in project.list_volumes(): click.echo(volume) @cli.command(name='volumes:add') @click.argument('volume_name') def create_volume(volume_name): """Creates a new volume. """ project = projects.current_project() volume = project.add_volume(volume_name) click.echo('Volume {} added to the project {}'.format(volume, project.name)) @cli.command(name='volumes:remove') @click.argument('volume_name') def remove_volume(volume_name): """Removes a new volume. """ pass @cli.command(name='volumes:ls') @click.argument('path') def ls_volume(path): """Lists you files in a volume. Example: \b roro volume:ls <volume_name> lists all files in volume "volume_name" \b roro volume:ls <volume_name:dir> lists all filies at directory "dir" in volume "volume" """ path = path+':' if ':' not in path else path path = Path(path) project = projects.current_project() stat = project.ls(path) rows = [[item['mode'], item['size'], item['name']] for item in stat] click.echo(tabulate(rows, tablefmt='plain')) @cli.command() def models(): project = projects.current_project() for repo in project.list_model_repositories(): print(repo.name) @cli.command(name="models:log") @click.argument('name', required=False) @click.option('-a', '--all', default=False, is_flag=True, help="Show all fields") def models_log(name=None, all=False): project = projects.current_project() images = project.get_model_activity(repo=name) for im in images: if all: print(im) else: print(im.get_summary()) @cli.command(name="models:show") @click.argument('modelref') def models_show(modelref): project = projects.current_project() model = modelref tag = None version = None if ":" in modelref: model, version_or_tag = modelref.split(":", 1) if version_or_tag.isnumeric(): version = int(version_or_tag) else: tag = version_or_tag repo = project.get_model_repository(model) image = repo and repo.get_model_image(version=version, tag=tag) if not image: click.echo("Invalid model reference {!r}".format(model)) sys.exit(1) print(image) def main_dev(): config.SERVER_URL = "http://api.local.rorodata.com:8080/" cli()
28.601942
132
0.639087
d1d3bc124e81144461f1456decb40d45cdd5d8fa
730
py
Python
tyrell/venv/lib/python3.8/site-packages/rpy2/tests/robjects/test_formula.py
YuehanLee/CS190I
c5e3dca9f3b936a15b254abfd0c245c470e8c27e
[ "Apache-2.0" ]
null
null
null
tyrell/venv/lib/python3.8/site-packages/rpy2/tests/robjects/test_formula.py
YuehanLee/CS190I
c5e3dca9f3b936a15b254abfd0c245c470e8c27e
[ "Apache-2.0" ]
null
null
null
tyrell/venv/lib/python3.8/site-packages/rpy2/tests/robjects/test_formula.py
YuehanLee/CS190I
c5e3dca9f3b936a15b254abfd0c245c470e8c27e
[ "Apache-2.0" ]
null
null
null
import pytest import rpy2.robjects as robjects rinterface = robjects.rinterface def test_init(): fml = robjects.Formula('y ~ x') assert fml.rclass[0] == 'formula' def test_getenvironment(): fml = robjects.Formula('y ~ x') env = fml.getenvironment() assert env.rclass[0] == 'environment' def test_setenvironment(): fml = robjects.Formula('y ~ x') newenv = robjects.baseenv['new.env']() env = fml.getenvironment() assert not newenv.rsame(env) fml.setenvironment(newenv) env = fml.getenvironment() assert newenv.rsame(env) def test_setenvironment_error(): fml = robjects.Formula('y ~ x') with pytest.raises(TypeError): fml.setenvironment(rinterface.NA_Logical)
23.548387
49
0.680822
b94164a7208d393ad14fd16f6eca9cbdb916ae52
11,663
py
Python
tests/test_auth.py
timgates42/ramses
ea2e1e896325b7256cdf5902309e05fd98e0c14c
[ "Apache-2.0" ]
178
2016-01-29T10:59:56.000Z
2021-09-17T18:28:24.000Z
tests/test_auth.py
timgates42/ramses
ea2e1e896325b7256cdf5902309e05fd98e0c14c
[ "Apache-2.0" ]
35
2015-03-31T19:52:23.000Z
2016-01-11T22:44:30.000Z
tests/test_auth.py
timgates42/ramses
ea2e1e896325b7256cdf5902309e05fd98e0c14c
[ "Apache-2.0" ]
24
2016-02-12T02:38:28.000Z
2020-06-20T23:35:38.000Z
import pytest from mock import Mock, patch from nefertari.utils import dictset from pyramid.security import Allow, ALL_PERMISSIONS from .fixtures import engine_mock, guards_engine_mock @pytest.mark.usefixtures('engine_mock') class TestACLAssignRegisterMixin(object): def _dummy_view(self): from ramses import auth class DummyBase(object): def register(self, *args, **kwargs): return 1 class DummyView(auth.ACLAssignRegisterMixin, DummyBase): def __init__(self, *args, **kwargs): super(DummyView, self).__init__(*args, **kwargs) self.Model = Mock() self.request = Mock(_user=Mock()) self.request.registry._model_collections = {} return DummyView def test_register_acl_present(self): DummyView = self._dummy_view() view = DummyView() view.request._user._acl = ['a'] assert view.register() == 1 assert view.request._user._acl == ['a'] def test_register_no_model_collection(self): DummyView = self._dummy_view() view = DummyView() view.Model.__name__ = 'Foo' view.request._user._acl = [] assert view.register() == 1 assert view.request._user._acl == [] def test_register_acl_set(self, guards_engine_mock): DummyView = self._dummy_view() view = DummyView() view.Model.__name__ = 'Foo' resource = Mock() view.request.registry._model_collections['Foo'] = resource view.request._user._acl = [] assert view.register() == 1 factory = resource.view._factory factory.assert_called_once_with(view.request) factory().generate_item_acl.assert_called_once_with( view.request._user) guards_engine_mock.ACLField.stringify_acl.assert_called_once_with( factory().generate_item_acl()) view.request._user.update.assert_called_once_with( {'_acl': guards_engine_mock.ACLField.stringify_acl()}) @pytest.mark.usefixtures('engine_mock') class TestSetupTicketPolicy(object): def test_no_secret(self): from ramses import auth with pytest.raises(ValueError) as ex: auth._setup_ticket_policy(config='', params={}) expected = 'Missing required security scheme settings: secret' assert expected == str(ex.value) @patch('ramses.auth.AuthTktAuthenticationPolicy') def test_params_converted(self, mock_policy): from ramses import auth params = dictset( secure=True, include_ip=True, http_only=False, wild_domain=True, debug=True, parent_domain=True, secret='my_secret_setting' ) auth_model = Mock() config = Mock() config.registry.settings = {'my_secret_setting': 12345} config.registry.auth_model = auth_model auth._setup_ticket_policy(config=config, params=params) mock_policy.assert_called_once_with( include_ip=True, secure=True, parent_domain=True, callback=auth_model.get_groups_by_userid, secret=12345, wild_domain=True, debug=True, http_only=False ) @patch('ramses.auth.AuthTktAuthenticationPolicy') def test_request_method_added(self, mock_policy): from ramses import auth config = Mock() config.registry.settings = {'my_secret': 12345} config.registry.auth_model = Mock() policy = auth._setup_ticket_policy( config=config, params={'secret': 'my_secret'}) config.add_request_method.assert_called_once_with( config.registry.auth_model.get_authuser_by_userid, 'user', reify=True) assert policy == mock_policy() @patch('ramses.auth.AuthTktAuthenticationPolicy') def test_routes_views_added(self, mock_policy): from ramses import auth config = Mock() config.registry.settings = {'my_secret': 12345} config.registry.auth_model = Mock() root = Mock() config.get_root_resource.return_value = root auth._setup_ticket_policy( config=config, params={'secret': 'my_secret'}) assert root.add.call_count == 3 login, logout, register = root.add.call_args_list login_kwargs = login[1] assert sorted(login_kwargs.keys()) == sorted([ 'view', 'prefix', 'factory']) assert login_kwargs['prefix'] == 'auth' assert login_kwargs['factory'] == 'nefertari.acl.AuthenticationACL' logout_kwargs = logout[1] assert sorted(logout_kwargs.keys()) == sorted([ 'view', 'prefix', 'factory']) assert logout_kwargs['prefix'] == 'auth' assert logout_kwargs['factory'] == 'nefertari.acl.AuthenticationACL' register_kwargs = register[1] assert sorted(register_kwargs.keys()) == sorted([ 'view', 'prefix', 'factory']) assert register_kwargs['prefix'] == 'auth' assert register_kwargs['factory'] == 'nefertari.acl.AuthenticationACL' @pytest.mark.usefixtures('engine_mock') class TestSetupApiKeyPolicy(object): @patch('ramses.auth.ApiKeyAuthenticationPolicy') def test_policy_params(self, mock_policy): from ramses import auth auth_model = Mock() config = Mock() config.registry.auth_model = auth_model policy = auth._setup_apikey_policy(config, {'foo': 'bar'}) mock_policy.assert_called_once_with( foo='bar', check=auth_model.get_groups_by_token, credentials_callback=auth_model.get_token_credentials, user_model=auth_model, ) assert policy == mock_policy() @patch('ramses.auth.ApiKeyAuthenticationPolicy') def test_routes_views_added(self, mock_policy): from ramses import auth auth_model = Mock() config = Mock() config.registry.auth_model = auth_model root = Mock() config.get_root_resource.return_value = root auth._setup_apikey_policy(config, {}) assert root.add.call_count == 3 token, reset_token, register = root.add.call_args_list token_kwargs = token[1] assert sorted(token_kwargs.keys()) == sorted([ 'view', 'prefix', 'factory']) assert token_kwargs['prefix'] == 'auth' assert token_kwargs['factory'] == 'nefertari.acl.AuthenticationACL' reset_token_kwargs = reset_token[1] assert sorted(reset_token_kwargs.keys()) == sorted([ 'view', 'prefix', 'factory']) assert reset_token_kwargs['prefix'] == 'auth' assert reset_token_kwargs['factory'] == 'nefertari.acl.AuthenticationACL' register_kwargs = register[1] assert sorted(register_kwargs.keys()) == sorted([ 'view', 'prefix', 'factory']) assert register_kwargs['prefix'] == 'auth' assert register_kwargs['factory'] == 'nefertari.acl.AuthenticationACL' @pytest.mark.usefixtures('engine_mock') class TestSetupAuthPolicies(object): def test_not_secured(self): from ramses import auth raml_data = Mock(secured_by=[None]) config = Mock() auth.setup_auth_policies(config, raml_data) assert not config.set_authentication_policy.called assert not config.set_authorization_policy.called def test_not_defined_security_scheme(self): from ramses import auth scheme = Mock() scheme.name = 'foo' raml_data = Mock(secured_by=['zoo'], security_schemes=[scheme]) with pytest.raises(ValueError) as ex: auth.setup_auth_policies('asd', raml_data) expected = 'Undefined security scheme used in `secured_by`: zoo' assert expected == str(ex.value) def test_not_supported_scheme_type(self): from ramses import auth scheme = Mock(type='asd123') scheme.name = 'foo' raml_data = Mock(secured_by=['foo'], security_schemes=[scheme]) with pytest.raises(ValueError) as ex: auth.setup_auth_policies(None, raml_data) expected = 'Unsupported security scheme type: asd123' assert expected == str(ex.value) @patch('ramses.auth.ACLAuthorizationPolicy') def test_policies_calls(self, mock_acl): from ramses import auth scheme = Mock(type='mytype', settings={'name': 'user1'}) scheme.name = 'foo' raml_data = Mock(secured_by=['foo'], security_schemes=[scheme]) config = Mock() mock_setup = Mock() with patch.dict(auth.AUTHENTICATION_POLICIES, {'mytype': mock_setup}): auth.setup_auth_policies(config, raml_data) mock_setup.assert_called_once_with(config, {'name': 'user1'}) config.set_authentication_policy.assert_called_once_with( mock_setup()) mock_acl.assert_called_once_with() config.set_authorization_policy.assert_called_once_with( mock_acl()) @pytest.mark.usefixtures('engine_mock') class TestHelperFunctions(object): def test_create_system_user_key_error(self): from ramses import auth config = Mock() config.registry.settings = {} auth.create_system_user(config) assert not config.registry.auth_model.get_or_create.called @patch('ramses.auth.transaction') @patch('ramses.auth.cryptacular') def test_create_system_user_exists(self, mock_crypt, mock_trans): from ramses import auth encoder = mock_crypt.bcrypt.BCRYPTPasswordManager() encoder.encode.return_value = '654321' config = Mock() config.registry.settings = { 'system.user': 'user12', 'system.password': '123456', 'system.email': 'user12@example.com', } config.registry.auth_model.get_or_create.return_value = (1, False) auth.create_system_user(config) assert not mock_trans.commit.called encoder.encode.assert_called_once_with('123456') config.registry.auth_model.get_or_create.assert_called_once_with( username='user12', defaults={ 'password': '654321', 'email': 'user12@example.com', 'groups': ['admin'], '_acl': [(Allow, 'g:admin', ALL_PERMISSIONS)], } ) @patch('ramses.auth.transaction') @patch('ramses.auth.cryptacular') def test_create_system_user_created(self, mock_crypt, mock_trans): from ramses import auth encoder = mock_crypt.bcrypt.BCRYPTPasswordManager() encoder.encode.return_value = '654321' config = Mock() config.registry.settings = { 'system.user': 'user12', 'system.password': '123456', 'system.email': 'user12@example.com', } config.registry.auth_model.get_or_create.return_value = ( Mock(), True) auth.create_system_user(config) mock_trans.commit.assert_called_once_with() encoder.encode.assert_called_once_with('123456') config.registry.auth_model.get_or_create.assert_called_once_with( username='user12', defaults={ 'password': '654321', 'email': 'user12@example.com', 'groups': ['admin'], '_acl': [(Allow, 'g:admin', ALL_PERMISSIONS)], } ) @patch('ramses.auth.create_system_user') def test_includeme(self, mock_create): from ramses import auth auth.includeme(config=1) mock_create.assert_called_once_with(1)
38.747508
81
0.638944
57d420262a2dc3ba0cf40199963753050c0a2240
7,449
py
Python
mkdocs/__main__.py
UnsolvedCypher/mkdocs
eb31d4c0d70259755b779bd6bf34609ac2adca7b
[ "BSD-2-Clause" ]
null
null
null
mkdocs/__main__.py
UnsolvedCypher/mkdocs
eb31d4c0d70259755b779bd6bf34609ac2adca7b
[ "BSD-2-Clause" ]
null
null
null
mkdocs/__main__.py
UnsolvedCypher/mkdocs
eb31d4c0d70259755b779bd6bf34609ac2adca7b
[ "BSD-2-Clause" ]
null
null
null
#!/usr/bin/env python import os import sys import logging import click from mkdocs import __version__ from mkdocs import utils from mkdocs import exceptions from mkdocs import config from mkdocs.commands import build, gh_deploy, new, serve log = logging.getLogger(__name__) class State: ''' Maintain logging level.''' def __init__(self, log_name='mkdocs', level=logging.INFO): self.logger = logging.getLogger(log_name) self.logger.propagate = False stream = logging.StreamHandler() formatter = logging.Formatter("%(levelname)-7s - %(message)s ") stream.setFormatter(formatter) self.logger.addHandler(stream) self.logger.setLevel(level) pass_state = click.make_pass_decorator(State, ensure=True) clean_help = "Remove old files from the site_dir before building (the default)." config_help = "Provide a specific MkDocs config" dev_addr_help = ("IP address and port to serve documentation locally (default: " "localhost:8000)") strict_help = ("Enable strict mode. This will cause MkDocs to abort the build " "on any warnings.") theme_help = "The theme to use when building your documentation." theme_choices = utils.get_theme_names() site_dir_help = "The directory to output the result of the documentation build." use_directory_urls_help = "Use directory URLs when building pages (the default)." reload_help = "Enable the live reloading in the development server (this is the default)" no_reload_help = "Disable the live reloading in the development server." dirty_reload_help = "Enable the live reloading in the development server, but only re-build files that have changed" commit_message_help = ("A commit message to use when committing to the " "Github Pages remote branch. Commit {sha} and MkDocs {version} are available as expansions") remote_branch_help = ("The remote branch to commit to for Github Pages. This " "overrides the value specified in config") remote_name_help = ("The remote name to commit to for Github Pages. This " "overrides the value specified in config") force_help = "Force the push to the repository." ignore_version_help = "Ignore check that build is not being deployed with an older version of MkDocs." watch_theme_help = ("Include the theme in list of files to watch for live reloading. " "Ignored when live reload is not used.") shell_help = "Use the shell when invoking Git." def add_options(opts): def inner(f): for i in reversed(opts): f = i(f) return f return inner def verbose_option(f): def callback(ctx, param, value): state = ctx.ensure_object(State) if value: state.logger.setLevel(logging.DEBUG) return click.option('-v', '--verbose', is_flag=True, expose_value=False, help='Enable verbose output', callback=callback)(f) def quiet_option(f): def callback(ctx, param, value): state = ctx.ensure_object(State) if value: state.logger.setLevel(logging.ERROR) return click.option('-q', '--quiet', is_flag=True, expose_value=False, help='Silence warnings', callback=callback)(f) common_options = add_options([quiet_option, verbose_option]) common_config_options = add_options([ click.option('-f', '--config-file', type=click.File('rb'), help=config_help), # Don't override config value if user did not specify --strict flag # Conveniently, load_config drops None values click.option('-s', '--strict', is_flag=True, default=None, help=strict_help), click.option('-t', '--theme', type=click.Choice(theme_choices), help=theme_help), # As with --strict, set the default to None so that this doesn't incorrectly # override the config file click.option('--use-directory-urls/--no-directory-urls', is_flag=True, default=None, help=use_directory_urls_help) ]) PYTHON_VERSION = sys.version[:3] PKG_DIR = os.path.dirname(os.path.abspath(__file__)) @click.group(context_settings={'help_option_names': ['-h', '--help']}) @click.version_option( __version__, '-V', '--version', message=f'%(prog)s, version %(version)s from { PKG_DIR } (Python { PYTHON_VERSION })' ) @common_options def cli(): """ MkDocs - Project documentation with Markdown. """ @cli.command(name="serve") @click.option('-a', '--dev-addr', help=dev_addr_help, metavar='<IP:PORT>') @click.option('--livereload', 'livereload', flag_value='livereload', help=reload_help, default=True) @click.option('--no-livereload', 'livereload', flag_value='no-livereload', help=no_reload_help) @click.option('--dirtyreload', 'livereload', flag_value='dirty', help=dirty_reload_help) @click.option('--watch-theme', help=watch_theme_help, is_flag=True) @common_config_options @common_options def serve_command(dev_addr, livereload, **kwargs): """Run the builtin development server""" logging.getLogger('tornado').setLevel(logging.WARNING) try: serve.serve( dev_addr=dev_addr, livereload=livereload, **kwargs ) except (exceptions.ConfigurationError, OSError) as e: # pragma: no cover # Avoid ugly, unhelpful traceback raise SystemExit('\n' + str(e)) @cli.command(name="build") @click.option('-c', '--clean/--dirty', is_flag=True, default=True, help=clean_help) @common_config_options @click.option('-d', '--site-dir', type=click.Path(), help=site_dir_help) @common_options def build_command(clean, **kwargs): """Build the MkDocs documentation""" try: build.build(config.load_config(**kwargs), dirty=not clean) except exceptions.ConfigurationError as e: # pragma: no cover # Avoid ugly, unhelpful traceback raise SystemExit('\n' + str(e)) @cli.command(name="gh-deploy") @click.option('-c', '--clean/--dirty', is_flag=True, default=True, help=clean_help) @click.option('-m', '--message', help=commit_message_help) @click.option('-b', '--remote-branch', help=remote_branch_help) @click.option('-r', '--remote-name', help=remote_name_help) @click.option('--force', is_flag=True, help=force_help) @click.option('--ignore-version', is_flag=True, help=ignore_version_help) @click.option('--shell', is_flag=True, help=shell_help) @common_config_options @click.option('-d', '--site-dir', type=click.Path(), help=site_dir_help) @common_options def gh_deploy_command(clean, message, remote_branch, remote_name, force, ignore_version, shell, **kwargs): """Deploy your documentation to GitHub Pages""" try: cfg = config.load_config( remote_branch=remote_branch, remote_name=remote_name, **kwargs ) build.build(cfg, dirty=not clean) gh_deploy.gh_deploy(cfg, message=message, force=force, ignore_version=ignore_version, shell=shell) except exceptions.ConfigurationError as e: # pragma: no cover # Avoid ugly, unhelpful traceback raise SystemExit('\n' + str(e)) @cli.command(name="new") @click.argument("project_directory") @common_options def new_command(project_directory): """Create a new MkDocs project""" new.new(project_directory) if __name__ == '__main__': # pragma: no cover cli()
37.812183
118
0.680226
cd409dcba34ad80acf6e2beb47eccaf651c72a2f
6,079
py
Python
parseAndPopulate/integrity.py
richardzilincikPantheon/backend
d70d9aa3baa113f5c8fc05fba84ae8b18b857b0c
[ "Apache-2.0" ]
2
2020-08-19T16:44:48.000Z
2021-04-30T06:48:16.000Z
parseAndPopulate/integrity.py
richardzilincikPantheon/backend
d70d9aa3baa113f5c8fc05fba84ae8b18b857b0c
[ "Apache-2.0" ]
243
2018-08-21T09:12:57.000Z
2022-03-31T12:31:48.000Z
parseAndPopulate/integrity.py
richardzilincikPantheon/backend
d70d9aa3baa113f5c8fc05fba84ae8b18b857b0c
[ "Apache-2.0" ]
25
2018-08-21T08:45:43.000Z
2021-12-12T13:51:47.000Z
# Copyright The IETF Trust 2019, All Rights Reserved # Copyright 2018 Cisco and its affiliates # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ This class serves to create integrity of yang files. It stores all the missing modules that are not in the directory and are in xml file or modules that have incorrect namespace, or modules with missing revision or missing submodules or even if we have extra files in the vendor directory - meaning that we have yang files in the directory that are not mentioned in capability xml file and/or are not included or imported by some module. """ __author__ = "Miroslav Kovac" __copyright__ = "Copyright 2018 Cisco and its affiliates, Copyright The IETF Trust 2019, All Rights Reserved" __license__ = "Apache License, Version 2.0" __email__ = "miroslav.kovac@pantheon.tech" import fnmatch import glob import os import time def find_missing_hello(directory, pattern): for root, dirs, files in os.walk(directory): for basename in files: if fnmatch.fnmatch(basename, pattern): if not any(".xml" in name for name in files): yield root class Statistics: useless_modules = {} missing_modules = {} missing_submodules = {} missing_revision = {} missing_wrong_namespaces = {} unique_modules_per_vendor = set() os = {} def __init__(self, path): Statistics.missing_modules[path] = set() Statistics.missing_submodules[path] = set() Statistics.missing_wrong_namespaces[path] = set() Statistics.missing_revision[path] = set() folder = path.split('/') os_type = '/'.join(path.split('/')[:-2]) folder.remove(path.split('/')[-1]) folder = '/'.join(folder) if os_type not in Statistics.os: Statistics.os[os_type] = set() if folder not in Statistics.useless_modules: Statistics.useless_modules[folder] = glob.glob(folder + '/*.yang') @staticmethod def add_platform(os_type, platform): Statistics.os[os_type] = platform @staticmethod def add_unique(modules_revision): Statistics.unique_modules_per_vendor.update(set(modules_revision)) @staticmethod def remove_one(key, value): if key + '/' + value in Statistics.useless_modules[key]: Statistics.useless_modules[key].remove(key + '/' + value) @staticmethod def dumps(file, yang_models): file.write('<!DOCTYPE html><html><body> <ul>' '<li>Generated on {}</li>' '</ul><h1>Yangcatalog statistics</h1>' .format(time.strftime("%d/%m/%y"))) file.write('<h3>YANG modules in directory but not present in any NETCONF hello message in that directory:</h3>') for key in Statistics.useless_modules: if len(Statistics.useless_modules[key]) > 0: file.write('<h5>' + key + ':</h5>') file.write('<p>' + ', '.join([value.split('/')[-1] for value in Statistics.useless_modules[key]]) + '</p>') file.write('<h3>YANG modules in NETCONF hello messages for a directory but the YANG modules is not present' + ' in that directory:</h3>') for key in Statistics.missing_modules: file.write('<h5>' + key + ':</h5>') file.write('<p>' + ', '.join([value.split('/')[-1] for value in Statistics.missing_modules[key]]) + '</p>') file.write('<h3>YANG modules in NETCONF hello messages for a directory but their' + ' submodules are missing:</h3>') for key in Statistics.missing_submodules: file.write('<h5>' + key + ':</h5>') file.write('<p>' + ', '.join([value.split('/')[-1] for value in Statistics.missing_submodules[key]]) + '</p>') file.write('<h3>YANG modules in NETCONF hello messages for a directory but their' + ' revision date is missing:</h3>') for key in Statistics.missing_revision: file.write('<h5>' + key + ':</h5>') file.write('<p>' + ', '.join([value.split('/')[-1] for value in Statistics.missing_revision[key]]) + '</p>') file.write('<h3>YANG modules in NETCONF hello messages for a directory but their' + ' namespace is wrong or missing:</h3>') for key in Statistics.missing_wrong_namespaces: file.write('<h5>' + key + ':</h5>') for value in Statistics.missing_wrong_namespaces[key]: file.write('<p>' + str(value) + '</p>') missing = [] my_files = find_missing_hello(yang_models + '/vendor/', '*.yang') for name in set(my_files): if '.incompatible' not in name and 'MIBS' not in name: missing.append(name) missing = ', '.join(missing).replace(yang_models, '') file.write('<h3>Folders with yang files but missing hello message inside of file:</h3><p>' + missing + '</p>') file.write('</body></html>') @staticmethod def add_submodule(path, value): if len(value) > 0: Statistics.missing_submodules[path].update(value) @staticmethod def add_module(path, value): if len(value) > 0: Statistics.missing_modules[path].update(value) @staticmethod def add_namespace(path, value): if value: Statistics.missing_wrong_namespaces[path] = value @staticmethod def add_revision(path, value): if value: Statistics.missing_revision[path] = value
41.353741
120
0.627735
8624fa7f888ac33a70693b1e2bfa2ce3bae7b68f
898
py
Python
tflite-onnx/onnx_tflite/tflite/FloorModOptions.py
jwj04ok/ONNX_Convertor
067a17e16dfc8aa80e36f44c4523959daf7359f5
[ "MIT" ]
193
2017-12-20T16:46:20.000Z
2022-03-29T07:40:54.000Z
tinyengine/tflite/FloorModOptions.py
liuyy3364/mcunet
f53f9e20e8e912bdb111b4c32da75e71e9a59597
[ "Apache-2.0" ]
141
2017-12-21T08:00:20.000Z
2021-06-15T14:53:03.000Z
tinyengine/tflite/FloorModOptions.py
liuyy3364/mcunet
f53f9e20e8e912bdb111b4c32da75e71e9a59597
[ "Apache-2.0" ]
55
2017-12-22T18:40:13.000Z
2022-01-17T05:43:51.000Z
# automatically generated by the FlatBuffers compiler, do not modify # namespace: tflite import flatbuffers from flatbuffers.compat import import_numpy np = import_numpy() class FloorModOptions(object): __slots__ = ['_tab'] @classmethod def GetRootAsFloorModOptions(cls, buf, offset): n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) x = FloorModOptions() x.Init(buf, n + offset) return x @classmethod def FloorModOptionsBufferHasIdentifier(cls, buf, offset, size_prefixed=False): return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x54\x46\x4C\x33", size_prefixed=size_prefixed) # FloorModOptions def Init(self, buf, pos): self._tab = flatbuffers.table.Table(buf, pos) def FloorModOptionsStart(builder): builder.StartObject(0) def FloorModOptionsEnd(builder): return builder.EndObject()
30.965517
114
0.729399
1468b825470371880ac76e40ee39f899167bed28
4,942
py
Python
app/user/tests/test_user_api.py
BenoCharlo/recipe-app-api_2
071673c6080db43359973e7ce9612489408e50c6
[ "MIT" ]
null
null
null
app/user/tests/test_user_api.py
BenoCharlo/recipe-app-api_2
071673c6080db43359973e7ce9612489408e50c6
[ "MIT" ]
null
null
null
app/user/tests/test_user_api.py
BenoCharlo/recipe-app-api_2
071673c6080db43359973e7ce9612489408e50c6
[ "MIT" ]
null
null
null
from django.test import TestCase from django.contrib.auth import get_user_model from django.urls import reverse from rest_framework.test import APIClient from rest_framework import status CREATE_USER_URL = reverse("user:create") TOKEN_URL = reverse("user:token") ME_URL = reverse("user:me") def create_user(**params): return get_user_model().objects.create_user(**params) class PublicUserApiTests(TestCase): """Test the users API (public)""" def setUp(self): self.client = APIClient() def test_create_valid_user_success(self): """Test creating user with valid payload is successful""" payload = { "email": "test@benocharlo.com", "password": "testpass", "name": "Test name", } res = self.client.post(CREATE_USER_URL, payload) self.assertEqual(res.status_code, status.HTTP_201_CREATED) user = get_user_model().objects.get(**res.data) self.assertTrue(user.check_password(payload["password"])) self.assertNotIn("password", res.data) def test_user_exists(self): """Test creating a user that already exists fails""" payload = { "email": "test@benocharlo.com", "password": "testpass", } create_user(**payload) res = self.client.post(CREATE_USER_URL, payload) self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) def test_pass_too_short(self): """The password must be more than 5 characters""" payload = { "email": "test@benocharlo.com", "password": "pw", } res = self.client.post(CREATE_USER_URL, payload) self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) user_exists = get_user_model().objects.filter(email=payload["email"]).exists() self.assertFalse(user_exists) def test_create_token_for_user(self): """Test that a token is created for the user""" payload = {"email": "test@benocharlo.com", "password": "testpass"} create_user(**payload) res = self.client.post(TOKEN_URL, payload) self.assertIn("token", res.data) self.assertEqual(res.status_code, status.HTTP_200_OK) def test_create_token_invalid_credentials(self): """Test token is not created if invalid credentials are given""" create_user(email="test@benocharlo.com", password="testpass") payload = {"email": "test@benocharlo.com", "password": "wrong"} res = self.client.post(TOKEN_URL, payload) self.assertNotIn("token", res.data) self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) def test_create_token_no_user(self): """Test that token is not created if user doesn't exist""" payload = {"email": "test@benocharlo.com", "password": "testpass"} res = self.client.post(TOKEN_URL, payload) self.assertNotIn("token", res.data) self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) def test_create_token_missing_field(self): """Test that email ansd password are required""" res = self.client.post(TOKEN_URL, {"email": "one", "password": ""}) self.assertNotIn("token", res.data) self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST) def test_retrieve_user_unauthorized(self): """Test that authentication is required for user""" res = self.client.get(ME_URL) self.assertEqual(res.status_code, status.HTTP_401_UNAUTHORIZED) class PrivateUserApiTests(TestCase): """test api requestes that require authentication""" def setUp(self): self.user = create_user( email="test@benocharlo.com", password="testpass", name="name", ) self.client = APIClient() self.client.force_authenticate(user=self.user) def test_retrieve_profile_success(self): """test retriveing profile for logged in used""" res = self.client.get(ME_URL) self.assertEqual(res.status_code, status.HTTP_200_OK) self.assertEqual( res.data, { "name": self.user.name, "email": self.user.email, }, ) def test_post_me_not_allowed(self): """Test that post is not allowed on the me url""" res = self.client.post(ME_URL, {}) self.assertEqual(res.status_code, status.HTTP_405_METHOD_NOT_ALLOWED) def test_update_user_orofile(self): """Test updateing the user profile for authenticated user""" payload = {"name": "new name", "password": "newpassword123"} res = self.client.patch(ME_URL, payload) self.user.refresh_from_db() self.assertEqual(self.user.name, payload["name"]) self.assertTrue(self.user.check_password(payload["password"])) self.assertEqual(res.status_code, status.HTTP_200_OK)
34.802817
86
0.648928
46201649b1d1aeb31ca6f9f60acb7ff390d766dc
1,150
py
Python
macgraph/regression_test.py
Octavian-ai/mac-graph
3ef978e8a6f79f2dcc46783d34f01934aabf7f19
[ "Unlicense" ]
116
2018-07-11T13:19:56.000Z
2021-07-26T17:22:44.000Z
macgraph/regression_test.py
Octavian-ai/mac-graph
3ef978e8a6f79f2dcc46783d34f01934aabf7f19
[ "Unlicense" ]
1
2019-02-11T02:25:02.000Z
2019-02-11T17:05:19.000Z
macgraph/regression_test.py
Octavian-ai/mac-graph
3ef978e8a6f79f2dcc46783d34f01934aabf7f19
[ "Unlicense" ]
21
2018-10-11T23:03:22.000Z
2021-07-14T22:42:08.000Z
try: # import comet_ml in the top of your file from comet_ml import Experiment except: # It's ok if we didn't install it pass import yaml import tensorflow as tf from .args import get_args from .estimator import get_estimator from .input import gen_input_fn from .train import train # Make TF be quiet import os os.environ["TF_CPP_MIN_LOG_LEVEL"]="2" if __name__ == "__main__": args = get_args() train(args) estimator = get_estimator(args) results = estimator.evaluate(input_fn=gen_input_fn(args, "eval")) try: with tf.gfile.GFile(args["results_path"], "r") as file: doc = yaml.load(file) except: doc = {} if doc is None: doc = {} simplified_results = { "accuracy": float(results["accuracy"]), "accuracy_pct": str(round(results["accuracy"]*1000.0)/10.0) + "%", "loss": float(results["loss"]), "steps": int(results["current_step"]), } print(args["dataset"], simplified_results) if not args["dataset"] in doc or simplified_results["accuracy"] > doc[args["dataset"]]["accuracy"]: doc[args["dataset"]] = simplified_results with tf.gfile.GFile(args["results_path"], "w") as file: yaml.dump(doc, file)
20.535714
100
0.697391
cb0eff88e9d676b495b5707f8d81edcd6ae3634f
1,275
py
Python
presentation/shapely_bool_ops.py
bendemott/Python-Shapely-Examples
feda19bb4bf32e6d387d717bcc95bfc39057696f
[ "MIT" ]
3
2017-11-21T14:51:16.000Z
2018-12-06T08:07:09.000Z
presentation/shapely_bool_ops.py
deep0072/Python-Shapely-Examples
feda19bb4bf32e6d387d717bcc95bfc39057696f
[ "MIT" ]
null
null
null
presentation/shapely_bool_ops.py
deep0072/Python-Shapely-Examples
feda19bb4bf32e6d387d717bcc95bfc39057696f
[ "MIT" ]
4
2016-09-20T06:00:34.000Z
2021-05-18T09:42:53.000Z
''' @author Ben DeMott @file shapely_bool_ops.py Shapely Boolean Operations are methods associated with a geometric object that return True/False ''' from shapely.geometry import * import sys point1 = Point((1, 1)) # See if another point is almost equal to our point... # The second argument determines variance in the calculation print "Point 1 is about equal to Point2?:" print point1.almost_equals(Point(1.01, 1.01), decimal=1) # True # See if the exterior of an object is within our object point2 = point1 point1.buffer(1) # See if point1 contains point2 ? print "Point 1 contains Point 2 ?:" print point1.contains(point2) # True sys.exit() # OTHERS: # True if the interior or exterior intersects shape1.intersects(shape2) # Intersection is equivelant to this statement intersects = (shape1.contains(shape2) OR shape1.crosses(shape2) OR shape1.equals(shape2) OR shape1.touches(shape2), OR shape1.within(shape2)) # True if ONLY the boundary (exterior) of two objects intersect/touch shape1.touches(shape2) # True of one objects components are equal to another shape1.equals(shape2) # True If interior of shape1 intersects interior of shape2 shape1.crosses(shape2) # Interior and exterior boundaries don't intersect/share coordinates shape1.disjoint(shape2)
25.5
141
0.773333
94cb5c9d203a4f91adab6e708aa656e2b0f95203
921
py
Python
bookmarks/bookmarks/account/models.py
EssaAlshammri/django-by-example
d1a1cba9308d4f19bbb1228dbd191ad5540b2c78
[ "MIT" ]
3
2017-04-25T10:19:02.000Z
2017-06-07T12:50:30.000Z
bookmarks/bookmarks/account/models.py
EssaAlshammri/django-by-example
d1a1cba9308d4f19bbb1228dbd191ad5540b2c78
[ "MIT" ]
null
null
null
bookmarks/bookmarks/account/models.py
EssaAlshammri/django-by-example
d1a1cba9308d4f19bbb1228dbd191ad5540b2c78
[ "MIT" ]
null
null
null
from django.conf import settings from django.contrib.auth.models import User from django.db import models class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL) date_of_birth = models.DateField(blank=True, null=True) photo = models.ImageField(upload_to="users/%Y/%m/%d", blank=True) def __str__(self): return "Profile for user {}".format(self.user.username) class Contact(models.Model): user_from = models.ForeignKey(User, related_name='rel_from_set') user_to = models.ForeignKey(User, related_name='rel_to_set') created = models.DateTimeField(auto_now_add=True, db_index=True) class Meta: ordering = ['-created'] def __str__(self): return '{} follows {}.'.format(self.user_from, self.user_to) User.add_to_class('following', models.ManyToManyField( 'self', through=Contact, related_name='followers', symmetrical=False))
31.758621
74
0.724213
f09e1a6ae51d48a3383e45dd244a717ebe97e6a9
99
py
Python
predict/admin.py
ehsangh7/Django-ML-Iris
c65930e5044aa83c3b3062dd512d7f6cff24b1b9
[ "Apache-2.0" ]
2
2021-03-24T00:22:13.000Z
2021-06-22T08:51:54.000Z
predict/admin.py
ehsangh7/Django-ML-Iris
c65930e5044aa83c3b3062dd512d7f6cff24b1b9
[ "Apache-2.0" ]
null
null
null
predict/admin.py
ehsangh7/Django-ML-Iris
c65930e5044aa83c3b3062dd512d7f6cff24b1b9
[ "Apache-2.0" ]
null
null
null
from django.contrib import admin from .models import PredResults admin.site.register(PredResults)
19.8
32
0.838384
4b084ac5368f5c8fed8ae06c5d74cbec4d898694
4,592
py
Python
utils/utils.py
hoangnt2601/RAPiD
8e765ccec45e192305ca3d9d547967dbb4299cc3
[ "MIT" ]
null
null
null
utils/utils.py
hoangnt2601/RAPiD
8e765ccec45e192305ca3d9d547967dbb4299cc3
[ "MIT" ]
null
null
null
utils/utils.py
hoangnt2601/RAPiD
8e765ccec45e192305ca3d9d547967dbb4299cc3
[ "MIT" ]
null
null
null
from PIL import Image import random import torch from torchvision import transforms from utils.iou_mask import iou_mask, iou_rle def normalize_bbox(xywha, w, h, max_angle=1): ''' Normalize bounding boxes to 0~1 range Args: xywha: torch.tensor, bounding boxes, shape(...,5) w: image width h: image height max_angle: the angle will be divided by max_angle ''' assert torch.is_tensor(xywha) if xywha.dim() == 1: assert xywha.shape[0] == 5 xywha[0] /= w xywha[1] /= h xywha[2] /= w xywha[3] /= h xywha[4] /= max_angle elif xywha.dim() == 2: assert xywha.shape[1] == 5 xywha[:,0] /= w xywha[:,1] /= h xywha[:,2] /= w xywha[:,3] /= h xywha[:,4] /= max_angle else: raise Exception('unkown bbox format') return xywha def rect_to_square(img, labels, target_size, pad_value=0, aug=False): ''' Pre-processing during training and testing 1. Resize img such that the longer side of the image = target_size; 2. Pad the img it to square Arguments: img: PIL image labels: torch.tensor, shape(N,5), [cx, cy, w, h, angle], not normalized target_size: int, e.g. 608 pad_value: int aug: bool ''' assert isinstance(img, Image.Image) ori_h, ori_w = img.height, img.width # resize to target input size (usually smaller) resize_scale = target_size / max(ori_w,ori_h) # unpad_w, unpad_h = target_size * w / max(w,h), target_size * h / max(w,h) unpad_w, unpad_h = int(ori_w*resize_scale), int(ori_h*resize_scale) img = transforms.functional.resize(img, (unpad_h,unpad_w)) # pad to square if aug: # random placing left = random.randint(0, target_size - unpad_w) top = random.randint(0, target_size - unpad_h) else: left = (target_size - unpad_w) // 2 top = (target_size - unpad_h) // 2 right = target_size - unpad_w - left bottom = target_size - unpad_h - top img = transforms.functional.pad(img, padding=(left,top,right,bottom), fill=0) # record the padding info img_tl = (left, top) # start of the true image img_wh = (unpad_w, unpad_h) # modify labels if labels is not None: labels[:,0:4] *= resize_scale labels[:,0] += left labels[:,1] += top pad_info = torch.Tensor((ori_w, ori_h) + img_tl + img_wh) return img, labels, pad_info def detection2original(boxes, pad_info): ''' Recover the bbox from the resized and padded image to the original image. Args: boxes: tensor, rows of [cx, cy, w, h, angle] pad_info: (ori w, ori h, tl x, tl y, imw, imh) ''' assert boxes.dim() == 2 ori_w, ori_h, tl_x, tl_y, imw, imh = pad_info boxes[:,0] = (boxes[:,0] - tl_x) / imw * ori_w boxes[:,1] = (boxes[:,1] - tl_y) / imh * ori_h boxes[:,2] = boxes[:,2] / imw * ori_w boxes[:,3] = boxes[:,3] / imh * ori_h return boxes def nms(detections, is_degree=True, nms_thres=0.45, img_size=2048): ''' Single-class non-maximum suppression for bounding boxes with angle. Args: detections: rows of (x,y,w,h,angle,conf,...) is_degree: True -> input angle is degree, False -> radian nms_thres: suppresion IoU threshold img_size: int, preferably the image size ''' assert (detections.dim() == 2) and (detections.shape[1] >= 6) device = detections.device if detections.shape[0] == 0: return detections # sort by confidence idx = torch.argsort(detections[:,5], descending=True) detections = detections[idx,:] boxes = detections[:,0:5] # only [x,y,w,h,a] valid = torch.zeros(boxes.shape[0], dtype=torch.bool, device=device) # the first one is always valid valid[0] = True # only one candidate at the beginning. Its votes number is 1 (it self) votes = [1] for i in range(1, boxes.shape[0]): # compute IoU with valid boxes ious = iou_mask(boxes[i], boxes[valid,:], True, 32, is_degree=is_degree) # ious = iou_rle(boxes[i], boxes[valid,:], xywha=True, is_degree=is_degree, # img_size=img_size) # the i'th BB is invalid if it is similar to any valid BB if (ious >= nms_thres).any(): continue # else, this box is valid valid[i] = True # the votes number of the new candidate BB is 1 (it self) votes.append(1) selected = detections[valid,:] return selected
31.238095
83
0.601263
4a4a820d1a73ee65c3431f9f1dc42f592ada3644
13,635
py
Python
packages/snet_cli/snet_cli/mpe_service_command.py
vforvalerio87/snet-cli
9c3d028dd82fcc8a2f009527aa9925499646580a
[ "MIT" ]
null
null
null
packages/snet_cli/snet_cli/mpe_service_command.py
vforvalerio87/snet-cli
9c3d028dd82fcc8a2f009527aa9925499646580a
[ "MIT" ]
1
2019-06-04T15:56:03.000Z
2019-06-04T15:56:03.000Z
packages/snet_cli/snet_cli/mpe_service_command.py
vforvalerio87/snet-cli
9c3d028dd82fcc8a2f009527aa9925499646580a
[ "MIT" ]
null
null
null
import web3 import json import grpc from collections import defaultdict from grpc_health.v1 import health_pb2 as heartb_pb2 from grpc_health.v1 import health_pb2_grpc as heartb_pb2_grpc from snet_cli.commands import BlockchainCommand import snet.snet_cli.utils_ipfs as utils_ipfs from snet.snet_cli.utils_ipfs import hash_to_bytesuri, bytesuri_to_hash, get_from_ipfs_and_checkhash, safe_extract_proto_from_ipfs from snet.snet_cli.mpe_service_metadata import MPEServiceMetadata, load_mpe_service_metadata, mpe_service_metadata_from_json from snet.snet_cli.utils import type_converter, bytes32_to_str, open_grpc_channel class MPEServiceCommand(BlockchainCommand): def publish_proto_in_ipfs(self): """ Publish proto files in ipfs and print hash """ ipfs_hash_base58 = utils_ipfs.publish_proto_in_ipfs( self._get_ipfs_client(), self.args.protodir) self._printout(ipfs_hash_base58) def publish_proto_metadata_init(self): model_ipfs_hash_base58 = utils_ipfs.publish_proto_in_ipfs( self._get_ipfs_client(), self.args.protodir) metadata = MPEServiceMetadata() mpe_address = self.get_mpe_address() metadata.set_simple_field("model_ipfs_hash", model_ipfs_hash_base58) metadata.set_simple_field("mpe_address", mpe_address) metadata.set_simple_field("display_name", self.args.display_name) metadata.set_simple_field("encoding", self.args.encoding) metadata.set_simple_field("service_type", self.args.service_type) metadata.set_simple_field( "payment_expiration_threshold", self.args.payment_expiration_threshold) self._metadata_add_group(metadata) for endpoint in self.args.endpoints: metadata.add_endpoint(self.args.group_name, endpoint) if (self.args.fixed_price is not None): metadata.set_fixed_price_in_cogs(self.args.fixed_price) metadata.save_pretty(self.args.metadata_file) def publish_proto_metadata_update(self): """ Publish protobuf model in ipfs and update existing metadata file """ metadata = load_mpe_service_metadata(self.args.metadata_file) ipfs_hash_base58 = utils_ipfs.publish_proto_in_ipfs( self._get_ipfs_client(), self.args.protodir) metadata.set_simple_field("model_ipfs_hash", ipfs_hash_base58) metadata.save_pretty(self.args.metadata_file) def metadata_set_fixed_price(self): metadata = load_mpe_service_metadata(self.args.metadata_file) metadata.set_fixed_price_in_cogs(self.args.price) metadata.save_pretty(self.args.metadata_file) def _metadata_add_group(self, metadata): if (not web3.eth.is_checksum_address(self.args.payment_address)): raise Exception( "payment_address parameter is not a valid Ethereum checksum address") metadata.add_group(self.args.group_name, self.args.payment_address) def metadata_add_group(self): metadata = load_mpe_service_metadata(self.args.metadata_file) self._metadata_add_group(metadata) metadata.save_pretty(self.args.metadata_file) def metadata_add_endpoints(self): """ Metadata: add endpoint to the group """ metadata = load_mpe_service_metadata(self.args.metadata_file) group_name = metadata.get_group_name_nonetrick(self.args.group_name) for endpoint in self.args.endpoints: metadata.add_endpoint(group_name, endpoint) metadata.save_pretty(self.args.metadata_file) def metadata_remove_all_endpoints(self): """ Metadata: remove all endpoints from all groups """ metadata = load_mpe_service_metadata(self.args.metadata_file) metadata.remove_all_endpoints() metadata.save_pretty(self.args.metadata_file) def metadata_update_endpoints(self): """ Metadata: Remove all endpoints from the group and add new ones """ metadata = load_mpe_service_metadata(self.args.metadata_file) group_name = metadata.get_group_name_nonetrick(self.args.group_name) metadata.remove_all_endpoints_for_group(group_name) for endpoint in self.args.endpoints: metadata.add_endpoint(group_name, endpoint) metadata.save_pretty(self.args.metadata_file) def metadata_add_asset_to_ipfs(self): metadata = load_mpe_service_metadata(self.args.metadata_file) asset_file_ipfs_hash_base58 = utils_ipfs.publish_file_in_ipfs(self._get_ipfs_client(), self.args.asset_file_path) metadata.add_asset(asset_file_ipfs_hash_base58, self.args.asset_type) metadata.save_pretty(self.args.metadata_file) def metadata_remove_all_assets(self): metadata = load_mpe_service_metadata(self.args.metadata_file) metadata.remove_all_assets() metadata.save_pretty(self.args.metadata_file) def metadata_remove_assets_of_a_given_type(self): metadata = load_mpe_service_metadata(self.args.metadata_file) metadata.remove_assets(self.args.asset_type) metadata.save_pretty(self.args.metadata_file) def metadata_add_description(self): """ Metadata: add description """ service_description = {} if (self.args.json): service_description = json.loads(self.args.json) if (self.args.url): if "url" in service_description: raise Exception( "json service description already contains url field") service_description["url"] = self.args.url if (self.args.description): if "description" in service_description: raise Exception( "json service description already contains description field") service_description["description"] = self.args.description metadata = load_mpe_service_metadata(self.args.metadata_file) # merge with old service_description if necessary if ("service_description" in metadata): service_description = { **metadata["service_description"], **service_description} metadata.set_simple_field("service_description", service_description) metadata.save_pretty(self.args.metadata_file) def _publish_metadata_in_ipfs(self, metadata_file): metadata = load_mpe_service_metadata(metadata_file) mpe_address = self.get_mpe_address() if (self.args.update_mpe_address): metadata.set_simple_field("mpe_address", mpe_address) metadata.save_pretty(self.args.metadata_file) if (mpe_address.lower() != metadata["mpe_address"].lower()): raise Exception("\n\nmpe_address in metadata does not correspond to the current MultiPartyEscrow contract address\n" + "You have two possibilities:\n" + "1. You can use --multipartyescrow-at to set current mpe address\n" + "2. You can use --update-mpe-address parameter to update mpe_address in metadata before publishing it\n") return self._get_ipfs_client().add_bytes(metadata.get_json().encode("utf-8")) def publish_metadata_in_ipfs(self): """ Publish metadata in ipfs and print hash """ self._printout(self._publish_metadata_in_ipfs(self.args.metadata_file)) def _get_converted_tags(self): return [type_converter("bytes32")(tag) for tag in self.args.tags] def publish_service_with_metadata(self): metadata_uri = hash_to_bytesuri( self._publish_metadata_in_ipfs(self.args.metadata_file)) tags = self._get_converted_tags() params = [type_converter("bytes32")(self.args.org_id), type_converter( "bytes32")(self.args.service_id), metadata_uri, tags] self.transact_contract_command( "Registry", "createServiceRegistration", params) def publish_metadata_in_ipfs_and_update_registration(self): # first we check that we do not change payment_address or group_id in existed payment groups old_metadata = self._get_service_metadata_from_registry() new_metadata = load_mpe_service_metadata(self.args.metadata_file) for old_group in old_metadata["groups"]: if (new_metadata.is_group_name_exists(old_group["group_name"])): new_group = new_metadata.get_group(old_group["group_name"]) if (new_group["group_id"] != old_group["group_id"] or new_group["payment_address"] != old_group["payment_address"]): raise Exception("\n\nYou are trying to change group_id or payment_address in group '%s'.\n" % old_group["group_name"] + "It would make all open channels invalid.\n" + "You shoudn't use 'metadata-init' for existed service, because it reinitialize group_id\n" + "Please use 'metadata-set-model' for change your protobuf file\n" + "Please use 'metadata-remove-all-endpoints/metadata-add-endpoints to update endpoints'\n\n") metadata_uri = hash_to_bytesuri( self._publish_metadata_in_ipfs(self.args.metadata_file)) params = [type_converter("bytes32")(self.args.org_id), type_converter( "bytes32")(self.args.service_id), metadata_uri] self.transact_contract_command( "Registry", "updateServiceRegistration", params) def _get_params_for_tags_update(self): tags = self._get_converted_tags() params = [type_converter("bytes32")(self.args.org_id), type_converter( "bytes32")(self.args.service_id), tags] return params def update_registration_add_tags(self): params = self._get_params_for_tags_update() self.transact_contract_command( "Registry", "addTagsToServiceRegistration", params) def update_registration_remove_tags(self): params = self._get_params_for_tags_update() self.transact_contract_command( "Registry", "removeTagsFromServiceRegistration", params) def _get_service_registration(self): params = [type_converter("bytes32")(self.args.org_id), type_converter( "bytes32")(self.args.service_id)] rez = self.call_contract_command( "Registry", "getServiceRegistrationById", params) if (rez[0] == False): raise Exception("Cannot find Service with id=%s in Organization with id=%s" % ( self.args.service_id, self.args.org_id)) return {"metadataURI": rez[2], "tags": rez[3]} def _get_service_metadata_from_registry(self): rez = self._get_service_registration() metadata_hash = bytesuri_to_hash(rez["metadataURI"]) metadata = get_from_ipfs_and_checkhash( self._get_ipfs_client(), metadata_hash) metadata = metadata.decode("utf-8") metadata = mpe_service_metadata_from_json(metadata) return metadata def print_service_metadata_from_registry(self): metadata = self._get_service_metadata_from_registry() self._printout(metadata.get_json_pretty()) def _service_status(self, url, secure=True): try: channel = open_grpc_channel(endpoint=url) stub = heartb_pb2_grpc.HealthStub(channel) response = stub.Check( heartb_pb2.HealthCheckRequest(service=""), timeout=10) if response != None and response.status == 1: return True return False except Exception as e: return False def print_service_status(self): metadata = self._get_service_metadata_from_registry() if self.args.group_name != None: groups = {self.args.group_name: metadata.get_endpoints_for_group( self.args.group_name)} else: groups = metadata.get_all_endpoints_with_group_name() srvc_status = defaultdict(list) for grp in groups: for endpoint in groups[grp]: status = "Available" if self._service_status( url=endpoint) else "Not Available" srvc_status[grp].append( {"endpoint": endpoint, "status": status}) if srvc_status == {}: self._printout( "Error: No endpoints found to check service status.") return self._pprint(srvc_status) def print_service_tags_from_registry(self): rez = self._get_service_registration() tags = rez["tags"] tags = [bytes32_to_str(tag) for tag in tags] self._printout(" ".join(tags)) def extract_service_api_from_metadata(self): metadata = load_mpe_service_metadata(self.args.metadata_file) safe_extract_proto_from_ipfs(self._get_ipfs_client( ), metadata["model_ipfs_hash"], self.args.protodir) def extract_service_api_from_registry(self): metadata = self._get_service_metadata_from_registry() safe_extract_proto_from_ipfs(self._get_ipfs_client( ), metadata["model_ipfs_hash"], self.args.protodir) def delete_service_registration(self): params = [type_converter("bytes32")(self.args.org_id), type_converter( "bytes32")(self.args.service_id)] self.transact_contract_command( "Registry", "deleteServiceRegistration", params)
48.870968
139
0.678475
6df993e92822cb33a38c466fef30ad48163f32a7
825,508
py
Python
packages/python/plotly/plotly/graph_objs/_figurewidget.py
grootstebozewolf/plotly.py
06873b7c14754963cf700050759b2eadd2859979
[ "MIT" ]
null
null
null
packages/python/plotly/plotly/graph_objs/_figurewidget.py
grootstebozewolf/plotly.py
06873b7c14754963cf700050759b2eadd2859979
[ "MIT" ]
null
null
null
packages/python/plotly/plotly/graph_objs/_figurewidget.py
grootstebozewolf/plotly.py
06873b7c14754963cf700050759b2eadd2859979
[ "MIT" ]
null
null
null
from plotly.basewidget import BaseFigureWidget class FigureWidget(BaseFigureWidget): def __init__( self, data=None, layout=None, frames=None, skip_invalid=False, **kwargs ): """ Create a new :class:FigureWidget instance Parameters ---------- data The 'data' property is a tuple of trace instances that may be specified as: - A list or tuple of trace instances (e.g. [Scatter(...), Bar(...)]) - A single trace instance (e.g. Scatter(...), Bar(...), etc.) - A list or tuple of dicts of string/value properties where: - The 'type' property specifies the trace type One of: ['area', 'bar', 'barpolar', 'box', 'candlestick', 'carpet', 'choropleth', 'choroplethmapbox', 'cone', 'contour', 'contourcarpet', 'densitymapbox', 'funnel', 'funnelarea', 'heatmap', 'heatmapgl', 'histogram', 'histogram2d', 'histogram2dcontour', 'image', 'indicator', 'isosurface', 'mesh3d', 'ohlc', 'parcats', 'parcoords', 'pie', 'pointcloud', 'sankey', 'scatter', 'scatter3d', 'scattercarpet', 'scattergeo', 'scattergl', 'scattermapbox', 'scatterpolar', 'scatterpolargl', 'scatterternary', 'splom', 'streamtube', 'sunburst', 'surface', 'table', 'treemap', 'violin', 'volume', 'waterfall'] - All remaining properties are passed to the constructor of the specified trace type (e.g. [{'type': 'scatter', ...}, {'type': 'bar, ...}]) layout The 'layout' property is an instance of Layout that may be specified as: - An instance of :class:`plotly.graph_objs.Layout` - A dict of string/value properties that will be passed to the Layout constructor Supported dict properties: activeshape :class:`plotly.graph_objects.layout.Activeshape ` instance or dict with compatible properties angularaxis :class:`plotly.graph_objects.layout.AngularAxis ` instance or dict with compatible properties annotations A tuple of :class:`plotly.graph_objects.layout.Annotation` instances or dicts with compatible properties annotationdefaults When used in a template (as layout.template.layout.annotationdefaults), sets the default property values to use for elements of layout.annotations autosize Determines whether or not a layout width or height that has been left undefined by the user is initialized on each relayout. Note that, regardless of this attribute, an undefined layout width or height is always initialized on the first call to plot. bargap Sets the gap (in plot fraction) between bars of adjacent location coordinates. bargroupgap Sets the gap (in plot fraction) between bars of the same location coordinate. barmode Determines how bars at the same location coordinate are displayed on the graph. With "stack", the bars are stacked on top of one another With "relative", the bars are stacked on top of one another, with negative values below the axis, positive values above With "group", the bars are plotted next to one another centered around the shared location. With "overlay", the bars are plotted over one another, you might need to an "opacity" to see multiple bars. barnorm Sets the normalization for bar traces on the graph. With "fraction", the value of each bar is divided by the sum of all values at that location coordinate. "percent" is the same but multiplied by 100 to show percentages. boxgap Sets the gap (in plot fraction) between boxes of adjacent location coordinates. Has no effect on traces that have "width" set. boxgroupgap Sets the gap (in plot fraction) between boxes of the same location coordinate. Has no effect on traces that have "width" set. boxmode Determines how boxes at the same location coordinate are displayed on the graph. If "group", the boxes are plotted next to one another centered around the shared location. If "overlay", the boxes are plotted over one another, you might need to set "opacity" to see them multiple boxes. Has no effect on traces that have "width" set. calendar Sets the default calendar system to use for interpreting and displaying dates throughout the plot. clickmode Determines the mode of single click interactions. "event" is the default value and emits the `plotly_click` event. In addition this mode emits the `plotly_selected` event in drag modes "lasso" and "select", but with no event data attached (kept for compatibility reasons). The "select" flag enables selecting single data points via click. This mode also supports persistent selections, meaning that pressing Shift while clicking, adds to / subtracts from an existing selection. "select" with `hovermode`: "x" can be confusing, consider explicitly setting `hovermode`: "closest" when using this feature. Selection events are sent accordingly as long as "event" flag is set as well. When the "event" flag is missing, `plotly_click` and `plotly_selected` events are not fired. coloraxis :class:`plotly.graph_objects.layout.Coloraxis` instance or dict with compatible properties colorscale :class:`plotly.graph_objects.layout.Colorscale` instance or dict with compatible properties colorway Sets the default trace colors. computed Placeholder for exporting automargin-impacting values namely `margin.t`, `margin.b`, `margin.l` and `margin.r` in "full-json" mode. datarevision If provided, a changed value tells `Plotly.react` that one or more data arrays has changed. This way you can modify arrays in- place rather than making a complete new copy for an incremental change. If NOT provided, `Plotly.react` assumes that data arrays are being treated as immutable, thus any data array with a different identity from its predecessor contains new data. direction Legacy polar charts are deprecated! Please switch to "polar" subplots. Sets the direction corresponding to positive angles in legacy polar charts. dragmode Determines the mode of drag interactions. "select" and "lasso" apply only to scatter traces with markers or text. "orbit" and "turntable" apply only to 3D scenes. editrevision Controls persistence of user-driven changes in `editable: true` configuration, other than trace names and axis titles. Defaults to `layout.uirevision`. extendfunnelareacolors If `true`, the funnelarea slice colors (whether given by `funnelareacolorway` or inherited from `colorway`) will be extended to three times its original length by first repeating every color 20% lighter then each color 20% darker. This is intended to reduce the likelihood of reusing the same color when you have many slices, but you can set `false` to disable. Colors provided in the trace, using `marker.colors`, are never extended. extendpiecolors If `true`, the pie slice colors (whether given by `piecolorway` or inherited from `colorway`) will be extended to three times its original length by first repeating every color 20% lighter then each color 20% darker. This is intended to reduce the likelihood of reusing the same color when you have many slices, but you can set `false` to disable. Colors provided in the trace, using `marker.colors`, are never extended. extendsunburstcolors If `true`, the sunburst slice colors (whether given by `sunburstcolorway` or inherited from `colorway`) will be extended to three times its original length by first repeating every color 20% lighter then each color 20% darker. This is intended to reduce the likelihood of reusing the same color when you have many slices, but you can set `false` to disable. Colors provided in the trace, using `marker.colors`, are never extended. extendtreemapcolors If `true`, the treemap slice colors (whether given by `treemapcolorway` or inherited from `colorway`) will be extended to three times its original length by first repeating every color 20% lighter then each color 20% darker. This is intended to reduce the likelihood of reusing the same color when you have many slices, but you can set `false` to disable. Colors provided in the trace, using `marker.colors`, are never extended. font Sets the global font. Note that fonts used in traces and other layout components inherit from the global font. funnelareacolorway Sets the default funnelarea slice colors. Defaults to the main `colorway` used for trace colors. If you specify a new list here it can still be extended with lighter and darker colors, see `extendfunnelareacolors`. funnelgap Sets the gap (in plot fraction) between bars of adjacent location coordinates. funnelgroupgap Sets the gap (in plot fraction) between bars of the same location coordinate. funnelmode Determines how bars at the same location coordinate are displayed on the graph. With "stack", the bars are stacked on top of one another With "group", the bars are plotted next to one another centered around the shared location. With "overlay", the bars are plotted over one another, you might need to an "opacity" to see multiple bars. geo :class:`plotly.graph_objects.layout.Geo` instance or dict with compatible properties grid :class:`plotly.graph_objects.layout.Grid` instance or dict with compatible properties height Sets the plot's height (in px). hiddenlabels hiddenlabels is the funnelarea & pie chart analog of visible:'legendonly' but it can contain many labels, and can simultaneously hide slices from several pies/funnelarea charts hiddenlabelssrc Sets the source reference on Chart Studio Cloud for hiddenlabels . hidesources Determines whether or not a text link citing the data source is placed at the bottom-right cored of the figure. Has only an effect only on graphs that have been generated via forked graphs from the Chart Studio Cloud (at https://chart-studio.plotly.com or on-premise). hoverdistance Sets the default distance (in pixels) to look for data to add hover labels (-1 means no cutoff, 0 means no looking for data). This is only a real distance for hovering on point-like objects, like scatter points. For area-like objects (bars, scatter fills, etc) hovering is on inside the area and off outside, but these objects will not supersede hover on point-like objects in case of conflict. hoverlabel :class:`plotly.graph_objects.layout.Hoverlabel` instance or dict with compatible properties hovermode Determines the mode of hover interactions. If "closest", a single hoverlabel will appear for the "closest" point within the `hoverdistance`. If "x" (or "y"), multiple hoverlabels will appear for multiple points at the "closest" x- (or y-) coordinate within the `hoverdistance`, with the caveat that no more than one hoverlabel will appear per trace. If *x unified* (or *y unified*), a single hoverlabel will appear multiple points at the closest x- (or y-) coordinate within the `hoverdistance` with the caveat that no more than one hoverlabel will appear per trace. In this mode, spikelines are enabled by default perpendicular to the specified axis. If false, hover interactions are disabled. If `clickmode` includes the "select" flag, `hovermode` defaults to "closest". If `clickmode` lacks the "select" flag, it defaults to "x" or "y" (depending on the trace's `orientation` value) for plots based on cartesian coordinates. For anything else the default value is "closest". images A tuple of :class:`plotly.graph_objects.layout.Image` instances or dicts with compatible properties imagedefaults When used in a template (as layout.template.layout.imagedefaults), sets the default property values to use for elements of layout.images legend :class:`plotly.graph_objects.layout.Legend` instance or dict with compatible properties mapbox :class:`plotly.graph_objects.layout.Mapbox` instance or dict with compatible properties margin :class:`plotly.graph_objects.layout.Margin` instance or dict with compatible properties meta Assigns extra meta information that can be used in various `text` attributes. Attributes such as the graph, axis and colorbar `title.text`, annotation `text` `trace.name` in legend items, `rangeselector`, `updatemenus` and `sliders` `label` text all support `meta`. One can access `meta` fields using template strings: `%{meta[i]}` where `i` is the index of the `meta` item in question. `meta` can also be an object for example `{key: value}` which can be accessed %{meta[key]}. metasrc Sets the source reference on Chart Studio Cloud for meta . modebar :class:`plotly.graph_objects.layout.Modebar` instance or dict with compatible properties newshape :class:`plotly.graph_objects.layout.Newshape` instance or dict with compatible properties orientation Legacy polar charts are deprecated! Please switch to "polar" subplots. Rotates the entire polar by the given angle in legacy polar charts. paper_bgcolor Sets the background color of the paper where the graph is drawn. piecolorway Sets the default pie slice colors. Defaults to the main `colorway` used for trace colors. If you specify a new list here it can still be extended with lighter and darker colors, see `extendpiecolors`. plot_bgcolor Sets the background color of the plotting area in-between x and y axes. polar :class:`plotly.graph_objects.layout.Polar` instance or dict with compatible properties radialaxis :class:`plotly.graph_objects.layout.RadialAxis` instance or dict with compatible properties scene :class:`plotly.graph_objects.layout.Scene` instance or dict with compatible properties selectdirection When `dragmode` is set to "select", this limits the selection of the drag to horizontal, vertical or diagonal. "h" only allows horizontal selection, "v" only vertical, "d" only diagonal and "any" sets no limit. selectionrevision Controls persistence of user-driven changes in selected points from all traces. separators Sets the decimal and thousand separators. For example, *. * puts a '.' before decimals and a space between thousands. In English locales, dflt is ".," but other locales may alter this default. shapes A tuple of :class:`plotly.graph_objects.layout.Shape` instances or dicts with compatible properties shapedefaults When used in a template (as layout.template.layout.shapedefaults), sets the default property values to use for elements of layout.shapes showlegend Determines whether or not a legend is drawn. Default is `true` if there is a trace to show and any of these: a) Two or more traces would by default be shown in the legend. b) One pie trace is shown in the legend. c) One trace is explicitly given with `showlegend: true`. sliders A tuple of :class:`plotly.graph_objects.layout.Slider` instances or dicts with compatible properties sliderdefaults When used in a template (as layout.template.layout.sliderdefaults), sets the default property values to use for elements of layout.sliders spikedistance Sets the default distance (in pixels) to look for data to draw spikelines to (-1 means no cutoff, 0 means no looking for data). As with hoverdistance, distance does not apply to area- like objects. In addition, some objects can be hovered on but will not generate spikelines, such as scatter fills. sunburstcolorway Sets the default sunburst slice colors. Defaults to the main `colorway` used for trace colors. If you specify a new list here it can still be extended with lighter and darker colors, see `extendsunburstcolors`. template Default attributes to be applied to the plot. This should be a dict with format: `{'layout': layoutTemplate, 'data': {trace_type: [traceTemplate, ...], ...}}` where `layoutTemplate` is a dict matching the structure of `figure.layout` and `traceTemplate` is a dict matching the structure of the trace with type `trace_type` (e.g. 'scatter'). Alternatively, this may be specified as an instance of plotly.graph_objs.layout.Template. Trace templates are applied cyclically to traces of each type. Container arrays (eg `annotations`) have special handling: An object ending in `defaults` (eg `annotationdefaults`) is applied to each array item. But if an item has a `templateitemname` key we look in the template array for an item with matching `name` and apply that instead. If no matching `name` is found we mark the item invisible. Any named template item not referenced is appended to the end of the array, so this can be used to add a watermark annotation or a logo image, for example. To omit one of these items on the plot, make an item with matching `templateitemname` and `visible: false`. ternary :class:`plotly.graph_objects.layout.Ternary` instance or dict with compatible properties title :class:`plotly.graph_objects.layout.Title` instance or dict with compatible properties titlefont Deprecated: Please use layout.title.font instead. Sets the title font. Note that the title's font used to be customized by the now deprecated `titlefont` attribute. transition Sets transition options used during Plotly.react updates. treemapcolorway Sets the default treemap slice colors. Defaults to the main `colorway` used for trace colors. If you specify a new list here it can still be extended with lighter and darker colors, see `extendtreemapcolors`. uirevision Used to allow user interactions with the plot to persist after `Plotly.react` calls that are unaware of these interactions. If `uirevision` is omitted, or if it is given and it changed from the previous `Plotly.react` call, the exact new figure is used. If `uirevision` is truthy and did NOT change, any attribute that has been affected by user interactions and did not receive a different value in the new figure will keep the interaction value. `layout.uirevision` attribute serves as the default for `uirevision` attributes in various sub-containers. For finer control you can set these sub-attributes directly. For example, if your app separately controls the data on the x and y axes you might set `xaxis.uirevision=*time*` and `yaxis.uirevision=*cost*`. Then if only the y data is changed, you can update `yaxis.uirevision=*quantity*` and the y axis range will reset but the x axis range will retain any user-driven zoom. uniformtext :class:`plotly.graph_objects.layout.Uniformtext ` instance or dict with compatible properties updatemenus A tuple of :class:`plotly.graph_objects.layout.Updatemenu` instances or dicts with compatible properties updatemenudefaults When used in a template (as layout.template.layout.updatemenudefaults), sets the default property values to use for elements of layout.updatemenus violingap Sets the gap (in plot fraction) between violins of adjacent location coordinates. Has no effect on traces that have "width" set. violingroupgap Sets the gap (in plot fraction) between violins of the same location coordinate. Has no effect on traces that have "width" set. violinmode Determines how violins at the same location coordinate are displayed on the graph. If "group", the violins are plotted next to one another centered around the shared location. If "overlay", the violins are plotted over one another, you might need to set "opacity" to see them multiple violins. Has no effect on traces that have "width" set. waterfallgap Sets the gap (in plot fraction) between bars of adjacent location coordinates. waterfallgroupgap Sets the gap (in plot fraction) between bars of the same location coordinate. waterfallmode Determines how bars at the same location coordinate are displayed on the graph. With "group", the bars are plotted next to one another centered around the shared location. With "overlay", the bars are plotted over one another, you might need to an "opacity" to see multiple bars. width Sets the plot's width (in px). xaxis :class:`plotly.graph_objects.layout.XAxis` instance or dict with compatible properties yaxis :class:`plotly.graph_objects.layout.YAxis` instance or dict with compatible properties frames The 'frames' property is a tuple of instances of Frame that may be specified as: - A list or tuple of instances of plotly.graph_objs.Frame - A list or tuple of dicts of string/value properties that will be passed to the Frame constructor Supported dict properties: baseframe The name of the frame into which this frame's properties are merged before applying. This is used to unify properties and avoid needing to specify the same values for the same properties in multiple frames. data A list of traces this frame modifies. The format is identical to the normal trace definition. group An identifier that specifies the group to which the frame belongs, used by animate to select a subset of frames. layout Layout properties which this frame modifies. The format is identical to the normal layout definition. name A label by which to identify the frame traces A list of trace indices that identify the respective traces in the data attribute skip_invalid: bool If True, invalid properties in the figure specification will be skipped silently. If False (default) invalid properties in the figure specification will result in a ValueError Raises ------ ValueError if a property in the specification of data, layout, or frames is invalid AND skip_invalid is False """ super(FigureWidget, self).__init__(data, layout, frames, skip_invalid, **kwargs) def add_area( self, customdata=None, customdatasrc=None, hoverinfo=None, hoverinfosrc=None, hoverlabel=None, ids=None, idssrc=None, legendgroup=None, marker=None, meta=None, metasrc=None, name=None, opacity=None, r=None, rsrc=None, showlegend=None, stream=None, t=None, tsrc=None, uid=None, uirevision=None, visible=None, row=None, col=None, **kwargs ): """ Add a new Area trace Parameters ---------- customdata Assigns extra data each datum. This may be useful when listening to hover, click and selection events. Note that, "scatter" traces also appends customdata items in the markers DOM elements customdatasrc Sets the source reference on Chart Studio Cloud for customdata . hoverinfo Determines which trace information appear on hover. If `none` or `skip` are set, no information is displayed upon hovering. But, if `none` is set, click and hover events are still fired. hoverinfosrc Sets the source reference on Chart Studio Cloud for hoverinfo . hoverlabel :class:`plotly.graph_objects.area.Hoverlabel` instance or dict with compatible properties ids Assigns id labels to each datum. These ids for object constancy of data points during animation. Should be an array of strings, not numbers or any other type. idssrc Sets the source reference on Chart Studio Cloud for ids . legendgroup Sets the legend group for this trace. Traces part of the same legend group hide/show at the same time when toggling legend items. marker :class:`plotly.graph_objects.area.Marker` instance or dict with compatible properties meta Assigns extra meta information associated with this trace that can be used in various text attributes. Attributes such as trace `name`, graph, axis and colorbar `title.text`, annotation `text` `rangeselector`, `updatemenues` and `sliders` `label` text all support `meta`. To access the trace `meta` values in an attribute in the same trace, simply use `%{meta[i]}` where `i` is the index or key of the `meta` item in question. To access trace `meta` in layout attributes, use `%{data[n[.meta[i]}` where `i` is the index or key of the `meta` and `n` is the trace index. metasrc Sets the source reference on Chart Studio Cloud for meta . name Sets the trace name. The trace name appear as the legend item and on hover. opacity Sets the opacity of the trace. r Area traces are deprecated! Please switch to the "barpolar" trace type. Sets the radial coordinates for legacy polar chart only. rsrc Sets the source reference on Chart Studio Cloud for r . showlegend Determines whether or not an item corresponding to this trace is shown in the legend. stream :class:`plotly.graph_objects.area.Stream` instance or dict with compatible properties t Area traces are deprecated! Please switch to the "barpolar" trace type. Sets the angular coordinates for legacy polar chart only. tsrc Sets the source reference on Chart Studio Cloud for t . uid Assign an id to this trace, Use this to provide object constancy between traces during animations and transitions. uirevision Controls persistence of some user-driven changes to the trace: `constraintrange` in `parcoords` traces, as well as some `editable: true` modifications such as `name` and `colorbar.title`. Defaults to `layout.uirevision`. Note that other user-driven trace attribute changes are controlled by `layout` attributes: `trace.visible` is controlled by `layout.legend.uirevision`, `selectedpoints` is controlled by `layout.selectionrevision`, and `colorbar.(x|y)` (accessible with `config: {editable: true}`) is controlled by `layout.editrevision`. Trace changes are tracked by `uid`, which only falls back on trace index if no `uid` is provided. So if your app can add/remove traces before the end of the `data` array, such that the same trace has a different index, you can still preserve user-driven changes if you give each trace a `uid` that stays with it as it moves. visible Determines whether or not this trace is visible. If "legendonly", the trace is not drawn, but can appear as a legend item (provided that the legend itself is visible). row : int or None (default) Subplot row index (starting from 1) for the trace to be added. Only valid if figure was created using `plotly.tools.make_subplots` col : int or None (default) Subplot col index (starting from 1) for the trace to be added. Only valid if figure was created using `plotly.tools.make_subplots` Returns ------- FigureWidget """ from plotly.graph_objs import Area new_trace = Area( customdata=customdata, customdatasrc=customdatasrc, hoverinfo=hoverinfo, hoverinfosrc=hoverinfosrc, hoverlabel=hoverlabel, ids=ids, idssrc=idssrc, legendgroup=legendgroup, marker=marker, meta=meta, metasrc=metasrc, name=name, opacity=opacity, r=r, rsrc=rsrc, showlegend=showlegend, stream=stream, t=t, tsrc=tsrc, uid=uid, uirevision=uirevision, visible=visible, **kwargs ) return self.add_trace(new_trace, row=row, col=col) def add_bar( self, alignmentgroup=None, base=None, basesrc=None, cliponaxis=None, constraintext=None, customdata=None, customdatasrc=None, dx=None, dy=None, error_x=None, error_y=None, hoverinfo=None, hoverinfosrc=None, hoverlabel=None, hovertemplate=None, hovertemplatesrc=None, hovertext=None, hovertextsrc=None, ids=None, idssrc=None, insidetextanchor=None, insidetextfont=None, legendgroup=None, marker=None, meta=None, metasrc=None, name=None, offset=None, offsetgroup=None, offsetsrc=None, opacity=None, orientation=None, outsidetextfont=None, r=None, rsrc=None, selected=None, selectedpoints=None, showlegend=None, stream=None, t=None, text=None, textangle=None, textfont=None, textposition=None, textpositionsrc=None, textsrc=None, texttemplate=None, texttemplatesrc=None, tsrc=None, uid=None, uirevision=None, unselected=None, visible=None, width=None, widthsrc=None, x=None, x0=None, xaxis=None, xcalendar=None, xperiod=None, xperiod0=None, xperiodalignment=None, xsrc=None, y=None, y0=None, yaxis=None, ycalendar=None, yperiod=None, yperiod0=None, yperiodalignment=None, ysrc=None, row=None, col=None, secondary_y=None, **kwargs ): """ Add a new Bar trace The data visualized by the span of the bars is set in `y` if `orientation` is set th "v" (the default) and the labels are set in `x`. By setting `orientation` to "h", the roles are interchanged. Parameters ---------- alignmentgroup Set several traces linked to the same position axis or matching axes to the same alignmentgroup. This controls whether bars compute their positional range dependently or independently. base Sets where the bar base is drawn (in position axis units). In "stack" or "relative" barmode, traces that set "base" will be excluded and drawn in "overlay" mode instead. basesrc Sets the source reference on Chart Studio Cloud for base . cliponaxis Determines whether the text nodes are clipped about the subplot axes. To show the text nodes above axis lines and tick labels, make sure to set `xaxis.layer` and `yaxis.layer` to *below traces*. constraintext Constrain the size of text inside or outside a bar to be no larger than the bar itself. customdata Assigns extra data each datum. This may be useful when listening to hover, click and selection events. Note that, "scatter" traces also appends customdata items in the markers DOM elements customdatasrc Sets the source reference on Chart Studio Cloud for customdata . dx Sets the x coordinate step. See `x0` for more info. dy Sets the y coordinate step. See `y0` for more info. error_x :class:`plotly.graph_objects.bar.ErrorX` instance or dict with compatible properties error_y :class:`plotly.graph_objects.bar.ErrorY` instance or dict with compatible properties hoverinfo Determines which trace information appear on hover. If `none` or `skip` are set, no information is displayed upon hovering. But, if `none` is set, click and hover events are still fired. hoverinfosrc Sets the source reference on Chart Studio Cloud for hoverinfo . hoverlabel :class:`plotly.graph_objects.bar.Hoverlabel` instance or dict with compatible properties hovertemplate Template string used for rendering the information that appear on hover box. Note that this will override `hoverinfo`. Variables are inserted using %{variable}, for example "y: %{y}". Numbers are formatted using d3-format's syntax %{variable:d3-format}, for example "Price: %{y:$.2f}". https://github.com/d3/d3-3.x-api- reference/blob/master/Formatting.md#d3_format for details on the formatting syntax. Dates are formatted using d3-time-format's syntax %{variable|d3-time- format}, for example "Day: %{2019-01-01|%A}". https://github.com/d3/d3-time-format#locale_format for details on the date formatting syntax. The variables available in `hovertemplate` are the ones emitted as event data described at this link https://plotly.com/javascript/plotlyjs-events/#event- data. Additionally, every attributes that can be specified per-point (the ones that are `arrayOk: true`) are available. variables `value` and `label`. Anything contained in tag `<extra>` is displayed in the secondary box, for example "<extra>{fullData.name}</extra>". To hide the secondary box completely, use an empty tag `<extra></extra>`. hovertemplatesrc Sets the source reference on Chart Studio Cloud for hovertemplate . hovertext Sets hover text elements associated with each (x,y) pair. If a single string, the same string appears over all the data points. If an array of string, the items are mapped in order to the this trace's (x,y) coordinates. To be seen, trace `hoverinfo` must contain a "text" flag. hovertextsrc Sets the source reference on Chart Studio Cloud for hovertext . ids Assigns id labels to each datum. These ids for object constancy of data points during animation. Should be an array of strings, not numbers or any other type. idssrc Sets the source reference on Chart Studio Cloud for ids . insidetextanchor Determines if texts are kept at center or start/end points in `textposition` "inside" mode. insidetextfont Sets the font used for `text` lying inside the bar. legendgroup Sets the legend group for this trace. Traces part of the same legend group hide/show at the same time when toggling legend items. marker :class:`plotly.graph_objects.bar.Marker` instance or dict with compatible properties meta Assigns extra meta information associated with this trace that can be used in various text attributes. Attributes such as trace `name`, graph, axis and colorbar `title.text`, annotation `text` `rangeselector`, `updatemenues` and `sliders` `label` text all support `meta`. To access the trace `meta` values in an attribute in the same trace, simply use `%{meta[i]}` where `i` is the index or key of the `meta` item in question. To access trace `meta` in layout attributes, use `%{data[n[.meta[i]}` where `i` is the index or key of the `meta` and `n` is the trace index. metasrc Sets the source reference on Chart Studio Cloud for meta . name Sets the trace name. The trace name appear as the legend item and on hover. offset Shifts the position where the bar is drawn (in position axis units). In "group" barmode, traces that set "offset" will be excluded and drawn in "overlay" mode instead. offsetgroup Set several traces linked to the same position axis or matching axes to the same offsetgroup where bars of the same position coordinate will line up. offsetsrc Sets the source reference on Chart Studio Cloud for offset . opacity Sets the opacity of the trace. orientation Sets the orientation of the bars. With "v" ("h"), the value of the each bar spans along the vertical (horizontal). outsidetextfont Sets the font used for `text` lying outside the bar. r r coordinates in scatter traces are deprecated!Please switch to the "scatterpolar" trace type.Sets the radial coordinatesfor legacy polar chart only. rsrc Sets the source reference on Chart Studio Cloud for r . selected :class:`plotly.graph_objects.bar.Selected` instance or dict with compatible properties selectedpoints Array containing integer indices of selected points. Has an effect only for traces that support selections. Note that an empty array means an empty selection where the `unselected` are turned on for all points, whereas, any other non-array values means no selection all where the `selected` and `unselected` styles have no effect. showlegend Determines whether or not an item corresponding to this trace is shown in the legend. stream :class:`plotly.graph_objects.bar.Stream` instance or dict with compatible properties t t coordinates in scatter traces are deprecated!Please switch to the "scatterpolar" trace type.Sets the angular coordinatesfor legacy polar chart only. text Sets text elements associated with each (x,y) pair. If a single string, the same string appears over all the data points. If an array of string, the items are mapped in order to the this trace's (x,y) coordinates. If trace `hoverinfo` contains a "text" flag and "hovertext" is not set, these elements will be seen in the hover labels. textangle Sets the angle of the tick labels with respect to the bar. For example, a `tickangle` of -90 draws the tick labels vertically. With "auto" the texts may automatically be rotated to fit with the maximum size in bars. textfont Sets the font used for `text`. textposition Specifies the location of the `text`. "inside" positions `text` inside, next to the bar end (rotated and scaled if needed). "outside" positions `text` outside, next to the bar end (scaled if needed), unless there is another bar stacked on this one, then the text gets pushed inside. "auto" tries to position `text` inside the bar, but if the bar is too small and no bar is stacked on this one the text is moved outside. textpositionsrc Sets the source reference on Chart Studio Cloud for textposition . textsrc Sets the source reference on Chart Studio Cloud for text . texttemplate Template string used for rendering the information text that appear on points. Note that this will override `textinfo`. Variables are inserted using %{variable}, for example "y: %{y}". Numbers are formatted using d3-format's syntax %{variable:d3-format}, for example "Price: %{y:$.2f}". https://github.com/d3/d3-3.x-api- reference/blob/master/Formatting.md#d3_format for details on the formatting syntax. Dates are formatted using d3-time-format's syntax %{variable|d3-time- format}, for example "Day: %{2019-01-01|%A}". https://github.com/d3/d3-time-format#locale_format for details on the date formatting syntax. Every attributes that can be specified per-point (the ones that are `arrayOk: true`) are available. variables `value` and `label`. texttemplatesrc Sets the source reference on Chart Studio Cloud for texttemplate . tsrc Sets the source reference on Chart Studio Cloud for t . uid Assign an id to this trace, Use this to provide object constancy between traces during animations and transitions. uirevision Controls persistence of some user-driven changes to the trace: `constraintrange` in `parcoords` traces, as well as some `editable: true` modifications such as `name` and `colorbar.title`. Defaults to `layout.uirevision`. Note that other user-driven trace attribute changes are controlled by `layout` attributes: `trace.visible` is controlled by `layout.legend.uirevision`, `selectedpoints` is controlled by `layout.selectionrevision`, and `colorbar.(x|y)` (accessible with `config: {editable: true}`) is controlled by `layout.editrevision`. Trace changes are tracked by `uid`, which only falls back on trace index if no `uid` is provided. So if your app can add/remove traces before the end of the `data` array, such that the same trace has a different index, you can still preserve user-driven changes if you give each trace a `uid` that stays with it as it moves. unselected :class:`plotly.graph_objects.bar.Unselected` instance or dict with compatible properties visible Determines whether or not this trace is visible. If "legendonly", the trace is not drawn, but can appear as a legend item (provided that the legend itself is visible). width Sets the bar width (in position axis units). widthsrc Sets the source reference on Chart Studio Cloud for width . x Sets the x coordinates. x0 Alternate to `x`. Builds a linear space of x coordinates. Use with `dx` where `x0` is the starting coordinate and `dx` the step. xaxis Sets a reference between this trace's x coordinates and a 2D cartesian x axis. If "x" (the default value), the x coordinates refer to `layout.xaxis`. If "x2", the x coordinates refer to `layout.xaxis2`, and so on. xcalendar Sets the calendar system to use with `x` date data. xperiod Only relevant when the axis `type` is "date". Sets the period positioning in milliseconds or "M<n>" on the x axis. Special values in the form of "M<n>" could be used to declare the number of months. In this case `n` must be a positive integer. xperiod0 Only relevant when the axis `type` is "date". Sets the base for period positioning in milliseconds or date string on the x0 axis. When `x0period` is round number of weeks, the `x0period0` by default would be on a Sunday i.e. 2000-01-02, otherwise it would be at 2000-01-01. xperiodalignment Only relevant when the axis `type` is "date". Sets the alignment of data points on the x axis. xsrc Sets the source reference on Chart Studio Cloud for x . y Sets the y coordinates. y0 Alternate to `y`. Builds a linear space of y coordinates. Use with `dy` where `y0` is the starting coordinate and `dy` the step. yaxis Sets a reference between this trace's y coordinates and a 2D cartesian y axis. If "y" (the default value), the y coordinates refer to `layout.yaxis`. If "y2", the y coordinates refer to `layout.yaxis2`, and so on. ycalendar Sets the calendar system to use with `y` date data. yperiod Only relevant when the axis `type` is "date". Sets the period positioning in milliseconds or "M<n>" on the y axis. Special values in the form of "M<n>" could be used to declare the number of months. In this case `n` must be a positive integer. yperiod0 Only relevant when the axis `type` is "date". Sets the base for period positioning in milliseconds or date string on the y0 axis. When `y0period` is round number of weeks, the `y0period0` by default would be on a Sunday i.e. 2000-01-02, otherwise it would be at 2000-01-01. yperiodalignment Only relevant when the axis `type` is "date". Sets the alignment of data points on the y axis. ysrc Sets the source reference on Chart Studio Cloud for y . row : int or None (default) Subplot row index (starting from 1) for the trace to be added. Only valid if figure was created using `plotly.tools.make_subplots` col : int or None (default) Subplot col index (starting from 1) for the trace to be added. Only valid if figure was created using `plotly.tools.make_subplots` secondary_y: boolean or None (default None) If True, associate this trace with the secondary y-axis of the subplot at the specified row and col. Only valid if all of the following conditions are satisfied: * The figure was created using `plotly.subplots.make_subplots`. * The row and col arguments are not None * The subplot at the specified row and col has type xy (which is the default) and secondary_y True. These properties are specified in the specs argument to make_subplots. See the make_subplots docstring for more info. Returns ------- FigureWidget """ from plotly.graph_objs import Bar new_trace = Bar( alignmentgroup=alignmentgroup, base=base, basesrc=basesrc, cliponaxis=cliponaxis, constraintext=constraintext, customdata=customdata, customdatasrc=customdatasrc, dx=dx, dy=dy, error_x=error_x, error_y=error_y, hoverinfo=hoverinfo, hoverinfosrc=hoverinfosrc, hoverlabel=hoverlabel, hovertemplate=hovertemplate, hovertemplatesrc=hovertemplatesrc, hovertext=hovertext, hovertextsrc=hovertextsrc, ids=ids, idssrc=idssrc, insidetextanchor=insidetextanchor, insidetextfont=insidetextfont, legendgroup=legendgroup, marker=marker, meta=meta, metasrc=metasrc, name=name, offset=offset, offsetgroup=offsetgroup, offsetsrc=offsetsrc, opacity=opacity, orientation=orientation, outsidetextfont=outsidetextfont, r=r, rsrc=rsrc, selected=selected, selectedpoints=selectedpoints, showlegend=showlegend, stream=stream, t=t, text=text, textangle=textangle, textfont=textfont, textposition=textposition, textpositionsrc=textpositionsrc, textsrc=textsrc, texttemplate=texttemplate, texttemplatesrc=texttemplatesrc, tsrc=tsrc, uid=uid, uirevision=uirevision, unselected=unselected, visible=visible, width=width, widthsrc=widthsrc, x=x, x0=x0, xaxis=xaxis, xcalendar=xcalendar, xperiod=xperiod, xperiod0=xperiod0, xperiodalignment=xperiodalignment, xsrc=xsrc, y=y, y0=y0, yaxis=yaxis, ycalendar=ycalendar, yperiod=yperiod, yperiod0=yperiod0, yperiodalignment=yperiodalignment, ysrc=ysrc, **kwargs ) return self.add_trace(new_trace, row=row, col=col, secondary_y=secondary_y) def add_barpolar( self, base=None, basesrc=None, customdata=None, customdatasrc=None, dr=None, dtheta=None, hoverinfo=None, hoverinfosrc=None, hoverlabel=None, hovertemplate=None, hovertemplatesrc=None, hovertext=None, hovertextsrc=None, ids=None, idssrc=None, legendgroup=None, marker=None, meta=None, metasrc=None, name=None, offset=None, offsetsrc=None, opacity=None, r=None, r0=None, rsrc=None, selected=None, selectedpoints=None, showlegend=None, stream=None, subplot=None, text=None, textsrc=None, theta=None, theta0=None, thetasrc=None, thetaunit=None, uid=None, uirevision=None, unselected=None, visible=None, width=None, widthsrc=None, row=None, col=None, **kwargs ): """ Add a new Barpolar trace The data visualized by the radial span of the bars is set in `r` Parameters ---------- base Sets where the bar base is drawn (in radial axis units). In "stack" barmode, traces that set "base" will be excluded and drawn in "overlay" mode instead. basesrc Sets the source reference on Chart Studio Cloud for base . customdata Assigns extra data each datum. This may be useful when listening to hover, click and selection events. Note that, "scatter" traces also appends customdata items in the markers DOM elements customdatasrc Sets the source reference on Chart Studio Cloud for customdata . dr Sets the r coordinate step. dtheta Sets the theta coordinate step. By default, the `dtheta` step equals the subplot's period divided by the length of the `r` coordinates. hoverinfo Determines which trace information appear on hover. If `none` or `skip` are set, no information is displayed upon hovering. But, if `none` is set, click and hover events are still fired. hoverinfosrc Sets the source reference on Chart Studio Cloud for hoverinfo . hoverlabel :class:`plotly.graph_objects.barpolar.Hoverlabel` instance or dict with compatible properties hovertemplate Template string used for rendering the information that appear on hover box. Note that this will override `hoverinfo`. Variables are inserted using %{variable}, for example "y: %{y}". Numbers are formatted using d3-format's syntax %{variable:d3-format}, for example "Price: %{y:$.2f}". https://github.com/d3/d3-3.x-api- reference/blob/master/Formatting.md#d3_format for details on the formatting syntax. Dates are formatted using d3-time-format's syntax %{variable|d3-time- format}, for example "Day: %{2019-01-01|%A}". https://github.com/d3/d3-time-format#locale_format for details on the date formatting syntax. The variables available in `hovertemplate` are the ones emitted as event data described at this link https://plotly.com/javascript/plotlyjs-events/#event- data. Additionally, every attributes that can be specified per-point (the ones that are `arrayOk: true`) are available. Anything contained in tag `<extra>` is displayed in the secondary box, for example "<extra>{fullData.name}</extra>". To hide the secondary box completely, use an empty tag `<extra></extra>`. hovertemplatesrc Sets the source reference on Chart Studio Cloud for hovertemplate . hovertext Same as `text`. hovertextsrc Sets the source reference on Chart Studio Cloud for hovertext . ids Assigns id labels to each datum. These ids for object constancy of data points during animation. Should be an array of strings, not numbers or any other type. idssrc Sets the source reference on Chart Studio Cloud for ids . legendgroup Sets the legend group for this trace. Traces part of the same legend group hide/show at the same time when toggling legend items. marker :class:`plotly.graph_objects.barpolar.Marker` instance or dict with compatible properties meta Assigns extra meta information associated with this trace that can be used in various text attributes. Attributes such as trace `name`, graph, axis and colorbar `title.text`, annotation `text` `rangeselector`, `updatemenues` and `sliders` `label` text all support `meta`. To access the trace `meta` values in an attribute in the same trace, simply use `%{meta[i]}` where `i` is the index or key of the `meta` item in question. To access trace `meta` in layout attributes, use `%{data[n[.meta[i]}` where `i` is the index or key of the `meta` and `n` is the trace index. metasrc Sets the source reference on Chart Studio Cloud for meta . name Sets the trace name. The trace name appear as the legend item and on hover. offset Shifts the angular position where the bar is drawn (in "thetatunit" units). offsetsrc Sets the source reference on Chart Studio Cloud for offset . opacity Sets the opacity of the trace. r Sets the radial coordinates r0 Alternate to `r`. Builds a linear space of r coordinates. Use with `dr` where `r0` is the starting coordinate and `dr` the step. rsrc Sets the source reference on Chart Studio Cloud for r . selected :class:`plotly.graph_objects.barpolar.Selected` instance or dict with compatible properties selectedpoints Array containing integer indices of selected points. Has an effect only for traces that support selections. Note that an empty array means an empty selection where the `unselected` are turned on for all points, whereas, any other non-array values means no selection all where the `selected` and `unselected` styles have no effect. showlegend Determines whether or not an item corresponding to this trace is shown in the legend. stream :class:`plotly.graph_objects.barpolar.Stream` instance or dict with compatible properties subplot Sets a reference between this trace's data coordinates and a polar subplot. If "polar" (the default value), the data refer to `layout.polar`. If "polar2", the data refer to `layout.polar2`, and so on. text Sets hover text elements associated with each bar. If a single string, the same string appears over all bars. If an array of string, the items are mapped in order to the this trace's coordinates. textsrc Sets the source reference on Chart Studio Cloud for text . theta Sets the angular coordinates theta0 Alternate to `theta`. Builds a linear space of theta coordinates. Use with `dtheta` where `theta0` is the starting coordinate and `dtheta` the step. thetasrc Sets the source reference on Chart Studio Cloud for theta . thetaunit Sets the unit of input "theta" values. Has an effect only when on "linear" angular axes. uid Assign an id to this trace, Use this to provide object constancy between traces during animations and transitions. uirevision Controls persistence of some user-driven changes to the trace: `constraintrange` in `parcoords` traces, as well as some `editable: true` modifications such as `name` and `colorbar.title`. Defaults to `layout.uirevision`. Note that other user-driven trace attribute changes are controlled by `layout` attributes: `trace.visible` is controlled by `layout.legend.uirevision`, `selectedpoints` is controlled by `layout.selectionrevision`, and `colorbar.(x|y)` (accessible with `config: {editable: true}`) is controlled by `layout.editrevision`. Trace changes are tracked by `uid`, which only falls back on trace index if no `uid` is provided. So if your app can add/remove traces before the end of the `data` array, such that the same trace has a different index, you can still preserve user-driven changes if you give each trace a `uid` that stays with it as it moves. unselected :class:`plotly.graph_objects.barpolar.Unselected` instance or dict with compatible properties visible Determines whether or not this trace is visible. If "legendonly", the trace is not drawn, but can appear as a legend item (provided that the legend itself is visible). width Sets the bar angular width (in "thetaunit" units). widthsrc Sets the source reference on Chart Studio Cloud for width . row : int or None (default) Subplot row index (starting from 1) for the trace to be added. Only valid if figure was created using `plotly.tools.make_subplots` col : int or None (default) Subplot col index (starting from 1) for the trace to be added. Only valid if figure was created using `plotly.tools.make_subplots` Returns ------- FigureWidget """ from plotly.graph_objs import Barpolar new_trace = Barpolar( base=base, basesrc=basesrc, customdata=customdata, customdatasrc=customdatasrc, dr=dr, dtheta=dtheta, hoverinfo=hoverinfo, hoverinfosrc=hoverinfosrc, hoverlabel=hoverlabel, hovertemplate=hovertemplate, hovertemplatesrc=hovertemplatesrc, hovertext=hovertext, hovertextsrc=hovertextsrc, ids=ids, idssrc=idssrc, legendgroup=legendgroup, marker=marker, meta=meta, metasrc=metasrc, name=name, offset=offset, offsetsrc=offsetsrc, opacity=opacity, r=r, r0=r0, rsrc=rsrc, selected=selected, selectedpoints=selectedpoints, showlegend=showlegend, stream=stream, subplot=subplot, text=text, textsrc=textsrc, theta=theta, theta0=theta0, thetasrc=thetasrc, thetaunit=thetaunit, uid=uid, uirevision=uirevision, unselected=unselected, visible=visible, width=width, widthsrc=widthsrc, **kwargs ) return self.add_trace(new_trace, row=row, col=col) def add_box( self, alignmentgroup=None, boxmean=None, boxpoints=None, customdata=None, customdatasrc=None, dx=None, dy=None, fillcolor=None, hoverinfo=None, hoverinfosrc=None, hoverlabel=None, hoveron=None, hovertemplate=None, hovertemplatesrc=None, hovertext=None, hovertextsrc=None, ids=None, idssrc=None, jitter=None, legendgroup=None, line=None, lowerfence=None, lowerfencesrc=None, marker=None, mean=None, meansrc=None, median=None, mediansrc=None, meta=None, metasrc=None, name=None, notched=None, notchspan=None, notchspansrc=None, notchwidth=None, offsetgroup=None, opacity=None, orientation=None, pointpos=None, q1=None, q1src=None, q3=None, q3src=None, quartilemethod=None, sd=None, sdsrc=None, selected=None, selectedpoints=None, showlegend=None, stream=None, text=None, textsrc=None, uid=None, uirevision=None, unselected=None, upperfence=None, upperfencesrc=None, visible=None, whiskerwidth=None, width=None, x=None, x0=None, xaxis=None, xcalendar=None, xperiod=None, xperiod0=None, xperiodalignment=None, xsrc=None, y=None, y0=None, yaxis=None, ycalendar=None, yperiod=None, yperiod0=None, yperiodalignment=None, ysrc=None, row=None, col=None, secondary_y=None, **kwargs ): """ Add a new Box trace Each box spans from quartile 1 (Q1) to quartile 3 (Q3). The second quartile (Q2, i.e. the median) is marked by a line inside the box. The fences grow outward from the boxes' edges, by default they span +/- 1.5 times the interquartile range (IQR: Q3-Q1), The sample mean and standard deviation as well as notches and the sample, outlier and suspected outliers points can be optionally added to the box plot. The values and positions corresponding to each boxes can be input using two signatures. The first signature expects users to supply the sample values in the `y` data array for vertical boxes (`x` for horizontal boxes). By supplying an `x` (`y`) array, one box per distinct `x` (`y`) value is drawn If no `x` (`y`) list is provided, a single box is drawn. In this case, the box is positioned with the trace `name` or with `x0` (`y0`) if provided. The second signature expects users to supply the boxes corresponding Q1, median and Q3 statistics in the `q1`, `median` and `q3` data arrays respectively. Other box features relying on statistics namely `lowerfence`, `upperfence`, `notchspan` can be set directly by the users. To have plotly compute them or to show sample points besides the boxes, users can set the `y` data array for vertical boxes (`x` for horizontal boxes) to a 2D array with the outer length corresponding to the number of boxes in the traces and the inner length corresponding the sample size. Parameters ---------- alignmentgroup Set several traces linked to the same position axis or matching axes to the same alignmentgroup. This controls whether bars compute their positional range dependently or independently. boxmean If True, the mean of the box(es)' underlying distribution is drawn as a dashed line inside the box(es). If "sd" the standard deviation is also drawn. Defaults to True when `mean` is set. Defaults to "sd" when `sd` is set Otherwise defaults to False. boxpoints If "outliers", only the sample points lying outside the whiskers are shown If "suspectedoutliers", the outlier points are shown and points either less than 4*Q1-3*Q3 or greater than 4*Q3-3*Q1 are highlighted (see `outliercolor`) If "all", all sample points are shown If False, only the box(es) are shown with no sample points Defaults to "suspectedoutliers" when `marker.outliercolor` or `marker.line.outliercolor` is set. Defaults to "all" under the q1/median/q3 signature. Otherwise defaults to "outliers". customdata Assigns extra data each datum. This may be useful when listening to hover, click and selection events. Note that, "scatter" traces also appends customdata items in the markers DOM elements customdatasrc Sets the source reference on Chart Studio Cloud for customdata . dx Sets the x coordinate step for multi-box traces set using q1/median/q3. dy Sets the y coordinate step for multi-box traces set using q1/median/q3. fillcolor Sets the fill color. Defaults to a half-transparent variant of the line color, marker color, or marker line color, whichever is available. hoverinfo Determines which trace information appear on hover. If `none` or `skip` are set, no information is displayed upon hovering. But, if `none` is set, click and hover events are still fired. hoverinfosrc Sets the source reference on Chart Studio Cloud for hoverinfo . hoverlabel :class:`plotly.graph_objects.box.Hoverlabel` instance or dict with compatible properties hoveron Do the hover effects highlight individual boxes or sample points or both? hovertemplate Template string used for rendering the information that appear on hover box. Note that this will override `hoverinfo`. Variables are inserted using %{variable}, for example "y: %{y}". Numbers are formatted using d3-format's syntax %{variable:d3-format}, for example "Price: %{y:$.2f}". https://github.com/d3/d3-3.x-api- reference/blob/master/Formatting.md#d3_format for details on the formatting syntax. Dates are formatted using d3-time-format's syntax %{variable|d3-time- format}, for example "Day: %{2019-01-01|%A}". https://github.com/d3/d3-time-format#locale_format for details on the date formatting syntax. The variables available in `hovertemplate` are the ones emitted as event data described at this link https://plotly.com/javascript/plotlyjs-events/#event- data. Additionally, every attributes that can be specified per-point (the ones that are `arrayOk: true`) are available. Anything contained in tag `<extra>` is displayed in the secondary box, for example "<extra>{fullData.name}</extra>". To hide the secondary box completely, use an empty tag `<extra></extra>`. hovertemplatesrc Sets the source reference on Chart Studio Cloud for hovertemplate . hovertext Same as `text`. hovertextsrc Sets the source reference on Chart Studio Cloud for hovertext . ids Assigns id labels to each datum. These ids for object constancy of data points during animation. Should be an array of strings, not numbers or any other type. idssrc Sets the source reference on Chart Studio Cloud for ids . jitter Sets the amount of jitter in the sample points drawn. If 0, the sample points align along the distribution axis. If 1, the sample points are drawn in a random jitter of width equal to the width of the box(es). legendgroup Sets the legend group for this trace. Traces part of the same legend group hide/show at the same time when toggling legend items. line :class:`plotly.graph_objects.box.Line` instance or dict with compatible properties lowerfence Sets the lower fence values. There should be as many items as the number of boxes desired. This attribute has effect only under the q1/median/q3 signature. If `lowerfence` is not provided but a sample (in `y` or `x`) is set, we compute the lower as the last sample point below 1.5 times the IQR. lowerfencesrc Sets the source reference on Chart Studio Cloud for lowerfence . marker :class:`plotly.graph_objects.box.Marker` instance or dict with compatible properties mean Sets the mean values. There should be as many items as the number of boxes desired. This attribute has effect only under the q1/median/q3 signature. If `mean` is not provided but a sample (in `y` or `x`) is set, we compute the mean for each box using the sample values. meansrc Sets the source reference on Chart Studio Cloud for mean . median Sets the median values. There should be as many items as the number of boxes desired. mediansrc Sets the source reference on Chart Studio Cloud for median . meta Assigns extra meta information associated with this trace that can be used in various text attributes. Attributes such as trace `name`, graph, axis and colorbar `title.text`, annotation `text` `rangeselector`, `updatemenues` and `sliders` `label` text all support `meta`. To access the trace `meta` values in an attribute in the same trace, simply use `%{meta[i]}` where `i` is the index or key of the `meta` item in question. To access trace `meta` in layout attributes, use `%{data[n[.meta[i]}` where `i` is the index or key of the `meta` and `n` is the trace index. metasrc Sets the source reference on Chart Studio Cloud for meta . name Sets the trace name. The trace name appear as the legend item and on hover. For box traces, the name will also be used for the position coordinate, if `x` and `x0` (`y` and `y0` if horizontal) are missing and the position axis is categorical notched Determines whether or not notches are drawn. Notches displays a confidence interval around the median. We compute the confidence interval as median +/- 1.57 * IQR / sqrt(N), where IQR is the interquartile range and N is the sample size. If two boxes' notches do not overlap there is 95% confidence their medians differ. See https://sites.google.com/site/davidsstatistics/home /notched-box-plots for more info. Defaults to False unless `notchwidth` or `notchspan` is set. notchspan Sets the notch span from the boxes' `median` values. There should be as many items as the number of boxes desired. This attribute has effect only under the q1/median/q3 signature. If `notchspan` is not provided but a sample (in `y` or `x`) is set, we compute it as 1.57 * IQR / sqrt(N), where N is the sample size. notchspansrc Sets the source reference on Chart Studio Cloud for notchspan . notchwidth Sets the width of the notches relative to the box' width. For example, with 0, the notches are as wide as the box(es). offsetgroup Set several traces linked to the same position axis or matching axes to the same offsetgroup where bars of the same position coordinate will line up. opacity Sets the opacity of the trace. orientation Sets the orientation of the box(es). If "v" ("h"), the distribution is visualized along the vertical (horizontal). pointpos Sets the position of the sample points in relation to the box(es). If 0, the sample points are places over the center of the box(es). Positive (negative) values correspond to positions to the right (left) for vertical boxes and above (below) for horizontal boxes q1 Sets the Quartile 1 values. There should be as many items as the number of boxes desired. q1src Sets the source reference on Chart Studio Cloud for q1 . q3 Sets the Quartile 3 values. There should be as many items as the number of boxes desired. q3src Sets the source reference on Chart Studio Cloud for q3 . quartilemethod Sets the method used to compute the sample's Q1 and Q3 quartiles. The "linear" method uses the 25th percentile for Q1 and 75th percentile for Q3 as computed using method #10 (listed on http://www.amstat.org/publication s/jse/v14n3/langford.html). The "exclusive" method uses the median to divide the ordered dataset into two halves if the sample is odd, it does not include the median in either half - Q1 is then the median of the lower half and Q3 the median of the upper half. The "inclusive" method also uses the median to divide the ordered dataset into two halves but if the sample is odd, it includes the median in both halves - Q1 is then the median of the lower half and Q3 the median of the upper half. sd Sets the standard deviation values. There should be as many items as the number of boxes desired. This attribute has effect only under the q1/median/q3 signature. If `sd` is not provided but a sample (in `y` or `x`) is set, we compute the standard deviation for each box using the sample values. sdsrc Sets the source reference on Chart Studio Cloud for sd . selected :class:`plotly.graph_objects.box.Selected` instance or dict with compatible properties selectedpoints Array containing integer indices of selected points. Has an effect only for traces that support selections. Note that an empty array means an empty selection where the `unselected` are turned on for all points, whereas, any other non-array values means no selection all where the `selected` and `unselected` styles have no effect. showlegend Determines whether or not an item corresponding to this trace is shown in the legend. stream :class:`plotly.graph_objects.box.Stream` instance or dict with compatible properties text Sets the text elements associated with each sample value. If a single string, the same string appears over all the data points. If an array of string, the items are mapped in order to the this trace's (x,y) coordinates. To be seen, trace `hoverinfo` must contain a "text" flag. textsrc Sets the source reference on Chart Studio Cloud for text . uid Assign an id to this trace, Use this to provide object constancy between traces during animations and transitions. uirevision Controls persistence of some user-driven changes to the trace: `constraintrange` in `parcoords` traces, as well as some `editable: true` modifications such as `name` and `colorbar.title`. Defaults to `layout.uirevision`. Note that other user-driven trace attribute changes are controlled by `layout` attributes: `trace.visible` is controlled by `layout.legend.uirevision`, `selectedpoints` is controlled by `layout.selectionrevision`, and `colorbar.(x|y)` (accessible with `config: {editable: true}`) is controlled by `layout.editrevision`. Trace changes are tracked by `uid`, which only falls back on trace index if no `uid` is provided. So if your app can add/remove traces before the end of the `data` array, such that the same trace has a different index, you can still preserve user-driven changes if you give each trace a `uid` that stays with it as it moves. unselected :class:`plotly.graph_objects.box.Unselected` instance or dict with compatible properties upperfence Sets the upper fence values. There should be as many items as the number of boxes desired. This attribute has effect only under the q1/median/q3 signature. If `upperfence` is not provided but a sample (in `y` or `x`) is set, we compute the lower as the last sample point above 1.5 times the IQR. upperfencesrc Sets the source reference on Chart Studio Cloud for upperfence . visible Determines whether or not this trace is visible. If "legendonly", the trace is not drawn, but can appear as a legend item (provided that the legend itself is visible). whiskerwidth Sets the width of the whiskers relative to the box' width. For example, with 1, the whiskers are as wide as the box(es). width Sets the width of the box in data coordinate If 0 (default value) the width is automatically selected based on the positions of other box traces in the same subplot. x Sets the x sample data or coordinates. See overview for more info. x0 Sets the x coordinate for single-box traces or the starting coordinate for multi-box traces set using q1/median/q3. See overview for more info. xaxis Sets a reference between this trace's x coordinates and a 2D cartesian x axis. If "x" (the default value), the x coordinates refer to `layout.xaxis`. If "x2", the x coordinates refer to `layout.xaxis2`, and so on. xcalendar Sets the calendar system to use with `x` date data. xperiod Only relevant when the axis `type` is "date". Sets the period positioning in milliseconds or "M<n>" on the x axis. Special values in the form of "M<n>" could be used to declare the number of months. In this case `n` must be a positive integer. xperiod0 Only relevant when the axis `type` is "date". Sets the base for period positioning in milliseconds or date string on the x0 axis. When `x0period` is round number of weeks, the `x0period0` by default would be on a Sunday i.e. 2000-01-02, otherwise it would be at 2000-01-01. xperiodalignment Only relevant when the axis `type` is "date". Sets the alignment of data points on the x axis. xsrc Sets the source reference on Chart Studio Cloud for x . y Sets the y sample data or coordinates. See overview for more info. y0 Sets the y coordinate for single-box traces or the starting coordinate for multi-box traces set using q1/median/q3. See overview for more info. yaxis Sets a reference between this trace's y coordinates and a 2D cartesian y axis. If "y" (the default value), the y coordinates refer to `layout.yaxis`. If "y2", the y coordinates refer to `layout.yaxis2`, and so on. ycalendar Sets the calendar system to use with `y` date data. yperiod Only relevant when the axis `type` is "date". Sets the period positioning in milliseconds or "M<n>" on the y axis. Special values in the form of "M<n>" could be used to declare the number of months. In this case `n` must be a positive integer. yperiod0 Only relevant when the axis `type` is "date". Sets the base for period positioning in milliseconds or date string on the y0 axis. When `y0period` is round number of weeks, the `y0period0` by default would be on a Sunday i.e. 2000-01-02, otherwise it would be at 2000-01-01. yperiodalignment Only relevant when the axis `type` is "date". Sets the alignment of data points on the y axis. ysrc Sets the source reference on Chart Studio Cloud for y . row : int or None (default) Subplot row index (starting from 1) for the trace to be added. Only valid if figure was created using `plotly.tools.make_subplots` col : int or None (default) Subplot col index (starting from 1) for the trace to be added. Only valid if figure was created using `plotly.tools.make_subplots` secondary_y: boolean or None (default None) If True, associate this trace with the secondary y-axis of the subplot at the specified row and col. Only valid if all of the following conditions are satisfied: * The figure was created using `plotly.subplots.make_subplots`. * The row and col arguments are not None * The subplot at the specified row and col has type xy (which is the default) and secondary_y True. These properties are specified in the specs argument to make_subplots. See the make_subplots docstring for more info. Returns ------- FigureWidget """ from plotly.graph_objs import Box new_trace = Box( alignmentgroup=alignmentgroup, boxmean=boxmean, boxpoints=boxpoints, customdata=customdata, customdatasrc=customdatasrc, dx=dx, dy=dy, fillcolor=fillcolor, hoverinfo=hoverinfo, hoverinfosrc=hoverinfosrc, hoverlabel=hoverlabel, hoveron=hoveron, hovertemplate=hovertemplate, hovertemplatesrc=hovertemplatesrc, hovertext=hovertext, hovertextsrc=hovertextsrc, ids=ids, idssrc=idssrc, jitter=jitter, legendgroup=legendgroup, line=line, lowerfence=lowerfence, lowerfencesrc=lowerfencesrc, marker=marker, mean=mean, meansrc=meansrc, median=median, mediansrc=mediansrc, meta=meta, metasrc=metasrc, name=name, notched=notched, notchspan=notchspan, notchspansrc=notchspansrc, notchwidth=notchwidth, offsetgroup=offsetgroup, opacity=opacity, orientation=orientation, pointpos=pointpos, q1=q1, q1src=q1src, q3=q3, q3src=q3src, quartilemethod=quartilemethod, sd=sd, sdsrc=sdsrc, selected=selected, selectedpoints=selectedpoints, showlegend=showlegend, stream=stream, text=text, textsrc=textsrc, uid=uid, uirevision=uirevision, unselected=unselected, upperfence=upperfence, upperfencesrc=upperfencesrc, visible=visible, whiskerwidth=whiskerwidth, width=width, x=x, x0=x0, xaxis=xaxis, xcalendar=xcalendar, xperiod=xperiod, xperiod0=xperiod0, xperiodalignment=xperiodalignment, xsrc=xsrc, y=y, y0=y0, yaxis=yaxis, ycalendar=ycalendar, yperiod=yperiod, yperiod0=yperiod0, yperiodalignment=yperiodalignment, ysrc=ysrc, **kwargs ) return self.add_trace(new_trace, row=row, col=col, secondary_y=secondary_y) def add_candlestick( self, close=None, closesrc=None, customdata=None, customdatasrc=None, decreasing=None, high=None, highsrc=None, hoverinfo=None, hoverinfosrc=None, hoverlabel=None, hovertext=None, hovertextsrc=None, ids=None, idssrc=None, increasing=None, legendgroup=None, line=None, low=None, lowsrc=None, meta=None, metasrc=None, name=None, opacity=None, open=None, opensrc=None, selectedpoints=None, showlegend=None, stream=None, text=None, textsrc=None, uid=None, uirevision=None, visible=None, whiskerwidth=None, x=None, xaxis=None, xcalendar=None, xperiod=None, xperiod0=None, xperiodalignment=None, xsrc=None, yaxis=None, row=None, col=None, secondary_y=None, **kwargs ): """ Add a new Candlestick trace The candlestick is a style of financial chart describing open, high, low and close for a given `x` coordinate (most likely time). The boxes represent the spread between the `open` and `close` values and the lines represent the spread between the `low` and `high` values Sample points where the close value is higher (lower) then the open value are called increasing (decreasing). By default, increasing candles are drawn in green whereas decreasing are drawn in red. Parameters ---------- close Sets the close values. closesrc Sets the source reference on Chart Studio Cloud for close . customdata Assigns extra data each datum. This may be useful when listening to hover, click and selection events. Note that, "scatter" traces also appends customdata items in the markers DOM elements customdatasrc Sets the source reference on Chart Studio Cloud for customdata . decreasing :class:`plotly.graph_objects.candlestick.Decreasing` instance or dict with compatible properties high Sets the high values. highsrc Sets the source reference on Chart Studio Cloud for high . hoverinfo Determines which trace information appear on hover. If `none` or `skip` are set, no information is displayed upon hovering. But, if `none` is set, click and hover events are still fired. hoverinfosrc Sets the source reference on Chart Studio Cloud for hoverinfo . hoverlabel :class:`plotly.graph_objects.candlestick.Hoverlabel` instance or dict with compatible properties hovertext Same as `text`. hovertextsrc Sets the source reference on Chart Studio Cloud for hovertext . ids Assigns id labels to each datum. These ids for object constancy of data points during animation. Should be an array of strings, not numbers or any other type. idssrc Sets the source reference on Chart Studio Cloud for ids . increasing :class:`plotly.graph_objects.candlestick.Increasing` instance or dict with compatible properties legendgroup Sets the legend group for this trace. Traces part of the same legend group hide/show at the same time when toggling legend items. line :class:`plotly.graph_objects.candlestick.Line` instance or dict with compatible properties low Sets the low values. lowsrc Sets the source reference on Chart Studio Cloud for low . meta Assigns extra meta information associated with this trace that can be used in various text attributes. Attributes such as trace `name`, graph, axis and colorbar `title.text`, annotation `text` `rangeselector`, `updatemenues` and `sliders` `label` text all support `meta`. To access the trace `meta` values in an attribute in the same trace, simply use `%{meta[i]}` where `i` is the index or key of the `meta` item in question. To access trace `meta` in layout attributes, use `%{data[n[.meta[i]}` where `i` is the index or key of the `meta` and `n` is the trace index. metasrc Sets the source reference on Chart Studio Cloud for meta . name Sets the trace name. The trace name appear as the legend item and on hover. opacity Sets the opacity of the trace. open Sets the open values. opensrc Sets the source reference on Chart Studio Cloud for open . selectedpoints Array containing integer indices of selected points. Has an effect only for traces that support selections. Note that an empty array means an empty selection where the `unselected` are turned on for all points, whereas, any other non-array values means no selection all where the `selected` and `unselected` styles have no effect. showlegend Determines whether or not an item corresponding to this trace is shown in the legend. stream :class:`plotly.graph_objects.candlestick.Stream` instance or dict with compatible properties text Sets hover text elements associated with each sample point. If a single string, the same string appears over all the data points. If an array of string, the items are mapped in order to this trace's sample points. textsrc Sets the source reference on Chart Studio Cloud for text . uid Assign an id to this trace, Use this to provide object constancy between traces during animations and transitions. uirevision Controls persistence of some user-driven changes to the trace: `constraintrange` in `parcoords` traces, as well as some `editable: true` modifications such as `name` and `colorbar.title`. Defaults to `layout.uirevision`. Note that other user-driven trace attribute changes are controlled by `layout` attributes: `trace.visible` is controlled by `layout.legend.uirevision`, `selectedpoints` is controlled by `layout.selectionrevision`, and `colorbar.(x|y)` (accessible with `config: {editable: true}`) is controlled by `layout.editrevision`. Trace changes are tracked by `uid`, which only falls back on trace index if no `uid` is provided. So if your app can add/remove traces before the end of the `data` array, such that the same trace has a different index, you can still preserve user-driven changes if you give each trace a `uid` that stays with it as it moves. visible Determines whether or not this trace is visible. If "legendonly", the trace is not drawn, but can appear as a legend item (provided that the legend itself is visible). whiskerwidth Sets the width of the whiskers relative to the box' width. For example, with 1, the whiskers are as wide as the box(es). x Sets the x coordinates. If absent, linear coordinate will be generated. xaxis Sets a reference between this trace's x coordinates and a 2D cartesian x axis. If "x" (the default value), the x coordinates refer to `layout.xaxis`. If "x2", the x coordinates refer to `layout.xaxis2`, and so on. xcalendar Sets the calendar system to use with `x` date data. xperiod Only relevant when the axis `type` is "date". Sets the period positioning in milliseconds or "M<n>" on the x axis. Special values in the form of "M<n>" could be used to declare the number of months. In this case `n` must be a positive integer. xperiod0 Only relevant when the axis `type` is "date". Sets the base for period positioning in milliseconds or date string on the x0 axis. When `x0period` is round number of weeks, the `x0period0` by default would be on a Sunday i.e. 2000-01-02, otherwise it would be at 2000-01-01. xperiodalignment Only relevant when the axis `type` is "date". Sets the alignment of data points on the x axis. xsrc Sets the source reference on Chart Studio Cloud for x . yaxis Sets a reference between this trace's y coordinates and a 2D cartesian y axis. If "y" (the default value), the y coordinates refer to `layout.yaxis`. If "y2", the y coordinates refer to `layout.yaxis2`, and so on. row : int or None (default) Subplot row index (starting from 1) for the trace to be added. Only valid if figure was created using `plotly.tools.make_subplots` col : int or None (default) Subplot col index (starting from 1) for the trace to be added. Only valid if figure was created using `plotly.tools.make_subplots` secondary_y: boolean or None (default None) If True, associate this trace with the secondary y-axis of the subplot at the specified row and col. Only valid if all of the following conditions are satisfied: * The figure was created using `plotly.subplots.make_subplots`. * The row and col arguments are not None * The subplot at the specified row and col has type xy (which is the default) and secondary_y True. These properties are specified in the specs argument to make_subplots. See the make_subplots docstring for more info. Returns ------- FigureWidget """ from plotly.graph_objs import Candlestick new_trace = Candlestick( close=close, closesrc=closesrc, customdata=customdata, customdatasrc=customdatasrc, decreasing=decreasing, high=high, highsrc=highsrc, hoverinfo=hoverinfo, hoverinfosrc=hoverinfosrc, hoverlabel=hoverlabel, hovertext=hovertext, hovertextsrc=hovertextsrc, ids=ids, idssrc=idssrc, increasing=increasing, legendgroup=legendgroup, line=line, low=low, lowsrc=lowsrc, meta=meta, metasrc=metasrc, name=name, opacity=opacity, open=open, opensrc=opensrc, selectedpoints=selectedpoints, showlegend=showlegend, stream=stream, text=text, textsrc=textsrc, uid=uid, uirevision=uirevision, visible=visible, whiskerwidth=whiskerwidth, x=x, xaxis=xaxis, xcalendar=xcalendar, xperiod=xperiod, xperiod0=xperiod0, xperiodalignment=xperiodalignment, xsrc=xsrc, yaxis=yaxis, **kwargs ) return self.add_trace(new_trace, row=row, col=col, secondary_y=secondary_y) def add_carpet( self, a=None, a0=None, aaxis=None, asrc=None, b=None, b0=None, baxis=None, bsrc=None, carpet=None, cheaterslope=None, color=None, customdata=None, customdatasrc=None, da=None, db=None, font=None, ids=None, idssrc=None, meta=None, metasrc=None, name=None, opacity=None, stream=None, uid=None, uirevision=None, visible=None, x=None, xaxis=None, xsrc=None, y=None, yaxis=None, ysrc=None, row=None, col=None, secondary_y=None, **kwargs ): """ Add a new Carpet trace The data describing carpet axis layout is set in `y` and (optionally) also `x`. If only `y` is present, `x` the plot is interpreted as a cheater plot and is filled in using the `y` values. `x` and `y` may either be 2D arrays matching with each dimension matching that of `a` and `b`, or they may be 1D arrays with total length equal to that of `a` and `b`. Parameters ---------- a An array containing values of the first parameter value a0 Alternate to `a`. Builds a linear space of a coordinates. Use with `da` where `a0` is the starting coordinate and `da` the step. aaxis :class:`plotly.graph_objects.carpet.Aaxis` instance or dict with compatible properties asrc Sets the source reference on Chart Studio Cloud for a . b A two dimensional array of y coordinates at each carpet point. b0 Alternate to `b`. Builds a linear space of a coordinates. Use with `db` where `b0` is the starting coordinate and `db` the step. baxis :class:`plotly.graph_objects.carpet.Baxis` instance or dict with compatible properties bsrc Sets the source reference on Chart Studio Cloud for b . carpet An identifier for this carpet, so that `scattercarpet` and `contourcarpet` traces can specify a carpet plot on which they lie cheaterslope The shift applied to each successive row of data in creating a cheater plot. Only used if `x` is been ommitted. color Sets default for all colors associated with this axis all at once: line, font, tick, and grid colors. Grid color is lightened by blending this with the plot background Individual pieces can override this. customdata Assigns extra data each datum. This may be useful when listening to hover, click and selection events. Note that, "scatter" traces also appends customdata items in the markers DOM elements customdatasrc Sets the source reference on Chart Studio Cloud for customdata . da Sets the a coordinate step. See `a0` for more info. db Sets the b coordinate step. See `b0` for more info. font The default font used for axis & tick labels on this carpet ids Assigns id labels to each datum. These ids for object constancy of data points during animation. Should be an array of strings, not numbers or any other type. idssrc Sets the source reference on Chart Studio Cloud for ids . meta Assigns extra meta information associated with this trace that can be used in various text attributes. Attributes such as trace `name`, graph, axis and colorbar `title.text`, annotation `text` `rangeselector`, `updatemenues` and `sliders` `label` text all support `meta`. To access the trace `meta` values in an attribute in the same trace, simply use `%{meta[i]}` where `i` is the index or key of the `meta` item in question. To access trace `meta` in layout attributes, use `%{data[n[.meta[i]}` where `i` is the index or key of the `meta` and `n` is the trace index. metasrc Sets the source reference on Chart Studio Cloud for meta . name Sets the trace name. The trace name appear as the legend item and on hover. opacity Sets the opacity of the trace. stream :class:`plotly.graph_objects.carpet.Stream` instance or dict with compatible properties uid Assign an id to this trace, Use this to provide object constancy between traces during animations and transitions. uirevision Controls persistence of some user-driven changes to the trace: `constraintrange` in `parcoords` traces, as well as some `editable: true` modifications such as `name` and `colorbar.title`. Defaults to `layout.uirevision`. Note that other user-driven trace attribute changes are controlled by `layout` attributes: `trace.visible` is controlled by `layout.legend.uirevision`, `selectedpoints` is controlled by `layout.selectionrevision`, and `colorbar.(x|y)` (accessible with `config: {editable: true}`) is controlled by `layout.editrevision`. Trace changes are tracked by `uid`, which only falls back on trace index if no `uid` is provided. So if your app can add/remove traces before the end of the `data` array, such that the same trace has a different index, you can still preserve user-driven changes if you give each trace a `uid` that stays with it as it moves. visible Determines whether or not this trace is visible. If "legendonly", the trace is not drawn, but can appear as a legend item (provided that the legend itself is visible). x A two dimensional array of x coordinates at each carpet point. If ommitted, the plot is a cheater plot and the xaxis is hidden by default. xaxis Sets a reference between this trace's x coordinates and a 2D cartesian x axis. If "x" (the default value), the x coordinates refer to `layout.xaxis`. If "x2", the x coordinates refer to `layout.xaxis2`, and so on. xsrc Sets the source reference on Chart Studio Cloud for x . y A two dimensional array of y coordinates at each carpet point. yaxis Sets a reference between this trace's y coordinates and a 2D cartesian y axis. If "y" (the default value), the y coordinates refer to `layout.yaxis`. If "y2", the y coordinates refer to `layout.yaxis2`, and so on. ysrc Sets the source reference on Chart Studio Cloud for y . row : int or None (default) Subplot row index (starting from 1) for the trace to be added. Only valid if figure was created using `plotly.tools.make_subplots` col : int or None (default) Subplot col index (starting from 1) for the trace to be added. Only valid if figure was created using `plotly.tools.make_subplots` secondary_y: boolean or None (default None) If True, associate this trace with the secondary y-axis of the subplot at the specified row and col. Only valid if all of the following conditions are satisfied: * The figure was created using `plotly.subplots.make_subplots`. * The row and col arguments are not None * The subplot at the specified row and col has type xy (which is the default) and secondary_y True. These properties are specified in the specs argument to make_subplots. See the make_subplots docstring for more info. Returns ------- FigureWidget """ from plotly.graph_objs import Carpet new_trace = Carpet( a=a, a0=a0, aaxis=aaxis, asrc=asrc, b=b, b0=b0, baxis=baxis, bsrc=bsrc, carpet=carpet, cheaterslope=cheaterslope, color=color, customdata=customdata, customdatasrc=customdatasrc, da=da, db=db, font=font, ids=ids, idssrc=idssrc, meta=meta, metasrc=metasrc, name=name, opacity=opacity, stream=stream, uid=uid, uirevision=uirevision, visible=visible, x=x, xaxis=xaxis, xsrc=xsrc, y=y, yaxis=yaxis, ysrc=ysrc, **kwargs ) return self.add_trace(new_trace, row=row, col=col, secondary_y=secondary_y) def add_choropleth( self, autocolorscale=None, coloraxis=None, colorbar=None, colorscale=None, customdata=None, customdatasrc=None, featureidkey=None, geo=None, geojson=None, hoverinfo=None, hoverinfosrc=None, hoverlabel=None, hovertemplate=None, hovertemplatesrc=None, hovertext=None, hovertextsrc=None, ids=None, idssrc=None, legendgroup=None, locationmode=None, locations=None, locationssrc=None, marker=None, meta=None, metasrc=None, name=None, reversescale=None, selected=None, selectedpoints=None, showlegend=None, showscale=None, stream=None, text=None, textsrc=None, uid=None, uirevision=None, unselected=None, visible=None, z=None, zauto=None, zmax=None, zmid=None, zmin=None, zsrc=None, row=None, col=None, **kwargs ): """ Add a new Choropleth trace The data that describes the choropleth value-to-color mapping is set in `z`. The geographic locations corresponding to each value in `z` are set in `locations`. Parameters ---------- autocolorscale Determines whether the colorscale is a default palette (`autocolorscale: true`) or the palette determined by `colorscale`. In case `colorscale` is unspecified or `autocolorscale` is true, the default palette will be chosen according to whether numbers in the `color` array are all positive, all negative or mixed. coloraxis Sets a reference to a shared color axis. References to these shared color axes are "coloraxis", "coloraxis2", "coloraxis3", etc. Settings for these shared color axes are set in the layout, under `layout.coloraxis`, `layout.coloraxis2`, etc. Note that multiple color scales can be linked to the same color axis. colorbar :class:`plotly.graph_objects.choropleth.ColorBar` instance or dict with compatible properties colorscale Sets the colorscale. The colorscale must be an array containing arrays mapping a normalized value to an rgb, rgba, hex, hsl, hsv, or named color string. At minimum, a mapping for the lowest (0) and highest (1) values are required. For example, `[[0, 'rgb(0,0,255)'], [1, 'rgb(255,0,0)']]`. To control the bounds of the colorscale in color space, use`zmin` and `zmax`. Alternatively, `colorscale` may be a palette name string of the following list: Greys,YlGnBu,Greens,YlOrR d,Bluered,RdBu,Reds,Blues,Picnic,Rainbow,Portland,Jet,H ot,Blackbody,Earth,Electric,Viridis,Cividis. customdata Assigns extra data each datum. This may be useful when listening to hover, click and selection events. Note that, "scatter" traces also appends customdata items in the markers DOM elements customdatasrc Sets the source reference on Chart Studio Cloud for customdata . featureidkey Sets the key in GeoJSON features which is used as id to match the items included in the `locations` array. Only has an effect when `geojson` is set. Support nested property, for example "properties.name". geo Sets a reference between this trace's geospatial coordinates and a geographic map. If "geo" (the default value), the geospatial coordinates refer to `layout.geo`. If "geo2", the geospatial coordinates refer to `layout.geo2`, and so on. geojson Sets optional GeoJSON data associated with this trace. If not given, the features on the base map are used. It can be set as a valid GeoJSON object or as a URL string. Note that we only accept GeoJSONs of type "FeatureCollection" or "Feature" with geometries of type "Polygon" or "MultiPolygon". hoverinfo Determines which trace information appear on hover. If `none` or `skip` are set, no information is displayed upon hovering. But, if `none` is set, click and hover events are still fired. hoverinfosrc Sets the source reference on Chart Studio Cloud for hoverinfo . hoverlabel :class:`plotly.graph_objects.choropleth.Hoverlabel` instance or dict with compatible properties hovertemplate Template string used for rendering the information that appear on hover box. Note that this will override `hoverinfo`. Variables are inserted using %{variable}, for example "y: %{y}". Numbers are formatted using d3-format's syntax %{variable:d3-format}, for example "Price: %{y:$.2f}". https://github.com/d3/d3-3.x-api- reference/blob/master/Formatting.md#d3_format for details on the formatting syntax. Dates are formatted using d3-time-format's syntax %{variable|d3-time- format}, for example "Day: %{2019-01-01|%A}". https://github.com/d3/d3-time-format#locale_format for details on the date formatting syntax. The variables available in `hovertemplate` are the ones emitted as event data described at this link https://plotly.com/javascript/plotlyjs-events/#event- data. Additionally, every attributes that can be specified per-point (the ones that are `arrayOk: true`) are available. Anything contained in tag `<extra>` is displayed in the secondary box, for example "<extra>{fullData.name}</extra>". To hide the secondary box completely, use an empty tag `<extra></extra>`. hovertemplatesrc Sets the source reference on Chart Studio Cloud for hovertemplate . hovertext Same as `text`. hovertextsrc Sets the source reference on Chart Studio Cloud for hovertext . ids Assigns id labels to each datum. These ids for object constancy of data points during animation. Should be an array of strings, not numbers or any other type. idssrc Sets the source reference on Chart Studio Cloud for ids . legendgroup Sets the legend group for this trace. Traces part of the same legend group hide/show at the same time when toggling legend items. locationmode Determines the set of locations used to match entries in `locations` to regions on the map. Values "ISO-3", "USA-states", *country names* correspond to features on the base map and value "geojson-id" corresponds to features from a custom GeoJSON linked to the `geojson` attribute. locations Sets the coordinates via location IDs or names. See `locationmode` for more info. locationssrc Sets the source reference on Chart Studio Cloud for locations . marker :class:`plotly.graph_objects.choropleth.Marker` instance or dict with compatible properties meta Assigns extra meta information associated with this trace that can be used in various text attributes. Attributes such as trace `name`, graph, axis and colorbar `title.text`, annotation `text` `rangeselector`, `updatemenues` and `sliders` `label` text all support `meta`. To access the trace `meta` values in an attribute in the same trace, simply use `%{meta[i]}` where `i` is the index or key of the `meta` item in question. To access trace `meta` in layout attributes, use `%{data[n[.meta[i]}` where `i` is the index or key of the `meta` and `n` is the trace index. metasrc Sets the source reference on Chart Studio Cloud for meta . name Sets the trace name. The trace name appear as the legend item and on hover. reversescale Reverses the color mapping if true. If true, `zmin` will correspond to the last color in the array and `zmax` will correspond to the first color. selected :class:`plotly.graph_objects.choropleth.Selected` instance or dict with compatible properties selectedpoints Array containing integer indices of selected points. Has an effect only for traces that support selections. Note that an empty array means an empty selection where the `unselected` are turned on for all points, whereas, any other non-array values means no selection all where the `selected` and `unselected` styles have no effect. showlegend Determines whether or not an item corresponding to this trace is shown in the legend. showscale Determines whether or not a colorbar is displayed for this trace. stream :class:`plotly.graph_objects.choropleth.Stream` instance or dict with compatible properties text Sets the text elements associated with each location. textsrc Sets the source reference on Chart Studio Cloud for text . uid Assign an id to this trace, Use this to provide object constancy between traces during animations and transitions. uirevision Controls persistence of some user-driven changes to the trace: `constraintrange` in `parcoords` traces, as well as some `editable: true` modifications such as `name` and `colorbar.title`. Defaults to `layout.uirevision`. Note that other user-driven trace attribute changes are controlled by `layout` attributes: `trace.visible` is controlled by `layout.legend.uirevision`, `selectedpoints` is controlled by `layout.selectionrevision`, and `colorbar.(x|y)` (accessible with `config: {editable: true}`) is controlled by `layout.editrevision`. Trace changes are tracked by `uid`, which only falls back on trace index if no `uid` is provided. So if your app can add/remove traces before the end of the `data` array, such that the same trace has a different index, you can still preserve user-driven changes if you give each trace a `uid` that stays with it as it moves. unselected :class:`plotly.graph_objects.choropleth.Unselected` instance or dict with compatible properties visible Determines whether or not this trace is visible. If "legendonly", the trace is not drawn, but can appear as a legend item (provided that the legend itself is visible). z Sets the color values. zauto Determines whether or not the color domain is computed with respect to the input data (here in `z`) or the bounds set in `zmin` and `zmax` Defaults to `false` when `zmin` and `zmax` are set by the user. zmax Sets the upper bound of the color domain. Value should have the same units as in `z` and if set, `zmin` must be set as well. zmid Sets the mid-point of the color domain by scaling `zmin` and/or `zmax` to be equidistant to this point. Value should have the same units as in `z`. Has no effect when `zauto` is `false`. zmin Sets the lower bound of the color domain. Value should have the same units as in `z` and if set, `zmax` must be set as well. zsrc Sets the source reference on Chart Studio Cloud for z . row : int or None (default) Subplot row index (starting from 1) for the trace to be added. Only valid if figure was created using `plotly.tools.make_subplots` col : int or None (default) Subplot col index (starting from 1) for the trace to be added. Only valid if figure was created using `plotly.tools.make_subplots` Returns ------- FigureWidget """ from plotly.graph_objs import Choropleth new_trace = Choropleth( autocolorscale=autocolorscale, coloraxis=coloraxis, colorbar=colorbar, colorscale=colorscale, customdata=customdata, customdatasrc=customdatasrc, featureidkey=featureidkey, geo=geo, geojson=geojson, hoverinfo=hoverinfo, hoverinfosrc=hoverinfosrc, hoverlabel=hoverlabel, hovertemplate=hovertemplate, hovertemplatesrc=hovertemplatesrc, hovertext=hovertext, hovertextsrc=hovertextsrc, ids=ids, idssrc=idssrc, legendgroup=legendgroup, locationmode=locationmode, locations=locations, locationssrc=locationssrc, marker=marker, meta=meta, metasrc=metasrc, name=name, reversescale=reversescale, selected=selected, selectedpoints=selectedpoints, showlegend=showlegend, showscale=showscale, stream=stream, text=text, textsrc=textsrc, uid=uid, uirevision=uirevision, unselected=unselected, visible=visible, z=z, zauto=zauto, zmax=zmax, zmid=zmid, zmin=zmin, zsrc=zsrc, **kwargs ) return self.add_trace(new_trace, row=row, col=col) def add_choroplethmapbox( self, autocolorscale=None, below=None, coloraxis=None, colorbar=None, colorscale=None, customdata=None, customdatasrc=None, featureidkey=None, geojson=None, hoverinfo=None, hoverinfosrc=None, hoverlabel=None, hovertemplate=None, hovertemplatesrc=None, hovertext=None, hovertextsrc=None, ids=None, idssrc=None, legendgroup=None, locations=None, locationssrc=None, marker=None, meta=None, metasrc=None, name=None, reversescale=None, selected=None, selectedpoints=None, showlegend=None, showscale=None, stream=None, subplot=None, text=None, textsrc=None, uid=None, uirevision=None, unselected=None, visible=None, z=None, zauto=None, zmax=None, zmid=None, zmin=None, zsrc=None, row=None, col=None, **kwargs ): """ Add a new Choroplethmapbox trace GeoJSON features to be filled are set in `geojson` The data that describes the choropleth value-to-color mapping is set in `locations` and `z`. Parameters ---------- autocolorscale Determines whether the colorscale is a default palette (`autocolorscale: true`) or the palette determined by `colorscale`. In case `colorscale` is unspecified or `autocolorscale` is true, the default palette will be chosen according to whether numbers in the `color` array are all positive, all negative or mixed. below Determines if the choropleth polygons will be inserted before the layer with the specified ID. By default, choroplethmapbox traces are placed above the water layers. If set to '', the layer will be inserted above every existing layer. coloraxis Sets a reference to a shared color axis. References to these shared color axes are "coloraxis", "coloraxis2", "coloraxis3", etc. Settings for these shared color axes are set in the layout, under `layout.coloraxis`, `layout.coloraxis2`, etc. Note that multiple color scales can be linked to the same color axis. colorbar :class:`plotly.graph_objects.choroplethmapbox.ColorBar` instance or dict with compatible properties colorscale Sets the colorscale. The colorscale must be an array containing arrays mapping a normalized value to an rgb, rgba, hex, hsl, hsv, or named color string. At minimum, a mapping for the lowest (0) and highest (1) values are required. For example, `[[0, 'rgb(0,0,255)'], [1, 'rgb(255,0,0)']]`. To control the bounds of the colorscale in color space, use`zmin` and `zmax`. Alternatively, `colorscale` may be a palette name string of the following list: Greys,YlGnBu,Greens,YlOrR d,Bluered,RdBu,Reds,Blues,Picnic,Rainbow,Portland,Jet,H ot,Blackbody,Earth,Electric,Viridis,Cividis. customdata Assigns extra data each datum. This may be useful when listening to hover, click and selection events. Note that, "scatter" traces also appends customdata items in the markers DOM elements customdatasrc Sets the source reference on Chart Studio Cloud for customdata . featureidkey Sets the key in GeoJSON features which is used as id to match the items included in the `locations` array. Support nested property, for example "properties.name". geojson Sets the GeoJSON data associated with this trace. It can be set as a valid GeoJSON object or as a URL string. Note that we only accept GeoJSONs of type "FeatureCollection" or "Feature" with geometries of type "Polygon" or "MultiPolygon". hoverinfo Determines which trace information appear on hover. If `none` or `skip` are set, no information is displayed upon hovering. But, if `none` is set, click and hover events are still fired. hoverinfosrc Sets the source reference on Chart Studio Cloud for hoverinfo . hoverlabel :class:`plotly.graph_objects.choroplethmapbox.Hoverlabe l` instance or dict with compatible properties hovertemplate Template string used for rendering the information that appear on hover box. Note that this will override `hoverinfo`. Variables are inserted using %{variable}, for example "y: %{y}". Numbers are formatted using d3-format's syntax %{variable:d3-format}, for example "Price: %{y:$.2f}". https://github.com/d3/d3-3.x-api- reference/blob/master/Formatting.md#d3_format for details on the formatting syntax. Dates are formatted using d3-time-format's syntax %{variable|d3-time- format}, for example "Day: %{2019-01-01|%A}". https://github.com/d3/d3-time-format#locale_format for details on the date formatting syntax. The variables available in `hovertemplate` are the ones emitted as event data described at this link https://plotly.com/javascript/plotlyjs-events/#event- data. Additionally, every attributes that can be specified per-point (the ones that are `arrayOk: true`) are available. variable `properties` Anything contained in tag `<extra>` is displayed in the secondary box, for example "<extra>{fullData.name}</extra>". To hide the secondary box completely, use an empty tag `<extra></extra>`. hovertemplatesrc Sets the source reference on Chart Studio Cloud for hovertemplate . hovertext Same as `text`. hovertextsrc Sets the source reference on Chart Studio Cloud for hovertext . ids Assigns id labels to each datum. These ids for object constancy of data points during animation. Should be an array of strings, not numbers or any other type. idssrc Sets the source reference on Chart Studio Cloud for ids . legendgroup Sets the legend group for this trace. Traces part of the same legend group hide/show at the same time when toggling legend items. locations Sets which features found in "geojson" to plot using their feature `id` field. locationssrc Sets the source reference on Chart Studio Cloud for locations . marker :class:`plotly.graph_objects.choroplethmapbox.Marker` instance or dict with compatible properties meta Assigns extra meta information associated with this trace that can be used in various text attributes. Attributes such as trace `name`, graph, axis and colorbar `title.text`, annotation `text` `rangeselector`, `updatemenues` and `sliders` `label` text all support `meta`. To access the trace `meta` values in an attribute in the same trace, simply use `%{meta[i]}` where `i` is the index or key of the `meta` item in question. To access trace `meta` in layout attributes, use `%{data[n[.meta[i]}` where `i` is the index or key of the `meta` and `n` is the trace index. metasrc Sets the source reference on Chart Studio Cloud for meta . name Sets the trace name. The trace name appear as the legend item and on hover. reversescale Reverses the color mapping if true. If true, `zmin` will correspond to the last color in the array and `zmax` will correspond to the first color. selected :class:`plotly.graph_objects.choroplethmapbox.Selected` instance or dict with compatible properties selectedpoints Array containing integer indices of selected points. Has an effect only for traces that support selections. Note that an empty array means an empty selection where the `unselected` are turned on for all points, whereas, any other non-array values means no selection all where the `selected` and `unselected` styles have no effect. showlegend Determines whether or not an item corresponding to this trace is shown in the legend. showscale Determines whether or not a colorbar is displayed for this trace. stream :class:`plotly.graph_objects.choroplethmapbox.Stream` instance or dict with compatible properties subplot Sets a reference between this trace's data coordinates and a mapbox subplot. If "mapbox" (the default value), the data refer to `layout.mapbox`. If "mapbox2", the data refer to `layout.mapbox2`, and so on. text Sets the text elements associated with each location. textsrc Sets the source reference on Chart Studio Cloud for text . uid Assign an id to this trace, Use this to provide object constancy between traces during animations and transitions. uirevision Controls persistence of some user-driven changes to the trace: `constraintrange` in `parcoords` traces, as well as some `editable: true` modifications such as `name` and `colorbar.title`. Defaults to `layout.uirevision`. Note that other user-driven trace attribute changes are controlled by `layout` attributes: `trace.visible` is controlled by `layout.legend.uirevision`, `selectedpoints` is controlled by `layout.selectionrevision`, and `colorbar.(x|y)` (accessible with `config: {editable: true}`) is controlled by `layout.editrevision`. Trace changes are tracked by `uid`, which only falls back on trace index if no `uid` is provided. So if your app can add/remove traces before the end of the `data` array, such that the same trace has a different index, you can still preserve user-driven changes if you give each trace a `uid` that stays with it as it moves. unselected :class:`plotly.graph_objects.choroplethmapbox.Unselecte d` instance or dict with compatible properties visible Determines whether or not this trace is visible. If "legendonly", the trace is not drawn, but can appear as a legend item (provided that the legend itself is visible). z Sets the color values. zauto Determines whether or not the color domain is computed with respect to the input data (here in `z`) or the bounds set in `zmin` and `zmax` Defaults to `false` when `zmin` and `zmax` are set by the user. zmax Sets the upper bound of the color domain. Value should have the same units as in `z` and if set, `zmin` must be set as well. zmid Sets the mid-point of the color domain by scaling `zmin` and/or `zmax` to be equidistant to this point. Value should have the same units as in `z`. Has no effect when `zauto` is `false`. zmin Sets the lower bound of the color domain. Value should have the same units as in `z` and if set, `zmax` must be set as well. zsrc Sets the source reference on Chart Studio Cloud for z . row : int or None (default) Subplot row index (starting from 1) for the trace to be added. Only valid if figure was created using `plotly.tools.make_subplots` col : int or None (default) Subplot col index (starting from 1) for the trace to be added. Only valid if figure was created using `plotly.tools.make_subplots` Returns ------- FigureWidget """ from plotly.graph_objs import Choroplethmapbox new_trace = Choroplethmapbox( autocolorscale=autocolorscale, below=below, coloraxis=coloraxis, colorbar=colorbar, colorscale=colorscale, customdata=customdata, customdatasrc=customdatasrc, featureidkey=featureidkey, geojson=geojson, hoverinfo=hoverinfo, hoverinfosrc=hoverinfosrc, hoverlabel=hoverlabel, hovertemplate=hovertemplate, hovertemplatesrc=hovertemplatesrc, hovertext=hovertext, hovertextsrc=hovertextsrc, ids=ids, idssrc=idssrc, legendgroup=legendgroup, locations=locations, locationssrc=locationssrc, marker=marker, meta=meta, metasrc=metasrc, name=name, reversescale=reversescale, selected=selected, selectedpoints=selectedpoints, showlegend=showlegend, showscale=showscale, stream=stream, subplot=subplot, text=text, textsrc=textsrc, uid=uid, uirevision=uirevision, unselected=unselected, visible=visible, z=z, zauto=zauto, zmax=zmax, zmid=zmid, zmin=zmin, zsrc=zsrc, **kwargs ) return self.add_trace(new_trace, row=row, col=col) def add_cone( self, anchor=None, autocolorscale=None, cauto=None, cmax=None, cmid=None, cmin=None, coloraxis=None, colorbar=None, colorscale=None, customdata=None, customdatasrc=None, hoverinfo=None, hoverinfosrc=None, hoverlabel=None, hovertemplate=None, hovertemplatesrc=None, hovertext=None, hovertextsrc=None, ids=None, idssrc=None, legendgroup=None, lighting=None, lightposition=None, meta=None, metasrc=None, name=None, opacity=None, reversescale=None, scene=None, showlegend=None, showscale=None, sizemode=None, sizeref=None, stream=None, text=None, textsrc=None, u=None, uid=None, uirevision=None, usrc=None, v=None, visible=None, vsrc=None, w=None, wsrc=None, x=None, xsrc=None, y=None, ysrc=None, z=None, zsrc=None, row=None, col=None, **kwargs ): """ Add a new Cone trace Use cone traces to visualize vector fields. Specify a vector field using 6 1D arrays, 3 position arrays `x`, `y` and `z` and 3 vector component arrays `u`, `v`, `w`. The cones are drawn exactly at the positions given by `x`, `y` and `z`. Parameters ---------- anchor Sets the cones' anchor with respect to their x/y/z positions. Note that "cm" denote the cone's center of mass which corresponds to 1/4 from the tail to tip. autocolorscale Determines whether the colorscale is a default palette (`autocolorscale: true`) or the palette determined by `colorscale`. In case `colorscale` is unspecified or `autocolorscale` is true, the default palette will be chosen according to whether numbers in the `color` array are all positive, all negative or mixed. cauto Determines whether or not the color domain is computed with respect to the input data (here u/v/w norm) or the bounds set in `cmin` and `cmax` Defaults to `false` when `cmin` and `cmax` are set by the user. cmax Sets the upper bound of the color domain. Value should have the same units as u/v/w norm and if set, `cmin` must be set as well. cmid Sets the mid-point of the color domain by scaling `cmin` and/or `cmax` to be equidistant to this point. Value should have the same units as u/v/w norm. Has no effect when `cauto` is `false`. cmin Sets the lower bound of the color domain. Value should have the same units as u/v/w norm and if set, `cmax` must be set as well. coloraxis Sets a reference to a shared color axis. References to these shared color axes are "coloraxis", "coloraxis2", "coloraxis3", etc. Settings for these shared color axes are set in the layout, under `layout.coloraxis`, `layout.coloraxis2`, etc. Note that multiple color scales can be linked to the same color axis. colorbar :class:`plotly.graph_objects.cone.ColorBar` instance or dict with compatible properties colorscale Sets the colorscale. The colorscale must be an array containing arrays mapping a normalized value to an rgb, rgba, hex, hsl, hsv, or named color string. At minimum, a mapping for the lowest (0) and highest (1) values are required. For example, `[[0, 'rgb(0,0,255)'], [1, 'rgb(255,0,0)']]`. To control the bounds of the colorscale in color space, use`cmin` and `cmax`. Alternatively, `colorscale` may be a palette name string of the following list: Greys,YlGnBu,Greens,YlOrR d,Bluered,RdBu,Reds,Blues,Picnic,Rainbow,Portland,Jet,H ot,Blackbody,Earth,Electric,Viridis,Cividis. customdata Assigns extra data each datum. This may be useful when listening to hover, click and selection events. Note that, "scatter" traces also appends customdata items in the markers DOM elements customdatasrc Sets the source reference on Chart Studio Cloud for customdata . hoverinfo Determines which trace information appear on hover. If `none` or `skip` are set, no information is displayed upon hovering. But, if `none` is set, click and hover events are still fired. hoverinfosrc Sets the source reference on Chart Studio Cloud for hoverinfo . hoverlabel :class:`plotly.graph_objects.cone.Hoverlabel` instance or dict with compatible properties hovertemplate Template string used for rendering the information that appear on hover box. Note that this will override `hoverinfo`. Variables are inserted using %{variable}, for example "y: %{y}". Numbers are formatted using d3-format's syntax %{variable:d3-format}, for example "Price: %{y:$.2f}". https://github.com/d3/d3-3.x-api- reference/blob/master/Formatting.md#d3_format for details on the formatting syntax. Dates are formatted using d3-time-format's syntax %{variable|d3-time- format}, for example "Day: %{2019-01-01|%A}". https://github.com/d3/d3-time-format#locale_format for details on the date formatting syntax. The variables available in `hovertemplate` are the ones emitted as event data described at this link https://plotly.com/javascript/plotlyjs-events/#event- data. Additionally, every attributes that can be specified per-point (the ones that are `arrayOk: true`) are available. variable `norm` Anything contained in tag `<extra>` is displayed in the secondary box, for example "<extra>{fullData.name}</extra>". To hide the secondary box completely, use an empty tag `<extra></extra>`. hovertemplatesrc Sets the source reference on Chart Studio Cloud for hovertemplate . hovertext Same as `text`. hovertextsrc Sets the source reference on Chart Studio Cloud for hovertext . ids Assigns id labels to each datum. These ids for object constancy of data points during animation. Should be an array of strings, not numbers or any other type. idssrc Sets the source reference on Chart Studio Cloud for ids . legendgroup Sets the legend group for this trace. Traces part of the same legend group hide/show at the same time when toggling legend items. lighting :class:`plotly.graph_objects.cone.Lighting` instance or dict with compatible properties lightposition :class:`plotly.graph_objects.cone.Lightposition` instance or dict with compatible properties meta Assigns extra meta information associated with this trace that can be used in various text attributes. Attributes such as trace `name`, graph, axis and colorbar `title.text`, annotation `text` `rangeselector`, `updatemenues` and `sliders` `label` text all support `meta`. To access the trace `meta` values in an attribute in the same trace, simply use `%{meta[i]}` where `i` is the index or key of the `meta` item in question. To access trace `meta` in layout attributes, use `%{data[n[.meta[i]}` where `i` is the index or key of the `meta` and `n` is the trace index. metasrc Sets the source reference on Chart Studio Cloud for meta . name Sets the trace name. The trace name appear as the legend item and on hover. opacity Sets the opacity of the surface. Please note that in the case of using high `opacity` values for example a value greater than or equal to 0.5 on two surfaces (and 0.25 with four surfaces), an overlay of multiple transparent surfaces may not perfectly be sorted in depth by the webgl API. This behavior may be improved in the near future and is subject to change. reversescale Reverses the color mapping if true. If true, `cmin` will correspond to the last color in the array and `cmax` will correspond to the first color. scene Sets a reference between this trace's 3D coordinate system and a 3D scene. If "scene" (the default value), the (x,y,z) coordinates refer to `layout.scene`. If "scene2", the (x,y,z) coordinates refer to `layout.scene2`, and so on. showlegend Determines whether or not an item corresponding to this trace is shown in the legend. showscale Determines whether or not a colorbar is displayed for this trace. sizemode Determines whether `sizeref` is set as a "scaled" (i.e unitless) scalar (normalized by the max u/v/w norm in the vector field) or as "absolute" value (in the same units as the vector field). sizeref Adjusts the cone size scaling. The size of the cones is determined by their u/v/w norm multiplied a factor and `sizeref`. This factor (computed internally) corresponds to the minimum "time" to travel across two successive x/y/z positions at the average velocity of those two successive positions. All cones in a given trace use the same factor. With `sizemode` set to "scaled", `sizeref` is unitless, its default value is 0.5 With `sizemode` set to "absolute", `sizeref` has the same units as the u/v/w vector field, its the default value is half the sample's maximum vector norm. stream :class:`plotly.graph_objects.cone.Stream` instance or dict with compatible properties text Sets the text elements associated with the cones. If trace `hoverinfo` contains a "text" flag and "hovertext" is not set, these elements will be seen in the hover labels. textsrc Sets the source reference on Chart Studio Cloud for text . u Sets the x components of the vector field. uid Assign an id to this trace, Use this to provide object constancy between traces during animations and transitions. uirevision Controls persistence of some user-driven changes to the trace: `constraintrange` in `parcoords` traces, as well as some `editable: true` modifications such as `name` and `colorbar.title`. Defaults to `layout.uirevision`. Note that other user-driven trace attribute changes are controlled by `layout` attributes: `trace.visible` is controlled by `layout.legend.uirevision`, `selectedpoints` is controlled by `layout.selectionrevision`, and `colorbar.(x|y)` (accessible with `config: {editable: true}`) is controlled by `layout.editrevision`. Trace changes are tracked by `uid`, which only falls back on trace index if no `uid` is provided. So if your app can add/remove traces before the end of the `data` array, such that the same trace has a different index, you can still preserve user-driven changes if you give each trace a `uid` that stays with it as it moves. usrc Sets the source reference on Chart Studio Cloud for u . v Sets the y components of the vector field. visible Determines whether or not this trace is visible. If "legendonly", the trace is not drawn, but can appear as a legend item (provided that the legend itself is visible). vsrc Sets the source reference on Chart Studio Cloud for v . w Sets the z components of the vector field. wsrc Sets the source reference on Chart Studio Cloud for w . x Sets the x coordinates of the vector field and of the displayed cones. xsrc Sets the source reference on Chart Studio Cloud for x . y Sets the y coordinates of the vector field and of the displayed cones. ysrc Sets the source reference on Chart Studio Cloud for y . z Sets the z coordinates of the vector field and of the displayed cones. zsrc Sets the source reference on Chart Studio Cloud for z . row : int or None (default) Subplot row index (starting from 1) for the trace to be added. Only valid if figure was created using `plotly.tools.make_subplots` col : int or None (default) Subplot col index (starting from 1) for the trace to be added. Only valid if figure was created using `plotly.tools.make_subplots` Returns ------- FigureWidget """ from plotly.graph_objs import Cone new_trace = Cone( anchor=anchor, autocolorscale=autocolorscale, cauto=cauto, cmax=cmax, cmid=cmid, cmin=cmin, coloraxis=coloraxis, colorbar=colorbar, colorscale=colorscale, customdata=customdata, customdatasrc=customdatasrc, hoverinfo=hoverinfo, hoverinfosrc=hoverinfosrc, hoverlabel=hoverlabel, hovertemplate=hovertemplate, hovertemplatesrc=hovertemplatesrc, hovertext=hovertext, hovertextsrc=hovertextsrc, ids=ids, idssrc=idssrc, legendgroup=legendgroup, lighting=lighting, lightposition=lightposition, meta=meta, metasrc=metasrc, name=name, opacity=opacity, reversescale=reversescale, scene=scene, showlegend=showlegend, showscale=showscale, sizemode=sizemode, sizeref=sizeref, stream=stream, text=text, textsrc=textsrc, u=u, uid=uid, uirevision=uirevision, usrc=usrc, v=v, visible=visible, vsrc=vsrc, w=w, wsrc=wsrc, x=x, xsrc=xsrc, y=y, ysrc=ysrc, z=z, zsrc=zsrc, **kwargs ) return self.add_trace(new_trace, row=row, col=col) def add_contour( self, autocolorscale=None, autocontour=None, coloraxis=None, colorbar=None, colorscale=None, connectgaps=None, contours=None, customdata=None, customdatasrc=None, dx=None, dy=None, fillcolor=None, hoverinfo=None, hoverinfosrc=None, hoverlabel=None, hoverongaps=None, hovertemplate=None, hovertemplatesrc=None, hovertext=None, hovertextsrc=None, ids=None, idssrc=None, legendgroup=None, line=None, meta=None, metasrc=None, name=None, ncontours=None, opacity=None, reversescale=None, showlegend=None, showscale=None, stream=None, text=None, textsrc=None, transpose=None, uid=None, uirevision=None, visible=None, x=None, x0=None, xaxis=None, xcalendar=None, xperiod=None, xperiod0=None, xperiodalignment=None, xsrc=None, xtype=None, y=None, y0=None, yaxis=None, ycalendar=None, yperiod=None, yperiod0=None, yperiodalignment=None, ysrc=None, ytype=None, z=None, zauto=None, zhoverformat=None, zmax=None, zmid=None, zmin=None, zsrc=None, row=None, col=None, secondary_y=None, **kwargs ): """ Add a new Contour trace The data from which contour lines are computed is set in `z`. Data in `z` must be a 2D list of numbers. Say that `z` has N rows and M columns, then by default, these N rows correspond to N y coordinates (set in `y` or auto-generated) and the M columns correspond to M x coordinates (set in `x` or auto- generated). By setting `transpose` to True, the above behavior is flipped. Parameters ---------- autocolorscale Determines whether the colorscale is a default palette (`autocolorscale: true`) or the palette determined by `colorscale`. In case `colorscale` is unspecified or `autocolorscale` is true, the default palette will be chosen according to whether numbers in the `color` array are all positive, all negative or mixed. autocontour Determines whether or not the contour level attributes are picked by an algorithm. If True, the number of contour levels can be set in `ncontours`. If False, set the contour level attributes in `contours`. coloraxis Sets a reference to a shared color axis. References to these shared color axes are "coloraxis", "coloraxis2", "coloraxis3", etc. Settings for these shared color axes are set in the layout, under `layout.coloraxis`, `layout.coloraxis2`, etc. Note that multiple color scales can be linked to the same color axis. colorbar :class:`plotly.graph_objects.contour.ColorBar` instance or dict with compatible properties colorscale Sets the colorscale. The colorscale must be an array containing arrays mapping a normalized value to an rgb, rgba, hex, hsl, hsv, or named color string. At minimum, a mapping for the lowest (0) and highest (1) values are required. For example, `[[0, 'rgb(0,0,255)'], [1, 'rgb(255,0,0)']]`. To control the bounds of the colorscale in color space, use`zmin` and `zmax`. Alternatively, `colorscale` may be a palette name string of the following list: Greys,YlGnBu,Greens,YlOrR d,Bluered,RdBu,Reds,Blues,Picnic,Rainbow,Portland,Jet,H ot,Blackbody,Earth,Electric,Viridis,Cividis. connectgaps Determines whether or not gaps (i.e. {nan} or missing values) in the `z` data are filled in. It is defaulted to true if `z` is a one dimensional array otherwise it is defaulted to false. contours :class:`plotly.graph_objects.contour.Contours` instance or dict with compatible properties customdata Assigns extra data each datum. This may be useful when listening to hover, click and selection events. Note that, "scatter" traces also appends customdata items in the markers DOM elements customdatasrc Sets the source reference on Chart Studio Cloud for customdata . dx Sets the x coordinate step. See `x0` for more info. dy Sets the y coordinate step. See `y0` for more info. fillcolor Sets the fill color if `contours.type` is "constraint". Defaults to a half-transparent variant of the line color, marker color, or marker line color, whichever is available. hoverinfo Determines which trace information appear on hover. If `none` or `skip` are set, no information is displayed upon hovering. But, if `none` is set, click and hover events are still fired. hoverinfosrc Sets the source reference on Chart Studio Cloud for hoverinfo . hoverlabel :class:`plotly.graph_objects.contour.Hoverlabel` instance or dict with compatible properties hoverongaps Determines whether or not gaps (i.e. {nan} or missing values) in the `z` data have hover labels associated with them. hovertemplate Template string used for rendering the information that appear on hover box. Note that this will override `hoverinfo`. Variables are inserted using %{variable}, for example "y: %{y}". Numbers are formatted using d3-format's syntax %{variable:d3-format}, for example "Price: %{y:$.2f}". https://github.com/d3/d3-3.x-api- reference/blob/master/Formatting.md#d3_format for details on the formatting syntax. Dates are formatted using d3-time-format's syntax %{variable|d3-time- format}, for example "Day: %{2019-01-01|%A}". https://github.com/d3/d3-time-format#locale_format for details on the date formatting syntax. The variables available in `hovertemplate` are the ones emitted as event data described at this link https://plotly.com/javascript/plotlyjs-events/#event- data. Additionally, every attributes that can be specified per-point (the ones that are `arrayOk: true`) are available. Anything contained in tag `<extra>` is displayed in the secondary box, for example "<extra>{fullData.name}</extra>". To hide the secondary box completely, use an empty tag `<extra></extra>`. hovertemplatesrc Sets the source reference on Chart Studio Cloud for hovertemplate . hovertext Same as `text`. hovertextsrc Sets the source reference on Chart Studio Cloud for hovertext . ids Assigns id labels to each datum. These ids for object constancy of data points during animation. Should be an array of strings, not numbers or any other type. idssrc Sets the source reference on Chart Studio Cloud for ids . legendgroup Sets the legend group for this trace. Traces part of the same legend group hide/show at the same time when toggling legend items. line :class:`plotly.graph_objects.contour.Line` instance or dict with compatible properties meta Assigns extra meta information associated with this trace that can be used in various text attributes. Attributes such as trace `name`, graph, axis and colorbar `title.text`, annotation `text` `rangeselector`, `updatemenues` and `sliders` `label` text all support `meta`. To access the trace `meta` values in an attribute in the same trace, simply use `%{meta[i]}` where `i` is the index or key of the `meta` item in question. To access trace `meta` in layout attributes, use `%{data[n[.meta[i]}` where `i` is the index or key of the `meta` and `n` is the trace index. metasrc Sets the source reference on Chart Studio Cloud for meta . name Sets the trace name. The trace name appear as the legend item and on hover. ncontours Sets the maximum number of contour levels. The actual number of contours will be chosen automatically to be less than or equal to the value of `ncontours`. Has an effect only if `autocontour` is True or if `contours.size` is missing. opacity Sets the opacity of the trace. reversescale Reverses the color mapping if true. If true, `zmin` will correspond to the last color in the array and `zmax` will correspond to the first color. showlegend Determines whether or not an item corresponding to this trace is shown in the legend. showscale Determines whether or not a colorbar is displayed for this trace. stream :class:`plotly.graph_objects.contour.Stream` instance or dict with compatible properties text Sets the text elements associated with each z value. textsrc Sets the source reference on Chart Studio Cloud for text . transpose Transposes the z data. uid Assign an id to this trace, Use this to provide object constancy between traces during animations and transitions. uirevision Controls persistence of some user-driven changes to the trace: `constraintrange` in `parcoords` traces, as well as some `editable: true` modifications such as `name` and `colorbar.title`. Defaults to `layout.uirevision`. Note that other user-driven trace attribute changes are controlled by `layout` attributes: `trace.visible` is controlled by `layout.legend.uirevision`, `selectedpoints` is controlled by `layout.selectionrevision`, and `colorbar.(x|y)` (accessible with `config: {editable: true}`) is controlled by `layout.editrevision`. Trace changes are tracked by `uid`, which only falls back on trace index if no `uid` is provided. So if your app can add/remove traces before the end of the `data` array, such that the same trace has a different index, you can still preserve user-driven changes if you give each trace a `uid` that stays with it as it moves. visible Determines whether or not this trace is visible. If "legendonly", the trace is not drawn, but can appear as a legend item (provided that the legend itself is visible). x Sets the x coordinates. x0 Alternate to `x`. Builds a linear space of x coordinates. Use with `dx` where `x0` is the starting coordinate and `dx` the step. xaxis Sets a reference between this trace's x coordinates and a 2D cartesian x axis. If "x" (the default value), the x coordinates refer to `layout.xaxis`. If "x2", the x coordinates refer to `layout.xaxis2`, and so on. xcalendar Sets the calendar system to use with `x` date data. xperiod Only relevant when the axis `type` is "date". Sets the period positioning in milliseconds or "M<n>" on the x axis. Special values in the form of "M<n>" could be used to declare the number of months. In this case `n` must be a positive integer. xperiod0 Only relevant when the axis `type` is "date". Sets the base for period positioning in milliseconds or date string on the x0 axis. When `x0period` is round number of weeks, the `x0period0` by default would be on a Sunday i.e. 2000-01-02, otherwise it would be at 2000-01-01. xperiodalignment Only relevant when the axis `type` is "date". Sets the alignment of data points on the x axis. xsrc Sets the source reference on Chart Studio Cloud for x . xtype If "array", the heatmap's x coordinates are given by "x" (the default behavior when `x` is provided). If "scaled", the heatmap's x coordinates are given by "x0" and "dx" (the default behavior when `x` is not provided). y Sets the y coordinates. y0 Alternate to `y`. Builds a linear space of y coordinates. Use with `dy` where `y0` is the starting coordinate and `dy` the step. yaxis Sets a reference between this trace's y coordinates and a 2D cartesian y axis. If "y" (the default value), the y coordinates refer to `layout.yaxis`. If "y2", the y coordinates refer to `layout.yaxis2`, and so on. ycalendar Sets the calendar system to use with `y` date data. yperiod Only relevant when the axis `type` is "date". Sets the period positioning in milliseconds or "M<n>" on the y axis. Special values in the form of "M<n>" could be used to declare the number of months. In this case `n` must be a positive integer. yperiod0 Only relevant when the axis `type` is "date". Sets the base for period positioning in milliseconds or date string on the y0 axis. When `y0period` is round number of weeks, the `y0period0` by default would be on a Sunday i.e. 2000-01-02, otherwise it would be at 2000-01-01. yperiodalignment Only relevant when the axis `type` is "date". Sets the alignment of data points on the y axis. ysrc Sets the source reference on Chart Studio Cloud for y . ytype If "array", the heatmap's y coordinates are given by "y" (the default behavior when `y` is provided) If "scaled", the heatmap's y coordinates are given by "y0" and "dy" (the default behavior when `y` is not provided) z Sets the z data. zauto Determines whether or not the color domain is computed with respect to the input data (here in `z`) or the bounds set in `zmin` and `zmax` Defaults to `false` when `zmin` and `zmax` are set by the user. zhoverformat Sets the hover text formatting rule using d3 formatting mini-languages which are very similar to those in Python. See: https://github.com/d3/d3-3.x-api- reference/blob/master/Formatting.md#d3_format zmax Sets the upper bound of the color domain. Value should have the same units as in `z` and if set, `zmin` must be set as well. zmid Sets the mid-point of the color domain by scaling `zmin` and/or `zmax` to be equidistant to this point. Value should have the same units as in `z`. Has no effect when `zauto` is `false`. zmin Sets the lower bound of the color domain. Value should have the same units as in `z` and if set, `zmax` must be set as well. zsrc Sets the source reference on Chart Studio Cloud for z . row : int or None (default) Subplot row index (starting from 1) for the trace to be added. Only valid if figure was created using `plotly.tools.make_subplots` col : int or None (default) Subplot col index (starting from 1) for the trace to be added. Only valid if figure was created using `plotly.tools.make_subplots` secondary_y: boolean or None (default None) If True, associate this trace with the secondary y-axis of the subplot at the specified row and col. Only valid if all of the following conditions are satisfied: * The figure was created using `plotly.subplots.make_subplots`. * The row and col arguments are not None * The subplot at the specified row and col has type xy (which is the default) and secondary_y True. These properties are specified in the specs argument to make_subplots. See the make_subplots docstring for more info. Returns ------- FigureWidget """ from plotly.graph_objs import Contour new_trace = Contour( autocolorscale=autocolorscale, autocontour=autocontour, coloraxis=coloraxis, colorbar=colorbar, colorscale=colorscale, connectgaps=connectgaps, contours=contours, customdata=customdata, customdatasrc=customdatasrc, dx=dx, dy=dy, fillcolor=fillcolor, hoverinfo=hoverinfo, hoverinfosrc=hoverinfosrc, hoverlabel=hoverlabel, hoverongaps=hoverongaps, hovertemplate=hovertemplate, hovertemplatesrc=hovertemplatesrc, hovertext=hovertext, hovertextsrc=hovertextsrc, ids=ids, idssrc=idssrc, legendgroup=legendgroup, line=line, meta=meta, metasrc=metasrc, name=name, ncontours=ncontours, opacity=opacity, reversescale=reversescale, showlegend=showlegend, showscale=showscale, stream=stream, text=text, textsrc=textsrc, transpose=transpose, uid=uid, uirevision=uirevision, visible=visible, x=x, x0=x0, xaxis=xaxis, xcalendar=xcalendar, xperiod=xperiod, xperiod0=xperiod0, xperiodalignment=xperiodalignment, xsrc=xsrc, xtype=xtype, y=y, y0=y0, yaxis=yaxis, ycalendar=ycalendar, yperiod=yperiod, yperiod0=yperiod0, yperiodalignment=yperiodalignment, ysrc=ysrc, ytype=ytype, z=z, zauto=zauto, zhoverformat=zhoverformat, zmax=zmax, zmid=zmid, zmin=zmin, zsrc=zsrc, **kwargs ) return self.add_trace(new_trace, row=row, col=col, secondary_y=secondary_y) def add_contourcarpet( self, a=None, a0=None, asrc=None, atype=None, autocolorscale=None, autocontour=None, b=None, b0=None, bsrc=None, btype=None, carpet=None, coloraxis=None, colorbar=None, colorscale=None, contours=None, customdata=None, customdatasrc=None, da=None, db=None, fillcolor=None, hovertext=None, hovertextsrc=None, ids=None, idssrc=None, legendgroup=None, line=None, meta=None, metasrc=None, name=None, ncontours=None, opacity=None, reversescale=None, showlegend=None, showscale=None, stream=None, text=None, textsrc=None, transpose=None, uid=None, uirevision=None, visible=None, xaxis=None, yaxis=None, z=None, zauto=None, zmax=None, zmid=None, zmin=None, zsrc=None, row=None, col=None, secondary_y=None, **kwargs ): """ Add a new Contourcarpet trace Plots contours on either the first carpet axis or the carpet axis with a matching `carpet` attribute. Data `z` is interpreted as matching that of the corresponding carpet axis. Parameters ---------- a Sets the x coordinates. a0 Alternate to `x`. Builds a linear space of x coordinates. Use with `dx` where `x0` is the starting coordinate and `dx` the step. asrc Sets the source reference on Chart Studio Cloud for a . atype If "array", the heatmap's x coordinates are given by "x" (the default behavior when `x` is provided). If "scaled", the heatmap's x coordinates are given by "x0" and "dx" (the default behavior when `x` is not provided). autocolorscale Determines whether the colorscale is a default palette (`autocolorscale: true`) or the palette determined by `colorscale`. In case `colorscale` is unspecified or `autocolorscale` is true, the default palette will be chosen according to whether numbers in the `color` array are all positive, all negative or mixed. autocontour Determines whether or not the contour level attributes are picked by an algorithm. If True, the number of contour levels can be set in `ncontours`. If False, set the contour level attributes in `contours`. b Sets the y coordinates. b0 Alternate to `y`. Builds a linear space of y coordinates. Use with `dy` where `y0` is the starting coordinate and `dy` the step. bsrc Sets the source reference on Chart Studio Cloud for b . btype If "array", the heatmap's y coordinates are given by "y" (the default behavior when `y` is provided) If "scaled", the heatmap's y coordinates are given by "y0" and "dy" (the default behavior when `y` is not provided) carpet The `carpet` of the carpet axes on which this contour trace lies coloraxis Sets a reference to a shared color axis. References to these shared color axes are "coloraxis", "coloraxis2", "coloraxis3", etc. Settings for these shared color axes are set in the layout, under `layout.coloraxis`, `layout.coloraxis2`, etc. Note that multiple color scales can be linked to the same color axis. colorbar :class:`plotly.graph_objects.contourcarpet.ColorBar` instance or dict with compatible properties colorscale Sets the colorscale. The colorscale must be an array containing arrays mapping a normalized value to an rgb, rgba, hex, hsl, hsv, or named color string. At minimum, a mapping for the lowest (0) and highest (1) values are required. For example, `[[0, 'rgb(0,0,255)'], [1, 'rgb(255,0,0)']]`. To control the bounds of the colorscale in color space, use`zmin` and `zmax`. Alternatively, `colorscale` may be a palette name string of the following list: Greys,YlGnBu,Greens,YlOrR d,Bluered,RdBu,Reds,Blues,Picnic,Rainbow,Portland,Jet,H ot,Blackbody,Earth,Electric,Viridis,Cividis. contours :class:`plotly.graph_objects.contourcarpet.Contours` instance or dict with compatible properties customdata Assigns extra data each datum. This may be useful when listening to hover, click and selection events. Note that, "scatter" traces also appends customdata items in the markers DOM elements customdatasrc Sets the source reference on Chart Studio Cloud for customdata . da Sets the x coordinate step. See `x0` for more info. db Sets the y coordinate step. See `y0` for more info. fillcolor Sets the fill color if `contours.type` is "constraint". Defaults to a half-transparent variant of the line color, marker color, or marker line color, whichever is available. hovertext Same as `text`. hovertextsrc Sets the source reference on Chart Studio Cloud for hovertext . ids Assigns id labels to each datum. These ids for object constancy of data points during animation. Should be an array of strings, not numbers or any other type. idssrc Sets the source reference on Chart Studio Cloud for ids . legendgroup Sets the legend group for this trace. Traces part of the same legend group hide/show at the same time when toggling legend items. line :class:`plotly.graph_objects.contourcarpet.Line` instance or dict with compatible properties meta Assigns extra meta information associated with this trace that can be used in various text attributes. Attributes such as trace `name`, graph, axis and colorbar `title.text`, annotation `text` `rangeselector`, `updatemenues` and `sliders` `label` text all support `meta`. To access the trace `meta` values in an attribute in the same trace, simply use `%{meta[i]}` where `i` is the index or key of the `meta` item in question. To access trace `meta` in layout attributes, use `%{data[n[.meta[i]}` where `i` is the index or key of the `meta` and `n` is the trace index. metasrc Sets the source reference on Chart Studio Cloud for meta . name Sets the trace name. The trace name appear as the legend item and on hover. ncontours Sets the maximum number of contour levels. The actual number of contours will be chosen automatically to be less than or equal to the value of `ncontours`. Has an effect only if `autocontour` is True or if `contours.size` is missing. opacity Sets the opacity of the trace. reversescale Reverses the color mapping if true. If true, `zmin` will correspond to the last color in the array and `zmax` will correspond to the first color. showlegend Determines whether or not an item corresponding to this trace is shown in the legend. showscale Determines whether or not a colorbar is displayed for this trace. stream :class:`plotly.graph_objects.contourcarpet.Stream` instance or dict with compatible properties text Sets the text elements associated with each z value. textsrc Sets the source reference on Chart Studio Cloud for text . transpose Transposes the z data. uid Assign an id to this trace, Use this to provide object constancy between traces during animations and transitions. uirevision Controls persistence of some user-driven changes to the trace: `constraintrange` in `parcoords` traces, as well as some `editable: true` modifications such as `name` and `colorbar.title`. Defaults to `layout.uirevision`. Note that other user-driven trace attribute changes are controlled by `layout` attributes: `trace.visible` is controlled by `layout.legend.uirevision`, `selectedpoints` is controlled by `layout.selectionrevision`, and `colorbar.(x|y)` (accessible with `config: {editable: true}`) is controlled by `layout.editrevision`. Trace changes are tracked by `uid`, which only falls back on trace index if no `uid` is provided. So if your app can add/remove traces before the end of the `data` array, such that the same trace has a different index, you can still preserve user-driven changes if you give each trace a `uid` that stays with it as it moves. visible Determines whether or not this trace is visible. If "legendonly", the trace is not drawn, but can appear as a legend item (provided that the legend itself is visible). xaxis Sets a reference between this trace's x coordinates and a 2D cartesian x axis. If "x" (the default value), the x coordinates refer to `layout.xaxis`. If "x2", the x coordinates refer to `layout.xaxis2`, and so on. yaxis Sets a reference between this trace's y coordinates and a 2D cartesian y axis. If "y" (the default value), the y coordinates refer to `layout.yaxis`. If "y2", the y coordinates refer to `layout.yaxis2`, and so on. z Sets the z data. zauto Determines whether or not the color domain is computed with respect to the input data (here in `z`) or the bounds set in `zmin` and `zmax` Defaults to `false` when `zmin` and `zmax` are set by the user. zmax Sets the upper bound of the color domain. Value should have the same units as in `z` and if set, `zmin` must be set as well. zmid Sets the mid-point of the color domain by scaling `zmin` and/or `zmax` to be equidistant to this point. Value should have the same units as in `z`. Has no effect when `zauto` is `false`. zmin Sets the lower bound of the color domain. Value should have the same units as in `z` and if set, `zmax` must be set as well. zsrc Sets the source reference on Chart Studio Cloud for z . row : int or None (default) Subplot row index (starting from 1) for the trace to be added. Only valid if figure was created using `plotly.tools.make_subplots` col : int or None (default) Subplot col index (starting from 1) for the trace to be added. Only valid if figure was created using `plotly.tools.make_subplots` secondary_y: boolean or None (default None) If True, associate this trace with the secondary y-axis of the subplot at the specified row and col. Only valid if all of the following conditions are satisfied: * The figure was created using `plotly.subplots.make_subplots`. * The row and col arguments are not None * The subplot at the specified row and col has type xy (which is the default) and secondary_y True. These properties are specified in the specs argument to make_subplots. See the make_subplots docstring for more info. Returns ------- FigureWidget """ from plotly.graph_objs import Contourcarpet new_trace = Contourcarpet( a=a, a0=a0, asrc=asrc, atype=atype, autocolorscale=autocolorscale, autocontour=autocontour, b=b, b0=b0, bsrc=bsrc, btype=btype, carpet=carpet, coloraxis=coloraxis, colorbar=colorbar, colorscale=colorscale, contours=contours, customdata=customdata, customdatasrc=customdatasrc, da=da, db=db, fillcolor=fillcolor, hovertext=hovertext, hovertextsrc=hovertextsrc, ids=ids, idssrc=idssrc, legendgroup=legendgroup, line=line, meta=meta, metasrc=metasrc, name=name, ncontours=ncontours, opacity=opacity, reversescale=reversescale, showlegend=showlegend, showscale=showscale, stream=stream, text=text, textsrc=textsrc, transpose=transpose, uid=uid, uirevision=uirevision, visible=visible, xaxis=xaxis, yaxis=yaxis, z=z, zauto=zauto, zmax=zmax, zmid=zmid, zmin=zmin, zsrc=zsrc, **kwargs ) return self.add_trace(new_trace, row=row, col=col, secondary_y=secondary_y) def add_densitymapbox( self, autocolorscale=None, below=None, coloraxis=None, colorbar=None, colorscale=None, customdata=None, customdatasrc=None, hoverinfo=None, hoverinfosrc=None, hoverlabel=None, hovertemplate=None, hovertemplatesrc=None, hovertext=None, hovertextsrc=None, ids=None, idssrc=None, lat=None, latsrc=None, legendgroup=None, lon=None, lonsrc=None, meta=None, metasrc=None, name=None, opacity=None, radius=None, radiussrc=None, reversescale=None, showlegend=None, showscale=None, stream=None, subplot=None, text=None, textsrc=None, uid=None, uirevision=None, visible=None, z=None, zauto=None, zmax=None, zmid=None, zmin=None, zsrc=None, row=None, col=None, **kwargs ): """ Add a new Densitymapbox trace Draws a bivariate kernel density estimation with a Gaussian kernel from `lon` and `lat` coordinates and optional `z` values using a colorscale. Parameters ---------- autocolorscale Determines whether the colorscale is a default palette (`autocolorscale: true`) or the palette determined by `colorscale`. In case `colorscale` is unspecified or `autocolorscale` is true, the default palette will be chosen according to whether numbers in the `color` array are all positive, all negative or mixed. below Determines if the densitymapbox trace will be inserted before the layer with the specified ID. By default, densitymapbox traces are placed below the first layer of type symbol If set to '', the layer will be inserted above every existing layer. coloraxis Sets a reference to a shared color axis. References to these shared color axes are "coloraxis", "coloraxis2", "coloraxis3", etc. Settings for these shared color axes are set in the layout, under `layout.coloraxis`, `layout.coloraxis2`, etc. Note that multiple color scales can be linked to the same color axis. colorbar :class:`plotly.graph_objects.densitymapbox.ColorBar` instance or dict with compatible properties colorscale Sets the colorscale. The colorscale must be an array containing arrays mapping a normalized value to an rgb, rgba, hex, hsl, hsv, or named color string. At minimum, a mapping for the lowest (0) and highest (1) values are required. For example, `[[0, 'rgb(0,0,255)'], [1, 'rgb(255,0,0)']]`. To control the bounds of the colorscale in color space, use`zmin` and `zmax`. Alternatively, `colorscale` may be a palette name string of the following list: Greys,YlGnBu,Greens,YlOrR d,Bluered,RdBu,Reds,Blues,Picnic,Rainbow,Portland,Jet,H ot,Blackbody,Earth,Electric,Viridis,Cividis. customdata Assigns extra data each datum. This may be useful when listening to hover, click and selection events. Note that, "scatter" traces also appends customdata items in the markers DOM elements customdatasrc Sets the source reference on Chart Studio Cloud for customdata . hoverinfo Determines which trace information appear on hover. If `none` or `skip` are set, no information is displayed upon hovering. But, if `none` is set, click and hover events are still fired. hoverinfosrc Sets the source reference on Chart Studio Cloud for hoverinfo . hoverlabel :class:`plotly.graph_objects.densitymapbox.Hoverlabel` instance or dict with compatible properties hovertemplate Template string used for rendering the information that appear on hover box. Note that this will override `hoverinfo`. Variables are inserted using %{variable}, for example "y: %{y}". Numbers are formatted using d3-format's syntax %{variable:d3-format}, for example "Price: %{y:$.2f}". https://github.com/d3/d3-3.x-api- reference/blob/master/Formatting.md#d3_format for details on the formatting syntax. Dates are formatted using d3-time-format's syntax %{variable|d3-time- format}, for example "Day: %{2019-01-01|%A}". https://github.com/d3/d3-time-format#locale_format for details on the date formatting syntax. The variables available in `hovertemplate` are the ones emitted as event data described at this link https://plotly.com/javascript/plotlyjs-events/#event- data. Additionally, every attributes that can be specified per-point (the ones that are `arrayOk: true`) are available. Anything contained in tag `<extra>` is displayed in the secondary box, for example "<extra>{fullData.name}</extra>". To hide the secondary box completely, use an empty tag `<extra></extra>`. hovertemplatesrc Sets the source reference on Chart Studio Cloud for hovertemplate . hovertext Sets hover text elements associated with each (lon,lat) pair If a single string, the same string appears over all the data points. If an array of string, the items are mapped in order to the this trace's (lon,lat) coordinates. To be seen, trace `hoverinfo` must contain a "text" flag. hovertextsrc Sets the source reference on Chart Studio Cloud for hovertext . ids Assigns id labels to each datum. These ids for object constancy of data points during animation. Should be an array of strings, not numbers or any other type. idssrc Sets the source reference on Chart Studio Cloud for ids . lat Sets the latitude coordinates (in degrees North). latsrc Sets the source reference on Chart Studio Cloud for lat . legendgroup Sets the legend group for this trace. Traces part of the same legend group hide/show at the same time when toggling legend items. lon Sets the longitude coordinates (in degrees East). lonsrc Sets the source reference on Chart Studio Cloud for lon . meta Assigns extra meta information associated with this trace that can be used in various text attributes. Attributes such as trace `name`, graph, axis and colorbar `title.text`, annotation `text` `rangeselector`, `updatemenues` and `sliders` `label` text all support `meta`. To access the trace `meta` values in an attribute in the same trace, simply use `%{meta[i]}` where `i` is the index or key of the `meta` item in question. To access trace `meta` in layout attributes, use `%{data[n[.meta[i]}` where `i` is the index or key of the `meta` and `n` is the trace index. metasrc Sets the source reference on Chart Studio Cloud for meta . name Sets the trace name. The trace name appear as the legend item and on hover. opacity Sets the opacity of the trace. radius Sets the radius of influence of one `lon` / `lat` point in pixels. Increasing the value makes the densitymapbox trace smoother, but less detailed. radiussrc Sets the source reference on Chart Studio Cloud for radius . reversescale Reverses the color mapping if true. If true, `zmin` will correspond to the last color in the array and `zmax` will correspond to the first color. showlegend Determines whether or not an item corresponding to this trace is shown in the legend. showscale Determines whether or not a colorbar is displayed for this trace. stream :class:`plotly.graph_objects.densitymapbox.Stream` instance or dict with compatible properties subplot Sets a reference between this trace's data coordinates and a mapbox subplot. If "mapbox" (the default value), the data refer to `layout.mapbox`. If "mapbox2", the data refer to `layout.mapbox2`, and so on. text Sets text elements associated with each (lon,lat) pair If a single string, the same string appears over all the data points. If an array of string, the items are mapped in order to the this trace's (lon,lat) coordinates. If trace `hoverinfo` contains a "text" flag and "hovertext" is not set, these elements will be seen in the hover labels. textsrc Sets the source reference on Chart Studio Cloud for text . uid Assign an id to this trace, Use this to provide object constancy between traces during animations and transitions. uirevision Controls persistence of some user-driven changes to the trace: `constraintrange` in `parcoords` traces, as well as some `editable: true` modifications such as `name` and `colorbar.title`. Defaults to `layout.uirevision`. Note that other user-driven trace attribute changes are controlled by `layout` attributes: `trace.visible` is controlled by `layout.legend.uirevision`, `selectedpoints` is controlled by `layout.selectionrevision`, and `colorbar.(x|y)` (accessible with `config: {editable: true}`) is controlled by `layout.editrevision`. Trace changes are tracked by `uid`, which only falls back on trace index if no `uid` is provided. So if your app can add/remove traces before the end of the `data` array, such that the same trace has a different index, you can still preserve user-driven changes if you give each trace a `uid` that stays with it as it moves. visible Determines whether or not this trace is visible. If "legendonly", the trace is not drawn, but can appear as a legend item (provided that the legend itself is visible). z Sets the points' weight. For example, a value of 10 would be equivalent to having 10 points of weight 1 in the same spot zauto Determines whether or not the color domain is computed with respect to the input data (here in `z`) or the bounds set in `zmin` and `zmax` Defaults to `false` when `zmin` and `zmax` are set by the user. zmax Sets the upper bound of the color domain. Value should have the same units as in `z` and if set, `zmin` must be set as well. zmid Sets the mid-point of the color domain by scaling `zmin` and/or `zmax` to be equidistant to this point. Value should have the same units as in `z`. Has no effect when `zauto` is `false`. zmin Sets the lower bound of the color domain. Value should have the same units as in `z` and if set, `zmax` must be set as well. zsrc Sets the source reference on Chart Studio Cloud for z . row : int or None (default) Subplot row index (starting from 1) for the trace to be added. Only valid if figure was created using `plotly.tools.make_subplots` col : int or None (default) Subplot col index (starting from 1) for the trace to be added. Only valid if figure was created using `plotly.tools.make_subplots` Returns ------- FigureWidget """ from plotly.graph_objs import Densitymapbox new_trace = Densitymapbox( autocolorscale=autocolorscale, below=below, coloraxis=coloraxis, colorbar=colorbar, colorscale=colorscale, customdata=customdata, customdatasrc=customdatasrc, hoverinfo=hoverinfo, hoverinfosrc=hoverinfosrc, hoverlabel=hoverlabel, hovertemplate=hovertemplate, hovertemplatesrc=hovertemplatesrc, hovertext=hovertext, hovertextsrc=hovertextsrc, ids=ids, idssrc=idssrc, lat=lat, latsrc=latsrc, legendgroup=legendgroup, lon=lon, lonsrc=lonsrc, meta=meta, metasrc=metasrc, name=name, opacity=opacity, radius=radius, radiussrc=radiussrc, reversescale=reversescale, showlegend=showlegend, showscale=showscale, stream=stream, subplot=subplot, text=text, textsrc=textsrc, uid=uid, uirevision=uirevision, visible=visible, z=z, zauto=zauto, zmax=zmax, zmid=zmid, zmin=zmin, zsrc=zsrc, **kwargs ) return self.add_trace(new_trace, row=row, col=col) def add_funnel( self, alignmentgroup=None, cliponaxis=None, connector=None, constraintext=None, customdata=None, customdatasrc=None, dx=None, dy=None, hoverinfo=None, hoverinfosrc=None, hoverlabel=None, hovertemplate=None, hovertemplatesrc=None, hovertext=None, hovertextsrc=None, ids=None, idssrc=None, insidetextanchor=None, insidetextfont=None, legendgroup=None, marker=None, meta=None, metasrc=None, name=None, offset=None, offsetgroup=None, opacity=None, orientation=None, outsidetextfont=None, selectedpoints=None, showlegend=None, stream=None, text=None, textangle=None, textfont=None, textinfo=None, textposition=None, textpositionsrc=None, textsrc=None, texttemplate=None, texttemplatesrc=None, uid=None, uirevision=None, visible=None, width=None, x=None, x0=None, xaxis=None, xperiod=None, xperiod0=None, xperiodalignment=None, xsrc=None, y=None, y0=None, yaxis=None, yperiod=None, yperiod0=None, yperiodalignment=None, ysrc=None, row=None, col=None, secondary_y=None, **kwargs ): """ Add a new Funnel trace Visualize stages in a process using length-encoded bars. This trace can be used to show data in either a part-to-whole representation wherein each item appears in a single stage, or in a "drop-off" representation wherein each item appears in each stage it traversed. See also the "funnelarea" trace type for a different approach to visualizing funnel data. Parameters ---------- alignmentgroup Set several traces linked to the same position axis or matching axes to the same alignmentgroup. This controls whether bars compute their positional range dependently or independently. cliponaxis Determines whether the text nodes are clipped about the subplot axes. To show the text nodes above axis lines and tick labels, make sure to set `xaxis.layer` and `yaxis.layer` to *below traces*. connector :class:`plotly.graph_objects.funnel.Connector` instance or dict with compatible properties constraintext Constrain the size of text inside or outside a bar to be no larger than the bar itself. customdata Assigns extra data each datum. This may be useful when listening to hover, click and selection events. Note that, "scatter" traces also appends customdata items in the markers DOM elements customdatasrc Sets the source reference on Chart Studio Cloud for customdata . dx Sets the x coordinate step. See `x0` for more info. dy Sets the y coordinate step. See `y0` for more info. hoverinfo Determines which trace information appear on hover. If `none` or `skip` are set, no information is displayed upon hovering. But, if `none` is set, click and hover events are still fired. hoverinfosrc Sets the source reference on Chart Studio Cloud for hoverinfo . hoverlabel :class:`plotly.graph_objects.funnel.Hoverlabel` instance or dict with compatible properties hovertemplate Template string used for rendering the information that appear on hover box. Note that this will override `hoverinfo`. Variables are inserted using %{variable}, for example "y: %{y}". Numbers are formatted using d3-format's syntax %{variable:d3-format}, for example "Price: %{y:$.2f}". https://github.com/d3/d3-3.x-api- reference/blob/master/Formatting.md#d3_format for details on the formatting syntax. Dates are formatted using d3-time-format's syntax %{variable|d3-time- format}, for example "Day: %{2019-01-01|%A}". https://github.com/d3/d3-time-format#locale_format for details on the date formatting syntax. The variables available in `hovertemplate` are the ones emitted as event data described at this link https://plotly.com/javascript/plotlyjs-events/#event- data. Additionally, every attributes that can be specified per-point (the ones that are `arrayOk: true`) are available. variables `percentInitial`, `percentPrevious` and `percentTotal`. Anything contained in tag `<extra>` is displayed in the secondary box, for example "<extra>{fullData.name}</extra>". To hide the secondary box completely, use an empty tag `<extra></extra>`. hovertemplatesrc Sets the source reference on Chart Studio Cloud for hovertemplate . hovertext Sets hover text elements associated with each (x,y) pair. If a single string, the same string appears over all the data points. If an array of string, the items are mapped in order to the this trace's (x,y) coordinates. To be seen, trace `hoverinfo` must contain a "text" flag. hovertextsrc Sets the source reference on Chart Studio Cloud for hovertext . ids Assigns id labels to each datum. These ids for object constancy of data points during animation. Should be an array of strings, not numbers or any other type. idssrc Sets the source reference on Chart Studio Cloud for ids . insidetextanchor Determines if texts are kept at center or start/end points in `textposition` "inside" mode. insidetextfont Sets the font used for `text` lying inside the bar. legendgroup Sets the legend group for this trace. Traces part of the same legend group hide/show at the same time when toggling legend items. marker :class:`plotly.graph_objects.funnel.Marker` instance or dict with compatible properties meta Assigns extra meta information associated with this trace that can be used in various text attributes. Attributes such as trace `name`, graph, axis and colorbar `title.text`, annotation `text` `rangeselector`, `updatemenues` and `sliders` `label` text all support `meta`. To access the trace `meta` values in an attribute in the same trace, simply use `%{meta[i]}` where `i` is the index or key of the `meta` item in question. To access trace `meta` in layout attributes, use `%{data[n[.meta[i]}` where `i` is the index or key of the `meta` and `n` is the trace index. metasrc Sets the source reference on Chart Studio Cloud for meta . name Sets the trace name. The trace name appear as the legend item and on hover. offset Shifts the position where the bar is drawn (in position axis units). In "group" barmode, traces that set "offset" will be excluded and drawn in "overlay" mode instead. offsetgroup Set several traces linked to the same position axis or matching axes to the same offsetgroup where bars of the same position coordinate will line up. opacity Sets the opacity of the trace. orientation Sets the orientation of the funnels. With "v" ("h"), the value of the each bar spans along the vertical (horizontal). By default funnels are tend to be oriented horizontally; unless only "y" array is presented or orientation is set to "v". Also regarding graphs including only 'horizontal' funnels, "autorange" on the "y-axis" are set to "reversed". outsidetextfont Sets the font used for `text` lying outside the bar. selectedpoints Array containing integer indices of selected points. Has an effect only for traces that support selections. Note that an empty array means an empty selection where the `unselected` are turned on for all points, whereas, any other non-array values means no selection all where the `selected` and `unselected` styles have no effect. showlegend Determines whether or not an item corresponding to this trace is shown in the legend. stream :class:`plotly.graph_objects.funnel.Stream` instance or dict with compatible properties text Sets text elements associated with each (x,y) pair. If a single string, the same string appears over all the data points. If an array of string, the items are mapped in order to the this trace's (x,y) coordinates. If trace `hoverinfo` contains a "text" flag and "hovertext" is not set, these elements will be seen in the hover labels. textangle Sets the angle of the tick labels with respect to the bar. For example, a `tickangle` of -90 draws the tick labels vertically. With "auto" the texts may automatically be rotated to fit with the maximum size in bars. textfont Sets the font used for `text`. textinfo Determines which trace information appear on the graph. In the case of having multiple funnels, percentages & totals are computed separately (per trace). textposition Specifies the location of the `text`. "inside" positions `text` inside, next to the bar end (rotated and scaled if needed). "outside" positions `text` outside, next to the bar end (scaled if needed), unless there is another bar stacked on this one, then the text gets pushed inside. "auto" tries to position `text` inside the bar, but if the bar is too small and no bar is stacked on this one the text is moved outside. textpositionsrc Sets the source reference on Chart Studio Cloud for textposition . textsrc Sets the source reference on Chart Studio Cloud for text . texttemplate Template string used for rendering the information text that appear on points. Note that this will override `textinfo`. Variables are inserted using %{variable}, for example "y: %{y}". Numbers are formatted using d3-format's syntax %{variable:d3-format}, for example "Price: %{y:$.2f}". https://github.com/d3/d3-3.x-api- reference/blob/master/Formatting.md#d3_format for details on the formatting syntax. Dates are formatted using d3-time-format's syntax %{variable|d3-time- format}, for example "Day: %{2019-01-01|%A}". https://github.com/d3/d3-time-format#locale_format for details on the date formatting syntax. Every attributes that can be specified per-point (the ones that are `arrayOk: true`) are available. variables `percentInitial`, `percentPrevious`, `percentTotal`, `label` and `value`. texttemplatesrc Sets the source reference on Chart Studio Cloud for texttemplate . uid Assign an id to this trace, Use this to provide object constancy between traces during animations and transitions. uirevision Controls persistence of some user-driven changes to the trace: `constraintrange` in `parcoords` traces, as well as some `editable: true` modifications such as `name` and `colorbar.title`. Defaults to `layout.uirevision`. Note that other user-driven trace attribute changes are controlled by `layout` attributes: `trace.visible` is controlled by `layout.legend.uirevision`, `selectedpoints` is controlled by `layout.selectionrevision`, and `colorbar.(x|y)` (accessible with `config: {editable: true}`) is controlled by `layout.editrevision`. Trace changes are tracked by `uid`, which only falls back on trace index if no `uid` is provided. So if your app can add/remove traces before the end of the `data` array, such that the same trace has a different index, you can still preserve user-driven changes if you give each trace a `uid` that stays with it as it moves. visible Determines whether or not this trace is visible. If "legendonly", the trace is not drawn, but can appear as a legend item (provided that the legend itself is visible). width Sets the bar width (in position axis units). x Sets the x coordinates. x0 Alternate to `x`. Builds a linear space of x coordinates. Use with `dx` where `x0` is the starting coordinate and `dx` the step. xaxis Sets a reference between this trace's x coordinates and a 2D cartesian x axis. If "x" (the default value), the x coordinates refer to `layout.xaxis`. If "x2", the x coordinates refer to `layout.xaxis2`, and so on. xperiod Only relevant when the axis `type` is "date". Sets the period positioning in milliseconds or "M<n>" on the x axis. Special values in the form of "M<n>" could be used to declare the number of months. In this case `n` must be a positive integer. xperiod0 Only relevant when the axis `type` is "date". Sets the base for period positioning in milliseconds or date string on the x0 axis. When `x0period` is round number of weeks, the `x0period0` by default would be on a Sunday i.e. 2000-01-02, otherwise it would be at 2000-01-01. xperiodalignment Only relevant when the axis `type` is "date". Sets the alignment of data points on the x axis. xsrc Sets the source reference on Chart Studio Cloud for x . y Sets the y coordinates. y0 Alternate to `y`. Builds a linear space of y coordinates. Use with `dy` where `y0` is the starting coordinate and `dy` the step. yaxis Sets a reference between this trace's y coordinates and a 2D cartesian y axis. If "y" (the default value), the y coordinates refer to `layout.yaxis`. If "y2", the y coordinates refer to `layout.yaxis2`, and so on. yperiod Only relevant when the axis `type` is "date". Sets the period positioning in milliseconds or "M<n>" on the y axis. Special values in the form of "M<n>" could be used to declare the number of months. In this case `n` must be a positive integer. yperiod0 Only relevant when the axis `type` is "date". Sets the base for period positioning in milliseconds or date string on the y0 axis. When `y0period` is round number of weeks, the `y0period0` by default would be on a Sunday i.e. 2000-01-02, otherwise it would be at 2000-01-01. yperiodalignment Only relevant when the axis `type` is "date". Sets the alignment of data points on the y axis. ysrc Sets the source reference on Chart Studio Cloud for y . row : int or None (default) Subplot row index (starting from 1) for the trace to be added. Only valid if figure was created using `plotly.tools.make_subplots` col : int or None (default) Subplot col index (starting from 1) for the trace to be added. Only valid if figure was created using `plotly.tools.make_subplots` secondary_y: boolean or None (default None) If True, associate this trace with the secondary y-axis of the subplot at the specified row and col. Only valid if all of the following conditions are satisfied: * The figure was created using `plotly.subplots.make_subplots`. * The row and col arguments are not None * The subplot at the specified row and col has type xy (which is the default) and secondary_y True. These properties are specified in the specs argument to make_subplots. See the make_subplots docstring for more info. Returns ------- FigureWidget """ from plotly.graph_objs import Funnel new_trace = Funnel( alignmentgroup=alignmentgroup, cliponaxis=cliponaxis, connector=connector, constraintext=constraintext, customdata=customdata, customdatasrc=customdatasrc, dx=dx, dy=dy, hoverinfo=hoverinfo, hoverinfosrc=hoverinfosrc, hoverlabel=hoverlabel, hovertemplate=hovertemplate, hovertemplatesrc=hovertemplatesrc, hovertext=hovertext, hovertextsrc=hovertextsrc, ids=ids, idssrc=idssrc, insidetextanchor=insidetextanchor, insidetextfont=insidetextfont, legendgroup=legendgroup, marker=marker, meta=meta, metasrc=metasrc, name=name, offset=offset, offsetgroup=offsetgroup, opacity=opacity, orientation=orientation, outsidetextfont=outsidetextfont, selectedpoints=selectedpoints, showlegend=showlegend, stream=stream, text=text, textangle=textangle, textfont=textfont, textinfo=textinfo, textposition=textposition, textpositionsrc=textpositionsrc, textsrc=textsrc, texttemplate=texttemplate, texttemplatesrc=texttemplatesrc, uid=uid, uirevision=uirevision, visible=visible, width=width, x=x, x0=x0, xaxis=xaxis, xperiod=xperiod, xperiod0=xperiod0, xperiodalignment=xperiodalignment, xsrc=xsrc, y=y, y0=y0, yaxis=yaxis, yperiod=yperiod, yperiod0=yperiod0, yperiodalignment=yperiodalignment, ysrc=ysrc, **kwargs ) return self.add_trace(new_trace, row=row, col=col, secondary_y=secondary_y) def add_funnelarea( self, aspectratio=None, baseratio=None, customdata=None, customdatasrc=None, dlabel=None, domain=None, hoverinfo=None, hoverinfosrc=None, hoverlabel=None, hovertemplate=None, hovertemplatesrc=None, hovertext=None, hovertextsrc=None, ids=None, idssrc=None, insidetextfont=None, label0=None, labels=None, labelssrc=None, legendgroup=None, marker=None, meta=None, metasrc=None, name=None, opacity=None, scalegroup=None, showlegend=None, stream=None, text=None, textfont=None, textinfo=None, textposition=None, textpositionsrc=None, textsrc=None, texttemplate=None, texttemplatesrc=None, title=None, uid=None, uirevision=None, values=None, valuessrc=None, visible=None, row=None, col=None, **kwargs ): """ Add a new Funnelarea trace Visualize stages in a process using area-encoded trapezoids. This trace can be used to show data in a part-to-whole representation similar to a "pie" trace, wherein each item appears in a single stage. See also the "funnel" trace type for a different approach to visualizing funnel data. Parameters ---------- aspectratio Sets the ratio between height and width baseratio Sets the ratio between bottom length and maximum top length. customdata Assigns extra data each datum. This may be useful when listening to hover, click and selection events. Note that, "scatter" traces also appends customdata items in the markers DOM elements customdatasrc Sets the source reference on Chart Studio Cloud for customdata . dlabel Sets the label step. See `label0` for more info. domain :class:`plotly.graph_objects.funnelarea.Domain` instance or dict with compatible properties hoverinfo Determines which trace information appear on hover. If `none` or `skip` are set, no information is displayed upon hovering. But, if `none` is set, click and hover events are still fired. hoverinfosrc Sets the source reference on Chart Studio Cloud for hoverinfo . hoverlabel :class:`plotly.graph_objects.funnelarea.Hoverlabel` instance or dict with compatible properties hovertemplate Template string used for rendering the information that appear on hover box. Note that this will override `hoverinfo`. Variables are inserted using %{variable}, for example "y: %{y}". Numbers are formatted using d3-format's syntax %{variable:d3-format}, for example "Price: %{y:$.2f}". https://github.com/d3/d3-3.x-api- reference/blob/master/Formatting.md#d3_format for details on the formatting syntax. Dates are formatted using d3-time-format's syntax %{variable|d3-time- format}, for example "Day: %{2019-01-01|%A}". https://github.com/d3/d3-time-format#locale_format for details on the date formatting syntax. The variables available in `hovertemplate` are the ones emitted as event data described at this link https://plotly.com/javascript/plotlyjs-events/#event- data. Additionally, every attributes that can be specified per-point (the ones that are `arrayOk: true`) are available. variables `label`, `color`, `value`, `text` and `percent`. Anything contained in tag `<extra>` is displayed in the secondary box, for example "<extra>{fullData.name}</extra>". To hide the secondary box completely, use an empty tag `<extra></extra>`. hovertemplatesrc Sets the source reference on Chart Studio Cloud for hovertemplate . hovertext Sets hover text elements associated with each sector. If a single string, the same string appears for all data points. If an array of string, the items are mapped in order of this trace's sectors. To be seen, trace `hoverinfo` must contain a "text" flag. hovertextsrc Sets the source reference on Chart Studio Cloud for hovertext . ids Assigns id labels to each datum. These ids for object constancy of data points during animation. Should be an array of strings, not numbers or any other type. idssrc Sets the source reference on Chart Studio Cloud for ids . insidetextfont Sets the font used for `textinfo` lying inside the sector. label0 Alternate to `labels`. Builds a numeric set of labels. Use with `dlabel` where `label0` is the starting label and `dlabel` the step. labels Sets the sector labels. If `labels` entries are duplicated, we sum associated `values` or simply count occurrences if `values` is not provided. For other array attributes (including color) we use the first non-empty entry among all occurrences of the label. labelssrc Sets the source reference on Chart Studio Cloud for labels . legendgroup Sets the legend group for this trace. Traces part of the same legend group hide/show at the same time when toggling legend items. marker :class:`plotly.graph_objects.funnelarea.Marker` instance or dict with compatible properties meta Assigns extra meta information associated with this trace that can be used in various text attributes. Attributes such as trace `name`, graph, axis and colorbar `title.text`, annotation `text` `rangeselector`, `updatemenues` and `sliders` `label` text all support `meta`. To access the trace `meta` values in an attribute in the same trace, simply use `%{meta[i]}` where `i` is the index or key of the `meta` item in question. To access trace `meta` in layout attributes, use `%{data[n[.meta[i]}` where `i` is the index or key of the `meta` and `n` is the trace index. metasrc Sets the source reference on Chart Studio Cloud for meta . name Sets the trace name. The trace name appear as the legend item and on hover. opacity Sets the opacity of the trace. scalegroup If there are multiple funnelareas that should be sized according to their totals, link them by providing a non-empty group id here shared by every trace in the same group. showlegend Determines whether or not an item corresponding to this trace is shown in the legend. stream :class:`plotly.graph_objects.funnelarea.Stream` instance or dict with compatible properties text Sets text elements associated with each sector. If trace `textinfo` contains a "text" flag, these elements will be seen on the chart. If trace `hoverinfo` contains a "text" flag and "hovertext" is not set, these elements will be seen in the hover labels. textfont Sets the font used for `textinfo`. textinfo Determines which trace information appear on the graph. textposition Specifies the location of the `textinfo`. textpositionsrc Sets the source reference on Chart Studio Cloud for textposition . textsrc Sets the source reference on Chart Studio Cloud for text . texttemplate Template string used for rendering the information text that appear on points. Note that this will override `textinfo`. Variables are inserted using %{variable}, for example "y: %{y}". Numbers are formatted using d3-format's syntax %{variable:d3-format}, for example "Price: %{y:$.2f}". https://github.com/d3/d3-3.x-api- reference/blob/master/Formatting.md#d3_format for details on the formatting syntax. Dates are formatted using d3-time-format's syntax %{variable|d3-time- format}, for example "Day: %{2019-01-01|%A}". https://github.com/d3/d3-time-format#locale_format for details on the date formatting syntax. Every attributes that can be specified per-point (the ones that are `arrayOk: true`) are available. variables `label`, `color`, `value`, `text` and `percent`. texttemplatesrc Sets the source reference on Chart Studio Cloud for texttemplate . title :class:`plotly.graph_objects.funnelarea.Title` instance or dict with compatible properties uid Assign an id to this trace, Use this to provide object constancy between traces during animations and transitions. uirevision Controls persistence of some user-driven changes to the trace: `constraintrange` in `parcoords` traces, as well as some `editable: true` modifications such as `name` and `colorbar.title`. Defaults to `layout.uirevision`. Note that other user-driven trace attribute changes are controlled by `layout` attributes: `trace.visible` is controlled by `layout.legend.uirevision`, `selectedpoints` is controlled by `layout.selectionrevision`, and `colorbar.(x|y)` (accessible with `config: {editable: true}`) is controlled by `layout.editrevision`. Trace changes are tracked by `uid`, which only falls back on trace index if no `uid` is provided. So if your app can add/remove traces before the end of the `data` array, such that the same trace has a different index, you can still preserve user-driven changes if you give each trace a `uid` that stays with it as it moves. values Sets the values of the sectors. If omitted, we count occurrences of each label. valuessrc Sets the source reference on Chart Studio Cloud for values . visible Determines whether or not this trace is visible. If "legendonly", the trace is not drawn, but can appear as a legend item (provided that the legend itself is visible). row : int or None (default) Subplot row index (starting from 1) for the trace to be added. Only valid if figure was created using `plotly.tools.make_subplots` col : int or None (default) Subplot col index (starting from 1) for the trace to be added. Only valid if figure was created using `plotly.tools.make_subplots` Returns ------- FigureWidget """ from plotly.graph_objs import Funnelarea new_trace = Funnelarea( aspectratio=aspectratio, baseratio=baseratio, customdata=customdata, customdatasrc=customdatasrc, dlabel=dlabel, domain=domain, hoverinfo=hoverinfo, hoverinfosrc=hoverinfosrc, hoverlabel=hoverlabel, hovertemplate=hovertemplate, hovertemplatesrc=hovertemplatesrc, hovertext=hovertext, hovertextsrc=hovertextsrc, ids=ids, idssrc=idssrc, insidetextfont=insidetextfont, label0=label0, labels=labels, labelssrc=labelssrc, legendgroup=legendgroup, marker=marker, meta=meta, metasrc=metasrc, name=name, opacity=opacity, scalegroup=scalegroup, showlegend=showlegend, stream=stream, text=text, textfont=textfont, textinfo=textinfo, textposition=textposition, textpositionsrc=textpositionsrc, textsrc=textsrc, texttemplate=texttemplate, texttemplatesrc=texttemplatesrc, title=title, uid=uid, uirevision=uirevision, values=values, valuessrc=valuessrc, visible=visible, **kwargs ) return self.add_trace(new_trace, row=row, col=col) def add_heatmap( self, autocolorscale=None, coloraxis=None, colorbar=None, colorscale=None, connectgaps=None, customdata=None, customdatasrc=None, dx=None, dy=None, hoverinfo=None, hoverinfosrc=None, hoverlabel=None, hoverongaps=None, hovertemplate=None, hovertemplatesrc=None, hovertext=None, hovertextsrc=None, ids=None, idssrc=None, legendgroup=None, meta=None, metasrc=None, name=None, opacity=None, reversescale=None, showlegend=None, showscale=None, stream=None, text=None, textsrc=None, transpose=None, uid=None, uirevision=None, visible=None, x=None, x0=None, xaxis=None, xcalendar=None, xgap=None, xperiod=None, xperiod0=None, xperiodalignment=None, xsrc=None, xtype=None, y=None, y0=None, yaxis=None, ycalendar=None, ygap=None, yperiod=None, yperiod0=None, yperiodalignment=None, ysrc=None, ytype=None, z=None, zauto=None, zhoverformat=None, zmax=None, zmid=None, zmin=None, zsmooth=None, zsrc=None, row=None, col=None, secondary_y=None, **kwargs ): """ Add a new Heatmap trace The data that describes the heatmap value-to-color mapping is set in `z`. Data in `z` can either be a 2D list of values (ragged or not) or a 1D array of values. In the case where `z` is a 2D list, say that `z` has N rows and M columns. Then, by default, the resulting heatmap will have N partitions along the y axis and M partitions along the x axis. In other words, the i-th row/ j-th column cell in `z` is mapped to the i-th partition of the y axis (starting from the bottom of the plot) and the j-th partition of the x-axis (starting from the left of the plot). This behavior can be flipped by using `transpose`. Moreover, `x` (`y`) can be provided with M or M+1 (N or N+1) elements. If M (N), then the coordinates correspond to the center of the heatmap cells and the cells have equal width. If M+1 (N+1), then the coordinates correspond to the edges of the heatmap cells. In the case where `z` is a 1D list, the x and y coordinates must be provided in `x` and `y` respectively to form data triplets. Parameters ---------- autocolorscale Determines whether the colorscale is a default palette (`autocolorscale: true`) or the palette determined by `colorscale`. In case `colorscale` is unspecified or `autocolorscale` is true, the default palette will be chosen according to whether numbers in the `color` array are all positive, all negative or mixed. coloraxis Sets a reference to a shared color axis. References to these shared color axes are "coloraxis", "coloraxis2", "coloraxis3", etc. Settings for these shared color axes are set in the layout, under `layout.coloraxis`, `layout.coloraxis2`, etc. Note that multiple color scales can be linked to the same color axis. colorbar :class:`plotly.graph_objects.heatmap.ColorBar` instance or dict with compatible properties colorscale Sets the colorscale. The colorscale must be an array containing arrays mapping a normalized value to an rgb, rgba, hex, hsl, hsv, or named color string. At minimum, a mapping for the lowest (0) and highest (1) values are required. For example, `[[0, 'rgb(0,0,255)'], [1, 'rgb(255,0,0)']]`. To control the bounds of the colorscale in color space, use`zmin` and `zmax`. Alternatively, `colorscale` may be a palette name string of the following list: Greys,YlGnBu,Greens,YlOrR d,Bluered,RdBu,Reds,Blues,Picnic,Rainbow,Portland,Jet,H ot,Blackbody,Earth,Electric,Viridis,Cividis. connectgaps Determines whether or not gaps (i.e. {nan} or missing values) in the `z` data are filled in. It is defaulted to true if `z` is a one dimensional array and `zsmooth` is not false; otherwise it is defaulted to false. customdata Assigns extra data each datum. This may be useful when listening to hover, click and selection events. Note that, "scatter" traces also appends customdata items in the markers DOM elements customdatasrc Sets the source reference on Chart Studio Cloud for customdata . dx Sets the x coordinate step. See `x0` for more info. dy Sets the y coordinate step. See `y0` for more info. hoverinfo Determines which trace information appear on hover. If `none` or `skip` are set, no information is displayed upon hovering. But, if `none` is set, click and hover events are still fired. hoverinfosrc Sets the source reference on Chart Studio Cloud for hoverinfo . hoverlabel :class:`plotly.graph_objects.heatmap.Hoverlabel` instance or dict with compatible properties hoverongaps Determines whether or not gaps (i.e. {nan} or missing values) in the `z` data have hover labels associated with them. hovertemplate Template string used for rendering the information that appear on hover box. Note that this will override `hoverinfo`. Variables are inserted using %{variable}, for example "y: %{y}". Numbers are formatted using d3-format's syntax %{variable:d3-format}, for example "Price: %{y:$.2f}". https://github.com/d3/d3-3.x-api- reference/blob/master/Formatting.md#d3_format for details on the formatting syntax. Dates are formatted using d3-time-format's syntax %{variable|d3-time- format}, for example "Day: %{2019-01-01|%A}". https://github.com/d3/d3-time-format#locale_format for details on the date formatting syntax. The variables available in `hovertemplate` are the ones emitted as event data described at this link https://plotly.com/javascript/plotlyjs-events/#event- data. Additionally, every attributes that can be specified per-point (the ones that are `arrayOk: true`) are available. Anything contained in tag `<extra>` is displayed in the secondary box, for example "<extra>{fullData.name}</extra>". To hide the secondary box completely, use an empty tag `<extra></extra>`. hovertemplatesrc Sets the source reference on Chart Studio Cloud for hovertemplate . hovertext Same as `text`. hovertextsrc Sets the source reference on Chart Studio Cloud for hovertext . ids Assigns id labels to each datum. These ids for object constancy of data points during animation. Should be an array of strings, not numbers or any other type. idssrc Sets the source reference on Chart Studio Cloud for ids . legendgroup Sets the legend group for this trace. Traces part of the same legend group hide/show at the same time when toggling legend items. meta Assigns extra meta information associated with this trace that can be used in various text attributes. Attributes such as trace `name`, graph, axis and colorbar `title.text`, annotation `text` `rangeselector`, `updatemenues` and `sliders` `label` text all support `meta`. To access the trace `meta` values in an attribute in the same trace, simply use `%{meta[i]}` where `i` is the index or key of the `meta` item in question. To access trace `meta` in layout attributes, use `%{data[n[.meta[i]}` where `i` is the index or key of the `meta` and `n` is the trace index. metasrc Sets the source reference on Chart Studio Cloud for meta . name Sets the trace name. The trace name appear as the legend item and on hover. opacity Sets the opacity of the trace. reversescale Reverses the color mapping if true. If true, `zmin` will correspond to the last color in the array and `zmax` will correspond to the first color. showlegend Determines whether or not an item corresponding to this trace is shown in the legend. showscale Determines whether or not a colorbar is displayed for this trace. stream :class:`plotly.graph_objects.heatmap.Stream` instance or dict with compatible properties text Sets the text elements associated with each z value. textsrc Sets the source reference on Chart Studio Cloud for text . transpose Transposes the z data. uid Assign an id to this trace, Use this to provide object constancy between traces during animations and transitions. uirevision Controls persistence of some user-driven changes to the trace: `constraintrange` in `parcoords` traces, as well as some `editable: true` modifications such as `name` and `colorbar.title`. Defaults to `layout.uirevision`. Note that other user-driven trace attribute changes are controlled by `layout` attributes: `trace.visible` is controlled by `layout.legend.uirevision`, `selectedpoints` is controlled by `layout.selectionrevision`, and `colorbar.(x|y)` (accessible with `config: {editable: true}`) is controlled by `layout.editrevision`. Trace changes are tracked by `uid`, which only falls back on trace index if no `uid` is provided. So if your app can add/remove traces before the end of the `data` array, such that the same trace has a different index, you can still preserve user-driven changes if you give each trace a `uid` that stays with it as it moves. visible Determines whether or not this trace is visible. If "legendonly", the trace is not drawn, but can appear as a legend item (provided that the legend itself is visible). x Sets the x coordinates. x0 Alternate to `x`. Builds a linear space of x coordinates. Use with `dx` where `x0` is the starting coordinate and `dx` the step. xaxis Sets a reference between this trace's x coordinates and a 2D cartesian x axis. If "x" (the default value), the x coordinates refer to `layout.xaxis`. If "x2", the x coordinates refer to `layout.xaxis2`, and so on. xcalendar Sets the calendar system to use with `x` date data. xgap Sets the horizontal gap (in pixels) between bricks. xperiod Only relevant when the axis `type` is "date". Sets the period positioning in milliseconds or "M<n>" on the x axis. Special values in the form of "M<n>" could be used to declare the number of months. In this case `n` must be a positive integer. xperiod0 Only relevant when the axis `type` is "date". Sets the base for period positioning in milliseconds or date string on the x0 axis. When `x0period` is round number of weeks, the `x0period0` by default would be on a Sunday i.e. 2000-01-02, otherwise it would be at 2000-01-01. xperiodalignment Only relevant when the axis `type` is "date". Sets the alignment of data points on the x axis. xsrc Sets the source reference on Chart Studio Cloud for x . xtype If "array", the heatmap's x coordinates are given by "x" (the default behavior when `x` is provided). If "scaled", the heatmap's x coordinates are given by "x0" and "dx" (the default behavior when `x` is not provided). y Sets the y coordinates. y0 Alternate to `y`. Builds a linear space of y coordinates. Use with `dy` where `y0` is the starting coordinate and `dy` the step. yaxis Sets a reference between this trace's y coordinates and a 2D cartesian y axis. If "y" (the default value), the y coordinates refer to `layout.yaxis`. If "y2", the y coordinates refer to `layout.yaxis2`, and so on. ycalendar Sets the calendar system to use with `y` date data. ygap Sets the vertical gap (in pixels) between bricks. yperiod Only relevant when the axis `type` is "date". Sets the period positioning in milliseconds or "M<n>" on the y axis. Special values in the form of "M<n>" could be used to declare the number of months. In this case `n` must be a positive integer. yperiod0 Only relevant when the axis `type` is "date". Sets the base for period positioning in milliseconds or date string on the y0 axis. When `y0period` is round number of weeks, the `y0period0` by default would be on a Sunday i.e. 2000-01-02, otherwise it would be at 2000-01-01. yperiodalignment Only relevant when the axis `type` is "date". Sets the alignment of data points on the y axis. ysrc Sets the source reference on Chart Studio Cloud for y . ytype If "array", the heatmap's y coordinates are given by "y" (the default behavior when `y` is provided) If "scaled", the heatmap's y coordinates are given by "y0" and "dy" (the default behavior when `y` is not provided) z Sets the z data. zauto Determines whether or not the color domain is computed with respect to the input data (here in `z`) or the bounds set in `zmin` and `zmax` Defaults to `false` when `zmin` and `zmax` are set by the user. zhoverformat Sets the hover text formatting rule using d3 formatting mini-languages which are very similar to those in Python. See: https://github.com/d3/d3-3.x-api- reference/blob/master/Formatting.md#d3_format zmax Sets the upper bound of the color domain. Value should have the same units as in `z` and if set, `zmin` must be set as well. zmid Sets the mid-point of the color domain by scaling `zmin` and/or `zmax` to be equidistant to this point. Value should have the same units as in `z`. Has no effect when `zauto` is `false`. zmin Sets the lower bound of the color domain. Value should have the same units as in `z` and if set, `zmax` must be set as well. zsmooth Picks a smoothing algorithm use to smooth `z` data. zsrc Sets the source reference on Chart Studio Cloud for z . row : int or None (default) Subplot row index (starting from 1) for the trace to be added. Only valid if figure was created using `plotly.tools.make_subplots` col : int or None (default) Subplot col index (starting from 1) for the trace to be added. Only valid if figure was created using `plotly.tools.make_subplots` secondary_y: boolean or None (default None) If True, associate this trace with the secondary y-axis of the subplot at the specified row and col. Only valid if all of the following conditions are satisfied: * The figure was created using `plotly.subplots.make_subplots`. * The row and col arguments are not None * The subplot at the specified row and col has type xy (which is the default) and secondary_y True. These properties are specified in the specs argument to make_subplots. See the make_subplots docstring for more info. Returns ------- FigureWidget """ from plotly.graph_objs import Heatmap new_trace = Heatmap( autocolorscale=autocolorscale, coloraxis=coloraxis, colorbar=colorbar, colorscale=colorscale, connectgaps=connectgaps, customdata=customdata, customdatasrc=customdatasrc, dx=dx, dy=dy, hoverinfo=hoverinfo, hoverinfosrc=hoverinfosrc, hoverlabel=hoverlabel, hoverongaps=hoverongaps, hovertemplate=hovertemplate, hovertemplatesrc=hovertemplatesrc, hovertext=hovertext, hovertextsrc=hovertextsrc, ids=ids, idssrc=idssrc, legendgroup=legendgroup, meta=meta, metasrc=metasrc, name=name, opacity=opacity, reversescale=reversescale, showlegend=showlegend, showscale=showscale, stream=stream, text=text, textsrc=textsrc, transpose=transpose, uid=uid, uirevision=uirevision, visible=visible, x=x, x0=x0, xaxis=xaxis, xcalendar=xcalendar, xgap=xgap, xperiod=xperiod, xperiod0=xperiod0, xperiodalignment=xperiodalignment, xsrc=xsrc, xtype=xtype, y=y, y0=y0, yaxis=yaxis, ycalendar=ycalendar, ygap=ygap, yperiod=yperiod, yperiod0=yperiod0, yperiodalignment=yperiodalignment, ysrc=ysrc, ytype=ytype, z=z, zauto=zauto, zhoverformat=zhoverformat, zmax=zmax, zmid=zmid, zmin=zmin, zsmooth=zsmooth, zsrc=zsrc, **kwargs ) return self.add_trace(new_trace, row=row, col=col, secondary_y=secondary_y) def add_heatmapgl( self, autocolorscale=None, coloraxis=None, colorbar=None, colorscale=None, customdata=None, customdatasrc=None, dx=None, dy=None, hoverinfo=None, hoverinfosrc=None, hoverlabel=None, ids=None, idssrc=None, meta=None, metasrc=None, name=None, opacity=None, reversescale=None, showscale=None, stream=None, text=None, textsrc=None, transpose=None, uid=None, uirevision=None, visible=None, x=None, x0=None, xaxis=None, xsrc=None, xtype=None, y=None, y0=None, yaxis=None, ysrc=None, ytype=None, z=None, zauto=None, zmax=None, zmid=None, zmin=None, zsmooth=None, zsrc=None, row=None, col=None, secondary_y=None, **kwargs ): """ Add a new Heatmapgl trace WebGL version of the heatmap trace type. Parameters ---------- autocolorscale Determines whether the colorscale is a default palette (`autocolorscale: true`) or the palette determined by `colorscale`. In case `colorscale` is unspecified or `autocolorscale` is true, the default palette will be chosen according to whether numbers in the `color` array are all positive, all negative or mixed. coloraxis Sets a reference to a shared color axis. References to these shared color axes are "coloraxis", "coloraxis2", "coloraxis3", etc. Settings for these shared color axes are set in the layout, under `layout.coloraxis`, `layout.coloraxis2`, etc. Note that multiple color scales can be linked to the same color axis. colorbar :class:`plotly.graph_objects.heatmapgl.ColorBar` instance or dict with compatible properties colorscale Sets the colorscale. The colorscale must be an array containing arrays mapping a normalized value to an rgb, rgba, hex, hsl, hsv, or named color string. At minimum, a mapping for the lowest (0) and highest (1) values are required. For example, `[[0, 'rgb(0,0,255)'], [1, 'rgb(255,0,0)']]`. To control the bounds of the colorscale in color space, use`zmin` and `zmax`. Alternatively, `colorscale` may be a palette name string of the following list: Greys,YlGnBu,Greens,YlOrR d,Bluered,RdBu,Reds,Blues,Picnic,Rainbow,Portland,Jet,H ot,Blackbody,Earth,Electric,Viridis,Cividis. customdata Assigns extra data each datum. This may be useful when listening to hover, click and selection events. Note that, "scatter" traces also appends customdata items in the markers DOM elements customdatasrc Sets the source reference on Chart Studio Cloud for customdata . dx Sets the x coordinate step. See `x0` for more info. dy Sets the y coordinate step. See `y0` for more info. hoverinfo Determines which trace information appear on hover. If `none` or `skip` are set, no information is displayed upon hovering. But, if `none` is set, click and hover events are still fired. hoverinfosrc Sets the source reference on Chart Studio Cloud for hoverinfo . hoverlabel :class:`plotly.graph_objects.heatmapgl.Hoverlabel` instance or dict with compatible properties ids Assigns id labels to each datum. These ids for object constancy of data points during animation. Should be an array of strings, not numbers or any other type. idssrc Sets the source reference on Chart Studio Cloud for ids . meta Assigns extra meta information associated with this trace that can be used in various text attributes. Attributes such as trace `name`, graph, axis and colorbar `title.text`, annotation `text` `rangeselector`, `updatemenues` and `sliders` `label` text all support `meta`. To access the trace `meta` values in an attribute in the same trace, simply use `%{meta[i]}` where `i` is the index or key of the `meta` item in question. To access trace `meta` in layout attributes, use `%{data[n[.meta[i]}` where `i` is the index or key of the `meta` and `n` is the trace index. metasrc Sets the source reference on Chart Studio Cloud for meta . name Sets the trace name. The trace name appear as the legend item and on hover. opacity Sets the opacity of the trace. reversescale Reverses the color mapping if true. If true, `zmin` will correspond to the last color in the array and `zmax` will correspond to the first color. showscale Determines whether or not a colorbar is displayed for this trace. stream :class:`plotly.graph_objects.heatmapgl.Stream` instance or dict with compatible properties text Sets the text elements associated with each z value. textsrc Sets the source reference on Chart Studio Cloud for text . transpose Transposes the z data. uid Assign an id to this trace, Use this to provide object constancy between traces during animations and transitions. uirevision Controls persistence of some user-driven changes to the trace: `constraintrange` in `parcoords` traces, as well as some `editable: true` modifications such as `name` and `colorbar.title`. Defaults to `layout.uirevision`. Note that other user-driven trace attribute changes are controlled by `layout` attributes: `trace.visible` is controlled by `layout.legend.uirevision`, `selectedpoints` is controlled by `layout.selectionrevision`, and `colorbar.(x|y)` (accessible with `config: {editable: true}`) is controlled by `layout.editrevision`. Trace changes are tracked by `uid`, which only falls back on trace index if no `uid` is provided. So if your app can add/remove traces before the end of the `data` array, such that the same trace has a different index, you can still preserve user-driven changes if you give each trace a `uid` that stays with it as it moves. visible Determines whether or not this trace is visible. If "legendonly", the trace is not drawn, but can appear as a legend item (provided that the legend itself is visible). x Sets the x coordinates. x0 Alternate to `x`. Builds a linear space of x coordinates. Use with `dx` where `x0` is the starting coordinate and `dx` the step. xaxis Sets a reference between this trace's x coordinates and a 2D cartesian x axis. If "x" (the default value), the x coordinates refer to `layout.xaxis`. If "x2", the x coordinates refer to `layout.xaxis2`, and so on. xsrc Sets the source reference on Chart Studio Cloud for x . xtype If "array", the heatmap's x coordinates are given by "x" (the default behavior when `x` is provided). If "scaled", the heatmap's x coordinates are given by "x0" and "dx" (the default behavior when `x` is not provided). y Sets the y coordinates. y0 Alternate to `y`. Builds a linear space of y coordinates. Use with `dy` where `y0` is the starting coordinate and `dy` the step. yaxis Sets a reference between this trace's y coordinates and a 2D cartesian y axis. If "y" (the default value), the y coordinates refer to `layout.yaxis`. If "y2", the y coordinates refer to `layout.yaxis2`, and so on. ysrc Sets the source reference on Chart Studio Cloud for y . ytype If "array", the heatmap's y coordinates are given by "y" (the default behavior when `y` is provided) If "scaled", the heatmap's y coordinates are given by "y0" and "dy" (the default behavior when `y` is not provided) z Sets the z data. zauto Determines whether or not the color domain is computed with respect to the input data (here in `z`) or the bounds set in `zmin` and `zmax` Defaults to `false` when `zmin` and `zmax` are set by the user. zmax Sets the upper bound of the color domain. Value should have the same units as in `z` and if set, `zmin` must be set as well. zmid Sets the mid-point of the color domain by scaling `zmin` and/or `zmax` to be equidistant to this point. Value should have the same units as in `z`. Has no effect when `zauto` is `false`. zmin Sets the lower bound of the color domain. Value should have the same units as in `z` and if set, `zmax` must be set as well. zsmooth Picks a smoothing algorithm use to smooth `z` data. zsrc Sets the source reference on Chart Studio Cloud for z . row : int or None (default) Subplot row index (starting from 1) for the trace to be added. Only valid if figure was created using `plotly.tools.make_subplots` col : int or None (default) Subplot col index (starting from 1) for the trace to be added. Only valid if figure was created using `plotly.tools.make_subplots` secondary_y: boolean or None (default None) If True, associate this trace with the secondary y-axis of the subplot at the specified row and col. Only valid if all of the following conditions are satisfied: * The figure was created using `plotly.subplots.make_subplots`. * The row and col arguments are not None * The subplot at the specified row and col has type xy (which is the default) and secondary_y True. These properties are specified in the specs argument to make_subplots. See the make_subplots docstring for more info. Returns ------- FigureWidget """ from plotly.graph_objs import Heatmapgl new_trace = Heatmapgl( autocolorscale=autocolorscale, coloraxis=coloraxis, colorbar=colorbar, colorscale=colorscale, customdata=customdata, customdatasrc=customdatasrc, dx=dx, dy=dy, hoverinfo=hoverinfo, hoverinfosrc=hoverinfosrc, hoverlabel=hoverlabel, ids=ids, idssrc=idssrc, meta=meta, metasrc=metasrc, name=name, opacity=opacity, reversescale=reversescale, showscale=showscale, stream=stream, text=text, textsrc=textsrc, transpose=transpose, uid=uid, uirevision=uirevision, visible=visible, x=x, x0=x0, xaxis=xaxis, xsrc=xsrc, xtype=xtype, y=y, y0=y0, yaxis=yaxis, ysrc=ysrc, ytype=ytype, z=z, zauto=zauto, zmax=zmax, zmid=zmid, zmin=zmin, zsmooth=zsmooth, zsrc=zsrc, **kwargs ) return self.add_trace(new_trace, row=row, col=col, secondary_y=secondary_y) def add_histogram( self, alignmentgroup=None, autobinx=None, autobiny=None, bingroup=None, cumulative=None, customdata=None, customdatasrc=None, error_x=None, error_y=None, histfunc=None, histnorm=None, hoverinfo=None, hoverinfosrc=None, hoverlabel=None, hovertemplate=None, hovertemplatesrc=None, hovertext=None, hovertextsrc=None, ids=None, idssrc=None, legendgroup=None, marker=None, meta=None, metasrc=None, name=None, nbinsx=None, nbinsy=None, offsetgroup=None, opacity=None, orientation=None, selected=None, selectedpoints=None, showlegend=None, stream=None, text=None, textsrc=None, uid=None, uirevision=None, unselected=None, visible=None, x=None, xaxis=None, xbins=None, xcalendar=None, xsrc=None, y=None, yaxis=None, ybins=None, ycalendar=None, ysrc=None, row=None, col=None, secondary_y=None, **kwargs ): """ Add a new Histogram trace The sample data from which statistics are computed is set in `x` for vertically spanning histograms and in `y` for horizontally spanning histograms. Binning options are set `xbins` and `ybins` respectively if no aggregation data is provided. Parameters ---------- alignmentgroup Set several traces linked to the same position axis or matching axes to the same alignmentgroup. This controls whether bars compute their positional range dependently or independently. autobinx Obsolete: since v1.42 each bin attribute is auto- determined separately and `autobinx` is not needed. However, we accept `autobinx: true` or `false` and will update `xbins` accordingly before deleting `autobinx` from the trace. autobiny Obsolete: since v1.42 each bin attribute is auto- determined separately and `autobiny` is not needed. However, we accept `autobiny: true` or `false` and will update `ybins` accordingly before deleting `autobiny` from the trace. bingroup Set a group of histogram traces which will have compatible bin settings. Note that traces on the same subplot and with the same "orientation" under `barmode` "stack", "relative" and "group" are forced into the same bingroup, Using `bingroup`, traces under `barmode` "overlay" and on different axes (of the same axis type) can have compatible bin settings. Note that histogram and histogram2d* trace can share the same `bingroup` cumulative :class:`plotly.graph_objects.histogram.Cumulative` instance or dict with compatible properties customdata Assigns extra data each datum. This may be useful when listening to hover, click and selection events. Note that, "scatter" traces also appends customdata items in the markers DOM elements customdatasrc Sets the source reference on Chart Studio Cloud for customdata . error_x :class:`plotly.graph_objects.histogram.ErrorX` instance or dict with compatible properties error_y :class:`plotly.graph_objects.histogram.ErrorY` instance or dict with compatible properties histfunc Specifies the binning function used for this histogram trace. If "count", the histogram values are computed by counting the number of values lying inside each bin. If "sum", "avg", "min", "max", the histogram values are computed using the sum, the average, the minimum or the maximum of the values lying inside each bin respectively. histnorm Specifies the type of normalization used for this histogram trace. If "", the span of each bar corresponds to the number of occurrences (i.e. the number of data points lying inside the bins). If "percent" / "probability", the span of each bar corresponds to the percentage / fraction of occurrences with respect to the total number of sample points (here, the sum of all bin HEIGHTS equals 100% / 1). If "density", the span of each bar corresponds to the number of occurrences in a bin divided by the size of the bin interval (here, the sum of all bin AREAS equals the total number of sample points). If *probability density*, the area of each bar corresponds to the probability that an event will fall into the corresponding bin (here, the sum of all bin AREAS equals 1). hoverinfo Determines which trace information appear on hover. If `none` or `skip` are set, no information is displayed upon hovering. But, if `none` is set, click and hover events are still fired. hoverinfosrc Sets the source reference on Chart Studio Cloud for hoverinfo . hoverlabel :class:`plotly.graph_objects.histogram.Hoverlabel` instance or dict with compatible properties hovertemplate Template string used for rendering the information that appear on hover box. Note that this will override `hoverinfo`. Variables are inserted using %{variable}, for example "y: %{y}". Numbers are formatted using d3-format's syntax %{variable:d3-format}, for example "Price: %{y:$.2f}". https://github.com/d3/d3-3.x-api- reference/blob/master/Formatting.md#d3_format for details on the formatting syntax. Dates are formatted using d3-time-format's syntax %{variable|d3-time- format}, for example "Day: %{2019-01-01|%A}". https://github.com/d3/d3-time-format#locale_format for details on the date formatting syntax. The variables available in `hovertemplate` are the ones emitted as event data described at this link https://plotly.com/javascript/plotlyjs-events/#event- data. Additionally, every attributes that can be specified per-point (the ones that are `arrayOk: true`) are available. variable `binNumber` Anything contained in tag `<extra>` is displayed in the secondary box, for example "<extra>{fullData.name}</extra>". To hide the secondary box completely, use an empty tag `<extra></extra>`. hovertemplatesrc Sets the source reference on Chart Studio Cloud for hovertemplate . hovertext Same as `text`. hovertextsrc Sets the source reference on Chart Studio Cloud for hovertext . ids Assigns id labels to each datum. These ids for object constancy of data points during animation. Should be an array of strings, not numbers or any other type. idssrc Sets the source reference on Chart Studio Cloud for ids . legendgroup Sets the legend group for this trace. Traces part of the same legend group hide/show at the same time when toggling legend items. marker :class:`plotly.graph_objects.histogram.Marker` instance or dict with compatible properties meta Assigns extra meta information associated with this trace that can be used in various text attributes. Attributes such as trace `name`, graph, axis and colorbar `title.text`, annotation `text` `rangeselector`, `updatemenues` and `sliders` `label` text all support `meta`. To access the trace `meta` values in an attribute in the same trace, simply use `%{meta[i]}` where `i` is the index or key of the `meta` item in question. To access trace `meta` in layout attributes, use `%{data[n[.meta[i]}` where `i` is the index or key of the `meta` and `n` is the trace index. metasrc Sets the source reference on Chart Studio Cloud for meta . name Sets the trace name. The trace name appear as the legend item and on hover. nbinsx Specifies the maximum number of desired bins. This value will be used in an algorithm that will decide the optimal bin size such that the histogram best visualizes the distribution of the data. Ignored if `xbins.size` is provided. nbinsy Specifies the maximum number of desired bins. This value will be used in an algorithm that will decide the optimal bin size such that the histogram best visualizes the distribution of the data. Ignored if `ybins.size` is provided. offsetgroup Set several traces linked to the same position axis or matching axes to the same offsetgroup where bars of the same position coordinate will line up. opacity Sets the opacity of the trace. orientation Sets the orientation of the bars. With "v" ("h"), the value of the each bar spans along the vertical (horizontal). selected :class:`plotly.graph_objects.histogram.Selected` instance or dict with compatible properties selectedpoints Array containing integer indices of selected points. Has an effect only for traces that support selections. Note that an empty array means an empty selection where the `unselected` are turned on for all points, whereas, any other non-array values means no selection all where the `selected` and `unselected` styles have no effect. showlegend Determines whether or not an item corresponding to this trace is shown in the legend. stream :class:`plotly.graph_objects.histogram.Stream` instance or dict with compatible properties text Sets hover text elements associated with each bar. If a single string, the same string appears over all bars. If an array of string, the items are mapped in order to the this trace's coordinates. textsrc Sets the source reference on Chart Studio Cloud for text . uid Assign an id to this trace, Use this to provide object constancy between traces during animations and transitions. uirevision Controls persistence of some user-driven changes to the trace: `constraintrange` in `parcoords` traces, as well as some `editable: true` modifications such as `name` and `colorbar.title`. Defaults to `layout.uirevision`. Note that other user-driven trace attribute changes are controlled by `layout` attributes: `trace.visible` is controlled by `layout.legend.uirevision`, `selectedpoints` is controlled by `layout.selectionrevision`, and `colorbar.(x|y)` (accessible with `config: {editable: true}`) is controlled by `layout.editrevision`. Trace changes are tracked by `uid`, which only falls back on trace index if no `uid` is provided. So if your app can add/remove traces before the end of the `data` array, such that the same trace has a different index, you can still preserve user-driven changes if you give each trace a `uid` that stays with it as it moves. unselected :class:`plotly.graph_objects.histogram.Unselected` instance or dict with compatible properties visible Determines whether or not this trace is visible. If "legendonly", the trace is not drawn, but can appear as a legend item (provided that the legend itself is visible). x Sets the sample data to be binned on the x axis. xaxis Sets a reference between this trace's x coordinates and a 2D cartesian x axis. If "x" (the default value), the x coordinates refer to `layout.xaxis`. If "x2", the x coordinates refer to `layout.xaxis2`, and so on. xbins :class:`plotly.graph_objects.histogram.XBins` instance or dict with compatible properties xcalendar Sets the calendar system to use with `x` date data. xsrc Sets the source reference on Chart Studio Cloud for x . y Sets the sample data to be binned on the y axis. yaxis Sets a reference between this trace's y coordinates and a 2D cartesian y axis. If "y" (the default value), the y coordinates refer to `layout.yaxis`. If "y2", the y coordinates refer to `layout.yaxis2`, and so on. ybins :class:`plotly.graph_objects.histogram.YBins` instance or dict with compatible properties ycalendar Sets the calendar system to use with `y` date data. ysrc Sets the source reference on Chart Studio Cloud for y . row : int or None (default) Subplot row index (starting from 1) for the trace to be added. Only valid if figure was created using `plotly.tools.make_subplots` col : int or None (default) Subplot col index (starting from 1) for the trace to be added. Only valid if figure was created using `plotly.tools.make_subplots` secondary_y: boolean or None (default None) If True, associate this trace with the secondary y-axis of the subplot at the specified row and col. Only valid if all of the following conditions are satisfied: * The figure was created using `plotly.subplots.make_subplots`. * The row and col arguments are not None * The subplot at the specified row and col has type xy (which is the default) and secondary_y True. These properties are specified in the specs argument to make_subplots. See the make_subplots docstring for more info. Returns ------- FigureWidget """ from plotly.graph_objs import Histogram new_trace = Histogram( alignmentgroup=alignmentgroup, autobinx=autobinx, autobiny=autobiny, bingroup=bingroup, cumulative=cumulative, customdata=customdata, customdatasrc=customdatasrc, error_x=error_x, error_y=error_y, histfunc=histfunc, histnorm=histnorm, hoverinfo=hoverinfo, hoverinfosrc=hoverinfosrc, hoverlabel=hoverlabel, hovertemplate=hovertemplate, hovertemplatesrc=hovertemplatesrc, hovertext=hovertext, hovertextsrc=hovertextsrc, ids=ids, idssrc=idssrc, legendgroup=legendgroup, marker=marker, meta=meta, metasrc=metasrc, name=name, nbinsx=nbinsx, nbinsy=nbinsy, offsetgroup=offsetgroup, opacity=opacity, orientation=orientation, selected=selected, selectedpoints=selectedpoints, showlegend=showlegend, stream=stream, text=text, textsrc=textsrc, uid=uid, uirevision=uirevision, unselected=unselected, visible=visible, x=x, xaxis=xaxis, xbins=xbins, xcalendar=xcalendar, xsrc=xsrc, y=y, yaxis=yaxis, ybins=ybins, ycalendar=ycalendar, ysrc=ysrc, **kwargs ) return self.add_trace(new_trace, row=row, col=col, secondary_y=secondary_y) def add_histogram2d( self, autobinx=None, autobiny=None, autocolorscale=None, bingroup=None, coloraxis=None, colorbar=None, colorscale=None, customdata=None, customdatasrc=None, histfunc=None, histnorm=None, hoverinfo=None, hoverinfosrc=None, hoverlabel=None, hovertemplate=None, hovertemplatesrc=None, ids=None, idssrc=None, legendgroup=None, marker=None, meta=None, metasrc=None, name=None, nbinsx=None, nbinsy=None, opacity=None, reversescale=None, showlegend=None, showscale=None, stream=None, uid=None, uirevision=None, visible=None, x=None, xaxis=None, xbingroup=None, xbins=None, xcalendar=None, xgap=None, xsrc=None, y=None, yaxis=None, ybingroup=None, ybins=None, ycalendar=None, ygap=None, ysrc=None, z=None, zauto=None, zhoverformat=None, zmax=None, zmid=None, zmin=None, zsmooth=None, zsrc=None, row=None, col=None, secondary_y=None, **kwargs ): """ Add a new Histogram2d trace The sample data from which statistics are computed is set in `x` and `y` (where `x` and `y` represent marginal distributions, binning is set in `xbins` and `ybins` in this case) or `z` (where `z` represent the 2D distribution and binning set, binning is set by `x` and `y` in this case). The resulting distribution is visualized as a heatmap. Parameters ---------- autobinx Obsolete: since v1.42 each bin attribute is auto- determined separately and `autobinx` is not needed. However, we accept `autobinx: true` or `false` and will update `xbins` accordingly before deleting `autobinx` from the trace. autobiny Obsolete: since v1.42 each bin attribute is auto- determined separately and `autobiny` is not needed. However, we accept `autobiny: true` or `false` and will update `ybins` accordingly before deleting `autobiny` from the trace. autocolorscale Determines whether the colorscale is a default palette (`autocolorscale: true`) or the palette determined by `colorscale`. In case `colorscale` is unspecified or `autocolorscale` is true, the default palette will be chosen according to whether numbers in the `color` array are all positive, all negative or mixed. bingroup Set the `xbingroup` and `ybingroup` default prefix For example, setting a `bingroup` of 1 on two histogram2d traces will make them their x-bins and y-bins match separately. coloraxis Sets a reference to a shared color axis. References to these shared color axes are "coloraxis", "coloraxis2", "coloraxis3", etc. Settings for these shared color axes are set in the layout, under `layout.coloraxis`, `layout.coloraxis2`, etc. Note that multiple color scales can be linked to the same color axis. colorbar :class:`plotly.graph_objects.histogram2d.ColorBar` instance or dict with compatible properties colorscale Sets the colorscale. The colorscale must be an array containing arrays mapping a normalized value to an rgb, rgba, hex, hsl, hsv, or named color string. At minimum, a mapping for the lowest (0) and highest (1) values are required. For example, `[[0, 'rgb(0,0,255)'], [1, 'rgb(255,0,0)']]`. To control the bounds of the colorscale in color space, use`zmin` and `zmax`. Alternatively, `colorscale` may be a palette name string of the following list: Greys,YlGnBu,Greens,YlOrR d,Bluered,RdBu,Reds,Blues,Picnic,Rainbow,Portland,Jet,H ot,Blackbody,Earth,Electric,Viridis,Cividis. customdata Assigns extra data each datum. This may be useful when listening to hover, click and selection events. Note that, "scatter" traces also appends customdata items in the markers DOM elements customdatasrc Sets the source reference on Chart Studio Cloud for customdata . histfunc Specifies the binning function used for this histogram trace. If "count", the histogram values are computed by counting the number of values lying inside each bin. If "sum", "avg", "min", "max", the histogram values are computed using the sum, the average, the minimum or the maximum of the values lying inside each bin respectively. histnorm Specifies the type of normalization used for this histogram trace. If "", the span of each bar corresponds to the number of occurrences (i.e. the number of data points lying inside the bins). If "percent" / "probability", the span of each bar corresponds to the percentage / fraction of occurrences with respect to the total number of sample points (here, the sum of all bin HEIGHTS equals 100% / 1). If "density", the span of each bar corresponds to the number of occurrences in a bin divided by the size of the bin interval (here, the sum of all bin AREAS equals the total number of sample points). If *probability density*, the area of each bar corresponds to the probability that an event will fall into the corresponding bin (here, the sum of all bin AREAS equals 1). hoverinfo Determines which trace information appear on hover. If `none` or `skip` are set, no information is displayed upon hovering. But, if `none` is set, click and hover events are still fired. hoverinfosrc Sets the source reference on Chart Studio Cloud for hoverinfo . hoverlabel :class:`plotly.graph_objects.histogram2d.Hoverlabel` instance or dict with compatible properties hovertemplate Template string used for rendering the information that appear on hover box. Note that this will override `hoverinfo`. Variables are inserted using %{variable}, for example "y: %{y}". Numbers are formatted using d3-format's syntax %{variable:d3-format}, for example "Price: %{y:$.2f}". https://github.com/d3/d3-3.x-api- reference/blob/master/Formatting.md#d3_format for details on the formatting syntax. Dates are formatted using d3-time-format's syntax %{variable|d3-time- format}, for example "Day: %{2019-01-01|%A}". https://github.com/d3/d3-time-format#locale_format for details on the date formatting syntax. The variables available in `hovertemplate` are the ones emitted as event data described at this link https://plotly.com/javascript/plotlyjs-events/#event- data. Additionally, every attributes that can be specified per-point (the ones that are `arrayOk: true`) are available. variable `z` Anything contained in tag `<extra>` is displayed in the secondary box, for example "<extra>{fullData.name}</extra>". To hide the secondary box completely, use an empty tag `<extra></extra>`. hovertemplatesrc Sets the source reference on Chart Studio Cloud for hovertemplate . ids Assigns id labels to each datum. These ids for object constancy of data points during animation. Should be an array of strings, not numbers or any other type. idssrc Sets the source reference on Chart Studio Cloud for ids . legendgroup Sets the legend group for this trace. Traces part of the same legend group hide/show at the same time when toggling legend items. marker :class:`plotly.graph_objects.histogram2d.Marker` instance or dict with compatible properties meta Assigns extra meta information associated with this trace that can be used in various text attributes. Attributes such as trace `name`, graph, axis and colorbar `title.text`, annotation `text` `rangeselector`, `updatemenues` and `sliders` `label` text all support `meta`. To access the trace `meta` values in an attribute in the same trace, simply use `%{meta[i]}` where `i` is the index or key of the `meta` item in question. To access trace `meta` in layout attributes, use `%{data[n[.meta[i]}` where `i` is the index or key of the `meta` and `n` is the trace index. metasrc Sets the source reference on Chart Studio Cloud for meta . name Sets the trace name. The trace name appear as the legend item and on hover. nbinsx Specifies the maximum number of desired bins. This value will be used in an algorithm that will decide the optimal bin size such that the histogram best visualizes the distribution of the data. Ignored if `xbins.size` is provided. nbinsy Specifies the maximum number of desired bins. This value will be used in an algorithm that will decide the optimal bin size such that the histogram best visualizes the distribution of the data. Ignored if `ybins.size` is provided. opacity Sets the opacity of the trace. reversescale Reverses the color mapping if true. If true, `zmin` will correspond to the last color in the array and `zmax` will correspond to the first color. showlegend Determines whether or not an item corresponding to this trace is shown in the legend. showscale Determines whether or not a colorbar is displayed for this trace. stream :class:`plotly.graph_objects.histogram2d.Stream` instance or dict with compatible properties uid Assign an id to this trace, Use this to provide object constancy between traces during animations and transitions. uirevision Controls persistence of some user-driven changes to the trace: `constraintrange` in `parcoords` traces, as well as some `editable: true` modifications such as `name` and `colorbar.title`. Defaults to `layout.uirevision`. Note that other user-driven trace attribute changes are controlled by `layout` attributes: `trace.visible` is controlled by `layout.legend.uirevision`, `selectedpoints` is controlled by `layout.selectionrevision`, and `colorbar.(x|y)` (accessible with `config: {editable: true}`) is controlled by `layout.editrevision`. Trace changes are tracked by `uid`, which only falls back on trace index if no `uid` is provided. So if your app can add/remove traces before the end of the `data` array, such that the same trace has a different index, you can still preserve user-driven changes if you give each trace a `uid` that stays with it as it moves. visible Determines whether or not this trace is visible. If "legendonly", the trace is not drawn, but can appear as a legend item (provided that the legend itself is visible). x Sets the sample data to be binned on the x axis. xaxis Sets a reference between this trace's x coordinates and a 2D cartesian x axis. If "x" (the default value), the x coordinates refer to `layout.xaxis`. If "x2", the x coordinates refer to `layout.xaxis2`, and so on. xbingroup Set a group of histogram traces which will have compatible x-bin settings. Using `xbingroup`, histogram2d and histogram2dcontour traces (on axes of the same axis type) can have compatible x-bin settings. Note that the same `xbingroup` value can be used to set (1D) histogram `bingroup` xbins :class:`plotly.graph_objects.histogram2d.XBins` instance or dict with compatible properties xcalendar Sets the calendar system to use with `x` date data. xgap Sets the horizontal gap (in pixels) between bricks. xsrc Sets the source reference on Chart Studio Cloud for x . y Sets the sample data to be binned on the y axis. yaxis Sets a reference between this trace's y coordinates and a 2D cartesian y axis. If "y" (the default value), the y coordinates refer to `layout.yaxis`. If "y2", the y coordinates refer to `layout.yaxis2`, and so on. ybingroup Set a group of histogram traces which will have compatible y-bin settings. Using `ybingroup`, histogram2d and histogram2dcontour traces (on axes of the same axis type) can have compatible y-bin settings. Note that the same `ybingroup` value can be used to set (1D) histogram `bingroup` ybins :class:`plotly.graph_objects.histogram2d.YBins` instance or dict with compatible properties ycalendar Sets the calendar system to use with `y` date data. ygap Sets the vertical gap (in pixels) between bricks. ysrc Sets the source reference on Chart Studio Cloud for y . z Sets the aggregation data. zauto Determines whether or not the color domain is computed with respect to the input data (here in `z`) or the bounds set in `zmin` and `zmax` Defaults to `false` when `zmin` and `zmax` are set by the user. zhoverformat Sets the hover text formatting rule using d3 formatting mini-languages which are very similar to those in Python. See: https://github.com/d3/d3-3.x-api- reference/blob/master/Formatting.md#d3_format zmax Sets the upper bound of the color domain. Value should have the same units as in `z` and if set, `zmin` must be set as well. zmid Sets the mid-point of the color domain by scaling `zmin` and/or `zmax` to be equidistant to this point. Value should have the same units as in `z`. Has no effect when `zauto` is `false`. zmin Sets the lower bound of the color domain. Value should have the same units as in `z` and if set, `zmax` must be set as well. zsmooth Picks a smoothing algorithm use to smooth `z` data. zsrc Sets the source reference on Chart Studio Cloud for z . row : int or None (default) Subplot row index (starting from 1) for the trace to be added. Only valid if figure was created using `plotly.tools.make_subplots` col : int or None (default) Subplot col index (starting from 1) for the trace to be added. Only valid if figure was created using `plotly.tools.make_subplots` secondary_y: boolean or None (default None) If True, associate this trace with the secondary y-axis of the subplot at the specified row and col. Only valid if all of the following conditions are satisfied: * The figure was created using `plotly.subplots.make_subplots`. * The row and col arguments are not None * The subplot at the specified row and col has type xy (which is the default) and secondary_y True. These properties are specified in the specs argument to make_subplots. See the make_subplots docstring for more info. Returns ------- FigureWidget """ from plotly.graph_objs import Histogram2d new_trace = Histogram2d( autobinx=autobinx, autobiny=autobiny, autocolorscale=autocolorscale, bingroup=bingroup, coloraxis=coloraxis, colorbar=colorbar, colorscale=colorscale, customdata=customdata, customdatasrc=customdatasrc, histfunc=histfunc, histnorm=histnorm, hoverinfo=hoverinfo, hoverinfosrc=hoverinfosrc, hoverlabel=hoverlabel, hovertemplate=hovertemplate, hovertemplatesrc=hovertemplatesrc, ids=ids, idssrc=idssrc, legendgroup=legendgroup, marker=marker, meta=meta, metasrc=metasrc, name=name, nbinsx=nbinsx, nbinsy=nbinsy, opacity=opacity, reversescale=reversescale, showlegend=showlegend, showscale=showscale, stream=stream, uid=uid, uirevision=uirevision, visible=visible, x=x, xaxis=xaxis, xbingroup=xbingroup, xbins=xbins, xcalendar=xcalendar, xgap=xgap, xsrc=xsrc, y=y, yaxis=yaxis, ybingroup=ybingroup, ybins=ybins, ycalendar=ycalendar, ygap=ygap, ysrc=ysrc, z=z, zauto=zauto, zhoverformat=zhoverformat, zmax=zmax, zmid=zmid, zmin=zmin, zsmooth=zsmooth, zsrc=zsrc, **kwargs ) return self.add_trace(new_trace, row=row, col=col, secondary_y=secondary_y) def add_histogram2dcontour( self, autobinx=None, autobiny=None, autocolorscale=None, autocontour=None, bingroup=None, coloraxis=None, colorbar=None, colorscale=None, contours=None, customdata=None, customdatasrc=None, histfunc=None, histnorm=None, hoverinfo=None, hoverinfosrc=None, hoverlabel=None, hovertemplate=None, hovertemplatesrc=None, ids=None, idssrc=None, legendgroup=None, line=None, marker=None, meta=None, metasrc=None, name=None, nbinsx=None, nbinsy=None, ncontours=None, opacity=None, reversescale=None, showlegend=None, showscale=None, stream=None, uid=None, uirevision=None, visible=None, x=None, xaxis=None, xbingroup=None, xbins=None, xcalendar=None, xsrc=None, y=None, yaxis=None, ybingroup=None, ybins=None, ycalendar=None, ysrc=None, z=None, zauto=None, zhoverformat=None, zmax=None, zmid=None, zmin=None, zsrc=None, row=None, col=None, secondary_y=None, **kwargs ): """ Add a new Histogram2dContour trace The sample data from which statistics are computed is set in `x` and `y` (where `x` and `y` represent marginal distributions, binning is set in `xbins` and `ybins` in this case) or `z` (where `z` represent the 2D distribution and binning set, binning is set by `x` and `y` in this case). The resulting distribution is visualized as a contour plot. Parameters ---------- autobinx Obsolete: since v1.42 each bin attribute is auto- determined separately and `autobinx` is not needed. However, we accept `autobinx: true` or `false` and will update `xbins` accordingly before deleting `autobinx` from the trace. autobiny Obsolete: since v1.42 each bin attribute is auto- determined separately and `autobiny` is not needed. However, we accept `autobiny: true` or `false` and will update `ybins` accordingly before deleting `autobiny` from the trace. autocolorscale Determines whether the colorscale is a default palette (`autocolorscale: true`) or the palette determined by `colorscale`. In case `colorscale` is unspecified or `autocolorscale` is true, the default palette will be chosen according to whether numbers in the `color` array are all positive, all negative or mixed. autocontour Determines whether or not the contour level attributes are picked by an algorithm. If True, the number of contour levels can be set in `ncontours`. If False, set the contour level attributes in `contours`. bingroup Set the `xbingroup` and `ybingroup` default prefix For example, setting a `bingroup` of 1 on two histogram2d traces will make them their x-bins and y-bins match separately. coloraxis Sets a reference to a shared color axis. References to these shared color axes are "coloraxis", "coloraxis2", "coloraxis3", etc. Settings for these shared color axes are set in the layout, under `layout.coloraxis`, `layout.coloraxis2`, etc. Note that multiple color scales can be linked to the same color axis. colorbar :class:`plotly.graph_objects.histogram2dcontour.ColorBa r` instance or dict with compatible properties colorscale Sets the colorscale. The colorscale must be an array containing arrays mapping a normalized value to an rgb, rgba, hex, hsl, hsv, or named color string. At minimum, a mapping for the lowest (0) and highest (1) values are required. For example, `[[0, 'rgb(0,0,255)'], [1, 'rgb(255,0,0)']]`. To control the bounds of the colorscale in color space, use`zmin` and `zmax`. Alternatively, `colorscale` may be a palette name string of the following list: Greys,YlGnBu,Greens,YlOrR d,Bluered,RdBu,Reds,Blues,Picnic,Rainbow,Portland,Jet,H ot,Blackbody,Earth,Electric,Viridis,Cividis. contours :class:`plotly.graph_objects.histogram2dcontour.Contour s` instance or dict with compatible properties customdata Assigns extra data each datum. This may be useful when listening to hover, click and selection events. Note that, "scatter" traces also appends customdata items in the markers DOM elements customdatasrc Sets the source reference on Chart Studio Cloud for customdata . histfunc Specifies the binning function used for this histogram trace. If "count", the histogram values are computed by counting the number of values lying inside each bin. If "sum", "avg", "min", "max", the histogram values are computed using the sum, the average, the minimum or the maximum of the values lying inside each bin respectively. histnorm Specifies the type of normalization used for this histogram trace. If "", the span of each bar corresponds to the number of occurrences (i.e. the number of data points lying inside the bins). If "percent" / "probability", the span of each bar corresponds to the percentage / fraction of occurrences with respect to the total number of sample points (here, the sum of all bin HEIGHTS equals 100% / 1). If "density", the span of each bar corresponds to the number of occurrences in a bin divided by the size of the bin interval (here, the sum of all bin AREAS equals the total number of sample points). If *probability density*, the area of each bar corresponds to the probability that an event will fall into the corresponding bin (here, the sum of all bin AREAS equals 1). hoverinfo Determines which trace information appear on hover. If `none` or `skip` are set, no information is displayed upon hovering. But, if `none` is set, click and hover events are still fired. hoverinfosrc Sets the source reference on Chart Studio Cloud for hoverinfo . hoverlabel :class:`plotly.graph_objects.histogram2dcontour.Hoverla bel` instance or dict with compatible properties hovertemplate Template string used for rendering the information that appear on hover box. Note that this will override `hoverinfo`. Variables are inserted using %{variable}, for example "y: %{y}". Numbers are formatted using d3-format's syntax %{variable:d3-format}, for example "Price: %{y:$.2f}". https://github.com/d3/d3-3.x-api- reference/blob/master/Formatting.md#d3_format for details on the formatting syntax. Dates are formatted using d3-time-format's syntax %{variable|d3-time- format}, for example "Day: %{2019-01-01|%A}". https://github.com/d3/d3-time-format#locale_format for details on the date formatting syntax. The variables available in `hovertemplate` are the ones emitted as event data described at this link https://plotly.com/javascript/plotlyjs-events/#event- data. Additionally, every attributes that can be specified per-point (the ones that are `arrayOk: true`) are available. variable `z` Anything contained in tag `<extra>` is displayed in the secondary box, for example "<extra>{fullData.name}</extra>". To hide the secondary box completely, use an empty tag `<extra></extra>`. hovertemplatesrc Sets the source reference on Chart Studio Cloud for hovertemplate . ids Assigns id labels to each datum. These ids for object constancy of data points during animation. Should be an array of strings, not numbers or any other type. idssrc Sets the source reference on Chart Studio Cloud for ids . legendgroup Sets the legend group for this trace. Traces part of the same legend group hide/show at the same time when toggling legend items. line :class:`plotly.graph_objects.histogram2dcontour.Line` instance or dict with compatible properties marker :class:`plotly.graph_objects.histogram2dcontour.Marker` instance or dict with compatible properties meta Assigns extra meta information associated with this trace that can be used in various text attributes. Attributes such as trace `name`, graph, axis and colorbar `title.text`, annotation `text` `rangeselector`, `updatemenues` and `sliders` `label` text all support `meta`. To access the trace `meta` values in an attribute in the same trace, simply use `%{meta[i]}` where `i` is the index or key of the `meta` item in question. To access trace `meta` in layout attributes, use `%{data[n[.meta[i]}` where `i` is the index or key of the `meta` and `n` is the trace index. metasrc Sets the source reference on Chart Studio Cloud for meta . name Sets the trace name. The trace name appear as the legend item and on hover. nbinsx Specifies the maximum number of desired bins. This value will be used in an algorithm that will decide the optimal bin size such that the histogram best visualizes the distribution of the data. Ignored if `xbins.size` is provided. nbinsy Specifies the maximum number of desired bins. This value will be used in an algorithm that will decide the optimal bin size such that the histogram best visualizes the distribution of the data. Ignored if `ybins.size` is provided. ncontours Sets the maximum number of contour levels. The actual number of contours will be chosen automatically to be less than or equal to the value of `ncontours`. Has an effect only if `autocontour` is True or if `contours.size` is missing. opacity Sets the opacity of the trace. reversescale Reverses the color mapping if true. If true, `zmin` will correspond to the last color in the array and `zmax` will correspond to the first color. showlegend Determines whether or not an item corresponding to this trace is shown in the legend. showscale Determines whether or not a colorbar is displayed for this trace. stream :class:`plotly.graph_objects.histogram2dcontour.Stream` instance or dict with compatible properties uid Assign an id to this trace, Use this to provide object constancy between traces during animations and transitions. uirevision Controls persistence of some user-driven changes to the trace: `constraintrange` in `parcoords` traces, as well as some `editable: true` modifications such as `name` and `colorbar.title`. Defaults to `layout.uirevision`. Note that other user-driven trace attribute changes are controlled by `layout` attributes: `trace.visible` is controlled by `layout.legend.uirevision`, `selectedpoints` is controlled by `layout.selectionrevision`, and `colorbar.(x|y)` (accessible with `config: {editable: true}`) is controlled by `layout.editrevision`. Trace changes are tracked by `uid`, which only falls back on trace index if no `uid` is provided. So if your app can add/remove traces before the end of the `data` array, such that the same trace has a different index, you can still preserve user-driven changes if you give each trace a `uid` that stays with it as it moves. visible Determines whether or not this trace is visible. If "legendonly", the trace is not drawn, but can appear as a legend item (provided that the legend itself is visible). x Sets the sample data to be binned on the x axis. xaxis Sets a reference between this trace's x coordinates and a 2D cartesian x axis. If "x" (the default value), the x coordinates refer to `layout.xaxis`. If "x2", the x coordinates refer to `layout.xaxis2`, and so on. xbingroup Set a group of histogram traces which will have compatible x-bin settings. Using `xbingroup`, histogram2d and histogram2dcontour traces (on axes of the same axis type) can have compatible x-bin settings. Note that the same `xbingroup` value can be used to set (1D) histogram `bingroup` xbins :class:`plotly.graph_objects.histogram2dcontour.XBins` instance or dict with compatible properties xcalendar Sets the calendar system to use with `x` date data. xsrc Sets the source reference on Chart Studio Cloud for x . y Sets the sample data to be binned on the y axis. yaxis Sets a reference between this trace's y coordinates and a 2D cartesian y axis. If "y" (the default value), the y coordinates refer to `layout.yaxis`. If "y2", the y coordinates refer to `layout.yaxis2`, and so on. ybingroup Set a group of histogram traces which will have compatible y-bin settings. Using `ybingroup`, histogram2d and histogram2dcontour traces (on axes of the same axis type) can have compatible y-bin settings. Note that the same `ybingroup` value can be used to set (1D) histogram `bingroup` ybins :class:`plotly.graph_objects.histogram2dcontour.YBins` instance or dict with compatible properties ycalendar Sets the calendar system to use with `y` date data. ysrc Sets the source reference on Chart Studio Cloud for y . z Sets the aggregation data. zauto Determines whether or not the color domain is computed with respect to the input data (here in `z`) or the bounds set in `zmin` and `zmax` Defaults to `false` when `zmin` and `zmax` are set by the user. zhoverformat Sets the hover text formatting rule using d3 formatting mini-languages which are very similar to those in Python. See: https://github.com/d3/d3-3.x-api- reference/blob/master/Formatting.md#d3_format zmax Sets the upper bound of the color domain. Value should have the same units as in `z` and if set, `zmin` must be set as well. zmid Sets the mid-point of the color domain by scaling `zmin` and/or `zmax` to be equidistant to this point. Value should have the same units as in `z`. Has no effect when `zauto` is `false`. zmin Sets the lower bound of the color domain. Value should have the same units as in `z` and if set, `zmax` must be set as well. zsrc Sets the source reference on Chart Studio Cloud for z . row : int or None (default) Subplot row index (starting from 1) for the trace to be added. Only valid if figure was created using `plotly.tools.make_subplots` col : int or None (default) Subplot col index (starting from 1) for the trace to be added. Only valid if figure was created using `plotly.tools.make_subplots` secondary_y: boolean or None (default None) If True, associate this trace with the secondary y-axis of the subplot at the specified row and col. Only valid if all of the following conditions are satisfied: * The figure was created using `plotly.subplots.make_subplots`. * The row and col arguments are not None * The subplot at the specified row and col has type xy (which is the default) and secondary_y True. These properties are specified in the specs argument to make_subplots. See the make_subplots docstring for more info. Returns ------- FigureWidget """ from plotly.graph_objs import Histogram2dContour new_trace = Histogram2dContour( autobinx=autobinx, autobiny=autobiny, autocolorscale=autocolorscale, autocontour=autocontour, bingroup=bingroup, coloraxis=coloraxis, colorbar=colorbar, colorscale=colorscale, contours=contours, customdata=customdata, customdatasrc=customdatasrc, histfunc=histfunc, histnorm=histnorm, hoverinfo=hoverinfo, hoverinfosrc=hoverinfosrc, hoverlabel=hoverlabel, hovertemplate=hovertemplate, hovertemplatesrc=hovertemplatesrc, ids=ids, idssrc=idssrc, legendgroup=legendgroup, line=line, marker=marker, meta=meta, metasrc=metasrc, name=name, nbinsx=nbinsx, nbinsy=nbinsy, ncontours=ncontours, opacity=opacity, reversescale=reversescale, showlegend=showlegend, showscale=showscale, stream=stream, uid=uid, uirevision=uirevision, visible=visible, x=x, xaxis=xaxis, xbingroup=xbingroup, xbins=xbins, xcalendar=xcalendar, xsrc=xsrc, y=y, yaxis=yaxis, ybingroup=ybingroup, ybins=ybins, ycalendar=ycalendar, ysrc=ysrc, z=z, zauto=zauto, zhoverformat=zhoverformat, zmax=zmax, zmid=zmid, zmin=zmin, zsrc=zsrc, **kwargs ) return self.add_trace(new_trace, row=row, col=col, secondary_y=secondary_y) def add_image( self, colormodel=None, customdata=None, customdatasrc=None, dx=None, dy=None, hoverinfo=None, hoverinfosrc=None, hoverlabel=None, hovertemplate=None, hovertemplatesrc=None, hovertext=None, hovertextsrc=None, ids=None, idssrc=None, meta=None, metasrc=None, name=None, opacity=None, source=None, stream=None, text=None, textsrc=None, uid=None, uirevision=None, visible=None, x0=None, xaxis=None, y0=None, yaxis=None, z=None, zmax=None, zmin=None, zsrc=None, row=None, col=None, secondary_y=None, **kwargs ): """ Add a new Image trace Display an image, i.e. data on a 2D regular raster. By default, when an image is displayed in a subplot, its y axis will be reversed (ie. `autorange: 'reversed'`), constrained to the domain (ie. `constrain: 'domain'`) and it will have the same scale as its x axis (ie. `scaleanchor: 'x,`) in order for pixels to be rendered as squares. Parameters ---------- colormodel Color model used to map the numerical color components described in `z` into colors. If `source` is specified, this attribute will be set to `rgba256` otherwise it defaults to `rgb`. customdata Assigns extra data each datum. This may be useful when listening to hover, click and selection events. Note that, "scatter" traces also appends customdata items in the markers DOM elements customdatasrc Sets the source reference on Chart Studio Cloud for customdata . dx Set the pixel's horizontal size. dy Set the pixel's vertical size hoverinfo Determines which trace information appear on hover. If `none` or `skip` are set, no information is displayed upon hovering. But, if `none` is set, click and hover events are still fired. hoverinfosrc Sets the source reference on Chart Studio Cloud for hoverinfo . hoverlabel :class:`plotly.graph_objects.image.Hoverlabel` instance or dict with compatible properties hovertemplate Template string used for rendering the information that appear on hover box. Note that this will override `hoverinfo`. Variables are inserted using %{variable}, for example "y: %{y}". Numbers are formatted using d3-format's syntax %{variable:d3-format}, for example "Price: %{y:$.2f}". https://github.com/d3/d3-3.x-api- reference/blob/master/Formatting.md#d3_format for details on the formatting syntax. Dates are formatted using d3-time-format's syntax %{variable|d3-time- format}, for example "Day: %{2019-01-01|%A}". https://github.com/d3/d3-time-format#locale_format for details on the date formatting syntax. The variables available in `hovertemplate` are the ones emitted as event data described at this link https://plotly.com/javascript/plotlyjs-events/#event- data. Additionally, every attributes that can be specified per-point (the ones that are `arrayOk: true`) are available. variables `z`, `color` and `colormodel`. Anything contained in tag `<extra>` is displayed in the secondary box, for example "<extra>{fullData.name}</extra>". To hide the secondary box completely, use an empty tag `<extra></extra>`. hovertemplatesrc Sets the source reference on Chart Studio Cloud for hovertemplate . hovertext Same as `text`. hovertextsrc Sets the source reference on Chart Studio Cloud for hovertext . ids Assigns id labels to each datum. These ids for object constancy of data points during animation. Should be an array of strings, not numbers or any other type. idssrc Sets the source reference on Chart Studio Cloud for ids . meta Assigns extra meta information associated with this trace that can be used in various text attributes. Attributes such as trace `name`, graph, axis and colorbar `title.text`, annotation `text` `rangeselector`, `updatemenues` and `sliders` `label` text all support `meta`. To access the trace `meta` values in an attribute in the same trace, simply use `%{meta[i]}` where `i` is the index or key of the `meta` item in question. To access trace `meta` in layout attributes, use `%{data[n[.meta[i]}` where `i` is the index or key of the `meta` and `n` is the trace index. metasrc Sets the source reference on Chart Studio Cloud for meta . name Sets the trace name. The trace name appear as the legend item and on hover. opacity Sets the opacity of the trace. source Specifies the data URI of the image to be visualized. The URI consists of "data:image/[<media subtype>][;base64],<data>" stream :class:`plotly.graph_objects.image.Stream` instance or dict with compatible properties text Sets the text elements associated with each z value. textsrc Sets the source reference on Chart Studio Cloud for text . uid Assign an id to this trace, Use this to provide object constancy between traces during animations and transitions. uirevision Controls persistence of some user-driven changes to the trace: `constraintrange` in `parcoords` traces, as well as some `editable: true` modifications such as `name` and `colorbar.title`. Defaults to `layout.uirevision`. Note that other user-driven trace attribute changes are controlled by `layout` attributes: `trace.visible` is controlled by `layout.legend.uirevision`, `selectedpoints` is controlled by `layout.selectionrevision`, and `colorbar.(x|y)` (accessible with `config: {editable: true}`) is controlled by `layout.editrevision`. Trace changes are tracked by `uid`, which only falls back on trace index if no `uid` is provided. So if your app can add/remove traces before the end of the `data` array, such that the same trace has a different index, you can still preserve user-driven changes if you give each trace a `uid` that stays with it as it moves. visible Determines whether or not this trace is visible. If "legendonly", the trace is not drawn, but can appear as a legend item (provided that the legend itself is visible). x0 Set the image's x position. xaxis Sets a reference between this trace's x coordinates and a 2D cartesian x axis. If "x" (the default value), the x coordinates refer to `layout.xaxis`. If "x2", the x coordinates refer to `layout.xaxis2`, and so on. y0 Set the image's y position. yaxis Sets a reference between this trace's y coordinates and a 2D cartesian y axis. If "y" (the default value), the y coordinates refer to `layout.yaxis`. If "y2", the y coordinates refer to `layout.yaxis2`, and so on. z A 2-dimensional array in which each element is an array of 3 or 4 numbers representing a color. zmax Array defining the higher bound for each color component. Note that the default value will depend on the colormodel. For the `rgb` colormodel, it is [255, 255, 255]. For the `rgba` colormodel, it is [255, 255, 255, 1]. For the `rgba256` colormodel, it is [255, 255, 255, 255]. For the `hsl` colormodel, it is [360, 100, 100]. For the `hsla` colormodel, it is [360, 100, 100, 1]. zmin Array defining the lower bound for each color component. Note that the default value will depend on the colormodel. For the `rgb` colormodel, it is [0, 0, 0]. For the `rgba` colormodel, it is [0, 0, 0, 0]. For the `rgba256` colormodel, it is [0, 0, 0, 0]. For the `hsl` colormodel, it is [0, 0, 0]. For the `hsla` colormodel, it is [0, 0, 0, 0]. zsrc Sets the source reference on Chart Studio Cloud for z . row : int or None (default) Subplot row index (starting from 1) for the trace to be added. Only valid if figure was created using `plotly.tools.make_subplots` col : int or None (default) Subplot col index (starting from 1) for the trace to be added. Only valid if figure was created using `plotly.tools.make_subplots` secondary_y: boolean or None (default None) If True, associate this trace with the secondary y-axis of the subplot at the specified row and col. Only valid if all of the following conditions are satisfied: * The figure was created using `plotly.subplots.make_subplots`. * The row and col arguments are not None * The subplot at the specified row and col has type xy (which is the default) and secondary_y True. These properties are specified in the specs argument to make_subplots. See the make_subplots docstring for more info. Returns ------- FigureWidget """ from plotly.graph_objs import Image new_trace = Image( colormodel=colormodel, customdata=customdata, customdatasrc=customdatasrc, dx=dx, dy=dy, hoverinfo=hoverinfo, hoverinfosrc=hoverinfosrc, hoverlabel=hoverlabel, hovertemplate=hovertemplate, hovertemplatesrc=hovertemplatesrc, hovertext=hovertext, hovertextsrc=hovertextsrc, ids=ids, idssrc=idssrc, meta=meta, metasrc=metasrc, name=name, opacity=opacity, source=source, stream=stream, text=text, textsrc=textsrc, uid=uid, uirevision=uirevision, visible=visible, x0=x0, xaxis=xaxis, y0=y0, yaxis=yaxis, z=z, zmax=zmax, zmin=zmin, zsrc=zsrc, **kwargs ) return self.add_trace(new_trace, row=row, col=col, secondary_y=secondary_y) def add_indicator( self, align=None, customdata=None, customdatasrc=None, delta=None, domain=None, gauge=None, ids=None, idssrc=None, meta=None, metasrc=None, mode=None, name=None, number=None, stream=None, title=None, uid=None, uirevision=None, value=None, visible=None, row=None, col=None, **kwargs ): """ Add a new Indicator trace An indicator is used to visualize a single `value` along with some contextual information such as `steps` or a `threshold`, using a combination of three visual elements: a number, a delta, and/or a gauge. Deltas are taken with respect to a `reference`. Gauges can be either angular or bullet (aka linear) gauges. Parameters ---------- align Sets the horizontal alignment of the `text` within the box. Note that this attribute has no effect if an angular gauge is displayed: in this case, it is always centered customdata Assigns extra data each datum. This may be useful when listening to hover, click and selection events. Note that, "scatter" traces also appends customdata items in the markers DOM elements customdatasrc Sets the source reference on Chart Studio Cloud for customdata . delta :class:`plotly.graph_objects.indicator.Delta` instance or dict with compatible properties domain :class:`plotly.graph_objects.indicator.Domain` instance or dict with compatible properties gauge The gauge of the Indicator plot. ids Assigns id labels to each datum. These ids for object constancy of data points during animation. Should be an array of strings, not numbers or any other type. idssrc Sets the source reference on Chart Studio Cloud for ids . meta Assigns extra meta information associated with this trace that can be used in various text attributes. Attributes such as trace `name`, graph, axis and colorbar `title.text`, annotation `text` `rangeselector`, `updatemenues` and `sliders` `label` text all support `meta`. To access the trace `meta` values in an attribute in the same trace, simply use `%{meta[i]}` where `i` is the index or key of the `meta` item in question. To access trace `meta` in layout attributes, use `%{data[n[.meta[i]}` where `i` is the index or key of the `meta` and `n` is the trace index. metasrc Sets the source reference on Chart Studio Cloud for meta . mode Determines how the value is displayed on the graph. `number` displays the value numerically in text. `delta` displays the difference to a reference value in text. Finally, `gauge` displays the value graphically on an axis. name Sets the trace name. The trace name appear as the legend item and on hover. number :class:`plotly.graph_objects.indicator.Number` instance or dict with compatible properties stream :class:`plotly.graph_objects.indicator.Stream` instance or dict with compatible properties title :class:`plotly.graph_objects.indicator.Title` instance or dict with compatible properties uid Assign an id to this trace, Use this to provide object constancy between traces during animations and transitions. uirevision Controls persistence of some user-driven changes to the trace: `constraintrange` in `parcoords` traces, as well as some `editable: true` modifications such as `name` and `colorbar.title`. Defaults to `layout.uirevision`. Note that other user-driven trace attribute changes are controlled by `layout` attributes: `trace.visible` is controlled by `layout.legend.uirevision`, `selectedpoints` is controlled by `layout.selectionrevision`, and `colorbar.(x|y)` (accessible with `config: {editable: true}`) is controlled by `layout.editrevision`. Trace changes are tracked by `uid`, which only falls back on trace index if no `uid` is provided. So if your app can add/remove traces before the end of the `data` array, such that the same trace has a different index, you can still preserve user-driven changes if you give each trace a `uid` that stays with it as it moves. value Sets the number to be displayed. visible Determines whether or not this trace is visible. If "legendonly", the trace is not drawn, but can appear as a legend item (provided that the legend itself is visible). row : int or None (default) Subplot row index (starting from 1) for the trace to be added. Only valid if figure was created using `plotly.tools.make_subplots` col : int or None (default) Subplot col index (starting from 1) for the trace to be added. Only valid if figure was created using `plotly.tools.make_subplots` Returns ------- FigureWidget """ from plotly.graph_objs import Indicator new_trace = Indicator( align=align, customdata=customdata, customdatasrc=customdatasrc, delta=delta, domain=domain, gauge=gauge, ids=ids, idssrc=idssrc, meta=meta, metasrc=metasrc, mode=mode, name=name, number=number, stream=stream, title=title, uid=uid, uirevision=uirevision, value=value, visible=visible, **kwargs ) return self.add_trace(new_trace, row=row, col=col) def add_isosurface( self, autocolorscale=None, caps=None, cauto=None, cmax=None, cmid=None, cmin=None, coloraxis=None, colorbar=None, colorscale=None, contour=None, customdata=None, customdatasrc=None, flatshading=None, hoverinfo=None, hoverinfosrc=None, hoverlabel=None, hovertemplate=None, hovertemplatesrc=None, hovertext=None, hovertextsrc=None, ids=None, idssrc=None, isomax=None, isomin=None, legendgroup=None, lighting=None, lightposition=None, meta=None, metasrc=None, name=None, opacity=None, reversescale=None, scene=None, showlegend=None, showscale=None, slices=None, spaceframe=None, stream=None, surface=None, text=None, textsrc=None, uid=None, uirevision=None, value=None, valuesrc=None, visible=None, x=None, xsrc=None, y=None, ysrc=None, z=None, zsrc=None, row=None, col=None, **kwargs ): """ Add a new Isosurface trace Draws isosurfaces between iso-min and iso-max values with coordinates given by four 1-dimensional arrays containing the `value`, `x`, `y` and `z` of every vertex of a uniform or non- uniform 3-D grid. Horizontal or vertical slices, caps as well as spaceframe between iso-min and iso-max values could also be drawn using this trace. Parameters ---------- autocolorscale Determines whether the colorscale is a default palette (`autocolorscale: true`) or the palette determined by `colorscale`. In case `colorscale` is unspecified or `autocolorscale` is true, the default palette will be chosen according to whether numbers in the `color` array are all positive, all negative or mixed. caps :class:`plotly.graph_objects.isosurface.Caps` instance or dict with compatible properties cauto Determines whether or not the color domain is computed with respect to the input data (here `value`) or the bounds set in `cmin` and `cmax` Defaults to `false` when `cmin` and `cmax` are set by the user. cmax Sets the upper bound of the color domain. Value should have the same units as `value` and if set, `cmin` must be set as well. cmid Sets the mid-point of the color domain by scaling `cmin` and/or `cmax` to be equidistant to this point. Value should have the same units as `value`. Has no effect when `cauto` is `false`. cmin Sets the lower bound of the color domain. Value should have the same units as `value` and if set, `cmax` must be set as well. coloraxis Sets a reference to a shared color axis. References to these shared color axes are "coloraxis", "coloraxis2", "coloraxis3", etc. Settings for these shared color axes are set in the layout, under `layout.coloraxis`, `layout.coloraxis2`, etc. Note that multiple color scales can be linked to the same color axis. colorbar :class:`plotly.graph_objects.isosurface.ColorBar` instance or dict with compatible properties colorscale Sets the colorscale. The colorscale must be an array containing arrays mapping a normalized value to an rgb, rgba, hex, hsl, hsv, or named color string. At minimum, a mapping for the lowest (0) and highest (1) values are required. For example, `[[0, 'rgb(0,0,255)'], [1, 'rgb(255,0,0)']]`. To control the bounds of the colorscale in color space, use`cmin` and `cmax`. Alternatively, `colorscale` may be a palette name string of the following list: Greys,YlGnBu,Greens,YlOrR d,Bluered,RdBu,Reds,Blues,Picnic,Rainbow,Portland,Jet,H ot,Blackbody,Earth,Electric,Viridis,Cividis. contour :class:`plotly.graph_objects.isosurface.Contour` instance or dict with compatible properties customdata Assigns extra data each datum. This may be useful when listening to hover, click and selection events. Note that, "scatter" traces also appends customdata items in the markers DOM elements customdatasrc Sets the source reference on Chart Studio Cloud for customdata . flatshading Determines whether or not normal smoothing is applied to the meshes, creating meshes with an angular, low- poly look via flat reflections. hoverinfo Determines which trace information appear on hover. If `none` or `skip` are set, no information is displayed upon hovering. But, if `none` is set, click and hover events are still fired. hoverinfosrc Sets the source reference on Chart Studio Cloud for hoverinfo . hoverlabel :class:`plotly.graph_objects.isosurface.Hoverlabel` instance or dict with compatible properties hovertemplate Template string used for rendering the information that appear on hover box. Note that this will override `hoverinfo`. Variables are inserted using %{variable}, for example "y: %{y}". Numbers are formatted using d3-format's syntax %{variable:d3-format}, for example "Price: %{y:$.2f}". https://github.com/d3/d3-3.x-api- reference/blob/master/Formatting.md#d3_format for details on the formatting syntax. Dates are formatted using d3-time-format's syntax %{variable|d3-time- format}, for example "Day: %{2019-01-01|%A}". https://github.com/d3/d3-time-format#locale_format for details on the date formatting syntax. The variables available in `hovertemplate` are the ones emitted as event data described at this link https://plotly.com/javascript/plotlyjs-events/#event- data. Additionally, every attributes that can be specified per-point (the ones that are `arrayOk: true`) are available. Anything contained in tag `<extra>` is displayed in the secondary box, for example "<extra>{fullData.name}</extra>". To hide the secondary box completely, use an empty tag `<extra></extra>`. hovertemplatesrc Sets the source reference on Chart Studio Cloud for hovertemplate . hovertext Same as `text`. hovertextsrc Sets the source reference on Chart Studio Cloud for hovertext . ids Assigns id labels to each datum. These ids for object constancy of data points during animation. Should be an array of strings, not numbers or any other type. idssrc Sets the source reference on Chart Studio Cloud for ids . isomax Sets the maximum boundary for iso-surface plot. isomin Sets the minimum boundary for iso-surface plot. legendgroup Sets the legend group for this trace. Traces part of the same legend group hide/show at the same time when toggling legend items. lighting :class:`plotly.graph_objects.isosurface.Lighting` instance or dict with compatible properties lightposition :class:`plotly.graph_objects.isosurface.Lightposition` instance or dict with compatible properties meta Assigns extra meta information associated with this trace that can be used in various text attributes. Attributes such as trace `name`, graph, axis and colorbar `title.text`, annotation `text` `rangeselector`, `updatemenues` and `sliders` `label` text all support `meta`. To access the trace `meta` values in an attribute in the same trace, simply use `%{meta[i]}` where `i` is the index or key of the `meta` item in question. To access trace `meta` in layout attributes, use `%{data[n[.meta[i]}` where `i` is the index or key of the `meta` and `n` is the trace index. metasrc Sets the source reference on Chart Studio Cloud for meta . name Sets the trace name. The trace name appear as the legend item and on hover. opacity Sets the opacity of the surface. Please note that in the case of using high `opacity` values for example a value greater than or equal to 0.5 on two surfaces (and 0.25 with four surfaces), an overlay of multiple transparent surfaces may not perfectly be sorted in depth by the webgl API. This behavior may be improved in the near future and is subject to change. reversescale Reverses the color mapping if true. If true, `cmin` will correspond to the last color in the array and `cmax` will correspond to the first color. scene Sets a reference between this trace's 3D coordinate system and a 3D scene. If "scene" (the default value), the (x,y,z) coordinates refer to `layout.scene`. If "scene2", the (x,y,z) coordinates refer to `layout.scene2`, and so on. showlegend Determines whether or not an item corresponding to this trace is shown in the legend. showscale Determines whether or not a colorbar is displayed for this trace. slices :class:`plotly.graph_objects.isosurface.Slices` instance or dict with compatible properties spaceframe :class:`plotly.graph_objects.isosurface.Spaceframe` instance or dict with compatible properties stream :class:`plotly.graph_objects.isosurface.Stream` instance or dict with compatible properties surface :class:`plotly.graph_objects.isosurface.Surface` instance or dict with compatible properties text Sets the text elements associated with the vertices. If trace `hoverinfo` contains a "text" flag and "hovertext" is not set, these elements will be seen in the hover labels. textsrc Sets the source reference on Chart Studio Cloud for text . uid Assign an id to this trace, Use this to provide object constancy between traces during animations and transitions. uirevision Controls persistence of some user-driven changes to the trace: `constraintrange` in `parcoords` traces, as well as some `editable: true` modifications such as `name` and `colorbar.title`. Defaults to `layout.uirevision`. Note that other user-driven trace attribute changes are controlled by `layout` attributes: `trace.visible` is controlled by `layout.legend.uirevision`, `selectedpoints` is controlled by `layout.selectionrevision`, and `colorbar.(x|y)` (accessible with `config: {editable: true}`) is controlled by `layout.editrevision`. Trace changes are tracked by `uid`, which only falls back on trace index if no `uid` is provided. So if your app can add/remove traces before the end of the `data` array, such that the same trace has a different index, you can still preserve user-driven changes if you give each trace a `uid` that stays with it as it moves. value Sets the 4th dimension (value) of the vertices. valuesrc Sets the source reference on Chart Studio Cloud for value . visible Determines whether or not this trace is visible. If "legendonly", the trace is not drawn, but can appear as a legend item (provided that the legend itself is visible). x Sets the X coordinates of the vertices on X axis. xsrc Sets the source reference on Chart Studio Cloud for x . y Sets the Y coordinates of the vertices on Y axis. ysrc Sets the source reference on Chart Studio Cloud for y . z Sets the Z coordinates of the vertices on Z axis. zsrc Sets the source reference on Chart Studio Cloud for z . row : int or None (default) Subplot row index (starting from 1) for the trace to be added. Only valid if figure was created using `plotly.tools.make_subplots` col : int or None (default) Subplot col index (starting from 1) for the trace to be added. Only valid if figure was created using `plotly.tools.make_subplots` Returns ------- FigureWidget """ from plotly.graph_objs import Isosurface new_trace = Isosurface( autocolorscale=autocolorscale, caps=caps, cauto=cauto, cmax=cmax, cmid=cmid, cmin=cmin, coloraxis=coloraxis, colorbar=colorbar, colorscale=colorscale, contour=contour, customdata=customdata, customdatasrc=customdatasrc, flatshading=flatshading, hoverinfo=hoverinfo, hoverinfosrc=hoverinfosrc, hoverlabel=hoverlabel, hovertemplate=hovertemplate, hovertemplatesrc=hovertemplatesrc, hovertext=hovertext, hovertextsrc=hovertextsrc, ids=ids, idssrc=idssrc, isomax=isomax, isomin=isomin, legendgroup=legendgroup, lighting=lighting, lightposition=lightposition, meta=meta, metasrc=metasrc, name=name, opacity=opacity, reversescale=reversescale, scene=scene, showlegend=showlegend, showscale=showscale, slices=slices, spaceframe=spaceframe, stream=stream, surface=surface, text=text, textsrc=textsrc, uid=uid, uirevision=uirevision, value=value, valuesrc=valuesrc, visible=visible, x=x, xsrc=xsrc, y=y, ysrc=ysrc, z=z, zsrc=zsrc, **kwargs ) return self.add_trace(new_trace, row=row, col=col) def add_mesh3d( self, alphahull=None, autocolorscale=None, cauto=None, cmax=None, cmid=None, cmin=None, color=None, coloraxis=None, colorbar=None, colorscale=None, contour=None, customdata=None, customdatasrc=None, delaunayaxis=None, facecolor=None, facecolorsrc=None, flatshading=None, hoverinfo=None, hoverinfosrc=None, hoverlabel=None, hovertemplate=None, hovertemplatesrc=None, hovertext=None, hovertextsrc=None, i=None, ids=None, idssrc=None, intensity=None, intensitymode=None, intensitysrc=None, isrc=None, j=None, jsrc=None, k=None, ksrc=None, legendgroup=None, lighting=None, lightposition=None, meta=None, metasrc=None, name=None, opacity=None, reversescale=None, scene=None, showlegend=None, showscale=None, stream=None, text=None, textsrc=None, uid=None, uirevision=None, vertexcolor=None, vertexcolorsrc=None, visible=None, x=None, xcalendar=None, xsrc=None, y=None, ycalendar=None, ysrc=None, z=None, zcalendar=None, zsrc=None, row=None, col=None, **kwargs ): """ Add a new Mesh3d trace Draws sets of triangles with coordinates given by three 1-dimensional arrays in `x`, `y`, `z` and (1) a sets of `i`, `j`, `k` indices (2) Delaunay triangulation or (3) the Alpha- shape algorithm or (4) the Convex-hull algorithm Parameters ---------- alphahull Determines how the mesh surface triangles are derived from the set of vertices (points) represented by the `x`, `y` and `z` arrays, if the `i`, `j`, `k` arrays are not supplied. For general use of `mesh3d` it is preferred that `i`, `j`, `k` are supplied. If "-1", Delaunay triangulation is used, which is mainly suitable if the mesh is a single, more or less layer surface that is perpendicular to `delaunayaxis`. In case the `delaunayaxis` intersects the mesh surface at more than one point it will result triangles that are very long in the dimension of `delaunayaxis`. If ">0", the alpha-shape algorithm is used. In this case, the positive `alphahull` value signals the use of the alpha-shape algorithm, _and_ its value acts as the parameter for the mesh fitting. If 0, the convex-hull algorithm is used. It is suitable for convex bodies or if the intention is to enclose the `x`, `y` and `z` point set into a convex hull. autocolorscale Determines whether the colorscale is a default palette (`autocolorscale: true`) or the palette determined by `colorscale`. In case `colorscale` is unspecified or `autocolorscale` is true, the default palette will be chosen according to whether numbers in the `color` array are all positive, all negative or mixed. cauto Determines whether or not the color domain is computed with respect to the input data (here `intensity`) or the bounds set in `cmin` and `cmax` Defaults to `false` when `cmin` and `cmax` are set by the user. cmax Sets the upper bound of the color domain. Value should have the same units as `intensity` and if set, `cmin` must be set as well. cmid Sets the mid-point of the color domain by scaling `cmin` and/or `cmax` to be equidistant to this point. Value should have the same units as `intensity`. Has no effect when `cauto` is `false`. cmin Sets the lower bound of the color domain. Value should have the same units as `intensity` and if set, `cmax` must be set as well. color Sets the color of the whole mesh coloraxis Sets a reference to a shared color axis. References to these shared color axes are "coloraxis", "coloraxis2", "coloraxis3", etc. Settings for these shared color axes are set in the layout, under `layout.coloraxis`, `layout.coloraxis2`, etc. Note that multiple color scales can be linked to the same color axis. colorbar :class:`plotly.graph_objects.mesh3d.ColorBar` instance or dict with compatible properties colorscale Sets the colorscale. The colorscale must be an array containing arrays mapping a normalized value to an rgb, rgba, hex, hsl, hsv, or named color string. At minimum, a mapping for the lowest (0) and highest (1) values are required. For example, `[[0, 'rgb(0,0,255)'], [1, 'rgb(255,0,0)']]`. To control the bounds of the colorscale in color space, use`cmin` and `cmax`. Alternatively, `colorscale` may be a palette name string of the following list: Greys,YlGnBu,Greens,YlOrR d,Bluered,RdBu,Reds,Blues,Picnic,Rainbow,Portland,Jet,H ot,Blackbody,Earth,Electric,Viridis,Cividis. contour :class:`plotly.graph_objects.mesh3d.Contour` instance or dict with compatible properties customdata Assigns extra data each datum. This may be useful when listening to hover, click and selection events. Note that, "scatter" traces also appends customdata items in the markers DOM elements customdatasrc Sets the source reference on Chart Studio Cloud for customdata . delaunayaxis Sets the Delaunay axis, which is the axis that is perpendicular to the surface of the Delaunay triangulation. It has an effect if `i`, `j`, `k` are not provided and `alphahull` is set to indicate Delaunay triangulation. facecolor Sets the color of each face Overrides "color" and "vertexcolor". facecolorsrc Sets the source reference on Chart Studio Cloud for facecolor . flatshading Determines whether or not normal smoothing is applied to the meshes, creating meshes with an angular, low- poly look via flat reflections. hoverinfo Determines which trace information appear on hover. If `none` or `skip` are set, no information is displayed upon hovering. But, if `none` is set, click and hover events are still fired. hoverinfosrc Sets the source reference on Chart Studio Cloud for hoverinfo . hoverlabel :class:`plotly.graph_objects.mesh3d.Hoverlabel` instance or dict with compatible properties hovertemplate Template string used for rendering the information that appear on hover box. Note that this will override `hoverinfo`. Variables are inserted using %{variable}, for example "y: %{y}". Numbers are formatted using d3-format's syntax %{variable:d3-format}, for example "Price: %{y:$.2f}". https://github.com/d3/d3-3.x-api- reference/blob/master/Formatting.md#d3_format for details on the formatting syntax. Dates are formatted using d3-time-format's syntax %{variable|d3-time- format}, for example "Day: %{2019-01-01|%A}". https://github.com/d3/d3-time-format#locale_format for details on the date formatting syntax. The variables available in `hovertemplate` are the ones emitted as event data described at this link https://plotly.com/javascript/plotlyjs-events/#event- data. Additionally, every attributes that can be specified per-point (the ones that are `arrayOk: true`) are available. Anything contained in tag `<extra>` is displayed in the secondary box, for example "<extra>{fullData.name}</extra>". To hide the secondary box completely, use an empty tag `<extra></extra>`. hovertemplatesrc Sets the source reference on Chart Studio Cloud for hovertemplate . hovertext Same as `text`. hovertextsrc Sets the source reference on Chart Studio Cloud for hovertext . i A vector of vertex indices, i.e. integer values between 0 and the length of the vertex vectors, representing the "first" vertex of a triangle. For example, `{i[m], j[m], k[m]}` together represent face m (triangle m) in the mesh, where `i[m] = n` points to the triplet `{x[n], y[n], z[n]}` in the vertex arrays. Therefore, each element in `i` represents a point in space, which is the first vertex of a triangle. ids Assigns id labels to each datum. These ids for object constancy of data points during animation. Should be an array of strings, not numbers or any other type. idssrc Sets the source reference on Chart Studio Cloud for ids . intensity Sets the intensity values for vertices or cells as defined by `intensitymode`. It can be used for plotting fields on meshes. intensitymode Determines the source of `intensity` values. intensitysrc Sets the source reference on Chart Studio Cloud for intensity . isrc Sets the source reference on Chart Studio Cloud for i . j A vector of vertex indices, i.e. integer values between 0 and the length of the vertex vectors, representing the "second" vertex of a triangle. For example, `{i[m], j[m], k[m]}` together represent face m (triangle m) in the mesh, where `j[m] = n` points to the triplet `{x[n], y[n], z[n]}` in the vertex arrays. Therefore, each element in `j` represents a point in space, which is the second vertex of a triangle. jsrc Sets the source reference on Chart Studio Cloud for j . k A vector of vertex indices, i.e. integer values between 0 and the length of the vertex vectors, representing the "third" vertex of a triangle. For example, `{i[m], j[m], k[m]}` together represent face m (triangle m) in the mesh, where `k[m] = n` points to the triplet `{x[n], y[n], z[n]}` in the vertex arrays. Therefore, each element in `k` represents a point in space, which is the third vertex of a triangle. ksrc Sets the source reference on Chart Studio Cloud for k . legendgroup Sets the legend group for this trace. Traces part of the same legend group hide/show at the same time when toggling legend items. lighting :class:`plotly.graph_objects.mesh3d.Lighting` instance or dict with compatible properties lightposition :class:`plotly.graph_objects.mesh3d.Lightposition` instance or dict with compatible properties meta Assigns extra meta information associated with this trace that can be used in various text attributes. Attributes such as trace `name`, graph, axis and colorbar `title.text`, annotation `text` `rangeselector`, `updatemenues` and `sliders` `label` text all support `meta`. To access the trace `meta` values in an attribute in the same trace, simply use `%{meta[i]}` where `i` is the index or key of the `meta` item in question. To access trace `meta` in layout attributes, use `%{data[n[.meta[i]}` where `i` is the index or key of the `meta` and `n` is the trace index. metasrc Sets the source reference on Chart Studio Cloud for meta . name Sets the trace name. The trace name appear as the legend item and on hover. opacity Sets the opacity of the surface. Please note that in the case of using high `opacity` values for example a value greater than or equal to 0.5 on two surfaces (and 0.25 with four surfaces), an overlay of multiple transparent surfaces may not perfectly be sorted in depth by the webgl API. This behavior may be improved in the near future and is subject to change. reversescale Reverses the color mapping if true. If true, `cmin` will correspond to the last color in the array and `cmax` will correspond to the first color. scene Sets a reference between this trace's 3D coordinate system and a 3D scene. If "scene" (the default value), the (x,y,z) coordinates refer to `layout.scene`. If "scene2", the (x,y,z) coordinates refer to `layout.scene2`, and so on. showlegend Determines whether or not an item corresponding to this trace is shown in the legend. showscale Determines whether or not a colorbar is displayed for this trace. stream :class:`plotly.graph_objects.mesh3d.Stream` instance or dict with compatible properties text Sets the text elements associated with the vertices. If trace `hoverinfo` contains a "text" flag and "hovertext" is not set, these elements will be seen in the hover labels. textsrc Sets the source reference on Chart Studio Cloud for text . uid Assign an id to this trace, Use this to provide object constancy between traces during animations and transitions. uirevision Controls persistence of some user-driven changes to the trace: `constraintrange` in `parcoords` traces, as well as some `editable: true` modifications such as `name` and `colorbar.title`. Defaults to `layout.uirevision`. Note that other user-driven trace attribute changes are controlled by `layout` attributes: `trace.visible` is controlled by `layout.legend.uirevision`, `selectedpoints` is controlled by `layout.selectionrevision`, and `colorbar.(x|y)` (accessible with `config: {editable: true}`) is controlled by `layout.editrevision`. Trace changes are tracked by `uid`, which only falls back on trace index if no `uid` is provided. So if your app can add/remove traces before the end of the `data` array, such that the same trace has a different index, you can still preserve user-driven changes if you give each trace a `uid` that stays with it as it moves. vertexcolor Sets the color of each vertex Overrides "color". While Red, green and blue colors are in the range of 0 and 255; in the case of having vertex color data in RGBA format, the alpha color should be normalized to be between 0 and 1. vertexcolorsrc Sets the source reference on Chart Studio Cloud for vertexcolor . visible Determines whether or not this trace is visible. If "legendonly", the trace is not drawn, but can appear as a legend item (provided that the legend itself is visible). x Sets the X coordinates of the vertices. The nth element of vectors `x`, `y` and `z` jointly represent the X, Y and Z coordinates of the nth vertex. xcalendar Sets the calendar system to use with `x` date data. xsrc Sets the source reference on Chart Studio Cloud for x . y Sets the Y coordinates of the vertices. The nth element of vectors `x`, `y` and `z` jointly represent the X, Y and Z coordinates of the nth vertex. ycalendar Sets the calendar system to use with `y` date data. ysrc Sets the source reference on Chart Studio Cloud for y . z Sets the Z coordinates of the vertices. The nth element of vectors `x`, `y` and `z` jointly represent the X, Y and Z coordinates of the nth vertex. zcalendar Sets the calendar system to use with `z` date data. zsrc Sets the source reference on Chart Studio Cloud for z . row : int or None (default) Subplot row index (starting from 1) for the trace to be added. Only valid if figure was created using `plotly.tools.make_subplots` col : int or None (default) Subplot col index (starting from 1) for the trace to be added. Only valid if figure was created using `plotly.tools.make_subplots` Returns ------- FigureWidget """ from plotly.graph_objs import Mesh3d new_trace = Mesh3d( alphahull=alphahull, autocolorscale=autocolorscale, cauto=cauto, cmax=cmax, cmid=cmid, cmin=cmin, color=color, coloraxis=coloraxis, colorbar=colorbar, colorscale=colorscale, contour=contour, customdata=customdata, customdatasrc=customdatasrc, delaunayaxis=delaunayaxis, facecolor=facecolor, facecolorsrc=facecolorsrc, flatshading=flatshading, hoverinfo=hoverinfo, hoverinfosrc=hoverinfosrc, hoverlabel=hoverlabel, hovertemplate=hovertemplate, hovertemplatesrc=hovertemplatesrc, hovertext=hovertext, hovertextsrc=hovertextsrc, i=i, ids=ids, idssrc=idssrc, intensity=intensity, intensitymode=intensitymode, intensitysrc=intensitysrc, isrc=isrc, j=j, jsrc=jsrc, k=k, ksrc=ksrc, legendgroup=legendgroup, lighting=lighting, lightposition=lightposition, meta=meta, metasrc=metasrc, name=name, opacity=opacity, reversescale=reversescale, scene=scene, showlegend=showlegend, showscale=showscale, stream=stream, text=text, textsrc=textsrc, uid=uid, uirevision=uirevision, vertexcolor=vertexcolor, vertexcolorsrc=vertexcolorsrc, visible=visible, x=x, xcalendar=xcalendar, xsrc=xsrc, y=y, ycalendar=ycalendar, ysrc=ysrc, z=z, zcalendar=zcalendar, zsrc=zsrc, **kwargs ) return self.add_trace(new_trace, row=row, col=col) def add_ohlc( self, close=None, closesrc=None, customdata=None, customdatasrc=None, decreasing=None, high=None, highsrc=None, hoverinfo=None, hoverinfosrc=None, hoverlabel=None, hovertext=None, hovertextsrc=None, ids=None, idssrc=None, increasing=None, legendgroup=None, line=None, low=None, lowsrc=None, meta=None, metasrc=None, name=None, opacity=None, open=None, opensrc=None, selectedpoints=None, showlegend=None, stream=None, text=None, textsrc=None, tickwidth=None, uid=None, uirevision=None, visible=None, x=None, xaxis=None, xcalendar=None, xperiod=None, xperiod0=None, xperiodalignment=None, xsrc=None, yaxis=None, row=None, col=None, secondary_y=None, **kwargs ): """ Add a new Ohlc trace The ohlc (short for Open-High-Low-Close) is a style of financial chart describing open, high, low and close for a given `x` coordinate (most likely time). The tip of the lines represent the `low` and `high` values and the horizontal segments represent the `open` and `close` values. Sample points where the close value is higher (lower) then the open value are called increasing (decreasing). By default, increasing items are drawn in green whereas decreasing are drawn in red. Parameters ---------- close Sets the close values. closesrc Sets the source reference on Chart Studio Cloud for close . customdata Assigns extra data each datum. This may be useful when listening to hover, click and selection events. Note that, "scatter" traces also appends customdata items in the markers DOM elements customdatasrc Sets the source reference on Chart Studio Cloud for customdata . decreasing :class:`plotly.graph_objects.ohlc.Decreasing` instance or dict with compatible properties high Sets the high values. highsrc Sets the source reference on Chart Studio Cloud for high . hoverinfo Determines which trace information appear on hover. If `none` or `skip` are set, no information is displayed upon hovering. But, if `none` is set, click and hover events are still fired. hoverinfosrc Sets the source reference on Chart Studio Cloud for hoverinfo . hoverlabel :class:`plotly.graph_objects.ohlc.Hoverlabel` instance or dict with compatible properties hovertext Same as `text`. hovertextsrc Sets the source reference on Chart Studio Cloud for hovertext . ids Assigns id labels to each datum. These ids for object constancy of data points during animation. Should be an array of strings, not numbers or any other type. idssrc Sets the source reference on Chart Studio Cloud for ids . increasing :class:`plotly.graph_objects.ohlc.Increasing` instance or dict with compatible properties legendgroup Sets the legend group for this trace. Traces part of the same legend group hide/show at the same time when toggling legend items. line :class:`plotly.graph_objects.ohlc.Line` instance or dict with compatible properties low Sets the low values. lowsrc Sets the source reference on Chart Studio Cloud for low . meta Assigns extra meta information associated with this trace that can be used in various text attributes. Attributes such as trace `name`, graph, axis and colorbar `title.text`, annotation `text` `rangeselector`, `updatemenues` and `sliders` `label` text all support `meta`. To access the trace `meta` values in an attribute in the same trace, simply use `%{meta[i]}` where `i` is the index or key of the `meta` item in question. To access trace `meta` in layout attributes, use `%{data[n[.meta[i]}` where `i` is the index or key of the `meta` and `n` is the trace index. metasrc Sets the source reference on Chart Studio Cloud for meta . name Sets the trace name. The trace name appear as the legend item and on hover. opacity Sets the opacity of the trace. open Sets the open values. opensrc Sets the source reference on Chart Studio Cloud for open . selectedpoints Array containing integer indices of selected points. Has an effect only for traces that support selections. Note that an empty array means an empty selection where the `unselected` are turned on for all points, whereas, any other non-array values means no selection all where the `selected` and `unselected` styles have no effect. showlegend Determines whether or not an item corresponding to this trace is shown in the legend. stream :class:`plotly.graph_objects.ohlc.Stream` instance or dict with compatible properties text Sets hover text elements associated with each sample point. If a single string, the same string appears over all the data points. If an array of string, the items are mapped in order to this trace's sample points. textsrc Sets the source reference on Chart Studio Cloud for text . tickwidth Sets the width of the open/close tick marks relative to the "x" minimal interval. uid Assign an id to this trace, Use this to provide object constancy between traces during animations and transitions. uirevision Controls persistence of some user-driven changes to the trace: `constraintrange` in `parcoords` traces, as well as some `editable: true` modifications such as `name` and `colorbar.title`. Defaults to `layout.uirevision`. Note that other user-driven trace attribute changes are controlled by `layout` attributes: `trace.visible` is controlled by `layout.legend.uirevision`, `selectedpoints` is controlled by `layout.selectionrevision`, and `colorbar.(x|y)` (accessible with `config: {editable: true}`) is controlled by `layout.editrevision`. Trace changes are tracked by `uid`, which only falls back on trace index if no `uid` is provided. So if your app can add/remove traces before the end of the `data` array, such that the same trace has a different index, you can still preserve user-driven changes if you give each trace a `uid` that stays with it as it moves. visible Determines whether or not this trace is visible. If "legendonly", the trace is not drawn, but can appear as a legend item (provided that the legend itself is visible). x Sets the x coordinates. If absent, linear coordinate will be generated. xaxis Sets a reference between this trace's x coordinates and a 2D cartesian x axis. If "x" (the default value), the x coordinates refer to `layout.xaxis`. If "x2", the x coordinates refer to `layout.xaxis2`, and so on. xcalendar Sets the calendar system to use with `x` date data. xperiod Only relevant when the axis `type` is "date". Sets the period positioning in milliseconds or "M<n>" on the x axis. Special values in the form of "M<n>" could be used to declare the number of months. In this case `n` must be a positive integer. xperiod0 Only relevant when the axis `type` is "date". Sets the base for period positioning in milliseconds or date string on the x0 axis. When `x0period` is round number of weeks, the `x0period0` by default would be on a Sunday i.e. 2000-01-02, otherwise it would be at 2000-01-01. xperiodalignment Only relevant when the axis `type` is "date". Sets the alignment of data points on the x axis. xsrc Sets the source reference on Chart Studio Cloud for x . yaxis Sets a reference between this trace's y coordinates and a 2D cartesian y axis. If "y" (the default value), the y coordinates refer to `layout.yaxis`. If "y2", the y coordinates refer to `layout.yaxis2`, and so on. row : int or None (default) Subplot row index (starting from 1) for the trace to be added. Only valid if figure was created using `plotly.tools.make_subplots` col : int or None (default) Subplot col index (starting from 1) for the trace to be added. Only valid if figure was created using `plotly.tools.make_subplots` secondary_y: boolean or None (default None) If True, associate this trace with the secondary y-axis of the subplot at the specified row and col. Only valid if all of the following conditions are satisfied: * The figure was created using `plotly.subplots.make_subplots`. * The row and col arguments are not None * The subplot at the specified row and col has type xy (which is the default) and secondary_y True. These properties are specified in the specs argument to make_subplots. See the make_subplots docstring for more info. Returns ------- FigureWidget """ from plotly.graph_objs import Ohlc new_trace = Ohlc( close=close, closesrc=closesrc, customdata=customdata, customdatasrc=customdatasrc, decreasing=decreasing, high=high, highsrc=highsrc, hoverinfo=hoverinfo, hoverinfosrc=hoverinfosrc, hoverlabel=hoverlabel, hovertext=hovertext, hovertextsrc=hovertextsrc, ids=ids, idssrc=idssrc, increasing=increasing, legendgroup=legendgroup, line=line, low=low, lowsrc=lowsrc, meta=meta, metasrc=metasrc, name=name, opacity=opacity, open=open, opensrc=opensrc, selectedpoints=selectedpoints, showlegend=showlegend, stream=stream, text=text, textsrc=textsrc, tickwidth=tickwidth, uid=uid, uirevision=uirevision, visible=visible, x=x, xaxis=xaxis, xcalendar=xcalendar, xperiod=xperiod, xperiod0=xperiod0, xperiodalignment=xperiodalignment, xsrc=xsrc, yaxis=yaxis, **kwargs ) return self.add_trace(new_trace, row=row, col=col, secondary_y=secondary_y) def add_parcats( self, arrangement=None, bundlecolors=None, counts=None, countssrc=None, dimensions=None, dimensiondefaults=None, domain=None, hoverinfo=None, hoveron=None, hovertemplate=None, labelfont=None, line=None, meta=None, metasrc=None, name=None, sortpaths=None, stream=None, tickfont=None, uid=None, uirevision=None, visible=None, row=None, col=None, **kwargs ): """ Add a new Parcats trace Parallel categories diagram for multidimensional categorical data. Parameters ---------- arrangement Sets the drag interaction mode for categories and dimensions. If `perpendicular`, the categories can only move along a line perpendicular to the paths. If `freeform`, the categories can freely move on the plane. If `fixed`, the categories and dimensions are stationary. bundlecolors Sort paths so that like colors are bundled together within each category. counts The number of observations represented by each state. Defaults to 1 so that each state represents one observation countssrc Sets the source reference on Chart Studio Cloud for counts . dimensions The dimensions (variables) of the parallel categories diagram. dimensiondefaults When used in a template (as layout.template.data.parcats.dimensiondefaults), sets the default property values to use for elements of parcats.dimensions domain :class:`plotly.graph_objects.parcats.Domain` instance or dict with compatible properties hoverinfo Determines which trace information appear on hover. If `none` or `skip` are set, no information is displayed upon hovering. But, if `none` is set, click and hover events are still fired. hoveron Sets the hover interaction mode for the parcats diagram. If `category`, hover interaction take place per category. If `color`, hover interactions take place per color per category. If `dimension`, hover interactions take place across all categories per dimension. hovertemplate Template string used for rendering the information that appear on hover box. Note that this will override `hoverinfo`. Variables are inserted using %{variable}, for example "y: %{y}". Numbers are formatted using d3-format's syntax %{variable:d3-format}, for example "Price: %{y:$.2f}". https://github.com/d3/d3-3.x-api- reference/blob/master/Formatting.md#d3_format for details on the formatting syntax. Dates are formatted using d3-time-format's syntax %{variable|d3-time- format}, for example "Day: %{2019-01-01|%A}". https://github.com/d3/d3-time-format#locale_format for details on the date formatting syntax. The variables available in `hovertemplate` are the ones emitted as event data described at this link https://plotly.com/javascript/plotlyjs-events/#event- data. Additionally, every attributes that can be specified per-point (the ones that are `arrayOk: true`) are available. variables `count`, `probability`, `category`, `categorycount`, `colorcount` and `bandcolorcount`. Anything contained in tag `<extra>` is displayed in the secondary box, for example "<extra>{fullData.name}</extra>". To hide the secondary box completely, use an empty tag `<extra></extra>`. labelfont Sets the font for the `dimension` labels. line :class:`plotly.graph_objects.parcats.Line` instance or dict with compatible properties meta Assigns extra meta information associated with this trace that can be used in various text attributes. Attributes such as trace `name`, graph, axis and colorbar `title.text`, annotation `text` `rangeselector`, `updatemenues` and `sliders` `label` text all support `meta`. To access the trace `meta` values in an attribute in the same trace, simply use `%{meta[i]}` where `i` is the index or key of the `meta` item in question. To access trace `meta` in layout attributes, use `%{data[n[.meta[i]}` where `i` is the index or key of the `meta` and `n` is the trace index. metasrc Sets the source reference on Chart Studio Cloud for meta . name Sets the trace name. The trace name appear as the legend item and on hover. sortpaths Sets the path sorting algorithm. If `forward`, sort paths based on dimension categories from left to right. If `backward`, sort paths based on dimensions categories from right to left. stream :class:`plotly.graph_objects.parcats.Stream` instance or dict with compatible properties tickfont Sets the font for the `category` labels. uid Assign an id to this trace, Use this to provide object constancy between traces during animations and transitions. uirevision Controls persistence of some user-driven changes to the trace: `constraintrange` in `parcoords` traces, as well as some `editable: true` modifications such as `name` and `colorbar.title`. Defaults to `layout.uirevision`. Note that other user-driven trace attribute changes are controlled by `layout` attributes: `trace.visible` is controlled by `layout.legend.uirevision`, `selectedpoints` is controlled by `layout.selectionrevision`, and `colorbar.(x|y)` (accessible with `config: {editable: true}`) is controlled by `layout.editrevision`. Trace changes are tracked by `uid`, which only falls back on trace index if no `uid` is provided. So if your app can add/remove traces before the end of the `data` array, such that the same trace has a different index, you can still preserve user-driven changes if you give each trace a `uid` that stays with it as it moves. visible Determines whether or not this trace is visible. If "legendonly", the trace is not drawn, but can appear as a legend item (provided that the legend itself is visible). row : int or None (default) Subplot row index (starting from 1) for the trace to be added. Only valid if figure was created using `plotly.tools.make_subplots` col : int or None (default) Subplot col index (starting from 1) for the trace to be added. Only valid if figure was created using `plotly.tools.make_subplots` Returns ------- FigureWidget """ from plotly.graph_objs import Parcats new_trace = Parcats( arrangement=arrangement, bundlecolors=bundlecolors, counts=counts, countssrc=countssrc, dimensions=dimensions, dimensiondefaults=dimensiondefaults, domain=domain, hoverinfo=hoverinfo, hoveron=hoveron, hovertemplate=hovertemplate, labelfont=labelfont, line=line, meta=meta, metasrc=metasrc, name=name, sortpaths=sortpaths, stream=stream, tickfont=tickfont, uid=uid, uirevision=uirevision, visible=visible, **kwargs ) return self.add_trace(new_trace, row=row, col=col) def add_parcoords( self, customdata=None, customdatasrc=None, dimensions=None, dimensiondefaults=None, domain=None, ids=None, idssrc=None, labelangle=None, labelfont=None, labelside=None, line=None, meta=None, metasrc=None, name=None, rangefont=None, stream=None, tickfont=None, uid=None, uirevision=None, visible=None, row=None, col=None, **kwargs ): """ Add a new Parcoords trace Parallel coordinates for multidimensional exploratory data analysis. The samples are specified in `dimensions`. The colors are set in `line.color`. Parameters ---------- customdata Assigns extra data each datum. This may be useful when listening to hover, click and selection events. Note that, "scatter" traces also appends customdata items in the markers DOM elements customdatasrc Sets the source reference on Chart Studio Cloud for customdata . dimensions The dimensions (variables) of the parallel coordinates chart. 2..60 dimensions are supported. dimensiondefaults When used in a template (as layout.template.data.parcoords.dimensiondefaults), sets the default property values to use for elements of parcoords.dimensions domain :class:`plotly.graph_objects.parcoords.Domain` instance or dict with compatible properties ids Assigns id labels to each datum. These ids for object constancy of data points during animation. Should be an array of strings, not numbers or any other type. idssrc Sets the source reference on Chart Studio Cloud for ids . labelangle Sets the angle of the labels with respect to the horizontal. For example, a `tickangle` of -90 draws the labels vertically. Tilted labels with "labelangle" may be positioned better inside margins when `labelposition` is set to "bottom". labelfont Sets the font for the `dimension` labels. labelside Specifies the location of the `label`. "top" positions labels above, next to the title "bottom" positions labels below the graph Tilted labels with "labelangle" may be positioned better inside margins when `labelposition` is set to "bottom". line :class:`plotly.graph_objects.parcoords.Line` instance or dict with compatible properties meta Assigns extra meta information associated with this trace that can be used in various text attributes. Attributes such as trace `name`, graph, axis and colorbar `title.text`, annotation `text` `rangeselector`, `updatemenues` and `sliders` `label` text all support `meta`. To access the trace `meta` values in an attribute in the same trace, simply use `%{meta[i]}` where `i` is the index or key of the `meta` item in question. To access trace `meta` in layout attributes, use `%{data[n[.meta[i]}` where `i` is the index or key of the `meta` and `n` is the trace index. metasrc Sets the source reference on Chart Studio Cloud for meta . name Sets the trace name. The trace name appear as the legend item and on hover. rangefont Sets the font for the `dimension` range values. stream :class:`plotly.graph_objects.parcoords.Stream` instance or dict with compatible properties tickfont Sets the font for the `dimension` tick values. uid Assign an id to this trace, Use this to provide object constancy between traces during animations and transitions. uirevision Controls persistence of some user-driven changes to the trace: `constraintrange` in `parcoords` traces, as well as some `editable: true` modifications such as `name` and `colorbar.title`. Defaults to `layout.uirevision`. Note that other user-driven trace attribute changes are controlled by `layout` attributes: `trace.visible` is controlled by `layout.legend.uirevision`, `selectedpoints` is controlled by `layout.selectionrevision`, and `colorbar.(x|y)` (accessible with `config: {editable: true}`) is controlled by `layout.editrevision`. Trace changes are tracked by `uid`, which only falls back on trace index if no `uid` is provided. So if your app can add/remove traces before the end of the `data` array, such that the same trace has a different index, you can still preserve user-driven changes if you give each trace a `uid` that stays with it as it moves. visible Determines whether or not this trace is visible. If "legendonly", the trace is not drawn, but can appear as a legend item (provided that the legend itself is visible). row : int or None (default) Subplot row index (starting from 1) for the trace to be added. Only valid if figure was created using `plotly.tools.make_subplots` col : int or None (default) Subplot col index (starting from 1) for the trace to be added. Only valid if figure was created using `plotly.tools.make_subplots` Returns ------- FigureWidget """ from plotly.graph_objs import Parcoords new_trace = Parcoords( customdata=customdata, customdatasrc=customdatasrc, dimensions=dimensions, dimensiondefaults=dimensiondefaults, domain=domain, ids=ids, idssrc=idssrc, labelangle=labelangle, labelfont=labelfont, labelside=labelside, line=line, meta=meta, metasrc=metasrc, name=name, rangefont=rangefont, stream=stream, tickfont=tickfont, uid=uid, uirevision=uirevision, visible=visible, **kwargs ) return self.add_trace(new_trace, row=row, col=col) def add_pie( self, automargin=None, customdata=None, customdatasrc=None, direction=None, dlabel=None, domain=None, hole=None, hoverinfo=None, hoverinfosrc=None, hoverlabel=None, hovertemplate=None, hovertemplatesrc=None, hovertext=None, hovertextsrc=None, ids=None, idssrc=None, insidetextfont=None, insidetextorientation=None, label0=None, labels=None, labelssrc=None, legendgroup=None, marker=None, meta=None, metasrc=None, name=None, opacity=None, outsidetextfont=None, pull=None, pullsrc=None, rotation=None, scalegroup=None, showlegend=None, sort=None, stream=None, text=None, textfont=None, textinfo=None, textposition=None, textpositionsrc=None, textsrc=None, texttemplate=None, texttemplatesrc=None, title=None, titlefont=None, titleposition=None, uid=None, uirevision=None, values=None, valuessrc=None, visible=None, row=None, col=None, **kwargs ): """ Add a new Pie trace A data visualized by the sectors of the pie is set in `values`. The sector labels are set in `labels`. The sector colors are set in `marker.colors` Parameters ---------- automargin Determines whether outside text labels can push the margins. customdata Assigns extra data each datum. This may be useful when listening to hover, click and selection events. Note that, "scatter" traces also appends customdata items in the markers DOM elements customdatasrc Sets the source reference on Chart Studio Cloud for customdata . direction Specifies the direction at which succeeding sectors follow one another. dlabel Sets the label step. See `label0` for more info. domain :class:`plotly.graph_objects.pie.Domain` instance or dict with compatible properties hole Sets the fraction of the radius to cut out of the pie. Use this to make a donut chart. hoverinfo Determines which trace information appear on hover. If `none` or `skip` are set, no information is displayed upon hovering. But, if `none` is set, click and hover events are still fired. hoverinfosrc Sets the source reference on Chart Studio Cloud for hoverinfo . hoverlabel :class:`plotly.graph_objects.pie.Hoverlabel` instance or dict with compatible properties hovertemplate Template string used for rendering the information that appear on hover box. Note that this will override `hoverinfo`. Variables are inserted using %{variable}, for example "y: %{y}". Numbers are formatted using d3-format's syntax %{variable:d3-format}, for example "Price: %{y:$.2f}". https://github.com/d3/d3-3.x-api- reference/blob/master/Formatting.md#d3_format for details on the formatting syntax. Dates are formatted using d3-time-format's syntax %{variable|d3-time- format}, for example "Day: %{2019-01-01|%A}". https://github.com/d3/d3-time-format#locale_format for details on the date formatting syntax. The variables available in `hovertemplate` are the ones emitted as event data described at this link https://plotly.com/javascript/plotlyjs-events/#event- data. Additionally, every attributes that can be specified per-point (the ones that are `arrayOk: true`) are available. variables `label`, `color`, `value`, `percent` and `text`. Anything contained in tag `<extra>` is displayed in the secondary box, for example "<extra>{fullData.name}</extra>". To hide the secondary box completely, use an empty tag `<extra></extra>`. hovertemplatesrc Sets the source reference on Chart Studio Cloud for hovertemplate . hovertext Sets hover text elements associated with each sector. If a single string, the same string appears for all data points. If an array of string, the items are mapped in order of this trace's sectors. To be seen, trace `hoverinfo` must contain a "text" flag. hovertextsrc Sets the source reference on Chart Studio Cloud for hovertext . ids Assigns id labels to each datum. These ids for object constancy of data points during animation. Should be an array of strings, not numbers or any other type. idssrc Sets the source reference on Chart Studio Cloud for ids . insidetextfont Sets the font used for `textinfo` lying inside the sector. insidetextorientation Controls the orientation of the text inside chart sectors. When set to "auto", text may be oriented in any direction in order to be as big as possible in the middle of a sector. The "horizontal" option orients text to be parallel with the bottom of the chart, and may make text smaller in order to achieve that goal. The "radial" option orients text along the radius of the sector. The "tangential" option orients text perpendicular to the radius of the sector. label0 Alternate to `labels`. Builds a numeric set of labels. Use with `dlabel` where `label0` is the starting label and `dlabel` the step. labels Sets the sector labels. If `labels` entries are duplicated, we sum associated `values` or simply count occurrences if `values` is not provided. For other array attributes (including color) we use the first non-empty entry among all occurrences of the label. labelssrc Sets the source reference on Chart Studio Cloud for labels . legendgroup Sets the legend group for this trace. Traces part of the same legend group hide/show at the same time when toggling legend items. marker :class:`plotly.graph_objects.pie.Marker` instance or dict with compatible properties meta Assigns extra meta information associated with this trace that can be used in various text attributes. Attributes such as trace `name`, graph, axis and colorbar `title.text`, annotation `text` `rangeselector`, `updatemenues` and `sliders` `label` text all support `meta`. To access the trace `meta` values in an attribute in the same trace, simply use `%{meta[i]}` where `i` is the index or key of the `meta` item in question. To access trace `meta` in layout attributes, use `%{data[n[.meta[i]}` where `i` is the index or key of the `meta` and `n` is the trace index. metasrc Sets the source reference on Chart Studio Cloud for meta . name Sets the trace name. The trace name appear as the legend item and on hover. opacity Sets the opacity of the trace. outsidetextfont Sets the font used for `textinfo` lying outside the sector. pull Sets the fraction of larger radius to pull the sectors out from the center. This can be a constant to pull all slices apart from each other equally or an array to highlight one or more slices. pullsrc Sets the source reference on Chart Studio Cloud for pull . rotation Instead of the first slice starting at 12 o'clock, rotate to some other angle. scalegroup If there are multiple pie charts that should be sized according to their totals, link them by providing a non-empty group id here shared by every trace in the same group. showlegend Determines whether or not an item corresponding to this trace is shown in the legend. sort Determines whether or not the sectors are reordered from largest to smallest. stream :class:`plotly.graph_objects.pie.Stream` instance or dict with compatible properties text Sets text elements associated with each sector. If trace `textinfo` contains a "text" flag, these elements will be seen on the chart. If trace `hoverinfo` contains a "text" flag and "hovertext" is not set, these elements will be seen in the hover labels. textfont Sets the font used for `textinfo`. textinfo Determines which trace information appear on the graph. textposition Specifies the location of the `textinfo`. textpositionsrc Sets the source reference on Chart Studio Cloud for textposition . textsrc Sets the source reference on Chart Studio Cloud for text . texttemplate Template string used for rendering the information text that appear on points. Note that this will override `textinfo`. Variables are inserted using %{variable}, for example "y: %{y}". Numbers are formatted using d3-format's syntax %{variable:d3-format}, for example "Price: %{y:$.2f}". https://github.com/d3/d3-3.x-api- reference/blob/master/Formatting.md#d3_format for details on the formatting syntax. Dates are formatted using d3-time-format's syntax %{variable|d3-time- format}, for example "Day: %{2019-01-01|%A}". https://github.com/d3/d3-time-format#locale_format for details on the date formatting syntax. Every attributes that can be specified per-point (the ones that are `arrayOk: true`) are available. variables `label`, `color`, `value`, `percent` and `text`. texttemplatesrc Sets the source reference on Chart Studio Cloud for texttemplate . title :class:`plotly.graph_objects.pie.Title` instance or dict with compatible properties titlefont Deprecated: Please use pie.title.font instead. Sets the font used for `title`. Note that the title's font used to be set by the now deprecated `titlefont` attribute. titleposition Deprecated: Please use pie.title.position instead. Specifies the location of the `title`. Note that the title's position used to be set by the now deprecated `titleposition` attribute. uid Assign an id to this trace, Use this to provide object constancy between traces during animations and transitions. uirevision Controls persistence of some user-driven changes to the trace: `constraintrange` in `parcoords` traces, as well as some `editable: true` modifications such as `name` and `colorbar.title`. Defaults to `layout.uirevision`. Note that other user-driven trace attribute changes are controlled by `layout` attributes: `trace.visible` is controlled by `layout.legend.uirevision`, `selectedpoints` is controlled by `layout.selectionrevision`, and `colorbar.(x|y)` (accessible with `config: {editable: true}`) is controlled by `layout.editrevision`. Trace changes are tracked by `uid`, which only falls back on trace index if no `uid` is provided. So if your app can add/remove traces before the end of the `data` array, such that the same trace has a different index, you can still preserve user-driven changes if you give each trace a `uid` that stays with it as it moves. values Sets the values of the sectors. If omitted, we count occurrences of each label. valuessrc Sets the source reference on Chart Studio Cloud for values . visible Determines whether or not this trace is visible. If "legendonly", the trace is not drawn, but can appear as a legend item (provided that the legend itself is visible). row : int or None (default) Subplot row index (starting from 1) for the trace to be added. Only valid if figure was created using `plotly.tools.make_subplots` col : int or None (default) Subplot col index (starting from 1) for the trace to be added. Only valid if figure was created using `plotly.tools.make_subplots` Returns ------- FigureWidget """ from plotly.graph_objs import Pie new_trace = Pie( automargin=automargin, customdata=customdata, customdatasrc=customdatasrc, direction=direction, dlabel=dlabel, domain=domain, hole=hole, hoverinfo=hoverinfo, hoverinfosrc=hoverinfosrc, hoverlabel=hoverlabel, hovertemplate=hovertemplate, hovertemplatesrc=hovertemplatesrc, hovertext=hovertext, hovertextsrc=hovertextsrc, ids=ids, idssrc=idssrc, insidetextfont=insidetextfont, insidetextorientation=insidetextorientation, label0=label0, labels=labels, labelssrc=labelssrc, legendgroup=legendgroup, marker=marker, meta=meta, metasrc=metasrc, name=name, opacity=opacity, outsidetextfont=outsidetextfont, pull=pull, pullsrc=pullsrc, rotation=rotation, scalegroup=scalegroup, showlegend=showlegend, sort=sort, stream=stream, text=text, textfont=textfont, textinfo=textinfo, textposition=textposition, textpositionsrc=textpositionsrc, textsrc=textsrc, texttemplate=texttemplate, texttemplatesrc=texttemplatesrc, title=title, titlefont=titlefont, titleposition=titleposition, uid=uid, uirevision=uirevision, values=values, valuessrc=valuessrc, visible=visible, **kwargs ) return self.add_trace(new_trace, row=row, col=col) def add_pointcloud( self, customdata=None, customdatasrc=None, hoverinfo=None, hoverinfosrc=None, hoverlabel=None, ids=None, idssrc=None, indices=None, indicessrc=None, legendgroup=None, marker=None, meta=None, metasrc=None, name=None, opacity=None, showlegend=None, stream=None, text=None, textsrc=None, uid=None, uirevision=None, visible=None, x=None, xaxis=None, xbounds=None, xboundssrc=None, xsrc=None, xy=None, xysrc=None, y=None, yaxis=None, ybounds=None, yboundssrc=None, ysrc=None, row=None, col=None, secondary_y=None, **kwargs ): """ Add a new Pointcloud trace The data visualized as a point cloud set in `x` and `y` using the WebGl plotting engine. Parameters ---------- customdata Assigns extra data each datum. This may be useful when listening to hover, click and selection events. Note that, "scatter" traces also appends customdata items in the markers DOM elements customdatasrc Sets the source reference on Chart Studio Cloud for customdata . hoverinfo Determines which trace information appear on hover. If `none` or `skip` are set, no information is displayed upon hovering. But, if `none` is set, click and hover events are still fired. hoverinfosrc Sets the source reference on Chart Studio Cloud for hoverinfo . hoverlabel :class:`plotly.graph_objects.pointcloud.Hoverlabel` instance or dict with compatible properties ids Assigns id labels to each datum. These ids for object constancy of data points during animation. Should be an array of strings, not numbers or any other type. idssrc Sets the source reference on Chart Studio Cloud for ids . indices A sequential value, 0..n, supply it to avoid creating this array inside plotting. If specified, it must be a typed `Int32Array` array. Its length must be equal to or greater than the number of points. For the best performance and memory use, create one large `indices` typed array that is guaranteed to be at least as long as the largest number of points during use, and reuse it on each `Plotly.restyle()` call. indicessrc Sets the source reference on Chart Studio Cloud for indices . legendgroup Sets the legend group for this trace. Traces part of the same legend group hide/show at the same time when toggling legend items. marker :class:`plotly.graph_objects.pointcloud.Marker` instance or dict with compatible properties meta Assigns extra meta information associated with this trace that can be used in various text attributes. Attributes such as trace `name`, graph, axis and colorbar `title.text`, annotation `text` `rangeselector`, `updatemenues` and `sliders` `label` text all support `meta`. To access the trace `meta` values in an attribute in the same trace, simply use `%{meta[i]}` where `i` is the index or key of the `meta` item in question. To access trace `meta` in layout attributes, use `%{data[n[.meta[i]}` where `i` is the index or key of the `meta` and `n` is the trace index. metasrc Sets the source reference on Chart Studio Cloud for meta . name Sets the trace name. The trace name appear as the legend item and on hover. opacity Sets the opacity of the trace. showlegend Determines whether or not an item corresponding to this trace is shown in the legend. stream :class:`plotly.graph_objects.pointcloud.Stream` instance or dict with compatible properties text Sets text elements associated with each (x,y) pair. If a single string, the same string appears over all the data points. If an array of string, the items are mapped in order to the this trace's (x,y) coordinates. If trace `hoverinfo` contains a "text" flag and "hovertext" is not set, these elements will be seen in the hover labels. textsrc Sets the source reference on Chart Studio Cloud for text . uid Assign an id to this trace, Use this to provide object constancy between traces during animations and transitions. uirevision Controls persistence of some user-driven changes to the trace: `constraintrange` in `parcoords` traces, as well as some `editable: true` modifications such as `name` and `colorbar.title`. Defaults to `layout.uirevision`. Note that other user-driven trace attribute changes are controlled by `layout` attributes: `trace.visible` is controlled by `layout.legend.uirevision`, `selectedpoints` is controlled by `layout.selectionrevision`, and `colorbar.(x|y)` (accessible with `config: {editable: true}`) is controlled by `layout.editrevision`. Trace changes are tracked by `uid`, which only falls back on trace index if no `uid` is provided. So if your app can add/remove traces before the end of the `data` array, such that the same trace has a different index, you can still preserve user-driven changes if you give each trace a `uid` that stays with it as it moves. visible Determines whether or not this trace is visible. If "legendonly", the trace is not drawn, but can appear as a legend item (provided that the legend itself is visible). x Sets the x coordinates. xaxis Sets a reference between this trace's x coordinates and a 2D cartesian x axis. If "x" (the default value), the x coordinates refer to `layout.xaxis`. If "x2", the x coordinates refer to `layout.xaxis2`, and so on. xbounds Specify `xbounds` in the shape of `[xMin, xMax] to avoid looping through the `xy` typed array. Use it in conjunction with `xy` and `ybounds` for the performance benefits. xboundssrc Sets the source reference on Chart Studio Cloud for xbounds . xsrc Sets the source reference on Chart Studio Cloud for x . xy Faster alternative to specifying `x` and `y` separately. If supplied, it must be a typed `Float32Array` array that represents points such that `xy[i * 2] = x[i]` and `xy[i * 2 + 1] = y[i]` xysrc Sets the source reference on Chart Studio Cloud for xy . y Sets the y coordinates. yaxis Sets a reference between this trace's y coordinates and a 2D cartesian y axis. If "y" (the default value), the y coordinates refer to `layout.yaxis`. If "y2", the y coordinates refer to `layout.yaxis2`, and so on. ybounds Specify `ybounds` in the shape of `[yMin, yMax] to avoid looping through the `xy` typed array. Use it in conjunction with `xy` and `xbounds` for the performance benefits. yboundssrc Sets the source reference on Chart Studio Cloud for ybounds . ysrc Sets the source reference on Chart Studio Cloud for y . row : int or None (default) Subplot row index (starting from 1) for the trace to be added. Only valid if figure was created using `plotly.tools.make_subplots` col : int or None (default) Subplot col index (starting from 1) for the trace to be added. Only valid if figure was created using `plotly.tools.make_subplots` secondary_y: boolean or None (default None) If True, associate this trace with the secondary y-axis of the subplot at the specified row and col. Only valid if all of the following conditions are satisfied: * The figure was created using `plotly.subplots.make_subplots`. * The row and col arguments are not None * The subplot at the specified row and col has type xy (which is the default) and secondary_y True. These properties are specified in the specs argument to make_subplots. See the make_subplots docstring for more info. Returns ------- FigureWidget """ from plotly.graph_objs import Pointcloud new_trace = Pointcloud( customdata=customdata, customdatasrc=customdatasrc, hoverinfo=hoverinfo, hoverinfosrc=hoverinfosrc, hoverlabel=hoverlabel, ids=ids, idssrc=idssrc, indices=indices, indicessrc=indicessrc, legendgroup=legendgroup, marker=marker, meta=meta, metasrc=metasrc, name=name, opacity=opacity, showlegend=showlegend, stream=stream, text=text, textsrc=textsrc, uid=uid, uirevision=uirevision, visible=visible, x=x, xaxis=xaxis, xbounds=xbounds, xboundssrc=xboundssrc, xsrc=xsrc, xy=xy, xysrc=xysrc, y=y, yaxis=yaxis, ybounds=ybounds, yboundssrc=yboundssrc, ysrc=ysrc, **kwargs ) return self.add_trace(new_trace, row=row, col=col, secondary_y=secondary_y) def add_sankey( self, arrangement=None, customdata=None, customdatasrc=None, domain=None, hoverinfo=None, hoverlabel=None, ids=None, idssrc=None, link=None, meta=None, metasrc=None, name=None, node=None, orientation=None, selectedpoints=None, stream=None, textfont=None, uid=None, uirevision=None, valueformat=None, valuesuffix=None, visible=None, row=None, col=None, **kwargs ): """ Add a new Sankey trace Sankey plots for network flow data analysis. The nodes are specified in `nodes` and the links between sources and targets in `links`. The colors are set in `nodes[i].color` and `links[i].color`, otherwise defaults are used. Parameters ---------- arrangement If value is `snap` (the default), the node arrangement is assisted by automatic snapping of elements to preserve space between nodes specified via `nodepad`. If value is `perpendicular`, the nodes can only move along a line perpendicular to the flow. If value is `freeform`, the nodes can freely move on the plane. If value is `fixed`, the nodes are stationary. customdata Assigns extra data each datum. This may be useful when listening to hover, click and selection events. Note that, "scatter" traces also appends customdata items in the markers DOM elements customdatasrc Sets the source reference on Chart Studio Cloud for customdata . domain :class:`plotly.graph_objects.sankey.Domain` instance or dict with compatible properties hoverinfo Determines which trace information appear on hover. If `none` or `skip` are set, no information is displayed upon hovering. But, if `none` is set, click and hover events are still fired. Note that this attribute is superseded by `node.hoverinfo` and `node.hoverinfo` for nodes and links respectively. hoverlabel :class:`plotly.graph_objects.sankey.Hoverlabel` instance or dict with compatible properties ids Assigns id labels to each datum. These ids for object constancy of data points during animation. Should be an array of strings, not numbers or any other type. idssrc Sets the source reference on Chart Studio Cloud for ids . link The links of the Sankey plot. meta Assigns extra meta information associated with this trace that can be used in various text attributes. Attributes such as trace `name`, graph, axis and colorbar `title.text`, annotation `text` `rangeselector`, `updatemenues` and `sliders` `label` text all support `meta`. To access the trace `meta` values in an attribute in the same trace, simply use `%{meta[i]}` where `i` is the index or key of the `meta` item in question. To access trace `meta` in layout attributes, use `%{data[n[.meta[i]}` where `i` is the index or key of the `meta` and `n` is the trace index. metasrc Sets the source reference on Chart Studio Cloud for meta . name Sets the trace name. The trace name appear as the legend item and on hover. node The nodes of the Sankey plot. orientation Sets the orientation of the Sankey diagram. selectedpoints Array containing integer indices of selected points. Has an effect only for traces that support selections. Note that an empty array means an empty selection where the `unselected` are turned on for all points, whereas, any other non-array values means no selection all where the `selected` and `unselected` styles have no effect. stream :class:`plotly.graph_objects.sankey.Stream` instance or dict with compatible properties textfont Sets the font for node labels uid Assign an id to this trace, Use this to provide object constancy between traces during animations and transitions. uirevision Controls persistence of some user-driven changes to the trace: `constraintrange` in `parcoords` traces, as well as some `editable: true` modifications such as `name` and `colorbar.title`. Defaults to `layout.uirevision`. Note that other user-driven trace attribute changes are controlled by `layout` attributes: `trace.visible` is controlled by `layout.legend.uirevision`, `selectedpoints` is controlled by `layout.selectionrevision`, and `colorbar.(x|y)` (accessible with `config: {editable: true}`) is controlled by `layout.editrevision`. Trace changes are tracked by `uid`, which only falls back on trace index if no `uid` is provided. So if your app can add/remove traces before the end of the `data` array, such that the same trace has a different index, you can still preserve user-driven changes if you give each trace a `uid` that stays with it as it moves. valueformat Sets the value formatting rule using d3 formatting mini-language which is similar to those of Python. See https://github.com/d3/d3-3.x-api- reference/blob/master/Formatting.md#d3_format valuesuffix Adds a unit to follow the value in the hover tooltip. Add a space if a separation is necessary from the value. visible Determines whether or not this trace is visible. If "legendonly", the trace is not drawn, but can appear as a legend item (provided that the legend itself is visible). row : int or None (default) Subplot row index (starting from 1) for the trace to be added. Only valid if figure was created using `plotly.tools.make_subplots` col : int or None (default) Subplot col index (starting from 1) for the trace to be added. Only valid if figure was created using `plotly.tools.make_subplots` Returns ------- FigureWidget """ from plotly.graph_objs import Sankey new_trace = Sankey( arrangement=arrangement, customdata=customdata, customdatasrc=customdatasrc, domain=domain, hoverinfo=hoverinfo, hoverlabel=hoverlabel, ids=ids, idssrc=idssrc, link=link, meta=meta, metasrc=metasrc, name=name, node=node, orientation=orientation, selectedpoints=selectedpoints, stream=stream, textfont=textfont, uid=uid, uirevision=uirevision, valueformat=valueformat, valuesuffix=valuesuffix, visible=visible, **kwargs ) return self.add_trace(new_trace, row=row, col=col) def add_scatter( self, cliponaxis=None, connectgaps=None, customdata=None, customdatasrc=None, dx=None, dy=None, error_x=None, error_y=None, fill=None, fillcolor=None, groupnorm=None, hoverinfo=None, hoverinfosrc=None, hoverlabel=None, hoveron=None, hovertemplate=None, hovertemplatesrc=None, hovertext=None, hovertextsrc=None, ids=None, idssrc=None, legendgroup=None, line=None, marker=None, meta=None, metasrc=None, mode=None, name=None, opacity=None, orientation=None, r=None, rsrc=None, selected=None, selectedpoints=None, showlegend=None, stackgaps=None, stackgroup=None, stream=None, t=None, text=None, textfont=None, textposition=None, textpositionsrc=None, textsrc=None, texttemplate=None, texttemplatesrc=None, tsrc=None, uid=None, uirevision=None, unselected=None, visible=None, x=None, x0=None, xaxis=None, xcalendar=None, xperiod=None, xperiod0=None, xperiodalignment=None, xsrc=None, y=None, y0=None, yaxis=None, ycalendar=None, yperiod=None, yperiod0=None, yperiodalignment=None, ysrc=None, row=None, col=None, secondary_y=None, **kwargs ): """ Add a new Scatter trace The scatter trace type encompasses line charts, scatter charts, text charts, and bubble charts. The data visualized as scatter point or lines is set in `x` and `y`. Text (appearing either on the chart or on hover only) is via `text`. Bubble charts are achieved by setting `marker.size` and/or `marker.color` to numerical arrays. Parameters ---------- cliponaxis Determines whether or not markers and text nodes are clipped about the subplot axes. To show markers and text nodes above axis lines and tick labels, make sure to set `xaxis.layer` and `yaxis.layer` to *below traces*. connectgaps Determines whether or not gaps (i.e. {nan} or missing values) in the provided data arrays are connected. customdata Assigns extra data each datum. This may be useful when listening to hover, click and selection events. Note that, "scatter" traces also appends customdata items in the markers DOM elements customdatasrc Sets the source reference on Chart Studio Cloud for customdata . dx Sets the x coordinate step. See `x0` for more info. dy Sets the y coordinate step. See `y0` for more info. error_x :class:`plotly.graph_objects.scatter.ErrorX` instance or dict with compatible properties error_y :class:`plotly.graph_objects.scatter.ErrorY` instance or dict with compatible properties fill Sets the area to fill with a solid color. Defaults to "none" unless this trace is stacked, then it gets "tonexty" ("tonextx") if `orientation` is "v" ("h") Use with `fillcolor` if not "none". "tozerox" and "tozeroy" fill to x=0 and y=0 respectively. "tonextx" and "tonexty" fill between the endpoints of this trace and the endpoints of the trace before it, connecting those endpoints with straight lines (to make a stacked area graph); if there is no trace before it, they behave like "tozerox" and "tozeroy". "toself" connects the endpoints of the trace (or each segment of the trace if it has gaps) into a closed shape. "tonext" fills the space between two traces if one completely encloses the other (eg consecutive contour lines), and behaves like "toself" if there is no trace before it. "tonext" should not be used if one trace does not enclose the other. Traces in a `stackgroup` will only fill to (or be filled to) other traces in the same group. With multiple `stackgroup`s or some traces stacked and some not, if fill-linked traces are not already consecutive, the later ones will be pushed down in the drawing order. fillcolor Sets the fill color. Defaults to a half-transparent variant of the line color, marker color, or marker line color, whichever is available. groupnorm Only relevant when `stackgroup` is used, and only the first `groupnorm` found in the `stackgroup` will be used - including if `visible` is "legendonly" but not if it is `false`. Sets the normalization for the sum of this `stackgroup`. With "fraction", the value of each trace at each location is divided by the sum of all trace values at that location. "percent" is the same but multiplied by 100 to show percentages. If there are multiple subplots, or multiple `stackgroup`s on one subplot, each will be normalized within its own set. hoverinfo Determines which trace information appear on hover. If `none` or `skip` are set, no information is displayed upon hovering. But, if `none` is set, click and hover events are still fired. hoverinfosrc Sets the source reference on Chart Studio Cloud for hoverinfo . hoverlabel :class:`plotly.graph_objects.scatter.Hoverlabel` instance or dict with compatible properties hoveron Do the hover effects highlight individual points (markers or line points) or do they highlight filled regions? If the fill is "toself" or "tonext" and there are no markers or text, then the default is "fills", otherwise it is "points". hovertemplate Template string used for rendering the information that appear on hover box. Note that this will override `hoverinfo`. Variables are inserted using %{variable}, for example "y: %{y}". Numbers are formatted using d3-format's syntax %{variable:d3-format}, for example "Price: %{y:$.2f}". https://github.com/d3/d3-3.x-api- reference/blob/master/Formatting.md#d3_format for details on the formatting syntax. Dates are formatted using d3-time-format's syntax %{variable|d3-time- format}, for example "Day: %{2019-01-01|%A}". https://github.com/d3/d3-time-format#locale_format for details on the date formatting syntax. The variables available in `hovertemplate` are the ones emitted as event data described at this link https://plotly.com/javascript/plotlyjs-events/#event- data. Additionally, every attributes that can be specified per-point (the ones that are `arrayOk: true`) are available. Anything contained in tag `<extra>` is displayed in the secondary box, for example "<extra>{fullData.name}</extra>". To hide the secondary box completely, use an empty tag `<extra></extra>`. hovertemplatesrc Sets the source reference on Chart Studio Cloud for hovertemplate . hovertext Sets hover text elements associated with each (x,y) pair. If a single string, the same string appears over all the data points. If an array of string, the items are mapped in order to the this trace's (x,y) coordinates. To be seen, trace `hoverinfo` must contain a "text" flag. hovertextsrc Sets the source reference on Chart Studio Cloud for hovertext . ids Assigns id labels to each datum. These ids for object constancy of data points during animation. Should be an array of strings, not numbers or any other type. idssrc Sets the source reference on Chart Studio Cloud for ids . legendgroup Sets the legend group for this trace. Traces part of the same legend group hide/show at the same time when toggling legend items. line :class:`plotly.graph_objects.scatter.Line` instance or dict with compatible properties marker :class:`plotly.graph_objects.scatter.Marker` instance or dict with compatible properties meta Assigns extra meta information associated with this trace that can be used in various text attributes. Attributes such as trace `name`, graph, axis and colorbar `title.text`, annotation `text` `rangeselector`, `updatemenues` and `sliders` `label` text all support `meta`. To access the trace `meta` values in an attribute in the same trace, simply use `%{meta[i]}` where `i` is the index or key of the `meta` item in question. To access trace `meta` in layout attributes, use `%{data[n[.meta[i]}` where `i` is the index or key of the `meta` and `n` is the trace index. metasrc Sets the source reference on Chart Studio Cloud for meta . mode Determines the drawing mode for this scatter trace. If the provided `mode` includes "text" then the `text` elements appear at the coordinates. Otherwise, the `text` elements appear on hover. If there are less than 20 points and the trace is not stacked then the default is "lines+markers". Otherwise, "lines". name Sets the trace name. The trace name appear as the legend item and on hover. opacity Sets the opacity of the trace. orientation Only relevant when `stackgroup` is used, and only the first `orientation` found in the `stackgroup` will be used - including if `visible` is "legendonly" but not if it is `false`. Sets the stacking direction. With "v" ("h"), the y (x) values of subsequent traces are added. Also affects the default value of `fill`. r r coordinates in scatter traces are deprecated!Please switch to the "scatterpolar" trace type.Sets the radial coordinatesfor legacy polar chart only. rsrc Sets the source reference on Chart Studio Cloud for r . selected :class:`plotly.graph_objects.scatter.Selected` instance or dict with compatible properties selectedpoints Array containing integer indices of selected points. Has an effect only for traces that support selections. Note that an empty array means an empty selection where the `unselected` are turned on for all points, whereas, any other non-array values means no selection all where the `selected` and `unselected` styles have no effect. showlegend Determines whether or not an item corresponding to this trace is shown in the legend. stackgaps Only relevant when `stackgroup` is used, and only the first `stackgaps` found in the `stackgroup` will be used - including if `visible` is "legendonly" but not if it is `false`. Determines how we handle locations at which other traces in this group have data but this one does not. With *infer zero* we insert a zero at these locations. With "interpolate" we linearly interpolate between existing values, and extrapolate a constant beyond the existing values. stackgroup Set several scatter traces (on the same subplot) to the same stackgroup in order to add their y values (or their x values if `orientation` is "h"). If blank or omitted this trace will not be stacked. Stacking also turns `fill` on by default, using "tonexty" ("tonextx") if `orientation` is "h" ("v") and sets the default `mode` to "lines" irrespective of point count. You can only stack on a numeric (linear or log) axis. Traces in a `stackgroup` will only fill to (or be filled to) other traces in the same group. With multiple `stackgroup`s or some traces stacked and some not, if fill-linked traces are not already consecutive, the later ones will be pushed down in the drawing order. stream :class:`plotly.graph_objects.scatter.Stream` instance or dict with compatible properties t t coordinates in scatter traces are deprecated!Please switch to the "scatterpolar" trace type.Sets the angular coordinatesfor legacy polar chart only. text Sets text elements associated with each (x,y) pair. If a single string, the same string appears over all the data points. If an array of string, the items are mapped in order to the this trace's (x,y) coordinates. If trace `hoverinfo` contains a "text" flag and "hovertext" is not set, these elements will be seen in the hover labels. textfont Sets the text font. textposition Sets the positions of the `text` elements with respects to the (x,y) coordinates. textpositionsrc Sets the source reference on Chart Studio Cloud for textposition . textsrc Sets the source reference on Chart Studio Cloud for text . texttemplate Template string used for rendering the information text that appear on points. Note that this will override `textinfo`. Variables are inserted using %{variable}, for example "y: %{y}". Numbers are formatted using d3-format's syntax %{variable:d3-format}, for example "Price: %{y:$.2f}". https://github.com/d3/d3-3.x-api- reference/blob/master/Formatting.md#d3_format for details on the formatting syntax. Dates are formatted using d3-time-format's syntax %{variable|d3-time- format}, for example "Day: %{2019-01-01|%A}". https://github.com/d3/d3-time-format#locale_format for details on the date formatting syntax. Every attributes that can be specified per-point (the ones that are `arrayOk: true`) are available. texttemplatesrc Sets the source reference on Chart Studio Cloud for texttemplate . tsrc Sets the source reference on Chart Studio Cloud for t . uid Assign an id to this trace, Use this to provide object constancy between traces during animations and transitions. uirevision Controls persistence of some user-driven changes to the trace: `constraintrange` in `parcoords` traces, as well as some `editable: true` modifications such as `name` and `colorbar.title`. Defaults to `layout.uirevision`. Note that other user-driven trace attribute changes are controlled by `layout` attributes: `trace.visible` is controlled by `layout.legend.uirevision`, `selectedpoints` is controlled by `layout.selectionrevision`, and `colorbar.(x|y)` (accessible with `config: {editable: true}`) is controlled by `layout.editrevision`. Trace changes are tracked by `uid`, which only falls back on trace index if no `uid` is provided. So if your app can add/remove traces before the end of the `data` array, such that the same trace has a different index, you can still preserve user-driven changes if you give each trace a `uid` that stays with it as it moves. unselected :class:`plotly.graph_objects.scatter.Unselected` instance or dict with compatible properties visible Determines whether or not this trace is visible. If "legendonly", the trace is not drawn, but can appear as a legend item (provided that the legend itself is visible). x Sets the x coordinates. x0 Alternate to `x`. Builds a linear space of x coordinates. Use with `dx` where `x0` is the starting coordinate and `dx` the step. xaxis Sets a reference between this trace's x coordinates and a 2D cartesian x axis. If "x" (the default value), the x coordinates refer to `layout.xaxis`. If "x2", the x coordinates refer to `layout.xaxis2`, and so on. xcalendar Sets the calendar system to use with `x` date data. xperiod Only relevant when the axis `type` is "date". Sets the period positioning in milliseconds or "M<n>" on the x axis. Special values in the form of "M<n>" could be used to declare the number of months. In this case `n` must be a positive integer. xperiod0 Only relevant when the axis `type` is "date". Sets the base for period positioning in milliseconds or date string on the x0 axis. When `x0period` is round number of weeks, the `x0period0` by default would be on a Sunday i.e. 2000-01-02, otherwise it would be at 2000-01-01. xperiodalignment Only relevant when the axis `type` is "date". Sets the alignment of data points on the x axis. xsrc Sets the source reference on Chart Studio Cloud for x . y Sets the y coordinates. y0 Alternate to `y`. Builds a linear space of y coordinates. Use with `dy` where `y0` is the starting coordinate and `dy` the step. yaxis Sets a reference between this trace's y coordinates and a 2D cartesian y axis. If "y" (the default value), the y coordinates refer to `layout.yaxis`. If "y2", the y coordinates refer to `layout.yaxis2`, and so on. ycalendar Sets the calendar system to use with `y` date data. yperiod Only relevant when the axis `type` is "date". Sets the period positioning in milliseconds or "M<n>" on the y axis. Special values in the form of "M<n>" could be used to declare the number of months. In this case `n` must be a positive integer. yperiod0 Only relevant when the axis `type` is "date". Sets the base for period positioning in milliseconds or date string on the y0 axis. When `y0period` is round number of weeks, the `y0period0` by default would be on a Sunday i.e. 2000-01-02, otherwise it would be at 2000-01-01. yperiodalignment Only relevant when the axis `type` is "date". Sets the alignment of data points on the y axis. ysrc Sets the source reference on Chart Studio Cloud for y . row : int or None (default) Subplot row index (starting from 1) for the trace to be added. Only valid if figure was created using `plotly.tools.make_subplots` col : int or None (default) Subplot col index (starting from 1) for the trace to be added. Only valid if figure was created using `plotly.tools.make_subplots` secondary_y: boolean or None (default None) If True, associate this trace with the secondary y-axis of the subplot at the specified row and col. Only valid if all of the following conditions are satisfied: * The figure was created using `plotly.subplots.make_subplots`. * The row and col arguments are not None * The subplot at the specified row and col has type xy (which is the default) and secondary_y True. These properties are specified in the specs argument to make_subplots. See the make_subplots docstring for more info. Returns ------- FigureWidget """ from plotly.graph_objs import Scatter new_trace = Scatter( cliponaxis=cliponaxis, connectgaps=connectgaps, customdata=customdata, customdatasrc=customdatasrc, dx=dx, dy=dy, error_x=error_x, error_y=error_y, fill=fill, fillcolor=fillcolor, groupnorm=groupnorm, hoverinfo=hoverinfo, hoverinfosrc=hoverinfosrc, hoverlabel=hoverlabel, hoveron=hoveron, hovertemplate=hovertemplate, hovertemplatesrc=hovertemplatesrc, hovertext=hovertext, hovertextsrc=hovertextsrc, ids=ids, idssrc=idssrc, legendgroup=legendgroup, line=line, marker=marker, meta=meta, metasrc=metasrc, mode=mode, name=name, opacity=opacity, orientation=orientation, r=r, rsrc=rsrc, selected=selected, selectedpoints=selectedpoints, showlegend=showlegend, stackgaps=stackgaps, stackgroup=stackgroup, stream=stream, t=t, text=text, textfont=textfont, textposition=textposition, textpositionsrc=textpositionsrc, textsrc=textsrc, texttemplate=texttemplate, texttemplatesrc=texttemplatesrc, tsrc=tsrc, uid=uid, uirevision=uirevision, unselected=unselected, visible=visible, x=x, x0=x0, xaxis=xaxis, xcalendar=xcalendar, xperiod=xperiod, xperiod0=xperiod0, xperiodalignment=xperiodalignment, xsrc=xsrc, y=y, y0=y0, yaxis=yaxis, ycalendar=ycalendar, yperiod=yperiod, yperiod0=yperiod0, yperiodalignment=yperiodalignment, ysrc=ysrc, **kwargs ) return self.add_trace(new_trace, row=row, col=col, secondary_y=secondary_y) def add_scatter3d( self, connectgaps=None, customdata=None, customdatasrc=None, error_x=None, error_y=None, error_z=None, hoverinfo=None, hoverinfosrc=None, hoverlabel=None, hovertemplate=None, hovertemplatesrc=None, hovertext=None, hovertextsrc=None, ids=None, idssrc=None, legendgroup=None, line=None, marker=None, meta=None, metasrc=None, mode=None, name=None, opacity=None, projection=None, scene=None, showlegend=None, stream=None, surfaceaxis=None, surfacecolor=None, text=None, textfont=None, textposition=None, textpositionsrc=None, textsrc=None, texttemplate=None, texttemplatesrc=None, uid=None, uirevision=None, visible=None, x=None, xcalendar=None, xsrc=None, y=None, ycalendar=None, ysrc=None, z=None, zcalendar=None, zsrc=None, row=None, col=None, **kwargs ): """ Add a new Scatter3d trace The data visualized as scatter point or lines in 3D dimension is set in `x`, `y`, `z`. Text (appearing either on the chart or on hover only) is via `text`. Bubble charts are achieved by setting `marker.size` and/or `marker.color` Projections are achieved via `projection`. Surface fills are achieved via `surfaceaxis`. Parameters ---------- connectgaps Determines whether or not gaps (i.e. {nan} or missing values) in the provided data arrays are connected. customdata Assigns extra data each datum. This may be useful when listening to hover, click and selection events. Note that, "scatter" traces also appends customdata items in the markers DOM elements customdatasrc Sets the source reference on Chart Studio Cloud for customdata . error_x :class:`plotly.graph_objects.scatter3d.ErrorX` instance or dict with compatible properties error_y :class:`plotly.graph_objects.scatter3d.ErrorY` instance or dict with compatible properties error_z :class:`plotly.graph_objects.scatter3d.ErrorZ` instance or dict with compatible properties hoverinfo Determines which trace information appear on hover. If `none` or `skip` are set, no information is displayed upon hovering. But, if `none` is set, click and hover events are still fired. hoverinfosrc Sets the source reference on Chart Studio Cloud for hoverinfo . hoverlabel :class:`plotly.graph_objects.scatter3d.Hoverlabel` instance or dict with compatible properties hovertemplate Template string used for rendering the information that appear on hover box. Note that this will override `hoverinfo`. Variables are inserted using %{variable}, for example "y: %{y}". Numbers are formatted using d3-format's syntax %{variable:d3-format}, for example "Price: %{y:$.2f}". https://github.com/d3/d3-3.x-api- reference/blob/master/Formatting.md#d3_format for details on the formatting syntax. Dates are formatted using d3-time-format's syntax %{variable|d3-time- format}, for example "Day: %{2019-01-01|%A}". https://github.com/d3/d3-time-format#locale_format for details on the date formatting syntax. The variables available in `hovertemplate` are the ones emitted as event data described at this link https://plotly.com/javascript/plotlyjs-events/#event- data. Additionally, every attributes that can be specified per-point (the ones that are `arrayOk: true`) are available. Anything contained in tag `<extra>` is displayed in the secondary box, for example "<extra>{fullData.name}</extra>". To hide the secondary box completely, use an empty tag `<extra></extra>`. hovertemplatesrc Sets the source reference on Chart Studio Cloud for hovertemplate . hovertext Sets text elements associated with each (x,y,z) triplet. If a single string, the same string appears over all the data points. If an array of string, the items are mapped in order to the this trace's (x,y,z) coordinates. To be seen, trace `hoverinfo` must contain a "text" flag. hovertextsrc Sets the source reference on Chart Studio Cloud for hovertext . ids Assigns id labels to each datum. These ids for object constancy of data points during animation. Should be an array of strings, not numbers or any other type. idssrc Sets the source reference on Chart Studio Cloud for ids . legendgroup Sets the legend group for this trace. Traces part of the same legend group hide/show at the same time when toggling legend items. line :class:`plotly.graph_objects.scatter3d.Line` instance or dict with compatible properties marker :class:`plotly.graph_objects.scatter3d.Marker` instance or dict with compatible properties meta Assigns extra meta information associated with this trace that can be used in various text attributes. Attributes such as trace `name`, graph, axis and colorbar `title.text`, annotation `text` `rangeselector`, `updatemenues` and `sliders` `label` text all support `meta`. To access the trace `meta` values in an attribute in the same trace, simply use `%{meta[i]}` where `i` is the index or key of the `meta` item in question. To access trace `meta` in layout attributes, use `%{data[n[.meta[i]}` where `i` is the index or key of the `meta` and `n` is the trace index. metasrc Sets the source reference on Chart Studio Cloud for meta . mode Determines the drawing mode for this scatter trace. If the provided `mode` includes "text" then the `text` elements appear at the coordinates. Otherwise, the `text` elements appear on hover. If there are less than 20 points and the trace is not stacked then the default is "lines+markers". Otherwise, "lines". name Sets the trace name. The trace name appear as the legend item and on hover. opacity Sets the opacity of the trace. projection :class:`plotly.graph_objects.scatter3d.Projection` instance or dict with compatible properties scene Sets a reference between this trace's 3D coordinate system and a 3D scene. If "scene" (the default value), the (x,y,z) coordinates refer to `layout.scene`. If "scene2", the (x,y,z) coordinates refer to `layout.scene2`, and so on. showlegend Determines whether or not an item corresponding to this trace is shown in the legend. stream :class:`plotly.graph_objects.scatter3d.Stream` instance or dict with compatible properties surfaceaxis If "-1", the scatter points are not fill with a surface If 0, 1, 2, the scatter points are filled with a Delaunay surface about the x, y, z respectively. surfacecolor Sets the surface fill color. text Sets text elements associated with each (x,y,z) triplet. If a single string, the same string appears over all the data points. If an array of string, the items are mapped in order to the this trace's (x,y,z) coordinates. If trace `hoverinfo` contains a "text" flag and "hovertext" is not set, these elements will be seen in the hover labels. textfont :class:`plotly.graph_objects.scatter3d.Textfont` instance or dict with compatible properties textposition Sets the positions of the `text` elements with respects to the (x,y) coordinates. textpositionsrc Sets the source reference on Chart Studio Cloud for textposition . textsrc Sets the source reference on Chart Studio Cloud for text . texttemplate Template string used for rendering the information text that appear on points. Note that this will override `textinfo`. Variables are inserted using %{variable}, for example "y: %{y}". Numbers are formatted using d3-format's syntax %{variable:d3-format}, for example "Price: %{y:$.2f}". https://github.com/d3/d3-3.x-api- reference/blob/master/Formatting.md#d3_format for details on the formatting syntax. Dates are formatted using d3-time-format's syntax %{variable|d3-time- format}, for example "Day: %{2019-01-01|%A}". https://github.com/d3/d3-time-format#locale_format for details on the date formatting syntax. Every attributes that can be specified per-point (the ones that are `arrayOk: true`) are available. texttemplatesrc Sets the source reference on Chart Studio Cloud for texttemplate . uid Assign an id to this trace, Use this to provide object constancy between traces during animations and transitions. uirevision Controls persistence of some user-driven changes to the trace: `constraintrange` in `parcoords` traces, as well as some `editable: true` modifications such as `name` and `colorbar.title`. Defaults to `layout.uirevision`. Note that other user-driven trace attribute changes are controlled by `layout` attributes: `trace.visible` is controlled by `layout.legend.uirevision`, `selectedpoints` is controlled by `layout.selectionrevision`, and `colorbar.(x|y)` (accessible with `config: {editable: true}`) is controlled by `layout.editrevision`. Trace changes are tracked by `uid`, which only falls back on trace index if no `uid` is provided. So if your app can add/remove traces before the end of the `data` array, such that the same trace has a different index, you can still preserve user-driven changes if you give each trace a `uid` that stays with it as it moves. visible Determines whether or not this trace is visible. If "legendonly", the trace is not drawn, but can appear as a legend item (provided that the legend itself is visible). x Sets the x coordinates. xcalendar Sets the calendar system to use with `x` date data. xsrc Sets the source reference on Chart Studio Cloud for x . y Sets the y coordinates. ycalendar Sets the calendar system to use with `y` date data. ysrc Sets the source reference on Chart Studio Cloud for y . z Sets the z coordinates. zcalendar Sets the calendar system to use with `z` date data. zsrc Sets the source reference on Chart Studio Cloud for z . row : int or None (default) Subplot row index (starting from 1) for the trace to be added. Only valid if figure was created using `plotly.tools.make_subplots` col : int or None (default) Subplot col index (starting from 1) for the trace to be added. Only valid if figure was created using `plotly.tools.make_subplots` Returns ------- FigureWidget """ from plotly.graph_objs import Scatter3d new_trace = Scatter3d( connectgaps=connectgaps, customdata=customdata, customdatasrc=customdatasrc, error_x=error_x, error_y=error_y, error_z=error_z, hoverinfo=hoverinfo, hoverinfosrc=hoverinfosrc, hoverlabel=hoverlabel, hovertemplate=hovertemplate, hovertemplatesrc=hovertemplatesrc, hovertext=hovertext, hovertextsrc=hovertextsrc, ids=ids, idssrc=idssrc, legendgroup=legendgroup, line=line, marker=marker, meta=meta, metasrc=metasrc, mode=mode, name=name, opacity=opacity, projection=projection, scene=scene, showlegend=showlegend, stream=stream, surfaceaxis=surfaceaxis, surfacecolor=surfacecolor, text=text, textfont=textfont, textposition=textposition, textpositionsrc=textpositionsrc, textsrc=textsrc, texttemplate=texttemplate, texttemplatesrc=texttemplatesrc, uid=uid, uirevision=uirevision, visible=visible, x=x, xcalendar=xcalendar, xsrc=xsrc, y=y, ycalendar=ycalendar, ysrc=ysrc, z=z, zcalendar=zcalendar, zsrc=zsrc, **kwargs ) return self.add_trace(new_trace, row=row, col=col) def add_scattercarpet( self, a=None, asrc=None, b=None, bsrc=None, carpet=None, connectgaps=None, customdata=None, customdatasrc=None, fill=None, fillcolor=None, hoverinfo=None, hoverinfosrc=None, hoverlabel=None, hoveron=None, hovertemplate=None, hovertemplatesrc=None, hovertext=None, hovertextsrc=None, ids=None, idssrc=None, legendgroup=None, line=None, marker=None, meta=None, metasrc=None, mode=None, name=None, opacity=None, selected=None, selectedpoints=None, showlegend=None, stream=None, text=None, textfont=None, textposition=None, textpositionsrc=None, textsrc=None, texttemplate=None, texttemplatesrc=None, uid=None, uirevision=None, unselected=None, visible=None, xaxis=None, yaxis=None, row=None, col=None, secondary_y=None, **kwargs ): """ Add a new Scattercarpet trace Plots a scatter trace on either the first carpet axis or the carpet axis with a matching `carpet` attribute. Parameters ---------- a Sets the a-axis coordinates. asrc Sets the source reference on Chart Studio Cloud for a . b Sets the b-axis coordinates. bsrc Sets the source reference on Chart Studio Cloud for b . carpet An identifier for this carpet, so that `scattercarpet` and `contourcarpet` traces can specify a carpet plot on which they lie connectgaps Determines whether or not gaps (i.e. {nan} or missing values) in the provided data arrays are connected. customdata Assigns extra data each datum. This may be useful when listening to hover, click and selection events. Note that, "scatter" traces also appends customdata items in the markers DOM elements customdatasrc Sets the source reference on Chart Studio Cloud for customdata . fill Sets the area to fill with a solid color. Use with `fillcolor` if not "none". scatterternary has a subset of the options available to scatter. "toself" connects the endpoints of the trace (or each segment of the trace if it has gaps) into a closed shape. "tonext" fills the space between two traces if one completely encloses the other (eg consecutive contour lines), and behaves like "toself" if there is no trace before it. "tonext" should not be used if one trace does not enclose the other. fillcolor Sets the fill color. Defaults to a half-transparent variant of the line color, marker color, or marker line color, whichever is available. hoverinfo Determines which trace information appear on hover. If `none` or `skip` are set, no information is displayed upon hovering. But, if `none` is set, click and hover events are still fired. hoverinfosrc Sets the source reference on Chart Studio Cloud for hoverinfo . hoverlabel :class:`plotly.graph_objects.scattercarpet.Hoverlabel` instance or dict with compatible properties hoveron Do the hover effects highlight individual points (markers or line points) or do they highlight filled regions? If the fill is "toself" or "tonext" and there are no markers or text, then the default is "fills", otherwise it is "points". hovertemplate Template string used for rendering the information that appear on hover box. Note that this will override `hoverinfo`. Variables are inserted using %{variable}, for example "y: %{y}". Numbers are formatted using d3-format's syntax %{variable:d3-format}, for example "Price: %{y:$.2f}". https://github.com/d3/d3-3.x-api- reference/blob/master/Formatting.md#d3_format for details on the formatting syntax. Dates are formatted using d3-time-format's syntax %{variable|d3-time- format}, for example "Day: %{2019-01-01|%A}". https://github.com/d3/d3-time-format#locale_format for details on the date formatting syntax. The variables available in `hovertemplate` are the ones emitted as event data described at this link https://plotly.com/javascript/plotlyjs-events/#event- data. Additionally, every attributes that can be specified per-point (the ones that are `arrayOk: true`) are available. Anything contained in tag `<extra>` is displayed in the secondary box, for example "<extra>{fullData.name}</extra>". To hide the secondary box completely, use an empty tag `<extra></extra>`. hovertemplatesrc Sets the source reference on Chart Studio Cloud for hovertemplate . hovertext Sets hover text elements associated with each (a,b) point. If a single string, the same string appears over all the data points. If an array of strings, the items are mapped in order to the the data points in (a,b). To be seen, trace `hoverinfo` must contain a "text" flag. hovertextsrc Sets the source reference on Chart Studio Cloud for hovertext . ids Assigns id labels to each datum. These ids for object constancy of data points during animation. Should be an array of strings, not numbers or any other type. idssrc Sets the source reference on Chart Studio Cloud for ids . legendgroup Sets the legend group for this trace. Traces part of the same legend group hide/show at the same time when toggling legend items. line :class:`plotly.graph_objects.scattercarpet.Line` instance or dict with compatible properties marker :class:`plotly.graph_objects.scattercarpet.Marker` instance or dict with compatible properties meta Assigns extra meta information associated with this trace that can be used in various text attributes. Attributes such as trace `name`, graph, axis and colorbar `title.text`, annotation `text` `rangeselector`, `updatemenues` and `sliders` `label` text all support `meta`. To access the trace `meta` values in an attribute in the same trace, simply use `%{meta[i]}` where `i` is the index or key of the `meta` item in question. To access trace `meta` in layout attributes, use `%{data[n[.meta[i]}` where `i` is the index or key of the `meta` and `n` is the trace index. metasrc Sets the source reference on Chart Studio Cloud for meta . mode Determines the drawing mode for this scatter trace. If the provided `mode` includes "text" then the `text` elements appear at the coordinates. Otherwise, the `text` elements appear on hover. If there are less than 20 points and the trace is not stacked then the default is "lines+markers". Otherwise, "lines". name Sets the trace name. The trace name appear as the legend item and on hover. opacity Sets the opacity of the trace. selected :class:`plotly.graph_objects.scattercarpet.Selected` instance or dict with compatible properties selectedpoints Array containing integer indices of selected points. Has an effect only for traces that support selections. Note that an empty array means an empty selection where the `unselected` are turned on for all points, whereas, any other non-array values means no selection all where the `selected` and `unselected` styles have no effect. showlegend Determines whether or not an item corresponding to this trace is shown in the legend. stream :class:`plotly.graph_objects.scattercarpet.Stream` instance or dict with compatible properties text Sets text elements associated with each (a,b) point. If a single string, the same string appears over all the data points. If an array of strings, the items are mapped in order to the the data points in (a,b). If trace `hoverinfo` contains a "text" flag and "hovertext" is not set, these elements will be seen in the hover labels. textfont Sets the text font. textposition Sets the positions of the `text` elements with respects to the (x,y) coordinates. textpositionsrc Sets the source reference on Chart Studio Cloud for textposition . textsrc Sets the source reference on Chart Studio Cloud for text . texttemplate Template string used for rendering the information text that appear on points. Note that this will override `textinfo`. Variables are inserted using %{variable}, for example "y: %{y}". Numbers are formatted using d3-format's syntax %{variable:d3-format}, for example "Price: %{y:$.2f}". https://github.com/d3/d3-3.x-api- reference/blob/master/Formatting.md#d3_format for details on the formatting syntax. Dates are formatted using d3-time-format's syntax %{variable|d3-time- format}, for example "Day: %{2019-01-01|%A}". https://github.com/d3/d3-time-format#locale_format for details on the date formatting syntax. Every attributes that can be specified per-point (the ones that are `arrayOk: true`) are available. variables `a`, `b` and `text`. texttemplatesrc Sets the source reference on Chart Studio Cloud for texttemplate . uid Assign an id to this trace, Use this to provide object constancy between traces during animations and transitions. uirevision Controls persistence of some user-driven changes to the trace: `constraintrange` in `parcoords` traces, as well as some `editable: true` modifications such as `name` and `colorbar.title`. Defaults to `layout.uirevision`. Note that other user-driven trace attribute changes are controlled by `layout` attributes: `trace.visible` is controlled by `layout.legend.uirevision`, `selectedpoints` is controlled by `layout.selectionrevision`, and `colorbar.(x|y)` (accessible with `config: {editable: true}`) is controlled by `layout.editrevision`. Trace changes are tracked by `uid`, which only falls back on trace index if no `uid` is provided. So if your app can add/remove traces before the end of the `data` array, such that the same trace has a different index, you can still preserve user-driven changes if you give each trace a `uid` that stays with it as it moves. unselected :class:`plotly.graph_objects.scattercarpet.Unselected` instance or dict with compatible properties visible Determines whether or not this trace is visible. If "legendonly", the trace is not drawn, but can appear as a legend item (provided that the legend itself is visible). xaxis Sets a reference between this trace's x coordinates and a 2D cartesian x axis. If "x" (the default value), the x coordinates refer to `layout.xaxis`. If "x2", the x coordinates refer to `layout.xaxis2`, and so on. yaxis Sets a reference between this trace's y coordinates and a 2D cartesian y axis. If "y" (the default value), the y coordinates refer to `layout.yaxis`. If "y2", the y coordinates refer to `layout.yaxis2`, and so on. row : int or None (default) Subplot row index (starting from 1) for the trace to be added. Only valid if figure was created using `plotly.tools.make_subplots` col : int or None (default) Subplot col index (starting from 1) for the trace to be added. Only valid if figure was created using `plotly.tools.make_subplots` secondary_y: boolean or None (default None) If True, associate this trace with the secondary y-axis of the subplot at the specified row and col. Only valid if all of the following conditions are satisfied: * The figure was created using `plotly.subplots.make_subplots`. * The row and col arguments are not None * The subplot at the specified row and col has type xy (which is the default) and secondary_y True. These properties are specified in the specs argument to make_subplots. See the make_subplots docstring for more info. Returns ------- FigureWidget """ from plotly.graph_objs import Scattercarpet new_trace = Scattercarpet( a=a, asrc=asrc, b=b, bsrc=bsrc, carpet=carpet, connectgaps=connectgaps, customdata=customdata, customdatasrc=customdatasrc, fill=fill, fillcolor=fillcolor, hoverinfo=hoverinfo, hoverinfosrc=hoverinfosrc, hoverlabel=hoverlabel, hoveron=hoveron, hovertemplate=hovertemplate, hovertemplatesrc=hovertemplatesrc, hovertext=hovertext, hovertextsrc=hovertextsrc, ids=ids, idssrc=idssrc, legendgroup=legendgroup, line=line, marker=marker, meta=meta, metasrc=metasrc, mode=mode, name=name, opacity=opacity, selected=selected, selectedpoints=selectedpoints, showlegend=showlegend, stream=stream, text=text, textfont=textfont, textposition=textposition, textpositionsrc=textpositionsrc, textsrc=textsrc, texttemplate=texttemplate, texttemplatesrc=texttemplatesrc, uid=uid, uirevision=uirevision, unselected=unselected, visible=visible, xaxis=xaxis, yaxis=yaxis, **kwargs ) return self.add_trace(new_trace, row=row, col=col, secondary_y=secondary_y) def add_scattergeo( self, connectgaps=None, customdata=None, customdatasrc=None, featureidkey=None, fill=None, fillcolor=None, geo=None, geojson=None, hoverinfo=None, hoverinfosrc=None, hoverlabel=None, hovertemplate=None, hovertemplatesrc=None, hovertext=None, hovertextsrc=None, ids=None, idssrc=None, lat=None, latsrc=None, legendgroup=None, line=None, locationmode=None, locations=None, locationssrc=None, lon=None, lonsrc=None, marker=None, meta=None, metasrc=None, mode=None, name=None, opacity=None, selected=None, selectedpoints=None, showlegend=None, stream=None, text=None, textfont=None, textposition=None, textpositionsrc=None, textsrc=None, texttemplate=None, texttemplatesrc=None, uid=None, uirevision=None, unselected=None, visible=None, row=None, col=None, **kwargs ): """ Add a new Scattergeo trace The data visualized as scatter point or lines on a geographic map is provided either by longitude/latitude pairs in `lon` and `lat` respectively or by geographic location IDs or names in `locations`. Parameters ---------- connectgaps Determines whether or not gaps (i.e. {nan} or missing values) in the provided data arrays are connected. customdata Assigns extra data each datum. This may be useful when listening to hover, click and selection events. Note that, "scatter" traces also appends customdata items in the markers DOM elements customdatasrc Sets the source reference on Chart Studio Cloud for customdata . featureidkey Sets the key in GeoJSON features which is used as id to match the items included in the `locations` array. Only has an effect when `geojson` is set. Support nested property, for example "properties.name". fill Sets the area to fill with a solid color. Use with `fillcolor` if not "none". "toself" connects the endpoints of the trace (or each segment of the trace if it has gaps) into a closed shape. fillcolor Sets the fill color. Defaults to a half-transparent variant of the line color, marker color, or marker line color, whichever is available. geo Sets a reference between this trace's geospatial coordinates and a geographic map. If "geo" (the default value), the geospatial coordinates refer to `layout.geo`. If "geo2", the geospatial coordinates refer to `layout.geo2`, and so on. geojson Sets optional GeoJSON data associated with this trace. If not given, the features on the base map are used when `locations` is set. It can be set as a valid GeoJSON object or as a URL string. Note that we only accept GeoJSONs of type "FeatureCollection" or "Feature" with geometries of type "Polygon" or "MultiPolygon". hoverinfo Determines which trace information appear on hover. If `none` or `skip` are set, no information is displayed upon hovering. But, if `none` is set, click and hover events are still fired. hoverinfosrc Sets the source reference on Chart Studio Cloud for hoverinfo . hoverlabel :class:`plotly.graph_objects.scattergeo.Hoverlabel` instance or dict with compatible properties hovertemplate Template string used for rendering the information that appear on hover box. Note that this will override `hoverinfo`. Variables are inserted using %{variable}, for example "y: %{y}". Numbers are formatted using d3-format's syntax %{variable:d3-format}, for example "Price: %{y:$.2f}". https://github.com/d3/d3-3.x-api- reference/blob/master/Formatting.md#d3_format for details on the formatting syntax. Dates are formatted using d3-time-format's syntax %{variable|d3-time- format}, for example "Day: %{2019-01-01|%A}". https://github.com/d3/d3-time-format#locale_format for details on the date formatting syntax. The variables available in `hovertemplate` are the ones emitted as event data described at this link https://plotly.com/javascript/plotlyjs-events/#event- data. Additionally, every attributes that can be specified per-point (the ones that are `arrayOk: true`) are available. Anything contained in tag `<extra>` is displayed in the secondary box, for example "<extra>{fullData.name}</extra>". To hide the secondary box completely, use an empty tag `<extra></extra>`. hovertemplatesrc Sets the source reference on Chart Studio Cloud for hovertemplate . hovertext Sets hover text elements associated with each (lon,lat) pair or item in `locations`. If a single string, the same string appears over all the data points. If an array of string, the items are mapped in order to the this trace's (lon,lat) or `locations` coordinates. To be seen, trace `hoverinfo` must contain a "text" flag. hovertextsrc Sets the source reference on Chart Studio Cloud for hovertext . ids Assigns id labels to each datum. These ids for object constancy of data points during animation. Should be an array of strings, not numbers or any other type. idssrc Sets the source reference on Chart Studio Cloud for ids . lat Sets the latitude coordinates (in degrees North). latsrc Sets the source reference on Chart Studio Cloud for lat . legendgroup Sets the legend group for this trace. Traces part of the same legend group hide/show at the same time when toggling legend items. line :class:`plotly.graph_objects.scattergeo.Line` instance or dict with compatible properties locationmode Determines the set of locations used to match entries in `locations` to regions on the map. Values "ISO-3", "USA-states", *country names* correspond to features on the base map and value "geojson-id" corresponds to features from a custom GeoJSON linked to the `geojson` attribute. locations Sets the coordinates via location IDs or names. Coordinates correspond to the centroid of each location given. See `locationmode` for more info. locationssrc Sets the source reference on Chart Studio Cloud for locations . lon Sets the longitude coordinates (in degrees East). lonsrc Sets the source reference on Chart Studio Cloud for lon . marker :class:`plotly.graph_objects.scattergeo.Marker` instance or dict with compatible properties meta Assigns extra meta information associated with this trace that can be used in various text attributes. Attributes such as trace `name`, graph, axis and colorbar `title.text`, annotation `text` `rangeselector`, `updatemenues` and `sliders` `label` text all support `meta`. To access the trace `meta` values in an attribute in the same trace, simply use `%{meta[i]}` where `i` is the index or key of the `meta` item in question. To access trace `meta` in layout attributes, use `%{data[n[.meta[i]}` where `i` is the index or key of the `meta` and `n` is the trace index. metasrc Sets the source reference on Chart Studio Cloud for meta . mode Determines the drawing mode for this scatter trace. If the provided `mode` includes "text" then the `text` elements appear at the coordinates. Otherwise, the `text` elements appear on hover. If there are less than 20 points and the trace is not stacked then the default is "lines+markers". Otherwise, "lines". name Sets the trace name. The trace name appear as the legend item and on hover. opacity Sets the opacity of the trace. selected :class:`plotly.graph_objects.scattergeo.Selected` instance or dict with compatible properties selectedpoints Array containing integer indices of selected points. Has an effect only for traces that support selections. Note that an empty array means an empty selection where the `unselected` are turned on for all points, whereas, any other non-array values means no selection all where the `selected` and `unselected` styles have no effect. showlegend Determines whether or not an item corresponding to this trace is shown in the legend. stream :class:`plotly.graph_objects.scattergeo.Stream` instance or dict with compatible properties text Sets text elements associated with each (lon,lat) pair or item in `locations`. If a single string, the same string appears over all the data points. If an array of string, the items are mapped in order to the this trace's (lon,lat) or `locations` coordinates. If trace `hoverinfo` contains a "text" flag and "hovertext" is not set, these elements will be seen in the hover labels. textfont Sets the text font. textposition Sets the positions of the `text` elements with respects to the (x,y) coordinates. textpositionsrc Sets the source reference on Chart Studio Cloud for textposition . textsrc Sets the source reference on Chart Studio Cloud for text . texttemplate Template string used for rendering the information text that appear on points. Note that this will override `textinfo`. Variables are inserted using %{variable}, for example "y: %{y}". Numbers are formatted using d3-format's syntax %{variable:d3-format}, for example "Price: %{y:$.2f}". https://github.com/d3/d3-3.x-api- reference/blob/master/Formatting.md#d3_format for details on the formatting syntax. Dates are formatted using d3-time-format's syntax %{variable|d3-time- format}, for example "Day: %{2019-01-01|%A}". https://github.com/d3/d3-time-format#locale_format for details on the date formatting syntax. Every attributes that can be specified per-point (the ones that are `arrayOk: true`) are available. variables `lat`, `lon`, `location` and `text`. texttemplatesrc Sets the source reference on Chart Studio Cloud for texttemplate . uid Assign an id to this trace, Use this to provide object constancy between traces during animations and transitions. uirevision Controls persistence of some user-driven changes to the trace: `constraintrange` in `parcoords` traces, as well as some `editable: true` modifications such as `name` and `colorbar.title`. Defaults to `layout.uirevision`. Note that other user-driven trace attribute changes are controlled by `layout` attributes: `trace.visible` is controlled by `layout.legend.uirevision`, `selectedpoints` is controlled by `layout.selectionrevision`, and `colorbar.(x|y)` (accessible with `config: {editable: true}`) is controlled by `layout.editrevision`. Trace changes are tracked by `uid`, which only falls back on trace index if no `uid` is provided. So if your app can add/remove traces before the end of the `data` array, such that the same trace has a different index, you can still preserve user-driven changes if you give each trace a `uid` that stays with it as it moves. unselected :class:`plotly.graph_objects.scattergeo.Unselected` instance or dict with compatible properties visible Determines whether or not this trace is visible. If "legendonly", the trace is not drawn, but can appear as a legend item (provided that the legend itself is visible). row : int or None (default) Subplot row index (starting from 1) for the trace to be added. Only valid if figure was created using `plotly.tools.make_subplots` col : int or None (default) Subplot col index (starting from 1) for the trace to be added. Only valid if figure was created using `plotly.tools.make_subplots` Returns ------- FigureWidget """ from plotly.graph_objs import Scattergeo new_trace = Scattergeo( connectgaps=connectgaps, customdata=customdata, customdatasrc=customdatasrc, featureidkey=featureidkey, fill=fill, fillcolor=fillcolor, geo=geo, geojson=geojson, hoverinfo=hoverinfo, hoverinfosrc=hoverinfosrc, hoverlabel=hoverlabel, hovertemplate=hovertemplate, hovertemplatesrc=hovertemplatesrc, hovertext=hovertext, hovertextsrc=hovertextsrc, ids=ids, idssrc=idssrc, lat=lat, latsrc=latsrc, legendgroup=legendgroup, line=line, locationmode=locationmode, locations=locations, locationssrc=locationssrc, lon=lon, lonsrc=lonsrc, marker=marker, meta=meta, metasrc=metasrc, mode=mode, name=name, opacity=opacity, selected=selected, selectedpoints=selectedpoints, showlegend=showlegend, stream=stream, text=text, textfont=textfont, textposition=textposition, textpositionsrc=textpositionsrc, textsrc=textsrc, texttemplate=texttemplate, texttemplatesrc=texttemplatesrc, uid=uid, uirevision=uirevision, unselected=unselected, visible=visible, **kwargs ) return self.add_trace(new_trace, row=row, col=col) def add_scattergl( self, connectgaps=None, customdata=None, customdatasrc=None, dx=None, dy=None, error_x=None, error_y=None, fill=None, fillcolor=None, hoverinfo=None, hoverinfosrc=None, hoverlabel=None, hovertemplate=None, hovertemplatesrc=None, hovertext=None, hovertextsrc=None, ids=None, idssrc=None, legendgroup=None, line=None, marker=None, meta=None, metasrc=None, mode=None, name=None, opacity=None, selected=None, selectedpoints=None, showlegend=None, stream=None, text=None, textfont=None, textposition=None, textpositionsrc=None, textsrc=None, texttemplate=None, texttemplatesrc=None, uid=None, uirevision=None, unselected=None, visible=None, x=None, x0=None, xaxis=None, xcalendar=None, xperiod=None, xperiod0=None, xperiodalignment=None, xsrc=None, y=None, y0=None, yaxis=None, ycalendar=None, yperiod=None, yperiod0=None, yperiodalignment=None, ysrc=None, row=None, col=None, secondary_y=None, **kwargs ): """ Add a new Scattergl trace The data visualized as scatter point or lines is set in `x` and `y` using the WebGL plotting engine. Bubble charts are achieved by setting `marker.size` and/or `marker.color` to a numerical arrays. Parameters ---------- connectgaps Determines whether or not gaps (i.e. {nan} or missing values) in the provided data arrays are connected. customdata Assigns extra data each datum. This may be useful when listening to hover, click and selection events. Note that, "scatter" traces also appends customdata items in the markers DOM elements customdatasrc Sets the source reference on Chart Studio Cloud for customdata . dx Sets the x coordinate step. See `x0` for more info. dy Sets the y coordinate step. See `y0` for more info. error_x :class:`plotly.graph_objects.scattergl.ErrorX` instance or dict with compatible properties error_y :class:`plotly.graph_objects.scattergl.ErrorY` instance or dict with compatible properties fill Sets the area to fill with a solid color. Defaults to "none" unless this trace is stacked, then it gets "tonexty" ("tonextx") if `orientation` is "v" ("h") Use with `fillcolor` if not "none". "tozerox" and "tozeroy" fill to x=0 and y=0 respectively. "tonextx" and "tonexty" fill between the endpoints of this trace and the endpoints of the trace before it, connecting those endpoints with straight lines (to make a stacked area graph); if there is no trace before it, they behave like "tozerox" and "tozeroy". "toself" connects the endpoints of the trace (or each segment of the trace if it has gaps) into a closed shape. "tonext" fills the space between two traces if one completely encloses the other (eg consecutive contour lines), and behaves like "toself" if there is no trace before it. "tonext" should not be used if one trace does not enclose the other. Traces in a `stackgroup` will only fill to (or be filled to) other traces in the same group. With multiple `stackgroup`s or some traces stacked and some not, if fill-linked traces are not already consecutive, the later ones will be pushed down in the drawing order. fillcolor Sets the fill color. Defaults to a half-transparent variant of the line color, marker color, or marker line color, whichever is available. hoverinfo Determines which trace information appear on hover. If `none` or `skip` are set, no information is displayed upon hovering. But, if `none` is set, click and hover events are still fired. hoverinfosrc Sets the source reference on Chart Studio Cloud for hoverinfo . hoverlabel :class:`plotly.graph_objects.scattergl.Hoverlabel` instance or dict with compatible properties hovertemplate Template string used for rendering the information that appear on hover box. Note that this will override `hoverinfo`. Variables are inserted using %{variable}, for example "y: %{y}". Numbers are formatted using d3-format's syntax %{variable:d3-format}, for example "Price: %{y:$.2f}". https://github.com/d3/d3-3.x-api- reference/blob/master/Formatting.md#d3_format for details on the formatting syntax. Dates are formatted using d3-time-format's syntax %{variable|d3-time- format}, for example "Day: %{2019-01-01|%A}". https://github.com/d3/d3-time-format#locale_format for details on the date formatting syntax. The variables available in `hovertemplate` are the ones emitted as event data described at this link https://plotly.com/javascript/plotlyjs-events/#event- data. Additionally, every attributes that can be specified per-point (the ones that are `arrayOk: true`) are available. Anything contained in tag `<extra>` is displayed in the secondary box, for example "<extra>{fullData.name}</extra>". To hide the secondary box completely, use an empty tag `<extra></extra>`. hovertemplatesrc Sets the source reference on Chart Studio Cloud for hovertemplate . hovertext Sets hover text elements associated with each (x,y) pair. If a single string, the same string appears over all the data points. If an array of string, the items are mapped in order to the this trace's (x,y) coordinates. To be seen, trace `hoverinfo` must contain a "text" flag. hovertextsrc Sets the source reference on Chart Studio Cloud for hovertext . ids Assigns id labels to each datum. These ids for object constancy of data points during animation. Should be an array of strings, not numbers or any other type. idssrc Sets the source reference on Chart Studio Cloud for ids . legendgroup Sets the legend group for this trace. Traces part of the same legend group hide/show at the same time when toggling legend items. line :class:`plotly.graph_objects.scattergl.Line` instance or dict with compatible properties marker :class:`plotly.graph_objects.scattergl.Marker` instance or dict with compatible properties meta Assigns extra meta information associated with this trace that can be used in various text attributes. Attributes such as trace `name`, graph, axis and colorbar `title.text`, annotation `text` `rangeselector`, `updatemenues` and `sliders` `label` text all support `meta`. To access the trace `meta` values in an attribute in the same trace, simply use `%{meta[i]}` where `i` is the index or key of the `meta` item in question. To access trace `meta` in layout attributes, use `%{data[n[.meta[i]}` where `i` is the index or key of the `meta` and `n` is the trace index. metasrc Sets the source reference on Chart Studio Cloud for meta . mode Determines the drawing mode for this scatter trace. name Sets the trace name. The trace name appear as the legend item and on hover. opacity Sets the opacity of the trace. selected :class:`plotly.graph_objects.scattergl.Selected` instance or dict with compatible properties selectedpoints Array containing integer indices of selected points. Has an effect only for traces that support selections. Note that an empty array means an empty selection where the `unselected` are turned on for all points, whereas, any other non-array values means no selection all where the `selected` and `unselected` styles have no effect. showlegend Determines whether or not an item corresponding to this trace is shown in the legend. stream :class:`plotly.graph_objects.scattergl.Stream` instance or dict with compatible properties text Sets text elements associated with each (x,y) pair. If a single string, the same string appears over all the data points. If an array of string, the items are mapped in order to the this trace's (x,y) coordinates. If trace `hoverinfo` contains a "text" flag and "hovertext" is not set, these elements will be seen in the hover labels. textfont Sets the text font. textposition Sets the positions of the `text` elements with respects to the (x,y) coordinates. textpositionsrc Sets the source reference on Chart Studio Cloud for textposition . textsrc Sets the source reference on Chart Studio Cloud for text . texttemplate Template string used for rendering the information text that appear on points. Note that this will override `textinfo`. Variables are inserted using %{variable}, for example "y: %{y}". Numbers are formatted using d3-format's syntax %{variable:d3-format}, for example "Price: %{y:$.2f}". https://github.com/d3/d3-3.x-api- reference/blob/master/Formatting.md#d3_format for details on the formatting syntax. Dates are formatted using d3-time-format's syntax %{variable|d3-time- format}, for example "Day: %{2019-01-01|%A}". https://github.com/d3/d3-time-format#locale_format for details on the date formatting syntax. Every attributes that can be specified per-point (the ones that are `arrayOk: true`) are available. texttemplatesrc Sets the source reference on Chart Studio Cloud for texttemplate . uid Assign an id to this trace, Use this to provide object constancy between traces during animations and transitions. uirevision Controls persistence of some user-driven changes to the trace: `constraintrange` in `parcoords` traces, as well as some `editable: true` modifications such as `name` and `colorbar.title`. Defaults to `layout.uirevision`. Note that other user-driven trace attribute changes are controlled by `layout` attributes: `trace.visible` is controlled by `layout.legend.uirevision`, `selectedpoints` is controlled by `layout.selectionrevision`, and `colorbar.(x|y)` (accessible with `config: {editable: true}`) is controlled by `layout.editrevision`. Trace changes are tracked by `uid`, which only falls back on trace index if no `uid` is provided. So if your app can add/remove traces before the end of the `data` array, such that the same trace has a different index, you can still preserve user-driven changes if you give each trace a `uid` that stays with it as it moves. unselected :class:`plotly.graph_objects.scattergl.Unselected` instance or dict with compatible properties visible Determines whether or not this trace is visible. If "legendonly", the trace is not drawn, but can appear as a legend item (provided that the legend itself is visible). x Sets the x coordinates. x0 Alternate to `x`. Builds a linear space of x coordinates. Use with `dx` where `x0` is the starting coordinate and `dx` the step. xaxis Sets a reference between this trace's x coordinates and a 2D cartesian x axis. If "x" (the default value), the x coordinates refer to `layout.xaxis`. If "x2", the x coordinates refer to `layout.xaxis2`, and so on. xcalendar Sets the calendar system to use with `x` date data. xperiod Only relevant when the axis `type` is "date". Sets the period positioning in milliseconds or "M<n>" on the x axis. Special values in the form of "M<n>" could be used to declare the number of months. In this case `n` must be a positive integer. xperiod0 Only relevant when the axis `type` is "date". Sets the base for period positioning in milliseconds or date string on the x0 axis. When `x0period` is round number of weeks, the `x0period0` by default would be on a Sunday i.e. 2000-01-02, otherwise it would be at 2000-01-01. xperiodalignment Only relevant when the axis `type` is "date". Sets the alignment of data points on the x axis. xsrc Sets the source reference on Chart Studio Cloud for x . y Sets the y coordinates. y0 Alternate to `y`. Builds a linear space of y coordinates. Use with `dy` where `y0` is the starting coordinate and `dy` the step. yaxis Sets a reference between this trace's y coordinates and a 2D cartesian y axis. If "y" (the default value), the y coordinates refer to `layout.yaxis`. If "y2", the y coordinates refer to `layout.yaxis2`, and so on. ycalendar Sets the calendar system to use with `y` date data. yperiod Only relevant when the axis `type` is "date". Sets the period positioning in milliseconds or "M<n>" on the y axis. Special values in the form of "M<n>" could be used to declare the number of months. In this case `n` must be a positive integer. yperiod0 Only relevant when the axis `type` is "date". Sets the base for period positioning in milliseconds or date string on the y0 axis. When `y0period` is round number of weeks, the `y0period0` by default would be on a Sunday i.e. 2000-01-02, otherwise it would be at 2000-01-01. yperiodalignment Only relevant when the axis `type` is "date". Sets the alignment of data points on the y axis. ysrc Sets the source reference on Chart Studio Cloud for y . row : int or None (default) Subplot row index (starting from 1) for the trace to be added. Only valid if figure was created using `plotly.tools.make_subplots` col : int or None (default) Subplot col index (starting from 1) for the trace to be added. Only valid if figure was created using `plotly.tools.make_subplots` secondary_y: boolean or None (default None) If True, associate this trace with the secondary y-axis of the subplot at the specified row and col. Only valid if all of the following conditions are satisfied: * The figure was created using `plotly.subplots.make_subplots`. * The row and col arguments are not None * The subplot at the specified row and col has type xy (which is the default) and secondary_y True. These properties are specified in the specs argument to make_subplots. See the make_subplots docstring for more info. Returns ------- FigureWidget """ from plotly.graph_objs import Scattergl new_trace = Scattergl( connectgaps=connectgaps, customdata=customdata, customdatasrc=customdatasrc, dx=dx, dy=dy, error_x=error_x, error_y=error_y, fill=fill, fillcolor=fillcolor, hoverinfo=hoverinfo, hoverinfosrc=hoverinfosrc, hoverlabel=hoverlabel, hovertemplate=hovertemplate, hovertemplatesrc=hovertemplatesrc, hovertext=hovertext, hovertextsrc=hovertextsrc, ids=ids, idssrc=idssrc, legendgroup=legendgroup, line=line, marker=marker, meta=meta, metasrc=metasrc, mode=mode, name=name, opacity=opacity, selected=selected, selectedpoints=selectedpoints, showlegend=showlegend, stream=stream, text=text, textfont=textfont, textposition=textposition, textpositionsrc=textpositionsrc, textsrc=textsrc, texttemplate=texttemplate, texttemplatesrc=texttemplatesrc, uid=uid, uirevision=uirevision, unselected=unselected, visible=visible, x=x, x0=x0, xaxis=xaxis, xcalendar=xcalendar, xperiod=xperiod, xperiod0=xperiod0, xperiodalignment=xperiodalignment, xsrc=xsrc, y=y, y0=y0, yaxis=yaxis, ycalendar=ycalendar, yperiod=yperiod, yperiod0=yperiod0, yperiodalignment=yperiodalignment, ysrc=ysrc, **kwargs ) return self.add_trace(new_trace, row=row, col=col, secondary_y=secondary_y) def add_scattermapbox( self, below=None, connectgaps=None, customdata=None, customdatasrc=None, fill=None, fillcolor=None, hoverinfo=None, hoverinfosrc=None, hoverlabel=None, hovertemplate=None, hovertemplatesrc=None, hovertext=None, hovertextsrc=None, ids=None, idssrc=None, lat=None, latsrc=None, legendgroup=None, line=None, lon=None, lonsrc=None, marker=None, meta=None, metasrc=None, mode=None, name=None, opacity=None, selected=None, selectedpoints=None, showlegend=None, stream=None, subplot=None, text=None, textfont=None, textposition=None, textsrc=None, texttemplate=None, texttemplatesrc=None, uid=None, uirevision=None, unselected=None, visible=None, row=None, col=None, **kwargs ): """ Add a new Scattermapbox trace The data visualized as scatter point, lines or marker symbols on a Mapbox GL geographic map is provided by longitude/latitude pairs in `lon` and `lat`. Parameters ---------- below Determines if this scattermapbox trace's layers are to be inserted before the layer with the specified ID. By default, scattermapbox layers are inserted above all the base layers. To place the scattermapbox layers above every other layer, set `below` to "''". connectgaps Determines whether or not gaps (i.e. {nan} or missing values) in the provided data arrays are connected. customdata Assigns extra data each datum. This may be useful when listening to hover, click and selection events. Note that, "scatter" traces also appends customdata items in the markers DOM elements customdatasrc Sets the source reference on Chart Studio Cloud for customdata . fill Sets the area to fill with a solid color. Use with `fillcolor` if not "none". "toself" connects the endpoints of the trace (or each segment of the trace if it has gaps) into a closed shape. fillcolor Sets the fill color. Defaults to a half-transparent variant of the line color, marker color, or marker line color, whichever is available. hoverinfo Determines which trace information appear on hover. If `none` or `skip` are set, no information is displayed upon hovering. But, if `none` is set, click and hover events are still fired. hoverinfosrc Sets the source reference on Chart Studio Cloud for hoverinfo . hoverlabel :class:`plotly.graph_objects.scattermapbox.Hoverlabel` instance or dict with compatible properties hovertemplate Template string used for rendering the information that appear on hover box. Note that this will override `hoverinfo`. Variables are inserted using %{variable}, for example "y: %{y}". Numbers are formatted using d3-format's syntax %{variable:d3-format}, for example "Price: %{y:$.2f}". https://github.com/d3/d3-3.x-api- reference/blob/master/Formatting.md#d3_format for details on the formatting syntax. Dates are formatted using d3-time-format's syntax %{variable|d3-time- format}, for example "Day: %{2019-01-01|%A}". https://github.com/d3/d3-time-format#locale_format for details on the date formatting syntax. The variables available in `hovertemplate` are the ones emitted as event data described at this link https://plotly.com/javascript/plotlyjs-events/#event- data. Additionally, every attributes that can be specified per-point (the ones that are `arrayOk: true`) are available. Anything contained in tag `<extra>` is displayed in the secondary box, for example "<extra>{fullData.name}</extra>". To hide the secondary box completely, use an empty tag `<extra></extra>`. hovertemplatesrc Sets the source reference on Chart Studio Cloud for hovertemplate . hovertext Sets hover text elements associated with each (lon,lat) pair If a single string, the same string appears over all the data points. If an array of string, the items are mapped in order to the this trace's (lon,lat) coordinates. To be seen, trace `hoverinfo` must contain a "text" flag. hovertextsrc Sets the source reference on Chart Studio Cloud for hovertext . ids Assigns id labels to each datum. These ids for object constancy of data points during animation. Should be an array of strings, not numbers or any other type. idssrc Sets the source reference on Chart Studio Cloud for ids . lat Sets the latitude coordinates (in degrees North). latsrc Sets the source reference on Chart Studio Cloud for lat . legendgroup Sets the legend group for this trace. Traces part of the same legend group hide/show at the same time when toggling legend items. line :class:`plotly.graph_objects.scattermapbox.Line` instance or dict with compatible properties lon Sets the longitude coordinates (in degrees East). lonsrc Sets the source reference on Chart Studio Cloud for lon . marker :class:`plotly.graph_objects.scattermapbox.Marker` instance or dict with compatible properties meta Assigns extra meta information associated with this trace that can be used in various text attributes. Attributes such as trace `name`, graph, axis and colorbar `title.text`, annotation `text` `rangeselector`, `updatemenues` and `sliders` `label` text all support `meta`. To access the trace `meta` values in an attribute in the same trace, simply use `%{meta[i]}` where `i` is the index or key of the `meta` item in question. To access trace `meta` in layout attributes, use `%{data[n[.meta[i]}` where `i` is the index or key of the `meta` and `n` is the trace index. metasrc Sets the source reference on Chart Studio Cloud for meta . mode Determines the drawing mode for this scatter trace. If the provided `mode` includes "text" then the `text` elements appear at the coordinates. Otherwise, the `text` elements appear on hover. name Sets the trace name. The trace name appear as the legend item and on hover. opacity Sets the opacity of the trace. selected :class:`plotly.graph_objects.scattermapbox.Selected` instance or dict with compatible properties selectedpoints Array containing integer indices of selected points. Has an effect only for traces that support selections. Note that an empty array means an empty selection where the `unselected` are turned on for all points, whereas, any other non-array values means no selection all where the `selected` and `unselected` styles have no effect. showlegend Determines whether or not an item corresponding to this trace is shown in the legend. stream :class:`plotly.graph_objects.scattermapbox.Stream` instance or dict with compatible properties subplot Sets a reference between this trace's data coordinates and a mapbox subplot. If "mapbox" (the default value), the data refer to `layout.mapbox`. If "mapbox2", the data refer to `layout.mapbox2`, and so on. text Sets text elements associated with each (lon,lat) pair If a single string, the same string appears over all the data points. If an array of string, the items are mapped in order to the this trace's (lon,lat) coordinates. If trace `hoverinfo` contains a "text" flag and "hovertext" is not set, these elements will be seen in the hover labels. textfont Sets the icon text font (color=mapbox.layer.paint.text- color, size=mapbox.layer.layout.text-size). Has an effect only when `type` is set to "symbol". textposition Sets the positions of the `text` elements with respects to the (x,y) coordinates. textsrc Sets the source reference on Chart Studio Cloud for text . texttemplate Template string used for rendering the information text that appear on points. Note that this will override `textinfo`. Variables are inserted using %{variable}, for example "y: %{y}". Numbers are formatted using d3-format's syntax %{variable:d3-format}, for example "Price: %{y:$.2f}". https://github.com/d3/d3-3.x-api- reference/blob/master/Formatting.md#d3_format for details on the formatting syntax. Dates are formatted using d3-time-format's syntax %{variable|d3-time- format}, for example "Day: %{2019-01-01|%A}". https://github.com/d3/d3-time-format#locale_format for details on the date formatting syntax. Every attributes that can be specified per-point (the ones that are `arrayOk: true`) are available. variables `lat`, `lon` and `text`. texttemplatesrc Sets the source reference on Chart Studio Cloud for texttemplate . uid Assign an id to this trace, Use this to provide object constancy between traces during animations and transitions. uirevision Controls persistence of some user-driven changes to the trace: `constraintrange` in `parcoords` traces, as well as some `editable: true` modifications such as `name` and `colorbar.title`. Defaults to `layout.uirevision`. Note that other user-driven trace attribute changes are controlled by `layout` attributes: `trace.visible` is controlled by `layout.legend.uirevision`, `selectedpoints` is controlled by `layout.selectionrevision`, and `colorbar.(x|y)` (accessible with `config: {editable: true}`) is controlled by `layout.editrevision`. Trace changes are tracked by `uid`, which only falls back on trace index if no `uid` is provided. So if your app can add/remove traces before the end of the `data` array, such that the same trace has a different index, you can still preserve user-driven changes if you give each trace a `uid` that stays with it as it moves. unselected :class:`plotly.graph_objects.scattermapbox.Unselected` instance or dict with compatible properties visible Determines whether or not this trace is visible. If "legendonly", the trace is not drawn, but can appear as a legend item (provided that the legend itself is visible). row : int or None (default) Subplot row index (starting from 1) for the trace to be added. Only valid if figure was created using `plotly.tools.make_subplots` col : int or None (default) Subplot col index (starting from 1) for the trace to be added. Only valid if figure was created using `plotly.tools.make_subplots` Returns ------- FigureWidget """ from plotly.graph_objs import Scattermapbox new_trace = Scattermapbox( below=below, connectgaps=connectgaps, customdata=customdata, customdatasrc=customdatasrc, fill=fill, fillcolor=fillcolor, hoverinfo=hoverinfo, hoverinfosrc=hoverinfosrc, hoverlabel=hoverlabel, hovertemplate=hovertemplate, hovertemplatesrc=hovertemplatesrc, hovertext=hovertext, hovertextsrc=hovertextsrc, ids=ids, idssrc=idssrc, lat=lat, latsrc=latsrc, legendgroup=legendgroup, line=line, lon=lon, lonsrc=lonsrc, marker=marker, meta=meta, metasrc=metasrc, mode=mode, name=name, opacity=opacity, selected=selected, selectedpoints=selectedpoints, showlegend=showlegend, stream=stream, subplot=subplot, text=text, textfont=textfont, textposition=textposition, textsrc=textsrc, texttemplate=texttemplate, texttemplatesrc=texttemplatesrc, uid=uid, uirevision=uirevision, unselected=unselected, visible=visible, **kwargs ) return self.add_trace(new_trace, row=row, col=col) def add_scatterpolar( self, cliponaxis=None, connectgaps=None, customdata=None, customdatasrc=None, dr=None, dtheta=None, fill=None, fillcolor=None, hoverinfo=None, hoverinfosrc=None, hoverlabel=None, hoveron=None, hovertemplate=None, hovertemplatesrc=None, hovertext=None, hovertextsrc=None, ids=None, idssrc=None, legendgroup=None, line=None, marker=None, meta=None, metasrc=None, mode=None, name=None, opacity=None, r=None, r0=None, rsrc=None, selected=None, selectedpoints=None, showlegend=None, stream=None, subplot=None, text=None, textfont=None, textposition=None, textpositionsrc=None, textsrc=None, texttemplate=None, texttemplatesrc=None, theta=None, theta0=None, thetasrc=None, thetaunit=None, uid=None, uirevision=None, unselected=None, visible=None, row=None, col=None, **kwargs ): """ Add a new Scatterpolar trace The scatterpolar trace type encompasses line charts, scatter charts, text charts, and bubble charts in polar coordinates. The data visualized as scatter point or lines is set in `r` (radial) and `theta` (angular) coordinates Text (appearing either on the chart or on hover only) is via `text`. Bubble charts are achieved by setting `marker.size` and/or `marker.color` to numerical arrays. Parameters ---------- cliponaxis Determines whether or not markers and text nodes are clipped about the subplot axes. To show markers and text nodes above axis lines and tick labels, make sure to set `xaxis.layer` and `yaxis.layer` to *below traces*. connectgaps Determines whether or not gaps (i.e. {nan} or missing values) in the provided data arrays are connected. customdata Assigns extra data each datum. This may be useful when listening to hover, click and selection events. Note that, "scatter" traces also appends customdata items in the markers DOM elements customdatasrc Sets the source reference on Chart Studio Cloud for customdata . dr Sets the r coordinate step. dtheta Sets the theta coordinate step. By default, the `dtheta` step equals the subplot's period divided by the length of the `r` coordinates. fill Sets the area to fill with a solid color. Use with `fillcolor` if not "none". scatterpolar has a subset of the options available to scatter. "toself" connects the endpoints of the trace (or each segment of the trace if it has gaps) into a closed shape. "tonext" fills the space between two traces if one completely encloses the other (eg consecutive contour lines), and behaves like "toself" if there is no trace before it. "tonext" should not be used if one trace does not enclose the other. fillcolor Sets the fill color. Defaults to a half-transparent variant of the line color, marker color, or marker line color, whichever is available. hoverinfo Determines which trace information appear on hover. If `none` or `skip` are set, no information is displayed upon hovering. But, if `none` is set, click and hover events are still fired. hoverinfosrc Sets the source reference on Chart Studio Cloud for hoverinfo . hoverlabel :class:`plotly.graph_objects.scatterpolar.Hoverlabel` instance or dict with compatible properties hoveron Do the hover effects highlight individual points (markers or line points) or do they highlight filled regions? If the fill is "toself" or "tonext" and there are no markers or text, then the default is "fills", otherwise it is "points". hovertemplate Template string used for rendering the information that appear on hover box. Note that this will override `hoverinfo`. Variables are inserted using %{variable}, for example "y: %{y}". Numbers are formatted using d3-format's syntax %{variable:d3-format}, for example "Price: %{y:$.2f}". https://github.com/d3/d3-3.x-api- reference/blob/master/Formatting.md#d3_format for details on the formatting syntax. Dates are formatted using d3-time-format's syntax %{variable|d3-time- format}, for example "Day: %{2019-01-01|%A}". https://github.com/d3/d3-time-format#locale_format for details on the date formatting syntax. The variables available in `hovertemplate` are the ones emitted as event data described at this link https://plotly.com/javascript/plotlyjs-events/#event- data. Additionally, every attributes that can be specified per-point (the ones that are `arrayOk: true`) are available. Anything contained in tag `<extra>` is displayed in the secondary box, for example "<extra>{fullData.name}</extra>". To hide the secondary box completely, use an empty tag `<extra></extra>`. hovertemplatesrc Sets the source reference on Chart Studio Cloud for hovertemplate . hovertext Sets hover text elements associated with each (x,y) pair. If a single string, the same string appears over all the data points. If an array of string, the items are mapped in order to the this trace's (x,y) coordinates. To be seen, trace `hoverinfo` must contain a "text" flag. hovertextsrc Sets the source reference on Chart Studio Cloud for hovertext . ids Assigns id labels to each datum. These ids for object constancy of data points during animation. Should be an array of strings, not numbers or any other type. idssrc Sets the source reference on Chart Studio Cloud for ids . legendgroup Sets the legend group for this trace. Traces part of the same legend group hide/show at the same time when toggling legend items. line :class:`plotly.graph_objects.scatterpolar.Line` instance or dict with compatible properties marker :class:`plotly.graph_objects.scatterpolar.Marker` instance or dict with compatible properties meta Assigns extra meta information associated with this trace that can be used in various text attributes. Attributes such as trace `name`, graph, axis and colorbar `title.text`, annotation `text` `rangeselector`, `updatemenues` and `sliders` `label` text all support `meta`. To access the trace `meta` values in an attribute in the same trace, simply use `%{meta[i]}` where `i` is the index or key of the `meta` item in question. To access trace `meta` in layout attributes, use `%{data[n[.meta[i]}` where `i` is the index or key of the `meta` and `n` is the trace index. metasrc Sets the source reference on Chart Studio Cloud for meta . mode Determines the drawing mode for this scatter trace. If the provided `mode` includes "text" then the `text` elements appear at the coordinates. Otherwise, the `text` elements appear on hover. If there are less than 20 points and the trace is not stacked then the default is "lines+markers". Otherwise, "lines". name Sets the trace name. The trace name appear as the legend item and on hover. opacity Sets the opacity of the trace. r Sets the radial coordinates r0 Alternate to `r`. Builds a linear space of r coordinates. Use with `dr` where `r0` is the starting coordinate and `dr` the step. rsrc Sets the source reference on Chart Studio Cloud for r . selected :class:`plotly.graph_objects.scatterpolar.Selected` instance or dict with compatible properties selectedpoints Array containing integer indices of selected points. Has an effect only for traces that support selections. Note that an empty array means an empty selection where the `unselected` are turned on for all points, whereas, any other non-array values means no selection all where the `selected` and `unselected` styles have no effect. showlegend Determines whether or not an item corresponding to this trace is shown in the legend. stream :class:`plotly.graph_objects.scatterpolar.Stream` instance or dict with compatible properties subplot Sets a reference between this trace's data coordinates and a polar subplot. If "polar" (the default value), the data refer to `layout.polar`. If "polar2", the data refer to `layout.polar2`, and so on. text Sets text elements associated with each (x,y) pair. If a single string, the same string appears over all the data points. If an array of string, the items are mapped in order to the this trace's (x,y) coordinates. If trace `hoverinfo` contains a "text" flag and "hovertext" is not set, these elements will be seen in the hover labels. textfont Sets the text font. textposition Sets the positions of the `text` elements with respects to the (x,y) coordinates. textpositionsrc Sets the source reference on Chart Studio Cloud for textposition . textsrc Sets the source reference on Chart Studio Cloud for text . texttemplate Template string used for rendering the information text that appear on points. Note that this will override `textinfo`. Variables are inserted using %{variable}, for example "y: %{y}". Numbers are formatted using d3-format's syntax %{variable:d3-format}, for example "Price: %{y:$.2f}". https://github.com/d3/d3-3.x-api- reference/blob/master/Formatting.md#d3_format for details on the formatting syntax. Dates are formatted using d3-time-format's syntax %{variable|d3-time- format}, for example "Day: %{2019-01-01|%A}". https://github.com/d3/d3-time-format#locale_format for details on the date formatting syntax. Every attributes that can be specified per-point (the ones that are `arrayOk: true`) are available. variables `r`, `theta` and `text`. texttemplatesrc Sets the source reference on Chart Studio Cloud for texttemplate . theta Sets the angular coordinates theta0 Alternate to `theta`. Builds a linear space of theta coordinates. Use with `dtheta` where `theta0` is the starting coordinate and `dtheta` the step. thetasrc Sets the source reference on Chart Studio Cloud for theta . thetaunit Sets the unit of input "theta" values. Has an effect only when on "linear" angular axes. uid Assign an id to this trace, Use this to provide object constancy between traces during animations and transitions. uirevision Controls persistence of some user-driven changes to the trace: `constraintrange` in `parcoords` traces, as well as some `editable: true` modifications such as `name` and `colorbar.title`. Defaults to `layout.uirevision`. Note that other user-driven trace attribute changes are controlled by `layout` attributes: `trace.visible` is controlled by `layout.legend.uirevision`, `selectedpoints` is controlled by `layout.selectionrevision`, and `colorbar.(x|y)` (accessible with `config: {editable: true}`) is controlled by `layout.editrevision`. Trace changes are tracked by `uid`, which only falls back on trace index if no `uid` is provided. So if your app can add/remove traces before the end of the `data` array, such that the same trace has a different index, you can still preserve user-driven changes if you give each trace a `uid` that stays with it as it moves. unselected :class:`plotly.graph_objects.scatterpolar.Unselected` instance or dict with compatible properties visible Determines whether or not this trace is visible. If "legendonly", the trace is not drawn, but can appear as a legend item (provided that the legend itself is visible). row : int or None (default) Subplot row index (starting from 1) for the trace to be added. Only valid if figure was created using `plotly.tools.make_subplots` col : int or None (default) Subplot col index (starting from 1) for the trace to be added. Only valid if figure was created using `plotly.tools.make_subplots` Returns ------- FigureWidget """ from plotly.graph_objs import Scatterpolar new_trace = Scatterpolar( cliponaxis=cliponaxis, connectgaps=connectgaps, customdata=customdata, customdatasrc=customdatasrc, dr=dr, dtheta=dtheta, fill=fill, fillcolor=fillcolor, hoverinfo=hoverinfo, hoverinfosrc=hoverinfosrc, hoverlabel=hoverlabel, hoveron=hoveron, hovertemplate=hovertemplate, hovertemplatesrc=hovertemplatesrc, hovertext=hovertext, hovertextsrc=hovertextsrc, ids=ids, idssrc=idssrc, legendgroup=legendgroup, line=line, marker=marker, meta=meta, metasrc=metasrc, mode=mode, name=name, opacity=opacity, r=r, r0=r0, rsrc=rsrc, selected=selected, selectedpoints=selectedpoints, showlegend=showlegend, stream=stream, subplot=subplot, text=text, textfont=textfont, textposition=textposition, textpositionsrc=textpositionsrc, textsrc=textsrc, texttemplate=texttemplate, texttemplatesrc=texttemplatesrc, theta=theta, theta0=theta0, thetasrc=thetasrc, thetaunit=thetaunit, uid=uid, uirevision=uirevision, unselected=unselected, visible=visible, **kwargs ) return self.add_trace(new_trace, row=row, col=col) def add_scatterpolargl( self, connectgaps=None, customdata=None, customdatasrc=None, dr=None, dtheta=None, fill=None, fillcolor=None, hoverinfo=None, hoverinfosrc=None, hoverlabel=None, hovertemplate=None, hovertemplatesrc=None, hovertext=None, hovertextsrc=None, ids=None, idssrc=None, legendgroup=None, line=None, marker=None, meta=None, metasrc=None, mode=None, name=None, opacity=None, r=None, r0=None, rsrc=None, selected=None, selectedpoints=None, showlegend=None, stream=None, subplot=None, text=None, textfont=None, textposition=None, textpositionsrc=None, textsrc=None, texttemplate=None, texttemplatesrc=None, theta=None, theta0=None, thetasrc=None, thetaunit=None, uid=None, uirevision=None, unselected=None, visible=None, row=None, col=None, **kwargs ): """ Add a new Scatterpolargl trace The scatterpolargl trace type encompasses line charts, scatter charts, and bubble charts in polar coordinates using the WebGL plotting engine. The data visualized as scatter point or lines is set in `r` (radial) and `theta` (angular) coordinates Bubble charts are achieved by setting `marker.size` and/or `marker.color` to numerical arrays. Parameters ---------- connectgaps Determines whether or not gaps (i.e. {nan} or missing values) in the provided data arrays are connected. customdata Assigns extra data each datum. This may be useful when listening to hover, click and selection events. Note that, "scatter" traces also appends customdata items in the markers DOM elements customdatasrc Sets the source reference on Chart Studio Cloud for customdata . dr Sets the r coordinate step. dtheta Sets the theta coordinate step. By default, the `dtheta` step equals the subplot's period divided by the length of the `r` coordinates. fill Sets the area to fill with a solid color. Defaults to "none" unless this trace is stacked, then it gets "tonexty" ("tonextx") if `orientation` is "v" ("h") Use with `fillcolor` if not "none". "tozerox" and "tozeroy" fill to x=0 and y=0 respectively. "tonextx" and "tonexty" fill between the endpoints of this trace and the endpoints of the trace before it, connecting those endpoints with straight lines (to make a stacked area graph); if there is no trace before it, they behave like "tozerox" and "tozeroy". "toself" connects the endpoints of the trace (or each segment of the trace if it has gaps) into a closed shape. "tonext" fills the space between two traces if one completely encloses the other (eg consecutive contour lines), and behaves like "toself" if there is no trace before it. "tonext" should not be used if one trace does not enclose the other. Traces in a `stackgroup` will only fill to (or be filled to) other traces in the same group. With multiple `stackgroup`s or some traces stacked and some not, if fill-linked traces are not already consecutive, the later ones will be pushed down in the drawing order. fillcolor Sets the fill color. Defaults to a half-transparent variant of the line color, marker color, or marker line color, whichever is available. hoverinfo Determines which trace information appear on hover. If `none` or `skip` are set, no information is displayed upon hovering. But, if `none` is set, click and hover events are still fired. hoverinfosrc Sets the source reference on Chart Studio Cloud for hoverinfo . hoverlabel :class:`plotly.graph_objects.scatterpolargl.Hoverlabel` instance or dict with compatible properties hovertemplate Template string used for rendering the information that appear on hover box. Note that this will override `hoverinfo`. Variables are inserted using %{variable}, for example "y: %{y}". Numbers are formatted using d3-format's syntax %{variable:d3-format}, for example "Price: %{y:$.2f}". https://github.com/d3/d3-3.x-api- reference/blob/master/Formatting.md#d3_format for details on the formatting syntax. Dates are formatted using d3-time-format's syntax %{variable|d3-time- format}, for example "Day: %{2019-01-01|%A}". https://github.com/d3/d3-time-format#locale_format for details on the date formatting syntax. The variables available in `hovertemplate` are the ones emitted as event data described at this link https://plotly.com/javascript/plotlyjs-events/#event- data. Additionally, every attributes that can be specified per-point (the ones that are `arrayOk: true`) are available. Anything contained in tag `<extra>` is displayed in the secondary box, for example "<extra>{fullData.name}</extra>". To hide the secondary box completely, use an empty tag `<extra></extra>`. hovertemplatesrc Sets the source reference on Chart Studio Cloud for hovertemplate . hovertext Sets hover text elements associated with each (x,y) pair. If a single string, the same string appears over all the data points. If an array of string, the items are mapped in order to the this trace's (x,y) coordinates. To be seen, trace `hoverinfo` must contain a "text" flag. hovertextsrc Sets the source reference on Chart Studio Cloud for hovertext . ids Assigns id labels to each datum. These ids for object constancy of data points during animation. Should be an array of strings, not numbers or any other type. idssrc Sets the source reference on Chart Studio Cloud for ids . legendgroup Sets the legend group for this trace. Traces part of the same legend group hide/show at the same time when toggling legend items. line :class:`plotly.graph_objects.scatterpolargl.Line` instance or dict with compatible properties marker :class:`plotly.graph_objects.scatterpolargl.Marker` instance or dict with compatible properties meta Assigns extra meta information associated with this trace that can be used in various text attributes. Attributes such as trace `name`, graph, axis and colorbar `title.text`, annotation `text` `rangeselector`, `updatemenues` and `sliders` `label` text all support `meta`. To access the trace `meta` values in an attribute in the same trace, simply use `%{meta[i]}` where `i` is the index or key of the `meta` item in question. To access trace `meta` in layout attributes, use `%{data[n[.meta[i]}` where `i` is the index or key of the `meta` and `n` is the trace index. metasrc Sets the source reference on Chart Studio Cloud for meta . mode Determines the drawing mode for this scatter trace. If the provided `mode` includes "text" then the `text` elements appear at the coordinates. Otherwise, the `text` elements appear on hover. If there are less than 20 points and the trace is not stacked then the default is "lines+markers". Otherwise, "lines". name Sets the trace name. The trace name appear as the legend item and on hover. opacity Sets the opacity of the trace. r Sets the radial coordinates r0 Alternate to `r`. Builds a linear space of r coordinates. Use with `dr` where `r0` is the starting coordinate and `dr` the step. rsrc Sets the source reference on Chart Studio Cloud for r . selected :class:`plotly.graph_objects.scatterpolargl.Selected` instance or dict with compatible properties selectedpoints Array containing integer indices of selected points. Has an effect only for traces that support selections. Note that an empty array means an empty selection where the `unselected` are turned on for all points, whereas, any other non-array values means no selection all where the `selected` and `unselected` styles have no effect. showlegend Determines whether or not an item corresponding to this trace is shown in the legend. stream :class:`plotly.graph_objects.scatterpolargl.Stream` instance or dict with compatible properties subplot Sets a reference between this trace's data coordinates and a polar subplot. If "polar" (the default value), the data refer to `layout.polar`. If "polar2", the data refer to `layout.polar2`, and so on. text Sets text elements associated with each (x,y) pair. If a single string, the same string appears over all the data points. If an array of string, the items are mapped in order to the this trace's (x,y) coordinates. If trace `hoverinfo` contains a "text" flag and "hovertext" is not set, these elements will be seen in the hover labels. textfont Sets the text font. textposition Sets the positions of the `text` elements with respects to the (x,y) coordinates. textpositionsrc Sets the source reference on Chart Studio Cloud for textposition . textsrc Sets the source reference on Chart Studio Cloud for text . texttemplate Template string used for rendering the information text that appear on points. Note that this will override `textinfo`. Variables are inserted using %{variable}, for example "y: %{y}". Numbers are formatted using d3-format's syntax %{variable:d3-format}, for example "Price: %{y:$.2f}". https://github.com/d3/d3-3.x-api- reference/blob/master/Formatting.md#d3_format for details on the formatting syntax. Dates are formatted using d3-time-format's syntax %{variable|d3-time- format}, for example "Day: %{2019-01-01|%A}". https://github.com/d3/d3-time-format#locale_format for details on the date formatting syntax. Every attributes that can be specified per-point (the ones that are `arrayOk: true`) are available. variables `r`, `theta` and `text`. texttemplatesrc Sets the source reference on Chart Studio Cloud for texttemplate . theta Sets the angular coordinates theta0 Alternate to `theta`. Builds a linear space of theta coordinates. Use with `dtheta` where `theta0` is the starting coordinate and `dtheta` the step. thetasrc Sets the source reference on Chart Studio Cloud for theta . thetaunit Sets the unit of input "theta" values. Has an effect only when on "linear" angular axes. uid Assign an id to this trace, Use this to provide object constancy between traces during animations and transitions. uirevision Controls persistence of some user-driven changes to the trace: `constraintrange` in `parcoords` traces, as well as some `editable: true` modifications such as `name` and `colorbar.title`. Defaults to `layout.uirevision`. Note that other user-driven trace attribute changes are controlled by `layout` attributes: `trace.visible` is controlled by `layout.legend.uirevision`, `selectedpoints` is controlled by `layout.selectionrevision`, and `colorbar.(x|y)` (accessible with `config: {editable: true}`) is controlled by `layout.editrevision`. Trace changes are tracked by `uid`, which only falls back on trace index if no `uid` is provided. So if your app can add/remove traces before the end of the `data` array, such that the same trace has a different index, you can still preserve user-driven changes if you give each trace a `uid` that stays with it as it moves. unselected :class:`plotly.graph_objects.scatterpolargl.Unselected` instance or dict with compatible properties visible Determines whether or not this trace is visible. If "legendonly", the trace is not drawn, but can appear as a legend item (provided that the legend itself is visible). row : int or None (default) Subplot row index (starting from 1) for the trace to be added. Only valid if figure was created using `plotly.tools.make_subplots` col : int or None (default) Subplot col index (starting from 1) for the trace to be added. Only valid if figure was created using `plotly.tools.make_subplots` Returns ------- FigureWidget """ from plotly.graph_objs import Scatterpolargl new_trace = Scatterpolargl( connectgaps=connectgaps, customdata=customdata, customdatasrc=customdatasrc, dr=dr, dtheta=dtheta, fill=fill, fillcolor=fillcolor, hoverinfo=hoverinfo, hoverinfosrc=hoverinfosrc, hoverlabel=hoverlabel, hovertemplate=hovertemplate, hovertemplatesrc=hovertemplatesrc, hovertext=hovertext, hovertextsrc=hovertextsrc, ids=ids, idssrc=idssrc, legendgroup=legendgroup, line=line, marker=marker, meta=meta, metasrc=metasrc, mode=mode, name=name, opacity=opacity, r=r, r0=r0, rsrc=rsrc, selected=selected, selectedpoints=selectedpoints, showlegend=showlegend, stream=stream, subplot=subplot, text=text, textfont=textfont, textposition=textposition, textpositionsrc=textpositionsrc, textsrc=textsrc, texttemplate=texttemplate, texttemplatesrc=texttemplatesrc, theta=theta, theta0=theta0, thetasrc=thetasrc, thetaunit=thetaunit, uid=uid, uirevision=uirevision, unselected=unselected, visible=visible, **kwargs ) return self.add_trace(new_trace, row=row, col=col) def add_scatterternary( self, a=None, asrc=None, b=None, bsrc=None, c=None, cliponaxis=None, connectgaps=None, csrc=None, customdata=None, customdatasrc=None, fill=None, fillcolor=None, hoverinfo=None, hoverinfosrc=None, hoverlabel=None, hoveron=None, hovertemplate=None, hovertemplatesrc=None, hovertext=None, hovertextsrc=None, ids=None, idssrc=None, legendgroup=None, line=None, marker=None, meta=None, metasrc=None, mode=None, name=None, opacity=None, selected=None, selectedpoints=None, showlegend=None, stream=None, subplot=None, sum=None, text=None, textfont=None, textposition=None, textpositionsrc=None, textsrc=None, texttemplate=None, texttemplatesrc=None, uid=None, uirevision=None, unselected=None, visible=None, row=None, col=None, **kwargs ): """ Add a new Scatterternary trace Provides similar functionality to the "scatter" type but on a ternary phase diagram. The data is provided by at least two arrays out of `a`, `b`, `c` triplets. Parameters ---------- a Sets the quantity of component `a` in each data point. If `a`, `b`, and `c` are all provided, they need not be normalized, only the relative values matter. If only two arrays are provided they must be normalized to match `ternary<i>.sum`. asrc Sets the source reference on Chart Studio Cloud for a . b Sets the quantity of component `a` in each data point. If `a`, `b`, and `c` are all provided, they need not be normalized, only the relative values matter. If only two arrays are provided they must be normalized to match `ternary<i>.sum`. bsrc Sets the source reference on Chart Studio Cloud for b . c Sets the quantity of component `a` in each data point. If `a`, `b`, and `c` are all provided, they need not be normalized, only the relative values matter. If only two arrays are provided they must be normalized to match `ternary<i>.sum`. cliponaxis Determines whether or not markers and text nodes are clipped about the subplot axes. To show markers and text nodes above axis lines and tick labels, make sure to set `xaxis.layer` and `yaxis.layer` to *below traces*. connectgaps Determines whether or not gaps (i.e. {nan} or missing values) in the provided data arrays are connected. csrc Sets the source reference on Chart Studio Cloud for c . customdata Assigns extra data each datum. This may be useful when listening to hover, click and selection events. Note that, "scatter" traces also appends customdata items in the markers DOM elements customdatasrc Sets the source reference on Chart Studio Cloud for customdata . fill Sets the area to fill with a solid color. Use with `fillcolor` if not "none". scatterternary has a subset of the options available to scatter. "toself" connects the endpoints of the trace (or each segment of the trace if it has gaps) into a closed shape. "tonext" fills the space between two traces if one completely encloses the other (eg consecutive contour lines), and behaves like "toself" if there is no trace before it. "tonext" should not be used if one trace does not enclose the other. fillcolor Sets the fill color. Defaults to a half-transparent variant of the line color, marker color, or marker line color, whichever is available. hoverinfo Determines which trace information appear on hover. If `none` or `skip` are set, no information is displayed upon hovering. But, if `none` is set, click and hover events are still fired. hoverinfosrc Sets the source reference on Chart Studio Cloud for hoverinfo . hoverlabel :class:`plotly.graph_objects.scatterternary.Hoverlabel` instance or dict with compatible properties hoveron Do the hover effects highlight individual points (markers or line points) or do they highlight filled regions? If the fill is "toself" or "tonext" and there are no markers or text, then the default is "fills", otherwise it is "points". hovertemplate Template string used for rendering the information that appear on hover box. Note that this will override `hoverinfo`. Variables are inserted using %{variable}, for example "y: %{y}". Numbers are formatted using d3-format's syntax %{variable:d3-format}, for example "Price: %{y:$.2f}". https://github.com/d3/d3-3.x-api- reference/blob/master/Formatting.md#d3_format for details on the formatting syntax. Dates are formatted using d3-time-format's syntax %{variable|d3-time- format}, for example "Day: %{2019-01-01|%A}". https://github.com/d3/d3-time-format#locale_format for details on the date formatting syntax. The variables available in `hovertemplate` are the ones emitted as event data described at this link https://plotly.com/javascript/plotlyjs-events/#event- data. Additionally, every attributes that can be specified per-point (the ones that are `arrayOk: true`) are available. Anything contained in tag `<extra>` is displayed in the secondary box, for example "<extra>{fullData.name}</extra>". To hide the secondary box completely, use an empty tag `<extra></extra>`. hovertemplatesrc Sets the source reference on Chart Studio Cloud for hovertemplate . hovertext Sets hover text elements associated with each (a,b,c) point. If a single string, the same string appears over all the data points. If an array of strings, the items are mapped in order to the the data points in (a,b,c). To be seen, trace `hoverinfo` must contain a "text" flag. hovertextsrc Sets the source reference on Chart Studio Cloud for hovertext . ids Assigns id labels to each datum. These ids for object constancy of data points during animation. Should be an array of strings, not numbers or any other type. idssrc Sets the source reference on Chart Studio Cloud for ids . legendgroup Sets the legend group for this trace. Traces part of the same legend group hide/show at the same time when toggling legend items. line :class:`plotly.graph_objects.scatterternary.Line` instance or dict with compatible properties marker :class:`plotly.graph_objects.scatterternary.Marker` instance or dict with compatible properties meta Assigns extra meta information associated with this trace that can be used in various text attributes. Attributes such as trace `name`, graph, axis and colorbar `title.text`, annotation `text` `rangeselector`, `updatemenues` and `sliders` `label` text all support `meta`. To access the trace `meta` values in an attribute in the same trace, simply use `%{meta[i]}` where `i` is the index or key of the `meta` item in question. To access trace `meta` in layout attributes, use `%{data[n[.meta[i]}` where `i` is the index or key of the `meta` and `n` is the trace index. metasrc Sets the source reference on Chart Studio Cloud for meta . mode Determines the drawing mode for this scatter trace. If the provided `mode` includes "text" then the `text` elements appear at the coordinates. Otherwise, the `text` elements appear on hover. If there are less than 20 points and the trace is not stacked then the default is "lines+markers". Otherwise, "lines". name Sets the trace name. The trace name appear as the legend item and on hover. opacity Sets the opacity of the trace. selected :class:`plotly.graph_objects.scatterternary.Selected` instance or dict with compatible properties selectedpoints Array containing integer indices of selected points. Has an effect only for traces that support selections. Note that an empty array means an empty selection where the `unselected` are turned on for all points, whereas, any other non-array values means no selection all where the `selected` and `unselected` styles have no effect. showlegend Determines whether or not an item corresponding to this trace is shown in the legend. stream :class:`plotly.graph_objects.scatterternary.Stream` instance or dict with compatible properties subplot Sets a reference between this trace's data coordinates and a ternary subplot. If "ternary" (the default value), the data refer to `layout.ternary`. If "ternary2", the data refer to `layout.ternary2`, and so on. sum The number each triplet should sum to, if only two of `a`, `b`, and `c` are provided. This overrides `ternary<i>.sum` to normalize this specific trace, but does not affect the values displayed on the axes. 0 (or missing) means to use ternary<i>.sum text Sets text elements associated with each (a,b,c) point. If a single string, the same string appears over all the data points. If an array of strings, the items are mapped in order to the the data points in (a,b,c). If trace `hoverinfo` contains a "text" flag and "hovertext" is not set, these elements will be seen in the hover labels. textfont Sets the text font. textposition Sets the positions of the `text` elements with respects to the (x,y) coordinates. textpositionsrc Sets the source reference on Chart Studio Cloud for textposition . textsrc Sets the source reference on Chart Studio Cloud for text . texttemplate Template string used for rendering the information text that appear on points. Note that this will override `textinfo`. Variables are inserted using %{variable}, for example "y: %{y}". Numbers are formatted using d3-format's syntax %{variable:d3-format}, for example "Price: %{y:$.2f}". https://github.com/d3/d3-3.x-api- reference/blob/master/Formatting.md#d3_format for details on the formatting syntax. Dates are formatted using d3-time-format's syntax %{variable|d3-time- format}, for example "Day: %{2019-01-01|%A}". https://github.com/d3/d3-time-format#locale_format for details on the date formatting syntax. Every attributes that can be specified per-point (the ones that are `arrayOk: true`) are available. variables `a`, `b`, `c` and `text`. texttemplatesrc Sets the source reference on Chart Studio Cloud for texttemplate . uid Assign an id to this trace, Use this to provide object constancy between traces during animations and transitions. uirevision Controls persistence of some user-driven changes to the trace: `constraintrange` in `parcoords` traces, as well as some `editable: true` modifications such as `name` and `colorbar.title`. Defaults to `layout.uirevision`. Note that other user-driven trace attribute changes are controlled by `layout` attributes: `trace.visible` is controlled by `layout.legend.uirevision`, `selectedpoints` is controlled by `layout.selectionrevision`, and `colorbar.(x|y)` (accessible with `config: {editable: true}`) is controlled by `layout.editrevision`. Trace changes are tracked by `uid`, which only falls back on trace index if no `uid` is provided. So if your app can add/remove traces before the end of the `data` array, such that the same trace has a different index, you can still preserve user-driven changes if you give each trace a `uid` that stays with it as it moves. unselected :class:`plotly.graph_objects.scatterternary.Unselected` instance or dict with compatible properties visible Determines whether or not this trace is visible. If "legendonly", the trace is not drawn, but can appear as a legend item (provided that the legend itself is visible). row : int or None (default) Subplot row index (starting from 1) for the trace to be added. Only valid if figure was created using `plotly.tools.make_subplots` col : int or None (default) Subplot col index (starting from 1) for the trace to be added. Only valid if figure was created using `plotly.tools.make_subplots` Returns ------- FigureWidget """ from plotly.graph_objs import Scatterternary new_trace = Scatterternary( a=a, asrc=asrc, b=b, bsrc=bsrc, c=c, cliponaxis=cliponaxis, connectgaps=connectgaps, csrc=csrc, customdata=customdata, customdatasrc=customdatasrc, fill=fill, fillcolor=fillcolor, hoverinfo=hoverinfo, hoverinfosrc=hoverinfosrc, hoverlabel=hoverlabel, hoveron=hoveron, hovertemplate=hovertemplate, hovertemplatesrc=hovertemplatesrc, hovertext=hovertext, hovertextsrc=hovertextsrc, ids=ids, idssrc=idssrc, legendgroup=legendgroup, line=line, marker=marker, meta=meta, metasrc=metasrc, mode=mode, name=name, opacity=opacity, selected=selected, selectedpoints=selectedpoints, showlegend=showlegend, stream=stream, subplot=subplot, sum=sum, text=text, textfont=textfont, textposition=textposition, textpositionsrc=textpositionsrc, textsrc=textsrc, texttemplate=texttemplate, texttemplatesrc=texttemplatesrc, uid=uid, uirevision=uirevision, unselected=unselected, visible=visible, **kwargs ) return self.add_trace(new_trace, row=row, col=col) def add_splom( self, customdata=None, customdatasrc=None, diagonal=None, dimensions=None, dimensiondefaults=None, hoverinfo=None, hoverinfosrc=None, hoverlabel=None, hovertemplate=None, hovertemplatesrc=None, hovertext=None, hovertextsrc=None, ids=None, idssrc=None, legendgroup=None, marker=None, meta=None, metasrc=None, name=None, opacity=None, selected=None, selectedpoints=None, showlegend=None, showlowerhalf=None, showupperhalf=None, stream=None, text=None, textsrc=None, uid=None, uirevision=None, unselected=None, visible=None, xaxes=None, yaxes=None, row=None, col=None, **kwargs ): """ Add a new Splom trace Splom traces generate scatter plot matrix visualizations. Each splom `dimensions` items correspond to a generated axis. Values for each of those dimensions are set in `dimensions[i].values`. Splom traces support all `scattergl` marker style attributes. Specify `layout.grid` attributes and/or layout x-axis and y-axis attributes for more control over the axis positioning and style. Parameters ---------- customdata Assigns extra data each datum. This may be useful when listening to hover, click and selection events. Note that, "scatter" traces also appends customdata items in the markers DOM elements customdatasrc Sets the source reference on Chart Studio Cloud for customdata . diagonal :class:`plotly.graph_objects.splom.Diagonal` instance or dict with compatible properties dimensions A tuple of :class:`plotly.graph_objects.splom.Dimension` instances or dicts with compatible properties dimensiondefaults When used in a template (as layout.template.data.splom.dimensiondefaults), sets the default property values to use for elements of splom.dimensions hoverinfo Determines which trace information appear on hover. If `none` or `skip` are set, no information is displayed upon hovering. But, if `none` is set, click and hover events are still fired. hoverinfosrc Sets the source reference on Chart Studio Cloud for hoverinfo . hoverlabel :class:`plotly.graph_objects.splom.Hoverlabel` instance or dict with compatible properties hovertemplate Template string used for rendering the information that appear on hover box. Note that this will override `hoverinfo`. Variables are inserted using %{variable}, for example "y: %{y}". Numbers are formatted using d3-format's syntax %{variable:d3-format}, for example "Price: %{y:$.2f}". https://github.com/d3/d3-3.x-api- reference/blob/master/Formatting.md#d3_format for details on the formatting syntax. Dates are formatted using d3-time-format's syntax %{variable|d3-time- format}, for example "Day: %{2019-01-01|%A}". https://github.com/d3/d3-time-format#locale_format for details on the date formatting syntax. The variables available in `hovertemplate` are the ones emitted as event data described at this link https://plotly.com/javascript/plotlyjs-events/#event- data. Additionally, every attributes that can be specified per-point (the ones that are `arrayOk: true`) are available. Anything contained in tag `<extra>` is displayed in the secondary box, for example "<extra>{fullData.name}</extra>". To hide the secondary box completely, use an empty tag `<extra></extra>`. hovertemplatesrc Sets the source reference on Chart Studio Cloud for hovertemplate . hovertext Same as `text`. hovertextsrc Sets the source reference on Chart Studio Cloud for hovertext . ids Assigns id labels to each datum. These ids for object constancy of data points during animation. Should be an array of strings, not numbers or any other type. idssrc Sets the source reference on Chart Studio Cloud for ids . legendgroup Sets the legend group for this trace. Traces part of the same legend group hide/show at the same time when toggling legend items. marker :class:`plotly.graph_objects.splom.Marker` instance or dict with compatible properties meta Assigns extra meta information associated with this trace that can be used in various text attributes. Attributes such as trace `name`, graph, axis and colorbar `title.text`, annotation `text` `rangeselector`, `updatemenues` and `sliders` `label` text all support `meta`. To access the trace `meta` values in an attribute in the same trace, simply use `%{meta[i]}` where `i` is the index or key of the `meta` item in question. To access trace `meta` in layout attributes, use `%{data[n[.meta[i]}` where `i` is the index or key of the `meta` and `n` is the trace index. metasrc Sets the source reference on Chart Studio Cloud for meta . name Sets the trace name. The trace name appear as the legend item and on hover. opacity Sets the opacity of the trace. selected :class:`plotly.graph_objects.splom.Selected` instance or dict with compatible properties selectedpoints Array containing integer indices of selected points. Has an effect only for traces that support selections. Note that an empty array means an empty selection where the `unselected` are turned on for all points, whereas, any other non-array values means no selection all where the `selected` and `unselected` styles have no effect. showlegend Determines whether or not an item corresponding to this trace is shown in the legend. showlowerhalf Determines whether or not subplots on the lower half from the diagonal are displayed. showupperhalf Determines whether or not subplots on the upper half from the diagonal are displayed. stream :class:`plotly.graph_objects.splom.Stream` instance or dict with compatible properties text Sets text elements associated with each (x,y) pair to appear on hover. If a single string, the same string appears over all the data points. If an array of string, the items are mapped in order to the this trace's (x,y) coordinates. textsrc Sets the source reference on Chart Studio Cloud for text . uid Assign an id to this trace, Use this to provide object constancy between traces during animations and transitions. uirevision Controls persistence of some user-driven changes to the trace: `constraintrange` in `parcoords` traces, as well as some `editable: true` modifications such as `name` and `colorbar.title`. Defaults to `layout.uirevision`. Note that other user-driven trace attribute changes are controlled by `layout` attributes: `trace.visible` is controlled by `layout.legend.uirevision`, `selectedpoints` is controlled by `layout.selectionrevision`, and `colorbar.(x|y)` (accessible with `config: {editable: true}`) is controlled by `layout.editrevision`. Trace changes are tracked by `uid`, which only falls back on trace index if no `uid` is provided. So if your app can add/remove traces before the end of the `data` array, such that the same trace has a different index, you can still preserve user-driven changes if you give each trace a `uid` that stays with it as it moves. unselected :class:`plotly.graph_objects.splom.Unselected` instance or dict with compatible properties visible Determines whether or not this trace is visible. If "legendonly", the trace is not drawn, but can appear as a legend item (provided that the legend itself is visible). xaxes Sets the list of x axes corresponding to dimensions of this splom trace. By default, a splom will match the first N xaxes where N is the number of input dimensions. Note that, in case where `diagonal.visible` is false and `showupperhalf` or `showlowerhalf` is false, this splom trace will generate one less x-axis and one less y-axis. yaxes Sets the list of y axes corresponding to dimensions of this splom trace. By default, a splom will match the first N yaxes where N is the number of input dimensions. Note that, in case where `diagonal.visible` is false and `showupperhalf` or `showlowerhalf` is false, this splom trace will generate one less x-axis and one less y-axis. row : int or None (default) Subplot row index (starting from 1) for the trace to be added. Only valid if figure was created using `plotly.tools.make_subplots` col : int or None (default) Subplot col index (starting from 1) for the trace to be added. Only valid if figure was created using `plotly.tools.make_subplots` Returns ------- FigureWidget """ from plotly.graph_objs import Splom new_trace = Splom( customdata=customdata, customdatasrc=customdatasrc, diagonal=diagonal, dimensions=dimensions, dimensiondefaults=dimensiondefaults, hoverinfo=hoverinfo, hoverinfosrc=hoverinfosrc, hoverlabel=hoverlabel, hovertemplate=hovertemplate, hovertemplatesrc=hovertemplatesrc, hovertext=hovertext, hovertextsrc=hovertextsrc, ids=ids, idssrc=idssrc, legendgroup=legendgroup, marker=marker, meta=meta, metasrc=metasrc, name=name, opacity=opacity, selected=selected, selectedpoints=selectedpoints, showlegend=showlegend, showlowerhalf=showlowerhalf, showupperhalf=showupperhalf, stream=stream, text=text, textsrc=textsrc, uid=uid, uirevision=uirevision, unselected=unselected, visible=visible, xaxes=xaxes, yaxes=yaxes, **kwargs ) return self.add_trace(new_trace, row=row, col=col) def add_streamtube( self, autocolorscale=None, cauto=None, cmax=None, cmid=None, cmin=None, coloraxis=None, colorbar=None, colorscale=None, customdata=None, customdatasrc=None, hoverinfo=None, hoverinfosrc=None, hoverlabel=None, hovertemplate=None, hovertemplatesrc=None, hovertext=None, ids=None, idssrc=None, legendgroup=None, lighting=None, lightposition=None, maxdisplayed=None, meta=None, metasrc=None, name=None, opacity=None, reversescale=None, scene=None, showlegend=None, showscale=None, sizeref=None, starts=None, stream=None, text=None, u=None, uid=None, uirevision=None, usrc=None, v=None, visible=None, vsrc=None, w=None, wsrc=None, x=None, xsrc=None, y=None, ysrc=None, z=None, zsrc=None, row=None, col=None, **kwargs ): """ Add a new Streamtube trace Use a streamtube trace to visualize flow in a vector field. Specify a vector field using 6 1D arrays of equal length, 3 position arrays `x`, `y` and `z` and 3 vector component arrays `u`, `v`, and `w`. By default, the tubes' starting positions will be cut from the vector field's x-z plane at its minimum y value. To specify your own starting position, use attributes `starts.x`, `starts.y` and `starts.z`. The color is encoded by the norm of (u, v, w), and the local radius by the divergence of (u, v, w). Parameters ---------- autocolorscale Determines whether the colorscale is a default palette (`autocolorscale: true`) or the palette determined by `colorscale`. In case `colorscale` is unspecified or `autocolorscale` is true, the default palette will be chosen according to whether numbers in the `color` array are all positive, all negative or mixed. cauto Determines whether or not the color domain is computed with respect to the input data (here u/v/w norm) or the bounds set in `cmin` and `cmax` Defaults to `false` when `cmin` and `cmax` are set by the user. cmax Sets the upper bound of the color domain. Value should have the same units as u/v/w norm and if set, `cmin` must be set as well. cmid Sets the mid-point of the color domain by scaling `cmin` and/or `cmax` to be equidistant to this point. Value should have the same units as u/v/w norm. Has no effect when `cauto` is `false`. cmin Sets the lower bound of the color domain. Value should have the same units as u/v/w norm and if set, `cmax` must be set as well. coloraxis Sets a reference to a shared color axis. References to these shared color axes are "coloraxis", "coloraxis2", "coloraxis3", etc. Settings for these shared color axes are set in the layout, under `layout.coloraxis`, `layout.coloraxis2`, etc. Note that multiple color scales can be linked to the same color axis. colorbar :class:`plotly.graph_objects.streamtube.ColorBar` instance or dict with compatible properties colorscale Sets the colorscale. The colorscale must be an array containing arrays mapping a normalized value to an rgb, rgba, hex, hsl, hsv, or named color string. At minimum, a mapping for the lowest (0) and highest (1) values are required. For example, `[[0, 'rgb(0,0,255)'], [1, 'rgb(255,0,0)']]`. To control the bounds of the colorscale in color space, use`cmin` and `cmax`. Alternatively, `colorscale` may be a palette name string of the following list: Greys,YlGnBu,Greens,YlOrR d,Bluered,RdBu,Reds,Blues,Picnic,Rainbow,Portland,Jet,H ot,Blackbody,Earth,Electric,Viridis,Cividis. customdata Assigns extra data each datum. This may be useful when listening to hover, click and selection events. Note that, "scatter" traces also appends customdata items in the markers DOM elements customdatasrc Sets the source reference on Chart Studio Cloud for customdata . hoverinfo Determines which trace information appear on hover. If `none` or `skip` are set, no information is displayed upon hovering. But, if `none` is set, click and hover events are still fired. hoverinfosrc Sets the source reference on Chart Studio Cloud for hoverinfo . hoverlabel :class:`plotly.graph_objects.streamtube.Hoverlabel` instance or dict with compatible properties hovertemplate Template string used for rendering the information that appear on hover box. Note that this will override `hoverinfo`. Variables are inserted using %{variable}, for example "y: %{y}". Numbers are formatted using d3-format's syntax %{variable:d3-format}, for example "Price: %{y:$.2f}". https://github.com/d3/d3-3.x-api- reference/blob/master/Formatting.md#d3_format for details on the formatting syntax. Dates are formatted using d3-time-format's syntax %{variable|d3-time- format}, for example "Day: %{2019-01-01|%A}". https://github.com/d3/d3-time-format#locale_format for details on the date formatting syntax. The variables available in `hovertemplate` are the ones emitted as event data described at this link https://plotly.com/javascript/plotlyjs-events/#event- data. Additionally, every attributes that can be specified per-point (the ones that are `arrayOk: true`) are available. variables `tubex`, `tubey`, `tubez`, `tubeu`, `tubev`, `tubew`, `norm` and `divergence`. Anything contained in tag `<extra>` is displayed in the secondary box, for example "<extra>{fullData.name}</extra>". To hide the secondary box completely, use an empty tag `<extra></extra>`. hovertemplatesrc Sets the source reference on Chart Studio Cloud for hovertemplate . hovertext Same as `text`. ids Assigns id labels to each datum. These ids for object constancy of data points during animation. Should be an array of strings, not numbers or any other type. idssrc Sets the source reference on Chart Studio Cloud for ids . legendgroup Sets the legend group for this trace. Traces part of the same legend group hide/show at the same time when toggling legend items. lighting :class:`plotly.graph_objects.streamtube.Lighting` instance or dict with compatible properties lightposition :class:`plotly.graph_objects.streamtube.Lightposition` instance or dict with compatible properties maxdisplayed The maximum number of displayed segments in a streamtube. meta Assigns extra meta information associated with this trace that can be used in various text attributes. Attributes such as trace `name`, graph, axis and colorbar `title.text`, annotation `text` `rangeselector`, `updatemenues` and `sliders` `label` text all support `meta`. To access the trace `meta` values in an attribute in the same trace, simply use `%{meta[i]}` where `i` is the index or key of the `meta` item in question. To access trace `meta` in layout attributes, use `%{data[n[.meta[i]}` where `i` is the index or key of the `meta` and `n` is the trace index. metasrc Sets the source reference on Chart Studio Cloud for meta . name Sets the trace name. The trace name appear as the legend item and on hover. opacity Sets the opacity of the surface. Please note that in the case of using high `opacity` values for example a value greater than or equal to 0.5 on two surfaces (and 0.25 with four surfaces), an overlay of multiple transparent surfaces may not perfectly be sorted in depth by the webgl API. This behavior may be improved in the near future and is subject to change. reversescale Reverses the color mapping if true. If true, `cmin` will correspond to the last color in the array and `cmax` will correspond to the first color. scene Sets a reference between this trace's 3D coordinate system and a 3D scene. If "scene" (the default value), the (x,y,z) coordinates refer to `layout.scene`. If "scene2", the (x,y,z) coordinates refer to `layout.scene2`, and so on. showlegend Determines whether or not an item corresponding to this trace is shown in the legend. showscale Determines whether or not a colorbar is displayed for this trace. sizeref The scaling factor for the streamtubes. The default is 1, which avoids two max divergence tubes from touching at adjacent starting positions. starts :class:`plotly.graph_objects.streamtube.Starts` instance or dict with compatible properties stream :class:`plotly.graph_objects.streamtube.Stream` instance or dict with compatible properties text Sets a text element associated with this trace. If trace `hoverinfo` contains a "text" flag, this text element will be seen in all hover labels. Note that streamtube traces do not support array `text` values. u Sets the x components of the vector field. uid Assign an id to this trace, Use this to provide object constancy between traces during animations and transitions. uirevision Controls persistence of some user-driven changes to the trace: `constraintrange` in `parcoords` traces, as well as some `editable: true` modifications such as `name` and `colorbar.title`. Defaults to `layout.uirevision`. Note that other user-driven trace attribute changes are controlled by `layout` attributes: `trace.visible` is controlled by `layout.legend.uirevision`, `selectedpoints` is controlled by `layout.selectionrevision`, and `colorbar.(x|y)` (accessible with `config: {editable: true}`) is controlled by `layout.editrevision`. Trace changes are tracked by `uid`, which only falls back on trace index if no `uid` is provided. So if your app can add/remove traces before the end of the `data` array, such that the same trace has a different index, you can still preserve user-driven changes if you give each trace a `uid` that stays with it as it moves. usrc Sets the source reference on Chart Studio Cloud for u . v Sets the y components of the vector field. visible Determines whether or not this trace is visible. If "legendonly", the trace is not drawn, but can appear as a legend item (provided that the legend itself is visible). vsrc Sets the source reference on Chart Studio Cloud for v . w Sets the z components of the vector field. wsrc Sets the source reference on Chart Studio Cloud for w . x Sets the x coordinates of the vector field. xsrc Sets the source reference on Chart Studio Cloud for x . y Sets the y coordinates of the vector field. ysrc Sets the source reference on Chart Studio Cloud for y . z Sets the z coordinates of the vector field. zsrc Sets the source reference on Chart Studio Cloud for z . row : int or None (default) Subplot row index (starting from 1) for the trace to be added. Only valid if figure was created using `plotly.tools.make_subplots` col : int or None (default) Subplot col index (starting from 1) for the trace to be added. Only valid if figure was created using `plotly.tools.make_subplots` Returns ------- FigureWidget """ from plotly.graph_objs import Streamtube new_trace = Streamtube( autocolorscale=autocolorscale, cauto=cauto, cmax=cmax, cmid=cmid, cmin=cmin, coloraxis=coloraxis, colorbar=colorbar, colorscale=colorscale, customdata=customdata, customdatasrc=customdatasrc, hoverinfo=hoverinfo, hoverinfosrc=hoverinfosrc, hoverlabel=hoverlabel, hovertemplate=hovertemplate, hovertemplatesrc=hovertemplatesrc, hovertext=hovertext, ids=ids, idssrc=idssrc, legendgroup=legendgroup, lighting=lighting, lightposition=lightposition, maxdisplayed=maxdisplayed, meta=meta, metasrc=metasrc, name=name, opacity=opacity, reversescale=reversescale, scene=scene, showlegend=showlegend, showscale=showscale, sizeref=sizeref, starts=starts, stream=stream, text=text, u=u, uid=uid, uirevision=uirevision, usrc=usrc, v=v, visible=visible, vsrc=vsrc, w=w, wsrc=wsrc, x=x, xsrc=xsrc, y=y, ysrc=ysrc, z=z, zsrc=zsrc, **kwargs ) return self.add_trace(new_trace, row=row, col=col) def add_sunburst( self, branchvalues=None, count=None, customdata=None, customdatasrc=None, domain=None, hoverinfo=None, hoverinfosrc=None, hoverlabel=None, hovertemplate=None, hovertemplatesrc=None, hovertext=None, hovertextsrc=None, ids=None, idssrc=None, insidetextfont=None, insidetextorientation=None, labels=None, labelssrc=None, leaf=None, level=None, marker=None, maxdepth=None, meta=None, metasrc=None, name=None, opacity=None, outsidetextfont=None, parents=None, parentssrc=None, rotation=None, sort=None, stream=None, text=None, textfont=None, textinfo=None, textsrc=None, texttemplate=None, texttemplatesrc=None, uid=None, uirevision=None, values=None, valuessrc=None, visible=None, row=None, col=None, **kwargs ): """ Add a new Sunburst trace Visualize hierarchal data spanning outward radially from root to leaves. The sunburst sectors are determined by the entries in "labels" or "ids" and in "parents". Parameters ---------- branchvalues Determines how the items in `values` are summed. When set to "total", items in `values` are taken to be value of all its descendants. When set to "remainder", items in `values` corresponding to the root and the branches sectors are taken to be the extra part not part of the sum of the values at their leaves. count Determines default for `values` when it is not provided, by inferring a 1 for each of the "leaves" and/or "branches", otherwise 0. customdata Assigns extra data each datum. This may be useful when listening to hover, click and selection events. Note that, "scatter" traces also appends customdata items in the markers DOM elements customdatasrc Sets the source reference on Chart Studio Cloud for customdata . domain :class:`plotly.graph_objects.sunburst.Domain` instance or dict with compatible properties hoverinfo Determines which trace information appear on hover. If `none` or `skip` are set, no information is displayed upon hovering. But, if `none` is set, click and hover events are still fired. hoverinfosrc Sets the source reference on Chart Studio Cloud for hoverinfo . hoverlabel :class:`plotly.graph_objects.sunburst.Hoverlabel` instance or dict with compatible properties hovertemplate Template string used for rendering the information that appear on hover box. Note that this will override `hoverinfo`. Variables are inserted using %{variable}, for example "y: %{y}". Numbers are formatted using d3-format's syntax %{variable:d3-format}, for example "Price: %{y:$.2f}". https://github.com/d3/d3-3.x-api- reference/blob/master/Formatting.md#d3_format for details on the formatting syntax. Dates are formatted using d3-time-format's syntax %{variable|d3-time- format}, for example "Day: %{2019-01-01|%A}". https://github.com/d3/d3-time-format#locale_format for details on the date formatting syntax. The variables available in `hovertemplate` are the ones emitted as event data described at this link https://plotly.com/javascript/plotlyjs-events/#event- data. Additionally, every attributes that can be specified per-point (the ones that are `arrayOk: true`) are available. variables `currentPath`, `root`, `entry`, `percentRoot`, `percentEntry` and `percentParent`. Anything contained in tag `<extra>` is displayed in the secondary box, for example "<extra>{fullData.name}</extra>". To hide the secondary box completely, use an empty tag `<extra></extra>`. hovertemplatesrc Sets the source reference on Chart Studio Cloud for hovertemplate . hovertext Sets hover text elements associated with each sector. If a single string, the same string appears for all data points. If an array of string, the items are mapped in order of this trace's sectors. To be seen, trace `hoverinfo` must contain a "text" flag. hovertextsrc Sets the source reference on Chart Studio Cloud for hovertext . ids Assigns id labels to each datum. These ids for object constancy of data points during animation. Should be an array of strings, not numbers or any other type. idssrc Sets the source reference on Chart Studio Cloud for ids . insidetextfont Sets the font used for `textinfo` lying inside the sector. insidetextorientation Controls the orientation of the text inside chart sectors. When set to "auto", text may be oriented in any direction in order to be as big as possible in the middle of a sector. The "horizontal" option orients text to be parallel with the bottom of the chart, and may make text smaller in order to achieve that goal. The "radial" option orients text along the radius of the sector. The "tangential" option orients text perpendicular to the radius of the sector. labels Sets the labels of each of the sectors. labelssrc Sets the source reference on Chart Studio Cloud for labels . leaf :class:`plotly.graph_objects.sunburst.Leaf` instance or dict with compatible properties level Sets the level from which this trace hierarchy is rendered. Set `level` to `''` to start from the root node in the hierarchy. Must be an "id" if `ids` is filled in, otherwise plotly attempts to find a matching item in `labels`. marker :class:`plotly.graph_objects.sunburst.Marker` instance or dict with compatible properties maxdepth Sets the number of rendered sectors from any given `level`. Set `maxdepth` to "-1" to render all the levels in the hierarchy. meta Assigns extra meta information associated with this trace that can be used in various text attributes. Attributes such as trace `name`, graph, axis and colorbar `title.text`, annotation `text` `rangeselector`, `updatemenues` and `sliders` `label` text all support `meta`. To access the trace `meta` values in an attribute in the same trace, simply use `%{meta[i]}` where `i` is the index or key of the `meta` item in question. To access trace `meta` in layout attributes, use `%{data[n[.meta[i]}` where `i` is the index or key of the `meta` and `n` is the trace index. metasrc Sets the source reference on Chart Studio Cloud for meta . name Sets the trace name. The trace name appear as the legend item and on hover. opacity Sets the opacity of the trace. outsidetextfont Sets the font used for `textinfo` lying outside the sector. This option refers to the root of the hierarchy presented at the center of a sunburst graph. Please note that if a hierarchy has multiple root nodes, this option won't have any effect and `insidetextfont` would be used. parents Sets the parent sectors for each of the sectors. Empty string items '' are understood to reference the root node in the hierarchy. If `ids` is filled, `parents` items are understood to be "ids" themselves. When `ids` is not set, plotly attempts to find matching items in `labels`, but beware they must be unique. parentssrc Sets the source reference on Chart Studio Cloud for parents . rotation Rotates the whole diagram counterclockwise by some angle. By default the first slice starts at 3 o'clock. sort Determines whether or not the sectors are reordered from largest to smallest. stream :class:`plotly.graph_objects.sunburst.Stream` instance or dict with compatible properties text Sets text elements associated with each sector. If trace `textinfo` contains a "text" flag, these elements will be seen on the chart. If trace `hoverinfo` contains a "text" flag and "hovertext" is not set, these elements will be seen in the hover labels. textfont Sets the font used for `textinfo`. textinfo Determines which trace information appear on the graph. textsrc Sets the source reference on Chart Studio Cloud for text . texttemplate Template string used for rendering the information text that appear on points. Note that this will override `textinfo`. Variables are inserted using %{variable}, for example "y: %{y}". Numbers are formatted using d3-format's syntax %{variable:d3-format}, for example "Price: %{y:$.2f}". https://github.com/d3/d3-3.x-api- reference/blob/master/Formatting.md#d3_format for details on the formatting syntax. Dates are formatted using d3-time-format's syntax %{variable|d3-time- format}, for example "Day: %{2019-01-01|%A}". https://github.com/d3/d3-time-format#locale_format for details on the date formatting syntax. Every attributes that can be specified per-point (the ones that are `arrayOk: true`) are available. variables `currentPath`, `root`, `entry`, `percentRoot`, `percentEntry`, `percentParent`, `label` and `value`. texttemplatesrc Sets the source reference on Chart Studio Cloud for texttemplate . uid Assign an id to this trace, Use this to provide object constancy between traces during animations and transitions. uirevision Controls persistence of some user-driven changes to the trace: `constraintrange` in `parcoords` traces, as well as some `editable: true` modifications such as `name` and `colorbar.title`. Defaults to `layout.uirevision`. Note that other user-driven trace attribute changes are controlled by `layout` attributes: `trace.visible` is controlled by `layout.legend.uirevision`, `selectedpoints` is controlled by `layout.selectionrevision`, and `colorbar.(x|y)` (accessible with `config: {editable: true}`) is controlled by `layout.editrevision`. Trace changes are tracked by `uid`, which only falls back on trace index if no `uid` is provided. So if your app can add/remove traces before the end of the `data` array, such that the same trace has a different index, you can still preserve user-driven changes if you give each trace a `uid` that stays with it as it moves. values Sets the values associated with each of the sectors. Use with `branchvalues` to determine how the values are summed. valuessrc Sets the source reference on Chart Studio Cloud for values . visible Determines whether or not this trace is visible. If "legendonly", the trace is not drawn, but can appear as a legend item (provided that the legend itself is visible). row : int or None (default) Subplot row index (starting from 1) for the trace to be added. Only valid if figure was created using `plotly.tools.make_subplots` col : int or None (default) Subplot col index (starting from 1) for the trace to be added. Only valid if figure was created using `plotly.tools.make_subplots` Returns ------- FigureWidget """ from plotly.graph_objs import Sunburst new_trace = Sunburst( branchvalues=branchvalues, count=count, customdata=customdata, customdatasrc=customdatasrc, domain=domain, hoverinfo=hoverinfo, hoverinfosrc=hoverinfosrc, hoverlabel=hoverlabel, hovertemplate=hovertemplate, hovertemplatesrc=hovertemplatesrc, hovertext=hovertext, hovertextsrc=hovertextsrc, ids=ids, idssrc=idssrc, insidetextfont=insidetextfont, insidetextorientation=insidetextorientation, labels=labels, labelssrc=labelssrc, leaf=leaf, level=level, marker=marker, maxdepth=maxdepth, meta=meta, metasrc=metasrc, name=name, opacity=opacity, outsidetextfont=outsidetextfont, parents=parents, parentssrc=parentssrc, rotation=rotation, sort=sort, stream=stream, text=text, textfont=textfont, textinfo=textinfo, textsrc=textsrc, texttemplate=texttemplate, texttemplatesrc=texttemplatesrc, uid=uid, uirevision=uirevision, values=values, valuessrc=valuessrc, visible=visible, **kwargs ) return self.add_trace(new_trace, row=row, col=col) def add_surface( self, autocolorscale=None, cauto=None, cmax=None, cmid=None, cmin=None, coloraxis=None, colorbar=None, colorscale=None, connectgaps=None, contours=None, customdata=None, customdatasrc=None, hidesurface=None, hoverinfo=None, hoverinfosrc=None, hoverlabel=None, hovertemplate=None, hovertemplatesrc=None, hovertext=None, hovertextsrc=None, ids=None, idssrc=None, legendgroup=None, lighting=None, lightposition=None, meta=None, metasrc=None, name=None, opacity=None, opacityscale=None, reversescale=None, scene=None, showlegend=None, showscale=None, stream=None, surfacecolor=None, surfacecolorsrc=None, text=None, textsrc=None, uid=None, uirevision=None, visible=None, x=None, xcalendar=None, xsrc=None, y=None, ycalendar=None, ysrc=None, z=None, zcalendar=None, zsrc=None, row=None, col=None, **kwargs ): """ Add a new Surface trace The data the describes the coordinates of the surface is set in `z`. Data in `z` should be a 2D list. Coordinates in `x` and `y` can either be 1D lists or 2D lists (e.g. to graph parametric surfaces). If not provided in `x` and `y`, the x and y coordinates are assumed to be linear starting at 0 with a unit step. The color scale corresponds to the `z` values by default. For custom color scales, use `surfacecolor` which should be a 2D list, where its bounds can be controlled using `cmin` and `cmax`. Parameters ---------- autocolorscale Determines whether the colorscale is a default palette (`autocolorscale: true`) or the palette determined by `colorscale`. In case `colorscale` is unspecified or `autocolorscale` is true, the default palette will be chosen according to whether numbers in the `color` array are all positive, all negative or mixed. cauto Determines whether or not the color domain is computed with respect to the input data (here z or surfacecolor) or the bounds set in `cmin` and `cmax` Defaults to `false` when `cmin` and `cmax` are set by the user. cmax Sets the upper bound of the color domain. Value should have the same units as z or surfacecolor and if set, `cmin` must be set as well. cmid Sets the mid-point of the color domain by scaling `cmin` and/or `cmax` to be equidistant to this point. Value should have the same units as z or surfacecolor. Has no effect when `cauto` is `false`. cmin Sets the lower bound of the color domain. Value should have the same units as z or surfacecolor and if set, `cmax` must be set as well. coloraxis Sets a reference to a shared color axis. References to these shared color axes are "coloraxis", "coloraxis2", "coloraxis3", etc. Settings for these shared color axes are set in the layout, under `layout.coloraxis`, `layout.coloraxis2`, etc. Note that multiple color scales can be linked to the same color axis. colorbar :class:`plotly.graph_objects.surface.ColorBar` instance or dict with compatible properties colorscale Sets the colorscale. The colorscale must be an array containing arrays mapping a normalized value to an rgb, rgba, hex, hsl, hsv, or named color string. At minimum, a mapping for the lowest (0) and highest (1) values are required. For example, `[[0, 'rgb(0,0,255)'], [1, 'rgb(255,0,0)']]`. To control the bounds of the colorscale in color space, use`cmin` and `cmax`. Alternatively, `colorscale` may be a palette name string of the following list: Greys,YlGnBu,Greens,YlOrR d,Bluered,RdBu,Reds,Blues,Picnic,Rainbow,Portland,Jet,H ot,Blackbody,Earth,Electric,Viridis,Cividis. connectgaps Determines whether or not gaps (i.e. {nan} or missing values) in the `z` data are filled in. contours :class:`plotly.graph_objects.surface.Contours` instance or dict with compatible properties customdata Assigns extra data each datum. This may be useful when listening to hover, click and selection events. Note that, "scatter" traces also appends customdata items in the markers DOM elements customdatasrc Sets the source reference on Chart Studio Cloud for customdata . hidesurface Determines whether or not a surface is drawn. For example, set `hidesurface` to False `contours.x.show` to True and `contours.y.show` to True to draw a wire frame plot. hoverinfo Determines which trace information appear on hover. If `none` or `skip` are set, no information is displayed upon hovering. But, if `none` is set, click and hover events are still fired. hoverinfosrc Sets the source reference on Chart Studio Cloud for hoverinfo . hoverlabel :class:`plotly.graph_objects.surface.Hoverlabel` instance or dict with compatible properties hovertemplate Template string used for rendering the information that appear on hover box. Note that this will override `hoverinfo`. Variables are inserted using %{variable}, for example "y: %{y}". Numbers are formatted using d3-format's syntax %{variable:d3-format}, for example "Price: %{y:$.2f}". https://github.com/d3/d3-3.x-api- reference/blob/master/Formatting.md#d3_format for details on the formatting syntax. Dates are formatted using d3-time-format's syntax %{variable|d3-time- format}, for example "Day: %{2019-01-01|%A}". https://github.com/d3/d3-time-format#locale_format for details on the date formatting syntax. The variables available in `hovertemplate` are the ones emitted as event data described at this link https://plotly.com/javascript/plotlyjs-events/#event- data. Additionally, every attributes that can be specified per-point (the ones that are `arrayOk: true`) are available. Anything contained in tag `<extra>` is displayed in the secondary box, for example "<extra>{fullData.name}</extra>". To hide the secondary box completely, use an empty tag `<extra></extra>`. hovertemplatesrc Sets the source reference on Chart Studio Cloud for hovertemplate . hovertext Same as `text`. hovertextsrc Sets the source reference on Chart Studio Cloud for hovertext . ids Assigns id labels to each datum. These ids for object constancy of data points during animation. Should be an array of strings, not numbers or any other type. idssrc Sets the source reference on Chart Studio Cloud for ids . legendgroup Sets the legend group for this trace. Traces part of the same legend group hide/show at the same time when toggling legend items. lighting :class:`plotly.graph_objects.surface.Lighting` instance or dict with compatible properties lightposition :class:`plotly.graph_objects.surface.Lightposition` instance or dict with compatible properties meta Assigns extra meta information associated with this trace that can be used in various text attributes. Attributes such as trace `name`, graph, axis and colorbar `title.text`, annotation `text` `rangeselector`, `updatemenues` and `sliders` `label` text all support `meta`. To access the trace `meta` values in an attribute in the same trace, simply use `%{meta[i]}` where `i` is the index or key of the `meta` item in question. To access trace `meta` in layout attributes, use `%{data[n[.meta[i]}` where `i` is the index or key of the `meta` and `n` is the trace index. metasrc Sets the source reference on Chart Studio Cloud for meta . name Sets the trace name. The trace name appear as the legend item and on hover. opacity Sets the opacity of the surface. Please note that in the case of using high `opacity` values for example a value greater than or equal to 0.5 on two surfaces (and 0.25 with four surfaces), an overlay of multiple transparent surfaces may not perfectly be sorted in depth by the webgl API. This behavior may be improved in the near future and is subject to change. opacityscale Sets the opacityscale. The opacityscale must be an array containing arrays mapping a normalized value to an opacity value. At minimum, a mapping for the lowest (0) and highest (1) values are required. For example, `[[0, 1], [0.5, 0.2], [1, 1]]` means that higher/lower values would have higher opacity values and those in the middle would be more transparent Alternatively, `opacityscale` may be a palette name string of the following list: 'min', 'max', 'extremes' and 'uniform'. The default is 'uniform'. reversescale Reverses the color mapping if true. If true, `cmin` will correspond to the last color in the array and `cmax` will correspond to the first color. scene Sets a reference between this trace's 3D coordinate system and a 3D scene. If "scene" (the default value), the (x,y,z) coordinates refer to `layout.scene`. If "scene2", the (x,y,z) coordinates refer to `layout.scene2`, and so on. showlegend Determines whether or not an item corresponding to this trace is shown in the legend. showscale Determines whether or not a colorbar is displayed for this trace. stream :class:`plotly.graph_objects.surface.Stream` instance or dict with compatible properties surfacecolor Sets the surface color values, used for setting a color scale independent of `z`. surfacecolorsrc Sets the source reference on Chart Studio Cloud for surfacecolor . text Sets the text elements associated with each z value. If trace `hoverinfo` contains a "text" flag and "hovertext" is not set, these elements will be seen in the hover labels. textsrc Sets the source reference on Chart Studio Cloud for text . uid Assign an id to this trace, Use this to provide object constancy between traces during animations and transitions. uirevision Controls persistence of some user-driven changes to the trace: `constraintrange` in `parcoords` traces, as well as some `editable: true` modifications such as `name` and `colorbar.title`. Defaults to `layout.uirevision`. Note that other user-driven trace attribute changes are controlled by `layout` attributes: `trace.visible` is controlled by `layout.legend.uirevision`, `selectedpoints` is controlled by `layout.selectionrevision`, and `colorbar.(x|y)` (accessible with `config: {editable: true}`) is controlled by `layout.editrevision`. Trace changes are tracked by `uid`, which only falls back on trace index if no `uid` is provided. So if your app can add/remove traces before the end of the `data` array, such that the same trace has a different index, you can still preserve user-driven changes if you give each trace a `uid` that stays with it as it moves. visible Determines whether or not this trace is visible. If "legendonly", the trace is not drawn, but can appear as a legend item (provided that the legend itself is visible). x Sets the x coordinates. xcalendar Sets the calendar system to use with `x` date data. xsrc Sets the source reference on Chart Studio Cloud for x . y Sets the y coordinates. ycalendar Sets the calendar system to use with `y` date data. ysrc Sets the source reference on Chart Studio Cloud for y . z Sets the z coordinates. zcalendar Sets the calendar system to use with `z` date data. zsrc Sets the source reference on Chart Studio Cloud for z . row : int or None (default) Subplot row index (starting from 1) for the trace to be added. Only valid if figure was created using `plotly.tools.make_subplots` col : int or None (default) Subplot col index (starting from 1) for the trace to be added. Only valid if figure was created using `plotly.tools.make_subplots` Returns ------- FigureWidget """ from plotly.graph_objs import Surface new_trace = Surface( autocolorscale=autocolorscale, cauto=cauto, cmax=cmax, cmid=cmid, cmin=cmin, coloraxis=coloraxis, colorbar=colorbar, colorscale=colorscale, connectgaps=connectgaps, contours=contours, customdata=customdata, customdatasrc=customdatasrc, hidesurface=hidesurface, hoverinfo=hoverinfo, hoverinfosrc=hoverinfosrc, hoverlabel=hoverlabel, hovertemplate=hovertemplate, hovertemplatesrc=hovertemplatesrc, hovertext=hovertext, hovertextsrc=hovertextsrc, ids=ids, idssrc=idssrc, legendgroup=legendgroup, lighting=lighting, lightposition=lightposition, meta=meta, metasrc=metasrc, name=name, opacity=opacity, opacityscale=opacityscale, reversescale=reversescale, scene=scene, showlegend=showlegend, showscale=showscale, stream=stream, surfacecolor=surfacecolor, surfacecolorsrc=surfacecolorsrc, text=text, textsrc=textsrc, uid=uid, uirevision=uirevision, visible=visible, x=x, xcalendar=xcalendar, xsrc=xsrc, y=y, ycalendar=ycalendar, ysrc=ysrc, z=z, zcalendar=zcalendar, zsrc=zsrc, **kwargs ) return self.add_trace(new_trace, row=row, col=col) def add_table( self, cells=None, columnorder=None, columnordersrc=None, columnwidth=None, columnwidthsrc=None, customdata=None, customdatasrc=None, domain=None, header=None, hoverinfo=None, hoverinfosrc=None, hoverlabel=None, ids=None, idssrc=None, meta=None, metasrc=None, name=None, stream=None, uid=None, uirevision=None, visible=None, row=None, col=None, **kwargs ): """ Add a new Table trace Table view for detailed data viewing. The data are arranged in a grid of rows and columns. Most styling can be specified for columns, rows or individual cells. Table is using a column- major order, ie. the grid is represented as a vector of column vectors. Parameters ---------- cells :class:`plotly.graph_objects.table.Cells` instance or dict with compatible properties columnorder Specifies the rendered order of the data columns; for example, a value `2` at position `0` means that column index `0` in the data will be rendered as the third column, as columns have an index base of zero. columnordersrc Sets the source reference on Chart Studio Cloud for columnorder . columnwidth The width of columns expressed as a ratio. Columns fill the available width in proportion of their specified column widths. columnwidthsrc Sets the source reference on Chart Studio Cloud for columnwidth . customdata Assigns extra data each datum. This may be useful when listening to hover, click and selection events. Note that, "scatter" traces also appends customdata items in the markers DOM elements customdatasrc Sets the source reference on Chart Studio Cloud for customdata . domain :class:`plotly.graph_objects.table.Domain` instance or dict with compatible properties header :class:`plotly.graph_objects.table.Header` instance or dict with compatible properties hoverinfo Determines which trace information appear on hover. If `none` or `skip` are set, no information is displayed upon hovering. But, if `none` is set, click and hover events are still fired. hoverinfosrc Sets the source reference on Chart Studio Cloud for hoverinfo . hoverlabel :class:`plotly.graph_objects.table.Hoverlabel` instance or dict with compatible properties ids Assigns id labels to each datum. These ids for object constancy of data points during animation. Should be an array of strings, not numbers or any other type. idssrc Sets the source reference on Chart Studio Cloud for ids . meta Assigns extra meta information associated with this trace that can be used in various text attributes. Attributes such as trace `name`, graph, axis and colorbar `title.text`, annotation `text` `rangeselector`, `updatemenues` and `sliders` `label` text all support `meta`. To access the trace `meta` values in an attribute in the same trace, simply use `%{meta[i]}` where `i` is the index or key of the `meta` item in question. To access trace `meta` in layout attributes, use `%{data[n[.meta[i]}` where `i` is the index or key of the `meta` and `n` is the trace index. metasrc Sets the source reference on Chart Studio Cloud for meta . name Sets the trace name. The trace name appear as the legend item and on hover. stream :class:`plotly.graph_objects.table.Stream` instance or dict with compatible properties uid Assign an id to this trace, Use this to provide object constancy between traces during animations and transitions. uirevision Controls persistence of some user-driven changes to the trace: `constraintrange` in `parcoords` traces, as well as some `editable: true` modifications such as `name` and `colorbar.title`. Defaults to `layout.uirevision`. Note that other user-driven trace attribute changes are controlled by `layout` attributes: `trace.visible` is controlled by `layout.legend.uirevision`, `selectedpoints` is controlled by `layout.selectionrevision`, and `colorbar.(x|y)` (accessible with `config: {editable: true}`) is controlled by `layout.editrevision`. Trace changes are tracked by `uid`, which only falls back on trace index if no `uid` is provided. So if your app can add/remove traces before the end of the `data` array, such that the same trace has a different index, you can still preserve user-driven changes if you give each trace a `uid` that stays with it as it moves. visible Determines whether or not this trace is visible. If "legendonly", the trace is not drawn, but can appear as a legend item (provided that the legend itself is visible). row : int or None (default) Subplot row index (starting from 1) for the trace to be added. Only valid if figure was created using `plotly.tools.make_subplots` col : int or None (default) Subplot col index (starting from 1) for the trace to be added. Only valid if figure was created using `plotly.tools.make_subplots` Returns ------- FigureWidget """ from plotly.graph_objs import Table new_trace = Table( cells=cells, columnorder=columnorder, columnordersrc=columnordersrc, columnwidth=columnwidth, columnwidthsrc=columnwidthsrc, customdata=customdata, customdatasrc=customdatasrc, domain=domain, header=header, hoverinfo=hoverinfo, hoverinfosrc=hoverinfosrc, hoverlabel=hoverlabel, ids=ids, idssrc=idssrc, meta=meta, metasrc=metasrc, name=name, stream=stream, uid=uid, uirevision=uirevision, visible=visible, **kwargs ) return self.add_trace(new_trace, row=row, col=col) def add_treemap( self, branchvalues=None, count=None, customdata=None, customdatasrc=None, domain=None, hoverinfo=None, hoverinfosrc=None, hoverlabel=None, hovertemplate=None, hovertemplatesrc=None, hovertext=None, hovertextsrc=None, ids=None, idssrc=None, insidetextfont=None, labels=None, labelssrc=None, level=None, marker=None, maxdepth=None, meta=None, metasrc=None, name=None, opacity=None, outsidetextfont=None, parents=None, parentssrc=None, pathbar=None, sort=None, stream=None, text=None, textfont=None, textinfo=None, textposition=None, textsrc=None, texttemplate=None, texttemplatesrc=None, tiling=None, uid=None, uirevision=None, values=None, valuessrc=None, visible=None, row=None, col=None, **kwargs ): """ Add a new Treemap trace Visualize hierarchal data from leaves (and/or outer branches) towards root with rectangles. The treemap sectors are determined by the entries in "labels" or "ids" and in "parents". Parameters ---------- branchvalues Determines how the items in `values` are summed. When set to "total", items in `values` are taken to be value of all its descendants. When set to "remainder", items in `values` corresponding to the root and the branches sectors are taken to be the extra part not part of the sum of the values at their leaves. count Determines default for `values` when it is not provided, by inferring a 1 for each of the "leaves" and/or "branches", otherwise 0. customdata Assigns extra data each datum. This may be useful when listening to hover, click and selection events. Note that, "scatter" traces also appends customdata items in the markers DOM elements customdatasrc Sets the source reference on Chart Studio Cloud for customdata . domain :class:`plotly.graph_objects.treemap.Domain` instance or dict with compatible properties hoverinfo Determines which trace information appear on hover. If `none` or `skip` are set, no information is displayed upon hovering. But, if `none` is set, click and hover events are still fired. hoverinfosrc Sets the source reference on Chart Studio Cloud for hoverinfo . hoverlabel :class:`plotly.graph_objects.treemap.Hoverlabel` instance or dict with compatible properties hovertemplate Template string used for rendering the information that appear on hover box. Note that this will override `hoverinfo`. Variables are inserted using %{variable}, for example "y: %{y}". Numbers are formatted using d3-format's syntax %{variable:d3-format}, for example "Price: %{y:$.2f}". https://github.com/d3/d3-3.x-api- reference/blob/master/Formatting.md#d3_format for details on the formatting syntax. Dates are formatted using d3-time-format's syntax %{variable|d3-time- format}, for example "Day: %{2019-01-01|%A}". https://github.com/d3/d3-time-format#locale_format for details on the date formatting syntax. The variables available in `hovertemplate` are the ones emitted as event data described at this link https://plotly.com/javascript/plotlyjs-events/#event- data. Additionally, every attributes that can be specified per-point (the ones that are `arrayOk: true`) are available. variables `currentPath`, `root`, `entry`, `percentRoot`, `percentEntry` and `percentParent`. Anything contained in tag `<extra>` is displayed in the secondary box, for example "<extra>{fullData.name}</extra>". To hide the secondary box completely, use an empty tag `<extra></extra>`. hovertemplatesrc Sets the source reference on Chart Studio Cloud for hovertemplate . hovertext Sets hover text elements associated with each sector. If a single string, the same string appears for all data points. If an array of string, the items are mapped in order of this trace's sectors. To be seen, trace `hoverinfo` must contain a "text" flag. hovertextsrc Sets the source reference on Chart Studio Cloud for hovertext . ids Assigns id labels to each datum. These ids for object constancy of data points during animation. Should be an array of strings, not numbers or any other type. idssrc Sets the source reference on Chart Studio Cloud for ids . insidetextfont Sets the font used for `textinfo` lying inside the sector. labels Sets the labels of each of the sectors. labelssrc Sets the source reference on Chart Studio Cloud for labels . level Sets the level from which this trace hierarchy is rendered. Set `level` to `''` to start from the root node in the hierarchy. Must be an "id" if `ids` is filled in, otherwise plotly attempts to find a matching item in `labels`. marker :class:`plotly.graph_objects.treemap.Marker` instance or dict with compatible properties maxdepth Sets the number of rendered sectors from any given `level`. Set `maxdepth` to "-1" to render all the levels in the hierarchy. meta Assigns extra meta information associated with this trace that can be used in various text attributes. Attributes such as trace `name`, graph, axis and colorbar `title.text`, annotation `text` `rangeselector`, `updatemenues` and `sliders` `label` text all support `meta`. To access the trace `meta` values in an attribute in the same trace, simply use `%{meta[i]}` where `i` is the index or key of the `meta` item in question. To access trace `meta` in layout attributes, use `%{data[n[.meta[i]}` where `i` is the index or key of the `meta` and `n` is the trace index. metasrc Sets the source reference on Chart Studio Cloud for meta . name Sets the trace name. The trace name appear as the legend item and on hover. opacity Sets the opacity of the trace. outsidetextfont Sets the font used for `textinfo` lying outside the sector. This option refers to the root of the hierarchy presented on top left corner of a treemap graph. Please note that if a hierarchy has multiple root nodes, this option won't have any effect and `insidetextfont` would be used. parents Sets the parent sectors for each of the sectors. Empty string items '' are understood to reference the root node in the hierarchy. If `ids` is filled, `parents` items are understood to be "ids" themselves. When `ids` is not set, plotly attempts to find matching items in `labels`, but beware they must be unique. parentssrc Sets the source reference on Chart Studio Cloud for parents . pathbar :class:`plotly.graph_objects.treemap.Pathbar` instance or dict with compatible properties sort Determines whether or not the sectors are reordered from largest to smallest. stream :class:`plotly.graph_objects.treemap.Stream` instance or dict with compatible properties text Sets text elements associated with each sector. If trace `textinfo` contains a "text" flag, these elements will be seen on the chart. If trace `hoverinfo` contains a "text" flag and "hovertext" is not set, these elements will be seen in the hover labels. textfont Sets the font used for `textinfo`. textinfo Determines which trace information appear on the graph. textposition Sets the positions of the `text` elements. textsrc Sets the source reference on Chart Studio Cloud for text . texttemplate Template string used for rendering the information text that appear on points. Note that this will override `textinfo`. Variables are inserted using %{variable}, for example "y: %{y}". Numbers are formatted using d3-format's syntax %{variable:d3-format}, for example "Price: %{y:$.2f}". https://github.com/d3/d3-3.x-api- reference/blob/master/Formatting.md#d3_format for details on the formatting syntax. Dates are formatted using d3-time-format's syntax %{variable|d3-time- format}, for example "Day: %{2019-01-01|%A}". https://github.com/d3/d3-time-format#locale_format for details on the date formatting syntax. Every attributes that can be specified per-point (the ones that are `arrayOk: true`) are available. variables `currentPath`, `root`, `entry`, `percentRoot`, `percentEntry`, `percentParent`, `label` and `value`. texttemplatesrc Sets the source reference on Chart Studio Cloud for texttemplate . tiling :class:`plotly.graph_objects.treemap.Tiling` instance or dict with compatible properties uid Assign an id to this trace, Use this to provide object constancy between traces during animations and transitions. uirevision Controls persistence of some user-driven changes to the trace: `constraintrange` in `parcoords` traces, as well as some `editable: true` modifications such as `name` and `colorbar.title`. Defaults to `layout.uirevision`. Note that other user-driven trace attribute changes are controlled by `layout` attributes: `trace.visible` is controlled by `layout.legend.uirevision`, `selectedpoints` is controlled by `layout.selectionrevision`, and `colorbar.(x|y)` (accessible with `config: {editable: true}`) is controlled by `layout.editrevision`. Trace changes are tracked by `uid`, which only falls back on trace index if no `uid` is provided. So if your app can add/remove traces before the end of the `data` array, such that the same trace has a different index, you can still preserve user-driven changes if you give each trace a `uid` that stays with it as it moves. values Sets the values associated with each of the sectors. Use with `branchvalues` to determine how the values are summed. valuessrc Sets the source reference on Chart Studio Cloud for values . visible Determines whether or not this trace is visible. If "legendonly", the trace is not drawn, but can appear as a legend item (provided that the legend itself is visible). row : int or None (default) Subplot row index (starting from 1) for the trace to be added. Only valid if figure was created using `plotly.tools.make_subplots` col : int or None (default) Subplot col index (starting from 1) for the trace to be added. Only valid if figure was created using `plotly.tools.make_subplots` Returns ------- FigureWidget """ from plotly.graph_objs import Treemap new_trace = Treemap( branchvalues=branchvalues, count=count, customdata=customdata, customdatasrc=customdatasrc, domain=domain, hoverinfo=hoverinfo, hoverinfosrc=hoverinfosrc, hoverlabel=hoverlabel, hovertemplate=hovertemplate, hovertemplatesrc=hovertemplatesrc, hovertext=hovertext, hovertextsrc=hovertextsrc, ids=ids, idssrc=idssrc, insidetextfont=insidetextfont, labels=labels, labelssrc=labelssrc, level=level, marker=marker, maxdepth=maxdepth, meta=meta, metasrc=metasrc, name=name, opacity=opacity, outsidetextfont=outsidetextfont, parents=parents, parentssrc=parentssrc, pathbar=pathbar, sort=sort, stream=stream, text=text, textfont=textfont, textinfo=textinfo, textposition=textposition, textsrc=textsrc, texttemplate=texttemplate, texttemplatesrc=texttemplatesrc, tiling=tiling, uid=uid, uirevision=uirevision, values=values, valuessrc=valuessrc, visible=visible, **kwargs ) return self.add_trace(new_trace, row=row, col=col) def add_violin( self, alignmentgroup=None, bandwidth=None, box=None, customdata=None, customdatasrc=None, fillcolor=None, hoverinfo=None, hoverinfosrc=None, hoverlabel=None, hoveron=None, hovertemplate=None, hovertemplatesrc=None, hovertext=None, hovertextsrc=None, ids=None, idssrc=None, jitter=None, legendgroup=None, line=None, marker=None, meanline=None, meta=None, metasrc=None, name=None, offsetgroup=None, opacity=None, orientation=None, pointpos=None, points=None, scalegroup=None, scalemode=None, selected=None, selectedpoints=None, showlegend=None, side=None, span=None, spanmode=None, stream=None, text=None, textsrc=None, uid=None, uirevision=None, unselected=None, visible=None, width=None, x=None, x0=None, xaxis=None, xsrc=None, y=None, y0=None, yaxis=None, ysrc=None, row=None, col=None, secondary_y=None, **kwargs ): """ Add a new Violin trace In vertical (horizontal) violin plots, statistics are computed using `y` (`x`) values. By supplying an `x` (`y`) array, one violin per distinct x (y) value is drawn If no `x` (`y`) list is provided, a single violin is drawn. That violin position is then positioned with with `name` or with `x0` (`y0`) if provided. Parameters ---------- alignmentgroup Set several traces linked to the same position axis or matching axes to the same alignmentgroup. This controls whether bars compute their positional range dependently or independently. bandwidth Sets the bandwidth used to compute the kernel density estimate. By default, the bandwidth is determined by Silverman's rule of thumb. box :class:`plotly.graph_objects.violin.Box` instance or dict with compatible properties customdata Assigns extra data each datum. This may be useful when listening to hover, click and selection events. Note that, "scatter" traces also appends customdata items in the markers DOM elements customdatasrc Sets the source reference on Chart Studio Cloud for customdata . fillcolor Sets the fill color. Defaults to a half-transparent variant of the line color, marker color, or marker line color, whichever is available. hoverinfo Determines which trace information appear on hover. If `none` or `skip` are set, no information is displayed upon hovering. But, if `none` is set, click and hover events are still fired. hoverinfosrc Sets the source reference on Chart Studio Cloud for hoverinfo . hoverlabel :class:`plotly.graph_objects.violin.Hoverlabel` instance or dict with compatible properties hoveron Do the hover effects highlight individual violins or sample points or the kernel density estimate or any combination of them? hovertemplate Template string used for rendering the information that appear on hover box. Note that this will override `hoverinfo`. Variables are inserted using %{variable}, for example "y: %{y}". Numbers are formatted using d3-format's syntax %{variable:d3-format}, for example "Price: %{y:$.2f}". https://github.com/d3/d3-3.x-api- reference/blob/master/Formatting.md#d3_format for details on the formatting syntax. Dates are formatted using d3-time-format's syntax %{variable|d3-time- format}, for example "Day: %{2019-01-01|%A}". https://github.com/d3/d3-time-format#locale_format for details on the date formatting syntax. The variables available in `hovertemplate` are the ones emitted as event data described at this link https://plotly.com/javascript/plotlyjs-events/#event- data. Additionally, every attributes that can be specified per-point (the ones that are `arrayOk: true`) are available. Anything contained in tag `<extra>` is displayed in the secondary box, for example "<extra>{fullData.name}</extra>". To hide the secondary box completely, use an empty tag `<extra></extra>`. hovertemplatesrc Sets the source reference on Chart Studio Cloud for hovertemplate . hovertext Same as `text`. hovertextsrc Sets the source reference on Chart Studio Cloud for hovertext . ids Assigns id labels to each datum. These ids for object constancy of data points during animation. Should be an array of strings, not numbers or any other type. idssrc Sets the source reference on Chart Studio Cloud for ids . jitter Sets the amount of jitter in the sample points drawn. If 0, the sample points align along the distribution axis. If 1, the sample points are drawn in a random jitter of width equal to the width of the violins. legendgroup Sets the legend group for this trace. Traces part of the same legend group hide/show at the same time when toggling legend items. line :class:`plotly.graph_objects.violin.Line` instance or dict with compatible properties marker :class:`plotly.graph_objects.violin.Marker` instance or dict with compatible properties meanline :class:`plotly.graph_objects.violin.Meanline` instance or dict with compatible properties meta Assigns extra meta information associated with this trace that can be used in various text attributes. Attributes such as trace `name`, graph, axis and colorbar `title.text`, annotation `text` `rangeselector`, `updatemenues` and `sliders` `label` text all support `meta`. To access the trace `meta` values in an attribute in the same trace, simply use `%{meta[i]}` where `i` is the index or key of the `meta` item in question. To access trace `meta` in layout attributes, use `%{data[n[.meta[i]}` where `i` is the index or key of the `meta` and `n` is the trace index. metasrc Sets the source reference on Chart Studio Cloud for meta . name Sets the trace name. The trace name appear as the legend item and on hover. For violin traces, the name will also be used for the position coordinate, if `x` and `x0` (`y` and `y0` if horizontal) are missing and the position axis is categorical. Note that the trace name is also used as a default value for attribute `scalegroup` (please see its description for details). offsetgroup Set several traces linked to the same position axis or matching axes to the same offsetgroup where bars of the same position coordinate will line up. opacity Sets the opacity of the trace. orientation Sets the orientation of the violin(s). If "v" ("h"), the distribution is visualized along the vertical (horizontal). pointpos Sets the position of the sample points in relation to the violins. If 0, the sample points are places over the center of the violins. Positive (negative) values correspond to positions to the right (left) for vertical violins and above (below) for horizontal violins. points If "outliers", only the sample points lying outside the whiskers are shown If "suspectedoutliers", the outlier points are shown and points either less than 4*Q1-3*Q3 or greater than 4*Q3-3*Q1 are highlighted (see `outliercolor`) If "all", all sample points are shown If False, only the violins are shown with no sample points. Defaults to "suspectedoutliers" when `marker.outliercolor` or `marker.line.outliercolor` is set, otherwise defaults to "outliers". scalegroup If there are multiple violins that should be sized according to to some metric (see `scalemode`), link them by providing a non-empty group id here shared by every trace in the same group. If a violin's `width` is undefined, `scalegroup` will default to the trace's name. In this case, violins with the same names will be linked together scalemode Sets the metric by which the width of each violin is determined."width" means each violin has the same (max) width*count* means the violins are scaled by the number of sample points makingup each violin. selected :class:`plotly.graph_objects.violin.Selected` instance or dict with compatible properties selectedpoints Array containing integer indices of selected points. Has an effect only for traces that support selections. Note that an empty array means an empty selection where the `unselected` are turned on for all points, whereas, any other non-array values means no selection all where the `selected` and `unselected` styles have no effect. showlegend Determines whether or not an item corresponding to this trace is shown in the legend. side Determines on which side of the position value the density function making up one half of a violin is plotted. Useful when comparing two violin traces under "overlay" mode, where one trace has `side` set to "positive" and the other to "negative". span Sets the span in data space for which the density function will be computed. Has an effect only when `spanmode` is set to "manual". spanmode Sets the method by which the span in data space where the density function will be computed. "soft" means the span goes from the sample's minimum value minus two bandwidths to the sample's maximum value plus two bandwidths. "hard" means the span goes from the sample's minimum to its maximum value. For custom span settings, use mode "manual" and fill in the `span` attribute. stream :class:`plotly.graph_objects.violin.Stream` instance or dict with compatible properties text Sets the text elements associated with each sample value. If a single string, the same string appears over all the data points. If an array of string, the items are mapped in order to the this trace's (x,y) coordinates. To be seen, trace `hoverinfo` must contain a "text" flag. textsrc Sets the source reference on Chart Studio Cloud for text . uid Assign an id to this trace, Use this to provide object constancy between traces during animations and transitions. uirevision Controls persistence of some user-driven changes to the trace: `constraintrange` in `parcoords` traces, as well as some `editable: true` modifications such as `name` and `colorbar.title`. Defaults to `layout.uirevision`. Note that other user-driven trace attribute changes are controlled by `layout` attributes: `trace.visible` is controlled by `layout.legend.uirevision`, `selectedpoints` is controlled by `layout.selectionrevision`, and `colorbar.(x|y)` (accessible with `config: {editable: true}`) is controlled by `layout.editrevision`. Trace changes are tracked by `uid`, which only falls back on trace index if no `uid` is provided. So if your app can add/remove traces before the end of the `data` array, such that the same trace has a different index, you can still preserve user-driven changes if you give each trace a `uid` that stays with it as it moves. unselected :class:`plotly.graph_objects.violin.Unselected` instance or dict with compatible properties visible Determines whether or not this trace is visible. If "legendonly", the trace is not drawn, but can appear as a legend item (provided that the legend itself is visible). width Sets the width of the violin in data coordinates. If 0 (default value) the width is automatically selected based on the positions of other violin traces in the same subplot. x Sets the x sample data or coordinates. See overview for more info. x0 Sets the x coordinate for single-box traces or the starting coordinate for multi-box traces set using q1/median/q3. See overview for more info. xaxis Sets a reference between this trace's x coordinates and a 2D cartesian x axis. If "x" (the default value), the x coordinates refer to `layout.xaxis`. If "x2", the x coordinates refer to `layout.xaxis2`, and so on. xsrc Sets the source reference on Chart Studio Cloud for x . y Sets the y sample data or coordinates. See overview for more info. y0 Sets the y coordinate for single-box traces or the starting coordinate for multi-box traces set using q1/median/q3. See overview for more info. yaxis Sets a reference between this trace's y coordinates and a 2D cartesian y axis. If "y" (the default value), the y coordinates refer to `layout.yaxis`. If "y2", the y coordinates refer to `layout.yaxis2`, and so on. ysrc Sets the source reference on Chart Studio Cloud for y . row : int or None (default) Subplot row index (starting from 1) for the trace to be added. Only valid if figure was created using `plotly.tools.make_subplots` col : int or None (default) Subplot col index (starting from 1) for the trace to be added. Only valid if figure was created using `plotly.tools.make_subplots` secondary_y: boolean or None (default None) If True, associate this trace with the secondary y-axis of the subplot at the specified row and col. Only valid if all of the following conditions are satisfied: * The figure was created using `plotly.subplots.make_subplots`. * The row and col arguments are not None * The subplot at the specified row and col has type xy (which is the default) and secondary_y True. These properties are specified in the specs argument to make_subplots. See the make_subplots docstring for more info. Returns ------- FigureWidget """ from plotly.graph_objs import Violin new_trace = Violin( alignmentgroup=alignmentgroup, bandwidth=bandwidth, box=box, customdata=customdata, customdatasrc=customdatasrc, fillcolor=fillcolor, hoverinfo=hoverinfo, hoverinfosrc=hoverinfosrc, hoverlabel=hoverlabel, hoveron=hoveron, hovertemplate=hovertemplate, hovertemplatesrc=hovertemplatesrc, hovertext=hovertext, hovertextsrc=hovertextsrc, ids=ids, idssrc=idssrc, jitter=jitter, legendgroup=legendgroup, line=line, marker=marker, meanline=meanline, meta=meta, metasrc=metasrc, name=name, offsetgroup=offsetgroup, opacity=opacity, orientation=orientation, pointpos=pointpos, points=points, scalegroup=scalegroup, scalemode=scalemode, selected=selected, selectedpoints=selectedpoints, showlegend=showlegend, side=side, span=span, spanmode=spanmode, stream=stream, text=text, textsrc=textsrc, uid=uid, uirevision=uirevision, unselected=unselected, visible=visible, width=width, x=x, x0=x0, xaxis=xaxis, xsrc=xsrc, y=y, y0=y0, yaxis=yaxis, ysrc=ysrc, **kwargs ) return self.add_trace(new_trace, row=row, col=col, secondary_y=secondary_y) def add_volume( self, autocolorscale=None, caps=None, cauto=None, cmax=None, cmid=None, cmin=None, coloraxis=None, colorbar=None, colorscale=None, contour=None, customdata=None, customdatasrc=None, flatshading=None, hoverinfo=None, hoverinfosrc=None, hoverlabel=None, hovertemplate=None, hovertemplatesrc=None, hovertext=None, hovertextsrc=None, ids=None, idssrc=None, isomax=None, isomin=None, legendgroup=None, lighting=None, lightposition=None, meta=None, metasrc=None, name=None, opacity=None, opacityscale=None, reversescale=None, scene=None, showlegend=None, showscale=None, slices=None, spaceframe=None, stream=None, surface=None, text=None, textsrc=None, uid=None, uirevision=None, value=None, valuesrc=None, visible=None, x=None, xsrc=None, y=None, ysrc=None, z=None, zsrc=None, row=None, col=None, **kwargs ): """ Add a new Volume trace Draws volume trace between iso-min and iso-max values with coordinates given by four 1-dimensional arrays containing the `value`, `x`, `y` and `z` of every vertex of a uniform or non- uniform 3-D grid. Horizontal or vertical slices, caps as well as spaceframe between iso-min and iso-max values could also be drawn using this trace. Parameters ---------- autocolorscale Determines whether the colorscale is a default palette (`autocolorscale: true`) or the palette determined by `colorscale`. In case `colorscale` is unspecified or `autocolorscale` is true, the default palette will be chosen according to whether numbers in the `color` array are all positive, all negative or mixed. caps :class:`plotly.graph_objects.volume.Caps` instance or dict with compatible properties cauto Determines whether or not the color domain is computed with respect to the input data (here `value`) or the bounds set in `cmin` and `cmax` Defaults to `false` when `cmin` and `cmax` are set by the user. cmax Sets the upper bound of the color domain. Value should have the same units as `value` and if set, `cmin` must be set as well. cmid Sets the mid-point of the color domain by scaling `cmin` and/or `cmax` to be equidistant to this point. Value should have the same units as `value`. Has no effect when `cauto` is `false`. cmin Sets the lower bound of the color domain. Value should have the same units as `value` and if set, `cmax` must be set as well. coloraxis Sets a reference to a shared color axis. References to these shared color axes are "coloraxis", "coloraxis2", "coloraxis3", etc. Settings for these shared color axes are set in the layout, under `layout.coloraxis`, `layout.coloraxis2`, etc. Note that multiple color scales can be linked to the same color axis. colorbar :class:`plotly.graph_objects.volume.ColorBar` instance or dict with compatible properties colorscale Sets the colorscale. The colorscale must be an array containing arrays mapping a normalized value to an rgb, rgba, hex, hsl, hsv, or named color string. At minimum, a mapping for the lowest (0) and highest (1) values are required. For example, `[[0, 'rgb(0,0,255)'], [1, 'rgb(255,0,0)']]`. To control the bounds of the colorscale in color space, use`cmin` and `cmax`. Alternatively, `colorscale` may be a palette name string of the following list: Greys,YlGnBu,Greens,YlOrR d,Bluered,RdBu,Reds,Blues,Picnic,Rainbow,Portland,Jet,H ot,Blackbody,Earth,Electric,Viridis,Cividis. contour :class:`plotly.graph_objects.volume.Contour` instance or dict with compatible properties customdata Assigns extra data each datum. This may be useful when listening to hover, click and selection events. Note that, "scatter" traces also appends customdata items in the markers DOM elements customdatasrc Sets the source reference on Chart Studio Cloud for customdata . flatshading Determines whether or not normal smoothing is applied to the meshes, creating meshes with an angular, low- poly look via flat reflections. hoverinfo Determines which trace information appear on hover. If `none` or `skip` are set, no information is displayed upon hovering. But, if `none` is set, click and hover events are still fired. hoverinfosrc Sets the source reference on Chart Studio Cloud for hoverinfo . hoverlabel :class:`plotly.graph_objects.volume.Hoverlabel` instance or dict with compatible properties hovertemplate Template string used for rendering the information that appear on hover box. Note that this will override `hoverinfo`. Variables are inserted using %{variable}, for example "y: %{y}". Numbers are formatted using d3-format's syntax %{variable:d3-format}, for example "Price: %{y:$.2f}". https://github.com/d3/d3-3.x-api- reference/blob/master/Formatting.md#d3_format for details on the formatting syntax. Dates are formatted using d3-time-format's syntax %{variable|d3-time- format}, for example "Day: %{2019-01-01|%A}". https://github.com/d3/d3-time-format#locale_format for details on the date formatting syntax. The variables available in `hovertemplate` are the ones emitted as event data described at this link https://plotly.com/javascript/plotlyjs-events/#event- data. Additionally, every attributes that can be specified per-point (the ones that are `arrayOk: true`) are available. Anything contained in tag `<extra>` is displayed in the secondary box, for example "<extra>{fullData.name}</extra>". To hide the secondary box completely, use an empty tag `<extra></extra>`. hovertemplatesrc Sets the source reference on Chart Studio Cloud for hovertemplate . hovertext Same as `text`. hovertextsrc Sets the source reference on Chart Studio Cloud for hovertext . ids Assigns id labels to each datum. These ids for object constancy of data points during animation. Should be an array of strings, not numbers or any other type. idssrc Sets the source reference on Chart Studio Cloud for ids . isomax Sets the maximum boundary for iso-surface plot. isomin Sets the minimum boundary for iso-surface plot. legendgroup Sets the legend group for this trace. Traces part of the same legend group hide/show at the same time when toggling legend items. lighting :class:`plotly.graph_objects.volume.Lighting` instance or dict with compatible properties lightposition :class:`plotly.graph_objects.volume.Lightposition` instance or dict with compatible properties meta Assigns extra meta information associated with this trace that can be used in various text attributes. Attributes such as trace `name`, graph, axis and colorbar `title.text`, annotation `text` `rangeselector`, `updatemenues` and `sliders` `label` text all support `meta`. To access the trace `meta` values in an attribute in the same trace, simply use `%{meta[i]}` where `i` is the index or key of the `meta` item in question. To access trace `meta` in layout attributes, use `%{data[n[.meta[i]}` where `i` is the index or key of the `meta` and `n` is the trace index. metasrc Sets the source reference on Chart Studio Cloud for meta . name Sets the trace name. The trace name appear as the legend item and on hover. opacity Sets the opacity of the surface. Please note that in the case of using high `opacity` values for example a value greater than or equal to 0.5 on two surfaces (and 0.25 with four surfaces), an overlay of multiple transparent surfaces may not perfectly be sorted in depth by the webgl API. This behavior may be improved in the near future and is subject to change. opacityscale Sets the opacityscale. The opacityscale must be an array containing arrays mapping a normalized value to an opacity value. At minimum, a mapping for the lowest (0) and highest (1) values are required. For example, `[[0, 1], [0.5, 0.2], [1, 1]]` means that higher/lower values would have higher opacity values and those in the middle would be more transparent Alternatively, `opacityscale` may be a palette name string of the following list: 'min', 'max', 'extremes' and 'uniform'. The default is 'uniform'. reversescale Reverses the color mapping if true. If true, `cmin` will correspond to the last color in the array and `cmax` will correspond to the first color. scene Sets a reference between this trace's 3D coordinate system and a 3D scene. If "scene" (the default value), the (x,y,z) coordinates refer to `layout.scene`. If "scene2", the (x,y,z) coordinates refer to `layout.scene2`, and so on. showlegend Determines whether or not an item corresponding to this trace is shown in the legend. showscale Determines whether or not a colorbar is displayed for this trace. slices :class:`plotly.graph_objects.volume.Slices` instance or dict with compatible properties spaceframe :class:`plotly.graph_objects.volume.Spaceframe` instance or dict with compatible properties stream :class:`plotly.graph_objects.volume.Stream` instance or dict with compatible properties surface :class:`plotly.graph_objects.volume.Surface` instance or dict with compatible properties text Sets the text elements associated with the vertices. If trace `hoverinfo` contains a "text" flag and "hovertext" is not set, these elements will be seen in the hover labels. textsrc Sets the source reference on Chart Studio Cloud for text . uid Assign an id to this trace, Use this to provide object constancy between traces during animations and transitions. uirevision Controls persistence of some user-driven changes to the trace: `constraintrange` in `parcoords` traces, as well as some `editable: true` modifications such as `name` and `colorbar.title`. Defaults to `layout.uirevision`. Note that other user-driven trace attribute changes are controlled by `layout` attributes: `trace.visible` is controlled by `layout.legend.uirevision`, `selectedpoints` is controlled by `layout.selectionrevision`, and `colorbar.(x|y)` (accessible with `config: {editable: true}`) is controlled by `layout.editrevision`. Trace changes are tracked by `uid`, which only falls back on trace index if no `uid` is provided. So if your app can add/remove traces before the end of the `data` array, such that the same trace has a different index, you can still preserve user-driven changes if you give each trace a `uid` that stays with it as it moves. value Sets the 4th dimension (value) of the vertices. valuesrc Sets the source reference on Chart Studio Cloud for value . visible Determines whether or not this trace is visible. If "legendonly", the trace is not drawn, but can appear as a legend item (provided that the legend itself is visible). x Sets the X coordinates of the vertices on X axis. xsrc Sets the source reference on Chart Studio Cloud for x . y Sets the Y coordinates of the vertices on Y axis. ysrc Sets the source reference on Chart Studio Cloud for y . z Sets the Z coordinates of the vertices on Z axis. zsrc Sets the source reference on Chart Studio Cloud for z . row : int or None (default) Subplot row index (starting from 1) for the trace to be added. Only valid if figure was created using `plotly.tools.make_subplots` col : int or None (default) Subplot col index (starting from 1) for the trace to be added. Only valid if figure was created using `plotly.tools.make_subplots` Returns ------- FigureWidget """ from plotly.graph_objs import Volume new_trace = Volume( autocolorscale=autocolorscale, caps=caps, cauto=cauto, cmax=cmax, cmid=cmid, cmin=cmin, coloraxis=coloraxis, colorbar=colorbar, colorscale=colorscale, contour=contour, customdata=customdata, customdatasrc=customdatasrc, flatshading=flatshading, hoverinfo=hoverinfo, hoverinfosrc=hoverinfosrc, hoverlabel=hoverlabel, hovertemplate=hovertemplate, hovertemplatesrc=hovertemplatesrc, hovertext=hovertext, hovertextsrc=hovertextsrc, ids=ids, idssrc=idssrc, isomax=isomax, isomin=isomin, legendgroup=legendgroup, lighting=lighting, lightposition=lightposition, meta=meta, metasrc=metasrc, name=name, opacity=opacity, opacityscale=opacityscale, reversescale=reversescale, scene=scene, showlegend=showlegend, showscale=showscale, slices=slices, spaceframe=spaceframe, stream=stream, surface=surface, text=text, textsrc=textsrc, uid=uid, uirevision=uirevision, value=value, valuesrc=valuesrc, visible=visible, x=x, xsrc=xsrc, y=y, ysrc=ysrc, z=z, zsrc=zsrc, **kwargs ) return self.add_trace(new_trace, row=row, col=col) def add_waterfall( self, alignmentgroup=None, base=None, cliponaxis=None, connector=None, constraintext=None, customdata=None, customdatasrc=None, decreasing=None, dx=None, dy=None, hoverinfo=None, hoverinfosrc=None, hoverlabel=None, hovertemplate=None, hovertemplatesrc=None, hovertext=None, hovertextsrc=None, ids=None, idssrc=None, increasing=None, insidetextanchor=None, insidetextfont=None, legendgroup=None, measure=None, measuresrc=None, meta=None, metasrc=None, name=None, offset=None, offsetgroup=None, offsetsrc=None, opacity=None, orientation=None, outsidetextfont=None, selectedpoints=None, showlegend=None, stream=None, text=None, textangle=None, textfont=None, textinfo=None, textposition=None, textpositionsrc=None, textsrc=None, texttemplate=None, texttemplatesrc=None, totals=None, uid=None, uirevision=None, visible=None, width=None, widthsrc=None, x=None, x0=None, xaxis=None, xperiod=None, xperiod0=None, xperiodalignment=None, xsrc=None, y=None, y0=None, yaxis=None, yperiod=None, yperiod0=None, yperiodalignment=None, ysrc=None, row=None, col=None, secondary_y=None, **kwargs ): """ Add a new Waterfall trace Draws waterfall trace which is useful graph to displays the contribution of various elements (either positive or negative) in a bar chart. The data visualized by the span of the bars is set in `y` if `orientation` is set th "v" (the default) and the labels are set in `x`. By setting `orientation` to "h", the roles are interchanged. Parameters ---------- alignmentgroup Set several traces linked to the same position axis or matching axes to the same alignmentgroup. This controls whether bars compute their positional range dependently or independently. base Sets where the bar base is drawn (in position axis units). cliponaxis Determines whether the text nodes are clipped about the subplot axes. To show the text nodes above axis lines and tick labels, make sure to set `xaxis.layer` and `yaxis.layer` to *below traces*. connector :class:`plotly.graph_objects.waterfall.Connector` instance or dict with compatible properties constraintext Constrain the size of text inside or outside a bar to be no larger than the bar itself. customdata Assigns extra data each datum. This may be useful when listening to hover, click and selection events. Note that, "scatter" traces also appends customdata items in the markers DOM elements customdatasrc Sets the source reference on Chart Studio Cloud for customdata . decreasing :class:`plotly.graph_objects.waterfall.Decreasing` instance or dict with compatible properties dx Sets the x coordinate step. See `x0` for more info. dy Sets the y coordinate step. See `y0` for more info. hoverinfo Determines which trace information appear on hover. If `none` or `skip` are set, no information is displayed upon hovering. But, if `none` is set, click and hover events are still fired. hoverinfosrc Sets the source reference on Chart Studio Cloud for hoverinfo . hoverlabel :class:`plotly.graph_objects.waterfall.Hoverlabel` instance or dict with compatible properties hovertemplate Template string used for rendering the information that appear on hover box. Note that this will override `hoverinfo`. Variables are inserted using %{variable}, for example "y: %{y}". Numbers are formatted using d3-format's syntax %{variable:d3-format}, for example "Price: %{y:$.2f}". https://github.com/d3/d3-3.x-api- reference/blob/master/Formatting.md#d3_format for details on the formatting syntax. Dates are formatted using d3-time-format's syntax %{variable|d3-time- format}, for example "Day: %{2019-01-01|%A}". https://github.com/d3/d3-time-format#locale_format for details on the date formatting syntax. The variables available in `hovertemplate` are the ones emitted as event data described at this link https://plotly.com/javascript/plotlyjs-events/#event- data. Additionally, every attributes that can be specified per-point (the ones that are `arrayOk: true`) are available. variables `initial`, `delta` and `final`. Anything contained in tag `<extra>` is displayed in the secondary box, for example "<extra>{fullData.name}</extra>". To hide the secondary box completely, use an empty tag `<extra></extra>`. hovertemplatesrc Sets the source reference on Chart Studio Cloud for hovertemplate . hovertext Sets hover text elements associated with each (x,y) pair. If a single string, the same string appears over all the data points. If an array of string, the items are mapped in order to the this trace's (x,y) coordinates. To be seen, trace `hoverinfo` must contain a "text" flag. hovertextsrc Sets the source reference on Chart Studio Cloud for hovertext . ids Assigns id labels to each datum. These ids for object constancy of data points during animation. Should be an array of strings, not numbers or any other type. idssrc Sets the source reference on Chart Studio Cloud for ids . increasing :class:`plotly.graph_objects.waterfall.Increasing` instance or dict with compatible properties insidetextanchor Determines if texts are kept at center or start/end points in `textposition` "inside" mode. insidetextfont Sets the font used for `text` lying inside the bar. legendgroup Sets the legend group for this trace. Traces part of the same legend group hide/show at the same time when toggling legend items. measure An array containing types of values. By default the values are considered as 'relative'. However; it is possible to use 'total' to compute the sums. Also 'absolute' could be applied to reset the computed total or to declare an initial value where needed. measuresrc Sets the source reference on Chart Studio Cloud for measure . meta Assigns extra meta information associated with this trace that can be used in various text attributes. Attributes such as trace `name`, graph, axis and colorbar `title.text`, annotation `text` `rangeselector`, `updatemenues` and `sliders` `label` text all support `meta`. To access the trace `meta` values in an attribute in the same trace, simply use `%{meta[i]}` where `i` is the index or key of the `meta` item in question. To access trace `meta` in layout attributes, use `%{data[n[.meta[i]}` where `i` is the index or key of the `meta` and `n` is the trace index. metasrc Sets the source reference on Chart Studio Cloud for meta . name Sets the trace name. The trace name appear as the legend item and on hover. offset Shifts the position where the bar is drawn (in position axis units). In "group" barmode, traces that set "offset" will be excluded and drawn in "overlay" mode instead. offsetgroup Set several traces linked to the same position axis or matching axes to the same offsetgroup where bars of the same position coordinate will line up. offsetsrc Sets the source reference on Chart Studio Cloud for offset . opacity Sets the opacity of the trace. orientation Sets the orientation of the bars. With "v" ("h"), the value of the each bar spans along the vertical (horizontal). outsidetextfont Sets the font used for `text` lying outside the bar. selectedpoints Array containing integer indices of selected points. Has an effect only for traces that support selections. Note that an empty array means an empty selection where the `unselected` are turned on for all points, whereas, any other non-array values means no selection all where the `selected` and `unselected` styles have no effect. showlegend Determines whether or not an item corresponding to this trace is shown in the legend. stream :class:`plotly.graph_objects.waterfall.Stream` instance or dict with compatible properties text Sets text elements associated with each (x,y) pair. If a single string, the same string appears over all the data points. If an array of string, the items are mapped in order to the this trace's (x,y) coordinates. If trace `hoverinfo` contains a "text" flag and "hovertext" is not set, these elements will be seen in the hover labels. textangle Sets the angle of the tick labels with respect to the bar. For example, a `tickangle` of -90 draws the tick labels vertically. With "auto" the texts may automatically be rotated to fit with the maximum size in bars. textfont Sets the font used for `text`. textinfo Determines which trace information appear on the graph. In the case of having multiple waterfalls, totals are computed separately (per trace). textposition Specifies the location of the `text`. "inside" positions `text` inside, next to the bar end (rotated and scaled if needed). "outside" positions `text` outside, next to the bar end (scaled if needed), unless there is another bar stacked on this one, then the text gets pushed inside. "auto" tries to position `text` inside the bar, but if the bar is too small and no bar is stacked on this one the text is moved outside. textpositionsrc Sets the source reference on Chart Studio Cloud for textposition . textsrc Sets the source reference on Chart Studio Cloud for text . texttemplate Template string used for rendering the information text that appear on points. Note that this will override `textinfo`. Variables are inserted using %{variable}, for example "y: %{y}". Numbers are formatted using d3-format's syntax %{variable:d3-format}, for example "Price: %{y:$.2f}". https://github.com/d3/d3-3.x-api- reference/blob/master/Formatting.md#d3_format for details on the formatting syntax. Dates are formatted using d3-time-format's syntax %{variable|d3-time- format}, for example "Day: %{2019-01-01|%A}". https://github.com/d3/d3-time-format#locale_format for details on the date formatting syntax. Every attributes that can be specified per-point (the ones that are `arrayOk: true`) are available. variables `initial`, `delta`, `final` and `label`. texttemplatesrc Sets the source reference on Chart Studio Cloud for texttemplate . totals :class:`plotly.graph_objects.waterfall.Totals` instance or dict with compatible properties uid Assign an id to this trace, Use this to provide object constancy between traces during animations and transitions. uirevision Controls persistence of some user-driven changes to the trace: `constraintrange` in `parcoords` traces, as well as some `editable: true` modifications such as `name` and `colorbar.title`. Defaults to `layout.uirevision`. Note that other user-driven trace attribute changes are controlled by `layout` attributes: `trace.visible` is controlled by `layout.legend.uirevision`, `selectedpoints` is controlled by `layout.selectionrevision`, and `colorbar.(x|y)` (accessible with `config: {editable: true}`) is controlled by `layout.editrevision`. Trace changes are tracked by `uid`, which only falls back on trace index if no `uid` is provided. So if your app can add/remove traces before the end of the `data` array, such that the same trace has a different index, you can still preserve user-driven changes if you give each trace a `uid` that stays with it as it moves. visible Determines whether or not this trace is visible. If "legendonly", the trace is not drawn, but can appear as a legend item (provided that the legend itself is visible). width Sets the bar width (in position axis units). widthsrc Sets the source reference on Chart Studio Cloud for width . x Sets the x coordinates. x0 Alternate to `x`. Builds a linear space of x coordinates. Use with `dx` where `x0` is the starting coordinate and `dx` the step. xaxis Sets a reference between this trace's x coordinates and a 2D cartesian x axis. If "x" (the default value), the x coordinates refer to `layout.xaxis`. If "x2", the x coordinates refer to `layout.xaxis2`, and so on. xperiod Only relevant when the axis `type` is "date". Sets the period positioning in milliseconds or "M<n>" on the x axis. Special values in the form of "M<n>" could be used to declare the number of months. In this case `n` must be a positive integer. xperiod0 Only relevant when the axis `type` is "date". Sets the base for period positioning in milliseconds or date string on the x0 axis. When `x0period` is round number of weeks, the `x0period0` by default would be on a Sunday i.e. 2000-01-02, otherwise it would be at 2000-01-01. xperiodalignment Only relevant when the axis `type` is "date". Sets the alignment of data points on the x axis. xsrc Sets the source reference on Chart Studio Cloud for x . y Sets the y coordinates. y0 Alternate to `y`. Builds a linear space of y coordinates. Use with `dy` where `y0` is the starting coordinate and `dy` the step. yaxis Sets a reference between this trace's y coordinates and a 2D cartesian y axis. If "y" (the default value), the y coordinates refer to `layout.yaxis`. If "y2", the y coordinates refer to `layout.yaxis2`, and so on. yperiod Only relevant when the axis `type` is "date". Sets the period positioning in milliseconds or "M<n>" on the y axis. Special values in the form of "M<n>" could be used to declare the number of months. In this case `n` must be a positive integer. yperiod0 Only relevant when the axis `type` is "date". Sets the base for period positioning in milliseconds or date string on the y0 axis. When `y0period` is round number of weeks, the `y0period0` by default would be on a Sunday i.e. 2000-01-02, otherwise it would be at 2000-01-01. yperiodalignment Only relevant when the axis `type` is "date". Sets the alignment of data points on the y axis. ysrc Sets the source reference on Chart Studio Cloud for y . row : int or None (default) Subplot row index (starting from 1) for the trace to be added. Only valid if figure was created using `plotly.tools.make_subplots` col : int or None (default) Subplot col index (starting from 1) for the trace to be added. Only valid if figure was created using `plotly.tools.make_subplots` secondary_y: boolean or None (default None) If True, associate this trace with the secondary y-axis of the subplot at the specified row and col. Only valid if all of the following conditions are satisfied: * The figure was created using `plotly.subplots.make_subplots`. * The row and col arguments are not None * The subplot at the specified row and col has type xy (which is the default) and secondary_y True. These properties are specified in the specs argument to make_subplots. See the make_subplots docstring for more info. Returns ------- FigureWidget """ from plotly.graph_objs import Waterfall new_trace = Waterfall( alignmentgroup=alignmentgroup, base=base, cliponaxis=cliponaxis, connector=connector, constraintext=constraintext, customdata=customdata, customdatasrc=customdatasrc, decreasing=decreasing, dx=dx, dy=dy, hoverinfo=hoverinfo, hoverinfosrc=hoverinfosrc, hoverlabel=hoverlabel, hovertemplate=hovertemplate, hovertemplatesrc=hovertemplatesrc, hovertext=hovertext, hovertextsrc=hovertextsrc, ids=ids, idssrc=idssrc, increasing=increasing, insidetextanchor=insidetextanchor, insidetextfont=insidetextfont, legendgroup=legendgroup, measure=measure, measuresrc=measuresrc, meta=meta, metasrc=metasrc, name=name, offset=offset, offsetgroup=offsetgroup, offsetsrc=offsetsrc, opacity=opacity, orientation=orientation, outsidetextfont=outsidetextfont, selectedpoints=selectedpoints, showlegend=showlegend, stream=stream, text=text, textangle=textangle, textfont=textfont, textinfo=textinfo, textposition=textposition, textpositionsrc=textpositionsrc, textsrc=textsrc, texttemplate=texttemplate, texttemplatesrc=texttemplatesrc, totals=totals, uid=uid, uirevision=uirevision, visible=visible, width=width, widthsrc=widthsrc, x=x, x0=x0, xaxis=xaxis, xperiod=xperiod, xperiod0=xperiod0, xperiodalignment=xperiodalignment, xsrc=xsrc, y=y, y0=y0, yaxis=yaxis, yperiod=yperiod, yperiod0=yperiod0, yperiodalignment=yperiodalignment, ysrc=ysrc, **kwargs ) return self.add_trace(new_trace, row=row, col=col, secondary_y=secondary_y) def select_coloraxes(self, selector=None, row=None, col=None): """ Select coloraxis subplot objects from a particular subplot cell and/or coloraxis subplot objects that satisfy custom selection criteria. Parameters ---------- selector: dict or None (default None) Dict to use as selection criteria. coloraxis objects will be selected if they contain properties corresponding to all of the dictionary's keys, with values that exactly match the supplied values. If None (the default), all coloraxis objects are selected. row, col: int or None (default None) Subplot row and column index of coloraxis objects to select. To select coloraxis objects by row and column, the Figure must have been created using plotly.subplots.make_subplots. If None (the default), all coloraxis objects are selected. Returns ------- generator Generator that iterates through all of the coloraxis objects that satisfy all of the specified selection criteria """ return self._select_layout_subplots_by_prefix("coloraxis", selector, row, col) def for_each_coloraxis(self, fn, selector=None, row=None, col=None): """ Apply a function to all coloraxis objects that satisfy the specified selection criteria Parameters ---------- fn: Function that inputs a single coloraxis object. selector: dict or None (default None) Dict to use as selection criteria. coloraxis objects will be selected if they contain properties corresponding to all of the dictionary's keys, with values that exactly match the supplied values. If None (the default), all coloraxis objects are selected. row, col: int or None (default None) Subplot row and column index of coloraxis objects to select. To select coloraxis objects by row and column, the Figure must have been created using plotly.subplots.make_subplots. If None (the default), all coloraxis objects are selected. Returns ------- self Returns the Figure object that the method was called on """ for obj in self.select_coloraxes(selector=selector, row=row, col=col): fn(obj) return self def update_coloraxes( self, patch=None, selector=None, overwrite=False, row=None, col=None, **kwargs ): """ Perform a property update operation on all coloraxis objects that satisfy the specified selection criteria Parameters ---------- patch: dict Dictionary of property updates to be applied to all coloraxis objects that satisfy the selection criteria. selector: dict or None (default None) Dict to use as selection criteria. coloraxis objects will be selected if they contain properties corresponding to all of the dictionary's keys, with values that exactly match the supplied values. If None (the default), all coloraxis objects are selected. overwrite: bool If True, overwrite existing properties. If False, apply updates to existing properties recursively, preserving existing properties that are not specified in the update operation. row, col: int or None (default None) Subplot row and column index of coloraxis objects to select. To select coloraxis objects by row and column, the Figure must have been created using plotly.subplots.make_subplots. If None (the default), all coloraxis objects are selected. **kwargs Additional property updates to apply to each selected coloraxis object. If a property is specified in both patch and in **kwargs then the one in **kwargs takes precedence. Returns ------- self Returns the Figure object that the method was called on """ for obj in self.select_coloraxes(selector=selector, row=row, col=col): obj.update(patch, overwrite=overwrite, **kwargs) return self def select_geos(self, selector=None, row=None, col=None): """ Select geo subplot objects from a particular subplot cell and/or geo subplot objects that satisfy custom selection criteria. Parameters ---------- selector: dict or None (default None) Dict to use as selection criteria. geo objects will be selected if they contain properties corresponding to all of the dictionary's keys, with values that exactly match the supplied values. If None (the default), all geo objects are selected. row, col: int or None (default None) Subplot row and column index of geo objects to select. To select geo objects by row and column, the Figure must have been created using plotly.subplots.make_subplots. If None (the default), all geo objects are selected. Returns ------- generator Generator that iterates through all of the geo objects that satisfy all of the specified selection criteria """ return self._select_layout_subplots_by_prefix("geo", selector, row, col) def for_each_geo(self, fn, selector=None, row=None, col=None): """ Apply a function to all geo objects that satisfy the specified selection criteria Parameters ---------- fn: Function that inputs a single geo object. selector: dict or None (default None) Dict to use as selection criteria. geo objects will be selected if they contain properties corresponding to all of the dictionary's keys, with values that exactly match the supplied values. If None (the default), all geo objects are selected. row, col: int or None (default None) Subplot row and column index of geo objects to select. To select geo objects by row and column, the Figure must have been created using plotly.subplots.make_subplots. If None (the default), all geo objects are selected. Returns ------- self Returns the Figure object that the method was called on """ for obj in self.select_geos(selector=selector, row=row, col=col): fn(obj) return self def update_geos( self, patch=None, selector=None, overwrite=False, row=None, col=None, **kwargs ): """ Perform a property update operation on all geo objects that satisfy the specified selection criteria Parameters ---------- patch: dict Dictionary of property updates to be applied to all geo objects that satisfy the selection criteria. selector: dict or None (default None) Dict to use as selection criteria. geo objects will be selected if they contain properties corresponding to all of the dictionary's keys, with values that exactly match the supplied values. If None (the default), all geo objects are selected. overwrite: bool If True, overwrite existing properties. If False, apply updates to existing properties recursively, preserving existing properties that are not specified in the update operation. row, col: int or None (default None) Subplot row and column index of geo objects to select. To select geo objects by row and column, the Figure must have been created using plotly.subplots.make_subplots. If None (the default), all geo objects are selected. **kwargs Additional property updates to apply to each selected geo object. If a property is specified in both patch and in **kwargs then the one in **kwargs takes precedence. Returns ------- self Returns the Figure object that the method was called on """ for obj in self.select_geos(selector=selector, row=row, col=col): obj.update(patch, overwrite=overwrite, **kwargs) return self def select_mapboxes(self, selector=None, row=None, col=None): """ Select mapbox subplot objects from a particular subplot cell and/or mapbox subplot objects that satisfy custom selection criteria. Parameters ---------- selector: dict or None (default None) Dict to use as selection criteria. mapbox objects will be selected if they contain properties corresponding to all of the dictionary's keys, with values that exactly match the supplied values. If None (the default), all mapbox objects are selected. row, col: int or None (default None) Subplot row and column index of mapbox objects to select. To select mapbox objects by row and column, the Figure must have been created using plotly.subplots.make_subplots. If None (the default), all mapbox objects are selected. Returns ------- generator Generator that iterates through all of the mapbox objects that satisfy all of the specified selection criteria """ return self._select_layout_subplots_by_prefix("mapbox", selector, row, col) def for_each_mapbox(self, fn, selector=None, row=None, col=None): """ Apply a function to all mapbox objects that satisfy the specified selection criteria Parameters ---------- fn: Function that inputs a single mapbox object. selector: dict or None (default None) Dict to use as selection criteria. mapbox objects will be selected if they contain properties corresponding to all of the dictionary's keys, with values that exactly match the supplied values. If None (the default), all mapbox objects are selected. row, col: int or None (default None) Subplot row and column index of mapbox objects to select. To select mapbox objects by row and column, the Figure must have been created using plotly.subplots.make_subplots. If None (the default), all mapbox objects are selected. Returns ------- self Returns the Figure object that the method was called on """ for obj in self.select_mapboxes(selector=selector, row=row, col=col): fn(obj) return self def update_mapboxes( self, patch=None, selector=None, overwrite=False, row=None, col=None, **kwargs ): """ Perform a property update operation on all mapbox objects that satisfy the specified selection criteria Parameters ---------- patch: dict Dictionary of property updates to be applied to all mapbox objects that satisfy the selection criteria. selector: dict or None (default None) Dict to use as selection criteria. mapbox objects will be selected if they contain properties corresponding to all of the dictionary's keys, with values that exactly match the supplied values. If None (the default), all mapbox objects are selected. overwrite: bool If True, overwrite existing properties. If False, apply updates to existing properties recursively, preserving existing properties that are not specified in the update operation. row, col: int or None (default None) Subplot row and column index of mapbox objects to select. To select mapbox objects by row and column, the Figure must have been created using plotly.subplots.make_subplots. If None (the default), all mapbox objects are selected. **kwargs Additional property updates to apply to each selected mapbox object. If a property is specified in both patch and in **kwargs then the one in **kwargs takes precedence. Returns ------- self Returns the Figure object that the method was called on """ for obj in self.select_mapboxes(selector=selector, row=row, col=col): obj.update(patch, overwrite=overwrite, **kwargs) return self def select_polars(self, selector=None, row=None, col=None): """ Select polar subplot objects from a particular subplot cell and/or polar subplot objects that satisfy custom selection criteria. Parameters ---------- selector: dict or None (default None) Dict to use as selection criteria. polar objects will be selected if they contain properties corresponding to all of the dictionary's keys, with values that exactly match the supplied values. If None (the default), all polar objects are selected. row, col: int or None (default None) Subplot row and column index of polar objects to select. To select polar objects by row and column, the Figure must have been created using plotly.subplots.make_subplots. If None (the default), all polar objects are selected. Returns ------- generator Generator that iterates through all of the polar objects that satisfy all of the specified selection criteria """ return self._select_layout_subplots_by_prefix("polar", selector, row, col) def for_each_polar(self, fn, selector=None, row=None, col=None): """ Apply a function to all polar objects that satisfy the specified selection criteria Parameters ---------- fn: Function that inputs a single polar object. selector: dict or None (default None) Dict to use as selection criteria. polar objects will be selected if they contain properties corresponding to all of the dictionary's keys, with values that exactly match the supplied values. If None (the default), all polar objects are selected. row, col: int or None (default None) Subplot row and column index of polar objects to select. To select polar objects by row and column, the Figure must have been created using plotly.subplots.make_subplots. If None (the default), all polar objects are selected. Returns ------- self Returns the Figure object that the method was called on """ for obj in self.select_polars(selector=selector, row=row, col=col): fn(obj) return self def update_polars( self, patch=None, selector=None, overwrite=False, row=None, col=None, **kwargs ): """ Perform a property update operation on all polar objects that satisfy the specified selection criteria Parameters ---------- patch: dict Dictionary of property updates to be applied to all polar objects that satisfy the selection criteria. selector: dict or None (default None) Dict to use as selection criteria. polar objects will be selected if they contain properties corresponding to all of the dictionary's keys, with values that exactly match the supplied values. If None (the default), all polar objects are selected. overwrite: bool If True, overwrite existing properties. If False, apply updates to existing properties recursively, preserving existing properties that are not specified in the update operation. row, col: int or None (default None) Subplot row and column index of polar objects to select. To select polar objects by row and column, the Figure must have been created using plotly.subplots.make_subplots. If None (the default), all polar objects are selected. **kwargs Additional property updates to apply to each selected polar object. If a property is specified in both patch and in **kwargs then the one in **kwargs takes precedence. Returns ------- self Returns the Figure object that the method was called on """ for obj in self.select_polars(selector=selector, row=row, col=col): obj.update(patch, overwrite=overwrite, **kwargs) return self def select_scenes(self, selector=None, row=None, col=None): """ Select scene subplot objects from a particular subplot cell and/or scene subplot objects that satisfy custom selection criteria. Parameters ---------- selector: dict or None (default None) Dict to use as selection criteria. scene objects will be selected if they contain properties corresponding to all of the dictionary's keys, with values that exactly match the supplied values. If None (the default), all scene objects are selected. row, col: int or None (default None) Subplot row and column index of scene objects to select. To select scene objects by row and column, the Figure must have been created using plotly.subplots.make_subplots. If None (the default), all scene objects are selected. Returns ------- generator Generator that iterates through all of the scene objects that satisfy all of the specified selection criteria """ return self._select_layout_subplots_by_prefix("scene", selector, row, col) def for_each_scene(self, fn, selector=None, row=None, col=None): """ Apply a function to all scene objects that satisfy the specified selection criteria Parameters ---------- fn: Function that inputs a single scene object. selector: dict or None (default None) Dict to use as selection criteria. scene objects will be selected if they contain properties corresponding to all of the dictionary's keys, with values that exactly match the supplied values. If None (the default), all scene objects are selected. row, col: int or None (default None) Subplot row and column index of scene objects to select. To select scene objects by row and column, the Figure must have been created using plotly.subplots.make_subplots. If None (the default), all scene objects are selected. Returns ------- self Returns the Figure object that the method was called on """ for obj in self.select_scenes(selector=selector, row=row, col=col): fn(obj) return self def update_scenes( self, patch=None, selector=None, overwrite=False, row=None, col=None, **kwargs ): """ Perform a property update operation on all scene objects that satisfy the specified selection criteria Parameters ---------- patch: dict Dictionary of property updates to be applied to all scene objects that satisfy the selection criteria. selector: dict or None (default None) Dict to use as selection criteria. scene objects will be selected if they contain properties corresponding to all of the dictionary's keys, with values that exactly match the supplied values. If None (the default), all scene objects are selected. overwrite: bool If True, overwrite existing properties. If False, apply updates to existing properties recursively, preserving existing properties that are not specified in the update operation. row, col: int or None (default None) Subplot row and column index of scene objects to select. To select scene objects by row and column, the Figure must have been created using plotly.subplots.make_subplots. If None (the default), all scene objects are selected. **kwargs Additional property updates to apply to each selected scene object. If a property is specified in both patch and in **kwargs then the one in **kwargs takes precedence. Returns ------- self Returns the Figure object that the method was called on """ for obj in self.select_scenes(selector=selector, row=row, col=col): obj.update(patch, overwrite=overwrite, **kwargs) return self def select_ternaries(self, selector=None, row=None, col=None): """ Select ternary subplot objects from a particular subplot cell and/or ternary subplot objects that satisfy custom selection criteria. Parameters ---------- selector: dict or None (default None) Dict to use as selection criteria. ternary objects will be selected if they contain properties corresponding to all of the dictionary's keys, with values that exactly match the supplied values. If None (the default), all ternary objects are selected. row, col: int or None (default None) Subplot row and column index of ternary objects to select. To select ternary objects by row and column, the Figure must have been created using plotly.subplots.make_subplots. If None (the default), all ternary objects are selected. Returns ------- generator Generator that iterates through all of the ternary objects that satisfy all of the specified selection criteria """ return self._select_layout_subplots_by_prefix("ternary", selector, row, col) def for_each_ternary(self, fn, selector=None, row=None, col=None): """ Apply a function to all ternary objects that satisfy the specified selection criteria Parameters ---------- fn: Function that inputs a single ternary object. selector: dict or None (default None) Dict to use as selection criteria. ternary objects will be selected if they contain properties corresponding to all of the dictionary's keys, with values that exactly match the supplied values. If None (the default), all ternary objects are selected. row, col: int or None (default None) Subplot row and column index of ternary objects to select. To select ternary objects by row and column, the Figure must have been created using plotly.subplots.make_subplots. If None (the default), all ternary objects are selected. Returns ------- self Returns the Figure object that the method was called on """ for obj in self.select_ternaries(selector=selector, row=row, col=col): fn(obj) return self def update_ternaries( self, patch=None, selector=None, overwrite=False, row=None, col=None, **kwargs ): """ Perform a property update operation on all ternary objects that satisfy the specified selection criteria Parameters ---------- patch: dict Dictionary of property updates to be applied to all ternary objects that satisfy the selection criteria. selector: dict or None (default None) Dict to use as selection criteria. ternary objects will be selected if they contain properties corresponding to all of the dictionary's keys, with values that exactly match the supplied values. If None (the default), all ternary objects are selected. overwrite: bool If True, overwrite existing properties. If False, apply updates to existing properties recursively, preserving existing properties that are not specified in the update operation. row, col: int or None (default None) Subplot row and column index of ternary objects to select. To select ternary objects by row and column, the Figure must have been created using plotly.subplots.make_subplots. If None (the default), all ternary objects are selected. **kwargs Additional property updates to apply to each selected ternary object. If a property is specified in both patch and in **kwargs then the one in **kwargs takes precedence. Returns ------- self Returns the Figure object that the method was called on """ for obj in self.select_ternaries(selector=selector, row=row, col=col): obj.update(patch, overwrite=overwrite, **kwargs) return self def select_xaxes(self, selector=None, row=None, col=None): """ Select xaxis subplot objects from a particular subplot cell and/or xaxis subplot objects that satisfy custom selection criteria. Parameters ---------- selector: dict or None (default None) Dict to use as selection criteria. xaxis objects will be selected if they contain properties corresponding to all of the dictionary's keys, with values that exactly match the supplied values. If None (the default), all xaxis objects are selected. row, col: int or None (default None) Subplot row and column index of xaxis objects to select. To select xaxis objects by row and column, the Figure must have been created using plotly.subplots.make_subplots. If None (the default), all xaxis objects are selected. Returns ------- generator Generator that iterates through all of the xaxis objects that satisfy all of the specified selection criteria """ return self._select_layout_subplots_by_prefix("xaxis", selector, row, col) def for_each_xaxis(self, fn, selector=None, row=None, col=None): """ Apply a function to all xaxis objects that satisfy the specified selection criteria Parameters ---------- fn: Function that inputs a single xaxis object. selector: dict or None (default None) Dict to use as selection criteria. xaxis objects will be selected if they contain properties corresponding to all of the dictionary's keys, with values that exactly match the supplied values. If None (the default), all xaxis objects are selected. row, col: int or None (default None) Subplot row and column index of xaxis objects to select. To select xaxis objects by row and column, the Figure must have been created using plotly.subplots.make_subplots. If None (the default), all xaxis objects are selected. Returns ------- self Returns the Figure object that the method was called on """ for obj in self.select_xaxes(selector=selector, row=row, col=col): fn(obj) return self def update_xaxes( self, patch=None, selector=None, overwrite=False, row=None, col=None, **kwargs ): """ Perform a property update operation on all xaxis objects that satisfy the specified selection criteria Parameters ---------- patch: dict Dictionary of property updates to be applied to all xaxis objects that satisfy the selection criteria. selector: dict or None (default None) Dict to use as selection criteria. xaxis objects will be selected if they contain properties corresponding to all of the dictionary's keys, with values that exactly match the supplied values. If None (the default), all xaxis objects are selected. overwrite: bool If True, overwrite existing properties. If False, apply updates to existing properties recursively, preserving existing properties that are not specified in the update operation. row, col: int or None (default None) Subplot row and column index of xaxis objects to select. To select xaxis objects by row and column, the Figure must have been created using plotly.subplots.make_subplots. If None (the default), all xaxis objects are selected. **kwargs Additional property updates to apply to each selected xaxis object. If a property is specified in both patch and in **kwargs then the one in **kwargs takes precedence. Returns ------- self Returns the Figure object that the method was called on """ for obj in self.select_xaxes(selector=selector, row=row, col=col): obj.update(patch, overwrite=overwrite, **kwargs) return self def select_yaxes(self, selector=None, row=None, col=None, secondary_y=None): """ Select yaxis subplot objects from a particular subplot cell and/or yaxis subplot objects that satisfy custom selection criteria. Parameters ---------- selector: dict or None (default None) Dict to use as selection criteria. yaxis objects will be selected if they contain properties corresponding to all of the dictionary's keys, with values that exactly match the supplied values. If None (the default), all yaxis objects are selected. row, col: int or None (default None) Subplot row and column index of yaxis objects to select. To select yaxis objects by row and column, the Figure must have been created using plotly.subplots.make_subplots. If None (the default), all yaxis objects are selected. secondary_y: boolean or None (default None) * If True, only select yaxis objects associated with the secondary y-axis of the subplot. * If False, only select yaxis objects associated with the primary y-axis of the subplot. * If None (the default), do not filter yaxis objects based on a secondary y-axis condition. To select yaxis objects by secondary y-axis, the Figure must have been created using plotly.subplots.make_subplots. See the docstring for the specs argument to make_subplots for more info on creating subplots with secondary y-axes. Returns ------- generator Generator that iterates through all of the yaxis objects that satisfy all of the specified selection criteria """ return self._select_layout_subplots_by_prefix( "yaxis", selector, row, col, secondary_y=secondary_y ) def for_each_yaxis(self, fn, selector=None, row=None, col=None, secondary_y=None): """ Apply a function to all yaxis objects that satisfy the specified selection criteria Parameters ---------- fn: Function that inputs a single yaxis object. selector: dict or None (default None) Dict to use as selection criteria. yaxis objects will be selected if they contain properties corresponding to all of the dictionary's keys, with values that exactly match the supplied values. If None (the default), all yaxis objects are selected. row, col: int or None (default None) Subplot row and column index of yaxis objects to select. To select yaxis objects by row and column, the Figure must have been created using plotly.subplots.make_subplots. If None (the default), all yaxis objects are selected. secondary_y: boolean or None (default None) * If True, only select yaxis objects associated with the secondary y-axis of the subplot. * If False, only select yaxis objects associated with the primary y-axis of the subplot. * If None (the default), do not filter yaxis objects based on a secondary y-axis condition. To select yaxis objects by secondary y-axis, the Figure must have been created using plotly.subplots.make_subplots. See the docstring for the specs argument to make_subplots for more info on creating subplots with secondary y-axes. Returns ------- self Returns the Figure object that the method was called on """ for obj in self.select_yaxes( selector=selector, row=row, col=col, secondary_y=secondary_y ): fn(obj) return self def update_yaxes( self, patch=None, selector=None, overwrite=False, row=None, col=None, secondary_y=None, **kwargs ): """ Perform a property update operation on all yaxis objects that satisfy the specified selection criteria Parameters ---------- patch: dict Dictionary of property updates to be applied to all yaxis objects that satisfy the selection criteria. selector: dict or None (default None) Dict to use as selection criteria. yaxis objects will be selected if they contain properties corresponding to all of the dictionary's keys, with values that exactly match the supplied values. If None (the default), all yaxis objects are selected. overwrite: bool If True, overwrite existing properties. If False, apply updates to existing properties recursively, preserving existing properties that are not specified in the update operation. row, col: int or None (default None) Subplot row and column index of yaxis objects to select. To select yaxis objects by row and column, the Figure must have been created using plotly.subplots.make_subplots. If None (the default), all yaxis objects are selected. secondary_y: boolean or None (default None) * If True, only select yaxis objects associated with the secondary y-axis of the subplot. * If False, only select yaxis objects associated with the primary y-axis of the subplot. * If None (the default), do not filter yaxis objects based on a secondary y-axis condition. To select yaxis objects by secondary y-axis, the Figure must have been created using plotly.subplots.make_subplots. See the docstring for the specs argument to make_subplots for more info on creating subplots with secondary y-axes. **kwargs Additional property updates to apply to each selected yaxis object. If a property is specified in both patch and in **kwargs then the one in **kwargs takes precedence. Returns ------- self Returns the Figure object that the method was called on """ for obj in self.select_yaxes( selector=selector, row=row, col=col, secondary_y=secondary_y ): obj.update(patch, overwrite=overwrite, **kwargs) return self def select_annotations(self, selector=None, row=None, col=None, secondary_y=None): """ Select annotations from a particular subplot cell and/or annotations that satisfy custom selection criteria. Parameters ---------- selector: dict or None (default None) Dict to use as selection criteria. Annotations will be selected if they contain properties corresponding to all of the dictionary's keys, with values that exactly match the supplied values. If None (the default), all annotations are selected. row, col: int or None (default None) Subplot row and column index of annotations to select. To select annotations by row and column, the Figure must have been created using plotly.subplots.make_subplots. To select only those annotation that are in paper coordinates, set row and col to the string 'paper'. If None (the default), all annotations are selected. secondary_y: boolean or None (default None) * If True, only select annotations associated with the secondary y-axis of the subplot. * If False, only select annotations associated with the primary y-axis of the subplot. * If None (the default), do not filter annotations based on secondary y-axis. To select annotations by secondary y-axis, the Figure must have been created using plotly.subplots.make_subplots. See the docstring for the specs argument to make_subplots for more info on creating subplots with secondary y-axes. Returns ------- generator Generator that iterates through all of the annotations that satisfy all of the specified selection criteria """ return self._select_annotations_like( "annotations", selector=selector, row=row, col=col, secondary_y=secondary_y ) def for_each_annotation( self, fn, selector=None, row=None, col=None, secondary_y=None ): """ Apply a function to all annotations that satisfy the specified selection criteria Parameters ---------- fn: Function that inputs a single annotation object. selector: dict or None (default None) Dict to use as selection criteria. Traces will be selected if they contain properties corresponding to all of the dictionary's keys, with values that exactly match the supplied values. If None (the default), all annotations are selected. row, col: int or None (default None) Subplot row and column index of annotations to select. To select annotations by row and column, the Figure must have been created using plotly.subplots.make_subplots. To select only those annotations that are in paper coordinates, set row and col to the string 'paper'. If None (the default), all annotations are selected. secondary_y: boolean or None (default None) * If True, only select annotations associated with the secondary y-axis of the subplot. * If False, only select annotations associated with the primary y-axis of the subplot. * If None (the default), do not filter annotations based on secondary y-axis. To select annotations by secondary y-axis, the Figure must have been created using plotly.subplots.make_subplots. See the docstring for the specs argument to make_subplots for more info on creating subplots with secondary y-axes. Returns ------- self Returns the Figure object that the method was called on """ for obj in self._select_annotations_like( prop="annotations", selector=selector, row=row, col=col, secondary_y=secondary_y, ): fn(obj) return self def update_annotations( self, patch=None, selector=None, row=None, col=None, secondary_y=None, **kwargs ): """ Perform a property update operation on all annotations that satisfy the specified selection criteria Parameters ---------- patch: dict or None (default None) Dictionary of property updates to be applied to all annotations that satisfy the selection criteria. selector: dict or None (default None) Dict to use as selection criteria. Traces will be selected if they contain properties corresponding to all of the dictionary's keys, with values that exactly match the supplied values. If None (the default), all annotations are selected. row, col: int or None (default None) Subplot row and column index of annotations to select. To select annotations by row and column, the Figure must have been created using plotly.subplots.make_subplots. To select only those annotation that are in paper coordinates, set row and col to the string 'paper'. If None (the default), all annotations are selected. secondary_y: boolean or None (default None) * If True, only select annotations associated with the secondary y-axis of the subplot. * If False, only select annotations associated with the primary y-axis of the subplot. * If None (the default), do not filter annotations based on secondary y-axis. To select annotations by secondary y-axis, the Figure must have been created using plotly.subplots.make_subplots. See the docstring for the specs argument to make_subplots for more info on creating subplots with secondary y-axes. **kwargs Additional property updates to apply to each selected annotation. If a property is specified in both patch and in **kwargs then the one in **kwargs takes precedence. Returns ------- self Returns the Figure object that the method was called on """ for obj in self._select_annotations_like( prop="annotations", selector=selector, row=row, col=col, secondary_y=secondary_y, ): obj.update(patch, **kwargs) return self def add_annotation( self, arg=None, align=None, arrowcolor=None, arrowhead=None, arrowside=None, arrowsize=None, arrowwidth=None, ax=None, axref=None, ay=None, ayref=None, bgcolor=None, bordercolor=None, borderpad=None, borderwidth=None, captureevents=None, clicktoshow=None, font=None, height=None, hoverlabel=None, hovertext=None, name=None, opacity=None, showarrow=None, standoff=None, startarrowhead=None, startarrowsize=None, startstandoff=None, templateitemname=None, text=None, textangle=None, valign=None, visible=None, width=None, x=None, xanchor=None, xclick=None, xref=None, xshift=None, y=None, yanchor=None, yclick=None, yref=None, yshift=None, row=None, col=None, secondary_y=None, **kwargs ): """ Create and add a new annotation to the figure's layout Parameters ---------- arg instance of Annotation or dict with compatible properties align Sets the horizontal alignment of the `text` within the box. Has an effect only if `text` spans two or more lines (i.e. `text` contains one or more <br> HTML tags) or if an explicit width is set to override the text width. arrowcolor Sets the color of the annotation arrow. arrowhead Sets the end annotation arrow head style. arrowside Sets the annotation arrow head position. arrowsize Sets the size of the end annotation arrow head, relative to `arrowwidth`. A value of 1 (default) gives a head about 3x as wide as the line. arrowwidth Sets the width (in px) of annotation arrow line. ax Sets the x component of the arrow tail about the arrow head. If `axref` is `pixel`, a positive (negative) component corresponds to an arrow pointing from right to left (left to right). If `axref` is not `pixel` and is exactly the same as `xref`, this is an absolute value on that axis, like `x`, specified in the same coordinates as `xref`. axref Indicates in what coordinates the tail of the annotation (ax,ay) is specified. If set to a ax axis id (e.g. "ax" or "ax2"), the `ax` position refers to a ax coordinate. If set to "paper", the `ax` position refers to the distance from the left of the plotting area in normalized coordinates where 0 (1) corresponds to the left (right). If set to a ax axis ID followed by "domain" (separated by a space), the position behaves like for "paper", but refers to the distance in fractions of the domain length from the left of the domain of that axis: e.g., *ax2 domain* refers to the domain of the second ax axis and a ax position of 0.5 refers to the point between the left and the right of the domain of the second ax axis. In order for absolute positioning of the arrow to work, "axref" must be exactly the same as "xref", otherwise "axref" will revert to "pixel" (explained next). For relative positioning, "axref" can be set to "pixel", in which case the "ax" value is specified in pixels relative to "x". Absolute positioning is useful for trendline annotations which should continue to indicate the correct trend when zoomed. Relative positioning is useful for specifying the text offset for an annotated point. ay Sets the y component of the arrow tail about the arrow head. If `ayref` is `pixel`, a positive (negative) component corresponds to an arrow pointing from bottom to top (top to bottom). If `ayref` is not `pixel` and is exactly the same as `yref`, this is an absolute value on that axis, like `y`, specified in the same coordinates as `yref`. ayref Indicates in what coordinates the tail of the annotation (ax,ay) is specified. If set to a ay axis id (e.g. "ay" or "ay2"), the `ay` position refers to a ay coordinate. If set to "paper", the `ay` position refers to the distance from the bottom of the plotting area in normalized coordinates where 0 (1) corresponds to the bottom (top). If set to a ay axis ID followed by "domain" (separated by a space), the position behaves like for "paper", but refers to the distance in fractions of the domain length from the bottom of the domain of that axis: e.g., *ay2 domain* refers to the domain of the second ay axis and a ay position of 0.5 refers to the point between the bottom and the top of the domain of the second ay axis. In order for absolute positioning of the arrow to work, "ayref" must be exactly the same as "yref", otherwise "ayref" will revert to "pixel" (explained next). For relative positioning, "ayref" can be set to "pixel", in which case the "ay" value is specified in pixels relative to "y". Absolute positioning is useful for trendline annotations which should continue to indicate the correct trend when zoomed. Relative positioning is useful for specifying the text offset for an annotated point. bgcolor Sets the background color of the annotation. bordercolor Sets the color of the border enclosing the annotation `text`. borderpad Sets the padding (in px) between the `text` and the enclosing border. borderwidth Sets the width (in px) of the border enclosing the annotation `text`. captureevents Determines whether the annotation text box captures mouse move and click events, or allows those events to pass through to data points in the plot that may be behind the annotation. By default `captureevents` is False unless `hovertext` is provided. If you use the event `plotly_clickannotation` without `hovertext` you must explicitly enable `captureevents`. clicktoshow Makes this annotation respond to clicks on the plot. If you click a data point that exactly matches the `x` and `y` values of this annotation, and it is hidden (visible: false), it will appear. In "onoff" mode, you must click the same point again to make it disappear, so if you click multiple points, you can show multiple annotations. In "onout" mode, a click anywhere else in the plot (on another data point or not) will hide this annotation. If you need to show/hide this annotation in response to different `x` or `y` values, you can set `xclick` and/or `yclick`. This is useful for example to label the side of a bar. To label markers though, `standoff` is preferred over `xclick` and `yclick`. font Sets the annotation text font. height Sets an explicit height for the text box. null (default) lets the text set the box height. Taller text will be clipped. hoverlabel :class:`plotly.graph_objects.layout.annotation.Hoverlab el` instance or dict with compatible properties hovertext Sets text to appear when hovering over this annotation. If omitted or blank, no hover label will appear. name When used in a template, named items are created in the output figure in addition to any items the figure already has in this array. You can modify these items in the output figure by making your own item with `templateitemname` matching this `name` alongside your modifications (including `visible: false` or `enabled: false` to hide it). Has no effect outside of a template. opacity Sets the opacity of the annotation (text + arrow). showarrow Determines whether or not the annotation is drawn with an arrow. If True, `text` is placed near the arrow's tail. If False, `text` lines up with the `x` and `y` provided. standoff Sets a distance, in pixels, to move the end arrowhead away from the position it is pointing at, for example to point at the edge of a marker independent of zoom. Note that this shortens the arrow from the `ax` / `ay` vector, in contrast to `xshift` / `yshift` which moves everything by this amount. startarrowhead Sets the start annotation arrow head style. startarrowsize Sets the size of the start annotation arrow head, relative to `arrowwidth`. A value of 1 (default) gives a head about 3x as wide as the line. startstandoff Sets a distance, in pixels, to move the start arrowhead away from the position it is pointing at, for example to point at the edge of a marker independent of zoom. Note that this shortens the arrow from the `ax` / `ay` vector, in contrast to `xshift` / `yshift` which moves everything by this amount. templateitemname Used to refer to a named item in this array in the template. Named items from the template will be created even without a matching item in the input figure, but you can modify one by making an item with `templateitemname` matching its `name`, alongside your modifications (including `visible: false` or `enabled: false` to hide it). If there is no template or no matching item, this item will be hidden unless you explicitly show it with `visible: true`. text Sets the text associated with this annotation. Plotly uses a subset of HTML tags to do things like newline (<br>), bold (<b></b>), italics (<i></i>), hyperlinks (<a href='...'></a>). Tags <em>, <sup>, <sub> <span> are also supported. textangle Sets the angle at which the `text` is drawn with respect to the horizontal. valign Sets the vertical alignment of the `text` within the box. Has an effect only if an explicit height is set to override the text height. visible Determines whether or not this annotation is visible. width Sets an explicit width for the text box. null (default) lets the text set the box width. Wider text will be clipped. There is no automatic wrapping; use <br> to start a new line. x Sets the annotation's x position. If the axis `type` is "log", then you must take the log of your desired range. If the axis `type` is "date", it should be date strings, like date data, though Date objects and unix milliseconds will be accepted and converted to strings. If the axis `type` is "category", it should be numbers, using the scale where each category is assigned a serial number from zero in the order it appears. xanchor Sets the text box's horizontal position anchor This anchor binds the `x` position to the "left", "center" or "right" of the annotation. For example, if `x` is set to 1, `xref` to "paper" and `xanchor` to "right" then the right-most portion of the annotation lines up with the right-most edge of the plotting area. If "auto", the anchor is equivalent to "center" for data- referenced annotations or if there is an arrow, whereas for paper-referenced with no arrow, the anchor picked corresponds to the closest side. xclick Toggle this annotation when clicking a data point whose `x` value is `xclick` rather than the annotation's `x` value. xref Sets the annotation's x coordinate axis. If set to a x axis id (e.g. "x" or "x2"), the `x` position refers to a x coordinate. If set to "paper", the `x` position refers to the distance from the left of the plotting area in normalized coordinates where 0 (1) corresponds to the left (right). If set to a x axis ID followed by "domain" (separated by a space), the position behaves like for "paper", but refers to the distance in fractions of the domain length from the left of the domain of that axis: e.g., *x2 domain* refers to the domain of the second x axis and a x position of 0.5 refers to the point between the left and the right of the domain of the second x axis. xshift Shifts the position of the whole annotation and arrow to the right (positive) or left (negative) by this many pixels. y Sets the annotation's y position. If the axis `type` is "log", then you must take the log of your desired range. If the axis `type` is "date", it should be date strings, like date data, though Date objects and unix milliseconds will be accepted and converted to strings. If the axis `type` is "category", it should be numbers, using the scale where each category is assigned a serial number from zero in the order it appears. yanchor Sets the text box's vertical position anchor This anchor binds the `y` position to the "top", "middle" or "bottom" of the annotation. For example, if `y` is set to 1, `yref` to "paper" and `yanchor` to "top" then the top-most portion of the annotation lines up with the top-most edge of the plotting area. If "auto", the anchor is equivalent to "middle" for data-referenced annotations or if there is an arrow, whereas for paper- referenced with no arrow, the anchor picked corresponds to the closest side. yclick Toggle this annotation when clicking a data point whose `y` value is `yclick` rather than the annotation's `y` value. yref Sets the annotation's y coordinate axis. If set to a y axis id (e.g. "y" or "y2"), the `y` position refers to a y coordinate. If set to "paper", the `y` position refers to the distance from the bottom of the plotting area in normalized coordinates where 0 (1) corresponds to the bottom (top). If set to a y axis ID followed by "domain" (separated by a space), the position behaves like for "paper", but refers to the distance in fractions of the domain length from the bottom of the domain of that axis: e.g., *y2 domain* refers to the domain of the second y axis and a y position of 0.5 refers to the point between the bottom and the top of the domain of the second y axis. yshift Shifts the position of the whole annotation and arrow up (positive) or down (negative) by this many pixels. row Subplot row for annotation col Subplot column for annotation secondary_y Whether to add annotation to secondary y-axis Returns ------- FigureWidget """ from plotly.graph_objs import layout as _layout new_obj = _layout.Annotation( arg, align=align, arrowcolor=arrowcolor, arrowhead=arrowhead, arrowside=arrowside, arrowsize=arrowsize, arrowwidth=arrowwidth, ax=ax, axref=axref, ay=ay, ayref=ayref, bgcolor=bgcolor, bordercolor=bordercolor, borderpad=borderpad, borderwidth=borderwidth, captureevents=captureevents, clicktoshow=clicktoshow, font=font, height=height, hoverlabel=hoverlabel, hovertext=hovertext, name=name, opacity=opacity, showarrow=showarrow, standoff=standoff, startarrowhead=startarrowhead, startarrowsize=startarrowsize, startstandoff=startstandoff, templateitemname=templateitemname, text=text, textangle=textangle, valign=valign, visible=visible, width=width, x=x, xanchor=xanchor, xclick=xclick, xref=xref, xshift=xshift, y=y, yanchor=yanchor, yclick=yclick, yref=yref, yshift=yshift, **kwargs ) return self._add_annotation_like( "annotation", "annotations", new_obj, row=row, col=col, secondary_y=secondary_y, ) def select_layout_images(self, selector=None, row=None, col=None, secondary_y=None): """ Select images from a particular subplot cell and/or images that satisfy custom selection criteria. Parameters ---------- selector: dict or None (default None) Dict to use as selection criteria. Annotations will be selected if they contain properties corresponding to all of the dictionary's keys, with values that exactly match the supplied values. If None (the default), all images are selected. row, col: int or None (default None) Subplot row and column index of images to select. To select images by row and column, the Figure must have been created using plotly.subplots.make_subplots. To select only those image that are in paper coordinates, set row and col to the string 'paper'. If None (the default), all images are selected. secondary_y: boolean or None (default None) * If True, only select images associated with the secondary y-axis of the subplot. * If False, only select images associated with the primary y-axis of the subplot. * If None (the default), do not filter images based on secondary y-axis. To select images by secondary y-axis, the Figure must have been created using plotly.subplots.make_subplots. See the docstring for the specs argument to make_subplots for more info on creating subplots with secondary y-axes. Returns ------- generator Generator that iterates through all of the images that satisfy all of the specified selection criteria """ return self._select_annotations_like( "images", selector=selector, row=row, col=col, secondary_y=secondary_y ) def for_each_layout_image( self, fn, selector=None, row=None, col=None, secondary_y=None ): """ Apply a function to all images that satisfy the specified selection criteria Parameters ---------- fn: Function that inputs a single image object. selector: dict or None (default None) Dict to use as selection criteria. Traces will be selected if they contain properties corresponding to all of the dictionary's keys, with values that exactly match the supplied values. If None (the default), all images are selected. row, col: int or None (default None) Subplot row and column index of images to select. To select images by row and column, the Figure must have been created using plotly.subplots.make_subplots. To select only those images that are in paper coordinates, set row and col to the string 'paper'. If None (the default), all images are selected. secondary_y: boolean or None (default None) * If True, only select images associated with the secondary y-axis of the subplot. * If False, only select images associated with the primary y-axis of the subplot. * If None (the default), do not filter images based on secondary y-axis. To select images by secondary y-axis, the Figure must have been created using plotly.subplots.make_subplots. See the docstring for the specs argument to make_subplots for more info on creating subplots with secondary y-axes. Returns ------- self Returns the Figure object that the method was called on """ for obj in self._select_annotations_like( prop="images", selector=selector, row=row, col=col, secondary_y=secondary_y, ): fn(obj) return self def update_layout_images( self, patch=None, selector=None, row=None, col=None, secondary_y=None, **kwargs ): """ Perform a property update operation on all images that satisfy the specified selection criteria Parameters ---------- patch: dict or None (default None) Dictionary of property updates to be applied to all images that satisfy the selection criteria. selector: dict or None (default None) Dict to use as selection criteria. Traces will be selected if they contain properties corresponding to all of the dictionary's keys, with values that exactly match the supplied values. If None (the default), all images are selected. row, col: int or None (default None) Subplot row and column index of images to select. To select images by row and column, the Figure must have been created using plotly.subplots.make_subplots. To select only those image that are in paper coordinates, set row and col to the string 'paper'. If None (the default), all images are selected. secondary_y: boolean or None (default None) * If True, only select images associated with the secondary y-axis of the subplot. * If False, only select images associated with the primary y-axis of the subplot. * If None (the default), do not filter images based on secondary y-axis. To select images by secondary y-axis, the Figure must have been created using plotly.subplots.make_subplots. See the docstring for the specs argument to make_subplots for more info on creating subplots with secondary y-axes. **kwargs Additional property updates to apply to each selected image. If a property is specified in both patch and in **kwargs then the one in **kwargs takes precedence. Returns ------- self Returns the Figure object that the method was called on """ for obj in self._select_annotations_like( prop="images", selector=selector, row=row, col=col, secondary_y=secondary_y, ): obj.update(patch, **kwargs) return self def add_layout_image( self, arg=None, layer=None, name=None, opacity=None, sizex=None, sizey=None, sizing=None, source=None, templateitemname=None, visible=None, x=None, xanchor=None, xref=None, y=None, yanchor=None, yref=None, row=None, col=None, secondary_y=None, **kwargs ): """ Create and add a new image to the figure's layout Parameters ---------- arg instance of Image or dict with compatible properties layer Specifies whether images are drawn below or above traces. When `xref` and `yref` are both set to `paper`, image is drawn below the entire plot area. name When used in a template, named items are created in the output figure in addition to any items the figure already has in this array. You can modify these items in the output figure by making your own item with `templateitemname` matching this `name` alongside your modifications (including `visible: false` or `enabled: false` to hide it). Has no effect outside of a template. opacity Sets the opacity of the image. sizex Sets the image container size horizontally. The image will be sized based on the `position` value. When `xref` is set to `paper`, units are sized relative to the plot width. When `xref` ends with ` domain`, units are sized relative to the axis width. sizey Sets the image container size vertically. The image will be sized based on the `position` value. When `yref` is set to `paper`, units are sized relative to the plot height. When `yref` ends with ` domain`, units are sized relative to the axis height. sizing Specifies which dimension of the image to constrain. source Specifies the URL of the image to be used. The URL must be accessible from the domain where the plot code is run, and can be either relative or absolute. templateitemname Used to refer to a named item in this array in the template. Named items from the template will be created even without a matching item in the input figure, but you can modify one by making an item with `templateitemname` matching its `name`, alongside your modifications (including `visible: false` or `enabled: false` to hide it). If there is no template or no matching item, this item will be hidden unless you explicitly show it with `visible: true`. visible Determines whether or not this image is visible. x Sets the image's x position. When `xref` is set to `paper`, units are sized relative to the plot height. See `xref` for more info xanchor Sets the anchor for the x position xref Sets the images's x coordinate axis. If set to a x axis id (e.g. "x" or "x2"), the `x` position refers to a x coordinate. If set to "paper", the `x` position refers to the distance from the left of the plotting area in normalized coordinates where 0 (1) corresponds to the left (right). If set to a x axis ID followed by "domain" (separated by a space), the position behaves like for "paper", but refers to the distance in fractions of the domain length from the left of the domain of that axis: e.g., *x2 domain* refers to the domain of the second x axis and a x position of 0.5 refers to the point between the left and the right of the domain of the second x axis. y Sets the image's y position. When `yref` is set to `paper`, units are sized relative to the plot height. See `yref` for more info yanchor Sets the anchor for the y position. yref Sets the images's y coordinate axis. If set to a y axis id (e.g. "y" or "y2"), the `y` position refers to a y coordinate. If set to "paper", the `y` position refers to the distance from the bottom of the plotting area in normalized coordinates where 0 (1) corresponds to the bottom (top). If set to a y axis ID followed by "domain" (separated by a space), the position behaves like for "paper", but refers to the distance in fractions of the domain length from the bottom of the domain of that axis: e.g., *y2 domain* refers to the domain of the second y axis and a y position of 0.5 refers to the point between the bottom and the top of the domain of the second y axis. row Subplot row for image col Subplot column for image secondary_y Whether to add image to secondary y-axis Returns ------- FigureWidget """ from plotly.graph_objs import layout as _layout new_obj = _layout.Image( arg, layer=layer, name=name, opacity=opacity, sizex=sizex, sizey=sizey, sizing=sizing, source=source, templateitemname=templateitemname, visible=visible, x=x, xanchor=xanchor, xref=xref, y=y, yanchor=yanchor, yref=yref, **kwargs ) return self._add_annotation_like( "image", "images", new_obj, row=row, col=col, secondary_y=secondary_y, ) def select_shapes(self, selector=None, row=None, col=None, secondary_y=None): """ Select shapes from a particular subplot cell and/or shapes that satisfy custom selection criteria. Parameters ---------- selector: dict or None (default None) Dict to use as selection criteria. Annotations will be selected if they contain properties corresponding to all of the dictionary's keys, with values that exactly match the supplied values. If None (the default), all shapes are selected. row, col: int or None (default None) Subplot row and column index of shapes to select. To select shapes by row and column, the Figure must have been created using plotly.subplots.make_subplots. To select only those shape that are in paper coordinates, set row and col to the string 'paper'. If None (the default), all shapes are selected. secondary_y: boolean or None (default None) * If True, only select shapes associated with the secondary y-axis of the subplot. * If False, only select shapes associated with the primary y-axis of the subplot. * If None (the default), do not filter shapes based on secondary y-axis. To select shapes by secondary y-axis, the Figure must have been created using plotly.subplots.make_subplots. See the docstring for the specs argument to make_subplots for more info on creating subplots with secondary y-axes. Returns ------- generator Generator that iterates through all of the shapes that satisfy all of the specified selection criteria """ return self._select_annotations_like( "shapes", selector=selector, row=row, col=col, secondary_y=secondary_y ) def for_each_shape(self, fn, selector=None, row=None, col=None, secondary_y=None): """ Apply a function to all shapes that satisfy the specified selection criteria Parameters ---------- fn: Function that inputs a single shape object. selector: dict or None (default None) Dict to use as selection criteria. Traces will be selected if they contain properties corresponding to all of the dictionary's keys, with values that exactly match the supplied values. If None (the default), all shapes are selected. row, col: int or None (default None) Subplot row and column index of shapes to select. To select shapes by row and column, the Figure must have been created using plotly.subplots.make_subplots. To select only those shapes that are in paper coordinates, set row and col to the string 'paper'. If None (the default), all shapes are selected. secondary_y: boolean or None (default None) * If True, only select shapes associated with the secondary y-axis of the subplot. * If False, only select shapes associated with the primary y-axis of the subplot. * If None (the default), do not filter shapes based on secondary y-axis. To select shapes by secondary y-axis, the Figure must have been created using plotly.subplots.make_subplots. See the docstring for the specs argument to make_subplots for more info on creating subplots with secondary y-axes. Returns ------- self Returns the Figure object that the method was called on """ for obj in self._select_annotations_like( prop="shapes", selector=selector, row=row, col=col, secondary_y=secondary_y, ): fn(obj) return self def update_shapes( self, patch=None, selector=None, row=None, col=None, secondary_y=None, **kwargs ): """ Perform a property update operation on all shapes that satisfy the specified selection criteria Parameters ---------- patch: dict or None (default None) Dictionary of property updates to be applied to all shapes that satisfy the selection criteria. selector: dict or None (default None) Dict to use as selection criteria. Traces will be selected if they contain properties corresponding to all of the dictionary's keys, with values that exactly match the supplied values. If None (the default), all shapes are selected. row, col: int or None (default None) Subplot row and column index of shapes to select. To select shapes by row and column, the Figure must have been created using plotly.subplots.make_subplots. To select only those shape that are in paper coordinates, set row and col to the string 'paper'. If None (the default), all shapes are selected. secondary_y: boolean or None (default None) * If True, only select shapes associated with the secondary y-axis of the subplot. * If False, only select shapes associated with the primary y-axis of the subplot. * If None (the default), do not filter shapes based on secondary y-axis. To select shapes by secondary y-axis, the Figure must have been created using plotly.subplots.make_subplots. See the docstring for the specs argument to make_subplots for more info on creating subplots with secondary y-axes. **kwargs Additional property updates to apply to each selected shape. If a property is specified in both patch and in **kwargs then the one in **kwargs takes precedence. Returns ------- self Returns the Figure object that the method was called on """ for obj in self._select_annotations_like( prop="shapes", selector=selector, row=row, col=col, secondary_y=secondary_y, ): obj.update(patch, **kwargs) return self def add_shape( self, arg=None, editable=None, fillcolor=None, fillrule=None, layer=None, line=None, name=None, opacity=None, path=None, templateitemname=None, type=None, visible=None, x0=None, x1=None, xanchor=None, xref=None, xsizemode=None, y0=None, y1=None, yanchor=None, yref=None, ysizemode=None, row=None, col=None, secondary_y=None, **kwargs ): """ Create and add a new shape to the figure's layout Parameters ---------- arg instance of Shape or dict with compatible properties editable Determines whether the shape could be activated for edit or not. Has no effect when the older editable shapes mode is enabled via `config.editable` or `config.edits.shapePosition`. fillcolor Sets the color filling the shape's interior. Only applies to closed shapes. fillrule Determines which regions of complex paths constitute the interior. For more info please visit https://developer.mozilla.org/en- US/docs/Web/SVG/Attribute/fill-rule layer Specifies whether shapes are drawn below or above traces. line :class:`plotly.graph_objects.layout.shape.Line` instance or dict with compatible properties name When used in a template, named items are created in the output figure in addition to any items the figure already has in this array. You can modify these items in the output figure by making your own item with `templateitemname` matching this `name` alongside your modifications (including `visible: false` or `enabled: false` to hide it). Has no effect outside of a template. opacity Sets the opacity of the shape. path For `type` "path" - a valid SVG path with the pixel values replaced by data values in `xsizemode`/`ysizemode` being "scaled" and taken unmodified as pixels relative to `xanchor` and `yanchor` in case of "pixel" size mode. There are a few restrictions / quirks only absolute instructions, not relative. So the allowed segments are: M, L, H, V, Q, C, T, S, and Z arcs (A) are not allowed because radius rx and ry are relative. In the future we could consider supporting relative commands, but we would have to decide on how to handle date and log axes. Note that even as is, Q and C Bezier paths that are smooth on linear axes may not be smooth on log, and vice versa. no chained "polybezier" commands - specify the segment type for each one. On category axes, values are numbers scaled to the serial numbers of categories because using the categories themselves there would be no way to describe fractional positions On data axes: because space and T are both normal components of path strings, we can't use either to separate date from time parts. Therefore we'll use underscore for this purpose: 2015-02-21_13:45:56.789 templateitemname Used to refer to a named item in this array in the template. Named items from the template will be created even without a matching item in the input figure, but you can modify one by making an item with `templateitemname` matching its `name`, alongside your modifications (including `visible: false` or `enabled: false` to hide it). If there is no template or no matching item, this item will be hidden unless you explicitly show it with `visible: true`. type Specifies the shape type to be drawn. If "line", a line is drawn from (`x0`,`y0`) to (`x1`,`y1`) with respect to the axes' sizing mode. If "circle", a circle is drawn from ((`x0`+`x1`)/2, (`y0`+`y1`)/2)) with radius (|(`x0`+`x1`)/2 - `x0`|, |(`y0`+`y1`)/2 -`y0`)|) with respect to the axes' sizing mode. If "rect", a rectangle is drawn linking (`x0`,`y0`), (`x1`,`y0`), (`x1`,`y1`), (`x0`,`y1`), (`x0`,`y0`) with respect to the axes' sizing mode. If "path", draw a custom SVG path using `path`. with respect to the axes' sizing mode. visible Determines whether or not this shape is visible. x0 Sets the shape's starting x position. See `type` and `xsizemode` for more info. x1 Sets the shape's end x position. See `type` and `xsizemode` for more info. xanchor Only relevant in conjunction with `xsizemode` set to "pixel". Specifies the anchor point on the x axis to which `x0`, `x1` and x coordinates within `path` are relative to. E.g. useful to attach a pixel sized shape to a certain data value. No effect when `xsizemode` not set to "pixel". xref Sets the shape's x coordinate axis. If set to a x axis id (e.g. "x" or "x2"), the `x` position refers to a x coordinate. If set to "paper", the `x` position refers to the distance from the left of the plotting area in normalized coordinates where 0 (1) corresponds to the left (right). If set to a x axis ID followed by "domain" (separated by a space), the position behaves like for "paper", but refers to the distance in fractions of the domain length from the left of the domain of that axis: e.g., *x2 domain* refers to the domain of the second x axis and a x position of 0.5 refers to the point between the left and the right of the domain of the second x axis. If the axis `type` is "log", then you must take the log of your desired range. If the axis `type` is "date", then you must convert the date to unix time in milliseconds. xsizemode Sets the shapes's sizing mode along the x axis. If set to "scaled", `x0`, `x1` and x coordinates within `path` refer to data values on the x axis or a fraction of the plot area's width (`xref` set to "paper"). If set to "pixel", `xanchor` specifies the x position in terms of data or plot fraction but `x0`, `x1` and x coordinates within `path` are pixels relative to `xanchor`. This way, the shape can have a fixed width while maintaining a position relative to data or plot fraction. y0 Sets the shape's starting y position. See `type` and `ysizemode` for more info. y1 Sets the shape's end y position. See `type` and `ysizemode` for more info. yanchor Only relevant in conjunction with `ysizemode` set to "pixel". Specifies the anchor point on the y axis to which `y0`, `y1` and y coordinates within `path` are relative to. E.g. useful to attach a pixel sized shape to a certain data value. No effect when `ysizemode` not set to "pixel". yref Sets the annotation's y coordinate axis. If set to a y axis id (e.g. "y" or "y2"), the `y` position refers to a y coordinate. If set to "paper", the `y` position refers to the distance from the bottom of the plotting area in normalized coordinates where 0 (1) corresponds to the bottom (top). If set to a y axis ID followed by "domain" (separated by a space), the position behaves like for "paper", but refers to the distance in fractions of the domain length from the bottom of the domain of that axis: e.g., *y2 domain* refers to the domain of the second y axis and a y position of 0.5 refers to the point between the bottom and the top of the domain of the second y axis. ysizemode Sets the shapes's sizing mode along the y axis. If set to "scaled", `y0`, `y1` and y coordinates within `path` refer to data values on the y axis or a fraction of the plot area's height (`yref` set to "paper"). If set to "pixel", `yanchor` specifies the y position in terms of data or plot fraction but `y0`, `y1` and y coordinates within `path` are pixels relative to `yanchor`. This way, the shape can have a fixed height while maintaining a position relative to data or plot fraction. row Subplot row for shape col Subplot column for shape secondary_y Whether to add shape to secondary y-axis Returns ------- FigureWidget """ from plotly.graph_objs import layout as _layout new_obj = _layout.Shape( arg, editable=editable, fillcolor=fillcolor, fillrule=fillrule, layer=layer, line=line, name=name, opacity=opacity, path=path, templateitemname=templateitemname, type=type, visible=visible, x0=x0, x1=x1, xanchor=xanchor, xref=xref, xsizemode=xsizemode, y0=y0, y1=y1, yanchor=yanchor, yref=yref, ysizemode=ysizemode, **kwargs ) return self._add_annotation_like( "shape", "shapes", new_obj, row=row, col=col, secondary_y=secondary_y, )
42.451301
88
0.585288
fc14a2b34a7f19adcaa0e680ea67d1682268aa83
42
py
Python
benchmarking/awrams/benchmarking/meta/__init__.py
Zac-HD/awra_cms
ebc51df859ee665d936cf9600ea29dc8e45321d7
[ "NetCDF" ]
20
2016-12-01T03:13:50.000Z
2021-12-02T23:43:38.000Z
benchmarking/awrams/benchmarking/meta/__init__.py
Zac-HD/awra_cms
ebc51df859ee665d936cf9600ea29dc8e45321d7
[ "NetCDF" ]
2
2018-02-05T03:42:11.000Z
2018-04-27T05:49:44.000Z
benchmarking/awrams/benchmarking/meta/__init__.py
Zac-HD/awra_cms
ebc51df859ee665d936cf9600ea29dc8e45321d7
[ "NetCDF" ]
22
2016-12-13T19:57:43.000Z
2021-12-08T02:52:19.000Z
''' Metadata for observation datasets '''
10.5
33
0.714286
0845d480d8607dce1e9bfcd30b48ae255a461e2e
9,001
py
Python
inception_resnet_v2.py
kentsommer/keras-inception-resnetV2
14994dfca36ca09725998a1abf81ea2027dbcb76
[ "Apache-2.0" ]
19
2017-02-08T12:42:50.000Z
2022-03-25T12:37:07.000Z
inception_resnet_v2.py
kentsommer/keras-inception-resnetV2
14994dfca36ca09725998a1abf81ea2027dbcb76
[ "Apache-2.0" ]
5
2017-02-09T08:57:14.000Z
2020-02-28T08:57:41.000Z
inception_resnet_v2.py
kentsommer/keras-inception-resnetV2
14994dfca36ca09725998a1abf81ea2027dbcb76
[ "Apache-2.0" ]
9
2017-05-07T06:38:54.000Z
2020-02-18T14:08:30.000Z
''' Copyright 2017 TensorFlow Authors and Kent Sommer Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ''' # Sys import warnings # Keras Core from keras.layers import Input, merge, Dropout, Dense, Lambda, Flatten, Activation from keras.layers.convolutional import MaxPooling2D, Convolution2D, AveragePooling2D from keras.layers.normalization import BatchNormalization from keras.models import Model # Backend from keras import backend as K # Utils from keras.utils.layer_utils import convert_all_kernels_in_model from keras.utils.data_utils import get_file ######################################################################################### # Implements the Inception ResNet v2 (http://arxiv.org/pdf/1602.07261v1.pdf) in Keras. # ######################################################################################### # TH_WEIGHTS_PATH = 'https://github.com/kentsommer/keras-inceptionV4/releases/download/2.0/inception-v4_weights_th_dim_ordering_th_kernels.h5' # TF_WEIGHTS_PATH = 'https://github.com/kentsommer/keras-inceptionV4/releases/download/2.0/inception-v4_weights_tf_dim_ordering_tf_kernels.h5' def do_scale(x, scale): y = scale * x return y def conv2d_bn(x, nb_filter, nb_row, nb_col, border_mode='same', subsample=(1, 1), bias=False, activ_fn='relu', normalize=True): """ Utility function to apply conv + BN. (Slightly modified from https://github.com/fchollet/keras/blob/master/keras/applications/inception_v3.py) """ if K.image_dim_ordering() == "th": channel_axis = 1 else: channel_axis = -1 if not normalize: bias = True x = Convolution2D(nb_filter, nb_row, nb_col, subsample=subsample, border_mode=border_mode, bias=bias)(x) if normalize: x = BatchNormalization(axis=channel_axis)(x) if activ_fn: x = Activation(activ_fn)(x) return x def block35(input, scale=1.0, activation_fn='relu'): if K.image_dim_ordering() == "th": channel_axis = 1 else: channel_axis = -1 shortcut = input tower_conv = conv2d_bn(input, 32, 1, 1, activ_fn=activation_fn) tower_conv1_0 = conv2d_bn(input, 32, 1, 1, activ_fn=activation_fn) tower_conv1_1 = conv2d_bn(tower_conv1_0, 32, 3, 3, activ_fn=activation_fn) tower_conv2_0 = conv2d_bn(input, 32, 1, 1, activ_fn=activation_fn) tower_conv2_1 = conv2d_bn(tower_conv2_0, 48, 3, 3, activ_fn=activation_fn) tower_conv2_2 = conv2d_bn(tower_conv2_1, 64, 3, 3, activ_fn=activation_fn) mixed = merge([tower_conv, tower_conv1_1, tower_conv2_2], mode='concat', concat_axis=channel_axis) up = conv2d_bn(mixed, 320, 1, 1, activ_fn=False, normalize=False) up = Lambda(do_scale, output_shape=K.int_shape(up)[1:], arguments={'scale':scale})(up) net = merge([shortcut, up], mode='sum') if activation_fn: net = Activation(activation_fn)(net) return net def block17(input, scale=1.0, activation_fn='relu'): if K.image_dim_ordering() == "th": channel_axis = 1 else: channel_axis = -1 shortcut = input tower_conv = conv2d_bn(input, 192, 1, 1, activ_fn=activation_fn) tower_conv1_0 = conv2d_bn(input, 128, 1, 1, activ_fn=activation_fn) tower_conv1_1 = conv2d_bn(tower_conv1_0, 160, 1, 7, activ_fn=activation_fn) tower_conv1_2 = conv2d_bn(tower_conv1_1, 192, 7, 1, activ_fn=activation_fn) mixed = merge([tower_conv, tower_conv1_2], mode='concat', concat_axis=channel_axis) up = conv2d_bn(mixed, 1088, 1, 1, activ_fn=False, normalize=False) up = Lambda(do_scale, output_shape=K.int_shape(up)[1:], arguments={'scale':scale})(up) net = merge([shortcut, up], mode='sum') if activation_fn: net = Activation(activation_fn)(net) return net def block8(input, scale=1.0, activation_fn='relu'): if K.image_dim_ordering() == "th": channel_axis = 1 else: channel_axis = -1 shortcut = input tower_conv = conv2d_bn(input, 192, 1, 1, activ_fn=activation_fn) tower_conv1_0 = conv2d_bn(input, 192, 1, 1, activ_fn=activation_fn) tower_conv1_1 = conv2d_bn(tower_conv1_0, 224, 1, 3, activ_fn=activation_fn) tower_conv1_2 = conv2d_bn(tower_conv1_1, 256, 3, 1, activ_fn=activation_fn) mixed = merge([tower_conv, tower_conv1_2], mode='concat', concat_axis=channel_axis) up = conv2d_bn(mixed, 2080, 1, 1, activ_fn=False, normalize=False) up = Lambda(do_scale, output_shape=K.int_shape(up)[1:], arguments={'scale':scale})(up) net = merge([shortcut, up], mode='sum') if activation_fn: net = Activation(activation_fn)(net) return net def inception_resnet_v2(num_classes, dropout_keep_prob, weights): ''' Creates the inception_resnet_v2 network Args: num_classes: number of classes dropout_keep_prob: float, the fraction to keep before final layer. Returns: logits: the logits outputs of the model. ''' # Input Shape is 299 x 299 x 3 (tf) or 3 x 299 x 299 (th) if K.image_dim_ordering() == 'th': inputs = Input((3, 299, 299)) channel_axis = 1 else: inputs = Input((299, 299, 3)) channel_axis = -1 ######################### # Build Base of network # ######################### # 149 x 149 x 32 net = conv2d_bn(inputs, 32, 3, 3, subsample=(2,2), border_mode='valid') # 147 x 147 x 32 net = conv2d_bn(net, 32, 3, 3, border_mode='valid') # 147 x 147 x 64 net = conv2d_bn(net, 64, 3, 3) # 73 x 73 x 64 net = MaxPooling2D((3,3), strides=(2,2), border_mode='valid')(net) # 73 x 73 x 80 net = conv2d_bn(net, 80, 1, 1, border_mode='valid') # 71 x 71 x 192 net = conv2d_bn(net, 192, 3, 3, border_mode='valid') # 35 x 35 x 192 net = MaxPooling2D((3,3), strides=(2,2), border_mode='valid')(net) ## Tower One tower_conv = conv2d_bn(net, 96, 1, 1) tower_conv1_0 = conv2d_bn(net, 48, 1, 1) tower_conv1_1 = conv2d_bn(tower_conv1_0, 64, 5, 5) tower_conv2_0 = conv2d_bn(net, 64, 1, 1) tower_conv2_1 = conv2d_bn(tower_conv2_0, 96, 3, 3) tower_conv2_2 = conv2d_bn(tower_conv2_1, 96, 3, 3) tower_pool = AveragePooling2D((3, 3), strides=(1, 1), border_mode='same')(net) tower_pool_1 = conv2d_bn(tower_pool, 64, 1, 1) net = merge([tower_conv, tower_conv1_1, tower_conv2_2, tower_pool_1], mode='concat', concat_axis=channel_axis) # 10 x block35 for idx in xrange(10): net = block35(net, scale=0.17) ## Tower Two tower_conv = conv2d_bn(net, 384, 3, 3, subsample=(2,2), border_mode='valid') tower_conv1_0 = conv2d_bn(net, 256, 1, 1) tower_conv1_1 = conv2d_bn(tower_conv1_0, 256, 3, 3) tower_conv1_2 = conv2d_bn(tower_conv1_1, 384, 3, 3, subsample=(2,2), border_mode='valid') tower_pool = MaxPooling2D((3, 3), strides=(2, 2), border_mode='valid')(net) net = merge([tower_conv, tower_conv1_2, tower_pool], mode='concat', concat_axis=channel_axis) # 20 x block17 for idx in xrange(20): net = block17(net, scale=0.10) ## Tower Three tower_conv = conv2d_bn(net, 256, 1, 1) tower_conv_1 = conv2d_bn(tower_conv, 384, 3, 3, subsample=(2,2), border_mode='valid') tower_conv1 = conv2d_bn(net, 256, 1, 1) tower_conv1_1 = conv2d_bn(tower_conv1, 288, 3, 3, subsample=(2,2), border_mode='valid') tower_conv2 = conv2d_bn(net, 256, 1, 1) tower_conv2_1 = conv2d_bn(tower_conv2, 288, 3, 3) tower_conv2_2 = conv2d_bn(tower_conv2_1, 320, 3, 3, subsample=(2,2), border_mode='valid') tower_pool = MaxPooling2D((3,3), strides=(2,2), border_mode='valid')(net) net = merge([tower_conv_1, tower_conv1_1, tower_conv2_2, tower_pool], mode='concat', concat_axis=channel_axis) # 9 x block8 for idx in xrange(9): net = block8(net, scale=0.20) net = block8(net, activation_fn=False) # Logits net = conv2d_bn(net, 1536, 1, 1) net = AveragePooling2D((8,8), border_mode='valid')(net) net = Flatten()(net) net = Dropout(dropout_keep_prob)(net) predictions = Dense(output_dim=num_classes, activation='softmax')(net) model = Model(inputs, predictions, name='inception_resnet_v2') if weights: model.load_weights(weights, by_name=True) print("Loaded Model Weights!") return model def create_model(num_classes=1001, dropout_keep_prob=0.8, weights=None): return inception_resnet_v2(num_classes, dropout_keep_prob, weights)
33.337037
142
0.661482
de72a22cb48afce070d22cea650269165b43482e
804
py
Python
examples/vtk/pyevtk_grid.py
lanahuong/dubrayn.github.io
fd78edb38442966395161cfcf9dfd9b464703ddd
[ "MIT" ]
7
2019-04-12T07:46:05.000Z
2022-03-30T06:11:47.000Z
examples/vtk/pyevtk_grid.py
lanahuong/dubrayn.github.io
fd78edb38442966395161cfcf9dfd9b464703ddd
[ "MIT" ]
3
2018-03-05T20:35:50.000Z
2022-03-28T13:09:44.000Z
examples/vtk/pyevtk_grid.py
lanahuong/dubrayn.github.io
fd78edb38442966395161cfcf9dfd9b464703ddd
[ "MIT" ]
10
2017-10-04T07:05:51.000Z
2020-12-15T12:08:32.000Z
#!/usr/bin/env python3 import numpy as np from pyevtk.hl import gridToVTK def mandelbrot_set(X, Y, maxiter, horizon = 2.0): C = X + Y[:, None] * 1j N = np.zeros(C.shape, dtype = int) Z = np.zeros(C.shape, np.complex64) for n in range(maxiter): if n % (maxiter / 10) == 0: print('progress: %d/%d' % (n, maxiter)) I = np.less(abs(Z), horizon) N[I] = n Z[I] = Z[I] ** 2 + C[I] return Z.transpose(), N.transpose() nx = 800 ny = 600 x = np.linspace(-2.25, 0.75, nx, dtype=np.float32) y = np.linspace(-1.25, 1.25, ny, dtype=np.float32) z = np.linspace(0.0, 1.0, 1, dtype=np.float32) Z, N = mandelbrot_set(x, y, 2000, 2.0) filename = 'mandel_grid' gridToVTK(filename, x, y, z, pointData = {'N': N.reshape((nx, ny, 1), order = 'C')}) print('%s.vtr generated' % (filename))
25.935484
84
0.598259
30ddc9541098abb20a9d81382d10c525bbc2aa4e
2,170
py
Python
Test_Cases/Remover_Producto_Carrito_Compras.py
w2k31984/Swag_Labs_Automation_QA
fbed455dc1b3d4e5894a9e47b6d8e31e9689f11b
[ "MIT" ]
null
null
null
Test_Cases/Remover_Producto_Carrito_Compras.py
w2k31984/Swag_Labs_Automation_QA
fbed455dc1b3d4e5894a9e47b6d8e31e9689f11b
[ "MIT" ]
null
null
null
Test_Cases/Remover_Producto_Carrito_Compras.py
w2k31984/Swag_Labs_Automation_QA
fbed455dc1b3d4e5894a9e47b6d8e31e9689f11b
[ "MIT" ]
null
null
null
import time import HtmlTestRunner import unittest from selenium import webdriver class myTestRemoveProductToCart(unittest.TestCase): def testRemoverProductoCarrito(self): driver = webdriver.Chrome(executable_path=r'C:\\Users\\cristian_parada\\Desktop\\Automatizacion_Test_Cases_Ecommerce\\chromedriver.exe') driver.get('https://www.saucedemo.com/') time.sleep(2) usuario = driver.find_element_by_id('user-name') usuario.clear() usuario.send_keys('standard_user') contrasena = driver.find_element_by_id('password') contrasena.clear() contrasena.send_keys('secret_sauce') time.sleep(3) driver.find_element_by_id('login-button').click() time.sleep(2) #Seleccionando productos en pantalla de productos a carrito de compras (Mochila) driver.find_element_by_id('add-to-cart-sauce-labs-backpack').click() time.sleep(2) #Seleccionando productos en pantalla de productos a carrito de compras (Fleece Jacket) driver.find_element_by_id('add-to-cart-sauce-labs-fleece-jacket').click() time.sleep(2) # Seleccionando productos en pantalla de productos a carrito de compras (Bolt T-Shirt) driver.find_element_by_id('add-to-cart-sauce-labs-bolt-t-shirt').click() time.sleep(2) #Revisando en carrito de compra los productos seleccionados. driver.find_element_by_id('shopping_cart_container').click() time.sleep(5) #Retornar a pantalla de productos dando click a boton driver.find_element_by_id('continue-shopping').click() time.sleep(2) #Removiendo producto dando click a boton de remover en el producto (Mochila) driver.find_element_by_id('remove-sauce-labs-backpack').click() time.sleep(2) #Revisando en carrito de compra que no aparezca el producto seleccionado. driver.find_element_by_id('shopping_cart_container').click() time.sleep(2) driver.stop_client() driver.quit() if __name__ == '__main__': unittest.main(testRunner=HtmlTestRunner.HTMLTestRunner(output=r'C:\Users\cristian_parada\Desktop\Automatizacion_Test_Cases_Ecommerce\Reports'))
41.730769
147
0.724885
ddf8121e218cbdf7a65c5ea3427b2ae8e7c30b82
1,005
py
Python
investment_dashboard/investment_dashboard/urls.py
mjenrungrot/investment-dashboard
89b296a635ee3c29171f7bf88cc8e49250981637
[ "MIT" ]
null
null
null
investment_dashboard/investment_dashboard/urls.py
mjenrungrot/investment-dashboard
89b296a635ee3c29171f7bf88cc8e49250981637
[ "MIT" ]
4
2017-12-19T08:39:10.000Z
2017-12-20T10:59:38.000Z
investment_dashboard/investment_dashboard/urls.py
mjenrungrot/investment-dashboard
89b296a635ee3c29171f7bf88cc8e49250981637
[ "MIT" ]
null
null
null
"""investment_dashboard URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.0/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('portfolio/', include('portfolio.urls')), path('equity/', include('equity.urls')), path('', include('home.urls')), ]
37.222222
78
0.690547
88ef526a46829c74495dd1265be36a3390aff55e
510
py
Python
cursoemvideo/exercicios/ex075.py
mrqssjeff/project-python
b3b08f2acfe825640a5ee92cf9d6fa45ab580384
[ "MIT" ]
null
null
null
cursoemvideo/exercicios/ex075.py
mrqssjeff/project-python
b3b08f2acfe825640a5ee92cf9d6fa45ab580384
[ "MIT" ]
null
null
null
cursoemvideo/exercicios/ex075.py
mrqssjeff/project-python
b3b08f2acfe825640a5ee92cf9d6fa45ab580384
[ "MIT" ]
null
null
null
num = (int(input(f'Digite um número:')), \ int(input('Digite outro número: ')), int(input('Digite mais um número: ')), int(input('Digite outro número: '))) print(f'Você digitou os valores {num}') print(f'O valor 9 aparece {num.count(9)} vezes') if 3 in num: print(f'O valor 3 apareceu na {num.index(3)+1}ª posição') else: print('O valor 3 não foi digitado nenhuma vez.') print(f'Os valores pares digitados foram: ', end=' ') for n in num: if n % 2 == 0: print(n, end=' ')
34
61
0.615686
102236ba33a72fa35463093b6c39bfa7b50d559a
450
py
Python
data/scripts/templates/object/tangible/food/spice/shared_spice_giggledust.py
obi-two/GameServer
7d37024e2291a97d49522610cd8f1dbe5666afc2
[ "MIT" ]
20
2015-02-23T15:11:56.000Z
2022-03-18T20:56:48.000Z
data/scripts/templates/object/tangible/food/spice/shared_spice_giggledust.py
apathyboy/swganh
665128efe9154611dec4cb5efc61d246dd095984
[ "MIT" ]
null
null
null
data/scripts/templates/object/tangible/food/spice/shared_spice_giggledust.py
apathyboy/swganh
665128efe9154611dec4cb5efc61d246dd095984
[ "MIT" ]
20
2015-04-04T16:35:59.000Z
2022-03-24T14:54:37.000Z
#### NOTICE: THIS FILE IS AUTOGENERATED #### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY #### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES from swgpy.object import * def create(kernel): result = Tangible() result.template = "object/tangible/food/spice/shared_spice_giggledust.iff" result.attribute_template_id = 5 result.stfName("food_name","giggledust") #### BEGIN MODIFICATIONS #### #### END MODIFICATIONS #### return result
26.470588
75
0.728889
9fa4bd36b1b13aededb23ae2f12bcbe75967698d
1,213
py
Python
cosmosis-standard-library/boltzmann/class/class_v2.4.1/python/setup.py
ktanidis2/Modified_CosmoSIS_for_galaxy_number_count_angular_power_spectra
07e5d308c6a8641a369a3e0b8d13c4104988cd2b
[ "BSD-2-Clause" ]
3
2017-04-26T07:17:53.000Z
2020-01-31T02:41:06.000Z
21cmMG_hi_class/python/setup.py
evanjarena/21cmMG
6b5e43932b552d5b9cb352774d404a7cff2206f5
[ "BSD-4-Clause-UC" ]
null
null
null
21cmMG_hi_class/python/setup.py
evanjarena/21cmMG
6b5e43932b552d5b9cb352774d404a7cff2206f5
[ "BSD-4-Clause-UC" ]
1
2021-06-11T15:29:43.000Z
2021-06-11T15:29:43.000Z
from distutils.core import setup from distutils.extension import Extension from Cython.Distutils import build_ext import numpy as nm import os import subprocess as sbp import os.path as osp # Recover the gcc compiler GCCPATH_STRING = sbp.Popen( ['gcc', '-print-libgcc-file-name'], stdout=sbp.PIPE).communicate()[0] GCCPATH = osp.normpath(osp.dirname(GCCPATH_STRING)) # Recover the CLASS version with open(os.path.join('..', 'include', 'common.h'), 'r') as v_file: for line in v_file: if line.find("_VERSION_") != -1: # get rid of the " and the v VERSION = line.split()[-1][2:-1] break setup( name='classy', version=VERSION, description='Python interface to the Cosmological Boltzmann code CLASS', url='http://www.class-code.net', cmdclass={'build_ext': build_ext}, ext_modules=[Extension("classy", ["classy.pyx"], include_dirs=[nm.get_include(), "../include"], libraries=["class"], library_dirs=["../", GCCPATH], extra_link_args=['-lgomp'], )], data_files=(('bbn', ['../bbn/sBBN.dat']),) )
31.921053
76
0.587799
07178552a9fc1382367f8e6bca0ce618f846890d
4,801
py
Python
test/test_igraph.py
cpacker/graphzip
d10549dd8eb5c08777f2fd8309238ded9a65cb3f
[ "MIT" ]
13
2017-02-28T21:55:11.000Z
2022-01-01T20:43:38.000Z
test/test_igraph.py
cpacker/graphzip
d10549dd8eb5c08777f2fd8309238ded9a65cb3f
[ "MIT" ]
null
null
null
test/test_igraph.py
cpacker/graphzip
d10549dd8eb5c08777f2fd8309238ded9a65cb3f
[ "MIT" ]
3
2018-10-16T20:41:01.000Z
2021-12-28T08:58:44.000Z
import unittest from collections import defaultdict from igraph import Graph class TestiGraph(unittest.TestCase): """ Basic tests to make sure iGraph is working the way we expect for the purposes of compress.py """ def setUp(self): """ Simple example graph: 1010,A ----- 1011,B | / | / | / | / | / | / 1100,C ----- 1101,D """ G = Graph() G.add_vertex("1010", id=1010, label="A") # index 0 G.add_vertex("1011", id=1011, label="B") # index 1 G.add_vertex("1100", id=1100, label="C") # index 2 G.add_vertex("1101", id=1101, label="D") # index 3 G.add_edge("1010", "1100") G.add_edge("1010", "1011") G.add_edge("1011", "1100") G.add_edge("1100", "1101") Gs = Graph() # Add the vertices in a different order so we get different indices Gs.add_vertex("1011", label="B") # index 0 Gs.add_vertex("1010", label="A") # index 1 Gs.add_edge("1010", "1011") self.G = G self.Gs = Gs def test_subisomorphisms(self): G = self.G Gs = self.Gs c1 = [int(v["name"]) for v in G.vs] c2 = [int(v["name"]) for v in Gs.vs] vmap = G.get_subisomorphisms_vf2(Gs, color1=c1, color2=c2) # Check that we get an isomorphism # Graph Gs: index -> element :Graph G # vertex 0 (B) -> vertex 1 (B) # vertex 1 (A) -> vertex 0 (A) # Graph G: :Graph Gs # vertex 0 (A) -> vertex 1 (A) # vertex 1 (B) -> vertex 0 (A) self.assertEqual(vmap, [[1, 0]]) def test_isomorphic(self): self.assertFalse(self.G.isomorphic_vf2(self.Gs)) # basic isomorphism w/o coloring self.Gs.add_vertex("1100") self.Gs.add_vertex("1101_wrong") self.Gs.add_edge("1010", "1100") self.Gs.add_edge("1011", "1100") self.Gs.add_edge("1100", "1101_wrong") self.assertTrue(self.G.isomorphic_vf2(self.Gs)) # check that isomorphic checks using coloring works # (by using a field called id which is name (str) casted as (int)) G2 = Graph() # add the vertices in a different order so they have differnet # underlying indices G2.add_vertex("1100", id=1100) # index 2 G2.add_vertex("1101", id=1101) # index 3 G2.add_vertex("1010", id=1010) # index 0 G2.add_vertex("1011", id=1011) # index 1 # add some of the edges in the other direction G2.add_edge("1100", "1011") G2.add_edge("1101", "1100") G2.add_edge("1010", "1100") G2.add_edge("1010", "1011") c1 = self.G.vs["id"] c2 = G2.vs["id"] self.assertTrue(self.G.isomorphic_vf2(G2, color1=c1, color2=c2)) self.assertTrue(self.G.isomorphic_vf2(G2)) # sanity check def test_are_connected(self): G = self.G Gs = self.Gs # try referencing via vertex names instead of indexes self.assertTrue(G.are_connected("1011", "1100")) self.assertTrue(G.are_connected("1100", "1011")) self.assertTrue(Gs.are_connected("1011", "1010")) self.assertTrue(Gs.are_connected("1010", "1011")) def test_indexing(self): G = self.G Gs = self.Gs # accessing VS self.assertEqual(G.vs.find("1100")["name"], "1100") self.assertEqual(G.vs[2]["name"], "1100") # accessing ES self.assertEqual(G.es[0].source, G.vs.find("1010").index) self.assertEqual(G.es[0].source, 0) self.assertEqual(G.es[0].target, G.vs.find("1100").index) self.assertEqual(G.es[0].target, 2) def test_names(self): G = self.G Gs = self.Gs # pulling the names out via a property of the graph should be an # effecient alternative to list comprehension when we need to color # edges before the VF2 algorithm color_str = G.vs["name"] color_int = G.vs["id"] self.assertEqual(color_str, ["1010", "1011", "1100", "1101"]) self.assertEqual(color_int, [int(v["name"]) for v in G.vs]) # Won't work unless we implement canonical ordering for the hash function # Currently just uses default (memory addresses) @unittest.expectedFailure def test_hashable(self): d = defaultdict(Graph) # Two identical graphs with the same vertices and labels should hash # to the same string d[G] = 1 print("hash g: %s\n hash g2: %s\n" % (hash(G), hash(G2))) self.assertEqual((G2 in d), True) if __name__ == '__main__': unittest.main()
34.789855
77
0.556134
805120e9421d438ee5b62353f8f711c8faaa58a0
11,536
py
Python
SWAG/config/fail2ban/action.d/badips.py
krzwiatrzyk/blog
ff1bc28abb5474cf76fba495f0ab00fc6f993736
[ "MIT" ]
null
null
null
SWAG/config/fail2ban/action.d/badips.py
krzwiatrzyk/blog
ff1bc28abb5474cf76fba495f0ab00fc6f993736
[ "MIT" ]
null
null
null
SWAG/config/fail2ban/action.d/badips.py
krzwiatrzyk/blog
ff1bc28abb5474cf76fba495f0ab00fc6f993736
[ "MIT" ]
null
null
null
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: t -*- # vi: set ft=python sts=4 ts=4 sw=4 noet : # This file is part of Fail2Ban. # # Fail2Ban is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # Fail2Ban is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Fail2Ban; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. import sys if sys.version_info < (2, 7): # pragma: no cover raise ImportError("badips.py action requires Python >= 2.7") import json import threading import logging if sys.version_info >= (3, ): # pragma: 2.x no cover from urllib.request import Request, urlopen from urllib.parse import urlencode from urllib.error import HTTPError else: # pragma: 3.x no cover from urllib2 import Request, urlopen, HTTPError from urllib import urlencode from fail2ban.server.actions import Actions, ActionBase, BanTicket from fail2ban.helpers import splitwords, str2LogLevel class BadIPsAction(ActionBase): # pragma: no cover - may be unavailable """Fail2Ban action which reports bans to badips.com, and also blacklist bad IPs listed on badips.com by using another action's ban method. Parameters ---------- jail : Jail The jail which the action belongs to. name : str Name assigned to the action. category : str Valid badips.com category for reporting failures. score : int, optional Minimum score for bad IPs. Default 3. age : str, optional Age of last report for bad IPs, per badips.com syntax. Default "24h" (24 hours) banaction : str, optional Name of banaction to use for blacklisting bad IPs. If `None`, no blacklist of IPs will take place. Default `None`. bancategory : str, optional Name of category to use for blacklisting, which can differ from category used for reporting. e.g. may want to report "postfix", but want to use whole "mail" category for blacklist. Default `category`. bankey : str, optional Key issued by badips.com to retrieve personal list of blacklist IPs. updateperiod : int, optional Time in seconds between updating bad IPs blacklist. Default 900 (15 minutes) loglevel : int/str, optional Log level of the message when an IP is (un)banned. Default `DEBUG`. Can be also supplied as two-value list (comma- or space separated) to provide level of the summary message when a group of IPs is (un)banned. Example `DEBUG,INFO`. agent : str, optional User agent transmitted to server. Default `Fail2Ban/ver.` Raises ------ ValueError If invalid `category`, `score`, `banaction` or `updateperiod`. """ TIMEOUT = 10 _badips = "https://www.badips.com" def _Request(self, url, **argv): return Request(url, headers={'User-Agent': self.agent}, **argv) def __init__(self, jail, name, category, score=3, age="24h", banaction=None, bancategory=None, bankey=None, updateperiod=900, loglevel='DEBUG', agent="Fail2Ban", timeout=TIMEOUT): super(BadIPsAction, self).__init__(jail, name) self.timeout = timeout self.agent = agent self.category = category self.score = score self.age = age self.banaction = banaction self.bancategory = bancategory or category self.bankey = bankey loglevel = splitwords(loglevel) self.sumloglevel = str2LogLevel(loglevel[-1]) self.loglevel = str2LogLevel(loglevel[0]) self.updateperiod = updateperiod self._bannedips = set() # Used later for threading.Timer for updating badips self._timer = None @staticmethod def isAvailable(timeout=1): try: response = urlopen(Request("/".join([BadIPsAction._badips]), headers={'User-Agent': "Fail2Ban"}), timeout=timeout) return True, '' except Exception as e: # pragma: no cover return False, e def logError(self, response, what=''): # pragma: no cover - sporadical (502: Bad Gateway, etc) messages = {} try: messages = json.loads(response.read().decode('utf-8')) except: pass self._logSys.error( "%s. badips.com response: '%s'", what, messages.get('err', 'Unknown')) def getCategories(self, incParents=False): """Get badips.com categories. Returns ------- set Set of categories. Raises ------ HTTPError Any issues with badips.com request. ValueError If badips.com response didn't contain necessary information """ try: response = urlopen( self._Request("/".join([self._badips, "get", "categories"])), timeout=self.timeout) except HTTPError as response: # pragma: no cover self.logError(response, "Failed to fetch categories") raise else: response_json = json.loads(response.read().decode('utf-8')) if not 'categories' in response_json: err = "badips.com response lacked categories specification. Response was: %s" \ % (response_json,) self._logSys.error(err) raise ValueError(err) categories = response_json['categories'] categories_names = set( value['Name'] for value in categories) if incParents: categories_names.update(set( value['Parent'] for value in categories if "Parent" in value)) return categories_names def getList(self, category, score, age, key=None): """Get badips.com list of bad IPs. Parameters ---------- category : str Valid badips.com category. score : int Minimum score for bad IPs. age : str Age of last report for bad IPs, per badips.com syntax. key : str, optional Key issued by badips.com to fetch IPs reported with the associated key. Returns ------- set Set of bad IPs. Raises ------ HTTPError Any issues with badips.com request. """ try: url = "?".join([ "/".join([self._badips, "get", "list", category, str(score)]), urlencode({'age': age})]) if key: url = "&".join([url, urlencode({'key': key})]) self._logSys.debug('badips.com: get list, url: %r', url) response = urlopen(self._Request(url), timeout=self.timeout) except HTTPError as response: # pragma: no cover self.logError(response, "Failed to fetch bad IP list") raise else: return set(response.read().decode('utf-8').split()) @property def category(self): """badips.com category for reporting IPs. """ return self._category @category.setter def category(self, category): if category not in self.getCategories(): self._logSys.error("Category name '%s' not valid. " "see badips.com for list of valid categories", category) raise ValueError("Invalid category: %s" % category) self._category = category @property def bancategory(self): """badips.com bancategory for fetching IPs. """ return self._bancategory @bancategory.setter def bancategory(self, bancategory): if bancategory != "any" and bancategory not in self.getCategories(incParents=True): self._logSys.error("Category name '%s' not valid. " "see badips.com for list of valid categories", bancategory) raise ValueError("Invalid bancategory: %s" % bancategory) self._bancategory = bancategory @property def score(self): """badips.com minimum score for fetching IPs. """ return self._score @score.setter def score(self, score): score = int(score) if 0 <= score <= 5: self._score = score else: raise ValueError("Score must be 0-5") @property def banaction(self): """Jail action to use for banning/unbanning. """ return self._banaction @banaction.setter def banaction(self, banaction): if banaction is not None and banaction not in self._jail.actions: self._logSys.error("Action name '%s' not in jail '%s'", banaction, self._jail.name) raise ValueError("Invalid banaction") self._banaction = banaction @property def updateperiod(self): """Period in seconds between banned bad IPs will be updated. """ return self._updateperiod @updateperiod.setter def updateperiod(self, updateperiod): updateperiod = int(updateperiod) if updateperiod > 0: self._updateperiod = updateperiod else: raise ValueError("Update period must be integer greater than 0") def _banIPs(self, ips): for ip in ips: try: ai = Actions.ActionInfo(BanTicket(ip), self._jail) self._jail.actions[self.banaction].ban(ai) except Exception as e: self._logSys.error( "Error banning IP %s for jail '%s' with action '%s': %s", ip, self._jail.name, self.banaction, e, exc_info=self._logSys.getEffectiveLevel()<=logging.DEBUG) else: self._bannedips.add(ip) self._logSys.log(self.loglevel, "Banned IP %s for jail '%s' with action '%s'", ip, self._jail.name, self.banaction) def _unbanIPs(self, ips): for ip in ips: try: ai = Actions.ActionInfo(BanTicket(ip), self._jail) self._jail.actions[self.banaction].unban(ai) except Exception as e: self._logSys.error( "Error unbanning IP %s for jail '%s' with action '%s': %s", ip, self._jail.name, self.banaction, e, exc_info=self._logSys.getEffectiveLevel()<=logging.DEBUG) else: self._logSys.log(self.loglevel, "Unbanned IP %s for jail '%s' with action '%s'", ip, self._jail.name, self.banaction) finally: self._bannedips.remove(ip) def start(self): """If `banaction` set, blacklists bad IPs. """ if self.banaction is not None: self.update() def update(self): """If `banaction` set, updates blacklisted IPs. Queries badips.com for list of bad IPs, removing IPs from the blacklist if no longer present, and adds new bad IPs to the blacklist. """ if self.banaction is not None: if self._timer: self._timer.cancel() self._timer = None try: ips = self.getList( self.bancategory, self.score, self.age, self.bankey) # Remove old IPs no longer listed s = self._bannedips - ips m = len(s) self._unbanIPs(s) # Add new IPs which are now listed s = ips - self._bannedips p = len(s) self._banIPs(s) if m != 0 or p != 0: self._logSys.log(self.sumloglevel, "Updated IPs for jail '%s' (-%d/+%d)", self._jail.name, m, p) self._logSys.debug( "Next update for jail '%' in %i seconds", self._jail.name, self.updateperiod) finally: self._timer = threading.Timer(self.updateperiod, self.update) self._timer.start() def stop(self): """If `banaction` set, clears blacklisted IPs. """ if self.banaction is not None: if self._timer: self._timer.cancel() self._timer = None self._unbanIPs(self._bannedips.copy()) def ban(self, aInfo): """Reports banned IP to badips.com. Parameters ---------- aInfo : dict Dictionary which includes information in relation to the ban. Raises ------ HTTPError Any issues with badips.com request. """ try: url = "/".join([self._badips, "add", self.category, str(aInfo['ip'])]) self._logSys.debug('badips.com: ban, url: %r', url) response = urlopen(self._Request(url), timeout=self.timeout) except HTTPError as response: # pragma: no cover self.logError(response, "Failed to ban") raise else: messages = json.loads(response.read().decode('utf-8')) self._logSys.debug( "Response from badips.com report: '%s'", messages['suc']) Action = BadIPsAction
29.428571
95
0.691141
1b66367bba7643712a2730343f60e1a71e82bfbe
1,496
py
Python
tests/fixtures.py
xdb64/dpaster
dbc6c4023de1a0fbe446fbc54b930f182bcc0c44
[ "MIT" ]
1
2019-01-16T19:36:17.000Z
2019-01-16T19:36:17.000Z
tests/fixtures.py
xdb64/dpaster
dbc6c4023de1a0fbe446fbc54b930f182bcc0c44
[ "MIT" ]
3
2019-01-16T16:58:43.000Z
2019-01-16T19:35:23.000Z
tests/fixtures.py
xdb64/dpaster
dbc6c4023de1a0fbe446fbc54b930f182bcc0c44
[ "MIT" ]
1
2020-12-30T12:43:18.000Z
2020-12-30T12:43:18.000Z
import json import textwrap import pytest from dpaster import ( cli, core, ) class FakeRequests: def post(self, *args, **kwargs): return FakeResponse() class FakeResponse: text = "http://dpaste.com/" def raise_for_status(self): pass class FakePyperclip: def copy(self, text, *args, **kwargs): assert text == FakeResponse.text @pytest.fixture def config_path(monkeypatch, tmp_path): path = tmp_path / "dpaster.conf" monkeypatch.setattr(core, "CONFIG_PATH", path) return path @pytest.fixture def default_options(config_path): options = { "raw": False, "autocp": False, "syntax": None, "expires": None, } with open(config_path, "w") as f: json.dump(options, f) @pytest.fixture def random_options(config_path): options = { "raw": True, "autocp": True, "syntax": "python", "expires": 10, } with open(config_path, "w") as f: json.dump(options, f) @pytest.fixture def fake_requests(monkeypatch): monkeypatch.setattr(core, "requests", FakeRequests()) @pytest.fixture def fake_pyperclip(monkeypatch): monkeypatch.setattr(cli, "pyperclip", FakePyperclip()) @pytest.fixture def python_code(): return textwrap.dedent( """\ import math def x_plus_2pi(x: int) -> float: return x + math.pi if __name__ == "__main__": print(x_plus_2pi(1)) """ )
18.024096
58
0.606283
6159017c148d831b016fbe03bceaac876d3d10c7
1,949
py
Python
tests/test_generator.py
microbit-carlos/project_generator
a498f6c1dac899010f22b855f9e2e981f3325596
[ "Apache-2.0" ]
197
2015-04-29T16:29:03.000Z
2022-03-28T01:14:55.000Z
tests/test_generator.py
microbit-carlos/project_generator
a498f6c1dac899010f22b855f9e2e981f3325596
[ "Apache-2.0" ]
305
2015-04-21T18:03:31.000Z
2022-03-10T22:21:45.000Z
tests/test_generator.py
microbit-carlos/project_generator
a498f6c1dac899010f22b855f9e2e981f3325596
[ "Apache-2.0" ]
84
2015-04-21T18:00:18.000Z
2022-03-28T13:31:06.000Z
# Copyright 2015 0xc0170 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import shutil import yaml from unittest import TestCase from project_generator.generate import Generator project_1_yaml = { 'common': { 'sources': ['sources/main.cpp'], 'includes': ['includes/header1.h'] } } projects_yaml = { 'projects': { 'project_1' : ['test_workspace/project_1.yaml'] }, 'settings' : { 'export_dir': ['not_generated_projects'] } } class TestGenerator(TestCase): """test things related to the PgenWorkspace class""" def setUp(self): if not os.path.exists('test_workspace'): os.makedirs('test_workspace') # write project file with open(os.path.join(os.getcwd(), 'test_workspace/project_1.yaml'), 'wt') as f: f.write(yaml.dump(project_1_yaml, default_flow_style=False)) # write projects file with open(os.path.join(os.getcwd(), 'test_workspace/projects.yaml'), 'wt') as f: f.write(yaml.dump(projects_yaml, default_flow_style=False)) self.workspace = Generator('test_workspace/projects.yaml') def tearDown(self): # remove created directory shutil.rmtree('test_workspace', ignore_errors=True) def test_settings(self): # only check things which are affected by projects.yaml assert self.workspace.settings.export_location_format == 'not_generated_projects'
32.483333
89
0.689584
483cd59288e0643869158427bfc7c54a59de249b
2,878
py
Python
aliyun-python-sdk-bssopenapi/aliyunsdkbssopenapi/request/v20171214/QueryRIUtilizationDetailRequest.py
yndu13/aliyun-openapi-python-sdk
12ace4fb39fe2fb0e3927a4b1b43ee4872da43f5
[ "Apache-2.0" ]
null
null
null
aliyun-python-sdk-bssopenapi/aliyunsdkbssopenapi/request/v20171214/QueryRIUtilizationDetailRequest.py
yndu13/aliyun-openapi-python-sdk
12ace4fb39fe2fb0e3927a4b1b43ee4872da43f5
[ "Apache-2.0" ]
null
null
null
aliyun-python-sdk-bssopenapi/aliyunsdkbssopenapi/request/v20171214/QueryRIUtilizationDetailRequest.py
yndu13/aliyun-openapi-python-sdk
12ace4fb39fe2fb0e3927a4b1b43ee4872da43f5
[ "Apache-2.0" ]
null
null
null
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # # http://www.apache.org/licenses/LICENSE-2.0 # # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. from aliyunsdkcore.request import RpcRequest from aliyunsdkbssopenapi.endpoint import endpoint_data class QueryRIUtilizationDetailRequest(RpcRequest): def __init__(self): RpcRequest.__init__(self, 'BssOpenApi', '2017-12-14', 'QueryRIUtilizationDetail') self.set_method('POST') if hasattr(self, "endpoint_map"): setattr(self, "endpoint_map", endpoint_data.getEndpointMap()) if hasattr(self, "endpoint_regional"): setattr(self, "endpoint_regional", endpoint_data.getEndpointRegional()) def get_DeductedInstanceId(self): # String return self.get_query_params().get('DeductedInstanceId') def set_DeductedInstanceId(self, DeductedInstanceId): # String self.add_query_param('DeductedInstanceId', DeductedInstanceId) def get_InstanceSpec(self): # String return self.get_query_params().get('InstanceSpec') def set_InstanceSpec(self, InstanceSpec): # String self.add_query_param('InstanceSpec', InstanceSpec) def get_EndTime(self): # String return self.get_query_params().get('EndTime') def set_EndTime(self, EndTime): # String self.add_query_param('EndTime', EndTime) def get_RIInstanceId(self): # String return self.get_query_params().get('RIInstanceId') def set_RIInstanceId(self, RIInstanceId): # String self.add_query_param('RIInstanceId', RIInstanceId) def get_StartTime(self): # String return self.get_query_params().get('StartTime') def set_StartTime(self, StartTime): # String self.add_query_param('StartTime', StartTime) def get_PageNum(self): # Integer return self.get_query_params().get('PageNum') def set_PageNum(self, PageNum): # Integer self.add_query_param('PageNum', PageNum) def get_PageSize(self): # Integer return self.get_query_params().get('PageSize') def set_PageSize(self, PageSize): # Integer self.add_query_param('PageSize', PageSize) def get_RICommodityCode(self): # String return self.get_query_params().get('RICommodityCode') def set_RICommodityCode(self, RICommodityCode): # String self.add_query_param('RICommodityCode', RICommodityCode)
38.891892
84
0.761987
3753f001bacb54bdf617a687f430286e5b4f0068
79,842
py
Python
Evalutaion/Plot.py
ToyasDhake/Intelligent-job-scheduling-using-HTN-planning
67ab64b9ac7c9315ec63fac1238fbca1e306d1b3
[ "MIT" ]
null
null
null
Evalutaion/Plot.py
ToyasDhake/Intelligent-job-scheduling-using-HTN-planning
67ab64b9ac7c9315ec63fac1238fbca1e306d1b3
[ "MIT" ]
null
null
null
Evalutaion/Plot.py
ToyasDhake/Intelligent-job-scheduling-using-HTN-planning
67ab64b9ac7c9315ec63fac1238fbca1e306d1b3
[ "MIT" ]
1
2021-07-14T13:12:55.000Z
2021-07-14T13:12:55.000Z
distance = [0, 0, 6.541640786499874, 11.541640786499874, 11.541640786499874, 11.541640786499874, 11.541640786499874, 11.541640786499874, 11.541640786499874, 11.541640786499874, 11.541640786499874, 13.107326211449113, 14.107326211449113, 14.107326211449113, 15.390168923923731, 16.39016892392373, 16.39016892392373, 16.39016892392373, 16.39016892392373, 16.39016892392373, 16.39016892392373, 20.67301163639835, 32.50143876114454, 40.50143876114454, 42.50143876114454, 47.50143876114454, 52.78428147361916, 63.48133774846687, 70.48133774846687, 71.48133774846687, 72.48133774846687, 72.48133774846687, 72.48133774846687, 72.48133774846687, 76.76418046094149, 80.76418046094149, 84.76418046094149, 87.76418046094149, 94.04702317341611, 99.04702317341611, 102.04702317341611, 104.04702317341611, 105.04702317341611, 105.04702317341611, 107.04702317341611, 119.30976487321306, 128.5926075856877, 132.5926075856877, 138.5926075856877, 142.5926075856877, 144.5926075856877, 145.5926075856877, 145.5926075856877, 145.5926075856877, 145.5926075856877, 145.5926075856877, 145.5926075856877, 145.5926075856877, 145.5926075856877, 145.5926075856877, 145.5926075856877, 145.5926075856877, 146.5926075856877, 147.5926075856877, 147.5926075856877, 147.5926075856877, 151.5926075856877, 155.5926075856877, 160.87545029816232, 164.87545029816232, 165.87545029816232, 165.87545029816232, 165.87545029816232, 165.87545029816232, 174.15829301063695, 186.7239784355862, 193.7239784355862, 200.00682114806082, 209.00682114806082, 217.57250657301006, 225.8553492854847, 233.8553492854847, 245.13819199795932, 252.13819199795932, 255.70387742290856, 256.7038774229086, 256.7038774229086, 262.5524055603325, 267.5524055603325, 270.5524055603325, 272.5524055603325, 273.5524055603325, 277.5524055603325, 281.5524055603325, 281.5524055603325, 281.5524055603325, 283.8352482728071, 285.8352482728071, 285.8352482728071, 285.8352482728071, 289.8352482728071, 298.11809098528175, 305.11809098528175, 310.11809098528175, 314.683776410231, 316.683776410231, 316.683776410231, 317.96661912270565, 323.2494618351803, 327.2494618351803, 327.2494618351803, 327.2494618351803, 327.2494618351803, 327.2494618351803, 327.2494618351803, 327.2494618351803, 327.2494618351803, 327.2494618351803, 327.2494618351803, 328.5323045476549, 329.5323045476549, 330.5323045476549, 330.5323045476549, 331.5323045476549, 332.5323045476549, 332.5323045476549, 332.5323045476549, 332.5323045476549, 336.81514726012955, 340.81514726012955, 345.0979899726042, 352.0979899726042, 357.0979899726042, 360.0979899726042, 363.3808326850788, 365.3808326850788, 365.3808326850788, 366.3808326850788, 367.3808326850788, 367.3808326850788, 367.3808326850788, 367.3808326850788, 371.3808326850788, 376.66367539755345, 384.07788895992655, 389.07788895992655, 396.3607316724012, 402.3607316724012, 406.3607316724012, 408.3607316724012, 409.3607316724012, 409.3607316724012, 410.6435743848758, 411.6435743848758, 411.6435743848758, 411.6435743848758, 411.6435743848758, 415.6435743848758, 419.6435743848758, 419.6435743848758, 423.92641709735045, 427.92641709735045, 430.92641709735045, 434.4921025222997, 436.4921025222997, 438.77494523477435, 439.77494523477435, 445.3406306597236, 450.3406306597236, 450.3406306597236, 450.3406306597236, 450.3406306597236, 450.3406306597236, 450.3406306597236, 450.3406306597236, 450.3406306597236, 450.3406306597236, 450.3406306597236, 450.3406306597236, 450.3406306597236, 450.3406306597236, 450.3406306597236, 450.3406306597236, 450.3406306597236, 450.3406306597236, 450.3406306597236, 450.3406306597236, 450.3406306597236, 450.3406306597236, 450.3406306597236, 450.3406306597236, 451.62347337219825, 456.9063160846729, 460.9063160846729, 460.9063160846729, 460.9063160846729, 463.1891587971475, 465.1891587971475, 466.47200150962215, 467.47200150962215, 473.0376869345714, 478.0376869345714, 481.0376869345714, 483.0376869345714, 486.1690577844699, 487.1690577844699, 487.1690577844699, 491.1690577844699, 496.4519004969445, 500.4519004969445, 502.4519004969445, 503.4519004969445, 504.73474320941915, 505.73474320941915, 510.0175859218938, 514.0175859218938, 517.0175859218938, 520.0175859218938, 522.0175859218938, 522.0175859218938, 523.3004286343684, 524.3004286343684, 525.5832713468429, 526.5832713468429, 526.5832713468429, 530.5832713468429, 535.8661140593175, 539.8661140593175, 541.8661140593175, 542.8661140593175, 542.8661140593175, 542.8661140593175, 542.8661140593175, 542.8661140593175, 542.8661140593175, 543.8661140593175, 544.8661140593175, 544.8661140593175, 544.8661140593175, 544.8661140593175, 544.8661140593175, 544.8661140593175, 544.8661140593175, 549.1489567717921, 553.1489567717921, 556.1489567717921, 558.1489567717921, 561.7146421967414, 563.7146421967414, 563.7146421967414, 563.7146421967414, 563.7146421967414, 563.7146421967414, 563.7146421967414, 564.9974849092159, 567.2803276216905, 573.5631703341651, 578.5631703341651, 585.8460130466397, 591.8460130466397, 592.8460130466397, 592.8460130466397, 598.1288557591142, 603.1288557591142, 606.1288557591142, 609.1288557591142, 611.1288557591142, 611.1288557591142, 611.1288557591142, 611.1288557591142, 611.1288557591142, 611.1288557591142, 616.4116984715888, 626.5430693214873, 635.1087547464366, 641.1087547464366, 650.5229683088097, 656.5229683088097, 656.5229683088097, 656.5229683088097, 656.5229683088097, 656.5229683088097, 658.8058110212843, 663.2200245836574, 665.7857100086067, 666.7857100086067, 666.7857100086067, 666.7857100086067, 666.7857100086067, 666.7857100086067, 666.7857100086067, 666.7857100086067, 666.7857100086067, 666.7857100086067, 666.7857100086067, 672.3513954335559, 677.3513954335559, 689.4827662834545, 699.4827662834545, 703.4827662834545, 705.4827662834545, 710.765608995929, 714.765608995929, 714.765608995929, 714.765608995929, 714.765608995929, 714.765608995929, 714.765608995929, 714.765608995929, 714.765608995929, 714.765608995929, 714.765608995929, 714.765608995929, 714.765608995929, 714.765608995929, 714.765608995929, 714.765608995929, 714.765608995929, 714.765608995929, 714.765608995929, 714.765608995929, 714.765608995929, 716.0484517084036, 721.0484517084036, 725.0484517084036, 728.0484517084036, 736.7455079832513, 742.7455079832513, 745.7455079832513, 747.7455079832513, 748.7455079832513, 748.7455079832513, 751.8768788331497, 753.8768788331497, 758.442564258099, 768.0082496830482, 773.0082496830482, 776.0082496830482, 779.5739351079975, 781.5739351079975, 785.8567778204721, 794.4224632454213, 806.5538340953199, 812.5538340953199, 816.5538340953199, 818.5538340953199, 819.5538340953199, 824.8366768077944, 831.4023622327437, 835.4023622327437, 838.6852049452183, 844.6852049452183, 848.6852049452183, 854.2508903701676, 858.2508903701676, 863.5337330826421, 867.5337330826421, 870.5337330826421, 872.5337330826421, 873.5337330826421, 873.5337330826421, 879.382261220066, 884.382261220066, 884.382261220066, 888.382261220066, 892.382261220066, 895.382261220066, 898.6651039325405, 900.6651039325405, 900.6651039325405, 900.6651039325405, 904.9479466450151, 908.9479466450151, 911.9479466450151, 913.9479466450151, 918.9479466450151, 922.9479466450151, 922.9479466450151, 928.5136320699643, 933.5136320699643, 936.5136320699643, 941.0793174949135, 944.0793174949135, 944.0793174949135, 948.3621602073881, 952.3621602073881, 952.3621602073881, 952.3621602073881, 956.6450029198627, 960.6450029198627, 960.6450029198627, 960.6450029198627, 960.6450029198627, 960.6450029198627, 964.9278456323373, 968.9278456323373, 971.9278456323373, 974.9278456323373, 976.9278456323373, 976.9278456323373, 976.9278456323373, 978.2106883448118, 979.2106883448118, 979.2106883448118, 983.2106883448118, 987.2106883448118, 990.2106883448118, 992.2106883448118, 993.2106883448118, 993.2106883448118, 993.2106883448118, 993.2106883448118, 993.2106883448118, 993.2106883448118, 997.2106883448118, 1001.2106883448118, 1001.2106883448118, 1001.2106883448118, 1001.2106883448118, 1001.2106883448118, 1001.2106883448118, 1009.4935310572864, 1017.4935310572864, 1020.4935310572864, 1022.4935310572864, 1023.4935310572864, 1023.4935310572864, 1032.0592164822356, 1040.0592164822356, 1043.0592164822356, 1045.0592164822356, 1046.0592164822356, 1046.0592164822356, 1050.0592164822356, 1054.0592164822356, 1057.0592164822356, 1059.0592164822356, 1064.0592164822356, 1072.3420591947101, 1076.3420591947101, 1079.3420591947101, 1085.6249019071847, 1094.6249019071847, 1098.6249019071847, 1098.6249019071847, 1098.6249019071847, 1102.9077446196593, 1106.9077446196593, 1109.9077446196593, 1111.9077446196593, 1112.9077446196593, 1112.9077446196593, 1112.9077446196593, 1112.9077446196593, 1112.9077446196593, 1112.9077446196593, 1112.9077446196593, 1112.9077446196593, 1112.9077446196593, 1112.9077446196593, 1116.9077446196593, 1120.9077446196593, 1120.9077446196593, 1122.1905873321339, 1124.1905873321339, 1125.1905873321339, 1125.1905873321339, 1125.1905873321339, 1125.1905873321339, 1125.1905873321339, 1125.1905873321339, 1125.1905873321339, 1131.0391154695576, 1140.0391154695576, 1148.3219581820322, 1155.6048008945068, 1160.6048008945068, 1160.6048008945068, 1160.6048008945068, 1160.6048008945068, 1160.6048008945068, 1160.6048008945068, 1160.6048008945068, 1164.6048008945068, 1168.6048008945068, 1168.6048008945068, 1168.6048008945068, 1168.6048008945068, 1168.6048008945068, 1169.8876436069813, 1170.8876436069813, 1170.8876436069813, 1170.8876436069813, 1170.8876436069813, 1170.8876436069813, 1170.8876436069813, 1175.170486319456, 1179.170486319456, 1182.170486319456, 1188.170486319456, 1193.170486319456, 1193.170486319456, 1193.170486319456, 1193.170486319456, 1193.170486319456, 1193.170486319456, 1195.170486319456, 1197.170486319456, 1205.4533290319305, 1212.4533290319305, 1217.4533290319305, 1220.4533290319305, 1221.4533290319305, 1222.4533290319305, 1223.4533290319305, 1223.4533290319305, 1223.4533290319305, 1223.4533290319305, 1223.4533290319305, 1223.4533290319305, 1223.4533290319305, 1227.736171744405, 1231.736171744405, 1233.3018571693542, 1239.5846998818288, 1250.4332280192527, 1254.4332280192527, 1260.7160707317273, 1266.7160707317273, 1270.7160707317273, 1272.7160707317273, 1273.7160707317273, 1277.998913444202, 1281.998913444202, 1284.998913444202, 1286.998913444202, 1287.998913444202, 1287.998913444202, 1287.998913444202, 1287.998913444202, 1290.564598869151, 1292.564598869151, 1292.564598869151, 1292.564598869151, 1292.564598869151, 1292.564598869151, 1292.564598869151, 1292.564598869151, 1293.564598869151, 1294.564598869151, 1294.564598869151, 1294.564598869151, 1294.564598869151, 1294.564598869151, 1294.564598869151, 1299.8474415816256, 1304.8474415816256, 1307.8474415816256, 1309.8474415816256, 1310.8474415816256, 1310.8474415816256, 1310.8474415816256, 1311.8474415816256, 1312.8474415816256, 1318.6959697190496, 1323.6959697190496, 1331.827340568948, 1342.1101832814227, 1350.1101832814227, 1352.1101832814227, 1354.9587114188466, 1355.9587114188466, 1355.9587114188466, 1356.9587114188466, 1357.9587114188466, 1357.9587114188466, 1361.9587114188466, 1365.9587114188466, 1365.9587114188466, 1365.9587114188466, 1365.9587114188466, 1365.9587114188466, 1366.9587114188466, 1367.9587114188466, 1367.9587114188466, 1367.9587114188466, 1371.9587114188466, 1375.9587114188466, 1378.9587114188466, 1380.9587114188466, 1382.9587114188466, 1383.9587114188466, 1383.9587114188466, 1383.9587114188466, 1385.2415541313212, 1386.2415541313212, 1386.2415541313212, 1390.2415541313212, 1402.2415541313212, 1414.5243968437958, 1424.5243968437958, 1428.5243968437958, 1434.5243968437958, 1442.5243968437958, 1446.5243968437958, 1454.3729249812197, 1463.938610406169, 1467.938610406169, 1467.938610406169, 1467.938610406169, 1467.938610406169, 1467.938610406169, 1467.938610406169, 1469.2214531186435, 1475.504295831118, 1480.504295831118, 1483.504295831118, 1488.0699812560672, 1496.2013521059657, 1500.2013521059657, 1503.2013521059657, 1505.2013521059657, 1506.2013521059657, 1506.2013521059657, 1506.2013521059657, 1510.4841948184403, 1518.7670375309149, 1525.7670375309149, 1530.7670375309149, 1533.7670375309149, 1534.7670375309149, 1534.7670375309149, 1534.7670375309149, 1538.7670375309149, 1551.0498802433895, 1562.0498802433895, 1572.4640938057626, 1580.4640938057626, 1582.4640938057626, 1582.4640938057626, 1582.4640938057626, 1582.4640938057626, 1582.4640938057626, 1582.4640938057626, 1582.4640938057626, 1582.4640938057626, 1582.4640938057626, 1582.4640938057626, 1582.4640938057626, 1582.4640938057626, 1582.4640938057626, 1582.4640938057626, 1586.7469365182371, 1590.7469365182371, 1590.7469365182371, 1590.7469365182371, 1590.7469365182371, 1590.7469365182371, 1590.7469365182371, 1590.7469365182371, 1590.7469365182371, 1590.7469365182371, 1590.7469365182371, 1591.7469365182371, 1592.7469365182371, 1592.7469365182371, 1592.7469365182371, 1592.7469365182371, 1592.7469365182371, 1592.7469365182371, 1592.7469365182371, 1598.8783073681357, 1609.858206355458, 1613.858206355458, 1623.5552626303056, 1630.5552626303056, 1631.5552626303056, 1635.8381053427802, 1639.8381053427802, 1642.8381053427802, 1644.8381053427802, 1648.4037907677293, 1650.4037907677293, 1654.686633480204, 1658.686633480204, 1666.686633480204, 1673.686633480204, 1674.686633480204, 1674.686633480204, 1677.252318905153, 1681.5351616176276, 1683.5351616176276, 1683.5351616176276, 1683.5351616176276, 1689.1008470425768, 1694.1008470425768, 1701.3836897550514, 1707.3836897550514, 1708.3836897550514, 1712.3836897550514, 1720.666532467526, 1724.666532467526, 1729.9493751800005, 1733.9493751800005, 1734.9493751800005, 1734.9493751800005, 1734.9493751800005, 1734.9493751800005, 1736.232217892475, 1737.232217892475, 1741.232217892475, 1745.232217892475, 1745.232217892475, 1745.232217892475, 1745.232217892475, 1745.232217892475, 1750.232217892475, 1755.232217892475, 1758.232217892475, 1761.5150606049497, 1763.5150606049497, 1763.5150606049497, 1764.5150606049497, 1769.5150606049497, 1773.5150606049497, 1776.5150606049497, 1778.5150606049497, 1779.5150606049497, 1779.5150606049497, 1779.5150606049497, 1779.5150606049497, 1779.5150606049497, 1779.5150606049497, 1783.7979033174242, 1787.7979033174242, 1792.0807460298988, 1795.0807460298988, 1796.0807460298988, 1796.0807460298988, 1797.0807460298988, 1798.0807460298988, 1798.0807460298988, 1798.0807460298988, 1798.0807460298988, 1798.0807460298988, 1798.0807460298988, 1798.0807460298988, 1798.0807460298988, 1798.0807460298988, 1798.0807460298988, 1798.0807460298988, 1799.0807460298988, 1800.0807460298988, 1805.3635887423734, 1810.3635887423734, 1814.3635887423734, 1816.3635887423734, 1817.3635887423734, 1817.3635887423734, 1821.3635887423734, 1825.3635887423734, 1825.3635887423734, 1825.3635887423734, 1825.3635887423734, 1825.3635887423734, 1830.646431454848, 1835.646431454848, 1838.646431454848, 1840.646431454848, 1841.646431454848, 1841.646431454848, 1841.646431454848, 1845.9292741673225, 1849.9292741673225, 1852.9292741673225, 1854.9292741673225, 1859.9292741673225, 1863.9292741673225, 1863.9292741673225, 1863.9292741673225, 1863.9292741673225, 1863.9292741673225, 1865.2121168797971, 1866.2121168797971, 1867.2121168797971, 1871.4949595922717, 1875.4949595922717, 1878.4949595922717, 1880.4949595922717, 1881.4949595922717, 1881.4949595922717, 1881.4949595922717, 1881.4949595922717, 1889.7778023047463, 1897.7778023047463, 1900.7778023047463, 1902.7778023047463, 1903.7778023047463, 1903.7778023047463, 1905.0606450172208, 1906.0606450172208, 1906.0606450172208, 1906.0606450172208, 1906.0606450172208, 1906.0606450172208, 1906.0606450172208, 1906.0606450172208, 1910.62633044217, 1914.62633044217, 1917.62633044217, 1919.62633044217, 1920.62633044217, 1920.62633044217, 1928.9091731546446, 1936.9091731546446, 1939.9091731546446, 1941.9091731546446, 1942.9091731546446, 1942.9091731546446, 1942.9091731546446, 1942.9091731546446, 1942.9091731546446, 1944.1920158671192, 1949.1920158671192, 1958.4748585795937, 1968.6062294294923, 1971.6062294294923, 1972.6062294294923, 1972.6062294294923, 1972.6062294294923, 1972.6062294294923, 1976.6062294294923, 1982.1719148544414, 1986.1719148544414, 1988.1719148544414, 1989.1719148544414, 1993.454757566916, 1999.0204429918651, 2003.0204429918651, 2005.0204429918651, 2006.0204429918651, 2006.0204429918651, 2008.3032857043397, 2014.3032857043397, 2018.3032857043397, 2018.3032857043397, 2019.3032857043397, 2026.1518138417634, 2036.5660274041365, 2040.5660274041365, 2043.5660274041365, 2045.5660274041365, 2046.5660274041365, 2046.5660274041365, 2046.5660274041365, 2046.5660274041365, 2046.5660274041365, 2046.5660274041365, 2046.5660274041365, 2046.5660274041365, 2046.5660274041365, 2046.5660274041365, 2047.8488701166111, 2048.848870116611, 2048.848870116611, 2052.848870116611, 2056.848870116611, 2056.848870116611, 2056.848870116611, 2056.848870116611, 2056.848870116611, 2056.848870116611, 2056.848870116611, 2056.848870116611, 2056.848870116611, 2061.1317128290857, 2065.1317128290857, 2068.1317128290857, 2072.697398254035, 2075.697398254035, 2075.697398254035, 2080.263083678984, 2084.263083678984, 2089.3944545288823, 2092.3944545288823, 2093.3944545288823, 2093.3944545288823, 2093.3944545288823, 2093.3944545288823, 2093.3944545288823, 2093.3944545288823, 2094.677297241357, 2095.677297241357, 2095.677297241357, 2096.677297241357, 2097.677297241357, 2097.677297241357, 2097.677297241357, 2097.677297241357, 2097.677297241357, 2101.677297241357, 2105.677297241357, 2112.677297241357, 2118.677297241357, 2122.677297241357, 2124.677297241357, 2125.677297241357, 2125.677297241357, 2125.677297241357, 2125.677297241357, 2126.9601399538315, 2130.808668091255, 2136.808668091255, 2139.808668091255, 2141.808668091255, 2142.808668091255, 2142.808668091255, 2151.3743535162043, 2159.3743535162043, 2162.3743535162043, 2164.3743535162043, 2165.3743535162043, 2165.3743535162043, 2165.3743535162043, 2165.3743535162043, 2165.3743535162043, 2165.3743535162043, 2165.3743535162043, 2165.3743535162043, 2167.9400389411535, 2179.919937928476, 2187.919937928476, 2192.919937928476, 2193.919937928476, 2195.7684660658997, 2196.7684660658997, 2196.7684660658997, 2196.7684660658997, 2196.7684660658997, 2196.7684660658997, 2196.7684660658997, 2196.7684660658997, 2196.7684660658997, 2196.7684660658997, 2196.7684660658997, 2196.7684660658997, 2197.7684660658997, 2198.7684660658997, 2198.7684660658997, 2198.7684660658997, 2198.7684660658997, 2198.7684660658997, 2198.7684660658997, 2198.7684660658997, 2200.7684660658997, 2205.0513087783743, 2207.0513087783743, 2207.0513087783743, 2207.0513087783743, 2207.0513087783743, 2207.0513087783743, 2207.0513087783743, 2207.0513087783743, 2207.0513087783743, 2207.0513087783743, 2207.0513087783743, 2207.0513087783743, 2207.0513087783743, 2207.0513087783743, 2207.0513087783743, 2207.0513087783743, 2207.0513087783743, 2208.0513087783743, 2209.0513087783743, 2209.0513087783743, 2209.0513087783743, 2209.0513087783743, 2210.0513087783743, 2211.0513087783743, 2220.1826796282726, 2228.1826796282726, 2231.1826796282726, 2233.1826796282726, 2234.1826796282726, 2234.1826796282726, 2234.1826796282726, 2234.1826796282726, 2235.1826796282726, 2236.1826796282726, 2236.1826796282726, 2236.1826796282726, 2236.1826796282726, 2236.1826796282726, 2237.1826796282726, 2238.1826796282726, 2238.1826796282726, 2238.1826796282726, 2238.1826796282726, 2238.1826796282726, 2242.1826796282726] roundRobin = [0, 0, 6.84489264765595, 11.84489264765595, 14.84489264765595, 16.84489264765595, 17.84489264765595, 17.84489264765595, 17.84489264765595, 17.84489264765595, 17.84489264765595, 19.477348179689628, 20.477348179689628, 20.477348179689628, 21.924561775189584, 22.924561775189584, 22.924561775189584, 22.924561775189584, 22.924561775189584, 22.924561775189584, 22.924561775189584, 27.77308991261344, 39.03583161241039, 47.03583161241039, 52.03583161241039, 61.298573312207346, 67.58141602468196, 77.258371286852, 82.258371286852, 82.258371286852, 83.258371286852, 84.258371286852, 84.258371286852, 84.258371286852, 88.54121399932662, 92.54121399932662, 97.10689942427585, 100.10689942427585, 106.95542756169971, 111.95542756169971, 111.95542756169971, 111.95542756169971, 111.95542756169971, 111.95542756169971, 115.65248383654742, 127.91522553634437, 137.4809109612936, 138.4809109612936, 142.4809109612936, 145.4809109612936, 147.4809109612936, 148.4809109612936, 148.4809109612936, 148.4809109612936, 148.4809109612936, 148.4809109612936, 148.4809109612936, 148.4809109612936, 148.4809109612936, 148.4809109612936, 148.4809109612936, 148.4809109612936, 150.04659638624284, 151.04659638624284, 151.04659638624284, 151.04659638624284, 155.04659638624284, 159.04659638624284, 163.02649537356518, 165.02649537356518, 165.02649537356518, 165.02649537356518, 165.02649537356518, 165.02649537356518, 173.87502351098905, 186.4407089359383, 193.4407089359383, 199.4407089359383, 208.4407089359383, 220.28923707336216, 231.8549224983114, 241.8549224983114, 248.70345063573527, 254.70345063573527, 258.9862933482099, 261.9862933482099, 269.68334962305767, 273.68334962305767, 275.68334962305767, 276.68334962305767, 276.68334962305767, 276.68334962305767, 281.5318777604815, 285.5318777604815, 285.5318777604815, 285.5318777604815, 287.81472047295614, 289.81472047295614, 289.81472047295614, 289.81472047295614, 294.0975631854308, 302.66324861038004, 306.66324861038004, 306.66324861038004, 308.2289340353293, 309.2289340353293, 309.2289340353293, 310.79461946027857, 316.92599031017704, 320.92599031017704, 320.92599031017704, 320.92599031017704, 320.92599031017704, 320.92599031017704, 320.92599031017704, 320.92599031017704, 320.92599031017704, 320.92599031017704, 320.92599031017704, 321.92599031017704, 322.92599031017704, 323.92599031017704, 323.92599031017704, 326.0573611600755, 327.0573611600755, 327.0573611600755, 327.0573611600755, 327.0573611600755, 331.34020387255015, 335.34020387255015, 340.4715747224486, 347.4715747224486, 352.4715747224486, 352.4715747224486, 353.75441743492325, 354.75441743492325, 354.75441743492325, 356.0372601473979, 357.0372601473979, 357.0372601473979, 357.0372601473979, 357.0372601473979, 362.16863099729636, 368.30000184719484, 375.4313726970933, 380.4313726970933, 388.27990083451715, 394.27990083451715, 395.27990083451715, 395.27990083451715, 395.27990083451715, 395.27990083451715, 397.4112716844156, 398.4112716844156, 398.4112716844156, 398.4112716844156, 398.4112716844156, 403.82548524678873, 407.82548524678873, 410.82548524678873, 416.82548524678873, 421.82548524678873, 424.82548524678873, 427.82548524678873, 429.82548524678873, 433.52254152163647, 434.52254152163647, 441.50244050895884, 446.50244050895884, 449.50244050895884, 451.50244050895884, 452.50244050895884, 452.50244050895884, 452.50244050895884, 452.50244050895884, 452.50244050895884, 452.50244050895884, 452.50244050895884, 452.50244050895884, 452.50244050895884, 452.50244050895884, 452.50244050895884, 452.50244050895884, 452.50244050895884, 452.50244050895884, 452.50244050895884, 452.50244050895884, 452.50244050895884, 452.50244050895884, 452.50244050895884, 452.50244050895884, 454.0681259339081, 460.1994967838066, 464.1994967838066, 464.1994967838066, 464.1994967838066, 467.33086763370505, 469.33086763370505, 470.6137103461797, 471.6137103461797, 479.15929475845127, 484.15929475845127, 487.15929475845127, 489.15929475845127, 491.72498018340053, 492.72498018340053, 492.72498018340053, 498.13919374577364, 503.4220364582483, 504.4220364582483, 504.4220364582483, 504.4220364582483, 505.7048791707229, 506.7048791707229, 511.55340730814675, 515.5534073081467, 518.5534073081467, 521.5534073081467, 523.5534073081467, 523.5534073081467, 524.8362500206213, 525.8362500206213, 527.4019354455705, 528.4019354455705, 528.4019354455705, 533.8161490079436, 539.6646771453675, 543.6646771453675, 545.6646771453675, 546.6646771453675, 546.6646771453675, 546.6646771453675, 546.6646771453675, 546.6646771453675, 546.6646771453675, 548.2303625703167, 549.2303625703167, 549.2303625703167, 549.2303625703167, 549.2303625703167, 549.2303625703167, 549.2303625703167, 549.2303625703167, 554.0788907077406, 558.0788907077406, 561.0788907077406, 563.0788907077406, 566.0788907077406, 568.0788907077406, 568.0788907077406, 568.0788907077406, 568.0788907077406, 568.0788907077406, 568.0788907077406, 569.6445761326898, 573.3416324075375, 579.6244751200121, 584.6244751200121, 592.7558459699106, 598.7558459699106, 599.7558459699106, 599.7558459699106, 607.0185876697076, 612.0185876697076, 615.0185876697076, 618.5842730946569, 620.5842730946569, 620.5842730946569, 620.5842730946569, 620.5842730946569, 620.5842730946569, 620.5842730946569, 626.99848665703, 636.2813293695045, 641.2813293695045, 648.2813293695045, 650.2813293695045, 651.2813293695045, 651.2813293695045, 651.2813293695045, 651.2813293695045, 651.2813293695045, 651.2813293695045, 651.2813293695045, 653.1298575069284, 663.5440710693015, 671.5440710693015, 674.5440710693015, 676.5440710693015, 677.5440710693015, 677.5440710693015, 677.5440710693015, 677.5440710693015, 677.5440710693015, 682.3925992067253, 686.3925992067253, 696.3724981940477, 703.3724981940477, 714.6352398938446, 724.3322961686923, 731.3322961686923, 736.3322961686923, 744.1808243061162, 749.1808243061162, 749.1808243061162, 749.1808243061162, 749.1808243061162, 749.1808243061162, 749.1808243061162, 749.1808243061162, 749.1808243061162, 749.1808243061162, 749.1808243061162, 749.1808243061162, 749.1808243061162, 749.1808243061162, 749.1808243061162, 749.1808243061162, 749.1808243061162, 749.1808243061162, 749.1808243061162, 749.1808243061162, 749.1808243061162, 751.3121951560147, 756.3121951560147, 760.3121951560147, 763.3121951560147, 773.4234649932356, 779.4234649932356, 779.4234649932356, 779.4234649932356, 779.4234649932356, 779.4234649932356, 782.554835843134, 784.554835843134, 790.2518921179817, 801.2317911053041, 809.2317911053041, 811.2317911053041, 814.0803192427279, 815.0803192427279, 820.494532805101, 829.3430609425249, 841.1915890799487, 847.1915890799487, 848.1915890799487, 848.1915890799487, 848.1915890799487, 854.3229599298471, 861.4543307797456, 865.4543307797456, 869.5857016296442, 875.5857016296442, 879.5857016296442, 888.2626568918142, 892.2626568918142, 898.3940277417128, 902.3940277417128, 902.3940277417128, 902.3940277417128, 902.3940277417128, 902.3940277417128, 908.8082413040859, 913.8082413040859, 916.8082413040859, 923.0910840165604, 928.0910840165604, 928.0910840165604, 930.7881402914081, 931.7881402914081, 931.7881402914081, 931.7881402914081, 936.3538257163574, 940.3538257163574, 943.3538257163574, 945.3538257163574, 950.9195111413067, 954.9195111413067, 957.9195111413067, 968.0307809785276, 974.0307809785276, 974.0307809785276, 977.162151828426, 979.162151828426, 979.162151828426, 979.162151828426, 984.0106799658498, 988.0106799658498, 988.0106799658498, 988.0106799658498, 993.9905789531722, 997.9905789531722, 997.9905789531722, 997.9905789531722, 997.9905789531722, 997.9905789531722, 1003.1219498030707, 1007.1219498030707, 1010.1219498030707, 1013.9704779404946, 1015.9704779404946, 1015.9704779404946, 1015.9704779404946, 1019.2332196402915, 1020.2332196402915, 1020.2332196402915, 1026.2131186276138, 1030.2131186276138, 1030.2131186276138, 1030.2131186276138, 1030.2131186276138, 1030.2131186276138, 1030.2131186276138, 1030.2131186276138, 1030.2131186276138, 1030.2131186276138, 1035.0616467650377, 1039.0616467650377, 1042.0616467650377, 1044.0616467650377, 1045.0616467650377, 1045.0616467650377, 1045.0616467650377, 1054.7587030398854, 1062.7587030398854, 1065.7587030398854, 1067.7587030398854, 1068.7587030398854, 1068.7587030398854, 1079.3042874521568, 1087.3042874521568, 1090.3042874521568, 1092.3042874521568, 1093.3042874521568, 1093.3042874521568, 1099.5670291519539, 1103.5670291519539, 1106.5670291519539, 1108.5670291519539, 1113.8498718644285, 1123.5469281392761, 1127.5469281392761, 1127.5469281392761, 1132.1126135642253, 1141.2439844141238, 1148.2439844141238, 1153.2439844141238, 1156.2439844141238, 1162.0925125515478, 1166.0925125515478, 1166.0925125515478, 1166.0925125515478, 1166.0925125515478, 1166.0925125515478, 1166.0925125515478, 1166.0925125515478, 1166.0925125515478, 1166.0925125515478, 1166.0925125515478, 1166.0925125515478, 1166.0925125515478, 1166.0925125515478, 1170.9410406889717, 1174.9410406889717, 1174.9410406889717, 1177.6380969638194, 1180.769467813718, 1181.769467813718, 1181.769467813718, 1181.769467813718, 1181.769467813718, 1181.769467813718, 1181.769467813718, 1181.769467813718, 1188.183681376091, 1197.7493668010402, 1203.5978949384642, 1211.8807376509387, 1217.8807376509387, 1218.8807376509387, 1218.8807376509387, 1218.8807376509387, 1218.8807376509387, 1218.8807376509387, 1218.8807376509387, 1224.0121085008373, 1228.0121085008373, 1228.0121085008373, 1228.0121085008373, 1228.0121085008373, 1228.0121085008373, 1229.2949512133118, 1230.2949512133118, 1230.2949512133118, 1230.2949512133118, 1230.2949512133118, 1230.2949512133118, 1230.2949512133118, 1234.5777939257864, 1238.5777939257864, 1241.5777939257864, 1248.709164775685, 1253.709164775685, 1253.709164775685, 1253.709164775685, 1253.709164775685, 1253.709164775685, 1253.709164775685, 1256.8405356255835, 1258.8405356255835, 1267.6890637630074, 1274.6890637630074, 1279.6890637630074, 1282.6890637630074, 1283.6890637630074, 1284.971906475482, 1285.971906475482, 1285.971906475482, 1285.971906475482, 1285.971906475482, 1285.971906475482, 1285.971906475482, 1285.971906475482, 1290.2547491879566, 1294.2547491879566, 1296.386120037855, 1303.8003336002282, 1313.8003336002282, 1317.8003336002282, 1323.8003336002282, 1329.8003336002282, 1335.648861737652, 1340.648861737652, 1343.648861737652, 1350.214547162601, 1355.214547162601, 1355.214547162601, 1355.214547162601, 1355.214547162601, 1355.214547162601, 1355.214547162601, 1355.214547162601, 1359.477288862398, 1361.477288862398, 1361.477288862398, 1361.477288862398, 1361.477288862398, 1361.477288862398, 1361.477288862398, 1361.477288862398, 1363.3258169998219, 1364.3258169998219, 1364.3258169998219, 1364.3258169998219, 1364.3258169998219, 1364.3258169998219, 1364.3258169998219, 1370.1743451372456, 1375.1743451372456, 1375.1743451372456, 1375.1743451372456, 1375.1743451372456, 1375.1743451372456, 1375.1743451372456, 1378.4370868370427, 1379.4370868370427, 1386.6998285368397, 1391.6998285368397, 1396.8311993867383, 1405.6797275241622, 1409.6797275241622, 1412.6797275241622, 1417.0939410865353, 1419.0939410865353, 1419.0939410865353, 1420.9424692239593, 1421.9424692239593, 1421.9424692239593, 1427.0738400738578, 1431.0738400738578, 1431.0738400738578, 1431.0738400738578, 1431.0738400738578, 1431.0738400738578, 1433.2052109237563, 1434.2052109237563, 1434.2052109237563, 1434.2052109237563, 1438.488053636231, 1442.488053636231, 1445.488053636231, 1447.488053636231, 1451.750795336028, 1452.750795336028, 1452.750795336028, 1452.750795336028, 1454.0336380485026, 1455.0336380485026, 1455.0336380485026, 1461.0135370358248, 1475.2762787356219, 1490.5591214480964, 1499.5591214480964, 1502.5591214480964, 1507.5591214480964, 1514.5591214480964, 1521.5591214480964, 1531.5591214480964, 1547.1047058603679, 1560.1047058603679, 1566.1047058603679, 1570.1047058603679, 1572.1047058603679, 1572.1047058603679, 1572.1047058603679, 1573.9532339977918, 1580.2360767102664, 1585.2360767102664, 1588.2360767102664, 1594.4988184100632, 1601.4988184100632, 1606.0645038350124, 1610.0645038350124, 1613.0645038350124, 1615.0645038350124, 1616.0645038350124, 1616.0645038350124, 1620.347346547487, 1629.195874684911, 1633.195874684911, 1633.195874684911, 1633.195874684911, 1633.195874684911, 1633.195874684911, 1633.195874684911, 1638.3272455348094, 1651.1757736722332, 1662.1757736722332, 1672.0243018096571, 1680.0243018096571, 1685.7213580845048, 1689.0042007969794, 1691.0042007969794, 1691.0042007969794, 1691.0042007969794, 1691.0042007969794, 1691.0042007969794, 1691.0042007969794, 1691.0042007969794, 1691.0042007969794, 1696.4184143593525, 1700.4184143593525, 1700.4184143593525, 1700.4184143593525, 1700.4184143593525, 1700.4184143593525, 1700.4184143593525, 1700.4184143593525, 1700.4184143593525, 1700.4184143593525, 1700.4184143593525, 1703.1154706342002, 1704.1154706342002, 1704.1154706342002, 1704.1154706342002, 1704.1154706342002, 1704.1154706342002, 1704.1154706342002, 1704.1154706342002, 1710.2468414840987, 1720.0953696215227, 1727.0953696215227, 1734.3782123339972, 1740.3782123339972, 1745.7924258963703, 1754.2066394587434, 1759.2066394587434, 1759.2066394587434, 1759.2066394587434, 1762.338010308642, 1764.338010308642, 1770.0350665834897, 1774.0350665834897, 1784.5806509957613, 1791.5806509957613, 1792.5806509957613, 1792.5806509957613, 1796.8433926955584, 1801.9747635454569, 1803.9747635454569, 1803.9747635454569, 1803.9747635454569, 1810.1061343953554, 1815.1061343953554, 1822.9546625327794, 1828.9546625327794, 1829.9546625327794, 1835.3688760951525, 1843.651718807627, 1847.651718807627, 1854.3487750824747, 1858.3487750824747, 1859.3487750824747, 1859.3487750824747, 1859.3487750824747, 1859.3487750824747, 1861.7629886448478, 1862.7629886448478, 1867.6115167822718, 1871.6115167822718, 1874.6115167822718, 1876.6115167822718, 1877.6115167822718, 1877.6115167822718, 1884.025730344645, 1889.025730344645, 1889.025730344645, 1891.1571011945434, 1892.1571011945434, 1892.1571011945434, 1894.0056293319674, 1899.8541574693913, 1903.8541574693913, 1906.8541574693913, 1908.8541574693913, 1909.8541574693913, 1909.8541574693913, 1909.8541574693913, 1909.8541574693913, 1909.8541574693913, 1909.8541574693913, 1915.8340564567136, 1919.8340564567136, 1921.6825845941376, 1922.6825845941376, 1922.6825845941376, 1922.6825845941376, 1924.813955444036, 1925.813955444036, 1925.813955444036, 1925.813955444036, 1925.813955444036, 1925.813955444036, 1925.813955444036, 1925.813955444036, 1925.813955444036, 1925.813955444036, 1925.813955444036, 1925.813955444036, 1927.66248358146, 1928.66248358146, 1934.2281690064092, 1939.2281690064092, 1940.2281690064092, 1940.2281690064092, 1940.2281690064092, 1940.2281690064092, 1944.5110117188838, 1948.5110117188838, 1951.5110117188838, 1953.5110117188838, 1954.5110117188838, 1954.5110117188838, 1961.4909107062063, 1966.4909107062063, 1966.4909107062063, 1966.4909107062063, 1966.4909107062063, 1966.4909107062063, 1966.4909107062063, 1970.7737534186808, 1974.7737534186808, 1974.7737534186808, 1974.7737534186808, 1978.7737534186808, 1982.7737534186808, 1985.7737534186808, 1987.7737534186808, 1988.7737534186808, 1988.7737534186808, 1991.187966981054, 1992.187966981054, 1993.187966981054, 1998.8850232559016, 2002.8850232559016, 2002.8850232559016, 2002.8850232559016, 2002.8850232559016, 2002.8850232559016, 2002.8850232559016, 2002.8850232559016, 2012.5820795307493, 2020.5820795307493, 2023.5820795307493, 2025.5820795307493, 2026.5820795307493, 2026.5820795307493, 2027.8649222432239, 2028.8649222432239, 2028.8649222432239, 2028.8649222432239, 2028.8649222432239, 2028.8649222432239, 2028.8649222432239, 2028.8649222432239, 2034.8448212305461, 2038.8448212305461, 2038.8448212305461, 2038.8448212305461, 2038.8448212305461, 2038.8448212305461, 2048.259034792919, 2056.259034792919, 2059.259034792919, 2061.259034792919, 2062.259034792919, 2062.259034792919, 2062.259034792919, 2062.259034792919, 2062.259034792919, 2063.5418775053936, 2070.2389337802415, 2079.2389337802415, 2086.9359900550894, 2087.9359900550894, 2087.9359900550894, 2087.9359900550894, 2087.9359900550894, 2087.9359900550894, 2093.6330463299373, 2099.1987317548865, 2100.1987317548865, 2100.1987317548865, 2100.1987317548865, 2104.481574467361, 2110.3301026047848, 2114.3301026047848, 2116.3301026047848, 2117.3301026047848, 2117.3301026047848, 2120.461473454683, 2126.7443161671576, 2130.7443161671576, 2133.7443161671576, 2137.027158879632, 2144.875687017056, 2155.572743291904, 2159.572743291904, 2162.572743291904, 2164.572743291904, 2165.572743291904, 2165.572743291904, 2165.572743291904, 2165.572743291904, 2165.572743291904, 2165.572743291904, 2165.572743291904, 2165.572743291904, 2165.572743291904, 2165.572743291904, 2167.704114141802, 2168.704114141802, 2168.704114141802, 2172.704114141802, 2176.704114141802, 2176.704114141802, 2176.704114141802, 2176.704114141802, 2176.704114141802, 2176.704114141802, 2176.704114141802, 2176.704114141802, 2176.704114141802, 2180.9869568542767, 2184.9869568542767, 2184.9869568542767, 2191.6840131291247, 2196.6840131291247, 2199.6840131291247, 2201.6840131291247, 2202.6840131291247, 2209.9467548289213, 2214.9467548289213, 2215.9467548289213, 2215.9467548289213, 2215.9467548289213, 2215.9467548289213, 2215.9467548289213, 2215.9467548289213, 2215.9467548289213, 2215.9467548289213, 2217.229597541396, 2218.229597541396, 2218.229597541396, 2219.5124402538704, 2220.5124402538704, 2220.5124402538704, 2220.5124402538704, 2220.5124402538704, 2220.5124402538704, 2224.795282966345, 2228.795282966345, 2234.209496528718, 2238.209496528718, 2238.209496528718, 2238.209496528718, 2238.209496528718, 2238.209496528718, 2238.209496528718, 2238.209496528718, 2241.1893955160403, 2246.734979928312, 2252.734979928312, 2255.734979928312, 2257.734979928312, 2258.734979928312, 2258.734979928312, 2268.714878915634, 2276.714878915634, 2279.714878915634, 2281.714878915634, 2282.714878915634, 2282.714878915634, 2282.714878915634, 2282.714878915634, 2282.714878915634, 2282.714878915634, 2282.714878915634, 2282.714878915634, 2285.280564340583, 2296.694777902956, 2304.694777902956, 2312.694777902956, 2315.694777902956, 2319.6746768902785, 2320.6746768902785, 2320.6746768902785, 2320.6746768902785, 2320.6746768902785, 2320.6746768902785, 2320.6746768902785, 2320.6746768902785, 2320.6746768902785, 2320.6746768902785, 2320.6746768902785, 2320.6746768902785, 2321.957519602753, 2322.957519602753, 2322.957519602753, 2322.957519602753, 2322.957519602753, 2322.957519602753, 2322.957519602753, 2322.957519602753, 2327.7859467274993, 2332.9173175773976, 2334.9173175773976, 2334.9173175773976, 2334.9173175773976, 2334.9173175773976, 2334.9173175773976, 2334.9173175773976, 2334.9173175773976, 2334.9173175773976, 2334.9173175773976, 2334.9173175773976, 2334.9173175773976, 2334.9173175773976, 2334.9173175773976, 2334.9173175773976, 2334.9173175773976, 2334.9173175773976, 2337.048688427296, 2338.048688427296, 2338.048688427296, 2338.048688427296, 2338.048688427296, 2339.048688427296, 2340.048688427296, 2350.8771155520417, 2358.8771155520417, 2358.8771155520417, 2358.8771155520417, 2358.8771155520417, 2358.8771155520417, 2358.8771155520417, 2358.8771155520417, 2361.2913291144146, 2362.2913291144146, 2362.2913291144146, 2362.2913291144146, 2362.2913291144146, 2362.2913291144146, 2365.5540708142116, 2366.5540708142116, 2366.5540708142116, 2366.5540708142116, 2366.5540708142116, 2366.5540708142116, 2371.119756239161] pyhop = [0, 0, 5, 11.725063222660214, 11.725063222660214, 11.725063222660214, 11.725063222660214, 11.725063222660214, 11.725063222660214, 11.725063222660214, 11.725063222660214, 12.725063222660214, 14.290748647609453, 14.290748647609453, 15.290748647609453, 16.85643407255869, 16.85643407255869, 16.85643407255869, 16.85643407255869, 16.85643407255869, 16.85643407255869, 20.85643407255869, 30.42211949750793, 39.5716574237162, 39.5716574237162, 43.5716574237162, 49.985870986089296, 57.11724183598777, 64.01429811083548, 64.01429811083548, 65.01429811083548, 67.14566896073396, 67.14566896073396, 67.14566896073396, 71.14566896073396, 75.99419709815781, 76.99419709815781, 79.69125337300552, 84.69125337300552, 90.822624222904, 90.822624222904, 90.822624222904, 90.822624222904, 90.822624222904, 92.822624222904, 104.80252321022633, 114.08536592270094, 115.65105134765018, 119.65105134765018, 122.65105134765018, 124.65105134765018, 125.65105134765018, 125.65105134765018, 125.65105134765018, 125.65105134765018, 125.65105134765018, 125.65105134765018, 125.65105134765018, 125.65105134765018, 125.65105134765018, 125.65105134765018, 125.65105134765018, 126.65105134765018, 128.49957948507404, 128.49957948507404, 128.49957948507404, 132.49957948507404, 136.49957948507404, 138.49957948507404, 142.47947847239638, 142.47947847239638, 142.47947847239638, 142.47947847239638, 142.47947847239638, 150.47947847239638, 163.04516389734562, 167.04516389734562, 175.61084932229485, 184.74222017219333, 194.15643373456643, 202.72211915951567, 211.85349000941414, 221.55054628426186, 227.39907442168573, 231.09613069653344, 232.37897340900807, 232.37897340900807, 237.37897340900807, 244.64171510880502, 244.64171510880502, 244.64171510880502, 244.64171510880502, 248.64171510880502, 254.05592867117812, 254.05592867117812, 254.05592867117812, 256.0559286711781, 258.3387713836527, 258.3387713836527, 258.3387713836527, 262.3387713836527, 271.75298494602583, 276.3186703709751, 276.3186703709751, 277.3186703709751, 278.88435579592436, 278.88435579592436, 279.88435579592436, 285.7328839333482, 290.8642547832467, 290.8642547832467, 290.8642547832467, 290.8642547832467, 290.8642547832467, 290.8642547832467, 290.8642547832467, 290.8642547832467, 290.8642547832467, 290.8642547832467, 291.8642547832467, 293.1470974957213, 294.1470974957213, 294.1470974957213, 295.1470974957213, 296.1470974957213, 296.1470974957213, 296.1470974957213, 296.1470974957213, 300.1470974957213, 304.99562563314515, 305.99562563314515, 311.844153770569, 316.40983919551826, 316.40983919551826, 317.40983919551826, 318.9755246204675, 318.9755246204675, 319.9755246204675, 320.9755246204675, 320.9755246204675, 320.9755246204675, 320.9755246204675, 324.9755246204675, 330.25836733294216, 337.106895470366, 344.369637170163, 348.369637170163, 353.21816530758684, 353.21816530758684, 353.21816530758684, 353.21816530758684, 353.21816530758684, 354.21816530758684, 356.3495361574853, 356.3495361574853, 356.3495361574853, 356.3495361574853, 360.3495361574853, 364.9152215824346, 364.9152215824346, 368.9152215824346, 373.1980642949092, 373.1980642949092, 374.1980642949092, 375.7637497198585, 377.7637497198585, 380.1779632822316, 385.1779632822316, 391.5921768446047, 391.5921768446047, 391.5921768446047, 391.5921768446047, 391.5921768446047, 391.5921768446047, 391.5921768446047, 391.5921768446047, 391.5921768446047, 391.5921768446047, 391.5921768446047, 391.5921768446047, 391.5921768446047, 391.5921768446047, 391.5921768446047, 391.5921768446047, 391.5921768446047, 391.5921768446047, 391.5921768446047, 391.5921768446047, 391.5921768446047, 391.5921768446047, 391.5921768446047, 392.5921768446047, 399.0063904069778, 403.28923311945243, 403.28923311945243, 403.28923311945243, 405.28923311945243, 410.6833456691479, 411.6833456691479, 414.097559231521, 419.097559231521, 425.7946155063687, 425.7946155063687, 425.7946155063687, 426.7946155063687, 429.49167178121644, 429.49167178121644, 433.49167178121644, 440.47157076853875, 443.45146975586107, 443.45146975586107, 443.45146975586107, 444.45146975586107, 446.8656833182342, 450.8656833182342, 456.2798968806073, 456.2798968806073, 457.2798968806073, 459.976953155455, 459.976953155455, 460.976953155455, 462.5426385804043, 463.5426385804043, 465.10832400535355, 465.10832400535355, 469.10832400535355, 475.52253756772666, 476.8053802802013, 476.8053802802013, 476.8053802802013, 476.8053802802013, 476.8053802802013, 476.8053802802013, 476.8053802802013, 476.8053802802013, 477.8053802802013, 479.65390841762513, 479.65390841762513, 479.65390841762513, 479.65390841762513, 479.65390841762513, 479.65390841762513, 479.65390841762513, 483.65390841762513, 487.93675113009976, 487.93675113009976, 487.93675113009976, 492.93675113009976, 498.7852792675236, 498.7852792675236, 498.7852792675236, 498.7852792675236, 499.7852792675236, 501.63380740494745, 501.63380740494745, 501.63380740494745, 501.63380740494745, 501.63380740494745, 501.63380740494745, 501.63380740494745, 501.63380740494745, 501.63380740494745, 501.63380740494745, 501.63380740494745, 501.63380740494745, 501.63380740494745, 501.63380740494745, 501.63380740494745, 501.63380740494745, 501.63380740494745, 505.63380740494745, 511.04802096732055, 516.0480209673206, 520.6137063922698, 520.6137063922698, 521.6137063922698, 524.0279199546429, 524.0279199546429, 524.0279199546429, 524.0279199546429, 524.0279199546429, 524.0279199546429, 529.0279199546429, 540.2906616544399, 545.5735043669144, 549.5735043669144, 549.5735043669144, 549.5735043669144, 549.5735043669144, 549.5735043669144, 549.5735043669144, 549.5735043669144, 549.5735043669144, 549.5735043669144, 550.5735043669144, 560.1391897918637, 569.8362460667114, 569.8362460667114, 569.8362460667114, 569.8362460667114, 569.8362460667114, 569.8362460667114, 569.8362460667114, 569.8362460667114, 573.8362460667114, 580.0989877665083, 585.0989877665083, 592.0788867538307, 600.0788867538307, 610.9073138785769, 610.9073138785769, 610.9073138785769, 614.9073138785769, 619.1901565910515, 619.1901565910515, 619.1901565910515, 619.1901565910515, 619.1901565910515, 619.1901565910515, 619.1901565910515, 619.1901565910515, 619.1901565910515, 619.1901565910515, 619.1901565910515, 619.1901565910515, 619.1901565910515, 619.1901565910515, 619.1901565910515, 619.1901565910515, 619.1901565910515, 619.1901565910515, 619.1901565910515, 619.1901565910515, 620.1901565910515, 626.32152744095, 630.6043701534246, 630.6043701534246, 632.6043701534246, 636.8671118532216, 636.8671118532216, 636.8671118532216, 636.8671118532216, 636.8671118532216, 636.8671118532216, 636.8671118532216, 637.8671118532216, 638.8671118532216, 638.8671118532216, 642.8671118532216, 651.8671118532216, 658.2813254155947, 658.2813254155947, 659.2813254155947, 660.8470108405439, 664.8470108405439, 674.261224402917, 683.1097525403409, 687.1097525403409, 691.6754379652901, 691.6754379652901, 696.6754379652901, 703.2411233902393, 704.5239661027139, 705.5239661027139, 711.0896515276631, 715.938179665087, 717.938179665087, 722.2009213648839, 726.2009213648839, 730.7666067898332, 730.7666067898332, 730.7666067898332, 730.7666067898332, 730.7666067898332, 735.7666067898332, 742.7465057771556, 742.7465057771556, 746.7465057771556, 752.1607193395287, 752.1607193395287, 753.1607193395287, 754.7264047644779, 754.7264047644779, 754.7264047644779, 758.7264047644779, 763.5749329019018, 763.5749329019018, 763.5749329019018, 767.5749329019018, 772.4234610393256, 772.4234610393256, 777.4234610393256, 784.9690454515973, 784.9690454515973, 786.9690454515973, 791.5146298638689, 791.5146298638689, 791.5146298638689, 795.5146298638689, 800.3631580012927, 800.3631580012927, 800.3631580012927, 804.3631580012927, 808.6460007137673, 808.6460007137673, 808.6460007137673, 808.6460007137673, 808.6460007137673, 812.6460007137673, 818.343056988615, 818.343056988615, 819.343056988615, 820.9087424135643, 820.9087424135643, 820.9087424135643, 821.9087424135643, 824.8886414008866, 824.8886414008866, 828.8886414008866, 833.1714841133612, 833.1714841133612, 833.1714841133612, 833.1714841133612, 833.1714841133612, 833.1714841133612, 833.1714841133612, 833.1714841133612, 833.1714841133612, 837.1714841133612, 842.3028549632597, 842.3028549632597, 842.3028549632597, 842.3028549632597, 842.3028549632597, 842.3028549632597, 850.3028549632597, 860.2827539505821, 860.2827539505821, 860.2827539505821, 860.2827539505821, 860.2827539505821, 868.2827539505821, 876.8484393755313, 876.8484393755313, 876.8484393755313, 876.8484393755313, 876.8484393755313, 880.8484393755313, 886.8283383628536, 886.8283383628536, 886.8283383628536, 890.8283383628536, 899.9597092127522, 905.3739227751253, 905.3739227751253, 909.3739227751253, 918.5052936250238, 923.3538217624476, 923.3538217624476, 923.3538217624476, 927.3538217624476, 931.6366644749222, 931.6366644749222, 931.6366644749222, 931.6366644749222, 931.6366644749222, 931.6366644749222, 931.6366644749222, 931.6366644749222, 931.6366644749222, 931.6366644749222, 931.6366644749222, 931.6366644749222, 931.6366644749222, 935.6366644749222, 940.485192612346, 940.485192612346, 941.485192612346, 944.0508780372953, 946.1822488871939, 946.1822488871939, 946.1822488871939, 946.1822488871939, 946.1822488871939, 946.1822488871939, 946.1822488871939, 951.1822488871939, 962.4449905869909, 967.4449905869909, 972.7278332994655, 978.7077322867879, 978.7077322867879, 978.7077322867879, 978.7077322867879, 978.7077322867879, 978.7077322867879, 978.7077322867879, 982.7077322867879, 987.5562604242117, 987.5562604242117, 987.5562604242117, 987.5562604242117, 987.5562604242117, 988.5562604242117, 990.121945849161, 990.121945849161, 990.121945849161, 990.121945849161, 990.121945849161, 990.121945849161, 994.121945849161, 998.121945849161, 998.121945849161, 1002.121945849161, 1006.4047885616355, 1006.4047885616355, 1006.4047885616355, 1006.4047885616355, 1006.4047885616355, 1006.4047885616355, 1008.4047885616355, 1012.6675302614326, 1020.6675302614326, 1028.2332156863818, 1030.2332156863818, 1031.2332156863818, 1031.2332156863818, 1032.2332156863818, 1034.0817438238057, 1034.0817438238057, 1034.0817438238057, 1034.0817438238057, 1034.0817438238057, 1034.0817438238057, 1034.0817438238057, 1038.0817438238057, 1043.4959573861788, 1044.4959573861788, 1051.6273282360773, 1062.7586990859759, 1066.7586990859759, 1074.324384510925, 1080.6072272233996, 1080.6072272233996, 1080.6072272233996, 1080.6072272233996, 1084.6072272233996, 1088.8900699358742, 1088.8900699358742, 1088.8900699358742, 1088.8900699358742, 1088.8900699358742, 1088.8900699358742, 1088.8900699358742, 1090.8900699358742, 1095.7184970606204, 1095.7184970606204, 1095.7184970606204, 1095.7184970606204, 1095.7184970606204, 1095.7184970606204, 1095.7184970606204, 1096.7184970606204, 1098.849867910519, 1098.849867910519, 1098.849867910519, 1098.849867910519, 1098.849867910519, 1098.849867910519, 1103.849867910519, 1110.8297668978412, 1110.8297668978412, 1110.8297668978412, 1110.8297668978412, 1110.8297668978412, 1110.8297668978412, 1111.8297668978412, 1113.3954523227903, 1118.3954523227903, 1124.8096658851634, 1128.8096658851634, 1137.3753513101126, 1141.6581940225872, 1141.6581940225872, 1142.6581940225872, 1145.0724075849603, 1145.0724075849603, 1146.0724075849603, 1147.0724075849603, 1147.0724075849603, 1151.0724075849603, 1156.2037784348588, 1156.2037784348588, 1156.2037784348588, 1156.2037784348588, 1156.2037784348588, 1157.2037784348588, 1158.4866211473334, 1158.4866211473334, 1158.4866211473334, 1162.4866211473334, 1167.617991997232, 1167.617991997232, 1167.617991997232, 1168.617991997232, 1169.617991997232, 1169.617991997232, 1169.617991997232, 1169.617991997232, 1169.617991997232, 1169.617991997232, 1169.617991997232, 1169.617991997232, 1173.617991997232, 1187.5978909845542, 1200.7292618344527, 1209.5777899718767, 1213.8606326843512, 1217.8606326843512, 1226.7091608217752, 1231.7091608217752, 1236.7091608217752, 1243.4062170966229, 1244.6890598090974, 1244.6890598090974, 1244.6890598090974, 1244.6890598090974, 1244.6890598090974, 1244.6890598090974, 1244.6890598090974, 1245.6890598090974, 1252.5375879465214, 1257.5375879465214, 1257.5375879465214, 1259.5375879465214, 1264.8003296463185, 1269.8003296463185, 1276.2145432086916, 1276.2145432086916, 1280.2145432086916, 1285.0630713461155, 1285.0630713461155, 1285.0630713461155, 1289.0630713461155, 1293.0630713461155, 1293.0630713461155, 1293.0630713461155, 1298.0630713461155, 1312.194442196014, 1321.8914984708617, 1330.1743411833363, 1336.871397458184, 1338.1542401706586, 1338.1542401706586, 1338.1542401706586, 1338.1542401706586, 1338.1542401706586, 1338.1542401706586, 1338.1542401706586, 1338.1542401706586, 1338.1542401706586, 1338.1542401706586, 1338.1542401706586, 1338.1542401706586, 1338.1542401706586, 1338.1542401706586, 1342.1542401706586, 1347.0027683080825, 1347.0027683080825, 1347.0027683080825, 1347.0027683080825, 1347.0027683080825, 1347.0027683080825, 1347.0027683080825, 1347.0027683080825, 1347.0027683080825, 1347.0027683080825, 1348.0027683080825, 1350.4169818704556, 1350.4169818704556, 1350.4169818704556, 1350.4169818704556, 1350.4169818704556, 1350.4169818704556, 1350.4169818704556, 1355.4169818704556, 1365.8311954328287, 1372.0939371326258, 1377.0939371326258, 1384.3566788324229, 1384.3566788324229, 1388.3566788324229, 1392.922364257372, 1392.922364257372, 1392.922364257372, 1394.922364257372, 1399.185105957169, 1403.185105957169, 1409.1650049444913, 1414.1650049444913, 1420.862061219339, 1420.862061219339, 1420.862061219339, 1422.862061219339, 1427.4277466442882, 1429.4277466442882, 1433.1248029191358, 1433.1248029191358, 1438.1248029191358, 1446.8017581813058, 1450.8017581813058, 1451.8017581813058, 1453.9331290312043, 1453.9331290312043, 1453.9331290312043, 1453.9331290312043, 1453.9331290312043, 1454.9331290312043, 1457.7816571686283, 1460.1958707310014, 1460.1958707310014, 1460.1958707310014, 1460.1958707310014, 1460.1958707310014, 1461.1958707310014, 1464.4586124307984, 1468.4586124307984, 1473.0242978557476, 1473.0242978557476, 1473.0242978557476, 1473.0242978557476, 1473.0242978557476, 1478.0242978557476, 1485.2870395555447, 1485.2870395555447, 1486.2870395555447, 1487.5698822680192, 1487.5698822680192, 1488.5698822680192, 1494.7012531179178, 1498.7012531179178, 1498.7012531179178, 1498.7012531179178, 1498.7012531179178, 1498.7012531179178, 1498.7012531179178, 1498.7012531179178, 1498.7012531179178, 1498.7012531179178, 1502.7012531179178, 1508.68115210524, 1509.68115210524, 1512.6610510925623, 1512.6610510925623, 1512.6610510925623, 1513.6610510925623, 1515.5095792299862, 1515.5095792299862, 1515.5095792299862, 1515.5095792299862, 1515.5095792299862, 1515.5095792299862, 1515.5095792299862, 1515.5095792299862, 1515.5095792299862, 1515.5095792299862, 1515.5095792299862, 1516.5095792299862, 1517.7924219424608, 1522.7924219424608, 1530.0551636422576, 1531.0551636422576, 1531.0551636422576, 1531.0551636422576, 1531.0551636422576, 1535.0551636422576, 1539.6208490672068, 1539.6208490672068, 1539.6208490672068, 1539.6208490672068, 1539.6208490672068, 1544.6208490672068, 1550.4693772046305, 1550.4693772046305, 1550.4693772046305, 1550.4693772046305, 1550.4693772046305, 1550.4693772046305, 1554.4693772046305, 1558.752219917105, 1558.752219917105, 1558.752219917105, 1562.752219917105, 1567.600748054529, 1567.600748054529, 1567.600748054529, 1567.600748054529, 1567.600748054529, 1568.600748054529, 1571.0149616169022, 1572.0149616169022, 1576.0149616169022, 1581.1463324668007, 1581.1463324668007, 1581.1463324668007, 1581.1463324668007, 1581.1463324668007, 1581.1463324668007, 1581.1463324668007, 1589.1463324668007, 1598.8433887416484, 1598.8433887416484, 1598.8433887416484, 1598.8433887416484, 1598.8433887416484, 1599.8433887416484, 1601.126231454123, 1601.126231454123, 1601.126231454123, 1601.126231454123, 1601.126231454123, 1601.126231454123, 1601.126231454123, 1605.126231454123, 1610.8232877289706, 1610.8232877289706, 1610.8232877289706, 1610.8232877289706, 1610.8232877289706, 1618.8232877289706, 1628.803186716293, 1628.803186716293, 1628.803186716293, 1628.803186716293, 1628.803186716293, 1628.803186716293, 1628.803186716293, 1628.803186716293, 1629.803186716293, 1635.0860294287677, 1644.6517148537168, 1652.06592841609, 1653.631613841039, 1653.631613841039, 1653.631613841039, 1653.631613841039, 1653.631613841039, 1657.631613841039, 1664.3286701158868, 1665.894355540836, 1665.894355540836, 1665.894355540836, 1669.894355540836, 1675.1771982533105, 1676.7428836782597, 1676.7428836782597, 1676.7428836782597, 1676.7428836782597, 1678.7428836782597, 1686.722782665582, 1691.0056253780565, 1691.0056253780565, 1692.0056253780565, 1698.0056253780565, 1708.136996227955, 1713.2683670778536, 1713.2683670778536, 1713.2683670778536, 1713.2683670778536, 1713.2683670778536, 1713.2683670778536, 1713.2683670778536, 1713.2683670778536, 1713.2683670778536, 1713.2683670778536, 1713.2683670778536, 1713.2683670778536, 1713.2683670778536, 1714.2683670778536, 1716.399737927752, 1716.399737927752, 1720.399737927752, 1724.399737927752, 1724.399737927752, 1724.399737927752, 1724.399737927752, 1724.399737927752, 1724.399737927752, 1724.399737927752, 1724.399737927752, 1724.399737927752, 1728.399737927752, 1733.5311087776506, 1733.5311087776506, 1738.5311087776506, 1743.8139514901252, 1743.8139514901252, 1743.8139514901252, 1743.8139514901252, 1748.8139514901252, 1755.2281650524983, 1756.2281650524983, 1756.2281650524983, 1756.2281650524983, 1756.2281650524983, 1756.2281650524983, 1756.2281650524983, 1756.2281650524983, 1756.2281650524983, 1757.2281650524983, 1758.5110077649729, 1758.5110077649729, 1759.5110077649729, 1761.925221327346, 1761.925221327346, 1761.925221327346, 1761.925221327346, 1761.925221327346, 1765.925221327346, 1770.2080640398206, 1774.2080640398206, 1779.9051203146682, 1779.9051203146682, 1779.9051203146682, 1779.9051203146682, 1779.9051203146682, 1779.9051203146682, 1779.9051203146682, 1780.9051203146682, 1784.4708057396174, 1791.8850193019905, 1795.8850193019905, 1800.016390151889, 1801.016390151889, 1801.016390151889, 1809.016390151889, 1820.1276599891098, 1820.1276599891098, 1820.1276599891098, 1820.1276599891098, 1820.1276599891098, 1820.1276599891098, 1820.1276599891098, 1820.1276599891098, 1820.1276599891098, 1820.1276599891098, 1820.1276599891098, 1822.1276599891098, 1833.541873551483, 1842.956087113856, 1847.956087113856, 1848.956087113856, 1849.956087113856, 1851.80461525128, 1851.80461525128, 1851.80461525128, 1851.80461525128, 1851.80461525128, 1851.80461525128, 1851.80461525128, 1851.80461525128, 1851.80461525128, 1851.80461525128, 1851.80461525128, 1852.80461525128, 1855.5016715261277, 1855.5016715261277, 1855.5016715261277, 1855.5016715261277, 1855.5016715261277, 1855.5016715261277, 1855.5016715261277, 1857.5016715261277, 1863.1987278009753, 1865.1987278009753, 1868.6129413633485, 1868.6129413633485, 1868.6129413633485, 1868.6129413633485, 1868.6129413633485, 1868.6129413633485, 1868.6129413633485, 1868.6129413633485, 1868.6129413633485, 1868.6129413633485, 1868.6129413633485, 1868.6129413633485, 1868.6129413633485, 1868.6129413633485, 1868.6129413633485, 1869.6129413633485, 1870.6129413633485, 1870.6129413633485, 1870.6129413633485, 1870.6129413633485, 1871.6129413633485, 1873.4614695007724, 1881.4614695007724, 1892.5727393379932, 1892.5727393379932] FirstCome = [0, 0, 6.84489264765595, 11.84489264765595, 14.84489264765595, 16.84489264765595, 17.84489264765595, 17.84489264765595, 17.84489264765595, 17.84489264765595, 17.84489264765595, 19.477348179689628, 20.477348179689628, 20.477348179689628, 21.924561775189584, 22.924561775189584, 22.924561775189584, 22.924561775189584, 22.924561775189584, 22.924561775189584, 22.924561775189584, 27.77308991261344, 39.03583161241039, 47.03583161241039, 52.03583161241039, 61.298573312207346, 67.58141602468196, 77.258371286852, 82.258371286852, 82.258371286852, 83.258371286852, 84.258371286852, 84.258371286852, 84.258371286852, 88.54121399932662, 92.54121399932662, 97.10689942427585, 100.10689942427585, 106.95542756169971, 111.95542756169971, 111.95542756169971, 111.95542756169971, 111.95542756169971, 111.95542756169971, 115.65248383654742, 127.91522553634437, 137.4809109612936, 138.4809109612936, 142.4809109612936, 145.4809109612936, 147.4809109612936, 148.4809109612936, 148.4809109612936, 148.4809109612936, 148.4809109612936, 148.4809109612936, 148.4809109612936, 148.4809109612936, 148.4809109612936, 148.4809109612936, 148.4809109612936, 148.4809109612936, 150.04659638624284, 151.04659638624284, 151.04659638624284, 151.04659638624284, 155.04659638624284, 159.04659638624284, 163.02649537356518, 165.02649537356518, 165.02649537356518, 165.02649537356518, 165.02649537356518, 165.02649537356518, 173.87502351098905, 186.4407089359383, 193.4407089359383, 199.4407089359383, 208.4407089359383, 219.72355164841292, 226.72355164841292, 237.40050691058298, 242.40050691058298, 243.6833496230576, 244.6833496230576, 244.6833496230576, 251.38040589790532, 256.38040589790535, 256.38040589790535, 256.38040589790535, 256.38040589790535, 260.38040589790535, 264.38040589790535, 264.38040589790535, 264.38040589790535, 267.79461946027845, 269.79461946027845, 269.79461946027845, 269.79461946027845, 273.79461946027845, 282.3603048852277, 286.3603048852277, 286.3603048852277, 287.925990310177, 288.925990310177, 288.925990310177, 290.49167573512625, 296.6230465850247, 300.6230465850247, 300.6230465850247, 300.6230465850247, 300.6230465850247, 300.6230465850247, 300.6230465850247, 300.6230465850247, 300.6230465850247, 300.6230465850247, 300.6230465850247, 301.6230465850247, 302.6230465850247, 303.6230465850247, 303.6230465850247, 305.7544174349232, 306.7544174349232, 306.7544174349232, 306.7544174349232, 306.7544174349232, 311.03726014739783, 315.03726014739783, 320.1686309972963, 327.1686309972963, 332.1686309972963, 332.1686309972963, 333.45147370977094, 334.45147370977094, 334.45147370977094, 335.73431642224557, 336.73431642224557, 336.73431642224557, 336.73431642224557, 336.73431642224557, 341.86568727214404, 347.9970581220425, 355.128428971941, 360.128428971941, 367.97695710936483, 373.97695710936483, 374.97695710936483, 374.97695710936483, 374.97695710936483, 374.97695710936483, 377.1083279592633, 378.1083279592633, 378.1083279592633, 378.1083279592633, 378.1083279592633, 383.5225415216364, 387.5225415216364, 390.5225415216364, 396.5225415216364, 401.5225415216364, 404.5225415216364, 407.5225415216364, 409.5225415216364, 413.21959779648415, 414.21959779648415, 421.1994967838065, 426.1994967838065, 429.1994967838065, 431.1994967838065, 432.1994967838065, 432.1994967838065, 432.1994967838065, 432.1994967838065, 432.1994967838065, 432.1994967838065, 432.1994967838065, 432.1994967838065, 432.1994967838065, 432.1994967838065, 432.1994967838065, 432.1994967838065, 432.1994967838065, 432.1994967838065, 432.1994967838065, 432.1994967838065, 432.1994967838065, 432.1994967838065, 432.1994967838065, 432.1994967838065, 433.7651822087558, 439.89655305865426, 443.89655305865426, 443.89655305865426, 443.89655305865426, 447.02792390855274, 449.02792390855274, 450.31076662102737, 451.31076662102737, 458.85635103329895, 463.85635103329895, 466.85635103329895, 468.85635103329895, 471.4220364582482, 472.4220364582482, 472.4220364582482, 477.8362500206213, 483.11909273309595, 484.11909273309595, 484.11909273309595, 484.11909273309595, 485.4019354455706, 486.4019354455706, 491.2504635829944, 495.2504635829944, 498.2504635829944, 501.2504635829944, 503.2504635829944, 503.2504635829944, 504.53330629546906, 505.53330629546906, 507.0989917204183, 508.0989917204183, 508.0989917204183, 513.5132052827914, 519.3617334202153, 523.3617334202153, 525.3617334202153, 526.3617334202153, 526.3617334202153, 526.3617334202153, 526.3617334202153, 526.3617334202153, 526.3617334202153, 527.9274188451645, 528.9274188451645, 528.9274188451645, 528.9274188451645, 528.9274188451645, 528.9274188451645, 528.9274188451645, 528.9274188451645, 533.7759469825884, 537.7759469825884, 540.7759469825884, 542.7759469825884, 545.7759469825884, 547.7759469825884, 547.7759469825884, 547.7759469825884, 547.7759469825884, 547.7759469825884, 547.7759469825884, 549.3416324075376, 553.0386886823853, 559.3215313948599, 564.3215313948599, 572.4529022447584, 578.4529022447584, 579.4529022447584, 579.4529022447584, 586.7156439445554, 591.7156439445554, 594.7156439445554, 598.2813293695046, 600.2813293695046, 600.2813293695046, 600.2813293695046, 600.2813293695046, 600.2813293695046, 600.2813293695046, 606.6955429318778, 615.9783856443523, 620.9783856443523, 627.9783856443523, 629.9783856443523, 630.9783856443523, 630.9783856443523, 630.9783856443523, 630.9783856443523, 630.9783856443523, 630.9783856443523, 630.9783856443523, 632.8269137817762, 643.2411273441493, 651.2411273441493, 654.2411273441493, 656.2411273441493, 657.2411273441493, 657.2411273441493, 657.2411273441493, 657.2411273441493, 657.2411273441493, 662.0896554815731, 666.0896554815731, 676.0695544688955, 683.0695544688955, 694.8979815936417, 702.8979815936417, 705.8979815936417, 707.8979815936417, 714.5950378684894, 718.5950378684894, 718.5950378684894, 718.5950378684894, 718.5950378684894, 718.5950378684894, 718.5950378684894, 718.5950378684894, 718.5950378684894, 718.5950378684894, 718.5950378684894, 718.5950378684894, 718.5950378684894, 718.5950378684894, 718.5950378684894, 718.5950378684894, 718.5950378684894, 718.5950378684894, 718.5950378684894, 718.5950378684894, 718.5950378684894, 720.4435660059132, 727.7063077057102, 731.7063077057102, 734.7063077057102, 744.8175775429311, 750.8175775429311, 750.8175775429311, 750.8175775429311, 750.8175775429311, 750.8175775429311, 753.9489483928295, 755.9489483928295, 761.6460046676772, 772.6259036549995, 777.6259036549995, 777.6259036549995, 779.4744317924234, 780.4744317924234, 785.8886453547965, 794.7371734922203, 802.7371734922203, 807.5857016296442, 811.5857016296442, 814.5857016296442, 822.7170724795426, 830.8484433294411, 831.8484433294411, 833.9798141793397, 838.9798141793397, 842.9798141793397, 851.6567694415097, 855.6567694415097, 861.7881402914082, 865.7881402914082, 868.7881402914082, 870.7881402914082, 871.7881402914082, 871.7881402914082, 878.2023538537813, 883.2023538537813, 886.2023538537813, 892.4851965662559, 897.4851965662559, 897.4851965662559, 900.1822528411036, 901.1822528411036, 901.1822528411036, 901.1822528411036, 905.7479382660529, 909.7479382660529, 912.7479382660529, 914.7479382660529, 920.3136236910021, 924.3136236910021, 924.3136236910021, 932.424893528223, 937.424893528223, 937.424893528223, 940.5562643781215, 942.5562643781215, 942.5562643781215, 942.5562643781215, 947.4047925155453, 951.4047925155453, 951.4047925155453, 951.4047925155453, 957.3846915028677, 961.3846915028677, 964.3846915028677, 966.3846915028677, 967.3846915028677, 967.3846915028677, 972.5160623527662, 976.5160623527662, 979.5160623527662, 983.36459049019, 985.36459049019, 985.36459049019, 985.36459049019, 988.627332189987, 989.627332189987, 989.627332189987, 995.6072311773094, 999.6072311773094, 1002.6072311773094, 1004.6072311773094, 1005.6072311773094, 1005.6072311773094, 1005.6072311773094, 1005.6072311773094, 1005.6072311773094, 1005.6072311773094, 1010.4557593147332, 1014.4557593147332, 1017.4557593147332, 1019.4557593147332, 1020.4557593147332, 1020.4557593147332, 1020.4557593147332, 1030.152815589581, 1038.152815589581, 1038.152815589581, 1038.152815589581, 1038.152815589581, 1038.152815589581, 1048.6984000018524, 1056.6984000018524, 1062.6984000018524, 1066.6984000018524, 1068.6984000018524, 1068.6984000018524, 1074.9611417016495, 1078.9611417016495, 1078.9611417016495, 1078.9611417016495, 1083.243984414124, 1092.9410406889717, 1096.9410406889717, 1099.9410406889717, 1106.5067261139209, 1116.6380969638194, 1123.6380969638194, 1125.6380969638194, 1126.6380969638194, 1131.4866251012434, 1135.4866251012434, 1135.4866251012434, 1135.4866251012434, 1135.4866251012434, 1135.4866251012434, 1135.4866251012434, 1135.4866251012434, 1135.4866251012434, 1135.4866251012434, 1135.4866251012434, 1135.4866251012434, 1135.4866251012434, 1135.4866251012434, 1140.3351532386673, 1144.3351532386673, 1147.3351532386673, 1152.032209513515, 1156.1635803634135, 1157.1635803634135, 1157.1635803634135, 1157.1635803634135, 1157.1635803634135, 1157.1635803634135, 1157.1635803634135, 1157.1635803634135, 1163.5777939257866, 1173.1434793507358, 1181.9920074881597, 1192.2748502006343, 1199.2748502006343, 1200.2748502006343, 1200.2748502006343, 1200.2748502006343, 1200.2748502006343, 1200.2748502006343, 1200.2748502006343, 1205.4062210505328, 1209.4062210505328, 1212.4062210505328, 1214.4062210505328, 1215.4062210505328, 1215.4062210505328, 1216.6890637630074, 1217.6890637630074, 1217.6890637630074, 1217.6890637630074, 1217.6890637630074, 1217.6890637630074, 1217.6890637630074, 1221.971906475482, 1225.971906475482, 1225.971906475482, 1231.1032773253805, 1235.1032773253805, 1235.1032773253805, 1235.1032773253805, 1235.1032773253805, 1235.1032773253805, 1235.1032773253805, 1238.234648175279, 1240.234648175279, 1249.083176312703, 1256.083176312703, 1258.083176312703, 1259.083176312703, 1259.083176312703, 1260.3660190251776, 1261.3660190251776, 1261.3660190251776, 1261.3660190251776, 1261.3660190251776, 1261.3660190251776, 1261.3660190251776, 1261.3660190251776, 1265.6488617376522, 1269.6488617376522, 1274.7802325875507, 1284.1944461499238, 1298.4772888623984, 1306.4772888623984, 1317.0429742873475, 1331.174345137246, 1343.7400305621952, 1350.7400305621952, 1356.7400305621952, 1361.7400305621952, 1365.7400305621952, 1368.7400305621952, 1371.7400305621952, 1374.7400305621952, 1381.1542441245683, 1386.1542441245683, 1389.1542441245683, 1392.1542441245683, 1395.1542441245683, 1398.1542441245683, 1401.1542441245683, 1404.1542441245683, 1409.851300399416, 1413.851300399416, 1416.851300399416, 1419.851300399416, 1422.851300399416, 1425.851300399416, 1428.851300399416, 1437.6998285368397, 1445.6998285368397, 1451.6998285368397, 1456.6998285368397, 1460.6998285368397, 1463.6998285368397, 1466.6998285368397, 1472.3968848116874, 1476.3968848116874, 1479.3968848116874, 1488.3767837990097, 1500.7909973613828, 1511.7909973613828, 1521.7909973613828, 1529.7909973613828, 1538.4880536362305, 1543.4880536362305, 1546.4880536362305, 1552.4679526235527, 1556.4679526235527, 1559.4679526235527, 1567.5993234734512, 1574.5993234734512, 1580.5993234734512, 1585.5993234734512, 1589.5993234734512, 1592.5993234734512, 1597.7306943233498, 1601.7306943233498, 1604.7306943233498, 1607.7306943233498, 1615.0135370358244, 1622.0135370358244, 1625.0135370358244, 1628.0135370358244, 1632.296379748299, 1636.296379748299, 1639.296379748299, 1642.296379748299, 1645.296379748299, 1648.296379748299, 1651.296379748299, 1654.296379748299, 1657.296379748299, 1665.4277505981975, 1676.710593310672, 1691.8419641605706, 1703.8419641605706, 1709.8419641605706, 1716.5390204354183, 1724.5390204354183, 1731.5390204354183, 1742.3875485728422, 1754.6703912853168, 1761.6703912853168, 1764.6703912853168, 1767.6703912853168, 1770.6703912853168, 1773.6703912853168, 1776.6703912853168, 1781.236076710266, 1791.3674475601642, 1799.3674475601642, 1805.3674475601642, 1812.9331329851134, 1824.064503835012, 1831.064503835012, 1834.064503835012, 1837.064503835012, 1840.064503835012, 1843.064503835012, 1846.064503835012, 1854.478717397385, 1866.0444028223342, 1873.0444028223342, 1879.0444028223342, 1884.0444028223342, 1888.0444028223342, 1891.0444028223342, 1894.0444028223342, 1901.3272455348088, 1917.1757736722325, 1931.1757736722325, 1941.0243018096564, 1950.0243018096564, 1957.0243018096564, 1962.0243018096564, 1966.0243018096564, 1969.0243018096564, 1972.0243018096564, 1975.0243018096564, 1978.0243018096564, 1981.0243018096564, 1984.0243018096564, 1987.0243018096564, 1990.0243018096564, 1993.0243018096564, 1996.0243018096564, 1999.0243018096564, 2006.8728299470804, 2013.8728299470804, 2016.8728299470804, 2019.8728299470804, 2022.8728299470804, 2025.8728299470804, 2028.8728299470804, 2031.8728299470804, 2034.8728299470804, 2037.8728299470804, 2040.8728299470804, 2045.155672659555, 2049.155672659555, 2052.155672659555, 2055.155672659555, 2058.155672659555, 2061.155672659555, 2064.155672659555, 2067.155672659555, 2076.8527289344024, 2087.2669424967753, 2094.2669424967753, 2099.2669424967753, 2103.2669424967753, 2106.2669424967753, 2109.2669424967753, 2116.54978520925, 2123.54978520925, 2129.54978520925, 2134.54978520925, 2141.9639987716228, 2146.9639987716228, 2155.9438977589452, 2162.9438977589452, 2173.4894821712164, 2181.4894821712164, 2187.4894821712164, 2192.4894821712164, 2200.752223871013, 2211.0350665834876, 2219.0350665834876, 2225.0350665834876, 2230.0350665834876, 2234.0350665834876, 2241.8835947209113, 2250.732122858335, 2254.732122858335, 2257.732122858335, 2260.732122858335, 2263.732122858335, 2266.732122858335, 2271.297808283284, 2275.297808283284, 2278.297808283284, 2281.297808283284, 2284.297808283284, 2292.409078120505, 2297.409078120505, 2300.409078120505, 2303.409078120505, 2306.409078120505, 2309.409078120505, 2312.409078120505, 2315.409078120505, 2324.823291682878, 2332.823291682878, 2338.823291682878, 2345.1061343953525, 2350.1061343953525, 2353.1061343953525, 2361.5203479577253, 2368.5203479577253, 2371.5203479577253, 2374.5203479577253, 2379.368876095149, 2384.934561520098, 2388.934561520098, 2391.934561520098, 2394.934561520098, 2397.934561520098, 2400.934561520098, 2403.934561520098, 2406.934561520098, 2409.934561520098, 2412.934561520098, 2416.934561520098, 2420.934561520098, 2423.934561520098, 2426.934561520098, 2429.934561520098, 2432.934561520098, 2435.934561520098, 2438.934561520098, 2441.934561520098, 2444.934561520098, 2447.934561520098, 2450.934561520098, 2455.783089657522, 2459.783089657522, 2468.348775082471, 2476.348775082471, 2483.348775082471, 2488.348775082471, 2492.348775082471, 2495.348775082471, 2502.6316177949457, 2509.6316177949457, 2515.6316177949457, 2520.6316177949457, 2524.6316177949457, 2527.6316177949457, 2537.6115167822677, 2545.6115167822677, 2548.6115167822677, 2551.6115167822677, 2554.6115167822677, 2557.6115167822677, 2560.6115167822677, 2567.8943594947423, 2574.8943594947423, 2580.8943594947423, 2585.8943594947423, 2593.8943594947423, 2600.8943594947423, 2606.8943594947423, 2611.8943594947423, 2615.8943594947423, 2618.8943594947423, 2624.308573057115, 2628.308573057115, 2632.308573057115, 2641.005629331963, 2648.005629331963, 2651.005629331963, 2654.005629331963, 2657.005629331963, 2660.005629331963, 2663.005629331963, 2666.005629331963, 2678.702685606811, 2689.702685606811, 2698.702685606811, 2705.702685606811, 2710.702685606811, 2713.702685606811, 2717.9855283192855, 2721.9855283192855, 2724.9855283192855, 2727.9855283192855, 2730.9855283192855, 2733.9855283192855, 2736.9855283192855, 2739.9855283192855, 2748.965427306608, 2755.965427306608, 2758.965427306608, 2761.965427306608, 2764.965427306608, 2767.965427306608, 2780.379640868981, 2791.379640868981, 2800.379640868981, 2807.379640868981, 2812.379640868981, 2815.379640868981, 2818.379640868981, 2821.379640868981, 2824.379640868981, 2828.6624835814555, 2838.3595398563034, 2850.3595398563034, 2861.0565961311513, 2868.0565961311513, 2873.0565961311513, 2877.0565961311513, 2880.0565961311513, 2883.0565961311513, 2891.753652405999, 2900.3193378309484, 2904.3193378309484, 2907.3193378309484, 2910.3193378309484, 2917.602180543423, 2926.4507086808467, 2933.4507086808467, 2938.4507086808467, 2942.4507086808467, 2945.4507086808467, 2951.582079530745, 2960.8649222432196, 2967.8649222432196, 2973.8649222432196, 2980.147764955694, 2990.996293093118, 2999.996293093118, 3002.996293093118, 3005.996293093118, 3008.996293093118, 3011.996293093118, 3014.996293093118, 3017.996293093118, 3020.996293093118, 3023.996293093118, 3026.996293093118, 3029.996293093118, 3032.996293093118, 3035.996293093118, 3041.4105066554907, 3045.4105066554907, 3048.4105066554907, 3055.97619208044, 3062.97619208044, 3065.97619208044, 3068.97619208044, 3071.97619208044, 3074.97619208044, 3077.97619208044, 3080.97619208044, 3083.97619208044, 3086.97619208044, 3095.107562930338, 3102.107562930338, 3105.107562930338, 3115.3703046301353, 3123.3703046301353, 3132.5016754800336, 3145.1987317548815, 3153.1987317548815, 3161.3301026047798, 3167.3301026047798, 3171.3301026047798, 3174.3301026047798, 3177.3301026047798, 3180.3301026047798, 3185.461473454678, 3189.461473454678, 3192.461473454678, 3196.7443161671526, 3200.7443161671526, 3203.7443161671526, 3206.7443161671526, 3209.7443161671526, 3212.7443161671526, 3220.027158879627, 3227.027158879627, 3237.5928443045764, 3246.5928443045764, 3250.5928443045764, 3253.5928443045764, 3256.5928443045764, 3259.5928443045764, 3262.5928443045764, 3265.5928443045764, 3271.572743291899, 3280.1183277041705, 3289.1183277041705, 3292.1183277041705, 3295.1183277041705, 3298.1183277041705, 3301.1183277041705, 3314.0982266914925, 3325.0982266914925, 3328.0982266914925, 3331.0982266914925, 3334.0982266914925, 3337.0982266914925, 3340.0982266914925, 3343.0982266914925, 3346.0982266914925, 3349.0982266914925, 3352.0982266914925, 3355.0982266914925, 3360.6639121164417, 3375.0781256788146, 3386.0781256788146, 3394.0781256788146, 3398.0781256788146, 3404.058024666137, 3408.058024666137, 3411.058024666137, 3414.058024666137, 3417.058024666137, 3420.058024666137, 3423.058024666137, 3426.058024666137, 3429.058024666137, 3432.058024666137, 3435.058024666137, 3438.058024666137, 3442.3408673786116, 3446.3408673786116, 3449.3408673786116, 3452.3408673786116, 3455.3408673786116, 3458.3408673786116, 3461.3408673786116, 3464.3408673786116, 3472.169294503358, 3480.300665353256, 3485.300665353256, 3488.300665353256, 3491.300665353256, 3494.300665353256, 3497.300665353256, 3500.300665353256, 3503.300665353256, 3506.300665353256, 3509.300665353256, 3512.300665353256, 3515.300665353256, 3518.300665353256, 3521.300665353256, 3524.300665353256, 3527.300665353256, 3530.300665353256, 3535.4320362031544, 3539.4320362031544, 3542.4320362031544, 3545.4320362031544, 3548.4320362031544, 3552.4320362031544, 3556.4320362031544, 3568.280564340578, 3584.4119351904765, 3594.4119351904765, 3601.2604633279, 3606.2604633279, 3609.2604633279, 3612.2604633279, 3615.2604633279, 3621.9575196027477, 3626.9575196027477, 3635.3717331651205, 3642.3717331651205, 3645.3717331651205, 3648.3717331651205, 3651.3717331651205, 3654.3717331651205, 3657.3717331651205, 3660.3717331651205, 3663.3717331651205, 3666.3717331651205, 3671.2202613025443, 3680.917317577392, 3687.917317577392, 3695.765845714816, 3701.765845714816, 3715.180059277189, 3731.745744702138] import matplotlib.pyplot as plt li = [i for i in range(len(distance))] plt.plot(li, distance, label='Distance Base') plt.plot(li, roundRobin, label='Round Robin') plt.plot(li, FirstCome, label='First Come First Server') plt.plot(li, pyhop, label='Pyhop') plt.xlabel("Time steps") plt.ylabel("Cost") plt.title("Cost Vs Time Steps") plt.legend() plt.show() import numpy as np # import matplotlib.pyplot as plt X = ['3 Robots', '4 Robots', '5 Robots', '6 Robots'] distance = [2290.1439807982006, 2242.1826796282726, 2274.031678518063, 2168.7104115175152] roundRobin = [2241.096092444879, 2371.119756239161, 2435.091329114414, 2357.072207802119] pyhop = [2003.1915589742046, 1892.5727393379932, 1889.7037295767773, 1872.548451714578] Firstcome = [4331.745744702138, 3731.745744702138, 2391.2428009769897, 2357.072207802119] X_axis = np.arange(len(X)) plt.bar(X_axis - 0.1, distance, 0.2, label='Distance Based') plt.bar(X_axis + 0.1, roundRobin, 0.2, label='Round Robin') plt.bar(X_axis - 0.3, pyhop, 0.2, label='PyHop') plt.bar(X_axis + 0.3, Firstcome, 0.2, label='First Come First Server') plt.xticks(X_axis, X) plt.xlabel("Variation in number of robots") plt.ylabel("Cost") plt.title("Cost Vs number of robots") plt.legend() plt.show() X = ['5 locations', '10 locations', '15 locations', '20 locations'] distance = [1847.3534394662329, 2294.6333887619035, 2328.0509248095495, 2232.0022212133536] roundRobin = [2539.7696172384094, 2683.1754192014014, 2886.643806978103, 2528.0148361989877] pyhop = [2047.8957551738933, 2182.5191235603843, 2224.1545552666034, 2111.0250050685286] Firstcome = [2856.524596262794, 5067.289441340767, 3882.6008198105524, 3436.365701988792] X_axis = np.arange(len(X)) plt.bar(X_axis - 0.1, distance, 0.2, label='Distance Based') plt.bar(X_axis + 0.1, roundRobin, 0.2, label='Round Robin') plt.bar(X_axis - 0.3, pyhop, 0.2, label='PyHop') plt.bar(X_axis + 0.3, Firstcome, 0.2, label='First Come First Server') plt.xticks(X_axis, X) plt.xlabel("Variation in number of locations") plt.ylabel("Cost") plt.title("Cost Vs number of locations") plt.legend() plt.show()
1,228.338462
19,506
0.842702
bc0f6edd6bee87e7193ce2de511e7a0d7a76f97f
31,813
py
Python
package_control/providers/repository_provider.py
Shekharrajak/my_sublime_packages
4627b7faa47b0b03578c339fb5081be9d92867a6
[ "Unlicense", "MIT" ]
1
2018-06-23T08:07:39.000Z
2018-06-23T08:07:39.000Z
package_control/providers/repository_provider.py
Shekharrajak/my_sublime_packages
4627b7faa47b0b03578c339fb5081be9d92867a6
[ "Unlicense", "MIT" ]
null
null
null
package_control/providers/repository_provider.py
Shekharrajak/my_sublime_packages
4627b7faa47b0b03578c339fb5081be9d92867a6
[ "Unlicense", "MIT" ]
null
null
null
import json import re import os from itertools import chain try: # Python 3 from urllib.parse import urljoin, urlparse str_cls = str except (ImportError): # Python 2 from urlparse import urljoin, urlparse str_cls = unicode from ..console_write import console_write from .provider_exception import ProviderException from .schema_compat import platforms_to_releases from ..downloaders.downloader_exception import DownloaderException from ..clients.client_exception import ClientException from ..clients.github_client import GitHubClient from ..clients.bitbucket_client import BitBucketClient from ..download_manager import downloader, update_url from ..versions import version_sort class RepositoryProvider(): """ Generic repository downloader that fetches package info With the current channel/repository architecture where the channel file caches info from all includes repositories, these package providers just serve the purpose of downloading packages not in the default channel. The structure of the JSON a repository should contain is located in example-packages.json. :param repo: The URL of the package repository :param settings: A dict containing at least the following fields: `cache_length`, `debug`, `timeout`, `user_agent` Optional fields: `http_proxy`, `https_proxy`, `proxy_username`, `proxy_password`, `query_string_params` """ def __init__(self, repo, settings): self.cache = {} self.repo_info = None self.schema_version = '0.0' self.schema_major_version = 0 self.repo = repo self.settings = settings self.failed_sources = {} self.broken_packages = {} self.broken_dependencies = {} @classmethod def match_url(cls, repo): """Indicates if this provider can handle the provided repo""" return True def prefetch(self): """ Go out and perform HTTP operations, caching the result :raises: DownloaderException: when there is an issue download package info ClientException: when there is an issue parsing package info """ [name for name, info in self.get_packages()] def get_failed_sources(self): """ List of any URLs that could not be accessed while accessing this repository :return: A generator of ("https://example.com", Exception()) tuples """ return self.failed_sources.items() def get_broken_packages(self): """ List of package names for packages that are missing information :return: A generator of ("Package Name", Exception()) tuples """ return self.broken_packages.items() def get_broken_dependencies(self): """ List of dependency names for dependencies that are missing information :return: A generator of ("Dependency Name", Exception()) tuples """ return self.broken_dependencies.items() def fetch(self): """ Retrieves and loads the JSON for other methods to use :raises: ProviderException: when an error occurs trying to open a file DownloaderException: when an error occurs trying to open a URL """ if self.repo_info is not None: return self.repo_info = self.fetch_location(self.repo) for key in ['packages', 'dependencies']: if key not in self.repo_info: self.repo_info[key] = [] if 'includes' not in self.repo_info: return # Allow repositories to include other repositories if re.match('https?://', self.repo, re.I) is None: relative_base = os.path.dirname(self.repo) is_http = False else: is_http = True includes = self.repo_info.get('includes', []) del self.repo_info['includes'] for include in includes: if re.match('^\./|\.\./', include): if is_http: include = urljoin(self.repo, include) else: include = os.path.join(relative_base, include) include = os.path.normpath(include) include_info = self.fetch_location(include) included_packages = include_info.get('packages', []) self.repo_info['packages'].extend(included_packages) included_dependencies = include_info.get('dependencies', []) self.repo_info['dependencies'].extend(included_dependencies) def fetch_and_validate(self): """ Fetch the repository and validates that it is parse-able :return: Boolean if the repo was fetched and validated """ if self.repo in self.failed_sources: return False if self.repo_info is not None: return True try: self.fetch() except (DownloaderException, ProviderException) as e: self.failed_sources[self.repo] = e self.cache['get_packages'] = {} return False def fail(message): exception = ProviderException(message) self.failed_sources[self.repo] = exception self.cache['get_packages'] = {} return schema_error = u'Repository %s does not appear to be a valid repository file because ' % self.repo if 'schema_version' not in self.repo_info: error_string = u'%s the "schema_version" JSON key is missing.' % schema_error fail(error_string) return False try: self.schema_version = self.repo_info.get('schema_version') if isinstance(self.schema_version, int): self.schema_version = float(self.schema_version) if isinstance(self.schema_version, float): self.schema_version = str_cls(self.schema_version) except (ValueError): error_string = u'%s the "schema_version" is not a valid number.' % schema_error fail(error_string) return False if self.schema_version not in ['1.0', '1.1', '1.2', '2.0', '3.0.0']: error_string = u'%s the "schema_version" is not recognized. Must be one of: 1.0, 1.1, 1.2, 2.0 or 3.0.0.' % schema_error fail(error_string) return False version_parts = self.schema_version.split('.') self.schema_major_version = int(version_parts[0]) if 'packages' not in self.repo_info: error_string = u'%s the "packages" JSON key is missing.' % schema_error fail(error_string) return False if isinstance(self.repo_info['packages'], dict): error_string = u'%s the "packages" key is an object, not an array. This indicates it is a channel not a repository.' % schema_error fail(error_string) return False return True def fetch_location(self, location): """ Fetches the contents of a URL of file path :param location: The URL or file path :raises: ProviderException: when an error occurs trying to open a file DownloaderException: when an error occurs trying to open a URL :return: A dict of the parsed JSON """ if re.match('https?://', self.repo, re.I): with downloader(location, self.settings) as manager: json_string = manager.fetch(location, 'Error downloading repository.') # Anything that is not a URL is expected to be a filesystem path else: if not os.path.exists(location): raise ProviderException(u'Error, file %s does not exist' % location) if self.settings.get('debug'): console_write( u''' Loading %s as a repository ''', location ) # We open as binary so we get bytes like the DownloadManager with open(location, 'rb') as f: json_string = f.read() try: return json.loads(json_string.decode('utf-8')) except (ValueError): raise ProviderException(u'Error parsing JSON from repository %s.' % location) def get_dependencies(self, invalid_sources=None): """ Provides access to the dependencies in this repository :param invalid_sources: A list of URLs that are permissible to fetch data from :raises: ProviderException: when an error occurs trying to open a file DownloaderException: when there is an issue download package info ClientException: when there is an issue parsing package info :return: A generator of ( 'Dependency Name', { 'name': name, 'load_order': two digit string, 'description': description, 'author': author, 'issues': URL, 'releases': [ { 'sublime_text': compatible version, 'platforms': [platform name, ...], 'url': url, 'version': version, 'sha256': hex hash }, ... ], 'sources': [url, ...] } ) tuples """ if 'get_dependencies' in self.cache: for key, value in self.cache['get_dependencies'].items(): yield (key, value) return if invalid_sources is not None and self.repo in invalid_sources: raise StopIteration() if not self.fetch_and_validate(): return debug = self.settings.get('debug') github_client = GitHubClient(self.settings) bitbucket_client = BitBucketClient(self.settings) if self.schema_major_version < 3: self.repo_info['dependencies'] = [] output = {} for dependency in self.repo_info['dependencies']: info = { 'sources': [self.repo] } for field in ['name', 'description', 'author', 'issues', 'load_order']: if dependency.get(field): info[field] = dependency.get(field) if 'name' not in info: self.failed_sources[self.repo] = ProviderException(u'No "name" value for one of the dependencies in the repository %s.' % self.repo) continue releases = dependency.get('releases', []) if releases and not isinstance(releases, list): self.broken_dependencies[info['name']] = ProviderException(u'The "releases" value is not an array for the dependency "%s" in the repository %s.' % (info['name'], self.repo)) continue for release in releases: if 'releases' not in info: info['releases'] = [] download_info = {} # Make sure that explicit fields are copied over for field in ['platforms', 'sublime_text', 'version', 'url', 'sha256']: if field in release: value = release[field] if field == 'url': value = update_url(value, debug) if field == 'platforms' and not isinstance(release['platforms'], list): value = [value] download_info[field] = value if 'platforms' not in download_info: download_info['platforms'] = ['*'] tags = release.get('tags') branch = release.get('branch') if tags or branch: try: base = None if 'base' in release: base = release['base'] if not base: raise ProviderException(u'Missing release-level "base" key for one of the releases of the dependency "%s" in the repository %s.' % (info['name'], self.repo)) github_url = False bitbucket_url = False extra = None if tags: github_url = github_client.make_tags_url(base) bitbucket_url = bitbucket_client.make_tags_url(base) if tags is not True: extra = tags if branch: github_url = github_client.make_branch_url(base, branch) bitbucket_url = bitbucket_client.make_branch_url(base, branch) if github_url: downloads = github_client.download_info(github_url, extra) url = github_url elif bitbucket_url: downloads = bitbucket_client.download_info(bitbucket_url, extra) url = bitbucket_url else: raise ProviderException(u'Invalid "base" value "%s" for one of the releases of the dependency "%s" in the repository %s.' % (base, info['name'], self.repo)) if downloads is False: raise ProviderException(u'No valid semver tags found at %s for the dependency "%s" in the repository %s.' % (url, info['name'], self.repo)) for download in downloads: del download['date'] new_download = download_info.copy() new_download.update(download) info['releases'].append(new_download) except (DownloaderException, ClientException, ProviderException) as e: self.broken_dependencies[info['name']] = e continue elif download_info: if 'url' in download_info: is_http = urlparse(download_info['url']).scheme == 'http' if is_http and 'sha256' not in download_info: self.broken_dependencies[info['name']] = ProviderException(u'No "sha256" key for the non-secure "url" value in one of the releases of the dependency "%s" in the repository %s.' % (info['name'], self.repo)) continue info['releases'].append(download_info) if info['name'] in self.broken_dependencies: continue # Make sure the dependency has the appropriate keys. We use a # function here so that we can break out of multiple loops. def is_missing_keys(): for key in ['author', 'releases', 'issues', 'description', 'load_order']: if key not in info: self.broken_dependencies[info['name']] = ProviderException(u'No "%s" key for the dependency "%s" in the repository %s.' % (key, info['name'], self.repo)) return True for release in info.get('releases', []): for key in ['version', 'url', 'sublime_text', 'platforms']: if key not in release: self.broken_dependencies[info['name']] = ProviderException(u'Missing "%s" key for one of the releases of the dependency "%s" in the repository %s.' % (key, info['name'], self.repo)) return True return False if is_missing_keys(): continue info['releases'] = version_sort(info['releases'], 'platforms', reverse=True) output[info['name']] = info yield (info['name'], info) self.cache['get_dependencies'] = output def get_packages(self, invalid_sources=None): """ Provides access to the packages in this repository :param invalid_sources: A list of URLs that are permissible to fetch data from :raises: ProviderException: when an error occurs trying to open a file DownloaderException: when there is an issue download package info ClientException: when there is an issue parsing package info :return: A generator of ( 'Package Name', { 'name': name, 'description': description, 'author': author, 'homepage': homepage, 'last_modified': last modified date, 'releases': [ { 'sublime_text': compatible version, 'platforms': [platform name, ...], 'url': url, 'date': date, 'version': version, 'dependencies': [dependency name, ...] }, ... ] 'previous_names': [old_name, ...], 'labels': [label, ...], 'sources': [url, ...], 'readme': url, 'issues': url, 'donate': url, 'buy': url } ) tuples """ if 'get_packages' in self.cache: for key, value in self.cache['get_packages'].items(): yield (key, value) return if invalid_sources is not None and self.repo in invalid_sources: raise StopIteration() if not self.fetch_and_validate(): return debug = self.settings.get('debug') github_client = GitHubClient(self.settings) bitbucket_client = BitBucketClient(self.settings) # Backfill the "previous_names" keys for old schemas previous_names = {} if self.schema_major_version < 2: renamed = self.get_renamed_packages() for old_name in renamed: new_name = renamed[old_name] if new_name not in previous_names: previous_names[new_name] = [] previous_names[new_name].append(old_name) output = {} for package in self.repo_info['packages']: info = { 'sources': [self.repo] } for field in ['name', 'description', 'author', 'last_modified', 'previous_names', 'labels', 'homepage', 'readme', 'issues', 'donate', 'buy']: if package.get(field): info[field] = package.get(field) # Schema version 2.0 allows for grabbing details about a package, or its # download from "details" urls. See the GitHubClient and BitBucketClient # classes for valid URLs. if self.schema_major_version >= 2: details = package.get('details') releases = package.get('releases') # Try to grab package-level details from GitHub or BitBucket if details: if invalid_sources is not None and details in invalid_sources: continue info['sources'].append(details) try: github_repo_info = github_client.repo_info(details) bitbucket_repo_info = bitbucket_client.repo_info(details) # When grabbing details, prefer explicit field values over the values # from the GitHub or BitBucket API if github_repo_info: info = dict(chain(github_repo_info.items(), info.items())) elif bitbucket_repo_info: info = dict(chain(bitbucket_repo_info.items(), info.items())) else: raise ProviderException(u'Invalid "details" value "%s" for one of the packages in the repository %s.' % (details, self.repo)) except (DownloaderException, ClientException, ProviderException) as e: if 'name' in info: self.broken_packages[info['name']] = e self.failed_sources[details] = e continue if 'name' not in info: self.failed_sources[self.repo] = ProviderException(u'No "name" value for one of the packages in the repository %s.' % self.repo) continue info['releases'] = [] if self.schema_major_version == 2: # If no releases info was specified, also grab the download info from GH or BB if not releases and details: releases = [{'details': details}] if self.schema_major_version >= 2: if not releases: e = ProviderException(u'No "releases" value for the package "%s" in the repository %s.' % (info['name'], self.repo)) self.broken_packages[info['name']] = e continue if not isinstance(releases, list): e = ProviderException(u'The "releases" value is not an array or the package "%s" in the repository %s.' % (info['name'], self.repo)) self.broken_packages[info['name']] = e continue # This allows developers to specify a GH or BB location to get releases from, # especially tags URLs (https://github.com/user/repo/tags or # https://bitbucket.org/user/repo#tags) for release in releases: download_details = None download_info = {} # Make sure that explicit fields are copied over for field in ['platforms', 'sublime_text', 'version', 'url', 'date', 'dependencies']: if field in release: value = release[field] if field == 'url': value = update_url(value, debug) if field == 'platforms' and not isinstance(release['platforms'], list): value = [value] download_info[field] = value if 'platforms' not in download_info: download_info['platforms'] = ['*'] if self.schema_major_version == 2: if 'sublime_text' not in download_info: download_info['sublime_text'] = '<3000' if 'details' in release: download_details = release['details'] try: github_downloads = github_client.download_info(download_details) bitbucket_downloads = bitbucket_client.download_info(download_details) if github_downloads is False or bitbucket_downloads is False: raise ProviderException(u'No valid semver tags found at %s for the package "%s" in the repository %s.' % (download_details, info['name'], self.repo)) if github_downloads: downloads = github_downloads elif bitbucket_downloads: downloads = bitbucket_downloads else: raise ProviderException(u'Invalid "details" value "%s" under the "releases" key for the package "%s" in the repository %s.' % (download_details, info['name'], self.repo)) for download in downloads: new_download = download_info.copy() new_download.update(download) info['releases'].append(new_download) except (DownloaderException, ClientException, ProviderException) as e: self.broken_packages[info['name']] = e elif download_info: info['releases'].append(download_info) elif self.schema_major_version == 3: tags = release.get('tags') branch = release.get('branch') if tags or branch: try: base = None if 'base' in release: base = release['base'] elif details: base = details if not base: raise ProviderException(u'Missing root-level "details" key, or release-level "base" key for one of the releases of the package "%s" in the repository %s.' % (info['name'], self.repo)) github_url = False bitbucket_url = False extra = None if tags: github_url = github_client.make_tags_url(base) bitbucket_url = bitbucket_client.make_tags_url(base) if tags is not True: extra = tags if branch: github_url = github_client.make_branch_url(base, branch) bitbucket_url = bitbucket_client.make_branch_url(base, branch) if github_url: downloads = github_client.download_info(github_url, extra) url = github_url elif bitbucket_url: downloads = bitbucket_client.download_info(bitbucket_url, extra) url = bitbucket_url else: raise ProviderException(u'Invalid "base" value "%s" for one of the releases of the package "%s" in the repository %s.' % (base, info['name'], self.repo)) if downloads is False: raise ProviderException(u'No valid semver tags found at %s for the package "%s" in the repository %s.' % (url, info['name'], self.repo)) for download in downloads: new_download = download_info.copy() new_download.update(download) info['releases'].append(new_download) except (DownloaderException, ClientException, ProviderException) as e: self.broken_packages[info['name']] = e continue elif download_info: info['releases'].append(download_info) # Schema version 1.0, 1.1 and 1.2 just require that all values be # explicitly specified in the package JSON else: info['releases'] = platforms_to_releases(package, debug) info['releases'] = version_sort(info['releases'], 'platforms', reverse=True) if info['name'] in self.broken_packages: continue if 'author' not in info: self.broken_packages[info['name']] = ProviderException(u'No "author" key for the package "%s" in the repository %s.' % (info['name'], self.repo)) continue if 'releases' not in info: self.broken_packages[info['name']] = ProviderException(u'No "releases" key for the package "%s" in the repository %s.' % (info['name'], self.repo)) continue # Make sure all releases have the appropriate keys. We use a # function here so that we can break out of multiple loops. def has_broken_release(): for release in info.get('releases', []): for key in ['version', 'date', 'url', 'sublime_text', 'platforms']: if key not in release: self.broken_packages[info['name']] = ProviderException(u'Missing "%s" key for one of the releases of the package "%s" in the repository %s.' % (key, info['name'], self.repo)) return True return False if has_broken_release(): continue for field in ['previous_names', 'labels']: if field not in info: info[field] = [] if 'readme' in info: info['readme'] = update_url(info['readme'], debug) for field in ['description', 'readme', 'issues', 'donate', 'buy']: if field not in info: info[field] = None if 'homepage' not in info: info['homepage'] = self.repo if 'releases' in info and 'last_modified' not in info: # Extract a date from the newest release date = '1970-01-01 00:00:00' for release in info['releases']: if 'date' in release and release['date'] > date: date = release['date'] info['last_modified'] = date if info['name'] in previous_names: info['previous_names'].extend(previous_names[info['name']]) output[info['name']] = info yield (info['name'], info) self.cache['get_packages'] = output def get_sources(self): """ Return a list of current URLs that are directly referenced by the repo :return: A list of URLs and/or file paths """ if not self.fetch_and_validate(): return [] output = [self.repo] if self.schema_major_version >= 2: for package in self.repo_info['packages']: details = package.get('details') if details: output.append(details) return output def get_renamed_packages(self): """:return: A dict of the packages that have been renamed""" if not self.fetch_and_validate(): return {} if self.schema_major_version < 2: return self.repo_info.get('renamed_packages', {}) output = {} for package in self.repo_info['packages']: if 'previous_names' not in package: continue previous_names = package['previous_names'] if not isinstance(previous_names, list): previous_names = [previous_names] for previous_name in previous_names: output[previous_name] = package['name'] return output
40.785897
233
0.517933
cfc41cb88ff439bbcc7cbe3715dc377e004f769b
526
py
Python
pyqtlet/leaflet/layer/tile/tilelayer.py
samhattangady/pyqtlet
2242f63b0dce6dd6357aaa0c6fe23a991451bfdd
[ "BSD-2-Clause-FreeBSD" ]
30
2018-05-24T17:38:11.000Z
2021-11-02T19:34:03.000Z
pyqtlet/leaflet/layer/tile/tilelayer.py
samhattangady/pyqtlet
2242f63b0dce6dd6357aaa0c6fe23a991451bfdd
[ "BSD-2-Clause-FreeBSD" ]
27
2018-02-21T07:22:11.000Z
2021-10-12T06:24:18.000Z
pyqtlet/leaflet/layer/tile/tilelayer.py
samhattangady/pyqtlet
2242f63b0dce6dd6357aaa0c6fe23a991451bfdd
[ "BSD-2-Clause-FreeBSD" ]
9
2018-06-11T06:50:44.000Z
2021-05-17T15:26:26.000Z
from . import GridLayer class TileLayer(GridLayer): def __init__(self, urlTemplate, options=None): super().__init__() self.urlTemplate = urlTemplate self.options = options self._initJs() def _initJs(self): leafletJsObject = 'L.tileLayer("{urlTemplate}"'.format(urlTemplate=self.urlTemplate) if self.options: leafletJsObject += ', {options}'.format(options=self.options) leafletJsObject += ')' self._createJsObject(leafletJsObject)
30.941176
92
0.640684
e8bc7e2e793de248bb5a7cebfd827ea4916c747e
4,345
py
Python
pybin/crawler.py
Sea-n/GPE-Helper
4e5d51f57ace01361ac852887ac4cc1aed880885
[ "MIT" ]
1
2021-12-08T14:47:00.000Z
2021-12-08T14:47:00.000Z
pybin/crawler.py
Sea-n/GPE-Helper
4e5d51f57ace01361ac852887ac4cc1aed880885
[ "MIT" ]
null
null
null
pybin/crawler.py
Sea-n/GPE-Helper
4e5d51f57ace01361ac852887ac4cc1aed880885
[ "MIT" ]
null
null
null
import requests import click import datetime import logging import json from bs4 import BeautifulSoup logging.basicConfig(level=logging.INFO, format='[*] %(asctime)s %(levelname)s: %(message)s', datefmt="%Y-%m-%d %H:%M:%S") # necessary cookie cookies = {} def parseCid(startY, endY, cookies): r = requests.get( "http://gpe3.acm-icpc.tw/onlinecontests.php?inactive=&tab=", cookies=cookies) soup = BeautifulSoup(r.text, "html.parser") table = soup.find('table', {'class': 'list sortable'}) # bypass first row trs = table.find_all('tr')[1:] # store the cids & exams information rows = {} # parse all cid for tr in trs: # store per exam information row = {} # Parse the examInfo examInfo = tr.find_all('td') # time, Name, cid examTime = examInfo[0].text.strip() examTimeStamp = datetime.datetime.strptime( examTime, "%Y-%m-%d").timestamp() examYear = int(examTime.split('-')[0]) examName = examInfo[4].text.strip() cid = int(examInfo[4].find_all('a')[0]['href'].split('cid=')[1]) if (examYear >= startY and examYear <= endY): # append to rows list row['timestamp'] = examTimeStamp row['examTime'] = examTime row['examName'] = examName rows[cid] = row return rows def parseExam(cid): logging.info('Crawling cid: %d exam', cid) url = "http://gpe3.acm-icpc.tw/problemlist.php?tab=&onlinetest=&cid={}".format( cid) r = requests.get(url, cookies=cookies) soup = BeautifulSoup(r.text, "html.parser") table = soup.find('table', {'class': 'sortable'}) # bypass first row trs = table.find_all('tr')[1:] # store the cids & exams information problems = [] # parse each problem for tr in trs: # store per exam information problem = {} # Parse the problem problemInfo = tr.find_all('td') problemInfoId = problemInfo[4].find_all('a')[0]['href'].split('&id=')[ 1] # problem id 有可能為 string...所以不轉型 problemName = problemInfoId + ': ' + \ problemInfo[0].text.strip().split( ':')[1].lstrip() # linter for error data problemSubs = int(problemInfo[1].text.strip()) problemACs = int(problemInfo[4].text.strip()) problemAcceptRate = float(problemInfo[2].text.strip()) problemOnSite = int(problemInfo[7].text.strip()) problemAccess = int(problemInfo[8].text.strip()) # append to rows list problem['pid'] = problemInfoId problem['name'] = problemName problem['subs'] = problemSubs problem['ACs'] = problemACs problem['AcceptRate'] = problemAcceptRate problem['onsite'] = problemOnSite problem['access'] = problemAccess problems.append(problem) return problems @click.command() @click.option('-s', '--startY', 'startY', help='crawler start year', type=int, default=2017, show_default=True) @click.option('-e', '--endY', 'endY', help='crawler end year', type=int, default=datetime.datetime.now().year, show_default=True) @click.option('-c', '--cookie', 'cookie', help='For crawling http://gpe3.acm-icpc.tw necessary cookie, please login first and get the ACMICPCTW cookie value', type=str, required=True) @click.option('-f', '--filename', 'filename', help='customized dump filename', type=str, default="exams.json", show_default=True) def main(startY, endY, cookie, filename): # input year validate if (startY > datetime.datetime.now().year or endY > datetime.datetime.now().year or endY < startY): raise click.UsageError( "Invalid year range from {} to {}".format(startY, endY)) logging.info('Parse the cid from %d to %d', startY, endY) # necessary cookies cookies['ACMICPCTW'] = cookie # Parse cid data = parseCid(startY, endY, cookies) logging.info('Parse cids successfully, total of %d exams', len(data)) # Parse each exam information for key in data: data[key]['problems'] = parseExam(key) # write file with open(filename, 'w') as outfile: json.dump(data, outfile, indent=4) logging.info('Write to file %s successfully', filename) if __name__ == '__main__': main()
33.423077
183
0.61542
98e5a82d6ff2a772163830a775e8748f40e77c06
9,515
py
Python
vis_imagine_static_voxels/lib/modules/try.py
mihirp1998/EmbLang
169b0468ccda554896973bcc226afb3e762a70e7
[ "Apache-2.0" ]
3
2020-07-12T02:15:27.000Z
2021-07-18T06:00:49.000Z
vis_imagine_static_voxels/lib/modules/try.py
mihirp1998/EmbLang
169b0468ccda554896973bcc226afb3e762a70e7
[ "Apache-2.0" ]
1
2021-07-18T06:00:10.000Z
2021-07-24T11:51:17.000Z
vis_imagine_static_voxels/lib/modules/try.py
mihirp1998/EmbLang
169b0468ccda554896973bcc226afb3e762a70e7
[ "Apache-2.0" ]
null
null
null
import tensorflow as tf import torch import cv2 import numpy as np import torch.nn.functional as F from tensorflow.keras import backend as K def _transform(X, affine_transformation, output_size): batch_size, num_channels = K.shape(X)[0], K.shape(X)[3] transformations = K.reshape(affine_transformation, shape=(batch_size, 2, 3)) regular_grids = _make_regular_grids(batch_size, *output_size) sampled_grids = K.batch_dot(transformations, regular_grids) interpolated_image = _interpolate(X, sampled_grids, output_size) new_shape = (batch_size, output_size[0], output_size[1], num_channels) interpolated_image = K.reshape(interpolated_image, new_shape) return interpolated_image def _make_regular_grids(batch_size, height, width): # making a single regular grid x_linspace = np.linspace(-1., 1., width) y_linspace = np.linspace(-1., 1., height) x_coordinates, y_coordinates = np.meshgrid(x_linspace,y_linspace) x_coordinates = K.flatten(x_coordinates) y_coordinates = K.flatten(y_coordinates) ones = K.ones_like(x_coordinates) grid = K.concatenate([x_coordinates, y_coordinates, ones], 0) # repeating grids for each batch grid = K.flatten(grid) grids = tf.tile(grid, K.stack([batch_size])) return K.reshape(grids, (batch_size, 3, height * width)) def _interpolate(image, sampled_grids, output_size): batch_size = K.shape(image)[0] height = K.shape(image)[1] width = K.shape(image)[2] num_channels = K.shape(image)[3] x = K.cast(K.flatten(sampled_grids[:, 0:1, :]), dtype='float32') y = K.cast(K.flatten(sampled_grids[:, 1:2, :]), dtype='float32') x = .5 * (x + 1.0) * K.cast(height-1, dtype='float32') y = .5 * (y + 1.0) * K.cast(width-1, dtype='float32') x0 = K.cast(x, 'int32') x1 = x0 + 1 y0 = K.cast(y, 'int32') y1 = y0 + 1 max_x = int(K.int_shape(image)[1] - 1) max_y = int(K.int_shape(image)[2] - 1) x0 = K.clip(x0, 0, max_x) x1 = K.clip(x1, 0, max_x) y0 = K.clip(y0, 0, max_y) y1 = K.clip(y1, 0, max_y) pixels_batch = K.arange(0, batch_size) * (height * width) pixels_batch = K.expand_dims(pixels_batch, axis=-1) flat_output_size = output_size[0] * output_size[1] base = K.repeat_elements(pixels_batch, flat_output_size, axis=1) base = K.flatten(base) base_y0 = y0 * width base_y0 = base + base_y0 base_y1 = y1 * width base_y1 = base_y1 + base indices_a = base_y0 + x0 indices_b = base_y1 + x0 print(x1.dtype,x.dtype,base_y0.dtype,base_y1.dtype) indices_c = base_y0 + x1 indices_d = base_y1 + x1 flat_image = K.reshape(image, shape=(-1, num_channels)) flat_image = K.cast(flat_image, dtype='float32') pixel_values_a = K.gather(flat_image, indices_a) pixel_values_b = K.gather(flat_image, indices_b) pixel_values_c = K.gather(flat_image, indices_c) pixel_values_d = K.gather(flat_image, indices_d) x0 = K.cast(x0, 'float32') x1 = K.cast(x1, 'float32') y0 = K.cast(y0, 'float32') y1 = K.cast(y1, 'float32') area_a = K.expand_dims(((x1 - x) * (y1 - y)), 1) area_b = K.expand_dims(((x1 - x) * (y - y0)), 1) area_c = K.expand_dims(((x - x0) * (y1 - y)), 1) area_d = K.expand_dims(((x - x0) * (y - y0)), 1) values_a = area_a * pixel_values_a values_b = area_b * pixel_values_b values_c = area_c * pixel_values_c values_d = area_d * pixel_values_d return values_a + values_b + values_c + values_d def np_to_torch(img): img = np.swapaxes(img, 0, 1) #w, h, 9 img = np.swapaxes(img, 0, 2) #9, h, w return torch.from_numpy(img).float() def torch_to_np(img): img = np.array(img) img = np.swapaxes(img, 1, 2) #w, h, 9 img = np.swapaxes(img, 2, 3) #9, h, w return img # return torch.from_numpy(img).float() def stn(x,theta): # xs = .localization(x) # xs = xs.view(-1, 10 * 3 * 3) # theta = .fc_loc(xs) # theta = theta.view(-1, 2, 3) theta =torch.from_numpy(theta) size = torch.Size([x.size(0), x.size(1),80, 80]) # print(theta.shape) grid = F.affine_grid(theta, size) x = F.grid_sample(x, grid) return x def affine_grid_generator(height, width, theta): """ This function returns a sampling grid, which when used with the bilinear sampler on the input feature map, will create an output feature map that is an affine transformation [1] of the input feature map. Input ----- - height: desired height of grid/output. Used to downsample or upsample. - width: desired width of grid/output. Used to downsample or upsample. - theta: affine transform matrices of shape (num_batch, 2, 3). For each image in the batch, we have 6 theta parameters of the form (2x3) that define the affine transformation T. Returns ------- - normalized grid (-1, 1) of shape (num_batch, 2, H, W). The 2nd dimension has 2 components: (x, y) which are the sampling points of the original image for each point in the target image. Note ---- [1]: the affine transformation allows cropping, translation, and isotropic scaling. """ num_batch = tf.shape(theta)[0] # create normalized 2D grid x = tf.linspace(-1.0, 1.0, width) y = tf.linspace(-1.0, 1.0, height) x_t, y_t = tf.meshgrid(x, y) # flatten x_t_flat = tf.reshape(x_t, [-1]) y_t_flat = tf.reshape(y_t, [-1]) # reshape to [x_t, y_t , 1] - (homogeneous form) ones = tf.ones_like(x_t_flat) sampling_grid = tf.stack([x_t_flat, y_t_flat, ones]) # repeat grid num_batch times sampling_grid = tf.math.expand_dims(sampling_grid, axis=0) sampling_grid = tf.tile(sampling_grid, tf.stack([num_batch, 1, 1])) # cast to float32 (required for matmul) theta = tf.cast(theta, 'float32') sampling_grid = tf.cast(sampling_grid, 'float32') # transform the sampling grid - batch multiply batch_grids = tf.matmul(theta, sampling_grid) # batch grid has shape (num_batch, 2, H*W) # reshape to (num_batch, H, W, 2) batch_grids = tf.reshape(batch_grids, [num_batch, 2, height, width]) return batch_grids def bilinear_sampler(img, x, y): """ Performs bilinear sampling of the input images according to the normalized coordinates provided by the sampling grid. Note that the sampling is done identically for each channel of the input. To test if the function works properly, output image should be identical to input image when theta is initialized to identity transform. Input ----- - img: batch of images in (B, H, W, C) layout. - grid: x, y which is the output of affine_grid_generator. Returns ------- - out: interpolated images according to grids. Same size as grid. """ H = tf.shape(img)[1] W = tf.shape(img)[2] max_y = tf.cast(H - 1, 'int32') max_x = tf.cast(W - 1, 'int32') zero = tf.zeros([], dtype='int32') # rescale x and y to [0, W-1/H-1] x = tf.cast(x, 'float32') y = tf.cast(y, 'float32') x = 0.5 * ((x + 1.0) * tf.cast(max_x-1, 'float32')) y = 0.5 * ((y + 1.0) * tf.cast(max_y-1, 'float32')) # grab 4 nearest corner points for each (x_i, y_i) x0 = tf.cast(tf.floor(x), 'int32') x1 = x0 + 1 y0 = tf.cast(tf.floor(y), 'int32') y1 = y0 + 1 # clip to range [0, H-1/W-1] to not violate img boundaries x0 = tf.clip_by_value(x0, zero, max_x) x1 = tf.clip_by_value(x1, zero, max_x) y0 = tf.clip_by_value(y0, zero, max_y) y1 = tf.clip_by_value(y1, zero, max_y) # get pixel value at corner coords Ia = get_pixel_value(img, x0, y0) Ib = get_pixel_value(img, x0, y1) Ic = get_pixel_value(img, x1, y0) Id = get_pixel_value(img, x1, y1) # recast as float for delta calculation x0 = tf.cast(x0, 'float32') x1 = tf.cast(x1, 'float32') y0 = tf.cast(y0, 'float32') y1 = tf.cast(y1, 'float32') # calculate deltas wa = (x1-x) * (y1-y) wb = (x1-x) * (y-y0) wc = (x-x0) * (y1-y) wd = (x-x0) * (y-y0) # add dimension for addition wa = tf.math.expand_dims(wa, axis=3) wb = tf.math.expand_dims(wb, axis=3) wc = tf.math.expand_dims(wc, axis=3) wd = tf.math.expand_dims(wd, axis=3) Ia = tf.cast(Ia, 'float32') Ib = tf.cast(Ib, 'float32') Ic = tf.cast(Ic, 'float32') Id = tf.cast(Id, 'float32') # print(wa.dtype,Ia.dtype,wb.dtype,Ib.dtype,Ic.dtype,wc.dtype,wd.dtype,Id.dtype,"dtypes") # compute output out = tf.add_n([wa*Ia, wb*Ib, wc*Ic, wd*Id]) return out def get_pixel_value(img, x, y): """ Utility function to get pixel value for coordinate vectors x and y from a 4D tensor image. Input ----- - img: tensor of shape (B, H, W, C) - x: flattened tensor of shape (B*H*W,) - y: flattened tensor of shape (B*H*W,) Returns ------- - output: tensor of shape (B, H, W, C) """ shape = tf.shape(x) batch_size = shape[0] height = shape[1] width = shape[2] batch_idx = tf.range(0, batch_size) batch_idx = tf.reshape(batch_idx, (batch_size, 1, 1)) b = tf.tile(batch_idx, (1, height, width)) indices = tf.stack([b, y, x], 3) return tf.gather_nd(img, indices) if __name__ == "__main__": a = cv2.imread("temp.png") theta = np.array([[[0.707, -0.707, 0.], [0.707, 0.707, 0.]]], dtype=np.float64) a = np.expand_dims(a,0) print(a.shape) sess = tf.Session() way= "tfcontrib" if way == "torch": a = np_to_torch(a) a = stn(a,theta) a = torch_to_np(a) print(a.shape) print("max",a.max(),"min",a.min()) elif way == "tf": t = _transform(a,theta,[80,80]) print(t.shape) print("max",t.max(),"min",t.min()) t = t.eval(session=sess) elif way == "tfcontrib": batch_grids =affine_grid_generator(80, 80, theta) x_s = batch_grids[:, 0, :, :] y_s = batch_grids[:, 1, :, :] t = bilinear_sampler(a,x_s,y_s) t = t.eval(session=sess) print(t.shape) print("max",t.max(),"min",t.min()) cv2.imshow("img",t[0]/255.0) cv2.waitKey(0) # stn()
30.993485
90
0.665581
e0b511c91bd0fea9ff68d21775cc555c4cf6d85e
2,035
py
Python
lldb/test/API/commands/expression/import-std-module/vector-of-vectors/TestVectorOfVectorsFromStdModule.py
mkinsner/llvm
589d48844edb12cd357b3024248b93d64b6760bf
[ "Apache-2.0" ]
2,338
2018-06-19T17:34:51.000Z
2022-03-31T11:00:37.000Z
lldb/test/API/commands/expression/import-std-module/vector-of-vectors/TestVectorOfVectorsFromStdModule.py
mkinsner/llvm
589d48844edb12cd357b3024248b93d64b6760bf
[ "Apache-2.0" ]
3,740
2019-01-23T15:36:48.000Z
2022-03-31T22:01:13.000Z
lldb/test/API/commands/expression/import-std-module/vector-of-vectors/TestVectorOfVectorsFromStdModule.py
mkinsner/llvm
589d48844edb12cd357b3024248b93d64b6760bf
[ "Apache-2.0" ]
500
2019-01-23T07:49:22.000Z
2022-03-30T02:59:37.000Z
""" Test std::vector functionality when it's contents are vectors. """ from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil class TestVectorOfVectors(TestBase): mydir = TestBase.compute_mydir(__file__) @add_test_categories(["libc++"]) @skipIf(compiler=no_match("clang")) def test(self): self.build() lldbutil.run_to_source_breakpoint(self, "// Set break point at this line.", lldb.SBFileSpec("main.cpp")) vector_type = "std::vector<int>" vector_of_vector_type = "std::vector<" + vector_type + " >" size_type = vector_of_vector_type + "::size_type" value_type = "std::__vector_base<int, std::allocator<int> >::value_type" self.runCmd("settings set target.import-std-module true") self.expect_expr( "a", result_type=vector_of_vector_type, result_children=[ ValueCheck(type="std::vector<int>", children=[ ValueCheck(value='1'), ValueCheck(value='2'), ValueCheck(value='3'), ]), ValueCheck(type="std::vector<int>", children=[ ValueCheck(value='3'), ValueCheck(value='2'), ValueCheck(value='1'), ]), ]) self.expect_expr("a.size()", result_type=size_type, result_value="2") self.expect_expr("a.front().front()", result_type=value_type, result_value="1") self.expect_expr("a[1][1]", result_type=value_type, result_value="2") self.expect_expr("a.back().at(0)", result_type=value_type, result_value="3")
37
80
0.49828
4dd21e673ac4eddcca1b65cdfb0162c64e50712b
2,103
py
Python
tests/test_rand_spatial_cropd.py
sudohainguyen/MONAI
89f8a39a1c0bc6f480522c443ee7813cea21df47
[ "Apache-2.0" ]
1
2020-07-09T08:03:22.000Z
2020-07-09T08:03:22.000Z
tests/test_rand_spatial_cropd.py
Scitator/MONAI
a42b563acf0c7504cee18ee84c8af2eff6e948a7
[ "Apache-2.0" ]
null
null
null
tests/test_rand_spatial_cropd.py
Scitator/MONAI
a42b563acf0c7504cee18ee84c8af2eff6e948a7
[ "Apache-2.0" ]
null
null
null
# Copyright 2020 MONAI Consortium # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import unittest import numpy as np from parameterized import parameterized from monai.transforms import RandSpatialCropd TEST_CASE_0 = [ {"keys": "img", "roi_size": [3, 3, -1], "random_center": True}, {"img": np.random.randint(0, 2, size=[3, 3, 3, 5])}, (3, 3, 3, 5), ] TEST_CASE_1 = [ {"keys": "img", "roi_size": [3, 3, 3], "random_center": True}, {"img": np.random.randint(0, 2, size=[3, 3, 3, 3])}, (3, 3, 3, 3), ] TEST_CASE_2 = [ {"keys": "img", "roi_size": [3, 3, 3], "random_center": False}, {"img": np.random.randint(0, 2, size=[3, 3, 3, 3])}, (3, 3, 3, 3), ] TEST_CASE_3 = [ {"keys": "img", "roi_size": [3, 3], "random_center": False}, {"img": np.array([[[0, 0, 0, 0, 0], [0, 1, 2, 1, 0], [0, 2, 3, 2, 0], [0, 1, 2, 1, 0], [0, 0, 0, 0, 0]]])}, ] class TestRandSpatialCropd(unittest.TestCase): @parameterized.expand([TEST_CASE_0, TEST_CASE_1, TEST_CASE_2]) def test_shape(self, input_param, input_data, expected_shape): result = RandSpatialCropd(**input_param)(input_data) self.assertTupleEqual(result["img"].shape, expected_shape) @parameterized.expand([TEST_CASE_3]) def test_value(self, input_param, input_data): cropper = RandSpatialCropd(**input_param) result = cropper(input_data) roi = [(2 - i // 2, 2 + i - i // 2) for i in cropper._size] np.testing.assert_allclose(result["img"], input_data["img"][:, roi[0][0] : roi[0][1], roi[1][0] : roi[1][1]]) if __name__ == "__main__": unittest.main()
36.894737
117
0.642416
e6c7b9406ea0df419870acae965f4090e97fd9b9
8,305
py
Python
SCODE-R/dpr/models/biencoder.py
rizwan09/REDCODER
e889b3d3f37573be8418c0ac536c2201e8f1be26
[ "MIT" ]
22
2021-11-15T06:00:13.000Z
2022-03-25T14:33:15.000Z
SCODE-R/dpr/models/biencoder.py
rizwan09/REDCODER
e889b3d3f37573be8418c0ac536c2201e8f1be26
[ "MIT" ]
2
2021-12-02T19:22:51.000Z
2022-02-19T10:50:58.000Z
SCODE-R/dpr/models/biencoder.py
rizwan09/REDCODER
e889b3d3f37573be8418c0ac536c2201e8f1be26
[ "MIT" ]
2
2021-10-07T15:27:25.000Z
2021-12-08T07:12:13.000Z
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. """ BiEncoder component + loss function for 'all-in-batch' training """ import collections import logging import random from typing import Tuple, List import numpy as np import torch import torch.nn.functional as F from torch import Tensor as T from torch import nn from dpr.utils.data_utils import Tensorizer from dpr.utils.data_utils import normalize_question logger = logging.getLogger(__name__) BiEncoderBatch = collections.namedtuple('BiENcoderInput', ['question_ids', 'question_segments', 'context_ids', 'ctx_segments', 'is_positive', 'hard_negatives']) def dot_product_scores(q_vectors: T, ctx_vectors: T) -> T: """ calculates q->ctx scores for every row in ctx_vector :param q_vector: :param ctx_vector: :return: """ # q_vector: n1 x D, ctx_vectors: n2 x D, result n1 x n2 r = torch.matmul(q_vectors, torch.transpose(ctx_vectors, 0, 1)) return r def cosine_scores(q_vector: T, ctx_vectors: T): # q_vector: n1 x D, ctx_vectors: n2 x D, result n1 x n2 return F.cosine_similarity(q_vector, ctx_vectors, dim=1) class BiEncoder(nn.Module): """ Bi-Encoder model component. Encapsulates query/question and context/passage encoders. """ def __init__(self, question_model: nn.Module, ctx_model: nn.Module, fix_q_encoder: bool = False, fix_ctx_encoder: bool = False): super(BiEncoder, self).__init__() self.question_model = question_model self.ctx_model = ctx_model self.fix_q_encoder = fix_q_encoder self.fix_ctx_encoder = fix_ctx_encoder @staticmethod def get_representation(sub_model: nn.Module, ids: T, segments: T, attn_mask: T, fix_encoder: bool = False) -> ( T, T, T): sequence_output = None pooled_output = None hidden_states = None if ids is not None: if fix_encoder: with torch.no_grad(): sequence_output, pooled_output, hidden_states = sub_model(ids, segments, attn_mask) if sub_model.training: sequence_output.requires_grad_(requires_grad=True) pooled_output.requires_grad_(requires_grad=True) else: sequence_output, pooled_output, hidden_states = sub_model(ids, segments, attn_mask) return sequence_output, pooled_output, hidden_states def forward(self, question_ids: T, question_segments: T, question_attn_mask: T, context_ids: T, ctx_segments: T, ctx_attn_mask: T) -> Tuple[T, T]: _q_seq, q_pooled_out, _q_hidden = self.get_representation(self.question_model, question_ids, question_segments, question_attn_mask, self.fix_q_encoder) _ctx_seq, ctx_pooled_out, _ctx_hidden = self.get_representation(self.ctx_model, context_ids, ctx_segments, ctx_attn_mask, self.fix_ctx_encoder) return q_pooled_out, ctx_pooled_out @classmethod def create_biencoder_input(cls, samples: List, tensorizer: Tensorizer, insert_title: bool, num_hard_negatives: int = 0, num_other_negatives: int = 0, shuffle: bool = True, shuffle_positives: bool = False, TopCodeR=True ) -> BiEncoderBatch: """ Creates a batch of the biencoder training tuple. :param samples: list of data items (from json) to create the batch for :param tensorizer: components to create model input tensors from a text sequence :param insert_title: enables title insertion at the beginning of the context sequences :param num_hard_negatives: amount of hard negatives per question (taken from samples' pools) :param num_other_negatives: amount of other negatives per question (taken from samples' pools) :param shuffle: shuffles negative passages pools :param shuffle_positives: shuffles positive passages pools :return: BiEncoderBatch tuple """ question_tensors = [] ctx_tensors = [] positive_ctx_indices = [] hard_neg_ctx_indices = [] for sample in samples: # ctx+ & [ctx-] composition # as of now, take the first(gold) ctx+ only if len(sample['positive_ctxs'])>0: if shuffle and shuffle_positives: positive_ctxs = sample['positive_ctxs'] positive_ctx = positive_ctxs[np.random.choice(len(positive_ctxs))] else: positive_ctx = sample['positive_ctxs'][0] neg_ctxs = sample['negative_ctxs'] hard_neg_ctxs = sample['hard_negative_ctxs'] question = normalize_question(sample['question']) if shuffle: random.shuffle(neg_ctxs) random.shuffle(hard_neg_ctxs) if len(hard_neg_ctxs)>0: neg_ctxs = neg_ctxs[0:num_other_negatives] hard_neg_ctxs = hard_neg_ctxs[0:num_hard_negatives] all_ctxs = [positive_ctx] + neg_ctxs + hard_neg_ctxs hard_negatives_start_idx = 1 hard_negatives_end_idx = 1 + len(hard_neg_ctxs) current_ctxs_len = len(ctx_tensors) sample_ctxs_tensors = [tensorizer.text_to_tensor(ctx['text'], title=ctx['title'] if insert_title else None) for ctx in all_ctxs] ctx_tensors.extend(sample_ctxs_tensors) positive_ctx_indices.append(current_ctxs_len) hard_neg_ctx_indices.append( [i for i in range(current_ctxs_len + hard_negatives_start_idx, current_ctxs_len + hard_negatives_end_idx)]) question_tensors.append(tensorizer.text_to_tensor(question)) ctxs_tensor = torch.cat([ctx.view(1, -1) for ctx in ctx_tensors], dim=0) questions_tensor = torch.cat([q.view(1, -1) for q in question_tensors], dim=0) ctx_segments = torch.zeros_like(ctxs_tensor) question_segments = torch.zeros_like(questions_tensor) return BiEncoderBatch(questions_tensor, question_segments, ctxs_tensor, ctx_segments, positive_ctx_indices, hard_neg_ctx_indices) class BiEncoderNllLoss(object): def calc(self, q_vectors: T, ctx_vectors: T, positive_idx_per_question: list, hard_negative_idx_per_question: list = None) -> Tuple[T, int]: """ Computes nll loss for the given lists of question and ctx vectors. Note that although hard_negative_idx_per_question in not currently in use, one can use it for the loss modifications. For example - weighted NLL with different factors for hard vs regular negatives. :return: a tuple of loss value and amount of correct predictions per batch """ scores = self.get_scores(q_vectors, ctx_vectors) if len(q_vectors.size()) > 1: q_num = q_vectors.size(0) scores = scores.view(q_num, -1) softmax_scores = F.log_softmax(scores, dim=1) loss = F.nll_loss(softmax_scores, torch.tensor(positive_idx_per_question).to(softmax_scores.device), reduction='mean') max_score, max_idxs = torch.max(softmax_scores, 1) correct_predictions_count = (max_idxs == torch.tensor(positive_idx_per_question).to(max_idxs.device)).sum() return loss, correct_predictions_count @staticmethod def get_scores(q_vector: T, ctx_vectors: T) -> T: f = BiEncoderNllLoss.get_similarity_function() return f(q_vector, ctx_vectors) @staticmethod def get_similarity_function(): return dot_product_scores
41.113861
119
0.629862
74949c8610d11ba09575d209de80dc8087d1df19
2,363
py
Python
src/start_rpc.py
sunoru/splatoon-privates
453508668ff630579cbc290b0c41b1d40346986e
[ "MIT" ]
1
2018-10-10T16:44:43.000Z
2018-10-10T16:44:43.000Z
src/start_rpc.py
sunoru/splatoon-privas
453508668ff630579cbc290b0c41b1d40346986e
[ "MIT" ]
null
null
null
src/start_rpc.py
sunoru/splatoon-privas
453508668ff630579cbc290b0c41b1d40346986e
[ "MIT" ]
null
null
null
#!/usr/bin/env python3 import sys import uuid import zerorpc from privas import Privas, PrivaError class PrivaRPC: priva_pool = {} @staticmethod def list_priva_types(): return { x: { 'names': Privas[x].Meta.names, 'args': [ (arg, Privas[x].__init__.__annotations__.get(arg, str).__name__) for arg in Privas[x].__init__.__code__.co_varnames[1:] ] } for x in Privas.keys() } def list_privas(self): return {pid: str(self.priva_pool[pid]) for pid in self.priva_pool} def show_rules(self, typename, language='en'): if typename not in Privas: raise NotImplementedError() return Privas[typename].rules(language) def create_priva(self, typename, *args, **kwargs): if typename not in Privas: raise NotImplementedError() priva = Privas[typename](*args, **kwargs) pid = str(uuid.uuid1()) self.priva_pool[pid] = priva return pid def delete_priva(self, pid): if pid not in self.priva_pool: return False del self.priva_pool[pid] return True def run_action(self, pid, action, *args, **kwargs): if pid not in self.priva_pool: raise Exception(-2, 'Invalid priva ID') priva = self.priva_pool[pid] action_func = getattr(priva, action) if action_func is None: raise Exception(-3, 'Invalid action name') if 'no_return' in kwargs: action_func(*args, **kwargs) return True return action_func(*args, **kwargs) def restore_priva(self, typename, pid, json_data): if typename not in Privas: raise NotImplementedError() priva_class = Privas[typename] action_func = getattr(priva_class, 'from_json') if action_func is None: raise NotImplementedError() priva = action_func(json_data) self.priva_pool[pid] = priva return pid def main(): endpoint = sys.argv[1] if len(sys.argv) > 1 else 'tcp://0.0.0.0:4242' s = zerorpc.Server(PrivaRPC()) s.bind(endpoint) s.run() if __name__ == '__main__': main()
28.817073
85
0.561997
032d8936e1a2388be0616a26e6e148632f1aab3e
13,555
py
Python
client/protocols/backup.py
akshitdewan/ok-client
3c5eca17100eed808023a815654cfe1c95179080
[ "Apache-2.0" ]
30
2018-07-10T17:32:49.000Z
2022-01-03T16:50:56.000Z
client/protocols/backup.py
akshitdewan/ok-client
3c5eca17100eed808023a815654cfe1c95179080
[ "Apache-2.0" ]
62
2018-08-07T18:43:33.000Z
2022-02-17T20:53:03.000Z
client/protocols/backup.py
akshitdewan/ok-client
3c5eca17100eed808023a815654cfe1c95179080
[ "Apache-2.0" ]
26
2018-11-13T22:12:47.000Z
2022-03-20T00:42:26.000Z
from display_timedelta import display_timedelta from client import exceptions from client.protocols.common import models from client.utils import network import client import datetime import logging import time import os import sys from subprocess import Popen import pickle import requests from filelock import Timeout, FileLock log = logging.getLogger(__name__) from client.utils.printer import print_warning, print_success, print_error from client.utils.output import DisableLog class BackupProtocol(models.Protocol): # Timeouts are specified in seconds. SHORT_TIMEOUT = 2 RETRY_LIMIT = 5 BACKUP_FILE = ".ok_messages" BACKUP_ENDPOINT = '{server}/api/v3/backups/' REVISION_ENDPOINT = '{server}/api/v3/revision/' ASSIGNMENT_ENDPOINT = '{server}/api/v3/assignment/' def run(self, messages, nointeract=False): if not self.assignment.endpoint: log.info('No assignment endpoint, skipping backup') return if self.args.local: print_warning("Cannot backup when running ok with --local.") return if not self.args.insecure: network.check_ssl() if self.args.revise: action = 'revision' elif self.args.submit: action = 'submission' else: action = 'backup' message_list = self.load_unsent_messages() access_token = self.assignment.authenticate(nointeract=nointeract) log.info('Authenticated with access token') log.info('Sending unsent messages') if not access_token: print_error("Not authenticated. Cannot send {} to server".format(action)) self.dump_unsent_messages(message_list) return # Messages from the current backup to send first is_send_first = self.args.submit or self.args.revise subm_messages = [messages] if is_send_first else [] if is_send_first: response = self.send_all_messages(access_token, subm_messages, current=True) if message_list: self.send_all_messages(access_token, message_list, current=False) else: message_list.append(messages) response = self.send_all_messages(access_token, message_list, current=False) base_url = self.assignment.server_url + '/{}/{}/{}' if isinstance(response, dict): print_success('{action} successful for user: {email}'.format(action=action.title(), email=response['data']['email'])) submission_type = 'submissions' if self.args.submit else 'backups' url = base_url.format(response['data']['assignment'], submission_type, response['data']['key']) if self.args.submit or self.args.backup: print_success('URL: {0}'.format(url)) if self.args.backup: print('NOTE: this is only a backup. ' 'To submit your assignment, use:\n' '\tpython3 ok --submit') self.dump_unsent_messages(message_list + subm_messages) print() def _update_last_autobackup_time(self, between): """ Updates the last autobackup time in TIME_PATH """ LOCK_PATH = ".ok_backup_time.lock" TIME_PATH = ".ok_backup_time" try: with FileLock(LOCK_PATH, timeout=1): try: with open(TIME_PATH) as f: last_time = datetime.datetime.fromtimestamp(int(f.read())) if datetime.datetime.now() - last_time < between: return False except FileNotFoundError: pass with open(TIME_PATH, "w") as f: f.write(str(int(datetime.datetime.now().timestamp()))) return True except Timeout: return False def _safe_run(self, messages, between): """ Run a backup, if and only if an autobackup has not been attempted more than `between` time ago. between: a timedelta of how long to wait between backups """ if not self._update_last_autobackup_time(between): return with DisableLog(): try: self.run(messages, nointeract=True) except Exception as e: return def _get_end_time(self): access_token = self.assignment.authenticate(nointeract=False) due_date = self.get_due_date(access_token, 5) if due_date is None: due_date = datetime.datetime.min.replace(tzinfo=datetime.timezone.utc) return max(due_date, datetime.datetime.now(tz=datetime.timezone.utc)) + datetime.timedelta(hours=1) def run_in_loop(self, messages_fn, period, synchronous): if not synchronous: self.run(messages_fn()) args = sys.argv[:] args.append("--autobackup-actual-run-sync") Popen([sys.executable, *args]) return end_time = self._get_end_time() self._run_sync(messages_fn, period, end_time) def _run_sync(self, messages_fn, period, end_time): while datetime.datetime.now(tz=datetime.timezone.utc) < end_time: self._safe_run(messages_fn(), between=period) time.sleep(5) @classmethod def load_unsent_messages(cls): message_list = [] try: with open(cls.BACKUP_FILE, 'rb') as fp: message_list = pickle.load(fp) log.info('Loaded %d backed up messages from %s', len(message_list), cls.BACKUP_FILE) except (IOError, EOFError) as e: log.info('Error reading from ' + cls.BACKUP_FILE + \ ', assume nothing backed up') return message_list @classmethod def dump_unsent_messages(cls, message_list): with open(cls.BACKUP_FILE, 'wb') as f: log.info('Save %d unsent messages to %s', len(message_list), cls.BACKUP_FILE) pickle.dump(message_list, f) os.fsync(f) def send_all_messages(self, access_token, message_list, current=False): if not self.args.insecure: ssl = network.check_ssl() else: ssl = None if current and self.args.revise: action = "Revise" elif current and self.args.submit: action = "Submit" else: action = "Backup" num_messages = len(message_list) send_all = self.args.submit or self.args.backup retries = self.RETRY_LIMIT if send_all: timeout = None stop_time = datetime.datetime.max retries = self.RETRY_LIMIT * 2 else: timeout = self.SHORT_TIMEOUT stop_time = datetime.datetime.now() + datetime.timedelta(seconds=timeout) log.info('Setting timeout to %d seconds', timeout) first_response = None error_msg = '' log.info("Sending {0} messages".format(num_messages)) while retries > 0 and message_list and datetime.datetime.now() < stop_time: log.info('Sending messages...%d left', len(message_list)) print('{action}... {percent}% complete'.format(action=action, percent=100 - round(len(message_list) * 100 / num_messages, 2)), end='\r') # message_list is assumed to be ordered in chronological order. # We want to send the most recent message first, and send older # messages after. message = message_list[-1] try: response = self.send_messages(access_token, message, timeout, current) except requests.exceptions.Timeout as ex: log.warning("HTTP request timeout: %s", str(ex)) retries -= 1 error_msg = 'Connection timed out after {} seconds. '.format(timeout) + \ 'Please check your network connection.' except (requests.exceptions.RequestException, requests.exceptions.BaseHTTPError) as ex: log.warning('%s: %s', ex.__class__.__name__, str(ex)) retries -= 1 if getattr(ex, 'response', None) is None: error_msg = 'Please check your network connection.' continue try: response_json = ex.response.json() except ValueError as ex: log.warning("Invalid JSON Response", exc_info=True) retries -= 1 error_msg = 'The server did not provide a valid response. Try again soon.' continue log.warning('%s error message: %s', ex.__class__.__name__, response_json['message']) if ex.response.status_code == 401: # UNAUTHORIZED (technically authorization != authentication, but oh well) raise exceptions.AuthenticationException(response_json.get('message')) # raise this for the caller elif ex.response.status_code == 403 and 'download_link' in response_json['data']: retries = 0 error_msg = 'Aborting because OK may need to be updated.' else: retries -= 1 error_msg = response_json['message'] except Exception as ex: if ssl and isinstance(ex, ssl.CertificateError): retries = 0 log.warning("SSL Error: %s", str(ex)) error_msg = 'SSL Verification Error: {}\n'.format(ex) + \ 'Please check your network connection and SSL configuration.' else: retries -= 1 log.warning(error_msg, exc_info=True) error_msg = "Unknown Error: {}".format(ex) else: if not first_response: first_response = response message_list.pop() if current and error_msg: print() # Preserve progress bar. print_error('Could not', action.lower() + ':', error_msg) elif not message_list: print('{action}... 100% complete'.format(action=action)) due_date = self.get_due_date(access_token, timeout) if due_date is not None and action != "Revise": now = datetime.datetime.now(tz=datetime.timezone.utc) time_to_deadline = due_date - now if time_to_deadline < datetime.timedelta(0): print_error("{action} past deadline by".format(action=action), display_timedelta(-time_to_deadline)) elif time_to_deadline < datetime.timedelta(hours=10): print_warning("Assignment is due in", display_timedelta(time_to_deadline)) return first_response elif not send_all: # Do not display any error messages if --backup or --submit are not # used. print() elif not error_msg: # No errors occurred, but could not complete request within TIMEOUT. print() # Preserve progress bar. print_error('Could not {} within {} seconds.'.format(action.lower(), timeout)) else: # If not all messages could be backed up successfully. print() # Preserve progress bar. print_error('Could not', action.lower() + ':', error_msg) def send_messages(self, access_token, messages, timeout, current): """Send messages to server, along with user authentication.""" is_submit = current and self.args.submit and not self.args.revise is_revision = current and self.args.revise data = { 'assignment': self.assignment.endpoint, 'messages': messages, 'submit': is_submit } if is_revision: address = self.REVISION_ENDPOINT.format(server=self.assignment.server_url) else: address = self.BACKUP_ENDPOINT.format(server=self.assignment.server_url) address_params = { 'client_name': 'ok-client', 'client_version': client.__version__, } headers = {'Authorization': 'Bearer {}'.format(access_token)} log.info('Sending messages to %s', address) response = requests.post(address, headers=headers, params=address_params, json=data, timeout=timeout) response.raise_for_status() return response.json() def get_due_date(self, access_token, timeout): address = self.ASSIGNMENT_ENDPOINT.format(server=self.assignment.server_url) + self.assignment.endpoint response = requests.get(address, headers={'Authorization': 'Bearer {}'.format(access_token)}, timeout=timeout) response_data = response.json()['data'] if 'due_date' not in response_data: return utc_date_string = response_data['due_date'] return datetime.datetime.strptime(utc_date_string, '%Y-%m-%dT%H:%M:%S').replace(tzinfo=datetime.timezone.utc) protocol = BackupProtocol
39.40407
125
0.58045
0a1f65209f38e0e206b547dfb7e3c7298ab0fcd9
2,643
py
Python
lib/surface/kuberun/core/brokers/list.py
google-cloud-sdk-unofficial/google-cloud-sdk
2a48a04df14be46c8745050f98768e30474a1aac
[ "Apache-2.0" ]
2
2019-11-10T09:17:07.000Z
2019-12-18T13:44:08.000Z
lib/surface/kuberun/core/brokers/list.py
google-cloud-sdk-unofficial/google-cloud-sdk
2a48a04df14be46c8745050f98768e30474a1aac
[ "Apache-2.0" ]
null
null
null
lib/surface/kuberun/core/brokers/list.py
google-cloud-sdk-unofficial/google-cloud-sdk
2a48a04df14be46c8745050f98768e30474a1aac
[ "Apache-2.0" ]
1
2020-07-25T01:40:19.000Z
2020-07-25T01:40:19.000Z
# -*- coding: utf-8 -*- # # Copyright 2020 Google LLC. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Command for listing a broker.""" from __future__ import absolute_import from __future__ import division from __future__ import unicode_literals from googlecloudsdk.calliope import base from googlecloudsdk.command_lib.events import eventflow_operations from googlecloudsdk.command_lib.events import resource_args from googlecloudsdk.command_lib.kuberun import connection_context from googlecloudsdk.command_lib.run import commands from googlecloudsdk.command_lib.run import pretty_print from googlecloudsdk.command_lib.util.concepts import concept_parsers from googlecloudsdk.command_lib.util.concepts import presentation_specs @base.ReleaseTracks(base.ReleaseTrack.BETA, base.ReleaseTrack.ALPHA) class List(commands.List): """List brokers.""" detailed_help = { 'DESCRIPTION': """\ {description} """, 'EXAMPLES': """\ To list brokers in the default namespace, run: $ {command} To list brokers in namespace ``NAMESPACE'', run: $ {command} --namespace=NAMESPACE """, } @classmethod def Args(cls, parser): namespace_presentation = presentation_specs.ResourcePresentationSpec( '--namespace', resource_args.GetCoreNamespaceResourceSpec(), 'Namespace to create the Broker in.', required=True, prefixes=False) concept_parsers.ConceptParser([namespace_presentation]).AddToParser(parser) parser.display_info.AddFormat("""table( {ready_column}, firstof(id,metadata.name):label=BROKER, status.address.url:label=URL) """.format(ready_column=pretty_print.READY_COLUMN)) parser.display_info.AddUriFunc(cls._GetResourceUri) def Run(self, args): conn_context = connection_context.EventsConnectionContext(args) namespace_ref = args.CONCEPTS.namespace.Parse() with eventflow_operations.Connect(conn_context) as client: brokers = client.ListBrokers(namespace_ref.RelativeName()) return brokers
35.24
79
0.730988
f35a35d66810398b55dabca807796e55f8de2466
412
py
Python
custom/icds_reports/migrations/0131_update_views_For_thr_colums.py
tobiasmcnulty/commcare-hq
234aa1fba98a96de1b625bbd70b2066fc877eed1
[ "BSD-3-Clause" ]
1
2020-07-14T13:00:23.000Z
2020-07-14T13:00:23.000Z
custom/icds_reports/migrations/0131_update_views_For_thr_colums.py
tobiasmcnulty/commcare-hq
234aa1fba98a96de1b625bbd70b2066fc877eed1
[ "BSD-3-Clause" ]
null
null
null
custom/icds_reports/migrations/0131_update_views_For_thr_colums.py
tobiasmcnulty/commcare-hq
234aa1fba98a96de1b625bbd70b2066fc877eed1
[ "BSD-3-Clause" ]
null
null
null
# Generated by Django 1.11.16 on 2019-06-17 16:38 from corehq.sql_db.operations import RawSQLMigration from django.db import migrations from custom.icds_reports.const import SQL_TEMPLATES_ROOT migrator = RawSQLMigration((SQL_TEMPLATES_ROOT, 'database_views')) class Migration(migrations.Migration): dependencies = [ ('icds_reports', '0130_thr_mother_column_agg_awc'), ] operations = []
24.235294
66
0.762136
4034b143bf33cc4452626bcc8963654c6c375013
1,561
py
Python
saleor/core/views.py
TysonRV/saleor
83d3ca5ae163fa853ab311d0ebcdbc22f4788166
[ "BSD-3-Clause" ]
3
2018-06-14T22:52:38.000Z
2019-01-24T03:48:46.000Z
saleor/core/views.py
TysonRV/saleor
83d3ca5ae163fa853ab311d0ebcdbc22f4788166
[ "BSD-3-Clause" ]
null
null
null
saleor/core/views.py
TysonRV/saleor
83d3ca5ae163fa853ab311d0ebcdbc22f4788166
[ "BSD-3-Clause" ]
1
2018-06-29T10:54:09.000Z
2018-06-29T10:54:09.000Z
import json from django.contrib import messages from django.template.response import TemplateResponse from django.utils.translation import pgettext_lazy from impersonate.views import impersonate as orig_impersonate from ..account.models import User from ..dashboard.views import staff_member_required from ..product.utils import products_for_homepage from ..product.utils.availability import products_with_availability from ..seo.schema.webpage import get_webpage_schema def home(request): products = products_for_homepage()[:8] products = products_with_availability( products, discounts=request.discounts, taxes=request.taxes, local_currency=request.currency) webpage_schema = get_webpage_schema(request) return TemplateResponse( request, 'home.html', { 'parent': None, 'products': products, 'webpage_schema': json.dumps(webpage_schema)}) @staff_member_required def styleguide(request): return TemplateResponse(request, 'styleguide.html') def impersonate(request, uid): response = orig_impersonate(request, uid) if request.session.modified: msg = pgettext_lazy( 'Impersonation message', 'You are now logged as {}'.format(User.objects.get(pk=uid))) messages.success(request, msg) return response def handle_404(request, exception=None): return TemplateResponse(request, '404.html', status=404) def manifest(request): return TemplateResponse( request, 'manifest.json', content_type='application/json')
31.22
72
0.737348
ebb9b69a1b72df29cb903ced948371d39043927b
3,098
py
Python
src/toil/test/src/resumabilityTest.py
cmarkello/toil
756c45c773c5bd95d48d5d2fd7986d467781f09b
[ "Apache-2.0" ]
null
null
null
src/toil/test/src/resumabilityTest.py
cmarkello/toil
756c45c773c5bd95d48d5d2fd7986d467781f09b
[ "Apache-2.0" ]
null
null
null
src/toil/test/src/resumabilityTest.py
cmarkello/toil
756c45c773c5bd95d48d5d2fd7986d467781f09b
[ "Apache-2.0" ]
1
2021-03-24T16:56:54.000Z
2021-03-24T16:56:54.000Z
# Copyright (C) 2016 UCSC Computational Genomics Lab # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from __future__ import absolute_import from builtins import range import os # Python 3 compatibility imports from six.moves import xrange from toil.job import Job from toil.test import ToilTest, slow from toil.jobStores.abstractJobStore import NoSuchFileException from toil.leader import FailedJobsException @slow class ResumabilityTest(ToilTest): """ https://github.com/BD2KGenomics/toil/issues/808 """ def test(self): """ Tests that a toil workflow that fails once can be resumed without a NoSuchJobException. """ options = Job.Runner.getDefaultOptions(self._getTestJobStorePath()) options.logLevel = "INFO" options.retryCount = 0 root = Job.wrapJobFn(parent) with self.assertRaises(FailedJobsException): # This one is intended to fail. Job.Runner.startToil(root, options) # Resume the workflow. Unfortunately, we have to check for # this bug using the logging output, since although the # NoSuchJobException causes the worker to fail, the batch # system code notices that the job has been deleted despite # the failure and avoids the failure. options.restart = True tempDir = self._createTempDir() options.logFile = os.path.join(tempDir, "log.txt") Job.Runner.startToil(root, options) with open(options.logFile) as f: logString = f.read() # We are looking for e.g. "Batch system is reporting that # the jobGraph with batch system ID: 1 and jobGraph # store ID: n/t/jobwbijqL failed with exit value 1" self.assertTrue("failed with exit value" not in logString) def parent(job): """ Set up a bunch of dummy child jobs, and a bad job that needs to be restarted as the follow on. """ for _ in range(5): job.addChildJobFn(goodChild) job.addFollowOnJobFn(badChild) def goodChild(job): """ Does nothing. """ return def badChild(job): """ Fails the first time it's run, succeeds the second time. """ try: with job.fileStore.jobStore.readSharedFileStream("alreadyRun") as fileHandle: fileHandle.read() except NoSuchFileException as ex: with job.fileStore.jobStore.writeSharedFileStream("alreadyRun", isProtected=False) as fileHandle: fileHandle.write(b"failed once\n") raise RuntimeError("this is an expected error: {}".format(str(ex)))
36.023256
105
0.685604
f6bbd1ebb8c1d356dc2db313e29814c94b219452
3,596
py
Python
tests/test_observable/test_skipuntilwithtime.py
mmpio/RxPY
4ed60bb5c04aa85de5210e5537a6adfe1b667d50
[ "MIT" ]
4,342
2015-01-06T09:00:23.000Z
2022-03-28T15:05:50.000Z
tests/test_observable/test_skipuntilwithtime.py
mmpio/RxPY
4ed60bb5c04aa85de5210e5537a6adfe1b667d50
[ "MIT" ]
613
2015-01-07T20:44:56.000Z
2022-03-20T06:14:20.000Z
tests/test_observable/test_skipuntilwithtime.py
mmpio/RxPY
4ed60bb5c04aa85de5210e5537a6adfe1b667d50
[ "MIT" ]
420
2015-01-07T14:30:30.000Z
2022-03-11T22:47:46.000Z
import unittest from datetime import datetime from rx import operators as ops from rx.testing import TestScheduler, ReactiveTest on_next = ReactiveTest.on_next on_completed = ReactiveTest.on_completed on_error = ReactiveTest.on_error subscribe = ReactiveTest.subscribe subscribed = ReactiveTest.subscribed disposed = ReactiveTest.disposed created = ReactiveTest.created class TestSkipUntilWithTIme(unittest.TestCase): def test_skipuntil_zero(self): scheduler = TestScheduler() xs = scheduler.create_hot_observable(on_next(210, 1), on_next(220, 2), on_completed(230)) def create(): return xs.pipe(ops.skip_until_with_time(datetime.utcfromtimestamp(0))) res = scheduler.start(create) assert res.messages == [on_next(210, 1), on_next(220, 2), on_completed(230)] assert xs.subscriptions == [subscribe(200, 230)] def test_skipuntil_late(self): scheduler = TestScheduler() xs = scheduler.create_hot_observable(on_next(210, 1), on_next(220, 2), on_completed(230)) def create(): return xs.pipe(ops.skip_until_with_time(datetime.utcfromtimestamp(250))) res = scheduler.start(create) assert res.messages == [on_completed(230)] assert xs.subscriptions == [subscribe(200, 230)] def test_skipuntil_error(self): ex = 'ex' scheduler = TestScheduler() xs = scheduler.create_hot_observable(on_error(210, ex)) def create(): return xs.pipe(ops.skip_until_with_time(datetime.utcfromtimestamp(250))) res = scheduler.start(create) assert res.messages == [on_error(210, ex)] assert xs.subscriptions == [subscribe(200, 210)] def test_skipuntil_never(self): scheduler = TestScheduler() xs = scheduler.create_hot_observable() def create(): return xs.pipe(ops.skip_until_with_time(datetime.utcfromtimestamp(250))) res = scheduler.start(create) assert res.messages == [] assert xs.subscriptions == [subscribe(200, 1000)] def test_skipuntil_twice1(self): scheduler = TestScheduler() xs = scheduler.create_hot_observable( on_next(210, 1), on_next(220, 2), on_next(230, 3), on_next(240, 4), on_next(250, 5), on_next(260, 6), on_completed(270)) def create(): return xs.pipe( ops.skip_until_with_time(datetime.utcfromtimestamp(215)), ops.skip_until_with_time(datetime.utcfromtimestamp(230)), ) res = scheduler.start(create) assert res.messages == [ on_next(240, 4), on_next(250, 5), on_next(260, 6), on_completed(270)] assert xs.subscriptions == [subscribe(200, 270)] def test_skipuntil_twice2(self): scheduler = TestScheduler() xs = scheduler.create_hot_observable( on_next(210, 1), on_next(220, 2), on_next(230, 3), on_next(240, 4), on_next(250, 5), on_next(260, 6), on_completed(270)) def create(): return xs.pipe( ops.skip_until_with_time(datetime.utcfromtimestamp(230)), ops.skip_until_with_time(datetime.utcfromtimestamp(215)), ) res = scheduler.start(create) assert res.messages == [on_next(240, 4), on_next(250, 5), on_next(260, 6), on_completed(270)] assert xs.subscriptions == [subscribe(200, 270)]
32.690909
101
0.622636
7a9d7911006b7e70767df60850f59f2a893d044b
1,394
py
Python
python/fingerprint_similarity.py
carpenterlab/puma_project
70e82c23f6cfec866298df31f54fe1ea2884ee9c
[ "MIT" ]
null
null
null
python/fingerprint_similarity.py
carpenterlab/puma_project
70e82c23f6cfec866298df31f54fe1ea2884ee9c
[ "MIT" ]
null
null
null
python/fingerprint_similarity.py
carpenterlab/puma_project
70e82c23f6cfec866298df31f54fe1ea2884ee9c
[ "MIT" ]
null
null
null
import csv import numpy as np from tqdm import tqdm from rdkit import Chem from rdkit import DataStructs from chemprop.data.utils import get_data_from_smiles from chemprop.features.features_generators import morgan_binary_features_generator ### Paths to assay matrices here assay_train_file = 'assay_matrix_discrete_train_scaff_filt.csv' assay_test_file = 'assay_matrix_discrete_test_scaff.csv' ### smiles = [] smiles_ = [] with open(assay_train_file) as f: next(f) reader = csv.reader(f) for row in reader: smiles.append([row[0]]) smiles_.append(row[0]) with open(assay_test_file) as f: next(f) reader = csv.reader(f) for row in reader: smiles.append([row[0]]) smiles_.append(row[0]) fingerprints = [] data = get_data_from_smiles(smiles) data = data.mols(flatten=True) for i in range(len(data)): mf = morgan_binary_features_generator(data[i]) fingerprints.append(mf) fingerprints = np.array(fingerprints) #print(fingerprints.shape) np.savez('fingerprints.npz', features = fingerprints) fps = [] for i in range(len(data)): fps.append(Chem.RDKFingerprint(data[i])) similarity = np.zeros([16978, 16978]) for (x, y), _ in tqdm(np.ndenumerate(similarity)): similarity[x, y] = DataStructs.FingerprintSimilarity(fps[x], fps[y]) np.savez('similarity_fingerprints.npz', features = similarity)
27.333333
82
0.716643
5ece1a9285303397842f3fb3d58824f71e90b4d5
2,753
py
Python
qutip/tests/test_simdiag.py
camponogaraviera/qutip
1b1f6dffcb3ab97f11b8c6114293e09f378d2e8f
[ "BSD-3-Clause" ]
1,205
2015-01-02T16:23:42.000Z
2022-03-31T03:21:21.000Z
qutip/tests/test_simdiag.py
camponogaraviera/qutip
1b1f6dffcb3ab97f11b8c6114293e09f378d2e8f
[ "BSD-3-Clause" ]
1,361
2015-01-09T23:38:25.000Z
2022-03-31T12:26:07.000Z
qutip/tests/test_simdiag.py
camponogaraviera/qutip
1b1f6dffcb3ab97f11b8c6114293e09f378d2e8f
[ "BSD-3-Clause" ]
569
2015-01-19T06:15:33.000Z
2022-03-28T20:43:39.000Z
import pytest import numpy as np import qutip @pytest.mark.parametrize('num_mat', [1, 2, 3, 5]) def test_simdiag(num_mat): N = 10 U = qutip.rand_unitary(N) commuting_matrices = [U * qutip.qdiags(np.random.rand(N), 0) * U.dag() for _ in range(num_mat)] all_evals, evecs = qutip.simdiag(commuting_matrices) for matrix, evals in zip(commuting_matrices, all_evals): for eval, evec in zip(evals, evecs): assert matrix * evec == evec * eval @pytest.mark.parametrize('num_mat', [1, 2, 3, 5]) def test_simdiag_no_evals(num_mat): N = 10 U = qutip.rand_unitary(N) commuting_matrices = [U * qutip.qdiags(np.random.rand(N), 0) * U.dag() for _ in range(num_mat)] evecs = qutip.simdiag(commuting_matrices, evals=False) for matrix in commuting_matrices: for evec in evecs: Mvec = matrix * evec eval = Mvec.norm() / evec.norm() assert matrix * evec == evec * eval def test_simdiag_degen(): N = 10 U = qutip.rand_unitary(N) commuting_matrices = [ U * qutip.qdiags([0, 0, 0, 1, 1, 1, 2, 2, 3, 4], 0) * U.dag(), U * qutip.qdiags([0, 0, 0, 1, 2, 2, 2, 2, 2, 2], 0) * U.dag(), U * qutip.qdiags([0, 0, 2, 1, 1, 2, 2, 3, 3, 4], 0) * U.dag(), ] all_evals, evecs = qutip.simdiag(commuting_matrices) for matrix, evals in zip(commuting_matrices, all_evals): for eval, evec in zip(evals, evecs): np.testing.assert_allclose( (matrix * evec).full(), (evec * eval).full() ) @pytest.mark.repeat(10) def test_simdiag_degen_large(): N = 20 U = qutip.rand_unitary(N) commuting_matrices = [ U * qutip.qdiags(np.random.randint(0, 3, N), 0) * U.dag() for _ in range(5) ] all_evals, evecs = qutip.simdiag(commuting_matrices, tol=1e-12) for matrix, evals in zip(commuting_matrices, all_evals): for eval, evec in zip(evals, evecs): np.testing.assert_allclose( (matrix * evec).full(), (evec * eval).full() ) def test_simdiag_no_input(): with pytest.raises(ValueError): qutip.simdiag([]) @pytest.mark.parametrize(['ops', 'error'], [ pytest.param([qutip.basis(5, 0)], 'square', id="Not square"), pytest.param([qutip.qeye(5), qutip.qeye(3)], 'shape', id="shape mismatch"), pytest.param([qutip.destroy(5)], 'Hermitian', id="Non Hermitian"), pytest.param([qutip.sigmax(), qutip.sigmay()], 'commute', id="Not commuting"), ]) def test_simdiag_errors(ops, error): with pytest.raises(TypeError) as err: qutip.simdiag(ops) assert error in str(err.value)
31.284091
79
0.585543
87a372e6201aadfb2e714df7aec38183b76d3eee
683
py
Python
app/core/migrations/0002_tag.py
shadow-smoke/recipe-app-api
b5a75be5eb2a541accc39772a23d542fac1d5a69
[ "MIT" ]
null
null
null
app/core/migrations/0002_tag.py
shadow-smoke/recipe-app-api
b5a75be5eb2a541accc39772a23d542fac1d5a69
[ "MIT" ]
null
null
null
app/core/migrations/0002_tag.py
shadow-smoke/recipe-app-api
b5a75be5eb2a541accc39772a23d542fac1d5a69
[ "MIT" ]
null
null
null
# Generated by Django 2.1.15 on 2020-10-14 12:24 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('core', '0001_initial'), ] operations = [ migrations.CreateModel( name='Tag', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=225)), ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], ), ]
28.458333
118
0.616398
2738c885c0a57b46632234e1af1522c4ee3a58f8
13,686
py
Python
astropy/coordinates/builtin_frames/icrs_cirs_transforms.py
CosmicTiger/astropy
88b6bd4879e81ccd55be4f2a3c20e78624c7d208
[ "BSD-3-Clause" ]
null
null
null
astropy/coordinates/builtin_frames/icrs_cirs_transforms.py
CosmicTiger/astropy
88b6bd4879e81ccd55be4f2a3c20e78624c7d208
[ "BSD-3-Clause" ]
null
null
null
astropy/coordinates/builtin_frames/icrs_cirs_transforms.py
CosmicTiger/astropy
88b6bd4879e81ccd55be4f2a3c20e78624c7d208
[ "BSD-3-Clause" ]
null
null
null
# -*- coding: utf-8 -*- # Licensed under a 3-clause BSD style license - see LICENSE.rst """ Contains the transformation functions for getting from ICRS/HCRS to CIRS and anything in between (currently that means GCRS) """ import numpy as np from astropy import units as u from astropy.coordinates.baseframe import frame_transform_graph from astropy.coordinates.transformations import ( FunctionTransformWithFiniteDifference, AffineTransform, ) from astropy.coordinates.representation import ( SphericalRepresentation, CartesianRepresentation, UnitSphericalRepresentation, CartesianDifferential, ) from .icrs import ICRS from .gcrs import GCRS from .cirs import CIRS from .hcrs import HCRS from .utils import aticq, atciqz from ..erfa_astrom import erfa_astrom # First the ICRS/CIRS related transforms @frame_transform_graph.transform(FunctionTransformWithFiniteDifference, ICRS, CIRS) def icrs_to_cirs(icrs_coo, cirs_frame): # first set up the astrometry context for ICRS<->CIRS astrom = erfa_astrom.get().apci(cirs_frame) if icrs_coo.data.get_name() == 'unitspherical' or icrs_coo.data.to_cartesian().x.unit == u.one: # if no distance, just do the infinite-distance/no parallax calculation srepr = icrs_coo.spherical cirs_ra, cirs_dec = atciqz(srepr.without_differentials(), astrom) newrep = UnitSphericalRepresentation(lat=u.Quantity(cirs_dec, u.radian, copy=False), lon=u.Quantity(cirs_ra, u.radian, copy=False), copy=False) else: # When there is a distance, we first offset for parallax to get the # astrometric coordinate direction and *then* run the ERFA transform for # no parallax/PM. This ensures reversibility and is more sensible for # inside solar system objects astrom_eb = CartesianRepresentation(astrom['eb'], unit=u.au, xyz_axis=-1, copy=False) newcart = icrs_coo.cartesian - astrom_eb srepr = newcart.represent_as(SphericalRepresentation) cirs_ra, cirs_dec = atciqz(srepr.without_differentials(), astrom) newrep = SphericalRepresentation(lat=u.Quantity(cirs_dec, u.radian, copy=False), lon=u.Quantity(cirs_ra, u.radian, copy=False), distance=srepr.distance, copy=False) return cirs_frame.realize_frame(newrep) @frame_transform_graph.transform(FunctionTransformWithFiniteDifference, CIRS, ICRS) def cirs_to_icrs(cirs_coo, icrs_frame): # set up the astrometry context for ICRS<->cirs and then convert to # astrometric coordinate direction astrom = erfa_astrom.get().apci(cirs_coo) srepr = cirs_coo.represent_as(SphericalRepresentation) i_ra, i_dec = aticq(srepr.without_differentials(), astrom) if cirs_coo.data.get_name() == 'unitspherical' or cirs_coo.data.to_cartesian().x.unit == u.one: # if no distance, just use the coordinate direction to yield the # infinite-distance/no parallax answer newrep = UnitSphericalRepresentation(lat=u.Quantity(i_dec, u.radian, copy=False), lon=u.Quantity(i_ra, u.radian, copy=False), copy=False) else: # When there is a distance, apply the parallax/offset to the SSB as the # last step - ensures round-tripping with the icrs_to_cirs transform # the distance in intermedrep is *not* a real distance as it does not # include the offset back to the SSB intermedrep = SphericalRepresentation(lat=u.Quantity(i_dec, u.radian, copy=False), lon=u.Quantity(i_ra, u.radian, copy=False), distance=srepr.distance, copy=False) astrom_eb = CartesianRepresentation(astrom['eb'], unit=u.au, xyz_axis=-1, copy=False) newrep = intermedrep + astrom_eb return icrs_frame.realize_frame(newrep) @frame_transform_graph.transform(FunctionTransformWithFiniteDifference, CIRS, CIRS) def cirs_to_cirs(from_coo, to_frame): if np.all(from_coo.obstime == to_frame.obstime): return to_frame.realize_frame(from_coo.data) else: # the CIRS<-> CIRS transform actually goes through ICRS. This has a # subtle implication that a point in CIRS is uniquely determined # by the corresponding astrometric ICRS coordinate *at its # current time*. This has some subtle implications in terms of GR, but # is sort of glossed over in the current scheme because we are dropping # distances anyway. return from_coo.transform_to(ICRS()).transform_to(to_frame) # Now the GCRS-related transforms to/from ICRS @frame_transform_graph.transform(FunctionTransformWithFiniteDifference, ICRS, GCRS) def icrs_to_gcrs(icrs_coo, gcrs_frame): # first set up the astrometry context for ICRS<->GCRS. astrom = erfa_astrom.get().apcs(gcrs_frame) if icrs_coo.data.get_name() == 'unitspherical' or icrs_coo.data.to_cartesian().x.unit == u.one: # if no distance, just do the infinite-distance/no parallax calculation srepr = icrs_coo.represent_as(SphericalRepresentation) gcrs_ra, gcrs_dec = atciqz(srepr.without_differentials(), astrom) newrep = UnitSphericalRepresentation(lat=u.Quantity(gcrs_dec, u.radian, copy=False), lon=u.Quantity(gcrs_ra, u.radian, copy=False), copy=False) else: # When there is a distance, we first offset for parallax to get the # BCRS coordinate direction and *then* run the ERFA transform for no # parallax/PM. This ensures reversibility and is more sensible for # inside solar system objects astrom_eb = CartesianRepresentation(astrom['eb'], unit=u.au, xyz_axis=-1, copy=False) newcart = icrs_coo.cartesian - astrom_eb srepr = newcart.represent_as(SphericalRepresentation) gcrs_ra, gcrs_dec = atciqz(srepr.without_differentials(), astrom) newrep = SphericalRepresentation(lat=u.Quantity(gcrs_dec, u.radian, copy=False), lon=u.Quantity(gcrs_ra, u.radian, copy=False), distance=srepr.distance, copy=False) return gcrs_frame.realize_frame(newrep) @frame_transform_graph.transform(FunctionTransformWithFiniteDifference, GCRS, ICRS) def gcrs_to_icrs(gcrs_coo, icrs_frame): # set up the astrometry context for ICRS<->GCRS and then convert to BCRS # coordinate direction astrom = erfa_astrom.get().apcs(gcrs_coo) srepr = gcrs_coo.represent_as(SphericalRepresentation) i_ra, i_dec = aticq(srepr.without_differentials(), astrom) if gcrs_coo.data.get_name() == 'unitspherical' or gcrs_coo.data.to_cartesian().x.unit == u.one: # if no distance, just use the coordinate direction to yield the # infinite-distance/no parallax answer newrep = UnitSphericalRepresentation(lat=u.Quantity(i_dec, u.radian, copy=False), lon=u.Quantity(i_ra, u.radian, copy=False), copy=False) else: # When there is a distance, apply the parallax/offset to the SSB as the # last step - ensures round-tripping with the icrs_to_gcrs transform # the distance in intermedrep is *not* a real distance as it does not # include the offset back to the SSB intermedrep = SphericalRepresentation(lat=u.Quantity(i_dec, u.radian, copy=False), lon=u.Quantity(i_ra, u.radian, copy=False), distance=srepr.distance, copy=False) astrom_eb = CartesianRepresentation(astrom['eb'], unit=u.au, xyz_axis=-1, copy=False) newrep = intermedrep + astrom_eb return icrs_frame.realize_frame(newrep) @frame_transform_graph.transform(FunctionTransformWithFiniteDifference, GCRS, GCRS) def gcrs_to_gcrs(from_coo, to_frame): if (np.all(from_coo.obstime == to_frame.obstime) and np.all(from_coo.obsgeoloc == to_frame.obsgeoloc)): return to_frame.realize_frame(from_coo.data) else: # like CIRS, we do this self-transform via ICRS return from_coo.transform_to(ICRS()).transform_to(to_frame) @frame_transform_graph.transform(FunctionTransformWithFiniteDifference, GCRS, HCRS) def gcrs_to_hcrs(gcrs_coo, hcrs_frame): if np.any(gcrs_coo.obstime != hcrs_frame.obstime): # if they GCRS obstime and HCRS obstime are not the same, we first # have to move to a GCRS where they are. frameattrs = gcrs_coo.get_frame_attr_names() frameattrs['obstime'] = hcrs_frame.obstime gcrs_coo = gcrs_coo.transform_to(GCRS(**frameattrs)) # set up the astrometry context for ICRS<->GCRS and then convert to ICRS # coordinate direction astrom = erfa_astrom.get().apcs(gcrs_coo) srepr = gcrs_coo.represent_as(SphericalRepresentation) i_ra, i_dec = aticq(srepr.without_differentials(), astrom) # convert to Quantity objects i_ra = u.Quantity(i_ra, u.radian, copy=False) i_dec = u.Quantity(i_dec, u.radian, copy=False) if gcrs_coo.data.get_name() == 'unitspherical' or gcrs_coo.data.to_cartesian().x.unit == u.one: # if no distance, just use the coordinate direction to yield the # infinite-distance/no parallax answer newrep = UnitSphericalRepresentation(lat=i_dec, lon=i_ra, copy=False) else: # When there is a distance, apply the parallax/offset to the # Heliocentre as the last step to ensure round-tripping with the # hcrs_to_gcrs transform # Note that the distance in intermedrep is *not* a real distance as it # does not include the offset back to the Heliocentre intermedrep = SphericalRepresentation(lat=i_dec, lon=i_ra, distance=srepr.distance, copy=False) # astrom['eh'] and astrom['em'] contain Sun to observer unit vector, # and distance, respectively. Shapes are (X) and (X,3), where (X) is the # shape resulting from broadcasting the shape of the times object # against the shape of the pv array. # broadcast em to eh and scale eh eh = astrom['eh'] * astrom['em'][..., np.newaxis] eh = CartesianRepresentation(eh, unit=u.au, xyz_axis=-1, copy=False) newrep = intermedrep.to_cartesian() + eh return hcrs_frame.realize_frame(newrep) _NEED_ORIGIN_HINT = ("The input {0} coordinates do not have length units. This " "probably means you created coordinates with lat/lon but " "no distance. Heliocentric<->ICRS transforms cannot " "function in this case because there is an origin shift.") @frame_transform_graph.transform(AffineTransform, HCRS, ICRS) def hcrs_to_icrs(hcrs_coo, icrs_frame): # this is just an origin translation so without a distance it cannot go ahead if isinstance(hcrs_coo.data, UnitSphericalRepresentation): raise u.UnitsError(_NEED_ORIGIN_HINT.format(hcrs_coo.__class__.__name__)) if hcrs_coo.data.differentials: from astropy.coordinates.solar_system import get_body_barycentric_posvel bary_sun_pos, bary_sun_vel = get_body_barycentric_posvel('sun', hcrs_coo.obstime) bary_sun_vel = bary_sun_vel.represent_as(CartesianDifferential) bary_sun_pos = bary_sun_pos.with_differentials(bary_sun_vel) else: from astropy.coordinates.solar_system import get_body_barycentric bary_sun_pos = get_body_barycentric('sun', hcrs_coo.obstime) bary_sun_vel = None return None, bary_sun_pos @frame_transform_graph.transform(AffineTransform, ICRS, HCRS) def icrs_to_hcrs(icrs_coo, hcrs_frame): # this is just an origin translation so without a distance it cannot go ahead if isinstance(icrs_coo.data, UnitSphericalRepresentation): raise u.UnitsError(_NEED_ORIGIN_HINT.format(icrs_coo.__class__.__name__)) if icrs_coo.data.differentials: from astropy.coordinates.solar_system import get_body_barycentric_posvel bary_sun_pos, bary_sun_vel = get_body_barycentric_posvel('sun', hcrs_frame.obstime) bary_sun_pos = -bary_sun_pos bary_sun_vel = -bary_sun_vel.represent_as(CartesianDifferential) bary_sun_pos = bary_sun_pos.with_differentials(bary_sun_vel) else: from astropy.coordinates.solar_system import get_body_barycentric bary_sun_pos = -get_body_barycentric('sun', hcrs_frame.obstime) bary_sun_vel = None return None, bary_sun_pos @frame_transform_graph.transform(FunctionTransformWithFiniteDifference, HCRS, HCRS) def hcrs_to_hcrs(from_coo, to_frame): if np.all(from_coo.obstime == to_frame.obstime): return to_frame.realize_frame(from_coo.data) else: # like CIRS, we do this self-transform via ICRS return from_coo.transform_to(ICRS()).transform_to(to_frame)
47.030928
99
0.662429
f339bd738cb9849a096a0e2e1b3bc03215e0a050
2,701
py
Python
qcodes/instrument_drivers/QuTech/M2j.py
GateBuilder/Qcodes
b3729f188847f9a7db77f23f8c1b3a2a635a2ac2
[ "MIT" ]
2
2019-04-09T09:39:22.000Z
2019-10-24T19:07:19.000Z
qcodes/instrument_drivers/QuTech/M2j.py
GateBuilder/Qcodes
b3729f188847f9a7db77f23f8c1b3a2a635a2ac2
[ "MIT" ]
null
null
null
qcodes/instrument_drivers/QuTech/M2j.py
GateBuilder/Qcodes
b3729f188847f9a7db77f23f8c1b3a2a635a2ac2
[ "MIT" ]
1
2019-11-19T12:32:29.000Z
2019-11-19T12:32:29.000Z
from qcodes.instrument.base import Instrument from qcodes.utils.validators import Numbers import numpy as np try: from spirack import M2j_module, SPI_rack except ImportError: raise ImportError(('The M2j_module class could not be found. ' 'Try installing it using pip install spirack')) class M2j(Instrument): def __init__(self, name: str, spi_rack: SPI_rack, module: int, **kwargs): """ Qcodes driver for the M2j RF amplifier SPI-rack module. Args: name: name of the instrument. spi_rack: instance of the SPI_rack class as defined in the spirack package. This class manages communication with the individual modules. module: module number as set on the hardware. The gain can only be set on the device, but not read from the device. """ super().__init__(name, **kwargs) self.m2j = M2j_module(spi_rack, module) self._max_gain_value = 4095 self._min_gain_value = 0 self._gain_parameters = {'slope': -1024.45, 'offset': 4450.63, 'db_offset': 32} self.add_parameter('gain', label='gain', set_cmd=self._set_gain, unit='dB', vals=Numbers(min_value=33, max_value=55), docstring='Amplifier gain in dB, range 33 to 55 dB') self.add_parameter('RF_level', label='RF level', get_cmd=self._meas_rf_level, unit='dBm', docstring='Measured RF power after amplification ' '(not calibrated)') self.add_function('clear_rf_clip', call_cmd=self.m2j.clear_rf_clip) self.add_function('is_rf_clipped', call_cmd=self.m2j.rf_clipped) def _set_gain(self, gain): ref_scale = int(self._gain_parameters['slope'] * np.log( gain - self._gain_parameters['db_offset']) + self._gain_parameters[ 'offset']) if ref_scale < self._min_gain_value: ref_scale = self._min_gain_value if ref_scale > self._max_gain_value: ref_scale = self._max_gain_value self.m2j.set_gain(ref_scale) def _meas_rf_level(self): """ Measure the power in dBm. Calibrated using an R&S SMA100 source. Linear relation between set power and measured data. Measurement range -80 to -40 dBm. """ return self.m2j.get_level()
36.5
79
0.562384
8f6bd8a24dd226f7988cea53a10102062aaf9c87
8,174
py
Python
funciones.py
JCGALVIS/ProyectoProgramacionCorte120191
4edfb2a5b250a9cadf87607232b869a60d4edc20
[ "MIT" ]
null
null
null
funciones.py
JCGALVIS/ProyectoProgramacionCorte120191
4edfb2a5b250a9cadf87607232b869a60d4edc20
[ "MIT" ]
null
null
null
funciones.py
JCGALVIS/ProyectoProgramacionCorte120191
4edfb2a5b250a9cadf87607232b869a60d4edc20
[ "MIT" ]
null
null
null
def calcular_precio_producto(coste_producto): """ num -> num se ingresa un numero y se obtiene el precio del producto sumandole el 50% al coste :param coste_producto: valor numerico del coste :return: precio del producto >>> calcular_precio_producto(1000) 1500.0 >>> calcular_precio_producto(2000) 3000.0 """ if(coste_producto <= 0): return 'El costo del producto debe ser mayor a cero.' precioProducto = (coste_producto * 0.5) + coste_producto return precioProducto def calcular_precio_servicio(cantidad_horas): """ num -> float opera un numeros para dar como resultado el precio del servicio :param cantidad_horas: Entero de las horas trabajadas :return: el precio del servicio >>> calcular_precio_servicio(4) 400000.0 >>> calcular_precio_servicio(5) 500000.0 """ if (cantidad_horas <= 0): return 'Las horas deben ser mayor a cero.' total = cantidad_horas * 100000 return float(total) def calcular_precio_servicio_extras(cantidad_horas): """ num -> num opera dos numeros y suma lo que tiene la funcion anterior :param cantidad_horas: Entero con las horas extras trabajadas :return: EL precio del servicio con las horas extras >>> calcular_precio_servicio_extras(1) 125000.0 >>> calcular_precio_servicio_extras(2) 250000.0 """ if (cantidad_horas == 0): return 'El servicio no genera horas extras.' if (cantidad_horas < 0): return 'Las horas deben ser mayor a cero.' precioServicio = calcular_precio_servicio(cantidad_horas) precioServicioExtras = (precioServicio * 0.25) + precioServicio return precioServicioExtras def calcular_costo_envio(kilometros): """ num -> float opera dos numeros para dar como resultado el costo de envio :param kilometros: se ingresan la cantidad de kilometros recorridos :return: el costo del envio >>> calcular_costo_envio(1) 115.0 >>> calcular_costo_envio(0) 0.0 """ if (kilometros < 0): return 'El numero de kilometros debe ser mayor a cero.' return float(kilometros * 115) def calcular_precio_producto_extra(coste_producto,kilometros): """ num -> float se operan dos numeros para dar como resultado del costo de envio fuera :param coste_producto: Es el numero que representa costo del producto :param kilometros: los kilometros recorridos del envio :return: El precio del producto fuera de la ciudad >>> calcular_precio_producto_extra(1000,1) 1615.0 >>> calcular_precio_producto_extra(500,5) 1325.0 """ if (coste_producto <= 0): return 'El costo del producto debe ser mayor a cero.' tprecio_producto_envio_fuera = calcular_precio_producto(coste_producto) + calcular_costo_envio(kilometros) return float(tprecio_producto_envio_fuera) def calcular_iva_producto(coste_producto, tasa): """ num -> num num -> num entran dos numers que multiplicados, dan el valor del iva :param coste_producto: Es el dato que corresponde al costo del producto :param tasa: El numero por el cual se multiplica el costo del producto y determinar el iva :return: El valor del iva >>> calcular_iva_producto(1000,0.19) 285.0 >>> calcular_iva_producto(1000,0) 0.0 """ if (coste_producto <= 0): return 'El costo del producto debe ser mayor a cero.' iva_final = calcular_precio_producto(coste_producto) * tasa return float(iva_final) def calcular_iva_servicio(cantidad_horas, tasa): """ num -> num num -> num entran dos numeros, que al ser operados, se obtiene el valor del iva de un servicio :param cantidad_horas: Numero de la cantidad de horas trabajadas :param tasa: Porcentaje para operar :return: el valor del iva del servicio >>> calcular_iva_servicio(4, 0.19) 76000.0 """ if (cantidad_horas <= 0): return 'El numero de horas debe ser mayor a cero.' iva_servicio = (calcular_precio_servicio(cantidad_horas)) * tasa return float(iva_servicio) def calcular_iva_envio(kilometros, tasa): """ num -> num num -> num entran dos numeros para calcular el iva del envio :param kilometros: Cantidad de kilometros recorridos :param tasa: la tasa para multiplicar los kilometros :return: el iva del envio >>> calcular_iva_envio(1,0.19) 21.85 >>> calcular_iva_envio(2,0.19) 43.7 """ if(kilometros < 0): return 'El numero de kilometros no debe ser menor a cero.' iva_envio = calcular_costo_envio(kilometros) * tasa return float(iva_envio) def calcular_iva_servicio_extra(cantidad_horas, tasa): """ num -> num num -> num entran dos numeros para poder calcular el iva del servicio :param cantidad_horas: numero de horas trabajadas :param tasa: porcentaje de iva :return: iva del servicio >>> calcular_iva_servicio_extra(1,0.19) 23750.0 >>> calcular_iva_servicio_extra(3,0.19) 71250.0 """ if (cantidad_horas <= 0): return 'El numero de horas no debe ser menor o igual a cero.' iva_servicio_fuera = ((calcular_precio_servicio(cantidad_horas) * 0.25) + calcular_precio_servicio(cantidad_horas)) * tasa return iva_servicio_fuera def calcular_recaudo_locales(coste_producto_1,coste_producto_2,coste_producto_3): """ num -> num num -> num num -> num entran 3 numeros que sumados, dan el recaudo total :param coste_producto_1: costo del primer producto :param coste_producto_2: costo del segundo producto :param coste_producto_3: costo del tercer producto :return: recaudo total de los locales >>> calcular_recaudo_locales(1000,1500,2000) 4500.0 >>> calcular_recaudo_locales(3000,1500,800) 5300.0 """ if (coste_producto_1<=0 or coste_producto_2<=0 or coste_producto_3<=0): return 'El costo del producto debe ser mayor a cero.' recaudo_local = coste_producto_1+coste_producto_2+coste_producto_3 return float(recaudo_local) def calcular_recaudo_horas_extra(horas_1,horas_2,horas_3,horas_4): """ num -> num num -> num num -> num num -> num Multiplica las horas por 100000 y le incrementa un 25% para después sumarla :param horas_1: Cantidad de horas uno :param horas_2: Cantidad de horas dos :param horas_3: Cantidad de horas tres :param horas_4: Cantidad de horas cuatro :return: La sumatoria de las horas extras >>> calcular_recaudo_horas_extra(3,4,5,6) 2250000.0 >>> calcular_recaudo_horas_extra(4,5,4,1) 1750000.0 """ if (horas_1 <= 0 or horas_2 <= 0 or horas_3 <= 0 or horas_4 <= 0): return 'El numero de horas no debe ser menor o igual a cero.' recaudo_extras = ((horas_1*100000)*0.25+(horas_1*100000))+((horas_2*100000)*0.25+(horas_2*100000))+((horas_3*100000)*0.25+(horas_3*100000))+((horas_4*100000)*0.25+(horas_4*100000)) return float(recaudo_extras) def calcular_recaudo_mixto_local(coste_producto_1,coste_producto_2,horas_1,horas_2): """ num -> num num -> num num -> num num -> num Multiplica el coste del producto por el 50% y suma el coste del producto, además las horas por 100000 y ls suma :param coste_producto_1: Valor del coste del producto uno :param coste_producto_2: Valor del coste del producto dos :param horas_1: Cantidad de horas trabajadas uno :param horas_2: Cantidad de horas trabajadas dos :return: La suma de las 4 cantidades >>> calcular_recaudo_mixto_local(1000,1500,1,1) 253750.0 >>> calcular_recaudo_mixto_local(2000,1000,8,10) 2254500.0 """ if (coste_producto_1 <= 0 or coste_producto_2 <= 0): return 'El costo del producto debe ser mayor a cero.' if (horas_1 <= 0 or horas_2 <= 0): return 'El numero de horas no debe ser menor o igual a cero.' recaudo_mix = (coste_producto_1+(coste_producto_1*0.5))+(coste_producto_2+(coste_producto_2*0.5))+((horas_1*100000)*0.25+(horas_1*100000))+((horas_2*100000)*0.25+(horas_2*100000)) return float(recaudo_mix)
31.929688
184
0.692195
224f3e53f583aa38159fe24af0c26287c1430e1c
4,798
py
Python
tests/fast_tests/test_traffic_light_grid.py
SHITIANYU-hue/flow
6fb5697868517fea7098a81b78c1be8e925f09f7
[ "MIT" ]
805
2018-08-16T22:30:51.000Z
2022-03-31T09:25:50.000Z
tests/fast_tests/test_traffic_light_grid.py
SHITIANYU-hue/flow
6fb5697868517fea7098a81b78c1be8e925f09f7
[ "MIT" ]
879
2018-08-22T17:37:06.000Z
2022-03-29T01:06:11.000Z
tests/fast_tests/test_traffic_light_grid.py
SHITIANYU-hue/flow
6fb5697868517fea7098a81b78c1be8e925f09f7
[ "MIT" ]
325
2018-08-22T06:48:00.000Z
2022-03-21T15:09:04.000Z
import unittest from flow.core.experiment import Experiment from tests.setup_scripts import traffic_light_grid_mxn_exp_setup class Test1x1Environment(unittest.TestCase): def setUp(self): # create the environment and network classes for a traffic light grid network self.env, _, flow_params = traffic_light_grid_mxn_exp_setup() self.env.reset() # instantiate an experiment class self.exp = Experiment(flow_params) def tearDown(self): # terminate the traci instance self.env.terminate() # free up used memory self.env = None self.exp = None def test_split_edge(self): """ In a 1x1 grid, edges are: [left0_0, right0_0, bot0_0, top0_0, bot0_1, top0_1, left1_0, right1_0, :center0] and should be indexed as such """ edges = [ "left0_0", "right0_0", "bot0_0", "top0_0", "bot0_1", "top0_1", "left1_0", "right1_0", ":center0" ] for i in range(len(edges)): edge = edges[i] self.assertEqual(self.env._split_edge(edge), i + 1) def test_convert_edge(self): edges = [ "left0_0", "right0_0", "bot0_0", "top0_0", "bot0_1", "top0_1", "left1_0", "right1_0", ":center0" ] self.assertEqual( sorted(self.env._convert_edge(edges)), [i + 1 for i in range(len(edges))]) @staticmethod def gen_edges(col_num, row_num): edges = [] for i in range(col_num): edges += ["left" + str(row_num) + '_' + str(i)] edges += ["right" + '0' + '_' + str(i)] # build the left and then the right edges for i in range(row_num): edges += ["bot" + str(i) + '_' + '0'] edges += ["top" + str(i) + '_' + str(col_num)] return edges def test_get_distance_to_intersection(self): # Obtain list of lists of vehicles on entrance # edges, then the distances. veh_ids = [ self.env.k.vehicle.get_ids_by_edge(e) for e in self.gen_edges(1, 1) ] dists = [self.env.get_distance_to_intersection(v) for v in veh_ids] grid = self.env.net_params.additional_params['grid_array'] short_length = grid['short_length'] # The first check asserts all the lists are equal. With the default # initial config (sans noise) it should be. The second check asserts # that all the vehicles are in the confines of [0, short_length] away # from the intersection. for d_list in dists: self.assertListEqual(d_list, dists[0]) for d in d_list: self.assertLessEqual(d, short_length) self.assertGreaterEqual(d, 0) # Asserts that when a vehicles is in a junction, # get_distance_to_intersection returns 0. veh_edges = self.env.k.vehicle.get_edge(self.env.k.vehicle.get_ids()) while not ['center' in edge for edge in veh_edges]: print(self.env.k.vehicle.get_edge(self.env.k.vehicle.get_ids())) self.env.step(rl_actions=[]) junction_veh = list( filter(lambda x: 'center' in x, self.env.k.vehicle.get_ids())) for veh_id in junction_veh: self.assertEqual(0, self.env.get_distance_to_intersection(veh_id)) class Test2x2Environment(unittest.TestCase): def setUp(self): # create the environment and network classes for a traffic light grid network self.env, _, flow_params = traffic_light_grid_mxn_exp_setup(row_num=2, col_num=2) self.env.reset() # instantiate an experiment class self.exp = Experiment(flow_params) def tearDown(self): # terminate the traci instance self.env.terminate() # free up used memory self.env = None self.exp = None def test_get_relative_node(self): node = self.env._get_relative_node('center0', 'top') self.assertEqual(2, node) node = self.env._get_relative_node('center0', 'right') self.assertEqual(1, node) node = self.env._get_relative_node('center0', 'bottom') self.assertEqual(-1, node) with self.assertRaises(NotImplementedError): self.env._get_relative_node('center0', 'blah') node = self.env._get_relative_node('center2', 'bottom') self.assertEqual(0, node) node = self.env._get_relative_node('center2', 'right') self.assertEqual(3, node) node = self.env._get_relative_node('center2', 'left') self.assertEqual(-1, node) with self.assertRaises(NotImplementedError): self.env._get_relative_node('center1', 'blah') if __name__ == '__main__': unittest.main()
34.028369
89
0.610463
7a40cc802a3cd7440afc689538a3120307c2b308
4,770
py
Python
Dataset/ToyExample/Control/UVS/uvs.py
atlas-jj/state-representation-robotics
04e381d534d9544101addcf502426fcb8f253643
[ "MIT-0" ]
2
2020-03-13T22:25:26.000Z
2021-12-29T12:42:52.000Z
Dataset/ToyExample/Control/UVS/uvs.py
atlas-jj/state-representation-robotics
04e381d534d9544101addcf502426fcb8f253643
[ "MIT-0" ]
null
null
null
Dataset/ToyExample/Control/UVS/uvs.py
atlas-jj/state-representation-robotics
04e381d534d9544101addcf502426fcb8f253643
[ "MIT-0" ]
null
null
null
#!/usr/bin/env python # -*- coding: utf-8 -*- """Provides training and testing module for Bayesian Inference used in visual imitation learning. ============================================================================= * paper: Robot Visual Imitation Learning using Variational Bayesian Inference * Author: Jun Jin (jjin5@ualberta.ca), University of Alberta * TimeMark: Dec 11, 2018 * Status: Dev * License: check LICENSE in parent folder ============================================================================= - input: training sample - output: network module + testing visualizations - comments: network module will further used in the control module. """ import numpy as np import math import sys, copy sys.path.insert(0,'../Robots') class UVS(): def __init__(self, robot, broyden_alpha, action_lambda, dim_error, step_normalize_range, estimate_jacobian_random_motion_range): self.robot = robot self.task_dof = robot.get_robot_dof() self.broyden_alpha = broyden_alpha self.action_lambda = action_lambda self.dim_error = dim_error self.jacobian = self.reset_jacobian() self.step_normalize_range = step_normalize_range #[min, max] self.random_motion_range = estimate_jacobian_random_motion_range def reset_jacobian(self): return np.zeros((self.dim_error, self.task_dof)) def estimate_jacobian_random_motion(self, trial_index): """ step 1, random motion :param perturbation_range: :return: """ np.random.seed(trial_index) random_motion = np.random.uniform(self.random_motion_range[0], self.random_motion_range[1], self.task_dof) random_marks = np.random.uniform(0, 1, self.task_dof) for i in range(self.task_dof): random_marks[i] = 1 if random_marks[i] > 0.5 else -1 random_motion = random_motion * random_marks self.robot.move_step(random_motion) return random_motion def estimate_jacobian_motion_quality(self, delta_error): if np.linalg.norm(delta_error) / math.sqrt(self.task_dof) < 0.01: return False # bad quality, not causing error change big enough else: return True def estimate_jacobian(self, delta_joints, delta_errors): """ step 2, input the randome motion and observed delta_error :param delta_joints: 2D matrix, n trials * random_motion vectors :param delta_errors: 2D matrix, n trials * delta_error vectors :return: """ trials = delta_joints.shape[0] self.jacobian = self.reset_jacobian() for i in range(trials): for j in range(self.task_dof): self.jacobian[:, j] += delta_errors[i] / delta_joints[i][j] self.jacobian = self.jacobian / trials print("result jacobian") print(self.jacobian) return self.jacobian def broyden_update_fake(self, delta_error, delta_joint): if np.linalg.norm(delta_joint) == 0: return False print("Broyden Update:") print("previous jacobian:") print(self.jacobian) self.estimate_jacobian(delta_joint.reshape(-1,delta_joint.shape[0]), delta_error.reshape(-1, delta_error.shape[0])) def broyden_update(self, delta_error, delta_joint): if np.linalg.norm(delta_joint) == 0: return False dde = (delta_error - np.matmul(self.jacobian, delta_joint)).reshape(self.dim_error, -1) update = np.matmul(dde, delta_joint.reshape(-1, self.task_dof)) / np.dot(delta_joint, delta_joint) # print("Broyden Update:") # print("previous jacobian:") # print(self.jacobian) self.jacobian = self.jacobian + self.broyden_alpha * update # print("updated jacobian") # print(self.jacobian) return self.jacobian def move_step(self, current_error): """ current error can also replaced using generic action :param current_error: = target - current, so there is no (-1) here, traditional vs is current-target :return: """ step = self.action_lambda * np.matmul(np.transpose(self.jacobian), current_error) step_norm = np.linalg.norm(step) # / math.sqrt(self.task_dof) if step_norm > self.step_normalize_range[1]: print('step norm too large: ' + str(step_norm)) step = step * self.step_normalize_range[1] / step_norm if step_norm < self.step_normalize_range[1]: print('step norm too small: ' + str(step_norm)) step = step * self.step_normalize_range[0] / step_norm # step = step * self.step_normalize_range / np.linalg.norm(step) self.robot.move_step(step) return step
40.769231
132
0.639832
338bb693099b86d452f675b3b919c130de2231c4
3,215
py
Python
yatube/yatube/settings.py
schactye/yatube_project
2079644fd183d925cbbac99815a78d69cdb65a19
[ "BSD-3-Clause" ]
1
2021-12-09T14:39:34.000Z
2021-12-09T14:39:34.000Z
yatube/yatube/settings.py
schactye/yatube_project
2079644fd183d925cbbac99815a78d69cdb65a19
[ "BSD-3-Clause" ]
null
null
null
yatube/yatube/settings.py
schactye/yatube_project
2079644fd183d925cbbac99815a78d69cdb65a19
[ "BSD-3-Clause" ]
null
null
null
""" Django settings for yatube project. Generated by 'django-admin startproject' using Django 2.2.19. For more information on this file, see https://docs.djangoproject.com/en/2.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.2/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '+=0eb3r&etny9dbx7!lyu0cl0i(_#0m3h33td6gh38#q^x_o@+' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'posts.apps.PostsConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'yatube.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'yatube.wsgi.application' # Database # https://docs.djangoproject.com/en/2.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/2.2/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.2/howto/static-files/ STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ]
25.72
91
0.696423
18233d29b8d797b1ab138c8b7f6972fb4d3fd56b
4,952
py
Python
tests/styles/parser/document_matcher_parser_tests.py
heekentertainment/python-mammoth
e8f71fc40b74e613c1737bf499076a0fc750283a
[ "BSD-2-Clause" ]
557
2015-01-19T20:06:31.000Z
2022-03-27T16:13:42.000Z
tests/styles/parser/document_matcher_parser_tests.py
heekentertainment/python-mammoth
e8f71fc40b74e613c1737bf499076a0fc750283a
[ "BSD-2-Clause" ]
111
2015-03-27T13:57:05.000Z
2022-03-09T21:06:51.000Z
tests/styles/parser/document_matcher_parser_tests.py
heekentertainment/python-mammoth
e8f71fc40b74e613c1737bf499076a0fc750283a
[ "BSD-2-Clause" ]
111
2015-03-26T11:47:23.000Z
2022-03-26T17:12:50.000Z
from nose.tools import istest, assert_equal from mammoth import documents, document_matchers from mammoth.styles.parser.document_matcher_parser import parse_document_matcher from mammoth.styles.parser.errors import LineParseError from mammoth.styles.parser.tokeniser import tokenise from mammoth.styles.parser.token_iterator import TokenIterator from ...testing import assert_raises @istest def unrecognised_document_element_raises_error(): error = assert_raises(LineParseError, lambda: read_document_matcher("x")) assert_equal("Unrecognised document element: x", str(error)) @istest def reads_plain_paragraph(): assert_equal( document_matchers.paragraph(), read_document_matcher("p") ) @istest def reads_paragraph_with_style_id(): assert_equal( document_matchers.paragraph(style_id="Heading1"), read_document_matcher("p.Heading1") ) @istest def reads_paragraph_with_exact_style_name(): assert_equal( document_matchers.paragraph(style_name=document_matchers.equal_to("Heading 1")), read_document_matcher("p[style-name='Heading 1']") ) @istest def reads_paragraph_with_style_name_prefix(): assert_equal( document_matchers.paragraph(style_name=document_matchers.starts_with("Heading")), read_document_matcher("p[style-name^='Heading']") ) @istest def unrecognised_string_matcher_raises_error(): error = assert_raises(LineParseError, lambda: read_document_matcher("p[style-name*='Heading']")) assert_equal("Unrecognised string matcher: *", str(error)) @istest def reads_paragraph_ordered_list(): assert_equal( document_matchers.paragraph(numbering=documents.numbering_level(1, is_ordered=True)), read_document_matcher("p:ordered-list(2)") ) @istest def reads_paragraph_unordered_list(): assert_equal( document_matchers.paragraph(numbering=documents.numbering_level(1, is_ordered=False)), read_document_matcher("p:unordered-list(2)") ) @istest def unrecognised_list_type_raises_error(): error = assert_raises(LineParseError, lambda: read_document_matcher("p:blah")) assert_equal("Unrecognised list type: blah", str(error)) @istest def reads_plain_run(): assert_equal( document_matchers.run(), read_document_matcher("r") ) @istest def reads_run_with_style_id(): assert_equal( document_matchers.run(style_id="Emphasis"), read_document_matcher("r.Emphasis") ) @istest def reads_run_with_style_name(): assert_equal( document_matchers.run(style_name=document_matchers.equal_to("Emphasis")), read_document_matcher("r[style-name='Emphasis']") ) @istest def reads_plain_table(): assert_equal( document_matchers.table(), read_document_matcher("table") ) @istest def reads_table_with_style_id(): assert_equal( document_matchers.table(style_id="TableNormal"), read_document_matcher("table.TableNormal") ) @istest def reads_table_with_style_name(): assert_equal( document_matchers.table(style_name=document_matchers.equal_to("Normal Table")), read_document_matcher("table[style-name='Normal Table']") ) @istest def reads_bold(): assert_equal( document_matchers.bold, read_document_matcher("b") ) @istest def reads_italic(): assert_equal( document_matchers.italic, read_document_matcher("i") ) @istest def reads_underline(): assert_equal( document_matchers.underline, read_document_matcher("u") ) @istest def reads_strikethrough(): assert_equal( document_matchers.strikethrough, read_document_matcher("strike") ) @istest def reads_all_caps(): assert_equal( document_matchers.all_caps, read_document_matcher("all-caps") ) @istest def reads_small_caps(): assert_equal( document_matchers.small_caps, read_document_matcher("small-caps") ) @istest def reads_comment_reference(): assert_equal( document_matchers.comment_reference, read_document_matcher("comment-reference") ) @istest def reads_line_breaks(): assert_equal( document_matchers.line_break, read_document_matcher("br[type='line']"), ) @istest def reads_page_breaks(): assert_equal( document_matchers.page_break, read_document_matcher("br[type='page']"), ) @istest def reads_column_breaks(): assert_equal( document_matchers.column_break, read_document_matcher("br[type='column']"), ) @istest def unrecognised_break_type_raises_error(): error = assert_raises(LineParseError, lambda: read_document_matcher("br[type='unknownBreakType']")) assert_equal("Unrecognised break type: unknownBreakType", str(error)) def read_document_matcher(string): return parse_document_matcher(TokenIterator(tokenise(string)))
24.27451
103
0.723142
c9fc7d773dfee37537a1c51fba03da0e73c47324
6,144
py
Python
utils/models.py
OmidSaj/HyDRA
de7c3fefd90fb965b47f3db75ed9c9349f4e54c8
[ "MIT" ]
2
2022-03-01T09:00:09.000Z
2022-03-01T09:00:23.000Z
utils/models.py
OmidSaj/HyDRA
de7c3fefd90fb965b47f3db75ed9c9349f4e54c8
[ "MIT" ]
null
null
null
utils/models.py
OmidSaj/HyDRA
de7c3fefd90fb965b47f3db75ed9c9349f4e54c8
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- """ Created on Sat Feb 19 13:26:47 2022 @author: Seyed Omid Sajedi """ from tensorflow.keras.regularizers import L1L2 from tensorflow.keras.layers import Input, Dense from tensorflow.keras.layers import concatenate as concat from tensorflow.keras.models import Model from tensorflow.keras.layers import Masking, GRU, Dropout from tensorflow.keras import backend as K import numpy as np def build_hydra(hydra_id:str='MWZ', nFeat_M:int=48, nFeat_W:int=48, nFeat_Z:int=14, drop_rate_GRU:float=0.08, drop_rate_dense:float=0.2, Bayesian_BN:bool=False, show_model_summary:bool=False): """ Parameters ---------- hydra_id : str, optional String containing the name of Hydra model branches (without spaces). Acceptable choices are any combinations of M,W and Z. The order in the input string is not important. However, the model's input list order is M, W, Z. For example, if the hydra_id='ZWM' or 'MZW', the model input will always be [M, W, Z] (or any subset). The default is 'MWZ'. nFeat_M : int, optional M branch input tensor channels feature dimension. The default is 48. nFeat_W : int, optional W branch input tensor channels feature dimension. The default is 48. nFeat_Z : int, optional Z branch input tensor(vector) channels feature . The default is 14. drop_rate_GRU : float, optional GRU layer dropout ratio. The default is 0.08. drop_rate_dense : float, optional Dense layer dropout ratio. The default is 0.2. Bayesian_BN : bool, optional If true, will add a dropout layer after each dense layer in both training and inference. Make sure the expected values are extracted with Monte Carlo Dropout Sampling if this option is set to True. The default is False. show_model_summary : bool, optional Print a summary of model architecture and the number of paramters. The default is False. Returns ------- The Hydra model. Input to the model is a list of input tensor in the order [M, W, Z] (or any subset) and the output is a single positive float. """ hydra_branches=['M','Z','W'] for branch_i in hydra_id: if branch_i not in hydra_branches: raise ValueError("Invalid branch %s, should be one of 'M','Z','W'"%(branch_i)) reg_kernel= L1L2(l1=1e-6, l2=1e-6) reg_bias=L1L2(l1=1e-6, l2=1e-6) reg_kernel_D= L1L2(l1=1e-5, l2=1e-5) reg_bias_D=L1L2(l1=1e-5, l2=1e-5) model_branches=[m_i for m_i in hydra_id] net_branch_list=[] input_layer_list=[] # ============================================================================= # M branch # ============================================================================= if 'M' in model_branches: M = Input(shape=(None, nFeat_M)) M_RNN=Masking(mask_value=0.0, input_shape=(None, nFeat_M))(M) M_RNN=GRU(300, activation='tanh',dropout=drop_rate_GRU,return_sequences=True, bias_regularizer=reg_bias,kernel_regularizer=reg_kernel)(M_RNN) M_RNN=GRU(50, activation='tanh',dropout=drop_rate_GRU, return_sequences=False, bias_regularizer=reg_bias,kernel_regularizer=reg_kernel)(M_RNN) input_layer_list.append(M) net_branch_list.append(M_RNN) # ============================================================================= # W branch # ============================================================================= if 'W' in model_branches: W = Input(shape=(None, nFeat_W)) W_RNN=Masking(mask_value=0.0, input_shape=(None, nFeat_W))(W) W_RNN=GRU(300, activation='tanh',dropout=drop_rate_GRU,return_sequences=True, bias_regularizer=reg_bias,kernel_regularizer=reg_kernel)(W_RNN) W_RNN=GRU(50, activation='tanh',dropout=drop_rate_GRU, return_sequences=False, bias_regularizer=reg_bias,kernel_regularizer=reg_kernel)(W_RNN) input_layer_list.append(W) net_branch_list.append(W_RNN) # ============================================================================= # Z branch # ============================================================================= if 'Z' in model_branches: Z = Input(shape=nFeat_Z) input_layer_list.append(Z) net_branch_list.append(Z) # ============================================================================= # Bottleneck # ============================================================================= if len(net_branch_list)>1: BNeck=concat(net_branch_list) else: # single input branch like: M, W, Z BNeck=net_branch_list[0] BNeck=Dense(500, activation='relu', bias_regularizer=reg_bias_D,kernel_regularizer=reg_kernel_D)(BNeck) if Bayesian_BN: BNeck=Dropout(drop_rate_dense)(BNeck,training=True) BNeck=Dense(500, activation='tanh', bias_regularizer=reg_bias_D,kernel_regularizer=reg_kernel_D)(BNeck) if Bayesian_BN: BNeck=Dropout(drop_rate_dense)(BNeck,training=True) Y=Dense(1, activation='relu', bias_regularizer=reg_bias_D,kernel_regularizer=reg_kernel_D)(BNeck) if len(input_layer_list)==1: input_layer_list=input_layer_list[0] model_hydra = Model(input_layer_list, Y) if show_model_summary: print(model_hydra.summary()) return model_hydra def mae_loss(y_true, y_pred): return K.mean(K.abs(y_true - y_pred)) def eval_r(Y_true,Y_pred): diff=np.abs(Y_true-Y_pred) diff2=np.power(diff,2) MAE=np.mean(diff) MSE=np.mean(diff2) return MAE,MSE def agg_Y(set_generator): for i in range(set_generator.n_batch): data_tuple_i=set_generator.__getitem__(i) if i==0: Y_gt=data_tuple_i[1] else: Y_gt=np.vstack((Y_gt,data_tuple_i[1])) return Y_gt
42.666667
109
0.585124
e1004ac953162ef3b2f72ded543e6683993ea206
756
py
Python
RecipeRecordingApp/urls.py
cs-fullstack-2019-spring/django-mini-project5-tdude0175
ebee9588a957e7bb44e3dfbe6877062c2a3f1402
[ "Apache-2.0" ]
null
null
null
RecipeRecordingApp/urls.py
cs-fullstack-2019-spring/django-mini-project5-tdude0175
ebee9588a957e7bb44e3dfbe6877062c2a3f1402
[ "Apache-2.0" ]
null
null
null
RecipeRecordingApp/urls.py
cs-fullstack-2019-spring/django-mini-project5-tdude0175
ebee9588a957e7bb44e3dfbe6877062c2a3f1402
[ "Apache-2.0" ]
null
null
null
from django.urls import path , include from . import views urlpatterns = \ [ # added all paths edir and recipe details want to go to specific pages # so they need id numbers for specific recipes path('',views.index, name='index'), path('NewUser/',views.NewUser , name='NewUser'), path('NewRecipe/',views.NewRecipe , name='NewRecipe'), path('AllRecipes/',views.AllRecipes , name='AllRecipes'), path('ProfilePage/',views.ProfilePage , name='ProfilePage'), path('EditRecipe/<int:RecipeID>/',views.EditRecipe , name='EditRecipe'), path('RecipeDetails/<int:RecipeID>/',views.RecipeDetails , name='RecipeDetails'), path('accounts/', include('django.contrib.auth.urls')), ]
44.470588
89
0.652116
48262c5e1de281cfb09feaf38ece035d6a17d11c
1,972
py
Python
Python/countStuff.py
kbroman/Paper_Rqtl_Experiences
9414b3826b242ce2f4f0306333cd108dcfd4680d
[ "CC-BY-3.0" ]
1
2021-11-06T05:34:34.000Z
2021-11-06T05:34:34.000Z
Python/countStuff.py
kbroman/Paper_Rqtl_Experiences
9414b3826b242ce2f4f0306333cd108dcfd4680d
[ "CC-BY-3.0" ]
null
null
null
Python/countStuff.py
kbroman/Paper_Rqtl_Experiences
9414b3826b242ce2f4f0306333cd108dcfd4680d
[ "CC-BY-3.0" ]
null
null
null
#!/usr/bin/env python # count stuff: # x- no. software releases # x- currently: no. lines C, R and doc code # x- amount of R vs C, rounded to tens # - scantwo R function: no. lines, as proportion of R code # - C code no. lines, as proportion of C code # and "more than x%" import re lines_file = "Data/lines_code_by_version.csv" lines = open(lines_file).readlines() isversion = [len(re.findall("^\d", line))>0 for line in lines] n_versions = sum(isversion) print 'n_versions =', n_versions nlines = lines[1].split(',') print 'lines_R =', nlines[2] print 'lines_C =', nlines[3] print 'lines_man =', nlines[4] scantwo_file = 'qtl/R/scantwo.R' import os.path if os.path.isfile(scantwo_file): delete_qtl = False else: delete_qtl = True from subprocess import call tar_file = '/Users/kbroman/Code/Rqtl/Backup/qtl_' + lines[1].split(',')[0] + '.tar.gz' call(['tar', 'xzf', tar_file]) # The following is an overly complicated method for counting lines in scantwo function lines = open(scantwo_file).readlines() firstline = 0 n_scantwo_lines = 0 n_brace = 0 for line in range(0, len(lines)): if len(re.findall("^scantwo ", lines[line])) > 0: firstline = line if firstline > 0: n_scantwo_lines += 1 n_forward = len(re.findall("{", lines[line])) n_backward = len(re.findall("}", lines[line])) n_brace += (n_forward - n_backward) if n_brace == 0 and firstline > 0 and line > firstline + 15: break print 'n_scantwo_lines =', n_scantwo_lines def countlines (file): import os n_lines = os.popen('wc -l ' + file).read().strip().split(' ')[0] return int(n_lines) # determine no. lines in scantwo C functions dir = 'qtl/src/' scantwo_c_files = [dir + file for file in os.listdir(dir) if len(re.findall("^scantwo.*\.c$", file))>0] n_scantwo_c_lines = sum( [countlines(file) for file in scantwo_c_files] ) print "n_scantwo_c_lines =", n_scantwo_c_lines # delete the qtl directory if delete_qtl: call(['rm', '-rf', 'qtl'])
27.013699
103
0.682049
244fd00430f170d78197da778ea3d298b2f9aaba
254
py
Python
advent_of_code_ocr/__version__.py
bsoyka/advent-of-code-ocr
b5a86d8284a58b76bf1c85fcdd8b38531c01cc08
[ "MIT" ]
4
2020-12-13T17:40:32.000Z
2021-12-13T13:26:19.000Z
advent_of_code_ocr/__version__.py
bsoyka/advent-of-code-ocr
b5a86d8284a58b76bf1c85fcdd8b38531c01cc08
[ "MIT" ]
11
2020-12-13T17:47:36.000Z
2022-01-30T03:51:59.000Z
advent_of_code_ocr/__version__.py
bsoyka/advent-of-code-ocr
b5a86d8284a58b76bf1c85fcdd8b38531c01cc08
[ "MIT" ]
3
2021-12-13T05:38:52.000Z
2021-12-13T12:23:38.000Z
__title__ = "advent-of-code-ocr" __description__ = "Convert Advent of Code ASCII art" __version__ = "0.2.0" __author__ = "Ben Soyka" __author_email__ = "bensoyka@icloud.com" __license__ = "MIT" __copyright__ = "Copyright (c) 2020-present Benjamin Soyka"
31.75
59
0.755906
669f40f26c1a535a3ca21a01faa11fd0eb1c814f
412
py
Python
algorithm/challenges/insertionsort.py
rishabhiitbhu/hackerrank
acc300851c81a29472177f15fd8b56ebebe853ea
[ "MIT" ]
null
null
null
algorithm/challenges/insertionsort.py
rishabhiitbhu/hackerrank
acc300851c81a29472177f15fd8b56ebebe853ea
[ "MIT" ]
null
null
null
algorithm/challenges/insertionsort.py
rishabhiitbhu/hackerrank
acc300851c81a29472177f15fd8b56ebebe853ea
[ "MIT" ]
1
2020-01-30T06:47:09.000Z
2020-01-30T06:47:09.000Z
def arrprint(arr): for i in arr: print(i, end=' ') print() def InsertionSort(arr, e): for i in range(len(arr)-2,-1,-1): if arr[i] > e: arr[i+1] = arr[i] arrprint(arr) elif arr[i] < e: arr[i+1] = e arrprint(arr) break if e not in arr: arr[0] = e arrprint(arr) size = int(input()) arr = [int(x) for x in input().strip().split(' ')] InsertionSort(arr, arr[size-1])
19.619048
51
0.548544
19d94ca91b70b7ad3ef51d8f505b7d1beb7b7039
5,860
py
Python
test/functional/p2p_fingerprint.py
cibadmin/GLBTC
52a0c8bfcb7abce8f97412dd1fd817335657896b
[ "MIT" ]
null
null
null
test/functional/p2p_fingerprint.py
cibadmin/GLBTC
52a0c8bfcb7abce8f97412dd1fd817335657896b
[ "MIT" ]
null
null
null
test/functional/p2p_fingerprint.py
cibadmin/GLBTC
52a0c8bfcb7abce8f97412dd1fd817335657896b
[ "MIT" ]
null
null
null
#!/usr/bin/env python3 # Copyright (c) 2017-2018 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test various fingerprinting protections. If a stale block more than a month old or its header are requested by a peer, the node should pretend that it does not have it to avoid fingerprinting. """ import time from test_framework.blocktools import (create_block, create_coinbase) from test_framework.messages import CInv from test_framework.mininode import ( P2PInterface, msg_headers, msg_block, msg_getdata, msg_getheaders, ) from test_framework.test_framework import GlobalBitcoinTestFramework from test_framework.util import ( assert_equal, wait_until, ) class P2PFingerprintTest(GlobalBitcoinTestFramework): def set_test_params(self): self.setup_clean_chain = True self.num_nodes = 1 def skip_test_if_missing_module(self): self.skip_if_no_wallet() # Build a chain of blocks on top of given one def build_chain(self, nblocks, prev_hash, prev_height, prev_median_time): blocks = [] for _ in range(nblocks): coinbase = create_coinbase(prev_height + 1) block_time = prev_median_time + 1 block = create_block(int(prev_hash, 16), coinbase, block_time) block.solve() blocks.append(block) prev_hash = block.hash prev_height += 1 prev_median_time = block_time return blocks # Send a getdata request for a given block hash def send_block_request(self, block_hash, node): msg = msg_getdata() msg.inv.append(CInv(2, block_hash)) # 2 == "Block" node.send_message(msg) # Send a getheaders request for a given single block hash def send_header_request(self, block_hash, node): msg = msg_getheaders() msg.hashstop = block_hash node.send_message(msg) # Check whether last block received from node has a given hash def last_block_equals(self, expected_hash, node): block_msg = node.last_message.get("block") return block_msg and block_msg.block.rehash() == expected_hash # Check whether last block header received from node has a given hash def last_header_equals(self, expected_hash, node): headers_msg = node.last_message.get("headers") return (headers_msg and headers_msg.headers and headers_msg.headers[0].rehash() == expected_hash) # Checks that stale blocks timestamped more than a month ago are not served # by the node while recent stale blocks and old active chain blocks are. # This does not currently test that stale blocks timestamped within the # last month but that have over a month's worth of work are also withheld. def run_test(self): node0 = self.nodes[0].add_p2p_connection(P2PInterface()) # Set node time to 60 days ago self.nodes[0].setmocktime(int(time.time()) - 60 * 24 * 60 * 60) # Generating a chain of 10 blocks block_hashes = self.nodes[0].generate(nblocks=10) # Create longer chain starting 2 blocks before current tip height = len(block_hashes) - 2 block_hash = block_hashes[height - 1] block_time = self.nodes[0].getblockheader(block_hash)["mediantime"] + 1 new_blocks = self.build_chain(5, block_hash, height, block_time) # Force reorg to a longer chain node0.send_message(msg_headers(new_blocks)) node0.wait_for_getdata() for block in new_blocks: node0.send_and_ping(msg_block(block)) # Check that reorg succeeded assert_equal(self.nodes[0].getblockcount(), 13) stale_hash = int(block_hashes[-1], 16) # Check that getdata request for stale block succeeds self.send_block_request(stale_hash, node0) test_function = lambda: self.last_block_equals(stale_hash, node0) wait_until(test_function, timeout=3) # Check that getheader request for stale block header succeeds self.send_header_request(stale_hash, node0) test_function = lambda: self.last_header_equals(stale_hash, node0) wait_until(test_function, timeout=3) # Longest chain is extended so stale is much older than chain tip self.nodes[0].setmocktime(0) tip = self.nodes[0].generate(nblocks=1)[0] assert_equal(self.nodes[0].getblockcount(), 14) # Send getdata & getheaders to refresh last received getheader message block_hash = int(tip, 16) self.send_block_request(block_hash, node0) self.send_header_request(block_hash, node0) node0.sync_with_ping() # Request for very old stale block should now fail self.send_block_request(stale_hash, node0) time.sleep(3) assert not self.last_block_equals(stale_hash, node0) # Request for very old stale block header should now fail self.send_header_request(stale_hash, node0) time.sleep(3) assert not self.last_header_equals(stale_hash, node0) # Verify we can fetch very old blocks and headers on the active chain block_hash = int(block_hashes[2], 16) self.send_block_request(block_hash, node0) self.send_header_request(block_hash, node0) node0.sync_with_ping() self.send_block_request(block_hash, node0) test_function = lambda: self.last_block_equals(block_hash, node0) wait_until(test_function, timeout=3) self.send_header_request(block_hash, node0) test_function = lambda: self.last_header_equals(block_hash, node0) wait_until(test_function, timeout=3) if __name__ == '__main__': P2PFingerprintTest().main()
38.552632
79
0.689249
6c9a4a78d51844e20a2dde506761ac16178962a6
11,864
py
Python
geomstats/geometry/positive_lower_triangular_matrices.py
chicken-biryani/geomstats
414b6832c63df60788eda934c694d68fc939708f
[ "MIT" ]
null
null
null
geomstats/geometry/positive_lower_triangular_matrices.py
chicken-biryani/geomstats
414b6832c63df60788eda934c694d68fc939708f
[ "MIT" ]
null
null
null
geomstats/geometry/positive_lower_triangular_matrices.py
chicken-biryani/geomstats
414b6832c63df60788eda934c694d68fc939708f
[ "MIT" ]
null
null
null
"""The manifold of lower triangular matrices with positive diagonal elements. Lead author: Saiteja Utpala. """ import geomstats.backend as gs from geomstats.geometry.base import OpenSet from geomstats.geometry.lower_triangular_matrices import LowerTriangularMatrices from geomstats.geometry.matrices import Matrices from geomstats.geometry.riemannian_metric import RiemannianMetric class PositiveLowerTriangularMatrices(OpenSet): """Manifold of lower triangular matrices with >0 diagonal. This manifold is also called the cholesky space. Parameters ---------- n : int Integer representing the shape of the matrices: n x n. References ---------- .. [TP2019] . "Riemannian Geometry of Symmetric Positive Definite Matrices Via Cholesky Decomposition" SIAM journal on Matrix Analysis and Applications , 2019. https://arxiv.org/abs/1908.09326 """ def __init__(self, n, **kwargs): kwargs.setdefault("metric", CholeskyMetric(n)) super(PositiveLowerTriangularMatrices, self).__init__( dim=int(n * (n + 1) / 2), ambient_space=LowerTriangularMatrices(n), **kwargs ) self.n = n def random_point(self, n_samples=1, bound=1.0): """Sample from the manifold. Parameters ---------- n_samples : int Number of samples. Optional, default: 1. bound : float Side of hypercube support of the uniform distribution. Optional, default: 1.0 Returns ------- point : array-like, shape=[..., n, n] Sample. """ sample = super(PositiveLowerTriangularMatrices, self).random_point( n_samples, bound ) return self.projection(sample) def belongs(self, mat, atol=gs.atol): """Check if mat is lower triangular with >0 diagonal. Parameters ---------- mat : array-like, shape=[..., n, n] Matrix to be checked. atol : float Tolerance. Optional, default: backend atol. Returns ------- belongs : array-like, shape=[...,] Boolean denoting if mat belongs to cholesky space. """ is_lower_triangular = self.ambient_space.belongs(mat, atol) diagonal = Matrices.diagonal(mat) is_positive = gs.all(diagonal > 0, axis=-1) belongs = gs.logical_and(is_lower_triangular, is_positive) return belongs def projection(self, point): """Project a matrix to the Cholesksy space. First it is projected to space lower triangular matrices and then diagonal elements are exponentiated to make it positive. Parameters ---------- point : array-like, shape=[..., n, n] Matrix to project. Returns ------- projected: array-like, shape=[..., n, n] SPD matrix. """ vec_diag = gs.abs(Matrices.diagonal(point) - 0.1) + 0.1 diag = gs.vec_to_diag(vec_diag) strictly_lower_triangular = Matrices.to_lower_triangular(point) projection = diag + strictly_lower_triangular return projection @staticmethod def gram(point): """Compute gram matrix of rows. Gram_matrix is mapping from point to point.point^{T}. This is diffeomorphism between cholesky space and spd manifold. Parameters ---------- point : array-like, shape=[..., n, n] element in cholesky space. Returns ------- projected: array-like, shape=[..., n, n] SPD matrix. """ return gs.einsum("...ij,...kj->...ik", point, point) @staticmethod def differential_gram(tangent_vec, base_point): """Compute differential of gram. Parameters ---------- tangent_vec : array_like, shape=[..., n, n] Tangent vector at base point. Symmetric Matrix. base_point : array_like, shape=[..., n, n] Base point. Returns ------- differential_gram : array-like, shape=[..., n, n] Differential of the gram. """ mat1 = gs.einsum("...ij,...kj->...ik", tangent_vec, base_point) mat2 = gs.einsum("...ij,...kj->...ik", base_point, tangent_vec) return mat1 + mat2 @staticmethod def inverse_differential_gram(tangent_vec, base_point): """Compute inverse differential of gram map. Parameters ---------- tangent_vec : array_like, shape=[..., n, n] tanget vector at gram(base_point) Symmetric Matrix. base_point : array_like, shape=[..., n, n] Base point. Returns ------- inverse_differential_gram : array-like, shape=[..., n, n] Inverse differential of gram. Lower triangular matrix. """ inv_base_point = gs.linalg.inv(base_point) inv_transpose_base_point = Matrices.transpose(inv_base_point) aux = Matrices.to_lower_triangular_diagonal_scaled( Matrices.mul(inv_base_point, tangent_vec, inv_transpose_base_point) ) inverse_differential_gram = Matrices.mul(base_point, aux) return inverse_differential_gram class CholeskyMetric(RiemannianMetric): """Class for cholesky metric on cholesky space. Parameters ---------- n : int Integer representing the shape of the matrices: n x n. References ---------- .. [TP2019] . "Riemannian Geometry of Symmetric Positive Definite Matrices Via Cholesky Decomposition" SIAM journal on Matrix Analysis and Applications , 2019. https://arxiv.org/abs/1908.09326 """ def __init__(self, n): """ """ dim = int(n * (n + 1) / 2) super(CholeskyMetric, self).__init__( dim=dim, signature=(dim, 0), default_point_type="matrix" ) self.n = n @staticmethod def diag_inner_product(tangent_vec_a, tangent_vec_b, base_point): """Compute the inner product using only diagonal elements. Parameters ---------- tangent_vec_a : array-like, shape=[..., n, n] Tangent vector at base point. tangent_vec_b : array-like, shape=[..., n, n] Tangent vector at base point. base_point : array-like, shape=[..., n, n] Base point. Returns ------- ip_diagonal : array-like, shape=[...] Inner-product. """ inv_sqrt_diagonal = gs.power(Matrices.diagonal(base_point), -2) tangent_vec_a_diagonal = Matrices.diagonal(tangent_vec_a) tangent_vec_b_diagonal = Matrices.diagonal(tangent_vec_b) prod = tangent_vec_a_diagonal * tangent_vec_b_diagonal * inv_sqrt_diagonal ip_diagonal = gs.sum(prod, axis=-1) return ip_diagonal @staticmethod def strictly_lower_inner_product(tangent_vec_a, tangent_vec_b): """Compute the inner product using only strictly lower triangular elements. Parameters ---------- tangent_vec_a : array-like, shape=[..., n, n] Tangent vector at base point. tangent_vec_b : array-like, shape=[..., n, n] Tangent vector at base point. Returns ------- ip_sl : array-like, shape=[...] Inner-product. """ sl_tagnet_vec_a = gs.tril_to_vec(tangent_vec_a, k=-1) sl_tagnet_vec_b = gs.tril_to_vec(tangent_vec_b, k=-1) ip_sl = gs.einsum("...i,...i->...", sl_tagnet_vec_a, sl_tagnet_vec_b) return ip_sl @classmethod def inner_product(cls, tangent_vec_a, tangent_vec_b, base_point): """Compute the inner product. Compute the inner-product of tangent_vec_a and tangent_vec_b at point base_point using the cholesky Riemannian metric. Parameters ---------- tangent_vec_a : array-like, shape=[..., n, n] Tangent vector at base point. tangent_vec_b : array-like, shape=[..., n, n] Tangent vector at base point. base_point : array-like, shape=[..., n, n] Base point. Returns ------- inner_product : array-like, shape=[...] Inner-product. """ diag_inner_product = cls.diag_inner_product( tangent_vec_a, tangent_vec_b, base_point ) strictly_lower_inner_product = cls.strictly_lower_inner_product( tangent_vec_a, tangent_vec_b ) return diag_inner_product + strictly_lower_inner_product def exp(self, tangent_vec, base_point, **kwargs): """Compute the Cholesky exponential map. Compute the Riemannian exponential at point base_point of tangent vector tangent_vec wrt the Cholesky metric. This gives a lower triangular matrix with positive elements. Parameters ---------- tangent_vec : array-like, shape=[..., n, n] Tangent vector at base point. base_point : array-like, shape=[..., n, n] Base point. Returns ------- exp : array-like, shape=[..., n, n] Riemannian exponential. """ sl_base_point = Matrices.to_strictly_lower_triangular(base_point) sl_tangent_vec = Matrices.to_strictly_lower_triangular(tangent_vec) diag_base_point = Matrices.diagonal(base_point) diag_tangent_vec = Matrices.diagonal(tangent_vec) diag_product_expm = gs.exp(gs.divide(diag_tangent_vec, diag_base_point)) sl_exp = sl_base_point + sl_tangent_vec diag_exp = gs.vec_to_diag(diag_base_point * diag_product_expm) exp = sl_exp + diag_exp return exp def log(self, point, base_point, **kwargs): """Compute the Cholesky logarithm map. Compute the Riemannian logarithm at point base_point, of point wrt the Cholesky metric. This gives a tangent vector at point base_point. Parameters ---------- point : array-like, shape=[..., n, n] Point. base_point : array-like, shape=[..., n, n] Base point. Returns ------- log : array-like, shape=[..., n, n] Riemannian logarithm. """ sl_base_point = Matrices.to_strictly_lower_triangular(base_point) sl_point = Matrices.to_strictly_lower_triangular(point) diag_base_point = Matrices.diagonal(base_point) diag_point = Matrices.diagonal(point) diag_product_logm = gs.log(gs.divide(diag_point, diag_base_point)) sl_log = sl_point - sl_base_point diag_log = gs.vec_to_diag(diag_base_point * diag_product_logm) log = sl_log + diag_log return log def squared_dist(self, point_a, point_b, **kwargs): """Compute the Cholesky Metric squared distance. Compute the Riemannian squared distance between point_a and point_b. Parameters ---------- point_a : array-like, shape=[..., n, n] Point. point_b : array-like, shape=[..., n, n] Point. Returns ------- _ : array-like, shape=[...] Riemannian squared distance. """ log_diag_a = gs.log(Matrices.diagonal(point_a)) log_diag_b = gs.log(Matrices.diagonal(point_b)) diag_diff = log_diag_a - log_diag_b squared_dist_diag = gs.sum((diag_diff) ** 2, axis=-1) sl_a = Matrices.to_strictly_lower_triangular(point_a) sl_b = Matrices.to_strictly_lower_triangular(point_b) sl_diff = sl_a - sl_b squared_dist_sl = Matrices.frobenius_product(sl_diff, sl_diff) return squared_dist_sl + squared_dist_diag
33.139665
88
0.600556
a22dffa1a75cccbcf07c24fcf5ae00e66e64a9fd
3,604
py
Python
ivory/utils/range.py
daizutabi/ivory
d961e6c05ece112d99b8f8c2d6dad530f60b7303
[ "MIT" ]
1
2019-05-16T10:38:53.000Z
2019-05-16T10:38:53.000Z
ivory/utils/range.py
daizutabi/ivory
d961e6c05ece112d99b8f8c2d6dad530f60b7303
[ "MIT" ]
null
null
null
ivory/utils/range.py
daizutabi/ivory
d961e6c05ece112d99b8f8c2d6dad530f60b7303
[ "MIT" ]
null
null
null
import ast import re import numpy as np class Range: def __init__(self, start, stop=None, step=1, num: int = 0, log: bool = False): if isinstance(start, str): start, stop, step, num, log = parse(start) elif stop is None: start, stop = 0, start self.start = start self.stop = stop self.step = step self.num = num self.log = log if log and step != 1: raise ValueError("Invalid step.") @property def is_integer(self): return all(isinstance(x, int) for x in [self.start, self.stop, self.step]) @property def is_float(self): return not self.is_integer def __repr__(self): class_name = self.__class__.__name__ s = f"{class_name}({self.start}, {self.stop}" if self.step != 1: s += f", {self.step}" if self.num >= 2: s += f", n={self.num}" if self.log: s += f", log={self.log}" return s + ")" def __iter__(self): if self.is_integer: if self.start < self.stop: it = range(self.start, self.stop + 1, self.step) else: it = range(self.start, self.stop - 1, -self.step) if self.num < 2: return iter(it) else: values = list(it) index = np.linspace(0, len(values) - 1, self.num) return (values[int(round(x))] for x in index) else: num = self.num if self.log: if self.num < 2: raise ValueError(f"num must be larger than 1, but {num} given.") start = np.log10(self.start) stop = np.log10(self.stop) return iter(float(x) for x in np.logspace(start, stop, num)) else: if num < 2: num = round(abs(self.stop - self.start) / self.step + 1) return iter(float(x) for x in np.linspace(self.start, self.stop, num)) def __len__(self): return len(list(iter(self))) def parse(value: str): """ Examples: >>> parse('2-3') (2, 3, 1, 0, False) >>> parse('2-4-2') (2, 4, 2, 0, False) >>> parse('2-4:3') (2, 4, 1, 3, False) >>> parse('0-1-0.2') (0, 1, 0.2, 0, False) >>> parse('0-1:5') (0, 1, 1, 5, False) >>> parse('0-1.log') (0, 1, 1, 0, True) >>> parse('1e-3_1e-2.log') (0.001, 0.01, 1, 0, True) """ num = 0 log = False if value.endswith(".log"): value = value[:-4] log = True if ":" in value: value, num_str = value.split(":") num = int(num_str) sep = "_" if "_" in value else "-" match = re.match(f"(.+){sep}(.+)", value) if not match: raise ValueError(f"Invalid string for Range: {value}") if sep in match.group(1): if num != 0: raise ValueError(f"Invalid string for Range: {value}") start, stop = match.group(1).split(sep) step = match.group(2) else: start = match.group(1) stop = match.group(2) step = "1" start = literal_eval(start) stop = literal_eval(stop) step = literal_eval(step) if all(isinstance(x, (int, float)) for x in [start, stop, step]): return start, stop, step, num, log raise ValueError(f"Invalid string for Range: {value}") def literal_eval(value): try: return ast.literal_eval(value) except ValueError: return value
29.785124
86
0.498058
d531223163e1754d1caf2a781a0cad6d80c3ba96
1,286
py
Python
gentelella/app/auth/utils.py
Dhvani35729/Trofi-Dashboard
a49b4cbac964e60ea3124e4808ba88ef7256a8fe
[ "MIT" ]
null
null
null
gentelella/app/auth/utils.py
Dhvani35729/Trofi-Dashboard
a49b4cbac964e60ea3124e4808ba88ef7256a8fe
[ "MIT" ]
null
null
null
gentelella/app/auth/utils.py
Dhvani35729/Trofi-Dashboard
a49b4cbac964e60ea3124e4808ba88ef7256a8fe
[ "MIT" ]
null
null
null
from ..config import authe, db def forgot_password(email): authe.send_password_reset_email(email) # check if user is logged in def logged_in(request): try: return request.session['uid'] except KeyError: return None def get_res_public_id(uid): map_ref = db.collection(u'general').document( "trofi-verification").collection(uid).document("map") try: map_data = map_ref.get().to_dict() return map_data["public_id"], None except Exception as e: return None, e def is_valid_trofi_code(code): code_ref = db.collection(u'general').document(u'trofi-verification') try: code_data = code_ref.get() if code in code_data.to_dict()["accepted_codes_unused"]: return True else: return False except Exception as e: return None def should_allow_user_in(public_id, uid): res_ref = db.collection(u'restaurants').document(public_id) res_private_ref = res_ref.collection(u'private').document(uid) try: res_private_data = res_private_ref.get().to_dict() if res_private_data["allow_in"]: return True, res_private_data else: return False, None except Exception as e: return None, None
24.730769
72
0.650078
1e8238171712b4886efff86eb753d4cc2c788f8f
1,114
py
Python
python/proxy2.py
kettlewell/bashisms
c6222424984264c7c6488f20ea5591ff5078d040
[ "MIT" ]
null
null
null
python/proxy2.py
kettlewell/bashisms
c6222424984264c7c6488f20ea5591ff5078d040
[ "MIT" ]
null
null
null
python/proxy2.py
kettlewell/bashisms
c6222424984264c7c6488f20ea5591ff5078d040
[ "MIT" ]
null
null
null
#!/usr/bin/env python3 # Create a SSH connection import paramiko import os import pprint pp = pprint.PrettyPrinter(indent=4) ssh = paramiko.SSHClient() ssh._policy = paramiko.WarningPolicy() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh_config = paramiko.SSHConfig() user_config_file = os.path.expanduser("~/.ssh/config") if os.path.exists(user_config_file): with open(user_config_file) as f: ssh_config.parse(f) cfg = {'hostname': 'dr-gfs00702.svale.netledger.com'} user_config = ssh_config.lookup(cfg['hostname']) cfg["hostname"] = user_config["hostname"] cfg["username"] = user_config["user"] if 'identityfile' in user_config: cfg['key_filename'] = user_config['identityfile'] #key=paramiko.RSAKey.from_private_key_file(pkey) #cfg["pkey"] = key if 'proxycommand' in user_config: cfg['sock'] = paramiko.ProxyCommand(user_config['proxycommand']) ssh.connect(**cfg) stdin, stdout, stderr = ssh.exec_command("ls -al") for out_line in stdout.readlines(): pp.pprint(out_line) for err_line in stderr.readlines(): pp.pprint(err_line) ssh.close()
24.217391
67
0.728905
774de5e49a408e88a335706a1084002148f2bf44
863
py
Python
app/config_dev.py
xtianmcd/coca_coda_app
66c24f95340df80df7fb9c0393ad486cb22c7dd8
[ "MIT" ]
null
null
null
app/config_dev.py
xtianmcd/coca_coda_app
66c24f95340df80df7fb9c0393ad486cb22c7dd8
[ "MIT" ]
null
null
null
app/config_dev.py
xtianmcd/coca_coda_app
66c24f95340df80df7fb9c0393ad486cb22c7dd8
[ "MIT" ]
null
null
null
import logging from app.config_common import * # DEBUG can only be set to True in a development environment for security reasons DEBUG = True # Secret key for generating tokens SECRET_KEY = 'houdini' # Admin credentials ADMIN_CREDENTIALS = ('admin', 'pa$$word') # Database choice SQLALCHEMY_DATABASE_URI = 'sqlite:///app.db' SQLALCHEMY_TRACK_MODIFICATIONS = True # Configuration of a Gmail account for sending mails MAIL_SERVER = 'smtp.googlemail.com' MAIL_PORT = 465 MAIL_USE_TLS = False MAIL_USE_SSL = True MAIL_USERNAME = 'flask.boilerplate' MAIL_PASSWORD = 'flaskboilerplate123' ADMINS = ['flask.boilerplate@gmail.com'] # Number of times a password is hashed BCRYPT_LOG_ROUNDS = 12 LOG_LEVEL = logging.DEBUG LOG_FILENAME = 'activity.log' LOG_MAXBYTES = 1024 LOG_BACKUPS = 2 UPLOAD_FOLDER = '/Users/xtian/Documents/GitHub/coca_coda_app/app/uploads/'
23.324324
81
0.780997
5d63cdf3c132b705c839d94469457f2d11d325ab
2,147
py
Python
quora_parser/filter_question_links.py
ilkoretskiy/Parsers
46528f88b3784c9cc26b05b8b8ae9ac7d974de45
[ "MIT" ]
null
null
null
quora_parser/filter_question_links.py
ilkoretskiy/Parsers
46528f88b3784c9cc26b05b8b8ae9ac7d974de45
[ "MIT" ]
null
null
null
quora_parser/filter_question_links.py
ilkoretskiy/Parsers
46528f88b3784c9cc26b05b8b8ae9ac7d974de45
[ "MIT" ]
null
null
null
import os import json import logging import shutil from quoraparser.utils import create_logger logger = logging.getLogger("parser") def exist_questions(): path = "/Users/jesterilianight/Documents/sources/projects/quora_parser/result_processed" files = [] for item in os.listdir(path): if "json" in item: files.append(item.split(".")[0]) return files def dump_new_questions(questions, dest_file): with open(dest_file, "w") as f: json.dump(questions, f, indent=2) def main(): processed_questions = exist_questions() unique_processed_questions = set(processed_questions) new_questions = [] topics_dir = "./question_links" filtered_topics_dir = "./filtered_question_links" os.makedirs(filtered_topics_dir, exist_ok=True) json_files = os.listdir(topics_dir) topics_count = len(json_files) for idx, item in enumerate(json_files): logger.info("Processing file {}; {} / {}".format(idx, item, topics_count)) full_json_path = os.path.join(topics_dir, item) if ".json" in item: with open(full_json_path) as f: data = json.load(f) for question in data: if question in unique_processed_questions: logger.info("\tSkip processed question {}".format(question)) continue else: if "/unanswered/" in question: logger.info("\tSkip unanswered question {}".format(question)) continue else: logger.info("\tProcess question {}".format(question)) new_questions.append(question) new_questions = list(set(new_questions)) full_dest_json_path = os.path.join(filtered_topics_dir, item) shutil.move(full_json_path, full_dest_json_path) #write in temp file all questions #dump_new_questions(new_questions, "temp_new_questions.json") dump_new_questions(new_questions, "result.json") if __name__ == "__main__": create_logger("filter_topic_links") main()
30.671429
92
0.630647
81f193605569023827614b4ff30ba9973931d5b4
1,145
py
Python
deploy/streetwise-prod/versions/8ce4e9d93356_.py
Streetwise/streetwise-app
13c1649077766e0e20d6903adcd057ae3c07cc9c
[ "MIT" ]
1
2020-05-28T06:50:01.000Z
2020-05-28T06:50:01.000Z
deploy/streetwise-prod/versions/8ce4e9d93356_.py
Streetwise/streetwise-app
13c1649077766e0e20d6903adcd057ae3c07cc9c
[ "MIT" ]
72
2020-05-01T11:11:17.000Z
2022-02-14T09:01:50.000Z
deploy/streetwise-prod/versions/8ce4e9d93356_.py
Streetwise/streetwise-app
13c1649077766e0e20d6903adcd057ae3c07cc9c
[ "MIT" ]
3
2020-05-06T20:35:32.000Z
2020-05-07T15:00:51.000Z
"""empty message Revision ID: 8ce4e9d93356 Revises: ae4855a2d99d Create Date: 2020-05-08 16:01:11.797745 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '8ce4e9d93356' down_revision = 'ae4855a2d99d' branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_table('comments') op.add_column('votes', sa.Column('comment', sa.Text(), nullable=True)) # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_column('votes', 'comment') op.create_table('comments', sa.Column('id', sa.INTEGER(), nullable=False), sa.Column('created', sa.DATETIME(), nullable=True), sa.Column('session_id', sa.INTEGER(), nullable=True), sa.Column('image_id', sa.INTEGER(), nullable=True), sa.Column('text', sa.TEXT(), nullable=True), sa.ForeignKeyConstraint(['image_id'], ['images.id'], ), sa.ForeignKeyConstraint(['session_id'], ['sessions.id'], ), sa.PrimaryKeyConstraint('id') ) # ### end Alembic commands ###
28.625
74
0.670742
893fc5419f99e4e2c0a995b951b734f3c1786ac8
10,429
py
Python
venv/Lib/site-packages/matplotlib/tests/test_category.py
AdarshSai/Final_project
f966834ca72dd232102ed500ef47ef2b3bdbed5b
[ "MIT" ]
353
2020-12-10T10:47:17.000Z
2022-03-31T23:08:29.000Z
venv/Lib/site-packages/matplotlib/tests/test_category.py
AdarshSai/Final_project
f966834ca72dd232102ed500ef47ef2b3bdbed5b
[ "MIT" ]
80
2020-12-10T09:54:22.000Z
2022-03-30T22:08:45.000Z
venv/Lib/site-packages/matplotlib/tests/test_category.py
AdarshSai/Final_project
f966834ca72dd232102ed500ef47ef2b3bdbed5b
[ "MIT" ]
63
2020-12-10T17:10:34.000Z
2022-03-28T16:27:07.000Z
"""Catch all for categorical functions""" import pytest import numpy as np from matplotlib.axes import Axes import matplotlib.pyplot as plt import matplotlib.category as cat class TestUnitData: test_cases = [('single', (["hello world"], [0])), ('unicode', (["Здравствуйте мир"], [0])), ('mixed', (['A', "np.nan", 'B', "3.14", "мир"], [0, 1, 2, 3, 4]))] ids, data = zip(*test_cases) @pytest.mark.parametrize("data, locs", data, ids=ids) def test_unit(self, data, locs): unit = cat.UnitData(data) assert list(unit._mapping.keys()) == data assert list(unit._mapping.values()) == locs def test_update(self): data = ['a', 'd'] locs = [0, 1] data_update = ['b', 'd', 'e'] unique_data = ['a', 'd', 'b', 'e'] updated_locs = [0, 1, 2, 3] unit = cat.UnitData(data) assert list(unit._mapping.keys()) == data assert list(unit._mapping.values()) == locs unit.update(data_update) assert list(unit._mapping.keys()) == unique_data assert list(unit._mapping.values()) == updated_locs failing_test_cases = [("number", 3.14), ("nan", np.nan), ("list", [3.14, 12]), ("mixed type", ["A", 2])] fids, fdata = zip(*test_cases) @pytest.mark.parametrize("fdata", fdata, ids=fids) def test_non_string_fails(self, fdata): with pytest.raises(TypeError): cat.UnitData(fdata) @pytest.mark.parametrize("fdata", fdata, ids=fids) def test_non_string_update_fails(self, fdata): unitdata = cat.UnitData() with pytest.raises(TypeError): unitdata.update(fdata) class FakeAxis: def __init__(self, units): self.units = units class TestStrCategoryConverter: """ Based on the pandas conversion and factorization tests: ref: /pandas/tseries/tests/test_converter.py /pandas/tests/test_algos.py:TestFactorize """ test_cases = [("unicode", ["Здравствуйте мир"]), ("ascii", ["hello world"]), ("single", ['a', 'b', 'c']), ("integer string", ["1", "2"]), ("single + values>10", ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"])] ids, values = zip(*test_cases) failing_test_cases = [("mixed", [3.14, 'A', np.inf]), ("string integer", ['42', 42])] fids, fvalues = zip(*failing_test_cases) @pytest.fixture(autouse=True) def mock_axis(self, request): self.cc = cat.StrCategoryConverter() # self.unit should be probably be replaced with real mock unit self.unit = cat.UnitData() self.ax = FakeAxis(self.unit) @pytest.mark.parametrize("vals", values, ids=ids) def test_convert(self, vals): np.testing.assert_allclose(self.cc.convert(vals, self.ax.units, self.ax), range(len(vals))) @pytest.mark.parametrize("value", ["hi", "мир"], ids=["ascii", "unicode"]) def test_convert_one_string(self, value): assert self.cc.convert(value, self.unit, self.ax) == 0 def test_convert_one_number(self): actual = self.cc.convert(0.0, self.unit, self.ax) np.testing.assert_allclose(actual, np.array([0.])) def test_convert_float_array(self): data = np.array([1, 2, 3], dtype=float) actual = self.cc.convert(data, self.unit, self.ax) np.testing.assert_allclose(actual, np.array([1., 2., 3.])) @pytest.mark.parametrize("fvals", fvalues, ids=fids) def test_convert_fail(self, fvals): with pytest.raises(TypeError): self.cc.convert(fvals, self.unit, self.ax) def test_axisinfo(self): axis = self.cc.axisinfo(self.unit, self.ax) assert isinstance(axis.majloc, cat.StrCategoryLocator) assert isinstance(axis.majfmt, cat.StrCategoryFormatter) def test_default_units(self): assert isinstance(self.cc.default_units(["a"], self.ax), cat.UnitData) @pytest.fixture def ax(): return plt.figure().subplots() PLOT_LIST = [Axes.scatter, Axes.plot, Axes.bar] PLOT_IDS = ["scatter", "plot", "bar"] class TestStrCategoryLocator: def test_StrCategoryLocator(self): locs = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] unit = cat.UnitData([str(j) for j in locs]) ticks = cat.StrCategoryLocator(unit._mapping) np.testing.assert_array_equal(ticks.tick_values(None, None), locs) @pytest.mark.parametrize("plotter", PLOT_LIST, ids=PLOT_IDS) def test_StrCategoryLocatorPlot(self, ax, plotter): ax.plot(["a", "b", "c"]) np.testing.assert_array_equal(ax.yaxis.major.locator(), range(3)) class TestStrCategoryFormatter: test_cases = [("ascii", ["hello", "world", "hi"]), ("unicode", ["Здравствуйте", "привет"])] ids, cases = zip(*test_cases) @pytest.mark.parametrize("ydata", cases, ids=ids) def test_StrCategoryFormatter(self, ax, ydata): unit = cat.UnitData(ydata) labels = cat.StrCategoryFormatter(unit._mapping) for i, d in enumerate(ydata): assert labels(i, i) == d assert labels(i, None) == d @pytest.mark.parametrize("ydata", cases, ids=ids) @pytest.mark.parametrize("plotter", PLOT_LIST, ids=PLOT_IDS) def test_StrCategoryFormatterPlot(self, ax, ydata, plotter): plotter(ax, range(len(ydata)), ydata) for i, d in enumerate(ydata): assert ax.yaxis.major.formatter(i) == d assert ax.yaxis.major.formatter(i+1) == "" def axis_test(axis, labels): ticks = list(range(len(labels))) np.testing.assert_array_equal(axis.get_majorticklocs(), ticks) graph_labels = [axis.major.formatter(i, i) for i in ticks] # _text also decodes bytes as utf-8. assert graph_labels == [cat.StrCategoryFormatter._text(l) for l in labels] assert list(axis.units._mapping.keys()) == [l for l in labels] assert list(axis.units._mapping.values()) == ticks class TestPlotBytes: bytes_cases = [('string list', ['a', 'b', 'c']), ('bytes list', [b'a', b'b', b'c']), ('bytes ndarray', np.array([b'a', b'b', b'c']))] bytes_ids, bytes_data = zip(*bytes_cases) @pytest.mark.parametrize("plotter", PLOT_LIST, ids=PLOT_IDS) @pytest.mark.parametrize("bdata", bytes_data, ids=bytes_ids) def test_plot_bytes(self, ax, plotter, bdata): counts = np.array([4, 6, 5]) plotter(ax, bdata, counts) axis_test(ax.xaxis, bdata) class TestPlotNumlike: numlike_cases = [('string list', ['1', '11', '3']), ('string ndarray', np.array(['1', '11', '3'])), ('bytes list', [b'1', b'11', b'3']), ('bytes ndarray', np.array([b'1', b'11', b'3']))] numlike_ids, numlike_data = zip(*numlike_cases) @pytest.mark.parametrize("plotter", PLOT_LIST, ids=PLOT_IDS) @pytest.mark.parametrize("ndata", numlike_data, ids=numlike_ids) def test_plot_numlike(self, ax, plotter, ndata): counts = np.array([4, 6, 5]) plotter(ax, ndata, counts) axis_test(ax.xaxis, ndata) class TestPlotTypes: @pytest.mark.parametrize("plotter", PLOT_LIST, ids=PLOT_IDS) def test_plot_unicode(self, ax, plotter): words = ['Здравствуйте', 'привет'] plotter(ax, words, [0, 1]) axis_test(ax.xaxis, words) @pytest.fixture def test_data(self): self.x = ["hello", "happy", "world"] self.xy = [2, 6, 3] self.y = ["Python", "is", "fun"] self.yx = [3, 4, 5] @pytest.mark.usefixtures("test_data") @pytest.mark.parametrize("plotter", PLOT_LIST, ids=PLOT_IDS) def test_plot_xaxis(self, ax, test_data, plotter): plotter(ax, self.x, self.xy) axis_test(ax.xaxis, self.x) @pytest.mark.usefixtures("test_data") @pytest.mark.parametrize("plotter", PLOT_LIST, ids=PLOT_IDS) def test_plot_yaxis(self, ax, test_data, plotter): plotter(ax, self.yx, self.y) axis_test(ax.yaxis, self.y) @pytest.mark.usefixtures("test_data") @pytest.mark.parametrize("plotter", PLOT_LIST, ids=PLOT_IDS) def test_plot_xyaxis(self, ax, test_data, plotter): plotter(ax, self.x, self.y) axis_test(ax.xaxis, self.x) axis_test(ax.yaxis, self.y) @pytest.mark.parametrize("plotter", PLOT_LIST, ids=PLOT_IDS) def test_update_plot(self, ax, plotter): plotter(ax, ['a', 'b'], ['e', 'g']) plotter(ax, ['a', 'b', 'd'], ['f', 'a', 'b']) plotter(ax, ['b', 'c', 'd'], ['g', 'e', 'd']) axis_test(ax.xaxis, ['a', 'b', 'd', 'c']) axis_test(ax.yaxis, ['e', 'g', 'f', 'a', 'b', 'd']) failing_test_cases = [("mixed", ['A', 3.14]), ("number integer", ['1', 1]), ("string integer", ['42', 42]), ("missing", ['12', np.nan])] fids, fvalues = zip(*failing_test_cases) plotters = [Axes.scatter, Axes.bar, pytest.param(Axes.plot, marks=pytest.mark.xfail)] @pytest.mark.parametrize("plotter", plotters) @pytest.mark.parametrize("xdata", fvalues, ids=fids) def test_mixed_type_exception(self, ax, plotter, xdata): with pytest.raises(TypeError): plotter(ax, xdata, [1, 2]) @pytest.mark.parametrize("plotter", plotters) @pytest.mark.parametrize("xdata", fvalues, ids=fids) def test_mixed_type_update_exception(self, ax, plotter, xdata): with pytest.raises(TypeError): plotter(ax, [0, 3], [1, 3]) plotter(ax, xdata, [1, 2]) def test_hist(): fig, ax = plt.subplots() n, bins, patches = ax.hist(['a', 'b', 'a', 'c', 'ff']) assert n.shape == (10,) np.testing.assert_allclose(n, [2., 0., 0., 1., 0., 0., 1., 0., 0., 1.])
37.379928
79
0.561415
902ceb279788bd1470bd2b1497a98986fb456e28
1,371
py
Python
src/breakpad/src/tools/gyp/test/generator-output/gyptest-top-all.py
ant0ine/phantomjs
8114d44a28134b765ab26b7e13ce31594fa81253
[ "BSD-3-Clause" ]
46
2015-01-08T14:32:34.000Z
2022-02-05T16:48:26.000Z
src/breakpad/src/tools/gyp/test/generator-output/gyptest-top-all.py
ant0ine/phantomjs
8114d44a28134b765ab26b7e13ce31594fa81253
[ "BSD-3-Clause" ]
7
2015-01-20T14:28:12.000Z
2017-01-18T17:21:44.000Z
src/breakpad/src/tools/gyp/test/generator-output/gyptest-top-all.py
ant0ine/phantomjs
8114d44a28134b765ab26b7e13ce31594fa81253
[ "BSD-3-Clause" ]
22
2015-01-04T10:37:36.000Z
2021-08-16T11:46:32.000Z
#!/usr/bin/env python # Copyright (c) 2009 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Verifies building a project hierarchy created when the --generator-output= option is used to put the build configuration files in a separate directory tree. """ import TestGyp test = TestGyp.TestGyp() test.writable(test.workpath('src'), False) test.run_gyp('prog1.gyp', '-Dset_symroot=1', '--generator-output=' + test.workpath('gypfiles'), chdir='src') test.writable(test.workpath('src/build'), True) test.writable(test.workpath('src/subdir2/build'), True) test.writable(test.workpath('src/subdir3/build'), True) test.build('prog1.gyp', test.ALL, chdir='gypfiles') chdir = 'gypfiles' expect = """\ Hello from %s Hello from inc.h Hello from inc1/include1.h Hello from inc2/include2.h Hello from inc3/include3.h Hello from subdir2/deeper/deeper.h """ if test.format == 'xcode': chdir = 'src' test.run_built_executable('prog1', chdir=chdir, stdout=expect % 'prog1.c') if test.format == 'xcode': chdir = 'src/subdir2' test.run_built_executable('prog2', chdir=chdir, stdout=expect % 'prog2.c') if test.format == 'xcode': chdir = 'src/subdir3' test.run_built_executable('prog3', chdir=chdir, stdout=expect % 'prog3.c') test.pass_test()
25.388889
74
0.706054
00da75b3daaf23e61b4c1810808c405d9dfc9826
1,743
py
Python
app/app.py
joelkyu/SantaComingToTown
c93bca9158459243205b26cb36f1b19346eeb058
[ "MIT" ]
null
null
null
app/app.py
joelkyu/SantaComingToTown
c93bca9158459243205b26cb36f1b19346eeb058
[ "MIT" ]
3
2019-09-09T14:55:12.000Z
2019-09-10T14:51:52.000Z
app/app.py
joelkyu/SantaComingToTowne
c93bca9158459243205b26cb36f1b19346eeb058
[ "MIT" ]
null
null
null
import os os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "auth.json" from flask import Flask, render_template, request, url_for, jsonify from flask_sqlalchemy import SQLAlchemy from flask_cors import CORS from config import app from models import db, Person, Characteristic @app.route('/') def index(): db.create_all() return jsonify([p.deserialize() for p in Person.query.all()]) # Initiate all objects @app.route('/add', methods=['POST']) def add_person(): db.create_all() lp = float(request.headers['Lower-Price']) hp = float(request.headers['Upper-Price']) if hp < lp: lp, hp = hp, lp # switch variables if user inputs wrong price bracket. p = Person(twitter=request.headers['Twitter-Handle'], lower_price=lp, upper_price=hp) db.session.add(p) db.session.commit() return jsonify([p.deserialize() for p in Person.query.all()]) @app.route('/person/<int:person_id>', methods=['GET']) def get_person(person_id): return jsonify(Person.query.get(person_id).deserialize()) @app.route('/compare/<int:person_id>', methods=['GET']) def get_comparison(person_id): description = request.headers['name'] price = request.headers['price'] compatible = {} for person in Person.query.all(): person.load_user_sentiment() c = person.compatibility(description, price) if c > 0: compatible[person.twitter] = c return jsonify(compatible) @app.route('/delete/<int:person_id>', methods=['POST']) def delete_target(person_id): db.session.delete(Person.query.get(person_id)) db.session.commit() return jsonify([p.deserialize() for p in Person.query.all()]) if __name__ == '__main__': app.run(host="0.0.0.0", port=8080)
28.112903
89
0.685026
2209b35923b076d29d354f6c10fe5b3f67bfbb3f
1,490
py
Python
modules/retrieval/text_classification/libs/transforms/crop.py
martinhoang11/vietnamese-ocr-toolbox
524b4908bedceb0c87b2c7cd7b5e3f6e1126ace5
[ "Apache-2.0" ]
14
2021-09-05T10:42:14.000Z
2022-03-10T16:27:26.000Z
modules/retrieval/text_classification/libs/transforms/crop.py
martinhoang11/vietnamese-ocr-toolbox
524b4908bedceb0c87b2c7cd7b5e3f6e1126ace5
[ "Apache-2.0" ]
1
2021-06-16T11:35:24.000Z
2021-06-16T11:35:24.000Z
modules/retrieval/text_classification/libs/transforms/crop.py
martinhoang11/vietnamese-ocr-toolbox
524b4908bedceb0c87b2c7cd7b5e3f6e1126ace5
[ "Apache-2.0" ]
5
2021-09-05T13:26:51.000Z
2022-03-09T07:49:45.000Z
import torch import torchvision.transforms as tvtf class RandomCrop: def __init__(self, crop_size): assert isinstance(crop_size, (int, float, list, tuple)), \ f'Invalid type, expect (int, float, list, tuple), get {type(crop_size)}' if isinstance(crop_size, int): crop_size = (crop_size, crop_size) if isinstance(crop_size, float): assert 0 < crop_size <= 1, \ f'Invalid crop size, float should be in (0, 1], get {crop_size}' crop_size = (crop_size, crop_size) if isinstance(crop_size, (list, tuple)): crop_size = crop_size self.crop_size = crop_size def __call__(self, x): # x => C, H, W h, w = x.size()[-2:] crop_size = (min(self.crop_size[0], h), min(self.crop_size[1], w)) r0 = torch.randint(high=h - crop_size[0] + 1, size=(1,)) c0 = torch.randint(high=w - crop_size[1] + 1, size=(1,)) r1 = r0 + crop_size[0] c1 = c0 + crop_size[1] return r0, r1, c0, c1 if __name__ == "__main__": import matplotlib.pyplot as plt x = torch.tensor(range(10000)).view(1, 1, 20, 500) for _ in range(10): r0, r1, c0, c1 = RandomCrop((150, 70))(x) plt.subplot(1, 2, 1) plt.imshow(x.squeeze(), vmin=0, vmax=10000) plt.subplot(1, 2, 2) plt.imshow(x[..., r0:r1, c0:c1].squeeze(), vmin=0, vmax=10000) plt.show() plt.close()
31.041667
84
0.552349
6faa4e962d3b10212ce2c9c6e08a00c2181f00c9
3,531
py
Python
users/migrations/0005_auto__add_field_questruserprofile_rating.py
donvvo/questr-master
6363ffb4c11ef61f3b6976e75c86a5cbc7f38590
[ "MIT" ]
null
null
null
users/migrations/0005_auto__add_field_questruserprofile_rating.py
donvvo/questr-master
6363ffb4c11ef61f3b6976e75c86a5cbc7f38590
[ "MIT" ]
null
null
null
users/migrations/0005_auto__add_field_questruserprofile_rating.py
donvvo/questr-master
6363ffb4c11ef61f3b6976e75c86a5cbc7f38590
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- from south.utils import datetime_utils as datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding field 'QuestrUserProfile.rating' db.add_column(u'users_questruserprofile', 'rating', self.gf('django.db.models.fields.DecimalField')(default='0', max_digits=5, decimal_places=2), keep_default=False) def backwards(self, orm): # Deleting field 'QuestrUserProfile.rating' db.delete_column(u'users_questruserprofile', 'rating') models = { u'users.questrtoken': { 'Meta': {'object_name': 'QuestrToken'}, 'timeframe': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'token_id': ('django.db.models.fields.CharField', [], {'max_length': '20', 'primary_key': 'True'}) }, u'users.questruserprofile': { 'Meta': {'object_name': 'QuestrUserProfile'}, 'account_status': ('django.db.models.fields.IntegerField', [], {'default': '1', 'max_length': '1', 'blank': 'True'}), 'avatar_file_name': ('django.db.models.fields.files.ImageField', [], {'max_length': '9999'}), 'biography': ('django.db.models.fields.TextField', [], {'max_length': '9999', 'blank': 'True'}), 'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'displayname': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'}), 'email': ('django.db.models.fields.EmailField', [], {'unique': 'True', 'max_length': '100'}), 'email_status': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30'}), 'gender': ('django.db.models.fields.CharField', [], {'max_length': '1'}), 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}), 'is_shipper': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}), 'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30'}), 'notifications': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}), 'phone': ('django.db.models.fields.CharField', [], {'max_length': '15', 'blank': 'True'}), 'privacy': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'rating': ('django.db.models.fields.DecimalField', [], {'default': "'0'", 'max_digits': '5', 'decimal_places': '2'}) }, u'users.usertransactional': { 'Meta': {'object_name': 'UserTransactional'}, 'email': ('django.db.models.fields.EmailField', [], {'max_length': '100'}), 'id': ('django.db.models.fields.IntegerField', [], {'primary_key': 'True'}), 'status': ('django.db.models.fields.BooleanField', [], {'default': 'False'}), 'user_code': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '64'}) } } complete_apps = ['users']
59.847458
129
0.582271
2b04b739ea1ba78ccd8c7732776351a202a94f0c
2,881
py
Python
workon/contrib/user/admin.py
dalou/django-workon
ef63c0a81c00ef560ed693e435cf3825f5170126
[ "BSD-3-Clause" ]
null
null
null
workon/contrib/user/admin.py
dalou/django-workon
ef63c0a81c00ef560ed693e435cf3825f5170126
[ "BSD-3-Clause" ]
null
null
null
workon/contrib/user/admin.py
dalou/django-workon
ef63c0a81c00ef560ed693e435cf3825f5170126
[ "BSD-3-Clause" ]
null
null
null
# encoding: utf-8 import datetime import operator from django.contrib import admin from django.db import models from django.contrib.auth.admin import UserAdmin as BaseUserAdmin from django.utils.functional import curry from django.conf import settings from django.contrib import admin from django.contrib.admin.models import LogEntry, ADDITION, CHANGE, DELETION from django.contrib.contenttypes.models import ContentType from django.core.urlresolvers import reverse, NoReverseMatch from django.utils.encoding import force_text from django.utils.html import escape from django.utils.translation import ugettext_lazy as _ from django.contrib.auth import get_user_model # User = get_user_model() class UserAdmin(BaseUserAdmin): # class Media: # js = ( "user/js/admin.js", ) #UserAdmin.list_display + list_display = ( 'email', 'first_name', 'last_name', 'last_login', 'date_joined', 'is_active', 'is_staff', 'is_superuser', ) list_filter = BaseUserAdmin.list_filter + ( #'is_fake', # 'profile__signup_source', # 'profile__register_from', # 'profile__registeration_platform' ) ordering = ("-date_joined",) def get_queryset(self, *args, **kwargs): queryset = super(UserAdmin, self).get_queryset( *args, **kwargs) return queryset actions = ['' ] def get_readonly_fields(self, *args, **kwargs): return ['last_login', 'date_joined'] def email(self, obj): return obj.email email.short_description = "Email" # fieldsets = ( # ('Information personnelle', { # 'classes': ('workon-tab workon-tab-infos',), # 'fields': ('first_name', 'last_name', 'email') #, 'display_filters') # }), # ) fieldsets = ( (None, { 'classes': ('workon-tab workon-tab-login',), 'fields': ('email', 'password', 'last_login', 'date_joined') }), (_(u'Personal info'), { 'classes': ('workon-tab workon-tab-infos',), 'fields': ('first_name', 'last_name', 'username') }), (_(u'Permissions'), { 'classes': ('workon-tab workon-tab-perms',), 'fields': ('is_active', 'is_staff', 'is_superuser', 'groups', 'user_permissions') }), ) add_fieldsets = ( (None, { 'classes': ('wide',), 'fields': ('email', 'password1', 'password2'), }), ) inlines = ( # CustomerProfileInline, # UserSettingsInline, ) workon_form_tabs = ( ('login', u"Login"), ('infos', u"Informations"), ('perms', u"Permissions"), # ('settings', u"Paramètres"), # ('profile', u"Profile"), # ('content', u"Contenus"), )
26.431193
82
0.582784
de687d4995414a28660ef2a8364312228e93b43d
2,481
py
Python
examples/classic_controllers/classic_controllers_synch_motor_example.py
RaviPandey33/gym-electric-motor-1
999e18dceed709decf43d646fb29dc7602b9a89c
[ "MIT" ]
null
null
null
examples/classic_controllers/classic_controllers_synch_motor_example.py
RaviPandey33/gym-electric-motor-1
999e18dceed709decf43d646fb29dc7602b9a89c
[ "MIT" ]
null
null
null
examples/classic_controllers/classic_controllers_synch_motor_example.py
RaviPandey33/gym-electric-motor-1
999e18dceed709decf43d646fb29dc7602b9a89c
[ "MIT" ]
null
null
null
from classic_controllers import Controller from externally_referenced_state_plot import ExternallyReferencedStatePlot import gym_electric_motor as gem from gym_electric_motor.visualization import MotorDashboard if __name__ == '__main__': """ motor type: 'PMSM' Permanent Magnet Synchronous Motor 'SynRM' Synchronous Reluctance Motor control type: 'SC' Speed Control 'TC' Torque Control 'CC' Current Control action_type: 'AbcCont' Continuous Action Space in ABC-Coordinates 'Finite' Discrete Action Space """ motor_type = 'PMSM' control_type = 'TC' action_type = 'AbcCont' env_id = action_type + '-' + control_type + '-' + motor_type + '-v0' # definition of the plotted variables external_ref_plots = [ExternallyReferencedStatePlot(state) for state in ['omega', 'torque', 'i_sd', 'i_sq', 'u_sd', 'u_sq']] # initialize the gym-electric-motor environment env = gem.make(env_id, visualization=MotorDashboard(additional_plots=external_ref_plots)) """ initialize the controller Args: environment gym-electric-motor environment external_ref_plots (optional) plots of the environment, to plot all reference values stages (optional) structure of the controller automated_gain (optional) if True (default), the controller will be tune automatically a (optional) tuning parameter of the Symmetrical Optimum (default: 4) additionally for TC or SC: torque_control (optional) mode of the torque controller, 'interpolate' (default), 'analytical' or 'online' plot_torque(optional) plot some graphs of the torque controller (default: True) plot_modulation (optional) plot some graphs of the modulation controller (default: False) """ controller = Controller.make(env, external_ref_plots=external_ref_plots, torque_control='analytical') state, reference = env.reset() # simulate the environment for i in range(10001): env.render() action = controller.control(state, reference) (state, reference), reward, done, _ = env.step(action) if done: env.reset() controller.reset() env.close()
38.169231
128
0.627973
3a0db597bdce015ad08c701e80d8088bf8a4885d
5,184
py
Python
runtime/client_runtime.py
epfl-dcsl/persona-orig
d94a8b60f07622bb61736127ff328329c7b131a9
[ "Apache-2.0" ]
null
null
null
runtime/client_runtime.py
epfl-dcsl/persona-orig
d94a8b60f07622bb61736127ff328329c7b131a9
[ "Apache-2.0" ]
null
null
null
runtime/client_runtime.py
epfl-dcsl/persona-orig
d94a8b60f07622bb61736127ff328329c7b131a9
[ "Apache-2.0" ]
null
null
null
# Copyright 2019 École Polytechnique Fédérale de Lausanne. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== import os import tensorflow as tf import shutil import contextlib import threading from . import dist_common import time from .dist_common import cluster_name from common import parse from tensorflow.contrib.persona import pipeline import logging logging.basicConfig() log = logging.getLogger(__file__) log.setLevel(logging.DEBUG) startup_wait_time = 1 @contextlib.contextmanager def enqueue_items(sess, enqueue_all_op, timeout=10): def enqueue_func(): sess.run(enqueue_all_op) enqueue_thread = threading.Thread(target=enqueue_func, name="enqueue_function") enqueue_thread.start() yield log.debug("Joining enqueue thread") enqueue_thread.join() log.debug("Enqueue thread is dead") def add_default_module_args(parser): parser.add_argument("-Q", "--queue-index", type=parse.numeric_min_checker(minimum=0, message="queue index must be non-negative"), default=0, help="task index for cluster node that hosts the queues") # TODO we want to have sensible defaults for this eventually! parser.add_argument("--queue-host", required=True, help="host running the queue service") parser.add_argument("--queue-port", type=parse.numeric_min_checker(0, "port must be >0"), required=True, help="port of the host running the queue service") def execute(args, modules): queue_index = args.queue_index module = modules[args.client_command] if hasattr(args, 'service'): service_mode = args.service service = module.lookup_service(name=service_mode) else: # there is only one service if the args does not have .service service = module.get_services()[0] if not service.distributed_capability(): raise Exception("Service {} does not support distributed execution".format(args.service)) run_arguments = tuple(service.extract_run_args(args=args)) if len(run_arguments) == 0: raise Exception("Client must have at least one run argument!") input_dtypes = service.input_dtypes(args=args) input_shapes = service.input_shapes(args=args) output_dtypes = service.output_dtypes(args=args) output_shapes = service.output_shapes(args=args) service_name = args.client_command + "_" + service.get_shortname() in_queue, out_queue = dist_common.make_common_queues(service_name=service_name, queue_index=queue_index, cluster_name=cluster_name, input_dtypes=input_dtypes, input_shapes=input_shapes, output_dtypes=output_dtypes, output_shapes=output_shapes) first_elem = run_arguments[0] if not isinstance(first_elem, (tuple,list)): run_arguments = [(a,) for a in run_arguments] uniq_lens = set(len(a) for a in run_arguments) if len(uniq_lens) != 1: raise Exception("all run arguments must be the same length. Got lengths {}".format(uniq_lens)) transposed = [list(i)for i in zip(*run_arguments)] enqueue_op = in_queue.enqueue_many(vals=transposed, name=service_name+"_client_enqueue") dequeue_single_op = out_queue.dequeue(name="client_dequeue") expected_result_count = len(run_arguments) # FIXME we're just making this assumption for now! # run our local graph queue_host = args.queue_host queue_port = args.queue_port target = "grpc://{host}:{port}".format(host=queue_host, port=queue_port) results = [] with tf.Session(target=target) as sess: uninitialized_vars = tf.report_uninitialized_variables() while len(sess.run(uninitialized_vars)) > 0: log.debug("Waiting for uninitialized variables") time.sleep(startup_wait_time) log.debug("All variables initialized. Persona dist executor starting {} ...".format(args.command)) with enqueue_items(sess=sess, enqueue_all_op=enqueue_op): try: while expected_result_count > 0: next_result = sess.run(dequeue_single_op) # TODO get rid of this! log.debug("Got result: {}".format(next_result)) expected_result_count -= 1 results.append(next_result) service.on_finish(args=args, results=results) except tf.errors.OutOfRangeError: log.error("Got out of range error! Session: {}".format(target))
45.078261
202
0.677469
c3fd33aabb86da5679ac646aa35f0f10b81fefcc
1,938
py
Python
tests/test_utils.py
oubiga/respect
550554ec4d3139379d03cb8f82a8cd2d80c3ad62
[ "BSD-3-Clause" ]
1
2017-06-25T19:09:05.000Z
2017-06-25T19:09:05.000Z
tests/test_utils.py
oubiga/respect
550554ec4d3139379d03cb8f82a8cd2d80c3ad62
[ "BSD-3-Clause" ]
null
null
null
tests/test_utils.py
oubiga/respect
550554ec4d3139379d03cb8f82a8cd2d80c3ad62
[ "BSD-3-Clause" ]
null
null
null
#!/usr/bin/env python # -*- coding: utf-8 -*- """ test_utils ---------- Tests for `respect.utils` module. """ import sys import types import requests from respect import utils if sys.version_info[:2] < (2, 7): import unittest2 as unittest else: import unittest class TestEmptyQualifiers(unittest.TestCase): def test_none_qualifiers(self): qualifiers = utils.sanitize_qualifiers(repos=None, followers=None, language=None) self.assertEqual(qualifiers, '') def test_empty_repos(self): qualifiers = utils.sanitize_qualifiers(repos='', followers=None, language=None) self.assertEqual(qualifiers, '') def test_empty_followers(self): qualifiers = utils.sanitize_qualifiers(repos=None, followers='', language=None) self.assertEqual(qualifiers, '') class TestSanitizedQualifiers(unittest.TestCase): def test_sanitized_repos_qualifiers(self): qualifiers = utils.sanitize_qualifiers(repos='+20') self.assertEqual(qualifiers, 'repos:>20 ') def test_sanitized_followers_qualifiers(self): qualifiers = utils.sanitize_qualifiers(followers='-20') self.assertEqual(qualifiers, 'followers:<20 ') def test_sanitized_language_qualifiers(self): qualifiers = utils.sanitize_qualifiers(language='python') self.assertEqual(qualifiers, 'language:python ') class TestInvalidUsername(unittest.TestCase): def test_dot_invalid_username(self): validation = utils.validate_username('ou.bi.ga') self.assertFalse(validation) def test_underscore_invalid_username(self): validation = utils.validate_username('ou_bi_ga') self.assertFalse(validation) class TestLogin(unittest.TestCase): def test_invalid_login(self): output = utils.login(404, {'<username>': 'oubiga'}) self.assertIsInstance(output, requests.Session) if __name__ == '__main__': unittest.main()
26.916667
89
0.707946
dd505cdff2e34053a80d71da356afc6360cb953b
346
py
Python
plugin/rasa_test.py
mayflower/err-rasa
a3fa9c02c9434dd716caa72bd7a91f36ce0d8a2e
[ "Apache-2.0" ]
1
2018-08-04T17:32:49.000Z
2018-08-04T17:32:49.000Z
plugin/rasa_test.py
mayflower/err-rasa
a3fa9c02c9434dd716caa72bd7a91f36ce0d8a2e
[ "Apache-2.0" ]
4
2019-12-26T16:41:50.000Z
2020-03-24T15:43:45.000Z
plugin/rasa_test.py
mayflower/err-rasa
a3fa9c02c9434dd716caa72bd7a91f36ce0d8a2e
[ "Apache-2.0" ]
2
2019-05-17T20:15:01.000Z
2019-08-08T03:08:25.000Z
import os import unittest from plugin.rasa import Rasa from errbot.backends.test import testbot from errbot.plugin_manager import PluginManager class TestRasa(object): extra_plugin_dir = '../plugin' def test_message_callback(self, testbot): testbot.push_message('test it') assert 'Test Result' in testbot.pop_message()
24.714286
53
0.754335
46b08ee69c3134b10e787afad7ee5f2e76eeda9f
17,834
py
Python
homeassistant/components/http/__init__.py
robaston9/core
c76d2c4283234f6b434bea8348d1cc8cd17ab4b3
[ "Apache-2.0" ]
null
null
null
homeassistant/components/http/__init__.py
robaston9/core
c76d2c4283234f6b434bea8348d1cc8cd17ab4b3
[ "Apache-2.0" ]
null
null
null
homeassistant/components/http/__init__.py
robaston9/core
c76d2c4283234f6b434bea8348d1cc8cd17ab4b3
[ "Apache-2.0" ]
null
null
null
"""Support to serve the Home Assistant API as WSGI application.""" from __future__ import annotations import datetime from ipaddress import IPv4Network, IPv6Network, ip_network import logging import os import ssl from tempfile import NamedTemporaryFile from typing import Any, Final, Optional, TypedDict, Union, cast from aiohttp import web from aiohttp.typedefs import StrOrURL from aiohttp.web_exceptions import HTTPMovedPermanently, HTTPRedirection from cryptography import x509 from cryptography.hazmat.primitives import hashes, serialization from cryptography.hazmat.primitives.asymmetric import rsa from cryptography.x509.oid import NameOID import voluptuous as vol from yarl import URL from homeassistant.components.network import async_get_source_ip from homeassistant.const import EVENT_HOMEASSISTANT_STOP, SERVER_PORT from homeassistant.core import Event, HomeAssistant from homeassistant.exceptions import HomeAssistantError from homeassistant.helpers import config_validation as cv, storage, supervisor from homeassistant.helpers.network import NoURLAvailableError, get_url from homeassistant.helpers.typing import ConfigType from homeassistant.loader import bind_hass from homeassistant.setup import async_start_setup, async_when_setup_or_start from homeassistant.util import ssl as ssl_util from .auth import async_setup_auth from .ban import setup_bans from .const import KEY_AUTHENTICATED, KEY_HASS, KEY_HASS_USER # noqa: F401 from .cors import setup_cors from .forwarded import async_setup_forwarded from .request_context import current_request, setup_request_context from .security_filter import setup_security_filter from .static import CACHE_HEADERS, CachingStaticResource from .view import HomeAssistantView from .web_runner import HomeAssistantTCPSite DOMAIN: Final = "http" CONF_SERVER_HOST: Final = "server_host" CONF_SERVER_PORT: Final = "server_port" CONF_BASE_URL: Final = "base_url" CONF_SSL_CERTIFICATE: Final = "ssl_certificate" CONF_SSL_PEER_CERTIFICATE: Final = "ssl_peer_certificate" CONF_SSL_KEY: Final = "ssl_key" CONF_CORS_ORIGINS: Final = "cors_allowed_origins" CONF_USE_X_FORWARDED_FOR: Final = "use_x_forwarded_for" CONF_TRUSTED_PROXIES: Final = "trusted_proxies" CONF_LOGIN_ATTEMPTS_THRESHOLD: Final = "login_attempts_threshold" CONF_IP_BAN_ENABLED: Final = "ip_ban_enabled" CONF_SSL_PROFILE: Final = "ssl_profile" SSL_MODERN: Final = "modern" SSL_INTERMEDIATE: Final = "intermediate" _LOGGER: Final = logging.getLogger(__name__) DEFAULT_DEVELOPMENT: Final = "0" # Cast to be able to load custom cards. # My to be able to check url and version info. DEFAULT_CORS: Final[list[str]] = ["https://cast.home-assistant.io"] NO_LOGIN_ATTEMPT_THRESHOLD: Final = -1 MAX_CLIENT_SIZE: Final = 1024**2 * 16 STORAGE_KEY: Final = DOMAIN STORAGE_VERSION: Final = 1 SAVE_DELAY: Final = 180 HTTP_SCHEMA: Final = vol.All( cv.deprecated(CONF_BASE_URL), vol.Schema( { vol.Optional(CONF_SERVER_HOST): vol.All( cv.ensure_list, vol.Length(min=1), [cv.string] ), vol.Optional(CONF_SERVER_PORT, default=SERVER_PORT): cv.port, vol.Optional(CONF_BASE_URL): cv.string, vol.Optional(CONF_SSL_CERTIFICATE): cv.isfile, vol.Optional(CONF_SSL_PEER_CERTIFICATE): cv.isfile, vol.Optional(CONF_SSL_KEY): cv.isfile, vol.Optional(CONF_CORS_ORIGINS, default=DEFAULT_CORS): vol.All( cv.ensure_list, [cv.string] ), vol.Inclusive(CONF_USE_X_FORWARDED_FOR, "proxy"): cv.boolean, vol.Inclusive(CONF_TRUSTED_PROXIES, "proxy"): vol.All( cv.ensure_list, [ip_network] ), vol.Optional( CONF_LOGIN_ATTEMPTS_THRESHOLD, default=NO_LOGIN_ATTEMPT_THRESHOLD ): vol.Any(cv.positive_int, NO_LOGIN_ATTEMPT_THRESHOLD), vol.Optional(CONF_IP_BAN_ENABLED, default=True): cv.boolean, vol.Optional(CONF_SSL_PROFILE, default=SSL_MODERN): vol.In( [SSL_INTERMEDIATE, SSL_MODERN] ), } ), ) CONFIG_SCHEMA: Final = vol.Schema({DOMAIN: HTTP_SCHEMA}, extra=vol.ALLOW_EXTRA) class ConfData(TypedDict, total=False): """Typed dict for config data.""" server_host: list[str] server_port: int base_url: str ssl_certificate: str ssl_peer_certificate: str ssl_key: str cors_allowed_origins: list[str] use_x_forwarded_for: bool trusted_proxies: list[IPv4Network | IPv6Network] login_attempts_threshold: int ip_ban_enabled: bool ssl_profile: str @bind_hass async def async_get_last_config(hass: HomeAssistant) -> dict | None: """Return the last known working config.""" store = storage.Store(hass, STORAGE_VERSION, STORAGE_KEY) return cast(Optional[dict], await store.async_load()) class ApiConfig: """Configuration settings for API server.""" def __init__( self, local_ip: str, host: str, port: int, use_ssl: bool, ) -> None: """Initialize a new API config object.""" self.local_ip = local_ip self.host = host self.port = port self.use_ssl = use_ssl async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool: """Set up the HTTP API and debug interface.""" conf: ConfData | None = config.get(DOMAIN) if conf is None: conf = cast(ConfData, HTTP_SCHEMA({})) server_host = conf.get(CONF_SERVER_HOST) server_port = conf[CONF_SERVER_PORT] ssl_certificate = conf.get(CONF_SSL_CERTIFICATE) ssl_peer_certificate = conf.get(CONF_SSL_PEER_CERTIFICATE) ssl_key = conf.get(CONF_SSL_KEY) cors_origins = conf[CONF_CORS_ORIGINS] use_x_forwarded_for = conf.get(CONF_USE_X_FORWARDED_FOR, False) trusted_proxies = conf.get(CONF_TRUSTED_PROXIES) or [] is_ban_enabled = conf[CONF_IP_BAN_ENABLED] login_threshold = conf[CONF_LOGIN_ATTEMPTS_THRESHOLD] ssl_profile = conf[CONF_SSL_PROFILE] if ssl_peer_certificate is not None and supervisor.has_supervisor(): _LOGGER.warning( "Peer certificates are not supported when running the supervisor" ) ssl_peer_certificate = None server = HomeAssistantHTTP( hass, server_host=server_host, server_port=server_port, ssl_certificate=ssl_certificate, ssl_peer_certificate=ssl_peer_certificate, ssl_key=ssl_key, trusted_proxies=trusted_proxies, ssl_profile=ssl_profile, ) await server.async_initialize( cors_origins=cors_origins, use_x_forwarded_for=use_x_forwarded_for, login_threshold=login_threshold, is_ban_enabled=is_ban_enabled, ) async def stop_server(event: Event) -> None: """Stop the server.""" await server.stop() async def start_server(*_: Any) -> None: """Start the server.""" with async_start_setup(hass, ["http"]): hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, stop_server) # We already checked it's not None. assert conf is not None await start_http_server_and_save_config(hass, dict(conf), server) async_when_setup_or_start(hass, "frontend", start_server) hass.http = server local_ip = await async_get_source_ip(hass) host = local_ip if server_host is not None: # Assume the first server host name provided as API host host = server_host[0] hass.config.api = ApiConfig( local_ip, host, server_port, ssl_certificate is not None ) return True class HomeAssistantHTTP: """HTTP server for Home Assistant.""" def __init__( self, hass: HomeAssistant, ssl_certificate: str | None, ssl_peer_certificate: str | None, ssl_key: str | None, server_host: list[str] | None, server_port: int, trusted_proxies: list[IPv4Network | IPv6Network], ssl_profile: str, ) -> None: """Initialize the HTTP Home Assistant server.""" self.app = web.Application(middlewares=[], client_max_size=MAX_CLIENT_SIZE) self.hass = hass self.ssl_certificate = ssl_certificate self.ssl_peer_certificate = ssl_peer_certificate self.ssl_key = ssl_key self.server_host = server_host self.server_port = server_port self.trusted_proxies = trusted_proxies self.ssl_profile = ssl_profile self.runner: web.AppRunner | None = None self.site: HomeAssistantTCPSite | None = None self.context: ssl.SSLContext | None = None async def async_initialize( self, *, cors_origins: list[str], use_x_forwarded_for: bool, login_threshold: int, is_ban_enabled: bool, ) -> None: """Initialize the server.""" self.app[KEY_HASS] = self.hass # Order matters, security filters middleware needs to go first, # forwarded middleware needs to go second. setup_security_filter(self.app) async_setup_forwarded(self.app, use_x_forwarded_for, self.trusted_proxies) setup_request_context(self.app, current_request) if is_ban_enabled: setup_bans(self.hass, self.app, login_threshold) await async_setup_auth(self.hass, self.app) setup_cors(self.app, cors_origins) if self.ssl_certificate: self.context = await self.hass.async_add_executor_job( self._create_ssl_context ) def register_view(self, view: HomeAssistantView | type[HomeAssistantView]) -> None: """Register a view with the WSGI server. The view argument must be a class that inherits from HomeAssistantView. It is optional to instantiate it before registering; this method will handle it either way. """ if isinstance(view, type): # Instantiate the view, if needed view = view() if not hasattr(view, "url"): class_name = view.__class__.__name__ raise AttributeError(f'{class_name} missing required attribute "url"') if not hasattr(view, "name"): class_name = view.__class__.__name__ raise AttributeError(f'{class_name} missing required attribute "name"') view.register(self.app, self.app.router) def register_redirect( self, url: str, redirect_to: StrOrURL, *, redirect_exc: type[HTTPRedirection] = HTTPMovedPermanently, ) -> None: """Register a redirect with the server. If given this must be either a string or callable. In case of a callable it's called with the url adapter that triggered the match and the values of the URL as keyword arguments and has to return the target for the redirect, otherwise it has to be a string with placeholders in rule syntax. """ async def redirect(request: web.Request) -> web.StreamResponse: """Redirect to location.""" # Should be instance of aiohttp.web_exceptions._HTTPMove. raise redirect_exc(redirect_to) # type: ignore[arg-type,misc] self.app["allow_configured_cors"]( self.app.router.add_route("GET", url, redirect) ) def register_static_path( self, url_path: str, path: str, cache_headers: bool = True ) -> None: """Register a folder or file to serve as a static path.""" if os.path.isdir(path): if cache_headers: resource: CachingStaticResource | web.StaticResource = ( CachingStaticResource(url_path, path) ) else: resource = web.StaticResource(url_path, path) self.app.router.register_resource(resource) self.app["allow_configured_cors"](resource) return async def serve_file(request: web.Request) -> web.FileResponse: """Serve file from disk.""" if cache_headers: return web.FileResponse(path, headers=CACHE_HEADERS) return web.FileResponse(path) self.app["allow_configured_cors"]( self.app.router.add_route("GET", url_path, serve_file) ) def _create_ssl_context(self) -> ssl.SSLContext | None: context: ssl.SSLContext | None = None assert self.ssl_certificate is not None try: if self.ssl_profile == SSL_INTERMEDIATE: context = ssl_util.server_context_intermediate() else: context = ssl_util.server_context_modern() context.load_cert_chain(self.ssl_certificate, self.ssl_key) except OSError as error: if not self.hass.config.safe_mode: raise HomeAssistantError( f"Could not use SSL certificate from {self.ssl_certificate}: {error}" ) from error _LOGGER.error( "Could not read SSL certificate from %s: %s", self.ssl_certificate, error, ) try: context = self._create_emergency_ssl_context() except OSError as error: _LOGGER.error( "Could not create an emergency self signed ssl certificate: %s", error, ) context = None else: _LOGGER.critical( "Home Assistant is running in safe mode with an emergency self signed ssl certificate because the configured SSL certificate was not usable" ) return context if self.ssl_peer_certificate: if context is None: raise HomeAssistantError( "Failed to create ssl context, no fallback available because a peer certificate is required." ) context.verify_mode = ssl.CERT_REQUIRED context.load_verify_locations(self.ssl_peer_certificate) return context def _create_emergency_ssl_context(self) -> ssl.SSLContext: """Create an emergency ssl certificate so we can still startup.""" context = ssl_util.server_context_modern() host: str try: host = cast(str, URL(get_url(self.hass, prefer_external=True)).host) except NoURLAvailableError: host = "homeassistant.local" key = rsa.generate_private_key( public_exponent=65537, key_size=2048, ) subject = issuer = x509.Name( [ x509.NameAttribute( NameOID.ORGANIZATION_NAME, "Home Assistant Emergency Certificate" ), x509.NameAttribute(NameOID.COMMON_NAME, host), ] ) cert = ( x509.CertificateBuilder() .subject_name(subject) .issuer_name(issuer) .public_key(key.public_key()) .serial_number(x509.random_serial_number()) .not_valid_before(datetime.datetime.utcnow()) .not_valid_after(datetime.datetime.utcnow() + datetime.timedelta(days=30)) .add_extension( x509.SubjectAlternativeName([x509.DNSName(host)]), critical=False, ) .sign(key, hashes.SHA256()) ) with NamedTemporaryFile() as cert_pem, NamedTemporaryFile() as key_pem: cert_pem.write(cert.public_bytes(serialization.Encoding.PEM)) key_pem.write( key.private_bytes( serialization.Encoding.PEM, format=serialization.PrivateFormat.TraditionalOpenSSL, encryption_algorithm=serialization.NoEncryption(), ) ) cert_pem.flush() key_pem.flush() context.load_cert_chain(cert_pem.name, key_pem.name) return context async def start(self) -> None: """Start the aiohttp server.""" # Aiohttp freezes apps after start so that no changes can be made. # However in Home Assistant components can be discovered after boot. # This will now raise a RunTimeError. # To work around this we now prevent the router from getting frozen # pylint: disable=protected-access self.app._router.freeze = lambda: None # type: ignore[assignment] self.runner = web.AppRunner(self.app) await self.runner.setup() self.site = HomeAssistantTCPSite( self.runner, self.server_host, self.server_port, ssl_context=self.context ) try: await self.site.start() except OSError as error: _LOGGER.error( "Failed to create HTTP server at port %d: %s", self.server_port, error ) _LOGGER.info("Now listening on port %d", self.server_port) async def stop(self) -> None: """Stop the aiohttp server.""" if self.site is not None: await self.site.stop() if self.runner is not None: await self.runner.cleanup() async def start_http_server_and_save_config( hass: HomeAssistant, conf: dict, server: HomeAssistantHTTP ) -> None: """Startup the http server and save the config.""" await server.start() # If we are set up successful, we store the HTTP settings for safe mode. store = storage.Store(hass, STORAGE_VERSION, STORAGE_KEY) if CONF_TRUSTED_PROXIES in conf: conf[CONF_TRUSTED_PROXIES] = [ str(cast(Union[IPv4Network, IPv6Network], ip).network_address) for ip in conf[CONF_TRUSTED_PROXIES] ] store.async_delay_save(lambda: conf, SAVE_DELAY)
36.247967
160
0.654761
9aa2e02bf599836b622b80fde0386b3dfcaacfe5
16,172
py
Python
Twitter/requests_oauthlib/oauth2_session.py
piscesfantasy/SocialNetworkSearchEngine
6ec04fd367020f74ef506b5927a0cf6d2bdbec7a
[ "BSD-3-Clause" ]
null
null
null
Twitter/requests_oauthlib/oauth2_session.py
piscesfantasy/SocialNetworkSearchEngine
6ec04fd367020f74ef506b5927a0cf6d2bdbec7a
[ "BSD-3-Clause" ]
null
null
null
Twitter/requests_oauthlib/oauth2_session.py
piscesfantasy/SocialNetworkSearchEngine
6ec04fd367020f74ef506b5927a0cf6d2bdbec7a
[ "BSD-3-Clause" ]
null
null
null
from __future__ import unicode_literals import logging from oauthlib.common import generate_token, urldecode from oauthlib.oauth2 import WebApplicationClient, InsecureTransportError from oauthlib.oauth2 import TokenExpiredError, is_secure_transport import requests log = logging.getLogger(__name__) class TokenUpdated(Warning): def __init__(self, token): super(TokenUpdated, self).__init__() self.token = token class OAuth2Session(requests.Session): """Versatile OAuth 2 extension to :class:`requests.Session`. Supports any grant type adhering to :class:`oauthlib.oauth2.Client` spec including the four core OAuth 2 grants. Can be used to create authorization urls, fetch tokens and access protected resources using the :class:`requests.Session` interface you are used to. - :class:`oauthlib.oauth2.WebApplicationClient` (default): Authorization Code Grant - :class:`oauthlib.oauth2.MobileApplicationClient`: Implicit Grant - :class:`oauthlib.oauth2.LegacyApplicationClient`: Password Credentials Grant - :class:`oauthlib.oauth2.BackendApplicationClient`: Client Credentials Grant Note that the only time you will be using Implicit Grant from python is if you are driving a user agent able to obtain URL fragments. """ def __init__(self, client_id=None, client=None, auto_refresh_url=None, auto_refresh_kwargs=None, scope=None, redirect_uri=None, token=None, state=None, token_updater=None, **kwargs): """Construct a new OAuth 2 client session. :param client_id: Client id obtained during registration :param client: :class:`oauthlib.oauth2.Client` to be used. Default is WebApplicationClient which is useful for any hosted application but not mobile or desktop. :param scope: List of scopes you wish to request access to :param redirect_uri: Redirect URI you registered as callback :param token: Token dictionary, must include access_token and token_type. :param state: State string used to prevent CSRF. This will be given when creating the authorization url and must be supplied when parsing the authorization response. Can be either a string or a no argument callable. :auto_refresh_url: Refresh token endpoint URL, must be HTTPS. Supply this if you wish the client to automatically refresh your access tokens. :auto_refresh_kwargs: Extra arguments to pass to the refresh token endpoint. :token_updater: Method with one argument, token, to be used to update your token databse on automatic token refresh. If not set a TokenUpdated warning will be raised when a token has been refreshed. This warning will carry the token in its token argument. :param kwargs: Arguments to pass to the Session constructor. """ super(OAuth2Session, self).__init__(**kwargs) self._client = client or WebApplicationClient(client_id, token=token) self.token = token or {} self.scope = scope self.redirect_uri = redirect_uri self.state = state or generate_token self._state = state self.auto_refresh_url = auto_refresh_url self.auto_refresh_kwargs = auto_refresh_kwargs or {} self.token_updater = token_updater # Allow customizations for non compliant providers through various # hooks to adjust requests and responses. self.compliance_hook = { 'access_token_response': set([]), 'refresh_token_response': set([]), 'protected_request': set([]), } def new_state(self): """Generates a state string to be used in authorizations.""" try: self._state = self.state() log.debug('Generated new state %s.', self._state) except TypeError: self._state = self.state log.debug('Re-using previously supplied state %s.', self._state) return self._state @property def client_id(self): return getattr(self._client, "client_id", None) @client_id.setter def client_id(self, value): self._client.client_id = value @client_id.deleter def client_id(self): del self._client.client_id @property def token(self): return getattr(self._client, "token", None) @token.setter def token(self, value): self._client.token = value self._client._populate_attributes(value) @property def access_token(self): return getattr(self._client, "access_token", None) @access_token.setter def access_token(self, value): self._client.access_token = value @access_token.deleter def access_token(self): del self._client.access_token @property def authorized(self): """Boolean that indicates whether this session has an OAuth token or not. If `self.authorized` is True, you can reasonably expect OAuth-protected requests to the resource to succeed. If `self.authorized` is False, you need the user to go through the OAuth authentication dance before OAuth-protected requests to the resource will succeed. """ return bool(self.access_token) def authorization_url(self, url, state=None, **kwargs): """Form an authorization URL. :param url: Authorization endpoint url, must be HTTPS. :param state: An optional state string for CSRF protection. If not given it will be generated for you. :param kwargs: Extra parameters to include. :return: authorization_url, state """ state = state or self.new_state() return self._client.prepare_request_uri(url, redirect_uri=self.redirect_uri, scope=self.scope, state=state, **kwargs), state def fetch_token(self, token_url, code=None, authorization_response=None, body='', auth=None, username=None, password=None, method='POST', timeout=None, headers=None, verify=True, **kwargs): """Generic method for fetching an access token from the token endpoint. If you are using the MobileApplicationClient you will want to use token_from_fragment instead of fetch_token. :param token_url: Token endpoint URL, must use HTTPS. :param code: Authorization code (used by WebApplicationClients). :param authorization_response: Authorization response URL, the callback URL of the request back to you. Used by WebApplicationClients instead of code. :param body: Optional application/x-www-form-urlencoded body to add the include in the token request. Prefer kwargs over body. :param auth: An auth tuple or method as accepted by requests. :param username: Username used by LegacyApplicationClients. :param password: Password used by LegacyApplicationClients. :param method: The HTTP method used to make the request. Defaults to POST, but may also be GET. Other methods should be added as needed. :param headers: Dict to default request headers with. :param timeout: Timeout of the request in seconds. :param verify: Verify SSL certificate. :param kwargs: Extra parameters to include in the token request. :return: A token dict """ if not is_secure_transport(token_url): raise InsecureTransportError() if not code and authorization_response: self._client.parse_request_uri_response(authorization_response, state=self._state) code = self._client.code elif not code and isinstance(self._client, WebApplicationClient): code = self._client.code if not code: raise ValueError('Please supply either code or ' 'authorization_code parameters.') body = self._client.prepare_request_body(code=code, body=body, redirect_uri=self.redirect_uri, username=username, password=password, **kwargs) if (not auth) and username: if password is None: raise ValueError('Username was supplied, but not password.') auth = requests.auth.HTTPBasicAuth(username, password) headers = headers or { 'Accept': 'application/json', 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8', } self.token = {} if method.upper() == 'POST': r = self.post(token_url, data=dict(urldecode(body)), timeout=timeout, headers=headers, auth=auth, verify=verify) log.debug('Prepared fetch token request body %s', body) elif method.upper() == 'GET': # if method is not 'POST', switch body to querystring and GET r = self.get(token_url, params=dict(urldecode(body)), timeout=timeout, headers=headers, auth=auth, verify=verify) log.debug('Prepared fetch token request querystring %s', body) else: raise ValueError('The method kwarg must be POST or GET.') log.debug('Request to fetch token completed with status %s.', r.status_code) log.debug('Request headers were %s', r.request.headers) log.debug('Request body was %s', r.request.body) log.debug('Response headers were %s and content %s.', r.headers, r.text) log.debug('Invoking %d token response hooks.', len(self.compliance_hook['access_token_response'])) for hook in self.compliance_hook['access_token_response']: log.debug('Invoking hook %s.', hook) r = hook(r) self._client.parse_request_body_response(r.text, scope=self.scope) self.token = self._client.token log.debug('Obtained token %s.', self.token) return self.token def token_from_fragment(self, authorization_response): """Parse token from the URI fragment, used by MobileApplicationClients. :param authorization_response: The full URL of the redirect back to you :return: A token dict """ self._client.parse_request_uri_response(authorization_response, state=self._state) self.token = self._client.token return self.token def refresh_token(self, token_url, refresh_token=None, body='', auth=None, timeout=None, headers=None, verify=True, **kwargs): """Fetch a new access token using a refresh token. :param token_url: The token endpoint, must be HTTPS. :param refresh_token: The refresh_token to use. :param body: Optional application/x-www-form-urlencoded body to add the include in the token request. Prefer kwargs over body. :param auth: An auth tuple or method as accepted by requests. :param timeout: Timeout of the request in seconds. :param verify: Verify SSL certificate. :param kwargs: Extra parameters to include in the token request. :return: A token dict """ if not token_url: raise ValueError('No token endpoint set for auto_refresh.') if not is_secure_transport(token_url): raise InsecureTransportError() # Need to nullify token to prevent it from being added to the request refresh_token = refresh_token or self.token.get('refresh_token') self.token = {} log.debug('Adding auto refresh key word arguments %s.', self.auto_refresh_kwargs) kwargs.update(self.auto_refresh_kwargs) body = self._client.prepare_refresh_body(body=body, refresh_token=refresh_token, scope=self.scope, **kwargs) log.debug('Prepared refresh token request body %s', body) if headers is None: headers = { 'Accept': 'application/json', 'Content-Type': ( 'application/x-www-form-urlencoded;charset=UTF-8' ), } r = self.post(token_url, data=dict(urldecode(body)), auth=auth, timeout=timeout, headers=headers, verify=verify) log.debug('Request to refresh token completed with status %s.', r.status_code) log.debug('Response headers were %s and content %s.', r.headers, r.text) log.debug('Invoking %d token response hooks.', len(self.compliance_hook['refresh_token_response'])) for hook in self.compliance_hook['refresh_token_response']: log.debug('Invoking hook %s.', hook) r = hook(r) self.token = self._client.parse_request_body_response(r.text, scope=self.scope) if not 'refresh_token' in self.token: log.debug('No new refresh token given. Re-using old.') self.token['refresh_token'] = refresh_token return self.token def request(self, method, url, data=None, headers=None, **kwargs): """Intercept all requests and add the OAuth 2 token if present.""" if not is_secure_transport(url): raise InsecureTransportError() if self.token: log.debug('Invoking %d protected resource request hooks.', len(self.compliance_hook['protected_request'])) for hook in self.compliance_hook['protected_request']: log.debug('Invoking hook %s.', hook) url, headers, data = hook(url, headers, data) log.debug('Adding token %s to request.', self.token) try: url, headers, data = self._client.add_token(url, http_method=method, body=data, headers=headers) # Attempt to retrieve and save new access token if expired except TokenExpiredError: if self.auto_refresh_url: log.debug('Auto refresh is set, attempting to refresh at %s.', self.auto_refresh_url) token = self.refresh_token(self.auto_refresh_url, **kwargs) if self.token_updater: log.debug('Updating token to %s using %s.', token, self.token_updater) self.token_updater(token) url, headers, data = self._client.add_token(url, http_method=method, body=data, headers=headers) else: raise TokenUpdated(token) else: raise log.debug('Requesting url %s using method %s.', url, method) log.debug('Supplying headers %s and data %s', headers, data) log.debug('Passing through key word arguments %s.', kwargs) return super(OAuth2Session, self).request(method, url, headers=headers, data=data, **kwargs) def register_compliance_hook(self, hook_type, hook): """Register a hook for request/response tweaking. Available hooks are: access_token_response invoked before token parsing. refresh_token_response invoked before refresh token parsing. protected_request invoked before making a request. If you find a new hook is needed please send a GitHub PR request or open an issue. """ if hook_type not in self.compliance_hook: raise ValueError('Hook type %s is not in %s.', hook_type, self.compliance_hook) self.compliance_hook[hook_type].add(hook)
44.674033
87
0.623361
9b18d79de7bd0f6cb32c77181ff6aa488bc58669
3,262
py
Python
tests/instantiation/native/qiskit/test_synthesize.py
BQSKit/qfast-qiskit
dd562f809f86d8a2b2633001f78a3ddb0bf3a3af
[ "BSD-3-Clause-LBNL" ]
3
2020-11-18T20:42:32.000Z
2021-03-22T15:52:56.000Z
tests/instantiation/native/qiskit/test_synthesize.py
BQSKit/qfast-qiskit
dd562f809f86d8a2b2633001f78a3ddb0bf3a3af
[ "BSD-3-Clause-LBNL" ]
null
null
null
tests/instantiation/native/qiskit/test_synthesize.py
BQSKit/qfast-qiskit
dd562f809f86d8a2b2633001f78a3ddb0bf3a3af
[ "BSD-3-Clause-LBNL" ]
null
null
null
import numpy as np import unittest as ut from qiskit import * from qfast import perm from qfast.instantiation.native.qiskit import QiskitTool def get_utry ( circ ): """Converts a qiskit circuit into a numpy unitary.""" backend = qiskit.BasicAer.get_backend( 'unitary_simulator' ) utry = qiskit.execute( circ, backend ).result().get_unitary() num_qubits = int( np.log2( len( utry ) ) ) qubit_order = tuple( reversed( range( num_qubits ) ) ) P = perm.calc_permutation_matrix( num_qubits, qubit_order ) return P @ utry @ P.T def hilbert_schmidt_distance ( X, Y ): """Calculates a Hilbert-Schmidt based distance.""" if X.shape != Y.shape: raise ValueError( "X and Y must have same shape." ) mat = np.matmul( np.transpose( np.conj( X ) ), Y ) num = np.abs( np.trace( mat ) ) dem = mat.shape[0] return 1 - ( num / dem ) class TestQiskitSynthesize ( ut.TestCase ): TOFFOLI = np.asarray( [[1.+0.j, 0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j], [0.+0.j, 1.+0.j, 0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j], [0.+0.j, 0.+0.j, 1.+0.j, 0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j], [0.+0.j, 0.+0.j, 0.+0.j, 1.+0.j, 0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j], [0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j, 1.+0.j, 0.+0.j, 0.+0.j, 0.+0.j], [0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j, 1.+0.j, 0.+0.j, 0.+0.j], [0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j, 1.+0.j], [0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j, 1.+0.j, 0.+0.j]] ) INVALID = np.asarray( [[1.+0.j, 0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j], [0.+0.j, 1.+0.j, 0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j], [0.+0.j, 0.+0.j, 1.+0.j, 0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j], [0.+0.j, 0.+0.j, 0.+0.j, 1.+0.j, 0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j], [0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j, 1.+0.j, 0.+0.j, 0.+0.j, 0.+0.j], [0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j, 1.+0.j, 0.+0.j, 0.+0.j], [0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j, 1.+0.j], [0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j, 1.+0.j, 0.+0.j], [0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j, 1.+0.j, 0.+0.j]] ) def test_qiskit_synthesize_invalid ( self ): qtool = QiskitTool() self.assertRaises( TypeError, qtool.synthesize, 1 ) self.assertRaises( TypeError, qtool.synthesize, np.array( [ 0, 1 ] ) ) self.assertRaises( TypeError, qtool.synthesize, np.array( [ [ [ 0 ] ] ] ) ) self.assertRaises( TypeError, qtool.synthesize, self.INVALID ) invalid_utry_matrix = np.copy( self.TOFFOLI ) invalid_utry_matrix[2][2] = 137.+0.j self.assertRaises( TypeError, qtool.synthesize, invalid_utry_matrix ) self.assertRaises( ValueError, qtool.synthesize, np.identity( 16 ) ) def test_qiskit_synthesize_valid ( self ): qtool = QiskitTool() qasm = qtool.synthesize( self.TOFFOLI ) utry = get_utry( QuantumCircuit.from_qasm_str( qasm ) ) self.assertTrue( hilbert_schmidt_distance( self.TOFFOLI, utry ) <= 1e-15 ) if __name__ == '__main__': ut.main()
42.363636
83
0.514408
ff8ac4d8b711b83be4b1c81d758df29145d453c9
5,057
py
Python
unity-environment/Learning/utils/nn.py
KooroshNaderi/UnityClimberAgent
1953dc6786872304a2fd19140f685895557ad052
[ "Apache-2.0" ]
null
null
null
unity-environment/Learning/utils/nn.py
KooroshNaderi/UnityClimberAgent
1953dc6786872304a2fd19140f685895557ad052
[ "Apache-2.0" ]
6
2019-12-23T21:43:11.000Z
2022-02-10T00:40:39.000Z
unity-environment/Learning/utils/nn.py
KooroshNaderi/UnityClimberAgent
1953dc6786872304a2fd19140f685895557ad052
[ "Apache-2.0" ]
null
null
null
import tensorflow as tf def dropout(x, std=0.05): return tf.multiply(x, tf.truncated_normal(shape=tf.shape(x), mean=1.0, stddev=std, dtype=tf.float32)) def selu(x, _lambda=1.0507, _alpha=1.6733): return _lambda * tf.where(x >= 0.0, x, _alpha * tf.nn.elu(x)) class CNN: def __init__(self, input_data, layers_info, dropout_std, trainable, suffix): layer_input = input_data self.layer_conv = [] for i in range(len(layers_info)): with tf.name_scope("Conv-" + str(i)): layer = CNN.new_conv_layer(layer_input, layers_info[i], dropout_std, trainable, suffix + str(i)) self.layer_conv.append(layer) layer_input = layer self.output, self.output_length = self.flatten_layer(layer_input) @staticmethod # layer_info dictionary: {num_filter, size_filter, stride_filter, padding, activation, use_pooling} def new_conv_layer(input_data, layer_info, dropout_std, trainable, suffix): if layer_info['padding'] == 'FULL': cols_to_add = int(layer_info['size_filter'][1] / 2) input_data = tf.pad(input_data, [[0, 0], [0, 0], [cols_to_add, cols_to_add], [0, 0]]) layer = tf.layers.conv2d( inputs=input_data, filters=layer_info['num_filter'], kernel_size=layer_info['size_filter'], strides=layer_info['stride_filter'], padding='SAME', data_format='channels_last', activation=None, use_bias=True, kernel_initializer=tf.contrib.layers.xavier_initializer_conv2d(), bias_initializer=tf.contrib.layers.xavier_initializer_conv2d(), kernel_regularizer=tf.nn.l2_loss, bias_regularizer=None, trainable=trainable, name='Conv2D-' + suffix ) layer = dropout(layer, dropout_std) if layer_info['activation'] == 'relu': layer = tf.nn.relu(layer) elif layer_info['activation'] == 'tanh': layer = tf.nn.tanh(layer) elif layer_info['activation'] == 'selu': layer = selu(layer) if layer_info['use_pooling']: layer = tf.nn.max_pool(value=layer, ksize=[1, 1, 2, 1], strides=[1, 1, 2, 1], padding='Valid') tf.summary.histogram("Activations", layer) return layer @staticmethod def flatten_layer(layer): layer_shape = layer.get_shape() num_features = layer_shape[1:4].num_elements() layer_flat = tf.reshape(layer, [-1, num_features]) return layer_flat, num_features class MLP: def __init__(self, input_data, layers_info, dropout_std, trainable, suffix): layer = dropout(input_data, dropout_std) # layer = input_data for i in range(len(layers_info)): scope = suffix + '-FC' + str(i) with tf.name_scope(scope): layer = MLP.new_fc_layer(layer, layers_info[i], dropout_std if (i + 1 < len(layers_info)) else 0 , trainable, scope) self.output = layer @staticmethod # layer_info format: [num_outputs, activation] def new_fc_layer(input_data, layer_info, dropout_std, trainable, suffix): layer = tf.contrib.layers.fully_connected( inputs=input_data , num_outputs=layer_info['num_outputs'] , activation_fn=None , normalizer_fn=None , normalizer_params=None # , weights_initializer=tf.contrib.layers.xavier_initializer() , weights_initializer=tf.truncated_normal_initializer(stddev=0.05) , biases_initializer=tf.zeros_initializer() , weights_regularizer=tf.nn.l2_loss , biases_regularizer=None , reuse=None , variables_collections=None , outputs_collections=None , trainable=trainable , scope=suffix ) if layer_info['activation'] == 'relu': layer = tf.nn.relu(layer) elif layer_info['activation'] == 'tanh': layer = tf.nn.tanh(layer) elif layer_info['activation'] == 'selu': layer = selu(layer) elif layer_info['activation'] == 'softmax': layer = tf.nn.softmax(layer) elif layer_info['activation'] == 'sigmoid': layer = tf.nn.sigmoid(layer) elif layer_info['activation'] == 'elu': layer = tf.nn.elu(layer) elif layer_info['activation'] == 'relu6': layer = tf.nn.relu6(layer) elif layer_info['activation'] == 'crelu': layer = tf.nn.crelu(layer) elif layer_info['activation'] == 'lrelu': layer = tf.nn.leaky_relu(layer) elif layer_info['activation'] == 'softplus': layer = tf.nn.softplus(layer) elif layer_info['activation'] == 'softsign': layer = tf.nn.softsign(layer) layer = dropout(layer, dropout_std) # tf.summary.histogram(suffix, layer) return layer
38.603053
112
0.598378
d13c6a3b803d086f105eb489e5be0f46a6695bba
3,190
py
Python
rhw/urls.py
misli/rhw
928c9d5ba5649c987c255cf8370d92fcee88031c
[ "BSD-3-Clause" ]
null
null
null
rhw/urls.py
misli/rhw
928c9d5ba5649c987c255cf8370d92fcee88031c
[ "BSD-3-Clause" ]
null
null
null
rhw/urls.py
misli/rhw
928c9d5ba5649c987c255cf8370d92fcee88031c
[ "BSD-3-Clause" ]
null
null
null
"""rhw URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.8/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf.urls import include, url from django.contrib import admin from django.contrib.auth.decorators import login_required as lr, permission_required as pr from django.contrib.auth.views import login, logout from .views import * from .forms import PasswordResetForm urlpatterns = [ url(r'^$', HomeView.as_view(), name='home'), url(r'^ideas/$', IdeasView.as_view(), name='ideas'), url(r'^ideas/new/$', lr(IdeaCreateView.as_view()), name='idea-create'), url(r'^ideas/(?P<slug>[^/]+)/$', IdeaView.as_view(), name='idea'), url(r'^ideas/(?P<slug>[^/]+)/edit/$', lr(IdeaEditView.as_view()), name='idea-edit'), url(r'^ideas/(?P<slug>[^/]+)/(?P<op>[+-])1$', lr(interested), name='interested'), url(r'^projects/$', ProjectsView.as_view(), name='projects'), url(r'^projects/(?P<slug>[^/]+)/$', ProjectView.as_view(), name='project'), url(r'^projects/(?P<slug>[^/]+)/edit/$', lr(ProjectEditView.as_view()), name='project-edit'), url(r'^projects/(?P<slug>[^/]+)/(?P<op>[+-])1$', lr(member_vote), name='member_vote'), url(r'^rhws/$', RhwsView.as_view(), name='rhws'), url(r'^rhws/new/$', pr('')(RhwCreateView.as_view()), name='rhw-create'), url(r'^rhws/(?P<slug>[^/]+)/$', RhwView.as_view(), name='rhw'), url(r'^rhws/(?P<slug>[^/]+)/edit/$', lr(RhwEditView.as_view()), name='rhw-edit'), url(r'^rhws/(?P<slug>[^/]+)/nominate/$', lr(RhwNominateView.as_view()), name='rhw-nominate'), url(r'^rhws/(?P<slug>[^/]+)/nominate/new$', lr(RhwNominateNewView.as_view()), name='rhw-nominate-new'), url(r'^rhws/(?P<rhw>[^/]+)/select/(?P<idea>[^/]+)/$', pr('')(RhwSelectView.as_view()), name='rhw-select'), url(r'^auth/password_reset/$', 'django.contrib.auth.views.password_reset', { 'password_reset_form': PasswordResetForm, 'from_email': settings.SERVER_EMAIL, }, name='password_reset'), url(r'^auth/', include('django.contrib.auth.urls')), url(r'^admin/', include(admin.site.urls)), url(r'^ckeditor/', include('ckeditor_uploader.urls')), ]
63.8
121
0.520376
5f651f973da8c9712c12f44fc55f83c70deb1a39
23,614
py
Python
image_generation/treeutils.py
mihirp1998/blender_emblang
4b7092b8f4dfdc5240ed8ecf8e18ec75b9e0141c
[ "BSD-3-Clause" ]
null
null
null
image_generation/treeutils.py
mihirp1998/blender_emblang
4b7092b8f4dfdc5240ed8ecf8e18ec75b9e0141c
[ "BSD-3-Clause" ]
null
null
null
image_generation/treeutils.py
mihirp1998/blender_emblang
4b7092b8f4dfdc5240ed8ecf8e18ec75b9e0141c
[ "BSD-3-Clause" ]
null
null
null
import _init_paths import os import sys import argparse import os.path as osp import random import numpy as np import utils from mathutils import Vector from lib.tree import Tree from modules import Layout, Combine, Describe # Made changes to expand_tree(), sample_tree_flexible(), refine_tree_info(), _set_describe_bbox(), _combine_bbox() # Ready for 3d ######### hyperparameters ########## # module list module_list = ['layout', 'describe', 'combine'] # children dict children_dict = dict() children_dict['layout'] = 2 children_dict['describe'] = 1 children_dict['combine'] = 1 # we will have two split dict for modules for designing a zero-shot setting module_dict_split1 = dict() module_dict_split2 = dict() module_dict_all = dict() # Zero shot split # objects list module_dict_split1['describe'] = ['cube'] module_dict_split2['describe'] = ['cylinder', 'sphere'] module_dict_all['describe'] = ['cylinder', 'cube', 'sphere'] # module_dict_all['describe'] = ['cup'] # attributes list attribute_list = ['material', 'color', 'size'] module_dict_split1['combine'] = {'material': ['metal'], 'color': ['green', 'blue', 'yellow', 'red'], 'size': ['large', 'small']} module_dict_split2['combine'] = {'material': ['rubber'], 'color': ['cyan', 'brown', 'gray', 'purple'], 'size': ['small', 'large']} module_dict_all['combine'] = {'material': ['rubber', 'metal'], 'color': ['cyan', 'brown', 'gray', 'purple', 'green', 'blue', 'yellow', 'red'], 'size': ['small', 'large']} # relations list module_dict_split1['layout'] = ['left', 'left-front', 'right-front'] module_dict_split2['layout'] = ['right', 'right-behind', 'left-behind'] module_dict_all['layout'] = ['right', 'left', 'right-behind', 'left-front', 'left-behind', 'right-front', 'front', 'behind'] module_dicts_zeroshot = [module_dict_split1, module_dict_split2] module_dict_normal = module_dict_all module_dicts_inside = dict() module_dicts_inside['describe'] = ['cylinder', 'cube', 'sphere', 'cup'] module_dicts_inside['combine'] = {'material': ['rubber', 'metal'], 'color': ['cyan', 'brown', 'gray', 'purple', 'green', 'blue', 'yellow', 'red'], 'size': ['large']} module_dicts_inside['layout'] = ['inside'] module_dicts_back_front = dict() module_dicts_back_front['describe'] = ['cylinder', 'cube', 'sphere'] module_dicts_back_front['combine'] = {'material': ['rubber', 'metal'], 'color': ['cyan', 'brown', 'gray', 'purple', 'green', 'blue', 'yellow', 'red'], 'size': ['large']} module_dicts_back_front['layout'] = ['front', 'behind'] pattern_map = {'describe': 0, 'material': 1, 'color': 2, 'size': 3, 'layout': 4} zs_training_patterns = [(0, 1, 0, 1, 0), (1, 0, 1, 0, 1)] zs_training_probs = [1.0 / 3, 2.0 / 3] zs_test_patterns = [(1, 1, 1, 1, 1), (0, 0, 0, 0, 0), (0, 0, 1, 1, 1), (1, 1, 0, 0, 0), (0, 1, 1, 1, 0), (1, 0, 0, 0, 1), (0, 1, 1, 1, 1), (1, 0, 0, 0, 0)] zs_test_probs = [1.0 / 6, 1.0 / 12, 1.0 / 12, 1.0 / 6, 1.0 / 12, 1.0 / 6, 1.0 / 12, 1.0 / 6] def expand_tree_with_inside(tree, level, parent, memorylist, child_idx, max_layout_level, add_layout_prob, train, obj_count, zero_shot=False, metadata_pattern=None, back_front_only_flag=False): if parent is None or parent.function == 'layout': # sample module, the module can be either layout or describe here if level + 1 > max_layout_level: module_idx = 1 else: module_idx = 0 tree.function = module_list[module_idx] if zero_shot and (level == 0 or tree.function == 'describe'): r = random.random() if train: metadata_pattern = _choose_pattern(zs_training_patterns, zs_training_probs, r) else: metadata_pattern = _choose_pattern(zs_test_patterns, zs_test_probs, r) # sample content if zero_shot: assert (metadata_pattern is not None) dict_index = metadata_pattern[pattern_map[tree.function]] module_dict = module_dicts_zeroshot[dict_index] else: module_dict = module_dicts_inside if tree.function == 'describe' and child_idx == 1: tree.word = module_dict[tree.function][-1] elif tree.function == 'layout': tree.word = module_dict[tree.function][-1] else: word_id = random.randint(0, len(module_dict[tree.function]) - 2) tree.word = module_dict[tree.function][word_id] if tree.function == 'layout': tree.function_obj = Layout(tree.word) # print('add layout') else: obj_count += 1 tree.function_obj = Describe(tree.word, obj_count) # print('add describe') tree.num_children = children_dict[tree.function] if parent is not None: # then the parent must be a layout node if child_idx == 0: parent.function_obj.left_child = tree.function_obj else: parent.function_obj.right_child = tree.function_obj for i in range(tree.num_children): tree.children.append(Tree()) tree.children[i], obj_count = expand_tree_with_inside(tree.children[i], level + 1, tree, [], i, max_layout_level, add_layout_prob, train, obj_count, zero_shot, metadata_pattern, back_front_only_flag) # must contain only one child node, which is a combine node elif parent.function == 'describe' or parent.function == 'combine': # print('add combine') valid = [2] # no need to sample module for now module_id = 0 tree.function = module_list[valid[module_id]] # sample content # sample which attributes if len(set(attribute_list) - set(memorylist)) <= 1: full_attribute = True else: full_attribute = False attribute = random.sample(set(attribute_list) - set(memorylist), 1)[0] memorylist += [attribute] if zero_shot: assert (metadata_pattern is not None) dict_idx = metadata_pattern[pattern_map[attribute]] module_dict = module_dicts_zeroshot[dict_idx] else: module_dict = module_dict_normal word_id = random.randint(0, len(module_dict[tree.function][attribute]) - 1) tree.word = module_dict[tree.function][attribute][word_id] if isinstance(parent.function_obj, Describe): carrier = parent.function_obj else: carrier = parent.function_obj.get_carrier() tree.function_obj = Combine(attribute, tree.word) tree.function_obj.set_carrier(carrier) carrier.set_attribute(attribute, tree.function_obj) if not full_attribute: tree.num_children = children_dict[tree.function] for i in range(tree.num_children): tree.children.append(Tree()) tree.children[i], obj_count = expand_tree_with_inside(tree.children[i], level + 1, tree, memorylist, i, max_layout_level, add_layout_prob, train, obj_count, zero_shot, metadata_pattern, back_front_only_flag) else: raise ValueError('Wrong function.') return tree, obj_count def expand_tree(tree, level, parent, memorylist, child_idx, max_layout_level, add_layout_prob, train, obj_count, zero_shot=False, metadata_pattern=None, back_front_only_flag=False): if parent is None or parent.function == 'layout': # sample module, the module can be either layout or describe here if level + 1 > max_layout_level: module_idx = 1 else: rand = random.random() if rand >= 1 - add_layout_prob: module_idx = 0 else: module_idx = 1 tree.function = module_list[module_idx] if zero_shot and (level == 0 or tree.function == 'describe'): r = random.random() if train: metadata_pattern = _choose_pattern(zs_training_patterns, zs_training_probs, r) else: metadata_pattern = _choose_pattern(zs_test_patterns, zs_test_probs, r) # sample content if zero_shot: assert (metadata_pattern is not None) dict_index = metadata_pattern[pattern_map[tree.function]] module_dict = module_dicts_zeroshot[dict_index] elif back_front_only_flag: module_dict = module_dicts_back_front else: module_dict = module_dict_normal word_id = random.randint(0, len(module_dict[tree.function]) - 1) tree.word = module_dict[tree.function][word_id] if tree.function == 'layout': tree.function_obj = Layout(tree.word) # print('add layout') else: obj_count += 1 tree.function_obj = Describe(tree.word, obj_count) # print('add describe') tree.num_children = children_dict[tree.function] if parent is not None: # then the parent must be a layout node if child_idx == 0: parent.function_obj.left_child = tree.function_obj else: parent.function_obj.right_child = tree.function_obj for i in range(tree.num_children): tree.children.append(Tree()) tree.children[i], obj_count = expand_tree(tree.children[i], level + 1, tree, [], i, max_layout_level, add_layout_prob, train, obj_count, zero_shot, metadata_pattern, back_front_only_flag) # must contain only one child node, which is a combine node elif parent.function == 'describe' or parent.function == 'combine': # print('add combine') valid = [2] # no need to sample module for now module_id = 0 tree.function = module_list[valid[module_id]] # sample content # sample which attributes if len(set(attribute_list) - set(memorylist)) <= 1: full_attribute = True else: full_attribute = False attribute = random.sample(set(attribute_list) - set(memorylist), 1)[0] memorylist += [attribute] if zero_shot: assert (metadata_pattern is not None) dict_idx = metadata_pattern[pattern_map[attribute]] module_dict = module_dicts_zeroshot[dict_idx] else: module_dict = module_dict_normal word_id = random.randint(0, len(module_dict[tree.function][attribute]) - 1) tree.word = module_dict[tree.function][attribute][word_id] if isinstance(parent.function_obj, Describe): carrier = parent.function_obj else: carrier = parent.function_obj.get_carrier() tree.function_obj = Combine(attribute, tree.word) tree.function_obj.set_carrier(carrier) carrier.set_attribute(attribute, tree.function_obj) if not full_attribute: tree.num_children = children_dict[tree.function] for i in range(tree.num_children): tree.children.append(Tree()) tree.children[i], obj_count = expand_tree(tree.children[i], level + 1, tree, memorylist, i, max_layout_level, add_layout_prob, train, obj_count, zero_shot, metadata_pattern, back_front_only_flag) else: raise ValueError('Wrong function.') return tree, obj_count def _choose_pattern(patterns, probs, r): assert (sum(probs) == 1, 'Given prob list should sum up to 1') assert (len(patterns) == len(probs), 'Given patterns should have the same length as the given probs') accum = 0 for i, prob in enumerate(probs): accum += prob if r < accum: return patterns[i] def visualize_trees(trees): for i in range(len(trees)): print('************** tree **************') _visualize_tree(trees[i], 0) print('**********************************') def _visualize_tree(tree, level): if tree == None: return for i in range(tree.num_children - 1, (tree.num_children - 1) // 2, -1): _visualize_tree(tree.children[i], level + 1) print(' ' * level + tree.word) if isinstance(tree.function_obj, Describe): print(tree.function_obj.attributes, tree.function_obj) if tree.function != 'combine': print('position {}'.format(tree.function_obj.position)) for i in range((tree.num_children - 1) // 2, -1, -1): _visualize_tree(tree.children[i], level + 1) return def allign_tree(tree, level): """ A pre-order traversal, set the position of tree nodes according to the layouts :param tree: :return: """ if tree is None: return if tree.function == 'describe' and level == 0: tree.function_obj.set_random_pos() elif tree.function == 'layout': tree.function_obj.set_children_pos() for i in range(tree.num_children): allign_tree(tree.children[i], level + 1) else: pass def extract_objects(tree): objects = list() if tree is None: return objects if tree.function == 'describe': objects.append(tree.function_obj) elif tree.function == 'layout': for i in range(tree.num_children): objects += extract_objects(tree.children[i]) else: pass return objects def sample_tree(max_layout_level, add_layout_prob, obj_count, zero_shot=False, train=True): tree = Tree() tree, obj_count = expand_tree(tree, 0, None, [], 0, max_layout_level, add_layout_prob, train, obj_count, zero_shot=zero_shot) allign_tree(tree, 0) return tree def sample_tree_flexible(percent_inside_samples, include_inside_config, max_layout_level, add_layout_prob, obj_count, zero_shot=False, train=True, arguments=None, back_front_only_flag=False): tree = Tree() if not include_inside_config: expand_func = expand_tree else: rand = random.random() if rand < percent_inside_samples: arguments = {'fix_num_objs':2} expand_func = expand_tree_with_inside max_layout_level = 1 else: expand_func = expand_tree if arguments is None: tree, obj_count = expand_func(tree, 0, None, [], 0, max_layout_level, add_layout_prob, train, obj_count, zero_shot=zero_shot, back_front_only_flag=back_front_only_flag) else: max_num_objs = arguments['max_num_objs'] min_num_objs = arguments['min_num_objs'] object_count_range = range(min_num_objs, max_num_objs + 1) tree, obj_count = expand_func(tree, 0, None, [], 0, max_layout_level, add_layout_prob, train, obj_count, zero_shot=zero_shot, back_front_only_flag=back_front_only_flag) num_objs = count_functions(tree, 'describe') while num_objs not in object_count_range: tree = Tree() tree, obj_count = expand_func(tree, 0, None, [], 0, max_layout_level, add_layout_prob, train, obj_count, zero_shot=zero_shot, back_front_only_flag=back_front_only_flag) num_objs = count_functions(tree, 'describe') # if 'max_num_objs' in arguments: # max_num_objs = arguments['max_num_objs'] # tree, obj_count = expand_func(tree, 0, None, [], 0, max_layout_level, add_layout_prob, train, obj_count, zero_shot=zero_shot, back_front_only_flag=back_front_only_flag) # num_objs = count_functions(tree, 'describe') # while num_objs > max_num_objs: # tree = Tree() # tree, obj_count = expand_func(tree, 0, None, [], 0, max_layout_level, add_layout_prob, train, obj_count, zero_shot=zero_shot, back_front_only_flag=back_front_only_flag) # num_objs = count_functions(tree, 'describe') # print(num_objs) # elif 'fix_num_objs' in arguments: # fix_num_objs = arguments['fix_num_objs'] # tree, obj_count = expand_func(tree, 0, None, [], 0, max_layout_level, add_layout_prob, train, obj_count, zero_shot=zero_shot, back_front_only_flag=back_front_only_flag) # num_objs = count_functions(tree, 'describe') # while num_objs != fix_num_objs: # tree = Tree() # tree, obj_count = expand_func(tree, 0, None, [], 0, max_layout_level, add_layout_prob, train, obj_count, zero_shot=zero_shot, back_front_only_flag=back_front_only_flag) # num_objs = count_functions(tree, 'describe') allign_tree(tree, 0) return tree def count_functions(tree, name): num_functions = _count_functions(tree, name) return num_functions def _count_functions(tree, name): num_objs = 0 for i in range(0, tree.num_children): num_objs += _count_functions(tree.children[i], name) if tree.function == name: num_objs += 1 return num_objs # def _project_bbox(camera, points_3d): # points_2d = [utils.get_camera_coords(camera, Vector(location)) for location in points_3d] # x_cords = [location[0] for location in points_2d] # y_cords = [location[1] for location in points_2d] # left_top = (min(x_cords), min(y_cords)) # right_bottom = (max(x_cords), max(y_cords)) # # print('-'*50) # # print(points_3d, points_2d) # # print('-'*50) # return [left_top, right_bottom] # def _get_describe_bbox(tree, blocks, camera, bboxes_2d): # function_obj = tree.function_obj # # set the bbox for the tree node # if hasattr(function_obj, 'bbox'): # block_id = function_obj.block_id # object_idx = np.where(blocks == block_id) # x_top = object_idx[0].min() # y_top = object_idx[1].min() # z_top = object_idx[2].min() # x_bottom = object_idx[0].max() # y_bottom = object_idx[1].max() # z_bottom = object_idx[2].max() # points_3d = [[x_top, y_top, z_top],[x_bottom - x_top, # y_bottom - y_top, z_bottom - z_top]] # bbox = _project_bbox(camera, points_3d) # bboxes_2d[block_id] = bbox # for child in tree.children: # bboxes_2d = _get_describe_bbox(child, blocks, camera, bboxes_2d) # return bboxes_2d # def get_2d_bboxes(tree, blocks, camera): # bboxes_2d = {} # bboxes_2d = _get_describe_bbox(tree, blocks, camera, bboxes_2d) # return bboxes_2d def refine_tree_info(tree, blocks): tree = _set_describe_bbox(tree, blocks) tree = _set_layout_bbox(tree) return tree def remove_function_obj(tree): tree = _remove_function_obj(tree) return tree def _remove_function_obj(tree): if hasattr(tree, 'function_obj'): delattr(tree, 'function_obj') for child in tree.children: _remove_function_obj(child) return tree def _set_describe_bbox(tree, blocks): function_obj = tree.function_obj # set the bbox for the tree node if hasattr(function_obj, 'bbox'): block_id = function_obj.block_id object_idx = np.where(blocks == block_id) # try: # x_top = object_idx[0].min() # except Exception as e: # print(blocks.max()) # print(blocks.min()) # print(np.unique(blocks)) # print(block_id) x_top = object_idx[0].min() y_top = object_idx[1].min() z_top = object_idx[2].min() x_bottom = object_idx[0].max() y_bottom = object_idx[1].max() z_bottom = object_idx[2].max() # bbox = (x_top, y_top, z_top, x_bottom - x_top, y_bottom - y_top, z_bottom - z_top) bbox = (x_top, z_top, y_top, x_bottom - x_top, z_bottom - z_top, y_bottom - y_top) tree.bbox = np.array(bbox) # print(x_top, y_top, z_top, x_bottom, y_bottom, z_bottom) # print(tree.bbox) # print(tree.word) # print('--------------') for child in tree.children: _set_describe_bbox(child, blocks) return tree def _set_layout_bbox(tree): if tree.function != 'layout': return tree else: for child in tree.children: _set_layout_bbox(child) # set the bbox for layout module left_child_bbox = tree.children[0].bbox right_child_bbox = tree.children[1].bbox tree.bbox = np.array(_combine_bbox(left_child_bbox, right_child_bbox)) return tree def _correct_layout_word(tree): if tree.function != 'layout': return tree else: left_child_bbox = tree.children[0].bbox right_child_bbox = tree.children[1].bbox if left_child_bbox[0] < right_child_bbox[0]: if right_child_bbox[1] - 5 < left_child_bbox[1] < right_child_bbox[1] + 5: tree.word = 'left' elif left_child_bbox[1] <= right_child_bbox[1] - 5: tree.word = 'left-behind' else: tree.word = 'left-front' else: if right_child_bbox[1] - 5 < left_child_bbox[1] < right_child_bbox[1] + 5: tree.word = 'right' elif left_child_bbox[1] <= right_child_bbox[1] - 5: tree.word = 'right-behind' else: tree.word = 'right-front' for child in tree.children: _correct_layout_word(child) return tree def _combine_bbox(bbox1, bbox2): x = min(bbox1[0], bbox2[0]) y = min(bbox1[1], bbox2[1]) z = min(bbox1[2], bbox2[2]) x_bottom = max(bbox1[0] + bbox1[3], bbox2[0] + bbox2[3]) y_bottom = max(bbox1[1] + bbox1[4], bbox2[1] + bbox2[4]) z_bottom = max(bbox1[2] + bbox1[5], bbox2[2] + bbox2[5]) return [x, y, z, x_bottom - x, y_bottom - y, z_bottom - z] def add_parent(tree): tree = _add_parent(tree, None) return tree def _add_parent(tree, parent): tree.parent = parent for i in range(0, tree.num_children): tree.children[i] = _add_parent(tree.children[i], tree) if __name__ == '__main__': # random.seed(12113) # # # tree = Tree() # # tree = expand_tree(tree, 0, None, [], 0) # # allign_tree(tree) # # num_sample = 1 # trees = [] # for i in range(num_sample): # treei = Tree() # treei = expand_tree(treei, 0, None, [], 0, max_level=2) # allign_tree(treei, 0) # objects = extract_objects(treei) # trees += [treei] # print(objects) # # visualize_tree(trees) for i in range(1): print('normal sample tree') tree = sample_tree(max_layout_level=2, add_layout_prob=0.6, zero_shot=True, train=True) visualize_trees([tree]) print('max sample tree') tree = sample_tree_flexible(max_layout_level=3, add_layout_prob=0.6, zero_shot=False, train=True, arguments={'max_num_objs': 3}) visualize_trees([tree]) print('fix sample tree') tree = sample_tree_flexible(max_layout_level=3, add_layout_prob=0.6, zero_shot=False, train=True, arguments={'fix_num_objs': 8}) visualize_trees([tree])
37.96463
191
0.607902
1e2369717aa0ac2565fd6fb38fa64b90419dc9db
85,131
py
Python
Blender 2.91/2.91/scripts/addons/measureit/measureit_main.py
calculusrobotics/RNNs-for-Bayesian-State-Estimation
2aacf86d2e447e10c840b4926d4de7bc5e46d9bc
[ "MIT" ]
1
2021-06-30T00:39:40.000Z
2021-06-30T00:39:40.000Z
release/scripts/addons/measureit/measureit_main.py
ringsce/Rings3D
8059d1e2460fc8d6f101eff8e695f68a99f6671d
[ "Naumen", "Condor-1.1", "MS-PL" ]
null
null
null
release/scripts/addons/measureit/measureit_main.py
ringsce/Rings3D
8059d1e2460fc8d6f101eff8e695f68a99f6671d
[ "Naumen", "Condor-1.1", "MS-PL" ]
null
null
null
# ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # ##### END GPL LICENSE BLOCK ##### # <pep8 compliant> # ---------------------------------------------------------- # File: measureit_main.py # Main panel for different Measureit general actions # Author: Antonio Vazquez (antonioya) # # ---------------------------------------------------------- # noinspection PyUnresolvedReferences import bpy import bmesh from bmesh import from_edit_mesh # noinspection PyUnresolvedReferences import bgl from bpy.types import PropertyGroup, Panel, Object, Operator, SpaceView3D from bpy.props import IntProperty, CollectionProperty, FloatVectorProperty, BoolProperty, StringProperty, \ FloatProperty, EnumProperty from bpy.app.handlers import persistent # noinspection PyUnresolvedReferences from .measureit_geometry import * from .measureit_render import * # ------------------------------------------------------ # Handler to detect new Blend load # # ------------------------------------------------------ # noinspection PyUnusedLocal @persistent def load_handler(dummy): MEASUREIT_OT_RunHintDisplay.handle_remove(None, bpy.context) # ------------------------------------------------------ # Handler to detect save Blend # Clear not used measured # # ------------------------------------------------------ # noinspection PyUnusedLocal @persistent def save_handler(dummy): # noinspection PyBroadException try: print("MeasureIt: Cleaning data") objlist = bpy.context.scene.objects for myobj in objlist: if 'MeasureGenerator' in myobj: mp = myobj.MeasureGenerator[0] x = 0 for ms in mp.measureit_segments: ms.name = "segment_" + str(x) x += 1 if ms.glfree is True: idx = mp.measureit_segments.find(ms.name) if idx > -1: print("MeasureIt: Removed segment not used") mp.measureit_segments.remove(idx) # reset size mp.measureit_num = len(mp.measureit_segments) except: pass bpy.app.handlers.load_post.append(load_handler) bpy.app.handlers.save_pre.append(save_handler) # ------------------------------------------------------------------ # Define property group class for measureit faces index # ------------------------------------------------------------------ class MeasureitIndex(PropertyGroup): glidx: IntProperty(name="index", description="vertex index") # Register bpy.utils.register_class(MeasureitIndex) # ------------------------------------------------------------------ # Define property group class for measureit faces # ------------------------------------------------------------------ class MeasureitFaces(PropertyGroup): glface: IntProperty(name="glface", description="Face number") # Array of index measureit_index: CollectionProperty(type=MeasureitIndex) # Register bpy.utils.register_class(MeasureitFaces) # ------------------------------------------------------------------ # Define property group class for measureit data # ------------------------------------------------------------------ class MeasureitProperties(PropertyGroup): gltype: IntProperty(name="gltype", description="Measure type (1-Segment, 2-Label, etc..)", default=1) glpointa: IntProperty(name="glpointa", description="Hidden property for opengl") glpointb: IntProperty(name="glpointb", description="Hidden property for opengl") glpointc: IntProperty(name="glpointc", description="Hidden property for opengl") glcolor: FloatVectorProperty(name="glcolor", description="Color for the measure", default=(0.173, 0.545, 1.0, 1.0), min=0.1, max=1, subtype='COLOR', size=4) glview: BoolProperty(name="glview", description="Measure visible/hide", default=True) glspace: FloatProperty(name='glspace', min=-100, max=100, default=0.1, precision=3, description='Distance to display measure') glwidth: IntProperty(name='glwidth', min=1, max=10, default=1, description='line width') glfree: BoolProperty(name="glfree", description="This measure is free and can be deleted", default=False) gltxt: StringProperty(name="gltxt", maxlen=256, description="Short description (use | for line break)") gladvance: BoolProperty(name="gladvance", description="Advanced options as line width or position", default=False) gldefault: BoolProperty(name="gldefault", description="Display measure in position calculated by default", default=True) glnormalx: FloatProperty(name="glnormalx", description="Change orientation in X axis", default=1, min=-1, max=1, precision=2) glnormaly: FloatProperty(name="glnormaly", description="Change orientation in Y axis", default=0, min=-1, max=1, precision=2) glnormalz: FloatProperty(name="glnormalz", description="Change orientation in Z axis", default=0, min=-1, max=1, precision=2) glfont_size: IntProperty(name="Text Size", description="Text size", default=14, min=6, max=150) glfont_align: EnumProperty(items=(('L', "Left Align", ""), ('C', "Center Align", ""), ('R', "Right Align", "")), name="Align Font", description="Set Font Alignment") glfont_rotat: IntProperty(name='Rotate', min=0, max=360, default=0, description="Text rotation in degrees") gllink: StringProperty(name="gllink", description="linked object for linked measures") glocwarning: BoolProperty(name="glocwarning", description="Display a warning if some axis is not used in distance", default=True) glocx: BoolProperty(name="glocx", description="Include changes in X axis for calculating the distance", default=True) glocy: BoolProperty(name="glocy", description="Include changes in Y axis for calculating the distance", default=True) glocz: BoolProperty(name="glocz", description="Include changes in Z axis for calculating the distance", default=True) glfontx: IntProperty(name="glfontx", description="Change font position in X axis", default=0, min=-3000, max=3000) glfonty: IntProperty(name="glfonty", description="Change font position in Y axis", default=0, min=-3000, max=3000) gldist: BoolProperty(name="gldist", description="Display distance for this measure", default=True) glnames: BoolProperty(name="glnames", description="Display text for this measure", default=True) gltot: EnumProperty(items=(('99', "-", "Select a group for sum"), ('0', "A", ""), ('1', "B", ""), ('2', "C", ""), ('3', "D", ""), ('4', "E", ""), ('5', "F", ""), ('6', "G", ""), ('7', "H", ""), ('8', "I", ""), ('9', "J", ""), ('10', "K", ""), ('11', "L", ""), ('12', "M", ""), ('13', "N", ""), ('14', "O", ""), ('15', "P", ""), ('16', "Q", ""), ('17', "R", ""), ('18', "S", ""), ('19', "T", ""), ('20', "U", ""), ('21', "V", ""), ('22', "W", ""), ('23', "X", ""), ('24', "Y", ""), ('25', "Z", "")), name="Sum in Group", description="Add segment length in selected group") glorto: EnumProperty(items=(('99', "None", ""), ('0', "A", "Point A must use selected point B location"), ('1', "B", "Point B must use selected point A location")), name="Orthogonal", description="Display point selected as orthogonal (select axis to copy)") glorto_x: BoolProperty(name="ox", description="Copy X location", default=False) glorto_y: BoolProperty(name="oy", description="Copy Y location", default=False) glorto_z: BoolProperty(name="oz", description="Copy Z location", default=False) glarrow_a: EnumProperty(items=(('99', "--", "No arrow"), ('1', "Line", "The point of the arrow are lines"), ('2', "Triangle", "The point of the arrow is triangle"), ('3', "TShape", "The point of the arrow is a T")), name="A end", description="Add arrows to point A") glarrow_b: EnumProperty(items=(('99', "--", "No arrow"), ('1', "Line", "The point of the arrow are lines"), ('2', "Triangle", "The point of the arrow is triangle"), ('3', "TShape", "The point of the arrow is a T")), name="B end", description="Add arrows to point B") glarrow_s: IntProperty(name="Size", description="Arrow size", default=15, min=6, max=500) glarc_full: BoolProperty(name="arcfull", description="Create full circunference", default=False) glarc_extrad: BoolProperty(name="arcextrad", description="Adapt radio length to arc line", default=True) glarc_rad: BoolProperty(name="arc rad", description="Show arc radius", default=True) glarc_len: BoolProperty(name="arc len", description="Show arc length", default=True) glarc_ang: BoolProperty(name="arc ang", description="Show arc angle", default=True) glarc_a: EnumProperty(items=(('99', "--", "No arrow"), ('1', "Line", "The point of the arrow are lines"), ('2', "Triangle", "The point of the arrow is triangle"), ('3', "TShape", "The point of the arrow is a T")), name="Ar end", description="Add arrows to point A") glarc_b: EnumProperty(items=(('99', "--", "No arrow"), ('1', "Line", "The point of the arrow are lines"), ('2', "Triangle", "The point of the arrow is triangle"), ('3', "TShape", "The point of the arrow is a T")), name="Br end", description="Add arrows to point B") glarc_s: IntProperty(name="Size", description="Arrow size", default=15, min=6, max=500) glarc_txradio: StringProperty(name="txradio", description="Text for radius", default="r=") glarc_txlen: StringProperty(name="txlen", description="Text for length", default="L=") glarc_txang: StringProperty(name="txang", description="Text for angle", default="A=") glcolorarea: FloatVectorProperty(name="glcolorarea", description="Color for the measure of area", default=(0.1, 0.1, 0.1, 1.0), min=0.1, max=1, subtype='COLOR', size=4) # Array of faces measureit_faces: CollectionProperty(type=MeasureitFaces) # Register bpy.utils.register_class(MeasureitProperties) # ------------------------------------------------------------------ # Define object class (container of segments) # Measureit # ------------------------------------------------------------------ class MeasureContainer(PropertyGroup): measureit_num: IntProperty(name='Number of measures', min=0, max=1000, default=0, description='Number total of measureit elements') # Array of segments measureit_segments: CollectionProperty(type=MeasureitProperties) bpy.utils.register_class(MeasureContainer) Object.MeasureGenerator = CollectionProperty(type=MeasureContainer) # ------------------------------------------------------------------ # Define UI class # Measureit # ------------------------------------------------------------------ class MEASUREIT_PT_Edit(Panel): bl_idname = "MEASUREIT_PT_Edit" bl_label = "Items" bl_space_type = 'VIEW_3D' bl_region_type = 'UI' bl_category= 'View' bl_parent_id = 'MEASUREIT_PT_Main' # ----------------------------------------------------- # Verify if visible # ----------------------------------------------------- @classmethod def poll(cls, context): o = context.object if o is None: return False if 'MeasureGenerator' not in o: return False else: mp = context.object.MeasureGenerator[0] if mp.measureit_num > 0: return True else: return False # ----------------------------------------------------- # Draw (create UI interface) # ----------------------------------------------------- # noinspection PyUnusedLocal def draw(self, context): layout = self.layout scene = context.scene if context.object is not None: if 'MeasureGenerator' in context.object: box = layout.box() row = box.row() row.label(text=context.object.name) row = box.row() row.prop(scene, 'measureit_gl_precision', text="Precision") row.prop(scene, 'measureit_units') row = box.row() row.prop(scene, 'measureit_gl_show_d', text="Distances", toggle=True, icon="ALIGN_CENTER") row.prop(scene, 'measureit_gl_show_n', text="Texts", toggle=True, icon="FONT_DATA") row = box.row() row.prop(scene, 'measureit_hide_units', text="Hide measurement unit") # Scale factor row = box.row() row.prop(scene, 'measureit_scale', text="Scale") if scene.measureit_scale is True: split = row.split(factor=0.25, align=False) split.prop(scene, 'measureit_scale_color', text="") split.prop(scene, 'measureit_scale_factor', text="1") row = box.row() row.separator() row.prop(scene, 'measureit_gl_scaletxt', text="") row.prop(scene, 'measureit_scale_font') row.prop(scene, 'measureit_scale_precision', text="") row = box.row() row.separator() row.prop(scene, 'measureit_scale_pos_x') row.prop(scene, 'measureit_scale_pos_y') # Override row = box.row() row.prop(scene, 'measureit_ovr', text="Override") if scene.measureit_ovr is True: split = row.split(factor=0.25, align=False) split.prop(scene, 'measureit_ovr_color', text="") split.prop(scene, 'measureit_ovr_width', text="Width") row = box.row() row.separator() row.prop(scene, 'measureit_ovr_font', text="Font") row.prop(scene, 'measureit_ovr_font_align', text="") if scene.measureit_ovr_font_align == 'L': row.prop(scene, 'measureit_ovr_font_rotation', text="Rotate") mp = context.object.MeasureGenerator[0] # ----------------- # loop # ----------------- if mp.measureit_num > 0: box = layout.box() row = box.row(align=True) row.operator("measureit.expandallsegment", text="Expand all", icon="ZOOM_IN") row.operator("measureit.collapseallsegment", text="Collapse all", icon="ZOOM_OUT") for idx in range(mp.measureit_num): if mp.measureit_segments[idx].glfree is False: add_item(box, idx, mp.measureit_segments[idx]) row = box.row() row.operator("measureit.deleteallsegment", text="Delete all", icon="X") # ----------------- # Sum loop segments # ----------------- if mp.measureit_num > 0: scale = bpy.context.scene.unit_settings.scale_length tx = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"] tot = [0.0] * len(tx) ac = [False] * len(tx) myobj = context.object obverts = get_mesh_vertices(myobj) viewtot = False for idx in range(mp.measureit_num): ms = mp.measureit_segments[idx] if (ms.gltype == 1 or ms.gltype == 12 or ms.gltype == 13 or ms.gltype == 14) and ms.gltot != '99' \ and ms.glfree is False: # only segments if bpy.context.mode == "EDIT_MESH": bm = bmesh.from_edit_mesh(bpy.context.edit_object.data) if hasattr(bm.verts, "ensure_lookup_table"): bm.verts.ensure_lookup_table() if ms.glpointa <= len(obverts) and ms.glpointb <= len(obverts): p1 = get_point(obverts[ms.glpointa].co, myobj) if ms.gltype == 1: p2 = get_point(obverts[ms.glpointb].co, myobj) elif ms.gltype == 12: p2 = get_point((0.0, obverts[ms.glpointa].co[1], obverts[ms.glpointa].co[2]), myobj) elif ms.gltype == 13: p2 = get_point((obverts[ms.glpointa].co[0], 0.0, obverts[ms.glpointa].co[2]), myobj) else: p2 = get_point((obverts[ms.glpointa].co[0], obverts[ms.glpointa].co[1], 0.0), myobj) dist, distloc = distance(p1, p2, ms.glocx, ms.glocy, ms.glocz) if dist == distloc: usedist = dist else: usedist = distloc usedist *= scale tot[int(ms.gltot)] += usedist ac[int(ms.gltot)] = True viewtot = True # ----------------- # Print values # ----------------- if viewtot is True: pr = scene.measureit_gl_precision fmt = "%1." + str(pr) + "f" units = scene.measureit_units box = layout.box() box.label(text="Totals", icon='SOLO_ON') final = 0 for idx in range(len(tot)): if ac[idx] is True: final += tot[idx] tx_dist = format_distance(fmt, units, tot[idx]) row = box.row(align=True) row.label(text="Group " + tx[idx] + ":") row.label(text=" ") row.label(text=tx_dist) # Grand total row = box.row(align=True) row.label(text="") row.label(text=" ") row.label(text="-" * 20) tx_dist = format_distance(fmt, units, final) row = box.row(align=True) row.label(text="") row.label(text=" ") row.label(text=tx_dist) # delete all row = box.row() row.operator("measureit.deleteallsum", text="Delete all", icon="X") # ----------------------------------------------------- # Add segment options to the panel. # ----------------------------------------------------- def add_item(box, idx, segment): scene = bpy.context.scene row = box.row(align=True) if segment.glview is True: icon = "HIDE_OFF" else: icon = "HIDE_ON" row.prop(segment, 'glview', text="", toggle=True, icon=icon) row.prop(segment, 'gladvance', text="", toggle=True, icon="PREFERENCES") if segment.gltype == 20: # Area special split = row.split(factor=0.15, align=True) split.prop(segment, 'glcolorarea', text="") split = split.split(factor=0.20, align=True) split.prop(segment, 'glcolor', text="") else: split = row.split(factor=0.25, align=True) split.prop(segment, 'glcolor', text="") split.prop(segment, 'gltxt', text="") op = row.operator("measureit.deletesegment", text="", icon="X") op.tag = idx # saves internal data if segment.gladvance is True: row = box.row(align=True) row.prop(segment, 'glfont_size', text="Font") row.prop(segment, 'glfont_align', text="") if segment.glfont_align == 'L': row.prop(segment, 'glfont_rotat', text="Rotate") row = box.row(align=True) if segment.gltype != 9 and segment.gltype != 10 and segment.gltype != 20: row.prop(segment, 'glspace', text="Distance") row.prop(segment, 'glfontx', text="X") row.prop(segment, 'glfonty', text="Y") # Arrows if segment.gltype != 9 and segment.gltype != 10 and segment.gltype != 20: row = box.row(align=True) row.prop(segment, 'glarrow_a', text="") row.prop(segment, 'glarrow_b', text="") if segment.glarrow_a != '99' or segment.glarrow_b != '99': row.prop(segment, 'glarrow_s', text="Size") if segment.gltype != 2 and segment.gltype != 10: row = box.row(align=True) if scene.measureit_gl_show_d is True and segment.gltype != 9: row.prop(segment, 'gldist', text="Distance", toggle=True, icon="ALIGN_CENTER") if scene.measureit_gl_show_n is True: row.prop(segment, 'glnames', text="Text", toggle=True, icon="FONT_DATA") # sum distances if segment.gltype == 1 or segment.gltype == 12 or segment.gltype == 13 or segment.gltype == 14: row.prop(segment, 'gltot', text="Sum") if segment.gltype != 9 and segment.gltype != 10 and segment.gltype != 20: row = box.row(align=True) row.prop(segment, 'glwidth', text="Line") row.prop(segment, 'gldefault', text="Automatic position") if segment.gldefault is False: row = box.row(align=True) row.prop(segment, 'glnormalx', text="X") row.prop(segment, 'glnormaly', text="Y") row.prop(segment, 'glnormalz', text="Z") # Loc axis if segment.gltype != 2 and segment.gltype != 9 and segment.gltype != 10 \ and segment.gltype != 11 and segment.gltype != 12 and segment.gltype != 13 \ and segment.gltype != 14 and segment.gltype != 20: row = box.row(align=True) row.prop(segment, 'glocx', text="X", toggle=True) row.prop(segment, 'glocy', text="Y", toggle=True) row.prop(segment, 'glocz', text="Z", toggle=True) if segment.glocx is False or segment.glocy is False or segment.glocz is False: row = box.row() if segment.gltype == 1: row.prop(segment, 'glorto', text="Orthogonal") row.prop(segment, 'glocwarning', text="Warning") # ortogonal (only segments) if segment.gltype == 1: if segment.glorto != "99": row = box.row(align=True) row.prop(segment, 'glorto_x', text="X", toggle=True) row.prop(segment, 'glorto_y', text="Y", toggle=True) row.prop(segment, 'glorto_z', text="Z", toggle=True) # Arc special if segment.gltype == 11: row = box.row(align=True) row.prop(segment, 'glarc_rad', text="Radius") row.prop(segment, 'glarc_len', text="Length") row.prop(segment, 'glarc_ang', text="Angle") row = box.row(align=True) row.prop(segment, 'glarc_txradio', text="") row.prop(segment, 'glarc_txlen', text="") row.prop(segment, 'glarc_txang', text="") row = box.row(align=True) row.prop(segment, 'glarc_full', text="Full Circle") if segment.glarc_rad is True: row.prop(segment, 'glarc_extrad', text="Adapt radio") row = box.row(align=True) row.prop(segment, 'glarc_a', text="") row.prop(segment, 'glarc_b', text="") if segment.glarc_a != '99' or segment.glarc_b != '99': row.prop(segment, 'glarc_s', text="Size") # ------------------------------------------------------------------ # Define panel class for main functions. # ------------------------------------------------------------------ class MEASUREIT_PT_Main(Panel): bl_idname = "MEASUREIT_PT_Main" bl_label = "MeasureIt Tools" bl_space_type = 'VIEW_3D' bl_region_type = 'UI' bl_category= 'View' bl_options = {'DEFAULT_CLOSED'} # ------------------------------ # Draw UI # ------------------------------ def draw(self, context): layout = self.layout scene = context.scene # ------------------------------ # Tool Buttons # ------------------------------ box = layout.box() # ------------------------------ # Display Buttons # ------------------------------ row = box.row() if context.window_manager.measureit_run_opengl is False: icon = 'PLAY' txt = 'Show' else: icon = "PAUSE" txt = 'Hide' row.operator("measureit.runopengl", text=txt, icon=icon) row.prop(scene, "measureit_gl_ghost", text="", icon='GHOST_ENABLED') # Tools box = layout.box() box.label(text="Add Measures") row = box.row() row.operator("measureit.addsegment", text="Segment") row.prop(scene, "measureit_sum", text="Sum") # To origin row = box.row() op = row.operator("measureit.addsegmentorto", text="X") op.tag = 0 # saves internal data op = row.operator("measureit.addsegmentorto", text="Y") op.tag = 1 # saves internal data op = row.operator("measureit.addsegmentorto", text="Z") op.tag = 2 # saves internal data row = box.row() row.operator("measureit.addangle", text="Angle", icon="LINCURVE") row.operator("measureit.addarc", text="Arc") row = box.row() row.operator("measureit.addlabel", text="Label", icon="FONT_DATA") row.operator("measureit.addnote", text="Annotation") row = box.row() row.operator("measureit.addlink", text="Link") row.operator("measureit.addorigin", text="Origin") row = box.row() row.operator("measureit.addarea", text="Area", icon="MESH_GRID") # ------------------------------ # Debug data # ------------------------------ box = layout.box() row = box.row(align=False) if scene.measureit_debug is False: row.prop(scene, "measureit_debug", icon="TRIA_RIGHT", text="Mesh Debug", emboss=False) else: row.prop(scene, "measureit_debug", icon="TRIA_DOWN", text="Mesh Debug", emboss=False) row = box.row() split = row.split(factor=0.10, align=True) split.prop(scene, 'measureit_debug_obj_color', text="") split.prop(scene, "measureit_debug_objects", icon="OBJECT_DATA") split.prop(scene, "measureit_debug_object_loc", icon="EMPTY_DATA") row = box.row() split = row.split(factor=0.10, align=True) split.prop(scene, 'measureit_debug_vert_color', text="") split.prop(scene, "measureit_debug_vertices", icon="VERTEXSEL") split.prop(scene, "measureit_debug_vert_loc", icon="EMPTY_DATA") if scene.measureit_debug_vert_loc is True: split.prop(scene, 'measureit_debug_vert_loc_toggle', text="") row = box.row() split = row.split(factor=0.10, align=True) split.prop(scene, 'measureit_debug_edge_color', text="") split = split.split(factor=0.5, align=True) split.prop(scene, "measureit_debug_edges", icon="EDGESEL") row = box.row() split = row.split(factor=0.10, align=True) split.prop(scene, 'measureit_debug_face_color', text="") split = split.split(factor=0.5, align=True) split.prop(scene, "measureit_debug_faces", icon="FACESEL") row = box.row() split = row.split(factor=0.10, align=True) split.prop(scene, 'measureit_debug_norm_color', text="") if scene.measureit_debug_normals is False: split = split.split(factor=0.50, align=True) split.prop(scene, "measureit_debug_normals", icon="OBJECT_ORIGIN") else: split = split.split(factor=0.5, align=True) split.prop(scene, "measureit_debug_normals", icon="OBJECT_ORIGIN") split.prop(scene, "measureit_debug_normal_size") row = box.row() split = row.split(factor=0.10, align=True) split.separator() split.prop(scene, "measureit_debug_normal_details") split.prop(scene, 'measureit_debug_width', text="Thickness") row = box.row(align=True) row.prop(scene, "measureit_debug_select", icon="GHOST_ENABLED") row.prop(scene, 'measureit_debug_font', text="Font") row.prop(scene, 'measureit_debug_precision', text="Precision") # ------------------------------------------------------------------ # Define panel class for conf functions. # ------------------------------------------------------------------ class MEASUREIT_PT_Conf(Panel): bl_idname = "MEASUREIT_PT_Conf" bl_label = "Configuration" bl_space_type = 'VIEW_3D' bl_region_type = 'UI' bl_category= 'View' bl_parent_id = 'MEASUREIT_PT_Main' bl_options = {'DEFAULT_CLOSED'} # ------------------------------ # Draw UI # ------------------------------ def draw(self, context): layout = self.layout scene = context.scene # Configuration data box = layout.box() row = box.row() split = row.split(factor=0.2, align=True) split.label(text="Text") split = split.split(factor=0.2, align=True) split.prop(scene, "measureit_default_color", text="") split.prop(scene, "measureit_gl_txt", text="") row = box.row(align=True) row.prop(scene, "measureit_hint_space") row.prop(scene, "measureit_font_align", text="") # Arrow row = box.row(align=True) row.prop(scene, "measureit_glarrow_a", text="") row.prop(scene, "measureit_glarrow_b", text="") if scene.measureit_glarrow_a != '99' or scene.measureit_glarrow_b != '99': row.prop(scene, "measureit_glarrow_s", text="Size") row = box.row(align=True) row.prop(scene, "measureit_font_size") if scene.measureit_font_align == 'L': row.prop(scene, "measureit_font_rotation", text="Rotate") # ------------------------------------------------------------------ # Define panel class for render functions. # ------------------------------------------------------------------ class MEASUREIT_PT_Render(Panel): bl_idname = "MEASUREIT_PT_Render" bl_label = "Render" bl_space_type = 'VIEW_3D' bl_region_type = 'UI' bl_category= 'Display' bl_parent_id = 'MEASUREIT_PT_Main' bl_options = {'DEFAULT_CLOSED'} # ------------------------------ # Draw UI # ------------------------------ def draw(self, context): layout = self.layout scene = context.scene # Render settings box = layout.box() row = box.row() row.prop(scene, "measureit_render_type") row = box.row() row.operator("measureit.rendersegment", icon='SCRIPT') row = box.row() row.prop(scene, "measureit_render", text="Save render image") row = box.row() row.prop(scene, "measureit_rf", text="Frame") if scene.measureit_rf is True: row.prop(scene, "measureit_rf_color", text="Color") row = box.row() row.prop(scene, "measureit_rf_border", text="Space") row.prop(scene, "measureit_rf_line", text="Width") # ------------------------------------------------------------- # Defines button that adds a measure segment # # ------------------------------------------------------------- class MEASUREIT_OT_AddSegment(Operator): bl_idname = "measureit.addsegment" bl_label = "Add" bl_description = "(EDITMODE only) Add a new measure segment between 2 vertices (select 2 vertices or more)" # ------------------------------ # Poll # ------------------------------ @classmethod def poll(cls, context): o = context.object if o is None: return False else: if o.type == "MESH": if bpy.context.mode == 'EDIT_MESH': return True else: return False else: return False # ------------------------------ # Execute button action # ------------------------------ def execute(self, context): if context.area.type == 'VIEW_3D': # Add properties scene = context.scene mainobject = context.object mylist = get_smart_selected(mainobject) if len(mylist) < 2: # if not selected linked vertex mylist = get_selected_vertex(mainobject) if len(mylist) >= 2: if 'MeasureGenerator' not in mainobject: mainobject.MeasureGenerator.add() mp = mainobject.MeasureGenerator[0] for x in range(0, len(mylist) - 1, 2): # ----------------------- # Only if not exist # ----------------------- if exist_segment(mp, mylist[x], mylist[x + 1]) is False: # Create all array elements for cont in range(len(mp.measureit_segments) - 1, mp.measureit_num): mp.measureit_segments.add() # Set values ms = mp.measureit_segments[mp.measureit_num] ms.gltype = 1 ms.glpointa = mylist[x] ms.glpointb = mylist[x + 1] ms.glarrow_a = scene.measureit_glarrow_a ms.glarrow_b = scene.measureit_glarrow_b ms.glarrow_s = scene.measureit_glarrow_s # color ms.glcolor = scene.measureit_default_color # dist ms.glspace = scene.measureit_hint_space # text ms.gltxt = scene.measureit_gl_txt ms.glfont_size = scene.measureit_font_size ms.glfont_align = scene.measureit_font_align ms.glfont_rotat = scene.measureit_font_rotation # Sum group ms.gltot = scene.measureit_sum # Add index mp.measureit_num += 1 # redraw context.area.tag_redraw() return {'FINISHED'} else: self.report({'ERROR'}, "MeasureIt: Select at least two vertices for creating measure segment.") return {'FINISHED'} else: self.report({'WARNING'}, "View3D not found, cannot run operator") return {'CANCELLED'} # ------------------------------------------------------------- # Defines button that adds an area measure # # ------------------------------------------------------------- class MEASUREIT_OT_AddArea(Operator): bl_idname = "measureit.addarea" bl_label = "Area" bl_description = "(EDITMODE only) Add a new measure for area (select 1 o more faces)" # ------------------------------ # Poll # ------------------------------ @classmethod def poll(cls, context): o = context.object if o is None: return False else: if o.type == "MESH": if bpy.context.mode == 'EDIT_MESH': return True else: return False else: return False # ------------------------------ # Execute button action # ------------------------------ def execute(self, context): if context.area.type == 'VIEW_3D': # Add properties scene = context.scene mainobject = context.object mylist = get_selected_faces(mainobject) if len(mylist) >= 1: if 'MeasureGenerator' not in mainobject: mainobject.MeasureGenerator.add() mp = mainobject.MeasureGenerator[0] mp.measureit_segments.add() ms = mp.measureit_segments[mp.measureit_num] ms.gltype = 20 f = -1 for face in mylist: # Create array elements ms.measureit_faces.add() f += 1 # Set values mf = ms.measureit_faces[f] mf.glface = f i = 0 for v in face: mf.measureit_index.add() mi = mf.measureit_index[i] mi.glidx = v i += 1 # color rgb = scene.measureit_default_color ms.glcolor = (rgb[0], rgb[1], rgb[2], 0.4) # dist ms.glspace = scene.measureit_hint_space # text ms.gltxt = scene.measureit_gl_txt ms.glfont_size = scene.measureit_font_size ms.glfont_align = scene.measureit_font_align ms.glfont_rotat = scene.measureit_font_rotation # Sum group ms.gltot = scene.measureit_sum # Add index mp.measureit_num += 1 # redraw context.area.tag_redraw() return {'FINISHED'} else: self.report({'ERROR'}, "MeasureIt: Select at least one face for creating area measure. ") return {'FINISHED'} else: self.report({'WARNING'}, "View3D not found, cannot run operator") return {'CANCELLED'} # ------------------------------------------------------------- # Defines button that adds a measure segment to x/y/z origin # # ------------------------------------------------------------- class MEASUREIT_OT_AddSegmentOrto(Operator): bl_idname = "measureit.addsegmentorto" bl_label = "Add" bl_description = "(EDITMODE only) Add a new measure segment from vertex to object origin for one " \ "axis (select 1 vertex)" tag: IntProperty() # ------------------------------ # Poll # ------------------------------ @classmethod def poll(cls, context): o = context.object if o is None: return False else: if o.type == "MESH": if bpy.context.mode == 'EDIT_MESH': return True else: return False else: return False # ------------------------------ # Execute button action # ------------------------------ def execute(self, context): if context.area.type == 'VIEW_3D': # Add properties scene = context.scene mainobject = context.object mylist = get_smart_selected(mainobject) if len(mylist) < 1: # if not selected linked vertex mylist = get_selected_vertex(mainobject) if len(mylist) >= 1: if 'MeasureGenerator' not in mainobject: mainobject.MeasureGenerator.add() mp = mainobject.MeasureGenerator[0] for x in range(len(mylist)): # ----------------------- # Only if not exist # ----------------------- if exist_segment(mp, mylist[x], mylist[x], 12 + int(self.tag)) is False: # Create all array elements for cont in range(len(mp.measureit_segments) - 1, mp.measureit_num): mp.measureit_segments.add() # Set values ms = mp.measureit_segments[mp.measureit_num] ms.gltype = 12 + int(self.tag) ms.glpointa = mylist[x] ms.glpointb = mylist[x] ms.glarrow_a = scene.measureit_glarrow_a ms.glarrow_b = scene.measureit_glarrow_b ms.glarrow_s = scene.measureit_glarrow_s # color ms.glcolor = scene.measureit_default_color # dist ms.glspace = scene.measureit_hint_space # text ms.gltxt = scene.measureit_gl_txt ms.glfont_size = scene.measureit_font_size ms.glfont_align = scene.measureit_font_align ms.glfont_rotat = scene.measureit_font_rotation # Sum group ms.gltot = scene.measureit_sum # Add index mp.measureit_num += 1 # redraw context.area.tag_redraw() return {'FINISHED'} else: self.report({'ERROR'}, "MeasureIt: Select at least one vertex for creating measure segment.") return {'FINISHED'} else: self.report({'WARNING'}, "View3D not found, cannot run operator") return {'CANCELLED'} # ------------------------------------------------------------- # Defines button that adds an angle measure # # ------------------------------------------------------------- class MEASUREIT_OT_AddAngle(Operator): bl_idname = "measureit.addangle" bl_label = "Angle" bl_description = "(EDITMODE only) Add a new angle measure (select 3 vertices, 2nd is angle vertex)" # ------------------------------ # Poll # ------------------------------ @classmethod def poll(cls, context): o = context.object if o is None: return False else: if o.type == "MESH": if bpy.context.mode == 'EDIT_MESH': return True else: return False else: return False # ------------------------------ # Execute button action # ------------------------------ def execute(self, context): if context.area.type == 'VIEW_3D': # Add properties scene = context.scene mainobject = context.object mylist = get_selected_vertex_history(mainobject) if len(mylist) == 3: if 'MeasureGenerator' not in mainobject: mainobject.MeasureGenerator.add() mp = mainobject.MeasureGenerator[0] # ----------------------- # Only if not exist # ----------------------- if exist_segment(mp, mylist[0], mylist[1], 9, mylist[2]) is False: # Create all array elements for cont in range(len(mp.measureit_segments) - 1, mp.measureit_num): mp.measureit_segments.add() # Set values ms = mp.measureit_segments[mp.measureit_num] ms.gltype = 9 ms.glpointa = mylist[0] ms.glpointb = mylist[1] ms.glpointc = mylist[2] # color ms.glcolor = scene.measureit_default_color # dist ms.glspace = scene.measureit_hint_space # text ms.gltxt = scene.measureit_gl_txt ms.glfont_size = scene.measureit_font_size ms.glfont_align = scene.measureit_font_align ms.glfont_rotat = scene.measureit_font_rotation # Add index mp.measureit_num += 1 # redraw context.area.tag_redraw() return {'FINISHED'} else: self.report({'ERROR'}, "MeasureIt: Select three vertices for creating angle measure") return {'FINISHED'} else: self.report({'WARNING'}, "View3D not found, cannot run operator") return {'CANCELLED'} # ------------------------------------------------------------- # Defines button that adds an arc measure # # ------------------------------------------------------------- class MEASUREIT_OT_AddArc(Operator): bl_idname = "measureit.addarc" bl_label = "Angle" bl_description = "(EDITMODE only) Add a new arc measure (select 3 vertices of the arc," \ " vertices 1st and 3rd are arc extremes)" # ------------------------------ # Poll # ------------------------------ @classmethod def poll(cls, context): o = context.object if o is None: return False else: if o.type == "MESH": if bpy.context.mode == 'EDIT_MESH': return True else: return False else: return False # ------------------------------ # Execute button action # ------------------------------ def execute(self, context): if context.area.type == 'VIEW_3D': # Add properties scene = context.scene mainobject = context.object mylist = get_selected_vertex_history(mainobject) if len(mylist) == 3: if 'MeasureGenerator' not in mainobject: mainobject.MeasureGenerator.add() mp = mainobject.MeasureGenerator[0] # ----------------------- # Only if not exist # ----------------------- if exist_segment(mp, mylist[0], mylist[1], 11, mylist[2]) is False: # Create all array elements for cont in range(len(mp.measureit_segments) - 1, mp.measureit_num): mp.measureit_segments.add() # Set values ms = mp.measureit_segments[mp.measureit_num] ms.gltype = 11 ms.glpointa = mylist[0] ms.glpointb = mylist[1] ms.glpointc = mylist[2] ms.glarrow_a = scene.measureit_glarrow_a ms.glarrow_b = scene.measureit_glarrow_b ms.glarrow_s = scene.measureit_glarrow_s # color ms.glcolor = scene.measureit_default_color # dist ms.glspace = scene.measureit_hint_space # text ms.gltxt = scene.measureit_gl_txt ms.glfont_size = scene.measureit_font_size ms.glfont_align = scene.measureit_font_align ms.glfont_rotat = scene.measureit_font_rotation # Add index mp.measureit_num += 1 # redraw context.area.tag_redraw() return {'FINISHED'} else: self.report({'ERROR'}, "MeasureIt: Select three vertices for creating arc measure") return {'FINISHED'} else: self.report({'WARNING'}, "View3D not found, cannot run operator") return {'CANCELLED'} # ------------------------------------------------------------- # Defines button that adds a label segment # # ------------------------------------------------------------- class MEASUREIT_OT_AddLabel(Operator): bl_idname = "measureit.addlabel" bl_label = "Add" bl_description = "(EDITMODE only) Add a new measure label (select 1 vertex)" # ------------------------------ # Poll # ------------------------------ @classmethod def poll(cls, context): o = context.object if o is None: return False else: if o.type == "MESH": if bpy.context.mode == 'EDIT_MESH': return True else: return False else: return False # ------------------------------ # Execute button action # ------------------------------ def execute(self, context): if context.area.type == 'VIEW_3D': # Add properties scene = context.scene mainobject = context.object mylist = get_selected_vertex(mainobject) if len(mylist) == 1: if 'MeasureGenerator' not in mainobject: mainobject.MeasureGenerator.add() mp = mainobject.MeasureGenerator[0] # ----------------------- # Only if not exist # ----------------------- if exist_segment(mp, mylist[0], mylist[0], 2) is False: # Both equal # Create all array elements for cont in range(len(mp.measureit_segments) - 1, mp.measureit_num): mp.measureit_segments.add() # Set values ms = mp.measureit_segments[mp.measureit_num] ms.gltype = 2 ms.glpointa = mylist[0] ms.glpointb = mylist[0] # Equal ms.glarrow_a = scene.measureit_glarrow_a ms.glarrow_b = scene.measureit_glarrow_b ms.glarrow_s = scene.measureit_glarrow_s # color ms.glcolor = scene.measureit_default_color # dist ms.glspace = scene.measureit_hint_space # text ms.gltxt = scene.measureit_gl_txt ms.glfont_size = scene.measureit_font_size ms.glfont_align = scene.measureit_font_align ms.glfont_rotat = scene.measureit_font_rotation # Add index mp.measureit_num += 1 # redraw context.area.tag_redraw() return {'FINISHED'} else: self.report({'ERROR'}, "MeasureIt: Select one vertex for creating measure label") return {'FINISHED'} else: self.report({'WARNING'}, "View3D not found, cannot run operator") return {'CANCELLED'} # ------------------------------------------------------------- # Defines button that adds a link # # ------------------------------------------------------------- class MEASUREIT_OT_AddLink(Operator): bl_idname = "measureit.addlink" bl_label = "Add" bl_description = "(OBJECT mode only) Add a new measure between objects (select 2 " \ "objects and optionally 1 or 2 vertices)" # ------------------------------ # Poll # ------------------------------ @classmethod def poll(cls, context): o = context.object if o is None: return False else: if o.type == "MESH" or o.type == "EMPTY" or o.type == "CAMERA" or o.type == "LIGHT": if bpy.context.mode == 'OBJECT': return True else: return False else: return False # ------------------------------ # Execute button action # ------------------------------ def execute(self, context): if context.area.type == 'VIEW_3D': scene = context.scene mainobject = context.object # ------------------------------- # Verify number of objects # ------------------------------- if len(context.selected_objects) != 2: self.report({'ERROR'}, "MeasureIt: Select two objects only, and optionally 1 vertex or 2 vertices " "(one of each object)") return {'FINISHED'} # Locate other object linkobject = None for o in context.selected_objects: if o.name != mainobject.name: linkobject = o.name # Verify destination vertex lkobj = bpy.data.objects[linkobject] mylinkvertex = get_selected_vertex(lkobj) if len(mylinkvertex) > 1: self.report({'ERROR'}, "MeasureIt: The destination object has more than one vertex selected. " "Select only 1 or none") return {'FINISHED'} # Verify origin vertex myobjvertex = get_selected_vertex(mainobject) if len(mylinkvertex) > 1: self.report({'ERROR'}, "MeasureIt: The active object has more than one vertex selected. Select only 1 or none") return {'FINISHED'} # ------------------------------- # Add properties # ------------------------------- flag = False if 'MeasureGenerator' not in mainobject: mainobject.MeasureGenerator.add() mp = mainobject.MeasureGenerator[0] # if exist_segment(mp, mylist[0], mylist[0], 3) is False: # flag = True # Create all array elements for cont in range(len(mp.measureit_segments) - 1, mp.measureit_num): mp.measureit_segments.add() # Set values ms = mp.measureit_segments[mp.measureit_num] # ----------------------- # Vertex to Vertex # ----------------------- if len(myobjvertex) == 1 and len(mylinkvertex) == 1: ms.gltype = 3 ms.glpointa = myobjvertex[0] ms.glpointb = mylinkvertex[0] flag = True # ----------------------- # Vertex to Object # ----------------------- if len(myobjvertex) == 1 and len(mylinkvertex) == 0: ms.gltype = 4 ms.glpointa = myobjvertex[0] ms.glpointb = 0 flag = True # ----------------------- # Object to Vertex # ----------------------- if len(myobjvertex) == 0 and len(mylinkvertex) == 1: ms.gltype = 5 ms.glpointa = 0 ms.glpointb = mylinkvertex[0] flag = True # ----------------------- # Object to Object # ----------------------- if len(myobjvertex) == 0 and len(mylinkvertex) == 0: ms.gltype = 8 ms.glpointa = 0 ms.glpointb = 0 # Equal flag = True # ------------------ # only if created # ------------------ if flag is True: ms.glarrow_a = scene.measureit_glarrow_a ms.glarrow_b = scene.measureit_glarrow_b ms.glarrow_s = scene.measureit_glarrow_s # color ms.glcolor = scene.measureit_default_color # dist ms.glspace = scene.measureit_hint_space # text ms.gltxt = scene.measureit_gl_txt ms.glfont_size = scene.measureit_font_size ms.glfont_align = scene.measureit_font_align ms.glfont_rotat = scene.measureit_font_rotation # link ms.gllink = linkobject # Add index mp.measureit_num += 1 # ----------------------- # Only if not exist # ----------------------- # redraw context.area.tag_redraw() return {'FINISHED'} else: self.report({'WARNING'}, "View3D not found, cannot run operator") return {'CANCELLED'} # ------------------------------------------------------------- # Defines button that adds an origin segment # # ------------------------------------------------------------- class MEASUREIT_OT_AddOrigin(Operator): bl_idname = "measureit.addorigin" bl_label = "Add" bl_description = "(OBJECT mode only) Add a new measure to origin (select object and optionally 1 vertex)" # ------------------------------ # Poll # ------------------------------ @classmethod def poll(cls, context): o = context.object if o is None: return False else: if o.type == "MESH" or o.type == "EMPTY" or o.type == "CAMERA" or o.type == "LIGHT": if bpy.context.mode == 'OBJECT': return True else: return False else: return False # ------------------------------ # Execute button action # ------------------------------ def execute(self, context): if context.area.type == 'VIEW_3D': # Add properties scene = context.scene mainobject = context.object mylist = get_selected_vertex(mainobject) if 'MeasureGenerator' not in mainobject: mainobject.MeasureGenerator.add() mp = mainobject.MeasureGenerator[0] # Create all array elements for cont in range(len(mp.measureit_segments) - 1, mp.measureit_num): mp.measureit_segments.add() # ----------------------- # Set values # ----------------------- ms = mp.measureit_segments[mp.measureit_num] flag = False if len(mylist) > 0: if len(mylist) == 1: if exist_segment(mp, mylist[0], mylist[0], 6) is False: # Both equal flag = True # Vertex to origin ms.gltype = 6 ms.glpointa = mylist[0] ms.glpointb = mylist[0] else: self.report({'ERROR'}, "MeasureIt: Enter in EDITMODE and select one vertex only for creating " "measure from vertex to origin") return {'FINISHED'} else: # Object to origin if exist_segment(mp, 0, 0, 7) is False: # Both equal flag = True ms.gltype = 7 ms.glpointa = 0 ms.glpointb = 0 # ------------------ # only if created # ------------------ if flag is True: ms.glarrow_a = scene.measureit_glarrow_a ms.glarrow_b = scene.measureit_glarrow_b ms.glarrow_s = scene.measureit_glarrow_s # color ms.glcolor = scene.measureit_default_color # dist ms.glspace = scene.measureit_hint_space # text ms.gltxt = scene.measureit_gl_txt ms.glfont_size = scene.measureit_font_size ms.glfont_align = scene.measureit_font_align ms.glfont_rotat = scene.measureit_font_rotation # Add index mp.measureit_num += 1 # redraw context.area.tag_redraw() return {'FINISHED'} else: self.report({'WARNING'}, "View3D not found, cannot run operator") return {'CANCELLED'} # ------------------------------------------------------------- # Defines button that deletes a measure segment # # ------------------------------------------------------------- class MEASUREIT_OT_DeleteSegment(Operator): bl_idname = "measureit.deletesegment" bl_label = "Delete" bl_description = "Delete a measure" tag: IntProperty() # ------------------------------ # Execute button action # ------------------------------ def execute(self, context): if context.area.type == 'VIEW_3D': # Add properties mainobject = context.object mp = mainobject.MeasureGenerator[0] ms = mp.measureit_segments[self.tag] ms.glfree = True # Delete element mp.measureit_segments.remove(self.tag) mp.measureit_num -= 1 # redraw context.area.tag_redraw() return {'FINISHED'} else: self.report({'WARNING'}, "View3D not found, cannot run operator") return {'CANCELLED'} # ------------------------------------------------------------- # Defines button that deletes all measure segments # # ------------------------------------------------------------- class MEASUREIT_OT_DeleteAllSegment(Operator): bl_idname = "measureit.deleteallsegment" bl_label = "Delete" bl_description = "Delete all measures (it cannot be undone)" tag: IntProperty() # ------------------------------ # Execute button action # ------------------------------ def execute(self, context): if context.area.type == 'VIEW_3D': # Add properties mainobject = context.object mp = mainobject.MeasureGenerator[0] while len(mp.measureit_segments) > 0: mp.measureit_segments.remove(0) # reset size mp.measureit_num = len(mp.measureit_segments) # redraw context.area.tag_redraw() return {'FINISHED'} else: self.report({'WARNING'}, "View3D not found, cannot run operator") return {'CANCELLED'} # ------------------------------------------------------------- # Defines button that deletes all measure segment sums # # ------------------------------------------------------------- class MEASUREIT_OT_DeleteAllSum(Operator): bl_idname = "measureit.deleteallsum" bl_label = "Delete" bl_description = "Delete all sum groups" tag: IntProperty() # ------------------------------ # Execute button action # ------------------------------ # noinspection PyMethodMayBeStatic def execute(self, context): if context.object is not None: if 'MeasureGenerator' in context.object: mp = context.object.MeasureGenerator[0] for idx in range(mp.measureit_num): ms = mp.measureit_segments[idx] ms.gltot = '99' return {'FINISHED'} # ------------------------------------------------------------- # Defines button that expands all measure segments # # ------------------------------------------------------------- class MEASUREIT_OT_ExpandAllSegment(Operator): bl_idname = "measureit.expandallsegment" bl_label = "Expand" bl_description = "Expand all measure properties" tag: IntProperty() # ------------------------------ # Execute button action # ------------------------------ def execute(self, context): if context.area.type == 'VIEW_3D': # Add properties mainobject = context.object mp = mainobject.MeasureGenerator[0] for i in mp.measureit_segments: i.gladvance = True return {'FINISHED'} else: self.report({'WARNING'}, "View3D not found, cannot run operator") return {'CANCELLED'} # ------------------------------------------------------------- # Defines button that collapses all measure segments # # ------------------------------------------------------------- class MEASUREIT_OT_CollapseAllSegment(Operator): bl_idname = "measureit.collapseallsegment" bl_label = "Collapse" bl_description = "Collapses all measure properties" tag: IntProperty() # ------------------------------ # Execute button action # ------------------------------ def execute(self, context): if context.area.type == 'VIEW_3D': # Add properties mainobject = context.object mp = mainobject.MeasureGenerator[0] for i in mp.measureit_segments: i.gladvance = False return {'FINISHED'} else: self.report({'WARNING'}, "View3D not found, cannot run operator") return {'CANCELLED'} # ------------------------------------------------------------- # Defines button for render option # # ------------------------------------------------------------- class MEASUREIT_OT_RenderSegment(Operator): bl_idname = "measureit.rendersegment" bl_label = "Render" bl_description = "Create a render image with measures. Use UV/Image editor to view image generated" tag: IntProperty() # ------------------------------ # Execute button action # ------------------------------ # noinspection PyMethodMayBeStatic,PyUnusedLocal def execute(self, context): scene = context.scene msg = "New image created with measures. Open it in UV/image editor" camera_msg = "Unable to render. No camera found" # ----------------------------- # Check camera # ----------------------------- if scene.camera is None: self.report({'ERROR'}, camera_msg) return {'FINISHED'} # ----------------------------- # Frame render # ----------------------------- if scene.measureit_render_type == "1": # noinspection PyBroadException if render_main(self, context) is True: self.report({'INFO'}, msg) # ----------------------------- # Animation # ----------------------------- if scene.measureit_render_type == "2": oldframe = scene.frame_current flag = False # loop frames for frm in range(scene.frame_start, scene.frame_end + 1): scene.frame_set(frm) print("MeasureIt: Rendering frame %04d" % frm) flag = render_main(self, context, True) if flag is False: break scene.frame_current = oldframe if flag is True: self.report({'INFO'}, msg) return {'FINISHED'} # --------------------- # Set cameraView # --------------------- # noinspection PyMethodMayBeStatic def set_camera_view(self): for area in bpy.context.screen.areas: if area.type == 'VIEW_3D': area.spaces[0].region_3d.view_perspective = 'CAMERA' # ------------------------------------- # Set only render status # ------------------------------------- # noinspection PyMethodMayBeStatic def set_only_render(self, status): screen = bpy.context.screen v3d = False s = None # get spaceview_3d in current screen for a in screen.areas: if a.type == 'VIEW_3D': for s in a.spaces: if s.type == 'VIEW_3D': v3d = s break if v3d is not False: s.show_only_render = status # ------------------------------------------------------------- # Defines a new note # # ------------------------------------------------------------- class MEASUREIT_OT_AddNote(Operator): bl_idname = "measureit.addnote" bl_label = "Note" bl_description = "(OBJECT mode only) Add a new annotation" tag: IntProperty() # ------------------------------ # Poll # ------------------------------ # noinspection PyUnusedLocal @classmethod def poll(cls, context): if bpy.context.mode == 'OBJECT': return True else: return False # ------------------------------ # Execute button action # ------------------------------ def execute(self, context): if context.area.type == 'VIEW_3D': bpy.ops.object.empty_add(type='PLAIN_AXES') myempty = bpy.data.objects[bpy.context.active_object.name] myempty.location = bpy.context.scene.cursor.location myempty.empty_display_size = 0.01 myempty.name = "Annotation" # Add properties scene = context.scene mainobject = myempty if 'MeasureGenerator' not in mainobject: mainobject.MeasureGenerator.add() mp = mainobject.MeasureGenerator[0] # Create all array elements for cont in range(len(mp.measureit_segments) - 1, mp.measureit_num): mp.measureit_segments.add() # Set values ms = mp.measureit_segments[mp.measureit_num] ms.gltype = 10 ms.glpointa = 0 ms.glpointb = 0 # Equal # color ms.glcolor = scene.measureit_default_color # dist ms.glspace = scene.measureit_hint_space # text ms.gltxt = scene.measureit_gl_txt ms.glfont_size = scene.measureit_font_size ms.glfont_align = scene.measureit_font_align ms.glfont_rotat = scene.measureit_font_rotation # Add index mp.measureit_num += 1 # redraw context.area.tag_redraw() return {'FINISHED'} else: self.report({'WARNING'}, "View3D not found, cannot run operator") return {'CANCELLED'} # ------------------------------------------------------------- # Defines button that enables/disables the tip display # # ------------------------------------------------------------- class MEASUREIT_OT_RunHintDisplay(Operator): bl_idname = "measureit.runopengl" bl_label = "Display hint data manager" bl_description = "Main control for enabling or disabling the display of measurements in the viewport" _handle = None # keep function handler # ---------------------------------- # Enable gl drawing adding handler # ---------------------------------- @staticmethod def handle_add(self, context): if MEASUREIT_OT_RunHintDisplay._handle is None: MEASUREIT_OT_RunHintDisplay._handle = SpaceView3D.draw_handler_add(draw_callback_px, (self, context), 'WINDOW', 'POST_PIXEL') context.window_manager.measureit_run_opengl = True # ------------------------------------ # Disable gl drawing removing handler # ------------------------------------ # noinspection PyUnusedLocal @staticmethod def handle_remove(self, context): if MEASUREIT_OT_RunHintDisplay._handle is not None: SpaceView3D.draw_handler_remove(MEASUREIT_OT_RunHintDisplay._handle, 'WINDOW') MEASUREIT_OT_RunHintDisplay._handle = None context.window_manager.measureit_run_opengl = False # ------------------------------ # Execute button action # ------------------------------ def execute(self, context): if context.area.type == 'VIEW_3D': if context.window_manager.measureit_run_opengl is False: self.handle_add(self, context) context.area.tag_redraw() else: self.handle_remove(self, context) context.area.tag_redraw() return {'FINISHED'} else: self.report({'WARNING'}, "View3D not found, cannot run operator") return {'CANCELLED'} # ------------------------------------------------------------- # Handle all draw routines (OpenGL main entry point) # # ------------------------------------------------------------- def draw_main(context): region = bpy.context.region # Detect if Quadview to get drawing area if not context.space_data.region_quadviews: rv3d = bpy.context.space_data.region_3d else: # verify area if context.area.type != 'VIEW_3D' or context.space_data.type != 'VIEW_3D': return i = -1 for region in context.area.regions: if region.type == 'WINDOW': i += 1 if context.region.id == region.id: break else: return rv3d = context.space_data.region_quadviews[i] scene = bpy.context.scene # Display selected or all if scene.measureit_gl_ghost is False: objlist = context.selected_objects else: objlist = context.view_layer.objects # Enable GL drawing bgl.glEnable(bgl.GL_BLEND) # --------------------------------------- # Generate all OpenGL calls for measures # --------------------------------------- for myobj in objlist: if myobj.visible_get() is True: if 'MeasureGenerator' in myobj: op = myobj.MeasureGenerator[0] draw_segments(context, myobj, op, region, rv3d) # --------------------------------------- # Generate all OpenGL calls for debug # --------------------------------------- if scene.measureit_debug is True: selobj = bpy.context.selected_objects for myobj in selobj: if scene.measureit_debug_objects is True: draw_object(context, myobj, region, rv3d) elif scene.measureit_debug_object_loc is True: draw_object(context, myobj, region, rv3d) if scene.measureit_debug_vertices is True: draw_vertices(context, myobj, region, rv3d) elif scene.measureit_debug_vert_loc is True: draw_vertices(context, myobj, region, rv3d) if scene.measureit_debug_edges is True: draw_edges(context, myobj, region, rv3d) if scene.measureit_debug_faces is True or scene.measureit_debug_normals is True: draw_faces(context, myobj, region, rv3d) # ----------------------- # restore opengl defaults # ----------------------- bgl.glLineWidth(1) bgl.glDisable(bgl.GL_BLEND) # ------------------------------------------------------------- # Handler for drawing OpenGl # ------------------------------------------------------------- # noinspection PyUnusedLocal def draw_callback_px(self, context): draw_main(context) # ------------------------------------------------------------- # Check if the segment already exist # # ------------------------------------------------------------- def exist_segment(mp, pointa, pointb, typ=1, pointc=None): # for ms in mp.measureit_segments[mp.measureit_num] for ms in mp.measureit_segments: if ms.gltype == typ and ms.glfree is False: if typ != 9: if ms.glpointa == pointa and ms.glpointb == pointb: return True if ms.glpointa == pointb and ms.glpointb == pointa: return True else: if ms.glpointa == pointa and ms.glpointb == pointb and ms.glpointc == pointc: return True return False # ------------------------------------------------------------- # Get vertex selected # ------------------------------------------------------------- def get_selected_vertex(myobject): mylist = [] # if not mesh, no vertex if myobject.type != "MESH": return mylist # -------------------- # meshes # -------------------- oldobj = bpy.context.object bpy.context.view_layer.objects.active = myobject flag = False if myobject.mode != 'EDIT': bpy.ops.object.mode_set(mode='EDIT') flag = True bm = from_edit_mesh(myobject.data) tv = len(bm.verts) for v in bm.verts: if v.select: mylist.append(v.index) if flag is True: bpy.ops.object.editmode_toggle() # Back context object bpy.context.view_layer.objects.active = oldobj # if select all vertices, then use origin if tv == len(mylist): return [] return mylist # ------------------------------------------------------------- # Get vertex selected # ------------------------------------------------------------- def get_selected_vertex_history(myobject): mylist = [] # if not mesh, no vertex if myobject.type != "MESH": return mylist # -------------------- # meshes # -------------------- oldobj = bpy.context.object bpy.context.view_layer.objects.active = myobject flag = False if myobject.mode != 'EDIT': bpy.ops.object.mode_set(mode='EDIT') flag = True bm = from_edit_mesh(myobject.data) for v in bm.select_history: mylist.append(v.index) if flag is True: bpy.ops.object.editmode_toggle() # Back context object bpy.context.view_layer.objects.active = oldobj return mylist # ------------------------------------------------------------- # Get vertex selected segments # ------------------------------------------------------------- def get_smart_selected(myobject): mylist = [] # if not mesh, no vertex if myobject.type != "MESH": return mylist # -------------------- # meshes # -------------------- oldobj = bpy.context.object bpy.context.view_layer.objects.active = myobject flag = False if myobject.mode != 'EDIT': bpy.ops.object.mode_set(mode='EDIT') flag = True bm = from_edit_mesh(myobject.data) for e in bm.edges: if e.select is True: mylist.append(e.verts[0].index) mylist.append(e.verts[1].index) if flag is True: bpy.ops.object.editmode_toggle() # Back context object bpy.context.view_layer.objects.active = oldobj return mylist # ------------------------------------------------------------- # Get vertex selected faces # ------------------------------------------------------------- def get_selected_faces(myobject): mylist = [] # if not mesh, no vertex if myobject.type != "MESH": return mylist # -------------------- # meshes # -------------------- oldobj = bpy.context.object bpy.context.view_layer.objects.active = myobject flag = False if myobject.mode != 'EDIT': bpy.ops.object.mode_set(mode='EDIT') flag = True bm = from_edit_mesh(myobject.data) for e in bm.faces: myfaces = [] if e.select is True: for i in range(len(e.verts)): myfaces.append(e.verts[i].index) mylist.extend([myfaces]) if flag is True: bpy.ops.object.editmode_toggle() # Back context object bpy.context.view_layer.objects.active = oldobj return mylist
39.595814
120
0.463638