text
stringlengths
3
1.05M
# -*- coding: utf-8 -*- # Copyright (c) 2017, masonarmani38@gmail.com and Contributors # See license.txt from __future__ import unicode_literals import frappe import unittest class TestSalesWeeklyReportOutlets(unittest.TestCase): pass
/* Named export */ export const steps = [ 'Basic knowledge', 'Installation', 'Create default build', 'Using npx', 'Using ES6 Modules', 'Using lodash', 'Add configuration', 'Using npm scripts', 'Using Dev Server', 'Loading CSS', 'Extract CSS', 'Using Handlebars', 'Loading Handlebars Templates', 'Copy index.html file', 'Expose to global scope', ];
const cons = require('../../common/constants'); const Game = require('../game'); let game = module.exports = new Game(cons.Game.BCBM()); // game.registerClass('room.db', require('./room/db')); game.registerClass('room.robot', require('./room/robot')); game.registerClass('room.robotManager', require('./room/robotManager')); game.registerClass('room.seat', require('./room/seat')); game.registerClass('room.seatManager', require('./room/seatManager')); game.registerClass('room.stateManager', require('./room/stateManager')); game.registerClass('room.loggerManager', require('./room/loggerManager')); game.registerClass('room.jackpotManager', require('./room/jackpotManager')); game.registerData('zone.match', require('./data/match')); game.registerInterface('zone.match.parseRoomParams', require('./zone/match/parseRoomParams')); // game.registerInterface('zone.private.parseRoomParams', require('./zone/private/parseRoomParams'));
import {createStore, combineReducers, applyMiddleware, compose} from 'redux' import createHistory from 'history/createBrowserHistory' import {routerReducer, routerMiddleware} from 'react-router-redux' import thunk from 'redux-thunk' import createSagaMiddleware from 'redux-saga' import reducers from '../redux/reducers' import rootSaga from '../redux/sagas' const history = createHistory({ }) const sagaMiddleware = createSagaMiddleware() const routeMiddleware = routerMiddleware(history) const middlewares = [thunk, sagaMiddleware, routeMiddleware] const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose const store = createStore( combineReducers({ ...reducers, router: routerReducer }), composeEnhancers( applyMiddleware(...middlewares) ) ) sagaMiddleware.run(rootSaga) export {store, history}
#ifndef __UHOOK_OS_H__ #define __UHOOK_OS_H__ #ifdef __cplusplus extern "C" { #endif #include "defs.h" #include <stddef.h> /** * @brief Alloc a block of memory that has EXEC attribute * @param[in] size Memory size * @return Address */ API_LOCAL void* _alloc_execute_memory(size_t size); /** * @brief Release memory alloc by #_alloc_execute_memory() */ API_LOCAL void _free_execute_memory(void* ptr); API_LOCAL size_t _get_page_size(void); API_LOCAL int _system_modify_opcode(void* addr, size_t size, void (*callback)(void*), void* data); /** * @brief Flush the processor's instruction cache for the region of memory. * * Some targets require that the instruction cache be flushed, after modifying * memory containing code, in order to obtain deterministic behavior. * * @param[in] addr Start address * @param[in] size Address length */ API_LOCAL void _flush_instruction_cache(void* addr, size_t size); /** * @brief Get start address of page from given address. * @parm[in] addr Address to calculate * @param[in] page_size Page size * @return The start address of page */ API_LOCAL void* _page_of(void* addr, size_t page_size); #ifdef __cplusplus } #endif #endif
# -*- coding: utf-8 -*- ''' Minion side functions for salt-cp ''' # Import python libs from __future__ import absolute_import import os import logging import fnmatch # Import salt libs import salt.minion import salt.fileclient import salt.utils import salt.utils.url import salt.crypt import salt.transport from salt.exceptions import CommandExecutionError # Import 3rd-party libs import salt.ext.six as six log = logging.getLogger(__name__) def _auth(): ''' Return the auth object ''' if 'auth' not in __context__: __context__['auth'] = salt.crypt.SAuth(__opts__) return __context__['auth'] def _gather_pillar(pillarenv, pillar_override): ''' Whenever a state run starts, gather the pillar data fresh ''' pillar = salt.pillar.get_pillar( __opts__, __grains__, __opts__['id'], __opts__['environment'], pillar=pillar_override, pillarenv=pillarenv ) ret = pillar.compile_pillar() if pillar_override and isinstance(pillar_override, dict): ret.update(pillar_override) return ret def recv(files, dest): ''' Used with salt-cp, pass the files dict, and the destination. This function receives small fast copy files from the master via salt-cp. It does not work via the CLI. ''' ret = {} for path, data in six.iteritems(files): if os.path.basename(path) == os.path.basename(dest) \ and not os.path.isdir(dest): final = dest elif os.path.isdir(dest): final = os.path.join(dest, os.path.basename(path)) elif os.path.isdir(os.path.dirname(dest)): final = dest else: return 'Destination unavailable' try: salt.utils.fopen(final, 'w+').write(data) ret[final] = True except IOError: ret[final] = False return ret def _mk_client(): ''' Create a file client and add it to the context. ''' if 'cp.fileclient' not in __context__: __context__['cp.fileclient'] = \ salt.fileclient.get_file_client(__opts__) def _render_filenames(path, dest, saltenv, template, **kw): ''' Process markup in the :param:`path` and :param:`dest` variables (NOT the files under the paths they ultimately point to) according to the markup format provided by :param:`template`. ''' if not template: return (path, dest) # render the path as a template using path_template_engine as the engine if template not in salt.utils.templates.TEMPLATE_REGISTRY: raise CommandExecutionError( 'Attempted to render file paths with unavailable engine ' '{0}'.format(template) ) kwargs = {} kwargs['salt'] = __salt__ if 'pillarenv' in kw or 'pillar' in kw: pillarenv = kw.get('pillarenv', __opts__.get('pillarenv')) kwargs['pillar'] = _gather_pillar(pillarenv, kw.get('pillar')) else: kwargs['pillar'] = __pillar__ kwargs['grains'] = __grains__ kwargs['opts'] = __opts__ kwargs['saltenv'] = saltenv def _render(contents): ''' Render :param:`contents` into a literal pathname by writing it to a temp file, rendering that file, and returning the result. ''' # write out path to temp file tmp_path_fn = salt.utils.mkstemp() with salt.utils.fopen(tmp_path_fn, 'w+') as fp_: fp_.write(contents) data = salt.utils.templates.TEMPLATE_REGISTRY[template]( tmp_path_fn, to_str=True, **kwargs ) salt.utils.safe_rm(tmp_path_fn) if not data['result']: # Failed to render the template raise CommandExecutionError( 'Failed to render file path with error: {0}'.format( data['data'] ) ) else: return data['data'] path = _render(path) dest = _render(dest) return (path, dest) def get_file(path, dest, saltenv='base', makedirs=False, template=None, gzip=None, env=None, **kwargs): ''' Used to get a single file from the salt master CLI Example: .. code-block:: bash salt '*' cp.get_file salt://path/to/file /minion/dest Template rendering can be enabled on both the source and destination file names like so: .. code-block:: bash salt '*' cp.get_file "salt://{{grains.os}}/vimrc" /etc/vimrc template=jinja This example would instruct all Salt minions to download the vimrc from a directory with the same name as their os grain and copy it to /etc/vimrc For larger files, the cp.get_file module also supports gzip compression. Because gzip is CPU-intensive, this should only be used in scenarios where the compression ratio is very high (e.g. pretty-printed JSON or YAML files). Use the *gzip* named argument to enable it. Valid values are 1..9, where 1 is the lightest compression and 9 the heaviest. 1 uses the least CPU on the master (and minion), 9 uses the most. ''' if env is not None: salt.utils.warn_until( 'Boron', 'Passing a salt environment should be done using \'saltenv\' ' 'not \'env\'. This functionality will be removed in Salt Boron.' ) # Backwards compatibility saltenv = env (path, dest) = _render_filenames(path, dest, saltenv, template, **kwargs) path, senv = salt.utils.url.split_env(path) if senv: saltenv = senv if not hash_file(path, saltenv): return '' else: _mk_client() return __context__['cp.fileclient'].get_file( path, dest, makedirs, saltenv, gzip) def get_template(path, dest, template='jinja', saltenv='base', env=None, makedirs=False, **kwargs): ''' Render a file as a template before setting it down. Warning, order is not the same as in fileclient.cp for non breaking old API. CLI Example: .. code-block:: bash salt '*' cp.get_template salt://path/to/template /minion/dest ''' if env is not None: salt.utils.warn_until( 'Boron', 'Passing a salt environment should be done using \'saltenv\' ' 'not \'env\'. This functionality will be removed in Salt Boron.' ) # Backwards compatibility saltenv = env _mk_client() if 'salt' not in kwargs: kwargs['salt'] = __salt__ if 'pillar' not in kwargs: kwargs['pillar'] = __pillar__ if 'grains' not in kwargs: kwargs['grains'] = __grains__ if 'opts' not in kwargs: kwargs['opts'] = __opts__ return __context__['cp.fileclient'].get_template( path, dest, template, makedirs, saltenv, **kwargs) def get_dir(path, dest, saltenv='base', template=None, gzip=None, env=None, **kwargs): ''' Used to recursively copy a directory from the salt master CLI Example: .. code-block:: bash salt '*' cp.get_dir salt://path/to/dir/ /minion/dest get_dir supports the same template and gzip arguments as get_file. ''' if env is not None: salt.utils.warn_until( 'Boron', 'Passing a salt environment should be done using \'saltenv\' ' 'not \'env\'. This functionality will be removed in Salt Boron.' ) # Backwards compatibility saltenv = env (path, dest) = _render_filenames(path, dest, saltenv, template, **kwargs) _mk_client() return __context__['cp.fileclient'].get_dir(path, dest, saltenv, gzip) def get_url(path, dest, saltenv='base', env=None): ''' Used to get a single file from a URL. The default behaviuor is to write the fetched file to the given destination path. To simply return the text contents instead, set destination to None. CLI Example: .. code-block:: bash salt '*' cp.get_url salt://my/file /tmp/mine salt '*' cp.get_url http://www.slashdot.org /tmp/index.html ''' if env is not None: salt.utils.warn_until( 'Boron', 'Passing a salt environment should be done using \'saltenv\' ' 'not \'env\'. This functionality will be removed in Salt Boron.' ) # Backwards compatibility saltenv = env _mk_client() if dest: return __context__['cp.fileclient'].get_url(path, dest, False, saltenv) else: return __context__['cp.fileclient'].get_url(path, None, False, saltenv, no_cache=True) def get_file_str(path, saltenv='base', env=None): ''' Return the contents of a file from a URL CLI Example: .. code-block:: bash salt '*' cp.get_file_str salt://my/file ''' if env is not None: salt.utils.warn_until( 'Boron', 'Passing a salt environment should be done using \'saltenv\' ' 'not \'env\'. This functionality will be removed in Salt Boron.' ) # Backwards compatibility saltenv = env fn_ = cache_file(path, saltenv) with salt.utils.fopen(fn_, 'r') as fp_: data = fp_.read() return data def cache_file(path, saltenv='base', env=None): ''' Used to cache a single file on the salt-minion Returns the location of the new cached file on the minion CLI Example: .. code-block:: bash salt '*' cp.cache_file salt://path/to/file ''' if env is not None: salt.utils.warn_until( 'Boron', 'Passing a salt environment should be done using \'saltenv\' ' 'not \'env\'. This functionality will be removed in Salt Boron.' ) # Backwards compatibility saltenv = env _mk_client() path, senv = salt.utils.url.split_env(path) if senv: saltenv = senv result = __context__['cp.fileclient'].cache_file(path, saltenv) if not result: log.error( 'Unable to cache file {0!r} from saltenv {1!r}.'.format( path, saltenv ) ) return result def cache_files(paths, saltenv='base', env=None): ''' Used to gather many files from the master, the gathered files will be saved in the minion cachedir reflective to the paths retrieved from the master. CLI Example: .. code-block:: bash salt '*' cp.cache_files salt://pathto/file1,salt://pathto/file1 ''' if env is not None: salt.utils.warn_until( 'Boron', 'Passing a salt environment should be done using \'saltenv\' ' 'not \'env\'. This functionality will be removed in Salt Boron.' ) # Backwards compatibility saltenv = env _mk_client() return __context__['cp.fileclient'].cache_files(paths, saltenv) def cache_dir(path, saltenv='base', include_empty=False, include_pat=None, exclude_pat=None, env=None): ''' Download and cache everything under a directory from the master include_pat : None Glob or regex to narrow down the files cached from the given path. If matching with a regex, the regex must be prefixed with ``E@``, otherwise the expression will be interpreted as a glob. .. versionadded:: 2014.7.0 exclude_pat : None Glob or regex to exclude certain files from being cached from the given path. If matching with a regex, the regex must be prefixed with ``E@``, otherwise the expression will be interpreted as a glob. .. note:: If used with ``include_pat``, files matching this pattern will be excluded from the subset of files defined by ``include_pat``. .. versionadded:: 2014.7.0 CLI Examples: .. code-block:: bash salt '*' cp.cache_dir salt://path/to/dir salt '*' cp.cache_dir salt://path/to/dir include_pat='E@*.py$' ''' if env is not None: salt.utils.warn_until( 'Boron', 'Passing a salt environment should be done using \'saltenv\' ' 'not \'env\'. This functionality will be removed in Salt Boron.' ) # Backwards compatibility saltenv = env _mk_client() return __context__['cp.fileclient'].cache_dir( path, saltenv, include_empty, include_pat, exclude_pat ) def cache_master(saltenv='base', env=None): ''' Retrieve all of the files on the master and cache them locally CLI Example: .. code-block:: bash salt '*' cp.cache_master ''' if env is not None: salt.utils.warn_until( 'Boron', 'Passing a salt environment should be done using \'saltenv\' ' 'not \'env\'. This functionality will be removed in Salt Boron.' ) # Backwards compatibility saltenv = env _mk_client() return __context__['cp.fileclient'].cache_master(saltenv) def cache_local_file(path): ''' Cache a local file on the minion in the localfiles cache CLI Example: .. code-block:: bash salt '*' cp.cache_local_file /etc/hosts ''' if not os.path.exists(path): return '' path_cached = is_cached(path) # If the file has already been cached, return the path if path_cached: path_hash = hash_file(path) path_cached_hash = hash_file(path_cached) if path_hash['hsum'] == path_cached_hash['hsum']: return path_cached # The file hasn't been cached or has changed; cache it _mk_client() return __context__['cp.fileclient'].cache_local_file(path) def list_states(saltenv='base', env=None): ''' List all of the available state modules in an environment CLI Example: .. code-block:: bash salt '*' cp.list_states ''' if env is not None: salt.utils.warn_until( 'Boron', 'Passing a salt environment should be done using \'saltenv\' ' 'not \'env\'. This functionality will be removed in Salt Boron.' ) # Backwards compatibility saltenv = env _mk_client() return __context__['cp.fileclient'].list_states(saltenv) def list_master(saltenv='base', prefix='', env=None): ''' List all of the files stored on the master CLI Example: .. code-block:: bash salt '*' cp.list_master ''' if env is not None: salt.utils.warn_until( 'Boron', 'Passing a salt environment should be done using \'saltenv\' ' 'not \'env\'. This functionality will be removed in Salt Boron.' ) # Backwards compatibility saltenv = env _mk_client() return __context__['cp.fileclient'].file_list(saltenv, prefix) def list_master_dirs(saltenv='base', prefix='', env=None): ''' List all of the directories stored on the master CLI Example: .. code-block:: bash salt '*' cp.list_master_dirs ''' if env is not None: salt.utils.warn_until( 'Boron', 'Passing a salt environment should be done using \'saltenv\' ' 'not \'env\'. This functionality will be removed in Salt Boron.' ) # Backwards compatibility saltenv = env _mk_client() return __context__['cp.fileclient'].dir_list(saltenv, prefix) def list_master_symlinks(saltenv='base', prefix='', env=None): ''' List all of the symlinks stored on the master CLI Example: .. code-block:: bash salt '*' cp.list_master_symlinks ''' if env is not None: salt.utils.warn_until( 'Boron', 'Passing a salt environment should be done using \'saltenv\' ' 'not \'env\'. This functionality will be removed in Salt Boron.' ) # Backwards compatibility saltenv = env _mk_client() return __context__['cp.fileclient'].symlink_list(saltenv, prefix) def list_minion(saltenv='base', env=None): ''' List all of the files cached on the minion CLI Example: .. code-block:: bash salt '*' cp.list_minion ''' if env is not None: salt.utils.warn_until( 'Boron', 'Passing a salt environment should be done using \'saltenv\' ' 'not \'env\'. This functionality will be removed in Salt Boron.' ) # Backwards compatibility saltenv = env _mk_client() return __context__['cp.fileclient'].file_local_list(saltenv) def is_cached(path, saltenv='base', env=None): ''' Return a boolean if the given path on the master has been cached on the minion CLI Example: .. code-block:: bash salt '*' cp.is_cached salt://path/to/file ''' if env is not None: salt.utils.warn_until( 'Boron', 'Passing a salt environment should be done using \'saltenv\' ' 'not \'env\'. This functionality will be removed in Salt Boron.' ) # Backwards compatibility saltenv = env _mk_client() return __context__['cp.fileclient'].is_cached(path, saltenv) def hash_file(path, saltenv='base', env=None): ''' Return the hash of a file, to get the hash of a file on the salt master file server prepend the path with salt://<file on server> otherwise, prepend the file with / for a local file. CLI Example: .. code-block:: bash salt '*' cp.hash_file salt://path/to/file ''' if env is not None: salt.utils.warn_until( 'Boron', 'Passing a salt environment should be done using \'saltenv\' ' 'not \'env\'. This functionality will be removed in Salt Boron.' ) # Backwards compatibility saltenv = env _mk_client() return __context__['cp.fileclient'].hash_file(path, saltenv) def push(path, keep_symlinks=False, upload_path=None): ''' Push a file from the minion up to the master, the file will be saved to the salt master in the master's minion files cachedir (defaults to ``/var/cache/salt/master/minions/minion-id/files``) Since this feature allows a minion to push a file up to the master server it is disabled by default for security purposes. To enable, set ``file_recv`` to ``True`` in the master configuration file, and restart the master. keep_symlinks Keep the path value without resolving its canonical form upload_path Provide a different path inside the master's minion files cachedir CLI Example: .. code-block:: bash salt '*' cp.push /etc/fstab salt '*' cp.push /etc/system-release keep_symlinks=True salt '*' cp.push /etc/fstab upload_path='/new/path/fstab' ''' log.debug('Trying to copy {0!r} to master'.format(path)) if '../' in path or not os.path.isabs(path): log.debug('Path must be absolute, returning False') return False if not keep_symlinks: path = os.path.realpath(path) if not os.path.isfile(path): log.debug('Path failed os.path.isfile check, returning False') return False auth = _auth() if upload_path: if '../' in upload_path: log.debug('Path must be absolute, returning False') log.debug('Bad path: {0}'.format(upload_path)) return False load_path = upload_path.lstrip(os.sep) else: load_path = path.lstrip(os.sep) load = {'cmd': '_file_recv', 'id': __opts__['id'], 'path': load_path, 'tok': auth.gen_token('salt')} channel = salt.transport.Channel.factory(__opts__) with salt.utils.fopen(path, 'rb') as fp_: init_send = False while True: load['loc'] = fp_.tell() load['data'] = fp_.read(__opts__['file_buffer_size']) if not load['data'] and init_send: return True ret = channel.send(load) if not ret: log.error('cp.push Failed transfer failed. Ensure master has ' '\'file_recv\' set to \'True\' and that the file is not ' 'larger than the \'file_recv_size_max\' setting on the master.') return ret init_send = True def push_dir(path, glob=None, upload_path=None): ''' Push a directory from the minion up to the master, the files will be saved to the salt master in the master's minion files cachedir (defaults to ``/var/cache/salt/master/minions/minion-id/files``). It also has a glob for matching specific files using globbing. .. versionadded:: 2014.7.0 Since this feature allows a minion to push files up to the master server it is disabled by default for security purposes. To enable, set ``file_recv`` to ``True`` in the master configuration file, and restart the master. upload_path Provide a different path and directory name inside the master's minion files cachedir CLI Example: .. code-block:: bash salt '*' cp.push /usr/lib/mysql salt '*' cp.push /usr/lib/mysql upload_path='/newmysql/path' salt '*' cp.push_dir /etc/modprobe.d/ glob='*.conf' ''' if '../' in path or not os.path.isabs(path): return False tmpupload_path = upload_path path = os.path.realpath(path) if os.path.isfile(path): return push(path, upload_path=upload_path) else: filelist = [] for root, dirs, files in os.walk(path): filelist += [os.path.join(root, tmpfile) for tmpfile in files] if glob is not None: filelist = [fi for fi in filelist if fnmatch.fnmatch(fi, glob)] for tmpfile in filelist: if upload_path and tmpfile.startswith(path): tmpupload_path = os.path.join(os.path.sep, upload_path.strip(os.path.sep), tmpfile.replace(path, '').strip(os.path.sep)) ret = push(tmpfile, upload_path=tmpupload_path) if not ret: return ret return True
# -*- coding: utf-8 -*- # # PyFR documentation build configuration file, created by # sphinx-quickstart on Sat Oct 6 23:44:12 2012. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import os import sys # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. sys.path.insert(0, os.path.abspath('../../')) # -- General configuration ----------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.graphviz', 'sphinx.ext.inheritance_diagram', 'sphinx.ext.viewcode', 'sphinx_rtd_theme', 'sphinx.ext.autosectionlabel', 'sphinxcontrib.contentui', ] # Settings for inheritance diagrams. graphviz_output_format = 'svg' inheritance_graph_attrs = dict( center='true', layout='dot', rankdir='LR', ranksep='0.05', splines='ortho', ratio='compress') inheritance_node_attrs = dict( color='"#333333"', fillcolor='"#d8e6b8"', fontsize='6.5', penwidth='0.3', shape='box', style='"rounded,filled"') inheritance_edge_attrs = dict( color='"#333333"', penwidth='0.3') # The names of modules to mock and hence avoid import. autodoc_mock_imports = ['h5py', 'mpi4py', 'gimmik', 'numpy', 'mako', 'platformdirs'] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = u'PyFR' copyright = u'2013–2021, Imperial College London' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = '1.14.0' # The full version, including alpha/beta/rc tags. release = '1.14.0' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = [] # The reST default role (used for this markup: `text`) to use for all documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # -- Options for HTML output --------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = "sphinx_rtd_theme" html_logo = "../fig/logo.svg" html_favicon = "../fig/pyfr_favicon.png" # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. html_theme_options = { 'analytics_anonymize_ip': False, 'logo_only': True, 'display_version': False, 'prev_next_buttons_location': 'bottom', 'style_external_links': False, 'vcs_pageview_mode': '', 'style_nav_header_background': '#94b24c', # Toc options 'collapse_navigation': True, 'sticky_navigation': True, 'navigation_depth': 4, 'includehidden': True, 'titles_only': False, } # Add any paths that contain custom themes here, relative to this directory. #html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # "<project> v<release> documentation". html_title = 'Documentation' # A shorter title for the navigation bar. Default is the same as html_title. html_short_title = 'PyFR - Documentation' # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] html_css_files = [ 'css/custom.css', ] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a <link> tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'PyFRdoc' # -- Options for LaTeX output -------------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', # Additional stuff for the LaTeX preamble. 'preamble': '\setcounter{secnumdepth}{4}', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]). latex_documents = [ ('index', 'PyFR.tex', u'PyFR Documentation', u'Imperial College London', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output -------------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('index', 'pyfr', u'PyFR Documentation', [u'Imperial College London'], 1) ] # If true, show URL addresses after external links. #man_show_urls = False # -- Options for Texinfo output ------------------------------------------------ # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ('index', 'PyFR', u'PyFR Documentation', u'Imperial College London', 'PyFR', 'A high-order Flux Reconstruction solver.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. #texinfo_appendices = [] # If false, no module index is generated. #texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. #texinfo_show_urls = 'footnote'
("undefined"==typeof window?global:window).__07e029149e7b50ff5008626a55c0874d=function(){function e(e){return e&&e.__esModule?e:{default:e}}var t={},i=e(__ce09c80fb835cb76cda82f0f0d4a1ea3),n=e(__7a6521db1039cb333e437aa8031353cf);return function(){function e(e){String(e.value).trim().length||(e.value=e.getAttribute("placeholder"),(0,i.default)(e).addClass("aui-placeholder-shown"))}"placeholder"in document.createElement("input")||(0,n.default)("placeholder",{type:n.default.type.ATTRIBUTE,events:{blur:e,focus:function(e){e.value===e.getAttribute("placeholder")&&(e.value="",(0,i.default)(e).removeClass("aui-placeholder-shown"))}},created:e})}(),t}.call(this),("undefined"==typeof window?global:window).__c6ad19cff937f24a9e7543bca33f8b40=function(){function e(e){return e&&e.__esModule?e:{default:e}}function t(e){var t=function(e){return(0,a.default)((0,c.default)('<div class="aui-banner aui-banner-{type}" role="banner">{body}</div>').fill({type:"error","body:html":e.body||""}).toString())}(e);return i().find(".aui-banner").get().forEach(function(e){"true"===e.getAttribute("aria-hidden")&&(0,a.default)(e).remove()}),function(e){var t=i();if(!t.length)throw new Error("You must implement the application header");e.prependTo(t),(0,r.recomputeStyle)(e),e.attr("aria-hidden","false")}(t),t[0]}function i(){return(0,a.default)("#"+d)}var n={exports:{}},s=n.exports;Object.defineProperty(s,"__esModule",{value:!0});var a=e(__ce09c80fb835cb76cda82f0f0d4a1ea3),r=__027703b7d07563496ecfdc7f4681e189,o=e(__fb114d9b531e09c60f5fdf12262b017c),l=e(__2bc1a6edbc312083fbf11f878f780e28),c=e(__41bafd0ad7106b8a30c707ace285f769),d="header";return(0,o.default)("aui/banner",t),(0,l.default)("banner",t),s.default=t,n.exports=s.default,n.exports}.call(this),("undefined"==typeof window?global:window).__a6e1673bb01a22322ef9341042944d0a=function(){function e(e){return e&&e.__esModule?e:{default:e}}function t(e){return e.hasAttribute("aria-busy")&&"true"===e.getAttribute("aria-busy")}function i(e){return"INPUT"===e.nodeName}var n={},s=e(__ce09c80fb835cb76cda82f0f0d4a1ea3),a=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&(t[i]=e[i]);return t.default=e,t}(__5cedb2bf0c96530c8ee1c2fdf05590cb),r=e(__fb114d9b531e09c60f5fdf12262b017c),o=e(__7a6521db1039cb333e437aa8031353cf);return(0,o.default)("aui-button",{type:o.default.type.CLASSNAME,prototype:{busy:function(){return i(this)||t(this)?(a.warn("It is not valid to call busy() on an input button."),this):((0,s.default)(this).spin(),this.setAttribute("aria-busy",!0),this.setAttribute("busy",""),this)},idle:function(){return i(this)||!t(this)?(a.warn("It is not valid to call idle() on an input button."),this):((0,s.default)(this).spinStop(),this.removeAttribute("aria-busy"),this.removeAttribute("busy"),this)},isBusy:function(){return i(this)?(a.warn("It is not valid to call isBusy() on an input button."),!1):t(this)}}}),(0,r.default)("aui/button"),n}.call(this),("undefined"==typeof window?global:window).__86b584d7b2dca6d114205bd2e5d490d7=function(){var e={};return function(e){function t(e,t){return"function"==typeof e?e.call(t):e}function i(e){for(;e=e.parentNode;)if(e==document)return!0;return!1}function n(t,i){this.$element=e(t),this.options=i,this.enabled=!0,this.fixTitle()}var s=0;n.prototype={show:function(){if(i(this.$element[0])){var n=this.getTitle();if(n&&this.enabled){var a=this.tip();a.find(".tipsy-inner")[this.options.html?"html":"text"](n),a[0].className="tipsy",a.remove().css({top:0,left:0,visibility:"hidden",display:"block"}).appendTo(document.body);var r=this;this.options.hoverable&&a.hover(function(){r.hoverTooltip=!0},function(){if("in"!=r.hoverState&&(r.hoverTooltip=!1,"manual"!=r.options.trigger)){var e="hover"==r.options.trigger?"mouseleave.tipsy":"blur.tipsy";r.$element.trigger(e)}}),this.options.className&&a.addClass(t(this.options.className,this.$element[0]));var o=e.extend({},this.$element.offset(),{width:this.$element[0].getBoundingClientRect().width,height:this.$element[0].getBoundingClientRect().height}),l={},c=a[0].offsetWidth,d=a[0].offsetHeight,u=t(this.options.gravity,this.$element[0]);switch(2===u.length&&("w"===u.charAt(1)?l.left=o.left+o.width/2-15:l.left=o.left+o.width/2-c+15),u.charAt(0)){case"n":void 0===l.left&&(l.left=o.left+o.width/2-c/2),l.top=o.top+o.height+this.options.offset;break;case"s":void 0===l.left&&(l.left=o.left+o.width/2-c/2,a.css(l),d=a[0].offsetHeight),l.top=o.top-d-this.options.offset;break;case"e":l.left=o.left-c-this.options.offset,l.top=o.top+o.height/2-d/2;break;case"w":l.left=o.left+o.width+this.options.offset,l.top=o.top+o.height/2-d/2}if(a.css(l).addClass("tipsy-"+u),a.find(".tipsy-arrow")[0].className="tipsy-arrow tipsy-arrow-"+u.charAt(0),this.options.fade?a.stop().css({opacity:0,display:"block",visibility:"visible"}).animate({opacity:this.options.opacity}):a.css({visibility:"visible",opacity:this.options.opacity}),this.options.aria){var h="tipsyuid"+s++;a.attr("id",h),this.$element.attr("aria-describedby",h)}}}},destroy:function(){this.$element.removeData("tipsy"),this.unbindHandlers(),this.hide()},unbindHandlers:function(){this.options.live?e(this.$element.context).off(".tipsy"):this.$element.unbind(".tipsy")},hide:function(){this.options.fade?this.tip().stop().fadeOut(function(){e(this).remove()}):this.tip().remove(),this.options.aria&&this.$element.removeAttr("aria-describedby")},fixTitle:function(){var e=this.$element;(e.attr("title")||"string"!=typeof e.attr("original-title"))&&e.attr("original-title",e.attr("title")||"").removeAttr("title")},getTitle:function(){var e=this.$element,t=this.options;this.fixTitle();var i;return"string"==typeof(t=this.options).title?i=e.attr("title"==t.title?"original-title":t.title):"function"==typeof t.title&&(i=t.title.call(e[0])),(i=(""+i).replace(/(^\s*|\s*$)/,""))||t.fallback},tip:function(){return this.$tip||(this.$tip=e('<div class="tipsy"></div>').html('<div class="tipsy-arrow"></div><div class="tipsy-inner"></div>').attr("role","tooltip"),this.$tip.data("tipsy-pointee",this.$element[0])),this.$tip},validate:function(){this.$element[0].parentNode||(this.hide(),this.$element=null,this.options=null)},enable:function(){this.enabled=!0},disable:function(){this.enabled=!1},toggleEnabled:function(){this.enabled=!this.enabled}},e.fn.tipsy=function(t){function i(i){var s=e.data(i,"tipsy");return s||(s=new n(i,e.fn.tipsy.elementOptions(i,t)),e.data(i,"tipsy",s)),s}function s(){var e=i(this);e.hoverState="in",0==t.delayIn?e.show():(e.fixTitle(),setTimeout(function(){"in"==e.hoverState&&e.show()},t.delayIn))}function a(){var e=i(this);e.hoverState="out",0==t.delayOut?e.hide():setTimeout(function(){"out"!=e.hoverState||e.hoverTooltip||e.hide()},t.delayOut)}if(!0===t)return this.data("tipsy");if("string"==typeof t){var r=this.data("tipsy");return r&&r[t](),this}if((t=e.extend({},e.fn.tipsy.defaults,t)).hoverable&&(t.delayOut=t.delayOut||20),t.live||this.each(function(){i(this)}),"manual"!=t.trigger){var o="hover"==t.trigger?"mouseenter.tipsy focus.tipsy":"focus.tipsy",l="hover"==t.trigger?"mouseleave.tipsy blur.tipsy":"blur.tipsy";t.live?e(this.context).on(o,this.selector,s).on(l,this.selector,a):this.bind(o,s).bind(l,a)}return this},e.fn.tipsy.defaults={aria:!1,className:null,delayIn:0,delayOut:0,fade:!1,fallback:"",gravity:"n",html:!1,live:!1,hoverable:!1,offset:0,opacity:.8,title:"title",trigger:"hover"},e.fn.tipsy.revalidate=function(){e(".tipsy").each(function(){var t=e.data(this,"tipsy-pointee");t&&i(t)||e(this).remove()})},e.fn.tipsy.elementOptions=function(t,i){return e.metadata?e.extend({},i,e(t).metadata()):i},e.fn.tipsy.autoNS=function(){return e(this).offset().top>e(document).scrollTop()+e(window).height()/2?"s":"n"},e.fn.tipsy.autoWE=function(){return e(this).offset().left>e(document).scrollLeft()+e(window).width()/2?"e":"w"},e.fn.tipsy.autoBounds=function(t,i){return function(){var n={ns:i[0],ew:i.length>1&&i[1]},s=e(document).scrollTop()+t,a=e(document).scrollLeft()+t,r=e(this);return r.offset().top<s&&(n.ns="n"),r.offset().left<a&&(n.ew="w"),e(window).width()+e(document).scrollLeft()-r.offset().left<t&&(n.ew="e"),e(window).height()+e(document).scrollTop()-r.offset().top<t&&(n.ns="s"),n.ns+(n.ew?n.ew:"")}}}(jQuery),e}.call(this),("undefined"==typeof window?global:window).__a294568ce889e2dee24779703d6be870=function(){function e(e,t,i){return e.tipsy(i),"destroy"===i&&(t.live?(0,n.default)(e.context).off(".tipsy",e.selector):e.unbind(".tipsy")),e}function t(e,t){e.tipsy(t);if(t&&t.hideOnClick&&("hover"===t.trigger||!t.trigger&&"hover"===e.tipsy.defaults.trigger)){var i=function(){(0,n.default)(this).tipsy("hide")};t.live?(0,n.default)(e.context).on("click.tipsy",e.selector,i):e.bind("click.tipsy",i)}return e}var i={},n=function(e){return e&&e.__esModule?e:{default:e}}(__ce09c80fb835cb76cda82f0f0d4a1ea3);return __86b584d7b2dca6d114205bd2e5d490d7,n.default.fn.tooltip=function(i){var s=n.default.extend({},n.default.fn.tooltip.defaults,i);return s.live?("string"==typeof i?e(this,s,i):t(this,s),this):this.each(function(){var a=(0,n.default)(this);return"string"==typeof i?e(a,s,i):t(a,s),a})},n.default.fn.tooltip.defaults={opacity:1,offset:1,delayIn:500,hoverable:!0,hideOnClick:!0,aria:!0},i}.call(this),("undefined"==typeof window?global:window).__854c952394699e4cd7993f3206d22691=function(){function e(e){return e&&e.__esModule?e:{default:e}}function t(e){var t=(0,u.default)(e.target);i(this,t.attr("data-value"),t.hasClass("aui-dropdown2-checked"))}function i(e,t,i){var n=e.$select.find("option").filter(function(){var e=(0,u.default)(this);return e.attr("value")===t&&e.prop("selected")!==i});n.length&&(n.prop("selected",i),e.$select.trigger("change"))}function n(e){e.$dropdown.find("[data-aui-checkbox-multiselect-clear]").prop("disabled",function(){return o(e).length<1})}function s(e){return e.map(function(){var e=(0,u.default)(this);return{value:e.val(),label:e.text(),icon:e.data("icon"),styleClass:e.data("styleClass"),title:e.attr("title"),disabled:e.attr("disabled"),selected:e.prop("selected")}})}function a(e){e.$dropdown.html(g.dropdown(function(e){return s(e.getOptions())}(e))),n(e)}function r(e){var t=l(e),i=function(e){return 0===o(e).length}(e)?function(e){return(0,u.default)(e).data("allLabel")||"All"}(e):t.join(", ");e.$btn.text(i)}function o(e){return s(e.getSelectedOptions())}function l(e){return u.default.map(o(e),function(e){return e.label})}var c={exports:{}},d=c.exports;Object.defineProperty(d,"__esModule",{value:!0});var u=e(__ce09c80fb835cb76cda82f0f0d4a1ea3);__38aed1c652a99429a6c4df9946edf6f4,__a294568ce889e2dee24779703d6be870,__6e5c1a3f5afadc2fe31a54c52b7091ab;var h=e(__fb114d9b531e09c60f5fdf12262b017c),f=e(__7a6521db1039cb333e437aa8031353cf),p=e(__77c8c05565043823fdeac2c0158b936e),g={dropdown:function(e){function t(){return(0,u.default)('<div class="aui-dropdown2-section">')}var i=t();(0,u.default)("<button />").attr({type:"button","data-aui-checkbox-multiselect-clear":"",class:"aui-button aui-button-link"}).text(AJS.I18n.getText("aui.checkboxmultiselect.clear.selected")).appendTo(i);var n=t(),s=(0,u.default)("<ul />").appendTo(n);return u.default.each(e,function(e,t){var i=(0,u.default)("<li />").attr({class:t.styleClass||""}).appendTo(s),n=(0,u.default)("<a />").text(t.label).attr("data-value",t.value).addClass("aui-dropdown2-checkbox aui-dropdown2-interactive").appendTo(i);t.icon&&(0,u.default)("<span />").addClass("aui-icon").css("backgroundImage","url("+t.icon+')")').appendTo(n),t.selected&&n.addClass("aui-dropdown2-checked")}),(0,u.default)("<div />").append(i).append(n).html()},furniture:function(e,t){var i=e+"-dropdown",n=(0,u.default)("<select />").attr({name:e,multiple:"multiple"}).html(t),s=(0,u.default)("<div>").attr({id:i,class:"aui-checkbox-multiselect-dropdown aui-dropdown2 aui-style-default"}),a=(0,u.default)("<button />").attr({class:"aui-checkbox-multiselect-btn aui-button aui-dropdown2-trigger",type:"button","aria-owns":i,"aria-haspopup":!0});return(0,u.default)("<div />").append(n).append(a).append(s).html()}},v=(0,f.default)("aui-checkbox-multiselect",{attached:function(e){var i=e.getAttribute("name")||(0,p.default)("aui-checkbox-multiselect-");e.innerHTML=g.furniture(i,e.innerHTML),e.$select=(0,u.default)("select",e).change(function(){r(e),n(e)}),e.$dropdown=(0,u.default)(".aui-checkbox-multiselect-dropdown",e).on("aui-dropdown2-item-check",t.bind(e)).on("aui-dropdown2-item-uncheck",t.bind(e)).on("click","button[data-aui-checkbox-multiselect-clear]",e.deselectAllOptions.bind(e)),e.$btn=(0,u.default)(".aui-checkbox-multiselect-btn",e).tooltip({title:function(){return function(e){return e.$dropdown.is("[aria-hidden=false]")?"":l(e).join(", ")}(e)}}),r(e),a(e)},prototype:{getOptions:function(){return this.$select.find("option")},getSelectedOptions:function(){return this.$select.find("option:selected")},selectOption:function(e){i(this,e,!0)},unselectOption:function(e){i(this,e,!1)},getValue:function(){return this.$select.val()},deselectAllOptions:function(){this.$select.val([]).trigger("change"),this.$dropdown.find(".aui-dropdown2-checked,.checked").removeClass("aui-dropdown2-checked checked")},addOption:function(e){(0,u.default)("<option />").attr({value:e.value,icon:e.icon,disabled:e.disabled,selected:e.selected,title:e.title}).text(e.label).appendTo(this.$select),r(this),a(this)},removeOption:function(e){this.$select.find("[value='"+e+"']").remove(),r(this),a(this)}}});return(0,h.default)("aui/checkbox-multiselect"),d.default=v,c.exports=d.default,c.exports}.call(this),("undefined"==typeof window?global:window).__25f6ecd120c36f98f80013c17563c5e4=function(){function e(e){return e&&e.__esModule?e:{default:e}}function t(e){this.$el=e?(0,s.default)(e):(0,s.default)(aui.dialog.dialog2({})),function(e){s.default.each(c,function(t,i){var n="data-"+t;e[0].hasAttribute(n)||e.attr(n,i)})}(this.$el)}var i={exports:{}},n=i.exports;Object.defineProperty(n,"__esModule",{value:!0});var s=e(__ce09c80fb835cb76cda82f0f0d4a1ea3),a=e(__fb114d9b531e09c60f5fdf12262b017c),r=e(__2bc1a6edbc312083fbf11f878f780e28),o=e(__cf31d764659b2033862570138beab86e),l=e(__ca3e3104543f86ce5d69c679cc0b6ddd),c={"aui-focus":"false","aui-blanketed":"true"};t.prototype.on=function(e,t){return(0,o.default)(this.$el).on(e,t),this},t.prototype.off=function(e,t){return(0,o.default)(this.$el).off(e,t),this},t.prototype.show=function(){return(0,o.default)(this.$el).show(),this},t.prototype.hide=function(){return(0,o.default)(this.$el).hide(),this},t.prototype.remove=function(){return(0,o.default)(this.$el).remove(),this},t.prototype.isVisible=function(){return(0,o.default)(this.$el).isVisible()};var d=(0,l.default)("dialog2",t);return d.on=function(e,t){return o.default.on(e,".aui-dialog2",t),this},d.off=function(e,t){return o.default.off(e,".aui-dialog2",t),this},(0,s.default)(document).on("click",".aui-dialog2-header-close",function(e){e.preventDefault(),d((0,s.default)(this).closest(".aui-dialog2")).hide()}),d.on("show",function(e,t){var i;[".aui-dialog2-content",".aui-dialog2-footer",".aui-dialog2-header"].some(function(e){return(i=t.find(e+" :aui-tabbable")).length}),i&&i.first().focus()}),d.on("hide",function(e,t){var i=(0,o.default)(t);t.data("aui-remove-on-hide")&&i.remove()}),(0,a.default)("aui/dialog2",d),(0,r.default)("dialog2",d),n.default=d,i.exports=n.default,i.exports}.call(this),("undefined"==typeof window?global:window).__e99a1d9cad8cc3c3d6710c33f4f366db=function(){var e={},t=function(e){return e&&e.__esModule?e:{default:e}}(__ce09c80fb835cb76cda82f0f0d4a1ea3),i=(0,t.default)(document),n=function(e){var n={};return n.$trigger=(0,t.default)(e.currentTarget),n.$content=i.find("#"+n.$trigger.attr("aria-controls")),n.triggerIsParent=0!==n.$content.parent().filter(n.$trigger).length,n.$shortContent=n.triggerIsParent?n.$trigger.find(".aui-expander-short-content"):null,n.height=n.$content.css("min-height"),n.isCollapsible=!1!==n.$trigger.data("collapsible"),n.replaceText=n.$trigger.attr("data-replace-text"),n.replaceSelector=n.$trigger.data("replace-selector"),n},s=function(e){if(e.replaceText){var t=e.replaceSelector?e.$trigger.find(e.replaceSelector):e.$trigger;e.$trigger.attr("data-replace-text",t.text()),t.text(e.replaceText)}},a={"aui-expander-invoke":function(e){var n=(0,t.default)(e.currentTarget),s=i.find("#"+n.attr("aria-controls")),a=!1!==n.data("collapsible");"true"===s.attr("aria-expanded")&&a?n.trigger("aui-expander-collapse"):n.trigger("aui-expander-expand")},"aui-expander-expand":function(e){var t=n(e);"true"!==t.$content.attr("aria-expanded")&&(t.$content.attr("aria-expanded","true"),t.$trigger.attr("aria-expanded","true"),t.$content.outerHeight()>0&&t.$content.attr("aria-hidden","false"),s(t),t.triggerIsParent&&t.$shortContent.hide(),t.$trigger.trigger("aui-expander-expanded"))},"aui-expander-collapse":function(e){var t=n(e);"true"===t.$content.attr("aria-expanded")&&(s(t),t.$content.attr("aria-expanded","false"),t.$trigger.attr("aria-expanded","false"),t.triggerIsParent&&t.$shortContent.show(),0===t.$content.outerHeight()&&t.$content.attr("aria-hidden","true"),t.$trigger.trigger("aui-expander-collapsed"))},"click.aui-expander":function(e){(0,t.default)(e.currentTarget).trigger("aui-expander-invoke",e.currentTarget)}};return i.on(a,".aui-expander-trigger"),e}.call(this),("undefined"==typeof window?global:window).__021e9cff0ae14087301bfc6bbcd8d193=function(){function e(e){return e&&e.__esModule?e:{default:e}}function t(e){var t=function(e){var t=(0,h.default)('<div class="aui-flag"><div class="aui-message aui-message-{type} {type} {closeable} shadowed"><p class="title"><strong>{title}</strong></p>{body}\x3c!-- .aui-message --\x3e</div></div>').fill({"body:html":e.body||"",closeable:"never"===e.close?"":"closeable",title:e.title||"",type:e.type}).toString();return(0,o.default)(t)}(e=o.default.extend({},v,e));return function(e){e[0].close=function(){n(e)}}(t),"auto"===e.close?(i(t),function(e){e.find(".aui-message").addClass("aui-will-close"),setTimeout(function(){e[0].close()},p)}(t)):"manual"===e.close&&i(t),s().find(".aui-flag").get().forEach(function(e){"true"===e.getAttribute("aria-hidden")&&(0,o.default)(e).remove()}),function(e){var t=s();t.length||(t=(0,o.default)('<div id="'+g+'"></div>'),(0,o.default)("body").prepend(t));return e.appendTo(t),(0,l.recomputeStyle)(e),e.attr("aria-hidden","false")[0]}(t)}function i(e){var t=(0,o.default)('<span class="aui-icon icon-close" role="button" tabindex="0"></span>');return t.click(function(){n(e)}),t.keypress(function(t){t.which!==u.default.ENTER&&t.which!==u.default.SPACE||(n(e),t.preventDefault())}),e.find(".aui-message").append(t)[0]}function n(e){var t=e.get(0);return t.setAttribute("aria-hidden","true"),t.dispatchEvent(new f.default("aui-flag-close",{bubbles:!0})),t}function s(){return(0,o.default)("#"+g)}var a={exports:{}},r=a.exports;Object.defineProperty(r,"__esModule",{value:!0});var o=e(__ce09c80fb835cb76cda82f0f0d4a1ea3),l=__027703b7d07563496ecfdc7f4681e189,c=e(__fb114d9b531e09c60f5fdf12262b017c),d=e(__2bc1a6edbc312083fbf11f878f780e28),u=e(__4850ac7f6e93ba35f83ca6803a088772),h=e(__41bafd0ad7106b8a30c707ace285f769),f=e(__59d7c0f9f17285b854c637a67b2cc160),p=5e3,g="aui-flag-container",v={body:"",close:"manual",title:"",type:"info"};return(0,c.default)("aui/flag",t),(0,d.default)("flag",t),r.default=t,a.exports=r.default,a.exports}.call(this),("undefined"==typeof window?global:window).__2220bade9e250c8271d410ece8bca942=function(){function e(e){return e&&e.__esModule?e:{default:e}}function t(e){i(e)||(!function(e){e.addClass(C),function(e){var t=(0,b.default)('<span class="aui-icon aui-icon-small '+S+'"/>');e.after(t)}(e)}(e),function(e){h(e).tipsy({gravity:function(e){var t=e.data(D)||"side",i={side:"w",top:"se",bottom:"ne"}[t];i||(i="w",m.warn('Invalid notification position: "'+t+'". Valid options are "side", "bottom, "top"'));return i}(e),title:function(){return n(e)},trigger:"manual",offset:function(e){return-1!==F.indexOf(e.attr("type"))}(e)?M:L,opacity:P,className:function(){return"aui-form-notification-tooltip "+function(e){var t=s(e);{if(t===$)return A;if(t===I)return T}}(e)},html:!0})}(e),function(e){a(e)&&function(e){e.on("keydown",function(t){if(c(t)&&function(e){return""!==n(e)}(e)){var i=d(e);i.length&&(i.focus(),t.preventDefault())}})}(e)}(e),g(e)),k.push(e)}function i(e){return e.hasClass(C)}function n(e){var t=s(e);return function(e){if(""===e)return e;var t=function(e){var t;try{t=JSON.parse(e)}catch(i){t=[e]}return t}(e);return 1===t.length?t[0]:"<ul><li>"+t.join("</li><li>")+"</li></ul>"}(t?e.attr(t):"")}function s(e){var t;return N.some(function(i){if(e.is("["+i+"]"))return t=i,!0}),t}function a(e){return e.is(":aui-focusable")}function r(e){h(e).tipsy("show"),a(e)&&function(e){u(e).on("keydown",function(t){var i=p(function(e){return u(e).find(":aui-tabbable").last()}(e)),n=p(d(e));c(t)&&i&&i&&e.focus(),function(e){return e.keyCode===w.default.TAB&&e.shiftKey}(t)&&n&&n&&(e.focus(),t.preventDefault())})}(e)}function o(e){h(e).tipsy("hide")}function l(e,t){return(0,b.default)(e.target).closest(t).length>0}function c(e){return e.keyCode===w.default.TAB&&!e.shiftKey&&!e.altKey}function d(e){return u(e).find(":aui-tabbable").first()}function u(e){var t=h(e);if(t.data("tipsy"))return t.data("tipsy").$tip}function h(e){return f(e)}function f(e){return e.next("."+S)}function p(e){var t=e instanceof b.default?e[0]:e;return t&&t===document.activeElement}function g(e){var t=(0,b.default)(e);if(i(t)){var l=s(t);!function(e,t){t?f(e).addClass("aui-icon-wait"):f(e).removeClass("aui-icon-wait")}(t,l===O);if(!l)o(t);else{var c=n(t);(b.default.contains(t[0],document.activeElement)||p(t)||!a(t))&&c?r(t):o(t)}}}var v={},b=e(__ce09c80fb835cb76cda82f0f0d4a1ea3);__86b584d7b2dca6d114205bd2e5d490d7;var m=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&(t[i]=e[i]);return t.default=e,t}(__5cedb2bf0c96530c8ee1c2fdf05590cb),_=e(__fb114d9b531e09c60f5fdf12262b017c),w=e(__4850ac7f6e93ba35f83ca6803a088772),y=e(__7a6521db1039cb333e437aa8031353cf),x="aui-form-notification",C="_aui-form-notification-initialised",S="aui-icon-notification",E=x+"-tooltip",A=E+"-error",T=E+"-info",R="data-aui-notification-",O=R+"wait",I=R+"info",$=R+"error",D=x+"-position",N=[$,"data-aui-notification-success",O,I],k=[],P=1,M=9,L=3,F=["text","url","email","tel","password"];return document.addEventListener("focus",function(e){k.forEach(function(t){var i=(0,b.default)(t),n=u(i);if(a(i)){var s=n&&b.default.contains(n[0],e.target),c=i.is(e.target),d=l(e,i);c||d?r(i):n&&!s&&o(i)}})},!0),document.addEventListener("mousedown",function(e){if(!(0,b.default)(e.target).is("a")){if(!((0,b.default)(e.target).closest(".aui-form-notification-tooltip").length>0)){(0,b.default)("[data-aui-notification-field]").each(function(){var t=(0,b.default)(this),i=t.is(e.target),n=l(e,t);i||n||o(t),a(t)&&o(t)})}}}),(0,y.default)("data-aui-notification-field",{attached:function(e){t((0,b.default)(e))},attributes:function(){var e={};return N.forEach(function(t){e[t]=g}),e}(),type:y.default.type.ATTRIBUTE}),(0,_.default)("aui/form-notification"),v}.call(this),("undefined"==typeof window?global:window).__b2f7b02e2b6317ef4485dba3603d3a09=function(){function e(e){return e&&e.__esModule?e:{default:e}}var t={exports:{}},i=t.exports;Object.defineProperty(i,"__esModule",{value:!0});var n=e(__ce09c80fb835cb76cda82f0f0d4a1ea3),s=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&(t[i]=e[i]);return t.default=e,t}(__5cedb2bf0c96530c8ee1c2fdf05590cb),a=["displayfield","watchfield","when","novalidate","state"],r=[],o={register:function(e,t){var i;if("string"==typeof e)i=e;else{var o=function(t){var i=!1;return e.some(function(e){var t=-1!==n.default.inArray(e,a);return t&&(i=e),t}),i}();if(o)return s.warn('Validators cannot be registered with the argument "'+o+'", as it is a reserved argument.'),!1;i="[data-aui-validation-"+e.join("],[data-aui-validation-")+"]"}var l={validatorFunction:t,validatorTrigger:i};return r.push(l),l},validators:function(){return r}};return(0,e(__fb114d9b531e09c60f5fdf12262b017c).default)("aui/form-validation/validator-register",o),i.default=o,t.exports=i.default,t.exports}.call(this),("undefined"==typeof window?global:window).__9dcc477dc72b9fd8eed74f58663d0f22=function(){function e(e){return e&&e.__esModule?e:{default:e}}function t(e){var t=e.el.value.length,i=0===t,n=parseInt(e.args("minlength"),10),s=parseInt(e.args("maxlength"),10);if(n&&s&&n===s&&!i&&t!==n){var a=o("exactlength",e.args,[n]);e.invalidate(a)}else if(n&&t<n&&!i){var r=o("minlength",e.args);e.invalidate(r)}else if(s&&t>s){var l=o("maxlength",e.args);e.invalidate(l)}else e.validate()}function i(e){return"password"===e.getAttribute("type")}function n(e,t){var i=e.match(t);if(!i)return!1;return e===i[0]}function s(e){var t=o("pattern",e.args);n(e.el.value,new RegExp(e.args("pattern")))?e.validate():e.invalidate(t)}function a(e){var t=o("required",e.args);e.el.value?e.validate():e.invalidate(t)}function r(e){var t=o("validnumber",e.args),i=parseInt(e.el.value,10);if(isNaN(i))e.invalidate(t);else{var n=e.args("min"),s=e.args("max");n&&i<parseInt(n,10)?e.invalidate(o("min",e.args)):s&&i>parseInt(s,10)?e.invalidate(o("max",e.args)):e.validate()}}function o(e,t,i){var n;n=void 0!==AJS.I18n.keys?AJS.I18n.keys["aui.validation.message."+e]:h[e];var s=i;i||(s=[t(e)]);var a,r=t(e+"-msg");return a=r?[r].concat(s):[n].concat(s),AJS.format.apply(null,a)}var l={},c=e(__ce09c80fb835cb76cda82f0f0d4a1ea3),d=e(__fb114d9b531e09c60f5fdf12262b017c),u=(e(__873f998b9d3c8cc70ab3feb0d146fab0),e(__6e5c1a3f5afadc2fe31a54c52b7091ab),e(__b2f7b02e2b6317ef4485dba3603d3a09));u.default.register(["maxlength","minlength"],t),u.default.register("[maxlength],[minlength]",t),u.default.register(["matchingfield"],function(e){var t=e.el.value,n=document.getElementById(e.args("matchingfield")),s=n.value,a=o("matchingfield",e.args,[t,s]);(i(e.el)||i(n))&&(a=o("matchingfield-novalue",e.args)),t&&s&&s!==t?e.invalidate(a):e.validate()}),u.default.register(["doesnotcontain"],function(e){var t=o("doesnotcontain",e.args);-1===e.el.value.indexOf(e.args("doesnotcontain"))?e.validate():e.invalidate(t)}),u.default.register(["pattern"],s),u.default.register("[pattern]",s),u.default.register(["required"],a),u.default.register("[required]",a),u.default.register(["min","max"],r),u.default.register("[min],[max]",r),u.default.register(["dateformat"],function(e){var t=e.args("dateformat"),i=o("dateformat",e.args),s={Y:"[0-9]{4}",y:"[0-9]{2}",m:"(0?[1-9]|10|11|12)",M:"[Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec]",D:"[Mon|Tue|Wed|Thu|Fri|Sat|Sun]",d:"([0-2]?[1-9]|10|20|30|31)"},a="";t.split("").forEach(function(e){var t=s.hasOwnProperty(e);a+=t?s[e]:e});var r=new RegExp(a+"$","i");n(e.el.value,r)?e.validate():e.invalidate(i)}),u.default.register(["minchecked","maxchecked"],function(e){var t=(0,c.default)(e.el).find(":checked").length,i=!e.args("minchecked")||t>=e.args("minchecked"),n=!e.args("maxchecked")||t<=e.args("maxchecked"),s=o("minchecked",e.args),a=o("maxchecked",e.args);i&&n?e.validate():i?n||e.invalidate(a):e.invalidate(s)});var h={minlength:AJS.I18n.getText("aui.validation.message.minlength"),maxlength:AJS.I18n.getText("aui.validation.message.maxlength"),exactlength:AJS.I18n.getText("aui.validation.message.exactlength"),matchingfield:AJS.I18n.getText("aui.validation.message.matchingfield"),"matchingfield-novalue":AJS.I18n.getText("aui.validation.message.matchingfield-novalue"),doesnotcontain:AJS.I18n.getText("aui.validation.message.doesnotcontain"),pattern:AJS.I18n.getText("aui.validation.message.pattern"),required:AJS.I18n.getText("aui.validation.message.required"),validnumber:AJS.I18n.getText("aui.validation.message.validnumber"),min:AJS.I18n.getText("aui.validation.message.min"),max:AJS.I18n.getText("aui.validation.message.max"),dateformat:AJS.I18n.getText("aui.validation.message.dateformat"),minchecked:AJS.I18n.getText("aui.validation.message.minchecked"),maxchecked:AJS.I18n.getText("aui.validation.message.maxchecked")};return(0,d.default)("aui/form-validation/basic-validators"),l}.call(this),("undefined"==typeof window?global:window).__4bb68509831c5889ca4df930402a1328=function(){function e(e){return e&&e.__esModule?e:{default:e}}function t(e){(function(e){return e.hasClass(R)})(e)||(!function(e){l(e).attr("data-aui-notification-field","")}(e),function(e){e.addClass(R)}(e),function(e){(function(e){var t,i=function(){e.trigger("aui-stop-typing")};e.on("keyup",function(){clearTimeout(t),t=setTimeout(i,1500)})})(e),function(e){var t=n(e,"when"),s=n(e,"watchfield");(s?e.add("#"+s):e).on(t,function(){i(e)})}(e)}(e),a(e,T))}function i(e){if(!n(e,"novalidate"))return function(e){!function(e){r(l(e),"none")}(e);var t=function(e){var t=[];return s().forEach(function(i,n){var s=i.validatorTrigger;e.is(s)&&t.push(n)}),t}(e);a(e,A);var i=function(e,t){var i=[];return t.forEach(function(t){var n=s()[t].validatorFunction,r=new g.default.Deferred;n(function(e,t){var i={validate:function(){t.resolve()},invalidate:function(i){a(e,S,i),t.reject()},args:function(e){return function(t){return e.attr("data-"+y+t)||e.attr(t)}}(e),el:e[0],$el:e};return b.prop(i,"$el",{sinceVersion:"5.9.0",removeInVersion:"8.0.0",alternativeName:"el",extraInfo:"See https://ecosystem.atlassian.net/browse/AUI-3263."}),i}(e,r)),i.push(r)}),i}(e,t),n=g.default.when.apply(g.default,i);return n.done(function(){a(e,E)}),n}(e);a(e,E)}function n(e,t){var i=e.attr("data-"+y+t);return i||(i={when:"change"}[t]),i}function s(){return w.default.validators()}function a(e,t,i){if(e.attr("data-"+C,t),t!==T){e.trigger(g.default.Event(O));var n=l(e),s={};s[A]="wait",s[S]="error",s[E]="success";var a=s[t];t===A?function(e){setTimeout(function(){c(e)===A&&r(e,"wait")},500)}(e):r(n,a,i)}}function r(e,t,i){var n=function(e){return e.is("["+x+"wait]")}(e);!function(e){o(e,"wait"),o(e,"success")}(e);if(!("success"===t&&!n))if("none"===t)o(e,"error");else{var s=e.attr(x+t)||"[]",a=i?function(e,t){var i=JSON.parse(t).concat([e]);return JSON.stringify(i)}(i,s):"";e.attr(x+t,a)}}function o(e,t){e.removeAttr(x+t)}function l(e){var t=n(e,"displayfield");return void 0===t?e:(0,g.default)("#"+t)}function c(e){return e.attr("data-"+C)}function d(e,t){t.preventDefault(),e.one(O,function(){e.trigger("submit")})}function u(e){return function(e){var t=-1!==e.indexOf(S),i=-1!==e.indexOf(T),n=-1!==e.indexOf(A);return t?S:i?T:n?A:E}(function(e){return g.default.map(e,function(e){return c((0,g.default)(e))})}(e.find("."+R)))}function h(e,t){var i="[data-"+C+"="+t+"]";return e.find(i)}var f={exports:{}},p=f.exports;Object.defineProperty(p,"__esModule",{value:!0});var g=e(__ce09c80fb835cb76cda82f0f0d4a1ea3);__2220bade9e250c8271d410ece8bca942,__9dcc477dc72b9fd8eed74f58663d0f22;var v=e(__fb114d9b531e09c60f5fdf12262b017c),b=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&(t[i]=e[i]);return t.default=e,t}(__3632ac12e0e2db0a58ef6348743599e5),m=e(__2bc1a6edbc312083fbf11f878f780e28),_=e(__7a6521db1039cb333e437aa8031353cf),w=e(__b2f7b02e2b6317ef4485dba3603d3a09),y="aui-validation-",x="data-aui-notification-",C="aui-validation-state",S="invalid",E="valid",A="validating",T="unvalidated",R="_aui-form-validation-initialised",O="_aui-internal-field-state-changed";(0,g.default)(document).on("submit",function(e){var t=e.target,i=(0,g.default)(t),n=u(i);if(n===T)d(i,e),function(e){h(e,T).each(function(e,t){I.validate((0,g.default)(t))})}(i);else if(n===A)d(i,e);else if(n===S)e.preventDefault(),function(e){h(e,S).first().focus()}(i);else if(n===E){var s=g.default.Event("aui-valid-submit");i.trigger(s);s.isDefaultPrevented()&&e.preventDefault()}});var I={register:w.default.register,validate:function(e){i(e=(0,g.default)(e))}};return(0,_.default)("data-aui-validation-field",{attached:function(e){e.form&&e.form.setAttribute("novalidate","novalidate");t((0,g.default)(e)),_.default.init(e)},type:_.default.type.ATTRIBUTE}),(0,v.default)("aui/form-validation",I),(0,m.default)("formValidation",I),p.default=I,f.exports=p.default,f.exports}.call(this),("undefined"==typeof window?global:window).__e4e1727c26af0a5037c104d27c13c775=function(){var e={exports:{}},t=e.exports;Object.defineProperty(t,"__esModule",{value:!0});return t.default={INPUT_SUFFIX:"-input"},e.exports=t.default,e.exports}.call(this),("undefined"==typeof window?global:window).__67491bb3bce20d8f91c94f98d7717c17=function(){function e(e){return e&&e.__esModule?e:{default:e}}function t(e){return e.querySelector("label")}var i={exports:{}},n=i.exports;Object.defineProperty(n,"__esModule",{value:!0});var s=e(__7a6521db1039cb333e437aa8031353cf),a=e(__f33ac309b94c246736966ea50a11b323),r=e(__502b59e357a07cdf19c6edc9cbaa8719),o=__e4e1727c26af0a5037c104d27c13c775,l=(0,s.default)("aui-label",{template:(0,a.default)("<label><content></content></label>"),created:function(e){e._label=t(e)},attached:function(e){(0,r.default)(e).attributeExists("for")},attributes:{for:function(e,i){e.hasAttribute("for")?t(e).setAttribute("for",""+i.newValue+o.INPUT_SUFFIX):t(e).removeAttribute("for")},form:function(e,i){e.hasAttribute("form")?t(e).setAttribute("form",i.newValue):t(e).removeAttribute("form")}},prototype:{get disabled(){return this.hasAttribute("disabled")},set disabled(e){e?this.setAttribute("disabled",""):this.removeAttribute("disabled")}},events:{click:function(e,t){e.disabled&&t.preventDefault()}}});return n.default=l,i.exports=n.default,i.exports}.call(this),("undefined"==typeof window?global:window).__3e1b3de594cf0afb3ff875e48b0a233b=function(){function e(e){return e&&e.__esModule?e:{default:e}}function t(e,t,i){(0,p.recomputeStyle)(e),e.css("width",100*i+"%"),t.attr("data-value",i)}function i(e,i,n){var s=n.currentProgress,a=n.value,r=(0,u.default)(e),o=(0,u.default)(i);"number"==typeof a&&a<=1&&a>=0&&(o.trigger(_,[s,a]),(0,g.supportsCssTransition)()?(r.one(w,function(){o.trigger(m,[s,a])}),t(r,o,a)):(t(r,o,a),o.trigger(m,[s,a])))}function n(e){var t=(0,u.default)(e).first(),i=t.children(".aui-progress-indicator-value");t.removeAttr("data-value"),(0,p.recomputeStyle)(t),i.css("width","")}function s(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1;return Number(parseFloat(e).toFixed(t))}function a(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},i=t.val,n=t.max,a=h.default.isNumber(n)?n:e.max,r=h.default.isNumber(i)?i:e.val,o=a>0?a:y.max,l=Math.max(0,Math.min(r,o)),c=s(l/o,6);return{max:o,val:l,valAsFraction:c,valAsPercent:s(100*c,2),indeterminate:e.indeterminate}}function r(e){var t=e._data,s=t.indeterminate,a=t.val,r=t.valAsFraction,o=t.max,l=e.querySelector(".aui-progress-indicator"),c=l.getAttribute("data-value");s?(l.removeAttribute("aria-valuenow"),n(l)):(l.setAttribute("aria-valuenow",a),l.setAttribute("aria-valuemax",o),i(l.querySelector(".aui-progress-indicator-value"),l,{currentProgress:c,value:r}))}function o(e){return h.default.isNumber(e)&&h.default.isFinite(e)&&!h.default.isNaN(e)}function l(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1,i=parseFloat(e);return o(i)?i:t}var c={exports:{}},d=c.exports;Object.defineProperty(d,"__esModule",{value:!0});var u=e(__ce09c80fb835cb76cda82f0f0d4a1ea3),h=e(__b1cf2cc50089fc912c34f79ef20e8bdf),f=e(__5a3c87f5b72a38db529a9ff0d14effa3),p=__027703b7d07563496ecfdc7f4681e189,g=__be1f1b4b3186372d22f47d92fb181b20,v=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&(t[i]=e[i]);return t.default=e,t}(__3632ac12e0e2db0a58ef6348743599e5),b=e(__2bc1a6edbc312083fbf11f878f780e28),m="aui-progress-indicator-after-update",_="aui-progress-indicator-before-update",w="transitionend webkitTransitionEnd",y={indeterminate:!1,max:1,val:0,valAsFraction:0,valAsPercent:0};(0,f.default)("aui-progressbar",{template:function(e){e._data.max=l(e.getAttribute("max"),y.max),e._data.val=l(e.getAttribute("value"),y.val),e._data.indeterminate=e.hasAttribute("indeterminate"),e._data=a(e._data);var t=e._data,i=t.val,n=t.valAsFraction,s=t.valAsPercent,r=t.max,o=e._data.indeterminate?"":'data-value="'+n+'"';e.innerHTML='<div class="aui-progress-indicator"\n '+o+'\n role="progressbar"\n aria-valuemin="0"\n aria-valuenow="'+i+'"\n aria-valuemax="'+r+'"\n tabindex="0"\n >\n <span class="aui-progress-indicator-value" style="width: '+s+'%"></span>\n </div>'},attached:function(e){r(e)},attributes:{indeterminate:{created:function(e){e.indeterminate=!0},removed:function(e){e.indeterminate=!1}},value:function(e,t){e.value=l(t.newValue,t.oldValue)},max:function(e,t){e.max=l(t.newValue,t.oldValue)}},prototype:{get _data(){return this.__data||(this._data=h.default.defaults({},y))},set _data(e){return this.__data=e},get indeterminate(){return this._data.indeterminate},set indeterminate(e){this._data.indeterminate=!!e,r(this)},get value(){return this._data.val},set value(e){if(!o(e))return!1;var t=s(e,6);this._data=a(this._data,{val:t}),r(this)},get max(){return this._data.max},set max(e){if(!o(e))return!1;var t=s(e,6);this._data=a(this._data,{max:t}),r(this)}}});var x={update:v.fn(function(e,t){var n=(0,u.default)(e).first(),s=n.children(".aui-progress-indicator-value"),a=n.attr("data-value"),r=parseFloat(a)||0;if(!a||r!==t)return!a&&s.css("width",0),i(s,n,{currentProgress:r,value:t}),n},"AJS.progressBars.update",{sinceVersion:"7.7.0",extraInfo:"Use the <aui-progressbar> web component instead"}),setIndeterminate:v.fn(n,"AJS.progressBars.setIndeterminate",{sinceVersion:"7.7.0",extraInfo:"Use the <aui-progressbar> web component instead"})};return(0,b.default)("progressBars",x),d.default=x,c.exports=d.default,c.exports}.call(this),("undefined"==typeof window?global:window).__b7ca42fac3745278a328ef1d08cf6b90=function(){var e={exports:{}},t=e.exports,i={module:e,exports:t,underscore:__95b499c4fb094f4ca0e999afdb27d59b,jquery:__ce09c80fb835cb76cda82f0f0d4a1ea3,underscore:__95b499c4fb094f4ca0e999afdb27d59b,jquery:__ce09c80fb835cb76cda82f0f0d4a1ea3},n=function(n){return function(s,a,r){var o,l,c=("undefined"==typeof window?global:window).define;r=[r,a,s].filter(function(e){return"function"==typeof e})[0],a=[a,s,[]].filter(Array.isArray)[0],l=typeof(o=r.apply(null,a.map(function(e){return i[e]}))),"function"==typeof c&&c("string"==typeof s?s:n,a,r),"string"===l?o=String(o):"number"===l?o=Number(o):"boolean"===l&&(o=Boolean(o)),void 0!==o&&(t=e.exports=o)}}("__b7ca42fac3745278a328ef1d08cf6b90");return n.amd=!0,function(e,i){if("function"==typeof n&&n.amd)n(["underscore","jquery","exports"],function(t,n,s){e.Backbone=i(e,s,t,n)});else if(void 0!==t){var s,a=__95b499c4fb094f4ca0e999afdb27d59b;try{s=__ce09c80fb835cb76cda82f0f0d4a1ea3}catch(e){}i(e,t,a,s)}else e.Backbone=i(e,{},e._,e.jQuery||e.Zepto||e.ender||e.$)}(this,function(e,t,i,n){var s=(e=this).Backbone,a=[],r=a.push,o=a.slice,l=a.splice;t.VERSION="1.0.0",t.$=n,t.noConflict=function(){return e.Backbone=s,this},t.emulateHTTP=!1,t.emulateJSON=!1;var c=t.Events={on:function(e,t,i){if(!u(this,"on",e,[t,i])||!t)return this;this._events||(this._events={});return(this._events[e]||(this._events[e]=[])).push({callback:t,context:i,ctx:i||this}),this},once:function(e,t,n){if(!u(this,"once",e,[t,n])||!t)return this;var s=this,a=i.once(function(){s.off(e,a),t.apply(this,arguments)});return a._callback=t,this.on(e,a,n)},off:function(e,t,n){var s,a,r,o,l,c,d,h;if(!this._events||!u(this,"off",e,[t,n]))return this;if(!e&&!t&&!n)return this._events={},this;for(l=0,c=(o=e?[e]:i.keys(this._events)).length;l<c;l++)if(e=o[l],r=this._events[e]){if(this._events[e]=s=[],t||n)for(d=0,h=r.length;d<h;d++)a=r[d],(t&&t!==a.callback&&t!==a.callback._callback||n&&n!==a.context)&&s.push(a);s.length||delete this._events[e]}return this},trigger:function(e){if(!this._events)return this;var t=o.call(arguments,1);if(!u(this,"trigger",e,t))return this;var i=this._events[e],n=this._events.all;return i&&h(i,t),n&&h(n,arguments),this},stopListening:function(e,t,i){var n=this._listeners;if(!n)return this;var s=!t&&!i;"object"==typeof t&&(i=this),e&&((n={})[e._listenerId]=e);for(var a in n)n[a].off(t,i,this),s&&delete this._listeners[a];return this}},d=/\s+/,u=function(e,t,i,n){if(!i)return!0;if("object"==typeof i){for(var s in i)e[t].apply(e,[s,i[s]].concat(n));return!1}if(d.test(i)){for(var a=i.split(d),r=0,o=a.length;r<o;r++)e[t].apply(e,[a[r]].concat(n));return!1}return!0},h=function(e,t){var i,n=-1,s=e.length,a=t[0],r=t[1],o=t[2];switch(t.length){case 0:for(;++n<s;)(i=e[n]).callback.call(i.ctx);return;case 1:for(;++n<s;)(i=e[n]).callback.call(i.ctx,a);return;case 2:for(;++n<s;)(i=e[n]).callback.call(i.ctx,a,r);return;case 3:for(;++n<s;)(i=e[n]).callback.call(i.ctx,a,r,o);return;default:for(;++n<s;)(i=e[n]).callback.apply(i.ctx,t)}};i.each({listenTo:"on",listenToOnce:"once"},function(e,t){c[t]=function(t,n,s){return(this._listeners||(this._listeners={}))[t._listenerId||(t._listenerId=i.uniqueId("l"))]=t,"object"==typeof n&&(s=this),t[e](n,s,this),this}}),c.bind=c.on,c.unbind=c.off,i.extend(t,c);var f=t.Model=function(e,t){var n,s=e||{};t||(t={}),this.cid=i.uniqueId("c"),this.attributes={},i.extend(this,i.pick(t,p)),t.parse&&(s=this.parse(s,t)||{}),(n=i.result(this,"defaults"))&&(s=i.defaults({},s,n)),this.set(s,t),this.changed={},this.initialize.apply(this,arguments)},p=["url","urlRoot","collection"];i.extend(f.prototype,c,{changed:null,validationError:null,idAttribute:"id",initialize:function(){},toJSON:function(e){return i.clone(this.attributes)},sync:function(){return t.sync.apply(this,arguments)},get:function(e){return this.attributes[e]},escape:function(e){return i.escape(this.get(e))},has:function(e){return null!=this.get(e)},set:function(e,t,n){var s,a,r,o,l,c,d,u;if(null==e)return this;if("object"==typeof e?(a=e,n=t):(a={})[e]=t,n||(n={}),!this._validate(a,n))return!1;r=n.unset,l=n.silent,o=[],c=this._changing,this._changing=!0,c||(this._previousAttributes=i.clone(this.attributes),this.changed={}),u=this.attributes,d=this._previousAttributes,this.idAttribute in a&&(this.id=a[this.idAttribute]);for(s in a)t=a[s],i.isEqual(u[s],t)||o.push(s),i.isEqual(d[s],t)?delete this.changed[s]:this.changed[s]=t,r?delete u[s]:u[s]=t;if(!l){o.length&&(this._pending=!0);for(var h=0,f=o.length;h<f;h++)this.trigger("change:"+o[h],this,u[o[h]],n)}if(c)return this;if(!l)for(;this._pending;)this._pending=!1,this.trigger("change",this,n);return this._pending=!1,this._changing=!1,this},unset:function(e,t){return this.set(e,void 0,i.extend({},t,{unset:!0}))},clear:function(e){var t={};for(var n in this.attributes)t[n]=void 0;return this.set(t,i.extend({},e,{unset:!0}))},hasChanged:function(e){return null==e?!i.isEmpty(this.changed):i.has(this.changed,e)},changedAttributes:function(e){if(!e)return!!this.hasChanged()&&i.clone(this.changed);var t,n=!1,s=this._changing?this._previousAttributes:this.attributes;for(var a in e)i.isEqual(s[a],t=e[a])||((n||(n={}))[a]=t);return n},previous:function(e){return null!=e&&this._previousAttributes?this._previousAttributes[e]:null},previousAttributes:function(){return i.clone(this._previousAttributes)},fetch:function(e){void 0===(e=e?i.clone(e):{}).parse&&(e.parse=!0);var t=this,n=e.success;return e.success=function(i){if(!t.set(t.parse(i,e),e))return!1;n&&n(t,i,e),t.trigger("sync",t,i,e)},N(this,e),this.sync("read",this,e)},save:function(e,t,n){var s,a,r,o=this.attributes;if(null==e||"object"==typeof e?(s=e,n=t):(s={})[e]=t,s&&(!n||!n.wait)&&!this.set(s,n))return!1;if(n=i.extend({validate:!0},n),!this._validate(s,n))return!1;s&&n.wait&&(this.attributes=i.extend({},o,s)),void 0===n.parse&&(n.parse=!0);var l=this,c=n.success;return n.success=function(e){l.attributes=o;var t=l.parse(e,n);if(n.wait&&(t=i.extend(s||{},t)),i.isObject(t)&&!l.set(t,n))return!1;c&&c(l,e,n),l.trigger("sync",l,e,n)},N(this,n),"patch"===(a=this.isNew()?"create":n.patch?"patch":"update")&&(n.attrs=s),r=this.sync(a,this,n),s&&n.wait&&(this.attributes=o),r},destroy:function(e){var t=this,n=(e=e?i.clone(e):{}).success,s=function(){t.trigger("destroy",t,t.collection,e)};if(e.success=function(i){(e.wait||t.isNew())&&s(),n&&n(t,i,e),t.isNew()||t.trigger("sync",t,i,e)},this.isNew())return e.success(),!1;N(this,e);var a=this.sync("delete",this,e);return e.wait||s(),a},url:function(){var e=i.result(this,"urlRoot")||i.result(this.collection,"url")||D();return this.isNew()?e:e+("/"===e.charAt(e.length-1)?"":"/")+encodeURIComponent(this.id)},parse:function(e,t){return e},clone:function(){return new this.constructor(this.attributes)},isNew:function(){return null==this.id},isValid:function(e){return this._validate({},i.extend(e||{},{validate:!0}))},_validate:function(e,t){if(!t.validate||!this.validate)return!0;e=i.extend({},this.attributes,e);var n=this.validationError=this.validate(e,t)||null;return!n||(this.trigger("invalid",this,n,i.extend(t||{},{validationError:n})),!1)}});i.each(["keys","values","pairs","invert","pick","omit"],function(e){f.prototype[e]=function(){var t=o.call(arguments);return t.unshift(this.attributes),i[e].apply(i,t)}});var g=t.Collection=function(e,t){t||(t={}),t.url&&(this.url=t.url),t.model&&(this.model=t.model),void 0!==t.comparator&&(this.comparator=t.comparator),this._reset(),this.initialize.apply(this,arguments),e&&this.reset(e,i.extend({silent:!0},t))},v={add:!0,remove:!0,merge:!0},b={add:!0,merge:!1,remove:!1};i.extend(g.prototype,c,{model:f,initialize:function(){},toJSON:function(e){return this.map(function(t){return t.toJSON(e)})},sync:function(){return t.sync.apply(this,arguments)},add:function(e,t){return this.set(e,i.defaults(t||{},b))},remove:function(e,t){e=i.isArray(e)?e.slice():[e],t||(t={});var n,s,a,r;for(n=0,s=e.length;n<s;n++)(r=this.get(e[n]))&&(delete this._byId[r.id],delete this._byId[r.cid],a=this.indexOf(r),this.models.splice(a,1),this.length--,t.silent||(t.index=a,r.trigger("remove",r,this,t)),this._removeReference(r));return this},set:function(e,t){(t=i.defaults(t||{},v)).parse&&(e=this.parse(e,t)),i.isArray(e)||(e=e?[e]:[]);var n,s,a,o,c,d=t.at,u=this.comparator&&null==d&&!1!==t.sort,h=i.isString(this.comparator)?this.comparator:null,f=[],p=[],g={};for(n=0,s=e.length;n<s;n++)(a=this._prepareModel(e[n],t))&&((o=this.get(a))?(t.remove&&(g[o.cid]=!0),t.merge&&(o.set(a.attributes,t),u&&!c&&o.hasChanged(h)&&(c=!0))):t.add&&(f.push(a),a.on("all",this._onModelEvent,this),this._byId[a.cid]=a,null!=a.id&&(this._byId[a.id]=a)));if(t.remove){for(n=0,s=this.length;n<s;++n)g[(a=this.models[n]).cid]||p.push(a);p.length&&this.remove(p,t)}if(f.length&&(u&&(c=!0),this.length+=f.length,null!=d?l.apply(this.models,[d,0].concat(f)):r.apply(this.models,f)),c&&this.sort({silent:!0}),t.silent)return this;for(n=0,s=f.length;n<s;n++)(a=f[n]).trigger("add",a,this,t);return c&&this.trigger("sort",this,t),this},reset:function(e,t){t||(t={});for(var n=0,s=this.models.length;n<s;n++)this._removeReference(this.models[n]);return t.previousModels=this.models,this._reset(),this.add(e,i.extend({silent:!0},t)),t.silent||this.trigger("reset",this,t),this},push:function(e,t){return e=this._prepareModel(e,t),this.add(e,i.extend({at:this.length},t)),e},pop:function(e){var t=this.at(this.length-1);return this.remove(t,e),t},unshift:function(e,t){return e=this._prepareModel(e,t),this.add(e,i.extend({at:0},t)),e},shift:function(e){var t=this.at(0);return this.remove(t,e),t},slice:function(e,t){return this.models.slice(e,t)},get:function(e){if(null!=e)return this._byId[null!=e.id?e.id:e.cid||e]},at:function(e){return this.models[e]},where:function(e,t){return i.isEmpty(e)?t?void 0:[]:this[t?"find":"filter"](function(t){for(var i in e)if(e[i]!==t.get(i))return!1;return!0})},findWhere:function(e){return this.where(e,!0)},sort:function(e){if(!this.comparator)throw new Error("Cannot sort a set without a comparator");return e||(e={}),i.isString(this.comparator)||1===this.comparator.length?this.models=this.sortBy(this.comparator,this):this.models.sort(i.bind(this.comparator,this)),e.silent||this.trigger("sort",this,e),this},sortedIndex:function(e,t,n){t||(t=this.comparator);var s=i.isFunction(t)?t:function(e){return e.get(t)};return i.sortedIndex(this.models,e,s,n)},pluck:function(e){return i.invoke(this.models,"get",e)},fetch:function(e){void 0===(e=e?i.clone(e):{}).parse&&(e.parse=!0);var t=e.success,n=this;return e.success=function(i){var s=e.reset?"reset":"set";n[s](i,e),t&&t(n,i,e),n.trigger("sync",n,i,e)},N(this,e),this.sync("read",this,e)},create:function(e,t){if(t=t?i.clone(t):{},!(e=this._prepareModel(e,t)))return!1;t.wait||this.add(e,t);var n=this,s=t.success;return t.success=function(e,t,i){i.wait&&n.add(e,i),s&&s(e,t,i)},e.save(null,t),e},parse:function(e,t){return e},clone:function(){return new this.constructor(this.models)},_reset:function(){this.length=0,this.models=[],this._byId={}},_prepareModel:function(e,t){if(e instanceof f)return e.collection||(e.collection=this),e;t||(t={}),t.collection=this;var i=new this.model(e,t);return i._validate(e,t)?i:(this.trigger("invalid",this,e,t),!1)},_removeReference:function(e){this===e.collection&&delete e.collection,e.off("all",this._onModelEvent,this)},_onModelEvent:function(e,t,i,n){("add"!==e&&"remove"!==e||i===this)&&("destroy"===e&&this.remove(t,n),t&&e==="change:"+t.idAttribute&&(delete this._byId[t.previous(t.idAttribute)],null!=t.id&&(this._byId[t.id]=t)),this.trigger.apply(this,arguments))}});i.each(["forEach","each","map","collect","reduce","foldl","inject","reduceRight","foldr","find","detect","filter","select","reject","every","all","some","any","include","contains","invoke","max","min","toArray","size","first","head","take","initial","rest","tail","drop","last","without","indexOf","shuffle","lastIndexOf","isEmpty","chain"],function(e){g.prototype[e]=function(){var t=o.call(arguments);return t.unshift(this.models),i[e].apply(i,t)}});i.each(["groupBy","countBy","sortBy"],function(e){g.prototype[e]=function(t,n){var s=i.isFunction(t)?t:function(e){return e.get(t)};return i[e](this.models,s,n)}});var m=t.View=function(e){this.cid=i.uniqueId("view"),this._configure(e||{}),this._ensureElement(),this.initialize.apply(this,arguments),this.delegateEvents()},_=/^(\S+)\s*(.*)$/,w=["model","collection","el","id","attributes","className","tagName","events"];i.extend(m.prototype,c,{tagName:"div",$:function(e){return this.$el.find(e)},initialize:function(){},render:function(){return this},remove:function(){return this.$el.remove(),this.stopListening(),this},setElement:function(e,i){return this.$el&&this.undelegateEvents(),this.$el=e instanceof t.$?e:t.$(e),this.el=this.$el[0],!1!==i&&this.delegateEvents(),this},delegateEvents:function(e){if(!e&&!(e=i.result(this,"events")))return this;this.undelegateEvents();for(var t in e){var n=e[t];if(i.isFunction(n)||(n=this[e[t]]),n){var s=t.match(_),a=s[1],r=s[2];n=i.bind(n,this),a+=".delegateEvents"+this.cid,""===r?this.$el.on(a,n):this.$el.on(a,r,n)}}return this},undelegateEvents:function(){return this.$el.off(".delegateEvents"+this.cid),this},_configure:function(e){this.options&&(e=i.extend({},i.result(this,"options"),e)),i.extend(this,i.pick(e,w)),this.options=e},_ensureElement:function(){if(this.el)this.setElement(i.result(this,"el"),!1);else{var e=i.extend({},i.result(this,"attributes"));this.id&&(e.id=i.result(this,"id")),this.className&&(e.class=i.result(this,"className"));var n=t.$("<"+i.result(this,"tagName")+">").attr(e);this.setElement(n,!1)}}}),t.sync=function(e,n,s){var a=y[e];i.defaults(s||(s={}),{emulateHTTP:t.emulateHTTP,emulateJSON:t.emulateJSON});var r={type:a,dataType:"json"};if(s.url||(r.url=i.result(n,"url")||D()),null!=s.data||!n||"create"!==e&&"update"!==e&&"patch"!==e||(r.contentType="application/json",r.data=JSON.stringify(s.attrs||n.toJSON(s))),s.emulateJSON&&(r.contentType="application/x-www-form-urlencoded",r.data=r.data?{model:r.data}:{}),s.emulateHTTP&&("PUT"===a||"DELETE"===a||"PATCH"===a)){r.type="POST",s.emulateJSON&&(r.data._method=a);var o=s.beforeSend;s.beforeSend=function(e){if(e.setRequestHeader("X-HTTP-Method-Override",a),o)return o.apply(this,arguments)}}"GET"===r.type||s.emulateJSON||(r.processData=!1),"PATCH"!==r.type||!window.ActiveXObject||window.external&&window.external.msActiveXFilteringEnabled||(r.xhr=function(){return new ActiveXObject("Microsoft.XMLHTTP")});var l=s.xhr=t.ajax(i.extend(r,s));return n.trigger("request",n,l,s),l};var y={create:"POST",update:"PUT",patch:"PATCH",delete:"DELETE",read:"GET"};t.ajax=function(){return t.$.ajax.apply(t.$,arguments)};var x=t.Router=function(e){e||(e={}),e.routes&&(this.routes=e.routes),this._bindRoutes(),this.initialize.apply(this,arguments)},C=/\((.*?)\)/g,S=/(\(\?)?:\w+/g,E=/\*\w+/g,A=/[\-{}\[\]+?.,\\\^$|#\s]/g;i.extend(x.prototype,c,{initialize:function(){},route:function(e,n,s){i.isRegExp(e)||(e=this._routeToRegExp(e)),i.isFunction(n)&&(s=n,n=""),s||(s=this[n]);var a=this;return t.history.route(e,function(i){var r=a._extractParameters(e,i);s&&s.apply(a,r),a.trigger.apply(a,["route:"+n].concat(r)),a.trigger("route",n,r),t.history.trigger("route",a,n,r)}),this},navigate:function(e,i){return t.history.navigate(e,i),this},_bindRoutes:function(){if(this.routes){this.routes=i.result(this,"routes");for(var e,t=i.keys(this.routes);null!=(e=t.pop());)this.route(e,this.routes[e])}},_routeToRegExp:function(e){return e=e.replace(A,"\\$&").replace(C,"(?:$1)?").replace(S,function(e,t){return t?e:"([^/]+)"}).replace(E,"(.*?)"),new RegExp("^"+e+"$")},_extractParameters:function(e,t){var n=e.exec(t).slice(1);return i.map(n,function(e){return e?decodeURIComponent(e):null})}});var T=t.History=function(){this.handlers=[],i.bindAll(this,"checkUrl"),"undefined"!=typeof window&&(this.location=window.location,this.history=window.history)},R=/^[#\/]|\s+$/g,O=/^\/+|\/+$/g,I=/msie [\w.]+/,$=/\/$/;T.started=!1,i.extend(T.prototype,c,{interval:50,getHash:function(e){var t=(e||this).location.href.match(/#(.*)$/);return t?t[1]:""},getFragment:function(e,t){if(null==e)if(this._hasPushState||!this._wantsHashChange||t){e=this.location.pathname;var i=this.root.replace($,"");e.indexOf(i)||(e=e.substr(i.length))}else e=this.getHash();return e.replace(R,"")},start:function(e){if(T.started)throw new Error("Backbone.history has already been started");T.started=!0,this.options=i.extend({},{root:"/"},this.options,e),this.root=this.options.root,this._wantsHashChange=!1!==this.options.hashChange,this._wantsPushState=!!this.options.pushState,this._hasPushState=!!(this.options.pushState&&this.history&&this.history.pushState);var n=this.getFragment(),s=document.documentMode,a=I.exec(navigator.userAgent.toLowerCase())&&(!s||s<=7);this.root=("/"+this.root+"/").replace(O,"/"),a&&this._wantsHashChange&&(this.iframe=t.$('<iframe src="javascript:0" tabindex="-1" />').hide().appendTo("body")[0].contentWindow,this.navigate(n)),this._hasPushState?t.$(window).on("popstate",this.checkUrl):this._wantsHashChange&&"onhashchange"in window&&!a?t.$(window).on("hashchange",this.checkUrl):this._wantsHashChange&&(this._checkUrlInterval=setInterval(this.checkUrl,this.interval)),this.fragment=n;var r=this.location,o=r.pathname.replace(/[^\/]$/,"$&/")===this.root;return this._wantsHashChange&&this._wantsPushState&&!this._hasPushState&&!o?(this.fragment=this.getFragment(null,!0),this.location.replace(this.root+this.location.search+"#"+this.fragment),!0):(this._wantsPushState&&this._hasPushState&&o&&r.hash&&(this.fragment=this.getHash().replace(R,""),this.history.replaceState({},document.title,this.root+this.fragment+r.search)),this.options.silent?void 0:this.loadUrl())},stop:function(){t.$(window).off("popstate",this.checkUrl).off("hashchange",this.checkUrl),clearInterval(this._checkUrlInterval),T.started=!1},route:function(e,t){this.handlers.unshift({route:e,callback:t})},checkUrl:function(e){var t=this.getFragment();if(t===this.fragment&&this.iframe&&(t=this.getFragment(this.getHash(this.iframe))),t===this.fragment)return!1;this.iframe&&this.navigate(t),this.loadUrl()||this.loadUrl(this.getHash())},loadUrl:function(e){var t=this.fragment=this.getFragment(e);return i.any(this.handlers,function(e){if(e.route.test(t))return e.callback(t),!0})},navigate:function(e,t){if(!T.started)return!1;if(t&&!0!==t||(t={trigger:t}),e=this.getFragment(e||""),this.fragment!==e){this.fragment=e;var i=this.root+e;if(this._hasPushState)this.history[t.replace?"replaceState":"pushState"]({},document.title,i);else{if(!this._wantsHashChange)return this.location.assign(i);this._updateHash(this.location,e,t.replace),this.iframe&&e!==this.getFragment(this.getHash(this.iframe))&&(t.replace||this.iframe.document.open().close(),this._updateHash(this.iframe.location,e,t.replace))}t.trigger&&this.loadUrl(e)}},_updateHash:function(e,t,i){if(i){var n=e.href.replace(/(javascript:|#).*$/,"");e.replace(n+"#"+t)}else e.hash="#"+t}}),t.history=new T;f.extend=g.extend=x.extend=m.extend=T.extend=function(e,t){var n,s=this;n=e&&i.has(e,"constructor")?e.constructor:function(){return s.apply(this,arguments)},i.extend(n,s,t);var a=function(){this.constructor=n};return a.prototype=s.prototype,n.prototype=new a,e&&i.extend(n.prototype,e),n.__super__=s.prototype,n};var D=function(){throw new Error('A "url" property or function must be specified')},N=function(e,t){var i=t.error;t.error=function(n){i&&i(e,n,t),e.trigger("error",e,n,t)}};return t}),e.exports}.call(this),("undefined"==typeof window?global:window).__17d4d8fa88c848020c0d2d72ad26d4a1=function(){function e(e){return e&&e.__esModule?e:{default:e}}var t={exports:{}},i=t.exports;Object.defineProperty(i,"__esModule",{value:!0});e(__b1cf2cc50089fc912c34f79ef20e8bdf);var n=e(__b7ca42fac3745278a328ef1d08cf6b90);return window.Backbone||(window.Backbone=n.default),i.default=window.Backbone,t.exports=i.default,t.exports}.call(this),("undefined"==typeof window?global:window).__c290b536f781d38fd8310af686be11a9=function(){function e(e){return e&&e.__esModule?e:{default:e}}var t={exports:{}},i=t.exports;Object.defineProperty(i,"__esModule",{value:!0});var n=e(__b1cf2cc50089fc912c34f79ef20e8bdf),s=e(__17d4d8fa88c848020c0d2d72ad26d4a1),a=e(__2bc1a6edbc312083fbf11f878f780e28),r=s.default.Collection.extend({initialize:function(e,t){t||(t={}),t.matcher&&(this.matcher=t.matcher),t.model&&(this.model=t.model),this._idAttribute=(new this.model).idAttribute,this._maxResults=t.maxResults||5,this._queryData=t.queryData||{},this._queryParamKey=t.queryParamKey||"q",this._queryEndpoint=t.queryEndpoint||"",this.value=null,this.queryCache={},this.activeQueryCount=0,n.default.bindAll(this,"query","respond")},url:function(){return this._queryEndpoint},query:function(e){var t,i,n=this;this.value=e,i=this.getFilteredResults(e),this.respond(e,i),e&&this._queryEndpoint&&!this.hasQueryCache(e)&&this.shouldGetMoreResults(i)&&(t=this.fetch(e),this.activeQueryCount++,this.trigger("activity",{activity:!0}),t.always(function(){n.activeQueryCount--,n.trigger("activity",{activity:!!n.activeQueryCount})}),t.done(function(t,i,s){n.addQueryCache(e,t,s)}),t.done(function(){e=n.value,i=n.getFilteredResults(e),n.respond(e,i)}))},getQueryData:function(e){var t=n.default.isFunction(this._queryData)?this._queryData(e):this._queryData,i=n.default.extend({},t);return i[this._queryParamKey]=e,i},fetch:function(e){var t={add:!0,update:!0,remove:!1,data:this.getQueryData(e)};return s.default.Collection.prototype.fetch.call(this,t)},respond:function(e,t){return this.trigger("respond",{query:e,results:t}),t},matcher:function(e,t){},getFilteredResults:function(e){var t=[];return e?(t=this.filter(function(t){return!!this.matcher(t,e)},this),this._maxResults&&(t=n.default.first(t,this._maxResults)),t):t},addQueryCache:function(e,t,i){var s=this.queryCache,a=this.parse(t,i);s[e]=n.default.pluck(a,this._idAttribute)},hasQueryCache:function(e){return this.queryCache.hasOwnProperty(e)},findQueryCache:function(e){return this.queryCache[e]},shouldGetMoreResults:function(e){return e.length<this._maxResults},setMaxResults:function(e){this._maxResults=e,this.value&&this.respond(this.value,this.getFilteredResults(this.value))}});return(0,a.default)("ProgressiveDataSet",r),i.default=r,t.exports=i.default,t.exports}.call(this),("undefined"==typeof window?global:window).__a18bab3d6582ccd64c009f3a6d64da2a=function(){function e(e){return e&&e.__esModule?e:{default:e}}var t={exports:{}},i=t.exports;Object.defineProperty(i,"__esModule",{value:!0});var n=e(__b1cf2cc50089fc912c34f79ef20e8bdf),s=e(__17d4d8fa88c848020c0d2d72ad26d4a1),a=e(__2bc1a6edbc312083fbf11f878f780e28),r=s.default.View.extend({initialize:function(){n.default.bindAll(this,"changed","val"),this._lastValue=this.val(),this.$el.bind("keyup focus",this.changed)},val:function(){return this.$el.val.apply(this.$el,arguments)},changed:function(){this._lastValue!==this.val()&&(this.trigger("change",this.val()),this._lastValue=this.val())}});return(0,a.default)("QueryInput",r),i.default=r,t.exports=i.default,t.exports}.call(this),("undefined"==typeof window?global:window).__96bb89abb319fdb98c02f6f1a0f2c116=function(){var e={exports:{}},t=e.exports;return Object.defineProperty(t,"__esModule",{value:!0}),t.default={NO_VALUE:"aui-restfultable-editable-no-value",NO_ENTRIES:"aui-restfultable-no-entires",RESTFUL_TABLE:"aui-restfultable",ROW:"aui-restfultable-row",READ_ONLY:"aui-restfultable-readonly",ACTIVE:"aui-restfultable-active",ALLOW_HOVER:"aui-restfultable-allowhover",FOCUSED:"aui-restfultable-focused",MOVEABLE:"aui-restfultable-movable",DISABLED:"aui-restfultable-disabled",SUBMIT:"aui-restfultable-submit",CANCEL:"aui-restfultable-cancel",EDIT_ROW:"aui-restfultable-editrow",CREATE:"aui-restfultable-create",DRAG_HANDLE:"aui-restfultable-draghandle",ORDER:"aui-restfultable-order",EDITABLE:"aui-restfultable-editable",ERROR:"error",DELETE:"aui-restfultable-delete",LOADING:"loading"},e.exports=t.default,e.exports}.call(this),("undefined"==typeof window?global:window).__881ed4b34bd4c45ccac42b8c297c98be=function(){var e={exports:{}},t=e.exports;Object.defineProperty(t,"__esModule",{value:!0});var i=function(e){return e&&e.__esModule?e:{default:e}}(__17d4d8fa88c848020c0d2d72ad26d4a1);return t.default=i.default.View,e.exports=t.default,e.exports}.call(this),("undefined"==typeof window?global:window).__009efd1873a6682a4417af50d22eb9a6=function(){var e={exports:{}},t=e.exports;Object.defineProperty(t,"__esModule",{value:!0});var i=function(e){return e&&e.__esModule?e:{default:e}}(__17d4d8fa88c848020c0d2d72ad26d4a1);return t.default=i.default.View,e.exports=t.default,e.exports}.call(this),("undefined"==typeof window?global:window).__a4beddeb67a6b4c45e1d297501421239=function(){var e={exports:{}},t=e.exports;Object.defineProperty(t,"__esModule",{value:!0});var i=function(e){return e&&e.__esModule?e:{default:e}}(__17d4d8fa88c848020c0d2d72ad26d4a1);return t.default=i.default.View,e.exports=t.default,e.exports}.call(this),("undefined"==typeof window?global:window).__b8b5fd184a816824b11f64dae056c122=function(){var e={exports:{}},t=e.exports;return Object.defineProperty(t,"__esModule",{value:!0}),t.default={ENABLED_SUBMIT:"enabledSubmit",ROW_VIEW:"RestfulTable_Row_View"},e.exports=t.default,e.exports}.call(this),("undefined"==typeof window?global:window).__abd75c4c8dad9910e332b82ab3f41425=function(){var e={};return jQuery.fn.serializeObject=function(){var e={};return this.find(":input:not(:button):not(:submit):not(:radio):not('select[multiple]')").each(function(){""!==this.name&&(null===this.value&&(this.value=""),e[this.name]=this.value.match(/^(tru|fals)e$/i)?"true"==this.value.toLowerCase():this.value)}),this.find("input:radio:checked").each(function(){e[this.name]=this.value}),this.find("select[multiple]").each(function(){var t=jQuery(this),i=t.val();t.data("aui-ss")?e[this.name]=i?i[0]:"":e[this.name]=null!==i?i:[]}),e},e}.call(this),("undefined"==typeof window?global:window).__41d71c452273f14b6e1fe9628c22f922=function(){var e={exports:{}},t=e.exports;return Object.defineProperty(t,"__esModule",{value:!0}),t.default={REORDER_SUCCESS:"RestfulTable.reorderSuccess",ROW_ADDED:"RestfulTable.rowAdded",ROW_REMOVED:"RestfulTable.rowRemoved",EDIT_ROW:"RestfulTable.switchedToEditMode",SERVER_ERROR:"RestfulTable.serverError",CREATED:"created",UPDATED:"updated",FOCUS:"focus",BLUR:"blur",SUBMIT:"submit",SAVE:"save",MODAL:"modal",MODELESS:"modeless",CANCEL:"cancel",CONTENT_REFRESHED:"contentRefreshed",RENDER:"render",FINISHED_EDITING:"finishedEditing",VALIDATION_ERROR:"validationError",SUBMIT_STARTED:"submitStarted",SUBMIT_FINISHED:"submitFinished",INITIALIZED:"initialized",ROW_INITIALIZED:"rowInitialized",ROW_EDIT:"editRow"},e.exports=t.default,e.exports}.call(this),("undefined"==typeof window?global:window).__38f919b442268d2272d4f529e41f4617=function(){var e={exports:{}},t=e.exports;return Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(){return'<span class="aui-restfultable-throbber"></span>'},e.exports=t.default,e.exports}.call(this),("undefined"==typeof window?global:window).__8ce02b7c8478eb1458d251ad651cd807=function(){function e(e){return e&&e.__esModule?e:{default:e}}var t={exports:{}},i=t.exports;Object.defineProperty(i,"__esModule",{value:!0});var n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},s=e(__ce09c80fb835cb76cda82f0f0d4a1ea3);__abd75c4c8dad9910e332b82ab3f41425;var a=e(__17d4d8fa88c848020c0d2d72ad26d4a1),r=e(__96bb89abb319fdb98c02f6f1a0f2c116),o=e(__b8b5fd184a816824b11f64dae056c122),l=e(__41d71c452273f14b6e1fe9628c22f922),c=(e(__6e5c1a3f5afadc2fe31a54c52b7091ab),e(__38f919b442268d2272d4f529e41f4617)),d=-1!==navigator.userAgent.toLowerCase().indexOf("firefox");return i.default=a.default.View.extend({tagName:"tr",events:{focusin:"_focus",click:"_focus",keyup:"_handleKeyUpEvent"},initialize:function(e){this.$el=(0,s.default)(this.el),this._event=l.default,this.classNames=r.default,this.dataKeys=o.default,this.columns=e.columns,this.isCreateRow=e.isCreateRow,this.allowReorder=e.allowReorder,this.events["click ."+this.classNames.CANCEL]="_cancel",this.delegateEvents(),e.isUpdateMode?this.isUpdateMode=!0:(this._modelClass=e.model,this.model=new this._modelClass),this.fieldFocusSelector=e.fieldFocusSelector,this.bind(this._event.CANCEL,function(){this.disabled=!0}).bind(this._event.SAVE,function(e){this.disabled||this.submit(e)}).bind(this._event.FOCUS,function(e){this.focus(e)}).bind(this._event.BLUR,function(){this.$el.removeClass(this.classNames.FOCUSED),this.disable()}).bind(this._event.SUBMIT_STARTED,function(){this._submitStarted()}).bind(this._event.SUBMIT_FINISHED,function(){this._submitFinished()})},defaultColumnRenderer:function(e){return!1!==e.allowEdit?(0,s.default)("<input type='text' />").addClass("text").attr({name:e.name,value:e.value}):e.value?document.createTextNode(e.value):void 0},renderDragHandle:function(){return'<span class="'+this.classNames.DRAG_HANDLE+'"></span></td>'},_handleKeyUpEvent:function(e){27===e.keyCode&&this.trigger(this._event.CANCEL)},_cancel:function(e){return this.trigger(this._event.CANCEL),e.preventDefault(),this},_submitStarted:function(){return this.submitting=!0,this.showLoading().disable().delegateEvents({}),this},_submitFinished:function(){return this.submitting=!1,this.hideLoading().enable().delegateEvents(this.events),this},_focus:function(e){return this.hasFocus()||this.trigger(this._event.FOCUS,e.target.name),this},hasFocus:function(){return this.$el.hasClass(this.classNames.FOCUSED)},focus:function(e){var t,i;return this.enable(),t=e?this.$el.find(this.fieldFocusSelector(e)):0===(i=this.$el.find(this.classNames.ERROR+":first")).length?this.$el.find(":input:text:first"):i.parent().find(":input"),this.$el.addClass(this.classNames.FOCUSED),t.focus().trigger("select"),this},disable:function(){var e,t;return d&&(t=this.$el.find(":submit")).length&&(e=(0,s.default)("<input type='submit' class='"+this.classNames.SUBMIT+"' />").addClass(t.attr("class")).val(t.val()).data(this.dataKeys.ENABLED_SUBMIT,t),t.replaceWith(e)),this.$el.addClass(this.classNames.DISABLED).find(":submit").attr("disabled","disabled"),this},enable:function(){var e,t;return d&&(t=(e=this.$el.find(this.classNames.SUBMIT)).data(this.dataKeys.ENABLED_SUBMIT))&&e.length&&e.replaceWith(t),this.$el.removeClass(this.classNames.DISABLED).find(":submit").removeAttr("disabled"),this},showLoading:function(){return this.$el.addClass(this.classNames.LOADING),this},hideLoading:function(){return this.$el.removeClass(this.classNames.LOADING),this},hasUpdates:function(){return!!this.mapSubmitParams(this.serializeObject())},serializeObject:function(){var e=this.$el;return e.serializeObject?e.serializeObject():e.serialize()},mapSubmitParams:function(e){return this.model.changedAttributes(e)},submit:function(e){var t,i=this;if(document.activeElement!==window&&(0,s.default)(document.activeElement).blur(),this.isUpdateMode){if(!(t=this.mapSubmitParams(this.serializeObject())))return i.trigger(i._event.CANCEL)}else this.model.clear(),t=this.mapSubmitParams(this.serializeObject());return this.trigger(this._event.SUBMIT_STARTED),this.model.save(t,{success:function(){i.isUpdateMode?i.trigger(i._event.UPDATED,i.model,e):(i.trigger(i._event.CREATED,i.model.toJSON()),i.model=new i._modelClass,i.render({errors:{},values:{}}),i.trigger(i._event.FOCUS)),i.trigger(i._event.SUBMIT_FINISHED)},error:function(e,t,n){400===n.status&&(i.renderErrors(t.errors),i.trigger(i._event.VALIDATION_ERROR,t.errors)),i.trigger(i._event.SUBMIT_FINISHED)},silent:!0}),this},renderError:function(e,t){return(0,s.default)("<div />").attr("data-field",e).addClass(this.classNames.ERROR).text(t)},renderErrors:function(e){var t=this;return this.$("."+this.classNames.ERROR).remove(),e&&s.default.each(e,function(e,i){t.$el.find("[name='"+e+"']").closest("td").append(t.renderError(e,i))}),this},render:function(e){var t=this;return this.$el.empty(),this.allowReorder&&(0,s.default)('<td class="'+this.classNames.ORDER+'" />').append(this.renderDragHandle()).appendTo(t.$el),s.default.each(this.columns,function(i,a){var r,o,l=e.values[a.id],c=[{name:a.id,value:l,allowEdit:a.allowEdit},e.values,t.model];l&&t.$el.attr("data-"+a.id,l),r=t.isCreateRow&&a.createView?new a.createView({model:t.model}).render(c[0]):a.editView?new a.editView({model:t.model}).render(c[0]):t.defaultColumnRenderer.apply(t,c),o=(0,s.default)("<td />"),"object"===(void 0===r?"undefined":n(r))&&r.done?r.done(function(e){o.append(e)}):o.append(r),a.styleClass&&o.addClass(a.styleClass),o.appendTo(t.$el)}),this.$el.append(this.renderOperations(e.update,e.values)).addClass(this.classNames.ROW+" "+this.classNames.EDIT_ROW),this.trigger(this._event.RENDER,this.$el,e.values),this.$el.trigger(this._event.CONTENT_REFRESHED,[this.$el]),this},renderOperations:function(e){var t=(0,s.default)('<td class="aui-restfultable-operations" />');return e?t.append((0,s.default)('<input class="aui-button" type="submit" />').attr({accesskey:this.submitAccessKey,value:AJS.I18n.getText("aui.words.update")})).append((0,s.default)('<a class="aui-button aui-button-link" href="#" />').addClass(this.classNames.CANCEL).text(AJS.I18n.getText("aui.words.cancel")).attr({accesskey:this.cancelAccessKey})):t.append((0,s.default)('<input class="aui-button" type="submit" />').attr({accesskey:this.submitAccessKey,value:AJS.I18n.getText("aui.words.add")})),t.add((0,s.default)('<td class="aui-restfultable-status" />').append((0,c.default)()))}}),t.exports=i.default,t.exports}.call(this),("undefined"==typeof window?global:window).__168c6e410224c17255ac33d720986055=function(){function e(e){return e&&e.__esModule?e:{default:e}}var t={exports:{}},i=t.exports;Object.defineProperty(i,"__esModule",{value:!0});var n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},s=e(__ce09c80fb835cb76cda82f0f0d4a1ea3),a=__6be2e725a5b9c6c7f3fc5f513760dedf,r=e(__b1cf2cc50089fc912c34f79ef20e8bdf),o=e(__17d4d8fa88c848020c0d2d72ad26d4a1),l=e(__41d71c452273f14b6e1fe9628c22f922),c=o.default.Model.extend({sync:function(e,t,i){var n=this,s=i.error;return i.error=function(e){n._serverErrorHandler(e,this),s&&s.apply(this,arguments)},o.default.sync.apply(o.default,arguments)},save:function(e,t){var i,n=this,a=(t=t||{}).error,r=t.success;t.error=function(e,t){var i=s.default.parseJSON(t.responseText||t.data);a&&a.call(n,n,i,t)},this.isNew()?o.default.Model.prototype.save.call(this,e,t):e&&((i=new(c.extend({url:this.url()}))({id:this.id})).save=o.default.Model.prototype.save,t.success=function(e,t){n.clear().set(e.toJSON()),r&&r.call(n,n,t)},i.save(e,t))},destroy:function(e){e=e||{};var t,i=this,n=this.url();return e.data&&(t=s.default.param(e.data)),""!==t&&(n=n+"?"+t),s.default.ajax({url:n,type:"DELETE",dataType:"json",contentType:"application/json",success:function(t){i.collection&&i.collection.remove(i),e.success&&e.success.call(i,t)},error:function(t){i._serverErrorHandler(t,this),e.error&&e.error.call(i,t)}}),this},changedAttributes:function(e){var t={},i=this.toJSON();if(s.default.each(e,function(e,a){i[e]?i[e]&&i[e]!==a&&("object"===(void 0===a?"undefined":n(a))?r.default.isEqual(a,i[e])||(t[e]=a):t[e]=a):"string"==typeof a?""!==s.default.trim(a)&&(t[e]=a):s.default.isArray(a)?0!==a.length&&(t[e]=a):t[e]=a}),!r.default.isEmpty(t))return this.addExpand(t),t},addExpand:function(e){},_serverErrorHandler:function(e,t){var i;400!==e.status&&(i=s.default.parseJSON(e.responseText||e.data),(0,a.triggerEvtForInst)(l.default.SERVER_ERROR,this,[i,e,t]))},fetch:function(e){e=e||{},this.clear(),o.default.Model.prototype.fetch.call(this,e)}});return i.default=c,t.exports=i.default,t.exports}.call(this),("undefined"==typeof window?global:window).__fdd30a4b110cb35a9ad1510499e0c255=function(){function e(e){return e&&e.__esModule?e:{default:e}}var t={exports:{}},i=t.exports;Object.defineProperty(i,"__esModule",{value:!0});var n=e(__ce09c80fb835cb76cda82f0f0d4a1ea3),s=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&(t[i]=e[i]);return t.default=e,t}(__8d48c0ed3868ba86704d96ecb0e58e88),a=e(__17d4d8fa88c848020c0d2d72ad26d4a1),r=e(__96bb89abb319fdb98c02f6f1a0f2c116),o=e(__b8b5fd184a816824b11f64dae056c122),l=e(__41d71c452273f14b6e1fe9628c22f922),c=(e(__6e5c1a3f5afadc2fe31a54c52b7091ab),e(__38f919b442268d2272d4f529e41f4617));return i.default=a.default.View.extend({tagName:"tr",events:{"click .aui-restfultable-editable":"edit"},initialize:function(e){if(e=e||{},this._event=l.default,this.classNames=r.default,this.dataKeys=o.default,this.columns=e.columns,this.allowEdit=e.allowEdit,this.allowDelete=e.allowDelete,!this.events["click .aui-restfultable-editable"])throw new Error("It appears you have overridden the events property. To add events you will need to usea work around. https://github.com/documentcloud/backbone/issues/244");this.index=e.index||0,this.deleteConfirmation=e.deleteConfirmation,this.allowReorder=e.allowReorder,this.$el=(0,n.default)(this.el),this.bind(this._event.CANCEL,function(){this.disabled=!0}).bind(this._event.FOCUS,function(e){this.focus(e)}).bind(this._event.BLUR,function(){this.unfocus()}).bind(this._event.MODAL,function(){this.$el.addClass(this.classNames.ACTIVE)}).bind(this._event.MODELESS,function(){this.$el.removeClass(this.classNames.ACTIVE)})},renderDragHandle:function(){return'<span class="'+this.classNames.DRAG_HANDLE+'"></span></td>'},defaultColumnRenderer:function(e){if(e.value)return document.createTextNode(e.value.toString())},sync:function(e){var t=this;return this.model.addExpand(e),this.showLoading(),this.model.save(e,{success:function(){t.hideLoading().render(),t.trigger(t._event.UPDATED)},error:function(){t.hideLoading()}}),this},refresh:function(e,t){var i=this;return this.showLoading(),this.model.fetch({success:function(){i.hideLoading().render(),e&&e.apply(this,arguments)},error:function(){i.hideLoading(),t&&t.apply(this,arguments)}}),this},hasFocus:function(){return this.$el.hasClass(this.classNames.FOCUSED)},focus:function(){return(0,n.default)(this.el).addClass(this.classNames.FOCUSED),this},unfocus:function(){return(0,n.default)(this.el).removeClass(this.classNames.FOCUSED),this},showLoading:function(){return this.$el.addClass(this.classNames.LOADING),this},hideLoading:function(){return this.$el.removeClass(this.classNames.LOADING),this},edit:function(e){var t;return t=(0,n.default)(e.target).is("."+this.classNames.EDITABLE)?(0,n.default)(e.target).attr("data-field-name"):(0,n.default)(e.target).closest("."+this.classNames.EDITABLE).attr("data-field-name"),this.trigger(this._event.ROW_EDIT,t),this},renderOperations:function(){var e=this;if(!1!==this.allowDelete)return(0,n.default)("<a href='#' class='aui-button' />").addClass(this.classNames.DELETE).text(AJS.I18n.getText("aui.words.delete")).click(function(t){t.preventDefault(),e.destroy()})},destroy:function(){if(this.deleteConfirmation){var e=s.popup(400,200,"delete-entity-"+this.model.get("id"));e.element.html(this.deleteConfirmation(this.model.toJSON())),e.show(),e.element.find(".cancel").click(function(){e.hide()}),e.element.find("form").submit(function(t){e.hide(),this.model.destroy(),t.preventDefault()}.bind(this))}else this.model.destroy()},render:function(){var e=this,t=this.model.toJSON(),i=(0,n.default)("<td class='aui-restfultable-operations' />").append(this.renderOperations({},t)),s=(0,n.default)("<td class='aui-restfultable-status' />").append((0,c.default)());return this.$el.removeClass(this.classNames.DISABLED+" "+this.classNames.FOCUSED+" "+this.classNames.LOADING+" "+this.classNames.EDIT_ROW).addClass(this.classNames.READ_ONLY).empty(),this.allowReorder&&(0,n.default)('<td class="'+this.classNames.ORDER+'" />').append(this.renderDragHandle()).appendTo(e.$el),this.$el.attr("data-id",this.model.id),n.default.each(this.columns,function(i,s){var a,r=(0,n.default)("<td />"),o=t[s.id],l=s.fieldName||s.id,c=[{name:l,value:o,allowEdit:s.allowEdit},t,e.model];if(o&&e.$el.attr("data-"+s.id,o),a=s.readView?new s.readView({model:e.model}).render(c[0]):e.defaultColumnRenderer.apply(e,c),!1!==e.allowEdit&&!1!==s.allowEdit){var d=(0,n.default)("<span />").addClass(e.classNames.EDITABLE).append('<span class="aui-icon aui-icon-small aui-iconfont-edit"></span>').append(a).attr("data-field-name",l);r=(0,n.default)("<td />").append(d).appendTo(e.$el),a&&""!=n.default.trim(a)||(r.addClass(e.classNames.NO_VALUE),d.html((0,n.default)("<em />").text(this.emptyText||AJS.I18n.getText("aui.enter.value"))))}else r.append(a);s.styleClass&&r.addClass(s.styleClass),r.appendTo(e.$el)}),this.$el.append(i).append(s).addClass(this.classNames.ROW+" "+this.classNames.READ_ONLY),this.trigger(this._event.RENDER,this.$el,t),this.$el.trigger(this._event.CONTENT_REFRESHED,[this.$el]),this}}),t.exports=i.default,t.exports}.call(this),("undefined"==typeof window?global:window).__b4462e3facf827e782aaf2b356c13a33=function(){function e(e){return e&&e.__esModule?e:{default:e}}function t(e,t){(0,a.default)(document).trigger(e,t)}function i(e,i,n){(0,a.default)(i).trigger(e,n),t(e,n),i.id&&t(i.id+"_"+e,n)}var n={exports:{}},s=n.exports;Object.defineProperty(s,"__esModule",{value:!0});var a=e(__ce09c80fb835cb76cda82f0f0d4a1ea3),r=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&(t[i]=e[i]);return t.default=e,t}(__5cedb2bf0c96530c8ee1c2fdf05590cb),o=e(__17d4d8fa88c848020c0d2d72ad26d4a1),l=e(__96bb89abb319fdb98c02f6f1a0f2c116),c=e(__881ed4b34bd4c45ccac42b8c297c98be),d=e(__009efd1873a6682a4417af50d22eb9a6),u=e(__a4beddeb67a6b4c45e1d297501421239),h=e(__b8b5fd184a816824b11f64dae056c122),f=e(__8ce02b7c8478eb1458d251ad651cd807),p=e(__168c6e410224c17255ac33d720986055),g=e(__41d71c452273f14b6e1fe9628c22f922),v=e(__2bc1a6edbc312083fbf11f878f780e28),b=(e(__6e5c1a3f5afadc2fe31a54c52b7091ab),e(__fdd30a4b110cb35a9ad1510499e0c255)),m=e(__38f919b442268d2272d4f529e41f4617),_=o.default.View.extend({initialize:function(e){var t=this;if(t.options=a.default.extend(!0,t._getDefaultOptions(e),e),t.id=this.options.id,t._event=g.default,t.classNames=l.default,t.dataKeys=h.default,this.$table=(0,a.default)(e.el).addClass(this.classNames.RESTFUL_TABLE).addClass(this.classNames.ALLOW_HOVER).addClass("aui").addClass(t.classNames.LOADING),this.$table.wrapAll("<form class='aui' action='#' />"),this.$thead=(0,a.default)("<thead/>"),this.$theadRow=(0,a.default)("<tr />").appendTo(this.$thead),this.$tbody=(0,a.default)("<tbody/>"),!this.$table.length)throw new Error("RestfulTable: Init failed! The table you have specified ["+this.$table.selector+"] cannot be found.");if(!this.options.columns)throw new Error("RestfulTable: Init failed! You haven't provided any columns to render.");this.showGlobalLoading(),this.options.columns.forEach(function(e){var i=a.default.isFunction(e.header)?e.header():e.header;void 0===i&&(r.warn("You have not specified [header] for column ["+e.id+"]. Using id for now..."),i=e.id),t.$theadRow.append("<th>"+i+"</th>")}),t.$theadRow.append("<th></th><th></th>"),this._models=this._createCollection(),this._rowClass=this.options.views.row,this.editRows=[],this.$table.closest("form").submit(function(e){t.focusedRow&&t.focusedRow.trigger(t._event.SAVE),e.preventDefault()}),this.options.allowReorder&&(this.$theadRow.prepend("<th />"),this.$tbody.sortable({handle:"."+this.classNames.DRAG_HANDLE,helper:function(e,i){var n=(0,a.default)("<div/>").attr("class",i.attr("class")).addClass(t.classNames.MOVEABLE);return i.children().each(function(e){var t=(0,a.default)(this),i=parseInt(0+t.css("border-left-width"),10),s=parseInt(0+t.css("border-right-width"),10),r=t[0].clientWidth+i+s;n.append((0,a.default)("<div/>").html(t.html()).attr("class",t.attr("class")).width(r))}),n=(0,a.default)("<div class='aui-restfultable-readonly'/>").append(n),n.css({left:i.offset().left}),n.appendTo(document.body),n},start:function(e,i){var n=i.helper[0].clientHeight,s=i.placeholder.find("td");i.item.addClass(t.classNames.MOVEABLE).children().each(function(e){(0,a.default)(this).width(s.eq(e).width())});var r='<td colspan="'+t.getColumnCount()+'">&nbsp;</td>';i.placeholder.html(r).css({height:n,visibility:"visible"}),t.getRowFromElement(i.item[0]).trigger(t._event.MODAL)},stop:function(e,i){(0,a.default)(i.item[0]).is(":visible")&&(i.item.removeClass(t.classNames.MOVEABLE).children().attr("style",""),i.placeholder.removeClass(t.classNames.ROW),t.getRowFromElement(i.item[0]).trigger(t._event.MODELESS))},update:function(e,i){var n={row:t.getRowFromElement(i.item[0]),item:i.item,nextItem:i.item.next(),prevItem:i.item.prev()};t.move(n)},axis:"y",delay:0,containment:"document",cursor:"move",scroll:!0,zIndex:8e3}),this.$tbody.bind("selectstart mousedown",function(e){return!(0,a.default)(e.target).is("."+t.classNames.DRAG_HANDLE)})),!1!==this.options.allowCreate&&(this._createRow=new this.options.views.editRow({columns:this.options.columns,isCreateRow:!0,model:this.options.model.extend({url:function(){return t.options.resources.self}}),cancelAccessKey:this.options.cancelAccessKey,submitAccessKey:this.options.submitAccessKey,allowReorder:this.options.allowReorder,fieldFocusSelector:this.options.fieldFocusSelector}).bind(this._event.CREATED,function(e){void 0==t.options.addPosition&&"bottom"===t.options.createPosition||"bottom"===t.options.addPosition?t.addRow(e):t.addRow(e,0)}).bind(this._event.VALIDATION_ERROR,function(){this.trigger(t._event.FOCUS)}).render({errors:{},values:{}}),this.$create=(0,a.default)('<tbody class="'+this.classNames.CREATE+'" />').append(this._createRow.el),this._applyFocusCoordinator(this._createRow),this._createRow.trigger(this._event.FOCUS)),this._models.bind("remove",function(e){t.getRows().forEach(function(i){i.model===e&&(i.hasFocus()&&t._createRow&&t._createRow.trigger(t._event.FOCUS),t.removeRow(i))})}),this.fetchInitialResources()},fetchInitialResources:function(){var e=this;a.default.isFunction(this.options.resources.all)?this.options.resources.all(function(t){e.populate(t)}):a.default.get(this.options.resources.all,function(t){e.populate(t)})},move:function(e){var t=this,n=function(e){if(e.length){return{after:t.getRowFromElement(e).model.url()}}return{position:"First"}};if(e.row){var s=n(t.options.reverseOrder?e.nextItem:e.prevItem);a.default.ajax({url:e.row.model.url()+"/move",type:"POST",dataType:"json",contentType:"application/json",data:JSON.stringify(s),complete:function(){e.row.hideLoading()},success:function(e){i(t._event.REORDER_SUCCESS,t,[e])},error:function(e){var n=a.default.parseJSON(e.responseText||e.data);i(t._event.SERVER_ERROR,t,[n,e,this])}}),e.row.showLoading()}},_createCollection:function(){var e=this;return new(this.options.Collection.extend({sort:function(t){if(t||(t={}),!this.comparator)throw new Error("Cannot sort a set without a comparator");return this.tableRows=e.getRows(),this.models=this.sortBy(this.comparator),this.tableRows=void 0,t.silent||this.trigger("refresh",this,t),this},remove:function(t,i){return this.tableRows=e.getRows(),o.default.Collection.prototype.remove.apply(this,arguments),this.tableRows=void 0,this}}))([],{comparator:function(t){var i;return(void 0!==this.tableRows?this.tableRows:e.getRows()).some(function(e,n){if(e.model.id===t.id)return i=n,!0}),i}})},populate:function(e){this.options.reverseOrder&&e.reverse(),this.hideGlobalLoading(),e&&e.length?(this._models.reset([],{silent:!0}),this.renderRows(e),this.isEmpty()&&this.showNoEntriesMsg()):this.showNoEntriesMsg(),this.$table.append(this.$thead),"bottom"===this.options.createPosition?this.$table.append(this.$tbody).append(this.$create):this.$table.append(this.$create).append(this.$tbody),this.$table.removeClass(this.classNames.LOADING).trigger(this._event.INITIALIZED,[this]),i(this._event.INITIALIZED,this,[this]),this.options.autoFocus&&this.$table.find(":input:text:first").focus()},showGlobalLoading:function(){return this.$loading||(this.$loading=(0,a.default)('<div class="aui-restfultable-init">'+(0,m.default)()+'<span class="aui-restfultable-loading">'+this.options.loadingMsg+"</span></div>")),this.$loading.is(":visible")||this.$loading.insertAfter(this.$table),this},hideGlobalLoading:function(){return this.$loading&&this.$loading.remove(),this},addRow:function(e,t){var n,s;if(!e.id)throw new Error("RestfulTable.addRow: to add a row values object must contain an id. Maybe you are not returning it from your restend point?Recieved:"+JSON.stringify(e));return s=new this.options.model(e),n=this._renderRow(s,t),this._models.add(s),this.removeNoEntriesMsg(),i(this._event.ROW_ADDED,this,[n,this]),this},removeRow:function(e){this._models.remove(e.model),e.remove(),this.isEmpty()&&this.showNoEntriesMsg(),i(this._event.ROW_REMOVED,this,[e,this])},isEmpty:function(){return 0===this._models.length},getModels:function(){return this._models},getTable:function(){return this.$table},getTableBody:function(){return this.$tbody},getCreateRow:function(){return this._createRow},getColumnCount:function(){var e=2;return this.allowReorder&&++e,this.options.columns.length+e},getRowFromElement:function(e){return(0,a.default)(e).data(this.dataKeys.ROW_VIEW)},showNoEntriesMsg:function(){return this.$noEntries&&this.$noEntries.remove(),this.$noEntries=(0,a.default)("<tr>").addClass(this.classNames.NO_ENTRIES).append((0,a.default)("<td>").attr("colspan",this.getColumnCount()).text(this.options.noEntriesMsg)).appendTo(this.$tbody),this},removeNoEntriesMsg:function(){return this.$noEntries&&this._models.length>0&&this.$noEntries.remove(),this},getRows:function(){var e=this,t=[];return this.$tbody.find("."+this.classNames.READ_ONLY).each(function(){var i=(0,a.default)(this).data(e.dataKeys.ROW_VIEW);i&&t.push(i)}),t},_renderRow:function(e,t){var n,s,a=this,r=this.$tbody.find("."+this.classNames.READ_ONLY);return s=new this._rowClass({model:e,columns:this.options.columns,allowEdit:this.options.allowEdit,allowDelete:this.options.allowDelete,allowReorder:this.options.allowReorder,deleteConfirmation:this.options.deleteConfirmation}),this.removeNoEntriesMsg(),s.bind(this._event.ROW_EDIT,function(e){i(this._event.EDIT_ROW,{},[this,a]),a.edit(this,e)}),n=s.render().$el,-1!==t&&("number"==typeof t&&0!==r.length?n.insertBefore(r[t]):this.$tbody.append(n)),n.data(this.dataKeys.ROW_VIEW,s),s.bind(this._event.MODAL,function(){a.$table.removeClass(a.classNames.ALLOW_HOVER),a.$tbody.sortable("disable"),a.getRows().forEach(function(e){a.isRowBeingEdited(e)||e.delegateEvents({})})}),s.bind(this._event.MODELESS,function(){a.$table.addClass(a.classNames.ALLOW_HOVER),a.$tbody.sortable("enable"),a.getRows().forEach(function(e){a.isRowBeingEdited(e)||e.delegateEvents()})}),this._applyFocusCoordinator(s),this.trigger(this._event.ROW_INITIALIZED,s),s},isRowBeingEdited:function(e){var t=!1;return this.editRows.some(function(i){if(i.el===e.el)return t=!0,!0}),t},_applyFocusCoordinator:function(e){var t=this;return e.hasFocusBound||(e.hasFocusBound=!0,e.bind(this._event.FOCUS,function(){t.focusedRow&&t.focusedRow!==e&&t.focusedRow.trigger(t._event.BLUR),t.focusedRow=e,e instanceof b.default&&t._createRow&&t._createRow.enable()})),this},_removeEditRow:function(e){var t=a.default.inArray(e,this.editRows);return this.editRows.splice(t,1),this},_shiftFocusAfterEdit:function(){return this.editRows.length>0?this.editRows[this.editRows.length-1].trigger(this._event.FOCUS):this._createRow&&this._createRow.trigger(this._event.FOCUS),this},_saveEditRowOnBlur:function(){return this.editRows.length<=1},dismissEditRows:function(){this.editRows.forEach(function(e){e.hasUpdates()||e.trigger(this._event.FINISHED_EDITING)},this)},edit:function(e,t){var i=this,n=new this.options.views.editRow({el:e.el,columns:this.options.columns,isUpdateMode:!0,allowReorder:this.options.allowReorder,fieldFocusSelector:this.options.fieldFocusSelector,model:e.model,cancelAccessKey:this.options.cancelAccessKey,submitAccessKey:this.options.submitAccessKey}),s=e.model.toJSON();return s.update=!0,n.render({errors:{},update:!0,values:s}).bind(i._event.UPDATED,function(t,n){i._removeEditRow(this),this.unbind(),e.render().delegateEvents(),e.trigger(i._event.UPDATED),!1!==n&&i._shiftFocusAfterEdit()}).bind(i._event.VALIDATION_ERROR,function(){this.trigger(i._event.FOCUS)}).bind(i._event.FINISHED_EDITING,function(){i._removeEditRow(this),e.render().delegateEvents(),this.unbind()}).bind(i._event.CANCEL,function(){i._removeEditRow(this),this.unbind(),e.render().delegateEvents(),i._shiftFocusAfterEdit()}).bind(i._event.BLUR,function(){i.dismissEditRows(),i._saveEditRowOnBlur()&&this.trigger(i._event.SAVE,!1)}),this._applyFocusCoordinator(n),n.trigger(i._event.FOCUS,t),i._createRow&&i._createRow.disable(),this.editRows.push(n),n},renderRows:function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[],i=this._models.comparator,n=[];this._models.comparator=void 0;var s=t.map(function(t){var i=new e.options.model(t);return n.push(e._renderRow(i,-1).el),i});return this._models.add(s,{silent:!0}),this._models.comparator=i,this.removeNoEntriesMsg(),this.$tbody.append(n),this},_getDefaultOptions:function(e){return{model:e.model||p.default,allowEdit:!0,views:{editRow:f.default,row:b.default},Collection:o.default.Collection.extend({url:e.resources.self,model:e.model||p.default}),allowReorder:!1,fieldFocusSelector:function(e){return":input[name="+e+"], #"+e},loadingMsg:e.loadingMsg||AJS.I18n.getText("aui.words.loading")}}});return _.ClassNames=l.default,_.CustomCreateView=c.default,_.CustomEditView=d.default,_.CustomReadView=u.default,_.DataKeys=h.default,_.EditRow=f.default,_.EntryModel=p.default,_.Events=g.default,_.Row=b.default,_.Throbber=m.default,(0,v.default)("RestfulTable",_),s.default=_,n.exports=s.default,n.exports}.call(this),("undefined"==typeof window?global:window).__35286d201a93212a1713fc328bf98228=function(){function e(e){return e&&e.__esModule?e:{default:e}}var t={exports:{}},i=t.exports;Object.defineProperty(i,"__esModule",{value:!0});var n=e(__17d4d8fa88c848020c0d2d72ad26d4a1),s=e(__2bc1a6edbc312083fbf11f878f780e28),a=n.default.Model.extend({initialize:function(e){this.set("active",null,{silent:!0}),this.collection=new n.default.Collection,this.collection.bind("reset",this.setActive,this),this.source=e.source,this.source.bind("respond",this.process,this)},url:!1,process:function(e){this.set("query",e.query),this.collection.reset(e.results),this.set("length",e.results.length),this.trigger("update",this)},setActive:function(){var e=!(arguments[0]instanceof n.default.Collection)&&arguments[0],t=e?this.collection.get(e):this.collection.first();return this.set("active",t||null),this.get("active")},next:function(){var e=(this.collection.indexOf(this.get("active"))+1)%this.get("length"),t=this.collection.at(e);return this.setActive(t&&t.id)},prev:function(){var e=this.collection.indexOf(this.get("active")),t=(0===e?this.get("length"):e)-1,i=this.collection.at(t);return this.setActive(i&&i.id)},each:function(){return this.collection.each.apply(this.collection,arguments)}});return(0,s.default)("ResultSet",a),i.default=a,t.exports=i.default,t.exports}.call(this),("undefined"==typeof window?global:window).__c9b0155d89690eb9270f409840e010bf=function(){function e(e){return e&&e.__esModule?e:{default:e}}var t={exports:{}},i=t.exports;Object.defineProperty(i,"__esModule",{value:!0});var n=e(__b1cf2cc50089fc912c34f79ef20e8bdf),s=e(__17d4d8fa88c848020c0d2d72ad26d4a1),a=e(__2bc1a6edbc312083fbf11f878f780e28),r=e(__35286d201a93212a1713fc328bf98228),o=s.default.View.extend({events:{"click [data-id]":"setSelection"},initialize:function(e){if(this.model||(this.model=new r.default({source:e.source})),!(this.model instanceof r.default))throw new Error("model must be set to a ResultSet");this.model.bind("update",this.process,this),this.render=n.default.wrap(this.render,function(e){this.trigger("rendering"),e.apply(this,arguments),this.trigger("rendered")})},process:function(){this._shouldShow(this.model.get("query"))&&this.show()},render:function(){var e=s.default.$("<ul/>");return this.model.each(function(t){s.default.$("<li/>").attr("data-id",t.id).html(this.renderItem(t)).appendTo(e)},this),this.$el.html(e),this},renderItem:function(){},setSelection:function(e){var t=e.target.getAttribute("data-id"),i=this.model.setActive(t);this.trigger("selected",i)},show:function(){this.lastQuery=this.model.get("query"),this._hiddenQuery=null,this.render(),this.$el.show()},hide:function(){this.$el.hide(),this._hiddenQuery=this.lastQuery},size:function(){return this.model.get("length")},_shouldShow:function(e){return""===e||!(this._hiddenQuery&&this._hiddenQuery===e)}});return(0,a.default)("ResultsList",o),i.default=o,t.exports=i.default,t.exports}.call(this),("undefined"==typeof window?global:window).__7c3570a4f1c32f8d75931e52dbc74e57=function(){function e(e){return e&&e.__esModule?e:{default:e}}var t={exports:{}},i=t.exports;Object.defineProperty(i,"__esModule",{value:!0});var n=e(__7a6521db1039cb333e437aa8031353cf),s=e(__8a65566313033cce957bceeae5143a1a);return i.default=(0,n.default)("aui-option",{created:function(e){Object.defineProperty(e,"value",{get:function(){return e.getAttribute("value")||(0,s.default)(this.textContent)},set:function(t){e.setAttribute("value",t)}})},prototype:{serialize:function(){var e={};return this.hasAttribute("img-src")&&(e["img-src"]=this.getAttribute("img-src")),e.value=this.value,e.label=(0,s.default)(this.textContent),e}}}),t.exports=i.default,t.exports}.call(this),("undefined"==typeof window?global:window).__1cff5371449a662c0a7be7041d4b68b7=function(){var e={exports:{}},t=e.exports;Object.defineProperty(t,"__esModule",{value:!0});var i=function(e){return e&&e.__esModule?e:{default:e}}(__17d4d8fa88c848020c0d2d72ad26d4a1);return t.default=i.default.Model.extend({idAttribute:"label",getLabel:function(){return this.get("label")||this.get("value")}}),e.exports=t.default,e.exports}.call(this),("undefined"==typeof window?global:window).__d013a973f9737525d80a39c3b9f3006e=function(){function e(){this._suggestions=[],this._activeIndex=-1}var t={exports:{}},i=t.exports;return Object.defineProperty(i,"__esModule",{value:!0}),e.prototype={onChange:function(){},onHighlightChange:function(){},get:function(e){return this._suggestions[e]},set:function(e){var t=this._suggestions;return this._suggestions=e||[],this.onChange(t),this},getNumberOfResults:function(){return this._suggestions.length},setHighlighted:function(e){if(e)for(var t=0;t<this._suggestions.length;t++)this._suggestions[t].id===e.id&&this.highlight(t);return this},highlight:function(e){return this._activeIndex=e,this.onHighlightChange(),this},highlightPrevious:function(){var e=this._activeIndex,t=0===e?e:e-1;return this.highlight(t),this},highlightNext:function(){var e=this._activeIndex,t=e===this._suggestions.length-1?e:e+1;return this.highlight(t),this},highlighted:function(){return this.get(this._activeIndex)},highlightedIndex:function(){return this._activeIndex}},i.default=e,t.exports=i.default,t.exports}.call(this),("undefined"==typeof window?global:window).__de81bfb18da60d7a2ac3ffb6a6da48fd=function(){function e(e){return e&&e.__esModule?e:{default:e}}function t(e,t){return e+"-"+t}function i(e,t){this.el=e,this.anchor=t}function n(e){(0,r.default)(e).find(".aui-select-active").removeClass("aui-select-active")}var s={exports:{}},a=s.exports;Object.defineProperty(a,"__esModule",{value:!0});var r=e(__ce09c80fb835cb76cda82f0f0d4a1ea3);__6e5c1a3f5afadc2fe31a54c52b7091ab;var o=e(__25e93a8c51f0c7926d4f89a0348ea4dd),l=e(__cf31d764659b2033862570138beab86e);return i.prototype={render:function(e,i,n){this.currListId=n;var s="";if(e.length){var a=i;e.forEach(function(e){var i=e.getLabel(),r=e.get("img-src"),o=r?'<img src="'+r+'"/>':"",l=e.get("new-value")?" (<em>"+AJS.I18n.getText("aui.select.new.value")+"</em>)":"";s+='<li role="option" class="aui-select-suggestion" id="'+t(n,a)+'">'+o+i+l+"</li>",a++}),i?this.el.querySelector("ul").innerHTML+=s:this.el.querySelector("ul").innerHTML=s}else i||(this.el.querySelector("ul").innerHTML='<li role="option" class="aui-select-no-suggestions">'+AJS.I18n.getText("aui.select.no.suggestions")+"</li>");return this},setActive:function(e){n(this.el),(0,r.default)(this.el).find("#"+t(this.currListId,e)).addClass("aui-select-active")},getActive:function(){return this.el.querySelector(".aui-select-active")},show:function(){!function(e){(0,r.default)(e.el).css("min-width",(0,r.default)(e.anchor).outerWidth())}(this),(0,l.default)(this.el).show(),function(e){e.anchor&&!e.auiAlignment&&(e.auiAlignment=new o.default(e.el,e.anchor)),e.auiAlignment&&e.auiAlignment.enable()}(this)},hide:function(){n(this.el),(0,l.default)(this.el).hide(),function(e){e.auiAlignment&&e.auiAlignment.destroy()}(this)},isVisible:function(){return(0,r.default)(this.el).is(":visible")}},a.default=i,s.exports=a.default,s.exports}.call(this),("undefined"==typeof window?global:window).__766d193d8831e5b1342998cfb9354432=function(){var e={exports:{}},t=e.exports;Object.defineProperty(t,"__esModule",{value:!0});var i=function(e){return e&&e.__esModule?e:{default:e}}(__f33ac309b94c246736966ea50a11b323);return t.default=(0,i.default)('\n <input type="text" class="text" autocomplete="off" role="combobox" aria-autocomplete="list" aria-haspopup="true" aria-expanded="false">\n <select></select>\n <datalist>\n <content select="aui-option"></content>\n </datalist>\n <button class="aui-button" role="button" tabindex="-1" type="button"></button>\n <div class="aui-popover" role="listbox" data-aui-alignment="bottom left">\n <ul class="aui-optionlist" role="presentation"></ul>\n </div>\n <div class="aui-select-status assistive" aria-live="polite" role="status"></div>\n'),e.exports=t.default,e.exports}.call(this),("undefined"==typeof window?global:window).__a938c1843453a31c15c5deff68fc45ea=function(){function e(e){return e&&e.__esModule?e:{default:e}}function t(e){e._select.selectedIndex=L,function(e){e._input.removeAttribute("style"),(0,x.default)(e._input).removeClass("aui-select-has-inline-image")}(e)}function i(e){return e._suggestionModel.getNumberOfResults()}function n(e){setTimeout(e,50)}function s(e,t){return 0===e.get("label").toLowerCase().indexOf(t.toLowerCase())}function a(e){e._suggestionsView.hide(),e._input.setAttribute("aria-expanded","false")}function r(e){var t=i(e)?0:F;e._suggestionModel.highlight(t),a(e)}function o(e,t,i){e._autoHighlight=t,void 0===i&&(i=e._input.value),e._progressiveDataSet.query(i)}function l(e){var t=e._suggestionModel.highlighted()&&e._suggestionModel.highlighted().get("img-src");t&&function(e,t){(0,x.default)(e._input).addClass("aui-select-has-inline-image"),e._input.setAttribute("style","background-image: url("+t+")")}(e,t)}function c(e,t){if(t){var i=document.createElement("option"),n=e._select,s=t.get("value")||t.get("label");i.setAttribute("selected",""),i.setAttribute("value",s),i.textContent=t.getLabel(),e._input.value=i.textContent,n.innerHTML="",n.options.add(i),n.dispatchEvent(new E.default("change",{bubbles:!0}))}}function d(e){c(e,e._suggestionModel.highlighted()),l(e),r(e)}function u(e){return new $.default(e.serialize())}function h(e){for(var t=[],i=0;i<e._datalist.children.length;i++){var n=e._datalist.children[i];t.push(u(n))}return t}function f(e){var t=e._dropdown.querySelector(".aui-select-active");return t&&t.id}function p(e,t){return x.default.map(t,function(e){return e.id}).indexOf(e)}function g(e){e._progressiveDataSet=new R.default(h(e),{model:$.default,matcher:s,queryEndpoint:e._queryEndpoint,maxResults:H}),e._isSync=!e._queryEndpoint,e._progressiveDataSet.on("activity",function(){e._progressiveDataSet.activeQueryCount&&!e._isSync?(!function(e){e._button.isBusy()||(e._button.busy(),e._input.setAttribute("aria-busy","true"),e._dropdown.setAttribute("aria-busy","true"))}(e),(0,I.default)(e).set("should-flag-new-suggestions",!1)):(!function(e){e._button.idle(),e._input.setAttribute("aria-busy","false"),e._dropdown.setAttribute("aria-busy","false")}(e),(0,I.default)(e).set("should-flag-new-suggestions",!0))}),e._progressiveDataSet.on("respond",function(t){var i;if(!t.query||e._input.value)if((0,I.default)(e).get("should-cancel-response"))e._progressiveDataSet.activeQueryCount||(0,I.default)(e).set("should-cancel-response",!1);else{t.query||(t.results=h(e));var s=-1!==p(e._input.value,t.results),a=!e._input.value;if(!e.hasAttribute("can-create-values")||s||a||t.results.push(function(e){var t=new C.default;t.setAttribute("value",e._input.value);var i=u(t);return i.set("new-value",!0),i}(e)),!(0,I.default)(e).get("should-include-selected")){var r=p(e.value,t.results);r>=0&&t.results.splice(r,1)}!function(e,t){e._suggestionModel.set(),e._suggestionModel.set(t.results)}(e,t),i=e._suggestionModel.highlighted()||t.results[0],e._autoHighlight&&(e._suggestionModel.setHighlighted(i),n(function(){e._input.setAttribute("aria-activedescendant",f(e))})),e._input.setAttribute("aria-expanded","true"),!e._isSync&&e._suggestionsView.getActive()&&(0,I.default)(e).get("should-flag-new-suggestions")&&(e.querySelector(".aui-select-status").innerHTML=AJS.I18n.getText("aui.select.new.suggestions")),e._suggestionsView.show(),e._autoHighlight&&n(function(){e._input.setAttribute("aria-activedescendant",f(e))})}})}function v(e){var t=e.value?"":e._input.value,i=""===e._input.value;(0,I.default)(e).set("should-include-selected",i),o(e,!0,t)}function b(e){(function(e){return e._progressiveDataSet.activeQueryCount>0})(e)&&(0,I.default)(e).set("should-cancel-response",!0)}function m(e){if(e._select.selectedIndex>=0)return e._select.options[e._select.selectedIndex].textContent}function _(e){b(e),function(e){var i=!e.hasAttribute("no-empty-values"),n=!e._input.value,s=e._input.value!==m(e);if(n||s)if(i)t(e);else{var a=m(e);void 0===a?t(e):e._input.value=a}}(e),function(e){e._suggestionModel.highlight(F)}(e),a(e)}var w={exports:{}},y=w.exports;Object.defineProperty(y,"__esModule",{value:!0});var x=e(__ce09c80fb835cb76cda82f0f0d4a1ea3);__a6e1673bb01a22322ef9341042944d0a,__6e5c1a3f5afadc2fe31a54c52b7091ab,__2befe9148812946d2d69bd201cebc09f;var C=e(__7c3570a4f1c32f8d75931e52dbc74e57),S=e(__fb114d9b531e09c60f5fdf12262b017c),E=e(__59d7c0f9f17285b854c637a67b2cc160),A=e(__2bc1a6edbc312083fbf11f878f780e28),T=e(__4850ac7f6e93ba35f83ca6803a088772),R=e(__c290b536f781d38fd8310af686be11a9),O=e(__7a6521db1039cb333e437aa8031353cf),I=e(__36b0476263b031bdf3a69ef7b863c2db),$=e(__1cff5371449a662c0a7be7041d4b68b7),D=e(__d013a973f9737525d80a39c3b9f3006e),N=e(__de81bfb18da60d7a2ac3ffb6a6da48fd),k=e(__766d193d8831e5b1342998cfb9354432),P=e(__77c8c05565043823fdeac2c0158b936e),M=__e4e1727c26af0a5037c104d27c13c775,L=-1,F=-1,H=20,U=(0,O.default)("aui-select",{template:k.default,created:function(e){e._listId=(0,P.default)(),e._input=e.querySelector("input"),e._select=e.querySelector("select"),e._dropdown=e.querySelector(".aui-popover"),e._datalist=e.querySelector("datalist"),e._button=e.querySelector("button"),e._suggestionsView=new N.default(e._dropdown,e._input),e._suggestionModel=new D.default,e._suggestionModel.onChange=function(t){var i=[];e._suggestionModel._suggestions.forEach(function(e){t.some(function(t){return e.id===t.id})||i.push(e)}),e._suggestionsView.render(i,t.length,e._listId)},e._suggestionModel.onHighlightChange=function(){var t=e._suggestionModel.highlightedIndex();e._suggestionsView.setActive(t),e._input.setAttribute("aria-activedescendant",f(e))}},attached:function(e){O.default.init(e),g(e),function(e){e._dropdown.id=e._listId,e.querySelector("button").setAttribute("aria-controls",e._listId)}(e),e._input.setAttribute("aria-controls",e._listId),e.setAttribute("tabindex","-1"),function(e){(0,x.default)(e._dropdown).on("mouseover","li",function(t){i(e)&&e._suggestionModel.highlight((0,x.default)(t.target).index())})}(e),function(e){(0,x.default)(e._dropdown).on("mousedown","li",function(t){if(!i(e))return!1;e._suggestionModel.highlight((0,x.default)(t.target).index()),d(e),e._suggestionsView.hide(),e._input.removeAttribute("aria-activedescendant")})}(e),function(e){var t=e._datalist.querySelector("aui-option[selected]");t&&c(e,u(t))}(e),r(e),l(e)},attributes:{id:function(e,t){e.id&&(e.querySelector("input").id=t.newValue+M.INPUT_SUFFIX)},name:function(e,t){e.querySelector("select").setAttribute("name",t.newValue)},placeholder:function(e,t){e.querySelector("input").setAttribute("placeholder",t.newValue)},src:function(e,t){e._queryEndpoint=t.newValue}},events:{"blur input":function(e){_(e)},"mousedown button":function(e){document.activeElement===e._input&&"false"===e._dropdown.getAttribute("aria-hidden")&&(0,I.default)(e).set("prevent-open-on-button-click",!0)},"click input":function(e){v(e)},"click button":function(e){var t=(0,I.default)(e);t.get("prevent-open-on-button-click")?t.set("prevent-open-on-button-click",!1):e.focus()},input:function(e){e._input.value?((0,I.default)(e).set("should-include-selected",!0),o(e,!0)):a(e)},"keydown input":function(e,t){var n=e._input.value,s=!1;if(t.keyCode===T.default.ESCAPE)return b(e),void a(e);e._suggestionsView.isVisible()&&i(e)?t.keyCode===T.default.ENTER?(b(e),d(e),t.preventDefault()):t.keyCode===T.default.TAB?(!function(e){e._suggestionsView.isVisible()&&d(e)}(e),s=!0):t.keyCode===T.default.UP?(e._suggestionModel.highlightPrevious(),t.preventDefault()):t.keyCode===T.default.DOWN&&(e._suggestionModel.highlightNext(),t.preventDefault()):t.keyCode!==T.default.UP&&t.keyCode!==T.default.DOWN||(v(e),t.preventDefault()),s=s||t.defaultPrevented,setTimeout(function(){e._input.value===n||s||e.dispatchEvent(new E.default("input",{bubbles:!0}))},0)}},prototype:{get value(){var e=this._select.options[this._select.selectedIndex];return e?e.value:""},set value(e){if(""===e)!function(e){e._input.value="",e._select.innerHTML=""}(this);else if(e){var t=this._progressiveDataSet,i=t.findWhere({value:e})||t.findWhere({label:e});!i&&this.hasAttribute("can-create-values")&&(i=new $.default({value:e,label:e})),c(this,i)}return this},get displayValue(){return this._input.value},blur:function(){return this._input.blur(),_(this),this},focus:function(){return this._input.focus(),v(this),this}}});return(0,S.default)("aui/select",U),(0,A.default)("select",U),y.default=U,w.exports=y.default,w.exports}.call(this),("undefined"==typeof window?global:window).__31ae345091f25a4a96f7979654832b7c=function(){var e={};return function(e){void 0===e.fn.each2&&e.extend(e.fn,{each2:function(t){for(var i=e([0]),n=-1,s=this.length;++n<s&&(i.context=i[0]=this[n])&&!1!==t.call(i[0],n,i););return this}})}(jQuery),function(e,t){function i(e){var t,i,n,s;if(!e||e.length<1)return e;for(t="",i=0,n=e.length;i<n;i++)s=e.charAt(i),t+=I[s]||s;return t}function n(e,t){for(var i=0,n=t.length;i<n;i+=1)if(s(e,t[i]))return i;return-1}function s(e,i){return e===i||e!==t&&i!==t&&(null!==e&&null!==i&&(e.constructor===String?e+""==i+"":i.constructor===String&&i+""==e+""))}function a(t,i){var n,s,a;if(null===t||t.length<1)return[];for(s=0,a=(n=t.split(i)).length;s<a;s+=1)n[s]=e.trim(n[s]);return n}function r(e){return e.outerWidth(!1)-e.width()}function o(i){var n="keyup-change-value";i.on("keydown",function(){e.data(i,n)===t&&e.data(i,n,i.val())}),i.on("keyup",function(){var s=e.data(i,n);s!==t&&i.val()!==s&&(e.removeData(i,n),i.trigger("keyup-change"))})}function l(e,i,n){n=n||t;var s;return function(){var t=arguments;window.clearTimeout(s),s=window.setTimeout(function(){i.apply(n,t)},e)}}function c(e){e.preventDefault(),e.stopPropagation()}function d(t,i,n){var s,a,r=[];(s=t.attr("class"))&&e((s=""+s).split(" ")).each2(function(){0===this.indexOf("select2-")&&r.push(this)}),(s=i.attr("class"))&&e((s=""+s).split(" ")).each2(function(){0!==this.indexOf("select2-")&&(a=n(this))&&r.push(a)}),t.attr("class",r.join(" "))}function u(e,t,n,s){var a=i(e.toUpperCase()).indexOf(i(t.toUpperCase())),r=t.length;a<0?n.push(s(e)):(n.push(s(e.substring(0,a))),n.push("<span class='select2-match'>"),n.push(s(e.substring(a,a+r))),n.push("</span>"),n.push(s(e.substring(a+r,e.length))))}function h(e){var t={"\\":"&#92;","&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;","/":"&#47;"};return String(e).replace(/[&<>"'\/\\]/g,function(e){return t[e]})}function f(i){var n,s=null,a=i.quietMillis||100,r=i.url,o=this;return function(l){window.clearTimeout(n),n=window.setTimeout(function(){var n=i.data,a=r,c=i.transport||e.fn.select2.ajaxDefaults.transport,d={type:i.type||"GET",cache:i.cache||!1,jsonpCallback:i.jsonpCallback||t,dataType:i.dataType||"json"},u=e.extend({},e.fn.select2.ajaxDefaults.params,d);n=n?n.call(o,l.term,l.page,l.context):null,a="function"==typeof a?a.call(o,l.term,l.page,l.context):a,s&&s.abort(),i.params&&(e.isFunction(i.params)?e.extend(u,i.params.call(o)):e.extend(u,i.params)),e.extend(u,{url:a,dataType:i.dataType,data:n,success:function(e){var t=i.results(e,l.page);l.callback(t)}}),s=c.call(o,u)},a)}}function p(t){var i,n,s=t,a=function(e){return""+e.text};e.isArray(s)&&(s={results:n=s}),!1===e.isFunction(s)&&(n=s,s=function(){return n});var r=s();return r.text&&(a=r.text,e.isFunction(a)||(i=r.text,a=function(e){return e[i]})),function(t){var i,n=t.term,r={results:[]};""!==n?(i=function(s,r){var o,l;if((s=s[0]).children){o={};for(l in s)s.hasOwnProperty(l)&&(o[l]=s[l]);o.children=[],e(s.children).each2(function(e,t){i(t,o.children)}),(o.children.length||t.matcher(n,a(o),s))&&r.push(o)}else t.matcher(n,a(s),s)&&r.push(s)},e(s().results).each2(function(e,t){i(t,r.results)}),t.callback(r)):t.callback(s())}}function g(i){var n=e.isFunction(i);return function(s){var a=s.term,r={results:[]};e(n?i():i).each(function(){var e=this.text!==t,i=e?this.text:this;(""===a||s.matcher(a,i))&&r.results.push(e?this:{id:this,text:this})}),s.callback(r)}}function v(t,i){if(e.isFunction(t))return!0;if(!t)return!1;throw new Error(i+" must be a function or a falsy value")}function b(t){return e.isFunction(t)?t():t}function m(t){var i=0;return e.each(t,function(e,t){t.children?i+=m(t.children):i++}),i}function _(t,i){var n=function(){};return n.prototype=new t,n.prototype.constructor=n,n.prototype.parent=t.prototype,n.prototype=e.extend(n.prototype,i),n}if(window.Select2===t){var w,y,x,C,S,E,A,T={x:0,y:0},R={TAB:9,ENTER:13,ESC:27,SPACE:32,LEFT:37,UP:38,RIGHT:39,DOWN:40,SHIFT:16,CTRL:17,ALT:18,PAGE_UP:33,PAGE_DOWN:34,HOME:36,END:35,BACKSPACE:8,DELETE:46,isArrow:function(e){switch(e=e.which?e.which:e){case R.LEFT:case R.RIGHT:case R.UP:case R.DOWN:return!0}return!1},isControl:function(e){switch(e.which){case R.SHIFT:case R.CTRL:case R.ALT:return!0}return!!e.metaKey},isFunctionKey:function(e){return(e=e.which?e.which:e)>=112&&e<=123}},O="<div class='select2-measure-scrollbar'></div>",I={"Ⓐ":"A","A":"A","À":"A","Á":"A","Â":"A","Ầ":"A","Ấ":"A","Ẫ":"A","Ẩ":"A","Ã":"A","Ā":"A","Ă":"A","Ằ":"A","Ắ":"A","Ẵ":"A","Ẳ":"A","Ȧ":"A","Ǡ":"A","Ä":"A","Ǟ":"A","Ả":"A","Å":"A","Ǻ":"A","Ǎ":"A","Ȁ":"A","Ȃ":"A","Ạ":"A","Ậ":"A","Ặ":"A","Ḁ":"A","Ą":"A","Ⱥ":"A","Ɐ":"A","Ꜳ":"AA","Æ":"AE","Ǽ":"AE","Ǣ":"AE","Ꜵ":"AO","Ꜷ":"AU","Ꜹ":"AV","Ꜻ":"AV","Ꜽ":"AY","Ⓑ":"B","B":"B","Ḃ":"B","Ḅ":"B","Ḇ":"B","Ƀ":"B","Ƃ":"B","Ɓ":"B","Ⓒ":"C","C":"C","Ć":"C","Ĉ":"C","Ċ":"C","Č":"C","Ç":"C","Ḉ":"C","Ƈ":"C","Ȼ":"C","Ꜿ":"C","Ⓓ":"D","D":"D","Ḋ":"D","Ď":"D","Ḍ":"D","Ḑ":"D","Ḓ":"D","Ḏ":"D","Đ":"D","Ƌ":"D","Ɗ":"D","Ɖ":"D","Ꝺ":"D","DZ":"DZ","DŽ":"DZ","Dz":"Dz","Dž":"Dz","Ⓔ":"E","E":"E","È":"E","É":"E","Ê":"E","Ề":"E","Ế":"E","Ễ":"E","Ể":"E","Ẽ":"E","Ē":"E","Ḕ":"E","Ḗ":"E","Ĕ":"E","Ė":"E","Ë":"E","Ẻ":"E","Ě":"E","Ȅ":"E","Ȇ":"E","Ẹ":"E","Ệ":"E","Ȩ":"E","Ḝ":"E","Ę":"E","Ḙ":"E","Ḛ":"E","Ɛ":"E","Ǝ":"E","Ⓕ":"F","F":"F","Ḟ":"F","Ƒ":"F","Ꝼ":"F","Ⓖ":"G","G":"G","Ǵ":"G","Ĝ":"G","Ḡ":"G","Ğ":"G","Ġ":"G","Ǧ":"G","Ģ":"G","Ǥ":"G","Ɠ":"G","Ꞡ":"G","Ᵹ":"G","Ꝿ":"G","Ⓗ":"H","H":"H","Ĥ":"H","Ḣ":"H","Ḧ":"H","Ȟ":"H","Ḥ":"H","Ḩ":"H","Ḫ":"H","Ħ":"H","Ⱨ":"H","Ⱶ":"H","Ɥ":"H","Ⓘ":"I","I":"I","Ì":"I","Í":"I","Î":"I","Ĩ":"I","Ī":"I","Ĭ":"I","İ":"I","Ï":"I","Ḯ":"I","Ỉ":"I","Ǐ":"I","Ȉ":"I","Ȋ":"I","Ị":"I","Į":"I","Ḭ":"I","Ɨ":"I","Ⓙ":"J","J":"J","Ĵ":"J","Ɉ":"J","Ⓚ":"K","K":"K","Ḱ":"K","Ǩ":"K","Ḳ":"K","Ķ":"K","Ḵ":"K","Ƙ":"K","Ⱪ":"K","Ꝁ":"K","Ꝃ":"K","Ꝅ":"K","Ꞣ":"K","Ⓛ":"L","L":"L","Ŀ":"L","Ĺ":"L","Ľ":"L","Ḷ":"L","Ḹ":"L","Ļ":"L","Ḽ":"L","Ḻ":"L","Ł":"L","Ƚ":"L","Ɫ":"L","Ⱡ":"L","Ꝉ":"L","Ꝇ":"L","Ꞁ":"L","LJ":"LJ","Lj":"Lj","Ⓜ":"M","M":"M","Ḿ":"M","Ṁ":"M","Ṃ":"M","Ɱ":"M","Ɯ":"M","Ⓝ":"N","N":"N","Ǹ":"N","Ń":"N","Ñ":"N","Ṅ":"N","Ň":"N","Ṇ":"N","Ņ":"N","Ṋ":"N","Ṉ":"N","Ƞ":"N","Ɲ":"N","Ꞑ":"N","Ꞥ":"N","NJ":"NJ","Nj":"Nj","Ⓞ":"O","O":"O","Ò":"O","Ó":"O","Ô":"O","Ồ":"O","Ố":"O","Ỗ":"O","Ổ":"O","Õ":"O","Ṍ":"O","Ȭ":"O","Ṏ":"O","Ō":"O","Ṑ":"O","Ṓ":"O","Ŏ":"O","Ȯ":"O","Ȱ":"O","Ö":"O","Ȫ":"O","Ỏ":"O","Ő":"O","Ǒ":"O","Ȍ":"O","Ȏ":"O","Ơ":"O","Ờ":"O","Ớ":"O","Ỡ":"O","Ở":"O","Ợ":"O","Ọ":"O","Ộ":"O","Ǫ":"O","Ǭ":"O","Ø":"O","Ǿ":"O","Ɔ":"O","Ɵ":"O","Ꝋ":"O","Ꝍ":"O","Ƣ":"OI","Ꝏ":"OO","Ȣ":"OU","Ⓟ":"P","P":"P","Ṕ":"P","Ṗ":"P","Ƥ":"P","Ᵽ":"P","Ꝑ":"P","Ꝓ":"P","Ꝕ":"P","Ⓠ":"Q","Q":"Q","Ꝗ":"Q","Ꝙ":"Q","Ɋ":"Q","Ⓡ":"R","R":"R","Ŕ":"R","Ṙ":"R","Ř":"R","Ȑ":"R","Ȓ":"R","Ṛ":"R","Ṝ":"R","Ŗ":"R","Ṟ":"R","Ɍ":"R","Ɽ":"R","Ꝛ":"R","Ꞧ":"R","Ꞃ":"R","Ⓢ":"S","S":"S","ẞ":"S","Ś":"S","Ṥ":"S","Ŝ":"S","Ṡ":"S","Š":"S","Ṧ":"S","Ṣ":"S","Ṩ":"S","Ș":"S","Ş":"S","Ȿ":"S","Ꞩ":"S","Ꞅ":"S","Ⓣ":"T","T":"T","Ṫ":"T","Ť":"T","Ṭ":"T","Ț":"T","Ţ":"T","Ṱ":"T","Ṯ":"T","Ŧ":"T","Ƭ":"T","Ʈ":"T","Ⱦ":"T","Ꞇ":"T","Ꜩ":"TZ","Ⓤ":"U","U":"U","Ù":"U","Ú":"U","Û":"U","Ũ":"U","Ṹ":"U","Ū":"U","Ṻ":"U","Ŭ":"U","Ü":"U","Ǜ":"U","Ǘ":"U","Ǖ":"U","Ǚ":"U","Ủ":"U","Ů":"U","Ű":"U","Ǔ":"U","Ȕ":"U","Ȗ":"U","Ư":"U","Ừ":"U","Ứ":"U","Ữ":"U","Ử":"U","Ự":"U","Ụ":"U","Ṳ":"U","Ų":"U","Ṷ":"U","Ṵ":"U","Ʉ":"U","Ⓥ":"V","V":"V","Ṽ":"V","Ṿ":"V","Ʋ":"V","Ꝟ":"V","Ʌ":"V","Ꝡ":"VY","Ⓦ":"W","W":"W","Ẁ":"W","Ẃ":"W","Ŵ":"W","Ẇ":"W","Ẅ":"W","Ẉ":"W","Ⱳ":"W","Ⓧ":"X","X":"X","Ẋ":"X","Ẍ":"X","Ⓨ":"Y","Y":"Y","Ỳ":"Y","Ý":"Y","Ŷ":"Y","Ỹ":"Y","Ȳ":"Y","Ẏ":"Y","Ÿ":"Y","Ỷ":"Y","Ỵ":"Y","Ƴ":"Y","Ɏ":"Y","Ỿ":"Y","Ⓩ":"Z","Z":"Z","Ź":"Z","Ẑ":"Z","Ż":"Z","Ž":"Z","Ẓ":"Z","Ẕ":"Z","Ƶ":"Z","Ȥ":"Z","Ɀ":"Z","Ⱬ":"Z","Ꝣ":"Z","ⓐ":"a","a":"a","ẚ":"a","à":"a","á":"a","â":"a","ầ":"a","ấ":"a","ẫ":"a","ẩ":"a","ã":"a","ā":"a","ă":"a","ằ":"a","ắ":"a","ẵ":"a","ẳ":"a","ȧ":"a","ǡ":"a","ä":"a","ǟ":"a","ả":"a","å":"a","ǻ":"a","ǎ":"a","ȁ":"a","ȃ":"a","ạ":"a","ậ":"a","ặ":"a","ḁ":"a","ą":"a","ⱥ":"a","ɐ":"a","ꜳ":"aa","æ":"ae","ǽ":"ae","ǣ":"ae","ꜵ":"ao","ꜷ":"au","ꜹ":"av","ꜻ":"av","ꜽ":"ay","ⓑ":"b","b":"b","ḃ":"b","ḅ":"b","ḇ":"b","ƀ":"b","ƃ":"b","ɓ":"b","ⓒ":"c","c":"c","ć":"c","ĉ":"c","ċ":"c","č":"c","ç":"c","ḉ":"c","ƈ":"c","ȼ":"c","ꜿ":"c","ↄ":"c","ⓓ":"d","d":"d","ḋ":"d","ď":"d","ḍ":"d","ḑ":"d","ḓ":"d","ḏ":"d","đ":"d","ƌ":"d","ɖ":"d","ɗ":"d","ꝺ":"d","dz":"dz","dž":"dz","ⓔ":"e","e":"e","è":"e","é":"e","ê":"e","ề":"e","ế":"e","ễ":"e","ể":"e","ẽ":"e","ē":"e","ḕ":"e","ḗ":"e","ĕ":"e","ė":"e","ë":"e","ẻ":"e","ě":"e","ȅ":"e","ȇ":"e","ẹ":"e","ệ":"e","ȩ":"e","ḝ":"e","ę":"e","ḙ":"e","ḛ":"e","ɇ":"e","ɛ":"e","ǝ":"e","ⓕ":"f","f":"f","ḟ":"f","ƒ":"f","ꝼ":"f","ⓖ":"g","g":"g","ǵ":"g","ĝ":"g","ḡ":"g","ğ":"g","ġ":"g","ǧ":"g","ģ":"g","ǥ":"g","ɠ":"g","ꞡ":"g","ᵹ":"g","ꝿ":"g","ⓗ":"h","h":"h","ĥ":"h","ḣ":"h","ḧ":"h","ȟ":"h","ḥ":"h","ḩ":"h","ḫ":"h","ẖ":"h","ħ":"h","ⱨ":"h","ⱶ":"h","ɥ":"h","ƕ":"hv","ⓘ":"i","i":"i","ì":"i","í":"i","î":"i","ĩ":"i","ī":"i","ĭ":"i","ï":"i","ḯ":"i","ỉ":"i","ǐ":"i","ȉ":"i","ȋ":"i","ị":"i","į":"i","ḭ":"i","ɨ":"i","ı":"i","ⓙ":"j","j":"j","ĵ":"j","ǰ":"j","ɉ":"j","ⓚ":"k","k":"k","ḱ":"k","ǩ":"k","ḳ":"k","ķ":"k","ḵ":"k","ƙ":"k","ⱪ":"k","ꝁ":"k","ꝃ":"k","ꝅ":"k","ꞣ":"k","ⓛ":"l","l":"l","ŀ":"l","ĺ":"l","ľ":"l","ḷ":"l","ḹ":"l","ļ":"l","ḽ":"l","ḻ":"l","ſ":"l","ł":"l","ƚ":"l","ɫ":"l","ⱡ":"l","ꝉ":"l","ꞁ":"l","ꝇ":"l","lj":"lj","ⓜ":"m","m":"m","ḿ":"m","ṁ":"m","ṃ":"m","ɱ":"m","ɯ":"m","ⓝ":"n","n":"n","ǹ":"n","ń":"n","ñ":"n","ṅ":"n","ň":"n","ṇ":"n","ņ":"n","ṋ":"n","ṉ":"n","ƞ":"n","ɲ":"n","ʼn":"n","ꞑ":"n","ꞥ":"n","nj":"nj","ⓞ":"o","o":"o","ò":"o","ó":"o","ô":"o","ồ":"o","ố":"o","ỗ":"o","ổ":"o","õ":"o","ṍ":"o","ȭ":"o","ṏ":"o","ō":"o","ṑ":"o","ṓ":"o","ŏ":"o","ȯ":"o","ȱ":"o","ö":"o","ȫ":"o","ỏ":"o","ő":"o","ǒ":"o","ȍ":"o","ȏ":"o","ơ":"o","ờ":"o","ớ":"o","ỡ":"o","ở":"o","ợ":"o","ọ":"o","ộ":"o","ǫ":"o","ǭ":"o","ø":"o","ǿ":"o","ɔ":"o","ꝋ":"o","ꝍ":"o","ɵ":"o","ƣ":"oi","ȣ":"ou","ꝏ":"oo","ⓟ":"p","p":"p","ṕ":"p","ṗ":"p","ƥ":"p","ᵽ":"p","ꝑ":"p","ꝓ":"p","ꝕ":"p","ⓠ":"q","q":"q","ɋ":"q","ꝗ":"q","ꝙ":"q","ⓡ":"r","r":"r","ŕ":"r","ṙ":"r","ř":"r","ȑ":"r","ȓ":"r","ṛ":"r","ṝ":"r","ŗ":"r","ṟ":"r","ɍ":"r","ɽ":"r","ꝛ":"r","ꞧ":"r","ꞃ":"r","ⓢ":"s","s":"s","ß":"s","ś":"s","ṥ":"s","ŝ":"s","ṡ":"s","š":"s","ṧ":"s","ṣ":"s","ṩ":"s","ș":"s","ş":"s","ȿ":"s","ꞩ":"s","ꞅ":"s","ẛ":"s","ⓣ":"t","t":"t","ṫ":"t","ẗ":"t","ť":"t","ṭ":"t","ț":"t","ţ":"t","ṱ":"t","ṯ":"t","ŧ":"t","ƭ":"t","ʈ":"t","ⱦ":"t","ꞇ":"t","ꜩ":"tz","ⓤ":"u","u":"u","ù":"u","ú":"u","û":"u","ũ":"u","ṹ":"u","ū":"u","ṻ":"u","ŭ":"u","ü":"u","ǜ":"u","ǘ":"u","ǖ":"u","ǚ":"u","ủ":"u","ů":"u","ű":"u","ǔ":"u","ȕ":"u","ȗ":"u","ư":"u","ừ":"u","ứ":"u","ữ":"u","ử":"u","ự":"u","ụ":"u","ṳ":"u","ų":"u","ṷ":"u","ṵ":"u","ʉ":"u","ⓥ":"v","v":"v","ṽ":"v","ṿ":"v","ʋ":"v","ꝟ":"v","ʌ":"v","ꝡ":"vy","ⓦ":"w","w":"w","ẁ":"w","ẃ":"w","ŵ":"w","ẇ":"w","ẅ":"w","ẘ":"w","ẉ":"w","ⱳ":"w","ⓧ":"x","x":"x","ẋ":"x","ẍ":"x","ⓨ":"y","y":"y","ỳ":"y","ý":"y","ŷ":"y","ỹ":"y","ȳ":"y","ẏ":"y","ÿ":"y","ỷ":"y","ẙ":"y","ỵ":"y","ƴ":"y","ɏ":"y","ỿ":"y","ⓩ":"z","z":"z","ź":"z","ẑ":"z","ż":"z","ž":"z","ẓ":"z","ẕ":"z","ƶ":"z","ȥ":"z","ɀ":"z","ⱬ":"z","ꝣ":"z"};E=e(document),C=function(){var e=1;return function(){return e++}}(),E.on("mousemove",function(e){T.x=e.pageX,T.y=e.pageY}),w=_(Object,{bind:function(e){var t=this;return function(){e.apply(t,arguments)}},init:function(i){var s,a,r=".select2-results";this.opts=i=this.prepareOpts(i),this.id=i.id,i.element.data("select2")!==t&&null!==i.element.data("select2")&&i.element.data("select2").destroy(),this.container=this.createContainer(),this.containerId="s2id_"+(i.element.attr("id")||"autogen"+C()),this.containerSelector="#"+this.containerId.replace(/([;&,\.\+\*\~':"\!\^#$%@\[\]\(\)=>\|])/g,"\\$1"),this.container.attr("id",this.containerId),this.body=function(e){var t,i=!1;return function(){return!1===i&&(t=e(),i=!0),t}}(function(){return i.element.closest("body")}),d(this.container,this.opts.element,this.opts.adaptContainerCssClass),this.container.attr("style",i.element.attr("style")),this.container.css(b(i.containerCss)),this.container.addClass(b(i.containerCssClass)),this.elementTabIndex=this.opts.element.attr("tabindex"),this.opts.element.data("select2",this).attr("tabindex","-1").before(this.container).on("click.select2",c),this.container.data("select2",this),this.dropdown=this.container.find(".select2-drop"),d(this.dropdown,this.opts.element,this.opts.adaptDropdownCssClass),this.dropdown.addClass(b(i.dropdownCssClass)),this.dropdown.data("select2",this),this.dropdown.on("click",c),this.results=s=this.container.find(r),this.search=a=this.container.find("input.select2-input"),this.queryCount=0,this.resultsPage=0,this.context=null,this.initContainer(),this.container.on("click",c),function(i){i.on("mousemove",function(i){var n=T;n!==t&&n.x===i.pageX&&n.y===i.pageY||e(i.target).trigger("mousemove-filtered",i)})}(this.results),this.dropdown.on("mousemove-filtered touchstart touchmove touchend",r,this.bind(this.highlightUnderEvent)),function(e,t){var i=l(e,function(e){t.trigger("scroll-debounced",e)});t.on("scroll",function(e){n(e.target,t.get())>=0&&i(e)})}(80,this.results),this.dropdown.on("scroll-debounced",r,this.bind(this.loadMoreIfNeeded)),e(this.container).on("change",".select2-input",function(e){e.stopPropagation()}),e(this.dropdown).on("change",".select2-input",function(e){e.stopPropagation()}),e.fn.mousewheel&&s.mousewheel(function(e,t,i,n){var a=s.scrollTop();n>0&&a-n<=0?(s.scrollTop(0),c(e)):n<0&&s.get(0).scrollHeight-s.scrollTop()+n<=s.height()&&(s.scrollTop(s.get(0).scrollHeight-s.height()),c(e))}),o(a),a.on("keyup-change input paste",this.bind(this.updateResults)),a.on("focus",function(){a.addClass("select2-focused")}),a.on("blur",function(){a.removeClass("select2-focused")}),this.dropdown.on("mouseup",r,this.bind(function(t){e(t.target).closest(".select2-result-selectable").length>0&&(this.highlightUnderEvent(t),this.selectHighlighted(t))})),this.dropdown.on("click mouseup mousedown",function(e){e.stopPropagation()}),e.isFunction(this.opts.initSelection)&&(this.initSelection(),this.monitorSource()),null!==i.maximumInputLength&&this.search.attr("maxlength",i.maximumInputLength);var u=i.element.prop("disabled");u===t&&(u=!1),this.enable(!u);var h=i.element.prop("readonly");h===t&&(h=!1),this.readonly(h),A=A||function(){var t=e(O);t.appendTo("body");var i={width:t.width()-t[0].clientWidth,height:t.height()-t[0].clientHeight};return t.remove(),i}(),this.autofocus=i.element.prop("autofocus"),i.element.prop("autofocus",!1),this.autofocus&&this.focus(),this.nextSearchTerm=t},destroy:function(){var e=this.opts.element,i=e.data("select2");this.close(),this.propertyObserver&&(delete this.propertyObserver,this.propertyObserver=null),i!==t&&(i.container.remove(),i.dropdown.remove(),e.removeClass("select2-offscreen").removeData("select2").off(".select2").prop("autofocus",this.autofocus||!1),this.elementTabIndex?e.attr({tabindex:this.elementTabIndex}):e.removeAttr("tabindex"),e.show())},optionToData:function(e){return e.is("option")?{id:e.prop("value"),text:e.text(),element:e.get(),css:e.attr("class"),disabled:e.prop("disabled"),locked:s(e.attr("locked"),"locked")||s(e.data("locked"),!0)}:e.is("optgroup")?{text:e.attr("label"),children:[],element:e.get(),css:e.attr("class")}:void 0},prepareOpts:function(i){var n,r,o,l,c=this;if("select"===(n=i.element).get(0).tagName.toLowerCase()&&(this.select=r=i.element),r&&e.each(["id","multiple","ajax","query","createSearchChoice","initSelection","data","tags"],function(){if(this in i)throw new Error("Option '"+this+"' is not allowed for Select2 when attached to a <select> element.")}),"function"!=typeof(i=e.extend({},{populateResults:function(n,s,a){var r,o=this.opts.id;(r=function(n,s,l){var d,u,h,f,p,g,v,b,m,_;for(d=0,u=(n=i.sortResults(n,s,a)).length;d<u;d+=1)f=!(p=!0===(h=n[d]).disabled)&&o(h)!==t,g=h.children&&h.children.length>0,(v=e("<li></li>")).addClass("select2-results-dept-"+l),v.addClass("select2-result"),v.addClass(f?"select2-result-selectable":"select2-result-unselectable"),p&&v.addClass("select2-disabled"),g&&v.addClass("select2-result-with-children"),v.addClass(c.opts.formatResultCssClass(h)),(b=e(document.createElement("div"))).addClass("select2-result-label"),(_=i.formatResult(h,b,a,c.opts.escapeMarkup))!==t&&b.html(_),v.append(b),g&&((m=e("<ul></ul>")).addClass("select2-result-sub"),r(h.children,m,l+1),v.append(m)),v.data("select2-data",h),s.append(v)})(s,n,0)}},e.fn.select2.defaults,i)).id&&(o=i.id,i.id=function(e){return e[o]}),e.isArray(i.element.data("select2Tags"))){if("tags"in i)throw"tags specified as both an attribute 'data-select2-tags' and in options of Select2 "+i.element.attr("id");i.tags=i.element.data("select2Tags")}if(r?(i.query=this.bind(function(e){var i,s,a,r={results:[],more:!1},o=e.term;a=function(t,i){var n;t.is("option")?e.matcher(o,t.text(),t)&&i.push(c.optionToData(t)):t.is("optgroup")&&(n=c.optionToData(t),t.children().each2(function(e,t){a(t,n.children)}),n.children.length>0&&i.push(n))},i=n.children(),this.getPlaceholder()!==t&&i.length>0&&(s=this.getPlaceholderOption())&&(i=i.not(s)),i.each2(function(e,t){a(t,r.results)}),e.callback(r)}),i.id=function(e){return e.id},i.formatResultCssClass=function(e){return e.css}):"query"in i||("ajax"in i?((l=i.element.data("ajax-url"))&&l.length>0&&(i.ajax.url=l),i.query=f.call(i.element,i.ajax)):"data"in i?i.query=p(i.data):"tags"in i&&(i.query=g(i.tags),i.createSearchChoice===t&&(i.createSearchChoice=function(t){return{id:e.trim(t),text:e.trim(t)}}),i.initSelection===t&&(i.initSelection=function(t,n){var r=[];e(a(t.val(),i.separator)).each(function(){var t={id:this,text:this},n=i.tags;e.isFunction(n)&&(n=n()),e(n).each(function(){if(s(this.id,t.id))return t=this,!1}),r.push(t)}),n(r)}))),"function"!=typeof i.query)throw"query function not defined for Select2 "+i.element.attr("id");return i},monitorSource:function(){var e,i,n=this.opts.element;n.on("change.select2",this.bind(function(e){!0!==this.opts.element.data("select2-change-triggered")&&this.initSelection()})),e=this.bind(function(){var e=n.prop("disabled");e===t&&(e=!1),this.enable(!e);var i=n.prop("readonly");i===t&&(i=!1),this.readonly(i),d(this.container,this.opts.element,this.opts.adaptContainerCssClass),this.container.addClass(b(this.opts.containerCssClass)),d(this.dropdown,this.opts.element,this.opts.adaptDropdownCssClass),this.dropdown.addClass(b(this.opts.dropdownCssClass))}),n.on("propertychange.select2",e),this.mutationCallback===t&&(this.mutationCallback=function(t){t.forEach(e)}),(i=window.MutationObserver||window.WebKitMutationObserver||window.MozMutationObserver)!==t&&(this.propertyObserver&&(delete this.propertyObserver,this.propertyObserver=null),this.propertyObserver=new i(this.mutationCallback),this.propertyObserver.observe(n.get(0),{attributes:!0,subtree:!1}))},triggerSelect:function(t){var i=e.Event("select2-selecting",{val:this.id(t),object:t});return this.opts.element.trigger(i),!i.isDefaultPrevented()},triggerChange:function(t){t=t||{},t=e.extend({},t,{type:"change",val:this.val()}),this.opts.element.data("select2-change-triggered",!0),this.opts.element.trigger(t),this.opts.element.data("select2-change-triggered",!1),this.opts.element.click(),this.opts.blurOnChange&&this.opts.element.blur()},isInterfaceEnabled:function(){return!0===this.enabledInterface},enableInterface:function(){var e=this._enabled&&!this._readonly,t=!e;return e!==this.enabledInterface&&(this.container.toggleClass("select2-container-disabled",t),this.close(),this.enabledInterface=e,!0)},enable:function(e){e===t&&(e=!0),this._enabled!==e&&(this._enabled=e,this.opts.element.prop("disabled",!e),this.enableInterface())},disable:function(){this.enable(!1)},readonly:function(e){return e===t&&(e=!1),this._readonly!==e&&(this._readonly=e,this.opts.element.prop("readonly",e),this.enableInterface(),!0)},opened:function(){return this.container.hasClass("select2-dropdown-open")},positionDropdown:function(){var t,i,n,s,a,r=this.dropdown,o=this.container.offset(),l=this.container.outerHeight(!1),c=this.container.outerWidth(!1),d=r.outerHeight(!1),u=e(window),h=u.width(),f=u.height(),p=u.scrollLeft()+h,g=u.scrollTop()+f,v=o.top+l,m=o.left,_=v+d<=g,w=o.top-d>=this.body().scrollTop(),y=r.outerWidth(!1),x=m+y<=p;r.hasClass("select2-drop-above")?(i=!0,!w&&_&&(n=!0,i=!1)):(i=!1,!_&&w&&(n=!0,i=!0)),n&&(r.hide(),o=this.container.offset(),l=this.container.outerHeight(!1),c=this.container.outerWidth(!1),d=r.outerHeight(!1),p=u.scrollLeft()+h,g=u.scrollTop()+f,v=o.top+l,x=(m=o.left)+(y=r.outerWidth(!1))<=p,r.show()),this.opts.dropdownAutoWidth?(a=e(".select2-results",r)[0],r.addClass("select2-drop-auto-width"),r.css("width",""),(y=r.outerWidth(!1)+(a.scrollHeight===a.clientHeight?0:A.width))>c?c=y:y=c,x=m+y<=p):this.container.removeClass("select2-drop-auto-width"),"static"!==this.body().css("position")&&(v-=(t=this.body().offset()).top,m-=t.left),x||(m=o.left+c-y),s={left:m,width:c},i?(s.bottom=f-o.top,s.top="auto",this.container.addClass("select2-drop-above"),r.addClass("select2-drop-above")):(s.top=v,s.bottom="auto",this.container.removeClass("select2-drop-above"),r.removeClass("select2-drop-above")),s=e.extend(s,b(this.opts.dropdownCss)),r.css(s)},shouldOpen:function(){var t;return!this.opened()&&(!1!==this._enabled&&!0!==this._readonly&&(t=e.Event("select2-opening"),this.opts.element.trigger(t),!t.isDefaultPrevented()))},clearDropdownAlignmentPreference:function(){this.container.removeClass("select2-drop-above"),this.dropdown.removeClass("select2-drop-above")},open:function(){return!!this.shouldOpen()&&(this.opening(),!0)},opening:function(){var t,i=this.containerId,n="scroll."+i,s="resize."+i,a="orientationchange."+i;this.container.addClass("select2-dropdown-open").addClass("select2-container-active"),this.clearDropdownAlignmentPreference(),this.dropdown[0]!==this.body().children().last()[0]&&this.dropdown.detach().appendTo(this.body()),0==(t=e("#select2-drop-mask")).length&&((t=e(document.createElement("div"))).attr("id","select2-drop-mask").attr("class","select2-drop-mask"),t.hide(),t.appendTo(this.body()),t.on("mousedown touchstart click",function(t){var i,n=e("#select2-drop");n.length>0&&((i=n.data("select2")).opts.selectOnBlur&&i.selectHighlighted({noFocus:!0}),i.close({focus:!0}),t.preventDefault(),t.stopPropagation())})),this.dropdown.prev()[0]!==t[0]&&this.dropdown.before(t),e("#select2-drop").removeAttr("id"),this.dropdown.attr("id","select2-drop"),t.show(),this.positionDropdown(),this.dropdown.show(),this.positionDropdown(),this.dropdown.addClass("select2-drop-active");var r=this;this.container.parents().add(window).each(function(){e(this).on(s+" "+n+" "+a,function(e){r.positionDropdown()})})},close:function(){if(this.opened()){var t=this.containerId,i="scroll."+t,n="resize."+t,s="orientationchange."+t;this.container.parents().add(window).each(function(){e(this).off(i).off(n).off(s)}),this.clearDropdownAlignmentPreference(),e("#select2-drop-mask").hide(),this.dropdown.removeAttr("id"),this.dropdown.hide(),this.container.removeClass("select2-dropdown-open").removeClass("select2-container-active"),this.results.empty(),this.clearSearch(),this.search.removeClass("select2-active"),this.opts.element.trigger(e.Event("select2-close"))}},externalSearch:function(e){this.open(),this.search.val(e),this.updateResults(!1)},clearSearch:function(){},getMaximumSelectionSize:function(){return b(this.opts.maximumSelectionSize)},ensureHighlightVisible:function(){var t,i,n,s,a,r,o,l=this.results;(i=this.highlight())<0||(0!=i?(t=this.findHighlightableChoices().find(".select2-result-label"),s=(n=e(t[i])).offset().top+n.outerHeight(!0),i===t.length-1&&(o=l.find("li.select2-more-results")).length>0&&(s=o.offset().top+o.outerHeight(!0)),s>(a=l.offset().top+l.outerHeight(!0))&&l.scrollTop(l.scrollTop()+(s-a)),(r=n.offset().top-l.offset().top)<0&&"none"!=n.css("display")&&l.scrollTop(l.scrollTop()+r)):l.scrollTop(0))},findHighlightableChoices:function(){return this.results.find(".select2-result-selectable:not(.select2-disabled, .select2-selected)")},moveHighlight:function(t){for(var i=this.findHighlightableChoices(),n=this.highlight();n>-1&&n<i.length;){var s=e(i[n+=t]);if(s.hasClass("select2-result-selectable")&&!s.hasClass("select2-disabled")&&!s.hasClass("select2-selected")){this.highlight(n);break}}},highlight:function(t){var i,s,a=this.findHighlightableChoices();if(0===arguments.length)return n(a.filter(".select2-highlighted")[0],a.get());t>=a.length&&(t=a.length-1),t<0&&(t=0),this.removeHighlight(),(i=e(a[t])).addClass("select2-highlighted"),this.ensureHighlightVisible(),(s=i.data("select2-data"))&&this.opts.element.trigger({type:"select2-highlight",val:this.id(s),choice:s})},removeHighlight:function(){this.results.find(".select2-highlighted").removeClass("select2-highlighted")},countSelectableResults:function(){return this.findHighlightableChoices().length},highlightUnderEvent:function(t){var i=e(t.target).closest(".select2-result-selectable");if(i.length>0&&!i.is(".select2-highlighted")){var n=this.findHighlightableChoices();this.highlight(n.index(i))}else 0==i.length&&this.removeHighlight()},loadMoreIfNeeded:function(){var e=this.results,t=e.find("li.select2-more-results"),i=this.resultsPage+1,n=this,s=this.search.val(),a=this.context;0!==t.length&&t.offset().top-e.offset().top-e.height()<=this.opts.loadMorePadding&&(t.addClass("select2-active"),this.opts.query({element:this.opts.element,term:s,page:i,context:a,matcher:this.opts.matcher,callback:this.bind(function(r){n.opened()&&(n.opts.populateResults.call(this,e,r.results,{term:s,page:i,context:a}),n.postprocessResults(r,!1,!1),!0===r.more?(t.detach().appendTo(e).text(n.opts.formatLoadMore(i+1)),window.setTimeout(function(){n.loadMoreIfNeeded()},10)):t.remove(),n.positionDropdown(),n.resultsPage=i,n.context=r.context,this.opts.element.trigger({type:"select2-loaded",items:r}))})}))},tokenize:function(){},updateResults:function(i){function n(){c.removeClass("select2-active"),h.positionDropdown()}function a(e){d.html(e),n()}var r,o,l,c=this.search,d=this.results,u=this.opts,h=this,f=c.val(),p=e.data(this.container,"select2-last-term");if((!0===i||!p||!s(f,p))&&(e.data(this.container,"select2-last-term",f),!0===i||!1!==this.showSearchInput&&this.opened())){l=++this.queryCount;var g=this.getMaximumSelectionSize();if(!(g>=1&&(r=this.data(),e.isArray(r)&&r.length>=g&&v(u.formatSelectionTooBig,"formatSelectionTooBig"))))return c.val().length<u.minimumInputLength?(a(v(u.formatInputTooShort,"formatInputTooShort")?"<li class='select2-no-results'>"+u.formatInputTooShort(c.val(),u.minimumInputLength)+"</li>":""),void(i&&this.showSearch&&this.showSearch(!0))):void(u.maximumInputLength&&c.val().length>u.maximumInputLength?a(v(u.formatInputTooLong,"formatInputTooLong")?"<li class='select2-no-results'>"+u.formatInputTooLong(c.val(),u.maximumInputLength)+"</li>":""):(u.formatSearching&&0===this.findHighlightableChoices().length&&a("<li class='select2-searching'>"+u.formatSearching()+"</li>"),c.addClass("select2-active"),this.removeHighlight(),(o=this.tokenize())!=t&&null!=o&&c.val(o),this.resultsPage=1,u.query({element:u.element,term:c.val(),page:this.resultsPage,context:null,matcher:u.matcher,callback:this.bind(function(r){var o;l==this.queryCount&&(this.opened()?(this.context=r.context===t?null:r.context,this.opts.createSearchChoice&&""!==c.val()&&(o=this.opts.createSearchChoice.call(h,c.val(),r.results))!==t&&null!==o&&h.id(o)!==t&&null!==h.id(o)&&0===e(r.results).filter(function(){return s(h.id(this),h.id(o))}).length&&r.results.unshift(o),0===r.results.length&&v(u.formatNoMatches,"formatNoMatches")?a("<li class='select2-no-results'>"+u.formatNoMatches(c.val())+"</li>"):(d.empty(),h.opts.populateResults.call(this,d,r.results,{term:c.val(),page:this.resultsPage,context:null}),!0===r.more&&v(u.formatLoadMore,"formatLoadMore")&&(d.append("<li class='select2-more-results'>"+h.opts.escapeMarkup(u.formatLoadMore(this.resultsPage))+"</li>"),window.setTimeout(function(){h.loadMoreIfNeeded()},10)),this.postprocessResults(r,i),n(),this.opts.element.trigger({type:"select2-loaded",items:r}))):this.search.removeClass("select2-active"))})})));a("<li class='select2-selection-limit'>"+u.formatSelectionTooBig(g)+"</li>")}},cancel:function(){this.close()},blur:function(){this.opts.selectOnBlur&&this.selectHighlighted({noFocus:!0}),this.close(),this.container.removeClass("select2-container-active"),this.search[0]===document.activeElement&&this.search.blur(),this.clearSearch(),this.selection.find(".select2-search-choice-focus").removeClass("select2-search-choice-focus")},focusSearch:function(){!function(e){e[0]!==document.activeElement&&window.setTimeout(function(){var t,i=e[0],n=e.val().length;e.focus(),e.is(":visible")&&i===document.activeElement&&(i.setSelectionRange?i.setSelectionRange(n,n):i.createTextRange&&((t=i.createTextRange()).collapse(!1),t.select()))},0)}(this.search)},selectHighlighted:function(e){var t=this.highlight(),i=this.results.find(".select2-highlighted").closest(".select2-result").data("select2-data");i?(this.highlight(t),this.onSelect(i,e)):e&&e.noFocus&&this.close()},getPlaceholder:function(){var e;return this.opts.element.attr("placeholder")||this.opts.element.attr("data-placeholder")||this.opts.element.data("placeholder")||this.opts.placeholder||((e=this.getPlaceholderOption())!==t?e.text():t)},getPlaceholderOption:function(){if(this.select){var e=this.select.children("option").first();if(this.opts.placeholderOption!==t)return"first"===this.opts.placeholderOption&&e||"function"==typeof this.opts.placeholderOption&&this.opts.placeholderOption(this.select);if(""===e.text()&&""===e.val())return e}},initContainerWidth:function(){var i=function(){var i,n,s,a,r,o;if("off"===this.opts.width)return null;if("element"===this.opts.width)return 0===this.opts.element.outerWidth(!1)?"auto":this.opts.element.outerWidth(!1)+"px";if("copy"===this.opts.width||"resolve"===this.opts.width){if((i=this.opts.element.attr("style"))!==t)for(a=0,r=(n=i.split(";")).length;a<r;a+=1)if(o=n[a].replace(/\s/g,""),null!==(s=o.match(/^width:(([-+]?([0-9]*\.)?[0-9]+)(px|em|ex|%|in|cm|mm|pt|pc))/i))&&s.length>=1)return s[1];return"resolve"===this.opts.width?(i=this.opts.element.css("width")).indexOf("%")>0?i:0===this.opts.element.outerWidth(!1)?"auto":this.opts.element.outerWidth(!1)+"px":null}return e.isFunction(this.opts.width)?this.opts.width():this.opts.width}.call(this);null!==i&&this.container.css("width",i)}}),y=_(w,{createContainer:function(){return e(document.createElement("div")).attr({class:"select2-container"}).html(["<a href='javascript:void(0)' onclick='return false;' class='select2-choice' tabindex='-1'>"," <span class='select2-chosen'>&nbsp;</span><abbr class='select2-search-choice-close'></abbr>"," <span class='select2-arrow'><b></b></span>","</a>","<input class='select2-focusser select2-offscreen' type='text'/>","<div class='select2-drop select2-display-none'>"," <div class='select2-search'>"," <input type='text' autocomplete='off' autocorrect='off' autocapitalize='off' spellcheck='false' class='select2-input'/>"," </div>"," <ul class='select2-results'>"," </ul>","</div>"].join(""))},enableInterface:function(){this.parent.enableInterface.apply(this,arguments)&&this.focusser.prop("disabled",!this.isInterfaceEnabled())},opening:function(){var i,n,s;this.opts.minimumResultsForSearch>=0&&this.showSearch(!0),this.parent.opening.apply(this,arguments),!1!==this.showSearchInput&&this.search.val(this.focusser.val()),this.search.focus(),(i=this.search.get(0)).createTextRange?((n=i.createTextRange()).collapse(!1),n.select()):i.setSelectionRange&&(s=this.search.val().length,i.setSelectionRange(s,s)),""===this.search.val()&&this.nextSearchTerm!=t&&(this.search.val(this.nextSearchTerm),this.search.select()),this.focusser.prop("disabled",!0).val(""),this.updateResults(!0),this.opts.element.trigger(e.Event("select2-open"))},close:function(e){this.opened()&&(this.parent.close.apply(this,arguments),e=e||{focus:!0},this.focusser.removeAttr("disabled"),e.focus&&this.focusser.focus())},focus:function(){this.opened()?this.close():(this.focusser.removeAttr("disabled"),this.focusser.focus())},isFocused:function(){return this.container.hasClass("select2-container-active")},cancel:function(){this.parent.cancel.apply(this,arguments),this.focusser.removeAttr("disabled"),this.focusser.focus()},destroy:function(){e("label[for='"+this.focusser.attr("id")+"']").attr("for",this.opts.element.attr("id")),this.parent.destroy.apply(this,arguments)},initContainer:function(){var t,i=this.container,n=this.dropdown;this.opts.minimumResultsForSearch<0?this.showSearch(!1):this.showSearch(!0),this.selection=t=i.find(".select2-choice"),this.focusser=i.find(".select2-focusser"),this.focusser.attr("id","s2id_autogen"+C()),e("label[for='"+this.opts.element.attr("id")+"']").attr("for",this.focusser.attr("id")),this.focusser.attr("tabindex",this.elementTabIndex),this.search.on("keydown",this.bind(function(e){if(this.isInterfaceEnabled())if(e.which!==R.PAGE_UP&&e.which!==R.PAGE_DOWN)switch(e.which){case R.UP:case R.DOWN:return this.moveHighlight(e.which===R.UP?-1:1),void c(e);case R.ENTER:return this.selectHighlighted(),void c(e);case R.TAB:return void this.selectHighlighted({noFocus:!0});case R.ESC:return this.cancel(e),void c(e)}else c(e)})),this.search.on("blur",this.bind(function(e){document.activeElement===this.body().get(0)&&window.setTimeout(this.bind(function(){this.search.focus()}),0)})),this.focusser.on("keydown",this.bind(function(e){if(this.isInterfaceEnabled()&&e.which!==R.TAB&&!R.isControl(e)&&!R.isFunctionKey(e)&&e.which!==R.ESC){if(!1!==this.opts.openOnEnter||e.which!==R.ENTER){if(e.which==R.DOWN||e.which==R.UP||e.which==R.ENTER&&this.opts.openOnEnter){if(e.altKey||e.ctrlKey||e.shiftKey||e.metaKey)return;return this.open(),void c(e)}return e.which==R.DELETE||e.which==R.BACKSPACE?(this.opts.allowClear&&this.clear(),void c(e)):void 0}c(e)}})),o(this.focusser),this.focusser.on("keyup-change input",this.bind(function(e){if(this.opts.minimumResultsForSearch>=0){if(e.stopPropagation(),this.opened())return;this.open()}})),t.on("mousedown","abbr",this.bind(function(e){this.isInterfaceEnabled()&&(this.clear(),function(e){e.preventDefault(),e.stopImmediatePropagation()}(e),this.close(),this.selection.focus())})),t.on("mousedown",this.bind(function(t){this.container.hasClass("select2-container-active")||this.opts.element.trigger(e.Event("select2-focus")),this.opened()?this.close():this.isInterfaceEnabled()&&this.open(),c(t)})),n.on("mousedown",this.bind(function(){this.search.focus()})),t.on("focus",this.bind(function(e){c(e)})),this.focusser.on("focus",this.bind(function(){this.container.hasClass("select2-container-active")||this.opts.element.trigger(e.Event("select2-focus")),this.container.addClass("select2-container-active")})).on("blur",this.bind(function(){this.opened()||(this.container.removeClass("select2-container-active"),this.opts.element.trigger(e.Event("select2-blur")))})),this.search.on("focus",this.bind(function(){this.container.hasClass("select2-container-active")||this.opts.element.trigger(e.Event("select2-focus")),this.container.addClass("select2-container-active")})),this.initContainerWidth(),this.opts.element.addClass("select2-offscreen"),this.setPlaceholder()},clear:function(t){var i=this.selection.data("select2-data");if(i){var n=e.Event("select2-clearing");if(this.opts.element.trigger(n),n.isDefaultPrevented())return;var s=this.getPlaceholderOption();this.opts.element.val(s?s.val():""),this.selection.find(".select2-chosen").empty(),this.selection.removeData("select2-data"),this.setPlaceholder(),!1!==t&&(this.opts.element.trigger({type:"select2-removed",val:this.id(i),choice:i}),this.triggerChange({removed:i}))}},initSelection:function(){if(this.isPlaceholderOptionSelected())this.updateSelection(null),this.close(),this.setPlaceholder();else{var e=this;this.opts.initSelection.call(null,this.opts.element,function(i){i!==t&&null!==i&&(e.updateSelection(i),e.close(),e.setPlaceholder())})}},isPlaceholderOptionSelected:function(){var e;return!!this.getPlaceholder()&&((e=this.getPlaceholderOption())!==t&&e.prop("selected")||""===this.opts.element.val()||this.opts.element.val()===t||null===this.opts.element.val())},prepareOpts:function(){var t=this.parent.prepareOpts.apply(this,arguments),i=this;return"select"===t.element.get(0).tagName.toLowerCase()?t.initSelection=function(e,t){var n=e.find("option").filter(function(){return this.selected});t(i.optionToData(n))}:"data"in t&&(t.initSelection=t.initSelection||function(i,n){var a=i.val(),r=null;t.query({matcher:function(e,i,n){var o=s(a,t.id(n));return o&&(r=n),o},callback:e.isFunction(n)?function(){n(r)}:e.noop})}),t},getPlaceholder:function(){return this.select&&this.getPlaceholderOption()===t?t:this.parent.getPlaceholder.apply(this,arguments)},setPlaceholder:function(){var e=this.getPlaceholder();if(this.isPlaceholderOptionSelected()&&e!==t){if(this.select&&this.getPlaceholderOption()===t)return;this.selection.find(".select2-chosen").html(this.opts.escapeMarkup(e)),this.selection.addClass("select2-default"),this.container.removeClass("select2-allowclear")}},postprocessResults:function(e,t,i){var n=0,a=this;if(this.findHighlightableChoices().each2(function(e,t){if(s(a.id(t.data("select2-data")),a.opts.element.val()))return n=e,!1}),!1!==i&&(!0===t&&n>=0?this.highlight(n):this.highlight(0)),!0===t){var r=this.opts.minimumResultsForSearch;r>=0&&this.showSearch(m(e.results)>=r)}},showSearch:function(t){this.showSearchInput!==t&&(this.showSearchInput=t,this.dropdown.find(".select2-search").toggleClass("select2-search-hidden",!t),this.dropdown.find(".select2-search").toggleClass("select2-offscreen",!t),e(this.dropdown,this.container).toggleClass("select2-with-searchbox",t))},onSelect:function(e,t){if(this.triggerSelect(e)){var i=this.opts.element.val(),n=this.data();this.opts.element.val(this.id(e)),this.updateSelection(e),this.opts.element.trigger({type:"select2-selected",val:this.id(e),choice:e}),this.nextSearchTerm=this.opts.nextSearchTerm(e,this.search.val()),this.close(),t&&t.noFocus||this.focusser.focus(),s(i,this.id(e))||this.triggerChange({added:e,removed:n})}},updateSelection:function(e){var i,n,s=this.selection.find(".select2-chosen");this.selection.data("select2-data",e),s.empty(),null!==e&&(i=this.opts.formatSelection(e,s,this.opts.escapeMarkup)),i!==t&&s.append(i),(n=this.opts.formatSelectionCssClass(e,s))!==t&&s.addClass(n),this.selection.removeClass("select2-default"),this.opts.allowClear&&this.getPlaceholder()!==t&&this.container.addClass("select2-allowclear")},val:function(){var e,i=!1,n=null,s=this,a=this.data();if(0===arguments.length)return this.opts.element.val();if(e=arguments[0],arguments.length>1&&(i=arguments[1]),this.select)this.select.val(e).find("option").filter(function(){return this.selected}).each2(function(e,t){return n=s.optionToData(t),!1}),this.updateSelection(n),this.setPlaceholder(),i&&this.triggerChange({added:n,removed:a});else{if(!e&&0!==e)return void this.clear(i);if(this.opts.initSelection===t)throw new Error("cannot call val() if initSelection() is not defined");this.opts.element.val(e),this.opts.initSelection(this.opts.element,function(e){s.opts.element.val(e?s.id(e):""),s.updateSelection(e),s.setPlaceholder(),i&&s.triggerChange({added:e,removed:a})})}},clearSearch:function(){this.search.val(""),this.focusser.val("")},data:function(e){var i,n=!1;if(0===arguments.length)return(i=this.selection.data("select2-data"))==t&&(i=null),i;arguments.length>1&&(n=arguments[1]),e?(i=this.data(),this.opts.element.val(e?this.id(e):""),this.updateSelection(e),n&&this.triggerChange({added:e,removed:i})):this.clear(n)}}),x=_(w,{createContainer:function(){return e(document.createElement("div")).attr({class:"select2-container select2-container-multi"}).html(["<ul class='select2-choices'>"," <li class='select2-search-field'>"," <input type='text' autocomplete='off' autocorrect='off' autocapitalize='off' spellcheck='false' class='select2-input'>"," </li>","</ul>","<div class='select2-drop select2-drop-multi select2-display-none'>"," <ul class='select2-results'>"," </ul>","</div>"].join(""))},prepareOpts:function(){var t=this.parent.prepareOpts.apply(this,arguments),i=this;return"select"===t.element.get(0).tagName.toLowerCase()?t.initSelection=function(e,t){var n=[];e.find("option").filter(function(){return this.selected}).each2(function(e,t){n.push(i.optionToData(t))}),t(n)}:"data"in t&&(t.initSelection=t.initSelection||function(i,n){var r=a(i.val(),t.separator),o=[];t.query({matcher:function(i,n,a){var l=e.grep(r,function(e){return s(e,t.id(a))}).length;return l&&o.push(a),l},callback:e.isFunction(n)?function(){for(var e=[],i=0;i<r.length;i++)for(var a=r[i],l=0;l<o.length;l++){var c=o[l];if(s(a,t.id(c))){e.push(c),o.splice(l,1);break}}n(e)}:e.noop})}),t},selectChoice:function(e){var t=this.container.find(".select2-search-choice-focus");t.length&&e&&e[0]==t[0]||(t.length&&this.opts.element.trigger("choice-deselected",t),t.removeClass("select2-search-choice-focus"),e&&e.length&&(this.close(),e.addClass("select2-search-choice-focus"),this.opts.element.trigger("choice-selected",e)))},destroy:function(){e("label[for='"+this.search.attr("id")+"']").attr("for",this.opts.element.attr("id")),this.parent.destroy.apply(this,arguments)},initContainer:function(){var t,i=".select2-choices";this.searchContainer=this.container.find(".select2-search-field"),this.selection=t=this.container.find(i);var n=this;this.selection.on("click",".select2-search-choice:not(.select2-locked)",function(t){n.search[0].focus(),n.selectChoice(e(this))}),this.search.attr("id","s2id_autogen"+C()),e("label[for='"+this.opts.element.attr("id")+"']").attr("for",this.search.attr("id")),this.search.on("input paste",this.bind(function(){this.isInterfaceEnabled()&&(this.opened()||this.open())})),this.search.attr("tabindex",this.elementTabIndex),this.keydowns=0,this.search.on("keydown",this.bind(function(i){if(this.isInterfaceEnabled()){++this.keydowns;var n=t.find(".select2-search-choice-focus"),s=n.prev(".select2-search-choice:not(.select2-locked)"),a=n.next(".select2-search-choice:not(.select2-locked)"),r=function(t){var i=0,n=0;if("selectionStart"in(t=e(t)[0]))i=t.selectionStart,n=t.selectionEnd-i;else if("selection"in document){t.focus();var s=document.selection.createRange();n=document.selection.createRange().text.length,s.moveStart("character",-t.value.length),i=s.text.length-n}return{offset:i,length:n}}(this.search);if(n.length&&(i.which==R.LEFT||i.which==R.RIGHT||i.which==R.BACKSPACE||i.which==R.DELETE||i.which==R.ENTER)){var o=n;return i.which==R.LEFT&&s.length?o=s:i.which==R.RIGHT?o=a.length?a:null:i.which===R.BACKSPACE?(this.unselect(n.first()),this.search.width(10),o=s.length?s:a):i.which==R.DELETE?(this.unselect(n.first()),this.search.width(10),o=a.length?a:null):i.which==R.ENTER&&(o=null),this.selectChoice(o),c(i),void(o&&o.length||this.open())}if((i.which===R.BACKSPACE&&1==this.keydowns||i.which==R.LEFT)&&0==r.offset&&!r.length)return this.selectChoice(t.find(".select2-search-choice:not(.select2-locked)").last()),void c(i);if(this.selectChoice(null),this.opened())switch(i.which){case R.UP:case R.DOWN:return this.moveHighlight(i.which===R.UP?-1:1),void c(i);case R.ENTER:return this.selectHighlighted(),void c(i);case R.TAB:return this.selectHighlighted({noFocus:!0}),void this.close();case R.ESC:return this.cancel(i),void c(i)}if(i.which!==R.TAB&&!R.isControl(i)&&!R.isFunctionKey(i)&&i.which!==R.BACKSPACE&&i.which!==R.ESC){if(i.which===R.ENTER){if(!1===this.opts.openOnEnter)return;if(i.altKey||i.ctrlKey||i.shiftKey||i.metaKey)return}this.open(),i.which!==R.PAGE_UP&&i.which!==R.PAGE_DOWN||c(i),i.which===R.ENTER&&c(i)}}})),this.search.on("keyup",this.bind(function(e){this.keydowns=0,this.resizeSearch()})),this.search.on("blur",this.bind(function(t){this.container.removeClass("select2-container-active"),this.search.removeClass("select2-focused"),this.selectChoice(null),this.opened()||this.clearSearch(),t.stopImmediatePropagation(),this.opts.element.trigger(e.Event("select2-blur"))})),this.container.on("click",i,this.bind(function(t){this.isInterfaceEnabled()&&(e(t.target).closest(".select2-search-choice").length>0||(this.selectChoice(null),this.clearPlaceholder(),this.container.hasClass("select2-container-active")||this.opts.element.trigger(e.Event("select2-focus")),this.open(),this.focusSearch(),t.preventDefault()))})),this.container.on("focus",i,this.bind(function(){this.isInterfaceEnabled()&&(this.container.hasClass("select2-container-active")||this.opts.element.trigger(e.Event("select2-focus")),this.container.addClass("select2-container-active"),this.dropdown.addClass("select2-drop-active"),this.clearPlaceholder())})),this.initContainerWidth(),this.opts.element.addClass("select2-offscreen"),this.clearSearch()},enableInterface:function(){this.parent.enableInterface.apply(this,arguments)&&this.search.prop("disabled",!this.isInterfaceEnabled())},initSelection:function(){if(""===this.opts.element.val()&&""===this.opts.element.text()&&(this.updateSelection([]),this.close(),this.clearSearch()),this.select||""!==this.opts.element.val()){var e=this;this.opts.initSelection.call(null,this.opts.element,function(i){i!==t&&null!==i&&(e.updateSelection(i),e.close(),e.clearSearch())})}},clearSearch:function(){var e=this.getPlaceholder(),i=this.getMaxSearchWidth();e!==t&&0===this.getVal().length&&!1===this.search.hasClass("select2-focused")?(this.search.val(e).addClass("select2-default"),this.search.width(i>0?i:this.container.css("width"))):this.search.val("").width(10)},clearPlaceholder:function(){this.search.hasClass("select2-default")&&this.search.val("").removeClass("select2-default")},opening:function(){this.clearPlaceholder(),this.resizeSearch(),this.parent.opening.apply(this,arguments),this.focusSearch(),this.updateResults(!0),this.search.focus(),this.opts.element.trigger(e.Event("select2-open"))},close:function(){this.opened()&&this.parent.close.apply(this,arguments)},focus:function(){this.close(),this.search.focus()},isFocused:function(){return this.search.hasClass("select2-focused")},updateSelection:function(t){var i=[],s=[],a=this;e(t).each(function(){n(a.id(this),i)<0&&(i.push(a.id(this)),s.push(this))}),t=s,this.selection.find(".select2-search-choice").remove(),e(t).each(function(){a.addSelectedChoice(this)}),a.postprocessResults()},tokenize:function(){var e=this.search.val();null!=(e=this.opts.tokenizer.call(this,e,this.data(),this.bind(this.onSelect),this.opts))&&e!=t&&(this.search.val(e),e.length>0&&this.open())},onSelect:function(e,t){this.triggerSelect(e)&&(this.addSelectedChoice(e),this.opts.element.trigger({type:"selected",val:this.id(e),choice:e}),!this.select&&this.opts.closeOnSelect||this.postprocessResults(e,!1,!0===this.opts.closeOnSelect),this.opts.closeOnSelect?(this.close(),this.search.width(10)):this.countSelectableResults()>0?(this.search.width(10),this.resizeSearch(),this.getMaximumSelectionSize()>0&&this.val().length>=this.getMaximumSelectionSize()&&this.updateResults(!0),this.positionDropdown()):(this.close(),this.search.width(10)),this.triggerChange({added:e}),t&&t.noFocus||this.focusSearch())},cancel:function(){this.close(),this.focusSearch()},addSelectedChoice:function(i){var n,s,a=!i.locked,r=e("<li class='select2-search-choice'> <div></div> <a href='#' onclick='return false;' class='select2-search-choice-close' tabindex='-1'></a></li>"),o=e("<li class='select2-search-choice select2-locked'><div></div></li>"),l=a?r:o,d=this.id(i),u=this.getVal();(n=this.opts.formatSelection(i,l.find("div"),this.opts.escapeMarkup))!=t&&l.find("div").replaceWith("<div>"+n+"</div>"),(s=this.opts.formatSelectionCssClass(i,l.find("div")))!=t&&l.addClass(s),a&&l.find(".select2-search-choice-close").on("mousedown",c).on("click dblclick",this.bind(function(t){this.isInterfaceEnabled()&&(e(t.target).closest(".select2-search-choice").fadeOut("fast",this.bind(function(){this.unselect(e(t.target)),this.selection.find(".select2-search-choice-focus").removeClass("select2-search-choice-focus"),this.close(),this.focusSearch()})).dequeue(),c(t))})).on("focus",this.bind(function(){this.isInterfaceEnabled()&&(this.container.addClass("select2-container-active"),this.dropdown.addClass("select2-drop-active"))})),l.data("select2-data",i),l.insertBefore(this.searchContainer),u.push(d),this.setVal(u)},unselect:function(t){var i,s,a=this.getVal();if(0===(t=t.closest(".select2-search-choice")).length)throw"Invalid argument: "+t+". Must be .select2-search-choice";if(i=t.data("select2-data")){for(;(s=n(this.id(i),a))>=0;)a.splice(s,1),this.setVal(a),this.select&&this.postprocessResults();var r=e.Event("select2-removing");r.val=this.id(i),r.choice=i,this.opts.element.trigger(r),r.isDefaultPrevented()||(t.remove(),this.opts.element.trigger({type:"select2-removed",val:this.id(i),choice:i}),this.triggerChange({removed:i}))}},postprocessResults:function(e,t,i){var s=this.getVal(),a=this.results.find(".select2-result"),r=this.results.find(".select2-result-with-children"),o=this;a.each2(function(e,t){n(o.id(t.data("select2-data")),s)>=0&&(t.addClass("select2-selected"),t.find(".select2-result-selectable").addClass("select2-selected"))}),r.each2(function(e,t){t.is(".select2-result-selectable")||0!==t.find(".select2-result-selectable:not(.select2-selected)").length||t.addClass("select2-selected")}),-1==this.highlight()&&!1!==i&&o.highlight(0),!this.opts.createSearchChoice&&!a.filter(".select2-result:not(.select2-selected)").length>0&&(!e||e&&!e.more&&0===this.results.find(".select2-no-results").length)&&v(o.opts.formatNoMatches,"formatNoMatches")&&this.results.append("<li class='select2-no-results'>"+o.opts.formatNoMatches(o.search.val())+"</li>")},getMaxSearchWidth:function(){return this.selection.width()-r(this.search)},resizeSearch:function(){var t,i,n,s,a=r(this.search);t=function(t){if(!S){var i=t[0].currentStyle||window.getComputedStyle(t[0],null);(S=e(document.createElement("div")).css({position:"absolute",left:"-10000px",top:"-10000px",display:"none",fontSize:i.fontSize,fontFamily:i.fontFamily,fontStyle:i.fontStyle,fontWeight:i.fontWeight,letterSpacing:i.letterSpacing,textTransform:i.textTransform,whiteSpace:"nowrap"})).attr("class","select2-sizer"),e("body").append(S)}return S.text(t.val()),S.width()}(this.search)+10,i=this.search.offset().left,(s=(n=this.selection.width())-(i-this.selection.offset().left)-a)<t&&(s=n-a),s<40&&(s=n-a),s<=0&&(s=t),this.search.width(Math.floor(s))},getVal:function(){var e;return this.select?null===(e=this.select.val())?[]:e:(e=this.opts.element.val(),a(e,this.opts.separator))},setVal:function(t){var i;this.select?this.select.val(t):(i=[],e(t).each(function(){n(this,i)<0&&i.push(this)}),this.opts.element.val(0===i.length?"":i.join(this.opts.separator)))},buildChangeDetails:function(e,t){for(var t=t.slice(0),e=e.slice(0),i=0;i<t.length;i++)for(var n=0;n<e.length;n++)s(this.opts.id(t[i]),this.opts.id(e[n]))&&(t.splice(i,1),i>0&&i--,e.splice(n,1),n--);return{added:t,removed:e}},val:function(i,n){var s,a=this;if(0===arguments.length)return this.getVal();if((s=this.data()).length||(s=[]),!i&&0!==i)return this.opts.element.val(""),this.updateSelection([]),this.clearSearch(),void(n&&this.triggerChange({added:this.data(),removed:s}));if(this.setVal(i),this.select)this.opts.initSelection(this.select,this.bind(this.updateSelection)),n&&this.triggerChange(this.buildChangeDetails(s,this.data()));else{if(this.opts.initSelection===t)throw new Error("val() cannot be called if initSelection() is not defined");this.opts.initSelection(this.opts.element,function(t){var i=e.map(t,a.id);a.setVal(i),a.updateSelection(t),a.clearSearch(),n&&a.triggerChange(a.buildChangeDetails(s,a.data()))})}this.clearSearch()},onSortStart:function(){if(this.select)throw new Error("Sorting of elements is not supported when attached to <select>. Attach to <input type='hidden'/> instead.");this.search.width(0),this.searchContainer.hide()},onSortEnd:function(){var t=[],i=this;this.searchContainer.show(),this.searchContainer.appendTo(this.searchContainer.parent()),this.resizeSearch(),this.selection.find(".select2-search-choice").each(function(){t.push(i.opts.id(e(this).data("select2-data")))}),this.setVal(t),this.triggerChange()},data:function(t,i){var n,s,a=this;if(0===arguments.length)return this.selection.find(".select2-search-choice").map(function(){return e(this).data("select2-data")}).get();s=this.data(),t||(t=[]),n=e.map(t,function(e){return a.opts.id(e)}),this.setVal(n),this.updateSelection(t),this.clearSearch(),i&&this.triggerChange(this.buildChangeDetails(s,this.data()))}}),e.fn.select2=function(){var i,s,a,r,o,l=Array.prototype.slice.call(arguments,0),c=["val","destroy","opened","open","close","focus","isFocused","container","dropdown","onSortStart","onSortEnd","enable","disable","readonly","positionDropdown","data","search"],d=["opened","isFocused","container","dropdown"],u=["val","data"],h={search:"externalSearch"};return this.each(function(){if(0===l.length||"object"==typeof l[0])(i=0===l.length?{}:e.extend({},l[0])).element=e(this),"select"===i.element.get(0).tagName.toLowerCase()?o=i.element.prop("multiple"):(o=i.multiple||!1,"tags"in i&&(i.multiple=o=!0)),(s=o?new x:new y).init(i);else{if("string"!=typeof l[0])throw"Invalid arguments to select2 plugin: "+l;if(n(l[0],c)<0)throw"Unknown method: "+l[0];if(r=t,(s=e(this).data("select2"))===t)return;if("container"===(a=l[0])?r=s.container:"dropdown"===a?r=s.dropdown:(h[a]&&(a=h[a]),r=s[a].apply(s,l.slice(1))),n(l[0],d)>=0||n(l[0],u)&&1==l.length)return!1}}),r===t?this:r},e.fn.select2.defaults={width:"copy",loadMorePadding:0,closeOnSelect:!0,openOnEnter:!0,containerCss:{},dropdownCss:{},containerCssClass:"",dropdownCssClass:"",formatResult:function(e,t,i,n){var s=[];return u(e.text,i.term,s,n),s.join("")},formatSelection:function(e,i,n){return e?n(e.text):t},sortResults:function(e,t,i){return e},formatResultCssClass:function(e){return t},formatSelectionCssClass:function(e,i){return t},formatNoMatches:function(){return"No matches found"},formatInputTooShort:function(e,t){var i=t-e.length;return"Please enter "+i+" more character"+(1==i?"":"s")},formatInputTooLong:function(e,t){var i=e.length-t;return"Please delete "+i+" character"+(1==i?"":"s")},formatSelectionTooBig:function(e){return"You can only select "+e+" item"+(1==e?"":"s")},formatLoadMore:function(e){return"Loading more results..."},formatSearching:function(){return"Searching..."},minimumResultsForSearch:0,minimumInputLength:0,maximumInputLength:null,maximumSelectionSize:0,id:function(e){return e.id},matcher:function(e,t){return i(""+t).toUpperCase().indexOf(i(""+e).toUpperCase())>=0},separator:",",tokenSeparators:[],tokenizer:function(e,i,n,a){var r,o,l,c,d,u=e,h=!1;if(!a.createSearchChoice||!a.tokenSeparators||a.tokenSeparators.length<1)return t;for(;;){for(o=-1,l=0,c=a.tokenSeparators.length;l<c&&(d=a.tokenSeparators[l],!((o=e.indexOf(d))>=0));l++);if(o<0)break;if(r=e.substring(0,o),e=e.substring(o+d.length),r.length>0&&(r=a.createSearchChoice.call(this,r,i))!==t&&null!==r&&a.id(r)!==t&&null!==a.id(r)){for(h=!1,l=0,c=i.length;l<c;l++)if(s(a.id(r),a.id(i[l]))){h=!0;break}h||n(r)}}return u!==e?e:void 0},escapeMarkup:h,blurOnChange:!1,selectOnBlur:!1,adaptContainerCssClass:function(e){return e},adaptDropdownCssClass:function(e){return null},nextSearchTerm:function(e,i){return t}},e.fn.select2.ajaxDefaults={transport:e.ajax,params:{type:"GET",cache:!1,dataType:"json"}},window.Select2={query:{ajax:f,local:p,tags:g},util:{debounce:l,markMatch:u,escapeMarkup:h,stripDiacritics:i},class:{abstract:w,single:y,multi:x}}}}(jQuery),e}.call(this),("undefined"==typeof window?global:window).__e94988ffdda50ffba5e53ee4664a2df6=function(){var e={},t=function(e){return e&&e.__esModule?e:{default:e}}(__ce09c80fb835cb76cda82f0f0d4a1ea3);__31ae345091f25a4a96f7979654832b7c;var i=t.default.fn.select2,n="aui-select2-container",s="aui-select2-drop aui-dropdown2 aui-style-default";return t.default.fn.auiSelect2=function(e){var a;if(t.default.isPlainObject(e)){var r=t.default.extend({},e),o=r.hasAvatar?" aui-has-avatar":"";r.containerCssClass=n+o+(r.containerCssClass?" "+r.containerCssClass:""),r.dropdownCssClass=s+o+(r.dropdownCssClass?" "+r.dropdownCssClass:""),(a=Array.prototype.slice.call(arguments,1)).unshift(r)}else a=arguments.length?arguments:[{containerCssClass:n,dropdownCssClass:s}];return i.apply(this,a)},e}.call(this),("undefined"==typeof window?global:window).__8c4026b907ef72c5a5d5107442ffe97a=function(){var e={};return function(e){for(var t=0,i=["webkit","moz"],n=e.requestAnimationFrame,s=e.cancelAnimationFrame,a=i.length;--a>=0&&!n;)n=e[i[a]+"RequestAnimationFrame"],s=e[i[a]+"CancelAnimationFrame"];n&&s||(n=function(e){var i=Date.now(),n=Math.max(t+16,i);return setTimeout(function(){e(t=n)},n-i)},s=clearTimeout),e.requestAnimationFrame=n,e.cancelAnimationFrame=s}(window),e}.call(this),("undefined"==typeof window?global:window).__f44879594461118287e96fb61221cdd0=function(){var e={exports:{}},t=e.exports;Object.defineProperty(t,"__esModule",{value:!0});var i=window.DocumentTouch,n="ontouchstart"in window||i&&document instanceof i;return t.default=n,e.exports=t.default,e.exports}.call(this),("undefined"==typeof window?global:window).__2ac39c5fbcb5700537ed152f8d72957f=function(){var e={exports:{}},t=e.exports;return Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){return"value"in e||e.isContentEditable},e.exports=t.default,e.exports}.call(this),("undefined"==typeof window?global:window).__00c5fafd099449599429ebac7405f071=function(){var e={exports:{}},t=e.exports;return Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){if(window.matchMedia)return window.matchMedia(e).matches;var t=document.createElement("style");t.type="text/css",t.id="testMedia",t.innerText="@media "+e+" { #testMedia { width: 1px; } }",document.head.appendChild(t);var i="1px"===window.getComputedStyle(t,null).width;return t.parentNode.removeChild(t),i},e.exports=t.default,e.exports}.call(this),("undefined"==typeof window?global:window).__ced4da26b0960c7d9748908b0665dba7=function(){function e(e){return e&&e.__esModule?e:{default:e}}function t(e){return e.offset().top}function i(e){this.$el=(0,g.default)(e),this.$el.length&&(this.$body=(0,g.default)("body"),this.$wrapper=this.$el.children(".aui-sidebar-wrapper"),this.$body.addClass("aui-page-sidebar"),this._previousScrollTop=null,this._previousViewportHeight=null,this._previousViewportWidth=null,this._previousOffsetTop=null,this.submenus=new a,function(e){function t(e){return e.keyCode===y.default.TAB&&!e.shiftKey&&!e.altKey}if(!(0,g.default)(".aui-sidebar").length)return;(function(e){e.$el.on("mouseenter mouseleave click focus",e.collapsedTriggersSelector,function(t){var i=(0,g.default)(t.target);d(e,i)})})(e),_.default&&(0,x.default)("only screen and (max-device-width:1024px)")&&(0,g.default)("body").addClass("aui-page-sidebar-touch");var i=null,n=function(){null===i&&(i=requestAnimationFrame(function(){e.reflow(),i=null}))};(0,g.default)(window).on("scroll resize",n),n(),e.isAnimated()&&e.$el.on("transitionend webkitTransitionEnd",function(){e.$el.trigger(g.default.Event(T+(e.isCollapsed()?"collapse-end":"expand-end")))});e.$el.on("click",".aui-sidebar-toggle",function(t){t.preventDefault(),e.toggle()}),(0,g.default)(".aui-page-panel").click(function(){!e.isCollapsed()&&e.isViewportNarrow()&&e.collapse()});var s=function(t){(function(e){return!(e.which!==y.default.LEFT_SQUARE_BRACKET||e.shiftKey||e.ctrlKey||e.metaKey||(0,w.default)(e.target))})(t)&&e.toggle()};(0,g.default)(document).on("keypress",s),e._remove=function(){this._removeAllTooltips(),(0,g.default)(this.inlineDialogSelector).remove(),this.$el.off(),this.$el.remove(),(0,g.default)(document).off("keypress",s),(0,g.default)(window).off("scroll resize",n)},e.$el.on("touchend",function(t){e.isCollapsed()&&(e.expand(),t.preventDefault())}),e.$el.on("mouseenter focus",e.collapsedTriggersSelector,function(){if(e.isCollapsed()){var t=(0,g.default)(this);l(t)||u(t)}}),e.$el.on("click blur mouseleave",e.collapsedTriggersSelector,function(){e.isCollapsed()&&h((0,g.default)(this))}),e.$el.on("mouseenter focus",e.toggleSelector,function(){var t=(0,g.default)(this);e.isCollapsed()?t.data("tooltip",AJS.I18n.getText("aui.sidebar.expand.tooltip")):t.data("tooltip",AJS.I18n.getText("aui.sidebar.collapse.tooltip")),u(t)}),e.$el.on("click blur mouseleave",e.toggleSelector,function(){h((0,g.default)(this))});e.$el.on("keydown",e.collapsedTriggersSelector,function(i){if(e.isCollapsed()){var n=i.target,s=o(n);if(!s)return;var a=(0,g.default)(s);t(i)&&s.open&&(i.preventDefault(),function(e){e.attr("persistent",""),e.find(":aui-tabbable").first().focus(),setTimeout(function(){e.removeAttr("persistent")},100)}(a),a.on("keydown",function(e){((function(e){return e.keyCode===y.default.TAB&&e.shiftKey})(e)&&function(e,t){return e===t.find(":aui-tabbable")[0]}(e.target,a)||t(e)&&function(e,t){return e===t.find(":aui-tabbable").last()[0]}(e.target,a))&&(n.focus(),(0,g.default)(this).off("keydown"),c())}))}})}(this),function(e){(0,g.default)(e.collapsedTriggersSelector).each(function(){var t=(0,g.default)(this);d(e,t)})}(this))}function n(e){return g.default.map(e.split(" "),function(e){return T+e}).join(" ")}function s(){return document.querySelectorAll(i.prototype.inlineDialogSelector)}function a(){this.inlineDialog=null}function r(e){return e.is("a")?e.next(".aui-nav"):e.children(".aui-nav, hr")}function o(e){var t=e.getAttribute("aria-controls");return document.getElementById(t)}function l(e){return 0!==r(e).length}function c(){var e=s();Array.prototype.forEach.call(e,function(e){e.open=!1})}function d(e,t){if(!t.data("_aui-sidebar-submenu-constructed")&&(t.data("_aui-sidebar-submenu-constructed",!0),l(t))){var n=document.createElement("aui-inline-dialog"),s=(0,S.default)("sidebar-submenu");return t.attr("aria-controls",s),t.attr("data-aui-trigger",""),C.default.init(t),n.setAttribute("id",s),n.setAttribute("alignment","right top"),n.setAttribute("aria-hidden","true"),e.isCollapsed()&&n.setAttribute("responds-to","hover"),(0,g.default)(n).addClass(i.prototype.inlineDialogClass),document.body.appendChild(n),C.default.init(n),function(e,t,i){i.addEventListener("aui-layer-show",function(n){e.isCollapsed()?function(e,t){e.addClass("active"),t.innerHTML=R;var i=e.is("a")?e.text():e.children(".aui-nav-heading").text(),n=(0,g.default)(t).find(".aui-navgroup-inner");n.children(".aui-nav-heading").attr("title",i).children("strong").text(i);(function(e){var t=(0,v.default)(e);t.hasClass("aui-expander-content")&&(t.find(".aui-expander-cutoff").remove(),t.removeClass("aui-expander-content"));return t})(r(e)).appendTo(n)}(t,i):n.preventDefault()}),i.addEventListener("aui-layer-hide",function(){!function(e){e.removeClass("active")}(t)})}(e,t,n),n}}function u(e){e.tipsy(O).tipsy("show");var t=e.data("tipsy")&&e.data("tipsy").$tip;t&&t.css({opacity:""}).addClass("tooltip-shown")}function h(e){var t=e.data("tipsy")&&e.data("tipsy").$tip;if(t){var i=t.css("transition-duration");if(i){var n=i.indexOf("ms")>=0?parseInt(i.substring(0,i.length-2),10):1e3*parseInt(i.substring(0,i.length-1),10);setTimeout(function(){e.tipsy("hide")},n)}t.removeClass("tooltip-shown")}}var f={exports:{}},p=f.exports;Object.defineProperty(p,"__esModule",{value:!0});var g=e(__ce09c80fb835cb76cda82f0f0d4a1ea3);__86b584d7b2dca6d114205bd2e5d490d7,__8c4026b907ef72c5a5d5107442ffe97a,__6e5c1a3f5afadc2fe31a54c52b7091ab;var v=e(__30dbe3392e506771269a555c0f06428e),b=function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&(t[i]=e[i]);return t.default=e,t}(__3632ac12e0e2db0a58ef6348743599e5),m=e(__2bc1a6edbc312083fbf11f878f780e28),_=e(__f44879594461118287e96fb61221cdd0),w=e(__2ac39c5fbcb5700537ed152f8d72957f),y=e(__4850ac7f6e93ba35f83ca6803a088772),x=e(__00c5fafd099449599429ebac7405f071),C=e(__7a6521db1039cb333e437aa8031353cf),S=e(__77c8c05565043823fdeac2c0158b936e),E=e(__ca3e3104543f86ce5d69c679cc0b6ddd),A=void 0!==document.documentElement.style.transition||void 0!==document.documentElement.style.webkitTransition,T="_aui-internal-sidebar-";i.prototype.on=function(){var e=arguments[0],t=Array.prototype.slice.call(arguments,1),i=n(e);return this.$el.on.apply(this.$el,[i].concat(t)),this},i.prototype.off=function(){var e=arguments[0],t=Array.prototype.slice.call(arguments,1),i=n(e);return this.$el.off.apply(this.$el,[i].concat(t)),this},i.prototype.setHeight=function(e,t,i){var n=Math.max(0,i-e);return this.$wrapper.height(t-n),this},i.prototype.setTopPosition=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:window.pageYOffset;return this.$wrapper.toggleClass("aui-is-docked",e>t(this.$el)),this},i.prototype.setPosition=b.fn(i.prototype.setTopPosition,"Sidebar.setPosition",{removeInVersion:"8.0.0",sinceVersion:"7.6.1",alternativeName:"Sidebar.setTopPosition"}),i.prototype.setLeftPosition=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:window.pageXOffset;return this.$wrapper.hasClass("aui-is-docked")&&this.$wrapper.css({left:-e}),this},i.prototype.setCollapsedState=function(e){var t={collapsed:{},expanded:{}};t.collapsed.narrow={narrow:g.default.noop,wide:function(t){t._expand(e,!0)}},t.collapsed.wide={narrow:g.default.noop,wide:g.default.noop},t.expanded.narrow={narrow:g.default.noop,wide:function(e){e.$body.removeClass("aui-sidebar-collapsed"),e.$el.removeClass("aui-sidebar-fly-out")}},t.expanded.wide={narrow:function(e){e._collapse(!0)},wide:g.default.noop};var i=this.isCollapsed()?"collapsed":"expanded",n=this.isViewportNarrow(this._previousViewportWidth)?"narrow":"wide",s=this.isViewportNarrow(e)?"narrow":"wide";return t[i][n][s](this),this},i.prototype._collapse=function(e){if(this.isCollapsed())return this;var t=g.default.Event(T+"collapse-start",{isResponsive:e});return this.$el.trigger(t),t.isDefaultPrevented()?this:(this.$body.addClass("aui-sidebar-collapsed"),this.$el.attr("aria-expanded","false"),this.$el.removeClass("aui-sidebar-fly-out"),this.$el.find(this.submenuTriggersSelector).attr("tabindex",0),(0,g.default)(this.inlineDialogSelector).attr("responds-to","hover"),this.isAnimated()||this.$el.trigger(g.default.Event(T+"collapse-end",{isResponsive:e})),this)},i.prototype.collapse=function(){return this._collapse(!1)},i.prototype._expand=function(e,t){var i=g.default.Event(T+"expand-start",{isResponsive:t});if(this.$el.trigger(i),i.isDefaultPrevented())return this;var n=this.isViewportNarrow(e);return this.$el.attr("aria-expanded","true"),this.$body.toggleClass("aui-sidebar-collapsed",n),this.$el.toggleClass("aui-sidebar-fly-out",n),this.$el.find(this.submenuTriggersSelector).removeAttr("tabindex"),(0,g.default)(this.inlineDialogSelector).removeAttr("responds-to"),this.isAnimated()||this.$el.trigger(g.default.Event(T+"expand-end",{isResponsive:t})),this},i.prototype.expand=function(){return this.isCollapsed()&&this._expand(this._previousViewportWidth,!1),this},i.prototype.isAnimated=function(){return A&&this.$el.hasClass("aui-is-animated")},i.prototype.isCollapsed=function(){return"false"===this.$el.attr("aria-expanded")},i.prototype.isViewportNarrow=function(e){return(e=void 0===e?this._previousViewportWidth:e)<1240},i.prototype._removeAllTooltips=function(){(0,g.default)(this.tooltipSelector).remove()},i.prototype.responsiveReflow=function(e,t){if(e){if(!this.isCollapsed()&&this.isViewportNarrow(t)){var i=this.isAnimated();i&&this.$el.removeClass("aui-is-animated"),this.collapse(),i&&(this.$el[0].offsetHeight,this.$el.addClass("aui-is-animated"))}}else t!==this._previousViewportWidth&&this.setCollapsedState(t)},i.prototype.reflow=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:window.pageYOffset,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:document.documentElement.clientHeight,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:window.innerWidth,s=arguments.length>3&&void 0!==arguments[3]?arguments[3]:document.documentElement.scrollHeight,a=arguments.length>4&&void 0!==arguments[4]?arguments[4]:window.pageXOffset,r=t(this.$el),o=null===this._previousViewportWidth;if(e!==this._previousScrollTop||i!==this._previousViewportHeight||r!==this._previousOffsetTop){this.isCollapsed()&&!o&&e!==this._previousScrollTop&&(c(),this._removeAllTooltips());var l=this.$body.hasClass("aui-page-sidebar-touch"),d=e!==this._previousScrollTop&&(e<0||e+i>s);l||!o&&d||(this.setHeight(e,i,r),this.setTopPosition(e))}a!==this._previousScrollLeft&&this.setLeftPosition(a);if("false"!==this.$el.attr("data-aui-responsive"))this.responsiveReflow(o,n);else{var u=!this.isCollapsed()&&this.isViewportNarrow(n);this.$el.toggleClass("aui-sidebar-fly-out",u)}return this._previousScrollTop=e,this._previousViewportHeight=i,this._previousViewportWidth=n,this._previousOffsetTop=r,this._previousScrollLeft=a,this},i.prototype.toggle=function(){return this.isCollapsed()?(this.expand(),this._removeAllTooltips()):this.collapse(),this},i.prototype.submenuTriggersSelector=".aui-sidebar-group:not(.aui-sidebar-group-tier-one)",i.prototype.collapsedTriggersSelector=[i.prototype.submenuTriggersSelector,".aui-sidebar-group.aui-sidebar-group-tier-one > .aui-nav > li > a",".aui-sidebar-footer > .aui-sidebar-settings-button"].join(", "),i.prototype.toggleSelector=".aui-sidebar-footer > .aui-sidebar-toggle",i.prototype.tooltipSelector=".aui-sidebar-section-tooltip",i.prototype.inlineDialogClass="aui-sidebar-submenu-dialog",i.prototype.inlineDialogSelector="."+i.prototype.inlineDialogClass,a.prototype.submenu=function(e){return $(),r(e)},a.prototype.hasSubmenu=function(e){return $(),l(e)},a.prototype.submenuHeadingHeight=function(){return $(),34},a.prototype.isShowing=function(){return $(),i.prototype.isSubmenuVisible()},a.prototype.show=function(e,t){$(),function(e){o(e).open=!0}(t)},a.prototype.hide=function(){$(),c()},a.prototype.inlineDialogShowHandler=function(){$()},a.prototype.inlineDialogHideHandler=function(){$()},a.prototype.moveSubmenuToInlineDialog=function(){$()},a.prototype.restoreSubmenu=function(){$()},i.prototype.getVisibleSubmenus=function(){return Array.prototype.filter.call(s(),function(e){return e.open})},i.prototype.isSubmenuVisible=function(){return this.getVisibleSubmenus().length>0};var R='<div class="aui-inline-dialog-contents"><div class="aui-sidebar-submenu" ><div class="aui-navgroup aui-navgroup-vertical"><div class="aui-navgroup-inner"><div class="aui-nav-heading"><strong></strong></div></div></div></div></div>',O={trigger:"manual",gravity:"w",className:"aui-sidebar-section-tooltip",title:function(){var e=(0,g.default)(this);return e.is("a")?e.attr("title")||e.find(".aui-nav-item-label").text()||e.data("tooltip"):e.children(".aui-nav").attr("title")||e.children(".aui-nav-heading").text()}},I=(0,E.default)("sidebar",i);(0,g.default)(function(){I(".aui-sidebar")});var $=b.getMessageLogger("Sidebar.submenus",{removeInVersion:"8.0",sinceVersion:"5.8"});return(0,m.default)("sidebar",I),p.default=I,f.exports=p.default,f.exports}.call(this),("undefined"==typeof window?global:window).__040e46c8a552bd6d1dd4f4764a88f2b2=function(){var e={};return function(e){e.extend({tablesorter:new function(){function t(){var e=arguments[0],t=arguments.length>1?Array.prototype.slice.call(arguments):e;"undefined"!=typeof console&&void 0!==console.log?console[/error/i.test(e)?"error":/warn/i.test(e)?"warn":"log"](t):alert(t)}function i(e,i){t(e+" ("+((new Date).getTime()-i.getTime())+"ms)")}function n(e){for(var t in e)return!1;return!0}function s(t,i,n){if(!i)return"";var s,a=t.config,r=a.textExtraction||"",o="";return o="basic"===r?e(i).attr(a.textAttribute)||i.textContent||i.innerText||e(i).text()||"":"function"==typeof r?r(i,t,n):"function"==typeof(s=w.getColumnData(t,r,n))?s(i,t,n):i.textContent||i.innerText||e(i).text()||"",e.trim(o)}function a(e,i,n,a){for(var r,o=w.parsers.length,l=!1,c="",d=!0;""===c&&d;)i[++n]?(c=s(e,l=i[n].cells[a],a),e.config.debug&&t("Checking if value was empty on row "+n+", column: "+a+': "'+c+'"')):d=!1;for(;--o>=0;)if((r=w.parsers[o])&&"text"!==r.id&&r.is&&r.is(c,e,l))return r;return w.getParserById("text")}function r(e){var n,s,r,o,l,c,d,u,h,f,p=e.config,g=p.$tbodies=p.$table.children("tbody:not(."+p.cssInfoBlock+")"),v=0,b="",m=g.length;if(0===m)return p.debug?t("Warning: *Empty table!* Not building a parser cache"):"";for(p.debug&&(f=new Date,t("Detecting parsers for each column")),s={extractors:[],parsers:[]};v<m;){if((n=g[v].rows)[v])for(r=p.columns,o=0;o<r;o++)l=p.$headers.filter('[data-column="'+o+'"]:last'),c=w.getColumnData(e,p.headers,o),h=w.getParserById(w.getData(l,c,"extractor")),u=w.getParserById(w.getData(l,c,"sorter")),d="false"===w.getData(l,c,"parser"),p.empties[o]=w.getData(l,c,"empty")||p.emptyTo||(p.emptyToBottom?"bottom":"top"),p.strings[o]=w.getData(l,c,"string")||p.stringTo||"max",d&&(u=w.getParserById("no-parser")),h||(h=!1),u||(u=a(e,n,-1,o)),p.debug&&(b+="column:"+o+"; extractor:"+h.id+"; parser:"+u.id+"; string:"+p.strings[o]+"; empty: "+p.empties[o]+"\n"),s.parsers[o]=u,s.extractors[o]=h;v+=s.parsers.length?m:1}p.debug&&(t(b||"No parsers detected"),i("Completed detecting parsers",f)),p.parsers=s.parsers,p.extractors=s.extractors}function o(n){var a,r,o,l,c,d,u,h,f,p,g,v,b,m=n.config,_=m.$table.children("tbody"),y=m.extractors,x=m.parsers;if(m.cache={},m.totalRows=0,!x)return m.debug?t("Warning: *Empty table!* Not building a cache"):"";for(m.debug&&(p=new Date),m.showProcessing&&w.isProcessing(n,!0),u=0;u<_.length;u++)if(b=[],a=m.cache[u]={normalized:[]},!_.eq(u).hasClass(m.cssInfoBlock)){for(g=_[u]&&_[u].rows.length||0,c=0;c<g;++c)if(v={child:[]},h=e(_[u].rows[c]),[new Array(m.columns)],f=[],h.hasClass(m.cssChildRow)&&0!==c)r=a.normalized.length-1,a.normalized[r][m.columns].$row=a.normalized[r][m.columns].$row.add(h),h.prev().hasClass(m.cssChildRow)||h.prev().addClass(w.css.cssHasChild),v.child[r]=e.trim(h[0].textContent||h[0].innerText||h.text()||"");else{for(v.$row=h,v.order=c,d=0;d<m.columns;++d)void 0!==x[d]?(r=s(n,h[0].cells[d],d),o=void 0===y[d].id?r:y[d].format(r,n,h[0].cells[d],d),l="no-parser"===x[d].id?"":x[d].format(o,n,h[0].cells[d],d),f.push(m.ignoreCase&&"string"==typeof l?l.toLowerCase():l),"numeric"===(x[d].type||"").toLowerCase()&&(b[d]=Math.max(Math.abs(l)||0,b[d]||0))):m.debug&&t("No parser found for cell:",h[0].cells[d],"does it have a header?");f[m.columns]=v,a.normalized.push(f)}a.colMax=b,m.totalRows+=a.normalized.length}m.showProcessing&&w.isProcessing(n),m.debug&&i("Building cache for "+g+" rows",p)}function l(t,s){var a,r,o,l,c,d,u,h=t.config,f=h.widgetOptions,p=t.tBodies,g=[],v=h.cache;if(n(v))return h.appender?h.appender(t,g):t.isUpdating?h.$table.trigger("updateComplete",t):"";for(h.debug&&(u=new Date),d=0;d<p.length;d++)if((o=e(p[d])).length&&!o.hasClass(h.cssInfoBlock)){for(l=w.processTbody(t,o,!0),r=(a=v[d].normalized).length,c=0;c<r;c++)g.push(a[c][h.columns].$row),h.appender&&(!h.pager||h.pager.removeRows&&f.pager_removeRows||h.pager.ajax)||l.append(a[c][h.columns].$row);w.processTbody(t,l,!1)}h.appender&&h.appender(t,g),h.debug&&i("Rebuilt table",u),s||h.appender||w.applyWidget(t),t.isUpdating&&h.$table.trigger("updateComplete",t)}function c(e){return/^d/i.test(e)||1===e}function d(n){var s,a,r,o,l,d,u,f=n.config;f.headerList=[],f.headerContent=[],f.debug&&(u=new Date),f.columns=w.computeColumnIndex(f.$table.children("thead, tfoot").children("tr")),o=f.cssIcon?'<i class="'+(f.cssIcon===w.css.icon?w.css.icon:f.cssIcon+" "+w.css.icon)+'"></i>':"",f.$headers=e(n).find(f.selectorHeaders).each(function(t){a=e(this),s=w.getColumnData(n,f.headers,t,!0),f.headerContent[t]=e(this).html(),l=f.headerTemplate.replace(/\{content\}/g,e(this).html()).replace(/\{icon\}/g,o),f.onRenderTemplate&&(r=f.onRenderTemplate.apply(a,[t,l]))&&"string"==typeof r&&(l=r),e(this).html('<div class="'+w.css.headerIn+'">'+l+"</div>"),f.onRenderHeader&&f.onRenderHeader.apply(a,[t]),this.column=parseInt(e(this).attr("data-column"),10),this.order=c(w.getData(a,s,"sortInitialOrder")||f.sortInitialOrder)?[1,0,2]:[0,1,2],this.count=-1,this.lockedOrder=!1,void 0!==(d=w.getData(a,s,"lockedOrder")||!1)&&!1!==d&&(this.order=this.lockedOrder=c(d)?[1,1,1]:[0,0,0]),a.addClass(w.css.header+" "+f.cssHeader),f.headerList[t]=this,a.parent().addClass(w.css.headerRow+" "+f.cssHeaderRow).attr("role","row"),f.tabIndex&&a.attr("tabindex",0)}).attr({scope:"col",role:"columnheader"}),h(n),f.debug&&(i("Built headers:",u),t(f.$headers))}function u(e,t,i){var n=e.config;n.$table.find(n.selectorRemove).remove(),r(e),o(e),m(n.$table,t,i)}function h(t){var i,n,s,a=t.config;a.$headers.each(function(r,o){n=e(o),s=w.getColumnData(t,a.headers,r,!0),i="false"===w.getData(o,s,"sorter")||"false"===w.getData(o,s,"parser"),o.sortDisabled=i,n[i?"addClass":"removeClass"]("sorter-false").attr("aria-disabled",""+i),t.id&&(i?n.removeAttr("aria-controls"):n.attr("aria-controls",t.id))})}function f(t){var i,n,s,a=t.config,r=a.sortList,o=r.length,l=w.css.sortNone+" "+a.cssNone,c=[w.css.sortAsc+" "+a.cssAsc,w.css.sortDesc+" "+a.cssDesc],d=["ascending","descending"],u=e(t).find("tfoot tr").children().add(a.$extraHeaders).removeClass(c.join(" "));for(a.$headers.removeClass(c.join(" ")).addClass(l).attr("aria-sort","none"),n=0;n<o;n++)if(2!==r[n][1]&&(i=a.$headers.not(".sorter-false").filter('[data-column="'+r[n][0]+'"]'+(1===o?":last":""))).length){for(s=0;s<i.length;s++)i[s].sortDisabled||i.eq(s).removeClass(l).addClass(c[r[n][1]]).attr("aria-sort",d[r[n][1]]);u.length&&u.filter('[data-column="'+r[n][0]+'"]').removeClass(l).addClass(c[r[n][1]])}a.$headers.not(".sorter-false").each(function(){var t=e(this),i=this.order[(this.count+1)%(a.sortReset?3:2)],n=t.text()+": "+w.language[t.hasClass(w.css.sortAsc)?"sortAsc":t.hasClass(w.css.sortDesc)?"sortDesc":"sortNone"]+w.language[0===i?"nextAsc":1===i?"nextDesc":"nextNone"];t.attr("aria-label",n)})}function p(e,t){return e&&e[t]?e[t].type||"":""}function g(t,i,n){if(t.isUpdating)return setTimeout(function(){g(t,i,n)},50);var s,a,r,o,c,d=t.config,u=!n[d.sortMultiSortKey],h=d.$table;if(h.trigger("sortStart",t),i.count=n[d.sortResetKey]?2:(i.count+1)%(d.sortReset?3:2),d.sortRestart&&(a=i,d.$headers.each(function(){this===a||!u&&e(this).is("."+w.css.sortDesc+",."+w.css.sortAsc)||(this.count=-1)})),a=i.column,u){if(d.sortList=[],null!==d.sortForce)for(s=d.sortForce,r=0;r<s.length;r++)s[r][0]!==a&&d.sortList.push(s[r]);if((o=i.order[i.count])<2&&(d.sortList.push([a,o]),i.colSpan>1))for(r=1;r<i.colSpan;r++)d.sortList.push([a+r,o])}else{if(d.sortAppend&&d.sortList.length>1)for(r=0;r<d.sortAppend.length;r++)(c=w.isValueInArray(d.sortAppend[r][0],d.sortList))>=0&&d.sortList.splice(c,1);if(w.isValueInArray(a,d.sortList)>=0)for(r=0;r<d.sortList.length;r++)c=d.sortList[r],o=d.$headers.filter('[data-column="'+c[0]+'"]:last')[0],c[0]===a&&(c[1]=o.order[i.count],2===c[1]&&(d.sortList.splice(r,1),o.count=-1));else if((o=i.order[i.count])<2&&(d.sortList.push([a,o]),i.colSpan>1))for(r=1;r<i.colSpan;r++)d.sortList.push([a+r,o])}if(null!==d.sortAppend)for(s=d.sortAppend,r=0;r<s.length;r++)s[r][0]!==a&&d.sortList.push(s[r]);h.trigger("sortBegin",t),setTimeout(function(){f(t),v(t),l(t),h.trigger("sortEnd",t)},1)}function v(e){var t,s,a,r,o,l,c,d,u,h,f=0,g=e.config,v=g.textSorter||"",b=g.sortList,m=b.length,_=e.tBodies.length;if(!g.serverSideSorting&&!n(g.cache)){for(g.debug&&(o=new Date),s=0;s<_;s++)l=g.cache[s].colMax,g.cache[s].normalized.sort(function(i,n){for(t=0;t<m;t++){if(r=b[t][0],c=b[t][1],f=0===c,g.sortStable&&i[r]===n[r]&&1===m)return i[g.columns].order-n[g.columns].order;if((a=/n/i.test(p(g.parsers,r)))&&g.strings[r]?(a="boolean"==typeof g.string[g.strings[r]]?(f?1:-1)*(g.string[g.strings[r]]?-1:1):g.strings[r]?g.string[g.strings[r]]||0:0,d=g.numberSorter?g.numberSorter(i[r],n[r],f,l[r],e):w["sortNumeric"+(f?"Asc":"Desc")](i[r],n[r],a,l[r],r,e)):(u=f?i:n,h=f?n:i,d="function"==typeof v?v(u[r],h[r],f,r,e):"object"==typeof v&&v.hasOwnProperty(r)?v[r](u[r],h[r],f,r,e):w["sortNatural"+(f?"Asc":"Desc")](i[r],n[r],r,e,g)),d)return d}return i[g.columns].order-n[g.columns].order});g.debug&&i("Sorting on "+b.toString()+" and dir "+c+" time",o)}}function b(t,i){t[0].isUpdating&&t.trigger("updateComplete"),e.isFunction(i)&&i(t[0])}function m(e,t,i){var n=e[0].config.sortList;!1!==t&&!e[0].isProcessing&&n.length?e.trigger("sorton",[n,function(){b(e,i)},!0]):(b(e,i),w.applyWidget(e[0],!1))}function _(t){var i=t.config,a=i.$table;a.unbind("sortReset update updateRows updateCell updateAll addRows updateComplete sorton appendCache updateCache applyWidgetId applyWidgets refreshWidgets destroy mouseup mouseleave ".split(" ").join(i.namespace+" ")).bind("sortReset"+i.namespace,function(n,s){n.stopPropagation(),i.sortList=[],f(t),v(t),l(t),e.isFunction(s)&&s(t)}).bind("updateAll"+i.namespace,function(e,n,s){e.stopPropagation(),t.isUpdating=!0,w.refreshWidgets(t,!0,!0),w.restoreHeaders(t),d(t),w.bindEvents(t,i.$headers,!0),_(t),u(t,n,s)}).bind("update"+i.namespace+" updateRows"+i.namespace,function(e,i,n){e.stopPropagation(),t.isUpdating=!0,h(t),u(t,i,n)}).bind("updateCell"+i.namespace,function(n,r,o,l){n.stopPropagation(),t.isUpdating=!0,a.find(i.selectorRemove).remove();var c,d,u,h,f=a.find("tbody"),p=e(r),g=f.index(e.fn.closest?p.closest("tbody"):p.parents("tbody").filter(":first")),v=e.fn.closest?p.closest("tr"):p.parents("tr").filter(":first");r=p[0],f.length&&g>=0&&(u=f.eq(g).find("tr").index(v),h=p.index(),i.cache[g].normalized[u][i.columns].$row=v,d=void 0===i.extractors[h].id?s(t,r,h):i.extractors[h].format(s(t,r,h),t,r,h),c="no-parser"===i.parsers[h].id?"":i.parsers[h].format(d,t,r,h),i.cache[g].normalized[u][h]=i.ignoreCase&&"string"==typeof c?c.toLowerCase():c,"numeric"===(i.parsers[h].type||"").toLowerCase()&&(i.cache[g].colMax[h]=Math.max(Math.abs(c)||0,i.cache[g].colMax[h]||0)),m(a,o,l))}).bind("addRows"+i.namespace,function(o,l,c,d){if(o.stopPropagation(),t.isUpdating=!0,n(i.cache))h(t),u(t,c,d);else{var f,p,g,v,b,_,w,y=(l=e(l).attr("role","row")).filter("tr").length,x=a.find("tbody").index(l.parents("tbody").filter(":first"));for(i.parsers&&i.parsers.length||r(t),f=0;f<y;f++){for(g=l[f].cells.length,w=[],_={child:[],$row:l.eq(f),order:i.cache[x].normalized.length},p=0;p<g;p++)v=void 0===i.extractors[p].id?s(t,l[f].cells[p],p):i.extractors[p].format(s(t,l[f].cells[p],p),t,l[f].cells[p],p),b="no-parser"===i.parsers[p].id?"":i.parsers[p].format(v,t,l[f].cells[p],p),w[p]=i.ignoreCase&&"string"==typeof b?b.toLowerCase():b,"numeric"===(i.parsers[p].type||"").toLowerCase()&&(i.cache[x].colMax[p]=Math.max(Math.abs(w[p])||0,i.cache[x].colMax[p]||0));w.push(_),i.cache[x].normalized.push(w)}m(a,c,d)}}).bind("updateComplete"+i.namespace,function(){t.isUpdating=!1}).bind("sorton"+i.namespace,function(i,s,r,c){var d=t.config;i.stopPropagation(),a.trigger("sortStart",this),function(t,i){var n,s,a,r,o,l=t.config,c=i||l.sortList;l.sortList=[],e.each(c,function(t,i){if(r=parseInt(i[0],10),a=l.$headers.filter('[data-column="'+r+'"]:last')[0]){switch(s=(""+i[1]).match(/^(1|d|s|o|n)/),s=s?s[0]:""){case"1":case"d":s=1;break;case"s":s=o||0;break;case"o":n=a.order[(o||0)%(l.sortReset?3:2)],s=0===n?1:1===n?0:2;break;case"n":a.count=a.count+1,s=a.order[a.count%(l.sortReset?3:2)];break;default:s=0}o=0===t?s:o,n=[r,parseInt(s,10)||0],l.sortList.push(n),s=e.inArray(n[1],a.order),a.count=s>=0?s:n[1]%(l.sortReset?3:2)}})}(t,s),f(t),d.delayInit&&n(d.cache)&&o(t),a.trigger("sortBegin",this),v(t),l(t,c),a.trigger("sortEnd",this),w.applyWidget(t),e.isFunction(r)&&r(t)}).bind("appendCache"+i.namespace,function(i,n,s){i.stopPropagation(),l(t,s),e.isFunction(n)&&n(t)}).bind("updateCache"+i.namespace,function(n,s){i.parsers&&i.parsers.length||r(t),o(t),e.isFunction(s)&&s(t)}).bind("applyWidgetId"+i.namespace,function(e,n){e.stopPropagation(),w.getWidgetById(n).format(t,i,i.widgetOptions)}).bind("applyWidgets"+i.namespace,function(e,i){e.stopPropagation(),w.applyWidget(t,i)}).bind("refreshWidgets"+i.namespace,function(e,i,n){e.stopPropagation(),w.refreshWidgets(t,i,n)}).bind("destroy"+i.namespace,function(e,i,n){e.stopPropagation(),w.destroy(t,i,n)}).bind("resetToLoadState"+i.namespace,function(){w.refreshWidgets(t,!0,!0),i=e.extend(!0,w.defaults,i.originalSettings),t.hasInitialized=!1,w.setup(t,i)})}var w=this;w.version="2.17.7",w.parsers=[],w.widgets=[],w.defaults={theme:"default",widthFixed:!1,showProcessing:!1,headerTemplate:"{content}",onRenderTemplate:null,onRenderHeader:null,cancelSelection:!0,tabIndex:!0,dateFormat:"mmddyyyy",sortMultiSortKey:"shiftKey",sortResetKey:"ctrlKey",usNumberFormat:!0,delayInit:!1,serverSideSorting:!1,headers:{},ignoreCase:!0,sortForce:null,sortList:[],sortAppend:null,sortStable:!1,sortInitialOrder:"asc",sortLocaleCompare:!1,sortReset:!1,sortRestart:!1,emptyTo:"bottom",stringTo:"max",textExtraction:"basic",textAttribute:"data-text",textSorter:null,numberSorter:null,widgets:[],widgetOptions:{zebra:["even","odd"]},initWidgets:!0,initialized:null,tableClass:"",cssAsc:"",cssDesc:"",cssNone:"",cssHeader:"",cssHeaderRow:"",cssProcessing:"",cssChildRow:"tablesorter-childRow",cssIcon:"tablesorter-icon",cssInfoBlock:"tablesorter-infoOnly",selectorHeaders:"> thead th, > thead td",selectorSort:"th, td",selectorRemove:".remove-me",debug:!1,headerList:[],empties:{},strings:{},parsers:[]},w.css={table:"tablesorter",cssHasChild:"tablesorter-hasChildRow",childRow:"tablesorter-childRow",header:"tablesorter-header",headerRow:"tablesorter-headerRow",headerIn:"tablesorter-header-inner",icon:"tablesorter-icon",info:"tablesorter-infoOnly",processing:"tablesorter-processing",sortAsc:"tablesorter-headerAsc",sortDesc:"tablesorter-headerDesc",sortNone:"tablesorter-headerUnSorted"},w.language={sortAsc:"Ascending sort applied, ",sortDesc:"Descending sort applied, ",sortNone:"No sort applied, ",nextAsc:"activate to apply an ascending sort",nextDesc:"activate to apply a descending sort",nextNone:"activate to remove the sort"},w.log=t,w.benchmark=i,w.construct=function(t){return this.each(function(){var i=e.extend(!0,{},w.defaults,t);i.originalSettings=t,!this.hasInitialized&&w.buildTable&&"TABLE"!==this.tagName?w.buildTable(this,i):w.setup(this,i)})},w.setup=function(i,n){if(!i||!i.tHead||0===i.tBodies.length||!0===i.hasInitialized)return n.debug?t("ERROR: stopping initialization! No table, thead, tbody or tablesorter has already been initialized"):"";var s="",a=e(i),l=e.metadata;i.hasInitialized=!1,i.isProcessing=!0,i.config=n,e.data(i,"tablesorter",n),n.debug&&e.data(i,"startoveralltimer",new Date),n.supportsDataObject=function(e){return e[0]=parseInt(e[0],10),e[0]>1||1===e[0]&&parseInt(e[1],10)>=4}(e.fn.jquery.split(".")),n.string={max:1,min:-1,emptyMin:1,emptyMax:-1,zero:0,none:0,null:0,top:!0,bottom:!1},/tablesorter\-/.test(a.attr("class"))||(s=""!==n.theme?" tablesorter-"+n.theme:""),n.table=i,n.$table=a.addClass(w.css.table+" "+n.tableClass+s).attr("role","grid"),n.$headers=a.find(n.selectorHeaders),n.namespace?n.namespace="."+n.namespace.replace(/\W/g,""):n.namespace=".tablesorter"+Math.random().toString(16).slice(2),n.$table.children().children("tr").attr("role","row"),n.$tbodies=a.children("tbody:not(."+n.cssInfoBlock+")").attr({"aria-live":"polite","aria-relevant":"all"}),n.$table.find("caption").length&&n.$table.attr("aria-labelledby","theCaption"),n.widgetInit={},n.textExtraction=n.$table.attr("data-text-extraction")||n.textExtraction||"basic",d(i),function(t){if(t.config.widthFixed&&0===e(t).find("colgroup").length){var i=e("<colgroup>"),n=e(t).width();e(t.tBodies[0]).find("tr:first").children(":visible").each(function(){i.append(e("<col>").css("width",parseInt(e(this).width()/n*1e3,10)/10+"%"))}),e(t).prepend(i)}}(i),r(i),n.totalRows=0,n.delayInit||o(i),w.bindEvents(i,n.$headers,!0),_(i),n.supportsDataObject&&void 0!==a.data().sortlist?n.sortList=a.data().sortlist:l&&a.metadata()&&a.metadata().sortlist&&(n.sortList=a.metadata().sortlist),w.applyWidget(i,!0),n.sortList.length>0?a.trigger("sorton",[n.sortList,{},!n.initWidgets,!0]):(f(i),n.initWidgets&&w.applyWidget(i,!1)),n.showProcessing&&a.unbind("sortBegin"+n.namespace+" sortEnd"+n.namespace).bind("sortBegin"+n.namespace+" sortEnd"+n.namespace,function(e){clearTimeout(n.processTimer),w.isProcessing(i),"sortBegin"===e.type&&(n.processTimer=setTimeout(function(){w.isProcessing(i,!0)},500))}),i.hasInitialized=!0,i.isProcessing=!1,n.debug&&w.benchmark("Overall initialization time",e.data(i,"startoveralltimer")),a.trigger("tablesorter-initialized",i),"function"==typeof n.initialized&&n.initialized(i)},w.getColumnData=function(t,i,n,s){if(void 0!==i&&null!==i){var a,r=(t=e(t)[0]).config;if(i[n])return s?i[n]:i[r.$headers.index(r.$headers.filter('[data-column="'+n+'"]:last'))];for(a in i)if("string"==typeof a&&(s?r.$headers.eq(n).filter(a):r.$headers.filter('[data-column="'+n+'"]:last').filter(a)).length)return i[a]}},w.computeColumnIndex=function(t){var i,n,s,a,r,o,l,c,d,u,h,f,p,g=[],v={},b=0;for(i=0;i<t.length;i++)for(l=t[i].cells,n=0;n<l.length;n++){for(o=l[n],r=e(o),d=(c=o.parentNode.rowIndex)+"-"+r.index(),u=o.rowSpan||1,h=o.colSpan||1,void 0===g[c]&&(g[c]=[]),s=0;s<g[c].length+1;s++)if(void 0===g[c][s]){f=s;break}for(v[d]=f,b=Math.max(f,b),r.attr({"data-column":f}),s=c;s<c+u;s++)for(void 0===g[s]&&(g[s]=[]),p=g[s],a=f;a<f+h;a++)p[a]="x"}return b+1},w.isProcessing=function(t,i,n){var s=(t=e(t))[0].config,a=n||t.find("."+w.css.header);i?(void 0!==n&&s.sortList.length>0&&(a=a.filter(function(){return!this.sortDisabled&&w.isValueInArray(parseFloat(e(this).attr("data-column")),s.sortList)>=0})),t.add(a).addClass(w.css.processing+" "+s.cssProcessing)):t.add(a).removeClass(w.css.processing+" "+s.cssProcessing)},w.processTbody=function(t,i,n){t=e(t)[0];var s;if(n)return t.isProcessing=!0,i.before('<span class="tablesorter-savemyplace"/>'),s=e.fn.detach?i.detach():i.remove();s=e(t).find("span.tablesorter-savemyplace"),i.insertAfter(s),s.remove(),t.isProcessing=!1},w.clearTableBody=function(t){e(t)[0].config.$tbodies.children().detach()},w.bindEvents=function(t,i,s){var a,r=(t=e(t)[0]).config;!0!==s&&(r.$extraHeaders=r.$extraHeaders?r.$extraHeaders.add(i):i),i.find(r.selectorSort).add(i.filter(r.selectorSort)).unbind("mousedown mouseup sort keyup ".split(" ").join(r.namespace+" ")).bind("mousedown mouseup sort keyup ".split(" ").join(r.namespace+" "),function(s,l){var c,d=s.type;if(!(1!==(s.which||s.button)&&!/sort|keyup/.test(d)||"keyup"===d&&13!==s.which||"mouseup"===d&&!0!==l&&(new Date).getTime()-a>250)){if("mousedown"===d)return a=(new Date).getTime(),/(input|select|button|textarea)/i.test(s.target.tagName)?"":!r.cancelSelection;r.delayInit&&n(r.cache)&&o(t),c=e.fn.closest?e(this).closest("th, td")[0]:/TH|TD/.test(this.tagName)?this:e(this).parents("th, td")[0],(c=r.$headers[i.index(c)]).sortDisabled||g(t,c,s)}}),r.cancelSelection&&i.attr("unselectable","on").bind("selectstart",!1).css({"user-select":"none",MozUserSelect:"none"})},w.restoreHeaders=function(t){var i=e(t)[0].config;i.$table.find(i.selectorHeaders).each(function(t){e(this).find("."+w.css.headerIn).length&&e(this).html(i.headerContent[t])})},w.destroy=function(t,i,n){if((t=e(t)[0]).hasInitialized){w.refreshWidgets(t,!0,!0);var s=e(t),a=t.config,r=s.find("thead:first"),o=r.find("tr."+w.css.headerRow).removeClass(w.css.headerRow+" "+a.cssHeaderRow),l=s.find("tfoot:first > tr").children("th, td");!1===i&&e.inArray("uitheme",a.widgets)>=0&&(s.trigger("applyWidgetId",["uitheme"]),s.trigger("applyWidgetId",["zebra"])),r.find("tr").not(o).remove(),s.removeData("tablesorter").unbind("sortReset update updateAll updateRows updateCell addRows updateComplete sorton appendCache updateCache applyWidgetId applyWidgets refreshWidgets destroy mouseup mouseleave keypress sortBegin sortEnd resetToLoadState ".split(" ").join(a.namespace+" ")),a.$headers.add(l).removeClass([w.css.header,a.cssHeader,a.cssAsc,a.cssDesc,w.css.sortAsc,w.css.sortDesc,w.css.sortNone].join(" ")).removeAttr("data-column").removeAttr("aria-label").attr("aria-disabled","true"),o.find(a.selectorSort).unbind("mousedown mouseup keypress ".split(" ").join(a.namespace+" ")),w.restoreHeaders(t),s.toggleClass(w.css.table+" "+a.tableClass+" tablesorter-"+a.theme,!1===i),t.hasInitialized=!1,delete t.config.cache,"function"==typeof n&&n(t)}},w.regex={chunk:/(^([+\-]?(?:0|[1-9]\d*)(?:\.\d*)?(?:[eE][+\-]?\d+)?)?$|^0x[0-9a-f]+$|\d+)/gi,chunks:/(^\\0|\\0$)/,hex:/^0x[0-9a-f]+$/i},w.sortNatural=function(e,t){if(e===t)return 0;var i,n,s,a,r,o,l,c,d=w.regex;if(d.hex.test(t)){if(n=parseInt(e.match(d.hex),16),a=parseInt(t.match(d.hex),16),n<a)return-1;if(n>a)return 1}for(i=e.replace(d.chunk,"\\0$1\\0").replace(d.chunks,"").split("\\0"),s=t.replace(d.chunk,"\\0$1\\0").replace(d.chunks,"").split("\\0"),c=Math.max(i.length,s.length),l=0;l<c;l++){if(r=isNaN(i[l])?i[l]||0:parseFloat(i[l])||0,o=isNaN(s[l])?s[l]||0:parseFloat(s[l])||0,isNaN(r)!==isNaN(o))return isNaN(r)?1:-1;if(typeof r!=typeof o&&(r+="",o+=""),r<o)return-1;if(r>o)return 1}return 0},w.sortNaturalAsc=function(e,t,i,n,s){if(e===t)return 0;var a=s.string[s.empties[i]||s.emptyTo];return""===e&&0!==a?"boolean"==typeof a?a?-1:1:-a||-1:""===t&&0!==a?"boolean"==typeof a?a?1:-1:a||1:w.sortNatural(e,t)},w.sortNaturalDesc=function(e,t,i,n,s){if(e===t)return 0;var a=s.string[s.empties[i]||s.emptyTo];return""===e&&0!==a?"boolean"==typeof a?a?-1:1:a||1:""===t&&0!==a?"boolean"==typeof a?a?1:-1:-a||-1:w.sortNatural(t,e)},w.sortText=function(e,t){return e>t?1:e<t?-1:0},w.getTextValue=function(e,t,i){if(i){var n,s=e?e.length:0,a=i+t;for(n=0;n<s;n++)a+=e.charCodeAt(n);return t*a}return 0},w.sortNumericAsc=function(e,t,i,n,s,a){if(e===t)return 0;var r=a.config,o=r.string[r.empties[s]||r.emptyTo];return""===e&&0!==o?"boolean"==typeof o?o?-1:1:-o||-1:""===t&&0!==o?"boolean"==typeof o?o?1:-1:o||1:(isNaN(e)&&(e=w.getTextValue(e,i,n)),isNaN(t)&&(t=w.getTextValue(t,i,n)),e-t)},w.sortNumericDesc=function(e,t,i,n,s,a){if(e===t)return 0;var r=a.config,o=r.string[r.empties[s]||r.emptyTo];return""===e&&0!==o?"boolean"==typeof o?o?-1:1:o||1:""===t&&0!==o?"boolean"==typeof o?o?1:-1:-o||-1:(isNaN(e)&&(e=w.getTextValue(e,i,n)),isNaN(t)&&(t=w.getTextValue(t,i,n)),t-e)},w.sortNumeric=function(e,t){return e-t},w.characterEquivalents={a:"áàâãäąå",A:"ÁÀÂÃÄĄÅ",c:"çćč",C:"ÇĆČ",e:"éèêëěę",E:"ÉÈÊËĚĘ",i:"íìİîïı",I:"ÍÌİÎÏ",o:"óòôõö",O:"ÓÒÔÕÖ",ss:"ß",SS:"ẞ",u:"úùûüů",U:"ÚÙÛÜŮ"},w.replaceAccents=function(e){var t,i="[",n=w.characterEquivalents;if(!w.characterRegex){w.characterRegexArray={};for(t in n)"string"==typeof t&&(i+=n[t],w.characterRegexArray[t]=new RegExp("["+n[t]+"]","g"));w.characterRegex=new RegExp(i+"]")}if(w.characterRegex.test(e))for(t in n)"string"==typeof t&&(e=e.replace(w.characterRegexArray[t],t));return e},w.isValueInArray=function(e,t){var i,n=t.length;for(i=0;i<n;i++)if(t[i][0]===e)return i;return-1},w.addParser=function(e){var t,i=w.parsers.length,n=!0;for(t=0;t<i;t++)w.parsers[t].id.toLowerCase()===e.id.toLowerCase()&&(n=!1);n&&w.parsers.push(e)},w.getParserById=function(e){if("false"==e)return!1;var t,i=w.parsers.length;for(t=0;t<i;t++)if(w.parsers[t].id.toLowerCase()===e.toString().toLowerCase())return w.parsers[t];return!1},w.addWidget=function(e){w.widgets.push(e)},w.hasWidget=function(t,i){return(t=e(t)).length&&t[0].config&&t[0].config.widgetInit[i]||!1},w.getWidgetById=function(e){var t,i,n=w.widgets.length;for(t=0;t<n;t++)if((i=w.widgets[t])&&i.hasOwnProperty("id")&&i.id.toLowerCase()===e.toLowerCase())return i},w.applyWidget=function(t,n){var s,a,r,o=(t=e(t)[0]).config,l=o.widgetOptions,c=[];!1!==n&&t.hasInitialized&&(t.isApplyingWidgets||t.isUpdating)||(o.debug&&(s=new Date),o.widgets.length&&(t.isApplyingWidgets=!0,o.widgets=e.grep(o.widgets,function(t,i){return e.inArray(t,o.widgets)===i}),e.each(o.widgets||[],function(e,t){(r=w.getWidgetById(t))&&r.id&&(r.priority||(r.priority=10),c[e]=r)}),c.sort(function(e,t){return e.priority<t.priority?-1:e.priority===t.priority?0:1}),e.each(c,function(i,s){s&&(!n&&o.widgetInit[s.id]||(o.widgetInit[s.id]=!0,s.hasOwnProperty("options")&&(l=t.config.widgetOptions=e.extend(!0,{},s.options,l)),s.hasOwnProperty("init")&&s.init(t,s,o,l)),!n&&s.hasOwnProperty("format")&&s.format(t,o,l,!1))})),setTimeout(function(){t.isApplyingWidgets=!1},0),o.debug&&(a=o.widgets.length,i("Completed "+(!0===n?"initializing ":"applying ")+a+" widget"+(1!==a?"s":""),s)))},w.refreshWidgets=function(i,n,s){var a,r=(i=e(i)[0]).config,o=r.widgets,l=w.widgets,c=l.length;for(a=0;a<c;a++)l[a]&&l[a].id&&(n||e.inArray(l[a].id,o)<0)&&(r.debug&&t('Refeshing widgets: Removing "'+l[a].id+'"'),l[a].hasOwnProperty("remove")&&r.widgetInit[l[a].id]&&(l[a].remove(i,r,r.widgetOptions),r.widgetInit[l[a].id]=!1));!0!==s&&w.applyWidget(i,n)},w.getData=function(t,i,n){var s,a,r="",o=e(t);return o.length?(s=!!e.metadata&&o.metadata(),a=" "+(o.attr("class")||""),void 0!==o.data(n)||void 0!==o.data(n.toLowerCase())?r+=o.data(n)||o.data(n.toLowerCase()):s&&void 0!==s[n]?r+=s[n]:i&&void 0!==i[n]?r+=i[n]:" "!==a&&a.match(" "+n+"-")&&(r=a.match(new RegExp("\\s"+n+"-([\\w-]+)"))[1]||""),e.trim(r)):""},w.formatFloat=function(t,i){if("string"!=typeof t||""===t)return t;var n;return t=(i&&i.config?!1!==i.config.usNumberFormat:void 0===i||i)?t.replace(/,/g,""):t.replace(/[\s|\.]/g,"").replace(/,/g,"."),/^\s*\([.\d]+\)/.test(t)&&(t=t.replace(/^\s*\(([.\d]+)\)/,"-$1")),n=parseFloat(t),isNaN(n)?e.trim(t):n},w.isDigit=function(e){return!isNaN(e)||/^[\-+(]?\d+[)]?$/.test(e.toString().replace(/[,.'"\s]/g,""))}}});var t=e.tablesorter;e.fn.extend({tablesorter:t.construct}),t.addParser({id:"no-parser",is:function(){return!1},format:function(){return""},type:"text"}),t.addParser({id:"text",is:function(){return!0},format:function(i,n){var s=n.config;return i&&(i=e.trim(s.ignoreCase?i.toLocaleLowerCase():i),i=s.sortLocaleCompare?t.replaceAccents(i):i),i},type:"text"}),t.addParser({id:"digit",is:function(e){return t.isDigit(e)},format:function(i,n){var s=t.formatFloat((i||"").replace(/[^\w,. \-()]/g,""),n);return i&&"number"==typeof s?s:i?e.trim(i&&n.config.ignoreCase?i.toLocaleLowerCase():i):i},type:"numeric"}),t.addParser({id:"currency",is:function(e){return/^\(?\d+[\u00a3$\u20ac\u00a4\u00a5\u00a2?.]|[\u00a3$\u20ac\u00a4\u00a5\u00a2?.]\d+\)?$/.test((e||"").replace(/[+\-,. ]/g,""))},format:function(i,n){var s=t.formatFloat((i||"").replace(/[^\w,. \-()]/g,""),n);return i&&"number"==typeof s?s:i?e.trim(i&&n.config.ignoreCase?i.toLocaleLowerCase():i):i},type:"numeric"}),t.addParser({id:"ipAddress",is:function(e){return/^\d{1,3}[\.]\d{1,3}[\.]\d{1,3}[\.]\d{1,3}$/.test(e)},format:function(e,i){var n,s=e?e.split("."):"",a="",r=s.length;for(n=0;n<r;n++)a+=("00"+s[n]).slice(-3);return e?t.formatFloat(a,i):e},type:"numeric"}),t.addParser({id:"url",is:function(e){return/^(https?|ftp|file):\/\//.test(e)},format:function(t){return t?e.trim(t.replace(/(https?|ftp|file):\/\//,"")):t},type:"text"}),t.addParser({id:"isoDate",is:function(e){return/^\d{4}[\/\-]\d{1,2}[\/\-]\d{1,2}/.test(e)},format:function(e,i){return e?t.formatFloat(""!==e?new Date(e.replace(/-/g,"/")).getTime()||e:"",i):e},type:"numeric"}),t.addParser({id:"percent",is:function(e){return/(\d\s*?%|%\s*?\d)/.test(e)&&e.length<15},format:function(e,i){return e?t.formatFloat(e.replace(/%/g,""),i):e},type:"numeric"}),t.addParser({id:"usLongDate",is:function(e){return/^[A-Z]{3,10}\.?\s+\d{1,2},?\s+(\d{4})(\s+\d{1,2}:\d{2}(:\d{2})?(\s+[AP]M)?)?$/i.test(e)||/^\d{1,2}\s+[A-Z]{3,10}\s+\d{4}/i.test(e)},format:function(e,i){return e?t.formatFloat(new Date(e.replace(/(\S)([AP]M)$/i,"$1 $2")).getTime()||e,i):e},type:"numeric"}),t.addParser({id:"shortDate",is:function(e){return/(^\d{1,2}[\/\s]\d{1,2}[\/\s]\d{4})|(^\d{4}[\/\s]\d{1,2}[\/\s]\d{1,2})/.test((e||"").replace(/\s+/g," ").replace(/[\-.,]/g,"/"))},format:function(e,i,n,s){if(e){var a=i.config,r=a.$headers.filter("[data-column="+s+"]:last"),o=r.length&&r[0].dateFormat||t.getData(r,t.getColumnData(i,a.headers,s),"dateFormat")||a.dateFormat;e=e.replace(/\s+/g," ").replace(/[\-.,]/g,"/"),"mmddyyyy"===o?e=e.replace(/(\d{1,2})[\/\s](\d{1,2})[\/\s](\d{4})/,"$3/$1/$2"):"ddmmyyyy"===o?e=e.replace(/(\d{1,2})[\/\s](\d{1,2})[\/\s](\d{4})/,"$3/$2/$1"):"yyyymmdd"===o&&(e=e.replace(/(\d{4})[\/\s](\d{1,2})[\/\s](\d{1,2})/,"$1/$2/$3"))}return e?t.formatFloat(new Date(e).getTime()||e,i):e},type:"numeric"}),t.addParser({id:"time",is:function(e){return/^(([0-2]?\d:[0-5]\d)|([0-1]?\d:[0-5]\d\s?([AP]M)))$/i.test(e)},format:function(e,i){return e?t.formatFloat(new Date("2000/01/01 "+e.replace(/(\S)([AP]M)$/i,"$1 $2")).getTime()||e,i):e},type:"numeric"}),t.addParser({id:"metadata",is:function(){return!1},format:function(t,i,n){var s=i.config,a=s.parserMetadataName?s.parserMetadataName:"sortValue";return e(n).metadata()[a]},type:"numeric"}),t.addWidget({id:"zebra",priority:90,format:function(i,n,s){var a,r,o,l,c,d,u=new RegExp(n.cssChildRow,"i"),h=n.$tbodies;for(n.debug&&(c=new Date),d=0;d<h.length;d++)(a=h.eq(d)).children("tr").length>1&&(o=0,a.children("tr:visible").not(n.selectorRemove).each(function(){r=e(this),u.test(this.className)||o++,l=o%2==0,r.removeClass(s.zebra[l?1:0]).addClass(s.zebra[l?0:1])}));n.debug&&t.benchmark("Applying Zebra widget",c)},remove:function(t,i,n){var s,a,r=i.$tbodies,o=(n.zebra||["even","odd"]).join(" ");for(s=0;s<r.length;s++)(a=e.tablesorter.processTbody(t,r.eq(s),!0)).children().removeClass(o),e.tablesorter.processTbody(t,a,!1)}})}(jQuery),e}.call(this),("undefined"==typeof window?global:window).__86af8679b628c527ca168de38761335d=function(){function e(e){return e&&e.__esModule?e:{default:e}}function t(e){var t=r;e.find("th").each(function(e,i){var n=(0,s.default)(i);t.headers[e]={},n.hasClass("aui-table-column-unsortable")?t.headers[e].sorter=!1:(n.attr("tabindex","0"),n.wrapInner("<span class='aui-table-header-content'/>"),n.hasClass("aui-table-column-issue-key")&&(t.headers[e].sorter="issue-key"))}),e.tablesorter(t)}var i={exports:{}},n=i.exports;Object.defineProperty(n,"__esModule",{value:!0});var s=e(__ce09c80fb835cb76cda82f0f0d4a1ea3);__040e46c8a552bd6d1dd4f4764a88f2b2;var a=e(__2bc1a6edbc312083fbf11f878f780e28),r={sortMultiSortKey:"",headers:{},debug:!1,tabIndex:!1},o={setup:function(){s.default.tablesorter.addParser({id:"issue-key",is:function(){return!1},format:function(e){var t=e.split("-"),i=t[0],n=t[1],s=(i+"..........").slice(0,"..........".length);return s+=("000000"+n).slice(-"000000".length)},type:"text"}),s.default.tablesorter.addParser({id:"textSortAttributeParser",is:function(e,t,i){return i.hasAttribute("data-sort-value")&&(!i.hasAttribute("data-sort-type")||"text"===i.getAttribute("data-sort-type"))},format:function(e,t,i,n){return i.getAttribute("data-sort-value")},type:"text"}),s.default.tablesorter.addParser({id:"numericSortAttributeParser",is:function(e,t,i){return"numeric"===i.getAttribute("data-sort-type")&&i.hasAttribute("data-sort-value")},format:function(e,t,i,n){return i.getAttribute("data-sort-value")},type:"numeric"}),(0,s.default)(".aui-table-sortable").each(function(){t((0,s.default)(this))})},setTableSortable:function(e){t(e)}};return(0,s.default)(o.setup),(0,a.default)("tablessortable",o),n.default=o,i.exports=n.default,i.exports}.call(this),("undefined"==typeof window?global:window).__c99ab7328684c522781f6bf7fa62c92e=function(){var e={};return __86b584d7b2dca6d114205bd2e5d490d7,e}.call(this),("undefined"==typeof window?global:window).__bcb30073b1b4ce797bf3fc36fbdcd2b9=function(){function e(e){return e&&e.__esModule?e:{default:e}}function t(e){e.dispatchEvent(new CustomEvent("change",{bubbles:!0}))}function i(e){return e._input||(e._input=e.querySelector("input"))}function n(e,t){i(t).removeAttribute(e)}function s(e,t,n){i(t).setAttribute(e,n.newValue)}function a(e){return{removed:n.bind(this,e),fallback:s.bind(this,e)}}var r={};__2befe9148812946d2d69bd201cebc09f,__a294568ce889e2dee24779703d6be870;var o=__a7c54527eaa6ce7e8d0f0eae333c90b8,l=e(__ce09c80fb835cb76cda82f0f0d4a1ea3),c=e(__502b59e357a07cdf19c6edc9cbaa8719),d=e(__4850ac7f6e93ba35f83ca6803a088772),u=e(__f33ac309b94c246736966ea50a11b323),h=e(__7a6521db1039cb333e437aa8031353cf),f=__e4e1727c26af0a5037c104d27c13c775,p={removed:function(e){n.call(this,"form",e),e._formId=null},fallback:function(e,t){s.call(this,"form",e,t),e._formId=t.newValue}},g={removed:n.bind(void 0,"id"),fallback:function(e,t){i(e).setAttribute("id",""+t.newValue+f.INPUT_SUFFIX)}},v={removed:function(e){n.call(this,"checked",e),i(e).checked=!1,t(e)},fallback:function(e,n){var a=i(e),r=!a.hasAttribute("checked");s.call(this,"checked",e,n),a.checked=!0,r&&t(e)}},b={removed:function(e){i(e).removeAttribute("aria-label")},fallback:function(e,t){i(e).setAttribute("aria-label",t.newValue)}};return(0,h.default)("aui-toggle",{template:(0,u.default)('<input type="checkbox" class="aui-toggle-input assistive">','<span class="aui-toggle-view">','<span class="aui-toggle-tick aui-icon aui-icon-small aui-iconfont-success"></span>','<span class="aui-toggle-cross aui-icon aui-icon-small aui-iconfont-close-dialog"></span>',"</span>"),created:function(e){e._input=i(e),e._tick=e.querySelector(".aui-toggle-tick"),e._cross=e.querySelector(".aui-toggle-cross"),(0,l.default)(e._input).tooltip({title:function(){return this.checked?this.getAttribute("tooltip-on"):this.getAttribute("tooltip-off")},gravity:"s",hoverable:!1}),function(e){e._input.addEventListener("keydown",function(t){e.busy&&t.keyCode===d.default.SPACE&&t.preventDefault()}),navigator.userAgent.toLowerCase().indexOf("firefox")>-1&&e._input.addEventListener("click",function(t){e.busy&&t.preventDefault()})}(e)},attached:function(e){(0,c.default)(e).attributeExists("label")},events:{click:function(e,t){e.disabled||e.busy||t.target===e._input||(e._input.checked=!e._input.checked),(0,o.setBooleanAttribute)(e,"checked",i(e).checked)}},attributes:{id:g,checked:v,disabled:a("disabled"),form:p,name:a("name"),value:a("value"),"tooltip-on":{value:AJS.I18n.getText("aui.toggle.on"),fallback:function(e,t){i(e).setAttribute("tooltip-on",t.newValue||AJS.I18n.getText("aui.toggle.on"))}},"tooltip-off":{value:AJS.I18n.getText("aui.toggle.off"),fallback:function(e,t){i(e).setAttribute("tooltip-off",t.newValue||AJS.I18n.getText("aui.toggle.off"))}},label:b},prototype:{focus:function(){return this._input.focus(),this},get checked(){return this._input.checked},set checked(e){this._input.checked!==e&&(this._input.checked=e,(0,o.setBooleanAttribute)(this,"checked",e))},get disabled(){return this._input.disabled},set disabled(e){return(0,o.setBooleanAttribute)(this,"disabled",e)},get form(){return document.getElementById(this._formId)},set form(e){return p.fallback.call(this,this,{newValue:e||null}),this.form},get name(){return this._input.name},set name(e){return this.setAttribute("name",e),e},get value(){return this._input.value},set value(e){return this.setAttribute("value",null===e?"":e),e},get busy(){return"true"===this._input.getAttribute("aria-busy")},set busy(e){return(0,o.setBooleanAttribute)(this,"busy",e),e?(this._input.setAttribute("aria-busy","true"),this._input.indeterminate=!0,this.checked?((0,l.default)(this._input).addClass("indeterminate-checked"),(0,l.default)(this._tick).spin({zIndex:null})):(0,l.default)(this._cross).spin({zIndex:null,color:"black"})):((0,l.default)(this._input).removeClass("indeterminate-checked"),this._input.indeterminate=!1,this._input.removeAttribute("aria-busy"),(0,l.default)(this._cross).spinStop(),(0,l.default)(this._tick).spinStop()),function(e,t){e.id&&Array.prototype.forEach.call(document.querySelectorAll('aui-label[for="'+e.id+'"]'),function(e){e.disabled=t})}(this,!!e),e}}}),r}.call(this),("undefined"==typeof window?global:window).__f73b36c9c760188802fc48b158d3c951=function(){function e(e){return e&&e.__esModule?e:{default:e}}function t(e,t){if(e.isEnabled()){var i=function(e){return document.getElementById(e.getAttribute("aria-controls"))}(e);i&&i.message&&i.message(t)}}var i={},n=e(__ce09c80fb835cb76cda82f0f0d4a1ea3),s=e(__fb114d9b531e09c60f5fdf12262b017c),a=e(__7a6521db1039cb333e437aa8031353cf);return(0,a.default)("data-aui-trigger",{type:a.default.type.ATTRIBUTE,events:{click:function(e,i){(function(e,t){var i=(0,n.default)(t).closest("a[href]",e);return!!i.length&&i[0]!==e})(e,i.target)||(t(e,i),i.preventDefault())},mouseenter:function(e,i){t(e,i)},mouseleave:function(e,i){t(e,i)},focus:function(e,i){t(e,i)},blur:function(e,i){t(e,i)}},prototype:{disable:function(){this.setAttribute("aria-disabled","true")},enable:function(){this.setAttribute("aria-disabled","false")},isEnabled:function(){return"true"!==this.getAttribute("aria-disabled")}}}),(0,s.default)("aui/trigger"),i}.call(this),("undefined"==typeof window?global:window).__9b3652e710e54f45b656bf5e68fe3c92=function(){function e(e){return e&&e.__esModule?e:{default:e}}var t={exports:{}},i=t.exports;Object.defineProperty(i,"__esModule",{value:!0});var n=e(__2bc1a6edbc312083fbf11f878f780e28),s=e(__c290b536f781d38fd8310af686be11a9),a=s.default.extend({initialize:function(e,t){this._maxResponseSize=t.maxResponseSize,s.default.prototype.initialize.call(this,e,t)},shouldGetMoreResults:function(e){var t=this.findQueryResponse(this.value);return!t||t.length===this._maxResponseSize},findQueryResponse:function(e){for(;e;){var t=this.findQueryCache(e);if(t)return t;e=e.substr(0,e.length-1)}return null}});return(0,n.default)("TruncatingProgressiveDataSet",a),i.default=a,t.exports=i.default,t.exports}.call(this),("undefined"==typeof window?global:window).__9caa3d73f3aec10fb53e71583e61e037=function(){var e={exports:{}},t=e.exports;return Object.defineProperty(t,"__esModule",{value:!0}),__07e029149e7b50ff5008626a55c0874d,__c6ad19cff937f24a9e7543bca33f8b40,__a6e1673bb01a22322ef9341042944d0a,__854c952394699e4cd7993f3206d22691,__25f6ecd120c36f98f80013c17563c5e4,__e99a1d9cad8cc3c3d6710c33f4f366db,__021e9cff0ae14087301bfc6bbcd8d193,__4bb68509831c5889ca4df930402a1328,__67491bb3bce20d8f91c94f98d7717c17,__3e1b3de594cf0afb3ff875e48b0a233b,__c290b536f781d38fd8310af686be11a9,__a18bab3d6582ccd64c009f3a6d64da2a,__b4462e3facf827e782aaf2b356c13a33,__35286d201a93212a1713fc328bf98228,__c9b0155d89690eb9270f409840e010bf,__a938c1843453a31c15c5deff68fc45ea,__e94988ffdda50ffba5e53ee4664a2df6,__ced4da26b0960c7d9748908b0665dba7,__09cfaea3351d49ebebff7a3070bb6ffe,__2befe9148812946d2d69bd201cebc09f,__86af8679b628c527ca168de38761335d,__c99ab7328684c522781f6bf7fa62c92e,__bcb30073b1b4ce797bf3fc36fbdcd2b9,__a294568ce889e2dee24779703d6be870,__f73b36c9c760188802fc48b158d3c951,__9b3652e710e54f45b656bf5e68fe3c92,t.default=window.AJS,e.exports=t.default,e.exports}.call(this);
"""Module containing helpers for dealing with GitHub Apps. https://developer.github.com/apps/building-github-apps/ """ import time from jwcrypto import jwk from jwcrypto import jwt from . import models from . import users TEN_MINUTES_AS_SECONDS = 10 * 60 DEFAULT_JWT_TOKEN_EXPIRATION = TEN_MINUTES_AS_SECONDS APP_PREVIEW_HEADERS = {"Accept": "application/vnd.github.machine-man-preview+json"} class App(models.GitHubCore): """An object representing a GitHub App. .. versionadded:: 1.2.0 .. seealso:: `GitHub Apps`_ Documentation for Apps on GitHub `GitHub Apps API Documentation`_ API documentation of what's available about an App. This object has the following attributes: .. attribute:: created_at A :class:`~datetime.datetime` object representing the day and time the App was created. .. attribute:: description The description of the App provided by the owner. .. attribute:: external_url The URL provided for the App by the owner. .. attribute:: html_url The HTML URL provided for the App by the owner. .. attribute:: id The unique identifier for the App. This is useful in cases where you may want to authenticate either as an App or as a specific installation of an App. .. attribute:: name The display name of the App that the user sees. .. attribute:: node_id A base64-encoded blob returned by the GitHub API for who knows what reason. .. attribute:: owner A :class:`~github4.users.ShortUser` object representing the GitHub user who owns the App. github4 .. attribute:: updated_at A :class:`~datetime.datetime` object representing the day and time the App was last updated. .. _GitHub Apps: https://developer.github.com/apps/ .. _GitHub Apps API Documentation: https://developer.github.com/v3/apps/ """ CUSTOM_HEADERS = {"Accept": "application/vnd.github.machine-man-preview+json"} def _update_attributes(self, json): self.created_at = self._strptime(json["created_at"]) self.description = json["description"] self.external_url = json["external_url"] self.html_url = json["html_url"] self.id = json["id"] self.name = json["name"] self.node_id = json["node_id"] self.owner = users.ShortUser(json["owner"], self) self.updated_at = self._strptime(json["updated_at"]) _, slug = json["html_url"].rsplit("/", 1) self._api = self.url = self._build_url("apps", slug) def _repr(self): return '<App ["{}" by {}]>'.format(self.name, str(self.owner)) class Installation(models.GitHubCore): """An installation of a GitHub App either on a User or Org. .. versionadded:: 1.2.0 This has the following attributes: .. attribute:: access_tokens_url .. attribute:: account .. attribute:: app_id .. attribute:: created_at .. attribute:: events .. attribute:: html_url .. attribute:: id .. attribute:: permissions .. attribute:: repositories_url .. attribute:: repository_selection .. attribute:: single_file_name .. attribute:: target_id .. attribute:: target_type .. attribute:: updated_at """ def _update_attributes(self, json): self.access_tokens_url = json["access_tokens_url"] self.account = json["account"] self.app_id = json["app_id"] self.created_at = self._strptime(json["created_at"]) self.events = json["events"] self.html_url = json["html_url"] self.id = json["id"] self.permissions = json["permissions"] self.repositories_url = json["repositories_url"] self.repository_selection = json["repository_selection"] self.single_file_name = json["single_file_name"] self.target_id = json["target_id"] self.target_type = json["target_type"] self.updated_at = self._strptime(json["updated_at"]) def _load_private_key(pem_key_bytes): return jwk.JWK.from_pem(pem_key_bytes) def create_token(private_key_pem, app_id, expire_in=TEN_MINUTES_AS_SECONDS): """Create an encrypted token for the specified App. :param bytes private_key_pem: The bytes of the private key for this GitHub Application. :param int app_id: The integer identifier for this GitHub Application. :param int expire_in: The length in seconds for this token to be valid for. Default: 600 seconds (10 minutes) :returns: Serialized encrypted token. :rtype: text """ if not isinstance(private_key_pem, bytes): raise ValueError('"private_key_pem" parameter must be byte-string') key = _load_private_key(private_key_pem) now = int(time.time()) token = jwt.JWT( header={"alg": "RS256"}, claims={"iat": now, "exp": now + expire_in, "iss": app_id}, algs=["RS256"], ) token.make_signed_token(key) return token.serialize() def create_jwt_headers(private_key_pem, app_id, expire_in=DEFAULT_JWT_TOKEN_EXPIRATION): """Create an encrypted token for the specified App. :param bytes private_key_pem: The bytes of the private key for this GitHub Application. :param int app_id: The integer identifier for this GitHub Application. :param int expire_in: The length in seconds for this token to be valid for. Default: 600 seconds (10 minutes) :returns: Dictionary of headers for retrieving a token from a JWT. :rtype: dict """ jwt_token = create_token(private_key_pem, app_id, expire_in) headers = {"Authorization": "Bearer {}".format(jwt_token)} headers.update(APP_PREVIEW_HEADERS) return headers
import emoji import math import random print(emoji.emojize("Olá Mojao :heartbeat:", use_aliases=True)) print(emoji.emojize("sorriso :grinning:", use_aliases=True)) print(emoji.emojize("beijo :kissing:", use_aliases=True)) #num=float(input("Digite um numero: ")) #num2=float(input("digit um numero: ")) #num3=math.floor(num/num2) #print('a divisão do numero 1 pelo numero 2 vale: ',num3) #num=float(input("digite um numero: ")) #num2=float(input("digit um numero: ")) #num3=(num**2)+(num2**2) #print("o valor da hiotenusa desses catetos vale : {}".format(num3**(1/2))) #n=random.randint(1,4) #print('O aluno sorteado para ler o quadro foi: aluno {}'.format(n))# #ang=float(input('Digite o valor de um angulo:')) #angu=math.radians(ang) #print('O valor do seno é: {:.2f} e do cosseno: {:.2f}'.format(math.sin(angu), math.cos(angu))) n1=str(input('Nome do aluno: ')) n2=str(input('Nome do aluno: ')) n3=str(input('Nome do aluno: ')) n4=str(input('Nome do aluno: ')) Lista=[n1,n2,n3,n4] random.shuffle(Lista) print('A ordem e: ',Lista) n=random.choice(Lista) print('O nome escolhido foi ',n)
/* Template Name: Uplon - Responsive Bootstrap 4 Admin Dashboard Author: CoderThemes Version: 2.0.0 Website: https://coderthemes.com/ Contact: support@coderthemes.com File: Morris chart init js */ !function($) { "use strict"; var MorrisCharts = function() {}; //creates line chart MorrisCharts.prototype.createLineChart = function(element, data, xkey, ykeys, labels, opacity, Pfillcolor, Pstockcolor, lineColors) { Morris.Line({ element: element, data: data, xkey: xkey, ykeys: ykeys, labels: labels, fillOpacity: opacity, pointFillColors: Pfillcolor, pointStrokeColors: Pstockcolor, behaveLikeLine: true, gridLineColor: 'rgba(108, 120, 151, 0.1)', hideHover: 'auto', lineWidth: '3px', pointSize: 0, preUnits: '$', resize: true, //defaulted to true lineColors: lineColors }); }, //creates area chart MorrisCharts.prototype.createAreaChart = function(element, pointSize, lineWidth, data, xkey, ykeys, labels, lineColors) { Morris.Area({ element: element, pointSize: 0, lineWidth: 0, data: data, xkey: xkey, ykeys: ykeys, labels: labels, hideHover: 'auto', resize: true, gridLineColor: 'rgba(108, 120, 151, 0.1)', lineColors: lineColors }); }, //creates area chart with dotted MorrisCharts.prototype.createAreaChartDotted = function(element, pointSize, lineWidth, data, xkey, ykeys, labels, Pfillcolor, Pstockcolor, lineColors) { Morris.Area({ element: element, pointSize: 3, lineWidth: 1, data: data, xkey: xkey, ykeys: ykeys, labels: labels, hideHover: 'auto', pointFillColors: Pfillcolor, pointStrokeColors: Pstockcolor, resize: true, gridLineColor: 'rgba(108, 120, 151, 0.1)', lineColors: lineColors }); }, //creates Bar chart MorrisCharts.prototype.createBarChart = function(element, data, xkey, ykeys, labels, lineColors) { Morris.Bar({ element: element, data: data, xkey: xkey, ykeys: ykeys, labels: labels, hideHover: 'auto', resize: true, //defaulted to true gridLineColor: 'rgba(108, 120, 151, 0.1)', barSizeRatio: 0.4, xLabelAngle: 35, barColors: lineColors }); }, //creates Stacked chart MorrisCharts.prototype.createStackedChart = function(element, data, xkey, ykeys, labels, lineColors) { Morris.Bar({ element: element, data: data, xkey: xkey, ykeys: ykeys, stacked: true, labels: labels, hideHover: 'auto', resize: true, //defaulted to true gridLineColor: 'rgba(108, 120, 151, 0.1)', barColors: lineColors }); }, //creates Donut chart MorrisCharts.prototype.createDonutChart = function(element, data, colors) { Morris.Donut({ element: element, data: data, resize: true, //defaulted to true // backgroundColor: 'transparent', colors: colors }); }, MorrisCharts.prototype.init = function() { //create line chart var $data = [ { y: '2008', a: 50, b: 0 }, { y: '2009', a: 75, b: 50 }, { y: '2010', a: 30, b: 80 }, { y: '2011', a: 50, b: 50 }, { y: '2012', a: 75, b: 10 }, { y: '2013', a: 50, b: 40 }, { y: '2014', a: 75, b: 50 }, { y: '2015', a: 100, b: 70 } ]; this.createLineChart('morris-line-example', $data, 'y', ['a', 'b'], ['Series A', 'Series B'],['0.1'],['#ffffff'],['#999999'], ['#1bb99a', '#f1b53d']); //creating area chart var $areaData = [ { y: '2009', a: 10, b: 20 }, { y: '2010', a: 75, b: 65 }, { y: '2011', a: 50, b: 40 }, { y: '2012', a: 75, b: 65 }, { y: '2013', a: 50, b: 40 }, { y: '2014', a: 75, b: 65 }, { y: '2015', a: 90, b: 60 } ]; this.createAreaChart('morris-area-example', 0, 0, $areaData, 'y', ['a', 'b'], ['Series A', 'Series B'], ['#3db9dc', "#039cfd"]); //creating area chart with dotted var $areaDotData = [ { y: '2009', a: 10, b: 20 }, { y: '2010', a: 75, b: 65 }, { y: '2011', a: 50, b: 40 }, { y: '2012', a: 75, b: 65 }, { y: '2013', a: 50, b: 40 }, { y: '2014', a: 75, b: 65 }, { y: '2015', a: 90, b: 60 } ]; this.createAreaChartDotted('morris-area-with-dotted', 0, 0, $areaDotData, 'y', ['a', 'b'], ['Series A', 'Series B'],['#ffffff'],['#999999'], ['#9261c6', "#ff7aa3"]); //creating bar chart var $barData = [ { y: '2009', a: 100, b: 90 , c: 40 }, { y: '2010', a: 75, b: 65 , c: 20 }, { y: '2011', a: 50, b: 40 , c: 50 }, { y: '2012', a: 75, b: 65 , c: 95 }, { y: '2013', a: 50, b: 40 , c: 22 }, { y: '2014', a: 75, b: 65 , c: 56 }, { y: '2015', a: 100, b: 90 , c: 60 } ]; this.createBarChart('morris-bar-example', $barData, 'y', ['a', 'b', 'c'], ['Series A', 'Series B', 'Series C'], ['#3db9dc', '#f1b53d', "#ff5d48"]); //creating Stacked chart var $stckedData = [ { y: '2005', a: 45, b: 180 }, { y: '2006', a: 75, b: 65 }, { y: '2007', a: 100, b: 90 }, { y: '2008', a: 75, b: 65 }, { y: '2009', a: 100, b: 90 }, { y: '2010', a: 75, b: 65 }, { y: '2011', a: 50, b: 40 }, { y: '2012', a: 75, b: 65 }, { y: '2013', a: 50, b: 40 }, { y: '2014', a: 75, b: 65 }, { y: '2015', a: 100, b: 90 } ]; this.createStackedChart('morris-bar-stacked', $stckedData, 'y', ['a', 'b'], ['Series A', 'Series B'], ['#3db9dc', '#ebeff2']); //creating donut chart var $donutData = [ {label: "Series A", value: 12}, {label: "Series B", value: 30}, {label: "Series C", value: 20} ]; this.createDonutChart('morris-donut-example', $donutData, ['#f1b53d', '#9261c6', "#ff7aa3"]); }, //init $.MorrisCharts = new MorrisCharts, $.MorrisCharts.Constructor = MorrisCharts }(window.jQuery), //initializing function($) { "use strict"; $.MorrisCharts.init(); }(window.jQuery);
/* global describe, it */ var pkg = require('..'); var expect = require('chai').expect; describe('oauth2orize-crossorigin', function() { it('should export hello world', function() { expect(pkg.hello).to.equal('world'); }); });
#!/usr/bin/env python from setuptools import setup, find_packages TEST_REQUIRES = [ 'flexmock>=0.9.7', 'nose', 'coverage' ] INSTALL_REQUIRES = [ 'requests>=1.0.0', 'pycrypto>=2.5', 'python-dateutil>=1.5' ] setup( name='uber.py', version='1.0.3', author='Tal Shiri', author_email='eiopaa@gmail.com', url='http://github.com/tals/uber.py', description='Python client for Uber', long_description=__doc__, packages=find_packages(exclude=("tests", "tests.*",)), zip_safe=False, extras_require={ 'tests': TEST_REQUIRES, }, license='MIT', tests_require=TEST_REQUIRES, install_requires=INSTALL_REQUIRES, test_suite='tests', include_package_data=True, entry_points={ 'console_scripts': [ 'ubercli = examples.ubercli:main', ] }, classifiers=[ 'Intended Audience :: Developers', 'Operating System :: OS Independent', 'Topic :: Software Development', 'Programming Language :: Python', 'Programming Language :: Python :: 2.7', ], )
/* Based on Urban by TEMPLATED templated.co @templatedco Released for free under the Creative Commons Attribution 3.0 license (templated.co/license) */ (function($) { skel.breakpoints({ xlarge: '(max-width: 1680px)', large: '(max-width: 1280px)', medium: '(max-width: 980px)', small: '(max-width: 736px)', xsmall: '(max-width: 480px)' }); $(function() { var $window = $(window), $body = $('body'), $header = $('#header'), $banner = $('#banner'); // Disable animations/transitions until the page has loaded. $body.addClass('is-loading'); $window.on('load', function() { window.setTimeout(function() { $body.removeClass('is-loading'); }, 100); }); // Fix: Placeholder polyfill. $('form').placeholder(); // Prioritize "important" elements on medium. skel.on('+medium -medium', function() { $.prioritize( '.important\\28 medium\\29', skel.breakpoint('medium').active ); }); // Menu. $('#menu') .append('<a href="#menu" class="close"></a>') .appendTo($body) .panel({ delay: 500, hideOnClick: true, hideOnSwipe: true, resetScroll: true, resetForms: true, side: 'right' }); // Header. if (skel.vars.IEVersion < 9) $header.removeClass('alt'); if ($banner.length > 0 && $header.hasClass('alt')) { $window.on('resize', function() { $window.trigger('scroll'); }); $banner.scrollex({ bottom: $header.outerHeight(), terminate: function() { $header.removeClass('alt'); }, enter: function() { $header.addClass('alt'); }, leave: function() { $header.removeClass('alt'); $header.addClass('reveal'); } }); } // Banner. var $banner = $('#banner'); if ($banner.length > 0) { // IE fix. if (skel.vars.IEVersion < 12) { $window.on('resize', function() { var wh = $window.height() * 0.60, bh = $banner.height(); $banner.css('height', 'auto'); window.setTimeout(function() { if (bh < wh) $banner.css('height', wh + 'px'); }, 0); }); $window.on('load', function() { $window.triggerHandler('resize'); }); } // Video check. var video = $banner.data('video'); if (video) $window.on('load.banner', function() { // Disable banner load event (so it doesn't fire again). $window.off('load.banner'); // Append video if supported. if (!skel.vars.mobile && !skel.breakpoint('large').active && skel.vars.IEVersion > 9) $banner.append('<video autoplay loop><source src="' + video + '.mp4" type="video/mp4" /><source src="' + video + '.webm" type="video/webm" /></video>'); }); // More button. $banner.find('.more') .addClass('scrolly'); } // Tabs. $('.flex-tabs').each( function() { var t = jQuery(this), tab = t.find('.tab-list li a'), tabs = t.find('.tab'); tab.click(function(e) { var x = jQuery(this), y = x.data('tab'); // Set Classes on Tabs tab.removeClass('active'); x.addClass('active'); // Show/Hide Tab Content tabs.removeClass('active'); t.find('.' + y).addClass('active'); e.preventDefault(); }); }); // Scrolly. $('.scrolly').scrolly({ offset: function() { return $header.height() - 2; } }); }); })(jQuery);
try: from html import escape except ImportError: from cgi import escape from braintree.apple_pay_options import ApplePayOptions from braintree.error_result import ErrorResult from braintree.successful_result import SuccessfulResult from braintree.exceptions.unexpected_error import UnexpectedError class ApplePayGateway(object): def __init__(self, gateway): self.gateway = gateway self.config = gateway.config def register_domain(self, domain): response = self.config.http().post(self.config.base_merchant_path() + "/processing/apple_pay/validate_domains", {'url': domain}) if "response" in response and response["response"]["success"]: return SuccessfulResult() elif response["api_error_response"]: return ErrorResult(self.gateway, response["api_error_response"]) def unregister_domain(self, domain): self.config.http().delete(self.config.base_merchant_path() + "/processing/apple_pay/unregister_domain?url=" + escape(domain)) return SuccessfulResult() def registered_domains(self): response = self.config.http().get(self.config.base_merchant_path() + "/processing/apple_pay/registered_domains") if "response" in response: response = ApplePayOptions(response.pop("response")) return response.domains
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import storages.backends.s3boto import users.models class Migration(migrations.Migration): dependencies = [ ('users', '0018_auto_20160406_1016'), ] operations = [ migrations.AlterField( model_name='user', name='resume', field=models.FileField(storage=storages.backends.s3boto.S3BotoStorage(querystring_expire=600, bucket=b'proven-cc', querystring_auth=True, acl=b'private'), null=True, upload_to=users.models._get_resume_upload_path), preserve_default=True, ), ]
# ------------------------------------------------------------------------ # Copyright (c) 2021 4669 (for eccv submission only). All Rights Reserved. # ------------------------------------------------------------------------ # Modified from Deformable DETR (https://github.com/fundamentalvision/Deformable-DETR) # Copyright (c) 2020 SenseTime. All Rights Reserved. # ------------------------------------------------------------------------ # Modified from DETR (https://github.com/facebookresearch/detr) # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved # ------------------------------------------------------------------------ """ MOT dataset which returns image_id for evaluation. """ from pathlib import Path import cv2 import numpy as np import torch import torch.utils.data import os.path as osp from PIL import Image, ImageDraw import copy import datasets.transforms as T from models.structures import Instances class DetMOTDetection: def __init__(self, args, data_txt_path: str, seqs_folder, transforms): self.args = args self._transforms = transforms self.num_frames_per_batch = max(args.sampler_lengths) self.sample_mode = args.sample_mode self.sample_interval = args.sample_interval self.vis = args.vis self.video_dict = {} with open(data_txt_path, 'r') as file: self.img_files = file.readlines() self.img_files = [osp.join(seqs_folder, x.strip()) for x in self.img_files] self.img_files = list(filter(lambda x: len(x) > 0, self.img_files)) self.label_files = [(x.replace('images', 'labels_with_ids').replace('.png', '.txt').replace('.jpg', '.txt')) for x in self.img_files] # The number of images per sample: 1 + (num_frames - 1) * interval. # The number of valid samples: num_images - num_image_per_sample + 1. self.item_num = len(self.img_files) - (self.num_frames_per_batch - 1) * self.sample_interval self._register_videos() # video sampler. self.sampler_steps: list = args.sampler_steps self.lengths: list = args.sampler_lengths print("sampler_steps={} lenghts={}".format(self.sampler_steps, self.lengths)) if self.sampler_steps is not None and len(self.sampler_steps) > 0: # Enable sampling length adjustment. assert len(self.lengths) > 0 assert len(self.lengths) == len(self.sampler_steps) + 1 for i in range(len(self.sampler_steps) - 1): assert self.sampler_steps[i] < self.sampler_steps[i + 1] self.item_num = len(self.img_files) - (self.lengths[-1] - 1) * self.sample_interval self.period_idx = 0 self.num_frames_per_batch = self.lengths[0] self.current_epoch = 0 def _register_videos(self): for label_name in self.label_files: video_name = '/'.join(label_name.split('/')[:-1]) if video_name not in self.video_dict: print("register {}-th video: {} ".format(len(self.video_dict) + 1, video_name)) self.video_dict[video_name] = len(self.video_dict) assert len(self.video_dict) <= 300 def set_epoch(self, epoch): self.current_epoch = epoch if self.sampler_steps is None or len(self.sampler_steps) == 0: # fixed sampling length. return for i in range(len(self.sampler_steps)): if epoch >= self.sampler_steps[i]: self.period_idx = i + 1 print("set epoch: epoch {} period_idx={}".format(epoch, self.period_idx)) self.num_frames_per_batch = self.lengths[self.period_idx] def step_epoch(self): # one epoch finishes. print("Dataset: epoch {} finishes".format(self.current_epoch)) self.set_epoch(self.current_epoch + 1) @staticmethod def _targets_to_instances(targets: dict, img_shape) -> Instances: gt_instances = Instances(tuple(img_shape)) gt_instances.boxes = targets['boxes'] gt_instances.labels = targets['labels'] gt_instances.obj_ids = targets['obj_ids'] gt_instances.area = targets['area'] return gt_instances def _pre_single_frame(self, idx: int): img_path = self.img_files[idx].replace('.jpg', '.png') label_path = self.label_files[idx] img = Image.open(img_path) targets = {} w, h = img._size assert w > 0 and h > 0, "invalid image {} with shape {} {}".format(img_path, w, h) if osp.isfile(label_path): labels0 = np.loadtxt(label_path, dtype=np.float32).reshape(-1, 6) # normalized cewh to pixel xyxy format labels = labels0.copy() labels[:, 2] = w * (labels0[:, 2] - labels0[:, 4] / 2) labels[:, 3] = h * (labels0[:, 3] - labels0[:, 5] / 2) labels[:, 4] = w * (labels0[:, 2] + labels0[:, 4] / 2) labels[:, 5] = h * (labels0[:, 3] + labels0[:, 5] / 2) else: raise ValueError('invalid label path: {}'.format(label_path)) video_name = '/'.join(label_path.split('/')[:-1]) obj_idx_offset = self.video_dict[video_name] * 100000 # 100000 unique ids is enough for a video. targets['boxes'] = [] targets['area'] = [] targets['iscrowd'] = [] targets['labels'] = [] targets['obj_ids'] = [] targets['image_id'] = torch.as_tensor(idx) targets['size'] = torch.as_tensor([h, w]) targets['orig_size'] = torch.as_tensor([h, w]) for label in labels: targets['boxes'].append(label[2:6].tolist()) targets['area'].append(label[4] * label[5]) targets['iscrowd'].append(0) targets['labels'].append(0) obj_id = label[1] + obj_idx_offset if label[1] >= 0 else label[1] targets['obj_ids'].append(obj_id) # relative id targets['area'] = torch.as_tensor(targets['area']) targets['iscrowd'] = torch.as_tensor(targets['iscrowd']) targets['labels'] = torch.as_tensor(targets['labels']) targets['obj_ids'] = torch.as_tensor(targets['obj_ids']) targets['boxes'] = torch.as_tensor(targets['boxes'], dtype=torch.float32).reshape(-1, 4) targets['boxes'][:, 0::2].clamp_(min=0, max=w) targets['boxes'][:, 1::2].clamp_(min=0, max=h) return img, targets def _get_sample_range(self, start_idx): # take default sampling method for normal dataset. assert self.sample_mode in ['fixed_interval', 'random_interval'], 'invalid sample mode: {}'.format(self.sample_mode) if self.sample_mode == 'fixed_interval': sample_interval = self.sample_interval elif self.sample_mode == 'random_interval': sample_interval = np.random.randint(1, self.sample_interval + 1) default_range = start_idx, start_idx + (self.num_frames_per_batch - 1) * sample_interval + 1, sample_interval return default_range def pre_continuous_frames(self, idx): targets = [] images = [] # repeat current img and target for twice for i in range(self.num_frames_per_batch): img_i, targets_i = self._pre_single_frame(idx) images.append(img_i) targets.append(targets_i) return images, targets def __getitem__(self, idx): images, targets = self.pre_continuous_frames(idx) data = {} if self._transforms is not None: images, targets = self._transforms(images, targets) gt_instances = [] for img_i, targets_i in zip(images, targets): gt_instances_i = self._targets_to_instances(targets_i, img_i.shape[1:3]) gt_instances.append(gt_instances_i) data.update({ 'imgs': images, 'gt_instances': gt_instances, }) if self.args.vis: data['ori_img'] = [target_i['ori_img'] for target_i in targets] return data def __len__(self): return self.item_num class DetMOTDetectionValidation(DetMOTDetection): def __init__(self, args, seqs_folder, transforms): args.data_txt_path = args.val_data_txt_path super().__init__(args, seqs_folder, transforms) def make_detmot_transforms(image_set, args=None): normalize = T.MotCompose([ T.MotToTensor(), T.MotNormalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]) ]) scales = [608, 640, 672, 704, 736, 768, 800, 832, 864, 896, 928, 960, 992] if image_set == 'train': color_transforms = [] if args.cj: print('Training with RandomColorJitter.') color_transforms.append(T.MoTColorJitter(brightness=0.5, contrast=0.5, saturation=0.5, hue=0)) if not args.crop: scale_transforms = [ T.MotRandomHorizontalFlip(), T.FixedMotRandomShift(bs=1), T.MotRandomResize(scales, max_size=1536), normalize, ] else: print('Training with RandomCrop.') scale_transforms = [ T.MotRandomHorizontalFlip(), T.FixedMotRandomShift(bs=1), T.MotRandomSelect( T.MotRandomResize(scales, max_size=1536), T.MotCompose([ T.MotRandomResize([400, 500, 600]), T.FixedMotRandomCrop(384, 600), T.MotRandomResize(scales, max_size=1536), ]) ), normalize, ] return T.MotCompose(color_transforms + scale_transforms) if image_set == 'val': return T.MotCompose([ T.MotRandomResize([800], max_size=1536), normalize, ]) raise ValueError(f'unknown {image_set}') def build(image_set, args): root = Path(args.mot_path) assert root.exists(), f'provided MOT path {root} does not exist' transforms = make_detmot_transforms(image_set, args) if image_set == 'train': data_txt_path = args.data_txt_path_train dataset = DetMOTDetection(args, data_txt_path=data_txt_path, seqs_folder=root, transforms=transforms) if image_set == 'val': data_txt_path = args.data_txt_path_val dataset = DetMOTDetection(args, data_txt_path=data_txt_path, seqs_folder=root, transforms=transforms) return dataset
import { CommonModule } from '@angular/common'; import { Component, ViewEncapsulation, ChangeDetectionStrategy, ElementRef, Directive, ChangeDetectorRef, Optional, ContentChildren, ContentChild, forwardRef, Inject, ViewChild, Input, EventEmitter, Attribute, Output, NgModule } from '@angular/core'; import { mixinDisableRipple, setLines, MatLine, MatLineModule, MatRippleModule, MatCommonModule, MatPseudoCheckboxModule } from '@angular/material/core'; import { Subject } from 'rxjs'; import { takeUntil } from 'rxjs/operators'; import { FocusKeyManager } from '@angular/cdk/a11y'; import { coerceBooleanProperty } from '@angular/cdk/coercion'; import { SelectionModel } from '@angular/cdk/collections'; import { hasModifierKey, A, END, HOME, ENTER, SPACE, UP_ARROW, DOWN_ARROW } from '@angular/cdk/keycodes'; import { NG_VALUE_ACCESSOR } from '@angular/forms'; import { MatDividerModule } from '@angular/material/divider'; /** * @fileoverview added by tsickle * Generated from: src/material/list/list.ts * @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc */ // Boilerplate for applying mixins to MatList. /** * \@docs-private */ import * as ɵngcc0 from '@angular/core'; import * as ɵngcc1 from '@angular/material/core'; const _c0 = ["*"]; const _c1 = [[["", "mat-list-avatar", ""], ["", "mat-list-icon", ""], ["", "matListAvatar", ""], ["", "matListIcon", ""]], [["", "mat-line", ""], ["", "matLine", ""]], "*"]; const _c2 = ["[mat-list-avatar], [mat-list-icon], [matListAvatar], [matListIcon]", "[mat-line], [matLine]", "*"]; const _c3 = ["text"]; const _c4 = ["*", [["", "mat-list-avatar", ""], ["", "mat-list-icon", ""], ["", "matListAvatar", ""], ["", "matListIcon", ""]]]; const _c5 = ["*", "[mat-list-avatar], [mat-list-icon], [matListAvatar], [matListIcon]"]; class MatListBase { } /** @type {?} */ const _MatListMixinBase = mixinDisableRipple(MatListBase); // Boilerplate for applying mixins to MatListItem. /** * \@docs-private */ class MatListItemBase { } /** @type {?} */ const _MatListItemMixinBase = mixinDisableRipple(MatListItemBase); class MatNavList extends _MatListMixinBase { constructor() { super(...arguments); /** * Emits when the state of the list changes. */ this._stateChanges = new Subject(); } /** * @return {?} */ ngOnChanges() { this._stateChanges.next(); } /** * @return {?} */ ngOnDestroy() { this._stateChanges.complete(); } } MatNavList.ɵfac = function MatNavList_Factory(t) { return ɵMatNavList_BaseFactory(t || MatNavList); }; MatNavList.ɵcmp = ɵngcc0.ɵɵdefineComponent({ type: MatNavList, selectors: [["mat-nav-list"]], hostAttrs: ["role", "navigation", 1, "mat-nav-list", "mat-list-base"], inputs: { disableRipple: "disableRipple" }, exportAs: ["matNavList"], features: [ɵngcc0.ɵɵInheritDefinitionFeature, ɵngcc0.ɵɵNgOnChangesFeature], ngContentSelectors: _c0, decls: 1, vars: 0, template: function MatNavList_Template(rf, ctx) { if (rf & 1) { ɵngcc0.ɵɵprojectionDef(); ɵngcc0.ɵɵprojection(0); } }, styles: [".mat-subheader{display:flex;box-sizing:border-box;padding:16px;align-items:center}.mat-list-base .mat-subheader{margin:0}.mat-list-base{padding-top:8px;display:block;-webkit-tap-highlight-color:transparent}.mat-list-base .mat-subheader{height:48px;line-height:16px}.mat-list-base .mat-subheader:first-child{margin-top:-8px}.mat-list-base .mat-list-item,.mat-list-base .mat-list-option{display:block;height:48px;-webkit-tap-highlight-color:transparent;width:100%;padding:0}.mat-list-base .mat-list-item .mat-list-item-content,.mat-list-base .mat-list-option .mat-list-item-content{display:flex;flex-direction:row;align-items:center;box-sizing:border-box;padding:0 16px;position:relative;height:inherit}.mat-list-base .mat-list-item .mat-list-item-content-reverse,.mat-list-base .mat-list-option .mat-list-item-content-reverse{display:flex;align-items:center;padding:0 16px;flex-direction:row-reverse;justify-content:space-around}.mat-list-base .mat-list-item .mat-list-item-ripple,.mat-list-base .mat-list-option .mat-list-item-ripple{top:0;left:0;right:0;bottom:0;position:absolute;pointer-events:none}.mat-list-base .mat-list-item.mat-list-item-with-avatar,.mat-list-base .mat-list-option.mat-list-item-with-avatar{height:56px}.mat-list-base .mat-list-item.mat-2-line,.mat-list-base .mat-list-option.mat-2-line{height:72px}.mat-list-base .mat-list-item.mat-3-line,.mat-list-base .mat-list-option.mat-3-line{height:88px}.mat-list-base .mat-list-item.mat-multi-line,.mat-list-base .mat-list-option.mat-multi-line{height:auto}.mat-list-base .mat-list-item.mat-multi-line .mat-list-item-content,.mat-list-base .mat-list-option.mat-multi-line .mat-list-item-content{padding-top:16px;padding-bottom:16px}.mat-list-base .mat-list-item .mat-list-text,.mat-list-base .mat-list-option .mat-list-text{display:flex;flex-direction:column;width:100%;box-sizing:border-box;overflow:hidden;padding:0}.mat-list-base .mat-list-item .mat-list-text>*,.mat-list-base .mat-list-option .mat-list-text>*{margin:0;padding:0;font-weight:normal;font-size:inherit}.mat-list-base .mat-list-item .mat-list-text:empty,.mat-list-base .mat-list-option .mat-list-text:empty{display:none}.mat-list-base .mat-list-item.mat-list-item-with-avatar .mat-list-item-content .mat-list-text,.mat-list-base .mat-list-item.mat-list-option .mat-list-item-content .mat-list-text,.mat-list-base .mat-list-option.mat-list-item-with-avatar .mat-list-item-content .mat-list-text,.mat-list-base .mat-list-option.mat-list-option .mat-list-item-content .mat-list-text{padding-right:0;padding-left:16px}[dir=rtl] .mat-list-base .mat-list-item.mat-list-item-with-avatar .mat-list-item-content .mat-list-text,[dir=rtl] .mat-list-base .mat-list-item.mat-list-option .mat-list-item-content .mat-list-text,[dir=rtl] .mat-list-base .mat-list-option.mat-list-item-with-avatar .mat-list-item-content .mat-list-text,[dir=rtl] .mat-list-base .mat-list-option.mat-list-option .mat-list-item-content .mat-list-text{padding-right:16px;padding-left:0}.mat-list-base .mat-list-item.mat-list-item-with-avatar .mat-list-item-content-reverse .mat-list-text,.mat-list-base .mat-list-item.mat-list-option .mat-list-item-content-reverse .mat-list-text,.mat-list-base .mat-list-option.mat-list-item-with-avatar .mat-list-item-content-reverse .mat-list-text,.mat-list-base .mat-list-option.mat-list-option .mat-list-item-content-reverse .mat-list-text{padding-left:0;padding-right:16px}[dir=rtl] .mat-list-base .mat-list-item.mat-list-item-with-avatar .mat-list-item-content-reverse .mat-list-text,[dir=rtl] .mat-list-base .mat-list-item.mat-list-option .mat-list-item-content-reverse .mat-list-text,[dir=rtl] .mat-list-base .mat-list-option.mat-list-item-with-avatar .mat-list-item-content-reverse .mat-list-text,[dir=rtl] .mat-list-base .mat-list-option.mat-list-option .mat-list-item-content-reverse .mat-list-text{padding-right:0;padding-left:16px}.mat-list-base .mat-list-item.mat-list-item-with-avatar.mat-list-option .mat-list-item-content-reverse .mat-list-text,.mat-list-base .mat-list-item.mat-list-item-with-avatar.mat-list-option .mat-list-item-content .mat-list-text,.mat-list-base .mat-list-option.mat-list-item-with-avatar.mat-list-option .mat-list-item-content-reverse .mat-list-text,.mat-list-base .mat-list-option.mat-list-item-with-avatar.mat-list-option .mat-list-item-content .mat-list-text{padding-right:16px;padding-left:16px}.mat-list-base .mat-list-item .mat-list-avatar,.mat-list-base .mat-list-option .mat-list-avatar{flex-shrink:0;width:40px;height:40px;border-radius:50%;object-fit:cover}.mat-list-base .mat-list-item .mat-list-avatar~.mat-divider-inset,.mat-list-base .mat-list-option .mat-list-avatar~.mat-divider-inset{margin-left:72px;width:calc(100% - 72px)}[dir=rtl] .mat-list-base .mat-list-item .mat-list-avatar~.mat-divider-inset,[dir=rtl] .mat-list-base .mat-list-option .mat-list-avatar~.mat-divider-inset{margin-left:auto;margin-right:72px}.mat-list-base .mat-list-item .mat-list-icon,.mat-list-base .mat-list-option .mat-list-icon{flex-shrink:0;width:24px;height:24px;font-size:24px;box-sizing:content-box;border-radius:50%;padding:4px}.mat-list-base .mat-list-item .mat-list-icon~.mat-divider-inset,.mat-list-base .mat-list-option .mat-list-icon~.mat-divider-inset{margin-left:64px;width:calc(100% - 64px)}[dir=rtl] .mat-list-base .mat-list-item .mat-list-icon~.mat-divider-inset,[dir=rtl] .mat-list-base .mat-list-option .mat-list-icon~.mat-divider-inset{margin-left:auto;margin-right:64px}.mat-list-base .mat-list-item .mat-divider,.mat-list-base .mat-list-option .mat-divider{position:absolute;bottom:0;left:0;width:100%;margin:0}[dir=rtl] .mat-list-base .mat-list-item .mat-divider,[dir=rtl] .mat-list-base .mat-list-option .mat-divider{margin-left:auto;margin-right:0}.mat-list-base .mat-list-item .mat-divider.mat-divider-inset,.mat-list-base .mat-list-option .mat-divider.mat-divider-inset{position:absolute}.mat-list-base[dense]{padding-top:4px;display:block}.mat-list-base[dense] .mat-subheader{height:40px;line-height:8px}.mat-list-base[dense] .mat-subheader:first-child{margin-top:-4px}.mat-list-base[dense] .mat-list-item,.mat-list-base[dense] .mat-list-option{display:block;height:40px;-webkit-tap-highlight-color:transparent;width:100%;padding:0}.mat-list-base[dense] .mat-list-item .mat-list-item-content,.mat-list-base[dense] .mat-list-option .mat-list-item-content{display:flex;flex-direction:row;align-items:center;box-sizing:border-box;padding:0 16px;position:relative;height:inherit}.mat-list-base[dense] .mat-list-item .mat-list-item-content-reverse,.mat-list-base[dense] .mat-list-option .mat-list-item-content-reverse{display:flex;align-items:center;padding:0 16px;flex-direction:row-reverse;justify-content:space-around}.mat-list-base[dense] .mat-list-item .mat-list-item-ripple,.mat-list-base[dense] .mat-list-option .mat-list-item-ripple{top:0;left:0;right:0;bottom:0;position:absolute;pointer-events:none}.mat-list-base[dense] .mat-list-item.mat-list-item-with-avatar,.mat-list-base[dense] .mat-list-option.mat-list-item-with-avatar{height:48px}.mat-list-base[dense] .mat-list-item.mat-2-line,.mat-list-base[dense] .mat-list-option.mat-2-line{height:60px}.mat-list-base[dense] .mat-list-item.mat-3-line,.mat-list-base[dense] .mat-list-option.mat-3-line{height:76px}.mat-list-base[dense] .mat-list-item.mat-multi-line,.mat-list-base[dense] .mat-list-option.mat-multi-line{height:auto}.mat-list-base[dense] .mat-list-item.mat-multi-line .mat-list-item-content,.mat-list-base[dense] .mat-list-option.mat-multi-line .mat-list-item-content{padding-top:16px;padding-bottom:16px}.mat-list-base[dense] .mat-list-item .mat-list-text,.mat-list-base[dense] .mat-list-option .mat-list-text{display:flex;flex-direction:column;width:100%;box-sizing:border-box;overflow:hidden;padding:0}.mat-list-base[dense] .mat-list-item .mat-list-text>*,.mat-list-base[dense] .mat-list-option .mat-list-text>*{margin:0;padding:0;font-weight:normal;font-size:inherit}.mat-list-base[dense] .mat-list-item .mat-list-text:empty,.mat-list-base[dense] .mat-list-option .mat-list-text:empty{display:none}.mat-list-base[dense] .mat-list-item.mat-list-item-with-avatar .mat-list-item-content .mat-list-text,.mat-list-base[dense] .mat-list-item.mat-list-option .mat-list-item-content .mat-list-text,.mat-list-base[dense] .mat-list-option.mat-list-item-with-avatar .mat-list-item-content .mat-list-text,.mat-list-base[dense] .mat-list-option.mat-list-option .mat-list-item-content .mat-list-text{padding-right:0;padding-left:16px}[dir=rtl] .mat-list-base[dense] .mat-list-item.mat-list-item-with-avatar .mat-list-item-content .mat-list-text,[dir=rtl] .mat-list-base[dense] .mat-list-item.mat-list-option .mat-list-item-content .mat-list-text,[dir=rtl] .mat-list-base[dense] .mat-list-option.mat-list-item-with-avatar .mat-list-item-content .mat-list-text,[dir=rtl] .mat-list-base[dense] .mat-list-option.mat-list-option .mat-list-item-content .mat-list-text{padding-right:16px;padding-left:0}.mat-list-base[dense] .mat-list-item.mat-list-item-with-avatar .mat-list-item-content-reverse .mat-list-text,.mat-list-base[dense] .mat-list-item.mat-list-option .mat-list-item-content-reverse .mat-list-text,.mat-list-base[dense] .mat-list-option.mat-list-item-with-avatar .mat-list-item-content-reverse .mat-list-text,.mat-list-base[dense] .mat-list-option.mat-list-option .mat-list-item-content-reverse .mat-list-text{padding-left:0;padding-right:16px}[dir=rtl] .mat-list-base[dense] .mat-list-item.mat-list-item-with-avatar .mat-list-item-content-reverse .mat-list-text,[dir=rtl] .mat-list-base[dense] .mat-list-item.mat-list-option .mat-list-item-content-reverse .mat-list-text,[dir=rtl] .mat-list-base[dense] .mat-list-option.mat-list-item-with-avatar .mat-list-item-content-reverse .mat-list-text,[dir=rtl] .mat-list-base[dense] .mat-list-option.mat-list-option .mat-list-item-content-reverse .mat-list-text{padding-right:0;padding-left:16px}.mat-list-base[dense] .mat-list-item.mat-list-item-with-avatar.mat-list-option .mat-list-item-content-reverse .mat-list-text,.mat-list-base[dense] .mat-list-item.mat-list-item-with-avatar.mat-list-option .mat-list-item-content .mat-list-text,.mat-list-base[dense] .mat-list-option.mat-list-item-with-avatar.mat-list-option .mat-list-item-content-reverse .mat-list-text,.mat-list-base[dense] .mat-list-option.mat-list-item-with-avatar.mat-list-option .mat-list-item-content .mat-list-text{padding-right:16px;padding-left:16px}.mat-list-base[dense] .mat-list-item .mat-list-avatar,.mat-list-base[dense] .mat-list-option .mat-list-avatar{flex-shrink:0;width:36px;height:36px;border-radius:50%;object-fit:cover}.mat-list-base[dense] .mat-list-item .mat-list-avatar~.mat-divider-inset,.mat-list-base[dense] .mat-list-option .mat-list-avatar~.mat-divider-inset{margin-left:68px;width:calc(100% - 68px)}[dir=rtl] .mat-list-base[dense] .mat-list-item .mat-list-avatar~.mat-divider-inset,[dir=rtl] .mat-list-base[dense] .mat-list-option .mat-list-avatar~.mat-divider-inset{margin-left:auto;margin-right:68px}.mat-list-base[dense] .mat-list-item .mat-list-icon,.mat-list-base[dense] .mat-list-option .mat-list-icon{flex-shrink:0;width:20px;height:20px;font-size:20px;box-sizing:content-box;border-radius:50%;padding:4px}.mat-list-base[dense] .mat-list-item .mat-list-icon~.mat-divider-inset,.mat-list-base[dense] .mat-list-option .mat-list-icon~.mat-divider-inset{margin-left:60px;width:calc(100% - 60px)}[dir=rtl] .mat-list-base[dense] .mat-list-item .mat-list-icon~.mat-divider-inset,[dir=rtl] .mat-list-base[dense] .mat-list-option .mat-list-icon~.mat-divider-inset{margin-left:auto;margin-right:60px}.mat-list-base[dense] .mat-list-item .mat-divider,.mat-list-base[dense] .mat-list-option .mat-divider{position:absolute;bottom:0;left:0;width:100%;margin:0}[dir=rtl] .mat-list-base[dense] .mat-list-item .mat-divider,[dir=rtl] .mat-list-base[dense] .mat-list-option .mat-divider{margin-left:auto;margin-right:0}.mat-list-base[dense] .mat-list-item .mat-divider.mat-divider-inset,.mat-list-base[dense] .mat-list-option .mat-divider.mat-divider-inset{position:absolute}.mat-nav-list a{text-decoration:none;color:inherit}.mat-nav-list .mat-list-item{cursor:pointer;outline:none}mat-action-list button{background:none;color:inherit;border:none;font:inherit;outline:inherit;-webkit-tap-highlight-color:transparent;text-align:left}[dir=rtl] mat-action-list button{text-align:right}mat-action-list button::-moz-focus-inner{border:0}mat-action-list .mat-list-item{cursor:pointer;outline:inherit}.mat-list-option:not(.mat-list-item-disabled){cursor:pointer;outline:none}.cdk-high-contrast-active .mat-selection-list:focus{outline-style:dotted}.cdk-high-contrast-active .mat-list-option:hover,.cdk-high-contrast-active .mat-list-option:focus,.cdk-high-contrast-active .mat-nav-list .mat-list-item:hover,.cdk-high-contrast-active .mat-nav-list .mat-list-item:focus,.cdk-high-contrast-active mat-action-list .mat-list-item:hover,.cdk-high-contrast-active mat-action-list .mat-list-item:focus{outline:dotted 1px}@media(hover: none){.mat-list-option:not(.mat-list-item-disabled):hover,.mat-nav-list .mat-list-item:not(.mat-list-item-disabled):hover,.mat-action-list .mat-list-item:not(.mat-list-item-disabled):hover{background:none}}\n"], encapsulation: 2, changeDetection: 0 }); const ɵMatNavList_BaseFactory = ɵngcc0.ɵɵgetInheritedFactory(MatNavList); /*@__PURE__*/ (function () { ɵngcc0.ɵsetClassMetadata(MatNavList, [{ type: Component, args: [{ selector: 'mat-nav-list', exportAs: 'matNavList', host: { 'role': 'navigation', 'class': 'mat-nav-list mat-list-base' }, template: "<ng-content></ng-content>\n\n", inputs: ['disableRipple'], encapsulation: ViewEncapsulation.None, changeDetection: ChangeDetectionStrategy.OnPush, styles: [".mat-subheader{display:flex;box-sizing:border-box;padding:16px;align-items:center}.mat-list-base .mat-subheader{margin:0}.mat-list-base{padding-top:8px;display:block;-webkit-tap-highlight-color:transparent}.mat-list-base .mat-subheader{height:48px;line-height:16px}.mat-list-base .mat-subheader:first-child{margin-top:-8px}.mat-list-base .mat-list-item,.mat-list-base .mat-list-option{display:block;height:48px;-webkit-tap-highlight-color:transparent;width:100%;padding:0}.mat-list-base .mat-list-item .mat-list-item-content,.mat-list-base .mat-list-option .mat-list-item-content{display:flex;flex-direction:row;align-items:center;box-sizing:border-box;padding:0 16px;position:relative;height:inherit}.mat-list-base .mat-list-item .mat-list-item-content-reverse,.mat-list-base .mat-list-option .mat-list-item-content-reverse{display:flex;align-items:center;padding:0 16px;flex-direction:row-reverse;justify-content:space-around}.mat-list-base .mat-list-item .mat-list-item-ripple,.mat-list-base .mat-list-option .mat-list-item-ripple{top:0;left:0;right:0;bottom:0;position:absolute;pointer-events:none}.mat-list-base .mat-list-item.mat-list-item-with-avatar,.mat-list-base .mat-list-option.mat-list-item-with-avatar{height:56px}.mat-list-base .mat-list-item.mat-2-line,.mat-list-base .mat-list-option.mat-2-line{height:72px}.mat-list-base .mat-list-item.mat-3-line,.mat-list-base .mat-list-option.mat-3-line{height:88px}.mat-list-base .mat-list-item.mat-multi-line,.mat-list-base .mat-list-option.mat-multi-line{height:auto}.mat-list-base .mat-list-item.mat-multi-line .mat-list-item-content,.mat-list-base .mat-list-option.mat-multi-line .mat-list-item-content{padding-top:16px;padding-bottom:16px}.mat-list-base .mat-list-item .mat-list-text,.mat-list-base .mat-list-option .mat-list-text{display:flex;flex-direction:column;width:100%;box-sizing:border-box;overflow:hidden;padding:0}.mat-list-base .mat-list-item .mat-list-text>*,.mat-list-base .mat-list-option .mat-list-text>*{margin:0;padding:0;font-weight:normal;font-size:inherit}.mat-list-base .mat-list-item .mat-list-text:empty,.mat-list-base .mat-list-option .mat-list-text:empty{display:none}.mat-list-base .mat-list-item.mat-list-item-with-avatar .mat-list-item-content .mat-list-text,.mat-list-base .mat-list-item.mat-list-option .mat-list-item-content .mat-list-text,.mat-list-base .mat-list-option.mat-list-item-with-avatar .mat-list-item-content .mat-list-text,.mat-list-base .mat-list-option.mat-list-option .mat-list-item-content .mat-list-text{padding-right:0;padding-left:16px}[dir=rtl] .mat-list-base .mat-list-item.mat-list-item-with-avatar .mat-list-item-content .mat-list-text,[dir=rtl] .mat-list-base .mat-list-item.mat-list-option .mat-list-item-content .mat-list-text,[dir=rtl] .mat-list-base .mat-list-option.mat-list-item-with-avatar .mat-list-item-content .mat-list-text,[dir=rtl] .mat-list-base .mat-list-option.mat-list-option .mat-list-item-content .mat-list-text{padding-right:16px;padding-left:0}.mat-list-base .mat-list-item.mat-list-item-with-avatar .mat-list-item-content-reverse .mat-list-text,.mat-list-base .mat-list-item.mat-list-option .mat-list-item-content-reverse .mat-list-text,.mat-list-base .mat-list-option.mat-list-item-with-avatar .mat-list-item-content-reverse .mat-list-text,.mat-list-base .mat-list-option.mat-list-option .mat-list-item-content-reverse .mat-list-text{padding-left:0;padding-right:16px}[dir=rtl] .mat-list-base .mat-list-item.mat-list-item-with-avatar .mat-list-item-content-reverse .mat-list-text,[dir=rtl] .mat-list-base .mat-list-item.mat-list-option .mat-list-item-content-reverse .mat-list-text,[dir=rtl] .mat-list-base .mat-list-option.mat-list-item-with-avatar .mat-list-item-content-reverse .mat-list-text,[dir=rtl] .mat-list-base .mat-list-option.mat-list-option .mat-list-item-content-reverse .mat-list-text{padding-right:0;padding-left:16px}.mat-list-base .mat-list-item.mat-list-item-with-avatar.mat-list-option .mat-list-item-content-reverse .mat-list-text,.mat-list-base .mat-list-item.mat-list-item-with-avatar.mat-list-option .mat-list-item-content .mat-list-text,.mat-list-base .mat-list-option.mat-list-item-with-avatar.mat-list-option .mat-list-item-content-reverse .mat-list-text,.mat-list-base .mat-list-option.mat-list-item-with-avatar.mat-list-option .mat-list-item-content .mat-list-text{padding-right:16px;padding-left:16px}.mat-list-base .mat-list-item .mat-list-avatar,.mat-list-base .mat-list-option .mat-list-avatar{flex-shrink:0;width:40px;height:40px;border-radius:50%;object-fit:cover}.mat-list-base .mat-list-item .mat-list-avatar~.mat-divider-inset,.mat-list-base .mat-list-option .mat-list-avatar~.mat-divider-inset{margin-left:72px;width:calc(100% - 72px)}[dir=rtl] .mat-list-base .mat-list-item .mat-list-avatar~.mat-divider-inset,[dir=rtl] .mat-list-base .mat-list-option .mat-list-avatar~.mat-divider-inset{margin-left:auto;margin-right:72px}.mat-list-base .mat-list-item .mat-list-icon,.mat-list-base .mat-list-option .mat-list-icon{flex-shrink:0;width:24px;height:24px;font-size:24px;box-sizing:content-box;border-radius:50%;padding:4px}.mat-list-base .mat-list-item .mat-list-icon~.mat-divider-inset,.mat-list-base .mat-list-option .mat-list-icon~.mat-divider-inset{margin-left:64px;width:calc(100% - 64px)}[dir=rtl] .mat-list-base .mat-list-item .mat-list-icon~.mat-divider-inset,[dir=rtl] .mat-list-base .mat-list-option .mat-list-icon~.mat-divider-inset{margin-left:auto;margin-right:64px}.mat-list-base .mat-list-item .mat-divider,.mat-list-base .mat-list-option .mat-divider{position:absolute;bottom:0;left:0;width:100%;margin:0}[dir=rtl] .mat-list-base .mat-list-item .mat-divider,[dir=rtl] .mat-list-base .mat-list-option .mat-divider{margin-left:auto;margin-right:0}.mat-list-base .mat-list-item .mat-divider.mat-divider-inset,.mat-list-base .mat-list-option .mat-divider.mat-divider-inset{position:absolute}.mat-list-base[dense]{padding-top:4px;display:block}.mat-list-base[dense] .mat-subheader{height:40px;line-height:8px}.mat-list-base[dense] .mat-subheader:first-child{margin-top:-4px}.mat-list-base[dense] .mat-list-item,.mat-list-base[dense] .mat-list-option{display:block;height:40px;-webkit-tap-highlight-color:transparent;width:100%;padding:0}.mat-list-base[dense] .mat-list-item .mat-list-item-content,.mat-list-base[dense] .mat-list-option .mat-list-item-content{display:flex;flex-direction:row;align-items:center;box-sizing:border-box;padding:0 16px;position:relative;height:inherit}.mat-list-base[dense] .mat-list-item .mat-list-item-content-reverse,.mat-list-base[dense] .mat-list-option .mat-list-item-content-reverse{display:flex;align-items:center;padding:0 16px;flex-direction:row-reverse;justify-content:space-around}.mat-list-base[dense] .mat-list-item .mat-list-item-ripple,.mat-list-base[dense] .mat-list-option .mat-list-item-ripple{top:0;left:0;right:0;bottom:0;position:absolute;pointer-events:none}.mat-list-base[dense] .mat-list-item.mat-list-item-with-avatar,.mat-list-base[dense] .mat-list-option.mat-list-item-with-avatar{height:48px}.mat-list-base[dense] .mat-list-item.mat-2-line,.mat-list-base[dense] .mat-list-option.mat-2-line{height:60px}.mat-list-base[dense] .mat-list-item.mat-3-line,.mat-list-base[dense] .mat-list-option.mat-3-line{height:76px}.mat-list-base[dense] .mat-list-item.mat-multi-line,.mat-list-base[dense] .mat-list-option.mat-multi-line{height:auto}.mat-list-base[dense] .mat-list-item.mat-multi-line .mat-list-item-content,.mat-list-base[dense] .mat-list-option.mat-multi-line .mat-list-item-content{padding-top:16px;padding-bottom:16px}.mat-list-base[dense] .mat-list-item .mat-list-text,.mat-list-base[dense] .mat-list-option .mat-list-text{display:flex;flex-direction:column;width:100%;box-sizing:border-box;overflow:hidden;padding:0}.mat-list-base[dense] .mat-list-item .mat-list-text>*,.mat-list-base[dense] .mat-list-option .mat-list-text>*{margin:0;padding:0;font-weight:normal;font-size:inherit}.mat-list-base[dense] .mat-list-item .mat-list-text:empty,.mat-list-base[dense] .mat-list-option .mat-list-text:empty{display:none}.mat-list-base[dense] .mat-list-item.mat-list-item-with-avatar .mat-list-item-content .mat-list-text,.mat-list-base[dense] .mat-list-item.mat-list-option .mat-list-item-content .mat-list-text,.mat-list-base[dense] .mat-list-option.mat-list-item-with-avatar .mat-list-item-content .mat-list-text,.mat-list-base[dense] .mat-list-option.mat-list-option .mat-list-item-content .mat-list-text{padding-right:0;padding-left:16px}[dir=rtl] .mat-list-base[dense] .mat-list-item.mat-list-item-with-avatar .mat-list-item-content .mat-list-text,[dir=rtl] .mat-list-base[dense] .mat-list-item.mat-list-option .mat-list-item-content .mat-list-text,[dir=rtl] .mat-list-base[dense] .mat-list-option.mat-list-item-with-avatar .mat-list-item-content .mat-list-text,[dir=rtl] .mat-list-base[dense] .mat-list-option.mat-list-option .mat-list-item-content .mat-list-text{padding-right:16px;padding-left:0}.mat-list-base[dense] .mat-list-item.mat-list-item-with-avatar .mat-list-item-content-reverse .mat-list-text,.mat-list-base[dense] .mat-list-item.mat-list-option .mat-list-item-content-reverse .mat-list-text,.mat-list-base[dense] .mat-list-option.mat-list-item-with-avatar .mat-list-item-content-reverse .mat-list-text,.mat-list-base[dense] .mat-list-option.mat-list-option .mat-list-item-content-reverse .mat-list-text{padding-left:0;padding-right:16px}[dir=rtl] .mat-list-base[dense] .mat-list-item.mat-list-item-with-avatar .mat-list-item-content-reverse .mat-list-text,[dir=rtl] .mat-list-base[dense] .mat-list-item.mat-list-option .mat-list-item-content-reverse .mat-list-text,[dir=rtl] .mat-list-base[dense] .mat-list-option.mat-list-item-with-avatar .mat-list-item-content-reverse .mat-list-text,[dir=rtl] .mat-list-base[dense] .mat-list-option.mat-list-option .mat-list-item-content-reverse .mat-list-text{padding-right:0;padding-left:16px}.mat-list-base[dense] .mat-list-item.mat-list-item-with-avatar.mat-list-option .mat-list-item-content-reverse .mat-list-text,.mat-list-base[dense] .mat-list-item.mat-list-item-with-avatar.mat-list-option .mat-list-item-content .mat-list-text,.mat-list-base[dense] .mat-list-option.mat-list-item-with-avatar.mat-list-option .mat-list-item-content-reverse .mat-list-text,.mat-list-base[dense] .mat-list-option.mat-list-item-with-avatar.mat-list-option .mat-list-item-content .mat-list-text{padding-right:16px;padding-left:16px}.mat-list-base[dense] .mat-list-item .mat-list-avatar,.mat-list-base[dense] .mat-list-option .mat-list-avatar{flex-shrink:0;width:36px;height:36px;border-radius:50%;object-fit:cover}.mat-list-base[dense] .mat-list-item .mat-list-avatar~.mat-divider-inset,.mat-list-base[dense] .mat-list-option .mat-list-avatar~.mat-divider-inset{margin-left:68px;width:calc(100% - 68px)}[dir=rtl] .mat-list-base[dense] .mat-list-item .mat-list-avatar~.mat-divider-inset,[dir=rtl] .mat-list-base[dense] .mat-list-option .mat-list-avatar~.mat-divider-inset{margin-left:auto;margin-right:68px}.mat-list-base[dense] .mat-list-item .mat-list-icon,.mat-list-base[dense] .mat-list-option .mat-list-icon{flex-shrink:0;width:20px;height:20px;font-size:20px;box-sizing:content-box;border-radius:50%;padding:4px}.mat-list-base[dense] .mat-list-item .mat-list-icon~.mat-divider-inset,.mat-list-base[dense] .mat-list-option .mat-list-icon~.mat-divider-inset{margin-left:60px;width:calc(100% - 60px)}[dir=rtl] .mat-list-base[dense] .mat-list-item .mat-list-icon~.mat-divider-inset,[dir=rtl] .mat-list-base[dense] .mat-list-option .mat-list-icon~.mat-divider-inset{margin-left:auto;margin-right:60px}.mat-list-base[dense] .mat-list-item .mat-divider,.mat-list-base[dense] .mat-list-option .mat-divider{position:absolute;bottom:0;left:0;width:100%;margin:0}[dir=rtl] .mat-list-base[dense] .mat-list-item .mat-divider,[dir=rtl] .mat-list-base[dense] .mat-list-option .mat-divider{margin-left:auto;margin-right:0}.mat-list-base[dense] .mat-list-item .mat-divider.mat-divider-inset,.mat-list-base[dense] .mat-list-option .mat-divider.mat-divider-inset{position:absolute}.mat-nav-list a{text-decoration:none;color:inherit}.mat-nav-list .mat-list-item{cursor:pointer;outline:none}mat-action-list button{background:none;color:inherit;border:none;font:inherit;outline:inherit;-webkit-tap-highlight-color:transparent;text-align:left}[dir=rtl] mat-action-list button{text-align:right}mat-action-list button::-moz-focus-inner{border:0}mat-action-list .mat-list-item{cursor:pointer;outline:inherit}.mat-list-option:not(.mat-list-item-disabled){cursor:pointer;outline:none}.cdk-high-contrast-active .mat-selection-list:focus{outline-style:dotted}.cdk-high-contrast-active .mat-list-option:hover,.cdk-high-contrast-active .mat-list-option:focus,.cdk-high-contrast-active .mat-nav-list .mat-list-item:hover,.cdk-high-contrast-active .mat-nav-list .mat-list-item:focus,.cdk-high-contrast-active mat-action-list .mat-list-item:hover,.cdk-high-contrast-active mat-action-list .mat-list-item:focus{outline:dotted 1px}@media(hover: none){.mat-list-option:not(.mat-list-item-disabled):hover,.mat-nav-list .mat-list-item:not(.mat-list-item-disabled):hover,.mat-action-list .mat-list-item:not(.mat-list-item-disabled):hover{background:none}}\n"] }] }], null, null); })(); if (false) { /** @type {?} */ MatNavList.ngAcceptInputType_disableRipple; /** * Emits when the state of the list changes. * @type {?} */ MatNavList.prototype._stateChanges; } class MatList extends _MatListMixinBase { /** * @param {?} _elementRef */ constructor(_elementRef) { super(); this._elementRef = _elementRef; /** * Emits when the state of the list changes. */ this._stateChanges = new Subject(); if (this._getListType() === 'action-list') { _elementRef.nativeElement.classList.add('mat-action-list'); } } /** * @return {?} */ _getListType() { /** @type {?} */ const nodeName = this._elementRef.nativeElement.nodeName.toLowerCase(); if (nodeName === 'mat-list') { return 'list'; } if (nodeName === 'mat-action-list') { return 'action-list'; } return null; } /** * @return {?} */ ngOnChanges() { this._stateChanges.next(); } /** * @return {?} */ ngOnDestroy() { this._stateChanges.complete(); } } MatList.ɵfac = function MatList_Factory(t) { return new (t || MatList)(ɵngcc0.ɵɵdirectiveInject(ɵngcc0.ElementRef)); }; MatList.ɵcmp = ɵngcc0.ɵɵdefineComponent({ type: MatList, selectors: [["mat-list"], ["mat-action-list"]], hostAttrs: [1, "mat-list", "mat-list-base"], inputs: { disableRipple: "disableRipple" }, exportAs: ["matList"], features: [ɵngcc0.ɵɵInheritDefinitionFeature, ɵngcc0.ɵɵNgOnChangesFeature], ngContentSelectors: _c0, decls: 1, vars: 0, template: function MatList_Template(rf, ctx) { if (rf & 1) { ɵngcc0.ɵɵprojectionDef(); ɵngcc0.ɵɵprojection(0); } }, styles: [".mat-subheader{display:flex;box-sizing:border-box;padding:16px;align-items:center}.mat-list-base .mat-subheader{margin:0}.mat-list-base{padding-top:8px;display:block;-webkit-tap-highlight-color:transparent}.mat-list-base .mat-subheader{height:48px;line-height:16px}.mat-list-base .mat-subheader:first-child{margin-top:-8px}.mat-list-base .mat-list-item,.mat-list-base .mat-list-option{display:block;height:48px;-webkit-tap-highlight-color:transparent;width:100%;padding:0}.mat-list-base .mat-list-item .mat-list-item-content,.mat-list-base .mat-list-option .mat-list-item-content{display:flex;flex-direction:row;align-items:center;box-sizing:border-box;padding:0 16px;position:relative;height:inherit}.mat-list-base .mat-list-item .mat-list-item-content-reverse,.mat-list-base .mat-list-option .mat-list-item-content-reverse{display:flex;align-items:center;padding:0 16px;flex-direction:row-reverse;justify-content:space-around}.mat-list-base .mat-list-item .mat-list-item-ripple,.mat-list-base .mat-list-option .mat-list-item-ripple{top:0;left:0;right:0;bottom:0;position:absolute;pointer-events:none}.mat-list-base .mat-list-item.mat-list-item-with-avatar,.mat-list-base .mat-list-option.mat-list-item-with-avatar{height:56px}.mat-list-base .mat-list-item.mat-2-line,.mat-list-base .mat-list-option.mat-2-line{height:72px}.mat-list-base .mat-list-item.mat-3-line,.mat-list-base .mat-list-option.mat-3-line{height:88px}.mat-list-base .mat-list-item.mat-multi-line,.mat-list-base .mat-list-option.mat-multi-line{height:auto}.mat-list-base .mat-list-item.mat-multi-line .mat-list-item-content,.mat-list-base .mat-list-option.mat-multi-line .mat-list-item-content{padding-top:16px;padding-bottom:16px}.mat-list-base .mat-list-item .mat-list-text,.mat-list-base .mat-list-option .mat-list-text{display:flex;flex-direction:column;width:100%;box-sizing:border-box;overflow:hidden;padding:0}.mat-list-base .mat-list-item .mat-list-text>*,.mat-list-base .mat-list-option .mat-list-text>*{margin:0;padding:0;font-weight:normal;font-size:inherit}.mat-list-base .mat-list-item .mat-list-text:empty,.mat-list-base .mat-list-option .mat-list-text:empty{display:none}.mat-list-base .mat-list-item.mat-list-item-with-avatar .mat-list-item-content .mat-list-text,.mat-list-base .mat-list-item.mat-list-option .mat-list-item-content .mat-list-text,.mat-list-base .mat-list-option.mat-list-item-with-avatar .mat-list-item-content .mat-list-text,.mat-list-base .mat-list-option.mat-list-option .mat-list-item-content .mat-list-text{padding-right:0;padding-left:16px}[dir=rtl] .mat-list-base .mat-list-item.mat-list-item-with-avatar .mat-list-item-content .mat-list-text,[dir=rtl] .mat-list-base .mat-list-item.mat-list-option .mat-list-item-content .mat-list-text,[dir=rtl] .mat-list-base .mat-list-option.mat-list-item-with-avatar .mat-list-item-content .mat-list-text,[dir=rtl] .mat-list-base .mat-list-option.mat-list-option .mat-list-item-content .mat-list-text{padding-right:16px;padding-left:0}.mat-list-base .mat-list-item.mat-list-item-with-avatar .mat-list-item-content-reverse .mat-list-text,.mat-list-base .mat-list-item.mat-list-option .mat-list-item-content-reverse .mat-list-text,.mat-list-base .mat-list-option.mat-list-item-with-avatar .mat-list-item-content-reverse .mat-list-text,.mat-list-base .mat-list-option.mat-list-option .mat-list-item-content-reverse .mat-list-text{padding-left:0;padding-right:16px}[dir=rtl] .mat-list-base .mat-list-item.mat-list-item-with-avatar .mat-list-item-content-reverse .mat-list-text,[dir=rtl] .mat-list-base .mat-list-item.mat-list-option .mat-list-item-content-reverse .mat-list-text,[dir=rtl] .mat-list-base .mat-list-option.mat-list-item-with-avatar .mat-list-item-content-reverse .mat-list-text,[dir=rtl] .mat-list-base .mat-list-option.mat-list-option .mat-list-item-content-reverse .mat-list-text{padding-right:0;padding-left:16px}.mat-list-base .mat-list-item.mat-list-item-with-avatar.mat-list-option .mat-list-item-content-reverse .mat-list-text,.mat-list-base .mat-list-item.mat-list-item-with-avatar.mat-list-option .mat-list-item-content .mat-list-text,.mat-list-base .mat-list-option.mat-list-item-with-avatar.mat-list-option .mat-list-item-content-reverse .mat-list-text,.mat-list-base .mat-list-option.mat-list-item-with-avatar.mat-list-option .mat-list-item-content .mat-list-text{padding-right:16px;padding-left:16px}.mat-list-base .mat-list-item .mat-list-avatar,.mat-list-base .mat-list-option .mat-list-avatar{flex-shrink:0;width:40px;height:40px;border-radius:50%;object-fit:cover}.mat-list-base .mat-list-item .mat-list-avatar~.mat-divider-inset,.mat-list-base .mat-list-option .mat-list-avatar~.mat-divider-inset{margin-left:72px;width:calc(100% - 72px)}[dir=rtl] .mat-list-base .mat-list-item .mat-list-avatar~.mat-divider-inset,[dir=rtl] .mat-list-base .mat-list-option .mat-list-avatar~.mat-divider-inset{margin-left:auto;margin-right:72px}.mat-list-base .mat-list-item .mat-list-icon,.mat-list-base .mat-list-option .mat-list-icon{flex-shrink:0;width:24px;height:24px;font-size:24px;box-sizing:content-box;border-radius:50%;padding:4px}.mat-list-base .mat-list-item .mat-list-icon~.mat-divider-inset,.mat-list-base .mat-list-option .mat-list-icon~.mat-divider-inset{margin-left:64px;width:calc(100% - 64px)}[dir=rtl] .mat-list-base .mat-list-item .mat-list-icon~.mat-divider-inset,[dir=rtl] .mat-list-base .mat-list-option .mat-list-icon~.mat-divider-inset{margin-left:auto;margin-right:64px}.mat-list-base .mat-list-item .mat-divider,.mat-list-base .mat-list-option .mat-divider{position:absolute;bottom:0;left:0;width:100%;margin:0}[dir=rtl] .mat-list-base .mat-list-item .mat-divider,[dir=rtl] .mat-list-base .mat-list-option .mat-divider{margin-left:auto;margin-right:0}.mat-list-base .mat-list-item .mat-divider.mat-divider-inset,.mat-list-base .mat-list-option .mat-divider.mat-divider-inset{position:absolute}.mat-list-base[dense]{padding-top:4px;display:block}.mat-list-base[dense] .mat-subheader{height:40px;line-height:8px}.mat-list-base[dense] .mat-subheader:first-child{margin-top:-4px}.mat-list-base[dense] .mat-list-item,.mat-list-base[dense] .mat-list-option{display:block;height:40px;-webkit-tap-highlight-color:transparent;width:100%;padding:0}.mat-list-base[dense] .mat-list-item .mat-list-item-content,.mat-list-base[dense] .mat-list-option .mat-list-item-content{display:flex;flex-direction:row;align-items:center;box-sizing:border-box;padding:0 16px;position:relative;height:inherit}.mat-list-base[dense] .mat-list-item .mat-list-item-content-reverse,.mat-list-base[dense] .mat-list-option .mat-list-item-content-reverse{display:flex;align-items:center;padding:0 16px;flex-direction:row-reverse;justify-content:space-around}.mat-list-base[dense] .mat-list-item .mat-list-item-ripple,.mat-list-base[dense] .mat-list-option .mat-list-item-ripple{top:0;left:0;right:0;bottom:0;position:absolute;pointer-events:none}.mat-list-base[dense] .mat-list-item.mat-list-item-with-avatar,.mat-list-base[dense] .mat-list-option.mat-list-item-with-avatar{height:48px}.mat-list-base[dense] .mat-list-item.mat-2-line,.mat-list-base[dense] .mat-list-option.mat-2-line{height:60px}.mat-list-base[dense] .mat-list-item.mat-3-line,.mat-list-base[dense] .mat-list-option.mat-3-line{height:76px}.mat-list-base[dense] .mat-list-item.mat-multi-line,.mat-list-base[dense] .mat-list-option.mat-multi-line{height:auto}.mat-list-base[dense] .mat-list-item.mat-multi-line .mat-list-item-content,.mat-list-base[dense] .mat-list-option.mat-multi-line .mat-list-item-content{padding-top:16px;padding-bottom:16px}.mat-list-base[dense] .mat-list-item .mat-list-text,.mat-list-base[dense] .mat-list-option .mat-list-text{display:flex;flex-direction:column;width:100%;box-sizing:border-box;overflow:hidden;padding:0}.mat-list-base[dense] .mat-list-item .mat-list-text>*,.mat-list-base[dense] .mat-list-option .mat-list-text>*{margin:0;padding:0;font-weight:normal;font-size:inherit}.mat-list-base[dense] .mat-list-item .mat-list-text:empty,.mat-list-base[dense] .mat-list-option .mat-list-text:empty{display:none}.mat-list-base[dense] .mat-list-item.mat-list-item-with-avatar .mat-list-item-content .mat-list-text,.mat-list-base[dense] .mat-list-item.mat-list-option .mat-list-item-content .mat-list-text,.mat-list-base[dense] .mat-list-option.mat-list-item-with-avatar .mat-list-item-content .mat-list-text,.mat-list-base[dense] .mat-list-option.mat-list-option .mat-list-item-content .mat-list-text{padding-right:0;padding-left:16px}[dir=rtl] .mat-list-base[dense] .mat-list-item.mat-list-item-with-avatar .mat-list-item-content .mat-list-text,[dir=rtl] .mat-list-base[dense] .mat-list-item.mat-list-option .mat-list-item-content .mat-list-text,[dir=rtl] .mat-list-base[dense] .mat-list-option.mat-list-item-with-avatar .mat-list-item-content .mat-list-text,[dir=rtl] .mat-list-base[dense] .mat-list-option.mat-list-option .mat-list-item-content .mat-list-text{padding-right:16px;padding-left:0}.mat-list-base[dense] .mat-list-item.mat-list-item-with-avatar .mat-list-item-content-reverse .mat-list-text,.mat-list-base[dense] .mat-list-item.mat-list-option .mat-list-item-content-reverse .mat-list-text,.mat-list-base[dense] .mat-list-option.mat-list-item-with-avatar .mat-list-item-content-reverse .mat-list-text,.mat-list-base[dense] .mat-list-option.mat-list-option .mat-list-item-content-reverse .mat-list-text{padding-left:0;padding-right:16px}[dir=rtl] .mat-list-base[dense] .mat-list-item.mat-list-item-with-avatar .mat-list-item-content-reverse .mat-list-text,[dir=rtl] .mat-list-base[dense] .mat-list-item.mat-list-option .mat-list-item-content-reverse .mat-list-text,[dir=rtl] .mat-list-base[dense] .mat-list-option.mat-list-item-with-avatar .mat-list-item-content-reverse .mat-list-text,[dir=rtl] .mat-list-base[dense] .mat-list-option.mat-list-option .mat-list-item-content-reverse .mat-list-text{padding-right:0;padding-left:16px}.mat-list-base[dense] .mat-list-item.mat-list-item-with-avatar.mat-list-option .mat-list-item-content-reverse .mat-list-text,.mat-list-base[dense] .mat-list-item.mat-list-item-with-avatar.mat-list-option .mat-list-item-content .mat-list-text,.mat-list-base[dense] .mat-list-option.mat-list-item-with-avatar.mat-list-option .mat-list-item-content-reverse .mat-list-text,.mat-list-base[dense] .mat-list-option.mat-list-item-with-avatar.mat-list-option .mat-list-item-content .mat-list-text{padding-right:16px;padding-left:16px}.mat-list-base[dense] .mat-list-item .mat-list-avatar,.mat-list-base[dense] .mat-list-option .mat-list-avatar{flex-shrink:0;width:36px;height:36px;border-radius:50%;object-fit:cover}.mat-list-base[dense] .mat-list-item .mat-list-avatar~.mat-divider-inset,.mat-list-base[dense] .mat-list-option .mat-list-avatar~.mat-divider-inset{margin-left:68px;width:calc(100% - 68px)}[dir=rtl] .mat-list-base[dense] .mat-list-item .mat-list-avatar~.mat-divider-inset,[dir=rtl] .mat-list-base[dense] .mat-list-option .mat-list-avatar~.mat-divider-inset{margin-left:auto;margin-right:68px}.mat-list-base[dense] .mat-list-item .mat-list-icon,.mat-list-base[dense] .mat-list-option .mat-list-icon{flex-shrink:0;width:20px;height:20px;font-size:20px;box-sizing:content-box;border-radius:50%;padding:4px}.mat-list-base[dense] .mat-list-item .mat-list-icon~.mat-divider-inset,.mat-list-base[dense] .mat-list-option .mat-list-icon~.mat-divider-inset{margin-left:60px;width:calc(100% - 60px)}[dir=rtl] .mat-list-base[dense] .mat-list-item .mat-list-icon~.mat-divider-inset,[dir=rtl] .mat-list-base[dense] .mat-list-option .mat-list-icon~.mat-divider-inset{margin-left:auto;margin-right:60px}.mat-list-base[dense] .mat-list-item .mat-divider,.mat-list-base[dense] .mat-list-option .mat-divider{position:absolute;bottom:0;left:0;width:100%;margin:0}[dir=rtl] .mat-list-base[dense] .mat-list-item .mat-divider,[dir=rtl] .mat-list-base[dense] .mat-list-option .mat-divider{margin-left:auto;margin-right:0}.mat-list-base[dense] .mat-list-item .mat-divider.mat-divider-inset,.mat-list-base[dense] .mat-list-option .mat-divider.mat-divider-inset{position:absolute}.mat-nav-list a{text-decoration:none;color:inherit}.mat-nav-list .mat-list-item{cursor:pointer;outline:none}mat-action-list button{background:none;color:inherit;border:none;font:inherit;outline:inherit;-webkit-tap-highlight-color:transparent;text-align:left}[dir=rtl] mat-action-list button{text-align:right}mat-action-list button::-moz-focus-inner{border:0}mat-action-list .mat-list-item{cursor:pointer;outline:inherit}.mat-list-option:not(.mat-list-item-disabled){cursor:pointer;outline:none}.cdk-high-contrast-active .mat-selection-list:focus{outline-style:dotted}.cdk-high-contrast-active .mat-list-option:hover,.cdk-high-contrast-active .mat-list-option:focus,.cdk-high-contrast-active .mat-nav-list .mat-list-item:hover,.cdk-high-contrast-active .mat-nav-list .mat-list-item:focus,.cdk-high-contrast-active mat-action-list .mat-list-item:hover,.cdk-high-contrast-active mat-action-list .mat-list-item:focus{outline:dotted 1px}@media(hover: none){.mat-list-option:not(.mat-list-item-disabled):hover,.mat-nav-list .mat-list-item:not(.mat-list-item-disabled):hover,.mat-action-list .mat-list-item:not(.mat-list-item-disabled):hover{background:none}}\n"], encapsulation: 2, changeDetection: 0 }); /** @nocollapse */ MatList.ctorParameters = () => [ { type: ElementRef } ]; /*@__PURE__*/ (function () { ɵngcc0.ɵsetClassMetadata(MatList, [{ type: Component, args: [{ selector: 'mat-list, mat-action-list', exportAs: 'matList', template: "<ng-content></ng-content>\n\n", host: { 'class': 'mat-list mat-list-base' }, inputs: ['disableRipple'], encapsulation: ViewEncapsulation.None, changeDetection: ChangeDetectionStrategy.OnPush, styles: [".mat-subheader{display:flex;box-sizing:border-box;padding:16px;align-items:center}.mat-list-base .mat-subheader{margin:0}.mat-list-base{padding-top:8px;display:block;-webkit-tap-highlight-color:transparent}.mat-list-base .mat-subheader{height:48px;line-height:16px}.mat-list-base .mat-subheader:first-child{margin-top:-8px}.mat-list-base .mat-list-item,.mat-list-base .mat-list-option{display:block;height:48px;-webkit-tap-highlight-color:transparent;width:100%;padding:0}.mat-list-base .mat-list-item .mat-list-item-content,.mat-list-base .mat-list-option .mat-list-item-content{display:flex;flex-direction:row;align-items:center;box-sizing:border-box;padding:0 16px;position:relative;height:inherit}.mat-list-base .mat-list-item .mat-list-item-content-reverse,.mat-list-base .mat-list-option .mat-list-item-content-reverse{display:flex;align-items:center;padding:0 16px;flex-direction:row-reverse;justify-content:space-around}.mat-list-base .mat-list-item .mat-list-item-ripple,.mat-list-base .mat-list-option .mat-list-item-ripple{top:0;left:0;right:0;bottom:0;position:absolute;pointer-events:none}.mat-list-base .mat-list-item.mat-list-item-with-avatar,.mat-list-base .mat-list-option.mat-list-item-with-avatar{height:56px}.mat-list-base .mat-list-item.mat-2-line,.mat-list-base .mat-list-option.mat-2-line{height:72px}.mat-list-base .mat-list-item.mat-3-line,.mat-list-base .mat-list-option.mat-3-line{height:88px}.mat-list-base .mat-list-item.mat-multi-line,.mat-list-base .mat-list-option.mat-multi-line{height:auto}.mat-list-base .mat-list-item.mat-multi-line .mat-list-item-content,.mat-list-base .mat-list-option.mat-multi-line .mat-list-item-content{padding-top:16px;padding-bottom:16px}.mat-list-base .mat-list-item .mat-list-text,.mat-list-base .mat-list-option .mat-list-text{display:flex;flex-direction:column;width:100%;box-sizing:border-box;overflow:hidden;padding:0}.mat-list-base .mat-list-item .mat-list-text>*,.mat-list-base .mat-list-option .mat-list-text>*{margin:0;padding:0;font-weight:normal;font-size:inherit}.mat-list-base .mat-list-item .mat-list-text:empty,.mat-list-base .mat-list-option .mat-list-text:empty{display:none}.mat-list-base .mat-list-item.mat-list-item-with-avatar .mat-list-item-content .mat-list-text,.mat-list-base .mat-list-item.mat-list-option .mat-list-item-content .mat-list-text,.mat-list-base .mat-list-option.mat-list-item-with-avatar .mat-list-item-content .mat-list-text,.mat-list-base .mat-list-option.mat-list-option .mat-list-item-content .mat-list-text{padding-right:0;padding-left:16px}[dir=rtl] .mat-list-base .mat-list-item.mat-list-item-with-avatar .mat-list-item-content .mat-list-text,[dir=rtl] .mat-list-base .mat-list-item.mat-list-option .mat-list-item-content .mat-list-text,[dir=rtl] .mat-list-base .mat-list-option.mat-list-item-with-avatar .mat-list-item-content .mat-list-text,[dir=rtl] .mat-list-base .mat-list-option.mat-list-option .mat-list-item-content .mat-list-text{padding-right:16px;padding-left:0}.mat-list-base .mat-list-item.mat-list-item-with-avatar .mat-list-item-content-reverse .mat-list-text,.mat-list-base .mat-list-item.mat-list-option .mat-list-item-content-reverse .mat-list-text,.mat-list-base .mat-list-option.mat-list-item-with-avatar .mat-list-item-content-reverse .mat-list-text,.mat-list-base .mat-list-option.mat-list-option .mat-list-item-content-reverse .mat-list-text{padding-left:0;padding-right:16px}[dir=rtl] .mat-list-base .mat-list-item.mat-list-item-with-avatar .mat-list-item-content-reverse .mat-list-text,[dir=rtl] .mat-list-base .mat-list-item.mat-list-option .mat-list-item-content-reverse .mat-list-text,[dir=rtl] .mat-list-base .mat-list-option.mat-list-item-with-avatar .mat-list-item-content-reverse .mat-list-text,[dir=rtl] .mat-list-base .mat-list-option.mat-list-option .mat-list-item-content-reverse .mat-list-text{padding-right:0;padding-left:16px}.mat-list-base .mat-list-item.mat-list-item-with-avatar.mat-list-option .mat-list-item-content-reverse .mat-list-text,.mat-list-base .mat-list-item.mat-list-item-with-avatar.mat-list-option .mat-list-item-content .mat-list-text,.mat-list-base .mat-list-option.mat-list-item-with-avatar.mat-list-option .mat-list-item-content-reverse .mat-list-text,.mat-list-base .mat-list-option.mat-list-item-with-avatar.mat-list-option .mat-list-item-content .mat-list-text{padding-right:16px;padding-left:16px}.mat-list-base .mat-list-item .mat-list-avatar,.mat-list-base .mat-list-option .mat-list-avatar{flex-shrink:0;width:40px;height:40px;border-radius:50%;object-fit:cover}.mat-list-base .mat-list-item .mat-list-avatar~.mat-divider-inset,.mat-list-base .mat-list-option .mat-list-avatar~.mat-divider-inset{margin-left:72px;width:calc(100% - 72px)}[dir=rtl] .mat-list-base .mat-list-item .mat-list-avatar~.mat-divider-inset,[dir=rtl] .mat-list-base .mat-list-option .mat-list-avatar~.mat-divider-inset{margin-left:auto;margin-right:72px}.mat-list-base .mat-list-item .mat-list-icon,.mat-list-base .mat-list-option .mat-list-icon{flex-shrink:0;width:24px;height:24px;font-size:24px;box-sizing:content-box;border-radius:50%;padding:4px}.mat-list-base .mat-list-item .mat-list-icon~.mat-divider-inset,.mat-list-base .mat-list-option .mat-list-icon~.mat-divider-inset{margin-left:64px;width:calc(100% - 64px)}[dir=rtl] .mat-list-base .mat-list-item .mat-list-icon~.mat-divider-inset,[dir=rtl] .mat-list-base .mat-list-option .mat-list-icon~.mat-divider-inset{margin-left:auto;margin-right:64px}.mat-list-base .mat-list-item .mat-divider,.mat-list-base .mat-list-option .mat-divider{position:absolute;bottom:0;left:0;width:100%;margin:0}[dir=rtl] .mat-list-base .mat-list-item .mat-divider,[dir=rtl] .mat-list-base .mat-list-option .mat-divider{margin-left:auto;margin-right:0}.mat-list-base .mat-list-item .mat-divider.mat-divider-inset,.mat-list-base .mat-list-option .mat-divider.mat-divider-inset{position:absolute}.mat-list-base[dense]{padding-top:4px;display:block}.mat-list-base[dense] .mat-subheader{height:40px;line-height:8px}.mat-list-base[dense] .mat-subheader:first-child{margin-top:-4px}.mat-list-base[dense] .mat-list-item,.mat-list-base[dense] .mat-list-option{display:block;height:40px;-webkit-tap-highlight-color:transparent;width:100%;padding:0}.mat-list-base[dense] .mat-list-item .mat-list-item-content,.mat-list-base[dense] .mat-list-option .mat-list-item-content{display:flex;flex-direction:row;align-items:center;box-sizing:border-box;padding:0 16px;position:relative;height:inherit}.mat-list-base[dense] .mat-list-item .mat-list-item-content-reverse,.mat-list-base[dense] .mat-list-option .mat-list-item-content-reverse{display:flex;align-items:center;padding:0 16px;flex-direction:row-reverse;justify-content:space-around}.mat-list-base[dense] .mat-list-item .mat-list-item-ripple,.mat-list-base[dense] .mat-list-option .mat-list-item-ripple{top:0;left:0;right:0;bottom:0;position:absolute;pointer-events:none}.mat-list-base[dense] .mat-list-item.mat-list-item-with-avatar,.mat-list-base[dense] .mat-list-option.mat-list-item-with-avatar{height:48px}.mat-list-base[dense] .mat-list-item.mat-2-line,.mat-list-base[dense] .mat-list-option.mat-2-line{height:60px}.mat-list-base[dense] .mat-list-item.mat-3-line,.mat-list-base[dense] .mat-list-option.mat-3-line{height:76px}.mat-list-base[dense] .mat-list-item.mat-multi-line,.mat-list-base[dense] .mat-list-option.mat-multi-line{height:auto}.mat-list-base[dense] .mat-list-item.mat-multi-line .mat-list-item-content,.mat-list-base[dense] .mat-list-option.mat-multi-line .mat-list-item-content{padding-top:16px;padding-bottom:16px}.mat-list-base[dense] .mat-list-item .mat-list-text,.mat-list-base[dense] .mat-list-option .mat-list-text{display:flex;flex-direction:column;width:100%;box-sizing:border-box;overflow:hidden;padding:0}.mat-list-base[dense] .mat-list-item .mat-list-text>*,.mat-list-base[dense] .mat-list-option .mat-list-text>*{margin:0;padding:0;font-weight:normal;font-size:inherit}.mat-list-base[dense] .mat-list-item .mat-list-text:empty,.mat-list-base[dense] .mat-list-option .mat-list-text:empty{display:none}.mat-list-base[dense] .mat-list-item.mat-list-item-with-avatar .mat-list-item-content .mat-list-text,.mat-list-base[dense] .mat-list-item.mat-list-option .mat-list-item-content .mat-list-text,.mat-list-base[dense] .mat-list-option.mat-list-item-with-avatar .mat-list-item-content .mat-list-text,.mat-list-base[dense] .mat-list-option.mat-list-option .mat-list-item-content .mat-list-text{padding-right:0;padding-left:16px}[dir=rtl] .mat-list-base[dense] .mat-list-item.mat-list-item-with-avatar .mat-list-item-content .mat-list-text,[dir=rtl] .mat-list-base[dense] .mat-list-item.mat-list-option .mat-list-item-content .mat-list-text,[dir=rtl] .mat-list-base[dense] .mat-list-option.mat-list-item-with-avatar .mat-list-item-content .mat-list-text,[dir=rtl] .mat-list-base[dense] .mat-list-option.mat-list-option .mat-list-item-content .mat-list-text{padding-right:16px;padding-left:0}.mat-list-base[dense] .mat-list-item.mat-list-item-with-avatar .mat-list-item-content-reverse .mat-list-text,.mat-list-base[dense] .mat-list-item.mat-list-option .mat-list-item-content-reverse .mat-list-text,.mat-list-base[dense] .mat-list-option.mat-list-item-with-avatar .mat-list-item-content-reverse .mat-list-text,.mat-list-base[dense] .mat-list-option.mat-list-option .mat-list-item-content-reverse .mat-list-text{padding-left:0;padding-right:16px}[dir=rtl] .mat-list-base[dense] .mat-list-item.mat-list-item-with-avatar .mat-list-item-content-reverse .mat-list-text,[dir=rtl] .mat-list-base[dense] .mat-list-item.mat-list-option .mat-list-item-content-reverse .mat-list-text,[dir=rtl] .mat-list-base[dense] .mat-list-option.mat-list-item-with-avatar .mat-list-item-content-reverse .mat-list-text,[dir=rtl] .mat-list-base[dense] .mat-list-option.mat-list-option .mat-list-item-content-reverse .mat-list-text{padding-right:0;padding-left:16px}.mat-list-base[dense] .mat-list-item.mat-list-item-with-avatar.mat-list-option .mat-list-item-content-reverse .mat-list-text,.mat-list-base[dense] .mat-list-item.mat-list-item-with-avatar.mat-list-option .mat-list-item-content .mat-list-text,.mat-list-base[dense] .mat-list-option.mat-list-item-with-avatar.mat-list-option .mat-list-item-content-reverse .mat-list-text,.mat-list-base[dense] .mat-list-option.mat-list-item-with-avatar.mat-list-option .mat-list-item-content .mat-list-text{padding-right:16px;padding-left:16px}.mat-list-base[dense] .mat-list-item .mat-list-avatar,.mat-list-base[dense] .mat-list-option .mat-list-avatar{flex-shrink:0;width:36px;height:36px;border-radius:50%;object-fit:cover}.mat-list-base[dense] .mat-list-item .mat-list-avatar~.mat-divider-inset,.mat-list-base[dense] .mat-list-option .mat-list-avatar~.mat-divider-inset{margin-left:68px;width:calc(100% - 68px)}[dir=rtl] .mat-list-base[dense] .mat-list-item .mat-list-avatar~.mat-divider-inset,[dir=rtl] .mat-list-base[dense] .mat-list-option .mat-list-avatar~.mat-divider-inset{margin-left:auto;margin-right:68px}.mat-list-base[dense] .mat-list-item .mat-list-icon,.mat-list-base[dense] .mat-list-option .mat-list-icon{flex-shrink:0;width:20px;height:20px;font-size:20px;box-sizing:content-box;border-radius:50%;padding:4px}.mat-list-base[dense] .mat-list-item .mat-list-icon~.mat-divider-inset,.mat-list-base[dense] .mat-list-option .mat-list-icon~.mat-divider-inset{margin-left:60px;width:calc(100% - 60px)}[dir=rtl] .mat-list-base[dense] .mat-list-item .mat-list-icon~.mat-divider-inset,[dir=rtl] .mat-list-base[dense] .mat-list-option .mat-list-icon~.mat-divider-inset{margin-left:auto;margin-right:60px}.mat-list-base[dense] .mat-list-item .mat-divider,.mat-list-base[dense] .mat-list-option .mat-divider{position:absolute;bottom:0;left:0;width:100%;margin:0}[dir=rtl] .mat-list-base[dense] .mat-list-item .mat-divider,[dir=rtl] .mat-list-base[dense] .mat-list-option .mat-divider{margin-left:auto;margin-right:0}.mat-list-base[dense] .mat-list-item .mat-divider.mat-divider-inset,.mat-list-base[dense] .mat-list-option .mat-divider.mat-divider-inset{position:absolute}.mat-nav-list a{text-decoration:none;color:inherit}.mat-nav-list .mat-list-item{cursor:pointer;outline:none}mat-action-list button{background:none;color:inherit;border:none;font:inherit;outline:inherit;-webkit-tap-highlight-color:transparent;text-align:left}[dir=rtl] mat-action-list button{text-align:right}mat-action-list button::-moz-focus-inner{border:0}mat-action-list .mat-list-item{cursor:pointer;outline:inherit}.mat-list-option:not(.mat-list-item-disabled){cursor:pointer;outline:none}.cdk-high-contrast-active .mat-selection-list:focus{outline-style:dotted}.cdk-high-contrast-active .mat-list-option:hover,.cdk-high-contrast-active .mat-list-option:focus,.cdk-high-contrast-active .mat-nav-list .mat-list-item:hover,.cdk-high-contrast-active .mat-nav-list .mat-list-item:focus,.cdk-high-contrast-active mat-action-list .mat-list-item:hover,.cdk-high-contrast-active mat-action-list .mat-list-item:focus{outline:dotted 1px}@media(hover: none){.mat-list-option:not(.mat-list-item-disabled):hover,.mat-nav-list .mat-list-item:not(.mat-list-item-disabled):hover,.mat-action-list .mat-list-item:not(.mat-list-item-disabled):hover{background:none}}\n"] }] }], function () { return [{ type: ɵngcc0.ElementRef }]; }, null); })(); if (false) { /** @type {?} */ MatList.ngAcceptInputType_disableRipple; /** * Emits when the state of the list changes. * @type {?} */ MatList.prototype._stateChanges; /** * @type {?} * @private */ MatList.prototype._elementRef; } /** * Directive whose purpose is to add the mat- CSS styling to this selector. * \@docs-private */ class MatListAvatarCssMatStyler { } MatListAvatarCssMatStyler.ɵfac = function MatListAvatarCssMatStyler_Factory(t) { return new (t || MatListAvatarCssMatStyler)(); }; MatListAvatarCssMatStyler.ɵdir = ɵngcc0.ɵɵdefineDirective({ type: MatListAvatarCssMatStyler, selectors: [["", "mat-list-avatar", ""], ["", "matListAvatar", ""]], hostAttrs: [1, "mat-list-avatar"] }); /*@__PURE__*/ (function () { ɵngcc0.ɵsetClassMetadata(MatListAvatarCssMatStyler, [{ type: Directive, args: [{ selector: '[mat-list-avatar], [matListAvatar]', host: { 'class': 'mat-list-avatar' } }] }], null, null); })(); /** * Directive whose purpose is to add the mat- CSS styling to this selector. * \@docs-private */ class MatListIconCssMatStyler { } MatListIconCssMatStyler.ɵfac = function MatListIconCssMatStyler_Factory(t) { return new (t || MatListIconCssMatStyler)(); }; MatListIconCssMatStyler.ɵdir = ɵngcc0.ɵɵdefineDirective({ type: MatListIconCssMatStyler, selectors: [["", "mat-list-icon", ""], ["", "matListIcon", ""]], hostAttrs: [1, "mat-list-icon"] }); /*@__PURE__*/ (function () { ɵngcc0.ɵsetClassMetadata(MatListIconCssMatStyler, [{ type: Directive, args: [{ selector: '[mat-list-icon], [matListIcon]', host: { 'class': 'mat-list-icon' } }] }], null, null); })(); /** * Directive whose purpose is to add the mat- CSS styling to this selector. * \@docs-private */ class MatListSubheaderCssMatStyler { } MatListSubheaderCssMatStyler.ɵfac = function MatListSubheaderCssMatStyler_Factory(t) { return new (t || MatListSubheaderCssMatStyler)(); }; MatListSubheaderCssMatStyler.ɵdir = ɵngcc0.ɵɵdefineDirective({ type: MatListSubheaderCssMatStyler, selectors: [["", "mat-subheader", ""], ["", "matSubheader", ""]], hostAttrs: [1, "mat-subheader"] }); /*@__PURE__*/ (function () { ɵngcc0.ɵsetClassMetadata(MatListSubheaderCssMatStyler, [{ type: Directive, args: [{ selector: '[mat-subheader], [matSubheader]', host: { 'class': 'mat-subheader' } }] }], null, null); })(); /** * An item within a Material Design list. */ class MatListItem extends _MatListItemMixinBase { /** * @param {?} _element * @param {?} _changeDetectorRef * @param {?=} navList * @param {?=} list */ constructor(_element, _changeDetectorRef, navList, list) { super(); this._element = _element; this._isInteractiveList = false; this._destroyed = new Subject(); this._isInteractiveList = !!(navList || (list && list._getListType() === 'action-list')); this._list = navList || list; // If no type attributed is specified for <button>, set it to "button". // If a type attribute is already specified, do nothing. /** @type {?} */ const element = this._getHostElement(); if (element.nodeName.toLowerCase() === 'button' && !element.hasAttribute('type')) { element.setAttribute('type', 'button'); } if (this._list) { // React to changes in the state of the parent list since // some of the item's properties depend on it (e.g. `disableRipple`). this._list._stateChanges.pipe(takeUntil(this._destroyed)).subscribe((/** * @return {?} */ () => { _changeDetectorRef.markForCheck(); })); } } /** * @return {?} */ ngAfterContentInit() { setLines(this._lines, this._element); } /** * @return {?} */ ngOnDestroy() { this._destroyed.next(); this._destroyed.complete(); } /** * Whether this list item should show a ripple effect when clicked. * @return {?} */ _isRippleDisabled() { return !this._isInteractiveList || this.disableRipple || !!(this._list && this._list.disableRipple); } /** * Retrieves the DOM element of the component host. * @return {?} */ _getHostElement() { return this._element.nativeElement; } } MatListItem.ɵfac = function MatListItem_Factory(t) { return new (t || MatListItem)(ɵngcc0.ɵɵdirectiveInject(ɵngcc0.ElementRef), ɵngcc0.ɵɵdirectiveInject(ɵngcc0.ChangeDetectorRef), ɵngcc0.ɵɵdirectiveInject(MatNavList, 8), ɵngcc0.ɵɵdirectiveInject(MatList, 8)); }; MatListItem.ɵcmp = ɵngcc0.ɵɵdefineComponent({ type: MatListItem, selectors: [["mat-list-item"], ["a", "mat-list-item", ""], ["button", "mat-list-item", ""]], contentQueries: function MatListItem_ContentQueries(rf, ctx, dirIndex) { if (rf & 1) { ɵngcc0.ɵɵcontentQuery(dirIndex, MatListAvatarCssMatStyler, true); ɵngcc0.ɵɵcontentQuery(dirIndex, MatListIconCssMatStyler, true); ɵngcc0.ɵɵcontentQuery(dirIndex, MatLine, true); } if (rf & 2) { var _t; ɵngcc0.ɵɵqueryRefresh(_t = ɵngcc0.ɵɵloadQuery()) && (ctx._avatar = _t.first); ɵngcc0.ɵɵqueryRefresh(_t = ɵngcc0.ɵɵloadQuery()) && (ctx._icon = _t.first); ɵngcc0.ɵɵqueryRefresh(_t = ɵngcc0.ɵɵloadQuery()) && (ctx._lines = _t); } }, hostAttrs: [1, "mat-list-item"], hostVars: 4, hostBindings: function MatListItem_HostBindings(rf, ctx) { if (rf & 2) { ɵngcc0.ɵɵclassProp("mat-list-item-avatar", ctx._avatar || ctx._icon)("mat-list-item-with-avatar", ctx._avatar || ctx._icon); } }, inputs: { disableRipple: "disableRipple" }, exportAs: ["matListItem"], features: [ɵngcc0.ɵɵInheritDefinitionFeature], ngContentSelectors: _c2, decls: 6, vars: 2, consts: [[1, "mat-list-item-content"], ["mat-ripple", "", 1, "mat-list-item-ripple", 3, "matRippleTrigger", "matRippleDisabled"], [1, "mat-list-text"]], template: function MatListItem_Template(rf, ctx) { if (rf & 1) { ɵngcc0.ɵɵprojectionDef(_c1); ɵngcc0.ɵɵelementStart(0, "div", 0); ɵngcc0.ɵɵelement(1, "div", 1); ɵngcc0.ɵɵprojection(2); ɵngcc0.ɵɵelementStart(3, "div", 2); ɵngcc0.ɵɵprojection(4, 1); ɵngcc0.ɵɵelementEnd(); ɵngcc0.ɵɵprojection(5, 2); ɵngcc0.ɵɵelementEnd(); } if (rf & 2) { ɵngcc0.ɵɵadvance(1); ɵngcc0.ɵɵproperty("matRippleTrigger", ctx._getHostElement())("matRippleDisabled", ctx._isRippleDisabled()); } }, directives: [ɵngcc1.MatRipple], encapsulation: 2, changeDetection: 0 }); /** @nocollapse */ MatListItem.ctorParameters = () => [ { type: ElementRef }, { type: ChangeDetectorRef }, { type: MatNavList, decorators: [{ type: Optional }] }, { type: MatList, decorators: [{ type: Optional }] } ]; MatListItem.propDecorators = { _lines: [{ type: ContentChildren, args: [MatLine, { descendants: true },] }], _avatar: [{ type: ContentChild, args: [MatListAvatarCssMatStyler,] }], _icon: [{ type: ContentChild, args: [MatListIconCssMatStyler,] }] }; /*@__PURE__*/ (function () { ɵngcc0.ɵsetClassMetadata(MatListItem, [{ type: Component, args: [{ selector: 'mat-list-item, a[mat-list-item], button[mat-list-item]', exportAs: 'matListItem', host: { 'class': 'mat-list-item', // @breaking-change 8.0.0 Remove `mat-list-item-avatar` in favor of `mat-list-item-with-avatar`. '[class.mat-list-item-avatar]': '_avatar || _icon', '[class.mat-list-item-with-avatar]': '_avatar || _icon' }, inputs: ['disableRipple'], template: "<div class=\"mat-list-item-content\">\n <div class=\"mat-list-item-ripple\" mat-ripple\n [matRippleTrigger]=\"_getHostElement()\"\n [matRippleDisabled]=\"_isRippleDisabled()\">\n </div>\n\n <ng-content select=\"[mat-list-avatar], [mat-list-icon], [matListAvatar], [matListIcon]\">\n </ng-content>\n\n <div class=\"mat-list-text\"><ng-content select=\"[mat-line], [matLine]\"></ng-content></div>\n\n <ng-content></ng-content>\n</div>\n", encapsulation: ViewEncapsulation.None, changeDetection: ChangeDetectionStrategy.OnPush }] }], function () { return [{ type: ɵngcc0.ElementRef }, { type: ɵngcc0.ChangeDetectorRef }, { type: MatNavList, decorators: [{ type: Optional }] }, { type: MatList, decorators: [{ type: Optional }] }]; }, { _lines: [{ type: ContentChildren, args: [MatLine, { descendants: true }] }], _avatar: [{ type: ContentChild, args: [MatListAvatarCssMatStyler] }], _icon: [{ type: ContentChild, args: [MatListIconCssMatStyler] }] }); })(); if (false) { /** @type {?} */ MatListItem.ngAcceptInputType_disableRipple; /** * @type {?} * @private */ MatListItem.prototype._isInteractiveList; /** * @type {?} * @private */ MatListItem.prototype._list; /** * @type {?} * @private */ MatListItem.prototype._destroyed; /** @type {?} */ MatListItem.prototype._lines; /** @type {?} */ MatListItem.prototype._avatar; /** @type {?} */ MatListItem.prototype._icon; /** * @type {?} * @private */ MatListItem.prototype._element; } /** * @fileoverview added by tsickle * Generated from: src/material/list/selection-list.ts * @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc */ /** * \@docs-private */ class MatSelectionListBase { } /** @type {?} */ const _MatSelectionListMixinBase = mixinDisableRipple(MatSelectionListBase); /** * \@docs-private */ class MatListOptionBase { } /** @type {?} */ const _MatListOptionMixinBase = mixinDisableRipple(MatListOptionBase); /** * \@docs-private * @type {?} */ const MAT_SELECTION_LIST_VALUE_ACCESSOR = { provide: NG_VALUE_ACCESSOR, useExisting: forwardRef((/** * @return {?} */ () => MatSelectionList)), multi: true }; /** * Change event that is being fired whenever the selected state of an option changes. */ class MatSelectionListChange { /** * @param {?} source * @param {?} option */ constructor(source, option) { this.source = source; this.option = option; } } if (false) { /** * Reference to the selection list that emitted the event. * @type {?} */ MatSelectionListChange.prototype.source; /** * Reference to the option that has been changed. * @type {?} */ MatSelectionListChange.prototype.option; } /** * Component for list-options of selection-list. Each list-option can automatically * generate a checkbox and can put current item into the selectionModel of selection-list * if the current item is selected. */ class MatListOption extends _MatListOptionMixinBase { /** * @param {?} _element * @param {?} _changeDetector * @param {?} selectionList */ constructor(_element, _changeDetector, selectionList) { super(); this._element = _element; this._changeDetector = _changeDetector; this.selectionList = selectionList; this._selected = false; this._disabled = false; this._hasFocus = false; /** * Whether the label should appear before or after the checkbox. Defaults to 'after' */ this.checkboxPosition = 'after'; /** * This is set to true after the first OnChanges cycle so we don't clear the value of `selected` * in the first cycle. */ this._inputsInitialized = false; } /** * Theme color of the list option. This sets the color of the checkbox. * @return {?} */ get color() { return this._color || this.selectionList.color; } /** * @param {?} newValue * @return {?} */ set color(newValue) { this._color = newValue; } /** * Value of the option * @return {?} */ get value() { return this._value; } /** * @param {?} newValue * @return {?} */ set value(newValue) { if (this.selected && newValue !== this.value && this._inputsInitialized) { this.selected = false; } this._value = newValue; } /** * Whether the option is disabled. * @return {?} */ get disabled() { return this._disabled || (this.selectionList && this.selectionList.disabled); } /** * @param {?} value * @return {?} */ set disabled(value) { /** @type {?} */ const newValue = coerceBooleanProperty(value); if (newValue !== this._disabled) { this._disabled = newValue; this._changeDetector.markForCheck(); } } /** * Whether the option is selected. * @return {?} */ get selected() { return this.selectionList.selectedOptions.isSelected(this); } /** * @param {?} value * @return {?} */ set selected(value) { /** @type {?} */ const isSelected = coerceBooleanProperty(value); if (isSelected !== this._selected) { this._setSelected(isSelected); this.selectionList._reportValueChange(); } } /** * @return {?} */ ngOnInit() { /** @type {?} */ const list = this.selectionList; if (list._value && list._value.some((/** * @param {?} value * @return {?} */ value => list.compareWith(value, this._value)))) { this._setSelected(true); } /** @type {?} */ const wasSelected = this._selected; // List options that are selected at initialization can't be reported properly to the form // control. This is because it takes some time until the selection-list knows about all // available options. Also it can happen that the ControlValueAccessor has an initial value // that should be used instead. Deferring the value change report to the next tick ensures // that the form control value is not being overwritten. Promise.resolve().then((/** * @return {?} */ () => { if (this._selected || wasSelected) { this.selected = true; this._changeDetector.markForCheck(); } })); this._inputsInitialized = true; } /** * @return {?} */ ngAfterContentInit() { setLines(this._lines, this._element); } /** * @return {?} */ ngOnDestroy() { if (this.selected) { // We have to delay this until the next tick in order // to avoid changed after checked errors. Promise.resolve().then((/** * @return {?} */ () => { this.selected = false; })); } /** @type {?} */ const hadFocus = this._hasFocus; /** @type {?} */ const newActiveItem = this.selectionList._removeOptionFromList(this); // Only move focus if this option was focused at the time it was destroyed. if (hadFocus && newActiveItem) { newActiveItem.focus(); } } /** * Toggles the selection state of the option. * @return {?} */ toggle() { this.selected = !this.selected; } /** * Allows for programmatic focusing of the option. * @return {?} */ focus() { this._element.nativeElement.focus(); } /** * Returns the list item's text label. Implemented as a part of the FocusKeyManager. * \@docs-private * @return {?} */ getLabel() { return this._text ? (this._text.nativeElement.textContent || '') : ''; } /** * Whether this list item should show a ripple effect when clicked. * @return {?} */ _isRippleDisabled() { return this.disabled || this.disableRipple || this.selectionList.disableRipple; } /** * @return {?} */ _handleClick() { if (!this.disabled) { this.toggle(); // Emit a change event if the selected state of the option changed through user interaction. this.selectionList._emitChangeEvent(this); } } /** * @return {?} */ _handleFocus() { this.selectionList._setFocusedOption(this); this._hasFocus = true; } /** * @return {?} */ _handleBlur() { this.selectionList._onTouched(); this._hasFocus = false; } /** * Retrieves the DOM element of the component host. * @return {?} */ _getHostElement() { return this._element.nativeElement; } /** * Sets the selected state of the option. Returns whether the value has changed. * @param {?} selected * @return {?} */ _setSelected(selected) { if (selected === this._selected) { return false; } this._selected = selected; if (selected) { this.selectionList.selectedOptions.select(this); } else { this.selectionList.selectedOptions.deselect(this); } this._changeDetector.markForCheck(); return true; } /** * Notifies Angular that the option needs to be checked in the next change detection run. Mainly * used to trigger an update of the list option if the disabled state of the selection list * changed. * @return {?} */ _markForCheck() { this._changeDetector.markForCheck(); } } MatListOption.ɵfac = function MatListOption_Factory(t) { return new (t || MatListOption)(ɵngcc0.ɵɵdirectiveInject(ɵngcc0.ElementRef), ɵngcc0.ɵɵdirectiveInject(ɵngcc0.ChangeDetectorRef), ɵngcc0.ɵɵdirectiveInject(forwardRef(( /** * @return {?} */() => MatSelectionList)))); }; MatListOption.ɵcmp = ɵngcc0.ɵɵdefineComponent({ type: MatListOption, selectors: [["mat-list-option"]], contentQueries: function MatListOption_ContentQueries(rf, ctx, dirIndex) { if (rf & 1) { ɵngcc0.ɵɵcontentQuery(dirIndex, MatListAvatarCssMatStyler, true); ɵngcc0.ɵɵcontentQuery(dirIndex, MatListIconCssMatStyler, true); ɵngcc0.ɵɵcontentQuery(dirIndex, MatLine, true); } if (rf & 2) { var _t; ɵngcc0.ɵɵqueryRefresh(_t = ɵngcc0.ɵɵloadQuery()) && (ctx._avatar = _t.first); ɵngcc0.ɵɵqueryRefresh(_t = ɵngcc0.ɵɵloadQuery()) && (ctx._icon = _t.first); ɵngcc0.ɵɵqueryRefresh(_t = ɵngcc0.ɵɵloadQuery()) && (ctx._lines = _t); } }, viewQuery: function MatListOption_Query(rf, ctx) { if (rf & 1) { ɵngcc0.ɵɵviewQuery(_c3, true); } if (rf & 2) { var _t; ɵngcc0.ɵɵqueryRefresh(_t = ɵngcc0.ɵɵloadQuery()) && (ctx._text = _t.first); } }, hostAttrs: ["role", "option", "tabindex", "-1", 1, "mat-list-item", "mat-list-option"], hostVars: 12, hostBindings: function MatListOption_HostBindings(rf, ctx) { if (rf & 1) { ɵngcc0.ɵɵlistener("focus", function MatListOption_focus_HostBindingHandler() { return ctx._handleFocus(); })("blur", function MatListOption_blur_HostBindingHandler() { return ctx._handleBlur(); })("click", function MatListOption_click_HostBindingHandler() { return ctx._handleClick(); }); } if (rf & 2) { ɵngcc0.ɵɵattribute("aria-selected", ctx.selected)("aria-disabled", ctx.disabled); ɵngcc0.ɵɵclassProp("mat-list-item-disabled", ctx.disabled)("mat-list-item-with-avatar", ctx._avatar || ctx._icon)("mat-primary", ctx.color === "primary")("mat-accent", ctx.color !== "primary" && ctx.color !== "warn")("mat-warn", ctx.color === "warn"); } }, inputs: { disableRipple: "disableRipple", checkboxPosition: "checkboxPosition", color: "color", value: "value", selected: "selected", disabled: "disabled" }, exportAs: ["matListOption"], features: [ɵngcc0.ɵɵInheritDefinitionFeature], ngContentSelectors: _c5, decls: 7, vars: 6, consts: [[1, "mat-list-item-content"], ["mat-ripple", "", 1, "mat-list-item-ripple", 3, "matRippleTrigger", "matRippleDisabled"], [3, "state", "disabled"], [1, "mat-list-text"], ["text", ""]], template: function MatListOption_Template(rf, ctx) { if (rf & 1) { ɵngcc0.ɵɵprojectionDef(_c4); ɵngcc0.ɵɵelementStart(0, "div", 0); ɵngcc0.ɵɵelement(1, "div", 1); ɵngcc0.ɵɵelement(2, "mat-pseudo-checkbox", 2); ɵngcc0.ɵɵelementStart(3, "div", 3, 4); ɵngcc0.ɵɵprojection(5); ɵngcc0.ɵɵelementEnd(); ɵngcc0.ɵɵprojection(6, 1); ɵngcc0.ɵɵelementEnd(); } if (rf & 2) { ɵngcc0.ɵɵclassProp("mat-list-item-content-reverse", ctx.checkboxPosition == "after"); ɵngcc0.ɵɵadvance(1); ɵngcc0.ɵɵproperty("matRippleTrigger", ctx._getHostElement())("matRippleDisabled", ctx._isRippleDisabled()); ɵngcc0.ɵɵadvance(1); ɵngcc0.ɵɵproperty("state", ctx.selected ? "checked" : "unchecked")("disabled", ctx.disabled); } }, directives: [ɵngcc1.MatRipple, ɵngcc1.MatPseudoCheckbox], encapsulation: 2, changeDetection: 0 }); /** @nocollapse */ MatListOption.ctorParameters = () => [ { type: ElementRef }, { type: ChangeDetectorRef }, { type: MatSelectionList, decorators: [{ type: Inject, args: [forwardRef((/** * @return {?} */ () => MatSelectionList)),] }] } ]; MatListOption.propDecorators = { _avatar: [{ type: ContentChild, args: [MatListAvatarCssMatStyler,] }], _icon: [{ type: ContentChild, args: [MatListIconCssMatStyler,] }], _lines: [{ type: ContentChildren, args: [MatLine, { descendants: true },] }], _text: [{ type: ViewChild, args: ['text',] }], checkboxPosition: [{ type: Input }], color: [{ type: Input }], value: [{ type: Input }], disabled: [{ type: Input }], selected: [{ type: Input }] }; /*@__PURE__*/ (function () { ɵngcc0.ɵsetClassMetadata(MatListOption, [{ type: Component, args: [{ selector: 'mat-list-option', exportAs: 'matListOption', inputs: ['disableRipple'], host: { 'role': 'option', 'class': 'mat-list-item mat-list-option', '(focus)': '_handleFocus()', '(blur)': '_handleBlur()', '(click)': '_handleClick()', 'tabindex': '-1', '[class.mat-list-item-disabled]': 'disabled', '[class.mat-list-item-with-avatar]': '_avatar || _icon', // Manually set the "primary" or "warn" class if the color has been explicitly // set to "primary" or "warn". The pseudo checkbox picks up these classes for // its theme. '[class.mat-primary]': 'color === "primary"', // Even though accent is the default, we need to set this class anyway, because the list might // be placed inside a parent that has one of the other colors with a higher specificity. '[class.mat-accent]': 'color !== "primary" && color !== "warn"', '[class.mat-warn]': 'color === "warn"', '[attr.aria-selected]': 'selected', '[attr.aria-disabled]': 'disabled' }, template: "<div class=\"mat-list-item-content\"\n [class.mat-list-item-content-reverse]=\"checkboxPosition == 'after'\">\n\n <div mat-ripple\n class=\"mat-list-item-ripple\"\n [matRippleTrigger]=\"_getHostElement()\"\n [matRippleDisabled]=\"_isRippleDisabled()\"></div>\n\n <mat-pseudo-checkbox\n [state]=\"selected ? 'checked' : 'unchecked'\"\n [disabled]=\"disabled\"></mat-pseudo-checkbox>\n\n <div class=\"mat-list-text\" #text><ng-content></ng-content></div>\n\n <ng-content select=\"[mat-list-avatar], [mat-list-icon], [matListAvatar], [matListIcon]\">\n </ng-content>\n\n</div>\n", encapsulation: ViewEncapsulation.None, changeDetection: ChangeDetectionStrategy.OnPush }] }], function () { return [{ type: ɵngcc0.ElementRef }, { type: ɵngcc0.ChangeDetectorRef }, { type: MatSelectionList, decorators: [{ type: Inject, args: [forwardRef(( /** * @return {?} */() => MatSelectionList))] }] }]; }, { checkboxPosition: [{ type: Input }], color: [{ type: Input }], value: [{ type: Input }], selected: [{ type: Input }], disabled: [{ type: Input }], _avatar: [{ type: ContentChild, args: [MatListAvatarCssMatStyler] }], _icon: [{ type: ContentChild, args: [MatListIconCssMatStyler] }], _lines: [{ type: ContentChildren, args: [MatLine, { descendants: true }] }], _text: [{ type: ViewChild, args: ['text'] }] }); })(); if (false) { /** @type {?} */ MatListOption.ngAcceptInputType_disabled; /** @type {?} */ MatListOption.ngAcceptInputType_selected; /** @type {?} */ MatListOption.ngAcceptInputType_disableRipple; /** * @type {?} * @private */ MatListOption.prototype._selected; /** * @type {?} * @private */ MatListOption.prototype._disabled; /** * @type {?} * @private */ MatListOption.prototype._hasFocus; /** @type {?} */ MatListOption.prototype._avatar; /** @type {?} */ MatListOption.prototype._icon; /** @type {?} */ MatListOption.prototype._lines; /** * DOM element containing the item's text. * @type {?} */ MatListOption.prototype._text; /** * Whether the label should appear before or after the checkbox. Defaults to 'after' * @type {?} */ MatListOption.prototype.checkboxPosition; /** * @type {?} * @private */ MatListOption.prototype._color; /** * This is set to true after the first OnChanges cycle so we don't clear the value of `selected` * in the first cycle. * @type {?} * @private */ MatListOption.prototype._inputsInitialized; /** * @type {?} * @private */ MatListOption.prototype._value; /** * @type {?} * @private */ MatListOption.prototype._element; /** * @type {?} * @private */ MatListOption.prototype._changeDetector; /** * \@docs-private * @type {?} */ MatListOption.prototype.selectionList; } /** * Material Design list component where each item is a selectable option. Behaves as a listbox. */ class MatSelectionList extends _MatSelectionListMixinBase { /** * @param {?} _element * @param {?} tabIndex */ constructor(_element, tabIndex) { super(); this._element = _element; /** * Emits a change event whenever the selected state of an option changes. */ this.selectionChange = new EventEmitter(); /** * Tabindex of the selection list. */ this.tabIndex = 0; /** * Theme color of the selection list. This sets the checkbox color for all list options. */ this.color = 'accent'; /** * Function used for comparing an option against the selected value when determining which * options should appear as selected. The first argument is the value of an options. The second * one is a value from the selected value. A boolean must be returned. */ this.compareWith = (/** * @param {?} a1 * @param {?} a2 * @return {?} */ (a1, a2) => a1 === a2); this._disabled = false; /** * The currently selected options. */ this.selectedOptions = new SelectionModel(true); /** * View to model callback that should be called whenever the selected options change. */ this._onChange = (/** * @param {?} _ * @return {?} */ (_) => { }); /** * Emits when the list has been destroyed. */ this._destroyed = new Subject(); /** * View to model callback that should be called if the list or its options lost focus. */ this._onTouched = (/** * @return {?} */ () => { }); this.tabIndex = parseInt(tabIndex) || 0; } /** * Whether the selection list is disabled. * @return {?} */ get disabled() { return this._disabled; } /** * @param {?} value * @return {?} */ set disabled(value) { this._disabled = coerceBooleanProperty(value); // The `MatSelectionList` and `MatListOption` are using the `OnPush` change detection // strategy. Therefore the options will not check for any changes if the `MatSelectionList` // changed its state. Since we know that a change to `disabled` property of the list affects // the state of the options, we manually mark each option for check. this._markOptionsForCheck(); } /** * @return {?} */ ngAfterContentInit() { this._keyManager = new FocusKeyManager(this.options) .withWrap() .withTypeAhead() // Allow disabled items to be focusable. For accessibility reasons, there must be a way for // screenreader users, that allows reading the different options of the list. .skipPredicate((/** * @return {?} */ () => false)) .withAllowedModifierKeys(['shiftKey']); if (this._value) { this._setOptionsFromValues(this._value); } // Sync external changes to the model back to the options. this.selectedOptions.changed.pipe(takeUntil(this._destroyed)).subscribe((/** * @param {?} event * @return {?} */ event => { if (event.added) { for (let item of event.added) { item.selected = true; } } if (event.removed) { for (let item of event.removed) { item.selected = false; } } })); } /** * @param {?} changes * @return {?} */ ngOnChanges(changes) { /** @type {?} */ const disableRippleChanges = changes['disableRipple']; /** @type {?} */ const colorChanges = changes['color']; if ((disableRippleChanges && !disableRippleChanges.firstChange) || (colorChanges && !colorChanges.firstChange)) { this._markOptionsForCheck(); } } /** * @return {?} */ ngOnDestroy() { this._destroyed.next(); this._destroyed.complete(); this._isDestroyed = true; } /** * Focuses the selection list. * @param {?=} options * @return {?} */ focus(options) { this._element.nativeElement.focus(options); } /** * Selects all of the options. * @return {?} */ selectAll() { this._setAllOptionsSelected(true); } /** * Deselects all of the options. * @return {?} */ deselectAll() { this._setAllOptionsSelected(false); } /** * Sets the focused option of the selection-list. * @param {?} option * @return {?} */ _setFocusedOption(option) { this._keyManager.updateActiveItem(option); } /** * Removes an option from the selection list and updates the active item. * @param {?} option * @return {?} Currently-active item. */ _removeOptionFromList(option) { /** @type {?} */ const optionIndex = this._getOptionIndex(option); if (optionIndex > -1 && this._keyManager.activeItemIndex === optionIndex) { // Check whether the option is the last item if (optionIndex > 0) { this._keyManager.updateActiveItem(optionIndex - 1); } else if (optionIndex === 0 && this.options.length > 1) { this._keyManager.updateActiveItem(Math.min(optionIndex + 1, this.options.length - 1)); } } return this._keyManager.activeItem; } /** * Passes relevant key presses to our key manager. * @param {?} event * @return {?} */ _keydown(event) { /** @type {?} */ const keyCode = event.keyCode; /** @type {?} */ const manager = this._keyManager; /** @type {?} */ const previousFocusIndex = manager.activeItemIndex; /** @type {?} */ const hasModifier = hasModifierKey(event); switch (keyCode) { case SPACE: case ENTER: if (!hasModifier && !manager.isTyping()) { this._toggleFocusedOption(); // Always prevent space from scrolling the page since the list has focus event.preventDefault(); } break; case HOME: case END: if (!hasModifier) { keyCode === HOME ? manager.setFirstItemActive() : manager.setLastItemActive(); event.preventDefault(); } break; case A: if (hasModifierKey(event, 'ctrlKey') && !manager.isTyping()) { this.options.find((/** * @param {?} option * @return {?} */ option => !option.selected)) ? this.selectAll() : this.deselectAll(); event.preventDefault(); } break; default: manager.onKeydown(event); } if ((keyCode === UP_ARROW || keyCode === DOWN_ARROW) && event.shiftKey && manager.activeItemIndex !== previousFocusIndex) { this._toggleFocusedOption(); } } /** * Reports a value change to the ControlValueAccessor * @return {?} */ _reportValueChange() { // Stop reporting value changes after the list has been destroyed. This avoids // cases where the list might wrongly reset its value once it is removed, but // the form control is still live. if (this.options && !this._isDestroyed) { /** @type {?} */ const value = this._getSelectedOptionValues(); this._onChange(value); this._value = value; } } /** * Emits a change event if the selected state of an option changed. * @param {?} option * @return {?} */ _emitChangeEvent(option) { this.selectionChange.emit(new MatSelectionListChange(this, option)); } /** * Implemented as part of ControlValueAccessor. * @param {?} values * @return {?} */ writeValue(values) { this._value = values; if (this.options) { this._setOptionsFromValues(values || []); } } /** * Implemented as a part of ControlValueAccessor. * @param {?} isDisabled * @return {?} */ setDisabledState(isDisabled) { this.disabled = isDisabled; } /** * Implemented as part of ControlValueAccessor. * @param {?} fn * @return {?} */ registerOnChange(fn) { this._onChange = fn; } /** * Implemented as part of ControlValueAccessor. * @param {?} fn * @return {?} */ registerOnTouched(fn) { this._onTouched = fn; } /** * Sets the selected options based on the specified values. * @private * @param {?} values * @return {?} */ _setOptionsFromValues(values) { this.options.forEach((/** * @param {?} option * @return {?} */ option => option._setSelected(false))); values.forEach((/** * @param {?} value * @return {?} */ value => { /** @type {?} */ const correspondingOption = this.options.find((/** * @param {?} option * @return {?} */ option => { // Skip options that are already in the model. This allows us to handle cases // where the same primitive value is selected multiple times. return option.selected ? false : this.compareWith(option.value, value); })); if (correspondingOption) { correspondingOption._setSelected(true); } })); } /** * Returns the values of the selected options. * @private * @return {?} */ _getSelectedOptionValues() { return this.options.filter((/** * @param {?} option * @return {?} */ option => option.selected)).map((/** * @param {?} option * @return {?} */ option => option.value)); } /** * Toggles the state of the currently focused option if enabled. * @private * @return {?} */ _toggleFocusedOption() { /** @type {?} */ let focusedIndex = this._keyManager.activeItemIndex; if (focusedIndex != null && this._isValidIndex(focusedIndex)) { /** @type {?} */ let focusedOption = this.options.toArray()[focusedIndex]; if (focusedOption && !focusedOption.disabled) { focusedOption.toggle(); // Emit a change event because the focused option changed its state through user // interaction. this._emitChangeEvent(focusedOption); } } } /** * Sets the selected state on all of the options * and emits an event if anything changed. * @private * @param {?} isSelected * @return {?} */ _setAllOptionsSelected(isSelected) { // Keep track of whether anything changed, because we only want to // emit the changed event when something actually changed. /** @type {?} */ let hasChanged = false; this.options.forEach((/** * @param {?} option * @return {?} */ option => { if (option._setSelected(isSelected)) { hasChanged = true; } })); if (hasChanged) { this._reportValueChange(); } } /** * Utility to ensure all indexes are valid. * @private * @param {?} index The index to be checked. * @return {?} True if the index is valid for our list of options. */ _isValidIndex(index) { return index >= 0 && index < this.options.length; } /** * Returns the index of the specified list option. * @private * @param {?} option * @return {?} */ _getOptionIndex(option) { return this.options.toArray().indexOf(option); } /** * Marks all the options to be checked in the next change detection run. * @private * @return {?} */ _markOptionsForCheck() { if (this.options) { this.options.forEach((/** * @param {?} option * @return {?} */ option => option._markForCheck())); } } } MatSelectionList.ɵfac = function MatSelectionList_Factory(t) { return new (t || MatSelectionList)(ɵngcc0.ɵɵdirectiveInject(ɵngcc0.ElementRef), ɵngcc0.ɵɵinjectAttribute('tabindex')); }; MatSelectionList.ɵcmp = ɵngcc0.ɵɵdefineComponent({ type: MatSelectionList, selectors: [["mat-selection-list"]], contentQueries: function MatSelectionList_ContentQueries(rf, ctx, dirIndex) { if (rf & 1) { ɵngcc0.ɵɵcontentQuery(dirIndex, MatListOption, true); } if (rf & 2) { var _t; ɵngcc0.ɵɵqueryRefresh(_t = ɵngcc0.ɵɵloadQuery()) && (ctx.options = _t); } }, hostAttrs: ["role", "listbox", "aria-multiselectable", "true", 1, "mat-selection-list", "mat-list-base"], hostVars: 2, hostBindings: function MatSelectionList_HostBindings(rf, ctx) { if (rf & 1) { ɵngcc0.ɵɵlistener("blur", function MatSelectionList_blur_HostBindingHandler() { return ctx._onTouched(); })("keydown", function MatSelectionList_keydown_HostBindingHandler($event) { return ctx._keydown($event); }); } if (rf & 2) { ɵngcc0.ɵɵhostProperty("tabIndex", ctx.tabIndex); ɵngcc0.ɵɵattribute("aria-disabled", ctx.disabled.toString()); } }, inputs: { disableRipple: "disableRipple", tabIndex: "tabIndex", color: "color", compareWith: "compareWith", disabled: "disabled" }, outputs: { selectionChange: "selectionChange" }, exportAs: ["matSelectionList"], features: [ɵngcc0.ɵɵProvidersFeature([MAT_SELECTION_LIST_VALUE_ACCESSOR]), ɵngcc0.ɵɵInheritDefinitionFeature, ɵngcc0.ɵɵNgOnChangesFeature], ngContentSelectors: _c0, decls: 1, vars: 0, template: function MatSelectionList_Template(rf, ctx) { if (rf & 1) { ɵngcc0.ɵɵprojectionDef(); ɵngcc0.ɵɵprojection(0); } }, styles: [".mat-subheader{display:flex;box-sizing:border-box;padding:16px;align-items:center}.mat-list-base .mat-subheader{margin:0}.mat-list-base{padding-top:8px;display:block;-webkit-tap-highlight-color:transparent}.mat-list-base .mat-subheader{height:48px;line-height:16px}.mat-list-base .mat-subheader:first-child{margin-top:-8px}.mat-list-base .mat-list-item,.mat-list-base .mat-list-option{display:block;height:48px;-webkit-tap-highlight-color:transparent;width:100%;padding:0}.mat-list-base .mat-list-item .mat-list-item-content,.mat-list-base .mat-list-option .mat-list-item-content{display:flex;flex-direction:row;align-items:center;box-sizing:border-box;padding:0 16px;position:relative;height:inherit}.mat-list-base .mat-list-item .mat-list-item-content-reverse,.mat-list-base .mat-list-option .mat-list-item-content-reverse{display:flex;align-items:center;padding:0 16px;flex-direction:row-reverse;justify-content:space-around}.mat-list-base .mat-list-item .mat-list-item-ripple,.mat-list-base .mat-list-option .mat-list-item-ripple{top:0;left:0;right:0;bottom:0;position:absolute;pointer-events:none}.mat-list-base .mat-list-item.mat-list-item-with-avatar,.mat-list-base .mat-list-option.mat-list-item-with-avatar{height:56px}.mat-list-base .mat-list-item.mat-2-line,.mat-list-base .mat-list-option.mat-2-line{height:72px}.mat-list-base .mat-list-item.mat-3-line,.mat-list-base .mat-list-option.mat-3-line{height:88px}.mat-list-base .mat-list-item.mat-multi-line,.mat-list-base .mat-list-option.mat-multi-line{height:auto}.mat-list-base .mat-list-item.mat-multi-line .mat-list-item-content,.mat-list-base .mat-list-option.mat-multi-line .mat-list-item-content{padding-top:16px;padding-bottom:16px}.mat-list-base .mat-list-item .mat-list-text,.mat-list-base .mat-list-option .mat-list-text{display:flex;flex-direction:column;width:100%;box-sizing:border-box;overflow:hidden;padding:0}.mat-list-base .mat-list-item .mat-list-text>*,.mat-list-base .mat-list-option .mat-list-text>*{margin:0;padding:0;font-weight:normal;font-size:inherit}.mat-list-base .mat-list-item .mat-list-text:empty,.mat-list-base .mat-list-option .mat-list-text:empty{display:none}.mat-list-base .mat-list-item.mat-list-item-with-avatar .mat-list-item-content .mat-list-text,.mat-list-base .mat-list-item.mat-list-option .mat-list-item-content .mat-list-text,.mat-list-base .mat-list-option.mat-list-item-with-avatar .mat-list-item-content .mat-list-text,.mat-list-base .mat-list-option.mat-list-option .mat-list-item-content .mat-list-text{padding-right:0;padding-left:16px}[dir=rtl] .mat-list-base .mat-list-item.mat-list-item-with-avatar .mat-list-item-content .mat-list-text,[dir=rtl] .mat-list-base .mat-list-item.mat-list-option .mat-list-item-content .mat-list-text,[dir=rtl] .mat-list-base .mat-list-option.mat-list-item-with-avatar .mat-list-item-content .mat-list-text,[dir=rtl] .mat-list-base .mat-list-option.mat-list-option .mat-list-item-content .mat-list-text{padding-right:16px;padding-left:0}.mat-list-base .mat-list-item.mat-list-item-with-avatar .mat-list-item-content-reverse .mat-list-text,.mat-list-base .mat-list-item.mat-list-option .mat-list-item-content-reverse .mat-list-text,.mat-list-base .mat-list-option.mat-list-item-with-avatar .mat-list-item-content-reverse .mat-list-text,.mat-list-base .mat-list-option.mat-list-option .mat-list-item-content-reverse .mat-list-text{padding-left:0;padding-right:16px}[dir=rtl] .mat-list-base .mat-list-item.mat-list-item-with-avatar .mat-list-item-content-reverse .mat-list-text,[dir=rtl] .mat-list-base .mat-list-item.mat-list-option .mat-list-item-content-reverse .mat-list-text,[dir=rtl] .mat-list-base .mat-list-option.mat-list-item-with-avatar .mat-list-item-content-reverse .mat-list-text,[dir=rtl] .mat-list-base .mat-list-option.mat-list-option .mat-list-item-content-reverse .mat-list-text{padding-right:0;padding-left:16px}.mat-list-base .mat-list-item.mat-list-item-with-avatar.mat-list-option .mat-list-item-content-reverse .mat-list-text,.mat-list-base .mat-list-item.mat-list-item-with-avatar.mat-list-option .mat-list-item-content .mat-list-text,.mat-list-base .mat-list-option.mat-list-item-with-avatar.mat-list-option .mat-list-item-content-reverse .mat-list-text,.mat-list-base .mat-list-option.mat-list-item-with-avatar.mat-list-option .mat-list-item-content .mat-list-text{padding-right:16px;padding-left:16px}.mat-list-base .mat-list-item .mat-list-avatar,.mat-list-base .mat-list-option .mat-list-avatar{flex-shrink:0;width:40px;height:40px;border-radius:50%;object-fit:cover}.mat-list-base .mat-list-item .mat-list-avatar~.mat-divider-inset,.mat-list-base .mat-list-option .mat-list-avatar~.mat-divider-inset{margin-left:72px;width:calc(100% - 72px)}[dir=rtl] .mat-list-base .mat-list-item .mat-list-avatar~.mat-divider-inset,[dir=rtl] .mat-list-base .mat-list-option .mat-list-avatar~.mat-divider-inset{margin-left:auto;margin-right:72px}.mat-list-base .mat-list-item .mat-list-icon,.mat-list-base .mat-list-option .mat-list-icon{flex-shrink:0;width:24px;height:24px;font-size:24px;box-sizing:content-box;border-radius:50%;padding:4px}.mat-list-base .mat-list-item .mat-list-icon~.mat-divider-inset,.mat-list-base .mat-list-option .mat-list-icon~.mat-divider-inset{margin-left:64px;width:calc(100% - 64px)}[dir=rtl] .mat-list-base .mat-list-item .mat-list-icon~.mat-divider-inset,[dir=rtl] .mat-list-base .mat-list-option .mat-list-icon~.mat-divider-inset{margin-left:auto;margin-right:64px}.mat-list-base .mat-list-item .mat-divider,.mat-list-base .mat-list-option .mat-divider{position:absolute;bottom:0;left:0;width:100%;margin:0}[dir=rtl] .mat-list-base .mat-list-item .mat-divider,[dir=rtl] .mat-list-base .mat-list-option .mat-divider{margin-left:auto;margin-right:0}.mat-list-base .mat-list-item .mat-divider.mat-divider-inset,.mat-list-base .mat-list-option .mat-divider.mat-divider-inset{position:absolute}.mat-list-base[dense]{padding-top:4px;display:block}.mat-list-base[dense] .mat-subheader{height:40px;line-height:8px}.mat-list-base[dense] .mat-subheader:first-child{margin-top:-4px}.mat-list-base[dense] .mat-list-item,.mat-list-base[dense] .mat-list-option{display:block;height:40px;-webkit-tap-highlight-color:transparent;width:100%;padding:0}.mat-list-base[dense] .mat-list-item .mat-list-item-content,.mat-list-base[dense] .mat-list-option .mat-list-item-content{display:flex;flex-direction:row;align-items:center;box-sizing:border-box;padding:0 16px;position:relative;height:inherit}.mat-list-base[dense] .mat-list-item .mat-list-item-content-reverse,.mat-list-base[dense] .mat-list-option .mat-list-item-content-reverse{display:flex;align-items:center;padding:0 16px;flex-direction:row-reverse;justify-content:space-around}.mat-list-base[dense] .mat-list-item .mat-list-item-ripple,.mat-list-base[dense] .mat-list-option .mat-list-item-ripple{top:0;left:0;right:0;bottom:0;position:absolute;pointer-events:none}.mat-list-base[dense] .mat-list-item.mat-list-item-with-avatar,.mat-list-base[dense] .mat-list-option.mat-list-item-with-avatar{height:48px}.mat-list-base[dense] .mat-list-item.mat-2-line,.mat-list-base[dense] .mat-list-option.mat-2-line{height:60px}.mat-list-base[dense] .mat-list-item.mat-3-line,.mat-list-base[dense] .mat-list-option.mat-3-line{height:76px}.mat-list-base[dense] .mat-list-item.mat-multi-line,.mat-list-base[dense] .mat-list-option.mat-multi-line{height:auto}.mat-list-base[dense] .mat-list-item.mat-multi-line .mat-list-item-content,.mat-list-base[dense] .mat-list-option.mat-multi-line .mat-list-item-content{padding-top:16px;padding-bottom:16px}.mat-list-base[dense] .mat-list-item .mat-list-text,.mat-list-base[dense] .mat-list-option .mat-list-text{display:flex;flex-direction:column;width:100%;box-sizing:border-box;overflow:hidden;padding:0}.mat-list-base[dense] .mat-list-item .mat-list-text>*,.mat-list-base[dense] .mat-list-option .mat-list-text>*{margin:0;padding:0;font-weight:normal;font-size:inherit}.mat-list-base[dense] .mat-list-item .mat-list-text:empty,.mat-list-base[dense] .mat-list-option .mat-list-text:empty{display:none}.mat-list-base[dense] .mat-list-item.mat-list-item-with-avatar .mat-list-item-content .mat-list-text,.mat-list-base[dense] .mat-list-item.mat-list-option .mat-list-item-content .mat-list-text,.mat-list-base[dense] .mat-list-option.mat-list-item-with-avatar .mat-list-item-content .mat-list-text,.mat-list-base[dense] .mat-list-option.mat-list-option .mat-list-item-content .mat-list-text{padding-right:0;padding-left:16px}[dir=rtl] .mat-list-base[dense] .mat-list-item.mat-list-item-with-avatar .mat-list-item-content .mat-list-text,[dir=rtl] .mat-list-base[dense] .mat-list-item.mat-list-option .mat-list-item-content .mat-list-text,[dir=rtl] .mat-list-base[dense] .mat-list-option.mat-list-item-with-avatar .mat-list-item-content .mat-list-text,[dir=rtl] .mat-list-base[dense] .mat-list-option.mat-list-option .mat-list-item-content .mat-list-text{padding-right:16px;padding-left:0}.mat-list-base[dense] .mat-list-item.mat-list-item-with-avatar .mat-list-item-content-reverse .mat-list-text,.mat-list-base[dense] .mat-list-item.mat-list-option .mat-list-item-content-reverse .mat-list-text,.mat-list-base[dense] .mat-list-option.mat-list-item-with-avatar .mat-list-item-content-reverse .mat-list-text,.mat-list-base[dense] .mat-list-option.mat-list-option .mat-list-item-content-reverse .mat-list-text{padding-left:0;padding-right:16px}[dir=rtl] .mat-list-base[dense] .mat-list-item.mat-list-item-with-avatar .mat-list-item-content-reverse .mat-list-text,[dir=rtl] .mat-list-base[dense] .mat-list-item.mat-list-option .mat-list-item-content-reverse .mat-list-text,[dir=rtl] .mat-list-base[dense] .mat-list-option.mat-list-item-with-avatar .mat-list-item-content-reverse .mat-list-text,[dir=rtl] .mat-list-base[dense] .mat-list-option.mat-list-option .mat-list-item-content-reverse .mat-list-text{padding-right:0;padding-left:16px}.mat-list-base[dense] .mat-list-item.mat-list-item-with-avatar.mat-list-option .mat-list-item-content-reverse .mat-list-text,.mat-list-base[dense] .mat-list-item.mat-list-item-with-avatar.mat-list-option .mat-list-item-content .mat-list-text,.mat-list-base[dense] .mat-list-option.mat-list-item-with-avatar.mat-list-option .mat-list-item-content-reverse .mat-list-text,.mat-list-base[dense] .mat-list-option.mat-list-item-with-avatar.mat-list-option .mat-list-item-content .mat-list-text{padding-right:16px;padding-left:16px}.mat-list-base[dense] .mat-list-item .mat-list-avatar,.mat-list-base[dense] .mat-list-option .mat-list-avatar{flex-shrink:0;width:36px;height:36px;border-radius:50%;object-fit:cover}.mat-list-base[dense] .mat-list-item .mat-list-avatar~.mat-divider-inset,.mat-list-base[dense] .mat-list-option .mat-list-avatar~.mat-divider-inset{margin-left:68px;width:calc(100% - 68px)}[dir=rtl] .mat-list-base[dense] .mat-list-item .mat-list-avatar~.mat-divider-inset,[dir=rtl] .mat-list-base[dense] .mat-list-option .mat-list-avatar~.mat-divider-inset{margin-left:auto;margin-right:68px}.mat-list-base[dense] .mat-list-item .mat-list-icon,.mat-list-base[dense] .mat-list-option .mat-list-icon{flex-shrink:0;width:20px;height:20px;font-size:20px;box-sizing:content-box;border-radius:50%;padding:4px}.mat-list-base[dense] .mat-list-item .mat-list-icon~.mat-divider-inset,.mat-list-base[dense] .mat-list-option .mat-list-icon~.mat-divider-inset{margin-left:60px;width:calc(100% - 60px)}[dir=rtl] .mat-list-base[dense] .mat-list-item .mat-list-icon~.mat-divider-inset,[dir=rtl] .mat-list-base[dense] .mat-list-option .mat-list-icon~.mat-divider-inset{margin-left:auto;margin-right:60px}.mat-list-base[dense] .mat-list-item .mat-divider,.mat-list-base[dense] .mat-list-option .mat-divider{position:absolute;bottom:0;left:0;width:100%;margin:0}[dir=rtl] .mat-list-base[dense] .mat-list-item .mat-divider,[dir=rtl] .mat-list-base[dense] .mat-list-option .mat-divider{margin-left:auto;margin-right:0}.mat-list-base[dense] .mat-list-item .mat-divider.mat-divider-inset,.mat-list-base[dense] .mat-list-option .mat-divider.mat-divider-inset{position:absolute}.mat-nav-list a{text-decoration:none;color:inherit}.mat-nav-list .mat-list-item{cursor:pointer;outline:none}mat-action-list button{background:none;color:inherit;border:none;font:inherit;outline:inherit;-webkit-tap-highlight-color:transparent;text-align:left}[dir=rtl] mat-action-list button{text-align:right}mat-action-list button::-moz-focus-inner{border:0}mat-action-list .mat-list-item{cursor:pointer;outline:inherit}.mat-list-option:not(.mat-list-item-disabled){cursor:pointer;outline:none}.cdk-high-contrast-active .mat-selection-list:focus{outline-style:dotted}.cdk-high-contrast-active .mat-list-option:hover,.cdk-high-contrast-active .mat-list-option:focus,.cdk-high-contrast-active .mat-nav-list .mat-list-item:hover,.cdk-high-contrast-active .mat-nav-list .mat-list-item:focus,.cdk-high-contrast-active mat-action-list .mat-list-item:hover,.cdk-high-contrast-active mat-action-list .mat-list-item:focus{outline:dotted 1px}@media(hover: none){.mat-list-option:not(.mat-list-item-disabled):hover,.mat-nav-list .mat-list-item:not(.mat-list-item-disabled):hover,.mat-action-list .mat-list-item:not(.mat-list-item-disabled):hover{background:none}}\n"], encapsulation: 2, changeDetection: 0 }); /** @nocollapse */ MatSelectionList.ctorParameters = () => [ { type: ElementRef }, { type: String, decorators: [{ type: Attribute, args: ['tabindex',] }] } ]; MatSelectionList.propDecorators = { options: [{ type: ContentChildren, args: [MatListOption, { descendants: true },] }], selectionChange: [{ type: Output }], tabIndex: [{ type: Input }], color: [{ type: Input }], compareWith: [{ type: Input }], disabled: [{ type: Input }] }; /*@__PURE__*/ (function () { ɵngcc0.ɵsetClassMetadata(MatSelectionList, [{ type: Component, args: [{ selector: 'mat-selection-list', exportAs: 'matSelectionList', inputs: ['disableRipple'], host: { 'role': 'listbox', '[tabIndex]': 'tabIndex', 'class': 'mat-selection-list mat-list-base', '(blur)': '_onTouched()', '(keydown)': '_keydown($event)', 'aria-multiselectable': 'true', '[attr.aria-disabled]': 'disabled.toString()' }, template: '<ng-content></ng-content>', encapsulation: ViewEncapsulation.None, providers: [MAT_SELECTION_LIST_VALUE_ACCESSOR], changeDetection: ChangeDetectionStrategy.OnPush, styles: [".mat-subheader{display:flex;box-sizing:border-box;padding:16px;align-items:center}.mat-list-base .mat-subheader{margin:0}.mat-list-base{padding-top:8px;display:block;-webkit-tap-highlight-color:transparent}.mat-list-base .mat-subheader{height:48px;line-height:16px}.mat-list-base .mat-subheader:first-child{margin-top:-8px}.mat-list-base .mat-list-item,.mat-list-base .mat-list-option{display:block;height:48px;-webkit-tap-highlight-color:transparent;width:100%;padding:0}.mat-list-base .mat-list-item .mat-list-item-content,.mat-list-base .mat-list-option .mat-list-item-content{display:flex;flex-direction:row;align-items:center;box-sizing:border-box;padding:0 16px;position:relative;height:inherit}.mat-list-base .mat-list-item .mat-list-item-content-reverse,.mat-list-base .mat-list-option .mat-list-item-content-reverse{display:flex;align-items:center;padding:0 16px;flex-direction:row-reverse;justify-content:space-around}.mat-list-base .mat-list-item .mat-list-item-ripple,.mat-list-base .mat-list-option .mat-list-item-ripple{top:0;left:0;right:0;bottom:0;position:absolute;pointer-events:none}.mat-list-base .mat-list-item.mat-list-item-with-avatar,.mat-list-base .mat-list-option.mat-list-item-with-avatar{height:56px}.mat-list-base .mat-list-item.mat-2-line,.mat-list-base .mat-list-option.mat-2-line{height:72px}.mat-list-base .mat-list-item.mat-3-line,.mat-list-base .mat-list-option.mat-3-line{height:88px}.mat-list-base .mat-list-item.mat-multi-line,.mat-list-base .mat-list-option.mat-multi-line{height:auto}.mat-list-base .mat-list-item.mat-multi-line .mat-list-item-content,.mat-list-base .mat-list-option.mat-multi-line .mat-list-item-content{padding-top:16px;padding-bottom:16px}.mat-list-base .mat-list-item .mat-list-text,.mat-list-base .mat-list-option .mat-list-text{display:flex;flex-direction:column;width:100%;box-sizing:border-box;overflow:hidden;padding:0}.mat-list-base .mat-list-item .mat-list-text>*,.mat-list-base .mat-list-option .mat-list-text>*{margin:0;padding:0;font-weight:normal;font-size:inherit}.mat-list-base .mat-list-item .mat-list-text:empty,.mat-list-base .mat-list-option .mat-list-text:empty{display:none}.mat-list-base .mat-list-item.mat-list-item-with-avatar .mat-list-item-content .mat-list-text,.mat-list-base .mat-list-item.mat-list-option .mat-list-item-content .mat-list-text,.mat-list-base .mat-list-option.mat-list-item-with-avatar .mat-list-item-content .mat-list-text,.mat-list-base .mat-list-option.mat-list-option .mat-list-item-content .mat-list-text{padding-right:0;padding-left:16px}[dir=rtl] .mat-list-base .mat-list-item.mat-list-item-with-avatar .mat-list-item-content .mat-list-text,[dir=rtl] .mat-list-base .mat-list-item.mat-list-option .mat-list-item-content .mat-list-text,[dir=rtl] .mat-list-base .mat-list-option.mat-list-item-with-avatar .mat-list-item-content .mat-list-text,[dir=rtl] .mat-list-base .mat-list-option.mat-list-option .mat-list-item-content .mat-list-text{padding-right:16px;padding-left:0}.mat-list-base .mat-list-item.mat-list-item-with-avatar .mat-list-item-content-reverse .mat-list-text,.mat-list-base .mat-list-item.mat-list-option .mat-list-item-content-reverse .mat-list-text,.mat-list-base .mat-list-option.mat-list-item-with-avatar .mat-list-item-content-reverse .mat-list-text,.mat-list-base .mat-list-option.mat-list-option .mat-list-item-content-reverse .mat-list-text{padding-left:0;padding-right:16px}[dir=rtl] .mat-list-base .mat-list-item.mat-list-item-with-avatar .mat-list-item-content-reverse .mat-list-text,[dir=rtl] .mat-list-base .mat-list-item.mat-list-option .mat-list-item-content-reverse .mat-list-text,[dir=rtl] .mat-list-base .mat-list-option.mat-list-item-with-avatar .mat-list-item-content-reverse .mat-list-text,[dir=rtl] .mat-list-base .mat-list-option.mat-list-option .mat-list-item-content-reverse .mat-list-text{padding-right:0;padding-left:16px}.mat-list-base .mat-list-item.mat-list-item-with-avatar.mat-list-option .mat-list-item-content-reverse .mat-list-text,.mat-list-base .mat-list-item.mat-list-item-with-avatar.mat-list-option .mat-list-item-content .mat-list-text,.mat-list-base .mat-list-option.mat-list-item-with-avatar.mat-list-option .mat-list-item-content-reverse .mat-list-text,.mat-list-base .mat-list-option.mat-list-item-with-avatar.mat-list-option .mat-list-item-content .mat-list-text{padding-right:16px;padding-left:16px}.mat-list-base .mat-list-item .mat-list-avatar,.mat-list-base .mat-list-option .mat-list-avatar{flex-shrink:0;width:40px;height:40px;border-radius:50%;object-fit:cover}.mat-list-base .mat-list-item .mat-list-avatar~.mat-divider-inset,.mat-list-base .mat-list-option .mat-list-avatar~.mat-divider-inset{margin-left:72px;width:calc(100% - 72px)}[dir=rtl] .mat-list-base .mat-list-item .mat-list-avatar~.mat-divider-inset,[dir=rtl] .mat-list-base .mat-list-option .mat-list-avatar~.mat-divider-inset{margin-left:auto;margin-right:72px}.mat-list-base .mat-list-item .mat-list-icon,.mat-list-base .mat-list-option .mat-list-icon{flex-shrink:0;width:24px;height:24px;font-size:24px;box-sizing:content-box;border-radius:50%;padding:4px}.mat-list-base .mat-list-item .mat-list-icon~.mat-divider-inset,.mat-list-base .mat-list-option .mat-list-icon~.mat-divider-inset{margin-left:64px;width:calc(100% - 64px)}[dir=rtl] .mat-list-base .mat-list-item .mat-list-icon~.mat-divider-inset,[dir=rtl] .mat-list-base .mat-list-option .mat-list-icon~.mat-divider-inset{margin-left:auto;margin-right:64px}.mat-list-base .mat-list-item .mat-divider,.mat-list-base .mat-list-option .mat-divider{position:absolute;bottom:0;left:0;width:100%;margin:0}[dir=rtl] .mat-list-base .mat-list-item .mat-divider,[dir=rtl] .mat-list-base .mat-list-option .mat-divider{margin-left:auto;margin-right:0}.mat-list-base .mat-list-item .mat-divider.mat-divider-inset,.mat-list-base .mat-list-option .mat-divider.mat-divider-inset{position:absolute}.mat-list-base[dense]{padding-top:4px;display:block}.mat-list-base[dense] .mat-subheader{height:40px;line-height:8px}.mat-list-base[dense] .mat-subheader:first-child{margin-top:-4px}.mat-list-base[dense] .mat-list-item,.mat-list-base[dense] .mat-list-option{display:block;height:40px;-webkit-tap-highlight-color:transparent;width:100%;padding:0}.mat-list-base[dense] .mat-list-item .mat-list-item-content,.mat-list-base[dense] .mat-list-option .mat-list-item-content{display:flex;flex-direction:row;align-items:center;box-sizing:border-box;padding:0 16px;position:relative;height:inherit}.mat-list-base[dense] .mat-list-item .mat-list-item-content-reverse,.mat-list-base[dense] .mat-list-option .mat-list-item-content-reverse{display:flex;align-items:center;padding:0 16px;flex-direction:row-reverse;justify-content:space-around}.mat-list-base[dense] .mat-list-item .mat-list-item-ripple,.mat-list-base[dense] .mat-list-option .mat-list-item-ripple{top:0;left:0;right:0;bottom:0;position:absolute;pointer-events:none}.mat-list-base[dense] .mat-list-item.mat-list-item-with-avatar,.mat-list-base[dense] .mat-list-option.mat-list-item-with-avatar{height:48px}.mat-list-base[dense] .mat-list-item.mat-2-line,.mat-list-base[dense] .mat-list-option.mat-2-line{height:60px}.mat-list-base[dense] .mat-list-item.mat-3-line,.mat-list-base[dense] .mat-list-option.mat-3-line{height:76px}.mat-list-base[dense] .mat-list-item.mat-multi-line,.mat-list-base[dense] .mat-list-option.mat-multi-line{height:auto}.mat-list-base[dense] .mat-list-item.mat-multi-line .mat-list-item-content,.mat-list-base[dense] .mat-list-option.mat-multi-line .mat-list-item-content{padding-top:16px;padding-bottom:16px}.mat-list-base[dense] .mat-list-item .mat-list-text,.mat-list-base[dense] .mat-list-option .mat-list-text{display:flex;flex-direction:column;width:100%;box-sizing:border-box;overflow:hidden;padding:0}.mat-list-base[dense] .mat-list-item .mat-list-text>*,.mat-list-base[dense] .mat-list-option .mat-list-text>*{margin:0;padding:0;font-weight:normal;font-size:inherit}.mat-list-base[dense] .mat-list-item .mat-list-text:empty,.mat-list-base[dense] .mat-list-option .mat-list-text:empty{display:none}.mat-list-base[dense] .mat-list-item.mat-list-item-with-avatar .mat-list-item-content .mat-list-text,.mat-list-base[dense] .mat-list-item.mat-list-option .mat-list-item-content .mat-list-text,.mat-list-base[dense] .mat-list-option.mat-list-item-with-avatar .mat-list-item-content .mat-list-text,.mat-list-base[dense] .mat-list-option.mat-list-option .mat-list-item-content .mat-list-text{padding-right:0;padding-left:16px}[dir=rtl] .mat-list-base[dense] .mat-list-item.mat-list-item-with-avatar .mat-list-item-content .mat-list-text,[dir=rtl] .mat-list-base[dense] .mat-list-item.mat-list-option .mat-list-item-content .mat-list-text,[dir=rtl] .mat-list-base[dense] .mat-list-option.mat-list-item-with-avatar .mat-list-item-content .mat-list-text,[dir=rtl] .mat-list-base[dense] .mat-list-option.mat-list-option .mat-list-item-content .mat-list-text{padding-right:16px;padding-left:0}.mat-list-base[dense] .mat-list-item.mat-list-item-with-avatar .mat-list-item-content-reverse .mat-list-text,.mat-list-base[dense] .mat-list-item.mat-list-option .mat-list-item-content-reverse .mat-list-text,.mat-list-base[dense] .mat-list-option.mat-list-item-with-avatar .mat-list-item-content-reverse .mat-list-text,.mat-list-base[dense] .mat-list-option.mat-list-option .mat-list-item-content-reverse .mat-list-text{padding-left:0;padding-right:16px}[dir=rtl] .mat-list-base[dense] .mat-list-item.mat-list-item-with-avatar .mat-list-item-content-reverse .mat-list-text,[dir=rtl] .mat-list-base[dense] .mat-list-item.mat-list-option .mat-list-item-content-reverse .mat-list-text,[dir=rtl] .mat-list-base[dense] .mat-list-option.mat-list-item-with-avatar .mat-list-item-content-reverse .mat-list-text,[dir=rtl] .mat-list-base[dense] .mat-list-option.mat-list-option .mat-list-item-content-reverse .mat-list-text{padding-right:0;padding-left:16px}.mat-list-base[dense] .mat-list-item.mat-list-item-with-avatar.mat-list-option .mat-list-item-content-reverse .mat-list-text,.mat-list-base[dense] .mat-list-item.mat-list-item-with-avatar.mat-list-option .mat-list-item-content .mat-list-text,.mat-list-base[dense] .mat-list-option.mat-list-item-with-avatar.mat-list-option .mat-list-item-content-reverse .mat-list-text,.mat-list-base[dense] .mat-list-option.mat-list-item-with-avatar.mat-list-option .mat-list-item-content .mat-list-text{padding-right:16px;padding-left:16px}.mat-list-base[dense] .mat-list-item .mat-list-avatar,.mat-list-base[dense] .mat-list-option .mat-list-avatar{flex-shrink:0;width:36px;height:36px;border-radius:50%;object-fit:cover}.mat-list-base[dense] .mat-list-item .mat-list-avatar~.mat-divider-inset,.mat-list-base[dense] .mat-list-option .mat-list-avatar~.mat-divider-inset{margin-left:68px;width:calc(100% - 68px)}[dir=rtl] .mat-list-base[dense] .mat-list-item .mat-list-avatar~.mat-divider-inset,[dir=rtl] .mat-list-base[dense] .mat-list-option .mat-list-avatar~.mat-divider-inset{margin-left:auto;margin-right:68px}.mat-list-base[dense] .mat-list-item .mat-list-icon,.mat-list-base[dense] .mat-list-option .mat-list-icon{flex-shrink:0;width:20px;height:20px;font-size:20px;box-sizing:content-box;border-radius:50%;padding:4px}.mat-list-base[dense] .mat-list-item .mat-list-icon~.mat-divider-inset,.mat-list-base[dense] .mat-list-option .mat-list-icon~.mat-divider-inset{margin-left:60px;width:calc(100% - 60px)}[dir=rtl] .mat-list-base[dense] .mat-list-item .mat-list-icon~.mat-divider-inset,[dir=rtl] .mat-list-base[dense] .mat-list-option .mat-list-icon~.mat-divider-inset{margin-left:auto;margin-right:60px}.mat-list-base[dense] .mat-list-item .mat-divider,.mat-list-base[dense] .mat-list-option .mat-divider{position:absolute;bottom:0;left:0;width:100%;margin:0}[dir=rtl] .mat-list-base[dense] .mat-list-item .mat-divider,[dir=rtl] .mat-list-base[dense] .mat-list-option .mat-divider{margin-left:auto;margin-right:0}.mat-list-base[dense] .mat-list-item .mat-divider.mat-divider-inset,.mat-list-base[dense] .mat-list-option .mat-divider.mat-divider-inset{position:absolute}.mat-nav-list a{text-decoration:none;color:inherit}.mat-nav-list .mat-list-item{cursor:pointer;outline:none}mat-action-list button{background:none;color:inherit;border:none;font:inherit;outline:inherit;-webkit-tap-highlight-color:transparent;text-align:left}[dir=rtl] mat-action-list button{text-align:right}mat-action-list button::-moz-focus-inner{border:0}mat-action-list .mat-list-item{cursor:pointer;outline:inherit}.mat-list-option:not(.mat-list-item-disabled){cursor:pointer;outline:none}.cdk-high-contrast-active .mat-selection-list:focus{outline-style:dotted}.cdk-high-contrast-active .mat-list-option:hover,.cdk-high-contrast-active .mat-list-option:focus,.cdk-high-contrast-active .mat-nav-list .mat-list-item:hover,.cdk-high-contrast-active .mat-nav-list .mat-list-item:focus,.cdk-high-contrast-active mat-action-list .mat-list-item:hover,.cdk-high-contrast-active mat-action-list .mat-list-item:focus{outline:dotted 1px}@media(hover: none){.mat-list-option:not(.mat-list-item-disabled):hover,.mat-nav-list .mat-list-item:not(.mat-list-item-disabled):hover,.mat-action-list .mat-list-item:not(.mat-list-item-disabled):hover{background:none}}\n"] }] }], function () { return [{ type: ɵngcc0.ElementRef }, { type: String, decorators: [{ type: Attribute, args: ['tabindex'] }] }]; }, { selectionChange: [{ type: Output }], tabIndex: [{ type: Input }], color: [{ type: Input }], compareWith: [{ type: Input }], disabled: [{ type: Input }], options: [{ type: ContentChildren, args: [MatListOption, { descendants: true }] }] }); })(); if (false) { /** @type {?} */ MatSelectionList.ngAcceptInputType_disabled; /** @type {?} */ MatSelectionList.ngAcceptInputType_disableRipple; /** * The FocusKeyManager which handles focus. * @type {?} */ MatSelectionList.prototype._keyManager; /** * The option components contained within this selection-list. * @type {?} */ MatSelectionList.prototype.options; /** * Emits a change event whenever the selected state of an option changes. * @type {?} */ MatSelectionList.prototype.selectionChange; /** * Tabindex of the selection list. * @type {?} */ MatSelectionList.prototype.tabIndex; /** * Theme color of the selection list. This sets the checkbox color for all list options. * @type {?} */ MatSelectionList.prototype.color; /** * Function used for comparing an option against the selected value when determining which * options should appear as selected. The first argument is the value of an options. The second * one is a value from the selected value. A boolean must be returned. * @type {?} */ MatSelectionList.prototype.compareWith; /** * @type {?} * @private */ MatSelectionList.prototype._disabled; /** * The currently selected options. * @type {?} */ MatSelectionList.prototype.selectedOptions; /** * View to model callback that should be called whenever the selected options change. * @type {?} * @private */ MatSelectionList.prototype._onChange; /** * Keeps track of the currently-selected value. * @type {?} */ MatSelectionList.prototype._value; /** * Emits when the list has been destroyed. * @type {?} * @private */ MatSelectionList.prototype._destroyed; /** * View to model callback that should be called if the list or its options lost focus. * @type {?} */ MatSelectionList.prototype._onTouched; /** * Whether the list has been destroyed. * @type {?} * @private */ MatSelectionList.prototype._isDestroyed; /** * @type {?} * @private */ MatSelectionList.prototype._element; } /** * @fileoverview added by tsickle * Generated from: src/material/list/list-module.ts * @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc */ class MatListModule { } MatListModule.ɵmod = ɵngcc0.ɵɵdefineNgModule({ type: MatListModule }); MatListModule.ɵinj = ɵngcc0.ɵɵdefineInjector({ factory: function MatListModule_Factory(t) { return new (t || MatListModule)(); }, imports: [[MatLineModule, MatRippleModule, MatCommonModule, MatPseudoCheckboxModule, CommonModule], MatLineModule, MatCommonModule, MatPseudoCheckboxModule, MatDividerModule] }); (function () { (typeof ngJitMode === "undefined" || ngJitMode) && ɵngcc0.ɵɵsetNgModuleScope(MatListModule, { declarations: function () { return [MatList, MatNavList, MatListItem, MatListAvatarCssMatStyler, MatListIconCssMatStyler, MatListSubheaderCssMatStyler, MatSelectionList, MatListOption]; }, imports: function () { return [MatLineModule, MatRippleModule, MatCommonModule, MatPseudoCheckboxModule, CommonModule]; }, exports: function () { return [MatList, MatNavList, MatListItem, MatListAvatarCssMatStyler, MatLineModule, MatCommonModule, MatListIconCssMatStyler, MatListSubheaderCssMatStyler, MatPseudoCheckboxModule, MatSelectionList, MatListOption, MatDividerModule]; } }); })(); /*@__PURE__*/ (function () { ɵngcc0.ɵsetClassMetadata(MatListModule, [{ type: NgModule, args: [{ imports: [MatLineModule, MatRippleModule, MatCommonModule, MatPseudoCheckboxModule, CommonModule], exports: [ MatList, MatNavList, MatListItem, MatListAvatarCssMatStyler, MatLineModule, MatCommonModule, MatListIconCssMatStyler, MatListSubheaderCssMatStyler, MatPseudoCheckboxModule, MatSelectionList, MatListOption, MatDividerModule ], declarations: [ MatList, MatNavList, MatListItem, MatListAvatarCssMatStyler, MatListIconCssMatStyler, MatListSubheaderCssMatStyler, MatSelectionList, MatListOption ] }] }], null, null); })(); /** * @fileoverview added by tsickle * Generated from: src/material/list/public-api.ts * @suppress {checkTypes,constantProperty,extraRequire,missingOverride,missingReturn,unusedPrivateMembers,uselessCode} checked by tsc */ /** * Generated bundle index. Do not edit. */ export { MAT_SELECTION_LIST_VALUE_ACCESSOR, MatList, MatListAvatarCssMatStyler, MatListIconCssMatStyler, MatListItem, MatListModule, MatListOption, MatListSubheaderCssMatStyler, MatNavList, MatSelectionList, MatSelectionListChange }; //# sourceMappingURL=list.js.map
import os from routes import url_for from paste import fixture from paste.deploy import loadapp import pytest from ddtrace.ext import http, errors from ddtrace.constants import SAMPLING_PRIORITY_KEY, ANALYTICS_SAMPLE_RATE_KEY from ddtrace.contrib.pylons import PylonsTraceMiddleware from tests.opentracer.utils import init_tracer from ...base import BaseTracerTestCase class PylonsTestCase(BaseTracerTestCase): """Pylons Test Controller that is used to test specific cases defined in the Pylons controller. To test a new behavior, add a new action in the `app.controllers.root` module. """ conf_dir = os.path.dirname(os.path.abspath(__file__)) def setUp(self): super(PylonsTestCase, self).setUp() # initialize a real traced Pylons app wsgiapp = loadapp('config:test.ini', relative_to=PylonsTestCase.conf_dir) self._wsgiapp = wsgiapp app = PylonsTraceMiddleware(wsgiapp, self.tracer, service='web') self.app = fixture.TestApp(app) def test_controller_exception(self): """Ensure exceptions thrown in controllers can be handled. No error tags should be set in the span. """ from .app.middleware import ExceptionToSuccessMiddleware wsgiapp = ExceptionToSuccessMiddleware(self._wsgiapp) app = PylonsTraceMiddleware(wsgiapp, self.tracer, service='web') app = fixture.TestApp(app) app.get(url_for(controller='root', action='raise_exception')) spans = self.tracer.writer.pop() assert spans, spans assert len(spans) == 1 span = spans[0] assert span.service == 'web' assert span.resource == 'root.raise_exception' assert span.error == 0 assert span.get_tag(http.URL) == 'http://localhost:80/raise_exception' assert span.get_tag('http.status_code') == '200' assert span.get_tag(errors.ERROR_MSG) is None assert span.get_tag(errors.ERROR_TYPE) is None assert span.get_tag(errors.ERROR_STACK) is None assert span.span_type == 'http' def test_mw_exc_success(self): """Ensure exceptions can be properly handled by other middleware. No error should be reported in the span. """ from .app.middleware import ExceptionMiddleware, ExceptionToSuccessMiddleware wsgiapp = ExceptionMiddleware(self._wsgiapp) wsgiapp = ExceptionToSuccessMiddleware(wsgiapp) app = PylonsTraceMiddleware(wsgiapp, self.tracer, service='web') app = fixture.TestApp(app) app.get(url_for(controller='root', action='index')) spans = self.tracer.writer.pop() assert spans, spans assert len(spans) == 1 span = spans[0] assert span.service == 'web' assert span.resource == 'None.None' assert span.error == 0 assert span.get_tag(http.URL) == 'http://localhost:80/' assert span.get_tag('http.status_code') == '200' assert span.get_tag(errors.ERROR_MSG) is None assert span.get_tag(errors.ERROR_TYPE) is None assert span.get_tag(errors.ERROR_STACK) is None def test_middleware_exception(self): """Ensure exceptions raised in middleware are properly handled. Uncaught exceptions should result in error tagged spans. """ from .app.middleware import ExceptionMiddleware wsgiapp = ExceptionMiddleware(self._wsgiapp) app = PylonsTraceMiddleware(wsgiapp, self.tracer, service='web') app = fixture.TestApp(app) with pytest.raises(Exception): app.get(url_for(controller='root', action='index')) spans = self.tracer.writer.pop() assert spans, spans assert len(spans) == 1 span = spans[0] assert span.service == 'web' assert span.resource == 'None.None' assert span.error == 1 assert span.get_tag(http.URL) == 'http://localhost:80/' assert span.get_tag('http.status_code') == '500' assert span.get_tag(errors.ERROR_MSG) == 'Middleware exception' assert span.get_tag(errors.ERROR_TYPE) == 'exceptions.Exception' assert span.get_tag(errors.ERROR_STACK) def test_exc_success(self): from .app.middleware import ExceptionToSuccessMiddleware wsgiapp = ExceptionToSuccessMiddleware(self._wsgiapp) app = PylonsTraceMiddleware(wsgiapp, self.tracer, service='web') app = fixture.TestApp(app) app.get(url_for(controller='root', action='raise_exception')) spans = self.tracer.writer.pop() assert spans, spans assert len(spans) == 1 span = spans[0] assert span.service == 'web' assert span.resource == 'root.raise_exception' assert span.error == 0 assert span.get_tag(http.URL) == 'http://localhost:80/raise_exception' assert span.get_tag('http.status_code') == '200' assert span.get_tag(errors.ERROR_MSG) is None assert span.get_tag(errors.ERROR_TYPE) is None assert span.get_tag(errors.ERROR_STACK) is None def test_exc_client_failure(self): from .app.middleware import ExceptionToClientErrorMiddleware wsgiapp = ExceptionToClientErrorMiddleware(self._wsgiapp) app = PylonsTraceMiddleware(wsgiapp, self.tracer, service='web') app = fixture.TestApp(app) app.get(url_for(controller='root', action='raise_exception'), status=404) spans = self.tracer.writer.pop() assert spans, spans assert len(spans) == 1 span = spans[0] assert span.service == 'web' assert span.resource == 'root.raise_exception' assert span.error == 0 assert span.get_tag(http.URL) == 'http://localhost:80/raise_exception' assert span.get_tag('http.status_code') == '404' assert span.get_tag(errors.ERROR_MSG) is None assert span.get_tag(errors.ERROR_TYPE) is None assert span.get_tag(errors.ERROR_STACK) is None def test_success_200(self): res = self.app.get(url_for(controller='root', action='index')) assert res.status == 200 spans = self.tracer.writer.pop() assert spans, spans assert len(spans) == 1 span = spans[0] assert span.service == 'web' assert span.resource == 'root.index' assert span.meta.get(http.STATUS_CODE) == '200' assert span.error == 0 def test_analytics_global_on_integration_default(self): """ When making a request When an integration trace search is not event sample rate is not set and globally trace search is enabled We expect the root span to have the appropriate tag """ with self.override_global_config(dict(analytics_enabled=True)): res = self.app.get(url_for(controller='root', action='index')) self.assertEqual(res.status, 200) self.assert_structure( dict(name='pylons.request', metrics={ANALYTICS_SAMPLE_RATE_KEY: 1.0}) ) def test_analytics_global_on_integration_on(self): """ When making a request When an integration trace search is enabled and sample rate is set and globally trace search is enabled We expect the root span to have the appropriate tag """ with self.override_global_config(dict(analytics_enabled=True)): with self.override_config('pylons', dict(analytics_enabled=True, analytics_sample_rate=0.5)): res = self.app.get(url_for(controller='root', action='index')) self.assertEqual(res.status, 200) self.assert_structure( dict(name='pylons.request', metrics={ANALYTICS_SAMPLE_RATE_KEY: 0.5}) ) def test_analytics_global_off_integration_default(self): """ When making a request When an integration trace search is not set and sample rate is set and globally trace search is disabled We expect the root span to not include tag """ with self.override_global_config(dict(analytics_enabled=False)): res = self.app.get(url_for(controller='root', action='index')) self.assertEqual(res.status, 200) root = self.get_root_span() self.assertIsNone(root.get_metric(ANALYTICS_SAMPLE_RATE_KEY)) def test_analytics_global_off_integration_on(self): """ When making a request When an integration trace search is enabled and sample rate is set and globally trace search is disabled We expect the root span to have the appropriate tag """ with self.override_global_config(dict(analytics_enabled=False)): with self.override_config('pylons', dict(analytics_enabled=True, analytics_sample_rate=0.5)): res = self.app.get(url_for(controller='root', action='index')) self.assertEqual(res.status, 200) self.assert_structure( dict(name='pylons.request', metrics={ANALYTICS_SAMPLE_RATE_KEY: 0.5}) ) def test_template_render(self): res = self.app.get(url_for(controller='root', action='render')) assert res.status == 200 spans = self.tracer.writer.pop() assert spans, spans assert len(spans) == 2 request = spans[0] template = spans[1] assert request.service == 'web' assert request.resource == 'root.render' assert request.meta.get(http.STATUS_CODE) == '200' assert request.error == 0 assert template.service == 'web' assert template.resource == 'pylons.render' assert template.meta.get('template.name') == '/template.mako' assert template.error == 0 def test_template_render_exception(self): with pytest.raises(Exception): self.app.get(url_for(controller='root', action='render_exception')) spans = self.tracer.writer.pop() assert spans, spans assert len(spans) == 2 request = spans[0] template = spans[1] assert request.service == 'web' assert request.resource == 'root.render_exception' assert request.meta.get(http.STATUS_CODE) == '500' assert request.error == 1 assert template.service == 'web' assert template.resource == 'pylons.render' assert template.meta.get('template.name') == '/exception.mako' assert template.error == 1 assert template.get_tag('error.msg') == 'integer division or modulo by zero' assert 'ZeroDivisionError: integer division or modulo by zero' in template.get_tag('error.stack') def test_failure_500(self): with pytest.raises(Exception): self.app.get(url_for(controller='root', action='raise_exception')) spans = self.tracer.writer.pop() assert spans, spans assert len(spans) == 1 span = spans[0] assert span.service == 'web' assert span.resource == 'root.raise_exception' assert span.error == 1 assert span.get_tag('http.status_code') == '500' assert span.get_tag('error.msg') == 'Ouch!' assert span.get_tag(http.URL) == 'http://localhost:80/raise_exception' assert 'Exception: Ouch!' in span.get_tag('error.stack') def test_failure_500_with_wrong_code(self): with pytest.raises(Exception): self.app.get(url_for(controller='root', action='raise_wrong_code')) spans = self.tracer.writer.pop() assert spans, spans assert len(spans) == 1 span = spans[0] assert span.service == 'web' assert span.resource == 'root.raise_wrong_code' assert span.error == 1 assert span.get_tag('http.status_code') == '500' assert span.meta.get(http.URL) == 'http://localhost:80/raise_wrong_code' assert span.get_tag('error.msg') == 'Ouch!' assert 'Exception: Ouch!' in span.get_tag('error.stack') def test_failure_500_with_custom_code(self): with pytest.raises(Exception): self.app.get(url_for(controller='root', action='raise_custom_code')) spans = self.tracer.writer.pop() assert spans, spans assert len(spans) == 1 span = spans[0] assert span.service == 'web' assert span.resource == 'root.raise_custom_code' assert span.error == 1 assert span.get_tag('http.status_code') == '512' assert span.meta.get(http.URL) == 'http://localhost:80/raise_custom_code' assert span.get_tag('error.msg') == 'Ouch!' assert 'Exception: Ouch!' in span.get_tag('error.stack') def test_failure_500_with_code_method(self): with pytest.raises(Exception): self.app.get(url_for(controller='root', action='raise_code_method')) spans = self.tracer.writer.pop() assert spans, spans assert len(spans) == 1 span = spans[0] assert span.service == 'web' assert span.resource == 'root.raise_code_method' assert span.error == 1 assert span.get_tag('http.status_code') == '500' assert span.meta.get(http.URL) == 'http://localhost:80/raise_code_method' assert span.get_tag('error.msg') == 'Ouch!' def test_distributed_tracing_default(self): # ensure by default, distributed tracing is not enabled headers = { 'x-datadog-trace-id': '100', 'x-datadog-parent-id': '42', 'x-datadog-sampling-priority': '2', } res = self.app.get(url_for(controller='root', action='index'), headers=headers) assert res.status == 200 spans = self.tracer.writer.pop() assert spans, spans assert len(spans) == 1 span = spans[0] assert span.trace_id == 100 assert span.parent_id == 42 assert span.get_metric(SAMPLING_PRIORITY_KEY) == 2 def test_distributed_tracing_disabled(self): # ensure distributed tracing propagator is working middleware = self.app.app middleware._distributed_tracing = False headers = { 'x-datadog-trace-id': '100', 'x-datadog-parent-id': '42', 'x-datadog-sampling-priority': '2', } res = self.app.get(url_for(controller='root', action='index'), headers=headers) assert res.status == 200 spans = self.tracer.writer.pop() assert spans, spans assert len(spans) == 1 span = spans[0] assert span.trace_id != 100 assert span.parent_id != 42 assert span.get_metric(SAMPLING_PRIORITY_KEY) != 2 def test_success_200_ot(self): """OpenTracing version of test_success_200.""" ot_tracer = init_tracer('pylons_svc', self.tracer) with ot_tracer.start_active_span('pylons_get'): res = self.app.get(url_for(controller='root', action='index')) assert res.status == 200 spans = self.tracer.writer.pop() assert spans, spans assert len(spans) == 2 ot_span, dd_span = spans # confirm the parenting assert ot_span.parent_id is None assert dd_span.parent_id == ot_span.span_id assert ot_span.name == 'pylons_get' assert ot_span.service == 'pylons_svc' assert dd_span.service == 'web' assert dd_span.resource == 'root.index' assert dd_span.meta.get(http.STATUS_CODE) == '200' assert dd_span.meta.get(http.URL) == 'http://localhost:80/' assert dd_span.error == 0
# Lint as: python3 # Copyright 2019 The TensorFlow Authors. 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. # ============================================================================== """The compatible tensorflow library.""" import tensorflow.compat.v1 as tf1 from tensorflow.compat.v2 import * # pylint:disable=wildcard-import, g-bad-import-order # Import absl.flags and absl.logging to overwrite the Tensorflow ones. # This is the intended behavior in TF 2.0. # pylint:disable=g-bad-import-order, unused-import, g-import-not-at-top from absl import flags from absl import logging # pylint: disable=g-direct-tensorflow-import from tensorflow.core.protobuf import config_pb2 from tensorflow.python.data.ops import dataset_ops from tensorflow.python.data.util import random_seed from tensorflow.python.framework import function as _function_lib from tensorflow.python.framework import ops from tensorflow.python.ops import array_ops from tensorflow.python.ops import check_ops from tensorflow.python.ops import embedding_ops from tensorflow.python.ops import functional_ops from tensorflow.python.ops import gen_dataset_ops from tensorflow.python.ops import gen_io_ops from tensorflow.python.ops import inplace_ops from tensorflow.python.ops import math_ops from tensorflow.python.platform import app from tensorflow.python.util import module_wrapper as _module_wrapper # pylint: enable=g-direct-tensorflow-import # pylint: enable=unused-import, g-bad-import-order, g-import-not-at-top if tf1.executing_eagerly(): logging.warning("Lingvo does not support eager execution yet. Please disable " "eager execution with tf.compat.v1.disable_eager_execution() " "or proceed at your own risk.") def _clone_module(m): """Shallow clone of module `m`.""" if isinstance(m, _module_wrapper.TFModuleWrapper): # pylint: disable=protected-access return _module_wrapper.TFModuleWrapper( wrapped=_clone_module(m._tfmw_wrapped_module), module_name=m._tfmw_module_name, public_apis=m._tfmw_public_apis, deprecation=m._tfmw_print_deprecation_warnings, has_lite=m._tfmw_has_lite) # pylint: enable=protected-access out = type(m)(m.__name__, m.__doc__) out.__dict__.update(m.__dict__) return out # Aliases to a few routines lingvo libraries uses often. Defun = _function_lib.Defun While = functional_ops.While If = functional_ops.If InplaceUpdate = inplace_ops.alias_inplace_update Empty = inplace_ops.empty EmptyLike = inplace_ops.empty_like # pylint: disable=undefined-variable, used-before-assignment # Move this V2 symbol here to avoid being overwritten by its following V1 # version. where_v2 = where while_loop_v2 = while_loop # Import the local V2 module to maker sure the following V1 overwritting never # applies to the global module and symbol. data = _clone_module(data) graph_util = _clone_module(graph_util) image = _clone_module(image) io = _clone_module(io) losses = _clone_module(keras.losses) metrics = _clone_module(keras.metrics) nn = _clone_module(nn) saved_model = _clone_module(saved_model) strings = _clone_module(strings) summary = _clone_module(summary) test = _clone_module(test) train = _clone_module(train) # By default, with TF2 enabled and (eager execution or tf.function), # `tf.data` API will choose the stateful implementation for methods # `tf.data.Dataset.shuffle()`, `tf.data.Dataset.cache()` and # `tf.data.Dataset.list_files()`. which is not compatible with # `tf.data.make_one_shot_iterator` in TF2 (see b/162270607). # Here is a stateless implementation of `shuffle`, `cache` and # `list_files` to resolve the TF2 imcompatibility issue. # Note that, these methods are meant for internal use only. Please don't use # it unless you know exactly what you do. class _CacheDataset(dataset_ops.UnaryUnchangedStructureDataset): """A `Dataset` that caches elements of its input.""" def __init__(self, input_dataset, filename): """Caches the elements in the dataset.""" self._input_dataset = input_dataset self._filename = ops.convert_to_tensor( filename, dtype=string, name="filename") variant_tensor = gen_dataset_ops.cache_dataset( input_dataset._variant_tensor, # pylint: disable=protected-access filename=self._filename, **self._flat_structure) super(_CacheDataset, self).__init__(input_dataset, variant_tensor) class _ShuffleDataset(dataset_ops.UnaryUnchangedStructureDataset): """A `Dataset` that randomly shuffles the elements of its input.""" def __init__(self, input_dataset, buffer_size, seed=None, reshuffle_each_iteration=None): """Randomly shuffles the elements of this dataset.""" self._input_dataset = input_dataset self._buffer_size = ops.convert_to_tensor( buffer_size, dtype=int64, name="buffer_size") self._seed, self._seed2 = random_seed.get_seed(seed) if reshuffle_each_iteration is None: reshuffle_each_iteration = True self._reshuffle_each_iteration = reshuffle_each_iteration variant_tensor = gen_dataset_ops.shuffle_dataset( input_dataset._variant_tensor, # pylint: disable=protected-access buffer_size=self._buffer_size, seed=self._seed, seed2=self._seed2, reshuffle_each_iteration=self._reshuffle_each_iteration, **self._flat_structure) super(_ShuffleDataset, self).__init__(input_dataset, variant_tensor) def stateless_shuffle_dataset(buffer_size, seed=None, reshuffle_each_iteration=None): """Randomly shuffles the elements of the dataset based on a stateless shuffle implementation. This method returns a stateless ShuffleDataset unconditionally. It can be used with `dataset.apply()` to obtain a stateless shuffled dataset, which supports the TF1 compatibility API `tf.data.make_one_shot_iterator()` in TF2. Example: >>> dataset = tf.data.Dataset.range(3) >>> dataset = dataset.apply( ... stateless_shuffle_dataset((3, reshuffle_each_iteration=True)) Args: buffer_size: A `tf.int64` scalar `tf.Tensor`, representing the number of elements from this dataset from which the new dataset will sample. seed: (Optional.) A `tf.int64` scalar `tf.Tensor`, representing the random seed that will be used to create the distribution. See `tf.random.set_seed` for behavior. reshuffle_each_iteration: (Optional.) A boolean, which if true indicates that the dataset should be pseudorandomly reshuffled each time it is iterated over. (Defaults to `True`.) Returns: Dataset: A `Dataset`. """ def _apply_fn(dataset): out_dataset = dataset_ops.DatasetV1Adapter( _ShuffleDataset(dataset, buffer_size, seed, reshuffle_each_iteration)) return out_dataset return _apply_fn def stateless_cache_dataset(filename=""): """Caches the elements in the dataset based on a stateless cache implementation. This method returns a stateless CacheDataset unconditionally. It can be used with `dataset.apply()` to obtain a stateless cached dataset, which supports the TF1 compatibility API `tf.data.make_one_shot_iterator()` in TF2. Example: >>> dataset = tf.data.Dataset.range(3) >>> dataset = dataset.apply(stateless_cache_dataset()) Args: filename: A `tf.string` scalar `tf.Tensor`, representing the name of a directory on the filesystem to use for caching elements in this Dataset. If a filename is not provided, the dataset will be cached in memory. Returns: Dataset: A `Dataset`. """ def _apply_fn(dataset): out_dataset = dataset_ops.DatasetV1Adapter(_CacheDataset(dataset, filename)) return out_dataset return _apply_fn def stateless_list_files(file_pattern, shuffle=None, seed=None): """A dataset of all files matching one or more glob patterns. Note that, if `shuffle` is not None, it will use a stateless shuffle implementation. Then the returned dataset supports the TF1 compatibility API `tf.data.make_one_shot_iterator()` in TF2. Example: >>> dataset = tf.stateless_list_files("some_file_pattern") Args: file_pattern: A string, a list of strings, or a `tf.Tensor` of string type (scalar or vector), representing the filename glob (i.e. shell wildcard) pattern(s) that will be matched. shuffle: (Optional.) If `True`, the file names will be shuffled randomly based on a stateless implementation. Defaults to `True`. seed: (Optional.) A `tf.int64` scalar `tf.Tensor`, representing the random seed that will be used to create the distribution. See `tf.random.set_seed` for behavior. Returns: Dataset: A `Dataset` of strings corresponding to file names. """ with ops.name_scope("list_files"): if shuffle is None: shuffle = True file_pattern = ops.convert_to_tensor( file_pattern, dtype=string, name="file_pattern") matching_files = gen_io_ops.matching_files(file_pattern) # Raise an exception if `file_pattern` does not match any files. condition = math_ops.greater( array_ops.shape(matching_files)[0], 0, name="match_not_empty") message = math_ops.add( "No files matched pattern: ", strings.reduce_join(file_pattern, separator=", "), name="message") assert_not_empty = debugging.Assert( condition, [message], summarize=1, name="assert_not_empty") with control_dependencies([assert_not_empty]): matching_files = identity(matching_files) dataset = data.Dataset.from_tensor_slices(matching_files) if shuffle: buffer_size = math_ops.maximum( shape(matching_files, out_type=dtypes.int64)[0], 1) # Use stateless shuffled dataset dataset = dataset.apply(stateless_shuffle_dataset(buffer_size, seed=seed)) return dataset # pylint: enable=undefined-variable, used-before-assignment # TF 1.x symbols used in the codebase. # To keep this list short, please use TF 2.x API whenever applicable. # Only use TF 1.x API if it has no 2.x equivalent. # pylint: disable=undefined-variable add_to_collection = tf1.add_to_collection all_variables = tf1.global_variables # The following asserts can be directly replaced with TF2 `tf.debugging.*` # after TF2/eager is enabled. assert_integer = tf1.assert_integer assert_positive = tf1.assert_positive assert_type = tf1.assert_type assert_scalar = tf1.assert_scalar assign = tf1.assign assign_add = tf1.assign_add assign_sub = tf1.assign_sub AUTO_REUSE = tf1.AUTO_REUSE container = tf1.container data.Dataset = tf1.data.Dataset data.TFRecordDataset = tf1.data.TFRecordDataset device = tf1.device Dimension = tf1.Dimension disable_eager_execution = tf1.disable_eager_execution div = tf1.div enable_eager_execution = tf1.enable_eager_execution floor_div = tf1.floor_div get_collection = tf1.get_collection get_collection_ref = tf1.get_collection_ref get_default_graph = tf1.get_default_graph get_local_variable = tf1.get_local_variable get_seed = tf1.get_seed get_variable = tf1.get_variable get_variable_scope = tf1.get_variable_scope global_variables = tf1.global_variables global_variables_initializer = tf1.global_variables_initializer gradients = tf1.gradients graph_util.convert_variables_to_constants = ( tf1.graph_util.convert_variables_to_constants) graph_util.extract_sub_graph = tf1.graph_util.extract_sub_graph GraphDef = tf1.GraphDef GraphKeys = tf1.GraphKeys GraphOptions = tf1.GraphOptions group = tf1.group image.resize_bilinear = tf1.image.resize_bilinear image.resize_images = tf1.image.resize_images image.resize_nearest_neighbor = tf1.image.resize_nearest_neighbor initialize_all_tables = tf1.initialize_all_tables InteractiveSession = tf1.InteractiveSession io.tf_record_iterator = tf1.io.tf_record_iterator layers = tf1.layers local_variables_initializer = tf1.local_variables_initializer losses.absolute_difference = tf1.losses.absolute_difference losses.add_loss = tf1.losses.add_loss losses.compute_weighted_loss = tf1.losses.compute_weighted_loss losses.get_regularization_loss = tf1.losses.get_regularization_loss losses.huber_loss = tf1.losses.huber_loss losses.mean_squared_error = tf1.losses.mean_squared_error losses.Reduction.MEAN = tf1.losses.Reduction.MEAN losses.Reduction.SUM = tf1.losses.Reduction.SUM losses.sigmoid_cross_entropy = tf1.losses.sigmoid_cross_entropy losses.softmax_cross_entropy = tf1.losses.softmax_cross_entropy losses.sparse_softmax_cross_entropy = (tf1.losses.sparse_softmax_cross_entropy) make_template = tf1.make_template metrics.accuracy = tf1.metrics.accuracy metrics.auc = tf1.metrics.auc metrics.precision = tf1.metrics.precision metrics.recall = tf1.metrics.recall moving_average_variables = tf1.moving_average_variables multinomial = tf1.multinomial name_scope = tf1.name_scope OptimizerOptions = tf1.OptimizerOptions placeholder = tf1.placeholder placeholder_with_default = tf1.placeholder_with_default Print = tf1.Print py_func = tf1.py_func python_io = tf1.python_io report_uninitialized_variables = tf1.report_uninitialized_variables reset_default_graph = tf1.reset_default_graph resource_loader = tf1.resource_loader RunMetadata = tf1.RunMetadata RunOptions = tf1.RunOptions saved_model.build_signature_def = tf1.saved_model.build_signature_def saved_model.Builder = tf1.saved_model.Builder saved_model.load = tf1.saved_model.load saved_model.loader = tf1.saved_model.loader saved_model.signature_constants = tf1.saved_model.signature_constants saved_model.simple_save = tf1.saved_model.simple_save saved_model.tag_constants = tf1.saved_model.tag_constants saved_model.utils = tf1.saved_model.utils Session = tf1.Session sparse_to_dense = tf1.sparse_to_dense string_split = tf1.string_split strings.reduce_join = tf1.reduce_join strings.split = tf1.strings.split Summary = tf1.Summary if tf1.summary is not None: # tf.summary are not supported on TPU so we sometimes set tf.summary to None # to prohibit the direct use of it. # It is safe to skip copying tf.summary members in such cases. summary.audio = tf1.summary.audio summary.FileWriter = tf1.summary.FileWriter summary.histogram = tf1.summary.histogram summary.image = tf1.summary.image summary.merge = tf1.summary.merge summary.merge_all = tf1.summary.merge_all summary.scalar = tf1.summary.scalar summary.Summary = tf1.summary.Summary summary.Summary.FromString = tf1.summary.Summary.FromString tables_initializer = tf1.tables_initializer test.compute_gradient_error = tf1.test.compute_gradient_error test.get_temp_dir = tf1.test.get_temp_dir test.mock = tf1.test.mock tpu = tf1.tpu train.AdadeltaOptimizer = tf1.train.AdadeltaOptimizer train.AdagradOptimizer = tf1.train.AdagradOptimizer train.AdamOptimizer = tf1.train.AdamOptimizer train.export_meta_graph = tf1.train.export_meta_graph train.get_or_create_global_step = tf1.train.get_or_create_global_step train.get_global_step = tf1.train.get_global_step train.GradientDescentOptimizer = tf1.train.GradientDescentOptimizer train.MomentumOptimizer = tf1.train.MomentumOptimizer train.MonitoredTrainingSession = tf1.train.MonitoredTrainingSession train.NewCheckpointReader = tf1.train.NewCheckpointReader train.Optimizer = tf1.train.Optimizer train.RMSPropOptimizer = tf1.train.RMSPropOptimizer train.Saver = tf1.train.Saver train.SaverDef = tf1.train.SaverDef train.summary_iterator = tf1.train.summary_iterator trainable_variables = tf1.trainable_variables Variable = tf1.Variable variables_initializer = tf1.variables_initializer VariableScope = tf1.VariableScope variance_scaling_initializer = tf1.variance_scaling_initializer variable_scope = tf1.variable_scope where = tf1.where while_loop = tf1.while_loop wrap_function = tf1.wrap_function # Explicit 1.x symbol import. data.make_initializable_iterator = dataset_ops.make_initializable_iterator data.make_one_shot_iterator = dataset_ops.make_one_shot_iterator # For `nn.embedding_lookup`, v2 doesn't have the arg 'partition_strategy' in # the API, and uses 'partition_strategy="div"' by default; # while v1 uses 'partition_strategy="mod"' by default. Keep this for now. nn.embedding_lookup = embedding_ops.embedding_lookup # pylint: enable=undefined-variable
#!/usr/bin/env node const yargs = require('yargs'); const { hideBin } = require('yargs/helpers'); const pkg = require('../package.json'); const checkUserInput = require('./process-input'); /** * Gets the user input from the command line and checks the input, printing an error message if the input argument is invalid */ const main = () => { const argv = yargs(hideBin(process.argv)) .help('h') .alias('h', 'help') .version(pkg.name + ' ' + pkg.version) .alias('v', 'version') .option('config', { alias: 'c', describe: 'Path to a JSON config file', type: 'string', }) .options('input', { alias: 'i', describe: 'Path to a file or folder with files', type: 'array', }) .option('lang', { alias: 'l', describe: 'Language used in generated HTML files', type: 'string', }) .option('output', { alias: 'o', describe: 'Path to an output directory', type: 'string', }) .option('stylesheet', { alias: 's', describe: 'Stylesheet URL', type: 'string', }).argv; if (!checkUserInput(argv)) { console.error('Please see --help for options.'); process.exit(1); } }; main();
#ifndef __CONFIG_H__ #define __CONFIG_H__ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <locale.h> #include <time.h> #include <errno.h> /*size and limit settings*/ #define MAX_NAME_SIZE 50+1 #define MAX_OPTION_MENU_SIZE 50 #define TOTAL_OPTION_MAIN_MENU 6 #define MAX_USERNAME_SIZE 25+1 #define MAX_PASSWD_SIZE 5+1 #define MAX_TITLE_SIZE 120+1 #define MAX_ANSWER_SIZE 80+1 #define MAX_SIZE_THEME_NAME 25+1 #define MAX_NICKNAME_SIZE 5+1 #define MAX_TOP_LIST 10 #define MAX_HISTORY_LIST 15 #define TOTAL_THEMES 4 #define MINIMUM_QUESTIONS 10 /*definition of controllers*/ #define SUCCESS 1 #define FAILURE 0 #define TRUE 1 #define FALSE 0 #define EXIT 0 #define NOT_FOUND -1 #define OPEN_RANGE 0 #define CLOSED_RANGE 1 #define TRY_AGAIN 1 /*Adm settings*/ #define RECORD_QUESTION 2 #define ALLOCATED_POWERS 1 #define CONFIRM_DELETE_ACCOUNT 1 /*login settings*/ #define INVALID_PASSWORD 1 #define INVALID_USER 0 #define MINIMUM_ID 2 #define MAXIMUM_LOGIN_ATTEMPTS 3 #define REGISTER_USER 1 /*register settings*/ #define GET_PASSWORD 1 #define PASSWORD_CONFIRMATION 2 /*user type definition*/ #define ADMIN_USER 1 #define PLAYER_USER 2 /*CRUD settings*/ #define BINARY_READING "rb" #define BINARY_WRITING "wb" #define BINARY_APPEND "ab" #define BINARY_READING_PLUS "r+b" #define USER_DATA 1 #define QUESTION_DATA 2 #define LOG_DIRECTORY "logs" #define DATA_DIRECTORY "db" #define LOG_FILE_NAME "logs/logs.txt" #define SETTING_FILE_NAME "db/settings.dat" #define USERS_FILE_NAME "db/users.dat" #define THEMES_FILE_NAME "db/themes.dat" #define QUESTION_PREFIX "db/themeQuestions" #define QUESTION_SUFIX_SIZE 12 #define TOP_LIST_FILE_NAME "db/top.dat" #define HISTORY_FILE_NAME "db/history.dat" /*event and error settings*/ #define STANDARD_EVENT 1 #define CRITICAL_FAILURE 2 #define INCOMPLETE_RECORD 3 #define INCOMPLETE_READING 4 #define REMOVAL_STACK_EMPTY 5 #define GAME_STATUS_UNIDENTIFIED 6 #define DATA_TYPE_UNIDENTIFIED 7 #define EMPTY_QUEUE 8 #define QUEUE_NOT_STARTED 9 #define LIST_NOT_STARTED 10 #define LIST_QUEUE 11 #define FEW_QUESTIONS 12 /*color setting*/ #define RED "\033[1;91m" #define RESET_COLORS "\033[0;0m" /*game logic*/ #define CORRECT_ANSWER 0 #define SMALL_MODE_QUESTIONS 4 #define MEDIUM_MODE_QUESTIONS 8 #define LARGE_MODE_QUESTIONS 16 #define REPEAT 1 #define GAME_STARTED 1 #define GAME_FINISHED 2 #define RESET 0 #define MAX_PLAYERS 6 #define MIN_PLAYERS 2 #define MAX_RESPONSE_OPTIONS 4 /*setting menus*/ /*main menu*/ #define PLAY 1 #define NEW_USER 2 #define TOP_10 3 #define LATEST_PLAYERS 4 #define MY_ACCOUNT 5 /*User menu*/ #define EDIT_ACCOUNT 1 #define DELETE_ACCOUNT 2 #define COME_BACK 0 /*Adm menu*/ #define INSERT_QUESTION 3 #define CREATE_ADMINISTRATOR 4 #define RECOVER_PASSWORD 5 #define BACK_TO_MAIN_MENU 99 /*game mode*/ #define SMALL_MODE 1 #define MEDIUM_MODE 2 #define LARGE_MODE 3 #include "structs.h" /*global variables*/ /*configuration variables*/ SETTINGS settings; char keyboard[BUFSIZ]; NODE ** topPlayers; NODE ** historyPlayers; #endif #include "dependency.h"
# Copyright 2013 Novo Nordisk Foundation Center for Biosustainability, # Technical University of Denmark. # # 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 from setuptools import setup, find_packages from itertools import chain import versioneer versioneer.VCS = 'git' versioneer.versionfile_source = 'optlang/_version.py' versioneer.versionfile_build = 'optlang/_version.py' versioneer.tag_prefix = '' # tags are like 1.2.0 versioneer.parentdir_prefix = 'optlang-' # dirname like 'myproject-1.2.0' # Run # pandoc --from=markdown --to=rst README.md -o README.rst # from time to time, to keep README.rst updated with open('README.rst', 'r') as f: description = f.read() on_rtd = os.environ.get('READTHEDOCS', None) == 'True' if on_rtd: requirements = [] else: # requirements = ['sympy>=1.0.0', 'six>=1.9.0'] with open("requirements.txt") as infile: requirements = infile.read().splitlines() extra_requirements = { 'test': ['nose>=1.3.7', 'rednose>=0.4.3', 'coverage>=4.0.3', 'jsonschema>=2.5'], } extra_requirements['all'] = list(set(chain(*extra_requirements.values()))) setup( name='optlang', version=versioneer.get_version(), cmdclass=versioneer.get_cmdclass(), packages=find_packages(), install_requires=requirements, # from requirements.txt extras_require=extra_requirements, test_suite='nose.collector', author='Nikolaus Sonnenschein', author_email='niko.sonnenschein@gmail.com', description='Formulate optimization problems using sympy expressions and solve them using interfaces to third-party optimization software (e.g. GLPK).', license='Apache License Version 2.0', url='https://github.com/biosustain/optlang', long_description=description, keywords=['optimization', 'sympy', 'mathematical programming', 'heuristic optimization'], classifiers=[ 'Development Status :: 5 - Production/Stable', 'Topic :: Scientific/Engineering :: Mathematics', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'License :: OSI Approved :: Apache Software License', ], )
export default { 'menu.welcome': '歡迎', // 'menu.more-blocks': '更多區塊', 'menu.product.manage': '产品管理', 'menu.product.entry': '产品录入', 'menu.product.inquiry': '产品查询', 'menu.list': '列表', 'menu.list.order': '订单列表', 'menu.list.policy': '保单列表', 'menu.account.center': '個人中心', 'menu.account.settings': '個人設置', 'menu.account.trigger': '觸發報錯', 'menu.account.logout': '退出登錄', };
import mz P = mz.Parameter class SignalWithEnvelope(mz.BaseModule): src: mz.BaseModule env: mz.BaseModule def out(self, clock_signal: mz.ClockSignal): # This defines the length! env = self.env(clock_signal) fake_clock_signal = clock_signal.change_length(env.shape[0]) src = self.src(fake_clock_signal) return env * src class BabiesFirstSynthie(mz.Module): def setup(self): base_frequency = mz.Parameter(220, key='f') lfo = mz.SineSource(frequency=mz.Parameter(0.66, key='l', lo=0.1, hi=60, clip=True)) dancing_triangle = mz.SkewedTriangleSource(frequency=base_frequency, alpha=mz.lift(lfo)) low_hum = mz.SineSource(frequency=mz.Parameter(66, key='b')) self.out = dancing_triangle + low_hum * 0.5 class Test(mz.Module): def setup(self): # self.lfo = mz.SineSource(frequency=(mz.Parameter(3) + 1)/2) # self.src = mz.SineSource(frequency=self.lfo * 440) # self.out = self.src self.sick = mz.SkewedTriangleSource(frequency=P(220), alpha=mz.lift(mz.SineSource(P(1)))) self.out = self.sick # self.out = mz.ButterworthFilter(self.sick, # f_low=P(10, key='k', lo=1, hi=40000, clip=True), # f_high=P(10000, key='l', lo=1, hi=40000, clip=True), # mode="bp")
// Copyright 2018 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #pragma once #include <ddk/mmio-buffer.h> #include <ddk/protocol/pci.h> #include <stdio.h> #include <zircon/syscalls.h> __BEGIN_CDECLS static inline zx_status_t pci_map_bar_buffer(const pci_protocol_t* pci, uint32_t bar_id, uint32_t cache_policy, mmio_buffer_t* buffer) { zx_pci_bar_t bar; zx_status_t st = pci->ops->get_bar(pci->ctx, bar_id, &bar); if (st != ZX_OK) { return st; } // TODO(cja): PIO may be mappable on non-x86 architectures if (bar.type == ZX_PCI_BAR_TYPE_PIO || bar.handle == ZX_HANDLE_INVALID) { return ZX_ERR_WRONG_TYPE; } size_t vmo_size; st = zx_vmo_get_size(bar.handle, &vmo_size); if (st != ZX_OK) { return st; } return mmio_buffer_init(buffer, 0, vmo_size, bar.handle, cache_policy); } __END_CDECLS
import requests import json import re import pandas as pd class Data: """ This module retrieves statistics of cases of the 2019 Novel Coronavirus. Data Source: https://view.inews.qq.com/g2/getOnsInfo?name=disease_h5 ... Attributes ---------- statistics : dict The raw data retrieved from the server. china : pandas.DataFrame Nation-level data of China. province : pandas.DataFrame province-level data of China. city : pandas.DataFrame city-level data of China international : pandas.DataFrame Data of foreign countries. history_china : pandas.DataFrame Not supported after v3.0. Historical data of China history_china_add : pandas.DataFrame Not supported after v3.0. Historical data of added confirmed cases in China history_add : pandas.DataFrame Not supported after v3.0. Historical data of added confirmed cases in Hubei history_dead : pandas.DataFrame Not supported after v3.0. Historical data of dead cases confirm_add_rank : pd.DataFrame Not supported after v3.0. Ranking of provinces in terms of added confirmed case update_time : str Time of the last update. _trans : dict A dict that stores the translation of the keys from the English labels in original Jason data to Chinese """ def __init__(self): self._trans = {'confirm': '确诊', 'suspect': '疑似', 'dead': '病亡', 'heal': '治愈', 'date': '日期', 'isUpdated': '数据已更新', 'hubei': '湖北', 'country': '全国', 'notHubei': '非湖北', 'deadRate': '病亡率', 'healRate': '治愈率', 'hubeiDead': '湖北病亡', 'hubeiConfirm': '湖北确诊', 'countryDead': '全国病亡', 'countryConfirm': '全国确诊', 'hubeiRate': '湖北比率', 'notHubeiRate': '非湖北比率', 'countryRate': '全国比率', 'yesterday': '昨日', 'before': '前日', 'addRate': '增加率', 'name': '名称'} self.statistics = self._request_data() self.china = self._china_data() self.province = self._province_data() self.city = self._city_data() self.international = self._country_data() self.update_time = self._update_time_data() # self.history_china = self._china_history() # self.history_china_add = self._china_add_history() # self.history_add = self._add_history() # self.history_dead = self._dead_rate_history() # self.confirm_add_rank = self._confirm_add_rank() self.news = self._news() def _request_data(self): data_request = requests.get('https://view.inews.qq.com/g2/getOnsInfo?name=disease_h5') data_process = re.sub("^\\d+\\(", "", data_request.text) data_process = re.sub("\\)$", "", data_process) data_process_json = json.loads(data_process) data_json = json.loads(data_process_json['data']) return data_json def _province_data(self): province_dict = {} for province in self.statistics['areaTree'][0]['children']: province_dict[province['name']] = province # Make a list of multi-index province_key_list = [] for province in province_dict.keys(): for dimension in ['新增', '累计']: province_key_list.append((province, dimension)) index = pd.MultiIndex.from_tuples(province_key_list, names=['省/直辖市/自治区', '累计/新增']) # Make a array of data array_list = [] for province in province_dict.keys(): for dimension in ['today', 'total']: array_list.append(pd.Series(data=province_dict[province][dimension])) # Put data in a DataFrame df = pd.DataFrame(data=array_list, index=index) df.rename(columns=self._trans, inplace=True) return df def _city_data(self): province_dict = {} for province in self.statistics['areaTree'][0]['children']: province_dict[province['name']] = province # Make a list of multi-index county_key_list = [] for province in province_dict.keys(): for county in province_dict[province]['children']: for dimension in ['新增', '累计']: county_key_list.append((province, county['name'], dimension)) index = pd.MultiIndex.from_tuples(county_key_list, names=['省/直辖市/自治区', '行政区', '累计/新增']) # Make a array of data array_list = [] for province in province_dict.keys(): for county in province_dict[province]['children']: for dimension in ['today', 'total']: array_list.append(pd.Series(data=county[dimension])) # Put data in a DataFrame df = pd.DataFrame(data=array_list, index=index) df.rename(columns=self._trans, inplace=True) return df def _country_data(self): country_dict = {} for country in self.statistics['areaTree'][1:]: country_dict[country['name']] = country country_key_list = [] for country in country_dict.keys(): for dimension in ['新增', '累计']: country_key_list.append((country, dimension)) index = pd.MultiIndex.from_tuples(country_key_list, names=['国家', '累计/新增']) array_list = [] for country in country_dict.keys(): for dimension in ['today', 'total']: array_list.append(pd.Series(data=country_dict[country][dimension])) df = pd.DataFrame(data=array_list, index=index) df.rename(columns=self._trans, inplace=True) return df def _china_data(self): china_total = pd.Series(self.statistics['chinaTotal']) china_add = pd.Series(self.statistics['chinaAdd']) df = pd.DataFrame([china_total, china_add], index=['累计', '新增']) df.rename(columns=self._trans, inplace=True) return df def _china_history(self): df = pd.DataFrame(self.statistics['chinaDayList'])[['date', 'confirm', 'suspect', 'dead', 'heal', 'deadRate', 'healRate']] df.rename(columns=self._trans, inplace=True) df.set_index('日期', inplace=True) return df def _china_add_history(self): df = pd.DataFrame(self.statistics['chinaDayAddList'])[['date', 'confirm', 'suspect', 'dead', 'heal', 'deadRate', 'healRate']] df.rename(columns=self._trans, inplace=True) df.set_index('日期', inplace=True) return df def _add_history(self): df = pd.DataFrame(self.statistics['dailyNewAddHistory']) df.rename(columns=self._trans, inplace=True) df.set_index('日期', inplace=True) return df def _dead_rate_history(self): df = pd.DataFrame(self.statistics['dailyDeadRateHistory']) df.rename(columns=self._trans, inplace=True) df.set_index('日期', inplace=True) return df def _confirm_add_rank(self): df = pd.DataFrame(self.statistics['confirmAddRank']) df.rename(columns=self._trans, inplace=True) df.index = df.index + 1 return df def _news(self): return pd.DataFrame(self.statistics['articleList']) def _update_time_data(self): return self.statistics['lastUpdateTime']
define("ace/ext/spellcheck", ["require", "exports", "module", "ace/lib/event", "ace/editor", "ace/config"], function (e, t, n) { "use strict"; var r = e("../lib/event"); t.contextMenuHandler = function (e) { var t = e.target, n = t.textInput.getElement(); if (!t.selection.isEmpty()) return; var i = t.getCursorPosition(), s = t.session.getWordRange(i.row, i.column), o = t.session.getTextRange(s); t.session.tokenRe.lastIndex = 0; if (!t.session.tokenRe.test(o)) return; var u = "\x01\x01", a = o + " " + u; n.value = a, n.setSelectionRange(o.length, o.length + 1), n.setSelectionRange(0, 0), n.setSelectionRange(0, o.length); var f = !1; r.addListener(n, "keydown", function l() { r.removeListener(n, "keydown", l), f = !0 }), t.textInput.setInputHandler(function (e) { console.log(e, a, n.selectionStart, n.selectionEnd); if (e == a) return ""; if (e.lastIndexOf(a, 0) === 0) return e.slice(a.length); if (e.substr(n.selectionEnd) == a) return e.slice(0, -a.length); if (e.slice(-2) == u) { var r = e.slice(0, -2); if (r.slice(-1) == " ") return f ? r.substring(0, n.selectionEnd) : (r = r.slice(0, -1), t.session.replace(s, r), "") } return e }) }; var i = e("../editor").Editor; e("../config").defineOptions(i.prototype, "editor", { spellcheck: { set: function (e) { var n = this.textInput.getElement(); n.spellcheck = !!e, e ? this.on("nativecontextmenu", t.contextMenuHandler) : this.removeListener("nativecontextmenu", t.contextMenuHandler) }, value: !0 } }) }); (function () { window.require(["ace/ext/spellcheck"], function (m) { if (typeof module == "object" && typeof exports == "object" && module) { module.exports = m; } }); })();
const path = require('path'); const globalJestConfig = require('../../../jest.config'); const finalJestConfig = globalJestConfig; finalJestConfig.rootDir = path.join(__dirname, '../../..'); finalJestConfig.testMatch = [ '<rootDir>/examples/official-storybook/image-snapshots/storyshots-image.runner.js', ]; module.exports = finalJestConfig;
# Copyright 2016 F5 Networks Inc. # # 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. # # Requires Python 2.6+ and Openssl 1.0+ # import os import socket import time import unittest import azurelinuxagent.common.logger as logger import azurelinuxagent.common.osutil.bigip as osutil import azurelinuxagent.common.osutil.default as default import azurelinuxagent.common.utils.shellutil as shellutil from azurelinuxagent.common.exception import OSUtilError from azurelinuxagent.common.osutil.bigip import BigIpOSUtil from tests.tools import AgentTestCase, patch from .test_default import osutil_get_dhcp_pid_should_return_a_list_of_pids class TestBigIpOSUtil_wait_until_mcpd_is_initialized(AgentTestCase): # pylint: disable=invalid-name @patch.object(shellutil, "run", return_value=0) @patch.object(logger, "info", return_value=None) def test_success(self, *args): result = osutil.BigIpOSUtil._wait_until_mcpd_is_initialized( # pylint: disable=protected-access osutil.BigIpOSUtil() ) self.assertEqual(result, True) # There are two logger calls in the mcpd wait function. The second # occurs after mcpd is found to be "up" self.assertEqual(args[0].call_count, 2) @patch.object(shellutil, "run", return_value=1) @patch.object(logger, "info", return_value=None) @patch.object(time, "sleep", return_value=None) def test_failure(self, *args): # pylint: disable=unused-argument self.assertRaises( OSUtilError, osutil.BigIpOSUtil._wait_until_mcpd_is_initialized, # pylint: disable=protected-access osutil.BigIpOSUtil() ) class TestBigIpOSUtil_save_sys_config(AgentTestCase): # pylint: disable=invalid-name @patch.object(shellutil, "run", return_value=0) @patch.object(logger, "error", return_value=None) def test_success(self, *args): result = osutil.BigIpOSUtil._save_sys_config(osutil.BigIpOSUtil()) # pylint: disable=protected-access self.assertEqual(result, 0) self.assertEqual(args[0].call_count, 0) @patch.object(shellutil, "run", return_value=1) @patch.object(logger, "error", return_value=None) def test_failure(self, *args): result = osutil.BigIpOSUtil._save_sys_config(osutil.BigIpOSUtil()) # pylint: disable=protected-access self.assertEqual(result, 1) self.assertEqual(args[0].call_count, 1) class TestBigIpOSUtil_useradd(AgentTestCase): # pylint: disable=invalid-name @patch.object(osutil.BigIpOSUtil, 'get_userentry', return_value=None) @patch.object(shellutil, "run_command") def test_success(self, *args): args[0].return_value = (0, None) result = osutil.BigIpOSUtil.useradd( osutil.BigIpOSUtil(), 'foo', expiration=None ) self.assertEqual(result, 0) @patch.object(osutil.BigIpOSUtil, 'get_userentry', return_value=None) def test_user_already_exists(self, *args): args[0].return_value = 'admin' result = osutil.BigIpOSUtil.useradd( osutil.BigIpOSUtil(), 'admin', expiration=None ) self.assertEqual(result, None) @patch.object(shellutil, "run", return_value=1) def test_failure(self, *args): # pylint: disable=unused-argument self.assertRaises( OSUtilError, osutil.BigIpOSUtil.useradd, osutil.BigIpOSUtil(), 'foo', expiration=None ) class TestBigIpOSUtil_chpasswd(AgentTestCase): # pylint: disable=invalid-name @patch.object(shellutil, "run_command") @patch.object(osutil.BigIpOSUtil, 'get_userentry', return_value=True) @patch.object(osutil.BigIpOSUtil, 'is_sys_user', return_value=False) @patch.object(osutil.BigIpOSUtil, '_save_sys_config', return_value=None) def test_success(self, *args): result = osutil.BigIpOSUtil.chpasswd( osutil.BigIpOSUtil(), 'admin', 'password', crypt_id=6, salt_len=10 ) self.assertEqual(result, 0) self.assertEqual(args[0].call_count, 1) self.assertEqual(args[0].call_count, 1) @patch.object(osutil.BigIpOSUtil, 'is_sys_user', return_value=True) def test_is_sys_user(self, *args): # pylint: disable=unused-argument self.assertRaises( OSUtilError, osutil.BigIpOSUtil.chpasswd, osutil.BigIpOSUtil(), 'admin', 'password', crypt_id=6, salt_len=10 ) @patch.object(shellutil, "run_get_output", return_value=(1, None)) @patch.object(osutil.BigIpOSUtil, 'is_sys_user', return_value=False) def test_failed_to_set_user_password(self, *args): # pylint: disable=unused-argument self.assertRaises( OSUtilError, osutil.BigIpOSUtil.chpasswd, osutil.BigIpOSUtil(), 'admin', 'password', crypt_id=6, salt_len=10 ) @patch.object(shellutil, "run_get_output", return_value=(0, None)) @patch.object(osutil.BigIpOSUtil, 'is_sys_user', return_value=False) @patch.object(osutil.BigIpOSUtil, 'get_userentry', return_value=None) def test_failed_to_get_user_entry(self, *args): # pylint: disable=unused-argument self.assertRaises( OSUtilError, osutil.BigIpOSUtil.chpasswd, osutil.BigIpOSUtil(), 'admin', 'password', crypt_id=6, salt_len=10 ) class TestBigIpOSUtil_get_dvd_device(AgentTestCase): # pylint: disable=invalid-name @patch.object(os, "listdir", return_value=['tty1','cdrom0']) def test_success(self, *args): # pylint: disable=unused-argument result = osutil.BigIpOSUtil.get_dvd_device( osutil.BigIpOSUtil(), '/dev' ) self.assertEqual(result, '/dev/cdrom0') @patch.object(os, "listdir", return_value=['foo', 'bar']) def test_failure(self, *args): # pylint: disable=unused-argument self.assertRaises( OSUtilError, osutil.BigIpOSUtil.get_dvd_device, osutil.BigIpOSUtil(), '/dev' ) class TestBigIpOSUtil_restart_ssh_service(AgentTestCase): # pylint: disable=invalid-name @patch.object(shellutil, "run", return_value=0) def test_success(self, *args): # pylint: disable=unused-argument result = osutil.BigIpOSUtil.restart_ssh_service( osutil.BigIpOSUtil() ) self.assertEqual(result, 0) class TestBigIpOSUtil_stop_agent_service(AgentTestCase): # pylint: disable=invalid-name @patch.object(shellutil, "run", return_value=0) def test_success(self, *args): # pylint: disable=unused-argument result = osutil.BigIpOSUtil.stop_agent_service( osutil.BigIpOSUtil() ) self.assertEqual(result, 0) class TestBigIpOSUtil_start_agent_service(AgentTestCase): # pylint: disable=invalid-name @patch.object(shellutil, "run", return_value=0) def test_success(self, *args): # pylint: disable=unused-argument result = osutil.BigIpOSUtil.start_agent_service( osutil.BigIpOSUtil() ) self.assertEqual(result, 0) class TestBigIpOSUtil_register_agent_service(AgentTestCase): # pylint: disable=invalid-name @patch.object(shellutil, "run", return_value=0) def test_success(self, *args): # pylint: disable=unused-argument result = osutil.BigIpOSUtil.register_agent_service( osutil.BigIpOSUtil() ) self.assertEqual(result, 0) class TestBigIpOSUtil_unregister_agent_service(AgentTestCase): # pylint: disable=invalid-name @patch.object(shellutil, "run", return_value=0) def test_success(self, *args): # pylint: disable=unused-argument result = osutil.BigIpOSUtil.unregister_agent_service( osutil.BigIpOSUtil() ) self.assertEqual(result, 0) class TestBigIpOSUtil_set_hostname(AgentTestCase): # pylint: disable=invalid-name @patch.object(os.path, "exists", return_value=False) def test_success(self, *args): result = osutil.BigIpOSUtil.set_hostname( # pylint: disable=assignment-from-none osutil.BigIpOSUtil(), None ) self.assertEqual(args[0].call_count, 0) self.assertEqual(result, None) class TestBigIpOSUtil_set_dhcp_hostname(AgentTestCase): # pylint: disable=invalid-name @patch.object(os.path, "exists", return_value=False) def test_success(self, *args): result = osutil.BigIpOSUtil.set_dhcp_hostname( # pylint: disable=assignment-from-none osutil.BigIpOSUtil(), None ) self.assertEqual(args[0].call_count, 0) self.assertEqual(result, None) class TestBigIpOSUtil_get_first_if(AgentTestCase): # pylint: disable=invalid-name @patch.object(osutil.BigIpOSUtil, '_format_single_interface_name', return_value=b'eth0') def test_success(self, *args): # pylint: disable=unused-argument ifname, ipaddr = osutil.BigIpOSUtil().get_first_if() self.assertTrue(ifname.startswith('eth')) self.assertTrue(ipaddr is not None) try: socket.inet_aton(ipaddr) except socket.error: self.fail("not a valid ip address") @patch.object(osutil.BigIpOSUtil, '_format_single_interface_name', return_value=b'loenp0s3') def test_success(self, *args): # pylint: disable=unused-argument,function-redefined ifname, ipaddr = osutil.BigIpOSUtil().get_first_if() self.assertFalse(ifname.startswith('eth')) self.assertTrue(ipaddr is not None) try: socket.inet_aton(ipaddr) except socket.error: self.fail("not a valid ip address") class TestBigIpOSUtil_mount_dvd(AgentTestCase): # pylint: disable=invalid-name @patch.object(shellutil, "run", return_value=0) @patch.object(time, "sleep", return_value=None) @patch.object(osutil.BigIpOSUtil, '_wait_until_mcpd_is_initialized', return_value=None) @patch.object(default.DefaultOSUtil, 'mount_dvd', return_value=None) def test_success(self, *args): osutil.BigIpOSUtil.mount_dvd( osutil.BigIpOSUtil(), max_retry=6, chk_err=True ) self.assertEqual(args[0].call_count, 1) self.assertEqual(args[1].call_count, 1) class TestBigIpOSUtil_route_add(AgentTestCase): # pylint: disable=invalid-name @patch.object(shellutil, "run", return_value=0) def test_success(self, *args): osutil.BigIpOSUtil.route_add( osutil.BigIpOSUtil(), '10.10.10.0', '255.255.255.0', '10.10.10.1' ) self.assertEqual(args[0].call_count, 1) class TestBigIpOSUtil_device_for_ide_port(AgentTestCase): # pylint: disable=invalid-name @patch.object(time, "sleep", return_value=None) @patch.object(os.path, "exists", return_value=False) @patch.object(default.DefaultOSUtil, 'device_for_ide_port', return_value=None) def test_success_waiting(self, *args): osutil.BigIpOSUtil.device_for_ide_port( osutil.BigIpOSUtil(), '5' ) self.assertEqual(args[0].call_count, 1) self.assertEqual(args[1].call_count, 99) self.assertEqual(args[2].call_count, 99) @patch.object(time, "sleep", return_value=None) @patch.object(os.path, "exists", return_value=True) @patch.object(default.DefaultOSUtil, 'device_for_ide_port', return_value=None) def test_success_immediate(self, *args): osutil.BigIpOSUtil.device_for_ide_port( osutil.BigIpOSUtil(), '5' ) self.assertEqual(args[0].call_count, 1) self.assertEqual(args[1].call_count, 1) self.assertEqual(args[2].call_count, 0) class TestBigIpOSUtil(AgentTestCase): def setUp(self): AgentTestCase.setUp(self) def tearDown(self): AgentTestCase.tearDown(self) def test_get_dhcp_pid_should_return_a_list_of_pids(self): osutil_get_dhcp_pid_should_return_a_list_of_pids(self, BigIpOSUtil()) if __name__ == '__main__': unittest.main()
// words-model.js - A mongoose model // // See http://mongoosejs.com/docs/models.html // for more of what you can do here. module.exports = function (app) { const mongooseClient = app.get('mongooseClient'); const { Schema } = mongooseClient; const words = new Schema({ userId: { type: Schema.Types.ObjectId, required: true }, text: { type: String, required: true }, translation: { type: String } }, { timestamps: true }); return mongooseClient.model('words', words); };
import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import App from './components/App'; //redux import store from './redux/store'; import './styles.css'; ReactDOM.render( <Provider store={store}> <App /> </Provider>, document.getElementById('root'), );
/** * vue-touch-keyboard v0.3.0 * https://github.com/icebob/vue-touch-keyboard * Released under the MIT License. */ !function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.VueTouchKeyboard=e():t.VueTouchKeyboard=e()}(this,function(){return function(t){function e(r){if(n[r])return n[r].exports;var o=n[r]={exports:{},id:r,loaded:!1};return t[r].call(o.exports,o,o.exports,e),o.loaded=!0,o.exports}var n={};return e.m=t,e.c=n,e.p="",e(0)}([function(t,e,n){"use strict";var r=n(1);t.exports={component:r,layouts:n(72),install:function(t){t.component("VueTouchKeyboard",r)}}},function(t,e,n){n(2);var r=n(3)(n(4),n(83),null,null);t.exports=r.exports},function(t,e){},function(t,e){t.exports=function(t,e,n,r){var o,i=t=t||{},u=typeof t["default"];"object"!==u&&"function"!==u||(o=t,i=t["default"]);var c="function"==typeof i?i.options:i;if(e&&(c.render=e.render,c.staticRenderFns=e.staticRenderFns),n&&(c._scopeId=n),r){var s=Object.create(c.computed||null);Object.keys(r).forEach(function(t){var e=r[t];s[t]=function(){return e}}),c.computed=s}return{esModule:o,exports:i,options:c}}},function(t,e,n){"use strict";function r(t){return t&&t.__esModule?t:{"default":t}}Object.defineProperty(e,"__esModule",{value:!0});var o=n(5),i=r(o),u=n(72),c=r(u),s=n(73),a=r(s),f=n(82),l=r(f);e["default"]={props:{input:[HTMLInputElement,HTMLTextAreaElement],layout:[String,Object],defaultKeySet:{type:String,"default":"default"},accept:Function,cancel:Function,change:Function,next:Function,options:{type:Object,"default":function(){return{}}}},data:function(){return{currentKeySet:this.defaultKeySet,inputScrollLeft:0}},computed:{keySet:function p(){var t=this.getLayout();if(t){var p=t[this.currentKeySet];if(p){var e=[],n=t._meta||{};return p.forEach(function(t){var r=[];t.split(" ").forEach(function(t){if((0,l["default"])(t))r.push(t);else if((0,a["default"])(t))if(t.length>2&&"{"==t[0]&&"}"==t[t.length-1]){var e=t.substring(1,t.length-1);n[e]?r.push(n[e]):console.warn("Missing named key from meta: "+e)}else""==t?r.push({placeholder:!0}):r.push({key:t,text:t})}),e.push(r)}),e}}}},watch:{layout:function(){console.log("Layout changed"),this.currentKeySet="default"}},methods:{getLayout:function(){return(0,a["default"])(this.layout)?c["default"][this.layout]:this.layout},changeKeySet:function(t){var e=this.getLayout();null!=e[t]&&(this.currentKeySet=t)},toggleKeySet:function(t){this.currentKeySet=this.currentKeySet==t?"default":t},getCaptionOfKey:function(t){return t.text||t.key||""},getClassesOfKey:function(t){if(t.placeholder)return"placeholder";var e="key "+(t.func||"")+" "+(t.classes||"");return t.keySet&&this.currentKeySet==t.keySet&&(e+=" activated"),e},getKeyStyle:function(t){if(t.width)return{flex:t.width}},supportsSelection:function(){return/text|password|search|tel|url/.test(this.input.type)},getCaret:function(){if(this.supportsSelection()){var t={start:this.input.selectionStart||0,end:this.input.selectionEnd||0};return t.end<t.start&&(t.end=t.start),t}var e=this.input.value;return{start:e.length,end:e.length}},backspace:function(t,e){return e=e.substring(0,t.start-1)+e.substring(t.start),t.start-=1,t.end=t.start,e},insertChar:function(t,e,n){return e=e.substr(0,t.start)+n.toString()+e.substr(t.start),t.start+=n.length,t.end=t.start,e},mousedown:function(t){this.input&&(this.options.preventClickEvent&&t.preventDefault(),this.inputScrollLeft=this.input.scrollLeft)},clickKey:function(t,e){if(this.input){this.options.preventClickEvent&&t.preventDefault();var n=this.getCaret(),r=this.input.value,o=null;if("object"==("undefined"==typeof e?"undefined":(0,i["default"])(e)))if(e.keySet)this.toggleKeySet(e.keySet);else if(e.func)switch(e.func){case"backspace":r=this.backspace(n,r);break;case"accept":return void(this.accept&&this.accept(r));case"cancel":return void(this.cancel&&this.cancel());case"next":return void(this.next&&this.next())}else o=e.key;else o=e;if(o){if(this.input.maxLength<=0||r.length<this.input.maxLength)if(this.options.useKbEvents){var u=document.createEvent("Event");u.initEvent("keydown",!0,!0),u.which=u.keyCode=o.charCodeAt(),this.input.dispatchEvent(u)&&(r=this.insertChar(n,r,o))}else r=this.insertChar(n,r,o);"shifted"==this.currentKeySet&&this.changeKeySet("default")}this.input.value=r,this.setFocusToInput(n),this.change&&this.change(r,o),this.input.maxLength>0&&r.length>=this.input.maxLength&&this.next&&this.next(),this.input.dispatchEvent(new Event("input",{bubbles:!0}))}},setFocusToInput:function(t){this.input.focus(),t&&this.supportsSelection()&&(this.input.selectionStart=t.start,this.input.selectionEnd=t.end)}},mounted:function(){this.input&&this.setFocusToInput()}}},function(t,e,n){"use strict";function r(t){return t&&t.__esModule?t:{"default":t}}e.__esModule=!0;var o=n(6),i=r(o),u=n(57),c=r(u),s="function"==typeof c["default"]&&"symbol"==typeof i["default"]?function(t){return typeof t}:function(t){return t&&"function"==typeof c["default"]&&t.constructor===c["default"]&&t!==c["default"].prototype?"symbol":typeof t};e["default"]="function"==typeof c["default"]&&"symbol"===s(i["default"])?function(t){return"undefined"==typeof t?"undefined":s(t)}:function(t){return t&&"function"==typeof c["default"]&&t.constructor===c["default"]&&t!==c["default"].prototype?"symbol":"undefined"==typeof t?"undefined":s(t)}},function(t,e,n){t.exports={"default":n(7),__esModule:!0}},function(t,e,n){n(8),n(52),t.exports=n(56).f("iterator")},function(t,e,n){"use strict";var r=n(9)(!0);n(12)(String,"String",function(t){this._t=String(t),this._i=0},function(){var t,e=this._t,n=this._i;return n>=e.length?{value:void 0,done:!0}:(t=r(e,n),this._i+=t.length,{value:t,done:!1})})},function(t,e,n){var r=n(10),o=n(11);t.exports=function(t){return function(e,n){var i,u,c=String(o(e)),s=r(n),a=c.length;return s<0||s>=a?t?"":void 0:(i=c.charCodeAt(s),i<55296||i>56319||s+1===a||(u=c.charCodeAt(s+1))<56320||u>57343?t?c.charAt(s):i:t?c.slice(s,s+2):(i-55296<<10)+(u-56320)+65536)}}},function(t,e){var n=Math.ceil,r=Math.floor;t.exports=function(t){return isNaN(t=+t)?0:(t>0?r:n)(t)}},function(t,e){t.exports=function(t){if(void 0==t)throw TypeError("Can't call method on "+t);return t}},function(t,e,n){"use strict";var r=n(13),o=n(14),i=n(29),u=n(19),c=n(30),s=n(31),a=n(32),f=n(48),l=n(50),p=n(49)("iterator"),h=!([].keys&&"next"in[].keys()),y="@@iterator",d="keys",v="values",b=function(){return this};t.exports=function(t,e,n,x,g,S,m){a(n,e,x);var O,k,w,j=function(t){if(!h&&t in T)return T[t];switch(t){case d:return function(){return new n(this,t)};case v:return function(){return new n(this,t)}}return function(){return new n(this,t)}},_=e+" Iterator",E=g==v,L=!1,T=t.prototype,C=T[p]||T[y]||g&&T[g],P=!h&&C||j(g),M=g?E?j("entries"):P:void 0,K="Array"==e?T.entries||C:C;if(K&&(w=l(K.call(new t)),w!==Object.prototype&&w.next&&(f(w,_,!0),r||c(w,p)||u(w,p,b))),E&&C&&C.name!==v&&(L=!0,P=function(){return C.call(this)}),r&&!m||!h&&!L&&T[p]||u(T,p,P),s[e]=P,s[_]=b,g)if(O={values:E?P:j(v),keys:S?P:j(d),entries:M},m)for(k in O)k in T||i(T,k,O[k]);else o(o.P+o.F*(h||L),e,O);return O}},function(t,e){t.exports=!0},function(t,e,n){var r=n(15),o=n(16),i=n(17),u=n(19),c="prototype",s=function(t,e,n){var a,f,l,p=t&s.F,h=t&s.G,y=t&s.S,d=t&s.P,v=t&s.B,b=t&s.W,x=h?o:o[e]||(o[e]={}),g=x[c],S=h?r:y?r[e]:(r[e]||{})[c];h&&(n=e);for(a in n)f=!p&&S&&void 0!==S[a],f&&a in x||(l=f?S[a]:n[a],x[a]=h&&"function"!=typeof S[a]?n[a]:v&&f?i(l,r):b&&S[a]==l?function(t){var e=function(e,n,r){if(this instanceof t){switch(arguments.length){case 0:return new t;case 1:return new t(e);case 2:return new t(e,n)}return new t(e,n,r)}return t.apply(this,arguments)};return e[c]=t[c],e}(l):d&&"function"==typeof l?i(Function.call,l):l,d&&((x.virtual||(x.virtual={}))[a]=l,t&s.R&&g&&!g[a]&&u(g,a,l)))};s.F=1,s.G=2,s.S=4,s.P=8,s.B=16,s.W=32,s.U=64,s.R=128,t.exports=s},function(t,e){var n=t.exports="undefined"!=typeof window&&window.Math==Math?window:"undefined"!=typeof self&&self.Math==Math?self:Function("return this")();"number"==typeof __g&&(__g=n)},function(t,e){var n=t.exports={version:"2.5.3"};"number"==typeof __e&&(__e=n)},function(t,e,n){var r=n(18);t.exports=function(t,e,n){if(r(t),void 0===e)return t;switch(n){case 1:return function(n){return t.call(e,n)};case 2:return function(n,r){return t.call(e,n,r)};case 3:return function(n,r,o){return t.call(e,n,r,o)}}return function(){return t.apply(e,arguments)}}},function(t,e){t.exports=function(t){if("function"!=typeof t)throw TypeError(t+" is not a function!");return t}},function(t,e,n){var r=n(20),o=n(28);t.exports=n(24)?function(t,e,n){return r.f(t,e,o(1,n))}:function(t,e,n){return t[e]=n,t}},function(t,e,n){var r=n(21),o=n(23),i=n(27),u=Object.defineProperty;e.f=n(24)?Object.defineProperty:function(t,e,n){if(r(t),e=i(e,!0),r(n),o)try{return u(t,e,n)}catch(c){}if("get"in n||"set"in n)throw TypeError("Accessors not supported!");return"value"in n&&(t[e]=n.value),t}},function(t,e,n){var r=n(22);t.exports=function(t){if(!r(t))throw TypeError(t+" is not an object!");return t}},function(t,e){t.exports=function(t){return"object"==typeof t?null!==t:"function"==typeof t}},function(t,e,n){t.exports=!n(24)&&!n(25)(function(){return 7!=Object.defineProperty(n(26)("div"),"a",{get:function(){return 7}}).a})},function(t,e,n){t.exports=!n(25)(function(){return 7!=Object.defineProperty({},"a",{get:function(){return 7}}).a})},function(t,e){t.exports=function(t){try{return!!t()}catch(e){return!0}}},function(t,e,n){var r=n(22),o=n(15).document,i=r(o)&&r(o.createElement);t.exports=function(t){return i?o.createElement(t):{}}},function(t,e,n){var r=n(22);t.exports=function(t,e){if(!r(t))return t;var n,o;if(e&&"function"==typeof(n=t.toString)&&!r(o=n.call(t)))return o;if("function"==typeof(n=t.valueOf)&&!r(o=n.call(t)))return o;if(!e&&"function"==typeof(n=t.toString)&&!r(o=n.call(t)))return o;throw TypeError("Can't convert object to primitive value")}},function(t,e){t.exports=function(t,e){return{enumerable:!(1&t),configurable:!(2&t),writable:!(4&t),value:e}}},function(t,e,n){t.exports=n(19)},function(t,e){var n={}.hasOwnProperty;t.exports=function(t,e){return n.call(t,e)}},function(t,e){t.exports={}},function(t,e,n){"use strict";var r=n(33),o=n(28),i=n(48),u={};n(19)(u,n(49)("iterator"),function(){return this}),t.exports=function(t,e,n){t.prototype=r(u,{next:o(1,n)}),i(t,e+" Iterator")}},function(t,e,n){var r=n(21),o=n(34),i=n(46),u=n(43)("IE_PROTO"),c=function(){},s="prototype",a=function(){var t,e=n(26)("iframe"),r=i.length,o="<",u=">";for(e.style.display="none",n(47).appendChild(e),e.src="javascript:",t=e.contentWindow.document,t.open(),t.write(o+"script"+u+"document.F=Object"+o+"/script"+u),t.close(),a=t.F;r--;)delete a[s][i[r]];return a()};t.exports=Object.create||function(t,e){var n;return null!==t?(c[s]=r(t),n=new c,c[s]=null,n[u]=t):n=a(),void 0===e?n:o(n,e)}},function(t,e,n){var r=n(20),o=n(21),i=n(35);t.exports=n(24)?Object.defineProperties:function(t,e){o(t);for(var n,u=i(e),c=u.length,s=0;c>s;)r.f(t,n=u[s++],e[n]);return t}},function(t,e,n){var r=n(36),o=n(46);t.exports=Object.keys||function(t){return r(t,o)}},function(t,e,n){var r=n(30),o=n(37),i=n(40)(!1),u=n(43)("IE_PROTO");t.exports=function(t,e){var n,c=o(t),s=0,a=[];for(n in c)n!=u&&r(c,n)&&a.push(n);for(;e.length>s;)r(c,n=e[s++])&&(~i(a,n)||a.push(n));return a}},function(t,e,n){var r=n(38),o=n(11);t.exports=function(t){return r(o(t))}},function(t,e,n){var r=n(39);t.exports=Object("z").propertyIsEnumerable(0)?Object:function(t){return"String"==r(t)?t.split(""):Object(t)}},function(t,e){var n={}.toString;t.exports=function(t){return n.call(t).slice(8,-1)}},function(t,e,n){var r=n(37),o=n(41),i=n(42);t.exports=function(t){return function(e,n,u){var c,s=r(e),a=o(s.length),f=i(u,a);if(t&&n!=n){for(;a>f;)if(c=s[f++],c!=c)return!0}else for(;a>f;f++)if((t||f in s)&&s[f]===n)return t||f||0;return!t&&-1}}},function(t,e,n){var r=n(10),o=Math.min;t.exports=function(t){return t>0?o(r(t),9007199254740991):0}},function(t,e,n){var r=n(10),o=Math.max,i=Math.min;t.exports=function(t,e){return t=r(t),t<0?o(t+e,0):i(t,e)}},function(t,e,n){var r=n(44)("keys"),o=n(45);t.exports=function(t){return r[t]||(r[t]=o(t))}},function(t,e,n){var r=n(15),o="__core-js_shared__",i=r[o]||(r[o]={});t.exports=function(t){return i[t]||(i[t]={})}},function(t,e){var n=0,r=Math.random();t.exports=function(t){return"Symbol(".concat(void 0===t?"":t,")_",(++n+r).toString(36))}},function(t,e){t.exports="constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf".split(",")},function(t,e,n){var r=n(15).document;t.exports=r&&r.documentElement},function(t,e,n){var r=n(20).f,o=n(30),i=n(49)("toStringTag");t.exports=function(t,e,n){t&&!o(t=n?t:t.prototype,i)&&r(t,i,{configurable:!0,value:e})}},function(t,e,n){var r=n(44)("wks"),o=n(45),i=n(15).Symbol,u="function"==typeof i,c=t.exports=function(t){return r[t]||(r[t]=u&&i[t]||(u?i:o)("Symbol."+t))};c.store=r},function(t,e,n){var r=n(30),o=n(51),i=n(43)("IE_PROTO"),u=Object.prototype;t.exports=Object.getPrototypeOf||function(t){return t=o(t),r(t,i)?t[i]:"function"==typeof t.constructor&&t instanceof t.constructor?t.constructor.prototype:t instanceof Object?u:null}},function(t,e,n){var r=n(11);t.exports=function(t){return Object(r(t))}},function(t,e,n){n(53);for(var r=n(15),o=n(19),i=n(31),u=n(49)("toStringTag"),c="CSSRuleList,CSSStyleDeclaration,CSSValueList,ClientRectList,DOMRectList,DOMStringList,DOMTokenList,DataTransferItemList,FileList,HTMLAllCollection,HTMLCollection,HTMLFormElement,HTMLSelectElement,MediaList,MimeTypeArray,NamedNodeMap,NodeList,PaintRequestList,Plugin,PluginArray,SVGLengthList,SVGNumberList,SVGPathSegList,SVGPointList,SVGStringList,SVGTransformList,SourceBufferList,StyleSheetList,TextTrackCueList,TextTrackList,TouchList".split(","),s=0;s<c.length;s++){var a=c[s],f=r[a],l=f&&f.prototype;l&&!l[u]&&o(l,u,a),i[a]=i.Array}},function(t,e,n){"use strict";var r=n(54),o=n(55),i=n(31),u=n(37);t.exports=n(12)(Array,"Array",function(t,e){this._t=u(t),this._i=0,this._k=e},function(){var t=this._t,e=this._k,n=this._i++;return!t||n>=t.length?(this._t=void 0,o(1)):"keys"==e?o(0,n):"values"==e?o(0,t[n]):o(0,[n,t[n]])},"values"),i.Arguments=i.Array,r("keys"),r("values"),r("entries")},function(t,e){t.exports=function(){}},function(t,e){t.exports=function(t,e){return{value:e,done:!!t}}},function(t,e,n){e.f=n(49)},function(t,e,n){t.exports={"default":n(58),__esModule:!0}},function(t,e,n){n(59),n(69),n(70),n(71),t.exports=n(16).Symbol},function(t,e,n){"use strict";var r=n(15),o=n(30),i=n(24),u=n(14),c=n(29),s=n(60).KEY,a=n(25),f=n(44),l=n(48),p=n(45),h=n(49),y=n(56),d=n(61),v=n(62),b=n(65),x=n(21),g=n(22),S=n(37),m=n(27),O=n(28),k=n(33),w=n(66),j=n(68),_=n(20),E=n(35),L=j.f,T=_.f,C=w.f,P=r.Symbol,M=r.JSON,K=M&&M.stringify,F="prototype",A=h("_hidden"),N=h("toPrimitive"),I={}.propertyIsEnumerable,R=f("symbol-registry"),D=f("symbols"),V=f("op-symbols"),G=Object[F],H="function"==typeof P,W=r.QObject,z=!W||!W[F]||!W[F].findChild,B=i&&a(function(){return 7!=k(T({},"a",{get:function(){return T(this,"a",{value:7}).a}})).a})?function(t,e,n){var r=L(G,e);r&&delete G[e],T(t,e,n),r&&t!==G&&T(G,e,r)}:T,J=function(t){var e=D[t]=k(P[F]);return e._k=t,e},U=H&&"symbol"==typeof P.iterator?function(t){return"symbol"==typeof t}:function(t){return t instanceof P},Y=function(t,e,n){return t===G&&Y(V,e,n),x(t),e=m(e,!0),x(n),o(D,e)?(n.enumerable?(o(t,A)&&t[A][e]&&(t[A][e]=!1),n=k(n,{enumerable:O(0,!1)})):(o(t,A)||T(t,A,O(1,{})),t[A][e]=!0),B(t,e,n)):T(t,e,n)},Q=function(t,e){x(t);for(var n,r=v(e=S(e)),o=0,i=r.length;i>o;)Y(t,n=r[o++],e[n]);return t},q=function(t,e){return void 0===e?k(t):Q(k(t),e)},X=function(t){var e=I.call(this,t=m(t,!0));return!(this===G&&o(D,t)&&!o(V,t))&&(!(e||!o(this,t)||!o(D,t)||o(this,A)&&this[A][t])||e)},Z=function(t,e){if(t=S(t),e=m(e,!0),t!==G||!o(D,e)||o(V,e)){var n=L(t,e);return!n||!o(D,e)||o(t,A)&&t[A][e]||(n.enumerable=!0),n}},$=function(t){for(var e,n=C(S(t)),r=[],i=0;n.length>i;)o(D,e=n[i++])||e==A||e==s||r.push(e);return r},tt=function(t){for(var e,n=t===G,r=C(n?V:S(t)),i=[],u=0;r.length>u;)!o(D,e=r[u++])||n&&!o(G,e)||i.push(D[e]);return i};H||(P=function(){if(this instanceof P)throw TypeError("Symbol is not a constructor!");var t=p(arguments.length>0?arguments[0]:void 0),e=function(n){this===G&&e.call(V,n),o(this,A)&&o(this[A],t)&&(this[A][t]=!1),B(this,t,O(1,n))};return i&&z&&B(G,t,{configurable:!0,set:e}),J(t)},c(P[F],"toString",function(){return this._k}),j.f=Z,_.f=Y,n(67).f=w.f=$,n(64).f=X,n(63).f=tt,i&&!n(13)&&c(G,"propertyIsEnumerable",X,!0),y.f=function(t){return J(h(t))}),u(u.G+u.W+u.F*!H,{Symbol:P});for(var et="hasInstance,isConcatSpreadable,iterator,match,replace,search,species,split,toPrimitive,toStringTag,unscopables".split(","),nt=0;et.length>nt;)h(et[nt++]);for(var rt=E(h.store),ot=0;rt.length>ot;)d(rt[ot++]);u(u.S+u.F*!H,"Symbol",{"for":function(t){return o(R,t+="")?R[t]:R[t]=P(t)},keyFor:function(t){if(!U(t))throw TypeError(t+" is not a symbol!");for(var e in R)if(R[e]===t)return e},useSetter:function(){z=!0},useSimple:function(){z=!1}}),u(u.S+u.F*!H,"Object",{create:q,defineProperty:Y,defineProperties:Q,getOwnPropertyDescriptor:Z,getOwnPropertyNames:$,getOwnPropertySymbols:tt}),M&&u(u.S+u.F*(!H||a(function(){var t=P();return"[null]"!=K([t])||"{}"!=K({a:t})||"{}"!=K(Object(t))})),"JSON",{stringify:function(t){for(var e,n,r=[t],o=1;arguments.length>o;)r.push(arguments[o++]);if(n=e=r[1],(g(e)||void 0!==t)&&!U(t))return b(e)||(e=function(t,e){if("function"==typeof n&&(e=n.call(this,t,e)),!U(e))return e}),r[1]=e,K.apply(M,r)}}),P[F][N]||n(19)(P[F],N,P[F].valueOf),l(P,"Symbol"),l(Math,"Math",!0),l(r.JSON,"JSON",!0)},function(t,e,n){var r=n(45)("meta"),o=n(22),i=n(30),u=n(20).f,c=0,s=Object.isExtensible||function(){return!0},a=!n(25)(function(){return s(Object.preventExtensions({}))}),f=function(t){u(t,r,{value:{i:"O"+ ++c,w:{}}})},l=function(t,e){if(!o(t))return"symbol"==typeof t?t:("string"==typeof t?"S":"P")+t;if(!i(t,r)){if(!s(t))return"F";if(!e)return"E";f(t)}return t[r].i},p=function(t,e){if(!i(t,r)){if(!s(t))return!0;if(!e)return!1;f(t)}return t[r].w},h=function(t){return a&&y.NEED&&s(t)&&!i(t,r)&&f(t),t},y=t.exports={KEY:r,NEED:!1,fastKey:l,getWeak:p,onFreeze:h}},function(t,e,n){var r=n(15),o=n(16),i=n(13),u=n(56),c=n(20).f;t.exports=function(t){var e=o.Symbol||(o.Symbol=i?{}:r.Symbol||{});"_"==t.charAt(0)||t in e||c(e,t,{value:u.f(t)})}},function(t,e,n){var r=n(35),o=n(63),i=n(64);t.exports=function(t){var e=r(t),n=o.f;if(n)for(var u,c=n(t),s=i.f,a=0;c.length>a;)s.call(t,u=c[a++])&&e.push(u);return e}},function(t,e){e.f=Object.getOwnPropertySymbols},function(t,e){e.f={}.propertyIsEnumerable},function(t,e,n){var r=n(39);t.exports=Array.isArray||function(t){return"Array"==r(t)}},function(t,e,n){var r=n(37),o=n(67).f,i={}.toString,u="object"==typeof window&&window&&Object.getOwnPropertyNames?Object.getOwnPropertyNames(window):[],c=function(t){try{return o(t)}catch(e){return u.slice()}};t.exports.f=function(t){return u&&"[object Window]"==i.call(t)?c(t):o(r(t))}},function(t,e,n){var r=n(36),o=n(46).concat("length","prototype");e.f=Object.getOwnPropertyNames||function(t){return r(t,o)}},function(t,e,n){var r=n(64),o=n(28),i=n(37),u=n(27),c=n(30),s=n(23),a=Object.getOwnPropertyDescriptor;e.f=n(24)?a:function(t,e){if(t=i(t),e=u(e,!0),s)try{return a(t,e)}catch(n){}if(c(t,e))return o(!r.f.call(t,e),t[e])}},function(t,e){},function(t,e,n){n(61)("asyncIterator")},function(t,e,n){n(61)("observable")},function(t,e){"use strict";t.exports={normal:{_meta:{tab:{key:"\t",text:"Tab",width:60,classes:"control"},shiftl:{keySet:"shifted",text:"Shift",width:100,classes:"control"},shiftr:{keySet:"shifted",text:"Shift",width:100,classes:"control"},caps:{keySet:"capsed",text:"Caps lock",width:80,classes:"control"},space:{key:" ",text:"Space",width:180},enter:{key:"\r\n",text:"Enter",width:80,classes:"control"},backspace:{func:"backspace",classes:"control backspace",width:65},accept:{func:"accept",text:"Close",classes:"control featured"},next:{func:"next",text:"Next",classes:"control featured"}},"default":["` 1 2 3 4 5 6 7 8 9 0 - = {backspace}","{tab} q w e r t y u i o p [ ] \\","{caps} a s d f g h j k l ; ' {enter}","{shiftl} z x c v b n m , . / {shiftr}","{next} {space} {accept}"],shifted:["~ ! @ # $ % ^ & * ( ) _ + {backspace}","{tab} Q W E R T Y U I O P { } |",'{caps} A S D F G H J K L : " {enter}',"{shiftl} Z X C V B N M < > ? {shiftr}","{next} {space} {accept}"],capsed:["` 1 2 3 4 5 6 7 8 9 0 - = {backspace}","{tab} Q W E R T Y U I O P [ ] \\","{caps} A S D F G H J K L ; ' {enter}","{shiftl} Z X C V B N M , . / {shiftr}","{next} {space} {accept}"]},compact:{_meta:{"default":{keySet:"default",text:"abc",classes:"control"},alpha:{keySet:"default",text:"Abc",classes:"control"},shift:{keySet:"shifted",text:"ABC",classes:"control"},numbers:{keySet:"numbers",text:"123",classes:"control"},space:{key:" ",text:"Space",width:200},backspace:{func:"backspace",classes:"control"},accept:{func:"accept",text:"Close",classes:"control featured"},next:{func:"next",text:"Next",classes:"featured"},zero:{key:"0",width:130}},"default":["q w e r t y u i o p"," a s d f g h j k l ","{shift} z x c v b n m {backspace}","{numbers} , {space} . {next} {accept}"],shifted:["Q W E R T Y U I O P"," A S D F G H J K L ","{default} Z X C V B N M ","{numbers} _ {space} {backspace} {next} {accept}"],numbers:["1 2 3","4 5 6","7 8 9"," {alpha} . {zero} {backspace} {next} {accept}"]},numeric:{_meta:{backspace:{func:"backspace",classes:"control"},accept:{func:"accept",text:"Close",classes:"control featured"},next:{func:"next",text:"Next",classes:"control featured"},zero:{key:"0",width:130}},"default":["1 2 3","4 5 6","7 8 9","_ - . {zero} {backspace} {next} {accept}"]}}},function(t,e,n){function r(t){return"string"==typeof t||!i(t)&&u(t)&&o(t)==c}var o=n(74),i=n(80),u=n(81),c="[object String]";t.exports=r},function(t,e,n){function r(t){return null==t?void 0===t?s:c:a&&a in Object(t)?i(t):u(t)}var o=n(75),i=n(78),u=n(79),c="[object Null]",s="[object Undefined]",a=o?o.toStringTag:void 0;t.exports=r},function(t,e,n){var r=n(76),o=r.Symbol;t.exports=o},function(t,e,n){var r=n(77),o="object"==typeof self&&self&&self.Object===Object&&self,i=r||o||Function("return this")();t.exports=i},function(t,e){(function(e){var n="object"==typeof e&&e&&e.Object===Object&&e;t.exports=n}).call(e,function(){return this}())},function(t,e,n){function r(t){var e=u.call(t,s),n=t[s];try{t[s]=void 0;var r=!0}catch(o){}var i=c.call(t);return r&&(e?t[s]=n:delete t[s]),i}var o=n(75),i=Object.prototype,u=i.hasOwnProperty,c=i.toString,s=o?o.toStringTag:void 0;t.exports=r},function(t,e){function n(t){return o.call(t)}var r=Object.prototype,o=r.toString;t.exports=n},function(t,e){var n=Array.isArray;t.exports=n},function(t,e){function n(t){return null!=t&&"object"==typeof t}t.exports=n},function(t,e){function n(t){var e=typeof t;return null!=t&&("object"==e||"function"==e)}t.exports=n},function(t,e){t.exports={render:function(){var t=this,e=t.$createElement,n=t._self._c||e;return n("div",{staticClass:"vue-touch-keyboard"},[n("div",{staticClass:"keyboard"},t._l(t.keySet,function(e,r){return n("div",{key:r,staticClass:"line"},t._l(e,function(e,r){return n("span",{key:r,"class":t.getClassesOfKey(e),style:t.getKeyStyle(e),domProps:{textContent:t._s(t.getCaptionOfKey(e))},on:{click:function(n){return t.clickKey(n,e)},mousedown:t.mousedown}})}))}))])},staticRenderFns:[]}}])});
# coding=utf-8 # *** WARNING: this file was generated by crd2pulumi. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** SNAKE_TO_CAMEL_CASE_TABLE = { "api_version": "apiVersion", "application_selector": "applicationSelector", "backing_service_selector": "backingServiceSelector", "backing_service_selectors": "backingServiceSelectors", "binding_path": "bindingPath", "config_map_key_ref": "configMapKeyRef", "container_name": "containerName", "containers_path": "containersPath", "custom_env_var": "customEnvVar", "detect_binding_resources": "detectBindingResources", "env_var_prefix": "envVarPrefix", "field_path": "fieldPath", "field_ref": "fieldRef", "label_selector": "labelSelector", "last_heartbeat_time": "lastHeartbeatTime", "last_transition_time": "lastTransitionTime", "match_expressions": "matchExpressions", "match_labels": "matchLabels", "mount_path_prefix": "mountPathPrefix", "resource_field_ref": "resourceFieldRef", "resource_ref": "resourceRef", "secret_key_ref": "secretKeyRef", "secret_path": "secretPath", "value_from": "valueFrom", } CAMEL_TO_SNAKE_CASE_TABLE = { "apiVersion": "api_version", "applicationSelector": "application_selector", "backingServiceSelector": "backing_service_selector", "backingServiceSelectors": "backing_service_selectors", "bindingPath": "binding_path", "configMapKeyRef": "config_map_key_ref", "containerName": "container_name", "containersPath": "containers_path", "customEnvVar": "custom_env_var", "detectBindingResources": "detect_binding_resources", "envVarPrefix": "env_var_prefix", "fieldPath": "field_path", "fieldRef": "field_ref", "labelSelector": "label_selector", "lastHeartbeatTime": "last_heartbeat_time", "lastTransitionTime": "last_transition_time", "matchExpressions": "match_expressions", "matchLabels": "match_labels", "mountPathPrefix": "mount_path_prefix", "resourceFieldRef": "resource_field_ref", "resourceRef": "resource_ref", "secretKeyRef": "secret_key_ref", "secretPath": "secret_path", "valueFrom": "value_from", }
(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('echarts/lib/echarts'), require('echarts/lib/component/tooltip'), require('echarts/lib/component/legend'), require('echarts/lib/chart/bar')) : typeof define === 'function' && define.amd ? define(['echarts/lib/echarts', 'echarts/lib/component/tooltip', 'echarts/lib/component/legend', 'echarts/lib/chart/bar'], factory) : (global.VeWaterfall = factory(global.echarts)); }(this, (function (echarts) { 'use strict'; echarts = 'default' in echarts ? echarts['default'] : echarts; if (typeof Object.assign !== 'function') { Object.assign = function (target) { if (target == null) { throw new TypeError('Cannot convert undefined or null to object'); } target = Object(target); for (var index = 1; index < arguments.length; index++) { var source = arguments[index]; if (source != null) { for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } } return target; }; } echarts.registerTheme('ve-chart', { categoryAxis: { axisLine: { show: false }, axisTick: { show: false }, splitLine: { show: false } }, valueAxis: { axisLine: { show: false } }, line: { smooth: true }, grid: { containLabel: true, left: 10, right: 10 } }); var color = ['#19d4ae', '#5ab1ef', '#fa6e86', '#ffb980', '#0067a6', '#c4b4e4', '#d87a80', '#9cbbff', '#d9d0c7', '#87a997', '#d49ea2', '#5b4947', '#7ba3a8']; var numberFormat = function numberFormat(val) { var digits = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 2; if (isNaN(+val)) return val; var symbolMap = [{ value: 1E18, symbol: 'E' }, { value: 1E15, symbol: 'P' }, { value: 1E12, symbol: 'T' }, { value: 1E9, symbol: 'B' }, { value: 1E6, symbol: 'M' }, { value: 1E3, symbol: 'k' }]; for (var i = 0; i < symbolMap.length; i++) { if (Math.abs(val) >= symbolMap[i].value) { return (val / symbolMap[i].value).toFixed(digits) + symbolMap[i].symbol; } } return val.toString(); }; var formatTausends = function formatTausends(num) { return String(num).replace(/^(\s+|-)?\d+(?=.?\d*($|\s))/g, function (m) { return m.replace(/(?=(?!\b)(\d{3})+$)/g, ','); }); }; var getFormated = function getFormated(val, type) { var digit = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 2; var defaultVal = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : '-'; if (val == null || isNaN(val)) return defaultVal; switch (type) { case 'KMB': return numberFormat(val); case 'percent': return parseFloat((val * 100).toFixed(digit)) + '%'; case 'normal': return formatTausends(val); default: return val; } }; var getType = function getType(v) { return Object.prototype.toString.call(v); }; function getWaterfallTooltip(dataType, digit) { return { trigger: 'axis', axisPointer: { type: 'shadow' }, formatter: function formatter(items) { var item = items[1]; return [item.name + '<br/>' + item.seriesName + ' :', '' + getFormated(item.value, dataType, digit)].join(''); } }; } function getWaterfallXAxis(args) { var dimension = args.dimension, rows = args.rows, remainStatus = args.remainStatus, totalName = args.totalName, remainName = args.remainName, xAxisName = args.xAxisName, axisVisible = args.axisVisible; var xAxisData = [totalName].concat(rows.map(function (row) { return row[dimension]; })); if (remainStatus === 'have-remain') { xAxisData = xAxisData.concat([remainName]); } return { type: 'category', name: xAxisName, splitLine: { show: false }, data: xAxisData, show: axisVisible }; } function getWaterfallYAxis(args) { var dataType = args.dataType, yAxisName = args.yAxisName, axisVisible = args.axisVisible, digit = args.digit; return { type: 'value', name: yAxisName, axisTick: { show: false }, axisLabel: { formatter: function formatter(val) { return getFormated(val, dataType, digit); } }, show: axisVisible }; } function getWaterfallSeries(args) { var dataType = args.dataType, rows = args.rows, metrics = args.metrics, totalNum = args.totalNum, remainStatus = args.remainStatus, dataSum = args.dataSum, digit = args.digit; var seriesBase = { type: 'bar', stack: '总量' }; var dataSumTemp = dataSum; var totalNumTemp = totalNum; var assistData = void 0; var mainData = void 0; var rowData = rows.map(function (row) { return row[metrics]; }); if (remainStatus === 'have-remain') { assistData = [0].concat(rows.map(function (row) { totalNumTemp -= row[metrics]; return totalNumTemp; })).concat([0]); mainData = [totalNum].concat(rowData).concat([totalNum - dataSum]); } else { assistData = [0].concat(rows.map(function (row) { dataSumTemp -= row[metrics]; return dataSumTemp; })); mainData = [dataSum].concat(rowData); } var series = []; series.push(Object.assign({ name: '辅助', itemStyle: { normal: { opacity: 0 }, emphasis: { opacity: 0 } }, data: assistData }, seriesBase)); series.push(Object.assign({ name: '数值', label: { normal: { show: true, position: 'top', formatter: function formatter(item) { return getFormated(item.value, dataType, digit); } } }, data: mainData }, seriesBase)); return series; } function getWaterfallRemainStatus(dataSum, totalNum) { if (!totalNum) return 'not-total'; return totalNum > dataSum ? 'have-remain' : 'none-remain'; } var waterfall = function waterfall(columns, rows, settings, extra) { var _settings$dataType = settings.dataType, dataType = _settings$dataType === undefined ? 'normal' : _settings$dataType, _settings$dimension = settings.dimension, dimension = _settings$dimension === undefined ? columns[0] : _settings$dimension, _settings$totalName = settings.totalName, totalName = _settings$totalName === undefined ? '总计' : _settings$totalName, totalNum = settings.totalNum, _settings$remainName = settings.remainName, remainName = _settings$remainName === undefined ? '其他' : _settings$remainName, _settings$xAxisName = settings.xAxisName, xAxisName = _settings$xAxisName === undefined ? dimension : _settings$xAxisName, _settings$axisVisible = settings.axisVisible, axisVisible = _settings$axisVisible === undefined ? true : _settings$axisVisible, _settings$digit = settings.digit, digit = _settings$digit === undefined ? 2 : _settings$digit; var tooltipVisible = extra.tooltipVisible; var metricsTemp = columns.slice(); metricsTemp.splice(metricsTemp.indexOf(dimension), 1); var metrics = metricsTemp[0]; var yAxisName = metrics; var tooltip = tooltipVisible && getWaterfallTooltip(dataType, digit); var dataSum = parseFloat(rows.reduce(function (pre, cur) { return pre + Number(cur[metrics]); }, 0).toFixed(digit)); var remainStatus = getWaterfallRemainStatus(dataSum, totalNum); var xAxisParams = { dimension: dimension, rows: rows, remainStatus: remainStatus, totalName: totalName, remainName: remainName, xAxisName: xAxisName, axisVisible: axisVisible }; var xAxis = getWaterfallXAxis(xAxisParams); var yAxis = getWaterfallYAxis({ dataType: dataType, yAxisName: yAxisName, axisVisible: axisVisible, digit: digit }); var seriesParams = { dataType: dataType, rows: rows, dimension: dimension, metrics: metrics, totalNum: totalNum, remainStatus: remainStatus, dataSum: dataSum, digit: digit }; var series = getWaterfallSeries(seriesParams); var options = { tooltip: tooltip, xAxis: xAxis, yAxis: yAxis, series: series }; return options; }; var chartMixin = { props: { data: { type: [Object, Array], default: function _default() { return {}; } }, settings: { type: Object, default: function _default() { return {}; } }, width: { type: String, default: 'auto' }, height: { type: String, default: '400px' }, beforeConfig: { type: Function }, afterConfig: { type: Function }, afterSetOption: { type: Function }, afterSetOptionOnce: { type: Function }, events: { type: Object }, grid: { type: Object }, colors: { type: Array }, tooltipVisible: { type: Boolean, default: true }, legendVisible: { type: Boolean, default: true }, legendPosition: { type: String }, markLine: { type: Object }, markArea: { type: Object }, markPoint: { type: Object }, visualMap: { type: [Object, Array] }, dataZoom: { type: [Object, Array] }, toolbox: { type: Object }, initOptions: { type: Object, default: function _default() { return {}; } }, title: Object, legend: Object, xAxis: Object, yAxis: Object, radar: Object, tooltip: Object, axisPointer: Object, brush: Object, geo: Object, timeline: Object, graphic: Object, series: [Object, Array], backgroundColor: [Object, String], textStyle: Object, animation: Object, theme: Object, themeName: String }, watch: { data: { deep: true, handler: function handler(v) { if (v) { this.dataHandler(v); } } }, settings: { deep: true, handler: function handler(v) { if (v.type && this.chartLib) this.chartHandler = this.chartLib[v.type]; this.dataHandler(this.data); } } }, computed: { canvasStyle: function canvasStyle() { return { width: this.width, height: this.height, position: 'relative' }; }, chartColor: function chartColor() { return this.colors || this.theme && this.theme.color || color; } }, methods: { dataHandler: function dataHandler(data) { if (!this.chartHandler) return; var _data = data, _data$columns = _data.columns, columns = _data$columns === undefined ? [] : _data$columns, _data$rows = _data.rows, rows = _data$rows === undefined ? [] : _data$rows; var extra = { tooltipVisible: this.tooltipVisible, legendVisible: this.legendVisible, echarts: this.echarts, color: this.chartColor }; if (this.beforeConfig) data = this.beforeConfig(data); var options = this.chartHandler(columns, rows, this.settings, extra); if (options) { if (typeof options.then === 'function') { options.then(this.optionsHandler); } else { this.optionsHandler(options); } } }, optionsHandler: function optionsHandler(options) { var _this = this; if (this.legendPosition && options.legend) { options.legend[this.legendPosition] = 10; if (~['left', 'right'].indexOf(this.legendPosition)) { options.legend.top = 'middle'; options.legend.orient = 'vertical'; } } if (!this.themeName) options.color = this.chartColor; var echartsSettings = ['grid', 'dataZoom', 'visualMap', 'toolbox', 'title', 'legend', 'xAxis', 'yAxis', 'radar', 'tooltip', 'axisPointer', 'brush', 'geo', 'timeline', 'graphic', 'series', 'backgroundColor', 'textStyle']; echartsSettings.forEach(function (setting) { if (_this[setting]) options[setting] = _this[setting]; }); if (this.animation) { Object.keys(this.animation).forEach(function (key) { options[key] = _this.animation[key]; }); } if (this.markArea || this.markLine || this.markPoint) { var marks = { markArea: this.markArea, markLine: this.markLine, markPoint: this.markPoint }; var series = options.series; if (getType(series) === '[object Array]') { series.forEach(function (item) { _this.addMark(item, marks); }); } else if (getType(series) === '[object Object]') { this.addMark(series, marks); } } if (this.afterConfig) options = this.afterConfig(options); this.echarts.setOption(options, true); if (this.afterSetOption) this.afterSetOption(this.echarts); if (this.afterSetOptionOnce && !this._once['afterSetOptionOnce']) { this._once['afterSetOptionOnce'] = this.afterSetOptionOnce(this.echarts); } }, addMark: function addMark(seriesItem, marks) { Object.keys(marks).forEach(function (key) { if (marks[key]) { seriesItem[key] = marks[key]; } }); }, init: function init() { if (this.echarts) return; var themeName = this.themeName || (this.theme ? 'outer-theme' : 've-chart'); this.echarts = this.echartsLib.init(this.$refs.canvas, themeName, this.initOptions); if (this.data) this.dataHandler(this.data); if (this.events) this.bindEvents(); }, bindEvents: function bindEvents() { var _this2 = this; Object.keys(this.events).forEach(function (event) { _this2.echarts.on(event, _this2.events[event]); }); }, addWatchToProps: function addWatchToProps() { var _this3 = this; var watchedVariable = this._watchers.map(function (watcher) { return watcher.expression; }); Object.keys(this.$props).forEach(function (prop) { if (!~watchedVariable.indexOf(prop)) { var opts = {}; if (getType(prop) === '[object Object]') { opts.deep = true; } _this3.$watch(prop, function () { _this3.dataHandler(_this3.data); }, opts); } }); }, registerTheme: function registerTheme() { echarts.registerTheme('outer-theme', this.theme); } }, created: function created() { this.echarts = null; this._once = {}; this.addWatchToProps(); if (this.theme) this.registerTheme(); }, mounted: function mounted() { this.init(); window.addEventListener('resize', this.echarts.resize); }, beforeDestory: function beforeDestory() { window.removeEventListener('resize', this.echarts.resize); this.echarts.dispose(); } }; var index = { render: function render() { var _vm = this;var _h = _vm.$createElement;var _c = _vm._self._c || _h;return _c('div', { ref: "canvas", staticClass: "ve-waterfall", style: _vm.canvasStyle }); }, staticRenderFns: [], name: 'VeWaterfall', mixins: [chartMixin], created: function created() { this.chartHandler = waterfall; this.echartsLib = echarts; } }; return index; })));
""" Output Script Descriptors ************************* HWI has a more limited implementation of descriptors. See `Bitcoin Core's documentation <https://github.com/bitcoin/bitcoin/blob/master/doc/descriptors.md>`_ for more details on descriptors. This implementation only supports ``sh()``, ``wsh()``, ``pkh()``, ``wpkh()``, ``multi()``, and ``sortedmulti()`` descriptors. Descriptors can be parsed, however the actual scripts are not generated. """ from .key import ExtendedKey, KeyOriginInfo, parse_path from .common import hash160, sha256 from binascii import unhexlify from collections import namedtuple from enum import Enum from typing import ( List, Optional, Tuple, ) MAX_TAPROOT_NODES = 128 ExpandedScripts = namedtuple("ExpandedScripts", ["output_script", "redeem_script", "witness_script"]) def PolyMod(c: int, val: int) -> int: """ :meta private: Function to compute modulo over the polynomial used for descriptor checksums From: https://github.com/bitcoin/bitcoin/blob/master/src/script/descriptor.cpp """ c0 = c >> 35 c = ((c & 0x7ffffffff) << 5) ^ val if (c0 & 1): c ^= 0xf5dee51989 if (c0 & 2): c ^= 0xa9fdca3312 if (c0 & 4): c ^= 0x1bab10e32d if (c0 & 8): c ^= 0x3706b1677a if (c0 & 16): c ^= 0x644d626ffd return c def DescriptorChecksum(desc: str) -> str: """ Compute the checksum for a descriptor :param desc: The descriptor string to compute a checksum for :return: A checksum """ INPUT_CHARSET = "0123456789()[],'/*abcdefgh@:$%{}IJKLMNOPQRSTUVWXYZ&+-.;<=>?!^_|~ijklmnopqrstuvwxyzABCDEFGH`#\"\\ " CHECKSUM_CHARSET = "qpzry9x8gf2tvdw0s3jn54khce6mua7l" c = 1 cls = 0 clscount = 0 for ch in desc: pos = INPUT_CHARSET.find(ch) if pos == -1: return "" c = PolyMod(c, pos & 31) cls = cls * 3 + (pos >> 5) clscount += 1 if clscount == 3: c = PolyMod(c, cls) cls = 0 clscount = 0 if clscount > 0: c = PolyMod(c, cls) for j in range(0, 8): c = PolyMod(c, 0) c ^= 1 ret = [''] * 8 for j in range(0, 8): ret[j] = CHECKSUM_CHARSET[(c >> (5 * (7 - j))) & 31] return ''.join(ret) def AddChecksum(desc: str) -> str: """ Compute and attach the checksum for a descriptor :param desc: The descriptor string to add a checksum to :return: Descriptor with checksum """ return desc + "#" + DescriptorChecksum(desc) class PubkeyProvider(object): """ A public key expression in a descriptor. Can contain the key origin info, the pubkey itself, and subsequent derivation paths for derivation from the pubkey The pubkey can be a typical pubkey or an extended pubkey. """ def __init__( self, origin: Optional['KeyOriginInfo'], pubkey: str, deriv_path: Optional[str] ) -> None: """ :param origin: The key origin if one is available :param pubkey: The public key. Either a hex string or a serialized extended pubkey :param deriv_path: Additional derivation path if the pubkey is an extended pubkey """ self.origin = origin self.pubkey = pubkey self.deriv_path = deriv_path # Make ExtendedKey from pubkey if it isn't hex self.extkey = None try: unhexlify(self.pubkey) # Is hex, normal pubkey except Exception: # Not hex, maybe xpub self.extkey = ExtendedKey.deserialize(self.pubkey) @classmethod def parse(cls, s: str) -> 'PubkeyProvider': """ Deserialize a key expression from the string into a ``PubkeyProvider``. :param s: String containing the key expression :return: A new ``PubkeyProvider`` containing the details given by ``s`` """ origin = None deriv_path = None if s[0] == "[": end = s.index("]") origin = KeyOriginInfo.from_string(s[1:end]) s = s[end + 1:] pubkey = s slash_idx = s.find("/") if slash_idx != -1: pubkey = s[:slash_idx] deriv_path = s[slash_idx:] return cls(origin, pubkey, deriv_path) def to_string(self) -> str: """ Serialize the pubkey expression to a string to be used in a descriptor :return: The pubkey expression as a string """ s = "" if self.origin: s += "[{}]".format(self.origin.to_string()) s += self.pubkey if self.deriv_path: s += self.deriv_path return s def get_pubkey_bytes(self, pos: int) -> bytes: if self.extkey is not None: if self.deriv_path is not None: path_str = self.deriv_path[1:] if path_str[-1] == "*": path_str = path_str[-1] + str(pos) path = parse_path(path_str) child_key = self.extkey.derive_pub_path(path) return child_key.pubkey else: return self.extkey.pubkey return unhexlify(self.pubkey) def get_full_derivation_path(self, pos: int) -> str: """ Returns the full derivation path at the given position, including the origin """ path = self.origin.get_derivation_path() if self.origin is not None else "m/" path += self.deriv_path if self.deriv_path is not None else "" if path[-1] == "*": path = path[:-1] + str(pos) return path def get_full_derivation_int_list(self, pos: int) -> List[int]: """ Returns the full derivation path as an integer list at the given position. Includes the origin and master key fingerprint as an int """ path: List[int] = self.origin.get_full_int_list() if self.origin is not None else [] if self.deriv_path is not None: der_split = self.deriv_path.split("/") for p in der_split: if not p: continue if p == "*": i = pos elif p[-1] in "'phHP": assert len(p) >= 2 i = int(p[:-1]) | 0x80000000 else: i = int(p) path.append(i) return path def __lt__(self, other: 'PubkeyProvider') -> bool: return self.pubkey < other.pubkey class Descriptor(object): r""" An abstract class for Descriptors themselves. Descriptors can contain multiple :class:`PubkeyProvider`\ s and multiple ``Descriptor`` as subdescriptors. """ def __init__( self, pubkeys: List['PubkeyProvider'], subdescriptors: List['Descriptor'], name: str ) -> None: r""" :param pubkeys: The :class:`PubkeyProvider`\ s that are part of this descriptor :param subdescriptor: The ``Descriptor``s that are part of this descriptor :param name: The name of the function for this descriptor """ self.pubkeys = pubkeys self.subdescriptors = subdescriptors self.name = name def to_string_no_checksum(self) -> str: """ Serializes the descriptor as a string without the descriptor checksum :return: The descriptor string """ return "{}({}{})".format( self.name, ",".join([p.to_string() for p in self.pubkeys]), self.subdescriptors[0].to_string_no_checksum() if len(self.subdescriptors) > 0 else "" ) def to_string(self) -> str: """ Serializes the descriptor as a string with the checksum :return: The descriptor with a checksum """ return AddChecksum(self.to_string_no_checksum()) def expand(self, pos: int) -> "ExpandedScripts": """ Returns the scripts for a descriptor at the given `pos` for ranged descriptors. """ raise NotImplementedError("The Descriptor base class does not implement this method") class PKDescriptor(Descriptor): """ A descriptor for ``pk()`` descriptors """ def __init__( self, pubkey: 'PubkeyProvider' ) -> None: """ :param pubkey: The :class:`PubkeyProvider` for this descriptor """ super().__init__([pubkey], [], "pk") class PKHDescriptor(Descriptor): """ A descriptor for ``pkh()`` descriptors """ def __init__( self, pubkey: 'PubkeyProvider' ) -> None: """ :param pubkey: The :class:`PubkeyProvider` for this descriptor """ super().__init__([pubkey], [], "pkh") def expand(self, pos: int) -> "ExpandedScripts": script = b"\x76\xa9\x14" + hash160(self.pubkeys[0].get_pubkey_bytes(pos)) + b"\x88\xac" return ExpandedScripts(script, None, None) class WPKHDescriptor(Descriptor): """ A descriptor for ``wpkh()`` descriptors """ def __init__( self, pubkey: 'PubkeyProvider' ) -> None: """ :param pubkey: The :class:`PubkeyProvider` for this descriptor """ super().__init__([pubkey], [], "wpkh") def expand(self, pos: int) -> "ExpandedScripts": script = b"\x00\x14" + hash160(self.pubkeys[0].get_pubkey_bytes(pos)) return ExpandedScripts(script, None, None) class MultisigDescriptor(Descriptor): """ A descriptor for ``multi()`` and ``sortedmulti()`` descriptors """ def __init__( self, pubkeys: List['PubkeyProvider'], thresh: int, is_sorted: bool ) -> None: r""" :param pubkeys: The :class:`PubkeyProvider`\ s for this descriptor :param thresh: The number of keys required to sign this multisig :param is_sorted: Whether this is a ``sortedmulti()`` descriptor """ super().__init__(pubkeys, [], "sortedmulti" if is_sorted else "multi") self.thresh = thresh self.is_sorted = is_sorted if self.is_sorted: self.pubkeys.sort() def to_string_no_checksum(self) -> str: return "{}({},{})".format(self.name, self.thresh, ",".join([p.to_string() for p in self.pubkeys])) def expand(self, pos: int) -> "ExpandedScripts": if self.thresh > 16: m = b"\x01" + self.thresh.to_bytes(1, "big") else: m = (self.thresh + 0x50).to_bytes(1, "big") if self.thresh > 0 else b"\x00" n = (len(self.pubkeys) + 0x50).to_bytes(1, "big") if len(self.pubkeys) > 0 else b"\x00" script: bytes = m der_pks = [p.get_pubkey_bytes(pos) for p in self.pubkeys] if self.is_sorted: der_pks.sort() for pk in der_pks: script += len(pk).to_bytes(1, "big") + pk script += n + b"\xae" return ExpandedScripts(script, None, None) class SHDescriptor(Descriptor): """ A descriptor for ``sh()`` descriptors """ def __init__( self, subdescriptor: 'Descriptor' ) -> None: """ :param subdescriptor: The :class:`Descriptor` that is a sub-descriptor for this descriptor """ super().__init__([], [subdescriptor], "sh") def expand(self, pos: int) -> "ExpandedScripts": assert len(self.subdescriptors) == 1 redeem_script, _, witness_script = self.subdescriptors[0].expand(pos) script = b"\xa9\x14" + hash160(redeem_script) + b"\x87" return ExpandedScripts(script, redeem_script, witness_script) class WSHDescriptor(Descriptor): """ A descriptor for ``wsh()`` descriptors """ def __init__( self, subdescriptor: 'Descriptor' ) -> None: """ :param subdescriptor: The :class:`Descriptor` that is a sub-descriptor for this descriptor """ super().__init__([], [subdescriptor], "wsh") def expand(self, pos: int) -> "ExpandedScripts": assert len(self.subdescriptors) == 1 witness_script, _, _ = self.subdescriptors[0].expand(pos) script = b"\x00\x20" + sha256(witness_script) return ExpandedScripts(script, None, witness_script) class TRDescriptor(Descriptor): """ A descriptor for ``tr()`` descriptors """ def __init__( self, internal_key: 'PubkeyProvider', subdescriptors: List['Descriptor'] = [], depths: List[int] = [] ) -> None: """ :param internal_key: The :class:`PubkeyProvider` that is the internal key for this descriptor :param subdescriptors: The :class:`Descriptor`s that are the leaf scripts for this descriptor :param depths: The depths of the leaf scripts in the same order as `subdescriptors` """ super().__init__([internal_key], subdescriptors, "tr") self.depths = depths def to_string_no_checksum(self) -> str: r = f"{self.name}({self.pubkeys[0].to_string()}" path: List[bool] = [] # Track left or right for each depth for p, depth in enumerate(self.depths): r += "," while len(path) <= depth: if len(path) > 0: r += "{" path.append(False) r += self.subdescriptors[p].to_string_no_checksum() while len(path) > 0 and path[-1]: if len(path) > 0: r += "}" path.pop() if len(path) > 0: path[-1] = True r += ")" return r def _get_func_expr(s: str) -> Tuple[str, str]: """ Get the function name and then the expression inside :param s: The string that begins with a function name :return: The function name as the first element of the tuple, and the expression contained within the function as the second element :raises: ValueError: if a matching pair of parentheses cannot be found """ start = s.index("(") end = s.rindex(")") return s[0:start], s[start + 1:end] def _get_const(s: str, const: str) -> str: """ Get the first character of the string, make sure it is the expected character, and return the rest of the string :param s: The string that begins with a constant character :param const: The constant character :return: The remainder of the string without the constant character :raises: ValueError: if the first character is not the constant character """ if s[0] != const: raise ValueError(f"Expected '{const}' but got '{s[0]}'") return s[1:] def _get_expr(s: str) -> Tuple[str, str]: """ Extract the expression that ``s`` begins with. This will return the initial part of ``s``, up to the first comma or closing brace, skipping ones that are surrounded by braces. :param s: The string to extract the expression from :return: A pair with the first item being the extracted expression and the second the rest of the string """ level: int = 0 for i, c in enumerate(s): if c in ["(", "{"]: level += 1 elif level > 0 and c in [")", "}"]: level -= 1 elif level == 0 and c in [")", "}", ","]: break return s[0:i], s[i:] def parse_pubkey(expr: str) -> Tuple['PubkeyProvider', str]: """ Parses an individual pubkey expression from a string that may contain more than one pubkey expression. :param expr: The expression to parse a pubkey expression from :return: The :class:`PubkeyProvider` that is parsed as the first item of a tuple, and the remainder of the expression as the second item. """ end = len(expr) comma_idx = expr.find(",") next_expr = "" if comma_idx != -1: end = comma_idx next_expr = expr[end + 1:] return PubkeyProvider.parse(expr[:end]), next_expr class _ParseDescriptorContext(Enum): """ :meta private: Enum representing the level that we are in when parsing a descriptor. Some expressions aren't allowed at certain levels, this helps us track those. """ TOP = 1 """The top level, not within any descriptor""" P2SH = 2 """Within a ``sh()`` descriptor""" P2WSH = 3 """Within a ``wsh()`` descriptor""" P2TR = 4 """Within a ``tr()`` descriptor""" def _parse_descriptor(desc: str, ctx: '_ParseDescriptorContext') -> 'Descriptor': """ :meta private: Parse a descriptor given the context level we are in. Used recursively to parse subdescriptors :param desc: The descriptor string to parse :param ctx: The :class:`_ParseDescriptorContext` indicating the level we are in :return: The parsed descriptor :raises: ValueError: if the descriptor is malformed """ func, expr = _get_func_expr(desc) if func == "pk": pubkey, expr = parse_pubkey(expr) if expr: raise ValueError("more than one pubkey in pk descriptor") return PKDescriptor(pubkey) if func == "pkh": if not (ctx == _ParseDescriptorContext.TOP or ctx == _ParseDescriptorContext.P2SH or ctx == _ParseDescriptorContext.P2WSH): raise ValueError("Can only have pkh at top level, in sh(), or in wsh()") pubkey, expr = parse_pubkey(expr) if expr: raise ValueError("More than one pubkey in pkh descriptor") return PKHDescriptor(pubkey) if func == "sortedmulti" or func == "multi": if not (ctx == _ParseDescriptorContext.TOP or ctx == _ParseDescriptorContext.P2SH or ctx == _ParseDescriptorContext.P2WSH): raise ValueError("Can only have multi/sortedmulti at top level, in sh(), or in wsh()") is_sorted = func == "sortedmulti" comma_idx = expr.index(",") thresh = int(expr[:comma_idx]) expr = expr[comma_idx + 1:] pubkeys = [] while expr: pubkey, expr = parse_pubkey(expr) pubkeys.append(pubkey) if len(pubkeys) == 0 or len(pubkeys) > 16: raise ValueError("Cannot have {} keys in a multisig; must have between 1 and 16 keys, inclusive".format(len(pubkeys))) elif thresh < 1: raise ValueError("Multisig threshold cannot be {}, must be at least 1".format(thresh)) elif thresh > len(pubkeys): raise ValueError("Multisig threshold cannot be larger than the number of keys; threshold is {} but only {} keys specified".format(thresh, len(pubkeys))) if ctx == _ParseDescriptorContext.TOP and len(pubkeys) > 3: raise ValueError("Cannot have {} pubkeys in bare multisig: only at most 3 pubkeys") return MultisigDescriptor(pubkeys, thresh, is_sorted) if func == "wpkh": if not (ctx == _ParseDescriptorContext.TOP or ctx == _ParseDescriptorContext.P2SH): raise ValueError("Can only have wpkh() at top level or inside sh()") pubkey, expr = parse_pubkey(expr) if expr: raise ValueError("More than one pubkey in pkh descriptor") return WPKHDescriptor(pubkey) if func == "sh": if ctx != _ParseDescriptorContext.TOP: raise ValueError("Can only have sh() at top level") subdesc = _parse_descriptor(expr, _ParseDescriptorContext.P2SH) return SHDescriptor(subdesc) if func == "wsh": if not (ctx == _ParseDescriptorContext.TOP or ctx == _ParseDescriptorContext.P2SH): raise ValueError("Can only have wsh() at top level or inside sh()") subdesc = _parse_descriptor(expr, _ParseDescriptorContext.P2WSH) return WSHDescriptor(subdesc) if func == "tr": if ctx != _ParseDescriptorContext.TOP: raise ValueError("Can only have tr at top level") internal_key, expr = parse_pubkey(expr) subscripts = [] depths = [] if expr: # Path from top of the tree to what we're currently processing. # branches[i] == False: left branch in the i'th step from the top # branches[i] == true: right branch branches = [] while True: # Process open braces while True: try: expr = _get_const(expr, "{") branches.append(False) except ValueError: break if len(branches) > MAX_TAPROOT_NODES: raise ValueError("tr() supports at most {MAX_TAPROOT_NODES} nesting levels") # Process script expression sarg, expr = _get_expr(expr) subscripts.append(_parse_descriptor(sarg, _ParseDescriptorContext.P2TR)) depths.append(len(branches)) # Process closing braces while len(branches) > 0 and branches[-1]: expr = _get_const(expr, "}") branches.pop() # If we're at the end of a left branch, expect a comma if len(branches) > 0 and not branches[-1]: expr = _get_const(expr, ",") branches[-1] = True if len(branches) == 0: break return TRDescriptor(internal_key, subscripts, depths) if ctx == _ParseDescriptorContext.P2SH: raise ValueError("A function is needed within P2SH") elif ctx == _ParseDescriptorContext.P2WSH: raise ValueError("A function is needed within P2WSH") raise ValueError("{} is not a valid descriptor function".format(func)) def parse_descriptor(desc: str) -> 'Descriptor': """ Parse a descriptor string into a :class:`Descriptor`. Validates the checksum if one is provided in the string :param desc: The descriptor string :return: The parsed :class:`Descriptor` :raises: ValueError: if the descriptor string is malformed """ i = desc.find("#") if i != -1: checksum = desc[i + 1:] desc = desc[:i] computed = DescriptorChecksum(desc) if computed != checksum: raise ValueError("The checksum does not match; Got {}, expected {}".format(checksum, computed)) return _parse_descriptor(desc, _ParseDescriptorContext.TOP)
from operator import attrgetter import pyangbind.lib.xpathhelper as xpathhelper from pyangbind.lib.yangtypes import RestrictedPrecisionDecimalType, RestrictedClassType, TypedListType from pyangbind.lib.yangtypes import YANGBool, YANGListType, YANGDynClass, ReferenceType from pyangbind.lib.base import PybindBase from decimal import Decimal from bitarray import bitarray import __builtin__ import external_lsa import summary_lsa import on_startup class router_lsa(PybindBase): """ This class was auto-generated by the PythonClass plugin for PYANG from YANG module brocade-rbridge - based on the path /rbridge-id/ipv6/router/ospf/max-metric/router-lsa. Each member element of the container is represented as a class variable - with a specific YANG type. YANG Description: The router-lsa parameter configures the device to advertise the maximum metric for point-to-point and transit links. """ __slots__ = ('_pybind_generated_by', '_path_helper', '_yang_name', '_rest_name', '_extmethods', '__all_lsas','__external_lsa','__summary_lsa','__include_stub','__on_startup',) _yang_name = 'router-lsa' _rest_name = 'router-lsa' _pybind_generated_by = 'container' def __init__(self, *args, **kwargs): path_helper_ = kwargs.pop("path_helper", None) if path_helper_ is False: self._path_helper = False elif path_helper_ is not None and isinstance(path_helper_, xpathhelper.YANGPathHelper): self._path_helper = path_helper_ elif hasattr(self, "_parent"): path_helper_ = getattr(self._parent, "_path_helper", False) self._path_helper = path_helper_ else: self._path_helper = False extmethods = kwargs.pop("extmethods", None) if extmethods is False: self._extmethods = False elif extmethods is not None and isinstance(extmethods, dict): self._extmethods = extmethods elif hasattr(self, "_parent"): extmethods = getattr(self._parent, "_extmethods", None) self._extmethods = extmethods else: self._extmethods = False self.__external_lsa = YANGDynClass(base=external_lsa.external_lsa, is_container='container', presence=True, yang_name="external-lsa", rest_name="external-lsa", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'Replace Metric in External LSA with max metric value'}}, namespace='urn:brocade.com:mgmt:brocade-ospfv3', defining_module='brocade-ospfv3', yang_type='container', is_config=True) self.__summary_lsa = YANGDynClass(base=summary_lsa.summary_lsa, is_container='container', presence=True, yang_name="summary-lsa", rest_name="summary-lsa", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'Replace Metric in Summary LSA with max metric value'}}, namespace='urn:brocade.com:mgmt:brocade-ospfv3', defining_module='brocade-ospfv3', yang_type='container', is_config=True) self.__all_lsas = YANGDynClass(base=YANGBool, is_leaf=True, yang_name="all-lsas", rest_name="all-lsas", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'cli-full-command': None, u'info': u'Replace Metric in all External and Summary LSAs with default max metric value', u'cli-full-no': None}}, namespace='urn:brocade.com:mgmt:brocade-ospfv3', defining_module='brocade-ospfv3', yang_type='empty', is_config=True) self.__on_startup = YANGDynClass(base=on_startup.on_startup, is_container='container', presence=False, yang_name="on-startup", rest_name="on-startup", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'Apply this on OSPF startup'}}, namespace='urn:brocade.com:mgmt:brocade-ospfv3', defining_module='brocade-ospfv3', yang_type='container', is_config=True) self.__include_stub = YANGDynClass(base=YANGBool, is_leaf=True, yang_name="include-stub", rest_name="include-stub", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'Configure include-stub for max-metric', u'cli-full-command': None, u'cli-full-no': None}}, namespace='urn:brocade.com:mgmt:brocade-ospfv3', defining_module='brocade-ospfv3', yang_type='empty', is_config=True) load = kwargs.pop("load", None) if args: if len(args) > 1: raise TypeError("cannot create a YANG container with >1 argument") all_attr = True for e in self._pyangbind_elements: if not hasattr(args[0], e): all_attr = False break if not all_attr: raise ValueError("Supplied object did not have the correct attributes") for e in self._pyangbind_elements: nobj = getattr(args[0], e) if nobj._changed() is False: continue setmethod = getattr(self, "_set_%s" % e) if load is None: setmethod(getattr(args[0], e)) else: setmethod(getattr(args[0], e), load=load) def _path(self): if hasattr(self, "_parent"): return self._parent._path()+[self._yang_name] else: return [u'rbridge-id', u'ipv6', u'router', u'ospf', u'max-metric', u'router-lsa'] def _rest_path(self): if hasattr(self, "_parent"): if self._rest_name: return self._parent._rest_path()+[self._rest_name] else: return self._parent._rest_path() else: return [u'rbridge-id', u'ipv6', u'router', u'ospf', u'max-metric', u'router-lsa'] def _get_all_lsas(self): """ Getter method for all_lsas, mapped from YANG variable /rbridge_id/ipv6/router/ospf/max_metric/router_lsa/all_lsas (empty) """ return self.__all_lsas def _set_all_lsas(self, v, load=False): """ Setter method for all_lsas, mapped from YANG variable /rbridge_id/ipv6/router/ospf/max_metric/router_lsa/all_lsas (empty) If this variable is read-only (config: false) in the source YANG file, then _set_all_lsas is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_all_lsas() directly. """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=YANGBool, is_leaf=True, yang_name="all-lsas", rest_name="all-lsas", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'cli-full-command': None, u'info': u'Replace Metric in all External and Summary LSAs with default max metric value', u'cli-full-no': None}}, namespace='urn:brocade.com:mgmt:brocade-ospfv3', defining_module='brocade-ospfv3', yang_type='empty', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """all_lsas must be of a type compatible with empty""", 'defined-type': "empty", 'generated-type': """YANGDynClass(base=YANGBool, is_leaf=True, yang_name="all-lsas", rest_name="all-lsas", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'cli-full-command': None, u'info': u'Replace Metric in all External and Summary LSAs with default max metric value', u'cli-full-no': None}}, namespace='urn:brocade.com:mgmt:brocade-ospfv3', defining_module='brocade-ospfv3', yang_type='empty', is_config=True)""", }) self.__all_lsas = t if hasattr(self, '_set'): self._set() def _unset_all_lsas(self): self.__all_lsas = YANGDynClass(base=YANGBool, is_leaf=True, yang_name="all-lsas", rest_name="all-lsas", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'cli-full-command': None, u'info': u'Replace Metric in all External and Summary LSAs with default max metric value', u'cli-full-no': None}}, namespace='urn:brocade.com:mgmt:brocade-ospfv3', defining_module='brocade-ospfv3', yang_type='empty', is_config=True) def _get_external_lsa(self): """ Getter method for external_lsa, mapped from YANG variable /rbridge_id/ipv6/router/ospf/max_metric/router_lsa/external_lsa (container) YANG Description: The external-lsa parameter configures the maximum metric value for external type-5 and type-7 LSAs. """ return self.__external_lsa def _set_external_lsa(self, v, load=False): """ Setter method for external_lsa, mapped from YANG variable /rbridge_id/ipv6/router/ospf/max_metric/router_lsa/external_lsa (container) If this variable is read-only (config: false) in the source YANG file, then _set_external_lsa is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_external_lsa() directly. YANG Description: The external-lsa parameter configures the maximum metric value for external type-5 and type-7 LSAs. """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=external_lsa.external_lsa, is_container='container', presence=True, yang_name="external-lsa", rest_name="external-lsa", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'Replace Metric in External LSA with max metric value'}}, namespace='urn:brocade.com:mgmt:brocade-ospfv3', defining_module='brocade-ospfv3', yang_type='container', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """external_lsa must be of a type compatible with container""", 'defined-type': "container", 'generated-type': """YANGDynClass(base=external_lsa.external_lsa, is_container='container', presence=True, yang_name="external-lsa", rest_name="external-lsa", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'Replace Metric in External LSA with max metric value'}}, namespace='urn:brocade.com:mgmt:brocade-ospfv3', defining_module='brocade-ospfv3', yang_type='container', is_config=True)""", }) self.__external_lsa = t if hasattr(self, '_set'): self._set() def _unset_external_lsa(self): self.__external_lsa = YANGDynClass(base=external_lsa.external_lsa, is_container='container', presence=True, yang_name="external-lsa", rest_name="external-lsa", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'Replace Metric in External LSA with max metric value'}}, namespace='urn:brocade.com:mgmt:brocade-ospfv3', defining_module='brocade-ospfv3', yang_type='container', is_config=True) def _get_summary_lsa(self): """ Getter method for summary_lsa, mapped from YANG variable /rbridge_id/ipv6/router/ospf/max_metric/router_lsa/summary_lsa (container) """ return self.__summary_lsa def _set_summary_lsa(self, v, load=False): """ Setter method for summary_lsa, mapped from YANG variable /rbridge_id/ipv6/router/ospf/max_metric/router_lsa/summary_lsa (container) If this variable is read-only (config: false) in the source YANG file, then _set_summary_lsa is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_summary_lsa() directly. """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=summary_lsa.summary_lsa, is_container='container', presence=True, yang_name="summary-lsa", rest_name="summary-lsa", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'Replace Metric in Summary LSA with max metric value'}}, namespace='urn:brocade.com:mgmt:brocade-ospfv3', defining_module='brocade-ospfv3', yang_type='container', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """summary_lsa must be of a type compatible with container""", 'defined-type': "container", 'generated-type': """YANGDynClass(base=summary_lsa.summary_lsa, is_container='container', presence=True, yang_name="summary-lsa", rest_name="summary-lsa", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'Replace Metric in Summary LSA with max metric value'}}, namespace='urn:brocade.com:mgmt:brocade-ospfv3', defining_module='brocade-ospfv3', yang_type='container', is_config=True)""", }) self.__summary_lsa = t if hasattr(self, '_set'): self._set() def _unset_summary_lsa(self): self.__summary_lsa = YANGDynClass(base=summary_lsa.summary_lsa, is_container='container', presence=True, yang_name="summary-lsa", rest_name="summary-lsa", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'Replace Metric in Summary LSA with max metric value'}}, namespace='urn:brocade.com:mgmt:brocade-ospfv3', defining_module='brocade-ospfv3', yang_type='container', is_config=True) def _get_include_stub(self): """ Getter method for include_stub, mapped from YANG variable /rbridge_id/ipv6/router/ospf/max_metric/router_lsa/include_stub (empty) YANG Description: The include-stub parameter specifies the advertisement of the maximum metric value for point-to-point and broadcast stub links in the intra-area-prefix LSA. """ return self.__include_stub def _set_include_stub(self, v, load=False): """ Setter method for include_stub, mapped from YANG variable /rbridge_id/ipv6/router/ospf/max_metric/router_lsa/include_stub (empty) If this variable is read-only (config: false) in the source YANG file, then _set_include_stub is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_include_stub() directly. YANG Description: The include-stub parameter specifies the advertisement of the maximum metric value for point-to-point and broadcast stub links in the intra-area-prefix LSA. """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=YANGBool, is_leaf=True, yang_name="include-stub", rest_name="include-stub", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'Configure include-stub for max-metric', u'cli-full-command': None, u'cli-full-no': None}}, namespace='urn:brocade.com:mgmt:brocade-ospfv3', defining_module='brocade-ospfv3', yang_type='empty', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """include_stub must be of a type compatible with empty""", 'defined-type': "empty", 'generated-type': """YANGDynClass(base=YANGBool, is_leaf=True, yang_name="include-stub", rest_name="include-stub", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'Configure include-stub for max-metric', u'cli-full-command': None, u'cli-full-no': None}}, namespace='urn:brocade.com:mgmt:brocade-ospfv3', defining_module='brocade-ospfv3', yang_type='empty', is_config=True)""", }) self.__include_stub = t if hasattr(self, '_set'): self._set() def _unset_include_stub(self): self.__include_stub = YANGDynClass(base=YANGBool, is_leaf=True, yang_name="include-stub", rest_name="include-stub", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'Configure include-stub for max-metric', u'cli-full-command': None, u'cli-full-no': None}}, namespace='urn:brocade.com:mgmt:brocade-ospfv3', defining_module='brocade-ospfv3', yang_type='empty', is_config=True) def _get_on_startup(self): """ Getter method for on_startup, mapped from YANG variable /rbridge_id/ipv6/router/ospf/max_metric/router_lsa/on_startup (container) YANG Description: The on-startup parameter specifies the advertisement of the maximum metric for a limited period only, on startup. """ return self.__on_startup def _set_on_startup(self, v, load=False): """ Setter method for on_startup, mapped from YANG variable /rbridge_id/ipv6/router/ospf/max_metric/router_lsa/on_startup (container) If this variable is read-only (config: false) in the source YANG file, then _set_on_startup is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_on_startup() directly. YANG Description: The on-startup parameter specifies the advertisement of the maximum metric for a limited period only, on startup. """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=on_startup.on_startup, is_container='container', presence=False, yang_name="on-startup", rest_name="on-startup", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'Apply this on OSPF startup'}}, namespace='urn:brocade.com:mgmt:brocade-ospfv3', defining_module='brocade-ospfv3', yang_type='container', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """on_startup must be of a type compatible with container""", 'defined-type': "container", 'generated-type': """YANGDynClass(base=on_startup.on_startup, is_container='container', presence=False, yang_name="on-startup", rest_name="on-startup", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'Apply this on OSPF startup'}}, namespace='urn:brocade.com:mgmt:brocade-ospfv3', defining_module='brocade-ospfv3', yang_type='container', is_config=True)""", }) self.__on_startup = t if hasattr(self, '_set'): self._set() def _unset_on_startup(self): self.__on_startup = YANGDynClass(base=on_startup.on_startup, is_container='container', presence=False, yang_name="on-startup", rest_name="on-startup", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'Apply this on OSPF startup'}}, namespace='urn:brocade.com:mgmt:brocade-ospfv3', defining_module='brocade-ospfv3', yang_type='container', is_config=True) all_lsas = __builtin__.property(_get_all_lsas, _set_all_lsas) external_lsa = __builtin__.property(_get_external_lsa, _set_external_lsa) summary_lsa = __builtin__.property(_get_summary_lsa, _set_summary_lsa) include_stub = __builtin__.property(_get_include_stub, _set_include_stub) on_startup = __builtin__.property(_get_on_startup, _set_on_startup) _pyangbind_elements = {'all_lsas': all_lsas, 'external_lsa': external_lsa, 'summary_lsa': summary_lsa, 'include_stub': include_stub, 'on_startup': on_startup, }
#pragma once namespace Kore { namespace Graphics4 { class PipelineState; } class PipelineStateImpl; class ShaderImpl { public: ShaderImpl(void* data, int length); ShaderImpl(const char* source); virtual ~ShaderImpl(); uint _glid; const char* source; int length; friend class Graphics4::PipelineState; friend class PipelineStateImpl; }; class ConstantLocationImpl { public: int location; unsigned int type; }; }
(this["webpackJsonpsafe-react"]=this["webpackJsonpsafe-react"]||[]).push([[84],{1444:function(e,n,t){"use strict";t.r(n);var r=t(1),a=t.n(r),o=t(1506);function i(e,n,t,r,a,o,i){try{var l=e[o](i),s=l.value}catch(c){return void t(c)}l.done?n(s):Promise.resolve(s).then(r,a)}n.default=function(e){var n=e.preferred,r=e.label,l=e.iconSrc,s=e.svg,c=e.rpcUrl;return{name:r||"imToken",iconSrc:l,svg:s||'\n\t<svg xmlns="http://www.w3.org/2000/svg" width="40" height="40" viewBox="0 0 93 93">\n\t\t<defs>\n\t\t\t\t<linearGradient id="a" x1="97.185%" x2="-.038%" y1="3.105%" y2="99.699%">\n\t\t\t\t\t\t<stop offset="0%" stop-color="#11C4D1"/>\n\t\t\t\t\t\t<stop offset="100%" stop-color="#0062AD"/>\n\t\t\t\t</linearGradient>\n\t\t</defs>\n\t\t<g fill="none" fill-rule="nonzero">\n\t\t\t\t<path fill="url(#a)" d="M92.755 63.804s0 9.64-1.028 13.78c-1.028 4.187-2.985 7.06-5.09 9.202-2.154 2.142-4.993 4.09-9.3 5.112-4.356 1.023-13.754.974-13.754.974H29.417s-9.642 0-13.803-1.022c-4.16-1.071-7.097-2.97-9.25-5.113-2.155-2.142-4.112-4.966-5.091-9.3-1.028-4.333-.98-13.682-.98-13.682V29.671s0-9.64 1.029-13.78c1.027-4.187 2.985-7.06 5.09-9.202 2.154-2.142 4.993-4.09 9.3-5.113C20.068.554 29.466.603 29.466.603h34.166s9.642 0 13.803 1.022c4.16 1.071 7.097 2.97 9.25 5.113 2.154 2.142 4.112 4.966 5.091 9.3.98 4.333.98 13.682.98 13.682v34.084z"/>\n\t\t\t\t<path fill="#FFF" d="M78.267 28.795c1.909 26.244-15.614 38.71-31.326 40.073-14.587 1.265-28.292-7.304-29.467-20.597-.979-10.955 6.07-15.678 11.6-16.117 5.679-.486 10.427 3.263 10.867 7.84.392 4.382-2.447 6.427-4.454 6.573-1.566.146-3.524-.78-3.72-2.727-.147-1.704.538-1.899.342-3.7-.293-3.214-3.181-3.555-4.747-3.409-1.91.146-5.385 2.338-4.944 7.694.49 5.404 5.874 9.69 12.922 9.056 7.636-.682 12.971-6.378 13.363-14.412 0-.439.098-.828.293-1.218.098-.146.147-.292.294-.438.196-.292.392-.536.636-.779l.686-.682c3.328-3.019 15.37-10.225 26.676-7.985.098 0 .196.049.245.097.44 0 .685.341.734.73"/>\n\t\t</g>\n\t</svg>\n',wallet:function(){var e,n=(e=a.a.mark((function e(n){var r,o,i,l,s,u,f;return a.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(r=n.getProviderName,o=n.getBalance,i=window.ethereum,!(l="imToken"===r(i))||!c){e.next=7;break}return e.next=6,Promise.all([t.e(1),t.e(2),t.e(3)]).then(t.bind(null,1549));case 6:s=e.sent.default;case 7:return u=s?s({rpcUrl:c}):null,f=!1,e.abrupt("return",{provider:i,interface:l?{address:{get:function(){return Promise.resolve(i.selectedAddress)}},network:{get:function(){return Promise.resolve(Number(i.networkVersion))}},balance:{get:function(){return u?o(u,i.selectedAddress):(f||(console.warn('The imToken provider does not allow rpc calls preventing Onboard.js from getting the balance. You can pass in a "rpcUrl" to the imToken wallet initialization object to get the balance.'),f=!0),Promise.resolve(null))}},name:r(i),connect:function(){return i.enable()}}:null});case 10:case"end":return e.stop()}}),e)})),function(){var n=this,t=arguments;return new Promise((function(r,a){var o=e.apply(n,t);function l(e){i(o,r,a,l,s,"next",e)}function s(e){i(o,r,a,l,s,"throw",e)}l(void 0)}))});return function(e){return n.apply(this,arguments)}}(),type:"injected",link:"imtokenv2://navigate?screen=DappView&url=".concat(window.location.href),installMessage:o.b,mobile:!0,preferred:n}}},1506:function(e,n,t){"use strict";t.d(n,"a",(function(){return r})),t.d(n,"b",(function(){return a}));var r=function(e){var n=e.currentWallet,t=e.selectedWallet;return n?'\n <p style="font-size: 0.889rem; font-family: inherit; margin: 0.889rem 0;">\n We have detected that you already have\n <b>'.concat(n,"</b>\n installed. If you would prefer to use\n <b>").concat(t,'</b>\n instead, then click below to install.\n </p>\n <p style="font-size: 0.889rem; font-family: inherit; margin: 0.889rem 0;">\n <b>Tip:</b>\n If you already have ').concat(t,' installed, check your\n browser extension settings to make sure that you have it enabled\n and that you have disabled any other browser extension wallets.\n <span\n class="bn-onboard-clickable"\n style="color: #4a90e2; font-size: 0.889rem; font-family: inherit;"\n onclick="window.location.reload();">\n Then refresh the page.\n </span>\n </p>\n '):'\n <p style="font-size: 0.889rem; font-family: inherit; margin: 0.889rem 0;">\n You\'ll need to install <b>'.concat(t,'</b> to continue. Once you have it installed, go ahead and\n <span\n class="bn-onboard-clickable"\n style="color: #4a90e2; font-size: 0.889rem; font-family: inherit;"\n onclick={window.location.reload();}>\n refresh the page.\n </span>\n ').concat("Opera"===t?'<br><br><i>Hint: If you already have Opera installed, make sure that your web3 wallet is <a style="color: #4a90e2; font-size: 0.889rem; font-family: inherit;" class="bn-onboard-clickable" href="https://help.opera.com/en/touch/crypto-wallet/" rel="noreferrer noopener" target="_blank">enabled</a></i>':"","\n </p>\n ")},a=function(e){var n=e.selectedWallet;return'\n <p style="font-size: 0.889rem;">\n Tap the button below to <b>Open '.concat(n,"</b>. Please access this site on ").concat(n,"'s in-app browser for a seamless experience.\n </p>\n ")}}}]); //# sourceMappingURL=84.b8c7afca.chunk.js.map
import re f = open('04.txt') rows = f.readlines() f.close() validCount = 0 byr = iyr = eyr = hgt = hcl = ecl = pid = cid = False i = 0 while i < len(rows): row = str(rows[i]) i +=1 # next line if len(row) < 2: #end of passport entry or end of file if byr and iyr and eyr and hgt and hcl and ecl and pid: validCount += 1 byr = iyr = eyr = hgt = hcl = ecl = pid = cid = False continue if not byr: byrRes = re.search('byr:(\d{4})', row) byrVal = int(byrRes.group(1)) if byrRes else -1 if byrVal >= 1920 and byrVal <= 2002: byr = True if not iyr: iyrRes = re.search('iyr:(\d{4})', row) iyrVal = int(iyrRes.group(1)) if iyrRes else -1 if iyrVal >= 2010 and iyrVal <= 2020: iyr = True if not eyr: eyrRes = re.search('eyr:(\d{4})', row) eyrVal = int(eyrRes.group(1)) if eyrRes else -1 if eyrVal >= 2020 and eyrVal <= 2030: eyr = True if not hgt: hgtRes = re.search('hgt:(\d+)(.{2})', row) if hgtRes: hgtVal = int(hgtRes.group(1)) hgtUnit = hgtRes.group(2) if hgtUnit == 'cm': if hgtVal >= 150 and hgtVal <= 193: hgt = True elif hgtUnit == 'in': if hgtVal >= 59 and hgtVal <= 76: hgt = True if not hcl: hclRes = re.search('hcl:#([a-fA-F0-9]{6})', row) if hclRes: hcl = True if not ecl: eclRes = re.search('ecl:(amb|blu|brn|gry|grn|hzl|oth)', row) if eclRes: ecl = True if not pid: pidRes = re.search('pid:(\d{9})', row) if pidRes: pid = True print(str(validCount))
"""Test different accessory types: Media Players.""" from homeassistant.components.homekit.const import ( ATTR_VALUE, CONF_FEATURE_LIST, FEATURE_ON_OFF, FEATURE_PLAY_PAUSE, FEATURE_PLAY_STOP, FEATURE_TOGGLE_MUTE, ) from homeassistant.components.homekit.type_media_players import ( MediaPlayer, TelevisionMediaPlayer, ) from homeassistant.components.media_player import DEVICE_CLASS_TV from homeassistant.components.media_player.const import ( ATTR_INPUT_SOURCE, ATTR_INPUT_SOURCE_LIST, ATTR_MEDIA_VOLUME_LEVEL, ATTR_MEDIA_VOLUME_MUTED, DOMAIN, ) from homeassistant.const import ( ATTR_DEVICE_CLASS, ATTR_ENTITY_ID, ATTR_SUPPORTED_FEATURES, EVENT_HOMEASSISTANT_START, STATE_IDLE, STATE_OFF, STATE_ON, STATE_PAUSED, STATE_PLAYING, STATE_STANDBY, ) from homeassistant.core import CoreState from homeassistant.helpers import entity_registry from tests.common import async_mock_service async def test_media_player_set_state(hass, hk_driver, events): """Test if accessory and HA are updated accordingly.""" config = { CONF_FEATURE_LIST: { FEATURE_ON_OFF: None, FEATURE_PLAY_PAUSE: None, FEATURE_PLAY_STOP: None, FEATURE_TOGGLE_MUTE: None, } } entity_id = "media_player.test" hass.states.async_set( entity_id, None, {ATTR_SUPPORTED_FEATURES: 20873, ATTR_MEDIA_VOLUME_MUTED: False}, ) await hass.async_block_till_done() acc = MediaPlayer(hass, hk_driver, "MediaPlayer", entity_id, 2, config) await acc.run_handler() await hass.async_block_till_done() assert acc.aid == 2 assert acc.category == 8 # Switch assert acc.chars[FEATURE_ON_OFF].value is False assert acc.chars[FEATURE_PLAY_PAUSE].value is False assert acc.chars[FEATURE_PLAY_STOP].value is False assert acc.chars[FEATURE_TOGGLE_MUTE].value is False hass.states.async_set(entity_id, STATE_ON, {ATTR_MEDIA_VOLUME_MUTED: True}) await hass.async_block_till_done() assert acc.chars[FEATURE_ON_OFF].value is True assert acc.chars[FEATURE_TOGGLE_MUTE].value is True hass.states.async_set(entity_id, STATE_OFF) await hass.async_block_till_done() assert acc.chars[FEATURE_ON_OFF].value is False hass.states.async_set(entity_id, STATE_ON) await hass.async_block_till_done() assert acc.chars[FEATURE_ON_OFF].value is True hass.states.async_set(entity_id, STATE_STANDBY) await hass.async_block_till_done() assert acc.chars[FEATURE_ON_OFF].value is False hass.states.async_set(entity_id, STATE_PLAYING) await hass.async_block_till_done() assert acc.chars[FEATURE_PLAY_PAUSE].value is True assert acc.chars[FEATURE_PLAY_STOP].value is True hass.states.async_set(entity_id, STATE_PAUSED) await hass.async_block_till_done() assert acc.chars[FEATURE_PLAY_PAUSE].value is False hass.states.async_set(entity_id, STATE_IDLE) await hass.async_block_till_done() assert acc.chars[FEATURE_PLAY_STOP].value is False # Set from HomeKit call_turn_on = async_mock_service(hass, DOMAIN, "turn_on") call_turn_off = async_mock_service(hass, DOMAIN, "turn_off") call_media_play = async_mock_service(hass, DOMAIN, "media_play") call_media_pause = async_mock_service(hass, DOMAIN, "media_pause") call_media_stop = async_mock_service(hass, DOMAIN, "media_stop") call_toggle_mute = async_mock_service(hass, DOMAIN, "volume_mute") await hass.async_add_executor_job( acc.chars[FEATURE_ON_OFF].client_update_value, True ) await hass.async_block_till_done() assert call_turn_on assert call_turn_on[0].data[ATTR_ENTITY_ID] == entity_id assert len(events) == 1 assert events[-1].data[ATTR_VALUE] is None await hass.async_add_executor_job( acc.chars[FEATURE_ON_OFF].client_update_value, False ) await hass.async_block_till_done() assert call_turn_off assert call_turn_off[0].data[ATTR_ENTITY_ID] == entity_id assert len(events) == 2 assert events[-1].data[ATTR_VALUE] is None await hass.async_add_executor_job( acc.chars[FEATURE_PLAY_PAUSE].client_update_value, True ) await hass.async_block_till_done() assert call_media_play assert call_media_play[0].data[ATTR_ENTITY_ID] == entity_id assert len(events) == 3 assert events[-1].data[ATTR_VALUE] is None await hass.async_add_executor_job( acc.chars[FEATURE_PLAY_PAUSE].client_update_value, False ) await hass.async_block_till_done() assert call_media_pause assert call_media_pause[0].data[ATTR_ENTITY_ID] == entity_id assert len(events) == 4 assert events[-1].data[ATTR_VALUE] is None await hass.async_add_executor_job( acc.chars[FEATURE_PLAY_STOP].client_update_value, True ) await hass.async_block_till_done() assert call_media_play assert call_media_play[1].data[ATTR_ENTITY_ID] == entity_id assert len(events) == 5 assert events[-1].data[ATTR_VALUE] is None await hass.async_add_executor_job( acc.chars[FEATURE_PLAY_STOP].client_update_value, False ) await hass.async_block_till_done() assert call_media_stop assert call_media_stop[0].data[ATTR_ENTITY_ID] == entity_id assert len(events) == 6 assert events[-1].data[ATTR_VALUE] is None await hass.async_add_executor_job( acc.chars[FEATURE_TOGGLE_MUTE].client_update_value, True ) await hass.async_block_till_done() assert call_toggle_mute assert call_toggle_mute[0].data[ATTR_ENTITY_ID] == entity_id assert call_toggle_mute[0].data[ATTR_MEDIA_VOLUME_MUTED] is True assert len(events) == 7 assert events[-1].data[ATTR_VALUE] is None await hass.async_add_executor_job( acc.chars[FEATURE_TOGGLE_MUTE].client_update_value, False ) await hass.async_block_till_done() assert call_toggle_mute assert call_toggle_mute[1].data[ATTR_ENTITY_ID] == entity_id assert call_toggle_mute[1].data[ATTR_MEDIA_VOLUME_MUTED] is False assert len(events) == 8 assert events[-1].data[ATTR_VALUE] is None async def test_media_player_television(hass, hk_driver, events, caplog): """Test if television accessory and HA are updated accordingly.""" entity_id = "media_player.television" # Supports 'select_source', 'volume_step', 'turn_on', 'turn_off', # 'volume_mute', 'volume_set', 'pause' hass.states.async_set( entity_id, None, { ATTR_DEVICE_CLASS: DEVICE_CLASS_TV, ATTR_SUPPORTED_FEATURES: 3469, ATTR_MEDIA_VOLUME_MUTED: False, ATTR_INPUT_SOURCE_LIST: ["HDMI 1", "HDMI 2", "HDMI 3", "HDMI 4"], }, ) await hass.async_block_till_done() acc = TelevisionMediaPlayer(hass, hk_driver, "MediaPlayer", entity_id, 2, None) await acc.run_handler() await hass.async_block_till_done() assert acc.aid == 2 assert acc.category == 31 # Television assert acc.char_active.value == 0 assert acc.char_remote_key.value == 0 assert acc.char_input_source.value == 0 assert acc.char_mute.value is False hass.states.async_set(entity_id, STATE_ON, {ATTR_MEDIA_VOLUME_MUTED: True}) await hass.async_block_till_done() assert acc.char_active.value == 1 assert acc.char_mute.value is True hass.states.async_set(entity_id, STATE_OFF) await hass.async_block_till_done() assert acc.char_active.value == 0 hass.states.async_set(entity_id, STATE_ON) await hass.async_block_till_done() assert acc.char_active.value == 1 hass.states.async_set(entity_id, STATE_STANDBY) await hass.async_block_till_done() assert acc.char_active.value == 0 hass.states.async_set(entity_id, STATE_ON, {ATTR_INPUT_SOURCE: "HDMI 2"}) await hass.async_block_till_done() assert acc.char_input_source.value == 1 hass.states.async_set(entity_id, STATE_ON, {ATTR_INPUT_SOURCE: "HDMI 3"}) await hass.async_block_till_done() assert acc.char_input_source.value == 2 hass.states.async_set(entity_id, STATE_ON, {ATTR_INPUT_SOURCE: "HDMI 5"}) await hass.async_block_till_done() assert acc.char_input_source.value == 0 assert caplog.records[-2].levelname == "WARNING" # Set from HomeKit call_turn_on = async_mock_service(hass, DOMAIN, "turn_on") call_turn_off = async_mock_service(hass, DOMAIN, "turn_off") call_media_play = async_mock_service(hass, DOMAIN, "media_play") call_media_pause = async_mock_service(hass, DOMAIN, "media_pause") call_media_play_pause = async_mock_service(hass, DOMAIN, "media_play_pause") call_toggle_mute = async_mock_service(hass, DOMAIN, "volume_mute") call_select_source = async_mock_service(hass, DOMAIN, "select_source") call_volume_up = async_mock_service(hass, DOMAIN, "volume_up") call_volume_down = async_mock_service(hass, DOMAIN, "volume_down") call_volume_set = async_mock_service(hass, DOMAIN, "volume_set") await hass.async_add_executor_job(acc.char_active.client_update_value, 1) await hass.async_block_till_done() assert call_turn_on assert call_turn_on[0].data[ATTR_ENTITY_ID] == entity_id assert len(events) == 1 assert events[-1].data[ATTR_VALUE] is None await hass.async_add_executor_job(acc.char_active.client_update_value, 0) await hass.async_block_till_done() assert call_turn_off assert call_turn_off[0].data[ATTR_ENTITY_ID] == entity_id assert len(events) == 2 assert events[-1].data[ATTR_VALUE] is None await hass.async_add_executor_job(acc.char_remote_key.client_update_value, 11) await hass.async_block_till_done() assert call_media_play_pause assert call_media_play_pause[0].data[ATTR_ENTITY_ID] == entity_id assert len(events) == 3 assert events[-1].data[ATTR_VALUE] is None hass.states.async_set(entity_id, STATE_PLAYING) await hass.async_block_till_done() await hass.async_add_executor_job(acc.char_remote_key.client_update_value, 11) await hass.async_block_till_done() assert call_media_pause assert call_media_pause[0].data[ATTR_ENTITY_ID] == entity_id assert len(events) == 4 assert events[-1].data[ATTR_VALUE] is None await hass.async_add_executor_job(acc.char_remote_key.client_update_value, 10) await hass.async_block_till_done() assert len(events) == 4 assert events[-1].data[ATTR_VALUE] is None hass.states.async_set(entity_id, STATE_PAUSED) await hass.async_block_till_done() await hass.async_add_executor_job(acc.char_remote_key.client_update_value, 11) await hass.async_block_till_done() assert call_media_play assert call_media_play[0].data[ATTR_ENTITY_ID] == entity_id assert len(events) == 5 assert events[-1].data[ATTR_VALUE] is None await hass.async_add_executor_job(acc.char_mute.client_update_value, True) await hass.async_block_till_done() assert call_toggle_mute assert call_toggle_mute[0].data[ATTR_ENTITY_ID] == entity_id assert call_toggle_mute[0].data[ATTR_MEDIA_VOLUME_MUTED] is True assert len(events) == 6 assert events[-1].data[ATTR_VALUE] is None await hass.async_add_executor_job(acc.char_mute.client_update_value, False) await hass.async_block_till_done() assert call_toggle_mute assert call_toggle_mute[1].data[ATTR_ENTITY_ID] == entity_id assert call_toggle_mute[1].data[ATTR_MEDIA_VOLUME_MUTED] is False assert len(events) == 7 assert events[-1].data[ATTR_VALUE] is None await hass.async_add_executor_job(acc.char_input_source.client_update_value, 1) await hass.async_block_till_done() assert call_select_source assert call_select_source[0].data[ATTR_ENTITY_ID] == entity_id assert call_select_source[0].data[ATTR_INPUT_SOURCE] == "HDMI 2" assert len(events) == 8 assert events[-1].data[ATTR_VALUE] is None await hass.async_add_executor_job(acc.char_volume_selector.client_update_value, 0) await hass.async_block_till_done() assert call_volume_up assert call_volume_up[0].data[ATTR_ENTITY_ID] == entity_id assert len(events) == 9 assert events[-1].data[ATTR_VALUE] is None await hass.async_add_executor_job(acc.char_volume_selector.client_update_value, 1) await hass.async_block_till_done() assert call_volume_down assert call_volume_down[0].data[ATTR_ENTITY_ID] == entity_id assert len(events) == 10 assert events[-1].data[ATTR_VALUE] is None await hass.async_add_executor_job(acc.char_volume.client_update_value, 20) await hass.async_block_till_done() assert call_volume_set[0] assert call_volume_set[0].data[ATTR_ENTITY_ID] == entity_id assert call_volume_set[0].data[ATTR_MEDIA_VOLUME_LEVEL] == 20 assert len(events) == 11 assert events[-1].data[ATTR_VALUE] is None async def test_media_player_television_basic(hass, hk_driver, events, caplog): """Test if basic television accessory and HA are updated accordingly.""" entity_id = "media_player.television" # Supports turn_on', 'turn_off' hass.states.async_set( entity_id, None, {ATTR_DEVICE_CLASS: DEVICE_CLASS_TV, ATTR_SUPPORTED_FEATURES: 384}, ) await hass.async_block_till_done() acc = TelevisionMediaPlayer(hass, hk_driver, "MediaPlayer", entity_id, 2, None) await acc.run_handler() await hass.async_block_till_done() assert acc.chars_tv == [] assert acc.chars_speaker == [] assert acc.support_select_source is False hass.states.async_set(entity_id, STATE_ON, {ATTR_MEDIA_VOLUME_MUTED: True}) await hass.async_block_till_done() assert acc.char_active.value == 1 hass.states.async_set(entity_id, STATE_OFF) await hass.async_block_till_done() assert acc.char_active.value == 0 hass.states.async_set(entity_id, STATE_ON, {ATTR_INPUT_SOURCE: "HDMI 3"}) await hass.async_block_till_done() assert acc.char_active.value == 1 assert not caplog.messages or "Error" not in caplog.messages[-1] async def test_media_player_television_supports_source_select_no_sources( hass, hk_driver, events, caplog ): """Test if basic tv that supports source select but is missing a source list.""" entity_id = "media_player.television" # Supports turn_on', 'turn_off' hass.states.async_set( entity_id, None, {ATTR_DEVICE_CLASS: DEVICE_CLASS_TV, ATTR_SUPPORTED_FEATURES: 3469}, ) await hass.async_block_till_done() acc = TelevisionMediaPlayer(hass, hk_driver, "MediaPlayer", entity_id, 2, None) await acc.run_handler() await hass.async_block_till_done() assert acc.support_select_source is False async def test_tv_restore(hass, hk_driver, events): """Test setting up an entity from state in the event registry.""" hass.state = CoreState.not_running registry = await entity_registry.async_get_registry(hass) registry.async_get_or_create( "media_player", "generic", "1234", suggested_object_id="simple", device_class=DEVICE_CLASS_TV, ) registry.async_get_or_create( "media_player", "generic", "9012", suggested_object_id="all_info_set", capabilities={ ATTR_INPUT_SOURCE_LIST: ["HDMI 1", "HDMI 2", "HDMI 3", "HDMI 4"], }, supported_features=3469, device_class=DEVICE_CLASS_TV, ) hass.bus.async_fire(EVENT_HOMEASSISTANT_START, {}) await hass.async_block_till_done() acc = TelevisionMediaPlayer( hass, hk_driver, "MediaPlayer", "media_player.simple", 2, None ) assert acc.category == 31 assert acc.chars_tv == [] assert acc.chars_speaker == [] assert acc.support_select_source is False assert not hasattr(acc, "char_input_source") acc = TelevisionMediaPlayer( hass, hk_driver, "MediaPlayer", "media_player.all_info_set", 2, None ) assert acc.category == 31 assert acc.chars_tv == ["RemoteKey"] assert acc.chars_speaker == [ "Name", "Active", "VolumeControlType", "VolumeSelector", "Volume", ] assert acc.support_select_source is True assert acc.char_input_source is not None
import customAttributes, { CustomAttributeRegistry } from './index.js'; window.customAttributes = customAttributes; window.CustomAttributeRegistry = CustomAttributeRegistry;
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var typescript_1 = require("../../typescript"); var NodeHandlerHelper = /** @class */ (function () { function NodeHandlerHelper(compilerFactory) { this.compilerFactory = compilerFactory; } NodeHandlerHelper.prototype.handleForValues = function (handler, currentNode, newNode, newSourceFile) { if (this.compilerFactory.hasCompilerNode(currentNode)) handler.handleNode(this.compilerFactory.getExistingCompilerNode(currentNode), newNode, newSourceFile); else if (currentNode.kind === typescript_1.SyntaxKind.SyntaxList) { // always handle syntax lists because their children might be in the cache // todo: pass this in for performance reasons var sourceFile = this.compilerFactory.getExistingCompilerNode(currentNode.getSourceFile()); handler.handleNode(this.compilerFactory.getNodeFromCompilerNode(currentNode, sourceFile), newNode, newSourceFile); } }; NodeHandlerHelper.prototype.forgetNodeIfNecessary = function (currentNode) { if (this.compilerFactory.hasCompilerNode(currentNode)) this.compilerFactory.getExistingCompilerNode(currentNode).forget(); }; return NodeHandlerHelper; }()); exports.NodeHandlerHelper = NodeHandlerHelper;
module.exports = { blog: { posts: [], }, }
""" Functions to slice a mesh. For now, computes planar cross-section """ import numpy as np import numpy.linalg as la import collections # ---- Geometry datastructures def make_edge(v1, v2): """ We store edges as tuple where the vertex indices are sorted (so the edge going from v1 to v2 and v2 to v1 is the same) """ return tuple(sorted((v1, v2))) class TriangleMesh(object): def __init__(self, verts, tris): """ Args: verts: The 3D vertex positions tris: A list of triplet containing vertex indices for each triangle """ self.verts = verts # For each edge, contains the list of triangles it belongs to # If the mesh is closed, each edge belongs to 2 triangles self.edges_to_tris = collections.defaultdict(lambda: []) # For each triangle, contains the edges it contains self.tris_to_edges = {} # For each vertex, the list of triangles it belongs to self.verts_to_tris = collections.defaultdict(lambda: []) self.tris = tris # Fill data structures for tid, f in enumerate(tris): tri_edges = [] for i in range(3): v1 = f[i] v2 = f[(i + 1) % 3] e = make_edge(v1, v2) self.edges_to_tris[e].append(tid) tri_edges.append(e) self.verts_to_tris[f[i]].append(tid) self.tris_to_edges[tid] = tri_edges # Sanity check : max 2 faces per edge for e, tris in self.edges_to_tris.items(): assert len(tris) <= 2 def edges_for_triangle(self, tidx): """Returns the edges forming triangle with given index""" return self.tris_to_edges[tidx] def triangles_for_edge(self, edge): return self.edges_to_tris[edge] def triangles_for_vert(self, vidx): """Returns the triangles `vidx` belongs to""" return self.verts_to_tris[vidx] class Plane(object): def __init__(self, orig, normal): self.orig = orig self.n = normal / la.norm(normal) def __str__(self): return 'plane(o=%s, n=%s)' % (self.orig, self.n) def point_to_plane_dist(p, plane): return np.dot((p - plane.orig), plane.n) def triangle_intersects_plane(mesh, tid, plane): """ Returns true if the given triangle is cut by the plane. This will return false if a single vertex of the triangle lies on the plane """ dists = [point_to_plane_dist(mesh.verts[vid], plane) for vid in mesh.tris[tid]] side = np.sign(dists) return not (side[0] == side[1] == side[2]) # ---- Planar cross-section INTERSECT_EDGE = 0 INTERSECT_VERTEX = 1 def compute_triangle_plane_intersections(mesh, tid, plane, dist_tol): """ Compute the intersection between a triangle and a plane Returns a list of intersections in the form (INTERSECT_EDGE, <intersection point>, <edge>) for edges intersection (INTERSECT_VERTEX, <intersection point>, <vertex index) for vertices This return between 0 and 2 intersections : - 0 : the plane does not intersect the plane - 1 : one of the triangle's vertices lies on the plane (so it just "touches" the plane without really intersecting) - 2 : the plane slice the triangle in two parts (either vertex-edge, vertex-vertex or edge-edge) """ # TODO: Use a distance cache dists = {vid: point_to_plane_dist(mesh.verts[vid], plane) for vid in mesh.tris[tid]} # TODO: Use an edge intersection cache (we currently compute each edge # intersection twice : once for each tri) # This is to avoid registering the same vertex intersection twice # from two different edges vert_intersect = {vid: False for vid in dists.keys()} # Iterate through the edges, cutting the ones that intersect intersections = [] for e in mesh.edges_for_triangle(tid): v1 = mesh.verts[e[0]] d1 = dists[e[0]] v2 = mesh.verts[e[1]] d2 = dists[e[1]] if np.fabs(d1) < dist_tol: # Avoid creating the vertex intersection twice if not vert_intersect[e[0]]: # point on plane intersections.append((INTERSECT_VERTEX, v1, e[0])) vert_intersect[e[0]] = True if np.fabs(d2) < dist_tol: if not vert_intersect[e[1]]: # point on plane intersections.append((INTERSECT_VERTEX, v2, e[1])) vert_intersect[e[1]] = True if d1 * d2 < 0: # Due to numerical accuracy, we could have both a vertex intersect # and an edge intersect on the same vertex, which is impossible if not vert_intersect[e[0]] and not vert_intersect[e[1]]: # intersection factor (between 0 and 1) # here is a nice drawing : # https://ravehgonen.files.wordpress.com/2013/02/slide8.png # keep in mind d1, d2 are *signed* distances (=> d1 - d2) s = d1 / (d1 - d2) vdir = v2 - v1 ipos = v1 + vdir * s intersections.append((INTERSECT_EDGE, ipos, e)) return intersections def get_next_triangle(mesh, from_tid, plane, intersection, dist_tol): """ Returns the next triangle to visit given the intersection and the triangle we're coming from We look for a triangle that is cut by the plane (2 intersections) as opposed to one that only touch the plane (1 vertex intersection) """ if intersection[0] == INTERSECT_EDGE: tris = mesh.triangles_for_edge(intersection[2]) elif intersection[0] == INTERSECT_VERTEX: tris = mesh.triangles_for_vert(intersection[2]) for tid in tris: if tid != from_tid: intersections = compute_triangle_plane_intersections( mesh, tid, plane, dist_tol) if len(intersections) == 2: return tid, intersections return None, [] def cross_section_mesh(mesh, plane, dist_tol=1e-8): """ Args: mesh: A geom.TriangleMesh instance plane: The cut plane : geom.Plane instance dist_tol: If two points are closer than dist_tol, they are considered the same """ # Set of all triangles T = set(range(len(mesh.tris))) # List of all cross-section polylines P = [] while len(T) > 0: tid = T.pop() intersections = compute_triangle_plane_intersections( mesh, tid, plane, dist_tol) if len(intersections) == 2: # We found a starting triangle for a new polyline p = [] # We can start in either direction (intersections[0] or [1]), this # is arbitrary for the first triangle p.append(intersections[0][1]) tid, intersections = get_next_triangle(mesh, tid, plane, intersections[0], dist_tol) # Loop until we have explored all the triangles for the current # polyline while tid in T: T.remove(tid) # get_next_triangle returns triangles that our plane actually # intersects (as opposed to touching only a single vertex), # hence the assert assert len(intersections) == 2 # Of the two returned intersections, one should have the # intersection point equal to p[-1] if la.norm(intersections[0][1] - p[-1]) < dist_tol: intersect = intersections[1] else: assert la.norm(intersections[1][1] - p[-1]) < dist_tol, \ '%s not close to %s' % (str(p[-1]), str(intersections)) intersect = intersections[0] p.append(intersect[1]) tid, intersections = get_next_triangle(mesh, tid, plane, intersect, dist_tol) if tid is None: print('Degenerate case (probably non-closed mesh)') break P.append(np.array(p)) return P def cross_section(verts, tris, plane_orig, plane_normal, **kwargs): """ Compute the planar cross section of a mesh. This returns a set of polylines. Args: verts: Nx3 array of the vertices position faces: Nx3 array of the faces, containing vertex indices plane_orig: 3-vector indicating the plane origin plane_normal: 3-vector indicating the plane normal Returns: A list of Nx3 arrays, each representing a disconnected portion of the cross section as a polyline """ mesh = TriangleMesh(verts, tris) plane = Plane(plane_orig, plane_normal) return cross_section_mesh(mesh, plane, **kwargs)
import pytest import numpy as np from tbats.bats import Components class TestComponents(object): def test_period_normalization(self): periods = [2.2, 3.3, 1.0] c = Components(seasonal_periods=periods) assert np.array_equal([2, 3, 1], c.seasonal_periods) @pytest.mark.parametrize( "old_periods, new_periods", [ [ # no periods before and after [], [], ], [ # replaced period [5], [2], ], [ # 1 period changed to 3 [7], [3, 4, 6], ], ] ) def test_with_seasonal_periods(self, old_periods, new_periods): c = Components(seasonal_periods=old_periods) copied = c.with_seasonal_periods(seasonal_periods=new_periods) # old components should not change assert np.array_equal(old_periods, c.seasonal_periods) # new components should have new periods and zeros for harmonics assert np.array_equal(new_periods, copied.seasonal_periods) def test_without_seasonal_periods(self): old_periods = [3, 4] c = Components(seasonal_periods=old_periods) copied = c.without_seasonal_periods() # old components should not change assert np.array_equal(old_periods, c.seasonal_periods) # new components should have no periods and no harmonics assert np.array_equal([], copied.seasonal_periods)
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class Dcmtk(CMakePackage): """DCMTK is a collection of libraries and applications implementing large parts of the DICOM standard.""" homepage = "https://dicom.offis.de" url = "https://github.com/DCMTK/dcmtk/archive/DCMTK-3.6.3.tar.gz" version('3.6.3', sha256='57f4f71ee4af9114be6408ff6fcafc441c349e4c2954e17c9c22c8ce0fb065bf') version('3.6.2', sha256='e9bf6e8805bbcf8a25274566541798785fd4e73bd046045ef27a0109ab520924') variant('ssl', default=True, description="Suuport DICOM Security Enhancements one") depends_on('openssl', type=('build', 'link'), when="+ssl") variant('zlib', default=True, description="Support 'Deflated Explicit VR Little Endian' Transfer Syntax") depends_on('zlib', type=('build', 'link'), when="+zlib") variant('tiff', default=True, description="Support for TIFF output") depends_on('libtiff', type=('build', 'link'), when='+tiff') variant('png', default=True, description="Support for PNG output") depends_on('libpng', type=('build', 'link'), when='+png') variant('xml', default=True, description="Support for XML input") depends_on('libxml2', type=('build', 'link'), when='+xml') variant('iconv', default=True, description="Charset conversion support (iconv)") depends_on('iconv', type=('build', 'link')) variant('cxx11', default=False, description="Enable c++11 features") variant('stl', default=True, description="Use native STL implementation") def patch(self): # Backport 3.6.4 if self.spec.satisfies('@:3.6.3 %fj'): filter_file( 'OFintegral_constant<size_t,-1>', 'OFintegral_constant<size_t,~OFstatic_cast(size_t,0)>', 'ofstd/include/dcmtk/ofstd/variadic/helpers.h', string=True ) def cmake_args(self): args = ["-DDCMTK_WITH_OPENSSL={0}".format( 'ON' if '+ssl' in self.spec else 'OFF')] args += ["-DDCMTK_WITH_ZLIB={0}".format( 'ON' if '+zlib' in self.spec else 'OFF')] args += ["-DDCMTK_WITH_TIFF={0}".format( 'ON' if '+tiff' in self.spec else 'OFF')] args += ["-DDCMTK_WITH_PNG={0}".format( 'ON' if '+png' in self.spec else 'OFF')] args += ["-DDCMTK_WITH_XML={0}".format( 'ON' if '+xml' in self.spec else 'OFF')] args += ["-DDCMTK_WITH_ICONV={0}".format( 'ON' if '+iconv' in self.spec else 'OFF')] args += ["-DDCMTK_ENABLE_CXX11={0}".format( 'ON' if '+cxx11' in self.spec else 'OFF')] args += ["-DDCMTK_ENABLE_STL={0}".format( 'ON' if '+stl' in self.spec else 'OFF')] return args
import asyncio, discord, os, re, psutil, platform, time, sys, fnmatch, subprocess, speedtest, json, struct, shutil, tempfile from PIL import Image from discord.ext import commands from Cogs import Utils, Settings, DisplayName, ReadableTime, GetImage, ProgressBar, UserTime, Message, DL try: from urllib.parse import urlparse except ImportError: from urlparse import urlparse def setup(bot): # Add the bot and deps settings = bot.get_cog("Settings") bot.add_cog(Bot(bot, settings, sys.argv[0], 'python')) # This is the Bot module - it contains things like nickname, status, etc class Bot(commands.Cog): # Init with the bot reference, and a reference to the settings var def __init__(self, bot, settings, path = None, pypath = None): self.bot = bot self.settings = settings self.startTime = int(time.time()) self.path = path self.pypath = pypath self.regex = re.compile(r"(http|ftp|https)://([\w_-]+(?:(?:\.[\w_-]+)+))([\w.,@?^=%&:/~+#-]*[\w@?^=%&/~+#-])?") self.is_current = False global Utils, DisplayName Utils = self.bot.get_cog("Utils") DisplayName = self.bot.get_cog("DisplayName") def _is_submodule(self, parent, child): return parent == child or child.startswith(parent + ".") @commands.Cog.listener() async def on_unloaded_extension(self, ext): # Called to shut things down if not self._is_submodule(ext.__name__, self.__module__): return self.is_current = False @commands.Cog.listener() async def on_loaded_extension(self, ext): # See if we were loaded if not self._is_submodule(ext.__name__, self.__module__): return await self.bot.wait_until_ready() self.is_current = True self.bot.loop.create_task(self.status_loop()) async def status_loop(self): # Helper method to loop through and ensure the status remains while not self.bot.is_closed(): try: if not self.is_current: # Bail if we're not the current instance return await self._update_status() except Exception as e: print(str(e)) await asyncio.sleep(3600) # runs only every 60 minutes (3600 seconds) async def onserverjoin(self, server): # Iterate the blocked list and see if we are blocked serverList = self.settings.getGlobalStat('BlockedServers',[]) for serv in serverList: serverName = str(serv).lower() try: serverID = int(serv) except Exception: serverID = None if serverName == server.name.lower() or serverID == server.id: # Found it try: await server.leave() except: pass return True # Check for owner name and id quick # Name *MUST* be case-sensitive and have the discriminator for safety namecheck = server.owner.name + "#" + str(server.owner.discriminator) if serv == namecheck or serverID == server.owner.id: # Got the owner try: await server.leave() except: pass return True return False @commands.command(pass_context=True) async def botinfo(self, ctx): """Lists some general stats about the bot.""" bot_member = self.bot.user if not ctx.guild else ctx.guild.get_member(self.bot.user.id) color = bot_member if isinstance(bot_member,discord.Member) else None message = await Message.EmbedText(title="Gathering info...", color=color).send(ctx) # Get guild count guild_count = "{:,}".format(len(self.bot.guilds)) # Try to do this more efficiently, and faster total_members = [x.id for x in self.bot.get_all_members()] unique_members = set(total_members) if len(total_members) == len(unique_members): member_count = "{:,}".format(len(total_members)) else: member_count = "{:,} ({:,} unique)".format(len(total_members), len(unique_members)) # Get commands/cogs count cog_amnt = 0 empty_cog = 0 for cog in self.bot.cogs: visible = [] for c in self.bot.get_cog(cog).get_commands(): if c.hidden: continue visible.append(c) if not len(visible): empty_cog +=1 # Skip empty cogs continue cog_amnt += 1 cog_count = "{:,} cog".format(cog_amnt) # Easy way to append "s" if needed: if not len(self.bot.cogs) == 1: cog_count += "s" if empty_cog: cog_count += " [{:,} without commands]".format(empty_cog) visible = [] for command in self.bot.commands: if command.hidden: continue visible.append(command) command_count = "{:,}".format(len(visible)) # Get localized created time local_time = UserTime.getUserTime(ctx.author, self.settings, bot_member.created_at) created_at = "{} {}".format(local_time['time'], local_time['zone']) # Get localized joined time if in a server if isinstance(bot_member,discord.Member): local_time = UserTime.getUserTime(ctx.author, self.settings, bot_member.joined_at) joined_at = "{} {}".format(local_time['time'], local_time['zone']) # Get the current prefix prefix = await self.bot.command_prefix(self.bot, ctx.message) prefix = ", ".join([x for x in prefix if not x == "<@!{}> ".format(self.bot.user.id)]) # Get the owners ownerList = self.settings.getGlobalStat('Owner',[]) owners = "Unclaimed..." if len(ownerList): userList = [] for owner in ownerList: # Get the owner's name user = self.bot.get_user(int(owner)) if not user: userString = "Unknown User ({})".format(owner) else: userString = "{}#{}".format(user.name, user.discriminator) userList.append(userString) owners = ', '.join(userList) # Get bot's avatar url avatar = Utils.get_avatar(bot_member) # Build the embed fields = [ {"name":"Members","value":member_count,"inline":True}, {"name":"Servers","value":guild_count,"inline":True}, {"name":"Commands","value":command_count + " (in {})".format(cog_count),"inline":True}, {"name":"Created","value":created_at,"inline":True}, {"name":"Owners","value":owners,"inline":True}, {"name":"Prefixes","value":prefix,"inline":True}, {"name":"Shard Count","value":self.bot.shard_count,"inline":True} ] if isinstance(bot_member,discord.Member): fields.append({"name":"Joined","value":joined_at,"inline":True}) # Get status status_text = ":green_heart:" if bot_member.status == discord.Status.offline: status_text = ":black_heart:" elif bot_member.status == discord.Status.dnd: status_text = ":heart:" elif bot_member.status == discord.Status.idle: status_text = ":yellow_heart:" fields.append({"name":"Status","value":status_text,"inline":True}) if bot_member.activity and bot_member.activity.name: play_list = [ "Playing", "Streaming", "Listening to", "Watching" ] try: play_string = play_list[bot_member.activity.type] except: play_string = "Playing" fields.append({"name":play_string,"value":str(bot_member.activity.name),"inline":True}) if bot_member.activity.type == 1: # Add the URL too fields.append({"name":"Stream URL","value":"[Watch Now]({})".format(bot_member.activity.url),"inline":True}) # Update the embed await Message.Embed( title=DisplayName.name(bot_member) + " Info", color=color, description="Current Bot Information", fields=fields, thumbnail=avatar ).edit(ctx, message) @commands.command(pass_context=True) async def ping(self, ctx): """Feeling lonely?""" before_typing = time.monotonic() await ctx.trigger_typing() after_typing = time.monotonic() ms = int((after_typing - before_typing) * 1000) msg = '*{}*, ***PONG!*** (~{}ms)'.format(ctx.message.author.mention, ms) await ctx.send(msg,allowed_mentions=discord.AllowedMentions.all()) @commands.command(pass_context=True) async def nickname(self, ctx, *, name : str = None): """Set the bot's nickname (admin-only).""" if not await Utils.is_admin_reply(ctx): return # Let's get the bot's member in the current server botName = "{}#{}".format(self.bot.user.name, self.bot.user.discriminator) botMember = ctx.message.guild.get_member_named(botName) await botMember.edit(nick=name) @commands.command(pass_context=True) async def hostinfo(self, ctx): """List info about the bot's host environment.""" message = await ctx.channel.send('Gathering info...') # cpuCores = psutil.cpu_count(logical=False) # cpuThred = psutil.cpu_count() cpuThred = os.cpu_count() cpuUsage = psutil.cpu_percent(interval=1) memStats = psutil.virtual_memory() memPerc = memStats.percent memUsed = memStats.used memTotal = memStats.total memUsedGB = "{0:.1f}".format(((memUsed / 1024) / 1024) / 1024) memTotalGB = "{0:.1f}".format(((memTotal/1024)/1024)/1024) currentOS = platform.platform() system = platform.system() release = platform.release() version = platform.version() processor = platform.processor() botMember = DisplayName.memberForID(self.bot.user.id, ctx.message.guild) botName = DisplayName.name(botMember) currentTime = int(time.time()) timeString = ReadableTime.getReadableTimeBetween(self.startTime, currentTime) pythonMajor = sys.version_info.major pythonMinor = sys.version_info.minor pythonMicro = sys.version_info.micro pythonRelease = sys.version_info.releaselevel pyBit = struct.calcsize("P") * 8 process = subprocess.Popen(['git', 'rev-parse', '--short', 'HEAD'], shell=False, stdout=subprocess.PIPE) git_head_hash = process.communicate()[0].strip() threadString = 'thread' if not cpuThred == 1: threadString += 's' msg = '***{}\'s*** **Home:**\n'.format(botName) msg += '```\n' msg += 'OS : {}\n'.format(currentOS) if not self.settings.getGlobalStat("HideHostname",False): msg += 'Hostname : {}\n'.format(platform.node()) msg += 'Language : Python {}.{}.{} {} ({} bit)\n'.format(pythonMajor, pythonMinor, pythonMicro, pythonRelease, pyBit) msg += 'Commit : {}\n\n'.format(git_head_hash.decode("utf-8")) msg += ProgressBar.center('{}% of {} {}'.format(cpuUsage, cpuThred, threadString), 'CPU') + '\n' msg += ProgressBar.makeBar(int(round(cpuUsage))) + "\n\n" msg += ProgressBar.center('{} ({}%) of {}GB used'.format(memUsedGB, memPerc, memTotalGB), 'RAM') + '\n' msg += ProgressBar.makeBar(int(round(memPerc))) + "\n\n" msg += '{} uptime```'.format(timeString) await message.edit(content=msg) @commands.command() async def hidehostname(self, ctx, *, yes_no = None): """Queries or turns on/off hostname hiding in the hostinfo command (owner-only).""" if not await Utils.is_owner_reply(ctx): return await ctx.send(Utils.yes_no_setting( ctx, "Hostname hiding in `hostinfo`".format(ctx.prefix), "HideHostname", yes_no, default=False, is_global=True )) @commands.command(pass_context=True) async def getimage(self, ctx, *, image): """Tests downloading - owner only""" # Only allow owner to modify the limits if not await Utils.is_owner_reply(ctx): return mess = await Message.Embed(title="Test", description="Downloading file...").send(ctx) file_path = await GetImage.download(image) mess = await Message.Embed(title="Test", description="Uploading file...").edit(ctx, mess) await Message.EmbedText(title="Image", file=file_path).edit(ctx, mess) GetImage.remove(file_path) @commands.command(pass_context=True) async def speedtest(self, ctx): """Run a network speed test (owner only).""" if not await Utils.is_owner_reply(ctx): return message = await ctx.send('Running speed test...') try: st = speedtest.Speedtest() st.get_best_server() l = asyncio.get_event_loop() msg = '**Speed Test Results:**\n' msg += '```\n' await message.edit(content="Running speed test...\n- Downloading...") d = await self.bot.loop.run_in_executor(None, st.download) msg += ' Ping: {} ms\nDownload: {} Mb/s\n'.format(round(st.results.ping, 2), round(d/1024/1024, 2)) await message.edit(content="Running speed test...\n- Downloading...\n- Uploading...") u = await self.bot.loop.run_in_executor(None, st.upload) msg += ' Upload: {} Mb/s```'.format(round(u/1024/1024, 2)) await message.edit(content=msg) except Exception as e: await message.edit(content="Speedtest Error: {}".format(str(e))) @commands.command(pass_context=True) async def adminunlim(self, ctx, *, yes_no : str = None): """Sets whether or not to allow unlimited xp to admins (bot-admin only).""" if not await Utils.is_bot_admin_reply(ctx): return await ctx.send(Utils.yes_no_setting(ctx,"Admin unlimited xp","AdminUnlimited",yes_no)) @commands.command(pass_context=True) async def basadmin(self, ctx, *, yes_no : str = None): """Sets whether or not to treat bot-admins as admins with regards to xp (admin only).""" if not await Utils.is_bot_admin_reply(ctx): return await ctx.send(Utils.yes_no_setting(ctx,"Bot-admin as admin","BotAdminAsAdmin",yes_no)) @commands.command(pass_context=True) async def joinpm(self, ctx, *, yes_no : str = None): """Sets whether or not to pm the rules to new users when they join (bot-admin only).""" if not await Utils.is_bot_admin_reply(ctx): return await ctx.send(Utils.yes_no_setting(ctx,"New user pm","JoinPM",yes_no)) @commands.command(pass_context=True) async def avatar(self, ctx, filename = None): """Sets the bot's avatar (owner only).""" if not await Utils.is_owner_reply(ctx): return if filename is None and not len(ctx.message.attachments): m = await ctx.send("Removing avatar...") try: await self.bot.user.edit(avatar=None) except discord.errors.HTTPException as e: return await m.edit(content="Looks like I can't do that right now. Try again later!") return await m.edit(content='Avatar removed!') # Check if attachment if filename == None: filename = ctx.message.attachments[0].url # Let's check if the "url" is actually a user test_user = DisplayName.memberForName(filename, ctx.guild) if test_user: # Got a user! filename = Utils.get_avatar(test_user) # Ensure string filename = str(filename) # Check if we created a temp folder for this image isTemp = False status = await ctx.send('Checking if url (and downloading if valid)...') # File name is *something* - let's first check it as a url, then a file extList = ["jpg", "jpeg", "png", "gif", "tiff", "tif", "webp"] if GetImage.get_ext(filename).lower() in extList: # URL has an image extension f = await GetImage.download(filename) if f: # we got a download - let's reset and continue filename = f isTemp = True if not os.path.isfile(filename): if not os.path.isfile('./{}'.format(filename)): return await status.edit(content='*{}* doesn\'t exist absolutely, or in my working directory.'.format(filename)) else: # Local file name filename = './{}'.format(filename) # File exists - check if image img = Image.open(filename) ext = img.format if not ext: # File isn't a valid image return await status.edit(content='*{}* isn\'t a valid image format.'.format(filename)) wasConverted = False # Is an image PIL understands if not ext.lower == "png": # Not a PNG - let's convert await status.edit(content='Converting to png...') filename = '{}.png'.format(filename) img.save(filename) wasConverted = True # We got it - crop and go from there w, h = img.size dw = dh = 0 if w > h: # Wide dw = int((w-h)/2) elif h > w: # Tall dh = int((h-w)/2) # Run the crop img.crop((dw, dh, w-dw, h-dh)).save(filename) await status.edit(content='Uploading and applying avatar...') with open(filename, 'rb') as f: newAvatar = f.read() try: await self.bot.user.edit(avatar=newAvatar) except discord.errors.HTTPException as e: return await status.edit(content="Looks like I can't do that right now. Try again later!") # Cleanup - try removing with shutil.rmtree, then with os.remove() await status.edit(content='Cleaning up...') if isTemp: GetImage.remove(filename) else: if wasConverted: os.remove(filename) await status.edit(content='Avatar set!') @commands.command() async def setname(self, ctx, *, name = None): """Sets the bot's name - may take awhile to reflect (owner only).""" if not await Utils.is_owner_reply(ctx): return if not name: return await ctx.send("Usage: `{}setname [new name]`".format(ctx.prefix)) if name == self.bot.user.name: return await ctx.send("That's already my name!") try: await self.bot.user.edit(username=name) except discord.errors.HTTPException as e: return await ctx.send(content="Looks like I can't do that right now. Try again later!") # Must have gone through - we'll state that it was updated, but may take awhile for the changes # to show up. return await ctx.send("Username updated - may take some time to show!") # Needs rewrite! @commands.command(pass_context=True) async def reboot(self, ctx): """Reboots the bot (owner only).""" if not await Utils.is_owner_reply(ctx): return # Save the return channel and flush settings self.settings.setGlobalStat("ReturnChannel",ctx.channel.id) # Flush settings asynchronously here await ctx.invoke(self.settings.flush) await ctx.send("Rebooting...") # Logout, stop the event loop, close the loop, quit try: task_list = asyncio.Task.all_tasks() except AttributeError: task_list = asyncio.all_tasks() for task in task_list: try: task.cancel() except: continue try: await self.bot.close() self.bot.loop.stop() self.bot.loop.close() except: pass # Kill this process os._exit(2) @commands.command(pass_context=True) async def shutdown(self, ctx): """Shuts down the bot (owner only).""" if not await Utils.is_owner_reply(ctx): return # Flush settings asynchronously here await ctx.invoke(self.settings.flush) await ctx.send("Shutting down...") # Logout, stop the event loop, close the loop, quit try: task_list = asyncio.Task.all_tasks() except AttributeError: task_list = asyncio.all_tasks() for task in task_list: try: task.cancel() except: continue try: await self.bot.close() self.bot.loop.stop() self.bot.loop.close() except: pass # Kill this process os._exit(3) @commands.command(pass_context=True) async def servers(self, ctx): """Lists the number of servers I'm connected to!""" await ctx.send("I am a part of *{}* server{}!".format(len(self.bot.guilds),"" if len(self.bot.guilds) == 1 else "s")) async def _update_status(self): # Helper method to update the status based on the server dict # Get ready - play game! game = self.settings.getGlobalStat("Game", None) url = self.settings.getGlobalStat("Stream", None) t = self.settings.getGlobalStat("Type", 0) status = self.settings.getGlobalStat("Status", None) # Set status if status == "2": s = discord.Status.idle elif status == "3": s = discord.Status.dnd elif status == "4": s = discord.Status.invisible else: # Online when in doubt s = discord.Status.online dgame = discord.Activity(name=game, url=url, type=t) if game else None await self.bot.change_presence(status=s, activity=dgame) @commands.command(pass_context=True) async def pres(self, ctx, playing_type="0", status_type="online", game=None, url=None): """Changes the bot's presence (owner-only). Playing type options are: 0. Playing (or None without game) 1. Streaming (requires valid twitch url) 2. Listening 3. Watching Status type options are: 1. Online 2. Idle 3. DnD 4. Invisible If any of the passed entries have spaces, they must be in quotes.""" if not await Utils.is_owner_reply(ctx): return # Check playing type play = None play_string = "" if playing_type.lower() in [ "0", "play", "playing" ]: play = 0 play_string = "Playing" elif playing_type.lower() in [ "1", "stream", "streaming" ]: play = 1 play_string = "Streaming" if url == None or not any("twitch.tv" in x.lower() for x in Utils.get_urls(url)): # Guess what - you failed!! :D return await ctx.send("You need a valid twitch.tv url to set a streaming status!") elif playing_type.lower() in [ "2", "listen", "listening" ]: play = 2 play_string = "Listening" elif playing_type.lower() in [ "3", "watch", "watching" ]: play = 3 play_string = "Watching" # Verify we got something if play == None: # NOooooooooaooOOooOOooope. return await ctx.send("Playing type is invalid!") # Clear the URL if we're not streaming if not play == 1: url = None # Check status type stat = None stat_string = "" if status_type.lower() in [ "1", "online", "here", "green" ]: stat = "1" stat_string = "Online" elif status_type.lower() in [ "2", "idle", "away", "gone", "yellow" ]: stat = "2" stat_string = "Idle" elif status_type.lower() in [ "3", "dnd", "do not disturb", "don't disturb", "busy", "red" ]: stat = "3" stat_string = "Do Not Disturb" elif status_type.lower() in [ "4", "offline", "invisible", "ghost", "gray", "black" ]: stat = "4" stat_string = "Invisible" # Verify we got something if stat == None: # OHMYGODHOWHARDISITTOFOLLOWDIRECTIONS?!?!? return await ctx.send("Status type is invalid!") # Here, we assume that everything is A OK. Peachy keen. # Set the shiz and move along self.settings.setGlobalStat("Game",game) self.settings.setGlobalStat("Stream",url) self.settings.setGlobalStat("Status",stat) self.settings.setGlobalStat("Type",play) # Actually update our shit await self._update_status() # Let's formulate a sexy little response concoction inline = True await Message.Embed( title="Presence Update", color=ctx.author, fields=[ { "name" : "Game", "value" : str(game), "inline" : inline }, { "name" : "Status", "value" : stat_string, "inline" : inline }, { "name" : "Type", "value" : play_string, "inline" : inline }, { "name" : "URL", "value" : str(url), "inline" : inline } ] ).send(ctx) @commands.command(pass_context=True) async def status(self, ctx, status = None): """Gets or sets the bot's online status (owner-only). Options are: 1. Online 2. Idle 3. DnD 4. Invisible""" if not await Utils.is_owner_reply(ctx): return if status == None: botmem = ctx.guild.get_member(self.bot.user.id) return await ctx.send("I'm currently set to *{}!*".format(botmem.status)) stat_string = "1" if status == "1" or status.lower() == "online": s = discord.Status.online stat_name = "online" elif status == "2" or status.lower() == "idle" or status.lower() == "away" or status.lower() == "afk": stat_string = "2" s = discord.Status.idle stat_name = "idle" elif status == "3" or status.lower() == "dnd" or status.lower() == "do not disturb" or status.lower() == "don't disturb": stat_string = "3" s = discord.Status.dnd stat_name = "dnd" elif status == "4" or status.lower() == "offline" or status.lower() == "invisible": stat_string = "4" s = discord.Status.invisible stat_name = "invisible" else: return await ctx.send("That is not a valid status.") self.settings.setGlobalStat("Status",stat_string) await self._update_status() await ctx.send("Status changed to *{}!*".format(stat_name)) async def set_status(self, ctx, status, status_name="Playing", status_type=0, status_url=None): # Only allow owner if not await Utils.is_owner_reply(ctx): return if status == status_url == None: self.settings.setGlobalStat('Game',None) self.settings.setGlobalStat('Stream',None) self.settings.setGlobalStat('Type',0) msg = 'Removing my {} status...'.format(status_name.lower()) message = await ctx.send(msg) await self._update_status() return await message.edit(content='{} status removed!'.format(status_name)) if status_type == 1: if not status: return await ctx.send("You need to provide a url if streaming!") if not any("twitch.tv" in x.lower() for x in Utils.get_urls(ctx)): return await ctx.send("You need to provide a valid twitch.tv url for streaming!") self.settings.setGlobalStat('Game',status) self.settings.setGlobalStat('Stream',status_url) self.settings.setGlobalStat('Type',status_type) msg = 'Setting my {} status to *{}*...'.format(status_name.lower(), status) message = await ctx.send(Utils.suppressed(ctx,msg)) await self._update_status() await message.edit(content='{} status set to **{}**{}!'.format(status_name,Utils.suppressed(ctx,status)," at `{}`".format(status_url) if status_url else "")) @commands.command(pass_context=True) async def playgame(self, ctx, *, game : str = None): """Sets the playing status of the bot (owner-only).""" await self.set_status(ctx,game,"Playing",0) @commands.command(pass_context=True) async def watchgame(self, ctx, *, game : str = None): """Sets the watching status of the bot (owner-only).""" await self.set_status(ctx,game,"Watching",3) @commands.command(pass_context=True) async def listengame(self, ctx, *, game : str = None): """Sets the listening status of the bot (owner-only).""" await self.set_status(ctx,game,"Listening",2) @commands.command(pass_context=True) async def streamgame(self, ctx, url = None, *, game : str = None): """Sets the streaming status of the bot, requires the url and the game (owner-only).""" await self.set_status(ctx,game,"Streaming",1,url) @commands.command(pass_context=True) async def setbotparts(self, ctx, *, parts : str = None): """Set the bot's parts - can be a url, formatted text, or nothing to clear.""" if not await Utils.is_owner_reply(ctx): return if not parts: parts = "" self.settings.setGlobalUserStat(self.bot.user, "Parts", parts) msg = '*{}\'s* parts have been set to:\n{}'.format(DisplayName.serverNick(self.bot.user, ctx.guild), parts) await ctx.send(Utils.suppressed(ctx,msg)) @commands.command(pass_context=True) async def source(self, ctx): """Link the github source.""" source = "https://github.com/corpnewt/CorpBot.py" msg = '**My insides are located at:**\n\n{}'.format(source) await ctx.send(msg) @commands.command(pass_context=True) async def cloc(self, ctx): """Outputs the total count of lines of code in the currently installed repo.""" # Script pulled and edited from https://github.com/kyco/python-count-lines-of-code/blob/python3/cloc.py message = await Message.EmbedText(title="Shuffling papers...", color=ctx.author).send(ctx) bot_member = self.bot.user if not ctx.guild else ctx.guild.get_member(self.bot.user.id) # Get our current working directory - should be the bot's home path = os.getcwd() # Set up some lists extensions = [] code_count = [] ext_dict = { "py":"Python (.py)", "bat":"Windows Batch (.bat)", "sh":"Shell Script (.sh)", "command":"Command Script (.command)"} # Get the extensions - include our include list extensions = self.get_extensions(path, list(ext_dict)) for run in extensions: extension = "*."+run temp = 0 for root, dir, files in os.walk(path): for items in fnmatch.filter(files, extension): value = root + "/" + items temp += sum(+1 for line in open(value, 'rb')) code_count.append(temp) # Set up our output fields = [{"name":ext_dict.get(extensions[x],extensions[x]),"value":"{:,} line{}".format(code_count[x],"" if code_count[x]==1 else "s")} for x in range(len(code_count))] return await Message.Embed( title="Counted Lines of Code", description="Some poor soul took the time to sloppily write the following to bring me life...", fields=fields, thumbnail=Utils.get_avatar(bot_member) ).edit(ctx,message) # Helper function to get extensions def get_extensions(self, path, excl): extensions = [] for root, dir, files in os.walk(path): for items in fnmatch.filter(files, "*"): temp_extensions = items.rfind(".") ext = items[temp_extensions+1:] if ext not in extensions: if ext in excl: extensions.append(ext) return extensions
""" Simple RAW image processing module""" import sys import os import scipy from scipy import signal import numpy as np from numpy.lib.stride_tricks import as_strided import rawpy """ Process RAW file into a image file. Example usage: raw = read("sample.ARW") rgb = process(raw) write(rgb, "output.ARW") """ def read(filename): """ Read RAW data from specified file. Currently supported formats are ARW (Sony RAW format) JPEG with Raspberry Pi V2.1 camera RAW :param filename: path to the target RAW file """ return rawpy.imread(filename) def check_functions(filename): """ Check what functions to be enabled based on filename""" white_level = 1024 shading_enable = True defect_correction_enable = True noise_parameters = (8, 2, 246) wbg_norm = 1 extension = os.path.splitext(filename)[1] if extension in (".ARW", ".arw"): shading_enable = False defect_correction_enable = False white_level = 8192 noise_parameters = (8, 0.2, 25) wbg_norm = 1024 return (shading_enable, defect_correction_enable, white_level, wbg_norm, noise_parameters) DEFALT_MATRIX = (1024, 0, 0, 0, 1024, 0, 0, 0, 1024) DEFALT_TONE = ((0, 64, 128, 192, 256), (0, 64, 128, 192, 256)) def process(filename, output_filename, color_matrix=DEFALT_MATRIX, tone_curve=DEFALT_TONE): """ This processes RAW data that was read by read() method. Must be called after read() operation. No error is checked. """ shading_enable, defect_crrection_enable, white_level, wbg_norm, noise_param = check_functions(filename) raw = read(filename) raw_array = get_raw_array(raw) raw_array = black_level_correction(raw_array, raw.black_level_per_channel, raw.raw_pattern) if defect_crrection_enable: raw_array = defect_crrection(raw_array) if shading_enable: raw_array = lens_shading_correction(raw_array, LSC_DEFAULT) raw_array = white_balance_Bayer(raw_array, raw.camera_whitebalance, wbg_norm, raw.raw_pattern) rgb_array = advanced_demosaic(raw_array, raw.raw_pattern) del raw_array, raw rgb_array = noise_filter(rgb_array, noise_param[0], noise_param[1], noise_param[2]) rgb_array = color_correction_matrix(rgb_array, color_matrix) rgb_array = gamma_correction(rgb_array/white_level, 2.2) rgb_array = edge_correction(rgb_array, 2, 0.25, 1, 0.25) rgb_array = tone_curve_correction(rgb_array, tone_curve[0], tone_curve[1]) write(rgb_array, output_filename) def get_raw_array(raw): """ convert raw_img into numpy array""" h, w = raw.sizes.raw_height, raw.sizes.raw_width raw_array = np.array(raw.raw_image).reshape((h, w)).astype('float') return raw_array def black_level_correction(raw_array, black_level_per_channel, bayer_pattern): # rearrange black level black_level = [0] * 4 black_level[bayer_pattern[0, 0]] = black_level_per_channel[bayer_pattern[0, 0]] black_level[bayer_pattern[0, 1]] = black_level_per_channel[bayer_pattern[0, 1]] black_level[bayer_pattern[1, 0]] = black_level_per_channel[bayer_pattern[1, 0]] black_level[bayer_pattern[1, 1]] = black_level_per_channel[bayer_pattern[1, 1]] blc_raw = raw_array.copy() blc_raw[0::2, 0::2] -= black_level[0] blc_raw[0::2, 1::2] -= black_level[1] blc_raw[1::2, 0::2] -= black_level[2] blc_raw[1::2, 1::2] -= black_level[3] return blc_raw def defect_crrection(raw_array): dpc_raw = raw_array.copy() footprint = np.ones((5, 5)) footprint[2, 2] = 0 for (yo, xo) in ((0, 0), (1, 0), (0, 1), (1, 1)): single_channel = dpc_raw[yo::2, xo::2] flt = np.array([[0, 1, 0], [1, 0, 1], [0, 1, 0]]) / 4 average = scipy.signal.convolve2d(single_channel, flt, mode='same') local_max = scipy.ndimage.filters.maximum_filter(single_channel, footprint=footprint, mode='mirror') local_min = scipy.ndimage.filters.minimum_filter(single_channel, footprint=footprint, mode='mirror') threshold = 16 mask = (single_channel < local_min - threshold) + (single_channel > local_max + threshold) single_channel[mask] = average[mask] return dpc_raw LSC_DEFAULT = [np.array([6.07106808e-07, 9.60556906e-01]), np.array([6.32044369e-07, 9.70694361e-01]), np.array([6.28455183e-07, 9.72493898e-01]), np.array([9.58743579e-07, 9.29427169e-01])] def lens_shading_correction(raw, coef): """ Apply lens shading correction to Bayer input (raw) Parameter (coef) needs to be array type of coef[4][2] coef[color][0] is coefficient on 2nd order term. coef[color][1] is offset """ h, w = raw.shape gain_map = np.zeros((h, w)) center_y, center_x = h // 2, w // 2 x = np.arange(0, w) - center_x y = np.arange(0, h) - center_y xs, ys = np.meshgrid(x, y, sparse=True) r2 = ys * ys + xs * xs gain_map[::2, ::2] = r2[::2, ::2] * coef[0][0] + coef[0][1] gain_map[1::2, ::2] = r2[1::2, ::2] * coef[1][0] + coef[1][1] gain_map[::2, 1::2] = r2[::2, 1::2] * coef[2][0] + coef[2][1] gain_map[1::2, 1::2] = r2[1::2, 1::2] * coef[3][0] + coef[3][1] return raw * gain_map def preview_demosaic(raw_array, bayer_pattern): """ Very simple demosaic with down sampling for preview purpose""" h, w = raw_array.shape[0], raw_array.shape[1] shuffle = np.zeros((h // 2, w // 2, 4)) shuffle[:, :, bayer_pattern[0, 0]] += raw_array[0::2, 0::2] shuffle[:, :, bayer_pattern[0, 1]] += raw_array[0::2, 1::2] shuffle[:, :, bayer_pattern[1, 0]] += raw_array[1::2, 0::2] shuffle[:, :, bayer_pattern[1, 1]] += raw_array[1::2, 1::2] dms_img = np.zeros((h // 2, w // 2, 3)) dms_img[:, :, 0] = shuffle[:, :, 0] dms_img[:, :, 1] = (shuffle[:, :, 1] + shuffle[:, :, 3]) / 2 dms_img[:, :, 2] = shuffle[:, :, 2] return dms_img def simple_demosaic(raw, raw_array): """ Simple demosaic algorithm with linear interpolation """ h, w = raw_array.shape dms_img2 = np.zeros((h, w, 3)) green = raw_array.copy() green[(raw.raw_colors == 0) | (raw.raw_colors == 2)] = 0 g_flt = np.array([[0, 1 / 4, 0], [1 / 4, 1, 1 / 4], [0, 1 / 4, 0]]) dms_img2[:, :, 1] = signal.convolve2d(green, g_flt, boundary='symm', mode='same') red = raw_array.copy() red[raw.raw_colors != 0] = 0 rb_flt = np.array([[1 / 4, 1 / 2, 1 / 4], [1 / 2, 1, 1 / 2], [1 / 4, 1 / 2, 1 / 4]]) dms_img2[:, :, 0] = signal.convolve2d(red, rb_flt, boundary='symm', mode='same') blue = raw_array.copy() blue[raw.raw_colors != 2] = 0 rb_flt = np.array([[1 / 4, 1 / 2, 1 / 4], [1 / 2, 1, 1 / 2], [1 / 4, 1 / 2, 1 / 4]]) dms_img2[:, :, 2] = signal.convolve2d(blue, rb_flt, boundary='symm', mode='same') return dms_img2 def advanced_demosaic(dms_input, bayer_pattern): """ Demosaic algorithm in frequency domain """ hlpf = np.array([[1, 2, 3, 4, 3, 2, 1]]) / 16 vlpf = np.transpose(hlpf) hhpf = np.array([[-1, 2, -3, 4, -3, 2, -1]]) / 16 vhpf = np.transpose(hhpf) identity_filter = np.zeros((7, 7)) identity_filter[3, 3] = 1 # generate FIR filters to extract necessary components FC1 = np.matmul(vhpf, hhpf) FC2H = np.matmul(vlpf, hhpf) FC2V = np.matmul(vhpf, hlpf) FL = identity_filter - FC1 - FC2V - FC2H # f_C1 at 4 corners c1_mod = signal.convolve2d(dms_input, FC1, boundary='symm', mode='same') # f_C1^1 at wy = 0, wx = +Pi/-Pi c2h_mod = signal.convolve2d(dms_input, FC2H, boundary='symm', mode='same') # f_C1^1 at wy = +Pi/-Pi, wx = 0 c2v_mod = signal.convolve2d(dms_input, FC2V, boundary='symm', mode='same') # f_L at center f_L = signal.convolve2d(dms_input, FL, boundary='symm', mode='same') # Move c1 to the center by shifting by Pi in both x and y direction # f_c1 = c1 * (-1)^x * (-1)^y f_c1 = c1_mod.copy() f_c1[:, 1::2] *= -1 f_c1[1::2, :] *= -1 if bayer_pattern[0, 0] == 1 or bayer_pattern[0, 0] == 3: f_c1 *= -1 # Move c2a to the center by shifting by Pi in x direction, same for c2b in y direction c2h = c2h_mod.copy() c2h[:, 1::2] *= -1 if bayer_pattern[0, 0] == 2 or bayer_pattern[1, 0] == 2: c2h *= -1 c2v = c2v_mod.copy() c2v[1::2, :] *= -1 if bayer_pattern[0, 0] == 2 or bayer_pattern[0, 1] == 2: c2v *= -1 # f_c2 = (c2v_mod * x_mod + c2h_mod * y_mod) / 2 f_c2 = (c2v + c2h) / 2 # generate RGB channel using # [R, G, B] = [[1, 1, 2], [1, -1, 0], [1, 1, - 2]] x [L, C1, C2] height, width = dms_input.shape dms_img = np.zeros((height, width, 3)) dms_img[:, :, 0] = f_L + f_c1 + 2 * f_c2 dms_img[:, :, 1] = f_L - f_c1 dms_img[:, :, 2] = f_L + f_c1 - 2 * f_c2 return dms_img def white_balance_Bayer(raw_array, wbg, wbg_norm, bayer_pattern): """ Apply white balance to bayer input""" img_wb = raw_array.copy() img_wb[0::2, 0::2] *= wbg[bayer_pattern[0, 0]] / wbg_norm img_wb[0::2, 1::2] *= wbg[bayer_pattern[0, 1]] / wbg_norm img_wb[1::2, 0::2] *= wbg[bayer_pattern[1, 0]] / wbg_norm img_wb[1::2, 1::2] *= wbg[bayer_pattern[1, 1]] / wbg_norm return img_wb def noise_filter(rgb_array, coef=8, read_noise=2, shot_noise=246): """ Apply bilateral noise filter to RGB image""" h, w, _ = rgb_array.shape luma_img = rgb_array[:, :, 0] + rgb_array[:, :, 1] + rgb_array[:, :, 2] average = scipy.ndimage.filters.uniform_filter(luma_img, 5, mode='mirror') sigma_map = average * shot_noise + read_noise del average sigma_map[sigma_map < 1] = 1 sy, sx = sigma_map.strides sigma_tile = as_strided(sigma_map, strides=(sy, sx, 0, 0), shape=(h, w, 5, 5)) sigma_tile = sigma_tile[2:h-2, 2:w-2, :, :] del sigma_map sy, sx = luma_img.strides luma_tile = as_strided(luma_img, strides=(sy, sx, 0, 0), shape=(h, w, 5, 5)) luma_tile = luma_tile[2:h-2, 2:w-2, :, :] luma_box = as_strided(luma_img, strides=(sy, sx, sy, sx), shape=(h-4, w-4, 5, 5)) del luma_img diff = luma_box - luma_tile del luma_tile, luma_box diff = diff * diff weight = np.exp(-coef * diff / sigma_tile) del diff, sigma_tile weight_sum = weight.sum(axis=(2, 3)) sy, sx, sz, sw = weight.strides weight_extend = as_strided(weight, strides=(sy, sx, 0, sz, sw), shape=(h-4, w-4, 3, 5, 5)) del weight sy, sx = weight_sum.strides weight_sum_extend = as_strided(weight_sum, strides=(sy, sx, 0), shape=(h-4, w-4, 3)) del weight_sum sy, sx, sz = rgb_array.strides img_boxes = as_strided(rgb_array, strides=(sy, sx, sz, sy, sx), shape=(h-4, w-4, 3, 5, 5)) img_flt = (weight_extend * img_boxes).sum(axis=(3, 4)) / weight_sum_extend return img_flt def color_correction_matrix(rgb_array, color_matrix): """ Apply color correction matrix to RGB array""" img_ccm = np.zeros_like(rgb_array) ccm = np.array(color_matrix).reshape((3, 3)) norm = ccm.sum(axis=1).mean() for c in (0, 1, 2): img_ccm[:, :, c] = ccm[c, 0] * rgb_array[:, :, 0] + \ ccm[c, 1] * rgb_array[:, :, 1] + \ ccm[c, 2] * rgb_array[:, :, 2] return img_ccm / norm def gamma_correction(rgb_array, gamma_coef): """ Apply gamma correction to RGB image""" img_gamma = rgb_array.copy() img_gamma[img_gamma < 0] = 0 img_gamma = np.power(img_gamma, 1/gamma_coef) return img_gamma def apply_matrix(input_array, matrix): img_out = np.zeros_like(input_array) for c in (0, 1, 2): img_out[:, :, c] = matrix[c, 0] * input_array[:, :, 0] + \ matrix[c, 1] * input_array[:, :, 1] + \ matrix[c, 2] * input_array[:, :, 2] return img_out RGB_TO_YCBCR = np.array([[0.299, 0.587, 0.144], [-0.168736, -0.331264, 0.5], [0.5, -0.418688, -0.081312]]) def edge_correction(rgb_array, sigma1=2, coef1=0.25, sigma2=1, coef2=0.25): """ Edge correction for RGB input""" img_rgb = rgb_array.copy() * 256 img_rgb[img_rgb < 0] = 0 img_rgb[img_rgb > 255] = 255 img_ycbcr = apply_matrix(img_rgb, RGB_TO_YCBCR) luma = img_ycbcr[:, :, 0] unsharpen1 = scipy.ndimage.gaussian_filter(luma, sigma=sigma1) unsharpen2 = scipy.ndimage.gaussian_filter(luma, sigma=sigma2) sharpen = luma + coef1 * (luma - unsharpen1) + coef2 * (luma - unsharpen2) img_ycbcr[:, :, 0] = sharpen ycbcr2rgb = np.linalg.inv(RGB_TO_YCBCR) img_shp_rgb = apply_matrix(img_ycbcr, ycbcr2rgb) / 256 img_shp_rgb[img_shp_rgb < 0] = 0 img_shp_rgb[img_shp_rgb > 1] = 1 return img_shp_rgb def tone_curve_correction(img_rgb, xs=(0, 64, 128, 192, 256), ys=(0, 64, 128, 192, 256)): func = scipy.interpolate.splrep(xs, ys) img_ycbcr = apply_matrix(img_rgb * 256, RGB_TO_YCBCR) img_ycbcr[:, :, 0] = scipy.interpolate.splev(img_ycbcr[:, :, 0], func) ycbcr2rgb = np.linalg.inv(RGB_TO_YCBCR) img_rgb_out = apply_matrix(img_ycbcr, ycbcr2rgb) return img_rgb_out / 256 def write(rgb_image, output_filename): """ Write the processed RGB image to a specified file as PNG format. Thsi must be called after process(). No error is checked. :param output_filename: path to the output file. Extension must be png. """ import imageio outimg = rgb_image.copy() * 256 outimg[outimg < 0] = 0 outimg[outimg > 255] = 255 imageio.imwrite(output_filename, outimg.astype('uint8')) def main(argv): """ main function """ if (len(argv) < 2): print("Usage: {} input_filename [output_filename] \"color_matrix\" \"tone_x\" \"tone_y\"".format(argv[0])) print("\tDefault output_filename is output.png") print("\tDefault matrix is identity matrix \"1024, 0, 0, 0, 1024, 0, 0, 0, 1024\"") print("\tDefault tone curve is identity function \"0, 128, 256] [0, 128, 256\"") print("\tExample: python3 {} sample.ARW sample.png \"1141, -205, 88, -52, 1229, -154, 70, -225, 1179\" \"0, 72, 128, 200, 256\" \"0, 56, 128, 220, 256\"".format(argv[0])) print("\tSupported RAW format is ARW (Sony RAW) and Raspberry Pi (embedded in JPEG)") print("\tSupported output format is PNG only") return filename = argv[1] output_filename = "output.png" color_matrix = [1024, 0, 0, 0, 1024, 0, 0, 0, 1024] tone_curve = [(0, 64, 128, 192, 256), (0, 64, 128, 192, 256)] if len(argv) > 2: output_filename = argv[2] if len(argv) > 3: color_matrix = [int(value) for value in (argv[3]).split(',')] if len(argv) > 4: tone_curve[0] = [int(value) for value in (argv[4]).split(',')] if len(argv) > 5: tone_curve[1] = [int(value) for value in (argv[5]).split(',')] process(filename, output_filename, color_matrix, tone_curve) if __name__ == "__main__": main(sys.argv)
/* * Wi-Fi Direct - P2P Invitation procedure * Copyright (c) 2010, Atheros Communications * * This software may be distributed under the terms of the BSD license. * See README for more details. */ #include "includes.h" #include "common.h" #include "common/ieee802_11_defs.h" #include "common/wpa_ctrl.h" #include "p2p_i.h" #include "p2p.h" static struct wpabuf * p2p_build_invitation_req(struct p2p_data *p2p, struct p2p_device *peer, const u8 *go_dev_addr, int dev_pw_id) { struct wpabuf *buf; u8 *len; const u8 *dev_addr; size_t extra = 0; #ifdef CONFIG_WIFI_DISPLAY struct wpabuf *wfd_ie = p2p->wfd_ie_invitation; if (wfd_ie && p2p->inv_role == P2P_INVITE_ROLE_ACTIVE_GO) { size_t i; for (i = 0; i < p2p->num_groups; i++) { struct p2p_group *g = p2p->groups[i]; struct wpabuf *ie; if (os_memcmp(p2p_group_get_interface_addr(g), p2p->inv_bssid, ETH_ALEN) != 0) continue; ie = p2p_group_get_wfd_ie(g); if (ie) { wfd_ie = ie; break; } } } if (wfd_ie) extra = wpabuf_len(wfd_ie); #endif /* CONFIG_WIFI_DISPLAY */ if (p2p->vendor_elem && p2p->vendor_elem[VENDOR_ELEM_P2P_INV_REQ]) extra += wpabuf_len(p2p->vendor_elem[VENDOR_ELEM_P2P_INV_REQ]); buf = wpabuf_alloc(1000 + extra); if (buf == NULL) return NULL; peer->dialog_token++; if (peer->dialog_token == 0) peer->dialog_token = 1; p2p_buf_add_public_action_hdr(buf, P2P_INVITATION_REQ, peer->dialog_token); len = p2p_buf_add_ie_hdr(buf); if (p2p->inv_role == P2P_INVITE_ROLE_ACTIVE_GO || !p2p->inv_persistent) p2p_buf_add_config_timeout(buf, 0, 0); else p2p_buf_add_config_timeout(buf, p2p->go_timeout, p2p->client_timeout); p2p_buf_add_invitation_flags(buf, p2p->inv_persistent ? P2P_INVITATION_FLAGS_TYPE : 0); if (p2p->inv_role != P2P_INVITE_ROLE_CLIENT || !(peer->flags & P2P_DEV_NO_PREF_CHAN)) p2p_buf_add_operating_channel(buf, p2p->cfg->country, p2p->op_reg_class, p2p->op_channel); if (p2p->inv_bssid_set) p2p_buf_add_group_bssid(buf, p2p->inv_bssid); p2p_buf_add_channel_list(buf, p2p->cfg->country, &p2p->channels); if (go_dev_addr) dev_addr = go_dev_addr; else if (p2p->inv_role == P2P_INVITE_ROLE_CLIENT) dev_addr = peer->info.p2p_device_addr; else dev_addr = p2p->cfg->dev_addr; p2p_buf_add_group_id(buf, dev_addr, p2p->inv_ssid, p2p->inv_ssid_len); p2p_buf_add_device_info(buf, p2p, peer); p2p_buf_update_ie_hdr(buf, len); p2p_buf_add_pref_channel_list(buf, p2p->pref_freq_list, p2p->num_pref_freq); #ifdef CONFIG_WIFI_DISPLAY if (wfd_ie) wpabuf_put_buf(buf, wfd_ie); #endif /* CONFIG_WIFI_DISPLAY */ if (p2p->vendor_elem && p2p->vendor_elem[VENDOR_ELEM_P2P_INV_REQ]) wpabuf_put_buf(buf, p2p->vendor_elem[VENDOR_ELEM_P2P_INV_REQ]); if (dev_pw_id >= 0) { /* WSC IE in Invitation Request for NFC static handover */ p2p_build_wps_ie(p2p, buf, dev_pw_id, 0); } return buf; } static struct wpabuf * p2p_build_invitation_resp(struct p2p_data *p2p, struct p2p_device *peer, u8 dialog_token, u8 status, const u8 *group_bssid, u8 reg_class, u8 channel, struct p2p_channels *channels) { struct wpabuf *buf; u8 *len; size_t extra = 0; #ifdef CONFIG_WIFI_DISPLAY struct wpabuf *wfd_ie = p2p->wfd_ie_invitation; if (wfd_ie && group_bssid) { size_t i; for (i = 0; i < p2p->num_groups; i++) { struct p2p_group *g = p2p->groups[i]; struct wpabuf *ie; if (os_memcmp(p2p_group_get_interface_addr(g), group_bssid, ETH_ALEN) != 0) continue; ie = p2p_group_get_wfd_ie(g); if (ie) { wfd_ie = ie; break; } } } if (wfd_ie) extra = wpabuf_len(wfd_ie); #endif /* CONFIG_WIFI_DISPLAY */ if (p2p->vendor_elem && p2p->vendor_elem[VENDOR_ELEM_P2P_INV_RESP]) extra += wpabuf_len(p2p->vendor_elem[VENDOR_ELEM_P2P_INV_RESP]); buf = wpabuf_alloc(1000 + extra); if (buf == NULL) return NULL; p2p_buf_add_public_action_hdr(buf, P2P_INVITATION_RESP, dialog_token); len = p2p_buf_add_ie_hdr(buf); p2p_buf_add_status(buf, status); p2p_buf_add_config_timeout(buf, 0, 0); /* FIX */ if (reg_class && channel) p2p_buf_add_operating_channel(buf, p2p->cfg->country, reg_class, channel); if (group_bssid) p2p_buf_add_group_bssid(buf, group_bssid); if (channels) p2p_buf_add_channel_list(buf, p2p->cfg->country, channels); p2p_buf_update_ie_hdr(buf, len); #ifdef CONFIG_WIFI_DISPLAY if (wfd_ie) wpabuf_put_buf(buf, wfd_ie); #endif /* CONFIG_WIFI_DISPLAY */ if (p2p->vendor_elem && p2p->vendor_elem[VENDOR_ELEM_P2P_INV_RESP]) wpabuf_put_buf(buf, p2p->vendor_elem[VENDOR_ELEM_P2P_INV_RESP]); return buf; } void p2p_process_invitation_req(struct p2p_data *p2p, const u8 *sa, const u8 *data, size_t len, int rx_freq) { struct p2p_device *dev; struct p2p_message msg; struct wpabuf *resp = NULL; u8 status = P2P_SC_FAIL_INFO_CURRENTLY_UNAVAILABLE; int freq; int go = 0; u8 group_bssid[ETH_ALEN], *bssid; int op_freq = 0; u8 reg_class = 0, channel = 0; struct p2p_channels all_channels, intersection, *channels = NULL; int persistent; os_memset(group_bssid, 0, sizeof(group_bssid)); p2p_dbg(p2p, "Received Invitation Request from " MACSTR " (freq=%d)", MAC2STR(sa), rx_freq); if (p2p_parse(data, len, &msg)) return; dev = p2p_get_device(p2p, sa); if (dev == NULL || (dev->flags & P2P_DEV_PROBE_REQ_ONLY)) { p2p_dbg(p2p, "Invitation Request from unknown peer " MACSTR, MAC2STR(sa)); if (p2p_add_device(p2p, sa, rx_freq, NULL, 0, data + 1, len - 1, 0)) { p2p_dbg(p2p, "Invitation Request add device failed " MACSTR, MAC2STR(sa)); status = P2P_SC_FAIL_INFO_CURRENTLY_UNAVAILABLE; goto fail; } dev = p2p_get_device(p2p, sa); if (dev == NULL) { p2p_dbg(p2p, "Reject Invitation Request from unknown peer " MACSTR, MAC2STR(sa)); status = P2P_SC_FAIL_INFO_CURRENTLY_UNAVAILABLE; goto fail; } } if (!msg.group_id || !msg.channel_list) { p2p_dbg(p2p, "Mandatory attribute missing in Invitation Request from " MACSTR, MAC2STR(sa)); status = P2P_SC_FAIL_INVALID_PARAMS; goto fail; } if (msg.invitation_flags) persistent = *msg.invitation_flags & P2P_INVITATION_FLAGS_TYPE; else { /* Invitation Flags is a mandatory attribute starting from P2P * spec 1.06. As a backwards compatibility mechanism, assume * the request was for a persistent group if the attribute is * missing. */ p2p_dbg(p2p, "Mandatory Invitation Flags attribute missing from Invitation Request"); persistent = 1; } p2p_channels_union(&p2p->cfg->channels, &p2p->cfg->cli_channels, &all_channels); if (p2p_peer_channels_check(p2p, &all_channels, dev, msg.channel_list, msg.channel_list_len) < 0) { p2p_dbg(p2p, "No common channels found"); status = P2P_SC_FAIL_NO_COMMON_CHANNELS; goto fail; } p2p_channels_dump(p2p, "own channels", &p2p->cfg->channels); p2p_channels_dump(p2p, "own client channels", &all_channels); p2p_channels_dump(p2p, "peer channels", &dev->channels); p2p_channels_intersect(&all_channels, &dev->channels, &intersection); p2p_channels_dump(p2p, "intersection", &intersection); if (p2p->cfg->invitation_process) { status = p2p->cfg->invitation_process( p2p->cfg->cb_ctx, sa, msg.group_bssid, msg.group_id, msg.group_id + ETH_ALEN, msg.group_id_len - ETH_ALEN, &go, group_bssid, &op_freq, persistent, &intersection, msg.dev_password_id_present ? msg.dev_password_id : -1); } if (go) { p2p_channels_intersect(&p2p->cfg->channels, &dev->channels, &intersection); p2p_channels_dump(p2p, "intersection(GO)", &intersection); if (intersection.reg_classes == 0) { p2p_dbg(p2p, "No common channels found (GO)"); status = P2P_SC_FAIL_NO_COMMON_CHANNELS; goto fail; } } if (op_freq) { p2p_dbg(p2p, "Invitation processing forced frequency %d MHz", op_freq); if (p2p_freq_to_channel(op_freq, &reg_class, &channel) < 0) { p2p_dbg(p2p, "Unknown forced freq %d MHz from invitation_process()", op_freq); status = P2P_SC_FAIL_NO_COMMON_CHANNELS; goto fail; } if (!p2p_channels_includes(&intersection, reg_class, channel)) { p2p_dbg(p2p, "forced freq %d MHz not in the supported channels interaction", op_freq); status = P2P_SC_FAIL_NO_COMMON_CHANNELS; goto fail; } if (status == P2P_SC_SUCCESS) channels = &intersection; } else { p2p_dbg(p2p, "No forced channel from invitation processing - figure out best one to use"); /* Default to own configuration as a starting point */ p2p->op_reg_class = p2p->cfg->op_reg_class; p2p->op_channel = p2p->cfg->op_channel; p2p_dbg(p2p, "Own default op_class %d channel %d", p2p->op_reg_class, p2p->op_channel); /* Use peer preference if specified and compatible */ if (msg.operating_channel) { int req_freq; req_freq = p2p_channel_to_freq( msg.operating_channel[3], msg.operating_channel[4]); p2p_dbg(p2p, "Peer operating channel preference: %d MHz", req_freq); if (req_freq > 0 && p2p_channels_includes(&intersection, msg.operating_channel[3], msg.operating_channel[4])) { p2p->op_reg_class = msg.operating_channel[3]; p2p->op_channel = msg.operating_channel[4]; p2p_dbg(p2p, "Use peer preference op_class %d channel %d", p2p->op_reg_class, p2p->op_channel); } else { p2p_dbg(p2p, "Cannot use peer channel preference"); } } /* Reselect the channel only for the case of the GO */ if (go && !p2p_channels_includes(&intersection, p2p->op_reg_class, p2p->op_channel)) { p2p_dbg(p2p, "Initially selected channel (op_class %d channel %d) not in channel intersection - try to reselect", p2p->op_reg_class, p2p->op_channel); p2p_reselect_channel(p2p, &intersection); p2p_dbg(p2p, "Re-selection result: op_class %d channel %d", p2p->op_reg_class, p2p->op_channel); if (!p2p_channels_includes(&intersection, p2p->op_reg_class, p2p->op_channel)) { p2p_dbg(p2p, "Peer does not support selected operating channel (reg_class=%u channel=%u)", p2p->op_reg_class, p2p->op_channel); status = P2P_SC_FAIL_NO_COMMON_CHANNELS; goto fail; } } else if (go && !(dev->flags & P2P_DEV_FORCE_FREQ) && !p2p->cfg->cfg_op_channel) { p2p_dbg(p2p, "Try to reselect channel selection with peer information received; previously selected op_class %u channel %u", p2p->op_reg_class, p2p->op_channel); p2p_reselect_channel(p2p, &intersection); } /* * Use the driver preferred frequency list extension if * supported. */ p2p_check_pref_chan(p2p, go, dev, &msg); op_freq = p2p_channel_to_freq(p2p->op_reg_class, p2p->op_channel); if (op_freq < 0) { p2p_dbg(p2p, "Unknown operational channel (country=%c%c reg_class=%u channel=%u)", p2p->cfg->country[0], p2p->cfg->country[1], p2p->op_reg_class, p2p->op_channel); status = P2P_SC_FAIL_NO_COMMON_CHANNELS; goto fail; } p2p_dbg(p2p, "Selected operating channel - %d MHz", op_freq); if (status == P2P_SC_SUCCESS) { reg_class = p2p->op_reg_class; channel = p2p->op_channel; channels = &intersection; } } fail: if (go && status == P2P_SC_SUCCESS && !is_zero_ether_addr(group_bssid)) bssid = group_bssid; else bssid = NULL; resp = p2p_build_invitation_resp(p2p, dev, msg.dialog_token, status, bssid, reg_class, channel, channels); if (resp == NULL) goto out; if (rx_freq > 0) freq = rx_freq; else freq = p2p_channel_to_freq(p2p->cfg->reg_class, p2p->cfg->channel); if (freq < 0) { p2p_dbg(p2p, "Unknown regulatory class/channel"); goto out; } /* * Store copy of invitation data to be used when processing TX status * callback for the Acton frame. */ os_memcpy(p2p->inv_sa, sa, ETH_ALEN); if (msg.group_bssid) { os_memcpy(p2p->inv_group_bssid, msg.group_bssid, ETH_ALEN); p2p->inv_group_bssid_ptr = p2p->inv_group_bssid; } else p2p->inv_group_bssid_ptr = NULL; if (msg.group_id) { if (msg.group_id_len - ETH_ALEN <= SSID_MAX_LEN) { os_memcpy(p2p->inv_ssid, msg.group_id + ETH_ALEN, msg.group_id_len - ETH_ALEN); p2p->inv_ssid_len = msg.group_id_len - ETH_ALEN; } os_memcpy(p2p->inv_go_dev_addr, msg.group_id, ETH_ALEN); } else { p2p->inv_ssid_len = 0; os_memset(p2p->inv_go_dev_addr, 0, ETH_ALEN); } p2p->inv_status = status; p2p->inv_op_freq = op_freq; p2p->pending_action_state = P2P_PENDING_INVITATION_RESPONSE; if (p2p_send_action(p2p, freq, sa, p2p->cfg->dev_addr, p2p->cfg->dev_addr, wpabuf_head(resp), wpabuf_len(resp), 200) < 0) { p2p_dbg(p2p, "Failed to send Action frame"); } out: wpabuf_free(resp); p2p_parse_free(&msg); } void p2p_process_invitation_resp(struct p2p_data *p2p, const u8 *sa, const u8 *data, size_t len) { struct p2p_device *dev; struct p2p_message msg; struct p2p_channels intersection, *channels = NULL; p2p_dbg(p2p, "Received Invitation Response from " MACSTR, MAC2STR(sa)); dev = p2p_get_device(p2p, sa); if (dev == NULL) { p2p_dbg(p2p, "Ignore Invitation Response from unknown peer " MACSTR, MAC2STR(sa)); p2p->cfg->send_action_done(p2p->cfg->cb_ctx); return; } if (dev != p2p->invite_peer) { p2p_dbg(p2p, "Ignore unexpected Invitation Response from peer " MACSTR, MAC2STR(sa)); p2p->cfg->send_action_done(p2p->cfg->cb_ctx); return; } if (p2p_parse(data, len, &msg)) { p2p->cfg->send_action_done(p2p->cfg->cb_ctx); return; } if (!msg.status) { p2p_dbg(p2p, "Mandatory Status attribute missing in Invitation Response from " MACSTR, MAC2STR(sa)); p2p_parse_free(&msg); p2p->cfg->send_action_done(p2p->cfg->cb_ctx); return; } /* * We should not really receive a replayed response twice since * duplicate frames are supposed to be dropped. However, not all drivers * do that for pre-association frames. We did not use to verify dialog * token matches for invitation response frames, but that check can be * safely used to drop a replayed response to the previous Invitation * Request in case the suggested operating channel was changed. This * allows a duplicated reject frame to be dropped with the assumption * that the real response follows after it. */ if (*msg.status == P2P_SC_FAIL_NO_COMMON_CHANNELS && p2p->retry_invite_req_sent && msg.dialog_token != dev->dialog_token) { p2p_dbg(p2p, "Unexpected Dialog Token %u (expected %u)", msg.dialog_token, dev->dialog_token); p2p_parse_free(&msg); return; } if (*msg.status == P2P_SC_FAIL_NO_COMMON_CHANNELS && p2p->retry_invite_req && p2p_channel_random_social(&p2p->cfg->channels, &p2p->op_reg_class, &p2p->op_channel) == 0) { p2p->retry_invite_req = 0; p2p->cfg->send_action_done(p2p->cfg->cb_ctx); p2p->cfg->stop_listen(p2p->cfg->cb_ctx); p2p_set_state(p2p, P2P_INVITE); p2p_dbg(p2p, "Resend Invitation Request setting op_class %u channel %u as operating channel", p2p->op_reg_class, p2p->op_channel); p2p->retry_invite_req_sent = 1; p2p_invite_send(p2p, p2p->invite_peer, p2p->invite_go_dev_addr, p2p->invite_dev_pw_id); p2p_parse_free(&msg); return; } p2p->cfg->send_action_done(p2p->cfg->cb_ctx); p2p->retry_invite_req = 0; if (!msg.channel_list && *msg.status == P2P_SC_SUCCESS) { p2p_dbg(p2p, "Mandatory Channel List attribute missing in Invitation Response from " MACSTR, MAC2STR(sa)); #ifdef CONFIG_P2P_STRICT p2p_parse_free(&msg); return; #endif /* CONFIG_P2P_STRICT */ /* Try to survive without peer channel list */ channels = &p2p->channels; } else if (!msg.channel_list) { /* Non-success cases are not required to include Channel List */ channels = &p2p->channels; } else if (p2p_peer_channels_check(p2p, &p2p->channels, dev, msg.channel_list, msg.channel_list_len) < 0) { p2p_dbg(p2p, "No common channels found"); p2p_parse_free(&msg); return; } else { p2p_channels_intersect(&p2p->channels, &dev->channels, &intersection); channels = &intersection; } if (p2p->cfg->invitation_result) { int peer_oper_freq = 0; int freq = p2p_channel_to_freq(p2p->op_reg_class, p2p->op_channel); if (freq < 0) freq = 0; if (msg.operating_channel) { peer_oper_freq = p2p_channel_to_freq( msg.operating_channel[3], msg.operating_channel[4]); if (peer_oper_freq < 0) peer_oper_freq = 0; } /* * Use the driver preferred frequency list extension if * supported. */ p2p_check_pref_chan(p2p, 0, dev, &msg); p2p->cfg->invitation_result(p2p->cfg->cb_ctx, *msg.status, msg.group_bssid, channels, sa, freq, peer_oper_freq); } p2p_parse_free(&msg); p2p_clear_timeout(p2p); p2p_set_state(p2p, P2P_IDLE); p2p->invite_peer = NULL; } int p2p_invite_send(struct p2p_data *p2p, struct p2p_device *dev, const u8 *go_dev_addr, int dev_pw_id) { struct wpabuf *req; int freq; freq = dev->listen_freq > 0 ? dev->listen_freq : dev->oper_freq; if (freq <= 0) freq = dev->oob_go_neg_freq; if (freq <= 0) { p2p_dbg(p2p, "No Listen/Operating frequency known for the peer " MACSTR " to send Invitation Request", MAC2STR(dev->info.p2p_device_addr)); return -1; } req = p2p_build_invitation_req(p2p, dev, go_dev_addr, dev_pw_id); if (req == NULL) return -1; if (p2p->state != P2P_IDLE) p2p_stop_listen_for_freq(p2p, freq); p2p_dbg(p2p, "Sending Invitation Request"); p2p_set_state(p2p, P2P_INVITE); p2p->pending_action_state = P2P_PENDING_INVITATION_REQUEST; p2p->invite_peer = dev; dev->invitation_reqs++; if (p2p_send_action(p2p, freq, dev->info.p2p_device_addr, p2p->cfg->dev_addr, dev->info.p2p_device_addr, wpabuf_head(req), wpabuf_len(req), 500) < 0) { p2p_dbg(p2p, "Failed to send Action frame"); /* Use P2P find to recover and retry */ p2p_set_timeout(p2p, 0, 0); } else { dev->flags |= P2P_DEV_WAIT_INV_REQ_ACK; } wpabuf_free(req); return 0; } void p2p_invitation_req_cb(struct p2p_data *p2p, int success) { p2p_dbg(p2p, "Invitation Request TX callback: success=%d", success); if (p2p->invite_peer == NULL) { p2p_dbg(p2p, "No pending Invite"); return; } if (success) p2p->invite_peer->flags &= ~P2P_DEV_WAIT_INV_REQ_ACK; /* * Use P2P find, if needed, to find the other device from its listen * channel. */ p2p_set_state(p2p, P2P_INVITE); p2p_set_timeout(p2p, 0, success ? 500000 : 100000); } void p2p_invitation_resp_cb(struct p2p_data *p2p, int success) { p2p_dbg(p2p, "Invitation Response TX callback: success=%d", success); p2p->cfg->send_action_done(p2p->cfg->cb_ctx); if (!success) p2p_dbg(p2p, "Assume Invitation Response was actually received by the peer even though Ack was not reported"); if (p2p->cfg->invitation_received) { p2p->cfg->invitation_received(p2p->cfg->cb_ctx, p2p->inv_sa, p2p->inv_group_bssid_ptr, p2p->inv_ssid, p2p->inv_ssid_len, p2p->inv_go_dev_addr, p2p->inv_status, p2p->inv_op_freq); } } int p2p_invite(struct p2p_data *p2p, const u8 *peer, enum p2p_invite_role role, const u8 *bssid, const u8 *ssid, size_t ssid_len, unsigned int force_freq, const u8 *go_dev_addr, int persistent_group, unsigned int pref_freq, int dev_pw_id) { struct p2p_device *dev; p2p_dbg(p2p, "Request to invite peer " MACSTR " role=%d persistent=%d " "force_freq=%u", MAC2STR(peer), role, persistent_group, force_freq); if (bssid) p2p_dbg(p2p, "Invitation for BSSID " MACSTR, MAC2STR(bssid)); if (go_dev_addr) { p2p_dbg(p2p, "Invitation for GO Device Address " MACSTR, MAC2STR(go_dev_addr)); os_memcpy(p2p->invite_go_dev_addr_buf, go_dev_addr, ETH_ALEN); p2p->invite_go_dev_addr = p2p->invite_go_dev_addr_buf; } else p2p->invite_go_dev_addr = NULL; wpa_hexdump_ascii(MSG_DEBUG, "Invitation for SSID", ssid, ssid_len); if (dev_pw_id >= 0) { p2p_dbg(p2p, "Invitation to use Device Password ID %d", dev_pw_id); } p2p->invite_dev_pw_id = dev_pw_id; p2p->retry_invite_req = role == P2P_INVITE_ROLE_GO && persistent_group && !force_freq; p2p->retry_invite_req_sent = 0; dev = p2p_get_device(p2p, peer); if (dev == NULL || (dev->listen_freq <= 0 && dev->oper_freq <= 0 && dev->oob_go_neg_freq <= 0)) { p2p_dbg(p2p, "Cannot invite unknown P2P Device " MACSTR, MAC2STR(peer)); return -1; } if (p2p_prepare_channel(p2p, dev, force_freq, pref_freq, role != P2P_INVITE_ROLE_CLIENT) < 0) return -1; if (persistent_group && role == P2P_INVITE_ROLE_CLIENT && !force_freq && !pref_freq) dev->flags |= P2P_DEV_NO_PREF_CHAN; else dev->flags &= ~P2P_DEV_NO_PREF_CHAN; if (dev->flags & P2P_DEV_GROUP_CLIENT_ONLY) { if (!(dev->info.dev_capab & P2P_DEV_CAPAB_CLIENT_DISCOVERABILITY)) { p2p_dbg(p2p, "Cannot invite a P2P Device " MACSTR " that is in a group and is not discoverable", MAC2STR(peer)); } /* TODO: use device discoverability request through GO */ } dev->invitation_reqs = 0; if (p2p->state != P2P_IDLE) p2p_stop_find(p2p); p2p->inv_role = role; p2p->inv_bssid_set = bssid != NULL; if (bssid) os_memcpy(p2p->inv_bssid, bssid, ETH_ALEN); os_memcpy(p2p->inv_ssid, ssid, ssid_len); p2p->inv_ssid_len = ssid_len; p2p->inv_persistent = persistent_group; return p2p_invite_send(p2p, dev, go_dev_addr, dev_pw_id); }
// Copyright (c) 2011-2019 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_QT_WALLETMODELTRANSACTION_H #define BITCOIN_QT_WALLETMODELTRANSACTION_H #include <qt/walletmodel.h> #include <memory> #include <QObject> class SendCoinsRecipient; namespace interfaces { class Node; class PendingWalletTx; } /** Data model for a walletmodel transaction. */ class WalletModelTransaction { public: explicit WalletModelTransaction(const QList<SendCoinsRecipient> &recipients); QList<SendCoinsRecipient> getRecipients() const; std::unique_ptr<interfaces::PendingWalletTx>& getWtx(); unsigned int getTransactionSize(); void setTransactionFee(const CAmount& newFee); CAmount getTransactionFee() const; CAmount getTotalTransactionAmount() const; void reassignAmounts(int nChangePosRet); // needed for the subtract-fee-from-amount feature private: QList<SendCoinsRecipient> recipients; std::unique_ptr<interfaces::PendingWalletTx> wtx; CAmount fee; }; #endif // BITCOIN_QT_WALLETMODELTRANSACTION_H
from powerpy.synchronize import synchronized, synchronize_ensure, synchronize_release class Observer: def update(self, *args, **kwargs): pass class Observable: def __init__(self): self.observers = [] self.changed = False @synchronized def add_observer(self, observer): if observer not in self.observers: self.observers.append(observer) @synchronized def del_observer(self, observer): if observer in self.observers: self.observers.remove(observer) @property def has_changed(self): return self.changed def set_changed(self): self.changed = True def notify_observers(self, *args, **kwargs): try: synchronize_ensure(self) if not self.changed: return alocal = list(self.observers) self.changed = False finally: synchronize_release(self) for obs in alocal: obs.update(*args, **kwargs)
from south.db import db from django.db import models class Migration: def forwards(self): db.alter_column("fakeapp_spam", 'weight', models.FloatField(null=True)) def backwards(self): db.alter_column("fakeapp_spam", 'weight', models.FloatField()) models = { "fakeapp.bug135": { 'date': ('models.DateTimeField', [], {'default': 'datetime.datetime(2009, 5, 6, 15, 33, 15, 780013)'}), } }
#!/usr/bin/env python3 import sys import secrets from requests import Session import re limit = 128 offset = 0 ip = sys.argv[1] find_fileinfo_regexp = re.compile(r'<div class="filenames">(.*)</div>') new_filename_link = re.compile(r'<div class="message">Your fanfic was uploaded to (uploads/.*)</div>') url = f'http://{ip}:3113' login = secrets.token_hex(10) password = login s = Session() resp = s.post(url + '/register', data = {'login':login, 'password': password}) resp = s.post(url + '/login', data = {'login':login, 'password': password}) #get file listing uploads_html = s.get(url + f'/uploads?limit={limit}&offset={offset}').text files_info = find_fileinfo_regexp.findall(uploads_html) filenames = [f"{x.split(': ')[0]}_{x.split(': ')[1]}" for x in files_info] #for every file upload new by link 'file:///services/doseo/uploads' + old filename copy_filenames = [] for filename in filenames: link = f"file:///services/doseo/uploads/{filename}" r = s.post(url + '/upload_by_link', data = {'link':link}) new_link = new_filename_link.findall(r.text)[0] copy_filenames.append(new_link) #download all new files for filename in copy_filenames: print(s.get(url + '/' + filename).text)
/** ========================================================= * Material Dashboard 2 React - v2.0.0 ========================================================= * Product Page: https://www.creative-tim.com/product/material-dashboard-react * Copyright 2021 Creative Tim (https://www.creative-tim.com) Coded by www.creative-tim.com ========================================================= * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. */ // prop-types is a library for typechecking of props import PropTypes from "prop-types"; // @mui material components import Card from "@mui/material/Card"; // Material Dashboard 2 React components import MDBox from "components/MDBox"; import MDTypography from "components/MDTypography"; // Material Dashboard 2 React components import { useMaterialUIController } from "context"; // Timeline context import { TimelineProvider } from "examples/Timeline/context"; function TimelineList({ title, dark, children }) { const [controller] = useMaterialUIController(); const { darkMode } = controller; return ( <TimelineProvider value={dark}> <Card> <MDBox bgColor={dark ? "dark" : "white"} variant="gradient" borderRadius="xl" sx={{ background: ({ palette: { background } }) => darkMode && background.card }} > <MDBox pt={3} px={3}> <MDTypography variant="h6" fontWeight="medium" color={dark ? "white" : "dark"}> {title} </MDTypography> </MDBox> <MDBox p={2}>{children}</MDBox> </MDBox> </Card> </TimelineProvider> ); } // Setting default values for the props of TimelineList TimelineList.defaultProps = { dark: false, }; // Typechecking props for the TimelineList TimelineList.propTypes = { title: PropTypes.string.isRequired, dark: PropTypes.bool, children: PropTypes.node.isRequired, }; export default TimelineList;
"""Support for Xiaomi Mi Flora BLE plant sensor.""" from datetime import timedelta import logging import btlewrap from btlewrap import BluetoothBackendException from miflora import miflora_poller import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA from homeassistant.const import ( CONF_FORCE_UPDATE, CONF_MAC, CONF_MONITORED_CONDITIONS, CONF_NAME, CONF_SCAN_INTERVAL, EVENT_HOMEASSISTANT_START, UNIT_PERCENTAGE, ) from homeassistant.core import callback import homeassistant.helpers.config_validation as cv from homeassistant.helpers.entity import Entity try: import bluepy.btle # noqa: F401 pylint: disable=unused-import BACKEND = btlewrap.BluepyBackend except ImportError: BACKEND = btlewrap.GatttoolBackend _LOGGER = logging.getLogger(__name__) CONF_ADAPTER = "adapter" CONF_MEDIAN = "median" DEFAULT_ADAPTER = "hci0" DEFAULT_FORCE_UPDATE = False DEFAULT_MEDIAN = 3 DEFAULT_NAME = "Mi Flora" SCAN_INTERVAL = timedelta(seconds=1200) # Sensor types are defined like: Name, units, icon SENSOR_TYPES = { "temperature": ["Temperature", "°C", "mdi:thermometer"], "light": ["Light intensity", "lx", "mdi:white-balance-sunny"], "moisture": ["Moisture", UNIT_PERCENTAGE, "mdi:water-percent"], "conductivity": ["Conductivity", "µS/cm", "mdi:flash-circle"], "battery": ["Battery", UNIT_PERCENTAGE, "mdi:battery-charging"], } PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( { vol.Required(CONF_MAC): cv.string, vol.Optional(CONF_MONITORED_CONDITIONS, default=list(SENSOR_TYPES)): vol.All( cv.ensure_list, [vol.In(SENSOR_TYPES)] ), vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, vol.Optional(CONF_MEDIAN, default=DEFAULT_MEDIAN): cv.positive_int, vol.Optional(CONF_FORCE_UPDATE, default=DEFAULT_FORCE_UPDATE): cv.boolean, vol.Optional(CONF_ADAPTER, default=DEFAULT_ADAPTER): cv.string, } ) async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Set up the MiFlora sensor.""" backend = BACKEND _LOGGER.debug("Miflora is using %s backend.", backend.__name__) cache = config.get(CONF_SCAN_INTERVAL, SCAN_INTERVAL).total_seconds() poller = miflora_poller.MiFloraPoller( config.get(CONF_MAC), cache_timeout=cache, adapter=config.get(CONF_ADAPTER), backend=backend, ) force_update = config.get(CONF_FORCE_UPDATE) median = config.get(CONF_MEDIAN) devs = [] for parameter in config[CONF_MONITORED_CONDITIONS]: name = SENSOR_TYPES[parameter][0] unit = SENSOR_TYPES[parameter][1] icon = SENSOR_TYPES[parameter][2] prefix = config.get(CONF_NAME) if prefix: name = f"{prefix} {name}" devs.append( MiFloraSensor(poller, parameter, name, unit, icon, force_update, median) ) async_add_entities(devs) class MiFloraSensor(Entity): """Implementing the MiFlora sensor.""" def __init__(self, poller, parameter, name, unit, icon, force_update, median): """Initialize the sensor.""" self.poller = poller self.parameter = parameter self._unit = unit self._icon = icon self._name = name self._state = None self._available = False self.data = [] self._force_update = force_update # Median is used to filter out outliers. median of 3 will filter # single outliers, while median of 5 will filter double outliers # Use median_count = 1 if no filtering is required. self.median_count = median async def async_added_to_hass(self): """Set initial state.""" @callback def on_startup(_): self.async_schedule_update_ha_state(True) self.hass.bus.async_listen_once(EVENT_HOMEASSISTANT_START, on_startup) @property def name(self): """Return the name of the sensor.""" return self._name @property def state(self): """Return the state of the sensor.""" return self._state @property def available(self): """Return True if entity is available.""" return self._available @property def unit_of_measurement(self): """Return the units of measurement.""" return self._unit @property def icon(self): """Return the icon of the sensor.""" return self._icon @property def force_update(self): """Force update.""" return self._force_update def update(self): """ Update current conditions. This uses a rolling median over 3 values to filter out outliers. """ try: _LOGGER.debug("Polling data for %s", self.name) data = self.poller.parameter_value(self.parameter) except (OSError, BluetoothBackendException) as err: _LOGGER.info("Polling error %s: %s", type(err).__name__, err) self._available = False return if data is not None: _LOGGER.debug("%s = %s", self.name, data) self._available = True self.data.append(data) else: _LOGGER.info("Did not receive any data from Mi Flora sensor %s", self.name) # Remove old data from median list or set sensor value to None # if no data is available anymore if self.data: self.data = self.data[1:] else: self._state = None return _LOGGER.debug("Data collected: %s", self.data) if len(self.data) > self.median_count: self.data = self.data[1:] if len(self.data) == self.median_count: median = sorted(self.data)[int((self.median_count - 1) / 2)] _LOGGER.debug("Median is: %s", median) self._state = median elif self._state is None: _LOGGER.debug("Set initial state") self._state = self.data[0] else: _LOGGER.debug("Not yet enough data for median calculation")
import React, { useState, useEffect } from 'react'; import clsx from 'clsx'; import { makeStyles } from '@material-ui/core/styles'; import { Grid, Paper, Typography } from '@material-ui/core'; import moment from 'moment'; import { concat, flatten } from 'lodash/array'; import { orderBy } from 'lodash/collection'; import Title from './../../components/Title'; import { useFeedCampaignsReq, useFeedRewardsReq } from './FeedReq'; import { shortAddress } from './../../utils/getWeb3'; const useStyles = makeStyles((theme) => ({ feed: { width: '100%', display: 'flex', flexDirection: 'column', alignItems: 'center' }, feedItem: { marginTop: '15px', width: '75%', padding: theme.spacing(3), textAlign: 'left' }, feedItemMaster: { marginTop: '15px', marginBottom: '15px', width: '75%', padding: theme.spacing(2), textAlign: 'center' }, buttons: { display: 'flex', alignItems: 'center', justifyContent: 'space-around' } })); function FeedItem(props) { const classes = useStyles(); const { data } = props; const [elevation, setElevation] = useState(2); return ( <Paper className={classes.feedItem} elevation={elevation} onMouseOver={() => setElevation(6)} onMouseOut={() => setElevation(2)} > <Title>{ data.text }</Title> <div style={{ textAlign: 'right', right: 0, lineHeight: 0 }}>{data.ts}</div> </Paper> ); } export default function Campaigns(props) { const classes = useStyles(); const { web3 } = props; const fixedHeightPaper = clsx(classes.paper, classes.fixedHeight); const [graphData, setGraphData] = useState(); const campaigns = useFeedCampaignsReq(); const users = useFeedRewardsReq(); const getEth = (wei) => web3.utils.fromWei(wei.toString(), 'ether'); const timeDiff = (ts) => moment.duration(moment.utc().diff(moment.utc(ts * 1000))).humanize(); const getItem = ({ type, data }) => { if (type === 'campaign') { return { text: `[${shortAddress(data.creator.owner)}] created campaign '${data.title}' for ${getEth(data.budgetWei)} ETH 🔥`, ts: `${timeDiff(data.createdAt)} ago` }; } if (type === 'user') { return { text: `[${shortAddress(data.account)}] joined ad rewards 🚀`, ts: `${timeDiff(data.enabledAt)} ago` }; } return { text: `[${shortAddress(data.account)}] received ${getEth(data.rewardsWei)} ETH in rewards 💸`, ts: `${timeDiff(data.withdrewAt)} ago` }; } useEffect(() => { if (campaigns && users) { const all = concat(campaigns.mobilityCampaigns, users).map((d) => { if (d.creator) { return { type: 'campaign', ts: d.createdAt, ...d }; } // user + rewards if (d.rewards) { return concat({ type: 'user', ts: d.enabledAt, ...d }, d.rewards.map((r) => ({ type: 'reward', ts: d.withdrewAt, ...r, account: d.account }))); } return { type: 'user', ts: d.enabledAt, ...d }; }); setGraphData(orderBy(flatten(all), ['ts'], ['desc'])); } }, [campaigns, users]); return ( <Grid container spacing={3}> { graphData && ( <div className={classes.feed}> <Paper className={classes.feedItemMaster} elevation={3} > <Title>{`Advertisers: ${campaigns.mobilityCampaignOwners.length}`} | {`Campaigns: ${campaigns.mobilityCampaigns.length}`} | {`Users: ${users.length}`}</Title> </Paper> { graphData.map((data, idx) => ( <FeedItem key={`c-item-${idx}`} data={getItem({ type: data.type, data })} /> )) } </div> ) } </Grid> ); };
import numpy as np import h5py # def normalization(data): _range = np.max(data) - np.min(data) return (data - np.min(data)) / _range def onehot(data_y): # one-hot encoding sleep stages data_y=[data_y] temp_y = [] for i in range(len(data_y)): temp_ = [] for j in range(len(data_y[i])): temp = np.zeros((6,)) temp[data_y[i][j]] = 1. temp_.append(temp) temp_y.append(np.array(temp_)) data_y = np.array(temp_y) return data_y np.set_printoptions(suppress=True) def loaddata(dataset): npz = np.load(dataset) trainX = npz['X_train'] trainY = npz['y_train'] X_valid = npz['X_valid'] y_valid = npz['y_valid'] testX = npz['X_test'] testY = npz['y_test'] # trainX=np.array(data["train_data"]).astype('float32').transpose(0,2,1) # trainY=np.array(data["train_label"]).astype('int').transpose(1,0) # testX=np.array(data["test_data"]).astype('float32').transpose(0,2,1) # testY = np.array(data["test_label"]).astype('int').transpose(1,0) # X = np.zeros((trainX.shape[0]+testX.shape[0],trainX.shape[1],trainX.shape[2])) # X[0:trainX.shape[0],:,:] = trainX # X[trainX.shape[0]:trainX.shape[0]+testX.shape[0],:,:]=testX # # Y = np.append(trainY,testY) # # result=[X,Y] # trainY = onehot(trainY).transpose(1,2,0).squeeze() # testY = onehot(testY).transpose(1,2,0).squeeze() temp_x = np.zeros((trainX.shape[0],3072,trainX.shape[2])) temp_x[:,36:3036,:]=trainX trainX = temp_x temp_x = np.zeros((X_valid.shape[0],3072,trainX.shape[2])) temp_x[:,36:3036,:]=X_valid X_valid = temp_x temp_x = np.zeros((testX.shape[0],3072,testX.shape[2])) temp_x[:,36:3036,:]=testX testX = temp_x print(trainX.shape) print(trainY.shape) print(X_valid.shape) print(y_valid.shape) print(testX.shape) print(testY.shape) result = [trainX,trainY,X_valid,y_valid,testX,testY] return result # # trainX,trainY=loaddata('sleep_edf_data.mat') # # #_ = [print(len(x)) for x in loaddata('sleep_edf_data.mat')] # # print(type(testX)) # # print(testX.shape) # # print(trainX.shape) # print(trainX.shape) # print(trainY)
# Copyright (c) 2011 AlphaSierraPapa for the SharpDevelop Team # # Permission is hereby granted, free of charge, to any person obtaining a copy of this # software and associated documentation files (the "Software"), to deal in the Software # without restriction, including without limitation the rights to use, copy, modify, merge, # publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons # to whom the Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all copies or # substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, # INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR # PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE # FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR # OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER # DEALINGS IN THE SOFTWARE. from System import * from System.Collections.Generic import * class NavigationHistory(object): """ <summary> Stores the navigation history. </summary> """ def __init__(self): """ <summary> Stores the navigation history. </summary> """ self._NavigationSecondsBeforeNewEntry = 0.5 self._lastNavigationTime = DateTime.MinValue self._back = List[T]() self._forward = List[T]() def get_CanNavigateBack(self): return self._back.Count > 0 CanNavigateBack = property(fget=get_CanNavigateBack) def get_CanNavigateForward(self): return self._forward.Count > 0 CanNavigateForward = property(fget=get_CanNavigateForward) def GoBack(self): self._forward.Add(self._current) self._current = self._back[self._back.Count - 1] self._back.RemoveAt(self._back.Count - 1) return self._current def GoForward(self): self._back.Add(self._current) self._current = self._forward[self._forward.Count - 1] self._forward.RemoveAt(self._forward.Count - 1) return self._current def RemoveAll(self, predicate): self._back.RemoveAll(predicate) self._forward.RemoveAll(predicate) def Clear(self): self._back.Clear() self._forward.Clear() def UpdateCurrent(self, node): self._current = node def Record(self, node): navigationTime = DateTime.Now period = navigationTime - self._lastNavigationTime if period.TotalSeconds < self._NavigationSecondsBeforeNewEntry: self._current = node else: if self._current != None: self._back.Add(self._current) # We only store a record once, and ensure it is on the top of the stack, so we just remove the old record self._back.Remove(node) self._current = node self._forward.Clear() self._lastNavigationTime = navigationTime
export const piedPiper = {"viewBox":"0 0 2304 1792","children":[{"name":"path","attribs":{"d":"M2304 0q-69 46-125 92t-89 81-59.5 71.5-37.5 57.5-22 44.5-14 29.5q-10 18-35.5 136.5t-48.5 164.5q-15 29-50 60.5t-67.5 50.5-72.5 41-48 28q-47 31-151 231-341-14-630 158-92 53-303 179 47-16 86-31t55-22l15-7q71-27 163-64.5t133.5-53.5 108-34.5 142.5-31.5q186-31 465 7 1 0 10 3 11 6 14 17t-3 22l-194 345q-15 29-47 22-128-24-354-24-146 0-402 44.5t-392 46.5q-82 1-149-13t-107-37-61-40-33-34l-1-1v-2q0-6 6-6 138 0 371-55 192-366 374.5-524t383.5-158q5 0 14.5 0.5t38 5 55 12 61.5 24.5 63 39.5 54 59 40 82.5l102-177q2-4 21-42.5t44.5-86.5 61-109.5 84-133.5 100.5-137q66-82 128-141.5t121.5-96.5 92.5-53.5 88-39.5z"}}]};
// @flow import { FieldTextStateless } from '@atlaskit/field-text'; import React, { Component } from 'react'; import { withTranslation } from 'react-i18next'; import { connect } from 'react-redux'; import type { Dispatch } from 'redux'; import { compose } from 'redux'; import config from '../../config'; import { getExternalApiURL } from '../../utils'; import { setServerURL } from '../actions'; import { Form } from '../styled'; type Props = { /** * Redux dispatch. */ dispatch: Dispatch<*>; /** * Default Jitsi Meet Server URL in (redux) store. */ _serverURL: string; /** * I18next translation function. */ t: Function; }; type State = { /** * Whether the url of the Jitsi Meet Server valid. */ isValid: boolean; /** * Default Jitsi Meet Server URL in (local) state. */ serverURL: string; }; /** * Default Server URL field text placed in the Settings drawer. */ class ServerURLField extends Component<Props, State> { /** * Initializes a new {@code ServerURLField} instance. * * @inheritdoc */ constructor(props) { super(props); this.state = { isValid: true, serverURL: props._serverURL }; this._onServerURLChange = this._onServerURLChange.bind(this); this._onServerURLSubmit = this._onServerURLSubmit.bind(this); } /** * Render function of component. * * @returns {ReactElement} */ render() { const { t } = this.props; return ( <Form onSubmit = { this._onServerURLSubmit }> <FieldTextStateless invalidMessage = { t('settings.invalidServer') } isInvalid = { !this.state.isValid } isValidationHidden = { this.state.isValid } label = { t('settings.serverUrl') } onBlur = { this._onServerURLSubmit } onChange = { this._onServerURLChange } placeholder = { config.defaultServerURL } shouldFitContainer = { true } type = 'text' value = { this.state.serverURL } /> </Form> ); } _onServerURLChange: (*) => void; /** * Updates Server URL in (redux) state when it is updated. * * @param {SyntheticInputEvent<HTMLInputElement>} event - Event by which * this function is called. * @returns {void} */ _onServerURLChange(event: SyntheticInputEvent<HTMLInputElement>) { this.setState({ serverURL: event.currentTarget.value }, this._validateServerURL); } _onServerURLSubmit: (*) => void; /** * Updates Server URL in (redux) store when it is updated. * * @param {Event} event - Event by which this function is called. * @returns {void} */ _onServerURLSubmit(event: Event) { event.preventDefault(); if (this.state.isValid) { this.props.dispatch(setServerURL(this.state.serverURL)); } } /** * Validates the Server URL by fetching external_api.js using the HEAD * method. * * @returns {void} */ _validateServerURL() { fetch(getExternalApiURL(this.state.serverURL), { method: 'HEAD' }) .then((response: Object) => { this.setState({ isValid: response.ok }); }) .catch(() => { this.setState({ isValid: false }); }); } } /** * Maps (parts of) the redux store to the React props. * * @param {Object} state - The redux state. * @returns {{ * _serverURL: string * }} */ function _mapStateToProps(state: Object) { return { _serverURL: state.settings.serverURL }; } export default compose(connect(_mapStateToProps), withTranslation())(ServerURLField);
import numpy as np import pandas as pd from functools import reduce import seaborn as sns from scipy.stats import multivariate_normal import csv def read_data(year,data_path): path_name = data_path+'ENIGH'+year+'/' hog = pd.read_csv(path_name+'hogares.csv', index_col = 'folioviv', low_memory = False, na_values = [' ', '&']) pob = pd.read_csv(path_name+'poblacion.csv', index_col = 'folioviv', low_memory = False,na_values = [' ', '&']) conc = pd.read_csv(path_name+'concentradohogar.csv', index_col = 'folioviv', low_memory = False,na_values = [' ', '&']) viv = pd.read_csv(path_name+'viviendas.csv', index_col = 'folioviv', low_memory = False,na_values = [' ', '&']) data_frames = [pob,hog,conc,viv] df_merged = reduce(lambda left,right: pd.merge(left,right,on = 'folioviv', how = 'outer'), data_frames) if int(year)>=2018: df_merged.drop(columns=['foliohog_x','foliohog_y','ubica_geo_y', 'tam_loc_y','est_socio_y','est_dis_y','upm_y','factor_y','smg', 'est_dis_x','upm_x', 'factor_x','numren', 'foliohog'], inplace = True) df_merged.rename(columns={'ubica_geo_x':'ubica_geo', 'tam_loc_x':'tam_loc','est_socio_x':'est_socio'}, inplace = True) elif int(year)==2016: df_merged.drop(columns=['foliohog_x','foliohog_y','ubica_geo_y', 'tam_loc_y','est_socio_y','est_dis_y','upm_y','factor_y','smg','ageb_y', 'ageb_x','est_dis_x','upm_x','factor_x','numren'], inplace = True) df_merged.rename(columns={'ubica_geo_x':'ubica_geo','tam_loc_x':'tam_loc', 'est_socio_x':'est_socio'}, inplace = True) return(df_merged) def strg(variable): var = variable.astype(int).apply(str) return(var) def standardization(df): df_std = df.copy() for column in df_std.columns[:-2]: if (df_std[column].std(ddof=0)==0): df_std.drop(columns=column,inplace=True) else: df_std[column] = (df_std[column] - df_std[column].mean())/df_std[column].std() return df_std def hhld_classification(df): #Classification by sex of household referent person sexHHRP = [(df.sexo_jefe==1),(df.sexo_jefe==2)] choices = ['H','M'] df['sex_hhrp'] = np.select(sexHHRP,choices,default='empty') #Classification by age range of household members hh_members = [ (df.p12_64>0) & (df.p65mas==0) & (df.menores==0), (df.p12_64>0) & (df.p65mas==0) & (df.menores>0), (df.p12_64>0) & (df.p65mas>0) & (df.menores==0), (df.p12_64==0) & (df.p65mas>0) & (df.menores>0), (df.p12_64==0) & (df.p65mas>0) & (df.menores==0), (df.p12_64>0) & (df.p65mas>0) & (df.menores>0)] choices = ['Adultos','AdultosMenores','AdultosMayores', 'MayoresMenores','Mayores','AdultosMayoresMenores'] df['age_habit'] = np.select(hh_members,choices,default='empty') df['node'] = df.sex_hhrp+df.age_habit return df # Fibonacci series to apply into the powerlaw visualization def recur_fibo(n): if n <= 1: return n else: return(recur_fibo(n-1)+recur_fibo(n-2)) def criteria(dic,pc,n_nodes): df = dic[pc] df['covmul'] = df[pc]*df['cov'] c = df[df.index==df['covmul'].idxmax()] c = c[['idx',pc]] c['num'] = n_nodes[pc] c['PC'] = pc c.rename(columns={pc:'value'},inplace=True) return [c,df] def ComputeRepresentativity(df,type_class,yr,path): #Read ENIGH covariance matrix cov_matrixr = pd.read_csv(path+'cov_matrix_'+type_class+yr+'.csv',index_col=[0]) cov_matrix = cov_matrixr.copy() keys = list(cov_matrix.columns.unique()) representativity = {} n_nodes = {} for ps in keys: rep = (cov_matrix[ps]/sum(cov_matrix[ps])).sort_values(ascending=False).cumsum() representativity[ps] = rep representativity[ps] = representativity[ps].to_frame() representativity[ps]['idx'] = range(1,len(representativity[ps])+1) representativity[ps]['cov'] = cov_matrix[ps] n_nodes[ps] = len(df[df.node==ps]) return (cov_matrix,keys,representativity,n_nodes) def typeofcriteria(keys,criteriatype,frames1,mean,crt): frames = frames1 m = mean crt = crt ps_n = list() cov_cut = {} for ps in keys: if criteriatype=='static': df_c = frames[ps][frames[ps][ps]<=m] #Static criteria elif criteriatype=='dynamic': df_c = frames[ps][frames[ps][ps]<=np.array(crt[crt.PC==ps].value)[0]] #dynamic criteria df = df_c.copy() df.drop(index=list(df[df['cov']==0].index),inplace=True) if len(df)!=0: cov_cut[ps] = df['cov'] ps_n.append(ps) series_cut = list() #List to recreate the covariance matrix after criteria analysis for ps in ps_n: sx = cov_cut[ps] sx.rename(ps,inplace=True) series_cut.append(sx) cov_matrix_cut = pd.concat(series_cut, axis=1).fillna(0) return cov_matrix_cut
(this.webpackJsonpdashboard=this.webpackJsonpdashboard||[]).push([[83],{495:function(e,t,o){"use strict";function r(e){e.languages.mel={comment:/\/\/.*/,code:{pattern:/`(?:\\.|[^\\`\r\n])*`/,greedy:!0,alias:"italic",inside:{delimiter:{pattern:/^`|`$/,alias:"punctuation"}}},string:{pattern:/"(?:\\.|[^\\"\r\n])*"/,greedy:!0},variable:/\$\w+/,number:/\b0x[\da-fA-F]+\b|\b\d+\.?\d*|\B\.\d+/,flag:{pattern:/-[^\d\W]\w*/,alias:"operator"},keyword:/\b(?:break|case|continue|default|do|else|float|for|global|if|in|int|matrix|proc|return|string|switch|vector|while)\b/,function:/\w+(?=\()|\b(?:about|abs|addAttr|addAttributeEditorNodeHelp|addDynamic|addNewShelfTab|addPP|addPanelCategory|addPrefixToName|advanceToNextDrivenKey|affectedNet|affects|aimConstraint|air|alias|aliasAttr|align|alignCtx|alignCurve|alignSurface|allViewFit|ambientLight|angle|angleBetween|animCone|animCurveEditor|animDisplay|animView|annotate|appendStringArray|applicationName|applyAttrPreset|applyTake|arcLenDimContext|arcLengthDimension|arclen|arrayMapper|art3dPaintCtx|artAttrCtx|artAttrPaintVertexCtx|artAttrSkinPaintCtx|artAttrTool|artBuildPaintMenu|artFluidAttrCtx|artPuttyCtx|artSelectCtx|artSetPaintCtx|artUserPaintCtx|assignCommand|assignInputDevice|assignViewportFactories|attachCurve|attachDeviceAttr|attachSurface|attrColorSliderGrp|attrCompatibility|attrControlGrp|attrEnumOptionMenu|attrEnumOptionMenuGrp|attrFieldGrp|attrFieldSliderGrp|attrNavigationControlGrp|attrPresetEditWin|attributeExists|attributeInfo|attributeMenu|attributeQuery|autoKeyframe|autoPlace|bakeClip|bakeFluidShading|bakePartialHistory|bakeResults|bakeSimulation|basename|basenameEx|batchRender|bessel|bevel|bevelPlus|binMembership|bindSkin|blend2|blendShape|blendShapeEditor|blendShapePanel|blendTwoAttr|blindDataType|boneLattice|boundary|boxDollyCtx|boxZoomCtx|bufferCurve|buildBookmarkMenu|buildKeyframeMenu|button|buttonManip|CBG|cacheFile|cacheFileCombine|cacheFileMerge|cacheFileTrack|camera|cameraView|canCreateManip|canvas|capitalizeString|catch|catchQuiet|ceil|changeSubdivComponentDisplayLevel|changeSubdivRegion|channelBox|character|characterMap|characterOutlineEditor|characterize|chdir|checkBox|checkBoxGrp|checkDefaultRenderGlobals|choice|circle|circularFillet|clamp|clear|clearCache|clip|clipEditor|clipEditorCurrentTimeCtx|clipSchedule|clipSchedulerOutliner|clipTrimBefore|closeCurve|closeSurface|cluster|cmdFileOutput|cmdScrollFieldExecuter|cmdScrollFieldReporter|cmdShell|coarsenSubdivSelectionList|collision|color|colorAtPoint|colorEditor|colorIndex|colorIndexSliderGrp|colorSliderButtonGrp|colorSliderGrp|columnLayout|commandEcho|commandLine|commandPort|compactHairSystem|componentEditor|compositingInterop|computePolysetVolume|condition|cone|confirmDialog|connectAttr|connectControl|connectDynamic|connectJoint|connectionInfo|constrain|constrainValue|constructionHistory|container|containsMultibyte|contextInfo|control|convertFromOldLayers|convertIffToPsd|convertLightmap|convertSolidTx|convertTessellation|convertUnit|copyArray|copyFlexor|copyKey|copySkinWeights|cos|cpButton|cpCache|cpClothSet|cpCollision|cpConstraint|cpConvClothToMesh|cpForces|cpGetSolverAttr|cpPanel|cpProperty|cpRigidCollisionFilter|cpSeam|cpSetEdit|cpSetSolverAttr|cpSolver|cpSolverTypes|cpTool|cpUpdateClothUVs|createDisplayLayer|createDrawCtx|createEditor|createLayeredPsdFile|createMotionField|createNewShelf|createNode|createRenderLayer|createSubdivRegion|cross|crossProduct|ctxAbort|ctxCompletion|ctxEditMode|ctxTraverse|currentCtx|currentTime|currentTimeCtx|currentUnit|curve|curveAddPtCtx|curveCVCtx|curveEPCtx|curveEditorCtx|curveIntersect|curveMoveEPCtx|curveOnSurface|curveSketchCtx|cutKey|cycleCheck|cylinder|dagPose|date|defaultLightListCheckBox|defaultNavigation|defineDataServer|defineVirtualDevice|deformer|deg_to_rad|delete|deleteAttr|deleteShadingGroupsAndMaterials|deleteShelfTab|deleteUI|deleteUnusedBrushes|delrandstr|detachCurve|detachDeviceAttr|detachSurface|deviceEditor|devicePanel|dgInfo|dgdirty|dgeval|dgtimer|dimWhen|directKeyCtx|directionalLight|dirmap|dirname|disable|disconnectAttr|disconnectJoint|diskCache|displacementToPoly|displayAffected|displayColor|displayCull|displayLevelOfDetail|displayPref|displayRGBColor|displaySmoothness|displayStats|displayString|displaySurface|distanceDimContext|distanceDimension|doBlur|dolly|dollyCtx|dopeSheetEditor|dot|dotProduct|doubleProfileBirailSurface|drag|dragAttrContext|draggerContext|dropoffLocator|duplicate|duplicateCurve|duplicateSurface|dynCache|dynControl|dynExport|dynExpression|dynGlobals|dynPaintEditor|dynParticleCtx|dynPref|dynRelEdPanel|dynRelEditor|dynamicLoad|editAttrLimits|editDisplayLayerGlobals|editDisplayLayerMembers|editRenderLayerAdjustment|editRenderLayerGlobals|editRenderLayerMembers|editor|editorTemplate|effector|emit|emitter|enableDevice|encodeString|endString|endsWith|env|equivalent|equivalentTol|erf|error|eval|evalDeferred|evalEcho|event|exactWorldBoundingBox|exclusiveLightCheckBox|exec|executeForEachObject|exists|exp|expression|expressionEditorListen|extendCurve|extendSurface|extrude|fcheck|fclose|feof|fflush|fgetline|fgetword|file|fileBrowserDialog|fileDialog|fileExtension|fileInfo|filetest|filletCurve|filter|filterCurve|filterExpand|filterStudioImport|findAllIntersections|findAnimCurves|findKeyframe|findMenuItem|findRelatedSkinCluster|finder|firstParentOf|fitBspline|flexor|floatEq|floatField|floatFieldGrp|floatScrollBar|floatSlider|floatSlider2|floatSliderButtonGrp|floatSliderGrp|floor|flow|fluidCacheInfo|fluidEmitter|fluidVoxelInfo|flushUndo|fmod|fontDialog|fopen|formLayout|format|fprint|frameLayout|fread|freeFormFillet|frewind|fromNativePath|fwrite|gamma|gauss|geometryConstraint|getApplicationVersionAsFloat|getAttr|getClassification|getDefaultBrush|getFileList|getFluidAttr|getInputDeviceRange|getMayaPanelTypes|getModifiers|getPanel|getParticleAttr|getPluginResource|getenv|getpid|glRender|glRenderEditor|globalStitch|gmatch|goal|gotoBindPose|grabColor|gradientControl|gradientControlNoAttr|graphDollyCtx|graphSelectContext|graphTrackCtx|gravity|grid|gridLayout|group|groupObjectsByName|HfAddAttractorToAS|HfAssignAS|HfBuildEqualMap|HfBuildFurFiles|HfBuildFurImages|HfCancelAFR|HfConnectASToHF|HfCreateAttractor|HfDeleteAS|HfEditAS|HfPerformCreateAS|HfRemoveAttractorFromAS|HfSelectAttached|HfSelectAttractors|HfUnAssignAS|hardenPointCurve|hardware|hardwareRenderPanel|headsUpDisplay|headsUpMessage|help|helpLine|hermite|hide|hilite|hitTest|hotBox|hotkey|hotkeyCheck|hsv_to_rgb|hudButton|hudSlider|hudSliderButton|hwReflectionMap|hwRender|hwRenderLoad|hyperGraph|hyperPanel|hyperShade|hypot|iconTextButton|iconTextCheckBox|iconTextRadioButton|iconTextRadioCollection|iconTextScrollList|iconTextStaticLabel|ikHandle|ikHandleCtx|ikHandleDisplayScale|ikSolver|ikSplineHandleCtx|ikSystem|ikSystemInfo|ikfkDisplayMethod|illustratorCurves|image|imfPlugins|inheritTransform|insertJoint|insertJointCtx|insertKeyCtx|insertKnotCurve|insertKnotSurface|instance|instanceable|instancer|intField|intFieldGrp|intScrollBar|intSlider|intSliderGrp|interToUI|internalVar|intersect|iprEngine|isAnimCurve|isConnected|isDirty|isParentOf|isSameObject|isTrue|isValidObjectName|isValidString|isValidUiName|isolateSelect|itemFilter|itemFilterAttr|itemFilterRender|itemFilterType|joint|jointCluster|jointCtx|jointDisplayScale|jointLattice|keyTangent|keyframe|keyframeOutliner|keyframeRegionCurrentTimeCtx|keyframeRegionDirectKeyCtx|keyframeRegionDollyCtx|keyframeRegionInsertKeyCtx|keyframeRegionMoveKeyCtx|keyframeRegionScaleKeyCtx|keyframeRegionSelectKeyCtx|keyframeRegionSetKeyCtx|keyframeRegionTrackCtx|keyframeStats|lassoContext|lattice|latticeDeformKeyCtx|launch|launchImageEditor|layerButton|layeredShaderPort|layeredTexturePort|layout|layoutDialog|lightList|lightListEditor|lightListPanel|lightlink|lineIntersection|linearPrecision|linstep|listAnimatable|listAttr|listCameras|listConnections|listDeviceAttachments|listHistory|listInputDeviceAxes|listInputDeviceButtons|listInputDevices|listMenuAnnotation|listNodeTypes|listPanelCategories|listRelatives|listSets|listTransforms|listUnselected|listerEditor|loadFluid|loadNewShelf|loadPlugin|loadPluginLanguageResources|loadPrefObjects|localizedPanelLabel|lockNode|loft|log|longNameOf|lookThru|ls|lsThroughFilter|lsType|lsUI|Mayatomr|mag|makeIdentity|makeLive|makePaintable|makeRoll|makeSingleSurface|makeTubeOn|makebot|manipMoveContext|manipMoveLimitsCtx|manipOptions|manipRotateContext|manipRotateLimitsCtx|manipScaleContext|manipScaleLimitsCtx|marker|match|max|memory|menu|menuBarLayout|menuEditor|menuItem|menuItemToShelf|menuSet|menuSetPref|messageLine|min|minimizeApp|mirrorJoint|modelCurrentTimeCtx|modelEditor|modelPanel|mouse|movIn|movOut|move|moveIKtoFK|moveKeyCtx|moveVertexAlongDirection|multiProfileBirailSurface|mute|nParticle|nameCommand|nameField|namespace|namespaceInfo|newPanelItems|newton|nodeCast|nodeIconButton|nodeOutliner|nodePreset|nodeType|noise|nonLinear|normalConstraint|normalize|nurbsBoolean|nurbsCopyUVSet|nurbsCube|nurbsEditUV|nurbsPlane|nurbsSelect|nurbsSquare|nurbsToPoly|nurbsToPolygonsPref|nurbsToSubdiv|nurbsToSubdivPref|nurbsUVSet|nurbsViewDirectionVector|objExists|objectCenter|objectLayer|objectType|objectTypeUI|obsoleteProc|oceanNurbsPreviewPlane|offsetCurve|offsetCurveOnSurface|offsetSurface|openGLExtension|openMayaPref|optionMenu|optionMenuGrp|optionVar|orbit|orbitCtx|orientConstraint|outlinerEditor|outlinerPanel|overrideModifier|paintEffectsDisplay|pairBlend|palettePort|paneLayout|panel|panelConfiguration|panelHistory|paramDimContext|paramDimension|paramLocator|parent|parentConstraint|particle|particleExists|particleInstancer|particleRenderInfo|partition|pasteKey|pathAnimation|pause|pclose|percent|performanceOptions|pfxstrokes|pickWalk|picture|pixelMove|planarSrf|plane|play|playbackOptions|playblast|plugAttr|plugNode|pluginInfo|pluginResourceUtil|pointConstraint|pointCurveConstraint|pointLight|pointMatrixMult|pointOnCurve|pointOnSurface|pointPosition|poleVectorConstraint|polyAppend|polyAppendFacetCtx|polyAppendVertex|polyAutoProjection|polyAverageNormal|polyAverageVertex|polyBevel|polyBlendColor|polyBlindData|polyBoolOp|polyBridgeEdge|polyCacheMonitor|polyCheck|polyChipOff|polyClipboard|polyCloseBorder|polyCollapseEdge|polyCollapseFacet|polyColorBlindData|polyColorDel|polyColorPerVertex|polyColorSet|polyCompare|polyCone|polyCopyUV|polyCrease|polyCreaseCtx|polyCreateFacet|polyCreateFacetCtx|polyCube|polyCut|polyCutCtx|polyCylinder|polyCylindricalProjection|polyDelEdge|polyDelFacet|polyDelVertex|polyDuplicateAndConnect|polyDuplicateEdge|polyEditUV|polyEditUVShell|polyEvaluate|polyExtrudeEdge|polyExtrudeFacet|polyExtrudeVertex|polyFlipEdge|polyFlipUV|polyForceUV|polyGeoSampler|polyHelix|polyInfo|polyInstallAction|polyLayoutUV|polyListComponentConversion|polyMapCut|polyMapDel|polyMapSew|polyMapSewMove|polyMergeEdge|polyMergeEdgeCtx|polyMergeFacet|polyMergeFacetCtx|polyMergeUV|polyMergeVertex|polyMirrorFace|polyMoveEdge|polyMoveFacet|polyMoveFacetUV|polyMoveUV|polyMoveVertex|polyNormal|polyNormalPerVertex|polyNormalizeUV|polyOptUvs|polyOptions|polyOutput|polyPipe|polyPlanarProjection|polyPlane|polyPlatonicSolid|polyPoke|polyPrimitive|polyPrism|polyProjection|polyPyramid|polyQuad|polyQueryBlindData|polyReduce|polySelect|polySelectConstraint|polySelectConstraintMonitor|polySelectCtx|polySelectEditCtx|polySeparate|polySetToFaceNormal|polySewEdge|polyShortestPathCtx|polySmooth|polySoftEdge|polySphere|polySphericalProjection|polySplit|polySplitCtx|polySplitEdge|polySplitRing|polySplitVertex|polyStraightenUVBorder|polySubdivideEdge|polySubdivideFacet|polyToSubdiv|polyTorus|polyTransfer|polyTriangulate|polyUVSet|polyUnite|polyWedgeFace|popen|popupMenu|pose|pow|preloadRefEd|print|progressBar|progressWindow|projFileViewer|projectCurve|projectTangent|projectionContext|projectionManip|promptDialog|propModCtx|propMove|psdChannelOutliner|psdEditTextureFile|psdExport|psdTextureFile|putenv|pwd|python|querySubdiv|quit|rad_to_deg|radial|radioButton|radioButtonGrp|radioCollection|radioMenuItemCollection|rampColorPort|rand|randomizeFollicles|randstate|rangeControl|readTake|rebuildCurve|rebuildSurface|recordAttr|recordDevice|redo|reference|referenceEdit|referenceQuery|refineSubdivSelectionList|refresh|refreshAE|registerPluginResource|rehash|reloadImage|removeJoint|removeMultiInstance|removePanelCategory|rename|renameAttr|renameSelectionList|renameUI|render|renderGlobalsNode|renderInfo|renderLayerButton|renderLayerParent|renderLayerPostProcess|renderLayerUnparent|renderManip|renderPartition|renderQualityNode|renderSettings|renderThumbnailUpdate|renderWindowEditor|renderWindowSelectContext|renderer|reorder|reorderDeformers|requires|reroot|resampleFluid|resetAE|resetPfxToPolyCamera|resetTool|resolutionNode|retarget|reverseCurve|reverseSurface|revolve|rgb_to_hsv|rigidBody|rigidSolver|roll|rollCtx|rootOf|rot|rotate|rotationInterpolation|roundConstantRadius|rowColumnLayout|rowLayout|runTimeCommand|runup|sampleImage|saveAllShelves|saveAttrPreset|saveFluid|saveImage|saveInitialState|saveMenu|savePrefObjects|savePrefs|saveShelf|saveToolSettings|scale|scaleBrushBrightness|scaleComponents|scaleConstraint|scaleKey|scaleKeyCtx|sceneEditor|sceneUIReplacement|scmh|scriptCtx|scriptEditorInfo|scriptJob|scriptNode|scriptTable|scriptToShelf|scriptedPanel|scriptedPanelType|scrollField|scrollLayout|sculpt|searchPathArray|seed|selLoadSettings|select|selectContext|selectCurveCV|selectKey|selectKeyCtx|selectKeyframeRegionCtx|selectMode|selectPref|selectPriority|selectType|selectedNodes|selectionConnection|separator|setAttr|setAttrEnumResource|setAttrMapping|setAttrNiceNameResource|setConstraintRestPosition|setDefaultShadingGroup|setDrivenKeyframe|setDynamic|setEditCtx|setEditor|setFluidAttr|setFocus|setInfinity|setInputDeviceMapping|setKeyCtx|setKeyPath|setKeyframe|setKeyframeBlendshapeTargetWts|setMenuMode|setNodeNiceNameResource|setNodeTypeFlag|setParent|setParticleAttr|setPfxToPolyCamera|setPluginResource|setProject|setStampDensity|setStartupMessage|setState|setToolTo|setUITemplate|setXformManip|sets|shadingConnection|shadingGeometryRelCtx|shadingLightRelCtx|shadingNetworkCompare|shadingNode|shapeCompare|shelfButton|shelfLayout|shelfTabLayout|shellField|shortNameOf|showHelp|showHidden|showManipCtx|showSelectionInTitle|showShadingGroupAttrEditor|showWindow|sign|simplify|sin|singleProfileBirailSurface|size|sizeBytes|skinCluster|skinPercent|smoothCurve|smoothTangentSurface|smoothstep|snap2to2|snapKey|snapMode|snapTogetherCtx|snapshot|soft|softMod|softModCtx|sort|sound|soundControl|source|spaceLocator|sphere|sphrand|spotLight|spotLightPreviewPort|spreadSheetEditor|spring|sqrt|squareSurface|srtContext|stackTrace|startString|startsWith|stitchAndExplodeShell|stitchSurface|stitchSurfacePoints|strcmp|stringArrayCatenate|stringArrayContains|stringArrayCount|stringArrayInsertAtIndex|stringArrayIntersector|stringArrayRemove|stringArrayRemoveAtIndex|stringArrayRemoveDuplicates|stringArrayRemoveExact|stringArrayToString|stringToStringArray|strip|stripPrefixFromName|stroke|subdAutoProjection|subdCleanTopology|subdCollapse|subdDuplicateAndConnect|subdEditUV|subdListComponentConversion|subdMapCut|subdMapSewMove|subdMatchTopology|subdMirror|subdToBlind|subdToPoly|subdTransferUVsToCache|subdiv|subdivCrease|subdivDisplaySmoothness|substitute|substituteAllString|substituteGeometry|substring|surface|surfaceSampler|surfaceShaderList|swatchDisplayPort|switchTable|symbolButton|symbolCheckBox|sysFile|system|tabLayout|tan|tangentConstraint|texLatticeDeformContext|texManipContext|texMoveContext|texMoveUVShellContext|texRotateContext|texScaleContext|texSelectContext|texSelectShortestPathCtx|texSmudgeUVContext|texWinToolCtx|text|textCurves|textField|textFieldButtonGrp|textFieldGrp|textManip|textScrollList|textToShelf|textureDisplacePlane|textureHairColor|texturePlacementContext|textureWindow|threadCount|threePointArcCtx|timeControl|timePort|timerX|toNativePath|toggle|toggleAxis|toggleWindowVisibility|tokenize|tokenizeList|tolerance|tolower|toolButton|toolCollection|toolDropped|toolHasOptions|toolPropertyWindow|torus|toupper|trace|track|trackCtx|transferAttributes|transformCompare|transformLimits|translator|trim|trunc|truncateFluidCache|truncateHairCache|tumble|tumbleCtx|turbulence|twoPointArcCtx|uiRes|uiTemplate|unassignInputDevice|undo|undoInfo|ungroup|uniform|unit|unloadPlugin|untangleUV|untitledFileName|untrim|upAxis|updateAE|userCtx|uvLink|uvSnapshot|validateShelfName|vectorize|view2dToolCtx|viewCamera|viewClipPlane|viewFit|viewHeadOn|viewLookAt|viewManip|viewPlace|viewSet|visor|volumeAxis|vortex|waitCursor|warning|webBrowser|webBrowserPrefs|whatIs|window|windowPref|wire|wireContext|workspace|wrinkle|wrinkleContext|writeTake|xbmLangPathList|xform)\b/,operator:[/\+[+=]?|-[-=]?|&&|\|\||[<>]=|[*\/!=]=?|[%^]/,{pattern:/(^|[^<])<(?!<)/,lookbehind:!0},{pattern:/(^|[^>])>(?!>)/,lookbehind:!0}],punctuation:/<<|>>|[.,:;?\[\](){}]/},e.languages.mel.code.inside.rest=e.languages.mel}e.exports=r,r.displayName="mel",r.aliases=[]}}]);
# -*- coding: utf-8 -*- from .render.console import ConsoleRender from . import themes def prompt(questions, render=None, answers=None, theme=themes.Default(), raise_keyboard_interrupt=False): render = render or ConsoleRender(theme=theme) answers = answers or {} try: for question in questions: answers[question.name] = render.render(question, answers) return answers except KeyboardInterrupt: if raise_keyboard_interrupt: raise print('') print('Cancelled by user') print('')
from django.db import models from django.contrib.auth.models import User from PIL import Image class Profile(models.Model): user=models.OneToOneField(User,on_delete=models.CASCADE) image=models.ImageField(default='default.jpg',upload_to='profiles_pics') def __str__(self): return f'{self.user.username} Profile' def save(self,force_insert=False, force_update=False, using=None): super().save() img=Image.open(self.image.path) if img.height>250 or img.width>250: output_size=(250,250) img.thumbnail(output_size) img.save(self.image.path)
from .conditional_abunmatch_bin_based import * from .noisy_percentile import * from .engines import cython_bin_free_cam_kernel from .bin_free_cam import conditional_abunmatch
import 'prismjs' import 'prismjs/plugins/line-highlight/prism-line-highlight' import './common/icons.css' import Inferno from 'inferno' import Debugger from './components/Debugger' document.body.removeChild(document.querySelector('#error')) Inferno.render(( <Debugger /> ), document.getElementById('root'))
#include "certificate.h" #include <errno.h> #include <stdint.h> /* SIZE_MAX */ #include <time.h> #include <openssl/asn1.h> #include <sys/socket.h> #include "algorithm.h" #include "config.h" #include "extension.h" #include "log.h" #include "nid.h" #include "reqs_errors.h" #include "str_token.h" #include "thread_var.h" #include "asn1/decode.h" #include "asn1/oid.h" #include "asn1/asn1c/IPAddrBlocks.h" #include "crypto/hash.h" #include "incidence/incidence.h" #include "object/bgpsec.h" #include "object/name.h" #include "object/manifest.h" #include "object/signed_object.h" #include "rrdp/rrdp_loader.h" #include "rsync/rsync.h" /* Just to prevent some line breaking. */ #define GN_URI uniformResourceIdentifier /* * The X509V3_EXT_METHOD that references NID_sinfo_access uses the AIA item. * The SIA's d2i function, therefore, returns AIAs. * They are the same as far as LibreSSL is concerned. */ typedef AUTHORITY_INFO_ACCESS SIGNATURE_INFO_ACCESS; struct ski_arguments { X509 *cert; OCTET_STRING_t *sid; }; struct sia_uri { uint8_t position; struct rpki_uri *uri; }; struct sia_ca_uris { struct sia_uri caRepository; struct sia_uri rpkiNotify; struct sia_uri mft; }; struct bgpsec_ski { X509 *cert; unsigned char **ski_data; }; /* Callback method to fetch repository objects */ typedef int (access_method_exec)(struct sia_ca_uris *); static void sia_ca_uris_init(struct sia_ca_uris *sia_uris) { sia_uris->caRepository.uri = NULL; sia_uris->rpkiNotify.uri = NULL; sia_uris->mft.uri = NULL; } static void sia_ca_uris_cleanup(struct sia_ca_uris *sia_uris) { if (sia_uris->caRepository.uri != NULL) uri_refput(sia_uris->caRepository.uri); if (sia_uris->rpkiNotify.uri != NULL) uri_refput(sia_uris->rpkiNotify.uri); if (sia_uris->mft.uri != NULL) uri_refput(sia_uris->mft.uri); } static void debug_serial_number(BIGNUM *number) { char *number_str; number_str = BN_bn2dec(number); if (number_str == NULL) { val_crypto_err("Could not convert BN to string"); return; } pr_val_debug("serial Number: %s", number_str); free(number_str); } static int validate_serial_number(X509 *cert) { struct validation *state; BIGNUM *number; int error; state = state_retrieve(); if (state == NULL) return -EINVAL; number = ASN1_INTEGER_to_BN(X509_get0_serialNumber(cert), NULL); if (number == NULL) return val_crypto_err("Could not parse certificate serial number"); if (log_val_debug_enabled()) debug_serial_number(number); error = x509stack_store_serial(validation_certstack(state), number); if (error) BN_free(number); return error; } static int validate_signature_algorithm(X509 *cert) { int nid = OBJ_obj2nid(X509_get0_tbs_sigalg(cert)->algorithm); return validate_certificate_signature_algorithm(nid, "Certificate"); } static int validate_issuer(X509 *cert, bool is_ta) { X509_NAME *issuer; struct rfc5280_name *name; int error; issuer = X509_get_issuer_name(cert); if (!is_ta) return validate_issuer_name("Certificate", issuer); /* TODO wait. Shouldn't we check subject == issuer? */ error = x509_name_decode(issuer, "issuer", &name); if (error) return error; pr_val_debug("Issuer: %s", x509_name_commonName(name)); x509_name_put(name); return 0; } /* * Compare public keys, call @diff_alg_cb when the algorithm is different, call * @diff_pk_cb when the public key is different; return 0 if both are equal. */ static int spki_cmp(X509_PUBKEY *tal_spki, X509_PUBKEY *cert_spki, int (*diff_alg_cb)(void), int (*diff_pk_cb)(void)) { ASN1_OBJECT *tal_alg; ASN1_OBJECT *cert_alg; unsigned char const *tal_spk, *cert_spk; int tal_spk_len, cert_spk_len; int ok; ok = X509_PUBKEY_get0_param(&tal_alg, &tal_spk, &tal_spk_len, NULL, tal_spki); if (!ok) return val_crypto_err("X509_PUBKEY_get0_param() 1 returned %d", ok); ok = X509_PUBKEY_get0_param(&cert_alg, &cert_spk, &cert_spk_len, NULL, cert_spki); if (!ok) return val_crypto_err("X509_PUBKEY_get0_param() 2 returned %d", ok); if (OBJ_cmp(tal_alg, cert_alg) != 0) return diff_alg_cb(); if (tal_spk_len != cert_spk_len) return diff_pk_cb(); if (memcmp(tal_spk, cert_spk, cert_spk_len) != 0) return diff_pk_cb(); return 0; } /** Call whenever the public key is different and the subject is the same**/ static int cert_different_pk_err(void) { return 1; } /* * Beware: this function skips a lot (maybe all) RPKI validations for a signed * object, and clearly expects that the signed object has at least one * certificate. * * Allocates @result, don't forget to release it. * * It has been placed here to minimize the risk of misuse. */ static int cert_from_signed_object(struct rpki_uri *uri, uint8_t **result, int *size) { struct signed_object sobj; ANY_t *cert; unsigned char *tmp; int error; error = signed_object_decode(&sobj, uri); if (error) return error; cert = sobj.sdata.decoded->certificates->list.array[0]; tmp = malloc(cert->size); if (tmp == NULL) { signed_object_cleanup(&sobj); return pr_enomem(); } memcpy(tmp, cert->buf, cert->size); *result = tmp; (*size) = cert->size; signed_object_cleanup(&sobj); return 0; } static int check_dup_public_key(bool *duplicated, char const *file, void *arg) { X509 *curr_cert = arg; /* Current cert */ X509 *rcvd_cert; X509_PUBKEY *curr_pk, *rcvd_pk; struct rpki_uri *uri; uint8_t *tmp; int tmp_size; int error; uri = NULL; rcvd_cert = NULL; tmp_size = 0; error = uri_create_rsync_str(&uri, file, strlen(file)); if (error) return error; /* Check if it's '.cer', otherwise treat as a signed object */ if (uri_is_certificate(uri)) { error = certificate_load(uri, &rcvd_cert); if (error) goto free_uri; } else { error = cert_from_signed_object(uri, &tmp, &tmp_size); if (error) goto free_uri; rcvd_cert = d2i_X509(NULL, (const unsigned char **) &tmp, tmp_size); free(tmp); /* Release at once */ if (rcvd_cert == NULL) { error = val_crypto_err("Signed object's '%s' 'certificate' element does not decode into a Certificate", uri_val_get_printable(uri)); goto free_uri; } } curr_pk = X509_get_X509_PUBKEY(curr_cert); if (curr_pk == NULL) { error = val_crypto_err("X509_get_X509_PUBKEY() returned NULL"); goto free_cert; } rcvd_pk = X509_get_X509_PUBKEY(rcvd_cert); if (rcvd_pk == NULL) { error = val_crypto_err("X509_get_X509_PUBKEY() returned NULL"); goto free_cert; } /* * The function response will be: * < 0 if there's an error * = 0 if the PKs are equal * > 0 if the PKs are different */ error = spki_cmp(curr_pk, rcvd_pk, cert_different_pk_err, cert_different_pk_err); if (error < 0) goto free_cert; /* No error, a positive value means the name is duplicated */ if (error) (*duplicated) = true; error = 0; free_cert: X509_free(rcvd_cert); free_uri: uri_refput(uri); return error; } static int validate_subject(X509 *cert) { struct validation *state; struct rfc5280_name *name; int error; state = state_retrieve(); if (state == NULL) return -EINVAL; error = x509_name_decode(X509_get_subject_name(cert), "subject", &name); if (error) return error; pr_val_debug("Subject: %s", x509_name_commonName(name)); error = x509stack_store_subject(validation_certstack(state), name, check_dup_public_key, cert); x509_name_put(name); return error; } static int root_different_alg_err(void) { return pr_val_err("TAL's public key algorithm is different than the root certificate's public key algorithm."); } static int root_different_pk_err(void) { return pr_val_err("TAL's public key is different than the root certificate's public key."); } static int validate_spki(X509_PUBKEY *cert_spki) { struct validation *state; struct tal *tal; X509_PUBKEY *tal_spki; unsigned char const *_tal_spki; size_t _tal_spki_len; state = state_retrieve(); if (state == NULL) return -EINVAL; tal = validation_tal(state); if (tal == NULL) pr_crit("Validation state has no TAL."); /* * We have a problem at this point: * * RFC 8630 says "The public key used to verify the trust anchor MUST be * the same as the subjectPublicKeyInfo in the CA certificate and in the * TAL." * * It seems that libcrypto decodes the Subject Public Key Info (SPKI) * and gives us the Subject Public Key (SPK) instead. So we can't just * compare the two keys just like that. * * Luckily, the only other component of the SPKI is the algorithm * identifier. So doing a field-by-field comparison is not too much * trouble. We'll have to decode the TAL's SPKI though. * * Reminder: "X509_PUBKEY" and "Subject Public Key Info" are synonyms. */ fnstack_push(tal_get_file_name(tal)); tal_get_spki(tal, &_tal_spki, &_tal_spki_len); tal_spki = d2i_X509_PUBKEY(NULL, &_tal_spki, _tal_spki_len); fnstack_pop(); if (tal_spki == NULL) { op_crypto_err("The TAL's public key cannot be decoded"); goto fail1; } if (spki_cmp(tal_spki, cert_spki, root_different_alg_err, root_different_pk_err) != 0) goto fail2; X509_PUBKEY_free(tal_spki); validation_pubkey_valid(state); return 0; fail2: X509_PUBKEY_free(tal_spki); fail1: validation_pubkey_invalid(state); return -EINVAL; } /* * RFC 7935 Section 3: * "The RSA key pairs used to compute the signatures MUST have a * 2048-bit modulus and a public exponent (e) of 65,537." */ static int validate_subject_public_key(X509_PUBKEY *pubkey) { #define MODULUS 2048 #define EXPONENT "65537" const RSA *rsa; const BIGNUM *exp; char *exp_str; int modulus; int error; rsa = EVP_PKEY_get0_RSA(X509_PUBKEY_get0(pubkey)); if (rsa == NULL) return val_crypto_err("EVP_PKEY_get0_RSA() returned NULL"); modulus = RSA_bits(rsa); if (modulus != MODULUS) return pr_val_err("Certificate's subjectPublicKey (RSAPublicKey) modulus is %d bits, not %d bits.", modulus, MODULUS); RSA_get0_key(rsa, NULL, &exp, NULL); if (exp == NULL) return pr_val_err("Certificate's subjectPublicKey (RSAPublicKey) exponent isn't set, must be " EXPONENT " bits."); exp_str = BN_bn2dec(exp); if (exp_str == NULL) return val_crypto_err("Couldn't get subjectPublicKey exponent string"); if (strcmp(EXPONENT, exp_str) != 0) { error = pr_val_err("Certificate's subjectPublicKey (RSAPublicKey) exponent is %s, must be " EXPONENT " bits.", exp_str); free(exp_str); return error; } free(exp_str); return 0; #undef EXPONENT #undef MODULUS } static int validate_public_key(X509 *cert, enum cert_type type) { X509_PUBKEY *pubkey; X509_ALGOR *pa; ASN1_OBJECT *alg; int ok; int error; /* Reminder: X509_PUBKEY is the same as SubjectPublicKeyInfo. */ pubkey = X509_get_X509_PUBKEY(cert); if (pubkey == NULL) return val_crypto_err("X509_get_X509_PUBKEY() returned NULL"); ok = X509_PUBKEY_get0_param(&alg, NULL, NULL, &pa, pubkey); if (!ok) return val_crypto_err("X509_PUBKEY_get0_param() returned %d", ok); if (type == BGPSEC) return validate_certificate_public_key_algorithm_bgpsec(pa); error = validate_certificate_public_key_algorithm(pa); if (error) return error; error = validate_subject_public_key(pubkey); if (error) return error; /* * BTW: WTF. About that algorithm: * * RFC 6485: "The value for the associated parameters from that clause * [RFC4055] MUST also be used for the parameters field." * RFC 4055: "Implementations MUST accept the parameters being absent as * well as present." * * Either the RFCs found a convoluted way of saying nothing, or I'm not * getting the message. */ if (type == TA) { error = validate_spki(pubkey); if (error) return error; } return 0; } int certificate_validate_rfc6487(X509 *cert, enum cert_type type) { int error; /* * I'm simply assuming that libcrypto implements RFC 5280. (I mean, it's * not really stated anywhere AFAIK, but since OpenSSL is supposedly the * quintessential crypto lib implementation, and RFC 5280 is supposedly * the generic certificate RFC, it's fair to say it does a well enough * job for all practical purposes.) * * But it's obvious that we can't assume that LibreSSL implements RFC * 6487. It clearly doesn't. * * So here we go. */ /* rfc6487#section-4.1 */ if (X509_get_version(cert) != 2) return pr_val_err("Certificate version is not v3."); /* rfc6487#section-4.2 */ error = validate_serial_number(cert); if (error) return error; /* rfc6487#section-4.3 */ error = validate_signature_algorithm(cert); if (error) return error; /* rfc6487#section-4.4 */ error = validate_issuer(cert, type == TA); if (error) return error; /* * rfc6487#section-4.5 * * "An issuer SHOULD use a different subject name if the subject's * key pair has changed" (it's a SHOULD, so [for now] avoid validation) */ error = validate_subject(cert); if (error) return error; /* rfc6487#section-4.6 */ /* libcrypto already does this. */ /* rfc6487#section-4.7 */ /* Fragment of rfc8630#section-2.3 */ error = validate_public_key(cert, type); if (error) return error; /* We'll validate extensions later. */ return 0; } struct progress { size_t offset; size_t remaining; }; /** * Skip the "T" part of a TLV. */ static void skip_t(ANY_t *content, struct progress *p, unsigned int tag) { /* * BTW: I made these errors critical because the signedData is supposed * to be validated by this point. */ if (content->buf[p->offset] != tag) pr_crit("Expected tag 0x%x, got 0x%x", tag, content->buf[p->offset]); if (p->remaining == 0) pr_crit("Buffer seems to be truncated"); p->offset++; p->remaining--; } /** * Skip the "TL" part of a TLV. */ static void skip_tl(ANY_t *content, struct progress *p, unsigned int tag) { ssize_t len_len; /* Length of the length field */ ber_tlv_len_t value_len; /* Length of the value */ skip_t(content, p, tag); len_len = ber_fetch_length(true, &content->buf[p->offset], p->remaining, &value_len); if (len_len == -1) pr_crit("Could not decipher length (Cause is unknown)"); if (len_len == 0) pr_crit("Buffer seems to be truncated"); p->offset += len_len; p->remaining -= len_len; } static void skip_tlv(ANY_t *content, struct progress *p, unsigned int tag) { int is_constructed; int skip; is_constructed = BER_TLV_CONSTRUCTED(&content->buf[p->offset]); skip_t(content, p, tag); skip = ber_skip_length(NULL, is_constructed, &content->buf[p->offset], p->remaining); if (skip == -1) pr_crit("Could not skip length (Cause is unknown)"); if (skip == 0) pr_crit("Buffer seems to be truncated"); p->offset += skip; p->remaining -= skip; } /** * A structure that points to the LV part of a signedAttrs TLV. */ struct encoded_signedAttrs { const uint8_t *buffer; ber_tlv_len_t size; }; static void find_signedAttrs(ANY_t *signedData, struct encoded_signedAttrs *result) { #define INTEGER_TAG 0x02 #define SEQUENCE_TAG 0x30 #define SET_TAG 0x31 struct progress p; ssize_t len_len; /* Reference: rfc5652-12.1.asn1 */ p.offset = 0; p.remaining = signedData->size; /* SignedData: SEQUENCE */ skip_tl(signedData, &p, SEQUENCE_TAG); /* SignedData.version: CMSVersion -> INTEGER */ skip_tlv(signedData, &p, INTEGER_TAG); /* SignedData.digestAlgorithms: DigestAlgorithmIdentifiers -> SET */ skip_tlv(signedData, &p, SET_TAG); /* SignedData.encapContentInfo: EncapsulatedContentInfo -> SEQUENCE */ skip_tlv(signedData, &p, SEQUENCE_TAG); /* SignedData.certificates: CertificateSet -> SET */ skip_tlv(signedData, &p, 0xA0); /* SignedData.signerInfos: SignerInfos -> SET OF SEQUENCE */ skip_tl(signedData, &p, SET_TAG); skip_tl(signedData, &p, SEQUENCE_TAG); /* SignedData.signerInfos.version: CMSVersion -> INTEGER */ skip_tlv(signedData, &p, INTEGER_TAG); /* * SignedData.signerInfos.sid: SignerIdentifier -> CHOICE -> always * subjectKeyIdentifier, which is a [0]. */ skip_tlv(signedData, &p, 0x80); /* SignedData.signerInfos.digestAlgorithm: DigestAlgorithmIdentifier * -> AlgorithmIdentifier -> SEQUENCE */ skip_tlv(signedData, &p, SEQUENCE_TAG); /* SignedData.signerInfos.signedAttrs: SignedAttributes -> SET */ /* We will need to replace the tag 0xA0 with 0x31, so skip it as well */ skip_t(signedData, &p, 0xA0); result->buffer = &signedData->buf[p.offset]; len_len = ber_fetch_length(true, result->buffer, p.remaining, &result->size); if (len_len == -1) pr_crit("Could not decipher length (Cause is unknown)"); if (len_len == 0) pr_crit("Buffer seems to be truncated"); result->size += len_len; } /* * TODO (next iteration) there exists a thing called "PKCS7_NOVERIFY", which * skips unnecessary validations when using the PKCS7 API. Maybe the methods * we're using have something similar. */ int certificate_validate_signature(X509 *cert, ANY_t *signedData, SignatureValue_t *signature) { static const uint8_t EXPLICIT_SET_OF_TAG = 0x31; X509_PUBKEY *public_key; EVP_MD_CTX *ctx; struct encoded_signedAttrs signedAttrs; int error; public_key = X509_get_X509_PUBKEY(cert); if (public_key == NULL) return val_crypto_err("Certificate seems to lack a public key"); /* Create the Message Digest Context */ ctx = EVP_MD_CTX_create(); if (ctx == NULL) return val_crypto_err("EVP_MD_CTX_create() error"); if (1 != EVP_DigestVerifyInit(ctx, NULL, EVP_sha256(), NULL, X509_PUBKEY_get0(public_key))) { error = val_crypto_err("EVP_DigestVerifyInit() error"); goto end; } /* * When the [signedAttrs] field is present * (...), * the result is the message * digest of the complete DER encoding of the SignedAttrs value * contained in the signedAttrs field. * (...) * A separate encoding * of the signedAttrs field is performed for message digest calculation. * The IMPLICIT [0] tag in the signedAttrs is not used for the DER * encoding, rather an EXPLICIT SET OF tag is used. That is, the DER * encoding of the EXPLICIT SET OF tag, rather than of the IMPLICIT [0] * tag, MUST be included in the message digest calculation along with * the length and content octets of the SignedAttributes value. * (https://tools.ietf.org/html/rfc5652#section-5.4) * * FYI: IMPLICIT [0] is 0xA0, and EXPLICIT SET OF is 0x31. * * I can officially declare that these requirements are a gargantuan * pain in the ass. Through the validation, we need access to the * signedAttrs thingo in both encoded and decoded versions. * (We need the decoded version for the sake of profile validation * during validate_signed_attrs(), and the encoded version to check * the signature of the SO right here.) * Getting the encoded version is the problem. We have two options: * * 1. Re-encode the decoded version. * 2. Extract the encoded version from the original BER SignedData. * * The first one sounded less efficient but more straightforward, but * I couldn't pull it off because there's some memory bug with asn1c's * encoding function that core dumps the fuck out of everything. It's * caused by undefined behavior that triggers who knows where. * * There's another problem with that approach: If we DER-encode the * signedAttrs, we have no guarantee that the signature will match * because of the very real possibility that whoever signed used BER * instead. * * One drawback for the second option is that obviously there's no API * for it. asn1c encodes and decodes; there's no method for extracting * a particular encoded object out of an encoded container. We need to * do the parsing ourselves. But it's not that bad because of of * ber_fetch_length() and ber_skip_length(). * * Second option it is. */ find_signedAttrs(signedData, &signedAttrs); error = EVP_DigestVerifyUpdate(ctx, &EXPLICIT_SET_OF_TAG, sizeof(EXPLICIT_SET_OF_TAG)); if (1 != error) { error = val_crypto_err("EVP_DigestVerifyInit() error"); goto end; } error = EVP_DigestVerifyUpdate(ctx, signedAttrs.buffer, signedAttrs.size); if (1 != error) { error = val_crypto_err("EVP_DigestVerifyInit() error"); goto end; } if (1 != EVP_DigestVerifyFinal(ctx, signature->buf, signature->size)) { error = val_crypto_err("Signed Object's signature is invalid"); goto end; } error = 0; end: EVP_MD_CTX_free(ctx); return error; } int certificate_load(struct rpki_uri *uri, X509 **result) { X509 *cert = NULL; BIO *bio; int error; bio = BIO_new(BIO_s_file()); if (bio == NULL) return val_crypto_err("BIO_new(BIO_s_file()) returned NULL"); if (BIO_read_filename(bio, uri_get_local(uri)) <= 0) { error = val_crypto_err("Error reading certificate"); goto end; } cert = d2i_X509_bio(bio, NULL); if (cert == NULL) { error = val_crypto_err("Error parsing certificate"); goto end; } *result = cert; error = 0; end: BIO_free(bio); return error; } /* * Allocates a clone of @original_crl and pushes it to @crls. * * Don't forget to pop from @crls and release the popped CRL. */ static int update_crl_time(STACK_OF(X509_CRL) *crls, X509_CRL *original_crl) { ASN1_TIME *tm; X509_CRL *clone; time_t t; int error; error = get_current_time(&t); if (error) return error; /* * Yes, this is an awful hack. The other options were: * - Use X509_V_FLAG_NO_CHECK_TIME parameter, but this avoids also the * time check for the certificate. * - Avoid whole CRL check, but since we don't implement the * certificate chain validation, we can't assure that the CRL has * only the nextUpdate field wrong (maybe there are other invalid * things). */ tm = ASN1_TIME_adj(NULL, t, 0, 60); if (tm == NULL) return pr_val_err("Crypto function ASN1_TIME_adj() returned error"); clone = X509_CRL_dup(original_crl); if (clone == NULL) { ASN1_STRING_free(tm); return pr_enomem(); } X509_CRL_set1_nextUpdate(clone, tm); ASN1_STRING_free(tm); error = sk_X509_CRL_push(crls, clone); if (error <= 0) { X509_CRL_free(clone); return val_crypto_err("Error calling sk_X509_CRL_push()"); } return 0; } /* * Retry certificate validation without CRL time validation. */ static int verify_cert_crl_stale(struct validation *state, X509 *cert, STACK_OF(X509_CRL) *crls) { X509_STORE_CTX *ctx; X509_CRL *original_crl, *clone; int error; int ok; ctx = X509_STORE_CTX_new(); if (ctx == NULL) { val_crypto_err("X509_STORE_CTX_new() returned NULL"); return -EINVAL; } /* Returns 0 or 1 , all callers test ! only. */ ok = X509_STORE_CTX_init(ctx, validation_store(state), cert, NULL); if (!ok) { error = val_crypto_err("X509_STORE_CTX_init() returned %d", ok); goto release_ctx; } original_crl = sk_X509_CRL_pop(crls); error = update_crl_time(crls, original_crl); if (error) goto push_original; X509_STORE_CTX_trusted_stack(ctx, certstack_get_x509s(validation_certstack(state))); X509_STORE_CTX_set0_crls(ctx, crls); ok = X509_verify_cert(ctx); if (ok > 0) { error = 0; /* Happy path */ goto pop_clone; } error = X509_STORE_CTX_get_error(ctx); if (error) error = pr_val_err("Certificate validation failed: %s", X509_verify_cert_error_string(error)); else error = val_crypto_err("Certificate validation failed: %d", ok); pop_clone: clone = sk_X509_CRL_pop(crls); if (clone == NULL) error = pr_val_err("Error calling sk_X509_CRL_pop()"); else X509_CRL_free(clone); push_original: /* Try to return to the "regular" CRL chain */ ok = sk_X509_CRL_push(crls, original_crl); if (ok <= 0) error = val_crypto_err("Could not return CRL to a CRL stack"); release_ctx: X509_STORE_CTX_free(ctx); return error; } int certificate_validate_chain(X509 *cert, STACK_OF(X509_CRL) *crls) { /* Reference: openbsd/src/usr.bin/openssl/verify.c */ struct validation *state; X509_STORE_CTX *ctx; int ok; int error; if (crls == NULL) return 0; /* Certificate is TA; no chain validation needed. */ state = state_retrieve(); if (state == NULL) return -EINVAL; ctx = X509_STORE_CTX_new(); if (ctx == NULL) { val_crypto_err("X509_STORE_CTX_new() returned NULL"); return -EINVAL; } /* Returns 0 or 1 , all callers test ! only. */ ok = X509_STORE_CTX_init(ctx, validation_store(state), cert, NULL); if (!ok) { val_crypto_err("X509_STORE_CTX_init() returned %d", ok); goto abort; } X509_STORE_CTX_trusted_stack(ctx, certstack_get_x509s(validation_certstack(state))); X509_STORE_CTX_set0_crls(ctx, crls); /* * HERE'S THE MEAT OF LIBCRYPTO'S VALIDATION. * * Can return negative codes, all callers do <= 0. * * Debugging BTW: If you're looking for ctx->verify, * it might be internal_verify() from x509_vfy.c. */ ok = X509_verify_cert(ctx); if (ok <= 0) { /* * ARRRRGGGGGGGGGGGGG * Do not use val_crypto_err() here; for some reason the proper * error code is stored in the context. */ error = X509_STORE_CTX_get_error(ctx); if (error) { if (error != X509_V_ERR_CRL_HAS_EXPIRED) { pr_val_err("Certificate validation failed: %s", X509_verify_cert_error_string(error)); goto abort; } if (incidence(INID_CRL_STALE, "CRL is stale/expired")) goto abort; X509_STORE_CTX_free(ctx); if (incidence_get_action(INID_CRL_STALE) == INAC_WARN) pr_val_info("Re-validating avoiding CRL time check"); return verify_cert_crl_stale(state, cert, crls); } else { /* * ...But don't trust X509_STORE_CTX_get_error() either. * That said, there's not much to do about !error, * so hope for the best. */ val_crypto_err("Certificate validation failed: %d", ok); } goto abort; } X509_STORE_CTX_free(ctx); return 0; abort: X509_STORE_CTX_free(ctx); return -EINVAL; } static int handle_ip_extension(X509_EXTENSION *ext, struct resources *resources) { ASN1_OCTET_STRING *string; struct IPAddrBlocks *blocks; OCTET_STRING_t *family; int i; int error; string = X509_EXTENSION_get_data(ext); error = asn1_decode(string->data, string->length, &asn_DEF_IPAddrBlocks, (void **) &blocks, true, false); if (error) return error; /* * rfc3779#section-2.2.3.3, rfc6487#section-4.8.10: * We're expecting either one element (IPv4 or IPv6) or two elements * (IPv4 then IPv6). */ switch (blocks->list.count) { case 1: break; case 2: family = &blocks->list.array[0]->addressFamily; if (get_addr_family(family) != AF_INET) { error = pr_val_err("First IP address block listed is not v4."); goto end; } family = &blocks->list.array[1]->addressFamily; if (get_addr_family(family) != AF_INET6) { error = pr_val_err("Second IP address block listed is not v6."); goto end; } break; default: error = pr_val_err("Got %d IP address blocks Expected; 1 or 2 expected.", blocks->list.count); goto end; } for (i = 0; i < blocks->list.count && !error; i++) error = resources_add_ip(resources, blocks->list.array[i]); end: ASN_STRUCT_FREE(asn_DEF_IPAddrBlocks, blocks); return error; } static int handle_asn_extension(X509_EXTENSION *ext, struct resources *resources, bool allow_inherit) { ASN1_OCTET_STRING *string; struct ASIdentifiers *ids; int error; string = X509_EXTENSION_get_data(ext); error = asn1_decode(string->data, string->length, &asn_DEF_ASIdentifiers, (void **) &ids, true, false); if (error) return error; error = resources_add_asn(resources, ids, allow_inherit); ASN_STRUCT_FREE(asn_DEF_ASIdentifiers, ids); return error; } static int __certificate_get_resources(X509 *cert, struct resources *resources, int addr_nid, int asn_nid, int bad_addr_nid, int bad_asn_nid, char const *policy_rfc, char const *bad_ext_rfc, bool allow_asn_inherit) { X509_EXTENSION *ext; int nid; int i; int error; bool ip_ext_found = false; bool asn_ext_found = false; /* Reference: X509_get_ext_d2i */ /* rfc6487#section-2 */ for (i = 0; i < X509_get_ext_count(cert); i++) { ext = X509_get_ext(cert, i); nid = OBJ_obj2nid(X509_EXTENSION_get_object(ext)); if (nid == addr_nid) { if (ip_ext_found) return pr_val_err("Multiple IP extensions found."); if (!X509_EXTENSION_get_critical(ext)) return pr_val_err("The IP extension is not marked as critical."); pr_val_debug("IP {"); error = handle_ip_extension(ext, resources); pr_val_debug("}"); ip_ext_found = true; if (error) return error; } else if (nid == asn_nid) { if (asn_ext_found) return pr_val_err("Multiple AS extensions found."); if (!X509_EXTENSION_get_critical(ext)) return pr_val_err("The AS extension is not marked as critical."); pr_val_debug("ASN {"); error = handle_asn_extension(ext, resources, allow_asn_inherit); pr_val_debug("}"); asn_ext_found = true; if (error) return error; } else if (nid == bad_addr_nid) { return pr_val_err("Certificate has an RFC%s policy, but contains an RFC%s IP extension.", policy_rfc, bad_ext_rfc); } else if (nid == bad_asn_nid) { return pr_val_err("Certificate has an RFC%s policy, but contains an RFC%s ASN extension.", policy_rfc, bad_ext_rfc); } } if (!ip_ext_found && !asn_ext_found) return pr_val_err("Certificate lacks both IP and AS extension."); return 0; } int certificate_get_resources(X509 *cert, struct resources *resources, enum cert_type type) { enum rpki_policy policy; policy = resources_get_policy(resources); switch (policy) { case RPKI_POLICY_RFC6484: return __certificate_get_resources(cert, resources, NID_sbgp_ipAddrBlock, NID_sbgp_autonomousSysNum, nid_ipAddrBlocksv2(), nid_autonomousSysIdsv2(), "6484", "8360", type != BGPSEC); case RPKI_POLICY_RFC8360: return __certificate_get_resources(cert, resources, nid_ipAddrBlocksv2(), nid_autonomousSysIdsv2(), NID_sbgp_ipAddrBlock, NID_sbgp_autonomousSysNum, "8360", "6484", type != BGPSEC); } pr_crit("Unknown policy: %u", policy); } static bool is_rsync(ASN1_IA5STRING *uri) { static char const *const PREFIX = "rsync://"; size_t prefix_len = strlen(PREFIX); return (uri->length >= prefix_len) ? (strncmp((char *) uri->data, PREFIX, strlen(PREFIX)) == 0) : false; } static bool is_rsync_uri(GENERAL_NAME *name) { return name->type == GEN_URI && is_rsync(name->d.GN_URI); } static int handle_rpkiManifest(struct rpki_uri *uri, uint8_t pos, void *arg) { struct sia_uri *mft = arg; mft->position = pos; mft->uri = uri; uri_refget(uri); return 0; } static int handle_caRepository(struct rpki_uri *uri, uint8_t pos, void *arg) { struct sia_uri *repo = arg; pr_val_debug("caRepository: %s", uri_val_get_printable(uri)); repo->position = pos; repo->uri = uri; uri_refget(uri); return 0; } static int handle_rpkiNotify(struct rpki_uri *uri, uint8_t pos, void *arg) { struct sia_uri *notify = arg; pr_val_debug("rpkiNotify: %s", uri_val_get_printable(uri)); notify->position = pos; notify->uri = uri; uri_refget(uri); return 0; } static int handle_signedObject(struct rpki_uri *uri, uint8_t pos, void *arg) { struct certificate_refs *refs = arg; pr_val_debug("signedObject: %s", uri_val_get_printable(uri)); refs->signedObject = uri; uri_refget(uri); return 0; } static int handle_bc(X509_EXTENSION *ext, void *arg) { BASIC_CONSTRAINTS *bc; int error; bc = X509V3_EXT_d2i(ext); if (bc == NULL) return cannot_decode(ext_bc()); /* * 'The issuer determines whether the "cA" boolean is set.' * ................................. Uh-huh. So nothing then. * Well, libcrypto should do the RFC 5280 thing with it anyway. */ error = (bc->pathlen == NULL) ? 0 : pr_val_err("%s extension contains a Path Length Constraint.", ext_bc()->name); BASIC_CONSTRAINTS_free(bc); return error; } static int handle_ski_ca(X509_EXTENSION *ext, void *arg) { ASN1_OCTET_STRING *ski; int error; ski = X509V3_EXT_d2i(ext); if (ski == NULL) return cannot_decode(ext_ski()); error = validate_public_key_hash(arg, ski); ASN1_OCTET_STRING_free(ski); return error; } static int handle_ski_ee(X509_EXTENSION *ext, void *arg) { struct ski_arguments *args; ASN1_OCTET_STRING *ski; OCTET_STRING_t *sid; int error; ski = X509V3_EXT_d2i(ext); if (ski == NULL) return cannot_decode(ext_ski()); args = arg; error = validate_public_key_hash(args->cert, ski); if (error) goto end; /* rfc6488#section-2.1.6.2 */ /* rfc6488#section-3.1.c 2/2 */ sid = args->sid; if (ski->length != sid->size || memcmp(ski->data, sid->buf, sid->size) != 0) { error = pr_val_err("The EE certificate's subjectKeyIdentifier does not equal the Signed Object's sid."); } end: ASN1_OCTET_STRING_free(ski); return error; } static int handle_ski_bgpsec(X509_EXTENSION *ext, void *arg) { ASN1_OCTET_STRING *ski; struct bgpsec_ski *params; unsigned char *tmp; int error; ski = X509V3_EXT_d2i(ext); if (ski == NULL) return cannot_decode(ext_ski()); params = arg; error = validate_public_key_hash(params->cert, ski); if (error) goto end; tmp = malloc(ski->length + 1); if (tmp == NULL) goto end; memcpy(tmp, ski->data, ski->length); tmp[ski->length] = '\0'; *(params->ski_data) = tmp; end: ASN1_OCTET_STRING_free(ski); return error; } static int handle_aki_ta(X509_EXTENSION *ext, void *arg) { struct AUTHORITY_KEYID_st *aki; ASN1_OCTET_STRING *ski; int error; aki = X509V3_EXT_d2i(ext); if (aki == NULL) return cannot_decode(ext_aki()); if (aki->keyid == NULL) { error = pr_val_err("The '%s' extension lacks a keyIdentifier.", ext_aki()->name); goto revert_aki; } ski = X509_get_ext_d2i(arg, NID_subject_key_identifier, NULL, NULL); if (ski == NULL) { pr_val_err("Certificate lacks the '%s' extension.", ext_ski()->name); error = -ESRCH; goto revert_aki; } if (ASN1_OCTET_STRING_cmp(aki->keyid, ski) != 0) { error = pr_val_err("The '%s' does not equal the '%s'.", ext_aki()->name, ext_ski()->name); goto revert_ski; } error = 0; revert_ski: ASN1_BIT_STRING_free(ski); revert_aki: AUTHORITY_KEYID_free(aki); return error; } static int handle_ku(X509_EXTENSION *ext, unsigned char byte1) { /* * About the key usage string: At time of writing, it's 9 bits long. * But zeroized rightmost bits can be omitted. * This implementation assumes that the ninth bit should always be zero. */ ASN1_BIT_STRING *ku; unsigned char data[2]; int error = 0; ku = X509V3_EXT_d2i(ext); if (ku == NULL) return cannot_decode(ext_ku()); if (ku->length == 0) { error = pr_val_err("%s bit string has no enabled bits.", ext_ku()->name); goto end; } memset(data, 0, sizeof(data)); memcpy(data, ku->data, ku->length); if (ku->data[0] != byte1) { error = pr_val_err("Illegal key usage flag string: %d%d%d%d%d%d%d%d%d", !!(ku->data[0] & 0x80u), !!(ku->data[0] & 0x40u), !!(ku->data[0] & 0x20u), !!(ku->data[0] & 0x10u), !!(ku->data[0] & 0x08u), !!(ku->data[0] & 0x04u), !!(ku->data[0] & 0x02u), !!(ku->data[0] & 0x01u), !!(ku->data[1] & 0x80u)); goto end; } end: ASN1_BIT_STRING_free(ku); return error; } static int handle_ku_ca(X509_EXTENSION *ext, void *arg) { return handle_ku(ext, 0x06); } static int handle_ku_ee(X509_EXTENSION *ext, void *arg) { return handle_ku(ext, 0x80); } static int handle_cdp(X509_EXTENSION *ext, void *arg) { struct certificate_refs *refs = arg; STACK_OF(DIST_POINT) *crldp; DIST_POINT *dp; GENERAL_NAMES *names; GENERAL_NAME *name; int i; int error = 0; char const *error_msg; crldp = X509V3_EXT_d2i(ext); if (crldp == NULL) return cannot_decode(ext_cdp()); if (sk_DIST_POINT_num(crldp) != 1) { error = pr_val_err("The %s extension has %d distribution points. (1 expected)", ext_cdp()->name, sk_DIST_POINT_num(crldp)); goto end; } dp = sk_DIST_POINT_value(crldp, 0); if (dp->CRLissuer != NULL) { error_msg = "has a CRLIssuer field"; goto dist_point_error; } if (dp->reasons != NULL) { error_msg = "has a Reasons field"; goto dist_point_error; } if (dp->distpoint == NULL) { error_msg = "lacks a distributionPoint field"; goto dist_point_error; } /* Bleargh. There's no enum. 0 is fullname, 1 is relativename. */ switch (dp->distpoint->type) { case 0: break; case 1: error_msg = "has a relative name"; goto dist_point_error; default: error_msg = "has an unknown type of name"; goto dist_point_error; } names = dp->distpoint->name.fullname; for (i = 0; i < sk_GENERAL_NAME_num(names); i++) { name = sk_GENERAL_NAME_value(names, i); if (is_rsync_uri(name)) { /* * Since we're parsing and validating the manifest's CRL * at some point, I think that all we need to do now is * compare this CRL URI to that one's. * * But there is a problem: * The manifest's CRL might not have been parsed at this * point. In fact, it's guaranteed to not have been * parsed if the certificate we're validating is the EE * certificate of the manifest itself. * * So we will store the URI in @refs, and validate it * later. */ error = ia5s2string(name->d.GN_URI, &refs->crldp); goto end; } } error_msg = "lacks an RSYNC URI"; dist_point_error: error = pr_val_err("The %s extension's distribution point %s.", ext_cdp()->name, error_msg); end: sk_DIST_POINT_pop_free(crldp, DIST_POINT_free); return error; } /** * The RFC does not explain AD validation very well. This is personal * interpretation, influenced by Tim Bruijnzeels's response * (https://mailarchive.ietf.org/arch/msg/sidr/4ycmff9jEU4VU9gGK5RyhZ7JYsQ) * (I'm being a bit more lax than he suggested.) * * 1. Only one NID needs to be searched at a time. (This is currently somewhat * of a coincidence, and will probably be superseded at some point. But I'm * not going to complicate this until it's necessary.) * 2. The NID MUST be found, otherwise the certificate is invalid. * 3. The NID can be found more than once. * 4. All access descriptions that match the NID must be URLs. * 5. Precisely one of those matches will be an RSYNC URL, and it's the only one * we are required to support. * (I would have gone with "at least one of those matches", but I don't know * what to do with the other ones.) * 6. Other access descriptions that do not match the NID are allowed and * supposed to be ignored. * 7. Other access descriptions that match the NID but do not have RSYNC URIs * are also allowed, and also supposed to be ignored. */ static int handle_ad(char const *ia_name, SIGNATURE_INFO_ACCESS *ia, char const *ad_name, int ad_nid, int uri_flags, bool required, int (*cb)(struct rpki_uri *, uint8_t, void *), void *arg) { # define AD_METHOD ((uri_flags & URI_VALID_RSYNC) == URI_VALID_RSYNC ? \ "RSYNC" : \ (((uri_flags & URI_VALID_HTTPS) == URI_VALID_HTTPS) ? \ "HTTPS" : "RSYNC/HTTPS")) ACCESS_DESCRIPTION *ad; struct rpki_uri *uri; bool found = false; unsigned int i; int error; for (i = 0; i < sk_ACCESS_DESCRIPTION_num(ia); i++) { ad = sk_ACCESS_DESCRIPTION_value(ia, i); if (OBJ_obj2nid(ad->method) == ad_nid) { error = uri_create_ad(&uri, ad, uri_flags); switch (error) { case 0: break; case ENOTRSYNC: continue; case ENOTHTTPS: continue; case ENOTSUPPORTED: continue; default: return error; } if (found) { uri_refput(uri); return pr_val_err("Extension '%s' has multiple '%s' %s URIs.", ia_name, ad_name, AD_METHOD); } error = cb(uri, i, arg); if (error) { uri_refput(uri); return error; } uri_refput(uri); found = true; } } if (required && !found) { pr_val_err("Extension '%s' lacks a '%s' valid %s URI.", ia_name, ad_name, AD_METHOD); return -ESRCH; } return 0; } static int handle_caIssuers(struct rpki_uri *uri, uint8_t pos, void *arg) { struct certificate_refs *refs = arg; /* * Bringing the parent certificate's URI all the way * over here is too much trouble, so do the handle_cdp() * hack. */ refs->caIssuers = uri; uri_refget(uri); return 0; } static int handle_aia(X509_EXTENSION *ext, void *arg) { AUTHORITY_INFO_ACCESS *aia; int error; aia = X509V3_EXT_d2i(ext); if (aia == NULL) return cannot_decode(ext_aia()); error = handle_ad("AIA", aia, "caIssuers", NID_ad_ca_issuers, URI_VALID_RSYNC, true, handle_caIssuers, arg); AUTHORITY_INFO_ACCESS_free(aia); return error; } static int handle_sia_ca(X509_EXTENSION *ext, void *arg) { SIGNATURE_INFO_ACCESS *sia; struct sia_ca_uris *uris = arg; int error; sia = X509V3_EXT_d2i(ext); if (sia == NULL) return cannot_decode(ext_sia()); /* rsync, still the preferred and required */ error = handle_ad("SIA", sia, "caRepository", NID_caRepository, URI_VALID_RSYNC, true, handle_caRepository, &uris->caRepository); if (error) goto end; /* HTTPS RRDP */ error = handle_ad("SIA", sia, "rpkiNotify", nid_rpkiNotify(), URI_VALID_HTTPS | URI_USE_RRDP_WORKSPACE, false, handle_rpkiNotify, &uris->rpkiNotify); if (error) goto end; /* * Store the manifest URI in @mft. * (We won't actually touch the manifest until we know the certificate * is fully valid.) */ error = handle_ad("SIA", sia, "rpkiManifest", nid_rpkiManifest(), URI_VALID_RSYNC, true, handle_rpkiManifest, &uris->mft); end: AUTHORITY_INFO_ACCESS_free(sia); return error; } static int handle_sia_ee(X509_EXTENSION *ext, void *arg) { SIGNATURE_INFO_ACCESS *sia; int error; sia = X509V3_EXT_d2i(ext); if (sia == NULL) return cannot_decode(ext_sia()); error = handle_ad("SIA", sia, "signedObject", nid_signedObject(), URI_VALID_RSYNC, true, handle_signedObject, arg); AUTHORITY_INFO_ACCESS_free(sia); return error; } static int handle_cp(X509_EXTENSION *ext, void *arg) { enum rpki_policy *policy = arg; CERTIFICATEPOLICIES *cp; POLICYINFO *pi; POLICYQUALINFO *pqi; int error, nid_cp, nid_qt_cps, pqi_num; error = 0; cp = X509V3_EXT_d2i(ext); if (cp == NULL) return cannot_decode(ext_cp()); if (sk_POLICYINFO_num(cp) != 1) { error = pr_val_err("The %s extension has %d policy information's. (1 expected)", ext_cp()->name, sk_POLICYINFO_num(cp)); goto end; } /* rfc7318#section-2 and consider rfc8360#section-4.2.1 */ pi = sk_POLICYINFO_value(cp, 0); nid_cp = OBJ_obj2nid(pi->policyid); if (nid_cp == nid_certPolicyRpki()) { if (policy != NULL) *policy = RPKI_POLICY_RFC6484; } else if (nid_cp == nid_certPolicyRpkiV2()) { pr_val_debug("Found RFC8360 policy!"); if (policy != NULL) *policy = RPKI_POLICY_RFC8360; } else { error = pr_val_err("Invalid certificate policy OID, isn't 'id-cp-ipAddr-asNumber' nor 'id-cp-ipAddr-asNumber-v2'"); goto end; } /* Exactly one policy qualifier MAY be included (so none is also valid) */ if (pi->qualifiers == NULL) goto end; pqi_num = sk_POLICYQUALINFO_num(pi->qualifiers); if (pqi_num == 0) goto end; if (pqi_num != 1) { error = pr_val_err("The %s extension has %d policy qualifiers. (none or only 1 expected)", ext_cp()->name, pqi_num); goto end; } pqi = sk_POLICYQUALINFO_value(pi->qualifiers, 0); nid_qt_cps = OBJ_obj2nid(pqi->pqualid); if (nid_qt_cps != NID_id_qt_cps) { error = pr_val_err("Policy qualifier ID isn't Certification Practice Statement (CPS)"); goto end; } end: CERTIFICATEPOLICIES_free(cp); return error; } static int handle_ir(X509_EXTENSION *ext, void *arg) { return 0; /* Handled in certificate_get_resources(). */ } static int handle_ar(X509_EXTENSION *ext, void *arg) { return 0; /* Handled in certificate_get_resources(). */ } static int handle_eku(X509_EXTENSION *ext, void *arg) { EXTENDED_KEY_USAGE *eku; int nid; int error; eku = X509V3_EXT_d2i(ext); if (eku == NULL) return cannot_decode(ext_eku()); /* * RFC 8209 allows multiple KeyPurposeId, so look only for the one * required and specified at section 3.1.3.2 */ error = -ENOENT; while (sk_ASN1_OBJECT_num(eku) > 0) { nid = OBJ_obj2nid(sk_ASN1_OBJECT_pop(eku)); if (nid == nid_bgpsecRouter()) { error = 0; goto end; } } if (error) pr_val_err("Extended Key Usage doesn't include id-kp-bgpsec-router."); end: EXTENDED_KEY_USAGE_free(eku); return error; } /** * Validates the certificate extensions, Trust Anchor style. * * Depending on the Access Description preference at SIA, the rpki_uri's at * @sia_uris will be allocated. */ static int certificate_validate_extensions_ta(X509 *cert, struct sia_ca_uris *sia_uris, enum rpki_policy *policy) { struct extension_handler handlers[] = { /* ext reqd handler arg */ { ext_bc(), true, handle_bc, }, { ext_ski(), true, handle_ski_ca, cert }, { ext_aki(), false, handle_aki_ta, cert }, { ext_ku(), true, handle_ku_ca, }, { ext_sia(), true, handle_sia_ca, sia_uris }, { ext_cp(), true, handle_cp, policy }, { ext_ir(), false, handle_ir, }, { ext_ar(), false, handle_ar, }, { ext_ir2(), false, handle_ir, }, { ext_ar2(), false, handle_ar, }, { NULL }, }; return handle_extensions(handlers, X509_get0_extensions(cert)); } /** * Validates the certificate extensions, (intermediate) Certificate Authority * style. * * Depending on the Access Description preference at SIA, the rpki_uri's at * @sia_uris will be allocated. * Also initializes the fourth argument with the references found in the * extensions. */ static int certificate_validate_extensions_ca(X509 *cert, struct sia_ca_uris *sia_uris, struct certificate_refs *refs, enum rpki_policy *policy) { struct extension_handler handlers[] = { /* ext reqd handler arg */ { ext_bc(), true, handle_bc, }, { ext_ski(), true, handle_ski_ca, cert }, { ext_aki(), true, handle_aki, }, { ext_ku(), true, handle_ku_ca, }, { ext_cdp(), true, handle_cdp, refs }, { ext_aia(), true, handle_aia, refs }, { ext_sia(), true, handle_sia_ca, sia_uris }, { ext_cp(), true, handle_cp, policy }, { ext_ir(), false, handle_ir, }, { ext_ar(), false, handle_ar, }, { ext_ir2(), false, handle_ir, }, { ext_ar2(), false, handle_ar, }, { NULL }, }; return handle_extensions(handlers, X509_get0_extensions(cert)); } static int certificate_validate_extensions_bgpsec(X509 *cert, unsigned char **ski, struct certificate_refs *refs, enum rpki_policy *policy) { struct bgpsec_ski ski_param; struct extension_handler handlers[] = { /* ext reqd handler arg */ { ext_ski(), true, handle_ski_bgpsec, &ski_param }, { ext_aki(), true, handle_aki, }, { ext_ku(), true, handle_ku_ee, }, { ext_cdp(), true, handle_cdp, refs }, { ext_aia(), true, handle_aia, refs }, { ext_cp(), true, handle_cp, policy }, { ext_eku(), true, handle_eku, }, { ext_ar(), false, handle_ar, }, { ext_ar2(), false, handle_ar, }, { NULL }, }; ski_param.cert = cert; ski_param.ski_data = ski; return handle_extensions(handlers, X509_get0_extensions(cert)); } int certificate_validate_extensions_ee(X509 *cert, OCTET_STRING_t *sid, struct certificate_refs *refs, enum rpki_policy *policy) { struct ski_arguments ski_args; struct extension_handler handlers[] = { /* ext reqd handler arg */ { ext_ski(), true, handle_ski_ee, &ski_args }, { ext_aki(), true, handle_aki, }, { ext_ku(), true, handle_ku_ee, }, { ext_cdp(), true, handle_cdp, refs }, { ext_aia(), true, handle_aia, refs }, { ext_sia(), true, handle_sia_ee, refs }, { ext_cp(), true, handle_cp, policy }, { ext_ir(), false, handle_ir, }, { ext_ar(), false, handle_ar, }, { ext_ir2(), false, handle_ir, }, { ext_ar2(), false, handle_ar, }, { NULL }, }; ski_args.cert = cert; ski_args.sid = sid; return handle_extensions(handlers, X509_get0_extensions(cert)); } static enum cert_type get_certificate_type(X509 *cert, bool is_ta) { if (is_ta) return TA; if (X509_get_ext_by_NID(cert, ext_bc()->nid, -1) >= 0) return CA; if (X509_get_ext_by_NID(cert, NID_ext_key_usage, -1) >= 0) return BGPSEC; return EE; } /* * It does some of the things from validate_issuer(), but we can not wait for * such validation, since at this point the RSYNC URI at AIA extension must be * verified to comply with rfc6487#section-4.8.7 */ static int force_aia_validation(struct rpki_uri *caIssuers, X509 *son) { X509 *parent; struct rfc5280_name *son_name; struct rfc5280_name *parent_name; int error; pr_val_debug("AIA's URI didn't matched parent URI, trying to SYNC"); /* RSYNC is still the preferred access mechanism, force the sync */ do { error = download_files(caIssuers, false, true); if (!error) break; if (error == EREQFAILED) { pr_val_info("AIA URI couldn't be downloaded, trying to search locally"); break; } return error; } while (0); error = certificate_load(caIssuers, &parent); if (error) return error; error = x509_name_decode(X509_get_subject_name(parent), "subject", &parent_name); if (error) goto free_parent; error = x509_name_decode(X509_get_issuer_name(son), "issuer", &son_name); if (error) goto free_parent_name; if (x509_name_equals(parent_name, son_name)) error = 0; /* Everything its ok */ else error = pr_val_err("Certificate subject from AIA ('%s') isn't issuer of this certificate.", uri_val_get_printable(caIssuers)); x509_name_put(son_name); free_parent_name: x509_name_put(parent_name); free_parent: X509_free(parent); return error; } int certificate_validate_aia(struct rpki_uri *caIssuers, X509 *cert) { struct validation *state; struct rpki_uri *parent; if (caIssuers == NULL) pr_crit("Certificate's AIA was not recorded."); state = state_retrieve(); if (state == NULL) return -EINVAL; parent = x509stack_peek_uri(validation_certstack(state)); if (parent == NULL) pr_crit("Certificate has no parent."); /* * There are two possible issues here, specifically at first level root * certificate's childs: * * - Considering that the root certificate can be published at one or * more rsync or HTTPS URIs (RFC 8630), the validation is done * considering the first valid downloaded certificate URI from the * list of URIs; so, that URI doesn't necessarily matches AIA. And * this issue is more likely to happen if the 'shuffle-uris' flag * is active an a TAL has more than one rsync/HTTPS uri. * * - If the TAL has only one URI, and such URI is HTTPS, the root * certificate will be located at a distinct point that what it's * expected, so this might be an error if such certificate (root * certificate) isn't published at an rsync repository. See RFC 6487 * section-4.8.7: * * "The preferred URI access mechanisms is "rsync", and an rsync URI * [RFC5781] MUST be specified with an accessMethod value of * id-ad-caIssuers. The URI MUST reference the point of publication * of the certificate where this Issuer is the subject (the issuer's * immediate superior certificate)." * * As of today, this is a common scenario, since most of the TALs have * an HTTPS URI. */ if (uri_equals(caIssuers, parent)) return 0; /* * Avoid the check at direct TA childs, otherwise try to match the * immediate superior subject with the current issuer. This will force * an RSYNC of AIA's URI, load the certificate and do the comparison. */ return certstack_get_x509_num(validation_certstack(state)) == 1 ? 0 : force_aia_validation(caIssuers, cert); } /* * Verify that the manifest file actually exists at the local repository, if it * doesn't exist then discard the repository (which can result in a attempt * to fetch data from another repository). */ static int verify_mft_loc(struct rpki_uri *mft_uri) { if (!valid_file_or_dir(uri_get_local(mft_uri), true, false, pr_val_errno)) return -EINVAL; /* Error already logged */ return 0; } /* * Verify the manifest location at the local RRDP workspace. * * Don't log in case the @mft_uri doesn't exist at the RRDP workspace. */ static int verify_rrdp_mft_loc(struct rpki_uri *mft_uri) { struct rpki_uri *tmp; int error; if (db_rrdp_uris_workspace_get() == NULL) return -ENOENT; tmp = NULL; error = uri_create_rsync_str_rrdp(&tmp, uri_get_global(mft_uri), uri_get_global_len(mft_uri)); if (error) return error; if (!valid_file_or_dir(uri_get_local(tmp), true, false, NULL)) { uri_refput(tmp); return -ENOENT; } uri_refput(tmp); return 0; } static int replace_rrdp_mft_uri(struct sia_uri *sia_mft) { struct rpki_uri *tmp; int error; tmp = NULL; error = uri_create_rsync_str_rrdp(&tmp, uri_get_global(sia_mft->uri), uri_get_global_len(sia_mft->uri)); if (error) return error; uri_refput(sia_mft->uri); sia_mft->uri = tmp; return 0; } static int exec_rrdp_method(struct sia_ca_uris *sia_uris) { bool data_updated; int error; /* Start working on the RRDP local workspace */ error = db_rrdp_uris_workspace_enable(); if (error) return error; data_updated = false; error = rrdp_load(sia_uris->rpkiNotify.uri, &data_updated); if (error) goto err; error = verify_rrdp_mft_loc(sia_uris->mft.uri); switch(error) { case 0: /* MFT exists, great! We're good to go. */ break; case -ENOENT: /* Doesn't exist and the RRDP data was updated: error */ if (data_updated) goto err; /* Otherwise, force the snapshot processing and check again */ error = rrdp_reload_snapshot(sia_uris->rpkiNotify.uri); if (error) goto err; error = verify_rrdp_mft_loc(sia_uris->mft.uri); if (error) goto err; break; default: goto err; } /* Successfully loaded (or no updates yet), update MFT local URI */ error = replace_rrdp_mft_uri(&sia_uris->mft); if (error) goto err; return 0; err: db_rrdp_uris_workspace_disable(); return error; } static int exec_rsync_method(struct sia_ca_uris *sia_uris) { int error; /* Stop working on the RRDP local workspace */ db_rrdp_uris_workspace_disable(); error = download_files(sia_uris->caRepository.uri, false, false); if (error) return error; return verify_mft_loc(sia_uris->mft.uri); } /* * Currently only two access methods are supported, just consider those two: * rsync and RRDP. If a new access method is supported, this function must * change (and probably the sia_ca_uris struct as well). * * Both access method callbacks must verify the manifest existence. */ static int use_access_method(struct sia_ca_uris *sia_uris, access_method_exec rsync_cb, access_method_exec rrdp_cb, bool new_level, bool *retry_repo_sync) { access_method_exec *cb_primary; access_method_exec *cb_secondary; rrdp_req_status_t rrdp_req_status; bool primary_rrdp; int upd_error; int error; /* * By default, RRDP has a greater priority than rsync. * See "http.priority" default value. */ primary_rrdp = true; (*retry_repo_sync) = true; /* * Very specific scenario, yet possible: * - Still working at the same repository level * - The previous object was working on an RRDP repository * - This certificate doesn't have an update notification URI * * Probably the object does exist at the RRDP repository, so check if * that's the case. Otherwise, just keep going. * * The main reason, is a (possible) hole at RFC 8182. Apparently, the * CA childs aren't obligated to have the same RRDP accessMethod than * their parent, so there's no problem if they don't use it at all; not * even if such childs (and even the grandchilds or anyone below that * level) "reside" at the RRDP repository. */ if (!new_level && db_rrdp_uris_workspace_get() != NULL && sia_uris->rpkiNotify.uri == NULL && verify_rrdp_mft_loc(sia_uris->mft.uri) == 0) { (*retry_repo_sync) = false; return replace_rrdp_mft_uri(&sia_uris->mft); } /* * RSYNC will always be present (at least for now, see * rfc6487#section-4.8.8.1). If rsync is disabled, the cb will take * care of that. */ if (sia_uris->rpkiNotify.uri == NULL) { primary_rrdp = false; error = rsync_cb(sia_uris); if (!error) return 0; goto verify_mft; } /* * There isn't any restriction about the preferred access method of * children CAs being the same as the parent CA. * * Two possible scenarios arise: * 1) CA Parent didn't utilized (or didn't had) an RRDP update * notification URI. * 2) CA Parent successfully utilized an RRDP update notification URI. * * Step (1) is simple, do the check of the preferred access method. * Step (2) must do something different. * - If RRDP URI was already successfully visited, don't care * preference, don't execute access method. */ error = db_rrdp_uris_get_request_status( uri_get_global(sia_uris->rpkiNotify.uri), &rrdp_req_status); if (error == 0 && rrdp_req_status == RRDP_URI_REQ_VISITED) { error = db_rrdp_uris_workspace_enable(); if (error) { db_rrdp_uris_workspace_disable(); return error; } (*retry_repo_sync) = false; return replace_rrdp_mft_uri(&sia_uris->mft); } /* Use CA's or configured priority? */ if (config_get_rsync_priority() == config_get_http_priority()) primary_rrdp = sia_uris->caRepository.position > sia_uris->rpkiNotify.position; else primary_rrdp = config_get_rsync_priority() < config_get_http_priority(); cb_primary = primary_rrdp ? rrdp_cb : rsync_cb; cb_secondary = primary_rrdp ? rsync_cb : rrdp_cb; /* Try with the preferred; in case of error, try with the next one */ error = cb_primary(sia_uris); if (!error) { (*retry_repo_sync) = !primary_rrdp; return 0; } if (primary_rrdp) { working_repo_push(uri_get_global(sia_uris->rpkiNotify.uri)); if (error != -EPERM) pr_val_info("Couldn't fetch data from RRDP repository '%s', trying to fetch data now from '%s'.", uri_get_global(sia_uris->rpkiNotify.uri), uri_get_global(sia_uris->caRepository.uri)); else pr_val_info("RRDP repository '%s' download/processing returned error previously, now I will try to fetch data from '%s'.", uri_get_global(sia_uris->rpkiNotify.uri), uri_get_global(sia_uris->caRepository.uri)); } else { working_repo_push(uri_get_global(sia_uris->caRepository.uri)); pr_val_info("Couldn't fetch data from repository '%s', trying to fetch data now from RRDP '%s'.", uri_get_global(sia_uris->caRepository.uri), uri_get_global(sia_uris->rpkiNotify.uri)); } /* Retry if rrdp was the first option but failed */ (*retry_repo_sync) = primary_rrdp; error = cb_secondary(sia_uris); /* No need to remember the working repository anymore */ working_repo_pop(); verify_mft: /* Reach here on error or when both access methods were utilized */ switch (error) { case 0: /* Remove the error'd URI, since we got the repo files */ if (working_repo_peek() != NULL) reqs_errors_rem_uri(working_repo_peek()); break; case EREQFAILED: /* Log that we'll try to work with a local copy */ pr_val_warn("Trying to work with the local cache files."); (*retry_repo_sync) = false; break; case -EPERM: /* * Specific RRPD error: the URI error'd on the first try, so * we'll keep trying with the local files */ (*retry_repo_sync) = false; break; default: return error; } /* Error and the primary access method was RRDP? Use its workspace */ if (error && primary_rrdp) { db_rrdp_uris_workspace_enable(); upd_error = replace_rrdp_mft_uri(&sia_uris->mft); if (upd_error) return upd_error; } /* Look for the manifest */ return verify_mft_loc(sia_uris->mft.uri); } /* * Get the rsync server part from an rsync URI. * * If the URI is: * rsync://<server>/<service/<file path> * This will return: * rsync://<server> */ static int get_rsync_server_uri(struct rpki_uri *src, char **result, size_t *result_len) { char const *global; char *tmp; size_t global_len; unsigned int slashes; size_t i; global = uri_get_global(src); global_len = uri_get_global_len(src); slashes = 0; for (i = 0; i < global_len; i++) { if (global[i] == '/') { slashes++; if (slashes == 3) break; } } tmp = malloc(i + 1); if (tmp == NULL) return pr_enomem(); strncpy(tmp, global, i); tmp[i] = '\0'; *result_len = i; *result = tmp; return 0; } static int set_repository_level(bool is_ta, struct validation *state, struct rpki_uri *cert_uri, struct sia_ca_uris *sia_uris, bool *updated) { char *parent_server, *current_server; size_t parent_server_len, current_server_len; unsigned int new_level; bool update; int error; new_level = 0; if (is_ta || cert_uri == NULL) { working_repo_push_level(new_level); return 0; } /* Warning killer */ parent_server = NULL; current_server = NULL; parent_server_len = 0; current_server_len = 0; /* Both are rsync URIs, check the server part */ error = get_rsync_server_uri(cert_uri, &parent_server, &parent_server_len); if (error) return error; error = get_rsync_server_uri(sia_uris->caRepository.uri, &current_server, &current_server_len); if (error) { free(parent_server); return error; } if (parent_server_len != current_server_len) { update = true; goto end; } update = (strcmp(parent_server, current_server) != 0); end: new_level = x509stack_peek_level(validation_certstack(state)); if (update) new_level++; working_repo_push_level(new_level); free(parent_server); free(current_server); (*updated) = update; return 0; } /** Boilerplate code for CA certificate validation and recursive traversal. */ int certificate_traverse(struct rpp *rpp_parent, struct rpki_uri *cert_uri) { /** Is the CA certificate the TA certificate? */ #define IS_TA (rpp_parent == NULL) struct validation *state; int total_parents; STACK_OF(X509_CRL) *rpp_parent_crl; X509 *cert; struct sia_ca_uris sia_uris; struct certificate_refs refs; unsigned char *ski; enum rpki_policy policy; enum cert_type type; struct rpp *pp; bool repo_retry; bool new_level; int error; state = state_retrieve(); if (state == NULL) return -EINVAL; total_parents = certstack_get_x509_num(validation_certstack(state)); if (total_parents >= config_get_max_cert_depth()) return pr_val_err("Certificate chain maximum depth exceeded."); /* Debug cert type */ if (IS_TA) pr_val_debug("TA Certificate '%s' {", uri_val_get_printable(cert_uri)); else pr_val_debug("Certificate '%s' {", uri_val_get_printable(cert_uri)); fnstack_push_uri(cert_uri); memset(&refs, 0, sizeof(refs)); error = rpp_crl(rpp_parent, &rpp_parent_crl); if (error) goto revert_fnstack_and_debug; /* -- Validate the certificate (@cert) -- */ error = certificate_load(cert_uri, &cert); if (error) goto revert_fnstack_and_debug; error = certificate_validate_chain(cert, rpp_parent_crl); if (error) goto revert_cert; sia_ca_uris_init(&sia_uris); type = get_certificate_type(cert, IS_TA); /* Debug cert type */ switch (type) { case TA: break; case CA: pr_val_debug("Type: CA"); break; case BGPSEC: pr_val_debug("Type: BGPsec EE"); break; case EE: pr_val_debug("Type: unexpected, validated as CA"); break; } error = certificate_validate_rfc6487(cert, type); if (error) goto revert_cert; switch (type) { case TA: error = certificate_validate_extensions_ta(cert, &sia_uris, &policy); break; case BGPSEC: error = certificate_validate_extensions_bgpsec(cert, &ski, &refs, &policy); break; default: /* Validate as a CA */ error = certificate_validate_extensions_ca(cert, &sia_uris, &refs, &policy); break; } if (error) goto revert_cert; if (!IS_TA) { error = certificate_validate_aia(refs.caIssuers, cert); if (error) goto revert_uris; } error = refs_validate_ca(&refs, rpp_parent); if (error) goto revert_uris; if (type == BGPSEC) { /* This is an EE, so there's no manifest to process */ error = handle_bgpsec(cert, ski, x509stack_peek_resources(validation_certstack(state))); cert = NULL; /* Ownership stolen at x509stack_push */ free(ski); /* No need to remember it */ x509stack_cancel(validation_certstack(state)); goto revert_refs; } /* Identify if this is a new repository before fetching it */ new_level = false; error = set_repository_level(IS_TA, state, cert_uri, &sia_uris, &new_level); if (error) goto revert_uris; /* * RFC 6481 section 5: "when the repository publication point contents * are updated, a repository operator cannot assure RPs that the * manifest contents and the repository contents will be precisely * aligned at all times" * * Trying to avoid this issue, download the CA repository and validate * manifest (and its content) again. * * Avoid to re-download the repo if the mft was fetched with RRDP. */ repo_retry = true; error = use_access_method(&sia_uris, exec_rsync_method, exec_rrdp_method, new_level, &repo_retry); if (error) goto revert_uris; do { /* Validate the manifest (@mft) pointed by the certificate */ error = x509stack_push(validation_certstack(state), cert_uri, cert, policy, IS_TA); if (error) goto revert_uris; cert = NULL; /* Ownership stolen */ error = handle_manifest(sia_uris.mft.uri, !repo_retry, &pp); if (error == 0 || !repo_retry) break; /* * Don't reach here if: * - Manifest is valid. * - Working with local files due to a download error. * - RRDP was utilized to fetch the manifest. * - There was a previous attempt to re-fetch the repository. */ pr_val_info("Retrying repository download to discard 'transient inconsistency' manifest issue (see RFC 6481 section 5) '%s'", uri_val_get_printable(sia_uris.caRepository.uri)); error = download_files(sia_uris.caRepository.uri, false, true); if (error) break; /* Cancel stack, reload certificate (no need to revalidate) */ x509stack_cancel(validation_certstack(state)); error = certificate_load(cert_uri, &cert); if (error) goto revert_uris; repo_retry = false; } while (true); if (error) { x509stack_cancel(validation_certstack(state)); goto revert_uris; } /* -- Validate & traverse the RPP (@pp) described by the manifest -- */ rpp_traverse(pp); rpp_refput(pp); revert_uris: sia_ca_uris_cleanup(&sia_uris); revert_refs: refs_cleanup(&refs); revert_cert: if (cert != NULL) X509_free(cert); revert_fnstack_and_debug: fnstack_pop(); pr_val_debug("}"); return error; }
# # 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 ai.h2o.sparkling.ml.features.H2OTargetEncoder import H2OTargetEncoder from ai.h2o.sparkling.ml.features.ColumnPruner import ColumnPruner from ai.h2o.sparkling.ml.features.H2OWord2Vec import H2OWord2Vec
# -*- coding: utf-8 -*- class Solution: def replaceDigits(self, s: str) -> str: result = list(s) for i in range(1, len(result), 2): result[i] = self.shift(result[i - 1], int(result[i])) return ''.join(result) def shift(self, c: str, x: int) -> str: return chr(ord(c) + x) if __name__ == '__main__': solution = Solution() assert 'abcdef' == solution.replaceDigits('a1c1e1') assert 'abbdcfdhe' == solution.replaceDigits('a1b2c3d4e')
import React from "react"; import { OutboundLink } from "gatsby-plugin-google-analytics"; import { Link } from "gatsby"; import Layout from "../../components/layout"; import ChoiceSupport from "../../components/ChoiceSupport"; import SEO from "../../components/seo"; import GlobalStyles from "../../styles/Global.module.scss"; import ChoiceStyles from "../../styles/Choice.module.scss"; import ButtonStyles from "../../styles/Buttons.module.scss"; import Styles from "./Styles.module.scss"; import shareConfig from "../../configs/pages/choiceTravelConfig"; import ChoiceGridOnChoice from "../../components/ChoiceGrid/onChoice"; import HowIcon from "../../components/Images/Icons/HowIcon.svg"; import BannerImg from "../../components/Images/Graphics/choiceBannerTravel.svg"; import ShareSocialCta from "../../components/ShareSocialCta"; import EarthyShare from "../../components/EarthyShare"; import SuccessBanner from "../../components/SuccessBanner"; const ChangeHowYouTravelPage = () => ( <Layout> <SEO title="Change how you travel to help prevent climate change" description=" 26% of harmful greenhouse gas emissions come from the production and use of vehicles like cars, lorries and planes. Learn how you can help prevent earth's climate breaking down by making simple changes." image="https://climatechoice.co/images/Seo/travel.jpg" keywords={[ `Travel`, `climate change travel`, `prevent climate change cars`, `climate change fossil fuels`, `climate change flying`, `climate change airplanes`, `prevent climate change flying`, `climate change lorries`, `climate change electric cars`, `Change how you travel`, `ClimateChoice`, `climate change`, `climate breakdown`, `global warming`, `global warming solutions`, `Climate change the facts`, `climate change solutions` ]} /> <section className={`${ChoiceStyles.banner} ${Styles.banner}`}> <div className={`${GlobalStyles.inner} ${ChoiceStyles.inner}`}> <div className={`${ChoiceStyles.bannerContent} ${Styles.bannerContent}`} > <h1 className={`${ChoiceStyles.bannerTitle} ${Styles.bannerTitle}`}> Change how you travel to help prevent climate breakdown </h1> <p className={`${ChoiceStyles.bannerDesc} ${Styles.bannerDesc}`}> <b>26%</b> of the greenhouse gases emitted into our atmosphere are from the production and use of vehicles and airplanes. </p> <div className={ChoiceStyles.bannerActions}> <a className={ChoiceStyles.bannerCtaPrimary} href="#actions" title="See how you can take action" > <button className={`${ButtonStyles.btnSimple} ${ButtonStyles.btnMd} ${ ButtonStyles.btnBanner } ${ButtonStyles.btnMobile}`} > Learn what you can do </button> </a> <div className={ChoiceStyles.bannerCtaSecondary}> <a href="#how" title="How it happens"> Discover how it happens </a> </div> </div> </div> <div className={`${ChoiceStyles.bannerImg} ${Styles.bannerImg}`}> <img src={BannerImg} alt="Yomo" className={`${ChoiceStyles.bannerImgShadow} ${ Styles.bannerImgShadow }`} /> </div> </div> </section> <section className={`${ChoiceStyles.cba} ${Styles.cba}`}> <div className={`${GlobalStyles.inner} ${ChoiceStyles.cbaInner}`}> Short on time?{" "} <a className={ChoiceStyles.cbaAction} href="#tldr" title="Read a summary" > Get a quick summary </a> </div> </section> <section className={`${ChoiceStyles.how} ${Styles.how}`}> <button name="how">{null}</button> <div className={`${GlobalStyles.inner} ${ChoiceStyles.howInner}`}> <div className={`${ChoiceStyles.howContent} ${Styles.howContent}`}> <h1 className={`${ChoiceStyles.howTitle} ${Styles.howTitle}`}> How travel contributes to climate breakdown </h1> <ol className={`${ChoiceStyles.choiceList} ${ChoiceStyles.howList} ${ Styles.howList }`} > <li> <b> 88% of travel emissions are from vehicles like cars, lorries and motorbikes </b> . Their assembly process requires energy generating a carbon footprint (yes, electric too). However most of the damage occurs when a fossil fuel burning vehicle hits the road releasing tonnes of carbon in the process. There are over 1 billion of these vehicles on the road today. </li> <li> <b>11% comes from air travel</b>. The problems are much the same, planes also use fossil fuel emitting greenhouse gases into the atmosphere. </li> <li> Fossil fuels first need to be extracted, refined and transported for use which means more harmful emissions. </li> <li> Electric cars don’t emit any carbon once on the road, however they do require energy which has to come from somewhere. Until we hit 100% renewable energy electric car usage will harm the environment too but nowhere near as much. </li> </ol> </div> {/* <div className={`${ChoiceStyles.howImg} ${Styles.howImg}`}>Image</div> */} </div> </section> <section className={`${ChoiceStyles.stops} ${Styles.stops}`}> <div className={`${GlobalStyles.inner} ${ChoiceStyles.stopsInner}`}> <div className={`${ChoiceStyles.stopsImg} ${Styles.stopsImg}`}> <h1 className={`${ChoiceStyles.stopsTitle} ${Styles.stopsTitle}`}> What stops us from changing how we travel? </h1> </div> <div className={`${ChoiceStyles.stopsContent} ${Styles.stopsContent}`}> <div className={`${ChoiceStyles.stopsListContainer} ${ Styles.stopsListContainer }`} > <ol className={`${ChoiceStyles.choiceList} ${ ChoiceStyles.stopsList } ${Styles.stopsList}`} > <li> We don’t want to sacrifice the freedom cars and planes give us to get to places and live our chosen lifestyle. </li> <li> Using public transport can take more time and is often not as convenient. </li> <li> There is currently no real alternative to flying if you need to get somewhere quickly. </li> <li> We’re worried about the cost of buying an electric car and how having one will affect our lifestyle. Will I run out of battery? Will it take ages to charge? </li> <li> Businesses most often prioritise based on cost and efficiency, so until the cost of transporting goods and services is cheaper and more efficient with clean energy vehicles, they won’t be used. </li> <li> Acting on climate change represents a trade-off between short-term and long-term benefits, which is the hardest trade-off for people to make. Ignoring it in the short-term is easy as we don’t have to make any personal sacrifices. </li> </ol> </div> </div> </div> </section> <section className={`${ChoiceStyles.actions} ${Styles.actions}`}> <button name="actions" aria-label={"Actions"}> {null} </button> <div className={`${GlobalStyles.inner} ${ChoiceStyles.actionsInner}`}> <div className={`${ChoiceStyles.actionsContent} ${Styles.actionsContent}`} > <h1 className={`${ChoiceStyles.actionsTitle} ${Styles.actionsTitle}`}> What you can do now </h1> </div> <div className={`${ChoiceStyles.action} ${Styles.action}`}> <div className={`${ChoiceStyles.actionContent} ${Styles.actionContent}`} > <h2 className={`${ChoiceStyles.actionTitle} ${Styles.actionTitle}`}> The best thing to do is get rid of your fossil fuel powered vehicles </h2> <p className={`${ChoiceStyles.paragraph} ${Styles.paragraph}`}> To have the most impact{" "} <b>switch to cycling, public transport and walking</b>. For those who must have a vehicle, it’s time to get an electric car. Review your choices, it’s not as expensive as you might think and there are cost savings to be made over the long-term — especially if you install solar panels at your home to generate your own energy. <b> {" "} Many governments have already committed to ban fossil fuel vehicle sales </b>{" "} in the near future and more will follow. Think of it as an investment. </p> <h3 className={`${ChoiceStyles.actionHowTitle} ${ Styles.actionHowTitle }`} > <img src={HowIcon} alt="How it helps" /> How much would this help? </h3> <p className={`${ChoiceStyles.paragraph} ${Styles.paragraph}`}> A lot! Every time we take a carbon emitting vehicle off the road we{" "} <b> send a message to car companies that we don’t want fossil fuel powered cars anymore </b> . As their demand drops, more electric cars will be bought. With higher demand, supply and competition will increase causing prices to drop. Plus we’d innovate faster on the technology — better range, faster charging and more charging locations. </p> </div> <div className={`${ChoiceStyles.actionAside} ${Styles.actionAside}`}> <div className={`${ChoiceStyles.actionAsideContainer} ${ Styles.actionAsideContainer }`} > <h3 className={`${ChoiceStyles.actionAsideTitle} ${ Styles.actionAsideTitle }`} > Need help changing? </h3> <ul className={`${ChoiceStyles.actionAsideList} ${ Styles.actionAsideList }`} > <li> <OutboundLink href="https://electriccarbuyer.com/Compare.aspx" title="Compare electric cars" > Compare electric cars → </OutboundLink> </li> <li> <OutboundLink href="https://www.moneycrashers.com/living-without-car/" title="Benefits of having no car" > The benefits of getting rid of your car → </OutboundLink> </li> </ul> </div> </div> </div> <div className={`${ChoiceStyles.action} ${Styles.action} ${ ChoiceStyles.actionAnother }`} > <div className={`${ChoiceStyles.actionContent} ${Styles.actionContent}`} > <h2 className={`${ChoiceStyles.actionTitle} ${Styles.actionTitle}`}> Only fly when you absolutely must </h2> <p className={`${ChoiceStyles.paragraph} ${Styles.paragraph}`}> Currently there is no viable alternative to air travel beyond trains, buses and boats. Until someone figures out how to decarbonise airplanes we are going to have to make some sacrifices to our lifestyles. Try and{" "} <b> save flying for long-haul journeys which can’t be achieved any other way </b> . If you need to travel a shorter distance there’s usually another way. Look into it, cleaner travels methods like rail can be cheaper, and while it may take longer, you will get to experience more along the way. </p> <p className={`${ChoiceStyles.paragraph} ${Styles.paragraph}`}> When you must fly, consider{" "} <Link to="/offset-your-carbon-footprint" title="Pay to offset your carbon footprint" > paying a little to offset your carbon footprint </Link> . There are carbon footprint tools that will calculate the carbon cost of your flight and make it easy to pay. </p> <h3 className={`${ChoiceStyles.actionHowTitle} ${ Styles.actionHowTitle }`} > <img src={HowIcon} alt="How it helps" /> How much would this help? </h3> <p className={`${ChoiceStyles.paragraph} ${Styles.paragraph}`}> Air travel accounts for around 2% of global greenhouse gas emissions. There are bigger issues that need addressed, but remember every choice you make does have an impact. </p> </div> </div> </div> </section> <ShareSocialCta {...shareConfig} /> <SuccessBanner /> <ChoiceSupport /> <section className={`${ChoiceStyles.tldr} ${Styles.tldr}`}> <button name="tldr" aria-label={"Choice of styles"}> {null} </button> <div className={`${GlobalStyles.inner} ${ChoiceStyles.tldrInner}`}> <div className={`${ChoiceStyles.tldrImg} ${Styles.tldrImg}`} /> <div className={`${ChoiceStyles.tldrContent} ${Styles.tldrContent}`}> <div className={`${ChoiceStyles.tldrListContainer} ${ Styles.tldrListContainer }`} > <h1 className={`${ChoiceStyles.tldrTitle} ${Styles.tldrTitle}`}> Too long; didn't read? </h1> <p className={`${ChoiceStyles.tldrSubtitle} ${Styles.tldrSubtitle}`} > We’re killing the planet. 26% of dangerous greenhouse gas emissions enter our atmosphere because of the way we travel. To reduce these we must: </p> <ul className={`${ChoiceStyles.tldrList} ${Styles.tldrList}`}> <li>Transition to electric cars or better no cars</li> <li>Only fly when it’s absolutely necessary</li> <li> <Link to="/offset-your-carbon-footprint" title="Pay to offset your carbon footprint" > Pay to offset your carbon footprint </Link>{" "} if you must fly </li> <li>Vote for those who prioritize the planet</li> <li> <a href="#share" alt="Spread the word"> Spread the word </a>{" "} so others make changes too </li> </ul> </div> </div> </div> </section> <ChoiceGridOnChoice /> <EarthyShare /> </Layout> ); export default ChangeHowYouTravelPage;
"""SCons.Environment Base class for construction Environments. These are the primary objects used to communicate dependency and construction information to the build engine. Keyword arguments supplied when the construction Environment is created are construction variables used to initialize the Environment """ # # __COPYRIGHT__ # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY # KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE # WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. __revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__" import copy import os import sys import re import shlex from collections import UserDict import SCons.Action import SCons.Builder import SCons.Debug from SCons.Debug import logInstanceCreation import SCons.Defaults from SCons.Errors import UserError, BuildError import SCons.Memoize import SCons.Node import SCons.Node.Alias import SCons.Node.FS import SCons.Node.Python import SCons.Platform import SCons.SConf import SCons.SConsign import SCons.Subst import SCons.Tool import SCons.Util import SCons.Warnings class _Null: pass _null = _Null _warn_copy_deprecated = True _warn_source_signatures_deprecated = True _warn_target_signatures_deprecated = True CleanTargets = {} CalculatorArgs = {} semi_deepcopy = SCons.Util.semi_deepcopy semi_deepcopy_dict = SCons.Util.semi_deepcopy_dict def alias_builder(env, target, source): pass AliasBuilder = SCons.Builder.Builder(action = alias_builder, target_factory = SCons.Node.Alias.default_ans.Alias, source_factory = SCons.Node.FS.Entry, multi = 1, is_explicit = None, name='AliasBuilder') def apply_tools(env, tools, toolpath): # Store the toolpath in the Environment. if toolpath is not None: env['toolpath'] = toolpath if not tools: return # Filter out null tools from the list. for tool in [_f for _f in tools if _f]: if SCons.Util.is_List(tool) or isinstance(tool, tuple): toolname = tool[0] toolargs = tool[1] # should be a dict of kw args tool = env.Tool(toolname, **toolargs) else: env.Tool(tool) # These names are (or will be) controlled by SCons; users should never # set or override them. This warning can optionally be turned off, # but scons will still ignore the illegal variable names even if it's off. reserved_construction_var_names = [ 'CHANGED_SOURCES', 'CHANGED_TARGETS', 'SOURCE', 'SOURCES', 'TARGET', 'TARGETS', 'UNCHANGED_SOURCES', 'UNCHANGED_TARGETS', ] future_reserved_construction_var_names = [ #'HOST_OS', #'HOST_ARCH', #'HOST_CPU', ] def copy_non_reserved_keywords(dict): result = semi_deepcopy(dict) for k in result.copy().keys(): if k in reserved_construction_var_names: msg = "Ignoring attempt to set reserved variable `$%s'" SCons.Warnings.warn(SCons.Warnings.ReservedVariableWarning, msg % k) del result[k] return result def _set_reserved(env, key, value): msg = "Ignoring attempt to set reserved variable `$%s'" SCons.Warnings.warn(SCons.Warnings.ReservedVariableWarning, msg % key) def _set_future_reserved(env, key, value): env._dict[key] = value msg = "`$%s' will be reserved in a future release and setting it will become ignored" SCons.Warnings.warn(SCons.Warnings.FutureReservedVariableWarning, msg % key) def _set_BUILDERS(env, key, value): try: bd = env._dict[key] for k in bd.copy().keys(): del bd[k] except KeyError: bd = BuilderDict(bd, env) env._dict[key] = bd for k, v in value.items(): if not SCons.Builder.is_a_Builder(v): raise UserError('%s is not a Builder.' % repr(v)) bd.update(value) def _del_SCANNERS(env, key): del env._dict[key] env.scanner_map_delete() def _set_SCANNERS(env, key, value): env._dict[key] = value env.scanner_map_delete() def _delete_duplicates(l, keep_last): """Delete duplicates from a sequence, keeping the first or last.""" seen=set() result=[] if keep_last: # reverse in & out, then keep first l.reverse() for i in l: try: if i not in seen: result.append(i) seen.add(i) except TypeError: # probably unhashable. Just keep it. result.append(i) if keep_last: result.reverse() return result # The following is partly based on code in a comment added by Peter # Shannon at the following page (there called the "transplant" class): # # ASPN : Python Cookbook : Dynamically added methods to a class # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/81732 # # We had independently been using the idiom as BuilderWrapper, but # factoring out the common parts into this base class, and making # BuilderWrapper a subclass that overrides __call__() to enforce specific # Builder calling conventions, simplified some of our higher-layer code. class MethodWrapper: """ A generic Wrapper class that associates a method (which can actually be any callable) with an object. As part of creating this MethodWrapper object an attribute with the specified (by default, the name of the supplied method) is added to the underlying object. When that new "method" is called, our __call__() method adds the object as the first argument, simulating the Python behavior of supplying "self" on method calls. We hang on to the name by which the method was added to the underlying base class so that we can provide a method to "clone" ourselves onto a new underlying object being copied (without which we wouldn't need to save that info). """ def __init__(self, object, method, name=None): if name is None: name = method.__name__ self.object = object self.method = method self.name = name setattr(self.object, name, self) def __call__(self, *args, **kwargs): nargs = (self.object,) + args return self.method(*nargs, **kwargs) def clone(self, new_object): """ Returns an object that re-binds the underlying "method" to the specified new object. """ return self.__class__(new_object, self.method, self.name) class BuilderWrapper(MethodWrapper): """ A MethodWrapper subclass that that associates an environment with a Builder. This mainly exists to wrap the __call__() function so that all calls to Builders can have their argument lists massaged in the same way (treat a lone argument as the source, treat two arguments as target then source, make sure both target and source are lists) without having to have cut-and-paste code to do it. As a bit of obsessive backwards compatibility, we also intercept attempts to get or set the "env" or "builder" attributes, which were the names we used before we put the common functionality into the MethodWrapper base class. We'll keep this around for a while in case people shipped Tool modules that reached into the wrapper (like the Tool/qt.py module does, or did). There shouldn't be a lot attribute fetching or setting on these, so a little extra work shouldn't hurt. """ def __call__(self, target=None, source=_null, *args, **kw): if source is _null: source = target target = None if target is not None and not SCons.Util.is_List(target): target = [target] if source is not None and not SCons.Util.is_List(source): source = [source] return MethodWrapper.__call__(self, target, source, *args, **kw) def __repr__(self): return '<BuilderWrapper %s>' % repr(self.name) def __str__(self): return self.__repr__() def __getattr__(self, name): if name == 'env': return self.object elif name == 'builder': return self.method else: raise AttributeError(name) def __setattr__(self, name, value): if name == 'env': self.object = value elif name == 'builder': self.method = value else: self.__dict__[name] = value # This allows a Builder to be executed directly # through the Environment to which it's attached. # In practice, we shouldn't need this, because # builders actually get executed through a Node. # But we do have a unit test for this, and can't # yet rule out that it would be useful in the # future, so leave it for now. #def execute(self, **kw): # kw['env'] = self.env # self.builder.execute(**kw) class BuilderDict(UserDict): """This is a dictionary-like class used by an Environment to hold the Builders. We need to do this because every time someone changes the Builders in the Environment's BUILDERS dictionary, we must update the Environment's attributes.""" def __init__(self, dict, env): # Set self.env before calling the superclass initialization, # because it will end up calling our other methods, which will # need to point the values in this dictionary to self.env. self.env = env UserDict.__init__(self, dict) def __semi_deepcopy__(self): # These cannot be copied since they would both modify the same builder object, and indeed # just copying would modify the original builder raise TypeError( 'cannot semi_deepcopy a BuilderDict' ) def __setitem__(self, item, val): try: method = getattr(self.env, item).method except AttributeError: pass else: self.env.RemoveMethod(method) UserDict.__setitem__(self, item, val) BuilderWrapper(self.env, val, item) def __delitem__(self, item): UserDict.__delitem__(self, item) delattr(self.env, item) def update(self, dict): for i, v in dict.items(): self.__setitem__(i, v) _is_valid_var = re.compile(r'[_a-zA-Z]\w*$') def is_valid_construction_var(varstr): """Return if the specified string is a legitimate construction variable. """ return _is_valid_var.match(varstr) class SubstitutionEnvironment: """Base class for different flavors of construction environments. This class contains a minimal set of methods that handle construction variable expansion and conversion of strings to Nodes, which may or may not be actually useful as a stand-alone class. Which methods ended up in this class is pretty arbitrary right now. They're basically the ones which we've empirically determined are common to the different construction environment subclasses, and most of the others that use or touch the underlying dictionary of construction variables. Eventually, this class should contain all the methods that we determine are necessary for a "minimal" interface to the build engine. A full "native Python" SCons environment has gotten pretty heavyweight with all of the methods and Tools and construction variables we've jammed in there, so it would be nice to have a lighter weight alternative for interfaces that don't need all of the bells and whistles. (At some point, we'll also probably rename this class "Base," since that more reflects what we want this class to become, but because we've released comments that tell people to subclass Environment.Base to create their own flavors of construction environment, we'll save that for a future refactoring when this class actually becomes useful.) """ def __init__(self, **kw): """Initialization of an underlying SubstitutionEnvironment class. """ if SCons.Debug.track_instances: logInstanceCreation(self, 'Environment.SubstitutionEnvironment') self.fs = SCons.Node.FS.get_default_fs() self.ans = SCons.Node.Alias.default_ans self.lookup_list = SCons.Node.arg2nodes_lookups self._dict = kw.copy() self._init_special() self.added_methods = [] #self._memo = {} def _init_special(self): """Initial the dispatch tables for special handling of special construction variables.""" self._special_del = {} self._special_del['SCANNERS'] = _del_SCANNERS self._special_set = {} for key in reserved_construction_var_names: self._special_set[key] = _set_reserved for key in future_reserved_construction_var_names: self._special_set[key] = _set_future_reserved self._special_set['BUILDERS'] = _set_BUILDERS self._special_set['SCANNERS'] = _set_SCANNERS # Freeze the keys of self._special_set in a list for use by # methods that need to check. (Empirically, list scanning has # gotten better than dict.has_key() in Python 2.5.) self._special_set_keys = list(self._special_set.keys()) def __eq__(self, other): return self._dict == other._dict def __delitem__(self, key): special = self._special_del.get(key) if special: special(self, key) else: del self._dict[key] def __getitem__(self, key): return self._dict[key] def __setitem__(self, key, value): # This is heavily used. This implementation is the best we have # according to the timings in bench/env.__setitem__.py. # # The "key in self._special_set_keys" test here seems to perform # pretty well for the number of keys we have. A hard-coded # list works a little better in Python 2.5, but that has the # disadvantage of maybe getting out of sync if we ever add more # variable names. Using self._special_set.has_key() works a # little better in Python 2.4, but is worse than this test. # So right now it seems like a good trade-off, but feel free to # revisit this with bench/env.__setitem__.py as needed (and # as newer versions of Python come out). if key in self._special_set_keys: self._special_set[key](self, key, value) else: # If we already have the entry, then it's obviously a valid # key and we don't need to check. If we do check, using a # global, pre-compiled regular expression directly is more # efficient than calling another function or a method. if key not in self._dict \ and not _is_valid_var.match(key): raise UserError("Illegal construction variable `%s'" % key) self._dict[key] = value def get(self, key, default=None): """Emulates the get() method of dictionaries.""" return self._dict.get(key, default) def has_key(self, key): """Emulates the has_key() method of dictionaries.""" return key in self._dict def __contains__(self, key): return self._dict.__contains__(key) def keys(self): """Emulates the keys() method of dictionaries.""" return self._dict.keys() def values(self): """Emulates the values() method of dictionaries.""" return self._dict.values() def items(self): """Emulates the items() method of dictionaries.""" return self._dict.items() def setdefault(self, key, default=None): """Emulates the setdefault() method of dictionaries.""" return self._dict.setdefault(key, default) def arg2nodes(self, args, node_factory=_null, lookup_list=_null, **kw): if node_factory is _null: node_factory = self.fs.File if lookup_list is _null: lookup_list = self.lookup_list if not args: return [] args = SCons.Util.flatten(args) nodes = [] for v in args: if SCons.Util.is_String(v): n = None for l in lookup_list: n = l(v) if n is not None: break if n is not None: if SCons.Util.is_String(n): # n = self.subst(n, raw=1, **kw) kw['raw'] = 1 n = self.subst(n, **kw) if node_factory: n = node_factory(n) if SCons.Util.is_List(n): nodes.extend(n) else: nodes.append(n) elif node_factory: # v = node_factory(self.subst(v, raw=1, **kw)) kw['raw'] = 1 v = node_factory(self.subst(v, **kw)) if SCons.Util.is_List(v): nodes.extend(v) else: nodes.append(v) else: nodes.append(v) return nodes def gvars(self): return self._dict def lvars(self): return {} def subst(self, string, raw=0, target=None, source=None, conv=None, executor=None): """Recursively interpolates construction variables from the Environment into the specified string, returning the expanded result. Construction variables are specified by a $ prefix in the string and begin with an initial underscore or alphabetic character followed by any number of underscores or alphanumeric characters. The construction variable names may be surrounded by curly braces to separate the name from trailing characters. """ gvars = self.gvars() lvars = self.lvars() lvars['__env__'] = self if executor: lvars.update(executor.get_lvars()) return SCons.Subst.scons_subst(string, self, raw, target, source, gvars, lvars, conv) def subst_kw(self, kw, raw=0, target=None, source=None): nkw = {} for k, v in kw.items(): k = self.subst(k, raw, target, source) if SCons.Util.is_String(v): v = self.subst(v, raw, target, source) nkw[k] = v return nkw def subst_list(self, string, raw=0, target=None, source=None, conv=None, executor=None): """Calls through to SCons.Subst.scons_subst_list(). See the documentation for that function.""" gvars = self.gvars() lvars = self.lvars() lvars['__env__'] = self if executor: lvars.update(executor.get_lvars()) return SCons.Subst.scons_subst_list(string, self, raw, target, source, gvars, lvars, conv) def subst_path(self, path, target=None, source=None): """Substitute a path list, turning EntryProxies into Nodes and leaving Nodes (and other objects) as-is.""" if not SCons.Util.is_List(path): path = [path] def s(obj): """This is the "string conversion" routine that we have our substitutions use to return Nodes, not strings. This relies on the fact that an EntryProxy object has a get() method that returns the underlying Node that it wraps, which is a bit of architectural dependence that we might need to break or modify in the future in response to additional requirements.""" try: get = obj.get except AttributeError: obj = SCons.Util.to_String_for_subst(obj) else: obj = get() return obj r = [] for p in path: if SCons.Util.is_String(p): p = self.subst(p, target=target, source=source, conv=s) if SCons.Util.is_List(p): if len(p) == 1: p = p[0] else: # We have an object plus a string, or multiple # objects that we need to smush together. No choice # but to make them into a string. p = ''.join(map(SCons.Util.to_String_for_subst, p)) else: p = s(p) r.append(p) return r subst_target_source = subst def backtick(self, command): import subprocess # common arguments kw = { 'stdin' : 'devnull', 'stdout' : subprocess.PIPE, 'stderr' : subprocess.PIPE, 'universal_newlines' : True, } # if the command is a list, assume it's been quoted # othewise force a shell if not SCons.Util.is_List(command): kw['shell'] = True # run constructed command p = SCons.Action._subproc(self, command, **kw) out,err = p.communicate() status = p.wait() if err: sys.stderr.write("" + err) if status: raise OSError("'%s' exited %d" % (command, status)) return out def AddMethod(self, function, name=None): """ Adds the specified function as a method of this construction environment with the specified name. If the name is omitted, the default name is the name of the function itself. """ method = MethodWrapper(self, function, name) self.added_methods.append(method) def RemoveMethod(self, function): """ Removes the specified function's MethodWrapper from the added_methods list, so we don't re-bind it when making a clone. """ self.added_methods = [dm for dm in self.added_methods if dm.method is not function] def Override(self, overrides): """ Produce a modified environment whose variables are overridden by the overrides dictionaries. "overrides" is a dictionary that will override the variables of this environment. This function is much more efficient than Clone() or creating a new Environment because it doesn't copy the construction environment dictionary, it just wraps the underlying construction environment, and doesn't even create a wrapper object if there are no overrides. """ if not overrides: return self o = copy_non_reserved_keywords(overrides) if not o: return self overrides = {} merges = None for key, value in o.items(): if key == 'parse_flags': merges = value else: overrides[key] = SCons.Subst.scons_subst_once(value, self, key) env = OverrideEnvironment(self, overrides) if merges: env.MergeFlags(merges) return env def ParseFlags(self, *flags): """ Parse the set of flags and return a dict with the flags placed in the appropriate entry. The flags are treated as a typical set of command-line flags for a GNU-like toolchain and used to populate the entries in the dict immediately below. If one of the flag strings begins with a bang (exclamation mark), it is assumed to be a command and the rest of the string is executed; the result of that evaluation is then added to the dict. """ dict = { 'ASFLAGS' : SCons.Util.CLVar(''), 'CFLAGS' : SCons.Util.CLVar(''), 'CCFLAGS' : SCons.Util.CLVar(''), 'CXXFLAGS' : SCons.Util.CLVar(''), 'CPPDEFINES' : [], 'CPPFLAGS' : SCons.Util.CLVar(''), 'CPPPATH' : [], 'FRAMEWORKPATH' : SCons.Util.CLVar(''), 'FRAMEWORKS' : SCons.Util.CLVar(''), 'LIBPATH' : [], 'LIBS' : [], 'LINKFLAGS' : SCons.Util.CLVar(''), 'RPATH' : [], } def do_parse(arg): # if arg is a sequence, recurse with each element if not arg: return if not SCons.Util.is_String(arg): for t in arg: do_parse(t) return # if arg is a command, execute it if arg[0] == '!': arg = self.backtick(arg[1:]) # utility function to deal with -D option def append_define(name, dict = dict): t = name.split('=') if len(t) == 1: dict['CPPDEFINES'].append(name) else: dict['CPPDEFINES'].append([t[0], '='.join(t[1:])]) # Loop through the flags and add them to the appropriate option. # This tries to strike a balance between checking for all possible # flags and keeping the logic to a finite size, so it doesn't # check for some that don't occur often. It particular, if the # flag is not known to occur in a config script and there's a way # of passing the flag to the right place (by wrapping it in a -W # flag, for example) we don't check for it. Note that most # preprocessor options are not handled, since unhandled options # are placed in CCFLAGS, so unless the preprocessor is invoked # separately, these flags will still get to the preprocessor. # Other options not currently handled: # -iqoutedir (preprocessor search path) # -u symbol (linker undefined symbol) # -s (linker strip files) # -static* (linker static binding) # -shared* (linker dynamic binding) # -symbolic (linker global binding) # -R dir (deprecated linker rpath) # IBM compilers may also accept -qframeworkdir=foo params = shlex.split(arg) append_next_arg_to = None # for multi-word args for arg in params: if append_next_arg_to: if append_next_arg_to == 'CPPDEFINES': append_define(arg) elif append_next_arg_to == '-include': t = ('-include', self.fs.File(arg)) dict['CCFLAGS'].append(t) elif append_next_arg_to == '-imacros': t = ('-imacros', self.fs.File(arg)) dict['CCFLAGS'].append(t) elif append_next_arg_to == '-isysroot': t = ('-isysroot', arg) dict['CCFLAGS'].append(t) dict['LINKFLAGS'].append(t) elif append_next_arg_to == '-isystem': t = ('-isystem', arg) dict['CCFLAGS'].append(t) elif append_next_arg_to == '-iquote': t = ('-iquote', arg) dict['CCFLAGS'].append(t) elif append_next_arg_to == '-idirafter': t = ('-idirafter', arg) dict['CCFLAGS'].append(t) elif append_next_arg_to == '-arch': t = ('-arch', arg) dict['CCFLAGS'].append(t) dict['LINKFLAGS'].append(t) else: dict[append_next_arg_to].append(arg) append_next_arg_to = None elif not arg[0] in ['-', '+']: dict['LIBS'].append(self.fs.File(arg)) elif arg == '-dylib_file': dict['LINKFLAGS'].append(arg) append_next_arg_to = 'LINKFLAGS' elif arg[:2] == '-L': if arg[2:]: dict['LIBPATH'].append(arg[2:]) else: append_next_arg_to = 'LIBPATH' elif arg[:2] == '-l': if arg[2:]: dict['LIBS'].append(arg[2:]) else: append_next_arg_to = 'LIBS' elif arg[:2] == '-I': if arg[2:]: dict['CPPPATH'].append(arg[2:]) else: append_next_arg_to = 'CPPPATH' elif arg[:4] == '-Wa,': dict['ASFLAGS'].append(arg[4:]) dict['CCFLAGS'].append(arg) elif arg[:4] == '-Wl,': if arg[:11] == '-Wl,-rpath=': dict['RPATH'].append(arg[11:]) elif arg[:7] == '-Wl,-R,': dict['RPATH'].append(arg[7:]) elif arg[:6] == '-Wl,-R': dict['RPATH'].append(arg[6:]) else: dict['LINKFLAGS'].append(arg) elif arg[:4] == '-Wp,': dict['CPPFLAGS'].append(arg) elif arg[:2] == '-D': if arg[2:]: append_define(arg[2:]) else: append_next_arg_to = 'CPPDEFINES' elif arg == '-framework': append_next_arg_to = 'FRAMEWORKS' elif arg[:14] == '-frameworkdir=': dict['FRAMEWORKPATH'].append(arg[14:]) elif arg[:2] == '-F': if arg[2:]: dict['FRAMEWORKPATH'].append(arg[2:]) else: append_next_arg_to = 'FRAMEWORKPATH' elif arg in ['-mno-cygwin', '-pthread', '-openmp', '-fmerge-all-constants', '-fopenmp']: dict['CCFLAGS'].append(arg) dict['LINKFLAGS'].append(arg) elif arg == '-mwindows': dict['LINKFLAGS'].append(arg) elif arg[:5] == '-std=': if '++' in arg[5:]: key='CXXFLAGS' else: key='CFLAGS' dict[key].append(arg) elif arg[0] == '+': dict['CCFLAGS'].append(arg) dict['LINKFLAGS'].append(arg) elif arg in ['-include', '-imacros', '-isysroot', '-isystem', '-iquote', '-idirafter', '-arch']: append_next_arg_to = arg else: dict['CCFLAGS'].append(arg) for arg in flags: do_parse(arg) return dict def MergeFlags(self, args, unique=1, dict=None): """ Merge the dict in args into the construction variables of this env, or the passed-in dict. If args is not a dict, it is converted into a dict using ParseFlags. If unique is not set, the flags are appended rather than merged. """ if dict is None: dict = self if not SCons.Util.is_Dict(args): args = self.ParseFlags(args) if not unique: self.Append(**args) return self for key, value in args.items(): if not value: continue try: orig = self[key] except KeyError: orig = value else: if not orig: orig = value elif value: # Add orig and value. The logic here was lifted from # part of env.Append() (see there for a lot of comments # about the order in which things are tried) and is # used mainly to handle coercion of strings to CLVar to # "do the right thing" given (e.g.) an original CCFLAGS # string variable like '-pipe -Wall'. try: orig = orig + value except (KeyError, TypeError): try: add_to_orig = orig.append except AttributeError: value.insert(0, orig) orig = value else: add_to_orig(value) t = [] if key[-4:] == 'PATH': ### keep left-most occurence for v in orig: if v not in t: t.append(v) else: ### keep right-most occurence for v in orig[::-1]: if v not in t: t.insert(0, v) self[key] = t return self def default_decide_source(dependency, target, prev_ni, repo_node=None): f = SCons.Defaults.DefaultEnvironment().decide_source return f(dependency, target, prev_ni, repo_node) def default_decide_target(dependency, target, prev_ni, repo_node=None): f = SCons.Defaults.DefaultEnvironment().decide_target return f(dependency, target, prev_ni, repo_node) def default_copy_from_cache(src, dst): f = SCons.Defaults.DefaultEnvironment().copy_from_cache return f(src, dst) class Base(SubstitutionEnvironment): """Base class for "real" construction Environments. These are the primary objects used to communicate dependency and construction information to the build engine. Keyword arguments supplied when the construction Environment is created are construction variables used to initialize the Environment. """ ####################################################################### # This is THE class for interacting with the SCons build engine, # and it contains a lot of stuff, so we're going to try to keep this # a little organized by grouping the methods. ####################################################################### ####################################################################### # Methods that make an Environment act like a dictionary. These have # the expected standard names for Python mapping objects. Note that # we don't actually make an Environment a subclass of UserDict for # performance reasons. Note also that we only supply methods for # dictionary functionality that we actually need and use. ####################################################################### def __init__( self, platform=None, tools=None, toolpath=None, variables=None, parse_flags=None, **kw ): """Initialization of a basic SCons construction environment. Sets up special construction variables like BUILDER, PLATFORM, etc., and searches for and applies available Tools. Note that we do *not* call the underlying base class (SubsitutionEnvironment) initialization, because we need to initialize things in a very specific order that doesn't work with the much simpler base class initialization. """ if SCons.Debug.track_instances: logInstanceCreation(self, 'Environment.Base') self._memo = {} self.fs = SCons.Node.FS.get_default_fs() self.ans = SCons.Node.Alias.default_ans self.lookup_list = SCons.Node.arg2nodes_lookups self._dict = semi_deepcopy(SCons.Defaults.ConstructionEnvironment) self._init_special() self.added_methods = [] # We don't use AddMethod, or define these as methods in this # class, because we *don't* want these functions to be bound # methods. They need to operate independently so that the # settings will work properly regardless of whether a given # target ends up being built with a Base environment or an # OverrideEnvironment or what have you. self.decide_target = default_decide_target self.decide_source = default_decide_source self.copy_from_cache = default_copy_from_cache self._dict['BUILDERS'] = BuilderDict(self._dict['BUILDERS'], self) if platform is None: platform = self._dict.get('PLATFORM', None) if platform is None: platform = SCons.Platform.Platform() if SCons.Util.is_String(platform): platform = SCons.Platform.Platform(platform) self._dict['PLATFORM'] = str(platform) platform(self) self._dict['HOST_OS'] = self._dict.get('HOST_OS',None) self._dict['HOST_ARCH'] = self._dict.get('HOST_ARCH',None) # Now set defaults for TARGET_{OS|ARCH} self._dict['TARGET_OS'] = self._dict.get('TARGET_OS',None) self._dict['TARGET_ARCH'] = self._dict.get('TARGET_ARCH',None) # Apply the passed-in and customizable variables to the # environment before calling the tools, because they may use # some of them during initialization. if 'options' in kw: # Backwards compatibility: they may stll be using the # old "options" keyword. variables = kw['options'] del kw['options'] self.Replace(**kw) keys = list(kw.keys()) if variables: keys = keys + list(variables.keys()) variables.Update(self) save = {} for k in keys: try: save[k] = self._dict[k] except KeyError: # No value may have been set if they tried to pass in a # reserved variable name like TARGETS. pass SCons.Tool.Initializers(self) if tools is None: tools = self._dict.get('TOOLS', None) if tools is None: tools = ['default'] apply_tools(self, tools, toolpath) # Now restore the passed-in and customized variables # to the environment, since the values the user set explicitly # should override any values set by the tools. for key, val in save.items(): self._dict[key] = val # Finally, apply any flags to be merged in if parse_flags: self.MergeFlags(parse_flags) ####################################################################### # Utility methods that are primarily for internal use by SCons. # These begin with lower-case letters. ####################################################################### def get_builder(self, name): """Fetch the builder with the specified name from the environment. """ try: return self._dict['BUILDERS'][name] except KeyError: return None def get_CacheDir(self): try: path = self._CacheDir_path except AttributeError: path = SCons.Defaults.DefaultEnvironment()._CacheDir_path try: if path == self._last_CacheDir_path: return self._last_CacheDir except AttributeError: pass cd = SCons.CacheDir.CacheDir(path) self._last_CacheDir_path = path self._last_CacheDir = cd return cd def get_factory(self, factory, default='File'): """Return a factory function for creating Nodes for this construction environment. """ name = default try: is_node = issubclass(factory, SCons.Node.FS.Base) except TypeError: # The specified factory isn't a Node itself--it's # most likely None, or possibly a callable. pass else: if is_node: # The specified factory is a Node (sub)class. Try to # return the FS method that corresponds to the Node's # name--that is, we return self.fs.Dir if they want a Dir, # self.fs.File for a File, etc. try: name = factory.__name__ except AttributeError: pass else: factory = None if not factory: # They passed us None, or we picked up a name from a specified # class, so return the FS method. (Note that we *don't* # use our own self.{Dir,File} methods because that would # cause env.subst() to be called twice on the file name, # interfering with files that have $$ in them.) factory = getattr(self.fs, name) return factory @SCons.Memoize.CountMethodCall def _gsm(self): try: return self._memo['_gsm'] except KeyError: pass result = {} try: scanners = self._dict['SCANNERS'] except KeyError: pass else: # Reverse the scanner list so that, if multiple scanners # claim they can scan the same suffix, earlier scanners # in the list will overwrite later scanners, so that # the result looks like a "first match" to the user. if not SCons.Util.is_List(scanners): scanners = [scanners] else: scanners = scanners[:] # copy so reverse() doesn't mod original scanners.reverse() for scanner in scanners: for k in scanner.get_skeys(self): if k and self['PLATFORM'] == 'win32': k = k.lower() result[k] = scanner self._memo['_gsm'] = result return result def get_scanner(self, skey): """Find the appropriate scanner given a key (usually a file suffix). """ if skey and self['PLATFORM'] == 'win32': skey = skey.lower() return self._gsm().get(skey) def scanner_map_delete(self, kw=None): """Delete the cached scanner map (if we need to). """ try: del self._memo['_gsm'] except KeyError: pass def _update(self, other): """Private method to update an environment's consvar dict directly. Bypasses the normal checks that occur when users try to set items. """ self._dict.update(other) def _update_onlynew(self, other): """Private method to add new items to an environment's consvar dict. Only adds items from `other` whose keys do not already appear in the existing dict; values from `other` are not used for replacement. Bypasses the normal checks that occur when users try to set items. """ for k, v in other.items(): if k not in self._dict: self._dict[k] = v def get_src_sig_type(self): try: return self.src_sig_type except AttributeError: t = SCons.Defaults.DefaultEnvironment().src_sig_type self.src_sig_type = t return t def get_tgt_sig_type(self): try: return self.tgt_sig_type except AttributeError: t = SCons.Defaults.DefaultEnvironment().tgt_sig_type self.tgt_sig_type = t return t ####################################################################### # Public methods for manipulating an Environment. These begin with # upper-case letters. The essential characteristic of methods in # this section is that they do *not* have corresponding same-named # global functions. For example, a stand-alone Append() function # makes no sense, because Append() is all about appending values to # an Environment's construction variables. ####################################################################### def Append(self, **kw): """Append values to existing construction variables in an Environment. """ kw = copy_non_reserved_keywords(kw) for key, val in kw.items(): # It would be easier on the eyes to write this using # "continue" statements whenever we finish processing an item, # but Python 1.5.2 apparently doesn't let you use "continue" # within try:-except: blocks, so we have to nest our code. try: if key == 'CPPDEFINES' and SCons.Util.is_String(self._dict[key]): self._dict[key] = [self._dict[key]] orig = self._dict[key] except KeyError: # No existing variable in the environment, so just set # it to the new value. if key == 'CPPDEFINES' and SCons.Util.is_String(val): self._dict[key] = [val] else: self._dict[key] = val else: try: # Check if the original looks like a dictionary. # If it is, we can't just try adding the value because # dictionaries don't have __add__() methods, and # things like UserList will incorrectly coerce the # original dict to a list (which we don't want). update_dict = orig.update except AttributeError: try: # Most straightforward: just try to add them # together. This will work in most cases, when the # original and new values are of compatible types. self._dict[key] = orig + val except (KeyError, TypeError): try: # Check if the original is a list. add_to_orig = orig.append except AttributeError: # The original isn't a list, but the new # value is (by process of elimination), # so insert the original in the new value # (if there's one to insert) and replace # the variable with it. if orig: val.insert(0, orig) self._dict[key] = val else: # The original is a list, so append the new # value to it (if there's a value to append). if val: add_to_orig(val) else: # The original looks like a dictionary, so update it # based on what we think the value looks like. if SCons.Util.is_List(val): if key == 'CPPDEFINES': tmp = [] for (k, v) in orig.items(): if v is not None: tmp.append((k, v)) else: tmp.append((k,)) orig = tmp orig += val self._dict[key] = orig else: for v in val: orig[v] = None else: try: update_dict(val) except (AttributeError, TypeError, ValueError): if SCons.Util.is_Dict(val): for k, v in val.items(): orig[k] = v else: orig[val] = None self.scanner_map_delete(kw) # allow Dirs and strings beginning with # for top-relative # Note this uses the current env's fs (in self). def _canonicalize(self, path): if not SCons.Util.is_String(path): # typically a Dir path = str(path) if path and path[0] == '#': path = str(self.fs.Dir(path)) return path def AppendENVPath(self, name, newpath, envname = 'ENV', sep = os.pathsep, delete_existing=0): """Append path elements to the path 'name' in the 'ENV' dictionary for this environment. Will only add any particular path once, and will normpath and normcase all paths to help assure this. This can also handle the case where the env variable is a list instead of a string. If delete_existing is 0, a newpath which is already in the path will not be moved to the end (it will be left where it is). """ orig = '' if envname in self._dict and name in self._dict[envname]: orig = self._dict[envname][name] nv = SCons.Util.AppendPath(orig, newpath, sep, delete_existing, canonicalize=self._canonicalize) if envname not in self._dict: self._dict[envname] = {} self._dict[envname][name] = nv def AppendUnique(self, delete_existing=0, **kw): """Append values to existing construction variables in an Environment, if they're not already there. If delete_existing is 1, removes existing values first, so values move to end. """ kw = copy_non_reserved_keywords(kw) for key, val in kw.items(): if SCons.Util.is_List(val): val = _delete_duplicates(val, delete_existing) if key not in self._dict or self._dict[key] in ('', None): self._dict[key] = val elif SCons.Util.is_Dict(self._dict[key]) and \ SCons.Util.is_Dict(val): self._dict[key].update(val) elif SCons.Util.is_List(val): dk = self._dict[key] if key == 'CPPDEFINES': tmp = [] for i in val: if SCons.Util.is_List(i): if len(i) >= 2: tmp.append((i[0], i[1])) else: tmp.append((i[0],)) elif SCons.Util.is_Tuple(i): tmp.append(i) else: tmp.append((i,)) val = tmp # Construct a list of (key, value) tuples. if SCons.Util.is_Dict(dk): tmp = [] for (k, v) in dk.items(): if v is not None: tmp.append((k, v)) else: tmp.append((k,)) dk = tmp elif SCons.Util.is_String(dk): dk = [(dk,)] else: tmp = [] for i in dk: if SCons.Util.is_List(i): if len(i) >= 2: tmp.append((i[0], i[1])) else: tmp.append((i[0],)) elif SCons.Util.is_Tuple(i): tmp.append(i) else: tmp.append((i,)) dk = tmp else: if not SCons.Util.is_List(dk): dk = [dk] if delete_existing: dk = [x for x in dk if x not in val] else: val = [x for x in val if x not in dk] self._dict[key] = dk + val else: dk = self._dict[key] if SCons.Util.is_List(dk): if key == 'CPPDEFINES': tmp = [] for i in dk: if SCons.Util.is_List(i): if len(i) >= 2: tmp.append((i[0], i[1])) else: tmp.append((i[0],)) elif SCons.Util.is_Tuple(i): tmp.append(i) else: tmp.append((i,)) dk = tmp # Construct a list of (key, value) tuples. if SCons.Util.is_Dict(val): tmp = [] for (k, v) in val.items(): if v is not None: tmp.append((k, v)) else: tmp.append((k,)) val = tmp elif SCons.Util.is_String(val): val = [(val,)] if delete_existing: dk = list(filter(lambda x, val=val: x not in val, dk)) self._dict[key] = dk + val else: dk = [x for x in dk if x not in val] self._dict[key] = dk + val else: # By elimination, val is not a list. Since dk is a # list, wrap val in a list first. if delete_existing: dk = list(filter(lambda x, val=val: x not in val, dk)) self._dict[key] = dk + [val] else: if val not in dk: self._dict[key] = dk + [val] else: if key == 'CPPDEFINES': if SCons.Util.is_String(dk): dk = [dk] elif SCons.Util.is_Dict(dk): tmp = [] for (k, v) in dk.items(): if v is not None: tmp.append((k, v)) else: tmp.append((k,)) dk = tmp if SCons.Util.is_String(val): if val in dk: val = [] else: val = [val] elif SCons.Util.is_Dict(val): tmp = [] for i,j in val.items(): if j is not None: tmp.append((i,j)) else: tmp.append(i) val = tmp if delete_existing: dk = [x for x in dk if x not in val] self._dict[key] = dk + val self.scanner_map_delete(kw) def Clone(self, tools=[], toolpath=None, parse_flags = None, **kw): """Return a copy of a construction Environment. The copy is like a Python "deep copy"--that is, independent copies are made recursively of each objects--except that a reference is copied when an object is not deep-copyable (like a function). There are no references to any mutable objects in the original Environment. """ builders = self._dict.get('BUILDERS', {}) clone = copy.copy(self) # BUILDERS is not safe to do a simple copy clone._dict = semi_deepcopy_dict(self._dict, ['BUILDERS']) clone._dict['BUILDERS'] = BuilderDict(builders, clone) # Check the methods added via AddMethod() and re-bind them to # the cloned environment. Only do this if the attribute hasn't # been overwritten by the user explicitly and still points to # the added method. clone.added_methods = [] for mw in self.added_methods: if mw == getattr(self, mw.name): clone.added_methods.append(mw.clone(clone)) clone._memo = {} # Apply passed-in variables before the tools # so the tools can use the new variables kw = copy_non_reserved_keywords(kw) new = {} for key, value in kw.items(): new[key] = SCons.Subst.scons_subst_once(value, self, key) clone.Replace(**new) apply_tools(clone, tools, toolpath) # apply them again in case the tools overwrote them clone.Replace(**new) # Finally, apply any flags to be merged in if parse_flags: clone.MergeFlags(parse_flags) if SCons.Debug.track_instances: logInstanceCreation(self, 'Environment.EnvironmentClone') return clone def _changed_build(self, dependency, target, prev_ni, repo_node=None): if dependency.changed_state(target, prev_ni, repo_node): return 1 return self.decide_source(dependency, target, prev_ni, repo_node) def _changed_content(self, dependency, target, prev_ni, repo_node=None): return dependency.changed_content(target, prev_ni, repo_node) def _changed_source(self, dependency, target, prev_ni, repo_node=None): target_env = dependency.get_build_env() type = target_env.get_tgt_sig_type() if type == 'source': return target_env.decide_source(dependency, target, prev_ni, repo_node) else: return target_env.decide_target(dependency, target, prev_ni, repo_node) def _changed_timestamp_then_content(self, dependency, target, prev_ni, repo_node=None): return dependency.changed_timestamp_then_content(target, prev_ni, repo_node) def _changed_timestamp_newer(self, dependency, target, prev_ni, repo_node=None): return dependency.changed_timestamp_newer(target, prev_ni, repo_node) def _changed_timestamp_match(self, dependency, target, prev_ni, repo_node=None): return dependency.changed_timestamp_match(target, prev_ni, repo_node) def _copy_from_cache(self, src, dst): return self.fs.copy(src, dst) def _copy2_from_cache(self, src, dst): return self.fs.copy2(src, dst) def Decider(self, function): copy_function = self._copy2_from_cache if function in ('MD5', 'content'): if not SCons.Util.md5: raise UserError("MD5 signatures are not available in this version of Python.") function = self._changed_content elif function == 'MD5-timestamp': function = self._changed_timestamp_then_content elif function in ('timestamp-newer', 'make'): function = self._changed_timestamp_newer copy_function = self._copy_from_cache elif function == 'timestamp-match': function = self._changed_timestamp_match elif not callable(function): raise UserError("Unknown Decider value %s" % repr(function)) # We don't use AddMethod because we don't want to turn the # function, which only expects three arguments, into a bound # method, which would add self as an initial, fourth argument. self.decide_target = function self.decide_source = function self.copy_from_cache = copy_function def Detect(self, progs): """Return the first available program from one or more possibilities. Args: progs (str or list): one or more command names to check for """ if not SCons.Util.is_List(progs): progs = [progs] for prog in progs: path = self.WhereIs(prog) if path: return prog return None def Dictionary(self, *args): """Return construction variables from an environment. Args: \*args (optional): variable names to look up Returns: If `args` omitted, the dictionary of all construction variables. If one arg, the corresponding value is returned. If more than one arg, a list of values is returned. Raises: KeyError: if any of `args` is not in the construction environment. """ if not args: return self._dict dlist = [self._dict[x] for x in args] if len(dlist) == 1: dlist = dlist[0] return dlist def Dump(self, key=None, format='pretty'): """ Return construction variables serialized to a string. Args: key (optional): if None, format the whole dict of variables. Else format the value of `key` (Default value = None) format (str, optional): specify the format to serialize to. `"pretty"` generates a pretty-printed string, `"json"` a JSON-formatted string. (Default value = `"pretty"`) """ if key: cvars = self.Dictionary(key) else: cvars = self.Dictionary() fmt = format.lower() if fmt == 'pretty': import pprint pp = pprint.PrettyPrinter(indent=2) # TODO: pprint doesn't do a nice job on path-style values # if the paths contain spaces (i.e. Windows), because the # algorithm tries to break lines on spaces, while breaking # on the path-separator would be more "natural". Is there # a better way to format those? return pp.pformat(cvars) elif fmt == 'json': import json def non_serializable(obj): return str(type(obj).__qualname__) return json.dumps(cvars, indent=4, default=non_serializable) else: raise ValueError("Unsupported serialization format: %s." % fmt) def FindIxes(self, paths, prefix, suffix): """Search a list of paths for something that matches the prefix and suffix. Args: paths: the list of paths or nodes. prefix: construction variable for the prefix. suffix: construction variable for the suffix. Returns: the matched path or None """ suffix = self.subst('$'+suffix) prefix = self.subst('$'+prefix) for path in paths: dir,name = os.path.split(str(path)) if name[:len(prefix)] == prefix and name[-len(suffix):] == suffix: return path def ParseConfig(self, command, function=None, unique=1): """ Use the specified function to parse the output of the command in order to modify the current environment. The 'command' can be a string or a list of strings representing a command and its arguments. 'Function' is an optional argument that takes the environment, the output of the command, and the unique flag. If no function is specified, MergeFlags, which treats the output as the result of a typical 'X-config' command (i.e. gtk-config), will merge the output into the appropriate variables. """ if function is None: def parse_conf(env, cmd, unique=unique): return env.MergeFlags(cmd, unique) function = parse_conf if SCons.Util.is_List(command): command = ' '.join(command) command = self.subst(command) return function(self, self.backtick(command)) def ParseDepends(self, filename, must_exist=None, only_one=0): """ Parse a mkdep-style file for explicit dependencies. This is completely abusable, and should be unnecessary in the "normal" case of proper SCons configuration, but it may help make the transition from a Make hierarchy easier for some people to swallow. It can also be genuinely useful when using a tool that can write a .d file, but for which writing a scanner would be too complicated. """ filename = self.subst(filename) try: with open(filename, 'r') as fp: lines = SCons.Util.LogicalLines(fp).readlines() except IOError: if must_exist: raise return lines = [l for l in lines if l[0] != '#'] tdlist = [] for line in lines: try: target, depends = line.split(':', 1) except (AttributeError, ValueError): # Throws AttributeError if line isn't a string. Can throw # ValueError if line doesn't split into two or more elements. pass else: tdlist.append((target.split(), depends.split())) if only_one: targets = [] for td in tdlist: targets.extend(td[0]) if len(targets) > 1: raise UserError( "More than one dependency target found in `%s': %s" % (filename, targets)) for target, depends in tdlist: self.Depends(target, depends) def Platform(self, platform): platform = self.subst(platform) return SCons.Platform.Platform(platform)(self) def Prepend(self, **kw): """Prepend values to existing construction variables in an Environment. """ kw = copy_non_reserved_keywords(kw) for key, val in kw.items(): # It would be easier on the eyes to write this using # "continue" statements whenever we finish processing an item, # but Python 1.5.2 apparently doesn't let you use "continue" # within try:-except: blocks, so we have to nest our code. try: orig = self._dict[key] except KeyError: # No existing variable in the environment, so just set # it to the new value. self._dict[key] = val else: try: # Check if the original looks like a dictionary. # If it is, we can't just try adding the value because # dictionaries don't have __add__() methods, and # things like UserList will incorrectly coerce the # original dict to a list (which we don't want). update_dict = orig.update except AttributeError: try: # Most straightforward: just try to add them # together. This will work in most cases, when the # original and new values are of compatible types. self._dict[key] = val + orig except (KeyError, TypeError): try: # Check if the added value is a list. add_to_val = val.append except AttributeError: # The added value isn't a list, but the # original is (by process of elimination), # so insert the the new value in the original # (if there's one to insert). if val: orig.insert(0, val) else: # The added value is a list, so append # the original to it (if there's a value # to append). if orig: add_to_val(orig) self._dict[key] = val else: # The original looks like a dictionary, so update it # based on what we think the value looks like. if SCons.Util.is_List(val): for v in val: orig[v] = None else: try: update_dict(val) except (AttributeError, TypeError, ValueError): if SCons.Util.is_Dict(val): for k, v in val.items(): orig[k] = v else: orig[val] = None self.scanner_map_delete(kw) def PrependENVPath(self, name, newpath, envname = 'ENV', sep = os.pathsep, delete_existing=1): """Prepend path elements to the path 'name' in the 'ENV' dictionary for this environment. Will only add any particular path once, and will normpath and normcase all paths to help assure this. This can also handle the case where the env variable is a list instead of a string. If delete_existing is 0, a newpath which is already in the path will not be moved to the front (it will be left where it is). """ orig = '' if envname in self._dict and name in self._dict[envname]: orig = self._dict[envname][name] nv = SCons.Util.PrependPath(orig, newpath, sep, delete_existing, canonicalize=self._canonicalize) if envname not in self._dict: self._dict[envname] = {} self._dict[envname][name] = nv def PrependUnique(self, delete_existing=0, **kw): """Prepend values to existing construction variables in an Environment, if they're not already there. If delete_existing is 1, removes existing values first, so values move to front. """ kw = copy_non_reserved_keywords(kw) for key, val in kw.items(): if SCons.Util.is_List(val): val = _delete_duplicates(val, not delete_existing) if key not in self._dict or self._dict[key] in ('', None): self._dict[key] = val elif SCons.Util.is_Dict(self._dict[key]) and \ SCons.Util.is_Dict(val): self._dict[key].update(val) elif SCons.Util.is_List(val): dk = self._dict[key] if not SCons.Util.is_List(dk): dk = [dk] if delete_existing: dk = [x for x in dk if x not in val] else: val = [x for x in val if x not in dk] self._dict[key] = val + dk else: dk = self._dict[key] if SCons.Util.is_List(dk): # By elimination, val is not a list. Since dk is a # list, wrap val in a list first. if delete_existing: dk = [x for x in dk if x not in val] self._dict[key] = [val] + dk else: if val not in dk: self._dict[key] = [val] + dk else: if delete_existing: dk = [x for x in dk if x not in val] self._dict[key] = val + dk self.scanner_map_delete(kw) def Replace(self, **kw): """Replace existing construction variables in an Environment with new construction variables and/or values. """ try: kwbd = kw['BUILDERS'] except KeyError: pass else: kwbd = BuilderDict(kwbd,self) del kw['BUILDERS'] self.__setitem__('BUILDERS', kwbd) kw = copy_non_reserved_keywords(kw) self._update(semi_deepcopy(kw)) self.scanner_map_delete(kw) def ReplaceIxes(self, path, old_prefix, old_suffix, new_prefix, new_suffix): """ Replace old_prefix with new_prefix and old_suffix with new_suffix. env - Environment used to interpolate variables. path - the path that will be modified. old_prefix - construction variable for the old prefix. old_suffix - construction variable for the old suffix. new_prefix - construction variable for the new prefix. new_suffix - construction variable for the new suffix. """ old_prefix = self.subst('$'+old_prefix) old_suffix = self.subst('$'+old_suffix) new_prefix = self.subst('$'+new_prefix) new_suffix = self.subst('$'+new_suffix) dir,name = os.path.split(str(path)) if name[:len(old_prefix)] == old_prefix: name = name[len(old_prefix):] if name[-len(old_suffix):] == old_suffix: name = name[:-len(old_suffix)] return os.path.join(dir, new_prefix+name+new_suffix) def SetDefault(self, **kw): for k in list(kw.keys()): if k in self._dict: del kw[k] self.Replace(**kw) def _find_toolpath_dir(self, tp): return self.fs.Dir(self.subst(tp)).srcnode().get_abspath() def Tool(self, tool, toolpath=None, **kw): if SCons.Util.is_String(tool): tool = self.subst(tool) if toolpath is None: toolpath = self.get('toolpath', []) toolpath = list(map(self._find_toolpath_dir, toolpath)) tool = SCons.Tool.Tool(tool, toolpath, **kw) tool(self) def WhereIs(self, prog, path=None, pathext=None, reject=[]): """Find prog in the path. """ if path is None: try: path = self['ENV']['PATH'] except KeyError: pass elif SCons.Util.is_String(path): path = self.subst(path) if pathext is None: try: pathext = self['ENV']['PATHEXT'] except KeyError: pass elif SCons.Util.is_String(pathext): pathext = self.subst(pathext) prog = SCons.Util.CLVar(self.subst(prog)) # support "program --with-args" path = SCons.Util.WhereIs(prog[0], path, pathext, reject) if path: return path return None ####################################################################### # Public methods for doing real "SCons stuff" (manipulating # dependencies, setting attributes on targets, etc.). These begin # with upper-case letters. The essential characteristic of methods # in this section is that they all *should* have corresponding # same-named global functions. ####################################################################### def Action(self, *args, **kw): def subst_string(a, self=self): if SCons.Util.is_String(a): a = self.subst(a) return a nargs = list(map(subst_string, args)) nkw = self.subst_kw(kw) return SCons.Action.Action(*nargs, **nkw) def AddPreAction(self, files, action): nodes = self.arg2nodes(files, self.fs.Entry) action = SCons.Action.Action(action) uniq = {} for executor in [n.get_executor() for n in nodes]: uniq[executor] = 1 for executor in uniq.keys(): executor.add_pre_action(action) return nodes def AddPostAction(self, files, action): nodes = self.arg2nodes(files, self.fs.Entry) action = SCons.Action.Action(action) uniq = {} for executor in [n.get_executor() for n in nodes]: uniq[executor] = 1 for executor in uniq.keys(): executor.add_post_action(action) return nodes def Alias(self, target, source=[], action=None, **kw): tlist = self.arg2nodes(target, self.ans.Alias) if not SCons.Util.is_List(source): source = [source] source = [_f for _f in source if _f] if not action: if not source: # There are no source files and no action, so just # return a target list of classic Alias Nodes, without # any builder. The externally visible effect is that # this will make the wrapping Script.BuildTask class # say that there's "Nothing to be done" for this Alias, # instead of that it's "up to date." return tlist # No action, but there are sources. Re-call all the target # builders to add the sources to each target. result = [] for t in tlist: bld = t.get_builder(AliasBuilder) result.extend(bld(self, t, source)) return result nkw = self.subst_kw(kw) nkw.update({ 'action' : SCons.Action.Action(action), 'source_factory' : self.fs.Entry, 'multi' : 1, 'is_explicit' : None, }) bld = SCons.Builder.Builder(**nkw) # Apply the Builder separately to each target so that the Aliases # stay separate. If we did one "normal" Builder call with the # whole target list, then all of the target Aliases would be # associated under a single Executor. result = [] for t in tlist: # Calling the convert() method will cause a new Executor to be # created from scratch, so we have to explicitly initialize # it with the target's existing sources, plus our new ones, # so nothing gets lost. b = t.get_builder() if b is None or b is AliasBuilder: b = bld else: nkw['action'] = b.action + action b = SCons.Builder.Builder(**nkw) t.convert() result.extend(b(self, t, t.sources + source)) return result def AlwaysBuild(self, *targets): tlist = [] for t in targets: tlist.extend(self.arg2nodes(t, self.fs.Entry)) for t in tlist: t.set_always_build() return tlist def Builder(self, **kw): nkw = self.subst_kw(kw) return SCons.Builder.Builder(**nkw) def CacheDir(self, path): import SCons.CacheDir if path is not None: path = self.subst(path) self._CacheDir_path = path def Clean(self, targets, files): global CleanTargets tlist = self.arg2nodes(targets, self.fs.Entry) flist = self.arg2nodes(files, self.fs.Entry) for t in tlist: try: CleanTargets[t].extend(flist) except KeyError: CleanTargets[t] = flist def Configure(self, *args, **kw): nargs = [self] if args: nargs = nargs + self.subst_list(args)[0] nkw = self.subst_kw(kw) nkw['_depth'] = kw.get('_depth', 0) + 1 try: nkw['custom_tests'] = self.subst_kw(nkw['custom_tests']) except KeyError: pass return SCons.SConf.SConf(*nargs, **nkw) def Command(self, target, source, action, **kw): """Builds the supplied target files from the supplied source files using the supplied action. Action may be any type that the Builder constructor will accept for an action.""" bkw = { 'action': action, 'target_factory': self.fs.Entry, 'source_factory': self.fs.Entry, } # source scanner try: bkw['source_scanner'] = kw['source_scanner'] except KeyError: pass else: del kw['source_scanner'] # target scanner try: bkw['target_scanner'] = kw['target_scanner'] except KeyError: pass else: del kw['target_scanner'] # source factory try: bkw['source_factory'] = kw['source_factory'] except KeyError: pass else: del kw['source_factory'] # target factory try: bkw['target_factory'] = kw['target_factory'] except KeyError: pass else: del kw['target_factory'] bld = SCons.Builder.Builder(**bkw) return bld(self, target, source, **kw) def Depends(self, target, dependency): """Explicity specify that 'target's depend on 'dependency'.""" tlist = self.arg2nodes(target, self.fs.Entry) dlist = self.arg2nodes(dependency, self.fs.Entry) for t in tlist: t.add_dependency(dlist) return tlist def Dir(self, name, *args, **kw): """ """ s = self.subst(name) if SCons.Util.is_Sequence(s): result=[] for e in s: result.append(self.fs.Dir(e, *args, **kw)) return result return self.fs.Dir(s, *args, **kw) def PyPackageDir(self, modulename): s = self.subst(modulename) if SCons.Util.is_Sequence(s): result=[] for e in s: result.append(self.fs.PyPackageDir(e)) return result return self.fs.PyPackageDir(s) def NoClean(self, *targets): """Tags a target so that it will not be cleaned by -c""" tlist = [] for t in targets: tlist.extend(self.arg2nodes(t, self.fs.Entry)) for t in tlist: t.set_noclean() return tlist def NoCache(self, *targets): """Tags a target so that it will not be cached""" tlist = [] for t in targets: tlist.extend(self.arg2nodes(t, self.fs.Entry)) for t in tlist: t.set_nocache() return tlist def Entry(self, name, *args, **kw): """ """ s = self.subst(name) if SCons.Util.is_Sequence(s): result=[] for e in s: result.append(self.fs.Entry(e, *args, **kw)) return result return self.fs.Entry(s, *args, **kw) def Environment(self, **kw): return SCons.Environment.Environment(**self.subst_kw(kw)) def Execute(self, action, *args, **kw): """Directly execute an action through an Environment """ action = self.Action(action, *args, **kw) result = action([], [], self) if isinstance(result, BuildError): errstr = result.errstr if result.filename: errstr = result.filename + ': ' + errstr sys.stderr.write("scons: *** %s\n" % errstr) return result.status else: return result def File(self, name, *args, **kw): """ """ s = self.subst(name) if SCons.Util.is_Sequence(s): result=[] for e in s: result.append(self.fs.File(e, *args, **kw)) return result return self.fs.File(s, *args, **kw) def FindFile(self, file, dirs): file = self.subst(file) nodes = self.arg2nodes(dirs, self.fs.Dir) return SCons.Node.FS.find_file(file, tuple(nodes)) def Flatten(self, sequence): return SCons.Util.flatten(sequence) def GetBuildPath(self, files): result = list(map(str, self.arg2nodes(files, self.fs.Entry))) if SCons.Util.is_List(files): return result else: return result[0] def Glob(self, pattern, ondisk=True, source=False, strings=False, exclude=None): return self.fs.Glob(self.subst(pattern), ondisk, source, strings, exclude) def Ignore(self, target, dependency): """Ignore a dependency.""" tlist = self.arg2nodes(target, self.fs.Entry) dlist = self.arg2nodes(dependency, self.fs.Entry) for t in tlist: t.add_ignore(dlist) return tlist def Literal(self, string): return SCons.Subst.Literal(string) def Local(self, *targets): ret = [] for targ in targets: if isinstance(targ, SCons.Node.Node): targ.set_local() ret.append(targ) else: for t in self.arg2nodes(targ, self.fs.Entry): t.set_local() ret.append(t) return ret def Precious(self, *targets): tlist = [] for t in targets: tlist.extend(self.arg2nodes(t, self.fs.Entry)) for t in tlist: t.set_precious() return tlist def Pseudo(self, *targets): tlist = [] for t in targets: tlist.extend(self.arg2nodes(t, self.fs.Entry)) for t in tlist: t.set_pseudo() return tlist def Repository(self, *dirs, **kw): dirs = self.arg2nodes(list(dirs), self.fs.Dir) self.fs.Repository(*dirs, **kw) def Requires(self, target, prerequisite): """Specify that 'prerequisite' must be built before 'target', (but 'target' does not actually depend on 'prerequisite' and need not be rebuilt if it changes).""" tlist = self.arg2nodes(target, self.fs.Entry) plist = self.arg2nodes(prerequisite, self.fs.Entry) for t in tlist: t.add_prerequisite(plist) return tlist def Scanner(self, *args, **kw): nargs = [] for arg in args: if SCons.Util.is_String(arg): arg = self.subst(arg) nargs.append(arg) nkw = self.subst_kw(kw) return SCons.Scanner.Base(*nargs, **nkw) def SConsignFile(self, name=".sconsign", dbm_module=None): if name is not None: name = self.subst(name) if not os.path.isabs(name): name = os.path.join(str(self.fs.SConstruct_dir), name) if name: name = os.path.normpath(name) sconsign_dir = os.path.dirname(name) if sconsign_dir and not os.path.exists(sconsign_dir): self.Execute(SCons.Defaults.Mkdir(sconsign_dir)) SCons.SConsign.File(name, dbm_module) def SideEffect(self, side_effect, target): """Tell scons that side_effects are built as side effects of building targets.""" side_effects = self.arg2nodes(side_effect, self.fs.Entry) targets = self.arg2nodes(target, self.fs.Entry) for side_effect in side_effects: if side_effect.multiple_side_effect_has_builder(): raise UserError("Multiple ways to build the same target were specified for: %s" % str(side_effect)) side_effect.add_source(targets) side_effect.side_effect = 1 self.Precious(side_effect) for target in targets: target.side_effects.append(side_effect) return side_effects def Split(self, arg): """This function converts a string or list into a list of strings or Nodes. This makes things easier for users by allowing files to be specified as a white-space separated list to be split. The input rules are: - A single string containing names separated by spaces. These will be split apart at the spaces. - A single Node instance - A list containing either strings or Node instances. Any strings in the list are not split at spaces. In all cases, the function returns a list of Nodes and strings.""" if SCons.Util.is_List(arg): return list(map(self.subst, arg)) elif SCons.Util.is_String(arg): return self.subst(arg).split() else: return [self.subst(arg)] def Value(self, value, built_value=None, name=None): """ """ return SCons.Node.Python.ValueWithMemo(value, built_value, name) def VariantDir(self, variant_dir, src_dir, duplicate=1): variant_dir = self.arg2nodes(variant_dir, self.fs.Dir)[0] src_dir = self.arg2nodes(src_dir, self.fs.Dir)[0] self.fs.VariantDir(variant_dir, src_dir, duplicate) def FindSourceFiles(self, node='.'): """ returns a list of all source files. """ node = self.arg2nodes(node, self.fs.Entry)[0] sources = [] def build_source(ss): for s in ss: if isinstance(s, SCons.Node.FS.Dir): build_source(s.all_children()) elif s.has_builder(): build_source(s.sources) elif isinstance(s.disambiguate(), SCons.Node.FS.File): sources.append(s) build_source(node.all_children()) def final_source(node): while node != node.srcnode(): node = node.srcnode() return node sources = list(map(final_source, sources)) # remove duplicates return list(set(sources)) def FindInstalledFiles(self): """ returns the list of all targets of the Install and InstallAs Builder. """ from SCons.Tool import install if install._UNIQUE_INSTALLED_FILES is None: install._UNIQUE_INSTALLED_FILES = SCons.Util.uniquer_hashables(install._INSTALLED_FILES) return install._UNIQUE_INSTALLED_FILES class OverrideEnvironment(Base): """A proxy that overrides variables in a wrapped construction environment by returning values from an overrides dictionary in preference to values from the underlying subject environment. This is a lightweight (I hope) proxy that passes through most use of attributes to the underlying Environment.Base class, but has just enough additional methods defined to act like a real construction environment with overridden values. It can wrap either a Base construction environment, or another OverrideEnvironment, which can in turn nest arbitrary OverrideEnvironments... Note that we do *not* call the underlying base class (SubsitutionEnvironment) initialization, because we get most of those from proxying the attributes of the subject construction environment. But because we subclass SubstitutionEnvironment, this class also has inherited arg2nodes() and subst*() methods; those methods can't be proxied because they need *this* object's methods to fetch the values from the overrides dictionary. """ def __init__(self, subject, overrides=None): if SCons.Debug.track_instances: logInstanceCreation(self, 'Environment.OverrideEnvironment') self.__dict__['__subject'] = subject if overrides is None: self.__dict__['overrides'] = dict() else: self.__dict__['overrides'] = overrides # Methods that make this class act like a proxy. def __getattr__(self, name): attr = getattr(self.__dict__['__subject'], name) # Here we check if attr is one of the Wrapper classes. For # example when a pseudo-builder is being called from an # OverrideEnvironment. # # These wrappers when they're constructed capture the # Environment they are being constructed with and so will not # have access to overrided values. So we rebuild them with the # OverrideEnvironment so they have access to overrided values. if isinstance(attr, (MethodWrapper, BuilderWrapper)): return attr.clone(self) else: return attr def __setattr__(self, name, value): setattr(self.__dict__['__subject'], name, value) # Methods that make this class act like a dictionary. def __getitem__(self, key): try: return self.__dict__['overrides'][key] except KeyError: return self.__dict__['__subject'].__getitem__(key) def __setitem__(self, key, value): if not is_valid_construction_var(key): raise UserError("Illegal construction variable `%s'" % key) self.__dict__['overrides'][key] = value def __delitem__(self, key): try: del self.__dict__['overrides'][key] except KeyError: deleted = 0 else: deleted = 1 try: result = self.__dict__['__subject'].__delitem__(key) except KeyError: if not deleted: raise result = None return result def get(self, key, default=None): """Emulates the get() method of dictionaries.""" try: return self.__dict__['overrides'][key] except KeyError: return self.__dict__['__subject'].get(key, default) def has_key(self, key): """Emulates the has_key() method of dictionaries.""" try: self.__dict__['overrides'][key] return 1 except KeyError: return key in self.__dict__['__subject'] def __contains__(self, key): if self.__dict__['overrides'].__contains__(key): return 1 return self.__dict__['__subject'].__contains__(key) def Dictionary(self, *args): d = self.__dict__['__subject'].Dictionary().copy() d.update(self.__dict__['overrides']) if not args: return d dlist = [d[x] for x in args] if len(dlist) == 1: dlist = dlist[0] return dlist def items(self): """Emulates the items() method of dictionaries.""" return self.Dictionary().items() def keys(self): """Emulates the keys() method of dictionaries.""" return self.Dictionary().keys() def values(self): """Emulates the values() method of dictionaries.""" return self.Dictionary().values() def setdefault(self, key, default=None): """Emulates the setdefault() method of dictionaries.""" try: return self.__getitem__(key) except KeyError: self.__dict__['overrides'][key] = default return default # Overridden private construction environment methods. def _update(self, other): self.__dict__['overrides'].update(other) def _update_onlynew(self, other): for k, v in other.items(): if k not in self.__dict__['overrides']: self.__dict__['overrides'][k] = v def gvars(self): return self.__dict__['__subject'].gvars() def lvars(self): lvars = self.__dict__['__subject'].lvars() lvars.update(self.__dict__['overrides']) return lvars # Overridden public construction environment methods. def Replace(self, **kw): kw = copy_non_reserved_keywords(kw) self.__dict__['overrides'].update(semi_deepcopy(kw)) # The entry point that will be used by the external world # to refer to a construction environment. This allows the wrapper # interface to extend a construction environment for its own purposes # by subclassing SCons.Environment.Base and then assigning the # class to SCons.Environment.Environment. Environment = Base def NoSubstitutionProxy(subject): """ An entry point for returning a proxy subclass instance that overrides the subst*() methods so they don't actually perform construction variable substitution. This is specifically intended to be the shim layer in between global function calls (which don't want construction variable substitution) and the DefaultEnvironment() (which would substitute variables if left to its own devices). We have to wrap this in a function that allows us to delay definition of the class until it's necessary, so that when it subclasses Environment it will pick up whatever Environment subclass the wrapper interface might have assigned to SCons.Environment.Environment. """ class _NoSubstitutionProxy(Environment): def __init__(self, subject): self.__dict__['__subject'] = subject def __getattr__(self, name): return getattr(self.__dict__['__subject'], name) def __setattr__(self, name, value): return setattr(self.__dict__['__subject'], name, value) def executor_to_lvars(self, kwdict): if 'executor' in kwdict: kwdict['lvars'] = kwdict['executor'].get_lvars() del kwdict['executor'] else: kwdict['lvars'] = {} def raw_to_mode(self, dict): try: raw = dict['raw'] except KeyError: pass else: del dict['raw'] dict['mode'] = raw def subst(self, string, *args, **kwargs): return string def subst_kw(self, kw, *args, **kwargs): return kw def subst_list(self, string, *args, **kwargs): nargs = (string, self,) + args nkw = kwargs.copy() nkw['gvars'] = {} self.executor_to_lvars(nkw) self.raw_to_mode(nkw) return SCons.Subst.scons_subst_list(*nargs, **nkw) def subst_target_source(self, string, *args, **kwargs): nargs = (string, self,) + args nkw = kwargs.copy() nkw['gvars'] = {} self.executor_to_lvars(nkw) self.raw_to_mode(nkw) return SCons.Subst.scons_subst(*nargs, **nkw) return _NoSubstitutionProxy(subject) # Local Variables: # tab-width:4 # indent-tabs-mode:nil # End: # vim: set expandtab tabstop=4 shiftwidth=4:
import codecs import os import re from setuptools import find_packages, setup HERE = os.path.abspath(os.path.dirname(__file__)) def read(*parts): """ Build an absolute path from *parts* and and return the contents of the resulting file. Assume UTF-8 encoding. """ with codecs.open(os.path.join(HERE, *parts), 'rb', 'utf-8') as f: return f.read() META_FILE = read('src', 'extract_browser_data', '__init__.py') def find_meta(meta): """ Extract __*meta*__ from META_FILE. """ meta_match = re.search( r"^__{meta}__ = ['\"]([^'\"]*)['\"]".format(meta=meta), META_FILE, re.M) if meta_match: return meta_match.group(1) raise RuntimeError("Unable to find __{meta}__ string.".format(meta=meta)) setup( version=find_meta('version'), name='extract-browser-data', description= 'Python library and utility to extract cookies, history, bookmarks from browsers.', long_description=read('README.rst'), url='https://github.com/sandorex/extract-browser-data.py', license=find_meta('license'), author=find_meta('author'), author_email=find_meta('email'), maintainer=find_meta('author'), maintainer_email=find_meta('email'), packages=find_packages(where='src'), package_dir={'': 'src'}, include_package_data=True, install_requires=read('requirements.txt'), python_requires='>=3.6')
const React = require('react'); const Component = React.Component; const { Platform, TouchableOpacity, Linking, View, Switch, Slider, StyleSheet, Text, Button, ScrollView, TextInput } = require('react-native'); const { connect } = require('react-redux'); const { ScreenHeader } = require('lib/components/screen-header.js'); const { _, setLocale } = require('lib/locale.js'); const { BaseScreenComponent } = require('lib/components/base-screen.js'); const { Dropdown } = require('lib/components/Dropdown.js'); const { themeStyle } = require('lib/components/global-style.js'); const Setting = require('lib/models/Setting.js'); const shared = require('lib/components/shared/config-shared.js'); const SyncTargetRegistry = require('lib/SyncTargetRegistry'); class ConfigScreenComponent extends BaseScreenComponent { static navigationOptions(options) { return { header: null }; } constructor() { super(); this.styles_ = {}; shared.init(this); this.checkSyncConfig_ = async () => { await shared.checkSyncConfig(this, this.state.settings); } this.saveButton_press = () => { return shared.saveSettings(this); }; } UNSAFE_componentWillMount() { this.setState({ settings: this.props.settings }); } styles() { const themeId = this.props.theme; const theme = themeStyle(themeId); if (this.styles_[themeId]) return this.styles_[themeId]; this.styles_ = {}; let styles = { body: { flex: 1, justifyContent: 'flex-start', flexDirection: 'column', }, settingContainer: { flex: 1, flexDirection: 'row', alignItems: 'center', borderBottomWidth: 1, borderBottomColor: theme.dividerColor, paddingTop: theme.marginTop, paddingBottom: theme.marginBottom, paddingLeft: theme.marginLeft, paddingRight: theme.marginRight, }, settingText: { fontWeight: 'bold', color: theme.color, fontSize: theme.fontSize, flex: 1, }, descriptionText: { color: theme.color, fontSize: theme.fontSize, flex: 1, }, permissionText: { color: theme.color, fontSize: theme.fontSize, flex: 1, marginTop: 10, }, settingControl: { color: theme.color, flex: 1, }, } if (Platform.OS === 'ios') { styles.settingControl.borderBottomWidth = 1; styles.settingControl.borderBottomColor = theme.dividerColor; } styles.switchSettingText = Object.assign({}, styles.settingText); styles.switchSettingText.width = '80%'; styles.switchSettingContainer = Object.assign({}, styles.settingContainer); styles.switchSettingContainer.flexDirection = 'row'; styles.switchSettingContainer.justifyContent = 'space-between'; styles.linkText = Object.assign({}, styles.settingText); styles.linkText.borderBottomWidth = 1; styles.linkText.borderBottomColor = theme.color; styles.linkText.flex = 0; styles.linkText.fontWeight = 'normal'; styles.switchSettingControl = Object.assign({}, styles.settingControl); delete styles.switchSettingControl.color; //styles.switchSettingControl.width = '20%'; styles.switchSettingControl.flex = 0; this.styles_[themeId] = StyleSheet.create(styles); return this.styles_[themeId]; } settingToComponent(key, value) { const themeId = this.props.theme; const theme = themeStyle(themeId); let output = null; const updateSettingValue = (key, value) => { return shared.updateSettingValue(this, key, value); } const md = Setting.settingMetadata(key); if (md.isEnum) { value = value.toString(); let items = []; const settingOptions = md.options(); for (let k in settingOptions) { if (!settingOptions.hasOwnProperty(k)) continue; items.push({ label: settingOptions[k], value: k.toString() }); } return ( <View key={key} style={this.styles().settingContainer}> <Text key="label" style={this.styles().settingText}>{md.label()}</Text> <Dropdown key="control" style={this.styles().settingControl} items={items} selectedValue={value} itemListStyle={{ backgroundColor: theme.backgroundColor, }} headerStyle={{ color: theme.color, fontSize: theme.fontSize, }} itemStyle={{ color: theme.color, fontSize: theme.fontSize, }} onValueChange={(itemValue, itemIndex) => { updateSettingValue(key, itemValue); }} /> </View> ); } else if (md.type == Setting.TYPE_BOOL) { return ( <View key={key} style={this.styles().switchSettingContainer}> <Text key="label" style={this.styles().switchSettingText}>{md.label()}</Text> <Switch key="control" style={this.styles().switchSettingControl} value={value} onValueChange={(value) => updateSettingValue(key, value)} /> </View> ); } else if (md.type == Setting.TYPE_INT) { return ( <View key={key} style={this.styles().settingContainer}> <Text key="label" style={this.styles().settingText}>{md.label()}</Text> <Slider key="control" style={this.styles().settingControl} value={value} onValueChange={(value) => updateSettingValue(key, value)} /> </View> ); } else if (md.type == Setting.TYPE_STRING) { return ( <View key={key} style={this.styles().settingContainer}> <Text key="label" style={this.styles().settingText}>{md.label()}</Text> <TextInput selectionColor={theme.textSelectionColor} autoCapitalize="none" key="control" style={this.styles().settingControl} value={value} onChangeText={(value) => updateSettingValue(key, value)} secureTextEntry={!!md.secure} /> </View> ); } else { //throw new Error('Unsupported setting type: ' + md.type); } return output; } render() { const settings = this.state.settings; const settingComps = shared.settingsToComponents(this, 'mobile', settings); const syncTargetMd = SyncTargetRegistry.idToMetadata(settings['sync.target']); if (syncTargetMd.supportsConfigCheck) { const messages = shared.checkSyncConfigMessages(this); const statusComp = !messages.length ? null : ( <View style={{flex:1, marginTop: 10}}> <Text style={this.styles().descriptionText}>{messages[0]}</Text> {messages.length >= 1 ? (<View style={{marginTop:10}}><Text style={this.styles().descriptionText}>{messages[1]}</Text></View>) : null} </View>); settingComps.push( <View key="check_sync_config_button" style={this.styles().settingContainer}> <View style={{flex:1, flexDirection: 'column'}}> <View style={{flex:1}}> <Button title={_('Check synchronisation configuration')} onPress={this.checkSyncConfig_}/> </View> { statusComp } </View> </View>); } if (Platform.OS === 'android' && Platform.Version >= 23) { // Note: `PermissionsAndroid` doesn't work so we have to ask the user to manually // set these permissions. https://stackoverflow.com/questions/49771084/permission-always-returns-never-ask-again settingComps.push( <View key="permission_info" style={this.styles().settingContainer}> <View key="permission_info_wrapper"> <Text key="perm1a" style={this.styles().settingText}>{_('To work correctly, the app needs the following permissions. Please enable them in your phone settings, in Apps > Student Helperrt > Permissions')}</Text> <Text key="perm2" style={this.styles().permissionText}>{_('- Storage: to allow attaching files to notes and to enable filesystem synchronisation.')}</Text> <Text key="perm3" style={this.styles().permissionText}>{_('- Camera: to allow taking a picture and attaching it to a note.')}</Text> <Text key="perm4" style={this.styles().permissionText}>{_('- Location: to allow attaching geo-location information to a note.')}</Text> </View> </View> ); } settingComps.push( <View key="donate_link" style={this.styles().settingContainer}> <TouchableOpacity onPress={() => { Linking.openURL('https://joplin.cozic.net/donate/') }}> <Text key="label" style={this.styles().linkText}>{_('Make a donation')}</Text> </TouchableOpacity> </View> ); settingComps.push( <View key="website_link" style={this.styles().settingContainer}> <TouchableOpacity onPress={() => { Linking.openURL('https://joplin.cozic.net/') }}> <Text key="label" style={this.styles().linkText}>{_('Student Helperrt website')}</Text> </TouchableOpacity> </View> ); settingComps.push( <View key="privacy_link" style={this.styles().settingContainer}> <TouchableOpacity onPress={() => { Linking.openURL('https://joplin.cozic.net/privacy/') }}> <Text key="label" style={this.styles().linkText}>Privacy Policy</Text> </TouchableOpacity> </View> ); return ( <View style={this.rootStyle(this.props.theme).root}> <ScreenHeader title={_('Configuration')} showSaveButton={true} saveButtonDisabled={!this.state.changedSettingKeys.length} onSaveButtonPress={this.saveButton_press} /> <ScrollView > { settingComps } </ScrollView> </View> ); } } const ConfigScreen = connect( (state) => { return { settings: state.settings, theme: state.settings.theme, }; } )(ConfigScreenComponent) module.exports = { ConfigScreen };
export const ic_motion_photos_pause_outline = {"viewBox":"0 0 24 24","children":[{"name":"rect","attribs":{"fill":"none","height":"24","width":"24"},"children":[]},{"name":"path","attribs":{"d":"M2.88,7.88l1.54,1.54C4.15,10.23,4,11.1,4,12c0,4.41,3.59,8,8,8s8-3.59,8-8s-3.59-8-8-8c-0.9,0-1.77,0.15-2.58,0.42 L7.89,2.89C9.15,2.32,10.54,2,12,2c5.52,0,10,4.48,10,10s-4.48,10-10,10S2,17.52,2,12C2,10.53,2.32,9.14,2.88,7.88z M7,5.5 C7,6.33,6.33,7,5.5,7S4,6.33,4,5.5S4.67,4,5.5,4S7,4.67,7,5.5z M11,15H9V9h2V15z M15,15h-2V9h2V15z"},"children":[]}]};
/******************************************************************************* * @license * Copyright (c) 2011, 2012 IBM Corporation and others. * All rights reserved. This program and the accompanying materials are made * available under the terms of the Eclipse Public License v1.0 * (http://www.eclipse.org/legal/epl-v10.html), and the Eclipse Distribution * License v1.0 (http://www.eclipse.org/org/documents/edl-v10.html). * * Contributors: * Anton McConville (IBM Corporation) - initial API and implementation * *******************************************************************************/ /*global define dojo dijit orion window widgets localStorage*/ /*jslint browser:true devel:true*/ define(['i18n!orion/settings/nls/messages', 'require', 'dojo', 'orion/bootstrap', 'orion/status', 'orion/commands', 'orion/operationsClient', 'orion/fileClient', 'orion/searchClient', 'orion/dialogs', 'orion/globalCommands', 'orion/sites/siteClient', 'orion/sites/siteUtils', 'orion/sites/sitesExplorer', 'orion/treetable', 'dojo/parser', 'dojo/hash', 'dojo/date/locale', 'dijit/layout/BorderContainer', 'dijit/layout/ContentPane', 'orion/widgets/maker/PluginMakerContainer', 'orion/widgets/maker/ScrollingContainerSection', 'orion/widgets/maker/PluginDescriptionSection', 'orion/widgets/maker/PluginCompletionSection', 'dijit/form/Button', 'dijit/ColorPalette'], function(messages, require, dojo, mBootstrap, mStatus, mCommands, mOperationsClient, mFileClient, mSearchClient, mDialogs, mGlobalCommands, mSiteClient, mSiteUtils, mSiteTree, mTreeTable) { dojo.addOnLoad(function() { mBootstrap.startup().then(function(core) { var serviceRegistry = core.serviceRegistry; var preferences = core.preferences; document.body.style.visibility = "visible"; //$NON-NLS-0$ dojo.parser.parse(); // Register services var operationsClient = new mOperationsClient.OperationsClient(serviceRegistry); var preferencesStatusService = new mStatus.StatusReportingService(serviceRegistry, operationsClient, "statusPane", "notifications", "notificationArea"); //$NON-NLS-2$ //$NON-NLS-1$ //$NON-NLS-0$ var commandService = new mCommands.CommandService({ serviceRegistry: serviceRegistry }); var fileClient = new mFileClient.FileClient(serviceRegistry); var searcher = new mSearchClient.Searcher({ serviceRegistry: serviceRegistry, commandService: commandService, fileService: fileClient }); var preferenceDialogService = new mDialogs.DialogService(serviceRegistry); mGlobalCommands.generateBanner("banner", serviceRegistry, commandService, preferences, searcher); //$NON-NLS-0$ preferencesStatusService.setMessage("Loading..."); //$NON-NLS-0$ /* Note 'pageActions' is the attach id for commands in the toolbar */ var containerParameters = { preferences: preferences, serviceRegistry: core.serviceRegistry, preferencesStatusService: preferencesStatusService, commandService: commandService, preferenceDialogService: preferenceDialogService, settingsCore: core, toolbarID: "pageActions" }; //$NON-NLS-0$ var container = new orion.widgets.maker.PluginMakerContainer( containerParameters, dojo.byId( "selectionAgent" )); //$NON-NLS-0$ var description = orion.widgets.maker.PluginDescriptionSection({title:messages["Plugin Description"]}); container.addSection( description ); container.addCommand( messages['Create'], 'createPlugin' ); //$NON-NLS-1$ preferencesStatusService.setMessage(""); }); }); });
from act import Act from sample.projectcode import ProjectCode from utils.inout import * class BCBuilder(Act): def start(self): projects_dir = join_path(self.arguments.data_dir, self.arguments.projects_dir) dir_names = get_directories(projects_dir) for dir_name in dir_names: for project_name in self.arguments.projects: if get_basename(dir_name) == project_name or len(self.arguments.projects) == 0: print 'Analyzing {}'.format(get_basename(dir_name)) project_code = ProjectCode(project_dir=dir_name, arguments=self.arguments) if self.arguments.prepare: project_code.prepare_bc() else: project_code.retrieve_bc() # project_code.link_bc_files()
/******************************************************************** * * * THIS FILE IS PART OF THE OggVorbis SOFTWARE CODEC SOURCE CODE. * * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS * * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE * * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. * * * * THE OggVorbis SOURCE CODE IS (C) COPYRIGHT 1994-2009 * * by the Xiph.Org Foundation http://www.xiph.org/ * * * ******************************************************************** function: key psychoacoustic settings for 44.1/48kHz last mod: $Id: psych_44.h 16962 2010-03-11 07:30:34Z xiphmont $ ********************************************************************/ /* preecho trigger settings *****************************************/ static const vorbis_info_psy_global _psy_global_44[5] = { {8, /* lines per eighth octave */ {20.f, 14.f, 12.f, 12.f, 12.f, 12.f, 12.f}, {-60.f, -30.f, -40.f, -40.f, -40.f, -40.f, -40.f}, 2, -75.f, -6.f, {99.}, {{99.}, {99.}}, {0}, {0}, {{0.}, {0.}}}, {8, /* lines per eighth octave */ {14.f, 10.f, 10.f, 10.f, 10.f, 10.f, 10.f}, {-40.f, -30.f, -25.f, -25.f, -25.f, -25.f, -25.f}, 2, -80.f, -6.f, {99.}, {{99.}, {99.}}, {0}, {0}, {{0.}, {0.}}}, {8, /* lines per eighth octave */ {12.f, 10.f, 10.f, 10.f, 10.f, 10.f, 10.f}, {-20.f, -20.f, -15.f, -15.f, -15.f, -15.f, -15.f}, 0, -80.f, -6.f, {99.}, {{99.}, {99.}}, {0}, {0}, {{0.}, {0.}}}, {8, /* lines per eighth octave */ {10.f, 8.f, 8.f, 8.f, 8.f, 8.f, 8.f}, {-20.f, -15.f, -12.f, -12.f, -12.f, -12.f, -12.f}, 0, -80.f, -6.f, {99.}, {{99.}, {99.}}, {0}, {0}, {{0.}, {0.}}}, {8, /* lines per eighth octave */ {10.f, 6.f, 6.f, 6.f, 6.f, 6.f, 6.f}, {-15.f, -15.f, -12.f, -12.f, -12.f, -12.f, -12.f}, 0, -85.f, -6.f, {99.}, {{99.}, {99.}}, {0}, {0}, {{0.}, {0.}}}, }; /* noise compander lookups * low, mid, high quality ****************/ static const compandblock _psy_compand_44[6] = { /* sub-mode Z short */ {{ 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */ 8, 9, 10, 11, 12, 13, 14, 15, /* 15dB */ 16, 17, 18, 19, 20, 21, 22, 23, /* 23dB */ 24, 25, 26, 27, 28, 29, 30, 31, /* 31dB */ 32, 33, 34, 35, 36, 37, 38, 39, /* 39dB */ }}, /* mode_Z nominal short */ {{ 0, 1, 2, 3, 4, 5, 6, 6, /* 7dB */ 7, 7, 7, 7, 6, 6, 6, 7, /* 15dB */ 7, 8, 9, 10, 11, 12, 13, 14, /* 23dB */ 15, 16, 17, 17, 17, 18, 18, 19, /* 31dB */ 19, 19, 20, 21, 22, 23, 24, 25, /* 39dB */ }}, /* mode A short */ {{ 0, 1, 2, 3, 4, 5, 5, 5, /* 7dB */ 6, 6, 6, 5, 4, 4, 4, 4, /* 15dB */ 4, 4, 5, 5, 5, 6, 6, 6, /* 23dB */ 7, 7, 7, 8, 8, 8, 9, 10, /* 31dB */ 11, 12, 13, 14, 15, 16, 17, 18, /* 39dB */ }}, /* sub-mode Z long */ {{ 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */ 8, 9, 10, 11, 12, 13, 14, 15, /* 15dB */ 16, 17, 18, 19, 20, 21, 22, 23, /* 23dB */ 24, 25, 26, 27, 28, 29, 30, 31, /* 31dB */ 32, 33, 34, 35, 36, 37, 38, 39, /* 39dB */ }}, /* mode_Z nominal long */ {{ 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */ 8, 9, 10, 11, 12, 12, 13, 13, /* 15dB */ 13, 14, 14, 14, 15, 15, 15, 15, /* 23dB */ 16, 16, 17, 17, 17, 18, 18, 19, /* 31dB */ 19, 19, 20, 21, 22, 23, 24, 25, /* 39dB */ }}, /* mode A long */ {{ 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */ 8, 8, 7, 6, 5, 4, 4, 4, /* 15dB */ 4, 4, 5, 5, 5, 6, 6, 6, /* 23dB */ 7, 7, 7, 8, 8, 8, 9, 10, /* 31dB */ 11, 12, 13, 14, 15, 16, 17, 18, /* 39dB */ }}}; /* tonal masking curve level adjustments *************************/ static const vp_adjblock _vp_tonemask_adj_longblock[12]={ /* 63 125 250 500 1 2 4 8 16 */ {{ -3, -8,-13,-15,-10,-10,-10,-10,-10,-10,-10, 0, 0, 0, 0, 0, 0}}, /* -1 */ /* {{-15,-15,-15,-15,-10, -8, -4, -2, 0, 0, 0, 10, 0, 0, 0, 0, 0}}, 0 */ {{ -4,-10,-14,-16,-15,-14,-13,-12,-12,-12,-11, -1, -1, -1, -1, -1, 0}}, /* 0 */ /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 5, 0, 0, 0, 0, 0}}, 1 */ {{ -6,-12,-14,-16,-15,-15,-14,-13,-13,-12,-12, -2, -2, -1, -1, -1, 0}}, /* 1 */ /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 2 */ {{-12,-13,-14,-16,-16,-16,-15,-14,-13,-12,-12, -6, -3, -1, -1, -1, 0}}, /* 2 */ /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 3 */ {{-15,-15,-15,-16,-16,-16,-16,-14,-13,-13,-13,-10, -4, -2, -1, -1, 0}}, /* 3 */ /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, *//* 4 */ {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 4 */ /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 5 */ {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 5 */ /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 6 */ {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -8, -4, -2, -2, 0}}, /* 6 */ /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 7 */ {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 7 */ /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 8 */ {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 8 */ /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 9 */ {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 9 */ /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 10 */ {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 10 */ }; static const vp_adjblock _vp_tonemask_adj_otherblock[12] = { /* 63 125 250 500 1 2 4 8 16 */ {{-3, -8, -13, -15, -10, -10, -9, -9, -9, -9, -9, 1, 1, 1, 1, 1, 1}}, /* -1 */ /* {{-20,-20,-20,-20,-14,-12,-10, -8, -4, 0, 0, 10, 0, 0, 0, 0, 0}}, 0 */ {{-4, -10, -14, -16, -14, -13, -12, -12, -11, -11, -10, 0, 0, 0, 0, 0, 0}}, /* 0 */ /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 5, 0, 0, 0, 0, 0}}, 1 */ {{-6, -12, -14, -16, -15, -15, -14, -13, -13, -12, -12, -2, -2, -1, 0, 0, 0}}, /* 1 */ /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 2 */ {{-12, -13, -14, -16, -16, -16, -15, -14, -13, -12, -12, -5, -2, -1, 0, 0, 0}}, /* 2 */ /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 3 */ {{-15, -15, -15, -16, -16, -16, -16, -14, -13, -13, -13, -10, -4, -2, 0, 0, 0}}, /* 3 */ /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 4 */ {{-16, -16, -16, -16, -16, -16, -16, -15, -14, -14, -13, -11, -7 - 3, -1, -1, 0}}, /* 4 */ /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 5 */ {{-16, -16, -16, -16, -16, -16, -16, -15, -14, -14, -13, -11, -7 - 3, -1, -1, 0}}, /* 5 */ /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 6 */ {{-16, -16, -16, -16, -16, -16, -16, -15, -14, -14, -14, -12, -8, -4, -2, -2, 0}}, /* 6 */ /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 7 */ {{-16, -16, -16, -16, -16, -16, -16, -15, -14, -14, -14, -12, -9, -4, -2, -2, 0}}, /* 7 */ /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 8 */ {{-16, -16, -16, -16, -16, -16, -16, -15, -14, -14, -14, -12, -9, -4, -2, -2, 0}}, /* 8 */ /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 9 */ {{-16, -16, -16, -16, -16, -16, -16, -15, -14, -14, -14, -12, -9, -4, -2, -2, 0}}, /* 9 */ /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 10 */ {{-16, -16, -16, -16, -16, -16, -16, -15, -14, -14, -14, -12, -9, -4, -2, -2, 0}}, /* 10 */ }; /* noise bias (transition block) */ static const noise3 _psy_noisebias_trans[12] = { /* 63 125 250 500 1k 2k 4k 8k 16k*/ /* -1 */ {{{-10, -10, -10, -10, -10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20}, {-30, -30, -30, -30, -26, -20, -16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15}, {-30, -30, -30, -30, -30, -24, -20, -14, -10, -6, -8, -8, -6, -6, -6, -4, -2}}}, /* 0 {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10}, {-30,-30,-30,-30,-26,-22,-20,-14, -8, -4, 0, 0, 0, 0, 2, 4, 10}, {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -4, -4, -4, -2}}},*/ {{{-15, -15, -15, -15, -15, -12, -6, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10}, {-30, -30, -30, -30, -26, -22, -20, -14, -8, -4, 0, 0, 0, 0, 2, 3, 6}, {-30, -30, -30, -30, -26, -22, -20, -14, -10, -6, -6, -6, -6, -4, -4, -4, -2}}}, /* 1 {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10}, {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 8}, {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},*/ {{{-15, -15, -15, -15, -15, -12, -10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10}, {-30, -30, -30, -30, -26, -22, -20, -14, -10, -4, -2, -2, -2, -2, 0, 1, 4}, {-30, -30, -30, -30, -26, -22, -20, -14, -10, -8, -8, -8, -8, -6, -6, -6, -4}}}, /* 2 {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10}, {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 6}, {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}}, */ {{{-15, -15, -15, -15, -15, -12, -10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10}, {-30, -30, -30, -30, -26, -22, -20, -14, -10, -4, -3, -3, -3, -2, -1, 0, 3}, {-30, -30, -30, -30, -26, -22, -20, -14, -10, -10, -10, -10, -10, -8, -8, -7, -4}}}, /* 3 {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8}, {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 6}, {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/ {{{-15, -15, -15, -15, -15, -12, -10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8}, {-30, -30, -30, -30, -26, -22, -20, -14, -10, -4, -3, -3, -3, -3, -2, 0, 2}, {-30, -30, -30, -30, -26, -22, -20, -14, -10, -10, -10, -10, -10, -8, -8, -8, -4}}}, /* 4 {{{-20,-20,-20,-20,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7}, {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 5}, {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/ {{{-20, -20, -20, -20, -20, -18, -14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7}, {-30, -30, -30, -30, -26, -22, -20, -14, -10, -4, -3, -3, -3, -3, -2, -1, 1}, {-30, -30, -30, -30, -26, -22, -20, -14, -10, -10, -10, -10, -10, -8, -8, -8, -4}}}, /* 5 {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7}, {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -4, -4, -4, -4, -2, -1, 2}, {-34,-34,-34,-34,-30,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}}, */ {{{-24, -24, -24, -24, -20, -18, -14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7}, {-32, -32, -32, -32, -28, -24, -22, -16, -12, -6, -4, -4, -4, -4, -3, -1, 0}, {-34, -34, -34, -34, -30, -24, -24, -18, -14, -12, -12, -12, -12, -10, -10, -9, -5}}}, /* 6 {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7}, {-32,-32,-32,-32,-28,-24,-24,-18,-14, -8, -6, -6, -6, -6, -4, -2, 1}, {-34,-34,-34,-34,-30,-26,-24,-18,-17,-15,-15,-15,-15,-13,-13,-12, -8}}},*/ {{{-24, -24, -24, -24, -20, -18, -14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7}, {-32, -32, -32, -32, -28, -24, -24, -18, -14, -8, -6, -6, -6, -6, -5, -2, 0}, {-34, -34, -34, -34, -30, -26, -26, -24, -22, -19, -19, -19, -19, -18, -17, -16, -12}}}, /* 7 {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7}, {-32,-32,-32,-32,-28,-24,-24,-18,-14,-12,-10, -8, -8, -8, -6, -4, 0}, {-34,-34,-34,-34,-30,-26,-26,-24,-22,-19,-19,-19,-19,-18,-17,-16,-12}}},*/ {{{-24, -24, -24, -24, -20, -18, -14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7}, {-32, -32, -32, -32, -28, -24, -24, -24, -18, -14, -12, -10, -10, -10, -8, -6, -2}, {-34, -34, -34, -34, -30, -26, -26, -26, -24, -24, -24, -24, -24, -24, -24, -20, -16}}}, /* 8 {{{-24,-24,-24,-24,-22,-20,-15,-10, -8, -2, 0, 0, 0, 1, 2, 3, 7}, {-36,-36,-36,-36,-30,-30,-30,-24,-18,-14,-12,-10,-10,-10, -8, -6, -2}, {-36,-36,-36,-36,-34,-30,-28,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},*/ {{{-24, -24, -24, -24, -22, -20, -15, -10, -8, -2, 0, 0, 0, 1, 2, 3, 7}, {-36, -36, -36, -36, -30, -30, -30, -24, -20, -16, -16, -16, -16, -14, -12, -10, -7}, {-36, -36, -36, -36, -34, -30, -28, -26, -24, -30, -30, -30, -30, -30, -30, -24, -20}}}, /* 9 {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2}, {-36,-36,-36,-36,-34,-32,-32,-28,-20,-16,-16,-16,-16,-14,-12,-10, -7}, {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},*/ {{{-28, -28, -28, -28, -28, -28, -28, -20, -14, -8, -4, -4, -4, -4, -4, -2, 2}, {-38, -38, -38, -38, -36, -34, -34, -30, -24, -20, -20, -20, -20, -18, -16, -12, -10}, {-40, -40, -40, -40, -40, -40, -40, -38, -35, -35, -35, -35, -35, -35, -35, -35, -30}}}, /* 10 */ {{{-30, -30, -30, -30, -30, -30, -30, -28, -20, -14, -14, -14, -14, -14, -14, -12, -10}, {-40, -40, -40, -40, -40, -40, -40, -40, -35, -30, -30, -30, -30, -30, -30, -30, -20}, {-40, -40, -40, -40, -40, -40, -40, -40, -40, -40, -40, -40, -40, -40, -40, -40, -40}}}, }; /* noise bias (long block) */ static const noise3 _psy_noisebias_long[12] = { /*63 125 250 500 1k 2k 4k 8k 16k*/ /* -1 */ {{{-10, -10, -10, -10, -10, -4, 0, 0, 0, 6, 6, 6, 6, 10, 10, 12, 20}, {-20, -20, -20, -20, -20, -20, -10, -2, 0, 0, 0, 0, 0, 2, 4, 6, 15}, {-20, -20, -20, -20, -20, -20, -20, -10, -6, -6, -6, -6, -6, -4, -4, -4, -2}}}, /* 0 */ /* {{{-10,-10,-10,-10,-10,-10, -8, 2, 2, 2, 4, 4, 5, 5, 5, 8, 10}, {-20,-20,-20,-20,-20,-20,-20,-14, -6, 0, 0, 0, 0, 0, 2, 4, 10}, {-20,-20,-20,-20,-20,-20,-20,-14, -8, -6, -6, -6, -6, -4, -4, -4, -2}}},*/ {{{-10, -10, -10, -10, -10, -10, -8, 2, 2, 2, 4, 4, 5, 5, 5, 8, 10}, {-20, -20, -20, -20, -20, -20, -20, -14, -6, 0, 0, 0, 0, 0, 2, 3, 6}, {-20, -20, -20, -20, -20, -20, -20, -14, -8, -6, -6, -6, -6, -4, -4, -4, -2}}}, /* 1 */ /* {{{-10,-10,-10,-10,-10,-10, -8, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10}, {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 8}, {-20,-20,-20,-20,-20,-20,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},*/ {{{-10, -10, -10, -10, -10, -10, -8, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10}, {-20, -20, -20, -20, -20, -20, -20, -14, -10, -4, -2, -2, -2, -2, 0, 1, 4}, {-20, -20, -20, -20, -20, -20, -20, -14, -10, -8, -8, -8, -8, -6, -6, -6, -4}}}, /* 2 */ /* {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10}, {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 6}, {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/ {{{-10, -10, -10, -10, -10, -10, -10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10}, {-20, -20, -20, -20, -20, -20, -20, -14, -10, -4, -3, -3, -3, -2, -1, 0, 3}, {-20, -20, -20, -20, -20, -20, -20, -14, -10, -10, -10, -10, -10, -8, -8, -8, -4}}}, /* 3 */ /* {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8}, {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 6}, {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/ {{{-10, -10, -10, -10, -10, -10, -10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8}, {-20, -20, -20, -20, -20, -20, -20, -14, -10, -4, -3, -3, -3, -3, -2, 0, 2}, {-20, -20, -20, -20, -20, -20, -20, -14, -10, -10, -10, -10, -10, -8, -8, -8, -5}}}, /* 4 */ /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7}, {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 5}, {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/ {{{-15, -15, -15, -15, -15, -15, -15, -10, -4, 1, 1, 1, 2, 3, 3, 4, 7}, {-20, -20, -20, -20, -20, -20, -20, -14, -10, -4, -3, -3, -3, -3, -2, -1, 1}, {-20, -20, -20, -20, -20, -20, -20, -14, -10, -10, -10, -10, -10, -8, -8, -8, -7}}}, /* 5 */ /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7}, {-22,-22,-22,-22,-22,-22,-22,-16,-12, -6, -4, -4, -4, -4, -2, -1, 2}, {-24,-24,-24,-24,-24,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}},*/ {{{-15, -15, -15, -15, -15, -15, -15, -10, -4, 1, 1, 1, 2, 3, 3, 4, 7}, {-22, -22, -22, -22, -22, -22, -22, -16, -12, -6, -4, -4, -4, -4, -3, -1, 0}, {-24, -24, -24, -24, -24, -24, -24, -18, -14, -12, -12, -12, -12, -10, -10, -9, -8}}}, /* 6 */ /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7}, {-24,-24,-24,-24,-24,-24,-24,-18,-14, -8, -6, -6, -6, -6, -4, -2, 1}, {-26,-26,-26,-26,-26,-26,-26,-18,-16,-15,-15,-15,-15,-13,-13,-12, -8}}},*/ {{{-15, -15, -15, -15, -15, -15, -15, -10, -4, 1, 1, 1, 2, 3, 3, 4, 7}, {-24, -24, -24, -24, -24, -24, -24, -18, -14, -8, -6, -6, -6, -6, -5, -2, 0}, {-26, -26, -26, -26, -26, -26, -26, -18, -16, -15, -15, -15, -15, -13, -13, -12, -10}}}, /* 7 */ {{{-15, -15, -15, -15, -15, -15, -15, -10, -4, 1, 1, 1, 2, 3, 3, 4, 7}, {-24, -24, -24, -24, -24, -24, -24, -18, -14, -10, -8, -8, -8, -8, -6, -4, 0}, {-26, -26, -26, -26, -26, -26, -26, -22, -20, -19, -19, -19, -19, -18, -17, -16, -12}}}, /* 8 */ {{{-15, -15, -15, -15, -15, -15, -15, -10, -4, 0, 0, 0, 0, 1, 2, 3, 7}, {-26, -26, -26, -26, -26, -26, -26, -20, -16, -12, -10, -10, -10, -10, -8, -6, -2}, {-28, -28, -28, -28, -28, -28, -28, -26, -24, -24, -24, -24, -24, -24, -24, -20, -16}}}, /* 9 */ {{{-22, -22, -22, -22, -22, -22, -22, -18, -14, -8, -4, -4, -4, -4, -4, -2, 2}, {-26, -26, -26, -26, -26, -26, -26, -22, -18, -16, -16, -16, -16, -14, -12, -10, -7}, {-30, -30, -30, -30, -30, -30, -30, -30, -30, -30, -30, -30, -30, -30, -30, -24, -20}}}, /* 10 */ {{{-24, -24, -24, -24, -24, -24, -24, -24, -24, -18, -14, -14, -14, -14, -14, -12, -10}, {-30, -30, -30, -30, -30, -30, -30, -30, -30, -30, -30, -30, -30, -30, -30, -30, -20}, {-40, -40, -40, -40, -40, -40, -40, -40, -40, -40, -40, -40, -40, -40, -40, -40, -40}}}, }; /* noise bias (impulse block) */ static const noise3 _psy_noisebias_impulse[12] = { /* 63 125 250 500 1k 2k 4k 8k 16k*/ /* -1 */ {{{-10, -10, -10, -10, -10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20}, {-30, -30, -30, -30, -26, -20, -16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15}, {-30, -30, -30, -30, -30, -24, -20, -14, -10, -6, -8, -8, -6, -6, -6, -4, -2}}}, /* 0 */ /* {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 4, 8, 8, 8, 10, 12, 14, 20}, {-30,-30,-30,-30,-26,-22,-20,-14, -6, -2, 0, 0, 0, 0, 2, 4, 10}, {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},*/ {{{-10, -10, -10, -10, -10, -4, 0, 0, 4, 4, 8, 8, 8, 10, 12, 14, 20}, {-30, -30, -30, -30, -26, -22, -20, -14, -6, -2, 0, 0, 0, 0, 2, 3, 6}, {-30, -30, -30, -30, -30, -24, -20, -14, -10, -6, -8, -8, -6, -6, -6, -4, -2}}}, /* 1 */ {{{-12, -12, -12, -12, -12, -8, -6, -4, 0, 4, 4, 4, 4, 10, 12, 14, 20}, {-30, -30, -30, -30, -26, -22, -20, -14, -10, -6, -4, -4, -2, -2, -2, -2, 2}, {-30, -30, -30, -30, -26, -22, -20, -14, -10, -8, -10, -10, -8, -8, -8, -6, -4}}}, /* 2 */ {{{-14, -14, -14, -14, -14, -10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16}, {-30, -30, -30, -30, -26, -22, -20, -14, -10, -6, -6, -6, -4, -4, -4, -2, 0}, {-30, -30, -30, -30, -26, -22, -20, -14, -10, -10, -10, -10, -10, -10, -10, -8, -4}}}, /* 3 */ {{{-14, -14, -14, -14, -14, -10, -8, -6, -2, 2, 2, 2, 2, 6, 8, 8, 14}, {-30, -30, -30, -30, -26, -22, -20, -14, -10, -6, -6, -6, -4, -4, -4, -2, 0}, {-30, -30, -30, -30, -26, -22, -20, -14, -10, -10, -10, -10, -10, -10, -10, -8, -4}}}, /* 4 */ {{{-16, -16, -16, -16, -16, -12, -10, -6, -2, 0, 0, 0, 0, 4, 6, 6, 12}, {-30, -30, -30, -30, -26, -22, -20, -14, -10, -6, -6, -6, -4, -4, -4, -2, 0}, {-30, -30, -30, -30, -26, -22, -20, -14, -10, -10, -10, -10, -10, -10, -10, -8, -4}}}, /* 5 */ {{{-20, -20, -20, -20, -20, -18, -14, -10, -4, 0, 0, 0, 0, 4, 4, 6, 11}, {-32, -32, -32, -32, -28, -24, -22, -16, -10, -6, -8, -8, -6, -6, -6, -4, -2}, {-34, -34, -34, -34, -30, -26, -24, -18, -14, -12, -12, -12, -12, -12, -10, -9, -5}}}, /* 6 {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11}, {-34,-34,-34,-34,-30,-30,-24,-20,-12,-12,-14,-14,-10, -9, -8, -6, -4}, {-34,-34,-34,-34,-34,-30,-26,-20,-16,-15,-15,-15,-15,-15,-13,-12, -8}}},*/ {{{-20, -20, -20, -20, -20, -18, -14, -10, -4, 0, 0, 0, 0, 4, 4, 6, 11}, {-34, -34, -34, -34, -30, -30, -30, -24, -16, -16, -16, -16, -16, -16, -14, -14, -12}, {-36, -36, -36, -36, -36, -34, -28, -24, -20, -20, -20, -20, -20, -20, -20, -18, -16}}}, /* 7 */ /* {{{-22,-22,-22,-22,-22,-20,-14,-10, -6, 0, 0, 0, 0, 4, 4, 6, 11}, {-34,-34,-34,-34,-30,-30,-24,-20,-14,-14,-16,-16,-14,-12,-10,-10,-10}, {-34,-34,-34,-34,-32,-32,-30,-24,-20,-19,-19,-19,-19,-19,-17,-16,-12}}},*/ {{{-22, -22, -22, -22, -22, -20, -14, -10, -6, 0, 0, 0, 0, 4, 4, 6, 11}, {-34, -34, -34, -34, -30, -30, -30, -30, -26, -26, -26, -26, -26, -26, -26, -24, -22}, {-40, -40, -40, -40, -40, -40, -40, -32, -30, -30, -30, -30, -30, -30, -30, -30, -24}}}, /* 8 */ /* {{{-24,-24,-24,-24,-24,-22,-14,-10, -6, -1, -1, -1, -1, 3, 3, 5, 10}, {-34,-34,-34,-34,-30,-30,-30,-24,-20,-20,-20,-20,-20,-18,-16,-16,-14}, {-36,-36,-36,-36,-36,-34,-28,-24,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},*/ {{{-24, -24, -24, -24, -24, -22, -14, -10, -6, -1, -1, -1, -1, 3, 3, 5, 10}, {-34, -34, -34, -34, -34, -32, -32, -30, -26, -26, -26, -26, -26, -26, -26, -26, -24}, {-40, -40, -40, -40, -40, -40, -40, -32, -30, -30, -30, -30, -30, -30, -30, -30, -24}}}, /* 9 */ /* {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2}, {-36,-36,-36,-36,-34,-32,-32,-30,-26,-26,-26,-26,-26,-22,-20,-20,-18}, {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},*/ {{{-28, -28, -28, -28, -28, -28, -28, -20, -14, -8, -4, -4, -4, -4, -4, -2, 2}, {-36, -36, -36, -36, -34, -32, -32, -30, -26, -26, -26, -26, -26, -26, -26, -26, -26}, {-40, -40, -40, -40, -40, -40, -40, -32, -30, -30, -30, -30, -30, -30, -30, -24, -20}}}, /* 10 */ {{{-30, -30, -30, -30, -30, -26, -24, -24, -24, -20, -16, -16, -16, -16, -16, -14, -12}, {-40, -40, -40, -40, -40, -40, -40, -40, -35, -30, -30, -30, -30, -30, -30, -30, -26}, {-40, -40, -40, -40, -40, -40, -40, -40, -40, -40, -40, -40, -40, -40, -40, -40, -40}}}, }; /* noise bias (padding block) */ static const noise3 _psy_noisebias_padding[12] = { /* 63 125 250 500 1k 2k 4k 8k 16k*/ /* -1 */ {{{-10, -10, -10, -10, -10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20}, {-30, -30, -30, -30, -26, -20, -16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15}, {-30, -30, -30, -30, -30, -24, -20, -14, -10, -6, -8, -8, -6, -6, -6, -4, -2}}}, /* 0 */ {{{-10, -10, -10, -10, -10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20}, {-30, -30, -30, -30, -26, -22, -20, -14, -10, -4, -2, 2, 3, 6, 6, 8, 10}, {-30, -30, -30, -30, -26, -22, -20, -14, -10, -4, -4, -4, -4, -4, -2, 0, 2}}}, /* 1 */ {{{-12, -12, -12, -12, -12, -8, -6, -4, 0, 4, 4, 4, 4, 10, 12, 14, 20}, {-30, -30, -30, -30, -26, -22, -20, -14, -10, -4, 0, 0, 0, 2, 2, 4, 8}, {-30, -30, -30, -30, -26, -22, -20, -14, -10, -6, -6, -6, -6, -6, -4, -2, 0}}}, /* 2 */ /* {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16}, {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, 0, 0, 0, 2, 2, 4, 8}, {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},*/ {{{-14, -14, -14, -14, -14, -10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16}, {-30, -30, -30, -30, -26, -22, -20, -14, -10, -6, -1, -1, -1, 0, 0, 2, 6}, {-30, -30, -30, -30, -26, -22, -20, -14, -10, -8, -8, -8, -8, -8, -6, -4, -2}}}, /* 3 */ {{{-14, -14, -14, -14, -14, -10, -8, -6, -2, 2, 2, 2, 2, 6, 8, 8, 14}, {-30, -30, -30, -30, -26, -22, -20, -14, -10, -6, -1, -1, -1, 0, 0, 2, 6}, {-30, -30, -30, -30, -26, -22, -20, -14, -10, -8, -8, -8, -8, -8, -6, -4, -2}}}, /* 4 */ {{{-16, -16, -16, -16, -16, -12, -10, -6, -2, 0, 0, 0, 0, 4, 6, 6, 12}, {-30, -30, -30, -30, -26, -22, -20, -14, -10, -6, -1, -1, -1, -1, 0, 2, 6}, {-30, -30, -30, -30, -26, -22, -20, -14, -10, -8, -8, -8, -8, -8, -6, -4, -2}}}, /* 5 */ {{{-20, -20, -20, -20, -20, -18, -14, -10, -4, 0, 0, 0, 0, 4, 6, 6, 12}, {-32, -32, -32, -32, -28, -24, -22, -16, -12, -6, -3, -3, -3, -3, -2, 0, 4}, {-34, -34, -34, -34, -30, -26, -24, -18, -14, -10, -10, -10, -10, -10, -8, -5, -3}}}, /* 6 */ {{{-20, -20, -20, -20, -20, -18, -14, -10, -4, 0, 0, 0, 0, 4, 6, 6, 12}, {-34, -34, -34, -34, -30, -30, -24, -20, -14, -8, -4, -4, -4, -4, -3, -1, 4}, {-34, -34, -34, -34, -34, -30, -26, -20, -16, -13, -13, -13, -13, -13, -11, -8, -6}}}, /* 7 */ {{{-20, -20, -20, -20, -20, -18, -14, -10, -4, 0, 0, 0, 0, 4, 6, 6, 12}, {-34, -34, -34, -34, -30, -30, -30, -24, -16, -10, -8, -6, -6, -6, -5, -3, 1}, {-34, -34, -34, -34, -32, -32, -28, -22, -18, -16, -16, -16, -16, -16, -14, -12, -10}}}, /* 8 */ {{{-22, -22, -22, -22, -22, -20, -14, -10, -4, 0, 0, 0, 0, 3, 5, 5, 11}, {-34, -34, -34, -34, -30, -30, -30, -24, -16, -12, -10, -8, -8, -8, -7, -5, -2}, {-36, -36, -36, -36, -36, -34, -28, -22, -20, -20, -20, -20, -20, -20, -20, -16, -14}}}, /* 9 */ {{{-28, -28, -28, -28, -28, -28, -28, -20, -14, -8, -2, -2, -2, -2, 0, 2, 6}, {-36, -36, -36, -36, -34, -32, -32, -24, -16, -12, -12, -12, -12, -12, -10, -8, -5}, {-40, -40, -40, -40, -40, -40, -40, -32, -26, -24, -24, -24, -24, -24, -24, -20, -18}}}, /* 10 */ {{{-30, -30, -30, -30, -30, -26, -24, -24, -24, -20, -12, -12, -12, -12, -12, -10, -8}, {-40, -40, -40, -40, -40, -40, -40, -40, -35, -30, -25, -25, -25, -25, -25, -25, -15}, {-40, -40, -40, -40, -40, -40, -40, -40, -40, -40, -40, -40, -40, -40, -40, -40, -40}}}, }; static const noiseguard _psy_noiseguards_44[4] = { {3, 3, 15}, {3, 3, 15}, {10, 10, 100}, {10, 10, 100}, }; static const int _psy_tone_suppress[12] = { -20, -20, -20, -20, -20, -24, -30, -40, -40, -45, -45, -45, }; static const int _psy_tone_0dB[12] = { 90, 90, 95, 95, 95, 95, 105, 105, 105, 105, 105, 105, }; static const int _psy_noise_suppress[12] = { -20, -20, -24, -24, -24, -24, -30, -40, -40, -45, -45, -45, }; static const vorbis_info_psy _psy_info_template = { /* blockflag */ -1, /* ath_adjatt, ath_maxatt */ -140., -140., /* tonemask att boost/decay,suppr,curves */ {0.f, 0.f, 0.f}, 0., 0., -40.f, {0.}, /*noisemaskp,supp, low/high window, low/hi guard, minimum */ 1, -0.f, .5f, .5f, 0, 0, 0, /* noiseoffset*3, noisecompand, max_curve_dB */ {{-1}, {-1}, {-1}}, {-1}, 105.f, /* noise normalization - noise_p, start, partition, thresh. */ 0, -1, -1, 0., }; /* ath ****************/ static const int _psy_ath_floater[12] = { -100, -100, -100, -100, -100, -100, -105, -105, -105, -105, -110, -120, }; static const int _psy_ath_abs[12] = { -130, -130, -130, -130, -140, -140, -140, -140, -140, -140, -140, -150, }; /* stereo setup. These don't map directly to quality level, there's an additional indirection as several of the below may be used in a single bitmanaged stream ****************/ /* various stereo possibilities */ /* stereo mode by base quality level */ static const adj_stereo _psy_stereo_modes_44[12] = { /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 -1 */ {{4, 4, 4, 4, 4, 4, 4, 3, 2, 2, 1, 0, 0, 0, 0}, {8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 5, 4, 3}, {1, 2, 3, 4, 4, 4, 4, 4, 4, 5, 6, 7, 8, 8, 8}, {12, 12.5, 13, 13.5, 14, 14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}}, /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 0 */ {{4, 4, 4, 4, 4, 4, 4, 3, 2, 1, 0, 0, 0, 0, 0}, {8, 8, 8, 8, 6, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3}, {1, 2, 3, 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 8, 8}, {12, 12.5, 13, 13.5, 14, 14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}}, /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 1 */ {{3, 3, 3, 3, 3, 3, 3, 3, 2, 1, 0, 0, 0, 0, 0}, {8, 8, 8, 8, 6, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3}, {1, 2, 3, 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 8, 8}, {99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}}, /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 2 */ {{3, 3, 3, 3, 3, 3, 3, 2, 1, 1, 0, 0, 0, 0, 0}, {8, 8, 6, 6, 5, 5, 4, 4, 4, 4, 4, 4, 3, 2, 1}, {3, 4, 4, 5, 5, 6, 6, 6, 6, 6, 6, 8, 8, 8, 8}, {99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}}, /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 3 */ {{2, 2, 2, 2, 2, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0}, {5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 2, 1}, {4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 10, 10, 10, 10, 10}, {99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}}, /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 4 */ {{2, 2, 2, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 3, 2, 1, 0}, {6, 6, 6, 8, 8, 8, 8, 8, 8, 8, 10, 10, 10, 10, 10}, {99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}}, /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 5 */ {{2, 2, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0}, {6, 7, 8, 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12}, {99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}}, /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 6 */ {{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {3, 3, 3, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {8, 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12}, {99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}}, /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 7 */ {{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {3, 3, 3, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12}, {99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}}, /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 8 */ {{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12}, {99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}}, /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 9 */ {{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4}, {99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}}, /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 10 */ {{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4}, {99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}}, }; /* tone master attenuation by base quality mode and bitrate tweak */ static const att3 _psy_tone_masteratt_44[12] = { {{35, 21, 9}, 0, 0}, /* -1 */ {{30, 20, 8}, -2, 1.25}, /* 0 */ /* {{ 25, 14, 4}, 0, 0}, */ /* 1 */ {{25, 12, 2}, 0, 0}, /* 1 */ /* {{ 20, 10, -2}, 0, 0}, */ /* 2 */ {{20, 9, -3}, 0, 0}, /* 2 */ {{20, 9, -4}, 0, 0}, /* 3 */ {{20, 9, -4}, 0, 0}, /* 4 */ {{20, 6, -6}, 0, 0}, /* 5 */ {{20, 3, -10}, 0, 0}, /* 6 */ {{18, 1, -14}, 0, 0}, /* 7 */ {{18, 0, -16}, 0, 0}, /* 8 */ {{18, -2, -16}, 0, 0}, /* 9 */ {{12, -2, -20}, 0, 0}, /* 10 */ }; /* lowpass by mode **************/ static const double _psy_lowpass_44[12] = { /* 15.1,15.8,16.5,17.9,20.5,48.,999.,999.,999.,999.,999. */ 13.9, 15.1, 15.8, 16.5, 17.2, 18.9, 20.1, 48., 999., 999., 999., 999.}; /* noise normalization **********/ static const int _noise_start_short_44[11] = { /* 16,16,16,16,32,32,9999,9999,9999,9999 */ 32, 16, 16, 16, 32, 9999, 9999, 9999, 9999, 9999, 9999}; static const int _noise_start_long_44[11] = { /* 128,128,128,256,512,512,9999,9999,9999,9999 */ 256, 128, 128, 256, 512, 9999, 9999, 9999, 9999, 9999, 9999}; static const int _noise_part_short_44[11] = {8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8}; static const int _noise_part_long_44[11] = {32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32}; static const double _noise_thresh_44[11] = { /* .2,.2,.3,.4,.5,.5,9999.,9999.,9999.,9999., */ .2, .2, .2, .4, .6, 9999., 9999., 9999., 9999., 9999., 9999., }; static const double _noise_thresh_5only[2] = { .5, .5, };
#!/usr/bin/python """ @file routecheck.py @author Michael Behrisch @author Jakob Erdmann @author Yun-Pang Floetteroed @date 2007-03-09 @version $Id$ This script does simple checks for the routes on a given network. Warnings will be issued if there is an unknown edge in the route, if the route is disconnected, or if the route definition does not use the edges attribute. If one specifies -f or --fix all route files will be fixed (if possible). At the moment this means adding an intermediate edge if just one link is missing in a disconnected route, or adding an edges attribute if it is missing. All changes are documented within the output file which has the same name as the input file with an additional .fixed suffix. If the route file uses the old format (<route>edge1 edge2</route>) this is changed without adding comments. The same is true for camelCase changes of attributes. SUMO, Simulation of Urban MObility; see http://sumo.dlr.de/ Copyright (C) 2007-2017 DLR (http://www.dlr.de/) and contributors This file is part of SUMO. SUMO 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 3 of the License, or (at your option) any later version. """ from __future__ import absolute_import from __future__ import print_function import os import sys try: from StringIO import StringIO except ImportError: from io import StringIO from xml.sax import saxutils, make_parser, handler from optparse import OptionParser from collections import defaultdict camelCase = {"departlane": "departLane", "departpos": "departPos", "departspeed": "departSpeed", "arrivallane": "arrivalLane", "arrivalpos": "arrivalPos", "arrivalspeed": "arrivalSpeed", "maxspeed": "maxSpeed", "bus_stop": "busStop", "vclass": "vClass", "fromtaz": "fromTaz", "totaz": "toTaz", "no": "number", "vtype": "vType", "vtypeDistribution": "vTypeDistribution", "tripdef": "trip"} deletedKeys = defaultdict(list) deletedKeys["route"] = ["edges", "multi_ref"] class NetReader(handler.ContentHandler): def __init__(self): self._nb = {} def startElement(self, name, attrs): if name == 'edge' and ('function' not in attrs or attrs['function'] != 'internal'): self._nb[attrs['id']] = set() elif name == 'connection': if attrs['from'] in self._nb and attrs['to'] in self._nb: self._nb[attrs['from']].add(attrs['to']) def hasEdge(self, edge): return edge in self._nb def isNeighbor(self, orig, dest): return dest in self._nb[orig] def getIntermediateEdge(self, orig, dest): for inter in self._nb[orig]: if dest in self._nb[inter]: return inter return '' class RouteReader(handler.ContentHandler): def __init__(self, net, outFileName): self._vID = '' self._routeID = '' self._routeString = '' self._addedString = '' self._net = net if outFileName: self._out = open(outFileName, 'w') else: self._out = None self._fileOut = None self._isRouteValid = True self._changed = False def startDocument(self): if self._out: print('<?xml version="1.0"?>', file=self._out) def endDocument(self): if self._out: self._out.close() if not self._changed: os.remove(self._out.name) def condOutputRedirect(self): if self._out and not self._fileOut: self._fileOut = self._out self._out = StringIO() def endOutputRedirect(self): if self._fileOut: if not self._isRouteValid: self._changed = True self._fileOut.write("<!-- ") self._fileOut.write(self._out.getvalue()) if not self._isRouteValid: self._fileOut.write(" -->") if self._addedString != '': self._fileOut.write( "<!-- added edges: " + self._addedString + "-->") self._addedString = '' self._out.close() self._out = self._fileOut self._fileOut = None def startElement(self, name, attrs): if name == 'vehicle' and 'route' not in attrs: self.condOutputRedirect() self._vID = attrs['id'] if name == 'route': self.condOutputRedirect() if 'id' in attrs: self._routeID = attrs['id'] else: self._routeID = "for vehicle " + self._vID self._routeString = '' if 'edges' in attrs: self._routeString = attrs['edges'] else: self._changed = True print("Warning: No edges attribute in route " + self._routeID) elif self._routeID: print( "Warning: This script does not handle nested '%s' elements properly." % name) if self._out: if name in camelCase: name = camelCase[name] self._changed = True self._out.write('<' + name) if options.fix_length and 'length' in attrs and 'minGap' not in attrs: length = float(attrs["length"]) minGap = 2.5 if 'guiOffset' in attrs: minGap = float(attrs["guiOffset"]) attrs = dict(attrs) attrs["length"] = str(length - minGap) attrs["minGap"] = str(minGap) self._changed = True for key, value in sorted(attrs.items()): if key in camelCase: key = camelCase[key] self._changed = True if key not in deletedKeys[name]: self._out.write(' %s="%s"' % (key, saxutils.escape(value))) if name != 'route': if name in ["ride", "stop", "walk"]: self._out.write('/') self._out.write('>') def endElement(self, name): if name in ["ride", "stop", "walk"]: return if name == 'route': self._isRouteValid = self.testRoute() if self._out: self._out.write(' edges="%s"/>' % self._routeString) self._routeID = '' self._routeString = '' if self._vID == '': self.endOutputRedirect() elif name == 'vehicle' and self._vID != '': self._vID = '' if self._out: self._out.write('</vehicle>') self.endOutputRedirect() elif self._out: self._out.write('</%s>' % camelCase.get(name, name)) def characters(self, content): if self._routeID != '': self._routeString += content elif self._out: self._out.write(saxutils.escape(content)) def testRoute(self): if self._routeID != '': returnValue = True edgeList = self._routeString.split() if len(edgeList) == 0: print("Warning: Route %s is empty" % self._routeID) return False if net is None: return True doConnectivityTest = True cleanedEdgeList = [] for v in edgeList: if self._net.hasEdge(v): cleanedEdgeList.append(v) else: print( "Warning: Unknown edge " + v + " in route " + self._routeID) returnValue = False while doConnectivityTest: doConnectivityTest = False for i, v in enumerate(cleanedEdgeList): if i < len(cleanedEdgeList) - 1 and not self._net.isNeighbor(v, cleanedEdgeList[i + 1]): print("Warning: Route " + self._routeID + " disconnected between " + v + " and " + cleanedEdgeList[i + 1]) interEdge = self._net.getIntermediateEdge( v, cleanedEdgeList[i + 1]) if interEdge != '': cleanedEdgeList.insert(i + 1, interEdge) self._changed = True self._addedString += interEdge + " " self._routeString = ' '.join(cleanedEdgeList) doConnectivityTest = True break returnValue = False return returnValue return False def ignorableWhitespace(self, content): if self._out: self._out.write(content) def processingInstruction(self, target, data): if self._out: self._out.write('<?%s %s?>' % (target, data)) optParser = OptionParser( usage=os.path.basename(__file__) + " [options] <routes>*") optParser.add_option("-v", "--verbose", action="store_true", default=False, help="tell me what you are doing") optParser.add_option("-f", "--fix", action="store_true", default=False, help="fix errors into '.fixed' file") optParser.add_option("-l", "--fix-length", action="store_true", default=False, help="fix vehicle type's length and guiOffset attributes") optParser.add_option("-i", "--inplace", action="store_true", default=False, help="replace original files") optParser.add_option("-n", "--net", help="network to check connectivity") (options, args) = optParser.parse_args() if len(args) == 0: optParser.print_help() sys.exit() parser = make_parser() net = None if options.net: net = NetReader() parser.setContentHandler(net) parser.parse(options.net) parser.setContentHandler(RouteReader(net, '')) if options.fix_length: deletedKeys["vType"] += ['guiOffset'] for f in args: ffix = f + '.fixed' if options.fix: if options.verbose: print("fixing " + f) parser.setContentHandler(RouteReader(net, ffix)) else: if options.verbose: print("checking " + f) parser.parse(f) if options.fix and os.path.exists(ffix) and options.inplace: os.rename(ffix, f)
//======================================================= // File Name : wcard.h //======================================================= #ifndef __WCARD_H_ #define __WCARD_H_ #include <stdio.h> #include <sys/socket.h> #include <arpa/inet.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <math.h> #include <pthread.h> #include <sys/time.h> #include <slack/prog.h> #include "gwcenter.h" #include "mobility.h" #include "mathlib.h" #include "antenna.h" #include "energy.h" #include "channel.h" #include "propagation.h" #include "nomac.h" #include "mac.h" #include "802_11_frame.h" #include "timer.h" #include "wirelessphy.h" #include "vpl.h" #include "event.h" #include "errmodel.h" #include "awgn.h" #include "fading.h" #include "llc.h" void IniNodeWirelessCard(NodeType type); void FinalizeNodeWirelessCard(NodeType type); void SetWCardPrama( MobileNode *node, WCard_type Type); void ChWcardBandWidth(double bandwidth); #endif
export default { 'dictionary.yiji': 'Lớp 1', 'dictionary.erji': 'Thể loại phụ', 'dictionary.table.add': 'Thêm', 'dictionary.table.col1': 'Sắp xếp', 'dictionary.table.col2': 'Tên', 'dictionary.table.col3': 'Bí danh song ngữ', 'dictionary.table.col4': 'Có nên bắt đầu không', 'dictionary.table.col5': 'Tạo thời gian', 'dictionary.table.col6': 'Hoạt động', 'dictionary.table.col7': 'tên phụ', 'dictionary.table.col8': 'Thuộc về loại đầu tiên', 'dictionary.table.col9': 'Nhóm cho phép tối thiểu', 'dictionary.table.deleteconfirm': 'Xác nhận xóa', 'dictionary.table.edit': 'Chỉnh sửa', 'dictionary.table.delete': 'xóa', 'dictionary.table.s1': 'Đơn giá', 'dictionary.table.s2': 'Số tiền sửa đổi', 'dictionary.table.s3': 'Đơn vị', 'dictionary.table.s4': 'tên ghi chú', 'dictionary.table.s5': 'Phương pháp tư vấn', 'dictionary.table.s6': 'Kết quả tham vấn', 'dictionary.table.s7': 'Tiền tố', };
#!/usr/bin/env python3 from __future__ import print_function import unittest import torch from captum.attr._models.base import ( InterpretableEmbeddingBase, configure_interpretable_embedding_layer, remove_interpretable_embedding_layer, ) from tests.helpers.basic import assertTensorAlmostEqual from tests.helpers.basic_models import BasicEmbeddingModel, TextModule from torch.nn import Embedding class Test(unittest.TestCase): def test_interpretable_embedding_base(self): input1 = torch.tensor([2, 5, 0, 1]) input2 = torch.tensor([3, 0, 0, 2]) model = BasicEmbeddingModel() output = model(input1, input2) interpretable_embedding1 = configure_interpretable_embedding_layer( model, "embedding1" ) self.assertEqual(model.embedding1, interpretable_embedding1) self._assert_embeddings_equal( input1, output, interpretable_embedding1, model.embedding1.embedding_dim, model.embedding1.num_embeddings, ) interpretable_embedding2 = configure_interpretable_embedding_layer( model, "embedding2.inner_embedding" ) self.assertEqual(model.embedding2.inner_embedding, interpretable_embedding2) self._assert_embeddings_equal( input2, output, interpretable_embedding2, model.embedding2.inner_embedding.embedding_dim, model.embedding2.inner_embedding.num_embeddings, ) # configure another embedding when one is already configured with self.assertRaises(AssertionError): configure_interpretable_embedding_layer(model, "embedding2.inner_embedding") with self.assertRaises(AssertionError): configure_interpretable_embedding_layer(model, "embedding1") # remove interpretable embedding base self.assertTrue( model.embedding2.inner_embedding.__class__ is InterpretableEmbeddingBase ) remove_interpretable_embedding_layer(model, interpretable_embedding2) self.assertTrue(model.embedding2.inner_embedding.__class__ is Embedding) self.assertTrue(model.embedding1.__class__ is InterpretableEmbeddingBase) remove_interpretable_embedding_layer(model, interpretable_embedding1) self.assertTrue(model.embedding1.__class__ is Embedding) def test_custom_module(self): input1 = torch.tensor([[3, 2, 0], [1, 2, 4]]) input2 = torch.tensor([[0, 1, 0], [1, 2, 3]]) model = BasicEmbeddingModel() output = model(input1, input2) expected = model.embedding2(input=input2) # in this case we make interpretable the custom embedding layer - TextModule interpretable_embedding = configure_interpretable_embedding_layer( model, "embedding2" ) actual = interpretable_embedding.indices_to_embeddings(input=input2) output_interpretable_models = model(input1, actual) assertTensorAlmostEqual( self, output, output_interpretable_models, delta=0.05, mode="max" ) assertTensorAlmostEqual(self, expected, actual, delta=0.0, mode="max") self.assertTrue(model.embedding2.__class__ is InterpretableEmbeddingBase) remove_interpretable_embedding_layer(model, interpretable_embedding) self.assertTrue(model.embedding2.__class__ is TextModule) self._assert_embeddings_equal(input2, output, interpretable_embedding) def test_nested_multi_embeddings(self): input1 = torch.tensor([[3, 2, 0], [1, 2, 4]]) input2 = torch.tensor([[0, 1, 0], [2, 6, 8]]) input3 = torch.tensor([[4, 1, 0], [2, 2, 8]]) model = BasicEmbeddingModel(nested_second_embedding=True) output = model(input1, input2, input3) expected = model.embedding2(input=input2, another_input=input3) # in this case we make interpretable the custom embedding layer - TextModule interpretable_embedding2 = configure_interpretable_embedding_layer( model, "embedding2" ) actual = interpretable_embedding2.indices_to_embeddings( input=input2, another_input=input3 ) output_interpretable_models = model(input1, actual) assertTensorAlmostEqual( self, output, output_interpretable_models, delta=0.05, mode="max" ) assertTensorAlmostEqual(self, expected, actual, delta=0.0, mode="max") self.assertTrue(model.embedding2.__class__ is InterpretableEmbeddingBase) remove_interpretable_embedding_layer(model, interpretable_embedding2) self.assertTrue(model.embedding2.__class__ is TextModule) self._assert_embeddings_equal(input2, output, interpretable_embedding2) def _assert_embeddings_equal( self, input, output, interpretable_embedding, embedding_dim=None, num_embeddings=None, ): if interpretable_embedding.embedding_dim is not None: self.assertEqual(embedding_dim, interpretable_embedding.embedding_dim) self.assertEqual(num_embeddings, interpretable_embedding.num_embeddings) # dim - [4, 100] emb_shape = interpretable_embedding.indices_to_embeddings(input).shape self.assertEqual(emb_shape[0], input.shape[0]) if interpretable_embedding.embedding_dim is not None: self.assertEqual(emb_shape[1], interpretable_embedding.embedding_dim) self.assertEqual(input.shape[0], output.shape[0])
#!/usr/bin/env python # -*- coding: UTF-8 -*- # File: _test.py # Author: Yuxin Wu <ppwwyyxx@gmail.com> import logging import tensorflow as tf import unittest class TestModel(unittest.TestCase): def run_variable(self, var): sess = tf.Session() sess.run(tf.global_variables_initializer()) if isinstance(var, list): return sess.run(var) else: return sess.run([var])[0] def make_variable(self, *args): if len(args) > 1: return [tf.Variable(k) for k in args] else: return tf.Variable(args[0]) def run_test_case(case): suite = unittest.TestLoader().loadTestsFromTestCase(case) unittest.TextTestRunner(verbosity=2).run(suite) if __name__ == '__main__': import tensorpack from tensorpack.utils import logger from . import * logger.setLevel(logging.CRITICAL) subs = tensorpack.models._test.TestModel.__subclasses__() for cls in subs: run_test_case(cls)
import sublime import sublime_plugin import re SETTINGS_FILE = 'wrap_it.sublime-settings' PREFS = sublime.load_settings(SETTINGS_FILE) DEFINITIONS = PREFS.get('definitions') SELECTION_TAG = "<sel>" def detect_syntax(window): """ Detects syntax and returns wrappers. """ active_syntax = window.active_view().settings().get('syntax') for language in DEFINITIONS: if active_syntax in language["syntaxes"]: active_wrappers = [w for w in language["wrappers"] if w["name"] and w["template"]] if not active_wrappers: window.status_message('WrapIt: Current Syntax NOT Supported') return opts = [[w["name"], w["description"]] for w in active_wrappers] templates = [w["template"] for w in active_wrappers] return opts, templates class WrapItCommand(sublime_plugin.TextCommand): def run(self, edit, template_name): _, templates = detect_syntax(self.window) try: template = templates[template_name] except KeyError: msg = "WrapIt:: Template: {} not defined or wrong syntax." self.view.active_window.status_message(msg.format(template_name)) else: self.view.run_command('wrap', {"template": template}) class WrapItMenuCommand(sublime_plugin.WindowCommand): """ Detect current file syntax and return the menu chosen template. An unsupported syntax will trigger a status bar warning. """ def run(self): opts, self.templates = detect_syntax(self.window) self.window.show_quick_panel(opts, self.on_done) def on_done(self, opt): """ Callback for quick panel, calls wrap command. """ try: template = self.templates[opt] except IndexError: self.window.status_message('WrapIt: Sublime Wrap Cancelled.') except KeyError: msg = "WrapIt: Definitions malformed or template missing." self.window.status_message(msg) else: active_view = self.window.active_view() active_view.run_command('wrap', {"template": template}) class WrapCommand(sublime_plugin.TextCommand): def get_indent(self, text): """ Returns smallest indentation (distance from line start). """ spaces = [] tabs = [] for line in text.splitlines(): space_match = re.search("^ +", line) tab_match = re.search("^\t+", line) if space_match: spaces.append(space_match.group(0)) if tab_match: tabs.append(tab_match.group(0)) if spaces: indent = ' ' * len(min(spaces)) elif tabs: indent = '\t' * len(min(tabs)) else: indent = '' return indent def fill_template(self, text, template, indent, tab_size): tab_sel_tag = "\t" + SELECTION_TAG text = re.sub('$', '\$', text) # escape $ # if selection should be indentend and is not already: if not re.search(tab_sel_tag, template): tab_sel_tag = SELECTION_TAG else: # else indent one tab_size spacer = " " * tab_size lines = text.splitlines() lines = [spacer + l.strip() for l in lines] text = "\n".join(lines) return re.sub(tab_sel_tag, text, template) def run(self, edit, template): for sel in self.view.sel(): # window = sublime.active_window() # view = window.active_view() settings = self.view.settings() tab_size = 4 if settings.has("translate_tabs_to_spaces"): tab_size = settings.get("tab_size", 4) region = self.view.line(sel) text = self.view.substr(region) indent = self.get_indent(text) filled_template = self.fill_template( text, template, indent, tab_size) lines = [indent + l for l in filled_template.splitlines() if l] new_text = '\n'.join(lines) if template.startswith('\n'): new_text = '\n' + new_text self.view.erase(edit, region) self.view.run_command('insert_snippet', {'contents': new_text})
# -*- coding: utf-8 -*- from __future__ import absolute_import from django.conf import settings from django.conf.urls import include, url from django.contrib import admin from django.views.static import serve from filer.utils.compatibility import GTE_DJANGO_1_9 admin.autodiscover() admin_urls = admin.site.urls if not GTE_DJANGO_1_9: admin_urls = include(admin_urls) urlpatterns = [ url(r'^media/(?P<path>.*)$', serve, {'document_root': settings.MEDIA_ROOT, 'show_indexes': True}), url(r'^admin/', admin_urls), url(r'^', include('filer.server.urls')), url(r'^filer/', include('filer.urls')), ]
import React, { Component } from 'react'; class Info extends Component { render() { return ( <div> 这里是测试动态路由功能。 动态路由的值是:{this.props.match.params.value} </div> ) } } export default Info;
import { get } from '@ember/object'; import { run } from '@ember/runloop'; import RSVP, { resolve } from 'rsvp'; import setupStore from 'dummy/tests/helpers/store'; import { module, test } from 'qunit'; import JSONAPIAdapter from 'ember-data/adapters/json-api'; import JSONAPISerializer from 'ember-data/serializers/json-api'; import { setupTest } from 'ember-qunit'; import Store from 'ember-data/store'; import Model from 'ember-data/model'; import { attr, belongsTo } from '@ember-decorators/data'; import testInDebug, { testRecordData } from 'dummy/tests/helpers/test-in-debug'; import { setup as setupModelFactoryInjections, reset as resetModelFactoryInjection, } from 'dummy/tests/helpers/model-factory-injection'; import DS from 'ember-data'; import { RecordData } from 'ember-data/-private'; const { attr: DSattr, hasMany: DShasMany, belongsTo: DSbelongsTo } = DS; const { hash } = RSVP; let env, store, User, Message, Post, Comment, Book, Book1, Chapter, Author, NewMessage, Section; module('integration/relationship/belongs-to BelongsTo Relationships (new-style)', function(hooks) { let store; setupTest(hooks); class Person extends Model { @belongsTo('pet', { inverse: 'bestHuman', async: true }) bestDog; @attr name; } class Pet extends Model { @belongsTo('person', { inverse: 'bestDog', async: false }) bestHuman; @attr name; } hooks.beforeEach(function() { let { owner } = this; owner.register('service:store', Store); owner.register('model:person', Person); owner.register('model:pet', Pet); owner.register( 'serializer:application', JSONAPISerializer.extend({ normalizeResponse(_, __, payload) { return payload; }, }) ); store = owner.lookup('service:store'); }); test("async belongsTo chains the related record's loading promise when present", async function(assert) { let petFindRecordCalls = 0; this.owner.register( 'adapter:pet', JSONAPIAdapter.extend({ findRecord() { assert.equal(++petFindRecordCalls, 1, 'We call findRecord only once for our pet'); return resolve({ data: { type: 'pet', id: '1', attributes: { name: 'Shen' }, relationships: { bestHuman: { data: { type: 'person', id: '1' }, }, }, }, }); }, findBelongsTo() { return this.store.adapterFor('person').findRecord(); }, }) ); let personFindRecordCalls = 0; this.owner.register( 'adapter:person', JSONAPIAdapter.extend({ findRecord() { assert.equal(++personFindRecordCalls, 1, 'We call findRecord only once for our person'); return resolve({ data: { type: 'person', id: '1', attributes: { name: 'Chris' }, relationships: { bestDog: { data: { type: 'pet', id: '1' }, links: { related: './pet/1', }, }, }, }, }); }, findBelongsTo() { return this.store.adapterFor('pet').findRecord(); }, }) ); let person = await store.findRecord('person', '1'); let petRequest = store.findRecord('pet', '1'); let personPetRequest = person.get('bestDog'); let personPet = await personPetRequest; let pet = await petRequest; assert.ok(personPet === pet, 'We ended up in the same state'); }); test('async belongsTo returns correct new value after a local change', async function(assert) { let chris = store.push({ data: { type: 'person', id: '1', attributes: { name: 'Chris' }, relationships: { bestDog: { data: null, }, }, }, included: [ { type: 'pet', id: '1', attributes: { name: 'Shen' }, relationships: { bestHuman: { data: null, }, }, }, { type: 'pet', id: '2', attributes: { name: 'Pirate' }, relationships: { bestHuman: { data: null, }, }, }, ], }); let shen = store.peekRecord('pet', '1'); let pirate = store.peekRecord('pet', '2'); let bestDog = await chris.get('bestDog'); assert.ok(shen.get('bestHuman') === null, 'precond - Shen has no best human'); assert.ok(pirate.get('bestHuman') === null, 'precond - pirate has no best human'); assert.ok(bestDog === null, 'precond - Chris has no best dog'); chris.set('bestDog', shen); bestDog = await chris.get('bestDog'); assert.ok(shen.get('bestHuman') === chris, "scene 1 - Chris is Shen's best human"); assert.ok(pirate.get('bestHuman') === null, 'scene 1 - pirate has no best human'); assert.ok(bestDog === shen, "scene 1 - Shen is Chris's best dog"); chris.set('bestDog', pirate); bestDog = await chris.get('bestDog'); assert.ok(shen.get('bestHuman') === null, "scene 2 - Chris is no longer Shen's best human"); assert.ok(pirate.get('bestHuman') === chris, 'scene 2 - pirate now has Chris as best human'); assert.ok(bestDog === pirate, "scene 2 - Pirate is now Chris's best dog"); chris.set('bestDog', null); bestDog = await chris.get('bestDog'); assert.ok( shen.get('bestHuman') === null, "scene 3 - Chris remains no longer Shen's best human" ); assert.ok( pirate.get('bestHuman') === null, 'scene 3 - pirate no longer has Chris as best human' ); assert.ok(bestDog === null, 'scene 3 - Chris has no best dog'); }); }); module('integration/relationship/belongs_to Belongs-To Relationships', { beforeEach() { User = DS.Model.extend({ name: DSattr('string'), messages: DShasMany('message', { polymorphic: true, async: false }), favouriteMessage: DSbelongsTo('message', { polymorphic: true, inverse: null, async: false }), }); Message = DS.Model.extend({ user: DSbelongsTo('user', { inverse: 'messages', async: false }), created_at: DSattr('date'), }); Post = Message.extend({ title: DSattr('string'), comments: DShasMany('comment', { async: false, inverse: null }), }); Comment = Message.extend({ body: DS.attr('string'), message: DS.belongsTo('message', { polymorphic: true, async: false, inverse: null }), }); Book = DS.Model.extend({ name: DSattr('string'), author: DSbelongsTo('author', { async: false }), chapters: DShasMany('chapters', { async: false, inverse: 'book' }), }); Book1 = DS.Model.extend({ name: DSattr('string'), }); Chapter = DS.Model.extend({ title: DSattr('string'), book: DSbelongsTo('book', { async: false, inverse: 'chapters' }), }); Author = DS.Model.extend({ name: DSattr('string'), books: DShasMany('books', { async: false }), }); Section = DS.Model.extend({ name: DSattr('string'), }); env = setupStore({ user: User, post: Post, comment: Comment, message: Message, book: Book, book1: Book1, chapter: Chapter, author: Author, section: Section, }); env.registry.optionsForType('serializer', { singleton: false }); env.registry.optionsForType('adapter', { singleton: false }); env.registry.register( 'serializer:user', DS.JSONAPISerializer.extend({ attrs: { favouriteMessage: { embedded: 'always' }, }, }) ); store = env.store; User = store.modelFor('user'); Post = store.modelFor('post'); Comment = store.modelFor('comment'); Message = store.modelFor('message'); Book = store.modelFor('book'); Chapter = store.modelFor('chapter'); Author = store.modelFor('author'); }, afterEach() { resetModelFactoryInjection(); run(env.container, 'destroy'); }, }); test('returning a null relationship from payload sets the relationship to null on both sides', function(assert) { env.registry.register( 'model:app', DS.Model.extend({ name: DSattr('string'), team: DSbelongsTo('team', { async: true }), }) ); env.registry.register( 'model:team', DS.Model.extend({ apps: DShasMany('app', { async: true }), }) ); run(() => { env.store.push({ data: { id: '1', type: 'app', relationships: { team: { data: { id: '1', type: 'team', }, }, }, }, included: [ { id: '1', type: 'team', relationships: { apps: { data: [ { id: '1', type: 'app', }, ], }, }, }, ], }); }); const app = env.store.peekRecord('app', '1'); const team = env.store.peekRecord('team', '1'); assert.equal(app.get('team.id'), team.get('id'), 'sets team correctly on app'); assert.deepEqual( team .get('apps') .toArray() .mapBy('id'), ['1'], 'sets apps correctly on team' ); env.adapter.shouldBackgroundReloadRecord = () => false; env.adapter.updateRecord = (store, type, snapshot) => { return RSVP.resolve({ data: { id: '1', type: 'app', attributes: { name: 'Hello', }, relationships: { team: { data: null, }, }, }, }); }; return run(() => { app.set('name', 'Hello'); return app.save().then(() => { assert.equal(app.get('team.id'), null, 'team removed from app relationship'); assert.deepEqual( team .get('apps') .toArray() .mapBy('id'), [], 'app removed from team apps relationship' ); }); }); }); test('The store can materialize a non loaded monomorphic belongsTo association', function(assert) { assert.expect(1); env.store.modelFor('post').reopen({ user: DS.belongsTo('user', { async: true, inverse: 'messages', }), }); env.adapter.shouldBackgroundReloadRecord = () => false; env.adapter.findRecord = function(store, type, id, snapshot) { assert.ok(true, "The adapter's find method should be called"); return resolve({ data: { id, type: snapshot.modelName, }, }); }; run(() => { env.store.push({ data: { id: '1', type: 'post', relationships: { user: { data: { id: '2', type: 'user', }, }, }, }, }); }); return run(() => { return env.store.findRecord('post', 1).then(post => { post.get('user'); }); }); }); testInDebug('Invalid belongsTo relationship identifiers throw errors', function(assert) { assert.expect(2); let { store } = env; // test null id assert.expectAssertion(() => { run(() => { let post = store.push({ data: { id: '1', type: 'post', relationships: { user: { data: { id: null, type: 'user', }, }, }, }, }); post.get('user'); }); }, `Assertion Failed: Encountered a relationship identifier without an id for the belongsTo relationship 'user' on <post:1>, expected a json-api identifier but found '{"id":null,"type":"user"}'. Please check your serializer and make sure it is serializing the relationship payload into a JSON API format.`); // test missing type assert.expectAssertion(() => { run(() => { let post = store.push({ data: { id: '2', type: 'post', relationships: { user: { data: { id: '1', type: null, }, }, }, }, }); post.get('user'); }); }, `Assertion Failed: Encountered a relationship identifier without a type for the belongsTo relationship 'user' on <post:2>, expected a json-api identifier with type 'user' but found '{"id":"1","type":null}'. Please check your serializer and make sure it is serializing the relationship payload into a JSON API format.`); }); testInDebug( 'Only a record of the same modelClass can be used with a monomorphic belongsTo relationship', function(assert) { assert.expect(1); env.adapter.shouldBackgroundReloadRecord = () => false; run(() => { store.push({ data: { id: '1', type: 'post', }, }); store.push({ data: { id: '2', type: 'comment', }, }); }); return run(() => { return hash({ post: store.findRecord('post', 1), comment: store.findRecord('comment', 2), }).then(records => { assert.expectAssertion(() => { records.post.set('user', records.comment); }, /The 'comment' type does not implement 'user' and thus cannot be assigned to the 'user' relationship in 'post'/); }); }); } ); testInDebug( 'Only a record of the same base modelClass can be used with a polymorphic belongsTo relationship', function(assert) { env.adapter.shouldBackgroundReloadRecord = () => false; assert.expect(1); run(() => { store.push({ data: [ { id: '1', type: 'comment', }, { id: '2', type: 'comment', }, ], }); store.push({ data: { id: '1', type: 'post', }, }); store.push({ data: { id: '3', type: 'user', }, }); }); return run(() => { let asyncRecords = hash({ user: store.findRecord('user', 3), post: store.findRecord('post', 1), comment: store.findRecord('comment', 1), anotherComment: store.findRecord('comment', 2), }); return asyncRecords.then(records => { let comment = records.comment; comment.set('message', records.anotherComment); comment.set('message', records.post); comment.set('message', null); assert.expectAssertion(() => { comment.set('message', records.user); }, /The 'user' type does not implement 'message' and thus cannot be assigned to the 'message' relationship in 'comment'. Make it a descendant of 'message'/); }); }); } ); test('The store can load a polymorphic belongsTo association', function(assert) { env.adapter.shouldBackgroundReloadRecord = () => false; run(() => { env.store.push({ data: { id: '1', type: 'post', }, }); env.store.push({ data: { id: '2', type: 'comment', relationships: { message: { data: { id: '1', type: 'post', }, }, }, }, }); }); return run(() => { return hash({ message: store.findRecord('post', 1), comment: store.findRecord('comment', 2), }).then(records => { assert.equal(records.comment.get('message'), records.message); }); }); }); test('The store can serialize a polymorphic belongsTo association', function(assert) { env.adapter.shouldBackgroundReloadRecord = () => false; let serializerInstance = store.serializerFor('comment'); serializerInstance.serializePolymorphicType = function(record, json, relationship) { assert.ok(true, "The serializer's serializePolymorphicType method should be called"); json['message_type'] = 'post'; }; return run(() => { env.store.push({ data: { id: '1', type: 'post', }, }); env.store.push({ data: { id: '2', type: 'comment', relationships: { message: { data: { id: '1', type: 'post', }, }, }, }, }); return store.findRecord('comment', 2).then(comment => { let serialized = comment.serialize({ includeId: true }); assert.equal(serialized.data.relationships.message.data.id, 1); assert.equal(serialized.data.relationships.message.data.type, 'posts'); }); }); }); test('A serializer can materialize a belongsTo as a link that gets sent back to findBelongsTo', function(assert) { env.adapter.shouldBackgroundReloadRecord = () => false; let Group = DS.Model.extend({ people: DS.hasMany('person', { async: false }), }); let Person = DS.Model.extend({ group: DS.belongsTo({ async: true }), }); env.registry.register('model:group', Group); env.registry.register('model:person', Person); run(() => { store.push({ data: { id: '1', type: 'person', relationships: { group: { links: { related: '/people/1/group', }, }, }, }, }); }); env.adapter.findRecord = function(store, type, id, snapshot) { throw new Error("Adapter's find method should not be called"); }; env.adapter.findBelongsTo = function(store, snapshot, link, relationship) { assert.equal(relationship.type, 'group'); assert.equal(relationship.key, 'group'); assert.equal(link, '/people/1/group'); return resolve({ data: { id: 1, type: 'group', relationships: { people: { data: [{ id: 1, type: 'person' }], }, }, }, }); }; return run(() => { return env.store .findRecord('person', 1) .then(person => { return person.get('group'); }) .then(group => { assert.ok(group instanceof Group, 'A group object is loaded'); assert.ok(group.get('id') === '1', 'It is the group we are expecting'); }); }); }); test('A record with an async belongsTo relationship always returns a promise for that relationship', function(assert) { env.adapter.shouldBackgroundReloadRecord = () => false; let Seat = DS.Model.extend({ person: DS.belongsTo('person', { async: false }), }); let Person = DS.Model.extend({ seat: DS.belongsTo('seat', { async: true }), }); env.registry.register('model:seat', Seat); env.registry.register('model:person', Person); run(() => { store.push({ data: { id: '1', type: 'person', relationships: { seat: { links: { related: '/people/1/seat', }, }, }, }, }); }); env.adapter.findRecord = function(store, type, id, snapshot) { throw new Error("Adapter's find method should not be called"); }; env.adapter.findBelongsTo = function(store, snapshot, link, relationship) { return resolve({ data: { id: 1, type: 'seat' } }); }; return run(() => { return env.store.findRecord('person', 1).then(person => { return person.get('seat').then(seat => { // this assertion fails too // ok(seat.get('person') === person, 'parent relationship should be populated'); seat.set('person', person); assert.ok(person.get('seat').then, 'seat should be a PromiseObject'); }); }); }); }); test('A record with an async belongsTo relationship returning null should resolve null', function(assert) { assert.expect(1); env.adapter.shouldBackgroundReloadRecord = () => false; let Group = DS.Model.extend({ people: DS.hasMany('person', { async: false }), }); let Person = DS.Model.extend({ group: DS.belongsTo({ async: true }), }); env.registry.register('model:group', Group); env.registry.register('model:person', Person); run(() => { store.push({ data: { id: '1', type: 'person', relationships: { group: { links: { related: '/people/1/group', }, }, }, }, }); }); env.adapter.findRecord = function(store, type, id, snapshot) { throw new Error("Adapter's find method should not be called"); }; env.adapter.findBelongsTo = function(store, snapshot, link, relationship) { return resolve({ data: null }); }; return env.store .findRecord('person', '1') .then(person => { return person.get('group'); }) .then(group => { assert.ok(group === null, 'group should be null'); }); }); test('A record can be created with a resolved belongsTo promise', function(assert) { assert.expect(1); env.adapter.shouldBackgroundReloadRecord = () => false; let Group = DS.Model.extend({ people: DS.hasMany('person', { async: false }), }); let Person = DS.Model.extend({ group: DS.belongsTo({ async: true }), }); env.registry.register('model:group', Group); env.registry.register('model:person', Person); run(() => { store.push({ data: { id: 1, type: 'group', }, }); }); let groupPromise = store.findRecord('group', 1); return groupPromise.then(group => { let person = env.store.createRecord('person', { group: groupPromise, }); assert.equal(person.get('group.content'), group); }); }); test('polymorphic belongsTo class-checks check the superclass when MODEL_FACTORY_INJECTIONS is enabled', function(assert) { assert.expect(1); run(() => { let igor = env.store.createRecord('user', { name: 'Igor' }); let post = env.store.createRecord('post', { title: "Igor's unimaginative blog post" }); igor.set('favouriteMessage', post); assert.equal(igor.get('favouriteMessage.title'), "Igor's unimaginative blog post"); }); }); test('the subclass in a polymorphic belongsTo relationship is an instanceof its superclass', function(assert) { setupModelFactoryInjections(false); assert.expect(1); let message = env.store.createRecord('message', { id: 1 }); let comment = env.store.createRecord('comment', { id: 2, message: message }); assert.ok(comment instanceof Message, 'a comment is an instance of a message'); }); test('relationshipsByName does not cache a factory', function(assert) { // The model is loaded up via a container. It has relationshipsByName // called on it. let modelViaFirstFactory = store.modelFor('user'); get(modelViaFirstFactory, 'relationshipsByName'); // An app is reset, or the container otherwise destroyed. run(env.container, 'destroy'); // A new model for a relationship is created. Note that this may happen // due to an extend call internal to MODEL_FACTORY_INJECTIONS. NewMessage = Message.extend(); // A new store is created. env = setupStore({ user: User, message: NewMessage, }); store = env.store; // relationshipsByName is called again. let modelViaSecondFactory = store.modelFor('user'); let relationshipsByName = get(modelViaSecondFactory, 'relationshipsByName'); let messageType = relationshipsByName.get('messages').type; // A model is looked up in the store based on a string, via user input let messageModelFromStore = store.modelFor('message'); // And the model is lookup up internally via the relationship type let messageModelFromRelationType = store.modelFor(messageType); assert.equal( messageModelFromRelationType, messageModelFromStore, 'model factory based on relationship type matches the model based on store.modelFor' ); }); test('relationship changes shouldn’t cause async fetches', function(assert) { assert.expect(2); /* Scenario: * --------- * * post HM async comments * comments bt sync post * * scenario: * - post hm C [1,2,3] * - post has a partially realized comments array comment#1 has been realized * - comment has not yet realized its post relationship * - comment is destroyed */ env.store.modelFor('post').reopen({ comments: DS.hasMany('comment', { async: true, inverse: 'post', }), }); env.store.modelFor('comment').reopen({ post: DS.belongsTo('post', { async: false }), }); let comment; run(() => { env.store.push({ data: { id: '1', type: 'post', relationships: { comments: { data: [ { id: '1', type: 'comment', }, { id: '2', type: 'comment', }, { id: '3', type: 'comment', }, ], }, }, }, }); comment = env.store.push({ data: { id: '1', type: 'comment', relationships: { post: { data: { id: '1', type: 'post', }, }, }, }, }); }); env.adapter.deleteRecord = function(store, type, snapshot) { assert.ok(snapshot.record instanceof type); assert.equal(snapshot.id, 1, 'should first comment'); return snapshot.record.toJSON({ includeId: true }); }; env.adapter.findMany = function(store, type, ids, snapshots) { assert.ok(false, 'should not need to findMay more comments, but attempted to anyways'); }; run(comment, 'destroyRecord'); }); test('Destroying a record with an unloaded aync belongsTo association does not fetch the record', function(assert) { assert.expect(2); let post; env.store.modelFor('message').reopen({ user: DS.hasMany('user', { async: true, }), }); env.store.modelFor('post').reopen({ user: DS.belongsTo('user', { async: true, inverse: 'messages', }), }); run(() => { post = env.store.push({ data: { id: '1', type: 'post', relationships: { user: { data: { id: '2', type: 'user', }, }, }, }, }); }); env.adapter.findRecord = function(store, type, id, snapshot) { throw new Error("Adapter's find method should not be called"); }; env.adapter.deleteRecord = function(store, type, snapshot) { assert.ok(snapshot.record instanceof type); assert.equal(snapshot.id, 1, 'should first post'); return { data: { id: '1', type: 'post', attributes: { title: null, 'created-at': null, }, relationships: { user: { data: { id: '2', type: 'user', }, }, }, }, }; }; run(post, 'destroyRecord'); }); testInDebug('A sync belongsTo errors out if the record is unloaded', function(assert) { let message; run(() => { message = env.store.push({ data: { id: '1', type: 'message', relationships: { user: { data: { id: '2', type: 'user', }, }, }, }, }); }); assert.expectAssertion(() => { message.get('user'); }, /You looked up the 'user' relationship on a 'message' with id 1 but some of the associated records were not loaded. Either make sure they are all loaded together with the parent record, or specify that the relationship is async \(`DS.belongsTo\({ async: true }\)`\)/); }); test('Rollbacking attributes for a deleted record restores implicit relationship - async', function(assert) { Book.reopen({ author: DS.belongsTo('author', { async: true }), }); let book, author; run(() => { book = env.store.push({ data: { id: '1', type: 'book', attributes: { name: "Stanley's Amazing Adventures", }, relationships: { author: { data: { id: '2', type: 'author', }, }, }, }, }); author = env.store.push({ data: { id: '2', type: 'author', attributes: { name: 'Stanley', }, }, }); }); return run(() => { author.deleteRecord(); author.rollbackAttributes(); return book.get('author').then(fetchedAuthor => { assert.equal(fetchedAuthor, author, 'Book has an author after rollback attributes'); }); }); }); test('Rollbacking attributes for a deleted record restores implicit relationship - sync', function(assert) { let book, author; run(() => { book = env.store.push({ data: { id: '1', type: 'book', attributes: { name: "Stanley's Amazing Adventures", }, relationships: { author: { data: { id: '2', type: 'author', }, }, }, }, }); author = env.store.push({ data: { id: '2', type: 'author', attributes: { name: 'Stanley', }, }, }); }); run(() => { author.deleteRecord(); author.rollbackAttributes(); }); assert.equal(book.get('author'), author, 'Book has an author after rollback attributes'); }); testInDebug('Passing a model as type to belongsTo should not work', function(assert) { assert.expect(1); assert.expectAssertion(() => { User = DS.Model.extend(); DS.Model.extend({ user: DSbelongsTo(User, { async: false }), }); }, /The first argument to DS.belongsTo must be a string/); }); test('belongsTo hasAnyRelationshipData async loaded', function(assert) { assert.expect(1); Book.reopen({ author: DSbelongsTo('author', { async: true }), }); env.adapter.findRecord = function(store, type, id, snapshot) { return resolve({ data: { id: 1, type: 'book', attributes: { name: 'The Greatest Book' }, relationships: { author: { data: { id: 2, type: 'author' } }, }, }, }); }; return run(() => { return store.findRecord('book', 1).then(book => { let relationship = book._internalModel._relationships.get('author'); assert.equal(relationship.hasAnyRelationshipData, true, 'relationship has data'); }); }); }); test('belongsTo hasAnyRelationshipData sync loaded', function(assert) { assert.expect(1); env.adapter.findRecord = function(store, type, id, snapshot) { return resolve({ data: { id: 1, type: 'book', attributes: { name: 'The Greatest Book' }, relationships: { author: { data: { id: 2, type: 'author' } }, }, }, }); }; return run(() => { return store.findRecord('book', 1).then(book => { let relationship = book._internalModel._relationships.get('author'); assert.equal(relationship.hasAnyRelationshipData, true, 'relationship has data'); }); }); }); test('belongsTo hasAnyRelationshipData async not loaded', function(assert) { assert.expect(1); Book.reopen({ author: DSbelongsTo('author', { async: true }), }); env.adapter.findRecord = function(store, type, id, snapshot) { return resolve({ data: { id: 1, type: 'book', attributes: { name: 'The Greatest Book' }, relationships: { author: { links: { related: 'author' } }, }, }, }); }; return run(() => { return store.findRecord('book', 1).then(book => { let relationship = book._internalModel._relationships.get('author'); assert.equal(relationship.hasAnyRelationshipData, false, 'relationship does not have data'); }); }); }); test('belongsTo hasAnyRelationshipData sync not loaded', function(assert) { assert.expect(1); env.adapter.findRecord = function(store, type, id, snapshot) { return resolve({ data: { id: 1, type: 'book', attributes: { name: 'The Greatest Book' }, }, }); }; return run(() => { return store.findRecord('book', 1).then(book => { let relationship = book._internalModel._relationships.get('author'); assert.equal(relationship.hasAnyRelationshipData, false, 'relationship does not have data'); }); }); }); test('belongsTo hasAnyRelationshipData NOT created', function(assert) { assert.expect(2); Book.reopen({ author: DSbelongsTo('author', { async: true }), }); run(() => { let author = store.createRecord('author'); let book = store.createRecord('book', { name: 'The Greatest Book' }); let relationship = book._internalModel._relationships.get('author'); assert.equal(relationship.hasAnyRelationshipData, false, 'relationship does not have data'); book = store.createRecord('book', { name: 'The Greatest Book', author, }); relationship = book._internalModel._relationships.get('author'); assert.equal(relationship.hasAnyRelationshipData, true, 'relationship has data'); }); }); test('belongsTo hasAnyRelationshipData sync created', function(assert) { assert.expect(2); run(() => { let author = store.createRecord('author'); let book = store.createRecord('book', { name: 'The Greatest Book', }); let relationship = book._internalModel._relationships.get('author'); assert.equal(relationship.hasAnyRelationshipData, false, 'relationship does not have data'); book = store.createRecord('book', { name: 'The Greatest Book', author, }); relationship = book._internalModel._relationships.get('author'); assert.equal(relationship.hasAnyRelationshipData, true, 'relationship has data'); }); }); test("Model's belongsTo relationship should not be created during model creation", function(assert) { let user; run(() => { user = env.store.push({ data: { id: '1', type: 'user', }, }); assert.ok( !user._internalModel._relationships.has('favouriteMessage'), 'Newly created record should not have relationships' ); }); }); test("Model's belongsTo relationship should be created during model creation if relationship passed in constructor", function(assert) { let message = env.store.createRecord('message'); let user = env.store.createRecord('user', { name: 'John Doe', favouriteMessage: message, }); assert.ok( user._internalModel._relationships.has('favouriteMessage'), 'Newly created record with relationships in params passed in its constructor should have relationships' ); }); test("Model's belongsTo relationship should be created during 'set' method", function(assert) { let user, message; run(() => { message = env.store.createRecord('message'); user = env.store.createRecord('user'); user.set('favouriteMessage', message); assert.ok( user._internalModel._relationships.has('favouriteMessage'), 'Newly created record with relationships in params passed in its constructor should have relationships' ); }); }); test("Model's belongsTo relationship should be created during 'get' method", function(assert) { let user; run(() => { user = env.store.createRecord('user'); user.get('favouriteMessage'); assert.ok( user._internalModel._relationships.has('favouriteMessage'), 'Newly created record with relationships in params passed in its constructor should have relationships' ); }); }); test('Related link should be fetched when no relationship data is present', function(assert) { assert.expect(3); Book.reopen({ author: DS.belongsTo('author', { async: true }), }); env.adapter.findBelongsTo = function(store, snapshot, url, relationship) { assert.equal(url, 'author', 'url is correct'); assert.ok(true, "The adapter's findBelongsTo method should be called"); return resolve({ data: { id: '1', type: 'author', attributes: { name: 'This is author' }, }, }); }; return run(() => { let book = env.store.push({ data: { type: 'book', id: '1', relationships: { author: { links: { related: 'author', }, }, }, }, }); return book.get('author').then(author => { assert.equal(author.get('name'), 'This is author', 'author name is correct'); }); }); }); test('Related link should take precedence over relationship data if no local record data is available', function(assert) { assert.expect(2); Book.reopen({ author: DS.belongsTo('author', { async: true }), }); env.adapter.findBelongsTo = function(store, snapshot, url, relationship) { assert.ok(true, "The adapter's findBelongsTo method should be called"); return resolve({ data: { id: 1, type: 'author', attributes: { name: 'This is author' }, }, }); }; env.adapter.findRecord = function() { assert.ok(false, "The adapter's findRecord method should not be called"); }; return run(() => { let book = env.store.push({ data: { type: 'book', id: '1', relationships: { author: { links: { related: 'author', }, data: { type: 'author', id: '1' }, }, }, }, }); return book.get('author').then(author => { assert.equal(author.get('name'), 'This is author', 'author name is correct'); }); }); }); test('Relationship data should take precedence over related link when local record data is available', function(assert) { assert.expect(1); Book.reopen({ author: DS.belongsTo('author', { async: true }), }); env.adapter.shouldBackgroundReloadRecord = () => { return false; }; env.adapter.findBelongsTo = function(store, snapshot, url, relationship) { assert.ok(false, "The adapter's findBelongsTo method should not be called"); }; env.adapter.findRecord = function(store, type, id, snapshot) { assert.ok(false, "The adapter's findRecord method should not be called"); }; return run(() => { let book = env.store.push({ data: { type: 'book', id: '1', relationships: { author: { links: { related: 'author', }, data: { type: 'author', id: '1' }, }, }, }, included: [ { id: '1', type: 'author', attributes: { name: 'This is author' }, }, ], }); return book.get('author').then(author => { assert.equal(author.get('name'), 'This is author', 'author name is correct'); }); }); }); test('New related link should take precedence over local data', function(assert) { assert.expect(3); Book.reopen({ author: DS.belongsTo('author', { async: true }), }); env.adapter.findBelongsTo = function(store, snapshot, url, relationship) { assert.equal(url, 'author-new-link', 'url is correct'); assert.ok(true, "The adapter's findBelongsTo method should be called"); return resolve({ data: { id: 1, type: 'author', attributes: { name: 'This is author' }, }, }); }; env.adapter.findRecord = function(store, type, id, snapshot) { assert.ok(false, "The adapter's findRecord method should not be called"); }; return run(() => { let book = env.store.push({ data: { type: 'book', id: '1', relationships: { author: { data: { type: 'author', id: '1', }, }, }, }, }); env.store.push({ data: { type: 'book', id: '1', relationships: { author: { links: { related: 'author-new-link', }, }, }, }, }); book.get('author').then(author => { assert.equal(author.get('name'), 'This is author', 'author name is correct'); }); }); }); test('Updated related link should take precedence over relationship data and local record data', function(assert) { assert.expect(4); Book.reopen({ author: DS.belongsTo('author', { async: true }), }); env.adapter.findBelongsTo = function(store, snapshot, url, relationship) { assert.equal(url, 'author-updated-link', 'url is correct'); assert.ok(true, "The adapter's findBelongsTo method should be called"); return resolve({ data: { id: '1', type: 'author', attributes: { name: 'This is updated author', }, }, }); }; env.adapter.findRecord = function(store, type, id, snapshot) { assert.ok(false, "The adapter's findRecord method should not be called"); }; return run(() => { let book = env.store.push({ data: { type: 'book', id: '1', relationships: { author: { links: { related: 'author', }, data: { type: 'author', id: '1' }, }, }, }, included: [ { type: 'author', id: '1', attributes: { name: 'This is author', }, }, ], }); return book .get('author') .then(author => { assert.equal(author.get('name'), 'This is author', 'author name is correct'); }) .then(() => { env.store.push({ data: { type: 'book', id: '1', relationships: { author: { links: { related: 'author-updated-link', }, }, }, }, }); return book.get('author').then(author => { assert.equal(author.get('name'), 'This is updated author', 'author name is correct'); }); }); }); }); test('Updated identical related link should not take precedence over local data', function(assert) { assert.expect(2); Book.reopen({ author: DS.belongsTo('author', { async: true }), }); env.adapter.findBelongsTo = function() { assert.ok(false, "The adapter's findBelongsTo method should not be called"); }; env.adapter.findRecord = function() { assert.ok(false, "The adapter's findRecord method should not be called"); }; return run(() => { let book = env.store.push({ data: { type: 'book', id: '1', relationships: { author: { links: { related: 'author', }, data: { type: 'author', id: '1' }, }, }, }, included: [ { type: 'author', id: '1', attributes: { name: 'This is author', }, }, ], }); return book .get('author') .then(author => { assert.equal(author.get('name'), 'This is author', 'author name is correct'); }) .then(() => { env.store.push({ data: { type: 'book', id: '1', relationships: { author: { links: { related: 'author', }, }, }, }, }); return book.get('author').then(author => { assert.equal(author.get('name'), 'This is author', 'author name is correct'); }); }); }); }); test('A belongsTo relationship can be reloaded using the reference if it was fetched via link', function(assert) { Chapter.reopen({ book: DS.belongsTo({ async: true }), }); env.adapter.findRecord = function() { return resolve({ data: { id: 1, type: 'chapter', relationships: { book: { links: { related: '/books/1' }, }, }, }, }); }; env.adapter.findBelongsTo = function() { return resolve({ data: { id: 1, type: 'book', attributes: { name: 'book title' }, }, }); }; return run(() => { let chapter; return store .findRecord('chapter', 1) .then(_chapter => { chapter = _chapter; return chapter.get('book'); }) .then(book => { assert.equal(book.get('name'), 'book title'); env.adapter.findBelongsTo = function() { return resolve({ data: { id: 1, type: 'book', attributes: { name: 'updated book title' }, }, }); }; return chapter.belongsTo('book').reload(); }) .then(book => { assert.equal(book.get('name'), 'updated book title'); }); }); }); test('A synchronous belongsTo relationship can be reloaded using a reference if it was fetched via id', function(assert) { Chapter.reopen({ book: DS.belongsTo({ async: false }), }); let chapter; run(() => { chapter = env.store.push({ data: { type: 'chapter', id: '1', relationships: { book: { data: { type: 'book', id: '1' }, }, }, }, }); env.store.push({ data: { type: 'book', id: '1', attributes: { name: 'book title', }, }, }); }); env.adapter.findRecord = function() { return resolve({ data: { id: '1', type: 'book', attributes: { name: 'updated book title' }, }, }); }; return run(() => { let book = chapter.get('book'); assert.equal(book.get('name'), 'book title'); return chapter .belongsTo('book') .reload() .then(function(book) { assert.equal(book.get('name'), 'updated book title'); }); }); }); test('A belongsTo relationship can be reloaded using a reference if it was fetched via id', function(assert) { Chapter.reopen({ book: DS.belongsTo({ async: true }), }); let chapter; run(() => { chapter = env.store.push({ data: { type: 'chapter', id: 1, relationships: { book: { data: { type: 'book', id: 1 }, }, }, }, }); }); env.adapter.findRecord = function() { return resolve({ data: { id: 1, type: 'book', attributes: { name: 'book title' }, }, }); }; return run(() => { return chapter .get('book') .then(book => { assert.equal(book.get('name'), 'book title'); env.adapter.findRecord = function() { return resolve({ data: { id: 1, type: 'book', attributes: { name: 'updated book title' }, }, }); }; return chapter.belongsTo('book').reload(); }) .then(book => { assert.equal(book.get('name'), 'updated book title'); }); }); }); testInDebug( 'A belongsTo relationship warns if malformatted data is pushed into the store', function(assert) { assert.expectAssertion(() => { run(() => { let chapter = env.store.push({ data: { type: 'chapter', id: 1, relationships: { book: { data: { id: 1, name: 'The Gallic Wars' }, }, }, }, }); chapter.get('book'); }); }, /Encountered a relationship identifier without a type for the belongsTo relationship 'book' on <chapter:1>, expected a json-api identifier with type 'book'/); } ); test("belongsTo relationship with links doesn't trigger extra change notifications - #4942", function(assert) { Chapter.reopen({ book: DS.belongsTo({ async: true }), }); run(() => { env.store.push({ data: { type: 'chapter', id: '1', relationships: { book: { data: { type: 'book', id: '1' }, links: { related: '/chapter/1/book' }, }, }, }, included: [{ type: 'book', id: '1' }], }); }); let chapter = env.store.peekRecord('chapter', '1'); let count = 0; chapter.addObserver('book', () => { count++; }); run(() => { chapter.get('book'); }); assert.equal(count, 0); }); testRecordData( "belongsTo relationship doesn't trigger when model data doesn't support implicit relationship", function(assert) { class TestRecordData extends RecordData { constructor(modelName, id, clientId, storeWrapper, store) { super(modelName, id, clientId, storeWrapper, store); delete this.__implicitRelationships; delete this.__relationships; } _destroyRelationships() {} _allRelatedRecordDatas() {} _cleanupOrphanedRecordDatas() {} _directlyRelatedRecordDatas() { return []; } destroy() { this.isDestroyed = true; this.storeWrapper.disconnectRecord(this.modelName, this.id, this.clientId); } get _implicitRelationships() { return undefined; } get _relationships() { return undefined; } } Chapter.reopen({ // book is still an inverse from prior to the reopen sections: DS.hasMany('section', { async: false }), book1: DS.belongsTo('book1', { async: false, inverse: 'chapters' }), // incorrect inverse book2: DS.belongsTo('book1', { async: false, inverse: null }), // correct inverse }); const createRecordDataFor = env.store.createRecordDataFor; env.store.createRecordDataFor = function(modelName, id, clientId, storeWrapper) { if (modelName === 'book1' || modelName === 'section') { return new TestRecordData(modelName, id, clientId, storeWrapper, this); } return createRecordDataFor.call(this, modelName, id, clientId, storeWrapper); }; const data = { data: { type: 'chapter', id: '1', relationships: { book1: { data: { type: 'book1', id: '1' }, }, book2: { data: { type: 'book1', id: '2' }, }, book: { data: { type: 'book', id: '1' }, }, sections: { data: [ { type: 'section', id: 1, }, { type: 'section', id: 2, }, ], }, }, }, included: [ { type: 'book1', id: '1' }, { type: 'book1', id: '2' }, { type: 'section', id: '1' }, { type: 'book', id: '1' }, { type: 'section', id: '2' }, ], }; // Expect assertion failure as Book1 RecordData // doesn't have relationship attribute // and inverse is not set to null in // DSbelongsTo assert.expectAssertion(() => { run(() => { env.store.push(data); }); }, `Assertion Failed: We found no inverse relationships by the name of 'chapters' on the 'book1' model. This is most likely due to a missing attribute on your model definition.`); //Update setup // with inverse set to null // no errors thrown Chapter.reopen({ book1: DS.belongsTo({ async: false }), sections: DS.hasMany('section', { async: false }), book: DS.belongsTo({ async: false, inverse: null }), }); run(() => { env.store.push(data); }); let chapter = env.store.peekRecord('chapter', '1'); let book1 = env.store.peekRecord('book1', '1'); let book2 = env.store.peekRecord('book1', '2'); let book = env.store.peekRecord('book', '1'); let section1 = env.store.peekRecord('section', '1'); let section2 = env.store.peekRecord('section', '2'); let sections = chapter.get('sections'); assert.equal(chapter.get('book1.id'), '1'); assert.equal(chapter.get('book2.id'), '2'); assert.equal(chapter.get('book.id'), '1'); // No inverse setup created for book1 // as Model-Data of book1 doesn't support this // functionality. assert.notOk(book1.get('chapter')); assert.notOk(book2.get('chapter')); assert.notOk(book.get('chapter')); assert.notOk( book1._internalModel._recordData._implicitRelationships, 'no support for implicit relationship in custom RecordData' ); assert.notOk( book2._internalModel._recordData._implicitRelationships, 'no support for implicit relationship in custom RecordData' ); assert.ok( book._internalModel._recordData._implicitRelationships, 'support for implicit relationship in default RecordData' ); // No inverse setup is created for section assert.notOk(section1.get('chapter')); assert.notOk(section2.get('chapter')); // Removing the sections // shouldnot throw error // as Model-data of section // doesn't support implicit Relationship run(() => { chapter.get('sections').removeObject(section1); assert.notOk(section1._internalModel._recordData._implicitRelationships); chapter.get('sections').removeObject(section2); assert.notOk(section2._internalModel._recordData._implicitRelationships); }); assert.equal(chapter.get('sections.length'), 0); // Update the current state of chapter by // adding new sections // shouldnot throw error during // setup of implicit inverse run(() => { sections.addObject(env.store.createRecord('section', { id: 3 })); sections.addObject(env.store.createRecord('section', { id: 4 })); sections.addObject(env.store.createRecord('section', { id: 5 })); }); assert.equal(chapter.get('sections.length'), 3); assert.notOk(sections.get('firstObject')._internalModel._recordData._implicitRelationships); } );
#!/usr/bin/env python3 # Copyright (c) 2018-2019 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 the blocksdir option. """ import os import shutil from test_framework.test_framework import FlocoinTestFramework, initialize_datadir class BlocksdirTest(FlocoinTestFramework): def set_test_params(self): self.setup_clean_chain = True self.num_nodes = 1 def run_test(self): self.stop_node(0) assert os.path.isdir(os.path.join(self.nodes[0].datadir, self.chain, "blocks")) assert not os.path.isdir(os.path.join(self.nodes[0].datadir, "blocks")) shutil.rmtree(self.nodes[0].datadir) initialize_datadir(self.options.tmpdir, 0, self.chain) self.log.info("Starting with nonexistent blocksdir ...") blocksdir_path = os.path.join(self.options.tmpdir, 'blocksdir') self.nodes[0].assert_start_raises_init_error(["-blocksdir=" + blocksdir_path], 'Error: Specified blocks directory "{}" does not exist.'.format(blocksdir_path)) os.mkdir(blocksdir_path) self.log.info("Starting with existing blocksdir ...") self.start_node(0, ["-blocksdir=" + blocksdir_path]) self.log.info("mining blocks..") self.nodes[0].generatetoaddress(10, self.nodes[0].get_deterministic_priv_key().address) assert os.path.isfile(os.path.join(blocksdir_path, self.chain, "blocks", "blk00000.dat")) assert os.path.isdir(os.path.join(self.nodes[0].datadir, self.chain, "blocks", "index")) if __name__ == '__main__': BlocksdirTest().main()
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Dict, List, Mapping, Optional, Tuple, Union from .. import _utilities, _tables __all__ = [ 'AliasRoutingConfigArgs', 'EventSourceMappingDestinationConfigArgs', 'EventSourceMappingDestinationConfigOnFailureArgs', 'FunctionDeadLetterConfigArgs', 'FunctionEnvironmentArgs', 'FunctionEventInvokeConfigDestinationConfigArgs', 'FunctionEventInvokeConfigDestinationConfigOnFailureArgs', 'FunctionEventInvokeConfigDestinationConfigOnSuccessArgs', 'FunctionFileSystemConfigArgs', 'FunctionTracingConfigArgs', 'FunctionVpcConfigArgs', ] @pulumi.input_type class AliasRoutingConfigArgs: def __init__(__self__, *, additional_version_weights: Optional[pulumi.Input[Mapping[str, pulumi.Input[float]]]] = None): """ :param pulumi.Input[Mapping[str, pulumi.Input[float]]] additional_version_weights: A map that defines the proportion of events that should be sent to different versions of a lambda function. """ if additional_version_weights is not None: pulumi.set(__self__, "additional_version_weights", additional_version_weights) @property @pulumi.getter(name="additionalVersionWeights") def additional_version_weights(self) -> Optional[pulumi.Input[Mapping[str, pulumi.Input[float]]]]: """ A map that defines the proportion of events that should be sent to different versions of a lambda function. """ return pulumi.get(self, "additional_version_weights") @additional_version_weights.setter def additional_version_weights(self, value: Optional[pulumi.Input[Mapping[str, pulumi.Input[float]]]]): pulumi.set(self, "additional_version_weights", value) @pulumi.input_type class EventSourceMappingDestinationConfigArgs: def __init__(__self__, *, on_failure: Optional[pulumi.Input['EventSourceMappingDestinationConfigOnFailureArgs']] = None): """ :param pulumi.Input['EventSourceMappingDestinationConfigOnFailureArgs'] on_failure: The destination configuration for failed invocations. Detailed below. """ if on_failure is not None: pulumi.set(__self__, "on_failure", on_failure) @property @pulumi.getter(name="onFailure") def on_failure(self) -> Optional[pulumi.Input['EventSourceMappingDestinationConfigOnFailureArgs']]: """ The destination configuration for failed invocations. Detailed below. """ return pulumi.get(self, "on_failure") @on_failure.setter def on_failure(self, value: Optional[pulumi.Input['EventSourceMappingDestinationConfigOnFailureArgs']]): pulumi.set(self, "on_failure", value) @pulumi.input_type class EventSourceMappingDestinationConfigOnFailureArgs: def __init__(__self__, *, destination_arn: pulumi.Input[str]): """ :param pulumi.Input[str] destination_arn: The Amazon Resource Name (ARN) of the destination resource. """ pulumi.set(__self__, "destination_arn", destination_arn) @property @pulumi.getter(name="destinationArn") def destination_arn(self) -> pulumi.Input[str]: """ The Amazon Resource Name (ARN) of the destination resource. """ return pulumi.get(self, "destination_arn") @destination_arn.setter def destination_arn(self, value: pulumi.Input[str]): pulumi.set(self, "destination_arn", value) @pulumi.input_type class FunctionDeadLetterConfigArgs: def __init__(__self__, *, target_arn: pulumi.Input[str]): """ :param pulumi.Input[str] target_arn: The ARN of an SNS topic or SQS queue to notify when an invocation fails. If this option is used, the function's IAM role must be granted suitable access to write to the target object, which means allowing either the `sns:Publish` or `sqs:SendMessage` action on this ARN, depending on which service is targeted. """ pulumi.set(__self__, "target_arn", target_arn) @property @pulumi.getter(name="targetArn") def target_arn(self) -> pulumi.Input[str]: """ The ARN of an SNS topic or SQS queue to notify when an invocation fails. If this option is used, the function's IAM role must be granted suitable access to write to the target object, which means allowing either the `sns:Publish` or `sqs:SendMessage` action on this ARN, depending on which service is targeted. """ return pulumi.get(self, "target_arn") @target_arn.setter def target_arn(self, value: pulumi.Input[str]): pulumi.set(self, "target_arn", value) @pulumi.input_type class FunctionEnvironmentArgs: def __init__(__self__, *, variables: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]] = None): """ :param pulumi.Input[Mapping[str, pulumi.Input[str]]] variables: A map that defines environment variables for the Lambda function. """ if variables is not None: pulumi.set(__self__, "variables", variables) @property @pulumi.getter def variables(self) -> Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]]: """ A map that defines environment variables for the Lambda function. """ return pulumi.get(self, "variables") @variables.setter def variables(self, value: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]]): pulumi.set(self, "variables", value) @pulumi.input_type class FunctionEventInvokeConfigDestinationConfigArgs: def __init__(__self__, *, on_failure: Optional[pulumi.Input['FunctionEventInvokeConfigDestinationConfigOnFailureArgs']] = None, on_success: Optional[pulumi.Input['FunctionEventInvokeConfigDestinationConfigOnSuccessArgs']] = None): """ :param pulumi.Input['FunctionEventInvokeConfigDestinationConfigOnFailureArgs'] on_failure: Configuration block with destination configuration for failed asynchronous invocations. See below for details. :param pulumi.Input['FunctionEventInvokeConfigDestinationConfigOnSuccessArgs'] on_success: Configuration block with destination configuration for successful asynchronous invocations. See below for details. """ if on_failure is not None: pulumi.set(__self__, "on_failure", on_failure) if on_success is not None: pulumi.set(__self__, "on_success", on_success) @property @pulumi.getter(name="onFailure") def on_failure(self) -> Optional[pulumi.Input['FunctionEventInvokeConfigDestinationConfigOnFailureArgs']]: """ Configuration block with destination configuration for failed asynchronous invocations. See below for details. """ return pulumi.get(self, "on_failure") @on_failure.setter def on_failure(self, value: Optional[pulumi.Input['FunctionEventInvokeConfigDestinationConfigOnFailureArgs']]): pulumi.set(self, "on_failure", value) @property @pulumi.getter(name="onSuccess") def on_success(self) -> Optional[pulumi.Input['FunctionEventInvokeConfigDestinationConfigOnSuccessArgs']]: """ Configuration block with destination configuration for successful asynchronous invocations. See below for details. """ return pulumi.get(self, "on_success") @on_success.setter def on_success(self, value: Optional[pulumi.Input['FunctionEventInvokeConfigDestinationConfigOnSuccessArgs']]): pulumi.set(self, "on_success", value) @pulumi.input_type class FunctionEventInvokeConfigDestinationConfigOnFailureArgs: def __init__(__self__, *, destination: pulumi.Input[str]): """ :param pulumi.Input[str] destination: Amazon Resource Name (ARN) of the destination resource. See the [Lambda Developer Guide](https://docs.aws.amazon.com/lambda/latest/dg/invocation-async.html#invocation-async-destinations) for acceptable resource types and associated IAM permissions. """ pulumi.set(__self__, "destination", destination) @property @pulumi.getter def destination(self) -> pulumi.Input[str]: """ Amazon Resource Name (ARN) of the destination resource. See the [Lambda Developer Guide](https://docs.aws.amazon.com/lambda/latest/dg/invocation-async.html#invocation-async-destinations) for acceptable resource types and associated IAM permissions. """ return pulumi.get(self, "destination") @destination.setter def destination(self, value: pulumi.Input[str]): pulumi.set(self, "destination", value) @pulumi.input_type class FunctionEventInvokeConfigDestinationConfigOnSuccessArgs: def __init__(__self__, *, destination: pulumi.Input[str]): """ :param pulumi.Input[str] destination: Amazon Resource Name (ARN) of the destination resource. See the [Lambda Developer Guide](https://docs.aws.amazon.com/lambda/latest/dg/invocation-async.html#invocation-async-destinations) for acceptable resource types and associated IAM permissions. """ pulumi.set(__self__, "destination", destination) @property @pulumi.getter def destination(self) -> pulumi.Input[str]: """ Amazon Resource Name (ARN) of the destination resource. See the [Lambda Developer Guide](https://docs.aws.amazon.com/lambda/latest/dg/invocation-async.html#invocation-async-destinations) for acceptable resource types and associated IAM permissions. """ return pulumi.get(self, "destination") @destination.setter def destination(self, value: pulumi.Input[str]): pulumi.set(self, "destination", value) @pulumi.input_type class FunctionFileSystemConfigArgs: def __init__(__self__, *, arn: pulumi.Input[str], local_mount_path: pulumi.Input[str]): """ :param pulumi.Input[str] arn: The Amazon Resource Name (ARN) of the Amazon EFS Access Point that provides access to the file system. :param pulumi.Input[str] local_mount_path: The path where the function can access the file system, starting with /mnt/. """ pulumi.set(__self__, "arn", arn) pulumi.set(__self__, "local_mount_path", local_mount_path) @property @pulumi.getter def arn(self) -> pulumi.Input[str]: """ The Amazon Resource Name (ARN) of the Amazon EFS Access Point that provides access to the file system. """ return pulumi.get(self, "arn") @arn.setter def arn(self, value: pulumi.Input[str]): pulumi.set(self, "arn", value) @property @pulumi.getter(name="localMountPath") def local_mount_path(self) -> pulumi.Input[str]: """ The path where the function can access the file system, starting with /mnt/. """ return pulumi.get(self, "local_mount_path") @local_mount_path.setter def local_mount_path(self, value: pulumi.Input[str]): pulumi.set(self, "local_mount_path", value) @pulumi.input_type class FunctionTracingConfigArgs: def __init__(__self__, *, mode: pulumi.Input[str]): """ :param pulumi.Input[str] mode: Can be either `PassThrough` or `Active`. If PassThrough, Lambda will only trace the request from an upstream service if it contains a tracing header with "sampled=1". If Active, Lambda will respect any tracing header it receives from an upstream service. If no tracing header is received, Lambda will call X-Ray for a tracing decision. """ pulumi.set(__self__, "mode", mode) @property @pulumi.getter def mode(self) -> pulumi.Input[str]: """ Can be either `PassThrough` or `Active`. If PassThrough, Lambda will only trace the request from an upstream service if it contains a tracing header with "sampled=1". If Active, Lambda will respect any tracing header it receives from an upstream service. If no tracing header is received, Lambda will call X-Ray for a tracing decision. """ return pulumi.get(self, "mode") @mode.setter def mode(self, value: pulumi.Input[str]): pulumi.set(self, "mode", value) @pulumi.input_type class FunctionVpcConfigArgs: def __init__(__self__, *, security_group_ids: pulumi.Input[List[pulumi.Input[str]]], subnet_ids: pulumi.Input[List[pulumi.Input[str]]], vpc_id: Optional[pulumi.Input[str]] = None): """ :param pulumi.Input[List[pulumi.Input[str]]] security_group_ids: A list of security group IDs associated with the Lambda function. :param pulumi.Input[List[pulumi.Input[str]]] subnet_ids: A list of subnet IDs associated with the Lambda function. """ pulumi.set(__self__, "security_group_ids", security_group_ids) pulumi.set(__self__, "subnet_ids", subnet_ids) if vpc_id is not None: pulumi.set(__self__, "vpc_id", vpc_id) @property @pulumi.getter(name="securityGroupIds") def security_group_ids(self) -> pulumi.Input[List[pulumi.Input[str]]]: """ A list of security group IDs associated with the Lambda function. """ return pulumi.get(self, "security_group_ids") @security_group_ids.setter def security_group_ids(self, value: pulumi.Input[List[pulumi.Input[str]]]): pulumi.set(self, "security_group_ids", value) @property @pulumi.getter(name="subnetIds") def subnet_ids(self) -> pulumi.Input[List[pulumi.Input[str]]]: """ A list of subnet IDs associated with the Lambda function. """ return pulumi.get(self, "subnet_ids") @subnet_ids.setter def subnet_ids(self, value: pulumi.Input[List[pulumi.Input[str]]]): pulumi.set(self, "subnet_ids", value) @property @pulumi.getter(name="vpcId") def vpc_id(self) -> Optional[pulumi.Input[str]]: return pulumi.get(self, "vpc_id") @vpc_id.setter def vpc_id(self, value: Optional[pulumi.Input[str]]): pulumi.set(self, "vpc_id", value)
########################################################################## # # Copyright (c) 2014, Image Engine Design Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above # copyright notice, this list of conditions and the following # disclaimer. # # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided with # the distribution. # # * Neither the name of John Haddon nor the names of # any other contributors to this software may be used to endorse or # promote products derived from this software without specific prior # written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS # IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, # THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR # PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR # PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF # LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING # NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # ########################################################################## import functools import imath import IECore import Gaffer import GafferUI ########################################################################## # Public methods ########################################################################## ## May be called to connect the DotUI functionality to an application # instance. This isn't done automatically because some applications # may have graphs for which it doesn't make sense to use Dots. Typically # this function would be called from an application startup file. def connect( applicationRoot ) : applicationRoot.__dotUIConnected = True ########################################################################## # Metadata ########################################################################## Gaffer.Metadata.registerNode( Gaffer.Dot, "description", """ A utility node which can be used for organising large graphs. """, "nodeGadget:minWidth", 0.0, "nodeGadget:padding", 0.5, "layout:activator:labelTypeIsCustom", lambda node : node["labelType"].getValue() == node.LabelType.Custom, plugs = { "in" : [ "plugValueWidget:type", "" ], "out" : [ "plugValueWidget:type", "" ], "labelType" : [ "description", """ The method used to apply an optional label to the dot. Using a node name is recommended, because it encourages the use of descriptive node names, and updates automatically when nodes are renamed or upstream connections change. The custom label does however provide more flexibility, since node names are restricted in the characters they can use. """, "plugValueWidget:type", "GafferUI.PresetsPlugValueWidget", "nodule:type", "", "preset:None", Gaffer.Dot.LabelType.None, "preset:Node Name", Gaffer.Dot.LabelType.NodeName, "preset:Upstream Node Name", Gaffer.Dot.LabelType.UpstreamNodeName, "preset:Custom", Gaffer.Dot.LabelType.Custom, ], "label" : [ "description", """ The label displayed when the type is set to custom. """, "nodule:type", "", "layout:activator", "labelTypeIsCustom", ], }, ) ########################################################################## # NodeGraph menus ########################################################################## def __insertDot( menu, destinationPlug ) : nodeGraph = menu.ancestor( GafferUI.NodeGraph ) gadgetWidget = nodeGraph.graphGadgetWidget() graphGadget = nodeGraph.graphGadget() with Gaffer.UndoScope( destinationPlug.ancestor( Gaffer.ScriptNode ) ) : node = Gaffer.Dot() graphGadget.getRoot().addChild( node ) node.setup( destinationPlug ) node["in"].setInput( destinationPlug.getInput() ) destinationPlug.setInput( node["out"] ) menuPosition = menu.popupPosition( relativeTo = gadgetWidget ) position = gadgetWidget.getViewportGadget().rasterToGadgetSpace( imath.V2f( menuPosition.x, menuPosition.y ), gadget = graphGadget ).p0 graphGadget.setNodePosition( node, imath.V2f( position.x, position.y ) ) def __connectionContextMenu( nodeGraph, destinationPlug, menuDefinition ) : applicationRoot = nodeGraph.scriptNode().ancestor( Gaffer.ApplicationRoot ) connected = False with IECore.IgnoredExceptions( AttributeError ) : connected = applicationRoot.__dotUIConnected if not connected : return if len( menuDefinition.items() ) : menuDefinition.append( "/DotDivider", { "divider" : True } ) menuDefinition.append( "/Insert Dot", { "command" : functools.partial( __insertDot, destinationPlug = destinationPlug ), "active" : not Gaffer.MetadataAlgo.readOnly( destinationPlug ), } ) __connectionContextMenuConnection = GafferUI.NodeGraph.connectionContextMenuSignal().connect( __connectionContextMenu ) def __setPlugMetadata( plug, key, value ) : with Gaffer.UndoScope( plug.ancestor( Gaffer.ScriptNode ) ) : Gaffer.Metadata.registerValue( plug, key, value ) def __nodeGraphPlugContextMenu( nodeGraph, plug, menuDefinition ) : if isinstance( plug.node(), Gaffer.Dot ) : ## \todo This duplicates functionality from BoxUI. Is there some way # we could share it? currentEdge = Gaffer.Metadata.value( plug, "noduleLayout:section" ) if not currentEdge : currentEdge = "top" if plug.direction() == plug.Direction.In else "bottom" readOnly = Gaffer.MetadataAlgo.readOnly( plug ) for edge in ( "top", "bottom", "left", "right" ) : menuDefinition.append( "/Move To/" + edge.capitalize(), { "command" : functools.partial( __setPlugMetadata, plug, "noduleLayout:section", edge ), "active" : edge != currentEdge and not readOnly, } ) __nodeGraphPlugContextMenuConnection = GafferUI.NodeGraph.plugContextMenuSignal().connect( __nodeGraphPlugContextMenu )
# coding=utf-8 import time import re import logging from error import DiamondException class Metric(object): _METRIC_TYPES = ['COUNTER', 'GAUGE'] def __init__(self, path, value, raw_value=None, timestamp=None, precision=0, metric_type='COUNTER', ttl=None, host="ignored"): """ Create new instance of the Metric class Takes: path=string: string the specifies the path of the metric value=[float|int]: the value to be submitted timestamp=[float|int]: the timestamp, in seconds since the epoch (as from time.time()) precision=int: the precision to apply. Generally the default (2) should work fine. """ # Validate the path, value and metric_type submitted if (None in [path, value] or metric_type not in self._METRIC_TYPES): raise DiamondException(("Invalid parameter when creating new " "Metric with path: %r value: %r " "metric_type: %r") % (path, value, metric_type)) # If no timestamp was passed in, set it to the current time if timestamp is None: timestamp = int(time.time()) else: # If the timestamp isn't an int, then make it one if not isinstance(timestamp, int): try: timestamp = int(timestamp) except ValueError, e: raise DiamondException(("Invalid timestamp when " "creating new Metric %r: %s") % (path, e)) # The value needs to be a float or an int. If it is, great. If not, # try to cast it to one of those. if not isinstance(value, (int, float)): try: if precision == 0: value = round(float(value)) else: value = float(value) except ValueError, e: raise DiamondException(("Invalid value when creating new " "Metric %r: %s") % (path, e)) self.path = path self.value = value self.raw_value = raw_value self.timestamp = timestamp self.precision = precision self.metric_type = metric_type self.ttl = ttl def __repr__(self): """ Return the Metric as a string """ if not isinstance(self.precision, (int, long)): log = logging.getLogger('diamond') log.warn('Metric %s does not have a valid precision', self.path) self.precision = 0 # Set the format string fstring = "%%s %%0.%if %%i\n" % self.precision # Return formated string return fstring % (self.path, self.value, self.timestamp) @classmethod def parse(cls, string): """ Parse a string and create a metric """ match = re.match(r'^(?P<name>[A-Za-z0-9\.\-_]+)\s+' + '(?P<value>[0-9\.]+)\s+' + '(?P<timestamp>[0-9\.]+)(\n?)$', string) try: groups = match.groupdict() # TODO: get precision from value string return Metric(groups['name'], groups['value'], float(groups['timestamp'])) except: raise DiamondException( "Metric could not be parsed from string: %s." % string) def getPathPrefix(self): """ Returns the path prefix path servers.cpu.total.idle return "servers" """ return self.path.split('.')[0] def getCollectorPath(self): """ Returns collector path servers.cpu.total.idle return "cpu" """ return self.path.split('.')[1] def getMetricPath(self): """ Returns the metric path after the collector name servers.cpu.total.idle return "total.idle" """ path = self.path.split('.')[2:] return '.'.join(path)
#!/usr/bin/env python3 """ Build call-back mechanism for f2py2e. Copyright 2000 Pearu Peterson all rights reserved, Pearu Peterson <pearu@ioc.ee> Permission to use, modify, and distribute this software is given under the terms of the NumPy License. NO WARRANTY IS EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. $Date: 2005/07/20 11:27:58 $ Pearu Peterson """ from . import __version__ from .auxfuncs import ( applyrules, debugcapi, dictappend, errmess, getargs, hasnote, isarray, iscomplex, iscomplexarray, iscomplexfunction, isfunction, isintent_c, isintent_hide, isintent_in, isintent_inout, isintent_nothide, isintent_out, isoptional, isrequired, isscalar, isstring, isstringfunction, issubroutine, l_and, l_not, l_or, outmess, replace, stripcomma, throw_error ) from . import cfuncs f2py_version = __version__.version ################## Rules for callback function ############## cb_routine_rules = { 'cbtypedefs': 'typedef #rctype#(*#name#_typedef)(#optargs_td##args_td##strarglens_td##noargs#);', 'body': """ #begintitle# typedef struct { PyObject *capi; PyTupleObject *args_capi; int nofargs; jmp_buf jmpbuf; } #name#_t; #if defined(F2PY_THREAD_LOCAL_DECL) && !defined(F2PY_USE_PYTHON_TLS) static F2PY_THREAD_LOCAL_DECL #name#_t *_active_#name# = NULL; static #name#_t *swap_active_#name#(#name#_t *ptr) { #name#_t *prev = _active_#name#; _active_#name# = ptr; return prev; } static #name#_t *get_active_#name#(void) { return _active_#name#; } #else static #name#_t *swap_active_#name#(#name#_t *ptr) { char *key = "__f2py_cb_#name#"; return (#name#_t *)F2PySwapThreadLocalCallbackPtr(key, ptr); } static #name#_t *get_active_#name#(void) { char *key = "__f2py_cb_#name#"; return (#name#_t *)F2PyGetThreadLocalCallbackPtr(key); } #endif /*typedef #rctype#(*#name#_typedef)(#optargs_td##args_td##strarglens_td##noargs#);*/ #static# #rctype# #callbackname# (#optargs##args##strarglens##noargs#) { #name#_t *cb; PyTupleObject *capi_arglist = NULL; PyObject *capi_return = NULL; PyObject *capi_tmp = NULL; PyObject *capi_arglist_list = NULL; int capi_j,capi_i = 0; int capi_longjmp_ok = 1; #decl# #ifdef F2PY_REPORT_ATEXIT f2py_cb_start_clock(); #endif cb = get_active_#name#(); capi_arglist = cb->args_capi; CFUNCSMESS(\"cb:Call-back function #name# (maxnofargs=#maxnofargs#(-#nofoptargs#))\\n\"); CFUNCSMESSPY(\"cb:#name#_capi=\",cb->capi); if (cb->capi==NULL) { capi_longjmp_ok = 0; cb->capi = PyObject_GetAttrString(#modulename#_module,\"#argname#\"); } if (cb->capi==NULL) { PyErr_SetString(#modulename#_error,\"cb: Callback #argname# not defined (as an argument or module #modulename# attribute).\\n\"); goto capi_fail; } if (F2PyCapsule_Check(cb->capi)) { #name#_typedef #name#_cptr; #name#_cptr = F2PyCapsule_AsVoidPtr(cb->capi); #returncptr#(*#name#_cptr)(#optargs_nm##args_nm##strarglens_nm#); #return# } if (capi_arglist==NULL) { capi_longjmp_ok = 0; capi_tmp = PyObject_GetAttrString(#modulename#_module,\"#argname#_extra_args\"); if (capi_tmp) { capi_arglist = (PyTupleObject *)PySequence_Tuple(capi_tmp); if (capi_arglist==NULL) { PyErr_SetString(#modulename#_error,\"Failed to convert #modulename#.#argname#_extra_args to tuple.\\n\"); goto capi_fail; } } else { PyErr_Clear(); capi_arglist = (PyTupleObject *)Py_BuildValue(\"()\"); } } if (capi_arglist == NULL) { PyErr_SetString(#modulename#_error,\"Callback #argname# argument list is not set.\\n\"); goto capi_fail; } #setdims# #ifdef PYPY_VERSION #define CAPI_ARGLIST_SETITEM(idx, value) PyList_SetItem((PyObject *)capi_arglist_list, idx, value) capi_arglist_list = PySequence_List(capi_arglist); if (capi_arglist_list == NULL) goto capi_fail; #else #define CAPI_ARGLIST_SETITEM(idx, value) PyTuple_SetItem((PyObject *)capi_arglist, idx, value) #endif #pyobjfrom# #undef CAPI_ARGLIST_SETITEM #ifdef PYPY_VERSION CFUNCSMESSPY(\"cb:capi_arglist=\",capi_arglist_list); #else CFUNCSMESSPY(\"cb:capi_arglist=\",capi_arglist); #endif CFUNCSMESS(\"cb:Call-back calling Python function #argname#.\\n\"); #ifdef F2PY_REPORT_ATEXIT f2py_cb_start_call_clock(); #endif #ifdef PYPY_VERSION capi_return = PyObject_CallObject(cb->capi,(PyObject *)capi_arglist_list); Py_DECREF(capi_arglist_list); capi_arglist_list = NULL; #else capi_return = PyObject_CallObject(cb->capi,(PyObject *)capi_arglist); #endif #ifdef F2PY_REPORT_ATEXIT f2py_cb_stop_call_clock(); #endif CFUNCSMESSPY(\"cb:capi_return=\",capi_return); if (capi_return == NULL) { fprintf(stderr,\"capi_return is NULL\\n\"); goto capi_fail; } if (capi_return == Py_None) { Py_DECREF(capi_return); capi_return = Py_BuildValue(\"()\"); } else if (!PyTuple_Check(capi_return)) { capi_return = Py_BuildValue(\"(N)\",capi_return); } capi_j = PyTuple_Size(capi_return); capi_i = 0; #frompyobj# CFUNCSMESS(\"cb:#name#:successful\\n\"); Py_DECREF(capi_return); #ifdef F2PY_REPORT_ATEXIT f2py_cb_stop_clock(); #endif goto capi_return_pt; capi_fail: fprintf(stderr,\"Call-back #name# failed.\\n\"); Py_XDECREF(capi_return); Py_XDECREF(capi_arglist_list); if (capi_longjmp_ok) { longjmp(cb->jmpbuf,-1); } capi_return_pt: ; #return# } #endtitle# """, 'need': ['setjmp.h', 'CFUNCSMESS', 'F2PY_THREAD_LOCAL_DECL'], 'maxnofargs': '#maxnofargs#', 'nofoptargs': '#nofoptargs#', 'docstr': """\ \tdef #argname#(#docsignature#): return #docreturn#\\n\\ #docstrsigns#""", 'latexdocstr': """ {{}\\verb@def #argname#(#latexdocsignature#): return #docreturn#@{}} #routnote# #latexdocstrsigns#""", 'docstrshort': 'def #argname#(#docsignature#): return #docreturn#' } cb_rout_rules = [ { # Init 'separatorsfor': {'decl': '\n', 'args': ',', 'optargs': '', 'pyobjfrom': '\n', 'freemem': '\n', 'args_td': ',', 'optargs_td': '', 'args_nm': ',', 'optargs_nm': '', 'frompyobj': '\n', 'setdims': '\n', 'docstrsigns': '\\n"\n"', 'latexdocstrsigns': '\n', 'latexdocstrreq': '\n', 'latexdocstropt': '\n', 'latexdocstrout': '\n', 'latexdocstrcbs': '\n', }, 'decl': '/*decl*/', 'pyobjfrom': '/*pyobjfrom*/', 'frompyobj': '/*frompyobj*/', 'args': [], 'optargs': '', 'return': '', 'strarglens': '', 'freemem': '/*freemem*/', 'args_td': [], 'optargs_td': '', 'strarglens_td': '', 'args_nm': [], 'optargs_nm': '', 'strarglens_nm': '', 'noargs': '', 'setdims': '/*setdims*/', 'docstrsigns': '', 'latexdocstrsigns': '', 'docstrreq': '\tRequired arguments:', 'docstropt': '\tOptional arguments:', 'docstrout': '\tReturn objects:', 'docstrcbs': '\tCall-back functions:', 'docreturn': '', 'docsign': '', 'docsignopt': '', 'latexdocstrreq': '\\noindent Required arguments:', 'latexdocstropt': '\\noindent Optional arguments:', 'latexdocstrout': '\\noindent Return objects:', 'latexdocstrcbs': '\\noindent Call-back functions:', 'routnote': {hasnote: '--- #note#', l_not(hasnote): ''}, }, { # Function 'decl': ' #ctype# return_value;', 'frompyobj': [{debugcapi: ' CFUNCSMESS("cb:Getting return_value->");'}, ' if (capi_j>capi_i)\n GETSCALARFROMPYTUPLE(capi_return,capi_i++,&return_value,#ctype#,"#ctype#_from_pyobj failed in converting return_value of call-back function #name# to C #ctype#\\n");', {debugcapi: ' fprintf(stderr,"#showvalueformat#.\\n",return_value);'} ], 'need': ['#ctype#_from_pyobj', {debugcapi: 'CFUNCSMESS'}, 'GETSCALARFROMPYTUPLE'], 'return': ' return return_value;', '_check': l_and(isfunction, l_not(isstringfunction), l_not(iscomplexfunction)) }, { # String function 'pyobjfrom': {debugcapi: ' fprintf(stderr,"debug-capi:cb:#name#:%d:\\n",return_value_len);'}, 'args': '#ctype# return_value,int return_value_len', 'args_nm': 'return_value,&return_value_len', 'args_td': '#ctype# ,int', 'frompyobj': [{debugcapi: ' CFUNCSMESS("cb:Getting return_value->\\"");'}, """ if (capi_j>capi_i) GETSTRFROMPYTUPLE(capi_return,capi_i++,return_value,return_value_len);""", {debugcapi: ' fprintf(stderr,"#showvalueformat#\\".\\n",return_value);'} ], 'need': ['#ctype#_from_pyobj', {debugcapi: 'CFUNCSMESS'}, 'string.h', 'GETSTRFROMPYTUPLE'], 'return': 'return;', '_check': isstringfunction }, { # Complex function 'optargs': """ #ifndef F2PY_CB_RETURNCOMPLEX #ctype# *return_value #endif """, 'optargs_nm': """ #ifndef F2PY_CB_RETURNCOMPLEX return_value #endif """, 'optargs_td': """ #ifndef F2PY_CB_RETURNCOMPLEX #ctype# * #endif """, 'decl': """ #ifdef F2PY_CB_RETURNCOMPLEX #ctype# return_value; #endif """, 'frompyobj': [{debugcapi: ' CFUNCSMESS("cb:Getting return_value->");'}, """\ if (capi_j>capi_i) #ifdef F2PY_CB_RETURNCOMPLEX GETSCALARFROMPYTUPLE(capi_return,capi_i++,&return_value,#ctype#,\"#ctype#_from_pyobj failed in converting return_value of call-back function #name# to C #ctype#\\n\"); #else GETSCALARFROMPYTUPLE(capi_return,capi_i++,return_value,#ctype#,\"#ctype#_from_pyobj failed in converting return_value of call-back function #name# to C #ctype#\\n\"); #endif """, {debugcapi: """ #ifdef F2PY_CB_RETURNCOMPLEX fprintf(stderr,\"#showvalueformat#.\\n\",(return_value).r,(return_value).i); #else fprintf(stderr,\"#showvalueformat#.\\n\",(*return_value).r,(*return_value).i); #endif """} ], 'return': """ #ifdef F2PY_CB_RETURNCOMPLEX return return_value; #else return; #endif """, 'need': ['#ctype#_from_pyobj', {debugcapi: 'CFUNCSMESS'}, 'string.h', 'GETSCALARFROMPYTUPLE', '#ctype#'], '_check': iscomplexfunction }, {'docstrout': '\t\t#pydocsignout#', 'latexdocstrout': ['\\item[]{{}\\verb@#pydocsignout#@{}}', {hasnote: '--- #note#'}], 'docreturn': '#rname#,', '_check': isfunction}, {'_check': issubroutine, 'return': 'return;'} ] cb_arg_rules = [ { # Doc 'docstropt': {l_and(isoptional, isintent_nothide): '\t\t#pydocsign#'}, 'docstrreq': {l_and(isrequired, isintent_nothide): '\t\t#pydocsign#'}, 'docstrout': {isintent_out: '\t\t#pydocsignout#'}, 'latexdocstropt': {l_and(isoptional, isintent_nothide): ['\\item[]{{}\\verb@#pydocsign#@{}}', {hasnote: '--- #note#'}]}, 'latexdocstrreq': {l_and(isrequired, isintent_nothide): ['\\item[]{{}\\verb@#pydocsign#@{}}', {hasnote: '--- #note#'}]}, 'latexdocstrout': {isintent_out: ['\\item[]{{}\\verb@#pydocsignout#@{}}', {l_and(hasnote, isintent_hide): '--- #note#', l_and(hasnote, isintent_nothide): '--- See above.'}]}, 'docsign': {l_and(isrequired, isintent_nothide): '#varname#,'}, 'docsignopt': {l_and(isoptional, isintent_nothide): '#varname#,'}, 'depend': '' }, { 'args': { l_and(isscalar, isintent_c): '#ctype# #varname_i#', l_and(isscalar, l_not(isintent_c)): '#ctype# *#varname_i#_cb_capi', isarray: '#ctype# *#varname_i#', isstring: '#ctype# #varname_i#' }, 'args_nm': { l_and(isscalar, isintent_c): '#varname_i#', l_and(isscalar, l_not(isintent_c)): '#varname_i#_cb_capi', isarray: '#varname_i#', isstring: '#varname_i#' }, 'args_td': { l_and(isscalar, isintent_c): '#ctype#', l_and(isscalar, l_not(isintent_c)): '#ctype# *', isarray: '#ctype# *', isstring: '#ctype#' }, 'need': {l_or(isscalar, isarray, isstring): '#ctype#'}, # untested with multiple args 'strarglens': {isstring: ',int #varname_i#_cb_len'}, 'strarglens_td': {isstring: ',int'}, # untested with multiple args # untested with multiple args 'strarglens_nm': {isstring: ',#varname_i#_cb_len'}, }, { # Scalars 'decl': {l_not(isintent_c): ' #ctype# #varname_i#=(*#varname_i#_cb_capi);'}, 'error': {l_and(isintent_c, isintent_out, throw_error('intent(c,out) is forbidden for callback scalar arguments')): ''}, 'frompyobj': [{debugcapi: ' CFUNCSMESS("cb:Getting #varname#->");'}, {isintent_out: ' if (capi_j>capi_i)\n GETSCALARFROMPYTUPLE(capi_return,capi_i++,#varname_i#_cb_capi,#ctype#,"#ctype#_from_pyobj failed in converting argument #varname# of call-back function #name# to C #ctype#\\n");'}, {l_and(debugcapi, l_and(l_not(iscomplex), isintent_c)): ' fprintf(stderr,"#showvalueformat#.\\n",#varname_i#);'}, {l_and(debugcapi, l_and(l_not(iscomplex), l_not( isintent_c))): ' fprintf(stderr,"#showvalueformat#.\\n",*#varname_i#_cb_capi);'}, {l_and(debugcapi, l_and(iscomplex, isintent_c)): ' fprintf(stderr,"#showvalueformat#.\\n",(#varname_i#).r,(#varname_i#).i);'}, {l_and(debugcapi, l_and(iscomplex, l_not( isintent_c))): ' fprintf(stderr,"#showvalueformat#.\\n",(*#varname_i#_cb_capi).r,(*#varname_i#_cb_capi).i);'}, ], 'need': [{isintent_out: ['#ctype#_from_pyobj', 'GETSCALARFROMPYTUPLE']}, {debugcapi: 'CFUNCSMESS'}], '_check': isscalar }, { 'pyobjfrom': [{isintent_in: """\ if (cb->nofargs>capi_i) if (CAPI_ARGLIST_SETITEM(capi_i++,pyobj_from_#ctype#1(#varname_i#))) goto capi_fail;"""}, {isintent_inout: """\ if (cb->nofargs>capi_i) if (CAPI_ARGLIST_SETITEM(capi_i++,pyarr_from_p_#ctype#1(#varname_i#_cb_capi))) goto capi_fail;"""}], 'need': [{isintent_in: 'pyobj_from_#ctype#1'}, {isintent_inout: 'pyarr_from_p_#ctype#1'}, {iscomplex: '#ctype#'}], '_check': l_and(isscalar, isintent_nothide), '_optional': '' }, { # String 'frompyobj': [{debugcapi: ' CFUNCSMESS("cb:Getting #varname#->\\"");'}, """ if (capi_j>capi_i) GETSTRFROMPYTUPLE(capi_return,capi_i++,#varname_i#,#varname_i#_cb_len);""", {debugcapi: ' fprintf(stderr,"#showvalueformat#\\":%d:.\\n",#varname_i#,#varname_i#_cb_len);'}, ], 'need': ['#ctype#', 'GETSTRFROMPYTUPLE', {debugcapi: 'CFUNCSMESS'}, 'string.h'], '_check': l_and(isstring, isintent_out) }, { 'pyobjfrom': [{debugcapi: ' fprintf(stderr,"debug-capi:cb:#varname#=\\"#showvalueformat#\\":%d:\\n",#varname_i#,#varname_i#_cb_len);'}, {isintent_in: """\ if (cb->nofargs>capi_i) if (CAPI_ARGLIST_SETITEM(capi_i++,pyobj_from_#ctype#1size(#varname_i#,#varname_i#_cb_len))) goto capi_fail;"""}, {isintent_inout: """\ if (cb->nofargs>capi_i) { int #varname_i#_cb_dims[] = {#varname_i#_cb_len}; if (CAPI_ARGLIST_SETITEM(capi_i++,pyarr_from_p_#ctype#1(#varname_i#,#varname_i#_cb_dims))) goto capi_fail; }"""}], 'need': [{isintent_in: 'pyobj_from_#ctype#1size'}, {isintent_inout: 'pyarr_from_p_#ctype#1'}], '_check': l_and(isstring, isintent_nothide), '_optional': '' }, # Array ... { 'decl': ' npy_intp #varname_i#_Dims[#rank#] = {#rank*[-1]#};', 'setdims': ' #cbsetdims#;', '_check': isarray, '_depend': '' }, { 'pyobjfrom': [{debugcapi: ' fprintf(stderr,"debug-capi:cb:#varname#\\n");'}, {isintent_c: """\ if (cb->nofargs>capi_i) { int itemsize_ = #atype# == NPY_STRING ? 1 : 0; /*XXX: Hmm, what will destroy this array??? */ PyArrayObject *tmp_arr = (PyArrayObject *)PyArray_New(&PyArray_Type,#rank#,#varname_i#_Dims,#atype#,NULL,(char*)#varname_i#,itemsize_,NPY_ARRAY_CARRAY,NULL); """, l_not(isintent_c): """\ if (cb->nofargs>capi_i) { int itemsize_ = #atype# == NPY_STRING ? 1 : 0; /*XXX: Hmm, what will destroy this array??? */ PyArrayObject *tmp_arr = (PyArrayObject *)PyArray_New(&PyArray_Type,#rank#,#varname_i#_Dims,#atype#,NULL,(char*)#varname_i#,itemsize_,NPY_ARRAY_FARRAY,NULL); """, }, """ if (tmp_arr==NULL) goto capi_fail; if (CAPI_ARGLIST_SETITEM(capi_i++,(PyObject *)tmp_arr)) goto capi_fail; }"""], '_check': l_and(isarray, isintent_nothide, l_or(isintent_in, isintent_inout)), '_optional': '', }, { 'frompyobj': [{debugcapi: ' CFUNCSMESS("cb:Getting #varname#->");'}, """ if (capi_j>capi_i) { PyArrayObject *rv_cb_arr = NULL; if ((capi_tmp = PyTuple_GetItem(capi_return,capi_i++))==NULL) goto capi_fail; rv_cb_arr = array_from_pyobj(#atype#,#varname_i#_Dims,#rank#,F2PY_INTENT_IN""", {isintent_c: '|F2PY_INTENT_C'}, """,capi_tmp); if (rv_cb_arr == NULL) { fprintf(stderr,\"rv_cb_arr is NULL\\n\"); goto capi_fail; } MEMCOPY(#varname_i#,PyArray_DATA(rv_cb_arr),PyArray_NBYTES(rv_cb_arr)); if (capi_tmp != (PyObject *)rv_cb_arr) { Py_DECREF(rv_cb_arr); } }""", {debugcapi: ' fprintf(stderr,"<-.\\n");'}, ], 'need': ['MEMCOPY', {iscomplexarray: '#ctype#'}], '_check': l_and(isarray, isintent_out) }, { 'docreturn': '#varname#,', '_check': isintent_out } ] ################## Build call-back module ############# cb_map = {} def buildcallbacks(m): cb_map[m['name']] = [] for bi in m['body']: if bi['block'] == 'interface': for b in bi['body']: if b: buildcallback(b, m['name']) else: errmess('warning: empty body for %s\n' % (m['name'])) def buildcallback(rout, um): from . import capi_maps outmess('\tConstructing call-back function "cb_%s_in_%s"\n' % (rout['name'], um)) args, depargs = getargs(rout) capi_maps.depargs = depargs var = rout['vars'] vrd = capi_maps.cb_routsign2map(rout, um) rd = dictappend({}, vrd) cb_map[um].append([rout['name'], rd['name']]) for r in cb_rout_rules: if ('_check' in r and r['_check'](rout)) or ('_check' not in r): ar = applyrules(r, vrd, rout) rd = dictappend(rd, ar) savevrd = {} for i, a in enumerate(args): vrd = capi_maps.cb_sign2map(a, var[a], index=i) savevrd[a] = vrd for r in cb_arg_rules: if '_depend' in r: continue if '_optional' in r and isoptional(var[a]): continue if ('_check' in r and r['_check'](var[a])) or ('_check' not in r): ar = applyrules(r, vrd, var[a]) rd = dictappend(rd, ar) if '_break' in r: break for a in args: vrd = savevrd[a] for r in cb_arg_rules: if '_depend' in r: continue if ('_optional' not in r) or ('_optional' in r and isrequired(var[a])): continue if ('_check' in r and r['_check'](var[a])) or ('_check' not in r): ar = applyrules(r, vrd, var[a]) rd = dictappend(rd, ar) if '_break' in r: break for a in depargs: vrd = savevrd[a] for r in cb_arg_rules: if '_depend' not in r: continue if '_optional' in r: continue if ('_check' in r and r['_check'](var[a])) or ('_check' not in r): ar = applyrules(r, vrd, var[a]) rd = dictappend(rd, ar) if '_break' in r: break if 'args' in rd and 'optargs' in rd: if isinstance(rd['optargs'], list): rd['optargs'] = rd['optargs'] + [""" #ifndef F2PY_CB_RETURNCOMPLEX , #endif """] rd['optargs_nm'] = rd['optargs_nm'] + [""" #ifndef F2PY_CB_RETURNCOMPLEX , #endif """] rd['optargs_td'] = rd['optargs_td'] + [""" #ifndef F2PY_CB_RETURNCOMPLEX , #endif """] if isinstance(rd['docreturn'], list): rd['docreturn'] = stripcomma( replace('#docreturn#', {'docreturn': rd['docreturn']})) optargs = stripcomma(replace('#docsignopt#', {'docsignopt': rd['docsignopt']} )) if optargs == '': rd['docsignature'] = stripcomma( replace('#docsign#', {'docsign': rd['docsign']})) else: rd['docsignature'] = replace('#docsign#[#docsignopt#]', {'docsign': rd['docsign'], 'docsignopt': optargs, }) rd['latexdocsignature'] = rd['docsignature'].replace('_', '\\_') rd['latexdocsignature'] = rd['latexdocsignature'].replace(',', ', ') rd['docstrsigns'] = [] rd['latexdocstrsigns'] = [] for k in ['docstrreq', 'docstropt', 'docstrout', 'docstrcbs']: if k in rd and isinstance(rd[k], list): rd['docstrsigns'] = rd['docstrsigns'] + rd[k] k = 'latex' + k if k in rd and isinstance(rd[k], list): rd['latexdocstrsigns'] = rd['latexdocstrsigns'] + rd[k][0:1] +\ ['\\begin{description}'] + rd[k][1:] +\ ['\\end{description}'] if 'args' not in rd: rd['args'] = '' rd['args_td'] = '' rd['args_nm'] = '' if not (rd.get('args') or rd.get('optargs') or rd.get('strarglens')): rd['noargs'] = 'void' ar = applyrules(cb_routine_rules, rd) cfuncs.callbacks[rd['name']] = ar['body'] if isinstance(ar['need'], str): ar['need'] = [ar['need']] if 'need' in rd: for t in cfuncs.typedefs.keys(): if t in rd['need']: ar['need'].append(t) cfuncs.typedefs_generated[rd['name'] + '_typedef'] = ar['cbtypedefs'] ar['need'].append(rd['name'] + '_typedef') cfuncs.needs[rd['name']] = ar['need'] capi_maps.lcb2_map[rd['name']] = {'maxnofargs': ar['maxnofargs'], 'nofoptargs': ar['nofoptargs'], 'docstr': ar['docstr'], 'latexdocstr': ar['latexdocstr'], 'argname': rd['argname'] } outmess('\t %s\n' % (ar['docstrshort'])) return ################## Build call-back function #############
from .utils import memory_usage, write_log __all__ = ["memory_usage", "write_log"]
// requirements var gulp = require('gulp'), rename = require('gulp-rename'), uglify = require('gulp-uglify'), less = require('gulp-less'), path = require('path'); // run gulp.task('default', function() { // easier to read variable var themeName = 'simple'; // less gulp.src('./assets/less/' + themeName + '.less') .pipe(less({ paths: [path.join(__dirname, 'less', 'includes')]})) .pipe(rename('style.css')) .pipe(gulp.dest('./assets/css/')); // uglify gulp.src('./assets/js/' + themeName + '.js') .pipe(uglify()) .pipe(rename(themeName + '.min.js')) .pipe(gulp.dest('./assets/js/')); });
#!/usr/bin/env python # -*- encoding: utf-8 -*- # Copyright (c) 2014-2022 Megvii Inc. All rights reserved. import torch.nn as nn from exps.model.tal_head import TALHead from exps.model.dfp_pafpn import DFPPAFPN class YOLOX(nn.Module): """ YOLOX model module. The module list is defined by create_yolov3_modules function. The network returns loss values from three YOLO layers during training and detection results during test. """ def __init__(self, backbone=None, head=None): super().__init__() if backbone is None: backbone = DFPPAFPN() if head is None: head = TALHead(20) self.backbone = backbone self.head = head def forward(self, x, targets=None, buffer=None, mode='off_pipe'): # fpn output content features of [dark3, dark4, dark5] assert mode in ['off_pipe', 'on_pipe'] if mode == 'off_pipe': fpn_outs = self.backbone(x, buffer=buffer, mode='off_pipe') if self.training: assert targets is not None loss, iou_loss, conf_loss, cls_loss, l1_loss, num_fg = self.head( fpn_outs, targets, x ) outputs = { "total_loss": loss, "iou_loss": iou_loss, "l1_loss": l1_loss, "conf_loss": conf_loss, "cls_loss": cls_loss, "num_fg": num_fg, } else: outputs = self.head(fpn_outs) return outputs elif mode == 'on_pipe': fpn_outs, buffer_ = self.backbone(x, buffer=buffer, mode='on_pipe') outputs = self.head(fpn_outs) return outputs, buffer_
#!/usr/bin/env python # -*- coding: utf-8 -*- from typing import Optional, Union, Dict from dbas.database import DBDiscussionSession from dbas.database.discussion_model import ClickedStatement, ClickedArgument, User, MarkedArgument, MarkedStatement, \ Argument, Statement from dbas.lib import get_author_data, Relations, get_global_url from dbas.strings.lib import start_with_capital, start_with_small from .keywords import Keywords as _ from .translator import Translator nick_of_anonymous_user = 'anonymous' tag_type = 'span' start_attack = '<{} data-argumentation-type="attack">'.format(tag_type) start_argument = '<{} data-argumentation-type="argument">'.format(tag_type) start_position = '<{} data-argumentation-type="position">'.format(tag_type) start_content = '<{} class="triangle-content-text">'.format(tag_type) start_pro = '<{} data-attitude="pro">'.format(tag_type) start_con = '<{} data-attitude="con">'.format(tag_type) start_tag = '<{}>'.format(tag_type) end_tag = '</{}>'.format(tag_type) def get_text_for_add_premise_container(lang, confrontation, premise, attack_type, conclusion, is_supportive): """ Based on the users reaction, text will be build. This text can be used for the container where users can add their statements :param lang: ui_locales :param confrontation: chosen confrontation :param premise: current premise :param attack_type: type of the attack :param conclusion: current conclusion :param is_supportive: boolean :return: string """ _t = Translator(lang) while premise[-1] in ['.', ' ']: premise = premise[:-1] while conclusion[-1] in ['.', ' ']: conclusion = premise[:-1] confrontation = start_with_capital(confrontation) # different cases if attack_type == Relations.UNDERMINE: return '{} {} ...'.format(_t.get(_.itIsFalseThat), premise) elif attack_type == Relations.SUPPORT: intro = _t.get(_.itIsFalseThat) outro = _t.get(_.doesNotHold) if is_supportive: intro = _t.get(_.itIsTrueThat) outro = _t.get(_.hold) return '{} {} {} ...'.format(intro, conclusion, outro) elif attack_type == Relations.UNDERCUT: return '{}, {} ...'.format(confrontation, _t.get(_.butIDoNotBelieveCounterFor).format(conclusion)) elif attack_type == Relations.REBUT: mid = _t.get(_.iAcceptCounterThat) if is_supportive else _t.get(_.iAcceptArgumentThat) return '{} {} {} ...'.format(confrontation, mid, conclusion) else: return '' def get_header_for_users_confrontation_response(db_argument, lang, premise, attack_type, conclusion, start_lower_case, is_supportive, is_logged_in, redirect_from_jump=False): """ Based on the users reaction, text will be build. This text can be used for the speech bubbles where users justify an argument they have chosen. :param db_argument: Argument :param lang: ui_locales :param premise: current premise :param attack_type: type of the attack :param conclusion: current conclusion :param start_lower_case: boolean :param is_supportive: boolean :param is_logged_in: boolean :param redirect_from_jump: boolean :return: string """ _t = Translator(lang) if premise[-1] == '.': premise = premise[:-1] if conclusion[-1] == '.': conclusion = conclusion[:-1] # pretty print r = _t.get(_.right)[0:1].upper() f = _t.get(_.itIsFalseThat)[0:1].upper() t = _t.get(_.itIsTrueThat)[0:1].upper() if start_lower_case: r = _t.get(_.right)[0:1].lower() f = _t.get(_.itIsFalseThat)[0:1].lower() t = _t.get(_.itIsTrueThat)[0:1].lower() r += _t.get(_.right)[1:] + ', ' f += _t.get(_.itIsFalseThat)[1:] t += _t.get(_.itIsTrueThat)[1:] if lang == 'de': r += start_with_small(_t.get(_.itIsTrueThat)) + ' ' f = _t.get(_.wrong) + ', ' + start_with_small(_t.get(_.itIsFalseThat)) + ' ' if redirect_from_jump: r = _t.get(_.maybeItIsTrueThat) + ' ' # different cases user_msg = __get_user_msg_for_users_confrontation_response(db_argument, attack_type, premise, conclusion, f, t, r, is_supportive, _t) if not user_msg: user_msg = '' # is logged in? if is_logged_in: return user_msg, _t.get(_.canYouGiveAReasonForThat) else: return user_msg, '' def __get_user_msg_for_users_confrontation_response(db_argument, attack_type, premise, conclusion, itisfalsethat, itistruethat, right, is_supportive, _t): """ Builds a string based on the attack type to confront the user :param db_argument: Argument :param attack_type: String :param premise: String :param conclusion: String :param itisfalsethat: String :param itistruethat: String :param right: String :param is_supportive: Boolean :param _t: Translator :return: String """ # different cases if attack_type == Relations.UNDERMINE: return __get_user_msg_for_users_undermine_response(premise, _t.get(_.that)) if attack_type == Relations.SUPPORT: return __get_user_msg_for_users_support_response(conclusion, itistruethat, itisfalsethat, is_supportive, _t) if attack_type == Relations.UNDERCUT: return __get_user_msg_for_users_undercut_response(db_argument, premise, conclusion, right, _t) if attack_type == Relations.REBUT: return __get_user_msg_for_users_rebut_response(premise, conclusion, right, is_supportive, _t) def __get_user_msg_for_users_undermine_response(premise, that): """ Simple text for an undermine :param premise: String :param that: String :return: String """ return '{} {}{}{}'.format(that, '{}', premise, '{}') def __get_user_msg_for_users_support_response(conclusion, itistruethat, itisfalsethat, is_supportive, _t): """ Simple text for an support :param conclusion: String :param itistruethat: String :param itisfalsethat: String :param is_supportive: String :param _t: Translator :return: String """ if is_supportive: intro = itistruethat outro = _t.get(_.hold) else: intro = itisfalsethat outro = _t.get(_.doesNotHold) return '{}{} {} {}{}.'.format('{}', intro, conclusion, outro, '{}') def __get_user_msg_for_users_undercut_response(db_argument, premise, conclusion, right, _t): """ Simple text for the undercut :param db_argument: Argument :param premise: String :param conclusion: String :param right: String :param _t: Translator :return: """ tmp = None if db_argument.conclusion_uid is None and _t.get_lang() == 'de': # undercutting an undercut start_text = _t.get(_.itIsTrueThatAnonymous) if conclusion.lower().startswith(start_text.lower()): conclusion = conclusion[len(start_text):] tmp = _t.get(_.butThisDoesNotRejectArgument) if tmp is None: tmp = _t.get(_.butIDoNotBelieveArgumentFor if db_argument.is_supportive else _.butIDoNotBelieveCounterFor) tmp = tmp.format(conclusion) return '{}{}. {}{}{}'.format(right, premise, '{}', tmp, '{}') def __get_user_msg_for_users_rebut_response(premise, conclusion, right, is_supportive, _t): """ Simple text for the rebut :param premise: String :param conclusion: String :param right: String :param is_supportive: :param _t: Translator :return: String """ if is_supportive: intro = _t.get(_.iAcceptCounterThat) mid = _t.get(_.howeverIHaveMuchStrongerArgumentRejectingThat) else: intro = _t.get(_.iAcceptArgumentThat) mid = _t.get(_.howeverIHaveMuchStrongerArgumentAcceptingThat) return '{}{}{}, {} {}. {} {}.{}'.format('{}', right, premise, intro, conclusion, mid, conclusion, '{}') def get_relation_text_dict_without_substitution(lang, with_no_opinion_text, premise, conclusion, is_dont_know=False): """ Returns the four different reaction possibilities without any replacement based on the gender of the confrontation :param lang: Language.ui_locales :param with_no_opinion_text: Boolean :param premise: String :param conclusion: String :param is_dont_know: Boolean :return: dict() """ return __get_relation_text_dict(lang, with_no_opinion_text, premise, conclusion, is_dont_know) def get_relation_text_dict_with_substitution(lang, with_no_opinion_text, is_dont_know=False, attack_type=None, gender=''): """ Returns the four different reaction possibilities with replacements based on the gender of the confrontation :param lang: Language.ui_locales :param with_no_opinion_text: Boolean :param is_dont_know: Boolean :param attack_type: String :param gender: String :return: dict() """ _t = Translator(lang) assertion = _t.get(_.theirAssertion) reason = _t.get(_.theirReason) statement = _t.get(_.theirStatement) position = _t.get(_.theirPosition) opinion = _t.get(_.opinion) if gender == 'f': assertion = _t.get(_.herAssertion) reason = _t.get(_.herReason) statement = _t.get(_.herStatement) position = _t.get(_.herPosition) opinion = _t.get(_.opinion_her) elif gender == 'm': assertion = _t.get(_.hisAssertion) reason = _t.get(_.hisReason) statement = _t.get(_.hisStatement) position = _t.get(_.hisPosition) opinion = _t.get(_.opinion_his) premise = statement if lang == 'de': if is_dont_know: premise = assertion conclusion = assertion if is_dont_know: conclusion = reason else: conclusion = opinion if not is_dont_know: if attack_type == Relations.UNDERMINE or attack_type == Relations.REBUT: conclusion = position else: conclusion = _t.get(_.myArgument) return __get_relation_text_dict(lang, with_no_opinion_text, premise, conclusion, is_dont_know) def __get_relation_text_dict(lang, with_no_opinion_text, premise, conclusion, is_dont_know=False): """ Text of the different reaction types for an given argument :param lang: Language.ui_locales :param with_no_opinion_text: Boolean :param premise: String :param conclusion: String :param is_dont_know: Boolean :return: dict() """ _t = Translator(lang) premise = start_attack + premise + end_tag conclusion = start_argument + conclusion + end_tag ret_dict = dict() if with_no_opinion_text: ret_dict['step_back_text'] = _t.get(_.goStepBack) + '. (' + _t.get(_.noOtherAttack) + ')' ret_dict['no_opinion_text'] = _t.get(_.showMeAnotherArgument) + '.' ret_dict['undermine_text'] = _t.get(_.reaction_text_undermine).format(premise) ret_dict['support_text'] = _t.get(_.reaction_text_support).format(premise) ret_dict['undercut_text'] = _t.get(_.reaction_text_undercut).format(premise, conclusion) if is_dont_know: tmp = start_argument + _t.get(_.reason) + end_tag ret_dict['undercut_text'] = _t.get(_.reaction_text_undercut_for_dont_know).format(premise, tmp) conclusion_user = start_position + _t.get(_.myPosition) + end_tag ret_dict['rebut_text'] = _t.get(_.reaction_text_rebut).format(premise, conclusion, conclusion_user) if is_dont_know: ret_dict['rebut_text'] = _t.get(_.reaction_text_rebut_for_dont_know).format(conclusion) return ret_dict def get_jump_to_argument_text_list(lang): """ Returns answer set for the jumping step :param lang: ui_locales :return: Array with [Conclusion is (right, wrong), Premise is (right, wrong) Premise does not lead to the conclusion, both hold] """ _t = Translator(lang) premise = start_attack + _t.get(_.reason) + end_tag conclusion = start_argument + _t.get(_.assertion) + end_tag answers = list() answers.append(_t.get(_.jumpAnswer0).format(conclusion, premise)) answers.append(_t.get(_.jumpAnswer1).format(conclusion, premise)) answers.append(_t.get(_.jumpAnswer2).format(conclusion, premise)) answers.append(_t.get(_.jumpAnswer3).format(conclusion, premise)) answers.append(_t.get(_.jumpAnswer4).format(premise)) return answers def get_support_to_argument_text_list(lang): """ Returns answer set for the supporting step :param lang: ui_locales :return: Array with [Conclusion is (right, wrong), Premise is (right, wrong) Premise does not lead to the conclusion, both hold] """ _t = Translator(lang) premise = start_attack + _t.get(_.reason) + end_tag conclusion = start_argument + _t.get(_.assertion) + end_tag answers = list() answers.append(_t.get(_.supportAnswer0).format(premise)) answers.append(_t.get(_.supportAnswer3).format(premise)) answers.append(_t.get(_.supportAnswer2).format(premise, conclusion)) answers.append(_t.get(_.supportAnswer1).format(premise)) return answers def get_text_for_confrontation(lang, nickname, premise, conclusion, sys_conclusion, supportive, attack, confrontation, reply_for_argument, user_is_attacking, user_arg, sys_arg, color_html=True): """ Text for the confrontation of the system :param lang: ui_locales :param nickname: nickname :param premise: String :param conclusion: String :param sys_conclusion: String :param supportive: String :param attack: String :param confrontation: String :param reply_for_argument: Boolean :param user_is_attacking: Boolean :param user_arg: Argument :param sys_arg: Argument :param color_html: Boolean :return: String """ my_start_argument = '' my_end_tag = '' if color_html: my_start_attack = start_attack my_start_argument = start_argument my_end_tag = end_tag confrontation = my_start_attack + confrontation + my_end_tag conclusion = my_start_argument + conclusion + my_end_tag if attack == Relations.UNDERMINE: premise = my_start_argument + premise + my_end_tag sys_conclusion = my_start_argument + sys_conclusion + my_end_tag # build some confrontation text if attack == Relations.UNDERMINE: confrontation_text, gender = __get_confrontation_text_for_undermine(nickname, premise, lang, sys_arg, my_start_argument, my_end_tag, confrontation) elif attack == Relations.UNDERCUT: confrontation_text, gender = __get_confrontation_text_for_undercut(nickname, lang, premise, conclusion, confrontation, supportive, sys_arg) elif attack == Relations.REBUT: confrontation_text, gender = __get_confrontation_text_for_rebut(lang, nickname, reply_for_argument, user_arg, user_is_attacking, sys_conclusion, confrontation, premise, conclusion, my_start_argument, sys_arg) else: return '', '' _t = Translator(lang) question = '.<br><br>{}?'.format(_t.get(_.whatDoYouThinkAboutThat)) sys_text = confrontation_text + question return sys_text, gender def get_text_for_support(db_arg, argument_text, nickname, _t): """ Returns text for the system bubble during the support step :param db_arg: Argument :param argument_text: string :param nickname: User.nickname :param _t: translator :return: string """ intro = _t.get(_.goodPointAndUserIsInterestedToo) intro = intro.format(start_tag, end_tag, argument_text) question = '<br><br>{}?'.format(_t.get(_.whatDoYouThinkAboutThat)) return intro + question def get_text_for_edit_text_message(lang, nickname, orginal, edit, url, for_html=True): """ Returns text for the editing an statement :param lang: Language.ui_locales :param nickname: User.nickname :param orginal: :param edit: :param url: String :param for_html: Boolean :return: """ _t = Translator(lang) if for_html: return _t.get(_.editTextMessageForHtml).format(nickname, orginal, edit, url, url) else: return _t.get(_.editTextMessage).format(nickname, orginal, edit, url) def get_text_for_message(nickname, lang, path, message_content, for_html=True) -> str: """ This method creates a message used for example in mails or messages. :param nickname: The nickname of the addressed user :param lang: The language to be used in the email :param path: The url for the user where he can find the changes :param message_content: The key variable which will be translated into a message :param for_html: A boolean to determine if the Message should contain a clickable link :return: A Message addressed to a user which can contain a clickable or non-clickable link """ _t = Translator(lang) intro = _t.get(message_content).format(nickname) clickForMore = start_with_capital(_t.get(_.clickForMore)) dbas_url = get_global_url() message_appendix_auto_generated = _t.get(_.emailBodyText).format(dbas_url) abs_path = f'{dbas_url}/discuss{path}' link = f'<a href="{abs_path}">{clickForMore}</a>' if for_html else abs_path msg = f'{intro}\n\n{link}\n\n---\n\n{message_appendix_auto_generated}' return msg.replace("\n", "<br>") if for_html else msg def __get_confrontation_text_for_undermine(nickname: str, premise: str, lang: str, system_argument: Argument, my_argument_start_tag: str, my_end_tag: str, confrontation: str): """ Returns the system bubble text for an undermine :param nickname: User.nickname :param premise :param lang: Language :param system_argument :param my_argument_start_tag :param my_end_tag :param confrontation :return: """ _t = Translator(lang) data = get_name_link_of_arguments_author(system_argument, nickname) intro = f'{start_content}{_t.get(_.iThinkThat)}' pro_con_tag = start_con hold_it = _t.get(_.doesNotHold) if system_argument.is_supportive: pro_con_tag = start_pro hold_it = _t.get(_.hold) because = _t.get(_.because).lower() confrontation_text = f'{intro}{end_tag} {premise}{pro_con_tag} {my_argument_start_tag}{hold_it}{my_end_tag}{end_tag}, {because} {confrontation}' return confrontation_text, data['gender'] if data['is_valid'] else '' def __get_confrontation_text_for_undercut(nickname, lang, premise, conclusion, confrontation, supportive, system_argument): """ Returns the system bubble text for an undercut :param nickname: User.nickname :param lang: Language :param premise: String :param conclusion: String :param confrontation: String :param supportive: Boolean :param system_argument: String :return: """ _t = Translator(lang) data = get_name_link_of_arguments_author(system_argument, nickname) if data['is_valid']: gender_think = _t.get(_.iThink) else: gender_think = _t.get(_.iThink) intro = start_content + _t.get(_.iAgreeThat) if supportive: bind = _t.get(_.butIDoNotBelieveArgument) else: bind = _t.get(_.butIDoNotBelieveCounter) bind = bind.format(start_con, end_tag, start_argument, end_tag) confrontation_text = f'{intro} {premise}. {bind}{end_tag} {conclusion}. {gender_think} {confrontation}' return confrontation_text, data['gender'] if data['is_valid'] else '' def __get_confrontation_text_for_rebut(lang, nickname, reply_for_argument, user_arg, user_is_attacking, sys_conclusion, confrontation, premise, conclusion, my_start_argument, system_argument): """ Returns the system bubble text for a rebut :param lang: ui_locales :param nickname: of current user :param reply_for_argument: Boolean :param user_arg: Argument :param user_is_attacking: Boolean :param sys_conclusion: String :param confrontation: String :param premise: String :param conclusion: String :param my_start_argument: String :param system_argument: Counter argument of the system :return: String, String """ _t = Translator(lang) data = get_name_link_of_arguments_author(system_argument, nickname) db_other_nick = data['user'].nickname if data['user'] else '' infos = { 'is_okay': data['is_valid'], 'lang': lang, 'nickname': nickname, 'author': data['link'], 'gender': data['gender'], 'user_is_attacking': user_is_attacking, 'db_other_nick': db_other_nick, } # has the other user any opinion for the user's conclusion? has_other_user_opinion = False if data['is_valid']: if user_arg.argument_uid is not None: db_vote = DBDiscussionSession.query(ClickedArgument).filter( ClickedArgument.argument_uid == user_arg.argument_uid, ClickedArgument.author_uid == data['user'].uid, ClickedArgument.is_up_vote == True, ClickedArgument.is_valid == True).all() else: db_vote = DBDiscussionSession.query(ClickedStatement).filter( ClickedStatement.statement_uid == user_arg.conclusion_uid, ClickedStatement.author_uid == data['user'].uid, ClickedStatement.is_up_vote == True, ClickedStatement.is_valid == True).all() has_other_user_opinion = db_vote and len(db_vote) > 0 infos['has_other_user_opinion'] = has_other_user_opinion # distinguish between reply for argument and reply for premise group if reply_for_argument: # reply for argument confrontation_text = __get_confrontation_text_for_rebut_as_reply(_t, confrontation, user_arg, conclusion, sys_conclusion, system_argument, infos) else: # reply for premise group confrontation_text = __get_confrontation_text_for_rebut_as_pgroup(_t, confrontation, premise, conclusion, my_start_argument, infos) return confrontation_text, data['gender'] def __get_confrontation_text_for_rebut_as_reply(_t, confrontation, user_arg, conclusion, sys_conclusion, system_argument, infos): # changing arguments for better understanding if not user_arg.is_supportive: conclusion = sys_conclusion bind = start_content + start_tag + _t.get(_.otherUsersClaimStrongerArgument) + end_tag say = _t.get(_.iSay) tmp_start_tag = '' tmp_end_tag = '' if tag_type in confrontation: tmp_start_tag = start_argument tmp_end_tag = end_tag accept = _.accept reject = _.reject point = ':' if infos['lang'] == 'de': accept = _.assistance reject = _.rejection point = '' tmp = '{}{}{}'.format(tmp_start_tag, _t.get(accept if system_argument.is_supportive else reject), tmp_end_tag) bind = bind.format(tmp) confrontation_text = f'{bind} {conclusion}. {say}{point} {confrontation}' return confrontation_text def __get_confrontation_text_for_rebut_as_pgroup(_t, confrontation, premise, conclusion, start_argument, infos): if infos['is_okay']: if infos['has_other_user_opinion']: intro = start_content + _t.get(_.iAgreeThat) + ' {}. ' intro += _t.get(_.strongerStatement) elif infos['db_other_nick'] == infos['nickname']: intro = infos['author'] + ' ' + start_content intro += _t.get( _.earlierYouHadNoOpinitionForThisStatement) + ', ' # earlier you had no opinion for {premise} intro += _t.get(_.whichConfirmedYourView).format(start_position, end_tag) # which {start_position}confirmed your view{end_tag} intro += ' ' + _t.get( _.strongerStatementY) # But you had a stronger {tag}statement for {tmp}{end_tag} else: intro = start_content intro += _t.get(_.otherUserDoesntHaveOpinionForThisStatement) + '. ' intro += _t.get(_.strongerStatement) else: intro = start_content + _t.get(_.iNoOpinion) + ' {}. ' + _t.get(_.strongerStatement) tmp = start_argument if infos['user_is_attacking']: tag = start_pro tmp += _t.get(_.accepting) else: tag = start_con tmp += _t.get(_.rejecting) tmp += end_tag if len(start_argument) > 0 else '' intro = intro.format(premise, tag, tmp, ' ' + end_tag) tmp = _t.get(_.strongerStatementEnd) if tmp == '': tmp += ' ' conclusion = conclusion[len(start_argument):] if infos['db_other_nick'] == infos['nickname']: bind = _t.get(_.youSaidThat) else: bind = _t.get(_.iSay) confrontation_text = f'{intro} {conclusion}. {bind} {confrontation}' return confrontation_text def get_name_link_of_arguments_author(argument: Union[Argument, Statement], nickname: Optional[str], with_link: bool = True) -> Dict: """ Will return author of the argument, if the first supporting user, or the first supporting user None is returned as user if there currently is no supporting user. :param argument: Argument :param nickname: User.nickname :param with_link: :return: """ user, link, is_valid = get_author_data(argument.author, False, True) gender = argument.author.gender if argument.author else 'n' db_anonymous_user: User = DBDiscussionSession.query(User).filter_by(nickname=nick_of_anonymous_user).first() # if the data of arguments author is not okay, get the first user, who agrees with the argument if argument.author_uid == db_anonymous_user.uid or not is_valid: # get nick of current user nickname = nickname if nickname is not None else nick_of_anonymous_user db_current_user = DBDiscussionSession.query(User).filter_by(nickname=nickname).first() db_author_of_argument = get_author_or_first_supporter_of_element(argument.uid, db_current_user.uid, True) if db_author_of_argument: user, link, is_valid = get_author_data(db_author_of_argument, gravatar_on_right_side=False, linked_with_users_page=with_link) gender = db_author_of_argument.gender if db_author_of_argument else 'n' else: return { 'user': None, 'link': '', 'gender': 'n', 'is_valid': False } return { 'user': user, 'link': link if is_valid else '', 'gender': gender, 'is_valid': is_valid } def get_author_or_first_supporter_of_element(uid, current_user_uid, is_argument): """ Returns the first user with the same opinion and who is not the anonymous or current user :param uid: Argument.uid / Statement.uid :param current_user_uid: User.uid :param is_argument: Boolean :return: MarkedArgument or None """ db_anonymous_user = DBDiscussionSession.query(User).filter_by(nickname=nick_of_anonymous_user).first() if is_argument: db_mark = DBDiscussionSession.query(MarkedArgument).filter( ~MarkedArgument.author_uid.in_([db_anonymous_user.uid, current_user_uid]), MarkedArgument.argument_uid == uid, ).first() else: db_mark = DBDiscussionSession.query(MarkedStatement).filter( ~MarkedStatement.author_uid.in_([db_anonymous_user.uid, current_user_uid]), MarkedStatement.statement_uid == uid, ).first() if db_mark: return DBDiscussionSession.query(User).get(db_mark.author_uid) if is_argument: db_click = DBDiscussionSession.query(ClickedArgument).filter( ~ClickedArgument.author_uid.in_([db_anonymous_user.uid, current_user_uid]), ClickedArgument.argument_uid == uid, ).first() else: db_click = DBDiscussionSession.query(ClickedStatement).filter( ~ClickedStatement.author_uid.in_([db_anonymous_user.uid, current_user_uid]), ClickedStatement.statement_uid == uid, ).first() if db_click: return DBDiscussionSession.query(User).get(db_click.author_uid) return None def remove_punctuation(argument_text: str) -> str: """ Remove multiple punctuations at the end of a line. :param argument_text: :return: """ offset = len('</' + 'span' + '>') if argument_text.endswith('</' + 'span' + '>') else 1 while argument_text[:-offset].endswith(('.', '?', '!')): argument_text = argument_text[:-offset - 1] + argument_text[-offset:] return argument_text
import aerosandbox as asb import aerosandbox.numpy as np n_timesteps = 301 mass_block = 1 opti = asb.Opti() time = np.cosspace(0, 1, n_timesteps) position = opti.variable( init_guess=np.linspace(0, 1, n_timesteps) ) velocity = opti.derivative_of( position, with_respect_to=time, derivative_init_guess=1, ) force = opti.variable( init_guess=np.linspace(2, -2, n_timesteps), n_vars=n_timesteps ) opti.constrain_derivative( derivative=force / mass_block, variable=velocity, with_respect_to=time, ) effort_expended = np.sum( np.trapz(force ** 2) * np.diff(time) ) opti.minimize(effort_expended) ### Boundary conditions opti.subject_to([ position[0] == 0, position[-1] == 1, velocity[0] == 0, velocity[-1] == 0, ]) sol = opti.solve() import matplotlib.pyplot as plt import seaborn as sns fig, ax = plt.subplots(1, 1, figsize=(6.4, 4.8), dpi=200) plt.plot(sol.value(time), sol.value(position)) plt.xlabel(r"Time") plt.ylabel(r"Position") plt.title(r"Position") plt.tight_layout() plt.show() fig, ax = plt.subplots(1, 1, figsize=(6.4, 4.8), dpi=200) plt.plot(sol.value(time), sol.value(velocity)) plt.xlabel(r"Time") plt.ylabel(r"Velocity") plt.title(r"Velocity") plt.tight_layout() plt.show() fig, ax = plt.subplots(1, 1, figsize=(6.4, 4.8), dpi=200) plt.plot(sol.value(time), sol.value(force), "-") # plt.plot(sol.value(np.trapz(time)), sol.value(np.diff(velocity) / np.diff(time)), ".-") plt.show() # fig, ax = plt.subplots(1, 1, figsize=(6.4, 4.8), dpi=200) # plt.plot(sol.value(time), sol.value(velocity)) # plt.plot(sol.value(np.trapz(time)), sol.value(np.diff(position) / np.diff(time)), ".-") # plt.show()
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const React = require("react"); const wrapIcon_1 = require("../utils/wrapIcon"); const rawSvg = (iconProps) => { const { className, primaryFill } = iconProps; return React.createElement("svg", { width: 24, height: 24, viewBox: "0 0 24 24", xmlns: "http://www.w3.org/2000/svg", className: className }, React.createElement("path", { d: "M12.75 9.25a.75.75 0 010 1.5h-5.5a.75.75 0 010-1.5h5.5z", fill: primaryFill }), React.createElement("path", { d: "M17.25 10a7.25 7.25 0 10-2.68 5.63l4.9 4.9.08.07a.75.75 0 00.98-1.13l-4.9-4.9A7.22 7.22 0 0017.25 10zm-13 0a5.75 5.75 0 1111.5 0 5.75 5.75 0 01-11.5 0z", fill: primaryFill })); }; const ZoomOut24Regular = wrapIcon_1.default(rawSvg({}), 'ZoomOut24Regular'); exports.default = ZoomOut24Regular;
from matplotlib import pyplot as plt def plot(name, values): fig, ax = plt.subplots() ax.plot(values) ax.set(xlabel='days', ylabel='infected', title=name) ax.grid() plt.show()
# -*- coding: utf-8 -*- """ werkzeug.debug.console ~~~~~~~~~~~~~~~~~~~~~~ Interactive console support. :copyright: (c) 2010 by the Werkzeug Team, see AUTHORS for more details. :license: BSD. """ import sys import code from types import CodeType from werkzeug.utils import escape from werkzeug.local import Local from werkzeug.debug.repr import debug_repr, dump, helper from werkzeug.debug.utils import render_template _local = Local() class HTMLStringO(object): """A StringO version that HTML escapes on write.""" def __init__(self): self._buffer = [] def isatty(self): return False def close(self): pass def flush(self): pass def seek(self, n, mode=0): pass def readline(self): if len(self._buffer) == 0: return '' ret = self._buffer[0] del self._buffer[0] return ret def reset(self): val = ''.join(self._buffer) del self._buffer[:] return val def _write(self, x): if isinstance(x, str): x = x.decode('utf-8', 'replace') self._buffer.append(x) def write(self, x): self._write(escape(x)) def writelines(self, x): self._write(escape(''.join(x))) class ThreadedStream(object): """Thread-local wrapper for sys.stdout for the interactive console.""" def push(): if not isinstance(sys.stdout, ThreadedStream): sys.stdout = ThreadedStream() _local.stream = HTMLStringO() push = staticmethod(push) def fetch(): try: stream = _local.stream except AttributeError: return '' return stream.reset() fetch = staticmethod(fetch) def displayhook(obj): try: stream = _local.stream except AttributeError: return _displayhook(obj) # stream._write bypasses escaping as debug_repr is # already generating HTML for us. if obj is not None: stream._write(debug_repr(obj)) displayhook = staticmethod(displayhook) def __setattr__(self, name, value): raise AttributeError('read only attribute %s' % name) def __dir__(self): return dir(sys.__stdout__) def __getattribute__(self, name): if name == '__members__': return dir(sys.__stdout__) try: stream = _local.stream except AttributeError: stream = sys.__stdout__ return getattr(stream, name) def __repr__(self): return repr(sys.__stdout__) # add the threaded stream as display hook _displayhook = sys.displayhook sys.displayhook = ThreadedStream.displayhook class _ConsoleLoader(object): def __init__(self): self._storage = {} def register(self, code, source): self._storage[id(code)] = source # register code objects of wrapped functions too. for var in code.co_consts: if isinstance(var, CodeType): self._storage[id(var)] = source def get_source_by_code(self, code): try: return self._storage[id(code)] except KeyError: pass def _wrap_compiler(console): compile = console.compile def func(source, filename, symbol): code = compile(source, filename, symbol) console.loader.register(code, source) return code console.compile = func class _InteractiveConsole(code.InteractiveInterpreter): def __init__(self, globals, locals): code.InteractiveInterpreter.__init__(self, locals) self.globals = dict(globals) self.globals['dump'] = dump self.globals['help'] = helper self.globals['__loader__'] = self.loader = _ConsoleLoader() self.more = False self.buffer = [] _wrap_compiler(self) def runsource(self, source): source = source.rstrip() + '\n' ThreadedStream.push() prompt = self.more and '... ' or '>>> ' try: source_to_eval = ''.join(self.buffer + [source]) if code.InteractiveInterpreter.runsource(self, source_to_eval, '<debugger>', 'single'): self.more = True self.buffer.append(source) else: self.more = False del self.buffer[:] finally: output = ThreadedStream.fetch() return prompt + source + output def runcode(self, code): try: exec code in self.globals, self.locals except: self.showtraceback() def showtraceback(self): from werkzeug.debug.tbtools import get_current_traceback tb = get_current_traceback(skip=1) sys.stdout._write(tb.render_summary()) def showsyntaxerror(self, filename=None): from werkzeug.debug.tbtools import get_current_traceback tb = get_current_traceback(skip=4) sys.stdout._write(tb.render_summary()) def write(self, data): sys.stdout.write(data) class Console(object): """An interactive console.""" def __init__(self, globals=None, locals=None): if locals is None: locals = {} if globals is None: globals = {} self._ipy = _InteractiveConsole(globals, locals) def eval(self, code): return self._ipy.runsource(code)