text
stringlengths 6
947k
| repo_name
stringlengths 5
100
| path
stringlengths 4
231
| language
stringclasses 1
value | license
stringclasses 15
values | size
int64 6
947k
| score
float64 0
0.34
|
---|---|---|---|---|---|---|
from indiefilmrentals.products.models import *
from shop_simplecategories.models import *
def categories(request):
return {'categories': Category.objects.all()}
|
blorenz/indie-film-rentals
|
indiefilmrentals/products/processors.py
|
Python
|
bsd-3-clause
| 169 | 0.017751 |
# -*- coding: utf-8 -*-
# flake8: noqa
# Disable Flake8 because of all the sphinx imports
#
# 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.
# Airflow documentation build configuration file, created by
# sphinx-quickstart on Thu Oct 9 20:50:01 2014.
#
# 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.
"""Configuration of Airflow Docs"""
import os
import sys
from typing import Dict
import airflow
from airflow.configuration import default_config_yaml
try:
import sphinx_airflow_theme # pylint: disable=unused-import
airflow_theme_is_available = True
except ImportError:
airflow_theme_is_available = False
autodoc_mock_imports = [
'MySQLdb',
'adal',
'analytics',
'azure',
'azure.cosmos',
'azure.datalake',
'azure.mgmt',
'boto3',
'botocore',
'bson',
'cassandra',
'celery',
'cloudant',
'cryptography',
'cx_Oracle',
'datadog',
'distributed',
'docker',
'google',
'google_auth_httplib2',
'googleapiclient',
'grpc',
'hdfs',
'httplib2',
'jaydebeapi',
'jenkins',
'jira',
'kubernetes',
'mesos',
'msrestazure',
'pandas',
'pandas_gbq',
'paramiko',
'pinotdb',
'psycopg2',
'pydruid',
'pyhive',
'pyhive',
'pymongo',
'pymssql',
'pysftp',
'qds_sdk',
'redis',
'simple_salesforce',
'slackclient',
'smbclient',
'snowflake',
'sshtunnel',
'tenacity',
'vertica_python',
'winrm',
'zdesk',
]
# Hack to allow changing for piece of the code to behave differently while
# the docs are being built. The main objective was to alter the
# behavior of the utils.apply_default that was hiding function headers
os.environ['BUILDING_AIRFLOW_DOCS'] = 'TRUE'
# 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.append(os.path.join(os.path.dirname(__file__), 'exts'))
# -- 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.coverage',
'sphinx.ext.viewcode',
'sphinx.ext.graphviz',
'sphinxarg.ext',
'sphinxcontrib.httpdomain',
'sphinxcontrib.jinja',
'sphinx.ext.intersphinx',
'autoapi.extension',
'exampleinclude',
'docroles',
'removemarktransform',
]
autodoc_default_options = {
'show-inheritance': True,
'members': True
}
jinja_contexts = {
'config_ctx': {"configs": default_config_yaml()}
}
viewcode_follow_imported_members = True
# 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'Airflow'
# copyright = u''
# 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.0.0'
version = airflow.__version__
# The full version, including alpha/beta/rc tags.
# release = '1.0.0'
release = airflow.__version__
# 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 = [
'_api/airflow/_vendor',
'_api/airflow/api',
'_api/airflow/bin',
'_api/airflow/config_templates',
'_api/airflow/configuration',
'_api/airflow/contrib/auth',
'_api/airflow/contrib/example_dags',
'_api/airflow/contrib/index.rst',
'_api/airflow/contrib/kubernetes',
'_api/airflow/contrib/task_runner',
'_api/airflow/contrib/utils',
'_api/airflow/dag',
'_api/airflow/default_login',
'_api/airflow/example_dags',
'_api/airflow/exceptions',
'_api/airflow/index.rst',
'_api/airflow/jobs',
'_api/airflow/lineage',
'_api/airflow/logging_config',
'_api/airflow/macros',
'_api/airflow/migrations',
'_api/airflow/plugins_manager',
'_api/airflow/security',
'_api/airflow/serialization',
'_api/airflow/settings',
'_api/airflow/sentry',
'_api/airflow/stats',
'_api/airflow/task',
'_api/airflow/ti_deps',
'_api/airflow/utils',
'_api/airflow/version',
'_api/airflow/www',
'_api/airflow/www_rbac',
'_api/main',
'autoapi_templates',
'howto/operator/gcp/_partials',
]
# 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 = []
# If true, keep warnings as "system message" paragraphs in the built documents.
keep_warnings = True
intersphinx_mapping = {
'boto3': ('https://boto3.amazonaws.com/v1/documentation/api/latest/', None),
'mongodb': ('https://api.mongodb.com/python/current/', None),
'pandas': ('https://pandas.pydata.org/pandas-docs/stable/', None),
'python': ('https://docs.python.org/3/', None),
'requests': ('https://requests.readthedocs.io/en/master/', None),
'sqlalchemy': ('https://docs.sqlalchemy.org/en/latest/', None),
'hdfs': ('https://hdfscli.readthedocs.io/en/latest/', None),
# google-cloud-python
'google-cloud-automl': ('https://googleapis.dev/python/automl/latest', None),
'google-cloud-bigquery': ('https://googleapis.dev/python/bigquery/latest', None),
'google-cloud-bigquery-datatransfer': ('https://googleapis.dev/python/bigquerydatatransfer/latest', None),
'google-cloud-bigquery-storage': ('https://googleapis.dev/python/bigquerystorage/latest', None),
'google-cloud-bigtable': ('https://googleapis.dev/python/bigtable/latest', None),
'google-cloud-container': ('https://googleapis.dev/python/container/latest', None),
'google-cloud-core': ('https://googleapis.dev/python/google-cloud-core/latest', None),
'google-cloud-datastore': ('https://googleapis.dev/python/datastore/latest', None),
'google-cloud-dlp': ('https://googleapis.dev/python/dlp/latest', None),
'google-cloud-kms': ('https://googleapis.dev/python/cloudkms/latest', None),
'google-cloud-language': ('https://googleapis.dev/python/language/latest', None),
'google-cloud-pubsub': ('https://googleapis.dev/python/pubsub/latest', None),
'google-cloud-redis': ('https://googleapis.dev/python/redis/latest', None),
'google-cloud-spanner': ('https://googleapis.dev/python/spanner/latest', None),
'google-cloud-speech': ('https://googleapis.dev/python/speech/latest', None),
'google-cloud-storage': ('https://googleapis.dev/python/storage/latest', None),
'google-cloud-tasks': ('https://googleapis.dev/python/cloudtasks/latest', None),
'google-cloud-texttospeech': ('https://googleapis.dev/python/texttospeech/latest', None),
'google-cloud-translate': ('https://googleapis.dev/python/translation/latest', None),
'google-cloud-videointelligence': ('https://googleapis.dev/python/videointelligence/latest', None),
'google-cloud-vision': ('https://googleapis.dev/python/vision/latest', None),
}
# -- 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'
if airflow_theme_is_available:
html_theme = 'sphinx_airflow_theme'
# 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 = {}
# Add any paths that contain custom themes here, relative to this directory.
# html_theme_path = []
import sphinx_rtd_theme # pylint: disable=wrong-import-position,wrong-import-order
html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
html_title = "Airflow Documentation"
# A shorter title for the navigation bar. Default is the same as html_title.
html_short_title = ""
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
# html_logo = None
html_favicon = "../airflow/www/static/pin_32.png"
# 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']
# Add any extra paths that contain custom files (such as robots.txt or
# .htaccess) here, relative to this directory. These files are copied
# directly to the root of the documentation.
# html_extra_path = []
# A list of JavaScript filename. The entry must be a filename string or a
# tuple containing the filename string and the attributes dictionary. The
# filename must be relative to the html_static_path, or a full URI with
# scheme like http://example.org/script.js.
html_js_files = ['jira-links.js']
# 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.
if airflow_theme_is_available:
html_sidebars = {
'**': [
'version-selector.html',
'searchbox.html',
'globaltoc.html',
]
}
# 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 = False
# 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 = 'Airflowdoc'
# -- 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': '',
} # type: Dict[str,str]
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
('index', 'Airflow.tex', u'Airflow Documentation',
u'Apache Airflow', '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', 'airflow', u'Airflow Documentation',
[u'Apache Airflow'], 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', 'Airflow', u'Airflow Documentation',
u'Apache Airflow', 'Airflow',
'Airflow is a system to programmatically author, schedule and monitor data pipelines.',
'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'
# If true, do not generate a @detailmenu in the "Top" node's menu.
# texinfo_no_detailmenu = False
# sphinx-autoapi configuration
# See:
# https://sphinx-autoapi.readthedocs.io/en/latest/config.html
# Paths (relative or absolute) to the source code that you wish to generate
# your API documentation from.
autoapi_dirs = [
os.path.abspath('../airflow'),
]
# A directory that has user-defined templates to override our default templates.
autoapi_template_dir = 'autoapi_templates'
# A list of patterns to ignore when finding files
autoapi_ignore = [
# These modules are backcompat shims, don't build docs for them
'*/airflow/contrib/operators/s3_to_gcs_transfer_operator.py',
'*/airflow/contrib/operators/gcs_to_gcs_transfer_operator.py',
'*/airflow/contrib/operators/gcs_to_gcs_transfer_operator.py',
'*/node_modules/*',
'*/migrations/*',
]
# Keep the AutoAPI generated files on the filesystem after the run.
# Useful for debugging.
autoapi_keep_files = True
# Relative path to output the AutoAPI files into. This can also be used to place the generated documentation
# anywhere in your documentation hierarchy.
autoapi_root = '_api'
# -- Options for examole include ------------------------------------------
exampleinclude_sourceroot = os.path.abspath('..')
# -- Additional HTML Context variable
html_context = {
# Google Analytics ID.
# For more information look at:
# https://github.com/readthedocs/sphinx_rtd_theme/blob/master/sphinx_rtd_theme/layout.html#L222-L232
'theme_analytics_id': 'UA-140539454-1',
}
if airflow_theme_is_available:
html_context = {
# Variables used to build a button for editing the source code
#
# The path is created according to the following template:
#
# https://{{ github_host|default("github.com") }}/{{ github_user }}/{{ github_repo }}/
# {{ theme_vcs_pageview_mode|default("blob") }}/{{ github_version }}{{ conf_py_path }}
# {{ pagename }}{{ suffix }}
#
# More information:
# https://github.com/readthedocs/readthedocs.org/blob/master/readthedocs/doc_builder/templates/doc_builder/conf.py.tmpl#L100-L103
# https://github.com/readthedocs/sphinx_rtd_theme/blob/master/sphinx_rtd_theme/breadcrumbs.html#L45
# https://github.com/apache/airflow-site/blob/91f760c/sphinx_airflow_theme/sphinx_airflow_theme/suggest_change_button.html#L36-L40
#
'theme_vcs_pageview_mode': 'edit',
'conf_py_path': '/docs/',
'github_user': 'apache',
'github_repo': 'airflow',
'github_version': 'master',
'display_github': 'master',
'suffix': '.rst',
}
|
owlabs/incubator-airflow
|
docs/conf.py
|
Python
|
apache-2.0
| 17,740 | 0.001522 |
"""
Example generation for the scikit learn
Generate the rst files for the examples by iterating over the python
example files.
Files that generate images should start with 'plot'
"""
from __future__ import division, print_function
from time import time
import ast
import os
import re
import shutil
import traceback
import glob
import sys
import gzip
import posixpath
import subprocess
import warnings
from sklearn.externals import six
# Try Python 2 first, otherwise load from Python 3
try:
from StringIO import StringIO
import cPickle as pickle
import urllib2 as urllib
from urllib2 import HTTPError, URLError
except ImportError:
from io import StringIO
import pickle
import urllib.request
import urllib.error
import urllib.parse
from urllib.error import HTTPError, URLError
try:
# Python 2 built-in
execfile
except NameError:
def execfile(filename, global_vars=None, local_vars=None):
with open(filename, encoding='utf-8') as f:
code = compile(f.read(), filename, 'exec')
exec(code, global_vars, local_vars)
try:
basestring
except NameError:
basestring = str
import token
import tokenize
import numpy as np
try:
# make sure that the Agg backend is set before importing any
# matplotlib
import matplotlib
matplotlib.use('Agg')
except ImportError:
# this script can be imported by nosetest to find tests to run: we should not
# impose the matplotlib requirement in that case.
pass
from sklearn.externals import joblib
###############################################################################
# A tee object to redict streams to multiple outputs
class Tee(object):
def __init__(self, file1, file2):
self.file1 = file1
self.file2 = file2
def write(self, data):
self.file1.write(data)
self.file2.write(data)
def flush(self):
self.file1.flush()
self.file2.flush()
###############################################################################
# Documentation link resolver objects
def _get_data(url):
"""Helper function to get data over http or from a local file"""
if url.startswith('http://'):
# Try Python 2, use Python 3 on exception
try:
resp = urllib.urlopen(url)
encoding = resp.headers.dict.get('content-encoding', 'plain')
except AttributeError:
resp = urllib.request.urlopen(url)
encoding = resp.headers.get('content-encoding', 'plain')
data = resp.read()
if encoding == 'plain':
pass
elif encoding == 'gzip':
data = StringIO(data)
data = gzip.GzipFile(fileobj=data).read()
else:
raise RuntimeError('unknown encoding')
else:
with open(url, 'r') as fid:
data = fid.read()
fid.close()
return data
mem = joblib.Memory(cachedir='_build')
get_data = mem.cache(_get_data)
def parse_sphinx_searchindex(searchindex):
"""Parse a Sphinx search index
Parameters
----------
searchindex : str
The Sphinx search index (contents of searchindex.js)
Returns
-------
filenames : list of str
The file names parsed from the search index.
objects : dict
The objects parsed from the search index.
"""
def _select_block(str_in, start_tag, end_tag):
"""Select first block delimited by start_tag and end_tag"""
start_pos = str_in.find(start_tag)
if start_pos < 0:
raise ValueError('start_tag not found')
depth = 0
for pos in range(start_pos, len(str_in)):
if str_in[pos] == start_tag:
depth += 1
elif str_in[pos] == end_tag:
depth -= 1
if depth == 0:
break
sel = str_in[start_pos + 1:pos]
return sel
def _parse_dict_recursive(dict_str):
"""Parse a dictionary from the search index"""
dict_out = dict()
pos_last = 0
pos = dict_str.find(':')
while pos >= 0:
key = dict_str[pos_last:pos]
if dict_str[pos + 1] == '[':
# value is a list
pos_tmp = dict_str.find(']', pos + 1)
if pos_tmp < 0:
raise RuntimeError('error when parsing dict')
value = dict_str[pos + 2: pos_tmp].split(',')
# try to convert elements to int
for i in range(len(value)):
try:
value[i] = int(value[i])
except ValueError:
pass
elif dict_str[pos + 1] == '{':
# value is another dictionary
subdict_str = _select_block(dict_str[pos:], '{', '}')
value = _parse_dict_recursive(subdict_str)
pos_tmp = pos + len(subdict_str)
else:
raise ValueError('error when parsing dict: unknown elem')
key = key.strip('"')
if len(key) > 0:
dict_out[key] = value
pos_last = dict_str.find(',', pos_tmp)
if pos_last < 0:
break
pos_last += 1
pos = dict_str.find(':', pos_last)
return dict_out
# Make sure searchindex uses UTF-8 encoding
if hasattr(searchindex, 'decode'):
searchindex = searchindex.decode('UTF-8')
# parse objects
query = 'objects:'
pos = searchindex.find(query)
if pos < 0:
raise ValueError('"objects:" not found in search index')
sel = _select_block(searchindex[pos:], '{', '}')
objects = _parse_dict_recursive(sel)
# parse filenames
query = 'filenames:'
pos = searchindex.find(query)
if pos < 0:
raise ValueError('"filenames:" not found in search index')
filenames = searchindex[pos + len(query) + 1:]
filenames = filenames[:filenames.find(']')]
filenames = [f.strip('"') for f in filenames.split(',')]
return filenames, objects
class SphinxDocLinkResolver(object):
""" Resolve documentation links using searchindex.js generated by Sphinx
Parameters
----------
doc_url : str
The base URL of the project website.
searchindex : str
Filename of searchindex, relative to doc_url.
extra_modules_test : list of str
List of extra module names to test.
relative : bool
Return relative links (only useful for links to documentation of this
package).
"""
def __init__(self, doc_url, searchindex='searchindex.js',
extra_modules_test=None, relative=False):
self.doc_url = doc_url
self.relative = relative
self._link_cache = {}
self.extra_modules_test = extra_modules_test
self._page_cache = {}
if doc_url.startswith('http://'):
if relative:
raise ValueError('Relative links are only supported for local '
'URLs (doc_url cannot start with "http://)"')
searchindex_url = doc_url + '/' + searchindex
else:
searchindex_url = os.path.join(doc_url, searchindex)
# detect if we are using relative links on a Windows system
if os.name.lower() == 'nt' and not doc_url.startswith('http://'):
if not relative:
raise ValueError('You have to use relative=True for the local'
' package on a Windows system.')
self._is_windows = True
else:
self._is_windows = False
# download and initialize the search index
sindex = get_data(searchindex_url)
filenames, objects = parse_sphinx_searchindex(sindex)
self._searchindex = dict(filenames=filenames, objects=objects)
def _get_link(self, cobj):
"""Get a valid link, False if not found"""
fname_idx = None
full_name = cobj['module_short'] + '.' + cobj['name']
if full_name in self._searchindex['objects']:
value = self._searchindex['objects'][full_name]
if isinstance(value, dict):
value = value[next(iter(value.keys()))]
fname_idx = value[0]
elif cobj['module_short'] in self._searchindex['objects']:
value = self._searchindex['objects'][cobj['module_short']]
if cobj['name'] in value.keys():
fname_idx = value[cobj['name']][0]
if fname_idx is not None:
fname = self._searchindex['filenames'][fname_idx] + '.html'
if self._is_windows:
fname = fname.replace('/', '\\')
link = os.path.join(self.doc_url, fname)
else:
link = posixpath.join(self.doc_url, fname)
if hasattr(link, 'decode'):
link = link.decode('utf-8', 'replace')
if link in self._page_cache:
html = self._page_cache[link]
else:
html = get_data(link)
self._page_cache[link] = html
# test if cobj appears in page
comb_names = [cobj['module_short'] + '.' + cobj['name']]
if self.extra_modules_test is not None:
for mod in self.extra_modules_test:
comb_names.append(mod + '.' + cobj['name'])
url = False
if hasattr(html, 'decode'):
# Decode bytes under Python 3
html = html.decode('utf-8', 'replace')
for comb_name in comb_names:
if hasattr(comb_name, 'decode'):
# Decode bytes under Python 3
comb_name = comb_name.decode('utf-8', 'replace')
if comb_name in html:
url = link + u'#' + comb_name
link = url
else:
link = False
return link
def resolve(self, cobj, this_url):
"""Resolve the link to the documentation, returns None if not found
Parameters
----------
cobj : dict
Dict with information about the "code object" for which we are
resolving a link.
cobi['name'] : function or class name (str)
cobj['module_short'] : shortened module name (str)
cobj['module'] : module name (str)
this_url: str
URL of the current page. Needed to construct relative URLs
(only used if relative=True in constructor).
Returns
-------
link : str | None
The link (URL) to the documentation.
"""
full_name = cobj['module_short'] + '.' + cobj['name']
link = self._link_cache.get(full_name, None)
if link is None:
# we don't have it cached
link = self._get_link(cobj)
# cache it for the future
self._link_cache[full_name] = link
if link is False or link is None:
# failed to resolve
return None
if self.relative:
link = os.path.relpath(link, start=this_url)
if self._is_windows:
# replace '\' with '/' so it on the web
link = link.replace('\\', '/')
# for some reason, the relative link goes one directory too high up
link = link[3:]
return link
###############################################################################
rst_template = """
.. _example_%(short_fname)s:
%(docstring)s
**Python source code:** :download:`%(fname)s <%(fname)s>`
.. literalinclude:: %(fname)s
:lines: %(end_row)s-
"""
plot_rst_template = """
.. _example_%(short_fname)s:
%(docstring)s
%(image_list)s
%(stdout)s
**Python source code:** :download:`%(fname)s <%(fname)s>`
.. literalinclude:: %(fname)s
:lines: %(end_row)s-
**Total running time of the example:** %(time_elapsed) .2f seconds
(%(time_m) .0f minutes %(time_s) .2f seconds)
"""
# The following strings are used when we have several pictures: we use
# an html div tag that our CSS uses to turn the lists into horizontal
# lists.
HLIST_HEADER = """
.. rst-class:: horizontal
"""
HLIST_IMAGE_TEMPLATE = """
*
.. image:: images/%s
:scale: 47
"""
SINGLE_IMAGE = """
.. image:: images/%s
:align: center
"""
# The following dictionary contains the information used to create the
# thumbnails for the front page of the scikit-learn home page.
# key: first image in set
# values: (number of plot in set, height of thumbnail)
carousel_thumbs = {'plot_classifier_comparison_001.png': (1, 600),
'plot_outlier_detection_001.png': (3, 372),
'plot_gp_regression_001.png': (2, 250),
'plot_adaboost_twoclass_001.png': (1, 372),
'plot_compare_methods_001.png': (1, 349)}
def extract_docstring(filename, ignore_heading=False):
""" Extract a module-level docstring, if any
"""
if six.PY2:
lines = open(filename).readlines()
else:
lines = open(filename, encoding='utf-8').readlines()
start_row = 0
if lines[0].startswith('#!'):
lines.pop(0)
start_row = 1
docstring = ''
first_par = ''
line_iterator = iter(lines)
tokens = tokenize.generate_tokens(lambda: next(line_iterator))
for tok_type, tok_content, _, (erow, _), _ in tokens:
tok_type = token.tok_name[tok_type]
if tok_type in ('NEWLINE', 'COMMENT', 'NL', 'INDENT', 'DEDENT'):
continue
elif tok_type == 'STRING':
docstring = eval(tok_content)
# If the docstring is formatted with several paragraphs, extract
# the first one:
paragraphs = '\n'.join(
line.rstrip() for line
in docstring.split('\n')).split('\n\n')
if paragraphs:
if ignore_heading:
if len(paragraphs) > 1:
first_par = re.sub('\n', ' ', paragraphs[1])
first_par = ((first_par[:95] + '...')
if len(first_par) > 95 else first_par)
else:
raise ValueError("Docstring not found by gallery.\n"
"Please check the layout of your"
" example file:\n {}\n and make sure"
" it's correct".format(filename))
else:
first_par = paragraphs[0]
break
return docstring, first_par, erow + 1 + start_row
def generate_example_rst(app):
""" Generate the list of examples, as well as the contents of
examples.
"""
root_dir = os.path.join(app.builder.srcdir, 'auto_examples')
example_dir = os.path.abspath(os.path.join(app.builder.srcdir, '..',
'examples'))
generated_dir = os.path.abspath(os.path.join(app.builder.srcdir,
'modules', 'generated'))
try:
plot_gallery = eval(app.builder.config.plot_gallery)
except TypeError:
plot_gallery = bool(app.builder.config.plot_gallery)
if not os.path.exists(example_dir):
os.makedirs(example_dir)
if not os.path.exists(root_dir):
os.makedirs(root_dir)
if not os.path.exists(generated_dir):
os.makedirs(generated_dir)
# we create an index.rst with all examples
fhindex = open(os.path.join(root_dir, 'index.rst'), 'w')
# Note: The sidebar button has been removed from the examples page for now
# due to how it messes up the layout. Will be fixed at a later point
fhindex.write("""\
.. raw:: html
<style type="text/css">
div#sidebarbutton {
/* hide the sidebar collapser, while ensuring vertical arrangement */
display: none;
}
</style>
.. _examples-index:
Examples
========
""")
# Here we don't use an os.walk, but we recurse only twice: flat is
# better than nested.
seen_backrefs = set()
generate_dir_rst('.', fhindex, example_dir, root_dir, plot_gallery, seen_backrefs)
for directory in sorted(os.listdir(example_dir)):
if os.path.isdir(os.path.join(example_dir, directory)):
generate_dir_rst(directory, fhindex, example_dir, root_dir, plot_gallery, seen_backrefs)
fhindex.flush()
def extract_line_count(filename, target_dir):
# Extract the line count of a file
example_file = os.path.join(target_dir, filename)
if six.PY2:
lines = open(example_file).readlines()
else:
lines = open(example_file, encoding='utf-8').readlines()
start_row = 0
if lines and lines[0].startswith('#!'):
lines.pop(0)
start_row = 1
line_iterator = iter(lines)
tokens = tokenize.generate_tokens(lambda: next(line_iterator))
check_docstring = True
erow_docstring = 0
for tok_type, _, _, (erow, _), _ in tokens:
tok_type = token.tok_name[tok_type]
if tok_type in ('NEWLINE', 'COMMENT', 'NL', 'INDENT', 'DEDENT'):
continue
elif (tok_type == 'STRING') and check_docstring:
erow_docstring = erow
check_docstring = False
return erow_docstring+1+start_row, erow+1+start_row
def line_count_sort(file_list, target_dir):
# Sort the list of examples by line-count
new_list = [x for x in file_list if x.endswith('.py')]
unsorted = np.zeros(shape=(len(new_list), 2))
unsorted = unsorted.astype(np.object)
for count, exmpl in enumerate(new_list):
docstr_lines, total_lines = extract_line_count(exmpl, target_dir)
unsorted[count][1] = total_lines - docstr_lines
unsorted[count][0] = exmpl
index = np.lexsort((unsorted[:, 0].astype(np.str),
unsorted[:, 1].astype(np.float)))
if not len(unsorted):
return []
return np.array(unsorted[index][:, 0]).tolist()
def _thumbnail_div(subdir, full_dir, fname, snippet, is_backref=False):
"""Generates RST to place a thumbnail in a gallery"""
thumb = os.path.join(full_dir, 'images', 'thumb', fname[:-3] + '.png')
link_name = os.path.join(full_dir, fname).replace(os.path.sep, '_')
ref_name = os.path.join(subdir, fname).replace(os.path.sep, '_')
if ref_name.startswith('._'):
ref_name = ref_name[2:]
out = []
out.append("""
.. raw:: html
<div class="thumbnailContainer" tooltip="{}">
""".format(snippet))
out.append('.. only:: html\n\n')
out.append(' .. figure:: %s\n' % thumb)
if link_name.startswith('._'):
link_name = link_name[2:]
if full_dir != '.':
out.append(' :target: ./%s/%s.html\n\n' % (full_dir, fname[:-3]))
else:
out.append(' :target: ./%s.html\n\n' % link_name[:-3])
out.append(""" :ref:`example_%s`
.. raw:: html
</div>
""" % (ref_name))
if is_backref:
out.append('.. only:: not html\n\n * :ref:`example_%s`' % ref_name)
return ''.join(out)
def generate_dir_rst(directory, fhindex, example_dir, root_dir, plot_gallery, seen_backrefs):
""" Generate the rst file for an example directory.
"""
if not directory == '.':
target_dir = os.path.join(root_dir, directory)
src_dir = os.path.join(example_dir, directory)
else:
target_dir = root_dir
src_dir = example_dir
if not os.path.exists(os.path.join(src_dir, 'README.txt')):
raise ValueError('Example directory %s does not have a README.txt' %
src_dir)
fhindex.write("""
%s
""" % open(os.path.join(src_dir, 'README.txt')).read())
if not os.path.exists(target_dir):
os.makedirs(target_dir)
sorted_listdir = line_count_sort(os.listdir(src_dir),
src_dir)
if not os.path.exists(os.path.join(directory, 'images', 'thumb')):
os.makedirs(os.path.join(directory, 'images', 'thumb'))
for fname in sorted_listdir:
if fname.endswith('py'):
backrefs = generate_file_rst(fname, target_dir, src_dir, root_dir, plot_gallery)
new_fname = os.path.join(src_dir, fname)
_, snippet, _ = extract_docstring(new_fname, True)
fhindex.write(_thumbnail_div(directory, directory, fname, snippet))
fhindex.write("""
.. toctree::
:hidden:
%s/%s
""" % (directory, fname[:-3]))
for backref in backrefs:
include_path = os.path.join(root_dir, '../modules/generated/%s.examples' % backref)
seen = backref in seen_backrefs
with open(include_path, 'a' if seen else 'w') as ex_file:
if not seen:
# heading
print(file=ex_file)
print('Examples using ``%s``' % backref, file=ex_file)
print('-----------------%s--' % ('-' * len(backref)),
file=ex_file)
print(file=ex_file)
rel_dir = os.path.join('../../auto_examples', directory)
ex_file.write(_thumbnail_div(directory, rel_dir, fname, snippet, is_backref=True))
seen_backrefs.add(backref)
fhindex.write("""
.. raw:: html
<div class="clearer"></div>
""") # clear at the end of the section
# modules for which we embed links into example code
DOCMODULES = ['sklearn', 'matplotlib', 'numpy', 'scipy']
def make_thumbnail(in_fname, out_fname, width, height):
"""Make a thumbnail with the same aspect ratio centered in an
image with a given width and height
"""
# local import to avoid testing dependency on PIL:
try:
from PIL import Image
except ImportError:
import Image
img = Image.open(in_fname)
width_in, height_in = img.size
scale_w = width / float(width_in)
scale_h = height / float(height_in)
if height_in * scale_w <= height:
scale = scale_w
else:
scale = scale_h
width_sc = int(round(scale * width_in))
height_sc = int(round(scale * height_in))
# resize the image
img.thumbnail((width_sc, height_sc), Image.ANTIALIAS)
# insert centered
thumb = Image.new('RGB', (width, height), (255, 255, 255))
pos_insert = ((width - width_sc) // 2, (height - height_sc) // 2)
thumb.paste(img, pos_insert)
thumb.save(out_fname)
# Use optipng to perform lossless compression on the resized image if
# software is installed
if os.environ.get('SKLEARN_DOC_OPTIPNG', False):
try:
subprocess.call(["optipng", "-quiet", "-o", "9", out_fname])
except Exception:
warnings.warn('Install optipng to reduce the size of the generated images')
def get_short_module_name(module_name, obj_name):
""" Get the shortest possible module name """
parts = module_name.split('.')
short_name = module_name
for i in range(len(parts) - 1, 0, -1):
short_name = '.'.join(parts[:i])
try:
exec('from %s import %s' % (short_name, obj_name))
except ImportError:
# get the last working module name
short_name = '.'.join(parts[:(i + 1)])
break
return short_name
class NameFinder(ast.NodeVisitor):
"""Finds the longest form of variable names and their imports in code
Only retains names from imported modules.
"""
def __init__(self):
super(NameFinder, self).__init__()
self.imported_names = {}
self.accessed_names = set()
def visit_Import(self, node, prefix=''):
for alias in node.names:
local_name = alias.asname or alias.name
self.imported_names[local_name] = prefix + alias.name
def visit_ImportFrom(self, node):
self.visit_Import(node, node.module + '.')
def visit_Name(self, node):
self.accessed_names.add(node.id)
def visit_Attribute(self, node):
attrs = []
while isinstance(node, ast.Attribute):
attrs.append(node.attr)
node = node.value
if isinstance(node, ast.Name):
# This is a.b, not e.g. a().b
attrs.append(node.id)
self.accessed_names.add('.'.join(reversed(attrs)))
else:
# need to get a in a().b
self.visit(node)
def get_mapping(self):
for name in self.accessed_names:
local_name = name.split('.', 1)[0]
remainder = name[len(local_name):]
if local_name in self.imported_names:
# Join import path to relative path
full_name = self.imported_names[local_name] + remainder
yield name, full_name
def identify_names(code):
"""Builds a codeobj summary by identifying and resovles used names
>>> code = '''
... from a.b import c
... import d as e
... print(c)
... e.HelloWorld().f.g
... '''
>>> for name, o in sorted(identify_names(code).items()):
... print(name, o['name'], o['module'], o['module_short'])
c c a.b a.b
e.HelloWorld HelloWorld d d
"""
finder = NameFinder()
finder.visit(ast.parse(code))
example_code_obj = {}
for name, full_name in finder.get_mapping():
# name is as written in file (e.g. np.asarray)
# full_name includes resolved import path (e.g. numpy.asarray)
module, attribute = full_name.rsplit('.', 1)
# get shortened module name
module_short = get_short_module_name(module, attribute)
cobj = {'name': attribute, 'module': module,
'module_short': module_short}
example_code_obj[name] = cobj
return example_code_obj
def generate_file_rst(fname, target_dir, src_dir, root_dir, plot_gallery):
""" Generate the rst file for a given example.
Returns the set of sklearn functions/classes imported in the example.
"""
base_image_name = os.path.splitext(fname)[0]
image_fname = '%s_%%03d.png' % base_image_name
this_template = rst_template
last_dir = os.path.split(src_dir)[-1]
# to avoid leading . in file names, and wrong names in links
if last_dir == '.' or last_dir == 'examples':
last_dir = ''
else:
last_dir += '_'
short_fname = last_dir + fname
src_file = os.path.join(src_dir, fname)
example_file = os.path.join(target_dir, fname)
shutil.copyfile(src_file, example_file)
# The following is a list containing all the figure names
figure_list = []
image_dir = os.path.join(target_dir, 'images')
thumb_dir = os.path.join(image_dir, 'thumb')
if not os.path.exists(image_dir):
os.makedirs(image_dir)
if not os.path.exists(thumb_dir):
os.makedirs(thumb_dir)
image_path = os.path.join(image_dir, image_fname)
stdout_path = os.path.join(image_dir,
'stdout_%s.txt' % base_image_name)
time_path = os.path.join(image_dir,
'time_%s.txt' % base_image_name)
thumb_file = os.path.join(thumb_dir, base_image_name + '.png')
time_elapsed = 0
if plot_gallery and fname.startswith('plot'):
# generate the plot as png image if file name
# starts with plot and if it is more recent than an
# existing image.
first_image_file = image_path % 1
if os.path.exists(stdout_path):
stdout = open(stdout_path).read()
else:
stdout = ''
if os.path.exists(time_path):
time_elapsed = float(open(time_path).read())
if not os.path.exists(first_image_file) or \
os.stat(first_image_file).st_mtime <= os.stat(src_file).st_mtime:
# We need to execute the code
print('plotting %s' % fname)
t0 = time()
import matplotlib.pyplot as plt
plt.close('all')
cwd = os.getcwd()
try:
# First CD in the original example dir, so that any file
# created by the example get created in this directory
orig_stdout = sys.stdout
os.chdir(os.path.dirname(src_file))
my_buffer = StringIO()
my_stdout = Tee(sys.stdout, my_buffer)
sys.stdout = my_stdout
my_globals = {'pl': plt}
execfile(os.path.basename(src_file), my_globals)
time_elapsed = time() - t0
sys.stdout = orig_stdout
my_stdout = my_buffer.getvalue()
if '__doc__' in my_globals:
# The __doc__ is often printed in the example, we
# don't with to echo it
my_stdout = my_stdout.replace(
my_globals['__doc__'],
'')
my_stdout = my_stdout.strip().expandtabs()
if my_stdout:
stdout = '**Script output**::\n\n %s\n\n' % (
'\n '.join(my_stdout.split('\n')))
open(stdout_path, 'w').write(stdout)
open(time_path, 'w').write('%f' % time_elapsed)
os.chdir(cwd)
# In order to save every figure we have two solutions :
# * iterate from 1 to infinity and call plt.fignum_exists(n)
# (this requires the figures to be numbered
# incrementally: 1, 2, 3 and not 1, 2, 5)
# * iterate over [fig_mngr.num for fig_mngr in
# matplotlib._pylab_helpers.Gcf.get_all_fig_managers()]
fig_managers = matplotlib._pylab_helpers.Gcf.get_all_fig_managers()
for fig_mngr in fig_managers:
# Set the fig_num figure as the current figure as we can't
# save a figure that's not the current figure.
fig = plt.figure(fig_mngr.num)
kwargs = {}
to_rgba = matplotlib.colors.colorConverter.to_rgba
for attr in ['facecolor', 'edgecolor']:
fig_attr = getattr(fig, 'get_' + attr)()
default_attr = matplotlib.rcParams['figure.' + attr]
if to_rgba(fig_attr) != to_rgba(default_attr):
kwargs[attr] = fig_attr
fig.savefig(image_path % fig_mngr.num, **kwargs)
figure_list.append(image_fname % fig_mngr.num)
except:
print(80 * '_')
print('%s is not compiling:' % fname)
traceback.print_exc()
print(80 * '_')
finally:
os.chdir(cwd)
sys.stdout = orig_stdout
print(" - time elapsed : %.2g sec" % time_elapsed)
else:
figure_list = [f[len(image_dir):]
for f in glob.glob(image_path.replace("%03d",
'[0-9][0-9][0-9]'))]
figure_list.sort()
# generate thumb file
this_template = plot_rst_template
car_thumb_path = os.path.join(os.path.split(root_dir)[0], '_build/html/stable/_images/')
# Note: normaly, make_thumbnail is used to write to the path contained in `thumb_file`
# which is within `auto_examples/../images/thumbs` depending on the example.
# Because the carousel has different dimensions than those of the examples gallery,
# I did not simply reuse them all as some contained whitespace due to their default gallery
# thumbnail size. Below, for a few cases, seperate thumbnails are created (the originals can't
# just be overwritten with the carousel dimensions as it messes up the examples gallery layout).
# The special carousel thumbnails are written directly to _build/html/stable/_images/,
# as for some reason unknown to me, Sphinx refuses to copy my 'extra' thumbnails from the
# auto examples gallery to the _build folder. This works fine as is, but it would be cleaner to
# have it happen with the rest. Ideally the should be written to 'thumb_file' as well, and then
# copied to the _images folder during the `Copying Downloadable Files` step like the rest.
if not os.path.exists(car_thumb_path):
os.makedirs(car_thumb_path)
if os.path.exists(first_image_file):
# We generate extra special thumbnails for the carousel
carousel_tfile = os.path.join(car_thumb_path, base_image_name + '_carousel.png')
first_img = image_fname % 1
if first_img in carousel_thumbs:
make_thumbnail((image_path % carousel_thumbs[first_img][0]),
carousel_tfile, carousel_thumbs[first_img][1], 190)
make_thumbnail(first_image_file, thumb_file, 400, 280)
if not os.path.exists(thumb_file):
# create something to replace the thumbnail
make_thumbnail('images/no_image.png', thumb_file, 200, 140)
docstring, short_desc, end_row = extract_docstring(example_file)
# Depending on whether we have one or more figures, we're using a
# horizontal list or a single rst call to 'image'.
if len(figure_list) == 1:
figure_name = figure_list[0]
image_list = SINGLE_IMAGE % figure_name.lstrip('/')
else:
image_list = HLIST_HEADER
for figure_name in figure_list:
image_list += HLIST_IMAGE_TEMPLATE % figure_name.lstrip('/')
time_m, time_s = divmod(time_elapsed, 60)
f = open(os.path.join(target_dir, base_image_name + '.rst'), 'w')
f.write(this_template % locals())
f.flush()
# save variables so we can later add links to the documentation
if six.PY2:
example_code_obj = identify_names(open(example_file).read())
else:
example_code_obj = \
identify_names(open(example_file, encoding='utf-8').read())
if example_code_obj:
codeobj_fname = example_file[:-3] + '_codeobj.pickle'
with open(codeobj_fname, 'wb') as fid:
pickle.dump(example_code_obj, fid, pickle.HIGHEST_PROTOCOL)
backrefs = set('{module_short}.{name}'.format(**entry)
for entry in example_code_obj.values()
if entry['module'].startswith('sklearn'))
return backrefs
def embed_code_links(app, exception):
"""Embed hyperlinks to documentation into example code"""
if exception is not None:
return
print('Embedding documentation hyperlinks in examples..')
if app.builder.name == 'latex':
# Don't embed hyperlinks when a latex builder is used.
return
# Add resolvers for the packages for which we want to show links
doc_resolvers = {}
doc_resolvers['sklearn'] = SphinxDocLinkResolver(app.builder.outdir,
relative=True)
resolver_urls = {
'matplotlib': 'http://matplotlib.org',
'numpy': 'http://docs.scipy.org/doc/numpy-1.6.0',
'scipy': 'http://docs.scipy.org/doc/scipy-0.11.0/reference',
}
for this_module, url in resolver_urls.items():
try:
doc_resolvers[this_module] = SphinxDocLinkResolver(url)
except HTTPError as e:
print("The following HTTP Error has occurred:\n")
print(e.code)
except URLError as e:
print("\n...\n"
"Warning: Embedding the documentation hyperlinks requires "
"internet access.\nPlease check your network connection.\n"
"Unable to continue embedding `{0}` links due to a URL "
"Error:\n".format(this_module))
print(e.args)
example_dir = os.path.join(app.builder.srcdir, 'auto_examples')
html_example_dir = os.path.abspath(os.path.join(app.builder.outdir,
'auto_examples'))
# patterns for replacement
link_pattern = '<a href="%s">%s</a>'
orig_pattern = '<span class="n">%s</span>'
period = '<span class="o">.</span>'
for dirpath, _, filenames in os.walk(html_example_dir):
for fname in filenames:
print('\tprocessing: %s' % fname)
full_fname = os.path.join(html_example_dir, dirpath, fname)
subpath = dirpath[len(html_example_dir) + 1:]
pickle_fname = os.path.join(example_dir, subpath,
fname[:-5] + '_codeobj.pickle')
if os.path.exists(pickle_fname):
# we have a pickle file with the objects to embed links for
with open(pickle_fname, 'rb') as fid:
example_code_obj = pickle.load(fid)
fid.close()
str_repl = {}
# generate replacement strings with the links
for name, cobj in example_code_obj.items():
this_module = cobj['module'].split('.')[0]
if this_module not in doc_resolvers:
continue
try:
link = doc_resolvers[this_module].resolve(cobj,
full_fname)
except (HTTPError, URLError) as e:
print("The following error has occurred:\n")
print(repr(e))
continue
if link is not None:
parts = name.split('.')
name_html = period.join(orig_pattern % part
for part in parts)
str_repl[name_html] = link_pattern % (link, name_html)
# do the replacement in the html file
# ensure greediness
names = sorted(str_repl, key=len, reverse=True)
expr = re.compile(r'(?<!\.)\b' + # don't follow . or word
'|'.join(re.escape(name)
for name in names))
def substitute_link(match):
return str_repl[match.group()]
if len(str_repl) > 0:
with open(full_fname, 'rb') as fid:
lines_in = fid.readlines()
with open(full_fname, 'wb') as fid:
for line in lines_in:
line = line.decode('utf-8')
line = expr.sub(substitute_link, line)
fid.write(line.encode('utf-8'))
print('[done]')
def setup(app):
app.connect('builder-inited', generate_example_rst)
app.add_config_value('plot_gallery', True, 'html')
# embed links after build is finished
app.connect('build-finished', embed_code_links)
# Sphinx hack: sphinx copies generated images to the build directory
# each time the docs are made. If the desired image name already
# exists, it appends a digit to prevent overwrites. The problem is,
# the directory is never cleared. This means that each time you build
# the docs, the number of images in the directory grows.
#
# This question has been asked on the sphinx development list, but there
# was no response: http://osdir.com/ml/sphinx-dev/2011-02/msg00123.html
#
# The following is a hack that prevents this behavior by clearing the
# image build directory each time the docs are built. If sphinx
# changes their layout between versions, this will not work (though
# it should probably not cause a crash). Tested successfully
# on Sphinx 1.0.7
build_image_dir = '_build/html/_images'
if os.path.exists(build_image_dir):
filelist = os.listdir(build_image_dir)
for filename in filelist:
if filename.endswith('png'):
os.remove(os.path.join(build_image_dir, filename))
def setup_module():
# HACK: Stop nosetests running setup() above
pass
|
NelisVerhoef/scikit-learn
|
doc/sphinxext/gen_rst.py
|
Python
|
bsd-3-clause
| 40,198 | 0.000697 |
# -*- coding: utf-8 -*-
'''
Interface with a Junos device via proxy-minion.
'''
# Import python libs
from __future__ import print_function
from __future__ import absolute_import
import logging
# Import 3rd-party libs
import jnpr.junos
import jnpr.junos.utils
import jnpr.junos.utils.config
import json
HAS_JUNOS = True
__proxyenabled__ = ['junos']
thisproxy = {}
log = logging.getLogger(__name__)
def init(opts):
'''
Open the connection to the Junos device, login, and bind to the
Resource class
'''
log.debug('Opening connection to junos')
thisproxy['conn'] = jnpr.junos.Device(user=opts['proxy']['username'],
host=opts['proxy']['host'],
password=opts['proxy']['passwd'])
thisproxy['conn'].open()
thisproxy['conn'].bind(cu=jnpr.junos.utils.config.Config)
def conn():
return thisproxy['conn']
def facts():
return thisproxy['conn'].facts
def refresh():
return thisproxy['conn'].facts_refresh()
def proxytype():
'''
Returns the name of this proxy
'''
return 'junos'
def id(opts):
'''
Returns a unique ID for this proxy minion
'''
return thisproxy['conn'].facts['hostname']
def ping():
'''
Ping? Pong!
'''
return thisproxy['conn'].connected
def shutdown(opts):
'''
This is called when the proxy-minion is exiting to make sure the
connection to the device is closed cleanly.
'''
log.debug('Proxy module {0} shutting down!!'.format(opts['id']))
try:
thisproxy['conn'].close()
except Exception:
pass
def rpc():
return json.dumps(thisproxy['conn'].rpc.get_software_information())
|
smallyear/linuxLearn
|
salt/salt/proxy/junos.py
|
Python
|
apache-2.0
| 1,727 | 0.001158 |
from PyQt5.QtCore import pyqtSlot, QThread, pyqtSignal
import os
from PyQt5.QtWidgets import QFileDialog, QProgressDialog, QMessageBox
from PyQt5.QtCore import pyqtSlot, QObject
from books.soldiers import processData
import route_gui
from lxml import etree
import multiprocessing
import math
class XmlImport(QObject):
threadUpdateSignal = pyqtSignal(int, int, name="progressUpdate")
threadExceptionSignal = pyqtSignal(object, name="exceptionInProcess")
threadResultsSignal = pyqtSignal(dict, name="results")
finishedSignal = pyqtSignal(dict, str, name="processFinished")
def __init__(self, parent):
super(XmlImport, self).__init__(parent)
self.parent = parent
self.processCount = 0
self.result = {}
self.thread = QThread(parent = self.parent)
self.threadUpdateSignal.connect(self._updateProgressBarInMainThread)
self.threadExceptionSignal.connect(self._loadingFailed)
self.threadResultsSignal.connect(self._processFinished)
self.filepath = ""
def importOne(self, xmlEntry):
if self.processor is not None:
result = self.processor.extractOne(xmlEntry)
return result
else:
return None
@pyqtSlot()
def openXMLFile(self):
filename = QFileDialog.getOpenFileName(self.parent, "Open xml-file containing the data to be analyzed.",
".", "Person data files (*.xml);;All files (*)")
if filename[0] != "":
self.filepath = filename[0]
self.parent.setWindowTitle("Kaira " + filename[0])
self._analyzeOpenedXml(filename)
def _analyzeOpenedXml(self, file):
self.progressDialog = QProgressDialog(self.parent)
self.progressDialog.setCancelButton(None)
self.progressDialog.setLabelText("Extracting provided datafile...")
self.progressDialog.open()
self.progressDialog.setValue(0)
self.file = file
self.thread.run = self._runProcess
self.thread.start()
def _runProcess(self):
try:
xmlDataDocument = self._getXMLroot(self.file[0])
#TODO: Lue xml:n metadata
try:
#TODO: Moniprosarituki?
self.processor = route_gui.Router.get_processdata_class(xmlDataDocument.attrib["bookseries"])(self._processUpdateCallback)
result = self.processor.startExtractionProcess(xmlDataDocument, self.file[0])
self.threadResultsSignal.emit(result)
except KeyError:
raise MetadataException()
except Exception as e:
if "DEV" in os.environ and os.environ["DEV"]:
raise e
else:
print(e)
self.threadExceptionSignal.emit(e)
@pyqtSlot(int, int)
def _updateProgressBarInMainThread(self, i, max):
self.progressDialog.setRange(0, max)
self.progressDialog.setValue(i)
@pyqtSlot(object)
def _loadingFailed(self, e):
self.progressDialog.cancel()
import pymongo
errMessage = "Error in data-file. Extraction failed. Is the xml valid and in utf-8 format? More info: "
if isinstance(e, pymongo.errors.ServerSelectionTimeoutError):
errMessage = "Couldn't connect to database. Try going to '/mongodb/data/db' in application directory and deleting 'mongod.lock' file and restart application. More info: "
msgbox = QMessageBox()
msgbox.information(self.parent, "Extraction failed", errMessage + str(e))
msgbox.show()
@pyqtSlot(dict)
def _processFinished(self, result):
self.result = result
self.finishedSignal.emit(self.result, self.filepath)
def _processUpdateCallback(self, i, max):
self.threadUpdateSignal.emit(i, max)
def _getXMLroot(self, filepath):
#read the data in XML-format to be processed
parser = etree.XMLParser(encoding="utf-8")
tree = etree.parse(filepath, parser=parser) #ET.parse(filepath)
return tree.getroot()
class MetadataException(Exception):
def __init__(self):
self.msg = "ERROR: The document doesn't contain bookseries attribute in the beginning of the file. Couldn't import. Try " \
"to generate new xml-file from the source ocr-text or add the missing attribute to the file manually."
def __str__(self):
return repr(self.msg)
|
Learning-from-our-past/Kaira
|
qtgui/xmlImport.py
|
Python
|
gpl-2.0
| 4,469 | 0.005147 |
import datetime
import json
class Experience:
def __init__(self, date, event):
self._date = date
self._event = event
@classmethod
def reconstruct_from_db_data_event(cls, date, event):
event = json.loads(event)
date = datetime.datetime.strptime(date, "%Y-%m-%d %H:%M:%S.%f")
exp = Experience(date, event)
return exp
def time_from_this_event(self, event):
return self._date - event._date
|
semiirs/ai_project
|
common/experience.py
|
Python
|
gpl-3.0
| 462 | 0.002165 |
# -*- coding: utf-8 -*-
from operator import attrgetter
from pyangbind.lib.yangtypes import RestrictedPrecisionDecimalType
from pyangbind.lib.yangtypes import RestrictedClassType
from pyangbind.lib.yangtypes import TypedListType
from pyangbind.lib.yangtypes import YANGBool
from pyangbind.lib.yangtypes import YANGListType
from pyangbind.lib.yangtypes import YANGDynClass
from pyangbind.lib.yangtypes import ReferenceType
from pyangbind.lib.base import PybindBase
from collections import OrderedDict
from decimal import Decimal
from bitarray import bitarray
import six
# PY3 support of some PY2 keywords (needs improved)
if six.PY3:
import builtins as __builtin__
long = int
elif six.PY2:
import __builtin__
class yc_config_openconfig_macsec__macsec_mka_policies_policy_config(PybindBase):
"""
This class was auto-generated by the PythonClass plugin for PYANG
from YANG module openconfig-macsec - based on the path /macsec/mka/policies/policy/config. Each member element of
the container is represented as a class variable - with a specific
YANG type.
YANG Description: Configuration of the MKA policy
"""
__slots__ = ('_path_helper', '_extmethods', '__name','__key_server_priority','__macsec_cipher_suite','__confidentiality_offset','__delay_protection','__include_icv_indicator','__sak_rekey_interval','__sak_rekey_on_live_peer_loss','__use_updated_eth_header',)
_yang_name = 'config'
_yang_namespace = 'http://openconfig.net/yang/macsec'
_pybind_generated_by = 'container'
def __init__(self, *args, **kwargs):
self._path_helper = False
self._extmethods = False
self.__name = YANGDynClass(base=six.text_type, is_leaf=True, yang_name="name", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='string', is_config=True)
self.__key_server_priority = YANGDynClass(base=RestrictedClassType(base_type=int, restriction_dict={'range': ['0..255']}, int_size=8), default=RestrictedClassType(base_type=int, restriction_dict={'range': ['0..255']}, int_size=8)(16), is_leaf=True, yang_name="key-server-priority", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='uint8', is_config=True)
self.__macsec_cipher_suite = YANGDynClass(unique=True, base=TypedListType(allowed_type=RestrictedClassType(base_type=six.text_type, restriction_type="dict_key", restriction_arg={'GCM_AES_128': {}, 'GCM_AES_256': {}, 'GCM_AES_XPN_128': {}, 'GCM_AES_XPN_256': {}},)), is_leaf=False, yang_name="macsec-cipher-suite", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='macsec-types:macsec-cipher-suite', is_config=True)
self.__confidentiality_offset = YANGDynClass(base=RestrictedClassType(base_type=six.text_type, restriction_type="dict_key", restriction_arg={'0_BYTES': {}, '30_BYTES': {}, '50_BYTES': {}},), default=six.text_type("0_BYTES"), is_leaf=True, yang_name="confidentiality-offset", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='macsec-types:confidentiality-offset', is_config=True)
self.__delay_protection = YANGDynClass(base=YANGBool, default=YANGBool("false"), is_leaf=True, yang_name="delay-protection", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='boolean', is_config=True)
self.__include_icv_indicator = YANGDynClass(base=YANGBool, default=YANGBool("true"), is_leaf=True, yang_name="include-icv-indicator", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='boolean', is_config=True)
self.__sak_rekey_interval = YANGDynClass(base=RestrictedClassType(base_type=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), restriction_dict={'range': ['0', '30..65535']}), default=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32)(0), is_leaf=True, yang_name="sak-rekey-interval", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='uint32', is_config=True)
self.__sak_rekey_on_live_peer_loss = YANGDynClass(base=YANGBool, default=YANGBool("false"), is_leaf=True, yang_name="sak-rekey-on-live-peer-loss", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='boolean', is_config=True)
self.__use_updated_eth_header = YANGDynClass(base=YANGBool, default=YANGBool("false"), is_leaf=True, yang_name="use-updated-eth-header", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='boolean', 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 ['macsec', 'mka', 'policies', 'policy', 'config']
def _get_name(self):
"""
Getter method for name, mapped from YANG variable /macsec/mka/policies/policy/config/name (string)
YANG Description: Name of the MKA policy.
"""
return self.__name
def _set_name(self, v, load=False):
"""
Setter method for name, mapped from YANG variable /macsec/mka/policies/policy/config/name (string)
If this variable is read-only (config: false) in the
source YANG file, then _set_name is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_name() directly.
YANG Description: Name of the MKA policy.
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=six.text_type, is_leaf=True, yang_name="name", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='string', is_config=True)
except (TypeError, ValueError):
raise ValueError({
'error-string': """name must be of a type compatible with string""",
'defined-type': "string",
'generated-type': """YANGDynClass(base=six.text_type, is_leaf=True, yang_name="name", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='string', is_config=True)""",
})
self.__name = t
if hasattr(self, '_set'):
self._set()
def _unset_name(self):
self.__name = YANGDynClass(base=six.text_type, is_leaf=True, yang_name="name", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='string', is_config=True)
def _get_key_server_priority(self):
"""
Getter method for key_server_priority, mapped from YANG variable /macsec/mka/policies/policy/config/key_server_priority (uint8)
YANG Description: Specifies the key server priority used by the MACsec Key Agreement
(MKA) protocol to select the key server when MACsec is enabled using
static connectivity association key (CAK) security mode. The switch with
the lower priority-number is selected as the key server. If the
priority-number is identical on both sides of a point-to-point link, the
MKA protocol selects the device with the lower MAC address as the key
server
"""
return self.__key_server_priority
def _set_key_server_priority(self, v, load=False):
"""
Setter method for key_server_priority, mapped from YANG variable /macsec/mka/policies/policy/config/key_server_priority (uint8)
If this variable is read-only (config: false) in the
source YANG file, then _set_key_server_priority is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_key_server_priority() directly.
YANG Description: Specifies the key server priority used by the MACsec Key Agreement
(MKA) protocol to select the key server when MACsec is enabled using
static connectivity association key (CAK) security mode. The switch with
the lower priority-number is selected as the key server. If the
priority-number is identical on both sides of a point-to-point link, the
MKA protocol selects the device with the lower MAC address as the key
server
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=RestrictedClassType(base_type=int, restriction_dict={'range': ['0..255']}, int_size=8), default=RestrictedClassType(base_type=int, restriction_dict={'range': ['0..255']}, int_size=8)(16), is_leaf=True, yang_name="key-server-priority", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='uint8', is_config=True)
except (TypeError, ValueError):
raise ValueError({
'error-string': """key_server_priority must be of a type compatible with uint8""",
'defined-type': "uint8",
'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=int, restriction_dict={'range': ['0..255']}, int_size=8), default=RestrictedClassType(base_type=int, restriction_dict={'range': ['0..255']}, int_size=8)(16), is_leaf=True, yang_name="key-server-priority", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='uint8', is_config=True)""",
})
self.__key_server_priority = t
if hasattr(self, '_set'):
self._set()
def _unset_key_server_priority(self):
self.__key_server_priority = YANGDynClass(base=RestrictedClassType(base_type=int, restriction_dict={'range': ['0..255']}, int_size=8), default=RestrictedClassType(base_type=int, restriction_dict={'range': ['0..255']}, int_size=8)(16), is_leaf=True, yang_name="key-server-priority", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='uint8', is_config=True)
def _get_macsec_cipher_suite(self):
"""
Getter method for macsec_cipher_suite, mapped from YANG variable /macsec/mka/policies/policy/config/macsec_cipher_suite (macsec-types:macsec-cipher-suite)
YANG Description: Set Cipher suite(s) for SAK derivation
"""
return self.__macsec_cipher_suite
def _set_macsec_cipher_suite(self, v, load=False):
"""
Setter method for macsec_cipher_suite, mapped from YANG variable /macsec/mka/policies/policy/config/macsec_cipher_suite (macsec-types:macsec-cipher-suite)
If this variable is read-only (config: false) in the
source YANG file, then _set_macsec_cipher_suite is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_macsec_cipher_suite() directly.
YANG Description: Set Cipher suite(s) for SAK derivation
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,unique=True, base=TypedListType(allowed_type=RestrictedClassType(base_type=six.text_type, restriction_type="dict_key", restriction_arg={'GCM_AES_128': {}, 'GCM_AES_256': {}, 'GCM_AES_XPN_128': {}, 'GCM_AES_XPN_256': {}},)), is_leaf=False, yang_name="macsec-cipher-suite", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='macsec-types:macsec-cipher-suite', is_config=True)
except (TypeError, ValueError):
raise ValueError({
'error-string': """macsec_cipher_suite must be of a type compatible with macsec-types:macsec-cipher-suite""",
'defined-type': "macsec-types:macsec-cipher-suite",
'generated-type': """YANGDynClass(unique=True, base=TypedListType(allowed_type=RestrictedClassType(base_type=six.text_type, restriction_type="dict_key", restriction_arg={'GCM_AES_128': {}, 'GCM_AES_256': {}, 'GCM_AES_XPN_128': {}, 'GCM_AES_XPN_256': {}},)), is_leaf=False, yang_name="macsec-cipher-suite", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='macsec-types:macsec-cipher-suite', is_config=True)""",
})
self.__macsec_cipher_suite = t
if hasattr(self, '_set'):
self._set()
def _unset_macsec_cipher_suite(self):
self.__macsec_cipher_suite = YANGDynClass(unique=True, base=TypedListType(allowed_type=RestrictedClassType(base_type=six.text_type, restriction_type="dict_key", restriction_arg={'GCM_AES_128': {}, 'GCM_AES_256': {}, 'GCM_AES_XPN_128': {}, 'GCM_AES_XPN_256': {}},)), is_leaf=False, yang_name="macsec-cipher-suite", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='macsec-types:macsec-cipher-suite', is_config=True)
def _get_confidentiality_offset(self):
"""
Getter method for confidentiality_offset, mapped from YANG variable /macsec/mka/policies/policy/config/confidentiality_offset (macsec-types:confidentiality-offset)
YANG Description: The confidentiality offset specifies a number of octets in an Ethernet
frame that are sent in unencrypted plain-text
"""
return self.__confidentiality_offset
def _set_confidentiality_offset(self, v, load=False):
"""
Setter method for confidentiality_offset, mapped from YANG variable /macsec/mka/policies/policy/config/confidentiality_offset (macsec-types:confidentiality-offset)
If this variable is read-only (config: false) in the
source YANG file, then _set_confidentiality_offset is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_confidentiality_offset() directly.
YANG Description: The confidentiality offset specifies a number of octets in an Ethernet
frame that are sent in unencrypted plain-text
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=RestrictedClassType(base_type=six.text_type, restriction_type="dict_key", restriction_arg={'0_BYTES': {}, '30_BYTES': {}, '50_BYTES': {}},), default=six.text_type("0_BYTES"), is_leaf=True, yang_name="confidentiality-offset", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='macsec-types:confidentiality-offset', is_config=True)
except (TypeError, ValueError):
raise ValueError({
'error-string': """confidentiality_offset must be of a type compatible with macsec-types:confidentiality-offset""",
'defined-type': "macsec-types:confidentiality-offset",
'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=six.text_type, restriction_type="dict_key", restriction_arg={'0_BYTES': {}, '30_BYTES': {}, '50_BYTES': {}},), default=six.text_type("0_BYTES"), is_leaf=True, yang_name="confidentiality-offset", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='macsec-types:confidentiality-offset', is_config=True)""",
})
self.__confidentiality_offset = t
if hasattr(self, '_set'):
self._set()
def _unset_confidentiality_offset(self):
self.__confidentiality_offset = YANGDynClass(base=RestrictedClassType(base_type=six.text_type, restriction_type="dict_key", restriction_arg={'0_BYTES': {}, '30_BYTES': {}, '50_BYTES': {}},), default=six.text_type("0_BYTES"), is_leaf=True, yang_name="confidentiality-offset", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='macsec-types:confidentiality-offset', is_config=True)
def _get_delay_protection(self):
"""
Getter method for delay_protection, mapped from YANG variable /macsec/mka/policies/policy/config/delay_protection (boolean)
YANG Description: Traffic delayed longer than 2 seconds is rejected by the interfaces
enabled with delay protection.
"""
return self.__delay_protection
def _set_delay_protection(self, v, load=False):
"""
Setter method for delay_protection, mapped from YANG variable /macsec/mka/policies/policy/config/delay_protection (boolean)
If this variable is read-only (config: false) in the
source YANG file, then _set_delay_protection is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_delay_protection() directly.
YANG Description: Traffic delayed longer than 2 seconds is rejected by the interfaces
enabled with delay protection.
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=YANGBool, default=YANGBool("false"), is_leaf=True, yang_name="delay-protection", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='boolean', is_config=True)
except (TypeError, ValueError):
raise ValueError({
'error-string': """delay_protection must be of a type compatible with boolean""",
'defined-type': "boolean",
'generated-type': """YANGDynClass(base=YANGBool, default=YANGBool("false"), is_leaf=True, yang_name="delay-protection", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='boolean', is_config=True)""",
})
self.__delay_protection = t
if hasattr(self, '_set'):
self._set()
def _unset_delay_protection(self):
self.__delay_protection = YANGDynClass(base=YANGBool, default=YANGBool("false"), is_leaf=True, yang_name="delay-protection", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='boolean', is_config=True)
def _get_include_icv_indicator(self):
"""
Getter method for include_icv_indicator, mapped from YANG variable /macsec/mka/policies/policy/config/include_icv_indicator (boolean)
YANG Description: Generate and include an Integrity Check Value (ICV) field in the MKPDU.
For compatibility with previous MACsec implementation that do not
require an ICV
"""
return self.__include_icv_indicator
def _set_include_icv_indicator(self, v, load=False):
"""
Setter method for include_icv_indicator, mapped from YANG variable /macsec/mka/policies/policy/config/include_icv_indicator (boolean)
If this variable is read-only (config: false) in the
source YANG file, then _set_include_icv_indicator is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_include_icv_indicator() directly.
YANG Description: Generate and include an Integrity Check Value (ICV) field in the MKPDU.
For compatibility with previous MACsec implementation that do not
require an ICV
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=YANGBool, default=YANGBool("true"), is_leaf=True, yang_name="include-icv-indicator", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='boolean', is_config=True)
except (TypeError, ValueError):
raise ValueError({
'error-string': """include_icv_indicator must be of a type compatible with boolean""",
'defined-type': "boolean",
'generated-type': """YANGDynClass(base=YANGBool, default=YANGBool("true"), is_leaf=True, yang_name="include-icv-indicator", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='boolean', is_config=True)""",
})
self.__include_icv_indicator = t
if hasattr(self, '_set'):
self._set()
def _unset_include_icv_indicator(self):
self.__include_icv_indicator = YANGDynClass(base=YANGBool, default=YANGBool("true"), is_leaf=True, yang_name="include-icv-indicator", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='boolean', is_config=True)
def _get_sak_rekey_interval(self):
"""
Getter method for sak_rekey_interval, mapped from YANG variable /macsec/mka/policies/policy/config/sak_rekey_interval (uint32)
YANG Description: SAK Rekey interval in seconds. The default value is 0 where no rekey is
performed.
"""
return self.__sak_rekey_interval
def _set_sak_rekey_interval(self, v, load=False):
"""
Setter method for sak_rekey_interval, mapped from YANG variable /macsec/mka/policies/policy/config/sak_rekey_interval (uint32)
If this variable is read-only (config: false) in the
source YANG file, then _set_sak_rekey_interval is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_sak_rekey_interval() directly.
YANG Description: SAK Rekey interval in seconds. The default value is 0 where no rekey is
performed.
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=RestrictedClassType(base_type=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), restriction_dict={'range': ['0', '30..65535']}), default=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32)(0), is_leaf=True, yang_name="sak-rekey-interval", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='uint32', is_config=True)
except (TypeError, ValueError):
raise ValueError({
'error-string': """sak_rekey_interval must be of a type compatible with uint32""",
'defined-type': "uint32",
'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), restriction_dict={'range': ['0', '30..65535']}), default=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32)(0), is_leaf=True, yang_name="sak-rekey-interval", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='uint32', is_config=True)""",
})
self.__sak_rekey_interval = t
if hasattr(self, '_set'):
self._set()
def _unset_sak_rekey_interval(self):
self.__sak_rekey_interval = YANGDynClass(base=RestrictedClassType(base_type=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), restriction_dict={'range': ['0', '30..65535']}), default=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32)(0), is_leaf=True, yang_name="sak-rekey-interval", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='uint32', is_config=True)
def _get_sak_rekey_on_live_peer_loss(self):
"""
Getter method for sak_rekey_on_live_peer_loss, mapped from YANG variable /macsec/mka/policies/policy/config/sak_rekey_on_live_peer_loss (boolean)
YANG Description: Rekey on peer loss
"""
return self.__sak_rekey_on_live_peer_loss
def _set_sak_rekey_on_live_peer_loss(self, v, load=False):
"""
Setter method for sak_rekey_on_live_peer_loss, mapped from YANG variable /macsec/mka/policies/policy/config/sak_rekey_on_live_peer_loss (boolean)
If this variable is read-only (config: false) in the
source YANG file, then _set_sak_rekey_on_live_peer_loss is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_sak_rekey_on_live_peer_loss() directly.
YANG Description: Rekey on peer loss
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=YANGBool, default=YANGBool("false"), is_leaf=True, yang_name="sak-rekey-on-live-peer-loss", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='boolean', is_config=True)
except (TypeError, ValueError):
raise ValueError({
'error-string': """sak_rekey_on_live_peer_loss must be of a type compatible with boolean""",
'defined-type': "boolean",
'generated-type': """YANGDynClass(base=YANGBool, default=YANGBool("false"), is_leaf=True, yang_name="sak-rekey-on-live-peer-loss", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='boolean', is_config=True)""",
})
self.__sak_rekey_on_live_peer_loss = t
if hasattr(self, '_set'):
self._set()
def _unset_sak_rekey_on_live_peer_loss(self):
self.__sak_rekey_on_live_peer_loss = YANGDynClass(base=YANGBool, default=YANGBool("false"), is_leaf=True, yang_name="sak-rekey-on-live-peer-loss", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='boolean', is_config=True)
def _get_use_updated_eth_header(self):
"""
Getter method for use_updated_eth_header, mapped from YANG variable /macsec/mka/policies/policy/config/use_updated_eth_header (boolean)
YANG Description: Use updated ethernet header for ICV calculation. In case the Ethernet
frame headers change, use the updated headers to calculate the ICV.
"""
return self.__use_updated_eth_header
def _set_use_updated_eth_header(self, v, load=False):
"""
Setter method for use_updated_eth_header, mapped from YANG variable /macsec/mka/policies/policy/config/use_updated_eth_header (boolean)
If this variable is read-only (config: false) in the
source YANG file, then _set_use_updated_eth_header is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_use_updated_eth_header() directly.
YANG Description: Use updated ethernet header for ICV calculation. In case the Ethernet
frame headers change, use the updated headers to calculate the ICV.
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=YANGBool, default=YANGBool("false"), is_leaf=True, yang_name="use-updated-eth-header", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='boolean', is_config=True)
except (TypeError, ValueError):
raise ValueError({
'error-string': """use_updated_eth_header must be of a type compatible with boolean""",
'defined-type': "boolean",
'generated-type': """YANGDynClass(base=YANGBool, default=YANGBool("false"), is_leaf=True, yang_name="use-updated-eth-header", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='boolean', is_config=True)""",
})
self.__use_updated_eth_header = t
if hasattr(self, '_set'):
self._set()
def _unset_use_updated_eth_header(self):
self.__use_updated_eth_header = YANGDynClass(base=YANGBool, default=YANGBool("false"), is_leaf=True, yang_name="use-updated-eth-header", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='boolean', is_config=True)
name = __builtin__.property(_get_name, _set_name)
key_server_priority = __builtin__.property(_get_key_server_priority, _set_key_server_priority)
macsec_cipher_suite = __builtin__.property(_get_macsec_cipher_suite, _set_macsec_cipher_suite)
confidentiality_offset = __builtin__.property(_get_confidentiality_offset, _set_confidentiality_offset)
delay_protection = __builtin__.property(_get_delay_protection, _set_delay_protection)
include_icv_indicator = __builtin__.property(_get_include_icv_indicator, _set_include_icv_indicator)
sak_rekey_interval = __builtin__.property(_get_sak_rekey_interval, _set_sak_rekey_interval)
sak_rekey_on_live_peer_loss = __builtin__.property(_get_sak_rekey_on_live_peer_loss, _set_sak_rekey_on_live_peer_loss)
use_updated_eth_header = __builtin__.property(_get_use_updated_eth_header, _set_use_updated_eth_header)
_pyangbind_elements = OrderedDict([('name', name), ('key_server_priority', key_server_priority), ('macsec_cipher_suite', macsec_cipher_suite), ('confidentiality_offset', confidentiality_offset), ('delay_protection', delay_protection), ('include_icv_indicator', include_icv_indicator), ('sak_rekey_interval', sak_rekey_interval), ('sak_rekey_on_live_peer_loss', sak_rekey_on_live_peer_loss), ('use_updated_eth_header', use_updated_eth_header), ])
class yc_state_openconfig_macsec__macsec_mka_policies_policy_state(PybindBase):
"""
This class was auto-generated by the PythonClass plugin for PYANG
from YANG module openconfig-macsec - based on the path /macsec/mka/policies/policy/state. Each member element of
the container is represented as a class variable - with a specific
YANG type.
YANG Description: Operational state data for MKA policy
"""
__slots__ = ('_path_helper', '_extmethods', '__name','__key_server_priority','__macsec_cipher_suite','__confidentiality_offset','__delay_protection','__include_icv_indicator','__sak_rekey_interval','__sak_rekey_on_live_peer_loss','__use_updated_eth_header',)
_yang_name = 'state'
_yang_namespace = 'http://openconfig.net/yang/macsec'
_pybind_generated_by = 'container'
def __init__(self, *args, **kwargs):
self._path_helper = False
self._extmethods = False
self.__name = YANGDynClass(base=six.text_type, is_leaf=True, yang_name="name", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='string', is_config=False)
self.__key_server_priority = YANGDynClass(base=RestrictedClassType(base_type=int, restriction_dict={'range': ['0..255']}, int_size=8), default=RestrictedClassType(base_type=int, restriction_dict={'range': ['0..255']}, int_size=8)(16), is_leaf=True, yang_name="key-server-priority", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='uint8', is_config=False)
self.__macsec_cipher_suite = YANGDynClass(unique=True, base=TypedListType(allowed_type=RestrictedClassType(base_type=six.text_type, restriction_type="dict_key", restriction_arg={'GCM_AES_128': {}, 'GCM_AES_256': {}, 'GCM_AES_XPN_128': {}, 'GCM_AES_XPN_256': {}},)), is_leaf=False, yang_name="macsec-cipher-suite", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='macsec-types:macsec-cipher-suite', is_config=False)
self.__confidentiality_offset = YANGDynClass(base=RestrictedClassType(base_type=six.text_type, restriction_type="dict_key", restriction_arg={'0_BYTES': {}, '30_BYTES': {}, '50_BYTES': {}},), default=six.text_type("0_BYTES"), is_leaf=True, yang_name="confidentiality-offset", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='macsec-types:confidentiality-offset', is_config=False)
self.__delay_protection = YANGDynClass(base=YANGBool, default=YANGBool("false"), is_leaf=True, yang_name="delay-protection", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='boolean', is_config=False)
self.__include_icv_indicator = YANGDynClass(base=YANGBool, default=YANGBool("true"), is_leaf=True, yang_name="include-icv-indicator", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='boolean', is_config=False)
self.__sak_rekey_interval = YANGDynClass(base=RestrictedClassType(base_type=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), restriction_dict={'range': ['0', '30..65535']}), default=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32)(0), is_leaf=True, yang_name="sak-rekey-interval", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='uint32', is_config=False)
self.__sak_rekey_on_live_peer_loss = YANGDynClass(base=YANGBool, default=YANGBool("false"), is_leaf=True, yang_name="sak-rekey-on-live-peer-loss", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='boolean', is_config=False)
self.__use_updated_eth_header = YANGDynClass(base=YANGBool, default=YANGBool("false"), is_leaf=True, yang_name="use-updated-eth-header", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='boolean', is_config=False)
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 ['macsec', 'mka', 'policies', 'policy', 'state']
def _get_name(self):
"""
Getter method for name, mapped from YANG variable /macsec/mka/policies/policy/state/name (string)
YANG Description: Name of the MKA policy.
"""
return self.__name
def _set_name(self, v, load=False):
"""
Setter method for name, mapped from YANG variable /macsec/mka/policies/policy/state/name (string)
If this variable is read-only (config: false) in the
source YANG file, then _set_name is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_name() directly.
YANG Description: Name of the MKA policy.
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=six.text_type, is_leaf=True, yang_name="name", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='string', is_config=False)
except (TypeError, ValueError):
raise ValueError({
'error-string': """name must be of a type compatible with string""",
'defined-type': "string",
'generated-type': """YANGDynClass(base=six.text_type, is_leaf=True, yang_name="name", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='string', is_config=False)""",
})
self.__name = t
if hasattr(self, '_set'):
self._set()
def _unset_name(self):
self.__name = YANGDynClass(base=six.text_type, is_leaf=True, yang_name="name", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='string', is_config=False)
def _get_key_server_priority(self):
"""
Getter method for key_server_priority, mapped from YANG variable /macsec/mka/policies/policy/state/key_server_priority (uint8)
YANG Description: Specifies the key server priority used by the MACsec Key Agreement
(MKA) protocol to select the key server when MACsec is enabled using
static connectivity association key (CAK) security mode. The switch with
the lower priority-number is selected as the key server. If the
priority-number is identical on both sides of a point-to-point link, the
MKA protocol selects the device with the lower MAC address as the key
server
"""
return self.__key_server_priority
def _set_key_server_priority(self, v, load=False):
"""
Setter method for key_server_priority, mapped from YANG variable /macsec/mka/policies/policy/state/key_server_priority (uint8)
If this variable is read-only (config: false) in the
source YANG file, then _set_key_server_priority is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_key_server_priority() directly.
YANG Description: Specifies the key server priority used by the MACsec Key Agreement
(MKA) protocol to select the key server when MACsec is enabled using
static connectivity association key (CAK) security mode. The switch with
the lower priority-number is selected as the key server. If the
priority-number is identical on both sides of a point-to-point link, the
MKA protocol selects the device with the lower MAC address as the key
server
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=RestrictedClassType(base_type=int, restriction_dict={'range': ['0..255']}, int_size=8), default=RestrictedClassType(base_type=int, restriction_dict={'range': ['0..255']}, int_size=8)(16), is_leaf=True, yang_name="key-server-priority", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='uint8', is_config=False)
except (TypeError, ValueError):
raise ValueError({
'error-string': """key_server_priority must be of a type compatible with uint8""",
'defined-type': "uint8",
'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=int, restriction_dict={'range': ['0..255']}, int_size=8), default=RestrictedClassType(base_type=int, restriction_dict={'range': ['0..255']}, int_size=8)(16), is_leaf=True, yang_name="key-server-priority", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='uint8', is_config=False)""",
})
self.__key_server_priority = t
if hasattr(self, '_set'):
self._set()
def _unset_key_server_priority(self):
self.__key_server_priority = YANGDynClass(base=RestrictedClassType(base_type=int, restriction_dict={'range': ['0..255']}, int_size=8), default=RestrictedClassType(base_type=int, restriction_dict={'range': ['0..255']}, int_size=8)(16), is_leaf=True, yang_name="key-server-priority", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='uint8', is_config=False)
def _get_macsec_cipher_suite(self):
"""
Getter method for macsec_cipher_suite, mapped from YANG variable /macsec/mka/policies/policy/state/macsec_cipher_suite (macsec-types:macsec-cipher-suite)
YANG Description: Set Cipher suite(s) for SAK derivation
"""
return self.__macsec_cipher_suite
def _set_macsec_cipher_suite(self, v, load=False):
"""
Setter method for macsec_cipher_suite, mapped from YANG variable /macsec/mka/policies/policy/state/macsec_cipher_suite (macsec-types:macsec-cipher-suite)
If this variable is read-only (config: false) in the
source YANG file, then _set_macsec_cipher_suite is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_macsec_cipher_suite() directly.
YANG Description: Set Cipher suite(s) for SAK derivation
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,unique=True, base=TypedListType(allowed_type=RestrictedClassType(base_type=six.text_type, restriction_type="dict_key", restriction_arg={'GCM_AES_128': {}, 'GCM_AES_256': {}, 'GCM_AES_XPN_128': {}, 'GCM_AES_XPN_256': {}},)), is_leaf=False, yang_name="macsec-cipher-suite", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='macsec-types:macsec-cipher-suite', is_config=False)
except (TypeError, ValueError):
raise ValueError({
'error-string': """macsec_cipher_suite must be of a type compatible with macsec-types:macsec-cipher-suite""",
'defined-type': "macsec-types:macsec-cipher-suite",
'generated-type': """YANGDynClass(unique=True, base=TypedListType(allowed_type=RestrictedClassType(base_type=six.text_type, restriction_type="dict_key", restriction_arg={'GCM_AES_128': {}, 'GCM_AES_256': {}, 'GCM_AES_XPN_128': {}, 'GCM_AES_XPN_256': {}},)), is_leaf=False, yang_name="macsec-cipher-suite", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='macsec-types:macsec-cipher-suite', is_config=False)""",
})
self.__macsec_cipher_suite = t
if hasattr(self, '_set'):
self._set()
def _unset_macsec_cipher_suite(self):
self.__macsec_cipher_suite = YANGDynClass(unique=True, base=TypedListType(allowed_type=RestrictedClassType(base_type=six.text_type, restriction_type="dict_key", restriction_arg={'GCM_AES_128': {}, 'GCM_AES_256': {}, 'GCM_AES_XPN_128': {}, 'GCM_AES_XPN_256': {}},)), is_leaf=False, yang_name="macsec-cipher-suite", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='macsec-types:macsec-cipher-suite', is_config=False)
def _get_confidentiality_offset(self):
"""
Getter method for confidentiality_offset, mapped from YANG variable /macsec/mka/policies/policy/state/confidentiality_offset (macsec-types:confidentiality-offset)
YANG Description: The confidentiality offset specifies a number of octets in an Ethernet
frame that are sent in unencrypted plain-text
"""
return self.__confidentiality_offset
def _set_confidentiality_offset(self, v, load=False):
"""
Setter method for confidentiality_offset, mapped from YANG variable /macsec/mka/policies/policy/state/confidentiality_offset (macsec-types:confidentiality-offset)
If this variable is read-only (config: false) in the
source YANG file, then _set_confidentiality_offset is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_confidentiality_offset() directly.
YANG Description: The confidentiality offset specifies a number of octets in an Ethernet
frame that are sent in unencrypted plain-text
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=RestrictedClassType(base_type=six.text_type, restriction_type="dict_key", restriction_arg={'0_BYTES': {}, '30_BYTES': {}, '50_BYTES': {}},), default=six.text_type("0_BYTES"), is_leaf=True, yang_name="confidentiality-offset", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='macsec-types:confidentiality-offset', is_config=False)
except (TypeError, ValueError):
raise ValueError({
'error-string': """confidentiality_offset must be of a type compatible with macsec-types:confidentiality-offset""",
'defined-type': "macsec-types:confidentiality-offset",
'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=six.text_type, restriction_type="dict_key", restriction_arg={'0_BYTES': {}, '30_BYTES': {}, '50_BYTES': {}},), default=six.text_type("0_BYTES"), is_leaf=True, yang_name="confidentiality-offset", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='macsec-types:confidentiality-offset', is_config=False)""",
})
self.__confidentiality_offset = t
if hasattr(self, '_set'):
self._set()
def _unset_confidentiality_offset(self):
self.__confidentiality_offset = YANGDynClass(base=RestrictedClassType(base_type=six.text_type, restriction_type="dict_key", restriction_arg={'0_BYTES': {}, '30_BYTES': {}, '50_BYTES': {}},), default=six.text_type("0_BYTES"), is_leaf=True, yang_name="confidentiality-offset", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='macsec-types:confidentiality-offset', is_config=False)
def _get_delay_protection(self):
"""
Getter method for delay_protection, mapped from YANG variable /macsec/mka/policies/policy/state/delay_protection (boolean)
YANG Description: Traffic delayed longer than 2 seconds is rejected by the interfaces
enabled with delay protection.
"""
return self.__delay_protection
def _set_delay_protection(self, v, load=False):
"""
Setter method for delay_protection, mapped from YANG variable /macsec/mka/policies/policy/state/delay_protection (boolean)
If this variable is read-only (config: false) in the
source YANG file, then _set_delay_protection is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_delay_protection() directly.
YANG Description: Traffic delayed longer than 2 seconds is rejected by the interfaces
enabled with delay protection.
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=YANGBool, default=YANGBool("false"), is_leaf=True, yang_name="delay-protection", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='boolean', is_config=False)
except (TypeError, ValueError):
raise ValueError({
'error-string': """delay_protection must be of a type compatible with boolean""",
'defined-type': "boolean",
'generated-type': """YANGDynClass(base=YANGBool, default=YANGBool("false"), is_leaf=True, yang_name="delay-protection", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='boolean', is_config=False)""",
})
self.__delay_protection = t
if hasattr(self, '_set'):
self._set()
def _unset_delay_protection(self):
self.__delay_protection = YANGDynClass(base=YANGBool, default=YANGBool("false"), is_leaf=True, yang_name="delay-protection", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='boolean', is_config=False)
def _get_include_icv_indicator(self):
"""
Getter method for include_icv_indicator, mapped from YANG variable /macsec/mka/policies/policy/state/include_icv_indicator (boolean)
YANG Description: Generate and include an Integrity Check Value (ICV) field in the MKPDU.
For compatibility with previous MACsec implementation that do not
require an ICV
"""
return self.__include_icv_indicator
def _set_include_icv_indicator(self, v, load=False):
"""
Setter method for include_icv_indicator, mapped from YANG variable /macsec/mka/policies/policy/state/include_icv_indicator (boolean)
If this variable is read-only (config: false) in the
source YANG file, then _set_include_icv_indicator is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_include_icv_indicator() directly.
YANG Description: Generate and include an Integrity Check Value (ICV) field in the MKPDU.
For compatibility with previous MACsec implementation that do not
require an ICV
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=YANGBool, default=YANGBool("true"), is_leaf=True, yang_name="include-icv-indicator", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='boolean', is_config=False)
except (TypeError, ValueError):
raise ValueError({
'error-string': """include_icv_indicator must be of a type compatible with boolean""",
'defined-type': "boolean",
'generated-type': """YANGDynClass(base=YANGBool, default=YANGBool("true"), is_leaf=True, yang_name="include-icv-indicator", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='boolean', is_config=False)""",
})
self.__include_icv_indicator = t
if hasattr(self, '_set'):
self._set()
def _unset_include_icv_indicator(self):
self.__include_icv_indicator = YANGDynClass(base=YANGBool, default=YANGBool("true"), is_leaf=True, yang_name="include-icv-indicator", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='boolean', is_config=False)
def _get_sak_rekey_interval(self):
"""
Getter method for sak_rekey_interval, mapped from YANG variable /macsec/mka/policies/policy/state/sak_rekey_interval (uint32)
YANG Description: SAK Rekey interval in seconds. The default value is 0 where no rekey is
performed.
"""
return self.__sak_rekey_interval
def _set_sak_rekey_interval(self, v, load=False):
"""
Setter method for sak_rekey_interval, mapped from YANG variable /macsec/mka/policies/policy/state/sak_rekey_interval (uint32)
If this variable is read-only (config: false) in the
source YANG file, then _set_sak_rekey_interval is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_sak_rekey_interval() directly.
YANG Description: SAK Rekey interval in seconds. The default value is 0 where no rekey is
performed.
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=RestrictedClassType(base_type=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), restriction_dict={'range': ['0', '30..65535']}), default=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32)(0), is_leaf=True, yang_name="sak-rekey-interval", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='uint32', is_config=False)
except (TypeError, ValueError):
raise ValueError({
'error-string': """sak_rekey_interval must be of a type compatible with uint32""",
'defined-type': "uint32",
'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), restriction_dict={'range': ['0', '30..65535']}), default=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32)(0), is_leaf=True, yang_name="sak-rekey-interval", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='uint32', is_config=False)""",
})
self.__sak_rekey_interval = t
if hasattr(self, '_set'):
self._set()
def _unset_sak_rekey_interval(self):
self.__sak_rekey_interval = YANGDynClass(base=RestrictedClassType(base_type=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32), restriction_dict={'range': ['0', '30..65535']}), default=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..4294967295']}, int_size=32)(0), is_leaf=True, yang_name="sak-rekey-interval", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='uint32', is_config=False)
def _get_sak_rekey_on_live_peer_loss(self):
"""
Getter method for sak_rekey_on_live_peer_loss, mapped from YANG variable /macsec/mka/policies/policy/state/sak_rekey_on_live_peer_loss (boolean)
YANG Description: Rekey on peer loss
"""
return self.__sak_rekey_on_live_peer_loss
def _set_sak_rekey_on_live_peer_loss(self, v, load=False):
"""
Setter method for sak_rekey_on_live_peer_loss, mapped from YANG variable /macsec/mka/policies/policy/state/sak_rekey_on_live_peer_loss (boolean)
If this variable is read-only (config: false) in the
source YANG file, then _set_sak_rekey_on_live_peer_loss is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_sak_rekey_on_live_peer_loss() directly.
YANG Description: Rekey on peer loss
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=YANGBool, default=YANGBool("false"), is_leaf=True, yang_name="sak-rekey-on-live-peer-loss", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='boolean', is_config=False)
except (TypeError, ValueError):
raise ValueError({
'error-string': """sak_rekey_on_live_peer_loss must be of a type compatible with boolean""",
'defined-type': "boolean",
'generated-type': """YANGDynClass(base=YANGBool, default=YANGBool("false"), is_leaf=True, yang_name="sak-rekey-on-live-peer-loss", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='boolean', is_config=False)""",
})
self.__sak_rekey_on_live_peer_loss = t
if hasattr(self, '_set'):
self._set()
def _unset_sak_rekey_on_live_peer_loss(self):
self.__sak_rekey_on_live_peer_loss = YANGDynClass(base=YANGBool, default=YANGBool("false"), is_leaf=True, yang_name="sak-rekey-on-live-peer-loss", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='boolean', is_config=False)
def _get_use_updated_eth_header(self):
"""
Getter method for use_updated_eth_header, mapped from YANG variable /macsec/mka/policies/policy/state/use_updated_eth_header (boolean)
YANG Description: Use updated ethernet header for ICV calculation. In case the Ethernet
frame headers change, use the updated headers to calculate the ICV.
"""
return self.__use_updated_eth_header
def _set_use_updated_eth_header(self, v, load=False):
"""
Setter method for use_updated_eth_header, mapped from YANG variable /macsec/mka/policies/policy/state/use_updated_eth_header (boolean)
If this variable is read-only (config: false) in the
source YANG file, then _set_use_updated_eth_header is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_use_updated_eth_header() directly.
YANG Description: Use updated ethernet header for ICV calculation. In case the Ethernet
frame headers change, use the updated headers to calculate the ICV.
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=YANGBool, default=YANGBool("false"), is_leaf=True, yang_name="use-updated-eth-header", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='boolean', is_config=False)
except (TypeError, ValueError):
raise ValueError({
'error-string': """use_updated_eth_header must be of a type compatible with boolean""",
'defined-type': "boolean",
'generated-type': """YANGDynClass(base=YANGBool, default=YANGBool("false"), is_leaf=True, yang_name="use-updated-eth-header", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='boolean', is_config=False)""",
})
self.__use_updated_eth_header = t
if hasattr(self, '_set'):
self._set()
def _unset_use_updated_eth_header(self):
self.__use_updated_eth_header = YANGDynClass(base=YANGBool, default=YANGBool("false"), is_leaf=True, yang_name="use-updated-eth-header", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='boolean', is_config=False)
name = __builtin__.property(_get_name)
key_server_priority = __builtin__.property(_get_key_server_priority)
macsec_cipher_suite = __builtin__.property(_get_macsec_cipher_suite)
confidentiality_offset = __builtin__.property(_get_confidentiality_offset)
delay_protection = __builtin__.property(_get_delay_protection)
include_icv_indicator = __builtin__.property(_get_include_icv_indicator)
sak_rekey_interval = __builtin__.property(_get_sak_rekey_interval)
sak_rekey_on_live_peer_loss = __builtin__.property(_get_sak_rekey_on_live_peer_loss)
use_updated_eth_header = __builtin__.property(_get_use_updated_eth_header)
_pyangbind_elements = OrderedDict([('name', name), ('key_server_priority', key_server_priority), ('macsec_cipher_suite', macsec_cipher_suite), ('confidentiality_offset', confidentiality_offset), ('delay_protection', delay_protection), ('include_icv_indicator', include_icv_indicator), ('sak_rekey_interval', sak_rekey_interval), ('sak_rekey_on_live_peer_loss', sak_rekey_on_live_peer_loss), ('use_updated_eth_header', use_updated_eth_header), ])
class yc_policy_openconfig_macsec__macsec_mka_policies_policy(PybindBase):
"""
This class was auto-generated by the PythonClass plugin for PYANG
from YANG module openconfig-macsec - based on the path /macsec/mka/policies/policy. Each member element of
the container is represented as a class variable - with a specific
YANG type.
YANG Description: List of MKA policies
"""
__slots__ = ('_path_helper', '_extmethods', '__name','__config','__state',)
_yang_name = 'policy'
_yang_namespace = 'http://openconfig.net/yang/macsec'
_pybind_generated_by = 'container'
def __init__(self, *args, **kwargs):
self._path_helper = False
self._extmethods = False
self.__name = YANGDynClass(base=six.text_type, is_leaf=True, yang_name="name", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, is_keyval=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='leafref', is_config=True)
self.__config = YANGDynClass(base=yc_config_openconfig_macsec__macsec_mka_policies_policy_config, is_container='container', yang_name="config", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True)
self.__state = YANGDynClass(base=yc_state_openconfig_macsec__macsec_mka_policies_policy_state, is_container='container', yang_name="state", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', 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 ['macsec', 'mka', 'policies', 'policy']
def _get_name(self):
"""
Getter method for name, mapped from YANG variable /macsec/mka/policies/policy/name (leafref)
YANG Description: Reference to MKA policy name
"""
return self.__name
def _set_name(self, v, load=False):
"""
Setter method for name, mapped from YANG variable /macsec/mka/policies/policy/name (leafref)
If this variable is read-only (config: false) in the
source YANG file, then _set_name is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_name() directly.
YANG Description: Reference to MKA policy name
"""
parent = getattr(self, "_parent", None)
if parent is not None and load is False:
raise AttributeError("Cannot set keys directly when" +
" within an instantiated list")
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=six.text_type, is_leaf=True, yang_name="name", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, is_keyval=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='leafref', is_config=True)
except (TypeError, ValueError):
raise ValueError({
'error-string': """name must be of a type compatible with leafref""",
'defined-type': "leafref",
'generated-type': """YANGDynClass(base=six.text_type, is_leaf=True, yang_name="name", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, is_keyval=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='leafref', is_config=True)""",
})
self.__name = t
if hasattr(self, '_set'):
self._set()
def _unset_name(self):
self.__name = YANGDynClass(base=six.text_type, is_leaf=True, yang_name="name", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, is_keyval=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='leafref', is_config=True)
def _get_config(self):
"""
Getter method for config, mapped from YANG variable /macsec/mka/policies/policy/config (container)
YANG Description: Configuration of the MKA policy
"""
return self.__config
def _set_config(self, v, load=False):
"""
Setter method for config, mapped from YANG variable /macsec/mka/policies/policy/config (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_config is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_config() directly.
YANG Description: Configuration of the MKA policy
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=yc_config_openconfig_macsec__macsec_mka_policies_policy_config, is_container='container', yang_name="config", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True)
except (TypeError, ValueError):
raise ValueError({
'error-string': """config must be of a type compatible with container""",
'defined-type': "container",
'generated-type': """YANGDynClass(base=yc_config_openconfig_macsec__macsec_mka_policies_policy_config, is_container='container', yang_name="config", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True)""",
})
self.__config = t
if hasattr(self, '_set'):
self._set()
def _unset_config(self):
self.__config = YANGDynClass(base=yc_config_openconfig_macsec__macsec_mka_policies_policy_config, is_container='container', yang_name="config", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True)
def _get_state(self):
"""
Getter method for state, mapped from YANG variable /macsec/mka/policies/policy/state (container)
YANG Description: Operational state data for MKA policy
"""
return self.__state
def _set_state(self, v, load=False):
"""
Setter method for state, mapped from YANG variable /macsec/mka/policies/policy/state (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_state is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_state() directly.
YANG Description: Operational state data for MKA policy
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=yc_state_openconfig_macsec__macsec_mka_policies_policy_state, is_container='container', yang_name="state", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True)
except (TypeError, ValueError):
raise ValueError({
'error-string': """state must be of a type compatible with container""",
'defined-type': "container",
'generated-type': """YANGDynClass(base=yc_state_openconfig_macsec__macsec_mka_policies_policy_state, is_container='container', yang_name="state", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True)""",
})
self.__state = t
if hasattr(self, '_set'):
self._set()
def _unset_state(self):
self.__state = YANGDynClass(base=yc_state_openconfig_macsec__macsec_mka_policies_policy_state, is_container='container', yang_name="state", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True)
name = __builtin__.property(_get_name, _set_name)
config = __builtin__.property(_get_config, _set_config)
state = __builtin__.property(_get_state, _set_state)
_pyangbind_elements = OrderedDict([('name', name), ('config', config), ('state', state), ])
class yc_policies_openconfig_macsec__macsec_mka_policies(PybindBase):
"""
This class was auto-generated by the PythonClass plugin for PYANG
from YANG module openconfig-macsec - based on the path /macsec/mka/policies. Each member element of
the container is represented as a class variable - with a specific
YANG type.
YANG Description: Enclosing container for the list of MKA policies
"""
__slots__ = ('_path_helper', '_extmethods', '__policy',)
_yang_name = 'policies'
_yang_namespace = 'http://openconfig.net/yang/macsec'
_pybind_generated_by = 'container'
def __init__(self, *args, **kwargs):
self._path_helper = False
self._extmethods = False
self.__policy = YANGDynClass(base=YANGListType("name",yc_policy_openconfig_macsec__macsec_mka_policies_policy, yang_name="policy", parent=self, is_container='list', user_ordered=False, path_helper=self._path_helper, yang_keys='name', extensions=None), is_container='list', yang_name="policy", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='list', 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 ['macsec', 'mka', 'policies']
def _get_policy(self):
"""
Getter method for policy, mapped from YANG variable /macsec/mka/policies/policy (list)
YANG Description: List of MKA policies
"""
return self.__policy
def _set_policy(self, v, load=False):
"""
Setter method for policy, mapped from YANG variable /macsec/mka/policies/policy (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_policy is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_policy() directly.
YANG Description: List of MKA policies
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=YANGListType("name",yc_policy_openconfig_macsec__macsec_mka_policies_policy, yang_name="policy", parent=self, is_container='list', user_ordered=False, path_helper=self._path_helper, yang_keys='name', extensions=None), is_container='list', yang_name="policy", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='list', is_config=True)
except (TypeError, ValueError):
raise ValueError({
'error-string': """policy must be of a type compatible with list""",
'defined-type': "list",
'generated-type': """YANGDynClass(base=YANGListType("name",yc_policy_openconfig_macsec__macsec_mka_policies_policy, yang_name="policy", parent=self, is_container='list', user_ordered=False, path_helper=self._path_helper, yang_keys='name', extensions=None), is_container='list', yang_name="policy", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='list', is_config=True)""",
})
self.__policy = t
if hasattr(self, '_set'):
self._set()
def _unset_policy(self):
self.__policy = YANGDynClass(base=YANGListType("name",yc_policy_openconfig_macsec__macsec_mka_policies_policy, yang_name="policy", parent=self, is_container='list', user_ordered=False, path_helper=self._path_helper, yang_keys='name', extensions=None), is_container='list', yang_name="policy", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='list', is_config=True)
policy = __builtin__.property(_get_policy, _set_policy)
_pyangbind_elements = OrderedDict([('policy', policy), ])
class yc_config_openconfig_macsec__macsec_mka_key_chains_key_chain_config(PybindBase):
"""
This class was auto-generated by the PythonClass plugin for PYANG
from YANG module openconfig-macsec - based on the path /macsec/mka/key-chains/key-chain/config. Each member element of
the container is represented as a class variable - with a specific
YANG type.
YANG Description: Configuration of the MKA key chain
"""
__slots__ = ('_path_helper', '_extmethods', '__name',)
_yang_name = 'config'
_yang_namespace = 'http://openconfig.net/yang/macsec'
_pybind_generated_by = 'container'
def __init__(self, *args, **kwargs):
self._path_helper = False
self._extmethods = False
self.__name = YANGDynClass(base=six.text_type, is_leaf=True, yang_name="name", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='string', 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 ['macsec', 'mka', 'key-chains', 'key-chain', 'config']
def _get_name(self):
"""
Getter method for name, mapped from YANG variable /macsec/mka/key_chains/key_chain/config/name (string)
YANG Description: MKA Key-chain name
"""
return self.__name
def _set_name(self, v, load=False):
"""
Setter method for name, mapped from YANG variable /macsec/mka/key_chains/key_chain/config/name (string)
If this variable is read-only (config: false) in the
source YANG file, then _set_name is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_name() directly.
YANG Description: MKA Key-chain name
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=six.text_type, is_leaf=True, yang_name="name", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='string', is_config=True)
except (TypeError, ValueError):
raise ValueError({
'error-string': """name must be of a type compatible with string""",
'defined-type': "string",
'generated-type': """YANGDynClass(base=six.text_type, is_leaf=True, yang_name="name", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='string', is_config=True)""",
})
self.__name = t
if hasattr(self, '_set'):
self._set()
def _unset_name(self):
self.__name = YANGDynClass(base=six.text_type, is_leaf=True, yang_name="name", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='string', is_config=True)
name = __builtin__.property(_get_name, _set_name)
_pyangbind_elements = OrderedDict([('name', name), ])
class yc_state_openconfig_macsec__macsec_mka_key_chains_key_chain_state(PybindBase):
"""
This class was auto-generated by the PythonClass plugin for PYANG
from YANG module openconfig-macsec - based on the path /macsec/mka/key-chains/key-chain/state. Each member element of
the container is represented as a class variable - with a specific
YANG type.
YANG Description: Operational state data for MKA key chain
"""
__slots__ = ('_path_helper', '_extmethods', '__name',)
_yang_name = 'state'
_yang_namespace = 'http://openconfig.net/yang/macsec'
_pybind_generated_by = 'container'
def __init__(self, *args, **kwargs):
self._path_helper = False
self._extmethods = False
self.__name = YANGDynClass(base=six.text_type, is_leaf=True, yang_name="name", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='string', is_config=False)
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 ['macsec', 'mka', 'key-chains', 'key-chain', 'state']
def _get_name(self):
"""
Getter method for name, mapped from YANG variable /macsec/mka/key_chains/key_chain/state/name (string)
YANG Description: MKA Key-chain name
"""
return self.__name
def _set_name(self, v, load=False):
"""
Setter method for name, mapped from YANG variable /macsec/mka/key_chains/key_chain/state/name (string)
If this variable is read-only (config: false) in the
source YANG file, then _set_name is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_name() directly.
YANG Description: MKA Key-chain name
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=six.text_type, is_leaf=True, yang_name="name", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='string', is_config=False)
except (TypeError, ValueError):
raise ValueError({
'error-string': """name must be of a type compatible with string""",
'defined-type': "string",
'generated-type': """YANGDynClass(base=six.text_type, is_leaf=True, yang_name="name", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='string', is_config=False)""",
})
self.__name = t
if hasattr(self, '_set'):
self._set()
def _unset_name(self):
self.__name = YANGDynClass(base=six.text_type, is_leaf=True, yang_name="name", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='string', is_config=False)
name = __builtin__.property(_get_name)
_pyangbind_elements = OrderedDict([('name', name), ])
class yc_config_openconfig_macsec__macsec_mka_key_chains_key_chain_mka_keys_mka_key_config(PybindBase):
"""
This class was auto-generated by the PythonClass plugin for PYANG
from YANG module openconfig-macsec - based on the path /macsec/mka/key-chains/key-chain/mka-keys/mka-key/config. Each member element of
the container is represented as a class variable - with a specific
YANG type.
YANG Description: Configuration of MKA key
"""
__slots__ = ('_path_helper', '_extmethods', '__id','__key_clear_text','__cryptographic_algorithm','__valid_date_time','__expiration_date_time',)
_yang_name = 'config'
_yang_namespace = 'http://openconfig.net/yang/macsec'
_pybind_generated_by = 'container'
def __init__(self, *args, **kwargs):
self._path_helper = False
self._extmethods = False
self.__id = YANGDynClass(base=RestrictedClassType(base_type=RestrictedClassType(base_type=six.text_type, restriction_dict={'pattern': '[0-9a-fA-F]*'}), restriction_dict={'length': ['1..64']}), is_leaf=True, yang_name="id", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:hex-string', is_config=True)
self.__key_clear_text = YANGDynClass(base=six.text_type, is_leaf=True, yang_name="key-clear-text", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='string', is_config=True)
self.__cryptographic_algorithm = YANGDynClass(base=RestrictedClassType(base_type=six.text_type, restriction_type="dict_key", restriction_arg={'AES_128_CMAC': {}, 'AES_256_CMAC': {}},), is_leaf=True, yang_name="cryptographic-algorithm", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='enumeration', is_config=True)
self.__valid_date_time = YANGDynClass(base=[RestrictedClassType(base_type=six.text_type, restriction_dict={'pattern': '[0-9]{4}\\-(0[1-9]|1[0-2])\\-(0[1-9]|[12][0-9]|3[01])[Tt](0[0-9]|1[0-9]|2[0-3]):(0[0-9]|[1-5][0-9]):(0[0-9]|[1-5][0-9]|60)(\\.[0-9]+)?([Zz]|([+-](0[0-9]|1[0-9]|2[0-3]):(0[0-9]|[1-5][0-9])))'}),RestrictedClassType(base_type=six.text_type, restriction_type="dict_key", restriction_arg={'VALID_IMMEDIATELY': {}},),], default=six.text_type("VALID_IMMEDIATELY"), is_leaf=True, yang_name="valid-date-time", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='union', is_config=True)
self.__expiration_date_time = YANGDynClass(base=[RestrictedClassType(base_type=six.text_type, restriction_dict={'pattern': '[0-9]{4}\\-(0[1-9]|1[0-2])\\-(0[1-9]|[12][0-9]|3[01])[Tt](0[0-9]|1[0-9]|2[0-3]):(0[0-9]|[1-5][0-9]):(0[0-9]|[1-5][0-9]|60)(\\.[0-9]+)?([Zz]|([+-](0[0-9]|1[0-9]|2[0-3]):(0[0-9]|[1-5][0-9])))'}),RestrictedClassType(base_type=six.text_type, restriction_type="dict_key", restriction_arg={'NO_EXPIRATION': {}},),], default=six.text_type("NO_EXPIRATION"), is_leaf=True, yang_name="expiration-date-time", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='union', 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 ['macsec', 'mka', 'key-chains', 'key-chain', 'mka-keys', 'mka-key', 'config']
def _get_id(self):
"""
Getter method for id, mapped from YANG variable /macsec/mka/key_chains/key_chain/mka_keys/mka_key/config/id (oc-yang:hex-string)
YANG Description: Key identifier is used as the
Connectivity Association Key name (CKN)
"""
return self.__id
def _set_id(self, v, load=False):
"""
Setter method for id, mapped from YANG variable /macsec/mka/key_chains/key_chain/mka_keys/mka_key/config/id (oc-yang:hex-string)
If this variable is read-only (config: false) in the
source YANG file, then _set_id is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_id() directly.
YANG Description: Key identifier is used as the
Connectivity Association Key name (CKN)
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=RestrictedClassType(base_type=RestrictedClassType(base_type=six.text_type, restriction_dict={'pattern': '[0-9a-fA-F]*'}), restriction_dict={'length': ['1..64']}), is_leaf=True, yang_name="id", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:hex-string', is_config=True)
except (TypeError, ValueError):
raise ValueError({
'error-string': """id must be of a type compatible with oc-yang:hex-string""",
'defined-type': "oc-yang:hex-string",
'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=RestrictedClassType(base_type=six.text_type, restriction_dict={'pattern': '[0-9a-fA-F]*'}), restriction_dict={'length': ['1..64']}), is_leaf=True, yang_name="id", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:hex-string', is_config=True)""",
})
self.__id = t
if hasattr(self, '_set'):
self._set()
def _unset_id(self):
self.__id = YANGDynClass(base=RestrictedClassType(base_type=RestrictedClassType(base_type=six.text_type, restriction_dict={'pattern': '[0-9a-fA-F]*'}), restriction_dict={'length': ['1..64']}), is_leaf=True, yang_name="id", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:hex-string', is_config=True)
def _get_key_clear_text(self):
"""
Getter method for key_clear_text, mapped from YANG variable /macsec/mka/key_chains/key_chain/mka_keys/mka_key/config/key_clear_text (string)
YANG Description: The key, used for signing and encrypting. Supplied as a clear text
string. When read, also returned as clear text string.
"""
return self.__key_clear_text
def _set_key_clear_text(self, v, load=False):
"""
Setter method for key_clear_text, mapped from YANG variable /macsec/mka/key_chains/key_chain/mka_keys/mka_key/config/key_clear_text (string)
If this variable is read-only (config: false) in the
source YANG file, then _set_key_clear_text is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_key_clear_text() directly.
YANG Description: The key, used for signing and encrypting. Supplied as a clear text
string. When read, also returned as clear text string.
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=six.text_type, is_leaf=True, yang_name="key-clear-text", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='string', is_config=True)
except (TypeError, ValueError):
raise ValueError({
'error-string': """key_clear_text must be of a type compatible with string""",
'defined-type': "string",
'generated-type': """YANGDynClass(base=six.text_type, is_leaf=True, yang_name="key-clear-text", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='string', is_config=True)""",
})
self.__key_clear_text = t
if hasattr(self, '_set'):
self._set()
def _unset_key_clear_text(self):
self.__key_clear_text = YANGDynClass(base=six.text_type, is_leaf=True, yang_name="key-clear-text", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='string', is_config=True)
def _get_cryptographic_algorithm(self):
"""
Getter method for cryptographic_algorithm, mapped from YANG variable /macsec/mka/key_chains/key_chain/mka_keys/mka_key/config/cryptographic_algorithm (enumeration)
YANG Description: MKA Cryptographic authentication algorithm to use
"""
return self.__cryptographic_algorithm
def _set_cryptographic_algorithm(self, v, load=False):
"""
Setter method for cryptographic_algorithm, mapped from YANG variable /macsec/mka/key_chains/key_chain/mka_keys/mka_key/config/cryptographic_algorithm (enumeration)
If this variable is read-only (config: false) in the
source YANG file, then _set_cryptographic_algorithm is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_cryptographic_algorithm() directly.
YANG Description: MKA Cryptographic authentication algorithm to use
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=RestrictedClassType(base_type=six.text_type, restriction_type="dict_key", restriction_arg={'AES_128_CMAC': {}, 'AES_256_CMAC': {}},), is_leaf=True, yang_name="cryptographic-algorithm", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='enumeration', is_config=True)
except (TypeError, ValueError):
raise ValueError({
'error-string': """cryptographic_algorithm must be of a type compatible with enumeration""",
'defined-type': "openconfig-macsec:enumeration",
'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=six.text_type, restriction_type="dict_key", restriction_arg={'AES_128_CMAC': {}, 'AES_256_CMAC': {}},), is_leaf=True, yang_name="cryptographic-algorithm", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='enumeration', is_config=True)""",
})
self.__cryptographic_algorithm = t
if hasattr(self, '_set'):
self._set()
def _unset_cryptographic_algorithm(self):
self.__cryptographic_algorithm = YANGDynClass(base=RestrictedClassType(base_type=six.text_type, restriction_type="dict_key", restriction_arg={'AES_128_CMAC': {}, 'AES_256_CMAC': {}},), is_leaf=True, yang_name="cryptographic-algorithm", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='enumeration', is_config=True)
def _get_valid_date_time(self):
"""
Getter method for valid_date_time, mapped from YANG variable /macsec/mka/key_chains/key_chain/mka_keys/mka_key/config/valid_date_time (union)
YANG Description: Date and time the key starts being valid according to local date and
time configuration.
"""
return self.__valid_date_time
def _set_valid_date_time(self, v, load=False):
"""
Setter method for valid_date_time, mapped from YANG variable /macsec/mka/key_chains/key_chain/mka_keys/mka_key/config/valid_date_time (union)
If this variable is read-only (config: false) in the
source YANG file, then _set_valid_date_time is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_valid_date_time() directly.
YANG Description: Date and time the key starts being valid according to local date and
time configuration.
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=[RestrictedClassType(base_type=six.text_type, restriction_dict={'pattern': '[0-9]{4}\\-(0[1-9]|1[0-2])\\-(0[1-9]|[12][0-9]|3[01])[Tt](0[0-9]|1[0-9]|2[0-3]):(0[0-9]|[1-5][0-9]):(0[0-9]|[1-5][0-9]|60)(\\.[0-9]+)?([Zz]|([+-](0[0-9]|1[0-9]|2[0-3]):(0[0-9]|[1-5][0-9])))'}),RestrictedClassType(base_type=six.text_type, restriction_type="dict_key", restriction_arg={'VALID_IMMEDIATELY': {}},),], default=six.text_type("VALID_IMMEDIATELY"), is_leaf=True, yang_name="valid-date-time", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='union', is_config=True)
except (TypeError, ValueError):
raise ValueError({
'error-string': """valid_date_time must be of a type compatible with union""",
'defined-type': "openconfig-macsec:union",
'generated-type': """YANGDynClass(base=[RestrictedClassType(base_type=six.text_type, restriction_dict={'pattern': '[0-9]{4}\\-(0[1-9]|1[0-2])\\-(0[1-9]|[12][0-9]|3[01])[Tt](0[0-9]|1[0-9]|2[0-3]):(0[0-9]|[1-5][0-9]):(0[0-9]|[1-5][0-9]|60)(\\.[0-9]+)?([Zz]|([+-](0[0-9]|1[0-9]|2[0-3]):(0[0-9]|[1-5][0-9])))'}),RestrictedClassType(base_type=six.text_type, restriction_type="dict_key", restriction_arg={'VALID_IMMEDIATELY': {}},),], default=six.text_type("VALID_IMMEDIATELY"), is_leaf=True, yang_name="valid-date-time", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='union', is_config=True)""",
})
self.__valid_date_time = t
if hasattr(self, '_set'):
self._set()
def _unset_valid_date_time(self):
self.__valid_date_time = YANGDynClass(base=[RestrictedClassType(base_type=six.text_type, restriction_dict={'pattern': '[0-9]{4}\\-(0[1-9]|1[0-2])\\-(0[1-9]|[12][0-9]|3[01])[Tt](0[0-9]|1[0-9]|2[0-3]):(0[0-9]|[1-5][0-9]):(0[0-9]|[1-5][0-9]|60)(\\.[0-9]+)?([Zz]|([+-](0[0-9]|1[0-9]|2[0-3]):(0[0-9]|[1-5][0-9])))'}),RestrictedClassType(base_type=six.text_type, restriction_type="dict_key", restriction_arg={'VALID_IMMEDIATELY': {}},),], default=six.text_type("VALID_IMMEDIATELY"), is_leaf=True, yang_name="valid-date-time", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='union', is_config=True)
def _get_expiration_date_time(self):
"""
Getter method for expiration_date_time, mapped from YANG variable /macsec/mka/key_chains/key_chain/mka_keys/mka_key/config/expiration_date_time (union)
YANG Description: Key date and time expiration according to local date and time
configuration.
"""
return self.__expiration_date_time
def _set_expiration_date_time(self, v, load=False):
"""
Setter method for expiration_date_time, mapped from YANG variable /macsec/mka/key_chains/key_chain/mka_keys/mka_key/config/expiration_date_time (union)
If this variable is read-only (config: false) in the
source YANG file, then _set_expiration_date_time is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_expiration_date_time() directly.
YANG Description: Key date and time expiration according to local date and time
configuration.
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=[RestrictedClassType(base_type=six.text_type, restriction_dict={'pattern': '[0-9]{4}\\-(0[1-9]|1[0-2])\\-(0[1-9]|[12][0-9]|3[01])[Tt](0[0-9]|1[0-9]|2[0-3]):(0[0-9]|[1-5][0-9]):(0[0-9]|[1-5][0-9]|60)(\\.[0-9]+)?([Zz]|([+-](0[0-9]|1[0-9]|2[0-3]):(0[0-9]|[1-5][0-9])))'}),RestrictedClassType(base_type=six.text_type, restriction_type="dict_key", restriction_arg={'NO_EXPIRATION': {}},),], default=six.text_type("NO_EXPIRATION"), is_leaf=True, yang_name="expiration-date-time", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='union', is_config=True)
except (TypeError, ValueError):
raise ValueError({
'error-string': """expiration_date_time must be of a type compatible with union""",
'defined-type': "openconfig-macsec:union",
'generated-type': """YANGDynClass(base=[RestrictedClassType(base_type=six.text_type, restriction_dict={'pattern': '[0-9]{4}\\-(0[1-9]|1[0-2])\\-(0[1-9]|[12][0-9]|3[01])[Tt](0[0-9]|1[0-9]|2[0-3]):(0[0-9]|[1-5][0-9]):(0[0-9]|[1-5][0-9]|60)(\\.[0-9]+)?([Zz]|([+-](0[0-9]|1[0-9]|2[0-3]):(0[0-9]|[1-5][0-9])))'}),RestrictedClassType(base_type=six.text_type, restriction_type="dict_key", restriction_arg={'NO_EXPIRATION': {}},),], default=six.text_type("NO_EXPIRATION"), is_leaf=True, yang_name="expiration-date-time", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='union', is_config=True)""",
})
self.__expiration_date_time = t
if hasattr(self, '_set'):
self._set()
def _unset_expiration_date_time(self):
self.__expiration_date_time = YANGDynClass(base=[RestrictedClassType(base_type=six.text_type, restriction_dict={'pattern': '[0-9]{4}\\-(0[1-9]|1[0-2])\\-(0[1-9]|[12][0-9]|3[01])[Tt](0[0-9]|1[0-9]|2[0-3]):(0[0-9]|[1-5][0-9]):(0[0-9]|[1-5][0-9]|60)(\\.[0-9]+)?([Zz]|([+-](0[0-9]|1[0-9]|2[0-3]):(0[0-9]|[1-5][0-9])))'}),RestrictedClassType(base_type=six.text_type, restriction_type="dict_key", restriction_arg={'NO_EXPIRATION': {}},),], default=six.text_type("NO_EXPIRATION"), is_leaf=True, yang_name="expiration-date-time", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='union', is_config=True)
id = __builtin__.property(_get_id, _set_id)
key_clear_text = __builtin__.property(_get_key_clear_text, _set_key_clear_text)
cryptographic_algorithm = __builtin__.property(_get_cryptographic_algorithm, _set_cryptographic_algorithm)
valid_date_time = __builtin__.property(_get_valid_date_time, _set_valid_date_time)
expiration_date_time = __builtin__.property(_get_expiration_date_time, _set_expiration_date_time)
_pyangbind_elements = OrderedDict([('id', id), ('key_clear_text', key_clear_text), ('cryptographic_algorithm', cryptographic_algorithm), ('valid_date_time', valid_date_time), ('expiration_date_time', expiration_date_time), ])
class yc_state_openconfig_macsec__macsec_mka_key_chains_key_chain_mka_keys_mka_key_state(PybindBase):
"""
This class was auto-generated by the PythonClass plugin for PYANG
from YANG module openconfig-macsec - based on the path /macsec/mka/key-chains/key-chain/mka-keys/mka-key/state. Each member element of
the container is represented as a class variable - with a specific
YANG type.
YANG Description: Operational state data for MKA key
"""
__slots__ = ('_path_helper', '_extmethods', '__id','__key_clear_text','__cryptographic_algorithm','__valid_date_time','__expiration_date_time',)
_yang_name = 'state'
_yang_namespace = 'http://openconfig.net/yang/macsec'
_pybind_generated_by = 'container'
def __init__(self, *args, **kwargs):
self._path_helper = False
self._extmethods = False
self.__id = YANGDynClass(base=RestrictedClassType(base_type=RestrictedClassType(base_type=six.text_type, restriction_dict={'pattern': '[0-9a-fA-F]*'}), restriction_dict={'length': ['1..64']}), is_leaf=True, yang_name="id", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:hex-string', is_config=False)
self.__key_clear_text = YANGDynClass(base=six.text_type, is_leaf=True, yang_name="key-clear-text", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='string', is_config=False)
self.__cryptographic_algorithm = YANGDynClass(base=RestrictedClassType(base_type=six.text_type, restriction_type="dict_key", restriction_arg={'AES_128_CMAC': {}, 'AES_256_CMAC': {}},), is_leaf=True, yang_name="cryptographic-algorithm", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='enumeration', is_config=False)
self.__valid_date_time = YANGDynClass(base=[RestrictedClassType(base_type=six.text_type, restriction_dict={'pattern': '[0-9]{4}\\-(0[1-9]|1[0-2])\\-(0[1-9]|[12][0-9]|3[01])[Tt](0[0-9]|1[0-9]|2[0-3]):(0[0-9]|[1-5][0-9]):(0[0-9]|[1-5][0-9]|60)(\\.[0-9]+)?([Zz]|([+-](0[0-9]|1[0-9]|2[0-3]):(0[0-9]|[1-5][0-9])))'}),RestrictedClassType(base_type=six.text_type, restriction_type="dict_key", restriction_arg={'VALID_IMMEDIATELY': {}},),], default=six.text_type("VALID_IMMEDIATELY"), is_leaf=True, yang_name="valid-date-time", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='union', is_config=False)
self.__expiration_date_time = YANGDynClass(base=[RestrictedClassType(base_type=six.text_type, restriction_dict={'pattern': '[0-9]{4}\\-(0[1-9]|1[0-2])\\-(0[1-9]|[12][0-9]|3[01])[Tt](0[0-9]|1[0-9]|2[0-3]):(0[0-9]|[1-5][0-9]):(0[0-9]|[1-5][0-9]|60)(\\.[0-9]+)?([Zz]|([+-](0[0-9]|1[0-9]|2[0-3]):(0[0-9]|[1-5][0-9])))'}),RestrictedClassType(base_type=six.text_type, restriction_type="dict_key", restriction_arg={'NO_EXPIRATION': {}},),], default=six.text_type("NO_EXPIRATION"), is_leaf=True, yang_name="expiration-date-time", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='union', is_config=False)
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 ['macsec', 'mka', 'key-chains', 'key-chain', 'mka-keys', 'mka-key', 'state']
def _get_id(self):
"""
Getter method for id, mapped from YANG variable /macsec/mka/key_chains/key_chain/mka_keys/mka_key/state/id (oc-yang:hex-string)
YANG Description: Key identifier is used as the
Connectivity Association Key name (CKN)
"""
return self.__id
def _set_id(self, v, load=False):
"""
Setter method for id, mapped from YANG variable /macsec/mka/key_chains/key_chain/mka_keys/mka_key/state/id (oc-yang:hex-string)
If this variable is read-only (config: false) in the
source YANG file, then _set_id is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_id() directly.
YANG Description: Key identifier is used as the
Connectivity Association Key name (CKN)
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=RestrictedClassType(base_type=RestrictedClassType(base_type=six.text_type, restriction_dict={'pattern': '[0-9a-fA-F]*'}), restriction_dict={'length': ['1..64']}), is_leaf=True, yang_name="id", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:hex-string', is_config=False)
except (TypeError, ValueError):
raise ValueError({
'error-string': """id must be of a type compatible with oc-yang:hex-string""",
'defined-type': "oc-yang:hex-string",
'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=RestrictedClassType(base_type=six.text_type, restriction_dict={'pattern': '[0-9a-fA-F]*'}), restriction_dict={'length': ['1..64']}), is_leaf=True, yang_name="id", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:hex-string', is_config=False)""",
})
self.__id = t
if hasattr(self, '_set'):
self._set()
def _unset_id(self):
self.__id = YANGDynClass(base=RestrictedClassType(base_type=RestrictedClassType(base_type=six.text_type, restriction_dict={'pattern': '[0-9a-fA-F]*'}), restriction_dict={'length': ['1..64']}), is_leaf=True, yang_name="id", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:hex-string', is_config=False)
def _get_key_clear_text(self):
"""
Getter method for key_clear_text, mapped from YANG variable /macsec/mka/key_chains/key_chain/mka_keys/mka_key/state/key_clear_text (string)
YANG Description: The key, used for signing and encrypting. Supplied as a clear text
string. When read, also returned as clear text string.
"""
return self.__key_clear_text
def _set_key_clear_text(self, v, load=False):
"""
Setter method for key_clear_text, mapped from YANG variable /macsec/mka/key_chains/key_chain/mka_keys/mka_key/state/key_clear_text (string)
If this variable is read-only (config: false) in the
source YANG file, then _set_key_clear_text is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_key_clear_text() directly.
YANG Description: The key, used for signing and encrypting. Supplied as a clear text
string. When read, also returned as clear text string.
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=six.text_type, is_leaf=True, yang_name="key-clear-text", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='string', is_config=False)
except (TypeError, ValueError):
raise ValueError({
'error-string': """key_clear_text must be of a type compatible with string""",
'defined-type': "string",
'generated-type': """YANGDynClass(base=six.text_type, is_leaf=True, yang_name="key-clear-text", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='string', is_config=False)""",
})
self.__key_clear_text = t
if hasattr(self, '_set'):
self._set()
def _unset_key_clear_text(self):
self.__key_clear_text = YANGDynClass(base=six.text_type, is_leaf=True, yang_name="key-clear-text", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='string', is_config=False)
def _get_cryptographic_algorithm(self):
"""
Getter method for cryptographic_algorithm, mapped from YANG variable /macsec/mka/key_chains/key_chain/mka_keys/mka_key/state/cryptographic_algorithm (enumeration)
YANG Description: MKA Cryptographic authentication algorithm to use
"""
return self.__cryptographic_algorithm
def _set_cryptographic_algorithm(self, v, load=False):
"""
Setter method for cryptographic_algorithm, mapped from YANG variable /macsec/mka/key_chains/key_chain/mka_keys/mka_key/state/cryptographic_algorithm (enumeration)
If this variable is read-only (config: false) in the
source YANG file, then _set_cryptographic_algorithm is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_cryptographic_algorithm() directly.
YANG Description: MKA Cryptographic authentication algorithm to use
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=RestrictedClassType(base_type=six.text_type, restriction_type="dict_key", restriction_arg={'AES_128_CMAC': {}, 'AES_256_CMAC': {}},), is_leaf=True, yang_name="cryptographic-algorithm", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='enumeration', is_config=False)
except (TypeError, ValueError):
raise ValueError({
'error-string': """cryptographic_algorithm must be of a type compatible with enumeration""",
'defined-type': "openconfig-macsec:enumeration",
'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=six.text_type, restriction_type="dict_key", restriction_arg={'AES_128_CMAC': {}, 'AES_256_CMAC': {}},), is_leaf=True, yang_name="cryptographic-algorithm", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='enumeration', is_config=False)""",
})
self.__cryptographic_algorithm = t
if hasattr(self, '_set'):
self._set()
def _unset_cryptographic_algorithm(self):
self.__cryptographic_algorithm = YANGDynClass(base=RestrictedClassType(base_type=six.text_type, restriction_type="dict_key", restriction_arg={'AES_128_CMAC': {}, 'AES_256_CMAC': {}},), is_leaf=True, yang_name="cryptographic-algorithm", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='enumeration', is_config=False)
def _get_valid_date_time(self):
"""
Getter method for valid_date_time, mapped from YANG variable /macsec/mka/key_chains/key_chain/mka_keys/mka_key/state/valid_date_time (union)
YANG Description: Date and time the key starts being valid according to local date and
time configuration.
"""
return self.__valid_date_time
def _set_valid_date_time(self, v, load=False):
"""
Setter method for valid_date_time, mapped from YANG variable /macsec/mka/key_chains/key_chain/mka_keys/mka_key/state/valid_date_time (union)
If this variable is read-only (config: false) in the
source YANG file, then _set_valid_date_time is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_valid_date_time() directly.
YANG Description: Date and time the key starts being valid according to local date and
time configuration.
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=[RestrictedClassType(base_type=six.text_type, restriction_dict={'pattern': '[0-9]{4}\\-(0[1-9]|1[0-2])\\-(0[1-9]|[12][0-9]|3[01])[Tt](0[0-9]|1[0-9]|2[0-3]):(0[0-9]|[1-5][0-9]):(0[0-9]|[1-5][0-9]|60)(\\.[0-9]+)?([Zz]|([+-](0[0-9]|1[0-9]|2[0-3]):(0[0-9]|[1-5][0-9])))'}),RestrictedClassType(base_type=six.text_type, restriction_type="dict_key", restriction_arg={'VALID_IMMEDIATELY': {}},),], default=six.text_type("VALID_IMMEDIATELY"), is_leaf=True, yang_name="valid-date-time", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='union', is_config=False)
except (TypeError, ValueError):
raise ValueError({
'error-string': """valid_date_time must be of a type compatible with union""",
'defined-type': "openconfig-macsec:union",
'generated-type': """YANGDynClass(base=[RestrictedClassType(base_type=six.text_type, restriction_dict={'pattern': '[0-9]{4}\\-(0[1-9]|1[0-2])\\-(0[1-9]|[12][0-9]|3[01])[Tt](0[0-9]|1[0-9]|2[0-3]):(0[0-9]|[1-5][0-9]):(0[0-9]|[1-5][0-9]|60)(\\.[0-9]+)?([Zz]|([+-](0[0-9]|1[0-9]|2[0-3]):(0[0-9]|[1-5][0-9])))'}),RestrictedClassType(base_type=six.text_type, restriction_type="dict_key", restriction_arg={'VALID_IMMEDIATELY': {}},),], default=six.text_type("VALID_IMMEDIATELY"), is_leaf=True, yang_name="valid-date-time", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='union', is_config=False)""",
})
self.__valid_date_time = t
if hasattr(self, '_set'):
self._set()
def _unset_valid_date_time(self):
self.__valid_date_time = YANGDynClass(base=[RestrictedClassType(base_type=six.text_type, restriction_dict={'pattern': '[0-9]{4}\\-(0[1-9]|1[0-2])\\-(0[1-9]|[12][0-9]|3[01])[Tt](0[0-9]|1[0-9]|2[0-3]):(0[0-9]|[1-5][0-9]):(0[0-9]|[1-5][0-9]|60)(\\.[0-9]+)?([Zz]|([+-](0[0-9]|1[0-9]|2[0-3]):(0[0-9]|[1-5][0-9])))'}),RestrictedClassType(base_type=six.text_type, restriction_type="dict_key", restriction_arg={'VALID_IMMEDIATELY': {}},),], default=six.text_type("VALID_IMMEDIATELY"), is_leaf=True, yang_name="valid-date-time", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='union', is_config=False)
def _get_expiration_date_time(self):
"""
Getter method for expiration_date_time, mapped from YANG variable /macsec/mka/key_chains/key_chain/mka_keys/mka_key/state/expiration_date_time (union)
YANG Description: Key date and time expiration according to local date and time
configuration.
"""
return self.__expiration_date_time
def _set_expiration_date_time(self, v, load=False):
"""
Setter method for expiration_date_time, mapped from YANG variable /macsec/mka/key_chains/key_chain/mka_keys/mka_key/state/expiration_date_time (union)
If this variable is read-only (config: false) in the
source YANG file, then _set_expiration_date_time is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_expiration_date_time() directly.
YANG Description: Key date and time expiration according to local date and time
configuration.
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=[RestrictedClassType(base_type=six.text_type, restriction_dict={'pattern': '[0-9]{4}\\-(0[1-9]|1[0-2])\\-(0[1-9]|[12][0-9]|3[01])[Tt](0[0-9]|1[0-9]|2[0-3]):(0[0-9]|[1-5][0-9]):(0[0-9]|[1-5][0-9]|60)(\\.[0-9]+)?([Zz]|([+-](0[0-9]|1[0-9]|2[0-3]):(0[0-9]|[1-5][0-9])))'}),RestrictedClassType(base_type=six.text_type, restriction_type="dict_key", restriction_arg={'NO_EXPIRATION': {}},),], default=six.text_type("NO_EXPIRATION"), is_leaf=True, yang_name="expiration-date-time", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='union', is_config=False)
except (TypeError, ValueError):
raise ValueError({
'error-string': """expiration_date_time must be of a type compatible with union""",
'defined-type': "openconfig-macsec:union",
'generated-type': """YANGDynClass(base=[RestrictedClassType(base_type=six.text_type, restriction_dict={'pattern': '[0-9]{4}\\-(0[1-9]|1[0-2])\\-(0[1-9]|[12][0-9]|3[01])[Tt](0[0-9]|1[0-9]|2[0-3]):(0[0-9]|[1-5][0-9]):(0[0-9]|[1-5][0-9]|60)(\\.[0-9]+)?([Zz]|([+-](0[0-9]|1[0-9]|2[0-3]):(0[0-9]|[1-5][0-9])))'}),RestrictedClassType(base_type=six.text_type, restriction_type="dict_key", restriction_arg={'NO_EXPIRATION': {}},),], default=six.text_type("NO_EXPIRATION"), is_leaf=True, yang_name="expiration-date-time", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='union', is_config=False)""",
})
self.__expiration_date_time = t
if hasattr(self, '_set'):
self._set()
def _unset_expiration_date_time(self):
self.__expiration_date_time = YANGDynClass(base=[RestrictedClassType(base_type=six.text_type, restriction_dict={'pattern': '[0-9]{4}\\-(0[1-9]|1[0-2])\\-(0[1-9]|[12][0-9]|3[01])[Tt](0[0-9]|1[0-9]|2[0-3]):(0[0-9]|[1-5][0-9]):(0[0-9]|[1-5][0-9]|60)(\\.[0-9]+)?([Zz]|([+-](0[0-9]|1[0-9]|2[0-3]):(0[0-9]|[1-5][0-9])))'}),RestrictedClassType(base_type=six.text_type, restriction_type="dict_key", restriction_arg={'NO_EXPIRATION': {}},),], default=six.text_type("NO_EXPIRATION"), is_leaf=True, yang_name="expiration-date-time", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='union', is_config=False)
id = __builtin__.property(_get_id)
key_clear_text = __builtin__.property(_get_key_clear_text)
cryptographic_algorithm = __builtin__.property(_get_cryptographic_algorithm)
valid_date_time = __builtin__.property(_get_valid_date_time)
expiration_date_time = __builtin__.property(_get_expiration_date_time)
_pyangbind_elements = OrderedDict([('id', id), ('key_clear_text', key_clear_text), ('cryptographic_algorithm', cryptographic_algorithm), ('valid_date_time', valid_date_time), ('expiration_date_time', expiration_date_time), ])
class yc_mka_key_openconfig_macsec__macsec_mka_key_chains_key_chain_mka_keys_mka_key(PybindBase):
"""
This class was auto-generated by the PythonClass plugin for PYANG
from YANG module openconfig-macsec - based on the path /macsec/mka/key-chains/key-chain/mka-keys/mka-key. Each member element of
the container is represented as a class variable - with a specific
YANG type.
YANG Description: List of MKA keys
"""
__slots__ = ('_path_helper', '_extmethods', '__id','__config','__state',)
_yang_name = 'mka-key'
_yang_namespace = 'http://openconfig.net/yang/macsec'
_pybind_generated_by = 'container'
def __init__(self, *args, **kwargs):
self._path_helper = False
self._extmethods = False
self.__id = YANGDynClass(base=six.text_type, is_leaf=True, yang_name="id", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, is_keyval=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='leafref', is_config=True)
self.__config = YANGDynClass(base=yc_config_openconfig_macsec__macsec_mka_key_chains_key_chain_mka_keys_mka_key_config, is_container='container', yang_name="config", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True)
self.__state = YANGDynClass(base=yc_state_openconfig_macsec__macsec_mka_key_chains_key_chain_mka_keys_mka_key_state, is_container='container', yang_name="state", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', 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 ['macsec', 'mka', 'key-chains', 'key-chain', 'mka-keys', 'mka-key']
def _get_id(self):
"""
Getter method for id, mapped from YANG variable /macsec/mka/key_chains/key_chain/mka_keys/mka_key/id (leafref)
YANG Description: Reference to the MKA key id
"""
return self.__id
def _set_id(self, v, load=False):
"""
Setter method for id, mapped from YANG variable /macsec/mka/key_chains/key_chain/mka_keys/mka_key/id (leafref)
If this variable is read-only (config: false) in the
source YANG file, then _set_id is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_id() directly.
YANG Description: Reference to the MKA key id
"""
parent = getattr(self, "_parent", None)
if parent is not None and load is False:
raise AttributeError("Cannot set keys directly when" +
" within an instantiated list")
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=six.text_type, is_leaf=True, yang_name="id", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, is_keyval=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='leafref', is_config=True)
except (TypeError, ValueError):
raise ValueError({
'error-string': """id must be of a type compatible with leafref""",
'defined-type': "leafref",
'generated-type': """YANGDynClass(base=six.text_type, is_leaf=True, yang_name="id", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, is_keyval=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='leafref', is_config=True)""",
})
self.__id = t
if hasattr(self, '_set'):
self._set()
def _unset_id(self):
self.__id = YANGDynClass(base=six.text_type, is_leaf=True, yang_name="id", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, is_keyval=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='leafref', is_config=True)
def _get_config(self):
"""
Getter method for config, mapped from YANG variable /macsec/mka/key_chains/key_chain/mka_keys/mka_key/config (container)
YANG Description: Configuration of MKA key
"""
return self.__config
def _set_config(self, v, load=False):
"""
Setter method for config, mapped from YANG variable /macsec/mka/key_chains/key_chain/mka_keys/mka_key/config (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_config is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_config() directly.
YANG Description: Configuration of MKA key
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=yc_config_openconfig_macsec__macsec_mka_key_chains_key_chain_mka_keys_mka_key_config, is_container='container', yang_name="config", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True)
except (TypeError, ValueError):
raise ValueError({
'error-string': """config must be of a type compatible with container""",
'defined-type': "container",
'generated-type': """YANGDynClass(base=yc_config_openconfig_macsec__macsec_mka_key_chains_key_chain_mka_keys_mka_key_config, is_container='container', yang_name="config", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True)""",
})
self.__config = t
if hasattr(self, '_set'):
self._set()
def _unset_config(self):
self.__config = YANGDynClass(base=yc_config_openconfig_macsec__macsec_mka_key_chains_key_chain_mka_keys_mka_key_config, is_container='container', yang_name="config", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True)
def _get_state(self):
"""
Getter method for state, mapped from YANG variable /macsec/mka/key_chains/key_chain/mka_keys/mka_key/state (container)
YANG Description: Operational state data for MKA key
"""
return self.__state
def _set_state(self, v, load=False):
"""
Setter method for state, mapped from YANG variable /macsec/mka/key_chains/key_chain/mka_keys/mka_key/state (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_state is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_state() directly.
YANG Description: Operational state data for MKA key
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=yc_state_openconfig_macsec__macsec_mka_key_chains_key_chain_mka_keys_mka_key_state, is_container='container', yang_name="state", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True)
except (TypeError, ValueError):
raise ValueError({
'error-string': """state must be of a type compatible with container""",
'defined-type': "container",
'generated-type': """YANGDynClass(base=yc_state_openconfig_macsec__macsec_mka_key_chains_key_chain_mka_keys_mka_key_state, is_container='container', yang_name="state", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True)""",
})
self.__state = t
if hasattr(self, '_set'):
self._set()
def _unset_state(self):
self.__state = YANGDynClass(base=yc_state_openconfig_macsec__macsec_mka_key_chains_key_chain_mka_keys_mka_key_state, is_container='container', yang_name="state", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True)
id = __builtin__.property(_get_id, _set_id)
config = __builtin__.property(_get_config, _set_config)
state = __builtin__.property(_get_state, _set_state)
_pyangbind_elements = OrderedDict([('id', id), ('config', config), ('state', state), ])
class yc_mka_keys_openconfig_macsec__macsec_mka_key_chains_key_chain_mka_keys(PybindBase):
"""
This class was auto-generated by the PythonClass plugin for PYANG
from YANG module openconfig-macsec - based on the path /macsec/mka/key-chains/key-chain/mka-keys. Each member element of
the container is represented as a class variable - with a specific
YANG type.
YANG Description: Enclosing container for the list of MKA keys
"""
__slots__ = ('_path_helper', '_extmethods', '__mka_key',)
_yang_name = 'mka-keys'
_yang_namespace = 'http://openconfig.net/yang/macsec'
_pybind_generated_by = 'container'
def __init__(self, *args, **kwargs):
self._path_helper = False
self._extmethods = False
self.__mka_key = YANGDynClass(base=YANGListType("id",yc_mka_key_openconfig_macsec__macsec_mka_key_chains_key_chain_mka_keys_mka_key, yang_name="mka-key", parent=self, is_container='list', user_ordered=False, path_helper=self._path_helper, yang_keys='id', extensions=None), is_container='list', yang_name="mka-key", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='list', 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 ['macsec', 'mka', 'key-chains', 'key-chain', 'mka-keys']
def _get_mka_key(self):
"""
Getter method for mka_key, mapped from YANG variable /macsec/mka/key_chains/key_chain/mka_keys/mka_key (list)
YANG Description: List of MKA keys
"""
return self.__mka_key
def _set_mka_key(self, v, load=False):
"""
Setter method for mka_key, mapped from YANG variable /macsec/mka/key_chains/key_chain/mka_keys/mka_key (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_mka_key is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_mka_key() directly.
YANG Description: List of MKA keys
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=YANGListType("id",yc_mka_key_openconfig_macsec__macsec_mka_key_chains_key_chain_mka_keys_mka_key, yang_name="mka-key", parent=self, is_container='list', user_ordered=False, path_helper=self._path_helper, yang_keys='id', extensions=None), is_container='list', yang_name="mka-key", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='list', is_config=True)
except (TypeError, ValueError):
raise ValueError({
'error-string': """mka_key must be of a type compatible with list""",
'defined-type': "list",
'generated-type': """YANGDynClass(base=YANGListType("id",yc_mka_key_openconfig_macsec__macsec_mka_key_chains_key_chain_mka_keys_mka_key, yang_name="mka-key", parent=self, is_container='list', user_ordered=False, path_helper=self._path_helper, yang_keys='id', extensions=None), is_container='list', yang_name="mka-key", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='list', is_config=True)""",
})
self.__mka_key = t
if hasattr(self, '_set'):
self._set()
def _unset_mka_key(self):
self.__mka_key = YANGDynClass(base=YANGListType("id",yc_mka_key_openconfig_macsec__macsec_mka_key_chains_key_chain_mka_keys_mka_key, yang_name="mka-key", parent=self, is_container='list', user_ordered=False, path_helper=self._path_helper, yang_keys='id', extensions=None), is_container='list', yang_name="mka-key", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='list', is_config=True)
mka_key = __builtin__.property(_get_mka_key, _set_mka_key)
_pyangbind_elements = OrderedDict([('mka_key', mka_key), ])
class yc_key_chain_openconfig_macsec__macsec_mka_key_chains_key_chain(PybindBase):
"""
This class was auto-generated by the PythonClass plugin for PYANG
from YANG module openconfig-macsec - based on the path /macsec/mka/key-chains/key-chain. Each member element of
the container is represented as a class variable - with a specific
YANG type.
YANG Description: MKA Key chain name
"""
__slots__ = ('_path_helper', '_extmethods', '__name','__config','__state','__mka_keys',)
_yang_name = 'key-chain'
_yang_namespace = 'http://openconfig.net/yang/macsec'
_pybind_generated_by = 'container'
def __init__(self, *args, **kwargs):
self._path_helper = False
self._extmethods = False
self.__name = YANGDynClass(base=six.text_type, is_leaf=True, yang_name="name", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, is_keyval=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='leafref', is_config=True)
self.__config = YANGDynClass(base=yc_config_openconfig_macsec__macsec_mka_key_chains_key_chain_config, is_container='container', yang_name="config", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True)
self.__state = YANGDynClass(base=yc_state_openconfig_macsec__macsec_mka_key_chains_key_chain_state, is_container='container', yang_name="state", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True)
self.__mka_keys = YANGDynClass(base=yc_mka_keys_openconfig_macsec__macsec_mka_key_chains_key_chain_mka_keys, is_container='container', yang_name="mka-keys", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', 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 ['macsec', 'mka', 'key-chains', 'key-chain']
def _get_name(self):
"""
Getter method for name, mapped from YANG variable /macsec/mka/key_chains/key_chain/name (leafref)
YANG Description: Reference to the MKA Key chain name
"""
return self.__name
def _set_name(self, v, load=False):
"""
Setter method for name, mapped from YANG variable /macsec/mka/key_chains/key_chain/name (leafref)
If this variable is read-only (config: false) in the
source YANG file, then _set_name is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_name() directly.
YANG Description: Reference to the MKA Key chain name
"""
parent = getattr(self, "_parent", None)
if parent is not None and load is False:
raise AttributeError("Cannot set keys directly when" +
" within an instantiated list")
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=six.text_type, is_leaf=True, yang_name="name", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, is_keyval=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='leafref', is_config=True)
except (TypeError, ValueError):
raise ValueError({
'error-string': """name must be of a type compatible with leafref""",
'defined-type': "leafref",
'generated-type': """YANGDynClass(base=six.text_type, is_leaf=True, yang_name="name", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, is_keyval=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='leafref', is_config=True)""",
})
self.__name = t
if hasattr(self, '_set'):
self._set()
def _unset_name(self):
self.__name = YANGDynClass(base=six.text_type, is_leaf=True, yang_name="name", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, is_keyval=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='leafref', is_config=True)
def _get_config(self):
"""
Getter method for config, mapped from YANG variable /macsec/mka/key_chains/key_chain/config (container)
YANG Description: Configuration of the MKA key chain
"""
return self.__config
def _set_config(self, v, load=False):
"""
Setter method for config, mapped from YANG variable /macsec/mka/key_chains/key_chain/config (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_config is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_config() directly.
YANG Description: Configuration of the MKA key chain
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=yc_config_openconfig_macsec__macsec_mka_key_chains_key_chain_config, is_container='container', yang_name="config", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True)
except (TypeError, ValueError):
raise ValueError({
'error-string': """config must be of a type compatible with container""",
'defined-type': "container",
'generated-type': """YANGDynClass(base=yc_config_openconfig_macsec__macsec_mka_key_chains_key_chain_config, is_container='container', yang_name="config", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True)""",
})
self.__config = t
if hasattr(self, '_set'):
self._set()
def _unset_config(self):
self.__config = YANGDynClass(base=yc_config_openconfig_macsec__macsec_mka_key_chains_key_chain_config, is_container='container', yang_name="config", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True)
def _get_state(self):
"""
Getter method for state, mapped from YANG variable /macsec/mka/key_chains/key_chain/state (container)
YANG Description: Operational state data for MKA key chain
"""
return self.__state
def _set_state(self, v, load=False):
"""
Setter method for state, mapped from YANG variable /macsec/mka/key_chains/key_chain/state (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_state is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_state() directly.
YANG Description: Operational state data for MKA key chain
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=yc_state_openconfig_macsec__macsec_mka_key_chains_key_chain_state, is_container='container', yang_name="state", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True)
except (TypeError, ValueError):
raise ValueError({
'error-string': """state must be of a type compatible with container""",
'defined-type': "container",
'generated-type': """YANGDynClass(base=yc_state_openconfig_macsec__macsec_mka_key_chains_key_chain_state, is_container='container', yang_name="state", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True)""",
})
self.__state = t
if hasattr(self, '_set'):
self._set()
def _unset_state(self):
self.__state = YANGDynClass(base=yc_state_openconfig_macsec__macsec_mka_key_chains_key_chain_state, is_container='container', yang_name="state", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True)
def _get_mka_keys(self):
"""
Getter method for mka_keys, mapped from YANG variable /macsec/mka/key_chains/key_chain/mka_keys (container)
YANG Description: Enclosing container for the list of MKA keys
"""
return self.__mka_keys
def _set_mka_keys(self, v, load=False):
"""
Setter method for mka_keys, mapped from YANG variable /macsec/mka/key_chains/key_chain/mka_keys (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_mka_keys is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_mka_keys() directly.
YANG Description: Enclosing container for the list of MKA keys
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=yc_mka_keys_openconfig_macsec__macsec_mka_key_chains_key_chain_mka_keys, is_container='container', yang_name="mka-keys", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True)
except (TypeError, ValueError):
raise ValueError({
'error-string': """mka_keys must be of a type compatible with container""",
'defined-type': "container",
'generated-type': """YANGDynClass(base=yc_mka_keys_openconfig_macsec__macsec_mka_key_chains_key_chain_mka_keys, is_container='container', yang_name="mka-keys", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True)""",
})
self.__mka_keys = t
if hasattr(self, '_set'):
self._set()
def _unset_mka_keys(self):
self.__mka_keys = YANGDynClass(base=yc_mka_keys_openconfig_macsec__macsec_mka_key_chains_key_chain_mka_keys, is_container='container', yang_name="mka-keys", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True)
name = __builtin__.property(_get_name, _set_name)
config = __builtin__.property(_get_config, _set_config)
state = __builtin__.property(_get_state, _set_state)
mka_keys = __builtin__.property(_get_mka_keys, _set_mka_keys)
_pyangbind_elements = OrderedDict([('name', name), ('config', config), ('state', state), ('mka_keys', mka_keys), ])
class yc_key_chains_openconfig_macsec__macsec_mka_key_chains(PybindBase):
"""
This class was auto-generated by the PythonClass plugin for PYANG
from YANG module openconfig-macsec - based on the path /macsec/mka/key-chains. Each member element of
the container is represented as a class variable - with a specific
YANG type.
YANG Description: Enclosing container for the MKA key chains
"""
__slots__ = ('_path_helper', '_extmethods', '__key_chain',)
_yang_name = 'key-chains'
_yang_namespace = 'http://openconfig.net/yang/macsec'
_pybind_generated_by = 'container'
def __init__(self, *args, **kwargs):
self._path_helper = False
self._extmethods = False
self.__key_chain = YANGDynClass(base=YANGListType("name",yc_key_chain_openconfig_macsec__macsec_mka_key_chains_key_chain, yang_name="key-chain", parent=self, is_container='list', user_ordered=False, path_helper=self._path_helper, yang_keys='name', extensions=None), is_container='list', yang_name="key-chain", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='list', 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 ['macsec', 'mka', 'key-chains']
def _get_key_chain(self):
"""
Getter method for key_chain, mapped from YANG variable /macsec/mka/key_chains/key_chain (list)
YANG Description: MKA Key chain name
"""
return self.__key_chain
def _set_key_chain(self, v, load=False):
"""
Setter method for key_chain, mapped from YANG variable /macsec/mka/key_chains/key_chain (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_key_chain is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_key_chain() directly.
YANG Description: MKA Key chain name
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=YANGListType("name",yc_key_chain_openconfig_macsec__macsec_mka_key_chains_key_chain, yang_name="key-chain", parent=self, is_container='list', user_ordered=False, path_helper=self._path_helper, yang_keys='name', extensions=None), is_container='list', yang_name="key-chain", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='list', is_config=True)
except (TypeError, ValueError):
raise ValueError({
'error-string': """key_chain must be of a type compatible with list""",
'defined-type': "list",
'generated-type': """YANGDynClass(base=YANGListType("name",yc_key_chain_openconfig_macsec__macsec_mka_key_chains_key_chain, yang_name="key-chain", parent=self, is_container='list', user_ordered=False, path_helper=self._path_helper, yang_keys='name', extensions=None), is_container='list', yang_name="key-chain", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='list', is_config=True)""",
})
self.__key_chain = t
if hasattr(self, '_set'):
self._set()
def _unset_key_chain(self):
self.__key_chain = YANGDynClass(base=YANGListType("name",yc_key_chain_openconfig_macsec__macsec_mka_key_chains_key_chain, yang_name="key-chain", parent=self, is_container='list', user_ordered=False, path_helper=self._path_helper, yang_keys='name', extensions=None), is_container='list', yang_name="key-chain", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='list', is_config=True)
key_chain = __builtin__.property(_get_key_chain, _set_key_chain)
_pyangbind_elements = OrderedDict([('key_chain', key_chain), ])
class yc_counters_openconfig_macsec__macsec_mka_state_counters(PybindBase):
"""
This class was auto-generated by the PythonClass plugin for PYANG
from YANG module openconfig-macsec - based on the path /macsec/mka/state/counters. Each member element of
the container is represented as a class variable - with a specific
YANG type.
YANG Description: MKA global counters
"""
__slots__ = ('_path_helper', '_extmethods', '__out_mkpdu_errors','__in_mkpdu_icv_verification_errors','__in_mkpdu_validation_errors','__in_mkpdu_bad_peer_errors','__in_mkpdu_peer_list_errors','__sak_generation_errors','__sak_hash_errors','__sak_encryption_errors','__sak_decryption_errors','__sak_cipher_mismatch_errors',)
_yang_name = 'counters'
_yang_namespace = 'http://openconfig.net/yang/macsec'
_pybind_generated_by = 'container'
def __init__(self, *args, **kwargs):
self._path_helper = False
self._extmethods = False
self.__out_mkpdu_errors = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="out-mkpdu-errors", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)
self.__in_mkpdu_icv_verification_errors = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="in-mkpdu-icv-verification-errors", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)
self.__in_mkpdu_validation_errors = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="in-mkpdu-validation-errors", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)
self.__in_mkpdu_bad_peer_errors = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="in-mkpdu-bad-peer-errors", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)
self.__in_mkpdu_peer_list_errors = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="in-mkpdu-peer-list-errors", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)
self.__sak_generation_errors = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="sak-generation-errors", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)
self.__sak_hash_errors = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="sak-hash-errors", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)
self.__sak_encryption_errors = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="sak-encryption-errors", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)
self.__sak_decryption_errors = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="sak-decryption-errors", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)
self.__sak_cipher_mismatch_errors = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="sak-cipher-mismatch-errors", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)
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 ['macsec', 'mka', 'state', 'counters']
def _get_out_mkpdu_errors(self):
"""
Getter method for out_mkpdu_errors, mapped from YANG variable /macsec/mka/state/counters/out_mkpdu_errors (oc-yang:counter64)
YANG Description: MKPDU TX error count
"""
return self.__out_mkpdu_errors
def _set_out_mkpdu_errors(self, v, load=False):
"""
Setter method for out_mkpdu_errors, mapped from YANG variable /macsec/mka/state/counters/out_mkpdu_errors (oc-yang:counter64)
If this variable is read-only (config: false) in the
source YANG file, then _set_out_mkpdu_errors is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_out_mkpdu_errors() directly.
YANG Description: MKPDU TX error count
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="out-mkpdu-errors", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)
except (TypeError, ValueError):
raise ValueError({
'error-string': """out_mkpdu_errors must be of a type compatible with oc-yang:counter64""",
'defined-type': "oc-yang:counter64",
'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="out-mkpdu-errors", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)""",
})
self.__out_mkpdu_errors = t
if hasattr(self, '_set'):
self._set()
def _unset_out_mkpdu_errors(self):
self.__out_mkpdu_errors = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="out-mkpdu-errors", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)
def _get_in_mkpdu_icv_verification_errors(self):
"""
Getter method for in_mkpdu_icv_verification_errors, mapped from YANG variable /macsec/mka/state/counters/in_mkpdu_icv_verification_errors (oc-yang:counter64)
YANG Description: MKPDU RX ICV verification error count
"""
return self.__in_mkpdu_icv_verification_errors
def _set_in_mkpdu_icv_verification_errors(self, v, load=False):
"""
Setter method for in_mkpdu_icv_verification_errors, mapped from YANG variable /macsec/mka/state/counters/in_mkpdu_icv_verification_errors (oc-yang:counter64)
If this variable is read-only (config: false) in the
source YANG file, then _set_in_mkpdu_icv_verification_errors is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_in_mkpdu_icv_verification_errors() directly.
YANG Description: MKPDU RX ICV verification error count
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="in-mkpdu-icv-verification-errors", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)
except (TypeError, ValueError):
raise ValueError({
'error-string': """in_mkpdu_icv_verification_errors must be of a type compatible with oc-yang:counter64""",
'defined-type': "oc-yang:counter64",
'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="in-mkpdu-icv-verification-errors", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)""",
})
self.__in_mkpdu_icv_verification_errors = t
if hasattr(self, '_set'):
self._set()
def _unset_in_mkpdu_icv_verification_errors(self):
self.__in_mkpdu_icv_verification_errors = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="in-mkpdu-icv-verification-errors", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)
def _get_in_mkpdu_validation_errors(self):
"""
Getter method for in_mkpdu_validation_errors, mapped from YANG variable /macsec/mka/state/counters/in_mkpdu_validation_errors (oc-yang:counter64)
YANG Description: MKPDU RX validation error count
"""
return self.__in_mkpdu_validation_errors
def _set_in_mkpdu_validation_errors(self, v, load=False):
"""
Setter method for in_mkpdu_validation_errors, mapped from YANG variable /macsec/mka/state/counters/in_mkpdu_validation_errors (oc-yang:counter64)
If this variable is read-only (config: false) in the
source YANG file, then _set_in_mkpdu_validation_errors is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_in_mkpdu_validation_errors() directly.
YANG Description: MKPDU RX validation error count
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="in-mkpdu-validation-errors", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)
except (TypeError, ValueError):
raise ValueError({
'error-string': """in_mkpdu_validation_errors must be of a type compatible with oc-yang:counter64""",
'defined-type': "oc-yang:counter64",
'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="in-mkpdu-validation-errors", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)""",
})
self.__in_mkpdu_validation_errors = t
if hasattr(self, '_set'):
self._set()
def _unset_in_mkpdu_validation_errors(self):
self.__in_mkpdu_validation_errors = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="in-mkpdu-validation-errors", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)
def _get_in_mkpdu_bad_peer_errors(self):
"""
Getter method for in_mkpdu_bad_peer_errors, mapped from YANG variable /macsec/mka/state/counters/in_mkpdu_bad_peer_errors (oc-yang:counter64)
YANG Description: MKPDU RX bad peer message number error count
"""
return self.__in_mkpdu_bad_peer_errors
def _set_in_mkpdu_bad_peer_errors(self, v, load=False):
"""
Setter method for in_mkpdu_bad_peer_errors, mapped from YANG variable /macsec/mka/state/counters/in_mkpdu_bad_peer_errors (oc-yang:counter64)
If this variable is read-only (config: false) in the
source YANG file, then _set_in_mkpdu_bad_peer_errors is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_in_mkpdu_bad_peer_errors() directly.
YANG Description: MKPDU RX bad peer message number error count
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="in-mkpdu-bad-peer-errors", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)
except (TypeError, ValueError):
raise ValueError({
'error-string': """in_mkpdu_bad_peer_errors must be of a type compatible with oc-yang:counter64""",
'defined-type': "oc-yang:counter64",
'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="in-mkpdu-bad-peer-errors", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)""",
})
self.__in_mkpdu_bad_peer_errors = t
if hasattr(self, '_set'):
self._set()
def _unset_in_mkpdu_bad_peer_errors(self):
self.__in_mkpdu_bad_peer_errors = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="in-mkpdu-bad-peer-errors", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)
def _get_in_mkpdu_peer_list_errors(self):
"""
Getter method for in_mkpdu_peer_list_errors, mapped from YANG variable /macsec/mka/state/counters/in_mkpdu_peer_list_errors (oc-yang:counter64)
YANG Description: MKPDU RX non-recent peer list Message Number error count
"""
return self.__in_mkpdu_peer_list_errors
def _set_in_mkpdu_peer_list_errors(self, v, load=False):
"""
Setter method for in_mkpdu_peer_list_errors, mapped from YANG variable /macsec/mka/state/counters/in_mkpdu_peer_list_errors (oc-yang:counter64)
If this variable is read-only (config: false) in the
source YANG file, then _set_in_mkpdu_peer_list_errors is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_in_mkpdu_peer_list_errors() directly.
YANG Description: MKPDU RX non-recent peer list Message Number error count
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="in-mkpdu-peer-list-errors", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)
except (TypeError, ValueError):
raise ValueError({
'error-string': """in_mkpdu_peer_list_errors must be of a type compatible with oc-yang:counter64""",
'defined-type': "oc-yang:counter64",
'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="in-mkpdu-peer-list-errors", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)""",
})
self.__in_mkpdu_peer_list_errors = t
if hasattr(self, '_set'):
self._set()
def _unset_in_mkpdu_peer_list_errors(self):
self.__in_mkpdu_peer_list_errors = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="in-mkpdu-peer-list-errors", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)
def _get_sak_generation_errors(self):
"""
Getter method for sak_generation_errors, mapped from YANG variable /macsec/mka/state/counters/sak_generation_errors (oc-yang:counter64)
YANG Description: MKA error SAK generation count
"""
return self.__sak_generation_errors
def _set_sak_generation_errors(self, v, load=False):
"""
Setter method for sak_generation_errors, mapped from YANG variable /macsec/mka/state/counters/sak_generation_errors (oc-yang:counter64)
If this variable is read-only (config: false) in the
source YANG file, then _set_sak_generation_errors is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_sak_generation_errors() directly.
YANG Description: MKA error SAK generation count
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="sak-generation-errors", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)
except (TypeError, ValueError):
raise ValueError({
'error-string': """sak_generation_errors must be of a type compatible with oc-yang:counter64""",
'defined-type': "oc-yang:counter64",
'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="sak-generation-errors", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)""",
})
self.__sak_generation_errors = t
if hasattr(self, '_set'):
self._set()
def _unset_sak_generation_errors(self):
self.__sak_generation_errors = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="sak-generation-errors", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)
def _get_sak_hash_errors(self):
"""
Getter method for sak_hash_errors, mapped from YANG variable /macsec/mka/state/counters/sak_hash_errors (oc-yang:counter64)
YANG Description: MKA error Hash Key generation count
"""
return self.__sak_hash_errors
def _set_sak_hash_errors(self, v, load=False):
"""
Setter method for sak_hash_errors, mapped from YANG variable /macsec/mka/state/counters/sak_hash_errors (oc-yang:counter64)
If this variable is read-only (config: false) in the
source YANG file, then _set_sak_hash_errors is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_sak_hash_errors() directly.
YANG Description: MKA error Hash Key generation count
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="sak-hash-errors", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)
except (TypeError, ValueError):
raise ValueError({
'error-string': """sak_hash_errors must be of a type compatible with oc-yang:counter64""",
'defined-type': "oc-yang:counter64",
'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="sak-hash-errors", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)""",
})
self.__sak_hash_errors = t
if hasattr(self, '_set'):
self._set()
def _unset_sak_hash_errors(self):
self.__sak_hash_errors = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="sak-hash-errors", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)
def _get_sak_encryption_errors(self):
"""
Getter method for sak_encryption_errors, mapped from YANG variable /macsec/mka/state/counters/sak_encryption_errors (oc-yang:counter64)
YANG Description: MKA error SAK encryption/wrap count
"""
return self.__sak_encryption_errors
def _set_sak_encryption_errors(self, v, load=False):
"""
Setter method for sak_encryption_errors, mapped from YANG variable /macsec/mka/state/counters/sak_encryption_errors (oc-yang:counter64)
If this variable is read-only (config: false) in the
source YANG file, then _set_sak_encryption_errors is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_sak_encryption_errors() directly.
YANG Description: MKA error SAK encryption/wrap count
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="sak-encryption-errors", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)
except (TypeError, ValueError):
raise ValueError({
'error-string': """sak_encryption_errors must be of a type compatible with oc-yang:counter64""",
'defined-type': "oc-yang:counter64",
'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="sak-encryption-errors", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)""",
})
self.__sak_encryption_errors = t
if hasattr(self, '_set'):
self._set()
def _unset_sak_encryption_errors(self):
self.__sak_encryption_errors = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="sak-encryption-errors", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)
def _get_sak_decryption_errors(self):
"""
Getter method for sak_decryption_errors, mapped from YANG variable /macsec/mka/state/counters/sak_decryption_errors (oc-yang:counter64)
YANG Description: MKA error SAK decryption/unwrap count
"""
return self.__sak_decryption_errors
def _set_sak_decryption_errors(self, v, load=False):
"""
Setter method for sak_decryption_errors, mapped from YANG variable /macsec/mka/state/counters/sak_decryption_errors (oc-yang:counter64)
If this variable is read-only (config: false) in the
source YANG file, then _set_sak_decryption_errors is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_sak_decryption_errors() directly.
YANG Description: MKA error SAK decryption/unwrap count
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="sak-decryption-errors", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)
except (TypeError, ValueError):
raise ValueError({
'error-string': """sak_decryption_errors must be of a type compatible with oc-yang:counter64""",
'defined-type': "oc-yang:counter64",
'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="sak-decryption-errors", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)""",
})
self.__sak_decryption_errors = t
if hasattr(self, '_set'):
self._set()
def _unset_sak_decryption_errors(self):
self.__sak_decryption_errors = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="sak-decryption-errors", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)
def _get_sak_cipher_mismatch_errors(self):
"""
Getter method for sak_cipher_mismatch_errors, mapped from YANG variable /macsec/mka/state/counters/sak_cipher_mismatch_errors (oc-yang:counter64)
YANG Description: MKA error SAK cipher mismatch count
"""
return self.__sak_cipher_mismatch_errors
def _set_sak_cipher_mismatch_errors(self, v, load=False):
"""
Setter method for sak_cipher_mismatch_errors, mapped from YANG variable /macsec/mka/state/counters/sak_cipher_mismatch_errors (oc-yang:counter64)
If this variable is read-only (config: false) in the
source YANG file, then _set_sak_cipher_mismatch_errors is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_sak_cipher_mismatch_errors() directly.
YANG Description: MKA error SAK cipher mismatch count
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="sak-cipher-mismatch-errors", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)
except (TypeError, ValueError):
raise ValueError({
'error-string': """sak_cipher_mismatch_errors must be of a type compatible with oc-yang:counter64""",
'defined-type': "oc-yang:counter64",
'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="sak-cipher-mismatch-errors", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)""",
})
self.__sak_cipher_mismatch_errors = t
if hasattr(self, '_set'):
self._set()
def _unset_sak_cipher_mismatch_errors(self):
self.__sak_cipher_mismatch_errors = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="sak-cipher-mismatch-errors", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)
out_mkpdu_errors = __builtin__.property(_get_out_mkpdu_errors)
in_mkpdu_icv_verification_errors = __builtin__.property(_get_in_mkpdu_icv_verification_errors)
in_mkpdu_validation_errors = __builtin__.property(_get_in_mkpdu_validation_errors)
in_mkpdu_bad_peer_errors = __builtin__.property(_get_in_mkpdu_bad_peer_errors)
in_mkpdu_peer_list_errors = __builtin__.property(_get_in_mkpdu_peer_list_errors)
sak_generation_errors = __builtin__.property(_get_sak_generation_errors)
sak_hash_errors = __builtin__.property(_get_sak_hash_errors)
sak_encryption_errors = __builtin__.property(_get_sak_encryption_errors)
sak_decryption_errors = __builtin__.property(_get_sak_decryption_errors)
sak_cipher_mismatch_errors = __builtin__.property(_get_sak_cipher_mismatch_errors)
_pyangbind_elements = OrderedDict([('out_mkpdu_errors', out_mkpdu_errors), ('in_mkpdu_icv_verification_errors', in_mkpdu_icv_verification_errors), ('in_mkpdu_validation_errors', in_mkpdu_validation_errors), ('in_mkpdu_bad_peer_errors', in_mkpdu_bad_peer_errors), ('in_mkpdu_peer_list_errors', in_mkpdu_peer_list_errors), ('sak_generation_errors', sak_generation_errors), ('sak_hash_errors', sak_hash_errors), ('sak_encryption_errors', sak_encryption_errors), ('sak_decryption_errors', sak_decryption_errors), ('sak_cipher_mismatch_errors', sak_cipher_mismatch_errors), ])
class yc_state_openconfig_macsec__macsec_mka_state(PybindBase):
"""
This class was auto-generated by the PythonClass plugin for PYANG
from YANG module openconfig-macsec - based on the path /macsec/mka/state. Each member element of
the container is represented as a class variable - with a specific
YANG type.
YANG Description: Operational state data for MKA
"""
__slots__ = ('_path_helper', '_extmethods', '__counters',)
_yang_name = 'state'
_yang_namespace = 'http://openconfig.net/yang/macsec'
_pybind_generated_by = 'container'
def __init__(self, *args, **kwargs):
self._path_helper = False
self._extmethods = False
self.__counters = YANGDynClass(base=yc_counters_openconfig_macsec__macsec_mka_state_counters, is_container='container', yang_name="counters", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=False)
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 ['macsec', 'mka', 'state']
def _get_counters(self):
"""
Getter method for counters, mapped from YANG variable /macsec/mka/state/counters (container)
YANG Description: MKA global counters
"""
return self.__counters
def _set_counters(self, v, load=False):
"""
Setter method for counters, mapped from YANG variable /macsec/mka/state/counters (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_counters is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_counters() directly.
YANG Description: MKA global counters
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=yc_counters_openconfig_macsec__macsec_mka_state_counters, is_container='container', yang_name="counters", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=False)
except (TypeError, ValueError):
raise ValueError({
'error-string': """counters must be of a type compatible with container""",
'defined-type': "container",
'generated-type': """YANGDynClass(base=yc_counters_openconfig_macsec__macsec_mka_state_counters, is_container='container', yang_name="counters", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=False)""",
})
self.__counters = t
if hasattr(self, '_set'):
self._set()
def _unset_counters(self):
self.__counters = YANGDynClass(base=yc_counters_openconfig_macsec__macsec_mka_state_counters, is_container='container', yang_name="counters", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=False)
counters = __builtin__.property(_get_counters)
_pyangbind_elements = OrderedDict([('counters', counters), ])
class yc_mka_openconfig_macsec__macsec_mka(PybindBase):
"""
This class was auto-generated by the PythonClass plugin for PYANG
from YANG module openconfig-macsec - based on the path /macsec/mka. Each member element of
the container is represented as a class variable - with a specific
YANG type.
YANG Description: The MKA
"""
__slots__ = ('_path_helper', '_extmethods', '__policies','__key_chains','__state',)
_yang_name = 'mka'
_yang_namespace = 'http://openconfig.net/yang/macsec'
_pybind_generated_by = 'container'
def __init__(self, *args, **kwargs):
self._path_helper = False
self._extmethods = False
self.__policies = YANGDynClass(base=yc_policies_openconfig_macsec__macsec_mka_policies, is_container='container', yang_name="policies", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True)
self.__key_chains = YANGDynClass(base=yc_key_chains_openconfig_macsec__macsec_mka_key_chains, is_container='container', yang_name="key-chains", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True)
self.__state = YANGDynClass(base=yc_state_openconfig_macsec__macsec_mka_state, is_container='container', yang_name="state", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', 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 ['macsec', 'mka']
def _get_policies(self):
"""
Getter method for policies, mapped from YANG variable /macsec/mka/policies (container)
YANG Description: Enclosing container for the list of MKA policies
"""
return self.__policies
def _set_policies(self, v, load=False):
"""
Setter method for policies, mapped from YANG variable /macsec/mka/policies (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_policies is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_policies() directly.
YANG Description: Enclosing container for the list of MKA policies
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=yc_policies_openconfig_macsec__macsec_mka_policies, is_container='container', yang_name="policies", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True)
except (TypeError, ValueError):
raise ValueError({
'error-string': """policies must be of a type compatible with container""",
'defined-type': "container",
'generated-type': """YANGDynClass(base=yc_policies_openconfig_macsec__macsec_mka_policies, is_container='container', yang_name="policies", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True)""",
})
self.__policies = t
if hasattr(self, '_set'):
self._set()
def _unset_policies(self):
self.__policies = YANGDynClass(base=yc_policies_openconfig_macsec__macsec_mka_policies, is_container='container', yang_name="policies", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True)
def _get_key_chains(self):
"""
Getter method for key_chains, mapped from YANG variable /macsec/mka/key_chains (container)
YANG Description: Enclosing container for the MKA key chains
"""
return self.__key_chains
def _set_key_chains(self, v, load=False):
"""
Setter method for key_chains, mapped from YANG variable /macsec/mka/key_chains (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_key_chains is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_key_chains() directly.
YANG Description: Enclosing container for the MKA key chains
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=yc_key_chains_openconfig_macsec__macsec_mka_key_chains, is_container='container', yang_name="key-chains", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True)
except (TypeError, ValueError):
raise ValueError({
'error-string': """key_chains must be of a type compatible with container""",
'defined-type': "container",
'generated-type': """YANGDynClass(base=yc_key_chains_openconfig_macsec__macsec_mka_key_chains, is_container='container', yang_name="key-chains", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True)""",
})
self.__key_chains = t
if hasattr(self, '_set'):
self._set()
def _unset_key_chains(self):
self.__key_chains = YANGDynClass(base=yc_key_chains_openconfig_macsec__macsec_mka_key_chains, is_container='container', yang_name="key-chains", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True)
def _get_state(self):
"""
Getter method for state, mapped from YANG variable /macsec/mka/state (container)
YANG Description: Operational state data for MKA
"""
return self.__state
def _set_state(self, v, load=False):
"""
Setter method for state, mapped from YANG variable /macsec/mka/state (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_state is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_state() directly.
YANG Description: Operational state data for MKA
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=yc_state_openconfig_macsec__macsec_mka_state, is_container='container', yang_name="state", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True)
except (TypeError, ValueError):
raise ValueError({
'error-string': """state must be of a type compatible with container""",
'defined-type': "container",
'generated-type': """YANGDynClass(base=yc_state_openconfig_macsec__macsec_mka_state, is_container='container', yang_name="state", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True)""",
})
self.__state = t
if hasattr(self, '_set'):
self._set()
def _unset_state(self):
self.__state = YANGDynClass(base=yc_state_openconfig_macsec__macsec_mka_state, is_container='container', yang_name="state", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True)
policies = __builtin__.property(_get_policies, _set_policies)
key_chains = __builtin__.property(_get_key_chains, _set_key_chains)
state = __builtin__.property(_get_state, _set_state)
_pyangbind_elements = OrderedDict([('policies', policies), ('key_chains', key_chains), ('state', state), ])
class yc_config_openconfig_macsec__macsec_interfaces_interface_config(PybindBase):
"""
This class was auto-generated by the PythonClass plugin for PYANG
from YANG module openconfig-macsec - based on the path /macsec/interfaces/interface/config. Each member element of
the container is represented as a class variable - with a specific
YANG type.
YANG Description: Configuration data for MACsec on each interface
"""
__slots__ = ('_path_helper', '_extmethods', '__name','__enable','__replay_protection',)
_yang_name = 'config'
_yang_namespace = 'http://openconfig.net/yang/macsec'
_pybind_generated_by = 'container'
def __init__(self, *args, **kwargs):
self._path_helper = False
self._extmethods = False
self.__name = YANGDynClass(base=six.text_type, is_leaf=True, yang_name="name", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-if:base-interface-ref', is_config=True)
self.__enable = YANGDynClass(base=YANGBool, default=YANGBool("false"), is_leaf=True, yang_name="enable", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='boolean', is_config=True)
self.__replay_protection = YANGDynClass(base=RestrictedClassType(base_type=int, restriction_dict={'range': ['0..65535']},int_size=16), default=RestrictedClassType(base_type=int, restriction_dict={'range': ['0..65535']},int_size=16)(0), is_leaf=True, yang_name="replay-protection", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='uint16', 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 ['macsec', 'interfaces', 'interface', 'config']
def _get_name(self):
"""
Getter method for name, mapped from YANG variable /macsec/interfaces/interface/config/name (oc-if:base-interface-ref)
YANG Description: Reference to the MACsec Ethernet interface
"""
return self.__name
def _set_name(self, v, load=False):
"""
Setter method for name, mapped from YANG variable /macsec/interfaces/interface/config/name (oc-if:base-interface-ref)
If this variable is read-only (config: false) in the
source YANG file, then _set_name is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_name() directly.
YANG Description: Reference to the MACsec Ethernet interface
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=six.text_type, is_leaf=True, yang_name="name", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-if:base-interface-ref', is_config=True)
except (TypeError, ValueError):
raise ValueError({
'error-string': """name must be of a type compatible with oc-if:base-interface-ref""",
'defined-type': "oc-if:base-interface-ref",
'generated-type': """YANGDynClass(base=six.text_type, is_leaf=True, yang_name="name", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-if:base-interface-ref', is_config=True)""",
})
self.__name = t
if hasattr(self, '_set'):
self._set()
def _unset_name(self):
self.__name = YANGDynClass(base=six.text_type, is_leaf=True, yang_name="name", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-if:base-interface-ref', is_config=True)
def _get_enable(self):
"""
Getter method for enable, mapped from YANG variable /macsec/interfaces/interface/config/enable (boolean)
YANG Description: Enable MACsec on an interface
"""
return self.__enable
def _set_enable(self, v, load=False):
"""
Setter method for enable, mapped from YANG variable /macsec/interfaces/interface/config/enable (boolean)
If this variable is read-only (config: false) in the
source YANG file, then _set_enable is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_enable() directly.
YANG Description: Enable MACsec on an interface
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=YANGBool, default=YANGBool("false"), is_leaf=True, yang_name="enable", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='boolean', is_config=True)
except (TypeError, ValueError):
raise ValueError({
'error-string': """enable must be of a type compatible with boolean""",
'defined-type': "boolean",
'generated-type': """YANGDynClass(base=YANGBool, default=YANGBool("false"), is_leaf=True, yang_name="enable", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='boolean', is_config=True)""",
})
self.__enable = t
if hasattr(self, '_set'):
self._set()
def _unset_enable(self):
self.__enable = YANGDynClass(base=YANGBool, default=YANGBool("false"), is_leaf=True, yang_name="enable", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='boolean', is_config=True)
def _get_replay_protection(self):
"""
Getter method for replay_protection, mapped from YANG variable /macsec/interfaces/interface/config/replay_protection (uint16)
YANG Description: MACsec window size, as defined by the number of out-of-order frames
that are accepted. A value of 0 means that frames are accepted only in
the correct order.
"""
return self.__replay_protection
def _set_replay_protection(self, v, load=False):
"""
Setter method for replay_protection, mapped from YANG variable /macsec/interfaces/interface/config/replay_protection (uint16)
If this variable is read-only (config: false) in the
source YANG file, then _set_replay_protection is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_replay_protection() directly.
YANG Description: MACsec window size, as defined by the number of out-of-order frames
that are accepted. A value of 0 means that frames are accepted only in
the correct order.
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=RestrictedClassType(base_type=int, restriction_dict={'range': ['0..65535']},int_size=16), default=RestrictedClassType(base_type=int, restriction_dict={'range': ['0..65535']},int_size=16)(0), is_leaf=True, yang_name="replay-protection", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='uint16', is_config=True)
except (TypeError, ValueError):
raise ValueError({
'error-string': """replay_protection must be of a type compatible with uint16""",
'defined-type': "uint16",
'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=int, restriction_dict={'range': ['0..65535']},int_size=16), default=RestrictedClassType(base_type=int, restriction_dict={'range': ['0..65535']},int_size=16)(0), is_leaf=True, yang_name="replay-protection", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='uint16', is_config=True)""",
})
self.__replay_protection = t
if hasattr(self, '_set'):
self._set()
def _unset_replay_protection(self):
self.__replay_protection = YANGDynClass(base=RestrictedClassType(base_type=int, restriction_dict={'range': ['0..65535']},int_size=16), default=RestrictedClassType(base_type=int, restriction_dict={'range': ['0..65535']},int_size=16)(0), is_leaf=True, yang_name="replay-protection", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='uint16', is_config=True)
name = __builtin__.property(_get_name, _set_name)
enable = __builtin__.property(_get_enable, _set_enable)
replay_protection = __builtin__.property(_get_replay_protection, _set_replay_protection)
_pyangbind_elements = OrderedDict([('name', name), ('enable', enable), ('replay_protection', replay_protection), ])
class yc_counters_openconfig_macsec__macsec_interfaces_interface_state_counters(PybindBase):
"""
This class was auto-generated by the PythonClass plugin for PYANG
from YANG module openconfig-macsec - based on the path /macsec/interfaces/interface/state/counters. Each member element of
the container is represented as a class variable - with a specific
YANG type.
YANG Description: MACsec interface counters
"""
__slots__ = ('_path_helper', '_extmethods', '__tx_untagged_pkts','__rx_untagged_pkts','__rx_badtag_pkts','__rx_unknownsci_pkts','__rx_nosci_pkts',)
_yang_name = 'counters'
_yang_namespace = 'http://openconfig.net/yang/macsec'
_pybind_generated_by = 'container'
def __init__(self, *args, **kwargs):
self._path_helper = False
self._extmethods = False
self.__tx_untagged_pkts = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="tx-untagged-pkts", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)
self.__rx_untagged_pkts = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="rx-untagged-pkts", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)
self.__rx_badtag_pkts = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="rx-badtag-pkts", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)
self.__rx_unknownsci_pkts = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="rx-unknownsci-pkts", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)
self.__rx_nosci_pkts = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="rx-nosci-pkts", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)
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 ['macsec', 'interfaces', 'interface', 'state', 'counters']
def _get_tx_untagged_pkts(self):
"""
Getter method for tx_untagged_pkts, mapped from YANG variable /macsec/interfaces/interface/state/counters/tx_untagged_pkts (oc-yang:counter64)
YANG Description: MACsec interface level Transmit untagged Packets counter.
This counter will increment if MACsec is enabled on interface and the
outgoing packet is not tagged with MACsec header.
"""
return self.__tx_untagged_pkts
def _set_tx_untagged_pkts(self, v, load=False):
"""
Setter method for tx_untagged_pkts, mapped from YANG variable /macsec/interfaces/interface/state/counters/tx_untagged_pkts (oc-yang:counter64)
If this variable is read-only (config: false) in the
source YANG file, then _set_tx_untagged_pkts is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_tx_untagged_pkts() directly.
YANG Description: MACsec interface level Transmit untagged Packets counter.
This counter will increment if MACsec is enabled on interface and the
outgoing packet is not tagged with MACsec header.
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="tx-untagged-pkts", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)
except (TypeError, ValueError):
raise ValueError({
'error-string': """tx_untagged_pkts must be of a type compatible with oc-yang:counter64""",
'defined-type': "oc-yang:counter64",
'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="tx-untagged-pkts", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)""",
})
self.__tx_untagged_pkts = t
if hasattr(self, '_set'):
self._set()
def _unset_tx_untagged_pkts(self):
self.__tx_untagged_pkts = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="tx-untagged-pkts", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)
def _get_rx_untagged_pkts(self):
"""
Getter method for rx_untagged_pkts, mapped from YANG variable /macsec/interfaces/interface/state/counters/rx_untagged_pkts (oc-yang:counter64)
YANG Description: MACsec interface level Receive untagged Packets counter.
This counter will increment if MACsec is enabled on interface and the
incoming packet does not have MACsec tag.
"""
return self.__rx_untagged_pkts
def _set_rx_untagged_pkts(self, v, load=False):
"""
Setter method for rx_untagged_pkts, mapped from YANG variable /macsec/interfaces/interface/state/counters/rx_untagged_pkts (oc-yang:counter64)
If this variable is read-only (config: false) in the
source YANG file, then _set_rx_untagged_pkts is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_rx_untagged_pkts() directly.
YANG Description: MACsec interface level Receive untagged Packets counter.
This counter will increment if MACsec is enabled on interface and the
incoming packet does not have MACsec tag.
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="rx-untagged-pkts", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)
except (TypeError, ValueError):
raise ValueError({
'error-string': """rx_untagged_pkts must be of a type compatible with oc-yang:counter64""",
'defined-type': "oc-yang:counter64",
'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="rx-untagged-pkts", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)""",
})
self.__rx_untagged_pkts = t
if hasattr(self, '_set'):
self._set()
def _unset_rx_untagged_pkts(self):
self.__rx_untagged_pkts = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="rx-untagged-pkts", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)
def _get_rx_badtag_pkts(self):
"""
Getter method for rx_badtag_pkts, mapped from YANG variable /macsec/interfaces/interface/state/counters/rx_badtag_pkts (oc-yang:counter64)
YANG Description: MACsec interface level Receive Bad Tag Packets counter.
This counter will increment if MACsec is enabled on interface and
incoming packet has incorrect MACsec tag.
"""
return self.__rx_badtag_pkts
def _set_rx_badtag_pkts(self, v, load=False):
"""
Setter method for rx_badtag_pkts, mapped from YANG variable /macsec/interfaces/interface/state/counters/rx_badtag_pkts (oc-yang:counter64)
If this variable is read-only (config: false) in the
source YANG file, then _set_rx_badtag_pkts is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_rx_badtag_pkts() directly.
YANG Description: MACsec interface level Receive Bad Tag Packets counter.
This counter will increment if MACsec is enabled on interface and
incoming packet has incorrect MACsec tag.
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="rx-badtag-pkts", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)
except (TypeError, ValueError):
raise ValueError({
'error-string': """rx_badtag_pkts must be of a type compatible with oc-yang:counter64""",
'defined-type': "oc-yang:counter64",
'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="rx-badtag-pkts", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)""",
})
self.__rx_badtag_pkts = t
if hasattr(self, '_set'):
self._set()
def _unset_rx_badtag_pkts(self):
self.__rx_badtag_pkts = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="rx-badtag-pkts", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)
def _get_rx_unknownsci_pkts(self):
"""
Getter method for rx_unknownsci_pkts, mapped from YANG variable /macsec/interfaces/interface/state/counters/rx_unknownsci_pkts (oc-yang:counter64)
YANG Description: MACsec interface level Receive Unknown SCI Packets counter.
This counter will increment if MACsec is enabled on the interface and
SCI present in the MACsec tag of the incoming packet does not match any
SCI present in ingress SCI table.
"""
return self.__rx_unknownsci_pkts
def _set_rx_unknownsci_pkts(self, v, load=False):
"""
Setter method for rx_unknownsci_pkts, mapped from YANG variable /macsec/interfaces/interface/state/counters/rx_unknownsci_pkts (oc-yang:counter64)
If this variable is read-only (config: false) in the
source YANG file, then _set_rx_unknownsci_pkts is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_rx_unknownsci_pkts() directly.
YANG Description: MACsec interface level Receive Unknown SCI Packets counter.
This counter will increment if MACsec is enabled on the interface and
SCI present in the MACsec tag of the incoming packet does not match any
SCI present in ingress SCI table.
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="rx-unknownsci-pkts", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)
except (TypeError, ValueError):
raise ValueError({
'error-string': """rx_unknownsci_pkts must be of a type compatible with oc-yang:counter64""",
'defined-type': "oc-yang:counter64",
'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="rx-unknownsci-pkts", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)""",
})
self.__rx_unknownsci_pkts = t
if hasattr(self, '_set'):
self._set()
def _unset_rx_unknownsci_pkts(self):
self.__rx_unknownsci_pkts = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="rx-unknownsci-pkts", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)
def _get_rx_nosci_pkts(self):
"""
Getter method for rx_nosci_pkts, mapped from YANG variable /macsec/interfaces/interface/state/counters/rx_nosci_pkts (oc-yang:counter64)
YANG Description: MACsec interface level Receive No SCI Packets counter.
This counter will increment if MACsec is enabled on interface and
incoming packet does not have SCI field in MACsec tag.
"""
return self.__rx_nosci_pkts
def _set_rx_nosci_pkts(self, v, load=False):
"""
Setter method for rx_nosci_pkts, mapped from YANG variable /macsec/interfaces/interface/state/counters/rx_nosci_pkts (oc-yang:counter64)
If this variable is read-only (config: false) in the
source YANG file, then _set_rx_nosci_pkts is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_rx_nosci_pkts() directly.
YANG Description: MACsec interface level Receive No SCI Packets counter.
This counter will increment if MACsec is enabled on interface and
incoming packet does not have SCI field in MACsec tag.
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="rx-nosci-pkts", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)
except (TypeError, ValueError):
raise ValueError({
'error-string': """rx_nosci_pkts must be of a type compatible with oc-yang:counter64""",
'defined-type': "oc-yang:counter64",
'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="rx-nosci-pkts", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)""",
})
self.__rx_nosci_pkts = t
if hasattr(self, '_set'):
self._set()
def _unset_rx_nosci_pkts(self):
self.__rx_nosci_pkts = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="rx-nosci-pkts", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)
tx_untagged_pkts = __builtin__.property(_get_tx_untagged_pkts)
rx_untagged_pkts = __builtin__.property(_get_rx_untagged_pkts)
rx_badtag_pkts = __builtin__.property(_get_rx_badtag_pkts)
rx_unknownsci_pkts = __builtin__.property(_get_rx_unknownsci_pkts)
rx_nosci_pkts = __builtin__.property(_get_rx_nosci_pkts)
_pyangbind_elements = OrderedDict([('tx_untagged_pkts', tx_untagged_pkts), ('rx_untagged_pkts', rx_untagged_pkts), ('rx_badtag_pkts', rx_badtag_pkts), ('rx_unknownsci_pkts', rx_unknownsci_pkts), ('rx_nosci_pkts', rx_nosci_pkts), ])
class yc_state_openconfig_macsec__macsec_interfaces_interface_state(PybindBase):
"""
This class was auto-generated by the PythonClass plugin for PYANG
from YANG module openconfig-macsec - based on the path /macsec/interfaces/interface/state. Each member element of
the container is represented as a class variable - with a specific
YANG type.
YANG Description: Operational state data
"""
__slots__ = ('_path_helper', '_extmethods', '__name','__enable','__replay_protection','__counters',)
_yang_name = 'state'
_yang_namespace = 'http://openconfig.net/yang/macsec'
_pybind_generated_by = 'container'
def __init__(self, *args, **kwargs):
self._path_helper = False
self._extmethods = False
self.__name = YANGDynClass(base=six.text_type, is_leaf=True, yang_name="name", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-if:base-interface-ref', is_config=False)
self.__enable = YANGDynClass(base=YANGBool, default=YANGBool("false"), is_leaf=True, yang_name="enable", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='boolean', is_config=False)
self.__replay_protection = YANGDynClass(base=RestrictedClassType(base_type=int, restriction_dict={'range': ['0..65535']},int_size=16), default=RestrictedClassType(base_type=int, restriction_dict={'range': ['0..65535']},int_size=16)(0), is_leaf=True, yang_name="replay-protection", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='uint16', is_config=False)
self.__counters = YANGDynClass(base=yc_counters_openconfig_macsec__macsec_interfaces_interface_state_counters, is_container='container', yang_name="counters", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=False)
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 ['macsec', 'interfaces', 'interface', 'state']
def _get_name(self):
"""
Getter method for name, mapped from YANG variable /macsec/interfaces/interface/state/name (oc-if:base-interface-ref)
YANG Description: Reference to the MACsec Ethernet interface
"""
return self.__name
def _set_name(self, v, load=False):
"""
Setter method for name, mapped from YANG variable /macsec/interfaces/interface/state/name (oc-if:base-interface-ref)
If this variable is read-only (config: false) in the
source YANG file, then _set_name is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_name() directly.
YANG Description: Reference to the MACsec Ethernet interface
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=six.text_type, is_leaf=True, yang_name="name", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-if:base-interface-ref', is_config=False)
except (TypeError, ValueError):
raise ValueError({
'error-string': """name must be of a type compatible with oc-if:base-interface-ref""",
'defined-type': "oc-if:base-interface-ref",
'generated-type': """YANGDynClass(base=six.text_type, is_leaf=True, yang_name="name", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-if:base-interface-ref', is_config=False)""",
})
self.__name = t
if hasattr(self, '_set'):
self._set()
def _unset_name(self):
self.__name = YANGDynClass(base=six.text_type, is_leaf=True, yang_name="name", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-if:base-interface-ref', is_config=False)
def _get_enable(self):
"""
Getter method for enable, mapped from YANG variable /macsec/interfaces/interface/state/enable (boolean)
YANG Description: Enable MACsec on an interface
"""
return self.__enable
def _set_enable(self, v, load=False):
"""
Setter method for enable, mapped from YANG variable /macsec/interfaces/interface/state/enable (boolean)
If this variable is read-only (config: false) in the
source YANG file, then _set_enable is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_enable() directly.
YANG Description: Enable MACsec on an interface
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=YANGBool, default=YANGBool("false"), is_leaf=True, yang_name="enable", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='boolean', is_config=False)
except (TypeError, ValueError):
raise ValueError({
'error-string': """enable must be of a type compatible with boolean""",
'defined-type': "boolean",
'generated-type': """YANGDynClass(base=YANGBool, default=YANGBool("false"), is_leaf=True, yang_name="enable", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='boolean', is_config=False)""",
})
self.__enable = t
if hasattr(self, '_set'):
self._set()
def _unset_enable(self):
self.__enable = YANGDynClass(base=YANGBool, default=YANGBool("false"), is_leaf=True, yang_name="enable", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='boolean', is_config=False)
def _get_replay_protection(self):
"""
Getter method for replay_protection, mapped from YANG variable /macsec/interfaces/interface/state/replay_protection (uint16)
YANG Description: MACsec window size, as defined by the number of out-of-order frames
that are accepted. A value of 0 means that frames are accepted only in
the correct order.
"""
return self.__replay_protection
def _set_replay_protection(self, v, load=False):
"""
Setter method for replay_protection, mapped from YANG variable /macsec/interfaces/interface/state/replay_protection (uint16)
If this variable is read-only (config: false) in the
source YANG file, then _set_replay_protection is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_replay_protection() directly.
YANG Description: MACsec window size, as defined by the number of out-of-order frames
that are accepted. A value of 0 means that frames are accepted only in
the correct order.
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=RestrictedClassType(base_type=int, restriction_dict={'range': ['0..65535']},int_size=16), default=RestrictedClassType(base_type=int, restriction_dict={'range': ['0..65535']},int_size=16)(0), is_leaf=True, yang_name="replay-protection", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='uint16', is_config=False)
except (TypeError, ValueError):
raise ValueError({
'error-string': """replay_protection must be of a type compatible with uint16""",
'defined-type': "uint16",
'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=int, restriction_dict={'range': ['0..65535']},int_size=16), default=RestrictedClassType(base_type=int, restriction_dict={'range': ['0..65535']},int_size=16)(0), is_leaf=True, yang_name="replay-protection", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='uint16', is_config=False)""",
})
self.__replay_protection = t
if hasattr(self, '_set'):
self._set()
def _unset_replay_protection(self):
self.__replay_protection = YANGDynClass(base=RestrictedClassType(base_type=int, restriction_dict={'range': ['0..65535']},int_size=16), default=RestrictedClassType(base_type=int, restriction_dict={'range': ['0..65535']},int_size=16)(0), is_leaf=True, yang_name="replay-protection", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='uint16', is_config=False)
def _get_counters(self):
"""
Getter method for counters, mapped from YANG variable /macsec/interfaces/interface/state/counters (container)
YANG Description: MACsec interface counters
"""
return self.__counters
def _set_counters(self, v, load=False):
"""
Setter method for counters, mapped from YANG variable /macsec/interfaces/interface/state/counters (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_counters is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_counters() directly.
YANG Description: MACsec interface counters
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=yc_counters_openconfig_macsec__macsec_interfaces_interface_state_counters, is_container='container', yang_name="counters", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=False)
except (TypeError, ValueError):
raise ValueError({
'error-string': """counters must be of a type compatible with container""",
'defined-type': "container",
'generated-type': """YANGDynClass(base=yc_counters_openconfig_macsec__macsec_interfaces_interface_state_counters, is_container='container', yang_name="counters", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=False)""",
})
self.__counters = t
if hasattr(self, '_set'):
self._set()
def _unset_counters(self):
self.__counters = YANGDynClass(base=yc_counters_openconfig_macsec__macsec_interfaces_interface_state_counters, is_container='container', yang_name="counters", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=False)
name = __builtin__.property(_get_name)
enable = __builtin__.property(_get_enable)
replay_protection = __builtin__.property(_get_replay_protection)
counters = __builtin__.property(_get_counters)
_pyangbind_elements = OrderedDict([('name', name), ('enable', enable), ('replay_protection', replay_protection), ('counters', counters), ])
class yc_counters_openconfig_macsec__macsec_interfaces_interface_scsa_tx_scsa_tx_state_counters(PybindBase):
"""
This class was auto-generated by the PythonClass plugin for PYANG
from YANG module openconfig-macsec - based on the path /macsec/interfaces/interface/scsa-tx/scsa-tx/state/counters. Each member element of
the container is represented as a class variable - with a specific
YANG type.
YANG Description: Counters container for macsec-scsa-tx-interface-stats
"""
__slots__ = ('_path_helper', '_extmethods', '__sc_auth_only','__sc_encrypted','__sa_auth_only','__sa_encrypted',)
_yang_name = 'counters'
_yang_namespace = 'http://openconfig.net/yang/macsec'
_pybind_generated_by = 'container'
def __init__(self, *args, **kwargs):
self._path_helper = False
self._extmethods = False
self.__sc_auth_only = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="sc-auth-only", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)
self.__sc_encrypted = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="sc-encrypted", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)
self.__sa_auth_only = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="sa-auth-only", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)
self.__sa_encrypted = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="sa-encrypted", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)
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 ['macsec', 'interfaces', 'interface', 'scsa-tx', 'scsa-tx', 'state', 'counters']
def _get_sc_auth_only(self):
"""
Getter method for sc_auth_only, mapped from YANG variable /macsec/interfaces/interface/scsa_tx/scsa_tx/state/counters/sc_auth_only (oc-yang:counter64)
YANG Description: Secure Channel Authenticated only TX Packets counter.
This counter reflects the number of authenticated only transmitted
packets in a secure channel.
"""
return self.__sc_auth_only
def _set_sc_auth_only(self, v, load=False):
"""
Setter method for sc_auth_only, mapped from YANG variable /macsec/interfaces/interface/scsa_tx/scsa_tx/state/counters/sc_auth_only (oc-yang:counter64)
If this variable is read-only (config: false) in the
source YANG file, then _set_sc_auth_only is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_sc_auth_only() directly.
YANG Description: Secure Channel Authenticated only TX Packets counter.
This counter reflects the number of authenticated only transmitted
packets in a secure channel.
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="sc-auth-only", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)
except (TypeError, ValueError):
raise ValueError({
'error-string': """sc_auth_only must be of a type compatible with oc-yang:counter64""",
'defined-type': "oc-yang:counter64",
'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="sc-auth-only", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)""",
})
self.__sc_auth_only = t
if hasattr(self, '_set'):
self._set()
def _unset_sc_auth_only(self):
self.__sc_auth_only = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="sc-auth-only", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)
def _get_sc_encrypted(self):
"""
Getter method for sc_encrypted, mapped from YANG variable /macsec/interfaces/interface/scsa_tx/scsa_tx/state/counters/sc_encrypted (oc-yang:counter64)
YANG Description: Secure Channel Encrypted TX Packets counter.
This counter reflects the number of encrypted and authenticated
transmitted packets in a secure channel.
"""
return self.__sc_encrypted
def _set_sc_encrypted(self, v, load=False):
"""
Setter method for sc_encrypted, mapped from YANG variable /macsec/interfaces/interface/scsa_tx/scsa_tx/state/counters/sc_encrypted (oc-yang:counter64)
If this variable is read-only (config: false) in the
source YANG file, then _set_sc_encrypted is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_sc_encrypted() directly.
YANG Description: Secure Channel Encrypted TX Packets counter.
This counter reflects the number of encrypted and authenticated
transmitted packets in a secure channel.
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="sc-encrypted", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)
except (TypeError, ValueError):
raise ValueError({
'error-string': """sc_encrypted must be of a type compatible with oc-yang:counter64""",
'defined-type': "oc-yang:counter64",
'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="sc-encrypted", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)""",
})
self.__sc_encrypted = t
if hasattr(self, '_set'):
self._set()
def _unset_sc_encrypted(self):
self.__sc_encrypted = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="sc-encrypted", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)
def _get_sa_auth_only(self):
"""
Getter method for sa_auth_only, mapped from YANG variable /macsec/interfaces/interface/scsa_tx/scsa_tx/state/counters/sa_auth_only (oc-yang:counter64)
YANG Description: Secure Association Authenticated only TX Packets counter.
This counter reflects the number of authenticated only, transmitted
packets in a secure association.
"""
return self.__sa_auth_only
def _set_sa_auth_only(self, v, load=False):
"""
Setter method for sa_auth_only, mapped from YANG variable /macsec/interfaces/interface/scsa_tx/scsa_tx/state/counters/sa_auth_only (oc-yang:counter64)
If this variable is read-only (config: false) in the
source YANG file, then _set_sa_auth_only is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_sa_auth_only() directly.
YANG Description: Secure Association Authenticated only TX Packets counter.
This counter reflects the number of authenticated only, transmitted
packets in a secure association.
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="sa-auth-only", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)
except (TypeError, ValueError):
raise ValueError({
'error-string': """sa_auth_only must be of a type compatible with oc-yang:counter64""",
'defined-type': "oc-yang:counter64",
'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="sa-auth-only", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)""",
})
self.__sa_auth_only = t
if hasattr(self, '_set'):
self._set()
def _unset_sa_auth_only(self):
self.__sa_auth_only = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="sa-auth-only", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)
def _get_sa_encrypted(self):
"""
Getter method for sa_encrypted, mapped from YANG variable /macsec/interfaces/interface/scsa_tx/scsa_tx/state/counters/sa_encrypted (oc-yang:counter64)
YANG Description: Secure Association Encrypted TX Packets counter.
This counter reflects the number of encrypted and authenticated
transmitted packets in a secure association.
"""
return self.__sa_encrypted
def _set_sa_encrypted(self, v, load=False):
"""
Setter method for sa_encrypted, mapped from YANG variable /macsec/interfaces/interface/scsa_tx/scsa_tx/state/counters/sa_encrypted (oc-yang:counter64)
If this variable is read-only (config: false) in the
source YANG file, then _set_sa_encrypted is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_sa_encrypted() directly.
YANG Description: Secure Association Encrypted TX Packets counter.
This counter reflects the number of encrypted and authenticated
transmitted packets in a secure association.
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="sa-encrypted", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)
except (TypeError, ValueError):
raise ValueError({
'error-string': """sa_encrypted must be of a type compatible with oc-yang:counter64""",
'defined-type': "oc-yang:counter64",
'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="sa-encrypted", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)""",
})
self.__sa_encrypted = t
if hasattr(self, '_set'):
self._set()
def _unset_sa_encrypted(self):
self.__sa_encrypted = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="sa-encrypted", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)
sc_auth_only = __builtin__.property(_get_sc_auth_only)
sc_encrypted = __builtin__.property(_get_sc_encrypted)
sa_auth_only = __builtin__.property(_get_sa_auth_only)
sa_encrypted = __builtin__.property(_get_sa_encrypted)
_pyangbind_elements = OrderedDict([('sc_auth_only', sc_auth_only), ('sc_encrypted', sc_encrypted), ('sa_auth_only', sa_auth_only), ('sa_encrypted', sa_encrypted), ])
class yc_state_openconfig_macsec__macsec_interfaces_interface_scsa_tx_scsa_tx_state(PybindBase):
"""
This class was auto-generated by the PythonClass plugin for PYANG
from YANG module openconfig-macsec - based on the path /macsec/interfaces/interface/scsa-tx/scsa-tx/state. Each member element of
the container is represented as a class variable - with a specific
YANG type.
YANG Description: State container for macsec-scsa-tx-interface-stats
"""
__slots__ = ('_path_helper', '_extmethods', '__sci_tx','__counters',)
_yang_name = 'state'
_yang_namespace = 'http://openconfig.net/yang/macsec'
_pybind_generated_by = 'container'
def __init__(self, *args, **kwargs):
self._path_helper = False
self._extmethods = False
self.__sci_tx = YANGDynClass(base=RestrictedClassType(base_type=RestrictedClassType(base_type=six.text_type, restriction_dict={'pattern': '[0-9a-fA-F]*'}), restriction_dict={'length': ['16']}), is_leaf=True, yang_name="sci-tx", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:hex-string', is_config=False)
self.__counters = YANGDynClass(base=yc_counters_openconfig_macsec__macsec_interfaces_interface_scsa_tx_scsa_tx_state_counters, is_container='container', yang_name="counters", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=False)
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 ['macsec', 'interfaces', 'interface', 'scsa-tx', 'scsa-tx', 'state']
def _get_sci_tx(self):
"""
Getter method for sci_tx, mapped from YANG variable /macsec/interfaces/interface/scsa_tx/scsa_tx/state/sci_tx (oc-yang:hex-string)
YANG Description: Secure Channel Identifier.
Every Transmit Channel is uniquely identified using this field.
"""
return self.__sci_tx
def _set_sci_tx(self, v, load=False):
"""
Setter method for sci_tx, mapped from YANG variable /macsec/interfaces/interface/scsa_tx/scsa_tx/state/sci_tx (oc-yang:hex-string)
If this variable is read-only (config: false) in the
source YANG file, then _set_sci_tx is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_sci_tx() directly.
YANG Description: Secure Channel Identifier.
Every Transmit Channel is uniquely identified using this field.
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=RestrictedClassType(base_type=RestrictedClassType(base_type=six.text_type, restriction_dict={'pattern': '[0-9a-fA-F]*'}), restriction_dict={'length': ['16']}), is_leaf=True, yang_name="sci-tx", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:hex-string', is_config=False)
except (TypeError, ValueError):
raise ValueError({
'error-string': """sci_tx must be of a type compatible with oc-yang:hex-string""",
'defined-type': "oc-yang:hex-string",
'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=RestrictedClassType(base_type=six.text_type, restriction_dict={'pattern': '[0-9a-fA-F]*'}), restriction_dict={'length': ['16']}), is_leaf=True, yang_name="sci-tx", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:hex-string', is_config=False)""",
})
self.__sci_tx = t
if hasattr(self, '_set'):
self._set()
def _unset_sci_tx(self):
self.__sci_tx = YANGDynClass(base=RestrictedClassType(base_type=RestrictedClassType(base_type=six.text_type, restriction_dict={'pattern': '[0-9a-fA-F]*'}), restriction_dict={'length': ['16']}), is_leaf=True, yang_name="sci-tx", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:hex-string', is_config=False)
def _get_counters(self):
"""
Getter method for counters, mapped from YANG variable /macsec/interfaces/interface/scsa_tx/scsa_tx/state/counters (container)
YANG Description: Counters container for macsec-scsa-tx-interface-stats
"""
return self.__counters
def _set_counters(self, v, load=False):
"""
Setter method for counters, mapped from YANG variable /macsec/interfaces/interface/scsa_tx/scsa_tx/state/counters (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_counters is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_counters() directly.
YANG Description: Counters container for macsec-scsa-tx-interface-stats
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=yc_counters_openconfig_macsec__macsec_interfaces_interface_scsa_tx_scsa_tx_state_counters, is_container='container', yang_name="counters", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=False)
except (TypeError, ValueError):
raise ValueError({
'error-string': """counters must be of a type compatible with container""",
'defined-type': "container",
'generated-type': """YANGDynClass(base=yc_counters_openconfig_macsec__macsec_interfaces_interface_scsa_tx_scsa_tx_state_counters, is_container='container', yang_name="counters", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=False)""",
})
self.__counters = t
if hasattr(self, '_set'):
self._set()
def _unset_counters(self):
self.__counters = YANGDynClass(base=yc_counters_openconfig_macsec__macsec_interfaces_interface_scsa_tx_scsa_tx_state_counters, is_container='container', yang_name="counters", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=False)
sci_tx = __builtin__.property(_get_sci_tx)
counters = __builtin__.property(_get_counters)
_pyangbind_elements = OrderedDict([('sci_tx', sci_tx), ('counters', counters), ])
class yc_scsa_tx_openconfig_macsec__macsec_interfaces_interface_scsa_tx_scsa_tx(PybindBase):
"""
This class was auto-generated by the PythonClass plugin for PYANG
from YANG module openconfig-macsec - based on the path /macsec/interfaces/interface/scsa-tx/scsa-tx. Each member element of
the container is represented as a class variable - with a specific
YANG type.
YANG Description: TX Secure Channel and Secure Association Statistics
"""
__slots__ = ('_path_helper', '_extmethods', '__sci_tx','__state',)
_yang_name = 'scsa-tx'
_yang_namespace = 'http://openconfig.net/yang/macsec'
_pybind_generated_by = 'container'
def __init__(self, *args, **kwargs):
self._path_helper = False
self._extmethods = False
self.__sci_tx = YANGDynClass(base=six.text_type, is_leaf=True, yang_name="sci-tx", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, is_keyval=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='leafref', is_config=False)
self.__state = YANGDynClass(base=yc_state_openconfig_macsec__macsec_interfaces_interface_scsa_tx_scsa_tx_state, is_container='container', yang_name="state", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=False)
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 ['macsec', 'interfaces', 'interface', 'scsa-tx', 'scsa-tx']
def _get_sci_tx(self):
"""
Getter method for sci_tx, mapped from YANG variable /macsec/interfaces/interface/scsa_tx/scsa_tx/sci_tx (leafref)
YANG Description: TX Secure Channel and Secure Association Statistics
"""
return self.__sci_tx
def _set_sci_tx(self, v, load=False):
"""
Setter method for sci_tx, mapped from YANG variable /macsec/interfaces/interface/scsa_tx/scsa_tx/sci_tx (leafref)
If this variable is read-only (config: false) in the
source YANG file, then _set_sci_tx is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_sci_tx() directly.
YANG Description: TX Secure Channel and Secure Association Statistics
"""
parent = getattr(self, "_parent", None)
if parent is not None and load is False:
raise AttributeError("Cannot set keys directly when" +
" within an instantiated list")
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=six.text_type, is_leaf=True, yang_name="sci-tx", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, is_keyval=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='leafref', is_config=False)
except (TypeError, ValueError):
raise ValueError({
'error-string': """sci_tx must be of a type compatible with leafref""",
'defined-type': "leafref",
'generated-type': """YANGDynClass(base=six.text_type, is_leaf=True, yang_name="sci-tx", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, is_keyval=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='leafref', is_config=False)""",
})
self.__sci_tx = t
if hasattr(self, '_set'):
self._set()
def _unset_sci_tx(self):
self.__sci_tx = YANGDynClass(base=six.text_type, is_leaf=True, yang_name="sci-tx", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, is_keyval=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='leafref', is_config=False)
def _get_state(self):
"""
Getter method for state, mapped from YANG variable /macsec/interfaces/interface/scsa_tx/scsa_tx/state (container)
YANG Description: State container for macsec-scsa-tx-interface-stats
"""
return self.__state
def _set_state(self, v, load=False):
"""
Setter method for state, mapped from YANG variable /macsec/interfaces/interface/scsa_tx/scsa_tx/state (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_state is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_state() directly.
YANG Description: State container for macsec-scsa-tx-interface-stats
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=yc_state_openconfig_macsec__macsec_interfaces_interface_scsa_tx_scsa_tx_state, is_container='container', yang_name="state", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=False)
except (TypeError, ValueError):
raise ValueError({
'error-string': """state must be of a type compatible with container""",
'defined-type': "container",
'generated-type': """YANGDynClass(base=yc_state_openconfig_macsec__macsec_interfaces_interface_scsa_tx_scsa_tx_state, is_container='container', yang_name="state", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=False)""",
})
self.__state = t
if hasattr(self, '_set'):
self._set()
def _unset_state(self):
self.__state = YANGDynClass(base=yc_state_openconfig_macsec__macsec_interfaces_interface_scsa_tx_scsa_tx_state, is_container='container', yang_name="state", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=False)
sci_tx = __builtin__.property(_get_sci_tx)
state = __builtin__.property(_get_state)
_pyangbind_elements = OrderedDict([('sci_tx', sci_tx), ('state', state), ])
class yc_scsa_tx_openconfig_macsec__macsec_interfaces_interface_scsa_tx(PybindBase):
"""
This class was auto-generated by the PythonClass plugin for PYANG
from YANG module openconfig-macsec - based on the path /macsec/interfaces/interface/scsa-tx. Each member element of
the container is represented as a class variable - with a specific
YANG type.
YANG Description: Enclosing container for transmitted packets for Secure Channel and
Secure Association
"""
__slots__ = ('_path_helper', '_extmethods', '__scsa_tx',)
_yang_name = 'scsa-tx'
_yang_namespace = 'http://openconfig.net/yang/macsec'
_pybind_generated_by = 'container'
def __init__(self, *args, **kwargs):
self._path_helper = False
self._extmethods = False
self.__scsa_tx = YANGDynClass(base=YANGListType("sci_tx",yc_scsa_tx_openconfig_macsec__macsec_interfaces_interface_scsa_tx_scsa_tx, yang_name="scsa-tx", parent=self, is_container='list', user_ordered=False, path_helper=self._path_helper, yang_keys='sci-tx', extensions=None), is_container='list', yang_name="scsa-tx", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='list', is_config=False)
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 ['macsec', 'interfaces', 'interface', 'scsa-tx']
def _get_scsa_tx(self):
"""
Getter method for scsa_tx, mapped from YANG variable /macsec/interfaces/interface/scsa_tx/scsa_tx (list)
YANG Description: TX Secure Channel and Secure Association Statistics
"""
return self.__scsa_tx
def _set_scsa_tx(self, v, load=False):
"""
Setter method for scsa_tx, mapped from YANG variable /macsec/interfaces/interface/scsa_tx/scsa_tx (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_scsa_tx is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_scsa_tx() directly.
YANG Description: TX Secure Channel and Secure Association Statistics
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=YANGListType("sci_tx",yc_scsa_tx_openconfig_macsec__macsec_interfaces_interface_scsa_tx_scsa_tx, yang_name="scsa-tx", parent=self, is_container='list', user_ordered=False, path_helper=self._path_helper, yang_keys='sci-tx', extensions=None), is_container='list', yang_name="scsa-tx", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='list', is_config=False)
except (TypeError, ValueError):
raise ValueError({
'error-string': """scsa_tx must be of a type compatible with list""",
'defined-type': "list",
'generated-type': """YANGDynClass(base=YANGListType("sci_tx",yc_scsa_tx_openconfig_macsec__macsec_interfaces_interface_scsa_tx_scsa_tx, yang_name="scsa-tx", parent=self, is_container='list', user_ordered=False, path_helper=self._path_helper, yang_keys='sci-tx', extensions=None), is_container='list', yang_name="scsa-tx", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='list', is_config=False)""",
})
self.__scsa_tx = t
if hasattr(self, '_set'):
self._set()
def _unset_scsa_tx(self):
self.__scsa_tx = YANGDynClass(base=YANGListType("sci_tx",yc_scsa_tx_openconfig_macsec__macsec_interfaces_interface_scsa_tx_scsa_tx, yang_name="scsa-tx", parent=self, is_container='list', user_ordered=False, path_helper=self._path_helper, yang_keys='sci-tx', extensions=None), is_container='list', yang_name="scsa-tx", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='list', is_config=False)
scsa_tx = __builtin__.property(_get_scsa_tx)
_pyangbind_elements = OrderedDict([('scsa_tx', scsa_tx), ])
class yc_counters_openconfig_macsec__macsec_interfaces_interface_scsa_rx_scsa_rx_state_counters(PybindBase):
"""
This class was auto-generated by the PythonClass plugin for PYANG
from YANG module openconfig-macsec - based on the path /macsec/interfaces/interface/scsa-rx/scsa-rx/state/counters. Each member element of
the container is represented as a class variable - with a specific
YANG type.
YANG Description: Counters container for macsec-scsa-rx-interface-stats
"""
__slots__ = ('_path_helper', '_extmethods', '__sc_invalid','__sc_valid','__sa_invalid','__sa_valid',)
_yang_name = 'counters'
_yang_namespace = 'http://openconfig.net/yang/macsec'
_pybind_generated_by = 'container'
def __init__(self, *args, **kwargs):
self._path_helper = False
self._extmethods = False
self.__sc_invalid = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="sc-invalid", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)
self.__sc_valid = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="sc-valid", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)
self.__sa_invalid = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="sa-invalid", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)
self.__sa_valid = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="sa-valid", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)
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 ['macsec', 'interfaces', 'interface', 'scsa-rx', 'scsa-rx', 'state', 'counters']
def _get_sc_invalid(self):
"""
Getter method for sc_invalid, mapped from YANG variable /macsec/interfaces/interface/scsa_rx/scsa_rx/state/counters/sc_invalid (oc-yang:counter64)
YANG Description: Invalid Secure Channel RX Packets counter.
This counter reflects the number of invalid received packets in a
secure channel.
"""
return self.__sc_invalid
def _set_sc_invalid(self, v, load=False):
"""
Setter method for sc_invalid, mapped from YANG variable /macsec/interfaces/interface/scsa_rx/scsa_rx/state/counters/sc_invalid (oc-yang:counter64)
If this variable is read-only (config: false) in the
source YANG file, then _set_sc_invalid is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_sc_invalid() directly.
YANG Description: Invalid Secure Channel RX Packets counter.
This counter reflects the number of invalid received packets in a
secure channel.
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="sc-invalid", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)
except (TypeError, ValueError):
raise ValueError({
'error-string': """sc_invalid must be of a type compatible with oc-yang:counter64""",
'defined-type': "oc-yang:counter64",
'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="sc-invalid", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)""",
})
self.__sc_invalid = t
if hasattr(self, '_set'):
self._set()
def _unset_sc_invalid(self):
self.__sc_invalid = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="sc-invalid", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)
def _get_sc_valid(self):
"""
Getter method for sc_valid, mapped from YANG variable /macsec/interfaces/interface/scsa_rx/scsa_rx/state/counters/sc_valid (oc-yang:counter64)
YANG Description: Valid Secure Channel RX Packets counter.
This counter reflects the number of valid received packets in a
secure channel.
"""
return self.__sc_valid
def _set_sc_valid(self, v, load=False):
"""
Setter method for sc_valid, mapped from YANG variable /macsec/interfaces/interface/scsa_rx/scsa_rx/state/counters/sc_valid (oc-yang:counter64)
If this variable is read-only (config: false) in the
source YANG file, then _set_sc_valid is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_sc_valid() directly.
YANG Description: Valid Secure Channel RX Packets counter.
This counter reflects the number of valid received packets in a
secure channel.
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="sc-valid", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)
except (TypeError, ValueError):
raise ValueError({
'error-string': """sc_valid must be of a type compatible with oc-yang:counter64""",
'defined-type': "oc-yang:counter64",
'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="sc-valid", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)""",
})
self.__sc_valid = t
if hasattr(self, '_set'):
self._set()
def _unset_sc_valid(self):
self.__sc_valid = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="sc-valid", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)
def _get_sa_invalid(self):
"""
Getter method for sa_invalid, mapped from YANG variable /macsec/interfaces/interface/scsa_rx/scsa_rx/state/counters/sa_invalid (oc-yang:counter64)
YANG Description: Invalid Secure Association RX Packets counter.
This counter reflects the number of integrity check fails for received
packets in a secure association.
"""
return self.__sa_invalid
def _set_sa_invalid(self, v, load=False):
"""
Setter method for sa_invalid, mapped from YANG variable /macsec/interfaces/interface/scsa_rx/scsa_rx/state/counters/sa_invalid (oc-yang:counter64)
If this variable is read-only (config: false) in the
source YANG file, then _set_sa_invalid is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_sa_invalid() directly.
YANG Description: Invalid Secure Association RX Packets counter.
This counter reflects the number of integrity check fails for received
packets in a secure association.
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="sa-invalid", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)
except (TypeError, ValueError):
raise ValueError({
'error-string': """sa_invalid must be of a type compatible with oc-yang:counter64""",
'defined-type': "oc-yang:counter64",
'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="sa-invalid", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)""",
})
self.__sa_invalid = t
if hasattr(self, '_set'):
self._set()
def _unset_sa_invalid(self):
self.__sa_invalid = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="sa-invalid", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)
def _get_sa_valid(self):
"""
Getter method for sa_valid, mapped from YANG variable /macsec/interfaces/interface/scsa_rx/scsa_rx/state/counters/sa_valid (oc-yang:counter64)
YANG Description: Secure Association Valid RX Packets counter.
This counter reflects the number of packets in a secure association
that passed integrity check.
"""
return self.__sa_valid
def _set_sa_valid(self, v, load=False):
"""
Setter method for sa_valid, mapped from YANG variable /macsec/interfaces/interface/scsa_rx/scsa_rx/state/counters/sa_valid (oc-yang:counter64)
If this variable is read-only (config: false) in the
source YANG file, then _set_sa_valid is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_sa_valid() directly.
YANG Description: Secure Association Valid RX Packets counter.
This counter reflects the number of packets in a secure association
that passed integrity check.
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="sa-valid", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)
except (TypeError, ValueError):
raise ValueError({
'error-string': """sa_valid must be of a type compatible with oc-yang:counter64""",
'defined-type': "oc-yang:counter64",
'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="sa-valid", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)""",
})
self.__sa_valid = t
if hasattr(self, '_set'):
self._set()
def _unset_sa_valid(self):
self.__sa_valid = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="sa-valid", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)
sc_invalid = __builtin__.property(_get_sc_invalid)
sc_valid = __builtin__.property(_get_sc_valid)
sa_invalid = __builtin__.property(_get_sa_invalid)
sa_valid = __builtin__.property(_get_sa_valid)
_pyangbind_elements = OrderedDict([('sc_invalid', sc_invalid), ('sc_valid', sc_valid), ('sa_invalid', sa_invalid), ('sa_valid', sa_valid), ])
class yc_state_openconfig_macsec__macsec_interfaces_interface_scsa_rx_scsa_rx_state(PybindBase):
"""
This class was auto-generated by the PythonClass plugin for PYANG
from YANG module openconfig-macsec - based on the path /macsec/interfaces/interface/scsa-rx/scsa-rx/state. Each member element of
the container is represented as a class variable - with a specific
YANG type.
YANG Description: State container for macsec-scsa-rx-interface-stats
"""
__slots__ = ('_path_helper', '_extmethods', '__sci_rx','__counters',)
_yang_name = 'state'
_yang_namespace = 'http://openconfig.net/yang/macsec'
_pybind_generated_by = 'container'
def __init__(self, *args, **kwargs):
self._path_helper = False
self._extmethods = False
self.__sci_rx = YANGDynClass(base=RestrictedClassType(base_type=RestrictedClassType(base_type=six.text_type, restriction_dict={'pattern': '[0-9a-fA-F]*'}), restriction_dict={'length': ['16']}), is_leaf=True, yang_name="sci-rx", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:hex-string', is_config=False)
self.__counters = YANGDynClass(base=yc_counters_openconfig_macsec__macsec_interfaces_interface_scsa_rx_scsa_rx_state_counters, is_container='container', yang_name="counters", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=False)
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 ['macsec', 'interfaces', 'interface', 'scsa-rx', 'scsa-rx', 'state']
def _get_sci_rx(self):
"""
Getter method for sci_rx, mapped from YANG variable /macsec/interfaces/interface/scsa_rx/scsa_rx/state/sci_rx (oc-yang:hex-string)
YANG Description: Secure Channel Identifier.
Every Receive Channel is uniquely identified using this field.
"""
return self.__sci_rx
def _set_sci_rx(self, v, load=False):
"""
Setter method for sci_rx, mapped from YANG variable /macsec/interfaces/interface/scsa_rx/scsa_rx/state/sci_rx (oc-yang:hex-string)
If this variable is read-only (config: false) in the
source YANG file, then _set_sci_rx is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_sci_rx() directly.
YANG Description: Secure Channel Identifier.
Every Receive Channel is uniquely identified using this field.
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=RestrictedClassType(base_type=RestrictedClassType(base_type=six.text_type, restriction_dict={'pattern': '[0-9a-fA-F]*'}), restriction_dict={'length': ['16']}), is_leaf=True, yang_name="sci-rx", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:hex-string', is_config=False)
except (TypeError, ValueError):
raise ValueError({
'error-string': """sci_rx must be of a type compatible with oc-yang:hex-string""",
'defined-type': "oc-yang:hex-string",
'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=RestrictedClassType(base_type=six.text_type, restriction_dict={'pattern': '[0-9a-fA-F]*'}), restriction_dict={'length': ['16']}), is_leaf=True, yang_name="sci-rx", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:hex-string', is_config=False)""",
})
self.__sci_rx = t
if hasattr(self, '_set'):
self._set()
def _unset_sci_rx(self):
self.__sci_rx = YANGDynClass(base=RestrictedClassType(base_type=RestrictedClassType(base_type=six.text_type, restriction_dict={'pattern': '[0-9a-fA-F]*'}), restriction_dict={'length': ['16']}), is_leaf=True, yang_name="sci-rx", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:hex-string', is_config=False)
def _get_counters(self):
"""
Getter method for counters, mapped from YANG variable /macsec/interfaces/interface/scsa_rx/scsa_rx/state/counters (container)
YANG Description: Counters container for macsec-scsa-rx-interface-stats
"""
return self.__counters
def _set_counters(self, v, load=False):
"""
Setter method for counters, mapped from YANG variable /macsec/interfaces/interface/scsa_rx/scsa_rx/state/counters (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_counters is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_counters() directly.
YANG Description: Counters container for macsec-scsa-rx-interface-stats
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=yc_counters_openconfig_macsec__macsec_interfaces_interface_scsa_rx_scsa_rx_state_counters, is_container='container', yang_name="counters", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=False)
except (TypeError, ValueError):
raise ValueError({
'error-string': """counters must be of a type compatible with container""",
'defined-type': "container",
'generated-type': """YANGDynClass(base=yc_counters_openconfig_macsec__macsec_interfaces_interface_scsa_rx_scsa_rx_state_counters, is_container='container', yang_name="counters", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=False)""",
})
self.__counters = t
if hasattr(self, '_set'):
self._set()
def _unset_counters(self):
self.__counters = YANGDynClass(base=yc_counters_openconfig_macsec__macsec_interfaces_interface_scsa_rx_scsa_rx_state_counters, is_container='container', yang_name="counters", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=False)
sci_rx = __builtin__.property(_get_sci_rx)
counters = __builtin__.property(_get_counters)
_pyangbind_elements = OrderedDict([('sci_rx', sci_rx), ('counters', counters), ])
class yc_scsa_rx_openconfig_macsec__macsec_interfaces_interface_scsa_rx_scsa_rx(PybindBase):
"""
This class was auto-generated by the PythonClass plugin for PYANG
from YANG module openconfig-macsec - based on the path /macsec/interfaces/interface/scsa-rx/scsa-rx. Each member element of
the container is represented as a class variable - with a specific
YANG type.
YANG Description: RX Secure Channel and Secure Association Statistics
"""
__slots__ = ('_path_helper', '_extmethods', '__sci_rx','__state',)
_yang_name = 'scsa-rx'
_yang_namespace = 'http://openconfig.net/yang/macsec'
_pybind_generated_by = 'container'
def __init__(self, *args, **kwargs):
self._path_helper = False
self._extmethods = False
self.__sci_rx = YANGDynClass(base=six.text_type, is_leaf=True, yang_name="sci-rx", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, is_keyval=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='leafref', is_config=False)
self.__state = YANGDynClass(base=yc_state_openconfig_macsec__macsec_interfaces_interface_scsa_rx_scsa_rx_state, is_container='container', yang_name="state", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=False)
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 ['macsec', 'interfaces', 'interface', 'scsa-rx', 'scsa-rx']
def _get_sci_rx(self):
"""
Getter method for sci_rx, mapped from YANG variable /macsec/interfaces/interface/scsa_rx/scsa_rx/sci_rx (leafref)
YANG Description: RX Secure Channel and Secure Association Statistics
"""
return self.__sci_rx
def _set_sci_rx(self, v, load=False):
"""
Setter method for sci_rx, mapped from YANG variable /macsec/interfaces/interface/scsa_rx/scsa_rx/sci_rx (leafref)
If this variable is read-only (config: false) in the
source YANG file, then _set_sci_rx is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_sci_rx() directly.
YANG Description: RX Secure Channel and Secure Association Statistics
"""
parent = getattr(self, "_parent", None)
if parent is not None and load is False:
raise AttributeError("Cannot set keys directly when" +
" within an instantiated list")
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=six.text_type, is_leaf=True, yang_name="sci-rx", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, is_keyval=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='leafref', is_config=False)
except (TypeError, ValueError):
raise ValueError({
'error-string': """sci_rx must be of a type compatible with leafref""",
'defined-type': "leafref",
'generated-type': """YANGDynClass(base=six.text_type, is_leaf=True, yang_name="sci-rx", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, is_keyval=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='leafref', is_config=False)""",
})
self.__sci_rx = t
if hasattr(self, '_set'):
self._set()
def _unset_sci_rx(self):
self.__sci_rx = YANGDynClass(base=six.text_type, is_leaf=True, yang_name="sci-rx", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, is_keyval=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='leafref', is_config=False)
def _get_state(self):
"""
Getter method for state, mapped from YANG variable /macsec/interfaces/interface/scsa_rx/scsa_rx/state (container)
YANG Description: State container for macsec-scsa-rx-interface-stats
"""
return self.__state
def _set_state(self, v, load=False):
"""
Setter method for state, mapped from YANG variable /macsec/interfaces/interface/scsa_rx/scsa_rx/state (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_state is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_state() directly.
YANG Description: State container for macsec-scsa-rx-interface-stats
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=yc_state_openconfig_macsec__macsec_interfaces_interface_scsa_rx_scsa_rx_state, is_container='container', yang_name="state", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=False)
except (TypeError, ValueError):
raise ValueError({
'error-string': """state must be of a type compatible with container""",
'defined-type': "container",
'generated-type': """YANGDynClass(base=yc_state_openconfig_macsec__macsec_interfaces_interface_scsa_rx_scsa_rx_state, is_container='container', yang_name="state", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=False)""",
})
self.__state = t
if hasattr(self, '_set'):
self._set()
def _unset_state(self):
self.__state = YANGDynClass(base=yc_state_openconfig_macsec__macsec_interfaces_interface_scsa_rx_scsa_rx_state, is_container='container', yang_name="state", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=False)
sci_rx = __builtin__.property(_get_sci_rx)
state = __builtin__.property(_get_state)
_pyangbind_elements = OrderedDict([('sci_rx', sci_rx), ('state', state), ])
class yc_scsa_rx_openconfig_macsec__macsec_interfaces_interface_scsa_rx(PybindBase):
"""
This class was auto-generated by the PythonClass plugin for PYANG
from YANG module openconfig-macsec - based on the path /macsec/interfaces/interface/scsa-rx. Each member element of
the container is represented as a class variable - with a specific
YANG type.
YANG Description: Enclosing container for received packets for Secure Channel and
Secure Association
"""
__slots__ = ('_path_helper', '_extmethods', '__scsa_rx',)
_yang_name = 'scsa-rx'
_yang_namespace = 'http://openconfig.net/yang/macsec'
_pybind_generated_by = 'container'
def __init__(self, *args, **kwargs):
self._path_helper = False
self._extmethods = False
self.__scsa_rx = YANGDynClass(base=YANGListType("sci_rx",yc_scsa_rx_openconfig_macsec__macsec_interfaces_interface_scsa_rx_scsa_rx, yang_name="scsa-rx", parent=self, is_container='list', user_ordered=False, path_helper=self._path_helper, yang_keys='sci-rx', extensions=None), is_container='list', yang_name="scsa-rx", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='list', is_config=False)
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 ['macsec', 'interfaces', 'interface', 'scsa-rx']
def _get_scsa_rx(self):
"""
Getter method for scsa_rx, mapped from YANG variable /macsec/interfaces/interface/scsa_rx/scsa_rx (list)
YANG Description: RX Secure Channel and Secure Association Statistics
"""
return self.__scsa_rx
def _set_scsa_rx(self, v, load=False):
"""
Setter method for scsa_rx, mapped from YANG variable /macsec/interfaces/interface/scsa_rx/scsa_rx (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_scsa_rx is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_scsa_rx() directly.
YANG Description: RX Secure Channel and Secure Association Statistics
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=YANGListType("sci_rx",yc_scsa_rx_openconfig_macsec__macsec_interfaces_interface_scsa_rx_scsa_rx, yang_name="scsa-rx", parent=self, is_container='list', user_ordered=False, path_helper=self._path_helper, yang_keys='sci-rx', extensions=None), is_container='list', yang_name="scsa-rx", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='list', is_config=False)
except (TypeError, ValueError):
raise ValueError({
'error-string': """scsa_rx must be of a type compatible with list""",
'defined-type': "list",
'generated-type': """YANGDynClass(base=YANGListType("sci_rx",yc_scsa_rx_openconfig_macsec__macsec_interfaces_interface_scsa_rx_scsa_rx, yang_name="scsa-rx", parent=self, is_container='list', user_ordered=False, path_helper=self._path_helper, yang_keys='sci-rx', extensions=None), is_container='list', yang_name="scsa-rx", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='list', is_config=False)""",
})
self.__scsa_rx = t
if hasattr(self, '_set'):
self._set()
def _unset_scsa_rx(self):
self.__scsa_rx = YANGDynClass(base=YANGListType("sci_rx",yc_scsa_rx_openconfig_macsec__macsec_interfaces_interface_scsa_rx_scsa_rx, yang_name="scsa-rx", parent=self, is_container='list', user_ordered=False, path_helper=self._path_helper, yang_keys='sci-rx', extensions=None), is_container='list', yang_name="scsa-rx", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='list', is_config=False)
scsa_rx = __builtin__.property(_get_scsa_rx)
_pyangbind_elements = OrderedDict([('scsa_rx', scsa_rx), ])
class yc_config_openconfig_macsec__macsec_interfaces_interface_mka_config(PybindBase):
"""
This class was auto-generated by the PythonClass plugin for PYANG
from YANG module openconfig-macsec - based on the path /macsec/interfaces/interface/mka/config. Each member element of
the container is represented as a class variable - with a specific
YANG type.
YANG Description: Configuration data for MKA interface
"""
__slots__ = ('_path_helper', '_extmethods', '__mka_policy','__key_chain',)
_yang_name = 'config'
_yang_namespace = 'http://openconfig.net/yang/macsec'
_pybind_generated_by = 'container'
def __init__(self, *args, **kwargs):
self._path_helper = False
self._extmethods = False
self.__mka_policy = YANGDynClass(base=six.text_type, is_leaf=True, yang_name="mka-policy", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='leafref', is_config=True)
self.__key_chain = YANGDynClass(base=six.text_type, is_leaf=True, yang_name="key-chain", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='leafref', 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 ['macsec', 'interfaces', 'interface', 'mka', 'config']
def _get_mka_policy(self):
"""
Getter method for mka_policy, mapped from YANG variable /macsec/interfaces/interface/mka/config/mka_policy (leafref)
YANG Description: Apply MKA policy on the interface
"""
return self.__mka_policy
def _set_mka_policy(self, v, load=False):
"""
Setter method for mka_policy, mapped from YANG variable /macsec/interfaces/interface/mka/config/mka_policy (leafref)
If this variable is read-only (config: false) in the
source YANG file, then _set_mka_policy is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_mka_policy() directly.
YANG Description: Apply MKA policy on the interface
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=six.text_type, is_leaf=True, yang_name="mka-policy", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='leafref', is_config=True)
except (TypeError, ValueError):
raise ValueError({
'error-string': """mka_policy must be of a type compatible with leafref""",
'defined-type': "leafref",
'generated-type': """YANGDynClass(base=six.text_type, is_leaf=True, yang_name="mka-policy", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='leafref', is_config=True)""",
})
self.__mka_policy = t
if hasattr(self, '_set'):
self._set()
def _unset_mka_policy(self):
self.__mka_policy = YANGDynClass(base=six.text_type, is_leaf=True, yang_name="mka-policy", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='leafref', is_config=True)
def _get_key_chain(self):
"""
Getter method for key_chain, mapped from YANG variable /macsec/interfaces/interface/mka/config/key_chain (leafref)
YANG Description: Configure Key Chain name
"""
return self.__key_chain
def _set_key_chain(self, v, load=False):
"""
Setter method for key_chain, mapped from YANG variable /macsec/interfaces/interface/mka/config/key_chain (leafref)
If this variable is read-only (config: false) in the
source YANG file, then _set_key_chain is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_key_chain() directly.
YANG Description: Configure Key Chain name
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=six.text_type, is_leaf=True, yang_name="key-chain", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='leafref', is_config=True)
except (TypeError, ValueError):
raise ValueError({
'error-string': """key_chain must be of a type compatible with leafref""",
'defined-type': "leafref",
'generated-type': """YANGDynClass(base=six.text_type, is_leaf=True, yang_name="key-chain", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='leafref', is_config=True)""",
})
self.__key_chain = t
if hasattr(self, '_set'):
self._set()
def _unset_key_chain(self):
self.__key_chain = YANGDynClass(base=six.text_type, is_leaf=True, yang_name="key-chain", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='leafref', is_config=True)
mka_policy = __builtin__.property(_get_mka_policy, _set_mka_policy)
key_chain = __builtin__.property(_get_key_chain, _set_key_chain)
_pyangbind_elements = OrderedDict([('mka_policy', mka_policy), ('key_chain', key_chain), ])
class yc_counters_openconfig_macsec__macsec_interfaces_interface_mka_state_counters(PybindBase):
"""
This class was auto-generated by the PythonClass plugin for PYANG
from YANG module openconfig-macsec - based on the path /macsec/interfaces/interface/mka/state/counters. Each member element of
the container is represented as a class variable - with a specific
YANG type.
YANG Description: MKA interface counters
"""
__slots__ = ('_path_helper', '_extmethods', '__in_mkpdu','__in_sak_mkpdu','__in_cak_mkpdu','__out_mkpdu','__out_sak_mkpdu','__out_cak_mkpdu',)
_yang_name = 'counters'
_yang_namespace = 'http://openconfig.net/yang/macsec'
_pybind_generated_by = 'container'
def __init__(self, *args, **kwargs):
self._path_helper = False
self._extmethods = False
self.__in_mkpdu = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="in-mkpdu", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)
self.__in_sak_mkpdu = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="in-sak-mkpdu", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)
self.__in_cak_mkpdu = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="in-cak-mkpdu", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)
self.__out_mkpdu = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="out-mkpdu", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)
self.__out_sak_mkpdu = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="out-sak-mkpdu", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)
self.__out_cak_mkpdu = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="out-cak-mkpdu", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)
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 ['macsec', 'interfaces', 'interface', 'mka', 'state', 'counters']
def _get_in_mkpdu(self):
"""
Getter method for in_mkpdu, mapped from YANG variable /macsec/interfaces/interface/mka/state/counters/in_mkpdu (oc-yang:counter64)
YANG Description: Validated MKPDU received count
"""
return self.__in_mkpdu
def _set_in_mkpdu(self, v, load=False):
"""
Setter method for in_mkpdu, mapped from YANG variable /macsec/interfaces/interface/mka/state/counters/in_mkpdu (oc-yang:counter64)
If this variable is read-only (config: false) in the
source YANG file, then _set_in_mkpdu is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_in_mkpdu() directly.
YANG Description: Validated MKPDU received count
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="in-mkpdu", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)
except (TypeError, ValueError):
raise ValueError({
'error-string': """in_mkpdu must be of a type compatible with oc-yang:counter64""",
'defined-type': "oc-yang:counter64",
'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="in-mkpdu", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)""",
})
self.__in_mkpdu = t
if hasattr(self, '_set'):
self._set()
def _unset_in_mkpdu(self):
self.__in_mkpdu = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="in-mkpdu", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)
def _get_in_sak_mkpdu(self):
"""
Getter method for in_sak_mkpdu, mapped from YANG variable /macsec/interfaces/interface/mka/state/counters/in_sak_mkpdu (oc-yang:counter64)
YANG Description: Validated MKPDU received SAK count
"""
return self.__in_sak_mkpdu
def _set_in_sak_mkpdu(self, v, load=False):
"""
Setter method for in_sak_mkpdu, mapped from YANG variable /macsec/interfaces/interface/mka/state/counters/in_sak_mkpdu (oc-yang:counter64)
If this variable is read-only (config: false) in the
source YANG file, then _set_in_sak_mkpdu is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_in_sak_mkpdu() directly.
YANG Description: Validated MKPDU received SAK count
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="in-sak-mkpdu", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)
except (TypeError, ValueError):
raise ValueError({
'error-string': """in_sak_mkpdu must be of a type compatible with oc-yang:counter64""",
'defined-type': "oc-yang:counter64",
'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="in-sak-mkpdu", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)""",
})
self.__in_sak_mkpdu = t
if hasattr(self, '_set'):
self._set()
def _unset_in_sak_mkpdu(self):
self.__in_sak_mkpdu = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="in-sak-mkpdu", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)
def _get_in_cak_mkpdu(self):
"""
Getter method for in_cak_mkpdu, mapped from YANG variable /macsec/interfaces/interface/mka/state/counters/in_cak_mkpdu (oc-yang:counter64)
YANG Description: Validated MKPDU received CAK count
"""
return self.__in_cak_mkpdu
def _set_in_cak_mkpdu(self, v, load=False):
"""
Setter method for in_cak_mkpdu, mapped from YANG variable /macsec/interfaces/interface/mka/state/counters/in_cak_mkpdu (oc-yang:counter64)
If this variable is read-only (config: false) in the
source YANG file, then _set_in_cak_mkpdu is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_in_cak_mkpdu() directly.
YANG Description: Validated MKPDU received CAK count
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="in-cak-mkpdu", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)
except (TypeError, ValueError):
raise ValueError({
'error-string': """in_cak_mkpdu must be of a type compatible with oc-yang:counter64""",
'defined-type': "oc-yang:counter64",
'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="in-cak-mkpdu", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)""",
})
self.__in_cak_mkpdu = t
if hasattr(self, '_set'):
self._set()
def _unset_in_cak_mkpdu(self):
self.__in_cak_mkpdu = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="in-cak-mkpdu", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)
def _get_out_mkpdu(self):
"""
Getter method for out_mkpdu, mapped from YANG variable /macsec/interfaces/interface/mka/state/counters/out_mkpdu (oc-yang:counter64)
YANG Description: MKPDU sent count
"""
return self.__out_mkpdu
def _set_out_mkpdu(self, v, load=False):
"""
Setter method for out_mkpdu, mapped from YANG variable /macsec/interfaces/interface/mka/state/counters/out_mkpdu (oc-yang:counter64)
If this variable is read-only (config: false) in the
source YANG file, then _set_out_mkpdu is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_out_mkpdu() directly.
YANG Description: MKPDU sent count
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="out-mkpdu", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)
except (TypeError, ValueError):
raise ValueError({
'error-string': """out_mkpdu must be of a type compatible with oc-yang:counter64""",
'defined-type': "oc-yang:counter64",
'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="out-mkpdu", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)""",
})
self.__out_mkpdu = t
if hasattr(self, '_set'):
self._set()
def _unset_out_mkpdu(self):
self.__out_mkpdu = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="out-mkpdu", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)
def _get_out_sak_mkpdu(self):
"""
Getter method for out_sak_mkpdu, mapped from YANG variable /macsec/interfaces/interface/mka/state/counters/out_sak_mkpdu (oc-yang:counter64)
YANG Description: MKPDU SAK sent count
"""
return self.__out_sak_mkpdu
def _set_out_sak_mkpdu(self, v, load=False):
"""
Setter method for out_sak_mkpdu, mapped from YANG variable /macsec/interfaces/interface/mka/state/counters/out_sak_mkpdu (oc-yang:counter64)
If this variable is read-only (config: false) in the
source YANG file, then _set_out_sak_mkpdu is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_out_sak_mkpdu() directly.
YANG Description: MKPDU SAK sent count
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="out-sak-mkpdu", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)
except (TypeError, ValueError):
raise ValueError({
'error-string': """out_sak_mkpdu must be of a type compatible with oc-yang:counter64""",
'defined-type': "oc-yang:counter64",
'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="out-sak-mkpdu", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)""",
})
self.__out_sak_mkpdu = t
if hasattr(self, '_set'):
self._set()
def _unset_out_sak_mkpdu(self):
self.__out_sak_mkpdu = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="out-sak-mkpdu", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)
def _get_out_cak_mkpdu(self):
"""
Getter method for out_cak_mkpdu, mapped from YANG variable /macsec/interfaces/interface/mka/state/counters/out_cak_mkpdu (oc-yang:counter64)
YANG Description: MKPDU CAK sent count
"""
return self.__out_cak_mkpdu
def _set_out_cak_mkpdu(self, v, load=False):
"""
Setter method for out_cak_mkpdu, mapped from YANG variable /macsec/interfaces/interface/mka/state/counters/out_cak_mkpdu (oc-yang:counter64)
If this variable is read-only (config: false) in the
source YANG file, then _set_out_cak_mkpdu is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_out_cak_mkpdu() directly.
YANG Description: MKPDU CAK sent count
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="out-cak-mkpdu", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)
except (TypeError, ValueError):
raise ValueError({
'error-string': """out_cak_mkpdu must be of a type compatible with oc-yang:counter64""",
'defined-type': "oc-yang:counter64",
'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="out-cak-mkpdu", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)""",
})
self.__out_cak_mkpdu = t
if hasattr(self, '_set'):
self._set()
def _unset_out_cak_mkpdu(self):
self.__out_cak_mkpdu = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="out-cak-mkpdu", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='oc-yang:counter64', is_config=False)
in_mkpdu = __builtin__.property(_get_in_mkpdu)
in_sak_mkpdu = __builtin__.property(_get_in_sak_mkpdu)
in_cak_mkpdu = __builtin__.property(_get_in_cak_mkpdu)
out_mkpdu = __builtin__.property(_get_out_mkpdu)
out_sak_mkpdu = __builtin__.property(_get_out_sak_mkpdu)
out_cak_mkpdu = __builtin__.property(_get_out_cak_mkpdu)
_pyangbind_elements = OrderedDict([('in_mkpdu', in_mkpdu), ('in_sak_mkpdu', in_sak_mkpdu), ('in_cak_mkpdu', in_cak_mkpdu), ('out_mkpdu', out_mkpdu), ('out_sak_mkpdu', out_sak_mkpdu), ('out_cak_mkpdu', out_cak_mkpdu), ])
class yc_state_openconfig_macsec__macsec_interfaces_interface_mka_state(PybindBase):
"""
This class was auto-generated by the PythonClass plugin for PYANG
from YANG module openconfig-macsec - based on the path /macsec/interfaces/interface/mka/state. Each member element of
the container is represented as a class variable - with a specific
YANG type.
YANG Description: Operational state data for MKA interface
"""
__slots__ = ('_path_helper', '_extmethods', '__mka_policy','__key_chain','__counters',)
_yang_name = 'state'
_yang_namespace = 'http://openconfig.net/yang/macsec'
_pybind_generated_by = 'container'
def __init__(self, *args, **kwargs):
self._path_helper = False
self._extmethods = False
self.__mka_policy = YANGDynClass(base=six.text_type, is_leaf=True, yang_name="mka-policy", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='leafref', is_config=False)
self.__key_chain = YANGDynClass(base=six.text_type, is_leaf=True, yang_name="key-chain", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='leafref', is_config=False)
self.__counters = YANGDynClass(base=yc_counters_openconfig_macsec__macsec_interfaces_interface_mka_state_counters, is_container='container', yang_name="counters", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=False)
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 ['macsec', 'interfaces', 'interface', 'mka', 'state']
def _get_mka_policy(self):
"""
Getter method for mka_policy, mapped from YANG variable /macsec/interfaces/interface/mka/state/mka_policy (leafref)
YANG Description: Apply MKA policy on the interface
"""
return self.__mka_policy
def _set_mka_policy(self, v, load=False):
"""
Setter method for mka_policy, mapped from YANG variable /macsec/interfaces/interface/mka/state/mka_policy (leafref)
If this variable is read-only (config: false) in the
source YANG file, then _set_mka_policy is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_mka_policy() directly.
YANG Description: Apply MKA policy on the interface
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=six.text_type, is_leaf=True, yang_name="mka-policy", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='leafref', is_config=False)
except (TypeError, ValueError):
raise ValueError({
'error-string': """mka_policy must be of a type compatible with leafref""",
'defined-type': "leafref",
'generated-type': """YANGDynClass(base=six.text_type, is_leaf=True, yang_name="mka-policy", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='leafref', is_config=False)""",
})
self.__mka_policy = t
if hasattr(self, '_set'):
self._set()
def _unset_mka_policy(self):
self.__mka_policy = YANGDynClass(base=six.text_type, is_leaf=True, yang_name="mka-policy", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='leafref', is_config=False)
def _get_key_chain(self):
"""
Getter method for key_chain, mapped from YANG variable /macsec/interfaces/interface/mka/state/key_chain (leafref)
YANG Description: Configure Key Chain name
"""
return self.__key_chain
def _set_key_chain(self, v, load=False):
"""
Setter method for key_chain, mapped from YANG variable /macsec/interfaces/interface/mka/state/key_chain (leafref)
If this variable is read-only (config: false) in the
source YANG file, then _set_key_chain is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_key_chain() directly.
YANG Description: Configure Key Chain name
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=six.text_type, is_leaf=True, yang_name="key-chain", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='leafref', is_config=False)
except (TypeError, ValueError):
raise ValueError({
'error-string': """key_chain must be of a type compatible with leafref""",
'defined-type': "leafref",
'generated-type': """YANGDynClass(base=six.text_type, is_leaf=True, yang_name="key-chain", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='leafref', is_config=False)""",
})
self.__key_chain = t
if hasattr(self, '_set'):
self._set()
def _unset_key_chain(self):
self.__key_chain = YANGDynClass(base=six.text_type, is_leaf=True, yang_name="key-chain", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='leafref', is_config=False)
def _get_counters(self):
"""
Getter method for counters, mapped from YANG variable /macsec/interfaces/interface/mka/state/counters (container)
YANG Description: MKA interface counters
"""
return self.__counters
def _set_counters(self, v, load=False):
"""
Setter method for counters, mapped from YANG variable /macsec/interfaces/interface/mka/state/counters (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_counters is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_counters() directly.
YANG Description: MKA interface counters
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=yc_counters_openconfig_macsec__macsec_interfaces_interface_mka_state_counters, is_container='container', yang_name="counters", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=False)
except (TypeError, ValueError):
raise ValueError({
'error-string': """counters must be of a type compatible with container""",
'defined-type': "container",
'generated-type': """YANGDynClass(base=yc_counters_openconfig_macsec__macsec_interfaces_interface_mka_state_counters, is_container='container', yang_name="counters", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=False)""",
})
self.__counters = t
if hasattr(self, '_set'):
self._set()
def _unset_counters(self):
self.__counters = YANGDynClass(base=yc_counters_openconfig_macsec__macsec_interfaces_interface_mka_state_counters, is_container='container', yang_name="counters", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=False)
mka_policy = __builtin__.property(_get_mka_policy)
key_chain = __builtin__.property(_get_key_chain)
counters = __builtin__.property(_get_counters)
_pyangbind_elements = OrderedDict([('mka_policy', mka_policy), ('key_chain', key_chain), ('counters', counters), ])
class yc_mka_openconfig_macsec__macsec_interfaces_interface_mka(PybindBase):
"""
This class was auto-generated by the PythonClass plugin for PYANG
from YANG module openconfig-macsec - based on the path /macsec/interfaces/interface/mka. Each member element of
the container is represented as a class variable - with a specific
YANG type.
YANG Description: Enclosing container for the MKA interface
"""
__slots__ = ('_path_helper', '_extmethods', '__config','__state',)
_yang_name = 'mka'
_yang_namespace = 'http://openconfig.net/yang/macsec'
_pybind_generated_by = 'container'
def __init__(self, *args, **kwargs):
self._path_helper = False
self._extmethods = False
self.__config = YANGDynClass(base=yc_config_openconfig_macsec__macsec_interfaces_interface_mka_config, is_container='container', yang_name="config", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True)
self.__state = YANGDynClass(base=yc_state_openconfig_macsec__macsec_interfaces_interface_mka_state, is_container='container', yang_name="state", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', 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 ['macsec', 'interfaces', 'interface', 'mka']
def _get_config(self):
"""
Getter method for config, mapped from YANG variable /macsec/interfaces/interface/mka/config (container)
YANG Description: Configuration data for MKA interface
"""
return self.__config
def _set_config(self, v, load=False):
"""
Setter method for config, mapped from YANG variable /macsec/interfaces/interface/mka/config (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_config is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_config() directly.
YANG Description: Configuration data for MKA interface
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=yc_config_openconfig_macsec__macsec_interfaces_interface_mka_config, is_container='container', yang_name="config", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True)
except (TypeError, ValueError):
raise ValueError({
'error-string': """config must be of a type compatible with container""",
'defined-type': "container",
'generated-type': """YANGDynClass(base=yc_config_openconfig_macsec__macsec_interfaces_interface_mka_config, is_container='container', yang_name="config", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True)""",
})
self.__config = t
if hasattr(self, '_set'):
self._set()
def _unset_config(self):
self.__config = YANGDynClass(base=yc_config_openconfig_macsec__macsec_interfaces_interface_mka_config, is_container='container', yang_name="config", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True)
def _get_state(self):
"""
Getter method for state, mapped from YANG variable /macsec/interfaces/interface/mka/state (container)
YANG Description: Operational state data for MKA interface
"""
return self.__state
def _set_state(self, v, load=False):
"""
Setter method for state, mapped from YANG variable /macsec/interfaces/interface/mka/state (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_state is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_state() directly.
YANG Description: Operational state data for MKA interface
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=yc_state_openconfig_macsec__macsec_interfaces_interface_mka_state, is_container='container', yang_name="state", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True)
except (TypeError, ValueError):
raise ValueError({
'error-string': """state must be of a type compatible with container""",
'defined-type': "container",
'generated-type': """YANGDynClass(base=yc_state_openconfig_macsec__macsec_interfaces_interface_mka_state, is_container='container', yang_name="state", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True)""",
})
self.__state = t
if hasattr(self, '_set'):
self._set()
def _unset_state(self):
self.__state = YANGDynClass(base=yc_state_openconfig_macsec__macsec_interfaces_interface_mka_state, is_container='container', yang_name="state", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True)
config = __builtin__.property(_get_config, _set_config)
state = __builtin__.property(_get_state, _set_state)
_pyangbind_elements = OrderedDict([('config', config), ('state', state), ])
class yc_interface_openconfig_macsec__macsec_interfaces_interface(PybindBase):
"""
This class was auto-generated by the PythonClass plugin for PYANG
from YANG module openconfig-macsec - based on the path /macsec/interfaces/interface. Each member element of
the container is represented as a class variable - with a specific
YANG type.
YANG Description: List of interfaces on which MACsec is enabled / available
"""
__slots__ = ('_path_helper', '_extmethods', '__name','__config','__state','__scsa_tx','__scsa_rx','__mka',)
_yang_name = 'interface'
_yang_namespace = 'http://openconfig.net/yang/macsec'
_pybind_generated_by = 'container'
def __init__(self, *args, **kwargs):
self._path_helper = False
self._extmethods = False
self.__name = YANGDynClass(base=six.text_type, is_leaf=True, yang_name="name", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, is_keyval=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='leafref', is_config=True)
self.__config = YANGDynClass(base=yc_config_openconfig_macsec__macsec_interfaces_interface_config, is_container='container', yang_name="config", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True)
self.__state = YANGDynClass(base=yc_state_openconfig_macsec__macsec_interfaces_interface_state, is_container='container', yang_name="state", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True)
self.__scsa_tx = YANGDynClass(base=yc_scsa_tx_openconfig_macsec__macsec_interfaces_interface_scsa_tx, is_container='container', yang_name="scsa-tx", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True)
self.__scsa_rx = YANGDynClass(base=yc_scsa_rx_openconfig_macsec__macsec_interfaces_interface_scsa_rx, is_container='container', yang_name="scsa-rx", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True)
self.__mka = YANGDynClass(base=yc_mka_openconfig_macsec__macsec_interfaces_interface_mka, is_container='container', yang_name="mka", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', 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 ['macsec', 'interfaces', 'interface']
def _get_name(self):
"""
Getter method for name, mapped from YANG variable /macsec/interfaces/interface/name (leafref)
YANG Description: Reference to the list key
"""
return self.__name
def _set_name(self, v, load=False):
"""
Setter method for name, mapped from YANG variable /macsec/interfaces/interface/name (leafref)
If this variable is read-only (config: false) in the
source YANG file, then _set_name is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_name() directly.
YANG Description: Reference to the list key
"""
parent = getattr(self, "_parent", None)
if parent is not None and load is False:
raise AttributeError("Cannot set keys directly when" +
" within an instantiated list")
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=six.text_type, is_leaf=True, yang_name="name", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, is_keyval=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='leafref', is_config=True)
except (TypeError, ValueError):
raise ValueError({
'error-string': """name must be of a type compatible with leafref""",
'defined-type': "leafref",
'generated-type': """YANGDynClass(base=six.text_type, is_leaf=True, yang_name="name", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, is_keyval=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='leafref', is_config=True)""",
})
self.__name = t
if hasattr(self, '_set'):
self._set()
def _unset_name(self):
self.__name = YANGDynClass(base=six.text_type, is_leaf=True, yang_name="name", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, is_keyval=True, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='leafref', is_config=True)
def _get_config(self):
"""
Getter method for config, mapped from YANG variable /macsec/interfaces/interface/config (container)
YANG Description: Configuration data for MACsec on each interface
"""
return self.__config
def _set_config(self, v, load=False):
"""
Setter method for config, mapped from YANG variable /macsec/interfaces/interface/config (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_config is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_config() directly.
YANG Description: Configuration data for MACsec on each interface
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=yc_config_openconfig_macsec__macsec_interfaces_interface_config, is_container='container', yang_name="config", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True)
except (TypeError, ValueError):
raise ValueError({
'error-string': """config must be of a type compatible with container""",
'defined-type': "container",
'generated-type': """YANGDynClass(base=yc_config_openconfig_macsec__macsec_interfaces_interface_config, is_container='container', yang_name="config", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True)""",
})
self.__config = t
if hasattr(self, '_set'):
self._set()
def _unset_config(self):
self.__config = YANGDynClass(base=yc_config_openconfig_macsec__macsec_interfaces_interface_config, is_container='container', yang_name="config", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True)
def _get_state(self):
"""
Getter method for state, mapped from YANG variable /macsec/interfaces/interface/state (container)
YANG Description: Operational state data
"""
return self.__state
def _set_state(self, v, load=False):
"""
Setter method for state, mapped from YANG variable /macsec/interfaces/interface/state (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_state is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_state() directly.
YANG Description: Operational state data
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=yc_state_openconfig_macsec__macsec_interfaces_interface_state, is_container='container', yang_name="state", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True)
except (TypeError, ValueError):
raise ValueError({
'error-string': """state must be of a type compatible with container""",
'defined-type': "container",
'generated-type': """YANGDynClass(base=yc_state_openconfig_macsec__macsec_interfaces_interface_state, is_container='container', yang_name="state", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True)""",
})
self.__state = t
if hasattr(self, '_set'):
self._set()
def _unset_state(self):
self.__state = YANGDynClass(base=yc_state_openconfig_macsec__macsec_interfaces_interface_state, is_container='container', yang_name="state", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True)
def _get_scsa_tx(self):
"""
Getter method for scsa_tx, mapped from YANG variable /macsec/interfaces/interface/scsa_tx (container)
YANG Description: Enclosing container for transmitted packets for Secure Channel and
Secure Association
"""
return self.__scsa_tx
def _set_scsa_tx(self, v, load=False):
"""
Setter method for scsa_tx, mapped from YANG variable /macsec/interfaces/interface/scsa_tx (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_scsa_tx is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_scsa_tx() directly.
YANG Description: Enclosing container for transmitted packets for Secure Channel and
Secure Association
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=yc_scsa_tx_openconfig_macsec__macsec_interfaces_interface_scsa_tx, is_container='container', yang_name="scsa-tx", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True)
except (TypeError, ValueError):
raise ValueError({
'error-string': """scsa_tx must be of a type compatible with container""",
'defined-type': "container",
'generated-type': """YANGDynClass(base=yc_scsa_tx_openconfig_macsec__macsec_interfaces_interface_scsa_tx, is_container='container', yang_name="scsa-tx", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True)""",
})
self.__scsa_tx = t
if hasattr(self, '_set'):
self._set()
def _unset_scsa_tx(self):
self.__scsa_tx = YANGDynClass(base=yc_scsa_tx_openconfig_macsec__macsec_interfaces_interface_scsa_tx, is_container='container', yang_name="scsa-tx", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True)
def _get_scsa_rx(self):
"""
Getter method for scsa_rx, mapped from YANG variable /macsec/interfaces/interface/scsa_rx (container)
YANG Description: Enclosing container for received packets for Secure Channel and
Secure Association
"""
return self.__scsa_rx
def _set_scsa_rx(self, v, load=False):
"""
Setter method for scsa_rx, mapped from YANG variable /macsec/interfaces/interface/scsa_rx (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_scsa_rx is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_scsa_rx() directly.
YANG Description: Enclosing container for received packets for Secure Channel and
Secure Association
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=yc_scsa_rx_openconfig_macsec__macsec_interfaces_interface_scsa_rx, is_container='container', yang_name="scsa-rx", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True)
except (TypeError, ValueError):
raise ValueError({
'error-string': """scsa_rx must be of a type compatible with container""",
'defined-type': "container",
'generated-type': """YANGDynClass(base=yc_scsa_rx_openconfig_macsec__macsec_interfaces_interface_scsa_rx, is_container='container', yang_name="scsa-rx", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True)""",
})
self.__scsa_rx = t
if hasattr(self, '_set'):
self._set()
def _unset_scsa_rx(self):
self.__scsa_rx = YANGDynClass(base=yc_scsa_rx_openconfig_macsec__macsec_interfaces_interface_scsa_rx, is_container='container', yang_name="scsa-rx", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True)
def _get_mka(self):
"""
Getter method for mka, mapped from YANG variable /macsec/interfaces/interface/mka (container)
YANG Description: Enclosing container for the MKA interface
"""
return self.__mka
def _set_mka(self, v, load=False):
"""
Setter method for mka, mapped from YANG variable /macsec/interfaces/interface/mka (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_mka is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_mka() directly.
YANG Description: Enclosing container for the MKA interface
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=yc_mka_openconfig_macsec__macsec_interfaces_interface_mka, is_container='container', yang_name="mka", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True)
except (TypeError, ValueError):
raise ValueError({
'error-string': """mka must be of a type compatible with container""",
'defined-type': "container",
'generated-type': """YANGDynClass(base=yc_mka_openconfig_macsec__macsec_interfaces_interface_mka, is_container='container', yang_name="mka", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True)""",
})
self.__mka = t
if hasattr(self, '_set'):
self._set()
def _unset_mka(self):
self.__mka = YANGDynClass(base=yc_mka_openconfig_macsec__macsec_interfaces_interface_mka, is_container='container', yang_name="mka", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True)
name = __builtin__.property(_get_name, _set_name)
config = __builtin__.property(_get_config, _set_config)
state = __builtin__.property(_get_state, _set_state)
scsa_tx = __builtin__.property(_get_scsa_tx, _set_scsa_tx)
scsa_rx = __builtin__.property(_get_scsa_rx, _set_scsa_rx)
mka = __builtin__.property(_get_mka, _set_mka)
_pyangbind_elements = OrderedDict([('name', name), ('config', config), ('state', state), ('scsa_tx', scsa_tx), ('scsa_rx', scsa_rx), ('mka', mka), ])
class yc_interfaces_openconfig_macsec__macsec_interfaces(PybindBase):
"""
This class was auto-generated by the PythonClass plugin for PYANG
from YANG module openconfig-macsec - based on the path /macsec/interfaces. Each member element of
the container is represented as a class variable - with a specific
YANG type.
YANG Description: Enclosing container for the MACsec interfaces list
"""
__slots__ = ('_path_helper', '_extmethods', '__interface',)
_yang_name = 'interfaces'
_yang_namespace = 'http://openconfig.net/yang/macsec'
_pybind_generated_by = 'container'
def __init__(self, *args, **kwargs):
self._path_helper = False
self._extmethods = False
self.__interface = YANGDynClass(base=YANGListType("name",yc_interface_openconfig_macsec__macsec_interfaces_interface, yang_name="interface", parent=self, is_container='list', user_ordered=False, path_helper=self._path_helper, yang_keys='name', extensions=None), is_container='list', yang_name="interface", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='list', 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 ['macsec', 'interfaces']
def _get_interface(self):
"""
Getter method for interface, mapped from YANG variable /macsec/interfaces/interface (list)
YANG Description: List of interfaces on which MACsec is enabled / available
"""
return self.__interface
def _set_interface(self, v, load=False):
"""
Setter method for interface, mapped from YANG variable /macsec/interfaces/interface (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_interface is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_interface() directly.
YANG Description: List of interfaces on which MACsec is enabled / available
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=YANGListType("name",yc_interface_openconfig_macsec__macsec_interfaces_interface, yang_name="interface", parent=self, is_container='list', user_ordered=False, path_helper=self._path_helper, yang_keys='name', extensions=None), is_container='list', yang_name="interface", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='list', is_config=True)
except (TypeError, ValueError):
raise ValueError({
'error-string': """interface must be of a type compatible with list""",
'defined-type': "list",
'generated-type': """YANGDynClass(base=YANGListType("name",yc_interface_openconfig_macsec__macsec_interfaces_interface, yang_name="interface", parent=self, is_container='list', user_ordered=False, path_helper=self._path_helper, yang_keys='name', extensions=None), is_container='list', yang_name="interface", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='list', is_config=True)""",
})
self.__interface = t
if hasattr(self, '_set'):
self._set()
def _unset_interface(self):
self.__interface = YANGDynClass(base=YANGListType("name",yc_interface_openconfig_macsec__macsec_interfaces_interface, yang_name="interface", parent=self, is_container='list', user_ordered=False, path_helper=self._path_helper, yang_keys='name', extensions=None), is_container='list', yang_name="interface", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='list', is_config=True)
interface = __builtin__.property(_get_interface, _set_interface)
_pyangbind_elements = OrderedDict([('interface', interface), ])
class yc_macsec_openconfig_macsec__macsec(PybindBase):
"""
This class was auto-generated by the PythonClass plugin for PYANG
from YANG module openconfig-macsec - based on the path /macsec. Each member element of
the container is represented as a class variable - with a specific
YANG type.
YANG Description: The MACsec
"""
__slots__ = ('_path_helper', '_extmethods', '__mka','__interfaces',)
_yang_name = 'macsec'
_yang_namespace = 'http://openconfig.net/yang/macsec'
_pybind_generated_by = 'container'
def __init__(self, *args, **kwargs):
self._path_helper = False
self._extmethods = False
self.__mka = YANGDynClass(base=yc_mka_openconfig_macsec__macsec_mka, is_container='container', yang_name="mka", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True)
self.__interfaces = YANGDynClass(base=yc_interfaces_openconfig_macsec__macsec_interfaces, is_container='container', yang_name="interfaces", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', 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 ['macsec']
def _get_mka(self):
"""
Getter method for mka, mapped from YANG variable /macsec/mka (container)
YANG Description: The MKA
"""
return self.__mka
def _set_mka(self, v, load=False):
"""
Setter method for mka, mapped from YANG variable /macsec/mka (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_mka is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_mka() directly.
YANG Description: The MKA
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=yc_mka_openconfig_macsec__macsec_mka, is_container='container', yang_name="mka", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True)
except (TypeError, ValueError):
raise ValueError({
'error-string': """mka must be of a type compatible with container""",
'defined-type': "container",
'generated-type': """YANGDynClass(base=yc_mka_openconfig_macsec__macsec_mka, is_container='container', yang_name="mka", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True)""",
})
self.__mka = t
if hasattr(self, '_set'):
self._set()
def _unset_mka(self):
self.__mka = YANGDynClass(base=yc_mka_openconfig_macsec__macsec_mka, is_container='container', yang_name="mka", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True)
def _get_interfaces(self):
"""
Getter method for interfaces, mapped from YANG variable /macsec/interfaces (container)
YANG Description: Enclosing container for the MACsec interfaces list
"""
return self.__interfaces
def _set_interfaces(self, v, load=False):
"""
Setter method for interfaces, mapped from YANG variable /macsec/interfaces (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_interfaces is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_interfaces() directly.
YANG Description: Enclosing container for the MACsec interfaces list
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=yc_interfaces_openconfig_macsec__macsec_interfaces, is_container='container', yang_name="interfaces", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True)
except (TypeError, ValueError):
raise ValueError({
'error-string': """interfaces must be of a type compatible with container""",
'defined-type': "container",
'generated-type': """YANGDynClass(base=yc_interfaces_openconfig_macsec__macsec_interfaces, is_container='container', yang_name="interfaces", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True)""",
})
self.__interfaces = t
if hasattr(self, '_set'):
self._set()
def _unset_interfaces(self):
self.__interfaces = YANGDynClass(base=yc_interfaces_openconfig_macsec__macsec_interfaces, is_container='container', yang_name="interfaces", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True)
mka = __builtin__.property(_get_mka, _set_mka)
interfaces = __builtin__.property(_get_interfaces, _set_interfaces)
_pyangbind_elements = OrderedDict([('mka', mka), ('interfaces', interfaces), ])
class openconfig_macsec(PybindBase):
"""
This class was auto-generated by the PythonClass plugin for PYANG
from YANG module openconfig-macsec - based on the path /openconfig-macsec. Each member element of
the container is represented as a class variable - with a specific
YANG type.
YANG Description: This module defines configuration and state data for
MACsec IEEE Std 802.1AE-2018.
"""
__slots__ = ('_path_helper', '_extmethods', '__macsec',)
_yang_name = 'openconfig-macsec'
_yang_namespace = 'http://openconfig.net/yang/macsec'
_pybind_generated_by = 'container'
def __init__(self, *args, **kwargs):
self._path_helper = False
self._extmethods = False
self.__macsec = YANGDynClass(base=yc_macsec_openconfig_macsec__macsec, is_container='container', yang_name="macsec", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', 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 []
def _get_macsec(self):
"""
Getter method for macsec, mapped from YANG variable /macsec (container)
YANG Description: The MACsec
"""
return self.__macsec
def _set_macsec(self, v, load=False):
"""
Setter method for macsec, mapped from YANG variable /macsec (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_macsec is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_macsec() directly.
YANG Description: The MACsec
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=yc_macsec_openconfig_macsec__macsec, is_container='container', yang_name="macsec", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True)
except (TypeError, ValueError):
raise ValueError({
'error-string': """macsec must be of a type compatible with container""",
'defined-type': "container",
'generated-type': """YANGDynClass(base=yc_macsec_openconfig_macsec__macsec, is_container='container', yang_name="macsec", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True)""",
})
self.__macsec = t
if hasattr(self, '_set'):
self._set()
def _unset_macsec(self):
self.__macsec = YANGDynClass(base=yc_macsec_openconfig_macsec__macsec, is_container='container', yang_name="macsec", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions=None, namespace='http://openconfig.net/yang/macsec', defining_module='openconfig-macsec', yang_type='container', is_config=True)
macsec = __builtin__.property(_get_macsec, _set_macsec)
_pyangbind_elements = OrderedDict([('macsec', macsec), ])
class openconfig_macsec_types(PybindBase):
"""
This class was auto-generated by the PythonClass plugin for PYANG
from YANG module openconfig-macsec-types - based on the path /openconfig-macsec-types. Each member element of
the container is represented as a class variable - with a specific
YANG type.
YANG Description: This module defines types related to the MACsec configuration
and operational state model.
"""
_pyangbind_elements = {}
|
google/gnxi
|
oc_config_validate/oc_config_validate/models/macsec.py
|
Python
|
apache-2.0
| 391,144 | 0.007626 |
# 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.
"""
Port of NNVM version of MobileNet to Relay.
"""
# pylint: disable=invalid-name
from tvm import relay
from . import layers
from .init import create_workload
def conv_block(
data,
name,
channels,
kernel_size=(3, 3),
strides=(1, 1),
padding=(1, 1),
epsilon=1e-5,
layout="NCHW",
):
"""Helper function to construct conv_bn-relu"""
# convolution + bn + relu
conv = layers.conv2d(
data=data,
channels=channels,
kernel_size=kernel_size,
strides=strides,
padding=padding,
data_layout=layout,
kernel_layout=layers.conv_kernel_layout(layout),
name=name + "_conv",
)
bn = layers.batch_norm_infer(data=conv, epsilon=epsilon, name=name + "_bn")
act = relay.nn.relu(data=bn)
return act
def separable_conv_block(
data,
name,
depthwise_channels,
pointwise_channels,
kernel_size=(3, 3),
downsample=False,
padding=(1, 1),
epsilon=1e-5,
layout="NCHW",
dtype="float32",
):
"""Helper function to get a separable conv block"""
if downsample:
strides = (2, 2)
else:
strides = (1, 1)
# depthwise convolution + bn + relu
if layout == "NCHW":
wshape = (depthwise_channels, 1) + kernel_size
elif layout == "NHWC":
wshape = kernel_size + (depthwise_channels, 1)
else:
raise ValueError("Invalid layout: " + layout)
bn_axis = layout.index("C")
weight = relay.var(name + "_weight", shape=wshape, dtype=dtype)
conv1 = layers.conv2d(
data=data,
weight=weight,
channels=depthwise_channels,
groups=depthwise_channels,
kernel_size=kernel_size,
strides=strides,
padding=padding,
data_layout=layout,
kernel_layout=layers.conv_kernel_layout(layout, True),
name=name + "_depthwise_conv1",
)
bn1 = layers.batch_norm_infer(data=conv1, epsilon=epsilon, axis=bn_axis, name=name + "_bn1")
act1 = relay.nn.relu(data=bn1)
# pointwise convolution + bn + relu
conv2 = layers.conv2d(
data=act1,
channels=pointwise_channels,
kernel_size=(1, 1),
strides=(1, 1),
padding=(0, 0),
data_layout=layout,
kernel_layout=layers.conv_kernel_layout(layout),
name=name + "_conv2",
)
bn2 = layers.batch_norm_infer(data=conv2, epsilon=epsilon, axis=bn_axis, name=name + "_bn2")
act2 = relay.nn.relu(data=bn2)
return act2
def mobile_net(
num_classes=1000,
data_shape=(1, 3, 224, 224),
dtype="float32",
alpha=1.0,
is_shallow=False,
layout="NCHW",
):
"""Function to construct a MobileNet"""
data = relay.var("data", shape=data_shape, dtype=dtype)
body = conv_block(data, "conv_block_1", int(32 * alpha), strides=(2, 2), layout=layout)
body = separable_conv_block(
body, "separable_conv_block_1", int(32 * alpha), int(64 * alpha), layout=layout, dtype=dtype
)
body = separable_conv_block(
body,
"separable_conv_block_2",
int(64 * alpha),
int(128 * alpha),
downsample=True,
layout=layout,
dtype=dtype,
)
body = separable_conv_block(
body,
"separable_conv_block_3",
int(128 * alpha),
int(128 * alpha),
layout=layout,
dtype=dtype,
)
body = separable_conv_block(
body,
"separable_conv_block_4",
int(128 * alpha),
int(256 * alpha),
downsample=True,
layout=layout,
dtype=dtype,
)
body = separable_conv_block(
body,
"separable_conv_block_5",
int(256 * alpha),
int(256 * alpha),
layout=layout,
dtype=dtype,
)
body = separable_conv_block(
body,
"separable_conv_block_6",
int(256 * alpha),
int(512 * alpha),
downsample=True,
layout=layout,
dtype=dtype,
)
if is_shallow:
body = separable_conv_block(
body,
"separable_conv_block_7",
int(512 * alpha),
int(1024 * alpha),
downsample=True,
layout=layout,
dtype=dtype,
)
body = separable_conv_block(
body,
"separable_conv_block_8",
int(1024 * alpha),
int(1024 * alpha),
downsample=True,
layout=layout,
dtype=dtype,
)
else:
for i in range(7, 12):
body = separable_conv_block(
body,
"separable_conv_block_%d" % i,
int(512 * alpha),
int(512 * alpha),
layout=layout,
dtype=dtype,
)
body = separable_conv_block(
body,
"separable_conv_block_12",
int(512 * alpha),
int(1024 * alpha),
downsample=True,
layout=layout,
dtype=dtype,
)
body = separable_conv_block(
body,
"separable_conv_block_13",
int(1024 * alpha),
int(1024 * alpha),
layout=layout,
dtype=dtype,
)
pool = relay.nn.global_avg_pool2d(data=body, layout=layout)
flatten = relay.nn.batch_flatten(data=pool)
weight = relay.var("fc_weight")
bias = relay.var("fc_bias")
fc = relay.nn.dense(data=flatten, weight=weight, units=num_classes)
fc = relay.nn.bias_add(fc, bias)
softmax = relay.nn.softmax(data=fc)
return relay.Function(relay.analysis.free_vars(softmax), softmax)
def get_workload(
batch_size=1, num_classes=1000, image_shape=(3, 224, 224), dtype="float32", layout="NCHW"
):
"""Get benchmark workload for mobilenet
Parameters
----------
batch_size : int, optional
The batch size used in the model
num_classes : int, optional
Number of classes
image_shape : tuple, optional
The input image shape, cooperate with layout
dtype : str, optional
The data type
layout : str, optional
The data layout of image_shape and the operators
cooperate with image_shape
Returns
-------
mod : tvm.IRModule
The relay module that contains a MobileNet network.
params : dict of str to NDArray
The parameters.
"""
data_shape = tuple([batch_size] + list(image_shape))
net = mobile_net(
num_classes=num_classes,
data_shape=data_shape,
dtype=dtype,
alpha=1.0,
is_shallow=False,
layout=layout,
)
return create_workload(net)
|
dmlc/tvm
|
python/tvm/relay/testing/mobilenet.py
|
Python
|
apache-2.0
| 7,444 | 0.000672 |
#!/usr/bin/python3
"""Filter to normalize/canonicalize objdump --dwarf=info dumps.
Reads stdin, normalizes / canonicalizes and/or strips the output of objdump
--dwarf to make it easier to "diff".
Support is provided for rewriting absolute offsets within the dump to relative
offsets. A chunk like
<2><2d736>: Abbrev Number: 5 (DW_TAG_variable)
<2d737> DW_AT_name : oy
<2d73a> DW_AT_decl_line : 23
<2d73b> DW_AT_location : 0x15eee8 (location list)
<2d73f> DW_AT_type : <0x2f1f2>
Would be rewritten as
<2><0>: Abbrev Number: 5 (DW_TAG_variable)
<0> DW_AT_name : oy
<0> DW_AT_decl_line : 23
<0> DW_AT_location : ... (location list)
<0> DW_AT_type : <0x10>
You can also request that all offsets and PC info be stripped, although that can
can obscure some important differences. Abstract origin references are tracked
and annotated (unless disabled).
"""
import getopt
import os
import re
import sys
import script_utils as u
# Input and output file (if not specified, defaults to stdin/stdout)
flag_infile = None
flag_outfile = None
# Perform normalization
flag_normalize = True
# Compile units to be included in dump.
flag_compunits = {}
# Strip offsets if true
flag_strip_offsets = False
# Strip hi/lo PC and location lists
flag_strip_pcinfo = False
# Annotate abstract origin refs
flag_annotate_abstract = True
# Strip these
pcinfo_attrs = {"DW_AT_low_pc": 1, "DW_AT_high_pc": 1}
# Untracked DW refs
untracked_dwrefs = {}
# Line buffer
linebuf = None
linebuffered = False
#......................................................................
# Regular expressions to match:
# Begin-DIE preamble
bdiere = re.compile(r"^(\s*)\<(\d+)\>\<(\S+)\>\:(.*)$")
bdiezre = re.compile(r"^\s*Abbrev Number\:\s+0\s*$")
bdiebodre = re.compile(r"^\s*Abbrev Number\:\s+\d+\s+\(DW_TAG_(\S+)\)\s*$")
# Within-DIE regex
indiere = re.compile(r"^(\s*)\<(\S+)\>(\s+)(DW_AT_\S+)(\s*)\:(.*)$")
indie2re = re.compile(r"^(\s*)\<(\S+)\>(\s+)(Unknown\s+AT\s+value)(\s*)\:(.*)$")
# For grabbing dwarf ref from attr value
absore = re.compile(r"^\s*\<\S+\>\s+DW_AT_\S+\s*\:\s*\<0x(\S+)\>.*$")
# Attr value dwarf offset
attrdwoffre = re.compile(r"^(.*)\<0x(\S+)\>(.*)$")
def compute_reloff(absoff, origin):
"""Compute relative offset from absolute offset."""
oabs = int(absoff, 16)
if not flag_normalize:
return oabs
odec = int(origin, 16)
delta = oabs - odec
return delta
def abstorel(val, diestart):
"""Convert absolute to relative DIE offset."""
# FIXME: this will not handle backwards refs; that would
# require multiple passes.
m1 = attrdwoffre.match(val)
if m1:
absref = m1.group(2)
if absref in diestart:
val = re.sub(r"<0x%s>" % absref, r"<0x%x>" % diestart[absref], val)
u.verbose(3, "abs %s converted to rel %s" % (absref, val))
return (0, val)
return (1, absref)
return (2, None)
def munge_attrval(attr, oval, diestart):
"""Munge attr value."""
# Convert abs reference to rel reference.
# FIXME: this will not handle backwards refs; that would
# require multiple passes.
code, val = abstorel(oval, diestart)
if code == 1:
absref = val
if absref in untracked_dwrefs:
val = untracked_dwrefs[absref]
else:
n = len(untracked_dwrefs)
if flag_normalize:
unk = (" <untracked %d>" % (n+1))
else:
unk = (" <untracked 0x%s>" % absref)
untracked_dwrefs[absref] = unk
val = unk
if code == 2:
val = oval
if flag_strip_pcinfo:
if attr in pcinfo_attrs:
val = "<stripped>"
return val
def read_line(inf):
"""Read an input line."""
global linebuffered
global linebuf
if linebuffered:
linebuffered = False
u.verbose(3, "buffered line is %s" % linebuf)
return linebuf
line = inf.readline()
u.verbose(3, "line is %s" % line.rstrip())
return line
def unread_line(line):
"""Unread an input line."""
global linebuffered
global linebuf
u.verbose(3, "unread_line on %s" % line.rstrip())
if linebuffered:
u.error("internal error: multiple line unread")
linebuffered = True
linebuf = line
def read_die(inf, outf):
"""Reads in and returns the next DIE."""
lines = []
indie = False
while True:
line = read_line(inf)
if not line:
break
m1 = bdiere.match(line)
if not indie:
if m1:
lines.append(line)
indie = True
continue
outf.write(line)
else:
if m1:
unread_line(line)
break
m2 = indiere.match(line)
if not m2:
m2 = indie2re.match(line)
if not m2:
unread_line(line)
break
lines.append(line)
u.verbose(2, "=-= DIE read:")
for line in lines:
u.verbose(2, "=-= %s" % line.rstrip())
return lines
def emit_die(lines, outf, origin, diename, diestart):
"""Emit body of DIE."""
# First line
m1 = bdiere.match(lines[0])
if not m1:
u.error("internal error: first line of DIE "
"should match bdiere: %s" % lines[0])
sp = m1.group(1)
depth = m1.group(2)
absoff = m1.group(3)
rem = m1.group(4)
off = compute_reloff(absoff, origin)
if flag_strip_offsets:
outf.write("%s<%s>:%s\n" % (sp, depth, rem))
else:
outf.write("%s<%s><%0x>:%s\n" % (sp, depth, off, rem))
# Remaining lines
for line in lines[1:]:
m2 = indiere.match(line)
if not m2:
m2 = indie2re.match(line)
if not m2:
u.error("internal error: m2 match failed on attr line")
sp1 = m2.group(1)
absoff = m2.group(2)
sp2 = m2.group(3)
attr = m2.group(4)
sp3 = m2.group(5)
rem = m2.group(6)
addend = ""
off = compute_reloff(absoff, origin)
u.verbose(3, "attr is %s" % attr)
# Special sauce if abs origin.
if attr == "DW_AT_abstract_origin":
m3 = absore.match(line)
if m3:
absoff = m3.group(1)
reloff = compute_reloff(absoff, origin)
if reloff in diename:
addend = "// " + diename[reloff]
else:
u.verbose(2, "absore() failed on %s\n", line)
# Post-process attr value
rem = munge_attrval(attr, rem, diestart)
# Emit
if flag_strip_offsets:
outf.write("%s%s%s:%s%s%s\n" % (sp1, sp2, attr,
sp3, rem, addend))
else:
outf.write("%s<%0x>%s%s:%s%s%s\n" % (sp1, off, sp2,
attr, sp3, rem, addend))
def attrval(lines, tattr):
"""Return the specified attr for this DIE (or empty string if no name)."""
for line in lines[1:]:
m2 = indiere.match(line)
if not m2:
m2 = indie2re.match(line)
if not m2:
u.error("attr match failed for %s" % line)
attr = m2.group(4)
if attr == tattr:
rem = m2.group(6)
return rem.strip()
return ""
def perform_filt(inf, outf):
"""Read inf and filter contents to outf."""
# Records DIE starts: hex string => new offset
diestart = {}
# Maps rel DIE offset to name. Note that not all DIEs have names.
diename = {}
# Origin (starting absolute offset)
origin = None
# Set to true if output is filtered off
filtered = False
if flag_compunits:
u.verbose(1, "Selected compunits:")
for cu in sorted(flag_compunits):
u.verbose(1, "%s" % cu)
# Read input
while True:
dielines = read_die(inf, outf)
if not dielines:
break
# Process starting line of DIE
line1 = dielines[0]
m1 = bdiere.match(line1)
if not m1:
u.error("internal error: first line of DIE should match bdiere")
absoff = m1.group(3)
rem = m1.group(4)
if not origin:
u.verbose(2, "origin set to %s" % absoff)
origin = absoff
off = compute_reloff(absoff, origin)
diestart[absoff] = off
# Handle zero terminators.
if bdiezre.match(rem):
if not filtered:
emit_die(dielines, outf, origin, diename, diestart)
continue
# See what flavor of DIE this is to adjust filtering.
m2 = bdiebodre.match(rem)
if not m2:
u.error("bdiebodre/bdiezre match failed on: '%s'" % rem)
tag = m2.group(1)
u.verbose(2, "=-= tag = %s" % tag)
if flag_compunits and tag == "compile_unit":
name = attrval(dielines, "DW_AT_name")
if name:
if name in flag_compunits:
u.verbose(1, "=-= output enabled since %s is in compunits" % name)
filtered = False
else:
u.verbose(1, "=-= output disabled since %s not in compunits" % name)
filtered = True
# Emit die if not filtered
if not filtered:
u.verbose(2, "=-= emit DIE")
emit_die(dielines, outf, origin, diename, diestart)
else:
u.verbose(2, "=-= flush DIE (filtered): %s" % dielines[0])
def perform():
"""Main driver routine."""
inf = sys.stdin
outf = sys.stdout
if flag_infile:
try:
inf = open(flag_infile, "rb")
except IOError as e:
u.error("unable to open input file %s: "
"%s" % (flag_infile, e.strerror))
if flag_outfile:
try:
outf = open(flag_outfile, "wb")
except IOError as e:
u.error("unable to open output file %s: "
"%s" % (flag_outfile, e.strerror))
perform_filt(inf, outf)
if flag_infile:
inf.close()
if flag_outfile:
outf.close()
def usage(msgarg):
"""Print usage and exit."""
me = os.path.basename(sys.argv[0])
if msgarg:
sys.stderr.write("error: %s\n" % msgarg)
print("""\
usage: %s [options] < input > output
options:
-d increase debug msg verbosity level
-i F read from input file F
-o G write to output file O
-u X emit only compile unit match name X
-S strip DWARF offsets from die/attr dumps
-P strip location lists, hi/lo PC attrs
-A do not annotate abstract origin refs with name
-N don't rewrite offsets (turn normalization off)
""" % me)
sys.exit(1)
def parse_args():
"""Command line argument parsing."""
global flag_infile, flag_outfile, flag_strip_offsets, flag_strip_pcinfo
global flag_annotate_abstract, flag_normalize
try:
optlist, _ = getopt.getopt(sys.argv[1:], "di:o:u:SPAN")
except getopt.GetoptError as err:
# unrecognized option
usage(str(err))
for opt, arg in optlist:
if opt == "-d":
u.increment_verbosity()
elif opt == "-i":
flag_infile = arg
elif opt == "-o":
flag_outfile = arg
elif opt == "-S":
flag_strip_offsets = True
elif opt == "-P":
flag_strip_pcinfo = True
elif opt == "-A":
flag_annotate_abstract = False
elif opt == "-N":
flag_normalize = False
elif opt == "-u":
flag_compunits[arg] = 1
parse_args()
u.setdeflanglocale()
perform()
|
thanm/devel-scripts
|
normalize-dwarf-objdump.py
|
Python
|
apache-2.0
| 10,730 | 0.014073 |
#
# 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.
#
import unittest
from unittest import mock
from zdesk import RateLimitError
from airflow.providers.zendesk.hooks.zendesk import ZendeskHook
class TestZendeskHook(unittest.TestCase):
@mock.patch("airflow.providers.zendesk.hooks.zendesk.time")
def test_sleeps_for_correct_interval(self, mocked_time):
sleep_time = 10
# To break out of the otherwise infinite tries
mocked_time.sleep = mock.Mock(side_effect=ValueError, return_value=3)
conn_mock = mock.Mock()
mock_response = mock.Mock()
mock_response.headers.get.return_value = sleep_time
conn_mock.call = mock.Mock(
side_effect=RateLimitError(msg="some message",
code="some code",
response=mock_response))
zendesk_hook = ZendeskHook("conn_id")
zendesk_hook.get_conn = mock.Mock(return_value=conn_mock)
with self.assertRaises(ValueError):
zendesk_hook.call("some_path", get_all_pages=False)
mocked_time.sleep.assert_called_once_with(sleep_time)
@mock.patch("airflow.providers.zendesk.hooks.zendesk.Zendesk")
def test_returns_single_page_if_get_all_pages_false(self, _):
zendesk_hook = ZendeskHook("conn_id")
mock_connection = mock.Mock()
mock_connection.host = "some_host"
zendesk_hook.get_connection = mock.Mock(return_value=mock_connection)
zendesk_hook.get_conn()
mock_conn = mock.Mock()
mock_call = mock.Mock(
return_value={'next_page': 'https://some_host/something',
'path': []})
mock_conn.call = mock_call
zendesk_hook.get_conn = mock.Mock(return_value=mock_conn)
zendesk_hook.call("path", get_all_pages=False)
mock_call.assert_called_once_with("path", None)
@mock.patch("airflow.providers.zendesk.hooks.zendesk.Zendesk")
def test_returns_multiple_pages_if_get_all_pages_true(self, _):
zendesk_hook = ZendeskHook("conn_id")
mock_connection = mock.Mock()
mock_connection.host = "some_host"
zendesk_hook.get_connection = mock.Mock(return_value=mock_connection)
zendesk_hook.get_conn()
mock_conn = mock.Mock()
mock_call = mock.Mock(
return_value={'next_page': 'https://some_host/something',
'path': []})
mock_conn.call = mock_call
zendesk_hook.get_conn = mock.Mock(return_value=mock_conn)
zendesk_hook.call("path", get_all_pages=True)
assert mock_call.call_count == 2
@mock.patch("airflow.providers.zendesk.hooks.zendesk.Zendesk")
def test_zdesk_is_inited_correctly(self, mock_zendesk):
conn_mock = mock.Mock()
conn_mock.host = "conn_host"
conn_mock.login = "conn_login"
conn_mock.password = "conn_pass"
zendesk_hook = ZendeskHook("conn_id")
zendesk_hook.get_connection = mock.Mock(return_value=conn_mock)
zendesk_hook.get_conn()
mock_zendesk.assert_called_once_with(zdesk_url='https://conn_host', zdesk_email='conn_login',
zdesk_password='conn_pass', zdesk_token=True)
@mock.patch("airflow.providers.zendesk.hooks.zendesk.Zendesk")
def test_zdesk_sideloading_works_correctly(self, mock_zendesk):
zendesk_hook = ZendeskHook("conn_id")
mock_connection = mock.Mock()
mock_connection.host = "some_host"
zendesk_hook.get_connection = mock.Mock(return_value=mock_connection)
zendesk_hook.get_conn()
mock_conn = mock.Mock()
mock_call = mock.Mock(
return_value={'next_page': 'https://some_host/something',
'tickets': [],
'users': [],
'groups': []})
mock_conn.call = mock_call
zendesk_hook.get_conn = mock.Mock(return_value=mock_conn)
results = zendesk_hook.call(".../tickets.json",
query={"include": "users,groups"},
get_all_pages=False,
side_loading=True)
assert results == {'groups': [], 'users': [], 'tickets': []}
|
spektom/incubator-airflow
|
tests/providers/zendesk/hooks/test_zendesk.py
|
Python
|
apache-2.0
| 5,046 | 0.000396 |
# -*- coding:utf-8 -*-
from sqlalchemy import desc, func
from atlas.modeles.entities.vmSearchTaxon import VmSearchTaxon
def listeTaxons(session):
"""
revoie un tableau de dict :
label = nom latin et nom francais concatene, value = cd_ref
TODO Fonction inutile à supprimer !!!
"""
req = session.query(VmSearchTaxon.search_name, VmSearchTaxon.cd_ref).all()
taxonList = list()
for r in req:
temp = {"label": r[0], "value": r[1]}
taxonList.append(temp)
return taxonList
def listeTaxonsSearch(session, search, limit=50):
"""
Recherche dans la VmSearchTaxon en ilike
Utilisé pour l'autocomplétion de la recherche de taxon
:query SQLA_Session session
:query str search : chaine de charactere pour la recherche
:query int limit: limite des résultats
**Returns:**
list: retourne un tableau {'label':'str': 'value': 'int'}
label = search_name
value = cd_ref
"""
req = session.query(
VmSearchTaxon.search_name,
VmSearchTaxon.cd_ref,
func.similarity(VmSearchTaxon.search_name, search).label("idx_trgm"),
).distinct()
search = search.replace(" ", "%")
req = (
req.filter(VmSearchTaxon.search_name.ilike("%" + search + "%"))
.order_by(desc("idx_trgm"))
.order_by(VmSearchTaxon.cd_ref == VmSearchTaxon.cd_nom)
.limit(limit)
)
data = req.all()
return [{"label": d[0], "value": d[1]} for d in data]
|
PnEcrins/GeoNature-atlas
|
atlas/modeles/repositories/vmSearchTaxonRepository.py
|
Python
|
gpl-3.0
| 1,550 | 0.000647 |
# urllib3/util.py
# Copyright 2008-2012 Andrey Petrov and contributors (see CONTRIBUTORS.txt)
#
# This module is part of urllib3 and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
from __future__ import absolute_import
from base64 import b64encode
from socket import error as SocketError
from hashlib import md5, sha1
from binascii import hexlify, unhexlify
import sys
from core.backports.collections import namedtuple
try:
from select import poll, POLLIN
except ImportError: # `poll` doesn't exist on OSX and other platforms
poll = False
try:
from select import select
except ImportError: # `select` doesn't exist on AppEngine.
select = False
try: # Test for SSL features
SSLContext = None
HAS_SNI = False
import ssl
from ssl import wrap_socket, CERT_NONE, PROTOCOL_SSLv23
from ssl import SSLContext # Modern SSL?
from ssl import HAS_SNI # Has SNI?
except ImportError:
pass
from .packages import six
from .exceptions import LocationParseError, SSLError
class Url(namedtuple('Url', ['scheme', 'auth', 'host', 'port', 'path', 'query', 'fragment'])):
"""
Datastructure for representing an HTTP URL. Used as a return value for
:func:`parse_url`.
"""
slots = ()
def __new__(cls, scheme=None, auth=None, host=None, port=None, path=None, query=None, fragment=None):
return super(Url, cls).__new__(cls, scheme, auth, host, port, path, query, fragment)
@property
def hostname(self):
"""For backwards-compatibility with urlparse. We're nice like that."""
return self.host
@property
def request_uri(self):
"""Absolute path including the query string."""
uri = self.path or '/'
if self.query is not None:
uri += '?' + self.query
return uri
def split_first(s, delims):
"""
Given a string and an iterable of delimiters, split on the first found
delimiter. Return two split parts and the matched delimiter.
If not found, then the first part is the full input string.
Example: ::
>>> split_first('foo/bar?baz', '?/=')
('foo', 'bar?baz', '/')
>>> split_first('foo/bar?baz', '123')
('foo/bar?baz', '', None)
Scales linearly with number of delims. Not ideal for large number of delims.
"""
min_idx = None
min_delim = None
for d in delims:
idx = s.find(d)
if idx < 0:
continue
if min_idx is None or idx < min_idx:
min_idx = idx
min_delim = d
if min_idx is None or min_idx < 0:
return s, '', None
return s[:min_idx], s[min_idx+1:], min_delim
def parse_url(url):
"""
Given a url, return a parsed :class:`.Url` namedtuple. Best-effort is
performed to parse incomplete urls. Fields not provided will be None.
Partly backwards-compatible with :mod:`urlparse`.
Example: ::
>>> parse_url('http://google.com/mail/')
Url(scheme='http', host='google.com', port=None, path='/', ...)
>>> parse_url('google.com:80')
Url(scheme=None, host='google.com', port=80, path=None, ...)
>>> parse_url('/foo?bar')
Url(scheme=None, host=None, port=None, path='/foo', query='bar', ...)
"""
# While this code has overlap with stdlib's urlparse, it is much
# simplified for our needs and less annoying.
# Additionally, this imeplementations does silly things to be optimal
# on CPython.
scheme = None
auth = None
host = None
port = None
path = None
fragment = None
query = None
# Scheme
if '://' in url:
scheme, url = url.split('://', 1)
# Find the earliest Authority Terminator
# (http://tools.ietf.org/html/rfc3986#section-3.2)
url, path_, delim = split_first(url, ['/', '?', '#'])
if delim:
# Reassemble the path
path = delim + path_
# Auth
if '@' in url:
auth, url = url.split('@', 1)
# IPv6
if url and url[0] == '[':
host, url = url[1:].split(']', 1)
# Port
if ':' in url:
_host, port = url.split(':', 1)
if not host:
host = _host
if not port.isdigit():
raise LocationParseError("Failed to parse: %s" % url)
port = int(port)
elif not host and url:
host = url
if not path:
return Url(scheme, auth, host, port, path, query, fragment)
# Fragment
if '#' in path:
path, fragment = path.split('#', 1)
# Query
if '?' in path:
path, query = path.split('?', 1)
return Url(scheme, auth, host, port, path, query, fragment)
def get_host(url):
"""
Deprecated. Use :func:`.parse_url` instead.
"""
p = parse_url(url)
return p.scheme or 'http', p.hostname, p.port
def make_headers(keep_alive=None, accept_encoding=None, user_agent=None,
basic_auth=None):
"""
Shortcuts for generating request headers.
:param keep_alive:
If ``True``, adds 'connection: keep-alive' header.
:param accept_encoding:
Can be a boolean, list, or string.
``True`` translates to 'gzip,deflate'.
List will get joined by comma.
String will be used as provided.
:param user_agent:
String representing the user-agent you want, such as
"python-urllib3/0.6"
:param basic_auth:
Colon-separated username:password string for 'authorization: basic ...'
auth header.
Example: ::
>>> make_headers(keep_alive=True, user_agent="Batman/1.0")
{'connection': 'keep-alive', 'user-agent': 'Batman/1.0'}
>>> make_headers(accept_encoding=True)
{'accept-encoding': 'gzip,deflate'}
"""
headers = {}
if accept_encoding:
if isinstance(accept_encoding, str):
pass
elif isinstance(accept_encoding, list):
accept_encoding = ','.join(accept_encoding)
else:
accept_encoding = 'gzip,deflate'
headers['accept-encoding'] = accept_encoding
if user_agent:
headers['user-agent'] = user_agent
if keep_alive:
headers['connection'] = 'keep-alive'
if basic_auth:
headers['authorization'] = 'Basic ' + \
b64encode(six.b(basic_auth)).decode('utf-8')
return headers
def is_connection_dropped(conn): # Platform-specific
"""
Returns True if the connection is dropped and should be closed.
:param conn:
:class:`httplib.HTTPConnection` object.
Note: For platforms like AppEngine, this will always return ``False`` to
let the platform handle connection recycling transparently for us.
"""
sock = getattr(conn, 'sock', False)
if not sock: # Platform-specific: AppEngine
return False
if not poll:
if not select: # Platform-specific: AppEngine
return False
try:
return select([sock], [], [], 0.0)[0]
except SocketError:
return True
# This version is better on platforms that support it.
p = poll()
p.register(sock, POLLIN)
for (fno, ev) in p.poll(0.0):
if fno == sock.fileno():
# Either data is buffered (bad), or the connection is dropped.
return True
def resolve_cert_reqs(candidate):
"""
Resolves the argument to a numeric constant, which can be passed to
the wrap_socket function/method from the ssl module.
Defaults to :data:`ssl.CERT_NONE`.
If given a string it is assumed to be the name of the constant in the
:mod:`ssl` module or its abbrevation.
(So you can specify `REQUIRED` instead of `CERT_REQUIRED`.
If it's neither `None` nor a string we assume it is already the numeric
constant which can directly be passed to wrap_socket.
"""
if candidate is None:
return CERT_NONE
if isinstance(candidate, str):
res = getattr(ssl, candidate, None)
if res is None:
res = getattr(ssl, 'CERT_' + candidate)
return res
return candidate
def resolve_ssl_version(candidate):
"""
like resolve_cert_reqs
"""
if candidate is None:
return PROTOCOL_SSLv23
if isinstance(candidate, str):
res = getattr(ssl, candidate, None)
if res is None:
res = getattr(ssl, 'PROTOCOL_' + candidate)
return res
return candidate
def assert_fingerprint(cert, fingerprint):
"""
Checks if given fingerprint matches the supplied certificate.
:param cert:
Certificate as bytes object.
:param fingerprint:
Fingerprint as string of hexdigits, can be interspersed by colons.
"""
# Maps the length of a digest to a possible hash function producing
# this digest.
hashfunc_map = {
16: md5,
20: sha1
}
fingerprint = fingerprint.replace(':', '').lower()
digest_length, rest = divmod(len(fingerprint), 2)
if rest or digest_length not in hashfunc_map:
raise SSLError('Fingerprint is of invalid length.')
# We need encode() here for py32; works on py2 and p33.
fingerprint_bytes = unhexlify(fingerprint.encode())
hashfunc = hashfunc_map[digest_length]
cert_digest = hashfunc(cert).digest()
if not cert_digest == fingerprint_bytes:
raise SSLError('Fingerprints did not match. Expected "{0}", got "{1}".'
.format(hexlify(fingerprint_bytes),
hexlify(cert_digest)))
if SSLContext is not None: # Python 3.2+
def ssl_wrap_socket(sock, keyfile=None, certfile=None, cert_reqs=None,
ca_certs=None, server_hostname=None,
ssl_version=None):
"""
All arguments except `server_hostname` have the same meaning as for
:func:`ssl.wrap_socket`
:param server_hostname:
Hostname of the expected certificate
"""
context = SSLContext(ssl_version)
context.verify_mode = cert_reqs
if ca_certs:
try:
context.load_verify_locations(ca_certs)
# Py32 raises IOError
# Py33 raises FileNotFoundError
except Exception: # Reraise as SSLError
e = sys.exc_info()[1]
raise SSLError(e)
if certfile:
# FIXME: This block needs a test.
context.load_cert_chain(certfile, keyfile)
if HAS_SNI: # Platform-specific: OpenSSL with enabled SNI
return context.wrap_socket(sock, server_hostname=server_hostname)
return context.wrap_socket(sock)
else: # Python 3.1 and earlier
def ssl_wrap_socket(sock, keyfile=None, certfile=None, cert_reqs=None,
ca_certs=None, server_hostname=None,
ssl_version=None):
return wrap_socket(sock, keyfile=keyfile, certfile=certfile,
ca_certs=ca_certs, cert_reqs=cert_reqs,
ssl_version=ssl_version)
|
ryfx/modrana
|
core/backports/urllib3_python25/util.py
|
Python
|
gpl-3.0
| 11,071 | 0.000542 |
from __future__ import absolute_import
from fulltext.backends import __html
from fulltext.util import run, assert_cmd_exists
from fulltext.util import BaseBackend
def cmd(path, **kwargs):
cmd = ['hwp5proc', 'xml']
cmd.extend([path])
return cmd
def to_text_with_backend(html):
return __html.handle_fobj(html)
class Backend(BaseBackend):
def check(self, title):
assert_cmd_exists('hwp5proc')
def handle_path(self, path):
out = self.decode(run(*cmd(path)))
return to_text_with_backend(out)
|
btimby/fulltext
|
fulltext/backends/__hwp.py
|
Python
|
mit
| 544 | 0 |
"""
xModule implementation of a learning sequence
"""
# pylint: disable=abstract-method
import json
import logging
from pkg_resources import resource_string
import warnings
from lxml import etree
from xblock.core import XBlock
from xblock.fields import Integer, Scope, Boolean, Dict
from xblock.fragment import Fragment
from .exceptions import NotFoundError
from .fields import Date
from .mako_module import MakoModuleDescriptor
from .progress import Progress
from .x_module import XModule, STUDENT_VIEW
from .xml_module import XmlDescriptor
log = logging.getLogger(__name__)
# HACK: This shouldn't be hard-coded to two types
# OBSOLETE: This obsoletes 'type'
class_priority = ['problem', 'video']
# Make '_' a no-op so we can scrape strings. Using lambda instead of
# `django.utils.translation.ugettext_noop` because Django cannot be imported in this file
_ = lambda text: text
class SequenceFields(object):
has_children = True
# NOTE: Position is 1-indexed. This is silly, but there are now student
# positions saved on prod, so it's not easy to fix.
position = Integer(help="Last tab viewed in this sequence", scope=Scope.user_state)
due = Date(
display_name=_("Due Date"),
help=_("Enter the date by which problems are due."),
scope=Scope.settings,
)
# Entrance Exam flag -- see cms/contentstore/views/entrance_exam.py for usage
is_entrance_exam = Boolean(
display_name=_("Is Entrance Exam"),
help=_(
"Tag this course module as an Entrance Exam. "
"Note, you must enable Entrance Exams for this course setting to take effect."
),
default=False,
scope=Scope.settings,
)
individual_start_days = Integer(
help=_("Number of days from the base date to the chapter starts"),
scope=Scope.settings
)
individual_start_hours = Integer(
help=_("Number of hours from the base date to the chapter starts"),
scope=Scope.settings
)
individual_start_minutes = Integer(
help=_("Number of minutes from the base date to the chapter starts"),
scope=Scope.settings
)
individual_due_days = Integer(
help=_("Number of days from the base date to the due"),
scope=Scope.settings
)
individual_due_hours = Integer(
help=_("Number of hours from the base date to the due"),
scope=Scope.settings
)
individual_due_minutes = Integer(
help=_("Number of minutes from the base date to the due"),
scope=Scope.settings
)
progress_restriction = Dict(
help=_("Settings for progress restriction"),
default={
"type": "No Restriction",
},
scope=Scope.settings
)
class ProctoringFields(object):
"""
Fields that are specific to Proctored or Timed Exams
"""
is_time_limited = Boolean(
display_name=_("Is Time Limited"),
help=_(
"This setting indicates whether students have a limited time"
" to view or interact with this courseware component."
),
default=False,
scope=Scope.settings,
)
default_time_limit_minutes = Integer(
display_name=_("Time Limit in Minutes"),
help=_(
"The number of minutes available to students for viewing or interacting with this courseware component."
),
default=None,
scope=Scope.settings,
)
is_proctored_enabled = Boolean(
display_name=_("Is Proctoring Enabled"),
help=_(
"This setting indicates whether this exam is a proctored exam."
),
default=False,
scope=Scope.settings,
)
is_practice_exam = Boolean(
display_name=_("Is Practice Exam"),
help=_(
"This setting indicates whether this exam is for testing purposes only. Practice exams are not verified."
),
default=False,
scope=Scope.settings,
)
@property
def is_proctored_exam(self):
""" Alias the is_proctored_enabled field to the more legible is_proctored_exam """
return self.is_proctored_enabled
@is_proctored_exam.setter
def is_proctored_exam(self, value):
""" Alias the is_proctored_enabled field to the more legible is_proctored_exam """
self.is_proctored_enabled = value
@XBlock.wants('proctoring')
@XBlock.wants('credit')
class SequenceModule(SequenceFields, ProctoringFields, XModule):
''' Layout module which lays out content in a temporal sequence
'''
js = {
'coffee': [resource_string(__name__, 'js/src/sequence/display.coffee')],
'js': [resource_string(__name__, 'js/src/sequence/display/jquery.sequence.js')],
}
css = {
'scss': [resource_string(__name__, 'css/sequence/display.scss')],
}
js_module_name = "Sequence"
def __init__(self, *args, **kwargs):
super(SequenceModule, self).__init__(*args, **kwargs)
# If position is specified in system, then use that instead.
position = getattr(self.system, 'position', None)
if position is not None:
try:
self.position = int(self.system.position)
except (ValueError, TypeError):
# Check for https://openedx.atlassian.net/browse/LMS-6496
warnings.warn(
"Sequential position cannot be converted to an integer: {pos!r}".format(
pos=self.system.position,
),
RuntimeWarning,
)
def get_progress(self):
''' Return the total progress, adding total done and total available.
(assumes that each submodule uses the same "units" for progress.)
'''
# TODO: Cache progress or children array?
children = self.get_children()
progresses = [child.get_progress() for child in children]
progress = reduce(Progress.add_counts, progresses, None)
return progress
def handle_ajax(self, dispatch, data): # TODO: bounds checking
''' get = request.POST instance '''
if dispatch == 'goto_position':
# set position to default value if either 'position' argument not
# found in request or it is a non-positive integer
position = data.get('position', u'1')
if position.isdigit() and int(position) > 0:
self.position = int(position)
else:
self.position = 1
return json.dumps({'success': True})
raise NotFoundError('Unexpected dispatch type')
def student_view(self, context):
# If we're rendering this sequence, but no position is set yet,
# default the position to the first element
if self.position is None:
self.position = 1
## Returns a set of all types of all sub-children
contents = []
fragment = Fragment()
# Is this sequential part of a timed or proctored exam?
if self.is_time_limited:
view_html = self._time_limited_student_view(context)
# Do we have an alternate rendering
# from the edx_proctoring subsystem?
if view_html:
fragment.add_content(view_html)
return fragment
for child in self.get_display_items():
progress = child.get_progress()
rendered_child = child.render(STUDENT_VIEW, context)
fragment.add_frag_resources(rendered_child)
# `titles` is a list of titles to inject into the sequential tooltip display.
# We omit any blank titles to avoid blank lines in the tooltip display.
titles = [title.strip() for title in child.get_content_titles() if title.strip()]
childinfo = {
'content': rendered_child.content,
'title': "\n".join(titles),
'page_title': titles[0] if titles else '',
'progress_status': Progress.to_js_status_str(progress),
'progress_detail': Progress.to_js_detail_str(progress),
'type': child.get_icon_class(),
'id': child.scope_ids.usage_id.to_deprecated_string(),
}
if childinfo['title'] == '':
childinfo['title'] = child.display_name_with_default
contents.append(childinfo)
params = {
'items': contents,
'element_id': self.location.html_id(),
'item_id': self.location.to_deprecated_string(),
'position': self.position,
'tag': self.location.category,
'ajax_url': self.system.ajax_url,
}
fragment.add_content(self.system.render_template("seq_module.html", params))
return fragment
def _time_limited_student_view(self, context):
"""
Delegated rendering of a student view when in a time
limited view. This ultimately calls down into edx_proctoring
pip installed djangoapp
"""
# None = no overridden view rendering
view_html = None
proctoring_service = self.runtime.service(self, 'proctoring')
credit_service = self.runtime.service(self, 'credit')
# Is this sequence designated as a Timed Examination, which includes
# Proctored Exams
feature_enabled = (
proctoring_service and
credit_service and
self.is_time_limited
)
if feature_enabled:
user_id = self.runtime.user_id
user_role_in_course = 'staff' if self.runtime.user_is_staff else 'student'
course_id = self.runtime.course_id
content_id = self.location
context = {
'display_name': self.display_name,
'default_time_limit_mins': (
self.default_time_limit_minutes if
self.default_time_limit_minutes else 0
),
'is_practice_exam': self.is_practice_exam,
'due_date': self.due
}
# inject the user's credit requirements and fulfillments
if credit_service:
credit_state = credit_service.get_credit_state(user_id, course_id)
if credit_state:
context.update({
'credit_state': credit_state
})
# See if the edx-proctoring subsystem wants to present
# a special view to the student rather
# than the actual sequence content
#
# This will return None if there is no
# overridden view to display given the
# current state of the user
view_html = proctoring_service.get_student_view(
user_id=user_id,
course_id=course_id,
content_id=content_id,
context=context,
user_role=user_role_in_course
)
return view_html
def get_icon_class(self):
child_classes = set(child.get_icon_class()
for child in self.get_children())
new_class = 'other'
for c in class_priority:
if c in child_classes:
new_class = c
return new_class
class SequenceDescriptor(SequenceFields, ProctoringFields, MakoModuleDescriptor, XmlDescriptor):
"""
A Sequences Descriptor object
"""
mako_template = 'widgets/sequence-edit.html'
module_class = SequenceModule
show_in_read_only_mode = True
js = {
'coffee': [resource_string(__name__, 'js/src/sequence/edit.coffee')],
}
js_module_name = "SequenceDescriptor"
@classmethod
def definition_from_xml(cls, xml_object, system):
children = []
for child in xml_object:
try:
child_block = system.process_xml(etree.tostring(child, encoding='unicode'))
children.append(child_block.scope_ids.usage_id)
except Exception as e:
log.exception("Unable to load child when parsing Sequence. Continuing...")
if system.error_tracker is not None:
system.error_tracker(u"ERROR: {0}".format(e))
continue
return {}, children
def definition_to_xml(self, resource_fs):
xml_object = etree.Element('sequential')
for child in self.get_children():
self.runtime.add_block_as_child_node(child, xml_object)
return xml_object
@property
def non_editable_metadata_fields(self):
"""
`is_entrance_exam` should not be editable in the Studio settings editor.
"""
non_editable_fields = super(SequenceDescriptor, self).non_editable_metadata_fields
non_editable_fields.append(self.fields['is_entrance_exam'])
return non_editable_fields
def index_dictionary(self):
"""
Return dictionary prepared with module content and type for indexing.
"""
# return key/value fields in a Python dict object
# values may be numeric / string or dict
# default implementation is an empty dict
xblock_body = super(SequenceDescriptor, self).index_dictionary()
html_body = {
"display_name": self.display_name,
}
if "content" in xblock_body:
xblock_body["content"].update(html_body)
else:
xblock_body["content"] = html_body
xblock_body["content_type"] = "Sequence"
return xblock_body
|
nttks/edx-platform
|
common/lib/xmodule/xmodule/seq_module.py
|
Python
|
agpl-3.0
| 13,629 | 0.001761 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import re
import shutil
import sys
from setuptools import setup
def get_version(package):
"""
Return package version as listed in `__version__` in `init.py`.
"""
with open(os.path.join(package, '__init__.py'), 'rb') as init_py:
src = init_py.read().decode('utf-8')
return re.search("__version__ = ['\"]([^'\"]+)['\"]", src).group(1)
name = 'djangorestframework-jwt'
version = get_version('rest_framework_jwt')
package = 'rest_framework_jwt'
description = 'JSON Web Token based authentication for Django REST framework'
url = 'https://github.com/GetBlimp/django-rest-framework-jwt'
author = 'Jose Padilla'
author_email = 'jpadilla@getblimp.com'
license = 'MIT'
install_requires = [
'PyJWT>=1.4.0,<2.0.0',
]
def read(*paths):
"""
Build a file path from paths and return the contents.
"""
with open(os.path.join(*paths), 'r') as f:
return f.read()
def get_packages(package):
"""
Return root package and all sub-packages.
"""
return [dirpath
for dirpath, dirnames, filenames in os.walk(package)
if os.path.exists(os.path.join(dirpath, '__init__.py'))]
def get_package_data(package):
"""
Return all files under the root package, that are not in a
package themselves.
"""
walk = [(dirpath.replace(package + os.sep, '', 1), filenames)
for dirpath, dirnames, filenames in os.walk(package)
if not os.path.exists(os.path.join(dirpath, '__init__.py'))]
filepaths = []
for base, filenames in walk:
filepaths.extend([os.path.join(base, filename)
for filename in filenames])
return {package: filepaths}
if sys.argv[-1] == 'publish':
if os.system('pip freeze | grep wheel'):
print('wheel not installed.\nUse `pip install wheel`.\nExiting.')
sys.exit()
if os.system('pip freeze | grep twine'):
print('twine not installed.\nUse `pip install twine`.\nExiting.')
sys.exit()
os.system('python setup.py sdist bdist_wheel')
os.system('twine upload dist/*')
shutil.rmtree('dist')
shutil.rmtree('build')
shutil.rmtree('djangorestframework_jwt.egg-info')
print('You probably want to also tag the version now:')
print(" git tag -a {0} -m 'version {0}'".format(version))
print(' git push --tags')
sys.exit()
setup(
name=name,
version=version,
url=url,
license=license,
description=description,
long_description=read('README.rst'),
author=author,
author_email=author_email,
packages=get_packages(package),
package_data=get_package_data(package),
install_requires=install_requires,
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Topic :: Internet :: WWW/HTTP',
]
)
|
orf/django-rest-framework-jwt
|
setup.py
|
Python
|
mit
| 3,404 | 0 |
"""Support for switches which integrates with other components."""
import logging
import voluptuous as vol
from homeassistant.components.switch import (
ENTITY_ID_FORMAT,
PLATFORM_SCHEMA,
SwitchEntity,
)
from homeassistant.const import (
ATTR_ENTITY_ID,
ATTR_FRIENDLY_NAME,
CONF_ENTITY_PICTURE_TEMPLATE,
CONF_ICON_TEMPLATE,
CONF_SWITCHES,
CONF_UNIQUE_ID,
CONF_VALUE_TEMPLATE,
STATE_OFF,
STATE_ON,
)
from homeassistant.core import callback
from homeassistant.exceptions import TemplateError
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.entity import async_generate_entity_id
from homeassistant.helpers.reload import async_setup_reload_service
from homeassistant.helpers.restore_state import RestoreEntity
from homeassistant.helpers.script import Script
from .const import CONF_AVAILABILITY_TEMPLATE, DOMAIN, PLATFORMS
from .template_entity import TemplateEntity
_LOGGER = logging.getLogger(__name__)
_VALID_STATES = [STATE_ON, STATE_OFF, "true", "false"]
ON_ACTION = "turn_on"
OFF_ACTION = "turn_off"
SWITCH_SCHEMA = vol.Schema(
{
vol.Optional(CONF_VALUE_TEMPLATE): cv.template,
vol.Optional(CONF_ICON_TEMPLATE): cv.template,
vol.Optional(CONF_ENTITY_PICTURE_TEMPLATE): cv.template,
vol.Optional(CONF_AVAILABILITY_TEMPLATE): cv.template,
vol.Required(ON_ACTION): cv.SCRIPT_SCHEMA,
vol.Required(OFF_ACTION): cv.SCRIPT_SCHEMA,
vol.Optional(ATTR_FRIENDLY_NAME): cv.string,
vol.Optional(ATTR_ENTITY_ID): cv.entity_ids,
vol.Optional(CONF_UNIQUE_ID): cv.string,
}
)
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{vol.Required(CONF_SWITCHES): cv.schema_with_slug_keys(SWITCH_SCHEMA)}
)
async def _async_create_entities(hass, config):
"""Create the Template switches."""
switches = []
for device, device_config in config[CONF_SWITCHES].items():
friendly_name = device_config.get(ATTR_FRIENDLY_NAME, device)
state_template = device_config.get(CONF_VALUE_TEMPLATE)
icon_template = device_config.get(CONF_ICON_TEMPLATE)
entity_picture_template = device_config.get(CONF_ENTITY_PICTURE_TEMPLATE)
availability_template = device_config.get(CONF_AVAILABILITY_TEMPLATE)
on_action = device_config[ON_ACTION]
off_action = device_config[OFF_ACTION]
unique_id = device_config.get(CONF_UNIQUE_ID)
switches.append(
SwitchTemplate(
hass,
device,
friendly_name,
state_template,
icon_template,
entity_picture_template,
availability_template,
on_action,
off_action,
unique_id,
)
)
return switches
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
"""Set up the template switches."""
await async_setup_reload_service(hass, DOMAIN, PLATFORMS)
async_add_entities(await _async_create_entities(hass, config))
class SwitchTemplate(TemplateEntity, SwitchEntity, RestoreEntity):
"""Representation of a Template switch."""
def __init__(
self,
hass,
device_id,
friendly_name,
state_template,
icon_template,
entity_picture_template,
availability_template,
on_action,
off_action,
unique_id,
):
"""Initialize the Template switch."""
super().__init__(
availability_template=availability_template,
icon_template=icon_template,
entity_picture_template=entity_picture_template,
)
self.entity_id = async_generate_entity_id(
ENTITY_ID_FORMAT, device_id, hass=hass
)
self._name = friendly_name
self._template = state_template
domain = __name__.split(".")[-2]
self._on_script = Script(hass, on_action, friendly_name, domain)
self._off_script = Script(hass, off_action, friendly_name, domain)
self._state = False
self._unique_id = unique_id
@callback
def _update_state(self, result):
super()._update_state(result)
if isinstance(result, TemplateError):
self._state = None
return
self._state = result.lower() in ("true", STATE_ON)
async def async_added_to_hass(self):
"""Register callbacks."""
if self._template is None:
# restore state after startup
await super().async_added_to_hass()
state = await self.async_get_last_state()
if state:
self._state = state.state == STATE_ON
# no need to listen for events
else:
self.add_template_attribute(
"_state", self._template, None, self._update_state
)
await super().async_added_to_hass()
@property
def name(self):
"""Return the name of the switch."""
return self._name
@property
def unique_id(self):
"""Return the unique id of this switch."""
return self._unique_id
@property
def is_on(self):
"""Return true if device is on."""
return self._state
@property
def should_poll(self):
"""Return the polling state."""
return False
async def async_turn_on(self, **kwargs):
"""Fire the on action."""
await self._on_script.async_run(context=self._context)
if self._template is None:
self._state = True
self.async_write_ha_state()
async def async_turn_off(self, **kwargs):
"""Fire the off action."""
await self._off_script.async_run(context=self._context)
if self._template is None:
self._state = False
self.async_write_ha_state()
@property
def assumed_state(self):
"""State is assumed, if no template given."""
return self._template is None
|
titilambert/home-assistant
|
homeassistant/components/template/switch.py
|
Python
|
apache-2.0
| 6,023 | 0.000332 |
#!/usr/bin/env python3
from setuptools import setup, find_packages
version = '0.2.4'
setup(
name='lolbuddy',
version=version,
description='a cli tool to update league of legends itemsets and ability order from champion.gg',
author='Cyrus Roshan',
author_email='hello@cyrusroshan.com',
license='MIT',
keywords=['lol', 'league', 'league of legends', 'item', 'ability'],
url='https://github.com/CyrusRoshan/lolbuddy',
packages=find_packages(),
package_data={},
install_requires=[
'requests-futures >= 0.9.5',
],
entry_points={
'console_scripts': [
'lolbuddy=lolbuddy:main',
],
},
)
|
CyrusRoshan/lolbuddy
|
setup.py
|
Python
|
mit
| 674 | 0.001484 |
#!/usr/bin/env python
# remoteobj v0.4, best yet!
# TODO: This will get wrecked by recursive sets/lists/dicts; need a more picklish method.
# TODO: Dict/sets/lists should get unpacked to wrappers that are local for read-only access,
# but update the remote for write access. Note that __eq__ will be an interesting override.
import marshal
import struct
import socket
import sys, exceptions, errno, traceback
from types import CodeType, FunctionType
from os import urandom
from hashlib import sha1
DEBUG = False
class Proxy(object):
def __init__(self, conn, info, _hash=None, parent=None):
object.__setattr__(self, '_proxyconn', conn)
object.__setattr__(self, '_proxyinfo', info)
object.__setattr__(self, '_proxyparent', parent)
def __getattribute__(self, attr):
t = object.__getattribute__(self, '_proxyinfo').getattr(attr)
if t:
# We need to retain parent for garbage collection purposes.
return Proxy(object.__getattribute__(self, '_proxyconn'), t, parent=self)
else:
return object.__getattribute__(self, '_proxyconn').get(self, attr)
def __getattr__(self, attr):
return object.__getattribute__(self, '__getattribute__')(attr)
def __setattr__(self, attr, val):
object.__getattribute__(self, '_proxyconn').set(self, attr, val)
def __delattr__(self, attr):
object.__getattribute__(self, '_proxyconn').callattr(self, '__delattr__', (attr,), {})
def __call__(self, *args, **kwargs):
return object.__getattribute__(self, '_proxyconn').call(self, args, kwargs)
# GC isn't useful anyway...
"""
def __del__(self):
if object.__getattribute__(self, '_proxyparent') is not None: return
if not marshal or not struct or not socket: return # Reduce spurious messages when quitting python
object.__getattribute__(self, '_proxyconn').delete(self)
"""
# hash and repr need to be handled specially, due to hash(type) != type.__hash__()
# (and the same for repr). Incidentally, we'll cache the hash.
def __hash__(self):
info = object.__getattribute__(self, '_proxyinfo')
if info.proxyhash is None:
info.proxyhash = object.__getattribute__(self, '_proxyconn').hash(self)
return info.proxyhash
def __repr__(self):
return object.__getattribute__(self, '_proxyconn').repr(self)
# Special methods don't always go through __getattribute__, so redirect them all there.
for special in ('__str__', '__lt__', '__le__', '__eq__', '__ne__', '__gt__', '__ge__', '__cmp__', '__rcmp__', '__nonzero__', '__unicode__', '__len__', '__getitem__', '__setitem__', '__delitem__', '__iter__', '__reversed__', '__contains__', '__getslice__', '__setslice__', '__delslice__', '__add__', '__sub__', '__mul__', '__floordiv__', '__mod__', '__divmod__', '__pow__', '__lshift__', '__rshift__', '__and__', '__xor__', '__or__', '__div__', '__truediv__', '__radd__', '__rsub__', '__rmul__', '__rdiv__', '__rtruediv__', '__rfloordiv__', '__rmod__', '__rdivmod__', '__rpow__', '__rlshift__', '__rrshift__', '__rand__', '__rxor__', '__ror__', '__iadd__', '__isub__', '__imul__', '__idiv__', '__itruediv__', '__ifloordiv__', '__imod__', '__ipow__', '__ilshift__', '__irshift__', '__iand__', '__ixor__', '__ior__', '__neg__', '__pos__', '__abs__', '__invert__', '__complex__', '__int__', '__long__', '__float__', '__oct__', '__hex__', '__index__', '__coerce__', '__enter__', '__exit__'):
exec "def {special}(self, *args, **kwargs):\n\treturn object.__getattribute__(self, '_proxyconn').callattr(self, '{special}', args, kwargs)".format(special=special) in None, None
class ProxyInfo(object):
@classmethod
def isPacked(self, obj):
return type(obj) == tuple and len(obj) == 7 and obj[:2] == (StopIteration, Ellipsis)
@classmethod
def fromPacked(self, obj):
return self(obj[2], obj[3], obj[4] or '', obj[5], obj[6] or ())
def __init__(self, endpoint, remoteid, attrpath = '', proxyhash = None, lazyattrs = (), dbgnote = ''):
self.endpoint = endpoint
self.remoteid = remoteid
self.attrpath = attrpath
self.proxyhash = proxyhash
self.lazyattrs = set(lazyattrs)
self.dbgnote = dbgnote
def __repr__(self):
return 'ProxyInfo'+repr((self.endpoint, hex(self.remoteid))) + ('' if not self.dbgnote else ' <'+self.dbgnote+'>')
def packed(self):
return (StopIteration, Ellipsis, self.endpoint, self.remoteid, self.attrpath or None, self.proxyhash, None) # Don't pack lazyattrs
def getattr(self, attr):
if attr not in self.lazyattrs: return None
path = self.attrpath+'.'+attr if self.attrpath else attr
return type(self)(self.endpoint, self.remoteid, attrpath = path, lazyattrs = self.lazyattrs)
class Connection(object):
def __init__(self, sock, secret, endpoint = urandom(8).encode('hex')):
self.sock = sock
self.secret = secret
self.endpoint = endpoint
self.garbage = []
def __del__(self):
try: self.sock.close()
except: pass
def sendmsg(self, msg):
x = marshal.dumps(msg)
self.sock.sendall(struct.pack('<I', len(x)))
self.sock.sendall(x)
def recvmsg(self):
x = self.sock.recv(4)
if len(x) == 4:
y = struct.unpack('<I', x)[0]
z = self.sock.recv(y)
if len(z) == y:
return marshal.loads(z)
raise socket.error(errno.ECONNRESET, 'The socket was closed while receiving a message.')
# Note: must send after non-info_only packing, or objects will be left with +1 retain count in self.vended
def pack(self, val, info_only = False, isDictKey = False):
if type(val) in (bool, int, long, float, complex, str, unicode) or val is None or val is StopIteration or val is Ellipsis:
return val
elif type(val) == tuple:
return tuple(self.pack(i, info_only) for i in val)
elif type(val) == list:
return [self.pack(i, info_only) for i in val]
elif type(val) == set:
return {self.pack(i, info_only) for i in val}
elif type(val) == frozenset:
return frozenset(self.pack(i, info_only) for i in val)
elif type(val) == dict:
return {self.pack(k, info_only, isDictKey = True):self.pack(v, info_only) for k,v in val.iteritems()}
elif type(val) == Proxy:
return object.__getattribute__(val, '_proxyinfo').packed()
elif type(val) == CodeType:
return val
else:
if not info_only:
self.vended.setdefault(id(val), [val, 0])[1] += 1
t = hash(val) if isDictKey else None
return ProxyInfo(self.endpoint, id(val), proxyhash=t).packed()
def unpack(self, val, info_only = False):
if ProxyInfo.isPacked(val):
info = ProxyInfo.fromPacked(val)
try:
if self.endpoint == info.endpoint:
try:
obj = self.vended[info.remoteid][0]
except KeyError:
if not info_only:
raise Exception("Whoops, "+self.endpoint+" can't find reference to object "+repr(info.remoteid))
else:
info.dbgnote = 'missing local reference'
return info
if info.attrpath:
for i in info.attrpath.split('.'):
obj = getattr(obj, i)
return obj
else:
return Proxy(self, info) if not info_only else info
except:
if not info_only: raise
info.dbgnote = 'While unpacking, ' + ''.join(traceback.format_exc())
return info
elif type(val) == tuple:
return tuple(self.unpack(i, info_only) for i in val)
elif type(val) == list:
return [self.unpack(i, info_only) for i in val]
elif type(val) == set:
return {self.unpack(i, info_only) for i in val}
elif type(val) == frozenset:
return frozenset(self.unpack(i, info_only) for i in val)
elif type(val) == dict:
return {self.unpack(k, info_only):self.unpack(v, info_only) for k,v in val.iteritems()}
elif type(val) == CodeType:
return val
else:
return val
def connectProxy(self):
self.vended = {}
self.sock.sendall('yo')
chal = urandom(20)
self.sock.sendall(chal)
if self.sock.recv(20) != sha1(self.secret+chal).digest():
print >> sys.stderr, "Server failed challenge!"
return None
self.sock.sendall(sha1(self.secret+self.sock.recv(20)).digest())
return self.unpack(self.recvmsg())
def runServer(self, obj):
if self.sock.recv(2) != 'yo':
print >> sys.stderr, "Spurious connection!"
return
self.sock.sendall(sha1(self.secret+self.sock.recv(20)).digest())
chal = urandom(20)
self.sock.sendall(chal)
if self.sock.recv(20) != sha1(self.secret+chal).digest():
print >> sys.stderr, "Client failed challenge!"
return None
try:
self.vended = {}
self.sendmsg(self.pack(obj))
while self.vended:
self.handle(self.recvmsg())
except socket.error as e:
if e.errno in (errno.EPIPE, errno.ECONNRESET): pass # Client disconnect is a non-error.
else: raise
finally:
del self.vended
def request(self, msg):
self.sendmsg(msg)
while True:
x = self.recvmsg()
if DEBUG: print >> sys.stderr, self.endpoint, self.unpack(x, True)
if x[0] == 'ok':
return self.unpack(x[1])
elif x[0] == 'exn':
exntyp = exceptions.__dict__.get(x[1])
args = self.unpack(x[2])
trace = x[3]
if exntyp and issubclass(exntyp, BaseException):
if DEBUG: print >> sys.stderr, 'Remote '+''.join(trace)
raise exntyp(*args)
else:
raise Exception(str(x[1])+repr(args)+'\nRemote '+''.join(trace))
else:
self.handle(x)
def handle(self, msg):
if DEBUG: print >> sys.stderr, self.endpoint, self.unpack(msg, True)
try:
ret = {
'get' : self.handle_get,
'set' : self.handle_set,
'call' : self.handle_call,
'callattr' : self.handle_callattr,
'hash' : self.handle_hash,
'repr' : self.handle_repr,
'gc' : self.handle_gc,
'eval' : self.handle_eval,
'exec' : self.handle_exec,
'deffun' : self.handle_deffun,
}[msg[0]](*msg[1:])
self.sendmsg(('ok', ret))
except:
typ, val, tb = sys.exc_info()
self.sendmsg(('exn', typ.__name__, self.pack(val.args), traceback.format_exception(typ, val, tb)))
def get(self, proxy, attr):
info = object.__getattribute__(proxy, '_proxyinfo')
x, addlazy = self.request(('get', info.packed(), attr))
if addlazy:
info.lazyattrs.add(attr)
return x
def handle_get(self, obj, attr):
obj1 = self.unpack(obj)
attr1 = getattr(obj1, attr)
# Start of the "addlazy" perf hack, which may lead to incorrect behavior in some cases.
addlazy = True
addlazy = addlazy and type(attr1) not in (bool, int, long, float, complex, str, unicode, tuple, list, set, frozenset, dict)
addlazy = addlazy and attr1 is not None
try: addlazy = addlazy and not isinstance(getattr(obj1.__class__, attr), property)
except: pass
return self.pack(attr1), addlazy
def set(self, proxy, attr, val):
self.request(('set', object.__getattribute__(proxy, '_proxyinfo').packed(), attr, self.pack(val)))
def handle_set(self, obj, attr, val):
setattr(self.unpack(obj), attr, self.unpack(val))
def call(self, proxy, args, kwargs):
return self.request(('call', object.__getattribute__(proxy, '_proxyinfo').packed(), self.pack(args or None), self.pack(kwargs or None)))
def handle_call(self, obj, args, kwargs):
return self.pack(self.unpack(obj)(*(self.unpack(args) or ()), **(self.unpack(kwargs) or {})))
def callattr(self, proxy, attr, args, kwargs):
return self.request(('callattr', object.__getattribute__(proxy, '_proxyinfo').packed(), attr, self.pack(args or None), self.pack(kwargs or None)))
def handle_callattr(self, obj, attr, args, kwargs):
return self.pack(getattr(self.unpack(obj), attr)(*(self.unpack(args) or ()), **(self.unpack(kwargs) or {})))
def hash(self, proxy):
return self.request(('hash', object.__getattribute__(proxy, '_proxyinfo').packed()))
def handle_hash(self, obj):
return self.pack(hash(self.unpack(obj)))
def repr(self, proxy):
return self.request(('repr', object.__getattribute__(proxy, '_proxyinfo').packed()))
def handle_repr(self, obj):
return self.pack(repr(self.unpack(obj)))
def delete(self, proxy):
info = object.__getattribute__(proxy, '_proxyinfo')
if info.attrpath != '': return
self.garbage.append(info.packed())
if len(self.garbage) > 50:
try: self.request(('gc', tuple(self.garbage)))
except socket.error: pass # No need for complaints about a dead connection
self.garbage[:] = []
def handle_gc(self, objs):
for obj in objs:
try:
info = ProxyInfo.fromPacked(obj)
if info.endpoint != self.endpoint: continue
assert info.attrpath == ''
self.vended[info.remoteid][1] -= 1
if self.vended[info.remoteid][1] == 0:
del self.vended[info.remoteid]
elif self.vended[info.remoteid][1] < 0:
print >> sys.stderr, "Too many releases on", self.unpack(obj, True), self.vended[info.remoteid][1]
except:
print >> sys.stderr, "Exception while releasing", self.unpack(obj, True)
traceback.print_exc(sys.stderr)
def disconnect(self):
self.garbage = []
self.sock.close()
def _eval(self, expr, local = None):
ret, d = self.request(('eval', self.pack(expr), self.pack(local)))
if local is not None:
local.clear()
local.update(d)
return ret
def handle_eval(self, expr, local):
d = self.unpack(local)
ret = eval(self.unpack(expr), globals(), d)
return self.pack(ret), (self.pack(d) if d is not None else None)
def _exec(self, stmt, local = None):
d = self.request(('exec', self.pack(stmt), self.pack(local)))
if local is not None:
local.clear()
local.update(d)
def handle_exec(self, stmt, local):
d = self.unpack(local)
exec(self.unpack(stmt), globals(), d)
return self.pack(d) if d is not None else None
# Define a function on the remote side. Its __globals__ will be
# the local client-side func.__globals__ filtered to the keys in
# func_globals, underlaid with the remote server-side globals()
# filtered to the keys in remote_globals. None is a special value
# for the filters, and disables any filtering.
def deffun(self, func, func_globals = (), remote_globals = None):
glbls = {k:v for k,v in func.__globals__.iteritems() if k in func_globals} if func_globals is not None else func.__globals__
return self.request(('deffun', self.pack((func.__code__, glbls, func.__name__, func.__defaults__, func.__closure__)), self.pack(func.__dict__), self.pack(func.__doc__), remote_globals))
def handle_deffun(self, func, fdict, fdoc, remote_globals):
func = self.unpack(func)
g = globals()
glbls = {k:g[k] for k in remote_globals if k in g} if remote_globals is not None else g.copy()
glbls.update(func[1])
func[1].update(glbls)
f = FunctionType(*func)
f.__dict__ = self.unpack(fdict)
f.__doc__ = self.unpack(fdoc)
return self.pack(f)
__all__ = [Connection,]
# For demo purposes.
if __name__ == "__main__":
from sys import argv
if len(argv) <= 3:
print >> sys.stderr, "Usage:", argv[0], "server <address> <port> [<password>]"
print >> sys.stderr, " python -i", argv[0], "client <address> <port> [<password>]"
print >> sys.stderr, "In the client python shell, the server's module is available as 'proxy'"
print >> sys.stderr, "A good demo is `proxy.__builtins__.__import__('ctypes').memset(0,0,1)`"
exit(64)
hostport = (argv[2], int(argv[3]))
password = argv[4] if len(argv) > 4 else 'lol, python'
if argv[1] == 'server':
import SocketServer
class Server(SocketServer.BaseRequestHandler):
def handle(self):
print >> sys.stderr, 'Accepting client', self.client_address
Connection(self.request, password).runServer(sys.modules[__name__])
print >> sys.stderr, 'Finished with client', self.client_address
SocketServer.TCPServer.allow_reuse_address = True
SocketServer.TCPServer(hostport, Server).serve_forever()
exit(1)
elif argv[1] == 'client':
connection = Connection(socket.create_connection(hostport), password)
proxy = connection.connectProxy()
print >> sys.stderr, "`proxy` and `connection` are available for you to play with at the interactive prompt."
else:
exit(64)
|
KernelAnalysisPlatform/KlareDbg
|
static2/ida/remoteobj.py
|
Python
|
gpl-3.0
| 16,409 | 0.016942 |
# Copyright (c) 2015 Intel Research and Development Ireland Ltd.
#
# 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 experimental_framework.benchmarking_unit as b_unit
from experimental_framework import heat_template_generation, common
class FrameworkApi(object):
@staticmethod
def init():
"""
Initializes the Framework
:return: None
"""
common.init(api=True)
# @staticmethod
# def get_available_test_cases():
# """
# Returns a list of available test cases.
# This list include eventual modules developed by the user, if any.
# Each test case is returned as a string that represents the full name
# of the test case and that can be used to get more information
# calling get_test_case_features(test_case_name)
#
# :return: list of strings
# """
# return b_unit.BenchmarkingUnit.get_available_test_cases()
@staticmethod
def get_test_case_features(test_case):
"""
Returns a list of features (description, requested parameters,
allowed values, etc.) for a specified test case.
:param test_case: name of the test case (string)
The string represents the test case and can be
obtained calling "get_available_test_cases()"
method.
:return: dict() containing the features of the test case
"""
if not isinstance(test_case, str):
raise ValueError('The provided test_case parameter has to be '
'a string')
benchmark = b_unit.BenchmarkingUnit.get_required_benchmarks(
[test_case])[0]
return benchmark.get_features()
@staticmethod
def execute_framework(
test_cases,
iterations,
heat_template,
heat_template_parameters,
deployment_configuration,
openstack_credentials
):
"""
Executes the framework according the inputs
:param test_cases: Test cases to be ran on the workload
(dict() of dict())
Example:
test_case = dict()
test_case['name'] = 'module.Class'
test_case['params'] = dict()
test_case['params']['throughput'] = '1'
test_case['params']['vlan_sender'] = '1007'
test_case['params']['vlan_receiver'] = '1006'
test_cases = [test_case]
:param iterations: Number of cycles to be executed (int)
:param heat_template: (string) File name of the heat template of the
workload to be deployed. It contains the
parameters to be evaluated in the form of
#parameter_name. (See heat_templates/vTC.yaml as
example).
:param heat_template_parameters: (dict) Parameters to be provided
as input to the heat template.
See http://docs.openstack.org/developer/heat/
template_guide/hot_guide.html - section
"Template input parameters" for further info.
:param deployment_configuration: ( dict[string] = list(strings) ) )
Dictionary of parameters representing the
deployment configuration of the workload
The key is a string corresponding to the name of
the parameter, the value is a list of strings
representing the value to be assumed by a specific
param.
The parameters are user defined: they have to
correspond to the place holders (#parameter_name)
specified in the heat template.
:return: dict() Containing results
"""
common.init(api=True)
# Input Validation
common.InputValidation.validate_os_credentials(openstack_credentials)
credentials = openstack_credentials
msg = 'The provided heat_template does not exist'
if common.RELEASE == 'liberty':
heat_template = 'vTC_liberty.yaml'
else:
heat_template = 'vTC.yaml'
template = "{}{}".format(common.get_template_dir(), heat_template)
common.InputValidation.validate_file_exist(template, msg)
msg = 'The provided iterations variable must be an integer value'
common.InputValidation.validate_integer(iterations, msg)
msg = 'The provided heat_template_parameters variable must be a ' \
'dictionary'
common.InputValidation.validate_dictionary(heat_template_parameters,
msg)
log_msg = "Generation of all the heat templates " \
"required by the experiment"
common.LOG.info(log_msg)
heat_template_generation.generates_templates(heat_template,
deployment_configuration)
benchmarking_unit = \
b_unit.BenchmarkingUnit(
heat_template, credentials, heat_template_parameters,
iterations, test_cases)
try:
common.LOG.info("Benchmarking Unit initialization")
benchmarking_unit.initialize()
common.LOG.info("Benchmarking Unit Running")
results = benchmarking_unit.run_benchmarks()
finally:
common.LOG.info("Benchmarking Unit Finalization")
benchmarking_unit.finalize()
return results
|
dtudares/hello-world
|
yardstick/yardstick/vTC/apexlake/experimental_framework/api.py
|
Python
|
apache-2.0
| 6,381 | 0 |
# -*- coding: utf-8 -*-
from django.conf import settings
from django.contrib import admin
from django.contrib.auth import get_permission_codename, get_user_model
from django.contrib.auth.models import AnonymousUser
from django.contrib.sites.models import Site
from django.core.urlresolvers import reverse, NoReverseMatch, resolve, Resolver404
from django.db.models import Q
from django.utils.translation import override as force_language, ugettext_lazy as _
from cms.api import get_page_draft, can_change_page
from cms.constants import TEMPLATE_INHERITANCE_MAGIC, PUBLISHER_STATE_PENDING
from cms.models import Placeholder, Title, Page, PageType, StaticPlaceholder
from cms.toolbar.items import ButtonList, TemplateItem, REFRESH_PAGE
from cms.toolbar_base import CMSToolbar
from cms.toolbar_pool import toolbar_pool
from cms.utils import get_language_from_request, page_permissions
from cms.utils.conf import get_cms_setting
from cms.utils.i18n import get_language_tuple, get_language_dict
from cms.utils.page_permissions import (
user_can_change_page,
user_can_delete_page,
user_can_publish_page,
)
from cms.utils.urlutils import add_url_parameters, admin_reverse
from menus.utils import DefaultLanguageChanger
# Identifiers for search
ADMIN_MENU_IDENTIFIER = 'admin-menu'
LANGUAGE_MENU_IDENTIFIER = 'language-menu'
TEMPLATE_MENU_BREAK = 'Template Menu Break'
PAGE_MENU_IDENTIFIER = 'page'
PAGE_MENU_ADD_IDENTIFIER = 'add_page'
PAGE_MENU_FIRST_BREAK = 'Page Menu First Break'
PAGE_MENU_SECOND_BREAK = 'Page Menu Second Break'
PAGE_MENU_THIRD_BREAK = 'Page Menu Third Break'
PAGE_MENU_FOURTH_BREAK = 'Page Menu Fourth Break'
PAGE_MENU_LAST_BREAK = 'Page Menu Last Break'
HISTORY_MENU_BREAK = 'History Menu Break'
MANAGE_PAGES_BREAK = 'Manage Pages Break'
ADMIN_SITES_BREAK = 'Admin Sites Break'
ADMINISTRATION_BREAK = 'Administration Break'
CLIPBOARD_BREAK = 'Clipboard Break'
USER_SETTINGS_BREAK = 'User Settings Break'
ADD_PAGE_LANGUAGE_BREAK = "Add page language Break"
REMOVE_PAGE_LANGUAGE_BREAK = "Remove page language Break"
COPY_PAGE_LANGUAGE_BREAK = "Copy page language Break"
TOOLBAR_DISABLE_BREAK = 'Toolbar disable Break'
SHORTCUTS_BREAK = 'Shortcuts Break'
@toolbar_pool.register
class PlaceholderToolbar(CMSToolbar):
"""
Adds placeholder edit buttons if placeholders or static placeholders are detected in the template
"""
def populate(self):
self.page = get_page_draft(self.request.current_page)
def post_template_populate(self):
super(PlaceholderToolbar, self).post_template_populate()
self.add_wizard_button()
def add_wizard_button(self):
from cms.wizards.wizard_pool import entry_choices
title = _("Create")
if self.page:
user = self.request.user
page_pk = self.page.pk
disabled = len(list(entry_choices(user, self.page))) == 0
else:
page_pk = ''
disabled = True
url = '{url}?page={page}&language={lang}&edit'.format(
url=reverse("cms_wizard_create"),
page=page_pk,
lang=self.toolbar.site_language,
)
self.toolbar.add_modal_button(title, url,
side=self.toolbar.RIGHT,
disabled=disabled,
on_close=REFRESH_PAGE)
@toolbar_pool.register
class BasicToolbar(CMSToolbar):
"""
Basic Toolbar for site and languages menu
"""
page = None
_language_menu = None
_admin_menu = None
def init_from_request(self):
self.page = get_page_draft(self.request.current_page)
def populate(self):
if not self.page:
self.init_from_request()
self.clipboard = self.request.toolbar.user_settings.clipboard
self.add_admin_menu()
self.add_language_menu()
def add_admin_menu(self):
if not self._admin_menu:
self._admin_menu = self.toolbar.get_or_create_menu(ADMIN_MENU_IDENTIFIER, self.current_site.name)
# Users button
self.add_users_button(self._admin_menu)
# sites menu
sites_queryset = Site.objects.order_by('name')
if len(sites_queryset) > 1:
sites_menu = self._admin_menu.get_or_create_menu('sites', _('Sites'))
sites_menu.add_sideframe_item(_('Admin Sites'), url=admin_reverse('sites_site_changelist'))
sites_menu.add_break(ADMIN_SITES_BREAK)
for site in sites_queryset:
sites_menu.add_link_item(site.name, url='http://%s' % site.domain,
active=site.pk == self.current_site.pk)
# admin
self._admin_menu.add_sideframe_item(_('Administration'), url=admin_reverse('index'))
self._admin_menu.add_break(ADMINISTRATION_BREAK)
# cms users settings
self._admin_menu.add_sideframe_item(_('User settings'), url=admin_reverse('cms_usersettings_change'))
self._admin_menu.add_break(USER_SETTINGS_BREAK)
# clipboard
if self.toolbar.edit_mode_active:
# True if the clipboard exists and there's plugins in it.
clipboard_is_bound = self.toolbar.clipboard_plugin
self._admin_menu.add_link_item(_('Clipboard...'), url='#',
extra_classes=['cms-clipboard-trigger'],
disabled=not clipboard_is_bound)
self._admin_menu.add_link_item(_('Clear clipboard'), url='#',
extra_classes=['cms-clipboard-empty'],
disabled=not clipboard_is_bound)
self._admin_menu.add_break(CLIPBOARD_BREAK)
# Disable toolbar
self._admin_menu.add_link_item(_('Disable toolbar'), url='?%s' % get_cms_setting('CMS_TOOLBAR_URL__DISABLE'))
self._admin_menu.add_break(TOOLBAR_DISABLE_BREAK)
self._admin_menu.add_link_item(_('Shortcuts...'), url='#',
extra_classes=('cms-show-shortcuts',))
self._admin_menu.add_break(SHORTCUTS_BREAK)
# logout
self.add_logout_button(self._admin_menu)
def add_users_button(self, parent):
User = get_user_model()
if User in admin.site._registry:
opts = User._meta
if self.request.user.has_perm('%s.%s' % (opts.app_label, get_permission_codename('change', opts))):
user_changelist_url = admin_reverse('%s_%s_changelist' % (opts.app_label, opts.model_name))
parent.add_sideframe_item(_('Users'), url=user_changelist_url)
def add_logout_button(self, parent):
# If current page is not published or has view restrictions user is redirected to the home page:
# * published page: no redirect
# * unpublished page: redirect to the home page
# * published page with login_required: redirect to the home page
# * published page with view permissions: redirect to the home page
page_is_published = self.page and self.page.is_published(self.current_lang)
if page_is_published and not self.page.login_required:
anon_can_access = page_permissions.user_can_view_page(
user=AnonymousUser(),
page=self.page,
site=self.current_site,
)
else:
anon_can_access = False
on_success = self.toolbar.REFRESH_PAGE if anon_can_access else '/'
# We'll show "Logout Joe Bloggs" if the name fields in auth.User are completed, else "Logout jbloggs". If
# anything goes wrong, it'll just be "Logout".
user_name = self.get_username()
logout_menu_text = _('Logout %s') % user_name if user_name else _('Logout')
parent.add_ajax_item(
logout_menu_text,
action=admin_reverse('logout'),
active=True,
on_success=on_success,
method='GET',
)
def add_language_menu(self):
if settings.USE_I18N and not self._language_menu:
self._language_menu = self.toolbar.get_or_create_menu(LANGUAGE_MENU_IDENTIFIER, _('Language'), position=-1)
language_changer = getattr(self.request, '_language_changer', DefaultLanguageChanger(self.request))
for code, name in get_language_tuple(self.current_site.pk):
try:
url = language_changer(code)
except NoReverseMatch:
url = DefaultLanguageChanger(self.request)(code)
self._language_menu.add_link_item(name, url=url, active=self.current_lang == code)
def get_username(self, user=None, default=''):
user = user or self.request.user
try:
name = user.get_full_name()
if name:
return name
else:
return user.get_username()
except (AttributeError, NotImplementedError):
return default
@toolbar_pool.register
class PageToolbar(CMSToolbar):
_changed_admin_menu = None
watch_models = [Page, PageType]
def init_placeholders(self):
request = self.request
toolbar = self.toolbar
if toolbar._async and 'placeholders[]' in request.GET:
# AJAX request to reload page structure
placeholder_ids = request.GET.getlist("placeholders[]")
self.placeholders = Placeholder.objects.filter(pk__in=placeholder_ids)
self.statics = StaticPlaceholder.objects.filter(
Q(draft__in=placeholder_ids) | Q(public__in=placeholder_ids)
)
self.dirty_statics = [sp for sp in self.statics if sp.dirty]
else:
if toolbar.structure_mode_active and not toolbar.uses_legacy_structure_mode:
# User has explicitly requested structure mode
# and the object (page, blog, etc..) allows for the non-legacy structure mode
renderer = toolbar.structure_renderer
else:
renderer = toolbar.get_content_renderer()
self.placeholders = renderer.get_rendered_placeholders()
self.statics = renderer.get_rendered_static_placeholders()
self.dirty_statics = [sp for sp in self.statics if sp.dirty]
def add_structure_mode(self):
if self.page and not self.page.application_urls:
if user_can_change_page(self.request.user, page=self.page):
return self.add_structure_mode_item()
elif any(ph for ph in self.placeholders if ph.has_change_permission(self.request.user)):
return self.add_structure_mode_item()
for sp in self.statics:
if sp.has_change_permission(self.request):
return self.add_structure_mode_item()
def add_structure_mode_item(self, extra_classes=('cms-toolbar-item-cms-mode-switcher',)):
structure_active = self.toolbar.structure_mode_active
edit_mode_active = (not structure_active and self.toolbar.edit_mode_active)
build_url = '{}?{}'.format(self.toolbar.request_path, get_cms_setting('CMS_TOOLBAR_URL__BUILD'))
edit_url = '{}?{}'.format(self.toolbar.request_path, get_cms_setting('CMS_TOOLBAR_URL__EDIT_ON'))
if self.request.user.has_perm("cms.use_structure"):
switcher = self.toolbar.add_button_list('Mode Switcher', side=self.toolbar.RIGHT,
extra_classes=extra_classes)
switcher.add_button(_('Structure'), build_url, active=structure_active, disabled=False,
extra_classes='cms-structure-btn')
switcher.add_button(_('Content'), edit_url, active=edit_mode_active, disabled=False,
extra_classes='cms-content-btn')
def get_title(self):
try:
return Title.objects.get(page=self.page, language=self.current_lang, publisher_is_draft=True)
except Title.DoesNotExist:
return None
def has_publish_permission(self):
if self.page:
publish_permission = page_permissions.user_can_publish_page(
self.request.user,
page=self.page,
site=self.current_site
)
else:
publish_permission = False
if publish_permission and self.statics:
publish_permission = all(sp.has_publish_permission(self.request) for sp in self.dirty_statics)
return publish_permission
def has_unpublish_permission(self):
return self.has_publish_permission()
def has_page_change_permission(self):
if not hasattr(self, 'page_change_permission'):
self.page_change_permission = can_change_page(self.request)
return self.page_change_permission
def page_is_pending(self, page, language):
return (page.publisher_public_id and
page.publisher_public.get_publisher_state(language) == PUBLISHER_STATE_PENDING)
def in_apphook(self):
with force_language(self.toolbar.language):
try:
resolver = resolve(self.toolbar.request_path)
except Resolver404:
return False
else:
from cms.views import details
return resolver.func != details
def in_apphook_root(self):
"""
Returns True if the request is for a page handled by an apphook, but
is also the page it is attached to.
:return: Boolean
"""
page = getattr(self.request, 'current_page', False)
if page:
language = get_language_from_request(self.request)
return self.toolbar.request_path == page.get_absolute_url(language=language)
return False
def get_on_delete_redirect_url(self):
language = self.current_lang
parent_page = self.page.parent_page if self.page else None
# if the current page has a parent in the request's current language redirect to it
if parent_page and language in parent_page.get_languages():
with force_language(language):
return parent_page.get_absolute_url(language=language)
# else redirect to root, do not redirect to Page.objects.get_home() because user could have deleted the last
# page, if DEBUG == False this could cause a 404
return reverse('pages-root')
# Populate
def populate(self):
self.page = get_page_draft(self.request.current_page)
self.title = self.get_title()
self.permissions_activated = get_cms_setting('PERMISSION')
self.change_admin_menu()
self.add_page_menu()
self.change_language_menu()
def post_template_populate(self):
self.init_placeholders()
self.add_draft_live()
self.add_publish_button()
self.add_structure_mode()
def has_dirty_objects(self):
language = self.current_lang
if self.page:
if self.dirty_statics:
# There's dirty static placeholders on this page.
# Only show the page as dirty (publish button) if the page
# translation has been configured.
dirty = self.page.has_translation(language)
else:
dirty = (self.page.is_dirty(language) or self.page_is_pending(self.page, language))
else:
dirty = bool(self.dirty_statics)
return dirty
# Buttons
def add_publish_button(self, classes=('cms-btn-action', 'cms-btn-publish',)):
if self.user_can_publish():
button = self.get_publish_button(classes=classes)
self.toolbar.add_item(button)
def user_can_publish(self):
if self.page and self.page.is_page_type:
# By design, page-types are not publishable.
return False
if not self.toolbar.edit_mode_active:
return False
return self.has_publish_permission() and self.has_dirty_objects()
def get_publish_button(self, classes=None):
dirty = self.has_dirty_objects()
classes = list(classes or [])
if dirty and 'cms-btn-publish-active' not in classes:
classes.append('cms-btn-publish-active')
if self.dirty_statics or (self.page and self.page.is_published(self.current_lang)):
title = _('Publish page changes')
else:
title = _('Publish page now')
classes.append('cms-publish-page')
item = ButtonList(side=self.toolbar.RIGHT)
item.add_button(
title,
url=self.get_publish_url(),
disabled=not dirty,
extra_classes=classes,
)
return item
def get_publish_url(self):
pk = self.page.pk if self.page else 0
params = {}
if self.dirty_statics:
params['statics'] = ','.join(str(sp.pk) for sp in self.dirty_statics)
if self.in_apphook():
params['redirect'] = self.toolbar.request_path
with force_language(self.current_lang):
url = admin_reverse('cms_page_publish_page', args=(pk, self.current_lang))
return add_url_parameters(url, params)
def add_draft_live(self):
if self.page:
if self.toolbar.edit_mode_active and not self.title:
self.add_page_settings_button()
if user_can_change_page(self.request.user, page=self.page) and self.page.is_published(self.current_lang):
return self.add_draft_live_item()
elif self.placeholders:
return self.add_draft_live_item()
for sp in self.statics:
if sp.has_change_permission(self.request):
return self.add_draft_live_item()
def add_draft_live_item(self, template='cms/toolbar/items/live_draft.html', extra_context=None):
context = {'cms_toolbar': self.toolbar}
context.update(extra_context or {})
pos = len(self.toolbar.right_items)
self.toolbar.add_item(TemplateItem(template, extra_context=context, side=self.toolbar.RIGHT), position=pos)
def add_page_settings_button(self, extra_classes=('cms-btn-action',)):
url = '%s?language=%s' % (admin_reverse('cms_page_change', args=[self.page.pk]), self.toolbar.language)
self.toolbar.add_modal_button(_('Page settings'), url, side=self.toolbar.RIGHT, extra_classes=extra_classes)
# Menus
def change_language_menu(self):
if self.toolbar.edit_mode_active and self.page:
can_change = page_permissions.user_can_change_page(
user=self.request.user,
page=self.page,
site=self.current_site,
)
else:
can_change = False
if can_change:
language_menu = self.toolbar.get_menu(LANGUAGE_MENU_IDENTIFIER)
if not language_menu:
return None
languages = get_language_dict(self.current_site.pk)
remove = [(code, languages.get(code, code)) for code in self.page.get_languages() if code in languages]
add = [l for l in languages.items() if l not in remove]
copy = [(code, name) for code, name in languages.items() if code != self.current_lang and (code, name) in remove]
if add or remove or copy:
language_menu.add_break(ADD_PAGE_LANGUAGE_BREAK)
if add:
add_plugins_menu = language_menu.get_or_create_menu('{0}-add'.format(LANGUAGE_MENU_IDENTIFIER), _('Add Translation'))
if self.page.is_page_type:
page_change_url = admin_reverse('cms_pagetype_change', args=(self.page.pk,))
else:
page_change_url = admin_reverse('cms_page_change', args=(self.page.pk,))
for code, name in add:
url = add_url_parameters(page_change_url, language=code)
add_plugins_menu.add_modal_item(name, url=url)
if remove:
if self.page.is_page_type:
translation_delete_url = admin_reverse('cms_pagetype_delete_translation', args=(self.page.pk,))
else:
translation_delete_url = admin_reverse('cms_page_delete_translation', args=(self.page.pk,))
remove_plugins_menu = language_menu.get_or_create_menu('{0}-del'.format(LANGUAGE_MENU_IDENTIFIER), _('Delete Translation'))
disabled = len(remove) == 1
for code, name in remove:
url = add_url_parameters(translation_delete_url, language=code)
remove_plugins_menu.add_modal_item(name, url=url, disabled=disabled)
if copy:
copy_plugins_menu = language_menu.get_or_create_menu('{0}-copy'.format(LANGUAGE_MENU_IDENTIFIER), _('Copy all plugins'))
title = _('from %s')
question = _('Are you sure you want to copy all plugins from %s?')
if self.page.is_page_type:
page_copy_url = admin_reverse('cms_pagetype_copy_language', args=(self.page.pk,))
else:
page_copy_url = admin_reverse('cms_page_copy_language', args=(self.page.pk,))
for code, name in copy:
copy_plugins_menu.add_ajax_item(
title % name, action=page_copy_url,
data={'source_language': code, 'target_language': self.current_lang},
question=question % name, on_success=self.toolbar.REFRESH_PAGE
)
def change_admin_menu(self):
can_change_page = self.has_page_change_permission()
if not can_change_page:
# Check if the user has permissions to change at least one page
can_change_page = page_permissions.user_can_change_at_least_one_page(
user=self.request.user,
site=self.current_site,
)
if not self._changed_admin_menu and can_change_page:
admin_menu = self.toolbar.get_or_create_menu(ADMIN_MENU_IDENTIFIER)
url = admin_reverse('cms_page_changelist') # cms page admin
params = {'language': self.toolbar.language}
if self.page:
params['page_id'] = self.page.pk
url = add_url_parameters(url, params)
admin_menu.add_sideframe_item(_('Pages'), url=url, position=0)
# Used to prevent duplicates
self._changed_admin_menu = True
def add_page_menu(self):
if self.page:
edit_mode = self.toolbar.edit_mode_active
refresh = self.toolbar.REFRESH_PAGE
can_change = user_can_change_page(
user=self.request.user,
page=self.page,
site=self.current_site,
)
# menu for current page
# NOTE: disabled if the current path is "deeper" into the
# application's url patterns than its root. This is because
# when the Content Manager is at the root of the app-hook,
# some of the page options still make sense.
current_page_menu = self.toolbar.get_or_create_menu(
PAGE_MENU_IDENTIFIER, _('Page'), position=1, disabled=self.in_apphook() and not self.in_apphook_root())
new_page_params = {'edit': 1}
new_sub_page_params = {'edit': 1, 'parent_node': self.page.node_id}
if self.page.is_page_type:
add_page_url = admin_reverse('cms_pagetype_add')
advanced_url = admin_reverse('cms_pagetype_advanced', args=(self.page.pk,))
page_settings_url = admin_reverse('cms_pagetype_change', args=(self.page.pk,))
duplicate_page_url = admin_reverse('cms_pagetype_duplicate', args=[self.page.pk])
else:
add_page_url = admin_reverse('cms_page_add')
advanced_url = admin_reverse('cms_page_advanced', args=(self.page.pk,))
page_settings_url = admin_reverse('cms_page_change', args=(self.page.pk,))
duplicate_page_url = admin_reverse('cms_page_duplicate', args=[self.page.pk])
can_add_root_page = page_permissions.user_can_add_page(
user=self.request.user,
site=self.current_site,
)
if self.page.parent_page:
new_page_params['parent_node'] = self.page.parent_page.node_id
can_add_sibling_page = page_permissions.user_can_add_subpage(
user=self.request.user,
target=self.page.parent_page,
)
else:
can_add_sibling_page = can_add_root_page
can_add_sub_page = page_permissions.user_can_add_subpage(
user=self.request.user,
target=self.page,
)
# page operations menu
add_page_menu = current_page_menu.get_or_create_menu(
PAGE_MENU_ADD_IDENTIFIER,
_('Create Page'),
)
add_page_menu_modal_items = (
(_('New Page'), new_page_params, can_add_sibling_page),
(_('New Sub Page'), new_sub_page_params, can_add_sub_page),
)
for title, params, has_perm in add_page_menu_modal_items:
params.update(language=self.toolbar.language)
add_page_menu.add_modal_item(
title,
url=add_url_parameters(add_page_url, params),
disabled=not has_perm,
)
add_page_menu.add_modal_item(
_('Duplicate this Page'),
url=add_url_parameters(duplicate_page_url, {'language': self.toolbar.language}),
disabled=not can_add_sibling_page,
)
# first break
current_page_menu.add_break(PAGE_MENU_FIRST_BREAK)
# page edit
page_edit_url = '?%s' % get_cms_setting('CMS_TOOLBAR_URL__EDIT_ON')
current_page_menu.add_link_item(_('Edit this Page'), disabled=edit_mode, url=page_edit_url)
# page settings
page_settings_url = add_url_parameters(page_settings_url, language=self.toolbar.language)
settings_disabled = not edit_mode or not can_change
current_page_menu.add_modal_item(_('Page settings'), url=page_settings_url, disabled=settings_disabled,
on_close=refresh)
# advanced settings
advanced_url = add_url_parameters(advanced_url, language=self.toolbar.language)
can_change_advanced = self.page.has_advanced_settings_permission(self.request.user)
advanced_disabled = not edit_mode or not can_change_advanced
current_page_menu.add_modal_item(_('Advanced settings'), url=advanced_url, disabled=advanced_disabled)
# templates menu
if edit_mode:
if self.page.is_page_type:
action = admin_reverse('cms_pagetype_change_template', args=(self.page.pk,))
else:
action = admin_reverse('cms_page_change_template', args=(self.page.pk,))
if can_change_advanced:
templates_menu = current_page_menu.get_or_create_menu(
'templates',
_('Templates'),
disabled=not can_change,
)
for path, name in get_cms_setting('TEMPLATES'):
active = self.page.template == path
if path == TEMPLATE_INHERITANCE_MAGIC:
templates_menu.add_break(TEMPLATE_MENU_BREAK)
templates_menu.add_ajax_item(name, action=action, data={'template': path}, active=active,
on_success=refresh)
# page type
if not self.page.is_page_type:
page_type_url = admin_reverse('cms_pagetype_add')
page_type_url = add_url_parameters(page_type_url, source=self.page.pk, language=self.toolbar.language)
page_type_disabled = not edit_mode or not can_add_root_page
current_page_menu.add_modal_item(_('Save as Page Type'), page_type_url, disabled=page_type_disabled)
# second break
current_page_menu.add_break(PAGE_MENU_SECOND_BREAK)
# permissions
if self.permissions_activated:
permissions_url = admin_reverse('cms_page_permissions', args=(self.page.pk,))
permission_disabled = not edit_mode
if not permission_disabled:
permission_disabled = not page_permissions.user_can_change_page_permissions(
user=self.request.user,
page=self.page,
)
current_page_menu.add_modal_item(_('Permissions'), url=permissions_url, disabled=permission_disabled)
if not self.page.is_page_type:
# dates settings
dates_url = admin_reverse('cms_page_dates', args=(self.page.pk,))
current_page_menu.add_modal_item(
_('Publishing dates'),
url=dates_url,
disabled=(not edit_mode or not can_change),
)
# third break
current_page_menu.add_break(PAGE_MENU_THIRD_BREAK)
# navigation toggle
nav_title = _('Hide in navigation') if self.page.in_navigation else _('Display in navigation')
nav_action = admin_reverse('cms_page_change_innavigation', args=(self.page.pk,))
current_page_menu.add_ajax_item(
nav_title,
action=nav_action,
disabled=(not edit_mode or not can_change),
on_success=refresh,
)
# publisher
if self.title and not self.page.is_page_type:
if self.title.published:
publish_title = _('Unpublish page')
publish_url = admin_reverse('cms_page_unpublish', args=(self.page.pk, self.current_lang))
else:
publish_title = _('Publish page')
publish_url = admin_reverse('cms_page_publish_page', args=(self.page.pk, self.current_lang))
user_can_publish = user_can_publish_page(self.request.user, page=self.page)
current_page_menu.add_ajax_item(
publish_title,
action=publish_url,
disabled=not edit_mode or not user_can_publish,
on_success=refresh,
)
if self.current_lang and not self.page.is_page_type:
# revert to live
current_page_menu.add_break(PAGE_MENU_FOURTH_BREAK)
revert_action = admin_reverse('cms_page_revert_to_live', args=(self.page.pk, self.current_lang))
revert_question = _('Are you sure you want to revert to live?')
# Only show this action if the page has pending changes and a public version
is_enabled = (
edit_mode
and can_change
and self.page.is_dirty(self.current_lang)
and self.page.publisher_public
)
current_page_menu.add_ajax_item(
_('Revert to live'),
action=revert_action,
question=revert_question,
disabled=not is_enabled,
on_success=refresh,
extra_classes=('cms-toolbar-revert',),
)
# last break
current_page_menu.add_break(PAGE_MENU_LAST_BREAK)
# delete
if self.page.is_page_type:
delete_url = admin_reverse('cms_pagetype_delete', args=(self.page.pk,))
else:
delete_url = admin_reverse('cms_page_delete', args=(self.page.pk,))
delete_disabled = not edit_mode or not user_can_delete_page(self.request.user, page=self.page)
on_delete_redirect_url = self.get_on_delete_redirect_url()
current_page_menu.add_modal_item(_('Delete page'), url=delete_url, on_close=on_delete_redirect_url,
disabled=delete_disabled)
|
czpython/django-cms
|
cms/cms_toolbars.py
|
Python
|
bsd-3-clause
| 32,747 | 0.003237 |
"""Yummly data models.
"""
from inspect import getargspec
class Storage(dict):
"""An object that is like a dict except `obj.foo` can be used in addition
to `obj['foo']`.
Raises Attribute/Key errors for missing references.
>>> o = Storage(a=1, b=2)
>>> assert(o.a == o['a'])
>>> assert(o.b == o['b'])
>>> o.a = 2
>>> print o['a']
2
>>> x = o.copy()
>>> assert(x == o)
>>> del o.a
>>> print o.a
Traceback (most recent call last):
...
AttributeError: a
>>> print o['a']
Traceback (most recent call last):
...
KeyError: 'a'
>>> o._get_fields()
Traceback (most recent call last):
...
TypeError: ...
"""
def __getattr__(self, key):
if key in self:
return self[key]
else:
raise AttributeError(key)
def __setattr__(self, key, value):
self[key] = value
def __delattr__(self, key):
if key in self:
del self[key]
else:
raise AttributeError(key)
def __repr__(self):
return '%s(%s)' % (self.__class__.__name__, dict.__repr__(self))
@classmethod
def _get_fields(cls):
"""Return class' __init__() args excluding `self`.
Assumes that calling class has actually implemented __init__(),
otherwise, this will fail.
"""
# For classes, first element of args == self which we don't want.
return getargspec(cls.__init__).args[1:]
##################################################
# Get recipe related models
##################################################
class Recipe(Storage):
"""Recipe model."""
def __init__(self, **kargs):
self.id = kargs['id']
self.name = kargs['name']
self.rating = kargs.get('rating')
self.totalTime = kargs.get('totalTime') or 0
self.totalTimeInSeconds = kargs.get('totalTimeInSeconds') or 0
self.ingredientLines = kargs.get('ingredientLines') or []
self.numberOfServings = kargs.get('numberOfServings')
self.yields = kargs.get('yields')
self.attributes = kargs.get('attributes') or {}
self.source = RecipeSource(**(kargs.get('source') or {}))
self.attribution = Attribution(**(kargs.get('attribution') or {}))
# NOTE: For `flavors`, the keys are returned capitalized so normalize
# to lowercase since search results' flavor keys are lowercase.
flavors = kargs.get('flavors') or {}
self.flavors = Flavors(**{key.lower(): value
for key, value in flavors.iteritems()})
self.nutritionEstimates = [NutritionEstimate(**nute)
for nute in (kargs.get('nutritionEstimates')
or [])]
self.images = [RecipeImages(**imgs)
for imgs in (kargs.get('images') or [])]
class Flavors(Storage):
"""Flavors model."""
def __init__(self, **kargs):
self.salty = kargs.get('salty')
self.meaty = kargs.get('meaty')
self.piquant = kargs.get('piquant')
self.bitter = kargs.get('bitter')
self.sour = kargs.get('sour')
self.sweet = kargs.get('sweet')
class Attribution(Storage):
"""Attribution model."""
def __init__(self, **kargs):
self.html = kargs.get('html')
self.url = kargs.get('url')
self.text = kargs.get('text')
self.logo = kargs.get('logo')
class NutritionEstimate(Storage):
"""Nutrition estimate model."""
def __init__(self, **kargs):
self.attribute = kargs.get('attribute')
self.description = kargs.get('description')
self.value = kargs.get('value')
self.unit = NutritionUnit(**(kargs.get('unit') or {}))
class NutritionUnit(Storage):
"""Nutrition unit model."""
def __init__(self, **kargs):
self.id = kargs['id']
self.abbreviation = kargs.get('abbreviation')
self.plural = kargs.get('plural')
self.pluralAbbreviation = kargs.get('pluralAbbreviation')
class RecipeImages(Storage):
"""Recipe images model."""
def __init__(self, **kargs):
self.hostedLargeUrl = kargs.get('hostedLargeUrl')
self.hostedSmallUrl = kargs.get('hostedSmallUrl')
class RecipeSource(Storage):
"""Recipe source model."""
def __init__(self, **kargs):
self.sourceRecipeUrl = kargs.get('sourceRecipeUrl')
self.sourceSiteUrl = kargs.get('sourceSiteUrl')
self.sourceDisplayName = kargs.get('sourceDisplayName')
##################################################
# Search related models
##################################################
class SearchResult(Storage):
"""Search result model."""
def __init__(self, **kargs):
self.totalMatchCount = kargs['totalMatchCount']
self.criteria = SearchCriteria(**kargs['criteria'])
self.facetCounts = kargs['facetCounts']
self.matches = [SearchMatch(**match) for match in kargs['matches']]
self.attribution = Attribution(**kargs['attribution'])
class SearchMatch(Storage):
"""Search match model."""
def __init__(self, **kargs):
self.id = kargs['id']
self.recipeName = kargs['recipeName']
self.rating = kargs.get('rating')
self.totalTimeInSeconds = kargs.get('totalTimeInSeconds', 0)
self.ingredients = kargs.get('ingredients')
self.flavors = Flavors(**(kargs.get('flavors') or {}))
self.smallImageUrls = kargs.get('smallImageUrls')
self.sourceDisplayName = kargs.get('sourceDisplayName', '')
self.attributes = kargs.get('attributes')
class SearchCriteria(Storage):
"""Search criteria model."""
def __init__(self, **kargs):
self.maxResults = kargs.get('maxResults')
self.resultsToSkip = kargs.get('resultsToSkip')
self.terms = kargs.get('terms')
self.requirePictures = kargs.get('requirePictures')
self.facetFields = kargs.get('facetFields')
self.allowedIngredients = kargs.get('allowedIngredients')
self.excludedIngredients = kargs.get('excludedIngredients')
self.attributeRanges = kargs.get('attributeRanges', {})
self.allowedAttributes = kargs.get('allowedAttributes', [])
self.excludedAttributes = kargs.get('excludedAttributes', [])
self.allowedDiets = kargs.get('allowedDiets', [])
self.nutritionRestrictions = kargs.get('nutritionRestrictions', {})
##################################################
# Metadata related models
##################################################
class MetaAttribute(Storage):
"""Base class for metadata attributes."""
def __init__(self, **kargs):
self.id = kargs['id']
self.description = kargs['description']
self.localesAvailableIn = kargs['localesAvailableIn']
self.name = kargs['name']
self.searchValue = kargs['searchValue']
self.type = kargs['type']
class MetaHoliday(MetaAttribute):
"""Holiday metadata model."""
pass
class MetaCuisine(MetaAttribute):
"""Cuisine metadata model."""
pass
class MetaCourse(MetaAttribute):
"""Course metadata model."""
pass
class MetaTechnique(MetaAttribute):
"""Technique metadata model."""
pass
class MetaSource(Storage):
"""Source metadata model."""
def __init__(self, **kargs):
self.faviconUrl = kargs['faviconUrl']
self.description = kargs['description']
self.searchValue = kargs['searchValue']
class MetaBrand(Storage):
"""Brand metadata model."""
def __init__(self, **kargs):
self.faviconUrl = kargs['faviconUrl']
self.description = kargs['description']
self.searchValue = kargs['searchValue']
class MetaDiet(Storage):
"""Diet metadata model."""
def __init__(self, **kargs):
self.id = kargs['id']
self.localesAvailableIn = kargs['localesAvailableIn']
self.longDescription = kargs['longDescription']
self.searchValue = kargs['searchValue']
self.shortDescription = kargs['shortDescription']
self.type = kargs['type']
class MetaAllergy(Storage):
"""Allergy metadata model."""
def __init__(self, **kargs):
self.id = kargs['id']
self.localesAvailableIn = kargs['localesAvailableIn']
self.longDescription = kargs['longDescription']
self.shortDescription = kargs['shortDescription']
self.searchValue = kargs['searchValue']
self.type = kargs['type']
class MetaIngredient(Storage):
"""Ingredient metadata model."""
def __init__(self, **kargs):
self.description = kargs['description']
self.term = kargs['term']
self.searchValue = kargs['searchValue']
|
dgilland/yummly.py
|
yummly/models.py
|
Python
|
mit
| 8,795 | 0 |
from __future__ import absolute_import
from typing import Any, Callable, Dict, Iterable, List, Set, Tuple, Text
from collections import defaultdict
import datetime
import pytz
import six
from django.db.models import Q, QuerySet
from django.template import loader
from django.conf import settings
from django.utils.timezone import now as timezone_now
from zerver.lib.notifications import build_message_list, hash_util_encode, \
one_click_unsubscribe_link
from zerver.lib.send_email import send_future_email, FromAddress
from zerver.models import UserProfile, UserMessage, Recipient, Stream, \
Subscription, UserActivity, get_active_streams, get_user_profile_by_id, \
Realm
from zerver.context_processors import common_context
from zerver.lib.queue import queue_json_publish
from zerver.lib.logging_util import create_logger
logger = create_logger(__name__, settings.DIGEST_LOG_PATH, 'DEBUG')
VALID_DIGEST_DAY = 1 # Tuesdays
DIGEST_CUTOFF = 5
# Digests accumulate 4 types of interesting traffic for a user:
# 1. Missed PMs
# 2. New streams
# 3. New users
# 4. Interesting stream traffic, as determined by the longest and most
# diversely comment upon topics.
def inactive_since(user_profile, cutoff):
# type: (UserProfile, datetime.datetime) -> bool
# Hasn't used the app in the last DIGEST_CUTOFF (5) days.
most_recent_visit = [row.last_visit for row in
UserActivity.objects.filter(
user_profile=user_profile)]
if not most_recent_visit:
# This person has never used the app.
return True
last_visit = max(most_recent_visit)
return last_visit < cutoff
def should_process_digest(realm_str):
# type: (str) -> bool
if realm_str in settings.SYSTEM_ONLY_REALMS:
# Don't try to send emails to system-only realms
return False
return True
# Changes to this should also be reflected in
# zerver/worker/queue_processors.py:DigestWorker.consume()
def queue_digest_recipient(user_profile, cutoff):
# type: (UserProfile, datetime.datetime) -> None
# Convert cutoff to epoch seconds for transit.
event = {"user_profile_id": user_profile.id,
"cutoff": cutoff.strftime('%s')}
queue_json_publish("digest_emails", event, lambda event: None)
def enqueue_emails(cutoff):
# type: (datetime.datetime) -> None
# To be really conservative while we don't have user timezones or
# special-casing for companies with non-standard workweeks, only
# try to send mail on Tuesdays.
if timezone_now().weekday() != VALID_DIGEST_DAY:
return
for realm in Realm.objects.filter(deactivated=False, show_digest_email=True):
if not should_process_digest(realm.string_id):
continue
user_profiles = UserProfile.objects.filter(
realm=realm, is_active=True, is_bot=False, enable_digest_emails=True)
for user_profile in user_profiles:
if inactive_since(user_profile, cutoff):
queue_digest_recipient(user_profile, cutoff)
logger.info("%s is inactive, queuing for potential digest" % (
user_profile.email,))
def gather_hot_conversations(user_profile, stream_messages):
# type: (UserProfile, QuerySet) -> List[Dict[str, Any]]
# Gather stream conversations of 2 types:
# 1. long conversations
# 2. conversations where many different people participated
#
# Returns a list of dictionaries containing the templating
# information for each hot conversation.
conversation_length = defaultdict(int) # type: Dict[Tuple[int, Text], int]
conversation_diversity = defaultdict(set) # type: Dict[Tuple[int, Text], Set[Text]]
for user_message in stream_messages:
if not user_message.message.sent_by_human():
# Don't include automated messages in the count.
continue
key = (user_message.message.recipient.type_id,
user_message.message.subject)
conversation_diversity[key].add(
user_message.message.sender.full_name)
conversation_length[key] += 1
diversity_list = list(conversation_diversity.items())
diversity_list.sort(key=lambda entry: len(entry[1]), reverse=True)
length_list = list(conversation_length.items())
length_list.sort(key=lambda entry: entry[1], reverse=True)
# Get up to the 4 best conversations from the diversity list
# and length list, filtering out overlapping conversations.
hot_conversations = [elt[0] for elt in diversity_list[:2]]
for candidate, _ in length_list:
if candidate not in hot_conversations:
hot_conversations.append(candidate)
if len(hot_conversations) >= 4:
break
# There was so much overlap between the diversity and length lists that we
# still have < 4 conversations. Try to use remaining diversity items to pad
# out the hot conversations.
num_convos = len(hot_conversations)
if num_convos < 4:
hot_conversations.extend([elt[0] for elt in diversity_list[num_convos:4]])
hot_conversation_render_payloads = []
for h in hot_conversations:
stream_id, subject = h
users = list(conversation_diversity[h])
count = conversation_length[h]
# We'll display up to 2 messages from the conversation.
first_few_messages = [user_message.message for user_message in
stream_messages.filter(
message__recipient__type_id=stream_id,
message__subject=subject)[:2]]
teaser_data = {"participants": users,
"count": count - len(first_few_messages),
"first_few_messages": build_message_list(
user_profile, first_few_messages)}
hot_conversation_render_payloads.append(teaser_data)
return hot_conversation_render_payloads
def gather_new_users(user_profile, threshold):
# type: (UserProfile, datetime.datetime) -> Tuple[int, List[Text]]
# Gather information on users in the realm who have recently
# joined.
if user_profile.realm.is_zephyr_mirror_realm:
new_users = [] # type: List[UserProfile]
else:
new_users = list(UserProfile.objects.filter(
realm=user_profile.realm, date_joined__gt=threshold,
is_bot=False))
user_names = [user.full_name for user in new_users]
return len(user_names), user_names
def gather_new_streams(user_profile, threshold):
# type: (UserProfile, datetime.datetime) -> Tuple[int, Dict[str, List[Text]]]
if user_profile.realm.is_zephyr_mirror_realm:
new_streams = [] # type: List[Stream]
else:
new_streams = list(get_active_streams(user_profile.realm).filter(
invite_only=False, date_created__gt=threshold))
base_url = u"%s/ # narrow/stream/" % (user_profile.realm.uri,)
streams_html = []
streams_plain = []
for stream in new_streams:
narrow_url = base_url + hash_util_encode(stream.name)
stream_link = u"<a href='%s'>%s</a>" % (narrow_url, stream.name)
streams_html.append(stream_link)
streams_plain.append(stream.name)
return len(new_streams), {"html": streams_html, "plain": streams_plain}
def enough_traffic(unread_pms, hot_conversations, new_streams, new_users):
# type: (Text, Text, int, int) -> bool
if unread_pms or hot_conversations:
# If you have any unread traffic, good enough.
return True
if new_streams and new_users:
# If you somehow don't have any traffic but your realm did get
# new streams and users, good enough.
return True
return False
def handle_digest_email(user_profile_id, cutoff):
# type: (int, float) -> None
user_profile = get_user_profile_by_id(user_profile_id)
# We are disabling digest emails for soft deactivated users for the time.
# TODO: Find an elegant way to generate digest emails for these users.
if user_profile.long_term_idle:
return None
# Convert from epoch seconds to a datetime object.
cutoff_date = datetime.datetime.fromtimestamp(int(cutoff), tz=pytz.utc)
all_messages = UserMessage.objects.filter(
user_profile=user_profile,
message__pub_date__gt=cutoff_date).order_by("message__pub_date")
context = common_context(user_profile)
# Start building email template data.
context.update({
'realm_name': user_profile.realm.name,
'name': user_profile.full_name,
'unsubscribe_link': one_click_unsubscribe_link(user_profile, "digest")
})
# Gather recent missed PMs, re-using the missed PM email logic.
# You can't have an unread message that you sent, but when testing
# this causes confusion so filter your messages out.
pms = all_messages.filter(
~Q(message__recipient__type=Recipient.STREAM) &
~Q(message__sender=user_profile))
# Show up to 4 missed PMs.
pms_limit = 4
context['unread_pms'] = build_message_list(
user_profile, [pm.message for pm in pms[:pms_limit]])
context['remaining_unread_pms_count'] = min(0, len(pms) - pms_limit)
home_view_recipients = [sub.recipient for sub in
Subscription.objects.filter(
user_profile=user_profile,
active=True,
in_home_view=True)]
stream_messages = all_messages.filter(
message__recipient__type=Recipient.STREAM,
message__recipient__in=home_view_recipients)
# Gather hot conversations.
context["hot_conversations"] = gather_hot_conversations(
user_profile, stream_messages)
# Gather new streams.
new_streams_count, new_streams = gather_new_streams(
user_profile, cutoff_date)
context["new_streams"] = new_streams
context["new_streams_count"] = new_streams_count
# Gather users who signed up recently.
new_users_count, new_users = gather_new_users(
user_profile, cutoff_date)
context["new_users"] = new_users
# We don't want to send emails containing almost no information.
if enough_traffic(context["unread_pms"], context["hot_conversations"],
new_streams_count, new_users_count):
logger.info("Sending digest email for %s" % (user_profile.email,))
# Send now, as a ScheduledEmail
send_future_email('zerver/emails/digest', to_user_id=user_profile.id,
from_name="Zulip Digest", from_address=FromAddress.NOREPLY,
context=context)
|
verma-varsha/zulip
|
zerver/lib/digest.py
|
Python
|
apache-2.0
| 10,690 | 0.001403 |
# -*- coding: utf-8 -*-
# Copyright 2015 Objectif Libre
#
# 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.
#
# @author: Stéphane Albert
#
import os
from gabbi import driver
from cloudkitty.tests.gabbi import fixtures
from cloudkitty.tests.gabbi.rating.pyscripts import fixtures as py_fixtures
TESTS_DIR = 'gabbits'
def load_tests(loader, tests, pattern):
test_dir = os.path.join(os.path.dirname(__file__), TESTS_DIR)
return driver.build_tests(test_dir,
loader,
host=None,
intercept=fixtures.setup_app,
fixture_module=py_fixtures)
|
muraliselva10/cloudkitty
|
cloudkitty/tests/gabbi/rating/pyscripts/test_gabbi.py
|
Python
|
apache-2.0
| 1,187 | 0 |
from time import sleep
from worker import delayable
import requests
@delayable
def add(x, y, delay=None):
# Simulate your work here, preferably something interesting so Python doesn't sleep
sleep(delay or (x + y if 0 < x + y < 5 else 3))
return x + y
@delayable
def get(*args, **kwargs):
r = requests.get(*args, **kwargs)
return r.content
|
vals/google_devnull
|
tasks.py
|
Python
|
mit
| 361 | 0.00831 |
# Use this script to collapse a multi-level folder of images into one folder.
import fnmatch
import os
import shutil
folderName = 'unknown'
matches = []
for root, dirnames, filenames in os.walk(folderName):
for filename in fnmatch.filter(filenames, '*.jpg'):
matches.append(os.path.join(root, filename))
idx = 0
for match in matches:
print match
shutil.move('./' + match, './' + folderName + '/' + str(idx) + '.jpg')
idx = idx + 1
|
ajagnanan/docker-opencv-api
|
openface/images/collapse.py
|
Python
|
apache-2.0
| 465 | 0.004301 |
# -*- coding: UTF-8 -*-
import re
def mgo_text_split(query_text):
''' split text to support mongodb $text match on a phrase '''
sep = r'[`\-=~!@#$%^&*()_+\[\]{};\'\\:"|<,./<>?]'
word_lst = re.split(sep, query_text)
text_query = ' '.join('\"{}\"'.format(w) for w in word_lst)
return text_query
# 搜索逻辑
def querylogic(list):
query = {}
if len(list) > 1 or len(list[0].split(':')) > 1:
for _ in list:
if _.find(':') > -1:
q_key, q_value = _.split(':', 1)
if q_key == 'port':
query['port'] = int(q_value)
elif q_key == 'banner':
zhPattern = re.compile(u'[\u4e00-\u9fa5]+')
contents = q_value
match = zhPattern.search(contents)
# 如果没有中文用全文索引
if match:
query['banner'] = {"$regex": q_value, '$options': 'i'}
else:
text_query = mgo_text_split(q_value)
query['$text'] = {'$search': text_query, '$caseSensitive':True}
elif q_key == 'ip':
query['ip'] = {"$regex": q_value}
elif q_key == 'server':
query['server'] = q_value.lower()
elif q_key == 'title':
query['webinfo.title'] = {"$regex": q_value, '$options': 'i'}
elif q_key == 'tag':
query['webinfo.tag'] = q_value.lower()
elif q_key == 'hostname':
query['hostname'] = {"$regex": q_value, '$options': 'i'}
elif q_key == 'all':
filter_lst = []
for i in ('ip', 'banner', 'port', 'time', 'webinfo.tag', 'webinfo.title', 'server', 'hostname'):
filter_lst.append({i: {"$regex": q_value, '$options': 'i'}})
query['$or'] = filter_lst
else:
query[q_key] = q_value
else:
filter_lst = []
for i in ('ip', 'banner', 'port', 'time', 'webinfo.tag', 'webinfo.title', 'server', 'hostname'):
filter_lst.append({i: {"$regex": list[0], '$options': 'i'}})
query['$or'] = filter_lst
return query
|
ysrc/xunfeng
|
views/lib/QueryLogic.py
|
Python
|
gpl-3.0
| 2,319 | 0.002621 |
# 005_cleaner.py
#####################################################################
##################################
# Import des modules et ajout du path de travail pour import relatif
import sys
sys.path.insert(0 , 'C:/Users/WILLROS/Perso/Shade/scripts/LocalWC-Shade-App/apis/')
from voca import AddLog , StringFormatter , OutFileCreate , OdditiesFinder
##################################
# Init des paths et noms de fichiers
missionName = '005'
AddLog('title' , '{} : Début du nettoyage du fichier'.format(missionName))
work_dir = 'C:/Users/WILLROS/Perso/Shade/scripts/LocalWC-Shade-App/apis/raw/{}_raw/'.format(missionName)
# Nom du fichier source
raw_file = 'src'
##################################
# retreiving raw string
raw_string_with_tabs = open(work_dir + raw_file , 'r').read()
# replacing tabs with carriage return
raw_string_with_cr = raw_string_with_tabs.replace( '\t', '\n' )
# turning the string into a list
raw_list = raw_string_with_cr.splitlines()
# going through oddities finder
AddLog('subtitle' , 'Début de la fonction OdditiesFinder')
list_without_oddities = OdditiesFinder( raw_list )
# going through string formatter
ref_list = []
AddLog('subtitle' , 'Début de la fonction StringFormatter')
for line in list_without_oddities:
ref_list.append( StringFormatter( line ) )
##################################
# Enregistrement des fichiers sortie
AddLog('subtitle' , 'Début de la fonction OutFileCreate')
OutFileCreate('C:/Users/WILLROS/Perso/Shade/scripts/LocalWC-Shade-App/apis/out/','{}_src'.format(missionName),ref_list,'prenoms masculins italiens')
|
sighill/shade_app
|
apis/raw/005_raw/005_cleaner.py
|
Python
|
mit
| 1,625 | 0.015423 |
PER_PAGE = 50
ANNOUNCE_INTERVAL = 300
|
kron4eg/django-btt
|
settings.py
|
Python
|
gpl-3.0
| 39 | 0 |
import pygame
import os
from buffalo import utils
from item import Item
# User interface for trading with NPCs
# Similar to the crafting UI, with some minor differences
# The biggest thing is that it only appears when you "talk to" (read click on)
# A trader NPC and disappears when you leave that window, and only contains a
# Limited number of trades
class TradingUI:
BUTTON_SIZE = 32
PADDING = 6
def __init__(self, inventory, tradeSet):
self.tradeSet = tradeSet
self.inventory = inventory
self.surface = utils.empty_surface((228,500))
self.surface.fill((100,100,100,100))
self.pos = (utils.SCREEN_W / 2 + self.surface.get_width() / 2 + 350, utils.SCREEN_H / 2 - 150)
self.tileRects = list()
self.tileTrades = list()
self.updateTradeTable()
def updateTradeTable(self):
self.surface = utils.empty_surface((228,500))
self.surface.fill((100,100,100,100))
self.tileRects = list()
self.tileTrades = list()
tradeTiles = list()
total_y = 0
for t in self.tradeSet:
newTile = self.generateTradeTile(t)
tradeTiles.append(newTile)
self.tileRects.append(pygame.Rect(0, total_y, newTile.get_width(), newTile.get_height()))
self.tileTrades.append(t)
total_y += newTile.get_height()
newSurface = utils.empty_surface((228, total_y))
newSurface.fill((100,100,100,255))
currY = 0
for surf in tradeTiles:
newSurface.blit(surf, (0, currY))
currY += surf.get_height()
self.surface = newSurface
def generateTradeTile(self, trade):
y_length = 36 * (len(trade.price.keys()) / 3) + 78;
newScreen = utils.empty_surface((228, y_length))
for num, item in enumerate(trade.price.keys()):
x = ((num % 3) * TradingUI.BUTTON_SIZE) + TradingUI.PADDING
y = ((num / 3) * TradingUI.BUTTON_SIZE) + TradingUI.PADDING
itemSurface = pygame.Surface.copy(Item(item, quantity = trade.price[item]).surface)
if self.inventory.getTotalItemQuantity(item) < trade.price[item]:
itemSurface.fill(pygame.Color(255,0,0,250)[0:3] + (0,), None, pygame.BLEND_RGBA_ADD)
newScreen.blit(itemSurface, (x,y))
for num, item in enumerate(trade.goods.keys()):
x = 192 - (((num % 2) * TradingUI.BUTTON_SIZE) + TradingUI.PADDING)
y = ((num / 2) * TradingUI.BUTTON_SIZE) + TradingUI.PADDING
newScreen.blit(Item(item, quantity = trade.goods[item]).surface, (x,y))
path = os.path.join(os.path.join(*list(['assets'] + ['items'] + ["arrow.png"])))
arrowSurface = pygame.image.load(path)
newScreen.blit(arrowSurface,(114, (newScreen.get_height() / 2) - arrowSurface.get_height() / 2))
myfont = pygame.font.SysFont("monospace", 15)
color = (255,255,0)
if not trade.canTrade(self.inventory):
color = (255,0,0)
label = myfont.render(str(trade.name), 1, color)
newScreen.blit(label, (newScreen.get_width() - label.get_width() - 2, newScreen.get_height() - label.get_height() - 2))
pygame.draw.rect(newScreen, (0,0,0,255), pygame.Rect(0,0,228, y_length), 1)
return newScreen
def blit(self, dest, pos):
dest.blit(self.surface, pos)
def update(self):
pass
def mouseDown(self, pos):
for tile in self.tileRects:
if(tile.collidepoint(pos)):
clickedTrade = self.tileTrades[self.tileRects.index(tile)]
if not clickedTrade.canTrade(self.inventory):
return
for item in clickedTrade.price.keys():
self.inventory.removeItemQuantity(item, clickedTrade.price[item])
for item in clickedTrade.goods.keys():
newItem = Item(item)
newItem.quantity = clickedTrade.goods[item]
self.inventory.addItem(newItem)
self.inventory.update()
self.updateTradeTable()
return
|
benjamincongdon/adept
|
tradingUI.py
|
Python
|
mit
| 3,586 | 0.037646 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import (absolute_import, division, print_function,
unicode_literals)
from datetime import datetime
from os import environ
from requests import get
from bs4 import BeautifulSoup, NavigableString
from icalendar import Calendar, Event
# Pour faire du TLS1.0...
environ["OPENSSL_CONF"] = "openssl.cnf"
def scrape_url(url):
page = get(url)
result = [ ]
for div in BeautifulSoup(page.text, 'lxml').find_all('div', class_='infos_colonne_box'):
rows = div.find_all('tr')
if rows:
headers = [ ' '.join(x.stripped_strings) for x in rows[0] if not isinstance(x, NavigableString) ]
for row in rows[1:]:
result.append(
dict(zip(headers, [ x for x in row if not isinstance(x, NavigableString) ]))
)
return result
def create_event_formation(d):
event = Event()
dates = tuple(d['Date'].stripped_strings)
num = ''.join(d['N°'].stripped_strings)
event.add('summary', ' '.join(d['Nom'].stripped_strings))
event.add('dtstart', datetime.strptime(dates[0], '%d/%m/%y').date())
if len(dates) > 1:
event.add('dtend', datetime.strptime(dates[1], '%d/%m/%y').date())
event.add('location', ' '.join(d['Lieu'].stripped_strings).replace("\r\n", ' '))
event.add('uid', "%s@formation.ffme.fr" % (num,) )
event.add('description', 'http://www.ffme.fr/formation/fiche-evenement/%s.html' % (num, ))
return event
def create_event_compet(d):
event = Event()
nom_lieu = tuple(d['Nom de la compétition Lieu'].stripped_strings)
dates = tuple(d['Date'].stripped_strings)
link = 'http://www.ffme.fr'+d['Nom de la compétition Lieu'].a.get('href')
event.add('summary', nom_lieu[0])
event.add('location', nom_lieu[1])
event.add('dtstart', datetime.strptime(dates[0], '%d/%m/%y').date())
if len(dates) > 1:
event.add('dtend', datetime.strptime(dates[1], '%d/%m/%y').date())
event.add('uid', "%s@competition.ffme.fr" % (''.join(( a for a in link if a.isdigit())),) )
event.add('description', link)
return event
cal = Calendar()
cal.add('prodid', '-//Calendrier formations FFME//ffme.fr//')
cal.add('version', '2.0')
cal.add("X-WR-CALNAME", "Calendrier formations FFME")
urls = ('http://www.ffme.fr/formation/calendrier-liste/FMT_ESCSAE.html',
'http://www.ffme.fr/formation/calendrier-liste/FMT_ESCSNE.html',
#'http://www.ffme.fr/formation/calendrier-liste/FMT_ESCFCINI.html',
'http://www.ffme.fr/formation/calendrier-liste/FMT_ESCMONESP.html',
)
for u in urls:
for d in scrape_url(u):
cal.add_component(create_event_formation(d))
with open('cal_formation.ics', 'w') as f:
f.write(cal.to_ical().decode('utf-8'))
cal = Calendar()
cal.add('prodid', '-//Calendrier compétitions FFME//ffme.fr//')
cal.add('version', '2.0')
cal.add("X-WR-CALNAME", "Calendrier compétitions FFME")
url = 'http://www.ffme.fr/competition/calendrier-liste.html?DISCIPLINE=ESC&CPT_FUTUR=1'
page = 1
while True:
data = scrape_url(url + "&page=" + repr(page))
if not data:
break
for d in data:
cal.add_component(create_event_compet(d))
page +=1
with open('cal_competition.ics', 'w') as f:
f.write(cal.to_ical().decode('utf-8'))
|
albatros69/Divers
|
scrap_ffme.py
|
Python
|
gpl-3.0
| 3,373 | 0.006235 |
import sys
if __name__ == "__main__":
# Parse command line arguments
if len(sys.argv) < 2:
sys.exit("python {} <datasetFilename> {{<maxPoints>}}".format(sys.argv[0]))
datasetFilename = sys.argv[1]
if len(sys.argv) >= 3:
maxPoints = int(sys.argv[2])
else:
maxPoints = None
# Perform initial pass through file to determine line count (i.e. # of points)
lineCount = 0
with open(datasetFilename, "r") as f:
line = f.readline()
while line:
lineCount += 1
line = f.readline()
# Read first line and use to make assumption about the dimensionality of each point
numDimensions = 0
with open(datasetFilename, "r") as f:
firstLine = f.readline()
numDimensions = len(firstLine.split())
# If dimensionality of dataset is 0, print error message and exit
if numDimensions == 0:
sys.exit("Could not determine dimensionality of dataset")
# Print initial header at END of file (so we have number of points already)
if maxPoints:
numPoints = min(lineCount, maxPoints)
else:
numPoints = lineCount
print("{} {}".format(numDimensions, numPoints))
# Output dataset header which defines dimensionality of data and number of points
# Read entire file line-by-line, printing out each line as a point
with open(datasetFilename, "r") as f:
pointsRead = 0
line = f.readline()
while line:
fields = line.split()
floatFields = [ str(float(x)) for x in fields ]
print(" ".join(floatFields))
# Stop reading file is maximum number of points have been read
pointsRead += 1
if maxPoints and pointsRead >= maxPoints:
break
# Read next line of file
line = f.readline()
|
DonaldWhyte/multidimensional-search-fyp
|
scripts/read_multifield_dataset.py
|
Python
|
mit
| 1,612 | 0.030397 |
'''
aima-ui project
=============
This is just a graphic user interface to test
agents for an AI college course.
'''
from kivy.uix.button import Button
from kivy.uix.togglebutton import ToggleButton
from kivy.uix.widget import Widget
from kivy.core.window import Window
from kivy.uix.label import Label
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.spinner import Spinner
from kivy.uix.popup import Popup
from kivy.uix.image import Image
from kivy.app import App
from kivy.clock import Clock
from kivy.graphics import Color, Rectangle
from functools import partial
from agent_dir.agents import *
import agent_list
import env_list
from os import path
ALL_AGENTS = agent_list.load_agents()
ALL_MAPS = env_list.get_maps()
def check_img(img_name):
"""Check if the image is in img dir of the agents."""
return path.isfile(path.join("agents_dir", path.join("img", img_name)))
def memoize(func):
"""Memoize decorator."""
memo = {}
def helper(*args):
"""Helper function for memoize paradigm."""
if args not in memo:
memo[args] = func(*args)
return memo[args]
return helper
@memoize
def gen_popup(type_, text, dismiss=True):
"""Generate a popup."""
popup_layout = BoxLayout(orientation='vertical')
content = Button(text='Dismiss', size_hint=(1, .3))
popup_layout.add_widget(Label(text=text))
popup = Popup(title=type_,
content=popup_layout)
if dismiss:
popup_layout.add_widget(content)
content.bind(on_press=popup.dismiss)
return popup
class AimaUI(App):
"""Class to manage aima agents and environments."""
def __init__(self):
"""Initialize the user interface."""
App.__init__(self)
self.scoreA = 0
self.scoreB = 0
self.agentA = "Agent A"
self.agentAImgDef = "img/agent_1.png"
self.agentAImg = None
self.agentB = "Agent B"
self.agentBImgDef = "img/agent_2.png"
self.agentBImg = None
self.wall_img = Image(source="img/wall.png")
# self.trash_img = Image(source="img/trash.png")
self.trash_img = Image(source="img/cake.png")
self.map = None
self.running = False
self.env = None
self.counter_steps = 0
self.initialized = False
def __initialize_env(self):
"""Initialize aima environment."""
if self.env is not None:
del self.env
self.env = None
if self.map is not None:
self.env = ALL_MAPS[self.map]()
if self.agentA in ALL_AGENTS:
agent_A = TraceAgent(ALL_AGENTS[self.agentA]())
if agent_A.img is not None and check_img(agent_A.img):
self.agentAImg = Image(
source=path.join("agents_dir", path.join("img", agent_A.img)))
else:
self.agentAImg = Image(source=self.agentAImgDef)
self.env.add_thing(agent_A, location=self.env.start_from)
if self.agentB in ALL_AGENTS:
agent_B = TraceAgent(ALL_AGENTS[self.agentB]())
if agent_B.img is not None and check_img(agent_B.img):
self.agentBImg = Image(
source=path.join("agents_dir", path.join("img", agent_B.img)))
else:
self.agentBImg = Image(source=self.agentBImgDef)
self.env.add_thing(agent_B, location=self.env.start_from)
def get_scores(self):
"""Get agents' scores."""
return ("ScoreA = {0:d}".format(self.scoreA),
"ScoreB = {0:d}".format(self.scoreB))
def update_canvas(self, labels, wid, *largs):
"""Update the canvas to respect the environment."""
wid.canvas.clear()
self.counter.text = str(self.counter_steps)
n_x, n_y = max([thing.location for thing in self.env.things])
tile_x = wid.width / float(n_x + 1)
tile_y = wid.height / float(n_y + 1)
labelA, labelB = labels
with wid.canvas:
for thing in [thing for thing in self.env.things
if isinstance(thing, Dirt) or
isinstance(thing, Clean)]:
pos_x, pos_y = thing.location
if isinstance(thing, Dirt):
Color(0.5, 0, 0)
Rectangle(
pos=(
pos_x * tile_x + wid.x,
pos_y * tile_y + wid.y),
size=(tile_x, tile_y))
Color(1, 1, 1, 1)
Rectangle(texture=self.trash_img.texture,
pos=(
pos_x * tile_x + wid.x,
pos_y * tile_y + wid.y
),
size=(tile_x, tile_y))
elif isinstance(thing, Clean):
Color(0.1, 0.5, 0.1)
Rectangle(
pos=(
pos_x * tile_x + wid.x,
pos_y * tile_y + wid.y),
size=(tile_x, tile_y))
for thing in [thing for thing in self.env.things
if isinstance(thing, Wall)]:
pos_x, pos_y = thing.location
Color(1, 1, 1, 1)
Rectangle(texture=self.wall_img.texture,
pos=(pos_x * tile_x + wid.x,
pos_y * tile_y + wid.y),
size=(tile_x, tile_y))
for thing in [thing for thing in self.env.things
if isinstance(thing, ALL_AGENTS.get(self.agentA, Agent)) or
isinstance(thing, ALL_AGENTS.get(self.agentB, Agent))]:
pos_x, pos_y = thing.location
if self.agentA in ALL_AGENTS and\
isinstance(thing, ALL_AGENTS[self.agentA]):
self.scoreA = thing.performance
labelA.text = self.get_scores()[0]
Color(1, 1, 1, 1)
Rectangle(texture=self.agentAImg.texture,
pos=(pos_x * tile_x + wid.x,
pos_y * tile_y + wid.y),
size=(tile_x, tile_y))
if self.agentB in ALL_AGENTS and\
isinstance(thing, ALL_AGENTS[self.agentB]):
self.scoreB = thing.performance
labelB.text = self.get_scores()[1]
Color(1, 1, 1, 1)
Rectangle(texture=self.agentBImg.texture,
pos=(pos_x * tile_x + wid.x,
pos_y * tile_y + wid.y),
size=(tile_x, tile_y))
def load_env(self, labels, wid, *largs):
"""Load and prepare the environment."""
self.running = False
self.counter_steps = 0
if self.map is None or self.map == "Maps":
gen_popup("Error!", "No map selected...").open()
return
elif self.agentA not in ALL_AGENTS and\
self.agentB not in ALL_AGENTS:
gen_popup("Error!", "You must choose at least one agent...").open()
return
self.__initialize_env()
self.initialized = True
self.update_canvas(labels, wid)
def running_step(self, labels, wid, n_step=None, *largs):
"""Run the program of the environment, called from run."""
if self.env is not None:
if n_step is not None:
if self.counter_steps == n_step:
self.running = False
self.btn_100step.state = "normal"
self.counter_steps = 0
return False
else:
self.counter_steps += 1
if not self.running:
return False
self.env.step()
self.update_canvas(labels, wid)
def btn_step(self, labels, wid, *largs):
"""Update the environment one step."""
if not self.initialized:
gen_popup("Error!", "You must load a map...").open()
return
elif self.agentA == "Agent A" and self.agentB == "Agent B":
popup = gen_popup(
"Error!", "Agent not selected, reset required...", False).open()
Clock.schedule_once(popup.dismiss, timeout=2)
Clock.schedule_once(self.partial_reset, timeout=2)
return
if self.env is not None:
self.env.step()
self.update_canvas(labels, wid)
def btn_100step(self, function, labels, wid, *largs):
"""Update the environment one step."""
if not self.initialized:
gen_popup("Error!", "You must load a map...").open()
self.btn_100step.state = "normal"
return
elif self.agentA == "Agent A" and self.agentB == "Agent B":
popup = gen_popup(
"Error!", "Agent not selected, reset required...", False).open()
Clock.schedule_once(popup.dismiss, timeout=2)
Clock.schedule_once(self.partial_reset, timeout=2)
self.btn_100step.state = "down"
self.running = True
Clock.schedule_interval(partial(function, labels, wid, 100), 1 / 30.)
def btn_run(self, function, labels, wid, *largs):
"""Run a function for the update."""
if not self.initialized:
gen_popup("Error!", "You must load a map...").open()
self.btn_run.state = "normal"
return
elif self.agentA == "Agent A" and self.agentB == "Agent B":
popup = gen_popup(
"Error!", "Agent not selected, reset required...", False).open()
Clock.schedule_once(popup.dismiss, timeout=2)
Clock.schedule_once(self.partial_reset, timeout=2)
self.btn_run.state = "down"
self.running = True
Clock.schedule_interval(partial(function, labels, wid), 1 / 30.)
def btn_stop(self, function, *largs):
"""Stop a specific fuction."""
if not self.initialized:
gen_popup("Error!", "You must load a map...").open()
return
elif self.agentA == "Agent A" and self.agentB == "Agent B":
popup = gen_popup(
"Error!", "Agent not selected, reset required...", False).open()
Clock.schedule_once(popup.dismiss, timeout=2)
Clock.schedule_once(self.partial_reset, timeout=2)
self.running = False
self.counter_steps = 0
self.btn_run.state = "normal"
self.btn_100step.state = "normal"
Clock.unschedule(function)
@staticmethod
def reset_popup(popup, *largs):
popup.dismiss()
gen_popup("INFO", "Reset done!!!").open()
def reset_all(self, labels, spinners, wid, *largs):
"""Clear the entire environment."""
popup = gen_popup("WARNING!", "I'm deleting everything!!!", False)
popup.open()
self.initialized = False
self.agentA = "Agent A"
self.agentB = "Agent B"
self.map = None
self.running = False
self.counter_steps = 0
self.scoreA = 0
self.scoreB = 0
self.__initialize_env()
wid.canvas.clear()
labelA, labelB = labels
labelA.text = self.get_scores()[0]
labelB.text = self.get_scores()[1]
reload(env_list)
reload(agent_list)
global ALL_AGENTS
global ALL_MAPS
ALL_AGENTS = agent_list.load_agents()
ALL_MAPS = env_list.ALL_MAPS
spinnerA, spinnerB, spinnerMap = spinners
spinnerA.values = sorted(
[agent for agent in list(ALL_AGENTS.keys())]) + ["Agent A"]
spinnerB.values = sorted(
[agent for agent in list(ALL_AGENTS.keys())]) + ["Agent B"]
spinnerMap.values = sorted(
[map for map in list(ALL_MAPS.keys())]) + ["Maps"]
spinnerA.text = "Agent A"
spinnerB.text = "Agent B"
spinnerMap.text = "Maps"
self.counter.text = str(self.counter_steps)
Clock.schedule_once(partial(self.reset_popup, popup), timeout=1)
def reload_agents(self, labels, spinners, wid, *largs):
"""Reload all agents classes."""
self.running = False
self.counter_steps = 0
self.scoreA = 0
self.scoreB = 0
labelA, labelB = labels
labelA.text = self.get_scores()[0]
labelB.text = self.get_scores()[1]
global ALL_AGENTS
global ALL_MAPS
ALL_AGENTS = agent_list.load_agents()
ALL_MAPS = env_list.ALL_MAPS
spinnerA, spinnerB, spinnerMap = spinners
spinnerA.values = sorted(
[agent for agent in list(ALL_AGENTS.keys())]) + ["Agent A"]
spinnerB.values = sorted(
[agent for agent in list(ALL_AGENTS.keys())]) + ["Agent B"]
spinnerMap.values = sorted(
[map for map in list(ALL_MAPS.keys())]) + ["Maps"]
self.counter.text = str(self.counter_steps)
self.__initialize_env()
self.initialized = True
self.update_canvas(labels, wid)
def on_resize(self, width, eight):
self.update_canvas()
def select_agent_A(self, spinner, text):
self.agentA = text
def select_agent_B(self, spinner, text):
self.agentB = text
def select_map(self, spinner, text):
self.map = text
def on_resize(self, width, eight, test):
if self.initialized:
Clock.schedule_once(
partial(self.update_canvas, self.labels, self.wid))
def build(self):
"""Build the user interface."""
wid = Widget()
self.counter = Label(text="0")
labelA = Label(text=self.get_scores()[0])
labelB = Label(text=self.get_scores()[1])
labels = (labelA, labelB)
self.labels = labels
self.wid = wid
tmp_agents = list(sorted([agent for agent in list(ALL_AGENTS.keys())]))
agentA_spinner = Spinner(
text='Agent A',
text_size=(95, None),
shorten=True,
values=tmp_agents + ["Agent A"]
)
agentB_spinner = Spinner(
text='Agent B',
text_size=(95, None),
shorten=True,
values=tmp_agents + ["Agent B"]
)
maps_spinner = Spinner(
text='Maps',
text_size=(95, None),
shorten=True,
values=list(sorted([map for map in list(ALL_MAPS.keys())])) + ["Maps"]
)
agentA_spinner.bind(text=self.select_agent_A)
agentB_spinner.bind(text=self.select_agent_B)
maps_spinner.bind(text=self.select_map)
btn_load = Button(text='Load',
on_press=partial(self.load_env, labels, wid))
btn_step = Button(text='Step >',
on_press=partial(self.btn_step, labels, wid))
self.btn_100step = ToggleButton(text='100 Step >',
on_press=partial(self.btn_100step,
self.running_step,
labels,
wid))
self.btn_run = ToggleButton(
text='Run >>', on_press=partial(self.btn_run,
self.running_step,
labels,
wid))
btn_stop = Button(text='Stop [ ]',
on_press=partial(self.btn_stop,
self.running_step))
self.partial_reset = partial(self.reset_all,
labels,
(agentA_spinner,
agentB_spinner, maps_spinner),
wid)
self.partial_reload = partial(self.reload_agents,
labels,
(agentA_spinner,
agentB_spinner, maps_spinner),
wid)
btn_reload = Button(text='Reload',
on_press=self.partial_reload)
btn_reset = Button(text='Reset',
on_press=self.partial_reset)
Window.bind(on_resize=self.on_resize)
action_layout = BoxLayout(size_hint=(1, None), height=50)
action_layout.add_widget(btn_load)
action_layout.add_widget(btn_step)
action_layout.add_widget(self.btn_100step)
action_layout.add_widget(self.counter)
action_layout.add_widget(self.btn_run)
action_layout.add_widget(btn_stop)
action_layout.add_widget(btn_reload)
action_layout.add_widget(btn_reset)
agents_layout = BoxLayout(size_hint=(1, None), height=50)
agents_layout.add_widget(agentA_spinner)
agents_layout.add_widget(labelA)
agents_layout.add_widget(agentB_spinner)
agents_layout.add_widget(labelB)
agents_layout.add_widget(maps_spinner)
root = BoxLayout(orientation='vertical')
root.add_widget(wid)
root.add_widget(action_layout)
root.add_widget(agents_layout)
return root
if __name__ == '__main__':
AimaUI().run()
|
valefranz/AI-Project-VacuumEnvironment
|
aima-ui-2a.py
|
Python
|
apache-2.0
| 17,529 | 0.000628 |
import socket
import string
from driver import driver
class WiFiMouseDriver(driver):
ACTION_KEYS = {
'TAB': 'TAB',
'ENTER': 'RTN',
'ESCAPE': 'ESC',
'PAGE_UP': 'PGUP',
'PAGE_DOWN': 'PGDN',
'END': 'END',
'HOME': 'HOME',
'LEFT': 'LF',
'UP': 'UP',
'RIGHT': 'RT',
'DOWN': 'DW',
'BACK_SPACE': 'BAS',
'F1': 'F1',
'F2': 'F2',
'F3': 'F3',
'F4': 'F4',
'F5': 'F5',
'F6': 'F6',
'F7': 'F7',
'F8': 'F8',
'F9': 'F9',
'F10': 'F10',
'F11': 'F11',
'F12': 'F12',
'CONTROL': 'CTRL',
'ALT': 'ALT',
'SHIFT': 'SHIFT',
}
SERVER_PORT = 1978
def __init__(self, ip):
self._ip = ip
self._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self._socket.connect((ip, WiFiMouseDriver.SERVER_PORT))
self._socket.setblocking(1)
def _send(self, data):
print "sending: " + data
self._socket.send(data)
def left_click(self):
self._send("mos 1c")
return self
def right_click(self):
self._send("mos 5R r d")
self._send("mos 5R r u")
return self
def move_mouse(self, deltaX, deltaY):
# maximum movement is 99 in any direction
currX = deltaX
if deltaX > 0:
while currX > 0:
moveX = min(currX, 99)
self._send("mos " + str(len(str(moveX)) + len(str(0)) + 3) + "m " + str(moveX) + " " + str(0))
currX -= moveX
elif deltaX < 0:
while currX < 0:
moveX = max(currX, -99)
self._send("mos " + str(len(str(moveX)) + len(str(0)) + 3) + "m " + str(moveX) + " " + str(0))
currX -= moveX
currY = deltaY
if deltaY > 0:
while currY > 0:
moveY = min(currY, 99)
self._send("mos " + str(len(str(0)) + len(str(moveY)) + 3) + "m " + str(0) + " " + str(moveY))
currY -= moveY
elif deltaY < 0:
while currY < 0:
moveY = max(currY, -99)
self._send("mos " + str(len(str(0)) + len(str(moveY)) + 3) + "m " + str(0) + " " + str(moveY))
currY -= moveY
return self
def typeText(self, text):
format = "key "
for char in text:
self._send(format + str(len(char)) + char)
return self
def press_action_key(self, name, shift=False, ctrl=False, alt=False):
if name not in WiFiMouseDriver.ACTION_KEYS:
raise ValueError('Unknown action key name: %s' % name)
format = "key "
command = str(WiFiMouseDriver.ACTION_KEYS[name])
self._send(format + str(len(command)) + command)
return self
def close(self):
self._socket.close()
|
obi1kenobi/pyre
|
WiFiMouse/wifimouse_driver.py
|
Python
|
mit
| 2,923 | 0.002053 |
"""
Authenication and Authorization tests which require DC/OS Enterprise.
Currently test against root marathon. Assume we will want to test these
against MoM EE
"""
import common
import dcos
import pytest
import shakedown
from urllib.parse import urljoin
from dcos import marathon
from shakedown import credentials, ee_version
@pytest.mark.skipif("ee_version() is None")
@pytest.mark.usefixtures('credentials')
def test_non_authenicated_user():
with shakedown.no_user():
with pytest.raises(dcos.errors.DCOSAuthenticationException) as exec_info:
response = dcos.http.get(urljoin(shakedown.dcos_url(), 'service/marathon/v2/apps'))
error = exc_info.value
assert str(error) == "Authentication failed. Please run `dcos auth login`"
@pytest.mark.skipif("ee_version() is None")
@pytest.mark.usefixtures('credentials')
def test_non_authorized_user():
with shakedown.new_dcos_user('kenny', 'kenny'):
with pytest.raises(dcos.errors.DCOSAuthorizationException) as exec_info:
response = dcos.http.get(urljoin(shakedown.dcos_url(), 'service/marathon/v2/apps'))
error = exc_info.value
assert str(error) == "You are not authorized to perform this operation"
@pytest.fixture(scope="function")
def billy():
shakedown.add_user('billy', 'billy')
shakedown.set_user_permission(rid='dcos:adminrouter:service:marathon', uid='billy', action='full')
shakedown.set_user_permission(rid='dcos:service:marathon:marathon:services:/', uid='billy', action='full')
yield
shakedown.remove_user_permission(rid='dcos:adminrouter:service:marathon', uid='billy', action='full')
shakedown.remove_user_permission(rid='dcos:service:marathon:marathon:services:/', uid='billy', action='full')
shakedown.remove_user('billy')
@pytest.mark.skipif("ee_version() is None")
@pytest.mark.usefixtures('credentials')
def test_authorized_non_super_user(billy):
with shakedown.dcos_user('billy', 'billy'):
client = marathon.create_client()
len(client.get_apps()) == 0
|
Caerostris/marathon
|
tests/system/marathon_auth_common_tests.py
|
Python
|
apache-2.0
| 2,070 | 0.004831 |
import xml.etree.ElementTree as etree
import base64
from struct import unpack, pack
import sys
import io
import os
import time
import itertools
import xbmcaddon
import xbmc
import urllib2,urllib
import traceback
import urlparse
import posixpath
import re
import socket
from flvlib import tags
from flvlib import helpers
from flvlib.astypes import MalformedFLV
import zlib
from StringIO import StringIO
import hmac
import hashlib
import base64
addon_id = 'plugin.video.israelive'
selfAddon = xbmcaddon.Addon(id=addon_id)
__addonname__ = selfAddon.getAddonInfo('name')
__icon__ = selfAddon.getAddonInfo('icon')
downloadPath = xbmc.translatePath(selfAddon.getAddonInfo('profile'))#selfAddon["profile"])
#F4Mversion=''
class interalSimpleDownloader():
outputfile =''
clientHeader=None
def __init__(self):
self.init_done=False
def thisme(self):
return 'aaaa'
def openUrl(self,url, ischunkDownloading=False):
try:
post=None
openner = urllib2.build_opener(urllib2.HTTPHandler, urllib2.HTTPSHandler)
if post:
req = urllib2.Request(url, post)
else:
req = urllib2.Request(url)
ua_header=False
if self.clientHeader:
for n,v in self.clientHeader:
req.add_header(n,v)
if n=='User-Agent':
ua_header=True
if not ua_header:
req.add_header('User-Agent','Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.154 Safari/537.36')
#response = urllib2.urlopen(req)
if self.proxy and ( (not ischunkDownloading) or self.use_proxy_for_chunks ):
req.set_proxy(self.proxy, 'http')
response = openner.open(req)
return response
except:
#print 'Error in getUrl'
traceback.print_exc()
return None
def getUrl(self,url, ischunkDownloading=False):
try:
post=None
openner = urllib2.build_opener(urllib2.HTTPHandler, urllib2.HTTPSHandler)
if post:
req = urllib2.Request(url, post)
else:
req = urllib2.Request(url)
ua_header=False
if self.clientHeader:
for n,v in self.clientHeader:
req.add_header(n,v)
if n=='User-Agent':
ua_header=True
if not ua_header:
req.add_header('User-Agent','Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.154 Safari/537.36')
#response = urllib2.urlopen(req)
if self.proxy and ( (not ischunkDownloading) or self.use_proxy_for_chunks ):
req.set_proxy(self.proxy, 'http')
response = openner.open(req)
data=response.read()
return data
except:
#print 'Error in getUrl'
traceback.print_exc()
return None
def init(self, out_stream, url, proxy=None,g_stopEvent=None, maxbitRate=0):
try:
self.init_done=False
self.init_url=url
self.clientHeader=None
self.status='init'
self.proxy = proxy
self.maxbitRate=maxbitRate
if self.proxy and len(self.proxy)==0:
self.proxy=None
self.out_stream=out_stream
self.g_stopEvent=g_stopEvent
if '|' in url:
sp = url.split('|')
url = sp[0]
self.clientHeader = sp[1]
self.clientHeader= urlparse.parse_qsl(self.clientHeader)
#print 'header recieved now url and headers are',url, self.clientHeader
self.status='init done'
self.url=url
#self.downloadInternal( url)
return True
#os.remove(self.outputfile)
except:
traceback.print_exc()
self.status='finished'
return False
def keep_sending_video(self,dest_stream, segmentToStart=None, totalSegmentToSend=0):
try:
self.status='download Starting'
self.downloadInternal(self.url,dest_stream)
except:
traceback.print_exc()
self.status='finished'
def downloadInternal(self,url,dest_stream):
try:
url=self.url
fileout=dest_stream
self.status='bootstrap done'
while True:
response=self.openUrl(url)
buf="start"
firstBlock=True
try:
while (buf != None and len(buf) > 0):
if self.g_stopEvent and self.g_stopEvent.isSet():
return
buf = response.read(200 * 1024)
fileout.write(buf)
#print 'writing something..............'
fileout.flush()
try:
if firstBlock:
firstBlock=False
if self.maxbitRate and self.maxbitRate>0:# this is for being sports for time being
#print 'maxbitrate',self.maxbitRate
ec=EdgeClass(buf,url,'http://www.en.beinsports.net/i/PerformConsole_BEIN/player/bin-release/PerformConsole.swf',sendToken=False)
ec.switchStream(self.maxbitRate,"DOWN")
except:
traceback.print_exc()
response.close()
fileout.close()
#print time.asctime(), "Closing connection"
except socket.error, e:
#print time.asctime(), "Client Closed the connection."
try:
response.close()
fileout.close()
except Exception, e:
return
except Exception, e:
traceback.print_exc(file=sys.stdout)
response.close()
fileout.close()
except:
traceback.print_exc()
return
class EdgeClass():
def __init__(self, data, url, swfUrl, sendToken=False, switchStream=None):
self.url = url
self.swfUrl = swfUrl
self.domain = self.url.split('://')[1].split('/')[0]
self.control = 'http://%s/control/' % self.domain
self.onEdge = self.extractTags(data,onEdge=True)
self.sessionID=self.onEdge['session']
self.path=self.onEdge['streamName']
#print 'session',self.onEdge['session']
#print 'Edge variable',self.onEdge
#print 'self.control',self.control
#self.MetaData = self.extractTags(data,onMetaData=True)
if sendToken:
self.sendNewToken(self.onEdge['session'],self.onEdge['streamName'],self.swfUrl,self.control)
def getURL(self, url, post=False, sessionID=False, sessionToken=False):
try:
#print 'GetURL --> url = '+url
opener = urllib2.build_opener()
if sessionID and sessionToken:
opener.addheaders = [('User-Agent', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.7; rv:14.0) Gecko/20100101 Firefox/14.0.1' ),
('x-Akamai-Streaming-SessionToken', sessionToken ),
('x-Akamai-Streaming-SessionID', sessionID ),
('Content-Type', 'text/xml' )]
elif sessionID:
opener.addheaders = [('User-Agent', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.7; rv:14.0) Gecko/20100101 Firefox/14.0.1' ),
('x-Akamai-Streaming-SessionID', sessionID ),
('Content-Type', 'text/xml' )]
else:
opener.addheaders = [('User-Agent', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.7; rv:14.0) Gecko/20100101 Firefox/14.0.1' )]
if not post:
usock=opener.open(url)
else:
usock=opener.open(url,':)')
response=usock.read()
usock.close()
except urllib2.URLError, e:
#print 'Error reason: ', e
return False
else:
return response
def extractTags(self, filedata, onEdge=True,onMetaData=False):
f = StringIO(filedata)
flv = tags.FLV(f)
try:
tag_generator = flv.iter_tags()
for i, tag in enumerate(tag_generator):
if isinstance(tag, tags.ScriptTag):
if tag.name == "onEdge" and onEdge:
return tag.variable
elif tag.name == "onMetaData" and onMetaData:
return tag.variable
except MalformedFLV, e:
return False
except tags.EndOfFile:
return False
f.close()
return False
def decompressSWF(self,f):
if type(f) is str:
f = StringIO(f)
f.seek(0, 0)
magic = f.read(3)
if magic == "CWS":
return "FWS" + f.read(5) + zlib.decompress(f.read())
elif magic == "FWS":
#SWF Not Compressed
f.seek(0, 0)
return f.read()
else:
#Not SWF
return None
def MD5(self,data):
m = hashlib.md5()
m.update(data)
return m.digest()
def makeToken(self,sessionID,swfUrl):
swfData = self.getURL(swfUrl)
decData = self.decompressSWF(swfData)
swfMD5 = self.MD5(decData)
data = sessionID+swfMD5
sig = hmac.new('foo', data, hashlib.sha1)
return base64.encodestring(sig.digest()).replace('\n','')
def sendNewToken(self,sessionID,path,swf,domain):
sessionToken = self.makeToken(sessionID,swf)
commandUrl = domain+path+'?cmd=sendingNewToken&v=2.7.6&swf='+swf.replace('http://','http%3A//')
self.getURL(commandUrl,True,sessionID,sessionToken)
def switchStream(self, bitrate, upDown="UP"):
newStream=self.path
#print 'newStream before ',newStream
newStream=re.sub('_[0-9]*@','_'+str(bitrate)+'@',newStream)
#print 'newStream after ',newStream,bitrate
sessionToken =None# self.makeToken(sessionID,swf)
commandUrl = self.control+newStream+'?cmd=&reason=SWITCH_'+upDown+',1784,1000,1.3,2,'+self.path+'v=2.11.3'
self.getURL(commandUrl,True,self.sessionID,sessionToken)
|
noam09/kodi
|
script.module.israeliveresolver/lib/interalSimpleDownloader.py
|
Python
|
gpl-3.0
| 10,978 | 0.017216 |
# coding: utf-8
# Copyright 2017 Solthis.
#
# This file is part of Fugen 2.0.
#
# Fugen 2.0 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.
#
# Fugen 2.0 is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Fugen 2.0. If not, see <http://www.gnu.org/licenses/>.
import pandas as pd
from dateutil.relativedelta import relativedelta
from data.indicators.patient_indicator import PatientIndicator
from data.indicators.lost_patients import LostPatients
from data.indicators.arv_started_patients import ArvStartedPatients
from data.indicators.dead_patients import ArvDeadPatientsDuringPeriod
from data.indicators.transferred_patients import ArvTransferredPatientsDuringPeriod
from utils import getFirstDayOfPeriod, getLastDayOfPeriod
class ArvLostBackPatients(PatientIndicator):
def under_arv(self):
return False
@classmethod
def get_key(cls):
return "ARV_LOST_BACK"
@classmethod
def get_display_label(cls):
return "Perdus de vue de retour dans le TARV"
def filter_patients_dataframe(self, limit_date, start_date=None,
include_null_dates=False):
lost_prev = LostPatients(self.fuchia_database)
arv_started = ArvStartedPatients(self.fuchia_database)
n_limit = limit_date - relativedelta(months=1)
n_start = start_date - relativedelta(months=1)
i = (lost_prev & arv_started)
prev_lost_patients = i.get_filtered_patients_dataframe(
getLastDayOfPeriod(n_limit.month, n_limit.year),
start_date=getFirstDayOfPeriod(n_start.month, n_start.year),
include_null_dates=include_null_dates
)
visits = self.filter_visits_by_category(
limit_date,
start_date=None,
include_null_dates=include_null_dates
)
c1 = (visits['visit_date'] >= start_date)
c2 = (visits['visit_date'] <= limit_date)
visits = visits[c1 & c2]
seen_id = pd.Index(visits['patient_id'].unique())
# Arv dead during the period must be re-included
arv_dead = ArvDeadPatientsDuringPeriod(self.fuchia_database)
dead = arv_dead.get_filtered_patients_dataframe(
limit_date,
start_date=start_date,
include_null_dates=include_null_dates
)
seen_id = seen_id.union(dead.index)
# Transferred during the period must be re-included
arv_trans = ArvTransferredPatientsDuringPeriod(self.fuchia_database)
trans = arv_trans.get_filtered_patients_dataframe(
limit_date,
start_date=start_date,
include_null_dates=include_null_dates
)
seen_id = seen_id.union(trans.index)
n_index = prev_lost_patients.index.intersection(seen_id)
return prev_lost_patients.loc[n_index], None
|
Solthis/Fugen-2.0
|
data/indicators/lost_back_patients.py
|
Python
|
gpl-3.0
| 3,277 | 0.000305 |
from collections import namedtuple, OrderedDict
from functools import wraps
from queue import Queue
import os
import shutil
import threading
from plover import log, system
from plover.dictionary.loading_manager import DictionaryLoadingManager
from plover.exception import DictionaryLoaderException
from plover.formatting import Formatter
from plover.misc import shorten_path
from plover.registry import registry
from plover.resource import ASSET_SCHEME, resource_filename
from plover.steno import Stroke
from plover.steno_dictionary import StenoDictionary, StenoDictionaryCollection
from plover.suggestions import Suggestions
from plover.translation import Translator
class StartingStrokeState(namedtuple('StartingStrokeState', 'attach capitalize space_char')):
def __new__(cls, attach=False, capitalize=False, space_char=' '):
return super().__new__(cls, attach, capitalize, space_char)
MachineParams = namedtuple('MachineParams', 'type options keymap')
class ErroredDictionary(StenoDictionary):
""" Placeholder for dictionaries that failed to load. """
def __init__(self, path, exception):
super().__init__()
self.enabled = False
self.readonly = True
self.path = path
self.exception = exception
def __eq__(self, other):
if not isinstance(other, ErroredDictionary):
return False
return (self.path, self.exception) == (other.path, other.exception)
def copy_default_dictionaries(dictionaries_files):
'''Recreate default dictionaries.
Each default dictionary is recreated if it's
in use by the current config and missing.
'''
for dictionary in dictionaries_files:
# Ignore assets.
if dictionary.startswith(ASSET_SCHEME):
continue
# Nothing to do if dictionary file already exists.
if os.path.exists(dictionary):
continue
# Check it's actually a default dictionary.
basename = os.path.basename(dictionary)
if basename not in system.DEFAULT_DICTIONARIES:
continue
default_dictionary = os.path.join(system.DICTIONARIES_ROOT, basename)
log.info('recreating %s from %s', dictionary, default_dictionary)
shutil.copyfile(resource_filename(default_dictionary), dictionary)
def with_lock(func):
# To keep __doc__/__name__ attributes of the initial function.
@wraps(func)
def _with_lock(self, *args, **kwargs):
with self:
return func(self, *args, **kwargs)
return _with_lock
class StenoEngine:
HOOKS = '''
stroked
translated
machine_state_changed
output_changed
config_changed
dictionaries_loaded
send_string
send_backspaces
send_key_combination
add_translation
focus
configure
lookup
suggestions
quit
'''.split()
def __init__(self, config, controller, keyboard_emulation):
self._config = config
self._controller = controller
self._is_running = False
self._queue = Queue()
self._lock = threading.RLock()
self._machine = None
self._machine_state = None
self._machine_params = MachineParams(None, None, None)
self._formatter = Formatter()
self._formatter.set_output(Formatter.output_type(
self._send_backspaces,
self._send_string,
self._send_key_combination,
self._send_engine_command,
))
self._formatter.add_listener(self._on_translated)
self._translator = Translator()
self._translator.add_listener(log.translation)
self._translator.add_listener(self._formatter.format)
self._dictionaries = self._translator.get_dictionary()
self._dictionaries_manager = DictionaryLoadingManager()
self._running_state = self._translator.get_state()
self._keyboard_emulation = keyboard_emulation
self._hooks = { hook: [] for hook in self.HOOKS }
self._running_extensions = {}
def __enter__(self):
self._lock.__enter__()
return self
def __exit__(self, exc_type, exc_value, traceback):
self._lock.__exit__(exc_type, exc_value, traceback)
def _in_engine_thread(self):
raise NotImplementedError()
def _same_thread_hook(self, func, *args, **kwargs):
if self._in_engine_thread():
func(*args, **kwargs)
else:
self._queue.put((func, args, kwargs))
def run(self):
while True:
func, args, kwargs = self._queue.get()
try:
with self._lock:
if func(*args, **kwargs):
break
except Exception:
log.error('engine %s failed', func.__name__[1:], exc_info=True)
def _on_control_message(self, msg):
if msg[0] == 'command':
self._same_thread_hook(self._execute_engine_command,
*msg[1:], force=True)
else:
log.error('ignoring invalid control message: %r', msg)
def _stop(self):
self._controller.stop()
self._stop_extensions(self._running_extensions.keys())
if self._machine is not None:
self._machine.stop_capture()
self._machine = None
def _start(self):
self._set_output(self._config['auto_start'])
self._update(full=True)
self._controller.start(self._on_control_message)
def _set_dictionaries(self, dictionaries):
def dictionaries_changed(l1, l2):
if len(l1) != len(l2):
return True
for d1, d2 in zip(l1, l2):
if d1 is not d2:
return True
return False
if not dictionaries_changed(dictionaries, self._dictionaries.dicts):
# No change.
return
self._dictionaries = StenoDictionaryCollection(dictionaries)
self._translator.set_dictionary(self._dictionaries)
self._trigger_hook('dictionaries_loaded', self._dictionaries)
def _update(self, config_update=None, full=False, reset_machine=False):
original_config = self._config.as_dict()
# Update configuration.
if config_update is not None:
self._config.update(**config_update)
config = self._config.as_dict()
else:
config = original_config
# Create configuration update.
if full:
config_update = config
else:
config_update = {
option: value
for option, value in config.items()
if value != original_config[option]
}
# Save config if anything changed.
if config_update:
self._config.save()
# Update logging.
log.set_stroke_filename(config['log_file_name'])
log.enable_stroke_logging(config['enable_stroke_logging'])
log.enable_translation_logging(config['enable_translation_logging'])
# Update output.
self._formatter.set_space_placement(config['space_placement'])
self._formatter.start_attached = config['start_attached']
self._formatter.start_capitalized = config['start_capitalized']
self._translator.set_min_undo_length(config['undo_levels'])
# Update system.
system_name = config['system_name']
if system.NAME != system_name:
log.info('loading system: %s', system_name)
system.setup(system_name)
# Update machine.
update_keymap = False
start_machine = False
machine_params = MachineParams(config['machine_type'],
config['machine_specific_options'],
config['system_keymap'])
# Do not reset if only the keymap changed.
if self._machine_params is None or \
self._machine_params.type != machine_params.type or \
self._machine_params.options != machine_params.options:
reset_machine = True
if reset_machine:
if self._machine is not None:
self._machine.stop_capture()
self._machine = None
machine_class = registry.get_plugin('machine', machine_params.type).obj
log.info('setting machine: %s', machine_params.type)
self._machine = machine_class(machine_params.options)
self._machine.set_suppression(self._is_running)
self._machine.add_state_callback(self._machine_state_callback)
self._machine.add_stroke_callback(self._machine_stroke_callback)
self._machine_params = machine_params
update_keymap = True
start_machine = True
elif self._machine is not None:
update_keymap = 'system_keymap' in config_update
if update_keymap:
machine_keymap = config['system_keymap']
if machine_keymap is not None:
self._machine.set_keymap(machine_keymap)
if start_machine:
self._machine.start_capture()
# Update running extensions.
enabled_extensions = config['enabled_extensions']
running_extensions = set(self._running_extensions)
self._stop_extensions(running_extensions - enabled_extensions)
self._start_extensions(enabled_extensions - running_extensions)
# Trigger `config_changed` hook.
if config_update:
self._trigger_hook('config_changed', config_update)
# Update dictionaries.
config_dictionaries = OrderedDict(
(d.path, d)
for d in config['dictionaries']
)
copy_default_dictionaries(config_dictionaries.keys())
# Start by unloading outdated dictionaries.
self._dictionaries_manager.unload_outdated()
self._set_dictionaries([
d for d in self._dictionaries.dicts
if d.path in config_dictionaries and \
d.path in self._dictionaries_manager
])
# And then (re)load all dictionaries.
dictionaries = []
for result in self._dictionaries_manager.load(config_dictionaries.keys()):
if isinstance(result, DictionaryLoaderException):
d = ErroredDictionary(result.path, result.exception)
# Only show an error if it's new.
if d != self._dictionaries.get(result.path):
log.error('loading dictionary `%s` failed: %s',
shorten_path(result.path), str(result.exception))
else:
d = result
d.enabled = config_dictionaries[d.path].enabled
dictionaries.append(d)
self._set_dictionaries(dictionaries)
def _start_extensions(self, extension_list):
for extension_name in extension_list:
log.info('starting `%s` extension', extension_name)
try:
extension = registry.get_plugin('extension', extension_name).obj(self)
except KeyError:
# Plugin not installed, skip.
continue
try:
extension.start()
except Exception:
log.error('initializing extension `%s` failed', extension_name, exc_info=True)
else:
self._running_extensions[extension_name] = extension
def _stop_extensions(self, extension_list):
for extension_name in list(extension_list):
log.info('stopping `%s` extension', extension_name)
extension = self._running_extensions.pop(extension_name)
extension.stop()
del extension
def _quit(self, code):
self._stop()
self.code = code
self._trigger_hook('quit')
return True
def _toggle_output(self):
self._set_output(not self._is_running)
def _set_output(self, enabled):
if enabled == self._is_running:
return
self._is_running = enabled
if enabled:
self._translator.set_state(self._running_state)
else:
self._translator.clear_state()
if self._machine is not None:
self._machine.set_suppression(enabled)
self._trigger_hook('output_changed', enabled)
def _machine_state_callback(self, machine_state):
self._same_thread_hook(self._on_machine_state_changed, machine_state)
def _machine_stroke_callback(self, steno_keys):
self._same_thread_hook(self._on_stroked, steno_keys)
@with_lock
def _on_machine_state_changed(self, machine_state):
assert machine_state is not None
self._machine_state = machine_state
self._trigger_hook('machine_state_changed', self._machine_params.type, machine_state)
def _consume_engine_command(self, command, force=False):
# The first commands can be used whether plover has output enabled or not.
command_name, *command_args = command.split(':', 1)
command_name = command_name.lower()
if command_name == 'resume':
self._set_output(True)
return True
elif command_name == 'toggle':
self._toggle_output()
return True
elif command_name == 'quit':
self.quit()
return True
if not force and not self._is_running:
return False
# These commands can only be run when plover has output enabled.
if command_name == 'suspend':
self._set_output(False)
elif command_name == 'configure':
self._trigger_hook('configure')
elif command_name == 'focus':
self._trigger_hook('focus')
elif command_name == 'add_translation':
self._trigger_hook('add_translation')
elif command_name == 'lookup':
self._trigger_hook('lookup')
elif command_name == 'suggestions':
self._trigger_hook('suggestions')
else:
command_fn = registry.get_plugin('command', command_name).obj
command_fn(self, command_args[0] if command_args else '')
return False
def _execute_engine_command(self, command, force=False):
self._consume_engine_command(command, force=force)
return False
def _on_stroked(self, steno_keys):
stroke = Stroke(steno_keys)
log.stroke(stroke)
self._translator.translate(stroke)
self._trigger_hook('stroked', stroke)
def _on_translated(self, old, new):
if not self._is_running:
return
self._trigger_hook('translated', old, new)
def _send_backspaces(self, b):
if not self._is_running:
return
self._keyboard_emulation.send_backspaces(b)
self._trigger_hook('send_backspaces', b)
def _send_string(self, s):
if not self._is_running:
return
self._keyboard_emulation.send_string(s)
self._trigger_hook('send_string', s)
def _send_key_combination(self, c):
if not self._is_running:
return
self._keyboard_emulation.send_key_combination(c)
self._trigger_hook('send_key_combination', c)
def _send_engine_command(self, command):
suppress = not self._is_running
suppress &= self._consume_engine_command(command)
if suppress:
self._machine.suppress_last_stroke(self._keyboard_emulation.send_backspaces)
def toggle_output(self):
self._same_thread_hook(self._toggle_output)
def set_output(self, enabled):
self._same_thread_hook(self._set_output, enabled)
@property
@with_lock
def machine_state(self):
return self._machine_state
@property
@with_lock
def output(self):
return self._is_running
@output.setter
def output(self, enabled):
self._same_thread_hook(self._set_output, enabled)
@property
@with_lock
def config(self):
return self._config.as_dict()
@config.setter
def config(self, update):
self._same_thread_hook(self._update, config_update=update)
@with_lock
def __getitem__(self, setting):
return self._config[setting]
def __setitem__(self, setting, value):
self.config = {setting: value}
def reset_machine(self):
self._same_thread_hook(self._update, reset_machine=True)
def load_config(self):
try:
self._config.load()
except Exception:
log.error('loading configuration failed, resetting to default', exc_info=True)
self._config.clear()
return False
return True
def start(self):
self._same_thread_hook(self._start)
def quit(self, code=0):
# We need to go through the queue, even when already called
# from the engine thread so _quit's return code does break
# the thread out of its main loop.
self._queue.put((self._quit, (code,), {}))
def restart(self):
self.quit(-1)
def join(self):
return self.code
@with_lock
def lookup(self, translation):
return self._dictionaries.lookup(translation)
@with_lock
def raw_lookup(self, translation):
return self._dictionaries.raw_lookup(translation)
@with_lock
def lookup_from_all(self, translation):
return self._dictionaries.lookup_from_all(translation)
@with_lock
def raw_lookup_from_all(self, translation):
return self._dictionaries.raw_lookup_from_all(translation)
@with_lock
def reverse_lookup(self, translation):
matches = self._dictionaries.reverse_lookup(translation)
return [] if matches is None else matches
@with_lock
def casereverse_lookup(self, translation):
matches = self._dictionaries.casereverse_lookup(translation)
return set() if matches is None else matches
@with_lock
def add_dictionary_filter(self, dictionary_filter):
self._dictionaries.add_filter(dictionary_filter)
@with_lock
def remove_dictionary_filter(self, dictionary_filter):
self._dictionaries.remove_filter(dictionary_filter)
@with_lock
def get_suggestions(self, translation):
return Suggestions(self._dictionaries).find(translation)
@property
@with_lock
def translator_state(self):
return self._translator.get_state()
@translator_state.setter
@with_lock
def translator_state(self, state):
self._translator.set_state(state)
@with_lock
def clear_translator_state(self, undo=False):
if undo:
state = self._translator.get_state()
self._formatter.format(state.translations, (), None)
self._translator.clear_state()
@property
@with_lock
def starting_stroke_state(self):
return StartingStrokeState(self._formatter.start_attached,
self._formatter.start_capitalized,
self._formatter.space_char)
@starting_stroke_state.setter
@with_lock
def starting_stroke_state(self, state):
self._formatter.start_attached = state.attach
self._formatter.start_capitalized = state.capitalize
self._formatter.space_char = state.space_char
@with_lock
def add_translation(self, strokes, translation, dictionary_path=None):
if dictionary_path is None:
dictionary_path = self._dictionaries.first_writable().path
self._dictionaries.set(strokes, translation, path=dictionary_path)
self._dictionaries.save(path_list=(dictionary_path,))
@property
@with_lock
def dictionaries(self):
return self._dictionaries
# Hooks.
def _trigger_hook(self, hook, *args, **kwargs):
for callback in self._hooks[hook]:
try:
callback(*args, **kwargs)
except Exception:
log.error('hook %r callback %r failed',
hook, callback,
exc_info=True)
@with_lock
def hook_connect(self, hook, callback):
self._hooks[hook].append(callback)
@with_lock
def hook_disconnect(self, hook, callback):
self._hooks[hook].remove(callback)
|
openstenoproject/plover
|
plover/engine.py
|
Python
|
gpl-2.0
| 20,307 | 0.00064 |
import ast
from collections import defaultdict
from contextlib import ExitStack, contextmanager
from functools import singledispatch
from typing import Any, Dict, Iterable, List, Optional, Set, Tuple, Union
from breakfast.position import Position
from breakfast.source import Source
from tests import make_source
QualifiedName = Tuple[str, ...]
class Node:
def __init__(self, parent: Optional["Node"]):
self.parent = parent
self.children: Dict[str, "Node"] = defaultdict(lambda: Node(parent=self))
self.occurrences: Set[Position] = set()
self.is_class = False
def add_occurrence(self, occurrence: Any):
self.occurrences.add(occurrence)
def __getitem__(self, name: str) -> "Node":
return self.children[name]
def __contains__(self, name: str) -> bool:
return name in self.children
def alias(self, other: "Node") -> None:
for name, value in other.children.items():
if name not in self.children:
self.children[name] = value
else:
self.children[name].alias(value)
other.children = self.children
self.occurrences |= other.occurrences
other.occurrences = self.occurrences
def flatten(
self,
prefix: Tuple[str, ...] = tuple(),
seen: Optional[Set[Position]] = None,
) -> Dict[Tuple[str, ...], List[Tuple[int, int]]]:
if not seen:
seen = set()
result = {}
next_values = []
for key, value in self.children.items():
new_prefix = prefix + (key,)
if value.occurrences:
occurrence = next(iter(value.occurrences))
if occurrence in seen:
continue
positions = [(o.row, o.column) for o in value.occurrences]
result[new_prefix] = positions
seen |= value.occurrences
next_values.append((new_prefix, value))
for new_prefix, value in next_values:
result.update(value.flatten(prefix=new_prefix, seen=seen))
return result
class State:
def __init__(self, position: Position):
self.position = position
self.root = Node(parent=None)
self.current_node = self.root
self.current_path: QualifiedName = tuple()
self.lookup_scopes = [self.root]
self.found: Optional[Node] = None
@contextmanager
def scope(self, name: str, lookup_scope: bool = False, is_class: bool = False):
previous_node = self.current_node
self.current_node = self.current_node[name]
self.current_node.is_class = is_class
if lookup_scope:
self.lookup_scopes.append(self.current_node)
self.current_path += (name,)
yield
self.current_node = previous_node
self.current_path = self.current_path[:-1]
if lookup_scope:
self.lookup_scopes.pop()
def add_occurrence(self, *, position: Optional[Position] = None) -> None:
if position:
self.current_node.occurrences.add(position)
if position == self.position:
self.found = self.current_node
print(
f"{self.current_path}: {[(o.row,o.column) for o in self.current_node.occurrences]}"
)
def alias(self, path: QualifiedName) -> None:
other_node = self.current_node
for name in path:
if name == "..":
if other_node.parent:
other_node = other_node.parent
else:
other_node = other_node[name]
self.current_node.alias(other_node)
def node_position(
node: ast.AST, source: Source, row_offset=0, column_offset=0
) -> Position:
return source.position(
row=(node.lineno - 1) + row_offset, column=node.col_offset + column_offset
)
def generic_visit(node: ast.AST, source: Source, state: State) -> None:
"""Called if no explicit visitor function exists for a node.
Adapted from NodeVisitor in:
https://github.com/python/cpython/blob/master/Lib/ast.py
"""
for _, value in ast.iter_fields(node):
if isinstance(value, list):
for item in value:
if isinstance(item, ast.AST):
visit(item, source, state)
elif isinstance(value, ast.AST):
visit(value, source, state)
@singledispatch
def visit(node: ast.AST, source: Source, state: State) -> None:
generic_visit(node, source, state)
@visit.register
def visit_module(node: ast.Module, source: Source, state: State) -> None:
with state.scope(source.module_name):
with state.scope(".", lookup_scope=True):
generic_visit(node, source, state)
@visit.register
def visit_name(node: ast.Name, source: Source, state: State) -> None:
position = node_position(node, source)
if isinstance(node.ctx, ast.Store):
with state.scope(node.id):
state.add_occurrence(position=position)
else:
if node.id not in state.current_node:
for scope in state.lookup_scopes[::-1]:
if node.id in scope or scope is state.root:
scope[node.id].alias(state.current_node[node.id])
break
with state.scope(node.id):
state.add_occurrence(position=node_position(node, source))
@singledispatch
def names_for(node: ast.AST) -> QualifiedName: # pylint: disable= unused-argument
return ()
@names_for.register
def names_for_name(node: ast.Name) -> QualifiedName:
return (node.id,)
@names_for.register
def names_for_attribute(node: ast.Attribute) -> QualifiedName:
return names_for(node.value) + (node.attr,)
@names_for.register
def names_for_call(node: ast.Call) -> QualifiedName:
return names_for(node.func) + ("()",)
def get_names(value: ast.AST) -> List[QualifiedName]:
if isinstance(value, ast.Tuple):
return [names_for(v) for v in value.elts]
return [names_for(value)]
@visit.register
def visit_assign(node: ast.Assign, source: Source, state: State) -> None:
for node_target in node.targets:
visit(node_target, source, state)
visit(node.value, source, state)
target_names = get_names(node.targets[0])
value_names = get_names(node.value)
for target, value in zip(target_names, value_names):
if target and value:
path: QualifiedName = ("..",)
with ExitStack() as stack:
for name in target:
stack.enter_context(state.scope(name))
stack.enter_context(state.scope("."))
path += ("..",)
state.alias(path + value + (".",))
def is_static_method(node: ast.FunctionDef) -> bool:
return any(
n.id == "staticmethod" for n in node.decorator_list if isinstance(n, ast.Name)
)
@visit.register
def visit_function_definition(
node: ast.FunctionDef, source: Source, state: State
) -> None:
is_method = state.lookup_scopes[-1] and state.lookup_scopes[-1].is_class
position = node_position(node, source, column_offset=len("def "))
with state.scope(node.name):
state.add_occurrence(position=position)
with state.scope("()"):
for i, arg in enumerate(node.args.args):
position = node_position(arg, source)
with state.scope(arg.arg):
state.add_occurrence(position=position)
if i == 0 and is_method and not is_static_method(node):
with state.scope("."):
state.alias(("..", "..", "..", ".."))
generic_visit(node, source, state)
@visit.register
def visit_class(node: ast.ClassDef, source: Source, state: State) -> None:
position = node_position(node, source, column_offset=len("class "))
for base in node.bases:
visit(base, source, state)
with state.scope(node.name, lookup_scope=True, is_class=True):
state.add_occurrence(position=position)
with state.scope("()"):
with state.scope("."):
state.alias(("..", "..", "."))
for base in node.bases:
state.alias(("..", "..", "..") + names_from(base) + ("()", "."))
for statement in node.body:
visit(statement, source, state)
@visit.register
def visit_call(node: ast.Call, source: Source, state: State) -> None:
call_position = node_position(node, source)
for arg in node.args:
visit(arg, source, state)
visit(node.func, source, state)
names = names_from(node.func)
with ExitStack() as stack:
if names:
stack.enter_context(state.scope(names[0]))
for name in names[1:]:
stack.enter_context(state.scope(name))
stack.enter_context(state.scope("()"))
for keyword in node.keywords:
if not keyword.arg:
continue
position = source.find_after(keyword.arg, call_position)
with state.scope(keyword.arg):
state.add_occurrence(position=position)
@singledispatch
def names_from(node: ast.AST) -> QualifiedName: # pylint: disable=unused-argument
return ()
@names_from.register
def name_names(node: ast.Name) -> QualifiedName:
return (node.id,)
@names_from.register
def attribute_names(node: ast.Attribute) -> QualifiedName:
return names_from(node.value) + (".", node.attr)
@names_from.register
def call_names(node: ast.Call) -> QualifiedName:
names = names_from(node.func)
return names
@visit.register
def visit_attribute(node: ast.Attribute, source: Source, state: State) -> None:
visit(node.value, source, state)
position = node_position(node, source)
names = names_from(node.value)
with ExitStack() as stack:
for name in names:
position = source.find_after(name, position)
stack.enter_context(state.scope(name))
stack.enter_context(state.scope("."))
position = source.find_after(node.attr, position)
stack.enter_context(state.scope(node.attr))
state.add_occurrence(position=position)
def visit_comp(
node: Union[ast.DictComp, ast.ListComp, ast.SetComp, ast.GeneratorExp],
source: Source,
state: State,
*sub_nodes,
) -> None:
position = node_position(node, source)
name = f"{type(node)}-{position.row},{position.column}"
with state.scope(name):
for generator in node.generators:
visit(generator.target, source, state)
visit(generator.iter, source, state)
for if_node in generator.ifs:
visit(if_node, source, state)
for sub_node in sub_nodes:
visit(sub_node, source, state)
@visit.register
def visit_dict_comp(node: ast.DictComp, source: Source, state: State) -> None:
visit_comp(node, source, state, node.key, node.value)
@visit.register
def visit_list_comp(node: ast.ListComp, source: Source, state: State) -> None:
visit_comp(node, source, state, node.elt)
@visit.register
def visit_set_comp(node: ast.SetComp, source: Source, state: State) -> None:
visit_comp(node, source, state, node.elt)
@visit.register
def visit_generator_exp(node: ast.GeneratorExp, source: Source, state: State) -> None:
visit_comp(node, source, state, node.elt)
def all_occurrence_positions(
position: Position,
) -> Iterable[Position]:
source = position.source
state = State(position)
visit(source.get_ast(), source=source, state=state)
if state.found:
return sorted(state.found.occurrences)
return []
def test_distinguishes_local_variables_from_global():
source = make_source(
"""
def fun():
old = 12
old2 = 13
result = old + old2
del old
return result
old = 20
"""
)
position = source.position(row=2, column=4)
assert all_occurrence_positions(position) == [
source.position(row=2, column=4),
source.position(row=4, column=13),
source.position(row=5, column=8),
]
def test_finds_non_local_variable():
source = make_source(
"""
old = 12
def fun():
result = old + 1
return result
old = 20
"""
)
position = source.position(1, 0)
assert all_occurrence_positions(position) == [
Position(source, 1, 0),
Position(source, 4, 13),
Position(source, 7, 0),
]
def test_does_not_rename_random_attributes():
source = make_source(
"""
import os
path = os.path.dirname(__file__)
"""
)
position = source.position(row=3, column=0)
assert all_occurrence_positions(position) == [source.position(row=3, column=0)]
def test_finds_parameter():
source = make_source(
"""
def fun(old=1):
print(old)
old = 8
fun(old=old)
"""
)
assert all_occurrence_positions(source.position(1, 8)) == [
source.position(1, 8),
source.position(2, 10),
source.position(5, 4),
]
def test_finds_function():
source = make_source(
"""
def fun_old():
return 'result'
result = fun_old()
"""
)
assert [source.position(1, 4), source.position(3, 9)] == all_occurrence_positions(
source.position(1, 4)
)
def test_finds_class():
source = make_source(
"""
class OldClass:
pass
instance = OldClass()
"""
)
assert [source.position(1, 6), source.position(4, 11)] == all_occurrence_positions(
source.position(1, 6)
)
def test_finds_method_name():
source = make_source(
"""
class A:
def old(self):
pass
unbound = A.old
"""
)
position = source.position(row=3, column=8)
assert all_occurrence_positions(position) == [
source.position(row=3, column=8),
source.position(row=6, column=12),
]
def test_finds_passed_argument():
source = make_source(
"""
old = 2
def fun(arg, arg2):
return arg + arg2
fun(1, old)
"""
)
assert [source.position(1, 0), source.position(4, 7)] == all_occurrence_positions(
source.position(1, 0)
)
def test_finds_parameter_with_unusual_indentation():
source = make_source(
"""
def fun(arg, arg2):
return arg + arg2
fun(
arg=\\
1,
arg2=2)
"""
)
assert [
source.position(1, 8),
source.position(2, 11),
source.position(4, 4),
] == all_occurrence_positions(source.position(1, 8))
def test_does_not_find_method_of_unrelated_class():
source = make_source(
"""
class ClassThatShouldHaveMethodRenamed:
def old(self, arg):
pass
def foo(self):
self.old('whatever')
class UnrelatedClass:
def old(self, arg):
pass
def foo(self):
self.old('whatever')
a = ClassThatShouldHaveMethodRenamed()
a.old()
b = UnrelatedClass()
b.old()
"""
)
occurrences = all_occurrence_positions(source.position(3, 8))
assert [
source.position(3, 8),
source.position(7, 13),
source.position(20, 2),
] == occurrences
def test_finds_definition_from_call():
source = make_source(
"""
def old():
pass
def bar():
old()
"""
)
assert [source.position(1, 4), source.position(5, 4)] == all_occurrence_positions(
source.position(1, 4)
)
def test_finds_attribute_assignments():
source = make_source(
"""
class ClassName:
def __init__(self, property):
self.property = property
def get_property(self):
return self.property
"""
)
occurrences = all_occurrence_positions(source.position(4, 13))
assert [source.position(4, 13), source.position(7, 20)] == occurrences
def test_finds_dict_comprehension_variables():
source = make_source(
"""
old = 1
foo = {old: None for old in range(100) if old % 3}
old = 2
"""
)
position = source.position(row=2, column=21)
assert all_occurrence_positions(position) == [
source.position(row=2, column=7),
source.position(row=2, column=21),
source.position(row=2, column=42),
]
def test_finds_list_comprehension_variables():
source = make_source(
"""
old = 100
foo = [
old for old in range(100) if old % 3]
old = 200
"""
)
position = source.position(row=3, column=12)
assert all_occurrence_positions(position) == [
source.position(row=3, column=4),
source.position(row=3, column=12),
source.position(row=3, column=33),
]
def test_finds_set_comprehension_variables() -> None:
source = make_source(
"""
old = 100
foo = {old for old in range(100) if old % 3}
"""
)
position = source.position(row=2, column=15)
assert all_occurrence_positions(position) == [
source.position(row=2, column=7),
source.position(row=2, column=15),
source.position(row=2, column=36),
]
def test_finds_generator_comprehension_variables() -> None:
source = make_source(
"""
old = 100
foo = (old for old in range(100) if old % 3)
"""
)
position = source.position(row=2, column=15)
assert all_occurrence_positions(position) == [
source.position(row=2, column=7),
source.position(row=2, column=15),
source.position(row=2, column=36),
]
def test_finds_loop_variables():
source = make_source(
"""
old = None
for i, old in enumerate(['foo']):
print(i)
print(old)
print(old)
"""
)
position = source.position(row=1, column=0)
assert all_occurrence_positions(position) == [
source.position(row=1, column=0),
source.position(row=2, column=7),
source.position(row=4, column=10),
source.position(row=5, column=6),
]
def test_finds_tuple_unpack():
source = make_source(
"""
foo, old = 1, 2
print(old)
"""
)
position = source.position(row=1, column=5)
assert all_occurrence_positions(position) == [
source.position(1, 5),
source.position(2, 6),
]
def test_finds_superclasses():
source = make_source(
"""
class A:
def old(self):
pass
class B(A):
pass
b = B()
c = b
c.old()
"""
)
position = source.position(row=3, column=8)
assert all_occurrence_positions(position) == [
source.position(row=3, column=8),
source.position(row=11, column=2),
]
def test_recognizes_multiple_assignments():
source = make_source(
"""
class A:
def old(self):
pass
class B:
def old(self):
pass
foo, bar = A(), B()
foo.old()
bar.old()
"""
)
position = source.position(row=2, column=8)
assert all_occurrence_positions(position) == [
source.position(2, 8),
source.position(10, 4),
]
def test_finds_enclosing_scope_variable_from_comprehension():
source = make_source(
"""
old = 3
res = [foo for foo in range(100) if foo % old]
"""
)
position = source.position(row=1, column=0)
assert all_occurrence_positions(position) == [
source.position(1, 0),
source.position(2, 42),
]
def test_finds_static_method():
source = make_source(
"""
class A:
@staticmethod
def old(arg):
pass
a = A()
b = a.old('foo')
"""
)
position = source.position(row=4, column=8)
assert all_occurrence_positions(position) == [
source.position(4, 8),
source.position(8, 6),
]
def test_finds_method_after_call():
source = make_source(
"""
class A:
def old(arg):
pass
b = A().old('foo')
"""
)
position = source.position(row=3, column=8)
assert all_occurrence_positions(position) == [
source.position(3, 8),
source.position(6, 8),
]
def test_finds_argument():
source = make_source(
"""
class A:
def foo(self, arg):
print(arg)
def bar(self):
arg = "1"
self.foo(arg=arg)
"""
)
position = source.position(row=3, column=18)
assert all_occurrence_positions(position) == [
source.position(3, 18),
source.position(4, 14),
source.position(8, 17),
]
|
thisfred/breakfast
|
tests/test_attempt_12.py
|
Python
|
bsd-2-clause
| 21,250 | 0.000659 |
"""
Copyright (c) 2016 Keith Sterling
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.
"""
import logging
from programy.config.base import BaseConfigurationData
class BrainFileConfiguration(object):
def __init__(self, files, extension=".aiml", directories=False):
self._files = files
self._extension = extension
self._directories = directories
@property
def files(self):
return self._files
@property
def extension(self):
return self._extension
@property
def directories(self):
return self._directories
class BrainServiceConfiguration(object):
def __init__(self, name, data=None):
self._name = name.upper()
self._params = {}
if data is not None:
for key in data.keys():
self._params[key.upper()] = data[key]
@property
def name(self):
return self._name
@property
def path(self):
return self._params['PATH']
def parameters(self):
return self._params.keys()
def set_parameter(self, key, value):
self._params[key] = value
def parameter(self, name):
if name in self._params:
return self._params[name]
else:
return None
class BrainConfiguration(BaseConfigurationData):
DEFAULT_SUPRESS_WARNINGS = False
DEFAULT_ALLOW_SYSTEM_AIML = True
DEFAULT_ALLOW_LEARN_AIML = True
DEFAULT_ALLOW_LEARNF_AIML = True
def __init__(self):
self._supress_warnings = BrainConfiguration.DEFAULT_SUPRESS_WARNINGS
self._allow_system_aiml = BrainConfiguration.DEFAULT_ALLOW_SYSTEM_AIML
self._allow_learn_aiml = BrainConfiguration.DEFAULT_ALLOW_LEARN_AIML
self._allow_learnf_aiml = BrainConfiguration.DEFAULT_ALLOW_LEARNF_AIML
self._aiml_files = None
self._set_files = None
self._map_files = None
self._denormal = None
self._normal = None
self._gender = None
self._person = None
self._person2 = None
self._predicates = None
self._pronouns = None
self._properties = None
self._triples = None
self._preprocessors = None
self._postprocessors = None
self._services = []
BaseConfigurationData.__init__(self, "brain")
def _get_brain_file_configuration(self, config_file, section, bot_root):
files = config_file.get_option(section, "files")
files = self.sub_bot_root(files, bot_root)
extension = config_file.get_option(section, "extension")
directories = config_file.get_option(section, "directories")
return BrainFileConfiguration(files, extension, directories)
def load_config_section(self, config_file, bot_root):
brain = config_file.get_section(self.section_name)
if brain is not None:
self._supress_warnings = config_file.get_option(brain, "supress_warnings", BrainConfiguration.DEFAULT_SUPRESS_WARNINGS)
self._allow_system_aiml = config_file.get_option(brain, "allow_system_aiml", BrainConfiguration.DEFAULT_ALLOW_SYSTEM_AIML)
self._allow_learn_aiml = config_file.get_option(brain, "allow_learn_aiml", BrainConfiguration.DEFAULT_ALLOW_LEARN_AIML)
self._allow_learnf_aiml = config_file.get_option(brain, "allow_learnf_aiml", BrainConfiguration.DEFAULT_ALLOW_LEARNF_AIML)
self._allow_learnf_aiml = config_file.get_option(brain, "allow_learnf_aiml", BrainConfiguration.DEFAULT_ALLOW_LEARNF_AIML)
files = config_file.get_section("files", brain)
if files is not None:
aiml = config_file.get_section("aiml", files)
self._aiml_files = self._get_brain_file_configuration(config_file, aiml, bot_root)
sets = config_file.get_section("sets", files)
self._set_files = self._get_brain_file_configuration(config_file, sets, bot_root)
maps = config_file.get_section("maps", files)
self._map_files = self._get_brain_file_configuration(config_file, maps, bot_root)
self._denormal = self._get_file_option(config_file, "denormal", files, bot_root)
self._normal = self._get_file_option(config_file, "normal", files, bot_root)
self._gender = self._get_file_option(config_file, "gender", files, bot_root)
self._person = self._get_file_option(config_file, "person", files, bot_root)
self._person2 = self._get_file_option(config_file, "person2", files, bot_root)
self._predicates = self._get_file_option(config_file, "predicates", files, bot_root)
self._pronouns = self._get_file_option(config_file, "pronouns", files, bot_root)
self._properties = self._get_file_option(config_file, "properties", files, bot_root)
self._triples = self._get_file_option(config_file, "triples", files, bot_root)
self._preprocessors = self._get_file_option(config_file, "preprocessors", files, bot_root)
self._postprocessors = self._get_file_option(config_file, "postprocessors", files, bot_root)
else:
logging.warning("Config section [files] missing from Brain, default values not appropriate")
raise Exception ("Config section [files] missing from Brain")
services = config_file.get_section("services", brain)
if services is not None:
service_keys = config_file.get_child_section_keys("services", brain)
for name in service_keys:
service_data = config_file.get_section_data(name, services)
self._services.append(BrainServiceConfiguration(name, service_data))
else:
logging.warning("Config section [services] missing from Brain, no services loaded")
else:
logging.warning("Config section [%s] missing, using default values", self.section_name)
self._supress_warnings = BrainConfiguration.DEFAULT_SUPRESS_WARNINGS
self._allow_system_aiml = BrainConfiguration.DEFAULT_ALLOW_SYSTEM_AIML
self._allow_learn_aiml = BrainConfiguration.DEFAULT_ALLOW_LEARN_AIML
self._allow_learnf_aiml = BrainConfiguration.DEFAULT_ALLOW_LEARNF_AIML
self._allow_learnf_aiml = BrainConfiguration.DEFAULT_ALLOW_LEARNF_AIML
@property
def supress_warnings(self):
return self._supress_warnings
@property
def allow_system_aiml(self):
return self._allow_system_aiml
@property
def allow_learn_aiml(self):
return self._allow_learn_aiml
@property
def allow_learnf_aiml(self):
return self._allow_learnf_aiml
@property
def aiml_files(self):
return self._aiml_files
@property
def set_files(self):
return self._set_files
@property
def map_files(self):
return self._map_files
@property
def denormal(self):
return self._denormal
@property
def normal(self):
return self._normal
@property
def gender(self):
return self._gender
@property
def person(self):
return self._person
@property
def person2(self):
return self._person2
@property
def predicates(self):
return self._predicates
@property
def pronouns(self):
return self._pronouns
@property
def properties(self):
return self._properties
@property
def triples(self):
return self._triples
@property
def preprocessors(self):
return self._preprocessors
@property
def postprocessors(self):
return self._postprocessors
@property
def services(self):
return self._services
|
CHT5/program-y
|
src/programy/config/brain.py
|
Python
|
mit
| 8,932 | 0.007053 |
from mocket import Mocket, mocketize
from mocket.async_mocket import async_mocketize
from mocket.compat import byte_type, text_type
from mocket.mockhttp import Entry as MocketHttpEntry
from mocket.mockhttp import Request as MocketHttpRequest
from mocket.mockhttp import Response as MocketHttpResponse
def httprettifier_headers(headers):
return {k.lower().replace("_", "-"): v for k, v in headers.items()}
class Request(MocketHttpRequest):
@property
def body(self):
if self._body is None:
self._body = self.parser.recv_body()
return self._body
class Response(MocketHttpResponse):
def get_protocol_data(self, str_format_fun_name="lower"):
if "server" in self.headers and self.headers["server"] == "Python/Mocket":
self.headers["server"] = "Python/HTTPretty"
return super(Response, self).get_protocol_data(
str_format_fun_name=str_format_fun_name
)
def set_base_headers(self):
super(Response, self).set_base_headers()
self.headers = httprettifier_headers(self.headers)
original_set_base_headers = set_base_headers
def set_extra_headers(self, headers):
self.headers.update(headers)
class Entry(MocketHttpEntry):
request_cls = Request
response_cls = Response
activate = mocketize
httprettified = mocketize
async_httprettified = async_mocketize
enable = Mocket.enable
disable = Mocket.disable
reset = Mocket.reset
GET = Entry.GET
PUT = Entry.PUT
POST = Entry.POST
DELETE = Entry.DELETE
HEAD = Entry.HEAD
PATCH = Entry.PATCH
OPTIONS = Entry.OPTIONS
def register_uri(
method,
uri,
body="HTTPretty :)",
adding_headers=None,
forcing_headers=None,
status=200,
responses=None,
match_querystring=False,
priority=0,
**headers
):
headers = httprettifier_headers(headers)
if adding_headers is not None:
headers.update(httprettifier_headers(adding_headers))
if forcing_headers is not None:
def force_headers(self):
self.headers = httprettifier_headers(forcing_headers)
Response.set_base_headers = force_headers
else:
Response.set_base_headers = Response.original_set_base_headers
if responses:
Entry.register(method, uri, *responses)
else:
Entry.single_register(
method,
uri,
body=body,
status=status,
headers=headers,
match_querystring=match_querystring,
)
class MocketHTTPretty:
Response = Response
def __getattr__(self, name):
if name == "last_request":
return Mocket.last_request()
if name == "latest_requests":
return Mocket.request_list()
return getattr(Entry, name)
HTTPretty = MocketHTTPretty()
HTTPretty.register_uri = register_uri
httpretty = HTTPretty
__all__ = (
"HTTPretty",
"activate",
"async_httprettified",
"httprettified",
"enable",
"disable",
"reset",
"Response",
"GET",
"PUT",
"POST",
"DELETE",
"HEAD",
"PATCH",
"register_uri",
"text_type",
"byte_type",
)
|
mindflayer/python-mocket
|
mocket/plugins/httpretty/__init__.py
|
Python
|
bsd-3-clause
| 3,152 | 0.000317 |
"""Support for switches through the SmartThings cloud API."""
from __future__ import annotations
from collections.abc import Sequence
from pysmartthings import Capability
from homeassistant.components.switch import SwitchEntity
from . import SmartThingsEntity
from .const import DATA_BROKERS, DOMAIN
async def async_setup_entry(hass, config_entry, async_add_entities):
"""Add switches for a config entry."""
broker = hass.data[DOMAIN][DATA_BROKERS][config_entry.entry_id]
async_add_entities(
[
SmartThingsSwitch(device)
for device in broker.devices.values()
if broker.any_assigned(device.device_id, "switch")
]
)
def get_capabilities(capabilities: Sequence[str]) -> Sequence[str] | None:
"""Return all capabilities supported if minimum required are present."""
# Must be able to be turned on/off.
if Capability.switch in capabilities:
return [Capability.switch, Capability.energy_meter, Capability.power_meter]
return None
class SmartThingsSwitch(SmartThingsEntity, SwitchEntity):
"""Define a SmartThings switch."""
async def async_turn_off(self, **kwargs) -> None:
"""Turn the switch off."""
await self._device.switch_off(set_status=True)
# State is set optimistically in the command above, therefore update
# the entity state ahead of receiving the confirming push updates
self.async_write_ha_state()
async def async_turn_on(self, **kwargs) -> None:
"""Turn the switch on."""
await self._device.switch_on(set_status=True)
# State is set optimistically in the command above, therefore update
# the entity state ahead of receiving the confirming push updates
self.async_write_ha_state()
@property
def is_on(self) -> bool:
"""Return true if light is on."""
return self._device.status.switch
|
jawilson/home-assistant
|
homeassistant/components/smartthings/switch.py
|
Python
|
apache-2.0
| 1,911 | 0.000523 |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2018-05-30 17:02
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('main', '0062_auto_20171223_1552'),
]
operations = [
migrations.AddField(
model_name='event',
name='date_end',
field=models.DateField(blank=True, default=None, null=True),
),
]
|
OKThess/website
|
main/migrations/0063_event_date_end.py
|
Python
|
mit
| 469 | 0 |
from baseline.pytorch.torchy import *
from eight_mile.pytorch.layers import TransformerEncoderStack, subsequent_mask, MultiHeadedAttention
from baseline.model import LanguageModel, register_model
from eight_mile.pytorch.serialize import load_tlm_npz
import torch.autograd
import os
class LanguageModelBase(nn.Module, LanguageModel):
def __init__(self):
super().__init__()
def save(self, outname):
torch.save(self, outname)
basename, _ = os.path.splitext(outname)
def create_loss(self):
return SequenceCriterion(LossFn=nn.CrossEntropyLoss)
@classmethod
def load(cls, filename, **kwargs):
device = kwargs.get('device')
if not os.path.exists(filename):
filename += '.pyt'
model = torch.load(filename, map_location=device)
model.gpu = False if device == 'cpu' else model.gpu
return model
def zero_state(self, batchsz):
return None
@property
def requires_state(self):
pass
def make_input(self, batch_dict, numpy_to_tensor=False):
example_dict = dict({})
for key in self.src_keys:
tensor = batch_dict[key]
if numpy_to_tensor:
tensor = torch.from_numpy(tensor)
if self.gpu:
tensor = tensor.cuda()
example_dict[key] = tensor
y = batch_dict.get('y')
if y is not None:
if numpy_to_tensor:
y = torch.from_numpy(y)
if self.gpu:
y = y.cuda()
example_dict['y'] = y
return example_dict
@classmethod
def create(cls, embeddings, **kwargs):
lm = cls()
lm.gpu = kwargs.get('gpu', True)
lm.tgt_key = kwargs.get('tgt_key')
if lm.tgt_key is None:
raise Exception('Need a `tgt_key` to know which source vocabulary should be used for destination ')
lm.src_keys = kwargs.get('src_keys', embeddings.keys())
lm.create_layers(embeddings, **kwargs)
checkpoint_name = kwargs.get('checkpoint')
if checkpoint_name is not None:
if checkpoint_name.endswith('npz'):
load_tlm_npz(lm, checkpoint_name)
else:
lm.load_state_dict(torch.load(checkpoint_name))
return lm
def create_layers(self, embeddings, **kwargs):
"""This method defines the model itself, and must be overloaded by derived classes
This function will update `self` with the layers required to execute the `call()` method
:param embeddings: The input feature indices
:param kwargs:
:return:
"""
def predict(self, batch_dict, **kwargs):
self.eval()
numpy_to_tensor = bool(kwargs.get('numpy_to_tensor', True))
batch_dict = self.make_input(batch_dict, numpy_to_tensor=numpy_to_tensor)
hidden = batch_dict.get('h')
step_softmax, _ = self(batch_dict, hidden)
return F.softmax(step_softmax, dim=-1)
class AbstractGeneratorLanguageModel(LanguageModelBase):
def create_layers(self, embeddings, **kwargs):
self.embeddings = self.init_embed(embeddings, **kwargs)
self.embeddings_proj = self.init_embeddings_proj(**kwargs)
self.generator = self.init_generate(**kwargs)
self.output_layer = self.init_output(embeddings, **kwargs)
def forward(self, input: Dict[str, TensorDef], hidden: TensorDef) -> Tuple[TensorDef, TensorDef]:
emb = self.embed(input)
output, hidden = self.generate(emb, hidden)
return self.output_layer(output), hidden
def embed(self, input):
embedded_dropout = self.embeddings(input)
return self.embeddings_proj(embedded_dropout)
def init_embed(self, embeddings: Dict[str, TensorDef], **kwargs) -> BaseLayer:
"""This method creates the "embedding" layer of the inputs, with an optional reduction
:param embeddings: A dictionary of embeddings
:Keyword Arguments: See below
* *embeddings_reduction* (defaults to `concat`) An operator to perform on a stack of embeddings
* *embeddings_dropout = float(kwargs.get('embeddings_dropout', 0.0))
:return: The output of the embedding stack followed by its reduction. This will typically be an output
with an additional dimension which is the hidden representation of the input
"""
reduction = kwargs.get('embeddings_reduction', 'concat')
embeddings_dropout = float(kwargs.get('embeddings_dropout', 0.0))
return EmbeddingsStack({k: embeddings[k] for k in self.src_keys}, embeddings_dropout, reduction=reduction)
def init_embeddings_proj(self, **kwargs):
input_sz = self.embeddings.output_dim
hsz = kwargs.get('hsz', kwargs.get('d_model'))
if hsz != input_sz:
proj = pytorch_linear(input_sz, hsz)
print('Applying a transform from {} to {}'.format(input_sz, hsz))
else:
proj = nn.Identity()
return proj
def init_generate(self, **kwargs):
pass
def generate(self, emb, hidden):
return self.generator((emb, hidden))
def init_output(self, embeddings, **kwargs):
self.vsz = embeddings[self.tgt_key].get_vsz()
hsz = kwargs.get('hsz', kwargs.get('d_model'))
unif = float(kwargs.get('unif', 0.0))
do_weight_tying = bool(kwargs.get('tie_weights', False))
output_bias = kwargs.get('output_bias', False)
if do_weight_tying:
output = WeightTieDense(embeddings[self.tgt_key], output_bias)
else:
output = pytorch_linear(hsz, self.vsz, unif)
return output
@register_model(task='lm', name='default')
class RNNLanguageModel(AbstractGeneratorLanguageModel):
def __init__(self):
super().__init__()
def zero_state(self, batchsz):
weight = next(self.parameters()).data
return (torch.autograd.Variable(weight.new(self.num_layers, batchsz, self.hsz).zero_()),
torch.autograd.Variable(weight.new(self.num_layers, batchsz, self.hsz).zero_()))
@property
def requires_state(self):
True
def init_generate(self, **kwargs):
pdrop = float(kwargs.get('dropout', 0.5))
self.num_layers = kwargs.get('layers', kwargs.get('num_layers', 1))
self.hsz = kwargs.get('hsz', kwargs.get('d_model'))
return WithDropoutOnFirst(LSTMEncoderWithState(self.hsz, self.hsz, self.num_layers, pdrop, batch_first=True),
pdrop,
kwargs.get('variational', False))
@register_model(task='lm', name='transformer')
class TransformerLanguageModel(AbstractGeneratorLanguageModel):
def __init__(self):
super().__init__()
@property
def requires_state(self):
False
def init_layer_weights(self, module):
if isinstance(module, (nn.Linear, nn.Embedding, nn.LayerNorm)):
module.weight.data.normal_(mean=0.0, std=self.weight_std)
if isinstance(module, (nn.Linear, nn.LayerNorm)) and module.bias is not None:
module.bias.data.zero_()
def init_generate(self, **kwargs):
pdrop = float(kwargs.get('dropout', 0.1))
layers = kwargs.get('layers', kwargs.get('num_layers', 1))
d_model = int(kwargs.get('d_model', kwargs.get('hsz')))
num_heads = kwargs.get('num_heads', 4)
d_ff = int(kwargs.get('d_ff', 4 * d_model))
rpr_k = kwargs.get('rpr_k')
d_k = kwargs.get('d_k')
scale = bool(kwargs.get('scale', True))
activation = kwargs.get('activation', 'gelu')
ffn_pdrop = kwargs.get('ffn_pdrop', 0.0)
layer_norm_eps = kwargs.get('layer_norm_eps', 1e-12)
layer_norms_after = kwargs.get('layer_norms_after', False)
layer_drop = kwargs.get('layer_drop', 0.0)
windowed_ra = kwargs.get('windowed_ra', False)
rpr_value_on = kwargs.get('rpr_value_on', True)
return TransformerEncoderStack(num_heads, d_model=d_model, pdrop=pdrop, scale=scale,
layers=layers, d_ff=d_ff, rpr_k=rpr_k, d_k=d_k,
activation=activation,
ffn_pdrop=ffn_pdrop,
layer_norm_eps=layer_norm_eps,
layer_norms_after=layer_norms_after, windowed_ra=windowed_ra,
rpr_value_on=rpr_value_on,
layer_drop=layer_drop)
def create_layers(self, embeddings, **kwargs):
super().create_layers(embeddings, **kwargs)
self.weight_std = kwargs.get('weight_std', 0.02)
self.apply(self.init_layer_weights)
def create_mask(self, bth):
T = bth.shape[1]
mask = subsequent_mask(T).type_as(bth)
return mask
def generate(self, bth, _):
mask = self.create_mask(bth)
return self.generator((bth, mask)), None
@register_model(task='lm', name='transformer-mlm')
class TransformerMaskedLanguageModel(TransformerLanguageModel):
def create_mask(self, bth):
return None
@register_model(task='lm', name='gmlp-mlm')
class GatedMLPLanguageModel(AbstractGeneratorLanguageModel):
def __init__(self):
super().__init__()
@property
def requires_state(self):
False
def init_layer_weights(self, module):
if isinstance(module, (nn.Linear, nn.Embedding, nn.LayerNorm)):
module.weight.data.normal_(mean=0.0, std=self.weight_std)
if isinstance(module, (nn.Linear, nn.LayerNorm)) and module.bias is not None:
module.bias.data.zero_()
def init_generate(self, **kwargs):
pdrop = float(kwargs.get('dropout', 0.1))
layers = kwargs.get('layers', kwargs.get('num_layers', 1))
d_model = int(kwargs.get('d_model', kwargs.get('hsz')))
d_ff = int(kwargs.get('d_ff', 4 * d_model))
activation = kwargs.get('activation', 'gelu')
ffn_pdrop = kwargs.get('ffn_pdrop', 0.0)
layer_norm_eps = kwargs.get('layer_norm_eps', 1e-12)
layer_drop = kwargs.get('layer_drop', 0.0)
nctx = int(kwargs.get('nctx', 256))
return GatedMLPEncoderStack(d_model=d_model, pdrop=pdrop,
layers=layers, nctx=nctx, d_ff=d_ff,
activation=activation,
ffn_pdrop=ffn_pdrop,
layer_norm_eps=layer_norm_eps,
layer_drop=layer_drop)
def create_layers(self, embeddings, **kwargs):
super().create_layers(embeddings, **kwargs)
self.weight_std = kwargs.get('weight_std', 0.02)
self.apply(self.init_layer_weights)
def create_mask(self, bth):
return None
def generate(self, bth, _):
mask = self.create_mask(bth)
return self.generator((bth, mask)), None
|
dpressel/baseline
|
baseline/pytorch/lm/model.py
|
Python
|
apache-2.0
| 11,032 | 0.001813 |
import click
from pycolorterm.pycolorterm import print_pretty
from quarantine.cdc import CDC
from sh import ErrorReturnCode
@click.group()
def cli():
pass
@cli.command()
@click.argument('name')
@click.argument('pip_args', nargs=-1)
def install(name, pip_args):
"""Install the package. Pip args specified with --."""
cdc = CDC(name)
try:
cdc.install(pip_args)
except ErrorReturnCode as e:
print_pretty("<FG_RED>Something went wrong! Rolling back...<END>")
cdc.uninstall()
@cli.command()
@click.argument('name')
def uninstall(name):
"""Uninstall the package, environment and all."""
cdc = CDC(name)
cdc.uninstall()
if __name__ == '__main__':
quarantine()
|
Raynes/quarantine
|
quarantine/__main__.py
|
Python
|
apache-2.0
| 719 | 0.002782 |
# -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
#.apidoc title: Object Relational Mapping
#.apidoc module-mods: member-order: bysource
"""
Object relational mapping to database (postgresql) module
* Hierarchical structure
* Constraints consistency, validations
* Object meta Data depends on its status
* Optimised processing by complex query (multiple actions at once)
* Default fields value
* Permissions optimisation
* Persistant object: DB postgresql
* Datas conversions
* Multi-level caching system
* 2 different inheritancies
* Fields:
- classicals (varchar, integer, boolean, ...)
- relations (one2many, many2one, many2many)
- functions
"""
import calendar
import copy
import datetime
import itertools
import logging
import operator
import pickle
import re
import simplejson
import time
import types
from lxml import etree
import fields
import openerp
import openerp.netsvc as netsvc
import openerp.tools as tools
from openerp.tools.config import config
from openerp.tools.safe_eval import safe_eval as eval
from openerp.tools.translate import _
from openerp import SUPERUSER_ID
from query import Query
_logger = logging.getLogger(__name__)
_schema = logging.getLogger(__name__ + '.schema')
# List of etree._Element subclasses that we choose to ignore when parsing XML.
from openerp.tools import SKIPPED_ELEMENT_TYPES
regex_order = re.compile('^(([a-z0-9_]+|"[a-z0-9_]+")( *desc| *asc)?( *, *|))+$', re.I)
regex_object_name = re.compile(r'^[a-z0-9_.]+$')
def transfer_field_to_modifiers(field, modifiers):
default_values = {}
state_exceptions = {}
for attr in ('invisible', 'readonly', 'required'):
state_exceptions[attr] = []
default_values[attr] = bool(field.get(attr))
for state, modifs in (field.get("states",{})).items():
for modif in modifs:
if default_values[modif[0]] != modif[1]:
state_exceptions[modif[0]].append(state)
for attr, default_value in default_values.items():
if state_exceptions[attr]:
modifiers[attr] = [("state", "not in" if default_value else "in", state_exceptions[attr])]
else:
modifiers[attr] = default_value
# Don't deal with groups, it is done by check_group().
# Need the context to evaluate the invisible attribute on tree views.
# For non-tree views, the context shouldn't be given.
def transfer_node_to_modifiers(node, modifiers, context=None, in_tree_view=False):
if node.get('attrs'):
modifiers.update(eval(node.get('attrs')))
if node.get('states'):
if 'invisible' in modifiers and isinstance(modifiers['invisible'], list):
# TODO combine with AND or OR, use implicit AND for now.
modifiers['invisible'].append(('state', 'not in', node.get('states').split(',')))
else:
modifiers['invisible'] = [('state', 'not in', node.get('states').split(','))]
for a in ('invisible', 'readonly', 'required'):
if node.get(a):
v = bool(eval(node.get(a), {'context': context or {}}))
if in_tree_view and a == 'invisible':
# Invisible in a tree view has a specific meaning, make it a
# new key in the modifiers attribute.
modifiers['tree_invisible'] = v
elif v or (a not in modifiers or not isinstance(modifiers[a], list)):
# Don't set the attribute to False if a dynamic value was
# provided (i.e. a domain from attrs or states).
modifiers[a] = v
def simplify_modifiers(modifiers):
for a in ('invisible', 'readonly', 'required'):
if a in modifiers and not modifiers[a]:
del modifiers[a]
def transfer_modifiers_to_node(modifiers, node):
if modifiers:
simplify_modifiers(modifiers)
node.set('modifiers', simplejson.dumps(modifiers))
def setup_modifiers(node, field=None, context=None, in_tree_view=False):
""" Processes node attributes and field descriptors to generate
the ``modifiers`` node attribute and set it on the provided node.
Alters its first argument in-place.
:param node: ``field`` node from an OpenERP view
:type node: lxml.etree._Element
:param dict field: field descriptor corresponding to the provided node
:param dict context: execution context used to evaluate node attributes
:param bool in_tree_view: triggers the ``tree_invisible`` code
path (separate from ``invisible``): in
tree view there are two levels of
invisibility, cell content (a column is
present but the cell itself is not
displayed) with ``invisible`` and column
invisibility (the whole column is
hidden) with ``tree_invisible``.
:returns: nothing
"""
modifiers = {}
if field is not None:
transfer_field_to_modifiers(field, modifiers)
transfer_node_to_modifiers(
node, modifiers, context=context, in_tree_view=in_tree_view)
transfer_modifiers_to_node(modifiers, node)
def test_modifiers(what, expected):
modifiers = {}
if isinstance(what, basestring):
node = etree.fromstring(what)
transfer_node_to_modifiers(node, modifiers)
simplify_modifiers(modifiers)
json = simplejson.dumps(modifiers)
assert json == expected, "%s != %s" % (json, expected)
elif isinstance(what, dict):
transfer_field_to_modifiers(what, modifiers)
simplify_modifiers(modifiers)
json = simplejson.dumps(modifiers)
assert json == expected, "%s != %s" % (json, expected)
# To use this test:
# import openerp
# openerp.osv.orm.modifiers_tests()
def modifiers_tests():
test_modifiers('<field name="a"/>', '{}')
test_modifiers('<field name="a" invisible="1"/>', '{"invisible": true}')
test_modifiers('<field name="a" readonly="1"/>', '{"readonly": true}')
test_modifiers('<field name="a" required="1"/>', '{"required": true}')
test_modifiers('<field name="a" invisible="0"/>', '{}')
test_modifiers('<field name="a" readonly="0"/>', '{}')
test_modifiers('<field name="a" required="0"/>', '{}')
test_modifiers('<field name="a" invisible="1" required="1"/>', '{"invisible": true, "required": true}') # TODO order is not guaranteed
test_modifiers('<field name="a" invisible="1" required="0"/>', '{"invisible": true}')
test_modifiers('<field name="a" invisible="0" required="1"/>', '{"required": true}')
test_modifiers("""<field name="a" attrs="{'invisible': [('b', '=', 'c')]}"/>""", '{"invisible": [["b", "=", "c"]]}')
# The dictionary is supposed to be the result of fields_get().
test_modifiers({}, '{}')
test_modifiers({"invisible": True}, '{"invisible": true}')
test_modifiers({"invisible": False}, '{}')
def check_object_name(name):
""" Check if the given name is a valid openerp object name.
The _name attribute in osv and osv_memory object is subject to
some restrictions. This function returns True or False whether
the given name is allowed or not.
TODO: this is an approximation. The goal in this approximation
is to disallow uppercase characters (in some places, we quote
table/column names and in other not, which leads to this kind
of errors:
psycopg2.ProgrammingError: relation "xxx" does not exist).
The same restriction should apply to both osv and osv_memory
objects for consistency.
"""
if regex_object_name.match(name) is None:
return False
return True
def raise_on_invalid_object_name(name):
if not check_object_name(name):
msg = "The _name attribute %s is not valid." % name
_logger.error(msg)
raise except_orm('ValueError', msg)
POSTGRES_CONFDELTYPES = {
'RESTRICT': 'r',
'NO ACTION': 'a',
'CASCADE': 'c',
'SET NULL': 'n',
'SET DEFAULT': 'd',
}
def intersect(la, lb):
return filter(lambda x: x in lb, la)
def fix_import_export_id_paths(fieldname):
"""
Fixes the id fields in import and exports, and splits field paths
on '/'.
:param str fieldname: name of the field to import/export
:return: split field name
:rtype: list of str
"""
fixed_db_id = re.sub(r'([^/])\.id', r'\1/.id', fieldname)
fixed_external_id = re.sub(r'([^/]):id', r'\1/id', fixed_db_id)
return fixed_external_id.split('/')
class except_orm(Exception):
def __init__(self, name, value):
self.name = name
self.value = value
self.args = (name, value)
class BrowseRecordError(Exception):
pass
class browse_null(object):
""" Readonly python database object browser
"""
def __init__(self):
self.id = False
def __getitem__(self, name):
return None
def __getattr__(self, name):
return None # XXX: return self ?
def __int__(self):
return False
def __str__(self):
return ''
def __nonzero__(self):
return False
def __unicode__(self):
return u''
#
# TODO: execute an object method on browse_record_list
#
class browse_record_list(list):
""" Collection of browse objects
Such an instance will be returned when doing a ``browse([ids..])``
and will be iterable, yielding browse() objects
"""
def __init__(self, lst, context=None):
if not context:
context = {}
super(browse_record_list, self).__init__(lst)
self.context = context
class browse_record(object):
""" An object that behaves like a row of an object's table.
It has attributes after the columns of the corresponding object.
Examples::
uobj = pool.get('res.users')
user_rec = uobj.browse(cr, uid, 104)
name = user_rec.name
"""
def __init__(self, cr, uid, id, table, cache, context=None,
list_class=browse_record_list, fields_process=None):
"""
:param table: the browsed object (inherited from orm)
:param dict cache: a dictionary of model->field->data to be shared
across browse objects, thus reducing the SQL
read()s. It can speed up things a lot, but also be
disastrous if not discarded after write()/unlink()
operations
:param dict context: dictionary with an optional context
"""
if fields_process is None:
fields_process = {}
if context is None:
context = {}
self._list_class = list_class
self._cr = cr
self._uid = uid
self._id = id
self._table = table # deprecated, use _model!
self._model = table
self._table_name = self._table._name
self.__logger = logging.getLogger('openerp.osv.orm.browse_record.' + self._table_name)
self._context = context
self._fields_process = fields_process
cache.setdefault(table._name, {})
self._data = cache[table._name]
# if not (id and isinstance(id, (int, long,))):
# raise BrowseRecordError(_('Wrong ID for the browse record, got %r, expected an integer.') % (id,))
# if not table.exists(cr, uid, id, context):
# raise BrowseRecordError(_('Object %s does not exists') % (self,))
if id not in self._data:
self._data[id] = {'id': id}
self._cache = cache
def __getitem__(self, name):
if name == 'id':
return self._id
if name not in self._data[self._id]:
# build the list of fields we will fetch
# fetch the definition of the field which was asked for
if name in self._table._columns:
col = self._table._columns[name]
elif name in self._table._inherit_fields:
col = self._table._inherit_fields[name][2]
elif hasattr(self._table, str(name)):
attr = getattr(self._table, name)
if isinstance(attr, (types.MethodType, types.LambdaType, types.FunctionType)):
def function_proxy(*args, **kwargs):
if 'context' not in kwargs and self._context:
kwargs.update(context=self._context)
return attr(self._cr, self._uid, [self._id], *args, **kwargs)
return function_proxy
else:
return attr
else:
error_msg = "Field '%s' does not exist in object '%s'" % (name, self)
self.__logger.warning(error_msg)
raise KeyError(error_msg)
# if the field is a classic one or a many2one, we'll fetch all classic and many2one fields
if col._prefetch:
# gen the list of "local" (ie not inherited) fields which are classic or many2one
fields_to_fetch = filter(lambda x: x[1]._classic_write, self._table._columns.items())
# gen the list of inherited fields
inherits = map(lambda x: (x[0], x[1][2]), self._table._inherit_fields.items())
# complete the field list with the inherited fields which are classic or many2one
fields_to_fetch += filter(lambda x: x[1]._classic_write, inherits)
# otherwise we fetch only that field
else:
fields_to_fetch = [(name, col)]
ids = filter(lambda id: name not in self._data[id], self._data.keys())
# read the results
field_names = map(lambda x: x[0], fields_to_fetch)
field_values = self._table.read(self._cr, self._uid, ids, field_names, context=self._context, load="_classic_write")
# TODO: improve this, very slow for reports
if self._fields_process:
lang = self._context.get('lang', 'en_US') or 'en_US'
lang_obj_ids = self.pool.get('res.lang').search(self._cr, self._uid, [('code', '=', lang)])
if not lang_obj_ids:
raise Exception(_('Language with code "%s" is not defined in your system !\nDefine it through the Administration menu.') % (lang,))
lang_obj = self.pool.get('res.lang').browse(self._cr, self._uid, lang_obj_ids[0])
for field_name, field_column in fields_to_fetch:
if field_column._type in self._fields_process:
for result_line in field_values:
result_line[field_name] = self._fields_process[field_column._type](result_line[field_name])
if result_line[field_name]:
result_line[field_name].set_value(self._cr, self._uid, result_line[field_name], self, field_column, lang_obj)
if not field_values:
# Where did those ids come from? Perhaps old entries in ir_model_dat?
_logger.warning("No field_values found for ids %s in %s", ids, self)
raise KeyError('Field %s not found in %s'%(name, self))
# create browse records for 'remote' objects
for result_line in field_values:
new_data = {}
for field_name, field_column in fields_to_fetch:
if field_column._type in ('many2one', 'one2one'):
if result_line[field_name]:
obj = self._table.pool.get(field_column._obj)
if isinstance(result_line[field_name], (list, tuple)):
value = result_line[field_name][0]
else:
value = result_line[field_name]
if value:
# FIXME: this happen when a _inherits object
# overwrite a field of it parent. Need
# testing to be sure we got the right
# object and not the parent one.
if not isinstance(value, browse_record):
if obj is None:
# In some cases the target model is not available yet, so we must ignore it,
# which is safe in most cases, this value will just be loaded later when needed.
# This situation can be caused by custom fields that connect objects with m2o without
# respecting module dependencies, causing relationships to be connected to soon when
# the target is not loaded yet.
continue
new_data[field_name] = browse_record(self._cr,
self._uid, value, obj, self._cache,
context=self._context,
list_class=self._list_class,
fields_process=self._fields_process)
else:
new_data[field_name] = value
else:
new_data[field_name] = browse_null()
else:
new_data[field_name] = browse_null()
elif field_column._type in ('one2many', 'many2many') and len(result_line[field_name]):
new_data[field_name] = self._list_class([browse_record(self._cr, self._uid, id, self._table.pool.get(field_column._obj), self._cache, context=self._context, list_class=self._list_class, fields_process=self._fields_process) for id in result_line[field_name]], self._context)
elif field_column._type in ('reference'):
if result_line[field_name]:
if isinstance(result_line[field_name], browse_record):
new_data[field_name] = result_line[field_name]
else:
ref_obj, ref_id = result_line[field_name].split(',')
ref_id = long(ref_id)
if ref_id:
obj = self._table.pool.get(ref_obj)
new_data[field_name] = browse_record(self._cr, self._uid, ref_id, obj, self._cache, context=self._context, list_class=self._list_class, fields_process=self._fields_process)
else:
new_data[field_name] = browse_null()
else:
new_data[field_name] = browse_null()
else:
new_data[field_name] = result_line[field_name]
self._data[result_line['id']].update(new_data)
if not name in self._data[self._id]:
# How did this happen? Could be a missing model due to custom fields used too soon, see above.
self.__logger.error("Fields to fetch: %s, Field values: %s", field_names, field_values)
self.__logger.error("Cached: %s, Table: %s", self._data[self._id], self._table)
raise KeyError(_('Unknown attribute %s in %s ') % (name, self))
return self._data[self._id][name]
def __getattr__(self, name):
try:
return self[name]
except KeyError, e:
raise AttributeError(e)
def __contains__(self, name):
return (name in self._table._columns) or (name in self._table._inherit_fields) or hasattr(self._table, name)
def __iter__(self):
raise NotImplementedError("Iteration is not allowed on %s" % self)
def __hasattr__(self, name):
return name in self
def __int__(self):
return self._id
def __str__(self):
return "browse_record(%s, %d)" % (self._table_name, self._id)
def __eq__(self, other):
if not isinstance(other, browse_record):
return False
return (self._table_name, self._id) == (other._table_name, other._id)
def __ne__(self, other):
if not isinstance(other, browse_record):
return True
return (self._table_name, self._id) != (other._table_name, other._id)
# we need to define __unicode__ even though we've already defined __str__
# because we have overridden __getattr__
def __unicode__(self):
return unicode(str(self))
def __hash__(self):
return hash((self._table_name, self._id))
__repr__ = __str__
def refresh(self):
"""Force refreshing this browse_record's data and all the data of the
records that belong to the same cache, by emptying the cache completely,
preserving only the record identifiers (for prefetching optimizations).
"""
for model, model_cache in self._cache.iteritems():
# only preserve the ids of the records that were in the cache
cached_ids = dict([(i, {'id': i}) for i in model_cache.keys()])
self._cache[model].clear()
self._cache[model].update(cached_ids)
def pg_varchar(size=0):
""" Returns the VARCHAR declaration for the provided size:
* If no size (or an empty or negative size is provided) return an
'infinite' VARCHAR
* Otherwise return a VARCHAR(n)
:type int size: varchar size, optional
:rtype: str
"""
if size:
if not isinstance(size, int):
raise TypeError("VARCHAR parameter should be an int, got %s"
% type(size))
if size > 0:
return 'VARCHAR(%d)' % size
return 'VARCHAR'
FIELDS_TO_PGTYPES = {
fields.boolean: 'bool',
fields.integer: 'int4',
fields.integer_big: 'int8',
fields.text: 'text',
fields.date: 'date',
fields.time: 'time',
fields.datetime: 'timestamp',
fields.binary: 'bytea',
fields.many2one: 'int4',
fields.serialized: 'text',
}
def get_pg_type(f, type_override=None):
"""
:param fields._column f: field to get a Postgres type for
:param type type_override: use the provided type for dispatching instead of the field's own type
:returns: (postgres_identification_type, postgres_type_specification)
:rtype: (str, str)
"""
field_type = type_override or type(f)
if field_type in FIELDS_TO_PGTYPES:
pg_type = (FIELDS_TO_PGTYPES[field_type], FIELDS_TO_PGTYPES[field_type])
elif issubclass(field_type, fields.float):
if f.digits:
pg_type = ('numeric', 'NUMERIC')
else:
pg_type = ('float8', 'DOUBLE PRECISION')
elif issubclass(field_type, (fields.char, fields.reference)):
pg_type = ('varchar', pg_varchar(f.size))
elif issubclass(field_type, fields.selection):
if (isinstance(f.selection, list) and isinstance(f.selection[0][0], int))\
or getattr(f, 'size', None) == -1:
pg_type = ('int4', 'INTEGER')
else:
pg_type = ('varchar', pg_varchar(getattr(f, 'size', None)))
elif issubclass(field_type, fields.function):
if f._type == 'selection':
pg_type = ('varchar', pg_varchar())
else:
pg_type = get_pg_type(f, getattr(fields, f._type))
else:
_logger.warning('%s type not supported!', field_type)
pg_type = None
return pg_type
class MetaModel(type):
""" Metaclass for the Model.
This class is used as the metaclass for the Model class to discover
the models defined in a module (i.e. without instanciating them).
If the automatic discovery is not needed, it is possible to set the
model's _register attribute to False.
"""
module_to_models = {}
def __init__(self, name, bases, attrs):
if not self._register:
self._register = True
super(MetaModel, self).__init__(name, bases, attrs)
return
# The (OpenERP) module name can be in the `openerp.addons` namespace
# or not. For instance module `sale` can be imported as
# `openerp.addons.sale` (the good way) or `sale` (for backward
# compatibility).
module_parts = self.__module__.split('.')
if len(module_parts) > 2 and module_parts[0] == 'openerp' and \
module_parts[1] == 'addons':
module_name = self.__module__.split('.')[2]
else:
module_name = self.__module__.split('.')[0]
if not hasattr(self, '_module'):
self._module = module_name
# Remember which models to instanciate for this module.
self.module_to_models.setdefault(self._module, []).append(self)
# Definition of log access columns, automatically added to models if
# self._log_access is True
LOG_ACCESS_COLUMNS = {
'create_uid': 'INTEGER REFERENCES res_users ON DELETE SET NULL',
'create_date': 'TIMESTAMP',
'write_uid': 'INTEGER REFERENCES res_users ON DELETE SET NULL',
'write_date': 'TIMESTAMP'
}
# special columns automatically created by the ORM
MAGIC_COLUMNS = ['id'] + LOG_ACCESS_COLUMNS.keys()
class BaseModel(object):
""" Base class for OpenERP models.
OpenERP models are created by inheriting from this class' subclasses:
* Model: for regular database-persisted models
* TransientModel: for temporary data, stored in the database but automatically
vaccuumed every so often
* AbstractModel: for abstract super classes meant to be shared by multiple
_inheriting classes (usually Models or TransientModels)
The system will later instantiate the class once per database (on
which the class' module is installed).
To create a class that should not be instantiated, the _register class attribute
may be set to False.
"""
__metaclass__ = MetaModel
_register = False # Set to false if the model shouldn't be automatically discovered.
_name = None
_columns = {}
_constraints = []
_defaults = {}
_rec_name = 'name'
_parent_name = 'parent_id'
_parent_store = False
_parent_order = False
_date_name = 'date'
_order = 'id'
_sequence = None
_description = None
# dict of {field:method}, with method returning the name_get of records
# to include in the _read_group, if grouped on this field
_group_by_full = {}
# Transience
_transient = False # True in a TransientModel
_transient_max_count = None
_transient_max_hours = None
_transient_check_time = 20
# structure:
# { 'parent_model': 'm2o_field', ... }
_inherits = {}
# Mapping from inherits'd field name to triple (m, r, f, n) where m is the
# model from which it is inherits'd, r is the (local) field towards m, f
# is the _column object itself, and n is the original (i.e. top-most)
# parent model.
# Example:
# { 'field_name': ('parent_model', 'm2o_field_to_reach_parent',
# field_column_obj, origina_parent_model), ... }
_inherit_fields = {}
# Mapping field name/column_info object
# This is similar to _inherit_fields but:
# 1. includes self fields,
# 2. uses column_info instead of a triple.
_all_columns = {}
_table = None
_invalids = set()
_log_create = False
_sql_constraints = []
_protected = ['read', 'write', 'create', 'default_get', 'perm_read', 'unlink', 'fields_get', 'fields_view_get', 'search', 'name_get', 'distinct_field_get', 'name_search', 'copy', 'import_data', 'search_count', 'exists']
CONCURRENCY_CHECK_FIELD = '__last_update'
def log(self, cr, uid, id, message, secondary=False, context=None):
if context and context.get('disable_log'):
return True
return self.pool.get('res.log').create(cr, uid,
{
'name': message,
'res_model': self._name,
'secondary': secondary,
'res_id': id,
},
context=context
)
def view_init(self, cr, uid, fields_list, context=None):
"""Override this method to do specific things when a view on the object is opened."""
pass
def _field_create(self, cr, context=None):
""" Create entries in ir_model_fields for all the model's fields.
If necessary, also create an entry in ir_model, and if called from the
modules loading scheme (by receiving 'module' in the context), also
create entries in ir_model_data (for the model and the fields).
- create an entry in ir_model (if there is not already one),
- create an entry in ir_model_data (if there is not already one, and if
'module' is in the context),
- update ir_model_fields with the fields found in _columns
(TODO there is some redundancy as _columns is updated from
ir_model_fields in __init__).
"""
if context is None:
context = {}
cr.execute("SELECT id FROM ir_model WHERE model=%s", (self._name,))
if not cr.rowcount:
cr.execute('SELECT nextval(%s)', ('ir_model_id_seq',))
model_id = cr.fetchone()[0]
cr.execute("INSERT INTO ir_model (id,model, name, info,state) VALUES (%s, %s, %s, %s, %s)", (model_id, self._name, self._description, self.__doc__, 'base'))
else:
model_id = cr.fetchone()[0]
if 'module' in context:
name_id = 'model_'+self._name.replace('.', '_')
cr.execute('select * from ir_model_data where name=%s and module=%s', (name_id, context['module']))
if not cr.rowcount:
cr.execute("INSERT INTO ir_model_data (name,date_init,date_update,module,model,res_id) VALUES (%s, (now() at time zone 'UTC'), (now() at time zone 'UTC'), %s, %s, %s)", \
(name_id, context['module'], 'ir.model', model_id)
)
cr.commit()
cr.execute("SELECT * FROM ir_model_fields WHERE model=%s", (self._name,))
cols = {}
for rec in cr.dictfetchall():
cols[rec['name']] = rec
ir_model_fields_obj = self.pool.get('ir.model.fields')
# sparse field should be created at the end, as it depends on its serialized field already existing
model_fields = sorted(self._columns.items(), key=lambda x: 1 if x[1]._type == 'sparse' else 0)
for (k, f) in model_fields:
vals = {
'model_id': model_id,
'model': self._name,
'name': k,
'field_description': f.string.replace("'", " "),
'ttype': f._type,
'relation': f._obj or '',
'view_load': (f.view_load and 1) or 0,
'select_level': tools.ustr(f.select or 0),
'readonly': (f.readonly and 1) or 0,
'required': (f.required and 1) or 0,
'selectable': (f.selectable and 1) or 0,
'translate': (f.translate and 1) or 0,
'relation_field': (f._type=='one2many' and isinstance(f, fields.one2many)) and f._fields_id or '',
'serialization_field_id': None,
}
if getattr(f, 'serialization_field', None):
# resolve link to serialization_field if specified by name
serialization_field_id = ir_model_fields_obj.search(cr, 1, [('model','=',vals['model']), ('name', '=', f.serialization_field)])
if not serialization_field_id:
raise except_orm(_('Error'), _("Serialization field `%s` not found for sparse field `%s`!") % (f.serialization_field, k))
vals['serialization_field_id'] = serialization_field_id[0]
# When its a custom field,it does not contain f.select
if context.get('field_state', 'base') == 'manual':
if context.get('field_name', '') == k:
vals['select_level'] = context.get('select', '0')
#setting value to let the problem NOT occur next time
elif k in cols:
vals['select_level'] = cols[k]['select_level']
if k not in cols:
cr.execute('select nextval(%s)', ('ir_model_fields_id_seq',))
id = cr.fetchone()[0]
vals['id'] = id
cr.execute("""INSERT INTO ir_model_fields (
id, model_id, model, name, field_description, ttype,
relation,view_load,state,select_level,relation_field, translate, serialization_field_id
) VALUES (
%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s
)""", (
id, vals['model_id'], vals['model'], vals['name'], vals['field_description'], vals['ttype'],
vals['relation'], bool(vals['view_load']), 'base',
vals['select_level'], vals['relation_field'], bool(vals['translate']), vals['serialization_field_id']
))
if 'module' in context:
name1 = 'field_' + self._table + '_' + k
cr.execute("select name from ir_model_data where name=%s", (name1,))
if cr.fetchone():
name1 = name1 + "_" + str(id)
cr.execute("INSERT INTO ir_model_data (name,date_init,date_update,module,model,res_id) VALUES (%s, (now() at time zone 'UTC'), (now() at time zone 'UTC'), %s, %s, %s)", \
(name1, context['module'], 'ir.model.fields', id)
)
else:
for key, val in vals.items():
if cols[k][key] != vals[key]:
cr.execute('update ir_model_fields set field_description=%s where model=%s and name=%s', (vals['field_description'], vals['model'], vals['name']))
cr.commit()
cr.execute("""UPDATE ir_model_fields SET
model_id=%s, field_description=%s, ttype=%s, relation=%s,
view_load=%s, select_level=%s, readonly=%s ,required=%s, selectable=%s, relation_field=%s, translate=%s, serialization_field_id=%s
WHERE
model=%s AND name=%s""", (
vals['model_id'], vals['field_description'], vals['ttype'],
vals['relation'], bool(vals['view_load']),
vals['select_level'], bool(vals['readonly']), bool(vals['required']), bool(vals['selectable']), vals['relation_field'], bool(vals['translate']), vals['serialization_field_id'], vals['model'], vals['name']
))
break
cr.commit()
#
# Goal: try to apply inheritance at the instanciation level and
# put objects in the pool var
#
@classmethod
def create_instance(cls, pool, cr):
""" Instanciate a given model.
This class method instanciates the class of some model (i.e. a class
deriving from osv or osv_memory). The class might be the class passed
in argument or, if it inherits from another class, a class constructed
by combining the two classes.
The ``attributes`` argument specifies which parent class attributes
have to be combined.
TODO: the creation of the combined class is repeated at each call of
this method. This is probably unnecessary.
"""
attributes = ['_columns', '_defaults', '_inherits', '_constraints',
'_sql_constraints']
parent_names = getattr(cls, '_inherit', None)
if parent_names:
if isinstance(parent_names, (str, unicode)):
name = cls._name or parent_names
parent_names = [parent_names]
else:
name = cls._name
if not name:
raise TypeError('_name is mandatory in case of multiple inheritance')
for parent_name in ((type(parent_names)==list) and parent_names or [parent_names]):
parent_model = pool.get(parent_name)
if not parent_model:
raise TypeError('The model "%s" specifies an unexisting parent class "%s"\n'
'You may need to add a dependency on the parent class\' module.' % (name, parent_name))
if not getattr(cls, '_original_module', None) and name == parent_model._name:
cls._original_module = parent_model._original_module
parent_class = parent_model.__class__
nattr = {}
for s in attributes:
new = copy.copy(getattr(parent_model, s, {}))
if s == '_columns':
# Don't _inherit custom fields.
for c in new.keys():
if new[c].manual:
del new[c]
# Duplicate float fields because they have a .digits
# cache (which must be per-registry, not server-wide).
for c in new.keys():
if new[c]._type == 'float':
new[c] = copy.copy(new[c])
if hasattr(new, 'update'):
new.update(cls.__dict__.get(s, {}))
elif s=='_constraints':
for c in cls.__dict__.get(s, []):
exist = False
for c2 in range(len(new)):
#For _constraints, we should check field and methods as well
if new[c2][2]==c[2] and (new[c2][0] == c[0] \
or getattr(new[c2][0],'__name__', True) == \
getattr(c[0],'__name__', False)):
# If new class defines a constraint with
# same function name, we let it override
# the old one.
new[c2] = c
exist = True
break
if not exist:
new.append(c)
else:
new.extend(cls.__dict__.get(s, []))
nattr[s] = new
cls = type(name, (cls, parent_class), dict(nattr, _register=False))
if not getattr(cls, '_original_module', None):
cls._original_module = cls._module
obj = object.__new__(cls)
obj.__init__(pool, cr)
return obj
def __new__(cls):
"""Register this model.
This doesn't create an instance but simply register the model
as being part of the module where it is defined.
"""
# Set the module name (e.g. base, sale, accounting, ...) on the class.
module = cls.__module__.split('.')[0]
if not hasattr(cls, '_module'):
cls._module = module
# Record this class in the list of models to instantiate for this module,
# managed by the metaclass.
module_model_list = MetaModel.module_to_models.setdefault(cls._module, [])
if cls not in module_model_list:
module_model_list.append(cls)
# Since we don't return an instance here, the __init__
# method won't be called.
return None
def __init__(self, pool, cr):
""" Initialize a model and make it part of the given registry.
- copy the stored fields' functions in the osv_pool,
- update the _columns with the fields found in ir_model_fields,
- ensure there is a many2one for each _inherits'd parent,
- update the children's _columns,
- give a chance to each field to initialize itself.
"""
pool.add(self._name, self)
self.pool = pool
if not self._name and not hasattr(self, '_inherit'):
name = type(self).__name__.split('.')[0]
msg = "The class %s has to have a _name attribute" % name
_logger.error(msg)
raise except_orm('ValueError', msg)
if not self._description:
self._description = self._name
if not self._table:
self._table = self._name.replace('.', '_')
if not hasattr(self, '_log_access'):
# If _log_access is not specified, it is the same value as _auto.
self._log_access = getattr(self, "_auto", True)
self._columns = self._columns.copy()
for store_field in self._columns:
f = self._columns[store_field]
if hasattr(f, 'digits_change'):
f.digits_change(cr)
def not_this_field(stored_func):
x, y, z, e, f, l = stored_func
return x != self._name or y != store_field
self.pool._store_function[self._name] = filter(not_this_field, self.pool._store_function.get(self._name, []))
if not isinstance(f, fields.function):
continue
if not f.store:
continue
sm = f.store
if sm is True:
sm = {self._name: (lambda self, cr, uid, ids, c={}: ids, None, 10, None)}
for object, aa in sm.items():
if len(aa) == 4:
(fnct, fields2, order, length) = aa
elif len(aa) == 3:
(fnct, fields2, order) = aa
length = None
else:
raise except_orm('Error',
('Invalid function definition %s in object %s !\nYou must use the definition: store={object:(fnct, fields, priority, time length)}.' % (store_field, self._name)))
self.pool._store_function.setdefault(object, [])
self.pool._store_function[object].append((self._name, store_field, fnct, tuple(fields2) if fields2 else None, order, length))
self.pool._store_function[object].sort(lambda x, y: cmp(x[4], y[4]))
for (key, _, msg) in self._sql_constraints:
self.pool._sql_error[self._table+'_'+key] = msg
# Load manual fields
cr.execute("SELECT id FROM ir_model_fields WHERE name=%s AND model=%s", ('state', 'ir.model.fields'))
if cr.fetchone():
cr.execute('SELECT * FROM ir_model_fields WHERE model=%s AND state=%s', (self._name, 'manual'))
for field in cr.dictfetchall():
if field['name'] in self._columns:
continue
attrs = {
'string': field['field_description'],
'required': bool(field['required']),
'readonly': bool(field['readonly']),
'domain': eval(field['domain']) if field['domain'] else None,
'size': field['size'],
'ondelete': field['on_delete'],
'translate': (field['translate']),
'manual': True,
#'select': int(field['select_level'])
}
if field['serialization_field_id']:
cr.execute('SELECT name FROM ir_model_fields WHERE id=%s', (field['serialization_field_id'],))
attrs.update({'serialization_field': cr.fetchone()[0], 'type': field['ttype']})
if field['ttype'] in ['many2one', 'one2many', 'many2many']:
attrs.update({'relation': field['relation']})
self._columns[field['name']] = fields.sparse(**attrs)
elif field['ttype'] == 'selection':
self._columns[field['name']] = fields.selection(eval(field['selection']), **attrs)
elif field['ttype'] == 'reference':
self._columns[field['name']] = fields.reference(selection=eval(field['selection']), **attrs)
elif field['ttype'] == 'many2one':
self._columns[field['name']] = fields.many2one(field['relation'], **attrs)
elif field['ttype'] == 'one2many':
self._columns[field['name']] = fields.one2many(field['relation'], field['relation_field'], **attrs)
elif field['ttype'] == 'many2many':
_rel1 = field['relation'].replace('.', '_')
_rel2 = field['model'].replace('.', '_')
_rel_name = 'x_%s_%s_%s_rel' % (_rel1, _rel2, field['name'])
self._columns[field['name']] = fields.many2many(field['relation'], _rel_name, 'id1', 'id2', **attrs)
else:
self._columns[field['name']] = getattr(fields, field['ttype'])(**attrs)
self._inherits_check()
self._inherits_reload()
if not self._sequence:
self._sequence = self._table + '_id_seq'
for k in self._defaults:
assert (k in self._columns) or (k in self._inherit_fields), 'Default function defined in %s but field %s does not exist !' % (self._name, k,)
for f in self._columns:
self._columns[f].restart()
# Transience
if self.is_transient():
self._transient_check_count = 0
self._transient_max_count = config.get('osv_memory_count_limit')
self._transient_max_hours = config.get('osv_memory_age_limit')
assert self._log_access, "TransientModels must have log_access turned on, "\
"in order to implement their access rights policy"
def __export_row(self, cr, uid, row, fields, context=None):
if context is None:
context = {}
def check_type(field_type):
if field_type == 'float':
return 0.0
elif field_type == 'integer':
return 0
elif field_type == 'boolean':
return 'False'
return ''
def selection_field(in_field):
col_obj = self.pool.get(in_field.keys()[0])
if f[i] in col_obj._columns.keys():
return col_obj._columns[f[i]]
elif f[i] in col_obj._inherits.keys():
selection_field(col_obj._inherits)
else:
return False
def _get_xml_id(self, cr, uid, r):
model_data = self.pool.get('ir.model.data')
data_ids = model_data.search(cr, uid, [('model', '=', r._table_name), ('res_id', '=', r['id'])])
if len(data_ids):
d = model_data.read(cr, uid, data_ids, ['name', 'module'])[0]
if d['module']:
r = '%s.%s' % (d['module'], d['name'])
else:
r = d['name']
else:
postfix = 0
while True:
n = self._table+'_'+str(r['id']) + (postfix and ('_'+str(postfix)) or '' )
if not model_data.search(cr, uid, [('name', '=', n)]):
break
postfix += 1
model_data.create(cr, SUPERUSER_ID, {
'name': n,
'model': self._name,
'res_id': r['id'],
'module': '__export__',
})
r = '__export__.'+n
return r
lines = []
data = map(lambda x: '', range(len(fields)))
done = []
for fpos in range(len(fields)):
f = fields[fpos]
if f:
r = row
i = 0
while i < len(f):
cols = False
if f[i] == '.id':
r = r['id']
elif f[i] == 'id':
r = _get_xml_id(self, cr, uid, r)
else:
r = r[f[i]]
# To display external name of selection field when its exported
if f[i] in self._columns.keys():
cols = self._columns[f[i]]
elif f[i] in self._inherit_fields.keys():
cols = selection_field(self._inherits)
if cols and cols._type == 'selection':
sel_list = cols.selection
if r and type(sel_list) == type([]):
r = [x[1] for x in sel_list if r==x[0]]
r = r and r[0] or False
if not r:
if f[i] in self._columns:
r = check_type(self._columns[f[i]]._type)
elif f[i] in self._inherit_fields:
r = check_type(self._inherit_fields[f[i]][2]._type)
data[fpos] = r or False
break
if isinstance(r, (browse_record_list, list)):
first = True
fields2 = map(lambda x: (x[:i+1]==f[:i+1] and x[i+1:]) \
or [], fields)
if fields2 in done:
if [x for x in fields2 if x]:
break
done.append(fields2)
if cols and cols._type=='many2many' and len(fields[fpos])>(i+1) and (fields[fpos][i+1]=='id'):
data[fpos] = ','.join([_get_xml_id(self, cr, uid, x) for x in r])
break
for row2 in r:
lines2 = row2._model.__export_row(cr, uid, row2, fields2,
context)
if first:
for fpos2 in range(len(fields)):
if lines2 and lines2[0][fpos2]:
data[fpos2] = lines2[0][fpos2]
if not data[fpos]:
dt = ''
for rr in r:
name_relation = self.pool.get(rr._table_name)._rec_name
if isinstance(rr[name_relation], browse_record):
rr = rr[name_relation]
rr_name = self.pool.get(rr._table_name).name_get(cr, uid, [rr.id], context=context)
rr_name = rr_name and rr_name[0] and rr_name[0][1] or ''
dt += tools.ustr(rr_name or '') + ','
data[fpos] = dt[:-1]
break
lines += lines2[1:]
first = False
else:
lines += lines2
break
i += 1
if i == len(f):
if isinstance(r, browse_record):
r = self.pool.get(r._table_name).name_get(cr, uid, [r.id], context=context)
r = r and r[0] and r[0][1] or ''
data[fpos] = tools.ustr(r or '')
return [data] + lines
def export_data(self, cr, uid, ids, fields_to_export, context=None):
"""
Export fields for selected objects
:param cr: database cursor
:param uid: current user id
:param ids: list of ids
:param fields_to_export: list of fields
:param context: context arguments, like lang, time zone
:rtype: dictionary with a *datas* matrix
This method is used when exporting data via client menu
"""
if context is None:
context = {}
cols = self._columns.copy()
for f in self._inherit_fields:
cols.update({f: self._inherit_fields[f][2]})
fields_to_export = map(fix_import_export_id_paths, fields_to_export)
datas = []
for row in self.browse(cr, uid, ids, context):
datas += self.__export_row(cr, uid, row, fields_to_export, context)
return {'datas': datas}
def import_data(self, cr, uid, fields, datas, mode='init', current_module='', noupdate=False, context=None, filename=None):
"""Import given data in given module
This method is used when importing data via client menu.
Example of fields to import for a sale.order::
.id, (=database_id)
partner_id, (=name_search)
order_line/.id, (=database_id)
order_line/name,
order_line/product_id/id, (=xml id)
order_line/price_unit,
order_line/product_uom_qty,
order_line/product_uom/id (=xml_id)
This method returns a 4-tuple with the following structure::
(return_code, errored_resource, error_message, unused)
* The first item is a return code, it is ``-1`` in case of
import error, or the last imported row number in case of success
* The second item contains the record data dict that failed to import
in case of error, otherwise it's 0
* The third item contains an error message string in case of error,
otherwise it's 0
* The last item is currently unused, with no specific semantics
:param fields: list of fields to import
:param data: data to import
:param mode: 'init' or 'update' for record creation
:param current_module: module name
:param noupdate: flag for record creation
:param filename: optional file to store partial import state for recovery
:returns: 4-tuple in the form (return_code, errored_resource, error_message, unused)
:rtype: (int, dict or 0, str or 0, str or 0)
"""
if not context:
context = {}
fields = map(fix_import_export_id_paths, fields)
ir_model_data_obj = self.pool.get('ir.model.data')
# mode: id (XML id) or .id (database id) or False for name_get
def _get_id(model_name, id, current_module=False, mode='id'):
if mode=='.id':
id = int(id)
obj_model = self.pool.get(model_name)
ids = obj_model.search(cr, uid, [('id', '=', int(id))])
if not len(ids):
raise Exception(_("Database ID doesn't exist: %s : %s") %(model_name, id))
elif mode=='id':
if '.' in id:
module, xml_id = id.rsplit('.', 1)
else:
module, xml_id = current_module, id
record_id = ir_model_data_obj._get_id(cr, uid, module, xml_id)
ir_model_data = ir_model_data_obj.read(cr, uid, [record_id], ['res_id'])
if not ir_model_data:
raise ValueError('No references to %s.%s' % (module, xml_id))
id = ir_model_data[0]['res_id']
else:
obj_model = self.pool.get(model_name)
ids = obj_model.name_search(cr, uid, id, operator='=', context=context)
if not ids:
raise ValueError('No record found for %s' % (id,))
id = ids[0][0]
return id
# IN:
# datas: a list of records, each record is defined by a list of values
# prefix: a list of prefix fields ['line_ids']
# position: the line to process, skip is False if it's the first line of the current record
# OUT:
# (res, position, warning, res_id) with
# res: the record for the next line to process (including it's one2many)
# position: the new position for the next line
# res_id: the ID of the record if it's a modification
def process_liness(self, datas, prefix, current_module, model_name, fields_def, position=0, skip=0):
line = datas[position]
row = {}
warning = []
data_res_id = False
xml_id = False
nbrmax = position+1
done = {}
for i, field in enumerate(fields):
res = False
if i >= len(line):
raise Exception(_('Please check that all your lines have %d columns.'
'Stopped around line %d having %d columns.') % \
(len(fields), position+2, len(line)))
if not line[i]:
continue
if field[:len(prefix)] <> prefix:
if line[i] and skip:
return False
continue
field_name = field[len(prefix)]
#set the mode for m2o, o2m, m2m : xml_id/id/name
if len(field) == len(prefix)+1:
mode = False
else:
mode = field[len(prefix)+1]
# TODO: improve this by using csv.csv_reader
def many_ids(line, relation, current_module, mode):
res = []
for db_id in line.split(config.get('csv_internal_sep')):
res.append(_get_id(relation, db_id, current_module, mode))
return [(6,0,res)]
# ID of the record using a XML ID
if field_name == 'id':
try:
data_res_id = _get_id(model_name, line[i], current_module)
except ValueError:
pass
xml_id = line[i]
continue
# ID of the record using a database ID
elif field_name == '.id':
data_res_id = _get_id(model_name, line[i], current_module, '.id')
continue
field_type = fields_def[field_name]['type']
# recursive call for getting children and returning [(0,0,{})] or [(1,ID,{})]
if field_type == 'one2many':
if field_name in done:
continue
done[field_name] = True
relation = fields_def[field_name]['relation']
relation_obj = self.pool.get(relation)
newfd = relation_obj.fields_get( cr, uid, context=context )
pos = position
res = []
first = 0
while pos < len(datas):
res2 = process_liness(self, datas, prefix + [field_name], current_module, relation_obj._name, newfd, pos, first)
if not res2:
break
(newrow, pos, w2, data_res_id2, xml_id2) = res2
nbrmax = max(nbrmax, pos)
warning += w2
first += 1
if (not newrow) or not reduce(lambda x, y: x or y, newrow.values(), 0):
break
res.append( (data_res_id2 and 1 or 0, data_res_id2 or 0, newrow) )
elif field_type == 'many2one':
relation = fields_def[field_name]['relation']
res = _get_id(relation, line[i], current_module, mode)
elif field_type == 'many2many':
relation = fields_def[field_name]['relation']
res = many_ids(line[i], relation, current_module, mode)
elif field_type == 'integer':
res = line[i] and int(line[i]) or 0
elif field_type == 'boolean':
res = line[i].lower() not in ('0', 'false', 'off')
elif field_type == 'float':
res = line[i] and float(line[i]) or 0.0
elif field_type == 'selection':
for key, val in fields_def[field_name]['selection']:
if tools.ustr(line[i]) in [tools.ustr(key), tools.ustr(val)]:
res = key
break
if line[i] and not res:
_logger.warning(
_("key '%s' not found in selection field '%s'"),
tools.ustr(line[i]), tools.ustr(field_name))
warning.append(_("Key/value '%s' not found in selection field '%s'") % (
tools.ustr(line[i]), tools.ustr(field_name)))
else:
res = line[i]
row[field_name] = res or False
return row, nbrmax, warning, data_res_id, xml_id
fields_def = self.fields_get(cr, uid, context=context)
position = 0
if config.get('import_partial') and filename:
with open(config.get('import_partial'), 'rb') as partial_import_file:
data = pickle.load(partial_import_file)
position = data.get(filename, 0)
while position<len(datas):
(res, position, warning, res_id, xml_id) = \
process_liness(self, datas, [], current_module, self._name, fields_def, position=position)
if len(warning):
cr.rollback()
return -1, res, 'Line ' + str(position) +' : ' + '!\n'.join(warning), ''
try:
ir_model_data_obj._update(cr, uid, self._name,
current_module, res, mode=mode, xml_id=xml_id,
noupdate=noupdate, res_id=res_id, context=context)
except Exception, e:
return -1, res, 'Line ' + str(position) + ' : ' + tools.ustr(e), ''
if config.get('import_partial') and filename and (not (position%100)):
with open(config.get('import_partial'), 'rb') as partial_import:
data = pickle.load(partial_import)
data[filename] = position
with open(config.get('import_partial'), 'wb') as partial_import:
pickle.dump(data, partial_import)
if context.get('defer_parent_store_computation'):
self._parent_store_compute(cr)
cr.commit()
if context.get('defer_parent_store_computation'):
self._parent_store_compute(cr)
return position, 0, 0, 0
def get_invalid_fields(self, cr, uid):
return list(self._invalids)
def _validate(self, cr, uid, ids, context=None):
context = context or {}
lng = context.get('lang', False) or 'en_US'
trans = self.pool.get('ir.translation')
error_msgs = []
for constraint in self._constraints:
fun, msg, fields = constraint
if not fun(self, cr, uid, ids):
# Check presence of __call__ directly instead of using
# callable() because it will be deprecated as of Python 3.0
if hasattr(msg, '__call__'):
tmp_msg = msg(self, cr, uid, ids, context=context)
if isinstance(tmp_msg, tuple):
tmp_msg, params = tmp_msg
translated_msg = tmp_msg % params
else:
translated_msg = tmp_msg
else:
translated_msg = trans._get_source(cr, uid, self._name, 'constraint', lng, msg) or msg
error_msgs.append(
_("Error occurred while validating the field(s) %s: %s") % (','.join(fields), translated_msg)
)
self._invalids.update(fields)
if error_msgs:
cr.rollback()
raise except_orm('ValidateError', '\n'.join(error_msgs))
else:
self._invalids.clear()
def default_get(self, cr, uid, fields_list, context=None):
"""
Returns default values for the fields in fields_list.
:param fields_list: list of fields to get the default values for (example ['field1', 'field2',])
:type fields_list: list
:param context: optional context dictionary - it may contains keys for specifying certain options
like ``context_lang`` (language) or ``context_tz`` (timezone) to alter the results of the call.
It may contain keys in the form ``default_XXX`` (where XXX is a field name), to set
or override a default value for a field.
A special ``bin_size`` boolean flag may also be passed in the context to request the
value of all fields.binary columns to be returned as the size of the binary instead of its
contents. This can also be selectively overriden by passing a field-specific flag
in the form ``bin_size_XXX: True/False`` where ``XXX`` is the name of the field.
Note: The ``bin_size_XXX`` form is new in OpenERP v6.0.
:return: dictionary of the default values (set on the object model class, through user preferences, or in the context)
"""
# trigger view init hook
self.view_init(cr, uid, fields_list, context)
if not context:
context = {}
defaults = {}
# get the default values for the inherited fields
for t in self._inherits.keys():
defaults.update(self.pool.get(t).default_get(cr, uid, fields_list,
context))
# get the default values defined in the object
for f in fields_list:
if f in self._defaults:
if callable(self._defaults[f]):
defaults[f] = self._defaults[f](self, cr, uid, context)
else:
defaults[f] = self._defaults[f]
fld_def = ((f in self._columns) and self._columns[f]) \
or ((f in self._inherit_fields) and self._inherit_fields[f][2]) \
or False
if isinstance(fld_def, fields.property):
property_obj = self.pool.get('ir.property')
prop_value = property_obj.get(cr, uid, f, self._name, context=context)
if prop_value:
if isinstance(prop_value, (browse_record, browse_null)):
defaults[f] = prop_value.id
else:
defaults[f] = prop_value
else:
if f not in defaults:
defaults[f] = False
# get the default values set by the user and override the default
# values defined in the object
ir_values_obj = self.pool.get('ir.values')
res = ir_values_obj.get(cr, uid, 'default', False, [self._name])
for id, field, field_value in res:
if field in fields_list:
fld_def = (field in self._columns) and self._columns[field] or self._inherit_fields[field][2]
if fld_def._type in ('many2one', 'one2one'):
obj = self.pool.get(fld_def._obj)
if not obj.search(cr, uid, [('id', '=', field_value or False)]):
continue
if fld_def._type in ('many2many'):
obj = self.pool.get(fld_def._obj)
field_value2 = []
for i in range(len(field_value)):
if not obj.search(cr, uid, [('id', '=',
field_value[i])]):
continue
field_value2.append(field_value[i])
field_value = field_value2
if fld_def._type in ('one2many'):
obj = self.pool.get(fld_def._obj)
field_value2 = []
for i in range(len(field_value)):
field_value2.append({})
for field2 in field_value[i]:
if field2 in obj._columns.keys() and obj._columns[field2]._type in ('many2one', 'one2one'):
obj2 = self.pool.get(obj._columns[field2]._obj)
if not obj2.search(cr, uid,
[('id', '=', field_value[i][field2])]):
continue
elif field2 in obj._inherit_fields.keys() and obj._inherit_fields[field2][2]._type in ('many2one', 'one2one'):
obj2 = self.pool.get(obj._inherit_fields[field2][2]._obj)
if not obj2.search(cr, uid,
[('id', '=', field_value[i][field2])]):
continue
# TODO add test for many2many and one2many
field_value2[i][field2] = field_value[i][field2]
field_value = field_value2
defaults[field] = field_value
# get the default values from the context
for key in context or {}:
if key.startswith('default_') and (key[8:] in fields_list):
defaults[key[8:]] = context[key]
return defaults
def fields_get_keys(self, cr, user, context=None):
res = self._columns.keys()
# TODO I believe this loop can be replace by
# res.extend(self._inherit_fields.key())
for parent in self._inherits:
res.extend(self.pool.get(parent).fields_get_keys(cr, user, context))
return res
#
# Overload this method if you need a window title which depends on the context
#
def view_header_get(self, cr, user, view_id=None, view_type='form', context=None):
return False
def __view_look_dom(self, cr, user, node, view_id, in_tree_view, model_fields, context=None):
""" Return the description of the fields in the node.
In a normal call to this method, node is a complete view architecture
but it is actually possible to give some sub-node (this is used so
that the method can call itself recursively).
Originally, the field descriptions are drawn from the node itself.
But there is now some code calling fields_get() in order to merge some
of those information in the architecture.
"""
if context is None:
context = {}
result = False
fields = {}
children = True
modifiers = {}
def encode(s):
if isinstance(s, unicode):
return s.encode('utf8')
return s
def check_group(node):
""" Set invisible to true if the user is not in the specified groups. """
if node.get('groups'):
groups = node.get('groups').split(',')
ir_model_access = self.pool.get('ir.model.access')
can_see = any(ir_model_access.check_groups(cr, user, group) for group in groups)
if not can_see:
node.set('invisible', '1')
modifiers['invisible'] = True
if 'attrs' in node.attrib:
del(node.attrib['attrs']) #avoid making field visible later
del(node.attrib['groups'])
if node.tag in ('field', 'node', 'arrow'):
if node.get('object'):
attrs = {}
views = {}
xml = "<form>"
for f in node:
if f.tag in ('field'):
xml += etree.tostring(f, encoding="utf-8")
xml += "</form>"
new_xml = etree.fromstring(encode(xml))
ctx = context.copy()
ctx['base_model_name'] = self._name
xarch, xfields = self.pool.get(node.get('object')).__view_look_dom_arch(cr, user, new_xml, view_id, ctx)
views['form'] = {
'arch': xarch,
'fields': xfields
}
attrs = {'views': views}
fields = xfields
if node.get('name'):
attrs = {}
try:
if node.get('name') in self._columns:
column = self._columns[node.get('name')]
else:
column = self._inherit_fields[node.get('name')][2]
except Exception:
column = False
if column:
relation = self.pool.get(column._obj)
children = False
views = {}
for f in node:
if f.tag in ('form', 'tree', 'graph'):
node.remove(f)
ctx = context.copy()
ctx['base_model_name'] = self._name
xarch, xfields = relation.__view_look_dom_arch(cr, user, f, view_id, ctx)
views[str(f.tag)] = {
'arch': xarch,
'fields': xfields
}
attrs = {'views': views}
if node.get('widget') and node.get('widget') == 'selection':
# Prepare the cached selection list for the client. This needs to be
# done even when the field is invisible to the current user, because
# other events could need to change its value to any of the selectable ones
# (such as on_change events, refreshes, etc.)
# If domain and context are strings, we keep them for client-side, otherwise
# we evaluate them server-side to consider them when generating the list of
# possible values
# TODO: find a way to remove this hack, by allow dynamic domains
dom = []
if column._domain and not isinstance(column._domain, basestring):
dom = column._domain
dom = dom + eval(node.get('domain', '[]'), {'uid': user, 'time': time})
search_context = dict(context)
if column._context and not isinstance(column._context, basestring):
search_context.update(column._context)
attrs['selection'] = relation._name_search(cr, user, '', dom, context=search_context, limit=None, name_get_uid=1)
if (node.get('required') and not int(node.get('required'))) or not column.required:
attrs['selection'].append((False, ''))
fields[node.get('name')] = attrs
field = model_fields.get(node.get('name'))
if field:
transfer_field_to_modifiers(field, modifiers)
elif node.tag in ('form', 'tree'):
result = self.view_header_get(cr, user, False, node.tag, context)
if result:
node.set('string', result)
in_tree_view = node.tag == 'tree'
elif node.tag == 'calendar':
for additional_field in ('date_start', 'date_delay', 'date_stop', 'color'):
if node.get(additional_field):
fields[node.get(additional_field)] = {}
check_group(node)
# The view architeture overrides the python model.
# Get the attrs before they are (possibly) deleted by check_group below
transfer_node_to_modifiers(node, modifiers, context, in_tree_view)
# TODO remove attrs couterpart in modifiers when invisible is true ?
# translate view
if 'lang' in context:
if node.get('string') and not result:
trans = self.pool.get('ir.translation')._get_source(cr, user, self._name, 'view', context['lang'], node.get('string'))
if trans == node.get('string') and ('base_model_name' in context):
# If translation is same as source, perhaps we'd have more luck with the alternative model name
# (in case we are in a mixed situation, such as an inherited view where parent_view.model != model
trans = self.pool.get('ir.translation')._get_source(cr, user, context['base_model_name'], 'view', context['lang'], node.get('string'))
if trans:
node.set('string', trans)
if node.get('confirm'):
trans = self.pool.get('ir.translation')._get_source(cr, user, self._name, 'view', context['lang'], node.get('confirm'))
if trans:
node.set('confirm', trans)
if node.get('sum'):
trans = self.pool.get('ir.translation')._get_source(cr, user, self._name, 'view', context['lang'], node.get('sum'))
if trans:
node.set('sum', trans)
if node.get('avg'):
trans = self.pool.get('ir.translation')._get_source(cr, user, self._name, 'view', context['lang'], node.get('avg'))
if trans:
node.set('avg', trans)
if node.get('help'):
trans = self.pool.get('ir.translation')._get_source(cr, user, self._name, 'view', context['lang'], node.get('help'))
if trans:
node.set('help', trans)
for f in node:
if children or (node.tag == 'field' and f.tag in ('filter','separator')):
fields.update(self.__view_look_dom(cr, user, f, view_id, in_tree_view, model_fields, context))
transfer_modifiers_to_node(modifiers, node)
return fields
def _disable_workflow_buttons(self, cr, user, node):
""" Set the buttons in node to readonly if the user can't activate them. """
if user == 1:
# admin user can always activate workflow buttons
return node
# TODO handle the case of more than one workflow for a model or multiple
# transitions with different groups and same signal
usersobj = self.pool.get('res.users')
buttons = (n for n in node.getiterator('button') if n.get('type') != 'object')
for button in buttons:
user_groups = usersobj.read(cr, user, [user], ['groups_id'])[0]['groups_id']
cr.execute("""SELECT DISTINCT t.group_id
FROM wkf
INNER JOIN wkf_activity a ON a.wkf_id = wkf.id
INNER JOIN wkf_transition t ON (t.act_to = a.id)
WHERE wkf.osv = %s
AND t.signal = %s
AND t.group_id is NOT NULL
""", (self._name, button.get('name')))
group_ids = [x[0] for x in cr.fetchall() if x[0]]
can_click = not group_ids or bool(set(user_groups).intersection(group_ids))
button.set('readonly', str(int(not can_click)))
return node
def __view_look_dom_arch(self, cr, user, node, view_id, context=None):
""" Return an architecture and a description of all the fields.
The field description combines the result of fields_get() and
__view_look_dom().
:param node: the architecture as as an etree
:return: a tuple (arch, fields) where arch is the given node as a
string and fields is the description of all the fields.
"""
fields = {}
if node.tag == 'diagram':
if node.getchildren()[0].tag == 'node':
node_fields = self.pool.get(node.getchildren()[0].get('object')).fields_get(cr, user, None, context)
fields.update(node_fields)
if node.getchildren()[1].tag == 'arrow':
arrow_fields = self.pool.get(node.getchildren()[1].get('object')).fields_get(cr, user, None, context)
fields.update(arrow_fields)
else:
fields = self.fields_get(cr, user, None, context)
fields_def = self.__view_look_dom(cr, user, node, view_id, False, fields, context=context)
node = self._disable_workflow_buttons(cr, user, node)
arch = etree.tostring(node, encoding="utf-8").replace('\t', '')
for k in fields.keys():
if k not in fields_def:
del fields[k]
for field in fields_def:
if field == 'id':
# sometime, the view may contain the (invisible) field 'id' needed for a domain (when 2 objects have cross references)
fields['id'] = {'readonly': True, 'type': 'integer', 'string': 'ID'}
elif field in fields:
fields[field].update(fields_def[field])
else:
cr.execute('select name, model from ir_ui_view where (id=%s or inherit_id=%s) and arch like %s', (view_id, view_id, '%%%s%%' % field))
res = cr.fetchall()[:]
model = res[0][1]
res.insert(0, ("Can't find field '%s' in the following view parts composing the view of object model '%s':" % (field, model), None))
msg = "\n * ".join([r[0] for r in res])
msg += "\n\nEither you wrongly customized this view, or some modules bringing those views are not compatible with your current data model"
_logger.error(msg)
raise except_orm('View error', msg)
return arch, fields
def _get_default_form_view(self, cr, user, context=None):
""" Generates a default single-line form view using all fields
of the current model except the m2m and o2m ones.
:param cr: database cursor
:param int user: user id
:param dict context: connection context
:returns: a form view as an lxml document
:rtype: etree._Element
"""
view = etree.Element('form', string=self._description)
# TODO it seems fields_get can be replaced by _all_columns (no need for translation)
for field, descriptor in self.fields_get(cr, user, context=context).iteritems():
if descriptor['type'] in ('one2many', 'many2many'):
continue
etree.SubElement(view, 'field', name=field)
if descriptor['type'] == 'text':
etree.SubElement(view, 'newline')
return view
def _get_default_tree_view(self, cr, user, context=None):
""" Generates a single-field tree view, using _rec_name if
it's one of the columns or the first column it finds otherwise
:param cr: database cursor
:param int user: user id
:param dict context: connection context
:returns: a tree view as an lxml document
:rtype: etree._Element
"""
_rec_name = self._rec_name
if _rec_name not in self._columns:
_rec_name = self._columns.keys()[0] if len(self._columns.keys()) > 0 else "id"
view = etree.Element('tree', string=self._description)
etree.SubElement(view, 'field', name=_rec_name)
return view
def _get_default_calendar_view(self, cr, user, context=None):
""" Generates a default calendar view by trying to infer
calendar fields from a number of pre-set attribute names
:param cr: database cursor
:param int user: user id
:param dict context: connection context
:returns: a calendar view
:rtype: etree._Element
"""
def set_first_of(seq, in_, to):
"""Sets the first value of ``seq`` also found in ``in_`` to
the ``to`` attribute of the view being closed over.
Returns whether it's found a suitable value (and set it on
the attribute) or not
"""
for item in seq:
if item in in_:
view.set(to, item)
return True
return False
view = etree.Element('calendar', string=self._description)
etree.SubElement(view, 'field', name=self._rec_name)
if (self._date_name not in self._columns):
date_found = False
for dt in ['date', 'date_start', 'x_date', 'x_date_start']:
if dt in self._columns:
self._date_name = dt
date_found = True
break
if not date_found:
raise except_orm(_('Invalid Object Architecture!'), _("Insufficient fields for Calendar View!"))
view.set('date_start', self._date_name)
set_first_of(["user_id", "partner_id", "x_user_id", "x_partner_id"],
self._columns, 'color')
if not set_first_of(["date_stop", "date_end", "x_date_stop", "x_date_end"],
self._columns, 'date_stop'):
if not set_first_of(["date_delay", "planned_hours", "x_date_delay", "x_planned_hours"],
self._columns, 'date_delay'):
raise except_orm(
_('Invalid Object Architecture!'),
_("Insufficient fields to generate a Calendar View for %s, missing a date_stop or a date_delay" % (self._name)))
return view
def _get_default_search_view(self, cr, uid, context=None):
"""
:param cr: database cursor
:param int user: user id
:param dict context: connection context
:returns: an lxml document of the view
:rtype: etree._Element
"""
form_view = self.fields_view_get(cr, uid, False, 'form', context=context)
tree_view = self.fields_view_get(cr, uid, False, 'tree', context=context)
# TODO it seems _all_columns could be used instead of fields_get (no need for translated fields info)
fields = self.fields_get(cr, uid, context=context)
fields_to_search = set(
field for field, descriptor in fields.iteritems()
if descriptor.get('select'))
for view in (form_view, tree_view):
view_root = etree.fromstring(view['arch'])
# Only care about select=1 in xpath below, because select=2 is covered
# by the custom advanced search in clients
fields_to_search.update(view_root.xpath("//field[@select=1]/@name"))
tree_view_root = view_root # as provided by loop above
search_view = etree.Element("search", string=tree_view_root.get("string", ""))
field_group = etree.SubElement(search_view, "group")
for field_name in fields_to_search:
etree.SubElement(field_group, "field", name=field_name)
return search_view
#
# if view_id, view_type is not required
#
def fields_view_get(self, cr, user, view_id=None, view_type='form', context=None, toolbar=False, submenu=False):
"""
Get the detailed composition of the requested view like fields, model, view architecture
:param cr: database cursor
:param user: current user id
:param view_id: id of the view or None
:param view_type: type of the view to return if view_id is None ('form', tree', ...)
:param context: context arguments, like lang, time zone
:param toolbar: true to include contextual actions
:param submenu: deprecated
:return: dictionary describing the composition of the requested view (including inherited views and extensions)
:raise AttributeError:
* if the inherited view has unknown position to work with other than 'before', 'after', 'inside', 'replace'
* if some tag other than 'position' is found in parent view
:raise Invalid ArchitectureError: if there is view type other than form, tree, calendar, search etc defined on the structure
"""
if context is None:
context = {}
def encode(s):
if isinstance(s, unicode):
return s.encode('utf8')
return s
def raise_view_error(error_msg, child_view_id):
view, child_view = self.pool.get('ir.ui.view').browse(cr, user, [view_id, child_view_id], context)
raise AttributeError("View definition error for inherited view '%s' on model '%s': %s"
% (child_view.xml_id, self._name, error_msg))
def locate(source, spec):
""" Locate a node in a source (parent) architecture.
Given a complete source (parent) architecture (i.e. the field
`arch` in a view), and a 'spec' node (a node in an inheriting
view that specifies the location in the source view of what
should be changed), return (if it exists) the node in the
source view matching the specification.
:param source: a parent architecture to modify
:param spec: a modifying node in an inheriting view
:return: a node in the source matching the spec
"""
if spec.tag == 'xpath':
nodes = source.xpath(spec.get('expr'))
return nodes[0] if nodes else None
elif spec.tag == 'field':
# Only compare the field name: a field can be only once in a given view
# at a given level (and for multilevel expressions, we should use xpath
# inheritance spec anyway).
for node in source.getiterator('field'):
if node.get('name') == spec.get('name'):
return node
return None
else:
for node in source.getiterator(spec.tag):
good = True
for attr in spec.attrib:
if attr != 'position' and (not node.get(attr) or node.get(attr) != spec.get(attr)):
good = False
break
if good:
return node
return None
def apply_inheritance_specs(source, specs_arch, inherit_id=None):
""" Apply an inheriting view.
Apply to a source architecture all the spec nodes (i.e. nodes
describing where and what changes to apply to some parent
architecture) given by an inheriting view.
:param source: a parent architecture to modify
:param specs_arch: a modifying architecture in an inheriting view
:param inherit_id: the database id of the inheriting view
:return: a modified source where the specs are applied
"""
specs_tree = etree.fromstring(encode(specs_arch))
# Queue of specification nodes (i.e. nodes describing where and
# changes to apply to some parent architecture).
specs = [specs_tree]
while len(specs):
spec = specs.pop(0)
if isinstance(spec, SKIPPED_ELEMENT_TYPES):
continue
if spec.tag == 'data':
specs += [ c for c in specs_tree ]
continue
node = locate(source, spec)
if node is not None:
pos = spec.get('position', 'inside')
if pos == 'replace':
if node.getparent() is None:
source = copy.deepcopy(spec[0])
else:
for child in spec:
node.addprevious(child)
node.getparent().remove(node)
elif pos == 'attributes':
for child in spec.getiterator('attribute'):
attribute = (child.get('name'), child.text and child.text.encode('utf8') or None)
if attribute[1]:
node.set(attribute[0], attribute[1])
else:
del(node.attrib[attribute[0]])
else:
sib = node.getnext()
for child in spec:
if pos == 'inside':
node.append(child)
elif pos == 'after':
if sib is None:
node.addnext(child)
node = child
else:
sib.addprevious(child)
elif pos == 'before':
node.addprevious(child)
else:
raise_view_error("Invalid position value: '%s'" % pos, inherit_id)
else:
attrs = ''.join([
' %s="%s"' % (attr, spec.get(attr))
for attr in spec.attrib
if attr != 'position'
])
tag = "<%s%s>" % (spec.tag, attrs)
raise_view_error("Element '%s' not found in parent view '%%(parent_xml_id)s'" % tag, inherit_id)
return source
def apply_view_inheritance(cr, user, source, inherit_id):
""" Apply all the (directly and indirectly) inheriting views.
:param source: a parent architecture to modify (with parent
modifications already applied)
:param inherit_id: the database view_id of the parent view
:return: a modified source where all the modifying architecture
are applied
"""
sql_inherit = self.pool.get('ir.ui.view').get_inheriting_views_arch(cr, user, inherit_id, self._name)
for (view_arch, view_id) in sql_inherit:
source = apply_inheritance_specs(source, view_arch, view_id)
source = apply_view_inheritance(cr, user, source, view_id)
return source
result = {'type': view_type, 'model': self._name}
sql_res = False
parent_view_model = None
view_ref = context.get(view_type + '_view_ref')
# Search for a root (i.e. without any parent) view.
while True:
if view_ref and not view_id:
if '.' in view_ref:
module, view_ref = view_ref.split('.', 1)
cr.execute("SELECT res_id FROM ir_model_data WHERE model='ir.ui.view' AND module=%s AND name=%s", (module, view_ref))
view_ref_res = cr.fetchone()
if view_ref_res:
view_id = view_ref_res[0]
if view_id:
cr.execute("""SELECT arch,name,field_parent,id,type,inherit_id,model
FROM ir_ui_view
WHERE id=%s""", (view_id,))
else:
cr.execute("""SELECT arch,name,field_parent,id,type,inherit_id,model
FROM ir_ui_view
WHERE model=%s AND type=%s AND inherit_id IS NULL
ORDER BY priority""", (self._name, view_type))
sql_res = cr.dictfetchone()
if not sql_res:
break
view_id = sql_res['inherit_id'] or sql_res['id']
parent_view_model = sql_res['model']
if not sql_res['inherit_id']:
break
# if a view was found
if sql_res:
source = etree.fromstring(encode(sql_res['arch']))
result.update(
arch=apply_view_inheritance(cr, user, source, sql_res['id']),
type=sql_res['type'],
view_id=sql_res['id'],
name=sql_res['name'],
field_parent=sql_res['field_parent'] or False)
else:
# otherwise, build some kind of default view
try:
view = getattr(self, '_get_default_%s_view' % view_type)(
cr, user, context)
except AttributeError:
# what happens here, graph case?
raise except_orm(_('Invalid Architecture!'), _("There is no view of type '%s' defined for the structure!") % view_type)
result.update(
arch=view,
name='default',
field_parent=False,
view_id=0)
if parent_view_model != self._name:
ctx = context.copy()
ctx['base_model_name'] = parent_view_model
else:
ctx = context
xarch, xfields = self.__view_look_dom_arch(cr, user, result['arch'], view_id, context=ctx)
result['arch'] = xarch
result['fields'] = xfields
if toolbar:
def clean(x):
x = x[2]
for key in ('report_sxw_content', 'report_rml_content',
'report_sxw', 'report_rml',
'report_sxw_content_data', 'report_rml_content_data'):
if key in x:
del x[key]
return x
ir_values_obj = self.pool.get('ir.values')
resprint = ir_values_obj.get(cr, user, 'action',
'client_print_multi', [(self._name, False)], False,
context)
resaction = ir_values_obj.get(cr, user, 'action',
'client_action_multi', [(self._name, False)], False,
context)
resrelate = ir_values_obj.get(cr, user, 'action',
'client_action_relate', [(self._name, False)], False,
context)
resaction = [clean(action) for action in resaction
if view_type == 'tree' or not action[2].get('multi')]
resprint = [clean(print_) for print_ in resprint
if view_type == 'tree' or not print_[2].get('multi')]
resrelate = map(lambda x: x[2], resrelate)
for x in itertools.chain(resprint, resaction, resrelate):
x['string'] = x['name']
result['toolbar'] = {
'print': resprint,
'action': resaction,
'relate': resrelate
}
return result
_view_look_dom_arch = __view_look_dom_arch
def search_count(self, cr, user, args, context=None):
if not context:
context = {}
res = self.search(cr, user, args, context=context, count=True)
if isinstance(res, list):
return len(res)
return res
def search(self, cr, user, args, offset=0, limit=None, order=None, context=None, count=False):
"""
Search for records based on a search domain.
:param cr: database cursor
:param user: current user id
:param args: list of tuples specifying the search domain [('field_name', 'operator', value), ...]. Pass an empty list to match all records.
:param offset: optional number of results to skip in the returned values (default: 0)
:param limit: optional max number of records to return (default: **None**)
:param order: optional columns to sort by (default: self._order=id )
:param context: optional context arguments, like lang, time zone
:type context: dictionary
:param count: optional (default: **False**), if **True**, returns only the number of records matching the criteria, not their ids
:return: id or list of ids of records matching the criteria
:rtype: integer or list of integers
:raise AccessError: * if user tries to bypass access rules for read on the requested object.
**Expressing a search domain (args)**
Each tuple in the search domain needs to have 3 elements, in the form: **('field_name', 'operator', value)**, where:
* **field_name** must be a valid name of field of the object model, possibly following many-to-one relationships using dot-notation, e.g 'street' or 'partner_id.country' are valid values.
* **operator** must be a string with a valid comparison operator from this list: ``=, !=, >, >=, <, <=, like, ilike, in, not in, child_of, parent_left, parent_right``
The semantics of most of these operators are obvious.
The ``child_of`` operator will look for records who are children or grand-children of a given record,
according to the semantics of this model (i.e following the relationship field named by
``self._parent_name``, by default ``parent_id``.
* **value** must be a valid value to compare with the values of **field_name**, depending on its type.
Domain criteria can be combined using 3 logical operators than can be added between tuples: '**&**' (logical AND, default), '**|**' (logical OR), '**!**' (logical NOT).
These are **prefix** operators and the arity of the '**&**' and '**|**' operator is 2, while the arity of the '**!**' is just 1.
Be very careful about this when you combine them the first time.
Here is an example of searching for Partners named *ABC* from Belgium and Germany whose language is not english ::
[('name','=','ABC'),'!',('language.code','=','en_US'),'|',('country_id.code','=','be'),('country_id.code','=','de'))
The '&' is omitted as it is the default, and of course we could have used '!=' for the language, but what this domain really represents is::
(name is 'ABC' AND (language is NOT english) AND (country is Belgium OR Germany))
"""
return self._search(cr, user, args, offset=offset, limit=limit, order=order, context=context, count=count)
def name_get(self, cr, user, ids, context=None):
"""Returns the preferred display value (text representation) for the records with the
given ``ids``. By default this will be the value of the ``name`` column, unless
the model implements a custom behavior.
Can sometimes be seen as the inverse function of :meth:`~.name_search`, but it is not
guaranteed to be.
:rtype: list(tuple)
:return: list of pairs ``(id,text_repr)`` for all records with the given ``ids``.
"""
if not ids:
return []
if isinstance(ids, (int, long)):
ids = [ids]
return [(r['id'], tools.ustr(r[self._rec_name])) for r in self.read(cr, user, ids,
[self._rec_name], context, load='_classic_write')]
def name_search(self, cr, user, name='', args=None, operator='ilike', context=None, limit=100):
"""Search for records that have a display name matching the given ``name`` pattern if compared
with the given ``operator``, while also matching the optional search domain (``args``).
This is used for example to provide suggestions based on a partial value for a relational
field.
Sometimes be seen as the inverse function of :meth:`~.name_get`, but it is not
guaranteed to be.
This method is equivalent to calling :meth:`~.search` with a search domain based on ``name``
and then :meth:`~.name_get` on the result of the search.
:param list args: optional search domain (see :meth:`~.search` for syntax),
specifying further restrictions
:param str operator: domain operator for matching the ``name`` pattern, such as ``'like'``
or ``'='``.
:param int limit: optional max number of records to return
:rtype: list
:return: list of pairs ``(id,text_repr)`` for all matching records.
"""
return self._name_search(cr, user, name, args, operator, context, limit)
def name_create(self, cr, uid, name, context=None):
"""Creates a new record by calling :meth:`~.create` with only one
value provided: the name of the new record (``_rec_name`` field).
The new record will also be initialized with any default values applicable
to this model, or provided through the context. The usual behavior of
:meth:`~.create` applies.
Similarly, this method may raise an exception if the model has multiple
required fields and some do not have default values.
:param name: name of the record to create
:rtype: tuple
:return: the :meth:`~.name_get` pair value for the newly-created record.
"""
rec_id = self.create(cr, uid, {self._rec_name: name}, context);
return self.name_get(cr, uid, [rec_id], context)[0]
# private implementation of name_search, allows passing a dedicated user for the name_get part to
# solve some access rights issues
def _name_search(self, cr, user, name='', args=None, operator='ilike', context=None, limit=100, name_get_uid=None):
if args is None:
args = []
if context is None:
context = {}
args = args[:]
# optimize out the default criterion of ``ilike ''`` that matches everything
if not (name == '' and operator == 'ilike'):
args += [(self._rec_name, operator, name)]
access_rights_uid = name_get_uid or user
ids = self._search(cr, user, args, limit=limit, context=context, access_rights_uid=access_rights_uid)
res = self.name_get(cr, access_rights_uid, ids, context)
return res
def read_string(self, cr, uid, id, langs, fields=None, context=None):
res = {}
res2 = {}
self.pool.get('ir.translation').check_read(cr, uid)
if not fields:
fields = self._columns.keys() + self._inherit_fields.keys()
#FIXME: collect all calls to _get_source into one SQL call.
for lang in langs:
res[lang] = {'code': lang}
for f in fields:
if f in self._columns:
res_trans = self.pool.get('ir.translation')._get_source(cr, uid, self._name+','+f, 'field', lang)
if res_trans:
res[lang][f] = res_trans
else:
res[lang][f] = self._columns[f].string
for table in self._inherits:
cols = intersect(self._inherit_fields.keys(), fields)
res2 = self.pool.get(table).read_string(cr, uid, id, langs, cols, context)
for lang in res2:
if lang in res:
res[lang]['code'] = lang
for f in res2[lang]:
res[lang][f] = res2[lang][f]
return res
def write_string(self, cr, uid, id, langs, vals, context=None):
self.pool.get('ir.translation').check_write(cr, uid)
#FIXME: try to only call the translation in one SQL
for lang in langs:
for field in vals:
if field in self._columns:
src = self._columns[field].string
self.pool.get('ir.translation')._set_ids(cr, uid, self._name+','+field, 'field', lang, [0], vals[field], src)
for table in self._inherits:
cols = intersect(self._inherit_fields.keys(), vals)
if cols:
self.pool.get(table).write_string(cr, uid, id, langs, vals, context)
return True
def _add_missing_default_values(self, cr, uid, values, context=None):
missing_defaults = []
avoid_tables = [] # avoid overriding inherited values when parent is set
for tables, parent_field in self._inherits.items():
if parent_field in values:
avoid_tables.append(tables)
for field in self._columns.keys():
if not field in values:
missing_defaults.append(field)
for field in self._inherit_fields.keys():
if (field not in values) and (self._inherit_fields[field][0] not in avoid_tables):
missing_defaults.append(field)
if len(missing_defaults):
# override defaults with the provided values, never allow the other way around
defaults = self.default_get(cr, uid, missing_defaults, context)
for dv in defaults:
if ((dv in self._columns and self._columns[dv]._type == 'many2many') \
or (dv in self._inherit_fields and self._inherit_fields[dv][2]._type == 'many2many')) \
and defaults[dv] and isinstance(defaults[dv][0], (int, long)):
defaults[dv] = [(6, 0, defaults[dv])]
if (dv in self._columns and self._columns[dv]._type == 'one2many' \
or (dv in self._inherit_fields and self._inherit_fields[dv][2]._type == 'one2many')) \
and isinstance(defaults[dv], (list, tuple)) and defaults[dv] and isinstance(defaults[dv][0], dict):
defaults[dv] = [(0, 0, x) for x in defaults[dv]]
defaults.update(values)
values = defaults
return values
def clear_caches(self):
""" Clear the caches
This clears the caches associated to methods decorated with
``tools.ormcache`` or ``tools.ormcache_multi``.
"""
try:
getattr(self, '_ormcache')
self._ormcache = {}
self.pool._any_cache_cleared = True
except AttributeError:
pass
def _read_group_fill_results(self, cr, uid, domain, groupby, groupby_list, aggregated_fields,
read_group_result, read_group_order=None, context=None):
"""Helper method for filling in empty groups for all possible values of
the field being grouped by"""
# self._group_by_full should map groupable fields to a method that returns
# a list of all aggregated values that we want to display for this field,
# in the form of a m2o-like pair (key,label).
# This is useful to implement kanban views for instance, where all columns
# should be displayed even if they don't contain any record.
# Grab the list of all groups that should be displayed, including all present groups
present_group_ids = [x[groupby][0] for x in read_group_result if x[groupby]]
all_groups = self._group_by_full[groupby](self, cr, uid, present_group_ids, domain,
read_group_order=read_group_order,
access_rights_uid=openerp.SUPERUSER_ID,
context=context)
result_template = dict.fromkeys(aggregated_fields, False)
result_template.update({groupby + '_count':0})
if groupby_list and len(groupby_list) > 1:
result_template.update(__context={'group_by': groupby_list[1:]})
# Merge the left_side (current results as dicts) with the right_side (all
# possible values as m2o pairs). Both lists are supposed to be using the
# same ordering, and can be merged in one pass.
result = []
known_values = {}
def append_left(left_side):
grouped_value = left_side[groupby] and left_side[groupby][0]
if not grouped_value in known_values:
result.append(left_side)
known_values[grouped_value] = left_side
else:
count_attr = groupby + '_count'
known_values[grouped_value].update({count_attr: left_side[count_attr]})
def append_right(right_side):
grouped_value = right_side[0]
if not grouped_value in known_values:
line = dict(result_template)
line.update({
groupby: right_side,
'__domain': [(groupby,'=',grouped_value)] + domain,
})
result.append(line)
known_values[grouped_value] = line
while read_group_result or all_groups:
left_side = read_group_result[0] if read_group_result else None
right_side = all_groups[0] if all_groups else None
assert left_side is None or left_side[groupby] is False \
or isinstance(left_side[groupby], (tuple,list)), \
'M2O-like pair expected, got %r' % left_side[groupby]
assert right_side is None or isinstance(right_side, (tuple,list)), \
'M2O-like pair expected, got %r' % right_side
if left_side is None:
append_right(all_groups.pop(0))
elif right_side is None:
append_left(read_group_result.pop(0))
elif left_side[groupby] == right_side:
append_left(read_group_result.pop(0))
all_groups.pop(0) # discard right_side
elif not left_side[groupby] or not left_side[groupby][0]:
# left side == "Undefined" entry, not present on right_side
append_left(read_group_result.pop(0))
else:
append_right(all_groups.pop(0))
return result
def read_group(self, cr, uid, domain, fields, groupby, offset=0, limit=None, context=None, orderby=False):
"""
Get the list of records in list view grouped by the given ``groupby`` fields
:param cr: database cursor
:param uid: current user id
:param domain: list specifying search criteria [['field_name', 'operator', 'value'], ...]
:param list fields: list of fields present in the list view specified on the object
:param list groupby: fields by which the records will be grouped
:param int offset: optional number of records to skip
:param int limit: optional max number of records to return
:param dict context: context arguments, like lang, time zone
:param list orderby: optional ``order by`` specification, for
overriding the natural sort ordering of the
groups, see also :py:meth:`~osv.osv.osv.search`
(supported only for many2one fields currently)
:return: list of dictionaries(one dictionary for each record) containing:
* the values of fields grouped by the fields in ``groupby`` argument
* __domain: list of tuples specifying the search criteria
* __context: dictionary with argument like ``groupby``
:rtype: [{'field_name_1': value, ...]
:raise AccessError: * if user has no read rights on the requested object
* if user tries to bypass access rules for read on the requested object
"""
context = context or {}
self.check_read(cr, uid)
if not fields:
fields = self._columns.keys()
query = self._where_calc(cr, uid, domain, context=context)
self._apply_ir_rules(cr, uid, query, 'read', context=context)
# Take care of adding join(s) if groupby is an '_inherits'ed field
groupby_list = groupby
qualified_groupby_field = groupby
if groupby:
if isinstance(groupby, list):
groupby = groupby[0]
qualified_groupby_field = self._inherits_join_calc(groupby, query)
if groupby:
assert not groupby or groupby in fields, "Fields in 'groupby' must appear in the list of fields to read (perhaps it's missing in the list view?)"
groupby_def = self._columns.get(groupby) or (self._inherit_fields.get(groupby) and self._inherit_fields.get(groupby)[2])
assert groupby_def and groupby_def._classic_write, "Fields in 'groupby' must be regular database-persisted fields (no function or related fields), or function fields with store=True"
# TODO it seems fields_get can be replaced by _all_columns (no need for translation)
fget = self.fields_get(cr, uid, fields)
flist = ''
group_count = group_by = groupby
if groupby:
if fget.get(groupby):
groupby_type = fget[groupby]['type']
if groupby_type in ('date', 'datetime'):
qualified_groupby_field = "to_char(%s,'yyyy-mm')" % qualified_groupby_field
flist = "%s as %s " % (qualified_groupby_field, groupby)
elif groupby_type == 'boolean':
qualified_groupby_field = "coalesce(%s,false)" % qualified_groupby_field
flist = "%s as %s " % (qualified_groupby_field, groupby)
else:
flist = qualified_groupby_field
else:
# Don't allow arbitrary values, as this would be a SQL injection vector!
raise except_orm(_('Invalid group_by'),
_('Invalid group_by specification: "%s".\nA group_by specification must be a list of valid fields.')%(groupby,))
aggregated_fields = [
f for f in fields
if f not in ('id', 'sequence')
if fget[f]['type'] in ('integer', 'float')
if (f in self._columns and getattr(self._columns[f], '_classic_write'))]
for f in aggregated_fields:
group_operator = fget[f].get('group_operator', 'sum')
if flist:
flist += ', '
qualified_field = '"%s"."%s"' % (self._table, f)
flist += "%s(%s) AS %s" % (group_operator, qualified_field, f)
gb = groupby and (' GROUP BY ' + qualified_groupby_field) or ''
from_clause, where_clause, where_clause_params = query.get_sql()
where_clause = where_clause and ' WHERE ' + where_clause
limit_str = limit and ' limit %d' % limit or ''
offset_str = offset and ' offset %d' % offset or ''
if len(groupby_list) < 2 and context.get('group_by_no_leaf'):
group_count = '_'
cr.execute('SELECT min(%s.id) AS id, count(%s.id) AS %s_count' % (self._table, self._table, group_count) + (flist and ',') + flist + ' FROM ' + from_clause + where_clause + gb + limit_str + offset_str, where_clause_params)
alldata = {}
groupby = group_by
for r in cr.dictfetchall():
for fld, val in r.items():
if val == None: r[fld] = False
alldata[r['id']] = r
del r['id']
order = orderby or groupby
data_ids = self.search(cr, uid, [('id', 'in', alldata.keys())], order=order, context=context)
# the IDs of records that have groupby field value = False or '' should be included too
data_ids += set(alldata.keys()).difference(data_ids)
if groupby:
data = self.read(cr, uid, data_ids, [groupby], context=context)
# restore order of the search as read() uses the default _order (this is only for groups, so the footprint of data should be small):
data_dict = dict((d['id'], d[groupby] ) for d in data)
result = [{'id': i, groupby: data_dict[i]} for i in data_ids]
else:
result = [{'id': i} for i in data_ids]
for d in result:
if groupby:
d['__domain'] = [(groupby, '=', alldata[d['id']][groupby] or False)] + domain
if not isinstance(groupby_list, (str, unicode)):
if groupby or not context.get('group_by_no_leaf', False):
d['__context'] = {'group_by': groupby_list[1:]}
if groupby and groupby in fget:
if d[groupby] and fget[groupby]['type'] in ('date', 'datetime'):
dt = datetime.datetime.strptime(alldata[d['id']][groupby][:7], '%Y-%m')
days = calendar.monthrange(dt.year, dt.month)[1]
d[groupby] = datetime.datetime.strptime(d[groupby][:10], '%Y-%m-%d').strftime('%B %Y')
d['__domain'] = [(groupby, '>=', alldata[d['id']][groupby] and datetime.datetime.strptime(alldata[d['id']][groupby][:7] + '-01', '%Y-%m-%d').strftime('%Y-%m-%d') or False),\
(groupby, '<=', alldata[d['id']][groupby] and datetime.datetime.strptime(alldata[d['id']][groupby][:7] + '-' + str(days), '%Y-%m-%d').strftime('%Y-%m-%d') or False)] + domain
del alldata[d['id']][groupby]
d.update(alldata[d['id']])
del d['id']
if groupby and groupby in self._group_by_full:
result = self._read_group_fill_results(cr, uid, domain, groupby, groupby_list,
aggregated_fields, result, read_group_order=order,
context=context)
return result
def _inherits_join_add(self, current_table, parent_model_name, query):
"""
Add missing table SELECT and JOIN clause to ``query`` for reaching the parent table (no duplicates)
:param current_table: current model object
:param parent_model_name: name of the parent model for which the clauses should be added
:param query: query object on which the JOIN should be added
"""
inherits_field = current_table._inherits[parent_model_name]
parent_model = self.pool.get(parent_model_name)
parent_table_name = parent_model._table
quoted_parent_table_name = '"%s"' % parent_table_name
if quoted_parent_table_name not in query.tables:
query.tables.append(quoted_parent_table_name)
query.where_clause.append('(%s.%s = %s.id)' % (current_table._table, inherits_field, parent_table_name))
def _inherits_join_calc(self, field, query):
"""
Adds missing table select and join clause(s) to ``query`` for reaching
the field coming from an '_inherits' parent table (no duplicates).
:param field: name of inherited field to reach
:param query: query object on which the JOIN should be added
:return: qualified name of field, to be used in SELECT clause
"""
current_table = self
while field in current_table._inherit_fields and not field in current_table._columns:
parent_model_name = current_table._inherit_fields[field][0]
parent_table = self.pool.get(parent_model_name)
self._inherits_join_add(current_table, parent_model_name, query)
current_table = parent_table
return '"%s".%s' % (current_table._table, field)
def _parent_store_compute(self, cr):
if not self._parent_store:
return
_logger.info('Computing parent left and right for table %s...', self._table)
def browse_rec(root, pos=0):
# TODO: set order
where = self._parent_name+'='+str(root)
if not root:
where = self._parent_name+' IS NULL'
if self._parent_order:
where += ' order by '+self._parent_order
cr.execute('SELECT id FROM '+self._table+' WHERE '+where)
pos2 = pos + 1
for id in cr.fetchall():
pos2 = browse_rec(id[0], pos2)
cr.execute('update '+self._table+' set parent_left=%s, parent_right=%s where id=%s', (pos, pos2, root))
return pos2 + 1
query = 'SELECT id FROM '+self._table+' WHERE '+self._parent_name+' IS NULL'
if self._parent_order:
query += ' order by ' + self._parent_order
pos = 0
cr.execute(query)
for (root,) in cr.fetchall():
pos = browse_rec(root, pos)
return True
def _update_store(self, cr, f, k):
_logger.info("storing computed values of fields.function '%s'", k)
ss = self._columns[k]._symbol_set
update_query = 'UPDATE "%s" SET "%s"=%s WHERE id=%%s' % (self._table, k, ss[0])
cr.execute('select id from '+self._table)
ids_lst = map(lambda x: x[0], cr.fetchall())
while ids_lst:
iids = ids_lst[:40]
ids_lst = ids_lst[40:]
res = f.get(cr, self, iids, k, SUPERUSER_ID, {})
for key, val in res.items():
if f._multi:
val = val[k]
# if val is a many2one, just write the ID
if type(val) == tuple:
val = val[0]
if (val<>False) or (type(val)<>bool):
cr.execute(update_query, (ss[1](val), key))
def _check_selection_field_value(self, cr, uid, field, value, context=None):
"""Raise except_orm if value is not among the valid values for the selection field"""
if self._columns[field]._type == 'reference':
val_model, val_id_str = value.split(',', 1)
val_id = False
try:
val_id = long(val_id_str)
except ValueError:
pass
if not val_id:
raise except_orm(_('ValidateError'),
_('Invalid value for reference field "%s.%s" (last part must be a non-zero integer): "%s"') % (self._table, field, value))
val = val_model
else:
val = value
if isinstance(self._columns[field].selection, (tuple, list)):
if val in dict(self._columns[field].selection):
return
elif val in dict(self._columns[field].selection(self, cr, uid, context=context)):
return
raise except_orm(_('ValidateError'),
_('The value "%s" for the field "%s.%s" is not in the selection') % (value, self._table, field))
def _check_removed_columns(self, cr, log=False):
# iterate on the database columns to drop the NOT NULL constraints
# of fields which were required but have been removed (or will be added by another module)
columns = [c for c in self._columns if not (isinstance(self._columns[c], fields.function) and not self._columns[c].store)]
columns += MAGIC_COLUMNS
cr.execute("SELECT a.attname, a.attnotnull"
" FROM pg_class c, pg_attribute a"
" WHERE c.relname=%s"
" AND c.oid=a.attrelid"
" AND a.attisdropped=%s"
" AND pg_catalog.format_type(a.atttypid, a.atttypmod) NOT IN ('cid', 'tid', 'oid', 'xid')"
" AND a.attname NOT IN %s", (self._table, False, tuple(columns))),
for column in cr.dictfetchall():
if log:
_logger.debug("column %s is in the table %s but not in the corresponding object %s",
column['attname'], self._table, self._name)
if column['attnotnull']:
cr.execute('ALTER TABLE "%s" ALTER COLUMN "%s" DROP NOT NULL' % (self._table, column['attname']))
_schema.debug("Table '%s': column '%s': dropped NOT NULL constraint",
self._table, column['attname'])
# checked version: for direct m2o starting from `self`
def _m2o_add_foreign_key_checked(self, source_field, dest_model, ondelete):
assert self.is_transient() or not dest_model.is_transient(), \
'Many2One relationships from non-transient Model to TransientModel are forbidden'
if self.is_transient() and not dest_model.is_transient():
# TransientModel relationships to regular Models are annoying
# usually because they could block deletion due to the FKs.
# So unless stated otherwise we default them to ondelete=cascade.
ondelete = ondelete or 'cascade'
self._foreign_keys.append((self._table, source_field, dest_model._table, ondelete or 'set null'))
_schema.debug("Table '%s': added foreign key '%s' with definition=REFERENCES \"%s\" ON DELETE %s",
self._table, source_field, dest_model._table, ondelete)
# unchecked version: for custom cases, such as m2m relationships
def _m2o_add_foreign_key_unchecked(self, source_table, source_field, dest_model, ondelete):
self._foreign_keys.append((source_table, source_field, dest_model._table, ondelete or 'set null'))
_schema.debug("Table '%s': added foreign key '%s' with definition=REFERENCES \"%s\" ON DELETE %s",
source_table, source_field, dest_model._table, ondelete)
def _drop_constraint(self, cr, source_table, constraint_name):
cr.execute("ALTER TABLE %s DROP CONSTRAINT %s" % (source_table,constraint_name))
def _m2o_fix_foreign_key(self, cr, source_table, source_field, dest_model, ondelete):
# Find FK constraint(s) currently established for the m2o field,
# and see whether they are stale or not
cr.execute("""SELECT confdeltype as ondelete_rule, conname as constraint_name,
cl2.relname as foreign_table
FROM pg_constraint as con, pg_class as cl1, pg_class as cl2,
pg_attribute as att1, pg_attribute as att2
WHERE con.conrelid = cl1.oid
AND cl1.relname = %s
AND con.confrelid = cl2.oid
AND array_lower(con.conkey, 1) = 1
AND con.conkey[1] = att1.attnum
AND att1.attrelid = cl1.oid
AND att1.attname = %s
AND array_lower(con.confkey, 1) = 1
AND con.confkey[1] = att2.attnum
AND att2.attrelid = cl2.oid
AND att2.attname = %s
AND con.contype = 'f'""", (source_table, source_field, 'id'))
constraints = cr.dictfetchall()
if constraints:
if len(constraints) == 1:
# Is it the right constraint?
cons, = constraints
if cons['ondelete_rule'] != POSTGRES_CONFDELTYPES.get((ondelete or 'set null').upper(), 'a')\
or cons['foreign_table'] != dest_model._table:
_schema.debug("Table '%s': dropping obsolete FK constraint: '%s'",
source_table, cons['constraint_name'])
self._drop_constraint(cr, source_table, cons['constraint_name'])
self._m2o_add_foreign_key_checked(source_field, dest_model, ondelete)
# else it's all good, nothing to do!
else:
# Multiple FKs found for the same field, drop them all, and re-create
for cons in constraints:
_schema.debug("Table '%s': dropping duplicate FK constraints: '%s'",
source_table, cons['constraint_name'])
self._drop_constraint(cr, source_table, cons['constraint_name'])
self._m2o_add_foreign_key_checked(source_field, dest_model, ondelete)
def _auto_init(self, cr, context=None):
"""
Call _field_create and, unless _auto is False:
- create the corresponding table in database for the model,
- possibly add the parent columns in database,
- possibly add the columns 'create_uid', 'create_date', 'write_uid',
'write_date' in database if _log_access is True (the default),
- report on database columns no more existing in _columns,
- remove no more existing not null constraints,
- alter existing database columns to match _columns,
- create database tables to match _columns,
- add database indices to match _columns,
- save in self._foreign_keys a list a foreign keys to create (see
_auto_end).
"""
self._foreign_keys = []
raise_on_invalid_object_name(self._name)
if context is None:
context = {}
store_compute = False
todo_end = []
update_custom_fields = context.get('update_custom_fields', False)
self._field_create(cr, context=context)
create = not self._table_exist(cr)
if getattr(self, '_auto', True):
if create:
self._create_table(cr)
cr.commit()
if self._parent_store:
if not self._parent_columns_exist(cr):
self._create_parent_columns(cr)
store_compute = True
# Create the create_uid, create_date, write_uid, write_date, columns if desired.
if self._log_access:
self._add_log_columns(cr)
self._check_removed_columns(cr, log=False)
# iterate on the "object columns"
column_data = self._select_column_data(cr)
for k, f in self._columns.iteritems():
if k in MAGIC_COLUMNS:
continue
# Don't update custom (also called manual) fields
if f.manual and not update_custom_fields:
continue
if isinstance(f, fields.one2many):
self._o2m_raise_on_missing_reference(cr, f)
elif isinstance(f, fields.many2many):
self._m2m_raise_or_create_relation(cr, f)
else:
res = column_data.get(k)
# The field is not found as-is in database, try if it
# exists with an old name.
if not res and hasattr(f, 'oldname'):
res = column_data.get(f.oldname)
if res:
cr.execute('ALTER TABLE "%s" RENAME "%s" TO "%s"' % (self._table, f.oldname, k))
res['attname'] = k
column_data[k] = res
_schema.debug("Table '%s': renamed column '%s' to '%s'",
self._table, f.oldname, k)
# The field already exists in database. Possibly
# change its type, rename it, drop it or change its
# constraints.
if res:
f_pg_type = res['typname']
f_pg_size = res['size']
f_pg_notnull = res['attnotnull']
if isinstance(f, fields.function) and not f.store and\
not getattr(f, 'nodrop', False):
_logger.info('column %s (%s) in table %s removed: converted to a function !\n',
k, f.string, self._table)
cr.execute('ALTER TABLE "%s" DROP COLUMN "%s" CASCADE' % (self._table, k))
cr.commit()
_schema.debug("Table '%s': dropped column '%s' with cascade",
self._table, k)
f_obj_type = None
else:
f_obj_type = get_pg_type(f) and get_pg_type(f)[0]
if f_obj_type:
ok = False
casts = [
('text', 'char', pg_varchar(f.size), '::%s' % pg_varchar(f.size)),
('varchar', 'text', 'TEXT', ''),
('int4', 'float', get_pg_type(f)[1], '::'+get_pg_type(f)[1]),
('date', 'datetime', 'TIMESTAMP', '::TIMESTAMP'),
('timestamp', 'date', 'date', '::date'),
('numeric', 'float', get_pg_type(f)[1], '::'+get_pg_type(f)[1]),
('float8', 'float', get_pg_type(f)[1], '::'+get_pg_type(f)[1]),
]
if f_pg_type == 'varchar' and f._type == 'char' and f_pg_size < f.size:
cr.execute('ALTER TABLE "%s" RENAME COLUMN "%s" TO temp_change_size' % (self._table, k))
cr.execute('ALTER TABLE "%s" ADD COLUMN "%s" %s' % (self._table, k, pg_varchar(f.size)))
cr.execute('UPDATE "%s" SET "%s"=temp_change_size::%s' % (self._table, k, pg_varchar(f.size)))
cr.execute('ALTER TABLE "%s" DROP COLUMN temp_change_size CASCADE' % (self._table,))
cr.commit()
_schema.debug("Table '%s': column '%s' (type varchar) changed size from %s to %s",
self._table, k, f_pg_size, f.size)
for c in casts:
if (f_pg_type==c[0]) and (f._type==c[1]):
if f_pg_type != f_obj_type:
ok = True
cr.execute('ALTER TABLE "%s" RENAME COLUMN "%s" TO temp_change_size' % (self._table, k))
cr.execute('ALTER TABLE "%s" ADD COLUMN "%s" %s' % (self._table, k, c[2]))
cr.execute(('UPDATE "%s" SET "%s"=temp_change_size'+c[3]) % (self._table, k))
cr.execute('ALTER TABLE "%s" DROP COLUMN temp_change_size CASCADE' % (self._table,))
cr.commit()
_schema.debug("Table '%s': column '%s' changed type from %s to %s",
self._table, k, c[0], c[1])
break
if f_pg_type != f_obj_type:
if not ok:
i = 0
while True:
newname = k + '_moved' + str(i)
cr.execute("SELECT count(1) FROM pg_class c,pg_attribute a " \
"WHERE c.relname=%s " \
"AND a.attname=%s " \
"AND c.oid=a.attrelid ", (self._table, newname))
if not cr.fetchone()[0]:
break
i += 1
if f_pg_notnull:
cr.execute('ALTER TABLE "%s" ALTER COLUMN "%s" DROP NOT NULL' % (self._table, k))
cr.execute('ALTER TABLE "%s" RENAME COLUMN "%s" TO "%s"' % (self._table, k, newname))
cr.execute('ALTER TABLE "%s" ADD COLUMN "%s" %s' % (self._table, k, get_pg_type(f)[1]))
cr.execute("COMMENT ON COLUMN %s.\"%s\" IS %%s" % (self._table, k), (f.string,))
_schema.debug("Table '%s': column '%s' has changed type (DB=%s, def=%s), data moved to column %s !",
self._table, k, f_pg_type, f._type, newname)
# if the field is required and hasn't got a NOT NULL constraint
if f.required and f_pg_notnull == 0:
# set the field to the default value if any
if k in self._defaults:
if callable(self._defaults[k]):
default = self._defaults[k](self, cr, SUPERUSER_ID, context)
else:
default = self._defaults[k]
if (default is not None):
ss = self._columns[k]._symbol_set
query = 'UPDATE "%s" SET "%s"=%s WHERE "%s" is NULL' % (self._table, k, ss[0], k)
cr.execute(query, (ss[1](default),))
# add the NOT NULL constraint
cr.commit()
try:
cr.execute('ALTER TABLE "%s" ALTER COLUMN "%s" SET NOT NULL' % (self._table, k), log_exceptions=False)
cr.commit()
_schema.debug("Table '%s': column '%s': added NOT NULL constraint",
self._table, k)
except Exception:
msg = "Table '%s': unable to set a NOT NULL constraint on column '%s' !\n"\
"If you want to have it, you should update the records and execute manually:\n"\
"ALTER TABLE %s ALTER COLUMN %s SET NOT NULL"
_schema.warning(msg, self._table, k, self._table, k)
cr.commit()
elif not f.required and f_pg_notnull == 1:
cr.execute('ALTER TABLE "%s" ALTER COLUMN "%s" DROP NOT NULL' % (self._table, k))
cr.commit()
_schema.debug("Table '%s': column '%s': dropped NOT NULL constraint",
self._table, k)
# Verify index
indexname = '%s_%s_index' % (self._table, k)
cr.execute("SELECT indexname FROM pg_indexes WHERE indexname = %s and tablename = %s", (indexname, self._table))
res2 = cr.dictfetchall()
if not res2 and f.select:
cr.execute('CREATE INDEX "%s_%s_index" ON "%s" ("%s")' % (self._table, k, self._table, k))
cr.commit()
if f._type == 'text':
# FIXME: for fields.text columns we should try creating GIN indexes instead (seems most suitable for an ERP context)
msg = "Table '%s': Adding (b-tree) index for text column '%s'."\
"This is probably useless (does not work for fulltext search) and prevents INSERTs of long texts"\
" because there is a length limit for indexable btree values!\n"\
"Use a search view instead if you simply want to make the field searchable."
_schema.warning(msg, self._table, k, f._type)
if res2 and not f.select:
cr.execute('DROP INDEX "%s_%s_index"' % (self._table, k))
cr.commit()
msg = "Table '%s': dropping index for column '%s' of type '%s' as it is not required anymore"
_schema.debug(msg, self._table, k, f._type)
if isinstance(f, fields.many2one):
dest_model = self.pool.get(f._obj)
if dest_model._table != 'ir_actions':
self._m2o_fix_foreign_key(cr, self._table, k, dest_model, f.ondelete)
# The field doesn't exist in database. Create it if necessary.
else:
if not isinstance(f, fields.function) or f.store:
# add the missing field
cr.execute('ALTER TABLE "%s" ADD COLUMN "%s" %s' % (self._table, k, get_pg_type(f)[1]))
cr.execute("COMMENT ON COLUMN %s.\"%s\" IS %%s" % (self._table, k), (f.string,))
_schema.debug("Table '%s': added column '%s' with definition=%s",
self._table, k, get_pg_type(f)[1])
# initialize it
if not create and k in self._defaults:
if callable(self._defaults[k]):
default = self._defaults[k](self, cr, SUPERUSER_ID, context)
else:
default = self._defaults[k]
ss = self._columns[k]._symbol_set
query = 'UPDATE "%s" SET "%s"=%s' % (self._table, k, ss[0])
cr.execute(query, (ss[1](default),))
cr.commit()
_logger.debug("Table '%s': setting default value of new column %s", self._table, k)
# remember the functions to call for the stored fields
if isinstance(f, fields.function):
order = 10
if f.store is not True: # i.e. if f.store is a dict
order = f.store[f.store.keys()[0]][2]
todo_end.append((order, self._update_store, (f, k)))
# and add constraints if needed
if isinstance(f, fields.many2one):
if not self.pool.get(f._obj):
raise except_orm('Programming Error', ('There is no reference available for %s') % (f._obj,))
dest_model = self.pool.get(f._obj)
ref = dest_model._table
# ir_actions is inherited so foreign key doesn't work on it
if ref != 'ir_actions':
self._m2o_add_foreign_key_checked(k, dest_model, f.ondelete)
if f.select:
cr.execute('CREATE INDEX "%s_%s_index" ON "%s" ("%s")' % (self._table, k, self._table, k))
if f.required:
try:
cr.commit()
cr.execute('ALTER TABLE "%s" ALTER COLUMN "%s" SET NOT NULL' % (self._table, k), log_exceptions=False)
_schema.debug("Table '%s': column '%s': added a NOT NULL constraint",
self._table, k)
except Exception:
msg = "WARNING: unable to set column %s of table %s not null !\n"\
"Try to re-run: openerp-server --update=module\n"\
"If it doesn't work, update records and execute manually:\n"\
"ALTER TABLE %s ALTER COLUMN %s SET NOT NULL"
_logger.warning(msg, k, self._table, self._table, k)
cr.commit()
else:
cr.execute("SELECT relname FROM pg_class WHERE relkind IN ('r','v') AND relname=%s", (self._table,))
create = not bool(cr.fetchone())
cr.commit() # start a new transaction
self._add_sql_constraints(cr)
if create:
self._execute_sql(cr)
if store_compute:
self._parent_store_compute(cr)
cr.commit()
return todo_end
def _auto_end(self, cr, context=None):
""" Create the foreign keys recorded by _auto_init. """
for t, k, r, d in self._foreign_keys:
cr.execute('ALTER TABLE "%s" ADD FOREIGN KEY ("%s") REFERENCES "%s" ON DELETE %s' % (t, k, r, d))
cr.commit()
del self._foreign_keys
def _table_exist(self, cr):
cr.execute("SELECT relname FROM pg_class WHERE relkind IN ('r','v') AND relname=%s", (self._table,))
return cr.rowcount
def _create_table(self, cr):
cr.execute('CREATE TABLE "%s" (id SERIAL NOT NULL, PRIMARY KEY(id)) WITHOUT OIDS' % (self._table,))
cr.execute(("COMMENT ON TABLE \"%s\" IS %%s" % self._table), (self._description,))
_schema.debug("Table '%s': created", self._table)
def _parent_columns_exist(self, cr):
cr.execute("""SELECT c.relname
FROM pg_class c, pg_attribute a
WHERE c.relname=%s AND a.attname=%s AND c.oid=a.attrelid
""", (self._table, 'parent_left'))
return cr.rowcount
def _create_parent_columns(self, cr):
cr.execute('ALTER TABLE "%s" ADD COLUMN "parent_left" INTEGER' % (self._table,))
cr.execute('ALTER TABLE "%s" ADD COLUMN "parent_right" INTEGER' % (self._table,))
if 'parent_left' not in self._columns:
_logger.error('create a column parent_left on object %s: fields.integer(\'Left Parent\', select=1)',
self._table)
_schema.debug("Table '%s': added column '%s' with definition=%s",
self._table, 'parent_left', 'INTEGER')
elif not self._columns['parent_left'].select:
_logger.error('parent_left column on object %s must be indexed! Add select=1 to the field definition)',
self._table)
if 'parent_right' not in self._columns:
_logger.error('create a column parent_right on object %s: fields.integer(\'Right Parent\', select=1)',
self._table)
_schema.debug("Table '%s': added column '%s' with definition=%s",
self._table, 'parent_right', 'INTEGER')
elif not self._columns['parent_right'].select:
_logger.error('parent_right column on object %s must be indexed! Add select=1 to the field definition)',
self._table)
if self._columns[self._parent_name].ondelete != 'cascade':
_logger.error("The column %s on object %s must be set as ondelete='cascade'",
self._parent_name, self._name)
cr.commit()
def _add_log_columns(self, cr):
for field, field_def in LOG_ACCESS_COLUMNS.iteritems():
cr.execute("""
SELECT c.relname
FROM pg_class c, pg_attribute a
WHERE c.relname=%s AND a.attname=%s AND c.oid=a.attrelid
""", (self._table, field))
if not cr.rowcount:
cr.execute('ALTER TABLE "%s" ADD COLUMN "%s" %s' % (self._table, field, field_def))
cr.commit()
_schema.debug("Table '%s': added column '%s' with definition=%s",
self._table, field, field_def)
def _select_column_data(self, cr):
# attlen is the number of bytes necessary to represent the type when
# the type has a fixed size. If the type has a varying size attlen is
# -1 and atttypmod is the size limit + 4, or -1 if there is no limit.
# Thus the query can return a negative size for a unlimited varchar.
cr.execute("SELECT c.relname,a.attname,a.attlen,a.atttypmod,a.attnotnull,a.atthasdef,t.typname,CASE WHEN a.attlen=-1 THEN a.atttypmod-4 ELSE a.attlen END as size " \
"FROM pg_class c,pg_attribute a,pg_type t " \
"WHERE c.relname=%s " \
"AND c.oid=a.attrelid " \
"AND a.atttypid=t.oid", (self._table,))
return dict(map(lambda x: (x['attname'], x),cr.dictfetchall()))
def _o2m_raise_on_missing_reference(self, cr, f):
# TODO this check should be a method on fields.one2many.
other = self.pool.get(f._obj)
if other:
# TODO the condition could use fields_get_keys().
if f._fields_id not in other._columns.keys():
if f._fields_id not in other._inherit_fields.keys():
raise except_orm('Programming Error', ("There is no reference field '%s' found for '%s'") % (f._fields_id, f._obj,))
def _m2m_raise_or_create_relation(self, cr, f):
m2m_tbl, col1, col2 = f._sql_names(self)
cr.execute("SELECT relname FROM pg_class WHERE relkind IN ('r','v') AND relname=%s", (m2m_tbl,))
if not cr.dictfetchall():
if not self.pool.get(f._obj):
raise except_orm('Programming Error', ('Many2Many destination model does not exist: `%s`') % (f._obj,))
dest_model = self.pool.get(f._obj)
ref = dest_model._table
cr.execute('CREATE TABLE "%s" ("%s" INTEGER NOT NULL, "%s" INTEGER NOT NULL, UNIQUE("%s","%s")) WITH OIDS' % (m2m_tbl, col1, col2, col1, col2))
# create foreign key references with ondelete=cascade, unless the targets are SQL views
cr.execute("SELECT relkind FROM pg_class WHERE relkind IN ('v') AND relname=%s", (ref,))
if not cr.fetchall():
self._m2o_add_foreign_key_unchecked(m2m_tbl, col2, dest_model, 'cascade')
cr.execute("SELECT relkind FROM pg_class WHERE relkind IN ('v') AND relname=%s", (self._table,))
if not cr.fetchall():
self._m2o_add_foreign_key_unchecked(m2m_tbl, col1, self, 'cascade')
cr.execute('CREATE INDEX "%s_%s_index" ON "%s" ("%s")' % (m2m_tbl, col1, m2m_tbl, col1))
cr.execute('CREATE INDEX "%s_%s_index" ON "%s" ("%s")' % (m2m_tbl, col2, m2m_tbl, col2))
cr.execute("COMMENT ON TABLE \"%s\" IS 'RELATION BETWEEN %s AND %s'" % (m2m_tbl, self._table, ref))
cr.commit()
_schema.debug("Create table '%s': m2m relation between '%s' and '%s'", m2m_tbl, self._table, ref)
def _add_sql_constraints(self, cr):
"""
Modify this model's database table constraints so they match the one in
_sql_constraints.
"""
def unify_cons_text(txt):
return txt.lower().replace(', ',',').replace(' (','(')
for (key, con, _) in self._sql_constraints:
conname = '%s_%s' % (self._table, key)
cr.execute("SELECT conname, pg_catalog.pg_get_constraintdef(oid, true) as condef FROM pg_constraint where conname=%s", (conname,))
existing_constraints = cr.dictfetchall()
sql_actions = {
'drop': {
'execute': False,
'query': 'ALTER TABLE "%s" DROP CONSTRAINT "%s"' % (self._table, conname, ),
'msg_ok': "Table '%s': dropped constraint '%s'. Reason: its definition changed from '%%s' to '%s'" % (
self._table, conname, con),
'msg_err': "Table '%s': unable to drop \'%s\' constraint !" % (self._table, con),
'order': 1,
},
'add': {
'execute': False,
'query': 'ALTER TABLE "%s" ADD CONSTRAINT "%s" %s' % (self._table, conname, con,),
'msg_ok': "Table '%s': added constraint '%s' with definition=%s" % (self._table, conname, con),
'msg_err': "Table '%s': unable to add \'%s\' constraint !\n If you want to have it, you should update the records and execute manually:\n%%s" % (
self._table, con),
'order': 2,
},
}
if not existing_constraints:
# constraint does not exists:
sql_actions['add']['execute'] = True
sql_actions['add']['msg_err'] = sql_actions['add']['msg_err'] % (sql_actions['add']['query'], )
elif unify_cons_text(con) not in [unify_cons_text(item['condef']) for item in existing_constraints]:
# constraint exists but its definition has changed:
sql_actions['drop']['execute'] = True
sql_actions['drop']['msg_ok'] = sql_actions['drop']['msg_ok'] % (existing_constraints[0]['condef'].lower(), )
sql_actions['add']['execute'] = True
sql_actions['add']['msg_err'] = sql_actions['add']['msg_err'] % (sql_actions['add']['query'], )
# we need to add the constraint:
sql_actions = [item for item in sql_actions.values()]
sql_actions.sort(key=lambda x: x['order'])
for sql_action in [action for action in sql_actions if action['execute']]:
try:
cr.execute(sql_action['query'])
cr.commit()
_schema.debug(sql_action['msg_ok'])
except:
_schema.warning(sql_action['msg_err'])
cr.rollback()
def _execute_sql(self, cr):
""" Execute the SQL code from the _sql attribute (if any)."""
if hasattr(self, "_sql"):
for line in self._sql.split(';'):
line2 = line.replace('\n', '').strip()
if line2:
cr.execute(line2)
cr.commit()
#
# Update objects that uses this one to update their _inherits fields
#
def _inherits_reload_src(self):
""" Recompute the _inherit_fields mapping on each _inherits'd child model."""
for obj in self.pool.models.values():
if self._name in obj._inherits:
obj._inherits_reload()
def _inherits_reload(self):
""" Recompute the _inherit_fields mapping.
This will also call itself on each inherits'd child model.
"""
res = {}
for table in self._inherits:
other = self.pool.get(table)
for col in other._columns.keys():
res[col] = (table, self._inherits[table], other._columns[col], table)
for col in other._inherit_fields.keys():
res[col] = (table, self._inherits[table], other._inherit_fields[col][2], other._inherit_fields[col][3])
self._inherit_fields = res
self._all_columns = self._get_column_infos()
self._inherits_reload_src()
def _get_column_infos(self):
"""Returns a dict mapping all fields names (direct fields and
inherited field via _inherits) to a ``column_info`` struct
giving detailed columns """
result = {}
for k, (parent, m2o, col, original_parent) in self._inherit_fields.iteritems():
result[k] = fields.column_info(k, col, parent, m2o, original_parent)
for k, col in self._columns.iteritems():
result[k] = fields.column_info(k, col)
return result
def _inherits_check(self):
for table, field_name in self._inherits.items():
if field_name not in self._columns:
_logger.info('Missing many2one field definition for _inherits reference "%s" in "%s", using default one.', field_name, self._name)
self._columns[field_name] = fields.many2one(table, string="Automatically created field to link to parent %s" % table,
required=True, ondelete="cascade")
elif not self._columns[field_name].required or self._columns[field_name].ondelete.lower() != "cascade":
_logger.warning('Field definition for _inherits reference "%s" in "%s" must be marked as "required" with ondelete="cascade", forcing it.', field_name, self._name)
self._columns[field_name].required = True
self._columns[field_name].ondelete = "cascade"
#def __getattr__(self, name):
# """
# Proxies attribute accesses to the `inherits` parent so we can call methods defined on the inherited parent
# (though inherits doesn't use Python inheritance).
# Handles translating between local ids and remote ids.
# Known issue: doesn't work correctly when using python's own super(), don't involve inherit-based inheritance
# when you have inherits.
# """
# for model, field in self._inherits.iteritems():
# proxy = self.pool.get(model)
# if hasattr(proxy, name):
# attribute = getattr(proxy, name)
# if not hasattr(attribute, '__call__'):
# return attribute
# break
# else:
# return super(orm, self).__getattr__(name)
# def _proxy(cr, uid, ids, *args, **kwargs):
# objects = self.browse(cr, uid, ids, kwargs.get('context', None))
# lst = [obj[field].id for obj in objects if obj[field]]
# return getattr(proxy, name)(cr, uid, lst, *args, **kwargs)
# return _proxy
def fields_get(self, cr, user, allfields=None, context=None, write_access=True):
""" Return the definition of each field.
The returned value is a dictionary (indiced by field name) of
dictionaries. The _inherits'd fields are included. The string, help,
and selection (if present) attributes are translated.
:param cr: database cursor
:param user: current user id
:param fields: list of fields
:param context: context arguments, like lang, time zone
:return: dictionary of field dictionaries, each one describing a field of the business object
:raise AccessError: * if user has no create/write rights on the requested object
"""
if context is None:
context = {}
write_access = self.check_write(cr, user, False) or \
self.check_create(cr, user, False)
res = {}
translation_obj = self.pool.get('ir.translation')
for parent in self._inherits:
res.update(self.pool.get(parent).fields_get(cr, user, allfields, context))
for f, field in self._columns.iteritems():
if allfields and f not in allfields:
continue
res[f] = fields.field_to_dict(self, cr, user, field, context=context)
if not write_access:
res[f]['readonly'] = True
res[f]['states'] = {}
if 'string' in res[f]:
res_trans = translation_obj._get_source(cr, user, self._name + ',' + f, 'field', context.get('lang', False) or 'en_US')
if res_trans:
res[f]['string'] = res_trans
if 'help' in res[f]:
help_trans = translation_obj._get_source(cr, user, self._name + ',' + f, 'help', context.get('lang', False) or 'en_US')
if help_trans:
res[f]['help'] = help_trans
if 'selection' in res[f]:
if isinstance(field.selection, (tuple, list)):
sel = field.selection
sel2 = []
for key, val in sel:
val2 = None
if val:
val2 = translation_obj._get_source(cr, user, self._name + ',' + f, 'selection', context.get('lang', False) or 'en_US', val)
sel2.append((key, val2 or val))
res[f]['selection'] = sel2
return res
def read(self, cr, user, ids, fields=None, context=None, load='_classic_read'):
""" Read records with given ids with the given fields
:param cr: database cursor
:param user: current user id
:param ids: id or list of the ids of the records to read
:param fields: optional list of field names to return (default: all fields would be returned)
:type fields: list (example ['field_name_1', ...])
:param context: optional context dictionary - it may contains keys for specifying certain options
like ``context_lang``, ``context_tz`` to alter the results of the call.
A special ``bin_size`` boolean flag may also be passed in the context to request the
value of all fields.binary columns to be returned as the size of the binary instead of its
contents. This can also be selectively overriden by passing a field-specific flag
in the form ``bin_size_XXX: True/False`` where ``XXX`` is the name of the field.
Note: The ``bin_size_XXX`` form is new in OpenERP v6.0.
:return: list of dictionaries((dictionary per record asked)) with requested field values
:rtype: [{‘name_of_the_field’: value, ...}, ...]
:raise AccessError: * if user has no read rights on the requested object
* if user tries to bypass access rules for read on the requested object
"""
if not context:
context = {}
self.check_read(cr, user)
if not fields:
fields = list(set(self._columns.keys() + self._inherit_fields.keys()))
if isinstance(ids, (int, long)):
select = [ids]
else:
select = ids
select = map(lambda x: isinstance(x, dict) and x['id'] or x, select)
result = self._read_flat(cr, user, select, fields, context, load)
for r in result:
for key, v in r.items():
if v is None:
r[key] = False
if isinstance(ids, (int, long, dict)):
return result and result[0] or False
return result
def _read_flat(self, cr, user, ids, fields_to_read, context=None, load='_classic_read'):
if not context:
context = {}
if not ids:
return []
if fields_to_read == None:
fields_to_read = self._columns.keys()
# Construct a clause for the security rules.
# 'tables' hold the list of tables necessary for the SELECT including the ir.rule clauses,
# or will at least contain self._table.
rule_clause, rule_params, tables = self.pool.get('ir.rule').domain_get(cr, user, self._name, 'read', context=context)
# all inherited fields + all non inherited fields for which the attribute whose name is in load is True
fields_pre = [f for f in fields_to_read if
f == self.CONCURRENCY_CHECK_FIELD
or (f in self._columns and getattr(self._columns[f], '_classic_write'))
] + self._inherits.values()
res = []
if len(fields_pre):
def convert_field(f):
f_qual = '%s."%s"' % (self._table, f) # need fully-qualified references in case len(tables) > 1
if f in ('create_date', 'write_date'):
return "date_trunc('second', %s) as %s" % (f_qual, f)
if f == self.CONCURRENCY_CHECK_FIELD:
if self._log_access:
return "COALESCE(%s.write_date, %s.create_date, (now() at time zone 'UTC'))::timestamp AS %s" % (self._table, self._table, f,)
return "(now() at time zone 'UTC')::timestamp AS %s" % (f,)
if isinstance(self._columns[f], fields.binary) and context.get('bin_size', False):
return 'length(%s) as "%s"' % (f_qual, f)
return f_qual
fields_pre2 = map(convert_field, fields_pre)
order_by = self._parent_order or self._order
select_fields = ','.join(fields_pre2 + [self._table + '.id'])
query = 'SELECT %s FROM %s WHERE %s.id IN %%s' % (select_fields, ','.join(tables), self._table)
if rule_clause:
query += " AND " + (' OR '.join(rule_clause))
query += " ORDER BY " + order_by
for sub_ids in cr.split_for_in_conditions(ids):
if rule_clause:
cr.execute(query, [tuple(sub_ids)] + rule_params)
if cr.rowcount != len(sub_ids):
raise except_orm(_('AccessError'),
_('Operation prohibited by access rules, or performed on an already deleted document (Operation: read, Document type: %s).')
% (self._description,))
else:
cr.execute(query, (tuple(sub_ids),))
res.extend(cr.dictfetchall())
else:
res = map(lambda x: {'id': x}, ids)
for f in fields_pre:
if f == self.CONCURRENCY_CHECK_FIELD:
continue
if self._columns[f].translate:
ids = [x['id'] for x in res]
#TODO: optimize out of this loop
res_trans = self.pool.get('ir.translation')._get_ids(cr, user, self._name+','+f, 'model', context.get('lang', False) or 'en_US', ids)
for r in res:
r[f] = res_trans.get(r['id'], False) or r[f]
for table in self._inherits:
col = self._inherits[table]
cols = [x for x in intersect(self._inherit_fields.keys(), fields_to_read) if x not in self._columns.keys()]
if not cols:
continue
res2 = self.pool.get(table).read(cr, user, [x[col] for x in res], cols, context, load)
res3 = {}
for r in res2:
res3[r['id']] = r
del r['id']
for record in res:
if not record[col]: # if the record is deleted from _inherits table?
continue
record.update(res3[record[col]])
if col not in fields_to_read:
del record[col]
# all fields which need to be post-processed by a simple function (symbol_get)
fields_post = filter(lambda x: x in self._columns and self._columns[x]._symbol_get, fields_to_read)
if fields_post:
for r in res:
for f in fields_post:
r[f] = self._columns[f]._symbol_get(r[f])
ids = [x['id'] for x in res]
# all non inherited fields for which the attribute whose name is in load is False
fields_post = filter(lambda x: x in self._columns and not getattr(self._columns[x], load), fields_to_read)
# Compute POST fields
todo = {}
for f in fields_post:
todo.setdefault(self._columns[f]._multi, [])
todo[self._columns[f]._multi].append(f)
for key, val in todo.items():
if key:
res2 = self._columns[val[0]].get(cr, self, ids, val, user, context=context, values=res)
assert res2 is not None, \
'The function field "%s" on the "%s" model returned None\n' \
'(a dictionary was expected).' % (val[0], self._name)
for pos in val:
for record in res:
if isinstance(res2[record['id']], str): res2[record['id']] = eval(res2[record['id']]) #TOCHECK : why got string instend of dict in python2.6
multi_fields = res2.get(record['id'],{})
if multi_fields:
record[pos] = multi_fields.get(pos,[])
else:
for f in val:
res2 = self._columns[f].get(cr, self, ids, f, user, context=context, values=res)
for record in res:
if res2:
record[f] = res2[record['id']]
else:
record[f] = []
readonly = None
for vals in res:
for field in vals.copy():
fobj = None
if field in self._columns:
fobj = self._columns[field]
if not fobj:
continue
groups = fobj.read
if groups:
edit = False
for group in groups:
module = group.split(".")[0]
grp = group.split(".")[1]
cr.execute("select count(*) from res_groups_users_rel where gid IN (select res_id from ir_model_data where name=%s and module=%s and model=%s) and uid=%s", \
(grp, module, 'res.groups', user))
readonly = cr.fetchall()
if readonly[0][0] >= 1:
edit = True
break
elif readonly[0][0] == 0:
edit = False
else:
edit = False
if not edit:
if type(vals[field]) == type([]):
vals[field] = []
elif type(vals[field]) == type(0.0):
vals[field] = 0
elif type(vals[field]) == type(''):
vals[field] = '=No Permission='
else:
vals[field] = False
return res
# TODO check READ access
def perm_read(self, cr, user, ids, context=None, details=True):
"""
Returns some metadata about the given records.
:param details: if True, \*_uid fields are replaced with the name of the user
:return: list of ownership dictionaries for each requested record
:rtype: list of dictionaries with the following keys:
* id: object id
* create_uid: user who created the record
* create_date: date when the record was created
* write_uid: last user who changed the record
* write_date: date of the last change to the record
* xmlid: XML ID to use to refer to this record (if there is one), in format ``module.name``
"""
if not context:
context = {}
if not ids:
return []
fields = ''
uniq = isinstance(ids, (int, long))
if uniq:
ids = [ids]
fields = ['id']
if self._log_access:
fields += ['create_uid', 'create_date', 'write_uid', 'write_date']
quoted_table = '"%s"' % self._table
fields_str = ",".join('%s.%s'%(quoted_table, field) for field in fields)
query = '''SELECT %s, __imd.module, __imd.name
FROM %s LEFT JOIN ir_model_data __imd
ON (__imd.model = %%s and __imd.res_id = %s.id)
WHERE %s.id IN %%s''' % (fields_str, quoted_table, quoted_table, quoted_table)
cr.execute(query, (self._name, tuple(ids)))
res = cr.dictfetchall()
for r in res:
for key in r:
r[key] = r[key] or False
if details and key in ('write_uid', 'create_uid') and r[key]:
try:
r[key] = self.pool.get('res.users').name_get(cr, user, [r[key]])[0]
except Exception:
pass # Leave the numeric uid there
r['xmlid'] = ("%(module)s.%(name)s" % r) if r['name'] else False
del r['name'], r['module']
if uniq:
return res[ids[0]]
return res
def _check_concurrency(self, cr, ids, context):
if not context:
return
if not (context.get(self.CONCURRENCY_CHECK_FIELD) and self._log_access):
return
check_clause = "(id = %s AND %s < COALESCE(write_date, create_date, (now() at time zone 'UTC'))::timestamp)"
for sub_ids in cr.split_for_in_conditions(ids):
ids_to_check = []
for id in sub_ids:
id_ref = "%s,%s" % (self._name, id)
update_date = context[self.CONCURRENCY_CHECK_FIELD].pop(id_ref, None)
if update_date:
ids_to_check.extend([id, update_date])
if not ids_to_check:
continue
cr.execute("SELECT id FROM %s WHERE %s" % (self._table, " OR ".join([check_clause]*(len(ids_to_check)/2))), tuple(ids_to_check))
res = cr.fetchone()
if res:
# mention the first one only to keep the error message readable
raise except_orm('ConcurrencyException', _('A document was modified since you last viewed it (%s:%d)') % (self._description, res[0]))
def check_access_rights(self, cr, uid, operation, raise_exception=True): # no context on purpose.
"""Verifies that the operation given by ``operation`` is allowed for the user
according to the access rights."""
return self.pool.get('ir.model.access').check(cr, uid, self._name, operation, raise_exception)
def check_create(self, cr, uid, raise_exception=True):
return self.check_access_rights(cr, uid, 'create', raise_exception)
def check_read(self, cr, uid, raise_exception=True):
return self.check_access_rights(cr, uid, 'read', raise_exception)
def check_unlink(self, cr, uid, raise_exception=True):
return self.check_access_rights(cr, uid, 'unlink', raise_exception)
def check_write(self, cr, uid, raise_exception=True):
return self.check_access_rights(cr, uid, 'write', raise_exception)
def check_access_rule(self, cr, uid, ids, operation, context=None):
"""Verifies that the operation given by ``operation`` is allowed for the user
according to ir.rules.
:param operation: one of ``write``, ``unlink``
:raise except_orm: * if current ir.rules do not permit this operation.
:return: None if the operation is allowed
"""
if uid == SUPERUSER_ID:
return
if self.is_transient():
# Only one single implicit access rule for transient models: owner only!
# This is ok to hardcode because we assert that TransientModels always
# have log_access enabled and this the create_uid column is always there.
# And even with _inherits, these fields are always present in the local
# table too, so no need for JOINs.
cr.execute("""SELECT distinct create_uid
FROM %s
WHERE id IN %%s""" % self._table, (tuple(ids),))
uids = [x[0] for x in cr.fetchall()]
if len(uids) != 1 or uids[0] != uid:
raise except_orm(_('AccessError'), '%s access is '
'restricted to your own records for transient models '
'(except for the super-user).' % operation.capitalize())
else:
where_clause, where_params, tables = self.pool.get('ir.rule').domain_get(cr, uid, self._name, operation, context=context)
if where_clause:
where_clause = ' and ' + ' and '.join(where_clause)
for sub_ids in cr.split_for_in_conditions(ids):
cr.execute('SELECT ' + self._table + '.id FROM ' + ','.join(tables) +
' WHERE ' + self._table + '.id IN %s' + where_clause,
[sub_ids] + where_params)
if cr.rowcount != len(sub_ids):
raise except_orm(_('AccessError'),
_('Operation prohibited by access rules, or performed on an already deleted document (Operation: %s, Document type: %s).')
% (operation, self._description))
def unlink(self, cr, uid, ids, context=None):
"""
Delete records with given ids
:param cr: database cursor
:param uid: current user id
:param ids: id or list of ids
:param context: (optional) context arguments, like lang, time zone
:return: True
:raise AccessError: * if user has no unlink rights on the requested object
* if user tries to bypass access rules for unlink on the requested object
:raise UserError: if the record is default property for other records
"""
if not ids:
return True
if isinstance(ids, (int, long)):
ids = [ids]
result_store = self._store_get_values(cr, uid, ids, None, context)
self._check_concurrency(cr, ids, context)
self.check_unlink(cr, uid)
ir_property = self.pool.get('ir.property')
# Check if the records are used as default properties.
domain = [('res_id', '=', False),
('value_reference', 'in', ['%s,%s' % (self._name, i) for i in ids]),
]
if ir_property.search(cr, uid, domain, context=context):
raise except_orm(_('Error'), _('Unable to delete this document because it is used as a default property'))
# Delete the records' properties.
property_ids = ir_property.search(cr, uid, [('res_id', 'in', ['%s,%s' % (self._name, i) for i in ids])], context=context)
ir_property.unlink(cr, uid, property_ids, context=context)
wf_service = netsvc.LocalService("workflow")
for oid in ids:
wf_service.trg_delete(uid, self._name, oid, cr)
self.check_access_rule(cr, uid, ids, 'unlink', context=context)
pool_model_data = self.pool.get('ir.model.data')
ir_values_obj = self.pool.get('ir.values')
for sub_ids in cr.split_for_in_conditions(ids):
cr.execute('delete from ' + self._table + ' ' \
'where id IN %s', (sub_ids,))
# Removing the ir_model_data reference if the record being deleted is a record created by xml/csv file,
# as these are not connected with real database foreign keys, and would be dangling references.
# Note: following steps performed as admin to avoid access rights restrictions, and with no context
# to avoid possible side-effects during admin calls.
# Step 1. Calling unlink of ir_model_data only for the affected IDS
reference_ids = pool_model_data.search(cr, SUPERUSER_ID, [('res_id','in',list(sub_ids)),('model','=',self._name)])
# Step 2. Marching towards the real deletion of referenced records
if reference_ids:
pool_model_data.unlink(cr, SUPERUSER_ID, reference_ids)
# For the same reason, removing the record relevant to ir_values
ir_value_ids = ir_values_obj.search(cr, uid,
['|',('value','in',['%s,%s' % (self._name, sid) for sid in sub_ids]),'&',('res_id','in',list(sub_ids)),('model','=',self._name)],
context=context)
if ir_value_ids:
ir_values_obj.unlink(cr, uid, ir_value_ids, context=context)
for order, object, store_ids, fields in result_store:
if object != self._name:
obj = self.pool.get(object)
cr.execute('select id from '+obj._table+' where id IN %s', (tuple(store_ids),))
rids = map(lambda x: x[0], cr.fetchall())
if rids:
obj._store_set_values(cr, uid, rids, fields, context)
return True
#
# TODO: Validate
#
def write(self, cr, user, ids, vals, context=None):
"""
Update records with given ids with the given field values
:param cr: database cursor
:param user: current user id
:type user: integer
:param ids: object id or list of object ids to update according to **vals**
:param vals: field values to update, e.g {'field_name': new_field_value, ...}
:type vals: dictionary
:param context: (optional) context arguments, e.g. {'lang': 'en_us', 'tz': 'UTC', ...}
:type context: dictionary
:return: True
:raise AccessError: * if user has no write rights on the requested object
* if user tries to bypass access rules for write on the requested object
:raise ValidateError: if user tries to enter invalid value for a field that is not in selection
:raise UserError: if a loop would be created in a hierarchy of objects a result of the operation (such as setting an object as its own parent)
**Note**: The type of field values to pass in ``vals`` for relationship fields is specific:
+ For a many2many field, a list of tuples is expected.
Here is the list of tuple that are accepted, with the corresponding semantics ::
(0, 0, { values }) link to a new record that needs to be created with the given values dictionary
(1, ID, { values }) update the linked record with id = ID (write *values* on it)
(2, ID) remove and delete the linked record with id = ID (calls unlink on ID, that will delete the object completely, and the link to it as well)
(3, ID) cut the link to the linked record with id = ID (delete the relationship between the two objects but does not delete the target object itself)
(4, ID) link to existing record with id = ID (adds a relationship)
(5) unlink all (like using (3,ID) for all linked records)
(6, 0, [IDs]) replace the list of linked IDs (like using (5) then (4,ID) for each ID in the list of IDs)
Example:
[(6, 0, [8, 5, 6, 4])] sets the many2many to ids [8, 5, 6, 4]
+ For a one2many field, a lits of tuples is expected.
Here is the list of tuple that are accepted, with the corresponding semantics ::
(0, 0, { values }) link to a new record that needs to be created with the given values dictionary
(1, ID, { values }) update the linked record with id = ID (write *values* on it)
(2, ID) remove and delete the linked record with id = ID (calls unlink on ID, that will delete the object completely, and the link to it as well)
Example:
[(0, 0, {'field_name':field_value_record1, ...}), (0, 0, {'field_name':field_value_record2, ...})]
+ For a many2one field, simply use the ID of target record, which must already exist, or ``False`` to remove the link.
+ For a reference field, use a string with the model name, a comma, and the target object id (example: ``'product.product, 5'``)
"""
readonly = None
for field in vals.copy():
fobj = None
if field in self._columns:
fobj = self._columns[field]
elif field in self._inherit_fields:
fobj = self._inherit_fields[field][2]
if not fobj:
continue
groups = fobj.write
if groups:
edit = False
for group in groups:
module = group.split(".")[0]
grp = group.split(".")[1]
cr.execute("select count(*) from res_groups_users_rel where gid IN (select res_id from ir_model_data where name=%s and module=%s and model=%s) and uid=%s", \
(grp, module, 'res.groups', user))
readonly = cr.fetchall()
if readonly[0][0] >= 1:
edit = True
break
if not edit:
vals.pop(field)
if not context:
context = {}
if not ids:
return True
if isinstance(ids, (int, long)):
ids = [ids]
self._check_concurrency(cr, ids, context)
self.check_write(cr, user)
result = self._store_get_values(cr, user, ids, vals.keys(), context) or []
# No direct update of parent_left/right
vals.pop('parent_left', None)
vals.pop('parent_right', None)
parents_changed = []
parent_order = self._parent_order or self._order
if self._parent_store and (self._parent_name in vals):
# The parent_left/right computation may take up to
# 5 seconds. No need to recompute the values if the
# parent is the same.
# Note: to respect parent_order, nodes must be processed in
# order, so ``parents_changed`` must be ordered properly.
parent_val = vals[self._parent_name]
if parent_val:
query = "SELECT id FROM %s WHERE id IN %%s AND (%s != %%s OR %s IS NULL) ORDER BY %s" % \
(self._table, self._parent_name, self._parent_name, parent_order)
cr.execute(query, (tuple(ids), parent_val))
else:
query = "SELECT id FROM %s WHERE id IN %%s AND (%s IS NOT NULL) ORDER BY %s" % \
(self._table, self._parent_name, parent_order)
cr.execute(query, (tuple(ids),))
parents_changed = map(operator.itemgetter(0), cr.fetchall())
upd0 = []
upd1 = []
upd_todo = []
updend = []
direct = []
totranslate = context.get('lang', False) and (context['lang'] != 'en_US')
for field in vals:
if field in self._columns:
if self._columns[field]._classic_write and not (hasattr(self._columns[field], '_fnct_inv')):
if (not totranslate) or not self._columns[field].translate:
upd0.append('"'+field+'"='+self._columns[field]._symbol_set[0])
upd1.append(self._columns[field]._symbol_set[1](vals[field]))
direct.append(field)
else:
upd_todo.append(field)
else:
updend.append(field)
if field in self._columns \
and hasattr(self._columns[field], 'selection') \
and vals[field]:
self._check_selection_field_value(cr, user, field, vals[field], context=context)
if self._log_access:
upd0.append('write_uid=%s')
upd0.append("write_date=(now() at time zone 'UTC')")
upd1.append(user)
if len(upd0):
self.check_access_rule(cr, user, ids, 'write', context=context)
for sub_ids in cr.split_for_in_conditions(ids):
cr.execute('update ' + self._table + ' set ' + ','.join(upd0) + ' ' \
'where id IN %s', upd1 + [sub_ids])
if cr.rowcount != len(sub_ids):
raise except_orm(_('AccessError'),
_('One of the records you are trying to modify has already been deleted (Document type: %s).') % self._description)
if totranslate:
# TODO: optimize
for f in direct:
if self._columns[f].translate:
src_trans = self.pool.get(self._name).read(cr, user, ids, [f])[0][f]
if not src_trans:
src_trans = vals[f]
# Inserting value to DB
self.write(cr, user, ids, {f: vals[f]})
self.pool.get('ir.translation')._set_ids(cr, user, self._name+','+f, 'model', context['lang'], ids, vals[f], src_trans)
# call the 'set' method of fields which are not classic_write
upd_todo.sort(lambda x, y: self._columns[x].priority-self._columns[y].priority)
# default element in context must be removed when call a one2many or many2many
rel_context = context.copy()
for c in context.items():
if c[0].startswith('default_'):
del rel_context[c[0]]
for field in upd_todo:
for id in ids:
result += self._columns[field].set(cr, self, id, field, vals[field], user, context=rel_context) or []
unknown_fields = updend[:]
for table in self._inherits:
col = self._inherits[table]
nids = []
for sub_ids in cr.split_for_in_conditions(ids):
cr.execute('select distinct "'+col+'" from "'+self._table+'" ' \
'where id IN %s', (sub_ids,))
nids.extend([x[0] for x in cr.fetchall()])
v = {}
for val in updend:
if self._inherit_fields[val][0] == table:
v[val] = vals[val]
unknown_fields.remove(val)
if v:
self.pool.get(table).write(cr, user, nids, v, context)
if unknown_fields:
_logger.warning(
'No such field(s) in model %s: %s.',
self._name, ', '.join(unknown_fields))
self._validate(cr, user, ids, context)
# TODO: use _order to set dest at the right position and not first node of parent
# We can't defer parent_store computation because the stored function
# fields that are computer may refer (directly or indirectly) to
# parent_left/right (via a child_of domain)
if parents_changed:
if self.pool._init:
self.pool._init_parent[self._name] = True
else:
order = self._parent_order or self._order
parent_val = vals[self._parent_name]
if parent_val:
clause, params = '%s=%%s' % (self._parent_name,), (parent_val,)
else:
clause, params = '%s IS NULL' % (self._parent_name,), ()
for id in parents_changed:
cr.execute('SELECT parent_left, parent_right FROM %s WHERE id=%%s' % (self._table,), (id,))
pleft, pright = cr.fetchone()
distance = pright - pleft + 1
# Positions of current siblings, to locate proper insertion point;
# this can _not_ be fetched outside the loop, as it needs to be refreshed
# after each update, in case several nodes are sequentially inserted one
# next to the other (i.e computed incrementally)
cr.execute('SELECT parent_right, id FROM %s WHERE %s ORDER BY %s' % (self._table, clause, parent_order), params)
parents = cr.fetchall()
# Find Position of the element
position = None
for (parent_pright, parent_id) in parents:
if parent_id == id:
break
position = parent_pright + 1
# It's the first node of the parent
if not position:
if not parent_val:
position = 1
else:
cr.execute('select parent_left from '+self._table+' where id=%s', (parent_val,))
position = cr.fetchone()[0] + 1
if pleft < position <= pright:
raise except_orm(_('UserError'), _('Recursivity Detected.'))
if pleft < position:
cr.execute('update '+self._table+' set parent_left=parent_left+%s where parent_left>=%s', (distance, position))
cr.execute('update '+self._table+' set parent_right=parent_right+%s where parent_right>=%s', (distance, position))
cr.execute('update '+self._table+' set parent_left=parent_left+%s, parent_right=parent_right+%s where parent_left>=%s and parent_left<%s', (position-pleft, position-pleft, pleft, pright))
else:
cr.execute('update '+self._table+' set parent_left=parent_left+%s where parent_left>=%s', (distance, position))
cr.execute('update '+self._table+' set parent_right=parent_right+%s where parent_right>=%s', (distance, position))
cr.execute('update '+self._table+' set parent_left=parent_left-%s, parent_right=parent_right-%s where parent_left>=%s and parent_left<%s', (pleft-position+distance, pleft-position+distance, pleft+distance, pright+distance))
result += self._store_get_values(cr, user, ids, vals.keys(), context)
result.sort()
done = {}
for order, object, ids_to_update, fields_to_recompute in result:
key = (object, tuple(fields_to_recompute))
done.setdefault(key, {})
# avoid to do several times the same computation
todo = []
for id in ids_to_update:
if id not in done[key]:
done[key][id] = True
todo.append(id)
self.pool.get(object)._store_set_values(cr, user, todo, fields_to_recompute, context)
wf_service = netsvc.LocalService("workflow")
for id in ids:
wf_service.trg_write(user, self._name, id, cr)
return True
#
# TODO: Should set perm to user.xxx
#
def create(self, cr, user, vals, context=None):
"""
Create a new record for the model.
The values for the new record are initialized using the ``vals``
argument, and if necessary the result of ``default_get()``.
:param cr: database cursor
:param user: current user id
:type user: integer
:param vals: field values for new record, e.g {'field_name': field_value, ...}
:type vals: dictionary
:param context: optional context arguments, e.g. {'lang': 'en_us', 'tz': 'UTC', ...}
:type context: dictionary
:return: id of new record created
:raise AccessError: * if user has no create rights on the requested object
* if user tries to bypass access rules for create on the requested object
:raise ValidateError: if user tries to enter invalid value for a field that is not in selection
:raise UserError: if a loop would be created in a hierarchy of objects a result of the operation (such as setting an object as its own parent)
**Note**: The type of field values to pass in ``vals`` for relationship fields is specific.
Please see the description of the :py:meth:`~osv.osv.osv.write` method for details about the possible values and how
to specify them.
"""
if not context:
context = {}
if self.is_transient():
self._transient_vacuum(cr, user)
self.check_create(cr, user)
vals = self._add_missing_default_values(cr, user, vals, context)
tocreate = {}
for v in self._inherits:
if self._inherits[v] not in vals:
tocreate[v] = {}
else:
tocreate[v] = {'id': vals[self._inherits[v]]}
(upd0, upd1, upd2) = ('', '', [])
upd_todo = []
unknown_fields = []
for v in vals.keys():
if v in self._inherit_fields and v not in self._columns:
(table, col, col_detail, original_parent) = self._inherit_fields[v]
tocreate[table][v] = vals[v]
del vals[v]
else:
if (v not in self._inherit_fields) and (v not in self._columns):
del vals[v]
unknown_fields.append(v)
if unknown_fields:
_logger.warning(
'No such field(s) in model %s: %s.',
self._name, ', '.join(unknown_fields))
# Try-except added to filter the creation of those records whose filds are readonly.
# Example : any dashboard which has all the fields readonly.(due to Views(database views))
try:
cr.execute("SELECT nextval('"+self._sequence+"')")
except:
raise except_orm(_('UserError'),
_('You cannot perform this operation. New Record Creation is not allowed for this object as this object is for reporting purpose.'))
id_new = cr.fetchone()[0]
for table in tocreate:
if self._inherits[table] in vals:
del vals[self._inherits[table]]
record_id = tocreate[table].pop('id', None)
# When linking/creating parent records, force context without 'no_store_function' key that
# defers stored functions computing, as these won't be computed in batch at the end of create().
parent_context = dict(context)
parent_context.pop('no_store_function', None)
if record_id is None or not record_id:
record_id = self.pool.get(table).create(cr, user, tocreate[table], context=parent_context)
else:
self.pool.get(table).write(cr, user, [record_id], tocreate[table], context=parent_context)
upd0 += ',' + self._inherits[table]
upd1 += ',%s'
upd2.append(record_id)
#Start : Set bool fields to be False if they are not touched(to make search more powerful)
bool_fields = [x for x in self._columns.keys() if self._columns[x]._type=='boolean']
for bool_field in bool_fields:
if bool_field not in vals:
vals[bool_field] = False
#End
for field in vals.copy():
fobj = None
if field in self._columns:
fobj = self._columns[field]
else:
fobj = self._inherit_fields[field][2]
if not fobj:
continue
groups = fobj.write
if groups:
edit = False
for group in groups:
module = group.split(".")[0]
grp = group.split(".")[1]
cr.execute("select count(*) from res_groups_users_rel where gid IN (select res_id from ir_model_data where name='%s' and module='%s' and model='%s') and uid=%s" % \
(grp, module, 'res.groups', user))
readonly = cr.fetchall()
if readonly[0][0] >= 1:
edit = True
break
elif readonly[0][0] == 0:
edit = False
else:
edit = False
if not edit:
vals.pop(field)
for field in vals:
if self._columns[field]._classic_write:
upd0 = upd0 + ',"' + field + '"'
upd1 = upd1 + ',' + self._columns[field]._symbol_set[0]
upd2.append(self._columns[field]._symbol_set[1](vals[field]))
else:
if not isinstance(self._columns[field], fields.related):
upd_todo.append(field)
if field in self._columns \
and hasattr(self._columns[field], 'selection') \
and vals[field]:
self._check_selection_field_value(cr, user, field, vals[field], context=context)
if self._log_access:
upd0 += ',create_uid,create_date'
upd1 += ",%s,(now() at time zone 'UTC')"
upd2.append(user)
cr.execute('insert into "'+self._table+'" (id'+upd0+") values ("+str(id_new)+upd1+')', tuple(upd2))
self.check_access_rule(cr, user, [id_new], 'create', context=context)
upd_todo.sort(lambda x, y: self._columns[x].priority-self._columns[y].priority)
if self._parent_store and not context.get('defer_parent_store_computation'):
if self.pool._init:
self.pool._init_parent[self._name] = True
else:
parent = vals.get(self._parent_name, False)
if parent:
cr.execute('select parent_right from '+self._table+' where '+self._parent_name+'=%s order by '+(self._parent_order or self._order), (parent,))
pleft_old = None
result_p = cr.fetchall()
for (pleft,) in result_p:
if not pleft:
break
pleft_old = pleft
if not pleft_old:
cr.execute('select parent_left from '+self._table+' where id=%s', (parent,))
pleft_old = cr.fetchone()[0]
pleft = pleft_old
else:
cr.execute('select max(parent_right) from '+self._table)
pleft = cr.fetchone()[0] or 0
cr.execute('update '+self._table+' set parent_left=parent_left+2 where parent_left>%s', (pleft,))
cr.execute('update '+self._table+' set parent_right=parent_right+2 where parent_right>%s', (pleft,))
cr.execute('update '+self._table+' set parent_left=%s,parent_right=%s where id=%s', (pleft+1, pleft+2, id_new))
# default element in context must be remove when call a one2many or many2many
rel_context = context.copy()
for c in context.items():
if c[0].startswith('default_'):
del rel_context[c[0]]
result = []
for field in upd_todo:
result += self._columns[field].set(cr, self, id_new, field, vals[field], user, rel_context) or []
self._validate(cr, user, [id_new], context)
if not context.get('no_store_function', False):
result += self._store_get_values(cr, user, [id_new], vals.keys(), context)
result.sort()
done = []
for order, object, ids, fields2 in result:
if not (object, ids, fields2) in done:
self.pool.get(object)._store_set_values(cr, user, ids, fields2, context)
done.append((object, ids, fields2))
if self._log_create and not (context and context.get('no_store_function', False)):
message = self._description + \
" '" + \
self.name_get(cr, user, [id_new], context=context)[0][1] + \
"' " + _("created.")
self.log(cr, user, id_new, message, True, context=context)
wf_service = netsvc.LocalService("workflow")
wf_service.trg_create(user, self._name, id_new, cr)
return id_new
def browse(self, cr, uid, select, context=None, list_class=None, fields_process=None):
"""Fetch records as objects allowing to use dot notation to browse fields and relations
:param cr: database cursor
:param uid: current user id
:param select: id or list of ids.
:param context: context arguments, like lang, time zone
:rtype: object or list of objects requested
"""
self._list_class = list_class or browse_record_list
cache = {}
# need to accepts ints and longs because ids coming from a method
# launched by button in the interface have a type long...
if isinstance(select, (int, long)):
return browse_record(cr, uid, select, self, cache, context=context, list_class=self._list_class, fields_process=fields_process)
elif isinstance(select, list):
return self._list_class([browse_record(cr, uid, id, self, cache, context=context, list_class=self._list_class, fields_process=fields_process) for id in select], context=context)
else:
return browse_null()
def _store_get_values(self, cr, uid, ids, fields, context):
"""Returns an ordered list of fields.functions to call due to
an update operation on ``fields`` of records with ``ids``,
obtained by calling the 'store' functions of these fields,
as setup by their 'store' attribute.
:return: [(priority, model_name, [record_ids,], [function_fields,])]
"""
if fields is None: fields = []
stored_functions = self.pool._store_function.get(self._name, [])
# use indexed names for the details of the stored_functions:
model_name_, func_field_to_compute_, id_mapping_fnct_, trigger_fields_, priority_ = range(5)
# only keep functions that should be triggered for the ``fields``
# being written to.
to_compute = [f for f in stored_functions \
if ((not f[trigger_fields_]) or set(fields).intersection(f[trigger_fields_]))]
mapping = {}
for function in to_compute:
# use admin user for accessing objects having rules defined on store fields
target_ids = [id for id in function[id_mapping_fnct_](self, cr, SUPERUSER_ID, ids, context) if id]
# the compound key must consider the priority and model name
key = (function[priority_], function[model_name_])
for target_id in target_ids:
mapping.setdefault(key, {}).setdefault(target_id,set()).add(tuple(function))
# Here mapping looks like:
# { (10, 'model_a') : { target_id1: [ (function_1_tuple, function_2_tuple) ], ... }
# (20, 'model_a') : { target_id2: [ (function_3_tuple, function_4_tuple) ], ... }
# (99, 'model_a') : { target_id1: [ (function_5_tuple, function_6_tuple) ], ... }
# }
# Now we need to generate the batch function calls list
# call_map =
# { (10, 'model_a') : [(10, 'model_a', [record_ids,], [function_fields,])] }
call_map = {}
for ((priority,model), id_map) in mapping.iteritems():
functions_ids_maps = {}
# function_ids_maps =
# { (function_1_tuple, function_2_tuple) : [target_id1, target_id2, ..] }
for id, functions in id_map.iteritems():
functions_ids_maps.setdefault(tuple(functions), []).append(id)
for functions, ids in functions_ids_maps.iteritems():
call_map.setdefault((priority,model),[]).append((priority, model, ids,
[f[func_field_to_compute_] for f in functions]))
ordered_keys = call_map.keys()
ordered_keys.sort()
result = []
if ordered_keys:
result = reduce(operator.add, (call_map[k] for k in ordered_keys))
return result
def _store_set_values(self, cr, uid, ids, fields, context):
"""Calls the fields.function's "implementation function" for all ``fields``, on records with ``ids`` (taking care of
respecting ``multi`` attributes), and stores the resulting values in the database directly."""
if not ids:
return True
field_flag = False
field_dict = {}
if self._log_access:
cr.execute('select id,write_date from '+self._table+' where id IN %s', (tuple(ids),))
res = cr.fetchall()
for r in res:
if r[1]:
field_dict.setdefault(r[0], [])
res_date = time.strptime((r[1])[:19], '%Y-%m-%d %H:%M:%S')
write_date = datetime.datetime.fromtimestamp(time.mktime(res_date))
for i in self.pool._store_function.get(self._name, []):
if i[5]:
up_write_date = write_date + datetime.timedelta(hours=i[5])
if datetime.datetime.now() < up_write_date:
if i[1] in fields:
field_dict[r[0]].append(i[1])
if not field_flag:
field_flag = True
todo = {}
keys = []
for f in fields:
if self._columns[f]._multi not in keys:
keys.append(self._columns[f]._multi)
todo.setdefault(self._columns[f]._multi, [])
todo[self._columns[f]._multi].append(f)
for key in keys:
val = todo[key]
if key:
# use admin user for accessing objects having rules defined on store fields
result = self._columns[val[0]].get(cr, self, ids, val, SUPERUSER_ID, context=context)
for id, value in result.items():
if field_flag:
for f in value.keys():
if f in field_dict[id]:
value.pop(f)
upd0 = []
upd1 = []
for v in value:
if v not in val:
continue
if self._columns[v]._type in ('many2one', 'one2one'):
try:
value[v] = value[v][0]
except:
pass
upd0.append('"'+v+'"='+self._columns[v]._symbol_set[0])
upd1.append(self._columns[v]._symbol_set[1](value[v]))
upd1.append(id)
if upd0 and upd1:
cr.execute('update "' + self._table + '" set ' + \
','.join(upd0) + ' where id = %s', upd1)
else:
for f in val:
# use admin user for accessing objects having rules defined on store fields
result = self._columns[f].get(cr, self, ids, f, SUPERUSER_ID, context=context)
for r in result.keys():
if field_flag:
if r in field_dict.keys():
if f in field_dict[r]:
result.pop(r)
for id, value in result.items():
if self._columns[f]._type in ('many2one', 'one2one'):
try:
value = value[0]
except:
pass
cr.execute('update "' + self._table + '" set ' + \
'"'+f+'"='+self._columns[f]._symbol_set[0] + ' where id = %s', (self._columns[f]._symbol_set[1](value), id))
return True
#
# TODO: Validate
#
def perm_write(self, cr, user, ids, fields, context=None):
raise NotImplementedError(_('This method does not exist anymore'))
# TODO: ameliorer avec NULL
def _where_calc(self, cr, user, domain, active_test=True, context=None):
"""Computes the WHERE clause needed to implement an OpenERP domain.
:param domain: the domain to compute
:type domain: list
:param active_test: whether the default filtering of records with ``active``
field set to ``False`` should be applied.
:return: the query expressing the given domain as provided in domain
:rtype: osv.query.Query
"""
if not context:
context = {}
domain = domain[:]
# if the object has a field named 'active', filter out all inactive
# records unless they were explicitely asked for
if 'active' in self._all_columns and (active_test and context.get('active_test', True)):
if domain:
# the item[0] trick below works for domain items and '&'/'|'/'!'
# operators too
if not any(item[0] == 'active' for item in domain):
domain.insert(0, ('active', '=', 1))
else:
domain = [('active', '=', 1)]
if domain:
e = expression.expression(cr, user, domain, self, context)
tables = e.get_tables()
where_clause, where_params = e.to_sql()
where_clause = where_clause and [where_clause] or []
else:
where_clause, where_params, tables = [], [], ['"%s"' % self._table]
return Query(tables, where_clause, where_params)
def _check_qorder(self, word):
if not regex_order.match(word):
raise except_orm(_('AccessError'), _('Invalid "order" specified. A valid "order" specification is a comma-separated list of valid field names (optionally followed by asc/desc for the direction)'))
return True
def _apply_ir_rules(self, cr, uid, query, mode='read', context=None):
"""Add what's missing in ``query`` to implement all appropriate ir.rules
(using the ``model_name``'s rules or the current model's rules if ``model_name`` is None)
:param query: the current query object
"""
def apply_rule(added_clause, added_params, added_tables, parent_model=None, child_object=None):
if added_clause:
if parent_model and child_object:
# as inherited rules are being applied, we need to add the missing JOIN
# to reach the parent table (if it was not JOINed yet in the query)
child_object._inherits_join_add(child_object, parent_model, query)
query.where_clause += added_clause
query.where_clause_params += added_params
for table in added_tables:
if table not in query.tables:
query.tables.append(table)
return True
return False
# apply main rules on the object
rule_obj = self.pool.get('ir.rule')
apply_rule(*rule_obj.domain_get(cr, uid, self._name, mode, context=context))
# apply ir.rules from the parents (through _inherits)
for inherited_model in self._inherits:
kwargs = dict(parent_model=inherited_model, child_object=self) #workaround for python2.5
apply_rule(*rule_obj.domain_get(cr, uid, inherited_model, mode, context=context), **kwargs)
def _generate_m2o_order_by(self, order_field, query):
"""
Add possibly missing JOIN to ``query`` and generate the ORDER BY clause for m2o fields,
either native m2o fields or function/related fields that are stored, including
intermediate JOINs for inheritance if required.
:return: the qualified field name to use in an ORDER BY clause to sort by ``order_field``
"""
if order_field not in self._columns and order_field in self._inherit_fields:
# also add missing joins for reaching the table containing the m2o field
qualified_field = self._inherits_join_calc(order_field, query)
order_field_column = self._inherit_fields[order_field][2]
else:
qualified_field = '"%s"."%s"' % (self._table, order_field)
order_field_column = self._columns[order_field]
assert order_field_column._type == 'many2one', 'Invalid field passed to _generate_m2o_order_by()'
if not order_field_column._classic_write and not getattr(order_field_column, 'store', False):
_logger.debug("Many2one function/related fields must be stored " \
"to be used as ordering fields! Ignoring sorting for %s.%s",
self._name, order_field)
return
# figure out the applicable order_by for the m2o
dest_model = self.pool.get(order_field_column._obj)
m2o_order = dest_model._order
if not regex_order.match(m2o_order):
# _order is complex, can't use it here, so we default to _rec_name
m2o_order = dest_model._rec_name
else:
# extract the field names, to be able to qualify them and add desc/asc
m2o_order_list = []
for order_part in m2o_order.split(","):
m2o_order_list.append(order_part.strip().split(" ",1)[0].strip())
m2o_order = m2o_order_list
# Join the dest m2o table if it's not joined yet. We use [LEFT] OUTER join here
# as we don't want to exclude results that have NULL values for the m2o
src_table, src_field = qualified_field.replace('"','').split('.', 1)
query.join((src_table, dest_model._table, src_field, 'id'), outer=True)
qualify = lambda field: '"%s"."%s"' % (dest_model._table, field)
return map(qualify, m2o_order) if isinstance(m2o_order, list) else qualify(m2o_order)
def _generate_order_by(self, order_spec, query):
"""
Attempt to consruct an appropriate ORDER BY clause based on order_spec, which must be
a comma-separated list of valid field names, optionally followed by an ASC or DESC direction.
:raise" except_orm in case order_spec is malformed
"""
order_by_clause = self._order
if order_spec:
order_by_elements = []
self._check_qorder(order_spec)
for order_part in order_spec.split(','):
order_split = order_part.strip().split(' ')
order_field = order_split[0].strip()
order_direction = order_split[1].strip() if len(order_split) == 2 else ''
inner_clause = None
if order_field == 'id':
order_by_clause = '"%s"."%s"' % (self._table, order_field)
elif order_field in self._columns:
order_column = self._columns[order_field]
if order_column._classic_read:
inner_clause = '"%s"."%s"' % (self._table, order_field)
elif order_column._type == 'many2one':
inner_clause = self._generate_m2o_order_by(order_field, query)
else:
continue # ignore non-readable or "non-joinable" fields
elif order_field in self._inherit_fields:
parent_obj = self.pool.get(self._inherit_fields[order_field][3])
order_column = parent_obj._columns[order_field]
if order_column._classic_read:
inner_clause = self._inherits_join_calc(order_field, query)
elif order_column._type == 'many2one':
inner_clause = self._generate_m2o_order_by(order_field, query)
else:
continue # ignore non-readable or "non-joinable" fields
if inner_clause:
if isinstance(inner_clause, list):
for clause in inner_clause:
order_by_elements.append("%s %s" % (clause, order_direction))
else:
order_by_elements.append("%s %s" % (inner_clause, order_direction))
if order_by_elements:
order_by_clause = ",".join(order_by_elements)
return order_by_clause and (' ORDER BY %s ' % order_by_clause) or ''
def _search(self, cr, user, args, offset=0, limit=None, order=None, context=None, count=False, access_rights_uid=None):
"""
Private implementation of search() method, allowing specifying the uid to use for the access right check.
This is useful for example when filling in the selection list for a drop-down and avoiding access rights errors,
by specifying ``access_rights_uid=1`` to bypass access rights check, but not ir.rules!
This is ok at the security level because this method is private and not callable through XML-RPC.
:param access_rights_uid: optional user ID to use when checking access rights
(not for ir.rules, this is only for ir.model.access)
"""
if context is None:
context = {}
self.check_read(cr, access_rights_uid or user)
# For transient models, restrict acces to the current user, except for the super-user
if self.is_transient() and self._log_access and user != SUPERUSER_ID:
args = expression.AND(([('create_uid', '=', user)], args or []))
query = self._where_calc(cr, user, args, context=context)
self._apply_ir_rules(cr, user, query, 'read', context=context)
order_by = self._generate_order_by(order, query)
from_clause, where_clause, where_clause_params = query.get_sql()
limit_str = limit and ' limit %d' % limit or ''
offset_str = offset and ' offset %d' % offset or ''
where_str = where_clause and (" WHERE %s" % where_clause) or ''
if count:
cr.execute('SELECT count("%s".id) FROM ' % self._table + from_clause + where_str + limit_str + offset_str, where_clause_params)
res = cr.fetchall()
return res[0][0]
cr.execute('SELECT "%s".id FROM ' % self._table + from_clause + where_str + order_by + limit_str + offset_str, where_clause_params)
res = cr.fetchall()
return [x[0] for x in res]
# returns the different values ever entered for one field
# this is used, for example, in the client when the user hits enter on
# a char field
def distinct_field_get(self, cr, uid, field, value, args=None, offset=0, limit=None):
if not args:
args = []
if field in self._inherit_fields:
return self.pool.get(self._inherit_fields[field][0]).distinct_field_get(cr, uid, field, value, args, offset, limit)
else:
return self._columns[field].search(cr, self, args, field, value, offset, limit, uid)
def copy_data(self, cr, uid, id, default=None, context=None):
"""
Copy given record's data with all its fields values
:param cr: database cursor
:param user: current user id
:param id: id of the record to copy
:param default: field values to override in the original values of the copied record
:type default: dictionary
:param context: context arguments, like lang, time zone
:type context: dictionary
:return: dictionary containing all the field values
"""
if context is None:
context = {}
# avoid recursion through already copied records in case of circular relationship
seen_map = context.setdefault('__copy_data_seen',{})
if id in seen_map.setdefault(self._name,[]):
return
seen_map[self._name].append(id)
if default is None:
default = {}
if 'state' not in default:
if 'state' in self._defaults:
if callable(self._defaults['state']):
default['state'] = self._defaults['state'](self, cr, uid, context)
else:
default['state'] = self._defaults['state']
context_wo_lang = context.copy()
if 'lang' in context:
del context_wo_lang['lang']
data = self.read(cr, uid, [id,], context=context_wo_lang)
if data:
data = data[0]
else:
raise IndexError( _("Record #%d of %s not found, cannot copy!") %( id, self._name))
# TODO it seems fields_get can be replaced by _all_columns (no need for translation)
fields = self.fields_get(cr, uid, context=context)
for f in fields:
ftype = fields[f]['type']
if self._log_access and f in LOG_ACCESS_COLUMNS:
del data[f]
if f in default:
data[f] = default[f]
elif 'function' in fields[f]:
del data[f]
elif ftype == 'many2one':
try:
data[f] = data[f] and data[f][0]
except:
pass
elif ftype in ('one2many', 'one2one'):
res = []
rel = self.pool.get(fields[f]['relation'])
if data[f]:
# duplicate following the order of the ids
# because we'll rely on it later for copying
# translations in copy_translation()!
data[f].sort()
for rel_id in data[f]:
# the lines are first duplicated using the wrong (old)
# parent but then are reassigned to the correct one thanks
# to the (0, 0, ...)
d = rel.copy_data(cr, uid, rel_id, context=context)
if d:
res.append((0, 0, d))
data[f] = res
elif ftype == 'many2many':
data[f] = [(6, 0, data[f])]
del data['id']
# make sure we don't break the current parent_store structure and
# force a clean recompute!
for parent_column in ['parent_left', 'parent_right']:
data.pop(parent_column, None)
# Remove _inherits field's from data recursively, missing parents will
# be created by create() (so that copy() copy everything).
def remove_ids(inherits_dict):
for parent_table in inherits_dict:
del data[inherits_dict[parent_table]]
remove_ids(self.pool.get(parent_table)._inherits)
remove_ids(self._inherits)
return data
def copy_translations(self, cr, uid, old_id, new_id, context=None):
if context is None:
context = {}
# avoid recursion through already copied records in case of circular relationship
seen_map = context.setdefault('__copy_translations_seen',{})
if old_id in seen_map.setdefault(self._name,[]):
return
seen_map[self._name].append(old_id)
trans_obj = self.pool.get('ir.translation')
# TODO it seems fields_get can be replaced by _all_columns (no need for translation)
fields = self.fields_get(cr, uid, context=context)
translation_records = []
for field_name, field_def in fields.items():
# we must recursively copy the translations for o2o and o2m
if field_def['type'] in ('one2one', 'one2many'):
target_obj = self.pool.get(field_def['relation'])
old_record, new_record = self.read(cr, uid, [old_id, new_id], [field_name], context=context)
# here we rely on the order of the ids to match the translations
# as foreseen in copy_data()
old_children = sorted(old_record[field_name])
new_children = sorted(new_record[field_name])
for (old_child, new_child) in zip(old_children, new_children):
target_obj.copy_translations(cr, uid, old_child, new_child, context=context)
# and for translatable fields we keep them for copy
elif field_def.get('translate'):
trans_name = ''
if field_name in self._columns:
trans_name = self._name + "," + field_name
elif field_name in self._inherit_fields:
trans_name = self._inherit_fields[field_name][0] + "," + field_name
if trans_name:
trans_ids = trans_obj.search(cr, uid, [
('name', '=', trans_name),
('res_id', '=', old_id)
])
translation_records.extend(trans_obj.read(cr, uid, trans_ids, context=context))
for record in translation_records:
del record['id']
record['res_id'] = new_id
trans_obj.create(cr, uid, record, context=context)
def copy(self, cr, uid, id, default=None, context=None):
"""
Duplicate record with given id updating it with default values
:param cr: database cursor
:param uid: current user id
:param id: id of the record to copy
:param default: dictionary of field values to override in the original values of the copied record, e.g: ``{'field_name': overriden_value, ...}``
:type default: dictionary
:param context: context arguments, like lang, time zone
:type context: dictionary
:return: id of the newly created record
"""
if context is None:
context = {}
context = context.copy()
data = self.copy_data(cr, uid, id, default, context)
new_id = self.create(cr, uid, data, context)
self.copy_translations(cr, uid, id, new_id, context)
return new_id
def exists(self, cr, uid, ids, context=None):
"""Checks whether the given id or ids exist in this model,
and return the list of ids that do. This is simple to use for
a truth test on a browse_record::
if record.exists():
pass
:param ids: id or list of ids to check for existence
:type ids: int or [int]
:return: the list of ids that currently exist, out of
the given `ids`
"""
if type(ids) in (int, long):
ids = [ids]
query = 'SELECT id FROM "%s"' % (self._table)
cr.execute(query + "WHERE ID IN %s", (tuple(ids),))
return [x[0] for x in cr.fetchall()]
def check_recursion(self, cr, uid, ids, context=None, parent=None):
_logger.warning("You are using deprecated %s.check_recursion(). Please use the '_check_recursion()' instead!" % \
self._name)
assert parent is None or parent in self._columns or parent in self._inherit_fields,\
"The 'parent' parameter passed to check_recursion() must be None or a valid field name"
return self._check_recursion(cr, uid, ids, context, parent)
def _check_recursion(self, cr, uid, ids, context=None, parent=None):
"""
Verifies that there is no loop in a hierarchical structure of records,
by following the parent relationship using the **parent** field until a loop
is detected or until a top-level record is found.
:param cr: database cursor
:param uid: current user id
:param ids: list of ids of records to check
:param parent: optional parent field name (default: ``self._parent_name = parent_id``)
:return: **True** if the operation can proceed safely, or **False** if an infinite loop is detected.
"""
if not parent:
parent = self._parent_name
ids_parent = ids[:]
query = 'SELECT distinct "%s" FROM "%s" WHERE id IN %%s' % (parent, self._table)
while ids_parent:
ids_parent2 = []
for i in range(0, len(ids), cr.IN_MAX):
sub_ids_parent = ids_parent[i:i+cr.IN_MAX]
cr.execute(query, (tuple(sub_ids_parent),))
ids_parent2.extend(filter(None, map(lambda x: x[0], cr.fetchall())))
ids_parent = ids_parent2
for i in ids_parent:
if i in ids:
return False
return True
def _get_external_ids(self, cr, uid, ids, *args, **kwargs):
"""Retrieve the External ID(s) of any database record.
**Synopsis**: ``_get_xml_ids(cr, uid, ids) -> { 'id': ['module.xml_id'] }``
:return: map of ids to the list of their fully qualified External IDs
in the form ``module.key``, or an empty list when there's no External
ID for a record, e.g.::
{ 'id': ['module.ext_id', 'module.ext_id_bis'],
'id2': [] }
"""
ir_model_data = self.pool.get('ir.model.data')
data_ids = ir_model_data.search(cr, uid, [('model', '=', self._name), ('res_id', 'in', ids)])
data_results = ir_model_data.read(cr, uid, data_ids, ['module', 'name', 'res_id'])
result = {}
for id in ids:
# can't use dict.fromkeys() as the list would be shared!
result[id] = []
for record in data_results:
result[record['res_id']].append('%(module)s.%(name)s' % record)
return result
def get_external_id(self, cr, uid, ids, *args, **kwargs):
"""Retrieve the External ID of any database record, if there
is one. This method works as a possible implementation
for a function field, to be able to add it to any
model object easily, referencing it as ``Model.get_external_id``.
When multiple External IDs exist for a record, only one
of them is returned (randomly).
:return: map of ids to their fully qualified XML ID,
defaulting to an empty string when there's none
(to be usable as a function field),
e.g.::
{ 'id': 'module.ext_id',
'id2': '' }
"""
results = self._get_xml_ids(cr, uid, ids)
for k, v in results.iteritems():
if results[k]:
results[k] = v[0]
else:
results[k] = ''
return results
# backwards compatibility
get_xml_id = get_external_id
_get_xml_ids = _get_external_ids
# Transience
def is_transient(self):
""" Return whether the model is transient.
See TransientModel.
"""
return self._transient
def _transient_clean_rows_older_than(self, cr, seconds):
assert self._transient, "Model %s is not transient, it cannot be vacuumed!" % self._name
cr.execute("SELECT id FROM " + self._table + " WHERE"
" COALESCE(write_date, create_date, (now() at time zone 'UTC'))::timestamp <"
" ((now() at time zone 'UTC') - interval %s)", ("%s seconds" % seconds,))
ids = [x[0] for x in cr.fetchall()]
self.unlink(cr, SUPERUSER_ID, ids)
def _transient_clean_old_rows(self, cr, count):
assert self._transient, "Model %s is not transient, it cannot be vacuumed!" % self._name
cr.execute(
"SELECT id, COALESCE(write_date, create_date, (now() at time zone 'UTC'))::timestamp"
" AS t FROM " + self._table +
" ORDER BY t LIMIT %s", (count,))
ids = [x[0] for x in cr.fetchall()]
self.unlink(cr, SUPERUSER_ID, ids)
def _transient_vacuum(self, cr, uid, force=False):
"""Clean the transient records.
This unlinks old records from the transient model tables whenever the
"_transient_max_count" or "_max_age" conditions (if any) are reached.
Actual cleaning will happen only once every "_transient_check_time" calls.
This means this method can be called frequently called (e.g. whenever
a new record is created).
"""
assert self._transient, "Model %s is not transient, it cannot be vacuumed!" % self._name
self._transient_check_count += 1
if (not force) and (self._transient_check_count % self._transient_check_time):
self._transient_check_count = 0
return True
# Age-based expiration
if self._transient_max_hours:
self._transient_clean_rows_older_than(cr, self._transient_max_hours * 60 * 60)
# Count-based expiration
if self._transient_max_count:
self._transient_clean_old_rows(cr, self._transient_max_count)
return True
def resolve_o2m_commands_to_record_dicts(self, cr, uid, field_name, o2m_commands, fields=None, context=None):
""" Serializes o2m commands into record dictionaries (as if
all the o2m records came from the database via a read()), and
returns an iterable over these dictionaries.
Because o2m commands might be creation commands, not all
record ids will contain an ``id`` field. Commands matching an
existing record (``UPDATE`` and ``LINK_TO``) will have an id.
.. note:: ``CREATE``, ``UPDATE`` and ``LINK_TO`` stand for the
o2m command codes ``0``, ``1`` and ``4``
respectively
:param field_name: name of the o2m field matching the commands
:type field_name: str
:param o2m_commands: one2many commands to execute on ``field_name``
:type o2m_commands: list((int|False, int|False, dict|False))
:param fields: list of fields to read from the database, when applicable
:type fields: list(str)
:raises AssertionError: if a command is not ``CREATE``, ``UPDATE`` or ``LINK_TO``
:returns: o2m records in a shape similar to that returned by
``read()`` (except records may be missing the ``id``
field if they don't exist in db)
:rtype: ``list(dict)``
"""
o2m_model = self._all_columns[field_name].column._obj
# convert single ids and pairs to tripled commands
commands = []
for o2m_command in o2m_commands:
if not isinstance(o2m_command, (list, tuple)):
command = 4
commands.append((command, o2m_command, False))
elif len(o2m_command) == 1:
(command,) = o2m_command
commands.append((command, False, False))
elif len(o2m_command) == 2:
command, id = o2m_command
commands.append((command, id, False))
else:
command = o2m_command[0]
commands.append(o2m_command)
assert command in (0, 1, 4), \
"Only CREATE, UPDATE and LINK_TO commands are supported in resolver"
# extract records to read, by id, in a mapping dict
ids_to_read = [id for (command, id, _) in commands if command in (1, 4)]
records_by_id = dict(
(record['id'], record)
for record in self.pool.get(o2m_model).read(
cr, uid, ids_to_read, fields=fields, context=context))
record_dicts = []
# merge record from db with record provided by command
for command, id, record in commands:
item = {}
if command in (1, 4): item.update(records_by_id[id])
if command in (0, 1): item.update(record)
record_dicts.append(item)
return record_dicts
# keep this import here, at top it will cause dependency cycle errors
import expression
class Model(BaseModel):
"""Main super-class for regular database-persisted OpenERP models.
OpenERP models are created by inheriting from this class::
class user(Model):
...
The system will later instantiate the class once per database (on
which the class' module is installed).
"""
_auto = True
_register = False # not visible in ORM registry, meant to be python-inherited only
_transient = False # True in a TransientModel
class TransientModel(BaseModel):
"""Model super-class for transient records, meant to be temporarily
persisted, and regularly vaccuum-cleaned.
A TransientModel has a simplified access rights management,
all users can create new records, and may only access the
records they created. The super-user has unrestricted access
to all TransientModel records.
"""
_auto = True
_register = False # not visible in ORM registry, meant to be python-inherited only
_transient = True
class AbstractModel(BaseModel):
"""Abstract Model super-class for creating an abstract class meant to be
inherited by regular models (Models or TransientModels) but not meant to
be usable on its own, or persisted.
Technical note: we don't want to make AbstractModel the super-class of
Model or BaseModel because it would not make sense to put the main
definition of persistence methods such as create() in it, and still we
should be able to override them within an AbstractModel.
"""
_auto = False # don't create any database backend for AbstractModels
_register = False # not visible in ORM registry, meant to be python-inherited only
_transient = False
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
|
ksrajkumar/openerp-6.1
|
openerp/osv/orm.py
|
Python
|
agpl-3.0
| 245,233 | 0.004592 |
from model.info_contact import Infos
testdata = [
Infos(firstname="firstname1",lastname="lastname1"),
Infos(firstname="firstname2",lastname="lastname2")
]
|
Alex-Chizhov/python_training
|
home_works/data/contacts.py
|
Python
|
apache-2.0
| 166 | 0.018072 |
#__all__ = [ 'search', 'ham_distance', 'lev_distance', 'distance', 'distance_matrix' ]
|
vfulco/scalpel
|
lib/gravity/tae/match/__init__.py
|
Python
|
lgpl-3.0
| 94 | 0.031915 |
from mock import patch
import mock
from kiwi.storage.subformat.vhdx import DiskFormatVhdx
class TestDiskFormatVhdx:
@patch('platform.machine')
def setup(self, mock_machine):
mock_machine.return_value = 'x86_64'
xml_data = mock.Mock()
xml_data.get_name = mock.Mock(
return_value='some-disk-image'
)
self.xml_state = mock.Mock()
self.xml_state.xml_data = xml_data
self.xml_state.get_image_version = mock.Mock(
return_value='1.2.3'
)
self.disk_format = DiskFormatVhdx(
self.xml_state, 'root_dir', 'target_dir'
)
def test_post_init(self):
self.disk_format.post_init({'option': 'value'})
assert self.disk_format.options == [
'-o', 'option=value', '-o', 'subformat=dynamic'
]
@patch('kiwi.storage.subformat.vhdx.Command.run')
def test_create_image_format(self, mock_command):
self.disk_format.create_image_format()
mock_command.assert_called_once_with(
[
'qemu-img', 'convert', '-f', 'raw',
'target_dir/some-disk-image.x86_64-1.2.3.raw', '-O', 'vhdx',
'-o', 'subformat=dynamic',
'target_dir/some-disk-image.x86_64-1.2.3.vhdx'
]
)
|
b1-systems/kiwi
|
test/unit/storage/subformat/vhdx_test.py
|
Python
|
gpl-3.0
| 1,314 | 0 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
DEBUG = True
observer = None
ser_port = None
s = 0
ser = None
#--------------------------------------------------------------------
import signal
import sys
import os
def signal_handler(signal, frame):
global s, ser
print '\nYou pressed Ctrl+C!'
if s > 18:
print "MTK_Finalize"
serialPost(ser, "B7".decode("hex"))
time.sleep(0.1)
if ser.isOpen(): ser.close()
#sys.exit(0)
os._exit(0)
signal.signal(signal.SIGINT, signal_handler)
#--------------------------------------------------------------------
import os
import serial
from serial.tools import list_ports
def serial_ports():
"""
Returns a generator for all available serial ports
"""
if os.name == 'nt':
# windows
for i in range(256):
try:
s = serial.Serial(i)
s.close()
yield 'COM' + str(i + 1)
except serial.SerialException:
pass
else:
# unix
for port in list_ports.comports():
yield port[0]
#if __name__ == '__main__':
# print(list(serial_ports()))
#exit()
#--------------------------------------------------------------------
import serial, time, binascii
def serialPost(ser, data):
#time.sleep(0.5)
#data = chr(0x44)
print " -> " + binascii.b2a_hex(data)
ser.write(data)
#ser.flush()
def serialPostL(ser, data, slen, scnt):
sys.stdout.write("\r" + str(scnt) + " of " + str(slen) + " <- " + binascii.b2a_hex(data))
if slen == scnt: sys.stdout.write("\n")
#sys.stdout.flush()
ser.write(data)
def summ(block, length):
res = 0
for i in range(length):
res = res + ord(block[i])
#print str(res)
return chr(res & int(0xFF))
def swapSerialData(data):
l = len(data)
#if l > 16:
# print "-> " + str(l) + " bytes"
#else:
# print "-> " + binascii.b2a_hex(data)
if len(data) > 0: ser.write(data)
n = 0
while n < 1:
n = ser.inWaiting()
#time.sleep(1)
data = ser.read(n)
l = len(data)
#print "RX is L: " + str(l) + " -> " + binascii.b2a_hex(data)
return data
#----- CONNECT TO PORT----------
def conn_port (ser_port):
print ser_port
print "module PySerial version: " + serial.VERSION
# if: error open serial port: (22, 'Invalid argument')
# http://superuser.com/questions/572034/how-to-restart-ttyusb
# cat /proc/tty/drivers
# lsmod | grep usbserial
# sudo modprobe -r pl2303 qcaux
# sudo modprobe -r usbserial
#import subprocess
#subprocess.call(['statserial', ser_port])
#subprocess.call(['setserial', '-G', ser_port])
# http://www.roman10.net/serial-port-communication-in-python/
# initialization and open the port
# possible timeout values:
# 1. None: wait forever, block call
# 2. 0: non-blocking mode, return immediately
# 3. x, x is bigger than 0, float allowed, timeout block call
global ser
ser = serial.Serial()
#ser.port = "COM29"
ser.port = ser_port
ser.baudrate = 115200
ser.bytesize = serial.EIGHTBITS # number of bits per bytes
ser.parity = serial.PARITY_EVEN
ser.stopbits = serial.STOPBITS_ONE # number of stop bits
ser.timeout = None # block read
ser.rtscts = True # enable hardware (RTS/CTS) flow control (Hardware handshaking)
#ser.port = "/dev/ttyS0"
#ser.port = "/dev/ttyUSB0"
#ser.port = "2" # COM3
#ser.baudrate = 9600
#ser.parity = serial.PARITY_NONE # set parity check: no parity
#ser.timeout = 0 # non-block read
#ser.xonxoff = False # disable software flow control
#ser.rtscts = False # disable hardware (RTS/CTS) flow control
#ser.dsrdtr = False # disable hardware (DSR/DTR) flow control
#ser.writeTimeout = 2 # timeout for write
#data = chr(0x44) + chr(0x59)
#print "-> " + binascii.b2a_hex(data)
#exit()
try:
ser.open()
except Exception, e:
print "error open serial port: " + str(e)
print "for full reset serial device you must reload drivers:"
print " "
print " cat /proc/tty/drivers "
print " lsmod | grep usbserial "
print " sudo modprobe -r pl2303 qcaux "
print " sudo modprobe -r usbserial "
print " "
exit()
from hktool.bootload.samsung import sgh_e730
#loader1 = open("loader1.bin", "rb").read()
loader1 = sgh_e730.load_bootcode_first()
print "loader1.bin data size is: " + str(len(loader1))
ldr1_i = 0
ldr1_l = len(loader1)
ldr1_c = "4c00".decode("hex")
#loader2 = open("loader2.bin", "rb").read()
loader2 = sgh_e730.load_bootcode_second()
print "loader2.bin data size is: " + str(len(loader2))
ldr2_i = 0
ldr2_l = len(loader2)
#f = open("loader1.bin", "rb")
#try:
# byte = f.read(1)
# while byte != "":
# # Do stuff with byte.
# byte = f.read(1)
#except Exception, e1:
# print "error: " + str(e1)
# ser.close()
# import traceback
# traceback.print_exc()
#finally:
# f.close()
global s
if ser.isOpen():
try:
print 'Work with Samsung SGH-E730:'
print '- wait for SWIFT power on...'
ser.flushInput() # flush input buffer, discarding all its contents
ser.flushOutput() # flush output buffer, aborting current output
# and discard all that is in buffer
# write data
#ser.write("AT+CSQ=?\x0D")
#print("write data: AT+CSQ=?\x0D")
# steps
s = 0
serialPost(ser, "A0".decode("hex"))
while True:
n = 0
s += 1
while n < 1:
n = ser.inWaiting()
#time.sleep(1)
data = ser.read(n)
l = len(data)
#if s != 6 or ldr1_i == 0:
print "RX is L: " + str(l) + " <- " + binascii.b2a_hex(data)
if s == 1:
if data[l-1] == chr(0x5F):
serialPost(ser, chr(0x0A))
elif s == 2:
if data[l-1] == chr(0xF5):
serialPost(ser, chr(0x50))
elif s == 3:
#if l == 16:
# serialPost(ser, "4412345678".decode("hex") + data)
# -> AF
serialPost(ser, "05".decode("hex"))
elif s == 4:
#if data[l-1] == chr(0x4f):
# # set timeout to 1600 ms (10h)
# serialPost(ser, chr(0x54) + chr(0x10))
# # set timeout to 1600 ms (20h)
# #serialPost(ser, chr(0x54) + chr(0x20))
# -> FA
# A2 - read from memory
serialPost(ser, "A2".decode("hex"))
elif s == 5:
#if data[l-1] == chr(0x4f):
# serialPost(ser, "530000000c".decode("hex"))
# -> A2 - read command ACK
# 80 01 00 00 - Configuration Register: Hardware Version Register
serialPost(ser, "80010000".decode("hex"))
elif s == 6:
# -> 80 01 00 00
# 00 00 00 01 - read one byte
serialPost(ser, "00000001".decode("hex"))
#ldr1_i4 = 4*ldr1_i
#ldr1_i8 = 4*ldr1_i + 4
#if ldr1_i8 < ldr1_l:
# serialPostL(ser, ldr1_c + loader1[ldr1_i4:ldr1_i8], ldr1_l, ldr1_i8)
# s -= 1
#else:
# serialPostL(ser, ldr1_c + loader1[ldr1_i4:ldr1_l ], ldr1_l, ldr1_l )
#ldr1_i += 1
elif s == 7:
if l == 6: s += 1
elif s == 8:
# -> 00 00 00 01 - byte is read
# -> XX XX - byte:
serialPost(ser, "A2".decode("hex"))
#if data[l-1] == chr(0x4f):
# serialPost(ser, "530000000c".decode("hex"))
elif s == 9:
# -> A2
# 80 01 00 08 - Hardware Code Register
serialPost(ser, "80010008".decode("hex"))
#if data[l-1] == chr(0x4f):
# serialPost(ser, "4a".decode("hex"))
elif s == 10:
# -> 80 01 00 08
serialPost(ser, "00000001".decode("hex"))
#s = 20;
#if data[l-1] == chr(0xAB):
# # 0x00 -> Speed = 115200
# # 0x01 -> Speed = 230400
# # 0x02 -> Speed = 460800
# # 0x03 -> Speed = 921600
# serialPost(ser, "00".decode("hex"))
# # close comms, bootup completed
# ser.flushInput() # flush input buffer, discarding all its contents
# ser.flushOutput() # flush output buffer, aborting current output
# ser.close()
# # reopen comms at the new speed
# time.sleep(0.1)
# ser.port = "COM3"
# ser.baudrate = 115200
# ser.parity = serial.PARITY_NONE # set parity check: no parity
# ser.open()
# ser.flushInput() # flush input buffer, discarding all its contents
# ser.flushOutput() # flush output buffer, aborting current output
# serialPost(ser, "d9".decode("hex"))
elif s == 11:
if l == 6: s += 1
elif s == 12:
# -> 00 00 00 01
# -> XX XX - we hawe a MediaTek MT6253
serialPost(ser, "A2".decode("hex"))
elif s == 13:
# -> A2
# 80 01 00 04 - Software Version Register
serialPost(ser, "80010004".decode("hex"))
elif s == 14:
# -> 80 01 00 04
serialPost(ser, "00000001".decode("hex"))
elif s == 15:
if l == 6: s += 1
elif s == 16:
# -> 00 00 00 01
# -> XX XX -
# A1 - write to register
serialPost(ser, "A1".decode("hex"))
elif s == 17:
# -> A1 - write command ack
# 80 03 00 00 - Reset Generation Unit (RGU): Watchdog Timer Control Register
serialPost(ser, "80030000".decode("hex"))
elif s == 18:
# -> 80 03 00 00
serialPost(ser, "00000001".decode("hex"))
elif s == 19:
# -> 00 00 00 01
# 22 00 - set
serialPost(ser, "2200".decode("hex"))
elif s == 20:
s -= 1
elif s == 111:
data = "d4".decode("hex")
data0 = chr((ldr2_l >> 24) & int(0xFF))
data0 += chr((ldr2_l >> 16) & int(0xFF))
data0 += chr((ldr2_l >> 8) & int(0xFF))
data0 += chr((ldr2_l ) & int(0xFF))
data += data0
serialPost(ser, data)
elif s == 112:
# zapominaem CRC
crc = data
my_crc = summ(data0, 4)
print "crc is: " + binascii.b2a_hex(crc)
print "my_crc is: " + binascii.b2a_hex(my_crc)
if crc == my_crc:
send_len = 0
for i in range((ldr2_l - 1) >> 11):
send_len = ldr2_l - (i << 11)
if send_len > 2048: send_len = 2048
# calculate sum
ss = i << 11
su = summ(loader2[ss:ss+send_len], send_len)
# send command
data = swapSerialData("f7".decode("hex"))
data = swapSerialData(loader2[ss:ss+send_len])
#print "2 crc is: " + binascii.b2a_hex(data)
#print "2 my_crc is: " + binascii.b2a_hex(su)
#print "i: " + str(i)
sys.stdout.write("\ri: " + str(i))
sys.stdout.write("\n")
serialPost(ser, "FF".decode("hex"))
elif s == 113:
serialPost(ser, "D010000000".decode("hex"))
elif s == 114:
serialPost(ser, "D1".decode("hex"))
elif s == 115:
nand_id = (ord(data[8])<<8) + ord(data[9])
# nado proverit, chto 2,3,4 baity ravny sootvetstvenno 0xEC 0x22 0xFC
#
# additionally identify NAND for Swift
print "Flash... "
if nand_id == int(0x04): print " 16MB (128Mbit) NAND"
elif nand_id == int(0x14): print " 32MB (256Mbit) NAND"
elif nand_id == int(0x24): print " 64MB (512Mbit) NAND"
elif nand_id == int(0x34): print "128MB ( 1Gbit) NAND"
elif nand_id == int(0x0C): print " 16MB (128Mbit) NAND"
elif nand_id == int(0x1C): print " 32MB (256Mbit) NAND"
elif nand_id == int(0x2C): print " 64MB (512Mbit) NAND"
elif nand_id == int(0x3C): print "128MB ( 1Gbit) NAND"
else: print "Unknown NAND: " + str("%02x" % nand_id)
# here, the bootup is completed
# delay slightly (required!)
time.sleep(0.25)
else:
#data = chr(0x44)
data = chr(0x00)
print "-> " + binascii.b2a_hex(data)
#ser.write(data)
data = ser.read()
print "serial RX: " + binascii.b2a_hex(data)
data = chr(0x44)
print "-> " + binascii.b2a_hex(data)
ser.write(data)
#ser.flush()
data = ser.read()
print "serial RX: " + binascii.b2a_hex(data)
data = chr(0x51)
print "-> " + binascii.b2a_hex(data)
ser.write(data)
data = ser.read()
print "serial RX: " + binascii.b2a_hex(data)
#print ser.portstr
time.sleep(0.5) # give the serial port sometime to receive the data
numOfLines = 0
while True:
response = ser.readline()
print("read data: " + response)
numOfLines = numOfLines + 1
if (numOfLines >= 5):
break
ser.close()
except Exception, e1:
print "error communicating...: " + str(e1)
ser.close()
import traceback
traceback.print_exc()
except KeyboardInterrupt:
print "\nmanual interrupted!"
ser.close()
else:
print "cannot open serial port "
exit()
#===========================================================
#from hktool.bootload import mediatek
from hktool.bootload.mediatek import MTKBootload
from threading import Thread
from time import sleep as Sleep
def logical_xor(str1, str2):
return bool(str1) ^ bool(str2)
#----- MAIN CODE -------------------------------------------
if __name__=='__main__':
from sys import platform as _platform
import os
if _platform == "linux" or _platform == "linux2":
# linux
print "it is linux?"
from hktool.hotplug import linux_udev as port_notify
elif _platform == "darwin":
# OS X
print "it is osx?"
print "WARNING: port_notify is not realised !!!"
elif _platform == "win32":
# Windows...
print "it is windows?"
from hktool.hotplug import windevnotif as port_notify
print "sys.platform: " + _platform + ", os.name: " + os.name
print ""
print "Select: xml, boot, sgh, crc, usb, exit, quit, q"
print ""
tsk = str(raw_input("enter command > "))
if tsk.lower() in ['exit', 'quit', 'q']:
os._exit(0)
if tsk.lower() in ['boot']:
print "Working with device communication..."
print ""
Thread(target = port_notify.run_notify).start()
Sleep(1)
port = port_notify.get_notify()
print "port_name is: " + port
#conn_port(port)
#mediatek.init(port)
m = MTKBootload(port)
if 'sgh' in tsk.lower():
tsks = tsk.split()
print ""
print "Working with device communication..."
print ""
Sleep(1)
port = tsks[1]
print "port_name is: " + port
#m = SGHBootload(port)
if tsk.lower() in ['xml', 'lxml']:
print "Working with lxml..."
print ""
from lxml import etree
tree = etree.parse('../../mtk-tests/Projects/_lg-a290/data/UTLog_DownloadAgent_FlashTool.xml')
root = tree.getroot()
print root
#entries = tree.xpath("//atom:category[@term='accessibility']/..", namespaces=NSMAP)
entries = tree.xpath("//UTLOG/Request[@Dir='[OUT]']/Data")
#print entries
old_text = None
dmp_text = False
cnt_text = 0
bin_file = None
for xent in entries:
new_text = xent.text
if new_text == old_text:
continue
old_text = new_text
#print "-> " + new_text
bin_text = new_text.replace(" ", "")
bin_text = bin_text.decode("hex")
bin_len = len(bin_text)
print str(bin_len) + " -> " + new_text
if dmp_text is False and bin_len == 1024:
dmp_text = True
prt = xent.getparent()
atr = prt.attrib
num = atr["Number"]
nam = "big_" + num + ".bin"
bin_file = open(nam, 'wb')
print ""
print "start dump big data to: " + nam
if dmp_text is True:
#---
import array
a = array.array('H', bin_text) # array.array('H', bin_text)
a.byteswap()
bin_text = a.tostring()
#---
bin_file.write(bin_text)
if bin_len == 1024:
cnt_text += 1
else:
cnt_text = cnt_text * 1024 + bin_len
dmp_text = False
bin_file.close()
print "big data length is: " + str(cnt_text)
print ""
cnt_text = 0
pass
if tsk.lower() in ['crc']:
str1 = raw_input("Enter string one:")
str2 = raw_input("Enter string two:")
if logical_xor(str1, str2):
print "ok"
else:
print "bad"
pass
print hex(0x12ef ^ 0xabcd)
print hex(int("12ef", 16) ^ int("abcd", 16))
str1 = raw_input("Enter string one: ")
str2 = raw_input("Enter string two: ")
print hex(int(str1, 16) ^ int(str2, 16))
pass
if tsk.lower() in ['usb']:
import usb.core
#import usb.backend.libusb1
import usb.backend.libusb0
import logging
#PYUSB_DEBUG_LEVEL = "debug"
#PYUSB_LOG_FILENAME = "C:\dump"
__location__ = os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(__file__)))
__backend__ = os.path.join(__location__, "libusb0.dll")
#PYUSB_LOG_FILENAME = __location__
#backend = usb.backend.libusb1.get_backend(find_library=lambda x: "/usr/lib/libusb-1.0.so")
#backend = usb.backend.libusb1.get_backend(find_library=lambda x: __backend__)
backend = usb.backend.libusb0.get_backend(find_library=lambda x: __backend__)
dev = usb.core.find(find_all=True, backend=backend)
#dev = usb.core.find(find_all=True)
busses = usb.busses()
print busses
if dev is None:
raise ValueError('Our device is not connected')
for bus in busses:
devices = bus.devices
for dev in devices:
try:
_name = usb.util.get_string(dev.dev, 19, 1)
except:
continue
dev.set_configuration()
cfg = dev.get_active_configuration()
interface_number = cfg[(0,0)].bInterfaceNumber
alternate_settting = usb.control.get_interface(interface_number)
print "Device name:",_name
print "Device:", dev.filename
print " idVendor:",hex(dev.idVendor)
print " idProduct:",hex(dev.idProduct)
for config in dev.configurations:
print " Configuration:", config.value
print " Total length:", config.totalLength
print " selfPowered:", config.selfPowered
print " remoteWakeup:", config.remoteWakeup
print " maxPower:", config.maxPower
print
|
Ma3X/boot-talker
|
codes/python/talk.py
|
Python
|
gpl-3.0
| 19,742 | 0.020819 |
# Copyright (c) 2017 Charles University in Prague, Faculty of Arts,
# Institute of the Czech National Corpus
# Copyright (c) 2017 Tomas Machalek <tomas.machalek@gmail.com>
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; version 2
# dated June, 1991.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
class UnknownFormatException(Exception):
pass
class AbstractChartExport(object):
"""
AbstractChartExport represents a single
format export (e.g. PDF, Excel).
"""
def get_content_type(self):
"""
return a content type identifier (e.g. 'application/json')
"""
raise NotImplementedError()
def get_format_name(self):
"""
Return a format identifier. It should be both
human-readable and unique within a single plug-in
installation. It means that in case of mixing of
different AbstractChartExport implementations
it may be necessary to modify some names to
keep all the export functions available.
"""
raise NotImplementedError()
def get_suffix(self):
"""
Return a proper file suffix (e.g. 'xlsx' for Excel).
"""
raise NotImplementedError()
def export_pie_chart(self, data, title):
"""
Generate a PIE chart based on passed data and title.
The method is expected to return raw file data ready
to be downloaded by a client.
"""
raise NotImplementedError()
class AbstractChartExportPlugin(object):
"""
AbstractChartExportPlugin represents plug-in itself
which is expected to contain one or more implementations
of AbstractChartExport.
"""
def get_supported_types(self):
"""
Return a list of supported format names
(i.e. the values returned by AbstractChartExport.get_format_name()
of all the installed export classes).
"""
return []
def get_content_type(self, format):
"""
Return a content type for a specified format
(e.g. 'PDF' -> 'application/pdf')
arguments:
format -- format name (AbstractChartExport.get_format_name())
"""
raise NotImplementedError()
def get_suffix(self, format):
"""
Return a suffix for a specified format.
arguments:
format -- format name (AbstractChartExport.get_format_name())
"""
raise NotImplementedError()
def export_pie_chart(self, data, title, format):
"""
Export PIE chart data to a PIE chart of
a specified format.
arguments:
data -- chart data
title -- chart label
format -- format name (AbstractChartExport.get_format_name())
"""
raise NotImplementedError()
|
tomachalek/kontext
|
lib/plugins/abstract/chart_export.py
|
Python
|
gpl-2.0
| 3,124 | 0 |
import config
#This module is used for calling the Wolfram Alpha API
#It defines a function that constructs an URL based on the query.
#NOTE: This module returns only the URL. This URL is passed in the bot.py file. Telegram Takes care of the rest.
def query(query):
question = query.replace(" ","+") #plus encoding
return "http://api.wolframalpha.com/v1/simple?appid={}&i=".format(config.WOLFRAM) + question + "&format=image"
#returns ONLY the URL directly.
#Telegram's servers handle the requests by themselves for docs lesser than 20MB
|
SiddharthSham/PetAteMyHW
|
wolfram.py
|
Python
|
gpl-3.0
| 692 | 0.023121 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2010-2011, Volkan Esgel
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free
# Software Foundation; either version 3 of the License, or (at your option)
# any later version.
#
# Please read the COPYING file.
#
# PyQt4 Section
from PyQt4.QtCore import *
from PyQt4.QtGui import *
# PyKDE4 Section
from PyKDE4.plasma import Plasma
from PyKDE4 import plasmascript
# Application Section
from notemodel import NoteModel
from notedelegate import NoteDelegate
class QuickNotes(plasmascript.Applet):
def __init__(self, parent, args=None):
plasmascript.Applet.__init__(self, parent)
def init(self):
self.setHasConfigurationInterface(True)
self.setAspectRatioMode(Plasma.IgnoreAspectRatio)
"""
self.theme = Plasma.Svg(self)
self.theme.setImagePath("widgets/background")
self.setBackgroundHints(Plasma.Applet.DefaultBackground)
"""
self.setBackgroundHints(Plasma.Applet.NoBackground)
self.__createMainLayout()
width = self.viewerSize.width() + 20
height = self.viewerSize.height() - 20
self.resize(width, height)
def __createMainLayout(self):
self.mainLayout = QGraphicsLinearLayout(Qt.Vertical, self.applet)
noteview = Plasma.TreeView(self.applet)
noteview.setStyleSheet("QTreeView { background: Transparent }")
nmodel = NoteModel(self.package().path(), noteview)
noteview.setModel(nmodel)
noteview.nativeWidget().setItemDelegate(NoteDelegate(self))
noteview.nativeWidget().setHeaderHidden(True)
noteview.nativeWidget().setIndentation(0)
self.mainLayout.addItem(noteview)
self.viewerSize = noteview.size()
self.applet.setLayout(self.mainLayout)
def CreateApplet(parent):
return QuickNotes(parent)
|
vesgel/quicknotes
|
plasmoid/contents/code/main.py
|
Python
|
gpl-3.0
| 1,970 | 0.001015 |
# -*- coding: utf-8 -*-
import pytest
import env # noqa: F401
from pybind11_tests import kwargs_and_defaults as m
def test_function_signatures(doc):
assert doc(m.kw_func0) == "kw_func0(arg0: int, arg1: int) -> str"
assert doc(m.kw_func1) == "kw_func1(x: int, y: int) -> str"
assert doc(m.kw_func2) == "kw_func2(x: int = 100, y: int = 200) -> str"
assert doc(m.kw_func3) == "kw_func3(data: str = 'Hello world!') -> None"
assert doc(m.kw_func4) == "kw_func4(myList: List[int] = [13, 17]) -> str"
assert doc(m.kw_func_udl) == "kw_func_udl(x: int, y: int = 300) -> str"
assert doc(m.kw_func_udl_z) == "kw_func_udl_z(x: int, y: int = 0) -> str"
assert doc(m.args_function) == "args_function(*args) -> tuple"
assert (
doc(m.args_kwargs_function) == "args_kwargs_function(*args, **kwargs) -> tuple"
)
assert (
doc(m.KWClass.foo0)
== "foo0(self: m.kwargs_and_defaults.KWClass, arg0: int, arg1: float) -> None"
)
assert (
doc(m.KWClass.foo1)
== "foo1(self: m.kwargs_and_defaults.KWClass, x: int, y: float) -> None"
)
def test_named_arguments(msg):
assert m.kw_func0(5, 10) == "x=5, y=10"
assert m.kw_func1(5, 10) == "x=5, y=10"
assert m.kw_func1(5, y=10) == "x=5, y=10"
assert m.kw_func1(y=10, x=5) == "x=5, y=10"
assert m.kw_func2() == "x=100, y=200"
assert m.kw_func2(5) == "x=5, y=200"
assert m.kw_func2(x=5) == "x=5, y=200"
assert m.kw_func2(y=10) == "x=100, y=10"
assert m.kw_func2(5, 10) == "x=5, y=10"
assert m.kw_func2(x=5, y=10) == "x=5, y=10"
with pytest.raises(TypeError) as excinfo:
# noinspection PyArgumentList
m.kw_func2(x=5, y=10, z=12)
assert excinfo.match(
r"(?s)^kw_func2\(\): incompatible.*Invoked with: kwargs: ((x=5|y=10|z=12)(, |$))"
+ "{3}$"
)
assert m.kw_func4() == "{13 17}"
assert m.kw_func4(myList=[1, 2, 3]) == "{1 2 3}"
assert m.kw_func_udl(x=5, y=10) == "x=5, y=10"
assert m.kw_func_udl_z(x=5) == "x=5, y=0"
def test_arg_and_kwargs():
args = "arg1_value", "arg2_value", 3
assert m.args_function(*args) == args
args = "a1", "a2"
kwargs = dict(arg3="a3", arg4=4)
assert m.args_kwargs_function(*args, **kwargs) == (args, kwargs)
def test_mixed_args_and_kwargs(msg):
mpa = m.mixed_plus_args
mpk = m.mixed_plus_kwargs
mpak = m.mixed_plus_args_kwargs
mpakd = m.mixed_plus_args_kwargs_defaults
assert mpa(1, 2.5, 4, 99.5, None) == (1, 2.5, (4, 99.5, None))
assert mpa(1, 2.5) == (1, 2.5, ())
with pytest.raises(TypeError) as excinfo:
assert mpa(1)
assert (
msg(excinfo.value)
== """
mixed_plus_args(): incompatible function arguments. The following argument types are supported:
1. (arg0: int, arg1: float, *args) -> tuple
Invoked with: 1
""" # noqa: E501 line too long
)
with pytest.raises(TypeError) as excinfo:
assert mpa()
assert (
msg(excinfo.value)
== """
mixed_plus_args(): incompatible function arguments. The following argument types are supported:
1. (arg0: int, arg1: float, *args) -> tuple
Invoked with:
""" # noqa: E501 line too long
)
assert mpk(-2, 3.5, pi=3.14159, e=2.71828) == (
-2,
3.5,
{"e": 2.71828, "pi": 3.14159},
)
assert mpak(7, 7.7, 7.77, 7.777, 7.7777, minusseven=-7) == (
7,
7.7,
(7.77, 7.777, 7.7777),
{"minusseven": -7},
)
assert mpakd() == (1, 3.14159, (), {})
assert mpakd(3) == (3, 3.14159, (), {})
assert mpakd(j=2.71828) == (1, 2.71828, (), {})
assert mpakd(k=42) == (1, 3.14159, (), {"k": 42})
assert mpakd(1, 1, 2, 3, 5, 8, then=13, followedby=21) == (
1,
1,
(2, 3, 5, 8),
{"then": 13, "followedby": 21},
)
# Arguments specified both positionally and via kwargs should fail:
with pytest.raises(TypeError) as excinfo:
assert mpakd(1, i=1)
assert (
msg(excinfo.value)
== """
mixed_plus_args_kwargs_defaults(): incompatible function arguments. The following argument types are supported:
1. (i: int = 1, j: float = 3.14159, *args, **kwargs) -> tuple
Invoked with: 1; kwargs: i=1
""" # noqa: E501 line too long
)
with pytest.raises(TypeError) as excinfo:
assert mpakd(1, 2, j=1)
assert (
msg(excinfo.value)
== """
mixed_plus_args_kwargs_defaults(): incompatible function arguments. The following argument types are supported:
1. (i: int = 1, j: float = 3.14159, *args, **kwargs) -> tuple
Invoked with: 1, 2; kwargs: j=1
""" # noqa: E501 line too long
)
def test_keyword_only_args(msg):
assert m.kw_only_all(i=1, j=2) == (1, 2)
assert m.kw_only_all(j=1, i=2) == (2, 1)
with pytest.raises(TypeError) as excinfo:
assert m.kw_only_all(i=1) == (1,)
assert "incompatible function arguments" in str(excinfo.value)
with pytest.raises(TypeError) as excinfo:
assert m.kw_only_all(1, 2) == (1, 2)
assert "incompatible function arguments" in str(excinfo.value)
assert m.kw_only_some(1, k=3, j=2) == (1, 2, 3)
assert m.kw_only_with_defaults(z=8) == (3, 4, 5, 8)
assert m.kw_only_with_defaults(2, z=8) == (2, 4, 5, 8)
assert m.kw_only_with_defaults(2, j=7, k=8, z=9) == (2, 7, 8, 9)
assert m.kw_only_with_defaults(2, 7, z=9, k=8) == (2, 7, 8, 9)
assert m.kw_only_mixed(1, j=2) == (1, 2)
assert m.kw_only_mixed(j=2, i=3) == (3, 2)
assert m.kw_only_mixed(i=2, j=3) == (2, 3)
assert m.kw_only_plus_more(4, 5, k=6, extra=7) == (4, 5, 6, {"extra": 7})
assert m.kw_only_plus_more(3, k=5, j=4, extra=6) == (3, 4, 5, {"extra": 6})
assert m.kw_only_plus_more(2, k=3, extra=4) == (2, -1, 3, {"extra": 4})
with pytest.raises(TypeError) as excinfo:
assert m.kw_only_mixed(i=1) == (1,)
assert "incompatible function arguments" in str(excinfo.value)
with pytest.raises(RuntimeError) as excinfo:
m.register_invalid_kw_only(m)
assert (
msg(excinfo.value)
== """
arg(): cannot specify an unnamed argument after an kw_only() annotation
"""
)
def test_positional_only_args(msg):
assert m.pos_only_all(1, 2) == (1, 2)
assert m.pos_only_all(2, 1) == (2, 1)
with pytest.raises(TypeError) as excinfo:
m.pos_only_all(i=1, j=2)
assert "incompatible function arguments" in str(excinfo.value)
assert m.pos_only_mix(1, 2) == (1, 2)
assert m.pos_only_mix(2, j=1) == (2, 1)
with pytest.raises(TypeError) as excinfo:
m.pos_only_mix(i=1, j=2)
assert "incompatible function arguments" in str(excinfo.value)
assert m.pos_kw_only_mix(1, 2, k=3) == (1, 2, 3)
assert m.pos_kw_only_mix(1, j=2, k=3) == (1, 2, 3)
with pytest.raises(TypeError) as excinfo:
m.pos_kw_only_mix(i=1, j=2, k=3)
assert "incompatible function arguments" in str(excinfo.value)
with pytest.raises(TypeError) as excinfo:
m.pos_kw_only_mix(1, 2, 3)
assert "incompatible function arguments" in str(excinfo.value)
with pytest.raises(TypeError) as excinfo:
m.pos_only_def_mix()
assert "incompatible function arguments" in str(excinfo.value)
assert m.pos_only_def_mix(1) == (1, 2, 3)
assert m.pos_only_def_mix(1, 4) == (1, 4, 3)
assert m.pos_only_def_mix(1, 4, 7) == (1, 4, 7)
assert m.pos_only_def_mix(1, 4, k=7) == (1, 4, 7)
with pytest.raises(TypeError) as excinfo:
m.pos_only_def_mix(1, j=4)
assert "incompatible function arguments" in str(excinfo.value)
def test_signatures():
assert "kw_only_all(*, i: int, j: int) -> tuple\n" == m.kw_only_all.__doc__
assert "kw_only_mixed(i: int, *, j: int) -> tuple\n" == m.kw_only_mixed.__doc__
assert "pos_only_all(i: int, j: int, /) -> tuple\n" == m.pos_only_all.__doc__
assert "pos_only_mix(i: int, /, j: int) -> tuple\n" == m.pos_only_mix.__doc__
assert (
"pos_kw_only_mix(i: int, /, j: int, *, k: int) -> tuple\n"
== m.pos_kw_only_mix.__doc__
)
@pytest.mark.xfail("env.PYPY and env.PY2", reason="PyPy2 doesn't double count")
def test_args_refcount():
"""Issue/PR #1216 - py::args elements get double-inc_ref()ed when combined with regular
arguments"""
refcount = m.arg_refcount_h
myval = 54321
expected = refcount(myval)
assert m.arg_refcount_h(myval) == expected
assert m.arg_refcount_o(myval) == expected + 1
assert m.arg_refcount_h(myval) == expected
assert refcount(myval) == expected
assert m.mixed_plus_args(1, 2.0, "a", myval) == (1, 2.0, ("a", myval))
assert refcount(myval) == expected
assert m.mixed_plus_kwargs(3, 4.0, a=1, b=myval) == (3, 4.0, {"a": 1, "b": myval})
assert refcount(myval) == expected
assert m.args_function(-1, myval) == (-1, myval)
assert refcount(myval) == expected
assert m.mixed_plus_args_kwargs(5, 6.0, myval, a=myval) == (
5,
6.0,
(myval,),
{"a": myval},
)
assert refcount(myval) == expected
assert m.args_kwargs_function(7, 8, myval, a=1, b=myval) == (
(7, 8, myval),
{"a": 1, "b": myval},
)
assert refcount(myval) == expected
exp3 = refcount(myval, myval, myval)
assert m.args_refcount(myval, myval, myval) == (exp3, exp3, exp3)
assert refcount(myval) == expected
# This function takes the first arg as a `py::object` and the rest as a `py::args`. Unlike the
# previous case, when we have both positional and `py::args` we need to construct a new tuple
# for the `py::args`; in the previous case, we could simply inc_ref and pass on Python's input
# tuple without having to inc_ref the individual elements, but here we can't, hence the extra
# refs.
assert m.mixed_args_refcount(myval, myval, myval) == (exp3 + 3, exp3 + 3, exp3 + 3)
assert m.class_default_argument() == "<class 'decimal.Decimal'>"
|
YannickJadoul/Parselmouth
|
pybind11/tests/test_kwargs_and_defaults.py
|
Python
|
gpl-3.0
| 10,048 | 0.001393 |
import random
def preprocessing(mazeMap, mazeWidth, mazeHeight, playerLocation, opponentLocation, piecesOfCheese, timeAllowed):
return
def turn (mazeMap, mazeWidth, mazeHeight, playerLocation, opponentLocation, playerScore, opponentScore, piecesOfCheese, timeAllowed):
return
def postprocessing (mazeMap, mazeWidth, mazeHeight, playerLocation, opponentLocation, playerScore, opponentScore, piecesOfCheese, timeAllowed):
return
|
vgripon/PyRat
|
imports/dummyplayer.py
|
Python
|
gpl-3.0
| 440 | 0.018182 |
from skin import parseColor, parseFont, parseSize
from Components.config import config, ConfigClock, ConfigInteger, ConfigSubsection, ConfigYesNo, ConfigSelection, ConfigSelectionNumber
from Components.Pixmap import Pixmap
from Components.Button import Button
from Components.ActionMap import HelpableActionMap
from Components.HTMLComponent import HTMLComponent
from Components.GUIComponent import GUIComponent
from Components.EpgList import Rect
from Components.Sources.Event import Event
from Components.MultiContent import MultiContentEntryText, MultiContentEntryPixmapAlphaTest
from Components.TimerList import TimerList
from Components.Renderer.Picon import getPiconName
from Components.Sources.ServiceEvent import ServiceEvent
from Screens.Screen import Screen
from Screens.HelpMenu import HelpableScreen
from Screens.EventView import EventViewEPGSelect
from Screens.TimeDateInput import TimeDateInput
from Screens.TimerEntry import TimerEntry
from Screens.EpgSelection import EPGSelection
from Screens.TimerEdit import TimerSanityConflict
from Screens.MessageBox import MessageBox
from Tools.Directories import resolveFilename, SCOPE_CURRENT_SKIN
from RecordTimer import RecordTimerEntry, parseEvent, AFTEREVENT
from ServiceReference import ServiceReference, isPlayableForCur
from Tools.LoadPixmap import LoadPixmap
from Tools.Alternatives import CompareWithAlternatives
from Tools import Notifications
from enigma import eEPGCache, eListbox, ePicLoad, gFont, eListboxPythonMultiContent, RT_HALIGN_LEFT, RT_HALIGN_RIGHT, RT_HALIGN_CENTER, RT_VALIGN_CENTER, RT_WRAP,\
eSize, eRect, eTimer, getBestPlayableServiceReference
from GraphMultiEpgSetup import GraphMultiEpgSetup
from time import localtime, time, strftime
MAX_TIMELINES = 6
config.misc.graph_mepg = ConfigSubsection()
config.misc.graph_mepg.prev_time = ConfigClock(default = time())
config.misc.graph_mepg.prev_time_period = ConfigInteger(default = 120, limits = (60, 300))
config.misc.graph_mepg.ev_fontsize = ConfigSelectionNumber(default = 0, stepwidth = 1, min = -8, max = 8, wraparound = True)
config.misc.graph_mepg.items_per_page = ConfigSelectionNumber(min = 3, max = 40, stepwidth = 1, default = 6, wraparound = True)
config.misc.graph_mepg.items_per_page_listscreen = ConfigSelectionNumber(min = 3, max = 60, stepwidth = 1, default = 12, wraparound = True)
config.misc.graph_mepg.default_mode = ConfigYesNo(default = False)
config.misc.graph_mepg.overjump = ConfigYesNo(default = True)
config.misc.graph_mepg.center_timeline = ConfigYesNo(default = False)
config.misc.graph_mepg.servicetitle_mode = ConfigSelection(default = "picon+servicename", choices = [
("servicename", _("Service name")),
("picon", _("Picon")),
("picon+servicename", _("Picon and service name")) ])
config.misc.graph_mepg.roundTo = ConfigSelection(default = "900", choices = [("900", _("%d minutes") % 15), ("1800", _("%d minutes") % 30), ("3600", _("%d minutes") % 60)])
config.misc.graph_mepg.OKButton = ConfigSelection(default = "info", choices = [("info", _("Show detailed event info")), ("zap", _("Zap to selected channel"))])
possibleAlignmentChoices = [
( str(RT_HALIGN_LEFT | RT_VALIGN_CENTER ) , _("left")),
( str(RT_HALIGN_CENTER | RT_VALIGN_CENTER ) , _("centered")),
( str(RT_HALIGN_RIGHT | RT_VALIGN_CENTER ) , _("right")),
( str(RT_HALIGN_LEFT | RT_VALIGN_CENTER | RT_WRAP) , _("left, wrapped")),
( str(RT_HALIGN_CENTER | RT_VALIGN_CENTER | RT_WRAP) , _("centered, wrapped")),
( str(RT_HALIGN_RIGHT | RT_VALIGN_CENTER | RT_WRAP) , _("right, wrapped"))]
config.misc.graph_mepg.event_alignment = ConfigSelection(default = possibleAlignmentChoices[0][0], choices = possibleAlignmentChoices)
config.misc.graph_mepg.servicename_alignment = ConfigSelection(default = possibleAlignmentChoices[0][0], choices = possibleAlignmentChoices)
listscreen = config.misc.graph_mepg.default_mode.value
class EPGList(HTMLComponent, GUIComponent):
def __init__(self, selChangedCB = None, timer = None, time_epoch = 120, overjump_empty = True):
GUIComponent.__init__(self)
self.cur_event = None
self.cur_service = None
self.offs = 0
self.timer = timer
self.last_time = time()
self.onSelChanged = [ ]
if selChangedCB is not None:
self.onSelChanged.append(selChangedCB)
self.l = eListboxPythonMultiContent()
self.l.setBuildFunc(self.buildEntry)
self.setOverjump_Empty(overjump_empty)
self.epgcache = eEPGCache.getInstance()
self.clocks = [ LoadPixmap(cached=True, path=resolveFilename(SCOPE_CURRENT_SKIN, 'skin_default/icons/epgclock_add.png')),
LoadPixmap(cached=True, path=resolveFilename(SCOPE_CURRENT_SKIN, 'skin_default/icons/epgclock_pre.png')),
LoadPixmap(cached=True, path=resolveFilename(SCOPE_CURRENT_SKIN, 'skin_default/icons/epgclock.png')),
LoadPixmap(cached=True, path=resolveFilename(SCOPE_CURRENT_SKIN, 'skin_default/icons/epgclock_prepost.png')),
LoadPixmap(cached=True, path=resolveFilename(SCOPE_CURRENT_SKIN, 'skin_default/icons/epgclock_post.png')) ]
self.time_base = None
self.time_epoch = time_epoch
self.list = None
self.select_rect = None
self.event_rect = None
self.service_rect = None
self.picon_size = None
self.currentlyPlaying = None
self.showPicon = False
self.showServiceTitle = True
self.picload = ePicLoad()
self.nowEvPix = None
self.othEvPix = None
self.selEvPix = None
self.recEvPix = None
self.curSerPix = None
self.foreColor = 0xffffff
self.foreColorSelected = 0xffc000
self.borderColor = 0x464445
self.backColor = 0x595959
self.backColorSelected = 0x808080
self.foreColorService = 0xffffff
self.foreColorServiceSelected = 0xffffff
self.backColorService = 0x000000
self.backColorServiceSelected = 0x508050
self.borderColorService = 0x000000
self.foreColorNow = 0xffffff
self.backColorNow = 0x505080
self.foreColorRec = 0xffffff
self.backColorRec = 0x805050
self.serviceFont = gFont("Regular", 20)
self.entryFontName = "Regular"
self.entryFontSize = 18
self.listHeight = None
self.listWidth = None
self.serviceBorderWidth = 1
self.serviceNamePadding = 0
self.eventBorderWidth = 1
self.eventNamePadding = 0
def applySkin(self, desktop, screen):
if self.skinAttributes is not None:
attribs = [ ]
for (attrib, value) in self.skinAttributes:
if attrib == "EntryForegroundColor":
self.foreColor = parseColor(value).argb()
elif attrib == "EntryForegroundColorSelected":
self.foreColorSelected = parseColor(value).argb()
elif attrib == "EntryBackgroundColor":
self.backColor = parseColor(value).argb()
elif attrib == "EntryBackgroundColorSelected":
self.backColorSelected = parseColor(value).argb()
elif attrib == "EntryBorderColor":
self.borderColor = parseColor(value).argb()
elif attrib == "EntryFont":
font = parseFont(value, ((1,1),(1,1)) )
self.entryFontName = font.family
self.entryFontSize = font.pointSize
elif attrib == "ServiceForegroundColor" or attrib == "ServiceNameForegroundColor":
self.foreColorService = parseColor(value).argb()
elif attrib == "ServiceForegroundColorSelected":
self.foreColorServiceSelected = parseColor(value).argb()
elif attrib == "ServiceBackgroundColor" or attrib == "ServiceNameBackgroundColor":
self.backColorService = parseColor(value).argb()
elif attrib == "ServiceBackgroundColorSelected":
self.backColorServiceSelected = parseColor(value).argb()
elif attrib == "ServiceBackgroundColorRecording" or attrib == "ServiceNameBackgroundColor":
self.backColorRec = parseColor(value).argb()
elif attrib == "ServiceForegroundColorRecording":
self.foreColorRec = parseColor(value).argb()
elif attrib == "ServiceBorderColor":
self.borderColorService = parseColor(value).argb()
elif attrib == "ServiceFont":
self.serviceFont = parseFont(value, ((1,1),(1,1)) )
elif attrib == "EntryBackgroundColorNow":
self.backColorNow = parseColor(value).argb()
elif attrib == "EntryForegroundColorNow":
self.foreColorNow = parseColor(value).argb()
elif attrib == "ServiceBorderWidth":
self.serviceBorderWidth = int(value)
elif attrib == "ServiceNamePadding":
self.serviceNamePadding = int(value)
elif attrib == "EventBorderWidth":
self.eventBorderWidth = int(value)
elif attrib == "EventNamePadding":
self.eventNamePadding = int(value)
else:
attribs.append((attrib,value))
self.skinAttributes = attribs
self.l.setFont(0, self.serviceFont)
self.setEventFontsize()
rc = GUIComponent.applySkin(self, desktop, screen)
# now we know our size and can safely set items per page
self.listHeight = self.instance.size().height()
self.listWidth = self.instance.size().width()
self.setItemsPerPage()
return rc
def isSelectable(self, service, service_name, events, picon):
return (events and len(events) and True) or False
def setShowServiceMode(self, value):
self.showServiceTitle = "servicename" in value
self.showPicon = "picon" in value
self.recalcEntrySize()
self.selEntry(0) #Select entry again so that the clipping region gets updated if needed
def setOverjump_Empty(self, overjump_empty):
if overjump_empty:
self.l.setSelectableFunc(self.isSelectable)
else:
self.l.setSelectableFunc(None)
def setEpoch(self, epoch):
self.offs = 0
self.time_epoch = epoch
self.fillMultiEPG(None) # refill
def setCurrentlyPlaying(self, serviceref):
self.currentlyPlaying = serviceref
def getEventFromId(self, service, eventid):
event = None
if self.epgcache is not None and eventid is not None:
event = self.epgcache.lookupEventId(service.ref, eventid)
return event
def getIndexFromService(self, serviceref):
if serviceref is not None:
for x in range(len(self.list)):
if CompareWithAlternatives(self.list[x][0], serviceref.toString()):
return x
return None
def moveToService(self, serviceref):
newIdx = self.getIndexFromService(serviceref)
if newIdx is None:
newIdx = 0
self.setCurrentIndex(newIdx)
def setCurrentIndex(self, index):
if self.instance is not None:
self.instance.moveSelectionTo(index)
def moveTo(self, dir):
if self.instance is not None:
self.instance.moveSelection(dir)
def getCurrent(self):
if self.cur_service is None:
return (None, None)
old_service = self.cur_service #(service, service_name, events, picon)
events = self.cur_service[2]
refstr = self.cur_service[0]
if self.cur_event is None or not events or not len(events):
return (None, ServiceReference(refstr))
event = events[self.cur_event] #(event_id, event_title, begin_time, duration)
eventid = event[0]
service = ServiceReference(refstr)
event = self.getEventFromId(service, eventid) # get full event info
return (event, service)
def connectSelectionChanged(func):
if not self.onSelChanged.count(func):
self.onSelChanged.append(func)
def disconnectSelectionChanged(func):
self.onSelChanged.remove(func)
def serviceChanged(self):
cur_sel = self.l.getCurrentSelection()
if cur_sel:
self.findBestEvent()
def findBestEvent(self):
old_service = self.cur_service #(service, service_name, events, picon)
cur_service = self.cur_service = self.l.getCurrentSelection()
time_base = self.getTimeBase()
now = time()
if old_service and self.cur_event is not None:
events = old_service[2]
cur_event = events[self.cur_event] #(event_id, event_title, begin_time, duration)
if self.last_time < cur_event[2] or cur_event[2]+cur_event[3] < self.last_time:
self.last_time = cur_event[2]
if now > self.last_time:
self.last_time = now
if cur_service:
self.cur_event = None
events = cur_service[2]
if events and len(events):
self.cur_event = idx = 0
for event in events: #iterate all events
if event[2] <= self.last_time and event[2]+event[3] > self.last_time:
self.cur_event = idx
break
idx += 1
self.selEntry(0)
def selectionChanged(self):
for x in self.onSelChanged:
if x is not None:
x()
GUI_WIDGET = eListbox
def setItemsPerPage(self):
global listscreen
if self.listHeight > 0:
if listscreen:
itemHeight = self.listHeight / config.misc.graph_mepg.items_per_page_listscreen.getValue()
else:
itemHeight = self.listHeight / config.misc.graph_mepg.items_per_page.getValue()
else:
itemHeight = 54 # some default (270/5)
if listscreen:
self.instance.resize(eSize(self.listWidth, itemHeight * config.misc.graph_mepg.items_per_page_listscreen.getValue()))
else:
self.instance.resize(eSize(self.listWidth, itemHeight * config.misc.graph_mepg.items_per_page.getValue()))
self.l.setItemHeight(itemHeight)
self.picload.setPara((self.listWidth, itemHeight - 2 * self.eventBorderWidth, 0, 0, 1, 1, "#00000000"))
self.picload.startDecode(resolveFilename(SCOPE_CURRENT_SKIN, 'epg/CurrentEvent.png'), 0, 0, False)
self.nowEvPix = self.picload.getData()
self.picload.startDecode(resolveFilename(SCOPE_CURRENT_SKIN, 'epg/OtherEvent.png'), 0, 0, False)
self.othEvPix = self.picload.getData()
self.picload.startDecode(resolveFilename(SCOPE_CURRENT_SKIN, 'epg/SelectedEvent.png'), 0, 0, False)
self.selEvPix = self.picload.getData()
self.picload.startDecode(resolveFilename(SCOPE_CURRENT_SKIN, 'epg/RecordingEvent.png'), 0, 0, False)
self.recEvPix = self.picload.getData()
self.picload.startDecode(resolveFilename(SCOPE_CURRENT_SKIN, 'epg/CurrentService.png'), 0, 0, False)
self.curSerPix = self.picload.getData()
def setEventFontsize(self):
self.l.setFont(1, gFont(self.entryFontName, self.entryFontSize + config.misc.graph_mepg.ev_fontsize.getValue()))
def postWidgetCreate(self, instance):
instance.setWrapAround(True)
instance.selectionChanged.get().append(self.serviceChanged)
instance.setContent(self.l)
self.l.setSelectionClip(eRect(0, 0, 0, 0), False)
def preWidgetRemove(self, instance):
instance.selectionChanged.get().remove(self.serviceChanged)
instance.setContent(None)
def recalcEntrySize(self):
esize = self.l.getItemSize()
width = esize.width()
height = esize.height()
if self.showServiceTitle:
w = width / 10 * 2;
else: # if self.showPicon: # this must be set if showServiceTitle is None
w = 2 * height - 2 * self.serviceBorderWidth # FIXME: could do better...
self.service_rect = Rect(0, 0, w, height)
self.event_rect = Rect(w, 0, width - w, height)
piconHeight = height - 2 * self.serviceBorderWidth
piconWidth = 2 * piconHeight # FIXME: could do better...
if piconWidth > w - 2 * self.serviceBorderWidth:
piconWidth = w - 2 * self.serviceBorderWidth
self.picon_size = eSize(piconWidth, piconHeight)
def calcEntryPosAndWidthHelper(self, stime, duration, start, end, width):
xpos = (stime - start) * width / (end - start)
ewidth = (stime + duration - start) * width / (end - start)
ewidth -= xpos;
if xpos < 0:
ewidth += xpos;
xpos = 0;
if (xpos + ewidth) > width:
ewidth = width - xpos
return xpos, ewidth
def calcEntryPosAndWidth(self, event_rect, time_base, time_epoch, ev_start, ev_duration):
xpos, width = self.calcEntryPosAndWidthHelper(ev_start, ev_duration, time_base, time_base + time_epoch * 60, event_rect.width())
return xpos + event_rect.left(), width
def buildEntry(self, service, service_name, events, picon):
r1 = self.service_rect
r2 = self.event_rect
selected = self.cur_service[0] == service
# Picon and Service name
if CompareWithAlternatives(service, self.currentlyPlaying and self.currentlyPlaying.toString()):
serviceForeColor = self.foreColorServiceSelected
serviceBackColor = self.backColorServiceSelected
bgpng = self.curSerPix or self.nowEvPix
currentservice = True
else:
serviceForeColor = self.foreColorService
serviceBackColor = self.backColorService
bgpng = self.othEvPix
currentservice = False
res = [ None ]
if bgpng is not None: # bacground for service rect
res.append(MultiContentEntryPixmapAlphaTest(
pos = (r1.x + self.serviceBorderWidth, r1.y + self.serviceBorderWidth),
size = (r1.w - 2 * self.serviceBorderWidth, r1.h - 2 * self.serviceBorderWidth),
png = bgpng))
else:
res.append(MultiContentEntryText(
pos = (r1.x, r1.y),
size = (r1.w, r1.h),
font = 0, flags = RT_HALIGN_LEFT | RT_VALIGN_CENTER,
text = "",
color = serviceForeColor, color_sel = serviceForeColor,
backcolor = serviceBackColor, backcolor_sel = serviceBackColor) )
displayPicon = None
if self.showPicon:
if picon is None: # go find picon and cache its location
picon = getPiconName(service)
curIdx = self.l.getCurrentSelectionIndex()
self.list[curIdx] = (service, service_name, events, picon)
piconWidth = self.picon_size.width()
piconHeight = self.picon_size.height()
if picon != "":
self.picload.setPara((piconWidth, piconHeight, 1, 1, 1, 1, "#FFFFFFFF"))
self.picload.startDecode(picon, 0, 0, False)
displayPicon = self.picload.getData()
if displayPicon is not None:
res.append(MultiContentEntryPixmapAlphaTest(
pos = (r1.x + self.serviceBorderWidth, r1.y + self.serviceBorderWidth),
size = (piconWidth, piconHeight),
png = displayPicon,
backcolor = None, backcolor_sel = None) )
elif not self.showServiceTitle:
# no picon so show servicename anyway in picon space
namefont = 1
namefontflag = int(config.misc.graph_mepg.servicename_alignment.value)
namewidth = piconWidth
piconWidth = 0
else:
piconWidth = 0
if self.showServiceTitle: # we have more space so reset parms
namefont = 0
namefontflag = int(config.misc.graph_mepg.servicename_alignment.value)
namewidth = r1.w - piconWidth
if self.showServiceTitle or displayPicon is None:
res.append(MultiContentEntryText(
pos = (r1.x + piconWidth + self.serviceBorderWidth + self.serviceNamePadding,
r1.y + self.serviceBorderWidth),
size = (namewidth - 2 * (self.serviceBorderWidth + self.serviceNamePadding),
r1.h - 2 * self.serviceBorderWidth),
font = namefont, flags = namefontflag,
text = service_name,
color = serviceForeColor, color_sel = serviceForeColor,
backcolor = None, backcolor_sel = None))
# Events for service
backColorSel = self.backColorSelected
if events:
start = self.time_base + self.offs * self.time_epoch * 60
end = start + self.time_epoch * 60
left = r2.x
top = r2.y
width = r2.w
height = r2.h
now = time()
for ev in events: #(event_id, event_title, begin_time, duration)
stime = ev[2]
duration = ev[3]
xpos, ewidth = self.calcEntryPosAndWidthHelper(stime, duration, start, end, width)
rec = self.timer.isInTimer(ev[0], stime, duration, service)
# event box background
foreColorSelected = foreColor = self.foreColor
if stime <= now and now < stime + duration:
backColor = self.backColorNow
if isPlayableForCur(ServiceReference(service).ref):
foreColor = self.foreColorNow
foreColorSelected = self.foreColorSelected
else:
backColor = self.backColor
if selected and self.select_rect.x == xpos + left and self.selEvPix:
bgpng = self.selEvPix
backColorSel = None
elif rec is not None and rec[1] == 2:
bgpng = self.recEvPix
foreColor = self.foreColorRec
backColor = self.backColorRec
elif stime <= now and now < stime + duration:
bgpng = self.nowEvPix
elif currentservice:
bgpng = self.curSerPix or self.othEvPix
backColor = self.backColorServiceSelected
else:
bgpng = self.othEvPix
if bgpng is not None:
res.append(MultiContentEntryPixmapAlphaTest(
pos = (left + xpos + self.eventBorderWidth, top + self.eventBorderWidth),
size = (ewidth - 2 * self.eventBorderWidth, height - 2 * self.eventBorderWidth),
png = bgpng))
else:
res.append(MultiContentEntryText(
pos = (left + xpos, top), size = (ewidth, height),
font = 1, flags = int(config.misc.graph_mepg.event_alignment.value),
text = "", color = None, color_sel = None,
backcolor = backColor, backcolor_sel = backColorSel))
# event text
evX = left + xpos + self.eventBorderWidth + self.eventNamePadding
evY = top + self.eventBorderWidth
evW = ewidth - 2 * (self.eventBorderWidth + self.eventNamePadding)
evH = height - 2 * self.eventBorderWidth
if evW > 0:
res.append(MultiContentEntryText(
pos = (evX, evY),
size = (evW, evH),
font = 1,
flags = int(config.misc.graph_mepg.event_alignment.value),
text = ev[1],
color = foreColor,
color_sel = foreColorSelected))
# recording icons
if rec is not None and ewidth > 23:
res.append(MultiContentEntryPixmapAlphaTest(
pos = (left + xpos + ewidth - 22, top + height - 22), size = (21, 21),
png = self.clocks[rec[1]] ) )
else:
if selected and self.selEvPix:
res.append(MultiContentEntryPixmapAlphaTest(
pos = (r2.x + self.eventBorderWidth, r2.y + self.eventBorderWidth),
size = (r2.w - 2 * self.eventBorderWidth, r2.h - 2 * self.eventBorderWidth),
png = self.selEvPix))
return res
def selEntry(self, dir, visible = True):
cur_service = self.cur_service #(service, service_name, events, picon)
self.recalcEntrySize()
valid_event = self.cur_event is not None
if cur_service:
update = True
entries = cur_service[2]
if dir == 0: #current
update = False
elif dir == +1: #next
if valid_event and self.cur_event + 1 < len(entries):
self.cur_event += 1
else:
self.offs += 1
self.fillMultiEPG(None) # refill
return True
elif dir == -1: #prev
if valid_event and self.cur_event - 1 >= 0:
self.cur_event -= 1
elif self.offs > 0:
self.offs -= 1
self.fillMultiEPG(None) # refill
return True
elif dir == +2: #next page
self.offs += 1
self.fillMultiEPG(None) # refill
return True
elif dir == -2: #prev
if self.offs > 0:
self.offs -= 1
self.fillMultiEPG(None) # refill
return True
elif dir == +3: #next day
self.offs += 60 * 24 / self.time_epoch
self.fillMultiEPG(None) # refill
return True
elif dir == -3: #prev day
self.offs -= 60 * 24 / self.time_epoch
if self.offs < 0:
self.offs = 0;
self.fillMultiEPG(None) # refill
return True
if cur_service and valid_event:
entry = entries[self.cur_event] #(event_id, event_title, begin_time, duration)
time_base = self.time_base + self.offs*self.time_epoch * 60
xpos, width = self.calcEntryPosAndWidth(self.event_rect, time_base, self.time_epoch, entry[2], entry[3])
self.select_rect = Rect(xpos ,0, width, self.event_rect.height)
self.l.setSelectionClip(eRect(xpos, 0, width, self.event_rect.h), visible and update)
else:
self.select_rect = self.event_rect
self.l.setSelectionClip(eRect(self.event_rect.x, self.event_rect.y, self.event_rect.w, self.event_rect.h), False)
self.selectionChanged()
return False
def fillMultiEPG(self, services, stime = None):
if stime is not None:
self.time_base = int(stime)
if services is None:
time_base = self.time_base + self.offs * self.time_epoch * 60
test = [ (service[0], 0, time_base, self.time_epoch) for service in self.list ]
serviceList = self.list
piconIdx = 3
else:
self.cur_event = None
self.cur_service = None
test = [ (service.ref.toString(), 0, self.time_base, self.time_epoch) for service in services ]
serviceList = services
piconIdx = 0
test.insert(0, 'XRnITBD') #return record, service ref, service name, event id, event title, begin time, duration
epg_data = [] if self.epgcache is None else self.epgcache.lookupEvent(test)
self.list = [ ]
tmp_list = None
service = ""
sname = ""
serviceIdx = 0
for x in epg_data:
if service != x[0]:
if tmp_list is not None:
picon = None if piconIdx == 0 else serviceList[serviceIdx][piconIdx]
self.list.append((service, sname, tmp_list[0][0] is not None and tmp_list or None, picon))
serviceIdx += 1
service = x[0]
sname = x[1]
tmp_list = [ ]
tmp_list.append((x[2], x[3], x[4], x[5])) #(event_id, event_title, begin_time, duration)
if tmp_list and len(tmp_list):
picon = None if piconIdx == 0 else serviceList[serviceIdx][piconIdx]
self.list.append((service, sname, tmp_list[0][0] is not None and tmp_list or None, picon))
serviceIdx += 1
self.l.setList(self.list)
self.findBestEvent()
def getEventRect(self):
rc = self.event_rect
return Rect( rc.left() + (self.instance and self.instance.position().x() or 0), rc.top(), rc.width(), rc.height() )
def getServiceRect(self):
rc = self.service_rect
return Rect( rc.left() + (self.instance and self.instance.position().x() or 0), rc.top(), rc.width(), rc.height() )
def getTimeEpoch(self):
return self.time_epoch
def getTimeBase(self):
return self.time_base + (self.offs * self.time_epoch * 60)
def resetOffset(self):
self.offs = 0
class TimelineText(HTMLComponent, GUIComponent):
def __init__(self):
GUIComponent.__init__(self)
self.l = eListboxPythonMultiContent()
self.l.setSelectionClip(eRect(0, 0, 0, 0))
self.l.setItemHeight(25);
self.foreColor = 0xffc000
self.backColor = 0x000000
self.time_base = 0
self.time_epoch = 0
self.font = gFont("Regular", 20)
GUI_WIDGET = eListbox
def applySkin(self, desktop, screen):
if self.skinAttributes is not None:
attribs = [ ]
for (attrib, value) in self.skinAttributes:
if attrib == "foregroundColor":
self.foreColor = parseColor(value).argb()
elif attrib == "backgroundColor":
self.backColor = parseColor(value).argb()
elif attrib == "font":
self.font = parseFont(value, ((1, 1), (1, 1)) )
else:
attribs.append((attrib,value))
self.skinAttributes = attribs
self.l.setFont(0, self.font)
return GUIComponent.applySkin(self, desktop, screen)
def postWidgetCreate(self, instance):
instance.setContent(self.l)
def setDateFormat(self, value):
if "servicename" in value:
self.datefmt = _("%A %d %B")
elif "picon" in value:
self.datefmt = _("%d-%m")
def setEntries(self, l, timeline_now, time_lines, force):
event_rect = l.getEventRect()
time_epoch = l.getTimeEpoch()
time_base = l.getTimeBase()
if event_rect is None or time_epoch is None or time_base is None:
return
eventLeft = event_rect.left()
res = [ None ]
# Note: event_rect and service_rect are relative to the timeline_text position
# while the time lines are relative to the GraphEPG screen position!
if self.time_base != time_base or self.time_epoch != time_epoch or force:
service_rect = l.getServiceRect()
itemHeight = self.l.getItemSize().height()
time_steps = 60 if time_epoch > 180 else 30
num_lines = time_epoch / time_steps
timeStepsCalc = time_steps * 60
incWidth = event_rect.width() / num_lines
if int(config.misc.graph_mepg.center_timeline.value):
tlMove = incWidth / 2
tlFlags = RT_HALIGN_CENTER | RT_VALIGN_CENTER
else:
tlMove = 0
tlFlags = RT_HALIGN_LEFT | RT_VALIGN_CENTER
res.append( MultiContentEntryText(
pos = (0, 0),
size = (service_rect.width(), itemHeight),
font = 0, flags = RT_HALIGN_LEFT | RT_VALIGN_CENTER,
text = strftime(self.datefmt, localtime(time_base)),
color = self.foreColor, color_sel = self.foreColor,
backcolor = self.backColor, backcolor_sel = self.backColor) )
xpos = 0 # eventLeft
for x in range(0, num_lines):
res.append( MultiContentEntryText(
pos = (service_rect.width() + xpos-tlMove, 0),
size = (incWidth, itemHeight),
font = 0, flags = tlFlags,
text = strftime("%H:%M", localtime( time_base + x*timeStepsCalc )),
color = self.foreColor, color_sel = self.foreColor,
backcolor = self.backColor, backcolor_sel = self.backColor) )
line = time_lines[x]
old_pos = line.position
line.setPosition(xpos + eventLeft, old_pos[1])
line.visible = True
xpos += incWidth
for x in range(num_lines, MAX_TIMELINES):
time_lines[x].visible = False
self.l.setList([res])
self.time_base = time_base
self.time_epoch = time_epoch
now = time()
if now >= time_base and now < (time_base + time_epoch * 60):
xpos = int((((now - time_base) * event_rect.width()) / (time_epoch * 60)) - (timeline_now.instance.size().width() / 2))
old_pos = timeline_now.position
new_pos = (xpos + eventLeft, old_pos[1])
if old_pos != new_pos:
timeline_now.setPosition(new_pos[0], new_pos[1])
timeline_now.visible = True
else:
timeline_now.visible = False
class GraphMultiEPG(Screen, HelpableScreen):
EMPTY = 0
ADD_TIMER = 1
REMOVE_TIMER = 2
ZAP = 1
def __init__(self, session, services, zapFunc=None, bouquetChangeCB=None, bouquetname=""):
Screen.__init__(self, session)
self.bouquetChangeCB = bouquetChangeCB
now = time() - config.epg.histminutes.getValue() * 60
self.ask_time = now - now % int(config.misc.graph_mepg.roundTo.getValue())
self["key_red"] = Button("")
self["key_green"] = Button("")
global listscreen
if listscreen:
self["key_yellow"] = Button(_("Normal mode"))
self.skinName="GraphMultiEPGList"
else:
self["key_yellow"] = Button(_("List mode"))
self["key_blue"] = Button(_("Goto"))
self.key_green_choice = self.EMPTY
self.key_red_choice = self.EMPTY
self["timeline_text"] = TimelineText()
self["Service"] = ServiceEvent()
self["Event"] = Event()
self.time_lines = [ ]
for x in range(0, MAX_TIMELINES):
pm = Pixmap()
self.time_lines.append(pm)
self["timeline%d"%(x)] = pm
self["timeline_now"] = Pixmap()
self.services = services
self.zapFunc = zapFunc
if bouquetname != "":
Screen.setTitle(self, bouquetname)
self["list"] = EPGList( selChangedCB = self.onSelectionChanged,
timer = self.session.nav.RecordTimer,
time_epoch = config.misc.graph_mepg.prev_time_period.value,
overjump_empty = config.misc.graph_mepg.overjump.value)
HelpableScreen.__init__(self)
self["okactions"] = HelpableActionMap(self, "OkCancelActions",
{
"cancel": (self.closeScreen, _("Exit EPG")),
"ok": (self.eventSelected, _("Zap to selected channel, or show detailed event info (depends on configuration)"))
}, -1)
self["okactions"].csel = self
self["epgactions"] = HelpableActionMap(self, "EPGSelectActions",
{
"timerAdd": (self.timerAdd, _("Add/remove timer for current event")),
"info": (self.infoKeyPressed, _("Show detailed event info")),
"red": (self.zapTo, _("Zap to selected channel")),
"yellow": (self.swapMode, _("Switch between normal mode and list mode")),
"blue": (self.enterDateTime, _("Goto specific data/time")),
"menu": (self.showSetup, _("Setup menu")),
"nextBouquet": (self.nextBouquet, _("Show bouquet selection menu")),
"prevBouquet": (self.prevBouquet, _("Show bouquet selection menu")),
"nextService": (self.nextPressed, _("Goto next page of events")),
"prevService": (self.prevPressed, _("Goto previous page of events")),
"preview": (self.preview, _("Preview selected channel")),
"nextDay": (self.nextDay, _("Goto next day of events")),
"prevDay": (self.prevDay, _("Goto previous day of events"))
}, -1)
self["epgactions"].csel = self
self["inputactions"] = HelpableActionMap(self, "InputActions",
{
"left": (self.leftPressed, _("Go to previous event")),
"right": (self.rightPressed, _("Go to next event")),
"1": (self.key1, _("Set time window to 1 hour")),
"2": (self.key2, _("Set time window to 2 hours")),
"3": (self.key3, _("Set time window to 3 hours")),
"4": (self.key4, _("Set time window to 4 hours")),
"5": (self.key5, _("Set time window to 5 hours")),
"6": (self.key6, _("Set time window to 6 hours")),
"7": (self.prevPage, _("Go to previous page of service")),
"9": (self.nextPage, _("Go to next page of service")),
"8": (self.toTop, _("Go to first service")),
"0": (self.toEnd, _("Go to last service"))
}, -1)
self["inputactions"].csel = self
self.updateTimelineTimer = eTimer()
self.updateTimelineTimer.callback.append(self.moveTimeLines)
self.updateTimelineTimer.start(60 * 1000)
self.onLayoutFinish.append(self.onCreate)
self.previousref = self.session.nav.getCurrentlyPlayingServiceOrGroup()
def prevPage(self):
self["list"].moveTo(eListbox.pageUp)
def nextPage(self):
self["list"].moveTo(eListbox.pageDown)
def toTop(self):
self["list"].moveTo(eListbox.moveTop)
def toEnd(self):
self["list"].moveTo(eListbox.moveEnd)
def prevPressed(self):
self.updEvent(-2)
def nextPressed(self):
self.updEvent(+2)
def leftPressed(self):
self.updEvent(-1)
def rightPressed(self):
self.updEvent(+1)
def prevDay(self):
self.updEvent(-3)
def nextDay(self):
self.updEvent(+3)
def updEvent(self, dir, visible = True):
ret = self["list"].selEntry(dir, visible)
if ret:
self.moveTimeLines(True)
def updEpoch(self, mins):
self["list"].setEpoch(mins)
config.misc.graph_mepg.prev_time_period.value = mins
self.moveTimeLines()
def key1(self):
self.updEpoch(60)
def key2(self):
self.updEpoch(120)
def key3(self):
self.updEpoch(180)
def key4(self):
self.updEpoch(240)
def key5(self):
self.updEpoch(300)
def key6(self):
self.updEpoch(360)
def nextBouquet(self):
if self.bouquetChangeCB:
self.bouquetChangeCB(1, self)
def prevBouquet(self):
if self.bouquetChangeCB:
self.bouquetChangeCB(-1, self)
def enterDateTime(self):
t = localtime(time())
config.misc.graph_mepg.prev_time.value = [t.tm_hour, t.tm_min]
self.session.openWithCallback(self.onDateTimeInputClosed, TimeDateInput, config.misc.graph_mepg.prev_time)
def onDateTimeInputClosed(self, ret):
if len(ret) > 1:
if ret[0]:
now = time() - config.epg.histminutes.getValue() * 60
self.ask_time = ret[1] if ret[1] >= now else now
self.ask_time = self.ask_time - self.ask_time % int(config.misc.graph_mepg.roundTo.getValue())
l = self["list"]
l.resetOffset()
l.fillMultiEPG(None, self.ask_time)
self.moveTimeLines(True)
def showSetup(self):
self.session.openWithCallback(self.onSetupClose, GraphMultiEpgSetup)
def onSetupClose(self, ignore = -1):
l = self["list"]
l.setItemsPerPage()
l.setEventFontsize()
l.setEpoch(config.misc.graph_mepg.prev_time_period.value)
l.setOverjump_Empty(config.misc.graph_mepg.overjump.value)
l.setShowServiceMode(config.misc.graph_mepg.servicetitle_mode.value)
now = time() - config.epg.histminutes.getValue() * 60
self.ask_time = now - now % int(config.misc.graph_mepg.roundTo.getValue())
self["timeline_text"].setDateFormat(config.misc.graph_mepg.servicetitle_mode.value)
l.fillMultiEPG(None, self.ask_time)
self.moveTimeLines(True)
def closeScreen(self):
self.zapFunc(None, zapback = True)
config.misc.graph_mepg.save()
self.close(False)
def infoKeyPressed(self):
cur = self["list"].getCurrent()
event = cur[0]
service = cur[1]
if event is not None:
self.session.open(EventViewEPGSelect, event, service, self.eventViewCallback, self.openSingleServiceEPG, self.openMultiServiceEPG, self.openSimilarList)
def openSimilarList(self, eventid, refstr):
self.session.open(EPGSelection, refstr, None, eventid)
def openSingleServiceEPG(self):
ref = self["list"].getCurrent()[1].ref.toString()
if ref:
self.session.open(EPGSelection, ref)
def openMultiServiceEPG(self):
if self.services:
self.session.openWithCallback(self.doRefresh, EPGSelection, self.services, self.zapFunc, None, self.bouquetChangeCB)
def setServices(self, services):
self.services = services
self.onCreate()
def doRefresh(self, answer):
serviceref = self.session.nav.getCurrentlyPlayingServiceOrGroup()
l = self["list"]
l.moveToService(serviceref)
l.setCurrentlyPlaying(serviceref)
self.moveTimeLines()
def onCreate(self):
serviceref = self.session.nav.getCurrentlyPlayingServiceOrGroup()
l = self["list"]
l.setShowServiceMode(config.misc.graph_mepg.servicetitle_mode.value)
self["timeline_text"].setDateFormat(config.misc.graph_mepg.servicetitle_mode.value)
l.fillMultiEPG(self.services, self.ask_time)
l.moveToService(serviceref)
l.setCurrentlyPlaying(serviceref)
self.moveTimeLines()
def eventViewCallback(self, setEvent, setService, val):
l = self["list"]
old = l.getCurrent()
self.updEvent(val, False)
cur = l.getCurrent()
if cur[0] is None and cur[1].ref != old[1].ref:
self.eventViewCallback(setEvent, setService, val)
else:
setService(cur[1])
setEvent(cur[0])
def preview(self):
ref = self["list"].getCurrent()[1]
if ref:
self.zapFunc(ref.ref, preview = True)
self["list"].setCurrentlyPlaying(ref.ref)
self["list"].l.invalidate()
def zapTo(self):
if self.zapFunc and self.key_red_choice == self.ZAP:
ref = self["list"].getCurrent()[1]
if ref:
self.zapFunc(ref.ref)
if self.previousref and self.previousref == ref.ref:
config.misc.graph_mepg.save()
self.close(True)
self.previousref = ref.ref
self["list"].setCurrentlyPlaying(ref.ref)
self["list"].l.invalidate()
def swapMode(self):
global listscreen
listscreen = not listscreen
self.close(None)
def eventSelected(self):
if config.misc.graph_mepg.OKButton.value == "info":
self.infoKeyPressed()
else:
self.zapTo()
def removeTimer(self, timer):
timer.afterEvent = AFTEREVENT.NONE
self.session.nav.RecordTimer.removeEntry(timer)
self["key_green"].setText(_("Add timer"))
self.key_green_choice = self.ADD_TIMER
def timerAdd(self):
cur = self["list"].getCurrent()
event = cur[0]
if event is None:
return
eventid = event.getEventId()
serviceref = cur[1]
refstr = serviceref.ref.toString()
for timer in self.session.nav.RecordTimer.timer_list:
if timer.eit == eventid and timer.service_ref.ref.toString() == refstr:
cb_func = lambda ret : not ret or self.removeTimer(timer)
self.session.openWithCallback(cb_func, MessageBox, _("Do you really want to delete %s?") % event.getEventName())
break
else:
newEntry = RecordTimerEntry(serviceref, checkOldTimers = True, *parseEvent(event))
self.session.openWithCallback(self.finishedTimerAdd, TimerEntry, newEntry)
def finishedTimerAdd(self, answer):
print "finished add"
if answer[0]:
entry = answer[1]
simulTimerList = self.session.nav.RecordTimer.record(entry)
if simulTimerList is not None:
for x in simulTimerList:
if x.setAutoincreaseEnd(entry):
self.session.nav.RecordTimer.timeChanged(x)
simulTimerList = self.session.nav.RecordTimer.record(entry)
if simulTimerList is not None:
self.session.openWithCallback(self.finishSanityCorrection, TimerSanityConflict, simulTimerList)
self["key_green"].setText(_("Remove timer"))
self.key_green_choice = self.REMOVE_TIMER
else:
self["key_green"].setText(_("Add timer"))
self.key_green_choice = self.ADD_TIMER
print "Timeredit aborted"
def finishSanityCorrection(self, answer):
self.finishedTimerAdd(answer)
def onSelectionChanged(self):
cur = self["list"].getCurrent()
event = cur[0]
self["Event"].newEvent(event)
if cur[1] is None or cur[1].getServiceName() == "":
if self.key_green_choice != self.EMPTY:
self["key_green"].setText("")
self.key_green_choice = self.EMPTY
if self.key_red_choice != self.EMPTY:
self["key_red"].setText("")
self.key_red_choice = self.EMPTY
return
servicerefref = cur[1].ref
self["Service"].newService(servicerefref)
if self.key_red_choice != self.ZAP:
self["key_red"].setText(_("Zap"))
self.key_red_choice = self.ZAP
if not event:
if self.key_green_choice != self.EMPTY:
self["key_green"].setText("")
self.key_green_choice = self.EMPTY
return
eventid = event.getEventId()
refstr = servicerefref.toString()
isRecordEvent = False
for timer in self.session.nav.RecordTimer.timer_list:
if timer.eit == eventid and timer.service_ref.ref.toString() == refstr:
isRecordEvent = True
break
if isRecordEvent and self.key_green_choice != self.REMOVE_TIMER:
self["key_green"].setText(_("Remove timer"))
self.key_green_choice = self.REMOVE_TIMER
elif not isRecordEvent and self.key_green_choice != self.ADD_TIMER:
self["key_green"].setText(_("Add timer"))
self.key_green_choice = self.ADD_TIMER
def moveTimeLines(self, force=False):
self.updateTimelineTimer.start((60 - (int(time()) % 60)) * 1000) #keep syncronised
self["timeline_text"].setEntries(self["list"], self["timeline_now"], self.time_lines, force)
self["list"].l.invalidate() # not needed when the zPosition in the skin is correct! ?????
|
noox-/stbgui-1
|
lib/python/Plugins/Extensions/GraphMultiEPG/GraphMultiEpg.py
|
Python
|
gpl-2.0
| 40,917 | 0.034216 |
from ..Qt import QtGui, QtCore
import os, weakref, re
from ..pgcollections import OrderedDict
from .ParameterItem import ParameterItem
PARAM_TYPES = {}
PARAM_NAMES = {}
def registerParameterType(name, cls, override=False):
global PARAM_TYPES
if name in PARAM_TYPES and not override:
raise Exception("Parameter type '%s' already exists (use override=True to replace)" % name)
PARAM_TYPES[name] = cls
PARAM_NAMES[cls] = name
class Parameter(QtCore.QObject):
"""
A Parameter is the basic unit of data in a parameter tree. Each parameter has
a name, a type, a value, and several other properties that modify the behavior of the
Parameter. Parameters may have parent / child / sibling relationships to construct
organized hierarchies. Parameters generally do not have any inherent GUI or visual
interpretation; instead they manage ParameterItem instances which take care of
display and user interaction.
Note: It is fairly uncommon to use the Parameter class directly; mostly you
will use subclasses which provide specialized type and data handling. The static
pethod Parameter.create(...) is an easy way to generate instances of these subclasses.
For more Parameter types, see ParameterTree.parameterTypes module.
=================================== =========================================================
**Signals:**
sigStateChanged(self, change, info) Emitted when anything changes about this parameter at
all.
The second argument is a string indicating what changed
('value', 'childAdded', etc..)
The third argument can be any extra information about
the change
sigTreeStateChanged(self, changes) Emitted when any child in the tree changes state
(but only if monitorChildren() is called)
the format of *changes* is [(param, change, info), ...]
sigValueChanged(self, value) Emitted when value is finished changing
sigValueChanging(self, value) Emitted immediately for all value changes,
including during editing.
sigChildAdded(self, child, index) Emitted when a child is added
sigChildRemoved(self, child) Emitted when a child is removed
sigRemoved(self) Emitted when this parameter is removed
sigParentChanged(self, parent) Emitted when this parameter's parent has changed
sigLimitsChanged(self, limits) Emitted when this parameter's limits have changed
sigDefaultChanged(self, default) Emitted when this parameter's default value has changed
sigNameChanged(self, name) Emitted when this parameter's name has changed
sigOptionsChanged(self, opts) Emitted when any of this parameter's options have changed
=================================== =========================================================
"""
## name, type, limits, etc.
## can also carry UI hints (slider vs spinbox, etc.)
sigValueChanged = QtCore.Signal(object, object) ## self, value emitted when value is finished being edited
sigValueChanging = QtCore.Signal(object, object) ## self, value emitted as value is being edited
sigChildAdded = QtCore.Signal(object, object, object) ## self, child, index
sigChildRemoved = QtCore.Signal(object, object) ## self, child
sigRemoved = QtCore.Signal(object) ## self
sigParentChanged = QtCore.Signal(object, object) ## self, parent
sigLimitsChanged = QtCore.Signal(object, object) ## self, limits
sigDefaultChanged = QtCore.Signal(object, object) ## self, default
sigNameChanged = QtCore.Signal(object, object) ## self, name
sigOptionsChanged = QtCore.Signal(object, object) ## self, {opt:val, ...}
## Emitted when anything changes about this parameter at all.
## The second argument is a string indicating what changed ('value', 'childAdded', etc..)
## The third argument can be any extra information about the change
sigStateChanged = QtCore.Signal(object, object, object) ## self, change, info
## emitted when any child in the tree changes state
## (but only if monitorChildren() is called)
sigTreeStateChanged = QtCore.Signal(object, object) # self, changes
# changes = [(param, change, info), ...]
# bad planning.
#def __new__(cls, *args, **opts):
#try:
#cls = PARAM_TYPES[opts['type']]
#except KeyError:
#pass
#return QtCore.QObject.__new__(cls, *args, **opts)
@staticmethod
def create(**opts):
"""
Static method that creates a new Parameter (or subclass) instance using
opts['type'] to select the appropriate class.
All options are passed directly to the new Parameter's __init__ method.
Use registerParameterType() to add new class types.
"""
typ = opts.get('type', None)
if typ is None:
cls = Parameter
else:
cls = PARAM_TYPES[opts['type']]
return cls(**opts)
def __init__(self, **opts):
"""
Initialize a Parameter object. Although it is rare to directly create a
Parameter instance, the options available to this method are also allowed
by most Parameter subclasses.
================= =========================================================
Keyword Arguments
name The name to give this Parameter. This is the name that
will appear in the left-most column of a ParameterTree
for this Parameter.
value The value to initially assign to this Parameter.
default The default value for this Parameter (most Parameters
provide an option to 'reset to default').
children A list of children for this Parameter. Children
may be given either as a Parameter instance or as a
dictionary to pass to Parameter.create(). In this way,
it is possible to specify complex hierarchies of
Parameters from a single nested data structure.
readonly If True, the user will not be allowed to edit this
Parameter. (default=False)
enabled If False, any widget(s) for this parameter will appear
disabled. (default=True)
visible If False, the Parameter will not appear when displayed
in a ParameterTree. (default=True)
renamable If True, the user may rename this Parameter.
(default=False)
removable If True, the user may remove this Parameter.
(default=False)
expanded If True, the Parameter will appear expanded when
displayed in a ParameterTree (its children will be
visible). (default=True)
================= =========================================================
"""
QtCore.QObject.__init__(self)
self.opts = {
'type': None,
'readonly': False,
'visible': True,
'enabled': True,
'renamable': False,
'removable': False,
'strictNaming': False, # forces name to be usable as a python variable
'expanded': True,
#'limits': None, ## This is a bad plan--each parameter type may have a different data type for limits.
}
self.opts.update(opts)
self.childs = []
self.names = {} ## map name:child
self.items = weakref.WeakKeyDictionary() ## keeps track of tree items representing this parameter
self._parent = None
self.treeStateChanges = [] ## cache of tree state changes to be delivered on next emit
self.blockTreeChangeEmit = 0
#self.monitoringChildren = False ## prevent calling monitorChildren more than once
if 'value' not in self.opts:
self.opts['value'] = None
if 'name' not in self.opts or not isinstance(self.opts['name'], basestring):
raise Exception("Parameter must have a string name specified in opts.")
self.setName(opts['name'])
self.addChildren(self.opts.get('children', []))
if 'value' in self.opts and 'default' not in self.opts:
self.opts['default'] = self.opts['value']
## Connect all state changed signals to the general sigStateChanged
self.sigValueChanged.connect(lambda param, data: self.emitStateChanged('value', data))
self.sigChildAdded.connect(lambda param, *data: self.emitStateChanged('childAdded', data))
self.sigChildRemoved.connect(lambda param, data: self.emitStateChanged('childRemoved', data))
self.sigParentChanged.connect(lambda param, data: self.emitStateChanged('parent', data))
self.sigLimitsChanged.connect(lambda param, data: self.emitStateChanged('limits', data))
self.sigDefaultChanged.connect(lambda param, data: self.emitStateChanged('default', data))
self.sigNameChanged.connect(lambda param, data: self.emitStateChanged('name', data))
self.sigOptionsChanged.connect(lambda param, data: self.emitStateChanged('options', data))
#self.watchParam(self) ## emit treechange signals if our own state changes
def name(self):
"""Return the name of this Parameter."""
return self.opts['name']
def setName(self, name):
"""Attempt to change the name of this parameter; return the actual name.
(The parameter may reject the name change or automatically pick a different name)"""
if self.opts['strictNaming']:
if len(name) < 1 or re.search(r'\W', name) or re.match(r'\d', name[0]):
raise Exception("Parameter name '%s' is invalid. (Must contain only alphanumeric and underscore characters and may not start with a number)" % name)
parent = self.parent()
if parent is not None:
name = parent._renameChild(self, name) ## first ask parent if it's ok to rename
if self.opts['name'] != name:
self.opts['name'] = name
self.sigNameChanged.emit(self, name)
return name
def type(self):
"""Return the type string for this Parameter."""
return self.opts['type']
def isType(self, typ):
"""
Return True if this parameter type matches the name *typ*.
This can occur either of two ways:
- If self.type() == *typ*
- If this parameter's class is registered with the name *typ*
"""
if self.type() == typ:
return True
global PARAM_TYPES
cls = PARAM_TYPES.get(typ, None)
if cls is None:
raise Exception("Type name '%s' is not registered." % str(typ))
return self.__class__ is cls
def childPath(self, child):
"""
Return the path of parameter names from self to child.
If child is not a (grand)child of self, return None.
"""
path = []
while child is not self:
path.insert(0, child.name())
child = child.parent()
if child is None:
return None
return path
def setValue(self, value, blockSignal=None):
"""
Set the value of this Parameter; return the actual value that was set.
(this may be different from the value that was requested)
"""
try:
if blockSignal is not None:
self.sigValueChanged.disconnect(blockSignal)
if self.opts['value'] == value:
return value
self.opts['value'] = value
self.sigValueChanged.emit(self, value)
finally:
if blockSignal is not None:
self.sigValueChanged.connect(blockSignal)
return value
def value(self):
"""
Return the value of this Parameter.
"""
return self.opts['value']
def getValues(self):
"""Return a tree of all values that are children of this parameter"""
vals = OrderedDict()
for ch in self:
vals[ch.name()] = (ch.value(), ch.getValues())
return vals
def saveState(self):
"""
Return a structure representing the entire state of the parameter tree.
The tree state may be restored from this structure using restoreState()
"""
state = self.opts.copy()
state['children'] = OrderedDict([(ch.name(), ch.saveState()) for ch in self])
if state['type'] is None:
global PARAM_NAMES
state['type'] = PARAM_NAMES.get(type(self), None)
return state
def restoreState(self, state, recursive=True, addChildren=True, removeChildren=True, blockSignals=True):
"""
Restore the state of this parameter and its children from a structure generated using saveState()
If recursive is True, then attempt to restore the state of child parameters as well.
If addChildren is True, then any children which are referenced in the state object will be
created if they do not already exist.
If removeChildren is True, then any children which are not referenced in the state object will
be removed.
If blockSignals is True, no signals will be emitted until the tree has been completely restored.
This prevents signal handlers from responding to a partially-rebuilt network.
"""
childState = state.get('children', [])
## list of children may be stored either as list or dict.
if isinstance(childState, dict):
childState = childState.values()
if blockSignals:
self.blockTreeChangeSignal()
try:
self.setOpts(**state)
if not recursive:
return
ptr = 0 ## pointer to first child that has not been restored yet
foundChilds = set()
#print "==============", self.name()
for ch in childState:
name = ch['name']
typ = ch['type']
#print('child: %s, %s' % (self.name()+'.'+name, typ))
## First, see if there is already a child with this name and type
gotChild = False
for i, ch2 in enumerate(self.childs[ptr:]):
#print " ", ch2.name(), ch2.type()
if ch2.name() != name or not ch2.isType(typ):
continue
gotChild = True
#print " found it"
if i != 0: ## move parameter to next position
#self.removeChild(ch2)
self.insertChild(ptr, ch2)
#print " moved to position", ptr
ch2.restoreState(ch, recursive=recursive, addChildren=addChildren, removeChildren=removeChildren)
foundChilds.add(ch2)
break
if not gotChild:
if not addChildren:
#print " ignored child"
continue
#print " created new"
ch2 = Parameter.create(**ch)
self.insertChild(ptr, ch2)
foundChilds.add(ch2)
ptr += 1
if removeChildren:
for ch in self.childs[:]:
if ch not in foundChilds:
#print " remove:", ch
self.removeChild(ch)
finally:
if blockSignals:
self.unblockTreeChangeSignal()
def defaultValue(self):
"""Return the default value for this parameter."""
return self.opts['default']
def setDefault(self, val):
"""Set the default value for this parameter."""
if self.opts['default'] == val:
return
self.opts['default'] = val
self.sigDefaultChanged.emit(self, val)
def setToDefault(self):
"""Set this parameter's value to the default."""
if self.hasDefault():
self.setValue(self.defaultValue())
def hasDefault(self):
"""Returns True if this parameter has a default value."""
return 'default' in self.opts
def valueIsDefault(self):
"""Returns True if this parameter's value is equal to the default value."""
return self.value() == self.defaultValue()
def setLimits(self, limits):
"""Set limits on the acceptable values for this parameter.
The format of limits depends on the type of the parameter and
some parameters do not make use of limits at all."""
if 'limits' in self.opts and self.opts['limits'] == limits:
return
self.opts['limits'] = limits
self.sigLimitsChanged.emit(self, limits)
return limits
def writable(self):
"""
Returns True if this parameter's value can be changed by the user.
Note that the value of the parameter can *always* be changed by
calling setValue().
"""
return not self.opts.get('readonly', False)
def setWritable(self, writable=True):
"""Set whether this Parameter should be editable by the user. (This is
exactly the opposite of setReadonly)."""
self.setOpts(readonly=not writable)
def setReadonly(self, readonly=True):
"""Set whether this Parameter's value may be edited by the user."""
self.setOpts(readonly=readonly)
def setOpts(self, **opts):
"""
Set any arbitrary options on this parameter.
The exact behavior of this function will depend on the parameter type, but
most parameters will accept a common set of options: value, name, limits,
default, readonly, removable, renamable, visible, enabled, and expanded.
See :func:`Parameter.__init__ <pyqtgraph.parametertree.Parameter.__init__>`
for more information on default options.
"""
changed = OrderedDict()
for k in opts:
if k == 'value':
self.setValue(opts[k])
elif k == 'name':
self.setName(opts[k])
elif k == 'limits':
self.setLimits(opts[k])
elif k == 'default':
self.setDefault(opts[k])
elif k not in self.opts or self.opts[k] != opts[k]:
self.opts[k] = opts[k]
changed[k] = opts[k]
if len(changed) > 0:
self.sigOptionsChanged.emit(self, changed)
def emitStateChanged(self, changeDesc, data):
## Emits stateChanged signal and
## requests emission of new treeStateChanged signal
self.sigStateChanged.emit(self, changeDesc, data)
#self.treeStateChanged(self, changeDesc, data)
self.treeStateChanges.append((self, changeDesc, data))
self.emitTreeChanges()
def makeTreeItem(self, depth):
"""
Return a TreeWidgetItem suitable for displaying/controlling the content of
this parameter. This is called automatically when a ParameterTree attempts
to display this Parameter.
Most subclasses will want to override this function.
"""
if hasattr(self, 'itemClass'):
#print "Param:", self, "Make item from itemClass:", self.itemClass
return self.itemClass(self, depth)
else:
return ParameterItem(self, depth=depth)
def addChild(self, child):
"""Add another parameter to the end of this parameter's child list."""
return self.insertChild(len(self.childs), child)
def addChildren(self, children):
## If children was specified as dict, then assume keys are the names.
if isinstance(children, dict):
ch2 = []
for name, opts in children.items():
if isinstance(opts, dict) and 'name' not in opts:
opts = opts.copy()
opts['name'] = name
ch2.append(opts)
children = ch2
for chOpts in children:
#print self, "Add child:", type(chOpts), id(chOpts)
self.addChild(chOpts)
def insertChild(self, pos, child):
"""
Insert a new child at pos.
If pos is a Parameter, then insert at the position of that Parameter.
If child is a dict, then a parameter is constructed using
:func:`Parameter.create <pyqtgraph.parametertree.Parameter.create>`.
"""
if isinstance(child, dict):
child = Parameter.create(**child)
name = child.name()
if name in self.names and child is not self.names[name]:
if child.opts.get('autoIncrementName', False):
name = self.incrementName(name)
child.setName(name)
else:
raise Exception("Already have child named %s" % str(name))
if isinstance(pos, Parameter):
pos = self.childs.index(pos)
with self.treeChangeBlocker():
if child.parent() is not None:
child.remove()
self.names[name] = child
self.childs.insert(pos, child)
child.parentChanged(self)
self.sigChildAdded.emit(self, child, pos)
child.sigTreeStateChanged.connect(self.treeStateChanged)
return child
def removeChild(self, child):
"""Remove a child parameter."""
name = child.name()
if name not in self.names or self.names[name] is not child:
raise Exception("Parameter %s is not my child; can't remove." % str(child))
del self.names[name]
self.childs.pop(self.childs.index(child))
child.parentChanged(None)
self.sigChildRemoved.emit(self, child)
try:
child.sigTreeStateChanged.disconnect(self.treeStateChanged)
except TypeError: ## already disconnected
pass
def clearChildren(self):
"""Remove all child parameters."""
for ch in self.childs[:]:
self.removeChild(ch)
def children(self):
"""Return a list of this parameter's children.
Warning: this overrides QObject.children
"""
return self.childs[:]
def hasChildren(self):
"""Return True if this Parameter has children."""
return len(self.childs) > 0
def parentChanged(self, parent):
"""This method is called when the parameter's parent has changed.
It may be useful to extend this method in subclasses."""
self._parent = parent
self.sigParentChanged.emit(self, parent)
def parent(self):
"""Return the parent of this parameter."""
return self._parent
def remove(self):
"""Remove this parameter from its parent's child list"""
parent = self.parent()
if parent is None:
raise Exception("Cannot remove; no parent.")
parent.removeChild(self)
self.sigRemoved.emit(self)
def incrementName(self, name):
## return an unused name by adding a number to the name given
base, num = re.match('(.*)(\d*)', name).groups()
numLen = len(num)
if numLen == 0:
num = 2
numLen = 1
else:
num = int(num)
while True:
newName = base + ("%%0%dd"%numLen) % num
if newName not in self.names:
return newName
num += 1
def __iter__(self):
for ch in self.childs:
yield ch
def __getitem__(self, names):
"""Get the value of a child parameter. The name may also be a tuple giving
the path to a sub-parameter::
value = param[('child', 'grandchild')]
"""
if not isinstance(names, tuple):
names = (names,)
return self.param(*names).value()
def __setitem__(self, names, value):
"""Set the value of a child parameter. The name may also be a tuple giving
the path to a sub-parameter::
param[('child', 'grandchild')] = value
"""
if isinstance(names, basestring):
names = (names,)
return self.param(*names).setValue(value)
def param(self, *names):
"""Return a child parameter.
Accepts the name of the child or a tuple (path, to, child)"""
try:
param = self.names[names[0]]
except KeyError:
raise Exception("Parameter %s has no child named %s" % (self.name(), names[0]))
if len(names) > 1:
return param.param(*names[1:])
else:
return param
def __repr__(self):
return "<%s '%s' at 0x%x>" % (self.__class__.__name__, self.name(), id(self))
def __getattr__(self, attr):
## Leaving this undocumented because I might like to remove it in the future..
#print type(self), attr
if 'names' not in self.__dict__:
raise AttributeError(attr)
if attr in self.names:
import traceback
traceback.print_stack()
print("Warning: Use of Parameter.subParam is deprecated. Use Parameter.param(name) instead.")
return self.param(attr)
else:
raise AttributeError(attr)
def _renameChild(self, child, name):
## Only to be called from Parameter.rename
if name in self.names:
return child.name()
self.names[name] = child
del self.names[child.name()]
return name
def registerItem(self, item):
self.items[item] = None
def hide(self):
"""Hide this parameter. It and its children will no longer be visible in any ParameterTree
widgets it is connected to."""
self.show(False)
def show(self, s=True):
"""Show this parameter. """
self.opts['visible'] = s
self.sigOptionsChanged.emit(self, {'visible': s})
def treeChangeBlocker(self):
"""
Return an object that can be used to temporarily block and accumulate
sigTreeStateChanged signals. This is meant to be used when numerous changes are
about to be made to the tree and only one change signal should be
emitted at the end.
Example::
with param.treeChangeBlocker():
param.addChild(...)
param.removeChild(...)
param.setValue(...)
"""
return SignalBlocker(self.blockTreeChangeSignal, self.unblockTreeChangeSignal)
def blockTreeChangeSignal(self):
"""
Used to temporarily block and accumulate tree change signals.
*You must remember to unblock*, so it is advisable to use treeChangeBlocker() instead.
"""
self.blockTreeChangeEmit += 1
def unblockTreeChangeSignal(self):
"""Unblocks enission of sigTreeStateChanged and flushes the changes out through a single signal."""
self.blockTreeChangeEmit -= 1
self.emitTreeChanges()
def treeStateChanged(self, param, changes):
"""
Called when the state of any sub-parameter has changed.
========== ================================================================
Arguments:
param The immediate child whose tree state has changed.
note that the change may have originated from a grandchild.
changes List of tuples describing all changes that have been made
in this event: (param, changeDescr, data)
========== ================================================================
This function can be extended to react to tree state changes.
"""
self.treeStateChanges.extend(changes)
self.emitTreeChanges()
def emitTreeChanges(self):
if self.blockTreeChangeEmit == 0:
changes = self.treeStateChanges
self.treeStateChanges = []
self.sigTreeStateChanged.emit(self, changes)
class SignalBlocker(object):
def __init__(self, enterFn, exitFn):
self.enterFn = enterFn
self.exitFn = exitFn
def __enter__(self):
self.enterFn()
def __exit__(self, exc_type, exc_value, tb):
self.exitFn()
|
hiuwo/acq4
|
acq4/pyqtgraph/parametertree/Parameter.py
|
Python
|
mit
| 29,533 | 0.009142 |
from protoplot.engine.options_container import OptionsContainer
from protoplot.engine.tag import make_tags_list
from protoplot.engine.item_metaclass import ItemMetaclass # @UnusedImport
from protoplot.engine.item_container import ItemContainer
# TODO options should be resolved in the proper order. Here's the proposed
# resulting order for series:
# my_series .set(...)
# my_plot .series.all.set(...)
# my_page .plots.all.series.all.set(...)
# Page.all.plots.all.series.all.set(...)
# Plot .all.series.all.set(...)
# Series.all.set(...)
# For testability, a resolved option should store probably store a complete list
# of values in order of priority.
class Item(metaclass=ItemMetaclass):
'''
Represents an item in the tree. Items typically contain (a) other items, and
(b) item containers.
An Item *instance* has the following attributes:
* An "options" property (of type OptionsContainer), which contains the
options for this specific instance.
* A "set" method as a shortcut for setting these options.
* A (potentially empty) set of tags to allow selective application of
options (a tag is similar to a class in CSS).
An Item *subclass* has the following (class) attributes:
* An item accessor which will return a template item instance for a given
tag specification, which can be a string or the empty slice to specify
the default template. (TODO really empty slice?)
* An "all" property as a shortcut for [:]
* A "set" method as a shortcut for [:].set
* A constructor taking options like the set method
Item subclasses should call the Item constructor with all *args and **kwargs
and define a register_options method to register the options, like so:
self.options.register("color", False, "black")
Note that the Item constructor, which runs before the Item subclass
constructor, sets the initial options. The options must already be
registered at this point, so this cannot be done by the Item subclass
constructor.
'''
def __init__(self, **kwargs):
'''
All kwargs will be used as options, except:
* tag => use as tag(s)
'''
# Create the tag list and remove the tag argument from kwargs.
if 'tag' in kwargs:
self.tags = make_tags_list(kwargs['tag'])
del kwargs['tag']
else:
self.tags = []
# Create the instance-level options and initialize them from the
# remaining kwargs.
#self.options = OptionsContainer(self.__class__.options)
self.options = OptionsContainer()
# Subclasses must override this method. We cannot do this in the
# subclass constructor because it must be done before setting the kwargs
# as options.
self.register_options()
self.options.set(**kwargs)
# Add the instance-level set method. See __set for an explanation.
self.set = self.__set
##############
## Children ##
##############
def children(self):
return [(name, attribute)
for name, attribute in self.__dict__.items()
if isinstance(attribute, Item)]
def containers(self):
return [(name, attribute)
for name, attribute in self.__dict__.items()
if isinstance(attribute, ItemContainer)]
#############
## Options ##
#############
def register_options(self):
raise NotImplementedError(
"Item subclasses must implement the register_options method")
def __set(self, **kwargs):
'''
A setter shortcut for the instance-level options.
This can't be called "set" because there is already a class method with
the same name (defined in the metaclass) and Python does not have
separate namespaces for class methods and instance methods. Therefore,
this method will be assigned to the name of "set" in the instance
namespace by the constructor.
'''
self.options.set(**kwargs)
def resolve_options(self, templates = None, inherited = None, indent="", verbose = False):
def p(*args, **kwargs):
if verbose:
print(indent, *args, **kwargs)
p("Resolve options for", self)
p("* Templates:", templates)
p("* Tags:", self.tags)
# Determine the applicable templates: the ones kindly selected by our
# parent, plus the matching templates from our own class.
templates = templates or []
templates = templates + type(self).matching_templates(self.tags)
template_option_containers = [t.options for t in templates]
inherited = inherited or dict()
# Determine the options for self
own_options = self.options.resolve(template_option_containers, inherited)
#print(indent+"* Own options: {}".format(own_options))
# Determine the options for direct children (recursively)
children_options = {}
for name, child in self.children():
p("* Child", name)
child_templates = [
getattr(template, name)
for template in templates
]
child_inherited = own_options
child_options = child.resolve_options(child_templates, child_inherited, indent = indent+" ", verbose = verbose)
children_options.update(child_options)
# Determine the options for children in containers (recursively)
containers_options = {}
for name, container in self.containers():
p("* Container", name, container)
template_containers = [
getattr(template, name)
for template in templates + [self]
]
p("* Template_containers", template_containers)
for child in container.items:
# Select the matching templates for the child
child_templates = []
for container in template_containers:
child_templates += container.matching_templates(child.tags)
child_inherited = own_options
child_options = child.resolve_options(child_templates, own_options, indent = indent+" ", verbose = verbose)
containers_options.update(child_options)
result = {}
result[self] = own_options
result.update(children_options)
result.update(containers_options)
return result
|
deffi/protoplot
|
protoplot/engine/item.py
|
Python
|
agpl-3.0
| 6,684 | 0.006882 |
# Copyright 2020 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Methods related to outputting script results in a human-readable format.
Also probably a good example of how to *not* write HTML.
"""
from __future__ import print_function
import collections
import logging
import sys
import tempfile
import six
from unexpected_passes_common import data_types
FULL_PASS = 'Fully passed in the following'
PARTIAL_PASS = 'Partially passed in the following'
NEVER_PASS = 'Never passed in the following'
HTML_HEADER = """\
<!DOCTYPE html>
<html>
<head>
<meta content="width=device-width">
<style>
.collapsible_group {
background-color: #757575;
border: none;
color: white;
font-size:20px;
outline: none;
text-align: left;
width: 100%;
}
.active_collapsible_group, .collapsible_group:hover {
background-color: #474747;
}
.highlighted_collapsible_group {
background-color: #008000;
border: none;
color: white;
font-size:20px;
outline: none;
text-align: left;
width: 100%;
}
.active_highlighted_collapsible_group, .highlighted_collapsible_group:hover {
background-color: #004d00;
}
.content {
background-color: #e1e4e8;
display: none;
padding: 0 25px;
}
button {
user-select: text;
}
h1 {
background-color: black;
color: white;
}
</style>
</head>
<body>
"""
HTML_FOOTER = """\
<script>
function OnClickImpl(element) {
let sibling = element.nextElementSibling;
if (sibling.style.display === "block") {
sibling.style.display = "none";
} else {
sibling.style.display = "block";
}
}
function OnClick() {
this.classList.toggle("active_collapsible_group");
OnClickImpl(this);
}
function OnClickHighlighted() {
this.classList.toggle("active_highlighted_collapsible_group");
OnClickImpl(this);
}
// Repeatedly bubble up the highlighted_collapsible_group class as long as all
// siblings are highlighted.
let found_element_to_convert = false;
do {
found_element_to_convert = false;
// Get an initial list of all highlighted_collapsible_groups.
let highlighted_collapsible_groups = document.getElementsByClassName(
"highlighted_collapsible_group");
let highlighted_list = [];
for (elem of highlighted_collapsible_groups) {
highlighted_list.push(elem);
}
// Bubble up the highlighted_collapsible_group class.
while (highlighted_list.length) {
elem = highlighted_list.shift();
if (elem.tagName == 'BODY') {
continue;
}
if (elem.classList.contains("content")) {
highlighted_list.push(elem.previousElementSibling);
continue;
}
if (elem.classList.contains("collapsible_group")) {
found_element_to_convert = true;
elem.classList.add("highlighted_collapsible_group");
elem.classList.remove("collapsible_group");
}
sibling_elements = elem.parentElement.children;
let found_non_highlighted_group = false;
for (e of sibling_elements) {
if (e.classList.contains("collapsible_group")) {
found_non_highlighted_group = true;
break
}
}
if (!found_non_highlighted_group) {
highlighted_list.push(elem.parentElement);
}
}
} while (found_element_to_convert);
// Apply OnClick listeners so [highlighted_]collapsible_groups properly
// shrink/expand.
let collapsible_groups = document.getElementsByClassName("collapsible_group");
for (element of collapsible_groups) {
element.addEventListener("click", OnClick);
}
highlighted_collapsible_groups = document.getElementsByClassName(
"highlighted_collapsible_group");
for (element of highlighted_collapsible_groups) {
element.addEventListener("click", OnClickHighlighted);
}
</script>
</body>
</html>
"""
SECTION_STALE = 'Stale Expectations (Passed 100% Everywhere, Can Remove)'
SECTION_SEMI_STALE = ('Semi Stale Expectations (Passed 100% In Some Places, '
'But Not Everywhere - Can Likely Be Modified But Not '
'Necessarily Removed)')
SECTION_ACTIVE = ('Active Expectations (Failed At Least Once Everywhere, '
'Likely Should Be Left Alone)')
SECTION_UNMATCHED = ('Unmatched Results (An Expectation Existed When The Test '
'Ran, But No Matching One Currently Exists)')
SECTION_UNUSED = ('Unused Expectations (Indicative Of The Configuration No '
'Longer Being Tested Or Tags Changing)')
MAX_BUGS_PER_LINE = 5
MAX_CHARACTERS_PER_CL_LINE = 72
def OutputResults(stale_dict,
semi_stale_dict,
active_dict,
unmatched_results,
unused_expectations,
output_format,
file_handle=None):
"""Outputs script results to |file_handle|.
Args:
stale_dict: A data_types.TestExpectationMap containing all the stale
expectations.
semi_stale_dict: A data_types.TestExpectationMap containing all the
semi-stale expectations.
active_dict: A data_types.TestExpectationmap containing all the active
expectations.
ummatched_results: Any unmatched results found while filling
|test_expectation_map|, as returned by
queries.FillExpectationMapFor[Ci|Try]Builders().
unused_expectations: A dict from expectation file (str) to list of
unmatched Expectations that were pulled out of |test_expectation_map|
output_format: A string denoting the format to output to. Valid values are
"print" and "html".
file_handle: An optional open file-like object to output to. If not
specified, a suitable default will be used.
"""
assert isinstance(stale_dict, data_types.TestExpectationMap)
assert isinstance(semi_stale_dict, data_types.TestExpectationMap)
assert isinstance(active_dict, data_types.TestExpectationMap)
logging.info('Outputting results in format %s', output_format)
stale_str_dict = _ConvertTestExpectationMapToStringDict(stale_dict)
semi_stale_str_dict = _ConvertTestExpectationMapToStringDict(semi_stale_dict)
active_str_dict = _ConvertTestExpectationMapToStringDict(active_dict)
unmatched_results_str_dict = _ConvertUnmatchedResultsToStringDict(
unmatched_results)
unused_expectations_str_list = _ConvertUnusedExpectationsToStringDict(
unused_expectations)
if output_format == 'print':
file_handle = file_handle or sys.stdout
if stale_dict:
file_handle.write(SECTION_STALE + '\n')
RecursivePrintToFile(stale_str_dict, 0, file_handle)
if semi_stale_dict:
file_handle.write(SECTION_SEMI_STALE + '\n')
RecursivePrintToFile(semi_stale_str_dict, 0, file_handle)
if active_dict:
file_handle.write(SECTION_ACTIVE + '\n')
RecursivePrintToFile(active_str_dict, 0, file_handle)
if unused_expectations_str_list:
file_handle.write('\n' + SECTION_UNUSED + '\n')
RecursivePrintToFile(unused_expectations_str_list, 0, file_handle)
if unmatched_results_str_dict:
file_handle.write('\n' + SECTION_UNMATCHED + '\n')
RecursivePrintToFile(unmatched_results_str_dict, 0, file_handle)
elif output_format == 'html':
should_close_file = False
if not file_handle:
should_close_file = True
file_handle = tempfile.NamedTemporaryFile(delete=False,
suffix='.html',
mode='w')
file_handle.write(HTML_HEADER)
if stale_dict:
file_handle.write('<h1>' + SECTION_STALE + '</h1>\n')
_RecursiveHtmlToFile(stale_str_dict, file_handle)
if semi_stale_dict:
file_handle.write('<h1>' + SECTION_SEMI_STALE + '</h1>\n')
_RecursiveHtmlToFile(semi_stale_str_dict, file_handle)
if active_dict:
file_handle.write('<h1>' + SECTION_ACTIVE + '</h1>\n')
_RecursiveHtmlToFile(active_str_dict, file_handle)
if unused_expectations_str_list:
file_handle.write('\n<h1>' + SECTION_UNUSED + "</h1>\n")
_RecursiveHtmlToFile(unused_expectations_str_list, file_handle)
if unmatched_results_str_dict:
file_handle.write('\n<h1>' + SECTION_UNMATCHED + '</h1>\n')
_RecursiveHtmlToFile(unmatched_results_str_dict, file_handle)
file_handle.write(HTML_FOOTER)
if should_close_file:
file_handle.close()
print('Results available at file://%s' % file_handle.name)
else:
raise RuntimeError('Unsupported output format %s' % output_format)
def RecursivePrintToFile(element, depth, file_handle):
"""Recursively prints |element| as text to |file_handle|.
Args:
element: A dict, list, or str/unicode to output.
depth: The current depth of the recursion as an int.
file_handle: An open file-like object to output to.
"""
if element is None:
element = str(element)
if isinstance(element, six.string_types):
file_handle.write((' ' * depth) + element + '\n')
elif isinstance(element, dict):
for k, v in element.items():
RecursivePrintToFile(k, depth, file_handle)
RecursivePrintToFile(v, depth + 1, file_handle)
elif isinstance(element, list):
for i in element:
RecursivePrintToFile(i, depth, file_handle)
else:
raise RuntimeError('Given unhandled type %s' % type(element))
def _RecursiveHtmlToFile(element, file_handle):
"""Recursively outputs |element| as HTMl to |file_handle|.
Iterables will be output as a collapsible section containing any of the
iterable's contents.
Any link-like text will be turned into anchor tags.
Args:
element: A dict, list, or str/unicode to output.
file_handle: An open file-like object to output to.
"""
if isinstance(element, six.string_types):
file_handle.write('<p>%s</p>\n' % _LinkifyString(element))
elif isinstance(element, dict):
for k, v in element.items():
html_class = 'collapsible_group'
# This allows us to later (in JavaScript) recursively highlight sections
# that are likely of interest to the user, i.e. whose expectations can be
# modified.
if k and FULL_PASS in k:
html_class = 'highlighted_collapsible_group'
file_handle.write('<button type="button" class="%s">%s</button>\n' %
(html_class, k))
file_handle.write('<div class="content">\n')
_RecursiveHtmlToFile(v, file_handle)
file_handle.write('</div>\n')
elif isinstance(element, list):
for i in element:
_RecursiveHtmlToFile(i, file_handle)
else:
raise RuntimeError('Given unhandled type %s' % type(element))
def _LinkifyString(s):
"""Turns instances of links into anchor tags.
Args:
s: The string to linkify.
Returns:
A copy of |s| with instances of links turned into anchor tags pointing to
the link.
"""
for component in s.split():
if component.startswith('http'):
component = component.strip(',.!')
s = s.replace(component, '<a href="%s">%s</a>' % (component, component))
return s
def _ConvertTestExpectationMapToStringDict(test_expectation_map):
"""Converts |test_expectation_map| to a dict of strings for reporting.
Args:
test_expectation_map: A data_types.TestExpectationMap.
Returns:
A string dictionary representation of |test_expectation_map| in the
following format:
{
expectation_file: {
test_name: {
expectation_summary: {
builder_name: {
'Fully passed in the following': [
step1,
],
'Partially passed in the following': {
step2: [
failure_link,
],
},
'Never passed in the following': [
step3,
],
}
}
}
}
}
"""
assert isinstance(test_expectation_map, data_types.TestExpectationMap)
output_dict = {}
# This initially looks like a good target for using
# data_types.TestExpectationMap's iterators since there are many nested loops.
# However, we need to reset state in different loops, and the alternative of
# keeping all the state outside the loop and resetting under certain
# conditions ends up being less readable than just using nested loops.
for expectation_file, expectation_map in test_expectation_map.items():
output_dict[expectation_file] = {}
for expectation, builder_map in expectation_map.items():
test_name = expectation.test
expectation_str = _FormatExpectation(expectation)
output_dict[expectation_file].setdefault(test_name, {})
output_dict[expectation_file][test_name][expectation_str] = {}
for builder_name, step_map in builder_map.items():
output_dict[expectation_file][test_name][expectation_str][
builder_name] = {}
fully_passed = []
partially_passed = {}
never_passed = []
for step_name, stats in step_map.items():
if stats.NeverNeededExpectation(expectation):
fully_passed.append(AddStatsToStr(step_name, stats))
elif stats.AlwaysNeededExpectation(expectation):
never_passed.append(AddStatsToStr(step_name, stats))
else:
assert step_name not in partially_passed
partially_passed[step_name] = stats
output_builder_map = output_dict[expectation_file][test_name][
expectation_str][builder_name]
if fully_passed:
output_builder_map[FULL_PASS] = fully_passed
if partially_passed:
output_builder_map[PARTIAL_PASS] = {}
for step_name, stats in partially_passed.items():
s = AddStatsToStr(step_name, stats)
output_builder_map[PARTIAL_PASS][s] = list(stats.failure_links)
if never_passed:
output_builder_map[NEVER_PASS] = never_passed
return output_dict
def _ConvertUnmatchedResultsToStringDict(unmatched_results):
"""Converts |unmatched_results| to a dict of strings for reporting.
Args:
unmatched_results: A dict mapping builder names (string) to lists of
data_types.Result who did not have a matching expectation.
Returns:
A string dictionary representation of |unmatched_results| in the following
format:
{
test_name: {
builder_name: {
step_name: [
individual_result_string_1,
individual_result_string_2,
...
],
...
},
...
},
...
}
"""
output_dict = {}
for builder, results in unmatched_results.items():
for r in results:
builder_map = output_dict.setdefault(r.test, {})
step_map = builder_map.setdefault(builder, {})
result_str = 'Got "%s" on %s with tags [%s]' % (
r.actual_result, data_types.BuildLinkFromBuildId(
r.build_id), ' '.join(r.tags))
step_map.setdefault(r.step, []).append(result_str)
return output_dict
def _ConvertUnusedExpectationsToStringDict(unused_expectations):
"""Converts |unused_expectations| to a dict of strings for reporting.
Args:
unused_expectations: A dict mapping expectation file (str) to lists of
data_types.Expectation who did not have any matching results.
Returns:
A string dictionary representation of |unused_expectations| in the following
format:
{
expectation_file: [
expectation1,
expectation2,
],
}
The expectations are in a format similar to what would be present as a line
in an expectation file.
"""
output_dict = {}
for expectation_file, expectations in unused_expectations.items():
expectation_str_list = []
for e in expectations:
expectation_str_list.append(
'[ %s ] %s [ %s ]' %
(' '.join(e.tags), e.test, ' '.join(e.expected_results)))
output_dict[expectation_file] = expectation_str_list
return output_dict
def _FormatExpectation(expectation):
return '"%s" expectation on "%s"' % (' '.join(
expectation.expected_results), ' '.join(expectation.tags))
def AddStatsToStr(s, stats):
return '%s %s' % (s, stats.GetStatsAsString())
def OutputAffectedUrls(removed_urls, orphaned_urls=None):
"""Outputs URLs of affected expectations for easier consumption by the user.
Outputs the following:
1. A string suitable for passing to Chrome via the command line to
open all bugs in the browser.
2. A string suitable for copying into the CL description to associate the CL
with all the affected bugs.
3. A string containing any bugs that should be closable since there are no
longer any associated expectations.
Args:
removed_urls: A set or list of strings containing bug URLs.
orphaned_urls: A subset of |removed_urls| whose bugs no longer have any
corresponding expectations.
"""
removed_urls = list(removed_urls)
removed_urls.sort()
orphaned_urls = orphaned_urls or []
orphaned_urls = list(orphaned_urls)
orphaned_urls.sort()
_OutputAffectedUrls(removed_urls, orphaned_urls)
_OutputUrlsForClDescription(removed_urls, orphaned_urls)
def _OutputAffectedUrls(affected_urls, orphaned_urls, file_handle=None):
"""Outputs |urls| for opening in a browser as affected bugs.
Args:
affected_urls: A list of strings containing URLs to output.
orphaned_urls: A list of strings containing URLs to output as closable.
file_handle: A file handle to write the string to. Defaults to stdout.
"""
_OutputUrlsForCommandLine(affected_urls, "Affected bugs", file_handle)
if orphaned_urls:
_OutputUrlsForCommandLine(orphaned_urls, "Closable bugs", file_handle)
def _OutputUrlsForCommandLine(urls, description, file_handle=None):
"""Outputs |urls| for opening in a browser.
The output string is meant to be passed to a browser via the command line in
order to open all URLs in that browser, e.g.
`google-chrome https://crbug.com/1234 https://crbug.com/2345`
Args:
urls: A list of strings containing URLs to output.
description: A description of the URLs to be output.
file_handle: A file handle to write the string to. Defaults to stdout.
"""
file_handle = file_handle or sys.stdout
def _StartsWithHttp(url):
return url.startswith('https://') or url.startswith('http://')
urls = [u if _StartsWithHttp(u) else 'https://%s' % u for u in urls]
file_handle.write('%s: %s\n' % (description, ' '.join(urls)))
def _OutputUrlsForClDescription(affected_urls, orphaned_urls, file_handle=None):
"""Outputs |urls| for use in a CL description.
Output adheres to the line length recommendation and max number of bugs per
line supported in Gerrit.
Args:
affected_urls: A list of strings containing URLs to output.
orphaned_urls: A list of strings containing URLs to output as closable.
file_handle: A file handle to write the string to. Defaults to stdout.
"""
def AddBugTypeToOutputString(urls, prefix):
output_str = ''
current_line = ''
bugs_on_line = 0
urls = collections.deque(urls)
while len(urls):
current_bug = urls.popleft()
current_bug = current_bug.split('crbug.com/', 1)[1]
# Handles cases like crbug.com/angleproject/1234.
current_bug = current_bug.replace('/', ':')
# First bug on the line.
if not current_line:
current_line = '%s %s' % (prefix, current_bug)
# Bug or length limit hit for line.
elif (
len(current_line) + len(current_bug) + 2 > MAX_CHARACTERS_PER_CL_LINE
or bugs_on_line >= MAX_BUGS_PER_LINE):
output_str += current_line + '\n'
bugs_on_line = 0
current_line = '%s %s' % (prefix, current_bug)
# Can add to current line.
else:
current_line += ', %s' % current_bug
bugs_on_line += 1
output_str += current_line + '\n'
return output_str
file_handle = file_handle or sys.stdout
affected_but_not_closable = set(affected_urls) - set(orphaned_urls)
affected_but_not_closable = list(affected_but_not_closable)
affected_but_not_closable.sort()
output_str = ''
if affected_but_not_closable:
output_str += AddBugTypeToOutputString(affected_but_not_closable, 'Bug:')
if orphaned_urls:
output_str += AddBugTypeToOutputString(orphaned_urls, 'Fixed:')
file_handle.write('Affected bugs for CL description:\n%s' % output_str)
def ConvertBuilderMapToPassOrderedStringDict(builder_map):
"""Converts |builder_map| into an ordered dict split by pass type.
Args:
builder_map: A data_types.BuildStepMap.
Returns:
A collections.OrderedDict in the following format:
{
result_output.FULL_PASS: {
builder_name: [
step_name (total passes / total builds)
],
},
result_output.NEVER_PASS: {
builder_name: [
step_name (total passes / total builds)
],
},
result_output.PARTIAL_PASS: {
builder_name: [
step_name (total passes / total builds): [
failure links,
],
],
},
}
The ordering and presence of the top level keys is guaranteed.
"""
# This is similar to what we do in
# result_output._ConvertTestExpectationMapToStringDict, but we want the
# top-level grouping to be by pass type rather than by builder, so we can't
# re-use the code from there.
# Ordered dict used to ensure that order is guaranteed when printing out.
str_dict = collections.OrderedDict()
str_dict[FULL_PASS] = {}
str_dict[NEVER_PASS] = {}
str_dict[PARTIAL_PASS] = {}
for builder_name, step_name, stats in builder_map.IterBuildStats():
step_str = AddStatsToStr(step_name, stats)
if stats.did_fully_pass:
str_dict[FULL_PASS].setdefault(builder_name, []).append(step_str)
elif stats.did_never_pass:
str_dict[NEVER_PASS].setdefault(builder_name, []).append(step_str)
else:
str_dict[PARTIAL_PASS].setdefault(builder_name, {})[step_str] = list(
stats.failure_links)
return str_dict
|
nwjs/chromium.src
|
testing/unexpected_passes_common/result_output.py
|
Python
|
bsd-3-clause
| 21,925 | 0.007206 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import gtk
from objects.gradientcolor import GradientColor
from objects.gradient import Gradient
from interfaces.signalizable import Signalizable
class GradientLine(gtk.Viewport):
def __init__(self, moving_callback=None, color_callback=None, gradient=None):
"""
moving_callback - callback function to be called when changing position of the selected color(for spin widget)
gradient - editable gradient
"""
gtk.Viewport.__init__(self)
self.set_size_request(-1, 70)
self.set_shadow_type(gtk.SHADOW_NONE)
self.width = 0
self.height = 0
self._motion = False
self.selected = -1
self.x = 0
self.move = False
self.gradient = gradient
self.gradient.change_size(0, 0, 1, 0)
self.moving_callback = moving_callback
self.color_callback = color_callback
self.layout = gtk.Layout()
self.add(self.layout)
self.layout.set_events(0)
self.layout.add_events(gtk.gdk.BUTTON_PRESS_MASK)
self.layout.connect("button-press-event", self.press)
self.layout.add_events(gtk.gdk.EXPOSURE_MASK)
self.layout.connect("expose-event", self.expose)
self.layout.add_events(gtk.gdk.BUTTON_RELEASE_MASK)
self.layout.connect("button-release-event", self.release)
self.layout.add_events(gtk.gdk.POINTER_MOTION_MASK)
self.layout.connect("motion-notify-event", self.motion)
self.layout.add_events(gtk.gdk.ENTER_NOTIFY_MASK)
self.layout.connect("enter-notify-event", self.enter)
self.layout.add_events(gtk.gdk.LEAVE_NOTIFY_MASK)
self.layout.connect("leave-notify-event", self.leave)
def update(self):
self.queue_draw()
def set_position_for_selected(self, x):
self.gradient.set_position(self.selected, x)
def set_color_for_selected(self, color):
color.position = self.gradient.colors[self.selected].position
self.gradient.set_color(self.selected, color)
def motion(self, widget, event):
self._motion = True
self.x = event.x
if self.move:
if self.selected >= 0:
if self.moving_callback:
self.moving_callback(event.x / self.width)
self.set_position_for_selected(event.x / self.width)
self.gradient.update()
self.queue_draw()
return True
def enter(self, widget, event):
return True
def leave(self, widget, event):
self._motion = False
self.x = event.x
self.queue_draw()
return True
def press(self, widget, event):
self.move = True
cnt = len(self.gradient.colors)
if cnt > 0:
for col in range(0, cnt):
if (self.gradient.colors[col].position > (event.x / self.width - 0.01)) and (
self.gradient.colors[col].position < (event.x / self.width + 0.01)):
self.selected = col
self.moving_callback(self.gradient.colors[col].position)
self.color_callback(self.gradient.colors[col])
break
else:
self.selected = -1
if self.selected == -1 or not cnt:
self.gradient.add_new_color(GradientColor(1, 1, 0.1, 1.0, event.x / self.width))
self.selected = len(self.gradient.colors)-1
self.moving_callback(self.gradient.colors[self.selected].position)
self.color_callback(self.gradient.colors[self.selected])
self.gradient.update()
self.queue_draw()
def release(self, widget, event):
self.move = False
self.queue_draw()
def expose(self, widget, event):
context = widget.bin_window.cairo_create()
self.width, self.height = widget.window.get_size()
context.save()
context.new_path()
#context.translate(0, 0)
if (self.width > 0) and (self.height > 0):
context.scale(self.width, self.height)
context.rectangle(0, 0, 1, 1)
context.set_source(self.gradient.gradient)
context.fill_preserve()
context.restore()
if self._motion and not self.move:
context.new_path()
dash = list()
context.set_dash(dash)
context.set_line_width(2)
context.move_to(self.x, 0)
context.line_to(self.x, 30)
context.move_to(self.x, self.height - 30)
context.line_to(self.x, self.height)
scol = sorted(self.gradient.colors,
key=lambda color: color.position) # better in __init__ and update when necessary
cnt = len(scol)
rx = self.x / self.width
index = 0
for col in scol:
if rx < col.position:
for c in range(0, cnt):
if self.gradient.colors[c].position == col.position:
index = c
break
break
r = self.gradient.colors[index].red
g = self.gradient.colors[index].green
b = self.gradient.colors[index].blue
l = 1 - (r + g + b) / 3.0
if l >= 0.5:
l = 1
else:
l = 0
r, g, b = l, l, l
context.set_source_rgba(r, g, b, 1.0)
context.stroke()
for color in range(len(self.gradient.colors)):
if color == self.selected:
delta = 10
else:
delta = 0
context.new_path()
pos = int(self.width * self.gradient.colors[color].position)
context.move_to(pos - 5, 0)
context.line_to(pos + 5, 0)
context.line_to(pos, 20)
context.line_to(pos - 5, 0)
context.set_source_rgb(self.gradient.colors[color].alpha, self.gradient.colors[color].alpha,
self.gradient.colors[color].alpha)
context.fill_preserve()
if delta:
context.move_to(pos, 20)
context.line_to(pos, 20 + delta)
context.set_source_rgb(0.44, 0.62, 0.81)
context.stroke()
class LinearGradientEditor(gtk.VBox, Signalizable):
def __init__(self):
gtk.VBox.__init__(self)
from canvas import Canvas
self.canvas = Canvas()
table = gtk.Table(4, 4, False)
self.pack_start(table)
self.combobox = gtk.combo_box_new_text()
table.attach(self.combobox, 1, 2, 0, 1, gtk.FILL, 0)
gradient = Gradient()
self.gl = GradientLine(self.moving_callback, self.color_callback, gradient)
table.attach(self.gl, 1, 2, 1, 2, gtk.FILL | gtk.EXPAND, 0)
new_color = gtk.Button()
image = gtk.Image()
image.set_from_stock(gtk.STOCK_NEW, gtk.ICON_SIZE_MENU)
new_color.add(image)
table.attach(new_color, 2, 3, 0, 1, 0, 0, 0)
button = gtk.Button()
image = gtk.Image()
image.set_from_stock(gtk.STOCK_GO_FORWARD, gtk.ICON_SIZE_MENU)
button.add(image)
button.connect("clicked", self.forward)
table.attach(button, 2, 3, 1, 2, 0, gtk.FILL, 0)
button = gtk.Button()
image = gtk.Image()
image.set_from_stock(gtk.STOCK_GO_BACK, gtk.ICON_SIZE_MENU)
button.add(image)
button.connect("clicked", self.back)
table.attach(button, 0, 1, 1, 2, 0, gtk.FILL, 0)
hbox = gtk.HBox()
label = gtk.Label(_("Color:"))
hbox.pack_start(label)
self.color_button = gtk.ColorButton()
self.color_button.set_use_alpha(True)
self.color_button.connect("color-set", self.set_gradient_color)
hbox.pack_start(self.color_button)
label = gtk.Label(_("Position:"))
hbox.pack_start(label)
self.sel_position = gtk.SpinButton(climb_rate=0.00001, digits=5)
self.sel_position.set_range(0.0, 1.0)
self.sel_position.set_wrap(True)
self.sel_position.set_increments(0.00001, 0.1)
self.sel_position.connect("value-changed", self.move_color)
hbox.pack_start(self.sel_position)
table.attach(hbox, 1, 2, 2, 3, gtk.FILL, 0, 0)
self.install_signal("update")
self.show_all()
def set_value(self, value):
self.gl.gradient = Gradient(string=str(value))
def forward(self, widget):
if self.gl:
if self.gl.selected < len(self.gl.gradient.colors) - 1:
self.gl.selected += 1
else:
self.gl.selected = -1
self.moving_callback(self.gl.gradient.colors[self.gl.selected].position)
self.update()
def back(self, widget):
if self.gl:
if self.gl.selected > -1:
self.gl.selected -= 1
else:
self.gl.selected = len(self.gl.gradient.colors) - 1
self.moving_callback(self.gl.gradient.colors[self.gl.selected].position)
self.update()
def moving_callback(self, x):
self.sel_position.set_value(x)
self.update()
def color_callback(self, color):
self.color_button.set_color(gtk.gdk.Color(float(color.red), float(color.green), float(color.blue)))
self.color_button.set_alpha(int(color.alpha * 65535))
self.update()
def move_color(self, widget):
if self.gl:
self.gl.set_position_for_selected(widget.get_value())
self.update()
def set_gradient_color(self, widget):
if self.gl:
col = GradientColor(widget.get_color().red_float, widget.get_color().green_float,
widget.get_color().blue_float, widget.get_alpha() / 65535.0,0)
self.gl.set_color_for_selected(col)
self.update()
def update(self):
self.gl.update()
self.emit("update", self)
#self.canvas.update()
if __name__ == '__main__':
horizontal_window = gtk.Window()
horizontal_window.set_default_size(500, 100)
horizontal_window.connect("delete-event", gtk.main_quit)
ge = LinearGradientEditor()
horizontal_window.add(ge)
horizontal_window.show_all()
gtk.main()
|
jaliste/sanaviron
|
sanaviron/ui/gradienteditor.py
|
Python
|
apache-2.0
| 10,331 | 0.00242 |
# Copyright 2022 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from connector import channel
from google3.cloud.graphite.mmv2.services.google.identity_toolkit import tenant_pb2
from google3.cloud.graphite.mmv2.services.google.identity_toolkit import tenant_pb2_grpc
from typing import List
class Tenant(object):
def __init__(
self,
name: str = None,
display_name: str = None,
allow_password_signup: bool = None,
enable_email_link_signin: bool = None,
disable_auth: bool = None,
enable_anonymous_user: bool = None,
mfa_config: dict = None,
test_phone_numbers: dict = None,
project: str = None,
service_account_file: str = "",
):
channel.initialize()
self.name = name
self.display_name = display_name
self.allow_password_signup = allow_password_signup
self.enable_email_link_signin = enable_email_link_signin
self.disable_auth = disable_auth
self.enable_anonymous_user = enable_anonymous_user
self.mfa_config = mfa_config
self.test_phone_numbers = test_phone_numbers
self.project = project
self.service_account_file = service_account_file
def apply(self):
stub = tenant_pb2_grpc.IdentitytoolkitBetaTenantServiceStub(channel.Channel())
request = tenant_pb2.ApplyIdentitytoolkitBetaTenantRequest()
if Primitive.to_proto(self.name):
request.resource.name = Primitive.to_proto(self.name)
if Primitive.to_proto(self.display_name):
request.resource.display_name = Primitive.to_proto(self.display_name)
if Primitive.to_proto(self.allow_password_signup):
request.resource.allow_password_signup = Primitive.to_proto(
self.allow_password_signup
)
if Primitive.to_proto(self.enable_email_link_signin):
request.resource.enable_email_link_signin = Primitive.to_proto(
self.enable_email_link_signin
)
if Primitive.to_proto(self.disable_auth):
request.resource.disable_auth = Primitive.to_proto(self.disable_auth)
if Primitive.to_proto(self.enable_anonymous_user):
request.resource.enable_anonymous_user = Primitive.to_proto(
self.enable_anonymous_user
)
if TenantMfaConfig.to_proto(self.mfa_config):
request.resource.mfa_config.CopyFrom(
TenantMfaConfig.to_proto(self.mfa_config)
)
else:
request.resource.ClearField("mfa_config")
if Primitive.to_proto(self.test_phone_numbers):
request.resource.test_phone_numbers = Primitive.to_proto(
self.test_phone_numbers
)
if Primitive.to_proto(self.project):
request.resource.project = Primitive.to_proto(self.project)
request.service_account_file = self.service_account_file
response = stub.ApplyIdentitytoolkitBetaTenant(request)
self.name = Primitive.from_proto(response.name)
self.display_name = Primitive.from_proto(response.display_name)
self.allow_password_signup = Primitive.from_proto(
response.allow_password_signup
)
self.enable_email_link_signin = Primitive.from_proto(
response.enable_email_link_signin
)
self.disable_auth = Primitive.from_proto(response.disable_auth)
self.enable_anonymous_user = Primitive.from_proto(
response.enable_anonymous_user
)
self.mfa_config = TenantMfaConfig.from_proto(response.mfa_config)
self.test_phone_numbers = Primitive.from_proto(response.test_phone_numbers)
self.project = Primitive.from_proto(response.project)
def delete(self):
stub = tenant_pb2_grpc.IdentitytoolkitBetaTenantServiceStub(channel.Channel())
request = tenant_pb2.DeleteIdentitytoolkitBetaTenantRequest()
request.service_account_file = self.service_account_file
if Primitive.to_proto(self.name):
request.resource.name = Primitive.to_proto(self.name)
if Primitive.to_proto(self.display_name):
request.resource.display_name = Primitive.to_proto(self.display_name)
if Primitive.to_proto(self.allow_password_signup):
request.resource.allow_password_signup = Primitive.to_proto(
self.allow_password_signup
)
if Primitive.to_proto(self.enable_email_link_signin):
request.resource.enable_email_link_signin = Primitive.to_proto(
self.enable_email_link_signin
)
if Primitive.to_proto(self.disable_auth):
request.resource.disable_auth = Primitive.to_proto(self.disable_auth)
if Primitive.to_proto(self.enable_anonymous_user):
request.resource.enable_anonymous_user = Primitive.to_proto(
self.enable_anonymous_user
)
if TenantMfaConfig.to_proto(self.mfa_config):
request.resource.mfa_config.CopyFrom(
TenantMfaConfig.to_proto(self.mfa_config)
)
else:
request.resource.ClearField("mfa_config")
if Primitive.to_proto(self.test_phone_numbers):
request.resource.test_phone_numbers = Primitive.to_proto(
self.test_phone_numbers
)
if Primitive.to_proto(self.project):
request.resource.project = Primitive.to_proto(self.project)
response = stub.DeleteIdentitytoolkitBetaTenant(request)
@classmethod
def list(self, project, service_account_file=""):
stub = tenant_pb2_grpc.IdentitytoolkitBetaTenantServiceStub(channel.Channel())
request = tenant_pb2.ListIdentitytoolkitBetaTenantRequest()
request.service_account_file = service_account_file
request.Project = project
return stub.ListIdentitytoolkitBetaTenant(request).items
def to_proto(self):
resource = tenant_pb2.IdentitytoolkitBetaTenant()
if Primitive.to_proto(self.name):
resource.name = Primitive.to_proto(self.name)
if Primitive.to_proto(self.display_name):
resource.display_name = Primitive.to_proto(self.display_name)
if Primitive.to_proto(self.allow_password_signup):
resource.allow_password_signup = Primitive.to_proto(
self.allow_password_signup
)
if Primitive.to_proto(self.enable_email_link_signin):
resource.enable_email_link_signin = Primitive.to_proto(
self.enable_email_link_signin
)
if Primitive.to_proto(self.disable_auth):
resource.disable_auth = Primitive.to_proto(self.disable_auth)
if Primitive.to_proto(self.enable_anonymous_user):
resource.enable_anonymous_user = Primitive.to_proto(
self.enable_anonymous_user
)
if TenantMfaConfig.to_proto(self.mfa_config):
resource.mfa_config.CopyFrom(TenantMfaConfig.to_proto(self.mfa_config))
else:
resource.ClearField("mfa_config")
if Primitive.to_proto(self.test_phone_numbers):
resource.test_phone_numbers = Primitive.to_proto(self.test_phone_numbers)
if Primitive.to_proto(self.project):
resource.project = Primitive.to_proto(self.project)
return resource
class TenantMfaConfig(object):
def __init__(self, state: str = None, enabled_providers: list = None):
self.state = state
self.enabled_providers = enabled_providers
@classmethod
def to_proto(self, resource):
if not resource:
return None
res = tenant_pb2.IdentitytoolkitBetaTenantMfaConfig()
if TenantMfaConfigStateEnum.to_proto(resource.state):
res.state = TenantMfaConfigStateEnum.to_proto(resource.state)
if TenantMfaConfigEnabledProvidersEnumArray.to_proto(
resource.enabled_providers
):
res.enabled_providers.extend(
TenantMfaConfigEnabledProvidersEnumArray.to_proto(
resource.enabled_providers
)
)
return res
@classmethod
def from_proto(self, resource):
if not resource:
return None
return TenantMfaConfig(
state=TenantMfaConfigStateEnum.from_proto(resource.state),
enabled_providers=TenantMfaConfigEnabledProvidersEnumArray.from_proto(
resource.enabled_providers
),
)
class TenantMfaConfigArray(object):
@classmethod
def to_proto(self, resources):
if not resources:
return resources
return [TenantMfaConfig.to_proto(i) for i in resources]
@classmethod
def from_proto(self, resources):
return [TenantMfaConfig.from_proto(i) for i in resources]
class TenantMfaConfigStateEnum(object):
@classmethod
def to_proto(self, resource):
if not resource:
return resource
return tenant_pb2.IdentitytoolkitBetaTenantMfaConfigStateEnum.Value(
"IdentitytoolkitBetaTenantMfaConfigStateEnum%s" % resource
)
@classmethod
def from_proto(self, resource):
if not resource:
return resource
return tenant_pb2.IdentitytoolkitBetaTenantMfaConfigStateEnum.Name(resource)[
len("IdentitytoolkitBetaTenantMfaConfigStateEnum") :
]
class TenantMfaConfigEnabledProvidersEnum(object):
@classmethod
def to_proto(self, resource):
if not resource:
return resource
return tenant_pb2.IdentitytoolkitBetaTenantMfaConfigEnabledProvidersEnum.Value(
"IdentitytoolkitBetaTenantMfaConfigEnabledProvidersEnum%s" % resource
)
@classmethod
def from_proto(self, resource):
if not resource:
return resource
return tenant_pb2.IdentitytoolkitBetaTenantMfaConfigEnabledProvidersEnum.Name(
resource
)[len("IdentitytoolkitBetaTenantMfaConfigEnabledProvidersEnum") :]
class Primitive(object):
@classmethod
def to_proto(self, s):
if not s:
return ""
return s
@classmethod
def from_proto(self, s):
return s
|
GoogleCloudPlatform/declarative-resource-client-library
|
python/services/identitytoolkit/beta/tenant.py
|
Python
|
apache-2.0
| 10,862 | 0.002025 |
import urllib2
import base64
import json
from link import *;
from GitFetcher import GitHubFetcher;
username = "debuggerman"
password = "megadeth"
orgUrl = "https://api.github.com/orgs"
orgName = "coeus-solutions"
gitFetcher = GitHubFetcher(username = username, password = password, orgUrl = orgUrl, orgName = orgName)
gitFetcher.getOrgInfo()
|
debuggerman/gitstats.py
|
gitstats.py
|
Python
|
mit
| 344 | 0.031977 |
from omelette.fromage.common import DrawableNode
class DrawableNode(DrawableNode):
def __init__(self, uml_object):
super(DrawableNode, self).__init__(uml_object)
|
pienkowb/omelette
|
omelette/fromage/test/data/node.py
|
Python
|
gpl-3.0
| 175 | 0.005714 |
'''
Created on 20/10/2014
@author: fer
'''
if __name__ == '__main__':
print('hola')
x=32 #entero
print x
# variable mensaje
mensaje = "hola mundo"
print mensaje
#booleano
my_bool=True
print my_bool
#exponentes
calculo = 10**2
print calculo
print ("La variable calculo es de tipo: %s" % type(calculo))
print ("Clase %s" % type(calculo).__name__)
''' Conversion de tipos '''
entero = int(3.999)
print entero
real = float(3)
print real
cadena = str(32)
print type(cadena)
pass
|
arkadoel/AprendiendoPython
|
PrimerosPasos/dos.py
|
Python
|
gpl-3.0
| 579 | 0.018998 |
# ----------------------------------------------------------------------
# Numenta Platform for Intelligent Computing (NuPIC)
# Copyright (C) 2013, Numenta, Inc. Unless you have an agreement
# with Numenta, Inc., for a separate license for this software code, the
# following terms and conditions apply:
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero Public License version 3 as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the GNU Affero Public License for more details.
#
# You should have received a copy of the GNU Affero Public License
# along with this program. If not, see http://www.gnu.org/licenses.
#
# http://numenta.org/licenses/
# ----------------------------------------------------------------------
from abc import ABCMeta, abstractmethod
import numbers
import copy
import random
import numpy as np
from nupic.data.fieldmeta import FieldMetaType
import nupic.math.roc_utils as roc
from nupic.data import SENTINEL_VALUE_FOR_MISSING_DATA
from nupic.frameworks.opf.opfutils import InferenceType
from nupic.utils import MovingAverage
from collections import deque
from operator import itemgetter
from safe_interpreter import SafeInterpreter
from io import BytesIO, StringIO
from functools import partial
###############################################################################
# Public Metric specification class
###############################################################################
class MetricSpec(object):
""" This class represents a single Metrics specification in the TaskControl
block
"""
_LABEL_SEPARATOR = ":"
def __init__(self, metric, inferenceElement, field=None, params=None):
"""
metric: A metric type name that identifies which metrics module is
to be constructed by the metrics factory method
opf.metrics.getModule(); e.g., "rmse"
inferenceElement: Some inference types (such as classification), can output
more than one type of inference (i.e. the predicted class
AND the predicted next step). This field specifies which
of these inferences to compute the metrics on
field: Field name on which this metric is to be collected
params: Custom parameters dict for the metrics module's constructor
"""
self.metric = metric
self.inferenceElement = inferenceElement
self.field = field
self.params = params
return
def __repr__(self):
return "{0!s}(metric={1!r}, inferenceElement={2!r}, field={3!r}, params={4!r})".format(self.__class__.__name__,
self.metric,
self.inferenceElement,
self.field,
self.params)
def getLabel(self, inferenceType=None):
""" Helper method that generates a unique label
for a MetricSpec / InferenceType pair. The label is formatted
as follows:
<predictionKind>:<metric type>:(paramName=value)*:field=<fieldname>
For example:
classification:aae:paramA=10.2:paramB=20:window=100:field=pounds
"""
result = []
if inferenceType is not None:
result.append(InferenceType.getLabel(inferenceType))
result.append(self.inferenceElement)
result.append(self.metric)
params = self.params
if params is not None:
sortedParams= params.keys()
sortedParams.sort()
for param in sortedParams:
# Don't include the customFuncSource - it is too long an unwieldy
if param in ('customFuncSource', 'customFuncDef', 'customExpr'):
continue
value = params[param]
if isinstance(value, str):
result.extend(["{0!s}='{1!s}'".format(param, value)])
else:
result.extend(["{0!s}={1!s}".format(param, value)])
if self.field:
result.append("field={0!s}".format((self.field)) )
return self._LABEL_SEPARATOR.join(result)
@classmethod
def getInferenceTypeFromLabel(cls, label):
""" Extracts the PredicitonKind (temporal vs. nontemporal) from the given
metric label
Parameters:
-----------------------------------------------------------------------
label: A label (string) for a metric spec generated by getMetricLabel
(above)
Returns: An InferenceType value
"""
infType, _, _= label.partition(cls._LABEL_SEPARATOR)
if not InferenceType.validate(infType):
return None
return infType
def getModule(metricSpec):
"""
factory method to return an appropriate MetricsIface-based module
args:
metricSpec - an instance of MetricSpec.
metricSpec.metric must be one of:
rmse (root-mean-square error)
aae (average absolute error)
acc (accuracy, for enumerated types)
return:
an appropriate Metric module
"""
metricName = metricSpec.metric
if metricName == 'rmse':
return MetricRMSE(metricSpec)
if metricName == 'nrmse':
return MetricNRMSE(metricSpec)
elif metricName == 'aae':
return MetricAAE(metricSpec)
elif metricName == 'acc':
return MetricAccuracy(metricSpec)
elif metricName == 'avg_err':
return MetricAveError(metricSpec)
elif metricName == 'trivial':
return MetricTrivial(metricSpec)
elif metricName == 'two_gram':
return MetricTwoGram(metricSpec)
elif metricName == 'moving_mean':
return MetricMovingMean(metricSpec)
elif metricName == 'moving_mode':
return MetricMovingMode(metricSpec)
elif metricName == 'neg_auc':
return MetricNegAUC(metricSpec)
elif metricName == 'custom_error_metric':
return CustomErrorMetric(metricSpec)
elif metricName == 'multiStep':
return MetricMultiStep(metricSpec)
elif metricName == 'multiStepProbability':
return MetricMultiStepProbability(metricSpec)
elif metricName == 'ms_aae':
return MetricMultiStepAAE(metricSpec)
elif metricName == 'ms_avg_err':
return MetricMultiStepAveError(metricSpec)
elif metricName == 'passThruPrediction':
return MetricPassThruPrediction(metricSpec)
elif metricName == 'altMAPE':
return MetricAltMAPE(metricSpec)
elif metricName == 'MAPE':
return MetricMAPE(metricSpec)
elif metricName == 'multi':
return MetricMulti(metricSpec)
elif metricName == 'negativeLogLikelihood':
return MetricNegativeLogLikelihood(metricSpec)
else:
raise Exception("Unsupported metric type: {0!s}".format(metricName))
################################################################################
# Helper Methods and Classes #
################################################################################
class _MovingMode(object):
""" Helper class for computing windowed moving
mode of arbitrary values """
def __init__(self, windowSize = None):
"""
Parameters:
-----------------------------------------------------------------------
windowSize: The number of values that are used to compute the
moving average
"""
self._windowSize = windowSize
self._countDict = dict()
self._history = deque([])
def __call__(self, value):
if len(self._countDict) == 0:
pred = ""
else:
pred = max(self._countDict.items(), key = itemgetter(1))[0]
# Update count dict and history buffer
self._history.appendleft(value)
if not value in self._countDict:
self._countDict[value] = 0
self._countDict[value] += 1
if len(self._history) > self._windowSize:
removeElem = self._history.pop()
self._countDict[removeElem] -= 1
assert(self._countDict[removeElem] > -1)
return pred
def _isNumber(value):
return isinstance(value, (numbers.Number, np.number))
class MetricsIface(object):
"""
A Metrics module compares a prediction Y to corresponding ground truth X and returns a single
measure representing the "goodness" of the prediction. It is up to the implementation to
determine how this comparison is made.
"""
__metaclass__ = ABCMeta
@abstractmethod
def __init__(self, metricSpec):
"""
instantiate a MetricsIface-based module.
args:
metricSpec is an instance of MetricSpec
"""
@abstractmethod
def addInstance(self, groundTruth, prediction, record = None, result = None):
""" add one instance consisting of ground truth and a prediction.
Parameters:
-----------------------------------------------------------------------
groundTruth:
The actual measured value at the current timestep
prediction:
The value predicted by the network at the current timestep
groundTruthEncoding:
The binary encoding of the groundTruth value (as a numpy array). Right
now this is only used by CLA networks
predictionEncoding:
The binary encoding of the prediction value (as a numpy array). Right
now this is only used by CLA networks
result:
An ModelResult class (see opfutils.py)
return:
The average error as computed over the metric's window size
"""
@abstractmethod
def getMetric(self):
"""
return:
{value : <current measurement>, "stats" : {<stat> : <value> ...}}
metric name is defined by the MetricIface implementation. stats is expected to contain further
information relevant to the given metric, for example the number of timesteps represented in
the current measurement. all stats are implementation defined, and "stats" can be None
"""
class AggregateMetric(MetricsIface):
"""
Partial implementation of Metrics Interface for metrics that
accumulate an error and compute an aggregate score, potentially
over some window of previous data. This is a convenience class that
can serve as the base class for a wide variety of metrics
"""
___metaclass__ = ABCMeta
#FIXME @abstractmethod - this should be marked abstract method and required to be implemented
def accumulate(self, groundTruth, prediction, accumulatedError, historyBuffer, result):
"""
Updates the accumulated error given the prediction and the
ground truth.
groundTruth: Actual value that is observed for the current timestep
prediction: Value predicted by the network for the given timestep
accumulatedError: The total accumulated score from the previous
predictions (possibly over some finite window)
historyBuffer: A buffer of the last <self.window> ground truth values
that have been observed.
If historyBuffer = None, it means that no history is being kept.
result: An ModelResult class (see opfutils.py), used for advanced
metric calculation (e.g., MetricNegativeLogLikelihood)
retval:
The new accumulated error. That is:
self.accumulatedError = self.accumulate(groundTruth, predictions, accumulatedError)
historyBuffer should also be updated in this method.
self.spec.params["window"] indicates the maximum size of the window
"""
#FIXME @abstractmethod - this should be marked abstract method and required to be implemented
def aggregate(self, accumulatedError, historyBuffer, steps):
"""
Updates the final aggregated score error given the prediction and the
ground truth.
accumulatedError: The total accumulated score from the previous
predictions (possibly over some finite window)
historyBuffer: A buffer of the last <self.window> ground truth values
that have been observed.
If historyBuffer = None, it means that no history is being kept.
steps: The total number of (groundTruth, prediction) pairs that have
been passed to the metric. This does not include pairs where
the groundTruth = SENTINEL_VALUE_FOR_MISSING_DATA
retval:
The new aggregate (final) error measure.
"""
def __init__(self, metricSpec):
""" Initialize this metric
If the params contains the key 'errorMetric', then that is the name of
another metric to which we will pass a modified groundTruth and prediction
to from our addInstance() method. For example, we may compute a moving mean
on the groundTruth and then pass that to the AbsoluteAveError metric
"""
# Init default member variables
self.id = None
self.verbosity = 0
self.window = -1
self.history = None
self.accumulatedError = 0
self.aggregateError = None
self.steps = 0
self.spec = metricSpec
self.disabled = False
# Number of steps ahead we are trying to predict. This is a list of
# prediction steps are processing
self._predictionSteps = [0]
# Where we store the ground truth history
self._groundTruthHistory = deque([])
# The instances of another metric to which we will pass a possibly modified
# groundTruth and prediction to from addInstance(). There is one instance
# for each step present in self._predictionSteps
self._subErrorMetrics = None
# The maximum number of records to process. After this many records have
# been processed, the metric value never changes. This can be used
# as the optimization metric for swarming, while having another metric without
# the maxRecords limit to get an idea as to how well a production model
# would do on the remaining data
self._maxRecords = None
# Parse the metric's parameters
if metricSpec is not None and metricSpec.params is not None:
self.id = metricSpec.params.get('id', None)
self._predictionSteps = metricSpec.params.get('steps', [0])
# Make sure _predictionSteps is a list
if not hasattr(self._predictionSteps, '__iter__'):
self._predictionSteps = [self._predictionSteps]
self.verbosity = metricSpec.params.get('verbosity', 0)
self._maxRecords = metricSpec.params.get('maxRecords', None)
# Get the metric window size
if 'window' in metricSpec.params:
assert metricSpec.params['window'] >= 1
self.history = deque([])
self.window = metricSpec.params['window']
# Get the name of the sub-metric to chain to from addInstance()
if 'errorMetric' in metricSpec.params:
self._subErrorMetrics = []
for step in self._predictionSteps:
subSpec = copy.deepcopy(metricSpec)
# Do all ground truth shifting before we pass onto the sub-metric
subSpec.params.pop('steps', None)
subSpec.params.pop('errorMetric')
subSpec.metric = metricSpec.params['errorMetric']
self._subErrorMetrics.append(getModule(subSpec))
def _getShiftedGroundTruth(self, groundTruth):
""" Utility function that saves the passed in groundTruth into a local
history buffer, and returns the groundTruth from self._predictionSteps ago,
where self._predictionSteps is defined by the 'steps' parameter.
This can be called from the beginning of a derived class's addInstance()
before it passes groundTruth and prediction onto accumulate().
"""
# Save this ground truth into our input history
self._groundTruthHistory.append(groundTruth)
# This is only supported when _predictionSteps has one item in it
assert (len(self._predictionSteps) == 1)
# Return the one from N steps ago
if len(self._groundTruthHistory) > self._predictionSteps[0]:
return self._groundTruthHistory.popleft()
else:
if hasattr(groundTruth, '__iter__'):
return [None] * len(groundTruth)
else:
return None
def addInstance(self, groundTruth, prediction, record = None, result = None):
# This base class does not support time shifting the ground truth or a
# subErrorMetric.
assert (len(self._predictionSteps) == 1)
assert self._predictionSteps[0] == 0
assert self._subErrorMetrics is None
# If missing data,
if groundTruth == SENTINEL_VALUE_FOR_MISSING_DATA or prediction is None:
return self.aggregateError
if self.verbosity > 0:
print "groundTruth:\n{0!s}\nPredictions:\n{1!s}\n{2!s}\n".format(groundTruth,
prediction, self.getMetric())
# Ignore if we've reached maxRecords
if self._maxRecords is not None and self.steps >= self._maxRecords:
return self.aggregateError
# If there is a sub-metric, chain into it's addInstance
# Accumulate the error
self.accumulatedError = self.accumulate(groundTruth, prediction,
self.accumulatedError, self.history, result)
self.steps += 1
return self._compute()
def getMetric(self):
return {'value': self.aggregateError, "stats" : {"steps" : self.steps}}
def _compute(self):
self.aggregateError = self.aggregate(self.accumulatedError, self.history,
self.steps)
return self.aggregateError
class MetricNegativeLogLikelihood(AggregateMetric):
"""
computes negative log-likelihood. Likelihood is the predicted probability of
the true data from a model. It is more powerful than metrics that only considers
the single best prediction (e.g. MSE) as it considers the entire probability
distribution predicted by a model.
It is more appropriate to use likelihood as the error metric when multiple
predictions are possible.
"""
def accumulate(self, groundTruth, prediction, accumulatedError, historyBuffer, result):
bucketll = result.inferences['multiStepBucketLikelihoods']
bucketIdxTruth = result.classifierInput.bucketIndex
if bucketIdxTruth is not None:
# a manually set minimum prediction probability so that the log(LL) doesn't blow up
minProb = 0.00001
negLL = 0
for step in bucketll.keys():
outOfBucketProb = 1 - sum(bucketll[step].values())
if bucketIdxTruth in bucketll[step].keys():
prob = bucketll[step][bucketIdxTruth]
else:
prob = outOfBucketProb
if prob < minProb:
prob = minProb
negLL -= np.log(prob)
accumulatedError += negLL
if historyBuffer is not None:
historyBuffer.append(negLL)
if len(historyBuffer) > self.spec.params["window"]:
accumulatedError -= historyBuffer.popleft()
return accumulatedError
def aggregate(self, accumulatedError, historyBuffer, steps):
n = steps
if historyBuffer is not None:
n = len(historyBuffer)
return accumulatedError / float(n)
class MetricRMSE(AggregateMetric):
"""
computes root-mean-square error
"""
def accumulate(self, groundTruth, prediction, accumulatedError, historyBuffer, result = None):
error = (groundTruth - prediction)**2
accumulatedError += error
if historyBuffer is not None:
historyBuffer.append(error)
if len(historyBuffer) > self.spec.params["window"] :
accumulatedError -= historyBuffer.popleft()
return accumulatedError
def aggregate(self, accumulatedError, historyBuffer, steps):
n = steps
if historyBuffer is not None:
n = len(historyBuffer)
return np.sqrt(accumulatedError / float(n))
class MetricNRMSE(MetricRMSE):
"""computes normalized root-mean-square error"""
def __init__(self, *args, **kwargs):
super(MetricNRMSE, self).__init__(*args, **kwargs)
self.groundTruths = []
def accumulate(self, groundTruth, prediction, accumulatedError, historyBuffer, result = None):
self.groundTruths.append(groundTruth)
return super(MetricNRMSE, self).accumulate(groundTruth,
prediction,
accumulatedError,
historyBuffer,
result)
def aggregate(self, accumulatedError, historyBuffer, steps):
rmse = super(MetricNRMSE, self).aggregate(accumulatedError,
historyBuffer,
steps)
denominator = np.std(self.groundTruths)
return rmse / denominator if denominator > 0 else float("inf")
class MetricAAE(AggregateMetric):
"""
computes average absolute error
"""
def accumulate(self, groundTruth, prediction, accumulatedError, historyBuffer, result = None):
error = abs(groundTruth - prediction)
accumulatedError += error
if historyBuffer is not None:
historyBuffer.append(error)
if len(historyBuffer) > self.spec.params["window"] :
accumulatedError -= historyBuffer.popleft()
return accumulatedError
def aggregate(self, accumulatedError, historyBuffer, steps):
n = steps
if historyBuffer is not None:
n = len(historyBuffer)
return accumulatedError/ float(n)
class MetricAltMAPE(AggregateMetric):
"""
computes the "Alternative" Mean Absolute Percent Error.
A generic MAPE computes the percent error for each sample, and then gets
an average. This can suffer from samples where the actual value is very small
or zero - this one sample can drastically alter the mean.
This metric on the other hand first computes the average of the actual values
and the averages of the errors before dividing. This washes out the effects of
a small number of samples with very small actual values.
"""
def __init__(self, metricSpec):
super(MetricAltMAPE, self).__init__(metricSpec)
self._accumulatedGroundTruth = 0
self._accumulatedError = 0
def addInstance(self, groundTruth, prediction, record = None, result = None):
# If missing data,
if groundTruth == SENTINEL_VALUE_FOR_MISSING_DATA or prediction is None:
return self.aggregateError
# Compute absolute error
error = abs(groundTruth - prediction)
if self.verbosity > 0:
print "MetricAltMAPE:\n groundTruth: %s\n Prediction: " \
"%s\n Error: %s" % (groundTruth, prediction, error)
# Update the accumulated groundTruth and aggregate error
if self.history is not None:
self.history.append((groundTruth, error))
if len(self.history) > self.spec.params["window"] :
(oldGT, oldErr) = self.history.popleft()
self._accumulatedGroundTruth -= oldGT
self._accumulatedError -= oldErr
self._accumulatedGroundTruth += abs(groundTruth)
self._accumulatedError += error
# Compute aggregate pct error
if self._accumulatedGroundTruth > 0:
self.aggregateError = 100.0 * self._accumulatedError / \
self._accumulatedGroundTruth
else:
self.aggregateError = 0
if self.verbosity >= 1:
print " accumGT:", self._accumulatedGroundTruth
print " accumError:", self._accumulatedError
print " aggregateError:", self.aggregateError
self.steps += 1
return self.aggregateError
class MetricMAPE(AggregateMetric):
"""
computes the "Classic" Mean Absolute Percent Error.
This computes the percent error for each sample, and then gets
an average. Note that this can suffer from samples where the actual value is
very small or zero - this one sample can drastically alter the mean. To
avoid this potential issue, use 'altMAPE' instead.
This metric is provided mainly as a convenience when comparing results against
other investigations that have also used MAPE.
"""
def __init__(self, metricSpec):
super(MetricMAPE, self).__init__(metricSpec)
self._accumulatedPctError = 0
def addInstance(self, groundTruth, prediction, record = None, result = None):
# If missing data,
if groundTruth == SENTINEL_VALUE_FOR_MISSING_DATA or prediction is None:
return self.aggregateError
# Compute absolute error
if groundTruth != 0:
pctError = float(abs(groundTruth - prediction))/groundTruth
else:
# Ignore this sample
if self.verbosity > 0:
print "Ignoring sample with groundTruth of 0"
self.steps += 1
return self.aggregateError
if self.verbosity > 0:
print "MetricMAPE:\n groundTruth: %s\n Prediction: " \
"%s\n Error: %s" % (groundTruth, prediction, pctError)
# Update the accumulated groundTruth and aggregate error
if self.history is not None:
self.history.append(pctError)
if len(self.history) > self.spec.params["window"] :
(oldPctErr) = self.history.popleft()
self._accumulatedPctError -= oldPctErr
self._accumulatedPctError += pctError
# Compute aggregate pct error
self.aggregateError = 100.0 * self._accumulatedPctError / len(self.history)
if self.verbosity >= 1:
print " accumPctError:", self._accumulatedPctError
print " aggregateError:", self.aggregateError
self.steps += 1
return self.aggregateError
class MetricPassThruPrediction(MetricsIface):
"""
This is not a metric, but rather a facility for passing the predictions
generated by a baseline metric through to the prediction output cache produced
by a model.
For example, if you wanted to see the predictions generated for the TwoGram
metric, you would specify 'PassThruPredictions' as the 'errorMetric' parameter.
This metric class simply takes the prediction and outputs that as the
aggregateMetric value.
"""
def __init__(self, metricSpec):
self.spec = metricSpec
self.window = metricSpec.params.get("window", 1)
self.avg = MovingAverage(self.window)
self.value = None
def addInstance(self, groundTruth, prediction, record = None, result = None):
"""Compute and store metric value"""
self.value = self.avg(prediction)
def getMetric(self):
"""Return the metric value """
return {"value": self.value}
#def accumulate(self, groundTruth, prediction, accumulatedError, historyBuffer):
# # Simply return the prediction as the accumulated error
# return prediction
#
#def aggregate(self, accumulatedError, historyBuffer, steps):
# # Simply return the prediction as the aggregateError
# return accumulatedError
class MetricMovingMean(AggregateMetric):
"""
computes error metric based on moving mean prediction
"""
def __init__(self, metricSpec):
# This metric assumes a default 'steps' of 1
if not 'steps' in metricSpec.params:
metricSpec.params['steps'] = 1
super(MetricMovingMean, self).__init__(metricSpec)
# Only supports 1 item in _predictionSteps
assert (len(self._predictionSteps) == 1)
self.mean_window = 10
if metricSpec.params.has_key('mean_window'):
assert metricSpec.params['mean_window'] >= 1
self.mean_window = metricSpec.params['mean_window']
# Construct moving average instance
self._movingAverage = MovingAverage(self.mean_window)
def getMetric(self):
return self._subErrorMetrics[0].getMetric()
def addInstance(self, groundTruth, prediction, record = None, result = None):
# If missing data,
if groundTruth == SENTINEL_VALUE_FOR_MISSING_DATA:
return self._subErrorMetrics[0].aggregateError
if self.verbosity > 0:
print "groundTruth:\n{0!s}\nPredictions:\n{1!s}\n{2!s}\n".format(groundTruth, prediction, self.getMetric())
# Use ground truth from 'steps' steps ago as our most recent ground truth
lastGT = self._getShiftedGroundTruth(groundTruth)
if lastGT is None:
return self._subErrorMetrics[0].aggregateError
mean = self._movingAverage(lastGT)
return self._subErrorMetrics[0].addInstance(groundTruth, mean, record)
def evalCustomErrorMetric(expr, prediction, groundTruth, tools):
sandbox = SafeInterpreter(writer=StringIO())
if isinstance(prediction, dict):
sandbox.symtable['prediction'] = tools.mostLikely(prediction)
sandbox.symtable['EXP'] = tools.expValue(prediction)
sandbox.symtable['probabilityDistribution'] = prediction
else:
sandbox.symtable['prediction'] = prediction
sandbox.symtable['groundTruth'] = groundTruth
sandbox.symtable['tools'] = tools
error = sandbox(expr)
return error
class CustomErrorMetric(MetricsIface):
"""
Custom Error Metric class that handles user defined error metrics
"""
class CircularBuffer():
"""
implementation of a fixed size constant random access circular buffer
"""
def __init__(self,length):
#Create an array to back the buffer
#If the length<0 create a zero length array
self.data = [None for i in range(max(length,0))]
self.elements = 0
self.index = 0
self.dataLength = length
def getItem(self,n):
#Get item from n steps back
if n >= self.elements or (n >= self.dataLength and not self.dataLength < 0):
assert False,"Trying to access data not in the stored window"
return None
if self.dataLength>=0:
getInd = (self.index-n-1)%min(self.elements,self.dataLength)
else:
getInd = (self.index-n-1)%self.elements
return self.data[getInd]
def pushToEnd(self,obj):
ret = None
#If storing everything simply append right to the list
if(self.dataLength < 0 ):
self.data.append(obj)
self.index+=1
self.elements+=1
return None
if(self.elements==self.dataLength):
#pop last added element
ret = self.data[self.index % self.dataLength]
else:
#else push new element and increment the element counter
self.elements += 1
self.data[self.index % self.dataLength] = obj
self.index += 1
return ret
def __len__(self):
return self.elements
def __init__(self,metricSpec):
self.metricSpec = metricSpec
self.steps = 0
self.error = 0
self.averageError = None
self.errorMatrix = None
self.evalError = self.evalAbsErr
self.errorWindow = 1
self.storeWindow=-1
self.userDataStore = dict()
if "errorWindow" in metricSpec.params:
self.errorWindow = metricSpec.params["errorWindow"]
assert self.errorWindow != 0 , "Window Size cannon be zero"
if "storeWindow" in metricSpec.params:
self.storeWindow = metricSpec.params["storeWindow"]
assert self.storeWindow != 0 , "Window Size cannon be zero"
self.errorStore = self.CircularBuffer(self.errorWindow)
self.recordStore = self.CircularBuffer(self.storeWindow)
if "customExpr" in metricSpec.params:
assert not "customFuncDef" in metricSpec.params
assert not "customFuncSource" in metricSpec.params
self.evalError = partial(evalCustomErrorMetric, metricSpec.params["customExpr"])
elif "customFuncSource" in metricSpec.params:
assert not "customFuncDef" in metricSpec.params
assert not "customExpr" in metricSpec.params
exec(metricSpec.params["customFuncSource"])
#pull out defined function from locals
self.evalError = locals()["getError"]
elif "customFuncDef" in metricSpec.params:
assert not "customFuncSource" in metricSpec.params
assert not "customExpr" in metricSpec.params
self.evalError = metricSpec.params["customFuncDef"]
def getPrediction(self,n):
#Get prediction from n steps ago
return self.recordStore.getItem(n)["prediction"]
def getFieldValue(self,n,field):
#Get field value from record n steps ago
record = self.recordStore.getItem(n)["record"]
value = record[field]
return value
def getGroundTruth(self,n):
#Get the groundTruth from n steps ago
return self.recordStore.getItem(n)["groundTruth"]
def getBufferLen(self):
return len(self.recordStore)
def storeData(self,name,obj):
#Store custom user data
self.userDataStore[name] = obj
def getData(self,name):
#Retrieve user data
if name in self.userDataStore:
return self.userDataStore[name]
return None
def mostLikely(self, pred):
""" Helper function to return a scalar value representing the most
likely outcome given a probability distribution
"""
if len(pred) == 1:
return pred.keys()[0]
mostLikelyOutcome = None
maxProbability = 0
for prediction, probability in pred.items():
if probability > maxProbability:
mostLikelyOutcome = prediction
maxProbability = probability
return mostLikelyOutcome
def expValue(self, pred):
""" Helper function to return a scalar value representing the expected
value of a probability distribution
"""
if len(pred) == 1:
return pred.keys()[0]
return sum([x*p for x,p in pred.items()])
def evalAbsErr(self,pred,ground):
return abs(pred-ground)
def getMetric(self):
return {'value': self.averageError, "stats" : {"steps" : self.steps}}
def addInstance(self, groundTruth, prediction, record = None, result = None):
#If missing data,
if groundTruth == SENTINEL_VALUE_FOR_MISSING_DATA or prediction is None:
return self.averageError
self.recordStore.pushToEnd({"groundTruth":groundTruth,
"prediction":prediction,"record":record})
if isinstance(prediction, dict):
assert not any(True for p in prediction if p is None), \
"Invalid prediction of `None` in call to {0!s}.addInstance()".format( \
self.__class__.__name__)
error = self.evalError(prediction,groundTruth,self)
popped = self.errorStore.pushToEnd({"error":error})
if not popped is None:
#Subtract error that dropped out of the buffer
self.error -= popped["error"]
self.error+= error
self.averageError = float(self.error)/self.errorStore.elements
self.steps+=1
return self.averageError
class MetricMovingMode(AggregateMetric):
"""
computes error metric based on moving mode prediction
"""
def __init__(self, metricSpec):
super(MetricMovingMode, self).__init__(metricSpec)
self.mode_window = 100
if metricSpec.params.has_key('mode_window'):
assert metricSpec.params['mode_window'] >= 1
self.mode_window = metricSpec.params['mode_window']
# Only supports one stepsize
assert len(self._predictionSteps) == 1
# Construct moving average instance
self._movingMode = _MovingMode(self.mode_window)
def getMetric(self):
return self._subErrorMetrics[0].getMetric()
def addInstance(self, groundTruth, prediction, record = None, result = None):
# If missing data,
if groundTruth == SENTINEL_VALUE_FOR_MISSING_DATA:
return self._subErrorMetrics[0].aggregateError
if self.verbosity > 0:
print "groundTruth:\n{0!s}\nPredictions:\n{1!s}\n{2!s}\n".format(groundTruth, prediction,
self.getMetric())
# Use ground truth from 'steps' steps ago as our most recent ground truth
lastGT = self._getShiftedGroundTruth(groundTruth)
if lastGT is None:
return self._subErrorMetrics[0].aggregateError
mode = self._movingMode(lastGT)
result = self._subErrorMetrics[0].addInstance(groundTruth, mode, record)
return result
class MetricTrivial(AggregateMetric):
"""
computes a metric against the ground truth N steps ago. The metric to
compute is designated by the 'errorMetric' entry in the metric params.
"""
def __init__(self, metricSpec):
# This metric assumes a default 'steps' of 1
if not 'steps' in metricSpec.params:
metricSpec.params['steps'] = 1
super(MetricTrivial, self).__init__(metricSpec)
# Only supports one stepsize
assert len(self._predictionSteps) == 1
# Must have a suberror metric
assert self._subErrorMetrics is not None, "This metric requires that you" \
+ " specify the name of another base metric via the 'errorMetric' " \
+ " parameter."
def getMetric(self):
return self._subErrorMetrics[0].getMetric()
def addInstance(self, groundTruth, prediction, record = None, result = None):
# Use ground truth from 'steps' steps ago as our "prediction"
prediction = self._getShiftedGroundTruth(groundTruth)
if self.verbosity > 0:
print "groundTruth:\n{0!s}\nPredictions:\n{1!s}\n{2!s}\n".format(groundTruth,
prediction, self.getMetric())
# If missing data,
if groundTruth == SENTINEL_VALUE_FOR_MISSING_DATA:
return self._subErrorMetrics[0].aggregateError
# Our "prediction" is simply what happened 'steps' steps ago
return self._subErrorMetrics[0].addInstance(groundTruth, prediction, record)
class MetricTwoGram(AggregateMetric):
"""
computes error metric based on one-grams. The groundTruth passed into
this metric is the encoded output of the field (an array of 1's and 0's).
"""
def __init__(self, metricSpec):
# This metric assumes a default 'steps' of 1
if not 'steps' in metricSpec.params:
metricSpec.params['steps'] = 1
super(MetricTwoGram, self).__init__(metricSpec)
# Only supports 1 stepsize
assert len(self._predictionSteps) == 1
# Must supply the predictionField
assert(metricSpec.params.has_key('predictionField'))
self.predictionField = metricSpec.params['predictionField']
self.twoGramDict = dict()
def getMetric(self):
return self._subErrorMetrics[0].getMetric()
def addInstance(self, groundTruth, prediction, record = None, result = None):
# If missing data return previous error (assuming one gram will always
# receive an instance of ndarray)
if groundTruth.any() == False:
return self._subErrorMetrics[0].aggregateError
# Get actual ground Truth value from record. For this metric, the
# "groundTruth" parameter is the encoder output and we use actualGroundTruth
# to hold the input to the encoder (either a scalar or a category string).
#
# We will use 'groundTruthKey' (the stringified encoded value of
# groundTruth) as the key for our one-gram dict and the 'actualGroundTruth'
# as the values in our dict, which are used to compute our prediction.
actualGroundTruth = record[self.predictionField]
# convert binary array to a string
groundTruthKey = str(groundTruth)
# Get the ground truth key from N steps ago, that is what we will base
# our prediction on. Note that our "prediction" is the prediction for the
# current time step, to be compared to actualGroundTruth
prevGTKey = self._getShiftedGroundTruth(groundTruthKey)
# -------------------------------------------------------------------------
# Get the prediction based on the previously known ground truth
# If no previous, just default to "" or 0, depending on the groundTruth
# data type.
if prevGTKey is None:
if isinstance(actualGroundTruth,str):
pred = ""
else:
pred = 0
# If the previous was never seen before, create a new dict for it.
elif not prevGTKey in self.twoGramDict:
if isinstance(actualGroundTruth,str):
pred = ""
else:
pred = 0
# Create a new dict for it
self.twoGramDict[prevGTKey] = {actualGroundTruth:1}
# If it was seen before, compute the prediction from the past history
else:
# Find most often occurring 1-gram
if isinstance(actualGroundTruth,str):
# Get the most frequent category that followed the previous timestep
twoGramMax = max(self.twoGramDict[prevGTKey].items(), key=itemgetter(1))
pred = twoGramMax[0]
else:
# Get average of all possible values that followed the previous
# timestep
pred = sum(self.twoGramDict[prevGTKey].iterkeys())
pred /= len(self.twoGramDict[prevGTKey])
# Add current ground truth to dict
if actualGroundTruth in self.twoGramDict[prevGTKey]:
self.twoGramDict[prevGTKey][actualGroundTruth] += 1
else:
self.twoGramDict[prevGTKey][actualGroundTruth] = 1
if self.verbosity > 0:
print "\nencoding:{0!s}\nactual:{1!s}\nprevEncoding:{2!s}\nprediction:{3!s}\nmetric:{4!s}".format(groundTruth, actualGroundTruth, prevGTKey, pred, self.getMetric())
return self._subErrorMetrics[0].addInstance(actualGroundTruth, pred, record)
class MetricAccuracy(AggregateMetric):
"""
computes simple accuracy for an enumerated type. all inputs are treated as
discrete members of a set, therefore for example 0.5 is only a correct
response if the ground truth is exactly 0.5. Inputs can be strings, integers,
or reals
"""
def accumulate(self, groundTruth, prediction, accumulatedError, historyBuffer, result = None):
# This is really an accuracy measure rather than an "error" measure
error = 1.0 if groundTruth == prediction else 0.0
accumulatedError += error
if historyBuffer is not None:
historyBuffer.append(error)
if len(historyBuffer) > self.spec.params["window"] :
accumulatedError -= historyBuffer.popleft()
return accumulatedError
def aggregate(self, accumulatedError, historyBuffer, steps):
n = steps
if historyBuffer is not None:
n = len(historyBuffer)
return accumulatedError/ float(n)
class MetricAveError(AggregateMetric):
"""Simply the inverse of the Accuracy metric
More consistent with scalar metrics because
they all report an error to be minimized"""
def accumulate(self, groundTruth, prediction, accumulatedError, historyBuffer, result = None):
error = 1.0 if groundTruth != prediction else 0.0
accumulatedError += error
if historyBuffer is not None:
historyBuffer.append(error)
if len(historyBuffer) > self.spec.params["window"] :
accumulatedError -= historyBuffer.popleft()
return accumulatedError
def aggregate(self, accumulatedError, historyBuffer, steps):
n = steps
if historyBuffer is not None:
n = len(historyBuffer)
return accumulatedError/ float(n)
class MetricNegAUC(AggregateMetric):
""" Computes -1 * AUC (Area Under the Curve) of the ROC (Receiver Operator
Characteristics) curve. We compute -1 * AUC because metrics are optimized
to be LOWER when running hypersearch.
For this, we assuming that category 1 is the "positive" category and
we are generating an ROC curve with the TPR (True Positive Rate) of
category 1 on the y-axis and the FPR (False Positive Rate) on the x-axis.
"""
def accumulate(self, groundTruth, prediction, accumulatedError, historyBuffer, result = None):
""" Accumulate history of groundTruth and "prediction" values.
For this metric, groundTruth is the actual category and "prediction" is a
dict containing one top-level item with a key of 0 (meaning this is the
0-step classificaton) and a value which is another dict, which contains the
probability for each category as output from the classifier. For example,
this is what "prediction" would be if the classifier said that category 0
had a 0.6 probability and category 1 had a 0.4 probability: {0:0.6, 1: 0.4}
"""
# We disable it within aggregate() if we find that the classifier classes
# are not compatible with AUC calculations.
if self.disabled:
return 0
# Just store the groundTruth, probability into our history buffer. We will
# wait until aggregate gets called to actually compute AUC.
if historyBuffer is not None:
historyBuffer.append((groundTruth, prediction[0]))
if len(historyBuffer) > self.spec.params["window"] :
historyBuffer.popleft()
# accumulatedError not used in this metric
return 0
def aggregate(self, accumulatedError, historyBuffer, steps):
# If disabled, do nothing.
if self.disabled:
return 0.0
if historyBuffer is not None:
n = len(historyBuffer)
else:
return 0.0
# For performance reasons, only re-compute this every 'computeEvery' steps
frequency = self.spec.params.get('computeEvery', 1)
if ((steps+1) % frequency) != 0:
return self.aggregateError
# Compute the ROC curve and the area underneath it
actuals = [gt for (gt, probs) in historyBuffer]
classes = np.unique(actuals)
# We can only compute ROC when we have at least 1 sample of each category
if len(classes) < 2:
return -1 * 0.5
# Print warning the first time this metric is asked to be computed on a
# problem with more than 2 classes
if sorted(classes) != [0,1]:
print "WARNING: AUC only implemented for binary classifications where " \
"the categories are category 0 and 1. In this network, the " \
"categories are: %s" % (classes)
print "WARNING: Computation of this metric is disabled for the remainder of " \
"this experiment."
self.disabled = True
return 0.0
# Compute the ROC and AUC. Note that because we are online, there's a
# chance that some of the earlier classification probabilities don't
# have the True class (category 1) yet because it hasn't been seen yet.
# Therefore, we use probs.get() with a default value of 0.
scores = [probs.get(1, 0) for (gt, probs) in historyBuffer]
(fpr, tpr, thresholds) = roc.ROCCurve(actuals, scores)
auc = roc.AreaUnderCurve(fpr, tpr)
# Debug?
if False:
print
print "AUC metric debug info ({0:d} steps):".format((steps))
print " actuals:", actuals
print " probabilities:", ["{0:.2f}".format(x) for x in scores]
print " fpr:", fpr
print " tpr:", tpr
print " thresholds:", thresholds
print " AUC:", auc
return -1 * auc
class MetricMultiStep(AggregateMetric):
"""
This is an "uber" metric which is used to apply one of the other basic
metrics to a specific step in a multi-step prediction.
The specParams are expected to contain:
'errorMetric': name of basic metric to apply
'steps': compare prediction['steps'] to the current
ground truth.
Note that the metrics manager has already performed the time shifting
for us - it passes us the prediction element from 'steps' steps ago
and asks us to compare that to the current ground truth.
When multiple steps of prediction are requested, we average the results of
the underlying metric for each step.
"""
def __init__(self, metricSpec):
super(MetricMultiStep, self).__init__(metricSpec)
assert self._subErrorMetrics is not None
def getMetric(self):
return {'value': self.aggregateError, "stats" : {"steps" : self.steps}}
def addInstance(self, groundTruth, prediction, record = None, result = None):
# If missing data,
if groundTruth == SENTINEL_VALUE_FOR_MISSING_DATA:
return self.aggregateError
# Get the prediction for this time step
aggErrSum = 0
try:
for step, subErrorMetric in \
zip(self._predictionSteps, self._subErrorMetrics):
stepPrediction = prediction[step]
# Unless this is a custom_error_metric, when we have a dict of
# probabilities, get the most probable one. For custom error metrics,
# we pass the probabilities in so that it can decide how best to deal with
# them.
if isinstance(stepPrediction, dict) \
and not isinstance(subErrorMetric, CustomErrorMetric):
predictions = [(prob,value) for (value, prob) in \
stepPrediction.iteritems()]
predictions.sort()
stepPrediction = predictions[-1][1]
# Get sum of the errors
aggErr = subErrorMetric.addInstance(groundTruth, stepPrediction, record, result)
if self.verbosity >= 2:
print "MetricMultiStep {0!s}: aggErr for stepSize {1:d}: {2!s}".format(self._predictionSteps, step, aggErr)
aggErrSum += aggErr
except:
pass
# Return average aggregate error across all step sizes
self.aggregateError = aggErrSum / len(self._subErrorMetrics)
if self.verbosity >= 2:
print "MetricMultiStep {0!s}: aggErrAvg: {1!s}".format(self._predictionSteps,
self.aggregateError)
self.steps += 1
if self.verbosity >= 1:
print "\nMetricMultiStep %s: \n groundTruth: %s\n Predictions: %s" \
"\n Metric: %s" % (self._predictionSteps, groundTruth, prediction,
self.getMetric())
return self.aggregateError
class MetricMultiStepProbability(AggregateMetric):
"""
This is an "uber" metric which is used to apply one of the other basic
metrics to a specific step in a multi-step prediction.
The specParams are expected to contain:
'errorMetric': name of basic metric to apply
'steps': compare prediction['steps'] to the current
ground truth.
Note that the metrics manager has already performed the time shifting
for us - it passes us the prediction element from 'steps' steps ago
and asks us to compare that to the current ground truth.
"""
def __init__(self, metricSpec):
# Default window should be 1
if not 'window' in metricSpec.params:
metricSpec.params['window'] = 1
super(MetricMultiStepProbability, self).__init__(metricSpec)
# Must have a suberror metric
assert self._subErrorMetrics is not None, "This metric requires that you" \
+ " specify the name of another base metric via the 'errorMetric' " \
+ " parameter."
# Force all subErrorMetric windows to 1. This is necessary because by
# default they each do their own history averaging assuming that their
# addInstance() gets called once per interation. But, in this metric
# we actually call into each subErrorMetric multiple times per iteration
for subErrorMetric in self._subErrorMetrics:
subErrorMetric.window = 1
subErrorMetric.spec.params['window'] = 1
self._movingAverage = MovingAverage(self.window)
def getMetric(self):
return {'value': self.aggregateError, "stats" :
{"steps" : self.steps}}
def addInstance(self, groundTruth, prediction, record = None, result = None):
# If missing data,
if groundTruth == SENTINEL_VALUE_FOR_MISSING_DATA:
return self.aggregateError
if self.verbosity >= 1:
print "\nMetricMultiStepProbability %s: \n groundTruth: %s\n " \
"Predictions: %s" % (self._predictionSteps, groundTruth,
prediction)
# Get the aggregateErrors for all requested step sizes and average them
aggErrSum = 0
for step, subErrorMetric in \
zip(self._predictionSteps, self._subErrorMetrics):
stepPrediction = prediction[step]
# If it's a dict of probabilities, get the expected value
error = 0
if isinstance(stepPrediction, dict):
expectedValue = 0
# For every possible prediction multiply its error by its probability
for (pred, prob) in stepPrediction.iteritems():
error += subErrorMetric.addInstance(groundTruth, pred, record) \
* prob
else:
error += subErrorMetric.addInstance(groundTruth, stepPrediction,
record)
if self.verbosity >= 2:
print ("MetricMultiStepProbability {0!s}: aggErr for stepSize {1:d}: {2!s}".format(self._predictionSteps, step, error))
aggErrSum += error
# Return aggregate error
avgAggErr = aggErrSum / len(self._subErrorMetrics)
self.aggregateError = self._movingAverage(avgAggErr)
if self.verbosity >= 2:
print ("MetricMultiStepProbability %s: aggErr over all steps, this "
"iteration (%d): %s" % (self._predictionSteps, self.steps, avgAggErr))
print ("MetricMultiStepProbability {0!s}: aggErr moving avg: {1!s}".format(self._predictionSteps, self.aggregateError))
self.steps += 1
if self.verbosity >= 1:
print "MetricMultiStepProbability {0!s}: \n Error: {1!s}\n Metric: {2!s}".format(self._predictionSteps, avgAggErr, self.getMetric())
return self.aggregateError
class MetricMulti(MetricsIface):
"""Multi metric can combine multiple other (sub)metrics and
weight them to provide combined score."""
def __init__(self, metricSpec):
"""MetricMulti constructor using metricSpec is not allowed."""
raise ValueError("MetricMulti cannot be constructed from metricSpec string! "
"Use MetricMulti(weights,metrics) constructor instead.")
def __init__(self, weights, metrics, window=None):
"""MetricMulti
@param weights - [list of floats] used as weights
@param metrics - [list of submetrics]
@param window - (opt) window size for moving average, or None when disabled
"""
if (weights is None or not isinstance(weights, list) or
not len(weights) > 0 or
not isinstance(weights[0], float)):
raise ValueError("MetricMulti requires 'weights' parameter as a [list of floats]")
self.weights = weights
if (metrics is None or not isinstance(metrics, list) or
not len(metrics) > 0 or
not isinstance(metrics[0], MetricsIface)):
raise ValueError("MetricMulti requires 'metrics' parameter as a [list of Metrics]")
self.metrics = metrics
if window is not None:
self.movingAvg = MovingAverage(windowSize=window)
else:
self.movingAvg = None
def addInstance(self, groundTruth, prediction, record = None, result = None):
err = 0.0
subResults = [m.addInstance(groundTruth, prediction, record) for m in self.metrics]
for i in xrange(len(self.weights)):
if subResults[i] is not None:
err += subResults[i]*self.weights[i]
else: # submetric returned None, propagate
self.err = None
return None
if self.verbosity > 2:
print "IN=",groundTruth," pred=",prediction,": w=",self.weights[i]," metric=",self.metrics[i]," value=",m," err=",err
if self.movingAvg is not None:
err=self.movingAvg(err)
self.err = err
return err
def __repr__(self):
return "MetricMulti(weights={0!s}, metrics={1!s})".format(self.weights, self.metrics)
def getMetric(self):
return {'value': self.err, "stats" : {"weights" : self.weights}}
|
runt18/nupic
|
src/nupic/frameworks/opf/metrics.py
|
Python
|
agpl-3.0
| 54,801 | 0.012992 |
"""
Support for Synology Surveillance Station Cameras.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/camera.synology/
"""
import asyncio
import logging
import voluptuous as vol
import aiohttp
import async_timeout
from homeassistant.const import (
CONF_NAME, CONF_USERNAME, CONF_PASSWORD,
CONF_URL, CONF_WHITELIST, CONF_VERIFY_SSL)
from homeassistant.components.camera import (
Camera, PLATFORM_SCHEMA)
from homeassistant.helpers.aiohttp_client import (
async_get_clientsession, async_create_clientsession,
async_aiohttp_proxy_stream)
import homeassistant.helpers.config_validation as cv
from homeassistant.util.async import run_coroutine_threadsafe
_LOGGER = logging.getLogger(__name__)
DEFAULT_NAME = 'Synology Camera'
DEFAULT_STREAM_ID = '0'
TIMEOUT = 5
CONF_CAMERA_NAME = 'camera_name'
CONF_STREAM_ID = 'stream_id'
QUERY_CGI = 'query.cgi'
QUERY_API = 'SYNO.API.Info'
AUTH_API = 'SYNO.API.Auth'
CAMERA_API = 'SYNO.SurveillanceStation.Camera'
STREAMING_API = 'SYNO.SurveillanceStation.VideoStream'
SESSION_ID = '0'
WEBAPI_PATH = '/webapi/'
AUTH_PATH = 'auth.cgi'
CAMERA_PATH = 'camera.cgi'
STREAMING_PATH = 'SurveillanceStation/videoStreaming.cgi'
CONTENT_TYPE_HEADER = 'Content-Type'
SYNO_API_URL = '{0}{1}{2}'
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
vol.Required(CONF_USERNAME): cv.string,
vol.Required(CONF_PASSWORD): cv.string,
vol.Required(CONF_URL): cv.string,
vol.Optional(CONF_WHITELIST, default=[]): cv.ensure_list,
vol.Optional(CONF_VERIFY_SSL, default=True): cv.boolean,
})
@asyncio.coroutine
def async_setup_platform(hass, config, async_add_devices, discovery_info=None):
"""Setup a Synology IP Camera."""
verify_ssl = config.get(CONF_VERIFY_SSL)
websession_init = async_get_clientsession(hass, verify_ssl)
# Determine API to use for authentication
syno_api_url = SYNO_API_URL.format(
config.get(CONF_URL), WEBAPI_PATH, QUERY_CGI)
query_payload = {
'api': QUERY_API,
'method': 'Query',
'version': '1',
'query': 'SYNO.'
}
query_req = None
try:
with async_timeout.timeout(TIMEOUT, loop=hass.loop):
query_req = yield from websession_init.get(
syno_api_url,
params=query_payload
)
query_resp = yield from query_req.json()
auth_path = query_resp['data'][AUTH_API]['path']
camera_api = query_resp['data'][CAMERA_API]['path']
camera_path = query_resp['data'][CAMERA_API]['path']
streaming_path = query_resp['data'][STREAMING_API]['path']
except (asyncio.TimeoutError, aiohttp.errors.ClientError):
_LOGGER.exception("Error on %s", syno_api_url)
return False
finally:
if query_req is not None:
yield from query_req.release()
# Authticate to NAS to get a session id
syno_auth_url = SYNO_API_URL.format(
config.get(CONF_URL), WEBAPI_PATH, auth_path)
session_id = yield from get_session_id(
hass,
websession_init,
config.get(CONF_USERNAME),
config.get(CONF_PASSWORD),
syno_auth_url
)
# init websession
websession = async_create_clientsession(
hass, verify_ssl, cookies={'id': session_id})
# Use SessionID to get cameras in system
syno_camera_url = SYNO_API_URL.format(
config.get(CONF_URL), WEBAPI_PATH, camera_api)
camera_payload = {
'api': CAMERA_API,
'method': 'List',
'version': '1'
}
try:
with async_timeout.timeout(TIMEOUT, loop=hass.loop):
camera_req = yield from websession.get(
syno_camera_url,
params=camera_payload
)
except (asyncio.TimeoutError, aiohttp.errors.ClientError):
_LOGGER.exception("Error on %s", syno_camera_url)
return False
camera_resp = yield from camera_req.json()
cameras = camera_resp['data']['cameras']
yield from camera_req.release()
# add cameras
devices = []
for camera in cameras:
if not config.get(CONF_WHITELIST):
camera_id = camera['id']
snapshot_path = camera['snapshot_path']
device = SynologyCamera(
hass,
websession,
config,
camera_id,
camera['name'],
snapshot_path,
streaming_path,
camera_path,
auth_path
)
devices.append(device)
async_add_devices(devices)
@asyncio.coroutine
def get_session_id(hass, websession, username, password, login_url):
"""Get a session id."""
auth_payload = {
'api': AUTH_API,
'method': 'Login',
'version': '2',
'account': username,
'passwd': password,
'session': 'SurveillanceStation',
'format': 'sid'
}
auth_req = None
try:
with async_timeout.timeout(TIMEOUT, loop=hass.loop):
auth_req = yield from websession.get(
login_url,
params=auth_payload
)
auth_resp = yield from auth_req.json()
return auth_resp['data']['sid']
except (asyncio.TimeoutError, aiohttp.errors.ClientError):
_LOGGER.exception("Error on %s", login_url)
return False
finally:
if auth_req is not None:
yield from auth_req.release()
class SynologyCamera(Camera):
"""An implementation of a Synology NAS based IP camera."""
def __init__(self, hass, websession, config, camera_id,
camera_name, snapshot_path, streaming_path, camera_path,
auth_path):
"""Initialize a Synology Surveillance Station camera."""
super().__init__()
self.hass = hass
self._websession = websession
self._name = camera_name
self._synology_url = config.get(CONF_URL)
self._camera_name = config.get(CONF_CAMERA_NAME)
self._stream_id = config.get(CONF_STREAM_ID)
self._camera_id = camera_id
self._snapshot_path = snapshot_path
self._streaming_path = streaming_path
self._camera_path = camera_path
self._auth_path = auth_path
def camera_image(self):
"""Return bytes of camera image."""
return run_coroutine_threadsafe(
self.async_camera_image(), self.hass.loop).result()
@asyncio.coroutine
def async_camera_image(self):
"""Return a still image response from the camera."""
image_url = SYNO_API_URL.format(
self._synology_url, WEBAPI_PATH, self._camera_path)
image_payload = {
'api': CAMERA_API,
'method': 'GetSnapshot',
'version': '1',
'cameraId': self._camera_id
}
try:
with async_timeout.timeout(TIMEOUT, loop=self.hass.loop):
response = yield from self._websession.get(
image_url,
params=image_payload
)
except (asyncio.TimeoutError, aiohttp.errors.ClientError):
_LOGGER.exception("Error on %s", image_url)
return None
image = yield from response.read()
yield from response.release()
return image
@asyncio.coroutine
def handle_async_mjpeg_stream(self, request):
"""Return a MJPEG stream image response directly from the camera."""
streaming_url = SYNO_API_URL.format(
self._synology_url, WEBAPI_PATH, self._streaming_path)
streaming_payload = {
'api': STREAMING_API,
'method': 'Stream',
'version': '1',
'cameraId': self._camera_id,
'format': 'mjpeg'
}
stream_coro = self._websession.get(
streaming_url, params=streaming_payload)
yield from async_aiohttp_proxy_stream(self.hass, request, stream_coro)
@property
def name(self):
"""Return the name of this device."""
return self._name
|
morphis/home-assistant
|
homeassistant/components/camera/synology.py
|
Python
|
apache-2.0
| 8,436 | 0.000119 |
import os
import pickle
import numpy as np
from tqdm import tqdm
class SumTree:
def __init__(self, capacity):
self.capacity = capacity
self.tree = np.zeros(2 * capacity - 1, dtype=np.float32)
self.data = np.empty(capacity, dtype=object)
self.head = 0
@property
def total_priority(self):
return self.tree[0]
@property
def max_priority(self):
return np.max(self.tree[-self.capacity:])
@property
def min_priority(self):
return np.min(self.tree[-self.capacity:])
def _tree_to_data_index(self, i):
return i - self.capacity + 1
def _data_to_tree_index(self, i):
return i + self.capacity - 1
def add(self, priority, data):
tree_index = self._data_to_tree_index(self.head)
self.update_priority(tree_index, priority)
self.data[self.head] = data
self.head += 1
if self.head >= self.capacity:
self.head = 0
def update_priority(self, tree_index, priority):
delta = priority - self.tree[tree_index]
self.tree[tree_index] = priority
while tree_index != 0:
tree_index = (tree_index - 1) // 2
self.tree[tree_index] += delta
def get_leaf(self, value):
parent = 0
while True:
left = 2 * parent + 1
right = left + 1
if left >= len(self.tree):
leaf = parent
break
else:
if value <= self.tree[left]:
parent = left
else:
value -= self.tree[left]
parent = right
data_index = self._tree_to_data_index(leaf)
return leaf, self.tree[leaf], self.data[data_index]
class PrioritizedExperienceReplay:
def __init__(self, capacity, initial_size, epsilon, alpha, beta, beta_annealing_rate, max_td_error, ckpt_dir):
self.tree = SumTree(capacity)
self.capacity = capacity
self.epsilon = epsilon
self.initial_size = initial_size
self.alpha = alpha
self.beta = beta
self.beta_annealing_rate = beta_annealing_rate
self.max_td_error = max_td_error
self.ckpt_dir = ckpt_dir
def add(self, transition):
max_priority = self.tree.max_priority
if max_priority == 0:
max_priority = self.max_td_error
self.tree.add(max_priority, transition)
def sample(self, batch_size):
self.beta = np.min([1., self.beta + self.beta_annealing_rate])
priority_segment = self.tree.total_priority / batch_size
min_probability = self.tree.min_priority / self.tree.total_priority
max_weight = (min_probability * batch_size) ** (-self.beta)
samples, sample_indices, importance_sampling_weights = [], [], []
for i in range(batch_size):
value = np.random.uniform(priority_segment * i, priority_segment * (i + 1))
index, priority, transition = self.tree.get_leaf(value)
sample_probability = priority / self.tree.total_priority
importance_sampling_weights.append(((batch_size * sample_probability) ** -self.beta) / max_weight)
sample_indices.append(index)
samples.append(transition)
return sample_indices, samples, importance_sampling_weights
def update_priorities(self, tree_indices, td_errors):
td_errors += self.epsilon
clipped_errors = np.minimum(td_errors, self.max_td_error)
priorities = clipped_errors ** self.alpha
for tree_index, priority in zip(tree_indices, priorities):
self.tree.update_priority(tree_index, priority)
def load_or_instantiate(self, env):
if os.path.exists(os.path.join(self.ckpt_dir, "memory.pkl")):
self.load()
return
state = env.reset()
for _ in tqdm(range(self.initial_size), desc="Initializing replay memory", unit="transition"):
action = env.action_space.sample()
next_state, reward, done, info = env.step(action)
transition = (state, action, reward, next_state, done)
self.add(transition)
state = next_state
if done:
state = env.reset()
def load(self):
with open(os.path.join(self.ckpt_dir, "memory.pkl"), "rb") as f:
self.tree = pickle.load(f)
def save(self):
with open(os.path.join(self.ckpt_dir, "memory.pkl"), "wb") as f:
pickle.dump(self.tree, f)
|
akshaykurmi/reinforcement-learning
|
atari_breakout/per.py
|
Python
|
mit
| 4,539 | 0.000881 |
# SPDX-License-Identifier: Apache-2.0
# Copyright Contributors to the Rez Project
"""
Get a list of a package's plugins.
"""
from __future__ import print_function
def setup_parser(parser, completions=False):
parser.add_argument(
"--paths", type=str, default=None,
help="set package search path")
PKG_action = parser.add_argument(
"PKG", type=str,
help="package to list plugins for")
if completions:
from rez.cli._complete_util import PackageFamilyCompleter
PKG_action.completer = PackageFamilyCompleter
def command(opts, parser, extra_arg_groups=None):
from rez.package_search import get_plugins
from rez.config import config
import os
import os.path
import sys
config.override("warn_none", True)
if opts.paths is None:
pkg_paths = None
else:
pkg_paths = opts.paths.split(os.pathsep)
pkg_paths = [os.path.expanduser(x) for x in pkg_paths if x]
pkgs_list = get_plugins(package_name=opts.PKG, paths=pkg_paths)
if pkgs_list:
print('\n'.join(pkgs_list))
else:
print("package '%s' has no plugins." % opts.PKG, file=sys.stderr)
|
instinct-vfx/rez
|
src/rez/cli/plugins.py
|
Python
|
apache-2.0
| 1,176 | 0 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Tests for the file entry implementation using pyfsapfs."""
import unittest
from dfvfs.lib import definitions
from dfvfs.path import factory as path_spec_factory
from dfvfs.resolver import context
from dfvfs.resolver import resolver
from dfvfs.vfs import apfs_attribute
from dfvfs.vfs import apfs_file_entry
from dfvfs.vfs import apfs_file_system
from tests import test_lib as shared_test_lib
class APFSFileEntryTest(shared_test_lib.BaseTestCase):
"""Tests the APFS file entry."""
# pylint: disable=protected-access
_IDENTIFIER_A_DIRECTORY = 16
_IDENTIFIER_A_FILE = 17
_IDENTIFIER_A_LINK = 20
_IDENTIFIER_ANOTHER_FILE = 19
def setUp(self):
"""Sets up the needed objects used throughout the test."""
self._resolver_context = context.Context()
test_path = self._GetTestFilePath(['apfs.raw'])
self._SkipIfPathNotExists(test_path)
test_os_path_spec = path_spec_factory.Factory.NewPathSpec(
definitions.TYPE_INDICATOR_OS, location=test_path)
test_raw_path_spec = path_spec_factory.Factory.NewPathSpec(
definitions.TYPE_INDICATOR_RAW, parent=test_os_path_spec)
self._apfs_container_path_spec = path_spec_factory.Factory.NewPathSpec(
definitions.TYPE_INDICATOR_APFS_CONTAINER, location='/apfs1',
parent=test_raw_path_spec)
self._apfs_path_spec = path_spec_factory.Factory.NewPathSpec(
definitions.TYPE_INDICATOR_APFS, location='/',
parent=self._apfs_container_path_spec)
self._file_system = apfs_file_system.APFSFileSystem(
self._resolver_context, self._apfs_path_spec)
self._file_system.Open()
def tearDown(self):
"""Cleans up the needed objects used throughout the test."""
self._resolver_context.Empty()
def testInitialize(self):
"""Tests the __init__ function."""
file_entry = apfs_file_entry.APFSFileEntry(
self._resolver_context, self._file_system, self._apfs_path_spec)
self.assertIsNotNone(file_entry)
# TODO: add tests for _GetDirectory
# TODO: add tests for _GetLink
# TODO: add tests for _GetStat
# TODO: add tests for _GetSubFileEntries
def testAccessTime(self):
"""Test the access_time property."""
path_spec = path_spec_factory.Factory.NewPathSpec(
definitions.TYPE_INDICATOR_APFS,
identifier=self._IDENTIFIER_ANOTHER_FILE,
location='/a_directory/another_file',
parent=self._apfs_container_path_spec)
file_entry = self._file_system.GetFileEntryByPathSpec(path_spec)
self.assertIsNotNone(file_entry)
self.assertIsNotNone(file_entry.access_time)
def testAddedTime(self):
"""Test the added_time property."""
path_spec = path_spec_factory.Factory.NewPathSpec(
definitions.TYPE_INDICATOR_APFS,
identifier=self._IDENTIFIER_ANOTHER_FILE,
location='/a_directory/another_file',
parent=self._apfs_container_path_spec)
file_entry = self._file_system.GetFileEntryByPathSpec(path_spec)
self.assertIsNotNone(file_entry)
self.assertIsNotNone(file_entry.added_time)
def testChangeTime(self):
"""Test the change_time property."""
path_spec = path_spec_factory.Factory.NewPathSpec(
definitions.TYPE_INDICATOR_APFS,
identifier=self._IDENTIFIER_ANOTHER_FILE,
location='/a_directory/another_file',
parent=self._apfs_container_path_spec)
file_entry = self._file_system.GetFileEntryByPathSpec(path_spec)
self.assertIsNotNone(file_entry)
self.assertIsNotNone(file_entry.change_time)
def testCreationTime(self):
"""Test the creation_time property."""
path_spec = path_spec_factory.Factory.NewPathSpec(
definitions.TYPE_INDICATOR_APFS,
identifier=self._IDENTIFIER_ANOTHER_FILE,
location='/a_directory/another_file',
parent=self._apfs_container_path_spec)
file_entry = self._file_system.GetFileEntryByPathSpec(path_spec)
self.assertIsNotNone(file_entry)
self.assertIsNotNone(file_entry.creation_time)
def testModificationTime(self):
"""Test the modification_time property."""
path_spec = path_spec_factory.Factory.NewPathSpec(
definitions.TYPE_INDICATOR_APFS,
identifier=self._IDENTIFIER_ANOTHER_FILE,
location='/a_directory/another_file',
parent=self._apfs_container_path_spec)
file_entry = self._file_system.GetFileEntryByPathSpec(path_spec)
self.assertIsNotNone(file_entry)
self.assertIsNotNone(file_entry.modification_time)
def testName(self):
"""Test the name property."""
path_spec = path_spec_factory.Factory.NewPathSpec(
definitions.TYPE_INDICATOR_APFS,
identifier=self._IDENTIFIER_ANOTHER_FILE,
location='/a_directory/another_file',
parent=self._apfs_container_path_spec)
file_entry = self._file_system.GetFileEntryByPathSpec(path_spec)
self.assertIsNotNone(file_entry)
self.assertEqual(file_entry.name, 'another_file')
def testSize(self):
"""Test the size property."""
path_spec = path_spec_factory.Factory.NewPathSpec(
definitions.TYPE_INDICATOR_APFS,
identifier=self._IDENTIFIER_ANOTHER_FILE,
location='/a_directory/another_file',
parent=self._apfs_container_path_spec)
file_entry = self._file_system.GetFileEntryByPathSpec(path_spec)
self.assertIsNotNone(file_entry)
self.assertEqual(file_entry.size, 22)
def testGetAttributes(self):
"""Tests the _GetAttributes function."""
path_spec = path_spec_factory.Factory.NewPathSpec(
definitions.TYPE_INDICATOR_APFS, identifier=self._IDENTIFIER_A_FILE,
location='/a_directory/a_file', parent=self._apfs_container_path_spec)
file_entry = self._file_system.GetFileEntryByPathSpec(path_spec)
self.assertIsNotNone(file_entry)
self.assertIsNone(file_entry._attributes)
file_entry._GetAttributes()
self.assertIsNotNone(file_entry._attributes)
self.assertEqual(len(file_entry._attributes), 1)
test_attribute = file_entry._attributes[0]
self.assertIsInstance(test_attribute, apfs_attribute.APFSExtendedAttribute)
self.assertEqual(test_attribute.name, 'myxattr')
test_attribute_value_data = test_attribute.read()
self.assertEqual(test_attribute_value_data, b'My extended attribute')
def testGetStat(self):
"""Tests the _GetStat function."""
path_spec = path_spec_factory.Factory.NewPathSpec(
definitions.TYPE_INDICATOR_APFS,
identifier=self._IDENTIFIER_ANOTHER_FILE,
location='/a_directory/another_file',
parent=self._apfs_container_path_spec)
file_entry = self._file_system.GetFileEntryByPathSpec(path_spec)
self.assertIsNotNone(file_entry)
stat_object = file_entry._GetStat()
self.assertIsNotNone(stat_object)
self.assertEqual(stat_object.type, stat_object.TYPE_FILE)
self.assertEqual(stat_object.size, 22)
self.assertEqual(stat_object.mode, 420)
self.assertEqual(stat_object.uid, 99)
self.assertEqual(stat_object.gid, 99)
self.assertEqual(stat_object.atime, 1642144781)
self.assertEqual(stat_object.atime_nano, 2174301)
self.assertEqual(stat_object.ctime, 1642144781)
self.assertEqual(stat_object.ctime_nano, 2206372)
self.assertEqual(stat_object.crtime, 1642144781)
self.assertEqual(stat_object.crtime_nano, 2206372)
self.assertEqual(stat_object.mtime, 1642144781)
self.assertEqual(stat_object.mtime_nano, 2174301)
def testGetStatAttribute(self):
"""Tests the _GetStatAttribute function."""
path_spec = path_spec_factory.Factory.NewPathSpec(
definitions.TYPE_INDICATOR_HFS,
identifier=self._IDENTIFIER_ANOTHER_FILE,
location='/a_directory/another_file',
parent=self._apfs_container_path_spec)
file_entry = self._file_system.GetFileEntryByPathSpec(path_spec)
self.assertIsNotNone(file_entry)
stat_attribute = file_entry._GetStatAttribute()
self.assertIsNotNone(stat_attribute)
self.assertEqual(stat_attribute.group_identifier, 99)
self.assertEqual(stat_attribute.inode_number, 19)
self.assertEqual(stat_attribute.mode, 0o100644)
# TODO: implement number of hard links support in pyfshfs
# self.assertEqual(stat_attribute.number_of_links, 1)
self.assertEqual(stat_attribute.owner_identifier, 99)
self.assertEqual(stat_attribute.size, 22)
self.assertEqual(stat_attribute.type, stat_attribute.TYPE_FILE)
def testGetAPFSFileEntry(self):
"""Tests the GetAPFSFileEntry function."""
path_spec = path_spec_factory.Factory.NewPathSpec(
definitions.TYPE_INDICATOR_APFS,
identifier=self._IDENTIFIER_ANOTHER_FILE,
location='/a_directory/another_file',
parent=self._apfs_container_path_spec)
file_entry = self._file_system.GetFileEntryByPathSpec(path_spec)
self.assertIsNotNone(file_entry)
fsafps_file_entry = file_entry.GetAPFSFileEntry()
self.assertIsNotNone(fsafps_file_entry)
def testGetExtents(self):
"""Tests the GetExtents function."""
path_spec = path_spec_factory.Factory.NewPathSpec(
definitions.TYPE_INDICATOR_APFS,
identifier=self._IDENTIFIER_ANOTHER_FILE,
location='/a_directory/another_file',
parent=self._apfs_container_path_spec)
file_entry = self._file_system.GetFileEntryByPathSpec(path_spec)
self.assertIsNotNone(file_entry)
extents = file_entry.GetExtents()
self.assertEqual(len(extents), 1)
self.assertEqual(extents[0].extent_type, definitions.EXTENT_TYPE_DATA)
self.assertEqual(extents[0].offset, 393216)
self.assertEqual(extents[0].size, 4096)
path_spec = path_spec_factory.Factory.NewPathSpec(
definitions.TYPE_INDICATOR_APFS,
identifier=self._IDENTIFIER_A_DIRECTORY, location='/a_directory',
parent=self._apfs_container_path_spec)
file_entry = self._file_system.GetFileEntryByPathSpec(path_spec)
self.assertIsNotNone(file_entry)
extents = file_entry.GetExtents()
self.assertEqual(len(extents), 0)
def testGetFileEntryByPathSpec(self):
"""Tests the GetFileEntryByPathSpec function."""
path_spec = path_spec_factory.Factory.NewPathSpec(
definitions.TYPE_INDICATOR_APFS,
identifier=self._IDENTIFIER_A_FILE,
parent=self._apfs_container_path_spec)
file_entry = self._file_system.GetFileEntryByPathSpec(path_spec)
self.assertIsNotNone(file_entry)
def testGetLinkedFileEntry(self):
"""Tests the GetLinkedFileEntry function."""
path_spec = path_spec_factory.Factory.NewPathSpec(
definitions.TYPE_INDICATOR_APFS,
identifier=self._IDENTIFIER_A_LINK, location='/a_link',
parent=self._apfs_container_path_spec)
file_entry = self._file_system.GetFileEntryByPathSpec(path_spec)
self.assertIsNotNone(file_entry)
linked_file_entry = file_entry.GetLinkedFileEntry()
self.assertIsNotNone(linked_file_entry)
self.assertEqual(linked_file_entry.name, 'another_file')
def testGetParentFileEntry(self):
"""Tests the GetParentFileEntry function."""
path_spec = path_spec_factory.Factory.NewPathSpec(
definitions.TYPE_INDICATOR_APFS,
identifier=self._IDENTIFIER_ANOTHER_FILE,
location='/a_directory/another_file',
parent=self._apfs_container_path_spec)
file_entry = self._file_system.GetFileEntryByPathSpec(path_spec)
self.assertIsNotNone(file_entry)
parent_file_entry = file_entry.GetParentFileEntry()
self.assertIsNotNone(parent_file_entry)
self.assertEqual(parent_file_entry.name, 'a_directory')
def testIsFunctions(self):
"""Tests the Is? functions."""
path_spec = path_spec_factory.Factory.NewPathSpec(
definitions.TYPE_INDICATOR_APFS,
identifier=self._IDENTIFIER_ANOTHER_FILE,
location='/a_directory/another_file',
parent=self._apfs_container_path_spec)
file_entry = self._file_system.GetFileEntryByPathSpec(path_spec)
self.assertIsNotNone(file_entry)
self.assertFalse(file_entry.IsRoot())
self.assertFalse(file_entry.IsVirtual())
self.assertTrue(file_entry.IsAllocated())
self.assertFalse(file_entry.IsDevice())
self.assertFalse(file_entry.IsDirectory())
self.assertTrue(file_entry.IsFile())
self.assertFalse(file_entry.IsLink())
self.assertFalse(file_entry.IsPipe())
self.assertFalse(file_entry.IsSocket())
path_spec = path_spec_factory.Factory.NewPathSpec(
definitions.TYPE_INDICATOR_APFS,
identifier=self._IDENTIFIER_A_DIRECTORY, location='/a_directory',
parent=self._apfs_container_path_spec)
file_entry = self._file_system.GetFileEntryByPathSpec(path_spec)
self.assertIsNotNone(file_entry)
self.assertFalse(file_entry.IsRoot())
self.assertFalse(file_entry.IsVirtual())
self.assertTrue(file_entry.IsAllocated())
self.assertFalse(file_entry.IsDevice())
self.assertTrue(file_entry.IsDirectory())
self.assertFalse(file_entry.IsFile())
self.assertFalse(file_entry.IsLink())
self.assertFalse(file_entry.IsPipe())
self.assertFalse(file_entry.IsSocket())
path_spec = path_spec_factory.Factory.NewPathSpec(
definitions.TYPE_INDICATOR_APFS, location='/',
parent=self._apfs_container_path_spec)
file_entry = self._file_system.GetFileEntryByPathSpec(path_spec)
self.assertIsNotNone(file_entry)
self.assertTrue(file_entry.IsRoot())
self.assertFalse(file_entry.IsVirtual())
self.assertTrue(file_entry.IsAllocated())
self.assertFalse(file_entry.IsDevice())
self.assertTrue(file_entry.IsDirectory())
self.assertFalse(file_entry.IsFile())
self.assertFalse(file_entry.IsLink())
self.assertFalse(file_entry.IsPipe())
self.assertFalse(file_entry.IsSocket())
def testSubFileEntries(self):
"""Tests the number_of_sub_file_entries and sub_file_entries properties."""
path_spec = path_spec_factory.Factory.NewPathSpec(
definitions.TYPE_INDICATOR_APFS, location='/',
parent=self._apfs_container_path_spec)
file_entry = self._file_system.GetFileEntryByPathSpec(path_spec)
self.assertIsNotNone(file_entry)
self.assertEqual(file_entry.number_of_sub_file_entries, 4)
expected_sub_file_entry_names = [
'.fseventsd',
'a_directory',
'a_link',
'passwords.txt']
sub_file_entry_names = []
for sub_file_entry in file_entry.sub_file_entries:
sub_file_entry_names.append(sub_file_entry.name)
self.assertEqual(
len(sub_file_entry_names), len(expected_sub_file_entry_names))
self.assertEqual(
sorted(sub_file_entry_names), sorted(expected_sub_file_entry_names))
# Test a path specification without a location.
path_spec = path_spec_factory.Factory.NewPathSpec(
definitions.TYPE_INDICATOR_APFS,
identifier=self._IDENTIFIER_A_DIRECTORY,
parent=self._apfs_container_path_spec)
file_entry = self._file_system.GetFileEntryByPathSpec(path_spec)
self.assertIsNotNone(file_entry)
self.assertEqual(file_entry.number_of_sub_file_entries, 3)
def testDataStreams(self):
"""Tests the data streams functionality."""
path_spec = path_spec_factory.Factory.NewPathSpec(
definitions.TYPE_INDICATOR_APFS,
identifier=self._IDENTIFIER_ANOTHER_FILE,
location='/a_directory/another_file',
parent=self._apfs_container_path_spec)
file_entry = self._file_system.GetFileEntryByPathSpec(path_spec)
self.assertIsNotNone(file_entry)
self.assertEqual(file_entry.number_of_data_streams, 1)
data_stream_names = []
for data_stream in file_entry.data_streams:
data_stream_names.append(data_stream.name)
self.assertEqual(data_stream_names, [''])
path_spec = path_spec_factory.Factory.NewPathSpec(
definitions.TYPE_INDICATOR_APFS,
identifier=self._IDENTIFIER_A_DIRECTORY, location='/a_directory',
parent=self._apfs_container_path_spec)
file_entry = self._file_system.GetFileEntryByPathSpec(path_spec)
self.assertIsNotNone(file_entry)
self.assertEqual(file_entry.number_of_data_streams, 0)
data_stream_names = []
for data_stream in file_entry.data_streams:
data_stream_names.append(data_stream.name)
self.assertEqual(data_stream_names, [])
def testGetDataStream(self):
"""Tests the GetDataStream function."""
path_spec = path_spec_factory.Factory.NewPathSpec(
definitions.TYPE_INDICATOR_APFS,
identifier=self._IDENTIFIER_ANOTHER_FILE,
location='/a_directory/another_file',
parent=self._apfs_container_path_spec)
file_entry = self._file_system.GetFileEntryByPathSpec(path_spec)
self.assertIsNotNone(file_entry)
data_stream_name = ''
data_stream = file_entry.GetDataStream(data_stream_name)
self.assertIsNotNone(data_stream)
class APFSFileEntryTestEncrypted(shared_test_lib.BaseTestCase):
"""Tests the APFS file entry on an encrypted file system."""
_APFS_PASSWORD = 'apfs-TEST'
_IDENTIFIER_A_DIRECTORY = 18
_IDENTIFIER_A_LINK = 22
_IDENTIFIER_ANOTHER_FILE = 21
def setUp(self):
"""Sets up the needed objects used throughout the test."""
self._resolver_context = context.Context()
test_path = self._GetTestFilePath(['apfs_encrypted.dmg'])
self._SkipIfPathNotExists(test_path)
test_os_path_spec = path_spec_factory.Factory.NewPathSpec(
definitions.TYPE_INDICATOR_OS, location=test_path)
test_raw_path_spec = path_spec_factory.Factory.NewPathSpec(
definitions.TYPE_INDICATOR_RAW, parent=test_os_path_spec)
test_gpt_path_spec = path_spec_factory.Factory.NewPathSpec(
definitions.TYPE_INDICATOR_GPT, location='/p1',
parent=test_raw_path_spec)
self._apfs_container_path_spec = path_spec_factory.Factory.NewPathSpec(
definitions.TYPE_INDICATOR_APFS_CONTAINER, location='/apfs1',
parent=test_gpt_path_spec)
self._apfs_path_spec = path_spec_factory.Factory.NewPathSpec(
definitions.TYPE_INDICATOR_APFS, location='/',
parent=self._apfs_container_path_spec)
resolver.Resolver.key_chain.SetCredential(
self._apfs_container_path_spec, 'password', self._APFS_PASSWORD)
self._file_system = apfs_file_system.APFSFileSystem(
self._resolver_context, self._apfs_path_spec)
self._file_system.Open()
def tearDown(self):
"""Cleans up the needed objects used throughout the test."""
self._resolver_context.Empty()
def testInitialize(self):
"""Tests the __init__ function."""
file_entry = apfs_file_entry.APFSFileEntry(
self._resolver_context, self._file_system, self._apfs_path_spec)
self.assertIsNotNone(file_entry)
# TODO: add tests for _GetDirectory
# TODO: add tests for _GetLink
# TODO: add tests for _GetStat
# TODO: add tests for _GetSubFileEntries
def testAccessTime(self):
"""Test the access_time property."""
path_spec = path_spec_factory.Factory.NewPathSpec(
definitions.TYPE_INDICATOR_APFS,
identifier=self._IDENTIFIER_ANOTHER_FILE,
location='/a_directory/another_file',
parent=self._apfs_container_path_spec)
file_entry = self._file_system.GetFileEntryByPathSpec(path_spec)
self.assertIsNotNone(file_entry)
self.assertIsNotNone(file_entry.access_time)
def testChangeTime(self):
"""Test the change_time property."""
path_spec = path_spec_factory.Factory.NewPathSpec(
definitions.TYPE_INDICATOR_APFS,
identifier=self._IDENTIFIER_ANOTHER_FILE,
location='/a_directory/another_file',
parent=self._apfs_container_path_spec)
file_entry = self._file_system.GetFileEntryByPathSpec(path_spec)
self.assertIsNotNone(file_entry)
self.assertIsNotNone(file_entry.change_time)
def testCreationTime(self):
"""Test the creation_time property."""
path_spec = path_spec_factory.Factory.NewPathSpec(
definitions.TYPE_INDICATOR_APFS,
identifier=self._IDENTIFIER_ANOTHER_FILE,
location='/a_directory/another_file',
parent=self._apfs_container_path_spec)
file_entry = self._file_system.GetFileEntryByPathSpec(path_spec)
self.assertIsNotNone(file_entry)
self.assertIsNotNone(file_entry.creation_time)
def testModificationTime(self):
"""Test the modification_time property."""
path_spec = path_spec_factory.Factory.NewPathSpec(
definitions.TYPE_INDICATOR_APFS,
identifier=self._IDENTIFIER_ANOTHER_FILE,
location='/a_directory/another_file',
parent=self._apfs_container_path_spec)
file_entry = self._file_system.GetFileEntryByPathSpec(path_spec)
self.assertIsNotNone(file_entry)
self.assertIsNotNone(file_entry.modification_time)
def testName(self):
"""Test the name property."""
path_spec = path_spec_factory.Factory.NewPathSpec(
definitions.TYPE_INDICATOR_APFS,
identifier=self._IDENTIFIER_ANOTHER_FILE,
location='/a_directory/another_file',
parent=self._apfs_container_path_spec)
file_entry = self._file_system.GetFileEntryByPathSpec(path_spec)
self.assertIsNotNone(file_entry)
self.assertEqual(file_entry.name, 'another_file')
def testSize(self):
"""Test the size property."""
path_spec = path_spec_factory.Factory.NewPathSpec(
definitions.TYPE_INDICATOR_APFS,
identifier=self._IDENTIFIER_ANOTHER_FILE,
location='/a_directory/another_file',
parent=self._apfs_container_path_spec)
file_entry = self._file_system.GetFileEntryByPathSpec(path_spec)
self.assertIsNotNone(file_entry)
self.assertEqual(file_entry.size, 22)
def testGetAPFSFileEntry(self):
"""Tests the GetAPFSFileEntry function."""
path_spec = path_spec_factory.Factory.NewPathSpec(
definitions.TYPE_INDICATOR_APFS,
identifier=self._IDENTIFIER_ANOTHER_FILE,
location='/a_directory/another_file',
parent=self._apfs_container_path_spec)
file_entry = self._file_system.GetFileEntryByPathSpec(path_spec)
self.assertIsNotNone(file_entry)
fsafps_file_entry = file_entry.GetAPFSFileEntry()
self.assertIsNotNone(fsafps_file_entry)
def testGetExtents(self):
"""Tests the GetExtents function."""
path_spec = path_spec_factory.Factory.NewPathSpec(
definitions.TYPE_INDICATOR_APFS,
identifier=self._IDENTIFIER_ANOTHER_FILE,
location='/a_directory/another_file',
parent=self._apfs_container_path_spec)
file_entry = self._file_system.GetFileEntryByPathSpec(path_spec)
self.assertIsNotNone(file_entry)
extents = file_entry.GetExtents()
self.assertEqual(len(extents), 1)
self.assertEqual(extents[0].extent_type, definitions.EXTENT_TYPE_DATA)
self.assertEqual(extents[0].offset, 495616)
self.assertEqual(extents[0].size, 4096)
path_spec = path_spec_factory.Factory.NewPathSpec(
definitions.TYPE_INDICATOR_APFS,
identifier=self._IDENTIFIER_A_DIRECTORY, location='/a_directory',
parent=self._apfs_container_path_spec)
file_entry = self._file_system.GetFileEntryByPathSpec(path_spec)
self.assertIsNotNone(file_entry)
extents = file_entry.GetExtents()
self.assertEqual(len(extents), 0)
def testGetFileEntryByPathSpec(self):
"""Tests the GetFileEntryByPathSpec function."""
path_spec = path_spec_factory.Factory.NewPathSpec(
definitions.TYPE_INDICATOR_APFS, identifier=20,
parent=self._apfs_container_path_spec)
file_entry = self._file_system.GetFileEntryByPathSpec(path_spec)
self.assertIsNotNone(file_entry)
def testGetLinkedFileEntry(self):
"""Tests the GetLinkedFileEntry function."""
path_spec = path_spec_factory.Factory.NewPathSpec(
definitions.TYPE_INDICATOR_APFS, identifier=self._IDENTIFIER_A_LINK,
location='/a_link', parent=self._apfs_container_path_spec)
file_entry = self._file_system.GetFileEntryByPathSpec(path_spec)
self.assertIsNotNone(file_entry)
linked_file_entry = file_entry.GetLinkedFileEntry()
self.assertIsNotNone(linked_file_entry)
self.assertEqual(linked_file_entry.name, 'a_file')
def testGetParentFileEntry(self):
"""Tests the GetParentFileEntry function."""
path_spec = path_spec_factory.Factory.NewPathSpec(
definitions.TYPE_INDICATOR_APFS,
identifier=self._IDENTIFIER_ANOTHER_FILE,
location='/a_directory/another_file',
parent=self._apfs_container_path_spec)
file_entry = self._file_system.GetFileEntryByPathSpec(path_spec)
self.assertIsNotNone(file_entry)
parent_file_entry = file_entry.GetParentFileEntry()
self.assertIsNotNone(parent_file_entry)
self.assertEqual(parent_file_entry.name, 'a_directory')
def testGetStat(self):
"""Tests the GetStat function."""
path_spec = path_spec_factory.Factory.NewPathSpec(
definitions.TYPE_INDICATOR_APFS,
identifier=self._IDENTIFIER_ANOTHER_FILE,
location='/a_directory/another_file',
parent=self._apfs_container_path_spec)
file_entry = self._file_system.GetFileEntryByPathSpec(path_spec)
self.assertIsNotNone(file_entry)
stat_object = file_entry.GetStat()
self.assertIsNotNone(stat_object)
self.assertEqual(stat_object.type, stat_object.TYPE_FILE)
self.assertEqual(stat_object.size, 22)
self.assertEqual(stat_object.mode, 420)
self.assertEqual(stat_object.uid, 99)
self.assertEqual(stat_object.gid, 99)
self.assertEqual(stat_object.atime, 1539321508)
self.assertEqual(stat_object.atime_nano, 9478457)
self.assertEqual(stat_object.ctime, 1539321508)
self.assertEqual(stat_object.ctime_nano, 9495127)
self.assertEqual(stat_object.crtime, 1539321508)
self.assertEqual(stat_object.crtime_nano, 9495127)
self.assertEqual(stat_object.mtime, 1539321508)
self.assertEqual(stat_object.mtime_nano, 9478457)
def testIsFunctions(self):
"""Tests the Is? functions."""
path_spec = path_spec_factory.Factory.NewPathSpec(
definitions.TYPE_INDICATOR_APFS,
identifier=self._IDENTIFIER_ANOTHER_FILE,
location='/a_directory/another_file',
parent=self._apfs_container_path_spec)
file_entry = self._file_system.GetFileEntryByPathSpec(path_spec)
self.assertIsNotNone(file_entry)
self.assertFalse(file_entry.IsRoot())
self.assertFalse(file_entry.IsVirtual())
self.assertTrue(file_entry.IsAllocated())
self.assertFalse(file_entry.IsDevice())
self.assertFalse(file_entry.IsDirectory())
self.assertTrue(file_entry.IsFile())
self.assertFalse(file_entry.IsLink())
self.assertFalse(file_entry.IsPipe())
self.assertFalse(file_entry.IsSocket())
path_spec = path_spec_factory.Factory.NewPathSpec(
definitions.TYPE_INDICATOR_APFS,
identifier=self._IDENTIFIER_A_DIRECTORY, location='/a_directory',
parent=self._apfs_container_path_spec)
file_entry = self._file_system.GetFileEntryByPathSpec(path_spec)
self.assertIsNotNone(file_entry)
self.assertFalse(file_entry.IsRoot())
self.assertFalse(file_entry.IsVirtual())
self.assertTrue(file_entry.IsAllocated())
self.assertFalse(file_entry.IsDevice())
self.assertTrue(file_entry.IsDirectory())
self.assertFalse(file_entry.IsFile())
self.assertFalse(file_entry.IsLink())
self.assertFalse(file_entry.IsPipe())
self.assertFalse(file_entry.IsSocket())
path_spec = path_spec_factory.Factory.NewPathSpec(
definitions.TYPE_INDICATOR_APFS, location='/',
parent=self._apfs_container_path_spec)
file_entry = self._file_system.GetFileEntryByPathSpec(path_spec)
self.assertIsNotNone(file_entry)
self.assertTrue(file_entry.IsRoot())
self.assertFalse(file_entry.IsVirtual())
self.assertTrue(file_entry.IsAllocated())
self.assertFalse(file_entry.IsDevice())
self.assertTrue(file_entry.IsDirectory())
self.assertFalse(file_entry.IsFile())
self.assertFalse(file_entry.IsLink())
self.assertFalse(file_entry.IsPipe())
self.assertFalse(file_entry.IsSocket())
def testSubFileEntries(self):
"""Tests the number_of_sub_file_entries and sub_file_entries properties."""
path_spec = path_spec_factory.Factory.NewPathSpec(
definitions.TYPE_INDICATOR_APFS, location='/',
parent=self._apfs_container_path_spec)
file_entry = self._file_system.GetFileEntryByPathSpec(path_spec)
self.assertIsNotNone(file_entry)
self.assertEqual(file_entry.number_of_sub_file_entries, 4)
expected_sub_file_entry_names = [
'.fseventsd',
'a_directory',
'a_link',
'passwords.txt']
sub_file_entry_names = []
for sub_file_entry in file_entry.sub_file_entries:
sub_file_entry_names.append(sub_file_entry.name)
self.assertEqual(
len(sub_file_entry_names), len(expected_sub_file_entry_names))
self.assertEqual(
sorted(sub_file_entry_names), sorted(expected_sub_file_entry_names))
def testDataStreams(self):
"""Tests the data streams functionality."""
path_spec = path_spec_factory.Factory.NewPathSpec(
definitions.TYPE_INDICATOR_APFS,
identifier=self._IDENTIFIER_ANOTHER_FILE,
location='/a_directory/another_file',
parent=self._apfs_container_path_spec)
file_entry = self._file_system.GetFileEntryByPathSpec(path_spec)
self.assertIsNotNone(file_entry)
self.assertEqual(file_entry.number_of_data_streams, 1)
data_stream_names = []
for data_stream in file_entry.data_streams:
data_stream_names.append(data_stream.name)
self.assertEqual(data_stream_names, [''])
path_spec = path_spec_factory.Factory.NewPathSpec(
definitions.TYPE_INDICATOR_APFS,
identifier=self._IDENTIFIER_A_DIRECTORY, location='/a_directory',
parent=self._apfs_container_path_spec)
file_entry = self._file_system.GetFileEntryByPathSpec(path_spec)
self.assertIsNotNone(file_entry)
self.assertEqual(file_entry.number_of_data_streams, 0)
data_stream_names = []
for data_stream in file_entry.data_streams:
data_stream_names.append(data_stream.name)
self.assertEqual(data_stream_names, [])
def testGetDataStream(self):
"""Tests the GetDataStream function."""
path_spec = path_spec_factory.Factory.NewPathSpec(
definitions.TYPE_INDICATOR_APFS,
identifier=self._IDENTIFIER_ANOTHER_FILE,
location='/a_directory/another_file',
parent=self._apfs_container_path_spec)
file_entry = self._file_system.GetFileEntryByPathSpec(path_spec)
self.assertIsNotNone(file_entry)
data_stream_name = ''
data_stream = file_entry.GetDataStream(data_stream_name)
self.assertIsNotNone(data_stream)
if __name__ == '__main__':
unittest.main()
|
joachimmetz/dfvfs
|
tests/vfs/apfs_file_entry.py
|
Python
|
apache-2.0
| 30,722 | 0.002181 |
#
# ElementTree
# $Id: ElementTree.py 3440 2008-07-18 14:45:01Z fredrik $
#
# light-weight XML support for Python 2.3 and later.
#
# history (since 1.2.6):
# 2005-11-12 fl added tostringlist/fromstringlist helpers
# 2006-07-05 fl merged in selected changes from the 1.3 sandbox
# 2006-07-05 fl removed support for 2.1 and earlier
# 2007-06-21 fl added deprecation/future warnings
# 2007-08-25 fl added doctype hook, added parser version attribute etc
# 2007-08-26 fl added new serializer code (better namespace handling, etc)
# 2007-08-27 fl warn for broken /tag searches on tree level
# 2007-09-02 fl added html/text methods to serializer (experimental)
# 2007-09-05 fl added method argument to tostring/tostringlist
# 2007-09-06 fl improved error handling
# 2007-09-13 fl added itertext, iterfind; assorted cleanups
# 2007-12-15 fl added C14N hooks, copy method (experimental)
#
# Copyright (c) 1999-2008 by Fredrik Lundh. All rights reserved.
#
# fredrik@pythonware.com
# http://www.pythonware.com
#
# --------------------------------------------------------------------
# The ElementTree toolkit is
#
# Copyright (c) 1999-2008 by Fredrik Lundh
#
# By obtaining, using, and/or copying this software and/or its
# associated documentation, you agree that you have read, understood,
# and will comply with the following terms and conditions:
#
# Permission to use, copy, modify, and distribute this software and
# its associated documentation for any purpose and without fee is
# hereby granted, provided that the above copyright notice appears in
# all copies, and that both that copyright notice and this permission
# notice appear in supporting documentation, and that the name of
# Secret Labs AB or the author not be used in advertising or publicity
# pertaining to distribution of the software without specific, written
# prior permission.
#
# SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD
# TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANT-
# ABILITY AND FITNESS. IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR
# BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY
# DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
# WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
# ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
# OF THIS SOFTWARE.
# --------------------------------------------------------------------
# Licensed to PSF under a Contributor Agreement.
# See http://www.python.org/psf/license for licensing details.
__all__ = [
# public symbols
"Comment",
"dump",
"Element", "ElementTree",
"fromstring", "fromstringlist",
"iselement", "iterparse",
"parse", "ParseError",
"PI", "ProcessingInstruction",
"QName",
"SubElement",
"tostring", "tostringlist",
"TreeBuilder",
"VERSION",
"XML",
"XMLParser", "XMLTreeBuilder",
]
VERSION = "1.3.0"
##
# The <b>Element</b> type is a flexible container object, designed to
# store hierarchical data structures in memory. The type can be
# described as a cross between a list and a dictionary.
# <p>
# Each element has a number of properties associated with it:
# <ul>
# <li>a <i>tag</i>. This is a string identifying what kind of data
# this element represents (the element type, in other words).</li>
# <li>a number of <i>attributes</i>, stored in a Python dictionary.</li>
# <li>a <i>text</i> string.</li>
# <li>an optional <i>tail</i> string.</li>
# <li>a number of <i>child elements</i>, stored in a Python sequence</li>
# </ul>
#
# To create an element instance, use the {@link #Element} constructor
# or the {@link #SubElement} factory function.
# <p>
# The {@link #ElementTree} class can be used to wrap an element
# structure, and convert it from and to XML.
##
import sys
import re
import warnings
class _SimpleElementPath(object):
# emulate pre-1.2 find/findtext/findall behaviour
def find(self, element, tag, namespaces=None):
for elem in element:
if elem.tag == tag:
return elem
return None
def findtext(self, element, tag, default=None, namespaces=None):
elem = self.find(element, tag)
if elem is None:
return default
return elem.text or ""
def iterfind(self, element, tag, namespaces=None):
if tag[:3] == ".//":
for elem in element.iter(tag[3:]):
yield elem
for elem in element:
if elem.tag == tag:
yield elem
def findall(self, element, tag, namespaces=None):
return list(self.iterfind(element, tag, namespaces))
try:
from . import ElementPath
except ImportError:
ElementPath = _SimpleElementPath()
##
# Parser error. This is a subclass of <b>SyntaxError</b>.
# <p>
# In addition to the exception value, an exception instance contains a
# specific exception code in the <b>code</b> attribute, and the line and
# column of the error in the <b>position</b> attribute.
class ParseError(SyntaxError):
pass
# --------------------------------------------------------------------
##
# Checks if an object appears to be a valid element object.
#
# @param An element instance.
# @return A true value if this is an element object.
# @defreturn flag
def iselement(element):
# FIXME: not sure about this; might be a better idea to look
# for tag/attrib/text attributes
return isinstance(element, Element) or hasattr(element, "tag")
##
# Element class. This class defines the Element interface, and
# provides a reference implementation of this interface.
# <p>
# The element name, attribute names, and attribute values can be
# either ASCII strings (ordinary Python strings containing only 7-bit
# ASCII characters) or Unicode strings.
#
# @param tag The element name.
# @param attrib An optional dictionary, containing element attributes.
# @param **extra Additional attributes, given as keyword arguments.
# @see Element
# @see SubElement
# @see Comment
# @see ProcessingInstruction
class Element(object):
# <tag attrib>text<child/>...</tag>tail
##
# (Attribute) Element tag.
tag = None
##
# (Attribute) Element attribute dictionary. Where possible, use
# {@link #Element.get},
# {@link #Element.set},
# {@link #Element.keys}, and
# {@link #Element.items} to access
# element attributes.
attrib = None
##
# (Attribute) Text before first subelement. This is either a
# string or the value None. Note that if there was no text, this
# attribute may be either None or an empty string, depending on
# the parser.
text = None
##
# (Attribute) Text after this element's end tag, but before the
# next sibling element's start tag. This is either a string or
# the value None. Note that if there was no text, this attribute
# may be either None or an empty string, depending on the parser.
tail = None # text after end tag, if any
# constructor
def __init__(self, tag, attrib={}, **extra):
attrib = attrib.copy()
attrib.update(extra)
self.tag = tag
self.attrib = attrib
self._children = []
def __repr__(self):
return "<Element %s at 0x%x>" % (repr(self.tag), id(self))
##
# Creates a new element object of the same type as this element.
#
# @param tag Element tag.
# @param attrib Element attributes, given as a dictionary.
# @return A new element instance.
def makeelement(self, tag, attrib):
return self.__class__(tag, attrib)
##
# (Experimental) Copies the current element. This creates a
# shallow copy; subelements will be shared with the original tree.
#
# @return A new element instance.
def copy(self):
elem = self.makeelement(self.tag, self.attrib)
elem.text = self.text
elem.tail = self.tail
elem[:] = self
return elem
##
# Returns the number of subelements. Note that this only counts
# full elements; to check if there's any content in an element, you
# have to check both the length and the <b>text</b> attribute.
#
# @return The number of subelements.
def __len__(self):
return len(self._children)
def __nonzero__(self):
warnings.warn(
"The behavior of this method will change in future versions. "
"Use specific 'len(elem)' or 'elem is not None' test instead.",
FutureWarning, stacklevel=2
)
return len(self._children) != 0 # emulate old behaviour, for now
##
# Returns the given subelement, by index.
#
# @param index What subelement to return.
# @return The given subelement.
# @exception IndexError If the given element does not exist.
def __getitem__(self, index):
return self._children[index]
##
# Replaces the given subelement, by index.
#
# @param index What subelement to replace.
# @param element The new element value.
# @exception IndexError If the given element does not exist.
def __setitem__(self, index, element):
# if isinstance(index, slice):
# for elt in element:
# assert iselement(elt)
# else:
# assert iselement(element)
self._children[index] = element
##
# Deletes the given subelement, by index.
#
# @param index What subelement to delete.
# @exception IndexError If the given element does not exist.
def __delitem__(self, index):
del self._children[index]
##
# Adds a subelement to the end of this element. In document order,
# the new element will appear after the last existing subelement (or
# directly after the text, if it's the first subelement), but before
# the end tag for this element.
#
# @param element The element to add.
def append(self, element):
# assert iselement(element)
self._children.append(element)
##
# Appends subelements from a sequence.
#
# @param elements A sequence object with zero or more elements.
# @since 1.3
def extend(self, elements):
# for element in elements:
# assert iselement(element)
self._children.extend(elements)
##
# Inserts a subelement at the given position in this element.
#
# @param index Where to insert the new subelement.
def insert(self, index, element):
# assert iselement(element)
self._children.insert(index, element)
##
# Removes a matching subelement. Unlike the <b>find</b> methods,
# this method compares elements based on identity, not on tag
# value or contents. To remove subelements by other means, the
# easiest way is often to use a list comprehension to select what
# elements to keep, and use slice assignment to update the parent
# element.
#
# @param element What element to remove.
# @exception ValueError If a matching element could not be found.
def remove(self, element):
# assert iselement(element)
self._children.remove(element)
##
# (Deprecated) Returns all subelements. The elements are returned
# in document order.
#
# @return A list of subelements.
# @defreturn list of Element instances
def getchildren(self):
warnings.warn(
"This method will be removed in future versions. "
"Use 'list(elem)' or iteration over elem instead.",
DeprecationWarning, stacklevel=2
)
return self._children
##
# Finds the first matching subelement, by tag name or path.
#
# @param path What element to look for.
# @keyparam namespaces Optional namespace prefix map.
# @return The first matching element, or None if no element was found.
# @defreturn Element or None
def find(self, path, namespaces=None):
return ElementPath.find(self, path, namespaces)
##
# Finds text for the first matching subelement, by tag name or path.
#
# @param path What element to look for.
# @param default What to return if the element was not found.
# @keyparam namespaces Optional namespace prefix map.
# @return The text content of the first matching element, or the
# default value no element was found. Note that if the element
# is found, but has no text content, this method returns an
# empty string.
# @defreturn string
def findtext(self, path, default=None, namespaces=None):
return ElementPath.findtext(self, path, default, namespaces)
##
# Finds all matching subelements, by tag name or path.
#
# @param path What element to look for.
# @keyparam namespaces Optional namespace prefix map.
# @return A list or other sequence containing all matching elements,
# in document order.
# @defreturn list of Element instances
def findall(self, path, namespaces=None):
return ElementPath.findall(self, path, namespaces)
##
# Finds all matching subelements, by tag name or path.
#
# @param path What element to look for.
# @keyparam namespaces Optional namespace prefix map.
# @return An iterator or sequence containing all matching elements,
# in document order.
# @defreturn a generated sequence of Element instances
def iterfind(self, path, namespaces=None):
return ElementPath.iterfind(self, path, namespaces)
##
# Resets an element. This function removes all subelements, clears
# all attributes, and sets the <b>text</b> and <b>tail</b> attributes
# to None.
def clear(self):
self.attrib.clear()
self._children = []
self.text = self.tail = None
##
# Gets an element attribute. Equivalent to <b>attrib.get</b>, but
# some implementations may handle this a bit more efficiently.
#
# @param key What attribute to look for.
# @param default What to return if the attribute was not found.
# @return The attribute value, or the default value, if the
# attribute was not found.
# @defreturn string or None
def get(self, key, default=None):
return self.attrib.get(key, default)
##
# Sets an element attribute. Equivalent to <b>attrib[key] = value</b>,
# but some implementations may handle this a bit more efficiently.
#
# @param key What attribute to set.
# @param value The attribute value.
def set(self, key, value):
self.attrib[key] = value
##
# Gets a list of attribute names. The names are returned in an
# arbitrary order (just like for an ordinary Python dictionary).
# Equivalent to <b>attrib.keys()</b>.
#
# @return A list of element attribute names.
# @defreturn list of strings
def keys(self):
return self.attrib.keys()
##
# Gets element attributes, as a sequence. The attributes are
# returned in an arbitrary order. Equivalent to <b>attrib.items()</b>.
#
# @return A list of (name, value) tuples for all attributes.
# @defreturn list of (string, string) tuples
def items(self):
return self.attrib.items()
##
# Creates a tree iterator. The iterator loops over this element
# and all subelements, in document order, and returns all elements
# with a matching tag.
# <p>
# If the tree structure is modified during iteration, new or removed
# elements may or may not be included. To get a stable set, use the
# list() function on the iterator, and loop over the resulting list.
#
# @param tag What tags to look for (default is to return all elements).
# @return An iterator containing all the matching elements.
# @defreturn iterator
def iter(self, tag=None):
if tag == "*":
tag = None
if tag is None or self.tag == tag:
yield self
for e in self._children:
for e in e.iter(tag):
yield e
# compatibility
def getiterator(self, tag=None):
# Change for a DeprecationWarning in 1.4
warnings.warn(
"This method will be removed in future versions. "
"Use 'elem.iter()' or 'list(elem.iter())' instead.",
PendingDeprecationWarning, stacklevel=2
)
return list(self.iter(tag))
##
# Creates a text iterator. The iterator loops over this element
# and all subelements, in document order, and returns all inner
# text.
#
# @return An iterator containing all inner text.
# @defreturn iterator
def itertext(self):
tag = self.tag
if not isinstance(tag, basestring) and tag is not None:
return
if self.text:
yield self.text
for e in self:
for s in e.itertext():
yield s
if e.tail:
yield e.tail
# compatibility
_Element = _ElementInterface = Element
##
# Subelement factory. This function creates an element instance, and
# appends it to an existing element.
# <p>
# The element name, attribute names, and attribute values can be
# either 8-bit ASCII strings or Unicode strings.
#
# @param parent The parent element.
# @param tag The subelement name.
# @param attrib An optional dictionary, containing element attributes.
# @param **extra Additional attributes, given as keyword arguments.
# @return An element instance.
# @defreturn Element
def SubElement(parent, tag, attrib={}, **extra):
attrib = attrib.copy()
attrib.update(extra)
element = parent.makeelement(tag, attrib)
parent.append(element)
return element
##
# Comment element factory. This factory function creates a special
# element that will be serialized as an XML comment by the standard
# serializer.
# <p>
# The comment string can be either an 8-bit ASCII string or a Unicode
# string.
#
# @param text A string containing the comment string.
# @return An element instance, representing a comment.
# @defreturn Element
def Comment(text=None):
element = Element(Comment)
element.text = text
return element
##
# PI element factory. This factory function creates a special element
# that will be serialized as an XML processing instruction by the standard
# serializer.
#
# @param target A string containing the PI target.
# @param text A string containing the PI contents, if any.
# @return An element instance, representing a PI.
# @defreturn Element
def ProcessingInstruction(target, text=None):
element = Element(ProcessingInstruction)
element.text = target
if text:
element.text = element.text + " " + text
return element
PI = ProcessingInstruction
##
# QName wrapper. This can be used to wrap a QName attribute value, in
# order to get proper namespace handling on output.
#
# @param text A string containing the QName value, in the form {uri}local,
# or, if the tag argument is given, the URI part of a QName.
# @param tag Optional tag. If given, the first argument is interpreted as
# an URI, and this argument is interpreted as a local name.
# @return An opaque object, representing the QName.
class QName(object):
def __init__(self, text_or_uri, tag=None):
if tag:
text_or_uri = "{%s}%s" % (text_or_uri, tag)
self.text = text_or_uri
def __str__(self):
return self.text
def __hash__(self):
return hash(self.text)
def __cmp__(self, other):
if isinstance(other, QName):
return cmp(self.text, other.text)
return cmp(self.text, other)
# --------------------------------------------------------------------
##
# ElementTree wrapper class. This class represents an entire element
# hierarchy, and adds some extra support for serialization to and from
# standard XML.
#
# @param element Optional root element.
# @keyparam file Optional file handle or file name. If given, the
# tree is initialized with the contents of this XML file.
class ElementTree(object):
def __init__(self, element=None, file=None):
# assert element is None or iselement(element)
self._root = element # first node
if file:
self.parse(file)
##
# Gets the root element for this tree.
#
# @return An element instance.
# @defreturn Element
def getroot(self):
return self._root
##
# Replaces the root element for this tree. This discards the
# current contents of the tree, and replaces it with the given
# element. Use with care.
#
# @param element An element instance.
def _setroot(self, element):
# assert iselement(element)
self._root = element
##
# Loads an external XML document into this element tree.
#
# @param source A file name or file object. If a file object is
# given, it only has to implement a <b>read(n)</b> method.
# @keyparam parser An optional parser instance. If not given, the
# standard {@link XMLParser} parser is used.
# @return The document root element.
# @defreturn Element
# @exception ParseError If the parser fails to parse the document.
def parse(self, source, parser=None):
close_source = False
if not hasattr(source, "read"):
source = open(source, "rb")
close_source = True
try:
if not parser:
parser = XMLParser(target=TreeBuilder())
while 1:
data = source.read(65536)
if not data:
break
parser.feed(data)
self._root = parser.close()
return self._root
finally:
if close_source:
source.close()
##
# Creates a tree iterator for the root element. The iterator loops
# over all elements in this tree, in document order.
#
# @param tag What tags to look for (default is to return all elements)
# @return An iterator.
# @defreturn iterator
def iter(self, tag=None):
# assert self._root is not None
return self._root.iter(tag)
# compatibility
def getiterator(self, tag=None):
# Change for a DeprecationWarning in 1.4
warnings.warn(
"This method will be removed in future versions. "
"Use 'tree.iter()' or 'list(tree.iter())' instead.",
PendingDeprecationWarning, stacklevel=2
)
return list(self.iter(tag))
##
# Same as getroot().find(path), starting at the root of the
# tree.
#
# @param path What element to look for.
# @keyparam namespaces Optional namespace prefix map.
# @return The first matching element, or None if no element was found.
# @defreturn Element or None
def find(self, path, namespaces=None):
# assert self._root is not None
if path[:1] == "/":
path = "." + path
warnings.warn(
"This search is broken in 1.3 and earlier, and will be "
"fixed in a future version. If you rely on the current "
"behaviour, change it to %r" % path,
FutureWarning, stacklevel=2
)
return self._root.find(path, namespaces)
##
# Same as getroot().findtext(path), starting at the root of the tree.
#
# @param path What element to look for.
# @param default What to return if the element was not found.
# @keyparam namespaces Optional namespace prefix map.
# @return The text content of the first matching element, or the
# default value no element was found. Note that if the element
# is found, but has no text content, this method returns an
# empty string.
# @defreturn string
def findtext(self, path, default=None, namespaces=None):
# assert self._root is not None
if path[:1] == "/":
path = "." + path
warnings.warn(
"This search is broken in 1.3 and earlier, and will be "
"fixed in a future version. If you rely on the current "
"behaviour, change it to %r" % path,
FutureWarning, stacklevel=2
)
return self._root.findtext(path, default, namespaces)
##
# Same as getroot().findall(path), starting at the root of the tree.
#
# @param path What element to look for.
# @keyparam namespaces Optional namespace prefix map.
# @return A list or iterator containing all matching elements,
# in document order.
# @defreturn list of Element instances
def findall(self, path, namespaces=None):
# assert self._root is not None
if path[:1] == "/":
path = "." + path
warnings.warn(
"This search is broken in 1.3 and earlier, and will be "
"fixed in a future version. If you rely on the current "
"behaviour, change it to %r" % path,
FutureWarning, stacklevel=2
)
return self._root.findall(path, namespaces)
##
# Finds all matching subelements, by tag name or path.
# Same as getroot().iterfind(path).
#
# @param path What element to look for.
# @keyparam namespaces Optional namespace prefix map.
# @return An iterator or sequence containing all matching elements,
# in document order.
# @defreturn a generated sequence of Element instances
def iterfind(self, path, namespaces=None):
# assert self._root is not None
if path[:1] == "/":
path = "." + path
warnings.warn(
"This search is broken in 1.3 and earlier, and will be "
"fixed in a future version. If you rely on the current "
"behaviour, change it to %r" % path,
FutureWarning, stacklevel=2
)
return self._root.iterfind(path, namespaces)
##
# Writes the element tree to a file, as XML.
#
# @def write(file, **options)
# @param file A file name, or a file object opened for writing.
# @param **options Options, given as keyword arguments.
# @keyparam encoding Optional output encoding (default is US-ASCII).
# @keyparam xml_declaration Controls if an XML declaration should
# be added to the file. Use False for never, True for always,
# None for only if not US-ASCII or UTF-8. None is default.
# @keyparam default_namespace Sets the default XML namespace (for "xmlns").
# @keyparam method Optional output method ("xml", "html", "text" or
# "c14n"; default is "xml").
def write(self, file_or_filename,
# keyword arguments
encoding=None,
xml_declaration=None,
default_namespace=None,
method=None):
# assert self._root is not None
if not method:
method = "xml"
elif method not in _serialize:
# FIXME: raise an ImportError for c14n if ElementC14N is missing?
raise ValueError("unknown method %r" % method)
if hasattr(file_or_filename, "write"):
file = file_or_filename
else:
file = open(file_or_filename, "wb")
try:
write = file.write
if not encoding:
if method == "c14n":
encoding = "utf-8"
else:
encoding = "us-ascii"
elif xml_declaration or (xml_declaration is None and
encoding not in ("utf-8", "us-ascii")):
if method == "xml":
write("<?xml version='1.0' encoding='%s'?>\n" % encoding)
if method == "text":
_serialize_text(write, self._root, encoding)
else:
qnames, namespaces = _namespaces(
self._root, encoding, default_namespace
)
serialize = _serialize[method]
serialize(write, self._root, encoding, qnames, namespaces)
finally:
if file_or_filename is not file:
file.close()
def write_c14n(self, file):
# lxml.etree compatibility. use output method instead
return self.write(file, method="c14n")
# --------------------------------------------------------------------
# serialization support
def _namespaces(elem, encoding, default_namespace=None):
# identify namespaces used in this tree
# maps qnames to *encoded* prefix:local names
qnames = {None: None}
# maps uri:s to prefixes
namespaces = {}
if default_namespace:
namespaces[default_namespace] = ""
def encode(text):
return text.encode(encoding)
def add_qname(qname):
# calculate serialized qname representation
try:
if qname[:1] == "{":
uri, tag = qname[1:].rsplit("}", 1)
prefix = namespaces.get(uri)
if prefix is None:
prefix = _namespace_map.get(uri)
if prefix is None:
prefix = "ns%d" % len(namespaces)
if prefix != "xml":
namespaces[uri] = prefix
if prefix:
qnames[qname] = encode("%s:%s" % (prefix, tag))
else:
qnames[qname] = encode(tag) # default element
else:
if default_namespace:
# FIXME: can this be handled in XML 1.0?
raise ValueError(
"cannot use non-qualified names with "
"default_namespace option"
)
qnames[qname] = encode(qname)
except TypeError:
_raise_serialization_error(qname)
# populate qname and namespaces table
try:
iterate = elem.iter
except AttributeError:
iterate = elem.getiterator # cET compatibility
for elem in iterate():
tag = elem.tag
if isinstance(tag, QName):
if tag.text not in qnames:
add_qname(tag.text)
elif isinstance(tag, basestring):
if tag not in qnames:
add_qname(tag)
elif tag is not None and tag is not Comment and tag is not PI:
_raise_serialization_error(tag)
for key, value in elem.items():
if isinstance(key, QName):
key = key.text
if key not in qnames:
add_qname(key)
if isinstance(value, QName) and value.text not in qnames:
add_qname(value.text)
text = elem.text
if isinstance(text, QName) and text.text not in qnames:
add_qname(text.text)
return qnames, namespaces
def _serialize_xml(write, elem, encoding, qnames, namespaces):
tag = elem.tag
text = elem.text
if tag is Comment:
write("<!--%s-->" % _encode(text, encoding))
elif tag is ProcessingInstruction:
write("<?%s?>" % _encode(text, encoding))
else:
tag = qnames[tag]
if tag is None:
if text:
write(_escape_cdata(text, encoding))
for e in elem:
_serialize_xml(write, e, encoding, qnames, None)
else:
write("<" + tag)
items = elem.items()
if items or namespaces:
if namespaces:
for v, k in sorted(namespaces.items(),
key=lambda x: x[1]): # sort on prefix
if k:
k = ":" + k
write(" xmlns%s=\"%s\"" % (
k.encode(encoding),
_escape_attrib(v, encoding)
))
for k, v in sorted(items): # lexical order
if isinstance(k, QName):
k = k.text
if isinstance(v, QName):
v = qnames[v.text]
else:
v = _escape_attrib(v, encoding)
write(" %s=\"%s\"" % (qnames[k], v))
if text or len(elem):
write(">")
if text:
write(_escape_cdata(text, encoding))
for e in elem:
_serialize_xml(write, e, encoding, qnames, None)
write("</" + tag + ">")
else:
write(" />")
if elem.tail:
write(_escape_cdata(elem.tail, encoding))
HTML_EMPTY = ("area", "base", "basefont", "br", "col", "frame", "hr",
"img", "input", "isindex", "link", "meta", "param")
try:
HTML_EMPTY = set(HTML_EMPTY)
except NameError:
pass
def _serialize_html(write, elem, encoding, qnames, namespaces):
tag = elem.tag
text = elem.text
if tag is Comment:
write("<!--%s-->" % _escape_cdata(text, encoding))
elif tag is ProcessingInstruction:
write("<?%s?>" % _escape_cdata(text, encoding))
else:
tag = qnames[tag]
if tag is None:
if text:
write(_escape_cdata(text, encoding))
for e in elem:
_serialize_html(write, e, encoding, qnames, None)
else:
write("<" + tag)
items = elem.items()
if items or namespaces:
if namespaces:
for v, k in sorted(namespaces.items(),
key=lambda x: x[1]): # sort on prefix
if k:
k = ":" + k
write(" xmlns%s=\"%s\"" % (
k.encode(encoding),
_escape_attrib(v, encoding)
))
for k, v in sorted(items): # lexical order
if isinstance(k, QName):
k = k.text
if isinstance(v, QName):
v = qnames[v.text]
else:
v = _escape_attrib_html(v, encoding)
# FIXME: handle boolean attributes
write(" %s=\"%s\"" % (qnames[k], v))
write(">")
ltag = tag.lower()
if text:
if ltag == "script" or ltag == "style":
write(_encode(text, encoding))
else:
write(_escape_cdata(text, encoding))
for e in elem:
_serialize_html(write, e, encoding, qnames, None)
if ltag not in HTML_EMPTY:
write("</" + tag + ">")
if elem.tail:
write(_escape_cdata(elem.tail, encoding))
def _serialize_text(write, elem, encoding):
for part in elem.itertext():
write(part.encode(encoding))
if elem.tail:
write(elem.tail.encode(encoding))
_serialize = {
"xml": _serialize_xml,
"html": _serialize_html,
"text": _serialize_text,
# this optional method is imported at the end of the module
# "c14n": _serialize_c14n,
}
##
# Registers a namespace prefix. The registry is global, and any
# existing mapping for either the given prefix or the namespace URI
# will be removed.
#
# @param prefix Namespace prefix.
# @param uri Namespace uri. Tags and attributes in this namespace
# will be serialized with the given prefix, if at all possible.
# @exception ValueError If the prefix is reserved, or is otherwise
# invalid.
def register_namespace(prefix, uri):
if re.match("ns\d+$", prefix):
raise ValueError("Prefix format reserved for internal use")
for k, v in _namespace_map.items():
if k == uri or v == prefix:
del _namespace_map[k]
_namespace_map[uri] = prefix
_namespace_map = {
# "well-known" namespace prefixes
"http://www.w3.org/XML/1998/namespace": "xml",
"http://www.w3.org/1999/xhtml": "html",
"http://www.w3.org/1999/02/22-rdf-syntax-ns#": "rdf",
"http://schemas.xmlsoap.org/wsdl/": "wsdl",
# xml schema
"http://www.w3.org/2001/XMLSchema": "xs",
"http://www.w3.org/2001/XMLSchema-instance": "xsi",
# dublin core
"http://purl.org/dc/elements/1.1/": "dc",
}
def _raise_serialization_error(text):
raise TypeError(
"cannot serialize %r (type %s)" % (text, type(text).__name__)
)
def _encode(text, encoding):
try:
return text.encode(encoding, "xmlcharrefreplace")
except (TypeError, AttributeError):
_raise_serialization_error(text)
def _escape_cdata(text, encoding):
# escape character data
try:
# it's worth avoiding do-nothing calls for strings that are
# shorter than 500 character, or so. assume that's, by far,
# the most common case in most applications.
if "&" in text:
text = text.replace("&", "&")
if "<" in text:
text = text.replace("<", "<")
if ">" in text:
text = text.replace(">", ">")
return text.encode(encoding, "xmlcharrefreplace")
except (TypeError, AttributeError):
_raise_serialization_error(text)
def _escape_attrib(text, encoding):
# escape attribute value
try:
if "&" in text:
text = text.replace("&", "&")
if "<" in text:
text = text.replace("<", "<")
if ">" in text:
text = text.replace(">", ">")
if "\"" in text:
text = text.replace("\"", """)
if "\n" in text:
text = text.replace("\n", " ")
return text.encode(encoding, "xmlcharrefreplace")
except (TypeError, AttributeError):
_raise_serialization_error(text)
def _escape_attrib_html(text, encoding):
# escape attribute value
try:
if "&" in text:
text = text.replace("&", "&")
if ">" in text:
text = text.replace(">", ">")
if "\"" in text:
text = text.replace("\"", """)
return text.encode(encoding, "xmlcharrefreplace")
except (TypeError, AttributeError):
_raise_serialization_error(text)
# --------------------------------------------------------------------
##
# Generates a string representation of an XML element, including all
# subelements.
#
# @param element An Element instance.
# @keyparam encoding Optional output encoding (default is US-ASCII).
# @keyparam method Optional output method ("xml", "html", "text" or
# "c14n"; default is "xml").
# @return An encoded string containing the XML data.
# @defreturn string
def tostring(element, encoding=None, method=None):
class dummy:
pass
data = []
file = dummy()
file.write = data.append
ElementTree(element).write(file, encoding, method=method)
return "".join(data)
##
# Generates a string representation of an XML element, including all
# subelements. The string is returned as a sequence of string fragments.
#
# @param element An Element instance.
# @keyparam encoding Optional output encoding (default is US-ASCII).
# @keyparam method Optional output method ("xml", "html", "text" or
# "c14n"; default is "xml").
# @return A sequence object containing the XML data.
# @defreturn sequence
# @since 1.3
def tostringlist(element, encoding=None, method=None):
class dummy:
pass
data = []
file = dummy()
file.write = data.append
ElementTree(element).write(file, encoding, method=method)
# FIXME: merge small fragments into larger parts
return data
##
# Writes an element tree or element structure to sys.stdout. This
# function should be used for debugging only.
# <p>
# The exact output format is implementation dependent. In this
# version, it's written as an ordinary XML file.
#
# @param elem An element tree or an individual element.
def dump(elem):
# debugging
if not isinstance(elem, ElementTree):
elem = ElementTree(elem)
elem.write(sys.stdout)
tail = elem.getroot().tail
if not tail or tail[-1] != "\n":
sys.stdout.write("\n")
# --------------------------------------------------------------------
# parsing
##
# Parses an XML document into an element tree.
#
# @param source A filename or file object containing XML data.
# @param parser An optional parser instance. If not given, the
# standard {@link XMLParser} parser is used.
# @return An ElementTree instance
def parse(source, parser=None):
tree = ElementTree()
tree.parse(source, parser)
return tree
##
# Parses an XML document into an element tree incrementally, and reports
# what's going on to the user.
#
# @param source A filename or file object containing XML data.
# @param events A list of events to report back. If omitted, only "end"
# events are reported.
# @param parser An optional parser instance. If not given, the
# standard {@link XMLParser} parser is used.
# @return A (event, elem) iterator.
def iterparse(source, events=None, parser=None):
close_source = False
if not hasattr(source, "read"):
source = open(source, "rb")
close_source = True
try:
if not parser:
parser = XMLParser(target=TreeBuilder())
return _IterParseIterator(source, events, parser, close_source)
except:
if close_source:
source.close()
raise
class _IterParseIterator(object):
def __init__(self, source, events, parser, close_source=False):
self._file = source
self._close_file = close_source
self._events = []
self._index = 0
self._error = None
self.root = self._root = None
self._parser = parser
# wire up the parser for event reporting
parser = self._parser._parser
append = self._events.append
if events is None:
events = ["end"]
for event in events:
if event == "start":
try:
parser.ordered_attributes = 1
parser.specified_attributes = 1
def handler(tag, attrib_in, event=event, append=append,
start=self._parser._start_list):
append((event, start(tag, attrib_in)))
parser.StartElementHandler = handler
except AttributeError:
def handler(tag, attrib_in, event=event, append=append,
start=self._parser._start):
append((event, start(tag, attrib_in)))
parser.StartElementHandler = handler
elif event == "end":
def handler(tag, event=event, append=append,
end=self._parser._end):
append((event, end(tag)))
parser.EndElementHandler = handler
elif event == "start-ns":
def handler(prefix, uri, event=event, append=append):
try:
uri = (uri or "").encode("ascii")
except UnicodeError:
pass
append((event, (prefix or "", uri or "")))
parser.StartNamespaceDeclHandler = handler
elif event == "end-ns":
def handler(prefix, event=event, append=append):
append((event, None))
parser.EndNamespaceDeclHandler = handler
else:
raise ValueError("unknown event %r" % event)
def next(self):
try:
while 1:
try:
item = self._events[self._index]
self._index += 1
return item
except IndexError:
pass
if self._error:
e = self._error
self._error = None
raise e
if self._parser is None:
self.root = self._root
break
# load event buffer
del self._events[:]
self._index = 0
data = self._file.read(16384)
if data:
try:
self._parser.feed(data)
except SyntaxError as exc:
self._error = exc
else:
self._root = self._parser.close()
self._parser = None
except:
if self._close_file:
self._file.close()
raise
if self._close_file:
self._file.close()
raise StopIteration
def __iter__(self):
return self
##
# Parses an XML document from a string constant. This function can
# be used to embed "XML literals" in Python code.
#
# @param source A string containing XML data.
# @param parser An optional parser instance. If not given, the
# standard {@link XMLParser} parser is used.
# @return An Element instance.
# @defreturn Element
def XML(text, parser=None):
if not parser:
parser = XMLParser(target=TreeBuilder())
parser.feed(text)
return parser.close()
##
# Parses an XML document from a string constant, and also returns
# a dictionary which maps from element id:s to elements.
#
# @param source A string containing XML data.
# @param parser An optional parser instance. If not given, the
# standard {@link XMLParser} parser is used.
# @return A tuple containing an Element instance and a dictionary.
# @defreturn (Element, dictionary)
def XMLID(text, parser=None):
if not parser:
parser = XMLParser(target=TreeBuilder())
parser.feed(text)
tree = parser.close()
ids = {}
for elem in tree.iter():
id = elem.get("id")
if id:
ids[id] = elem
return tree, ids
##
# Parses an XML document from a string constant. Same as {@link #XML}.
#
# @def fromstring(text)
# @param source A string containing XML data.
# @return An Element instance.
# @defreturn Element
fromstring = XML
##
# Parses an XML document from a sequence of string fragments.
#
# @param sequence A list or other sequence containing XML data fragments.
# @param parser An optional parser instance. If not given, the
# standard {@link XMLParser} parser is used.
# @return An Element instance.
# @defreturn Element
# @since 1.3
def fromstringlist(sequence, parser=None):
if not parser:
parser = XMLParser(target=TreeBuilder())
for text in sequence:
parser.feed(text)
return parser.close()
# --------------------------------------------------------------------
##
# Generic element structure builder. This builder converts a sequence
# of {@link #TreeBuilder.start}, {@link #TreeBuilder.data}, and {@link
# #TreeBuilder.end} method calls to a well-formed element structure.
# <p>
# You can use this class to build an element structure using a custom XML
# parser, or a parser for some other XML-like format.
#
# @param element_factory Optional element factory. This factory
# is called to create new Element instances, as necessary.
class TreeBuilder(object):
def __init__(self, element_factory=None):
self._data = [] # data collector
self._elem = [] # element stack
self._last = None # last element
self._tail = None # true if we're after an end tag
if element_factory is None:
element_factory = Element
self._factory = element_factory
##
# Flushes the builder buffers, and returns the toplevel document
# element.
#
# @return An Element instance.
# @defreturn Element
def close(self):
assert len(self._elem) == 0, "missing end tags"
assert self._last is not None, "missing toplevel element"
return self._last
def _flush(self):
if self._data:
if self._last is not None:
text = "".join(self._data)
if self._tail:
assert self._last.tail is None, "internal error (tail)"
self._last.tail = text
else:
assert self._last.text is None, "internal error (text)"
self._last.text = text
self._data = []
##
# Adds text to the current element.
#
# @param data A string. This should be either an 8-bit string
# containing ASCII text, or a Unicode string.
def data(self, data):
self._data.append(data)
##
# Opens a new element.
#
# @param tag The element name.
# @param attrib A dictionary containing element attributes.
# @return The opened element.
# @defreturn Element
def start(self, tag, attrs):
self._flush()
self._last = elem = self._factory(tag, attrs)
if self._elem:
self._elem[-1].append(elem)
self._elem.append(elem)
self._tail = 0
return elem
##
# Closes the current element.
#
# @param tag The element name.
# @return The closed element.
# @defreturn Element
def end(self, tag):
self._flush()
self._last = self._elem.pop()
assert self._last.tag == tag,\
"end tag mismatch (expected %s, got %s)" % (
self._last.tag, tag)
self._tail = 1
return self._last
##
# Element structure builder for XML source data, based on the
# <b>expat</b> parser.
#
# @keyparam target Target object. If omitted, the builder uses an
# instance of the standard {@link #TreeBuilder} class.
# @keyparam html Predefine HTML entities. This flag is not supported
# by the current implementation.
# @keyparam encoding Optional encoding. If given, the value overrides
# the encoding specified in the XML file.
# @see #ElementTree
# @see #TreeBuilder
class XMLParser(object):
def __init__(self, html=0, target=None, encoding=None):
try:
from xml.parsers import expat
except ImportError:
try:
import pyexpat as expat
except ImportError:
raise ImportError(
"No module named expat; use SimpleXMLTreeBuilder instead"
)
parser = expat.ParserCreate(encoding, "}")
if target is None:
target = TreeBuilder()
# underscored names are provided for compatibility only
self.parser = self._parser = parser
self.target = self._target = target
self._error = expat.error
self._names = {} # name memo cache
# callbacks
parser.DefaultHandlerExpand = self._default
parser.StartElementHandler = self._start
parser.EndElementHandler = self._end
parser.CharacterDataHandler = self._data
# optional callbacks
parser.CommentHandler = self._comment
parser.ProcessingInstructionHandler = self._pi
# let expat do the buffering, if supported
try:
self._parser.buffer_text = 1
except AttributeError:
pass
# use new-style attribute handling, if supported
try:
self._parser.ordered_attributes = 1
self._parser.specified_attributes = 1
parser.StartElementHandler = self._start_list
except AttributeError:
pass
self._doctype = None
self.entity = {}
try:
self.version = "Expat %d.%d.%d" % expat.version_info
except AttributeError:
pass # unknown
def _raiseerror(self, value):
err = ParseError(value)
err.code = value.code
err.position = value.lineno, value.offset
raise err
def _fixtext(self, text):
# convert text string to ascii, if possible
try:
return text.encode("ascii")
except UnicodeError:
return text
def _fixname(self, key):
# expand qname, and convert name string to ascii, if possible
try:
name = self._names[key]
except KeyError:
name = key
if "}" in name:
name = "{" + name
self._names[key] = name = self._fixtext(name)
return name
def _start(self, tag, attrib_in):
fixname = self._fixname
fixtext = self._fixtext
tag = fixname(tag)
attrib = {}
for key, value in attrib_in.items():
attrib[fixname(key)] = fixtext(value)
return self.target.start(tag, attrib)
def _start_list(self, tag, attrib_in):
fixname = self._fixname
fixtext = self._fixtext
tag = fixname(tag)
attrib = {}
if attrib_in:
for i in range(0, len(attrib_in), 2):
attrib[fixname(attrib_in[i])] = fixtext(attrib_in[i+1])
return self.target.start(tag, attrib)
def _data(self, text):
return self.target.data(self._fixtext(text))
def _end(self, tag):
return self.target.end(self._fixname(tag))
def _comment(self, data):
try:
comment = self.target.comment
except AttributeError:
pass
else:
return comment(self._fixtext(data))
def _pi(self, target, data):
try:
pi = self.target.pi
except AttributeError:
pass
else:
return pi(self._fixtext(target), self._fixtext(data))
def _default(self, text):
prefix = text[:1]
if prefix == "&":
# deal with undefined entities
try:
self.target.data(self.entity[text[1:-1]])
except KeyError:
from xml.parsers import expat
err = expat.error(
"undefined entity %s: line %d, column %d" %
(text, self._parser.ErrorLineNumber,
self._parser.ErrorColumnNumber)
)
err.code = 11 # XML_ERROR_UNDEFINED_ENTITY
err.lineno = self._parser.ErrorLineNumber
err.offset = self._parser.ErrorColumnNumber
raise err
elif prefix == "<" and text[:9] == "<!DOCTYPE":
self._doctype = [] # inside a doctype declaration
elif self._doctype is not None:
# parse doctype contents
if prefix == ">":
self._doctype = None
return
text = text.strip()
if not text:
return
self._doctype.append(text)
n = len(self._doctype)
if n > 2:
type = self._doctype[1]
if type == "PUBLIC" and n == 4:
name, type, pubid, system = self._doctype
elif type == "SYSTEM" and n == 3:
name, type, system = self._doctype
pubid = None
else:
return
if pubid:
pubid = pubid[1:-1]
if hasattr(self.target, "doctype"):
self.target.doctype(name, pubid, system[1:-1])
elif self.doctype is not self._XMLParser__doctype:
# warn about deprecated call
self._XMLParser__doctype(name, pubid, system[1:-1])
self.doctype(name, pubid, system[1:-1])
self._doctype = None
##
# (Deprecated) Handles a doctype declaration.
#
# @param name Doctype name.
# @param pubid Public identifier.
# @param system System identifier.
def doctype(self, name, pubid, system):
"""This method of XMLParser is deprecated."""
warnings.warn(
"This method of XMLParser is deprecated. Define doctype() "
"method on the TreeBuilder target.",
DeprecationWarning,
)
# sentinel, if doctype is redefined in a subclass
__doctype = doctype
##
# Feeds data to the parser.
#
# @param data Encoded data.
def feed(self, data):
try:
self._parser.Parse(data, 0)
except self._error, v:
self._raiseerror(v)
##
# Finishes feeding data to the parser.
#
# @return An element structure.
# @defreturn Element
def close(self):
try:
self._parser.Parse("", 1) # end of data
except self._error, v:
self._raiseerror(v)
tree = self.target.close()
del self.target, self._parser # get rid of circular references
return tree
# compatibility
XMLTreeBuilder = XMLParser
# workaround circular import.
try:
from ElementC14N import _serialize_c14n
_serialize["c14n"] = _serialize_c14n
except ImportError:
pass
|
bikashgupta11/javarobot
|
src/main/resources/jython/Lib/xml/etree/ElementTree.py
|
Python
|
gpl-3.0
| 56,932 | 0.001194 |
# -*- coding: utf-8 -*-
'''
Flixnet Add-on
Copyright (C) 2017 homik
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
'''
import urllib, urlparse, re
from resources.lib.modules import cleantitle
from resources.lib.modules import client
class source:
def __init__(self):
self.priority = 1
self.language = ['pl']
self.domains = ['filiser.tv']
self.base_link = 'http://filiser.tv/'
self.url_transl = 'embed?salt=%s'
self.search_link = 'szukaj?q=%s'
self.episode_link = '-Season-%01d-Episode-%01d'
def do_search(self, title, year, is_movie_search):
try:
url = urlparse.urljoin(self.base_link, self.search_link)
url = url % urllib.quote(title)
result = client.request(url)
result = result.decode('utf-8')
result = client.parseDOM(result, 'ul', attrs={'id': 'resultList2'})
result = client.parseDOM(result[0], 'li')
result = [(client.parseDOM(i, 'a', ret='href')[0],
client.parseDOM(i, 'div', attrs={'class': 'title'})[0],
(client.parseDOM(i, 'div', attrs={'class': 'title_org'}) + [None])[0],
client.parseDOM(i, 'div', attrs={'class': 'info'})[0],
) for i in result]
search_type = 'Film' if is_movie_search else 'Serial'
cleaned_title = cleantitle.get(title)
# filter by name
result = [x for x in result if cleaned_title == cleantitle.get(self.get_first_not_none([x[2], x[1]]))]
# filter by type
result = [x for x in result if x[3].startswith(search_type)]
# filter by year
result = [x for x in result if x[3].endswith(str(year))]
if len(result) > 0:
return result[0][0]
else:
return
except :
return
def get_first_not_none(self, collection):
return next(item for item in collection if item is not None)
def movie(self, imdb, title, localtitle, year):
return self.do_search(title, year, True)
def tvshow(self, imdb, tvdb, tvshowtitle, localtvshowtitle, year):
return self.do_search(tvshowtitle, year, False)
def episode(self, url, imdb, tvdb, title, premiered, season, episode):
try:
if url == None: return
url = urlparse.urljoin(self.base_link, url)
result = client.request(url)
result = client.parseDOM(result, 'ul', attrs={'data-season-num': season})[0]
result = client.parseDOM(result, 'li')
for i in result:
s = client.parseDOM(i, 'a', attrs={'class': 'episodeNum'})[0]
e = int(s[7:-1])
if e == int(episode):
return client.parseDOM(i, 'a', attrs={'class': 'episodeNum'}, ret='href')[0]
except :
return
def sources(self, url, hostDict, hostprDict):
try:
sources = []
if url == None: return sources
url = urlparse.urljoin(self.base_link, url)
result = client.request(url)
result = client.parseDOM(result, 'div', attrs={'id': 'links'})
attr = client.parseDOM(result, 'ul', ret='data-type')
result = client.parseDOM(result, 'ul')
for x in range(0, len(result)):
transl_type = attr[x]
links = result[x]
sources += self.extract_sources(transl_type, links)
return sources
except:
return sources
def get_lang_by_type(self, lang_type):
if lang_type == 'DUBBING':
return 'pl', 'Dubbing'
elif lang_type == 'NAPISY_PL':
return 'pl', 'Napisy'
if lang_type == 'LEKTOR_PL':
return 'pl', 'Lektor'
elif lang_type == 'POLSKI':
return 'pl', None
return 'en', None
def extract_sources(self, transl_type, links):
sources = []
data_refs = client.parseDOM(links, 'li', ret='data-ref')
result = client.parseDOM(links, 'li')
lang, info = self.get_lang_by_type(transl_type)
for i in range(0, len(result)):
el = result[i];
host = client.parseDOM(el, 'span', attrs={'class': 'host'})[0]
quality = client.parseDOM(el, 'span', attrs={'class': 'quality'})[0]
q = 'SD'
if quality.endswith('720p'):
q = 'HD'
elif quality.endswith('1080p'):
q = '1080p'
sources.append({'source': host, 'quality': q, 'language': lang, 'url': data_refs[i], 'info': info, 'direct': False, 'debridonly': False})
return sources
def resolve(self, url):
try:
url_to_exec = urlparse.urljoin(self.base_link, self.url_transl) % url
result = client.request(url_to_exec)
m = re.search("(?<=var url = ')(.*\n?)(?=')", result)
result_url = m.group(0)
result_url = result_url.replace('#WIDTH', '100')
result_url = result_url.replace('#HEIGHT', '100')
return result_url
except:
return
|
azumimuo/family-xbmc-addon
|
plugin.video.showboxarize/resources/lib/sources_pl/filister.py
|
Python
|
gpl-2.0
| 5,852 | 0.003418 |
from gh_frespo_integration.utils import github_adapter
from gh_frespo_integration.models import *
from django.conf import settings
import logging
from datetime import timedelta
__author__ = 'tony'
logger = logging.getLogger(__name__)
def get_repos_and_configs(user):
repos = []
github_username = user.github_username()
if github_username:
repos = github_adapter.fetch_repos(github_username)
for repo_dict in repos:
gh_id = repo_dict['id']
repodb = get_repodb_by_githubid(gh_id)
if repodb:
user_repo_config = get_repo_config_by_repo_and_user(repodb, user)
if user_repo_config:
repo_dict['add_links'] = user_repo_config.add_links
repo_dict['new_only'] = user_repo_config.new_only
return repos
def get_repodb_by_githubid(gh_id):
repos = Repo.objects.filter(gh_id = gh_id)
if repos.count() > 1:
logger.error('Database inconsistency: multiple repos found with gh_id:%s'%gh_id)
elif repos.count() == 1:
return repos[0]
else:
return None
def get_repo_config_by_repo_and_user(repo, user):
configs = UserRepoConfig.objects.filter(repo__id = repo.id, user__id = user.id)
if configs.count() > 1:
logger.error('Database inconsistency: multiple configs found for repo:%s / user:%s'%(repo.id, user.id))
elif configs.count() == 1:
return configs[0]
else:
return None
def update_user_configs(user, dict):
github_username = user.github_username()
if github_username:
repos = github_adapter.fetch_repos(github_username)
my_repo_ids = []
for repo_dict in repos:
gh_id = repo_dict['id']
repodb = get_repodb_by_githubid(gh_id)
if not repodb:
owner = repo_dict['owner']['login']
owner_type = repo_dict['owner']['type']
name = repo_dict['name']
repodb = Repo.newRepo(owner, owner_type, name, gh_id, user)
repodb.save()
config = get_repo_config_by_repo_and_user(repodb, user)
if not config:
config = UserRepoConfig.newConfig(user, repodb)
config.add_links = dict.has_key('check_addlink_%s' % gh_id)
# config.new_only = dict.has_key('check_newonly_%s' % gh_id)
config.new_only = True
config.save()
my_repo_ids.append(gh_id)
UserRepoConfig.objects.filter(user__id = user.id).exclude(repo__gh_id__in = my_repo_ids).delete()
def add_sponsorthis_comments():
configs = UserRepoConfig.objects.filter(add_links = True)
logger.debug('starting sponsor_this routine...')
for config in configs:
repo_owner = config.repo.owner
repo_name = config.repo.name
last_ran = None
logger.debug('processing repo_config %s (%s/%s)' % (config.id, config.repo.owner, config.repo.name))
if config.new_only or config.already_did_old:
last_ran = config.last_ran - timedelta(hours=1)
logger.debug('will list issues after %s' % last_ran)
else:
logger.debug('will list all issues')
config.update_last_ran()
try:
issues = github_adapter.fetch_issues(repo_owner, repo_name, last_ran)
logger.debug('issues are fetched')
for issue in issues:
_add_comment_if_not_already(config, int(issue['number']), repo_owner, repo_name)
if not config.new_only:
config.set_already_did_old()
except BaseException as e:
logger.error("Error adding comments repository %s/%s: %s" % (repo_owner, repo_name, e))
logger.debug('sponsor_this ended successfully')
def _add_comment_if_not_already(repo_config, issue_number, repo_owner, repo_name):
issue_already_commented = get_issue_already_commented(repo_config.repo, issue_number)
if not issue_already_commented:
body = u"""Do you care about this issue? To get it fixed quickly, [offer a cash incentive to developers on FreedomSponsors.org](%s/core/issue/sponsor?trackerURL=https://github.com/%s/%s/issues/%s).
If you can only give US$5, offering just that will invite other people to do the same. Sharing the cost will soon add up!""" % (settings.SITE_HOME, repo_owner, repo_name, issue_number)
github_adapter.bot_comment(repo_owner, repo_name, issue_number, body)
issue_already_commented = IssueAlreadyCommented.newIssueAlreadyCommented(repo_config.repo, issue_number)
issue_already_commented.save()
logger.info('commented on issue %s of %s/%s' % (issue_number, repo_owner, repo_name))
else:
logger.debug('NOT commenting on issue %s of %s/%s because it was already commented on' % (issue_number, repo_owner, repo_name))
def get_issue_already_commented(repo, number):
iacs = IssueAlreadyCommented.objects.filter(repo__id = repo.id, number = number)
if iacs.count() > 1:
logger.error('Database inconsistency: multiple issue_already_commented found for repo:%s / number:%s'%(repo.id, number))
elif iacs.count() == 1:
return iacs[0]
else:
return None
|
eahneahn/free
|
djangoproject/gh_frespo_integration/services/github_services.py
|
Python
|
agpl-3.0
| 5,113 | 0.008801 |
from lxml import etree
import os
from BeautifulSoup import BeautifulSoup
from itertools import chain
def replacements(text):
text = text.replace('>', '\\textgreater ')
text = text.replace('<', '\\textless ')
text = text.replace('&', '\&')
text = text.replace('_', '\_')
text = text.replace('%', '\%')
text = text.replace('[', '\lbrack')
text = text.replace(']', '\\rbrack')
return text
def fillContent(tex, srchStr, insStr):
insStr = replacements(insStr)
insIndex = tex.index(srchStr)
tex = tex[:insIndex+len(srchStr)] + insStr + tex[insIndex+len(srchStr):]
return tex
def convertToTex(text, figInTabular=False):
text = replacements(text)
soup = BeautifulSoup(text)
contents = soup.contents[0].contents
retTxt = ''
for content in contents:
if str(type(content)) == "<class 'BeautifulSoup.NavigableString'>":
content = content.replace('\\newline', '~\\\\')
content = content.replace('\\newpara', '~\\\\\\\\')
content = content.replace('\\backslash', '\\textbackslash')
content = content.replace('|', '\\textbar ')
retTxt += content
elif str(type(content)) == "<class 'BeautifulSoup.Tag'>":
if content.name == 'b':
retTxt += '\\textbf{' + convertToTex(str(content)) + '}'
elif content.name == 'u':
retTxt += '\underline{' + convertToTex(str(content)) + '}'
elif content.name == 'i':
retTxt += '\\textit{' + convertToTex(str(content)) + '}'
elif content.name == 'ul':
retTxt += '\n\\begin{itemize}'
for item in content.contents:
if str(type(item)) == "<class 'BeautifulSoup.Tag'>":
retTxt += '\n \item ' + convertToTex(str(item))
retTxt += '\n\end{itemize}\n'
elif content.name == 'chapter':
attrs = dict(content.attrs)
if not attrs.has_key('name'):
print "One of the chapters do not have a 'name' attribute or is misspelled. Please correct it and re-run."
exit(0)
elif attrs['name'] == '':
print "One of the chapters' name is empty. Please correct it and re-run."
exit(0)
else:
retTxt += '\\begin{projChapter}{' + attrs['name'] + '}' + convertToTex(str(content)) + '\\end{projChapter}'
elif content.name == 'section':
attrs = dict(content.attrs)
if not attrs.has_key('name'):
print "One of the sections do not have a 'name' attribute or is misspelled. Please correct it and re-run."
exit(0)
elif attrs['name'] == '':
print "One of the sections' name is empty. Please correct it and re-run."
exit(0)
else:
retTxt += '\\begin{projSection}{' + attrs['name'] + '}' + convertToTex(str(content)) + '\\end{projSection}'
elif content.name == 'subsection':
attrs = dict(content.attrs)
if not attrs.has_key('name'):
print "One of the subsections do not have a 'name' attribute or is misspelled. Please correct it and re-run."
exit(0)
elif attrs['name'] == '':
print "One of the subsections' name is empty. Please correct it and re-run."
exit(0)
else:
retTxt += '\\begin{projSubSection}{' + attrs['name'] + '}' + convertToTex(str(content)) + '\\end{projSubSection}'
elif content.name == 'img':
props = dict(content.attrs)
if not props.has_key('id'):
print "One of the images do not have an 'id' attribute or is misspelled. Please correct it and re-run."
exit(0)
elif not props.has_key('src'):
print "One of the images do not have a 'src' attribute or is misspelled. Please correct it and re-run."
exit(0)
elif not props.has_key('caption'):
print "One of the images do not have a 'caption' attribute or is misspelled. Please correct it and re-run."
exit(0)
elif not props.has_key('scale'):
print "One of the images do not have a 'scale' attribute or is misspelled. Please correct it and re-run."
exit(0)
elif props['id'] == '':
print "One of the images has an empty 'id'. Please correct it and re-run."
exit(0)
elif props['src'] == '':
print "One of the images has an empty 'src'. Please correct it and re-run."
exit(0)
elif props['scale'] == '':
print "Scaling factor for one of the images hasnt been defined. Please correct it and re-run."
exit(0)
else:
if figInTabular:
retTxt += '\\raisebox{-\\totalheight}{\centering\n\includegraphics[scale=' + props['scale'] + ']{' + props['src'] + '}\n\label{' + props['id'] + '}}\n'
else:
retTxt += '\\begin{figure}[ht!]\n\centering\n\includegraphics[scale=' + props['scale'] + ']{' + props['src'] + '}\n\caption{' + props['caption'] + '}\n\label{' + props['id'] + '}\n\end{figure}\n'
elif content.name == 'ref':
props = dict(content.attrs)
if not props.has_key('type'):
print "One of the references doesnt have a 'type' attribute. Please correct it and re-run."
exit(0)
elif props['type'] == '':
print "One of the references has an empty string for 'type'. Please correct it and re-run."
exit(0)
else:
if props['type'] == 'figure':
retTxt += 'Figure \\ref{' + content.text + '}'
elif props['type'] == 'table':
retTxt += 'Table \\ref{' + content.text +'}'
elif content.name == 'table':
props = dict(content.attrs)
if not props.has_key('id'):
print "One of the tables do not have an 'id' attribute or is misspelled. Please correct it and re-run."
exit(0)
elif not props.has_key('alignments'):
print "One of the tables do not have a 'alignments' attribute or is misspelled. Please correct it and re-run."
exit(0)
elif not props.has_key('caption'):
print "One of the tables do not have a 'caption' attribute or is misspelled. Please correct it and re-run."
exit(0)
elif props['id'] == '':
print "One of the tables has an empty 'id'. Please correct it and re-run."
exit(0)
elif props['alignments'] == '':
print "One of the tables has an empty 'alignments'. Please correct it and re-run."
exit(0)
else:
alignments = props['alignments']
retTxt += '\\begin{table}[h]\\begin{center}\\begin{tabular}{' + alignments + '}'
for horizontal in content.contents:
if str(type(horizontal)) == "<class 'BeautifulSoup.Tag'>":
if horizontal.name == "tr":
cols = horizontal.contents
numOfCols = len(cols)
for i in range(numOfCols):
if str(type(cols[i])) == "<class 'BeautifulSoup.Tag'>":
retTxt += convertToTex(str(cols[i]), figInTabular=True)
print str(cols[i])
if i != numOfCols - 2:
retTxt += ' & '
else:
retTxt += ' \\\\\n'
elif horizontal.name == 'hline':
retTxt += '\hline\n'
retTxt += '\\end{tabular}\\end{center}\\caption{' + props['caption'] + '}\\label{' + props['id'] + '}\\end{table}'
return retTxt
def main():
f = open("fyp.stmplt", "r")
sty = f.read()
f.close()
f = open("fyp.ttmplt", "r")
tex = f.read()
f.close()
f = open("report.xml", "r")
xmlStr = f.read()
f.close()
root = etree.fromstring(xmlStr)
projectTitle = root.find('projectDetails').find('projectTitle').text
guide = root.find('projectDetails').find('guide').text
principal = root.find('projectDetails').find('principal').text
HOD = root.find('projectDetails').find('HOD').text
durationLong = root.find('projectDetails').find('duration').text
collLogoPath = root.find('projectDetails').find('collLogoPath').text
defaultFontFamily = root.find('font').find('defaultFontFamily').text
fontLevelOne = root.find('font').find('levelOne').text
fontLevelTwo = root.find('font').find('levelTwo').text
fontLevelThree = root.find('font').find('levelThree').text
fontLevelFour = root.find('font').find('levelFour').text
numberStrings = ["One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten"]
students = [ (student.find('name').text, student.find('usn').text) for student in root.find('students').getchildren() if student.tag == 'student']
students = [ (numberStrings[i], students[i][0], students[i][1]) for i in range(len(students))]
headerLogoScale = root.find('header').find('logoScale').text
headerTitleSize = root.find('header').find('titleSize').text
headerLineWidth = root.find('header').find('lineWidth').text
dept = root.find('footer').find('dept').text
durationShort = root.find('footer').find('duration').text
footerLineWidth = root.find('footer').find('lineWidth').text
chapterFontFamily = root.find('chapterControls').find('fontFamily').text
coverFontFamily = root.find('cover').find('fontFamily').text
univName = root.find('cover').find('univName').text
univLogoPath = root.find('cover').find('univLogoPath').text
univLogoScale = root.find('cover').find('univLogoScale').text
course = root.find('cover').find('course').text
stream = root.find('cover').find('stream').text
deptName = root.find('cover').find('deptName').text
collName = root.find('cover').find('collName').text
affiliation = root.find('cover').find('affiliation').text
address = root.find('cover').find('address').text
collCoverLogoScale = root.find('cover').find('collCoverLogoScale').text
vspaceInterblock = root.find('cover').find('vspaceInterblock').text
vspaceIntrablock = root.find('cover').find('vspaceIntrablock').text
certificateLogoScale = root.find('certificate').find('logoScale').text
certificateCourse = root.find('certificate').find('course').text
certificateStream = root.find('certificate').find('stream').text
certificateUnivName = root.find('certificate').find('univName').text
abstractFontFamily = root.find('abstractControls').find('fontFamily').text
'''
modifying the tex file
'''
tex = fillContent(tex, 'newcommand{\projectTitle}{', projectTitle)
tex = fillContent(tex, 'newcommand{\guide}{', guide)
tex = fillContent(tex, 'newcommand{\principal}{', principal)
tex = fillContent(tex, 'newcommand{\HOD}{', HOD)
tex = fillContent(tex, 'newcommand{\durationLong}{', durationLong)
tex = fillContent(tex, 'newcommand{\headerLineWidth}{', headerLineWidth)
tex = fillContent(tex, 'newcommand{\\footerLineWidth}{', footerLineWidth)
tex = fillContent(tex, 'newcommand{\collLogoPath}{', collLogoPath)
tex = fillContent(tex, 'newcommand{\defaultFontFamily}{', defaultFontFamily)
tex = fillContent(tex, 'newcommand{\\fontLevelOne}{', fontLevelOne)
tex = fillContent(tex, 'newcommand{\\fontLevelTwo}{', fontLevelTwo)
tex = fillContent(tex, 'newcommand{\\fontLevelThree}{', fontLevelThree)
tex = fillContent(tex, 'newcommand{\\fontLevelFour}{', fontLevelFour)
insIndex = tex.index('@studentsList')
insStr = ''
for student in students:
insStr += '\\newcommand{\\student' + student[0] + '}{' + student[1] + '}\n'
insStr += '\\newcommand{\\usn' + student[0] + '}{' + student[2] + '}\n'
tex = tex[:insIndex] + insStr + tex[insIndex + len('@studentsList'):]
tex = fillContent(tex, 'newcommand{\headerLogoScale}{', headerLogoScale)
tex = fillContent(tex, 'newcommand{\headerTitleSize}{', headerTitleSize)
tex = fillContent(tex, 'newcommand{\dept}{', dept)
tex = fillContent(tex, 'newcommand{\durationShort}{', durationShort)
tex = fillContent(tex, 'newcommand{\chapterFontFamily}{', chapterFontFamily)
tex = fillContent(tex, 'newcommand{\coverFontFamily}{', coverFontFamily)
tex = fillContent(tex, 'newcommand{\univName}{', univName)
tex = fillContent(tex, 'newcommand{\univLogoPath}{', univLogoPath)
tex = fillContent(tex, 'newcommand{\univLogoScale}{', univLogoScale)
tex = fillContent(tex, 'newcommand{\course}{', course)
tex = fillContent(tex, 'newcommand{\stream}{', stream)
tex = fillContent(tex, 'newcommand{\deptName}{', deptName)
tex = fillContent(tex, 'newcommand{\collName}{', collName)
tex = fillContent(tex, 'newcommand{\\affiliation}{', affiliation)
tex = fillContent(tex, 'newcommand{\\address}{', address)
tex = fillContent(tex, 'newcommand{\collCoverLogoScale}{', collCoverLogoScale)
tex = fillContent(tex, 'newcommand{\\vspaceInterblock}{', vspaceInterblock)
tex = fillContent(tex, 'newcommand{\\vspaceIntrablock}{', vspaceIntrablock)
tex = fillContent(tex, 'newcommand{\certificateLogoScale}{', certificateLogoScale)
tex = fillContent(tex, 'newcommand{\certificateCourse}{', certificateCourse)
tex = fillContent(tex, 'newcommand{\certificateStream}{', certificateStream)
tex = fillContent(tex, 'newcommand{\certificateUnivName}{', certificateUnivName)
tex = fillContent(tex, 'newcommand{\\abstractFontFamily}{', abstractFontFamily)
insIndex = tex.index('@acknowledgement')
insStr = etree.tostring(root.find('acknowledgement'))
insStr = convertToTex(insStr)
tex = tex[:insIndex] + insStr + tex[insIndex + len('@acknowledgement'):]
insIndex = tex.index('@abstract')
insStr = etree.tostring(root.find('abstract'))
insStr = convertToTex(insStr)
tex = tex[:insIndex] + insStr + tex[insIndex + len('@abstract'):]
insIndex = tex.index('@chapters')
insStr = ''
chapters = root.findall('chapter')
for chapter in chapters:
insStrTemp = etree.tostring(chapter)
insStrTemp = convertToTex('<content>' + insStrTemp + '</content>')
insStr += insStrTemp + '\n'
tex = tex[:insIndex] + insStr + tex[insIndex + len('@chapters'):]
f = open("sample.tex", "w")
f.write(tex)
f.close()
'''
modifying the style file
'''
#modifying the cover page
coverIndex = sty.index("@studentsListCover")
insStrCover = ''
for i in range(len(students)):
if i == 0:
insStrCover += '\\vspace{\\vspaceInterblock}\n\\textbf{\\student' + students[i][0] + ' - \usn' + students[i][0] + '}\n\n'
else:
insStrCover += '\\vspace{\\vspaceIntrablock}\n\\textbf{\\student' + students[i][0] + ' - \usn' + students[i][0] + '}\n\n'
sty = sty[:coverIndex] + insStrCover + sty[coverIndex + len('@studentsListCover'):]
#modifying the certificate
certIndex = sty.index("@studentsListCertificate")
insStrCertificate = ''
for i in range(len(students)):
if i == 0:
insStrCertificate += '\\vspace{\\vspaceInterblock}\n\\textbf{\student' + students[i][0] + ', \usn' + students[i][0] + '}\n\n'
else:
insStrCertificate += '\\vspace{\\vspaceIntrablock}\n\\textbf{\student' + students[i][0] + ', \usn' + students[i][0] + '}\n\n'
print insStrCertificate
sty = sty[:certIndex] + insStrCertificate + sty[certIndex + len('@studentsListCertificate'):]
f = open("sample.sty", "w")
f.write(sty)
f.close()
os.system("pdflatex sample.tex")
os.system("pdflatex sample.tex") #it must be compiled twice in order to get the table of contents updated properly
if __name__ == '__main__':
main()
|
vijeshm/eezyReport
|
eezyReport.py
|
Python
|
mit
| 16,797 | 0.006727 |
from django.contrib import admin
from widgy.admin import WidgyAdmin
from widgy.contrib.page_builder.models import Callout
admin.site.register(Callout, WidgyAdmin)
|
j00bar/django-widgy
|
widgy/contrib/page_builder/admin.py
|
Python
|
apache-2.0
| 165 | 0 |
from django.db import models
from gitireadme.utils import getUploadToPath
import datetime
class Article(models.Model):
name = models.CharField(max_length=255,blank=True,null=True)
path = models.CharField(max_length=255,blank=True,null=True)
class ArticleAlias(models.Model):
repo = models.CharField(max_length=255,blank=True,null=True)
article = models.ForeignKey(Article)
|
gitireadme/gitireadme.server
|
gitireadme/article/models.py
|
Python
|
apache-2.0
| 391 | 0.023018 |
# Copyright 2016 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.
# ==============================================================================
"""Deprecation tests."""
# pylint: disable=unused-import
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.python.platform import test
from tensorflow.python.platform import tf_logging as logging
from tensorflow.python.util import deprecation
class DeprecationTest(test.TestCase):
@test.mock.patch.object(logging, "warning", autospec=True)
def test_silence(self, mock_warning):
date = "2016-07-04"
instructions = "This is how you update..."
@deprecation.deprecated(date, instructions)
def _fn():
pass
_fn()
self.assertEqual(1, mock_warning.call_count)
with deprecation.silence():
_fn()
self.assertEqual(1, mock_warning.call_count)
_fn()
self.assertEqual(2, mock_warning.call_count)
def _assert_subset(self, expected_subset, actual_set):
self.assertTrue(
actual_set.issuperset(expected_subset),
msg="%s is not a superset of %s." % (actual_set, expected_subset))
def test_deprecated_illegal_args(self):
instructions = "This is how you update..."
with self.assertRaisesRegexp(ValueError, "YYYY-MM-DD"):
deprecation.deprecated("", instructions)
with self.assertRaisesRegexp(ValueError, "YYYY-MM-DD"):
deprecation.deprecated("07-04-2016", instructions)
date = "2016-07-04"
with self.assertRaisesRegexp(ValueError, "instructions"):
deprecation.deprecated(date, None)
with self.assertRaisesRegexp(ValueError, "instructions"):
deprecation.deprecated(date, "")
@test.mock.patch.object(logging, "warning", autospec=True)
def test_no_date(self, mock_warning):
date = None
instructions = "This is how you update..."
@deprecation.deprecated(date, instructions)
def _fn(arg0, arg1):
"""fn doc.
Args:
arg0: Arg 0.
arg1: Arg 1.
Returns:
Sum of args.
"""
return arg0 + arg1
self.assertEqual(
"fn doc. (deprecated)"
"\n"
"\nTHIS FUNCTION IS DEPRECATED. It will be removed in a future version."
"\nInstructions for updating:\n%s"
"\n"
"\nArgs:"
"\n arg0: Arg 0."
"\n arg1: Arg 1."
"\n"
"\nReturns:"
"\n Sum of args." % instructions, _fn.__doc__)
# Assert calling new fn issues log warning.
self.assertEqual(3, _fn(1, 2))
self.assertEqual(1, mock_warning.call_count)
(args, _) = mock_warning.call_args
self.assertRegexpMatches(
args[0], r"deprecated and will be removed")
self._assert_subset(set(["in a future version", instructions]),
set(args[1:]))
@test.mock.patch.object(logging, "warning", autospec=True)
def test_static_fn_with_doc(self, mock_warning):
date = "2016-07-04"
instructions = "This is how you update..."
@deprecation.deprecated(date, instructions)
def _fn(arg0, arg1):
"""fn doc.
Args:
arg0: Arg 0.
arg1: Arg 1.
Returns:
Sum of args.
"""
return arg0 + arg1
# Assert function docs are properly updated.
self.assertEqual("_fn", _fn.__name__)
self.assertEqual(
"fn doc. (deprecated)"
"\n"
"\nTHIS FUNCTION IS DEPRECATED. It will be removed after %s."
"\nInstructions for updating:\n%s"
"\n"
"\nArgs:"
"\n arg0: Arg 0."
"\n arg1: Arg 1."
"\n"
"\nReturns:"
"\n Sum of args." % (date, instructions), _fn.__doc__)
# Assert calling new fn issues log warning.
self.assertEqual(3, _fn(1, 2))
self.assertEqual(1, mock_warning.call_count)
(args, _) = mock_warning.call_args
self.assertRegexpMatches(args[0], r"deprecated and will be removed")
self._assert_subset(set(["after " + date, instructions]), set(args[1:]))
@test.mock.patch.object(logging, "warning", autospec=True)
def test_static_fn_with_one_line_doc(self, mock_warning):
date = "2016-07-04"
instructions = "This is how you update..."
@deprecation.deprecated(date, instructions)
def _fn(arg0, arg1):
"""fn doc."""
return arg0 + arg1
# Assert function docs are properly updated.
self.assertEqual("_fn", _fn.__name__)
self.assertEqual(
"fn doc. (deprecated)"
"\n"
"\nTHIS FUNCTION IS DEPRECATED. It will be removed after %s."
"\nInstructions for updating:\n%s" % (date, instructions), _fn.__doc__)
# Assert calling new fn issues log warning.
self.assertEqual(3, _fn(1, 2))
self.assertEqual(1, mock_warning.call_count)
(args, _) = mock_warning.call_args
self.assertRegexpMatches(args[0], r"deprecated and will be removed")
self._assert_subset(set(["after " + date, instructions]), set(args[1:]))
@test.mock.patch.object(logging, "warning", autospec=True)
def test_static_fn_no_doc(self, mock_warning):
date = "2016-07-04"
instructions = "This is how you update..."
@deprecation.deprecated(date, instructions)
def _fn(arg0, arg1):
return arg0 + arg1
# Assert function docs are properly updated.
self.assertEqual("_fn", _fn.__name__)
self.assertEqual(
"DEPRECATED FUNCTION"
"\n"
"\nTHIS FUNCTION IS DEPRECATED. It will be removed after %s."
"\nInstructions for updating:"
"\n%s" % (date, instructions), _fn.__doc__)
# Assert calling new fn issues log warning.
self.assertEqual(3, _fn(1, 2))
self.assertEqual(1, mock_warning.call_count)
(args, _) = mock_warning.call_args
self.assertRegexpMatches(args[0], r"deprecated and will be removed")
self._assert_subset(set(["after " + date, instructions]), set(args[1:]))
@test.mock.patch.object(logging, "warning", autospec=True)
def test_instance_fn_with_doc(self, mock_warning):
date = "2016-07-04"
instructions = "This is how you update..."
class _Object(object):
def __init(self):
pass
@deprecation.deprecated(date, instructions)
def _fn(self, arg0, arg1):
"""fn doc.
Args:
arg0: Arg 0.
arg1: Arg 1.
Returns:
Sum of args.
"""
return arg0 + arg1
# Assert function docs are properly updated.
self.assertEqual(
"fn doc. (deprecated)"
"\n"
"\nTHIS FUNCTION IS DEPRECATED. It will be removed after %s."
"\nInstructions for updating:\n%s"
"\n"
"\nArgs:"
"\n arg0: Arg 0."
"\n arg1: Arg 1."
"\n"
"\nReturns:"
"\n Sum of args." % (date, instructions),
getattr(_Object, "_fn").__doc__)
# Assert calling new fn issues log warning.
self.assertEqual(3, _Object()._fn(1, 2))
self.assertEqual(1, mock_warning.call_count)
(args, _) = mock_warning.call_args
self.assertRegexpMatches(args[0], r"deprecated and will be removed")
self._assert_subset(set(["after " + date, instructions]), set(args[1:]))
@test.mock.patch.object(logging, "warning", autospec=True)
def test_instance_fn_with_one_line_doc(self, mock_warning):
date = "2016-07-04"
instructions = "This is how you update..."
class _Object(object):
def __init(self):
pass
@deprecation.deprecated(date, instructions)
def _fn(self, arg0, arg1):
"""fn doc."""
return arg0 + arg1
# Assert function docs are properly updated.
self.assertEqual(
"fn doc. (deprecated)"
"\n"
"\nTHIS FUNCTION IS DEPRECATED. It will be removed after %s."
"\nInstructions for updating:\n%s" % (date, instructions),
getattr(_Object, "_fn").__doc__)
# Assert calling new fn issues log warning.
self.assertEqual(3, _Object()._fn(1, 2))
self.assertEqual(1, mock_warning.call_count)
(args, _) = mock_warning.call_args
self.assertRegexpMatches(args[0], r"deprecated and will be removed")
self._assert_subset(set(["after " + date, instructions]), set(args[1:]))
@test.mock.patch.object(logging, "warning", autospec=True)
def test_instance_fn_no_doc(self, mock_warning):
date = "2016-07-04"
instructions = "This is how you update..."
class _Object(object):
def __init(self):
pass
@deprecation.deprecated(date, instructions)
def _fn(self, arg0, arg1):
return arg0 + arg1
# Assert function docs are properly updated.
self.assertEqual(
"DEPRECATED FUNCTION"
"\n"
"\nTHIS FUNCTION IS DEPRECATED. It will be removed after %s."
"\nInstructions for updating:"
"\n%s" % (date, instructions), getattr(_Object, "_fn").__doc__)
# Assert calling new fn issues log warning.
self.assertEqual(3, _Object()._fn(1, 2))
self.assertEqual(1, mock_warning.call_count)
(args, _) = mock_warning.call_args
self.assertRegexpMatches(args[0], r"deprecated and will be removed")
self._assert_subset(set(["after " + date, instructions]), set(args[1:]))
def test_prop_wrong_order(self):
with self.assertRaisesRegexp(
ValueError,
"make sure @property appears before @deprecated in your source code"):
# pylint: disable=unused-variable
class _Object(object):
def __init(self):
pass
@deprecation.deprecated("2016-07-04", "Instructions.")
@property
def _prop(self):
return "prop_wrong_order"
@test.mock.patch.object(logging, "warning", autospec=True)
def test_prop_with_doc(self, mock_warning):
date = "2016-07-04"
instructions = "This is how you update..."
class _Object(object):
def __init(self):
pass
@property
@deprecation.deprecated(date, instructions)
def _prop(self):
"""prop doc.
Returns:
String.
"""
return "prop_with_doc"
# Assert function docs are properly updated.
self.assertEqual(
"prop doc. (deprecated)"
"\n"
"\nTHIS FUNCTION IS DEPRECATED. It will be removed after %s."
"\nInstructions for updating:"
"\n%s"
"\n"
"\nReturns:"
"\n String." % (date, instructions), getattr(_Object, "_prop").__doc__)
# Assert calling new fn issues log warning.
self.assertEqual("prop_with_doc", _Object()._prop)
self.assertEqual(1, mock_warning.call_count)
(args, _) = mock_warning.call_args
self.assertRegexpMatches(args[0], r"deprecated and will be removed")
self._assert_subset(set(["after " + date, instructions]), set(args[1:]))
@test.mock.patch.object(logging, "warning", autospec=True)
def test_prop_no_doc(self, mock_warning):
date = "2016-07-04"
instructions = "This is how you update..."
class _Object(object):
def __init(self):
pass
@property
@deprecation.deprecated(date, instructions)
def _prop(self):
return "prop_no_doc"
# Assert function docs are properly updated.
self.assertEqual(
"DEPRECATED FUNCTION"
"\n"
"\nTHIS FUNCTION IS DEPRECATED. It will be removed after %s."
"\nInstructions for updating:"
"\n%s" % (date, instructions), getattr(_Object, "_prop").__doc__)
# Assert calling new fn issues log warning.
self.assertEqual("prop_no_doc", _Object()._prop)
self.assertEqual(1, mock_warning.call_count)
(args, _) = mock_warning.call_args
self.assertRegexpMatches(args[0], r"deprecated and will be removed")
self._assert_subset(set(["after " + date, instructions]), set(args[1:]))
class DeprecatedArgsTest(test.TestCase):
def _assert_subset(self, expected_subset, actual_set):
self.assertTrue(
actual_set.issuperset(expected_subset),
msg="%s is not a superset of %s." % (actual_set, expected_subset))
def test_deprecated_illegal_args(self):
instructions = "This is how you update..."
date = "2016-07-04"
with self.assertRaisesRegexp(ValueError, "YYYY-MM-DD"):
deprecation.deprecated_args("", instructions, "deprecated")
with self.assertRaisesRegexp(ValueError, "YYYY-MM-DD"):
deprecation.deprecated_args("07-04-2016", instructions, "deprecated")
with self.assertRaisesRegexp(ValueError, "instructions"):
deprecation.deprecated_args(date, None, "deprecated")
with self.assertRaisesRegexp(ValueError, "instructions"):
deprecation.deprecated_args(date, "", "deprecated")
with self.assertRaisesRegexp(ValueError, "argument"):
deprecation.deprecated_args(date, instructions)
def test_deprecated_missing_args(self):
date = "2016-07-04"
instructions = "This is how you update..."
def _fn(arg0, arg1, deprecated=None):
return arg0 + arg1 if deprecated else arg1 + arg0
# Assert calls without the deprecated argument log nothing.
with self.assertRaisesRegexp(ValueError, "not present.*\\['missing'\\]"):
deprecation.deprecated_args(date, instructions, "missing")(_fn)
@test.mock.patch.object(logging, "warning", autospec=True)
def test_static_fn_with_doc(self, mock_warning):
date = "2016-07-04"
instructions = "This is how you update..."
@deprecation.deprecated_args(date, instructions, "deprecated")
def _fn(arg0, arg1, deprecated=True):
"""fn doc.
Args:
arg0: Arg 0.
arg1: Arg 1.
deprecated: Deprecated!
Returns:
Sum of args.
"""
return arg0 + arg1 if deprecated else arg1 + arg0
# Assert function docs are properly updated.
self.assertEqual("_fn", _fn.__name__)
self.assertEqual(
"fn doc. (deprecated arguments)"
"\n"
"\nSOME ARGUMENTS ARE DEPRECATED. They will be removed after %s."
"\nInstructions for updating:\n%s"
"\n"
"\nArgs:"
"\n arg0: Arg 0."
"\n arg1: Arg 1."
"\n deprecated: Deprecated!"
"\n"
"\nReturns:"
"\n Sum of args." % (date, instructions), _fn.__doc__)
# Assert calls without the deprecated argument log nothing.
self.assertEqual(3, _fn(1, 2))
self.assertEqual(0, mock_warning.call_count)
# Assert calls with the deprecated argument log a warning.
self.assertEqual(3, _fn(1, 2, True))
self.assertEqual(1, mock_warning.call_count)
(args, _) = mock_warning.call_args
self.assertRegexpMatches(args[0], r"deprecated and will be removed")
self._assert_subset(set(["after " + date, instructions]), set(args[1:]))
@test.mock.patch.object(logging, "warning", autospec=True)
def test_static_fn_with_one_line_doc(self, mock_warning):
date = "2016-07-04"
instructions = "This is how you update..."
@deprecation.deprecated_args(date, instructions, "deprecated")
def _fn(arg0, arg1, deprecated=True):
"""fn doc."""
return arg0 + arg1 if deprecated else arg1 + arg0
# Assert function docs are properly updated.
self.assertEqual("_fn", _fn.__name__)
self.assertEqual(
"fn doc. (deprecated arguments)"
"\n"
"\nSOME ARGUMENTS ARE DEPRECATED. They will be removed after %s."
"\nInstructions for updating:\n%s" % (date, instructions), _fn.__doc__)
# Assert calls without the deprecated argument log nothing.
self.assertEqual(3, _fn(1, 2))
self.assertEqual(0, mock_warning.call_count)
# Assert calls with the deprecated argument log a warning.
self.assertEqual(3, _fn(1, 2, True))
self.assertEqual(1, mock_warning.call_count)
(args, _) = mock_warning.call_args
self.assertRegexpMatches(args[0], r"deprecated and will be removed")
self._assert_subset(set(["after " + date, instructions]), set(args[1:]))
@test.mock.patch.object(logging, "warning", autospec=True)
def test_static_fn_no_doc(self, mock_warning):
date = "2016-07-04"
instructions = "This is how you update..."
@deprecation.deprecated_args(date, instructions, "deprecated")
def _fn(arg0, arg1, deprecated=True):
return arg0 + arg1 if deprecated else arg1 + arg0
# Assert function docs are properly updated.
self.assertEqual("_fn", _fn.__name__)
self.assertEqual(
"DEPRECATED FUNCTION ARGUMENTS"
"\n"
"\nSOME ARGUMENTS ARE DEPRECATED. They will be removed after %s."
"\nInstructions for updating:"
"\n%s" % (date, instructions), _fn.__doc__)
# Assert calls without the deprecated argument log nothing.
self.assertEqual(3, _fn(1, 2))
self.assertEqual(0, mock_warning.call_count)
# Assert calls with the deprecated argument log a warning.
self.assertEqual(3, _fn(1, 2, True))
self.assertEqual(1, mock_warning.call_count)
(args, _) = mock_warning.call_args
self.assertRegexpMatches(args[0], r"deprecated and will be removed")
self._assert_subset(set(["after " + date, instructions]), set(args[1:]))
@test.mock.patch.object(logging, "warning", autospec=True)
def test_varargs(self, mock_warning):
date = "2016-07-04"
instructions = "This is how you update..."
@deprecation.deprecated_args(date, instructions, "deprecated")
def _fn(arg0, arg1, *deprecated):
return arg0 + arg1 if deprecated else arg1 + arg0
# Assert calls without the deprecated argument log nothing.
self.assertEqual(3, _fn(1, 2))
self.assertEqual(0, mock_warning.call_count)
# Assert calls with the deprecated argument log a warning.
self.assertEqual(3, _fn(1, 2, True, False))
self.assertEqual(1, mock_warning.call_count)
(args, _) = mock_warning.call_args
self.assertRegexpMatches(args[0], r"deprecated and will be removed")
self._assert_subset(set(["after " + date, instructions]), set(args[1:]))
@test.mock.patch.object(logging, "warning", autospec=True)
def test_kwargs(self, mock_warning):
date = "2016-07-04"
instructions = "This is how you update..."
@deprecation.deprecated_args(date, instructions, "deprecated")
def _fn(arg0, arg1, **deprecated):
return arg0 + arg1 if deprecated else arg1 + arg0
# Assert calls without the deprecated argument log nothing.
self.assertEqual(3, _fn(1, 2))
self.assertEqual(0, mock_warning.call_count)
# Assert calls with the deprecated argument log a warning.
self.assertEqual(3, _fn(1, 2, a=True, b=False))
self.assertEqual(1, mock_warning.call_count)
(args, _) = mock_warning.call_args
self.assertRegexpMatches(args[0], r"deprecated and will be removed")
self._assert_subset(set(["after " + date, instructions]), set(args[1:]))
@test.mock.patch.object(logging, "warning", autospec=True)
def test_positional_and_named(self, mock_warning):
date = "2016-07-04"
instructions = "This is how you update..."
@deprecation.deprecated_args(date, instructions, "d1", "d2")
def _fn(arg0, d1=None, arg1=2, d2=None):
return arg0 + arg1 if d1 else arg1 + arg0 if d2 else arg0 * arg1
# Assert calls without the deprecated arguments log nothing.
self.assertEqual(2, _fn(1, arg1=2))
self.assertEqual(0, mock_warning.call_count)
# Assert calls with the deprecated arguments log warnings.
self.assertEqual(2, _fn(1, None, 2, d2=False))
self.assertEqual(2, mock_warning.call_count)
(args1, _) = mock_warning.call_args_list[0]
self.assertRegexpMatches(args1[0], r"deprecated and will be removed")
self._assert_subset(set(["after " + date, instructions, "d1"]),
set(args1[1:]))
(args2, _) = mock_warning.call_args_list[1]
self.assertRegexpMatches(args2[0], r"deprecated and will be removed")
self._assert_subset(set(["after " + date, instructions, "d2"]),
set(args2[1:]))
@test.mock.patch.object(logging, "warning", autospec=True)
def test_positional_and_named_with_ok_vals(self, mock_warning):
date = "2016-07-04"
instructions = "This is how you update..."
@deprecation.deprecated_args(date, instructions, ("d1", None),
("d2", "my_ok_val"))
def _fn(arg0, d1=None, arg1=2, d2=None):
return arg0 + arg1 if d1 else arg1 + arg0 if d2 else arg0 * arg1
# Assert calls without the deprecated arguments log nothing.
self.assertEqual(2, _fn(1, arg1=2))
self.assertEqual(0, mock_warning.call_count)
# Assert calls with the deprecated arguments log warnings.
self.assertEqual(2, _fn(1, False, 2, d2=False))
self.assertEqual(2, mock_warning.call_count)
(args1, _) = mock_warning.call_args_list[0]
self.assertRegexpMatches(args1[0], r"deprecated and will be removed")
self._assert_subset(set(["after " + date, instructions, "d1"]),
set(args1[1:]))
(args2, _) = mock_warning.call_args_list[1]
self.assertRegexpMatches(args2[0], r"deprecated and will be removed")
self._assert_subset(set(["after " + date, instructions, "d2"]),
set(args2[1:]))
# Assert calls with the deprecated arguments don't log warnings if
# the value matches the 'ok_val'.
mock_warning.reset_mock()
self.assertEqual(3, _fn(1, None, 2, d2="my_ok_val"))
self.assertEqual(0, mock_warning.call_count)
class DeprecatedArgValuesTest(test.TestCase):
def _assert_subset(self, expected_subset, actual_set):
self.assertTrue(
actual_set.issuperset(expected_subset),
msg="%s is not a superset of %s." % (actual_set, expected_subset))
def test_deprecated_illegal_args(self):
instructions = "This is how you update..."
with self.assertRaisesRegexp(ValueError, "YYYY-MM-DD"):
deprecation.deprecated_arg_values("", instructions, deprecated=True)
with self.assertRaisesRegexp(ValueError, "YYYY-MM-DD"):
deprecation.deprecated_arg_values(
"07-04-2016", instructions, deprecated=True)
date = "2016-07-04"
with self.assertRaisesRegexp(ValueError, "instructions"):
deprecation.deprecated_arg_values(date, None, deprecated=True)
with self.assertRaisesRegexp(ValueError, "instructions"):
deprecation.deprecated_arg_values(date, "", deprecated=True)
with self.assertRaisesRegexp(ValueError, "argument", deprecated=True):
deprecation.deprecated_arg_values(date, instructions)
@test.mock.patch.object(logging, "warning", autospec=True)
def test_static_fn_with_doc(self, mock_warning):
date = "2016-07-04"
instructions = "This is how you update..."
@deprecation.deprecated_arg_values(date, instructions, deprecated=True)
def _fn(arg0, arg1, deprecated=True):
"""fn doc.
Args:
arg0: Arg 0.
arg1: Arg 1.
deprecated: Deprecated!
Returns:
Sum of args.
"""
return arg0 + arg1 if deprecated else arg1 + arg0
# Assert function docs are properly updated.
self.assertEqual("_fn", _fn.__name__)
self.assertEqual(
"fn doc. (deprecated arguments)"
"\n"
"\nSOME ARGUMENTS ARE DEPRECATED. They will be removed after %s."
"\nInstructions for updating:\n%s"
"\n"
"\nArgs:"
"\n arg0: Arg 0."
"\n arg1: Arg 1."
"\n deprecated: Deprecated!"
"\n"
"\nReturns:"
"\n Sum of args." % (date, instructions), _fn.__doc__)
# Assert calling new fn with non-deprecated value logs nothing.
self.assertEqual(3, _fn(1, 2, deprecated=False))
self.assertEqual(0, mock_warning.call_count)
# Assert calling new fn with deprecated value issues log warning.
self.assertEqual(3, _fn(1, 2, deprecated=True))
self.assertEqual(1, mock_warning.call_count)
(args, _) = mock_warning.call_args
self.assertRegexpMatches(args[0], r"deprecated and will be removed")
self._assert_subset(set(["after " + date, instructions]), set(args[1:]))
# Assert calling new fn with default deprecated value issues log warning.
self.assertEqual(3, _fn(1, 2))
self.assertEqual(2, mock_warning.call_count)
@test.mock.patch.object(logging, "warning", autospec=True)
def test_static_fn_with_one_line_doc(self, mock_warning):
date = "2016-07-04"
instructions = "This is how you update..."
@deprecation.deprecated_arg_values(date, instructions, deprecated=True)
def _fn(arg0, arg1, deprecated=True):
"""fn doc."""
return arg0 + arg1 if deprecated else arg1 + arg0
# Assert function docs are properly updated.
self.assertEqual("_fn", _fn.__name__)
self.assertEqual(
"fn doc. (deprecated arguments)"
"\n"
"\nSOME ARGUMENTS ARE DEPRECATED. They will be removed after %s."
"\nInstructions for updating:\n%s" % (date, instructions), _fn.__doc__)
# Assert calling new fn with non-deprecated value logs nothing.
self.assertEqual(3, _fn(1, 2, deprecated=False))
self.assertEqual(0, mock_warning.call_count)
# Assert calling new fn with deprecated value issues log warning.
self.assertEqual(3, _fn(1, 2, deprecated=True))
self.assertEqual(1, mock_warning.call_count)
(args, _) = mock_warning.call_args
self.assertRegexpMatches(args[0], r"deprecated and will be removed")
self._assert_subset(set(["after " + date, instructions]), set(args[1:]))
# Assert calling new fn with default deprecated value issues log warning.
self.assertEqual(3, _fn(1, 2))
self.assertEqual(2, mock_warning.call_count)
@test.mock.patch.object(logging, "warning", autospec=True)
def test_static_fn_no_doc(self, mock_warning):
date = "2016-07-04"
instructions = "This is how you update..."
@deprecation.deprecated_arg_values(date, instructions, deprecated=True)
def _fn(arg0, arg1, deprecated=True):
return arg0 + arg1 if deprecated else arg1 + arg0
# Assert function docs are properly updated.
self.assertEqual("_fn", _fn.__name__)
self.assertEqual(
"DEPRECATED FUNCTION ARGUMENTS"
"\n"
"\nSOME ARGUMENTS ARE DEPRECATED. They will be removed after %s."
"\nInstructions for updating:"
"\n%s" % (date, instructions), _fn.__doc__)
# Assert calling new fn with non-deprecated value logs nothing.
self.assertEqual(3, _fn(1, 2, deprecated=False))
self.assertEqual(0, mock_warning.call_count)
# Assert calling new fn issues log warning.
self.assertEqual(3, _fn(1, 2, deprecated=True))
self.assertEqual(1, mock_warning.call_count)
(args, _) = mock_warning.call_args
self.assertRegexpMatches(args[0], r"deprecated and will be removed")
self._assert_subset(set(["after " + date, instructions]), set(args[1:]))
# Assert calling new fn with default deprecated value issues log warning.
self.assertEqual(3, _fn(1, 2))
self.assertEqual(2, mock_warning.call_count)
class DeprecationArgumentsTest(test.TestCase):
def testDeprecatedArgumentLookup(self):
good_value = 3
self.assertEqual(
deprecation.deprecated_argument_lookup("val_new", good_value, "val_old",
None), good_value)
self.assertEqual(
deprecation.deprecated_argument_lookup("val_new", None, "val_old",
good_value), good_value)
with self.assertRaisesRegexp(ValueError,
"Cannot specify both 'val_old' and 'val_new'"):
self.assertEqual(
deprecation.deprecated_argument_lookup("val_new", good_value,
"val_old", good_value),
good_value)
def testRewriteArgumentDocstring(self):
docs = """Add `a` and `b`
Args:
a: first arg
b: second arg
"""
new_docs = deprecation.rewrite_argument_docstring(
deprecation.rewrite_argument_docstring(docs, "a", "left"), "b", "right")
new_docs_ref = """Add `left` and `right`
Args:
left: first arg
right: second arg
"""
self.assertEqual(new_docs, new_docs_ref)
if __name__ == "__main__":
test.main()
|
npuichigo/ttsflow
|
third_party/tensorflow/tensorflow/python/util/deprecation_test.py
|
Python
|
apache-2.0
| 28,547 | 0.004134 |
# coding=UTF-8
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
#import tornado
from tornado import ioloop , web , httpserver , websocket , options
#import handler function
import handler
import os
#set server settings
server_settings = {
"static_path": os.path.join(os.path.dirname(__file__), "static"),
"xsrf_cookies": True,
"autoreload": True,
#"login_url": "/accounts/login",
"debug":True,
"template_path":os.path.join(os.path.dirname(__file__),"templates"),
}
#the handlers list
handlers=[
(r"/?",handler.MainHandler),
(r"/upload",handler.WavFileHandler)
]
options.define("port", default=8080, help="the application will be run on the given port", type=int)
if __name__ == "__main__":
options.parse_command_line()
app_server = httpserver.HTTPServer(web.Application(handlers,**server_settings))
app_server.listen(options.options.port)
ioloop.IOLoop.current().start()
|
ken1277725/pythonweb-STT
|
server/server.py
|
Python
|
mit
| 1,001 | 0.034965 |
"""
Copyright 2013 Steven Diamond
This file is part of CVXPY.
CVXPY 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.
CVXPY is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with CVXPY. If not, see <http://www.gnu.org/licenses/>.
"""
from cvxpy.lin_ops.lin_utils import *
from cvxpy.lin_ops.lin_op import *
from cvxpy.expressions.constants import Parameter
import cvxpy.interface as intf
import numpy as np
import scipy.sparse as sp
import unittest
from cvxpy.tests.base_test import BaseTest
import sys
PY2 = sys.version_info < (3, 0)
class test_lin_ops(BaseTest):
""" Unit tests for the lin_ops module. """
def test_variables(self):
"""Test creating a variable.
"""
var = create_var((5, 4), var_id=1)
self.assertEqual(var.size, (5, 4))
self.assertEqual(var.data, 1)
self.assertEqual(len(var.args), 0)
self.assertEqual(var.type, VARIABLE)
def test_param(self):
"""Test creating a parameter.
"""
A = Parameter(5, 4)
var = create_param(A, (5, 4))
self.assertEqual(var.size, (5, 4))
self.assertEqual(len(var.args), 0)
self.assertEqual(var.type, PARAM)
def test_constant(self):
"""Test creating a constant.
"""
# Scalar constant.
size = (1, 1)
mat = create_const(1.0, size)
self.assertEqual(mat.size, size)
self.assertEqual(len(mat.args), 0)
self.assertEqual(mat.type, SCALAR_CONST)
assert mat.data == 1.0
# Dense matrix constant.
size = (5, 4)
mat = create_const(np.ones(size), size)
self.assertEqual(mat.size, size)
self.assertEqual(len(mat.args), 0)
self.assertEqual(mat.type, DENSE_CONST)
assert (mat.data == np.ones(size)).all()
# Sparse matrix constant.
size = (5, 5)
mat = create_const(sp.eye(5), size, sparse=True)
self.assertEqual(mat.size, size)
self.assertEqual(len(mat.args), 0)
self.assertEqual(mat.type, SPARSE_CONST)
assert (mat.data.todense() == sp.eye(5).todense()).all()
def test_add_expr(self):
"""Test adding lin expr.
"""
size = (5, 4)
x = create_var(size)
y = create_var(size)
# Expanding dict.
add_expr = sum_expr([x, y])
self.assertEqual(add_expr.size, size)
assert len(add_expr.args) == 2
def test_get_vars(self):
"""Test getting vars from an expression.
"""
size = (5, 4)
x = create_var(size)
y = create_var(size)
A = create_const(np.ones(size), size)
# Expanding dict.
add_expr = sum_expr([x, y, A])
vars_ = get_expr_vars(add_expr)
ref = [(x.data, size), (y.data, size)]
if PY2:
self.assertItemsEqual(vars_, ref)
else:
self.assertCountEqual(vars_, ref)
def test_neg_expr(self):
"""Test negating an expression.
"""
size = (5, 4)
var = create_var(size)
expr = neg_expr(var)
assert len(expr.args) == 1
self.assertEqual(expr.size, size)
self.assertEqual(expr.type, NEG)
def test_eq_constr(self):
"""Test creating an equality constraint.
"""
size = (5, 5)
x = create_var(size)
y = create_var(size)
lh_expr = sum_expr([x, y])
value = np.ones(size)
rh_expr = create_const(value, size)
constr = create_eq(lh_expr, rh_expr)
self.assertEqual(constr.size, size)
vars_ = get_expr_vars(constr.expr)
ref = [(x.data, size), (y.data, size)]
if PY2:
self.assertItemsEqual(vars_, ref)
else:
self.assertCountEqual(vars_, ref)
def test_leq_constr(self):
"""Test creating a less than or equal constraint.
"""
size = (5, 5)
x = create_var(size)
y = create_var(size)
lh_expr = sum_expr([x, y])
value = np.ones(size)
rh_expr = create_const(value, size)
constr = create_leq(lh_expr, rh_expr)
self.assertEqual(constr.size, size)
vars_ = get_expr_vars(constr.expr)
ref = [(x.data, size), (y.data, size)]
if PY2:
self.assertItemsEqual(vars_, ref)
else:
self.assertCountEqual(vars_, ref)
def test_sum_entries(self):
"""Test sum entries op.
"""
size = (5, 5)
x = create_var(size)
expr = sum_entries(x)
self.assertEqual(expr.size, (1, 1))
self.assertEqual(len(expr.args), 1)
self.assertEqual(expr.type, lo.SUM_ENTRIES)
|
sdpython/cvxpy
|
cvxpy/tests/test_lin_ops.py
|
Python
|
gpl-3.0
| 5,078 | 0 |
########################################
# Automatically generated, do not edit.
########################################
from pyvisdk.thirdparty import Enum
VirtualDiskAdapterType = Enum(
'busLogic',
'ide',
'lsiLogic',
)
|
xuru/pyvisdk
|
pyvisdk/enums/virtual_disk_adapter_type.py
|
Python
|
mit
| 239 | 0 |
"""
A Python implementation of the _bh_ Olden benchmark.
The Olden benchmark implements the Barnes-Hut benchmark
that is decribed in:
J. Barnes and P. Hut, "A hierarchical o(N log N) force-calculation algorithm",
Nature, 324:446-449, Dec. 1986
The original code in the Olden benchmark suite is derived from the
ftp://hubble.ifa.hawaii.edu/pub/barnes/treecode
source distributed by Barnes.
This code comes from the third Java version.
This uses copy() instead of Vec3.clone(), and it's adapted for ShedSkin.
"""
from time import clock
from sys import stderr, maxint, argv
from copy import copy
from math import sqrt, pi, floor
class Random(object):
"""
Basic uniform random generator: Minimal Standard in Park and
Miller (1988): "Random Number Generators: Good Ones Are Hard to
Find", Comm. of the ACM, 31, 1192-1201.
Parameters: m = 2^31-1, a=48271.
Adapted from Pascal code by Jesper Lund:
http:#www.gnu-pascal.de/crystal/gpc/en/mail1390.html
"""
__slots__ = ["seed"]
m = maxint
a = 48271
q = m / a
r = m % a
def __init__(self, the_seed):
self.seed = the_seed
def uniform(self, min, max):
k = self.seed / Random.q
self.seed = Random.a * (self.seed - k * Random.q) - Random.r * k
if self.seed < 1:
self.seed += Random.m
r = float(self.seed) / Random.m
return r * (max - min) + min
class Vec3(object):
"""
A class representing a three dimensional vector that implements
several math operations. To improve speed we implement the
vector as an array of doubles rather than use the exising
code in the java.util.class.
"""
__slots__ = ["d0", "d1", "d2"]
# The number of dimensions in the vector
NDIM = 3
def __init__(self):
"""Construct an empty 3 dimensional vector for use in Barnes-Hut algorithm."""
self.d0 = 0.0
self.d1 = 0.0
self.d2 = 0.0
def __getitem__(self, i):
"""
Return the value at the i'th index of the vector.
@param i the vector index
@return the value at the i'th index of the vector.
"""
if i == 0:
return self.d0
elif i == 1:
return self.d1
else:
return self.d2
def __setitem__(self, i, v):
"""
Set the value of the i'th index of the vector.
@param i the vector index
@param v the value to store
"""
if i == 0:
self.d0 = v
elif i == 1:
self.d1 = v
else:
self.d2 = v
def __iadd__(self, u):
"""
Add two vectors and the result is placed in self vector.
@param u the other operand of the addition
"""
self.d0 += u.d0
self.d1 += u.d1
self.d2 += u.d2
return self
def __isub__(self, u):
"""
Subtract two vectors and the result is placed in self vector.
This vector contain the first operand.
@param u the other operand of the subtraction.
"""
self.d0 -= u.d0
self.d1 -= u.d1
self.d2 -= u.d2
return self
def __imul__(self, s):
"""
Multiply the vector times a scalar.
@param s the scalar value
"""
self.d0 *= s
self.d1 *= s
self.d2 *= s
return self
def __idiv__(self, s):
"""
Divide each element of the vector by a scalar value.
@param s the scalar value.
"""
self.d0 /= s
self.d1 /= s
self.d2 /= s
return self
def add_scalar(self, u, s):
self.d0 = u.d0 + s
self.d1 = u.d1 + s
self.d2 = u.d2 + s
def subtraction2(self, u, v):
"""
Subtract two vectors and the result is placed in self vector.
@param u the first operand of the subtraction.
@param v the second opernd of the subtraction
"""
self.d0 = u.d0 - v.d0
self.d1 = u.d1 - v.d1
self.d2 = u.d2 - v.d2
def mult_scalar2(self, u, s):
"""
Multiply the vector times a scalar and place the result in self vector.
@param u the vector
@param s the scalar value
"""
self.d0 = u.d0 * s
self.d1 = u.d1 * s
self.d2 = u.d2 * s
def dot(self):
"""
Return the dot product of a vector.
@return the dot product of a vector.
"""
return self.d0 * self.d0 + self.d1 * self.d1 + self.d2 * self.d2
def __repr__(self):
return "%.17f %.17f %.17f " % (self.d0, self.d1, self.d2)
class HG(object):
"""
A sub class which is used to compute and save information during the
gravity computation phase.
"""
__slots__ = ["pskip", "pos0", "phi0", "acc0"]
def __init__(self, b, p):
"""
Create a object.
@param b the body object
@param p a vector that represents the body
"""
# Body to skip in force evaluation
self.pskip = b
# Poat which to evaluate field
self.pos0 = copy(p)
# Computed potential at pos0
self.phi0 = 0.0
# computed acceleration at pos0
self.acc0 = Vec3()
class Node(object):
"""A class that represents the common fields of a cell or body data structure."""
# highest bit of coord
IMAX = 1073741824
# potential softening parameter
EPS = 0.05
def __init__(self):
"""Construct an empty node"""
self.mass = 0.0 # mass of the node
self.pos = Vec3() # Position of the node
def load_tree(self, p, xpic, l, root):
raise NotImplementedError()
def hack_cofm(self):
raise NotImplementedError()
def walk_sub_tree(self, dsq, hg):
raise NotImplementedError()
@staticmethod
def old_sub_index(ic, l):
i = 0
for k in xrange(Vec3.NDIM):
if (int(ic[k]) & l) != 0:
i += Cell.NSUB >> (k + 1)
return i
def __repr__(self):
return "%f : %f" % (self.mass, self.pos)
def grav_sub(self, hg):
"""Compute a single body-body or body-cell interaction"""
dr = Vec3()
dr.subtraction2(self.pos, hg.pos0)
drsq = dr.dot() + (Node.EPS * Node.EPS)
drabs = sqrt(drsq)
phii = self.mass / drabs
hg.phi0 -= phii
mor3 = phii / drsq
dr *= mor3
hg.acc0 += dr
return hg
class Body(Node):
"""A class used to representing particles in the N-body simulation."""
def __init__(self):
"""Create an empty body."""
Node.__init__(self)
self.vel = Vec3()
self.acc = Vec3()
self.new_acc = Vec3()
self.phi = 0.0
def expand_box(self, tree, nsteps):
"""
Enlarge cubical "box", salvaging existing tree structure.
@param tree the root of the tree.
@param nsteps the current time step
"""
rmid = Vec3()
inbox = self.ic_test(tree)
while not inbox:
rsize = tree.rsize
rmid.add_scalar(tree.rmin, 0.5 * rsize)
for k in xrange(Vec3.NDIM):
if self.pos[k] < rmid[k]:
rmin = tree.rmin[k]
tree.rmin[k] = rmin - rsize
tree.rsize = 2.0 * rsize
if tree.root is not None:
ic = tree.int_coord(rmid)
if ic is None:
raise Exception("Value is out of bounds")
k = Node.old_sub_index(ic, Node.IMAX >> 1)
newt = Cell()
newt.subp[k] = tree.root
tree.root = newt
inbox = self.ic_test(tree)
def ic_test(self, tree):
"""Check the bounds of the body and return True if it isn't in the correct bounds."""
pos0 = self.pos[0]
pos1 = self.pos[1]
pos2 = self.pos[2]
# by default, it is in bounds
result = True
xsc = (pos0 - tree.rmin[0]) / tree.rsize
if not (0.0 < xsc and xsc < 1.0):
result = False
xsc = (pos1 - tree.rmin[1]) / tree.rsize
if not (0.0 < xsc and xsc < 1.0):
result = False
xsc = (pos2 - tree.rmin[2]) / tree.rsize
if not (0.0 < xsc and xsc < 1.0):
result = False
return result
def load_tree(self, p, xpic, l, tree):
"""
Descend and insert particle. We're at a body so we need to
create a cell and attach self body to the cell.
@param p the body to insert
@param xpic
@param l
@param tree the root of the data structure
@return the subtree with the body inserted
"""
# create a Cell
retval = Cell()
si = self.sub_index(tree, l)
# attach self node to the cell
retval.subp[si] = self
# move down one level
si = Node.old_sub_index(xpic, l)
rt = retval.subp[si]
if rt is not None:
retval.subp[si] = rt.load_tree(p, xpic, l >> 1, tree)
else:
retval.subp[si] = p
return retval
def hack_cofm(self):
"""
Descend tree finding center of mass coordinates
@return the mass of self node
"""
return self.mass
def sub_index(self, tree, l):
"""
Determine which subcell to select.
Combination of int_coord and old_sub_index.
@param t the root of the tree
"""
xp = Vec3()
xsc = (self.pos[0] - tree.rmin[0]) / tree.rsize
xp[0] = floor(Node.IMAX * xsc)
xsc = (self.pos[1] - tree.rmin[1]) / tree.rsize
xp[1] = floor(Node.IMAX * xsc)
xsc = (self.pos[2] - tree.rmin[2]) / tree.rsize
xp[2] = floor(Node.IMAX * xsc)
i = 0
for k in xrange(Vec3.NDIM):
if (int(xp[k]) & l) != 0:
i += Cell.NSUB >> (k + 1)
return i
def hack_gravity(self, rsize, root):
"""
Evaluate gravitational field on the body.
The original olden version calls a routine named "walkscan",
but we use the same name that is in the Barnes code.
"""
hg = HG(self, self.pos)
hg = root.walk_sub_tree(rsize * rsize, hg)
self.phi = hg.phi0
self.new_acc = hg.acc0
def walk_sub_tree(self, dsq, hg):
"""Recursively walk the tree to do hackwalk calculation"""
if self != hg.pskip:
hg = self.grav_sub(hg)
return hg
def __repr__(self):
"""
Return a string represenation of a body.
@return a string represenation of a body.
"""
return "Body " + Node.__repr__(self)
class Cell(Node):
"""A class used to represent internal nodes in the tree"""
# subcells per cell
NSUB = 8 # 1 << NDIM
def __init__(self):
# The children of self cell node. Each entry may contain either
# another cell or a body.
Node.__init__(self)
self.subp = [None] * Cell.NSUB
def load_tree(self, p, xpic, l, tree):
"""
Descend and insert particle. We're at a cell so
we need to move down the tree.
@param p the body to insert into the tree
@param xpic
@param l
@param tree the root of the tree
@return the subtree with the body inserted
"""
# move down one level
si = Node.old_sub_index(xpic, l)
rt = self.subp[si]
if rt is not None:
self.subp[si] = rt.load_tree(p, xpic, l >> 1, tree)
else:
self.subp[si] = p
return self
def hack_cofm(self):
"""
Descend tree finding center of mass coordinates
@return the mass of self node
"""
mq = 0.0
tmp_pos = Vec3()
tmpv = Vec3()
for i in xrange(Cell.NSUB):
r = self.subp[i]
if r is not None:
mr = r.hack_cofm()
mq = mr + mq
tmpv.mult_scalar2(r.pos, mr)
tmp_pos += tmpv
self.mass = mq
self.pos = tmp_pos
self.pos /= self.mass
return mq
def walk_sub_tree(self, dsq, hg):
"""Recursively walk the tree to do hackwalk calculation"""
if self.subdiv_p(dsq, hg):
for k in xrange(Cell.NSUB):
r = self.subp[k]
if r is not None:
hg = r.walk_sub_tree(dsq / 4.0, hg)
else:
hg = self.grav_sub(hg)
return hg
def subdiv_p(self, dsq, hg):
"""
Decide if the cell is too close to accept as a single term.
@return True if the cell is too close.
"""
dr = Vec3()
dr.subtraction2(self.pos, hg.pos0)
drsq = dr.dot()
# in the original olden version drsp is multiplied by 1.0
return drsq < dsq
def __repr__(self):
"""
Return a string represenation of a cell.
@return a string represenation of a cell.
"""
return "Cell " + Node.__repr__(self)
class Tree:
"""
A class that represents the root of the data structure used
to represent the N-bodies in the Barnes-Hut algorithm.
"""
def __init__(self):
"""Construct the root of the data structure that represents the N-bodies."""
self.bodies = [] # The complete list of bodies that have been created.
self.rmin = Vec3()
self.rsize = -2.0 * -2.0
self.root = None # A reference to the root node.
self.rmin[0] = -2.0
self.rmin[1] = -2.0
self.rmin[2] = -2.0
def create_test_data(self, nbody):
"""
Create the testdata used in the benchmark.
@param nbody the number of bodies to create
"""
cmr = Vec3()
cmv = Vec3()
rsc = 3.0 * pi / 16.0
vsc = sqrt(1.0 / rsc)
seed = 123
rnd = Random(seed)
self.bodies = [None] * nbody
aux_mass = 1.0 / float(nbody)
for i in xrange(nbody):
p = Body()
self.bodies[i] = p
p.mass = aux_mass
t1 = rnd.uniform(0.0, 0.999)
t1 = pow(t1, (-2.0 / 3.0)) - 1.0
r = 1.0 / sqrt(t1)
coeff = 4.0
for k in xrange(Vec3.NDIM):
r = rnd.uniform(0.0, 0.999)
p.pos[k] = coeff * r
cmr += p.pos
while True:
x = rnd.uniform(0.0, 1.0)
y = rnd.uniform(0.0, 0.1)
if y <= (x * x * pow(1.0 - x * x, 3.5)):
break
v = sqrt(2.0) * x / pow(1 + r * r, 0.25)
rad = vsc * v
while True:
for k in xrange(Vec3.NDIM):
p.vel[k] = rnd.uniform(-1.0, 1.0)
rsq = p.vel.dot()
if rsq <= 1.0:
break
rsc1 = rad / sqrt(rsq)
p.vel *= rsc1
cmv += p.vel
cmr /= float(nbody)
cmv /= float(nbody)
for b in self.bodies:
b.pos -= cmr
b.vel -= cmv
def step_system(self, nstep):
"""
Advance the N-body system one time-step.
@param nstep the current time step
"""
# free the tree
self.root = None
self.make_tree(nstep)
# compute the gravity for all the particles
for b in reversed(self.bodies):
b.hack_gravity(self.rsize, self.root)
Tree.vp(self.bodies, nstep)
def make_tree(self, nstep):
"""
Initialize the tree structure for hack force calculation.
@param nsteps the current time step
"""
for q in reversed(self.bodies):
if q.mass != 0.0:
q.expand_box(self, nstep)
xqic = self.int_coord(q.pos)
if self.root is None:
self.root = q
else:
self.root = self.root.load_tree(q, xqic, Node.IMAX >> 1, self)
self.root.hack_cofm()
def int_coord(self, vp):
"""
Compute integerized coordinates.
@return the coordinates or None if rp is out of bounds
"""
xp = Vec3()
xsc = (vp[0] - self.rmin[0]) / self.rsize
if 0.0 <= xsc and xsc < 1.0:
xp[0] = floor(Node.IMAX * xsc)
else:
return None
xsc = (vp[1] - self.rmin[1]) / self.rsize
if 0.0 <= xsc and xsc < 1.0:
xp[1] = floor(Node.IMAX * xsc)
else:
return None
xsc = (vp[2] - self.rmin[2]) / self.rsize
if 0.0 <= xsc and xsc < 1.0:
xp[2] = floor(Node.IMAX * xsc)
else:
return None
return xp
@staticmethod
def vp(bodies, nstep):
dacc = Vec3()
dvel = Vec3()
dthf = 0.5 * BH.DTIME
for b in reversed(bodies):
acc1 = copy(b.new_acc)
if nstep > 0:
dacc.subtraction2(acc1, b.acc)
dvel.mult_scalar2(dacc, dthf)
dvel += b.vel
b.vel = copy(dvel)
b.acc = copy(acc1)
dvel.mult_scalar2(b.acc, dthf)
vel1 = copy(b.vel)
vel1 += dvel
dpos = copy(vel1)
dpos *= BH.DTIME
dpos += b.pos
b.pos = copy(dpos)
vel1 += dvel
b.vel = copy(vel1)
class BH(object):
DTIME = 0.0125
TSTOP = 2.0
# The user specified number of bodies to create.
nbody = 0
# The maximum number of time steps to take in the simulation
nsteps = 10
# Should we prinformation messsages
print_msgs = False
# Should we prdetailed results
print_results = False
@staticmethod
def main(args):
BH.parse_cmd_line(args)
if BH.print_msgs:
print "nbody =", BH.nbody
start0 = clock()
root = Tree()
root.create_test_data(BH.nbody)
end0 = clock()
if BH.print_msgs:
print "Bodies created"
start1 = clock()
tnow = 0.0
i = 0
while (tnow < BH.TSTOP + 0.1 * BH.DTIME) and i < BH.nsteps:
root.step_system(i)
i += 1
tnow += BH.DTIME
end1 = clock()
if BH.print_results:
for j, b in enumerate(root.bodies):
print "body %d: %s" % (j, b.pos)
if BH.print_msgs:
print "Build Time %.3f" % (end0 - start0)
print "Compute Time %.3f" % (end1 - start1)
print "Total Time %.3f" % (end1 - start0)
print "Done!"
@staticmethod
def parse_cmd_line(args):
i = 1
while i < len(args) and args[i].startswith("-"):
arg = args[i]
i += 1
# check for options that require arguments
if arg == "-b":
if i < len(args):
BH.nbody = int(args[i])
i += 1
else:
raise Exception("-l requires the number of levels")
elif arg == "-s":
if i < len(args):
BH.nsteps = int(args[i])
i += 1
else:
raise Exception("-l requires the number of levels")
elif arg == "-m":
BH.print_msgs = True
elif arg == "-p":
BH.print_results = True
elif arg == "-h":
BH.usage()
if BH.nbody == 0:
BH.usage()
@staticmethod
def usage():
"""The usage routine which describes the program options."""
print >>stderr, "usage: python bh.py -b <size> [-s <steps>] [-p] [-m] [-h]"
print >>stderr, " -b the number of bodies"
print >>stderr, " -s the max. number of time steps (default=10)"
print >>stderr, " -p (print detailed results)"
print >>stderr, " -m (print information messages"
print >>stderr, " -h (self message)"
raise SystemExit()
if __name__ == '__main__':
BH.main(argv)
|
shedskin/shedskin
|
examples/bh.py
|
Python
|
gpl-3.0
| 20,915 | 0.001004 |
from random import sample
import os
songList = []
songDict = None
userPlayList = []
directory = ''
def getSongs(name, limit):
global songList
global directory
print('*'*30)
print('* Minerando ', str(limit), ' músicas *')
print('*'*30)
status = 0
if not os.path.exists(directory):
os.makedirs(directory)
toSaveFile = open(
'config/data/oneMillionSongs/sets/' + str(name) + '/songs.csv',
'w+'
)
toSaveFile.write('id,title\n')
songSet = sample(
set(
open(
'config/data/oneMillionSongs/originalCleanEntry/songs.csv',
'r+'
)
), limit
)
for line in songSet:
if (status % 1000 == 0):
print ("-> [", status, "]")
lineSplit = line.split(',')
songList.append(lineSplit[0])
toSaveFile.write(lineSplit[0] + ',' + lineSplit[1] + '\n')
if (status > limit):
break
status += 1
print ('- Total de Musicas: ', len(songList))
toSaveFile.close()
print ('- Finalizando o script!')
def getPlayCount(name, limit, userLimit):
global songDict
global userPlayList
global directory
print ('*'*30)
print ('* Pegando Lista de pessoas que ouviram as musicas *')
print ('*'*30)
status = 0
if not os.path.exists(directory):
os.makedirs(directory)
toSaveFile = open(
'config/data/oneMillionSongs/sets/' + str(name) + '/playCount.csv',
'w+'
)
toSaveFile.write('user_id,song_id,play_count\n')
for line in open(
'config/data/oneMillionSongs/originalCleanEntry/playCount.csv',
'r+'
):
status += 1
if status == 1:
continue
if (status % 1000 == 0):
print ("-> [", status, "]")
lineSplit = line.split(',')
if (lineSplit[1] not in songDict):
continue
if (len(userPlayList) >= userLimit and lineSplit[0] not in userPlayList):
continue
if lineSplit[0] not in userPlayList:
userPlayList.append(lineSplit[0])
toSaveFile.write(line)
userDict = set(userPlayList)
print ('- Total de usuarios: ', len(userDict))
usersToSaveFile = open(
'config/data/oneMillionSongs/sets/' + str(name) + '/users.csv',
'w+'
)
usersToSaveFile.write('id\n')
for user in userDict:
usersToSaveFile.write(user + "\n")
toSaveFile.close()
usersToSaveFile.close()
print ('- Finalizando o script!')
def start(name, limit, userLimit=None):
global directory
global songDict
directory = 'config/data/oneMillionSongs/sets/' + str(name)
getSongs(name, limit)
songDict = set(songList)
getPlayCount(name, limit, userLimit)
##########
def main():
start(name="thousand", limit=1000)
start(name="two_thousand", limit=2000)
start(name="three_thousand", limit=3000)
start(name="ten_thousand", limit=10000)
|
DiegoCorrea/ouvidoMusical
|
config/data/oneMillionSongs/mining.py
|
Python
|
mit
| 2,978 | 0.003359 |
# -*- coding: utf-8 -*-
from django.core import exceptions
from django.utils.importlib import import_module
__author__ = 'jb'
MIGRATION_MANAGERS = {}
DEFAULT_MANAGER = None
def load_manager(path):
"""
Code taken from django.
Copyright (c) Django Software Foundation and individual contributors.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of Django nor the names of its contributors 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.
"""
try:
mw_module, mw_classname = path.rsplit('.', 1)
except ValueError:
raise exceptions.ImproperlyConfigured('%s isn\'t a manager module' % path)
try:
mod = import_module(mw_module)
except ImportError, e:
raise exceptions.ImproperlyConfigured('Error importing manager %s: "%s"' % (mw_module, e))
try:
manager_instance = getattr(mod, mw_classname)
except AttributeError:
raise exceptions.ImproperlyConfigured('Manager module "%s" does not define a "%s" object' % (mw_module, mw_classname))
return manager_instance
def initialize():
from django.conf import settings
global MIGRATION_MANAGERS, DEFAULT_MANAGER
MANAGERS = getattr(settings, "MIGRATION_MANAGERS", None)
if MANAGERS is not None:
for k, v in MANAGERS:
MIGRATION_MANAGERS[k] = load_manager(v)
DEFAULT_MANAGER = MIGRATION_MANAGERS[MANAGERS[0][0]]
initialize()
|
jbzdak/migration_manager
|
migration_manager/manager.py
|
Python
|
bsd-2-clause
| 2,915 | 0.009262 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
""" A script to manage development tasks """
from __future__ import (
absolute_import, division, print_function, with_statement,
unicode_literals)
from os import path as p
from manager import Manager
from subprocess import call
manager = Manager()
_basedir = p.dirname(__file__)
@manager.command
def clean():
"""Remove Python file and build artifacts"""
call(p.join(_basedir, 'helpers', 'clean'), shell=True)
@manager.command
def check():
"""Check staged changes for lint errors"""
call(p.join(_basedir, 'helpers', 'check-stage'), shell=True)
@manager.arg('where', 'w', help='Modules to check')
@manager.command
def lint(where=None):
"""Check style with flake8"""
call('flake8 %s' % (where if where else ''), shell=True)
@manager.command
def pipme():
"""Install requirements.txt"""
call('pip install -r requirements.txt', shell=True)
@manager.command
def require():
"""Create requirements.txt"""
cmd = 'pip freeze -l | grep -vxFf dev-requirements.txt > requirements.txt'
call(cmd, shell=True)
@manager.arg('where', 'w', help='test path', default=None)
@manager.arg(
'stop', 'x', help='Stop after first error', type=bool, default=False)
@manager.command
def test(where=None, stop=False):
"""Run nose and script tests"""
opts = '-xv' if stop else '-v'
opts += 'w %s' % where if where else ''
call([p.join(_basedir, 'helpers', 'test'), opts])
@manager.command
def register():
"""Register package with PyPI"""
call('python %s register' % p.join(_basedir, 'setup.py'), shell=True)
@manager.command
def release():
"""Package and upload a release"""
sdist()
wheel()
upload()
@manager.command
def build():
"""Create a source distribution and wheel package"""
sdist()
wheel()
@manager.command
def upload():
"""Upload distribution files"""
call('twine upload %s' % p.join(_basedir, 'dist', '*'), shell=True)
@manager.command
def sdist():
"""Create a source distribution package"""
call(p.join(_basedir, 'helpers', 'srcdist'), shell=True)
@manager.command
def wheel():
"""Create a wheel package"""
call(p.join(_basedir, 'helpers', 'wheel'), shell=True)
if __name__ == '__main__':
manager.main()
|
reubano/ckanutils
|
manage.py
|
Python
|
mit
| 2,296 | 0 |
"""
Unique place for all runscripts to set the module path.
(i.e. if you have a copy of TEMareels in some place on your
hard disk but not in PYTHONPATH).
NOTE: it is recommended to keep a copy of all TEMareels
module files with your data/analysis, as future versions
will be not necessarily backwards compatible.
Copyright (c) 2013, rhambach.
This file is part of the TEMareels package and released
under the MIT-Licence. See LICENCE file for details.
"""
# location of the TEMareels package on the hard disk
# (if not specified in PYTHONPATH)
pkgdir = '../..';
import sys
from os.path import abspath;
sys.path.insert(0,abspath(pkgdir));
|
rhambach/TEMareels
|
runscripts/_set_pkgdir.py
|
Python
|
mit
| 674 | 0.01632 |
import _plotly_utils.basevalidators
class SourceattributionValidator(_plotly_utils.basevalidators.StringValidator):
def __init__(
self,
plotly_name="sourceattribution",
parent_name="layout.mapbox.layer",
**kwargs
):
super(SourceattributionValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_type=kwargs.pop("edit_type", "plot"),
role=kwargs.pop("role", "info"),
**kwargs
)
|
plotly/python-api
|
packages/python/plotly/plotly/validators/layout/mapbox/layer/_sourceattribution.py
|
Python
|
mit
| 521 | 0 |
# coding=utf-8
"""
InaSAFE Disaster risk assessment tool by AusAid - **Clipper test suite.**
Contact : ole.moller.nielsen@gmail.com
.. note:: This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
"""
import unittest
import sys
from tempfile import mktemp
from qgis.core import QgsVectorLayer, QgsRasterLayer
from PyQt4.QtCore import QFileInfo
from osgeo import gdal
from safe.test.utilities import (
get_qgis_app,
load_test_vector_layer,
standard_data_path)
QGIS_APP, CANVAS, IFACE, PARENT = get_qgis_app()
from safe.datastore.geopackage import GeoPackage
# Decorator for expecting fails in windows but not other OS's
# Probably we should move this somewhere in utils for easy re-use...TS
def expect_failure_in_windows(exception):
"""Marks test to expect a fail in windows - call assertRaises internally.
..versionadded:: 4.0.0
"""
def test_decorator(fn):
def test_decorated(self, *args, **kwargs):
if sys.platform.startswith('win'):
self.assertRaises(exception, fn, self, *args, **kwargs)
return test_decorated
return test_decorator
class TestGeoPackage(unittest.TestCase):
"""Test the GeoPackage datastore."""
def setUp(self):
pass
def tearDown(self):
pass
@unittest.skipIf(
int(gdal.VersionInfo('VERSION_NUM')) < 2000000,
'GDAL 2.0 is required for geopackage.')
def test_create_geopackage(self):
"""Test if we can store geopackage."""
# Create a geopackage from an empty file.
path = QFileInfo(mktemp() + '.gpkg')
self.assertFalse(path.exists())
data_store = GeoPackage(path)
path.refresh()
self.assertTrue(path.exists())
# Let's add a vector layer.
layer_name = 'flood_test'
layer = standard_data_path('hazard', 'flood_multipart_polygons.shp')
vector_layer = QgsVectorLayer(layer, 'Flood', 'ogr')
result = data_store.add_layer(vector_layer, layer_name)
self.assertTrue(result[0])
# We should have one layer.
layers = data_store.layers()
self.assertEqual(len(layers), 1)
self.assertIn(layer_name, layers)
# Add the same layer with another name.
layer_name = 'another_vector_flood'
result = data_store.add_layer(vector_layer, layer_name)
self.assertTrue(result[0])
# We should have two layers.
layers = data_store.layers()
self.assertEqual(len(layers), 2)
self.assertIn(layer_name, layers)
# Test the URI of the new layer.
expected = path.absoluteFilePath() + '|layername=' + layer_name
self.assertEqual(data_store.layer_uri(layer_name), expected)
# Test a fake layer.
self.assertIsNone(data_store.layer_uri('fake_layer'))
# Test to add a raster
layer_name = 'raster_flood'
layer = standard_data_path('hazard', 'classified_hazard.tif')
raster_layer = QgsRasterLayer(layer, layer_name)
result = data_store.add_layer(raster_layer, layer_name)
self.assertTrue(result[0])
# We should have 3 layers inside.
layers = data_store.layers()
self.assertEqual(len(layers), 3)
# Check the URI for the raster layer.
expected = 'GPKG:' + path.absoluteFilePath() + ':' + layer_name
self.assertEqual(data_store.layer_uri(layer_name), expected)
# Add a second raster.
layer_name = 'big raster flood'
self.assertTrue(data_store.add_layer(raster_layer, layer_name))
self.assertEqual(len(data_store.layers()), 4)
# Test layer without geometry
layer = load_test_vector_layer(
'gisv4', 'impacts', 'exposure_summary_table.csv')
tabular_layer_name = 'breakdown'
result = data_store.add_layer(layer, tabular_layer_name)
self.assertTrue(result[0])
@unittest.skipIf(
int(gdal.VersionInfo('VERSION_NUM')) < 2000000,
'GDAL 2.0 is required for geopackage.')
@expect_failure_in_windows(AssertionError)
def test_read_existing_geopackage(self):
"""Test we can read an existing geopackage."""
path = standard_data_path('other', 'jakarta.gpkg')
import os
path = os.path.normpath(os.path.normcase(os.path.abspath(path)))
geopackage = QFileInfo(path)
data_store = GeoPackage(geopackage)
# We should have 3 layers in this geopackage.
self.assertEqual(len(data_store.layers()), 3)
# Test we can load a vector layer.
roads = QgsVectorLayer(
data_store.layer_uri('roads'),
'Test',
'ogr'
)
self.assertTrue(roads.isValid())
# Test we can load a raster layers.
# This currently fails on windows...
# So we have decorated it with expected fail on windows
# Should pass on other platforms.
path = data_store.layer_uri('flood')
flood = QgsRasterLayer(path, 'flood')
self.assertTrue(flood.isValid())
if __name__ == '__main__':
unittest.main()
|
Gustry/inasafe
|
safe/datastore/test/test_geopackage.py
|
Python
|
gpl-3.0
| 5,299 | 0.000189 |
import logging
import numpy as np
import pandas as pd
import numexpr as ne
from astropy import units as u, constants as const
from tardis.plasma.properties.base import ProcessingPlasmaProperty
from tardis.plasma.properties.util import macro_atom
logger = logging.getLogger(__name__)
__all__ = ['StimulatedEmissionFactor', 'TauSobolev', 'BetaSobolev',
'TransitionProbabilities', 'LTEJBlues']
class StimulatedEmissionFactor(ProcessingPlasmaProperty):
"""
Attributes
----------
stimulated_emission_factor : Numpy Array, dtype float
Indexed by lines, columns as zones.
"""
outputs = ('stimulated_emission_factor',)
latex_formula = ('1-\\dfrac{g_{lower}n_{upper}}{g_{upper}n_{lower}}',)
def __init__(self, plasma_parent=None, nlte_species=None):
super(StimulatedEmissionFactor, self).__init__(plasma_parent)
self._g_upper = None
self._g_lower = None
try:
self.nlte_species = self.plasma_parent.nlte_species
except:
self.nlte_species = nlte_species
def get_g_lower(self, g, lines_lower_level_index):
if self._g_lower is None:
g_lower = np.array(g.ix[lines_lower_level_index],
dtype=np.float64)
self._g_lower = g_lower[np.newaxis].T
return self._g_lower
def get_g_upper(self, g, lines_upper_level_index):
if self._g_upper is None:
g_upper = np.array(g.ix[lines_upper_level_index],
dtype=np.float64)
self._g_upper = g_upper[np.newaxis].T
return self._g_upper
def get_metastable_upper(self, metastability, lines_upper_level_index):
if getattr(self, '_meta_stable_upper', None) is None:
self._meta_stable_upper = metastability.values[
lines_upper_level_index][np.newaxis].T
return self._meta_stable_upper
def calculate(self, g, level_number_density, lines_lower_level_index,
lines_upper_level_index, metastability, lines):
n_lower = level_number_density.values.take(lines_lower_level_index,
axis=0, mode='raise')
n_upper = level_number_density.values.take(lines_upper_level_index,
axis=0, mode='raise')
g_lower = self.get_g_lower(g, lines_lower_level_index)
g_upper = self.get_g_upper(g, lines_upper_level_index)
meta_stable_upper = self.get_metastable_upper(metastability,
lines_upper_level_index)
stimulated_emission_factor = ne.evaluate('1 - ((g_lower * n_upper) / '
'(g_upper * n_lower))')
stimulated_emission_factor[n_lower == 0.0] = 0.0
stimulated_emission_factor[np.isneginf(stimulated_emission_factor)]\
= 0.0
stimulated_emission_factor[meta_stable_upper &
(stimulated_emission_factor < 0)] = 0.0
if self.nlte_species:
nlte_lines_mask = \
np.zeros(stimulated_emission_factor.shape[0]).astype(bool)
for species in self.nlte_species:
nlte_lines_mask |= (lines.atomic_number == species[0]) & \
(lines.ion_number == species[1])
stimulated_emission_factor[(stimulated_emission_factor < 0) &
nlte_lines_mask[np.newaxis].T] = 0.0
return stimulated_emission_factor
class TauSobolev(ProcessingPlasmaProperty):
"""
Attributes
----------
tau_sobolev : Pandas DataFrame, dtype float
Sobolev optical depth for each line. Indexed by line.
Columns as zones.
"""
outputs = ('tau_sobolevs',)
latex_name = ('\\tau_{\\textrm{sobolev}}',)
latex_formula = ('\\dfrac{\\pi e^{2}}{m_{e} c}f_{lu}\\lambda t_{exp}\
n_{lower} \\Big(1-\\dfrac{g_{lower}n_{upper}}{g_{upper}n_{lower}}\\Big)',)
def __init__(self, plasma_parent):
super(TauSobolev, self).__init__(plasma_parent)
self.sobolev_coefficient = (((np.pi * const.e.gauss ** 2) /
(const.m_e.cgs * const.c.cgs))
* u.cm * u.s / u.cm**3).to(1).value
def calculate(self, lines, level_number_density, lines_lower_level_index,
time_explosion, stimulated_emission_factor, j_blues,
f_lu, wavelength_cm):
f_lu = f_lu.values[np.newaxis].T
wavelength = wavelength_cm.values[np.newaxis].T
n_lower = level_number_density.values.take(lines_lower_level_index,
axis=0, mode='raise')
tau_sobolevs = (self.sobolev_coefficient * f_lu * wavelength *
time_explosion * n_lower * stimulated_emission_factor)
if (np.any(np.isnan(tau_sobolevs)) or
np.any(np.isinf(np.abs(tau_sobolevs)))):
raise ValueError(
'Some tau_sobolevs are nan, inf, -inf in tau_sobolevs.'
' Something went wrong!')
return pd.DataFrame(tau_sobolevs, index=lines.index,
columns=np.array(level_number_density.columns))
class BetaSobolev(ProcessingPlasmaProperty):
"""
Attributes
----------
beta_sobolev : Numpy Array, dtype float
"""
outputs = ('beta_sobolev',)
latex_name = ('\\beta_{\\textrm{sobolev}}',)
def calculate(self, tau_sobolevs):
if getattr(self, 'beta_sobolev', None) is None:
beta_sobolev = np.zeros_like(tau_sobolevs.values)
else:
beta_sobolev = self.beta_sobolev
macro_atom.calculate_beta_sobolev(
tau_sobolevs.values.ravel(),
beta_sobolev.ravel())
return beta_sobolev
class TransitionProbabilities(ProcessingPlasmaProperty):
"""
Attributes
----------
transition_probabilities : Pandas DataFrame, dtype float
"""
outputs = ('transition_probabilities',)
def __init__(self, plasma_parent):
super(TransitionProbabilities, self).__init__(plasma_parent)
self.initialize = True
def calculate(self, atomic_data, beta_sobolev, j_blues,
stimulated_emission_factor, tau_sobolevs):
#I wonder why?
# Not sure who wrote this but the answer is that when the plasma is
# first initialised (before the first iteration, without temperature
# values etc.) there are no j_blues values so this just prevents
# an error. Aoife.
if len(j_blues) == 0:
return None
macro_atom_data = self._get_macro_atom_data(atomic_data)
if self.initialize:
self.initialize_macro_atom_transition_type_filters(atomic_data,
macro_atom_data)
self.transition_probability_coef = (
self._get_transition_probability_coefs(macro_atom_data))
self.initialize = False
transition_probabilities = self._calculate_transition_probability(macro_atom_data, beta_sobolev, j_blues, stimulated_emission_factor)
transition_probabilities = pd.DataFrame(transition_probabilities,
index=macro_atom_data.transition_line_id,
columns=tau_sobolevs.columns)
return transition_probabilities
def _calculate_transition_probability(self, macro_atom_data, beta_sobolev, j_blues, stimulated_emission_factor):
transition_probabilities = np.empty((self.transition_probability_coef.shape[0], beta_sobolev.shape[1]))
#trans_old = self.calculate_transition_probabilities(macro_atom_data, beta_sobolev, j_blues, stimulated_emission_factor)
transition_type = macro_atom_data.transition_type.values
lines_idx = macro_atom_data.lines_idx.values
tpos = macro_atom_data.transition_probability.values
#optimized_calculate_transition_probabilities(tpos, beta_sobolev, j_blues, stimulated_emission_factor, transition_type, lines_idx, self.block_references, transition_probabilities)
macro_atom.calculate_transition_probabilities(tpos, beta_sobolev, j_blues, stimulated_emission_factor, transition_type, lines_idx, self.block_references, transition_probabilities)
return transition_probabilities
def calculate_transition_probabilities(self, macro_atom_data, beta_sobolev, j_blues, stimulated_emission_factor):
transition_probabilities = self.prepare_transition_probabilities(macro_atom_data, beta_sobolev, j_blues, stimulated_emission_factor)
return transition_probabilities
def initialize_macro_atom_transition_type_filters(self, atomic_data,
macro_atom_data):
self.transition_up_filter = (macro_atom_data.transition_type.values
== 1)
self.transition_up_line_filter = macro_atom_data.lines_idx.values[
self.transition_up_filter]
self.block_references = np.hstack((
atomic_data.macro_atom_references.block_references,
len(macro_atom_data)))
@staticmethod
def _get_transition_probability_coefs(macro_atom_data):
return macro_atom_data.transition_probability.values[np.newaxis].T
def prepare_transition_probabilities(self, macro_atom_data, beta_sobolev,
j_blues, stimulated_emission_factor):
current_beta_sobolev = beta_sobolev.take(
macro_atom_data.lines_idx.values, axis=0, mode='raise')
transition_probabilities = self.transition_probability_coef * current_beta_sobolev
j_blues = j_blues.take(self.transition_up_line_filter, axis=0,
mode='raise')
macro_stimulated_emission = stimulated_emission_factor.take(
self.transition_up_line_filter, axis=0, mode='raise')
transition_probabilities[self.transition_up_filter] *= (j_blues * macro_stimulated_emission)
return transition_probabilities
def _normalize_transition_probabilities(self, transition_probabilities):
macro_atom.normalize_transition_probabilities(
transition_probabilities, self.block_references)
def _new_normalize_transition_probabilities(self, transition_probabilites):
for i, start_id in enumerate(self.block_references[:-1]):
end_id = self.block_references[i + 1]
block = transition_probabilites[start_id:end_id]
transition_probabilites[start_id:end_id] *= 1 / ne.evaluate(
'sum(block, 0)')
@staticmethod
def _get_macro_atom_data(atomic_data):
try:
return atomic_data.macro_atom_data
except:
return atomic_data.macro_atom_data_all
class LTEJBlues(ProcessingPlasmaProperty):
'''
Attributes
----------
lte_j_blues : Pandas DataFrame, dtype float
J_blue values as calculated in LTE.
'''
outputs = ('lte_j_blues',)
latex_name = ('J^{b}_{lu(LTE)}')
@staticmethod
def calculate(lines, nu, beta_rad):
beta_rad = pd.Series(beta_rad)
nu = pd.Series(nu)
h = const.h.cgs.value
c = const.c.cgs.value
df = pd.DataFrame(1, index=nu.index, columns=beta_rad.index)
df = df.mul(nu, axis='index') * beta_rad
exponential = (np.exp(h * df) - 1)**(-1)
remainder = (2 * (h * nu.values ** 3) /
(c ** 2))
j_blues = exponential.mul(remainder, axis=0)
return pd.DataFrame(j_blues, index=lines.index, columns=beta_rad.index)
|
orbitfold/tardis
|
tardis/plasma/properties/radiative_properties.py
|
Python
|
bsd-3-clause
| 11,605 | 0.003188 |
#!/usr/bin/env python
"""
Get an action by name (name is not a supported selector for action)
"""
# import the basic python packages we need
import os
import sys
import tempfile
import pprint
import traceback
# disable python from generating a .pyc file
sys.dont_write_bytecode = True
# change me to the path of pytan if this script is not running from EXAMPLES/PYTAN_API
pytan_loc = "~/gh/pytan"
pytan_static_path = os.path.join(os.path.expanduser(pytan_loc), 'lib')
# Determine our script name, script dir
my_file = os.path.abspath(sys.argv[0])
my_dir = os.path.dirname(my_file)
# try to automatically determine the pytan lib directory by assuming it is in '../../lib/'
parent_dir = os.path.dirname(my_dir)
pytan_root_dir = os.path.dirname(parent_dir)
lib_dir = os.path.join(pytan_root_dir, 'lib')
# add pytan_loc and lib_dir to the PYTHONPATH variable
path_adds = [lib_dir, pytan_static_path]
[sys.path.append(aa) for aa in path_adds if aa not in sys.path]
# import pytan
import pytan
# create a dictionary of arguments for the pytan handler
handler_args = {}
# establish our connection info for the Tanium Server
handler_args['username'] = "Administrator"
handler_args['password'] = "Tanium2015!"
handler_args['host'] = "10.0.1.240"
handler_args['port'] = "443" # optional
handler_args['trusted_certs'] = "certs"
# optional, level 0 is no output except warnings/errors
# level 1 through 12 are more and more verbose
handler_args['loglevel'] = 1
# optional, use a debug format for the logging output (uses two lines per log entry)
handler_args['debugformat'] = False
# optional, this saves all response objects to handler.session.ALL_REQUESTS_RESPONSES
# very useful for capturing the full exchange of XML requests and responses
handler_args['record_all_requests'] = True
# instantiate a handler using all of the arguments in the handler_args dictionary
print "...CALLING: pytan.handler() with args: {}".format(handler_args)
handler = pytan.Handler(**handler_args)
# print out the handler string
print "...OUTPUT: handler string: {}".format(handler)
# setup the arguments for the handler() class
kwargs = {}
kwargs["objtype"] = u'action'
kwargs["name"] = u'Distribute Tanium Standard Utilities'
print "...CALLING: handler.get() with args: {}".format(kwargs)
try:
handler.get(**kwargs)
except Exception as e:
print "...EXCEPTION: {}".format(e)
# this should throw an exception of type: pytan.exceptions.HandlerError
# uncomment to see full exception
# traceback.print_exc(file=sys.stdout)
'''STDOUT from running this:
...CALLING: pytan.handler() with args: {'username': 'Administrator', 'record_all_requests': True, 'loglevel': 1, 'debugformat': False, 'host': '10.0.1.240', 'password': 'Tanium2015!', 'port': '443'}
...OUTPUT: handler string: PyTan v2.1.4 Handler for Session to 10.0.1.240:443, Authenticated: True, Platform Version: 6.5.314.4301
...CALLING: handler.get() with args: {'objtype': u'action', 'name': u'Distribute Tanium Standard Utilities'}
...EXCEPTION: Getting a action requires at least one filter: ['id']
'''
'''STDERR from running this:
'''
|
tanium/pytan
|
EXAMPLES/PYTAN_API/invalid_get_action_single_by_name.py
|
Python
|
mit
| 3,103 | 0.0029 |
from . import base
from grow.common import utils
from protorpc import messages
import logging
import os
import re
if utils.is_appengine():
sass = None # Unavailable on Google App Engine.
else:
import sass
SUFFIXES = frozenset(['sass', 'scss'])
SUFFIX_PATTERN = re.compile('[.](' + '|'.join(map(re.escape, SUFFIXES)) + ')$')
class Config(messages.Message):
sass_dir = messages.StringField(1)
out_dir = messages.StringField(2)
suffix = messages.StringField(3, default='.min.css')
output_style = messages.StringField(4, default='compressed')
source_comments = messages.BooleanField(5)
image_path = messages.StringField(6)
class SassPreprocessor(base.BasePreprocessor):
KIND = 'sass'
Config = Config
def run(self, build=True):
sass_dir = os.path.abspath(os.path.join(self.root, self.config.sass_dir.lstrip('/')))
out_dir = os.path.abspath(os.path.join(self.root, self.config.out_dir.lstrip('/')))
self.build_directory(sass_dir, out_dir)
def build_directory(self, sass_path, css_path, _root_sass=None, _root_css=None):
if sass is None:
raise utils.UnavailableError('The Sass compiler is not available in this environment.')
if self.config.image_path:
image_path = os.path.abspath(os.path.join(self.root, self.config.image_path.lstrip('/')))
else:
image_path = None
_root_sass = sass_path if _root_sass is None else _root_sass
_root_css = css_path if _root_css is None else _root_css
result = {}
if not os.path.isdir(css_path):
os.makedirs(css_path)
for name in os.listdir(sass_path):
if not SUFFIX_PATTERN.search(name) or name.startswith('_'):
continue
sass_fullname = os.path.join(sass_path, name)
if os.path.isfile(sass_fullname):
basename = os.path.splitext(name)[0]
css_fullname = os.path.join(css_path, basename) + self.config.suffix
try:
kwargs = {
'filename': sass_fullname,
'include_paths': [_root_sass],
'output_style': self.config.output_style,
}
if self.config.output_style is not None:
kwargs['output_style'] = self.config.output_style
if image_path is not None:
kwargs['image_path'] = image_path
if self.config.image_path is not None:
kwargs['image_path'] = image_path
css = sass.compile(**kwargs)
except sass.CompileError as e:
logging.error(str(e))
return result
with open(css_fullname, 'w') as css_file:
if isinstance(css, unicode):
css = css.encode('utf-8')
css_file.write(css)
result[sass_fullname] = css_fullname
elif os.path.isdir(sass_fullname):
css_fullname = os.path.join(css_path, name)
subresult = self.build_directory(sass_fullname, css_fullname,
_root_sass, _root_css)
result.update(subresult)
for sass_path, out_path in result.iteritems():
self.logger.info(
'Compiled: {} -> {}'.format(sass_path.replace(self.root, ''),
out_path.replace(self.root, '')))
return result
def list_watched_dirs(self):
return [self.config.sass_dir]
|
denmojo/pygrow
|
grow/preprocessors/sass_preprocessor.py
|
Python
|
mit
| 3,649 | 0.002192 |
# -*- coding: utf-8 -*-
#
# hdfs documentation build configuration file, created by
# sphinx-quickstart on Thu Mar 6 16:04:56 2014.
#
# 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
import mock
MOCK_MODULES = ['numpy', 'pandas', 'requests_kerberos']
for mod_name in MOCK_MODULES:
sys.modules[mod_name] = mock.Mock()
# 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.viewcode',
]
# 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'HdfsCLI'
copyright = u'2014'
# 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.
#
import hdfs
# The short X.Y version.
version = hdfs.__version__.rsplit('.', 1)[0]
# The full version, including alpha/beta/rc tags.
release = hdfs.__version__
# 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 = ['_build']
# 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 = []
# If true, keep warnings as "system message" paragraphs in the built documents.
#keep_warnings = False
# Autodoc
autoclass_content = 'both'
# -- 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 = 'default'
# 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 = {}
# 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 = None
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None
# 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_static_path = []
# Add any extra paths that contain custom files (such as robots.txt or
# .htaccess) here, relative to this directory. These files are copied
# directly to the root of the documentation.
#html_extra_path = []
# 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 = 'hdfsdoc'
# -- 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': '',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
('index', 'hdfs.tex', u'hdfs Documentation',
u'Author', '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', 'hdfs', u'hdfs documentation',
[u'Author'], 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', 'hdfs', u'hdfs documentation',
u'Author', 'hdfs', 'One line description of project.',
'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'
# If true, do not generate a @detailmenu in the "Top" node's menu.
#texinfo_no_detailmenu = False
# -- Options for Epub output ----------------------------------------------
# Bibliographic Dublin Core info.
epub_title = u'hdfs'
epub_author = u'Author'
epub_publisher = u'Author'
epub_copyright = u'2014, Author'
# The basename for the epub file. It defaults to the project name.
#epub_basename = u'hdfs'
# The HTML theme for the epub output. Since the default themes are not optimized
# for small screen space, using the same theme for HTML and epub output is
# usually not wise. This defaults to 'epub', a theme designed to save visual
# space.
#epub_theme = 'epub'
# The language of the text. It defaults to the language option
# or en if the language is not set.
#epub_language = ''
# The scheme of the identifier. Typical schemes are ISBN or URL.
#epub_scheme = ''
# The unique identifier of the text. This can be a ISBN number
# or the project homepage.
#epub_identifier = ''
# A unique identification for the text.
#epub_uid = ''
# A tuple containing the cover image and cover page html template filenames.
#epub_cover = ()
# A sequence of (type, uri, title) tuples for the guide element of content.opf.
#epub_guide = ()
# HTML files that should be inserted before the pages created by sphinx.
# The format is a list of tuples containing the path and title.
#epub_pre_files = []
# HTML files shat should be inserted after the pages created by sphinx.
# The format is a list of tuples containing the path and title.
#epub_post_files = []
# A list of files that should not be packed into the epub file.
epub_exclude_files = ['search.html']
# The depth of the table of contents in toc.ncx.
#epub_tocdepth = 3
# Allow duplicate toc entries.
#epub_tocdup = True
# Choose between 'default' and 'includehidden'.
#epub_tocscope = 'default'
# Fix unsupported image types using the PIL.
#epub_fix_images = False
# Scale large images.
#epub_max_image_width = 0
# How to display URL addresses: 'footnote', 'no', or 'inline'.
#epub_show_urls = 'inline'
# If false, no index is generated.
#epub_use_index = True
|
laserson/hdfs
|
doc/conf.py
|
Python
|
mit
| 10,413 | 0.006914 |
from __future__ import print_function, unicode_literals, division, absolute_import
import os
import sys
import string
import random
import hashlib
import logging
import subprocess
from io import StringIO
import config
def valid_path(path):
"""
Returns an expanded, absolute path, or None if the path does not exist.
"""
path = os.path.expanduser(path)
if not os.path.exists(path):
return None
return os.path.abspath(path)
def get_paths(args):
"""
Returns expanded, absolute paths for all valid paths in a list of arguments.
"""
assert isinstance(args, list)
valid_paths = []
for path in args:
abs_path = valid_path(path)
if abs_path is not None:
valid_paths.append(abs_path)
return valid_paths
def split_path(path):
"""
Returns a normalized list of the path's components.
"""
path = os.path.normpath(path)
return [x for x in path.split(os.path.sep) if x]
def generate_id(size=10, chars=string.ascii_uppercase + string.digits):
"""
Generate a string of random alphanumeric characters.
"""
return ''.join(random.choice(chars) for i in range(size))
def list_contents(rar_file_path):
"""
Returns a list of the archive's contents.
"""
assert os.path.isfile(rar_file_path) and rar_file_path.endswith('.rar')
contents = []
count = 0
command = '"{unrar}" v -- "{file}"'
command = command.format(unrar=config.UNRAR_PATH, file=rar_file_path)
try:
output = subprocess.check_output(command, stderr=subprocess.STDOUT, shell=True)
except subprocess.CalledProcessError as e:
output = e.output.decode(encoding='utf-8')
msg = 'Error while listing archive contents: "{error_string}"'
raise FileUtilsError(msg.format(error_string=output.strip()))
else:
output = StringIO(output.decode(encoding='utf-8'))
parse = False
for line in output.readlines():
line_list = line.strip().split()
# If the line is not empty...
if line_list:
# This marks the start and end of the section we want to parse
if line_list[0] == '-------------------------------------------------------------------------------':
parse = not parse
count = 0
# If we're in the section of the output we want to parse...
elif parse:
# Parse every other line (only the file paths)
if count % 2 == 0:
contents.append(line_list[0])
count += 1
return contents
def unrar(rar_file_path, destination_dir=None):
"""
Get a list of the archive's contents, then extract the archive and return the list.
"""
assert os.path.isfile(rar_file_path) and rar_file_path.endswith('.rar')
if not destination_dir:
destination_dir = os.path.split(rar_file_path)[0]
# Get a list of the archive's contents
contents = list_contents(rar_file_path)
extracted_files = []
# Extract the archive
command = '"{unrar}" x -o+ -- "{file}" "{destination}"'
command = command.format(unrar=config.UNRAR_PATH, file=rar_file_path, destination=destination_dir)
logging.debug(command)
try:
subprocess.check_output(command, stderr=subprocess.STDOUT, shell=True)
except subprocess.CalledProcessError as e:
output = e.output.decode(encoding='utf-8')
msg = 'Error while extracting!\n{error_string}'
raise FileUtilsError(msg.format(error_string=output.strip()))
for relative_path in contents:
path = os.path.join(destination_dir, relative_path)
# Recursively extract until there are no RAR files left
if path.endswith('.rar'):
extracted_files += unrar(path)
else:
extracted_files.append(path)
# Return the list of paths
return extracted_files
def sha1(data):
"""
Return the SHA-1 hash of the given data.
"""
assert isinstance(data, (bytes, bytearray))
sha1_hash = hashlib.sha1()
sha1_hash.update(data)
return sha1_hash.digest()
def set_log_file_name(file_name):
"""
Set the file name for log output.
"""
# Remove all logging handlers from the root logger
logger = logging.getLogger('')
for handler in list(logger.handlers):
logger.removeHandler(handler)
handler.flush()
handler.close()
# Configure console logging
console_log_format = logging.Formatter('%(module)-15s: %(levelname)-8s %(message)s')
console_log_handler = logging.StreamHandler(sys.stdout)
console_log_handler.setFormatter(console_log_format)
console_log_handler.setLevel(logging.INFO)
logger.addHandler(console_log_handler)
# Configure disk logging
if file_name:
log_path = os.path.join(config.LOG_DIR, file_name)
disk_log_format = logging.Formatter('%(asctime)s %(module)-15s: %(levelname)-8s %(message)s')
disk_log_handler = logging.FileHandler(filename=log_path, mode='w', encoding='utf-8')
disk_log_handler.setFormatter(disk_log_format)
disk_log_handler.setLevel(logging.DEBUG)
logger.addHandler(disk_log_handler)
logger.setLevel(logging.DEBUG)
# Set logging level for the requests lib to warning+
requests_log = logging.getLogger('requests')
requests_log.setLevel(logging.WARNING)
# Log system info and Python version for debugging purposes
logging.debug('Python {version}'.format(version=sys.version))
logging.debug('System platform: {platform}'.format(platform=sys.platform))
class FileUtilsError(Exception):
pass
|
hwkns/macguffin
|
files/utils.py
|
Python
|
gpl-3.0
| 5,724 | 0.001747 |
"""Config flow for TP-Link."""
from __future__ import annotations
from typing import Any
from kasa import SmartDevice, SmartDeviceException
from kasa.discover import Discover
import voluptuous as vol
from homeassistant import config_entries
from homeassistant.components import dhcp
from homeassistant.const import CONF_DEVICE, CONF_HOST, CONF_MAC
from homeassistant.core import callback
from homeassistant.data_entry_flow import FlowResult
from homeassistant.helpers import device_registry as dr
from homeassistant.helpers.typing import DiscoveryInfoType
from . import async_discover_devices
from .const import DOMAIN
class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
"""Handle a config flow for tplink."""
VERSION = 1
def __init__(self) -> None:
"""Initialize the config flow."""
self._discovered_devices: dict[str, SmartDevice] = {}
self._discovered_device: SmartDevice | None = None
async def async_step_dhcp(self, discovery_info: dhcp.DhcpServiceInfo) -> FlowResult:
"""Handle discovery via dhcp."""
return await self._async_handle_discovery(
discovery_info.ip, discovery_info.macaddress
)
async def async_step_discovery(
self, discovery_info: DiscoveryInfoType
) -> FlowResult:
"""Handle discovery."""
return await self._async_handle_discovery(
discovery_info[CONF_HOST], discovery_info[CONF_MAC]
)
async def _async_handle_discovery(self, host: str, mac: str) -> FlowResult:
"""Handle any discovery."""
await self.async_set_unique_id(dr.format_mac(mac))
self._abort_if_unique_id_configured(updates={CONF_HOST: host})
self._async_abort_entries_match({CONF_HOST: host})
self.context[CONF_HOST] = host
for progress in self._async_in_progress():
if progress.get("context", {}).get(CONF_HOST) == host:
return self.async_abort(reason="already_in_progress")
try:
self._discovered_device = await self._async_try_connect(
host, raise_on_progress=True
)
except SmartDeviceException:
return self.async_abort(reason="cannot_connect")
return await self.async_step_discovery_confirm()
async def async_step_discovery_confirm(
self, user_input: dict[str, Any] | None = None
) -> FlowResult:
"""Confirm discovery."""
assert self._discovered_device is not None
if user_input is not None:
return self._async_create_entry_from_device(self._discovered_device)
self._set_confirm_only()
placeholders = {
"name": self._discovered_device.alias,
"model": self._discovered_device.model,
"host": self._discovered_device.host,
}
self.context["title_placeholders"] = placeholders
return self.async_show_form(
step_id="discovery_confirm", description_placeholders=placeholders
)
async def async_step_user(
self, user_input: dict[str, Any] | None = None
) -> FlowResult:
"""Handle the initial step."""
errors = {}
if user_input is not None:
if not (host := user_input[CONF_HOST]):
return await self.async_step_pick_device()
try:
device = await self._async_try_connect(host, raise_on_progress=False)
except SmartDeviceException:
errors["base"] = "cannot_connect"
else:
return self._async_create_entry_from_device(device)
return self.async_show_form(
step_id="user",
data_schema=vol.Schema({vol.Optional(CONF_HOST, default=""): str}),
errors=errors,
)
async def async_step_pick_device(
self, user_input: dict[str, Any] | None = None
) -> FlowResult:
"""Handle the step to pick discovered device."""
if user_input is not None:
mac = user_input[CONF_DEVICE]
await self.async_set_unique_id(mac, raise_on_progress=False)
return self._async_create_entry_from_device(self._discovered_devices[mac])
configured_devices = {
entry.unique_id for entry in self._async_current_entries()
}
self._discovered_devices = await async_discover_devices(self.hass)
devices_name = {
formatted_mac: f"{device.alias} {device.model} ({device.host}) {formatted_mac}"
for formatted_mac, device in self._discovered_devices.items()
if formatted_mac not in configured_devices
}
# Check if there is at least one device
if not devices_name:
return self.async_abort(reason="no_devices_found")
return self.async_show_form(
step_id="pick_device",
data_schema=vol.Schema({vol.Required(CONF_DEVICE): vol.In(devices_name)}),
)
@callback
def _async_create_entry_from_device(self, device: SmartDevice) -> FlowResult:
"""Create a config entry from a smart device."""
self._abort_if_unique_id_configured(updates={CONF_HOST: device.host})
return self.async_create_entry(
title=f"{device.alias} {device.model}",
data={
CONF_HOST: device.host,
},
)
async def _async_try_connect(
self, host: str, raise_on_progress: bool = True
) -> SmartDevice:
"""Try to connect."""
self._async_abort_entries_match({CONF_HOST: host})
device: SmartDevice = await Discover.discover_single(host)
await self.async_set_unique_id(
dr.format_mac(device.mac), raise_on_progress=raise_on_progress
)
return device
|
home-assistant/home-assistant
|
homeassistant/components/tplink/config_flow.py
|
Python
|
apache-2.0
| 5,772 | 0.001213 |
# -*- coding: utf-8 -*-
#!/usr/bin/env python
#第 0001 题:做为 Apple Store App 独立开发者,你要搞限时促销,为你的应用生成激活码(或者优惠券),使用 Python 如何生成 200 个激活码(或者优惠券)?
import random
import string
def activation_code(chars = string.ascii_uppercase + string.digits, length=16):
return ''.join([random.choice(chars) for i in range(length)])
if __name__ == '__main__':
code_collection = set()
for i in range(200):
code = activation_code()
if code not in code_collection:
code_collection.add(code)
else:
continue
|
Show-Me-the-Code/python
|
pylyria/0001/0001_1.py
|
Python
|
mit
| 651 | 0.012939 |
"""
Simple http server to create streams for asyncio tests
"""
import asyncio
import aiohttp
from aiohttp import web
import codecs
from utils.streamdecoder import DecodingStreamReader
async def get_data(host, port):
url = 'http://{}:{}/'.format(host, port)
decoder = codecs.getincrementaldecoder('utf-8')(errors='strict')
async with aiohttp.get(url) as r:
stream = DecodingStreamReader(r.content)
while not stream.at_eof():
data = await stream.read(7)
print(data, end='')
class UTF8Server:
def __init__(self):
self.app = web.Application()
self.app.router.add_route('GET', '/', self.hello)
self.handler = self.app.make_handler()
async def hello(self, request):
return web.Response(body=b'M\xc3\xa4dchen mit Bi\xc3\x9f\n')
# return web.Response(body=b'\xc3\x84\xc3\xa4\xc3\xa4\xc3\xa4\xc3\xa4\xc3\xa4\xc3\xa4\xc3\xa4\xc3\xa4\xc3\xa4h!\n')
def start_server(self, loop, host, port):
setup = loop.create_server(self.handler, host, port)
self.srv = loop.run_until_complete(setup)
return self.srv
def stop_server(self, loop):
self.srv.close()
loop.run_until_complete(self.srv.wait_closed())
loop.run_until_complete(self.handler.finish_connections(1.0))
loop.run_until_complete(self.app.finish())
if __name__ == '__main__':
HOST = '127.0.0.1'
PORT = '56789'
loop = asyncio.get_event_loop()
server = UTF8Server()
server.start_server(loop, HOST, PORT)
print("serving on", server.srv.sockets[0].getsockname())
try:
task = asyncio.ensure_future(get_data(HOST, PORT))
loop.run_until_complete(task)
finally:
server.stop_server(loop)
loop.close()
|
ethanfrey/aiojson
|
aiojson/echo_server.py
|
Python
|
bsd-3-clause
| 1,771 | 0.000565 |
../../../../../../share/pyshared/twisted/persisted/journal/base.py
|
Alberto-Beralix/Beralix
|
i386-squashfs-root/usr/lib/python2.7/dist-packages/twisted/persisted/journal/base.py
|
Python
|
gpl-3.0
| 66 | 0.015152 |
__author__ = 'mFoxRU'
import scipy.signal as sps
from abstractwavelet import AbstractWavelet
class Ricker(AbstractWavelet):
name = 'Ricker(MHAT)'
params = {}
def fn(self):
return sps.ricker
|
mFoxRU/cwaveplay
|
cwp/wavelets/ricker.py
|
Python
|
mit
| 215 | 0 |
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
import itertools
import os
import sys
from dataclasses import dataclass
from pathlib import Path
from typing import Dict, Iterable, List, Mapping, Optional, Sequence, Set, Tuple, Type
from pants.base.build_environment import get_default_pants_config_file
from pants.option.config import Config
from pants.option.custom_types import ListValueComponent
from pants.option.global_options import GlobalOptions
from pants.option.optionable import Optionable
from pants.option.options import Options
from pants.option.scope import GLOBAL_SCOPE, ScopeInfo
from pants.util.dirutil import read_file
from pants.util.memo import memoized_method, memoized_property
from pants.util.ordered_set import FrozenOrderedSet
from pants.util.strutil import ensure_text
# This is a temporary hack that allows us to note the fact that we're in v2-exclusive mode
# in a static location, as soon as we know it. This way code that cannot access options
# can still use this information to customize behavior. Again, this is a temporary hack
# to provide a better v2 experience to users who are not (and possibly never have been)
# running v1, and should go away ASAP.
class IsV2Exclusive:
def __init__(self):
self._value = False
def set(self):
self._value = True
def __bool__(self):
return self._value
is_v2_exclusive = IsV2Exclusive()
@dataclass(frozen=True)
class OptionsBootstrapper:
"""Holds the result of the first stage of options parsing, and assists with parsing full
options."""
env_tuples: Tuple[Tuple[str, str], ...]
bootstrap_args: Tuple[str, ...]
args: Tuple[str, ...]
config: Config
@staticmethod
def get_config_file_paths(env, args) -> List[str]:
"""Get the location of the config files.
The locations are specified by the --pants-config-files option. However we need to load the
config in order to process the options. This method special-cases --pants-config-files
in order to solve this chicken-and-egg problem.
Note that, obviously, it's not possible to set the location of config files in a config file.
Doing so will have no effect.
"""
# This exactly mirrors the logic applied in Option to all regular options. Note that we'll
# also parse --pants-config as a regular option later, but there's no harm in that. In fact,
# it's preferable, so that any code that happens to want to know where we read config from
# can inspect the option.
flag = "--pants-config-files="
evars = [
"PANTS_GLOBAL_PANTS_CONFIG_FILES",
"PANTS_PANTS_CONFIG_FILES",
"PANTS_CONFIG_FILES",
]
path_list_values = []
default = get_default_pants_config_file()
if Path(default).is_file():
path_list_values.append(ListValueComponent.create(default))
for var in evars:
if var in env:
path_list_values.append(ListValueComponent.create(env[var]))
break
for arg in args:
# Technically this is very slightly incorrect, as we don't check scope. But it's
# very unlikely that any task or subsystem will have an option named --pants-config-files.
# TODO: Enforce a ban on options with a --pants- prefix outside our global options?
if arg.startswith(flag):
path_list_values.append(ListValueComponent.create(arg[len(flag) :]))
return ListValueComponent.merge(path_list_values).val
@staticmethod
def parse_bootstrap_options(
env: Mapping[str, str], args: Sequence[str], config: Config
) -> Options:
bootstrap_options = Options.create(
env=env, config=config, known_scope_infos=[GlobalOptions.get_scope_info()], args=args,
)
def register_global(*args, **kwargs):
## Only use of Options.register?
bootstrap_options.register(GLOBAL_SCOPE, *args, **kwargs)
GlobalOptions.register_bootstrap_options(register_global)
opts = bootstrap_options.for_global_scope()
if opts.v2 and not opts.v1 and opts.backend_packages == []:
is_v2_exclusive.set()
return bootstrap_options
@classmethod
def create(
cls, env: Optional[Mapping[str, str]] = None, args: Optional[Sequence[str]] = None,
) -> "OptionsBootstrapper":
"""Parses the minimum amount of configuration necessary to create an OptionsBootstrapper.
:param env: An environment dictionary, or None to use `os.environ`.
:param args: An args array, or None to use `sys.argv`.
"""
env = {
k: v for k, v in (os.environ if env is None else env).items() if k.startswith("PANTS_")
}
args = tuple(sys.argv if args is None else args)
flags = set()
short_flags = set()
# We can't use pants.engine.fs.FileContent here because it would cause a circular dep.
@dataclass(frozen=True)
class FileContent:
path: str
content: bytes
def filecontent_for(path: str) -> FileContent:
return FileContent(ensure_text(path), read_file(path, binary_mode=True),)
def capture_the_flags(*args: str, **kwargs) -> None:
for arg in args:
flags.add(arg)
if len(arg) == 2:
short_flags.add(arg)
elif kwargs.get("type") == bool:
flags.add(f"--no-{arg[2:]}")
GlobalOptions.register_bootstrap_options(capture_the_flags)
def is_bootstrap_option(arg: str) -> bool:
components = arg.split("=", 1)
if components[0] in flags:
return True
for flag in short_flags:
if arg.startswith(flag):
return True
return False
# Take just the bootstrap args, so we don't choke on other global-scope args on the cmd line.
# Stop before '--' since args after that are pass-through and may have duplicate names to our
# bootstrap options.
bargs = tuple(
filter(is_bootstrap_option, itertools.takewhile(lambda arg: arg != "--", args))
)
config_file_paths = cls.get_config_file_paths(env=env, args=args)
config_files_products = [filecontent_for(p) for p in config_file_paths]
pre_bootstrap_config = Config.load_file_contents(config_files_products)
initial_bootstrap_options = cls.parse_bootstrap_options(env, bargs, pre_bootstrap_config)
bootstrap_option_values = initial_bootstrap_options.for_global_scope()
# Now re-read the config, post-bootstrapping. Note the order: First whatever we bootstrapped
# from (typically pants.toml), then config override, then rcfiles.
full_config_paths = pre_bootstrap_config.sources()
if bootstrap_option_values.pantsrc:
rcfiles = [
os.path.expanduser(str(rcfile)) for rcfile in bootstrap_option_values.pantsrc_files
]
existing_rcfiles = list(filter(os.path.exists, rcfiles))
full_config_paths.extend(existing_rcfiles)
full_config_files_products = [filecontent_for(p) for p in full_config_paths]
post_bootstrap_config = Config.load_file_contents(
full_config_files_products, seed_values=bootstrap_option_values.as_dict(),
)
env_tuples = tuple(sorted(env.items(), key=lambda x: x[0]))
return cls(
env_tuples=env_tuples, bootstrap_args=bargs, args=args, config=post_bootstrap_config
)
@memoized_property
def env(self) -> Dict[str, str]:
return dict(self.env_tuples)
@memoized_property
def bootstrap_options(self) -> Options:
"""The post-bootstrap options, computed from the env, args, and fully discovered Config.
Re-computing options after Config has been fully expanded allows us to pick up bootstrap values
(such as backends) from a config override file, for example.
Because this can be computed from the in-memory representation of these values, it is not part
of the object's identity.
"""
return self.parse_bootstrap_options(self.env, self.bootstrap_args, self.config)
def get_bootstrap_options(self) -> Options:
"""Returns an Options instance that only knows about the bootstrap options."""
return self.bootstrap_options
@memoized_method
def _full_options(self, known_scope_infos: FrozenOrderedSet[ScopeInfo]) -> Options:
bootstrap_option_values = self.get_bootstrap_options().for_global_scope()
options = Options.create(
self.env,
self.config,
known_scope_infos,
args=self.args,
bootstrap_option_values=bootstrap_option_values,
)
distinct_optionable_classes: Set[Type[Optionable]] = set()
for ksi in known_scope_infos:
if not ksi.optionable_cls or ksi.optionable_cls in distinct_optionable_classes:
continue
distinct_optionable_classes.add(ksi.optionable_cls)
ksi.optionable_cls.register_options_on_scope(options)
return options
def get_full_options(self, known_scope_infos: Iterable[ScopeInfo]) -> Options:
"""Get the full Options instance bootstrapped by this object for the given known scopes.
:param known_scope_infos: ScopeInfos for all scopes that may be encountered.
:returns: A bootrapped Options instance that also carries options for all the supplied known
scopes.
"""
return self._full_options(
FrozenOrderedSet(sorted(known_scope_infos, key=lambda si: si.scope))
)
|
tdyas/pants
|
src/python/pants/option/options_bootstrapper.py
|
Python
|
apache-2.0
| 9,939 | 0.004628 |
import redis
class RedisAdapter:
storage = None
host = None
port = None
def __init__(self, host, port):
if not self.storage:
self.storage = redis.StrictRedis(host=host, port=int(port), db=0)
def get_storage(self):
return self.storage
|
MShel/PyChatBot
|
storage/Redis.py
|
Python
|
gpl-3.0
| 288 | 0 |
#
# Copyright (c) 2013 Red Hat, 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.
class DictUtils(object):
'''
Provides dict services
'''
@staticmethod
def exclude(dct, keys=[]):
"""
Removes given items from the disct
@param dct: the ditc to look at
@param keys: the keys of items to pop
@return: updated dict
"""
if dct:
for key in keys:
if dct.has_key(key):
dct.pop(key)
|
oVirt/ovirt-engine-sdk-tests
|
src/utils/dictutils.py
|
Python
|
apache-2.0
| 1,025 | 0.002927 |
import os
import numpy
from numpy.distutils.misc_util import Configuration
def configuration(parent_package="", top_path=None):
config = Configuration("tree", parent_package, top_path)
libraries = []
if os.name == 'posix':
libraries.append('m')
config.add_extension("_tree",
sources=["_tree.c"],
include_dirs=[numpy.get_include()],
libraries=libraries,
extra_compile_args=["-O3"])
config.add_subpackage("tests")
return config
if __name__ == "__main__":
from numpy.distutils.core import setup
setup(**configuration().todict())
|
B3AU/waveTree
|
sklearn/waveTree/setup.py
|
Python
|
bsd-3-clause
| 672 | 0.001488 |
#!/usr/bin/env python
"""
lit - LLVM Integrated Tester.
See lit.pod for more information.
"""
from __future__ import absolute_import
import math, os, platform, random, re, sys, time
import lit.ProgressBar
import lit.LitConfig
import lit.Test
import lit.run
import lit.util
import lit.discovery
class TestingProgressDisplay(object):
def __init__(self, opts, numTests, progressBar=None):
self.opts = opts
self.numTests = numTests
self.current = None
self.progressBar = progressBar
self.completed = 0
def finish(self):
if self.progressBar:
self.progressBar.clear()
elif self.opts.quiet:
pass
elif self.opts.succinct:
sys.stdout.write('\n')
def update(self, test):
self.completed += 1
if self.opts.incremental:
update_incremental_cache(test)
if self.progressBar:
self.progressBar.update(float(self.completed)/self.numTests,
test.getFullName())
shouldShow = test.result.code.isFailure or \
self.opts.showAllOutput or \
(not self.opts.quiet and not self.opts.succinct)
if not shouldShow:
return
if self.progressBar:
self.progressBar.clear()
# Show the test result line.
test_name = test.getFullName()
print('%s: %s (%d of %d)' % (test.result.code.name, test_name,
self.completed, self.numTests))
# Show the test failure output, if requested.
if (test.result.code.isFailure and self.opts.showOutput) or \
self.opts.showAllOutput:
if test.result.code.isFailure:
print("%s TEST '%s' FAILED %s" % ('*'*20, test.getFullName(),
'*'*20))
print(test.result.output)
print("*" * 20)
# Report test metrics, if present.
if test.result.metrics:
print("%s TEST '%s' RESULTS %s" % ('*'*10, test.getFullName(),
'*'*10))
items = sorted(test.result.metrics.items())
for metric_name, value in items:
print('%s: %s ' % (metric_name, value.format()))
print("*" * 10)
# Ensure the output is flushed.
sys.stdout.flush()
def write_test_results(run, lit_config, testing_time, output_path):
try:
import json
except ImportError:
lit_config.fatal('test output unsupported with Python 2.5')
# Construct the data we will write.
data = {}
# Encode the current lit version as a schema version.
data['__version__'] = lit.__versioninfo__
data['elapsed'] = testing_time
# FIXME: Record some information on the lit configuration used?
# FIXME: Record information from the individual test suites?
# Encode the tests.
data['tests'] = tests_data = []
for test in run.tests:
test_data = {
'name' : test.getFullName(),
'code' : test.result.code.name,
'output' : test.result.output,
'elapsed' : test.result.elapsed }
# Add test metrics, if present.
if test.result.metrics:
test_data['metrics'] = metrics_data = {}
for key, value in test.result.metrics.items():
metrics_data[key] = value.todata()
tests_data.append(test_data)
# Write the output.
f = open(output_path, 'w')
try:
json.dump(data, f, indent=2, sort_keys=True)
f.write('\n')
finally:
f.close()
def update_incremental_cache(test):
if not test.result.code.isFailure:
return
fname = test.getFilePath()
os.utime(fname, None)
def sort_by_incremental_cache(run):
def sortIndex(test):
fname = test.getFilePath()
try:
return -os.path.getmtime(fname)
except:
return 0
run.tests.sort(key = lambda t: sortIndex(t))
def main(builtinParameters = {}):
# Use processes by default on Unix platforms.
isWindows = platform.system() == 'Windows'
useProcessesIsDefault = not isWindows
global options
from optparse import OptionParser, OptionGroup
parser = OptionParser("usage: %prog [options] {file-or-path}")
parser.add_option("", "--version", dest="show_version",
help="Show version and exit",
action="store_true", default=False)
parser.add_option("-j", "--threads", dest="numThreads", metavar="N",
help="Number of testing threads",
type=int, action="store", default=None)
parser.add_option("", "--config-prefix", dest="configPrefix",
metavar="NAME", help="Prefix for 'lit' config files",
action="store", default=None)
parser.add_option("-D", "--param", dest="userParameters",
metavar="NAME=VAL",
help="Add 'NAME' = 'VAL' to the user defined parameters",
type=str, action="append", default=[])
group = OptionGroup(parser, "Output Format")
# FIXME: I find these names very confusing, although I like the
# functionality.
group.add_option("-q", "--quiet", dest="quiet",
help="Suppress no error output",
action="store_true", default=False)
group.add_option("-s", "--succinct", dest="succinct",
help="Reduce amount of output",
action="store_true", default=False)
group.add_option("-v", "--verbose", dest="showOutput",
help="Show test output for failures",
action="store_true", default=False)
group.add_option("-a", "--show-all", dest="showAllOutput",
help="Display all commandlines and output",
action="store_true", default=False)
group.add_option("-o", "--output", dest="output_path",
help="Write test results to the provided path",
action="store", type=str, metavar="PATH")
group.add_option("", "--no-progress-bar", dest="useProgressBar",
help="Do not use curses based progress bar",
action="store_false", default=True)
group.add_option("", "--show-unsupported", dest="show_unsupported",
help="Show unsupported tests",
action="store_true", default=False)
group.add_option("", "--show-xfail", dest="show_xfail",
help="Show tests that were expected to fail",
action="store_true", default=False)
parser.add_option_group(group)
group = OptionGroup(parser, "Test Execution")
group.add_option("", "--path", dest="path",
help="Additional paths to add to testing environment",
action="append", type=str, default=[])
group.add_option("", "--vg", dest="useValgrind",
help="Run tests under valgrind",
action="store_true", default=False)
group.add_option("", "--vg-leak", dest="valgrindLeakCheck",
help="Check for memory leaks under valgrind",
action="store_true", default=False)
group.add_option("", "--vg-arg", dest="valgrindArgs", metavar="ARG",
help="Specify an extra argument for valgrind",
type=str, action="append", default=[])
group.add_option("", "--time-tests", dest="timeTests",
help="Track elapsed wall time for each test",
action="store_true", default=False)
group.add_option("", "--no-execute", dest="noExecute",
help="Don't execute any tests (assume PASS)",
action="store_true", default=False)
group.add_option("", "--xunit-xml-output", dest="xunit_output_file",
help=("Write XUnit-compatible XML test reports to the"
" specified file"), default=None)
group.add_option("", "--timeout", dest="maxIndividualTestTime",
help="Maximum time to spend running a single test (in seconds)."
"0 means no time limit. [Default: 0]",
type=int, default=None)
parser.add_option_group(group)
group = OptionGroup(parser, "Test Selection")
group.add_option("", "--max-tests", dest="maxTests", metavar="N",
help="Maximum number of tests to run",
action="store", type=int, default=None)
group.add_option("", "--max-time", dest="maxTime", metavar="N",
help="Maximum time to spend testing (in seconds)",
action="store", type=float, default=None)
group.add_option("", "--shuffle", dest="shuffle",
help="Run tests in random order",
action="store_true", default=False)
group.add_option("-i", "--incremental", dest="incremental",
help="Run modified and failing tests first (updates "
"mtimes)",
action="store_true", default=False)
group.add_option("", "--filter", dest="filter", metavar="REGEX",
help=("Only run tests with paths matching the given "
"regular expression"),
action="store", default=None)
parser.add_option_group(group)
group = OptionGroup(parser, "Debug and Experimental Options")
group.add_option("", "--debug", dest="debug",
help="Enable debugging (for 'lit' development)",
action="store_true", default=False)
group.add_option("", "--show-suites", dest="showSuites",
help="Show discovered test suites",
action="store_true", default=False)
group.add_option("", "--show-tests", dest="showTests",
help="Show all discovered tests",
action="store_true", default=False)
group.add_option("", "--use-processes", dest="useProcesses",
help="Run tests in parallel with processes (not threads)",
action="store_true", default=useProcessesIsDefault)
group.add_option("", "--use-threads", dest="useProcesses",
help="Run tests in parallel with threads (not processes)",
action="store_false", default=useProcessesIsDefault)
parser.add_option_group(group)
(opts, args) = parser.parse_args()
if opts.show_version:
print("lit %s" % (lit.__version__,))
return
if not args:
parser.error('No inputs specified')
if opts.numThreads is None:
# Python <2.5 has a race condition causing lit to always fail with numThreads>1
# http://bugs.python.org/issue1731717
# I haven't seen this bug occur with 2.5.2 and later, so only enable multiple
# threads by default there.
if sys.hexversion >= 0x2050200:
opts.numThreads = lit.util.detectCPUs()
else:
opts.numThreads = 1
inputs = args
# Create the user defined parameters.
userParams = dict(builtinParameters)
for entry in opts.userParameters:
if '=' not in entry:
name,opc = entry,''
else:
name,opc = entry.split('=', 1)
userParams[name] = opc
# Decide what the requested maximum indvidual test time should be
if opts.maxIndividualTestTime != None:
maxIndividualTestTime = opts.maxIndividualTestTime
else:
# Default is zero
maxIndividualTestTime = 0
# Create the global config object.
litConfig = lit.LitConfig.LitConfig(
progname = os.path.basename(sys.argv[0]),
path = opts.path,
quiet = opts.quiet,
useValgrind = opts.useValgrind,
valgrindLeakCheck = opts.valgrindLeakCheck,
valgrindArgs = opts.valgrindArgs,
noExecute = opts.noExecute,
debug = opts.debug,
isWindows = isWindows,
params = userParams,
config_prefix = opts.configPrefix,
maxIndividualTestTime = maxIndividualTestTime)
# Perform test discovery.
run = lit.run.Run(litConfig,
lit.discovery.find_tests_for_inputs(litConfig, inputs))
# After test discovery the configuration might have changed
# the maxIndividualTestTime. If we explicitly set this on the
# command line then override what was set in the test configuration
if opts.maxIndividualTestTime != None:
if opts.maxIndividualTestTime != litConfig.maxIndividualTestTime:
litConfig.note(('The test suite configuration requested an individual'
' test timeout of {0} seconds but a timeout of {1} seconds was'
' requested on the command line. Forcing timeout to be {1}'
' seconds')
.format(litConfig.maxIndividualTestTime,
opts.maxIndividualTestTime))
litConfig.maxIndividualTestTime = opts.maxIndividualTestTime
if opts.showSuites or opts.showTests:
# Aggregate the tests by suite.
suitesAndTests = {}
for result_test in run.tests:
if result_test.suite not in suitesAndTests:
suitesAndTests[result_test.suite] = []
suitesAndTests[result_test.suite].append(result_test)
suitesAndTests = list(suitesAndTests.items())
suitesAndTests.sort(key = lambda item: item[0].name)
# Show the suites, if requested.
if opts.showSuites:
print('-- Test Suites --')
for ts,ts_tests in suitesAndTests:
print(' %s - %d tests' %(ts.name, len(ts_tests)))
print(' Source Root: %s' % ts.source_root)
print(' Exec Root : %s' % ts.exec_root)
if ts.config.available_features:
print(' Available Features : %s' % ' '.join(
sorted(ts.config.available_features)))
# Show the tests, if requested.
if opts.showTests:
print('-- Available Tests --')
for ts,ts_tests in suitesAndTests:
ts_tests.sort(key = lambda test: test.path_in_suite)
for test in ts_tests:
print(' %s' % (test.getFullName(),))
# Exit.
sys.exit(0)
# Select and order the tests.
numTotalTests = len(run.tests)
# First, select based on the filter expression if given.
if opts.filter:
try:
rex = re.compile(opts.filter)
except:
parser.error("invalid regular expression for --filter: %r" % (
opts.filter))
run.tests = [result_test for result_test in run.tests
if rex.search(result_test.getFullName())]
# Then select the order.
if opts.shuffle:
random.shuffle(run.tests)
elif opts.incremental:
sort_by_incremental_cache(run)
else:
run.tests.sort(key = lambda t: (not t.isEarlyTest(), t.getFullName()))
# Finally limit the number of tests, if desired.
if opts.maxTests is not None:
run.tests = run.tests[:opts.maxTests]
# Don't create more threads than tests.
opts.numThreads = min(len(run.tests), opts.numThreads)
# Because some tests use threads internally, and at least on Linux each
# of these threads counts toward the current process limit, try to
# raise the (soft) process limit so that tests don't fail due to
# resource exhaustion.
try:
cpus = lit.util.detectCPUs()
desired_limit = opts.numThreads * cpus * 2 # the 2 is a safety factor
# Import the resource module here inside this try block because it
# will likely fail on Windows.
import resource
max_procs_soft, max_procs_hard = resource.getrlimit(resource.RLIMIT_NPROC)
desired_limit = min(desired_limit, max_procs_hard)
if max_procs_soft < desired_limit:
resource.setrlimit(resource.RLIMIT_NPROC, (desired_limit, max_procs_hard))
litConfig.note('raised the process limit from %d to %d' % \
(max_procs_soft, desired_limit))
except:
pass
extra = ''
if len(run.tests) != numTotalTests:
extra = ' of %d' % numTotalTests
header = '-- Testing: %d%s tests, %d threads --'%(len(run.tests), extra,
opts.numThreads)
progressBar = None
if not opts.quiet:
if opts.succinct and opts.useProgressBar:
try:
tc = lit.ProgressBar.TerminalController()
progressBar = lit.ProgressBar.ProgressBar(tc, header)
except ValueError:
print(header)
progressBar = lit.ProgressBar.SimpleProgressBar('Testing: ')
else:
print(header)
startTime = time.time()
display = TestingProgressDisplay(opts, len(run.tests), progressBar)
try:
run.execute_tests(display, opts.numThreads, opts.maxTime,
opts.useProcesses)
except KeyboardInterrupt:
sys.exit(2)
display.finish()
testing_time = time.time() - startTime
if not opts.quiet:
print('Testing Time: %.2fs' % (testing_time,))
# Write out the test data, if requested.
if opts.output_path is not None:
write_test_results(run, litConfig, testing_time, opts.output_path)
# List test results organized by kind.
hasFailures = False
byCode = {}
for test in run.tests:
if test.result.code not in byCode:
byCode[test.result.code] = []
byCode[test.result.code].append(test)
if test.result.code.isFailure:
hasFailures = True
# Print each test in any of the failing groups.
for title,code in (('Unexpected Passing Tests', lit.Test.XPASS),
('Failing Tests', lit.Test.FAIL),
('Unresolved Tests', lit.Test.UNRESOLVED),
('Unsupported Tests', lit.Test.UNSUPPORTED),
('Expected Failing Tests', lit.Test.XFAIL),
('Timed Out Tests', lit.Test.TIMEOUT)):
if (lit.Test.XFAIL == code and not opts.show_xfail) or \
(lit.Test.UNSUPPORTED == code and not opts.show_unsupported):
continue
elts = byCode.get(code)
if not elts:
continue
print('*'*20)
print('%s (%d):' % (title, len(elts)))
for test in elts:
print(' %s' % test.getFullName())
sys.stdout.write('\n')
if opts.timeTests and run.tests:
# Order by time.
test_times = [(test.getFullName(), test.result.elapsed)
for test in run.tests]
lit.util.printHistogram(test_times, title='Tests')
for name,code in (('Expected Passes ', lit.Test.PASS),
('Passes With Retry ', lit.Test.FLAKYPASS),
('Expected Failures ', lit.Test.XFAIL),
('Unsupported Tests ', lit.Test.UNSUPPORTED),
('Unresolved Tests ', lit.Test.UNRESOLVED),
('Unexpected Passes ', lit.Test.XPASS),
('Unexpected Failures', lit.Test.FAIL),
('Individual Timeouts', lit.Test.TIMEOUT)):
if opts.quiet and not code.isFailure:
continue
N = len(byCode.get(code,[]))
if N:
print(' %s: %d' % (name,N))
if opts.xunit_output_file:
# Collect the tests, indexed by test suite
by_suite = {}
for result_test in run.tests:
suite = result_test.suite.config.name
if suite not in by_suite:
by_suite[suite] = {
'passes' : 0,
'failures' : 0,
'tests' : [] }
by_suite[suite]['tests'].append(result_test)
if result_test.result.code.isFailure:
by_suite[suite]['failures'] += 1
else:
by_suite[suite]['passes'] += 1
xunit_output_file = open(opts.xunit_output_file, "w")
xunit_output_file.write("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n")
xunit_output_file.write("<testsuites>\n")
for suite_name, suite in by_suite.items():
safe_suite_name = suite_name.replace(".", "-")
xunit_output_file.write("<testsuite name='" + safe_suite_name + "'")
xunit_output_file.write(" tests='" + str(suite['passes'] +
suite['failures']) + "'")
xunit_output_file.write(" failures='" + str(suite['failures']) +
"'>\n")
for result_test in suite['tests']:
xunit_output_file.write(result_test.getJUnitXML() + "\n")
xunit_output_file.write("</testsuite>\n")
xunit_output_file.write("</testsuites>")
xunit_output_file.close()
# If we encountered any additional errors, exit abnormally.
if litConfig.numErrors:
sys.stderr.write('\n%d error(s), exiting.\n' % litConfig.numErrors)
sys.exit(2)
# Warn about warnings.
if litConfig.numWarnings:
sys.stderr.write('\n%d warning(s) in tests.\n' % litConfig.numWarnings)
if hasFailures:
sys.exit(1)
sys.exit(0)
if __name__=='__main__':
main()
|
JianpingZeng/xcc
|
xcc/java/utils/lit/lit/main.py
|
Python
|
bsd-3-clause
| 21,621 | 0.005041 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.