repo_name
stringlengths 6
100
| path
stringlengths 4
294
| copies
stringlengths 1
5
| size
stringlengths 4
6
| content
stringlengths 606
896k
| license
stringclasses 15
values |
---|---|---|---|---|---|
potatolondon/django-mediagenerator | mediagenerator/utils.py | 1 | 4864 | import functools
import threading
from . import settings as media_settings
from .settings import (GLOBAL_MEDIA_DIRS, PRODUCTION_MEDIA_URL,
IGNORE_APP_MEDIA_DIRS, MEDIA_GENERATORS, DEV_MEDIA_URL,
GENERATED_MEDIA_NAMES_MODULE)
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.utils.importlib import import_module
from django.utils.http import urlquote
import os
import re
try:
NAMES = import_module(GENERATED_MEDIA_NAMES_MODULE).NAMES
except (ImportError, AttributeError):
NAMES = None
_generated_names = {}
_backend_mapping = {}
_refresh_dev_names_lock = threading.Lock()
def memoize(func):
cache = {}
@functools.wraps(func)
def memoized(*args):
if args not in cache:
cache[args] = func(*args)
return cache[args]
return memoized
@memoize
def _load_generators():
return [load_backend(name)() for name in MEDIA_GENERATORS]
def refresh_dev_names():
global _generated_names, _backend_mapping
generated_names = {}
backend_mapping = {}
for backend in _load_generators():
for key, url, hash in backend.get_dev_output_names():
versioned_url = urlquote(url)
if hash:
versioned_url += '?version=' + hash
generated_names.setdefault(key, [])
generated_names[key].append(versioned_url)
backend_mapping[url] = backend
with _refresh_dev_names_lock:
_generated_names, _backend_mapping = generated_names, backend_mapping
def get_backend(filename):
return _backend_mapping[filename]
class _MatchNothing(object):
def match(self, content):
return False
def prepare_patterns(patterns, setting_name):
"""Helper function for patter-matching settings."""
if isinstance(patterns, basestring):
patterns = (patterns,)
if not patterns:
return _MatchNothing()
# First validate each pattern individually
for pattern in patterns:
try:
re.compile(pattern, re.U)
except re.error:
raise ValueError("""Pattern "%s" can't be compiled """
"in %s" % (pattern, setting_name))
# Now return a combined pattern
return re.compile('^(' + ')$|^('.join(patterns) + ')$', re.U)
def get_production_mapping():
if NAMES is None:
raise ImportError('Could not import %s. This '
'file is needed for production mode. Please '
'run manage.py generatemedia to create it.'
% GENERATED_MEDIA_NAMES_MODULE)
return NAMES
def get_media_mapping():
if media_settings.MEDIA_DEV_MODE:
return _generated_names
return get_production_mapping()
def get_media_url_mapping():
if media_settings.MEDIA_DEV_MODE:
base_url = DEV_MEDIA_URL
else:
base_url = PRODUCTION_MEDIA_URL
mapping = {}
for key, value in get_media_mapping().items():
if isinstance(value, basestring):
value = (value,)
mapping[key] = [base_url + url for url in value]
return mapping
def media_urls(key, refresh=False):
if media_settings.MEDIA_DEV_MODE:
if refresh:
refresh_dev_names()
return [DEV_MEDIA_URL + url for url in _generated_names[key]]
return [PRODUCTION_MEDIA_URL + get_production_mapping()[key]]
def media_url(key, refresh=False):
urls = media_urls(key, refresh=refresh)
if len(urls) == 1:
return urls[0]
raise ValueError('media_url() only works with URLs that contain exactly '
'one file. Use media_urls() (or {% include_media %} in templates) instead.')
@memoize
def get_media_dirs():
media_dirs = GLOBAL_MEDIA_DIRS[:]
for app in settings.INSTALLED_APPS:
if app in IGNORE_APP_MEDIA_DIRS:
continue
for name in (u'static', u'media'):
app_root = os.path.dirname(import_module(app).__file__)
media_dirs.append(os.path.join(app_root, name))
return media_dirs
def find_file(name, media_dirs=None):
if media_dirs is None:
media_dirs = get_media_dirs()
for root in media_dirs:
path = os.path.normpath(os.path.join(root, name))
if os.path.isfile(path):
return path
def read_text_file(path):
fp = open(path, 'r')
output = fp.read()
fp.close()
return output.decode('utf8')
@memoize
def load_backend(path):
module_name, attr_name = path.rsplit('.', 1)
try:
mod = import_module(module_name)
except (ImportError, ValueError), e:
raise ImproperlyConfigured('Error importing backend module %s: "%s"' % (module_name, e))
try:
return getattr(mod, attr_name)
except AttributeError:
raise ImproperlyConfigured('Module "%s" does not define a "%s" backend' % (module_name, attr_name))
| bsd-3-clause |
erdc/proteus | proteus/tests/surface_tension/rising_bubble_rans3p/pressure_n.py | 1 | 1214 | from __future__ import absolute_import
from proteus import *
from proteus.default_n import *
try:
from .pressure_p import *
except:
from pressure_p import *
triangleOptions = triangleOptions
femSpaces = {0:pbasis}
stepController=FixedStep
#matrix type
numericalFluxType = NumericalFlux.ConstantAdvection_exterior
matrix = LinearAlgebraTools.SparseMatrix
linear_solver_options_prefix = 'pressure_'
if useSuperlu:
multilevelLinearSolver = LinearSolvers.LU
levelLinearSolver = LinearSolvers.LU
else:
multilevelLinearSolver = KSP_petsc4py
levelLinearSolver = KSP_petsc4py
parallelPartitioningType = parallelPartitioningType
nLayersOfOverlapForParallel = nLayersOfOverlapForParallel
nonlinearSmoother = None
linearSmoother = None
multilevelNonlinearSolver = NonlinearSolvers.Newton
levelNonlinearSolver = NonlinearSolvers.Newton
#linear solve rtolerance
linTolFac = 0.0
l_atol_res = 0.1*pressure_nl_atol_res
tolFac = 0.0
nl_atol_res = pressure_nl_atol_res
maxLineSearches = 0
nonlinearSolverConvergenceTest = 'r'
levelNonlinearSolverConvergenceTest = 'r'
linearSolverConvergenceTest = 'r-true'
periodicDirichletConditions=None
conservativeFlux=None
| mit |
kxliugang/edx-platform | lms/djangoapps/courseware/migrations/0007_allow_null_version_in_history.py | 114 | 7638 | # -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Changing field 'StudentModuleHistory.version'
db.alter_column('courseware_studentmodulehistory', 'version', self.gf('django.db.models.fields.CharField')(max_length=255, null=True))
def backwards(self, orm):
# User chose to not deal with backwards NULL issues for 'StudentModuleHistory.version'
raise RuntimeError("Cannot reverse this migration. 'StudentModuleHistory.version' and its values cannot be restored.")
models = {
'auth.group': {
'Meta': {'object_name': 'Group'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
},
'auth.permission': {
'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'},
'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
},
'auth.user': {
'Meta': {'object_name': 'User'},
'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
},
'contenttypes.contenttype': {
'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
},
'courseware.offlinecomputedgrade': {
'Meta': {'unique_together': "(('user', 'course_id'),)", 'object_name': 'OfflineComputedGrade'},
'course_id': ('django.db.models.fields.CharField', [], {'max_length': '255', 'db_index': 'True'}),
'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'null': 'True', 'db_index': 'True', 'blank': 'True'}),
'gradeset': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'updated': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'db_index': 'True', 'blank': 'True'}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"})
},
'courseware.offlinecomputedgradelog': {
'Meta': {'ordering': "['-created']", 'object_name': 'OfflineComputedGradeLog'},
'course_id': ('django.db.models.fields.CharField', [], {'max_length': '255', 'db_index': 'True'}),
'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'null': 'True', 'db_index': 'True', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'nstudents': ('django.db.models.fields.IntegerField', [], {'default': '0'}),
'seconds': ('django.db.models.fields.IntegerField', [], {'default': '0'})
},
'courseware.studentmodule': {
'Meta': {'unique_together': "(('student', 'module_state_key', 'course_id'),)", 'object_name': 'StudentModule'},
'course_id': ('django.db.models.fields.CharField', [], {'max_length': '255', 'db_index': 'True'}),
'created': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'db_index': 'True', 'blank': 'True'}),
'done': ('django.db.models.fields.CharField', [], {'default': "'na'", 'max_length': '8', 'db_index': 'True'}),
'grade': ('django.db.models.fields.FloatField', [], {'db_index': 'True', 'null': 'True', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'max_grade': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}),
'modified': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'db_index': 'True', 'blank': 'True'}),
'module_state_key': ('django.db.models.fields.CharField', [], {'max_length': '255', 'db_column': "'module_id'", 'db_index': 'True'}),
'module_type': ('django.db.models.fields.CharField', [], {'default': "'problem'", 'max_length': '32', 'db_index': 'True'}),
'state': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'student': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"})
},
'courseware.studentmodulehistory': {
'Meta': {'object_name': 'StudentModuleHistory'},
'created': ('django.db.models.fields.DateTimeField', [], {'db_index': 'True'}),
'grade': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'max_grade': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}),
'state': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'student_module': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['courseware.StudentModule']"}),
'version': ('django.db.models.fields.CharField', [], {'default': 'None', 'max_length': '255', 'null': 'True', 'db_index': 'True'})
}
}
complete_apps = ['courseware']
| agpl-3.0 |
bnbowman/HlaTools | src/pbhla/fasta/subset_sequences.py | 1 | 1114 | #! /usr/bin/env python
import sys
from pbcore.io.FastaIO import FastaReader, FastaWriter
from pbhla.fasta.utils import write_fasta
def subset_sequences( fasta_file, summary_file, output_file ):
seq_ids = identify_sequences( summary_file )
sequences = subset_sequence_records( fasta_file, seq_ids )
write_fasta( sequences, output_file )
def identify_sequences( summary_file ):
sequence_ids = []
for line in open( summary_file ):
if line.startswith('Locus'):
continue
sequence_ids.append( line.split()[1] )
return set(sequence_ids)
def subset_sequence_records( fasta_file, seq_ids ):
sequences = []
for record in FastaReader( fasta_file ):
name = record.name.split()[0]
name = name.split('|')[0]
if name.endswith('_cns'):
name = name[:-4]
if name in seq_ids:
sequences.append( record )
return sequences
if __name__ == '__main__':
fasta_file = sys.argv[1]
summary_file = sys.argv[2]
output_file = sys.argv[3]
subset_sequences( fasta_file, summary_file, output_file )
| bsd-3-clause |
harshita-gupta/Harvard-FRSEM-Catalog-2016-17 | flask/lib/python2.7/site-packages/sqlalchemy/testing/plugin/plugin_base.py | 7 | 17335 | # plugin/plugin_base.py
# Copyright (C) 2005-2016 the SQLAlchemy authors and contributors
# <see AUTHORS file>
#
# This module is part of SQLAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
"""Testing extensions.
this module is designed to work as a testing-framework-agnostic library,
so that we can continue to support nose and also begin adding new
functionality via py.test.
"""
from __future__ import absolute_import
import sys
import re
py3k = sys.version_info >= (3, 0)
if py3k:
import configparser
else:
import ConfigParser as configparser
# late imports
fixtures = None
engines = None
exclusions = None
warnings = None
profiling = None
assertions = None
requirements = None
config = None
testing = None
util = None
file_config = None
logging = None
include_tags = set()
exclude_tags = set()
options = None
def setup_options(make_option):
make_option("--log-info", action="callback", type="string", callback=_log,
help="turn on info logging for <LOG> (multiple OK)")
make_option("--log-debug", action="callback",
type="string", callback=_log,
help="turn on debug logging for <LOG> (multiple OK)")
make_option("--db", action="append", type="string", dest="db",
help="Use prefab database uri. Multiple OK, "
"first one is run by default.")
make_option('--dbs', action='callback', callback=_list_dbs,
help="List available prefab dbs")
make_option("--dburi", action="append", type="string", dest="dburi",
help="Database uri. Multiple OK, "
"first one is run by default.")
make_option("--dropfirst", action="store_true", dest="dropfirst",
help="Drop all tables in the target database first")
make_option("--backend-only", action="store_true", dest="backend_only",
help="Run only tests marked with __backend__")
make_option("--low-connections", action="store_true",
dest="low_connections",
help="Use a low number of distinct connections - "
"i.e. for Oracle TNS")
make_option("--write-idents", type="string", dest="write_idents",
help="write out generated follower idents to <file>, "
"when -n<num> is used")
make_option("--reversetop", action="store_true",
dest="reversetop", default=False,
help="Use a random-ordering set implementation in the ORM "
"(helps reveal dependency issues)")
make_option("--requirements", action="callback", type="string",
callback=_requirements_opt,
help="requirements class for testing, overrides setup.cfg")
make_option("--with-cdecimal", action="store_true",
dest="cdecimal", default=False,
help="Monkeypatch the cdecimal library into Python 'decimal' "
"for all tests")
make_option("--include-tag", action="callback", callback=_include_tag,
type="string",
help="Include tests with tag <tag>")
make_option("--exclude-tag", action="callback", callback=_exclude_tag,
type="string",
help="Exclude tests with tag <tag>")
make_option("--write-profiles", action="store_true",
dest="write_profiles", default=False,
help="Write/update failing profiling data.")
make_option("--force-write-profiles", action="store_true",
dest="force_write_profiles", default=False,
help="Unconditionally write/update profiling data.")
def configure_follower(follower_ident):
"""Configure required state for a follower.
This invokes in the parent process and typically includes
database creation.
"""
from sqlalchemy.testing import provision
provision.FOLLOWER_IDENT = follower_ident
def memoize_important_follower_config(dict_):
"""Store important configuration we will need to send to a follower.
This invokes in the parent process after normal config is set up.
This is necessary as py.test seems to not be using forking, so we
start with nothing in memory, *but* it isn't running our argparse
callables, so we have to just copy all of that over.
"""
dict_['memoized_config'] = {
'include_tags': include_tags,
'exclude_tags': exclude_tags
}
def restore_important_follower_config(dict_):
"""Restore important configuration needed by a follower.
This invokes in the follower process.
"""
global include_tags, exclude_tags
include_tags.update(dict_['memoized_config']['include_tags'])
exclude_tags.update(dict_['memoized_config']['exclude_tags'])
def read_config():
global file_config
file_config = configparser.ConfigParser()
file_config.read(['setup.cfg', 'test.cfg'])
def pre_begin(opt):
"""things to set up early, before coverage might be setup."""
global options
options = opt
for fn in pre_configure:
fn(options, file_config)
def set_coverage_flag(value):
options.has_coverage = value
_skip_test_exception = None
def set_skip_test(exc):
global _skip_test_exception
_skip_test_exception = exc
def post_begin():
"""things to set up later, once we know coverage is running."""
# Lazy setup of other options (post coverage)
for fn in post_configure:
fn(options, file_config)
# late imports, has to happen after config as well
# as nose plugins like coverage
global util, fixtures, engines, exclusions, \
assertions, warnings, profiling,\
config, testing
from sqlalchemy import testing # noqa
from sqlalchemy.testing import fixtures, engines, exclusions # noqa
from sqlalchemy.testing import assertions, warnings, profiling # noqa
from sqlalchemy.testing import config # noqa
from sqlalchemy import util # noqa
warnings.setup_filters()
def _log(opt_str, value, parser):
global logging
if not logging:
import logging
logging.basicConfig()
if opt_str.endswith('-info'):
logging.getLogger(value).setLevel(logging.INFO)
elif opt_str.endswith('-debug'):
logging.getLogger(value).setLevel(logging.DEBUG)
def _list_dbs(*args):
print("Available --db options (use --dburi to override)")
for macro in sorted(file_config.options('db')):
print("%20s\t%s" % (macro, file_config.get('db', macro)))
sys.exit(0)
def _requirements_opt(opt_str, value, parser):
_setup_requirements(value)
def _exclude_tag(opt_str, value, parser):
exclude_tags.add(value.replace('-', '_'))
def _include_tag(opt_str, value, parser):
include_tags.add(value.replace('-', '_'))
pre_configure = []
post_configure = []
def pre(fn):
pre_configure.append(fn)
return fn
def post(fn):
post_configure.append(fn)
return fn
@pre
def _setup_options(opt, file_config):
global options
options = opt
@pre
def _monkeypatch_cdecimal(options, file_config):
if options.cdecimal:
import cdecimal
sys.modules['decimal'] = cdecimal
@post
def _init_skiptest(options, file_config):
from sqlalchemy.testing import config
config._skip_test_exception = _skip_test_exception
@post
def _engine_uri(options, file_config):
from sqlalchemy.testing import config
from sqlalchemy import testing
from sqlalchemy.testing import provision
if options.dburi:
db_urls = list(options.dburi)
else:
db_urls = []
if options.db:
for db_token in options.db:
for db in re.split(r'[,\s]+', db_token):
if db not in file_config.options('db'):
raise RuntimeError(
"Unknown URI specifier '%s'. "
"Specify --dbs for known uris."
% db)
else:
db_urls.append(file_config.get('db', db))
if not db_urls:
db_urls.append(file_config.get('db', 'default'))
for db_url in db_urls:
cfg = provision.setup_config(
db_url, options, file_config, provision.FOLLOWER_IDENT)
if not config._current:
cfg.set_as_current(cfg, testing)
@post
def _requirements(options, file_config):
requirement_cls = file_config.get('sqla_testing', "requirement_cls")
_setup_requirements(requirement_cls)
def _setup_requirements(argument):
from sqlalchemy.testing import config
from sqlalchemy import testing
if config.requirements is not None:
return
modname, clsname = argument.split(":")
# importlib.import_module() only introduced in 2.7, a little
# late
mod = __import__(modname)
for component in modname.split(".")[1:]:
mod = getattr(mod, component)
req_cls = getattr(mod, clsname)
config.requirements = testing.requires = req_cls()
@post
def _prep_testing_database(options, file_config):
from sqlalchemy.testing import config, util
from sqlalchemy.testing.exclusions import against
from sqlalchemy import schema, inspect
if options.dropfirst:
for cfg in config.Config.all_configs():
e = cfg.db
inspector = inspect(e)
try:
view_names = inspector.get_view_names()
except NotImplementedError:
pass
else:
for vname in view_names:
e.execute(schema._DropView(
schema.Table(vname, schema.MetaData())
))
if config.requirements.schemas.enabled_for_config(cfg):
try:
view_names = inspector.get_view_names(
schema="test_schema")
except NotImplementedError:
pass
else:
for vname in view_names:
e.execute(schema._DropView(
schema.Table(vname, schema.MetaData(),
schema="test_schema")
))
util.drop_all_tables(e, inspector)
if config.requirements.schemas.enabled_for_config(cfg):
util.drop_all_tables(e, inspector, schema=cfg.test_schema)
if against(cfg, "postgresql"):
from sqlalchemy.dialects import postgresql
for enum in inspector.get_enums("*"):
e.execute(postgresql.DropEnumType(
postgresql.ENUM(
name=enum['name'],
schema=enum['schema'])))
@post
def _reverse_topological(options, file_config):
if options.reversetop:
from sqlalchemy.orm.util import randomize_unitofwork
randomize_unitofwork()
@post
def _post_setup_options(opt, file_config):
from sqlalchemy.testing import config
config.options = options
config.file_config = file_config
@post
def _setup_profiling(options, file_config):
from sqlalchemy.testing import profiling
profiling._profile_stats = profiling.ProfileStatsFile(
file_config.get('sqla_testing', 'profile_file'))
def want_class(cls):
if not issubclass(cls, fixtures.TestBase):
return False
elif cls.__name__.startswith('_'):
return False
elif config.options.backend_only and not getattr(cls, '__backend__',
False):
return False
else:
return True
def want_method(cls, fn):
if not fn.__name__.startswith("test_"):
return False
elif fn.__module__ is None:
return False
elif include_tags:
return (
hasattr(cls, '__tags__') and
exclusions.tags(cls.__tags__).include_test(
include_tags, exclude_tags)
) or (
hasattr(fn, '_sa_exclusion_extend') and
fn._sa_exclusion_extend.include_test(
include_tags, exclude_tags)
)
elif exclude_tags and hasattr(cls, '__tags__'):
return exclusions.tags(cls.__tags__).include_test(
include_tags, exclude_tags)
elif exclude_tags and hasattr(fn, '_sa_exclusion_extend'):
return fn._sa_exclusion_extend.include_test(include_tags, exclude_tags)
else:
return True
def generate_sub_tests(cls, module):
if getattr(cls, '__backend__', False):
for cfg in _possible_configs_for_cls(cls):
name = "%s_%s_%s" % (cls.__name__, cfg.db.name, cfg.db.driver)
subcls = type(
name,
(cls, ),
{
"__only_on__": ("%s+%s" % (cfg.db.name, cfg.db.driver)),
}
)
setattr(module, name, subcls)
yield subcls
else:
yield cls
def start_test_class(cls):
_do_skips(cls)
_setup_engine(cls)
def stop_test_class(cls):
#from sqlalchemy import inspect
#assert not inspect(testing.db).get_table_names()
engines.testing_reaper._stop_test_ctx()
try:
if not options.low_connections:
assertions.global_cleanup_assertions()
finally:
_restore_engine()
def _restore_engine():
config._current.reset(testing)
def _setup_engine(cls):
if getattr(cls, '__engine_options__', None):
eng = engines.testing_engine(options=cls.__engine_options__)
config._current.push_engine(eng, testing)
def before_test(test, test_module_name, test_class, test_name):
# like a nose id, e.g.:
# "test.aaa_profiling.test_compiler.CompileTest.test_update_whereclause"
name = test_class.__name__
suffix = "_%s_%s" % (config.db.name, config.db.driver)
if name.endswith(suffix):
name = name[0:-(len(suffix))]
id_ = "%s.%s.%s" % (test_module_name, name, test_name)
profiling._current_test = id_
def after_test(test):
engines.testing_reaper._after_test_ctx()
def _possible_configs_for_cls(cls, reasons=None):
all_configs = set(config.Config.all_configs())
if cls.__unsupported_on__:
spec = exclusions.db_spec(*cls.__unsupported_on__)
for config_obj in list(all_configs):
if spec(config_obj):
all_configs.remove(config_obj)
if getattr(cls, '__only_on__', None):
spec = exclusions.db_spec(*util.to_list(cls.__only_on__))
for config_obj in list(all_configs):
if not spec(config_obj):
all_configs.remove(config_obj)
if hasattr(cls, '__requires__'):
requirements = config.requirements
for config_obj in list(all_configs):
for requirement in cls.__requires__:
check = getattr(requirements, requirement)
skip_reasons = check.matching_config_reasons(config_obj)
if skip_reasons:
all_configs.remove(config_obj)
if reasons is not None:
reasons.extend(skip_reasons)
break
if hasattr(cls, '__prefer_requires__'):
non_preferred = set()
requirements = config.requirements
for config_obj in list(all_configs):
for requirement in cls.__prefer_requires__:
check = getattr(requirements, requirement)
if not check.enabled_for_config(config_obj):
non_preferred.add(config_obj)
if all_configs.difference(non_preferred):
all_configs.difference_update(non_preferred)
return all_configs
def _do_skips(cls):
reasons = []
all_configs = _possible_configs_for_cls(cls, reasons)
if getattr(cls, '__skip_if__', False):
for c in getattr(cls, '__skip_if__'):
if c():
config.skip_test("'%s' skipped by %s" % (
cls.__name__, c.__name__)
)
if not all_configs:
if getattr(cls, '__backend__', False):
msg = "'%s' unsupported for implementation '%s'" % (
cls.__name__, cls.__only_on__)
else:
msg = "'%s' unsupported on any DB implementation %s%s" % (
cls.__name__,
", ".join(
"'%s(%s)+%s'" % (
config_obj.db.name,
".".join(
str(dig) for dig in
config_obj.db.dialect.server_version_info),
config_obj.db.driver
)
for config_obj in config.Config.all_configs()
),
", ".join(reasons)
)
config.skip_test(msg)
elif hasattr(cls, '__prefer_backends__'):
non_preferred = set()
spec = exclusions.db_spec(*util.to_list(cls.__prefer_backends__))
for config_obj in all_configs:
if not spec(config_obj):
non_preferred.add(config_obj)
if all_configs.difference(non_preferred):
all_configs.difference_update(non_preferred)
if config._current not in all_configs:
_setup_config(all_configs.pop(), cls)
def _setup_config(config_obj, ctx):
config._current.push(config_obj, testing)
| mit |
LoHChina/nova | nova/tests/functional/v3/test_used_limits.py | 36 | 1457 | # Copyright 2012 Nebula, Inc.
# Copyright 2013 IBM Corp.
#
# 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 nova.tests.functional.v3 import api_sample_base
class UsedLimitsSamplesJsonTest(api_sample_base.ApiSampleTestBaseV3):
ADMIN_API = True
extension_name = "os-used-limits"
extra_extensions_to_load = ["limits"]
def test_get_used_limits(self):
# Get api sample to used limits.
response = self._do_get('limits')
subs = self._get_regexes()
self._verify_response('usedlimits-get-resp', subs, response, 200)
def test_get_used_limits_for_admin(self):
# TODO(sdague): if we split the admin tests out the whole
# class doesn't need admin api enabled.
tenant_id = 'openstack'
response = self._do_get('limits?tenant_id=%s' % tenant_id)
subs = self._get_regexes()
self._verify_response('usedlimits-get-resp', subs, response, 200)
| apache-2.0 |
spark-test/spark | python/pyspark/sql/tests/test_column.py | 4 | 7120 | # -*- encoding: utf-8 -*-
#
# 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 sys
from pyspark.sql import Column, Row
from pyspark.sql.types import *
from pyspark.sql.utils import AnalysisException
from pyspark.testing.sqlutils import ReusedSQLTestCase
class ColumnTests(ReusedSQLTestCase):
def test_column_name_encoding(self):
"""Ensure that created columns has `str` type consistently."""
columns = self.spark.createDataFrame([('Alice', 1)], ['name', u'age']).columns
self.assertEqual(columns, ['name', 'age'])
self.assertTrue(isinstance(columns[0], str))
self.assertTrue(isinstance(columns[1], str))
def test_and_in_expression(self):
self.assertEqual(4, self.df.filter((self.df.key <= 10) & (self.df.value <= "2")).count())
self.assertRaises(ValueError, lambda: (self.df.key <= 10) and (self.df.value <= "2"))
self.assertEqual(14, self.df.filter((self.df.key <= 3) | (self.df.value < "2")).count())
self.assertRaises(ValueError, lambda: self.df.key <= 3 or self.df.value < "2")
self.assertEqual(99, self.df.filter(~(self.df.key == 1)).count())
self.assertRaises(ValueError, lambda: not self.df.key == 1)
def test_validate_column_types(self):
from pyspark.sql.functions import udf, to_json
from pyspark.sql.column import _to_java_column
self.assertTrue("Column" in _to_java_column("a").getClass().toString())
self.assertTrue("Column" in _to_java_column(u"a").getClass().toString())
self.assertTrue("Column" in _to_java_column(self.spark.range(1).id).getClass().toString())
self.assertRaisesRegexp(
TypeError,
"Invalid argument, not a string or column",
lambda: _to_java_column(1))
class A():
pass
self.assertRaises(TypeError, lambda: _to_java_column(A()))
self.assertRaises(TypeError, lambda: _to_java_column([]))
self.assertRaisesRegexp(
TypeError,
"Invalid argument, not a string or column",
lambda: udf(lambda x: x)(None))
self.assertRaises(TypeError, lambda: to_json(1))
def test_column_operators(self):
ci = self.df.key
cs = self.df.value
c = ci == cs
self.assertTrue(isinstance((- ci - 1 - 2) % 3 * 2.5 / 3.5, Column))
rcc = (1 + ci), (1 - ci), (1 * ci), (1 / ci), (1 % ci), (1 ** ci), (ci ** 1)
self.assertTrue(all(isinstance(c, Column) for c in rcc))
cb = [ci == 5, ci != 0, ci > 3, ci < 4, ci >= 0, ci <= 7]
self.assertTrue(all(isinstance(c, Column) for c in cb))
cbool = (ci & ci), (ci | ci), (~ci)
self.assertTrue(all(isinstance(c, Column) for c in cbool))
css = cs.contains('a'), cs.like('a'), cs.rlike('a'), cs.asc(), cs.desc(),\
cs.startswith('a'), cs.endswith('a'), ci.eqNullSafe(cs)
self.assertTrue(all(isinstance(c, Column) for c in css))
self.assertTrue(isinstance(ci.cast(LongType()), Column))
self.assertRaisesRegexp(ValueError,
"Cannot apply 'in' operator against a column",
lambda: 1 in cs)
def test_column_accessor(self):
from pyspark.sql.functions import col
self.assertIsInstance(col("foo")[1:3], Column)
self.assertIsInstance(col("foo")[0], Column)
self.assertIsInstance(col("foo")["bar"], Column)
self.assertRaises(ValueError, lambda: col("foo")[0:10:2])
def test_column_select(self):
df = self.df
self.assertEqual(self.testData, df.select("*").collect())
self.assertEqual(self.testData, df.select(df.key, df.value).collect())
self.assertEqual([Row(value='1')], df.where(df.key == 1).select(df.value).collect())
def test_access_column(self):
df = self.df
self.assertTrue(isinstance(df.key, Column))
self.assertTrue(isinstance(df['key'], Column))
self.assertTrue(isinstance(df[0], Column))
self.assertRaises(IndexError, lambda: df[2])
self.assertRaises(AnalysisException, lambda: df["bad_key"])
self.assertRaises(TypeError, lambda: df[{}])
def test_column_name_with_non_ascii(self):
if sys.version >= '3':
columnName = "ζ°ι"
self.assertTrue(isinstance(columnName, str))
else:
columnName = unicode("ζ°ι", "utf-8")
self.assertTrue(isinstance(columnName, unicode))
schema = StructType([StructField(columnName, LongType(), True)])
df = self.spark.createDataFrame([(1,)], schema)
self.assertEqual(schema, df.schema)
self.assertEqual("DataFrame[ζ°ι: bigint]", str(df))
self.assertEqual([("ζ°ι", 'bigint')], df.dtypes)
self.assertEqual(1, df.select("ζ°ι").first()[0])
self.assertEqual(1, df.select(df["ζ°ι"]).first()[0])
def test_field_accessor(self):
df = self.sc.parallelize([Row(l=[1], r=Row(a=1, b="b"), d={"k": "v"})]).toDF()
self.assertEqual(1, df.select(df.l[0]).first()[0])
self.assertEqual(1, df.select(df.r["a"]).first()[0])
self.assertEqual(1, df.select(df["r.a"]).first()[0])
self.assertEqual("b", df.select(df.r["b"]).first()[0])
self.assertEqual("b", df.select(df["r.b"]).first()[0])
self.assertEqual("v", df.select(df.d["k"]).first()[0])
def test_bitwise_operations(self):
from pyspark.sql import functions
row = Row(a=170, b=75)
df = self.spark.createDataFrame([row])
result = df.select(df.a.bitwiseAND(df.b)).collect()[0].asDict()
self.assertEqual(170 & 75, result['(a & b)'])
result = df.select(df.a.bitwiseOR(df.b)).collect()[0].asDict()
self.assertEqual(170 | 75, result['(a | b)'])
result = df.select(df.a.bitwiseXOR(df.b)).collect()[0].asDict()
self.assertEqual(170 ^ 75, result['(a ^ b)'])
result = df.select(functions.bitwiseNOT(df.b)).collect()[0].asDict()
self.assertEqual(~75, result['~b'])
if __name__ == "__main__":
import unittest
from pyspark.sql.tests.test_column import *
try:
import xmlrunner
testRunner = xmlrunner.XMLTestRunner(output='target/test-reports', verbosity=2)
except ImportError:
testRunner = None
unittest.main(testRunner=testRunner, verbosity=2)
| apache-2.0 |
wanglongqi/sympy | sympy/combinatorics/permutations.py | 40 | 77752 | from __future__ import print_function, division
import random
from collections import defaultdict
from sympy.core import Basic
from sympy.core.compatibility import is_sequence, reduce, range
from sympy.utilities.iterables import (flatten, has_variety, minlex,
has_dups, runs)
from sympy.polys.polytools import lcm
from sympy.matrices import zeros
from mpmath.libmp.libintmath import ifac
def _af_rmul(a, b):
"""
Return the product b*a; input and output are array forms. The ith value
is a[b[i]].
Examples
========
>>> from sympy.combinatorics.permutations import _af_rmul, Permutation
>>> Permutation.print_cyclic = False
>>> a, b = [1, 0, 2], [0, 2, 1]
>>> _af_rmul(a, b)
[1, 2, 0]
>>> [a[b[i]] for i in range(3)]
[1, 2, 0]
This handles the operands in reverse order compared to the ``*`` operator:
>>> a = Permutation(a)
>>> b = Permutation(b)
>>> list(a*b)
[2, 0, 1]
>>> [b(a(i)) for i in range(3)]
[2, 0, 1]
See Also
========
rmul, _af_rmuln
"""
return [a[i] for i in b]
def _af_rmuln(*abc):
"""
Given [a, b, c, ...] return the product of ...*c*b*a using array forms.
The ith value is a[b[c[i]]].
Examples
========
>>> from sympy.combinatorics.permutations import _af_rmul, Permutation
>>> Permutation.print_cyclic = False
>>> a, b = [1, 0, 2], [0, 2, 1]
>>> _af_rmul(a, b)
[1, 2, 0]
>>> [a[b[i]] for i in range(3)]
[1, 2, 0]
This handles the operands in reverse order compared to the ``*`` operator:
>>> a = Permutation(a); b = Permutation(b)
>>> list(a*b)
[2, 0, 1]
>>> [b(a(i)) for i in range(3)]
[2, 0, 1]
See Also
========
rmul, _af_rmul
"""
a = abc
m = len(a)
if m == 3:
p0, p1, p2 = a
return [p0[p1[i]] for i in p2]
if m == 4:
p0, p1, p2, p3 = a
return [p0[p1[p2[i]]] for i in p3]
if m == 5:
p0, p1, p2, p3, p4 = a
return [p0[p1[p2[p3[i]]]] for i in p4]
if m == 6:
p0, p1, p2, p3, p4, p5 = a
return [p0[p1[p2[p3[p4[i]]]]] for i in p5]
if m == 7:
p0, p1, p2, p3, p4, p5, p6 = a
return [p0[p1[p2[p3[p4[p5[i]]]]]] for i in p6]
if m == 8:
p0, p1, p2, p3, p4, p5, p6, p7 = a
return [p0[p1[p2[p3[p4[p5[p6[i]]]]]]] for i in p7]
if m == 1:
return a[0][:]
if m == 2:
a, b = a
return [a[i] for i in b]
if m == 0:
raise ValueError("String must not be empty")
p0 = _af_rmuln(*a[:m//2])
p1 = _af_rmuln(*a[m//2:])
return [p0[i] for i in p1]
def _af_parity(pi):
"""
Computes the parity of a permutation in array form.
The parity of a permutation reflects the parity of the
number of inversions in the permutation, i.e., the
number of pairs of x and y such that x > y but p[x] < p[y].
Examples
========
>>> from sympy.combinatorics.permutations import _af_parity
>>> _af_parity([0, 1, 2, 3])
0
>>> _af_parity([3, 2, 0, 1])
1
See Also
========
Permutation
"""
n = len(pi)
a = [0] * n
c = 0
for j in range(n):
if a[j] == 0:
c += 1
a[j] = 1
i = j
while pi[i] != j:
i = pi[i]
a[i] = 1
return (n - c) % 2
def _af_invert(a):
"""
Finds the inverse, ~A, of a permutation, A, given in array form.
Examples
========
>>> from sympy.combinatorics.permutations import _af_invert, _af_rmul
>>> A = [1, 2, 0, 3]
>>> _af_invert(A)
[2, 0, 1, 3]
>>> _af_rmul(_, A)
[0, 1, 2, 3]
See Also
========
Permutation, __invert__
"""
inv_form = [0] * len(a)
for i, ai in enumerate(a):
inv_form[ai] = i
return inv_form
def _af_pow(a, n):
"""
Routine for finding powers of a permutation.
Examples
========
>>> from sympy.combinatorics.permutations import Permutation, _af_pow
>>> Permutation.print_cyclic = False
>>> p = Permutation([2, 0, 3, 1])
>>> p.order()
4
>>> _af_pow(p._array_form, 4)
[0, 1, 2, 3]
"""
if n == 0:
return list(range(len(a)))
if n < 0:
return _af_pow(_af_invert(a), -n)
if n == 1:
return a[:]
elif n == 2:
b = [a[i] for i in a]
elif n == 3:
b = [a[a[i]] for i in a]
elif n == 4:
b = [a[a[a[i]]] for i in a]
else:
# use binary multiplication
b = list(range(len(a)))
while 1:
if n & 1:
b = [b[i] for i in a]
n -= 1
if not n:
break
if n % 4 == 0:
a = [a[a[a[i]]] for i in a]
n = n // 4
elif n % 2 == 0:
a = [a[i] for i in a]
n = n // 2
return b
def _af_commutes_with(a, b):
"""
Checks if the two permutations with array forms
given by ``a`` and ``b`` commute.
Examples
========
>>> from sympy.combinatorics.permutations import _af_commutes_with
>>> _af_commutes_with([1, 2, 0], [0, 2, 1])
False
See Also
========
Permutation, commutes_with
"""
return not any(a[b[i]] != b[a[i]] for i in range(len(a) - 1))
class Cycle(dict):
"""
Wrapper around dict which provides the functionality of a disjoint cycle.
A cycle shows the rule to use to move subsets of elements to obtain
a permutation. The Cycle class is more flexible that Permutation in
that 1) all elements need not be present in order to investigate how
multiple cycles act in sequence and 2) it can contain singletons:
>>> from sympy.combinatorics.permutations import Perm, Cycle
A Cycle will automatically parse a cycle given as a tuple on the rhs:
>>> Cycle(1, 2)(2, 3)
Cycle(1, 3, 2)
The identity cycle, Cycle(), can be used to start a product:
>>> Cycle()(1, 2)(2, 3)
Cycle(1, 3, 2)
The array form of a Cycle can be obtained by calling the list
method (or passing it to the list function) and all elements from
0 will be shown:
>>> a = Cycle(1, 2)
>>> a.list()
[0, 2, 1]
>>> list(a)
[0, 2, 1]
If a larger (or smaller) range is desired use the list method and
provide the desired size -- but the Cycle cannot be truncated to
a size smaller than the largest element that is out of place:
>>> b = Cycle(2, 4)(1, 2)(3, 1, 4)(1, 3)
>>> b.list()
[0, 2, 1, 3, 4]
>>> b.list(b.size + 1)
[0, 2, 1, 3, 4, 5]
>>> b.list(-1)
[0, 2, 1]
Singletons are not shown when printing with one exception: the largest
element is always shown -- as a singleton if necessary:
>>> Cycle(1, 4, 10)(4, 5)
Cycle(1, 5, 4, 10)
>>> Cycle(1, 2)(4)(5)(10)
Cycle(1, 2)(10)
The array form can be used to instantiate a Permutation so other
properties of the permutation can be investigated:
>>> Perm(Cycle(1, 2)(3, 4).list()).transpositions()
[(1, 2), (3, 4)]
Notes
=====
The underlying structure of the Cycle is a dictionary and although
the __iter__ method has been redefined to give the array form of the
cycle, the underlying dictionary items are still available with the
such methods as items():
>>> list(Cycle(1, 2).items())
[(1, 2), (2, 1)]
See Also
========
Permutation
"""
def __missing__(self, arg):
"""Enter arg into dictionary and return arg."""
self[arg] = arg
return arg
def __iter__(self):
for i in self.list():
yield i
def __call__(self, *other):
"""Return product of cycles processed from R to L.
Examples
========
>>> from sympy.combinatorics.permutations import Cycle as C
>>> from sympy.combinatorics.permutations import Permutation as Perm
>>> C(1, 2)(2, 3)
Cycle(1, 3, 2)
An instance of a Cycle will automatically parse list-like
objects and Permutations that are on the right. It is more
flexible than the Permutation in that all elements need not
be present:
>>> a = C(1, 2)
>>> a(2, 3)
Cycle(1, 3, 2)
>>> a(2, 3)(4, 5)
Cycle(1, 3, 2)(4, 5)
"""
rv = Cycle(*other)
for k, v in zip(list(self.keys()), [rv[self[k]] for k in self.keys()]):
rv[k] = v
return rv
def list(self, size=None):
"""Return the cycles as an explicit list starting from 0 up
to the greater of the largest value in the cycles and size.
Truncation of trailing unmoved items will occur when size
is less than the maximum element in the cycle; if this is
desired, setting ``size=-1`` will guarantee such trimming.
Examples
========
>>> from sympy.combinatorics.permutations import Cycle
>>> from sympy.combinatorics.permutations import Permutation
>>> Permutation.print_cyclic = False
>>> p = Cycle(2, 3)(4, 5)
>>> p.list()
[0, 1, 3, 2, 5, 4]
>>> p.list(10)
[0, 1, 3, 2, 5, 4, 6, 7, 8, 9]
Passing a length too small will trim trailing, unchanged elements
in the permutation:
>>> Cycle(2, 4)(1, 2, 4).list(-1)
[0, 2, 1]
"""
if not self and size is None:
raise ValueError('must give size for empty Cycle')
if size is not None:
big = max([i for i in self.keys() if self[i] != i])
size = max(size, big + 1)
else:
size = self.size
return [self[i] for i in range(size)]
def __repr__(self):
"""We want it to print as a Cycle, not as a dict.
Examples
========
>>> from sympy.combinatorics import Cycle
>>> Cycle(1, 2)
Cycle(1, 2)
>>> print(_)
Cycle(1, 2)
>>> list(Cycle(1, 2).items())
[(1, 2), (2, 1)]
"""
if not self:
return 'Cycle()'
cycles = Permutation(self).cyclic_form
s = ''.join(str(tuple(c)) for c in cycles)
big = self.size - 1
if not any(i == big for c in cycles for i in c):
s += '(%s)' % big
return 'Cycle%s' % s
def __init__(self, *args):
"""Load up a Cycle instance with the values for the cycle.
Examples
========
>>> from sympy.combinatorics.permutations import Cycle
>>> Cycle(1, 2, 6)
Cycle(1, 2, 6)
"""
if not args:
return
if len(args) == 1:
if isinstance(args[0], Permutation):
for c in args[0].cyclic_form:
self.update(self(*c))
return
elif isinstance(args[0], Cycle):
for k, v in args[0].items():
self[k] = v
return
args = [int(a) for a in args]
if has_dups(args):
raise ValueError('All elements must be unique in a cycle.')
for i in range(-len(args), 0):
self[args[i]] = args[i + 1]
@property
def size(self):
return max(self.keys()) + 1
def copy(self):
return Cycle(self)
class Permutation(Basic):
"""
A permutation, alternatively known as an 'arrangement number' or 'ordering'
is an arrangement of the elements of an ordered list into a one-to-one
mapping with itself. The permutation of a given arrangement is given by
indicating the positions of the elements after re-arrangement [2]_. For
example, if one started with elements [x, y, a, b] (in that order) and
they were reordered as [x, y, b, a] then the permutation would be
[0, 1, 3, 2]. Notice that (in SymPy) the first element is always referred
to as 0 and the permutation uses the indices of the elements in the
original ordering, not the elements (a, b, etc...) themselves.
>>> from sympy.combinatorics import Permutation
>>> Permutation.print_cyclic = False
Permutations Notation
=====================
Permutations are commonly represented in disjoint cycle or array forms.
Array Notation and 2-line Form
------------------------------------
In the 2-line form, the elements and their final positions are shown
as a matrix with 2 rows:
[0 1 2 ... n-1]
[p(0) p(1) p(2) ... p(n-1)]
Since the first line is always range(n), where n is the size of p,
it is sufficient to represent the permutation by the second line,
referred to as the "array form" of the permutation. This is entered
in brackets as the argument to the Permutation class:
>>> p = Permutation([0, 2, 1]); p
Permutation([0, 2, 1])
Given i in range(p.size), the permutation maps i to i^p
>>> [i^p for i in range(p.size)]
[0, 2, 1]
The composite of two permutations p*q means first apply p, then q, so
i^(p*q) = (i^p)^q which is i^p^q according to Python precedence rules:
>>> q = Permutation([2, 1, 0])
>>> [i^p^q for i in range(3)]
[2, 0, 1]
>>> [i^(p*q) for i in range(3)]
[2, 0, 1]
One can use also the notation p(i) = i^p, but then the composition
rule is (p*q)(i) = q(p(i)), not p(q(i)):
>>> [(p*q)(i) for i in range(p.size)]
[2, 0, 1]
>>> [q(p(i)) for i in range(p.size)]
[2, 0, 1]
>>> [p(q(i)) for i in range(p.size)]
[1, 2, 0]
Disjoint Cycle Notation
-----------------------
In disjoint cycle notation, only the elements that have shifted are
indicated. In the above case, the 2 and 1 switched places. This can
be entered in two ways:
>>> Permutation(1, 2) == Permutation([[1, 2]]) == p
True
Only the relative ordering of elements in a cycle matter:
>>> Permutation(1,2,3) == Permutation(2,3,1) == Permutation(3,1,2)
True
The disjoint cycle notation is convenient when representing permutations
that have several cycles in them:
>>> Permutation(1, 2)(3, 5) == Permutation([[1, 2], [3, 5]])
True
It also provides some economy in entry when computing products of
permutations that are written in disjoint cycle notation:
>>> Permutation(1, 2)(1, 3)(2, 3)
Permutation([0, 3, 2, 1])
>>> _ == Permutation([[1, 2]])*Permutation([[1, 3]])*Permutation([[2, 3]])
True
Entering a singleton in a permutation is a way to indicate the size of the
permutation. The ``size`` keyword can also be used.
Array-form entry:
>>> Permutation([[1, 2], [9]])
Permutation([0, 2, 1], size=10)
>>> Permutation([[1, 2]], size=10)
Permutation([0, 2, 1], size=10)
Cyclic-form entry:
>>> Permutation(1, 2, size=10)
Permutation([0, 2, 1], size=10)
>>> Permutation(9)(1, 2)
Permutation([0, 2, 1], size=10)
Caution: no singleton containing an element larger than the largest
in any previous cycle can be entered. This is an important difference
in how Permutation and Cycle handle the __call__ syntax. A singleton
argument at the start of a Permutation performs instantiation of the
Permutation and is permitted:
>>> Permutation(5)
Permutation([], size=6)
A singleton entered after instantiation is a call to the permutation
-- a function call -- and if the argument is out of range it will
trigger an error. For this reason, it is better to start the cycle
with the singleton:
The following fails because there is is no element 3:
>>> Permutation(1, 2)(3)
Traceback (most recent call last):
...
IndexError: list index out of range
This is ok: only the call to an out of range singleton is prohibited;
otherwise the permutation autosizes:
>>> Permutation(3)(1, 2)
Permutation([0, 2, 1, 3])
>>> Permutation(1, 2)(3, 4) == Permutation(3, 4)(1, 2)
True
Equality testing
----------------
The array forms must be the same in order for permutations to be equal:
>>> Permutation([1, 0, 2, 3]) == Permutation([1, 0])
False
Identity Permutation
--------------------
The identity permutation is a permutation in which no element is out of
place. It can be entered in a variety of ways. All the following create
an identity permutation of size 4:
>>> I = Permutation([0, 1, 2, 3])
>>> all(p == I for p in [
... Permutation(3),
... Permutation(range(4)),
... Permutation([], size=4),
... Permutation(size=4)])
True
Watch out for entering the range *inside* a set of brackets (which is
cycle notation):
>>> I == Permutation([range(4)])
False
Permutation Printing
====================
There are a few things to note about how Permutations are printed.
1) If you prefer one form (array or cycle) over another, you can set that
with the print_cyclic flag.
>>> Permutation(1, 2)(4, 5)(3, 4)
Permutation([0, 2, 1, 4, 5, 3])
>>> p = _
>>> Permutation.print_cyclic = True
>>> p
Permutation(1, 2)(3, 4, 5)
>>> Permutation.print_cyclic = False
2) Regardless of the setting, a list of elements in the array for cyclic
form can be obtained and either of those can be copied and supplied as
the argument to Permutation:
>>> p.array_form
[0, 2, 1, 4, 5, 3]
>>> p.cyclic_form
[[1, 2], [3, 4, 5]]
>>> Permutation(_) == p
True
3) Printing is economical in that as little as possible is printed while
retaining all information about the size of the permutation:
>>> Permutation([1, 0, 2, 3])
Permutation([1, 0, 2, 3])
>>> Permutation([1, 0, 2, 3], size=20)
Permutation([1, 0], size=20)
>>> Permutation([1, 0, 2, 4, 3, 5, 6], size=20)
Permutation([1, 0, 2, 4, 3], size=20)
>>> p = Permutation([1, 0, 2, 3])
>>> Permutation.print_cyclic = True
>>> p
Permutation(3)(0, 1)
>>> Permutation.print_cyclic = False
The 2 was not printed but it is still there as can be seen with the
array_form and size methods:
>>> p.array_form
[1, 0, 2, 3]
>>> p.size
4
Short introduction to other methods
===================================
The permutation can act as a bijective function, telling what element is
located at a given position
>>> q = Permutation([5, 2, 3, 4, 1, 0])
>>> q.array_form[1] # the hard way
2
>>> q(1) # the easy way
2
>>> dict([(i, q(i)) for i in range(q.size)]) # showing the bijection
{0: 5, 1: 2, 2: 3, 3: 4, 4: 1, 5: 0}
The full cyclic form (including singletons) can be obtained:
>>> p.full_cyclic_form
[[0, 1], [2], [3]]
Any permutation can be factored into transpositions of pairs of elements:
>>> Permutation([[1, 2], [3, 4, 5]]).transpositions()
[(1, 2), (3, 5), (3, 4)]
>>> Permutation.rmul(*[Permutation([ti], size=6) for ti in _]).cyclic_form
[[1, 2], [3, 4, 5]]
The number of permutations on a set of n elements is given by n! and is
called the cardinality.
>>> p.size
4
>>> p.cardinality
24
A given permutation has a rank among all the possible permutations of the
same elements, but what that rank is depends on how the permutations are
enumerated. (There are a number of different methods of doing so.) The
lexicographic rank is given by the rank method and this rank is used to
increment a permutation with addition/subtraction:
>>> p.rank()
6
>>> p + 1
Permutation([1, 0, 3, 2])
>>> p.next_lex()
Permutation([1, 0, 3, 2])
>>> _.rank()
7
>>> p.unrank_lex(p.size, rank=7)
Permutation([1, 0, 3, 2])
The product of two permutations p and q is defined as their composition as
functions, (p*q)(i) = q(p(i)) [6]_.
>>> p = Permutation([1, 0, 2, 3])
>>> q = Permutation([2, 3, 1, 0])
>>> list(q*p)
[2, 3, 0, 1]
>>> list(p*q)
[3, 2, 1, 0]
>>> [q(p(i)) for i in range(p.size)]
[3, 2, 1, 0]
The permutation can be 'applied' to any list-like object, not only
Permutations:
>>> p(['zero', 'one', 'four', 'two'])
['one', 'zero', 'four', 'two']
>>> p('zo42')
['o', 'z', '4', '2']
If you have a list of arbitrary elements, the corresponding permutation
can be found with the from_sequence method:
>>> Permutation.from_sequence('SymPy')
Permutation([1, 3, 2, 0, 4])
See Also
========
Cycle
References
==========
.. [1] Skiena, S. 'Permutations.' 1.1 in Implementing Discrete Mathematics
Combinatorics and Graph Theory with Mathematica. Reading, MA:
Addison-Wesley, pp. 3-16, 1990.
.. [2] Knuth, D. E. The Art of Computer Programming, Vol. 4: Combinatorial
Algorithms, 1st ed. Reading, MA: Addison-Wesley, 2011.
.. [3] Wendy Myrvold and Frank Ruskey. 2001. Ranking and unranking
permutations in linear time. Inf. Process. Lett. 79, 6 (September 2001),
281-284. DOI=10.1016/S0020-0190(01)00141-7
.. [4] D. L. Kreher, D. R. Stinson 'Combinatorial Algorithms'
CRC Press, 1999
.. [5] Graham, R. L.; Knuth, D. E.; and Patashnik, O.
Concrete Mathematics: A Foundation for Computer Science, 2nd ed.
Reading, MA: Addison-Wesley, 1994.
.. [6] http://en.wikipedia.org/wiki/Permutation#Product_and_inverse
.. [7] http://en.wikipedia.org/wiki/Lehmer_code
"""
is_Permutation = True
_array_form = None
_cyclic_form = None
_cycle_structure = None
_size = None
_rank = None
def __new__(cls, *args, **kwargs):
"""
Constructor for the Permutation object from a list or a
list of lists in which all elements of the permutation may
appear only once.
Examples
========
>>> from sympy.combinatorics.permutations import Permutation
>>> Permutation.print_cyclic = False
Permutations entered in array-form are left unaltered:
>>> Permutation([0, 2, 1])
Permutation([0, 2, 1])
Permutations entered in cyclic form are converted to array form;
singletons need not be entered, but can be entered to indicate the
largest element:
>>> Permutation([[4, 5, 6], [0, 1]])
Permutation([1, 0, 2, 3, 5, 6, 4])
>>> Permutation([[4, 5, 6], [0, 1], [19]])
Permutation([1, 0, 2, 3, 5, 6, 4], size=20)
All manipulation of permutations assumes that the smallest element
is 0 (in keeping with 0-based indexing in Python) so if the 0 is
missing when entering a permutation in array form, an error will be
raised:
>>> Permutation([2, 1])
Traceback (most recent call last):
...
ValueError: Integers 0 through 2 must be present.
If a permutation is entered in cyclic form, it can be entered without
singletons and the ``size`` specified so those values can be filled
in, otherwise the array form will only extend to the maximum value
in the cycles:
>>> Permutation([[1, 4], [3, 5, 2]], size=10)
Permutation([0, 4, 3, 5, 1, 2], size=10)
>>> _.array_form
[0, 4, 3, 5, 1, 2, 6, 7, 8, 9]
"""
size = kwargs.pop('size', None)
if size is not None:
size = int(size)
#a) ()
#b) (1) = identity
#c) (1, 2) = cycle
#d) ([1, 2, 3]) = array form
#e) ([[1, 2]]) = cyclic form
#f) (Cycle) = conversion to permutation
#g) (Permutation) = adjust size or return copy
ok = True
if not args: # a
return _af_new(list(range(size or 0)))
elif len(args) > 1: # c
return _af_new(Cycle(*args).list(size))
if len(args) == 1:
a = args[0]
if isinstance(a, Perm): # g
if size is None or size == a.size:
return a
return Perm(a.array_form, size=size)
if isinstance(a, Cycle): # f
return _af_new(a.list(size))
if not is_sequence(a): # b
return _af_new(list(range(a + 1)))
if has_variety(is_sequence(ai) for ai in a):
ok = False
else:
ok = False
if not ok:
raise ValueError("Permutation argument must be a list of ints, "
"a list of lists, Permutation or Cycle.")
# safe to assume args are valid; this also makes a copy
# of the args
args = list(args[0])
is_cycle = args and is_sequence(args[0])
if is_cycle: # e
args = [[int(i) for i in c] for c in args]
else: # d
args = [int(i) for i in args]
# if there are n elements present, 0, 1, ..., n-1 should be present
# unless a cycle notation has been provided. A 0 will be added
# for convenience in case one wants to enter permutations where
# counting starts from 1.
temp = flatten(args)
if has_dups(temp):
if is_cycle:
raise ValueError('there were repeated elements; to resolve '
'cycles use Cycle%s.' % ''.join([str(tuple(c)) for c in args]))
else:
raise ValueError('there were repeated elements.')
temp = set(temp)
if not is_cycle and \
any(i not in temp for i in range(len(temp))):
raise ValueError("Integers 0 through %s must be present." %
max(temp))
if is_cycle:
# it's not necessarily canonical so we won't store
# it -- use the array form instead
c = Cycle()
for ci in args:
c = c(*ci)
aform = c.list()
else:
aform = list(args)
if size and size > len(aform):
# don't allow for truncation of permutation which
# might split a cycle and lead to an invalid aform
# but do allow the permutation size to be increased
aform.extend(list(range(len(aform), size)))
size = len(aform)
obj = Basic.__new__(cls, aform)
obj._array_form = aform
obj._size = size
return obj
@staticmethod
def _af_new(perm):
"""A method to produce a Permutation object from a list;
the list is bound to the _array_form attribute, so it must
not be modified; this method is meant for internal use only;
the list ``a`` is supposed to be generated as a temporary value
in a method, so p = Perm._af_new(a) is the only object
to hold a reference to ``a``::
Examples
========
>>> from sympy.combinatorics.permutations import Perm
>>> Perm.print_cyclic = False
>>> a = [2,1,3,0]
>>> p = Perm._af_new(a)
>>> p
Permutation([2, 1, 3, 0])
"""
p = Basic.__new__(Perm, perm)
p._array_form = perm
p._size = len(perm)
return p
def _hashable_content(self):
# the array_form (a list) is the Permutation arg, so we need to
# return a tuple, instead
return tuple(self.array_form)
@property
def array_form(self):
"""
Return a copy of the attribute _array_form
Examples
========
>>> from sympy.combinatorics.permutations import Permutation
>>> Permutation.print_cyclic = False
>>> p = Permutation([[2, 0], [3, 1]])
>>> p.array_form
[2, 3, 0, 1]
>>> Permutation([[2, 0, 3, 1]]).array_form
[3, 2, 0, 1]
>>> Permutation([2, 0, 3, 1]).array_form
[2, 0, 3, 1]
>>> Permutation([[1, 2], [4, 5]]).array_form
[0, 2, 1, 3, 5, 4]
"""
return self._array_form[:]
def list(self, size=None):
"""Return the permutation as an explicit list, possibly
trimming unmoved elements if size is less than the maximum
element in the permutation; if this is desired, setting
``size=-1`` will guarantee such trimming.
Examples
========
>>> from sympy.combinatorics.permutations import Permutation
>>> Permutation.print_cyclic = False
>>> p = Permutation(2, 3)(4, 5)
>>> p.list()
[0, 1, 3, 2, 5, 4]
>>> p.list(10)
[0, 1, 3, 2, 5, 4, 6, 7, 8, 9]
Passing a length too small will trim trailing, unchanged elements
in the permutation:
>>> Permutation(2, 4)(1, 2, 4).list(-1)
[0, 2, 1]
>>> Permutation(3).list(-1)
[]
"""
if not self and size is None:
raise ValueError('must give size for empty Cycle')
rv = self.array_form
if size is not None:
if size > self.size:
rv.extend(list(range(self.size, size)))
else:
# find first value from rhs where rv[i] != i
i = self.size - 1
while rv:
if rv[-1] != i:
break
rv.pop()
i -= 1
return rv
@property
def cyclic_form(self):
"""
This is used to convert to the cyclic notation
from the canonical notation. Singletons are omitted.
Examples
========
>>> from sympy.combinatorics.permutations import Permutation
>>> Permutation.print_cyclic = False
>>> p = Permutation([0, 3, 1, 2])
>>> p.cyclic_form
[[1, 3, 2]]
>>> Permutation([1, 0, 2, 4, 3, 5]).cyclic_form
[[0, 1], [3, 4]]
See Also
========
array_form, full_cyclic_form
"""
if self._cyclic_form is not None:
return list(self._cyclic_form)
array_form = self.array_form
unchecked = [True] * len(array_form)
cyclic_form = []
for i in range(len(array_form)):
if unchecked[i]:
cycle = []
cycle.append(i)
unchecked[i] = False
j = i
while unchecked[array_form[j]]:
j = array_form[j]
cycle.append(j)
unchecked[j] = False
if len(cycle) > 1:
cyclic_form.append(cycle)
assert cycle == list(minlex(cycle, is_set=True))
cyclic_form.sort()
self._cyclic_form = cyclic_form[:]
return cyclic_form
@property
def full_cyclic_form(self):
"""Return permutation in cyclic form including singletons.
Examples
========
>>> from sympy.combinatorics.permutations import Permutation
>>> Permutation([0, 2, 1]).full_cyclic_form
[[0], [1, 2]]
"""
need = set(range(self.size)) - set(flatten(self.cyclic_form))
rv = self.cyclic_form
rv.extend([[i] for i in need])
rv.sort()
return rv
@property
def size(self):
"""
Returns the number of elements in the permutation.
Examples
========
>>> from sympy.combinatorics import Permutation
>>> Permutation([[3, 2], [0, 1]]).size
4
See Also
========
cardinality, length, order, rank
"""
return self._size
def support(self):
"""Return the elements in permutation, P, for which P[i] != i.
Examples
========
>>> from sympy.combinatorics import Permutation
>>> p = Permutation([[3, 2], [0, 1], [4]])
>>> p.array_form
[1, 0, 3, 2, 4]
>>> p.support()
[0, 1, 2, 3]
"""
a = self.array_form
return [i for i, e in enumerate(a) if a[i] != i]
def __add__(self, other):
"""Return permutation that is other higher in rank than self.
The rank is the lexicographical rank, with the identity permutation
having rank of 0.
Examples
========
>>> from sympy.combinatorics.permutations import Permutation
>>> Permutation.print_cyclic = False
>>> I = Permutation([0, 1, 2, 3])
>>> a = Permutation([2, 1, 3, 0])
>>> I + a.rank() == a
True
See Also
========
__sub__, inversion_vector
"""
rank = (self.rank() + other) % self.cardinality
rv = Perm.unrank_lex(self.size, rank)
rv._rank = rank
return rv
def __sub__(self, other):
"""Return the permutation that is other lower in rank than self.
See Also
========
__add__
"""
return self.__add__(-other)
@staticmethod
def rmul(*args):
"""
Return product of Permutations [a, b, c, ...] as the Permutation whose
ith value is a(b(c(i))).
a, b, c, ... can be Permutation objects or tuples.
Examples
========
>>> from sympy.combinatorics.permutations import _af_rmul, Permutation
>>> Permutation.print_cyclic = False
>>> a, b = [1, 0, 2], [0, 2, 1]
>>> a = Permutation(a); b = Permutation(b)
>>> list(Permutation.rmul(a, b))
[1, 2, 0]
>>> [a(b(i)) for i in range(3)]
[1, 2, 0]
This handles the operands in reverse order compared to the ``*`` operator:
>>> a = Permutation(a); b = Permutation(b)
>>> list(a*b)
[2, 0, 1]
>>> [b(a(i)) for i in range(3)]
[2, 0, 1]
Notes
=====
All items in the sequence will be parsed by Permutation as
necessary as long as the first item is a Permutation:
>>> Permutation.rmul(a, [0, 2, 1]) == Permutation.rmul(a, b)
True
The reverse order of arguments will raise a TypeError.
"""
rv = args[0]
for i in range(1, len(args)):
rv = args[i]*rv
return rv
@staticmethod
def rmul_with_af(*args):
"""
same as rmul, but the elements of args are Permutation objects
which have _array_form
"""
a = [x._array_form for x in args]
rv = _af_new(_af_rmuln(*a))
return rv
def mul_inv(self, other):
"""
other*~self, self and other have _array_form
"""
a = _af_invert(self._array_form)
b = other._array_form
return _af_new(_af_rmul(a, b))
def __rmul__(self, other):
"""This is needed to coerse other to Permutation in rmul."""
return Perm(other)*self
def __mul__(self, other):
"""
Return the product a*b as a Permutation; the ith value is b(a(i)).
Examples
========
>>> from sympy.combinatorics.permutations import _af_rmul, Permutation
>>> Permutation.print_cyclic = False
>>> a, b = [1, 0, 2], [0, 2, 1]
>>> a = Permutation(a); b = Permutation(b)
>>> list(a*b)
[2, 0, 1]
>>> [b(a(i)) for i in range(3)]
[2, 0, 1]
This handles operands in reverse order compared to _af_rmul and rmul:
>>> al = list(a); bl = list(b)
>>> _af_rmul(al, bl)
[1, 2, 0]
>>> [al[bl[i]] for i in range(3)]
[1, 2, 0]
It is acceptable for the arrays to have different lengths; the shorter
one will be padded to match the longer one:
>>> b*Permutation([1, 0])
Permutation([1, 2, 0])
>>> Permutation([1, 0])*b
Permutation([2, 0, 1])
It is also acceptable to allow coercion to handle conversion of a
single list to the left of a Permutation:
>>> [0, 1]*a # no change: 2-element identity
Permutation([1, 0, 2])
>>> [[0, 1]]*a # exchange first two elements
Permutation([0, 1, 2])
You cannot use more than 1 cycle notation in a product of cycles
since coercion can only handle one argument to the left. To handle
multiple cycles it is convenient to use Cycle instead of Permutation:
>>> [[1, 2]]*[[2, 3]]*Permutation([]) # doctest: +SKIP
>>> from sympy.combinatorics.permutations import Cycle
>>> Cycle(1, 2)(2, 3)
Cycle(1, 3, 2)
"""
a = self.array_form
# __rmul__ makes sure the other is a Permutation
b = other.array_form
if not b:
perm = a
else:
b.extend(list(range(len(b), len(a))))
perm = [b[i] for i in a] + b[len(a):]
return _af_new(perm)
def commutes_with(self, other):
"""
Checks if the elements are commuting.
Examples
========
>>> from sympy.combinatorics.permutations import Permutation
>>> a = Permutation([1, 4, 3, 0, 2, 5])
>>> b = Permutation([0, 1, 2, 3, 4, 5])
>>> a.commutes_with(b)
True
>>> b = Permutation([2, 3, 5, 4, 1, 0])
>>> a.commutes_with(b)
False
"""
a = self.array_form
b = other.array_form
return _af_commutes_with(a, b)
def __pow__(self, n):
"""
Routine for finding powers of a permutation.
Examples
========
>>> from sympy.combinatorics.permutations import Permutation
>>> Permutation.print_cyclic = False
>>> p = Permutation([2,0,3,1])
>>> p.order()
4
>>> p**4
Permutation([0, 1, 2, 3])
"""
if type(n) == Perm:
raise NotImplementedError(
'p**p is not defined; do you mean p^p (conjugate)?')
n = int(n)
return _af_new(_af_pow(self.array_form, n))
def __rxor__(self, i):
"""Return self(i) when ``i`` is an int.
Examples
========
>>> from sympy.combinatorics import Permutation
>>> p = Permutation(1, 2, 9)
>>> 2^p == p(2) == 9
True
"""
if int(i) == i:
return self(i)
else:
raise NotImplementedError(
"i^p = p(i) when i is an integer, not %s." % i)
def __xor__(self, h):
"""Return the conjugate permutation ``~h*self*h` `.
If ``a`` and ``b`` are conjugates, ``a = h*b*~h`` and
``b = ~h*a*h`` and both have the same cycle structure.
Examples
========
>>> from sympy.combinatorics.permutations import Permutation
>>> Permutation.print_cyclic = True
>>> p = Permutation(1, 2, 9)
>>> q = Permutation(6, 9, 8)
>>> p*q != q*p
True
Calculate and check properties of the conjugate:
>>> c = p^q
>>> c == ~q*p*q and p == q*c*~q
True
The expression q^p^r is equivalent to q^(p*r):
>>> r = Permutation(9)(4, 6, 8)
>>> q^p^r == q^(p*r)
True
If the term to the left of the conjugate operator, i, is an integer
then this is interpreted as selecting the ith element from the
permutation to the right:
>>> all(i^p == p(i) for i in range(p.size))
True
Note that the * operator as higher precedence than the ^ operator:
>>> q^r*p^r == q^(r*p)^r == Permutation(9)(1, 6, 4)
True
Notes
=====
In Python the precedence rule is p^q^r = (p^q)^r which differs
in general from p^(q^r)
>>> q^p^r
Permutation(9)(1, 4, 8)
>>> q^(p^r)
Permutation(9)(1, 8, 6)
For a given r and p, both of the following are conjugates of p:
~r*p*r and r*p*~r. But these are not necessarily the same:
>>> ~r*p*r == r*p*~r
True
>>> p = Permutation(1, 2, 9)(5, 6)
>>> ~r*p*r == r*p*~r
False
The conjugate ~r*p*r was chosen so that ``p^q^r`` would be equivalent
to ``p^(q*r)`` rather than ``p^(r*q)``. To obtain r*p*~r, pass ~r to
this method:
>>> p^~r == r*p*~r
True
"""
if self.size != h.size:
raise ValueError("The permutations must be of equal size.")
a = [None]*self.size
h = h._array_form
p = self._array_form
for i in range(self.size):
a[h[i]] = h[p[i]]
return _af_new(a)
def transpositions(self):
"""
Return the permutation decomposed into a list of transpositions.
It is always possible to express a permutation as the product of
transpositions, see [1]
Examples
========
>>> from sympy.combinatorics.permutations import Permutation
>>> p = Permutation([[1, 2, 3], [0, 4, 5, 6, 7]])
>>> t = p.transpositions()
>>> t
[(0, 7), (0, 6), (0, 5), (0, 4), (1, 3), (1, 2)]
>>> print(''.join(str(c) for c in t))
(0, 7)(0, 6)(0, 5)(0, 4)(1, 3)(1, 2)
>>> Permutation.rmul(*[Permutation([ti], size=p.size) for ti in t]) == p
True
References
==========
1. http://en.wikipedia.org/wiki/Transposition_%28mathematics%29#Properties
"""
a = self.cyclic_form
res = []
for x in a:
nx = len(x)
if nx == 2:
res.append(tuple(x))
elif nx > 2:
first = x[0]
for y in x[nx - 1:0:-1]:
res.append((first, y))
return res
@classmethod
def from_sequence(self, i, key=None):
"""Return the permutation needed to obtain ``i`` from the sorted
elements of ``i``. If custom sorting is desired, a key can be given.
Examples
========
>>> from sympy.combinatorics import Permutation
>>> Permutation.print_cyclic = True
>>> Permutation.from_sequence('SymPy')
Permutation(4)(0, 1, 3)
>>> _(sorted("SymPy"))
['S', 'y', 'm', 'P', 'y']
>>> Permutation.from_sequence('SymPy', key=lambda x: x.lower())
Permutation(4)(0, 2)(1, 3)
"""
ic = list(zip(i, list(range(len(i)))))
if key:
ic.sort(key=lambda x: key(x[0]))
else:
ic.sort()
return ~Permutation([i[1] for i in ic])
def __invert__(self):
"""
Return the inverse of the permutation.
A permutation multiplied by its inverse is the identity permutation.
Examples
========
>>> from sympy.combinatorics.permutations import Permutation
>>> p = Permutation([[2,0], [3,1]])
>>> ~p
Permutation([2, 3, 0, 1])
>>> _ == p**-1
True
>>> p*~p == ~p*p == Permutation([0, 1, 2, 3])
True
"""
return _af_new(_af_invert(self._array_form))
def __iter__(self):
"""Yield elements from array form.
Examples
========
>>> from sympy.combinatorics import Permutation
>>> list(Permutation(range(3)))
[0, 1, 2]
"""
for i in self.array_form:
yield i
def __call__(self, *i):
"""
Allows applying a permutation instance as a bijective function.
Examples
========
>>> from sympy.combinatorics.permutations import Permutation
>>> p = Permutation([[2, 0], [3, 1]])
>>> p.array_form
[2, 3, 0, 1]
>>> [p(i) for i in range(4)]
[2, 3, 0, 1]
If an array is given then the permutation selects the items
from the array (i.e. the permutation is applied to the array):
>>> from sympy.abc import x
>>> p([x, 1, 0, x**2])
[0, x**2, x, 1]
"""
# list indices can be Integer or int; leave this
# as it is (don't test or convert it) because this
# gets called a lot and should be fast
if len(i) == 1:
i = i[0]
try:
# P(1)
return self._array_form[i]
except TypeError:
try:
# P([a, b, c])
return [i[j] for j in self._array_form]
except Exception:
raise TypeError('unrecognized argument')
else:
# P(1, 2, 3)
return self*Permutation(Cycle(*i), size=self.size)
def atoms(self):
"""
Returns all the elements of a permutation
Examples
========
>>> from sympy.combinatorics import Permutation
>>> Permutation([0, 1, 2, 3, 4, 5]).atoms()
set([0, 1, 2, 3, 4, 5])
>>> Permutation([[0, 1], [2, 3], [4, 5]]).atoms()
set([0, 1, 2, 3, 4, 5])
"""
return set(self.array_form)
def next_lex(self):
"""
Returns the next permutation in lexicographical order.
If self is the last permutation in lexicographical order
it returns None.
See [4] section 2.4.
Examples
========
>>> from sympy.combinatorics.permutations import Permutation
>>> p = Permutation([2, 3, 1, 0])
>>> p = Permutation([2, 3, 1, 0]); p.rank()
17
>>> p = p.next_lex(); p.rank()
18
See Also
========
rank, unrank_lex
"""
perm = self.array_form[:]
n = len(perm)
i = n - 2
while perm[i + 1] < perm[i]:
i -= 1
if i == -1:
return None
else:
j = n - 1
while perm[j] < perm[i]:
j -= 1
perm[j], perm[i] = perm[i], perm[j]
i += 1
j = n - 1
while i < j:
perm[j], perm[i] = perm[i], perm[j]
i += 1
j -= 1
return _af_new(perm)
@classmethod
def unrank_nonlex(self, n, r):
"""
This is a linear time unranking algorithm that does not
respect lexicographic order [3].
Examples
========
>>> from sympy.combinatorics.permutations import Permutation
>>> Permutation.print_cyclic = False
>>> Permutation.unrank_nonlex(4, 5)
Permutation([2, 0, 3, 1])
>>> Permutation.unrank_nonlex(4, -1)
Permutation([0, 1, 2, 3])
See Also
========
next_nonlex, rank_nonlex
"""
def _unrank1(n, r, a):
if n > 0:
a[n - 1], a[r % n] = a[r % n], a[n - 1]
_unrank1(n - 1, r//n, a)
id_perm = list(range(n))
n = int(n)
r = r % ifac(n)
_unrank1(n, r, id_perm)
return _af_new(id_perm)
def rank_nonlex(self, inv_perm=None):
"""
This is a linear time ranking algorithm that does not
enforce lexicographic order [3].
Examples
========
>>> from sympy.combinatorics.permutations import Permutation
>>> p = Permutation([0, 1, 2, 3])
>>> p.rank_nonlex()
23
See Also
========
next_nonlex, unrank_nonlex
"""
def _rank1(n, perm, inv_perm):
if n == 1:
return 0
s = perm[n - 1]
t = inv_perm[n - 1]
perm[n - 1], perm[t] = perm[t], s
inv_perm[n - 1], inv_perm[s] = inv_perm[s], t
return s + n*_rank1(n - 1, perm, inv_perm)
if inv_perm is None:
inv_perm = (~self).array_form
if not inv_perm:
return 0
perm = self.array_form[:]
r = _rank1(len(perm), perm, inv_perm)
return r
def next_nonlex(self):
"""
Returns the next permutation in nonlex order [3].
If self is the last permutation in this order it returns None.
Examples
========
>>> from sympy.combinatorics.permutations import Permutation
>>> Permutation.print_cyclic = False
>>> p = Permutation([2, 0, 3, 1]); p.rank_nonlex()
5
>>> p = p.next_nonlex(); p
Permutation([3, 0, 1, 2])
>>> p.rank_nonlex()
6
See Also
========
rank_nonlex, unrank_nonlex
"""
r = self.rank_nonlex()
if r == ifac(self.size) - 1:
return None
return Perm.unrank_nonlex(self.size, r + 1)
def rank(self):
"""
Returns the lexicographic rank of the permutation.
Examples
========
>>> from sympy.combinatorics.permutations import Permutation
>>> p = Permutation([0, 1, 2, 3])
>>> p.rank()
0
>>> p = Permutation([3, 2, 1, 0])
>>> p.rank()
23
See Also
========
next_lex, unrank_lex, cardinality, length, order, size
"""
if not self._rank is None:
return self._rank
rank = 0
rho = self.array_form[:]
n = self.size - 1
size = n + 1
psize = int(ifac(n))
for j in range(size - 1):
rank += rho[j]*psize
for i in range(j + 1, size):
if rho[i] > rho[j]:
rho[i] -= 1
psize //= n
n -= 1
self._rank = rank
return rank
@property
def cardinality(self):
"""
Returns the number of all possible permutations.
Examples
========
>>> from sympy.combinatorics.permutations import Permutation
>>> p = Permutation([0, 1, 2, 3])
>>> p.cardinality
24
See Also
========
length, order, rank, size
"""
return int(ifac(self.size))
def parity(self):
"""
Computes the parity of a permutation.
The parity of a permutation reflects the parity of the
number of inversions in the permutation, i.e., the
number of pairs of x and y such that ``x > y`` but ``p[x] < p[y]``.
Examples
========
>>> from sympy.combinatorics.permutations import Permutation
>>> p = Permutation([0, 1, 2, 3])
>>> p.parity()
0
>>> p = Permutation([3, 2, 0, 1])
>>> p.parity()
1
See Also
========
_af_parity
"""
if self._cyclic_form is not None:
return (self.size - self.cycles) % 2
return _af_parity(self.array_form)
@property
def is_even(self):
"""
Checks if a permutation is even.
Examples
========
>>> from sympy.combinatorics.permutations import Permutation
>>> p = Permutation([0, 1, 2, 3])
>>> p.is_even
True
>>> p = Permutation([3, 2, 1, 0])
>>> p.is_even
True
See Also
========
is_odd
"""
return not self.is_odd
@property
def is_odd(self):
"""
Checks if a permutation is odd.
Examples
========
>>> from sympy.combinatorics.permutations import Permutation
>>> p = Permutation([0, 1, 2, 3])
>>> p.is_odd
False
>>> p = Permutation([3, 2, 0, 1])
>>> p.is_odd
True
See Also
========
is_even
"""
return bool(self.parity() % 2)
@property
def is_Singleton(self):
"""
Checks to see if the permutation contains only one number and is
thus the only possible permutation of this set of numbers
Examples
========
>>> from sympy.combinatorics import Permutation
>>> Permutation([0]).is_Singleton
True
>>> Permutation([0, 1]).is_Singleton
False
See Also
========
is_Empty
"""
return self.size == 1
@property
def is_Empty(self):
"""
Checks to see if the permutation is a set with zero elements
Examples
========
>>> from sympy.combinatorics import Permutation
>>> Permutation([]).is_Empty
True
>>> Permutation([0]).is_Empty
False
See Also
========
is_Singleton
"""
return self.size == 0
@property
def is_Identity(self):
"""
Returns True if the Permutation is an identity permutation.
Examples
========
>>> from sympy.combinatorics.permutations import Permutation
>>> p = Permutation([])
>>> p.is_Identity
True
>>> p = Permutation([[0], [1], [2]])
>>> p.is_Identity
True
>>> p = Permutation([0, 1, 2])
>>> p.is_Identity
True
>>> p = Permutation([0, 2, 1])
>>> p.is_Identity
False
See Also
========
order
"""
af = self.array_form
return not af or all(i == af[i] for i in range(self.size))
def ascents(self):
"""
Returns the positions of ascents in a permutation, ie, the location
where p[i] < p[i+1]
Examples
========
>>> from sympy.combinatorics.permutations import Permutation
>>> p = Permutation([4, 0, 1, 3, 2])
>>> p.ascents()
[1, 2]
See Also
========
descents, inversions, min, max
"""
a = self.array_form
pos = [i for i in range(len(a) - 1) if a[i] < a[i + 1]]
return pos
def descents(self):
"""
Returns the positions of descents in a permutation, ie, the location
where p[i] > p[i+1]
Examples
========
>>> from sympy.combinatorics.permutations import Permutation
>>> p = Permutation([4, 0, 1, 3, 2])
>>> p.descents()
[0, 3]
See Also
========
ascents, inversions, min, max
"""
a = self.array_form
pos = [i for i in range(len(a) - 1) if a[i] > a[i + 1]]
return pos
def max(self):
"""
The maximum element moved by the permutation.
Examples
========
>>> from sympy.combinatorics.permutations import Permutation
>>> p = Permutation([1, 0, 2, 3, 4])
>>> p.max()
1
See Also
========
min, descents, ascents, inversions
"""
max = 0
a = self.array_form
for i in range(len(a)):
if a[i] != i and a[i] > max:
max = a[i]
return max
def min(self):
"""
The minimum element moved by the permutation.
Examples
========
>>> from sympy.combinatorics.permutations import Permutation
>>> p = Permutation([0, 1, 4, 3, 2])
>>> p.min()
2
See Also
========
max, descents, ascents, inversions
"""
a = self.array_form
min = len(a)
for i in range(len(a)):
if a[i] != i and a[i] < min:
min = a[i]
return min
def inversions(self):
"""
Computes the number of inversions of a permutation.
An inversion is where i > j but p[i] < p[j].
For small length of p, it iterates over all i and j
values and calculates the number of inversions.
For large length of p, it uses a variation of merge
sort to calculate the number of inversions.
References
==========
[1] http://www.cp.eng.chula.ac.th/~piak/teaching/algo/algo2008/count-inv.htm
Examples
========
>>> from sympy.combinatorics.permutations import Permutation
>>> p = Permutation([0, 1, 2, 3, 4, 5])
>>> p.inversions()
0
>>> Permutation([3, 2, 1, 0]).inversions()
6
See Also
========
descents, ascents, min, max
"""
inversions = 0
a = self.array_form
n = len(a)
if n < 130:
for i in range(n - 1):
b = a[i]
for c in a[i + 1:]:
if b > c:
inversions += 1
else:
k = 1
right = 0
arr = a[:]
temp = a[:]
while k < n:
i = 0
while i + k < n:
right = i + k * 2 - 1
if right >= n:
right = n - 1
inversions += _merge(arr, temp, i, i + k, right)
i = i + k * 2
k = k * 2
return inversions
def commutator(self, x):
"""Return the commutator of self and x: ``~x*~self*x*self``
If f and g are part of a group, G, then the commutator of f and g
is the group identity iff f and g commute, i.e. fg == gf.
Examples
========
>>> from sympy.combinatorics.permutations import Permutation
>>> Permutation.print_cyclic = False
>>> p = Permutation([0, 2, 3, 1])
>>> x = Permutation([2, 0, 3, 1])
>>> c = p.commutator(x); c
Permutation([2, 1, 3, 0])
>>> c == ~x*~p*x*p
True
>>> I = Permutation(3)
>>> p = [I + i for i in range(6)]
>>> for i in range(len(p)):
... for j in range(len(p)):
... c = p[i].commutator(p[j])
... if p[i]*p[j] == p[j]*p[i]:
... assert c == I
... else:
... assert c != I
...
References
==========
http://en.wikipedia.org/wiki/Commutator
"""
a = self.array_form
b = x.array_form
n = len(a)
if len(b) != n:
raise ValueError("The permutations must be of equal size.")
inva = [None]*n
for i in range(n):
inva[a[i]] = i
invb = [None]*n
for i in range(n):
invb[b[i]] = i
return _af_new([a[b[inva[i]]] for i in invb])
def signature(self):
"""
Gives the signature of the permutation needed to place the
elements of the permutation in canonical order.
The signature is calculated as (-1)^<number of inversions>
Examples
========
>>> from sympy.combinatorics.permutations import Permutation
>>> p = Permutation([0, 1, 2])
>>> p.inversions()
0
>>> p.signature()
1
>>> q = Permutation([0,2,1])
>>> q.inversions()
1
>>> q.signature()
-1
See Also
========
inversions
"""
if self.is_even:
return 1
return -1
def order(self):
"""
Computes the order of a permutation.
When the permutation is raised to the power of its
order it equals the identity permutation.
Examples
========
>>> from sympy.combinatorics.permutations import Permutation
>>> Permutation.print_cyclic = False
>>> p = Permutation([3, 1, 5, 2, 4, 0])
>>> p.order()
4
>>> (p**(p.order()))
Permutation([], size=6)
See Also
========
identity, cardinality, length, rank, size
"""
return reduce(lcm, [len(cycle) for cycle in self.cyclic_form], 1)
def length(self):
"""
Returns the number of integers moved by a permutation.
Examples
========
>>> from sympy.combinatorics import Permutation
>>> Permutation([0, 3, 2, 1]).length()
2
>>> Permutation([[0, 1], [2, 3]]).length()
4
See Also
========
min, max, support, cardinality, order, rank, size
"""
return len(self.support())
@property
def cycle_structure(self):
"""Return the cycle structure of the permutation as a dictionary
indicating the multiplicity of each cycle length.
Examples
========
>>> from sympy.combinatorics import Permutation
>>> Permutation.print_cyclic = True
>>> Permutation(3).cycle_structure
{1: 4}
>>> Permutation(0, 4, 3)(1, 2)(5, 6).cycle_structure
{2: 2, 3: 1}
"""
if self._cycle_structure:
rv = self._cycle_structure
else:
rv = defaultdict(int)
singletons = self.size
for c in self.cyclic_form:
rv[len(c)] += 1
singletons -= len(c)
if singletons:
rv[1] = singletons
self._cycle_structure = rv
return dict(rv) # make a copy
@property
def cycles(self):
"""
Returns the number of cycles contained in the permutation
(including singletons).
Examples
========
>>> from sympy.combinatorics import Permutation
>>> Permutation([0, 1, 2]).cycles
3
>>> Permutation([0, 1, 2]).full_cyclic_form
[[0], [1], [2]]
>>> Permutation(0, 1)(2, 3).cycles
2
See Also
========
sympy.functions.combinatorial.numbers.stirling
"""
return len(self.full_cyclic_form)
def index(self):
"""
Returns the index of a permutation.
The index of a permutation is the sum of all subscripts j such
that p[j] is greater than p[j+1].
Examples
========
>>> from sympy.combinatorics.permutations import Permutation
>>> p = Permutation([3, 0, 2, 1, 4])
>>> p.index()
2
"""
a = self.array_form
return sum([j for j in range(len(a) - 1) if a[j] > a[j + 1]])
def runs(self):
"""
Returns the runs of a permutation.
An ascending sequence in a permutation is called a run [5].
Examples
========
>>> from sympy.combinatorics.permutations import Permutation
>>> p = Permutation([2, 5, 7, 3, 6, 0, 1, 4, 8])
>>> p.runs()
[[2, 5, 7], [3, 6], [0, 1, 4, 8]]
>>> q = Permutation([1,3,2,0])
>>> q.runs()
[[1, 3], [2], [0]]
"""
return runs(self.array_form)
def inversion_vector(self):
"""Return the inversion vector of the permutation.
The inversion vector consists of elements whose value
indicates the number of elements in the permutation
that are lesser than it and lie on its right hand side.
The inversion vector is the same as the Lehmer encoding of a
permutation.
Examples
========
>>> from sympy.combinatorics.permutations import Permutation
>>> p = Permutation([4, 8, 0, 7, 1, 5, 3, 6, 2])
>>> p.inversion_vector()
[4, 7, 0, 5, 0, 2, 1, 1]
>>> p = Permutation([3, 2, 1, 0])
>>> p.inversion_vector()
[3, 2, 1]
The inversion vector increases lexicographically with the rank
of the permutation, the -ith element cycling through 0..i.
>>> p = Permutation(2)
>>> while p:
... print('%s %s %s' % (p, p.inversion_vector(), p.rank()))
... p = p.next_lex()
...
Permutation([0, 1, 2]) [0, 0] 0
Permutation([0, 2, 1]) [0, 1] 1
Permutation([1, 0, 2]) [1, 0] 2
Permutation([1, 2, 0]) [1, 1] 3
Permutation([2, 0, 1]) [2, 0] 4
Permutation([2, 1, 0]) [2, 1] 5
See Also
========
from_inversion_vector
"""
self_array_form = self.array_form
n = len(self_array_form)
inversion_vector = [0] * (n - 1)
for i in range(n - 1):
val = 0
for j in range(i + 1, n):
if self_array_form[j] < self_array_form[i]:
val += 1
inversion_vector[i] = val
return inversion_vector
def rank_trotterjohnson(self):
"""
Returns the Trotter Johnson rank, which we get from the minimal
change algorithm. See [4] section 2.4.
Examples
========
>>> from sympy.combinatorics.permutations import Permutation
>>> p = Permutation([0, 1, 2, 3])
>>> p.rank_trotterjohnson()
0
>>> p = Permutation([0, 2, 1, 3])
>>> p.rank_trotterjohnson()
7
See Also
========
unrank_trotterjohnson, next_trotterjohnson
"""
if self.array_form == [] or self.is_Identity:
return 0
if self.array_form == [1, 0]:
return 1
perm = self.array_form
n = self.size
rank = 0
for j in range(1, n):
k = 1
i = 0
while perm[i] != j:
if perm[i] < j:
k += 1
i += 1
j1 = j + 1
if rank % 2 == 0:
rank = j1*rank + j1 - k
else:
rank = j1*rank + k - 1
return rank
@classmethod
def unrank_trotterjohnson(self, size, rank):
"""
Trotter Johnson permutation unranking. See [4] section 2.4.
Examples
========
>>> from sympy.combinatorics.permutations import Permutation
>>> Permutation.unrank_trotterjohnson(5, 10)
Permutation([0, 3, 1, 2, 4])
See Also
========
rank_trotterjohnson, next_trotterjohnson
"""
perm = [0]*size
r2 = 0
n = ifac(size)
pj = 1
for j in range(2, size + 1):
pj *= j
r1 = (rank * pj) // n
k = r1 - j*r2
if r2 % 2 == 0:
for i in range(j - 1, j - k - 1, -1):
perm[i] = perm[i - 1]
perm[j - k - 1] = j - 1
else:
for i in range(j - 1, k, -1):
perm[i] = perm[i - 1]
perm[k] = j - 1
r2 = r1
return _af_new(perm)
def next_trotterjohnson(self):
"""
Returns the next permutation in Trotter-Johnson order.
If self is the last permutation it returns None.
See [4] section 2.4. If it is desired to generate all such
permutations, they can be generated in order more quickly
with the ``generate_bell`` function.
Examples
========
>>> from sympy.combinatorics.permutations import Permutation
>>> Permutation.print_cyclic = False
>>> p = Permutation([3, 0, 2, 1])
>>> p.rank_trotterjohnson()
4
>>> p = p.next_trotterjohnson(); p
Permutation([0, 3, 2, 1])
>>> p.rank_trotterjohnson()
5
See Also
========
rank_trotterjohnson, unrank_trotterjohnson, sympy.utilities.iterables.generate_bell
"""
pi = self.array_form[:]
n = len(pi)
st = 0
rho = pi[:]
done = False
m = n-1
while m > 0 and not done:
d = rho.index(m)
for i in range(d, m):
rho[i] = rho[i + 1]
par = _af_parity(rho[:m])
if par == 1:
if d == m:
m -= 1
else:
pi[st + d], pi[st + d + 1] = pi[st + d + 1], pi[st + d]
done = True
else:
if d == 0:
m -= 1
st += 1
else:
pi[st + d], pi[st + d - 1] = pi[st + d - 1], pi[st + d]
done = True
if m == 0:
return None
return _af_new(pi)
def get_precedence_matrix(self):
"""
Gets the precedence matrix. This is used for computing the
distance between two permutations.
Examples
========
>>> from sympy.combinatorics.permutations import Permutation
>>> p = Permutation.josephus(3, 6, 1)
>>> p
Permutation([2, 5, 3, 1, 4, 0])
>>> p.get_precedence_matrix()
Matrix([
[0, 0, 0, 0, 0, 0],
[1, 0, 0, 0, 1, 0],
[1, 1, 0, 1, 1, 1],
[1, 1, 0, 0, 1, 0],
[1, 0, 0, 0, 0, 0],
[1, 1, 0, 1, 1, 0]])
See Also
========
get_precedence_distance, get_adjacency_matrix, get_adjacency_distance
"""
m = zeros(self.size)
perm = self.array_form
for i in range(m.rows):
for j in range(i + 1, m.cols):
m[perm[i], perm[j]] = 1
return m
def get_precedence_distance(self, other):
"""
Computes the precedence distance between two permutations.
Suppose p and p' represent n jobs. The precedence metric
counts the number of times a job j is preceded by job i
in both p and p'. This metric is commutative.
Examples
========
>>> from sympy.combinatorics.permutations import Permutation
>>> p = Permutation([2, 0, 4, 3, 1])
>>> q = Permutation([3, 1, 2, 4, 0])
>>> p.get_precedence_distance(q)
7
>>> q.get_precedence_distance(p)
7
See Also
========
get_precedence_matrix, get_adjacency_matrix, get_adjacency_distance
"""
if self.size != other.size:
raise ValueError("The permutations must be of equal size.")
self_prec_mat = self.get_precedence_matrix()
other_prec_mat = other.get_precedence_matrix()
n_prec = 0
for i in range(self.size):
for j in range(self.size):
if i == j:
continue
if self_prec_mat[i, j] * other_prec_mat[i, j] == 1:
n_prec += 1
d = self.size * (self.size - 1)//2 - n_prec
return d
def get_adjacency_matrix(self):
"""
Computes the adjacency matrix of a permutation.
If job i is adjacent to job j in a permutation p
then we set m[i, j] = 1 where m is the adjacency
matrix of p.
Examples
========
>>> from sympy.combinatorics.permutations import Permutation
>>> p = Permutation.josephus(3, 6, 1)
>>> p.get_adjacency_matrix()
Matrix([
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 0],
[0, 0, 0, 0, 0, 1],
[0, 1, 0, 0, 0, 0],
[1, 0, 0, 0, 0, 0],
[0, 0, 0, 1, 0, 0]])
>>> q = Permutation([0, 1, 2, 3])
>>> q.get_adjacency_matrix()
Matrix([
[0, 1, 0, 0],
[0, 0, 1, 0],
[0, 0, 0, 1],
[0, 0, 0, 0]])
See Also
========
get_precedence_matrix, get_precedence_distance, get_adjacency_distance
"""
m = zeros(self.size)
perm = self.array_form
for i in range(self.size - 1):
m[perm[i], perm[i + 1]] = 1
return m
def get_adjacency_distance(self, other):
"""
Computes the adjacency distance between two permutations.
This metric counts the number of times a pair i,j of jobs is
adjacent in both p and p'. If n_adj is this quantity then
the adjacency distance is n - n_adj - 1 [1]
[1] Reeves, Colin R. Landscapes, Operators and Heuristic search, Annals
of Operational Research, 86, pp 473-490. (1999)
Examples
========
>>> from sympy.combinatorics.permutations import Permutation
>>> p = Permutation([0, 3, 1, 2, 4])
>>> q = Permutation.josephus(4, 5, 2)
>>> p.get_adjacency_distance(q)
3
>>> r = Permutation([0, 2, 1, 4, 3])
>>> p.get_adjacency_distance(r)
4
See Also
========
get_precedence_matrix, get_precedence_distance, get_adjacency_matrix
"""
if self.size != other.size:
raise ValueError("The permutations must be of the same size.")
self_adj_mat = self.get_adjacency_matrix()
other_adj_mat = other.get_adjacency_matrix()
n_adj = 0
for i in range(self.size):
for j in range(self.size):
if i == j:
continue
if self_adj_mat[i, j] * other_adj_mat[i, j] == 1:
n_adj += 1
d = self.size - n_adj - 1
return d
def get_positional_distance(self, other):
"""
Computes the positional distance between two permutations.
Examples
========
>>> from sympy.combinatorics.permutations import Permutation
>>> p = Permutation([0, 3, 1, 2, 4])
>>> q = Permutation.josephus(4, 5, 2)
>>> r = Permutation([3, 1, 4, 0, 2])
>>> p.get_positional_distance(q)
12
>>> p.get_positional_distance(r)
12
See Also
========
get_precedence_distance, get_adjacency_distance
"""
a = self.array_form
b = other.array_form
if len(a) != len(b):
raise ValueError("The permutations must be of the same size.")
return sum([abs(a[i] - b[i]) for i in range(len(a))])
@classmethod
def josephus(self, m, n, s=1):
"""Return as a permutation the shuffling of range(n) using the Josephus
scheme in which every m-th item is selected until all have been chosen.
The returned permutation has elements listed by the order in which they
were selected.
The parameter ``s`` stops the selection process when there are ``s``
items remaining and these are selected by continuing the selection,
counting by 1 rather than by ``m``.
Consider selecting every 3rd item from 6 until only 2 remain::
choices chosen
======== ======
012345
01 345 2
01 34 25
01 4 253
0 4 2531
0 25314
253140
Examples
========
>>> from sympy.combinatorics import Permutation
>>> Permutation.josephus(3, 6, 2).array_form
[2, 5, 3, 1, 4, 0]
References
==========
1. http://en.wikipedia.org/wiki/Flavius_Josephus
2. http://en.wikipedia.org/wiki/Josephus_problem
3. http://www.wou.edu/~burtonl/josephus.html
"""
from collections import deque
m -= 1
Q = deque(list(range(n)))
perm = []
while len(Q) > max(s, 1):
for dp in range(m):
Q.append(Q.popleft())
perm.append(Q.popleft())
perm.extend(list(Q))
return Perm(perm)
@classmethod
def from_inversion_vector(self, inversion):
"""
Calculates the permutation from the inversion vector.
Examples
========
>>> from sympy.combinatorics.permutations import Permutation
>>> Permutation.print_cyclic = False
>>> Permutation.from_inversion_vector([3, 2, 1, 0, 0])
Permutation([3, 2, 1, 0, 4, 5])
"""
size = len(inversion)
N = list(range(size + 1))
perm = []
try:
for k in range(size):
val = N[inversion[k]]
perm.append(val)
N.remove(val)
except IndexError:
raise ValueError("The inversion vector is not valid.")
perm.extend(N)
return _af_new(perm)
@classmethod
def random(self, n):
"""
Generates a random permutation of length ``n``.
Uses the underlying Python pseudo-random number generator.
Examples
========
>>> from sympy.combinatorics.permutations import Permutation
>>> Permutation.random(2) in (Permutation([1, 0]), Permutation([0, 1]))
True
"""
perm_array = list(range(n))
random.shuffle(perm_array)
return _af_new(perm_array)
@classmethod
def unrank_lex(self, size, rank):
"""
Lexicographic permutation unranking.
Examples
========
>>> from sympy.combinatorics.permutations import Permutation
>>> Permutation.print_cyclic = False
>>> a = Permutation.unrank_lex(5, 10)
>>> a.rank()
10
>>> a
Permutation([0, 2, 4, 1, 3])
See Also
========
rank, next_lex
"""
perm_array = [0] * size
psize = 1
for i in range(size):
new_psize = psize*(i + 1)
d = (rank % new_psize) // psize
rank -= d*psize
perm_array[size - i - 1] = d
for j in range(size - i, size):
if perm_array[j] > d - 1:
perm_array[j] += 1
psize = new_psize
return _af_new(perm_array)
# global flag to control how permutations are printed
# when True, Permutation([0, 2, 1, 3]) -> Cycle(1, 2)
# when False, Permutation([0, 2, 1, 3]) -> Permutation([0, 2, 1])
print_cyclic = True
def _merge(arr, temp, left, mid, right):
"""
Merges two sorted arrays and calculates the inversion count.
Helper function for calculating inversions. This method is
for internal use only.
"""
i = k = left
j = mid
inv_count = 0
while i < mid and j <= right:
if arr[i] < arr[j]:
temp[k] = arr[i]
k += 1
i += 1
else:
temp[k] = arr[j]
k += 1
j += 1
inv_count += (mid -i)
while i < mid:
temp[k] = arr[i]
k += 1
i += 1
if j <= right:
k += right - j + 1
j += right - j + 1
arr[left:k + 1] = temp[left:k + 1]
else:
arr[left:right + 1] = temp[left:right + 1]
return inv_count
Perm = Permutation
_af_new = Perm._af_new
| bsd-3-clause |
run2/citytour | 4symantec/Lib/encodings/cp861.py | 593 | 34889 | """ Python Character Mapping Codec generated from 'VENDORS/MICSFT/PC/CP861.TXT' with gencodec.py.
"""#"
import codecs
### Codec APIs
class Codec(codecs.Codec):
def encode(self,input,errors='strict'):
return codecs.charmap_encode(input,errors,encoding_map)
def decode(self,input,errors='strict'):
return codecs.charmap_decode(input,errors,decoding_table)
class IncrementalEncoder(codecs.IncrementalEncoder):
def encode(self, input, final=False):
return codecs.charmap_encode(input,self.errors,encoding_map)[0]
class IncrementalDecoder(codecs.IncrementalDecoder):
def decode(self, input, final=False):
return codecs.charmap_decode(input,self.errors,decoding_table)[0]
class StreamWriter(Codec,codecs.StreamWriter):
pass
class StreamReader(Codec,codecs.StreamReader):
pass
### encodings module API
def getregentry():
return codecs.CodecInfo(
name='cp861',
encode=Codec().encode,
decode=Codec().decode,
incrementalencoder=IncrementalEncoder,
incrementaldecoder=IncrementalDecoder,
streamreader=StreamReader,
streamwriter=StreamWriter,
)
### Decoding Map
decoding_map = codecs.make_identity_dict(range(256))
decoding_map.update({
0x0080: 0x00c7, # LATIN CAPITAL LETTER C WITH CEDILLA
0x0081: 0x00fc, # LATIN SMALL LETTER U WITH DIAERESIS
0x0082: 0x00e9, # LATIN SMALL LETTER E WITH ACUTE
0x0083: 0x00e2, # LATIN SMALL LETTER A WITH CIRCUMFLEX
0x0084: 0x00e4, # LATIN SMALL LETTER A WITH DIAERESIS
0x0085: 0x00e0, # LATIN SMALL LETTER A WITH GRAVE
0x0086: 0x00e5, # LATIN SMALL LETTER A WITH RING ABOVE
0x0087: 0x00e7, # LATIN SMALL LETTER C WITH CEDILLA
0x0088: 0x00ea, # LATIN SMALL LETTER E WITH CIRCUMFLEX
0x0089: 0x00eb, # LATIN SMALL LETTER E WITH DIAERESIS
0x008a: 0x00e8, # LATIN SMALL LETTER E WITH GRAVE
0x008b: 0x00d0, # LATIN CAPITAL LETTER ETH
0x008c: 0x00f0, # LATIN SMALL LETTER ETH
0x008d: 0x00de, # LATIN CAPITAL LETTER THORN
0x008e: 0x00c4, # LATIN CAPITAL LETTER A WITH DIAERESIS
0x008f: 0x00c5, # LATIN CAPITAL LETTER A WITH RING ABOVE
0x0090: 0x00c9, # LATIN CAPITAL LETTER E WITH ACUTE
0x0091: 0x00e6, # LATIN SMALL LIGATURE AE
0x0092: 0x00c6, # LATIN CAPITAL LIGATURE AE
0x0093: 0x00f4, # LATIN SMALL LETTER O WITH CIRCUMFLEX
0x0094: 0x00f6, # LATIN SMALL LETTER O WITH DIAERESIS
0x0095: 0x00fe, # LATIN SMALL LETTER THORN
0x0096: 0x00fb, # LATIN SMALL LETTER U WITH CIRCUMFLEX
0x0097: 0x00dd, # LATIN CAPITAL LETTER Y WITH ACUTE
0x0098: 0x00fd, # LATIN SMALL LETTER Y WITH ACUTE
0x0099: 0x00d6, # LATIN CAPITAL LETTER O WITH DIAERESIS
0x009a: 0x00dc, # LATIN CAPITAL LETTER U WITH DIAERESIS
0x009b: 0x00f8, # LATIN SMALL LETTER O WITH STROKE
0x009c: 0x00a3, # POUND SIGN
0x009d: 0x00d8, # LATIN CAPITAL LETTER O WITH STROKE
0x009e: 0x20a7, # PESETA SIGN
0x009f: 0x0192, # LATIN SMALL LETTER F WITH HOOK
0x00a0: 0x00e1, # LATIN SMALL LETTER A WITH ACUTE
0x00a1: 0x00ed, # LATIN SMALL LETTER I WITH ACUTE
0x00a2: 0x00f3, # LATIN SMALL LETTER O WITH ACUTE
0x00a3: 0x00fa, # LATIN SMALL LETTER U WITH ACUTE
0x00a4: 0x00c1, # LATIN CAPITAL LETTER A WITH ACUTE
0x00a5: 0x00cd, # LATIN CAPITAL LETTER I WITH ACUTE
0x00a6: 0x00d3, # LATIN CAPITAL LETTER O WITH ACUTE
0x00a7: 0x00da, # LATIN CAPITAL LETTER U WITH ACUTE
0x00a8: 0x00bf, # INVERTED QUESTION MARK
0x00a9: 0x2310, # REVERSED NOT SIGN
0x00aa: 0x00ac, # NOT SIGN
0x00ab: 0x00bd, # VULGAR FRACTION ONE HALF
0x00ac: 0x00bc, # VULGAR FRACTION ONE QUARTER
0x00ad: 0x00a1, # INVERTED EXCLAMATION MARK
0x00ae: 0x00ab, # LEFT-POINTING DOUBLE ANGLE QUOTATION MARK
0x00af: 0x00bb, # RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK
0x00b0: 0x2591, # LIGHT SHADE
0x00b1: 0x2592, # MEDIUM SHADE
0x00b2: 0x2593, # DARK SHADE
0x00b3: 0x2502, # BOX DRAWINGS LIGHT VERTICAL
0x00b4: 0x2524, # BOX DRAWINGS LIGHT VERTICAL AND LEFT
0x00b5: 0x2561, # BOX DRAWINGS VERTICAL SINGLE AND LEFT DOUBLE
0x00b6: 0x2562, # BOX DRAWINGS VERTICAL DOUBLE AND LEFT SINGLE
0x00b7: 0x2556, # BOX DRAWINGS DOWN DOUBLE AND LEFT SINGLE
0x00b8: 0x2555, # BOX DRAWINGS DOWN SINGLE AND LEFT DOUBLE
0x00b9: 0x2563, # BOX DRAWINGS DOUBLE VERTICAL AND LEFT
0x00ba: 0x2551, # BOX DRAWINGS DOUBLE VERTICAL
0x00bb: 0x2557, # BOX DRAWINGS DOUBLE DOWN AND LEFT
0x00bc: 0x255d, # BOX DRAWINGS DOUBLE UP AND LEFT
0x00bd: 0x255c, # BOX DRAWINGS UP DOUBLE AND LEFT SINGLE
0x00be: 0x255b, # BOX DRAWINGS UP SINGLE AND LEFT DOUBLE
0x00bf: 0x2510, # BOX DRAWINGS LIGHT DOWN AND LEFT
0x00c0: 0x2514, # BOX DRAWINGS LIGHT UP AND RIGHT
0x00c1: 0x2534, # BOX DRAWINGS LIGHT UP AND HORIZONTAL
0x00c2: 0x252c, # BOX DRAWINGS LIGHT DOWN AND HORIZONTAL
0x00c3: 0x251c, # BOX DRAWINGS LIGHT VERTICAL AND RIGHT
0x00c4: 0x2500, # BOX DRAWINGS LIGHT HORIZONTAL
0x00c5: 0x253c, # BOX DRAWINGS LIGHT VERTICAL AND HORIZONTAL
0x00c6: 0x255e, # BOX DRAWINGS VERTICAL SINGLE AND RIGHT DOUBLE
0x00c7: 0x255f, # BOX DRAWINGS VERTICAL DOUBLE AND RIGHT SINGLE
0x00c8: 0x255a, # BOX DRAWINGS DOUBLE UP AND RIGHT
0x00c9: 0x2554, # BOX DRAWINGS DOUBLE DOWN AND RIGHT
0x00ca: 0x2569, # BOX DRAWINGS DOUBLE UP AND HORIZONTAL
0x00cb: 0x2566, # BOX DRAWINGS DOUBLE DOWN AND HORIZONTAL
0x00cc: 0x2560, # BOX DRAWINGS DOUBLE VERTICAL AND RIGHT
0x00cd: 0x2550, # BOX DRAWINGS DOUBLE HORIZONTAL
0x00ce: 0x256c, # BOX DRAWINGS DOUBLE VERTICAL AND HORIZONTAL
0x00cf: 0x2567, # BOX DRAWINGS UP SINGLE AND HORIZONTAL DOUBLE
0x00d0: 0x2568, # BOX DRAWINGS UP DOUBLE AND HORIZONTAL SINGLE
0x00d1: 0x2564, # BOX DRAWINGS DOWN SINGLE AND HORIZONTAL DOUBLE
0x00d2: 0x2565, # BOX DRAWINGS DOWN DOUBLE AND HORIZONTAL SINGLE
0x00d3: 0x2559, # BOX DRAWINGS UP DOUBLE AND RIGHT SINGLE
0x00d4: 0x2558, # BOX DRAWINGS UP SINGLE AND RIGHT DOUBLE
0x00d5: 0x2552, # BOX DRAWINGS DOWN SINGLE AND RIGHT DOUBLE
0x00d6: 0x2553, # BOX DRAWINGS DOWN DOUBLE AND RIGHT SINGLE
0x00d7: 0x256b, # BOX DRAWINGS VERTICAL DOUBLE AND HORIZONTAL SINGLE
0x00d8: 0x256a, # BOX DRAWINGS VERTICAL SINGLE AND HORIZONTAL DOUBLE
0x00d9: 0x2518, # BOX DRAWINGS LIGHT UP AND LEFT
0x00da: 0x250c, # BOX DRAWINGS LIGHT DOWN AND RIGHT
0x00db: 0x2588, # FULL BLOCK
0x00dc: 0x2584, # LOWER HALF BLOCK
0x00dd: 0x258c, # LEFT HALF BLOCK
0x00de: 0x2590, # RIGHT HALF BLOCK
0x00df: 0x2580, # UPPER HALF BLOCK
0x00e0: 0x03b1, # GREEK SMALL LETTER ALPHA
0x00e1: 0x00df, # LATIN SMALL LETTER SHARP S
0x00e2: 0x0393, # GREEK CAPITAL LETTER GAMMA
0x00e3: 0x03c0, # GREEK SMALL LETTER PI
0x00e4: 0x03a3, # GREEK CAPITAL LETTER SIGMA
0x00e5: 0x03c3, # GREEK SMALL LETTER SIGMA
0x00e6: 0x00b5, # MICRO SIGN
0x00e7: 0x03c4, # GREEK SMALL LETTER TAU
0x00e8: 0x03a6, # GREEK CAPITAL LETTER PHI
0x00e9: 0x0398, # GREEK CAPITAL LETTER THETA
0x00ea: 0x03a9, # GREEK CAPITAL LETTER OMEGA
0x00eb: 0x03b4, # GREEK SMALL LETTER DELTA
0x00ec: 0x221e, # INFINITY
0x00ed: 0x03c6, # GREEK SMALL LETTER PHI
0x00ee: 0x03b5, # GREEK SMALL LETTER EPSILON
0x00ef: 0x2229, # INTERSECTION
0x00f0: 0x2261, # IDENTICAL TO
0x00f1: 0x00b1, # PLUS-MINUS SIGN
0x00f2: 0x2265, # GREATER-THAN OR EQUAL TO
0x00f3: 0x2264, # LESS-THAN OR EQUAL TO
0x00f4: 0x2320, # TOP HALF INTEGRAL
0x00f5: 0x2321, # BOTTOM HALF INTEGRAL
0x00f6: 0x00f7, # DIVISION SIGN
0x00f7: 0x2248, # ALMOST EQUAL TO
0x00f8: 0x00b0, # DEGREE SIGN
0x00f9: 0x2219, # BULLET OPERATOR
0x00fa: 0x00b7, # MIDDLE DOT
0x00fb: 0x221a, # SQUARE ROOT
0x00fc: 0x207f, # SUPERSCRIPT LATIN SMALL LETTER N
0x00fd: 0x00b2, # SUPERSCRIPT TWO
0x00fe: 0x25a0, # BLACK SQUARE
0x00ff: 0x00a0, # NO-BREAK SPACE
})
### Decoding Table
decoding_table = (
u'\x00' # 0x0000 -> NULL
u'\x01' # 0x0001 -> START OF HEADING
u'\x02' # 0x0002 -> START OF TEXT
u'\x03' # 0x0003 -> END OF TEXT
u'\x04' # 0x0004 -> END OF TRANSMISSION
u'\x05' # 0x0005 -> ENQUIRY
u'\x06' # 0x0006 -> ACKNOWLEDGE
u'\x07' # 0x0007 -> BELL
u'\x08' # 0x0008 -> BACKSPACE
u'\t' # 0x0009 -> HORIZONTAL TABULATION
u'\n' # 0x000a -> LINE FEED
u'\x0b' # 0x000b -> VERTICAL TABULATION
u'\x0c' # 0x000c -> FORM FEED
u'\r' # 0x000d -> CARRIAGE RETURN
u'\x0e' # 0x000e -> SHIFT OUT
u'\x0f' # 0x000f -> SHIFT IN
u'\x10' # 0x0010 -> DATA LINK ESCAPE
u'\x11' # 0x0011 -> DEVICE CONTROL ONE
u'\x12' # 0x0012 -> DEVICE CONTROL TWO
u'\x13' # 0x0013 -> DEVICE CONTROL THREE
u'\x14' # 0x0014 -> DEVICE CONTROL FOUR
u'\x15' # 0x0015 -> NEGATIVE ACKNOWLEDGE
u'\x16' # 0x0016 -> SYNCHRONOUS IDLE
u'\x17' # 0x0017 -> END OF TRANSMISSION BLOCK
u'\x18' # 0x0018 -> CANCEL
u'\x19' # 0x0019 -> END OF MEDIUM
u'\x1a' # 0x001a -> SUBSTITUTE
u'\x1b' # 0x001b -> ESCAPE
u'\x1c' # 0x001c -> FILE SEPARATOR
u'\x1d' # 0x001d -> GROUP SEPARATOR
u'\x1e' # 0x001e -> RECORD SEPARATOR
u'\x1f' # 0x001f -> UNIT SEPARATOR
u' ' # 0x0020 -> SPACE
u'!' # 0x0021 -> EXCLAMATION MARK
u'"' # 0x0022 -> QUOTATION MARK
u'#' # 0x0023 -> NUMBER SIGN
u'$' # 0x0024 -> DOLLAR SIGN
u'%' # 0x0025 -> PERCENT SIGN
u'&' # 0x0026 -> AMPERSAND
u"'" # 0x0027 -> APOSTROPHE
u'(' # 0x0028 -> LEFT PARENTHESIS
u')' # 0x0029 -> RIGHT PARENTHESIS
u'*' # 0x002a -> ASTERISK
u'+' # 0x002b -> PLUS SIGN
u',' # 0x002c -> COMMA
u'-' # 0x002d -> HYPHEN-MINUS
u'.' # 0x002e -> FULL STOP
u'/' # 0x002f -> SOLIDUS
u'0' # 0x0030 -> DIGIT ZERO
u'1' # 0x0031 -> DIGIT ONE
u'2' # 0x0032 -> DIGIT TWO
u'3' # 0x0033 -> DIGIT THREE
u'4' # 0x0034 -> DIGIT FOUR
u'5' # 0x0035 -> DIGIT FIVE
u'6' # 0x0036 -> DIGIT SIX
u'7' # 0x0037 -> DIGIT SEVEN
u'8' # 0x0038 -> DIGIT EIGHT
u'9' # 0x0039 -> DIGIT NINE
u':' # 0x003a -> COLON
u';' # 0x003b -> SEMICOLON
u'<' # 0x003c -> LESS-THAN SIGN
u'=' # 0x003d -> EQUALS SIGN
u'>' # 0x003e -> GREATER-THAN SIGN
u'?' # 0x003f -> QUESTION MARK
u'@' # 0x0040 -> COMMERCIAL AT
u'A' # 0x0041 -> LATIN CAPITAL LETTER A
u'B' # 0x0042 -> LATIN CAPITAL LETTER B
u'C' # 0x0043 -> LATIN CAPITAL LETTER C
u'D' # 0x0044 -> LATIN CAPITAL LETTER D
u'E' # 0x0045 -> LATIN CAPITAL LETTER E
u'F' # 0x0046 -> LATIN CAPITAL LETTER F
u'G' # 0x0047 -> LATIN CAPITAL LETTER G
u'H' # 0x0048 -> LATIN CAPITAL LETTER H
u'I' # 0x0049 -> LATIN CAPITAL LETTER I
u'J' # 0x004a -> LATIN CAPITAL LETTER J
u'K' # 0x004b -> LATIN CAPITAL LETTER K
u'L' # 0x004c -> LATIN CAPITAL LETTER L
u'M' # 0x004d -> LATIN CAPITAL LETTER M
u'N' # 0x004e -> LATIN CAPITAL LETTER N
u'O' # 0x004f -> LATIN CAPITAL LETTER O
u'P' # 0x0050 -> LATIN CAPITAL LETTER P
u'Q' # 0x0051 -> LATIN CAPITAL LETTER Q
u'R' # 0x0052 -> LATIN CAPITAL LETTER R
u'S' # 0x0053 -> LATIN CAPITAL LETTER S
u'T' # 0x0054 -> LATIN CAPITAL LETTER T
u'U' # 0x0055 -> LATIN CAPITAL LETTER U
u'V' # 0x0056 -> LATIN CAPITAL LETTER V
u'W' # 0x0057 -> LATIN CAPITAL LETTER W
u'X' # 0x0058 -> LATIN CAPITAL LETTER X
u'Y' # 0x0059 -> LATIN CAPITAL LETTER Y
u'Z' # 0x005a -> LATIN CAPITAL LETTER Z
u'[' # 0x005b -> LEFT SQUARE BRACKET
u'\\' # 0x005c -> REVERSE SOLIDUS
u']' # 0x005d -> RIGHT SQUARE BRACKET
u'^' # 0x005e -> CIRCUMFLEX ACCENT
u'_' # 0x005f -> LOW LINE
u'`' # 0x0060 -> GRAVE ACCENT
u'a' # 0x0061 -> LATIN SMALL LETTER A
u'b' # 0x0062 -> LATIN SMALL LETTER B
u'c' # 0x0063 -> LATIN SMALL LETTER C
u'd' # 0x0064 -> LATIN SMALL LETTER D
u'e' # 0x0065 -> LATIN SMALL LETTER E
u'f' # 0x0066 -> LATIN SMALL LETTER F
u'g' # 0x0067 -> LATIN SMALL LETTER G
u'h' # 0x0068 -> LATIN SMALL LETTER H
u'i' # 0x0069 -> LATIN SMALL LETTER I
u'j' # 0x006a -> LATIN SMALL LETTER J
u'k' # 0x006b -> LATIN SMALL LETTER K
u'l' # 0x006c -> LATIN SMALL LETTER L
u'm' # 0x006d -> LATIN SMALL LETTER M
u'n' # 0x006e -> LATIN SMALL LETTER N
u'o' # 0x006f -> LATIN SMALL LETTER O
u'p' # 0x0070 -> LATIN SMALL LETTER P
u'q' # 0x0071 -> LATIN SMALL LETTER Q
u'r' # 0x0072 -> LATIN SMALL LETTER R
u's' # 0x0073 -> LATIN SMALL LETTER S
u't' # 0x0074 -> LATIN SMALL LETTER T
u'u' # 0x0075 -> LATIN SMALL LETTER U
u'v' # 0x0076 -> LATIN SMALL LETTER V
u'w' # 0x0077 -> LATIN SMALL LETTER W
u'x' # 0x0078 -> LATIN SMALL LETTER X
u'y' # 0x0079 -> LATIN SMALL LETTER Y
u'z' # 0x007a -> LATIN SMALL LETTER Z
u'{' # 0x007b -> LEFT CURLY BRACKET
u'|' # 0x007c -> VERTICAL LINE
u'}' # 0x007d -> RIGHT CURLY BRACKET
u'~' # 0x007e -> TILDE
u'\x7f' # 0x007f -> DELETE
u'\xc7' # 0x0080 -> LATIN CAPITAL LETTER C WITH CEDILLA
u'\xfc' # 0x0081 -> LATIN SMALL LETTER U WITH DIAERESIS
u'\xe9' # 0x0082 -> LATIN SMALL LETTER E WITH ACUTE
u'\xe2' # 0x0083 -> LATIN SMALL LETTER A WITH CIRCUMFLEX
u'\xe4' # 0x0084 -> LATIN SMALL LETTER A WITH DIAERESIS
u'\xe0' # 0x0085 -> LATIN SMALL LETTER A WITH GRAVE
u'\xe5' # 0x0086 -> LATIN SMALL LETTER A WITH RING ABOVE
u'\xe7' # 0x0087 -> LATIN SMALL LETTER C WITH CEDILLA
u'\xea' # 0x0088 -> LATIN SMALL LETTER E WITH CIRCUMFLEX
u'\xeb' # 0x0089 -> LATIN SMALL LETTER E WITH DIAERESIS
u'\xe8' # 0x008a -> LATIN SMALL LETTER E WITH GRAVE
u'\xd0' # 0x008b -> LATIN CAPITAL LETTER ETH
u'\xf0' # 0x008c -> LATIN SMALL LETTER ETH
u'\xde' # 0x008d -> LATIN CAPITAL LETTER THORN
u'\xc4' # 0x008e -> LATIN CAPITAL LETTER A WITH DIAERESIS
u'\xc5' # 0x008f -> LATIN CAPITAL LETTER A WITH RING ABOVE
u'\xc9' # 0x0090 -> LATIN CAPITAL LETTER E WITH ACUTE
u'\xe6' # 0x0091 -> LATIN SMALL LIGATURE AE
u'\xc6' # 0x0092 -> LATIN CAPITAL LIGATURE AE
u'\xf4' # 0x0093 -> LATIN SMALL LETTER O WITH CIRCUMFLEX
u'\xf6' # 0x0094 -> LATIN SMALL LETTER O WITH DIAERESIS
u'\xfe' # 0x0095 -> LATIN SMALL LETTER THORN
u'\xfb' # 0x0096 -> LATIN SMALL LETTER U WITH CIRCUMFLEX
u'\xdd' # 0x0097 -> LATIN CAPITAL LETTER Y WITH ACUTE
u'\xfd' # 0x0098 -> LATIN SMALL LETTER Y WITH ACUTE
u'\xd6' # 0x0099 -> LATIN CAPITAL LETTER O WITH DIAERESIS
u'\xdc' # 0x009a -> LATIN CAPITAL LETTER U WITH DIAERESIS
u'\xf8' # 0x009b -> LATIN SMALL LETTER O WITH STROKE
u'\xa3' # 0x009c -> POUND SIGN
u'\xd8' # 0x009d -> LATIN CAPITAL LETTER O WITH STROKE
u'\u20a7' # 0x009e -> PESETA SIGN
u'\u0192' # 0x009f -> LATIN SMALL LETTER F WITH HOOK
u'\xe1' # 0x00a0 -> LATIN SMALL LETTER A WITH ACUTE
u'\xed' # 0x00a1 -> LATIN SMALL LETTER I WITH ACUTE
u'\xf3' # 0x00a2 -> LATIN SMALL LETTER O WITH ACUTE
u'\xfa' # 0x00a3 -> LATIN SMALL LETTER U WITH ACUTE
u'\xc1' # 0x00a4 -> LATIN CAPITAL LETTER A WITH ACUTE
u'\xcd' # 0x00a5 -> LATIN CAPITAL LETTER I WITH ACUTE
u'\xd3' # 0x00a6 -> LATIN CAPITAL LETTER O WITH ACUTE
u'\xda' # 0x00a7 -> LATIN CAPITAL LETTER U WITH ACUTE
u'\xbf' # 0x00a8 -> INVERTED QUESTION MARK
u'\u2310' # 0x00a9 -> REVERSED NOT SIGN
u'\xac' # 0x00aa -> NOT SIGN
u'\xbd' # 0x00ab -> VULGAR FRACTION ONE HALF
u'\xbc' # 0x00ac -> VULGAR FRACTION ONE QUARTER
u'\xa1' # 0x00ad -> INVERTED EXCLAMATION MARK
u'\xab' # 0x00ae -> LEFT-POINTING DOUBLE ANGLE QUOTATION MARK
u'\xbb' # 0x00af -> RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK
u'\u2591' # 0x00b0 -> LIGHT SHADE
u'\u2592' # 0x00b1 -> MEDIUM SHADE
u'\u2593' # 0x00b2 -> DARK SHADE
u'\u2502' # 0x00b3 -> BOX DRAWINGS LIGHT VERTICAL
u'\u2524' # 0x00b4 -> BOX DRAWINGS LIGHT VERTICAL AND LEFT
u'\u2561' # 0x00b5 -> BOX DRAWINGS VERTICAL SINGLE AND LEFT DOUBLE
u'\u2562' # 0x00b6 -> BOX DRAWINGS VERTICAL DOUBLE AND LEFT SINGLE
u'\u2556' # 0x00b7 -> BOX DRAWINGS DOWN DOUBLE AND LEFT SINGLE
u'\u2555' # 0x00b8 -> BOX DRAWINGS DOWN SINGLE AND LEFT DOUBLE
u'\u2563' # 0x00b9 -> BOX DRAWINGS DOUBLE VERTICAL AND LEFT
u'\u2551' # 0x00ba -> BOX DRAWINGS DOUBLE VERTICAL
u'\u2557' # 0x00bb -> BOX DRAWINGS DOUBLE DOWN AND LEFT
u'\u255d' # 0x00bc -> BOX DRAWINGS DOUBLE UP AND LEFT
u'\u255c' # 0x00bd -> BOX DRAWINGS UP DOUBLE AND LEFT SINGLE
u'\u255b' # 0x00be -> BOX DRAWINGS UP SINGLE AND LEFT DOUBLE
u'\u2510' # 0x00bf -> BOX DRAWINGS LIGHT DOWN AND LEFT
u'\u2514' # 0x00c0 -> BOX DRAWINGS LIGHT UP AND RIGHT
u'\u2534' # 0x00c1 -> BOX DRAWINGS LIGHT UP AND HORIZONTAL
u'\u252c' # 0x00c2 -> BOX DRAWINGS LIGHT DOWN AND HORIZONTAL
u'\u251c' # 0x00c3 -> BOX DRAWINGS LIGHT VERTICAL AND RIGHT
u'\u2500' # 0x00c4 -> BOX DRAWINGS LIGHT HORIZONTAL
u'\u253c' # 0x00c5 -> BOX DRAWINGS LIGHT VERTICAL AND HORIZONTAL
u'\u255e' # 0x00c6 -> BOX DRAWINGS VERTICAL SINGLE AND RIGHT DOUBLE
u'\u255f' # 0x00c7 -> BOX DRAWINGS VERTICAL DOUBLE AND RIGHT SINGLE
u'\u255a' # 0x00c8 -> BOX DRAWINGS DOUBLE UP AND RIGHT
u'\u2554' # 0x00c9 -> BOX DRAWINGS DOUBLE DOWN AND RIGHT
u'\u2569' # 0x00ca -> BOX DRAWINGS DOUBLE UP AND HORIZONTAL
u'\u2566' # 0x00cb -> BOX DRAWINGS DOUBLE DOWN AND HORIZONTAL
u'\u2560' # 0x00cc -> BOX DRAWINGS DOUBLE VERTICAL AND RIGHT
u'\u2550' # 0x00cd -> BOX DRAWINGS DOUBLE HORIZONTAL
u'\u256c' # 0x00ce -> BOX DRAWINGS DOUBLE VERTICAL AND HORIZONTAL
u'\u2567' # 0x00cf -> BOX DRAWINGS UP SINGLE AND HORIZONTAL DOUBLE
u'\u2568' # 0x00d0 -> BOX DRAWINGS UP DOUBLE AND HORIZONTAL SINGLE
u'\u2564' # 0x00d1 -> BOX DRAWINGS DOWN SINGLE AND HORIZONTAL DOUBLE
u'\u2565' # 0x00d2 -> BOX DRAWINGS DOWN DOUBLE AND HORIZONTAL SINGLE
u'\u2559' # 0x00d3 -> BOX DRAWINGS UP DOUBLE AND RIGHT SINGLE
u'\u2558' # 0x00d4 -> BOX DRAWINGS UP SINGLE AND RIGHT DOUBLE
u'\u2552' # 0x00d5 -> BOX DRAWINGS DOWN SINGLE AND RIGHT DOUBLE
u'\u2553' # 0x00d6 -> BOX DRAWINGS DOWN DOUBLE AND RIGHT SINGLE
u'\u256b' # 0x00d7 -> BOX DRAWINGS VERTICAL DOUBLE AND HORIZONTAL SINGLE
u'\u256a' # 0x00d8 -> BOX DRAWINGS VERTICAL SINGLE AND HORIZONTAL DOUBLE
u'\u2518' # 0x00d9 -> BOX DRAWINGS LIGHT UP AND LEFT
u'\u250c' # 0x00da -> BOX DRAWINGS LIGHT DOWN AND RIGHT
u'\u2588' # 0x00db -> FULL BLOCK
u'\u2584' # 0x00dc -> LOWER HALF BLOCK
u'\u258c' # 0x00dd -> LEFT HALF BLOCK
u'\u2590' # 0x00de -> RIGHT HALF BLOCK
u'\u2580' # 0x00df -> UPPER HALF BLOCK
u'\u03b1' # 0x00e0 -> GREEK SMALL LETTER ALPHA
u'\xdf' # 0x00e1 -> LATIN SMALL LETTER SHARP S
u'\u0393' # 0x00e2 -> GREEK CAPITAL LETTER GAMMA
u'\u03c0' # 0x00e3 -> GREEK SMALL LETTER PI
u'\u03a3' # 0x00e4 -> GREEK CAPITAL LETTER SIGMA
u'\u03c3' # 0x00e5 -> GREEK SMALL LETTER SIGMA
u'\xb5' # 0x00e6 -> MICRO SIGN
u'\u03c4' # 0x00e7 -> GREEK SMALL LETTER TAU
u'\u03a6' # 0x00e8 -> GREEK CAPITAL LETTER PHI
u'\u0398' # 0x00e9 -> GREEK CAPITAL LETTER THETA
u'\u03a9' # 0x00ea -> GREEK CAPITAL LETTER OMEGA
u'\u03b4' # 0x00eb -> GREEK SMALL LETTER DELTA
u'\u221e' # 0x00ec -> INFINITY
u'\u03c6' # 0x00ed -> GREEK SMALL LETTER PHI
u'\u03b5' # 0x00ee -> GREEK SMALL LETTER EPSILON
u'\u2229' # 0x00ef -> INTERSECTION
u'\u2261' # 0x00f0 -> IDENTICAL TO
u'\xb1' # 0x00f1 -> PLUS-MINUS SIGN
u'\u2265' # 0x00f2 -> GREATER-THAN OR EQUAL TO
u'\u2264' # 0x00f3 -> LESS-THAN OR EQUAL TO
u'\u2320' # 0x00f4 -> TOP HALF INTEGRAL
u'\u2321' # 0x00f5 -> BOTTOM HALF INTEGRAL
u'\xf7' # 0x00f6 -> DIVISION SIGN
u'\u2248' # 0x00f7 -> ALMOST EQUAL TO
u'\xb0' # 0x00f8 -> DEGREE SIGN
u'\u2219' # 0x00f9 -> BULLET OPERATOR
u'\xb7' # 0x00fa -> MIDDLE DOT
u'\u221a' # 0x00fb -> SQUARE ROOT
u'\u207f' # 0x00fc -> SUPERSCRIPT LATIN SMALL LETTER N
u'\xb2' # 0x00fd -> SUPERSCRIPT TWO
u'\u25a0' # 0x00fe -> BLACK SQUARE
u'\xa0' # 0x00ff -> NO-BREAK SPACE
)
### Encoding Map
encoding_map = {
0x0000: 0x0000, # NULL
0x0001: 0x0001, # START OF HEADING
0x0002: 0x0002, # START OF TEXT
0x0003: 0x0003, # END OF TEXT
0x0004: 0x0004, # END OF TRANSMISSION
0x0005: 0x0005, # ENQUIRY
0x0006: 0x0006, # ACKNOWLEDGE
0x0007: 0x0007, # BELL
0x0008: 0x0008, # BACKSPACE
0x0009: 0x0009, # HORIZONTAL TABULATION
0x000a: 0x000a, # LINE FEED
0x000b: 0x000b, # VERTICAL TABULATION
0x000c: 0x000c, # FORM FEED
0x000d: 0x000d, # CARRIAGE RETURN
0x000e: 0x000e, # SHIFT OUT
0x000f: 0x000f, # SHIFT IN
0x0010: 0x0010, # DATA LINK ESCAPE
0x0011: 0x0011, # DEVICE CONTROL ONE
0x0012: 0x0012, # DEVICE CONTROL TWO
0x0013: 0x0013, # DEVICE CONTROL THREE
0x0014: 0x0014, # DEVICE CONTROL FOUR
0x0015: 0x0015, # NEGATIVE ACKNOWLEDGE
0x0016: 0x0016, # SYNCHRONOUS IDLE
0x0017: 0x0017, # END OF TRANSMISSION BLOCK
0x0018: 0x0018, # CANCEL
0x0019: 0x0019, # END OF MEDIUM
0x001a: 0x001a, # SUBSTITUTE
0x001b: 0x001b, # ESCAPE
0x001c: 0x001c, # FILE SEPARATOR
0x001d: 0x001d, # GROUP SEPARATOR
0x001e: 0x001e, # RECORD SEPARATOR
0x001f: 0x001f, # UNIT SEPARATOR
0x0020: 0x0020, # SPACE
0x0021: 0x0021, # EXCLAMATION MARK
0x0022: 0x0022, # QUOTATION MARK
0x0023: 0x0023, # NUMBER SIGN
0x0024: 0x0024, # DOLLAR SIGN
0x0025: 0x0025, # PERCENT SIGN
0x0026: 0x0026, # AMPERSAND
0x0027: 0x0027, # APOSTROPHE
0x0028: 0x0028, # LEFT PARENTHESIS
0x0029: 0x0029, # RIGHT PARENTHESIS
0x002a: 0x002a, # ASTERISK
0x002b: 0x002b, # PLUS SIGN
0x002c: 0x002c, # COMMA
0x002d: 0x002d, # HYPHEN-MINUS
0x002e: 0x002e, # FULL STOP
0x002f: 0x002f, # SOLIDUS
0x0030: 0x0030, # DIGIT ZERO
0x0031: 0x0031, # DIGIT ONE
0x0032: 0x0032, # DIGIT TWO
0x0033: 0x0033, # DIGIT THREE
0x0034: 0x0034, # DIGIT FOUR
0x0035: 0x0035, # DIGIT FIVE
0x0036: 0x0036, # DIGIT SIX
0x0037: 0x0037, # DIGIT SEVEN
0x0038: 0x0038, # DIGIT EIGHT
0x0039: 0x0039, # DIGIT NINE
0x003a: 0x003a, # COLON
0x003b: 0x003b, # SEMICOLON
0x003c: 0x003c, # LESS-THAN SIGN
0x003d: 0x003d, # EQUALS SIGN
0x003e: 0x003e, # GREATER-THAN SIGN
0x003f: 0x003f, # QUESTION MARK
0x0040: 0x0040, # COMMERCIAL AT
0x0041: 0x0041, # LATIN CAPITAL LETTER A
0x0042: 0x0042, # LATIN CAPITAL LETTER B
0x0043: 0x0043, # LATIN CAPITAL LETTER C
0x0044: 0x0044, # LATIN CAPITAL LETTER D
0x0045: 0x0045, # LATIN CAPITAL LETTER E
0x0046: 0x0046, # LATIN CAPITAL LETTER F
0x0047: 0x0047, # LATIN CAPITAL LETTER G
0x0048: 0x0048, # LATIN CAPITAL LETTER H
0x0049: 0x0049, # LATIN CAPITAL LETTER I
0x004a: 0x004a, # LATIN CAPITAL LETTER J
0x004b: 0x004b, # LATIN CAPITAL LETTER K
0x004c: 0x004c, # LATIN CAPITAL LETTER L
0x004d: 0x004d, # LATIN CAPITAL LETTER M
0x004e: 0x004e, # LATIN CAPITAL LETTER N
0x004f: 0x004f, # LATIN CAPITAL LETTER O
0x0050: 0x0050, # LATIN CAPITAL LETTER P
0x0051: 0x0051, # LATIN CAPITAL LETTER Q
0x0052: 0x0052, # LATIN CAPITAL LETTER R
0x0053: 0x0053, # LATIN CAPITAL LETTER S
0x0054: 0x0054, # LATIN CAPITAL LETTER T
0x0055: 0x0055, # LATIN CAPITAL LETTER U
0x0056: 0x0056, # LATIN CAPITAL LETTER V
0x0057: 0x0057, # LATIN CAPITAL LETTER W
0x0058: 0x0058, # LATIN CAPITAL LETTER X
0x0059: 0x0059, # LATIN CAPITAL LETTER Y
0x005a: 0x005a, # LATIN CAPITAL LETTER Z
0x005b: 0x005b, # LEFT SQUARE BRACKET
0x005c: 0x005c, # REVERSE SOLIDUS
0x005d: 0x005d, # RIGHT SQUARE BRACKET
0x005e: 0x005e, # CIRCUMFLEX ACCENT
0x005f: 0x005f, # LOW LINE
0x0060: 0x0060, # GRAVE ACCENT
0x0061: 0x0061, # LATIN SMALL LETTER A
0x0062: 0x0062, # LATIN SMALL LETTER B
0x0063: 0x0063, # LATIN SMALL LETTER C
0x0064: 0x0064, # LATIN SMALL LETTER D
0x0065: 0x0065, # LATIN SMALL LETTER E
0x0066: 0x0066, # LATIN SMALL LETTER F
0x0067: 0x0067, # LATIN SMALL LETTER G
0x0068: 0x0068, # LATIN SMALL LETTER H
0x0069: 0x0069, # LATIN SMALL LETTER I
0x006a: 0x006a, # LATIN SMALL LETTER J
0x006b: 0x006b, # LATIN SMALL LETTER K
0x006c: 0x006c, # LATIN SMALL LETTER L
0x006d: 0x006d, # LATIN SMALL LETTER M
0x006e: 0x006e, # LATIN SMALL LETTER N
0x006f: 0x006f, # LATIN SMALL LETTER O
0x0070: 0x0070, # LATIN SMALL LETTER P
0x0071: 0x0071, # LATIN SMALL LETTER Q
0x0072: 0x0072, # LATIN SMALL LETTER R
0x0073: 0x0073, # LATIN SMALL LETTER S
0x0074: 0x0074, # LATIN SMALL LETTER T
0x0075: 0x0075, # LATIN SMALL LETTER U
0x0076: 0x0076, # LATIN SMALL LETTER V
0x0077: 0x0077, # LATIN SMALL LETTER W
0x0078: 0x0078, # LATIN SMALL LETTER X
0x0079: 0x0079, # LATIN SMALL LETTER Y
0x007a: 0x007a, # LATIN SMALL LETTER Z
0x007b: 0x007b, # LEFT CURLY BRACKET
0x007c: 0x007c, # VERTICAL LINE
0x007d: 0x007d, # RIGHT CURLY BRACKET
0x007e: 0x007e, # TILDE
0x007f: 0x007f, # DELETE
0x00a0: 0x00ff, # NO-BREAK SPACE
0x00a1: 0x00ad, # INVERTED EXCLAMATION MARK
0x00a3: 0x009c, # POUND SIGN
0x00ab: 0x00ae, # LEFT-POINTING DOUBLE ANGLE QUOTATION MARK
0x00ac: 0x00aa, # NOT SIGN
0x00b0: 0x00f8, # DEGREE SIGN
0x00b1: 0x00f1, # PLUS-MINUS SIGN
0x00b2: 0x00fd, # SUPERSCRIPT TWO
0x00b5: 0x00e6, # MICRO SIGN
0x00b7: 0x00fa, # MIDDLE DOT
0x00bb: 0x00af, # RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK
0x00bc: 0x00ac, # VULGAR FRACTION ONE QUARTER
0x00bd: 0x00ab, # VULGAR FRACTION ONE HALF
0x00bf: 0x00a8, # INVERTED QUESTION MARK
0x00c1: 0x00a4, # LATIN CAPITAL LETTER A WITH ACUTE
0x00c4: 0x008e, # LATIN CAPITAL LETTER A WITH DIAERESIS
0x00c5: 0x008f, # LATIN CAPITAL LETTER A WITH RING ABOVE
0x00c6: 0x0092, # LATIN CAPITAL LIGATURE AE
0x00c7: 0x0080, # LATIN CAPITAL LETTER C WITH CEDILLA
0x00c9: 0x0090, # LATIN CAPITAL LETTER E WITH ACUTE
0x00cd: 0x00a5, # LATIN CAPITAL LETTER I WITH ACUTE
0x00d0: 0x008b, # LATIN CAPITAL LETTER ETH
0x00d3: 0x00a6, # LATIN CAPITAL LETTER O WITH ACUTE
0x00d6: 0x0099, # LATIN CAPITAL LETTER O WITH DIAERESIS
0x00d8: 0x009d, # LATIN CAPITAL LETTER O WITH STROKE
0x00da: 0x00a7, # LATIN CAPITAL LETTER U WITH ACUTE
0x00dc: 0x009a, # LATIN CAPITAL LETTER U WITH DIAERESIS
0x00dd: 0x0097, # LATIN CAPITAL LETTER Y WITH ACUTE
0x00de: 0x008d, # LATIN CAPITAL LETTER THORN
0x00df: 0x00e1, # LATIN SMALL LETTER SHARP S
0x00e0: 0x0085, # LATIN SMALL LETTER A WITH GRAVE
0x00e1: 0x00a0, # LATIN SMALL LETTER A WITH ACUTE
0x00e2: 0x0083, # LATIN SMALL LETTER A WITH CIRCUMFLEX
0x00e4: 0x0084, # LATIN SMALL LETTER A WITH DIAERESIS
0x00e5: 0x0086, # LATIN SMALL LETTER A WITH RING ABOVE
0x00e6: 0x0091, # LATIN SMALL LIGATURE AE
0x00e7: 0x0087, # LATIN SMALL LETTER C WITH CEDILLA
0x00e8: 0x008a, # LATIN SMALL LETTER E WITH GRAVE
0x00e9: 0x0082, # LATIN SMALL LETTER E WITH ACUTE
0x00ea: 0x0088, # LATIN SMALL LETTER E WITH CIRCUMFLEX
0x00eb: 0x0089, # LATIN SMALL LETTER E WITH DIAERESIS
0x00ed: 0x00a1, # LATIN SMALL LETTER I WITH ACUTE
0x00f0: 0x008c, # LATIN SMALL LETTER ETH
0x00f3: 0x00a2, # LATIN SMALL LETTER O WITH ACUTE
0x00f4: 0x0093, # LATIN SMALL LETTER O WITH CIRCUMFLEX
0x00f6: 0x0094, # LATIN SMALL LETTER O WITH DIAERESIS
0x00f7: 0x00f6, # DIVISION SIGN
0x00f8: 0x009b, # LATIN SMALL LETTER O WITH STROKE
0x00fa: 0x00a3, # LATIN SMALL LETTER U WITH ACUTE
0x00fb: 0x0096, # LATIN SMALL LETTER U WITH CIRCUMFLEX
0x00fc: 0x0081, # LATIN SMALL LETTER U WITH DIAERESIS
0x00fd: 0x0098, # LATIN SMALL LETTER Y WITH ACUTE
0x00fe: 0x0095, # LATIN SMALL LETTER THORN
0x0192: 0x009f, # LATIN SMALL LETTER F WITH HOOK
0x0393: 0x00e2, # GREEK CAPITAL LETTER GAMMA
0x0398: 0x00e9, # GREEK CAPITAL LETTER THETA
0x03a3: 0x00e4, # GREEK CAPITAL LETTER SIGMA
0x03a6: 0x00e8, # GREEK CAPITAL LETTER PHI
0x03a9: 0x00ea, # GREEK CAPITAL LETTER OMEGA
0x03b1: 0x00e0, # GREEK SMALL LETTER ALPHA
0x03b4: 0x00eb, # GREEK SMALL LETTER DELTA
0x03b5: 0x00ee, # GREEK SMALL LETTER EPSILON
0x03c0: 0x00e3, # GREEK SMALL LETTER PI
0x03c3: 0x00e5, # GREEK SMALL LETTER SIGMA
0x03c4: 0x00e7, # GREEK SMALL LETTER TAU
0x03c6: 0x00ed, # GREEK SMALL LETTER PHI
0x207f: 0x00fc, # SUPERSCRIPT LATIN SMALL LETTER N
0x20a7: 0x009e, # PESETA SIGN
0x2219: 0x00f9, # BULLET OPERATOR
0x221a: 0x00fb, # SQUARE ROOT
0x221e: 0x00ec, # INFINITY
0x2229: 0x00ef, # INTERSECTION
0x2248: 0x00f7, # ALMOST EQUAL TO
0x2261: 0x00f0, # IDENTICAL TO
0x2264: 0x00f3, # LESS-THAN OR EQUAL TO
0x2265: 0x00f2, # GREATER-THAN OR EQUAL TO
0x2310: 0x00a9, # REVERSED NOT SIGN
0x2320: 0x00f4, # TOP HALF INTEGRAL
0x2321: 0x00f5, # BOTTOM HALF INTEGRAL
0x2500: 0x00c4, # BOX DRAWINGS LIGHT HORIZONTAL
0x2502: 0x00b3, # BOX DRAWINGS LIGHT VERTICAL
0x250c: 0x00da, # BOX DRAWINGS LIGHT DOWN AND RIGHT
0x2510: 0x00bf, # BOX DRAWINGS LIGHT DOWN AND LEFT
0x2514: 0x00c0, # BOX DRAWINGS LIGHT UP AND RIGHT
0x2518: 0x00d9, # BOX DRAWINGS LIGHT UP AND LEFT
0x251c: 0x00c3, # BOX DRAWINGS LIGHT VERTICAL AND RIGHT
0x2524: 0x00b4, # BOX DRAWINGS LIGHT VERTICAL AND LEFT
0x252c: 0x00c2, # BOX DRAWINGS LIGHT DOWN AND HORIZONTAL
0x2534: 0x00c1, # BOX DRAWINGS LIGHT UP AND HORIZONTAL
0x253c: 0x00c5, # BOX DRAWINGS LIGHT VERTICAL AND HORIZONTAL
0x2550: 0x00cd, # BOX DRAWINGS DOUBLE HORIZONTAL
0x2551: 0x00ba, # BOX DRAWINGS DOUBLE VERTICAL
0x2552: 0x00d5, # BOX DRAWINGS DOWN SINGLE AND RIGHT DOUBLE
0x2553: 0x00d6, # BOX DRAWINGS DOWN DOUBLE AND RIGHT SINGLE
0x2554: 0x00c9, # BOX DRAWINGS DOUBLE DOWN AND RIGHT
0x2555: 0x00b8, # BOX DRAWINGS DOWN SINGLE AND LEFT DOUBLE
0x2556: 0x00b7, # BOX DRAWINGS DOWN DOUBLE AND LEFT SINGLE
0x2557: 0x00bb, # BOX DRAWINGS DOUBLE DOWN AND LEFT
0x2558: 0x00d4, # BOX DRAWINGS UP SINGLE AND RIGHT DOUBLE
0x2559: 0x00d3, # BOX DRAWINGS UP DOUBLE AND RIGHT SINGLE
0x255a: 0x00c8, # BOX DRAWINGS DOUBLE UP AND RIGHT
0x255b: 0x00be, # BOX DRAWINGS UP SINGLE AND LEFT DOUBLE
0x255c: 0x00bd, # BOX DRAWINGS UP DOUBLE AND LEFT SINGLE
0x255d: 0x00bc, # BOX DRAWINGS DOUBLE UP AND LEFT
0x255e: 0x00c6, # BOX DRAWINGS VERTICAL SINGLE AND RIGHT DOUBLE
0x255f: 0x00c7, # BOX DRAWINGS VERTICAL DOUBLE AND RIGHT SINGLE
0x2560: 0x00cc, # BOX DRAWINGS DOUBLE VERTICAL AND RIGHT
0x2561: 0x00b5, # BOX DRAWINGS VERTICAL SINGLE AND LEFT DOUBLE
0x2562: 0x00b6, # BOX DRAWINGS VERTICAL DOUBLE AND LEFT SINGLE
0x2563: 0x00b9, # BOX DRAWINGS DOUBLE VERTICAL AND LEFT
0x2564: 0x00d1, # BOX DRAWINGS DOWN SINGLE AND HORIZONTAL DOUBLE
0x2565: 0x00d2, # BOX DRAWINGS DOWN DOUBLE AND HORIZONTAL SINGLE
0x2566: 0x00cb, # BOX DRAWINGS DOUBLE DOWN AND HORIZONTAL
0x2567: 0x00cf, # BOX DRAWINGS UP SINGLE AND HORIZONTAL DOUBLE
0x2568: 0x00d0, # BOX DRAWINGS UP DOUBLE AND HORIZONTAL SINGLE
0x2569: 0x00ca, # BOX DRAWINGS DOUBLE UP AND HORIZONTAL
0x256a: 0x00d8, # BOX DRAWINGS VERTICAL SINGLE AND HORIZONTAL DOUBLE
0x256b: 0x00d7, # BOX DRAWINGS VERTICAL DOUBLE AND HORIZONTAL SINGLE
0x256c: 0x00ce, # BOX DRAWINGS DOUBLE VERTICAL AND HORIZONTAL
0x2580: 0x00df, # UPPER HALF BLOCK
0x2584: 0x00dc, # LOWER HALF BLOCK
0x2588: 0x00db, # FULL BLOCK
0x258c: 0x00dd, # LEFT HALF BLOCK
0x2590: 0x00de, # RIGHT HALF BLOCK
0x2591: 0x00b0, # LIGHT SHADE
0x2592: 0x00b1, # MEDIUM SHADE
0x2593: 0x00b2, # DARK SHADE
0x25a0: 0x00fe, # BLACK SQUARE
}
| mit |
dedalusdev/docker-registry | tests/mock_s3.py | 35 | 1940 | # -*- coding: utf-8 -*-
'''Monkeypatch s3 Storage preventing parallel key stream read in unittesting.
It is called from lib/storage/s3'''
import six
from docker_registry.core import exceptions
import docker_registry.drivers.s3 as s3
from docker_registry.testing import utils
@six.add_metaclass(utils.monkeypatch_class)
class Storage(s3.Storage):
# def stream_read(self, path, bytes_range=None):
# path = self._init_path(path)
# headers = None
# if bytes_range:
# headers = {'Range': 'bytes={0}-{1}'.format(*bytes_range)}
# key = self._boto_bucket.lookup(path, headers=headers)
# if not key:
# raise exceptions.FileNotFoundError('%s is not there' % path)
# while True:
# buf = key.read(self.buffer_size)
# if not buf:
# break
# yield buf
def stream_read(self, path, bytes_range=None):
path = self._init_path(path)
nb_bytes = 0
total_size = 0
key = self._boto_bucket.lookup(path)
if not key:
raise exceptions.FileNotFoundError('%s is not there' % path)
if bytes_range:
key._last_position = bytes_range[0]
total_size = bytes_range[1] - bytes_range[0] + 1
while True:
if bytes_range:
# Bytes Range is enabled
buf_size = self.buffer_size
if nb_bytes + buf_size > total_size:
# We make sure we don't read out of the range
buf_size = total_size - nb_bytes
if buf_size > 0:
buf = key.read(buf_size)
nb_bytes += len(buf)
else:
# We're at the end of the range
buf = ''
else:
buf = key.read(self.buffer_size)
if not buf:
break
yield buf
| apache-2.0 |
wiki-ai/revscoring | revscoring/scoring/models/util.py | 2 | 1246 | import json
import numpy
def normalize(v):
if isinstance(v, numpy.bool_):
return bool(v)
elif isinstance(v, numpy.ndarray):
return [normalize(item) for item in v]
elif v == numpy.NaN:
return "NaN"
elif v == numpy.NINF:
return "-Infinity"
elif v == numpy.PINF:
return "Infinity"
elif isinstance(v, numpy.float):
return float(v)
elif isinstance(v, tuple):
return list(v)
else:
return v
def key_normalize(v):
v = normalize(v)
if isinstance(v, bool) or isinstance(v, int) or isinstance(v, float) or \
isinstance(v, str):
return v
elif isinstance(v, list) or isinstance(v, dict):
return json.dumps(v)
else:
return str(v)
def normalize_json(doc):
if isinstance(doc, dict):
return {key_normalize(k): normalize_json(v)
for k, v in doc.items()}
elif isinstance(doc, list) or isinstance(doc, tuple):
return [normalize_json(v) for v in doc]
else:
return normalize(doc)
def format_params(doc):
if doc is None:
return None
else:
return ", ".join("{0}={1}".format(k, json.dumps(v))
for k, v in doc.items())
| mit |
nhenezi/kuma | vendor/packages/html5lib/src/html5lib/filters/optionaltags.py | 129 | 10415 | import _base
class Filter(_base.Filter):
def slider(self):
previous1 = previous2 = None
for token in self.source:
if previous1 is not None:
yield previous2, previous1, token
previous2 = previous1
previous1 = token
yield previous2, previous1, None
def __iter__(self):
for previous, token, next in self.slider():
type = token["type"]
if type == "StartTag":
if (token["data"] or
not self.is_optional_start(token["name"], previous, next)):
yield token
elif type == "EndTag":
if not self.is_optional_end(token["name"], next):
yield token
else:
yield token
def is_optional_start(self, tagname, previous, next):
type = next and next["type"] or None
if tagname in 'html':
# An html element's start tag may be omitted if the first thing
# inside the html element is not a space character or a comment.
return type not in ("Comment", "SpaceCharacters")
elif tagname == 'head':
# A head element's start tag may be omitted if the first thing
# inside the head element is an element.
# XXX: we also omit the start tag if the head element is empty
if type in ("StartTag", "EmptyTag"):
return True
elif type == "EndTag":
return next["name"] == "head"
elif tagname == 'body':
# A body element's start tag may be omitted if the first thing
# inside the body element is not a space character or a comment,
# except if the first thing inside the body element is a script
# or style element and the node immediately preceding the body
# element is a head element whose end tag has been omitted.
if type in ("Comment", "SpaceCharacters"):
return False
elif type == "StartTag":
# XXX: we do not look at the preceding event, so we never omit
# the body element's start tag if it's followed by a script or
# a style element.
return next["name"] not in ('script', 'style')
else:
return True
elif tagname == 'colgroup':
# A colgroup element's start tag may be omitted if the first thing
# inside the colgroup element is a col element, and if the element
# is not immediately preceeded by another colgroup element whose
# end tag has been omitted.
if type in ("StartTag", "EmptyTag"):
# XXX: we do not look at the preceding event, so instead we never
# omit the colgroup element's end tag when it is immediately
# followed by another colgroup element. See is_optional_end.
return next["name"] == "col"
else:
return False
elif tagname == 'tbody':
# A tbody element's start tag may be omitted if the first thing
# inside the tbody element is a tr element, and if the element is
# not immediately preceeded by a tbody, thead, or tfoot element
# whose end tag has been omitted.
if type == "StartTag":
# omit the thead and tfoot elements' end tag when they are
# immediately followed by a tbody element. See is_optional_end.
if previous and previous['type'] == 'EndTag' and \
previous['name'] in ('tbody','thead','tfoot'):
return False
return next["name"] == 'tr'
else:
return False
return False
def is_optional_end(self, tagname, next):
type = next and next["type"] or None
if tagname in ('html', 'head', 'body'):
# An html element's end tag may be omitted if the html element
# is not immediately followed by a space character or a comment.
return type not in ("Comment", "SpaceCharacters")
elif tagname in ('li', 'optgroup', 'tr'):
# A li element's end tag may be omitted if the li element is
# immediately followed by another li element or if there is
# no more content in the parent element.
# An optgroup element's end tag may be omitted if the optgroup
# element is immediately followed by another optgroup element,
# or if there is no more content in the parent element.
# A tr element's end tag may be omitted if the tr element is
# immediately followed by another tr element, or if there is
# no more content in the parent element.
if type == "StartTag":
return next["name"] == tagname
else:
return type == "EndTag" or type is None
elif tagname in ('dt', 'dd'):
# A dt element's end tag may be omitted if the dt element is
# immediately followed by another dt element or a dd element.
# A dd element's end tag may be omitted if the dd element is
# immediately followed by another dd element or a dt element,
# or if there is no more content in the parent element.
if type == "StartTag":
return next["name"] in ('dt', 'dd')
elif tagname == 'dd':
return type == "EndTag" or type is None
else:
return False
elif tagname == 'p':
# A p element's end tag may be omitted if the p element is
# immediately followed by an address, article, aside,
# blockquote, datagrid, dialog, dir, div, dl, fieldset,
# footer, form, h1, h2, h3, h4, h5, h6, header, hr, menu,
# nav, ol, p, pre, section, table, or ul, element, or if
# there is no more content in the parent element.
if type in ("StartTag", "EmptyTag"):
return next["name"] in ('address', 'article', 'aside',
'blockquote', 'datagrid', 'dialog',
'dir', 'div', 'dl', 'fieldset', 'footer',
'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6',
'header', 'hr', 'menu', 'nav', 'ol',
'p', 'pre', 'section', 'table', 'ul')
else:
return type == "EndTag" or type is None
elif tagname == 'option':
# An option element's end tag may be omitted if the option
# element is immediately followed by another option element,
# or if it is immediately followed by an <code>optgroup</code>
# element, or if there is no more content in the parent
# element.
if type == "StartTag":
return next["name"] in ('option', 'optgroup')
else:
return type == "EndTag" or type is None
elif tagname in ('rt', 'rp'):
# An rt element's end tag may be omitted if the rt element is
# immediately followed by an rt or rp element, or if there is
# no more content in the parent element.
# An rp element's end tag may be omitted if the rp element is
# immediately followed by an rt or rp element, or if there is
# no more content in the parent element.
if type == "StartTag":
return next["name"] in ('rt', 'rp')
else:
return type == "EndTag" or type is None
elif tagname == 'colgroup':
# A colgroup element's end tag may be omitted if the colgroup
# element is not immediately followed by a space character or
# a comment.
if type in ("Comment", "SpaceCharacters"):
return False
elif type == "StartTag":
# XXX: we also look for an immediately following colgroup
# element. See is_optional_start.
return next["name"] != 'colgroup'
else:
return True
elif tagname in ('thead', 'tbody'):
# A thead element's end tag may be omitted if the thead element
# is immediately followed by a tbody or tfoot element.
# A tbody element's end tag may be omitted if the tbody element
# is immediately followed by a tbody or tfoot element, or if
# there is no more content in the parent element.
# A tfoot element's end tag may be omitted if the tfoot element
# is immediately followed by a tbody element, or if there is no
# more content in the parent element.
# XXX: we never omit the end tag when the following element is
# a tbody. See is_optional_start.
if type == "StartTag":
return next["name"] in ['tbody', 'tfoot']
elif tagname == 'tbody':
return type == "EndTag" or type is None
else:
return False
elif tagname == 'tfoot':
# A tfoot element's end tag may be omitted if the tfoot element
# is immediately followed by a tbody element, or if there is no
# more content in the parent element.
# XXX: we never omit the end tag when the following element is
# a tbody. See is_optional_start.
if type == "StartTag":
return next["name"] == 'tbody'
else:
return type == "EndTag" or type is None
elif tagname in ('td', 'th'):
# A td element's end tag may be omitted if the td element is
# immediately followed by a td or th element, or if there is
# no more content in the parent element.
# A th element's end tag may be omitted if the th element is
# immediately followed by a td or th element, or if there is
# no more content in the parent element.
if type == "StartTag":
return next["name"] in ('td', 'th')
else:
return type == "EndTag" or type is None
return False
| mpl-2.0 |
dnozay/lettuce | tests/integration/lib/Django-1.2.5/django/contrib/gis/db/backends/postgis/adapter.py | 311 | 1165 | """
This object provides quoting for GEOS geometries into PostgreSQL/PostGIS.
"""
from psycopg2 import Binary
from psycopg2.extensions import ISQLQuote
class PostGISAdapter(object):
def __init__(self, geom):
"Initializes on the geometry."
# Getting the WKB (in string form, to allow easy pickling of
# the adaptor) and the SRID from the geometry.
self.ewkb = str(geom.ewkb)
self.srid = geom.srid
def __conform__(self, proto):
# Does the given protocol conform to what Psycopg2 expects?
if proto == ISQLQuote:
return self
else:
raise Exception('Error implementing psycopg2 protocol. Is psycopg2 installed?')
def __eq__(self, other):
return (self.ewkb == other.ewkb) and (self.srid == other.srid)
def __str__(self):
return self.getquoted()
def getquoted(self):
"Returns a properly quoted string for use in PostgreSQL/PostGIS."
# Want to use WKB, so wrap with psycopg2 Binary() to quote properly.
return 'ST_GeomFromEWKB(E%s)' % Binary(self.ewkb)
def prepare_database_save(self, unused):
return self
| gpl-3.0 |
shinrain/tornado | demos/websocket/chatdemo.py | 14 | 3172 | #!/usr/bin/env python
#
# Copyright 2009 Facebook
#
# 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.
"""Simplified chat demo for websockets.
Authentication, error handling, etc are left as an exercise for the reader :)
"""
import logging
import tornado.escape
import tornado.ioloop
import tornado.options
import tornado.web
import tornado.websocket
import os.path
import uuid
from tornado.options import define, options
define("port", default=8888, help="run on the given port", type=int)
class Application(tornado.web.Application):
def __init__(self):
handlers = [
(r"/", MainHandler),
(r"/chatsocket", ChatSocketHandler),
]
settings = dict(
cookie_secret="__TODO:_GENERATE_YOUR_OWN_RANDOM_VALUE_HERE__",
template_path=os.path.join(os.path.dirname(__file__), "templates"),
static_path=os.path.join(os.path.dirname(__file__), "static"),
xsrf_cookies=True,
)
tornado.web.Application.__init__(self, handlers, **settings)
class MainHandler(tornado.web.RequestHandler):
def get(self):
self.render("index.html", messages=ChatSocketHandler.cache)
class ChatSocketHandler(tornado.websocket.WebSocketHandler):
waiters = set()
cache = []
cache_size = 200
def get_compression_options(self):
# Non-None enables compression with default options.
return {}
def open(self):
ChatSocketHandler.waiters.add(self)
def on_close(self):
ChatSocketHandler.waiters.remove(self)
@classmethod
def update_cache(cls, chat):
cls.cache.append(chat)
if len(cls.cache) > cls.cache_size:
cls.cache = cls.cache[-cls.cache_size:]
@classmethod
def send_updates(cls, chat):
logging.info("sending message to %d waiters", len(cls.waiters))
for waiter in cls.waiters:
try:
waiter.write_message(chat)
except:
logging.error("Error sending message", exc_info=True)
def on_message(self, message):
logging.info("got message %r", message)
parsed = tornado.escape.json_decode(message)
chat = {
"id": str(uuid.uuid4()),
"body": parsed["body"],
}
chat["html"] = tornado.escape.to_basestring(
self.render_string("message.html", message=chat))
ChatSocketHandler.update_cache(chat)
ChatSocketHandler.send_updates(chat)
def main():
tornado.options.parse_command_line()
app = Application()
app.listen(options.port)
tornado.ioloop.IOLoop.instance().start()
if __name__ == "__main__":
main()
| apache-2.0 |
ychen820/microblog | y/google-cloud-sdk/platform/google_appengine/lib/django-1.2/django/forms/widgets.py | 45 | 29994 | """
HTML Widget classes
"""
import django.utils.copycompat as copy
from itertools import chain
from django.conf import settings
from django.utils.datastructures import MultiValueDict, MergeDict
from django.utils.html import escape, conditional_escape
from django.utils.translation import ugettext
from django.utils.encoding import StrAndUnicode, force_unicode
from django.utils.safestring import mark_safe
from django.utils import datetime_safe, formats
import time
import datetime
from util import flatatt
from urlparse import urljoin
__all__ = (
'Media', 'MediaDefiningClass', 'Widget', 'TextInput', 'PasswordInput',
'HiddenInput', 'MultipleHiddenInput',
'FileInput', 'DateInput', 'DateTimeInput', 'TimeInput', 'Textarea', 'CheckboxInput',
'Select', 'NullBooleanSelect', 'SelectMultiple', 'RadioSelect',
'CheckboxSelectMultiple', 'MultiWidget',
'SplitDateTimeWidget',
)
MEDIA_TYPES = ('css','js')
class Media(StrAndUnicode):
def __init__(self, media=None, **kwargs):
if media:
media_attrs = media.__dict__
else:
media_attrs = kwargs
self._css = {}
self._js = []
for name in MEDIA_TYPES:
getattr(self, 'add_' + name)(media_attrs.get(name, None))
# Any leftover attributes must be invalid.
# if media_attrs != {}:
# raise TypeError("'class Media' has invalid attribute(s): %s" % ','.join(media_attrs.keys()))
def __unicode__(self):
return self.render()
def render(self):
return mark_safe(u'\n'.join(chain(*[getattr(self, 'render_' + name)() for name in MEDIA_TYPES])))
def render_js(self):
return [u'<script type="text/javascript" src="%s"></script>' % self.absolute_path(path) for path in self._js]
def render_css(self):
# To keep rendering order consistent, we can't just iterate over items().
# We need to sort the keys, and iterate over the sorted list.
media = self._css.keys()
media.sort()
return chain(*[
[u'<link href="%s" type="text/css" media="%s" rel="stylesheet" />' % (self.absolute_path(path), medium)
for path in self._css[medium]]
for medium in media])
def absolute_path(self, path):
if path.startswith(u'http://') or path.startswith(u'https://') or path.startswith(u'/'):
return path
return urljoin(settings.MEDIA_URL,path)
def __getitem__(self, name):
"Returns a Media object that only contains media of the given type"
if name in MEDIA_TYPES:
return Media(**{str(name): getattr(self, '_' + name)})
raise KeyError('Unknown media type "%s"' % name)
def add_js(self, data):
if data:
for path in data:
if path not in self._js:
self._js.append(path)
def add_css(self, data):
if data:
for medium, paths in data.items():
for path in paths:
if not self._css.get(medium) or path not in self._css[medium]:
self._css.setdefault(medium, []).append(path)
def __add__(self, other):
combined = Media()
for name in MEDIA_TYPES:
getattr(combined, 'add_' + name)(getattr(self, '_' + name, None))
getattr(combined, 'add_' + name)(getattr(other, '_' + name, None))
return combined
def media_property(cls):
def _media(self):
# Get the media property of the superclass, if it exists
if hasattr(super(cls, self), 'media'):
base = super(cls, self).media
else:
base = Media()
# Get the media definition for this class
definition = getattr(cls, 'Media', None)
if definition:
extend = getattr(definition, 'extend', True)
if extend:
if extend == True:
m = base
else:
m = Media()
for medium in extend:
m = m + base[medium]
return m + Media(definition)
else:
return Media(definition)
else:
return base
return property(_media)
class MediaDefiningClass(type):
"Metaclass for classes that can have media definitions"
def __new__(cls, name, bases, attrs):
new_class = super(MediaDefiningClass, cls).__new__(cls, name, bases,
attrs)
if 'media' not in attrs:
new_class.media = media_property(new_class)
return new_class
class Widget(object):
__metaclass__ = MediaDefiningClass
is_hidden = False # Determines whether this corresponds to an <input type="hidden">.
needs_multipart_form = False # Determines does this widget need multipart-encrypted form
is_localized = False
def __init__(self, attrs=None):
if attrs is not None:
self.attrs = attrs.copy()
else:
self.attrs = {}
def __deepcopy__(self, memo):
obj = copy.copy(self)
obj.attrs = self.attrs.copy()
memo[id(self)] = obj
return obj
def render(self, name, value, attrs=None):
"""
Returns this Widget rendered as HTML, as a Unicode string.
The 'value' given is not guaranteed to be valid input, so subclass
implementations should program defensively.
"""
raise NotImplementedError
def build_attrs(self, extra_attrs=None, **kwargs):
"Helper function for building an attribute dictionary."
attrs = dict(self.attrs, **kwargs)
if extra_attrs:
attrs.update(extra_attrs)
return attrs
def value_from_datadict(self, data, files, name):
"""
Given a dictionary of data and this widget's name, returns the value
of this widget. Returns None if it's not provided.
"""
return data.get(name, None)
def _has_changed(self, initial, data):
"""
Return True if data differs from initial.
"""
# For purposes of seeing whether something has changed, None is
# the same as an empty string, if the data or inital value we get
# is None, replace it w/ u''.
if data is None:
data_value = u''
else:
data_value = data
if initial is None:
initial_value = u''
else:
initial_value = initial
if force_unicode(initial_value) != force_unicode(data_value):
return True
return False
def id_for_label(self, id_):
"""
Returns the HTML ID attribute of this Widget for use by a <label>,
given the ID of the field. Returns None if no ID is available.
This hook is necessary because some widgets have multiple HTML
elements and, thus, multiple IDs. In that case, this method should
return an ID value that corresponds to the first ID in the widget's
tags.
"""
return id_
id_for_label = classmethod(id_for_label)
class Input(Widget):
"""
Base class for all <input> widgets (except type='checkbox' and
type='radio', which are special).
"""
input_type = None # Subclasses must define this.
def _format_value(self, value):
if self.is_localized:
return formats.localize_input(value)
return value
def render(self, name, value, attrs=None):
if value is None:
value = ''
final_attrs = self.build_attrs(attrs, type=self.input_type, name=name)
if value != '':
# Only add the 'value' attribute if a value is non-empty.
final_attrs['value'] = force_unicode(self._format_value(value))
return mark_safe(u'<input%s />' % flatatt(final_attrs))
class TextInput(Input):
input_type = 'text'
class PasswordInput(Input):
input_type = 'password'
def __init__(self, attrs=None, render_value=True):
super(PasswordInput, self).__init__(attrs)
self.render_value = render_value
def render(self, name, value, attrs=None):
if not self.render_value: value=None
return super(PasswordInput, self).render(name, value, attrs)
class HiddenInput(Input):
input_type = 'hidden'
is_hidden = True
class MultipleHiddenInput(HiddenInput):
"""
A widget that handles <input type="hidden"> for fields that have a list
of values.
"""
def __init__(self, attrs=None, choices=()):
super(MultipleHiddenInput, self).__init__(attrs)
# choices can be any iterable
self.choices = choices
def render(self, name, value, attrs=None, choices=()):
if value is None: value = []
final_attrs = self.build_attrs(attrs, type=self.input_type, name=name)
id_ = final_attrs.get('id', None)
inputs = []
for i, v in enumerate(value):
input_attrs = dict(value=force_unicode(v), **final_attrs)
if id_:
# An ID attribute was given. Add a numeric index as a suffix
# so that the inputs don't all have the same ID attribute.
input_attrs['id'] = '%s_%s' % (id_, i)
inputs.append(u'<input%s />' % flatatt(input_attrs))
return mark_safe(u'\n'.join(inputs))
def value_from_datadict(self, data, files, name):
if isinstance(data, (MultiValueDict, MergeDict)):
return data.getlist(name)
return data.get(name, None)
class FileInput(Input):
input_type = 'file'
needs_multipart_form = True
def render(self, name, value, attrs=None):
return super(FileInput, self).render(name, None, attrs=attrs)
def value_from_datadict(self, data, files, name):
"File widgets take data from FILES, not POST"
return files.get(name, None)
def _has_changed(self, initial, data):
if data is None:
return False
return True
class Textarea(Widget):
def __init__(self, attrs=None):
# The 'rows' and 'cols' attributes are required for HTML correctness.
default_attrs = {'cols': '40', 'rows': '10'}
if attrs:
default_attrs.update(attrs)
super(Textarea, self).__init__(default_attrs)
def render(self, name, value, attrs=None):
if value is None: value = ''
final_attrs = self.build_attrs(attrs, name=name)
return mark_safe(u'<textarea%s>%s</textarea>' % (flatatt(final_attrs),
conditional_escape(force_unicode(value))))
class DateInput(Input):
input_type = 'text'
format = '%Y-%m-%d' # '2006-10-25'
def __init__(self, attrs=None, format=None):
super(DateInput, self).__init__(attrs)
if format:
self.format = format
self.manual_format = True
else:
self.format = formats.get_format('DATE_INPUT_FORMATS')[0]
self.manual_format = False
def _format_value(self, value):
if self.is_localized and not self.manual_format:
return formats.localize_input(value)
elif hasattr(value, 'strftime'):
value = datetime_safe.new_date(value)
return value.strftime(self.format)
return value
def _has_changed(self, initial, data):
# If our field has show_hidden_initial=True, initial will be a string
# formatted by HiddenInput using formats.localize_input, which is not
# necessarily the format used for this widget. Attempt to convert it.
try:
input_format = formats.get_format('DATE_INPUT_FORMATS')[0]
initial = datetime.date(*time.strptime(initial, input_format)[:3])
except (TypeError, ValueError):
pass
return super(DateInput, self)._has_changed(self._format_value(initial), data)
class DateTimeInput(Input):
input_type = 'text'
format = '%Y-%m-%d %H:%M:%S' # '2006-10-25 14:30:59'
def __init__(self, attrs=None, format=None):
super(DateTimeInput, self).__init__(attrs)
if format:
self.format = format
self.manual_format = True
else:
self.format = formats.get_format('DATETIME_INPUT_FORMATS')[0]
self.manual_format = False
def _format_value(self, value):
if self.is_localized and not self.manual_format:
return formats.localize_input(value)
elif hasattr(value, 'strftime'):
value = datetime_safe.new_datetime(value)
return value.strftime(self.format)
return value
def _has_changed(self, initial, data):
# If our field has show_hidden_initial=True, initial will be a string
# formatted by HiddenInput using formats.localize_input, which is not
# necessarily the format used for this widget. Attempt to convert it.
try:
input_format = formats.get_format('DATETIME_INPUT_FORMATS')[0]
initial = datetime.datetime(*time.strptime(initial, input_format)[:6])
except (TypeError, ValueError):
pass
return super(DateTimeInput, self)._has_changed(self._format_value(initial), data)
class TimeInput(Input):
input_type = 'text'
format = '%H:%M:%S' # '14:30:59'
def __init__(self, attrs=None, format=None):
super(TimeInput, self).__init__(attrs)
if format:
self.format = format
self.manual_format = True
else:
self.format = formats.get_format('TIME_INPUT_FORMATS')[0]
self.manual_format = False
def _format_value(self, value):
if self.is_localized and not self.manual_format:
return formats.localize_input(value)
elif hasattr(value, 'strftime'):
return value.strftime(self.format)
return value
def _has_changed(self, initial, data):
# If our field has show_hidden_initial=True, initial will be a string
# formatted by HiddenInput using formats.localize_input, which is not
# necessarily the format used for this widget. Attempt to convert it.
try:
input_format = formats.get_format('TIME_INPUT_FORMATS')[0]
initial = datetime.time(*time.strptime(initial, input_format)[3:6])
except (TypeError, ValueError):
pass
return super(TimeInput, self)._has_changed(self._format_value(initial), data)
class CheckboxInput(Widget):
def __init__(self, attrs=None, check_test=bool):
super(CheckboxInput, self).__init__(attrs)
# check_test is a callable that takes a value and returns True
# if the checkbox should be checked for that value.
self.check_test = check_test
def render(self, name, value, attrs=None):
final_attrs = self.build_attrs(attrs, type='checkbox', name=name)
try:
result = self.check_test(value)
except: # Silently catch exceptions
result = False
if result:
final_attrs['checked'] = 'checked'
if value not in ('', True, False, None):
# Only add the 'value' attribute if a value is non-empty.
final_attrs['value'] = force_unicode(value)
return mark_safe(u'<input%s />' % flatatt(final_attrs))
def value_from_datadict(self, data, files, name):
if name not in data:
# A missing value means False because HTML form submission does not
# send results for unselected checkboxes.
return False
value = data.get(name)
# Translate true and false strings to boolean values.
values = {'true': True, 'false': False}
if isinstance(value, basestring):
value = values.get(value.lower(), value)
return value
def _has_changed(self, initial, data):
# Sometimes data or initial could be None or u'' which should be the
# same thing as False.
return bool(initial) != bool(data)
class Select(Widget):
def __init__(self, attrs=None, choices=()):
super(Select, self).__init__(attrs)
# choices can be any iterable, but we may need to render this widget
# multiple times. Thus, collapse it into a list so it can be consumed
# more than once.
self.choices = list(choices)
def render(self, name, value, attrs=None, choices=()):
if value is None: value = ''
final_attrs = self.build_attrs(attrs, name=name)
output = [u'<select%s>' % flatatt(final_attrs)]
options = self.render_options(choices, [value])
if options:
output.append(options)
output.append(u'</select>')
return mark_safe(u'\n'.join(output))
def render_option(self, selected_choices, option_value, option_label):
option_value = force_unicode(option_value)
selected_html = (option_value in selected_choices) and u' selected="selected"' or ''
return u'<option value="%s"%s>%s</option>' % (
escape(option_value), selected_html,
conditional_escape(force_unicode(option_label)))
def render_options(self, choices, selected_choices):
# Normalize to strings.
selected_choices = set([force_unicode(v) for v in selected_choices])
output = []
for option_value, option_label in chain(self.choices, choices):
if isinstance(option_label, (list, tuple)):
output.append(u'<optgroup label="%s">' % escape(force_unicode(option_value)))
for option in option_label:
output.append(self.render_option(selected_choices, *option))
output.append(u'</optgroup>')
else:
output.append(self.render_option(selected_choices, option_value, option_label))
return u'\n'.join(output)
class NullBooleanSelect(Select):
"""
A Select Widget intended to be used with NullBooleanField.
"""
def __init__(self, attrs=None):
choices = ((u'1', ugettext('Unknown')), (u'2', ugettext('Yes')), (u'3', ugettext('No')))
super(NullBooleanSelect, self).__init__(attrs, choices)
def render(self, name, value, attrs=None, choices=()):
try:
value = {True: u'2', False: u'3', u'2': u'2', u'3': u'3'}[value]
except KeyError:
value = u'1'
return super(NullBooleanSelect, self).render(name, value, attrs, choices)
def value_from_datadict(self, data, files, name):
value = data.get(name, None)
return {u'2': True,
True: True,
'True': True,
u'3': False,
'False': False,
False: False}.get(value, None)
def _has_changed(self, initial, data):
# For a NullBooleanSelect, None (unknown) and False (No)
# are not the same
if initial is not None:
initial = bool(initial)
if data is not None:
data = bool(data)
return initial != data
class SelectMultiple(Select):
def render(self, name, value, attrs=None, choices=()):
if value is None: value = []
final_attrs = self.build_attrs(attrs, name=name)
output = [u'<select multiple="multiple"%s>' % flatatt(final_attrs)]
options = self.render_options(choices, value)
if options:
output.append(options)
output.append('</select>')
return mark_safe(u'\n'.join(output))
def value_from_datadict(self, data, files, name):
if isinstance(data, (MultiValueDict, MergeDict)):
return data.getlist(name)
return data.get(name, None)
def _has_changed(self, initial, data):
if initial is None:
initial = []
if data is None:
data = []
if len(initial) != len(data):
return True
initial_set = set([force_unicode(value) for value in initial])
data_set = set([force_unicode(value) for value in data])
return data_set != initial_set
class RadioInput(StrAndUnicode):
"""
An object used by RadioFieldRenderer that represents a single
<input type='radio'>.
"""
def __init__(self, name, value, attrs, choice, index):
self.name, self.value = name, value
self.attrs = attrs
self.choice_value = force_unicode(choice[0])
self.choice_label = force_unicode(choice[1])
self.index = index
def __unicode__(self):
if 'id' in self.attrs:
label_for = ' for="%s_%s"' % (self.attrs['id'], self.index)
else:
label_for = ''
choice_label = conditional_escape(force_unicode(self.choice_label))
return mark_safe(u'<label%s>%s %s</label>' % (label_for, self.tag(), choice_label))
def is_checked(self):
return self.value == self.choice_value
def tag(self):
if 'id' in self.attrs:
self.attrs['id'] = '%s_%s' % (self.attrs['id'], self.index)
final_attrs = dict(self.attrs, type='radio', name=self.name, value=self.choice_value)
if self.is_checked():
final_attrs['checked'] = 'checked'
return mark_safe(u'<input%s />' % flatatt(final_attrs))
class RadioFieldRenderer(StrAndUnicode):
"""
An object used by RadioSelect to enable customization of radio widgets.
"""
def __init__(self, name, value, attrs, choices):
self.name, self.value, self.attrs = name, value, attrs
self.choices = choices
def __iter__(self):
for i, choice in enumerate(self.choices):
yield RadioInput(self.name, self.value, self.attrs.copy(), choice, i)
def __getitem__(self, idx):
choice = self.choices[idx] # Let the IndexError propogate
return RadioInput(self.name, self.value, self.attrs.copy(), choice, idx)
def __unicode__(self):
return self.render()
def render(self):
"""Outputs a <ul> for this set of radio fields."""
return mark_safe(u'<ul>\n%s\n</ul>' % u'\n'.join([u'<li>%s</li>'
% force_unicode(w) for w in self]))
class RadioSelect(Select):
renderer = RadioFieldRenderer
def __init__(self, *args, **kwargs):
# Override the default renderer if we were passed one.
renderer = kwargs.pop('renderer', None)
if renderer:
self.renderer = renderer
super(RadioSelect, self).__init__(*args, **kwargs)
def get_renderer(self, name, value, attrs=None, choices=()):
"""Returns an instance of the renderer."""
if value is None: value = ''
str_value = force_unicode(value) # Normalize to string.
final_attrs = self.build_attrs(attrs)
choices = list(chain(self.choices, choices))
return self.renderer(name, str_value, final_attrs, choices)
def render(self, name, value, attrs=None, choices=()):
return self.get_renderer(name, value, attrs, choices).render()
def id_for_label(self, id_):
# RadioSelect is represented by multiple <input type="radio"> fields,
# each of which has a distinct ID. The IDs are made distinct by a "_X"
# suffix, where X is the zero-based index of the radio field. Thus,
# the label for a RadioSelect should reference the first one ('_0').
if id_:
id_ += '_0'
return id_
id_for_label = classmethod(id_for_label)
class CheckboxSelectMultiple(SelectMultiple):
def render(self, name, value, attrs=None, choices=()):
if value is None: value = []
has_id = attrs and 'id' in attrs
final_attrs = self.build_attrs(attrs, name=name)
output = [u'<ul>']
# Normalize to strings
str_values = set([force_unicode(v) for v in value])
for i, (option_value, option_label) in enumerate(chain(self.choices, choices)):
# If an ID attribute was given, add a numeric index as a suffix,
# so that the checkboxes don't all have the same ID attribute.
if has_id:
final_attrs = dict(final_attrs, id='%s_%s' % (attrs['id'], i))
label_for = u' for="%s"' % final_attrs['id']
else:
label_for = ''
cb = CheckboxInput(final_attrs, check_test=lambda value: value in str_values)
option_value = force_unicode(option_value)
rendered_cb = cb.render(name, option_value)
option_label = conditional_escape(force_unicode(option_label))
output.append(u'<li><label%s>%s %s</label></li>' % (label_for, rendered_cb, option_label))
output.append(u'</ul>')
return mark_safe(u'\n'.join(output))
def id_for_label(self, id_):
# See the comment for RadioSelect.id_for_label()
if id_:
id_ += '_0'
return id_
id_for_label = classmethod(id_for_label)
class MultiWidget(Widget):
"""
A widget that is composed of multiple widgets.
Its render() method is different than other widgets', because it has to
figure out how to split a single value for display in multiple widgets.
The ``value`` argument can be one of two things:
* A list.
* A normal value (e.g., a string) that has been "compressed" from
a list of values.
In the second case -- i.e., if the value is NOT a list -- render() will
first "decompress" the value into a list before rendering it. It does so by
calling the decompress() method, which MultiWidget subclasses must
implement. This method takes a single "compressed" value and returns a
list.
When render() does its HTML rendering, each value in the list is rendered
with the corresponding widget -- the first value is rendered in the first
widget, the second value is rendered in the second widget, etc.
Subclasses may implement format_output(), which takes the list of rendered
widgets and returns a string of HTML that formats them any way you'd like.
You'll probably want to use this class with MultiValueField.
"""
def __init__(self, widgets, attrs=None):
self.widgets = [isinstance(w, type) and w() or w for w in widgets]
super(MultiWidget, self).__init__(attrs)
def render(self, name, value, attrs=None):
if self.is_localized:
for widget in self.widgets:
widget.is_localized = self.is_localized
# value is a list of values, each corresponding to a widget
# in self.widgets.
if not isinstance(value, list):
value = self.decompress(value)
output = []
final_attrs = self.build_attrs(attrs)
id_ = final_attrs.get('id', None)
for i, widget in enumerate(self.widgets):
try:
widget_value = value[i]
except IndexError:
widget_value = None
if id_:
final_attrs = dict(final_attrs, id='%s_%s' % (id_, i))
output.append(widget.render(name + '_%s' % i, widget_value, final_attrs))
return mark_safe(self.format_output(output))
def id_for_label(self, id_):
# See the comment for RadioSelect.id_for_label()
if id_:
id_ += '_0'
return id_
id_for_label = classmethod(id_for_label)
def value_from_datadict(self, data, files, name):
return [widget.value_from_datadict(data, files, name + '_%s' % i) for i, widget in enumerate(self.widgets)]
def _has_changed(self, initial, data):
if initial is None:
initial = [u'' for x in range(0, len(data))]
else:
if not isinstance(initial, list):
initial = self.decompress(initial)
for widget, initial, data in zip(self.widgets, initial, data):
if widget._has_changed(initial, data):
return True
return False
def format_output(self, rendered_widgets):
"""
Given a list of rendered widgets (as strings), returns a Unicode string
representing the HTML for the whole lot.
This hook allows you to format the HTML design of the widgets, if
needed.
"""
return u''.join(rendered_widgets)
def decompress(self, value):
"""
Returns a list of decompressed values for the given compressed value.
The given value can be assumed to be valid, but not necessarily
non-empty.
"""
raise NotImplementedError('Subclasses must implement this method.')
def _get_media(self):
"Media for a multiwidget is the combination of all media of the subwidgets"
media = Media()
for w in self.widgets:
media = media + w.media
return media
media = property(_get_media)
def __deepcopy__(self, memo):
obj = super(MultiWidget, self).__deepcopy__(memo)
obj.widgets = copy.deepcopy(self.widgets)
return obj
class SplitDateTimeWidget(MultiWidget):
"""
A Widget that splits datetime input into two <input type="text"> boxes.
"""
date_format = DateInput.format
time_format = TimeInput.format
def __init__(self, attrs=None, date_format=None, time_format=None):
widgets = (DateInput(attrs=attrs, format=date_format),
TimeInput(attrs=attrs, format=time_format))
super(SplitDateTimeWidget, self).__init__(widgets, attrs)
def decompress(self, value):
if value:
return [value.date(), value.time().replace(microsecond=0)]
return [None, None]
class SplitHiddenDateTimeWidget(SplitDateTimeWidget):
"""
A Widget that splits datetime input into two <input type="hidden"> inputs.
"""
is_hidden = True
def __init__(self, attrs=None, date_format=None, time_format=None):
super(SplitHiddenDateTimeWidget, self).__init__(attrs, date_format, time_format)
for widget in self.widgets:
widget.input_type = 'hidden'
widget.is_hidden = True
| bsd-3-clause |
maiklos-mirrors/jfx78 | modules/web/src/main/native/Tools/Scripts/webkitpy/tool/commands/perfalizer.py | 123 | 8751 | # Copyright (c) 2012 Google Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. 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.
import logging
from webkitpy.tool.bot.expectedfailures import ExpectedFailures
from webkitpy.tool.bot.irc_command import IRCCommand
from webkitpy.tool.bot.irc_command import Help
from webkitpy.tool.bot.irc_command import Hi
from webkitpy.tool.bot.irc_command import Restart
from webkitpy.tool.bot.ircbot import IRCBot
from webkitpy.tool.bot.patchanalysistask import PatchAnalysisTask, PatchAnalysisTaskDelegate, UnableToApplyPatch
from webkitpy.tool.bot.sheriff import Sheriff
from webkitpy.tool.commands.queues import AbstractQueue
from webkitpy.tool.commands.stepsequence import StepSequenceErrorHandler
_log = logging.getLogger(__name__)
class PerfalizerTask(PatchAnalysisTask):
def __init__(self, tool, patch, logger):
PatchAnalysisTask.__init__(self, self, patch)
self._port = tool.port_factory.get()
self._tool = tool
self._logger = logger
def _copy_build_product_without_patch(self):
filesystem = self._tool.filesystem
configuration = filesystem.basename(self._port._build_path())
self._build_directory = filesystem.dirname(self._port._build_path())
self._build_directory_without_patch = self._build_directory + 'WithoutPatch'
try:
filesystem.rmtree(self._build_directory_without_patch)
filesystem.copytree(filesystem.join(self._build_directory, configuration),
filesystem.join(self._build_directory_without_patch, configuration))
return True
except:
return False
def run(self):
if not self._patch.committer() and not self._patch.attacher().can_commit:
self._logger('The patch %d is not authorized by a commmitter' % self._patch.id())
return False
self._logger('Preparing to run performance tests for the attachment %d...' % self._patch.id())
if not self._clean() or not self._update():
return False
head_revision = self._tool.scm().head_svn_revision()
self._logger('Building WebKit at r%s without the patch' % head_revision)
if not self._build_without_patch():
return False
if not self._port.check_build(needs_http=False):
self._logger('Failed to build DumpRenderTree.')
return False
if not self._copy_build_product_without_patch():
self._logger('Failed to copy the build product from %s to %s' % (self._build_directory, self._build_directory_without_patch))
return False
self._logger('Building WebKit at r%s with the patch' % head_revision)
if not self._apply() or not self._build():
return False
if not self._port.check_build(needs_http=False):
self._logger('Failed to build DumpRenderTree.')
return False
filesystem = self._tool.filesystem
if filesystem.exists(self._json_path()):
filesystem.remove(self._json_path())
self._logger("Running performance tests...")
if self._run_perf_test(self._build_directory_without_patch, 'without %d' % self._patch.id()) < 0:
self._logger('Failed to run performance tests without the patch.')
return False
if self._run_perf_test(self._build_directory, 'with %d' % self._patch.id()) < 0:
self._logger('Failed to run performance tests with the patch.')
return False
if not filesystem.exists(self._results_page_path()):
self._logger('Failed to generate the results page.')
return False
results_page = filesystem.read_text_file(self._results_page_path())
self._tool.bugs.add_attachment_to_bug(self._patch.bug_id(), results_page,
description="Performance tests results for %d" % self._patch.id(), mimetype='text/html')
self._logger("Uploaded the results on the bug %d" % self._patch.bug_id())
return True
def parent_command(self):
return "perfalizer"
def run_webkit_patch(self, args):
webkit_patch_args = [self._tool.path()]
webkit_patch_args.extend(args)
return self._tool.executive.run_and_throw_if_fail(webkit_patch_args, cwd=self._tool.scm().checkout_root)
def _json_path(self):
return self._tool.filesystem.join(self._build_directory, 'PerformanceTestResults.json')
def _results_page_path(self):
return self._tool.filesystem.join(self._build_directory, 'PerformanceTestResults.html')
def _run_perf_test(self, build_path, description):
filesystem = self._tool.filesystem
script_path = filesystem.join(filesystem.dirname(self._tool.path()), 'run-perf-tests')
perf_test_runner_args = [script_path, '--no-build', '--no-show-results', '--build-directory', build_path,
'--output-json-path', self._json_path(), '--description', description]
return self._tool.executive.run_and_throw_if_fail(perf_test_runner_args, cwd=self._tool.scm().checkout_root)
def run_command(self, command):
self.run_webkit_patch(command)
def command_passed(self, message, patch):
pass
def command_failed(self, message, script_error, patch):
self._logger(message)
def refetch_patch(self, patch):
return self._tool.bugs.fetch_attachment(patch.id())
def expected_failures(self):
return ExpectedFailures()
def build_style(self):
return "release"
class PerfTest(IRCCommand):
def execute(self, nick, args, tool, sheriff):
if not args:
tool.irc().post(nick + ": Please specify an attachment/patch id")
return
patch_id = args[0]
patch = tool.bugs.fetch_attachment(patch_id)
if not patch:
tool.irc().post(nick + ": Could not fetch the patch")
return
task = PerfalizerTask(tool, patch, lambda message: tool.irc().post('%s: %s' % (nick, message)))
task.run()
class Perfalizer(AbstractQueue, StepSequenceErrorHandler):
name = "perfalizer"
watchers = AbstractQueue.watchers + ["[email protected]"]
_commands = {
"help": Help,
"hi": Hi,
"restart": Restart,
"test": PerfTest,
}
# AbstractQueue methods
def begin_work_queue(self):
AbstractQueue.begin_work_queue(self)
self._sheriff = Sheriff(self._tool, self)
self._irc_bot = IRCBot("perfalizer", self._tool, self._sheriff, self._commands)
self._tool.ensure_irc_connected(self._irc_bot.irc_delegate())
def work_item_log_path(self, failure_map):
return None
def _is_old_failure(self, revision):
return self._tool.status_server.svn_revision(revision)
def next_work_item(self):
self._irc_bot.process_pending_messages()
return
def process_work_item(self, failure_map):
return True
def handle_unexpected_error(self, failure_map, message):
_log.error(message)
# StepSequenceErrorHandler methods
@classmethod
def handle_script_error(cls, tool, state, script_error):
# Ideally we would post some information to IRC about what went wrong
# here, but we don't have the IRC password in the child process.
pass
| gpl-2.0 |
Techcable/TechBot | plugins/amazon.py | 12 | 3863 | import requests
import re
from bs4 import BeautifulSoup
from cloudbot import hook
from cloudbot.util import web, formatting, colors
SEARCH_URL = "http://www.amazon.{}/s/"
REGION = "com"
AMAZON_RE = re.compile(""".*ama?zo?n\.(com|co\.uk|com\.au|de|fr|ca|cn|es|it)/.*/(?:exec/obidos/ASIN/|o/|gp/product/|
(?:(?:[^"\'/]*)/)?dp/|)(B[A-Z0-9]{9})""", re.I)
# Feel free to set this to None or change it to your own ID.
# Or leave it in to support CloudBot, it's up to you!
AFFILIATE_TAG = "cloudbot-20"
@hook.regex(AMAZON_RE)
def amazon_url(match):
cc = match.group(1)
asin = match.group(2)
return amazon(asin, _parsed=cc)
@hook.command("amazon", "az")
def amazon(text, _parsed=False):
"""<query> -- Searches Amazon for query"""
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, '
'like Gecko) Chrome/41.0.2228.0 Safari/537.36',
'Referer': 'http://www.amazon.com/'
}
params = {
'url': 'search-alias',
'field-keywords': text.strip()
}
if _parsed:
# input is from a link parser, we need a specific URL
request = requests.get(SEARCH_URL.format(_parsed), params=params, headers=headers)
else:
request = requests.get(SEARCH_URL.format(REGION), params=params, headers=headers)
soup = BeautifulSoup(request.text)
# check if there are any results on the amazon page
results = soup.find('div', {'id': 'atfResults'})
if not results:
if not _parsed:
return "No results found."
else:
return
# get the first item from the results on the amazon page
results = results.find('ul', {'id': 's-results-list-atf'}).find_all('li', {'class': 's-result-item'})
item = results[0]
asin = item['data-asin']
# here we use dirty html scraping to get everything we need
title = formatting.truncate(item.find('h2', {'class': 's-access-title'}).text, 60)
tags = []
# tags!
if item.find('i', {'class': 'a-icon-prime'}):
tags.append("$(b)Prime$(b)")
if item.find('i', {'class': 'sx-bestseller-badge-primary'}):
tags.append("$(b)Bestseller$(b)")
# we use regex because we need to recognise text for this part
# the other parts detect based on html tags, not text
if re.search(r"(Kostenlose Lieferung|Livraison gratuite|FREE Shipping|EnvΓo GRATIS"
r"|Spedizione gratuita)", item.text, re.I):
tags.append("$(b)Free Shipping$(b)")
price = item.find('span', {'class': ['s-price', 'a-color-price']}).text
# use a whole lot of BS4 and regex to get the ratings
try:
# get the rating
rating = item.find('i', {'class': 'a-icon-star'}).find('span', {'class': 'a-icon-alt'}).text
rating = re.search(r"([0-9]+(?:(?:\.|,)[0-9])?).*5", rating).group(1).replace(",", ".")
# get the rating count
pattern = re.compile(r'(product-reviews|#customerReviews)')
num_ratings = item.find('a', {'href': pattern}).text.replace(".", ",")
# format the rating and count into a nice string
rating_str = "{}/5 stars ({} ratings)".format(rating, num_ratings)
except AttributeError:
rating_str = "No Ratings"
# generate a short url
if AFFILIATE_TAG:
url = "http://www.amazon.com/dp/" + asin + "/?tag=" + AFFILIATE_TAG
else:
url = "http://www.amazon.com/dp/" + asin + "/"
url = web.try_shorten(url)
# join all the tags into a string
tag_str = " - " + ", ".join(tags) if tags else ""
# finally, assemble everything into the final string, and return it!
if not _parsed:
return colors.parse("$(b){}$(b) ({}) - {}{} - {}".format(title, price, rating_str, tag_str, url))
else:
return colors.parse("$(b){}$(b) ({}) - {}{}".format(title, price, rating_str, tag_str))
| gpl-3.0 |
melgor/melgor.github.io | node_modules/pygmentize-bundled/vendor/pygments/build-3.3/pygments/lexers/foxpro.py | 335 | 26220 | # -*- coding: utf-8 -*-
"""
pygments.lexers.foxpro
~~~~~~~~~~~~~~~~~~~~~~
Simple lexer for Microsoft Visual FoxPro source code.
:copyright: Copyright 2006-2013 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
import re
from pygments.lexer import RegexLexer
from pygments.token import Punctuation, Text, Comment, Operator, Keyword, \
Name, String
__all__ = ['FoxProLexer']
class FoxProLexer(RegexLexer):
"""Lexer for Microsoft Visual FoxPro language.
FoxPro syntax allows to shorten all keywords and function names
to 4 characters. Shortened forms are not recognized by this lexer.
*New in Pygments 1.6.*
"""
name = 'FoxPro'
aliases = ['Clipper', 'XBase']
filenames = ['*.PRG', '*.prg']
mimetype = []
flags = re.IGNORECASE | re.MULTILINE
tokens = {
'root': [
(r';\s*\n', Punctuation), # consume newline
(r'(^|\n)\s*', Text, 'newline'),
# Square brackets may be used for array indices
# and for string literal. Look for arrays
# before matching string literals.
(r'(?<=\w)\[[0-9, ]+\]', Text),
(r'\'[^\'\n]*\'|"[^"\n]*"|\[[^]*]\]', String),
(r'(^\s*\*|&&|&&).*?\n', Comment.Single),
(r'(ABS|ACLASS|ACOPY|ACOS|ADATABASES|ADBOBJECTS|ADDBS|'
r'ADDPROPERTY|ADEL|ADIR|ADLLS|ADOCKSTATE|AELEMENT|AERROR|'
r'AEVENTS|AFIELDS|AFONT|AGETCLASS|AGETFILEVERSION|AINS|'
r'AINSTANCE|ALANGUAGE|ALEN|ALIAS|ALINES|ALLTRIM|'
r'AMEMBERS|AMOUSEOBJ|ANETRESOURCES|APRINTERS|APROCINFO|'
r'ASC|ASCAN|ASELOBJ|ASESSIONS|ASIN|ASORT|ASQLHANDLES|'
r'ASTACKINFO|ASUBSCRIPT|AT|AT_C|ATAGINFO|ATAN|ATC|ATCC|'
r'ATCLINE|ATLINE|ATN2|AUSED|AVCXCLASSES|BAR|BARCOUNT|'
r'BARPROMPT|BETWEEN|BINDEVENT|BINTOC|BITAND|BITCLEAR|'
r'BITLSHIFT|BITNOT|BITOR|BITRSHIFT|BITSET|BITTEST|BITXOR|'
r'BOF|CANDIDATE|CAPSLOCK|CAST|CDOW|CDX|CEILING|CHR|CHRSAW|'
r'CHRTRAN|CHRTRANC|CLEARRESULTSET|CMONTH|CNTBAR|CNTPAD|COL|'
r'COM|Functions|COMARRAY|COMCLASSINFO|COMPOBJ|COMPROP|'
r'COMRETURNERROR|COS|CPCONVERT|CPCURRENT|CPDBF|CREATEBINARY|'
r'CREATEOBJECT|CREATEOBJECTEX|CREATEOFFLINE|CTOBIN|CTOD|'
r'CTOT|CURDIR|CURSORGETPROP|CURSORSETPROP|CURSORTOXML|'
r'CURVAL|DATE|DATETIME|DAY|DBC|DBF|DBGETPROP|DBSETPROP|'
r'DBUSED|DDEAbortTrans|DDEAdvise|DDEEnabled|DDEExecute|'
r'DDEInitiate|DDELastError|DDEPoke|DDERequest|DDESetOption|'
r'DDESetService|DDESetTopic|DDETerminate|DEFAULTEXT|'
r'DELETED|DESCENDING|DIFFERENCE|DIRECTORY|DISKSPACE|'
r'DisplayPath|DMY|DODEFAULT|DOW|DRIVETYPE|DROPOFFLINE|'
r'DTOC|DTOR|DTOS|DTOT|EDITSOURCE|EMPTY|EOF|ERROR|EVAL(UATE)?|'
r'EVENTHANDLER|EVL|EXECSCRIPT|EXP|FCHSIZE|FCLOSE|FCOUNT|'
r'FCREATE|FDATE|FEOF|FERROR|FFLUSH|FGETS|FIELD|FILE|'
r'FILETOSTR|FILTER|FKLABEL|FKMAX|FLDLIST|FLOCK|FLOOR|'
r'FONTMETRIC|FOPEN|FOR|FORCEEXT|FORCEPATH|FOUND|FPUTS|'
r'FREAD|FSEEK|FSIZE|FTIME|FULLPATH|FV|FWRITE|'
r'GETAUTOINCVALUE|GETBAR|GETCOLOR|GETCP|GETDIR|GETENV|'
r'GETFILE|GETFLDSTATE|GETFONT|GETINTERFACE|'
r'GETNEXTMODIFIED|GETOBJECT|GETPAD|GETPEM|GETPICT|'
r'GETPRINTER|GETRESULTSET|GETWORDCOUNT|GETWORDNUM|'
r'GETCURSORADAPTER|GOMONTH|HEADER|HOME|HOUR|ICASE|'
r'IDXCOLLATE|IIF|IMESTATUS|INDBC|INDEXSEEK|INKEY|INLIST|'
r'INPUTBOX|INSMODE|INT|ISALPHA|ISBLANK|ISCOLOR|ISDIGIT|'
r'ISEXCLUSIVE|ISFLOCKED|ISLEADBYTE|ISLOWER|ISMEMOFETCHED|'
r'ISMOUSE|ISNULL|ISPEN|ISREADONLY|ISRLOCKED|'
r'ISTRANSACTABLE|ISUPPER|JUSTDRIVE|JUSTEXT|JUSTFNAME|'
r'JUSTPATH|JUSTSTEM|KEY|KEYMATCH|LASTKEY|LEFT|LEFTC|LEN|'
r'LENC|LIKE|LIKEC|LINENO|LOADPICTURE|LOCFILE|LOCK|LOG|'
r'LOG10|LOOKUP|LOWER|LTRIM|LUPDATE|MAKETRANSACTABLE|MAX|'
r'MCOL|MDOWN|MDX|MDY|MEMLINES|MEMORY|MENU|MESSAGE|'
r'MESSAGEBOX|MIN|MINUTE|MLINE|MOD|MONTH|MRKBAR|MRKPAD|'
r'MROW|MTON|MWINDOW|NDX|NEWOBJECT|NORMALIZE|NTOM|NUMLOCK|'
r'NVL|OBJNUM|OBJTOCLIENT|OBJVAR|OCCURS|OEMTOANSI|OLDVAL|'
r'ON|ORDER|OS|PAD|PADL|PARAMETERS|PAYMENT|PCOL|PCOUNT|'
r'PEMSTATUS|PI|POPUP|PRIMARY|PRINTSTATUS|PRMBAR|PRMPAD|'
r'PROGRAM|PROMPT|PROPER|PROW|PRTINFO|PUTFILE|PV|QUARTER|'
r'RAISEEVENT|RAND|RAT|RATC|RATLINE|RDLEVEL|READKEY|RECCOUNT|'
r'RECNO|RECSIZE|REFRESH|RELATION|REPLICATE|REQUERY|RGB|'
r'RGBSCHEME|RIGHT|RIGHTC|RLOCK|ROUND|ROW|RTOD|RTRIM|'
r'SAVEPICTURE|SCHEME|SCOLS|SEC|SECONDS|SEEK|SELECT|SET|'
r'SETFLDSTATE|SETRESULTSET|SIGN|SIN|SKPBAR|SKPPAD|SOUNDEX|'
r'SPACE|SQLCANCEL|SQLCOLUMNS|SQLCOMMIT|SQLCONNECT|'
r'SQLDISCONNECT|SQLEXEC|SQLGETPROP|SQLIDLEDISCONNECT|'
r'SQLMORERESULTS|SQLPREPARE|SQLROLLBACK|SQLSETPROP|'
r'SQLSTRINGCONNECT|SQLTABLES|SQRT|SROWS|STR|STRCONV|'
r'STREXTRACT|STRTOFILE|STRTRAN|STUFF|STUFFC|SUBSTR|'
r'SUBSTRC|SYS|SYSMETRIC|TABLEREVERT|TABLEUPDATE|TAG|'
r'TAGCOUNT|TAGNO|TAN|TARGET|TEXTMERGE|TIME|TRANSFORM|'
r'TRIM|TTOC|TTOD|TXNLEVEL|TXTWIDTH|TYPE|UNBINDEVENTS|'
r'UNIQUE|UPDATED|UPPER|USED|VAL|VARREAD|VARTYPE|VERSION|'
r'WBORDER|WCHILD|WCOLS|WDOCKABLE|WEEK|WEXIST|WFONT|WLAST|'
r'WLCOL|WLROW|WMAXIMUM|WMINIMUM|WONTOP|WOUTPUT|WPARENT|'
r'WREAD|WROWS|WTITLE|WVISIBLE|XMLTOCURSOR|XMLUPDATEGRAM|'
r'YEAR)(?=\s*\()', Name.Function),
(r'_ALIGNMENT|_ASCIICOLS|_ASCIIROWS|_ASSIST|_BEAUTIFY|_BOX|'
r'_BROWSER|_BUILDER|_CALCMEM|_CALCVALUE|_CLIPTEXT|_CONVERTER|'
r'_COVERAGE|_CUROBJ|_DBLCLICK|_DIARYDATE|_DOS|_FOXDOC|_FOXREF|'
r'_GALLERY|_GENGRAPH|_GENHTML|_GENMENU|_GENPD|_GENSCRN|'
r'_GENXTAB|_GETEXPR|_INCLUDE|_INCSEEK|_INDENT|_LMARGIN|_MAC|'
r'_MENUDESIGNER|_MLINE|_PADVANCE|_PAGENO|_PAGETOTAL|_PBPAGE|'
r'_PCOLNO|_PCOPIES|_PDRIVER|_PDSETUP|_PECODE|_PEJECT|_PEPAGE|'
r'_PLENGTH|_PLINENO|_PLOFFSET|_PPITCH|_PQUALITY|_PRETEXT|'
r'_PSCODE|_PSPACING|_PWAIT|_RMARGIN|_REPORTBUILDER|'
r'_REPORTOUTPUT|_REPORTPREVIEW|_SAMPLES|_SCCTEXT|_SCREEN|'
r'_SHELL|_SPELLCHK|_STARTUP|_TABS|_TALLY|_TASKPANE|_TEXT|'
r'_THROTTLE|_TOOLBOX|_TOOLTIPTIMEOUT|_TRANSPORT|_TRIGGERLEVEL|'
r'_UNIX|_VFP|_WINDOWS|_WIZARD|_WRAP', Keyword.Pseudo),
(r'THISFORMSET|THISFORM|THIS', Name.Builtin),
(r'Application|CheckBox|Collection|Column|ComboBox|'
r'CommandButton|CommandGroup|Container|Control|CursorAdapter|'
r'Cursor|Custom|DataEnvironment|DataObject|EditBox|'
r'Empty|Exception|Fields|Files|File|FormSet|Form|FoxCode|'
r'Grid|Header|Hyperlink|Image|Label|Line|ListBox|Objects|'
r'OptionButton|OptionGroup|PageFrame|Page|ProjectHook|Projects|'
r'Project|Relation|ReportListener|Separator|Servers|Server|'
r'Session|Shape|Spinner|Tables|TextBox|Timer|ToolBar|'
r'XMLAdapter|XMLField|XMLTable', Name.Class),
(r'm\.[a-z_]\w*', Name.Variable),
(r'\.(F|T|AND|OR|NOT|NULL)\.|\b(AND|OR|NOT|NULL)\b', Operator.Word),
(r'\.(ActiveColumn|ActiveControl|ActiveForm|ActivePage|'
r'ActiveProject|ActiveRow|AddLineFeeds|ADOCodePage|Alias|'
r'Alignment|Align|AllowAddNew|AllowAutoColumnFit|'
r'AllowCellSelection|AllowDelete|AllowHeaderSizing|'
r'AllowInsert|AllowModalMessages|AllowOutput|AllowRowSizing|'
r'AllowSimultaneousFetch|AllowTabs|AllowUpdate|'
r'AlwaysOnBottom|AlwaysOnTop|Anchor|Application|'
r'AutoActivate|AutoCenter|AutoCloseTables|AutoComplete|'
r'AutoCompSource|AutoCompTable|AutoHideScrollBar|'
r'AutoIncrement|AutoOpenTables|AutoRelease|AutoSize|'
r'AutoVerbMenu|AutoYield|BackColor|ForeColor|BackStyle|'
r'BaseClass|BatchUpdateCount|BindControls|BorderColor|'
r'BorderStyle|BorderWidth|BoundColumn|BoundTo|Bound|'
r'BreakOnError|BufferModeOverride|BufferMode|'
r'BuildDateTime|ButtonCount|Buttons|Cancel|Caption|'
r'Centered|Century|ChildAlias|ChildOrder|ChildTable|'
r'ClassLibrary|Class|ClipControls|Closable|CLSID|CodePage|'
r'ColorScheme|ColorSource|ColumnCount|ColumnLines|'
r'ColumnOrder|Columns|ColumnWidths|CommandClauses|'
r'Comment|CompareMemo|ConflictCheckCmd|ConflictCheckType|'
r'ContinuousScroll|ControlBox|ControlCount|Controls|'
r'ControlSource|ConversionFunc|Count|CurrentControl|'
r'CurrentDataSession|CurrentPass|CurrentX|CurrentY|'
r'CursorSchema|CursorSource|CursorStatus|Curvature|'
r'Database|DataSessionID|DataSession|DataSourceType|'
r'DataSource|DataType|DateFormat|DateMark|Debug|'
r'DeclareXMLPrefix|DEClassLibrary|DEClass|DefaultFilePath|'
r'Default|DefOLELCID|DeleteCmdDataSourceType|DeleteCmdDataSource|'
r'DeleteCmd|DeleteMark|Description|Desktop|'
r'Details|DisabledBackColor|DisabledForeColor|'
r'DisabledItemBackColor|DisabledItemForeColor|'
r'DisabledPicture|DisableEncode|DisplayCount|'
r'DisplayValue|Dockable|Docked|DockPosition|'
r'DocumentFile|DownPicture|DragIcon|DragMode|DrawMode|'
r'DrawStyle|DrawWidth|DynamicAlignment|DynamicBackColor|'
r'DynamicForeColor|DynamicCurrentControl|DynamicFontBold|'
r'DynamicFontItalic|DynamicFontStrikethru|'
r'DynamicFontUnderline|DynamicFontName|DynamicFontOutline|'
r'DynamicFontShadow|DynamicFontSize|DynamicInputMask|'
r'DynamicLineHeight|EditorOptions|Enabled|'
r'EnableHyperlinks|Encrypted|ErrorNo|Exclude|Exclusive|'
r'FetchAsNeeded|FetchMemoCmdList|FetchMemoDataSourceType|'
r'FetchMemoDataSource|FetchMemo|FetchSize|'
r'FileClassLibrary|FileClass|FillColor|FillStyle|Filter|'
r'FirstElement|FirstNestedTable|Flags|FontBold|FontItalic|'
r'FontStrikethru|FontUnderline|FontCharSet|FontCondense|'
r'FontExtend|FontName|FontOutline|FontShadow|FontSize|'
r'ForceCloseTag|Format|FormCount|FormattedOutput|Forms|'
r'FractionDigits|FRXDataSession|FullName|GDIPlusGraphics|'
r'GridLineColor|GridLines|GridLineWidth|HalfHeightCaption|'
r'HeaderClassLibrary|HeaderClass|HeaderHeight|Height|'
r'HelpContextID|HideSelection|HighlightBackColor|'
r'HighlightForeColor|HighlightStyle|HighlightRowLineWidth|'
r'HighlightRow|Highlight|HomeDir|Hours|HostName|'
r'HScrollSmallChange|hWnd|Icon|IncrementalSearch|Increment|'
r'InitialSelectedAlias|InputMask|InsertCmdDataSourceType|'
r'InsertCmdDataSource|InsertCmdRefreshCmd|'
r'InsertCmdRefreshFieldList|InsertCmdRefreshKeyFieldList|'
r'InsertCmd|Instancing|IntegralHeight|'
r'Interval|IMEMode|IsAttribute|IsBase64|IsBinary|IsNull|'
r'IsDiffGram|IsLoaded|ItemBackColor,|ItemData|ItemIDData|'
r'ItemTips|IXMLDOMElement|KeyboardHighValue|KeyboardLowValue|'
r'Keyfield|KeyFieldList|KeyPreview|KeySort|LanguageOptions|'
r'LeftColumn|Left|LineContents|LineNo|LineSlant|LinkMaster|'
r'ListCount|ListenerType|ListIndex|ListItemID|ListItem|'
r'List|LockColumnsLeft|LockColumns|LockScreen|MacDesktop|'
r'MainFile|MapN19_4ToCurrency|MapBinary|MapVarchar|Margin|'
r'MaxButton|MaxHeight|MaxLeft|MaxLength|MaxRecords|MaxTop|'
r'MaxWidth|MDIForm|MemberClassLibrary|MemberClass|'
r'MemoWindow|Message|MinButton|MinHeight|MinWidth|'
r'MouseIcon|MousePointer|Movable|MoverBars|MultiSelect|'
r'Name|NestedInto|NewIndex|NewItemID|NextSiblingTable|'
r'NoCpTrans|NoDataOnLoad|NoData|NullDisplay|'
r'NumberOfElements|Object|OLEClass|OLEDragMode|'
r'OLEDragPicture|OLEDropEffects|OLEDropHasData|'
r'OLEDropMode|OLEDropTextInsertion|OLELCID|'
r'OLERequestPendingTimeout|OLEServerBusyRaiseError|'
r'OLEServerBusyTimeout|OLETypeAllowed|OneToMany|'
r'OpenViews|OpenWindow|Optimize|OrderDirection|Order|'
r'OutputPageCount|OutputType|PageCount|PageHeight|'
r'PageNo|PageOrder|Pages|PageTotal|PageWidth|'
r'PanelLink|Panel|ParentAlias|ParentClass|ParentTable|'
r'Parent|Partition|PasswordChar|PictureMargin|'
r'PicturePosition|PictureSpacing|PictureSelectionDisplay|'
r'PictureVal|Picture|Prepared|'
r'PolyPoints|PreserveWhiteSpace|PreviewContainer|'
r'PrintJobName|Procedure|PROCESSID|ProgID|ProjectHookClass|'
r'ProjectHookLibrary|ProjectHook|QuietMode|'
r'ReadCycle|ReadLock|ReadMouse|ReadObject|ReadOnly|'
r'ReadSave|ReadTimeout|RecordMark|RecordSourceType|'
r'RecordSource|RefreshAlias|'
r'RefreshCmdDataSourceType|RefreshCmdDataSource|RefreshCmd|'
r'RefreshIgnoreFieldList|RefreshTimeStamp|RelationalExpr|'
r'RelativeColumn|RelativeRow|ReleaseType|Resizable|'
r'RespectCursorCP|RespectNesting|RightToLeft|RotateFlip|'
r'Rotation|RowColChange|RowHeight|RowSourceType|'
r'RowSource|ScaleMode|SCCProvider|SCCStatus|ScrollBars|'
r'Seconds|SelectCmd|SelectedID|'
r'SelectedItemBackColor|SelectedItemForeColor|Selected|'
r'SelectionNamespaces|SelectOnEntry|SelLength|SelStart|'
r'SelText|SendGDIPlusImage|SendUpdates|ServerClassLibrary|'
r'ServerClass|ServerHelpFile|ServerName|'
r'ServerProject|ShowTips|ShowInTaskbar|ShowWindow|'
r'Sizable|SizeBox|SOM|Sorted|Sparse|SpecialEffect|'
r'SpinnerHighValue|SpinnerLowValue|SplitBar|StackLevel|'
r'StartMode|StatusBarText|StatusBar|Stretch|StrictDateEntry|'
r'Style|TabIndex|Tables|TabOrientation|Tabs|TabStop|'
r'TabStretch|TabStyle|Tag|TerminateRead|Text|Themes|'
r'ThreadID|TimestampFieldList|TitleBar|ToolTipText|'
r'TopIndex|TopItemID|Top|TwoPassProcess|TypeLibCLSID|'
r'TypeLibDesc|TypeLibName|Type|Unicode|UpdatableFieldList|'
r'UpdateCmdDataSourceType|UpdateCmdDataSource|'
r'UpdateCmdRefreshCmd|UpdateCmdRefreshFieldList|'
r'UpdateCmdRefreshKeyFieldList|UpdateCmd|'
r'UpdateGramSchemaLocation|UpdateGram|UpdateNameList|UpdateType|'
r'UseCodePage|UseCursorSchema|UseDeDataSource|UseMemoSize|'
r'UserValue|UseTransactions|UTF8Encoded|Value|VersionComments|'
r'VersionCompany|VersionCopyright|VersionDescription|'
r'VersionNumber|VersionProduct|VersionTrademarks|Version|'
r'VFPXMLProgID|ViewPortHeight|ViewPortLeft|'
r'ViewPortTop|ViewPortWidth|VScrollSmallChange|View|Visible|'
r'VisualEffect|WhatsThisButton|WhatsThisHelpID|WhatsThisHelp|'
r'WhereType|Width|WindowList|WindowState|WindowType|WordWrap|'
r'WrapCharInCDATA|WrapInCDATA|WrapMemoInCDATA|XMLAdapter|'
r'XMLConstraints|XMLNameIsXPath|XMLNamespace|XMLName|'
r'XMLPrefix|XMLSchemaLocation|XMLTable|XMLType|'
r'XSDfractionDigits|XSDmaxLength|XSDtotalDigits|'
r'XSDtype|ZoomBox)', Name.Attribute),
(r'\.(ActivateCell|AddColumn|AddItem|AddListItem|AddObject|'
r'AddProperty|AddTableSchema|AddToSCC|Add|'
r'ApplyDiffgram|Attach|AutoFit|AutoOpen|Box|Build|'
r'CancelReport|ChangesToCursor|CheckIn|CheckOut|Circle|'
r'CleanUp|ClearData|ClearStatus|Clear|CloneObject|CloseTables|'
r'Close|Cls|CursorAttach|CursorDetach|CursorFill|'
r'CursorRefresh|DataToClip|DelayedMemoFetch|DeleteColumn|'
r'Dock|DoMessage|DoScroll|DoStatus|DoVerb|Drag|Draw|Eval|'
r'GetData|GetDockState|GetFormat|GetKey|GetLatestVersion|'
r'GetPageHeight|GetPageWidth|Help|Hide|IncludePageInOutput|'
r'IndexToItemID|ItemIDToIndex|Item|LoadXML|Line|Modify|'
r'MoveItem|Move|Nest|OLEDrag|OnPreviewClose|OutputPage|'
r'Point|Print|PSet|Quit|ReadExpression|ReadMethod|'
r'RecordRefresh|Refresh|ReleaseXML|Release|RemoveFromSCC|'
r'RemoveItem|RemoveListItem|RemoveObject|Remove|'
r'Render|Requery|RequestData|ResetToDefault|Reset|Run|'
r'SaveAsClass|SaveAs|SetAll|SetData|SetFocus|SetFormat|'
r'SetMain|SetVar|SetViewPort|ShowWhatsThis|Show|'
r'SupportsListenerType|TextHeight|TextWidth|ToCursor|'
r'ToXML|UndoCheckOut|Unnest|UpdateStatus|WhatsThisMode|'
r'WriteExpression|WriteMethod|ZOrder)', Name.Function),
(r'\.(Activate|AdjustObjectSize|AfterBand|AfterBuild|'
r'AfterCloseTables|AfterCursorAttach|AfterCursorClose|'
r'AfterCursorDetach|AfterCursorFill|AfterCursorRefresh|'
r'AfterCursorUpdate|AfterDelete|AfterInsert|'
r'AfterRecordRefresh|AfterUpdate|AfterDock|AfterReport|'
r'AfterRowColChange|BeforeBand|BeforeCursorAttach|'
r'BeforeCursorClose|BeforeCursorDetach|BeforeCursorFill|'
r'BeforeCursorRefresh|BeforeCursorUpdate|BeforeDelete|'
r'BeforeInsert|BeforeDock|BeforeOpenTables|'
r'BeforeRecordRefresh|BeforeReport|BeforeRowColChange|'
r'BeforeUpdate|Click|dbc_Activate|dbc_AfterAddTable|'
r'dbc_AfterAppendProc|dbc_AfterCloseTable|dbc_AfterCopyProc|'
r'dbc_AfterCreateConnection|dbc_AfterCreateOffline|'
r'dbc_AfterCreateTable|dbc_AfterCreateView|dbc_AfterDBGetProp|'
r'dbc_AfterDBSetProp|dbc_AfterDeleteConnection|'
r'dbc_AfterDropOffline|dbc_AfterDropTable|'
r'dbc_AfterModifyConnection|dbc_AfterModifyProc|'
r'dbc_AfterModifyTable|dbc_AfterModifyView|dbc_AfterOpenTable|'
r'dbc_AfterRemoveTable|dbc_AfterRenameConnection|'
r'dbc_AfterRenameTable|dbc_AfterRenameView|'
r'dbc_AfterValidateData|dbc_BeforeAddTable|'
r'dbc_BeforeAppendProc|dbc_BeforeCloseTable|'
r'dbc_BeforeCopyProc|dbc_BeforeCreateConnection|'
r'dbc_BeforeCreateOffline|dbc_BeforeCreateTable|'
r'dbc_BeforeCreateView|dbc_BeforeDBGetProp|'
r'dbc_BeforeDBSetProp|dbc_BeforeDeleteConnection|'
r'dbc_BeforeDropOffline|dbc_BeforeDropTable|'
r'dbc_BeforeModifyConnection|dbc_BeforeModifyProc|'
r'dbc_BeforeModifyTable|dbc_BeforeModifyView|'
r'dbc_BeforeOpenTable|dbc_BeforeRemoveTable|'
r'dbc_BeforeRenameConnection|dbc_BeforeRenameTable|'
r'dbc_BeforeRenameView|dbc_BeforeValidateData|'
r'dbc_CloseData|dbc_Deactivate|dbc_ModifyData|dbc_OpenData|'
r'dbc_PackData|DblClick|Deactivate|Deleted|Destroy|DoCmd|'
r'DownClick|DragDrop|DragOver|DropDown|ErrorMessage|Error|'
r'EvaluateContents|GotFocus|Init|InteractiveChange|KeyPress|'
r'LoadReport|Load|LostFocus|Message|MiddleClick|MouseDown|'
r'MouseEnter|MouseLeave|MouseMove|MouseUp|MouseWheel|Moved|'
r'OLECompleteDrag|OLEDragOver|OLEGiveFeedback|OLESetData|'
r'OLEStartDrag|OnMoveItem|Paint|ProgrammaticChange|'
r'QueryAddFile|QueryModifyFile|QueryNewFile|QueryRemoveFile|'
r'QueryRunFile|QueryUnload|RangeHigh|RangeLow|ReadActivate|'
r'ReadDeactivate|ReadShow|ReadValid|ReadWhen|Resize|'
r'RightClick|SCCInit|SCCDestroy|Scrolled|Timer|UIEnable|'
r'UnDock|UnloadReport|Unload|UpClick|Valid|When)', Name.Function),
(r'\s+', Text),
# everything else is not colored
(r'.', Text),
],
'newline': [
(r'\*.*?$', Comment.Single, '#pop'),
(r'(ACCEPT|ACTIVATE\s*MENU|ACTIVATE\s*POPUP|ACTIVATE\s*SCREEN|'
r'ACTIVATE\s*WINDOW|APPEND|APPEND\s*FROM|APPEND\s*FROM\s*ARRAY|'
r'APPEND\s*GENERAL|APPEND\s*MEMO|ASSIST|AVERAGE|BLANK|BROWSE|'
r'BUILD\s*APP|BUILD\s*EXE|BUILD\s*PROJECT|CALCULATE|CALL|'
r'CANCEL|CHANGE|CLEAR|CLOSE|CLOSE\s*MEMO|COMPILE|CONTINUE|'
r'COPY\s*FILE|COPY\s*INDEXES|COPY\s*MEMO|COPY\s*STRUCTURE|'
r'COPY\s*STRUCTURE\s*EXTENDED|COPY\s*TAG|COPY\s*TO|'
r'COPY\s*TO\s*ARRAY|COUNT|CREATE|CREATE\s*COLOR\s*SET|'
r'CREATE\s*CURSOR|CREATE\s*FROM|CREATE\s*LABEL|CREATE\s*MENU|'
r'CREATE\s*PROJECT|CREATE\s*QUERY|CREATE\s*REPORT|'
r'CREATE\s*SCREEN|CREATE\s*TABLE|CREATE\s*VIEW|DDE|'
r'DEACTIVATE\s*MENU|DEACTIVATE\s*POPUP|DEACTIVATE\s*WINDOW|'
r'DECLARE|DEFINE\s*BAR|DEFINE\s*BOX|DEFINE\s*MENU|'
r'DEFINE\s*PAD|DEFINE\s*POPUP|DEFINE\s*WINDOW|DELETE|'
r'DELETE\s*FILE|DELETE\s*TAG|DIMENSION|DIRECTORY|DISPLAY|'
r'DISPLAY\s*FILES|DISPLAY\s*MEMORY|DISPLAY\s*STATUS|'
r'DISPLAY\s*STRUCTURE|DO|EDIT|EJECT|EJECT\s*PAGE|ERASE|'
r'EXIT|EXPORT|EXTERNAL|FILER|FIND|FLUSH|FUNCTION|GATHER|'
r'GETEXPR|GO|GOTO|HELP|HIDE\s*MENU|HIDE\s*POPUP|'
r'HIDE\s*WINDOW|IMPORT|INDEX|INPUT|INSERT|JOIN|KEYBOARD|'
r'LABEL|LIST|LOAD|LOCATE|LOOP|MENU|MENU\s*TO|MODIFY\s*COMMAND|'
r'MODIFY\s*FILE|MODIFY\s*GENERAL|MODIFY\s*LABEL|MODIFY\s*MEMO|'
r'MODIFY\s*MENU|MODIFY\s*PROJECT|MODIFY\s*QUERY|'
r'MODIFY\s*REPORT|MODIFY\s*SCREEN|MODIFY\s*STRUCTURE|'
r'MODIFY\s*WINDOW|MOVE\s*POPUP|MOVE\s*WINDOW|NOTE|'
r'ON\s*APLABOUT|ON\s*BAR|ON\s*ERROR|ON\s*ESCAPE|'
r'ON\s*EXIT\s*BAR|ON\s*EXIT\s*MENU|ON\s*EXIT\s*PAD|'
r'ON\s*EXIT\s*POPUP|ON\s*KEY|ON\s*KEY\s*=|ON\s*KEY\s*LABEL|'
r'ON\s*MACHELP|ON\s*PAD|ON\s*PAGE|ON\s*READERROR|'
r'ON\s*SELECTION\s*BAR|ON\s*SELECTION\s*MENU|'
r'ON\s*SELECTION\s*PAD|ON\s*SELECTION\s*POPUP|ON\s*SHUTDOWN|'
r'PACK|PARAMETERS|PLAY\s*MACRO|POP\s*KEY|POP\s*MENU|'
r'POP\s*POPUP|PRIVATE|PROCEDURE|PUBLIC|PUSH\s*KEY|'
r'PUSH\s*MENU|PUSH\s*POPUP|QUIT|READ|READ\s*MENU|RECALL|'
r'REINDEX|RELEASE|RELEASE\s*MODULE|RENAME|REPLACE|'
r'REPLACE\s*FROM\s*ARRAY|REPORT|RESTORE\s*FROM|'
r'RESTORE\s*MACROS|RESTORE\s*SCREEN|RESTORE\s*WINDOW|'
r'RESUME|RETRY|RETURN|RUN|RUN\s*\/N"|RUNSCRIPT|'
r'SAVE\s*MACROS|SAVE\s*SCREEN|SAVE\s*TO|SAVE\s*WINDOWS|'
r'SCATTER|SCROLL|SEEK|SELECT|SET|SET\s*ALTERNATE|'
r'SET\s*ANSI|SET\s*APLABOUT|SET\s*AUTOSAVE|SET\s*BELL|'
r'SET\s*BLINK|SET\s*BLOCKSIZE|SET\s*BORDER|SET\s*BRSTATUS|'
r'SET\s*CARRY|SET\s*CENTURY|SET\s*CLEAR|SET\s*CLOCK|'
r'SET\s*COLLATE|SET\s*COLOR\s*OF|SET\s*COLOR\s*OF\s*SCHEME|'
r'SET\s*COLOR\s*SET|SET\s*COLOR\s*TO|SET\s*COMPATIBLE|'
r'SET\s*CONFIRM|SET\s*CONSOLE|SET\s*CURRENCY|SET\s*CURSOR|'
r'SET\s*DATE|SET\s*DEBUG|SET\s*DECIMALS|SET\s*DEFAULT|'
r'SET\s*DELETED|SET\s*DELIMITERS|SET\s*DEVELOPMENT|'
r'SET\s*DEVICE|SET\s*DISPLAY|SET\s*DOHISTORY|SET\s*ECHO|'
r'SET\s*ESCAPE|SET\s*EXACT|SET\s*EXCLUSIVE|SET\s*FIELDS|'
r'SET\s*FILTER|SET\s*FIXED|SET\s*FORMAT|SET\s*FULLPATH|'
r'SET\s*FUNCTION|SET\s*HEADINGS|SET\s*HELP|SET\s*HELPFILTER|'
r'SET\s*HOURS|SET\s*INDEX|SET\s*INTENSITY|SET\s*KEY|'
r'SET\s*KEYCOMP|SET\s*LIBRARY|SET\s*LOCK|SET\s*LOGERRORS|'
r'SET\s*MACDESKTOP|SET\s*MACHELP|SET\s*MACKEY|SET\s*MARGIN|'
r'SET\s*MARK\s*OF|SET\s*MARK\s*TO|SET\s*MEMOWIDTH|'
r'SET\s*MESSAGE|SET\s*MOUSE|SET\s*MULTILOCKS|SET\s*NEAR|'
r'SET\s*NOCPTRANS|SET\s*NOTIFY|SET\s*ODOMETER|SET\s*OPTIMIZE|'
r'SET\s*ORDER|SET\s*PALETTE|SET\s*PATH|SET\s*PDSETUP|'
r'SET\s*POINT|SET\s*PRINTER|SET\s*PROCEDURE|SET\s*READBORDER|'
r'SET\s*REFRESH|SET\s*RELATION|SET\s*RELATION\s*OFF|'
r'SET\s*REPROCESS|SET\s*RESOURCE|SET\s*SAFETY|SET\s*SCOREBOARD|'
r'SET\s*SEPARATOR|SET\s*SHADOWS|SET\s*SKIP|SET\s*SKIP\s*OF|'
r'SET\s*SPACE|SET\s*STATUS|SET\s*STATUS\s*BAR|SET\s*STEP|'
r'SET\s*STICKY|SET\s*SYSMENU|SET\s*TALK|SET\s*TEXTMERGE|'
r'SET\s*TEXTMERGE\s*DELIMITERS|SET\s*TOPIC|SET\s*TRBETWEEN|'
r'SET\s*TYPEAHEAD|SET\s*UDFPARMS|SET\s*UNIQUE|SET\s*VIEW|'
r'SET\s*VOLUME|SET\s*WINDOW\s*OF\s*MEMO|SET\s*XCMDFILE|'
r'SHOW\s*GET|SHOW\s*GETS|SHOW\s*MENU|SHOW\s*OBJECT|'
r'SHOW\s*POPUP|SHOW\s*WINDOW|SIZE\s*POPUP|SKIP|SORT|'
r'STORE|SUM|SUSPEND|TOTAL|TYPE|UNLOCK|UPDATE|USE|WAIT|'
r'ZAP|ZOOM\s*WINDOW|DO\s*CASE|CASE|OTHERWISE|ENDCASE|'
r'DO\s*WHILE|ENDDO|FOR|ENDFOR|NEXT|IF|ELSE|ENDIF|PRINTJOB|'
r'ENDPRINTJOB|SCAN|ENDSCAN|TEXT|ENDTEXT|=)',
Keyword.Reserved, '#pop'),
(r'#\s*(IF|ELIF|ELSE|ENDIF|DEFINE|IFDEF|IFNDEF|INCLUDE)',
Comment.Preproc, '#pop'),
(r'(m\.)?[a-z_]\w*', Name.Variable, '#pop'),
(r'.', Text, '#pop'),
],
}
| mit |
tmerr/bank_wrangler | bank_wrangler/bank/fidelity.py | 1 | 2374 | """
Uses OFX to fetch a 3 month window of transactions from Fidelity.
Other possibibilities:
* Download and parse statement PDFs.
Last 10 years are available, 1 month at a time.
* Download CSVs from Portfolio > Activity & Orders > History > Download.
Last 5 years are available, 3 months at a time.
"""
from io import BytesIO
from decimal import Decimal
from bank_wrangler.config import ConfigField
from bank_wrangler import schema
from bank_wrangler.bank.common import correct_balance
from ofxtools.Client import OFXClient, InvStmtRq
from ofxtools.Parser import OFXTree
def name():
return 'Fidelity'
def empty_config():
return [
ConfigField(False, 'Username', None),
ConfigField(True, 'Password', None),
ConfigField(False, 'Account IDs (Comma Delimited)', None)
]
def fetch(config, fileobj):
username, password, accts = config
client = OFXClient(
'https://ofx.fidelity.com/ftgw/OFX/clients/download',
userid=username.value,
org='fidelity.com', fid='7776', brokerid='fidelity.com')
accts = accts.value.split(',')
resp = client.request_statements(
password.value,
*[InvStmtRq(acctid=acct) for acct in accts])
fileobj.write(resp.read().decode())
def _networth(statement):
for bal in statement.ballist:
if bal.name == 'Networth':
return Decimal(bal.value)
raise ValueError('could not find net worth of {}'.format(statement))
def _statement_transactions(st):
result = []
acctname = str(st.invacctfrom.acctid)
for t in st.transactions:
if hasattr(t, 'total'):
# ignore investment buy/sell
continue
amount = t.trnamt
frm, to = '', acctname
if amount < 0:
frm, to = to, frm
amount *= -1
result.append(schema.Transaction(
frm,
to,
schema.Date(t.dtposted.year, t.dtposted.month, t.dtposted.day),
str(t.memo),
Decimal(amount),
))
net = _networth(st)
correct_balance(acctname, net, result)
return result
def transactions_by_account(fileobj):
parser = OFXTree()
parser.parse(fileobj.buffer)
ofx = parser.convert()
result = {}
for st in ofx.statements:
result[str(st.invacctfrom.acctid)] = _statement_transactions(st)
return result
| gpl-3.0 |
alajara/servo | tests/wpt/web-platform-tests/tools/html5lib/html5lib/trie/datrie.py | 785 | 1166 | from __future__ import absolute_import, division, unicode_literals
from datrie import Trie as DATrie
from six import text_type
from ._base import Trie as ABCTrie
class Trie(ABCTrie):
def __init__(self, data):
chars = set()
for key in data.keys():
if not isinstance(key, text_type):
raise TypeError("All keys must be strings")
for char in key:
chars.add(char)
self._data = DATrie("".join(chars))
for key, value in data.items():
self._data[key] = value
def __contains__(self, key):
return key in self._data
def __len__(self):
return len(self._data)
def __iter__(self):
raise NotImplementedError()
def __getitem__(self, key):
return self._data[key]
def keys(self, prefix=None):
return self._data.keys(prefix)
def has_keys_with_prefix(self, prefix):
return self._data.has_keys_with_prefix(prefix)
def longest_prefix(self, prefix):
return self._data.longest_prefix(prefix)
def longest_prefix_item(self, prefix):
return self._data.longest_prefix_item(prefix)
| mpl-2.0 |
40223137/2015cd_midterm | static/Brython3.1.1-20150328-091302/Lib/xml/sax/xmlreader.py | 824 | 12612 | """An XML Reader is the SAX 2 name for an XML parser. XML Parsers
should be based on this code. """
from . import handler
from ._exceptions import SAXNotSupportedException, SAXNotRecognizedException
# ===== XMLREADER =====
class XMLReader:
"""Interface for reading an XML document using callbacks.
XMLReader is the interface that an XML parser's SAX2 driver must
implement. This interface allows an application to set and query
features and properties in the parser, to register event handlers
for document processing, and to initiate a document parse.
All SAX interfaces are assumed to be synchronous: the parse
methods must not return until parsing is complete, and readers
must wait for an event-handler callback to return before reporting
the next event."""
def __init__(self):
self._cont_handler = handler.ContentHandler()
self._dtd_handler = handler.DTDHandler()
self._ent_handler = handler.EntityResolver()
self._err_handler = handler.ErrorHandler()
def parse(self, source):
"Parse an XML document from a system identifier or an InputSource."
raise NotImplementedError("This method must be implemented!")
def getContentHandler(self):
"Returns the current ContentHandler."
return self._cont_handler
def setContentHandler(self, handler):
"Registers a new object to receive document content events."
self._cont_handler = handler
def getDTDHandler(self):
"Returns the current DTD handler."
return self._dtd_handler
def setDTDHandler(self, handler):
"Register an object to receive basic DTD-related events."
self._dtd_handler = handler
def getEntityResolver(self):
"Returns the current EntityResolver."
return self._ent_handler
def setEntityResolver(self, resolver):
"Register an object to resolve external entities."
self._ent_handler = resolver
def getErrorHandler(self):
"Returns the current ErrorHandler."
return self._err_handler
def setErrorHandler(self, handler):
"Register an object to receive error-message events."
self._err_handler = handler
def setLocale(self, locale):
"""Allow an application to set the locale for errors and warnings.
SAX parsers are not required to provide localization for errors
and warnings; if they cannot support the requested locale,
however, they must raise a SAX exception. Applications may
request a locale change in the middle of a parse."""
raise SAXNotSupportedException("Locale support not implemented")
def getFeature(self, name):
"Looks up and returns the state of a SAX2 feature."
raise SAXNotRecognizedException("Feature '%s' not recognized" % name)
def setFeature(self, name, state):
"Sets the state of a SAX2 feature."
raise SAXNotRecognizedException("Feature '%s' not recognized" % name)
def getProperty(self, name):
"Looks up and returns the value of a SAX2 property."
raise SAXNotRecognizedException("Property '%s' not recognized" % name)
def setProperty(self, name, value):
"Sets the value of a SAX2 property."
raise SAXNotRecognizedException("Property '%s' not recognized" % name)
class IncrementalParser(XMLReader):
"""This interface adds three extra methods to the XMLReader
interface that allow XML parsers to support incremental
parsing. Support for this interface is optional, since not all
underlying XML parsers support this functionality.
When the parser is instantiated it is ready to begin accepting
data from the feed method immediately. After parsing has been
finished with a call to close the reset method must be called to
make the parser ready to accept new data, either from feed or
using the parse method.
Note that these methods must _not_ be called during parsing, that
is, after parse has been called and before it returns.
By default, the class also implements the parse method of the XMLReader
interface using the feed, close and reset methods of the
IncrementalParser interface as a convenience to SAX 2.0 driver
writers."""
def __init__(self, bufsize=2**16):
self._bufsize = bufsize
XMLReader.__init__(self)
def parse(self, source):
from . import saxutils
source = saxutils.prepare_input_source(source)
self.prepareParser(source)
file = source.getByteStream()
buffer = file.read(self._bufsize)
while buffer:
self.feed(buffer)
buffer = file.read(self._bufsize)
self.close()
def feed(self, data):
"""This method gives the raw XML data in the data parameter to
the parser and makes it parse the data, emitting the
corresponding events. It is allowed for XML constructs to be
split across several calls to feed.
feed may raise SAXException."""
raise NotImplementedError("This method must be implemented!")
def prepareParser(self, source):
"""This method is called by the parse implementation to allow
the SAX 2.0 driver to prepare itself for parsing."""
raise NotImplementedError("prepareParser must be overridden!")
def close(self):
"""This method is called when the entire XML document has been
passed to the parser through the feed method, to notify the
parser that there are no more data. This allows the parser to
do the final checks on the document and empty the internal
data buffer.
The parser will not be ready to parse another document until
the reset method has been called.
close may raise SAXException."""
raise NotImplementedError("This method must be implemented!")
def reset(self):
"""This method is called after close has been called to reset
the parser so that it is ready to parse new documents. The
results of calling parse or feed after close without calling
reset are undefined."""
raise NotImplementedError("This method must be implemented!")
# ===== LOCATOR =====
class Locator:
"""Interface for associating a SAX event with a document
location. A locator object will return valid results only during
calls to DocumentHandler methods; at any other time, the
results are unpredictable."""
def getColumnNumber(self):
"Return the column number where the current event ends."
return -1
def getLineNumber(self):
"Return the line number where the current event ends."
return -1
def getPublicId(self):
"Return the public identifier for the current event."
return None
def getSystemId(self):
"Return the system identifier for the current event."
return None
# ===== INPUTSOURCE =====
class InputSource:
"""Encapsulation of the information needed by the XMLReader to
read entities.
This class may include information about the public identifier,
system identifier, byte stream (possibly with character encoding
information) and/or the character stream of an entity.
Applications will create objects of this class for use in the
XMLReader.parse method and for returning from
EntityResolver.resolveEntity.
An InputSource belongs to the application, the XMLReader is not
allowed to modify InputSource objects passed to it from the
application, although it may make copies and modify those."""
def __init__(self, system_id = None):
self.__system_id = system_id
self.__public_id = None
self.__encoding = None
self.__bytefile = None
self.__charfile = None
def setPublicId(self, public_id):
"Sets the public identifier of this InputSource."
self.__public_id = public_id
def getPublicId(self):
"Returns the public identifier of this InputSource."
return self.__public_id
def setSystemId(self, system_id):
"Sets the system identifier of this InputSource."
self.__system_id = system_id
def getSystemId(self):
"Returns the system identifier of this InputSource."
return self.__system_id
def setEncoding(self, encoding):
"""Sets the character encoding of this InputSource.
The encoding must be a string acceptable for an XML encoding
declaration (see section 4.3.3 of the XML recommendation).
The encoding attribute of the InputSource is ignored if the
InputSource also contains a character stream."""
self.__encoding = encoding
def getEncoding(self):
"Get the character encoding of this InputSource."
return self.__encoding
def setByteStream(self, bytefile):
"""Set the byte stream (a Python file-like object which does
not perform byte-to-character conversion) for this input
source.
The SAX parser will ignore this if there is also a character
stream specified, but it will use a byte stream in preference
to opening a URI connection itself.
If the application knows the character encoding of the byte
stream, it should set it with the setEncoding method."""
self.__bytefile = bytefile
def getByteStream(self):
"""Get the byte stream for this input source.
The getEncoding method will return the character encoding for
this byte stream, or None if unknown."""
return self.__bytefile
def setCharacterStream(self, charfile):
"""Set the character stream for this input source. (The stream
must be a Python 2.0 Unicode-wrapped file-like that performs
conversion to Unicode strings.)
If there is a character stream specified, the SAX parser will
ignore any byte stream and will not attempt to open a URI
connection to the system identifier."""
self.__charfile = charfile
def getCharacterStream(self):
"Get the character stream for this input source."
return self.__charfile
# ===== ATTRIBUTESIMPL =====
class AttributesImpl:
def __init__(self, attrs):
"""Non-NS-aware implementation.
attrs should be of the form {name : value}."""
self._attrs = attrs
def getLength(self):
return len(self._attrs)
def getType(self, name):
return "CDATA"
def getValue(self, name):
return self._attrs[name]
def getValueByQName(self, name):
return self._attrs[name]
def getNameByQName(self, name):
if name not in self._attrs:
raise KeyError(name)
return name
def getQNameByName(self, name):
if name not in self._attrs:
raise KeyError(name)
return name
def getNames(self):
return list(self._attrs.keys())
def getQNames(self):
return list(self._attrs.keys())
def __len__(self):
return len(self._attrs)
def __getitem__(self, name):
return self._attrs[name]
def keys(self):
return list(self._attrs.keys())
def __contains__(self, name):
return name in self._attrs
def get(self, name, alternative=None):
return self._attrs.get(name, alternative)
def copy(self):
return self.__class__(self._attrs)
def items(self):
return list(self._attrs.items())
def values(self):
return list(self._attrs.values())
# ===== ATTRIBUTESNSIMPL =====
class AttributesNSImpl(AttributesImpl):
def __init__(self, attrs, qnames):
"""NS-aware implementation.
attrs should be of the form {(ns_uri, lname): value, ...}.
qnames of the form {(ns_uri, lname): qname, ...}."""
self._attrs = attrs
self._qnames = qnames
def getValueByQName(self, name):
for (nsname, qname) in self._qnames.items():
if qname == name:
return self._attrs[nsname]
raise KeyError(name)
def getNameByQName(self, name):
for (nsname, qname) in self._qnames.items():
if qname == name:
return nsname
raise KeyError(name)
def getQNameByName(self, name):
return self._qnames[name]
def getQNames(self):
return list(self._qnames.values())
def copy(self):
return self.__class__(self._attrs, self._qnames)
def _test():
XMLReader()
IncrementalParser()
Locator()
if __name__ == "__main__":
_test()
| gpl-3.0 |
giggsey/SickRage | lib/unidecode/x060.py | 250 | 4642 | data = (
'Huai ', # 0x00
'Tai ', # 0x01
'Song ', # 0x02
'Wu ', # 0x03
'Ou ', # 0x04
'Chang ', # 0x05
'Chuang ', # 0x06
'Ju ', # 0x07
'Yi ', # 0x08
'Bao ', # 0x09
'Chao ', # 0x0a
'Min ', # 0x0b
'Pei ', # 0x0c
'Zuo ', # 0x0d
'Zen ', # 0x0e
'Yang ', # 0x0f
'Kou ', # 0x10
'Ban ', # 0x11
'Nu ', # 0x12
'Nao ', # 0x13
'Zheng ', # 0x14
'Pa ', # 0x15
'Bu ', # 0x16
'Tie ', # 0x17
'Gu ', # 0x18
'Hu ', # 0x19
'Ju ', # 0x1a
'Da ', # 0x1b
'Lian ', # 0x1c
'Si ', # 0x1d
'Chou ', # 0x1e
'Di ', # 0x1f
'Dai ', # 0x20
'Yi ', # 0x21
'Tu ', # 0x22
'You ', # 0x23
'Fu ', # 0x24
'Ji ', # 0x25
'Peng ', # 0x26
'Xing ', # 0x27
'Yuan ', # 0x28
'Ni ', # 0x29
'Guai ', # 0x2a
'Fu ', # 0x2b
'Xi ', # 0x2c
'Bi ', # 0x2d
'You ', # 0x2e
'Qie ', # 0x2f
'Xuan ', # 0x30
'Cong ', # 0x31
'Bing ', # 0x32
'Huang ', # 0x33
'Xu ', # 0x34
'Chu ', # 0x35
'Pi ', # 0x36
'Xi ', # 0x37
'Xi ', # 0x38
'Tan ', # 0x39
'Koraeru ', # 0x3a
'Zong ', # 0x3b
'Dui ', # 0x3c
'[?] ', # 0x3d
'Ki ', # 0x3e
'Yi ', # 0x3f
'Chi ', # 0x40
'Ren ', # 0x41
'Xun ', # 0x42
'Shi ', # 0x43
'Xi ', # 0x44
'Lao ', # 0x45
'Heng ', # 0x46
'Kuang ', # 0x47
'Mu ', # 0x48
'Zhi ', # 0x49
'Xie ', # 0x4a
'Lian ', # 0x4b
'Tiao ', # 0x4c
'Huang ', # 0x4d
'Die ', # 0x4e
'Hao ', # 0x4f
'Kong ', # 0x50
'Gui ', # 0x51
'Heng ', # 0x52
'Xi ', # 0x53
'Xiao ', # 0x54
'Shu ', # 0x55
'S ', # 0x56
'Kua ', # 0x57
'Qiu ', # 0x58
'Yang ', # 0x59
'Hui ', # 0x5a
'Hui ', # 0x5b
'Chi ', # 0x5c
'Jia ', # 0x5d
'Yi ', # 0x5e
'Xiong ', # 0x5f
'Guai ', # 0x60
'Lin ', # 0x61
'Hui ', # 0x62
'Zi ', # 0x63
'Xu ', # 0x64
'Chi ', # 0x65
'Xiang ', # 0x66
'Nu ', # 0x67
'Hen ', # 0x68
'En ', # 0x69
'Ke ', # 0x6a
'Tong ', # 0x6b
'Tian ', # 0x6c
'Gong ', # 0x6d
'Quan ', # 0x6e
'Xi ', # 0x6f
'Qia ', # 0x70
'Yue ', # 0x71
'Peng ', # 0x72
'Ken ', # 0x73
'De ', # 0x74
'Hui ', # 0x75
'E ', # 0x76
'Kyuu ', # 0x77
'Tong ', # 0x78
'Yan ', # 0x79
'Kai ', # 0x7a
'Ce ', # 0x7b
'Nao ', # 0x7c
'Yun ', # 0x7d
'Mang ', # 0x7e
'Yong ', # 0x7f
'Yong ', # 0x80
'Yuan ', # 0x81
'Pi ', # 0x82
'Kun ', # 0x83
'Qiao ', # 0x84
'Yue ', # 0x85
'Yu ', # 0x86
'Yu ', # 0x87
'Jie ', # 0x88
'Xi ', # 0x89
'Zhe ', # 0x8a
'Lin ', # 0x8b
'Ti ', # 0x8c
'Han ', # 0x8d
'Hao ', # 0x8e
'Qie ', # 0x8f
'Ti ', # 0x90
'Bu ', # 0x91
'Yi ', # 0x92
'Qian ', # 0x93
'Hui ', # 0x94
'Xi ', # 0x95
'Bei ', # 0x96
'Man ', # 0x97
'Yi ', # 0x98
'Heng ', # 0x99
'Song ', # 0x9a
'Quan ', # 0x9b
'Cheng ', # 0x9c
'Hui ', # 0x9d
'Wu ', # 0x9e
'Wu ', # 0x9f
'You ', # 0xa0
'Li ', # 0xa1
'Liang ', # 0xa2
'Huan ', # 0xa3
'Cong ', # 0xa4
'Yi ', # 0xa5
'Yue ', # 0xa6
'Li ', # 0xa7
'Nin ', # 0xa8
'Nao ', # 0xa9
'E ', # 0xaa
'Que ', # 0xab
'Xuan ', # 0xac
'Qian ', # 0xad
'Wu ', # 0xae
'Min ', # 0xaf
'Cong ', # 0xb0
'Fei ', # 0xb1
'Bei ', # 0xb2
'Duo ', # 0xb3
'Cui ', # 0xb4
'Chang ', # 0xb5
'Men ', # 0xb6
'Li ', # 0xb7
'Ji ', # 0xb8
'Guan ', # 0xb9
'Guan ', # 0xba
'Xing ', # 0xbb
'Dao ', # 0xbc
'Qi ', # 0xbd
'Kong ', # 0xbe
'Tian ', # 0xbf
'Lun ', # 0xc0
'Xi ', # 0xc1
'Kan ', # 0xc2
'Kun ', # 0xc3
'Ni ', # 0xc4
'Qing ', # 0xc5
'Chou ', # 0xc6
'Dun ', # 0xc7
'Guo ', # 0xc8
'Chan ', # 0xc9
'Liang ', # 0xca
'Wan ', # 0xcb
'Yuan ', # 0xcc
'Jin ', # 0xcd
'Ji ', # 0xce
'Lin ', # 0xcf
'Yu ', # 0xd0
'Huo ', # 0xd1
'He ', # 0xd2
'Quan ', # 0xd3
'Tan ', # 0xd4
'Ti ', # 0xd5
'Ti ', # 0xd6
'Nie ', # 0xd7
'Wang ', # 0xd8
'Chuo ', # 0xd9
'Bu ', # 0xda
'Hun ', # 0xdb
'Xi ', # 0xdc
'Tang ', # 0xdd
'Xin ', # 0xde
'Wei ', # 0xdf
'Hui ', # 0xe0
'E ', # 0xe1
'Rui ', # 0xe2
'Zong ', # 0xe3
'Jian ', # 0xe4
'Yong ', # 0xe5
'Dian ', # 0xe6
'Ju ', # 0xe7
'Can ', # 0xe8
'Cheng ', # 0xe9
'De ', # 0xea
'Bei ', # 0xeb
'Qie ', # 0xec
'Can ', # 0xed
'Dan ', # 0xee
'Guan ', # 0xef
'Duo ', # 0xf0
'Nao ', # 0xf1
'Yun ', # 0xf2
'Xiang ', # 0xf3
'Zhui ', # 0xf4
'Die ', # 0xf5
'Huang ', # 0xf6
'Chun ', # 0xf7
'Qiong ', # 0xf8
'Re ', # 0xf9
'Xing ', # 0xfa
'Ce ', # 0xfb
'Bian ', # 0xfc
'Hun ', # 0xfd
'Zong ', # 0xfe
'Ti ', # 0xff
)
| gpl-3.0 |
imsparsh/python-for-android | python3-alpha/python3-src/Tools/pynche/Switchboard.py | 116 | 4797 | """Switchboard class.
This class is used to coordinate updates among all Viewers. Every Viewer must
conform to the following interface:
- it must include a method called update_yourself() which takes three
arguments; the red, green, and blue values of the selected color.
- When a Viewer selects a color and wishes to update all other Views, it
should call update_views() on the Switchboard object. Note that the
Viewer typically does *not* update itself before calling update_views(),
since this would cause it to get updated twice.
Optionally, Viewers can also implement:
- save_options() which takes an optiondb (a dictionary). Store into this
dictionary any values the Viewer wants to save in the persistent
~/.pynche file. This dictionary is saved using marshal. The namespace
for the keys is ad-hoc; make sure you don't clobber some other Viewer's
keys!
- withdraw() which takes no arguments. This is called when Pynche is
unmapped. All Viewers should implement this.
- colordb_changed() which takes a single argument, an instance of
ColorDB. This is called whenever the color name database is changed and
gives a chance for the Viewers to do something on those events. See
ListViewer for details.
External Viewers are found dynamically. Viewer modules should have names such
as FooViewer.py. If such a named module has a module global variable called
ADDTOVIEW and this variable is true, the Viewer will be added dynamically to
the `View' menu. ADDTOVIEW contains a string which is used as the menu item
to display the Viewer (one kludge: if the string contains a `%', this is used
to indicate that the next character will get an underline in the menu,
otherwise the first character is underlined).
FooViewer.py should contain a class called FooViewer, and its constructor
should take two arguments, an instance of Switchboard, and optionally a Tk
master window.
"""
import sys
import marshal
class Switchboard:
def __init__(self, initfile):
self.__initfile = initfile
self.__colordb = None
self.__optiondb = {}
self.__views = []
self.__red = 0
self.__green = 0
self.__blue = 0
self.__canceled = 0
# read the initialization file
fp = None
if initfile:
try:
try:
fp = open(initfile, 'rb')
self.__optiondb = marshal.load(fp)
if not isinstance(self.__optiondb, dict):
print('Problem reading options from file:', initfile,
file=sys.stderr)
self.__optiondb = {}
except (IOError, EOFError, ValueError):
pass
finally:
if fp:
fp.close()
def add_view(self, view):
self.__views.append(view)
def update_views(self, red, green, blue):
self.__red = red
self.__green = green
self.__blue = blue
for v in self.__views:
v.update_yourself(red, green, blue)
def update_views_current(self):
self.update_views(self.__red, self.__green, self.__blue)
def current_rgb(self):
return self.__red, self.__green, self.__blue
def colordb(self):
return self.__colordb
def set_colordb(self, colordb):
self.__colordb = colordb
for v in self.__views:
if hasattr(v, 'colordb_changed'):
v.colordb_changed(colordb)
self.update_views_current()
def optiondb(self):
return self.__optiondb
def save_views(self):
# save the current color
self.__optiondb['RED'] = self.__red
self.__optiondb['GREEN'] = self.__green
self.__optiondb['BLUE'] = self.__blue
for v in self.__views:
if hasattr(v, 'save_options'):
v.save_options(self.__optiondb)
# save the name of the file used for the color database. we'll try to
# load this first.
self.__optiondb['DBFILE'] = self.__colordb.filename()
fp = None
try:
try:
fp = open(self.__initfile, 'wb')
except IOError:
print('Cannot write options to file:', \
self.__initfile, file=sys.stderr)
else:
marshal.dump(self.__optiondb, fp)
finally:
if fp:
fp.close()
def withdraw_views(self):
for v in self.__views:
if hasattr(v, 'withdraw'):
v.withdraw()
def canceled(self, flag=1):
self.__canceled = flag
def canceled_p(self):
return self.__canceled
| apache-2.0 |
Dhivyap/ansible | lib/ansible/modules/network/check_point/cp_mgmt_assign_global_assignment.py | 20 | 2701 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Ansible module to manage Check Point Firewall (c) 2019
#
# Ansible 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.
#
# Ansible 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 Ansible. If not, see <http://www.gnu.org/licenses/>.
#
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = """
---
module: cp_mgmt_assign_global_assignment
short_description: assign global assignment on Check Point over Web Services API
description:
- assign global assignment on Check Point over Web Services API
- All operations are performed over Web Services API.
version_added: "2.9"
author: "Or Soffer (@chkp-orso)"
options:
dependent_domains:
description:
- N/A
type: list
global_domains:
description:
- N/A
type: list
details_level:
description:
- The level of detail for some of the fields in the response can vary from showing only the UID value of the object to a fully detailed
representation of the object.
type: str
choices: ['uid', 'standard', 'full']
extends_documentation_fragment: checkpoint_commands
"""
EXAMPLES = """
- name: assign-global-assignment
cp_mgmt_assign_global_assignment:
dependent_domains: domain1
global_domains: Global2
"""
RETURN = """
cp_mgmt_assign_global_assignment:
description: The checkpoint assign-global-assignment output.
returned: always.
type: dict
"""
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.network.checkpoint.checkpoint import checkpoint_argument_spec_for_commands, api_command
def main():
argument_spec = dict(
dependent_domains=dict(type='list'),
global_domains=dict(type='list'),
details_level=dict(type='str', choices=['uid', 'standard', 'full'])
)
argument_spec.update(checkpoint_argument_spec_for_commands)
module = AnsibleModule(argument_spec=argument_spec)
command = "assign-global-assignment"
result = api_command(module, command)
module.exit_json(**result)
if __name__ == '__main__':
main()
| gpl-3.0 |
cowai/jottalib | src/jottalib/jottafuse.py | 2 | 13210 | #!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''Mount your JottaCloud files locally and use it with your normal file tools'''
#
# This file is part of jottafs.
#
# jottafs 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.
#
# jottafs 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 jottafs. If not, see <http://www.gnu.org/licenses/>.
#
# Copyright 2011,2013-2015 HΓ₯vard Gulldahl <[email protected]>
# metadata
__author__ = '[email protected]'
# importing stdlib
import sys, os, pwd, stat, errno
import urllib, logging, datetime, argparse
import time
import itertools
try:
from cStringIO import StringIO # py2
except ImportError:
from io import StringIO # py3
logging.captureWarnings(True)
log = logging.getLogger(__name__)
# import jotta
from jottalib import JFS, __version__
from jottalib.contrib.mwt import Memoize
# import dependenceis (get them with pip!)
try:
from fuse import FUSE, Operations, LoggingMixIn, FuseOSError # this is 'pip install fusepy'
except ImportError:
print "JottaFuse won't work without fusepy! Please run `pip install fusepy`."
raise
class JottaFuseError(FuseOSError):
pass
ESUCCESS=0
BLACKLISTED_FILENAMES = ('.hidden', '._', '._.', '.DS_Store',
'.Trash', '.Spotlight-', '.hotfiles-btree',
'lost+found', 'Backups.backupdb', 'mach_kernel')
def is_blacklisted(path):
_basename = os.path.basename(path)
for bf in BLACKLISTED_FILENAMES:
if _basename.startswith(bf):
return True
return False
class JottaFuse(LoggingMixIn, Operations):
'''
A simple filesystem for JottaCloud.
'''
def __init__(self, auth, path='.'):
self.client = JFS.JFS(auth)
self.__newfiles = {} # a dict of stringio objects
self.__newfolders = []
self.ino = 0
#
# setup and teardown
#
def init(self, rootpath):
# Called on filesystem initialization. (Path is always /)
# Use it instead of __init__ if you start threads on initialization.
#TODO: Set up threaded work queue
pass
def destroy(self, path):
#TODO: do proper teardown
pass
#
# helpers
#
def _getpath(self, path):
"A wrapper of JFS.getObject(), with some tweaks that make sense in a file system."
if is_blacklisted(path):
raise JottaFuseError('Blacklisted file, refusing to retrieve it')
return self.client.getObject(path)
def _dirty(self, path):
'Remove path from cache'
return Memoize().yank_path(path)
#
# some methods are expected to always work on a rw filesystem, so let's make them work
#
def _success(self, *args):
'''shortcut to always return success (0) to masquerade as a proper filesystem'''
return 0
chmod = _success
chown = _success
utimens = _success
setxattr = _success
#
# fuse syscall implementations
#
def create(self, path, mode, fi=None):
if is_blacklisted(path):
raise JottaFuseError('Blacklisted file')
self.__newfiles[path] = StringIO()
self.ino += 1
return self.ino
@Memoize(timeout=60) # remember every result for 60 seconds
def getattr(self, path, fh=None):
if is_blacklisted(path):
raise OSError(errno.ENOENT)
pw = pwd.getpwuid( os.getuid() )
if path in self.__newfolders: # folder was just created, not synced yet
return {
'st_atime': time.time(),
'st_gid': pw.pw_gid,
'st_mode': stat.S_IFDIR | 0755,
'st_mtime': time.time(),
'st_size': 0,
'st_uid': pw.pw_uid,
}
elif path in self.__newfiles: # file was just created, not synced yet
return {
'st_atime': time.time(),
'st_gid': pw.pw_gid,
'st_mode': stat.S_IFREG | 0644,
'st_mtime': time.time(),
'st_size': 0,
'st_uid': pw.pw_uid,
}
try:
f = self._getpath(path)
except JFS.JFSError:
raise OSError(errno.ENOENT, '') # file not found
if isinstance(f, (JFS.JFSFile, JFS.JFSFolder, JFS.JFSIncompleteFile)) and f.is_deleted():
raise OSError(errno.ENOENT)
if isinstance(f, (JFS.JFSIncompleteFile, JFS.JFSFile)):
_mode = stat.S_IFREG | 0644
elif isinstance(f, JFS.JFSFolder):
_mode = stat.S_IFDIR | 0755
elif isinstance(f, (JFS.JFSMountPoint, JFS.JFSDevice) ):
_mode = stat.S_IFDIR | 0555 # these are special jottacloud dirs, make them read only
else:
if not f.tag in ('user', ):
log.warning('Unknown jfs object: %s <-> "%s"' % (type(f), f.tag) )
_mode = stat.S_IFDIR | 0555
return {
'st_atime': time.mktime(f.modified.timetuple()) if isinstance(f, JFS.JFSFile) else time.time(),
'st_gid': pw.pw_gid,
'st_mode': _mode,
'st_mtime': time.mktime(f.modified.timetuple()) if isinstance(f, JFS.JFSFile) else time.time(),
'st_size': f.size if isinstance(f, JFS.JFSFile) else 0,
'st_uid': pw.pw_uid,
}
def mkdir(self, path, mode):
parentfolder = os.path.dirname(path)
newfolder = os.path.basename(path)
try:
f = self._getpath(parentfolder)
except JFS.JFSError:
raise OSError(errno.ENOENT, '')
if not isinstance(f, JFS.JFSFolder):
raise OSError(errno.EACCES) # can only create stuff in folders
if isinstance(f, (JFS.JFSFile, JFS.JFSFolder)) and f.is_deleted():
raise OSError(errno.ENOENT)
r = f.mkdir(newfolder)
self.__newfolders.append(path)
self._dirty(path)
return ESUCCESS
def open(self, path, flags):
if flags & os.O_WRONLY:
if not self.__newfiles.has_key(path):
self.__newfiles[path] = StringIO()
self.ino += 1
return self.ino
return super(JottaFuse, self).open(path, flags)
def read(self, path, size, offset, fh):
if path in self.__newfiles.keys(): # file was just created, not synced yet
data = StringIO(self.__newfiles[path].getvalue())
data.seek(offset, 0)
buf = data.read(size)
data.close()
return buf
else:
try:
f = self._getpath(path)
except JFS.JFSError:
raise OSError(errno.ENOENT, '')
if isinstance(f, (JFS.JFSFile, JFS.JFSFolder)) and f.is_deleted():
raise OSError(errno.ENOENT)
# gnu tools may happily ask for content beyond file size
# but jottacloud doesn't like that
# so we make sure we stay within file size (f.size)
end = min(offset+size, f.size)
log.debug("f.readpartial(%s, %s) on file of size %s" % (offset, end, f.size))
return f.readpartial(offset, end)
def readdir(self, path, fh):
yield '.'
yield '..'
if path == '/':
for d in self.client.devices:
yield d.name
else:
p = self._getpath(path)
if isinstance(p, JFS.JFSDevice):
for name in p.mountPoints.keys():
yield name
else:
for el in itertools.chain(p.folders(), p.files()):
if not el.is_deleted():
yield el.name
def release(self, path, fh):
"Run after a read or write operation has finished. This is where we upload on writes"
#print "release! inpath:", path in self.__newfiles.keys()
# if the path exists in self.__newfiles.keys(), we have a new version to upload
try:
f = self.__newfiles[path] # make a local shortcut to Stringio object
f.seek(0, os.SEEK_END)
if f.tell() > 0: # file has length
self.client.up(path, f) # upload to jottacloud
del self.__newfiles[path]
del f
self._dirty(path)
except KeyError:
pass
return ESUCCESS
def rename(self, old, new):
if old == new: return
try:
f = self._getpath(old)
except JFS.JFSError:
raise OSError(errno.ENOENT, '')
f.rename(new)
self._dirty(old)
self._dirty(new)
return ESUCCESS
@Memoize(timeout=60)
def statfs(self, path):
"Return a statvfs(3) structure, for stat and df and friends"
# from fuse.py source code:
#
# class c_statvfs(Structure):
# _fields_ = [
# ('f_bsize', c_ulong), # preferred size of file blocks, in bytes
# ('f_frsize', c_ulong), # fundamental size of file blcoks, in bytes
# ('f_blocks', c_fsblkcnt_t), # total number of blocks in the filesystem
# ('f_bfree', c_fsblkcnt_t), # number of free blocks
# ('f_bavail', c_fsblkcnt_t), # free blocks avail to non-superuser
# ('f_files', c_fsfilcnt_t), # total file nodes in file system
# ('f_ffree', c_fsfilcnt_t), # free file nodes in fs
# ('f_favail', c_fsfilcnt_t)] #
#
# On Mac OS X f_bsize and f_frsize must be a power of 2
# (minimum 512).
_blocksize = 512
_usage = self.client.usage
_fs_size = self.client.capacity
if _fs_size == -1: # unlimited
# Since backend is supposed to be unlimited,
# always return a half-full filesystem, but at least 1 TB)
_fs_size = max(2 * _usage, 1024 ** 4)
_bfree = ( _fs_size - _usage ) // _blocksize
return {
'f_bsize': _blocksize,
'f_frsize': _blocksize,
'f_blocks': _fs_size // _blocksize,
'f_bfree': _bfree,
'f_bavail': _bfree,
# 'f_files': c_fsfilcnt_t,
# 'f_ffree': c_fsfilcnt_t,
# 'f_favail': c_fsfilcnt_t
}
def symlink(self, linkname, existing_file):
"""Called to create a symlink `target -> source` (e.g. ln -s existing_file linkname). In jottafuse, we upload the _contents_ of source.
This is a handy shortcut for streaming uploads directly from disk, without reading the file
into memory first"""
log.info("***SYMLINK* %s (link) -> %s (existing)", linkname, existing_file)
sourcepath = os.path.abspath(existing_file)
if not os.path.exists(sourcepath): # broken symlink
raise OSError(errno.ENOENT, '')
try:
with open(sourcepath) as sourcefile:
self.client.up(linkname, sourcefile)
return ESUCCESS
except Exception as e:
log.exception(e)
raise OSError(errno.ENOENT, '')
def truncate(self, path, length, fh=None):
"Download existing path, truncate and reupload"
try:
f = self._getpath(path)
except JFS.JFSError:
raise OSError(errno.ENOENT, '')
if isinstance(f, (JFS.JFSFile, JFS.JFSFolder)) and f.is_deleted():
raise OSError(errno.ENOENT)
data = StringIO(f.read())
data.truncate(length)
try:
self.client.up(path, data) # replace file contents
self._dirty(path)
return ESUCCESS
except:
raise OSError(errno.ENOENT, '')
def rmdir(self, path):
if path in self.__newfolders: # folder was just created, not synced yet
self.__newfolders.remove(path)
self._dirty(path)
return
try:
f = self._getpath(path)
except JFS.JFSError:
raise OSError(errno.ENOENT, '')
r = f.delete()
self._dirty(path)
return ESUCCESS
def unlink(self, path):
if path in self.__newfiles.keys(): # file was just created, not synced yet
del self.__newfiles[path]
self._dirty(path)
return
try:
f = self._getpath(path)
except JFS.JFSError:
raise OSError(errno.ENOENT, '')
r = f.delete()
self._dirty(path)
return ESUCCESS
def write(self, path, data, offset, fh=None):
if is_blacklisted(path):
raise JottaFuseError('Blacklisted file')
if not self.__newfiles.has_key(path):
self.__newfiles[path] = StringIO()
buf = self.__newfiles[path]
buf.seek(offset)
buf.write(data)
self._dirty(path)
return len(data)
| gpl-3.0 |
eleonrk/SickRage | lib/feedparser/namespaces/admin.py | 43 | 2368 | # Support for the administrative elements extension
# Copyright 2010-2015 Kurt McKee <[email protected]>
# Copyright 2002-2008 Mark Pilgrim
# All rights reserved.
#
# This file is a part of feedparser.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 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.
from __future__ import absolute_import, unicode_literals
from ..util import FeedParserDict
class Namespace(object):
# RDF Site Summary 1.0 Modules: Administrative
# http://web.resource.org/rss/1.0/modules/admin/
supported_namespaces = {
'http://webns.net/mvcb/': 'admin',
}
def _start_admin_generatoragent(self, attrsD):
self.push('generator', 1)
value = self._getAttribute(attrsD, 'rdf:resource')
if value:
self.elementstack[-1][2].append(value)
self.pop('generator')
self._getContext()['generator_detail'] = FeedParserDict({'href': value})
def _start_admin_errorreportsto(self, attrsD):
self.push('errorreportsto', 1)
value = self._getAttribute(attrsD, 'rdf:resource')
if value:
self.elementstack[-1][2].append(value)
self.pop('errorreportsto')
| gpl-3.0 |
konstruktoid/ansible-upstream | lib/ansible/modules/cloud/amazon/ec2_vpc_igw_facts.py | 19 | 4756 | #!/usr/bin/python
# Copyright: Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = '''
---
module: ec2_vpc_igw_facts
short_description: Gather facts about internet gateways in AWS
description:
- Gather facts about internet gateways in AWS.
version_added: "2.3"
requirements: [ boto3 ]
author: "Nick Aslanidis (@naslanidis)"
options:
filters:
description:
- A dict of filters to apply. Each dict item consists of a filter key and a filter value.
See U(http://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_DescribeInternetGateways.html) for possible filters.
internet_gateway_ids:
description:
- Get details of specific Internet Gateway ID. Provide this value as a list.
extends_documentation_fragment:
- aws
- ec2
'''
EXAMPLES = '''
# # Note: These examples do not set authentication details, see the AWS Guide for details.
- name: Gather facts about all Internet Gateways for an account or profile
ec2_vpc_igw_facts:
region: ap-southeast-2
profile: production
register: igw_facts
- name: Gather facts about a filtered list of Internet Gateways
ec2_vpc_igw_facts:
region: ap-southeast-2
profile: production
filters:
"tag:Name": "igw-123"
register: igw_facts
- name: Gather facts about a specific internet gateway by InternetGatewayId
ec2_vpc_igw_facts:
region: ap-southeast-2
profile: production
internet_gateway_ids: igw-c1231234
register: igw_facts
'''
RETURN = '''
internet_gateways:
description: The internet gateways for the account.
returned: always
type: list
sample: [
{
"attachments": [
{
"state": "available",
"vpc_id": "vpc-02123b67"
}
],
"internet_gateway_id": "igw-2123634d",
"tags": [
{
"key": "Name",
"value": "test-vpc-20-igw"
}
]
}
]
changed:
description: True if listing the internet gateways succeeds.
type: bool
returned: always
sample: "false"
'''
try:
import botocore
except ImportError:
pass # will be captured by imported HAS_BOTO3
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.ec2 import (ec2_argument_spec, get_aws_connection_info, boto3_conn,
camel_dict_to_snake_dict, ansible_dict_to_boto3_filter_list, HAS_BOTO3)
def get_internet_gateway_info(internet_gateway):
internet_gateway_info = {'InternetGatewayId': internet_gateway['InternetGatewayId'],
'Attachments': internet_gateway['Attachments'],
'Tags': internet_gateway['Tags']}
return internet_gateway_info
def list_internet_gateways(client, module):
params = dict()
params['Filters'] = ansible_dict_to_boto3_filter_list(module.params.get('filters'))
if module.params.get("internet_gateway_ids"):
params['InternetGatewayIds'] = module.params.get("internet_gateway_ids")
try:
all_internet_gateways = client.describe_internet_gateways(**params)
except botocore.exceptions.ClientError as e:
module.fail_json(msg=str(e))
snaked_internet_gateways = [camel_dict_to_snake_dict(get_internet_gateway_info(igw))
for igw in all_internet_gateways['InternetGateways']]
module.exit_json(internet_gateways=snaked_internet_gateways)
def main():
argument_spec = ec2_argument_spec()
argument_spec.update(
dict(
filters=dict(type='dict', default=dict()),
internet_gateway_ids=dict(type='list', default=None)
)
)
module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True)
# Validate Requirements
if not HAS_BOTO3:
module.fail_json(msg='botocore and boto3 are required.')
try:
region, ec2_url, aws_connect_kwargs = get_aws_connection_info(module, boto3=True)
connection = boto3_conn(module, conn_type='client', resource='ec2', region=region, endpoint=ec2_url, **aws_connect_kwargs)
except botocore.exceptions.NoCredentialsError as e:
module.fail_json(msg="Can't authorize connection - " + str(e))
# call your function here
results = list_internet_gateways(connection, module)
module.exit_json(result=results)
if __name__ == '__main__':
main()
| gpl-3.0 |
fishscene/streamlink | src/streamlink/logger.py | 41 | 1656 | import sys
from threading import Lock
class Logger(object):
Levels = ["none", "error", "warning", "info", "debug"]
Format = "[{module}][{level}] {msg}\n"
def __init__(self):
self.output = sys.stdout
self.level = 0
self.lock = Lock()
def new_module(self, module):
return LoggerModule(self, module)
def set_level(self, level):
try:
index = Logger.Levels.index(level)
except ValueError:
return
self.level = index
def set_output(self, output):
self.output = output
def msg(self, module, level, msg, *args, **kwargs):
if self.level < level or level > len(Logger.Levels):
return
msg = msg.format(*args, **kwargs)
with self.lock:
self.output.write(Logger.Format.format(module=module,
level=Logger.Levels[level],
msg=msg))
if hasattr(self.output, "flush"):
self.output.flush()
class LoggerModule(object):
def __init__(self, manager, module):
self.manager = manager
self.module = module
def error(self, msg, *args, **kwargs):
self.manager.msg(self.module, 1, msg, *args, **kwargs)
def warning(self, msg, *args, **kwargs):
self.manager.msg(self.module, 2, msg, *args, **kwargs)
def info(self, msg, *args, **kwargs):
self.manager.msg(self.module, 3, msg, *args, **kwargs)
def debug(self, msg, *args, **kwargs):
self.manager.msg(self.module, 4, msg, *args, **kwargs)
__all__ = ["Logger"]
| bsd-2-clause |
kost/volatility | volatility/plugins/overlays/windows/xp_sp3_x86_vtypes.py | 58 | 291918 | ntkrnlmp_types = {
'LIST_ENTRY64' : [ 0x10, {
'Flink' : [ 0x0, ['unsigned long long']],
'Blink' : [ 0x8, ['unsigned long long']],
} ],
'LIST_ENTRY32' : [ 0x8, {
'Flink' : [ 0x0, ['unsigned long']],
'Blink' : [ 0x4, ['unsigned long']],
} ],
'_LIST_ENTRY' : [ 0x8, {
'Flink' : [ 0x0, ['pointer', ['_LIST_ENTRY']]],
'Blink' : [ 0x4, ['pointer', ['_LIST_ENTRY']]],
} ],
'_IMAGE_NT_HEADERS' : [ 0xf8, {
'Signature' : [ 0x0, ['unsigned long']],
'FileHeader' : [ 0x4, ['_IMAGE_FILE_HEADER']],
'OptionalHeader' : [ 0x18, ['_IMAGE_OPTIONAL_HEADER']],
} ],
'__unnamed_1016' : [ 0x8, {
'LowPart' : [ 0x0, ['unsigned long']],
'HighPart' : [ 0x4, ['long']],
} ],
'_LARGE_INTEGER' : [ 0x8, {
'LowPart' : [ 0x0, ['unsigned long']],
'HighPart' : [ 0x4, ['long']],
'u' : [ 0x0, ['__unnamed_1016']],
'QuadPart' : [ 0x0, ['long long']],
} ],
'__unnamed_101b' : [ 0x8, {
'LowPart' : [ 0x0, ['unsigned long']],
'HighPart' : [ 0x4, ['unsigned long']],
} ],
'_ULARGE_INTEGER' : [ 0x8, {
'LowPart' : [ 0x0, ['unsigned long']],
'HighPart' : [ 0x4, ['unsigned long']],
'u' : [ 0x0, ['__unnamed_101b']],
'QuadPart' : [ 0x0, ['unsigned long long']],
} ],
'_LUID' : [ 0x8, {
'LowPart' : [ 0x0, ['unsigned long']],
'HighPart' : [ 0x4, ['long']],
} ],
'_KAPC' : [ 0x30, {
'Type' : [ 0x0, ['short']],
'Size' : [ 0x2, ['short']],
'Spare0' : [ 0x4, ['unsigned long']],
'Thread' : [ 0x8, ['pointer', ['_KTHREAD']]],
'ApcListEntry' : [ 0xc, ['_LIST_ENTRY']],
'KernelRoutine' : [ 0x14, ['pointer', ['void']]],
'RundownRoutine' : [ 0x18, ['pointer', ['void']]],
'NormalRoutine' : [ 0x1c, ['pointer', ['void']]],
'NormalContext' : [ 0x20, ['pointer', ['void']]],
'SystemArgument1' : [ 0x24, ['pointer', ['void']]],
'SystemArgument2' : [ 0x28, ['pointer', ['void']]],
'ApcStateIndex' : [ 0x2c, ['unsigned char']],
'ApcMode' : [ 0x2d, ['unsigned char']],
'Inserted' : [ 0x2e, ['unsigned char']],
} ],
'_SINGLE_LIST_ENTRY' : [ 0x4, {
'Next' : [ 0x0, ['pointer', ['_SINGLE_LIST_ENTRY']]],
} ],
'_KPRCB' : [ 0xc50, {
'MinorVersion' : [ 0x0, ['unsigned short']],
'MajorVersion' : [ 0x2, ['unsigned short']],
'CurrentThread' : [ 0x4, ['pointer', ['_KTHREAD']]],
'NextThread' : [ 0x8, ['pointer', ['_KTHREAD']]],
'IdleThread' : [ 0xc, ['pointer', ['_KTHREAD']]],
'Number' : [ 0x10, ['unsigned char']],
'Reserved' : [ 0x11, ['unsigned char']],
'BuildType' : [ 0x12, ['unsigned short']],
'SetMember' : [ 0x14, ['unsigned long']],
'CpuType' : [ 0x18, ['unsigned char']],
'CpuID' : [ 0x19, ['unsigned char']],
'CpuStep' : [ 0x1a, ['unsigned short']],
'ProcessorState' : [ 0x1c, ['_KPROCESSOR_STATE']],
'KernelReserved' : [ 0x33c, ['array', 16, ['unsigned long']]],
'HalReserved' : [ 0x37c, ['array', 16, ['unsigned long']]],
'PrcbPad0' : [ 0x3bc, ['array', 92, ['unsigned char']]],
'LockQueue' : [ 0x418, ['array', 16, ['_KSPIN_LOCK_QUEUE']]],
'PrcbPad1' : [ 0x498, ['array', 8, ['unsigned char']]],
'NpxThread' : [ 0x4a0, ['pointer', ['_KTHREAD']]],
'InterruptCount' : [ 0x4a4, ['unsigned long']],
'KernelTime' : [ 0x4a8, ['unsigned long']],
'UserTime' : [ 0x4ac, ['unsigned long']],
'DpcTime' : [ 0x4b0, ['unsigned long']],
'DebugDpcTime' : [ 0x4b4, ['unsigned long']],
'InterruptTime' : [ 0x4b8, ['unsigned long']],
'AdjustDpcThreshold' : [ 0x4bc, ['unsigned long']],
'PageColor' : [ 0x4c0, ['unsigned long']],
'SkipTick' : [ 0x4c4, ['unsigned long']],
'MultiThreadSetBusy' : [ 0x4c8, ['unsigned char']],
'Spare2' : [ 0x4c9, ['array', 3, ['unsigned char']]],
'ParentNode' : [ 0x4cc, ['pointer', ['_KNODE']]],
'MultiThreadProcessorSet' : [ 0x4d0, ['unsigned long']],
'MultiThreadSetMaster' : [ 0x4d4, ['pointer', ['_KPRCB']]],
'ThreadStartCount' : [ 0x4d8, ['array', 2, ['unsigned long']]],
'CcFastReadNoWait' : [ 0x4e0, ['unsigned long']],
'CcFastReadWait' : [ 0x4e4, ['unsigned long']],
'CcFastReadNotPossible' : [ 0x4e8, ['unsigned long']],
'CcCopyReadNoWait' : [ 0x4ec, ['unsigned long']],
'CcCopyReadWait' : [ 0x4f0, ['unsigned long']],
'CcCopyReadNoWaitMiss' : [ 0x4f4, ['unsigned long']],
'KeAlignmentFixupCount' : [ 0x4f8, ['unsigned long']],
'KeContextSwitches' : [ 0x4fc, ['unsigned long']],
'KeDcacheFlushCount' : [ 0x500, ['unsigned long']],
'KeExceptionDispatchCount' : [ 0x504, ['unsigned long']],
'KeFirstLevelTbFills' : [ 0x508, ['unsigned long']],
'KeFloatingEmulationCount' : [ 0x50c, ['unsigned long']],
'KeIcacheFlushCount' : [ 0x510, ['unsigned long']],
'KeSecondLevelTbFills' : [ 0x514, ['unsigned long']],
'KeSystemCalls' : [ 0x518, ['unsigned long']],
'SpareCounter0' : [ 0x51c, ['array', 1, ['unsigned long']]],
'PPLookasideList' : [ 0x520, ['array', 16, ['_PP_LOOKASIDE_LIST']]],
'PPNPagedLookasideList' : [ 0x5a0, ['array', 32, ['_PP_LOOKASIDE_LIST']]],
'PPPagedLookasideList' : [ 0x6a0, ['array', 32, ['_PP_LOOKASIDE_LIST']]],
'PacketBarrier' : [ 0x7a0, ['unsigned long']],
'ReverseStall' : [ 0x7a4, ['unsigned long']],
'IpiFrame' : [ 0x7a8, ['pointer', ['void']]],
'PrcbPad2' : [ 0x7ac, ['array', 52, ['unsigned char']]],
'CurrentPacket' : [ 0x7e0, ['array', 3, ['pointer', ['void']]]],
'TargetSet' : [ 0x7ec, ['unsigned long']],
'WorkerRoutine' : [ 0x7f0, ['pointer', ['void']]],
'IpiFrozen' : [ 0x7f4, ['unsigned long']],
'PrcbPad3' : [ 0x7f8, ['array', 40, ['unsigned char']]],
'RequestSummary' : [ 0x820, ['unsigned long']],
'SignalDone' : [ 0x824, ['pointer', ['_KPRCB']]],
'PrcbPad4' : [ 0x828, ['array', 56, ['unsigned char']]],
'DpcListHead' : [ 0x860, ['_LIST_ENTRY']],
'DpcStack' : [ 0x868, ['pointer', ['void']]],
'DpcCount' : [ 0x86c, ['unsigned long']],
'DpcQueueDepth' : [ 0x870, ['unsigned long']],
'DpcRoutineActive' : [ 0x874, ['unsigned long']],
'DpcInterruptRequested' : [ 0x878, ['unsigned long']],
'DpcLastCount' : [ 0x87c, ['unsigned long']],
'DpcRequestRate' : [ 0x880, ['unsigned long']],
'MaximumDpcQueueDepth' : [ 0x884, ['unsigned long']],
'MinimumDpcRate' : [ 0x888, ['unsigned long']],
'QuantumEnd' : [ 0x88c, ['unsigned long']],
'PrcbPad5' : [ 0x890, ['array', 16, ['unsigned char']]],
'DpcLock' : [ 0x8a0, ['unsigned long']],
'PrcbPad6' : [ 0x8a4, ['array', 28, ['unsigned char']]],
'CallDpc' : [ 0x8c0, ['_KDPC']],
'ChainedInterruptList' : [ 0x8e0, ['pointer', ['void']]],
'LookasideIrpFloat' : [ 0x8e4, ['long']],
'SpareFields0' : [ 0x8e8, ['array', 6, ['unsigned long']]],
'VendorString' : [ 0x900, ['array', 13, ['unsigned char']]],
'InitialApicId' : [ 0x90d, ['unsigned char']],
'LogicalProcessorsPerPhysicalProcessor' : [ 0x90e, ['unsigned char']],
'MHz' : [ 0x910, ['unsigned long']],
'FeatureBits' : [ 0x914, ['unsigned long']],
'UpdateSignature' : [ 0x918, ['_LARGE_INTEGER']],
'NpxSaveArea' : [ 0x920, ['_FX_SAVE_AREA']],
'PowerState' : [ 0xb30, ['_PROCESSOR_POWER_STATE']],
} ],
'_SLIST_HEADER' : [ 0x8, {
'Alignment' : [ 0x0, ['unsigned long long']],
'Next' : [ 0x0, ['_SINGLE_LIST_ENTRY']],
'Depth' : [ 0x4, ['unsigned short']],
'Sequence' : [ 0x6, ['unsigned short']],
} ],
'_NPAGED_LOOKASIDE_LIST' : [ 0x100, {
'L' : [ 0x0, ['_GENERAL_LOOKASIDE']],
'Lock__ObsoleteButDoNotDelete' : [ 0x80, ['unsigned long']],
} ],
'_PAGED_LOOKASIDE_LIST' : [ 0x100, {
'L' : [ 0x0, ['_GENERAL_LOOKASIDE']],
'Lock__ObsoleteButDoNotDelete' : [ 0x80, ['_FAST_MUTEX']],
} ],
'_GENERAL_LOOKASIDE' : [ 0x80, {
'ListHead' : [ 0x0, ['_SLIST_HEADER']],
'Depth' : [ 0x8, ['unsigned short']],
'MaximumDepth' : [ 0xa, ['unsigned short']],
'TotalAllocates' : [ 0xc, ['unsigned long']],
'AllocateMisses' : [ 0x10, ['unsigned long']],
'AllocateHits' : [ 0x10, ['unsigned long']],
'TotalFrees' : [ 0x14, ['unsigned long']],
'FreeMisses' : [ 0x18, ['unsigned long']],
'FreeHits' : [ 0x18, ['unsigned long']],
'Type' : [ 0x1c, ['Enumeration', dict(target = 'long', choices = {0: 'NonPagedPool', 1: 'PagedPool', 2: 'NonPagedPoolMustSucceed', 3: 'DontUseThisType', 4: 'NonPagedPoolCacheAligned', 5: 'PagedPoolCacheAligned', 6: 'NonPagedPoolCacheAlignedMustS', 7: 'MaxPoolType', 34: 'NonPagedPoolMustSucceedSession', 35: 'DontUseThisTypeSession', 32: 'NonPagedPoolSession', 36: 'NonPagedPoolCacheAlignedSession', 33: 'PagedPoolSession', 38: 'NonPagedPoolCacheAlignedMustSSession', 37: 'PagedPoolCacheAlignedSession'})]],
'Tag' : [ 0x20, ['unsigned long']],
'Size' : [ 0x24, ['unsigned long']],
'Allocate' : [ 0x28, ['pointer', ['void']]],
'Free' : [ 0x2c, ['pointer', ['void']]],
'ListEntry' : [ 0x30, ['_LIST_ENTRY']],
'LastTotalAllocates' : [ 0x38, ['unsigned long']],
'LastAllocateMisses' : [ 0x3c, ['unsigned long']],
'LastAllocateHits' : [ 0x3c, ['unsigned long']],
'Future' : [ 0x40, ['array', 2, ['unsigned long']]],
} ],
'_EX_RUNDOWN_REF' : [ 0x4, {
'Count' : [ 0x0, ['unsigned long']],
'Ptr' : [ 0x0, ['pointer', ['void']]],
} ],
'_EX_FAST_REF' : [ 0x4, {
'Object' : [ 0x0, ['pointer', ['void']]],
'RefCnt' : [ 0x0, ['BitField', dict(start_bit = 0, end_bit = 3, native_type='unsigned long')]],
'Value' : [ 0x0, ['unsigned long']],
} ],
'_EX_PUSH_LOCK' : [ 0x4, {
'Waiting' : [ 0x0, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned long')]],
'Exclusive' : [ 0x0, ['BitField', dict(start_bit = 1, end_bit = 2, native_type='unsigned long')]],
'Shared' : [ 0x0, ['BitField', dict(start_bit = 2, end_bit = 32, native_type='unsigned long')]],
'Value' : [ 0x0, ['unsigned long']],
'Ptr' : [ 0x0, ['pointer', ['void']]],
} ],
'_EX_PUSH_LOCK_WAIT_BLOCK' : [ 0x1c, {
'WakeEvent' : [ 0x0, ['_KEVENT']],
'Next' : [ 0x10, ['pointer', ['_EX_PUSH_LOCK_WAIT_BLOCK']]],
'ShareCount' : [ 0x14, ['unsigned long']],
'Exclusive' : [ 0x18, ['unsigned char']],
} ],
'_EX_PUSH_LOCK_CACHE_AWARE' : [ 0x80, {
'Locks' : [ 0x0, ['array', 32, ['pointer', ['_EX_PUSH_LOCK']]]],
} ],
'_ETHREAD' : [ 0x258, {
'Tcb' : [ 0x0, ['_KTHREAD']],
'CreateTime' : [ 0x1c0, ['_LARGE_INTEGER']],
'NestedFaultCount' : [ 0x1c0, ['BitField', dict(start_bit = 0, end_bit = 2, native_type='unsigned long')]],
'ApcNeeded' : [ 0x1c0, ['BitField', dict(start_bit = 2, end_bit = 3, native_type='unsigned long')]],
'ExitTime' : [ 0x1c8, ['_LARGE_INTEGER']],
'LpcReplyChain' : [ 0x1c8, ['_LIST_ENTRY']],
'KeyedWaitChain' : [ 0x1c8, ['_LIST_ENTRY']],
'ExitStatus' : [ 0x1d0, ['long']],
'OfsChain' : [ 0x1d0, ['pointer', ['void']]],
'PostBlockList' : [ 0x1d4, ['_LIST_ENTRY']],
'TerminationPort' : [ 0x1dc, ['pointer', ['_TERMINATION_PORT']]],
'ReaperLink' : [ 0x1dc, ['pointer', ['_ETHREAD']]],
'KeyedWaitValue' : [ 0x1dc, ['pointer', ['void']]],
'ActiveTimerListLock' : [ 0x1e0, ['unsigned long']],
'ActiveTimerListHead' : [ 0x1e4, ['_LIST_ENTRY']],
'Cid' : [ 0x1ec, ['_CLIENT_ID']],
'LpcReplySemaphore' : [ 0x1f4, ['_KSEMAPHORE']],
'KeyedWaitSemaphore' : [ 0x1f4, ['_KSEMAPHORE']],
'LpcReplyMessage' : [ 0x208, ['pointer', ['void']]],
'LpcWaitingOnPort' : [ 0x208, ['pointer', ['void']]],
'ImpersonationInfo' : [ 0x20c, ['pointer', ['_PS_IMPERSONATION_INFORMATION']]],
'IrpList' : [ 0x210, ['_LIST_ENTRY']],
'TopLevelIrp' : [ 0x218, ['unsigned long']],
'DeviceToVerify' : [ 0x21c, ['pointer', ['_DEVICE_OBJECT']]],
'ThreadsProcess' : [ 0x220, ['pointer', ['_EPROCESS']]],
'StartAddress' : [ 0x224, ['pointer', ['void']]],
'Win32StartAddress' : [ 0x228, ['pointer', ['void']]],
'LpcReceivedMessageId' : [ 0x228, ['unsigned long']],
'ThreadListEntry' : [ 0x22c, ['_LIST_ENTRY']],
'RundownProtect' : [ 0x234, ['_EX_RUNDOWN_REF']],
'ThreadLock' : [ 0x238, ['_EX_PUSH_LOCK']],
'LpcReplyMessageId' : [ 0x23c, ['unsigned long']],
'ReadClusterSize' : [ 0x240, ['unsigned long']],
'GrantedAccess' : [ 0x244, ['unsigned long']],
'CrossThreadFlags' : [ 0x248, ['unsigned long']],
'Terminated' : [ 0x248, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned long')]],
'DeadThread' : [ 0x248, ['BitField', dict(start_bit = 1, end_bit = 2, native_type='unsigned long')]],
'HideFromDebugger' : [ 0x248, ['BitField', dict(start_bit = 2, end_bit = 3, native_type='unsigned long')]],
'ActiveImpersonationInfo' : [ 0x248, ['BitField', dict(start_bit = 3, end_bit = 4, native_type='unsigned long')]],
'SystemThread' : [ 0x248, ['BitField', dict(start_bit = 4, end_bit = 5, native_type='unsigned long')]],
'HardErrorsAreDisabled' : [ 0x248, ['BitField', dict(start_bit = 5, end_bit = 6, native_type='unsigned long')]],
'BreakOnTermination' : [ 0x248, ['BitField', dict(start_bit = 6, end_bit = 7, native_type='unsigned long')]],
'SkipCreationMsg' : [ 0x248, ['BitField', dict(start_bit = 7, end_bit = 8, native_type='unsigned long')]],
'SkipTerminationMsg' : [ 0x248, ['BitField', dict(start_bit = 8, end_bit = 9, native_type='unsigned long')]],
'SameThreadPassiveFlags' : [ 0x24c, ['unsigned long']],
'ActiveExWorker' : [ 0x24c, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned long')]],
'ExWorkerCanWaitUser' : [ 0x24c, ['BitField', dict(start_bit = 1, end_bit = 2, native_type='unsigned long')]],
'MemoryMaker' : [ 0x24c, ['BitField', dict(start_bit = 2, end_bit = 3, native_type='unsigned long')]],
'SameThreadApcFlags' : [ 0x250, ['unsigned long']],
'LpcReceivedMsgIdValid' : [ 0x250, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned char')]],
'LpcExitThreadCalled' : [ 0x250, ['BitField', dict(start_bit = 1, end_bit = 2, native_type='unsigned char')]],
'AddressSpaceOwner' : [ 0x250, ['BitField', dict(start_bit = 2, end_bit = 3, native_type='unsigned char')]],
'ForwardClusterOnly' : [ 0x254, ['unsigned char']],
'DisablePageFaultClustering' : [ 0x255, ['unsigned char']],
} ],
'_EPROCESS' : [ 0x260, {
'Pcb' : [ 0x0, ['_KPROCESS']],
'ProcessLock' : [ 0x6c, ['_EX_PUSH_LOCK']],
'CreateTime' : [ 0x70, ['_LARGE_INTEGER']],
'ExitTime' : [ 0x78, ['_LARGE_INTEGER']],
'RundownProtect' : [ 0x80, ['_EX_RUNDOWN_REF']],
'UniqueProcessId' : [ 0x84, ['pointer', ['void']]],
'ActiveProcessLinks' : [ 0x88, ['_LIST_ENTRY']],
'QuotaUsage' : [ 0x90, ['array', 3, ['unsigned long']]],
'QuotaPeak' : [ 0x9c, ['array', 3, ['unsigned long']]],
'CommitCharge' : [ 0xa8, ['unsigned long']],
'PeakVirtualSize' : [ 0xac, ['unsigned long']],
'VirtualSize' : [ 0xb0, ['unsigned long']],
'SessionProcessLinks' : [ 0xb4, ['_LIST_ENTRY']],
'DebugPort' : [ 0xbc, ['pointer', ['void']]],
'ExceptionPort' : [ 0xc0, ['pointer', ['void']]],
'ObjectTable' : [ 0xc4, ['pointer', ['_HANDLE_TABLE']]],
'Token' : [ 0xc8, ['_EX_FAST_REF']],
'WorkingSetLock' : [ 0xcc, ['_FAST_MUTEX']],
'WorkingSetPage' : [ 0xec, ['unsigned long']],
'AddressCreationLock' : [ 0xf0, ['_FAST_MUTEX']],
'HyperSpaceLock' : [ 0x110, ['unsigned long']],
'ForkInProgress' : [ 0x114, ['pointer', ['_ETHREAD']]],
'HardwareTrigger' : [ 0x118, ['unsigned long']],
'VadRoot' : [ 0x11c, ['pointer', ['void']]],
'VadHint' : [ 0x120, ['pointer', ['void']]],
'CloneRoot' : [ 0x124, ['pointer', ['void']]],
'NumberOfPrivatePages' : [ 0x128, ['unsigned long']],
'NumberOfLockedPages' : [ 0x12c, ['unsigned long']],
'Win32Process' : [ 0x130, ['pointer', ['void']]],
'Job' : [ 0x134, ['pointer', ['_EJOB']]],
'SectionObject' : [ 0x138, ['pointer', ['void']]],
'SectionBaseAddress' : [ 0x13c, ['pointer', ['void']]],
'QuotaBlock' : [ 0x140, ['pointer', ['_EPROCESS_QUOTA_BLOCK']]],
'WorkingSetWatch' : [ 0x144, ['pointer', ['_PAGEFAULT_HISTORY']]],
'Win32WindowStation' : [ 0x148, ['pointer', ['void']]],
'InheritedFromUniqueProcessId' : [ 0x14c, ['pointer', ['void']]],
'LdtInformation' : [ 0x150, ['pointer', ['void']]],
'VadFreeHint' : [ 0x154, ['pointer', ['void']]],
'VdmObjects' : [ 0x158, ['pointer', ['void']]],
'DeviceMap' : [ 0x15c, ['pointer', ['void']]],
'PhysicalVadList' : [ 0x160, ['_LIST_ENTRY']],
'PageDirectoryPte' : [ 0x168, ['_HARDWARE_PTE']],
'Filler' : [ 0x168, ['unsigned long long']],
'Session' : [ 0x170, ['pointer', ['void']]],
'ImageFileName' : [ 0x174, ['array', 16, ['unsigned char']]],
'JobLinks' : [ 0x184, ['_LIST_ENTRY']],
'LockedPagesList' : [ 0x18c, ['pointer', ['void']]],
'ThreadListHead' : [ 0x190, ['_LIST_ENTRY']],
'SecurityPort' : [ 0x198, ['pointer', ['void']]],
'PaeTop' : [ 0x19c, ['pointer', ['void']]],
'ActiveThreads' : [ 0x1a0, ['unsigned long']],
'GrantedAccess' : [ 0x1a4, ['unsigned long']],
'DefaultHardErrorProcessing' : [ 0x1a8, ['unsigned long']],
'LastThreadExitStatus' : [ 0x1ac, ['long']],
'Peb' : [ 0x1b0, ['pointer', ['_PEB']]],
'PrefetchTrace' : [ 0x1b4, ['_EX_FAST_REF']],
'ReadOperationCount' : [ 0x1b8, ['_LARGE_INTEGER']],
'WriteOperationCount' : [ 0x1c0, ['_LARGE_INTEGER']],
'OtherOperationCount' : [ 0x1c8, ['_LARGE_INTEGER']],
'ReadTransferCount' : [ 0x1d0, ['_LARGE_INTEGER']],
'WriteTransferCount' : [ 0x1d8, ['_LARGE_INTEGER']],
'OtherTransferCount' : [ 0x1e0, ['_LARGE_INTEGER']],
'CommitChargeLimit' : [ 0x1e8, ['unsigned long']],
'CommitChargePeak' : [ 0x1ec, ['unsigned long']],
'AweInfo' : [ 0x1f0, ['pointer', ['void']]],
'SeAuditProcessCreationInfo' : [ 0x1f4, ['_SE_AUDIT_PROCESS_CREATION_INFO']],
'Vm' : [ 0x1f8, ['_MMSUPPORT']],
'LastFaultCount' : [ 0x238, ['unsigned long']],
'ModifiedPageCount' : [ 0x23c, ['unsigned long']],
'NumberOfVads' : [ 0x240, ['unsigned long']],
'JobStatus' : [ 0x244, ['unsigned long']],
'Flags' : [ 0x248, ['unsigned long']],
'CreateReported' : [ 0x248, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned long')]],
'NoDebugInherit' : [ 0x248, ['BitField', dict(start_bit = 1, end_bit = 2, native_type='unsigned long')]],
'ProcessExiting' : [ 0x248, ['BitField', dict(start_bit = 2, end_bit = 3, native_type='unsigned long')]],
'ProcessDelete' : [ 0x248, ['BitField', dict(start_bit = 3, end_bit = 4, native_type='unsigned long')]],
'Wow64SplitPages' : [ 0x248, ['BitField', dict(start_bit = 4, end_bit = 5, native_type='unsigned long')]],
'VmDeleted' : [ 0x248, ['BitField', dict(start_bit = 5, end_bit = 6, native_type='unsigned long')]],
'OutswapEnabled' : [ 0x248, ['BitField', dict(start_bit = 6, end_bit = 7, native_type='unsigned long')]],
'Outswapped' : [ 0x248, ['BitField', dict(start_bit = 7, end_bit = 8, native_type='unsigned long')]],
'ForkFailed' : [ 0x248, ['BitField', dict(start_bit = 8, end_bit = 9, native_type='unsigned long')]],
'HasPhysicalVad' : [ 0x248, ['BitField', dict(start_bit = 9, end_bit = 10, native_type='unsigned long')]],
'AddressSpaceInitialized' : [ 0x248, ['BitField', dict(start_bit = 10, end_bit = 12, native_type='unsigned long')]],
'SetTimerResolution' : [ 0x248, ['BitField', dict(start_bit = 12, end_bit = 13, native_type='unsigned long')]],
'BreakOnTermination' : [ 0x248, ['BitField', dict(start_bit = 13, end_bit = 14, native_type='unsigned long')]],
'SessionCreationUnderway' : [ 0x248, ['BitField', dict(start_bit = 14, end_bit = 15, native_type='unsigned long')]],
'WriteWatch' : [ 0x248, ['BitField', dict(start_bit = 15, end_bit = 16, native_type='unsigned long')]],
'ProcessInSession' : [ 0x248, ['BitField', dict(start_bit = 16, end_bit = 17, native_type='unsigned long')]],
'OverrideAddressSpace' : [ 0x248, ['BitField', dict(start_bit = 17, end_bit = 18, native_type='unsigned long')]],
'HasAddressSpace' : [ 0x248, ['BitField', dict(start_bit = 18, end_bit = 19, native_type='unsigned long')]],
'LaunchPrefetched' : [ 0x248, ['BitField', dict(start_bit = 19, end_bit = 20, native_type='unsigned long')]],
'InjectInpageErrors' : [ 0x248, ['BitField', dict(start_bit = 20, end_bit = 21, native_type='unsigned long')]],
'VmTopDown' : [ 0x248, ['BitField', dict(start_bit = 21, end_bit = 22, native_type='unsigned long')]],
'Unused3' : [ 0x248, ['BitField', dict(start_bit = 22, end_bit = 23, native_type='unsigned long')]],
'Unused4' : [ 0x248, ['BitField', dict(start_bit = 23, end_bit = 24, native_type='unsigned long')]],
'VdmAllowed' : [ 0x248, ['BitField', dict(start_bit = 24, end_bit = 25, native_type='unsigned long')]],
'Unused' : [ 0x248, ['BitField', dict(start_bit = 25, end_bit = 30, native_type='unsigned long')]],
'Unused1' : [ 0x248, ['BitField', dict(start_bit = 30, end_bit = 31, native_type='unsigned long')]],
'Unused2' : [ 0x248, ['BitField', dict(start_bit = 31, end_bit = 32, native_type='unsigned long')]],
'ExitStatus' : [ 0x24c, ['long']],
'NextPageColor' : [ 0x250, ['unsigned short']],
'SubSystemMinorVersion' : [ 0x252, ['unsigned char']],
'SubSystemMajorVersion' : [ 0x253, ['unsigned char']],
'SubSystemVersion' : [ 0x252, ['unsigned short']],
'PriorityClass' : [ 0x254, ['unsigned char']],
'WorkingSetAcquiredUnsafe' : [ 0x255, ['unsigned char']],
'Cookie' : [ 0x258, ['unsigned long']],
} ],
'_OBJECT_ATTRIBUTES' : [ 0x18, {
'Length' : [ 0x0, ['unsigned long']],
'RootDirectory' : [ 0x4, ['pointer', ['void']]],
'ObjectName' : [ 0x8, ['pointer', ['_UNICODE_STRING']]],
'Attributes' : [ 0xc, ['unsigned long']],
'SecurityDescriptor' : [ 0x10, ['pointer', ['void']]],
'SecurityQualityOfService' : [ 0x14, ['pointer', ['void']]],
} ],
'_OBJECT_TYPE' : [ 0x190, {
'Mutex' : [ 0x0, ['_ERESOURCE']],
'TypeList' : [ 0x38, ['_LIST_ENTRY']],
'Name' : [ 0x40, ['_UNICODE_STRING']],
'DefaultObject' : [ 0x48, ['pointer', ['void']]],
'Index' : [ 0x4c, ['unsigned long']],
'TotalNumberOfObjects' : [ 0x50, ['unsigned long']],
'TotalNumberOfHandles' : [ 0x54, ['unsigned long']],
'HighWaterNumberOfObjects' : [ 0x58, ['unsigned long']],
'HighWaterNumberOfHandles' : [ 0x5c, ['unsigned long']],
'TypeInfo' : [ 0x60, ['_OBJECT_TYPE_INITIALIZER']],
'Key' : [ 0xac, ['unsigned long']],
'ObjectLocks' : [ 0xb0, ['array', 4, ['_ERESOURCE']]],
} ],
'_OBJECT_HANDLE_INFORMATION' : [ 0x8, {
'HandleAttributes' : [ 0x0, ['unsigned long']],
'GrantedAccess' : [ 0x4, ['unsigned long']],
} ],
'_KTHREAD' : [ 0x1c0, {
'Header' : [ 0x0, ['_DISPATCHER_HEADER']],
'MutantListHead' : [ 0x10, ['_LIST_ENTRY']],
'InitialStack' : [ 0x18, ['pointer', ['void']]],
'StackLimit' : [ 0x1c, ['pointer', ['void']]],
'Teb' : [ 0x20, ['pointer', ['void']]],
'TlsArray' : [ 0x24, ['pointer', ['void']]],
'KernelStack' : [ 0x28, ['pointer', ['void']]],
'DebugActive' : [ 0x2c, ['unsigned char']],
'State' : [ 0x2d, ['unsigned char']],
'Alerted' : [ 0x2e, ['array', 2, ['unsigned char']]],
'Iopl' : [ 0x30, ['unsigned char']],
'NpxState' : [ 0x31, ['unsigned char']],
'Saturation' : [ 0x32, ['unsigned char']],
'Priority' : [ 0x33, ['unsigned char']],
'ApcState' : [ 0x34, ['_KAPC_STATE']],
'ContextSwitches' : [ 0x4c, ['unsigned long']],
'IdleSwapBlock' : [ 0x50, ['unsigned char']],
'Spare0' : [ 0x51, ['array', 3, ['unsigned char']]],
'WaitStatus' : [ 0x54, ['long']],
'WaitIrql' : [ 0x58, ['unsigned char']],
'WaitMode' : [ 0x59, ['unsigned char']],
'WaitNext' : [ 0x5a, ['unsigned char']],
'WaitReason' : [ 0x5b, ['unsigned char']],
'WaitBlockList' : [ 0x5c, ['pointer', ['_KWAIT_BLOCK']]],
'WaitListEntry' : [ 0x60, ['_LIST_ENTRY']],
'SwapListEntry' : [ 0x60, ['_SINGLE_LIST_ENTRY']],
'WaitTime' : [ 0x68, ['unsigned long']],
'BasePriority' : [ 0x6c, ['unsigned char']],
'DecrementCount' : [ 0x6d, ['unsigned char']],
'PriorityDecrement' : [ 0x6e, ['unsigned char']],
'Quantum' : [ 0x6f, ['unsigned char']],
'WaitBlock' : [ 0x70, ['array', 4, ['_KWAIT_BLOCK']]],
'LegoData' : [ 0xd0, ['pointer', ['void']]],
'KernelApcDisable' : [ 0xd4, ['unsigned long']],
'UserAffinity' : [ 0xd8, ['unsigned long']],
'SystemAffinityActive' : [ 0xdc, ['unsigned char']],
'PowerState' : [ 0xdd, ['unsigned char']],
'NpxIrql' : [ 0xde, ['unsigned char']],
'InitialNode' : [ 0xdf, ['unsigned char']],
'ServiceTable' : [ 0xe0, ['pointer', ['void']]],
'Queue' : [ 0xe4, ['pointer', ['_KQUEUE']]],
'ApcQueueLock' : [ 0xe8, ['unsigned long']],
'Timer' : [ 0xf0, ['_KTIMER']],
'QueueListEntry' : [ 0x118, ['_LIST_ENTRY']],
'SoftAffinity' : [ 0x120, ['unsigned long']],
'Affinity' : [ 0x124, ['unsigned long']],
'Preempted' : [ 0x128, ['unsigned char']],
'ProcessReadyQueue' : [ 0x129, ['unsigned char']],
'KernelStackResident' : [ 0x12a, ['unsigned char']],
'NextProcessor' : [ 0x12b, ['unsigned char']],
'CallbackStack' : [ 0x12c, ['pointer', ['void']]],
'Win32Thread' : [ 0x130, ['pointer', ['void']]],
'TrapFrame' : [ 0x134, ['pointer', ['_KTRAP_FRAME']]],
'ApcStatePointer' : [ 0x138, ['array', 2, ['pointer', ['_KAPC_STATE']]]],
'PreviousMode' : [ 0x140, ['unsigned char']],
'EnableStackSwap' : [ 0x141, ['unsigned char']],
'LargeStack' : [ 0x142, ['unsigned char']],
'ResourceIndex' : [ 0x143, ['unsigned char']],
'KernelTime' : [ 0x144, ['unsigned long']],
'UserTime' : [ 0x148, ['unsigned long']],
'SavedApcState' : [ 0x14c, ['_KAPC_STATE']],
'Alertable' : [ 0x164, ['unsigned char']],
'ApcStateIndex' : [ 0x165, ['unsigned char']],
'ApcQueueable' : [ 0x166, ['unsigned char']],
'AutoAlignment' : [ 0x167, ['unsigned char']],
'StackBase' : [ 0x168, ['pointer', ['void']]],
'SuspendApc' : [ 0x16c, ['_KAPC']],
'SuspendSemaphore' : [ 0x19c, ['_KSEMAPHORE']],
'ThreadListEntry' : [ 0x1b0, ['_LIST_ENTRY']],
'FreezeCount' : [ 0x1b8, ['unsigned char']],
'SuspendCount' : [ 0x1b9, ['unsigned char']],
'IdealProcessor' : [ 0x1ba, ['unsigned char']],
'DisableBoost' : [ 0x1bb, ['unsigned char']],
} ],
'__unnamed_10f2' : [ 0x208, {
'FnArea' : [ 0x0, ['_FNSAVE_FORMAT']],
'FxArea' : [ 0x0, ['_FXSAVE_FORMAT']],
} ],
'_FX_SAVE_AREA' : [ 0x210, {
'U' : [ 0x0, ['__unnamed_10f2']],
'NpxSavedCpu' : [ 0x208, ['unsigned long']],
'Cr0NpxState' : [ 0x20c, ['unsigned long']],
} ],
'__unnamed_10fe' : [ 0x4, {
'Long' : [ 0x0, ['unsigned long']],
'Hard' : [ 0x0, ['_MMPTE_HARDWARE']],
'Flush' : [ 0x0, ['_HARDWARE_PTE']],
'Proto' : [ 0x0, ['_MMPTE_PROTOTYPE']],
'Soft' : [ 0x0, ['_MMPTE_SOFTWARE']],
'Trans' : [ 0x0, ['_MMPTE_TRANSITION']],
'Subsect' : [ 0x0, ['_MMPTE_SUBSECTION']],
'List' : [ 0x0, ['_MMPTE_LIST']],
} ],
'_MMPTE' : [ 0x4, {
'u' : [ 0x0, ['__unnamed_10fe']],
} ],
'_EXCEPTION_RECORD64' : [ 0x98, {
'ExceptionCode' : [ 0x0, ['long']],
'ExceptionFlags' : [ 0x4, ['unsigned long']],
'ExceptionRecord' : [ 0x8, ['unsigned long long']],
'ExceptionAddress' : [ 0x10, ['unsigned long long']],
'NumberParameters' : [ 0x18, ['unsigned long']],
'__unusedAlignment' : [ 0x1c, ['unsigned long']],
'ExceptionInformation' : [ 0x20, ['array', 15, ['unsigned long long']]],
} ],
'_EXCEPTION_RECORD32' : [ 0x50, {
'ExceptionCode' : [ 0x0, ['long']],
'ExceptionFlags' : [ 0x4, ['unsigned long']],
'ExceptionRecord' : [ 0x8, ['unsigned long']],
'ExceptionAddress' : [ 0xc, ['unsigned long']],
'NumberParameters' : [ 0x10, ['unsigned long']],
'ExceptionInformation' : [ 0x14, ['array', 15, ['unsigned long']]],
} ],
'_DBGKM_EXCEPTION64' : [ 0xa0, {
'ExceptionRecord' : [ 0x0, ['_EXCEPTION_RECORD64']],
'FirstChance' : [ 0x98, ['unsigned long']],
} ],
'_DBGKM_EXCEPTION32' : [ 0x54, {
'ExceptionRecord' : [ 0x0, ['_EXCEPTION_RECORD32']],
'FirstChance' : [ 0x50, ['unsigned long']],
} ],
'_DBGKD_LOAD_SYMBOLS64' : [ 0x28, {
'PathNameLength' : [ 0x0, ['unsigned long']],
'BaseOfDll' : [ 0x8, ['unsigned long long']],
'ProcessId' : [ 0x10, ['unsigned long long']],
'CheckSum' : [ 0x18, ['unsigned long']],
'SizeOfImage' : [ 0x1c, ['unsigned long']],
'UnloadSymbols' : [ 0x20, ['unsigned char']],
} ],
'_DBGKD_LOAD_SYMBOLS32' : [ 0x18, {
'PathNameLength' : [ 0x0, ['unsigned long']],
'BaseOfDll' : [ 0x4, ['unsigned long']],
'ProcessId' : [ 0x8, ['unsigned long']],
'CheckSum' : [ 0xc, ['unsigned long']],
'SizeOfImage' : [ 0x10, ['unsigned long']],
'UnloadSymbols' : [ 0x14, ['unsigned char']],
} ],
'_DBGKD_READ_MEMORY64' : [ 0x10, {
'TargetBaseAddress' : [ 0x0, ['unsigned long long']],
'TransferCount' : [ 0x8, ['unsigned long']],
'ActualBytesRead' : [ 0xc, ['unsigned long']],
} ],
'_DBGKD_READ_MEMORY32' : [ 0xc, {
'TargetBaseAddress' : [ 0x0, ['unsigned long']],
'TransferCount' : [ 0x4, ['unsigned long']],
'ActualBytesRead' : [ 0x8, ['unsigned long']],
} ],
'_DBGKD_WRITE_MEMORY64' : [ 0x10, {
'TargetBaseAddress' : [ 0x0, ['unsigned long long']],
'TransferCount' : [ 0x8, ['unsigned long']],
'ActualBytesWritten' : [ 0xc, ['unsigned long']],
} ],
'_DBGKD_WRITE_MEMORY32' : [ 0xc, {
'TargetBaseAddress' : [ 0x0, ['unsigned long']],
'TransferCount' : [ 0x4, ['unsigned long']],
'ActualBytesWritten' : [ 0x8, ['unsigned long']],
} ],
'_DBGKD_WRITE_BREAKPOINT64' : [ 0x10, {
'BreakPointAddress' : [ 0x0, ['unsigned long long']],
'BreakPointHandle' : [ 0x8, ['unsigned long']],
} ],
'_DBGKD_WRITE_BREAKPOINT32' : [ 0x8, {
'BreakPointAddress' : [ 0x0, ['unsigned long']],
'BreakPointHandle' : [ 0x4, ['unsigned long']],
} ],
'_DBGKD_READ_WRITE_IO64' : [ 0x10, {
'IoAddress' : [ 0x0, ['unsigned long long']],
'DataSize' : [ 0x8, ['unsigned long']],
'DataValue' : [ 0xc, ['unsigned long']],
} ],
'_DBGKD_READ_WRITE_IO32' : [ 0xc, {
'DataSize' : [ 0x0, ['unsigned long']],
'IoAddress' : [ 0x4, ['unsigned long']],
'DataValue' : [ 0x8, ['unsigned long']],
} ],
'_DBGKD_READ_WRITE_IO_EXTENDED64' : [ 0x20, {
'DataSize' : [ 0x0, ['unsigned long']],
'InterfaceType' : [ 0x4, ['unsigned long']],
'BusNumber' : [ 0x8, ['unsigned long']],
'AddressSpace' : [ 0xc, ['unsigned long']],
'IoAddress' : [ 0x10, ['unsigned long long']],
'DataValue' : [ 0x18, ['unsigned long']],
} ],
'_DBGKD_READ_WRITE_IO_EXTENDED32' : [ 0x18, {
'DataSize' : [ 0x0, ['unsigned long']],
'InterfaceType' : [ 0x4, ['unsigned long']],
'BusNumber' : [ 0x8, ['unsigned long']],
'AddressSpace' : [ 0xc, ['unsigned long']],
'IoAddress' : [ 0x10, ['unsigned long']],
'DataValue' : [ 0x14, ['unsigned long']],
} ],
'_DBGKD_SET_SPECIAL_CALL32' : [ 0x4, {
'SpecialCall' : [ 0x0, ['unsigned long']],
} ],
'_DBGKD_SET_SPECIAL_CALL64' : [ 0x8, {
'SpecialCall' : [ 0x0, ['unsigned long long']],
} ],
'_DBGKD_SET_INTERNAL_BREAKPOINT32' : [ 0x8, {
'BreakpointAddress' : [ 0x0, ['unsigned long']],
'Flags' : [ 0x4, ['unsigned long']],
} ],
'_DBGKD_SET_INTERNAL_BREAKPOINT64' : [ 0x10, {
'BreakpointAddress' : [ 0x0, ['unsigned long long']],
'Flags' : [ 0x8, ['unsigned long']],
} ],
'_DBGKD_GET_INTERNAL_BREAKPOINT64' : [ 0x20, {
'BreakpointAddress' : [ 0x0, ['unsigned long long']],
'Flags' : [ 0x8, ['unsigned long']],
'Calls' : [ 0xc, ['unsigned long']],
'MaxCallsPerPeriod' : [ 0x10, ['unsigned long']],
'MinInstructions' : [ 0x14, ['unsigned long']],
'MaxInstructions' : [ 0x18, ['unsigned long']],
'TotalInstructions' : [ 0x1c, ['unsigned long']],
} ],
'_DBGKD_GET_INTERNAL_BREAKPOINT32' : [ 0x1c, {
'BreakpointAddress' : [ 0x0, ['unsigned long']],
'Flags' : [ 0x4, ['unsigned long']],
'Calls' : [ 0x8, ['unsigned long']],
'MaxCallsPerPeriod' : [ 0xc, ['unsigned long']],
'MinInstructions' : [ 0x10, ['unsigned long']],
'MaxInstructions' : [ 0x14, ['unsigned long']],
'TotalInstructions' : [ 0x18, ['unsigned long']],
} ],
'__unnamed_116f' : [ 0x28, {
'ReadMemory' : [ 0x0, ['_DBGKD_READ_MEMORY64']],
'WriteMemory' : [ 0x0, ['_DBGKD_WRITE_MEMORY64']],
'GetContext' : [ 0x0, ['_DBGKD_GET_CONTEXT']],
'SetContext' : [ 0x0, ['_DBGKD_SET_CONTEXT']],
'WriteBreakPoint' : [ 0x0, ['_DBGKD_WRITE_BREAKPOINT64']],
'RestoreBreakPoint' : [ 0x0, ['_DBGKD_RESTORE_BREAKPOINT']],
'Continue' : [ 0x0, ['_DBGKD_CONTINUE']],
'Continue2' : [ 0x0, ['_DBGKD_CONTINUE2']],
'ReadWriteIo' : [ 0x0, ['_DBGKD_READ_WRITE_IO64']],
'ReadWriteIoExtended' : [ 0x0, ['_DBGKD_READ_WRITE_IO_EXTENDED64']],
'QuerySpecialCalls' : [ 0x0, ['_DBGKD_QUERY_SPECIAL_CALLS']],
'SetSpecialCall' : [ 0x0, ['_DBGKD_SET_SPECIAL_CALL64']],
'SetInternalBreakpoint' : [ 0x0, ['_DBGKD_SET_INTERNAL_BREAKPOINT64']],
'GetInternalBreakpoint' : [ 0x0, ['_DBGKD_GET_INTERNAL_BREAKPOINT64']],
'GetVersion64' : [ 0x0, ['_DBGKD_GET_VERSION64']],
'BreakPointEx' : [ 0x0, ['_DBGKD_BREAKPOINTEX']],
'ReadWriteMsr' : [ 0x0, ['_DBGKD_READ_WRITE_MSR']],
'SearchMemory' : [ 0x0, ['_DBGKD_SEARCH_MEMORY']],
'GetSetBusData' : [ 0x0, ['_DBGKD_GET_SET_BUS_DATA']],
'FillMemory' : [ 0x0, ['_DBGKD_FILL_MEMORY']],
'QueryMemory' : [ 0x0, ['_DBGKD_QUERY_MEMORY']],
} ],
'_DBGKD_MANIPULATE_STATE64' : [ 0x38, {
'ApiNumber' : [ 0x0, ['unsigned long']],
'ProcessorLevel' : [ 0x4, ['unsigned short']],
'Processor' : [ 0x6, ['unsigned short']],
'ReturnStatus' : [ 0x8, ['long']],
'u' : [ 0x10, ['__unnamed_116f']],
} ],
'__unnamed_1176' : [ 0x28, {
'ReadMemory' : [ 0x0, ['_DBGKD_READ_MEMORY32']],
'WriteMemory' : [ 0x0, ['_DBGKD_WRITE_MEMORY32']],
'ReadMemory64' : [ 0x0, ['_DBGKD_READ_MEMORY64']],
'WriteMemory64' : [ 0x0, ['_DBGKD_WRITE_MEMORY64']],
'GetContext' : [ 0x0, ['_DBGKD_GET_CONTEXT']],
'SetContext' : [ 0x0, ['_DBGKD_SET_CONTEXT']],
'WriteBreakPoint' : [ 0x0, ['_DBGKD_WRITE_BREAKPOINT32']],
'RestoreBreakPoint' : [ 0x0, ['_DBGKD_RESTORE_BREAKPOINT']],
'Continue' : [ 0x0, ['_DBGKD_CONTINUE']],
'Continue2' : [ 0x0, ['_DBGKD_CONTINUE2']],
'ReadWriteIo' : [ 0x0, ['_DBGKD_READ_WRITE_IO32']],
'ReadWriteIoExtended' : [ 0x0, ['_DBGKD_READ_WRITE_IO_EXTENDED32']],
'QuerySpecialCalls' : [ 0x0, ['_DBGKD_QUERY_SPECIAL_CALLS']],
'SetSpecialCall' : [ 0x0, ['_DBGKD_SET_SPECIAL_CALL32']],
'SetInternalBreakpoint' : [ 0x0, ['_DBGKD_SET_INTERNAL_BREAKPOINT32']],
'GetInternalBreakpoint' : [ 0x0, ['_DBGKD_GET_INTERNAL_BREAKPOINT32']],
'GetVersion32' : [ 0x0, ['_DBGKD_GET_VERSION32']],
'BreakPointEx' : [ 0x0, ['_DBGKD_BREAKPOINTEX']],
'ReadWriteMsr' : [ 0x0, ['_DBGKD_READ_WRITE_MSR']],
'SearchMemory' : [ 0x0, ['_DBGKD_SEARCH_MEMORY']],
} ],
'_DBGKD_MANIPULATE_STATE32' : [ 0x34, {
'ApiNumber' : [ 0x0, ['unsigned long']],
'ProcessorLevel' : [ 0x4, ['unsigned short']],
'Processor' : [ 0x6, ['unsigned short']],
'ReturnStatus' : [ 0x8, ['long']],
'u' : [ 0xc, ['__unnamed_1176']],
} ],
'__unnamed_117f' : [ 0x8, {
'FileOffset' : [ 0x0, ['_LARGE_INTEGER']],
'ActiveCount' : [ 0x0, ['unsigned short']],
} ],
'_VACB' : [ 0x18, {
'BaseAddress' : [ 0x0, ['pointer', ['void']]],
'SharedCacheMap' : [ 0x4, ['pointer', ['_SHARED_CACHE_MAP']]],
'Overlay' : [ 0x8, ['__unnamed_117f']],
'LruList' : [ 0x10, ['_LIST_ENTRY']],
} ],
'_SHARED_CACHE_MAP' : [ 0x130, {
'NodeTypeCode' : [ 0x0, ['short']],
'NodeByteSize' : [ 0x2, ['short']],
'OpenCount' : [ 0x4, ['unsigned long']],
'FileSize' : [ 0x8, ['_LARGE_INTEGER']],
'BcbList' : [ 0x10, ['_LIST_ENTRY']],
'SectionSize' : [ 0x18, ['_LARGE_INTEGER']],
'ValidDataLength' : [ 0x20, ['_LARGE_INTEGER']],
'ValidDataGoal' : [ 0x28, ['_LARGE_INTEGER']],
'InitialVacbs' : [ 0x30, ['array', 4, ['pointer', ['_VACB']]]],
'Vacbs' : [ 0x40, ['pointer', ['pointer', ['_VACB']]]],
'FileObject' : [ 0x44, ['pointer', ['_FILE_OBJECT']]],
'ActiveVacb' : [ 0x48, ['pointer', ['_VACB']]],
'NeedToZero' : [ 0x4c, ['pointer', ['void']]],
'ActivePage' : [ 0x50, ['unsigned long']],
'NeedToZeroPage' : [ 0x54, ['unsigned long']],
'ActiveVacbSpinLock' : [ 0x58, ['unsigned long']],
'VacbActiveCount' : [ 0x5c, ['unsigned long']],
'DirtyPages' : [ 0x60, ['unsigned long']],
'SharedCacheMapLinks' : [ 0x64, ['_LIST_ENTRY']],
'Flags' : [ 0x6c, ['unsigned long']],
'Status' : [ 0x70, ['long']],
'Mbcb' : [ 0x74, ['pointer', ['_MBCB']]],
'Section' : [ 0x78, ['pointer', ['void']]],
'CreateEvent' : [ 0x7c, ['pointer', ['_KEVENT']]],
'WaitOnActiveCount' : [ 0x80, ['pointer', ['_KEVENT']]],
'PagesToWrite' : [ 0x84, ['unsigned long']],
'BeyondLastFlush' : [ 0x88, ['long long']],
'Callbacks' : [ 0x90, ['pointer', ['_CACHE_MANAGER_CALLBACKS']]],
'LazyWriteContext' : [ 0x94, ['pointer', ['void']]],
'PrivateList' : [ 0x98, ['_LIST_ENTRY']],
'LogHandle' : [ 0xa0, ['pointer', ['void']]],
'FlushToLsnRoutine' : [ 0xa4, ['pointer', ['void']]],
'DirtyPageThreshold' : [ 0xa8, ['unsigned long']],
'LazyWritePassCount' : [ 0xac, ['unsigned long']],
'UninitializeEvent' : [ 0xb0, ['pointer', ['_CACHE_UNINITIALIZE_EVENT']]],
'NeedToZeroVacb' : [ 0xb4, ['pointer', ['_VACB']]],
'BcbSpinLock' : [ 0xb8, ['unsigned long']],
'Reserved' : [ 0xbc, ['pointer', ['void']]],
'Event' : [ 0xc0, ['_KEVENT']],
'VacbPushLock' : [ 0xd0, ['_EX_PUSH_LOCK']],
'PrivateCacheMap' : [ 0xd8, ['_PRIVATE_CACHE_MAP']],
} ],
'_VACB_LEVEL_REFERENCE' : [ 0x8, {
'Reference' : [ 0x0, ['long']],
'SpecialReference' : [ 0x4, ['long']],
} ],
'_HEAP_ENTRY' : [ 0x8, {
'Size' : [ 0x0, ['unsigned short']],
'PreviousSize' : [ 0x2, ['unsigned short']],
'SubSegmentCode' : [ 0x0, ['pointer', ['void']]],
'SmallTagIndex' : [ 0x4, ['unsigned char']],
'Flags' : [ 0x5, ['unsigned char']],
'UnusedBytes' : [ 0x6, ['unsigned char']],
'SegmentIndex' : [ 0x7, ['unsigned char']],
} ],
'__unnamed_11a9' : [ 0x10, {
'FreeListsInUseUlong' : [ 0x0, ['array', 4, ['unsigned long']]],
'FreeListsInUseBytes' : [ 0x0, ['array', 16, ['unsigned char']]],
} ],
'__unnamed_11ab' : [ 0x2, {
'FreeListsInUseTerminate' : [ 0x0, ['unsigned short']],
'DecommitCount' : [ 0x0, ['unsigned short']],
} ],
'_HEAP' : [ 0x588, {
'Entry' : [ 0x0, ['_HEAP_ENTRY']],
'Signature' : [ 0x8, ['unsigned long']],
'Flags' : [ 0xc, ['unsigned long']],
'ForceFlags' : [ 0x10, ['unsigned long']],
'VirtualMemoryThreshold' : [ 0x14, ['unsigned long']],
'SegmentReserve' : [ 0x18, ['unsigned long']],
'SegmentCommit' : [ 0x1c, ['unsigned long']],
'DeCommitFreeBlockThreshold' : [ 0x20, ['unsigned long']],
'DeCommitTotalFreeThreshold' : [ 0x24, ['unsigned long']],
'TotalFreeSize' : [ 0x28, ['unsigned long']],
'MaximumAllocationSize' : [ 0x2c, ['unsigned long']],
'ProcessHeapsListIndex' : [ 0x30, ['unsigned short']],
'HeaderValidateLength' : [ 0x32, ['unsigned short']],
'HeaderValidateCopy' : [ 0x34, ['pointer', ['void']]],
'NextAvailableTagIndex' : [ 0x38, ['unsigned short']],
'MaximumTagIndex' : [ 0x3a, ['unsigned short']],
'TagEntries' : [ 0x3c, ['pointer', ['_HEAP_TAG_ENTRY']]],
'UCRSegments' : [ 0x40, ['pointer', ['_HEAP_UCR_SEGMENT']]],
'UnusedUnCommittedRanges' : [ 0x44, ['pointer', ['_HEAP_UNCOMMMTTED_RANGE']]],
'AlignRound' : [ 0x48, ['unsigned long']],
'AlignMask' : [ 0x4c, ['unsigned long']],
'VirtualAllocdBlocks' : [ 0x50, ['_LIST_ENTRY']],
'Segments' : [ 0x58, ['array', 64, ['pointer', ['_HEAP_SEGMENT']]]],
'u' : [ 0x158, ['__unnamed_11a9']],
'u2' : [ 0x168, ['__unnamed_11ab']],
'AllocatorBackTraceIndex' : [ 0x16a, ['unsigned short']],
'NonDedicatedListLength' : [ 0x16c, ['unsigned long']],
'LargeBlocksIndex' : [ 0x170, ['pointer', ['void']]],
'PseudoTagEntries' : [ 0x174, ['pointer', ['_HEAP_PSEUDO_TAG_ENTRY']]],
'FreeLists' : [ 0x178, ['array', 128, ['_LIST_ENTRY']]],
'LockVariable' : [ 0x578, ['pointer', ['_HEAP_LOCK']]],
'CommitRoutine' : [ 0x57c, ['pointer', ['void']]],
'FrontEndHeap' : [ 0x580, ['pointer', ['void']]],
'FrontHeapLockCount' : [ 0x584, ['unsigned short']],
'FrontEndHeapType' : [ 0x586, ['unsigned char']],
'LastSegmentIndex' : [ 0x587, ['unsigned char']],
} ],
'_HEAP_SEGMENT' : [ 0x3c, {
'Entry' : [ 0x0, ['_HEAP_ENTRY']],
'Signature' : [ 0x8, ['unsigned long']],
'Flags' : [ 0xc, ['unsigned long']],
'Heap' : [ 0x10, ['pointer', ['_HEAP']]],
'LargestUnCommittedRange' : [ 0x14, ['unsigned long']],
'BaseAddress' : [ 0x18, ['pointer', ['void']]],
'NumberOfPages' : [ 0x1c, ['unsigned long']],
'FirstEntry' : [ 0x20, ['pointer', ['_HEAP_ENTRY']]],
'LastValidEntry' : [ 0x24, ['pointer', ['_HEAP_ENTRY']]],
'NumberOfUnCommittedPages' : [ 0x28, ['unsigned long']],
'NumberOfUnCommittedRanges' : [ 0x2c, ['unsigned long']],
'UnCommittedRanges' : [ 0x30, ['pointer', ['_HEAP_UNCOMMMTTED_RANGE']]],
'AllocatorBackTraceIndex' : [ 0x34, ['unsigned short']],
'Reserved' : [ 0x36, ['unsigned short']],
'LastEntryInSegment' : [ 0x38, ['pointer', ['_HEAP_ENTRY']]],
} ],
'_HEAP_SUBSEGMENT' : [ 0x20, {
'Bucket' : [ 0x0, ['pointer', ['void']]],
'UserBlocks' : [ 0x4, ['pointer', ['_HEAP_USERDATA_HEADER']]],
'AggregateExchg' : [ 0x8, ['_INTERLOCK_SEQ']],
'BlockSize' : [ 0x10, ['unsigned short']],
'FreeThreshold' : [ 0x12, ['unsigned short']],
'BlockCount' : [ 0x14, ['unsigned short']],
'SizeIndex' : [ 0x16, ['unsigned char']],
'AffinityIndex' : [ 0x17, ['unsigned char']],
'Alignment' : [ 0x10, ['array', 2, ['unsigned long']]],
'SFreeListEntry' : [ 0x18, ['_SINGLE_LIST_ENTRY']],
'Lock' : [ 0x1c, ['unsigned long']],
} ],
'_HEAP_UCR_SEGMENT' : [ 0x10, {
'Next' : [ 0x0, ['pointer', ['_HEAP_UCR_SEGMENT']]],
'ReservedSize' : [ 0x4, ['unsigned long']],
'CommittedSize' : [ 0x8, ['unsigned long']],
'filler' : [ 0xc, ['unsigned long']],
} ],
'_HMAP_TABLE' : [ 0x2000, {
'Table' : [ 0x0, ['array', 512, ['_HMAP_ENTRY']]],
} ],
'_OBJECT_SYMBOLIC_LINK' : [ 0x20, {
'CreationTime' : [ 0x0, ['_LARGE_INTEGER']],
'LinkTarget' : [ 0x8, ['_UNICODE_STRING']],
'LinkTargetRemaining' : [ 0x10, ['_UNICODE_STRING']],
'LinkTargetObject' : [ 0x18, ['pointer', ['void']]],
'DosDeviceDriveIndex' : [ 0x1c, ['unsigned long']],
} ],
'_POOL_BLOCK_HEAD' : [ 0x10, {
'Header' : [ 0x0, ['_POOL_HEADER']],
'List' : [ 0x8, ['_LIST_ENTRY']],
} ],
'_DISPATCHER_HEADER' : [ 0x10, {
'Type' : [ 0x0, ['unsigned char']],
'Absolute' : [ 0x1, ['unsigned char']],
'Size' : [ 0x2, ['unsigned char']],
'Inserted' : [ 0x3, ['unsigned char']],
'SignalState' : [ 0x4, ['long']],
'WaitListHead' : [ 0x8, ['_LIST_ENTRY']],
} ],
'_LDR_DATA_TABLE_ENTRY' : [ 0x50, {
'InLoadOrderLinks' : [ 0x0, ['_LIST_ENTRY']],
'InMemoryOrderLinks' : [ 0x8, ['_LIST_ENTRY']],
'InInitializationOrderLinks' : [ 0x10, ['_LIST_ENTRY']],
'DllBase' : [ 0x18, ['pointer', ['void']]],
'EntryPoint' : [ 0x1c, ['pointer', ['void']]],
'SizeOfImage' : [ 0x20, ['unsigned long']],
'FullDllName' : [ 0x24, ['_UNICODE_STRING']],
'BaseDllName' : [ 0x2c, ['_UNICODE_STRING']],
'Flags' : [ 0x34, ['unsigned long']],
'LoadCount' : [ 0x38, ['unsigned short']],
'TlsIndex' : [ 0x3a, ['unsigned short']],
'HashLinks' : [ 0x3c, ['_LIST_ENTRY']],
'SectionPointer' : [ 0x3c, ['pointer', ['void']]],
'CheckSum' : [ 0x40, ['unsigned long']],
'TimeDateStamp' : [ 0x44, ['unsigned long']],
'LoadedImports' : [ 0x44, ['pointer', ['void']]],
'EntryPointActivationContext' : [ 0x48, ['pointer', ['void']]],
'PatchInformation' : [ 0x4c, ['pointer', ['void']]],
} ],
'_HEAP_UNCOMMMTTED_RANGE' : [ 0x10, {
'Next' : [ 0x0, ['pointer', ['_HEAP_UNCOMMMTTED_RANGE']]],
'Address' : [ 0x4, ['unsigned long']],
'Size' : [ 0x8, ['unsigned long']],
'filler' : [ 0xc, ['unsigned long']],
} ],
'_VI_DEADLOCK_GLOBALS' : [ 0x110, {
'Nodes' : [ 0x0, ['array', 2, ['unsigned long']]],
'Resources' : [ 0x8, ['array', 2, ['unsigned long']]],
'Threads' : [ 0x10, ['array', 2, ['unsigned long']]],
'TimeAcquire' : [ 0x18, ['long long']],
'TimeRelease' : [ 0x20, ['long long']],
'BytesAllocated' : [ 0x28, ['unsigned long']],
'ResourceDatabase' : [ 0x2c, ['pointer', ['_LIST_ENTRY']]],
'ThreadDatabase' : [ 0x30, ['pointer', ['_LIST_ENTRY']]],
'AllocationFailures' : [ 0x34, ['unsigned long']],
'NodesTrimmedBasedOnAge' : [ 0x38, ['unsigned long']],
'NodesTrimmedBasedOnCount' : [ 0x3c, ['unsigned long']],
'NodesSearched' : [ 0x40, ['unsigned long']],
'MaxNodesSearched' : [ 0x44, ['unsigned long']],
'SequenceNumber' : [ 0x48, ['unsigned long']],
'RecursionDepthLimit' : [ 0x4c, ['unsigned long']],
'SearchedNodesLimit' : [ 0x50, ['unsigned long']],
'DepthLimitHits' : [ 0x54, ['unsigned long']],
'SearchLimitHits' : [ 0x58, ['unsigned long']],
'ABC_ACB_Skipped' : [ 0x5c, ['unsigned long']],
'FreeResourceList' : [ 0x60, ['_LIST_ENTRY']],
'FreeThreadList' : [ 0x68, ['_LIST_ENTRY']],
'FreeNodeList' : [ 0x70, ['_LIST_ENTRY']],
'FreeResourceCount' : [ 0x78, ['unsigned long']],
'FreeThreadCount' : [ 0x7c, ['unsigned long']],
'FreeNodeCount' : [ 0x80, ['unsigned long']],
'Instigator' : [ 0x84, ['pointer', ['void']]],
'NumberOfParticipants' : [ 0x88, ['unsigned long']],
'Participant' : [ 0x8c, ['array', 32, ['pointer', ['_VI_DEADLOCK_NODE']]]],
'CacheReductionInProgress' : [ 0x10c, ['unsigned long']],
} ],
'_THERMAL_INFORMATION' : [ 0x4c, {
'ThermalStamp' : [ 0x0, ['unsigned long']],
'ThermalConstant1' : [ 0x4, ['unsigned long']],
'ThermalConstant2' : [ 0x8, ['unsigned long']],
'Processors' : [ 0xc, ['unsigned long']],
'SamplingPeriod' : [ 0x10, ['unsigned long']],
'CurrentTemperature' : [ 0x14, ['unsigned long']],
'PassiveTripPoint' : [ 0x18, ['unsigned long']],
'CriticalTripPoint' : [ 0x1c, ['unsigned long']],
'ActiveTripPointCount' : [ 0x20, ['unsigned char']],
'ActiveTripPoint' : [ 0x24, ['array', 10, ['unsigned long']]],
} ],
'_DBGKD_SEARCH_MEMORY' : [ 0x18, {
'SearchAddress' : [ 0x0, ['unsigned long long']],
'FoundAddress' : [ 0x0, ['unsigned long long']],
'SearchLength' : [ 0x8, ['unsigned long long']],
'PatternLength' : [ 0x10, ['unsigned long']],
} ],
'_SECTION_OBJECT' : [ 0x18, {
'StartingVa' : [ 0x0, ['pointer', ['void']]],
'EndingVa' : [ 0x4, ['pointer', ['void']]],
'Parent' : [ 0x8, ['pointer', ['void']]],
'LeftChild' : [ 0xc, ['pointer', ['void']]],
'RightChild' : [ 0x10, ['pointer', ['void']]],
'Segment' : [ 0x14, ['pointer', ['_SEGMENT_OBJECT']]],
} ],
'_POWER_STATE' : [ 0x4, {
'SystemState' : [ 0x0, ['Enumeration', dict(target = 'long', choices = {0: 'PowerSystemUnspecified', 1: 'PowerSystemWorking', 2: 'PowerSystemSleeping1', 3: 'PowerSystemSleeping2', 4: 'PowerSystemSleeping3', 5: 'PowerSystemHibernate', 6: 'PowerSystemShutdown', 7: 'PowerSystemMaximum'})]],
'DeviceState' : [ 0x0, ['Enumeration', dict(target = 'long', choices = {0: 'PowerDeviceUnspecified', 1: 'PowerDeviceD0', 2: 'PowerDeviceD1', 3: 'PowerDeviceD2', 4: 'PowerDeviceD3', 5: 'PowerDeviceMaximum'})]],
} ],
'_WMI_LOGGER_CONTEXT' : [ 0x1c8, {
'BufferSpinLock' : [ 0x0, ['unsigned long']],
'StartTime' : [ 0x8, ['_LARGE_INTEGER']],
'LogFileHandle' : [ 0x10, ['pointer', ['void']]],
'LoggerSemaphore' : [ 0x14, ['_KSEMAPHORE']],
'LoggerThread' : [ 0x28, ['pointer', ['_ETHREAD']]],
'LoggerEvent' : [ 0x2c, ['_KEVENT']],
'FlushEvent' : [ 0x3c, ['_KEVENT']],
'LoggerStatus' : [ 0x4c, ['long']],
'LoggerId' : [ 0x50, ['unsigned long']],
'BuffersAvailable' : [ 0x54, ['long']],
'UsePerfClock' : [ 0x58, ['unsigned long']],
'WriteFailureLimit' : [ 0x5c, ['unsigned long']],
'BuffersDirty' : [ 0x60, ['unsigned long']],
'BuffersInUse' : [ 0x64, ['unsigned long']],
'SwitchingInProgress' : [ 0x68, ['unsigned long']],
'FreeList' : [ 0x70, ['_SLIST_HEADER']],
'FlushList' : [ 0x78, ['_SLIST_HEADER']],
'GlobalList' : [ 0x80, ['_SLIST_HEADER']],
'ProcessorBuffers' : [ 0x88, ['pointer', ['_SLIST_HEADER']]],
'LoggerName' : [ 0x8c, ['_UNICODE_STRING']],
'LogFileName' : [ 0x94, ['_UNICODE_STRING']],
'LogFilePattern' : [ 0x9c, ['_UNICODE_STRING']],
'NewLogFileName' : [ 0xa4, ['_UNICODE_STRING']],
'EndPageMarker' : [ 0xac, ['pointer', ['unsigned char']]],
'CollectionOn' : [ 0xb0, ['long']],
'KernelTraceOn' : [ 0xb4, ['unsigned long']],
'PerfLogInTransition' : [ 0xb8, ['long']],
'RequestFlag' : [ 0xbc, ['unsigned long']],
'EnableFlags' : [ 0xc0, ['unsigned long']],
'MaximumFileSize' : [ 0xc4, ['unsigned long']],
'LoggerMode' : [ 0xc8, ['unsigned long']],
'LoggerModeFlags' : [ 0xc8, ['_WMI_LOGGER_MODE']],
'LastFlushedBuffer' : [ 0xcc, ['unsigned long']],
'RefCount' : [ 0xd0, ['unsigned long']],
'FlushTimer' : [ 0xd4, ['unsigned long']],
'FirstBufferOffset' : [ 0xd8, ['_LARGE_INTEGER']],
'ByteOffset' : [ 0xe0, ['_LARGE_INTEGER']],
'BufferAgeLimit' : [ 0xe8, ['_LARGE_INTEGER']],
'MaximumBuffers' : [ 0xf0, ['unsigned long']],
'MinimumBuffers' : [ 0xf4, ['unsigned long']],
'EventsLost' : [ 0xf8, ['unsigned long']],
'BuffersWritten' : [ 0xfc, ['unsigned long']],
'LogBuffersLost' : [ 0x100, ['unsigned long']],
'RealTimeBuffersLost' : [ 0x104, ['unsigned long']],
'BufferSize' : [ 0x108, ['unsigned long']],
'NumberOfBuffers' : [ 0x10c, ['long']],
'SequencePtr' : [ 0x110, ['pointer', ['long']]],
'InstanceGuid' : [ 0x114, ['_GUID']],
'LoggerHeader' : [ 0x124, ['pointer', ['void']]],
'GetCpuClock' : [ 0x128, ['pointer', ['void']]],
'ClientSecurityContext' : [ 0x12c, ['_SECURITY_CLIENT_CONTEXT']],
'LoggerExtension' : [ 0x168, ['pointer', ['void']]],
'ReleaseQueue' : [ 0x16c, ['long']],
'EnableFlagExtension' : [ 0x170, ['_TRACE_ENABLE_FLAG_EXTENSION']],
'LocalSequence' : [ 0x174, ['unsigned long']],
'MaximumIrql' : [ 0x178, ['unsigned long']],
'EnableFlagArray' : [ 0x17c, ['pointer', ['unsigned long']]],
'LoggerMutex' : [ 0x180, ['_KMUTANT']],
'MutexCount' : [ 0x1a0, ['long']],
'FileCounter' : [ 0x1a4, ['unsigned long']],
'BufferCallback' : [ 0x1a8, ['pointer', ['void']]],
'CallbackContext' : [ 0x1ac, ['pointer', ['void']]],
'PoolType' : [ 0x1b0, ['Enumeration', dict(target = 'long', choices = {0: 'NonPagedPool', 1: 'PagedPool', 2: 'NonPagedPoolMustSucceed', 3: 'DontUseThisType', 4: 'NonPagedPoolCacheAligned', 5: 'PagedPoolCacheAligned', 6: 'NonPagedPoolCacheAlignedMustS', 7: 'MaxPoolType', 34: 'NonPagedPoolMustSucceedSession', 35: 'DontUseThisTypeSession', 32: 'NonPagedPoolSession', 36: 'NonPagedPoolCacheAlignedSession', 33: 'PagedPoolSession', 38: 'NonPagedPoolCacheAlignedMustSSession', 37: 'PagedPoolCacheAlignedSession'})]],
'ReferenceSystemTime' : [ 0x1b8, ['_LARGE_INTEGER']],
'ReferenceTimeStamp' : [ 0x1c0, ['_LARGE_INTEGER']],
} ],
'_SEGMENT_OBJECT' : [ 0x30, {
'BaseAddress' : [ 0x0, ['pointer', ['void']]],
'TotalNumberOfPtes' : [ 0x4, ['unsigned long']],
'SizeOfSegment' : [ 0x8, ['_LARGE_INTEGER']],
'NonExtendedPtes' : [ 0x10, ['unsigned long']],
'ImageCommitment' : [ 0x14, ['unsigned long']],
'ControlArea' : [ 0x18, ['pointer', ['_CONTROL_AREA']]],
'Subsection' : [ 0x1c, ['pointer', ['_SUBSECTION']]],
'LargeControlArea' : [ 0x20, ['pointer', ['_LARGE_CONTROL_AREA']]],
'MmSectionFlags' : [ 0x24, ['pointer', ['_MMSECTION_FLAGS']]],
'MmSubSectionFlags' : [ 0x28, ['pointer', ['_MMSUBSECTION_FLAGS']]],
} ],
'__unnamed_123f' : [ 0x4, {
'LongFlags' : [ 0x0, ['unsigned long']],
'Flags' : [ 0x0, ['_MMSECTION_FLAGS']],
} ],
'_CONTROL_AREA' : [ 0x30, {
'Segment' : [ 0x0, ['pointer', ['_SEGMENT']]],
'DereferenceList' : [ 0x4, ['_LIST_ENTRY']],
'NumberOfSectionReferences' : [ 0xc, ['unsigned long']],
'NumberOfPfnReferences' : [ 0x10, ['unsigned long']],
'NumberOfMappedViews' : [ 0x14, ['unsigned long']],
'NumberOfSubsections' : [ 0x18, ['unsigned short']],
'FlushInProgressCount' : [ 0x1a, ['unsigned short']],
'NumberOfUserReferences' : [ 0x1c, ['unsigned long']],
'u' : [ 0x20, ['__unnamed_123f']],
'FilePointer' : [ 0x24, ['pointer', ['_FILE_OBJECT']]],
'WaitingForDeletion' : [ 0x28, ['pointer', ['_EVENT_COUNTER']]],
'ModifiedWriteCount' : [ 0x2c, ['unsigned short']],
'NumberOfSystemCacheViews' : [ 0x2e, ['unsigned short']],
} ],
'_HANDLE_TABLE' : [ 0x44, {
'TableCode' : [ 0x0, ['unsigned long']],
'QuotaProcess' : [ 0x4, ['pointer', ['_EPROCESS']]],
'UniqueProcessId' : [ 0x8, ['pointer', ['void']]],
'HandleTableLock' : [ 0xc, ['array', 4, ['_EX_PUSH_LOCK']]],
'HandleTableList' : [ 0x1c, ['_LIST_ENTRY']],
'HandleContentionEvent' : [ 0x24, ['_EX_PUSH_LOCK']],
'DebugInfo' : [ 0x28, ['pointer', ['_HANDLE_TRACE_DEBUG_INFO']]],
'ExtraInfoPages' : [ 0x2c, ['long']],
'FirstFree' : [ 0x30, ['unsigned long']],
'LastFree' : [ 0x34, ['unsigned long']],
'NextHandleNeedingPool' : [ 0x38, ['unsigned long']],
'HandleCount' : [ 0x3c, ['long']],
'Flags' : [ 0x40, ['unsigned long']],
'StrictFIFO' : [ 0x40, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned char')]],
} ],
'_POOL_HEADER' : [ 0x8, {
'PreviousSize' : [ 0x0, ['BitField', dict(start_bit = 0, end_bit = 9, native_type='unsigned short')]],
'PoolIndex' : [ 0x0, ['BitField', dict(start_bit = 9, end_bit = 16, native_type='unsigned short')]],
'BlockSize' : [ 0x2, ['BitField', dict(start_bit = 0, end_bit = 9, native_type='unsigned short')]],
'PoolType' : [ 0x2, ['BitField', dict(start_bit = 9, end_bit = 16, native_type='unsigned short')]],
'Ulong1' : [ 0x0, ['unsigned long']],
'ProcessBilled' : [ 0x4, ['pointer', ['_EPROCESS']]],
'PoolTag' : [ 0x4, ['unsigned long']],
'AllocatorBackTraceIndex' : [ 0x4, ['unsigned short']],
'PoolTagHash' : [ 0x6, ['unsigned short']],
} ],
'_KWAIT_BLOCK' : [ 0x18, {
'WaitListEntry' : [ 0x0, ['_LIST_ENTRY']],
'Thread' : [ 0x8, ['pointer', ['_KTHREAD']]],
'Object' : [ 0xc, ['pointer', ['void']]],
'NextWaitBlock' : [ 0x10, ['pointer', ['_KWAIT_BLOCK']]],
'WaitKey' : [ 0x14, ['unsigned short']],
'WaitType' : [ 0x16, ['unsigned short']],
} ],
'_MMPTE_PROTOTYPE' : [ 0x4, {
'Valid' : [ 0x0, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned long')]],
'ProtoAddressLow' : [ 0x0, ['BitField', dict(start_bit = 1, end_bit = 8, native_type='unsigned long')]],
'ReadOnly' : [ 0x0, ['BitField', dict(start_bit = 8, end_bit = 9, native_type='unsigned long')]],
'WhichPool' : [ 0x0, ['BitField', dict(start_bit = 9, end_bit = 10, native_type='unsigned long')]],
'Prototype' : [ 0x0, ['BitField', dict(start_bit = 10, end_bit = 11, native_type='unsigned long')]],
'ProtoAddressHigh' : [ 0x0, ['BitField', dict(start_bit = 11, end_bit = 32, native_type='unsigned long')]],
} ],
'_MMSUPPORT' : [ 0x40, {
'LastTrimTime' : [ 0x0, ['_LARGE_INTEGER']],
'Flags' : [ 0x8, ['_MMSUPPORT_FLAGS']],
'PageFaultCount' : [ 0xc, ['unsigned long']],
'PeakWorkingSetSize' : [ 0x10, ['unsigned long']],
'WorkingSetSize' : [ 0x14, ['unsigned long']],
'MinimumWorkingSetSize' : [ 0x18, ['unsigned long']],
'MaximumWorkingSetSize' : [ 0x1c, ['unsigned long']],
'VmWorkingSetList' : [ 0x20, ['pointer', ['_MMWSL']]],
'WorkingSetExpansionLinks' : [ 0x24, ['_LIST_ENTRY']],
'Claim' : [ 0x2c, ['unsigned long']],
'NextEstimationSlot' : [ 0x30, ['unsigned long']],
'NextAgingSlot' : [ 0x34, ['unsigned long']],
'EstimatedAvailable' : [ 0x38, ['unsigned long']],
'GrowthSinceLastEstimate' : [ 0x3c, ['unsigned long']],
} ],
'_EX_WORK_QUEUE' : [ 0x3c, {
'WorkerQueue' : [ 0x0, ['_KQUEUE']],
'DynamicThreadCount' : [ 0x28, ['unsigned long']],
'WorkItemsProcessed' : [ 0x2c, ['unsigned long']],
'WorkItemsProcessedLastPass' : [ 0x30, ['unsigned long']],
'QueueDepthLastPass' : [ 0x34, ['unsigned long']],
'Info' : [ 0x38, ['EX_QUEUE_WORKER_INFO']],
} ],
'_MMSUBSECTION_FLAGS' : [ 0x4, {
'ReadOnly' : [ 0x0, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned long')]],
'ReadWrite' : [ 0x0, ['BitField', dict(start_bit = 1, end_bit = 2, native_type='unsigned long')]],
'SubsectionStatic' : [ 0x0, ['BitField', dict(start_bit = 2, end_bit = 3, native_type='unsigned long')]],
'GlobalMemory' : [ 0x0, ['BitField', dict(start_bit = 3, end_bit = 4, native_type='unsigned long')]],
'Protection' : [ 0x0, ['BitField', dict(start_bit = 4, end_bit = 9, native_type='unsigned long')]],
'LargePages' : [ 0x0, ['BitField', dict(start_bit = 9, end_bit = 10, native_type='unsigned long')]],
'StartingSector4132' : [ 0x0, ['BitField', dict(start_bit = 10, end_bit = 20, native_type='unsigned long')]],
'SectorEndOffset' : [ 0x0, ['BitField', dict(start_bit = 20, end_bit = 32, native_type='unsigned long')]],
} ],
'_KMUTANT' : [ 0x20, {
'Header' : [ 0x0, ['_DISPATCHER_HEADER']],
'MutantListEntry' : [ 0x10, ['_LIST_ENTRY']],
'OwnerThread' : [ 0x18, ['pointer', ['_KTHREAD']]],
'Abandoned' : [ 0x1c, ['unsigned char']],
'ApcDisable' : [ 0x1d, ['unsigned char']],
} ],
'_HEAP_TAG_ENTRY' : [ 0x40, {
'Allocs' : [ 0x0, ['unsigned long']],
'Frees' : [ 0x4, ['unsigned long']],
'Size' : [ 0x8, ['unsigned long']],
'TagIndex' : [ 0xc, ['unsigned short']],
'CreatorBackTraceIndex' : [ 0xe, ['unsigned short']],
'TagName' : [ 0x10, ['array', 24, ['unsigned short']]],
} ],
'_KEVENT' : [ 0x10, {
'Header' : [ 0x0, ['_DISPATCHER_HEADER']],
} ],
'_EPROCESS_QUOTA_BLOCK' : [ 0x40, {
'QuotaEntry' : [ 0x0, ['array', 3, ['_EPROCESS_QUOTA_ENTRY']]],
'QuotaList' : [ 0x30, ['_LIST_ENTRY']],
'ReferenceCount' : [ 0x38, ['unsigned long']],
'ProcessCount' : [ 0x3c, ['unsigned long']],
} ],
'_UNICODE_STRING' : [ 0x8, {
'Length' : [ 0x0, ['unsigned short']],
'MaximumLength' : [ 0x2, ['unsigned short']],
'Buffer' : [ 0x4, ['pointer', ['unsigned short']]],
} ],
'_EVENT_COUNTER' : [ 0x18, {
'ListEntry' : [ 0x0, ['_SINGLE_LIST_ENTRY']],
'RefCount' : [ 0x4, ['unsigned long']],
'Event' : [ 0x8, ['_KEVENT']],
} ],
'_EJOB' : [ 0x180, {
'Event' : [ 0x0, ['_KEVENT']],
'JobLinks' : [ 0x10, ['_LIST_ENTRY']],
'ProcessListHead' : [ 0x18, ['_LIST_ENTRY']],
'JobLock' : [ 0x20, ['_ERESOURCE']],
'TotalUserTime' : [ 0x58, ['_LARGE_INTEGER']],
'TotalKernelTime' : [ 0x60, ['_LARGE_INTEGER']],
'ThisPeriodTotalUserTime' : [ 0x68, ['_LARGE_INTEGER']],
'ThisPeriodTotalKernelTime' : [ 0x70, ['_LARGE_INTEGER']],
'TotalPageFaultCount' : [ 0x78, ['unsigned long']],
'TotalProcesses' : [ 0x7c, ['unsigned long']],
'ActiveProcesses' : [ 0x80, ['unsigned long']],
'TotalTerminatedProcesses' : [ 0x84, ['unsigned long']],
'PerProcessUserTimeLimit' : [ 0x88, ['_LARGE_INTEGER']],
'PerJobUserTimeLimit' : [ 0x90, ['_LARGE_INTEGER']],
'LimitFlags' : [ 0x98, ['unsigned long']],
'MinimumWorkingSetSize' : [ 0x9c, ['unsigned long']],
'MaximumWorkingSetSize' : [ 0xa0, ['unsigned long']],
'ActiveProcessLimit' : [ 0xa4, ['unsigned long']],
'Affinity' : [ 0xa8, ['unsigned long']],
'PriorityClass' : [ 0xac, ['unsigned char']],
'UIRestrictionsClass' : [ 0xb0, ['unsigned long']],
'SecurityLimitFlags' : [ 0xb4, ['unsigned long']],
'Token' : [ 0xb8, ['pointer', ['void']]],
'Filter' : [ 0xbc, ['pointer', ['_PS_JOB_TOKEN_FILTER']]],
'EndOfJobTimeAction' : [ 0xc0, ['unsigned long']],
'CompletionPort' : [ 0xc4, ['pointer', ['void']]],
'CompletionKey' : [ 0xc8, ['pointer', ['void']]],
'SessionId' : [ 0xcc, ['unsigned long']],
'SchedulingClass' : [ 0xd0, ['unsigned long']],
'ReadOperationCount' : [ 0xd8, ['unsigned long long']],
'WriteOperationCount' : [ 0xe0, ['unsigned long long']],
'OtherOperationCount' : [ 0xe8, ['unsigned long long']],
'ReadTransferCount' : [ 0xf0, ['unsigned long long']],
'WriteTransferCount' : [ 0xf8, ['unsigned long long']],
'OtherTransferCount' : [ 0x100, ['unsigned long long']],
'IoInfo' : [ 0x108, ['_IO_COUNTERS']],
'ProcessMemoryLimit' : [ 0x138, ['unsigned long']],
'JobMemoryLimit' : [ 0x13c, ['unsigned long']],
'PeakProcessMemoryUsed' : [ 0x140, ['unsigned long']],
'PeakJobMemoryUsed' : [ 0x144, ['unsigned long']],
'CurrentJobMemoryUsed' : [ 0x148, ['unsigned long']],
'MemoryLimitsLock' : [ 0x14c, ['_FAST_MUTEX']],
'JobSetLinks' : [ 0x16c, ['_LIST_ENTRY']],
'MemberLevel' : [ 0x174, ['unsigned long']],
'JobFlags' : [ 0x178, ['unsigned long']],
} ],
'_LARGE_CONTROL_AREA' : [ 0x40, {
'Segment' : [ 0x0, ['pointer', ['_SEGMENT']]],
'DereferenceList' : [ 0x4, ['_LIST_ENTRY']],
'NumberOfSectionReferences' : [ 0xc, ['unsigned long']],
'NumberOfPfnReferences' : [ 0x10, ['unsigned long']],
'NumberOfMappedViews' : [ 0x14, ['unsigned long']],
'NumberOfSubsections' : [ 0x18, ['unsigned short']],
'FlushInProgressCount' : [ 0x1a, ['unsigned short']],
'NumberOfUserReferences' : [ 0x1c, ['unsigned long']],
'u' : [ 0x20, ['__unnamed_123f']],
'FilePointer' : [ 0x24, ['pointer', ['_FILE_OBJECT']]],
'WaitingForDeletion' : [ 0x28, ['pointer', ['_EVENT_COUNTER']]],
'ModifiedWriteCount' : [ 0x2c, ['unsigned short']],
'NumberOfSystemCacheViews' : [ 0x2e, ['unsigned short']],
'StartingFrame' : [ 0x30, ['unsigned long']],
'UserGlobalList' : [ 0x34, ['_LIST_ENTRY']],
'SessionId' : [ 0x3c, ['unsigned long']],
} ],
'_GUID' : [ 0x10, {
'Data1' : [ 0x0, ['unsigned long']],
'Data2' : [ 0x4, ['unsigned short']],
'Data3' : [ 0x6, ['unsigned short']],
'Data4' : [ 0x8, ['array', 8, ['unsigned char']]],
} ],
'_PS_JOB_TOKEN_FILTER' : [ 0x24, {
'CapturedSidCount' : [ 0x0, ['unsigned long']],
'CapturedSids' : [ 0x4, ['pointer', ['_SID_AND_ATTRIBUTES']]],
'CapturedSidsLength' : [ 0x8, ['unsigned long']],
'CapturedGroupCount' : [ 0xc, ['unsigned long']],
'CapturedGroups' : [ 0x10, ['pointer', ['_SID_AND_ATTRIBUTES']]],
'CapturedGroupsLength' : [ 0x14, ['unsigned long']],
'CapturedPrivilegeCount' : [ 0x18, ['unsigned long']],
'CapturedPrivileges' : [ 0x1c, ['pointer', ['_LUID_AND_ATTRIBUTES']]],
'CapturedPrivilegesLength' : [ 0x20, ['unsigned long']],
} ],
'_FAST_MUTEX' : [ 0x20, {
'Count' : [ 0x0, ['long']],
'Owner' : [ 0x4, ['pointer', ['_KTHREAD']]],
'Contention' : [ 0x8, ['unsigned long']],
'Event' : [ 0xc, ['_KEVENT']],
'OldIrql' : [ 0x1c, ['unsigned long']],
} ],
'_MM_DRIVER_VERIFIER_DATA' : [ 0x70, {
'Level' : [ 0x0, ['unsigned long']],
'RaiseIrqls' : [ 0x4, ['unsigned long']],
'AcquireSpinLocks' : [ 0x8, ['unsigned long']],
'SynchronizeExecutions' : [ 0xc, ['unsigned long']],
'AllocationsAttempted' : [ 0x10, ['unsigned long']],
'AllocationsSucceeded' : [ 0x14, ['unsigned long']],
'AllocationsSucceededSpecialPool' : [ 0x18, ['unsigned long']],
'AllocationsWithNoTag' : [ 0x1c, ['unsigned long']],
'TrimRequests' : [ 0x20, ['unsigned long']],
'Trims' : [ 0x24, ['unsigned long']],
'AllocationsFailed' : [ 0x28, ['unsigned long']],
'AllocationsFailedDeliberately' : [ 0x2c, ['unsigned long']],
'Loads' : [ 0x30, ['unsigned long']],
'Unloads' : [ 0x34, ['unsigned long']],
'UnTrackedPool' : [ 0x38, ['unsigned long']],
'UserTrims' : [ 0x3c, ['unsigned long']],
'CurrentPagedPoolAllocations' : [ 0x40, ['unsigned long']],
'CurrentNonPagedPoolAllocations' : [ 0x44, ['unsigned long']],
'PeakPagedPoolAllocations' : [ 0x48, ['unsigned long']],
'PeakNonPagedPoolAllocations' : [ 0x4c, ['unsigned long']],
'PagedBytes' : [ 0x50, ['unsigned long']],
'NonPagedBytes' : [ 0x54, ['unsigned long']],
'PeakPagedBytes' : [ 0x58, ['unsigned long']],
'PeakNonPagedBytes' : [ 0x5c, ['unsigned long']],
'BurstAllocationsFailedDeliberately' : [ 0x60, ['unsigned long']],
'SessionTrims' : [ 0x64, ['unsigned long']],
'Reserved' : [ 0x68, ['array', 2, ['unsigned long']]],
} ],
'_IMAGE_FILE_HEADER' : [ 0x14, {
'Machine' : [ 0x0, ['unsigned short']],
'NumberOfSections' : [ 0x2, ['unsigned short']],
'TimeDateStamp' : [ 0x4, ['unsigned long']],
'PointerToSymbolTable' : [ 0x8, ['unsigned long']],
'NumberOfSymbols' : [ 0xc, ['unsigned long']],
'SizeOfOptionalHeader' : [ 0x10, ['unsigned short']],
'Characteristics' : [ 0x12, ['unsigned short']],
} ],
'_FILE_OBJECT' : [ 0x70, {
'Type' : [ 0x0, ['short']],
'Size' : [ 0x2, ['short']],
'DeviceObject' : [ 0x4, ['pointer', ['_DEVICE_OBJECT']]],
'Vpb' : [ 0x8, ['pointer', ['_VPB']]],
'FsContext' : [ 0xc, ['pointer', ['void']]],
'FsContext2' : [ 0x10, ['pointer', ['void']]],
'SectionObjectPointer' : [ 0x14, ['pointer', ['_SECTION_OBJECT_POINTERS']]],
'PrivateCacheMap' : [ 0x18, ['pointer', ['void']]],
'FinalStatus' : [ 0x1c, ['long']],
'RelatedFileObject' : [ 0x20, ['pointer', ['_FILE_OBJECT']]],
'LockOperation' : [ 0x24, ['unsigned char']],
'DeletePending' : [ 0x25, ['unsigned char']],
'ReadAccess' : [ 0x26, ['unsigned char']],
'WriteAccess' : [ 0x27, ['unsigned char']],
'DeleteAccess' : [ 0x28, ['unsigned char']],
'SharedRead' : [ 0x29, ['unsigned char']],
'SharedWrite' : [ 0x2a, ['unsigned char']],
'SharedDelete' : [ 0x2b, ['unsigned char']],
'Flags' : [ 0x2c, ['unsigned long']],
'FileName' : [ 0x30, ['_UNICODE_STRING']],
'CurrentByteOffset' : [ 0x38, ['_LARGE_INTEGER']],
'Waiters' : [ 0x40, ['unsigned long']],
'Busy' : [ 0x44, ['unsigned long']],
'LastLock' : [ 0x48, ['pointer', ['void']]],
'Lock' : [ 0x4c, ['_KEVENT']],
'Event' : [ 0x5c, ['_KEVENT']],
'CompletionContext' : [ 0x6c, ['pointer', ['_IO_COMPLETION_CONTEXT']]],
} ],
'_MMPTE_HARDWARE' : [ 0x4, {
'Valid' : [ 0x0, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned long')]],
'Writable' : [ 0x0, ['BitField', dict(start_bit = 1, end_bit = 2, native_type='unsigned long')]],
'Owner' : [ 0x0, ['BitField', dict(start_bit = 2, end_bit = 3, native_type='unsigned long')]],
'WriteThrough' : [ 0x0, ['BitField', dict(start_bit = 3, end_bit = 4, native_type='unsigned long')]],
'CacheDisable' : [ 0x0, ['BitField', dict(start_bit = 4, end_bit = 5, native_type='unsigned long')]],
'Accessed' : [ 0x0, ['BitField', dict(start_bit = 5, end_bit = 6, native_type='unsigned long')]],
'Dirty' : [ 0x0, ['BitField', dict(start_bit = 6, end_bit = 7, native_type='unsigned long')]],
'LargePage' : [ 0x0, ['BitField', dict(start_bit = 7, end_bit = 8, native_type='unsigned long')]],
'Global' : [ 0x0, ['BitField', dict(start_bit = 8, end_bit = 9, native_type='unsigned long')]],
'CopyOnWrite' : [ 0x0, ['BitField', dict(start_bit = 9, end_bit = 10, native_type='unsigned long')]],
'Prototype' : [ 0x0, ['BitField', dict(start_bit = 10, end_bit = 11, native_type='unsigned long')]],
'Write' : [ 0x0, ['BitField', dict(start_bit = 11, end_bit = 12, native_type='unsigned long')]],
'PageFrameNumber' : [ 0x0, ['BitField', dict(start_bit = 12, end_bit = 32, native_type='unsigned long')]],
} ],
'_IO_COMPLETION_CONTEXT' : [ 0x8, {
'Port' : [ 0x0, ['pointer', ['void']]],
'Key' : [ 0x4, ['pointer', ['void']]],
} ],
'_CALL_HASH_ENTRY' : [ 0x14, {
'ListEntry' : [ 0x0, ['_LIST_ENTRY']],
'CallersAddress' : [ 0x8, ['pointer', ['void']]],
'CallersCaller' : [ 0xc, ['pointer', ['void']]],
'CallCount' : [ 0x10, ['unsigned long']],
} ],
'_HMAP_ENTRY' : [ 0x10, {
'BlockAddress' : [ 0x0, ['unsigned long']],
'BinAddress' : [ 0x4, ['unsigned long']],
'CmView' : [ 0x8, ['pointer', ['_CM_VIEW_OF_FILE']]],
'MemAlloc' : [ 0xc, ['unsigned long']],
} ],
'_DBGKD_SET_CONTEXT' : [ 0x4, {
'ContextFlags' : [ 0x0, ['unsigned long']],
} ],
'_KLOCK_QUEUE_HANDLE' : [ 0xc, {
'LockQueue' : [ 0x0, ['_KSPIN_LOCK_QUEUE']],
'OldIrql' : [ 0x8, ['unsigned char']],
} ],
'_MMSECTION_FLAGS' : [ 0x4, {
'BeingDeleted' : [ 0x0, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned long')]],
'BeingCreated' : [ 0x0, ['BitField', dict(start_bit = 1, end_bit = 2, native_type='unsigned long')]],
'BeingPurged' : [ 0x0, ['BitField', dict(start_bit = 2, end_bit = 3, native_type='unsigned long')]],
'NoModifiedWriting' : [ 0x0, ['BitField', dict(start_bit = 3, end_bit = 4, native_type='unsigned long')]],
'FailAllIo' : [ 0x0, ['BitField', dict(start_bit = 4, end_bit = 5, native_type='unsigned long')]],
'Image' : [ 0x0, ['BitField', dict(start_bit = 5, end_bit = 6, native_type='unsigned long')]],
'Based' : [ 0x0, ['BitField', dict(start_bit = 6, end_bit = 7, native_type='unsigned long')]],
'File' : [ 0x0, ['BitField', dict(start_bit = 7, end_bit = 8, native_type='unsigned long')]],
'Networked' : [ 0x0, ['BitField', dict(start_bit = 8, end_bit = 9, native_type='unsigned long')]],
'NoCache' : [ 0x0, ['BitField', dict(start_bit = 9, end_bit = 10, native_type='unsigned long')]],
'PhysicalMemory' : [ 0x0, ['BitField', dict(start_bit = 10, end_bit = 11, native_type='unsigned long')]],
'CopyOnWrite' : [ 0x0, ['BitField', dict(start_bit = 11, end_bit = 12, native_type='unsigned long')]],
'Reserve' : [ 0x0, ['BitField', dict(start_bit = 12, end_bit = 13, native_type='unsigned long')]],
'Commit' : [ 0x0, ['BitField', dict(start_bit = 13, end_bit = 14, native_type='unsigned long')]],
'FloppyMedia' : [ 0x0, ['BitField', dict(start_bit = 14, end_bit = 15, native_type='unsigned long')]],
'WasPurged' : [ 0x0, ['BitField', dict(start_bit = 15, end_bit = 16, native_type='unsigned long')]],
'UserReference' : [ 0x0, ['BitField', dict(start_bit = 16, end_bit = 17, native_type='unsigned long')]],
'GlobalMemory' : [ 0x0, ['BitField', dict(start_bit = 17, end_bit = 18, native_type='unsigned long')]],
'DeleteOnClose' : [ 0x0, ['BitField', dict(start_bit = 18, end_bit = 19, native_type='unsigned long')]],
'FilePointerNull' : [ 0x0, ['BitField', dict(start_bit = 19, end_bit = 20, native_type='unsigned long')]],
'DebugSymbolsLoaded' : [ 0x0, ['BitField', dict(start_bit = 20, end_bit = 21, native_type='unsigned long')]],
'SetMappedFileIoComplete' : [ 0x0, ['BitField', dict(start_bit = 21, end_bit = 22, native_type='unsigned long')]],
'CollidedFlush' : [ 0x0, ['BitField', dict(start_bit = 22, end_bit = 23, native_type='unsigned long')]],
'NoChange' : [ 0x0, ['BitField', dict(start_bit = 23, end_bit = 24, native_type='unsigned long')]],
'HadUserReference' : [ 0x0, ['BitField', dict(start_bit = 24, end_bit = 25, native_type='unsigned long')]],
'ImageMappedInSystemSpace' : [ 0x0, ['BitField', dict(start_bit = 25, end_bit = 26, native_type='unsigned long')]],
'UserWritable' : [ 0x0, ['BitField', dict(start_bit = 26, end_bit = 27, native_type='unsigned long')]],
'Accessed' : [ 0x0, ['BitField', dict(start_bit = 27, end_bit = 28, native_type='unsigned long')]],
'GlobalOnlyPerSession' : [ 0x0, ['BitField', dict(start_bit = 28, end_bit = 29, native_type='unsigned long')]],
'Rom' : [ 0x0, ['BitField', dict(start_bit = 29, end_bit = 30, native_type='unsigned long')]],
'filler' : [ 0x0, ['BitField', dict(start_bit = 30, end_bit = 32, native_type='unsigned long')]],
} ],
'_DEFERRED_WRITE' : [ 0x28, {
'NodeTypeCode' : [ 0x0, ['short']],
'NodeByteSize' : [ 0x2, ['short']],
'FileObject' : [ 0x4, ['pointer', ['_FILE_OBJECT']]],
'BytesToWrite' : [ 0x8, ['unsigned long']],
'DeferredWriteLinks' : [ 0xc, ['_LIST_ENTRY']],
'Event' : [ 0x14, ['pointer', ['_KEVENT']]],
'PostRoutine' : [ 0x18, ['pointer', ['void']]],
'Context1' : [ 0x1c, ['pointer', ['void']]],
'Context2' : [ 0x20, ['pointer', ['void']]],
'LimitModifiedPages' : [ 0x24, ['unsigned char']],
} ],
'_TRACE_ENABLE_FLAG_EXTENSION' : [ 0x4, {
'Offset' : [ 0x0, ['unsigned short']],
'Length' : [ 0x2, ['unsigned char']],
'Flag' : [ 0x3, ['unsigned char']],
} ],
'_SID_AND_ATTRIBUTES' : [ 0x8, {
'Sid' : [ 0x0, ['pointer', ['void']]],
'Attributes' : [ 0x4, ['unsigned long']],
} ],
'_HIVE_LIST_ENTRY' : [ 0x18, {
'Name' : [ 0x0, ['pointer', ['unsigned short']]],
'BaseName' : [ 0x4, ['pointer', ['unsigned short']]],
'CmHive' : [ 0x8, ['pointer', ['_CMHIVE']]],
'Flags' : [ 0xc, ['unsigned long']],
'CmHive2' : [ 0x10, ['pointer', ['_CMHIVE']]],
'ThreadFinished' : [ 0x14, ['unsigned char']],
'ThreadStarted' : [ 0x15, ['unsigned char']],
'Allocate' : [ 0x16, ['unsigned char']],
} ],
'_KSPIN_LOCK_QUEUE' : [ 0x8, {
'Next' : [ 0x0, ['pointer', ['_KSPIN_LOCK_QUEUE']]],
'Lock' : [ 0x4, ['pointer', ['unsigned long']]],
} ],
'_PS_IMPERSONATION_INFORMATION' : [ 0xc, {
'Token' : [ 0x0, ['pointer', ['void']]],
'CopyOnOpen' : [ 0x4, ['unsigned char']],
'EffectiveOnly' : [ 0x5, ['unsigned char']],
'ImpersonationLevel' : [ 0x8, ['Enumeration', dict(target = 'long', choices = {0: 'SecurityAnonymous', 1: 'SecurityIdentification', 2: 'SecurityImpersonation', 3: 'SecurityDelegation'})]],
} ],
'__unnamed_12ed' : [ 0x4, {
'LegacyDeviceNode' : [ 0x0, ['pointer', ['_DEVICE_NODE']]],
'PendingDeviceRelations' : [ 0x0, ['pointer', ['_DEVICE_RELATIONS']]],
} ],
'__unnamed_12ef' : [ 0x4, {
'NextResourceDeviceNode' : [ 0x0, ['pointer', ['_DEVICE_NODE']]],
} ],
'__unnamed_12f3' : [ 0x10, {
'DockStatus' : [ 0x0, ['Enumeration', dict(target = 'long', choices = {0: 'DOCK_NOTDOCKDEVICE', 1: 'DOCK_QUIESCENT', 2: 'DOCK_ARRIVING', 3: 'DOCK_DEPARTING', 4: 'DOCK_EJECTIRP_COMPLETED'})]],
'ListEntry' : [ 0x4, ['_LIST_ENTRY']],
'SerialNumber' : [ 0xc, ['pointer', ['unsigned short']]],
} ],
'_DEVICE_NODE' : [ 0x118, {
'Sibling' : [ 0x0, ['pointer', ['_DEVICE_NODE']]],
'Child' : [ 0x4, ['pointer', ['_DEVICE_NODE']]],
'Parent' : [ 0x8, ['pointer', ['_DEVICE_NODE']]],
'LastChild' : [ 0xc, ['pointer', ['_DEVICE_NODE']]],
'Level' : [ 0x10, ['unsigned long']],
'Notify' : [ 0x14, ['pointer', ['_PO_DEVICE_NOTIFY']]],
'State' : [ 0x18, ['Enumeration', dict(target = 'long', choices = {768: 'DeviceNodeUnspecified', 769: 'DeviceNodeUninitialized', 770: 'DeviceNodeInitialized', 771: 'DeviceNodeDriversAdded', 772: 'DeviceNodeResourcesAssigned', 773: 'DeviceNodeStartPending', 774: 'DeviceNodeStartCompletion', 775: 'DeviceNodeStartPostWork', 776: 'DeviceNodeStarted', 777: 'DeviceNodeQueryStopped', 778: 'DeviceNodeStopped', 779: 'DeviceNodeRestartCompletion', 780: 'DeviceNodeEnumeratePending', 781: 'DeviceNodeEnumerateCompletion', 782: 'DeviceNodeAwaitingQueuedDeletion', 783: 'DeviceNodeAwaitingQueuedRemoval', 784: 'DeviceNodeQueryRemoved', 785: 'DeviceNodeRemovePendingCloses', 786: 'DeviceNodeRemoved', 787: 'DeviceNodeDeletePendingCloses', 788: 'DeviceNodeDeleted'})]],
'PreviousState' : [ 0x1c, ['Enumeration', dict(target = 'long', choices = {768: 'DeviceNodeUnspecified', 769: 'DeviceNodeUninitialized', 770: 'DeviceNodeInitialized', 771: 'DeviceNodeDriversAdded', 772: 'DeviceNodeResourcesAssigned', 773: 'DeviceNodeStartPending', 774: 'DeviceNodeStartCompletion', 775: 'DeviceNodeStartPostWork', 776: 'DeviceNodeStarted', 777: 'DeviceNodeQueryStopped', 778: 'DeviceNodeStopped', 779: 'DeviceNodeRestartCompletion', 780: 'DeviceNodeEnumeratePending', 781: 'DeviceNodeEnumerateCompletion', 782: 'DeviceNodeAwaitingQueuedDeletion', 783: 'DeviceNodeAwaitingQueuedRemoval', 784: 'DeviceNodeQueryRemoved', 785: 'DeviceNodeRemovePendingCloses', 786: 'DeviceNodeRemoved', 787: 'DeviceNodeDeletePendingCloses', 788: 'DeviceNodeDeleted'})]],
'StateHistory' : [ 0x20, ['array', -80, ['Enumeration', dict(target = 'long', choices = {768: 'DeviceNodeUnspecified', 769: 'DeviceNodeUninitialized', 770: 'DeviceNodeInitialized', 771: 'DeviceNodeDriversAdded', 772: 'DeviceNodeResourcesAssigned', 773: 'DeviceNodeStartPending', 774: 'DeviceNodeStartCompletion', 775: 'DeviceNodeStartPostWork', 776: 'DeviceNodeStarted', 777: 'DeviceNodeQueryStopped', 778: 'DeviceNodeStopped', 779: 'DeviceNodeRestartCompletion', 780: 'DeviceNodeEnumeratePending', 781: 'DeviceNodeEnumerateCompletion', 782: 'DeviceNodeAwaitingQueuedDeletion', 783: 'DeviceNodeAwaitingQueuedRemoval', 784: 'DeviceNodeQueryRemoved', 785: 'DeviceNodeRemovePendingCloses', 786: 'DeviceNodeRemoved', 787: 'DeviceNodeDeletePendingCloses', 788: 'DeviceNodeDeleted'})]]],
'StateHistoryEntry' : [ 0x70, ['unsigned long']],
'CompletionStatus' : [ 0x74, ['long']],
'PendingIrp' : [ 0x78, ['pointer', ['_IRP']]],
'Flags' : [ 0x7c, ['unsigned long']],
'UserFlags' : [ 0x80, ['unsigned long']],
'Problem' : [ 0x84, ['unsigned long']],
'PhysicalDeviceObject' : [ 0x88, ['pointer', ['_DEVICE_OBJECT']]],
'ResourceList' : [ 0x8c, ['pointer', ['_CM_RESOURCE_LIST']]],
'ResourceListTranslated' : [ 0x90, ['pointer', ['_CM_RESOURCE_LIST']]],
'InstancePath' : [ 0x94, ['_UNICODE_STRING']],
'ServiceName' : [ 0x9c, ['_UNICODE_STRING']],
'DuplicatePDO' : [ 0xa4, ['pointer', ['_DEVICE_OBJECT']]],
'ResourceRequirements' : [ 0xa8, ['pointer', ['_IO_RESOURCE_REQUIREMENTS_LIST']]],
'InterfaceType' : [ 0xac, ['Enumeration', dict(target = 'long', choices = {0: 'Internal', 1: 'Isa', 2: 'Eisa', 3: 'MicroChannel', 4: 'TurboChannel', 5: 'PCIBus', 6: 'VMEBus', 7: 'NuBus', 8: 'PCMCIABus', 9: 'CBus', 10: 'MPIBus', 11: 'MPSABus', 12: 'ProcessorInternal', 13: 'InternalPowerBus', 14: 'PNPISABus', 15: 'PNPBus', 16: 'MaximumInterfaceType', -1: 'InterfaceTypeUndefined'})]],
'BusNumber' : [ 0xb0, ['unsigned long']],
'ChildInterfaceType' : [ 0xb4, ['Enumeration', dict(target = 'long', choices = {0: 'Internal', 1: 'Isa', 2: 'Eisa', 3: 'MicroChannel', 4: 'TurboChannel', 5: 'PCIBus', 6: 'VMEBus', 7: 'NuBus', 8: 'PCMCIABus', 9: 'CBus', 10: 'MPIBus', 11: 'MPSABus', 12: 'ProcessorInternal', 13: 'InternalPowerBus', 14: 'PNPISABus', 15: 'PNPBus', 16: 'MaximumInterfaceType', -1: 'InterfaceTypeUndefined'})]],
'ChildBusNumber' : [ 0xb8, ['unsigned long']],
'ChildBusTypeIndex' : [ 0xbc, ['unsigned short']],
'RemovalPolicy' : [ 0xbe, ['unsigned char']],
'HardwareRemovalPolicy' : [ 0xbf, ['unsigned char']],
'TargetDeviceNotify' : [ 0xc0, ['_LIST_ENTRY']],
'DeviceArbiterList' : [ 0xc8, ['_LIST_ENTRY']],
'DeviceTranslatorList' : [ 0xd0, ['_LIST_ENTRY']],
'NoTranslatorMask' : [ 0xd8, ['unsigned short']],
'QueryTranslatorMask' : [ 0xda, ['unsigned short']],
'NoArbiterMask' : [ 0xdc, ['unsigned short']],
'QueryArbiterMask' : [ 0xde, ['unsigned short']],
'OverUsed1' : [ 0xe0, ['__unnamed_12ed']],
'OverUsed2' : [ 0xe4, ['__unnamed_12ef']],
'BootResources' : [ 0xe8, ['pointer', ['_CM_RESOURCE_LIST']]],
'CapabilityFlags' : [ 0xec, ['unsigned long']],
'DockInfo' : [ 0xf0, ['__unnamed_12f3']],
'DisableableDepends' : [ 0x100, ['unsigned long']],
'PendedSetInterfaceState' : [ 0x104, ['_LIST_ENTRY']],
'LegacyBusListEntry' : [ 0x10c, ['_LIST_ENTRY']],
'DriverUnloadRetryCount' : [ 0x114, ['unsigned long']],
} ],
'__unnamed_12f8' : [ 0x38, {
'CriticalSection' : [ 0x0, ['_RTL_CRITICAL_SECTION']],
'Resource' : [ 0x0, ['_ERESOURCE']],
} ],
'_HEAP_LOCK' : [ 0x38, {
'Lock' : [ 0x0, ['__unnamed_12f8']],
} ],
'_KPCR' : [ 0xd70, {
'NtTib' : [ 0x0, ['_NT_TIB']],
'SelfPcr' : [ 0x1c, ['pointer', ['_KPCR']]],
'Prcb' : [ 0x20, ['pointer', ['_KPRCB']]],
'Irql' : [ 0x24, ['unsigned char']],
'IRR' : [ 0x28, ['unsigned long']],
'IrrActive' : [ 0x2c, ['unsigned long']],
'IDR' : [ 0x30, ['unsigned long']],
'KdVersionBlock' : [ 0x34, ['pointer', ['void']]],
'IDT' : [ 0x38, ['pointer', ['_KIDTENTRY']]],
'GDT' : [ 0x3c, ['pointer', ['_KGDTENTRY']]],
'TSS' : [ 0x40, ['pointer', ['_KTSS']]],
'MajorVersion' : [ 0x44, ['unsigned short']],
'MinorVersion' : [ 0x46, ['unsigned short']],
'SetMember' : [ 0x48, ['unsigned long']],
'StallScaleFactor' : [ 0x4c, ['unsigned long']],
'DebugActive' : [ 0x50, ['unsigned char']],
'Number' : [ 0x51, ['unsigned char']],
'Spare0' : [ 0x52, ['unsigned char']],
'SecondLevelCacheAssociativity' : [ 0x53, ['unsigned char']],
'VdmAlert' : [ 0x54, ['unsigned long']],
'KernelReserved' : [ 0x58, ['array', 14, ['unsigned long']]],
'SecondLevelCacheSize' : [ 0x90, ['unsigned long']],
'HalReserved' : [ 0x94, ['array', 16, ['unsigned long']]],
'InterruptMode' : [ 0xd4, ['unsigned long']],
'Spare1' : [ 0xd8, ['unsigned char']],
'KernelReserved2' : [ 0xdc, ['array', 17, ['unsigned long']]],
'PrcbData' : [ 0x120, ['_KPRCB']],
} ],
'_MMCOLOR_TABLES' : [ 0xc, {
'Flink' : [ 0x0, ['unsigned long']],
'Blink' : [ 0x4, ['pointer', ['void']]],
'Count' : [ 0x8, ['unsigned long']],
} ],
'_DBGKD_FILL_MEMORY' : [ 0x10, {
'Address' : [ 0x0, ['unsigned long long']],
'Length' : [ 0x8, ['unsigned long']],
'Flags' : [ 0xc, ['unsigned short']],
'PatternLength' : [ 0xe, ['unsigned short']],
} ],
'_PP_LOOKASIDE_LIST' : [ 0x8, {
'P' : [ 0x0, ['pointer', ['_GENERAL_LOOKASIDE']]],
'L' : [ 0x4, ['pointer', ['_GENERAL_LOOKASIDE']]],
} ],
'_PHYSICAL_MEMORY_RUN' : [ 0x8, {
'BasePage' : [ 0x0, ['unsigned long']],
'PageCount' : [ 0x4, ['unsigned long']],
} ],
'__unnamed_1317' : [ 0x4, {
'Flink' : [ 0x0, ['unsigned long']],
'WsIndex' : [ 0x0, ['unsigned long']],
'Event' : [ 0x0, ['pointer', ['_KEVENT']]],
'ReadStatus' : [ 0x0, ['long']],
'NextStackPfn' : [ 0x0, ['_SINGLE_LIST_ENTRY']],
} ],
'__unnamed_1319' : [ 0x4, {
'Blink' : [ 0x0, ['unsigned long']],
'ShareCount' : [ 0x0, ['unsigned long']],
} ],
'__unnamed_131c' : [ 0x4, {
'ShortFlags' : [ 0x0, ['unsigned short']],
'ReferenceCount' : [ 0x2, ['unsigned short']],
} ],
'__unnamed_131e' : [ 0x4, {
'e1' : [ 0x0, ['_MMPFNENTRY']],
'e2' : [ 0x0, ['__unnamed_131c']],
} ],
'__unnamed_1325' : [ 0x4, {
'EntireFrame' : [ 0x0, ['unsigned long']],
'PteFrame' : [ 0x0, ['BitField', dict(start_bit = 0, end_bit = 26, native_type='unsigned long')]],
'InPageError' : [ 0x0, ['BitField', dict(start_bit = 26, end_bit = 27, native_type='unsigned long')]],
'VerifierAllocation' : [ 0x0, ['BitField', dict(start_bit = 27, end_bit = 28, native_type='unsigned long')]],
'AweAllocation' : [ 0x0, ['BitField', dict(start_bit = 28, end_bit = 29, native_type='unsigned long')]],
'LockCharged' : [ 0x0, ['BitField', dict(start_bit = 29, end_bit = 30, native_type='unsigned long')]],
'KernelStack' : [ 0x0, ['BitField', dict(start_bit = 30, end_bit = 31, native_type='unsigned long')]],
'Reserved' : [ 0x0, ['BitField', dict(start_bit = 31, end_bit = 32, native_type='unsigned long')]],
} ],
'_MMPFN' : [ 0x18, {
'u1' : [ 0x0, ['__unnamed_1317']],
'PteAddress' : [ 0x4, ['pointer', ['_MMPTE']]],
'u2' : [ 0x8, ['__unnamed_1319']],
'u3' : [ 0xc, ['__unnamed_131e']],
'OriginalPte' : [ 0x10, ['_MMPTE']],
'u4' : [ 0x14, ['__unnamed_1325']],
} ],
'__unnamed_132b' : [ 0x4, {
'LongFlags' : [ 0x0, ['unsigned long']],
'Flags' : [ 0x0, ['_MM_SESSION_SPACE_FLAGS']],
} ],
'_MM_SESSION_SPACE' : [ 0x1278, {
'ReferenceCount' : [ 0x0, ['unsigned long']],
'u' : [ 0x4, ['__unnamed_132b']],
'SessionId' : [ 0x8, ['unsigned long']],
'SessionPageDirectoryIndex' : [ 0xc, ['unsigned long']],
'GlobalVirtualAddress' : [ 0x10, ['pointer', ['_MM_SESSION_SPACE']]],
'ProcessList' : [ 0x14, ['_LIST_ENTRY']],
'NonPagedPoolBytes' : [ 0x1c, ['unsigned long']],
'PagedPoolBytes' : [ 0x20, ['unsigned long']],
'NonPagedPoolAllocations' : [ 0x24, ['unsigned long']],
'PagedPoolAllocations' : [ 0x28, ['unsigned long']],
'NonPagablePages' : [ 0x2c, ['unsigned long']],
'CommittedPages' : [ 0x30, ['unsigned long']],
'LastProcessSwappedOutTime' : [ 0x38, ['_LARGE_INTEGER']],
'PageTables' : [ 0x40, ['pointer', ['_MMPTE']]],
'PagedPoolMutex' : [ 0x44, ['_FAST_MUTEX']],
'PagedPoolStart' : [ 0x64, ['pointer', ['void']]],
'PagedPoolEnd' : [ 0x68, ['pointer', ['void']]],
'PagedPoolBasePde' : [ 0x6c, ['pointer', ['_MMPTE']]],
'PagedPoolInfo' : [ 0x70, ['_MM_PAGED_POOL_INFO']],
'Color' : [ 0x94, ['unsigned long']],
'ProcessOutSwapCount' : [ 0x98, ['unsigned long']],
'ImageList' : [ 0x9c, ['_LIST_ENTRY']],
'GlobalPteEntry' : [ 0xa4, ['pointer', ['_MMPTE']]],
'CopyOnWriteCount' : [ 0xa8, ['unsigned long']],
'SessionPoolAllocationFailures' : [ 0xac, ['array', 4, ['unsigned long']]],
'AttachCount' : [ 0xbc, ['unsigned long']],
'AttachEvent' : [ 0xc0, ['_KEVENT']],
'LastProcess' : [ 0xd0, ['pointer', ['_EPROCESS']]],
'Vm' : [ 0xd8, ['_MMSUPPORT']],
'Wsle' : [ 0x118, ['pointer', ['_MMWSLE']]],
'WsLock' : [ 0x11c, ['_ERESOURCE']],
'WsListEntry' : [ 0x154, ['_LIST_ENTRY']],
'Session' : [ 0x15c, ['_MMSESSION']],
'Win32KDriverObject' : [ 0x198, ['_DRIVER_OBJECT']],
'WorkingSetLockOwner' : [ 0x240, ['pointer', ['_ETHREAD']]],
'PagedPool' : [ 0x244, ['_POOL_DESCRIPTOR']],
'ProcessReferenceToSession' : [ 0x126c, ['long']],
'LocaleId' : [ 0x1270, ['unsigned long']],
} ],
'_PEB' : [ 0x210, {
'InheritedAddressSpace' : [ 0x0, ['unsigned char']],
'ReadImageFileExecOptions' : [ 0x1, ['unsigned char']],
'BeingDebugged' : [ 0x2, ['unsigned char']],
'SpareBool' : [ 0x3, ['unsigned char']],
'Mutant' : [ 0x4, ['pointer', ['void']]],
'ImageBaseAddress' : [ 0x8, ['pointer', ['void']]],
'Ldr' : [ 0xc, ['pointer', ['_PEB_LDR_DATA']]],
'ProcessParameters' : [ 0x10, ['pointer', ['_RTL_USER_PROCESS_PARAMETERS']]],
'SubSystemData' : [ 0x14, ['pointer', ['void']]],
'ProcessHeap' : [ 0x18, ['pointer', ['void']]],
'FastPebLock' : [ 0x1c, ['pointer', ['_RTL_CRITICAL_SECTION']]],
'FastPebLockRoutine' : [ 0x20, ['pointer', ['void']]],
'FastPebUnlockRoutine' : [ 0x24, ['pointer', ['void']]],
'EnvironmentUpdateCount' : [ 0x28, ['unsigned long']],
'KernelCallbackTable' : [ 0x2c, ['pointer', ['void']]],
'SystemReserved' : [ 0x30, ['array', 1, ['unsigned long']]],
'AtlThunkSListPtr32' : [ 0x34, ['unsigned long']],
'FreeList' : [ 0x38, ['pointer', ['_PEB_FREE_BLOCK']]],
'TlsExpansionCounter' : [ 0x3c, ['unsigned long']],
'TlsBitmap' : [ 0x40, ['pointer', ['void']]],
'TlsBitmapBits' : [ 0x44, ['array', 2, ['unsigned long']]],
'ReadOnlySharedMemoryBase' : [ 0x4c, ['pointer', ['void']]],
'ReadOnlySharedMemoryHeap' : [ 0x50, ['pointer', ['void']]],
'ReadOnlyStaticServerData' : [ 0x54, ['pointer', ['pointer', ['void']]]],
'AnsiCodePageData' : [ 0x58, ['pointer', ['void']]],
'OemCodePageData' : [ 0x5c, ['pointer', ['void']]],
'UnicodeCaseTableData' : [ 0x60, ['pointer', ['void']]],
'NumberOfProcessors' : [ 0x64, ['unsigned long']],
'NtGlobalFlag' : [ 0x68, ['unsigned long']],
'CriticalSectionTimeout' : [ 0x70, ['_LARGE_INTEGER']],
'HeapSegmentReserve' : [ 0x78, ['unsigned long']],
'HeapSegmentCommit' : [ 0x7c, ['unsigned long']],
'HeapDeCommitTotalFreeThreshold' : [ 0x80, ['unsigned long']],
'HeapDeCommitFreeBlockThreshold' : [ 0x84, ['unsigned long']],
'NumberOfHeaps' : [ 0x88, ['unsigned long']],
'MaximumNumberOfHeaps' : [ 0x8c, ['unsigned long']],
'ProcessHeaps' : [ 0x90, ['pointer', ['pointer', ['void']]]],
'GdiSharedHandleTable' : [ 0x94, ['pointer', ['void']]],
'ProcessStarterHelper' : [ 0x98, ['pointer', ['void']]],
'GdiDCAttributeList' : [ 0x9c, ['unsigned long']],
'LoaderLock' : [ 0xa0, ['pointer', ['void']]],
'OSMajorVersion' : [ 0xa4, ['unsigned long']],
'OSMinorVersion' : [ 0xa8, ['unsigned long']],
'OSBuildNumber' : [ 0xac, ['unsigned short']],
'OSCSDVersion' : [ 0xae, ['unsigned short']],
'OSPlatformId' : [ 0xb0, ['unsigned long']],
'ImageSubsystem' : [ 0xb4, ['unsigned long']],
'ImageSubsystemMajorVersion' : [ 0xb8, ['unsigned long']],
'ImageSubsystemMinorVersion' : [ 0xbc, ['unsigned long']],
'ImageProcessAffinityMask' : [ 0xc0, ['unsigned long']],
'GdiHandleBuffer' : [ 0xc4, ['array', 34, ['unsigned long']]],
'PostProcessInitRoutine' : [ 0x14c, ['pointer', ['void']]],
'TlsExpansionBitmap' : [ 0x150, ['pointer', ['void']]],
'TlsExpansionBitmapBits' : [ 0x154, ['array', 32, ['unsigned long']]],
'SessionId' : [ 0x1d4, ['unsigned long']],
'AppCompatFlags' : [ 0x1d8, ['_ULARGE_INTEGER']],
'AppCompatFlagsUser' : [ 0x1e0, ['_ULARGE_INTEGER']],
'pShimData' : [ 0x1e8, ['pointer', ['void']]],
'AppCompatInfo' : [ 0x1ec, ['pointer', ['void']]],
'CSDVersion' : [ 0x1f0, ['_UNICODE_STRING']],
'ActivationContextData' : [ 0x1f8, ['pointer', ['void']]],
'ProcessAssemblyStorageMap' : [ 0x1fc, ['pointer', ['void']]],
'SystemDefaultActivationContextData' : [ 0x200, ['pointer', ['void']]],
'SystemAssemblyStorageMap' : [ 0x204, ['pointer', ['void']]],
'MinimumStackCommit' : [ 0x208, ['unsigned long']],
} ],
'_HEAP_FREE_ENTRY' : [ 0x10, {
'Size' : [ 0x0, ['unsigned short']],
'PreviousSize' : [ 0x2, ['unsigned short']],
'SubSegmentCode' : [ 0x0, ['pointer', ['void']]],
'SmallTagIndex' : [ 0x4, ['unsigned char']],
'Flags' : [ 0x5, ['unsigned char']],
'UnusedBytes' : [ 0x6, ['unsigned char']],
'SegmentIndex' : [ 0x7, ['unsigned char']],
'FreeList' : [ 0x8, ['_LIST_ENTRY']],
} ],
'_ERESOURCE' : [ 0x38, {
'SystemResourcesList' : [ 0x0, ['_LIST_ENTRY']],
'OwnerTable' : [ 0x8, ['pointer', ['_OWNER_ENTRY']]],
'ActiveCount' : [ 0xc, ['short']],
'Flag' : [ 0xe, ['unsigned short']],
'SharedWaiters' : [ 0x10, ['pointer', ['_KSEMAPHORE']]],
'ExclusiveWaiters' : [ 0x14, ['pointer', ['_KEVENT']]],
'OwnerThreads' : [ 0x18, ['array', 2, ['_OWNER_ENTRY']]],
'ContentionCount' : [ 0x28, ['unsigned long']],
'NumberOfSharedWaiters' : [ 0x2c, ['unsigned short']],
'NumberOfExclusiveWaiters' : [ 0x2e, ['unsigned short']],
'Address' : [ 0x30, ['pointer', ['void']]],
'CreatorBackTraceIndex' : [ 0x30, ['unsigned long']],
'SpinLock' : [ 0x34, ['unsigned long']],
} ],
'_DBGKD_GET_CONTEXT' : [ 0x4, {
'Unused' : [ 0x0, ['unsigned long']],
} ],
'_MMPTE_SOFTWARE' : [ 0x4, {
'Valid' : [ 0x0, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned long')]],
'PageFileLow' : [ 0x0, ['BitField', dict(start_bit = 1, end_bit = 5, native_type='unsigned long')]],
'Protection' : [ 0x0, ['BitField', dict(start_bit = 5, end_bit = 10, native_type='unsigned long')]],
'Prototype' : [ 0x0, ['BitField', dict(start_bit = 10, end_bit = 11, native_type='unsigned long')]],
'Transition' : [ 0x0, ['BitField', dict(start_bit = 11, end_bit = 12, native_type='unsigned long')]],
'PageFileHigh' : [ 0x0, ['BitField', dict(start_bit = 12, end_bit = 32, native_type='unsigned long')]],
} ],
'_IO_RESOURCE_REQUIREMENTS_LIST' : [ 0x48, {
'ListSize' : [ 0x0, ['unsigned long']],
'InterfaceType' : [ 0x4, ['Enumeration', dict(target = 'long', choices = {0: 'Internal', 1: 'Isa', 2: 'Eisa', 3: 'MicroChannel', 4: 'TurboChannel', 5: 'PCIBus', 6: 'VMEBus', 7: 'NuBus', 8: 'PCMCIABus', 9: 'CBus', 10: 'MPIBus', 11: 'MPSABus', 12: 'ProcessorInternal', 13: 'InternalPowerBus', 14: 'PNPISABus', 15: 'PNPBus', 16: 'MaximumInterfaceType', -1: 'InterfaceTypeUndefined'})]],
'BusNumber' : [ 0x8, ['unsigned long']],
'SlotNumber' : [ 0xc, ['unsigned long']],
'Reserved' : [ 0x10, ['array', 3, ['unsigned long']]],
'AlternativeLists' : [ 0x1c, ['unsigned long']],
'List' : [ 0x20, ['array', 1, ['_IO_RESOURCE_LIST']]],
} ],
'_CACHE_UNINITIALIZE_EVENT' : [ 0x14, {
'Next' : [ 0x0, ['pointer', ['_CACHE_UNINITIALIZE_EVENT']]],
'Event' : [ 0x4, ['_KEVENT']],
} ],
'_CM_RESOURCE_LIST' : [ 0x24, {
'Count' : [ 0x0, ['unsigned long']],
'List' : [ 0x4, ['array', 1, ['_CM_FULL_RESOURCE_DESCRIPTOR']]],
} ],
'_CM_FULL_RESOURCE_DESCRIPTOR' : [ 0x20, {
'InterfaceType' : [ 0x0, ['Enumeration', dict(target = 'long', choices = {0: 'Internal', 1: 'Isa', 2: 'Eisa', 3: 'MicroChannel', 4: 'TurboChannel', 5: 'PCIBus', 6: 'VMEBus', 7: 'NuBus', 8: 'PCMCIABus', 9: 'CBus', 10: 'MPIBus', 11: 'MPSABus', 12: 'ProcessorInternal', 13: 'InternalPowerBus', 14: 'PNPISABus', 15: 'PNPBus', 16: 'MaximumInterfaceType', -1: 'InterfaceTypeUndefined'})]],
'BusNumber' : [ 0x4, ['unsigned long']],
'PartialResourceList' : [ 0x8, ['_CM_PARTIAL_RESOURCE_LIST']],
} ],
'_EPROCESS_QUOTA_ENTRY' : [ 0x10, {
'Usage' : [ 0x0, ['unsigned long']],
'Limit' : [ 0x4, ['unsigned long']],
'Peak' : [ 0x8, ['unsigned long']],
'Return' : [ 0xc, ['unsigned long']],
} ],
'__unnamed_1362' : [ 0x50, {
'CellData' : [ 0x0, ['_CELL_DATA']],
'List' : [ 0x0, ['array', 1, ['unsigned long']]],
} ],
'_CM_CACHED_VALUE_INDEX' : [ 0x54, {
'CellIndex' : [ 0x0, ['unsigned long']],
'Data' : [ 0x4, ['__unnamed_1362']],
} ],
'_WMI_BUFFER_HEADER' : [ 0x48, {
'Wnode' : [ 0x0, ['_WNODE_HEADER']],
'Reserved1' : [ 0x0, ['unsigned long long']],
'Reserved2' : [ 0x8, ['unsigned long long']],
'Reserved3' : [ 0x10, ['_LARGE_INTEGER']],
'Alignment' : [ 0x18, ['pointer', ['void']]],
'SlistEntry' : [ 0x1c, ['_SINGLE_LIST_ENTRY']],
'Entry' : [ 0x18, ['_LIST_ENTRY']],
'ReferenceCount' : [ 0x0, ['long']],
'SavedOffset' : [ 0x4, ['unsigned long']],
'CurrentOffset' : [ 0x8, ['unsigned long']],
'UsePerfClock' : [ 0xc, ['unsigned long']],
'TimeStamp' : [ 0x10, ['_LARGE_INTEGER']],
'Guid' : [ 0x18, ['_GUID']],
'ClientContext' : [ 0x28, ['_WMI_CLIENT_CONTEXT']],
'State' : [ 0x2c, ['_WMI_BUFFER_STATE']],
'Flags' : [ 0x2c, ['unsigned long']],
'Offset' : [ 0x30, ['unsigned long']],
'EventsLost' : [ 0x34, ['unsigned long']],
'InstanceGuid' : [ 0x38, ['_GUID']],
'LoggerContext' : [ 0x38, ['pointer', ['void']]],
'GlobalEntry' : [ 0x3c, ['_SINGLE_LIST_ENTRY']],
} ],
'_KSEMAPHORE' : [ 0x14, {
'Header' : [ 0x0, ['_DISPATCHER_HEADER']],
'Limit' : [ 0x10, ['long']],
} ],
'_PROCESSOR_POWER_STATE' : [ 0x120, {
'IdleFunction' : [ 0x0, ['pointer', ['void']]],
'Idle0KernelTimeLimit' : [ 0x4, ['unsigned long']],
'Idle0LastTime' : [ 0x8, ['unsigned long']],
'IdleHandlers' : [ 0xc, ['pointer', ['void']]],
'IdleState' : [ 0x10, ['pointer', ['void']]],
'IdleHandlersCount' : [ 0x14, ['unsigned long']],
'LastCheck' : [ 0x18, ['unsigned long long']],
'IdleTimes' : [ 0x20, ['PROCESSOR_IDLE_TIMES']],
'IdleTime1' : [ 0x40, ['unsigned long']],
'PromotionCheck' : [ 0x44, ['unsigned long']],
'IdleTime2' : [ 0x48, ['unsigned long']],
'CurrentThrottle' : [ 0x4c, ['unsigned char']],
'ThermalThrottleLimit' : [ 0x4d, ['unsigned char']],
'CurrentThrottleIndex' : [ 0x4e, ['unsigned char']],
'ThermalThrottleIndex' : [ 0x4f, ['unsigned char']],
'LastKernelUserTime' : [ 0x50, ['unsigned long']],
'LastIdleThreadKernelTime' : [ 0x54, ['unsigned long']],
'PackageIdleStartTime' : [ 0x58, ['unsigned long']],
'PackageIdleTime' : [ 0x5c, ['unsigned long']],
'DebugCount' : [ 0x60, ['unsigned long']],
'LastSysTime' : [ 0x64, ['unsigned long']],
'TotalIdleStateTime' : [ 0x68, ['array', 3, ['unsigned long long']]],
'TotalIdleTransitions' : [ 0x80, ['array', 3, ['unsigned long']]],
'PreviousC3StateTime' : [ 0x90, ['unsigned long long']],
'KneeThrottleIndex' : [ 0x98, ['unsigned char']],
'ThrottleLimitIndex' : [ 0x99, ['unsigned char']],
'PerfStatesCount' : [ 0x9a, ['unsigned char']],
'ProcessorMinThrottle' : [ 0x9b, ['unsigned char']],
'ProcessorMaxThrottle' : [ 0x9c, ['unsigned char']],
'EnableIdleAccounting' : [ 0x9d, ['unsigned char']],
'LastC3Percentage' : [ 0x9e, ['unsigned char']],
'LastAdjustedBusyPercentage' : [ 0x9f, ['unsigned char']],
'PromotionCount' : [ 0xa0, ['unsigned long']],
'DemotionCount' : [ 0xa4, ['unsigned long']],
'ErrorCount' : [ 0xa8, ['unsigned long']],
'RetryCount' : [ 0xac, ['unsigned long']],
'Flags' : [ 0xb0, ['unsigned long']],
'PerfCounterFrequency' : [ 0xb8, ['_LARGE_INTEGER']],
'PerfTickCount' : [ 0xc0, ['unsigned long']],
'PerfTimer' : [ 0xc8, ['_KTIMER']],
'PerfDpc' : [ 0xf0, ['_KDPC']],
'PerfStates' : [ 0x110, ['pointer', ['PROCESSOR_PERF_STATE']]],
'PerfSetThrottle' : [ 0x114, ['pointer', ['void']]],
'LastC3KernelUserTime' : [ 0x118, ['unsigned long']],
'LastPackageIdleTime' : [ 0x11c, ['unsigned long']],
} ],
'_DBGKD_READ_WRITE_MSR' : [ 0xc, {
'Msr' : [ 0x0, ['unsigned long']],
'DataValueLow' : [ 0x4, ['unsigned long']],
'DataValueHigh' : [ 0x8, ['unsigned long']],
} ],
'_MMPFNENTRY' : [ 0x4, {
'Modified' : [ 0x0, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned long')]],
'ReadInProgress' : [ 0x0, ['BitField', dict(start_bit = 1, end_bit = 2, native_type='unsigned long')]],
'WriteInProgress' : [ 0x0, ['BitField', dict(start_bit = 2, end_bit = 3, native_type='unsigned long')]],
'PrototypePte' : [ 0x0, ['BitField', dict(start_bit = 3, end_bit = 4, native_type='unsigned long')]],
'PageColor' : [ 0x0, ['BitField', dict(start_bit = 4, end_bit = 7, native_type='unsigned long')]],
'ParityError' : [ 0x0, ['BitField', dict(start_bit = 7, end_bit = 8, native_type='unsigned long')]],
'PageLocation' : [ 0x0, ['BitField', dict(start_bit = 8, end_bit = 11, native_type='unsigned long')]],
'RemovalRequested' : [ 0x0, ['BitField', dict(start_bit = 11, end_bit = 12, native_type='unsigned long')]],
'CacheAttribute' : [ 0x0, ['BitField', dict(start_bit = 12, end_bit = 14, native_type='unsigned long')]],
'Rom' : [ 0x0, ['BitField', dict(start_bit = 14, end_bit = 15, native_type='unsigned long')]],
'LockCharged' : [ 0x0, ['BitField', dict(start_bit = 15, end_bit = 16, native_type='unsigned long')]],
'DontUse' : [ 0x0, ['BitField', dict(start_bit = 16, end_bit = 32, native_type='unsigned long')]],
} ],
'_IO_COUNTERS' : [ 0x30, {
'ReadOperationCount' : [ 0x0, ['unsigned long long']],
'WriteOperationCount' : [ 0x8, ['unsigned long long']],
'OtherOperationCount' : [ 0x10, ['unsigned long long']],
'ReadTransferCount' : [ 0x18, ['unsigned long long']],
'WriteTransferCount' : [ 0x20, ['unsigned long long']],
'OtherTransferCount' : [ 0x28, ['unsigned long long']],
} ],
'_KTSS' : [ 0x20ac, {
'Backlink' : [ 0x0, ['unsigned short']],
'Reserved0' : [ 0x2, ['unsigned short']],
'Esp0' : [ 0x4, ['unsigned long']],
'Ss0' : [ 0x8, ['unsigned short']],
'Reserved1' : [ 0xa, ['unsigned short']],
'NotUsed1' : [ 0xc, ['array', 4, ['unsigned long']]],
'CR3' : [ 0x1c, ['unsigned long']],
'Eip' : [ 0x20, ['unsigned long']],
'EFlags' : [ 0x24, ['unsigned long']],
'Eax' : [ 0x28, ['unsigned long']],
'Ecx' : [ 0x2c, ['unsigned long']],
'Edx' : [ 0x30, ['unsigned long']],
'Ebx' : [ 0x34, ['unsigned long']],
'Esp' : [ 0x38, ['unsigned long']],
'Ebp' : [ 0x3c, ['unsigned long']],
'Esi' : [ 0x40, ['unsigned long']],
'Edi' : [ 0x44, ['unsigned long']],
'Es' : [ 0x48, ['unsigned short']],
'Reserved2' : [ 0x4a, ['unsigned short']],
'Cs' : [ 0x4c, ['unsigned short']],
'Reserved3' : [ 0x4e, ['unsigned short']],
'Ss' : [ 0x50, ['unsigned short']],
'Reserved4' : [ 0x52, ['unsigned short']],
'Ds' : [ 0x54, ['unsigned short']],
'Reserved5' : [ 0x56, ['unsigned short']],
'Fs' : [ 0x58, ['unsigned short']],
'Reserved6' : [ 0x5a, ['unsigned short']],
'Gs' : [ 0x5c, ['unsigned short']],
'Reserved7' : [ 0x5e, ['unsigned short']],
'LDT' : [ 0x60, ['unsigned short']],
'Reserved8' : [ 0x62, ['unsigned short']],
'Flags' : [ 0x64, ['unsigned short']],
'IoMapBase' : [ 0x66, ['unsigned short']],
'IoMaps' : [ 0x68, ['array', 1, ['_KiIoAccessMap']]],
'IntDirectionMap' : [ 0x208c, ['array', 32, ['unsigned char']]],
} ],
'_DBGKD_QUERY_MEMORY' : [ 0x18, {
'Address' : [ 0x0, ['unsigned long long']],
'Reserved' : [ 0x8, ['unsigned long long']],
'AddressSpace' : [ 0x10, ['unsigned long']],
'Flags' : [ 0x14, ['unsigned long']],
} ],
'_KIDTENTRY' : [ 0x8, {
'Offset' : [ 0x0, ['unsigned short']],
'Selector' : [ 0x2, ['unsigned short']],
'Access' : [ 0x4, ['unsigned short']],
'ExtendedOffset' : [ 0x6, ['unsigned short']],
} ],
'_DEVICE_OBJECT_POWER_EXTENSION' : [ 0x4c, {
'IdleCount' : [ 0x0, ['unsigned long']],
'ConservationIdleTime' : [ 0x4, ['unsigned long']],
'PerformanceIdleTime' : [ 0x8, ['unsigned long']],
'DeviceObject' : [ 0xc, ['pointer', ['_DEVICE_OBJECT']]],
'IdleList' : [ 0x10, ['_LIST_ENTRY']],
'DeviceType' : [ 0x18, ['unsigned char']],
'State' : [ 0x1c, ['Enumeration', dict(target = 'long', choices = {0: 'PowerDeviceUnspecified', 1: 'PowerDeviceD0', 2: 'PowerDeviceD1', 3: 'PowerDeviceD2', 4: 'PowerDeviceD3', 5: 'PowerDeviceMaximum'})]],
'NotifySourceList' : [ 0x20, ['_LIST_ENTRY']],
'NotifyTargetList' : [ 0x28, ['_LIST_ENTRY']],
'PowerChannelSummary' : [ 0x30, ['_POWER_CHANNEL_SUMMARY']],
'Volume' : [ 0x44, ['_LIST_ENTRY']],
} ],
'_MMSUPPORT_FLAGS' : [ 0x4, {
'SessionSpace' : [ 0x0, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned long')]],
'BeingTrimmed' : [ 0x0, ['BitField', dict(start_bit = 1, end_bit = 2, native_type='unsigned long')]],
'SessionLeader' : [ 0x0, ['BitField', dict(start_bit = 2, end_bit = 3, native_type='unsigned long')]],
'TrimHard' : [ 0x0, ['BitField', dict(start_bit = 3, end_bit = 4, native_type='unsigned long')]],
'WorkingSetHard' : [ 0x0, ['BitField', dict(start_bit = 4, end_bit = 5, native_type='unsigned long')]],
'AddressSpaceBeingDeleted' : [ 0x0, ['BitField', dict(start_bit = 5, end_bit = 6, native_type='unsigned long')]],
'Available' : [ 0x0, ['BitField', dict(start_bit = 6, end_bit = 16, native_type='unsigned long')]],
'AllowWorkingSetAdjustment' : [ 0x0, ['BitField', dict(start_bit = 16, end_bit = 24, native_type='unsigned long')]],
'MemoryPriority' : [ 0x0, ['BitField', dict(start_bit = 24, end_bit = 32, native_type='unsigned long')]],
} ],
'_TERMINATION_PORT' : [ 0x8, {
'Next' : [ 0x0, ['pointer', ['_TERMINATION_PORT']]],
'Port' : [ 0x4, ['pointer', ['void']]],
} ],
'_SYSTEM_POWER_POLICY' : [ 0xe8, {
'Revision' : [ 0x0, ['unsigned long']],
'PowerButton' : [ 0x4, ['POWER_ACTION_POLICY']],
'SleepButton' : [ 0x10, ['POWER_ACTION_POLICY']],
'LidClose' : [ 0x1c, ['POWER_ACTION_POLICY']],
'LidOpenWake' : [ 0x28, ['Enumeration', dict(target = 'long', choices = {0: 'PowerSystemUnspecified', 1: 'PowerSystemWorking', 2: 'PowerSystemSleeping1', 3: 'PowerSystemSleeping2', 4: 'PowerSystemSleeping3', 5: 'PowerSystemHibernate', 6: 'PowerSystemShutdown', 7: 'PowerSystemMaximum'})]],
'Reserved' : [ 0x2c, ['unsigned long']],
'Idle' : [ 0x30, ['POWER_ACTION_POLICY']],
'IdleTimeout' : [ 0x3c, ['unsigned long']],
'IdleSensitivity' : [ 0x40, ['unsigned char']],
'DynamicThrottle' : [ 0x41, ['unsigned char']],
'Spare2' : [ 0x42, ['array', 2, ['unsigned char']]],
'MinSleep' : [ 0x44, ['Enumeration', dict(target = 'long', choices = {0: 'PowerSystemUnspecified', 1: 'PowerSystemWorking', 2: 'PowerSystemSleeping1', 3: 'PowerSystemSleeping2', 4: 'PowerSystemSleeping3', 5: 'PowerSystemHibernate', 6: 'PowerSystemShutdown', 7: 'PowerSystemMaximum'})]],
'MaxSleep' : [ 0x48, ['Enumeration', dict(target = 'long', choices = {0: 'PowerSystemUnspecified', 1: 'PowerSystemWorking', 2: 'PowerSystemSleeping1', 3: 'PowerSystemSleeping2', 4: 'PowerSystemSleeping3', 5: 'PowerSystemHibernate', 6: 'PowerSystemShutdown', 7: 'PowerSystemMaximum'})]],
'ReducedLatencySleep' : [ 0x4c, ['Enumeration', dict(target = 'long', choices = {0: 'PowerSystemUnspecified', 1: 'PowerSystemWorking', 2: 'PowerSystemSleeping1', 3: 'PowerSystemSleeping2', 4: 'PowerSystemSleeping3', 5: 'PowerSystemHibernate', 6: 'PowerSystemShutdown', 7: 'PowerSystemMaximum'})]],
'WinLogonFlags' : [ 0x50, ['unsigned long']],
'Spare3' : [ 0x54, ['unsigned long']],
'DozeS4Timeout' : [ 0x58, ['unsigned long']],
'BroadcastCapacityResolution' : [ 0x5c, ['unsigned long']],
'DischargePolicy' : [ 0x60, ['array', 4, ['SYSTEM_POWER_LEVEL']]],
'VideoTimeout' : [ 0xc0, ['unsigned long']],
'VideoDimDisplay' : [ 0xc4, ['unsigned char']],
'VideoReserved' : [ 0xc8, ['array', 3, ['unsigned long']]],
'SpindownTimeout' : [ 0xd4, ['unsigned long']],
'OptimizeForPower' : [ 0xd8, ['unsigned char']],
'FanThrottleTolerance' : [ 0xd9, ['unsigned char']],
'ForcedThrottle' : [ 0xda, ['unsigned char']],
'MinThrottle' : [ 0xdb, ['unsigned char']],
'OverThrottled' : [ 0xdc, ['POWER_ACTION_POLICY']],
} ],
'_POP_THERMAL_ZONE' : [ 0xd0, {
'Link' : [ 0x0, ['_LIST_ENTRY']],
'State' : [ 0x8, ['unsigned char']],
'Flags' : [ 0x9, ['unsigned char']],
'Mode' : [ 0xa, ['unsigned char']],
'PendingMode' : [ 0xb, ['unsigned char']],
'ActivePoint' : [ 0xc, ['unsigned char']],
'PendingActivePoint' : [ 0xd, ['unsigned char']],
'Throttle' : [ 0x10, ['long']],
'LastTime' : [ 0x18, ['unsigned long long']],
'SampleRate' : [ 0x20, ['unsigned long']],
'LastTemp' : [ 0x24, ['unsigned long']],
'PassiveTimer' : [ 0x28, ['_KTIMER']],
'PassiveDpc' : [ 0x50, ['_KDPC']],
'OverThrottled' : [ 0x70, ['_POP_ACTION_TRIGGER']],
'Irp' : [ 0x7c, ['pointer', ['_IRP']]],
'Info' : [ 0x80, ['_THERMAL_INFORMATION']],
} ],
'_DBGKD_CONTINUE2' : [ 0x20, {
'ContinueStatus' : [ 0x0, ['long']],
'ControlSet' : [ 0x4, ['_X86_DBGKD_CONTROL_SET']],
'AnyControlSet' : [ 0x4, ['_DBGKD_ANY_CONTROL_SET']],
} ],
'_PROCESSOR_POWER_POLICY' : [ 0x4c, {
'Revision' : [ 0x0, ['unsigned long']],
'DynamicThrottle' : [ 0x4, ['unsigned char']],
'Spare' : [ 0x5, ['array', 3, ['unsigned char']]],
'DisableCStates' : [ 0x8, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned long')]],
'Reserved' : [ 0x8, ['BitField', dict(start_bit = 1, end_bit = 32, native_type='unsigned long')]],
'PolicyCount' : [ 0xc, ['unsigned long']],
'Policy' : [ 0x10, ['array', 3, ['_PROCESSOR_POWER_POLICY_INFO']]],
} ],
'_IMAGE_DOS_HEADER' : [ 0x40, {
'e_magic' : [ 0x0, ['unsigned short']],
'e_cblp' : [ 0x2, ['unsigned short']],
'e_cp' : [ 0x4, ['unsigned short']],
'e_crlc' : [ 0x6, ['unsigned short']],
'e_cparhdr' : [ 0x8, ['unsigned short']],
'e_minalloc' : [ 0xa, ['unsigned short']],
'e_maxalloc' : [ 0xc, ['unsigned short']],
'e_ss' : [ 0xe, ['unsigned short']],
'e_sp' : [ 0x10, ['unsigned short']],
'e_csum' : [ 0x12, ['unsigned short']],
'e_ip' : [ 0x14, ['unsigned short']],
'e_cs' : [ 0x16, ['unsigned short']],
'e_lfarlc' : [ 0x18, ['unsigned short']],
'e_ovno' : [ 0x1a, ['unsigned short']],
'e_res' : [ 0x1c, ['array', 4, ['unsigned short']]],
'e_oemid' : [ 0x24, ['unsigned short']],
'e_oeminfo' : [ 0x26, ['unsigned short']],
'e_res2' : [ 0x28, ['array', 10, ['unsigned short']]],
'e_lfanew' : [ 0x3c, ['long']],
} ],
'_OWNER_ENTRY' : [ 0x8, {
'OwnerThread' : [ 0x0, ['unsigned long']],
'OwnerCount' : [ 0x4, ['long']],
'TableSize' : [ 0x4, ['unsigned long']],
} ],
'_HEAP_VIRTUAL_ALLOC_ENTRY' : [ 0x20, {
'Entry' : [ 0x0, ['_LIST_ENTRY']],
'ExtraStuff' : [ 0x8, ['_HEAP_ENTRY_EXTRA']],
'CommitSize' : [ 0x10, ['unsigned long']],
'ReserveSize' : [ 0x14, ['unsigned long']],
'BusyBlock' : [ 0x18, ['_HEAP_ENTRY']],
} ],
'_RTL_ATOM_TABLE' : [ 0x44, {
'Signature' : [ 0x0, ['unsigned long']],
'CriticalSection' : [ 0x4, ['_RTL_CRITICAL_SECTION']],
'RtlHandleTable' : [ 0x1c, ['_RTL_HANDLE_TABLE']],
'NumberOfBuckets' : [ 0x3c, ['unsigned long']],
'Buckets' : [ 0x40, ['array', 1, ['pointer', ['_RTL_ATOM_TABLE_ENTRY']]]],
} ],
'_FNSAVE_FORMAT' : [ 0x6c, {
'ControlWord' : [ 0x0, ['unsigned long']],
'StatusWord' : [ 0x4, ['unsigned long']],
'TagWord' : [ 0x8, ['unsigned long']],
'ErrorOffset' : [ 0xc, ['unsigned long']],
'ErrorSelector' : [ 0x10, ['unsigned long']],
'DataOffset' : [ 0x14, ['unsigned long']],
'DataSelector' : [ 0x18, ['unsigned long']],
'RegisterArea' : [ 0x1c, ['array', 80, ['unsigned char']]],
} ],
'EX_QUEUE_WORKER_INFO' : [ 0x4, {
'QueueDisabled' : [ 0x0, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned long')]],
'MakeThreadsAsNecessary' : [ 0x0, ['BitField', dict(start_bit = 1, end_bit = 2, native_type='unsigned long')]],
'WaitMode' : [ 0x0, ['BitField', dict(start_bit = 2, end_bit = 3, native_type='unsigned long')]],
'WorkerCount' : [ 0x0, ['BitField', dict(start_bit = 3, end_bit = 32, native_type='unsigned long')]],
'QueueWorkerInfo' : [ 0x0, ['long']],
} ],
'SYSTEM_POWER_LEVEL' : [ 0x18, {
'Enable' : [ 0x0, ['unsigned char']],
'Spare' : [ 0x1, ['array', 3, ['unsigned char']]],
'BatteryLevel' : [ 0x4, ['unsigned long']],
'PowerPolicy' : [ 0x8, ['POWER_ACTION_POLICY']],
'MinSystemState' : [ 0x14, ['Enumeration', dict(target = 'long', choices = {0: 'PowerSystemUnspecified', 1: 'PowerSystemWorking', 2: 'PowerSystemSleeping1', 3: 'PowerSystemSleeping2', 4: 'PowerSystemSleeping3', 5: 'PowerSystemHibernate', 6: 'PowerSystemShutdown', 7: 'PowerSystemMaximum'})]],
} ],
'POWER_ACTION_POLICY' : [ 0xc, {
'Action' : [ 0x0, ['Enumeration', dict(target = 'long', choices = {0: 'PowerActionNone', 1: 'PowerActionReserved', 2: 'PowerActionSleep', 3: 'PowerActionHibernate', 4: 'PowerActionShutdown', 5: 'PowerActionShutdownReset', 6: 'PowerActionShutdownOff', 7: 'PowerActionWarmEject'})]],
'Flags' : [ 0x4, ['unsigned long']],
'EventCode' : [ 0x8, ['unsigned long']],
} ],
'PROCESSOR_PERF_STATE' : [ 0x20, {
'PercentFrequency' : [ 0x0, ['unsigned char']],
'MinCapacity' : [ 0x1, ['unsigned char']],
'Power' : [ 0x2, ['unsigned short']],
'IncreaseLevel' : [ 0x4, ['unsigned char']],
'DecreaseLevel' : [ 0x5, ['unsigned char']],
'Flags' : [ 0x6, ['unsigned short']],
'IncreaseTime' : [ 0x8, ['unsigned long']],
'DecreaseTime' : [ 0xc, ['unsigned long']],
'IncreaseCount' : [ 0x10, ['unsigned long']],
'DecreaseCount' : [ 0x14, ['unsigned long']],
'PerformanceTime' : [ 0x18, ['unsigned long long']],
} ],
'PROCESSOR_IDLE_TIMES' : [ 0x20, {
'StartTime' : [ 0x0, ['unsigned long long']],
'EndTime' : [ 0x8, ['unsigned long long']],
'IdleHandlerReserved' : [ 0x10, ['array', 4, ['unsigned long']]],
} ],
'_IMAGE_ROM_OPTIONAL_HEADER' : [ 0x38, {
'Magic' : [ 0x0, ['unsigned short']],
'MajorLinkerVersion' : [ 0x2, ['unsigned char']],
'MinorLinkerVersion' : [ 0x3, ['unsigned char']],
'SizeOfCode' : [ 0x4, ['unsigned long']],
'SizeOfInitializedData' : [ 0x8, ['unsigned long']],
'SizeOfUninitializedData' : [ 0xc, ['unsigned long']],
'AddressOfEntryPoint' : [ 0x10, ['unsigned long']],
'BaseOfCode' : [ 0x14, ['unsigned long']],
'BaseOfData' : [ 0x18, ['unsigned long']],
'BaseOfBss' : [ 0x1c, ['unsigned long']],
'GprMask' : [ 0x20, ['unsigned long']],
'CprMask' : [ 0x24, ['array', 4, ['unsigned long']]],
'GpValue' : [ 0x34, ['unsigned long']],
} ],
'_MMPTE_LIST' : [ 0x4, {
'Valid' : [ 0x0, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned long')]],
'OneEntry' : [ 0x0, ['BitField', dict(start_bit = 1, end_bit = 2, native_type='unsigned long')]],
'filler0' : [ 0x0, ['BitField', dict(start_bit = 2, end_bit = 10, native_type='unsigned long')]],
'Prototype' : [ 0x0, ['BitField', dict(start_bit = 10, end_bit = 11, native_type='unsigned long')]],
'filler1' : [ 0x0, ['BitField', dict(start_bit = 11, end_bit = 12, native_type='unsigned long')]],
'NextEntry' : [ 0x0, ['BitField', dict(start_bit = 12, end_bit = 32, native_type='unsigned long')]],
} ],
'_CMHIVE' : [ 0x49c, {
'Hive' : [ 0x0, ['_HHIVE']],
'FileHandles' : [ 0x210, ['array', 3, ['pointer', ['void']]]],
'NotifyList' : [ 0x21c, ['_LIST_ENTRY']],
'HiveList' : [ 0x224, ['_LIST_ENTRY']],
'HiveLock' : [ 0x22c, ['pointer', ['_FAST_MUTEX']]],
'ViewLock' : [ 0x230, ['pointer', ['_FAST_MUTEX']]],
'LRUViewListHead' : [ 0x234, ['_LIST_ENTRY']],
'PinViewListHead' : [ 0x23c, ['_LIST_ENTRY']],
'FileObject' : [ 0x244, ['pointer', ['_FILE_OBJECT']]],
'FileFullPath' : [ 0x248, ['_UNICODE_STRING']],
'FileUserName' : [ 0x250, ['_UNICODE_STRING']],
'MappedViews' : [ 0x258, ['unsigned short']],
'PinnedViews' : [ 0x25a, ['unsigned short']],
'UseCount' : [ 0x25c, ['unsigned long']],
'SecurityCount' : [ 0x260, ['unsigned long']],
'SecurityCacheSize' : [ 0x264, ['unsigned long']],
'SecurityHitHint' : [ 0x268, ['long']],
'SecurityCache' : [ 0x26c, ['pointer', ['_CM_KEY_SECURITY_CACHE_ENTRY']]],
'SecurityHash' : [ 0x270, ['array', 64, ['_LIST_ENTRY']]],
'UnloadEvent' : [ 0x470, ['pointer', ['_KEVENT']]],
'RootKcb' : [ 0x474, ['pointer', ['_CM_KEY_CONTROL_BLOCK']]],
'Frozen' : [ 0x478, ['unsigned char']],
'UnloadWorkItem' : [ 0x47c, ['pointer', ['_WORK_QUEUE_ITEM']]],
'GrowOnlyMode' : [ 0x480, ['unsigned char']],
'GrowOffset' : [ 0x484, ['unsigned long']],
'KcbConvertListHead' : [ 0x488, ['_LIST_ENTRY']],
'KnodeConvertListHead' : [ 0x490, ['_LIST_ENTRY']],
'CellRemapArray' : [ 0x498, ['pointer', ['_CM_CELL_REMAP_BLOCK']]],
} ],
'_HANDLE_TRACE_DEBUG_INFO' : [ 0x50004, {
'CurrentStackIndex' : [ 0x0, ['unsigned long']],
'TraceDb' : [ 0x4, ['array', 4096, ['_HANDLE_TRACE_DB_ENTRY']]],
} ],
'_HHIVE' : [ 0x210, {
'Signature' : [ 0x0, ['unsigned long']],
'GetCellRoutine' : [ 0x4, ['pointer', ['void']]],
'ReleaseCellRoutine' : [ 0x8, ['pointer', ['void']]],
'Allocate' : [ 0xc, ['pointer', ['void']]],
'Free' : [ 0x10, ['pointer', ['void']]],
'FileSetSize' : [ 0x14, ['pointer', ['void']]],
'FileWrite' : [ 0x18, ['pointer', ['void']]],
'FileRead' : [ 0x1c, ['pointer', ['void']]],
'FileFlush' : [ 0x20, ['pointer', ['void']]],
'BaseBlock' : [ 0x24, ['pointer', ['_HBASE_BLOCK']]],
'DirtyVector' : [ 0x28, ['_RTL_BITMAP']],
'DirtyCount' : [ 0x30, ['unsigned long']],
'DirtyAlloc' : [ 0x34, ['unsigned long']],
'RealWrites' : [ 0x38, ['unsigned char']],
'Cluster' : [ 0x3c, ['unsigned long']],
'Flat' : [ 0x40, ['unsigned char']],
'ReadOnly' : [ 0x41, ['unsigned char']],
'Log' : [ 0x42, ['unsigned char']],
'HiveFlags' : [ 0x44, ['unsigned long']],
'LogSize' : [ 0x48, ['unsigned long']],
'RefreshCount' : [ 0x4c, ['unsigned long']],
'StorageTypeCount' : [ 0x50, ['unsigned long']],
'Version' : [ 0x54, ['unsigned long']],
'Storage' : [ 0x58, ['array', 2, ['_DUAL']]],
} ],
'_PAGEFAULT_HISTORY' : [ 0x18, {
'CurrentIndex' : [ 0x0, ['unsigned long']],
'MaxIndex' : [ 0x4, ['unsigned long']],
'SpinLock' : [ 0x8, ['unsigned long']],
'Reserved' : [ 0xc, ['pointer', ['void']]],
'WatchInfo' : [ 0x10, ['array', 1, ['_PROCESS_WS_WATCH_INFORMATION']]],
} ],
'_RTL_ATOM_TABLE_ENTRY' : [ 0x10, {
'HashLink' : [ 0x0, ['pointer', ['_RTL_ATOM_TABLE_ENTRY']]],
'HandleIndex' : [ 0x4, ['unsigned short']],
'Atom' : [ 0x6, ['unsigned short']],
'ReferenceCount' : [ 0x8, ['unsigned short']],
'Flags' : [ 0xa, ['unsigned char']],
'NameLength' : [ 0xb, ['unsigned char']],
'Name' : [ 0xc, ['array', 1, ['unsigned short']]],
} ],
'_MM_SESSION_SPACE_FLAGS' : [ 0x4, {
'Initialized' : [ 0x0, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned long')]],
'Filler0' : [ 0x0, ['BitField', dict(start_bit = 1, end_bit = 4, native_type='unsigned long')]],
'HasWsLock' : [ 0x0, ['BitField', dict(start_bit = 4, end_bit = 5, native_type='unsigned long')]],
'DeletePending' : [ 0x0, ['BitField', dict(start_bit = 5, end_bit = 6, native_type='unsigned long')]],
'Filler' : [ 0x0, ['BitField', dict(start_bit = 6, end_bit = 32, native_type='unsigned long')]],
} ],
'_CM_PARTIAL_RESOURCE_LIST' : [ 0x18, {
'Version' : [ 0x0, ['unsigned short']],
'Revision' : [ 0x2, ['unsigned short']],
'Count' : [ 0x4, ['unsigned long']],
'PartialDescriptors' : [ 0x8, ['array', 1, ['_CM_PARTIAL_RESOURCE_DESCRIPTOR']]],
} ],
'_DRIVER_OBJECT' : [ 0xa8, {
'Type' : [ 0x0, ['short']],
'Size' : [ 0x2, ['short']],
'DeviceObject' : [ 0x4, ['pointer', ['_DEVICE_OBJECT']]],
'Flags' : [ 0x8, ['unsigned long']],
'DriverStart' : [ 0xc, ['pointer', ['void']]],
'DriverSize' : [ 0x10, ['unsigned long']],
'DriverSection' : [ 0x14, ['pointer', ['void']]],
'DriverExtension' : [ 0x18, ['pointer', ['_DRIVER_EXTENSION']]],
'DriverName' : [ 0x1c, ['_UNICODE_STRING']],
'HardwareDatabase' : [ 0x24, ['pointer', ['_UNICODE_STRING']]],
'FastIoDispatch' : [ 0x28, ['pointer', ['_FAST_IO_DISPATCH']]],
'DriverInit' : [ 0x2c, ['pointer', ['void']]],
'DriverStartIo' : [ 0x30, ['pointer', ['void']]],
'DriverUnload' : [ 0x34, ['pointer', ['void']]],
'MajorFunction' : [ 0x38, ['array', 28, ['pointer', ['void']]]],
} ],
'_WMI_BUFFER_STATE' : [ 0x4, {
'Free' : [ 0x0, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned long')]],
'InUse' : [ 0x0, ['BitField', dict(start_bit = 1, end_bit = 2, native_type='unsigned long')]],
'Flush' : [ 0x0, ['BitField', dict(start_bit = 2, end_bit = 3, native_type='unsigned long')]],
'Unused' : [ 0x0, ['BitField', dict(start_bit = 3, end_bit = 32, native_type='unsigned long')]],
} ],
'_MMFREE_POOL_ENTRY' : [ 0x14, {
'List' : [ 0x0, ['_LIST_ENTRY']],
'Size' : [ 0x8, ['unsigned long']],
'Signature' : [ 0xc, ['unsigned long']],
'Owner' : [ 0x10, ['pointer', ['_MMFREE_POOL_ENTRY']]],
} ],
'__unnamed_143b' : [ 0x28, {
'ListEntry' : [ 0x0, ['_LIST_ENTRY']],
'Wcb' : [ 0x0, ['_WAIT_CONTEXT_BLOCK']],
} ],
'_DEVICE_OBJECT' : [ 0xb8, {
'Type' : [ 0x0, ['short']],
'Size' : [ 0x2, ['unsigned short']],
'ReferenceCount' : [ 0x4, ['long']],
'DriverObject' : [ 0x8, ['pointer', ['_DRIVER_OBJECT']]],
'NextDevice' : [ 0xc, ['pointer', ['_DEVICE_OBJECT']]],
'AttachedDevice' : [ 0x10, ['pointer', ['_DEVICE_OBJECT']]],
'CurrentIrp' : [ 0x14, ['pointer', ['_IRP']]],
'Timer' : [ 0x18, ['pointer', ['_IO_TIMER']]],
'Flags' : [ 0x1c, ['unsigned long']],
'Characteristics' : [ 0x20, ['unsigned long']],
'Vpb' : [ 0x24, ['pointer', ['_VPB']]],
'DeviceExtension' : [ 0x28, ['pointer', ['void']]],
'DeviceType' : [ 0x2c, ['unsigned long']],
'StackSize' : [ 0x30, ['unsigned char']],
'Queue' : [ 0x34, ['__unnamed_143b']],
'AlignmentRequirement' : [ 0x5c, ['unsigned long']],
'DeviceQueue' : [ 0x60, ['_KDEVICE_QUEUE']],
'Dpc' : [ 0x74, ['_KDPC']],
'ActiveThreadCount' : [ 0x94, ['unsigned long']],
'SecurityDescriptor' : [ 0x98, ['pointer', ['void']]],
'DeviceLock' : [ 0x9c, ['_KEVENT']],
'SectorSize' : [ 0xac, ['unsigned short']],
'Spare1' : [ 0xae, ['unsigned short']],
'DeviceObjectExtension' : [ 0xb0, ['pointer', ['_DEVOBJ_EXTENSION']]],
'Reserved' : [ 0xb4, ['pointer', ['void']]],
} ],
'_SECTION_OBJECT_POINTERS' : [ 0xc, {
'DataSectionObject' : [ 0x0, ['pointer', ['void']]],
'SharedCacheMap' : [ 0x4, ['pointer', ['void']]],
'ImageSectionObject' : [ 0x8, ['pointer', ['void']]],
} ],
'_RTL_BITMAP' : [ 0x8, {
'SizeOfBitMap' : [ 0x0, ['unsigned long']],
'Buffer' : [ 0x4, ['pointer', ['unsigned long']]],
} ],
'_MBCB' : [ 0x80, {
'NodeTypeCode' : [ 0x0, ['short']],
'NodeIsInZone' : [ 0x2, ['short']],
'PagesToWrite' : [ 0x4, ['unsigned long']],
'DirtyPages' : [ 0x8, ['unsigned long']],
'Reserved' : [ 0xc, ['unsigned long']],
'BitmapRanges' : [ 0x10, ['_LIST_ENTRY']],
'ResumeWritePage' : [ 0x18, ['long long']],
'BitmapRange1' : [ 0x20, ['_BITMAP_RANGE']],
'BitmapRange2' : [ 0x40, ['_BITMAP_RANGE']],
'BitmapRange3' : [ 0x60, ['_BITMAP_RANGE']],
} ],
'_POWER_CHANNEL_SUMMARY' : [ 0x14, {
'Signature' : [ 0x0, ['unsigned long']],
'TotalCount' : [ 0x4, ['unsigned long']],
'D0Count' : [ 0x8, ['unsigned long']],
'NotifyList' : [ 0xc, ['_LIST_ENTRY']],
} ],
'_CM_VIEW_OF_FILE' : [ 0x24, {
'LRUViewList' : [ 0x0, ['_LIST_ENTRY']],
'PinViewList' : [ 0x8, ['_LIST_ENTRY']],
'FileOffset' : [ 0x10, ['unsigned long']],
'Size' : [ 0x14, ['unsigned long']],
'ViewAddress' : [ 0x18, ['pointer', ['unsigned long']]],
'Bcb' : [ 0x1c, ['pointer', ['void']]],
'UseCount' : [ 0x20, ['unsigned long']],
} ],
'_KDEVICE_QUEUE' : [ 0x14, {
'Type' : [ 0x0, ['short']],
'Size' : [ 0x2, ['short']],
'DeviceListHead' : [ 0x4, ['_LIST_ENTRY']],
'Lock' : [ 0xc, ['unsigned long']],
'Busy' : [ 0x10, ['unsigned char']],
} ],
'_KUSER_SHARED_DATA' : [ 0x338, {
'TickCountLow' : [ 0x0, ['unsigned long']],
'TickCountMultiplier' : [ 0x4, ['unsigned long']],
'InterruptTime' : [ 0x8, ['_KSYSTEM_TIME']],
'SystemTime' : [ 0x14, ['_KSYSTEM_TIME']],
'TimeZoneBias' : [ 0x20, ['_KSYSTEM_TIME']],
'ImageNumberLow' : [ 0x2c, ['unsigned short']],
'ImageNumberHigh' : [ 0x2e, ['unsigned short']],
'NtSystemRoot' : [ 0x30, ['array', 260, ['unsigned short']]],
'MaxStackTraceDepth' : [ 0x238, ['unsigned long']],
'CryptoExponent' : [ 0x23c, ['unsigned long']],
'TimeZoneId' : [ 0x240, ['unsigned long']],
'Reserved2' : [ 0x244, ['array', 8, ['unsigned long']]],
'NtProductType' : [ 0x264, ['Enumeration', dict(target = 'long', choices = {1: 'NtProductWinNt', 2: 'NtProductLanManNt', 3: 'NtProductServer'})]],
'ProductTypeIsValid' : [ 0x268, ['unsigned char']],
'NtMajorVersion' : [ 0x26c, ['unsigned long']],
'NtMinorVersion' : [ 0x270, ['unsigned long']],
'ProcessorFeatures' : [ 0x274, ['array', 64, ['unsigned char']]],
'Reserved1' : [ 0x2b4, ['unsigned long']],
'Reserved3' : [ 0x2b8, ['unsigned long']],
'TimeSlip' : [ 0x2bc, ['unsigned long']],
'AlternativeArchitecture' : [ 0x2c0, ['Enumeration', dict(target = 'long', choices = {0: 'StandardDesign', 1: 'NEC98x86', 2: 'EndAlternatives'})]],
'SystemExpirationDate' : [ 0x2c8, ['_LARGE_INTEGER']],
'SuiteMask' : [ 0x2d0, ['unsigned long']],
'KdDebuggerEnabled' : [ 0x2d4, ['unsigned char']],
'NXSupportPolicy' : [ 0x2d5, ['unsigned char']],
'ActiveConsoleId' : [ 0x2d8, ['unsigned long']],
'DismountCount' : [ 0x2dc, ['unsigned long']],
'ComPlusPackage' : [ 0x2e0, ['unsigned long']],
'LastSystemRITEventTickCount' : [ 0x2e4, ['unsigned long']],
'NumberOfPhysicalPages' : [ 0x2e8, ['unsigned long']],
'SafeBootMode' : [ 0x2ec, ['unsigned char']],
'TraceLogging' : [ 0x2f0, ['unsigned long']],
'TestRetInstruction' : [ 0x2f8, ['unsigned long long']],
'SystemCall' : [ 0x300, ['unsigned long']],
'SystemCallReturn' : [ 0x304, ['unsigned long']],
'SystemCallPad' : [ 0x308, ['array', 3, ['unsigned long long']]],
'TickCount' : [ 0x320, ['_KSYSTEM_TIME']],
'TickCountQuad' : [ 0x320, ['unsigned long long']],
'Cookie' : [ 0x330, ['unsigned long']],
} ],
'_OBJECT_TYPE_INITIALIZER' : [ 0x4c, {
'Length' : [ 0x0, ['unsigned short']],
'UseDefaultObject' : [ 0x2, ['unsigned char']],
'CaseInsensitive' : [ 0x3, ['unsigned char']],
'InvalidAttributes' : [ 0x4, ['unsigned long']],
'GenericMapping' : [ 0x8, ['_GENERIC_MAPPING']],
'ValidAccessMask' : [ 0x18, ['unsigned long']],
'SecurityRequired' : [ 0x1c, ['unsigned char']],
'MaintainHandleCount' : [ 0x1d, ['unsigned char']],
'MaintainTypeList' : [ 0x1e, ['unsigned char']],
'PoolType' : [ 0x20, ['Enumeration', dict(target = 'long', choices = {0: 'NonPagedPool', 1: 'PagedPool', 2: 'NonPagedPoolMustSucceed', 3: 'DontUseThisType', 4: 'NonPagedPoolCacheAligned', 5: 'PagedPoolCacheAligned', 6: 'NonPagedPoolCacheAlignedMustS', 7: 'MaxPoolType', 34: 'NonPagedPoolMustSucceedSession', 35: 'DontUseThisTypeSession', 32: 'NonPagedPoolSession', 36: 'NonPagedPoolCacheAlignedSession', 33: 'PagedPoolSession', 38: 'NonPagedPoolCacheAlignedMustSSession', 37: 'PagedPoolCacheAlignedSession'})]],
'DefaultPagedPoolCharge' : [ 0x24, ['unsigned long']],
'DefaultNonPagedPoolCharge' : [ 0x28, ['unsigned long']],
'DumpProcedure' : [ 0x2c, ['pointer', ['void']]],
'OpenProcedure' : [ 0x30, ['pointer', ['void']]],
'CloseProcedure' : [ 0x34, ['pointer', ['void']]],
'DeleteProcedure' : [ 0x38, ['pointer', ['void']]],
'ParseProcedure' : [ 0x3c, ['pointer', ['void']]],
'SecurityProcedure' : [ 0x40, ['pointer', ['void']]],
'QueryNameProcedure' : [ 0x44, ['pointer', ['void']]],
'OkayToCloseProcedure' : [ 0x48, ['pointer', ['void']]],
} ],
'__unnamed_1481' : [ 0x4, {
'LongFlags' : [ 0x0, ['unsigned long']],
'SubsectionFlags' : [ 0x0, ['_MMSUBSECTION_FLAGS']],
} ],
'_SUBSECTION' : [ 0x20, {
'ControlArea' : [ 0x0, ['pointer', ['_CONTROL_AREA']]],
'u' : [ 0x4, ['__unnamed_1481']],
'StartingSector' : [ 0x8, ['unsigned long']],
'NumberOfFullSectors' : [ 0xc, ['unsigned long']],
'SubsectionBase' : [ 0x10, ['pointer', ['_MMPTE']]],
'UnusedPtes' : [ 0x14, ['unsigned long']],
'PtesInSubsection' : [ 0x18, ['unsigned long']],
'NextSubsection' : [ 0x1c, ['pointer', ['_SUBSECTION']]],
} ],
'_WMI_LOGGER_MODE' : [ 0x4, {
'SequentialFile' : [ 0x0, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned long')]],
'CircularFile' : [ 0x0, ['BitField', dict(start_bit = 1, end_bit = 2, native_type='unsigned long')]],
'AppendFile' : [ 0x0, ['BitField', dict(start_bit = 2, end_bit = 3, native_type='unsigned long')]],
'Unused1' : [ 0x0, ['BitField', dict(start_bit = 3, end_bit = 8, native_type='unsigned long')]],
'RealTime' : [ 0x0, ['BitField', dict(start_bit = 8, end_bit = 9, native_type='unsigned long')]],
'DelayOpenFile' : [ 0x0, ['BitField', dict(start_bit = 9, end_bit = 10, native_type='unsigned long')]],
'BufferOnly' : [ 0x0, ['BitField', dict(start_bit = 10, end_bit = 11, native_type='unsigned long')]],
'PrivateLogger' : [ 0x0, ['BitField', dict(start_bit = 11, end_bit = 12, native_type='unsigned long')]],
'AddHeader' : [ 0x0, ['BitField', dict(start_bit = 12, end_bit = 13, native_type='unsigned long')]],
'UseExisting' : [ 0x0, ['BitField', dict(start_bit = 13, end_bit = 14, native_type='unsigned long')]],
'UseGlobalSequence' : [ 0x0, ['BitField', dict(start_bit = 14, end_bit = 15, native_type='unsigned long')]],
'UseLocalSequence' : [ 0x0, ['BitField', dict(start_bit = 15, end_bit = 16, native_type='unsigned long')]],
'Unused2' : [ 0x0, ['BitField', dict(start_bit = 16, end_bit = 32, native_type='unsigned long')]],
} ],
'_NT_TIB' : [ 0x1c, {
'ExceptionList' : [ 0x0, ['pointer', ['_EXCEPTION_REGISTRATION_RECORD']]],
'StackBase' : [ 0x4, ['pointer', ['void']]],
'StackLimit' : [ 0x8, ['pointer', ['void']]],
'SubSystemTib' : [ 0xc, ['pointer', ['void']]],
'FiberData' : [ 0x10, ['pointer', ['void']]],
'Version' : [ 0x10, ['unsigned long']],
'ArbitraryUserPointer' : [ 0x14, ['pointer', ['void']]],
'Self' : [ 0x18, ['pointer', ['_NT_TIB']]],
} ],
'__unnamed_1492' : [ 0x4, {
'LongFlags' : [ 0x0, ['unsigned long']],
'VadFlags' : [ 0x0, ['_MMVAD_FLAGS']],
} ],
'__unnamed_1495' : [ 0x4, {
'LongFlags2' : [ 0x0, ['unsigned long']],
'VadFlags2' : [ 0x0, ['_MMVAD_FLAGS2']],
} ],
'__unnamed_1498' : [ 0x8, {
'List' : [ 0x0, ['_LIST_ENTRY']],
'Secured' : [ 0x0, ['_MMADDRESS_LIST']],
} ],
'__unnamed_149e' : [ 0x4, {
'Banked' : [ 0x0, ['pointer', ['_MMBANKED_SECTION']]],
'ExtendedInfo' : [ 0x0, ['pointer', ['_MMEXTEND_INFO']]],
} ],
'_MMVAD_LONG' : [ 0x34, {
'StartingVpn' : [ 0x0, ['unsigned long']],
'EndingVpn' : [ 0x4, ['unsigned long']],
'Parent' : [ 0x8, ['pointer', ['_MMVAD']]],
'LeftChild' : [ 0xc, ['pointer', ['_MMVAD']]],
'RightChild' : [ 0x10, ['pointer', ['_MMVAD']]],
'u' : [ 0x14, ['__unnamed_1492']],
'ControlArea' : [ 0x18, ['pointer', ['_CONTROL_AREA']]],
'FirstPrototypePte' : [ 0x1c, ['pointer', ['_MMPTE']]],
'LastContiguousPte' : [ 0x20, ['pointer', ['_MMPTE']]],
'u2' : [ 0x24, ['__unnamed_1495']],
'u3' : [ 0x28, ['__unnamed_1498']],
'u4' : [ 0x30, ['__unnamed_149e']],
} ],
'_MMVAD_FLAGS' : [ 0x4, {
'CommitCharge' : [ 0x0, ['BitField', dict(start_bit = 0, end_bit = 19, native_type='unsigned long')]],
'PhysicalMapping' : [ 0x0, ['BitField', dict(start_bit = 19, end_bit = 20, native_type='unsigned long')]],
'ImageMap' : [ 0x0, ['BitField', dict(start_bit = 20, end_bit = 21, native_type='unsigned long')]],
'UserPhysicalPages' : [ 0x0, ['BitField', dict(start_bit = 21, end_bit = 22, native_type='unsigned long')]],
'NoChange' : [ 0x0, ['BitField', dict(start_bit = 22, end_bit = 23, native_type='unsigned long')]],
'WriteWatch' : [ 0x0, ['BitField', dict(start_bit = 23, end_bit = 24, native_type='unsigned long')]],
'Protection' : [ 0x0, ['BitField', dict(start_bit = 24, end_bit = 29, native_type='unsigned long')]],
'LargePages' : [ 0x0, ['BitField', dict(start_bit = 29, end_bit = 30, native_type='unsigned long')]],
'MemCommit' : [ 0x0, ['BitField', dict(start_bit = 30, end_bit = 31, native_type='unsigned long')]],
'PrivateMemory' : [ 0x0, ['BitField', dict(start_bit = 31, end_bit = 32, native_type='unsigned long')]],
} ],
'_POOL_DESCRIPTOR' : [ 0x1028, {
'PoolType' : [ 0x0, ['Enumeration', dict(target = 'long', choices = {0: 'NonPagedPool', 1: 'PagedPool', 2: 'NonPagedPoolMustSucceed', 3: 'DontUseThisType', 4: 'NonPagedPoolCacheAligned', 5: 'PagedPoolCacheAligned', 6: 'NonPagedPoolCacheAlignedMustS', 7: 'MaxPoolType', 34: 'NonPagedPoolMustSucceedSession', 35: 'DontUseThisTypeSession', 32: 'NonPagedPoolSession', 36: 'NonPagedPoolCacheAlignedSession', 33: 'PagedPoolSession', 38: 'NonPagedPoolCacheAlignedMustSSession', 37: 'PagedPoolCacheAlignedSession'})]],
'PoolIndex' : [ 0x4, ['unsigned long']],
'RunningAllocs' : [ 0x8, ['unsigned long']],
'RunningDeAllocs' : [ 0xc, ['unsigned long']],
'TotalPages' : [ 0x10, ['unsigned long']],
'TotalBigPages' : [ 0x14, ['unsigned long']],
'Threshold' : [ 0x18, ['unsigned long']],
'LockAddress' : [ 0x1c, ['pointer', ['void']]],
'PendingFrees' : [ 0x20, ['pointer', ['void']]],
'PendingFreeDepth' : [ 0x24, ['long']],
'ListHeads' : [ 0x28, ['array', 512, ['_LIST_ENTRY']]],
} ],
'_HARDWARE_PTE' : [ 0x4, {
'Valid' : [ 0x0, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned long')]],
'Write' : [ 0x0, ['BitField', dict(start_bit = 1, end_bit = 2, native_type='unsigned long')]],
'Owner' : [ 0x0, ['BitField', dict(start_bit = 2, end_bit = 3, native_type='unsigned long')]],
'WriteThrough' : [ 0x0, ['BitField', dict(start_bit = 3, end_bit = 4, native_type='unsigned long')]],
'CacheDisable' : [ 0x0, ['BitField', dict(start_bit = 4, end_bit = 5, native_type='unsigned long')]],
'Accessed' : [ 0x0, ['BitField', dict(start_bit = 5, end_bit = 6, native_type='unsigned long')]],
'Dirty' : [ 0x0, ['BitField', dict(start_bit = 6, end_bit = 7, native_type='unsigned long')]],
'LargePage' : [ 0x0, ['BitField', dict(start_bit = 7, end_bit = 8, native_type='unsigned long')]],
'Global' : [ 0x0, ['BitField', dict(start_bit = 8, end_bit = 9, native_type='unsigned long')]],
'CopyOnWrite' : [ 0x0, ['BitField', dict(start_bit = 9, end_bit = 10, native_type='unsigned long')]],
'Prototype' : [ 0x0, ['BitField', dict(start_bit = 10, end_bit = 11, native_type='unsigned long')]],
'reserved' : [ 0x0, ['BitField', dict(start_bit = 11, end_bit = 12, native_type='unsigned long')]],
'PageFrameNumber' : [ 0x0, ['BitField', dict(start_bit = 12, end_bit = 32, native_type='unsigned long')]],
} ],
'_PEB_LDR_DATA' : [ 0x28, {
'Length' : [ 0x0, ['unsigned long']],
'Initialized' : [ 0x4, ['unsigned char']],
'SsHandle' : [ 0x8, ['pointer', ['void']]],
'InLoadOrderModuleList' : [ 0xc, ['_LIST_ENTRY']],
'InMemoryOrderModuleList' : [ 0x14, ['_LIST_ENTRY']],
'InInitializationOrderModuleList' : [ 0x1c, ['_LIST_ENTRY']],
'EntryInProgress' : [ 0x24, ['pointer', ['void']]],
} ],
'_DBGKD_GET_VERSION32' : [ 0x28, {
'MajorVersion' : [ 0x0, ['unsigned short']],
'MinorVersion' : [ 0x2, ['unsigned short']],
'ProtocolVersion' : [ 0x4, ['unsigned short']],
'Flags' : [ 0x6, ['unsigned short']],
'KernBase' : [ 0x8, ['unsigned long']],
'PsLoadedModuleList' : [ 0xc, ['unsigned long']],
'MachineType' : [ 0x10, ['unsigned short']],
'ThCallbackStack' : [ 0x12, ['unsigned short']],
'NextCallback' : [ 0x14, ['unsigned short']],
'FramePointer' : [ 0x16, ['unsigned short']],
'KiCallUserMode' : [ 0x18, ['unsigned long']],
'KeUserCallbackDispatcher' : [ 0x1c, ['unsigned long']],
'BreakpointWithStatus' : [ 0x20, ['unsigned long']],
'DebuggerDataList' : [ 0x24, ['unsigned long']],
} ],
'_MM_PAGED_POOL_INFO' : [ 0x24, {
'PagedPoolAllocationMap' : [ 0x0, ['pointer', ['_RTL_BITMAP']]],
'EndOfPagedPoolBitmap' : [ 0x4, ['pointer', ['_RTL_BITMAP']]],
'PagedPoolLargeSessionAllocationMap' : [ 0x8, ['pointer', ['_RTL_BITMAP']]],
'FirstPteForPagedPool' : [ 0xc, ['pointer', ['_MMPTE']]],
'LastPteForPagedPool' : [ 0x10, ['pointer', ['_MMPTE']]],
'NextPdeForPagedPoolExpansion' : [ 0x14, ['pointer', ['_MMPTE']]],
'PagedPoolHint' : [ 0x18, ['unsigned long']],
'PagedPoolCommit' : [ 0x1c, ['unsigned long']],
'AllocatedPagedPool' : [ 0x20, ['unsigned long']],
} ],
'_INTERLOCK_SEQ' : [ 0x8, {
'Depth' : [ 0x0, ['unsigned short']],
'FreeEntryOffset' : [ 0x2, ['unsigned short']],
'OffsetAndDepth' : [ 0x0, ['unsigned long']],
'Sequence' : [ 0x4, ['unsigned long']],
'Exchg' : [ 0x0, ['long long']],
} ],
'_VPB' : [ 0x58, {
'Type' : [ 0x0, ['short']],
'Size' : [ 0x2, ['short']],
'Flags' : [ 0x4, ['unsigned short']],
'VolumeLabelLength' : [ 0x6, ['unsigned short']],
'DeviceObject' : [ 0x8, ['pointer', ['_DEVICE_OBJECT']]],
'RealDevice' : [ 0xc, ['pointer', ['_DEVICE_OBJECT']]],
'SerialNumber' : [ 0x10, ['unsigned long']],
'ReferenceCount' : [ 0x14, ['unsigned long']],
'VolumeLabel' : [ 0x18, ['array', 32, ['unsigned short']]],
} ],
'_MMSESSION' : [ 0x3c, {
'SystemSpaceViewLock' : [ 0x0, ['_FAST_MUTEX']],
'SystemSpaceViewLockPointer' : [ 0x20, ['pointer', ['_FAST_MUTEX']]],
'SystemSpaceViewStart' : [ 0x24, ['pointer', ['unsigned char']]],
'SystemSpaceViewTable' : [ 0x28, ['pointer', ['_MMVIEW']]],
'SystemSpaceHashSize' : [ 0x2c, ['unsigned long']],
'SystemSpaceHashEntries' : [ 0x30, ['unsigned long']],
'SystemSpaceHashKey' : [ 0x34, ['unsigned long']],
'SystemSpaceBitMap' : [ 0x38, ['pointer', ['_RTL_BITMAP']]],
} ],
'_GENERIC_MAPPING' : [ 0x10, {
'GenericRead' : [ 0x0, ['unsigned long']],
'GenericWrite' : [ 0x4, ['unsigned long']],
'GenericExecute' : [ 0x8, ['unsigned long']],
'GenericAll' : [ 0xc, ['unsigned long']],
} ],
'_KiIoAccessMap' : [ 0x2024, {
'DirectionMap' : [ 0x0, ['array', 32, ['unsigned char']]],
'IoMap' : [ 0x20, ['array', 8196, ['unsigned char']]],
} ],
'_DBGKD_RESTORE_BREAKPOINT' : [ 0x4, {
'BreakPointHandle' : [ 0x0, ['unsigned long']],
} ],
'_EXCEPTION_REGISTRATION_RECORD' : [ 0x8, {
'Next' : [ 0x0, ['pointer', ['_EXCEPTION_REGISTRATION_RECORD']]],
'Handler' : [ 0x4, ['pointer', ['void']]],
} ],
'_POOL_TRACKER_BIG_PAGES' : [ 0xc, {
'Va' : [ 0x0, ['pointer', ['void']]],
'Key' : [ 0x4, ['unsigned long']],
'NumberOfPages' : [ 0x8, ['unsigned long']],
} ],
'_PROCESS_WS_WATCH_INFORMATION' : [ 0x8, {
'FaultingPc' : [ 0x0, ['pointer', ['void']]],
'FaultingVa' : [ 0x4, ['pointer', ['void']]],
} ],
'_MMPTE_SUBSECTION' : [ 0x4, {
'Valid' : [ 0x0, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned long')]],
'SubsectionAddressLow' : [ 0x0, ['BitField', dict(start_bit = 1, end_bit = 5, native_type='unsigned long')]],
'Protection' : [ 0x0, ['BitField', dict(start_bit = 5, end_bit = 10, native_type='unsigned long')]],
'Prototype' : [ 0x0, ['BitField', dict(start_bit = 10, end_bit = 11, native_type='unsigned long')]],
'SubsectionAddressHigh' : [ 0x0, ['BitField', dict(start_bit = 11, end_bit = 31, native_type='unsigned long')]],
'WhichPool' : [ 0x0, ['BitField', dict(start_bit = 31, end_bit = 32, native_type='unsigned long')]],
} ],
'_VI_DEADLOCK_NODE' : [ 0x68, {
'Parent' : [ 0x0, ['pointer', ['_VI_DEADLOCK_NODE']]],
'ChildrenList' : [ 0x4, ['_LIST_ENTRY']],
'SiblingsList' : [ 0xc, ['_LIST_ENTRY']],
'ResourceList' : [ 0x14, ['_LIST_ENTRY']],
'FreeListEntry' : [ 0x14, ['_LIST_ENTRY']],
'Root' : [ 0x1c, ['pointer', ['_VI_DEADLOCK_RESOURCE']]],
'ThreadEntry' : [ 0x20, ['pointer', ['_VI_DEADLOCK_THREAD']]],
'Active' : [ 0x24, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned long')]],
'OnlyTryAcquireUsed' : [ 0x24, ['BitField', dict(start_bit = 1, end_bit = 2, native_type='unsigned long')]],
'SequenceNumber' : [ 0x24, ['BitField', dict(start_bit = 2, end_bit = 32, native_type='unsigned long')]],
'StackTrace' : [ 0x28, ['array', 8, ['pointer', ['void']]]],
'ParentStackTrace' : [ 0x48, ['array', 8, ['pointer', ['void']]]],
} ],
'_CONTEXT' : [ 0x2cc, {
'ContextFlags' : [ 0x0, ['unsigned long']],
'Dr0' : [ 0x4, ['unsigned long']],
'Dr1' : [ 0x8, ['unsigned long']],
'Dr2' : [ 0xc, ['unsigned long']],
'Dr3' : [ 0x10, ['unsigned long']],
'Dr6' : [ 0x14, ['unsigned long']],
'Dr7' : [ 0x18, ['unsigned long']],
'FloatSave' : [ 0x1c, ['_FLOATING_SAVE_AREA']],
'SegGs' : [ 0x8c, ['unsigned long']],
'SegFs' : [ 0x90, ['unsigned long']],
'SegEs' : [ 0x94, ['unsigned long']],
'SegDs' : [ 0x98, ['unsigned long']],
'Edi' : [ 0x9c, ['unsigned long']],
'Esi' : [ 0xa0, ['unsigned long']],
'Ebx' : [ 0xa4, ['unsigned long']],
'Edx' : [ 0xa8, ['unsigned long']],
'Ecx' : [ 0xac, ['unsigned long']],
'Eax' : [ 0xb0, ['unsigned long']],
'Ebp' : [ 0xb4, ['unsigned long']],
'Eip' : [ 0xb8, ['unsigned long']],
'SegCs' : [ 0xbc, ['unsigned long']],
'EFlags' : [ 0xc0, ['unsigned long']],
'Esp' : [ 0xc4, ['unsigned long']],
'SegSs' : [ 0xc8, ['unsigned long']],
'ExtendedRegisters' : [ 0xcc, ['array', 512, ['unsigned char']]],
} ],
'_IMAGE_OPTIONAL_HEADER' : [ 0xe0, {
'Magic' : [ 0x0, ['unsigned short']],
'MajorLinkerVersion' : [ 0x2, ['unsigned char']],
'MinorLinkerVersion' : [ 0x3, ['unsigned char']],
'SizeOfCode' : [ 0x4, ['unsigned long']],
'SizeOfInitializedData' : [ 0x8, ['unsigned long']],
'SizeOfUninitializedData' : [ 0xc, ['unsigned long']],
'AddressOfEntryPoint' : [ 0x10, ['unsigned long']],
'BaseOfCode' : [ 0x14, ['unsigned long']],
'BaseOfData' : [ 0x18, ['unsigned long']],
'ImageBase' : [ 0x1c, ['unsigned long']],
'SectionAlignment' : [ 0x20, ['unsigned long']],
'FileAlignment' : [ 0x24, ['unsigned long']],
'MajorOperatingSystemVersion' : [ 0x28, ['unsigned short']],
'MinorOperatingSystemVersion' : [ 0x2a, ['unsigned short']],
'MajorImageVersion' : [ 0x2c, ['unsigned short']],
'MinorImageVersion' : [ 0x2e, ['unsigned short']],
'MajorSubsystemVersion' : [ 0x30, ['unsigned short']],
'MinorSubsystemVersion' : [ 0x32, ['unsigned short']],
'Win32VersionValue' : [ 0x34, ['unsigned long']],
'SizeOfImage' : [ 0x38, ['unsigned long']],
'SizeOfHeaders' : [ 0x3c, ['unsigned long']],
'CheckSum' : [ 0x40, ['unsigned long']],
'Subsystem' : [ 0x44, ['unsigned short']],
'DllCharacteristics' : [ 0x46, ['unsigned short']],
'SizeOfStackReserve' : [ 0x48, ['unsigned long']],
'SizeOfStackCommit' : [ 0x4c, ['unsigned long']],
'SizeOfHeapReserve' : [ 0x50, ['unsigned long']],
'SizeOfHeapCommit' : [ 0x54, ['unsigned long']],
'LoaderFlags' : [ 0x58, ['unsigned long']],
'NumberOfRvaAndSizes' : [ 0x5c, ['unsigned long']],
'DataDirectory' : [ 0x60, ['array', 16, ['_IMAGE_DATA_DIRECTORY']]],
} ],
'_DBGKD_QUERY_SPECIAL_CALLS' : [ 0x4, {
'NumberOfSpecialCalls' : [ 0x0, ['unsigned long']],
} ],
'CMP_OFFSET_ARRAY' : [ 0xc, {
'FileOffset' : [ 0x0, ['unsigned long']],
'DataBuffer' : [ 0x4, ['pointer', ['void']]],
'DataLength' : [ 0x8, ['unsigned long']],
} ],
'_PCI_PDO_EXTENSION' : [ 0xc8, {
'Next' : [ 0x0, ['pointer', ['_PCI_PDO_EXTENSION']]],
'ExtensionType' : [ 0x4, ['Enumeration', dict(target = 'long', choices = {1768116272: 'PciPdoExtensionType', 1768116273: 'PciFdoExtensionType', 1768116274: 'PciArb_Io', 1768116275: 'PciArb_Memory', 1768116276: 'PciArb_Interrupt', 1768116277: 'PciArb_BusNumber', 1768116278: 'PciTrans_Interrupt', 1768116279: 'PciInterface_BusHandler', 1768116280: 'PciInterface_IntRouteHandler', 1768116281: 'PciInterface_PciCb', 1768116282: 'PciInterface_LegacyDeviceDetection', 1768116283: 'PciInterface_PmeHandler', 1768116284: 'PciInterface_DevicePresent', 1768116285: 'PciInterface_NativeIde', 1768116286: 'PciInterface_AgpTarget'})]],
'IrpDispatchTable' : [ 0x8, ['pointer', ['_PCI_MJ_DISPATCH_TABLE']]],
'DeviceState' : [ 0xc, ['unsigned char']],
'TentativeNextState' : [ 0xd, ['unsigned char']],
'SecondaryExtLock' : [ 0x10, ['_KEVENT']],
'Slot' : [ 0x20, ['_PCI_SLOT_NUMBER']],
'PhysicalDeviceObject' : [ 0x24, ['pointer', ['_DEVICE_OBJECT']]],
'ParentFdoExtension' : [ 0x28, ['pointer', ['_PCI_FDO_EXTENSION']]],
'SecondaryExtension' : [ 0x2c, ['_SINGLE_LIST_ENTRY']],
'BusInterfaceReferenceCount' : [ 0x30, ['unsigned long']],
'AgpInterfaceReferenceCount' : [ 0x34, ['unsigned long']],
'VendorId' : [ 0x38, ['unsigned short']],
'DeviceId' : [ 0x3a, ['unsigned short']],
'SubsystemVendorId' : [ 0x3c, ['unsigned short']],
'SubsystemId' : [ 0x3e, ['unsigned short']],
'RevisionId' : [ 0x40, ['unsigned char']],
'ProgIf' : [ 0x41, ['unsigned char']],
'SubClass' : [ 0x42, ['unsigned char']],
'BaseClass' : [ 0x43, ['unsigned char']],
'AdditionalResourceCount' : [ 0x44, ['unsigned char']],
'AdjustedInterruptLine' : [ 0x45, ['unsigned char']],
'InterruptPin' : [ 0x46, ['unsigned char']],
'RawInterruptLine' : [ 0x47, ['unsigned char']],
'CapabilitiesPtr' : [ 0x48, ['unsigned char']],
'SavedLatencyTimer' : [ 0x49, ['unsigned char']],
'SavedCacheLineSize' : [ 0x4a, ['unsigned char']],
'HeaderType' : [ 0x4b, ['unsigned char']],
'NotPresent' : [ 0x4c, ['unsigned char']],
'ReportedMissing' : [ 0x4d, ['unsigned char']],
'ExpectedWritebackFailure' : [ 0x4e, ['unsigned char']],
'NoTouchPmeEnable' : [ 0x4f, ['unsigned char']],
'LegacyDriver' : [ 0x50, ['unsigned char']],
'UpdateHardware' : [ 0x51, ['unsigned char']],
'MovedDevice' : [ 0x52, ['unsigned char']],
'DisablePowerDown' : [ 0x53, ['unsigned char']],
'NeedsHotPlugConfiguration' : [ 0x54, ['unsigned char']],
'SwitchedIDEToNativeMode' : [ 0x55, ['unsigned char']],
'BIOSAllowsIDESwitchToNativeMode' : [ 0x56, ['unsigned char']],
'IoSpaceUnderNativeIdeControl' : [ 0x57, ['unsigned char']],
'OnDebugPath' : [ 0x58, ['unsigned char']],
'PowerState' : [ 0x5c, ['PCI_POWER_STATE']],
'Dependent' : [ 0x9c, ['PCI_HEADER_TYPE_DEPENDENT']],
'HackFlags' : [ 0xa0, ['unsigned long long']],
'Resources' : [ 0xa8, ['pointer', ['PCI_FUNCTION_RESOURCES']]],
'BridgeFdoExtension' : [ 0xac, ['pointer', ['_PCI_FDO_EXTENSION']]],
'NextBridge' : [ 0xb0, ['pointer', ['_PCI_PDO_EXTENSION']]],
'NextHashEntry' : [ 0xb4, ['pointer', ['_PCI_PDO_EXTENSION']]],
'Lock' : [ 0xb8, ['_PCI_LOCK']],
'PowerCapabilities' : [ 0xc0, ['_PCI_PMC']],
'TargetAgpCapabilityId' : [ 0xc2, ['unsigned char']],
'CommandEnables' : [ 0xc4, ['unsigned short']],
'InitialCommand' : [ 0xc6, ['unsigned short']],
} ],
'_HMAP_DIRECTORY' : [ 0x1000, {
'Directory' : [ 0x0, ['array', 1024, ['pointer', ['_HMAP_TABLE']]]],
} ],
'_OBJECT_HEADER' : [ 0x20, {
'PointerCount' : [ 0x0, ['long']],
'HandleCount' : [ 0x4, ['long']],
'NextToFree' : [ 0x4, ['pointer', ['void']]],
'Type' : [ 0x8, ['pointer', ['_OBJECT_TYPE']]],
'NameInfoOffset' : [ 0xc, ['unsigned char']],
'HandleInfoOffset' : [ 0xd, ['unsigned char']],
'QuotaInfoOffset' : [ 0xe, ['unsigned char']],
'Flags' : [ 0xf, ['unsigned char']],
'ObjectCreateInfo' : [ 0x10, ['pointer', ['_OBJECT_CREATE_INFORMATION']]],
'QuotaBlockCharged' : [ 0x10, ['pointer', ['void']]],
'SecurityDescriptor' : [ 0x14, ['pointer', ['void']]],
'Body' : [ 0x18, ['_QUAD']],
} ],
'_QUAD' : [ 0x8, {
'DoNotUseThisField' : [ 0x0, ['double']],
} ],
'_SECURITY_DESCRIPTOR' : [ 0x14, {
'Revision' : [ 0x0, ['unsigned char']],
'Sbz1' : [ 0x1, ['unsigned char']],
'Control' : [ 0x2, ['unsigned short']],
'Owner' : [ 0x4, ['pointer', ['void']]],
'Group' : [ 0x8, ['pointer', ['void']]],
'Sacl' : [ 0xc, ['pointer', ['_ACL']]],
'Dacl' : [ 0x10, ['pointer', ['_ACL']]],
} ],
'__unnamed_150f' : [ 0x8, {
'UserData' : [ 0x0, ['pointer', ['void']]],
'Owner' : [ 0x4, ['pointer', ['void']]],
} ],
'__unnamed_1511' : [ 0x8, {
'ListHead' : [ 0x0, ['_LIST_ENTRY']],
} ],
'_RTLP_RANGE_LIST_ENTRY' : [ 0x28, {
'Start' : [ 0x0, ['unsigned long long']],
'End' : [ 0x8, ['unsigned long long']],
'Allocated' : [ 0x10, ['__unnamed_150f']],
'Merged' : [ 0x10, ['__unnamed_1511']],
'Attributes' : [ 0x18, ['unsigned char']],
'PublicFlags' : [ 0x19, ['unsigned char']],
'PrivateFlags' : [ 0x1a, ['unsigned short']],
'ListEntry' : [ 0x1c, ['_LIST_ENTRY']],
} ],
'_KAPC_STATE' : [ 0x18, {
'ApcListHead' : [ 0x0, ['array', 2, ['_LIST_ENTRY']]],
'Process' : [ 0x10, ['pointer', ['_KPROCESS']]],
'KernelApcInProgress' : [ 0x14, ['unsigned char']],
'KernelApcPending' : [ 0x15, ['unsigned char']],
'UserApcPending' : [ 0x16, ['unsigned char']],
} ],
'_OBJECT_HEADER_CREATOR_INFO' : [ 0x10, {
'TypeList' : [ 0x0, ['_LIST_ENTRY']],
'CreatorUniqueProcess' : [ 0x8, ['pointer', ['void']]],
'CreatorBackTraceIndex' : [ 0xc, ['unsigned short']],
'Reserved' : [ 0xe, ['unsigned short']],
} ],
'_HEAP_STOP_ON_VALUES' : [ 0x18, {
'AllocAddress' : [ 0x0, ['unsigned long']],
'AllocTag' : [ 0x4, ['_HEAP_STOP_ON_TAG']],
'ReAllocAddress' : [ 0x8, ['unsigned long']],
'ReAllocTag' : [ 0xc, ['_HEAP_STOP_ON_TAG']],
'FreeAddress' : [ 0x10, ['unsigned long']],
'FreeTag' : [ 0x14, ['_HEAP_STOP_ON_TAG']],
} ],
'_DEVICE_RELATIONS' : [ 0x8, {
'Count' : [ 0x0, ['unsigned long']],
'Objects' : [ 0x4, ['array', 1, ['pointer', ['_DEVICE_OBJECT']]]],
} ],
'_KPROCESS' : [ 0x6c, {
'Header' : [ 0x0, ['_DISPATCHER_HEADER']],
'ProfileListHead' : [ 0x10, ['_LIST_ENTRY']],
'DirectoryTableBase' : [ 0x18, ['array', 2, ['unsigned long']]],
'LdtDescriptor' : [ 0x20, ['_KGDTENTRY']],
'Int21Descriptor' : [ 0x28, ['_KIDTENTRY']],
'IopmOffset' : [ 0x30, ['unsigned short']],
'Iopl' : [ 0x32, ['unsigned char']],
'Unused' : [ 0x33, ['unsigned char']],
'ActiveProcessors' : [ 0x34, ['unsigned long']],
'KernelTime' : [ 0x38, ['unsigned long']],
'UserTime' : [ 0x3c, ['unsigned long']],
'ReadyListHead' : [ 0x40, ['_LIST_ENTRY']],
'SwapListEntry' : [ 0x48, ['_SINGLE_LIST_ENTRY']],
'VdmTrapcHandler' : [ 0x4c, ['pointer', ['void']]],
'ThreadListHead' : [ 0x50, ['_LIST_ENTRY']],
'ProcessLock' : [ 0x58, ['unsigned long']],
'Affinity' : [ 0x5c, ['unsigned long']],
'StackCount' : [ 0x60, ['unsigned short']],
'BasePriority' : [ 0x62, ['unsigned char']],
'ThreadQuantum' : [ 0x63, ['unsigned char']],
'AutoAlignment' : [ 0x64, ['unsigned char']],
'State' : [ 0x65, ['unsigned char']],
'ThreadSeed' : [ 0x66, ['unsigned char']],
'DisableBoost' : [ 0x67, ['unsigned char']],
'PowerState' : [ 0x68, ['unsigned char']],
'DisableQuantum' : [ 0x69, ['unsigned char']],
'IdealNode' : [ 0x6a, ['unsigned char']],
'Flags' : [ 0x6b, ['_KEXECUTE_OPTIONS']],
'ExecuteOptions' : [ 0x6b, ['unsigned char']],
} ],
'_HEAP_PSEUDO_TAG_ENTRY' : [ 0xc, {
'Allocs' : [ 0x0, ['unsigned long']],
'Frees' : [ 0x4, ['unsigned long']],
'Size' : [ 0x8, ['unsigned long']],
} ],
'_IO_RESOURCE_LIST' : [ 0x28, {
'Version' : [ 0x0, ['unsigned short']],
'Revision' : [ 0x2, ['unsigned short']],
'Count' : [ 0x4, ['unsigned long']],
'Descriptors' : [ 0x8, ['array', 1, ['_IO_RESOURCE_DESCRIPTOR']]],
} ],
'_MMBANKED_SECTION' : [ 0x20, {
'BasePhysicalPage' : [ 0x0, ['unsigned long']],
'BasedPte' : [ 0x4, ['pointer', ['_MMPTE']]],
'BankSize' : [ 0x8, ['unsigned long']],
'BankShift' : [ 0xc, ['unsigned long']],
'BankedRoutine' : [ 0x10, ['pointer', ['void']]],
'Context' : [ 0x14, ['pointer', ['void']]],
'CurrentMappedPte' : [ 0x18, ['pointer', ['_MMPTE']]],
'BankTemplate' : [ 0x1c, ['array', 1, ['_MMPTE']]],
} ],
'_RTL_CRITICAL_SECTION' : [ 0x18, {
'DebugInfo' : [ 0x0, ['pointer', ['_RTL_CRITICAL_SECTION_DEBUG']]],
'LockCount' : [ 0x4, ['long']],
'RecursionCount' : [ 0x8, ['long']],
'OwningThread' : [ 0xc, ['pointer', ['void']]],
'LockSemaphore' : [ 0x10, ['pointer', ['void']]],
'SpinCount' : [ 0x14, ['unsigned long']],
} ],
'_KTRAP_FRAME' : [ 0x8c, {
'DbgEbp' : [ 0x0, ['unsigned long']],
'DbgEip' : [ 0x4, ['unsigned long']],
'DbgArgMark' : [ 0x8, ['unsigned long']],
'DbgArgPointer' : [ 0xc, ['unsigned long']],
'TempSegCs' : [ 0x10, ['unsigned long']],
'TempEsp' : [ 0x14, ['unsigned long']],
'Dr0' : [ 0x18, ['unsigned long']],
'Dr1' : [ 0x1c, ['unsigned long']],
'Dr2' : [ 0x20, ['unsigned long']],
'Dr3' : [ 0x24, ['unsigned long']],
'Dr6' : [ 0x28, ['unsigned long']],
'Dr7' : [ 0x2c, ['unsigned long']],
'SegGs' : [ 0x30, ['unsigned long']],
'SegEs' : [ 0x34, ['unsigned long']],
'SegDs' : [ 0x38, ['unsigned long']],
'Edx' : [ 0x3c, ['unsigned long']],
'Ecx' : [ 0x40, ['unsigned long']],
'Eax' : [ 0x44, ['unsigned long']],
'PreviousPreviousMode' : [ 0x48, ['unsigned long']],
'ExceptionList' : [ 0x4c, ['pointer', ['_EXCEPTION_REGISTRATION_RECORD']]],
'SegFs' : [ 0x50, ['unsigned long']],
'Edi' : [ 0x54, ['unsigned long']],
'Esi' : [ 0x58, ['unsigned long']],
'Ebx' : [ 0x5c, ['unsigned long']],
'Ebp' : [ 0x60, ['unsigned long']],
'ErrCode' : [ 0x64, ['unsigned long']],
'Eip' : [ 0x68, ['unsigned long']],
'SegCs' : [ 0x6c, ['unsigned long']],
'EFlags' : [ 0x70, ['unsigned long']],
'HardwareEsp' : [ 0x74, ['unsigned long']],
'HardwareSegSs' : [ 0x78, ['unsigned long']],
'V86Es' : [ 0x7c, ['unsigned long']],
'V86Ds' : [ 0x80, ['unsigned long']],
'V86Fs' : [ 0x84, ['unsigned long']],
'V86Gs' : [ 0x88, ['unsigned long']],
} ],
'__unnamed_153a' : [ 0x4, {
'BaseMid' : [ 0x0, ['unsigned char']],
'Flags1' : [ 0x1, ['unsigned char']],
'Flags2' : [ 0x2, ['unsigned char']],
'BaseHi' : [ 0x3, ['unsigned char']],
} ],
'__unnamed_1541' : [ 0x4, {
'BaseMid' : [ 0x0, ['BitField', dict(start_bit = 0, end_bit = 8, native_type='unsigned long')]],
'Type' : [ 0x0, ['BitField', dict(start_bit = 8, end_bit = 13, native_type='unsigned long')]],
'Dpl' : [ 0x0, ['BitField', dict(start_bit = 13, end_bit = 15, native_type='unsigned long')]],
'Pres' : [ 0x0, ['BitField', dict(start_bit = 15, end_bit = 16, native_type='unsigned long')]],
'LimitHi' : [ 0x0, ['BitField', dict(start_bit = 16, end_bit = 20, native_type='unsigned long')]],
'Sys' : [ 0x0, ['BitField', dict(start_bit = 20, end_bit = 21, native_type='unsigned long')]],
'Reserved_0' : [ 0x0, ['BitField', dict(start_bit = 21, end_bit = 22, native_type='unsigned long')]],
'Default_Big' : [ 0x0, ['BitField', dict(start_bit = 22, end_bit = 23, native_type='unsigned long')]],
'Granularity' : [ 0x0, ['BitField', dict(start_bit = 23, end_bit = 24, native_type='unsigned long')]],
'BaseHi' : [ 0x0, ['BitField', dict(start_bit = 24, end_bit = 32, native_type='unsigned long')]],
} ],
'__unnamed_1543' : [ 0x4, {
'Bytes' : [ 0x0, ['__unnamed_153a']],
'Bits' : [ 0x0, ['__unnamed_1541']],
} ],
'_KGDTENTRY' : [ 0x8, {
'LimitLow' : [ 0x0, ['unsigned short']],
'BaseLow' : [ 0x2, ['unsigned short']],
'HighWord' : [ 0x4, ['__unnamed_1543']],
} ],
'__unnamed_154d' : [ 0x5, {
'Acquired' : [ 0x0, ['unsigned char']],
'CacheLineSize' : [ 0x1, ['unsigned char']],
'LatencyTimer' : [ 0x2, ['unsigned char']],
'EnablePERR' : [ 0x3, ['unsigned char']],
'EnableSERR' : [ 0x4, ['unsigned char']],
} ],
'_PCI_FDO_EXTENSION' : [ 0xc0, {
'List' : [ 0x0, ['_SINGLE_LIST_ENTRY']],
'ExtensionType' : [ 0x4, ['Enumeration', dict(target = 'long', choices = {1768116272: 'PciPdoExtensionType', 1768116273: 'PciFdoExtensionType', 1768116274: 'PciArb_Io', 1768116275: 'PciArb_Memory', 1768116276: 'PciArb_Interrupt', 1768116277: 'PciArb_BusNumber', 1768116278: 'PciTrans_Interrupt', 1768116279: 'PciInterface_BusHandler', 1768116280: 'PciInterface_IntRouteHandler', 1768116281: 'PciInterface_PciCb', 1768116282: 'PciInterface_LegacyDeviceDetection', 1768116283: 'PciInterface_PmeHandler', 1768116284: 'PciInterface_DevicePresent', 1768116285: 'PciInterface_NativeIde', 1768116286: 'PciInterface_AgpTarget'})]],
'IrpDispatchTable' : [ 0x8, ['pointer', ['_PCI_MJ_DISPATCH_TABLE']]],
'DeviceState' : [ 0xc, ['unsigned char']],
'TentativeNextState' : [ 0xd, ['unsigned char']],
'SecondaryExtLock' : [ 0x10, ['_KEVENT']],
'PhysicalDeviceObject' : [ 0x20, ['pointer', ['_DEVICE_OBJECT']]],
'FunctionalDeviceObject' : [ 0x24, ['pointer', ['_DEVICE_OBJECT']]],
'AttachedDeviceObject' : [ 0x28, ['pointer', ['_DEVICE_OBJECT']]],
'ChildListLock' : [ 0x2c, ['_KEVENT']],
'ChildPdoList' : [ 0x3c, ['pointer', ['_PCI_PDO_EXTENSION']]],
'BusRootFdoExtension' : [ 0x40, ['pointer', ['_PCI_FDO_EXTENSION']]],
'ParentFdoExtension' : [ 0x44, ['pointer', ['_PCI_FDO_EXTENSION']]],
'ChildBridgePdoList' : [ 0x48, ['pointer', ['_PCI_PDO_EXTENSION']]],
'PciBusInterface' : [ 0x4c, ['pointer', ['_PCI_BUS_INTERFACE_STANDARD']]],
'MaxSubordinateBus' : [ 0x50, ['unsigned char']],
'BusHandler' : [ 0x54, ['pointer', ['_BUS_HANDLER']]],
'BaseBus' : [ 0x58, ['unsigned char']],
'Fake' : [ 0x59, ['unsigned char']],
'ChildDelete' : [ 0x5a, ['unsigned char']],
'Scanned' : [ 0x5b, ['unsigned char']],
'ArbitersInitialized' : [ 0x5c, ['unsigned char']],
'BrokenVideoHackApplied' : [ 0x5d, ['unsigned char']],
'Hibernated' : [ 0x5e, ['unsigned char']],
'PowerState' : [ 0x60, ['PCI_POWER_STATE']],
'SecondaryExtension' : [ 0xa0, ['_SINGLE_LIST_ENTRY']],
'ChildWaitWakeCount' : [ 0xa4, ['unsigned long']],
'PreservedConfig' : [ 0xa8, ['pointer', ['_PCI_COMMON_CONFIG']]],
'Lock' : [ 0xac, ['_PCI_LOCK']],
'HotPlugParameters' : [ 0xb4, ['__unnamed_154d']],
'BusHackFlags' : [ 0xbc, ['unsigned long']],
} ],
'__unnamed_1551' : [ 0xc, {
'Start' : [ 0x0, ['_LARGE_INTEGER']],
'Length' : [ 0x8, ['unsigned long']],
} ],
'__unnamed_1553' : [ 0xc, {
'Level' : [ 0x0, ['unsigned long']],
'Vector' : [ 0x4, ['unsigned long']],
'Affinity' : [ 0x8, ['unsigned long']],
} ],
'__unnamed_1555' : [ 0xc, {
'Channel' : [ 0x0, ['unsigned long']],
'Port' : [ 0x4, ['unsigned long']],
'Reserved1' : [ 0x8, ['unsigned long']],
} ],
'__unnamed_1557' : [ 0xc, {
'Data' : [ 0x0, ['array', 3, ['unsigned long']]],
} ],
'__unnamed_1559' : [ 0xc, {
'Start' : [ 0x0, ['unsigned long']],
'Length' : [ 0x4, ['unsigned long']],
'Reserved' : [ 0x8, ['unsigned long']],
} ],
'__unnamed_155b' : [ 0xc, {
'DataSize' : [ 0x0, ['unsigned long']],
'Reserved1' : [ 0x4, ['unsigned long']],
'Reserved2' : [ 0x8, ['unsigned long']],
} ],
'__unnamed_155d' : [ 0xc, {
'Generic' : [ 0x0, ['__unnamed_1551']],
'Port' : [ 0x0, ['__unnamed_1551']],
'Interrupt' : [ 0x0, ['__unnamed_1553']],
'Memory' : [ 0x0, ['__unnamed_1551']],
'Dma' : [ 0x0, ['__unnamed_1555']],
'DevicePrivate' : [ 0x0, ['__unnamed_1557']],
'BusNumber' : [ 0x0, ['__unnamed_1559']],
'DeviceSpecificData' : [ 0x0, ['__unnamed_155b']],
} ],
'_CM_PARTIAL_RESOURCE_DESCRIPTOR' : [ 0x10, {
'Type' : [ 0x0, ['unsigned char']],
'ShareDisposition' : [ 0x1, ['unsigned char']],
'Flags' : [ 0x2, ['unsigned short']],
'u' : [ 0x4, ['__unnamed_155d']],
} ],
'_SYSPTES_HEADER' : [ 0xc, {
'ListHead' : [ 0x0, ['_LIST_ENTRY']],
'Count' : [ 0x8, ['unsigned long']],
} ],
'_WAIT_CONTEXT_BLOCK' : [ 0x28, {
'WaitQueueEntry' : [ 0x0, ['_KDEVICE_QUEUE_ENTRY']],
'DeviceRoutine' : [ 0x10, ['pointer', ['void']]],
'DeviceContext' : [ 0x14, ['pointer', ['void']]],
'NumberOfMapRegisters' : [ 0x18, ['unsigned long']],
'DeviceObject' : [ 0x1c, ['pointer', ['void']]],
'CurrentIrp' : [ 0x20, ['pointer', ['void']]],
'BufferChainingDpc' : [ 0x24, ['pointer', ['_KDPC']]],
} ],
'_CM_KEY_CONTROL_BLOCK' : [ 0x50, {
'RefCount' : [ 0x0, ['unsigned long']],
'ExtFlags' : [ 0x4, ['BitField', dict(start_bit = 0, end_bit = 8, native_type='unsigned long')]],
'PrivateAlloc' : [ 0x4, ['BitField', dict(start_bit = 8, end_bit = 9, native_type='unsigned long')]],
'Delete' : [ 0x4, ['BitField', dict(start_bit = 9, end_bit = 10, native_type='unsigned long')]],
'DelayedCloseIndex' : [ 0x4, ['BitField', dict(start_bit = 10, end_bit = 22, native_type='unsigned long')]],
'TotalLevels' : [ 0x4, ['BitField', dict(start_bit = 22, end_bit = 32, native_type='unsigned long')]],
'KeyHash' : [ 0x8, ['_CM_KEY_HASH']],
'ConvKey' : [ 0x8, ['unsigned long']],
'NextHash' : [ 0xc, ['pointer', ['_CM_KEY_HASH']]],
'KeyHive' : [ 0x10, ['pointer', ['_HHIVE']]],
'KeyCell' : [ 0x14, ['unsigned long']],
'ParentKcb' : [ 0x18, ['pointer', ['_CM_KEY_CONTROL_BLOCK']]],
'NameBlock' : [ 0x1c, ['pointer', ['_CM_NAME_CONTROL_BLOCK']]],
'CachedSecurity' : [ 0x20, ['pointer', ['_CM_KEY_SECURITY_CACHE']]],
'ValueCache' : [ 0x24, ['_CACHED_CHILD_LIST']],
'IndexHint' : [ 0x2c, ['pointer', ['_CM_INDEX_HINT_BLOCK']]],
'HashKey' : [ 0x2c, ['unsigned long']],
'SubKeyCount' : [ 0x2c, ['unsigned long']],
'KeyBodyListHead' : [ 0x30, ['_LIST_ENTRY']],
'FreeListEntry' : [ 0x30, ['_LIST_ENTRY']],
'KcbLastWriteTime' : [ 0x38, ['_LARGE_INTEGER']],
'KcbMaxNameLen' : [ 0x40, ['unsigned short']],
'KcbMaxValueNameLen' : [ 0x42, ['unsigned short']],
'KcbMaxValueDataLen' : [ 0x44, ['unsigned long']],
'KcbUserFlags' : [ 0x48, ['BitField', dict(start_bit = 0, end_bit = 4, native_type='unsigned long')]],
'KcbVirtControlFlags' : [ 0x48, ['BitField', dict(start_bit = 4, end_bit = 8, native_type='unsigned long')]],
'KcbDebug' : [ 0x48, ['BitField', dict(start_bit = 8, end_bit = 16, native_type='unsigned long')]],
'Flags' : [ 0x48, ['BitField', dict(start_bit = 16, end_bit = 32, native_type='unsigned long')]],
} ],
'_KDPC' : [ 0x20, {
'Type' : [ 0x0, ['short']],
'Number' : [ 0x2, ['unsigned char']],
'Importance' : [ 0x3, ['unsigned char']],
'DpcListEntry' : [ 0x4, ['_LIST_ENTRY']],
'DeferredRoutine' : [ 0xc, ['pointer', ['void']]],
'DeferredContext' : [ 0x10, ['pointer', ['void']]],
'SystemArgument1' : [ 0x14, ['pointer', ['void']]],
'SystemArgument2' : [ 0x18, ['pointer', ['void']]],
'Lock' : [ 0x1c, ['pointer', ['unsigned long']]],
} ],
'_PCI_BUS_INTERFACE_STANDARD' : [ 0x20, {
'Size' : [ 0x0, ['unsigned short']],
'Version' : [ 0x2, ['unsigned short']],
'Context' : [ 0x4, ['pointer', ['void']]],
'InterfaceReference' : [ 0x8, ['pointer', ['void']]],
'InterfaceDereference' : [ 0xc, ['pointer', ['void']]],
'ReadConfig' : [ 0x10, ['pointer', ['void']]],
'WriteConfig' : [ 0x14, ['pointer', ['void']]],
'PinToLine' : [ 0x18, ['pointer', ['void']]],
'LineToPin' : [ 0x1c, ['pointer', ['void']]],
} ],
'_WORK_QUEUE_ITEM' : [ 0x10, {
'List' : [ 0x0, ['_LIST_ENTRY']],
'WorkerRoutine' : [ 0x8, ['pointer', ['void']]],
'Parameter' : [ 0xc, ['pointer', ['void']]],
} ],
'_PI_RESOURCE_ARBITER_ENTRY' : [ 0x38, {
'DeviceArbiterList' : [ 0x0, ['_LIST_ENTRY']],
'ResourceType' : [ 0x8, ['unsigned char']],
'ArbiterInterface' : [ 0xc, ['pointer', ['_ARBITER_INTERFACE']]],
'Level' : [ 0x10, ['unsigned long']],
'ResourceList' : [ 0x14, ['_LIST_ENTRY']],
'BestResourceList' : [ 0x1c, ['_LIST_ENTRY']],
'BestConfig' : [ 0x24, ['_LIST_ENTRY']],
'ActiveArbiterList' : [ 0x2c, ['_LIST_ENTRY']],
'State' : [ 0x34, ['unsigned char']],
'ResourcesChanged' : [ 0x35, ['unsigned char']],
} ],
'_KTIMER' : [ 0x28, {
'Header' : [ 0x0, ['_DISPATCHER_HEADER']],
'DueTime' : [ 0x10, ['_ULARGE_INTEGER']],
'TimerListEntry' : [ 0x18, ['_LIST_ENTRY']],
'Dpc' : [ 0x20, ['pointer', ['_KDPC']]],
'Period' : [ 0x24, ['long']],
} ],
'_CM_KEY_HASH' : [ 0x10, {
'ConvKey' : [ 0x0, ['unsigned long']],
'NextHash' : [ 0x4, ['pointer', ['_CM_KEY_HASH']]],
'KeyHive' : [ 0x8, ['pointer', ['_HHIVE']]],
'KeyCell' : [ 0xc, ['unsigned long']],
} ],
'__unnamed_159b' : [ 0x4, {
'MasterIrp' : [ 0x0, ['pointer', ['_IRP']]],
'IrpCount' : [ 0x0, ['long']],
'SystemBuffer' : [ 0x0, ['pointer', ['void']]],
} ],
'__unnamed_15a2' : [ 0x8, {
'UserApcRoutine' : [ 0x0, ['pointer', ['void']]],
'UserApcContext' : [ 0x4, ['pointer', ['void']]],
} ],
'__unnamed_15a4' : [ 0x8, {
'AsynchronousParameters' : [ 0x0, ['__unnamed_15a2']],
'AllocationSize' : [ 0x0, ['_LARGE_INTEGER']],
} ],
'__unnamed_15a9' : [ 0x28, {
'DeviceQueueEntry' : [ 0x0, ['_KDEVICE_QUEUE_ENTRY']],
'DriverContext' : [ 0x0, ['array', 4, ['pointer', ['void']]]],
'Thread' : [ 0x10, ['pointer', ['_ETHREAD']]],
'AuxiliaryBuffer' : [ 0x14, ['pointer', ['unsigned char']]],
'ListEntry' : [ 0x18, ['_LIST_ENTRY']],
'CurrentStackLocation' : [ 0x20, ['pointer', ['_IO_STACK_LOCATION']]],
'PacketType' : [ 0x20, ['unsigned long']],
'OriginalFileObject' : [ 0x24, ['pointer', ['_FILE_OBJECT']]],
} ],
'__unnamed_15ab' : [ 0x30, {
'Overlay' : [ 0x0, ['__unnamed_15a9']],
'Apc' : [ 0x0, ['_KAPC']],
'CompletionKey' : [ 0x0, ['pointer', ['void']]],
} ],
'_IRP' : [ 0x70, {
'Type' : [ 0x0, ['short']],
'Size' : [ 0x2, ['unsigned short']],
'MdlAddress' : [ 0x4, ['pointer', ['_MDL']]],
'Flags' : [ 0x8, ['unsigned long']],
'AssociatedIrp' : [ 0xc, ['__unnamed_159b']],
'ThreadListEntry' : [ 0x10, ['_LIST_ENTRY']],
'IoStatus' : [ 0x18, ['_IO_STATUS_BLOCK']],
'RequestorMode' : [ 0x20, ['unsigned char']],
'PendingReturned' : [ 0x21, ['unsigned char']],
'StackCount' : [ 0x22, ['unsigned char']],
'CurrentLocation' : [ 0x23, ['unsigned char']],
'Cancel' : [ 0x24, ['unsigned char']],
'CancelIrql' : [ 0x25, ['unsigned char']],
'ApcEnvironment' : [ 0x26, ['unsigned char']],
'AllocationFlags' : [ 0x27, ['unsigned char']],
'UserIosb' : [ 0x28, ['pointer', ['_IO_STATUS_BLOCK']]],
'UserEvent' : [ 0x2c, ['pointer', ['_KEVENT']]],
'Overlay' : [ 0x30, ['__unnamed_15a4']],
'CancelRoutine' : [ 0x38, ['pointer', ['void']]],
'UserBuffer' : [ 0x3c, ['pointer', ['void']]],
'Tail' : [ 0x40, ['__unnamed_15ab']],
} ],
'_PCI_LOCK' : [ 0x8, {
'Atom' : [ 0x0, ['unsigned long']],
'OldIrql' : [ 0x4, ['unsigned char']],
} ],
'_CM_KEY_SECURITY_CACHE_ENTRY' : [ 0x8, {
'Cell' : [ 0x0, ['unsigned long']],
'CachedSecurity' : [ 0x4, ['pointer', ['_CM_KEY_SECURITY_CACHE']]],
} ],
'__unnamed_15b4' : [ 0x4, {
'PhysicalAddress' : [ 0x0, ['unsigned long']],
'VirtualSize' : [ 0x0, ['unsigned long']],
} ],
'_IMAGE_SECTION_HEADER' : [ 0x28, {
'Name' : [ 0x0, ['array', 8, ['unsigned char']]],
'Misc' : [ 0x8, ['__unnamed_15b4']],
'VirtualAddress' : [ 0xc, ['unsigned long']],
'SizeOfRawData' : [ 0x10, ['unsigned long']],
'PointerToRawData' : [ 0x14, ['unsigned long']],
'PointerToRelocations' : [ 0x18, ['unsigned long']],
'PointerToLinenumbers' : [ 0x1c, ['unsigned long']],
'NumberOfRelocations' : [ 0x20, ['unsigned short']],
'NumberOfLinenumbers' : [ 0x22, ['unsigned short']],
'Characteristics' : [ 0x24, ['unsigned long']],
} ],
'__unnamed_15ba' : [ 0x4, {
'Level' : [ 0x0, ['unsigned long']],
} ],
'_POP_ACTION_TRIGGER' : [ 0xc, {
'Type' : [ 0x0, ['Enumeration', dict(target = 'long', choices = {0: 'PolicyDeviceSystemButton', 1: 'PolicyDeviceThermalZone', 2: 'PolicyDeviceBattery', 3: 'PolicyInitiatePowerActionAPI', 4: 'PolicySetPowerStateAPI', 5: 'PolicyImmediateDozeS4', 6: 'PolicySystemIdle'})]],
'Flags' : [ 0x4, ['unsigned char']],
'Spare' : [ 0x5, ['array', 3, ['unsigned char']]],
'Battery' : [ 0x8, ['__unnamed_15ba']],
'Wait' : [ 0x8, ['pointer', ['_POP_TRIGGER_WAIT']]],
} ],
'_FAST_IO_DISPATCH' : [ 0x70, {
'SizeOfFastIoDispatch' : [ 0x0, ['unsigned long']],
'FastIoCheckIfPossible' : [ 0x4, ['pointer', ['void']]],
'FastIoRead' : [ 0x8, ['pointer', ['void']]],
'FastIoWrite' : [ 0xc, ['pointer', ['void']]],
'FastIoQueryBasicInfo' : [ 0x10, ['pointer', ['void']]],
'FastIoQueryStandardInfo' : [ 0x14, ['pointer', ['void']]],
'FastIoLock' : [ 0x18, ['pointer', ['void']]],
'FastIoUnlockSingle' : [ 0x1c, ['pointer', ['void']]],
'FastIoUnlockAll' : [ 0x20, ['pointer', ['void']]],
'FastIoUnlockAllByKey' : [ 0x24, ['pointer', ['void']]],
'FastIoDeviceControl' : [ 0x28, ['pointer', ['void']]],
'AcquireFileForNtCreateSection' : [ 0x2c, ['pointer', ['void']]],
'ReleaseFileForNtCreateSection' : [ 0x30, ['pointer', ['void']]],
'FastIoDetachDevice' : [ 0x34, ['pointer', ['void']]],
'FastIoQueryNetworkOpenInfo' : [ 0x38, ['pointer', ['void']]],
'AcquireForModWrite' : [ 0x3c, ['pointer', ['void']]],
'MdlRead' : [ 0x40, ['pointer', ['void']]],
'MdlReadComplete' : [ 0x44, ['pointer', ['void']]],
'PrepareMdlWrite' : [ 0x48, ['pointer', ['void']]],
'MdlWriteComplete' : [ 0x4c, ['pointer', ['void']]],
'FastIoReadCompressed' : [ 0x50, ['pointer', ['void']]],
'FastIoWriteCompressed' : [ 0x54, ['pointer', ['void']]],
'MdlReadCompleteCompressed' : [ 0x58, ['pointer', ['void']]],
'MdlWriteCompleteCompressed' : [ 0x5c, ['pointer', ['void']]],
'FastIoQueryOpen' : [ 0x60, ['pointer', ['void']]],
'ReleaseForModWrite' : [ 0x64, ['pointer', ['void']]],
'AcquireForCcFlush' : [ 0x68, ['pointer', ['void']]],
'ReleaseForCcFlush' : [ 0x6c, ['pointer', ['void']]],
} ],
'_ETIMER' : [ 0x98, {
'KeTimer' : [ 0x0, ['_KTIMER']],
'TimerApc' : [ 0x28, ['_KAPC']],
'TimerDpc' : [ 0x58, ['_KDPC']],
'ActiveTimerListEntry' : [ 0x78, ['_LIST_ENTRY']],
'Lock' : [ 0x80, ['unsigned long']],
'Period' : [ 0x84, ['long']],
'ApcAssociated' : [ 0x88, ['unsigned char']],
'WakeTimer' : [ 0x89, ['unsigned char']],
'WakeTimerListEntry' : [ 0x8c, ['_LIST_ENTRY']],
} ],
'_DBGKD_BREAKPOINTEX' : [ 0x8, {
'BreakPointCount' : [ 0x0, ['unsigned long']],
'ContinueStatus' : [ 0x4, ['long']],
} ],
'_CM_CELL_REMAP_BLOCK' : [ 0x8, {
'OldCell' : [ 0x0, ['unsigned long']],
'NewCell' : [ 0x4, ['unsigned long']],
} ],
'_PCI_PMC' : [ 0x2, {
'Version' : [ 0x0, ['BitField', dict(start_bit = 0, end_bit = 3, native_type='unsigned char')]],
'PMEClock' : [ 0x0, ['BitField', dict(start_bit = 3, end_bit = 4, native_type='unsigned char')]],
'Rsvd1' : [ 0x0, ['BitField', dict(start_bit = 4, end_bit = 5, native_type='unsigned char')]],
'DeviceSpecificInitialization' : [ 0x0, ['BitField', dict(start_bit = 5, end_bit = 6, native_type='unsigned char')]],
'Rsvd2' : [ 0x0, ['BitField', dict(start_bit = 6, end_bit = 8, native_type='unsigned char')]],
'Support' : [ 0x1, ['_PM_SUPPORT']],
} ],
'_DBGKD_CONTINUE' : [ 0x4, {
'ContinueStatus' : [ 0x0, ['long']],
} ],
'__unnamed_161d' : [ 0x4, {
'VirtualAddress' : [ 0x0, ['pointer', ['void']]],
'Long' : [ 0x0, ['unsigned long']],
'e1' : [ 0x0, ['_MMWSLENTRY']],
} ],
'_MMWSLE' : [ 0x4, {
'u1' : [ 0x0, ['__unnamed_161d']],
} ],
'_EXCEPTION_POINTERS' : [ 0x8, {
'ExceptionRecord' : [ 0x0, ['pointer', ['_EXCEPTION_RECORD']]],
'ContextRecord' : [ 0x4, ['pointer', ['_CONTEXT']]],
} ],
'_KQUEUE' : [ 0x28, {
'Header' : [ 0x0, ['_DISPATCHER_HEADER']],
'EntryListHead' : [ 0x10, ['_LIST_ENTRY']],
'CurrentCount' : [ 0x18, ['unsigned long']],
'MaximumCount' : [ 0x1c, ['unsigned long']],
'ThreadListHead' : [ 0x20, ['_LIST_ENTRY']],
} ],
'_RTL_USER_PROCESS_PARAMETERS' : [ 0x290, {
'MaximumLength' : [ 0x0, ['unsigned long']],
'Length' : [ 0x4, ['unsigned long']],
'Flags' : [ 0x8, ['unsigned long']],
'DebugFlags' : [ 0xc, ['unsigned long']],
'ConsoleHandle' : [ 0x10, ['pointer', ['void']]],
'ConsoleFlags' : [ 0x14, ['unsigned long']],
'StandardInput' : [ 0x18, ['pointer', ['void']]],
'StandardOutput' : [ 0x1c, ['pointer', ['void']]],
'StandardError' : [ 0x20, ['pointer', ['void']]],
'CurrentDirectory' : [ 0x24, ['_CURDIR']],
'DllPath' : [ 0x30, ['_UNICODE_STRING']],
'ImagePathName' : [ 0x38, ['_UNICODE_STRING']],
'CommandLine' : [ 0x40, ['_UNICODE_STRING']],
'Environment' : [ 0x48, ['pointer', ['void']]],
'StartingX' : [ 0x4c, ['unsigned long']],
'StartingY' : [ 0x50, ['unsigned long']],
'CountX' : [ 0x54, ['unsigned long']],
'CountY' : [ 0x58, ['unsigned long']],
'CountCharsX' : [ 0x5c, ['unsigned long']],
'CountCharsY' : [ 0x60, ['unsigned long']],
'FillAttribute' : [ 0x64, ['unsigned long']],
'WindowFlags' : [ 0x68, ['unsigned long']],
'ShowWindowFlags' : [ 0x6c, ['unsigned long']],
'WindowTitle' : [ 0x70, ['_UNICODE_STRING']],
'DesktopInfo' : [ 0x78, ['_UNICODE_STRING']],
'ShellInfo' : [ 0x80, ['_UNICODE_STRING']],
'RuntimeData' : [ 0x88, ['_UNICODE_STRING']],
'CurrentDirectores' : [ 0x90, ['array', 32, ['_RTL_DRIVE_LETTER_CURDIR']]],
} ],
'_CACHE_MANAGER_CALLBACKS' : [ 0x10, {
'AcquireForLazyWrite' : [ 0x0, ['pointer', ['void']]],
'ReleaseFromLazyWrite' : [ 0x4, ['pointer', ['void']]],
'AcquireForReadAhead' : [ 0x8, ['pointer', ['void']]],
'ReleaseFromReadAhead' : [ 0xc, ['pointer', ['void']]],
} ],
'_FILE_BASIC_INFORMATION' : [ 0x28, {
'CreationTime' : [ 0x0, ['_LARGE_INTEGER']],
'LastAccessTime' : [ 0x8, ['_LARGE_INTEGER']],
'LastWriteTime' : [ 0x10, ['_LARGE_INTEGER']],
'ChangeTime' : [ 0x18, ['_LARGE_INTEGER']],
'FileAttributes' : [ 0x20, ['unsigned long']],
} ],
'_CELL_DATA' : [ 0x50, {
'u' : [ 0x0, ['_u']],
} ],
'_SE_AUDIT_PROCESS_CREATION_INFO' : [ 0x4, {
'ImageFileName' : [ 0x0, ['pointer', ['_OBJECT_NAME_INFORMATION']]],
} ],
'_HEAP_ENTRY_EXTRA' : [ 0x8, {
'AllocatorBackTraceIndex' : [ 0x0, ['unsigned short']],
'TagIndex' : [ 0x2, ['unsigned short']],
'Settable' : [ 0x4, ['unsigned long']],
'ZeroInit' : [ 0x0, ['unsigned long long']],
} ],
'_VI_DEADLOCK_RESOURCE' : [ 0x80, {
'Type' : [ 0x0, ['Enumeration', dict(target = 'long', choices = {0: 'VfDeadlockUnknown', 1: 'VfDeadlockMutex', 2: 'VfDeadlockFastMutex', 3: 'VfDeadlockFastMutexUnsafe', 4: 'VfDeadlockSpinLock', 5: 'VfDeadlockQueuedSpinLock', 6: 'VfDeadlockTypeMaximum'})]],
'NodeCount' : [ 0x4, ['BitField', dict(start_bit = 0, end_bit = 16, native_type='unsigned long')]],
'RecursionCount' : [ 0x4, ['BitField', dict(start_bit = 16, end_bit = 32, native_type='unsigned long')]],
'ResourceAddress' : [ 0x8, ['pointer', ['void']]],
'ThreadOwner' : [ 0xc, ['pointer', ['_VI_DEADLOCK_THREAD']]],
'ResourceList' : [ 0x10, ['_LIST_ENTRY']],
'HashChainList' : [ 0x18, ['_LIST_ENTRY']],
'FreeListEntry' : [ 0x18, ['_LIST_ENTRY']],
'StackTrace' : [ 0x20, ['array', 8, ['pointer', ['void']]]],
'LastAcquireTrace' : [ 0x40, ['array', 8, ['pointer', ['void']]]],
'LastReleaseTrace' : [ 0x60, ['array', 8, ['pointer', ['void']]]],
} ],
'_CLIENT_ID' : [ 0x8, {
'UniqueProcess' : [ 0x0, ['pointer', ['void']]],
'UniqueThread' : [ 0x4, ['pointer', ['void']]],
} ],
'_PEB_FREE_BLOCK' : [ 0x8, {
'Next' : [ 0x0, ['pointer', ['_PEB_FREE_BLOCK']]],
'Size' : [ 0x4, ['unsigned long']],
} ],
'_PO_DEVICE_NOTIFY' : [ 0x28, {
'Link' : [ 0x0, ['_LIST_ENTRY']],
'TargetDevice' : [ 0x8, ['pointer', ['_DEVICE_OBJECT']]],
'WakeNeeded' : [ 0xc, ['unsigned char']],
'OrderLevel' : [ 0xd, ['unsigned char']],
'DeviceObject' : [ 0x10, ['pointer', ['_DEVICE_OBJECT']]],
'Node' : [ 0x14, ['pointer', ['void']]],
'DeviceName' : [ 0x18, ['pointer', ['unsigned short']]],
'DriverName' : [ 0x1c, ['pointer', ['unsigned short']]],
'ChildCount' : [ 0x20, ['unsigned long']],
'ActiveChild' : [ 0x24, ['unsigned long']],
} ],
'_MMPFNLIST' : [ 0x10, {
'Total' : [ 0x0, ['unsigned long']],
'ListName' : [ 0x4, ['Enumeration', dict(target = 'long', choices = {0: 'ZeroedPageList', 1: 'FreePageList', 2: 'StandbyPageList', 3: 'ModifiedPageList', 4: 'ModifiedNoWritePageList', 5: 'BadPageList', 6: 'ActiveAndValid', 7: 'TransitionPage'})]],
'Flink' : [ 0x8, ['unsigned long']],
'Blink' : [ 0xc, ['unsigned long']],
} ],
'__unnamed_1649' : [ 0x4, {
'Spare' : [ 0x0, ['array', 4, ['unsigned char']]],
} ],
'__unnamed_164b' : [ 0x4, {
'PrimaryBus' : [ 0x0, ['unsigned char']],
'SecondaryBus' : [ 0x1, ['unsigned char']],
'SubordinateBus' : [ 0x2, ['unsigned char']],
'SubtractiveDecode' : [ 0x3, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned char')]],
'IsaBitSet' : [ 0x3, ['BitField', dict(start_bit = 1, end_bit = 2, native_type='unsigned char')]],
'VgaBitSet' : [ 0x3, ['BitField', dict(start_bit = 2, end_bit = 3, native_type='unsigned char')]],
'WeChangedBusNumbers' : [ 0x3, ['BitField', dict(start_bit = 3, end_bit = 4, native_type='unsigned char')]],
'IsaBitRequired' : [ 0x3, ['BitField', dict(start_bit = 4, end_bit = 5, native_type='unsigned char')]],
} ],
'PCI_HEADER_TYPE_DEPENDENT' : [ 0x4, {
'type0' : [ 0x0, ['__unnamed_1649']],
'type1' : [ 0x0, ['__unnamed_164b']],
'type2' : [ 0x0, ['__unnamed_164b']],
} ],
'_DBGKD_GET_SET_BUS_DATA' : [ 0x14, {
'BusDataType' : [ 0x0, ['unsigned long']],
'BusNumber' : [ 0x4, ['unsigned long']],
'SlotNumber' : [ 0x8, ['unsigned long']],
'Offset' : [ 0xc, ['unsigned long']],
'Length' : [ 0x10, ['unsigned long']],
} ],
'_OBJECT_HEADER_NAME_INFO' : [ 0x10, {
'Directory' : [ 0x0, ['pointer', ['_OBJECT_DIRECTORY']]],
'Name' : [ 0x4, ['_UNICODE_STRING']],
'QueryReferences' : [ 0xc, ['unsigned long']],
} ],
'_KINTERRUPT' : [ 0x1e4, {
'Type' : [ 0x0, ['short']],
'Size' : [ 0x2, ['short']],
'InterruptListEntry' : [ 0x4, ['_LIST_ENTRY']],
'ServiceRoutine' : [ 0xc, ['pointer', ['void']]],
'ServiceContext' : [ 0x10, ['pointer', ['void']]],
'SpinLock' : [ 0x14, ['unsigned long']],
'TickCount' : [ 0x18, ['unsigned long']],
'ActualLock' : [ 0x1c, ['pointer', ['unsigned long']]],
'DispatchAddress' : [ 0x20, ['pointer', ['void']]],
'Vector' : [ 0x24, ['unsigned long']],
'Irql' : [ 0x28, ['unsigned char']],
'SynchronizeIrql' : [ 0x29, ['unsigned char']],
'FloatingSave' : [ 0x2a, ['unsigned char']],
'Connected' : [ 0x2b, ['unsigned char']],
'Number' : [ 0x2c, ['unsigned char']],
'ShareVector' : [ 0x2d, ['unsigned char']],
'Mode' : [ 0x30, ['Enumeration', dict(target = 'long', choices = {0: 'LevelSensitive', 1: 'Latched'})]],
'ServiceCount' : [ 0x34, ['unsigned long']],
'DispatchCount' : [ 0x38, ['unsigned long']],
'DispatchCode' : [ 0x3c, ['array', 106, ['unsigned long']]],
} ],
'_SECURITY_CLIENT_CONTEXT' : [ 0x3c, {
'SecurityQos' : [ 0x0, ['_SECURITY_QUALITY_OF_SERVICE']],
'ClientToken' : [ 0xc, ['pointer', ['void']]],
'DirectlyAccessClientToken' : [ 0x10, ['unsigned char']],
'DirectAccessEffectiveOnly' : [ 0x11, ['unsigned char']],
'ServerIsRemote' : [ 0x12, ['unsigned char']],
'ClientTokenControl' : [ 0x14, ['_TOKEN_CONTROL']],
} ],
'_BITMAP_RANGE' : [ 0x20, {
'Links' : [ 0x0, ['_LIST_ENTRY']],
'BasePage' : [ 0x8, ['long long']],
'FirstDirtyPage' : [ 0x10, ['unsigned long']],
'LastDirtyPage' : [ 0x14, ['unsigned long']],
'DirtyPages' : [ 0x18, ['unsigned long']],
'Bitmap' : [ 0x1c, ['pointer', ['unsigned long']]],
} ],
'_PCI_ARBITER_INSTANCE' : [ 0xe0, {
'Header' : [ 0x0, ['PCI_SECONDARY_EXTENSION']],
'Interface' : [ 0xc, ['pointer', ['_PCI_INTERFACE']]],
'BusFdoExtension' : [ 0x10, ['pointer', ['_PCI_FDO_EXTENSION']]],
'InstanceName' : [ 0x14, ['array', 24, ['unsigned short']]],
'CommonInstance' : [ 0x44, ['_ARBITER_INSTANCE']],
} ],
'_HANDLE_TRACE_DB_ENTRY' : [ 0x50, {
'ClientId' : [ 0x0, ['_CLIENT_ID']],
'Handle' : [ 0x8, ['pointer', ['void']]],
'Type' : [ 0xc, ['unsigned long']],
'StackTrace' : [ 0x10, ['array', 16, ['pointer', ['void']]]],
} ],
'_MMPAGING_FILE' : [ 0x44, {
'Size' : [ 0x0, ['unsigned long']],
'MaximumSize' : [ 0x4, ['unsigned long']],
'MinimumSize' : [ 0x8, ['unsigned long']],
'FreeSpace' : [ 0xc, ['unsigned long']],
'CurrentUsage' : [ 0x10, ['unsigned long']],
'PeakUsage' : [ 0x14, ['unsigned long']],
'Hint' : [ 0x18, ['unsigned long']],
'HighestPage' : [ 0x1c, ['unsigned long']],
'Entry' : [ 0x20, ['array', 2, ['pointer', ['_MMMOD_WRITER_MDL_ENTRY']]]],
'Bitmap' : [ 0x28, ['pointer', ['_RTL_BITMAP']]],
'File' : [ 0x2c, ['pointer', ['_FILE_OBJECT']]],
'PageFileName' : [ 0x30, ['_UNICODE_STRING']],
'PageFileNumber' : [ 0x38, ['unsigned long']],
'Extended' : [ 0x3c, ['unsigned char']],
'HintSetToZero' : [ 0x3d, ['unsigned char']],
'BootPartition' : [ 0x3e, ['unsigned char']],
'FileHandle' : [ 0x40, ['pointer', ['void']]],
} ],
'_BUS_EXTENSION_LIST' : [ 0x8, {
'Next' : [ 0x0, ['pointer', ['void']]],
'BusExtension' : [ 0x4, ['pointer', ['_PI_BUS_EXTENSION']]],
} ],
'_PCI_MJ_DISPATCH_TABLE' : [ 0x20, {
'PnpIrpMaximumMinorFunction' : [ 0x0, ['unsigned long']],
'PnpIrpDispatchTable' : [ 0x4, ['pointer', ['_PCI_MN_DISPATCH_TABLE']]],
'PowerIrpMaximumMinorFunction' : [ 0x8, ['unsigned long']],
'PowerIrpDispatchTable' : [ 0xc, ['pointer', ['_PCI_MN_DISPATCH_TABLE']]],
'SystemControlIrpDispatchStyle' : [ 0x10, ['Enumeration', dict(target = 'long', choices = {0: 'IRP_COMPLETE', 1: 'IRP_DOWNWARD', 2: 'IRP_UPWARD', 3: 'IRP_DISPATCH'})]],
'SystemControlIrpDispatchFunction' : [ 0x14, ['pointer', ['void']]],
'OtherIrpDispatchStyle' : [ 0x18, ['Enumeration', dict(target = 'long', choices = {0: 'IRP_COMPLETE', 1: 'IRP_DOWNWARD', 2: 'IRP_UPWARD', 3: 'IRP_DISPATCH'})]],
'OtherIrpDispatchFunction' : [ 0x1c, ['pointer', ['void']]],
} ],
'_POP_TRIGGER_WAIT' : [ 0x20, {
'Event' : [ 0x0, ['_KEVENT']],
'Status' : [ 0x10, ['long']],
'Link' : [ 0x14, ['_LIST_ENTRY']],
'Trigger' : [ 0x1c, ['pointer', ['_POP_ACTION_TRIGGER']]],
} ],
'_IO_TIMER' : [ 0x18, {
'Type' : [ 0x0, ['short']],
'TimerFlag' : [ 0x2, ['short']],
'TimerList' : [ 0x4, ['_LIST_ENTRY']],
'TimerRoutine' : [ 0xc, ['pointer', ['void']]],
'Context' : [ 0x10, ['pointer', ['void']]],
'DeviceObject' : [ 0x14, ['pointer', ['_DEVICE_OBJECT']]],
} ],
'_FXSAVE_FORMAT' : [ 0x208, {
'ControlWord' : [ 0x0, ['unsigned short']],
'StatusWord' : [ 0x2, ['unsigned short']],
'TagWord' : [ 0x4, ['unsigned short']],
'ErrorOpcode' : [ 0x6, ['unsigned short']],
'ErrorOffset' : [ 0x8, ['unsigned long']],
'ErrorSelector' : [ 0xc, ['unsigned long']],
'DataOffset' : [ 0x10, ['unsigned long']],
'DataSelector' : [ 0x14, ['unsigned long']],
'MXCsr' : [ 0x18, ['unsigned long']],
'MXCsrMask' : [ 0x1c, ['unsigned long']],
'RegisterArea' : [ 0x20, ['array', 128, ['unsigned char']]],
'Reserved3' : [ 0xa0, ['array', 128, ['unsigned char']]],
'Reserved4' : [ 0x120, ['array', 224, ['unsigned char']]],
'Align16Byte' : [ 0x200, ['array', 8, ['unsigned char']]],
} ],
'_MMWSLENTRY' : [ 0x4, {
'Valid' : [ 0x0, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned long')]],
'LockedInWs' : [ 0x0, ['BitField', dict(start_bit = 1, end_bit = 2, native_type='unsigned long')]],
'LockedInMemory' : [ 0x0, ['BitField', dict(start_bit = 2, end_bit = 3, native_type='unsigned long')]],
'Protection' : [ 0x0, ['BitField', dict(start_bit = 3, end_bit = 8, native_type='unsigned long')]],
'Hashed' : [ 0x0, ['BitField', dict(start_bit = 8, end_bit = 9, native_type='unsigned long')]],
'Direct' : [ 0x0, ['BitField', dict(start_bit = 9, end_bit = 10, native_type='unsigned long')]],
'Age' : [ 0x0, ['BitField', dict(start_bit = 10, end_bit = 12, native_type='unsigned long')]],
'VirtualPageNumber' : [ 0x0, ['BitField', dict(start_bit = 12, end_bit = 32, native_type='unsigned long')]],
} ],
'_OBJECT_DIRECTORY' : [ 0xa4, {
'HashBuckets' : [ 0x0, ['array', 37, ['pointer', ['_OBJECT_DIRECTORY_ENTRY']]]],
'Lock' : [ 0x94, ['_EX_PUSH_LOCK']],
'DeviceMap' : [ 0x98, ['pointer', ['_DEVICE_MAP']]],
'SessionId' : [ 0x9c, ['unsigned long']],
'Reserved' : [ 0xa0, ['unsigned short']],
'SymbolicLinkUsageCount' : [ 0xa2, ['unsigned short']],
} ],
'_OBJECT_CREATE_INFORMATION' : [ 0x30, {
'Attributes' : [ 0x0, ['unsigned long']],
'RootDirectory' : [ 0x4, ['pointer', ['void']]],
'ParseContext' : [ 0x8, ['pointer', ['void']]],
'ProbeMode' : [ 0xc, ['unsigned char']],
'PagedPoolCharge' : [ 0x10, ['unsigned long']],
'NonPagedPoolCharge' : [ 0x14, ['unsigned long']],
'SecurityDescriptorCharge' : [ 0x18, ['unsigned long']],
'SecurityDescriptor' : [ 0x1c, ['pointer', ['void']]],
'SecurityQos' : [ 0x20, ['pointer', ['_SECURITY_QUALITY_OF_SERVICE']]],
'SecurityQualityOfService' : [ 0x24, ['_SECURITY_QUALITY_OF_SERVICE']],
} ],
'_WMI_CLIENT_CONTEXT' : [ 0x4, {
'ProcessorNumber' : [ 0x0, ['unsigned char']],
'Alignment' : [ 0x1, ['unsigned char']],
'LoggerId' : [ 0x2, ['unsigned short']],
} ],
'_HEAP_LOOKASIDE' : [ 0x30, {
'ListHead' : [ 0x0, ['_SLIST_HEADER']],
'Depth' : [ 0x8, ['unsigned short']],
'MaximumDepth' : [ 0xa, ['unsigned short']],
'TotalAllocates' : [ 0xc, ['unsigned long']],
'AllocateMisses' : [ 0x10, ['unsigned long']],
'TotalFrees' : [ 0x14, ['unsigned long']],
'FreeMisses' : [ 0x18, ['unsigned long']],
'LastTotalAllocates' : [ 0x1c, ['unsigned long']],
'LastAllocateMisses' : [ 0x20, ['unsigned long']],
'Counters' : [ 0x24, ['array', 2, ['unsigned long']]],
} ],
'_ARBITER_INTERFACE' : [ 0x18, {
'Size' : [ 0x0, ['unsigned short']],
'Version' : [ 0x2, ['unsigned short']],
'Context' : [ 0x4, ['pointer', ['void']]],
'InterfaceReference' : [ 0x8, ['pointer', ['void']]],
'InterfaceDereference' : [ 0xc, ['pointer', ['void']]],
'ArbiterHandler' : [ 0x10, ['pointer', ['void']]],
'Flags' : [ 0x14, ['unsigned long']],
} ],
'_ACL' : [ 0x8, {
'AclRevision' : [ 0x0, ['unsigned char']],
'Sbz1' : [ 0x1, ['unsigned char']],
'AclSize' : [ 0x2, ['unsigned short']],
'AceCount' : [ 0x4, ['unsigned short']],
'Sbz2' : [ 0x6, ['unsigned short']],
} ],
'_CALL_PERFORMANCE_DATA' : [ 0x204, {
'SpinLock' : [ 0x0, ['unsigned long']],
'HashTable' : [ 0x4, ['array', 64, ['_LIST_ENTRY']]],
} ],
'_MMWSL' : [ 0x69c, {
'Quota' : [ 0x0, ['unsigned long']],
'FirstFree' : [ 0x4, ['unsigned long']],
'FirstDynamic' : [ 0x8, ['unsigned long']],
'LastEntry' : [ 0xc, ['unsigned long']],
'NextSlot' : [ 0x10, ['unsigned long']],
'Wsle' : [ 0x14, ['pointer', ['_MMWSLE']]],
'LastInitializedWsle' : [ 0x18, ['unsigned long']],
'NonDirectCount' : [ 0x1c, ['unsigned long']],
'HashTable' : [ 0x20, ['pointer', ['_MMWSLE_HASH']]],
'HashTableSize' : [ 0x24, ['unsigned long']],
'NumberOfCommittedPageTables' : [ 0x28, ['unsigned long']],
'HashTableStart' : [ 0x2c, ['pointer', ['void']]],
'HighestPermittedHashAddress' : [ 0x30, ['pointer', ['void']]],
'NumberOfImageWaiters' : [ 0x34, ['unsigned long']],
'VadBitMapHint' : [ 0x38, ['unsigned long']],
'UsedPageTableEntries' : [ 0x3c, ['array', 768, ['unsigned short']]],
'CommittedPageTables' : [ 0x63c, ['array', 24, ['unsigned long']]],
} ],
'_RTL_DRIVE_LETTER_CURDIR' : [ 0x10, {
'Flags' : [ 0x0, ['unsigned short']],
'Length' : [ 0x2, ['unsigned short']],
'TimeStamp' : [ 0x4, ['unsigned long']],
'DosPath' : [ 0x8, ['_STRING']],
} ],
'PCI_FUNCTION_RESOURCES' : [ 0x150, {
'Limit' : [ 0x0, ['array', 7, ['_IO_RESOURCE_DESCRIPTOR']]],
'Current' : [ 0xe0, ['array', 7, ['_CM_PARTIAL_RESOURCE_DESCRIPTOR']]],
} ],
'_WNODE_HEADER' : [ 0x30, {
'BufferSize' : [ 0x0, ['unsigned long']],
'ProviderId' : [ 0x4, ['unsigned long']],
'HistoricalContext' : [ 0x8, ['unsigned long long']],
'Version' : [ 0x8, ['unsigned long']],
'Linkage' : [ 0xc, ['unsigned long']],
'CountLost' : [ 0x10, ['unsigned long']],
'KernelHandle' : [ 0x10, ['pointer', ['void']]],
'TimeStamp' : [ 0x10, ['_LARGE_INTEGER']],
'Guid' : [ 0x18, ['_GUID']],
'ClientContext' : [ 0x28, ['unsigned long']],
'Flags' : [ 0x2c, ['unsigned long']],
} ],
'_EXCEPTION_RECORD' : [ 0x50, {
'ExceptionCode' : [ 0x0, ['long']],
'ExceptionFlags' : [ 0x4, ['unsigned long']],
'ExceptionRecord' : [ 0x8, ['pointer', ['_EXCEPTION_RECORD']]],
'ExceptionAddress' : [ 0xc, ['pointer', ['void']]],
'NumberParameters' : [ 0x10, ['unsigned long']],
'ExceptionInformation' : [ 0x14, ['array', 15, ['unsigned long']]],
} ],
'__unnamed_16c4' : [ 0x4, {
'ImageCommitment' : [ 0x0, ['unsigned long']],
'CreatingProcess' : [ 0x0, ['pointer', ['_EPROCESS']]],
} ],
'__unnamed_16c8' : [ 0x4, {
'ImageInformation' : [ 0x0, ['pointer', ['_SECTION_IMAGE_INFORMATION']]],
'FirstMappedVa' : [ 0x0, ['pointer', ['void']]],
} ],
'_SEGMENT' : [ 0x40, {
'ControlArea' : [ 0x0, ['pointer', ['_CONTROL_AREA']]],
'TotalNumberOfPtes' : [ 0x4, ['unsigned long']],
'NonExtendedPtes' : [ 0x8, ['unsigned long']],
'WritableUserReferences' : [ 0xc, ['unsigned long']],
'SizeOfSegment' : [ 0x10, ['unsigned long long']],
'SegmentPteTemplate' : [ 0x18, ['_MMPTE']],
'NumberOfCommittedPages' : [ 0x1c, ['unsigned long']],
'ExtendInfo' : [ 0x20, ['pointer', ['_MMEXTEND_INFO']]],
'SystemImageBase' : [ 0x24, ['pointer', ['void']]],
'BasedAddress' : [ 0x28, ['pointer', ['void']]],
'u1' : [ 0x2c, ['__unnamed_16c4']],
'u2' : [ 0x30, ['__unnamed_16c8']],
'PrototypePte' : [ 0x34, ['pointer', ['_MMPTE']]],
'ThePtes' : [ 0x38, ['array', 1, ['_MMPTE']]],
} ],
'_PCI_COMMON_EXTENSION' : [ 0x20, {
'Next' : [ 0x0, ['pointer', ['void']]],
'ExtensionType' : [ 0x4, ['Enumeration', dict(target = 'long', choices = {1768116272: 'PciPdoExtensionType', 1768116273: 'PciFdoExtensionType', 1768116274: 'PciArb_Io', 1768116275: 'PciArb_Memory', 1768116276: 'PciArb_Interrupt', 1768116277: 'PciArb_BusNumber', 1768116278: 'PciTrans_Interrupt', 1768116279: 'PciInterface_BusHandler', 1768116280: 'PciInterface_IntRouteHandler', 1768116281: 'PciInterface_PciCb', 1768116282: 'PciInterface_LegacyDeviceDetection', 1768116283: 'PciInterface_PmeHandler', 1768116284: 'PciInterface_DevicePresent', 1768116285: 'PciInterface_NativeIde', 1768116286: 'PciInterface_AgpTarget'})]],
'IrpDispatchTable' : [ 0x8, ['pointer', ['_PCI_MJ_DISPATCH_TABLE']]],
'DeviceState' : [ 0xc, ['unsigned char']],
'TentativeNextState' : [ 0xd, ['unsigned char']],
'SecondaryExtLock' : [ 0x10, ['_KEVENT']],
} ],
'_PRIVATE_CACHE_MAP' : [ 0x58, {
'NodeTypeCode' : [ 0x0, ['short']],
'Flags' : [ 0x0, ['_PRIVATE_CACHE_MAP_FLAGS']],
'UlongFlags' : [ 0x0, ['unsigned long']],
'ReadAheadMask' : [ 0x4, ['unsigned long']],
'FileObject' : [ 0x8, ['pointer', ['_FILE_OBJECT']]],
'FileOffset1' : [ 0x10, ['_LARGE_INTEGER']],
'BeyondLastByte1' : [ 0x18, ['_LARGE_INTEGER']],
'FileOffset2' : [ 0x20, ['_LARGE_INTEGER']],
'BeyondLastByte2' : [ 0x28, ['_LARGE_INTEGER']],
'ReadAheadOffset' : [ 0x30, ['array', 2, ['_LARGE_INTEGER']]],
'ReadAheadLength' : [ 0x40, ['array', 2, ['unsigned long']]],
'ReadAheadSpinLock' : [ 0x48, ['unsigned long']],
'PrivateLinks' : [ 0x4c, ['_LIST_ENTRY']],
} ],
'_RTL_HANDLE_TABLE' : [ 0x20, {
'MaximumNumberOfHandles' : [ 0x0, ['unsigned long']],
'SizeOfHandleTableEntry' : [ 0x4, ['unsigned long']],
'Reserved' : [ 0x8, ['array', 2, ['unsigned long']]],
'FreeHandles' : [ 0x10, ['pointer', ['_RTL_HANDLE_TABLE_ENTRY']]],
'CommittedHandles' : [ 0x14, ['pointer', ['_RTL_HANDLE_TABLE_ENTRY']]],
'UnCommittedHandles' : [ 0x18, ['pointer', ['_RTL_HANDLE_TABLE_ENTRY']]],
'MaxReservedHandles' : [ 0x1c, ['pointer', ['_RTL_HANDLE_TABLE_ENTRY']]],
} ],
'_POP_IDLE_HANDLER' : [ 0x20, {
'Latency' : [ 0x0, ['unsigned long']],
'TimeCheck' : [ 0x4, ['unsigned long']],
'DemoteLimit' : [ 0x8, ['unsigned long']],
'PromoteLimit' : [ 0xc, ['unsigned long']],
'PromoteCount' : [ 0x10, ['unsigned long']],
'Demote' : [ 0x14, ['unsigned char']],
'Promote' : [ 0x15, ['unsigned char']],
'PromotePercent' : [ 0x16, ['unsigned char']],
'DemotePercent' : [ 0x17, ['unsigned char']],
'State' : [ 0x18, ['unsigned char']],
'Spare' : [ 0x19, ['array', 3, ['unsigned char']]],
'IdleFunction' : [ 0x1c, ['pointer', ['void']]],
} ],
'SYSTEM_POWER_CAPABILITIES' : [ 0x4c, {
'PowerButtonPresent' : [ 0x0, ['unsigned char']],
'SleepButtonPresent' : [ 0x1, ['unsigned char']],
'LidPresent' : [ 0x2, ['unsigned char']],
'SystemS1' : [ 0x3, ['unsigned char']],
'SystemS2' : [ 0x4, ['unsigned char']],
'SystemS3' : [ 0x5, ['unsigned char']],
'SystemS4' : [ 0x6, ['unsigned char']],
'SystemS5' : [ 0x7, ['unsigned char']],
'HiberFilePresent' : [ 0x8, ['unsigned char']],
'FullWake' : [ 0x9, ['unsigned char']],
'VideoDimPresent' : [ 0xa, ['unsigned char']],
'ApmPresent' : [ 0xb, ['unsigned char']],
'UpsPresent' : [ 0xc, ['unsigned char']],
'ThermalControl' : [ 0xd, ['unsigned char']],
'ProcessorThrottle' : [ 0xe, ['unsigned char']],
'ProcessorMinThrottle' : [ 0xf, ['unsigned char']],
'ProcessorMaxThrottle' : [ 0x10, ['unsigned char']],
'spare2' : [ 0x11, ['array', 4, ['unsigned char']]],
'DiskSpinDown' : [ 0x15, ['unsigned char']],
'spare3' : [ 0x16, ['array', 8, ['unsigned char']]],
'SystemBatteriesPresent' : [ 0x1e, ['unsigned char']],
'BatteriesAreShortTerm' : [ 0x1f, ['unsigned char']],
'BatteryScale' : [ 0x20, ['array', 3, ['BATTERY_REPORTING_SCALE']]],
'AcOnLineWake' : [ 0x38, ['Enumeration', dict(target = 'long', choices = {0: 'PowerSystemUnspecified', 1: 'PowerSystemWorking', 2: 'PowerSystemSleeping1', 3: 'PowerSystemSleeping2', 4: 'PowerSystemSleeping3', 5: 'PowerSystemHibernate', 6: 'PowerSystemShutdown', 7: 'PowerSystemMaximum'})]],
'SoftLidWake' : [ 0x3c, ['Enumeration', dict(target = 'long', choices = {0: 'PowerSystemUnspecified', 1: 'PowerSystemWorking', 2: 'PowerSystemSleeping1', 3: 'PowerSystemSleeping2', 4: 'PowerSystemSleeping3', 5: 'PowerSystemHibernate', 6: 'PowerSystemShutdown', 7: 'PowerSystemMaximum'})]],
'RtcWake' : [ 0x40, ['Enumeration', dict(target = 'long', choices = {0: 'PowerSystemUnspecified', 1: 'PowerSystemWorking', 2: 'PowerSystemSleeping1', 3: 'PowerSystemSleeping2', 4: 'PowerSystemSleeping3', 5: 'PowerSystemHibernate', 6: 'PowerSystemShutdown', 7: 'PowerSystemMaximum'})]],
'MinDeviceWakeState' : [ 0x44, ['Enumeration', dict(target = 'long', choices = {0: 'PowerSystemUnspecified', 1: 'PowerSystemWorking', 2: 'PowerSystemSleeping1', 3: 'PowerSystemSleeping2', 4: 'PowerSystemSleeping3', 5: 'PowerSystemHibernate', 6: 'PowerSystemShutdown', 7: 'PowerSystemMaximum'})]],
'DefaultLowLatencyWake' : [ 0x48, ['Enumeration', dict(target = 'long', choices = {0: 'PowerSystemUnspecified', 1: 'PowerSystemWorking', 2: 'PowerSystemSleeping1', 3: 'PowerSystemSleeping2', 4: 'PowerSystemSleeping3', 5: 'PowerSystemHibernate', 6: 'PowerSystemShutdown', 7: 'PowerSystemMaximum'})]],
} ],
'_DEVOBJ_EXTENSION' : [ 0x2c, {
'Type' : [ 0x0, ['short']],
'Size' : [ 0x2, ['unsigned short']],
'DeviceObject' : [ 0x4, ['pointer', ['_DEVICE_OBJECT']]],
'PowerFlags' : [ 0x8, ['unsigned long']],
'Dope' : [ 0xc, ['pointer', ['_DEVICE_OBJECT_POWER_EXTENSION']]],
'ExtensionFlags' : [ 0x10, ['unsigned long']],
'DeviceNode' : [ 0x14, ['pointer', ['void']]],
'AttachedTo' : [ 0x18, ['pointer', ['_DEVICE_OBJECT']]],
'StartIoCount' : [ 0x1c, ['long']],
'StartIoKey' : [ 0x20, ['long']],
'StartIoFlags' : [ 0x24, ['unsigned long']],
'Vpb' : [ 0x28, ['pointer', ['_VPB']]],
} ],
'_FLOATING_SAVE_AREA' : [ 0x70, {
'ControlWord' : [ 0x0, ['unsigned long']],
'StatusWord' : [ 0x4, ['unsigned long']],
'TagWord' : [ 0x8, ['unsigned long']],
'ErrorOffset' : [ 0xc, ['unsigned long']],
'ErrorSelector' : [ 0x10, ['unsigned long']],
'DataOffset' : [ 0x14, ['unsigned long']],
'DataSelector' : [ 0x18, ['unsigned long']],
'RegisterArea' : [ 0x1c, ['array', 80, ['unsigned char']]],
'Cr0NpxState' : [ 0x6c, ['unsigned long']],
} ],
'_DBGKD_GET_VERSION64' : [ 0x28, {
'MajorVersion' : [ 0x0, ['unsigned short']],
'MinorVersion' : [ 0x2, ['unsigned short']],
'ProtocolVersion' : [ 0x4, ['unsigned short']],
'Flags' : [ 0x6, ['unsigned short']],
'MachineType' : [ 0x8, ['unsigned short']],
'MaxPacketType' : [ 0xa, ['unsigned char']],
'MaxStateChange' : [ 0xb, ['unsigned char']],
'MaxManipulate' : [ 0xc, ['unsigned char']],
'Simulation' : [ 0xd, ['unsigned char']],
'Unused' : [ 0xe, ['array', 1, ['unsigned short']]],
'KernBase' : [ 0x10, ['unsigned long long']],
'PsLoadedModuleList' : [ 0x18, ['unsigned long long']],
'DebuggerDataList' : [ 0x20, ['unsigned long long']],
} ],
'_MMVIEW' : [ 0x8, {
'Entry' : [ 0x0, ['unsigned long']],
'ControlArea' : [ 0x4, ['pointer', ['_CONTROL_AREA']]],
} ],
'_KSYSTEM_TIME' : [ 0xc, {
'LowPart' : [ 0x0, ['unsigned long']],
'High1Time' : [ 0x4, ['long']],
'High2Time' : [ 0x8, ['long']],
} ],
'_TOKEN' : [ 0xa8, {
'TokenSource' : [ 0x0, ['_TOKEN_SOURCE']],
'TokenId' : [ 0x10, ['_LUID']],
'AuthenticationId' : [ 0x18, ['_LUID']],
'ParentTokenId' : [ 0x20, ['_LUID']],
'ExpirationTime' : [ 0x28, ['_LARGE_INTEGER']],
'TokenLock' : [ 0x30, ['pointer', ['_ERESOURCE']]],
'AuditPolicy' : [ 0x38, ['_SEP_AUDIT_POLICY']],
'ModifiedId' : [ 0x40, ['_LUID']],
'SessionId' : [ 0x48, ['unsigned long']],
'UserAndGroupCount' : [ 0x4c, ['unsigned long']],
'RestrictedSidCount' : [ 0x50, ['unsigned long']],
'PrivilegeCount' : [ 0x54, ['unsigned long']],
'VariableLength' : [ 0x58, ['unsigned long']],
'DynamicCharged' : [ 0x5c, ['unsigned long']],
'DynamicAvailable' : [ 0x60, ['unsigned long']],
'DefaultOwnerIndex' : [ 0x64, ['unsigned long']],
'UserAndGroups' : [ 0x68, ['pointer', ['_SID_AND_ATTRIBUTES']]],
'RestrictedSids' : [ 0x6c, ['pointer', ['_SID_AND_ATTRIBUTES']]],
'PrimaryGroup' : [ 0x70, ['pointer', ['void']]],
'Privileges' : [ 0x74, ['pointer', ['_LUID_AND_ATTRIBUTES']]],
'DynamicPart' : [ 0x78, ['pointer', ['unsigned long']]],
'DefaultDacl' : [ 0x7c, ['pointer', ['_ACL']]],
'TokenType' : [ 0x80, ['Enumeration', dict(target = 'long', choices = {1: 'TokenPrimary', 2: 'TokenImpersonation'})]],
'ImpersonationLevel' : [ 0x84, ['Enumeration', dict(target = 'long', choices = {0: 'SecurityAnonymous', 1: 'SecurityIdentification', 2: 'SecurityImpersonation', 3: 'SecurityDelegation'})]],
'TokenFlags' : [ 0x88, ['unsigned long']],
'TokenInUse' : [ 0x8c, ['unsigned char']],
'ProxyData' : [ 0x90, ['pointer', ['_SECURITY_TOKEN_PROXY_DATA']]],
'AuditData' : [ 0x94, ['pointer', ['_SECURITY_TOKEN_AUDIT_DATA']]],
'OriginatingLogonSession' : [ 0x98, ['_LUID']],
'VariablePart' : [ 0xa0, ['unsigned long']],
} ],
'_TEB' : [ 0xfb8, {
'NtTib' : [ 0x0, ['_NT_TIB']],
'EnvironmentPointer' : [ 0x1c, ['pointer', ['void']]],
'ClientId' : [ 0x20, ['_CLIENT_ID']],
'ActiveRpcHandle' : [ 0x28, ['pointer', ['void']]],
'ThreadLocalStoragePointer' : [ 0x2c, ['pointer', ['void']]],
'ProcessEnvironmentBlock' : [ 0x30, ['pointer', ['_PEB']]],
'LastErrorValue' : [ 0x34, ['unsigned long']],
'CountOfOwnedCriticalSections' : [ 0x38, ['unsigned long']],
'CsrClientThread' : [ 0x3c, ['pointer', ['void']]],
'Win32ThreadInfo' : [ 0x40, ['pointer', ['void']]],
'User32Reserved' : [ 0x44, ['array', 26, ['unsigned long']]],
'UserReserved' : [ 0xac, ['array', 5, ['unsigned long']]],
'WOW32Reserved' : [ 0xc0, ['pointer', ['void']]],
'CurrentLocale' : [ 0xc4, ['unsigned long']],
'FpSoftwareStatusRegister' : [ 0xc8, ['unsigned long']],
'SystemReserved1' : [ 0xcc, ['array', 54, ['pointer', ['void']]]],
'ExceptionCode' : [ 0x1a4, ['long']],
'ActivationContextStack' : [ 0x1a8, ['_ACTIVATION_CONTEXT_STACK']],
'SpareBytes1' : [ 0x1bc, ['array', 24, ['unsigned char']]],
'GdiTebBatch' : [ 0x1d4, ['_GDI_TEB_BATCH']],
'RealClientId' : [ 0x6b4, ['_CLIENT_ID']],
'GdiCachedProcessHandle' : [ 0x6bc, ['pointer', ['void']]],
'GdiClientPID' : [ 0x6c0, ['unsigned long']],
'GdiClientTID' : [ 0x6c4, ['unsigned long']],
'GdiThreadLocalInfo' : [ 0x6c8, ['pointer', ['void']]],
'Win32ClientInfo' : [ 0x6cc, ['array', 62, ['unsigned long']]],
'glDispatchTable' : [ 0x7c4, ['array', 233, ['pointer', ['void']]]],
'glReserved1' : [ 0xb68, ['array', 29, ['unsigned long']]],
'glReserved2' : [ 0xbdc, ['pointer', ['void']]],
'glSectionInfo' : [ 0xbe0, ['pointer', ['void']]],
'glSection' : [ 0xbe4, ['pointer', ['void']]],
'glTable' : [ 0xbe8, ['pointer', ['void']]],
'glCurrentRC' : [ 0xbec, ['pointer', ['void']]],
'glContext' : [ 0xbf0, ['pointer', ['void']]],
'LastStatusValue' : [ 0xbf4, ['unsigned long']],
'StaticUnicodeString' : [ 0xbf8, ['_UNICODE_STRING']],
'StaticUnicodeBuffer' : [ 0xc00, ['array', 261, ['unsigned short']]],
'DeallocationStack' : [ 0xe0c, ['pointer', ['void']]],
'TlsSlots' : [ 0xe10, ['array', 64, ['pointer', ['void']]]],
'TlsLinks' : [ 0xf10, ['_LIST_ENTRY']],
'Vdm' : [ 0xf18, ['pointer', ['void']]],
'ReservedForNtRpc' : [ 0xf1c, ['pointer', ['void']]],
'DbgSsReserved' : [ 0xf20, ['array', 2, ['pointer', ['void']]]],
'HardErrorsAreDisabled' : [ 0xf28, ['unsigned long']],
'Instrumentation' : [ 0xf2c, ['array', 16, ['pointer', ['void']]]],
'WinSockData' : [ 0xf6c, ['pointer', ['void']]],
'GdiBatchCount' : [ 0xf70, ['unsigned long']],
'InDbgPrint' : [ 0xf74, ['unsigned char']],
'FreeStackOnTermination' : [ 0xf75, ['unsigned char']],
'HasFiberData' : [ 0xf76, ['unsigned char']],
'IdealProcessor' : [ 0xf77, ['unsigned char']],
'Spare3' : [ 0xf78, ['unsigned long']],
'ReservedForPerf' : [ 0xf7c, ['pointer', ['void']]],
'ReservedForOle' : [ 0xf80, ['pointer', ['void']]],
'WaitingOnLoaderLock' : [ 0xf84, ['unsigned long']],
'Wx86Thread' : [ 0xf88, ['_Wx86ThreadState']],
'TlsExpansionSlots' : [ 0xf94, ['pointer', ['pointer', ['void']]]],
'ImpersonationLocale' : [ 0xf98, ['unsigned long']],
'IsImpersonating' : [ 0xf9c, ['unsigned long']],
'NlsCache' : [ 0xfa0, ['pointer', ['void']]],
'pShimData' : [ 0xfa4, ['pointer', ['void']]],
'HeapVirtualAffinity' : [ 0xfa8, ['unsigned long']],
'CurrentTransactionHandle' : [ 0xfac, ['pointer', ['void']]],
'ActiveFrame' : [ 0xfb0, ['pointer', ['_TEB_ACTIVE_FRAME']]],
'SafeThunkCall' : [ 0xfb4, ['unsigned char']],
'BooleanSpare' : [ 0xfb5, ['array', 3, ['unsigned char']]],
} ],
'PCI_SECONDARY_EXTENSION' : [ 0xc, {
'List' : [ 0x0, ['_SINGLE_LIST_ENTRY']],
'ExtensionType' : [ 0x4, ['Enumeration', dict(target = 'long', choices = {1768116272: 'PciPdoExtensionType', 1768116273: 'PciFdoExtensionType', 1768116274: 'PciArb_Io', 1768116275: 'PciArb_Memory', 1768116276: 'PciArb_Interrupt', 1768116277: 'PciArb_BusNumber', 1768116278: 'PciTrans_Interrupt', 1768116279: 'PciInterface_BusHandler', 1768116280: 'PciInterface_IntRouteHandler', 1768116281: 'PciInterface_PciCb', 1768116282: 'PciInterface_LegacyDeviceDetection', 1768116283: 'PciInterface_PmeHandler', 1768116284: 'PciInterface_DevicePresent', 1768116285: 'PciInterface_NativeIde', 1768116286: 'PciInterface_AgpTarget'})]],
'Destructor' : [ 0x8, ['pointer', ['void']]],
} ],
'__unnamed_170f' : [ 0x30, {
'type0' : [ 0x0, ['_PCI_HEADER_TYPE_0']],
'type1' : [ 0x0, ['_PCI_HEADER_TYPE_1']],
'type2' : [ 0x0, ['_PCI_HEADER_TYPE_2']],
} ],
'_PCI_COMMON_CONFIG' : [ 0x100, {
'VendorID' : [ 0x0, ['unsigned short']],
'DeviceID' : [ 0x2, ['unsigned short']],
'Command' : [ 0x4, ['unsigned short']],
'Status' : [ 0x6, ['unsigned short']],
'RevisionID' : [ 0x8, ['unsigned char']],
'ProgIf' : [ 0x9, ['unsigned char']],
'SubClass' : [ 0xa, ['unsigned char']],
'BaseClass' : [ 0xb, ['unsigned char']],
'CacheLineSize' : [ 0xc, ['unsigned char']],
'LatencyTimer' : [ 0xd, ['unsigned char']],
'HeaderType' : [ 0xe, ['unsigned char']],
'BIST' : [ 0xf, ['unsigned char']],
'u' : [ 0x10, ['__unnamed_170f']],
'DeviceSpecific' : [ 0x40, ['array', 192, ['unsigned char']]],
} ],
'_HEAP_FREE_ENTRY_EXTRA' : [ 0x4, {
'TagIndex' : [ 0x0, ['unsigned short']],
'FreeBackTraceIndex' : [ 0x2, ['unsigned short']],
} ],
'_X86_DBGKD_CONTROL_SET' : [ 0x10, {
'TraceFlag' : [ 0x0, ['unsigned long']],
'Dr7' : [ 0x4, ['unsigned long']],
'CurrentSymbolStart' : [ 0x8, ['unsigned long']],
'CurrentSymbolEnd' : [ 0xc, ['unsigned long']],
} ],
'_SECTION_IMAGE_INFORMATION' : [ 0x30, {
'TransferAddress' : [ 0x0, ['pointer', ['void']]],
'ZeroBits' : [ 0x4, ['unsigned long']],
'MaximumStackSize' : [ 0x8, ['unsigned long']],
'CommittedStackSize' : [ 0xc, ['unsigned long']],
'SubSystemType' : [ 0x10, ['unsigned long']],
'SubSystemMinorVersion' : [ 0x14, ['unsigned short']],
'SubSystemMajorVersion' : [ 0x16, ['unsigned short']],
'SubSystemVersion' : [ 0x14, ['unsigned long']],
'GpValue' : [ 0x18, ['unsigned long']],
'ImageCharacteristics' : [ 0x1c, ['unsigned short']],
'DllCharacteristics' : [ 0x1e, ['unsigned short']],
'Machine' : [ 0x20, ['unsigned short']],
'ImageContainsCode' : [ 0x22, ['unsigned char']],
'Spare1' : [ 0x23, ['unsigned char']],
'LoaderFlags' : [ 0x24, ['unsigned long']],
'ImageFileSize' : [ 0x28, ['unsigned long']],
'Reserved' : [ 0x2c, ['array', 1, ['unsigned long']]],
} ],
'_POOL_TRACKER_TABLE' : [ 0x1c, {
'Key' : [ 0x0, ['unsigned long']],
'NonPagedAllocs' : [ 0x4, ['unsigned long']],
'NonPagedFrees' : [ 0x8, ['unsigned long']],
'NonPagedBytes' : [ 0xc, ['unsigned long']],
'PagedAllocs' : [ 0x10, ['unsigned long']],
'PagedFrees' : [ 0x14, ['unsigned long']],
'PagedBytes' : [ 0x18, ['unsigned long']],
} ],
'_MDL' : [ 0x1c, {
'Next' : [ 0x0, ['pointer', ['_MDL']]],
'Size' : [ 0x4, ['short']],
'MdlFlags' : [ 0x6, ['short']],
'Process' : [ 0x8, ['pointer', ['_EPROCESS']]],
'MappedSystemVa' : [ 0xc, ['pointer', ['void']]],
'StartVa' : [ 0x10, ['pointer', ['void']]],
'ByteCount' : [ 0x14, ['unsigned long']],
'ByteOffset' : [ 0x18, ['unsigned long']],
} ],
'_KNODE' : [ 0x30, {
'ProcessorMask' : [ 0x0, ['unsigned long']],
'Color' : [ 0x4, ['unsigned long']],
'MmShiftedColor' : [ 0x8, ['unsigned long']],
'FreeCount' : [ 0xc, ['array', 2, ['unsigned long']]],
'DeadStackList' : [ 0x18, ['_SLIST_HEADER']],
'PfnDereferenceSListHead' : [ 0x20, ['_SLIST_HEADER']],
'PfnDeferredList' : [ 0x28, ['pointer', ['_SINGLE_LIST_ENTRY']]],
'Seed' : [ 0x2c, ['unsigned char']],
'Flags' : [ 0x2d, ['_flags']],
} ],
'_PHYSICAL_MEMORY_DESCRIPTOR' : [ 0x10, {
'NumberOfRuns' : [ 0x0, ['unsigned long']],
'NumberOfPages' : [ 0x4, ['unsigned long']],
'Run' : [ 0x8, ['array', 1, ['_PHYSICAL_MEMORY_RUN']]],
} ],
'_PI_BUS_EXTENSION' : [ 0x44, {
'Flags' : [ 0x0, ['unsigned long']],
'NumberCSNs' : [ 0x4, ['unsigned long']],
'ReadDataPort' : [ 0x8, ['pointer', ['unsigned char']]],
'DataPortMapped' : [ 0xc, ['unsigned char']],
'AddressPort' : [ 0x10, ['pointer', ['unsigned char']]],
'AddrPortMapped' : [ 0x14, ['unsigned char']],
'CommandPort' : [ 0x18, ['pointer', ['unsigned char']]],
'CmdPortMapped' : [ 0x1c, ['unsigned char']],
'NextSlotNumber' : [ 0x20, ['unsigned long']],
'DeviceList' : [ 0x24, ['_SINGLE_LIST_ENTRY']],
'CardList' : [ 0x28, ['_SINGLE_LIST_ENTRY']],
'PhysicalBusDevice' : [ 0x2c, ['pointer', ['_DEVICE_OBJECT']]],
'FunctionalBusDevice' : [ 0x30, ['pointer', ['_DEVICE_OBJECT']]],
'AttachedDevice' : [ 0x34, ['pointer', ['_DEVICE_OBJECT']]],
'BusNumber' : [ 0x38, ['unsigned long']],
'SystemPowerState' : [ 0x3c, ['Enumeration', dict(target = 'long', choices = {0: 'PowerSystemUnspecified', 1: 'PowerSystemWorking', 2: 'PowerSystemSleeping1', 3: 'PowerSystemSleeping2', 4: 'PowerSystemSleeping3', 5: 'PowerSystemHibernate', 6: 'PowerSystemShutdown', 7: 'PowerSystemMaximum'})]],
'DevicePowerState' : [ 0x40, ['Enumeration', dict(target = 'long', choices = {0: 'PowerDeviceUnspecified', 1: 'PowerDeviceD0', 2: 'PowerDeviceD1', 3: 'PowerDeviceD2', 4: 'PowerDeviceD3', 5: 'PowerDeviceMaximum'})]],
} ],
'_VI_DEADLOCK_THREAD' : [ 0x1c, {
'Thread' : [ 0x0, ['pointer', ['_KTHREAD']]],
'CurrentSpinNode' : [ 0x4, ['pointer', ['_VI_DEADLOCK_NODE']]],
'CurrentOtherNode' : [ 0x8, ['pointer', ['_VI_DEADLOCK_NODE']]],
'ListEntry' : [ 0xc, ['_LIST_ENTRY']],
'FreeListEntry' : [ 0xc, ['_LIST_ENTRY']],
'NodeCount' : [ 0x14, ['unsigned long']],
'PagingCount' : [ 0x18, ['unsigned long']],
} ],
'_MMEXTEND_INFO' : [ 0x10, {
'CommittedSize' : [ 0x0, ['unsigned long long']],
'ReferenceCount' : [ 0x8, ['unsigned long']],
} ],
'_IMAGE_DEBUG_DIRECTORY' : [ 0x1c, {
'Characteristics' : [ 0x0, ['unsigned long']],
'TimeDateStamp' : [ 0x4, ['unsigned long']],
'MajorVersion' : [ 0x8, ['unsigned short']],
'MinorVersion' : [ 0xa, ['unsigned short']],
'Type' : [ 0xc, ['unsigned long']],
'SizeOfData' : [ 0x10, ['unsigned long']],
'AddressOfRawData' : [ 0x14, ['unsigned long']],
'PointerToRawData' : [ 0x18, ['unsigned long']],
} ],
'_PCI_INTERFACE' : [ 0x1c, {
'InterfaceType' : [ 0x0, ['pointer', ['_GUID']]],
'MinSize' : [ 0x4, ['unsigned short']],
'MinVersion' : [ 0x6, ['unsigned short']],
'MaxVersion' : [ 0x8, ['unsigned short']],
'Flags' : [ 0xa, ['unsigned short']],
'ReferenceCount' : [ 0xc, ['long']],
'Signature' : [ 0x10, ['Enumeration', dict(target = 'long', choices = {1768116272: 'PciPdoExtensionType', 1768116273: 'PciFdoExtensionType', 1768116274: 'PciArb_Io', 1768116275: 'PciArb_Memory', 1768116276: 'PciArb_Interrupt', 1768116277: 'PciArb_BusNumber', 1768116278: 'PciTrans_Interrupt', 1768116279: 'PciInterface_BusHandler', 1768116280: 'PciInterface_IntRouteHandler', 1768116281: 'PciInterface_PciCb', 1768116282: 'PciInterface_LegacyDeviceDetection', 1768116283: 'PciInterface_PmeHandler', 1768116284: 'PciInterface_DevicePresent', 1768116285: 'PciInterface_NativeIde', 1768116286: 'PciInterface_AgpTarget'})]],
'Constructor' : [ 0x14, ['pointer', ['void']]],
'Initializer' : [ 0x18, ['pointer', ['void']]],
} ],
'_FILE_NETWORK_OPEN_INFORMATION' : [ 0x38, {
'CreationTime' : [ 0x0, ['_LARGE_INTEGER']],
'LastAccessTime' : [ 0x8, ['_LARGE_INTEGER']],
'LastWriteTime' : [ 0x10, ['_LARGE_INTEGER']],
'ChangeTime' : [ 0x18, ['_LARGE_INTEGER']],
'AllocationSize' : [ 0x20, ['_LARGE_INTEGER']],
'EndOfFile' : [ 0x28, ['_LARGE_INTEGER']],
'FileAttributes' : [ 0x30, ['unsigned long']],
} ],
'_MMVAD' : [ 0x28, {
'StartingVpn' : [ 0x0, ['unsigned long']],
'EndingVpn' : [ 0x4, ['unsigned long']],
'Parent' : [ 0x8, ['pointer', ['_MMVAD']]],
'LeftChild' : [ 0xc, ['pointer', ['_MMVAD']]],
'RightChild' : [ 0x10, ['pointer', ['_MMVAD']]],
'u' : [ 0x14, ['__unnamed_1492']],
'ControlArea' : [ 0x18, ['pointer', ['_CONTROL_AREA']]],
'FirstPrototypePte' : [ 0x1c, ['pointer', ['_MMPTE']]],
'LastContiguousPte' : [ 0x20, ['pointer', ['_MMPTE']]],
'u2' : [ 0x24, ['__unnamed_1495']],
} ],
'__unnamed_1743' : [ 0x8, {
'IoStatus' : [ 0x0, ['_IO_STATUS_BLOCK']],
'LastByte' : [ 0x0, ['_LARGE_INTEGER']],
} ],
'_MMMOD_WRITER_MDL_ENTRY' : [ 0x58, {
'Links' : [ 0x0, ['_LIST_ENTRY']],
'WriteOffset' : [ 0x8, ['_LARGE_INTEGER']],
'u' : [ 0x10, ['__unnamed_1743']],
'Irp' : [ 0x18, ['pointer', ['_IRP']]],
'LastPageToWrite' : [ 0x1c, ['unsigned long']],
'PagingListHead' : [ 0x20, ['pointer', ['_MMMOD_WRITER_LISTHEAD']]],
'CurrentList' : [ 0x24, ['pointer', ['_LIST_ENTRY']]],
'PagingFile' : [ 0x28, ['pointer', ['_MMPAGING_FILE']]],
'File' : [ 0x2c, ['pointer', ['_FILE_OBJECT']]],
'ControlArea' : [ 0x30, ['pointer', ['_CONTROL_AREA']]],
'FileResource' : [ 0x34, ['pointer', ['_ERESOURCE']]],
'Mdl' : [ 0x38, ['_MDL']],
'Page' : [ 0x54, ['array', 1, ['unsigned long']]],
} ],
'_POP_POWER_ACTION' : [ 0x40, {
'Updates' : [ 0x0, ['unsigned char']],
'State' : [ 0x1, ['unsigned char']],
'Shutdown' : [ 0x2, ['unsigned char']],
'Action' : [ 0x4, ['Enumeration', dict(target = 'long', choices = {0: 'PowerActionNone', 1: 'PowerActionReserved', 2: 'PowerActionSleep', 3: 'PowerActionHibernate', 4: 'PowerActionShutdown', 5: 'PowerActionShutdownReset', 6: 'PowerActionShutdownOff', 7: 'PowerActionWarmEject'})]],
'LightestState' : [ 0x8, ['Enumeration', dict(target = 'long', choices = {0: 'PowerSystemUnspecified', 1: 'PowerSystemWorking', 2: 'PowerSystemSleeping1', 3: 'PowerSystemSleeping2', 4: 'PowerSystemSleeping3', 5: 'PowerSystemHibernate', 6: 'PowerSystemShutdown', 7: 'PowerSystemMaximum'})]],
'Flags' : [ 0xc, ['unsigned long']],
'Status' : [ 0x10, ['long']],
'IrpMinor' : [ 0x14, ['unsigned char']],
'SystemState' : [ 0x18, ['Enumeration', dict(target = 'long', choices = {0: 'PowerSystemUnspecified', 1: 'PowerSystemWorking', 2: 'PowerSystemSleeping1', 3: 'PowerSystemSleeping2', 4: 'PowerSystemSleeping3', 5: 'PowerSystemHibernate', 6: 'PowerSystemShutdown', 7: 'PowerSystemMaximum'})]],
'NextSystemState' : [ 0x1c, ['Enumeration', dict(target = 'long', choices = {0: 'PowerSystemUnspecified', 1: 'PowerSystemWorking', 2: 'PowerSystemSleeping1', 3: 'PowerSystemSleeping2', 4: 'PowerSystemSleeping3', 5: 'PowerSystemHibernate', 6: 'PowerSystemShutdown', 7: 'PowerSystemMaximum'})]],
'ShutdownBugCode' : [ 0x20, ['pointer', ['_POP_SHUTDOWN_BUG_CHECK']]],
'DevState' : [ 0x24, ['pointer', ['_POP_DEVICE_SYS_STATE']]],
'HiberContext' : [ 0x28, ['pointer', ['_POP_HIBER_CONTEXT']]],
'LastWakeState' : [ 0x2c, ['Enumeration', dict(target = 'long', choices = {0: 'PowerSystemUnspecified', 1: 'PowerSystemWorking', 2: 'PowerSystemSleeping1', 3: 'PowerSystemSleeping2', 4: 'PowerSystemSleeping3', 5: 'PowerSystemHibernate', 6: 'PowerSystemShutdown', 7: 'PowerSystemMaximum'})]],
'WakeTime' : [ 0x30, ['unsigned long long']],
'SleepTime' : [ 0x38, ['unsigned long long']],
} ],
'_IO_STATUS_BLOCK' : [ 0x8, {
'Status' : [ 0x0, ['long']],
'Pointer' : [ 0x0, ['pointer', ['void']]],
'Information' : [ 0x4, ['unsigned long']],
} ],
'_LPCP_MESSAGE' : [ 0x30, {
'Entry' : [ 0x0, ['_LIST_ENTRY']],
'FreeEntry' : [ 0x0, ['_SINGLE_LIST_ENTRY']],
'Reserved0' : [ 0x4, ['unsigned long']],
'SenderPort' : [ 0x8, ['pointer', ['void']]],
'RepliedToThread' : [ 0xc, ['pointer', ['_ETHREAD']]],
'PortContext' : [ 0x10, ['pointer', ['void']]],
'Request' : [ 0x18, ['_PORT_MESSAGE']],
} ],
'_MMVAD_SHORT' : [ 0x18, {
'StartingVpn' : [ 0x0, ['unsigned long']],
'EndingVpn' : [ 0x4, ['unsigned long']],
'Parent' : [ 0x8, ['pointer', ['_MMVAD']]],
'LeftChild' : [ 0xc, ['pointer', ['_MMVAD']]],
'RightChild' : [ 0x10, ['pointer', ['_MMVAD']]],
'u' : [ 0x14, ['__unnamed_1492']],
} ],
'__unnamed_175f' : [ 0x2c, {
'InitialPrivilegeSet' : [ 0x0, ['_INITIAL_PRIVILEGE_SET']],
'PrivilegeSet' : [ 0x0, ['_PRIVILEGE_SET']],
} ],
'_ACCESS_STATE' : [ 0x74, {
'OperationID' : [ 0x0, ['_LUID']],
'SecurityEvaluated' : [ 0x8, ['unsigned char']],
'GenerateAudit' : [ 0x9, ['unsigned char']],
'GenerateOnClose' : [ 0xa, ['unsigned char']],
'PrivilegesAllocated' : [ 0xb, ['unsigned char']],
'Flags' : [ 0xc, ['unsigned long']],
'RemainingDesiredAccess' : [ 0x10, ['unsigned long']],
'PreviouslyGrantedAccess' : [ 0x14, ['unsigned long']],
'OriginalDesiredAccess' : [ 0x18, ['unsigned long']],
'SubjectSecurityContext' : [ 0x1c, ['_SECURITY_SUBJECT_CONTEXT']],
'SecurityDescriptor' : [ 0x2c, ['pointer', ['void']]],
'AuxData' : [ 0x30, ['pointer', ['void']]],
'Privileges' : [ 0x34, ['__unnamed_175f']],
'AuditPrivileges' : [ 0x60, ['unsigned char']],
'ObjectName' : [ 0x64, ['_UNICODE_STRING']],
'ObjectTypeName' : [ 0x6c, ['_UNICODE_STRING']],
} ],
'_PNP_DEVICE_EVENT_ENTRY' : [ 0x58, {
'ListEntry' : [ 0x0, ['_LIST_ENTRY']],
'Argument' : [ 0x8, ['unsigned long']],
'CallerEvent' : [ 0xc, ['pointer', ['_KEVENT']]],
'Callback' : [ 0x10, ['pointer', ['void']]],
'Context' : [ 0x14, ['pointer', ['void']]],
'VetoType' : [ 0x18, ['pointer', ['Enumeration', dict(target = 'long', choices = {0: 'PNP_VetoTypeUnknown', 1: 'PNP_VetoLegacyDevice', 2: 'PNP_VetoPendingClose', 3: 'PNP_VetoWindowsApp', 4: 'PNP_VetoWindowsService', 5: 'PNP_VetoOutstandingOpen', 6: 'PNP_VetoDevice', 7: 'PNP_VetoDriver', 8: 'PNP_VetoIllegalDeviceRequest', 9: 'PNP_VetoInsufficientPower', 10: 'PNP_VetoNonDisableable', 11: 'PNP_VetoLegacyDriver', 12: 'PNP_VetoInsufficientRights'})]]],
'VetoName' : [ 0x1c, ['pointer', ['_UNICODE_STRING']]],
'Data' : [ 0x20, ['_PLUGPLAY_EVENT_BLOCK']],
} ],
'_PRIVATE_CACHE_MAP_FLAGS' : [ 0x4, {
'DontUse' : [ 0x0, ['BitField', dict(start_bit = 0, end_bit = 16, native_type='unsigned long')]],
'ReadAheadActive' : [ 0x0, ['BitField', dict(start_bit = 16, end_bit = 17, native_type='unsigned long')]],
'ReadAheadEnabled' : [ 0x0, ['BitField', dict(start_bit = 17, end_bit = 18, native_type='unsigned long')]],
'Available' : [ 0x0, ['BitField', dict(start_bit = 18, end_bit = 32, native_type='unsigned long')]],
} ],
'_PNP_DEVICE_EVENT_LIST' : [ 0x4c, {
'Status' : [ 0x0, ['long']],
'EventQueueMutex' : [ 0x4, ['_KMUTANT']],
'Lock' : [ 0x24, ['_FAST_MUTEX']],
'List' : [ 0x44, ['_LIST_ENTRY']],
} ],
'_KPROCESSOR_STATE' : [ 0x320, {
'ContextFrame' : [ 0x0, ['_CONTEXT']],
'SpecialRegisters' : [ 0x2cc, ['_KSPECIAL_REGISTERS']],
} ],
'_MMPTE_TRANSITION' : [ 0x4, {
'Valid' : [ 0x0, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned long')]],
'Write' : [ 0x0, ['BitField', dict(start_bit = 1, end_bit = 2, native_type='unsigned long')]],
'Owner' : [ 0x0, ['BitField', dict(start_bit = 2, end_bit = 3, native_type='unsigned long')]],
'WriteThrough' : [ 0x0, ['BitField', dict(start_bit = 3, end_bit = 4, native_type='unsigned long')]],
'CacheDisable' : [ 0x0, ['BitField', dict(start_bit = 4, end_bit = 5, native_type='unsigned long')]],
'Protection' : [ 0x0, ['BitField', dict(start_bit = 5, end_bit = 10, native_type='unsigned long')]],
'Prototype' : [ 0x0, ['BitField', dict(start_bit = 10, end_bit = 11, native_type='unsigned long')]],
'Transition' : [ 0x0, ['BitField', dict(start_bit = 11, end_bit = 12, native_type='unsigned long')]],
'PageFrameNumber' : [ 0x0, ['BitField', dict(start_bit = 12, end_bit = 32, native_type='unsigned long')]],
} ],
'_TOKEN_SOURCE' : [ 0x10, {
'SourceName' : [ 0x0, ['array', 8, ['unsigned char']]],
'SourceIdentifier' : [ 0x8, ['_LUID']],
} ],
'_STRING' : [ 0x8, {
'Length' : [ 0x0, ['unsigned short']],
'MaximumLength' : [ 0x2, ['unsigned short']],
'Buffer' : [ 0x4, ['pointer', ['unsigned char']]],
} ],
'_MMVAD_FLAGS2' : [ 0x4, {
'FileOffset' : [ 0x0, ['BitField', dict(start_bit = 0, end_bit = 24, native_type='unsigned long')]],
'SecNoChange' : [ 0x0, ['BitField', dict(start_bit = 24, end_bit = 25, native_type='unsigned long')]],
'OneSecured' : [ 0x0, ['BitField', dict(start_bit = 25, end_bit = 26, native_type='unsigned long')]],
'MultipleSecured' : [ 0x0, ['BitField', dict(start_bit = 26, end_bit = 27, native_type='unsigned long')]],
'ReadOnly' : [ 0x0, ['BitField', dict(start_bit = 27, end_bit = 28, native_type='unsigned long')]],
'LongVad' : [ 0x0, ['BitField', dict(start_bit = 28, end_bit = 29, native_type='unsigned long')]],
'ExtendableFile' : [ 0x0, ['BitField', dict(start_bit = 29, end_bit = 30, native_type='unsigned long')]],
'Inherit' : [ 0x0, ['BitField', dict(start_bit = 30, end_bit = 31, native_type='unsigned long')]],
'CopyOnWrite' : [ 0x0, ['BitField', dict(start_bit = 31, end_bit = 32, native_type='unsigned long')]],
} ],
'_flags' : [ 0x1, {
'Removable' : [ 0x0, ['unsigned char']],
} ],
'_CM_KEY_SECURITY_CACHE' : [ 0x28, {
'Cell' : [ 0x0, ['unsigned long']],
'ConvKey' : [ 0x4, ['unsigned long']],
'List' : [ 0x8, ['_LIST_ENTRY']],
'DescriptorLength' : [ 0x10, ['unsigned long']],
'Descriptor' : [ 0x14, ['_SECURITY_DESCRIPTOR_RELATIVE']],
} ],
'_PROCESSOR_POWER_POLICY_INFO' : [ 0x14, {
'TimeCheck' : [ 0x0, ['unsigned long']],
'DemoteLimit' : [ 0x4, ['unsigned long']],
'PromoteLimit' : [ 0x8, ['unsigned long']],
'DemotePercent' : [ 0xc, ['unsigned char']],
'PromotePercent' : [ 0xd, ['unsigned char']],
'Spare' : [ 0xe, ['array', 2, ['unsigned char']]],
'AllowDemotion' : [ 0x10, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned long')]],
'AllowPromotion' : [ 0x10, ['BitField', dict(start_bit = 1, end_bit = 2, native_type='unsigned long')]],
'Reserved' : [ 0x10, ['BitField', dict(start_bit = 2, end_bit = 32, native_type='unsigned long')]],
} ],
'_ARBITER_INSTANCE' : [ 0x9c, {
'Signature' : [ 0x0, ['unsigned long']],
'MutexEvent' : [ 0x4, ['pointer', ['_KEVENT']]],
'Name' : [ 0x8, ['pointer', ['unsigned short']]],
'ResourceType' : [ 0xc, ['long']],
'Allocation' : [ 0x10, ['pointer', ['_RTL_RANGE_LIST']]],
'PossibleAllocation' : [ 0x14, ['pointer', ['_RTL_RANGE_LIST']]],
'OrderingList' : [ 0x18, ['_ARBITER_ORDERING_LIST']],
'ReservedList' : [ 0x20, ['_ARBITER_ORDERING_LIST']],
'ReferenceCount' : [ 0x28, ['long']],
'Interface' : [ 0x2c, ['pointer', ['_ARBITER_INTERFACE']]],
'AllocationStackMaxSize' : [ 0x30, ['unsigned long']],
'AllocationStack' : [ 0x34, ['pointer', ['_ARBITER_ALLOCATION_STATE']]],
'UnpackRequirement' : [ 0x38, ['pointer', ['void']]],
'PackResource' : [ 0x3c, ['pointer', ['void']]],
'UnpackResource' : [ 0x40, ['pointer', ['void']]],
'ScoreRequirement' : [ 0x44, ['pointer', ['void']]],
'TestAllocation' : [ 0x48, ['pointer', ['void']]],
'RetestAllocation' : [ 0x4c, ['pointer', ['void']]],
'CommitAllocation' : [ 0x50, ['pointer', ['void']]],
'RollbackAllocation' : [ 0x54, ['pointer', ['void']]],
'BootAllocation' : [ 0x58, ['pointer', ['void']]],
'QueryArbitrate' : [ 0x5c, ['pointer', ['void']]],
'QueryConflict' : [ 0x60, ['pointer', ['void']]],
'AddReserved' : [ 0x64, ['pointer', ['void']]],
'StartArbiter' : [ 0x68, ['pointer', ['void']]],
'PreprocessEntry' : [ 0x6c, ['pointer', ['void']]],
'AllocateEntry' : [ 0x70, ['pointer', ['void']]],
'GetNextAllocationRange' : [ 0x74, ['pointer', ['void']]],
'FindSuitableRange' : [ 0x78, ['pointer', ['void']]],
'AddAllocation' : [ 0x7c, ['pointer', ['void']]],
'BacktrackAllocation' : [ 0x80, ['pointer', ['void']]],
'OverrideConflict' : [ 0x84, ['pointer', ['void']]],
'TransactionInProgress' : [ 0x88, ['unsigned char']],
'Extension' : [ 0x8c, ['pointer', ['void']]],
'BusDeviceObject' : [ 0x90, ['pointer', ['_DEVICE_OBJECT']]],
'ConflictCallbackContext' : [ 0x94, ['pointer', ['void']]],
'ConflictCallback' : [ 0x98, ['pointer', ['void']]],
} ],
'_BUS_HANDLER' : [ 0x6c, {
'Version' : [ 0x0, ['unsigned long']],
'InterfaceType' : [ 0x4, ['Enumeration', dict(target = 'long', choices = {0: 'Internal', 1: 'Isa', 2: 'Eisa', 3: 'MicroChannel', 4: 'TurboChannel', 5: 'PCIBus', 6: 'VMEBus', 7: 'NuBus', 8: 'PCMCIABus', 9: 'CBus', 10: 'MPIBus', 11: 'MPSABus', 12: 'ProcessorInternal', 13: 'InternalPowerBus', 14: 'PNPISABus', 15: 'PNPBus', 16: 'MaximumInterfaceType', -1: 'InterfaceTypeUndefined'})]],
'ConfigurationType' : [ 0x8, ['Enumeration', dict(target = 'long', choices = {0: 'Cmos', 1: 'EisaConfiguration', 2: 'Pos', 3: 'CbusConfiguration', 4: 'PCIConfiguration', 5: 'VMEConfiguration', 6: 'NuBusConfiguration', 7: 'PCMCIAConfiguration', 8: 'MPIConfiguration', 9: 'MPSAConfiguration', 10: 'PNPISAConfiguration', 11: 'SgiInternalConfiguration', 12: 'MaximumBusDataType', -1: 'ConfigurationSpaceUndefined'})]],
'BusNumber' : [ 0xc, ['unsigned long']],
'DeviceObject' : [ 0x10, ['pointer', ['_DEVICE_OBJECT']]],
'ParentHandler' : [ 0x14, ['pointer', ['_BUS_HANDLER']]],
'BusData' : [ 0x18, ['pointer', ['void']]],
'DeviceControlExtensionSize' : [ 0x1c, ['unsigned long']],
'BusAddresses' : [ 0x20, ['pointer', ['_SUPPORTED_RANGES']]],
'Reserved' : [ 0x24, ['array', 4, ['unsigned long']]],
'GetBusData' : [ 0x34, ['pointer', ['void']]],
'SetBusData' : [ 0x38, ['pointer', ['void']]],
'AdjustResourceList' : [ 0x3c, ['pointer', ['void']]],
'AssignSlotResources' : [ 0x40, ['pointer', ['void']]],
'GetInterruptVector' : [ 0x44, ['pointer', ['void']]],
'TranslateBusAddress' : [ 0x48, ['pointer', ['void']]],
'Spare1' : [ 0x4c, ['pointer', ['void']]],
'Spare2' : [ 0x50, ['pointer', ['void']]],
'Spare3' : [ 0x54, ['pointer', ['void']]],
'Spare4' : [ 0x58, ['pointer', ['void']]],
'Spare5' : [ 0x5c, ['pointer', ['void']]],
'Spare6' : [ 0x60, ['pointer', ['void']]],
'Spare7' : [ 0x64, ['pointer', ['void']]],
'Spare8' : [ 0x68, ['pointer', ['void']]],
} ],
'_PCI_MN_DISPATCH_TABLE' : [ 0x8, {
'DispatchStyle' : [ 0x0, ['Enumeration', dict(target = 'long', choices = {0: 'IRP_COMPLETE', 1: 'IRP_DOWNWARD', 2: 'IRP_UPWARD', 3: 'IRP_DISPATCH'})]],
'DispatchFunction' : [ 0x4, ['pointer', ['void']]],
} ],
'_POP_DEVICE_SYS_STATE' : [ 0x620, {
'IrpMinor' : [ 0x0, ['unsigned char']],
'SystemState' : [ 0x4, ['Enumeration', dict(target = 'long', choices = {0: 'PowerSystemUnspecified', 1: 'PowerSystemWorking', 2: 'PowerSystemSleeping1', 3: 'PowerSystemSleeping2', 4: 'PowerSystemSleeping3', 5: 'PowerSystemHibernate', 6: 'PowerSystemShutdown', 7: 'PowerSystemMaximum'})]],
'Event' : [ 0x8, ['_KEVENT']],
'SpinLock' : [ 0x18, ['unsigned long']],
'Thread' : [ 0x1c, ['pointer', ['_KTHREAD']]],
'GetNewDeviceList' : [ 0x20, ['unsigned char']],
'Order' : [ 0x24, ['_PO_DEVICE_NOTIFY_ORDER']],
'Status' : [ 0x26c, ['long']],
'FailedDevice' : [ 0x270, ['pointer', ['_DEVICE_OBJECT']]],
'Waking' : [ 0x274, ['unsigned char']],
'Cancelled' : [ 0x275, ['unsigned char']],
'IgnoreErrors' : [ 0x276, ['unsigned char']],
'IgnoreNotImplemented' : [ 0x277, ['unsigned char']],
'WaitAny' : [ 0x278, ['unsigned char']],
'WaitAll' : [ 0x279, ['unsigned char']],
'PresentIrpQueue' : [ 0x27c, ['_LIST_ENTRY']],
'Head' : [ 0x284, ['_POP_DEVICE_POWER_IRP']],
'PowerIrpState' : [ 0x2b0, ['array', 20, ['_POP_DEVICE_POWER_IRP']]],
} ],
'_OBJECT_DUMP_CONTROL' : [ 0x8, {
'Stream' : [ 0x0, ['pointer', ['void']]],
'Detail' : [ 0x4, ['unsigned long']],
} ],
'_SECURITY_SUBJECT_CONTEXT' : [ 0x10, {
'ClientToken' : [ 0x0, ['pointer', ['void']]],
'ImpersonationLevel' : [ 0x4, ['Enumeration', dict(target = 'long', choices = {0: 'SecurityAnonymous', 1: 'SecurityIdentification', 2: 'SecurityImpersonation', 3: 'SecurityDelegation'})]],
'PrimaryToken' : [ 0x8, ['pointer', ['void']]],
'ProcessAuditId' : [ 0xc, ['pointer', ['void']]],
} ],
'_HEAP_STOP_ON_TAG' : [ 0x4, {
'HeapAndTagIndex' : [ 0x0, ['unsigned long']],
'TagIndex' : [ 0x0, ['unsigned short']],
'HeapIndex' : [ 0x2, ['unsigned short']],
} ],
'_ACTIVATION_CONTEXT_STACK' : [ 0x14, {
'Flags' : [ 0x0, ['unsigned long']],
'NextCookieSequenceNumber' : [ 0x4, ['unsigned long']],
'ActiveFrame' : [ 0x8, ['pointer', ['void']]],
'FrameListCache' : [ 0xc, ['_LIST_ENTRY']],
} ],
'_MMWSLE_HASH' : [ 0x8, {
'Key' : [ 0x0, ['pointer', ['void']]],
'Index' : [ 0x4, ['unsigned long']],
} ],
'_CM_NAME_CONTROL_BLOCK' : [ 0x10, {
'Compressed' : [ 0x0, ['unsigned char']],
'RefCount' : [ 0x2, ['unsigned short']],
'NameHash' : [ 0x4, ['_CM_NAME_HASH']],
'ConvKey' : [ 0x4, ['unsigned long']],
'NextHash' : [ 0x8, ['pointer', ['_CM_KEY_HASH']]],
'NameLength' : [ 0xc, ['unsigned short']],
'Name' : [ 0xe, ['array', 1, ['unsigned short']]],
} ],
'_SECURITY_TOKEN_PROXY_DATA' : [ 0x18, {
'Length' : [ 0x0, ['unsigned long']],
'ProxyClass' : [ 0x4, ['Enumeration', dict(target = 'long', choices = {0: 'ProxyFull', 1: 'ProxyService', 2: 'ProxyTree', 3: 'ProxyDirectory'})]],
'PathInfo' : [ 0x8, ['_UNICODE_STRING']],
'ContainerMask' : [ 0x10, ['unsigned long']],
'ObjectMask' : [ 0x14, ['unsigned long']],
} ],
'_HANDLE_TABLE_ENTRY' : [ 0x8, {
'Object' : [ 0x0, ['pointer', ['void']]],
'ObAttributes' : [ 0x0, ['unsigned long']],
'InfoTable' : [ 0x0, ['pointer', ['_HANDLE_TABLE_ENTRY_INFO']]],
'Value' : [ 0x0, ['unsigned long']],
'GrantedAccess' : [ 0x4, ['unsigned long']],
'GrantedAccessIndex' : [ 0x4, ['unsigned short']],
'CreatorBackTraceIndex' : [ 0x6, ['unsigned short']],
'NextFreeTableEntry' : [ 0x4, ['long']],
} ],
'_HEAP_USERDATA_HEADER' : [ 0x10, {
'SFreeListEntry' : [ 0x0, ['_SINGLE_LIST_ENTRY']],
'SubSegment' : [ 0x0, ['pointer', ['_HEAP_SUBSEGMENT']]],
'HeapHandle' : [ 0x4, ['pointer', ['void']]],
'SizeIndex' : [ 0x8, ['unsigned long']],
'Signature' : [ 0xc, ['unsigned long']],
} ],
'_LPCP_PORT_OBJECT' : [ 0xa4, {
'ConnectionPort' : [ 0x0, ['pointer', ['_LPCP_PORT_OBJECT']]],
'ConnectedPort' : [ 0x4, ['pointer', ['_LPCP_PORT_OBJECT']]],
'MsgQueue' : [ 0x8, ['_LPCP_PORT_QUEUE']],
'Creator' : [ 0x18, ['_CLIENT_ID']],
'ClientSectionBase' : [ 0x20, ['pointer', ['void']]],
'ServerSectionBase' : [ 0x24, ['pointer', ['void']]],
'PortContext' : [ 0x28, ['pointer', ['void']]],
'ClientThread' : [ 0x2c, ['pointer', ['_ETHREAD']]],
'SecurityQos' : [ 0x30, ['_SECURITY_QUALITY_OF_SERVICE']],
'StaticSecurity' : [ 0x3c, ['_SECURITY_CLIENT_CONTEXT']],
'LpcReplyChainHead' : [ 0x78, ['_LIST_ENTRY']],
'LpcDataInfoChainHead' : [ 0x80, ['_LIST_ENTRY']],
'ServerProcess' : [ 0x88, ['pointer', ['_EPROCESS']]],
'MappingProcess' : [ 0x88, ['pointer', ['_EPROCESS']]],
'MaxMessageLength' : [ 0x8c, ['unsigned short']],
'MaxConnectionInfoLength' : [ 0x8e, ['unsigned short']],
'Flags' : [ 0x90, ['unsigned long']],
'WaitEvent' : [ 0x94, ['_KEVENT']],
} ],
'PCI_POWER_STATE' : [ 0x40, {
'CurrentSystemState' : [ 0x0, ['Enumeration', dict(target = 'long', choices = {0: 'PowerSystemUnspecified', 1: 'PowerSystemWorking', 2: 'PowerSystemSleeping1', 3: 'PowerSystemSleeping2', 4: 'PowerSystemSleeping3', 5: 'PowerSystemHibernate', 6: 'PowerSystemShutdown', 7: 'PowerSystemMaximum'})]],
'CurrentDeviceState' : [ 0x4, ['Enumeration', dict(target = 'long', choices = {0: 'PowerDeviceUnspecified', 1: 'PowerDeviceD0', 2: 'PowerDeviceD1', 3: 'PowerDeviceD2', 4: 'PowerDeviceD3', 5: 'PowerDeviceMaximum'})]],
'SystemWakeLevel' : [ 0x8, ['Enumeration', dict(target = 'long', choices = {0: 'PowerSystemUnspecified', 1: 'PowerSystemWorking', 2: 'PowerSystemSleeping1', 3: 'PowerSystemSleeping2', 4: 'PowerSystemSleeping3', 5: 'PowerSystemHibernate', 6: 'PowerSystemShutdown', 7: 'PowerSystemMaximum'})]],
'DeviceWakeLevel' : [ 0xc, ['Enumeration', dict(target = 'long', choices = {0: 'PowerDeviceUnspecified', 1: 'PowerDeviceD0', 2: 'PowerDeviceD1', 3: 'PowerDeviceD2', 4: 'PowerDeviceD3', 5: 'PowerDeviceMaximum'})]],
'SystemStateMapping' : [ 0x10, ['array', -28, ['Enumeration', dict(target = 'long', choices = {0: 'PowerDeviceUnspecified', 1: 'PowerDeviceD0', 2: 'PowerDeviceD1', 3: 'PowerDeviceD2', 4: 'PowerDeviceD3', 5: 'PowerDeviceMaximum'})]]],
'WaitWakeIrp' : [ 0x2c, ['pointer', ['_IRP']]],
'SavedCancelRoutine' : [ 0x30, ['pointer', ['void']]],
'Paging' : [ 0x34, ['long']],
'Hibernate' : [ 0x38, ['long']],
'CrashDump' : [ 0x3c, ['long']],
} ],
'_POOL_HACKER' : [ 0x28, {
'Header' : [ 0x0, ['_POOL_HEADER']],
'Contents' : [ 0x8, ['array', 8, ['unsigned long']]],
} ],
'_CM_INDEX_HINT_BLOCK' : [ 0x8, {
'Count' : [ 0x0, ['unsigned long']],
'HashKey' : [ 0x4, ['array', 1, ['unsigned long']]],
} ],
'_TOKEN_CONTROL' : [ 0x28, {
'TokenId' : [ 0x0, ['_LUID']],
'AuthenticationId' : [ 0x8, ['_LUID']],
'ModifiedId' : [ 0x10, ['_LUID']],
'TokenSource' : [ 0x18, ['_TOKEN_SOURCE']],
} ],
'__unnamed_1803' : [ 0x10, {
'SecurityContext' : [ 0x0, ['pointer', ['_IO_SECURITY_CONTEXT']]],
'Options' : [ 0x4, ['unsigned long']],
'FileAttributes' : [ 0x8, ['unsigned short']],
'ShareAccess' : [ 0xa, ['unsigned short']],
'EaLength' : [ 0xc, ['unsigned long']],
} ],
'__unnamed_1807' : [ 0x10, {
'SecurityContext' : [ 0x0, ['pointer', ['_IO_SECURITY_CONTEXT']]],
'Options' : [ 0x4, ['unsigned long']],
'Reserved' : [ 0x8, ['unsigned short']],
'ShareAccess' : [ 0xa, ['unsigned short']],
'Parameters' : [ 0xc, ['pointer', ['_NAMED_PIPE_CREATE_PARAMETERS']]],
} ],
'__unnamed_180b' : [ 0x10, {
'SecurityContext' : [ 0x0, ['pointer', ['_IO_SECURITY_CONTEXT']]],
'Options' : [ 0x4, ['unsigned long']],
'Reserved' : [ 0x8, ['unsigned short']],
'ShareAccess' : [ 0xa, ['unsigned short']],
'Parameters' : [ 0xc, ['pointer', ['_MAILSLOT_CREATE_PARAMETERS']]],
} ],
'__unnamed_180d' : [ 0x10, {
'Length' : [ 0x0, ['unsigned long']],
'Key' : [ 0x4, ['unsigned long']],
'ByteOffset' : [ 0x8, ['_LARGE_INTEGER']],
} ],
'__unnamed_1812' : [ 0x10, {
'Length' : [ 0x0, ['unsigned long']],
'FileName' : [ 0x4, ['pointer', ['_STRING']]],
'FileInformationClass' : [ 0x8, ['Enumeration', dict(target = 'long', choices = {1: 'FileDirectoryInformation', 2: 'FileFullDirectoryInformation', 3: 'FileBothDirectoryInformation', 4: 'FileBasicInformation', 5: 'FileStandardInformation', 6: 'FileInternalInformation', 7: 'FileEaInformation', 8: 'FileAccessInformation', 9: 'FileNameInformation', 10: 'FileRenameInformation', 11: 'FileLinkInformation', 12: 'FileNamesInformation', 13: 'FileDispositionInformation', 14: 'FilePositionInformation', 15: 'FileFullEaInformation', 16: 'FileModeInformation', 17: 'FileAlignmentInformation', 18: 'FileAllInformation', 19: 'FileAllocationInformation', 20: 'FileEndOfFileInformation', 21: 'FileAlternateNameInformation', 22: 'FileStreamInformation', 23: 'FilePipeInformation', 24: 'FilePipeLocalInformation', 25: 'FilePipeRemoteInformation', 26: 'FileMailslotQueryInformation', 27: 'FileMailslotSetInformation', 28: 'FileCompressionInformation', 29: 'FileObjectIdInformation', 30: 'FileCompletionInformation', 31: 'FileMoveClusterInformation', 32: 'FileQuotaInformation', 33: 'FileReparsePointInformation', 34: 'FileNetworkOpenInformation', 35: 'FileAttributeTagInformation', 36: 'FileTrackingInformation', 37: 'FileIdBothDirectoryInformation', 38: 'FileIdFullDirectoryInformation', 39: 'FileValidDataLengthInformation', 40: 'FileShortNameInformation', 41: 'FileMaximumInformation'})]],
'FileIndex' : [ 0xc, ['unsigned long']],
} ],
'__unnamed_1814' : [ 0x8, {
'Length' : [ 0x0, ['unsigned long']],
'CompletionFilter' : [ 0x4, ['unsigned long']],
} ],
'__unnamed_1816' : [ 0x8, {
'Length' : [ 0x0, ['unsigned long']],
'FileInformationClass' : [ 0x4, ['Enumeration', dict(target = 'long', choices = {1: 'FileDirectoryInformation', 2: 'FileFullDirectoryInformation', 3: 'FileBothDirectoryInformation', 4: 'FileBasicInformation', 5: 'FileStandardInformation', 6: 'FileInternalInformation', 7: 'FileEaInformation', 8: 'FileAccessInformation', 9: 'FileNameInformation', 10: 'FileRenameInformation', 11: 'FileLinkInformation', 12: 'FileNamesInformation', 13: 'FileDispositionInformation', 14: 'FilePositionInformation', 15: 'FileFullEaInformation', 16: 'FileModeInformation', 17: 'FileAlignmentInformation', 18: 'FileAllInformation', 19: 'FileAllocationInformation', 20: 'FileEndOfFileInformation', 21: 'FileAlternateNameInformation', 22: 'FileStreamInformation', 23: 'FilePipeInformation', 24: 'FilePipeLocalInformation', 25: 'FilePipeRemoteInformation', 26: 'FileMailslotQueryInformation', 27: 'FileMailslotSetInformation', 28: 'FileCompressionInformation', 29: 'FileObjectIdInformation', 30: 'FileCompletionInformation', 31: 'FileMoveClusterInformation', 32: 'FileQuotaInformation', 33: 'FileReparsePointInformation', 34: 'FileNetworkOpenInformation', 35: 'FileAttributeTagInformation', 36: 'FileTrackingInformation', 37: 'FileIdBothDirectoryInformation', 38: 'FileIdFullDirectoryInformation', 39: 'FileValidDataLengthInformation', 40: 'FileShortNameInformation', 41: 'FileMaximumInformation'})]],
} ],
'__unnamed_1818' : [ 0x10, {
'Length' : [ 0x0, ['unsigned long']],
'FileInformationClass' : [ 0x4, ['Enumeration', dict(target = 'long', choices = {1: 'FileDirectoryInformation', 2: 'FileFullDirectoryInformation', 3: 'FileBothDirectoryInformation', 4: 'FileBasicInformation', 5: 'FileStandardInformation', 6: 'FileInternalInformation', 7: 'FileEaInformation', 8: 'FileAccessInformation', 9: 'FileNameInformation', 10: 'FileRenameInformation', 11: 'FileLinkInformation', 12: 'FileNamesInformation', 13: 'FileDispositionInformation', 14: 'FilePositionInformation', 15: 'FileFullEaInformation', 16: 'FileModeInformation', 17: 'FileAlignmentInformation', 18: 'FileAllInformation', 19: 'FileAllocationInformation', 20: 'FileEndOfFileInformation', 21: 'FileAlternateNameInformation', 22: 'FileStreamInformation', 23: 'FilePipeInformation', 24: 'FilePipeLocalInformation', 25: 'FilePipeRemoteInformation', 26: 'FileMailslotQueryInformation', 27: 'FileMailslotSetInformation', 28: 'FileCompressionInformation', 29: 'FileObjectIdInformation', 30: 'FileCompletionInformation', 31: 'FileMoveClusterInformation', 32: 'FileQuotaInformation', 33: 'FileReparsePointInformation', 34: 'FileNetworkOpenInformation', 35: 'FileAttributeTagInformation', 36: 'FileTrackingInformation', 37: 'FileIdBothDirectoryInformation', 38: 'FileIdFullDirectoryInformation', 39: 'FileValidDataLengthInformation', 40: 'FileShortNameInformation', 41: 'FileMaximumInformation'})]],
'FileObject' : [ 0x8, ['pointer', ['_FILE_OBJECT']]],
'ReplaceIfExists' : [ 0xc, ['unsigned char']],
'AdvanceOnly' : [ 0xd, ['unsigned char']],
'ClusterCount' : [ 0xc, ['unsigned long']],
'DeleteHandle' : [ 0xc, ['pointer', ['void']]],
} ],
'__unnamed_181a' : [ 0x10, {
'Length' : [ 0x0, ['unsigned long']],
'EaList' : [ 0x4, ['pointer', ['void']]],
'EaListLength' : [ 0x8, ['unsigned long']],
'EaIndex' : [ 0xc, ['unsigned long']],
} ],
'__unnamed_181c' : [ 0x4, {
'Length' : [ 0x0, ['unsigned long']],
} ],
'__unnamed_1820' : [ 0x8, {
'Length' : [ 0x0, ['unsigned long']],
'FsInformationClass' : [ 0x4, ['Enumeration', dict(target = 'long', choices = {1: 'FileFsVolumeInformation', 2: 'FileFsLabelInformation', 3: 'FileFsSizeInformation', 4: 'FileFsDeviceInformation', 5: 'FileFsAttributeInformation', 6: 'FileFsControlInformation', 7: 'FileFsFullSizeInformation', 8: 'FileFsObjectIdInformation', 9: 'FileFsDriverPathInformation', 10: 'FileFsMaximumInformation'})]],
} ],
'__unnamed_1822' : [ 0x10, {
'OutputBufferLength' : [ 0x0, ['unsigned long']],
'InputBufferLength' : [ 0x4, ['unsigned long']],
'FsControlCode' : [ 0x8, ['unsigned long']],
'Type3InputBuffer' : [ 0xc, ['pointer', ['void']]],
} ],
'__unnamed_1824' : [ 0x10, {
'Length' : [ 0x0, ['pointer', ['_LARGE_INTEGER']]],
'Key' : [ 0x4, ['unsigned long']],
'ByteOffset' : [ 0x8, ['_LARGE_INTEGER']],
} ],
'__unnamed_1826' : [ 0x10, {
'OutputBufferLength' : [ 0x0, ['unsigned long']],
'InputBufferLength' : [ 0x4, ['unsigned long']],
'IoControlCode' : [ 0x8, ['unsigned long']],
'Type3InputBuffer' : [ 0xc, ['pointer', ['void']]],
} ],
'__unnamed_1828' : [ 0x8, {
'SecurityInformation' : [ 0x0, ['unsigned long']],
'Length' : [ 0x4, ['unsigned long']],
} ],
'__unnamed_182a' : [ 0x8, {
'SecurityInformation' : [ 0x0, ['unsigned long']],
'SecurityDescriptor' : [ 0x4, ['pointer', ['void']]],
} ],
'__unnamed_182c' : [ 0x8, {
'Vpb' : [ 0x0, ['pointer', ['_VPB']]],
'DeviceObject' : [ 0x4, ['pointer', ['_DEVICE_OBJECT']]],
} ],
'__unnamed_1830' : [ 0x4, {
'Srb' : [ 0x0, ['pointer', ['_SCSI_REQUEST_BLOCK']]],
} ],
'__unnamed_1834' : [ 0x10, {
'Length' : [ 0x0, ['unsigned long']],
'StartSid' : [ 0x4, ['pointer', ['void']]],
'SidList' : [ 0x8, ['pointer', ['_FILE_GET_QUOTA_INFORMATION']]],
'SidListLength' : [ 0xc, ['unsigned long']],
} ],
'__unnamed_1838' : [ 0x4, {
'Type' : [ 0x0, ['Enumeration', dict(target = 'long', choices = {0: 'BusRelations', 1: 'EjectionRelations', 2: 'PowerRelations', 3: 'RemovalRelations', 4: 'TargetDeviceRelation', 5: 'SingleBusRelations'})]],
} ],
'__unnamed_183a' : [ 0x10, {
'InterfaceType' : [ 0x0, ['pointer', ['_GUID']]],
'Size' : [ 0x4, ['unsigned short']],
'Version' : [ 0x6, ['unsigned short']],
'Interface' : [ 0x8, ['pointer', ['_INTERFACE']]],
'InterfaceSpecificData' : [ 0xc, ['pointer', ['void']]],
} ],
'__unnamed_183e' : [ 0x4, {
'Capabilities' : [ 0x0, ['pointer', ['_DEVICE_CAPABILITIES']]],
} ],
'__unnamed_1840' : [ 0x4, {
'IoResourceRequirementList' : [ 0x0, ['pointer', ['_IO_RESOURCE_REQUIREMENTS_LIST']]],
} ],
'__unnamed_1842' : [ 0x10, {
'WhichSpace' : [ 0x0, ['unsigned long']],
'Buffer' : [ 0x4, ['pointer', ['void']]],
'Offset' : [ 0x8, ['unsigned long']],
'Length' : [ 0xc, ['unsigned long']],
} ],
'__unnamed_1844' : [ 0x1, {
'Lock' : [ 0x0, ['unsigned char']],
} ],
'__unnamed_1848' : [ 0x4, {
'IdType' : [ 0x0, ['Enumeration', dict(target = 'long', choices = {0: 'BusQueryDeviceID', 1: 'BusQueryHardwareIDs', 2: 'BusQueryCompatibleIDs', 3: 'BusQueryInstanceID', 4: 'BusQueryDeviceSerialNumber'})]],
} ],
'__unnamed_184c' : [ 0x8, {
'DeviceTextType' : [ 0x0, ['Enumeration', dict(target = 'long', choices = {0: 'DeviceTextDescription', 1: 'DeviceTextLocationInformation'})]],
'LocaleId' : [ 0x4, ['unsigned long']],
} ],
'__unnamed_1850' : [ 0x8, {
'InPath' : [ 0x0, ['unsigned char']],
'Reserved' : [ 0x1, ['array', 3, ['unsigned char']]],
'Type' : [ 0x4, ['Enumeration', dict(target = 'long', choices = {0: 'DeviceUsageTypeUndefined', 1: 'DeviceUsageTypePaging', 2: 'DeviceUsageTypeHibernation', 3: 'DeviceUsageTypeDumpFile'})]],
} ],
'__unnamed_1852' : [ 0x4, {
'PowerState' : [ 0x0, ['Enumeration', dict(target = 'long', choices = {0: 'PowerSystemUnspecified', 1: 'PowerSystemWorking', 2: 'PowerSystemSleeping1', 3: 'PowerSystemSleeping2', 4: 'PowerSystemSleeping3', 5: 'PowerSystemHibernate', 6: 'PowerSystemShutdown', 7: 'PowerSystemMaximum'})]],
} ],
'__unnamed_1856' : [ 0x4, {
'PowerSequence' : [ 0x0, ['pointer', ['_POWER_SEQUENCE']]],
} ],
'__unnamed_185a' : [ 0x10, {
'SystemContext' : [ 0x0, ['unsigned long']],
'Type' : [ 0x4, ['Enumeration', dict(target = 'long', choices = {0: 'SystemPowerState', 1: 'DevicePowerState'})]],
'State' : [ 0x8, ['_POWER_STATE']],
'ShutdownType' : [ 0xc, ['Enumeration', dict(target = 'long', choices = {0: 'PowerActionNone', 1: 'PowerActionReserved', 2: 'PowerActionSleep', 3: 'PowerActionHibernate', 4: 'PowerActionShutdown', 5: 'PowerActionShutdownReset', 6: 'PowerActionShutdownOff', 7: 'PowerActionWarmEject'})]],
} ],
'__unnamed_185c' : [ 0x8, {
'AllocatedResources' : [ 0x0, ['pointer', ['_CM_RESOURCE_LIST']]],
'AllocatedResourcesTranslated' : [ 0x4, ['pointer', ['_CM_RESOURCE_LIST']]],
} ],
'__unnamed_185e' : [ 0x10, {
'ProviderId' : [ 0x0, ['unsigned long']],
'DataPath' : [ 0x4, ['pointer', ['void']]],
'BufferSize' : [ 0x8, ['unsigned long']],
'Buffer' : [ 0xc, ['pointer', ['void']]],
} ],
'__unnamed_1860' : [ 0x10, {
'Argument1' : [ 0x0, ['pointer', ['void']]],
'Argument2' : [ 0x4, ['pointer', ['void']]],
'Argument3' : [ 0x8, ['pointer', ['void']]],
'Argument4' : [ 0xc, ['pointer', ['void']]],
} ],
'__unnamed_1862' : [ 0x10, {
'Create' : [ 0x0, ['__unnamed_1803']],
'CreatePipe' : [ 0x0, ['__unnamed_1807']],
'CreateMailslot' : [ 0x0, ['__unnamed_180b']],
'Read' : [ 0x0, ['__unnamed_180d']],
'Write' : [ 0x0, ['__unnamed_180d']],
'QueryDirectory' : [ 0x0, ['__unnamed_1812']],
'NotifyDirectory' : [ 0x0, ['__unnamed_1814']],
'QueryFile' : [ 0x0, ['__unnamed_1816']],
'SetFile' : [ 0x0, ['__unnamed_1818']],
'QueryEa' : [ 0x0, ['__unnamed_181a']],
'SetEa' : [ 0x0, ['__unnamed_181c']],
'QueryVolume' : [ 0x0, ['__unnamed_1820']],
'SetVolume' : [ 0x0, ['__unnamed_1820']],
'FileSystemControl' : [ 0x0, ['__unnamed_1822']],
'LockControl' : [ 0x0, ['__unnamed_1824']],
'DeviceIoControl' : [ 0x0, ['__unnamed_1826']],
'QuerySecurity' : [ 0x0, ['__unnamed_1828']],
'SetSecurity' : [ 0x0, ['__unnamed_182a']],
'MountVolume' : [ 0x0, ['__unnamed_182c']],
'VerifyVolume' : [ 0x0, ['__unnamed_182c']],
'Scsi' : [ 0x0, ['__unnamed_1830']],
'QueryQuota' : [ 0x0, ['__unnamed_1834']],
'SetQuota' : [ 0x0, ['__unnamed_181c']],
'QueryDeviceRelations' : [ 0x0, ['__unnamed_1838']],
'QueryInterface' : [ 0x0, ['__unnamed_183a']],
'DeviceCapabilities' : [ 0x0, ['__unnamed_183e']],
'FilterResourceRequirements' : [ 0x0, ['__unnamed_1840']],
'ReadWriteConfig' : [ 0x0, ['__unnamed_1842']],
'SetLock' : [ 0x0, ['__unnamed_1844']],
'QueryId' : [ 0x0, ['__unnamed_1848']],
'QueryDeviceText' : [ 0x0, ['__unnamed_184c']],
'UsageNotification' : [ 0x0, ['__unnamed_1850']],
'WaitWake' : [ 0x0, ['__unnamed_1852']],
'PowerSequence' : [ 0x0, ['__unnamed_1856']],
'Power' : [ 0x0, ['__unnamed_185a']],
'StartDevice' : [ 0x0, ['__unnamed_185c']],
'WMI' : [ 0x0, ['__unnamed_185e']],
'Others' : [ 0x0, ['__unnamed_1860']],
} ],
'_IO_STACK_LOCATION' : [ 0x24, {
'MajorFunction' : [ 0x0, ['unsigned char']],
'MinorFunction' : [ 0x1, ['unsigned char']],
'Flags' : [ 0x2, ['unsigned char']],
'Control' : [ 0x3, ['unsigned char']],
'Parameters' : [ 0x4, ['__unnamed_1862']],
'DeviceObject' : [ 0x14, ['pointer', ['_DEVICE_OBJECT']]],
'FileObject' : [ 0x18, ['pointer', ['_FILE_OBJECT']]],
'CompletionRoutine' : [ 0x1c, ['pointer', ['void']]],
'Context' : [ 0x20, ['pointer', ['void']]],
} ],
'__unnamed_1869' : [ 0x18, {
'Length' : [ 0x0, ['unsigned long']],
'Alignment' : [ 0x4, ['unsigned long']],
'MinimumAddress' : [ 0x8, ['_LARGE_INTEGER']],
'MaximumAddress' : [ 0x10, ['_LARGE_INTEGER']],
} ],
'__unnamed_186b' : [ 0x8, {
'MinimumVector' : [ 0x0, ['unsigned long']],
'MaximumVector' : [ 0x4, ['unsigned long']],
} ],
'__unnamed_186d' : [ 0x8, {
'MinimumChannel' : [ 0x0, ['unsigned long']],
'MaximumChannel' : [ 0x4, ['unsigned long']],
} ],
'__unnamed_186f' : [ 0x10, {
'Length' : [ 0x0, ['unsigned long']],
'MinBusNumber' : [ 0x4, ['unsigned long']],
'MaxBusNumber' : [ 0x8, ['unsigned long']],
'Reserved' : [ 0xc, ['unsigned long']],
} ],
'__unnamed_1871' : [ 0xc, {
'Priority' : [ 0x0, ['unsigned long']],
'Reserved1' : [ 0x4, ['unsigned long']],
'Reserved2' : [ 0x8, ['unsigned long']],
} ],
'__unnamed_1873' : [ 0x18, {
'Port' : [ 0x0, ['__unnamed_1869']],
'Memory' : [ 0x0, ['__unnamed_1869']],
'Interrupt' : [ 0x0, ['__unnamed_186b']],
'Dma' : [ 0x0, ['__unnamed_186d']],
'Generic' : [ 0x0, ['__unnamed_1869']],
'DevicePrivate' : [ 0x0, ['__unnamed_1557']],
'BusNumber' : [ 0x0, ['__unnamed_186f']],
'ConfigData' : [ 0x0, ['__unnamed_1871']],
} ],
'_IO_RESOURCE_DESCRIPTOR' : [ 0x20, {
'Option' : [ 0x0, ['unsigned char']],
'Type' : [ 0x1, ['unsigned char']],
'ShareDisposition' : [ 0x2, ['unsigned char']],
'Spare1' : [ 0x3, ['unsigned char']],
'Flags' : [ 0x4, ['unsigned short']],
'Spare2' : [ 0x6, ['unsigned short']],
'u' : [ 0x8, ['__unnamed_1873']],
} ],
'_LUID_AND_ATTRIBUTES' : [ 0xc, {
'Luid' : [ 0x0, ['_LUID']],
'Attributes' : [ 0x8, ['unsigned long']],
} ],
'_MI_VERIFIER_POOL_HEADER' : [ 0x8, {
'ListIndex' : [ 0x0, ['unsigned long']],
'Verifier' : [ 0x4, ['pointer', ['_MI_VERIFIER_DRIVER_ENTRY']]],
} ],
'_CM_KEY_BODY' : [ 0x44, {
'Type' : [ 0x0, ['unsigned long']],
'KeyControlBlock' : [ 0x4, ['pointer', ['_CM_KEY_CONTROL_BLOCK']]],
'NotifyBlock' : [ 0x8, ['pointer', ['_CM_NOTIFY_BLOCK']]],
'ProcessID' : [ 0xc, ['pointer', ['void']]],
'Callers' : [ 0x10, ['unsigned long']],
'CallerAddress' : [ 0x14, ['array', 10, ['pointer', ['void']]]],
'KeyBodyList' : [ 0x3c, ['_LIST_ENTRY']],
} ],
'__unnamed_1884' : [ 0x4, {
'DataLength' : [ 0x0, ['short']],
'TotalLength' : [ 0x2, ['short']],
} ],
'__unnamed_1886' : [ 0x4, {
's1' : [ 0x0, ['__unnamed_1884']],
'Length' : [ 0x0, ['unsigned long']],
} ],
'__unnamed_1888' : [ 0x4, {
'Type' : [ 0x0, ['short']],
'DataInfoOffset' : [ 0x2, ['short']],
} ],
'__unnamed_188a' : [ 0x4, {
's2' : [ 0x0, ['__unnamed_1888']],
'ZeroInit' : [ 0x0, ['unsigned long']],
} ],
'_PORT_MESSAGE' : [ 0x18, {
'u1' : [ 0x0, ['__unnamed_1886']],
'u2' : [ 0x4, ['__unnamed_188a']],
'ClientId' : [ 0x8, ['_CLIENT_ID']],
'DoNotUseThisField' : [ 0x8, ['double']],
'MessageId' : [ 0x10, ['unsigned long']],
'ClientViewSize' : [ 0x14, ['unsigned long']],
'CallbackId' : [ 0x14, ['unsigned long']],
} ],
'_DBGKD_ANY_CONTROL_SET' : [ 0x1c, {
'X86ControlSet' : [ 0x0, ['_X86_DBGKD_CONTROL_SET']],
'AlphaControlSet' : [ 0x0, ['unsigned long']],
'IA64ControlSet' : [ 0x0, ['_IA64_DBGKD_CONTROL_SET']],
'Amd64ControlSet' : [ 0x0, ['_AMD64_DBGKD_CONTROL_SET']],
} ],
'_ARBITER_ORDERING_LIST' : [ 0x8, {
'Count' : [ 0x0, ['unsigned short']],
'Maximum' : [ 0x2, ['unsigned short']],
'Orderings' : [ 0x4, ['pointer', ['_ARBITER_ORDERING']]],
} ],
'_HBASE_BLOCK' : [ 0x1000, {
'Signature' : [ 0x0, ['unsigned long']],
'Sequence1' : [ 0x4, ['unsigned long']],
'Sequence2' : [ 0x8, ['unsigned long']],
'TimeStamp' : [ 0xc, ['_LARGE_INTEGER']],
'Major' : [ 0x14, ['unsigned long']],
'Minor' : [ 0x18, ['unsigned long']],
'Type' : [ 0x1c, ['unsigned long']],
'Format' : [ 0x20, ['unsigned long']],
'RootCell' : [ 0x24, ['unsigned long']],
'Length' : [ 0x28, ['unsigned long']],
'Cluster' : [ 0x2c, ['unsigned long']],
'FileName' : [ 0x30, ['array', 64, ['unsigned char']]],
'Reserved1' : [ 0x70, ['array', 99, ['unsigned long']]],
'CheckSum' : [ 0x1fc, ['unsigned long']],
'Reserved2' : [ 0x200, ['array', 894, ['unsigned long']]],
'BootType' : [ 0xff8, ['unsigned long']],
'BootRecover' : [ 0xffc, ['unsigned long']],
} ],
'_DUAL' : [ 0xdc, {
'Length' : [ 0x0, ['unsigned long']],
'Map' : [ 0x4, ['pointer', ['_HMAP_DIRECTORY']]],
'SmallDir' : [ 0x8, ['pointer', ['_HMAP_TABLE']]],
'Guard' : [ 0xc, ['unsigned long']],
'FreeDisplay' : [ 0x10, ['array', 24, ['_RTL_BITMAP']]],
'FreeSummary' : [ 0xd0, ['unsigned long']],
'FreeBins' : [ 0xd4, ['_LIST_ENTRY']],
} ],
'_COMPRESSED_DATA_INFO' : [ 0xc, {
'CompressionFormatAndEngine' : [ 0x0, ['unsigned short']],
'CompressionUnitShift' : [ 0x2, ['unsigned char']],
'ChunkShift' : [ 0x3, ['unsigned char']],
'ClusterShift' : [ 0x4, ['unsigned char']],
'Reserved' : [ 0x5, ['unsigned char']],
'NumberOfChunks' : [ 0x6, ['unsigned short']],
'CompressedChunkSizes' : [ 0x8, ['array', 1, ['unsigned long']]],
} ],
'_LPCP_PORT_QUEUE' : [ 0x10, {
'NonPagedPortQueue' : [ 0x0, ['pointer', ['_LPCP_NONPAGED_PORT_QUEUE']]],
'Semaphore' : [ 0x4, ['pointer', ['_KSEMAPHORE']]],
'ReceiveHead' : [ 0x8, ['_LIST_ENTRY']],
} ],
'_INITIAL_PRIVILEGE_SET' : [ 0x2c, {
'PrivilegeCount' : [ 0x0, ['unsigned long']],
'Control' : [ 0x4, ['unsigned long']],
'Privilege' : [ 0x8, ['array', 3, ['_LUID_AND_ATTRIBUTES']]],
} ],
'_POP_HIBER_CONTEXT' : [ 0xe0, {
'WriteToFile' : [ 0x0, ['unsigned char']],
'ReserveLoaderMemory' : [ 0x1, ['unsigned char']],
'ReserveFreeMemory' : [ 0x2, ['unsigned char']],
'VerifyOnWake' : [ 0x3, ['unsigned char']],
'Reset' : [ 0x4, ['unsigned char']],
'HiberFlags' : [ 0x5, ['unsigned char']],
'LinkFile' : [ 0x6, ['unsigned char']],
'LinkFileHandle' : [ 0x8, ['pointer', ['void']]],
'Lock' : [ 0xc, ['unsigned long']],
'MapFrozen' : [ 0x10, ['unsigned char']],
'MemoryMap' : [ 0x14, ['_RTL_BITMAP']],
'ClonedRanges' : [ 0x1c, ['_LIST_ENTRY']],
'ClonedRangeCount' : [ 0x24, ['unsigned long']],
'NextCloneRange' : [ 0x28, ['pointer', ['_LIST_ENTRY']]],
'NextPreserve' : [ 0x2c, ['unsigned long']],
'LoaderMdl' : [ 0x30, ['pointer', ['_MDL']]],
'Clones' : [ 0x34, ['pointer', ['_MDL']]],
'NextClone' : [ 0x38, ['pointer', ['unsigned char']]],
'NoClones' : [ 0x3c, ['unsigned long']],
'Spares' : [ 0x40, ['pointer', ['_MDL']]],
'PagesOut' : [ 0x48, ['unsigned long long']],
'IoPage' : [ 0x50, ['pointer', ['void']]],
'CurrentMcb' : [ 0x54, ['pointer', ['void']]],
'DumpStack' : [ 0x58, ['pointer', ['_DUMP_STACK_CONTEXT']]],
'WakeState' : [ 0x5c, ['pointer', ['_KPROCESSOR_STATE']]],
'NoRanges' : [ 0x60, ['unsigned long']],
'HiberVa' : [ 0x64, ['unsigned long']],
'HiberPte' : [ 0x68, ['_LARGE_INTEGER']],
'Status' : [ 0x70, ['long']],
'MemoryImage' : [ 0x74, ['pointer', ['PO_MEMORY_IMAGE']]],
'TableHead' : [ 0x78, ['pointer', ['_PO_MEMORY_RANGE_ARRAY']]],
'CompressionWorkspace' : [ 0x7c, ['pointer', ['unsigned char']]],
'CompressedWriteBuffer' : [ 0x80, ['pointer', ['unsigned char']]],
'PerformanceStats' : [ 0x84, ['pointer', ['unsigned long']]],
'CompressionBlock' : [ 0x88, ['pointer', ['void']]],
'DmaIO' : [ 0x8c, ['pointer', ['void']]],
'TemporaryHeap' : [ 0x90, ['pointer', ['void']]],
'PerfInfo' : [ 0x98, ['_PO_HIBER_PERF']],
} ],
'_TEB_ACTIVE_FRAME' : [ 0xc, {
'Flags' : [ 0x0, ['unsigned long']],
'Previous' : [ 0x4, ['pointer', ['_TEB_ACTIVE_FRAME']]],
'Context' : [ 0x8, ['pointer', ['_TEB_ACTIVE_FRAME_CONTEXT']]],
} ],
'_FILE_GET_QUOTA_INFORMATION' : [ 0x14, {
'NextEntryOffset' : [ 0x0, ['unsigned long']],
'SidLength' : [ 0x4, ['unsigned long']],
'Sid' : [ 0x8, ['_SID']],
} ],
'_MMADDRESS_LIST' : [ 0x8, {
'StartVpn' : [ 0x0, ['unsigned long']],
'EndVpn' : [ 0x4, ['unsigned long']],
} ],
'_OBJECT_NAME_INFORMATION' : [ 0x8, {
'Name' : [ 0x0, ['_UNICODE_STRING']],
} ],
'_SECURITY_QUALITY_OF_SERVICE' : [ 0xc, {
'Length' : [ 0x0, ['unsigned long']],
'ImpersonationLevel' : [ 0x4, ['Enumeration', dict(target = 'long', choices = {0: 'SecurityAnonymous', 1: 'SecurityIdentification', 2: 'SecurityImpersonation', 3: 'SecurityDelegation'})]],
'ContextTrackingMode' : [ 0x8, ['unsigned char']],
'EffectiveOnly' : [ 0x9, ['unsigned char']],
} ],
'_DUMP_STACK_CONTEXT' : [ 0xb0, {
'Init' : [ 0x0, ['_DUMP_INITIALIZATION_CONTEXT']],
'PartitionOffset' : [ 0x70, ['_LARGE_INTEGER']],
'DumpPointers' : [ 0x78, ['pointer', ['void']]],
'PointersLength' : [ 0x7c, ['unsigned long']],
'ModulePrefix' : [ 0x80, ['pointer', ['unsigned short']]],
'DriverList' : [ 0x84, ['_LIST_ENTRY']],
'InitMsg' : [ 0x8c, ['_STRING']],
'ProgMsg' : [ 0x94, ['_STRING']],
'DoneMsg' : [ 0x9c, ['_STRING']],
'FileObject' : [ 0xa4, ['pointer', ['void']]],
'UsageType' : [ 0xa8, ['Enumeration', dict(target = 'long', choices = {0: 'DeviceUsageTypeUndefined', 1: 'DeviceUsageTypePaging', 2: 'DeviceUsageTypeHibernation', 3: 'DeviceUsageTypeDumpFile'})]],
} ],
'_FILE_STANDARD_INFORMATION' : [ 0x18, {
'AllocationSize' : [ 0x0, ['_LARGE_INTEGER']],
'EndOfFile' : [ 0x8, ['_LARGE_INTEGER']],
'NumberOfLinks' : [ 0x10, ['unsigned long']],
'DeletePending' : [ 0x14, ['unsigned char']],
'Directory' : [ 0x15, ['unsigned char']],
} ],
'_POP_SHUTDOWN_BUG_CHECK' : [ 0x14, {
'Code' : [ 0x0, ['unsigned long']],
'Parameter1' : [ 0x4, ['unsigned long']],
'Parameter2' : [ 0x8, ['unsigned long']],
'Parameter3' : [ 0xc, ['unsigned long']],
'Parameter4' : [ 0x10, ['unsigned long']],
} ],
'__unnamed_18c9' : [ 0x4, {
'DeviceNumber' : [ 0x0, ['BitField', dict(start_bit = 0, end_bit = 5, native_type='unsigned long')]],
'FunctionNumber' : [ 0x0, ['BitField', dict(start_bit = 5, end_bit = 8, native_type='unsigned long')]],
'Reserved' : [ 0x0, ['BitField', dict(start_bit = 8, end_bit = 32, native_type='unsigned long')]],
} ],
'__unnamed_18cb' : [ 0x4, {
'bits' : [ 0x0, ['__unnamed_18c9']],
'AsULONG' : [ 0x0, ['unsigned long']],
} ],
'_PCI_SLOT_NUMBER' : [ 0x4, {
'u' : [ 0x0, ['__unnamed_18cb']],
} ],
'_Wx86ThreadState' : [ 0xc, {
'CallBx86Eip' : [ 0x0, ['pointer', ['unsigned long']]],
'DeallocationCpu' : [ 0x4, ['pointer', ['void']]],
'UseKnownWx86Dll' : [ 0x8, ['unsigned char']],
'OleStubInvoked' : [ 0x9, ['unsigned char']],
} ],
'_DRIVER_EXTENSION' : [ 0x1c, {
'DriverObject' : [ 0x0, ['pointer', ['_DRIVER_OBJECT']]],
'AddDevice' : [ 0x4, ['pointer', ['void']]],
'Count' : [ 0x8, ['unsigned long']],
'ServiceKeyName' : [ 0xc, ['_UNICODE_STRING']],
'ClientDriverExtension' : [ 0x14, ['pointer', ['_IO_CLIENT_EXTENSION']]],
'FsFilterCallbacks' : [ 0x18, ['pointer', ['_FS_FILTER_CALLBACKS']]],
} ],
'_CM_NOTIFY_BLOCK' : [ 0x2c, {
'HiveList' : [ 0x0, ['_LIST_ENTRY']],
'PostList' : [ 0x8, ['_LIST_ENTRY']],
'KeyControlBlock' : [ 0x10, ['pointer', ['_CM_KEY_CONTROL_BLOCK']]],
'KeyBody' : [ 0x14, ['pointer', ['_CM_KEY_BODY']]],
'Filter' : [ 0x18, ['BitField', dict(start_bit = 0, end_bit = 30, native_type='unsigned long')]],
'WatchTree' : [ 0x18, ['BitField', dict(start_bit = 30, end_bit = 31, native_type='unsigned long')]],
'NotifyPending' : [ 0x18, ['BitField', dict(start_bit = 31, end_bit = 32, native_type='unsigned long')]],
'SubjectContext' : [ 0x1c, ['_SECURITY_SUBJECT_CONTEXT']],
} ],
'_SID' : [ 0xc, {
'Revision' : [ 0x0, ['unsigned char']],
'SubAuthorityCount' : [ 0x1, ['unsigned char']],
'IdentifierAuthority' : [ 0x2, ['_SID_IDENTIFIER_AUTHORITY']],
'SubAuthority' : [ 0x8, ['array', 1, ['unsigned long']]],
} ],
'_RTL_HANDLE_TABLE_ENTRY' : [ 0x4, {
'Flags' : [ 0x0, ['unsigned long']],
'NextFree' : [ 0x0, ['pointer', ['_RTL_HANDLE_TABLE_ENTRY']]],
} ],
'_INTERFACE' : [ 0x10, {
'Size' : [ 0x0, ['unsigned short']],
'Version' : [ 0x2, ['unsigned short']],
'Context' : [ 0x4, ['pointer', ['void']]],
'InterfaceReference' : [ 0x8, ['pointer', ['void']]],
'InterfaceDereference' : [ 0xc, ['pointer', ['void']]],
} ],
'_SUPPORTED_RANGES' : [ 0xa0, {
'Version' : [ 0x0, ['unsigned short']],
'Sorted' : [ 0x2, ['unsigned char']],
'Reserved' : [ 0x3, ['unsigned char']],
'NoIO' : [ 0x4, ['unsigned long']],
'IO' : [ 0x8, ['_SUPPORTED_RANGE']],
'NoMemory' : [ 0x28, ['unsigned long']],
'Memory' : [ 0x30, ['_SUPPORTED_RANGE']],
'NoPrefetchMemory' : [ 0x50, ['unsigned long']],
'PrefetchMemory' : [ 0x58, ['_SUPPORTED_RANGE']],
'NoDma' : [ 0x78, ['unsigned long']],
'Dma' : [ 0x80, ['_SUPPORTED_RANGE']],
} ],
'_SID_IDENTIFIER_AUTHORITY' : [ 0x6, {
'Value' : [ 0x0, ['array', 6, ['unsigned char']]],
} ],
'_SECURITY_DESCRIPTOR_RELATIVE' : [ 0x14, {
'Revision' : [ 0x0, ['unsigned char']],
'Sbz1' : [ 0x1, ['unsigned char']],
'Control' : [ 0x2, ['unsigned short']],
'Owner' : [ 0x4, ['unsigned long']],
'Group' : [ 0x8, ['unsigned long']],
'Sacl' : [ 0xc, ['unsigned long']],
'Dacl' : [ 0x10, ['unsigned long']],
} ],
'_PM_SUPPORT' : [ 0x1, {
'Rsvd2' : [ 0x0, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned char')]],
'D1' : [ 0x0, ['BitField', dict(start_bit = 1, end_bit = 2, native_type='unsigned char')]],
'D2' : [ 0x0, ['BitField', dict(start_bit = 2, end_bit = 3, native_type='unsigned char')]],
'PMED0' : [ 0x0, ['BitField', dict(start_bit = 3, end_bit = 4, native_type='unsigned char')]],
'PMED1' : [ 0x0, ['BitField', dict(start_bit = 4, end_bit = 5, native_type='unsigned char')]],
'PMED2' : [ 0x0, ['BitField', dict(start_bit = 5, end_bit = 6, native_type='unsigned char')]],
'PMED3Hot' : [ 0x0, ['BitField', dict(start_bit = 6, end_bit = 7, native_type='unsigned char')]],
'PMED3Cold' : [ 0x0, ['BitField', dict(start_bit = 7, end_bit = 8, native_type='unsigned char')]],
} ],
'__unnamed_18f1' : [ 0xc, {
'ArbitrationList' : [ 0x0, ['pointer', ['_LIST_ENTRY']]],
'AllocateFromCount' : [ 0x4, ['unsigned long']],
'AllocateFrom' : [ 0x8, ['pointer', ['_CM_PARTIAL_RESOURCE_DESCRIPTOR']]],
} ],
'__unnamed_18f3' : [ 0x4, {
'ArbitrationList' : [ 0x0, ['pointer', ['_LIST_ENTRY']]],
} ],
'__unnamed_18f7' : [ 0x4, {
'AllocatedResources' : [ 0x0, ['pointer', ['pointer', ['_CM_PARTIAL_RESOURCE_LIST']]]],
} ],
'__unnamed_18f9' : [ 0x10, {
'PhysicalDeviceObject' : [ 0x0, ['pointer', ['_DEVICE_OBJECT']]],
'ConflictingResource' : [ 0x4, ['pointer', ['_IO_RESOURCE_DESCRIPTOR']]],
'ConflictCount' : [ 0x8, ['pointer', ['unsigned long']]],
'Conflicts' : [ 0xc, ['pointer', ['pointer', ['_ARBITER_CONFLICT_INFO']]]],
} ],
'__unnamed_18fb' : [ 0x4, {
'ReserveDevice' : [ 0x0, ['pointer', ['_DEVICE_OBJECT']]],
} ],
'__unnamed_18fd' : [ 0x10, {
'TestAllocation' : [ 0x0, ['__unnamed_18f1']],
'RetestAllocation' : [ 0x0, ['__unnamed_18f1']],
'BootAllocation' : [ 0x0, ['__unnamed_18f3']],
'QueryAllocatedResources' : [ 0x0, ['__unnamed_18f7']],
'QueryConflict' : [ 0x0, ['__unnamed_18f9']],
'QueryArbitrate' : [ 0x0, ['__unnamed_18f3']],
'AddReserved' : [ 0x0, ['__unnamed_18fb']],
} ],
'_ARBITER_PARAMETERS' : [ 0x10, {
'Parameters' : [ 0x0, ['__unnamed_18fd']],
} ],
'_SECURITY_TOKEN_AUDIT_DATA' : [ 0xc, {
'Length' : [ 0x0, ['unsigned long']],
'GrantMask' : [ 0x4, ['unsigned long']],
'DenyMask' : [ 0x8, ['unsigned long']],
} ],
'_HANDLE_TABLE_ENTRY_INFO' : [ 0x4, {
'AuditMask' : [ 0x0, ['unsigned long']],
} ],
'_POWER_SEQUENCE' : [ 0xc, {
'SequenceD1' : [ 0x0, ['unsigned long']],
'SequenceD2' : [ 0x4, ['unsigned long']],
'SequenceD3' : [ 0x8, ['unsigned long']],
} ],
'_IMAGE_DATA_DIRECTORY' : [ 0x8, {
'VirtualAddress' : [ 0x0, ['unsigned long']],
'Size' : [ 0x4, ['unsigned long']],
} ],
'_MI_VERIFIER_DRIVER_ENTRY' : [ 0x60, {
'Links' : [ 0x0, ['_LIST_ENTRY']],
'Loads' : [ 0x8, ['unsigned long']],
'Unloads' : [ 0xc, ['unsigned long']],
'BaseName' : [ 0x10, ['_UNICODE_STRING']],
'StartAddress' : [ 0x18, ['pointer', ['void']]],
'EndAddress' : [ 0x1c, ['pointer', ['void']]],
'Flags' : [ 0x20, ['unsigned long']],
'Signature' : [ 0x24, ['unsigned long']],
'Reserved' : [ 0x28, ['unsigned long']],
'VerifierPoolLock' : [ 0x2c, ['unsigned long']],
'PoolHash' : [ 0x30, ['pointer', ['_VI_POOL_ENTRY']]],
'PoolHashSize' : [ 0x34, ['unsigned long']],
'PoolHashFree' : [ 0x38, ['unsigned long']],
'PoolHashReserved' : [ 0x3c, ['unsigned long']],
'CurrentPagedPoolAllocations' : [ 0x40, ['unsigned long']],
'CurrentNonPagedPoolAllocations' : [ 0x44, ['unsigned long']],
'PeakPagedPoolAllocations' : [ 0x48, ['unsigned long']],
'PeakNonPagedPoolAllocations' : [ 0x4c, ['unsigned long']],
'PagedBytes' : [ 0x50, ['unsigned long']],
'NonPagedBytes' : [ 0x54, ['unsigned long']],
'PeakPagedBytes' : [ 0x58, ['unsigned long']],
'PeakNonPagedBytes' : [ 0x5c, ['unsigned long']],
} ],
'_CURDIR' : [ 0xc, {
'DosPath' : [ 0x0, ['_UNICODE_STRING']],
'Handle' : [ 0x8, ['pointer', ['void']]],
} ],
'_MMMOD_WRITER_LISTHEAD' : [ 0x18, {
'ListHead' : [ 0x0, ['_LIST_ENTRY']],
'Event' : [ 0x8, ['_KEVENT']],
} ],
'_PO_HIBER_PERF' : [ 0x48, {
'IoTicks' : [ 0x0, ['unsigned long long']],
'InitTicks' : [ 0x8, ['unsigned long long']],
'CopyTicks' : [ 0x10, ['unsigned long long']],
'StartCount' : [ 0x18, ['unsigned long long']],
'ElapsedTime' : [ 0x20, ['unsigned long']],
'IoTime' : [ 0x24, ['unsigned long']],
'CopyTime' : [ 0x28, ['unsigned long']],
'InitTime' : [ 0x2c, ['unsigned long']],
'PagesWritten' : [ 0x30, ['unsigned long']],
'PagesProcessed' : [ 0x34, ['unsigned long']],
'BytesCopied' : [ 0x38, ['unsigned long']],
'DumpCount' : [ 0x3c, ['unsigned long']],
'FileRuns' : [ 0x40, ['unsigned long']],
} ],
'_GDI_TEB_BATCH' : [ 0x4e0, {
'Offset' : [ 0x0, ['unsigned long']],
'HDC' : [ 0x4, ['unsigned long']],
'Buffer' : [ 0x8, ['array', 310, ['unsigned long']]],
} ],
'PO_MEMORY_IMAGE' : [ 0xa8, {
'Signature' : [ 0x0, ['unsigned long']],
'Version' : [ 0x4, ['unsigned long']],
'CheckSum' : [ 0x8, ['unsigned long']],
'LengthSelf' : [ 0xc, ['unsigned long']],
'PageSelf' : [ 0x10, ['unsigned long']],
'PageSize' : [ 0x14, ['unsigned long']],
'ImageType' : [ 0x18, ['unsigned long']],
'SystemTime' : [ 0x20, ['_LARGE_INTEGER']],
'InterruptTime' : [ 0x28, ['unsigned long long']],
'FeatureFlags' : [ 0x30, ['unsigned long']],
'HiberFlags' : [ 0x34, ['unsigned char']],
'spare' : [ 0x35, ['array', 3, ['unsigned char']]],
'NoHiberPtes' : [ 0x38, ['unsigned long']],
'HiberVa' : [ 0x3c, ['unsigned long']],
'HiberPte' : [ 0x40, ['_LARGE_INTEGER']],
'NoFreePages' : [ 0x48, ['unsigned long']],
'FreeMapCheck' : [ 0x4c, ['unsigned long']],
'WakeCheck' : [ 0x50, ['unsigned long']],
'TotalPages' : [ 0x54, ['unsigned long']],
'FirstTablePage' : [ 0x58, ['unsigned long']],
'LastFilePage' : [ 0x5c, ['unsigned long']],
'PerfInfo' : [ 0x60, ['_PO_HIBER_PERF']],
} ],
'BATTERY_REPORTING_SCALE' : [ 0x8, {
'Granularity' : [ 0x0, ['unsigned long']],
'Capacity' : [ 0x4, ['unsigned long']],
} ],
'_KDEVICE_QUEUE_ENTRY' : [ 0x10, {
'DeviceListEntry' : [ 0x0, ['_LIST_ENTRY']],
'SortKey' : [ 0x8, ['unsigned long']],
'Inserted' : [ 0xc, ['unsigned char']],
} ],
'_DEVICE_CAPABILITIES' : [ 0x40, {
'Size' : [ 0x0, ['unsigned short']],
'Version' : [ 0x2, ['unsigned short']],
'DeviceD1' : [ 0x4, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned long')]],
'DeviceD2' : [ 0x4, ['BitField', dict(start_bit = 1, end_bit = 2, native_type='unsigned long')]],
'LockSupported' : [ 0x4, ['BitField', dict(start_bit = 2, end_bit = 3, native_type='unsigned long')]],
'EjectSupported' : [ 0x4, ['BitField', dict(start_bit = 3, end_bit = 4, native_type='unsigned long')]],
'Removable' : [ 0x4, ['BitField', dict(start_bit = 4, end_bit = 5, native_type='unsigned long')]],
'DockDevice' : [ 0x4, ['BitField', dict(start_bit = 5, end_bit = 6, native_type='unsigned long')]],
'UniqueID' : [ 0x4, ['BitField', dict(start_bit = 6, end_bit = 7, native_type='unsigned long')]],
'SilentInstall' : [ 0x4, ['BitField', dict(start_bit = 7, end_bit = 8, native_type='unsigned long')]],
'RawDeviceOK' : [ 0x4, ['BitField', dict(start_bit = 8, end_bit = 9, native_type='unsigned long')]],
'SurpriseRemovalOK' : [ 0x4, ['BitField', dict(start_bit = 9, end_bit = 10, native_type='unsigned long')]],
'WakeFromD0' : [ 0x4, ['BitField', dict(start_bit = 10, end_bit = 11, native_type='unsigned long')]],
'WakeFromD1' : [ 0x4, ['BitField', dict(start_bit = 11, end_bit = 12, native_type='unsigned long')]],
'WakeFromD2' : [ 0x4, ['BitField', dict(start_bit = 12, end_bit = 13, native_type='unsigned long')]],
'WakeFromD3' : [ 0x4, ['BitField', dict(start_bit = 13, end_bit = 14, native_type='unsigned long')]],
'HardwareDisabled' : [ 0x4, ['BitField', dict(start_bit = 14, end_bit = 15, native_type='unsigned long')]],
'NonDynamic' : [ 0x4, ['BitField', dict(start_bit = 15, end_bit = 16, native_type='unsigned long')]],
'WarmEjectSupported' : [ 0x4, ['BitField', dict(start_bit = 16, end_bit = 17, native_type='unsigned long')]],
'NoDisplayInUI' : [ 0x4, ['BitField', dict(start_bit = 17, end_bit = 18, native_type='unsigned long')]],
'Reserved' : [ 0x4, ['BitField', dict(start_bit = 18, end_bit = 32, native_type='unsigned long')]],
'Address' : [ 0x8, ['unsigned long']],
'UINumber' : [ 0xc, ['unsigned long']],
'DeviceState' : [ 0x10, ['array', -28, ['Enumeration', dict(target = 'long', choices = {0: 'PowerDeviceUnspecified', 1: 'PowerDeviceD0', 2: 'PowerDeviceD1', 3: 'PowerDeviceD2', 4: 'PowerDeviceD3', 5: 'PowerDeviceMaximum'})]]],
'SystemWake' : [ 0x2c, ['Enumeration', dict(target = 'long', choices = {0: 'PowerSystemUnspecified', 1: 'PowerSystemWorking', 2: 'PowerSystemSleeping1', 3: 'PowerSystemSleeping2', 4: 'PowerSystemSleeping3', 5: 'PowerSystemHibernate', 6: 'PowerSystemShutdown', 7: 'PowerSystemMaximum'})]],
'DeviceWake' : [ 0x30, ['Enumeration', dict(target = 'long', choices = {0: 'PowerDeviceUnspecified', 1: 'PowerDeviceD0', 2: 'PowerDeviceD1', 3: 'PowerDeviceD2', 4: 'PowerDeviceD3', 5: 'PowerDeviceMaximum'})]],
'D1Latency' : [ 0x34, ['unsigned long']],
'D2Latency' : [ 0x38, ['unsigned long']],
'D3Latency' : [ 0x3c, ['unsigned long']],
} ],
'_TEB_ACTIVE_FRAME_CONTEXT' : [ 0x8, {
'Flags' : [ 0x0, ['unsigned long']],
'FrameName' : [ 0x4, ['pointer', ['unsigned char']]],
} ],
'_RTL_RANGE_LIST' : [ 0x14, {
'ListHead' : [ 0x0, ['_LIST_ENTRY']],
'Flags' : [ 0x8, ['unsigned long']],
'Count' : [ 0xc, ['unsigned long']],
'Stamp' : [ 0x10, ['unsigned long']],
} ],
'_RTL_CRITICAL_SECTION_DEBUG' : [ 0x20, {
'Type' : [ 0x0, ['unsigned short']],
'CreatorBackTraceIndex' : [ 0x2, ['unsigned short']],
'CriticalSection' : [ 0x4, ['pointer', ['_RTL_CRITICAL_SECTION']]],
'ProcessLocksList' : [ 0x8, ['_LIST_ENTRY']],
'EntryCount' : [ 0x10, ['unsigned long']],
'ContentionCount' : [ 0x14, ['unsigned long']],
'Spare' : [ 0x18, ['array', 2, ['unsigned long']]],
} ],
'_SEP_AUDIT_POLICY' : [ 0x8, {
'PolicyElements' : [ 0x0, ['_SEP_AUDIT_POLICY_CATEGORIES']],
'PolicyOverlay' : [ 0x0, ['_SEP_AUDIT_POLICY_OVERLAY']],
'Overlay' : [ 0x0, ['unsigned long long']],
} ],
'__unnamed_192c' : [ 0x14, {
'ClassGuid' : [ 0x0, ['_GUID']],
'SymbolicLinkName' : [ 0x10, ['array', 1, ['unsigned short']]],
} ],
'__unnamed_192e' : [ 0x2, {
'DeviceIds' : [ 0x0, ['array', 1, ['unsigned short']]],
} ],
'__unnamed_1930' : [ 0x2, {
'DeviceId' : [ 0x0, ['array', 1, ['unsigned short']]],
} ],
'__unnamed_1932' : [ 0x8, {
'NotificationStructure' : [ 0x0, ['pointer', ['void']]],
'DeviceIds' : [ 0x4, ['array', 1, ['unsigned short']]],
} ],
'__unnamed_1934' : [ 0x4, {
'Notification' : [ 0x0, ['pointer', ['void']]],
} ],
'__unnamed_1936' : [ 0x8, {
'NotificationCode' : [ 0x0, ['unsigned long']],
'NotificationData' : [ 0x4, ['unsigned long']],
} ],
'__unnamed_1938' : [ 0x8, {
'VetoType' : [ 0x0, ['Enumeration', dict(target = 'long', choices = {0: 'PNP_VetoTypeUnknown', 1: 'PNP_VetoLegacyDevice', 2: 'PNP_VetoPendingClose', 3: 'PNP_VetoWindowsApp', 4: 'PNP_VetoWindowsService', 5: 'PNP_VetoOutstandingOpen', 6: 'PNP_VetoDevice', 7: 'PNP_VetoDriver', 8: 'PNP_VetoIllegalDeviceRequest', 9: 'PNP_VetoInsufficientPower', 10: 'PNP_VetoNonDisableable', 11: 'PNP_VetoLegacyDriver', 12: 'PNP_VetoInsufficientRights'})]],
'DeviceIdVetoNameBuffer' : [ 0x4, ['array', 1, ['unsigned short']]],
} ],
'__unnamed_193a' : [ 0x10, {
'BlockedDriverGuid' : [ 0x0, ['_GUID']],
} ],
'__unnamed_193c' : [ 0x14, {
'DeviceClass' : [ 0x0, ['__unnamed_192c']],
'TargetDevice' : [ 0x0, ['__unnamed_192e']],
'InstallDevice' : [ 0x0, ['__unnamed_1930']],
'CustomNotification' : [ 0x0, ['__unnamed_1932']],
'ProfileNotification' : [ 0x0, ['__unnamed_1934']],
'PowerNotification' : [ 0x0, ['__unnamed_1936']],
'VetoNotification' : [ 0x0, ['__unnamed_1938']],
'BlockedDriverNotification' : [ 0x0, ['__unnamed_193a']],
} ],
'_PLUGPLAY_EVENT_BLOCK' : [ 0x38, {
'EventGuid' : [ 0x0, ['_GUID']],
'EventCategory' : [ 0x10, ['Enumeration', dict(target = 'long', choices = {0: 'HardwareProfileChangeEvent', 1: 'TargetDeviceChangeEvent', 2: 'DeviceClassChangeEvent', 3: 'CustomDeviceEvent', 4: 'DeviceInstallEvent', 5: 'DeviceArrivalEvent', 6: 'PowerEvent', 7: 'VetoEvent', 8: 'BlockedDriverEvent', 9: 'MaxPlugEventCategory'})]],
'Result' : [ 0x14, ['pointer', ['unsigned long']]],
'Flags' : [ 0x18, ['unsigned long']],
'TotalSize' : [ 0x1c, ['unsigned long']],
'DeviceObject' : [ 0x20, ['pointer', ['void']]],
'u' : [ 0x24, ['__unnamed_193c']],
} ],
'_CACHED_CHILD_LIST' : [ 0x8, {
'Count' : [ 0x0, ['unsigned long']],
'ValueList' : [ 0x4, ['unsigned long']],
'RealKcb' : [ 0x4, ['pointer', ['_CM_KEY_CONTROL_BLOCK']]],
} ],
'__unnamed_1942' : [ 0x10, {
'PageNo' : [ 0x0, ['unsigned long']],
'StartPage' : [ 0x4, ['unsigned long']],
'EndPage' : [ 0x8, ['unsigned long']],
'CheckSum' : [ 0xc, ['unsigned long']],
} ],
'__unnamed_1944' : [ 0x10, {
'Next' : [ 0x0, ['pointer', ['_PO_MEMORY_RANGE_ARRAY']]],
'NextTable' : [ 0x4, ['unsigned long']],
'CheckSum' : [ 0x8, ['unsigned long']],
'EntryCount' : [ 0xc, ['unsigned long']],
} ],
'_PO_MEMORY_RANGE_ARRAY' : [ 0x10, {
'Range' : [ 0x0, ['__unnamed_1942']],
'Link' : [ 0x0, ['__unnamed_1944']],
} ],
'__unnamed_1956' : [ 0x8, {
'Signature' : [ 0x0, ['unsigned long']],
'CheckSum' : [ 0x4, ['unsigned long']],
} ],
'__unnamed_1958' : [ 0x10, {
'DiskId' : [ 0x0, ['_GUID']],
} ],
'__unnamed_195a' : [ 0x10, {
'Mbr' : [ 0x0, ['__unnamed_1956']],
'Gpt' : [ 0x0, ['__unnamed_1958']],
} ],
'_DUMP_INITIALIZATION_CONTEXT' : [ 0x70, {
'Length' : [ 0x0, ['unsigned long']],
'Reserved' : [ 0x4, ['unsigned long']],
'MemoryBlock' : [ 0x8, ['pointer', ['void']]],
'CommonBuffer' : [ 0xc, ['array', 2, ['pointer', ['void']]]],
'PhysicalAddress' : [ 0x18, ['array', 2, ['_LARGE_INTEGER']]],
'StallRoutine' : [ 0x28, ['pointer', ['void']]],
'OpenRoutine' : [ 0x2c, ['pointer', ['void']]],
'WriteRoutine' : [ 0x30, ['pointer', ['void']]],
'FinishRoutine' : [ 0x34, ['pointer', ['void']]],
'AdapterObject' : [ 0x38, ['pointer', ['_ADAPTER_OBJECT']]],
'MappedRegisterBase' : [ 0x3c, ['pointer', ['void']]],
'PortConfiguration' : [ 0x40, ['pointer', ['void']]],
'CrashDump' : [ 0x44, ['unsigned char']],
'MaximumTransferSize' : [ 0x48, ['unsigned long']],
'CommonBufferSize' : [ 0x4c, ['unsigned long']],
'TargetAddress' : [ 0x50, ['pointer', ['void']]],
'WritePendingRoutine' : [ 0x54, ['pointer', ['void']]],
'PartitionStyle' : [ 0x58, ['unsigned long']],
'DiskInfo' : [ 0x5c, ['__unnamed_195a']],
} ],
'_IO_CLIENT_EXTENSION' : [ 0x8, {
'NextExtension' : [ 0x0, ['pointer', ['_IO_CLIENT_EXTENSION']]],
'ClientIdentificationAddress' : [ 0x4, ['pointer', ['void']]],
} ],
'_KEXECUTE_OPTIONS' : [ 0x1, {
'ExecuteDisable' : [ 0x0, ['BitField', dict(start_bit = 0, end_bit = 1, native_type='unsigned char')]],
'ExecuteEnable' : [ 0x0, ['BitField', dict(start_bit = 1, end_bit = 2, native_type='unsigned char')]],
'DisableThunkEmulation' : [ 0x0, ['BitField', dict(start_bit = 2, end_bit = 3, native_type='unsigned char')]],
'Permanent' : [ 0x0, ['BitField', dict(start_bit = 3, end_bit = 4, native_type='unsigned char')]],
'ExecuteDispatchEnable' : [ 0x0, ['BitField', dict(start_bit = 4, end_bit = 5, native_type='unsigned char')]],
'ImageDispatchEnable' : [ 0x0, ['BitField', dict(start_bit = 5, end_bit = 6, native_type='unsigned char')]],
'Spare' : [ 0x0, ['BitField', dict(start_bit = 6, end_bit = 8, native_type='unsigned char')]],
} ],
'_CM_NAME_HASH' : [ 0xc, {
'ConvKey' : [ 0x0, ['unsigned long']],
'NextHash' : [ 0x4, ['pointer', ['_CM_NAME_HASH']]],
'NameLength' : [ 0x8, ['unsigned short']],
'Name' : [ 0xa, ['array', 1, ['unsigned short']]],
} ],
'_ARBITER_ALLOCATION_STATE' : [ 0x38, {
'Start' : [ 0x0, ['unsigned long long']],
'End' : [ 0x8, ['unsigned long long']],
'CurrentMinimum' : [ 0x10, ['unsigned long long']],
'CurrentMaximum' : [ 0x18, ['unsigned long long']],
'Entry' : [ 0x20, ['pointer', ['_ARBITER_LIST_ENTRY']]],
'CurrentAlternative' : [ 0x24, ['pointer', ['_ARBITER_ALTERNATIVE']]],
'AlternativeCount' : [ 0x28, ['unsigned long']],
'Alternatives' : [ 0x2c, ['pointer', ['_ARBITER_ALTERNATIVE']]],
'Flags' : [ 0x30, ['unsigned short']],
'RangeAttributes' : [ 0x32, ['unsigned char']],
'RangeAvailableAttributes' : [ 0x33, ['unsigned char']],
'WorkSpace' : [ 0x34, ['unsigned long']],
} ],
'_SEP_AUDIT_POLICY_OVERLAY' : [ 0x8, {
'PolicyBits' : [ 0x0, ['BitField', dict(start_bit = 0, end_bit = 36, native_type='unsigned long long')]],
'SetBit' : [ 0x0, ['BitField', dict(start_bit = 36, end_bit = 37, native_type='unsigned long long')]],
} ],
'_PCI_HEADER_TYPE_0' : [ 0x30, {
'BaseAddresses' : [ 0x0, ['array', 6, ['unsigned long']]],
'CIS' : [ 0x18, ['unsigned long']],
'SubVendorID' : [ 0x1c, ['unsigned short']],
'SubSystemID' : [ 0x1e, ['unsigned short']],
'ROMBaseAddress' : [ 0x20, ['unsigned long']],
'CapabilitiesPtr' : [ 0x24, ['unsigned char']],
'Reserved1' : [ 0x25, ['array', 3, ['unsigned char']]],
'Reserved2' : [ 0x28, ['unsigned long']],
'InterruptLine' : [ 0x2c, ['unsigned char']],
'InterruptPin' : [ 0x2d, ['unsigned char']],
'MinimumGrant' : [ 0x2e, ['unsigned char']],
'MaximumLatency' : [ 0x2f, ['unsigned char']],
} ],
'_PO_DEVICE_NOTIFY_ORDER' : [ 0x248, {
'DevNodeSequence' : [ 0x0, ['unsigned long']],
'WarmEjectPdoPointer' : [ 0x4, ['pointer', ['pointer', ['_DEVICE_OBJECT']]]],
'OrderLevel' : [ 0x8, ['array', 8, ['_PO_NOTIFY_ORDER_LEVEL']]],
} ],
'_FS_FILTER_CALLBACKS' : [ 0x38, {
'SizeOfFsFilterCallbacks' : [ 0x0, ['unsigned long']],
'Reserved' : [ 0x4, ['unsigned long']],
'PreAcquireForSectionSynchronization' : [ 0x8, ['pointer', ['void']]],
'PostAcquireForSectionSynchronization' : [ 0xc, ['pointer', ['void']]],
'PreReleaseForSectionSynchronization' : [ 0x10, ['pointer', ['void']]],
'PostReleaseForSectionSynchronization' : [ 0x14, ['pointer', ['void']]],
'PreAcquireForCcFlush' : [ 0x18, ['pointer', ['void']]],
'PostAcquireForCcFlush' : [ 0x1c, ['pointer', ['void']]],
'PreReleaseForCcFlush' : [ 0x20, ['pointer', ['void']]],
'PostReleaseForCcFlush' : [ 0x24, ['pointer', ['void']]],
'PreAcquireForModifiedPageWriter' : [ 0x28, ['pointer', ['void']]],
'PostAcquireForModifiedPageWriter' : [ 0x2c, ['pointer', ['void']]],
'PreReleaseForModifiedPageWriter' : [ 0x30, ['pointer', ['void']]],
'PostReleaseForModifiedPageWriter' : [ 0x34, ['pointer', ['void']]],
} ],
'_IA64_DBGKD_CONTROL_SET' : [ 0x14, {
'Continue' : [ 0x0, ['unsigned long']],
'CurrentSymbolStart' : [ 0x4, ['unsigned long long']],
'CurrentSymbolEnd' : [ 0xc, ['unsigned long long']],
} ],
'_DEVICE_MAP' : [ 0x30, {
'DosDevicesDirectory' : [ 0x0, ['pointer', ['_OBJECT_DIRECTORY']]],
'GlobalDosDevicesDirectory' : [ 0x4, ['pointer', ['_OBJECT_DIRECTORY']]],
'ReferenceCount' : [ 0x8, ['unsigned long']],
'DriveMap' : [ 0xc, ['unsigned long']],
'DriveType' : [ 0x10, ['array', 32, ['unsigned char']]],
} ],
'_u' : [ 0x50, {
'KeyNode' : [ 0x0, ['_CM_KEY_NODE']],
'KeyValue' : [ 0x0, ['_CM_KEY_VALUE']],
'KeySecurity' : [ 0x0, ['_CM_KEY_SECURITY']],
'KeyIndex' : [ 0x0, ['_CM_KEY_INDEX']],
'ValueData' : [ 0x0, ['_CM_BIG_DATA']],
'KeyList' : [ 0x0, ['array', 1, ['unsigned long']]],
'KeyString' : [ 0x0, ['array', 1, ['unsigned short']]],
} ],
'_ARBITER_CONFLICT_INFO' : [ 0x18, {
'OwningObject' : [ 0x0, ['pointer', ['_DEVICE_OBJECT']]],
'Start' : [ 0x8, ['unsigned long long']],
'End' : [ 0x10, ['unsigned long long']],
} ],
'_PO_NOTIFY_ORDER_LEVEL' : [ 0x48, {
'LevelReady' : [ 0x0, ['_KEVENT']],
'DeviceCount' : [ 0x10, ['unsigned long']],
'ActiveCount' : [ 0x14, ['unsigned long']],
'WaitSleep' : [ 0x18, ['_LIST_ENTRY']],
'ReadySleep' : [ 0x20, ['_LIST_ENTRY']],
'Pending' : [ 0x28, ['_LIST_ENTRY']],
'Complete' : [ 0x30, ['_LIST_ENTRY']],
'ReadyS0' : [ 0x38, ['_LIST_ENTRY']],
'WaitS0' : [ 0x40, ['_LIST_ENTRY']],
} ],
'__unnamed_198f' : [ 0x8, {
'Base' : [ 0x0, ['unsigned long']],
'Limit' : [ 0x4, ['unsigned long']],
} ],
'_PCI_HEADER_TYPE_2' : [ 0x30, {
'SocketRegistersBaseAddress' : [ 0x0, ['unsigned long']],
'CapabilitiesPtr' : [ 0x4, ['unsigned char']],
'Reserved' : [ 0x5, ['unsigned char']],
'SecondaryStatus' : [ 0x6, ['unsigned short']],
'PrimaryBus' : [ 0x8, ['unsigned char']],
'SecondaryBus' : [ 0x9, ['unsigned char']],
'SubordinateBus' : [ 0xa, ['unsigned char']],
'SecondaryLatency' : [ 0xb, ['unsigned char']],
'Range' : [ 0xc, ['array', 4, ['__unnamed_198f']]],
'InterruptLine' : [ 0x2c, ['unsigned char']],
'InterruptPin' : [ 0x2d, ['unsigned char']],
'BridgeControl' : [ 0x2e, ['unsigned short']],
} ],
'_SEP_AUDIT_POLICY_CATEGORIES' : [ 0x8, {
'System' : [ 0x0, ['BitField', dict(start_bit = 0, end_bit = 4, native_type='unsigned long')]],
'Logon' : [ 0x0, ['BitField', dict(start_bit = 4, end_bit = 8, native_type='unsigned long')]],
'ObjectAccess' : [ 0x0, ['BitField', dict(start_bit = 8, end_bit = 12, native_type='unsigned long')]],
'PrivilegeUse' : [ 0x0, ['BitField', dict(start_bit = 12, end_bit = 16, native_type='unsigned long')]],
'DetailedTracking' : [ 0x0, ['BitField', dict(start_bit = 16, end_bit = 20, native_type='unsigned long')]],
'PolicyChange' : [ 0x0, ['BitField', dict(start_bit = 20, end_bit = 24, native_type='unsigned long')]],
'AccountManagement' : [ 0x0, ['BitField', dict(start_bit = 24, end_bit = 28, native_type='unsigned long')]],
'DirectoryServiceAccess' : [ 0x0, ['BitField', dict(start_bit = 28, end_bit = 32, native_type='unsigned long')]],
'AccountLogon' : [ 0x4, ['BitField', dict(start_bit = 0, end_bit = 4, native_type='unsigned long')]],
} ],
'_CM_KEY_VALUE' : [ 0x18, {
'Signature' : [ 0x0, ['unsigned short']],
'NameLength' : [ 0x2, ['unsigned short']],
'DataLength' : [ 0x4, ['unsigned long']],
'Data' : [ 0x8, ['unsigned long']],
'Type' : [ 0xc, ['unsigned long']],
'Flags' : [ 0x10, ['unsigned short']],
'Spare' : [ 0x12, ['unsigned short']],
'Name' : [ 0x14, ['array', 1, ['unsigned short']]],
} ],
'_AMD64_DBGKD_CONTROL_SET' : [ 0x1c, {
'TraceFlag' : [ 0x0, ['unsigned long']],
'Dr7' : [ 0x4, ['unsigned long long']],
'CurrentSymbolStart' : [ 0xc, ['unsigned long long']],
'CurrentSymbolEnd' : [ 0x14, ['unsigned long long']],
} ],
'_FS_FILTER_CALLBACK_DATA' : [ 0x24, {
'SizeOfFsFilterCallbackData' : [ 0x0, ['unsigned long']],
'Operation' : [ 0x4, ['unsigned char']],
'Reserved' : [ 0x5, ['unsigned char']],
'DeviceObject' : [ 0x8, ['pointer', ['_DEVICE_OBJECT']]],
'FileObject' : [ 0xc, ['pointer', ['_FILE_OBJECT']]],
'Parameters' : [ 0x10, ['_FS_FILTER_PARAMETERS']],
} ],
'_OBJECT_DIRECTORY_ENTRY' : [ 0x8, {
'ChainLink' : [ 0x0, ['pointer', ['_OBJECT_DIRECTORY_ENTRY']]],
'Object' : [ 0x4, ['pointer', ['void']]],
} ],
'_VI_POOL_ENTRY' : [ 0x10, {
'InUse' : [ 0x0, ['_VI_POOL_ENTRY_INUSE']],
'FreeListNext' : [ 0x0, ['unsigned long']],
} ],
'_POP_DEVICE_POWER_IRP' : [ 0x2c, {
'Free' : [ 0x0, ['_SINGLE_LIST_ENTRY']],
'Irp' : [ 0x4, ['pointer', ['_IRP']]],
'Notify' : [ 0x8, ['pointer', ['_PO_DEVICE_NOTIFY']]],
'Pending' : [ 0xc, ['_LIST_ENTRY']],
'Complete' : [ 0x14, ['_LIST_ENTRY']],
'Abort' : [ 0x1c, ['_LIST_ENTRY']],
'Failed' : [ 0x24, ['_LIST_ENTRY']],
} ],
'_RTL_RANGE' : [ 0x20, {
'Start' : [ 0x0, ['unsigned long long']],
'End' : [ 0x8, ['unsigned long long']],
'UserData' : [ 0x10, ['pointer', ['void']]],
'Owner' : [ 0x14, ['pointer', ['void']]],
'Attributes' : [ 0x18, ['unsigned char']],
'Flags' : [ 0x19, ['unsigned char']],
} ],
'_PCI_HEADER_TYPE_1' : [ 0x30, {
'BaseAddresses' : [ 0x0, ['array', 2, ['unsigned long']]],
'PrimaryBus' : [ 0x8, ['unsigned char']],
'SecondaryBus' : [ 0x9, ['unsigned char']],
'SubordinateBus' : [ 0xa, ['unsigned char']],
'SecondaryLatency' : [ 0xb, ['unsigned char']],
'IOBase' : [ 0xc, ['unsigned char']],
'IOLimit' : [ 0xd, ['unsigned char']],
'SecondaryStatus' : [ 0xe, ['unsigned short']],
'MemoryBase' : [ 0x10, ['unsigned short']],
'MemoryLimit' : [ 0x12, ['unsigned short']],
'PrefetchBase' : [ 0x14, ['unsigned short']],
'PrefetchLimit' : [ 0x16, ['unsigned short']],
'PrefetchBaseUpper32' : [ 0x18, ['unsigned long']],
'PrefetchLimitUpper32' : [ 0x1c, ['unsigned long']],
'IOBaseUpper16' : [ 0x20, ['unsigned short']],
'IOLimitUpper16' : [ 0x22, ['unsigned short']],
'CapabilitiesPtr' : [ 0x24, ['unsigned char']],
'Reserved1' : [ 0x25, ['array', 3, ['unsigned char']]],
'ROMBaseAddress' : [ 0x28, ['unsigned long']],
'InterruptLine' : [ 0x2c, ['unsigned char']],
'InterruptPin' : [ 0x2d, ['unsigned char']],
'BridgeControl' : [ 0x2e, ['unsigned short']],
} ],
'_PRIVILEGE_SET' : [ 0x14, {
'PrivilegeCount' : [ 0x0, ['unsigned long']],
'Control' : [ 0x4, ['unsigned long']],
'Privilege' : [ 0x8, ['array', 1, ['_LUID_AND_ATTRIBUTES']]],
} ],
'_IO_SECURITY_CONTEXT' : [ 0x10, {
'SecurityQos' : [ 0x0, ['pointer', ['_SECURITY_QUALITY_OF_SERVICE']]],
'AccessState' : [ 0x4, ['pointer', ['_ACCESS_STATE']]],
'DesiredAccess' : [ 0x8, ['unsigned long']],
'FullCreateOptions' : [ 0xc, ['unsigned long']],
} ],
'_KSPECIAL_REGISTERS' : [ 0x54, {
'Cr0' : [ 0x0, ['unsigned long']],
'Cr2' : [ 0x4, ['unsigned long']],
'Cr3' : [ 0x8, ['unsigned long']],
'Cr4' : [ 0xc, ['unsigned long']],
'KernelDr0' : [ 0x10, ['unsigned long']],
'KernelDr1' : [ 0x14, ['unsigned long']],
'KernelDr2' : [ 0x18, ['unsigned long']],
'KernelDr3' : [ 0x1c, ['unsigned long']],
'KernelDr6' : [ 0x20, ['unsigned long']],
'KernelDr7' : [ 0x24, ['unsigned long']],
'Gdtr' : [ 0x28, ['_DESCRIPTOR']],
'Idtr' : [ 0x30, ['_DESCRIPTOR']],
'Tr' : [ 0x38, ['unsigned short']],
'Ldtr' : [ 0x3a, ['unsigned short']],
'Reserved' : [ 0x3c, ['array', 6, ['unsigned long']]],
} ],
'_MAILSLOT_CREATE_PARAMETERS' : [ 0x18, {
'MailslotQuota' : [ 0x0, ['unsigned long']],
'MaximumMessageSize' : [ 0x4, ['unsigned long']],
'ReadTimeout' : [ 0x8, ['_LARGE_INTEGER']],
'TimeoutSpecified' : [ 0x10, ['unsigned char']],
} ],
'_NAMED_PIPE_CREATE_PARAMETERS' : [ 0x28, {
'NamedPipeType' : [ 0x0, ['unsigned long']],
'ReadMode' : [ 0x4, ['unsigned long']],
'CompletionMode' : [ 0x8, ['unsigned long']],
'MaximumInstances' : [ 0xc, ['unsigned long']],
'InboundQuota' : [ 0x10, ['unsigned long']],
'OutboundQuota' : [ 0x14, ['unsigned long']],
'DefaultTimeout' : [ 0x18, ['_LARGE_INTEGER']],
'TimeoutSpecified' : [ 0x20, ['unsigned char']],
} ],
'_CM_BIG_DATA' : [ 0x8, {
'Signature' : [ 0x0, ['unsigned short']],
'Count' : [ 0x2, ['unsigned short']],
'List' : [ 0x4, ['unsigned long']],
} ],
'_SUPPORTED_RANGE' : [ 0x20, {
'Next' : [ 0x0, ['pointer', ['_SUPPORTED_RANGE']]],
'SystemAddressSpace' : [ 0x4, ['unsigned long']],
'SystemBase' : [ 0x8, ['long long']],
'Base' : [ 0x10, ['long long']],
'Limit' : [ 0x18, ['long long']],
} ],
'_CM_KEY_NODE' : [ 0x50, {
'Signature' : [ 0x0, ['unsigned short']],
'Flags' : [ 0x2, ['unsigned short']],
'LastWriteTime' : [ 0x4, ['_LARGE_INTEGER']],
'Spare' : [ 0xc, ['unsigned long']],
'Parent' : [ 0x10, ['unsigned long']],
'SubKeyCounts' : [ 0x14, ['array', 2, ['unsigned long']]],
'SubKeyLists' : [ 0x1c, ['array', 2, ['unsigned long']]],
'ValueList' : [ 0x24, ['_CHILD_LIST']],
'ChildHiveReference' : [ 0x1c, ['_CM_KEY_REFERENCE']],
'Security' : [ 0x2c, ['unsigned long']],
'Class' : [ 0x30, ['unsigned long']],
'MaxNameLen' : [ 0x34, ['BitField', dict(start_bit = 0, end_bit = 16, native_type='unsigned long')]],
'UserFlags' : [ 0x34, ['BitField', dict(start_bit = 16, end_bit = 20, native_type='unsigned long')]],
'VirtControlFlags' : [ 0x34, ['BitField', dict(start_bit = 20, end_bit = 24, native_type='unsigned long')]],
'Debug' : [ 0x34, ['BitField', dict(start_bit = 24, end_bit = 32, native_type='unsigned long')]],
'MaxClassLen' : [ 0x38, ['unsigned long']],
'MaxValueNameLen' : [ 0x3c, ['unsigned long']],
'MaxValueDataLen' : [ 0x40, ['unsigned long']],
'WorkVar' : [ 0x44, ['unsigned long']],
'NameLength' : [ 0x48, ['unsigned short']],
'ClassLength' : [ 0x4a, ['unsigned short']],
'Name' : [ 0x4c, ['array', 1, ['unsigned short']]],
} ],
'_ARBITER_ORDERING' : [ 0x10, {
'Start' : [ 0x0, ['unsigned long long']],
'End' : [ 0x8, ['unsigned long long']],
} ],
'_ARBITER_LIST_ENTRY' : [ 0x38, {
'ListEntry' : [ 0x0, ['_LIST_ENTRY']],
'AlternativeCount' : [ 0x8, ['unsigned long']],
'Alternatives' : [ 0xc, ['pointer', ['_IO_RESOURCE_DESCRIPTOR']]],
'PhysicalDeviceObject' : [ 0x10, ['pointer', ['_DEVICE_OBJECT']]],
'RequestSource' : [ 0x14, ['Enumeration', dict(target = 'long', choices = {0: 'ArbiterRequestLegacyReported', 1: 'ArbiterRequestHalReported', 2: 'ArbiterRequestLegacyAssigned', 3: 'ArbiterRequestPnpDetected', 4: 'ArbiterRequestPnpEnumerated', -1: 'ArbiterRequestUndefined'})]],
'Flags' : [ 0x18, ['unsigned long']],
'WorkSpace' : [ 0x1c, ['long']],
'InterfaceType' : [ 0x20, ['Enumeration', dict(target = 'long', choices = {0: 'Internal', 1: 'Isa', 2: 'Eisa', 3: 'MicroChannel', 4: 'TurboChannel', 5: 'PCIBus', 6: 'VMEBus', 7: 'NuBus', 8: 'PCMCIABus', 9: 'CBus', 10: 'MPIBus', 11: 'MPSABus', 12: 'ProcessorInternal', 13: 'InternalPowerBus', 14: 'PNPISABus', 15: 'PNPBus', 16: 'MaximumInterfaceType', -1: 'InterfaceTypeUndefined'})]],
'SlotNumber' : [ 0x24, ['unsigned long']],
'BusNumber' : [ 0x28, ['unsigned long']],
'Assignment' : [ 0x2c, ['pointer', ['_CM_PARTIAL_RESOURCE_DESCRIPTOR']]],
'SelectedAlternative' : [ 0x30, ['pointer', ['_IO_RESOURCE_DESCRIPTOR']]],
'Result' : [ 0x34, ['Enumeration', dict(target = 'long', choices = {0: 'ArbiterResultSuccess', 1: 'ArbiterResultExternalConflict', 2: 'ArbiterResultNullRequest', -1: 'ArbiterResultUndefined'})]],
} ],
'_LPCP_NONPAGED_PORT_QUEUE' : [ 0x18, {
'Semaphore' : [ 0x0, ['_KSEMAPHORE']],
'BackPointer' : [ 0x14, ['pointer', ['_LPCP_PORT_OBJECT']]],
} ],
'_CM_KEY_INDEX' : [ 0x8, {
'Signature' : [ 0x0, ['unsigned short']],
'Count' : [ 0x2, ['unsigned short']],
'List' : [ 0x4, ['array', 1, ['unsigned long']]],
} ],
'_CM_KEY_REFERENCE' : [ 0x8, {
'KeyCell' : [ 0x0, ['unsigned long']],
'KeyHive' : [ 0x4, ['pointer', ['_HHIVE']]],
} ],
'_ARBITER_ALTERNATIVE' : [ 0x30, {
'Minimum' : [ 0x0, ['unsigned long long']],
'Maximum' : [ 0x8, ['unsigned long long']],
'Length' : [ 0x10, ['unsigned long']],
'Alignment' : [ 0x14, ['unsigned long']],
'Priority' : [ 0x18, ['long']],
'Flags' : [ 0x1c, ['unsigned long']],
'Descriptor' : [ 0x20, ['pointer', ['_IO_RESOURCE_DESCRIPTOR']]],
'Reserved' : [ 0x24, ['array', 3, ['unsigned long']]],
} ],
'__unnamed_19d2' : [ 0x8, {
'EndingOffset' : [ 0x0, ['pointer', ['_LARGE_INTEGER']]],
'ResourceToRelease' : [ 0x4, ['pointer', ['pointer', ['_ERESOURCE']]]],
} ],
'__unnamed_19d4' : [ 0x4, {
'ResourceToRelease' : [ 0x0, ['pointer', ['_ERESOURCE']]],
} ],
'__unnamed_19d8' : [ 0x8, {
'SyncType' : [ 0x0, ['Enumeration', dict(target = 'long', choices = {0: 'SyncTypeOther', 1: 'SyncTypeCreateSection'})]],
'PageProtection' : [ 0x4, ['unsigned long']],
} ],
'__unnamed_19da' : [ 0x14, {
'Argument1' : [ 0x0, ['pointer', ['void']]],
'Argument2' : [ 0x4, ['pointer', ['void']]],
'Argument3' : [ 0x8, ['pointer', ['void']]],
'Argument4' : [ 0xc, ['pointer', ['void']]],
'Argument5' : [ 0x10, ['pointer', ['void']]],
} ],
'_FS_FILTER_PARAMETERS' : [ 0x14, {
'AcquireForModifiedPageWriter' : [ 0x0, ['__unnamed_19d2']],
'ReleaseForModifiedPageWriter' : [ 0x0, ['__unnamed_19d4']],
'AcquireForSectionSynchronization' : [ 0x0, ['__unnamed_19d8']],
'Others' : [ 0x0, ['__unnamed_19da']],
} ],
'_DESCRIPTOR' : [ 0x8, {
'Pad' : [ 0x0, ['unsigned short']],
'Limit' : [ 0x2, ['unsigned short']],
'Base' : [ 0x4, ['unsigned long']],
} ],
'_VI_POOL_ENTRY_INUSE' : [ 0x10, {
'VirtualAddress' : [ 0x0, ['pointer', ['void']]],
'CallingAddress' : [ 0x4, ['pointer', ['void']]],
'NumberOfBytes' : [ 0x8, ['unsigned long']],
'Tag' : [ 0xc, ['unsigned long']],
} ],
'_CHILD_LIST' : [ 0x8, {
'Count' : [ 0x0, ['unsigned long']],
'List' : [ 0x4, ['unsigned long']],
} ],
'_CM_KEY_SECURITY' : [ 0x28, {
'Signature' : [ 0x0, ['unsigned short']],
'Reserved' : [ 0x2, ['unsigned short']],
'Flink' : [ 0x4, ['unsigned long']],
'Blink' : [ 0x8, ['unsigned long']],
'ReferenceCount' : [ 0xc, ['unsigned long']],
'DescriptorLength' : [ 0x10, ['unsigned long']],
'Descriptor' : [ 0x14, ['_SECURITY_DESCRIPTOR_RELATIVE']],
} ],
}
| gpl-2.0 |
apple/swift-clang | tools/scan-build-py/libscanbuild/report.py | 32 | 17684 | # -*- coding: utf-8 -*-
# Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
# See https://llvm.org/LICENSE.txt for license information.
# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
""" This module is responsible to generate 'index.html' for the report.
The input for this step is the output directory, where individual reports
could be found. It parses those reports and generates 'index.html'. """
import re
import os
import os.path
import sys
import shutil
import plistlib
import glob
import json
import logging
import datetime
from libscanbuild import duplicate_check
from libscanbuild.clang import get_version
__all__ = ['document']
def document(args):
""" Generates cover report and returns the number of bugs/crashes. """
html_reports_available = args.output_format in {'html', 'plist-html'}
logging.debug('count crashes and bugs')
crash_count = sum(1 for _ in read_crashes(args.output))
bug_counter = create_counters()
for bug in read_bugs(args.output, html_reports_available):
bug_counter(bug)
result = crash_count + bug_counter.total
if html_reports_available and result:
use_cdb = os.path.exists(args.cdb)
logging.debug('generate index.html file')
# common prefix for source files to have sorter path
prefix = commonprefix_from(args.cdb) if use_cdb else os.getcwd()
# assemble the cover from multiple fragments
fragments = []
try:
if bug_counter.total:
fragments.append(bug_summary(args.output, bug_counter))
fragments.append(bug_report(args.output, prefix))
if crash_count:
fragments.append(crash_report(args.output, prefix))
assemble_cover(args, prefix, fragments)
# copy additional files to the report
copy_resource_files(args.output)
if use_cdb:
shutil.copy(args.cdb, args.output)
finally:
for fragment in fragments:
os.remove(fragment)
return result
def assemble_cover(args, prefix, fragments):
""" Put together the fragments into a final report. """
import getpass
import socket
if args.html_title is None:
args.html_title = os.path.basename(prefix) + ' - analyzer results'
with open(os.path.join(args.output, 'index.html'), 'w') as handle:
indent = 0
handle.write(reindent("""
|<!DOCTYPE html>
|<html>
| <head>
| <title>{html_title}</title>
| <link type="text/css" rel="stylesheet" href="scanview.css"/>
| <script type='text/javascript' src="sorttable.js"></script>
| <script type='text/javascript' src='selectable.js'></script>
| </head>""", indent).format(html_title=args.html_title))
handle.write(comment('SUMMARYENDHEAD'))
handle.write(reindent("""
| <body>
| <h1>{html_title}</h1>
| <table>
| <tr><th>User:</th><td>{user_name}@{host_name}</td></tr>
| <tr><th>Working Directory:</th><td>{current_dir}</td></tr>
| <tr><th>Command Line:</th><td>{cmd_args}</td></tr>
| <tr><th>Clang Version:</th><td>{clang_version}</td></tr>
| <tr><th>Date:</th><td>{date}</td></tr>
| </table>""", indent).format(html_title=args.html_title,
user_name=getpass.getuser(),
host_name=socket.gethostname(),
current_dir=prefix,
cmd_args=' '.join(sys.argv),
clang_version=get_version(args.clang),
date=datetime.datetime.today(
).strftime('%c')))
for fragment in fragments:
# copy the content of fragments
with open(fragment, 'r') as input_handle:
shutil.copyfileobj(input_handle, handle)
handle.write(reindent("""
| </body>
|</html>""", indent))
def bug_summary(output_dir, bug_counter):
""" Bug summary is a HTML table to give a better overview of the bugs. """
name = os.path.join(output_dir, 'summary.html.fragment')
with open(name, 'w') as handle:
indent = 4
handle.write(reindent("""
|<h2>Bug Summary</h2>
|<table>
| <thead>
| <tr>
| <td>Bug Type</td>
| <td>Quantity</td>
| <td class="sorttable_nosort">Display?</td>
| </tr>
| </thead>
| <tbody>""", indent))
handle.write(reindent("""
| <tr style="font-weight:bold">
| <td class="SUMM_DESC">All Bugs</td>
| <td class="Q">{0}</td>
| <td>
| <center>
| <input checked type="checkbox" id="AllBugsCheck"
| onClick="CopyCheckedStateToCheckButtons(this);"/>
| </center>
| </td>
| </tr>""", indent).format(bug_counter.total))
for category, types in bug_counter.categories.items():
handle.write(reindent("""
| <tr>
| <th>{0}</th><th colspan=2></th>
| </tr>""", indent).format(category))
for bug_type in types.values():
handle.write(reindent("""
| <tr>
| <td class="SUMM_DESC">{bug_type}</td>
| <td class="Q">{bug_count}</td>
| <td>
| <center>
| <input checked type="checkbox"
| onClick="ToggleDisplay(this,'{bug_type_class}');"/>
| </center>
| </td>
| </tr>""", indent).format(**bug_type))
handle.write(reindent("""
| </tbody>
|</table>""", indent))
handle.write(comment('SUMMARYBUGEND'))
return name
def bug_report(output_dir, prefix):
""" Creates a fragment from the analyzer reports. """
pretty = prettify_bug(prefix, output_dir)
bugs = (pretty(bug) for bug in read_bugs(output_dir, True))
name = os.path.join(output_dir, 'bugs.html.fragment')
with open(name, 'w') as handle:
indent = 4
handle.write(reindent("""
|<h2>Reports</h2>
|<table class="sortable" style="table-layout:automatic">
| <thead>
| <tr>
| <td>Bug Group</td>
| <td class="sorttable_sorted">
| Bug Type
| <span id="sorttable_sortfwdind"> ▾</span>
| </td>
| <td>File</td>
| <td>Function/Method</td>
| <td class="Q">Line</td>
| <td class="Q">Path Length</td>
| <td class="sorttable_nosort"></td>
| </tr>
| </thead>
| <tbody>""", indent))
handle.write(comment('REPORTBUGCOL'))
for current in bugs:
handle.write(reindent("""
| <tr class="{bug_type_class}">
| <td class="DESC">{bug_category}</td>
| <td class="DESC">{bug_type}</td>
| <td>{bug_file}</td>
| <td class="DESC">{bug_function}</td>
| <td class="Q">{bug_line}</td>
| <td class="Q">{bug_path_length}</td>
| <td><a href="{report_file}#EndPath">View Report</a></td>
| </tr>""", indent).format(**current))
handle.write(comment('REPORTBUG', {'id': current['report_file']}))
handle.write(reindent("""
| </tbody>
|</table>""", indent))
handle.write(comment('REPORTBUGEND'))
return name
def crash_report(output_dir, prefix):
""" Creates a fragment from the compiler crashes. """
pretty = prettify_crash(prefix, output_dir)
crashes = (pretty(crash) for crash in read_crashes(output_dir))
name = os.path.join(output_dir, 'crashes.html.fragment')
with open(name, 'w') as handle:
indent = 4
handle.write(reindent("""
|<h2>Analyzer Failures</h2>
|<p>The analyzer had problems processing the following files:</p>
|<table>
| <thead>
| <tr>
| <td>Problem</td>
| <td>Source File</td>
| <td>Preprocessed File</td>
| <td>STDERR Output</td>
| </tr>
| </thead>
| <tbody>""", indent))
for current in crashes:
handle.write(reindent("""
| <tr>
| <td>{problem}</td>
| <td>{source}</td>
| <td><a href="{file}">preprocessor output</a></td>
| <td><a href="{stderr}">analyzer std err</a></td>
| </tr>""", indent).format(**current))
handle.write(comment('REPORTPROBLEM', current))
handle.write(reindent("""
| </tbody>
|</table>""", indent))
handle.write(comment('REPORTCRASHES'))
return name
def read_crashes(output_dir):
""" Generate a unique sequence of crashes from given output directory. """
return (parse_crash(filename)
for filename in glob.iglob(os.path.join(output_dir, 'failures',
'*.info.txt')))
def read_bugs(output_dir, html):
# type: (str, bool) -> Generator[Dict[str, Any], None, None]
""" Generate a unique sequence of bugs from given output directory.
Duplicates can be in a project if the same module was compiled multiple
times with different compiler options. These would be better to show in
the final report (cover) only once. """
def empty(file_name):
return os.stat(file_name).st_size == 0
duplicate = duplicate_check(
lambda bug: '{bug_line}.{bug_path_length}:{bug_file}'.format(**bug))
# get the right parser for the job.
parser = parse_bug_html if html else parse_bug_plist
# get the input files, which are not empty.
pattern = os.path.join(output_dir, '*.html' if html else '*.plist')
bug_files = (file for file in glob.iglob(pattern) if not empty(file))
for bug_file in bug_files:
for bug in parser(bug_file):
if not duplicate(bug):
yield bug
def parse_bug_plist(filename):
""" Returns the generator of bugs from a single .plist file. """
content = plistlib.readPlist(filename)
files = content.get('files')
for bug in content.get('diagnostics', []):
if len(files) <= int(bug['location']['file']):
logging.warning('Parsing bug from "%s" failed', filename)
continue
yield {
'result': filename,
'bug_type': bug['type'],
'bug_category': bug['category'],
'bug_line': int(bug['location']['line']),
'bug_path_length': int(bug['location']['col']),
'bug_file': files[int(bug['location']['file'])]
}
def parse_bug_html(filename):
""" Parse out the bug information from HTML output. """
patterns = [re.compile(r'<!-- BUGTYPE (?P<bug_type>.*) -->$'),
re.compile(r'<!-- BUGFILE (?P<bug_file>.*) -->$'),
re.compile(r'<!-- BUGPATHLENGTH (?P<bug_path_length>.*) -->$'),
re.compile(r'<!-- BUGLINE (?P<bug_line>.*) -->$'),
re.compile(r'<!-- BUGCATEGORY (?P<bug_category>.*) -->$'),
re.compile(r'<!-- BUGDESC (?P<bug_description>.*) -->$'),
re.compile(r'<!-- FUNCTIONNAME (?P<bug_function>.*) -->$')]
endsign = re.compile(r'<!-- BUGMETAEND -->')
bug = {
'report_file': filename,
'bug_function': 'n/a', # compatibility with < clang-3.5
'bug_category': 'Other',
'bug_line': 0,
'bug_path_length': 1
}
with open(filename) as handler:
for line in handler.readlines():
# do not read the file further
if endsign.match(line):
break
# search for the right lines
for regex in patterns:
match = regex.match(line.strip())
if match:
bug.update(match.groupdict())
break
encode_value(bug, 'bug_line', int)
encode_value(bug, 'bug_path_length', int)
yield bug
def parse_crash(filename):
""" Parse out the crash information from the report file. """
match = re.match(r'(.*)\.info\.txt', filename)
name = match.group(1) if match else None
with open(filename, mode='rb') as handler:
# this is a workaround to fix windows read '\r\n' as new lines.
lines = [line.decode().rstrip() for line in handler.readlines()]
return {
'source': lines[0],
'problem': lines[1],
'file': name,
'info': name + '.info.txt',
'stderr': name + '.stderr.txt'
}
def category_type_name(bug):
""" Create a new bug attribute from bug by category and type.
The result will be used as CSS class selector in the final report. """
def smash(key):
""" Make value ready to be HTML attribute value. """
return bug.get(key, '').lower().replace(' ', '_').replace("'", '')
return escape('bt_' + smash('bug_category') + '_' + smash('bug_type'))
def create_counters():
""" Create counters for bug statistics.
Two entries are maintained: 'total' is an integer, represents the
number of bugs. The 'categories' is a two level categorisation of bug
counters. The first level is 'bug category' the second is 'bug type'.
Each entry in this classification is a dictionary of 'count', 'type'
and 'label'. """
def predicate(bug):
bug_category = bug['bug_category']
bug_type = bug['bug_type']
current_category = predicate.categories.get(bug_category, dict())
current_type = current_category.get(bug_type, {
'bug_type': bug_type,
'bug_type_class': category_type_name(bug),
'bug_count': 0
})
current_type.update({'bug_count': current_type['bug_count'] + 1})
current_category.update({bug_type: current_type})
predicate.categories.update({bug_category: current_category})
predicate.total += 1
predicate.total = 0
predicate.categories = dict()
return predicate
def prettify_bug(prefix, output_dir):
def predicate(bug):
""" Make safe this values to embed into HTML. """
bug['bug_type_class'] = category_type_name(bug)
encode_value(bug, 'bug_file', lambda x: escape(chop(prefix, x)))
encode_value(bug, 'bug_category', escape)
encode_value(bug, 'bug_type', escape)
encode_value(bug, 'report_file', lambda x: escape(chop(output_dir, x)))
return bug
return predicate
def prettify_crash(prefix, output_dir):
def predicate(crash):
""" Make safe this values to embed into HTML. """
encode_value(crash, 'source', lambda x: escape(chop(prefix, x)))
encode_value(crash, 'problem', escape)
encode_value(crash, 'file', lambda x: escape(chop(output_dir, x)))
encode_value(crash, 'info', lambda x: escape(chop(output_dir, x)))
encode_value(crash, 'stderr', lambda x: escape(chop(output_dir, x)))
return crash
return predicate
def copy_resource_files(output_dir):
""" Copy the javascript and css files to the report directory. """
this_dir = os.path.dirname(os.path.realpath(__file__))
for resource in os.listdir(os.path.join(this_dir, 'resources')):
shutil.copy(os.path.join(this_dir, 'resources', resource), output_dir)
def encode_value(container, key, encode):
""" Run 'encode' on 'container[key]' value and update it. """
if key in container:
value = encode(container[key])
container.update({key: value})
def chop(prefix, filename):
""" Create 'filename' from '/prefix/filename' """
return filename if not len(prefix) else os.path.relpath(filename, prefix)
def escape(text):
""" Paranoid HTML escape method. (Python version independent) """
escape_table = {
'&': '&',
'"': '"',
"'": ''',
'>': '>',
'<': '<'
}
return ''.join(escape_table.get(c, c) for c in text)
def reindent(text, indent):
""" Utility function to format html output and keep indentation. """
result = ''
for line in text.splitlines():
if len(line.strip()):
result += ' ' * indent + line.split('|')[1] + os.linesep
return result
def comment(name, opts=dict()):
""" Utility function to format meta information as comment. """
attributes = ''
for key, value in opts.items():
attributes += ' {0}="{1}"'.format(key, value)
return '<!-- {0}{1} -->{2}'.format(name, attributes, os.linesep)
def commonprefix_from(filename):
""" Create file prefix from a compilation database entries. """
with open(filename, 'r') as handle:
return commonprefix(item['file'] for item in json.load(handle))
def commonprefix(files):
""" Fixed version of os.path.commonprefix.
:param files: list of file names.
:return: the longest path prefix that is a prefix of all files. """
result = None
for current in files:
if result is not None:
result = os.path.commonprefix([result, current])
else:
result = current
if result is None:
return ''
elif not os.path.isdir(result):
return os.path.dirname(result)
else:
return os.path.abspath(result)
| apache-2.0 |
piyushroshan/xen-4.3.2 | tools/tests/utests/ut_xend/ut_image.py | 42 | 5072 | #===========================================================================
# This library is free software; you can redistribute it and/or
# modify it under the terms of version 2.1 of the GNU Lesser General Public
# License as published by the Free Software Foundation.
#
# This library 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
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#============================================================================
# Copyright (C) 2009 flonatel GmbH & Co. KG
#============================================================================
import unittest
import tempfile
import os
import xen.xend.image
class ImageHandlerUnitTests(unittest.TestCase):
class ImageHandlerUnitTestsVirtualMachine:
def __init__(self):
self.info = {
'name_label': 'ItsMyParty',
}
def storeVm(self, *args):
pass
def permissionsVm(self, *args):
pass
def getDomid(self):
return 7
# Sets up a vm_config with no bootloader.
def vm_config_no_bootloader(self):
return {
'PV_kernel': 'value_of_PV_kernel',
'PV_args': 'value_of_PV_args',
'PV_ramdisk': 'value_of_PV_ramdisk',
'platform': {},
'console_refs': [],
}
def check_configure_01(self):
# This retests the problem reported by Jun Koi on 24.07.2009
# see http://lists.xensource.com/archives/html/xen-devel/2009-07/msg01006.html
"ImageHandler - call configure with mostly empty vmConfig"
vmConfig = self.vm_config_no_bootloader()
vm = self.ImageHandlerUnitTestsVirtualMachine()
ih = xen.xend.image.ImageHandler(vm, vmConfig)
self.assertEqual(ih.use_tmp_kernel, False)
self.assertEqual(ih.use_tmp_ramdisk, False)
def check_configure_02(self):
"ImageHandler - call configure with use_tmp_xxx set to false"
vmConfig = self.vm_config_no_bootloader()
vmConfig['use_tmp_kernel'] = False
vmConfig['use_tmp_ramdisk'] = False
vm = self.ImageHandlerUnitTestsVirtualMachine()
ih = xen.xend.image.ImageHandler(vm, vmConfig)
self.assertEqual(ih.use_tmp_kernel, False)
self.assertEqual(ih.use_tmp_ramdisk, False)
def check_configure_03(self):
"ImageHandler - call configure with use_tmp_xxx set to true"
vmConfig = self.vm_config_no_bootloader()
vmConfig['use_tmp_kernel'] = True
vmConfig['use_tmp_ramdisk'] = True
vm = self.ImageHandlerUnitTestsVirtualMachine()
ih = xen.xend.image.ImageHandler(vm, vmConfig)
self.assertEqual(ih.use_tmp_kernel, True)
self.assertEqual(ih.use_tmp_ramdisk, True)
def cleanup_tmp_images_base(self, vmConfig):
vm = self.ImageHandlerUnitTestsVirtualMachine()
ih = xen.xend.image.ImageHandler(vm, vmConfig)
k, ih.kernel = tempfile.mkstemp(
prefix = "ImageHandler-cleanupTmpImages-k", dir = "/tmp")
r, ih.ramdisk = tempfile.mkstemp(
prefix = "ImageHandler-cleanupTmpImages-r", dir = "/tmp")
ih.cleanupTmpImages()
kres = os.path.exists(ih.kernel)
rres = os.path.exists(ih.ramdisk)
if not ih.use_tmp_kernel:
os.unlink(ih.kernel)
if not ih.use_tmp_ramdisk:
os.unlink(ih.ramdisk)
return kres, rres
def check_cleanup_tmp_images_01(self):
"ImageHandler - cleanupTmpImages with use_tmp_xxx unset"
vmConfig = self.vm_config_no_bootloader()
kres, rres = self.cleanup_tmp_images_base(vmConfig)
self.assertEqual(kres, True)
self.assertEqual(rres, True)
def check_cleanup_tmp_images_02(self):
"ImageHandler - cleanupTmpImages with use_tmp_xxx set to false"
vmConfig = self.vm_config_no_bootloader()
vmConfig['use_tmp_kernel'] = False
vmConfig['use_tmp_ramdisk'] = False
kres, rres = self.cleanup_tmp_images_base(vmConfig)
self.assertEqual(kres, True)
self.assertEqual(rres, True)
def check_cleanup_tmp_images_03(self):
"ImageHandler - cleanupTmpImages with use_tmp_xxx set to true"
vmConfig = self.vm_config_no_bootloader()
vmConfig['use_tmp_kernel'] = True
vmConfig['use_tmp_ramdisk'] = True
kres, rres = self.cleanup_tmp_images_base(vmConfig)
self.assertEqual(kres, False)
self.assertEqual(rres, False)
def suite():
return unittest.TestSuite(
[unittest.makeSuite(ImageHandlerUnitTests, 'check_'),])
if __name__ == "__main__":
testresult = unittest.TextTestRunner(verbosity=3).run(suite())
| gpl-2.0 |
rupran/ansible | test/units/playbook/test_helpers.py | 60 | 19182 | # (c) 2016, Adrian Likins <[email protected]>
#
# This file is part of Ansible
#
# Ansible 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.
#
# Ansible 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 Ansible. If not, see <http://www.gnu.org/licenses/>.
# Make coding more python3-ish
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import os
from ansible.compat.tests import unittest
from ansible.compat.tests.mock import MagicMock
from units.mock.loader import DictDataLoader
from ansible import errors
from ansible.playbook.block import Block
from ansible.playbook.handler import Handler
from ansible.playbook.task import Task
from ansible.playbook.task_include import TaskInclude
from ansible.playbook.role.include import RoleInclude
from ansible.playbook import helpers
class MixinForMocks(object):
def _setup(self):
# This is not a very good mixin, lots of side effects
self.fake_loader = DictDataLoader({'include_test.yml': "",
'other_include_test.yml': ""})
self.mock_tqm = MagicMock(name='MockTaskQueueManager')
self.mock_play = MagicMock(name='MockPlay')
self.mock_iterator = MagicMock(name='MockIterator')
self.mock_iterator._play = self.mock_play
self.mock_inventory = MagicMock(name='MockInventory')
self.mock_inventory._hosts_cache = dict()
def _get_host(host_name):
return None
self.mock_inventory.get_host.side_effect = _get_host
# TODO: can we use a real VariableManager?
self.mock_variable_manager = MagicMock(name='MockVariableManager')
self.mock_variable_manager.get_vars.return_value = dict()
self.mock_block = MagicMock(name='MockBlock')
self.fake_role_loader = DictDataLoader({"/etc/ansible/roles/bogus_role/tasks/main.yml": """
- shell: echo 'hello world'
"""})
self._test_data_path = os.path.dirname(__file__)
self.fake_include_loader = DictDataLoader({"/dev/null/includes/test_include.yml": """
- include: other_test_include.yml
- shell: echo 'hello world'
""",
"/dev/null/includes/static_test_include.yml": """
- include: other_test_include.yml
- shell: echo 'hello static world'
""",
"/dev/null/includes/other_test_include.yml": """
- debug:
msg: other_test_include_debug
"""})
class TestLoadListOfTasks(unittest.TestCase, MixinForMocks):
def setUp(self):
self._setup()
def _assert_is_task_list(self, results):
for result in results:
self.assertIsInstance(result, Task)
def _assert_is_task_list_or_blocks(self, results):
self.assertIsInstance(results, list)
for result in results:
self.assertIsInstance(result, (Task, Block))
def test_ds_not_list(self):
ds = {}
self.assertRaises(AssertionError, helpers.load_list_of_tasks,
ds, self.mock_play, block=None, role=None, task_include=None, use_handlers=False, variable_manager=None, loader=None)
def test_empty_task(self):
ds = [{}]
self.assertRaisesRegexp(errors.AnsibleParserError,
"no action detected in task. This often indicates a misspelled module name, or incorrect module path",
helpers.load_list_of_tasks,
ds, play=self.mock_play,
variable_manager=self.mock_variable_manager, loader=self.fake_loader)
def test_empty_task_use_handlers(self):
ds = [{}]
self.assertRaisesRegexp(errors.AnsibleParserError,
"no action detected in task. This often indicates a misspelled module name, or incorrect module path",
helpers.load_list_of_tasks,
ds,
use_handlers=True,
play=self.mock_play,
variable_manager=self.mock_variable_manager,
loader=self.fake_loader)
def test_one_bogus_block(self):
ds = [{'block': None}]
self.assertRaisesRegexp(errors.AnsibleParserError,
"A malformed block was encountered",
helpers.load_list_of_tasks,
ds, play=self.mock_play,
variable_manager=self.mock_variable_manager, loader=self.fake_loader)
def test_unknown_action(self):
action_name = 'foo_test_unknown_action'
ds = [{'action': action_name}]
res = helpers.load_list_of_tasks(ds, play=self.mock_play,
variable_manager=self.mock_variable_manager, loader=self.fake_loader)
self._assert_is_task_list_or_blocks(res)
self.assertEquals(res[0].action, action_name)
def test_block_unknown_action(self):
action_name = 'foo_test_block_unknown_action'
ds = [{
'block': [{'action': action_name}]
}]
res = helpers.load_list_of_tasks(ds, play=self.mock_play,
variable_manager=self.mock_variable_manager, loader=self.fake_loader)
self._assert_is_task_list_or_blocks(res)
self.assertIsInstance(res[0], Block)
self._assert_default_block(res[0])
def _assert_default_block(self, block):
# the expected defaults
self.assertIsInstance(block.block, list)
self.assertEquals(len(block.block), 1)
self.assertIsInstance(block.rescue, list)
self.assertEquals(len(block.rescue), 0)
self.assertIsInstance(block.always, list)
self.assertEquals(len(block.always), 0)
def test_block_unknown_action_use_handlers(self):
ds = [{
'block': [{'action': 'foo_test_block_unknown_action'}]
}]
res = helpers.load_list_of_tasks(ds, play=self.mock_play, use_handlers=True,
variable_manager=self.mock_variable_manager, loader=self.fake_loader)
self._assert_is_task_list_or_blocks(res)
self.assertIsInstance(res[0], Block)
self._assert_default_block(res[0])
def test_one_bogus_block_use_handlers(self):
ds = [{'block': True}]
self.assertRaisesRegexp(errors.AnsibleParserError,
"A malformed block was encountered",
helpers.load_list_of_tasks,
ds, play=self.mock_play, use_handlers=True,
variable_manager=self.mock_variable_manager, loader=self.fake_loader)
def test_one_bogus_include(self):
ds = [{'include': 'somefile.yml'}]
res = helpers.load_list_of_tasks(ds, play=self.mock_play,
variable_manager=self.mock_variable_manager, loader=self.fake_loader)
self.assertIsInstance(res, list)
self.assertEquals(len(res), 0)
def test_one_bogus_include_use_handlers(self):
ds = [{'include': 'somefile.yml'}]
res = helpers.load_list_of_tasks(ds, play=self.mock_play, use_handlers=True,
variable_manager=self.mock_variable_manager, loader=self.fake_loader)
self.assertIsInstance(res, list)
self.assertEquals(len(res), 0)
def test_one_bogus_include_static(self):
ds = [{'include': 'somefile.yml',
'static': 'true'}]
res = helpers.load_list_of_tasks(ds, play=self.mock_play,
variable_manager=self.mock_variable_manager, loader=self.fake_loader)
self.assertIsInstance(res, list)
self.assertEquals(len(res), 0)
def test_one_include(self):
ds = [{'include': '/dev/null/includes/other_test_include.yml'}]
res = helpers.load_list_of_tasks(ds, play=self.mock_play,
variable_manager=self.mock_variable_manager, loader=self.fake_include_loader)
self.assertEquals(len(res), 1)
self._assert_is_task_list_or_blocks(res)
def test_one_parent_include(self):
ds = [{'include': '/dev/null/includes/test_include.yml'}]
res = helpers.load_list_of_tasks(ds, play=self.mock_play,
variable_manager=self.mock_variable_manager, loader=self.fake_include_loader)
self._assert_is_task_list_or_blocks(res)
self.assertIsInstance(res[0], Block)
self.assertIsInstance(res[0]._parent, TaskInclude)
# TODO/FIXME: do this non deprecated way
def test_one_include_tags(self):
ds = [{'include': '/dev/null/includes/other_test_include.yml',
'tags': ['test_one_include_tags_tag1', 'and_another_tagB']
}]
res = helpers.load_list_of_tasks(ds, play=self.mock_play,
variable_manager=self.mock_variable_manager, loader=self.fake_include_loader)
self._assert_is_task_list_or_blocks(res)
self.assertIsInstance(res[0], Block)
self.assertIn('test_one_include_tags_tag1', res[0].tags)
self.assertIn('and_another_tagB', res[0].tags)
# TODO/FIXME: do this non deprecated way
def test_one_parent_include_tags(self):
ds = [{'include': '/dev/null/includes/test_include.yml',
#'vars': {'tags': ['test_one_parent_include_tags_tag1', 'and_another_tag2']}
'tags': ['test_one_parent_include_tags_tag1', 'and_another_tag2']
}
]
res = helpers.load_list_of_tasks(ds, play=self.mock_play,
variable_manager=self.mock_variable_manager, loader=self.fake_include_loader)
self._assert_is_task_list_or_blocks(res)
self.assertIsInstance(res[0], Block)
self.assertIn('test_one_parent_include_tags_tag1', res[0].tags)
self.assertIn('and_another_tag2', res[0].tags)
# It would be useful to be able to tell what kind of deprecation we encountered and where we encountered it.
def test_one_include_tags_deprecated_mixed(self):
ds = [{'include': "/dev/null/includes/other_test_include.yml",
'vars': {'tags': "['tag_on_include1', 'tag_on_include2']"},
'tags': 'mixed_tag1, mixed_tag2'
}]
self.assertRaisesRegexp(errors.AnsibleParserError, 'Mixing styles',
helpers.load_list_of_tasks,
ds, play=self.mock_play,
variable_manager=self.mock_variable_manager, loader=self.fake_include_loader)
def test_one_include_tags_deprecated_include(self):
ds = [{'include': '/dev/null/includes/other_test_include.yml',
'vars': {'tags': ['include_tag1_deprecated', 'and_another_tagB_deprecated']}
}]
res = helpers.load_list_of_tasks(ds, play=self.mock_play,
variable_manager=self.mock_variable_manager, loader=self.fake_include_loader)
self._assert_is_task_list_or_blocks(res)
self.assertIsInstance(res[0], Block)
self.assertIn('include_tag1_deprecated', res[0].tags)
self.assertIn('and_another_tagB_deprecated', res[0].tags)
def test_one_include_use_handlers(self):
ds = [{'include': '/dev/null/includes/other_test_include.yml'}]
res = helpers.load_list_of_tasks(ds, play=self.mock_play,
use_handlers=True,
variable_manager=self.mock_variable_manager, loader=self.fake_include_loader)
self._assert_is_task_list_or_blocks(res)
self.assertIsInstance(res[0], Handler)
def test_one_parent_include_use_handlers(self):
ds = [{'include': '/dev/null/includes/test_include.yml'}]
res = helpers.load_list_of_tasks(ds, play=self.mock_play,
use_handlers=True,
variable_manager=self.mock_variable_manager, loader=self.fake_include_loader)
self._assert_is_task_list_or_blocks(res)
self.assertIsInstance(res[0], Handler)
# default for Handler
self.assertEquals(res[0].listen, None)
# TODO/FIXME: this doesn't seen right
# figure out how to get the non-static errors to be raised, this seems to just ignore everything
def test_one_include_not_static(self):
ds = [{
'include': '/dev/null/includes/static_test_include.yml',
'static': False
}]
#a_block = Block()
ti_ds = {'include': '/dev/null/includes/ssdftatic_test_include.yml'}
a_task_include = TaskInclude()
ti = a_task_include.load(ti_ds)
res = helpers.load_list_of_tasks(ds, play=self.mock_play,
block=ti,
variable_manager=self.mock_variable_manager, loader=self.fake_include_loader)
self._assert_is_task_list_or_blocks(res)
self.assertIsInstance(res[0], Task)
self.assertEquals(res[0].args['_raw_params'], '/dev/null/includes/static_test_include.yml')
# TODO/FIXME: This two get stuck trying to make a mock_block into a TaskInclude
# def test_one_include(self):
# ds = [{'include': 'other_test_include.yml'}]
# res = helpers.load_list_of_tasks(ds, play=self.mock_play,
# block=self.mock_block,
# variable_manager=self.mock_variable_manager, loader=self.fake_include_loader)
# print(res)
# def test_one_parent_include(self):
# ds = [{'include': 'test_include.yml'}]
# res = helpers.load_list_of_tasks(ds, play=self.mock_play,
# block=self.mock_block,
# variable_manager=self.mock_variable_manager, loader=self.fake_include_loader)
# print(res)
def test_one_bogus_include_role(self):
ds = [{'include_role': {'name': 'bogus_role'}}]
res = helpers.load_list_of_tasks(ds, play=self.mock_play,
block=self.mock_block,
variable_manager=self.mock_variable_manager, loader=self.fake_role_loader)
self.assertEquals(len(res), 1)
self._assert_is_task_list_or_blocks(res)
def test_one_bogus_include_role_use_handlers(self):
ds = [{'include_role': {'name': 'bogus_role'}}]
res = helpers.load_list_of_tasks(ds, play=self.mock_play, use_handlers=True,
block=self.mock_block,
variable_manager=self.mock_variable_manager,
loader=self.fake_role_loader)
self.assertEquals(len(res), 1)
self._assert_is_task_list_or_blocks(res)
class TestLoadListOfRoles(unittest.TestCase, MixinForMocks):
def setUp(self):
self._setup()
def test_ds_not_list(self):
ds = {}
self.assertRaises(AssertionError, helpers.load_list_of_roles,
ds, self.mock_play)
def test_empty_role(self):
ds = [{}]
self.assertRaisesRegexp(errors.AnsibleError,
"role definitions must contain a role name",
helpers.load_list_of_roles,
ds, self.mock_play,
variable_manager=self.mock_variable_manager, loader=self.fake_role_loader)
def test_empty_role_just_name(self):
ds = [{'name': 'bogus_role'}]
res = helpers.load_list_of_roles(ds, self.mock_play,
variable_manager=self.mock_variable_manager, loader=self.fake_role_loader)
self.assertIsInstance(res, list)
for r in res:
self.assertIsInstance(r, RoleInclude)
def test_block_unknown_action(self):
ds = [{
'block': [{'action': 'foo_test_block_unknown_action'}]
}]
ds = [{'name': 'bogus_role'}]
res = helpers.load_list_of_roles(ds, self.mock_play,
variable_manager=self.mock_variable_manager, loader=self.fake_role_loader)
self.assertIsInstance(res, list)
for r in res:
self.assertIsInstance(r, RoleInclude)
class TestLoadListOfBlocks(unittest.TestCase, MixinForMocks):
def setUp(self):
self._setup()
def test_ds_not_list(self):
ds = {}
mock_play = MagicMock(name='MockPlay')
self.assertRaises(AssertionError, helpers.load_list_of_blocks,
ds, mock_play, parent_block=None, role=None, task_include=None, use_handlers=False, variable_manager=None, loader=None)
def test_empty_block(self):
ds = [{}]
mock_play = MagicMock(name='MockPlay')
self.assertRaisesRegexp(errors.AnsibleParserError,
"no action detected in task. This often indicates a misspelled module name, or incorrect module path",
helpers.load_list_of_blocks,
ds, mock_play,
parent_block=None,
role=None,
task_include=None,
use_handlers=False,
variable_manager=None,
loader=None)
def test_block_unknown_action(self):
ds = [{'action': 'foo'}]
mock_play = MagicMock(name='MockPlay')
res = helpers.load_list_of_blocks(ds, mock_play, parent_block=None, role=None, task_include=None, use_handlers=False, variable_manager=None,
loader=None)
self.assertIsInstance(res, list)
for block in res:
self.assertIsInstance(block, Block)
| gpl-3.0 |
TheAltcoinBoard/XAB-withoutSecp256k1 | share/qt/extract_strings_qt.py | 7 | 1854 | #!/usr/bin/python
'''
Extract _("...") strings for translation and convert to Qt4 stringdefs so that
they can be picked up by Qt linguist.
'''
from subprocess import Popen, PIPE
import glob
OUT_CPP="src/qt/bitcoinstrings.cpp"
EMPTY=['""']
def parse_po(text):
"""
Parse 'po' format produced by xgettext.
Return a list of (msgid,msgstr) tuples.
"""
messages = []
msgid = []
msgstr = []
in_msgid = False
in_msgstr = False
for line in text.split('\n'):
line = line.rstrip('\r')
if line.startswith('msgid '):
if in_msgstr:
messages.append((msgid, msgstr))
in_msgstr = False
# message start
in_msgid = True
msgid = [line[6:]]
elif line.startswith('msgstr '):
in_msgid = False
in_msgstr = True
msgstr = [line[7:]]
elif line.startswith('"'):
if in_msgid:
msgid.append(line)
if in_msgstr:
msgstr.append(line)
if in_msgstr:
messages.append((msgid, msgstr))
return messages
files = glob.glob('src/*.cpp') + glob.glob('src/*.h')
# xgettext -n --keyword=_ $FILES
child = Popen(['xgettext','--output=-','-n','--keyword=_'] + files, stdout=PIPE)
(out, err) = child.communicate()
messages = parse_po(out)
f = open(OUT_CPP, 'w')
f.write("""#include <QtGlobal>
// Automatically generated by extract_strings.py
#ifdef __GNUC__
#define UNUSED __attribute__((unused))
#else
#define UNUSED
#endif
""")
f.write('static const char UNUSED *bitcoin_strings[] = {')
for (msgid, msgstr) in messages:
if msgid != EMPTY:
f.write('QT_TRANSLATE_NOOP("bitcoin-core", %s),\n' % ('\n'.join(msgid)))
f.write('};')
f.close()
| mit |
FInAT/FInAT | finat/restricted.py | 1 | 8971 | from functools import singledispatch
from itertools import chain
import FIAT
from FIAT.polynomial_set import mis
import finat
from finat.fiat_elements import FiatElement
from finat.physically_mapped import PhysicallyMappedElement
# Sentinel for when restricted element is empty
null_element = object()
@singledispatch
def restrict(element, domain, take_closure):
"""Restrict an element to a given subentity.
:arg element: The element to restrict.
:arg domain: The subentity to restrict to.
:arg take_closure: Gather dofs in closure of the subentities?
Ignored for "interior" domain.
:raises NotImplementedError: If we don't know how to restrict this
element.
:raises ValueError: If the restricted element is empty.
:returns: A new finat element."""
return NotImplementedError(f"Don't know how to restrict element of type {type(element)}")
@restrict.register(FiatElement)
def restrict_fiat(element, domain, take_closure):
try:
return FiatElement(FIAT.RestrictedElement(element._element, restriction_domain=domain))
except ValueError:
return null_element
@restrict.register(PhysicallyMappedElement)
def restrict_physically_mapped(element, domain, take_closure):
raise NotImplementedError("Can't restrict Physically Mapped things")
@restrict.register(finat.FlattenedDimensions)
def restrict_flattened_dimensions(element, domain, take_closure):
restricted = restrict(element.product, domain, take_closure)
if restricted is null_element:
return null_element
else:
return finat.FlattenedDimensions(restricted)
@restrict.register(finat.DiscontinuousElement)
def restrict_discontinuous(element, domain, take_closure):
if domain == "interior":
return element
else:
return null_element
@restrict.register(finat.EnrichedElement)
def restrict_enriched(element, domain, take_closure):
if all(isinstance(e, finat.mixed.MixedSubElement) for e in element.elements):
# Mixed is handled by Enriched + MixedSubElement, we must
# restrict the subelements here because the transformation is
# nonlocal.
elements = tuple(restrict(e.element, domain, take_closure) for
e in element.elements)
reconstruct = finat.mixed.MixedElement
elif not any(isinstance(e, finat.mixed.MixedSubElement) for e in element.elements):
elements = tuple(restrict(e, domain, take_closure)
for e in element.elements)
reconstruct = finat.EnrichedElement
else:
raise NotImplementedError("Not expecting enriched with mixture of MixedSubElement and others")
elements = tuple(e for e in elements if e is not null_element)
if elements:
return reconstruct(elements)
else:
return null_element
@restrict.register(finat.HCurlElement)
def restrict_hcurl(element, domain, take_closure):
restricted = restrict(element.wrappee, domain, take_closure)
if restricted is null_element:
return null_element
else:
if isinstance(restricted, finat.EnrichedElement):
return finat.EnrichedElement(finat.HCurlElement(e)
for e in restricted.elements)
else:
return finat.HCurlElement(restricted)
@restrict.register(finat.HDivElement)
def restrict_hdiv(element, domain, take_closure):
restricted = restrict(element.wrappee, domain, take_closure)
if restricted is null_element:
return null_element
else:
if isinstance(restricted, finat.EnrichedElement):
return finat.EnrichedElement(finat.HDivElement(e)
for e in restricted.elements)
else:
return finat.HDivElement(restricted)
@restrict.register(finat.mixed.MixedSubElement)
def restrict_mixed(element, domain, take_closure):
raise AssertionError("Was expecting this to be handled inside EnrichedElement restriction")
@restrict.register(finat.GaussLobattoLegendre)
def restrict_gll(element, domain, take_closure):
try:
return FiatElement(FIAT.RestrictedElement(element._element, restriction_domain=domain))
except ValueError:
return null_element
@restrict.register(finat.GaussLegendre)
def restrict_gl(element, domain, take_closure):
if domain == "interior":
return element
else:
return null_element
def r_to_codim(restriction, dim):
if restriction == "interior":
return 0
elif restriction == "facet":
return 1
elif restriction == "face":
return dim - 2
elif restriction == "edge":
return dim - 1
elif restriction == "vertex":
return dim
else:
raise ValueError
def codim_to_r(codim, dim):
d = dim - codim
if codim == 0:
return "interior"
elif codim == 1:
return "facet"
elif d == 0:
return "vertex"
elif d == 1:
return "edge"
elif d == 2:
return "face"
else:
raise ValueError
@restrict.register(finat.TensorProductElement)
def restrict_tpe(element, domain, take_closure):
# The restriction of a TPE to a codim subentity is the direct sum
# of TPEs where the factors have been restricted in such a way
# that the sum of those restrictions is codim.
#
# For example, to restrict an interval x interval to edges (codim 1)
# we construct
#
# R(I, 0)βR(I, 1) β R(I, 1)βR(I, 0)
#
# If take_closure is true, the restriction wants to select dofs on
# entities with dim >= codim >= 1 (for the edge example)
# so we get
#
# R(I, 0)βR(I, 1) β R(I, 1)βR(I, 0) β R(I, 0)βR(I, 0)
factors = element.factors
dimension = element.cell.get_spatial_dimension()
# Figure out which codim entity we're selecting
codim = r_to_codim(domain, dimension)
# And the range of codims.
upper = 1 + (dimension
if (take_closure and domain != "interior")
else codim)
# restrictions on each factor taken from n-tuple that sums to the
# target codim (as long as the codim <= dim_factor)
restrictions = tuple(candidate
for candidate in chain(*(mis(len(factors), c)
for c in range(codim, upper)))
if all(d <= factor.cell.get_dimension()
for d, factor in zip(candidate, factors)))
elements = []
for decomposition in restrictions:
# Recurse, but don't take closure in recursion (since we
# handled it already).
new_factors = tuple(
restrict(factor, codim_to_r(codim, factor.cell.get_dimension()),
take_closure=False)
for factor, codim in zip(factors, decomposition))
# If one of the factors was empty then the whole TPE is empty,
# so skip.
if all(f is not null_element for f in new_factors):
elements.append(finat.TensorProductElement(new_factors))
if elements:
return finat.EnrichedElement(elements)
else:
return null_element
@restrict.register(finat.TensorFiniteElement)
def restrict_tfe(element, domain, take_closure):
restricted = restrict(element._base_element, domain, take_closure)
if restricted is null_element:
return null_element
else:
return finat.TensorFiniteElement(restricted, element._shape, element._transpose)
@restrict.register(finat.HDivTrace)
def restrict_hdivtrace(element, domain, take_closure):
try:
return FiatElement(FIAT.RestrictedElement(element._element, restriction_domain=domain))
except ValueError:
return null_element
def RestrictedElement(element, restriction_domain, *, indices=None):
"""Construct a restricted element.
:arg element: The element to restrict.
:arg restriction_domain: Which entities to restrict to.
:arg indices: Indices of basis functions to select (not supported)
:returns: A new element.
.. note::
A restriction domain of "interior" means to select the dofs on
the cell, all other domains (e.g. "face", "edge") select dofs
in the closure of the entity.
.. warning::
The returned element *may not* be interpolatory. That is, the
dual basis (if implemented) might not be nodal to the primal
basis. Assembly still works (``basis_evaluation`` is fine), but
interpolation may produce bad results.
Restrictions of FIAT-implemented CiarletElements are always
nodal.
"""
if indices is not None:
raise NotImplementedError("Only done for topological restrictions")
assert restriction_domain is not None
restricted = restrict(element, restriction_domain, take_closure=True)
if restricted is null_element:
raise ValueError("Restricted element is empty")
return restricted
| mit |
quozl/terminal-activity | terminal.py | 1 | 22474 | # Copyright (C) 2007, Eduardo Silva <[email protected]>.
# Copyright (C) 2008, One Laptop Per Child
# Copyright (C) 2009, Simon Schampijer
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
import os
import sys
import json
import ConfigParser
import logging
from gettext import gettext as _
import gi
vs = {'Gtk': '3.0', 'SugarExt': '1.0', 'SugarGestures': '1.0', 'Vte': '2.91'}
for api, ver in vs.iteritems():
gi.require_version(api, ver)
from gi.repository import GLib
from gi.repository import Gtk
from gi.repository import Gdk
from gi.repository import Vte
from gi.repository import Pango
from sugar3.graphics.toolbutton import ToolButton
from sugar3.graphics.toolbarbox import ToolbarBox
from sugar3.graphics.toolbarbox import ToolbarButton
from sugar3.activity.widgets import EditToolbar
from sugar3.activity.widgets import ActivityToolbarButton
from sugar3.activity.widgets import StopButton
from sugar3.activity import activity
from sugar3 import env
from widgets import BrowserNotebook
from widgets import TabLabel
from helpbutton import HelpButton
MASKED_ENVIRONMENT = [
'DBUS_SESSION_BUS_ADDRESS',
'PPID']
log = logging.getLogger('Terminal')
log.setLevel(logging.DEBUG)
logging.basicConfig()
FONT_SIZE = 10
VTE_VERSION = 0
try:
VTE_VERSION = Vte.MINOR_VERSION
except:
# version is not published in old versions of vte
pass
class TerminalActivity(activity.Activity):
def __init__(self, handle):
activity.Activity.__init__(self, handle)
# HACK to avoid Escape key disable fullscreen mode on Terminal Activity
# This is related with http://bugs.sugarlabs.org/ticket/440
self.disconnect_by_func(self._Window__key_press_cb)
self.connect('key-press-event', self.__key_press_cb)
self.max_participants = 1
self._theme_state = "light"
self._font_size = FONT_SIZE
toolbar_box = ToolbarBox()
activity_button = ActivityToolbarButton(self)
toolbar_box.toolbar.insert(activity_button, 0)
activity_button.show()
edit_toolbar = self._create_edit_toolbar()
edit_toolbar_button = ToolbarButton(
page=edit_toolbar,
icon_name='toolbar-edit'
)
edit_toolbar.show()
toolbar_box.toolbar.insert(edit_toolbar_button, -1)
edit_toolbar_button.show()
view_toolbar = self._create_view_toolbar()
view_toolbar_button = ToolbarButton(
page=view_toolbar,
icon_name='toolbar-view')
view_toolbar.show()
toolbar_box.toolbar.insert(view_toolbar_button, -1)
view_toolbar_button.show()
self._delete_tab_toolbar = None
self._previous_tab_toolbar = None
self._next_tab_toolbar = None
helpbutton = self._create_help_button()
toolbar_box.toolbar.insert(helpbutton, -1)
helpbutton.show_all()
separator = Gtk.SeparatorToolItem()
separator.props.draw = False
separator.set_expand(True)
toolbar_box.toolbar.insert(separator, -1)
separator.show()
stop_button = StopButton(self)
stop_button.props.accelerator = '<Ctrl><Shift>Q'
toolbar_box.toolbar.insert(stop_button, -1)
stop_button.show()
self.set_toolbar_box(toolbar_box)
toolbar_box.show()
self._notebook = BrowserNotebook()
self._notebook.connect("tab-added", self.__open_tab_cb)
self._notebook.set_property("tab-pos", Gtk.PositionType.TOP)
self._notebook.set_scrollable(True)
self._notebook.show()
self.set_canvas(self._notebook)
self._create_tab(None)
def _create_edit_toolbar(self):
edit_toolbar = EditToolbar()
edit_toolbar.undo.props.visible = False
edit_toolbar.redo.props.visible = False
edit_toolbar.separator.props.visible = False
edit_toolbar.copy.connect('clicked', self.__copy_cb)
edit_toolbar.copy.props.accelerator = '<Ctrl><Shift>C'
edit_toolbar.paste.connect('clicked', self.__paste_cb)
edit_toolbar.paste.props.accelerator = '<Ctrl><Shift>V'
return edit_toolbar
def __copy_cb(self, button):
vt = self._notebook.get_nth_page(self._notebook.get_current_page()).vt
if vt.get_has_selection():
vt.copy_clipboard()
def __paste_cb(self, button):
vt = self._notebook.get_nth_page(self._notebook.get_current_page()).vt
vt.paste_clipboard()
def _toggled_theme(self, button):
if self._theme_state == "dark":
self._theme_state = "light"
elif self._theme_state == "light":
self._theme_state = "dark"
self._update_theme()
def _update_theme(self):
if self._theme_state == "light":
self._theme_toggler.set_icon_name('dark-theme')
self._theme_toggler.set_tooltip('Switch to Dark Theme')
elif self._theme_state == "dark":
self._theme_toggler.set_icon_name('light-theme')
self._theme_toggler.set_tooltip('Switch to Light Theme')
for i in range(self._notebook.get_n_pages()):
vt = self._notebook.get_nth_page(i).vt
self._configure_vt(vt)
def _create_view_toolbar(self): # Color changer and Zoom toolbar
view_toolbar = Gtk.Toolbar()
self._theme_toggler = ToolButton('dark-theme')
self._theme_toggler.set_tooltip('Switch to Dark Theme')
self._theme_toggler.props.accelerator = '<Ctrl><Shift>I'
self._theme_toggler.connect('clicked', self._toggled_theme)
view_toolbar.insert(self._theme_toggler, -1)
self._theme_toggler.show()
sep = Gtk.SeparatorToolItem()
view_toolbar.insert(sep, -1)
sep.show()
zoom_out_button = ToolButton('zoom-out')
zoom_out_button.set_tooltip(_('Zoom out'))
zoom_out_button.props.accelerator = '<Ctrl>minus'
zoom_out_button.connect('clicked', self.__zoom_out_cb)
view_toolbar.insert(zoom_out_button, -1)
zoom_out_button.show()
zoom_in_button = ToolButton('zoom-in')
zoom_in_button.set_tooltip(_('Zoom in'))
zoom_in_button.props.accelerator = '<Ctrl>plus'
zoom_in_button.connect('clicked', self.__zoom_in_cb)
view_toolbar.insert(zoom_in_button, -1)
zoom_in_button.show()
fullscreen_button = ToolButton('view-fullscreen')
fullscreen_button.set_tooltip(_("Fullscreen"))
fullscreen_button.props.accelerator = '<Alt>Return'
fullscreen_button.connect('clicked', self.__fullscreen_cb)
view_toolbar.insert(fullscreen_button, -1)
fullscreen_button.show()
return view_toolbar
def _zoom(self, step):
current_page = self._notebook.get_current_page()
vt = self._notebook.get_nth_page(current_page).vt
font_desc = vt.get_font()
font_desc.set_size(font_desc.get_size() + Pango.SCALE * step)
vt.set_font(font_desc)
def __zoom_out_cb(self, button):
self._zoom(-1)
def __zoom_in_cb(self, button):
self._zoom(1)
def __fullscreen_cb(self, button):
self.fullscreen()
def _create_help_button(self):
helpitem = HelpButton()
helpitem.add_section(_('Useful commands'))
helpitem.add_section(_('cd'))
helpitem.add_paragraph(_('Change directory'))
helpitem.add_paragraph(_('To use it, write: cd directory'))
helpitem.add_paragraph(
_('If you call it without parameters, will change\n'
'to the user directory'))
helpitem.add_section(_('ls'))
helpitem.add_paragraph(_('List the content of a directory.'))
helpitem.add_paragraph(_('To use it, write: ls directory'))
helpitem.add_paragraph(
_('If you call it without parameters, will list the\n'
'working directory'))
helpitem.add_section(_('cp'))
helpitem.add_paragraph(_('Copy a file to a specific location'))
helpitem.add_paragraph(_('Call it with the file and the new location'))
helpitem.add_paragraph(_('Use: cp file directory'))
helpitem.add_section(_('rm'))
helpitem.add_paragraph(_('Removes a file in any path'))
helpitem.add_paragraph(_('Use: rm file'))
helpitem.add_section(_('su'))
helpitem.add_paragraph(_('Login as superuser (root)'))
helpitem.add_paragraph(
_('The root user is the administrator of the\nsystem'))
helpitem.add_paragraph(
_('You must be careful, because you can modify\nsystem files'))
return helpitem
def __open_tab_cb(self, btn):
vt = self._notebook.get_nth_page(self._notebook.get_current_page()).vt
font_desc = vt.get_font()
self._font_size = font_desc.get_size() / Pango.SCALE
index = self._create_tab(None)
self._notebook.page = index
def __close_tab_cb(self, btn, child):
index = self._notebook.page_num(child)
self._close_tab(index)
def __prev_tab_cb(self, btn):
if self._notebook.props.page == 0:
self._notebook.props.page = self._notebook.get_n_pages() - 1
else:
self._notebook.props.page = self._notebook.props.page - 1
vt = self._notebook.get_nth_page(self._notebook.get_current_page()).vt
vt.grab_focus()
def __next_tab_cb(self, btn):
if self._notebook.props.page == self._notebook.get_n_pages() - 1:
self._notebook.props.page = 0
else:
self._notebook.props.page = self._notebook.props.page + 1
vt = self._notebook.get_nth_page(self._notebook.get_current_page()).vt
vt.grab_focus()
def _close_tab(self, index):
self._notebook.remove_page(index)
if self._notebook.get_n_pages() == 0:
self.close()
if self._notebook.get_n_pages() == 1:
self._notebook.get_tab_label(
self._notebook.get_nth_page(0)).hide_close_button()
def __tab_child_exited_cb(self, vt, status=None):
for i in range(self._notebook.get_n_pages()):
if self._notebook.get_nth_page(i).vt == vt:
self._close_tab(i)
return
def __tab_title_changed_cb(self, vt):
for i in range(self._notebook.get_n_pages()):
if self._notebook.get_nth_page(i).vt == vt:
label = self._notebook.get_nth_page(i).label
label.set_text(vt.get_window_title())
return
def __drag_data_received_cb(self, widget, context, x, y, selection,
target, time):
widget.feed_child(selection.get_text(), -1)
context.finish(True, False, time)
return True
def _create_tab(self, tab_state):
vt = Vte.Terminal()
vt.connect("child-exited", self.__tab_child_exited_cb)
vt.connect("window-title-changed", self.__tab_title_changed_cb)
vt.drag_dest_set(Gtk.DestDefaults.MOTION | Gtk.DestDefaults.DROP,
[Gtk.TargetEntry.new('text/plain', 0, 0),
Gtk.TargetEntry.new('STRING', 0, 1)],
Gdk.DragAction.DEFAULT | Gdk.DragAction.COPY)
vt.drag_dest_add_text_targets()
vt.connect('drag_data_received', self.__drag_data_received_cb)
self._configure_vt(vt)
vt.show()
scrollbar = Gtk.VScrollbar.new(vt.get_vadjustment())
box = Gtk.HBox()
box.pack_start(vt, True, True, 0)
box.pack_start(scrollbar, False, True, 0)
box.vt = vt
box.show()
tablabel = TabLabel(box)
tablabel.connect('tab-close', self.__close_tab_cb)
tablabel.update_size(200)
box.label = tablabel
index = self._notebook.append_page(box, tablabel)
tablabel.show_all()
# Uncomment this to only show the tab bar when there is at least
# one tab. I think it's useful to always see it, since it displays
# the 'window title'.
# self._notebook.props.show_tabs = self._notebook.get_n_pages() > 1
if self._notebook.get_n_pages() == 1:
tablabel.hide_close_button()
if self._notebook.get_n_pages() == 2:
self._notebook.get_tab_label(
self._notebook.get_nth_page(0)).show_close_button()
self._notebook.show_all()
# Launch the default shell in the HOME directory.
os.chdir(os.environ["HOME"])
if tab_state:
# Restore the environment.
# This is currently not enabled.
environment = tab_state['env']
filtered_env = []
for e in environment:
var, sep, value = e.partition('=')
if var not in MASKED_ENVIRONMENT:
filtered_env.append(var + sep + value)
# TODO: Make the shell restore these environment variables,
# then clear out TERMINAL_ENV.
# os.environ['TERMINAL_ENV'] = '\n'.join(filtered_env)
# Restore the working directory.
if 'cwd' in tab_state and os.path.exists(tab_state['cwd']):
try:
os.chdir(tab_state['cwd'])
except:
# ACLs may deny access
sys.stdout.write("Could not chdir to " + tab_state['cwd'])
if 'font_size' in tab_state:
font_desc = vt.get_font()
font_desc.set_size(tab_state['font_size'])
vt.set_font(font_desc)
# Restore the scrollback buffer.
for l in tab_state['scrollback']:
vt.feed(str(l) + '\r\n')
shell_cmd = os.environ.get('SHELL') or '/bin/bash'
if hasattr(vt, 'fork_command_full'):
sucess_, box.pid = vt.fork_command_full(
Vte.PtyFlags.DEFAULT, os.environ["HOME"],
[shell_cmd], [], GLib.SpawnFlags. DO_NOT_REAP_CHILD,
None, None)
else:
sucess_, box.pid = vt.spawn_sync(
Vte.PtyFlags.DEFAULT, os.environ["HOME"],
[shell_cmd], [], GLib.SpawnFlags. DO_NOT_REAP_CHILD,
None, None)
self._notebook.props.page = index
vt.grab_focus()
return index
def __key_press_cb(self, window, event):
"""Route some keypresses directly to the vte and then drop them.
This prevents Sugar from hijacking events that are useful in
the vte.
"""
def event_to_vt(event):
current_page = self._notebook.get_current_page()
vt = self._notebook.get_nth_page(current_page).vt
vt.event(event)
key_name = Gdk.keyval_name(event.keyval)
# Escape is used in Sugar to cancel fullscreen mode.
if key_name == 'Escape':
event_to_vt(event)
return True
elif event.get_state() & Gdk.ModifierType.CONTROL_MASK:
if key_name in ['z', 'q']:
event_to_vt(event)
return True
elif key_name == 'Tab':
current_index = self._notebook.get_current_page()
if current_index == self._notebook.get_n_pages() - 1:
self._notebook.set_current_page(0)
else:
self._notebook.set_current_page(current_index + 1)
return True
elif event.get_state() & Gdk.ModifierType.SHIFT_MASK:
if key_name == 'ISO_Left_Tab':
current_index = self._notebook.get_current_page()
if current_index == 0:
self._notebook.set_current_page(
self._notebook.get_n_pages() - 1)
else:
self._notebook.set_current_page(current_index - 1)
return True
elif key_name == 'T':
self._create_tab(None)
return True
return False
def read_file(self, file_path):
if self.metadata['mime_type'] != 'text/plain':
return
fd = open(file_path, 'r')
text = fd.read()
data = json.loads(text)
fd.close()
# Clean out any existing tabs.
while self._notebook.get_n_pages():
self._notebook.remove_page(0)
# Restore theme
self._theme_state = data['theme']
self._update_theme()
# Create new tabs from saved state.
for tab_state in data['tabs']:
self._create_tab(tab_state)
# Restore active tab.
self._notebook.props.page = data['current-tab']
# Create a blank one if this state had no terminals.
if self._notebook.get_n_pages() == 0:
self._create_tab(None)
def write_file(self, file_path):
if not self.metadata['mime_type']:
self.metadata['mime_type'] = 'text/plain'
data = {}
data['current-tab'] = self._notebook.get_current_page()
data['theme'] = self._theme_state
data['tabs'] = []
for i in range(self._notebook.get_n_pages()):
def is_selected(vte, *args):
return True
page = self._notebook.get_nth_page(i)
text = ''
if VTE_VERSION >= 38:
# in older versions of vte, get_text() makes crash
# the activity at random - SL #4627
try:
# get_text is only available in latest vte #676999
# and pygobject/gobject-introspection #690041
text, attr_ = page.vt.get_text(is_selected, None)
except AttributeError:
pass
scrollback_lines = text.split('\n')
environ_file = '/proc/%d/environ' % page.pid
if os.path.isfile(environ_file):
# Note- this currently gets the child's initial environment
# rather than the current environment, making it not very useful.
environment = open(environ_file, 'r').read().split('\0')
cwd = os.readlink('/proc/%d/cwd' % page.pid)
else:
# terminal killed by the user
environment = []
cwd = '~'
font_desc = page.vt.get_font()
tab_state = {'env': environment, 'cwd': cwd,
'font_size': font_desc.get_size(),
'scrollback': scrollback_lines}
data['tabs'].append(tab_state)
fd = open(file_path, 'w')
text = json.dumps(data)
fd.write(text)
fd.close()
def _get_conf(self, conf, var, default):
if conf.has_option('terminal', var):
if isinstance(default, bool):
return conf.getboolean('terminal', var)
elif isinstance(default, int):
return conf.getint('terminal', var)
else:
return conf.get('terminal', var)
else:
conf.set('terminal', var, default)
return default
def _configure_vt(self, vt):
conf = ConfigParser.ConfigParser()
conf_file = os.path.join(env.get_profile_path(), 'terminalrc')
if os.path.isfile(conf_file):
f = open(conf_file, 'r')
conf.readfp(f)
f.close()
else:
conf.add_section('terminal')
font_desc = vt.get_font()
if font_desc is None:
font_size = self._font_size * Pango.SCALE
else:
font_size = font_desc.get_size()
font = self._get_conf(conf, 'font', 'Monospace')
font_desc = Pango.FontDescription(font)
font_desc.set_size(font_size)
vt.set_font(font_desc)
self._theme_colors = {"light": {'fg_color': '#000000',
'bg_color': '#FFFFFF'},
"dark": {'fg_color': '#FFFFFF',
'bg_color': '#000000'}}
fg_color = self._theme_colors[self._theme_state]['fg_color']
bg_color = self._theme_colors[self._theme_state]['bg_color']
try:
vt.set_colors(Gdk.color_parse(fg_color),
Gdk.color_parse(bg_color), [])
except TypeError:
# Vte 0.38 requires the colors set as a different type
# in Fedora 21 we get a exception
# TypeError: argument foreground: Expected Gdk.RGBA,
# but got gi.overrides.Gdk.Color
vt.set_colors(Gdk.RGBA(*Gdk.color_parse(fg_color).to_floats()),
Gdk.RGBA(*Gdk.color_parse(bg_color).to_floats()), [])
blink = self._get_conf(conf, 'cursor_blink', False)
vt.set_cursor_blink_mode(blink)
bell = self._get_conf(conf, 'bell', False)
vt.set_audible_bell(bell)
scrollback_lines = self._get_conf(conf, 'scrollback_lines', 1000)
vt.set_scrollback_lines(scrollback_lines)
vt.set_allow_bold(True)
scroll_key = self._get_conf(conf, 'scroll_on_keystroke', True)
vt.set_scroll_on_keystroke(scroll_key)
scroll_output = self._get_conf(conf, 'scroll_on_output', False)
vt.set_scroll_on_output(scroll_output)
if hasattr(vt, 'set_emulation'):
# set_emulation is not available after vte commit
# 4e253be9282829f594c8a55ca08d1299e80e471d
emulation = self._get_conf(conf, 'emulation', 'xterm')
vt.set_emulation(emulation)
if hasattr(vt, 'set_visible_bell'):
visible_bell = self._get_conf(conf, 'visible_bell', False)
vt.set_visible_bell(visible_bell)
conf.write(open(conf_file, 'w'))
| gpl-2.0 |
GehenHe/Recognize-Face-on-Android | tensorflow/contrib/distributions/python/ops/beta.py | 11 | 11466 | # 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.
# ==============================================================================
"""The Beta distribution class."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from tensorflow.contrib.distributions.python.ops import distribution
from tensorflow.contrib.distributions.python.ops import distribution_util
from tensorflow.contrib.distributions.python.ops import kullback_leibler
from tensorflow.contrib.framework.python.framework import tensor_util as contrib_tensor_util
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import ops
from tensorflow.python.framework import tensor_shape
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import check_ops
from tensorflow.python.ops import control_flow_ops
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import nn
from tensorflow.python.ops import random_ops
_beta_prob_note = """
Note that the argument `x` must be a non-negative floating point tensor
whose shape can be broadcast with `self.a` and `self.b`. For fixed leading
dimensions, the last dimension represents counts for the corresponding Beta
distribution in `self.a` and `self.b`. `x` is only legal if `0 < x < 1`.
"""
class Beta(distribution.Distribution):
"""Beta distribution.
This distribution is parameterized by `a` and `b` which are shape
parameters.
#### Mathematical details
The Beta is a distribution over the interval (0, 1).
The distribution has hyperparameters `a` and `b` and
probability mass function (pdf):
```pdf(x) = 1 / Beta(a, b) * x^(a - 1) * (1 - x)^(b - 1)```
where `Beta(a, b) = Gamma(a) * Gamma(b) / Gamma(a + b)`
is the beta function.
This class provides methods to create indexed batches of Beta
distributions. One entry of the broadcasted
shape represents of `a` and `b` represents one single Beta distribution.
When calling distribution functions (e.g. `dist.pdf(x)`), `a`, `b`
and `x` are broadcast to the same shape (if possible).
Every entry in a/b/x corresponds to a single Beta distribution.
#### Examples
Creates 3 distributions.
The distribution functions can be evaluated on x.
```python
a = [1, 2, 3]
b = [1, 2, 3]
dist = Beta(a, b)
```
```python
# x same shape as a.
x = [.2, .3, .7]
dist.pdf(x) # Shape [3]
# a/b will be broadcast to [[1, 2, 3], [1, 2, 3]] to match x.
x = [[.1, .4, .5], [.2, .3, .5]]
dist.pdf(x) # Shape [2, 3]
# a/b will be broadcast to shape [5, 7, 3] to match x.
x = [[...]] # Shape [5, 7, 3]
dist.pdf(x) # Shape [5, 7, 3]
```
Creates a 2-batch of 3-class distributions.
```python
a = [[1, 2, 3], [4, 5, 6]] # Shape [2, 3]
b = 5 # Shape []
dist = Beta(a, b)
# x will be broadcast to [[.2, .3, .9], [.2, .3, .9]] to match a/b.
x = [.2, .3, .9]
dist.pdf(x) # Shape [2]
```
"""
def __init__(self, a, b, validate_args=False, allow_nan_stats=True,
name="Beta"):
"""Initialize a batch of Beta distributions.
Args:
a: Positive floating point tensor with shape broadcastable to
`[N1,..., Nm]` `m >= 0`. Defines this as a batch of `N1 x ... x Nm`
different Beta distributions. This also defines the
dtype of the distribution.
b: Positive floating point tensor with shape broadcastable to
`[N1,..., Nm]` `m >= 0`. Defines this as a batch of `N1 x ... x Nm`
different Beta distributions.
validate_args: `Boolean`, default `False`. Whether to assert valid
values for parameters `a`, `b`, and `x` in `prob` and `log_prob`.
If `False` and inputs are invalid, correct behavior is not guaranteed.
allow_nan_stats: `Boolean`, default `True`. If `False`, raise an
exception if a statistic (e.g. mean/mode/etc...) is undefined for any
batch member. If `True`, batch members with valid parameters leading to
undefined statistics will return NaN for this statistic.
name: The name to prefix Ops created by this distribution class.
Examples:
```python
# Define 1-batch.
dist = Beta(1.1, 2.0)
# Define a 2-batch.
dist = Beta([1.0, 2.0], [4.0, 5.0])
```
"""
parameters = locals()
parameters.pop("self")
with ops.name_scope(name, values=[a, b]) as ns:
with ops.control_dependencies([
check_ops.assert_positive(a),
check_ops.assert_positive(b),
] if validate_args else []):
self._a = array_ops.identity(a, name="a")
self._b = array_ops.identity(b, name="b")
contrib_tensor_util.assert_same_float_dtype((self._a, self._b))
# Used for mean/mode/variance/entropy/sampling computations
self._a_b_sum = self._a + self._b
super(Beta, self).__init__(
dtype=self._a_b_sum.dtype,
validate_args=validate_args,
allow_nan_stats=allow_nan_stats,
is_continuous=True,
is_reparameterized=False,
parameters=parameters,
graph_parents=[self._a, self._b, self._a_b_sum],
name=ns)
@staticmethod
def _param_shapes(sample_shape):
return dict(
zip(("a", "b"), ([ops.convert_to_tensor(
sample_shape, dtype=dtypes.int32)] * 2)))
@property
def a(self):
"""Shape parameter."""
return self._a
@property
def b(self):
"""Shape parameter."""
return self._b
@property
def a_b_sum(self):
"""Sum of parameters."""
return self._a_b_sum
def _batch_shape(self):
return array_ops.shape(self.a_b_sum)
def _get_batch_shape(self):
return self.a_b_sum.get_shape()
def _event_shape(self):
return constant_op.constant([], dtype=dtypes.int32)
def _get_event_shape(self):
return tensor_shape.scalar()
def _sample_n(self, n, seed=None):
a = array_ops.ones_like(self.a_b_sum, dtype=self.dtype) * self.a
b = array_ops.ones_like(self.a_b_sum, dtype=self.dtype) * self.b
gamma1_sample = random_ops.random_gamma(
[n,], a, dtype=self.dtype, seed=seed)
gamma2_sample = random_ops.random_gamma(
[n,], b, dtype=self.dtype,
seed=distribution_util.gen_new_seed(seed, "beta"))
beta_sample = gamma1_sample / (gamma1_sample + gamma2_sample)
return beta_sample
def _log_prob(self, x):
x = self._assert_valid_sample(x)
log_unnormalized_prob = ((self.a - 1.) * math_ops.log(x) +
(self.b - 1.) * math_ops.log(1. - x))
log_normalization = (math_ops.lgamma(self.a) +
math_ops.lgamma(self.b) -
math_ops.lgamma(self.a_b_sum))
return log_unnormalized_prob - log_normalization
@distribution_util.AppendDocstring(_beta_prob_note)
def _prob(self, x):
return math_ops.exp(self._log_prob(x))
@distribution_util.AppendDocstring(_beta_prob_note)
def _log_cdf(self, x):
return math_ops.log(self._cdf(x))
def _cdf(self, x):
return math_ops.betainc(self.a, self.b, x)
def _entropy(self):
return (math_ops.lgamma(self.a) -
(self.a - 1.) * math_ops.digamma(self.a) +
math_ops.lgamma(self.b) -
(self.b - 1.) * math_ops.digamma(self.b) -
math_ops.lgamma(self.a_b_sum) +
(self.a_b_sum - 2.) * math_ops.digamma(self.a_b_sum))
def _mean(self):
return self.a / self.a_b_sum
def _variance(self):
return (self.a * self.b) / (self.a_b_sum**2. * (self.a_b_sum + 1.))
def _std(self):
return math_ops.sqrt(self.variance())
@distribution_util.AppendDocstring(
"""Note that the mode for the Beta distribution is only defined
when `a > 1`, `b > 1`. This returns the mode when `a > 1` and `b > 1`,
and `NaN` otherwise. If `self.allow_nan_stats` is `False`, an exception
will be raised rather than returning `NaN`.""")
def _mode(self):
mode = (self.a - 1.)/ (self.a_b_sum - 2.)
if self.allow_nan_stats:
nan = np.array(np.nan, dtype=self.dtype.as_numpy_dtype())
return array_ops.where(
math_ops.logical_and(
math_ops.greater(self.a, 1.),
math_ops.greater(self.b, 1.)),
mode,
array_ops.fill(self.batch_shape(), nan, name="nan"))
else:
return control_flow_ops.with_dependencies([
check_ops.assert_less(
array_ops.ones((), dtype=self.dtype), self.a,
message="Mode not defined for components of a <= 1."),
check_ops.assert_less(
array_ops.ones((), dtype=self.dtype), self.b,
message="Mode not defined for components of b <= 1."),
], mode)
def _assert_valid_sample(self, x):
"""Check x for proper shape, values, then return tensor version."""
if not self.validate_args: return x
return control_flow_ops.with_dependencies([
check_ops.assert_positive(
x,
message="Negative events lie outside Beta distribution support."),
check_ops.assert_less(
x, array_ops.ones((), self.dtype),
message="Event>=1 lies outside Beta distribution support."),
], x)
class BetaWithSoftplusAB(Beta):
"""Beta with softplus transform on `a` and `b`."""
def __init__(self,
a,
b,
validate_args=False,
allow_nan_stats=True,
name="BetaWithSoftplusAB"):
parameters = locals()
parameters.pop("self")
with ops.name_scope(name, values=[a, b]) as ns:
super(BetaWithSoftplusAB, self).__init__(
a=nn.softplus(a, name="softplus_a"),
b=nn.softplus(b, name="softplus_b"),
validate_args=validate_args,
allow_nan_stats=allow_nan_stats,
name=ns)
self._parameters = parameters
@kullback_leibler.RegisterKL(Beta, Beta)
def _kl_beta_beta(d1, d2, name=None):
"""Calculate the batched KL divergence KL(d1 || d2) with d1 and d2 Beta.
Args:
d1: instance of a Beta distribution object.
d2: instance of a Beta distribution object.
name: (optional) Name to use for created operations.
default is "kl_beta_beta".
Returns:
Batchwise KL(d1 || d2)
"""
inputs = [d1.a, d1.b, d1.a_b_sum, d2.a_b_sum]
with ops.name_scope(name, "kl_beta_beta", inputs):
# ln(B(a', b') / B(a, b))
log_betas = (math_ops.lgamma(d2.a) + math_ops.lgamma(d2.b)
- math_ops.lgamma(d2.a_b_sum) + math_ops.lgamma(d1.a_b_sum)
- math_ops.lgamma(d1.a) - math_ops.lgamma(d1.b))
# (a - a')*psi(a) + (b - b')*psi(b) + (a' - a + b' - b)*psi(a + b)
digammas = ((d1.a - d2.a)*math_ops.digamma(d1.a)
+ (d1.b - d2.b)*math_ops.digamma(d1.b)
+ (d2.a_b_sum - d1.a_b_sum)*math_ops.digamma(d1.a_b_sum))
return log_betas + digammas
| apache-2.0 |
zenodo/zenodo | zenodo/modules/records/serializers/schemas/pidrelations.py | 7 | 1981 | # -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2017 CERN.
#
# Invenio 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.
#
# Invenio 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 Invenio; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
# MA 02111-1307, USA.
#
# In applying this license, CERN does not
# waive the privileges and immunities granted to it by virtue of its status
# as an Intergovernmental Organization or submit itself to any jurisdiction.
"""PID Version relation schemas."""
from invenio_pidrelations.serializers.schemas import RelationSchema
from marshmallow import fields
class VersionRelation(RelationSchema):
"""PID version relation schema."""
count = fields.Method('dump_count')
last_child = fields.Method('dump_last_child')
draft_child_deposit = fields.Method('dump_draft_child_deposit')
def dump_count(self, obj):
"""Dump the number of children."""
return obj.children.count()
def dump_last_child(self, obj):
"""Dump the last child."""
if obj.is_ordered:
return self._dump_relative(obj.last_child)
def dump_draft_child_deposit(self, obj):
"""Dump the deposit of the draft child."""
if obj.draft_child_deposit:
return self._dump_relative(obj.draft_child_deposit)
class Meta:
"""Meta fields of the schema."""
fields = ('parent', 'is_last', 'index', 'last_child', 'count',
'draft_child_deposit')
| gpl-2.0 |
leohmoraes/weblate | weblate/trans/machine/base.py | 4 | 7113 | # -*- coding: utf-8 -*-
#
# Copyright Β© 2012 - 2015 Michal ΔihaΕ <[email protected]>
#
# This file is part of Weblate <http://weblate.org/>
#
# 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/>.
#
'''
Base code for machine translation services.
'''
from django.core.cache import cache
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
import sys
import json
import urllib
import urllib2
import weblate
from weblate.trans.util import report_error
class MachineTranslationError(Exception):
'''
Generic Machine translation error.
'''
class MissingConfiguration(ImproperlyConfigured):
'''
Exception raised when configuraiton is wrong.
'''
class MachineTranslation(object):
'''
Generic object for machine translation services.
'''
name = 'MT'
default_languages = []
def __init__(self):
'''
Creates new machine translation object.
'''
self.mtid = self.name.lower().replace(' ', '-')
self.request_url = None
self.request_params = None
def authenticate(self, request):
'''
Hook for backends to allow add authentication headers to request.
'''
return
def json_req(self, url, http_post=False, skip_auth=False, **kwargs):
'''
Performs JSON request.
'''
# Encode params
if len(kwargs) > 0:
params = urllib.urlencode(kwargs)
else:
params = ''
# Store for exception handling
self.request_url = url
self.request_params = params
# Append parameters
if len(params) > 0 and not http_post:
url = '%s?%s' % (url, params)
# Create request object with custom headers
request = urllib2.Request(url)
request.timeout = 0.5
request.add_header('User-Agent', weblate.USER_AGENT)
# Optional authentication
if not skip_auth:
self.authenticate(request)
# Fire request
if http_post:
handle = urllib2.urlopen(request, params)
else:
handle = urllib2.urlopen(request)
# Read and possibly convert response
text = handle.read()
# Needed for Microsoft
if text.startswith('\xef\xbb\xbf'):
text = text.decode('UTF-8-sig')
# Replace literal \t
text = text.replace(
'\t', '\\t'
).replace(
'\r', '\\r'
)
# Needed for Google
while ',,' in text or '[,' in text:
text = text.replace(',,', ',null,').replace('[,', '[')
# Parse JSON
response = json.loads(text)
# Return data
return response
def json_status_req(self, url, http_post=False, skip_auth=False, **kwargs):
'''
Performs JSON request with checking response status.
'''
# Perform request
response = self.json_req(url, http_post, skip_auth, **kwargs)
# Check response status
if response['responseStatus'] != 200:
raise MachineTranslationError(response['responseDetails'])
# Return data
return response
def download_languages(self):
'''
Downloads list of supported languages from a service.
'''
return []
def download_translations(self, language, text, unit, user):
'''
Downloads list of possible translations from a service.
Should return tuple - (translation text, translation quality, source of
translation, source string).
You can use self.name as source of translation, if you can not give
better hint and text parameter as source string if you do no fuzzy
matching.
'''
raise NotImplementedError()
def convert_language(self, language):
'''
Converts language to service specific code.
'''
return language
@property
def supported_languages(self):
'''
Returns list of supported languages.
'''
cache_key = '%s-languages' % self.mtid
# Try using list from cache
languages = cache.get(cache_key)
if languages is not None:
return languages
# Download
try:
languages = self.download_languages()
except Exception as exc:
report_error(
exc, sys.exc_info(),
{'mt_url': self.request_url, 'mt_params': self.request_params}
)
weblate.logger.error(
'Failed to fetch languages from %s, using defaults',
self.name,
)
weblate.logger.error(
'Last fetched URL: %s, params: %s',
self.request_url,
self.request_params,
)
if settings.DEBUG:
raise
return self.default_languages
# Update cache
cache.set(cache_key, languages, 3600 * 48)
return languages
def is_supported(self, language):
'''
Checks whether given language combination is supported.
'''
return language in self.supported_languages
def translate(self, language, text, unit, user):
'''
Returns list of machine translations.
'''
language = self.convert_language(language)
if text == '':
return []
if not self.is_supported(language):
return []
try:
translations = self.download_translations(
language, text, unit, user
)
return [
{
'text': trans[0],
'quality': trans[1],
'service': trans[2],
'source': trans[3]
}
for trans in translations
]
except Exception as exc:
report_error(
exc, sys.exc_info(),
{'mt_url': self.request_url, 'mt_params': self.request_params}
)
weblate.logger.error(
'Failed to fetch translations from %s',
self.name,
)
weblate.logger.error(
'Last fetched URL: %s, params: %s',
self.request_url,
self.request_params,
)
raise MachineTranslationError('{}: {}'.format(
exc.__class__.__name__,
str(exc)
))
| gpl-3.0 |
jackkiej/SickRage | lib/sqlalchemy/interfaces.py | 79 | 10918 | # sqlalchemy/interfaces.py
# Copyright (C) 2007-2014 the SQLAlchemy authors and contributors <see AUTHORS file>
# Copyright (C) 2007 Jason Kirtland [email protected]
#
# This module is part of SQLAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
"""Deprecated core event interfaces.
This module is **deprecated** and is superseded by the
event system.
"""
from . import event, util
class PoolListener(object):
"""Hooks into the lifecycle of connections in a :class:`.Pool`.
.. note::
:class:`.PoolListener` is deprecated. Please
refer to :class:`.PoolEvents`.
Usage::
class MyListener(PoolListener):
def connect(self, dbapi_con, con_record):
'''perform connect operations'''
# etc.
# create a new pool with a listener
p = QueuePool(..., listeners=[MyListener()])
# add a listener after the fact
p.add_listener(MyListener())
# usage with create_engine()
e = create_engine("url://", listeners=[MyListener()])
All of the standard connection :class:`~sqlalchemy.pool.Pool` types can
accept event listeners for key connection lifecycle events:
creation, pool check-out and check-in. There are no events fired
when a connection closes.
For any given DB-API connection, there will be one ``connect``
event, `n` number of ``checkout`` events, and either `n` or `n - 1`
``checkin`` events. (If a ``Connection`` is detached from its
pool via the ``detach()`` method, it won't be checked back in.)
These are low-level events for low-level objects: raw Python
DB-API connections, without the conveniences of the SQLAlchemy
``Connection`` wrapper, ``Dialect`` services or ``ClauseElement``
execution. If you execute SQL through the connection, explicitly
closing all cursors and other resources is recommended.
Events also receive a ``_ConnectionRecord``, a long-lived internal
``Pool`` object that basically represents a "slot" in the
connection pool. ``_ConnectionRecord`` objects have one public
attribute of note: ``info``, a dictionary whose contents are
scoped to the lifetime of the DB-API connection managed by the
record. You can use this shared storage area however you like.
There is no need to subclass ``PoolListener`` to handle events.
Any class that implements one or more of these methods can be used
as a pool listener. The ``Pool`` will inspect the methods
provided by a listener object and add the listener to one or more
internal event queues based on its capabilities. In terms of
efficiency and function call overhead, you're much better off only
providing implementations for the hooks you'll be using.
"""
@classmethod
def _adapt_listener(cls, self, listener):
"""Adapt a :class:`.PoolListener` to individual
:class:`event.Dispatch` events.
"""
listener = util.as_interface(listener, methods=('connect',
'first_connect', 'checkout', 'checkin'))
if hasattr(listener, 'connect'):
event.listen(self, 'connect', listener.connect)
if hasattr(listener, 'first_connect'):
event.listen(self, 'first_connect', listener.first_connect)
if hasattr(listener, 'checkout'):
event.listen(self, 'checkout', listener.checkout)
if hasattr(listener, 'checkin'):
event.listen(self, 'checkin', listener.checkin)
def connect(self, dbapi_con, con_record):
"""Called once for each new DB-API connection or Pool's ``creator()``.
dbapi_con
A newly connected raw DB-API connection (not a SQLAlchemy
``Connection`` wrapper).
con_record
The ``_ConnectionRecord`` that persistently manages the connection
"""
def first_connect(self, dbapi_con, con_record):
"""Called exactly once for the first DB-API connection.
dbapi_con
A newly connected raw DB-API connection (not a SQLAlchemy
``Connection`` wrapper).
con_record
The ``_ConnectionRecord`` that persistently manages the connection
"""
def checkout(self, dbapi_con, con_record, con_proxy):
"""Called when a connection is retrieved from the Pool.
dbapi_con
A raw DB-API connection
con_record
The ``_ConnectionRecord`` that persistently manages the connection
con_proxy
The ``_ConnectionFairy`` which manages the connection for the span of
the current checkout.
If you raise an ``exc.DisconnectionError``, the current
connection will be disposed and a fresh connection retrieved.
Processing of all checkout listeners will abort and restart
using the new connection.
"""
def checkin(self, dbapi_con, con_record):
"""Called when a connection returns to the pool.
Note that the connection may be closed, and may be None if the
connection has been invalidated. ``checkin`` will not be called
for detached connections. (They do not return to the pool.)
dbapi_con
A raw DB-API connection
con_record
The ``_ConnectionRecord`` that persistently manages the connection
"""
class ConnectionProxy(object):
"""Allows interception of statement execution by Connections.
.. note::
:class:`.ConnectionProxy` is deprecated. Please
refer to :class:`.ConnectionEvents`.
Either or both of the ``execute()`` and ``cursor_execute()``
may be implemented to intercept compiled statement and
cursor level executions, e.g.::
class MyProxy(ConnectionProxy):
def execute(self, conn, execute, clauseelement,
*multiparams, **params):
print "compiled statement:", clauseelement
return execute(clauseelement, *multiparams, **params)
def cursor_execute(self, execute, cursor, statement,
parameters, context, executemany):
print "raw statement:", statement
return execute(cursor, statement, parameters, context)
The ``execute`` argument is a function that will fulfill the default
execution behavior for the operation. The signature illustrated
in the example should be used.
The proxy is installed into an :class:`~sqlalchemy.engine.Engine` via
the ``proxy`` argument::
e = create_engine('someurl://', proxy=MyProxy())
"""
@classmethod
def _adapt_listener(cls, self, listener):
def adapt_execute(conn, clauseelement, multiparams, params):
def execute_wrapper(clauseelement, *multiparams, **params):
return clauseelement, multiparams, params
return listener.execute(conn, execute_wrapper,
clauseelement, *multiparams,
**params)
event.listen(self, 'before_execute', adapt_execute)
def adapt_cursor_execute(conn, cursor, statement,
parameters, context, executemany):
def execute_wrapper(
cursor,
statement,
parameters,
context,
):
return statement, parameters
return listener.cursor_execute(
execute_wrapper,
cursor,
statement,
parameters,
context,
executemany,
)
event.listen(self, 'before_cursor_execute', adapt_cursor_execute)
def do_nothing_callback(*arg, **kw):
pass
def adapt_listener(fn):
def go(conn, *arg, **kw):
fn(conn, do_nothing_callback, *arg, **kw)
return util.update_wrapper(go, fn)
event.listen(self, 'begin', adapt_listener(listener.begin))
event.listen(self, 'rollback',
adapt_listener(listener.rollback))
event.listen(self, 'commit', adapt_listener(listener.commit))
event.listen(self, 'savepoint',
adapt_listener(listener.savepoint))
event.listen(self, 'rollback_savepoint',
adapt_listener(listener.rollback_savepoint))
event.listen(self, 'release_savepoint',
adapt_listener(listener.release_savepoint))
event.listen(self, 'begin_twophase',
adapt_listener(listener.begin_twophase))
event.listen(self, 'prepare_twophase',
adapt_listener(listener.prepare_twophase))
event.listen(self, 'rollback_twophase',
adapt_listener(listener.rollback_twophase))
event.listen(self, 'commit_twophase',
adapt_listener(listener.commit_twophase))
def execute(self, conn, execute, clauseelement, *multiparams, **params):
"""Intercept high level execute() events."""
return execute(clauseelement, *multiparams, **params)
def cursor_execute(self, execute, cursor, statement, parameters,
context, executemany):
"""Intercept low-level cursor execute() events."""
return execute(cursor, statement, parameters, context)
def begin(self, conn, begin):
"""Intercept begin() events."""
return begin()
def rollback(self, conn, rollback):
"""Intercept rollback() events."""
return rollback()
def commit(self, conn, commit):
"""Intercept commit() events."""
return commit()
def savepoint(self, conn, savepoint, name=None):
"""Intercept savepoint() events."""
return savepoint(name=name)
def rollback_savepoint(self, conn, rollback_savepoint, name, context):
"""Intercept rollback_savepoint() events."""
return rollback_savepoint(name, context)
def release_savepoint(self, conn, release_savepoint, name, context):
"""Intercept release_savepoint() events."""
return release_savepoint(name, context)
def begin_twophase(self, conn, begin_twophase, xid):
"""Intercept begin_twophase() events."""
return begin_twophase(xid)
def prepare_twophase(self, conn, prepare_twophase, xid):
"""Intercept prepare_twophase() events."""
return prepare_twophase(xid)
def rollback_twophase(self, conn, rollback_twophase, xid, is_prepared):
"""Intercept rollback_twophase() events."""
return rollback_twophase(xid, is_prepared)
def commit_twophase(self, conn, commit_twophase, xid, is_prepared):
"""Intercept commit_twophase() events."""
return commit_twophase(xid, is_prepared)
| gpl-3.0 |
defance/edx-platform | lms/djangoapps/lti_provider/views.py | 94 | 5813 | """
LTI Provider view functions
"""
from django.conf import settings
from django.http import HttpResponseBadRequest, HttpResponseForbidden, Http404
from django.views.decorators.csrf import csrf_exempt
import logging
from lti_provider.outcomes import store_outcome_parameters
from lti_provider.models import LtiConsumer
from lti_provider.signature_validator import SignatureValidator
from lti_provider.users import authenticate_lti_user
from lms_xblock.runtime import unquote_slashes
from opaque_keys.edx.keys import CourseKey, UsageKey
from opaque_keys import InvalidKeyError
log = logging.getLogger("edx.lti_provider")
# LTI launch parameters that must be present for a successful launch
REQUIRED_PARAMETERS = [
'roles', 'context_id', 'oauth_version', 'oauth_consumer_key',
'oauth_signature', 'oauth_signature_method', 'oauth_timestamp',
'oauth_nonce', 'user_id'
]
OPTIONAL_PARAMETERS = [
'lis_result_sourcedid', 'lis_outcome_service_url',
'tool_consumer_instance_guid'
]
@csrf_exempt
def lti_launch(request, course_id, usage_id):
"""
Endpoint for all requests to embed edX content via the LTI protocol. This
endpoint will be called by a POST message that contains the parameters for
an LTI launch (we support version 1.2 of the LTI specification):
http://www.imsglobal.org/lti/ltiv1p2/ltiIMGv1p2.html
An LTI launch is successful if:
- The launch contains all the required parameters
- The launch data is correctly signed using a known client key/secret
pair
"""
if not settings.FEATURES['ENABLE_LTI_PROVIDER']:
return HttpResponseForbidden()
# Check the LTI parameters, and return 400 if any required parameters are
# missing
params = get_required_parameters(request.POST)
if not params:
return HttpResponseBadRequest()
params.update(get_optional_parameters(request.POST))
# Get the consumer information from either the instance GUID or the consumer
# key
try:
lti_consumer = LtiConsumer.get_or_supplement(
params.get('tool_consumer_instance_guid', None),
params['oauth_consumer_key']
)
except LtiConsumer.DoesNotExist:
return HttpResponseForbidden()
# Check the OAuth signature on the message
if not SignatureValidator(lti_consumer).verify(request):
return HttpResponseForbidden()
# Add the course and usage keys to the parameters array
try:
course_key, usage_key = parse_course_and_usage_keys(course_id, usage_id)
except InvalidKeyError:
log.error(
'Invalid course key %s or usage key %s from request %s',
course_id,
usage_id,
request
)
raise Http404()
params['course_key'] = course_key
params['usage_key'] = usage_key
# Create an edX account if the user identifed by the LTI launch doesn't have
# one already, and log the edX account into the platform.
authenticate_lti_user(request, params['user_id'], lti_consumer)
# Store any parameters required by the outcome service in order to report
# scores back later. We know that the consumer exists, since the record was
# used earlier to verify the oauth signature.
store_outcome_parameters(params, request.user, lti_consumer)
return render_courseware(request, params['usage_key'])
def get_required_parameters(dictionary, additional_params=None):
"""
Extract all required LTI parameters from a dictionary and verify that none
are missing.
:param dictionary: The dictionary that should contain all required parameters
:param additional_params: Any expected parameters, beyond those required for
the LTI launch.
:return: A new dictionary containing all the required parameters from the
original dictionary and additional parameters, or None if any expected
parameters are missing.
"""
params = {}
additional_params = additional_params or []
for key in REQUIRED_PARAMETERS + additional_params:
if key not in dictionary:
return None
params[key] = dictionary[key]
return params
def get_optional_parameters(dictionary):
"""
Extract all optional LTI parameters from a dictionary. This method does not
fail if any parameters are missing.
:param dictionary: A dictionary containing zero or more optional parameters.
:return: A new dictionary containing all optional parameters from the
original dictionary, or an empty dictionary if no optional parameters
were present.
"""
return {key: dictionary[key] for key in OPTIONAL_PARAMETERS if key in dictionary}
def render_courseware(request, usage_key):
"""
Render the content requested for the LTI launch.
TODO: This method depends on the current refactoring work on the
courseware/courseware.html template. It's signature may change depending on
the requirements for that template once the refactoring is complete.
Return an HttpResponse object that contains the template and necessary
context to render the courseware.
"""
# return an HttpResponse object that contains the template and necessary context to render the courseware.
from courseware.views import render_xblock
return render_xblock(request, unicode(usage_key), check_if_enrolled=False)
def parse_course_and_usage_keys(course_id, usage_id):
"""
Convert course and usage ID strings into key objects. Return a tuple of
(course_key, usage_key), or throw an InvalidKeyError if the translation
fails.
"""
course_key = CourseKey.from_string(course_id)
usage_id = unquote_slashes(usage_id)
usage_key = UsageKey.from_string(usage_id).map_into_course(course_key)
return course_key, usage_key
| agpl-3.0 |
projectcalico/calico-nova | nova/db/migration.py | 6 | 2212 | # Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# 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.
"""Database setup and migration commands."""
from nova import utils
IMPL = utils.LazyPluggable('backend',
config_group='database',
sqlalchemy='nova.db.sqlalchemy.migration')
def db_sync(version=None):
"""Migrate the database to `version` or the most recent version."""
return IMPL.db_sync(version=version)
def db_version():
"""Display the current database version."""
return IMPL.db_version()
def db_initial_version():
"""The starting version for the database."""
return IMPL.db_initial_version()
def db_null_instance_uuid_scan(delete=False):
"""Utility for scanning the database to look for NULL instance uuid rows.
Scans the backing nova database to look for table entries where
instances.uuid or instance_uuid columns are NULL (except for the
fixed_ips table since that can contain NULL instance_uuid entries by
design). Dumps the tables that have NULL instance_uuid entries or
optionally deletes them based on usage.
This tool is meant to be used in conjunction with the 267 database
migration script to detect and optionally cleanup NULL instance_uuid
records.
:param delete: If true, delete NULL instance_uuid records found, else
just query to see if they exist for reporting.
:returns: dict of table name to number of hits for NULL instance_uuid rows.
"""
return IMPL.db_null_instance_uuid_scan(delete=delete)
| apache-2.0 |
losnikitos/googleads-python-lib | examples/dfp/v201502/user_team_association_service/delete_user_team_associations.py | 4 | 2762 | #!/usr/bin/python
#
# Copyright 2015 Google Inc. 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.
"""This example removes the user from all its teams.
To determine which users exist, run get_all_users.py.
The LoadFromStorage method is pulling credentials and properties from a
"googleads.yaml" file. By default, it looks for this file in your home
directory. For more information, see the "Caching authentication information"
section of our README.
"""
# Import appropriate modules from the client library.
from googleads import dfp
USER_ID = 'INSERT_USER_ID_HERE'
def main(client, user_id):
# Initialize appropriate service.
user_team_association_service = client.GetService(
'UserTeamAssociationService', version='v201502')
# Create filter text to select user team associations by the user ID.
values = [{
'key': 'userId',
'value': {
'xsi_type': 'NumberValue',
'value': user_id
}
}]
query = 'WHERE userId = :userId'
# Create a filter statement.
statement = dfp.FilterStatement(query, values)
# Get user team associations by statement.
response = user_team_association_service.getUserTeamAssociationsByStatement(
statement.ToStatement())
user_team_associations = response['results'] if 'results' in response else []
for user_team_association in user_team_associations:
print ('User team association between user with ID \'%s\' and team with '
'ID \'%s\' will be deleted.' % (user_team_association['userId'],
user_team_association['teamId']))
print ('Number of teams that the user will be removed from: %s' %
len(user_team_associations))
# Perform action.
result = user_team_association_service.performUserTeamAssociationAction(
{'xsi_type': 'DeleteUserTeamAssociations'},
{'query': query, 'values': values})
# Display results.
if result and int(result['numChanges']) > 0:
print ('Number of teams that the user was removed from: %s'
% result['numChanges'])
else:
print 'No user team associations were deleted.'
if __name__ == '__main__':
# Initialize client object.
dfp_client = dfp.DfpClient.LoadFromStorage()
main(dfp_client, USER_ID)
| apache-2.0 |
ennoborg/gramps | gramps/plugins/gramplet/calendargramplet.py | 2 | 2757 | # Gramps - a GTK+/GNOME based genealogy program
#
# Copyright (C) 2007-2009 Douglas S. Blank <[email protected]>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#------------------------------------------------------------------------
#
# Gtk modules
#
#------------------------------------------------------------------------
from gi.repository import Gtk
#------------------------------------------------------------------------
#
# Gramps modules
#
#------------------------------------------------------------------------
from gramps.gen.plug import Gramplet
from gramps.gui.plug.quick import run_quick_report_by_name
from gramps.gen.lib import Date
from gramps.gen.const import GRAMPS_LOCALE as glocale
_ = glocale.translation.sgettext
#------------------------------------------------------------------------
#
# CalendarGramplet class
#
#------------------------------------------------------------------------
class CalendarGramplet(Gramplet):
"""
Gramplet showing a calendar of events.
"""
def init(self):
self.set_tooltip(_("Double-click a day for details"))
self.gui.calendar = Gtk.Calendar()
self.gui.calendar.connect('day-selected-double-click',
self.double_click)
self.gui.calendar.set_display_options(
Gtk.CalendarDisplayOptions.SHOW_HEADING)
self.gui.get_container_widget().remove(self.gui.textview)
vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
vbox.pack_start(self.gui.calendar, False, False, 0)
self.gui.get_container_widget().add(vbox)
vbox.show_all()
def post_init(self):
self.disconnect("active-changed")
def double_click(self, obj):
"""
Bring up events on this day.
"""
year, month, day = self.gui.calendar.get_date()
date = Date()
date.set_yr_mon_day(year, month + 1, day)
run_quick_report_by_name(self.gui.dbstate,
self.gui.uistate,
'onthisday',
date)
| gpl-2.0 |
bathepawan/workload-automation | wlauto/workloads/power_loadtest/__init__.py | 5 | 4947 | # Copyright 2015 ARM Limited
#
# 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.
#
# pylint: disable=attribute-defined-outside-init
import os
import re
from wlauto import Workload, Parameter
from wlauto.exceptions import WorkloadError
from wlauto.utils.misc import which, check_output
from wlauto.utils.types import arguments, numeric
# Location of the power_LoadTest under the chroot
#POWER_LOADTEST_DIR = '/mnt/host/source/src/third_party/autotest/files/client/site_tests/power_LoadTest'
MARKER = '---------------------------'
STATUS_REGEX = re.compile(r'^\S+\s+\[\s*(\S+)\s*\]')
METRIC_REGEX = re.compile(r'^\S+\s+(\S+)\s*(\S+)')
class PowerLoadtest(Workload):
name = 'power_loadtest'
description = '''
power_LoadTest (part of ChromeOS autotest suite) continuously cycles through a set of
browser-based activities and monitors battery drain on a device.
.. note:: This workload *must* be run inside a CromeOS SDK chroot.
See: https://www.chromium.org/chromium-os/testing/power-testing
'''
supported_platforms = ['chromeos']
parameters = [
Parameter('board', default=os.getenv('BOARD'),
description='''
The name of the board to be used for the test. If this is not specified,
BOARD environment variable will be used.
'''),
Parameter('variant',
description='''
The variant of the test to run; If not specified, the full power_LoadTest will
run (until the device battery is drained). The only other variant available in the
vanilla test is "1hour", but further variants may be added by providing custom
control files.
'''),
Parameter('test_that_args', kind=arguments, default='',
description='''
Extra arguments to be passed to test_that_invocation.
'''),
Parameter('run_timeout', kind=int, default=24 * 60 * 60,
description='''
Timeout, in seconds, for the test execution.
'''),
]
def setup(self, context):
if self.device.platform != 'chromeos':
raise WorkloadError('{} only supports ChromeOS devices'.format(self.name))
self.test_that = which('test_that')
if not self.test_that:
message = ('Could not find "test_that"; {} must be running in a ChromeOS SDK chroot '
'(did you execute "cros_sdk"?)')
raise WorkloadError(message.format(self.name))
self.command = self._build_command()
self.raw_output = None
# make sure no other test is running
self.device.execute('killall -9 autotest', check_exit_code=False)
def run(self, context):
self.logger.debug(self.command)
self.raw_output, _ = check_output(self.command, timeout=self.run_timeout, shell=True)
def update_result(self, context):
if not self.raw_output:
self.logger.warning('No power_LoadTest output detected; run failed?')
return
raw_outfile = os.path.join(context.output_directory, 'power_loadtest.raw')
with open(raw_outfile, 'w') as wfh:
wfh.write(self.raw_output)
context.add_artifact('power_LoadTest_raw', raw_outfile, kind='raw')
lines = iter(self.raw_output.split('\n'))
# Results are delimitted from the rest of the output by MARKER
for line in lines:
if MARKER in line:
break
for line in lines:
match = STATUS_REGEX.search(line)
if match:
status = match.group(1)
if status != 'PASSED':
self.logger.warning(line)
match = METRIC_REGEX.search(line)
if match:
try:
context.result.add_metric(match.group(1), numeric(match.group(2)), lower_is_better=True)
except ValueError:
pass # non-numeric metrics aren't supported
def _build_command(self):
test_name = 'power_LoadTest'
if self.variant:
test_name += '.' + self.variant
parts = [self.test_that, self.device.host, test_name]
if self.board:
parts.append('-b {}'.format(self.board))
parts.append(str(self.test_that_args))
return ' '.join(parts)
| apache-2.0 |
andyzsf/django | tests/resolve_url/tests.py | 33 | 2850 | from __future__ import unicode_literals
import warnings
from django.core.urlresolvers import NoReverseMatch
from django.contrib.auth.views import logout
from django.shortcuts import resolve_url
from django.test import TestCase, override_settings
from django.utils.deprecation import RemovedInDjango20Warning
from .models import UnimportantThing
@override_settings(ROOT_URLCONF='resolve_url.urls')
class ResolveUrlTests(TestCase):
"""
Tests for the ``resolve_url`` function.
"""
def test_url_path(self):
"""
Tests that passing a URL path to ``resolve_url`` will result in the
same url.
"""
self.assertEqual('/something/', resolve_url('/something/'))
def test_relative_path(self):
"""
Tests that passing a relative URL path to ``resolve_url`` will result
in the same url.
"""
self.assertEqual('../', resolve_url('../'))
self.assertEqual('../relative/', resolve_url('../relative/'))
self.assertEqual('./', resolve_url('./'))
self.assertEqual('./relative/', resolve_url('./relative/'))
def test_full_url(self):
"""
Tests that passing a full URL to ``resolve_url`` will result in the
same url.
"""
url = 'http://example.com/'
self.assertEqual(url, resolve_url(url))
def test_model(self):
"""
Tests that passing a model to ``resolve_url`` will result in
``get_absolute_url`` being called on that model instance.
"""
m = UnimportantThing(importance=1)
self.assertEqual(m.get_absolute_url(), resolve_url(m))
def test_view_function(self):
"""
Tests that passing a view name to ``resolve_url`` will result in the
URL path mapping to that view name.
"""
resolved_url = resolve_url(logout)
self.assertEqual('/accounts/logout/', resolved_url)
def test_valid_view_name(self):
"""
Tests that passing a view function to ``resolve_url`` will result in
the URL path mapping to that view.
"""
with warnings.catch_warnings():
warnings.filterwarnings("ignore", category=RemovedInDjango20Warning)
resolved_url = resolve_url('django.contrib.auth.views.logout')
self.assertEqual('/accounts/logout/', resolved_url)
def test_domain(self):
"""
Tests that passing a domain to ``resolve_url`` returns the same domain.
"""
self.assertEqual(resolve_url('example.com'), 'example.com')
def test_non_view_callable_raises_no_reverse_match(self):
"""
Tests that passing a non-view callable into ``resolve_url`` raises a
``NoReverseMatch`` exception.
"""
with self.assertRaises(NoReverseMatch):
resolve_url(lambda: 'asdf')
| bsd-3-clause |
NikNitro/Python-iBeacon-Scan | sympy/solvers/ode.py | 7 | 330554 | r"""
This module contains :py:meth:`~sympy.solvers.ode.dsolve` and different helper
functions that it uses.
:py:meth:`~sympy.solvers.ode.dsolve` solves ordinary differential equations.
See the docstring on the various functions for their uses. Note that partial
differential equations support is in ``pde.py``. Note that hint functions
have docstrings describing their various methods, but they are intended for
internal use. Use ``dsolve(ode, func, hint=hint)`` to solve an ODE using a
specific hint. See also the docstring on
:py:meth:`~sympy.solvers.ode.dsolve`.
**Functions in this module**
These are the user functions in this module:
- :py:meth:`~sympy.solvers.ode.dsolve` - Solves ODEs.
- :py:meth:`~sympy.solvers.ode.classify_ode` - Classifies ODEs into
possible hints for :py:meth:`~sympy.solvers.ode.dsolve`.
- :py:meth:`~sympy.solvers.ode.checkodesol` - Checks if an equation is the
solution to an ODE.
- :py:meth:`~sympy.solvers.ode.homogeneous_order` - Returns the
homogeneous order of an expression.
- :py:meth:`~sympy.solvers.ode.infinitesimals` - Returns the infinitesimals
of the Lie group of point transformations of an ODE, such that it is
invariant.
- :py:meth:`~sympy.solvers.ode_checkinfsol` - Checks if the given infinitesimals
are the actual infinitesimals of a first order ODE.
These are the non-solver helper functions that are for internal use. The
user should use the various options to
:py:meth:`~sympy.solvers.ode.dsolve` to obtain the functionality provided
by these functions:
- :py:meth:`~sympy.solvers.ode.odesimp` - Does all forms of ODE
simplification.
- :py:meth:`~sympy.solvers.ode.ode_sol_simplicity` - A key function for
comparing solutions by simplicity.
- :py:meth:`~sympy.solvers.ode.constantsimp` - Simplifies arbitrary
constants.
- :py:meth:`~sympy.solvers.ode.constant_renumber` - Renumber arbitrary
constants.
- :py:meth:`~sympy.solvers.ode._handle_Integral` - Evaluate unevaluated
Integrals.
See also the docstrings of these functions.
**Currently implemented solver methods**
The following methods are implemented for solving ordinary differential
equations. See the docstrings of the various hint functions for more
information on each (run ``help(ode)``):
- 1st order separable differential equations.
- 1st order differential equations whose coefficients or `dx` and `dy` are
functions homogeneous of the same order.
- 1st order exact differential equations.
- 1st order linear differential equations.
- 1st order Bernoulli differential equations.
- Power series solutions for first order differential equations.
- Lie Group method of solving first order differential equations.
- 2nd order Liouville differential equations.
- Power series solutions for second order differential equations
at ordinary and regular singular points.
- `n`\th order linear homogeneous differential equation with constant
coefficients.
- `n`\th order linear inhomogeneous differential equation with constant
coefficients using the method of undetermined coefficients.
- `n`\th order linear inhomogeneous differential equation with constant
coefficients using the method of variation of parameters.
**Philosophy behind this module**
This module is designed to make it easy to add new ODE solving methods without
having to mess with the solving code for other methods. The idea is that
there is a :py:meth:`~sympy.solvers.ode.classify_ode` function, which takes in
an ODE and tells you what hints, if any, will solve the ODE. It does this
without attempting to solve the ODE, so it is fast. Each solving method is a
hint, and it has its own function, named ``ode_<hint>``. That function takes
in the ODE and any match expression gathered by
:py:meth:`~sympy.solvers.ode.classify_ode` and returns a solved result. If
this result has any integrals in it, the hint function will return an
unevaluated :py:class:`~sympy.integrals.Integral` class.
:py:meth:`~sympy.solvers.ode.dsolve`, which is the user wrapper function
around all of this, will then call :py:meth:`~sympy.solvers.ode.odesimp` on
the result, which, among other things, will attempt to solve the equation for
the dependent variable (the function we are solving for), simplify the
arbitrary constants in the expression, and evaluate any integrals, if the hint
allows it.
**How to add new solution methods**
If you have an ODE that you want :py:meth:`~sympy.solvers.ode.dsolve` to be
able to solve, try to avoid adding special case code here. Instead, try
finding a general method that will solve your ODE, as well as others. This
way, the :py:mod:`~sympy.solvers.ode` module will become more robust, and
unhindered by special case hacks. WolphramAlpha and Maple's
DETools[odeadvisor] function are two resources you can use to classify a
specific ODE. It is also better for a method to work with an `n`\th order ODE
instead of only with specific orders, if possible.
To add a new method, there are a few things that you need to do. First, you
need a hint name for your method. Try to name your hint so that it is
unambiguous with all other methods, including ones that may not be implemented
yet. If your method uses integrals, also include a ``hint_Integral`` hint.
If there is more than one way to solve ODEs with your method, include a hint
for each one, as well as a ``<hint>_best`` hint. Your ``ode_<hint>_best()``
function should choose the best using min with ``ode_sol_simplicity`` as the
key argument. See
:py:meth:`~sympy.solvers.ode.ode_1st_homogeneous_coeff_best`, for example.
The function that uses your method will be called ``ode_<hint>()``, so the
hint must only use characters that are allowed in a Python function name
(alphanumeric characters and the underscore '``_``' character). Include a
function for every hint, except for ``_Integral`` hints
(:py:meth:`~sympy.solvers.ode.dsolve` takes care of those automatically).
Hint names should be all lowercase, unless a word is commonly capitalized
(such as Integral or Bernoulli). If you have a hint that you do not want to
run with ``all_Integral`` that doesn't have an ``_Integral`` counterpart (such
as a best hint that would defeat the purpose of ``all_Integral``), you will
need to remove it manually in the :py:meth:`~sympy.solvers.ode.dsolve` code.
See also the :py:meth:`~sympy.solvers.ode.classify_ode` docstring for
guidelines on writing a hint name.
Determine *in general* how the solutions returned by your method compare with
other methods that can potentially solve the same ODEs. Then, put your hints
in the :py:data:`~sympy.solvers.ode.allhints` tuple in the order that they
should be called. The ordering of this tuple determines which hints are
default. Note that exceptions are ok, because it is easy for the user to
choose individual hints with :py:meth:`~sympy.solvers.ode.dsolve`. In
general, ``_Integral`` variants should go at the end of the list, and
``_best`` variants should go before the various hints they apply to. For
example, the ``undetermined_coefficients`` hint comes before the
``variation_of_parameters`` hint because, even though variation of parameters
is more general than undetermined coefficients, undetermined coefficients
generally returns cleaner results for the ODEs that it can solve than
variation of parameters does, and it does not require integration, so it is
much faster.
Next, you need to have a match expression or a function that matches the type
of the ODE, which you should put in :py:meth:`~sympy.solvers.ode.classify_ode`
(if the match function is more than just a few lines, like
:py:meth:`~sympy.solvers.ode._undetermined_coefficients_match`, it should go
outside of :py:meth:`~sympy.solvers.ode.classify_ode`). It should match the
ODE without solving for it as much as possible, so that
:py:meth:`~sympy.solvers.ode.classify_ode` remains fast and is not hindered by
bugs in solving code. Be sure to consider corner cases. For example, if your
solution method involves dividing by something, make sure you exclude the case
where that division will be 0.
In most cases, the matching of the ODE will also give you the various parts
that you need to solve it. You should put that in a dictionary (``.match()``
will do this for you), and add that as ``matching_hints['hint'] = matchdict``
in the relevant part of :py:meth:`~sympy.solvers.ode.classify_ode`.
:py:meth:`~sympy.solvers.ode.classify_ode` will then send this to
:py:meth:`~sympy.solvers.ode.dsolve`, which will send it to your function as
the ``match`` argument. Your function should be named ``ode_<hint>(eq, func,
order, match)`. If you need to send more information, put it in the ``match``
dictionary. For example, if you had to substitute in a dummy variable in
:py:meth:`~sympy.solvers.ode.classify_ode` to match the ODE, you will need to
pass it to your function using the `match` dict to access it. You can access
the independent variable using ``func.args[0]``, and the dependent variable
(the function you are trying to solve for) as ``func.func``. If, while trying
to solve the ODE, you find that you cannot, raise ``NotImplementedError``.
:py:meth:`~sympy.solvers.ode.dsolve` will catch this error with the ``all``
meta-hint, rather than causing the whole routine to fail.
Add a docstring to your function that describes the method employed. Like
with anything else in SymPy, you will need to add a doctest to the docstring,
in addition to real tests in ``test_ode.py``. Try to maintain consistency
with the other hint functions' docstrings. Add your method to the list at the
top of this docstring. Also, add your method to ``ode.rst`` in the
``docs/src`` directory, so that the Sphinx docs will pull its docstring into
the main SymPy documentation. Be sure to make the Sphinx documentation by
running ``make html`` from within the doc directory to verify that the
docstring formats correctly.
If your solution method involves integrating, use :py:meth:`Integral()
<sympy.integrals.integrals.Integral>` instead of
:py:meth:`~sympy.core.expr.Expr.integrate`. This allows the user to bypass
hard/slow integration by using the ``_Integral`` variant of your hint. In
most cases, calling :py:meth:`sympy.core.basic.Basic.doit` will integrate your
solution. If this is not the case, you will need to write special code in
:py:meth:`~sympy.solvers.ode._handle_Integral`. Arbitrary constants should be
symbols named ``C1``, ``C2``, and so on. All solution methods should return
an equality instance. If you need an arbitrary number of arbitrary constants,
you can use ``constants = numbered_symbols(prefix='C', cls=Symbol, start=1)``.
If it is possible to solve for the dependent function in a general way, do so.
Otherwise, do as best as you can, but do not call solve in your
``ode_<hint>()`` function. :py:meth:`~sympy.solvers.ode.odesimp` will attempt
to solve the solution for you, so you do not need to do that. Lastly, if your
ODE has a common simplification that can be applied to your solutions, you can
add a special case in :py:meth:`~sympy.solvers.ode.odesimp` for it. For
example, solutions returned from the ``1st_homogeneous_coeff`` hints often
have many :py:meth:`~sympy.functions.log` terms, so
:py:meth:`~sympy.solvers.ode.odesimp` calls
:py:meth:`~sympy.simplify.simplify.logcombine` on them (it also helps to write
the arbitrary constant as ``log(C1)`` instead of ``C1`` in this case). Also
consider common ways that you can rearrange your solution to have
:py:meth:`~sympy.solvers.ode.constantsimp` take better advantage of it. It is
better to put simplification in :py:meth:`~sympy.solvers.ode.odesimp` than in
your method, because it can then be turned off with the simplify flag in
:py:meth:`~sympy.solvers.ode.dsolve`. If you have any extraneous
simplification in your function, be sure to only run it using ``if
match.get('simplify', True):``, especially if it can be slow or if it can
reduce the domain of the solution.
Finally, as with every contribution to SymPy, your method will need to be
tested. Add a test for each method in ``test_ode.py``. Follow the
conventions there, i.e., test the solver using ``dsolve(eq, f(x),
hint=your_hint)``, and also test the solution using
:py:meth:`~sympy.solvers.ode.checkodesol` (you can put these in a separate
tests and skip/XFAIL if it runs too slow/doesn't work). Be sure to call your
hint specifically in :py:meth:`~sympy.solvers.ode.dsolve`, that way the test
won't be broken simply by the introduction of another matching hint. If your
method works for higher order (>1) ODEs, you will need to run ``sol =
constant_renumber(sol, 'C', 1, order)`` for each solution, where ``order`` is
the order of the ODE. This is because ``constant_renumber`` renumbers the
arbitrary constants by printing order, which is platform dependent. Try to
test every corner case of your solver, including a range of orders if it is a
`n`\th order solver, but if your solver is slow, such as if it involves hard
integration, try to keep the test run time down.
Feel free to refactor existing hints to avoid duplicating code or creating
inconsistencies. If you can show that your method exactly duplicates an
existing method, including in the simplicity and speed of obtaining the
solutions, then you can remove the old, less general method. The existing
code is tested extensively in ``test_ode.py``, so if anything is broken, one
of those tests will surely fail.
"""
from __future__ import print_function, division
from collections import defaultdict
from itertools import islice
from sympy.core import Add, S, Mul, Pow, oo
from sympy.core.compatibility import ordered, iterable, is_sequence, range
from sympy.core.containers import Tuple
from sympy.core.exprtools import factor_terms
from sympy.core.expr import AtomicExpr, Expr
from sympy.core.function import (Function, Derivative, AppliedUndef, diff,
expand, expand_mul, Subs, _mexpand)
from sympy.core.multidimensional import vectorize
from sympy.core.numbers import NaN, zoo, I, Number
from sympy.core.relational import Equality, Eq
from sympy.core.symbol import Symbol, Wild, Dummy, symbols
from sympy.core.sympify import sympify
from sympy.logic.boolalg import BooleanAtom
from sympy.functions import cos, exp, im, log, re, sin, tan, sqrt, \
atan2, conjugate
from sympy.functions.combinatorial.factorials import factorial
from sympy.integrals.integrals import Integral, integrate
from sympy.matrices import wronskian, Matrix, eye, zeros
from sympy.polys import (Poly, RootOf, rootof, terms_gcd,
PolynomialError, lcm)
from sympy.polys.polyroots import roots_quartic
from sympy.polys.polytools import cancel, degree, div
from sympy.series import Order
from sympy.series.series import series
from sympy.simplify import collect, logcombine, powsimp, separatevars, \
simplify, trigsimp, denom, posify, cse
from sympy.simplify.powsimp import powdenest
from sympy.simplify.radsimp import collect_const
from sympy.solvers import solve
from sympy.solvers.pde import pdsolve
from sympy.utilities import numbered_symbols, default_sort_key, sift
from sympy.solvers.deutils import _preprocess, ode_order, _desolve
#: This is a list of hints in the order that they should be preferred by
#: :py:meth:`~sympy.solvers.ode.classify_ode`. In general, hints earlier in the
#: list should produce simpler solutions than those later in the list (for
#: ODEs that fit both). For now, the order of this list is based on empirical
#: observations by the developers of SymPy.
#:
#: The hint used by :py:meth:`~sympy.solvers.ode.dsolve` for a specific ODE
#: can be overridden (see the docstring).
#:
#: In general, ``_Integral`` hints are grouped at the end of the list, unless
#: there is a method that returns an unevaluable integral most of the time
#: (which go near the end of the list anyway). ``default``, ``all``,
#: ``best``, and ``all_Integral`` meta-hints should not be included in this
#: list, but ``_best`` and ``_Integral`` hints should be included.
allhints = (
"separable",
"1st_exact",
"1st_linear",
"Bernoulli",
"Riccati_special_minus2",
"1st_homogeneous_coeff_best",
"1st_homogeneous_coeff_subs_indep_div_dep",
"1st_homogeneous_coeff_subs_dep_div_indep",
"almost_linear",
"linear_coefficients",
"separable_reduced",
"1st_power_series",
"lie_group",
"nth_linear_constant_coeff_homogeneous",
"nth_linear_euler_eq_homogeneous",
"nth_linear_constant_coeff_undetermined_coefficients",
"nth_linear_euler_eq_nonhomogeneous_undetermined_coefficients",
"nth_linear_constant_coeff_variation_of_parameters",
"nth_linear_euler_eq_nonhomogeneous_variation_of_parameters",
"Liouville",
"2nd_power_series_ordinary",
"2nd_power_series_regular",
"separable_Integral",
"1st_exact_Integral",
"1st_linear_Integral",
"Bernoulli_Integral",
"1st_homogeneous_coeff_subs_indep_div_dep_Integral",
"1st_homogeneous_coeff_subs_dep_div_indep_Integral",
"almost_linear_Integral",
"linear_coefficients_Integral",
"separable_reduced_Integral",
"nth_linear_constant_coeff_variation_of_parameters_Integral",
"nth_linear_euler_eq_nonhomogeneous_variation_of_parameters_Integral",
"Liouville_Integral",
)
lie_heuristics = (
"abaco1_simple",
"abaco1_product",
"abaco2_similar",
"abaco2_unique_unknown",
"abaco2_unique_general",
"linear",
"function_sum",
"bivariate",
"chi"
)
def sub_func_doit(eq, func, new):
r"""
When replacing the func with something else, we usually want the
derivative evaluated, so this function helps in making that happen.
To keep subs from having to look through all derivatives, we mask them off
with dummy variables, do the func sub, and then replace masked-off
derivatives with their doit values.
Examples
========
>>> from sympy import Derivative, symbols, Function
>>> from sympy.solvers.ode import sub_func_doit
>>> x, z = symbols('x, z')
>>> y = Function('y')
>>> sub_func_doit(3*Derivative(y(x), x) - 1, y(x), x)
2
>>> sub_func_doit(x*Derivative(y(x), x) - y(x)**2 + y(x), y(x),
... 1/(x*(z + 1/x)))
x*(-1/(x**2*(z + 1/x)) + 1/(x**3*(z + 1/x)**2)) + 1/(x*(z + 1/x))
...- 1/(x**2*(z + 1/x)**2)
"""
reps = {}
repu = {}
for d in eq.atoms(Derivative):
u = Dummy('u')
repu[u] = d.subs(func, new).doit()
reps[d] = u
return eq.subs(reps).subs(func, new).subs(repu)
def get_numbered_constants(eq, num=1, start=1, prefix='C'):
"""
Returns a list of constants that do not occur
in eq already.
"""
if isinstance(eq, Expr):
eq = [eq]
elif not iterable(eq):
raise ValueError("Expected Expr or iterable but got %s" % eq)
atom_set = set().union(*[i.free_symbols for i in eq])
ncs = numbered_symbols(start=start, prefix=prefix, exclude=atom_set)
Cs = [next(ncs) for i in range(num)]
return (Cs[0] if num == 1 else tuple(Cs))
def dsolve(eq, func=None, hint="default", simplify=True,
ics= None, xi=None, eta=None, x0=0, n=6, **kwargs):
r"""
Solves any (supported) kind of ordinary differential equation and
system of ordinary differential equations.
For single ordinary differential equation
=========================================
It is classified under this when number of equation in ``eq`` is one.
**Usage**
``dsolve(eq, f(x), hint)`` -> Solve ordinary differential equation
``eq`` for function ``f(x)``, using method ``hint``.
**Details**
``eq`` can be any supported ordinary differential equation (see the
:py:mod:`~sympy.solvers.ode` docstring for supported methods).
This can either be an :py:class:`~sympy.core.relational.Equality`,
or an expression, which is assumed to be equal to ``0``.
``f(x)`` is a function of one variable whose derivatives in that
variable make up the ordinary differential equation ``eq``. In
many cases it is not necessary to provide this; it will be
autodetected (and an error raised if it couldn't be detected).
``hint`` is the solving method that you want dsolve to use. Use
``classify_ode(eq, f(x))`` to get all of the possible hints for an
ODE. The default hint, ``default``, will use whatever hint is
returned first by :py:meth:`~sympy.solvers.ode.classify_ode`. See
Hints below for more options that you can use for hint.
``simplify`` enables simplification by
:py:meth:`~sympy.solvers.ode.odesimp`. See its docstring for more
information. Turn this off, for example, to disable solving of
solutions for ``func`` or simplification of arbitrary constants.
It will still integrate with this hint. Note that the solution may
contain more arbitrary constants than the order of the ODE with
this option enabled.
``xi`` and ``eta`` are the infinitesimal functions of an ordinary
differential equation. They are the infinitesimals of the Lie group
of point transformations for which the differential equation is
invariant. The user can specify values for the infinitesimals. If
nothing is specified, ``xi`` and ``eta`` are calculated using
:py:meth:`~sympy.solvers.ode.infinitesimals` with the help of various
heuristics.
``ics`` is the set of boundary conditions for the differential equation.
It should be given in the form of ``{f(x0): x1, f(x).diff(x).subs(x, x2):
x3}`` and so on. For now initial conditions are implemented only for
power series solutions of first-order differential equations which should
be given in the form of ``{f(x0): x1}`` (See issue 4720). If nothing is
specified for this case ``f(0)`` is assumed to be ``C0`` and the power
series solution is calculated about 0.
``x0`` is the point about which the power series solution of a differential
equation is to be evaluated.
``n`` gives the exponent of the dependent variable up to which the power series
solution of a differential equation is to be evaluated.
**Hints**
Aside from the various solving methods, there are also some meta-hints
that you can pass to :py:meth:`~sympy.solvers.ode.dsolve`:
``default``:
This uses whatever hint is returned first by
:py:meth:`~sympy.solvers.ode.classify_ode`. This is the
default argument to :py:meth:`~sympy.solvers.ode.dsolve`.
``all``:
To make :py:meth:`~sympy.solvers.ode.dsolve` apply all
relevant classification hints, use ``dsolve(ODE, func,
hint="all")``. This will return a dictionary of
``hint:solution`` terms. If a hint causes dsolve to raise the
``NotImplementedError``, value of that hint's key will be the
exception object raised. The dictionary will also include
some special keys:
- ``order``: The order of the ODE. See also
:py:meth:`~sympy.solvers.deutils.ode_order` in
``deutils.py``.
- ``best``: The simplest hint; what would be returned by
``best`` below.
- ``best_hint``: The hint that would produce the solution
given by ``best``. If more than one hint produces the best
solution, the first one in the tuple returned by
:py:meth:`~sympy.solvers.ode.classify_ode` is chosen.
- ``default``: The solution that would be returned by default.
This is the one produced by the hint that appears first in
the tuple returned by
:py:meth:`~sympy.solvers.ode.classify_ode`.
``all_Integral``:
This is the same as ``all``, except if a hint also has a
corresponding ``_Integral`` hint, it only returns the
``_Integral`` hint. This is useful if ``all`` causes
:py:meth:`~sympy.solvers.ode.dsolve` to hang because of a
difficult or impossible integral. This meta-hint will also be
much faster than ``all``, because
:py:meth:`~sympy.core.expr.Expr.integrate` is an expensive
routine.
``best``:
To have :py:meth:`~sympy.solvers.ode.dsolve` try all methods
and return the simplest one. This takes into account whether
the solution is solvable in the function, whether it contains
any Integral classes (i.e. unevaluatable integrals), and
which one is the shortest in size.
See also the :py:meth:`~sympy.solvers.ode.classify_ode` docstring for
more info on hints, and the :py:mod:`~sympy.solvers.ode` docstring for
a list of all supported hints.
**Tips**
- You can declare the derivative of an unknown function this way:
>>> from sympy import Function, Derivative
>>> from sympy.abc import x # x is the independent variable
>>> f = Function("f")(x) # f is a function of x
>>> # f_ will be the derivative of f with respect to x
>>> f_ = Derivative(f, x)
- See ``test_ode.py`` for many tests, which serves also as a set of
examples for how to use :py:meth:`~sympy.solvers.ode.dsolve`.
- :py:meth:`~sympy.solvers.ode.dsolve` always returns an
:py:class:`~sympy.core.relational.Equality` class (except for the
case when the hint is ``all`` or ``all_Integral``). If possible, it
solves the solution explicitly for the function being solved for.
Otherwise, it returns an implicit solution.
- Arbitrary constants are symbols named ``C1``, ``C2``, and so on.
- Because all solutions should be mathematically equivalent, some
hints may return the exact same result for an ODE. Often, though,
two different hints will return the same solution formatted
differently. The two should be equivalent. Also note that sometimes
the values of the arbitrary constants in two different solutions may
not be the same, because one constant may have "absorbed" other
constants into it.
- Do ``help(ode.ode_<hintname>)`` to get help more information on a
specific hint, where ``<hintname>`` is the name of a hint without
``_Integral``.
For system of ordinary differential equations
=============================================
**Usage**
``dsolve(eq, func)`` -> Solve a system of ordinary differential
equations ``eq`` for ``func`` being list of functions including
`x(t)`, `y(t)`, `z(t)` where number of functions in the list depends
upon the number of equations provided in ``eq``.
**Details**
``eq`` can be any supported system of ordinary differential equations
This can either be an :py:class:`~sympy.core.relational.Equality`,
or an expression, which is assumed to be equal to ``0``.
``func`` holds ``x(t)`` and ``y(t)`` being functions of one variable which
together with some of their derivatives make up the system of ordinary
differential equation ``eq``. It is not necessary to provide this; it
will be autodetected (and an error raised if it couldn't be detected).
**Hints**
The hints are formed by parameters returned by classify_sysode, combining
them give hints name used later for forming method name.
Examples
========
>>> from sympy import Function, dsolve, Eq, Derivative, sin, cos, symbols
>>> from sympy.abc import x
>>> f = Function('f')
>>> dsolve(Derivative(f(x), x, x) + 9*f(x), f(x))
Eq(f(x), C1*sin(3*x) + C2*cos(3*x))
>>> eq = sin(x)*cos(f(x)) + cos(x)*sin(f(x))*f(x).diff(x)
>>> dsolve(eq, hint='1st_exact')
[Eq(f(x), -acos(C1/cos(x)) + 2*pi), Eq(f(x), acos(C1/cos(x)))]
>>> dsolve(eq, hint='almost_linear')
[Eq(f(x), -acos(C1/sqrt(-cos(x)**2)) + 2*pi), Eq(f(x), acos(C1/sqrt(-cos(x)**2)))]
>>> t = symbols('t')
>>> x, y = symbols('x, y', function=True)
>>> eq = (Eq(Derivative(x(t),t), 12*t*x(t) + 8*y(t)), Eq(Derivative(y(t),t), 21*x(t) + 7*t*y(t)))
>>> dsolve(eq)
[Eq(x(t), C1*x0 + C2*x0*Integral(8*exp(Integral(7*t, t))*exp(Integral(12*t, t))/x0**2, t)),
Eq(y(t), C1*y0 + C2(y0*Integral(8*exp(Integral(7*t, t))*exp(Integral(12*t, t))/x0**2, t) +
exp(Integral(7*t, t))*exp(Integral(12*t, t))/x0))]
>>> eq = (Eq(Derivative(x(t),t),x(t)*y(t)*sin(t)), Eq(Derivative(y(t),t),y(t)**2*sin(t)))
>>> dsolve(eq)
{Eq(x(t), -exp(C1)/(C2*exp(C1) - cos(t))), Eq(y(t), -1/(C1 - cos(t)))}
"""
if iterable(eq):
match = classify_sysode(eq, func)
eq = match['eq']
order = match['order']
func = match['func']
t = list(list(eq[0].atoms(Derivative))[0].atoms(Symbol))[0]
# keep highest order term coefficient positive
for i in range(len(eq)):
for func_ in func:
if isinstance(func_, list):
pass
else:
if eq[i].coeff(diff(func[i],t,ode_order(eq[i], func[i]))).is_negative:
eq[i] = -eq[i]
match['eq'] = eq
if len(set(order.values()))!=1:
raise ValueError("It solves only those systems of equations whose orders are equal")
match['order'] = list(order.values())[0]
def recur_len(l):
return sum(recur_len(item) if isinstance(item,list) else 1 for item in l)
if recur_len(func) != len(eq):
raise ValueError("dsolve() and classify_sysode() work with "
"number of functions being equal to number of equations")
if match['type_of_equation'] is None:
raise NotImplementedError
else:
if match['is_linear'] == True:
if match['no_of_equation'] > 3:
solvefunc = globals()['sysode_linear_neq_order%(order)s' % match]
else:
solvefunc = globals()['sysode_linear_%(no_of_equation)seq_order%(order)s' % match]
else:
solvefunc = globals()['sysode_nonlinear_%(no_of_equation)seq_order%(order)s' % match]
sols = solvefunc(match)
return sols
else:
given_hint = hint # hint given by the user
# See the docstring of _desolve for more details.
hints = _desolve(eq, func=func,
hint=hint, simplify=True, xi=xi, eta=eta, type='ode', ics=ics,
x0=x0, n=n, **kwargs)
eq = hints.pop('eq', eq)
all_ = hints.pop('all', False)
if all_:
retdict = {}
failed_hints = {}
gethints = classify_ode(eq, dict=True)
orderedhints = gethints['ordered_hints']
for hint in hints:
try:
rv = _helper_simplify(eq, hint, hints[hint], simplify)
except NotImplementedError as detail:
failed_hints[hint] = detail
else:
retdict[hint] = rv
func = hints[hint]['func']
retdict['best'] = min(list(retdict.values()), key=lambda x:
ode_sol_simplicity(x, func, trysolving=not simplify))
if given_hint == 'best':
return retdict['best']
for i in orderedhints:
if retdict['best'] == retdict.get(i, None):
retdict['best_hint'] = i
break
retdict['default'] = gethints['default']
retdict['order'] = gethints['order']
retdict.update(failed_hints)
return retdict
else:
# The key 'hint' stores the hint needed to be solved for.
hint = hints['hint']
return _helper_simplify(eq, hint, hints, simplify)
def _helper_simplify(eq, hint, match, simplify=True, **kwargs):
r"""
Helper function of dsolve that calls the respective
:py:mod:`~sympy.solvers.ode` functions to solve for the ordinary
differential equations. This minimises the computation in calling
:py:meth:`~sympy.solvers.deutils._desolve` multiple times.
"""
r = match
if hint.endswith('_Integral'):
solvefunc = globals()['ode_' + hint[:-len('_Integral')]]
else:
solvefunc = globals()['ode_' + hint]
func = r['func']
order = r['order']
match = r[hint]
if simplify:
# odesimp() will attempt to integrate, if necessary, apply constantsimp(),
# attempt to solve for func, and apply any other hint specific
# simplifications
sols = solvefunc(eq, func, order, match)
free = eq.free_symbols
cons = lambda s: s.free_symbols.difference(free)
if isinstance(sols, Expr):
return odesimp(sols, func, order, cons(sols), hint)
return [odesimp(s, func, order, cons(s), hint) for s in sols]
else:
# We still want to integrate (you can disable it separately with the hint)
match['simplify'] = False # Some hints can take advantage of this option
rv = _handle_Integral(solvefunc(eq, func, order, match),
func, order, hint)
return rv
def classify_ode(eq, func=None, dict=False, ics=None, **kwargs):
r"""
Returns a tuple of possible :py:meth:`~sympy.solvers.ode.dsolve`
classifications for an ODE.
The tuple is ordered so that first item is the classification that
:py:meth:`~sympy.solvers.ode.dsolve` uses to solve the ODE by default. In
general, classifications at the near the beginning of the list will
produce better solutions faster than those near the end, thought there are
always exceptions. To make :py:meth:`~sympy.solvers.ode.dsolve` use a
different classification, use ``dsolve(ODE, func,
hint=<classification>)``. See also the
:py:meth:`~sympy.solvers.ode.dsolve` docstring for different meta-hints
you can use.
If ``dict`` is true, :py:meth:`~sympy.solvers.ode.classify_ode` will
return a dictionary of ``hint:match`` expression terms. This is intended
for internal use by :py:meth:`~sympy.solvers.ode.dsolve`. Note that
because dictionaries are ordered arbitrarily, this will most likely not be
in the same order as the tuple.
You can get help on different hints by executing
``help(ode.ode_hintname)``, where ``hintname`` is the name of the hint
without ``_Integral``.
See :py:data:`~sympy.solvers.ode.allhints` or the
:py:mod:`~sympy.solvers.ode` docstring for a list of all supported hints
that can be returned from :py:meth:`~sympy.solvers.ode.classify_ode`.
Notes
=====
These are remarks on hint names.
``_Integral``
If a classification has ``_Integral`` at the end, it will return the
expression with an unevaluated :py:class:`~sympy.integrals.Integral`
class in it. Note that a hint may do this anyway if
:py:meth:`~sympy.core.expr.Expr.integrate` cannot do the integral,
though just using an ``_Integral`` will do so much faster. Indeed, an
``_Integral`` hint will always be faster than its corresponding hint
without ``_Integral`` because
:py:meth:`~sympy.core.expr.Expr.integrate` is an expensive routine.
If :py:meth:`~sympy.solvers.ode.dsolve` hangs, it is probably because
:py:meth:`~sympy.core.expr.Expr.integrate` is hanging on a tough or
impossible integral. Try using an ``_Integral`` hint or
``all_Integral`` to get it return something.
Note that some hints do not have ``_Integral`` counterparts. This is
because :py:meth:`~sympy.solvers.ode.integrate` is not used in solving
the ODE for those method. For example, `n`\th order linear homogeneous
ODEs with constant coefficients do not require integration to solve,
so there is no ``nth_linear_homogeneous_constant_coeff_Integrate``
hint. You can easily evaluate any unevaluated
:py:class:`~sympy.integrals.Integral`\s in an expression by doing
``expr.doit()``.
Ordinals
Some hints contain an ordinal such as ``1st_linear``. This is to help
differentiate them from other hints, as well as from other methods
that may not be implemented yet. If a hint has ``nth`` in it, such as
the ``nth_linear`` hints, this means that the method used to applies
to ODEs of any order.
``indep`` and ``dep``
Some hints contain the words ``indep`` or ``dep``. These reference
the independent variable and the dependent function, respectively. For
example, if an ODE is in terms of `f(x)`, then ``indep`` will refer to
`x` and ``dep`` will refer to `f`.
``subs``
If a hints has the word ``subs`` in it, it means the the ODE is solved
by substituting the expression given after the word ``subs`` for a
single dummy variable. This is usually in terms of ``indep`` and
``dep`` as above. The substituted expression will be written only in
characters allowed for names of Python objects, meaning operators will
be spelled out. For example, ``indep``/``dep`` will be written as
``indep_div_dep``.
``coeff``
The word ``coeff`` in a hint refers to the coefficients of something
in the ODE, usually of the derivative terms. See the docstring for
the individual methods for more info (``help(ode)``). This is
contrast to ``coefficients``, as in ``undetermined_coefficients``,
which refers to the common name of a method.
``_best``
Methods that have more than one fundamental way to solve will have a
hint for each sub-method and a ``_best`` meta-classification. This
will evaluate all hints and return the best, using the same
considerations as the normal ``best`` meta-hint.
Examples
========
>>> from sympy import Function, classify_ode, Eq
>>> from sympy.abc import x
>>> f = Function('f')
>>> classify_ode(Eq(f(x).diff(x), 0), f(x))
('separable', '1st_linear', '1st_homogeneous_coeff_best',
'1st_homogeneous_coeff_subs_indep_div_dep',
'1st_homogeneous_coeff_subs_dep_div_indep',
'1st_power_series', 'lie_group',
'nth_linear_constant_coeff_homogeneous',
'separable_Integral', '1st_linear_Integral',
'1st_homogeneous_coeff_subs_indep_div_dep_Integral',
'1st_homogeneous_coeff_subs_dep_div_indep_Integral')
>>> classify_ode(f(x).diff(x, 2) + 3*f(x).diff(x) + 2*f(x) - 4)
('nth_linear_constant_coeff_undetermined_coefficients',
'nth_linear_constant_coeff_variation_of_parameters',
'nth_linear_constant_coeff_variation_of_parameters_Integral')
"""
prep = kwargs.pop('prep', True)
if func and len(func.args) != 1:
raise ValueError("dsolve() and classify_ode() only "
"work with functions of one variable, not %s" % func)
if prep or func is None:
eq, func_ = _preprocess(eq, func)
if func is None:
func = func_
x = func.args[0]
f = func.func
y = Dummy('y')
xi = kwargs.get('xi')
eta = kwargs.get('eta')
terms = kwargs.get('n')
if isinstance(eq, Equality):
if eq.rhs != 0:
return classify_ode(eq.lhs - eq.rhs, func, ics=ics, xi=xi,
n=terms, eta=eta, prep=False)
eq = eq.lhs
order = ode_order(eq, f(x))
# hint:matchdict or hint:(tuple of matchdicts)
# Also will contain "default":<default hint> and "order":order items.
matching_hints = {"order": order}
if not order:
if dict:
matching_hints["default"] = None
return matching_hints
else:
return ()
df = f(x).diff(x)
a = Wild('a', exclude=[f(x)])
b = Wild('b', exclude=[f(x)])
c = Wild('c', exclude=[f(x)])
d = Wild('d', exclude=[df, f(x).diff(x, 2)])
e = Wild('e', exclude=[df])
k = Wild('k', exclude=[df])
n = Wild('n', exclude=[f(x)])
c1 = Wild('c1', exclude=[x])
a2 = Wild('a2', exclude=[x, f(x), df])
b2 = Wild('b2', exclude=[x, f(x), df])
c2 = Wild('c2', exclude=[x, f(x), df])
d2 = Wild('d2', exclude=[x, f(x), df])
a3 = Wild('a3', exclude=[f(x), df, f(x).diff(x, 2)])
b3 = Wild('b3', exclude=[f(x), df, f(x).diff(x, 2)])
c3 = Wild('c3', exclude=[f(x), df, f(x).diff(x, 2)])
r3 = {'xi': xi, 'eta': eta} # Used for the lie_group hint
boundary = {} # Used to extract initial conditions
C1 = Symbol("C1")
eq = expand(eq)
# Preprocessing to get the initial conditions out
if ics is not None:
for funcarg in ics:
# Separating derivatives
if isinstance(funcarg, Subs):
deriv = funcarg.expr
old = funcarg.variables[0]
new = funcarg.point[0]
if isinstance(deriv, Derivative) and isinstance(deriv.args[0],
AppliedUndef) and deriv.args[0].func == f and old == x and not new.has(x):
dorder = ode_order(deriv, x)
temp = 'f' + str(dorder)
boundary.update({temp: new, temp + 'val': ics[funcarg]})
else:
raise ValueError("Enter valid boundary conditions for Derivatives")
# Separating functions
elif isinstance(funcarg, AppliedUndef):
if funcarg.func == f and len(funcarg.args) == 1 and \
not funcarg.args[0].has(x):
boundary.update({'f0': funcarg.args[0], 'f0val': ics[funcarg]})
else:
raise ValueError("Enter valid boundary conditions for Function")
else:
raise ValueError("Enter boundary conditions of the form ics "
" = {f(point}: value, f(point).diff(point, order).subs(arg, point) "
":value")
# Precondition to try remove f(x) from highest order derivative
reduced_eq = None
if eq.is_Add:
deriv_coef = eq.coeff(f(x).diff(x, order))
if deriv_coef not in (1, 0):
r = deriv_coef.match(a*f(x)**c1)
if r and r[c1]:
den = f(x)**r[c1]
reduced_eq = Add(*[arg/den for arg in eq.args])
if not reduced_eq:
reduced_eq = eq
if order == 1:
## Linear case: a(x)*y'+b(x)*y+c(x) == 0
if eq.is_Add:
ind, dep = reduced_eq.as_independent(f)
else:
u = Dummy('u')
ind, dep = (reduced_eq + u).as_independent(f)
ind, dep = [tmp.subs(u, 0) for tmp in [ind, dep]]
r = {a: dep.coeff(df),
b: dep.coeff(f(x)),
c: ind}
# double check f[a] since the preconditioning may have failed
if not r[a].has(f) and not r[b].has(f) and (
r[a]*df + r[b]*f(x) + r[c]).expand() - reduced_eq == 0:
r['a'] = a
r['b'] = b
r['c'] = c
matching_hints["1st_linear"] = r
matching_hints["1st_linear_Integral"] = r
## Bernoulli case: a(x)*y'+b(x)*y+c(x)*y**n == 0
r = collect(
reduced_eq, f(x), exact=True).match(a*df + b*f(x) + c*f(x)**n)
if r and r[c] != 0 and r[n] != 1: # See issue 4676
r['a'] = a
r['b'] = b
r['c'] = c
r['n'] = n
matching_hints["Bernoulli"] = r
matching_hints["Bernoulli_Integral"] = r
## Riccati special n == -2 case: a2*y'+b2*y**2+c2*y/x+d2/x**2 == 0
r = collect(reduced_eq,
f(x), exact=True).match(a2*df + b2*f(x)**2 + c2*f(x)/x + d2/x**2)
if r and r[b2] != 0 and (r[c2] != 0 or r[d2] != 0):
r['a2'] = a2
r['b2'] = b2
r['c2'] = c2
r['d2'] = d2
matching_hints["Riccati_special_minus2"] = r
# NON-REDUCED FORM OF EQUATION matches
r = collect(eq, df, exact=True).match(d + e * df)
if r:
r['d'] = d
r['e'] = e
r['y'] = y
r[d] = r[d].subs(f(x), y)
r[e] = r[e].subs(f(x), y)
# FIRST ORDER POWER SERIES WHICH NEEDS INITIAL CONDITIONS
# TODO: Hint first order series should match only if d/e is analytic.
# For now, only d/e and (d/e).diff(arg) is checked for existence at
# at a given point.
# This is currently done internally in ode_1st_power_series.
point = boundary.get('f0', 0)
value = boundary.get('f0val', C1)
check = cancel(r[d]/r[e])
check1 = check.subs({x: point, y: value})
if not check1.has(oo) and not check1.has(zoo) and \
not check1.has(NaN) and not check1.has(-oo):
check2 = (check1.diff(x)).subs({x: point, y: value})
if not check2.has(oo) and not check2.has(zoo) and \
not check2.has(NaN) and not check2.has(-oo):
rseries = r.copy()
rseries.update({'terms': terms, 'f0': point, 'f0val': value})
matching_hints["1st_power_series"] = rseries
r3.update(r)
## Exact Differential Equation: P(x, y) + Q(x, y)*y' = 0 where
# dP/dy == dQ/dx
try:
if r[d] != 0:
numerator = simplify(r[d].diff(y) - r[e].diff(x))
# The following few conditions try to convert a non-exact
# differential equation into an exact one.
# References : Differential equations with applications
# and historical notes - George E. Simmons
if numerator:
# If (dP/dy - dQ/dx) / Q = f(x)
# then exp(integral(f(x))*equation becomes exact
factor = simplify(numerator/r[e])
variables = factor.free_symbols
if len(variables) == 1 and x == variables.pop():
factor = exp(Integral(factor).doit())
r[d] *= factor
r[e] *= factor
matching_hints["1st_exact"] = r
matching_hints["1st_exact_Integral"] = r
else:
# If (dP/dy - dQ/dx) / -P = f(y)
# then exp(integral(f(y))*equation becomes exact
factor = simplify(-numerator/r[d])
variables = factor.free_symbols
if len(variables) == 1 and y == variables.pop():
factor = exp(Integral(factor).doit())
r[d] *= factor
r[e] *= factor
matching_hints["1st_exact"] = r
matching_hints["1st_exact_Integral"] = r
else:
matching_hints["1st_exact"] = r
matching_hints["1st_exact_Integral"] = r
except NotImplementedError:
# Differentiating the coefficients might fail because of things
# like f(2*x).diff(x). See issue 4624 and issue 4719.
pass
# Any first order ODE can be ideally solved by the Lie Group
# method
matching_hints["lie_group"] = r3
# This match is used for several cases below; we now collect on
# f(x) so the matching works.
r = collect(reduced_eq, df, exact=True).match(d + e*df)
if r:
# Using r[d] and r[e] without any modification for hints
# linear-coefficients and separable-reduced.
num, den = r[d], r[e] # ODE = d/e + df
r['d'] = d
r['e'] = e
r['y'] = y
r[d] = num.subs(f(x), y)
r[e] = den.subs(f(x), y)
## Separable Case: y' == P(y)*Q(x)
r[d] = separatevars(r[d])
r[e] = separatevars(r[e])
# m1[coeff]*m1[x]*m1[y] + m2[coeff]*m2[x]*m2[y]*y'
m1 = separatevars(r[d], dict=True, symbols=(x, y))
m2 = separatevars(r[e], dict=True, symbols=(x, y))
if m1 and m2:
r1 = {'m1': m1, 'm2': m2, 'y': y}
matching_hints["separable"] = r1
matching_hints["separable_Integral"] = r1
## First order equation with homogeneous coefficients:
# dy/dx == F(y/x) or dy/dx == F(x/y)
ordera = homogeneous_order(r[d], x, y)
if ordera is not None:
orderb = homogeneous_order(r[e], x, y)
if ordera == orderb:
# u1=y/x and u2=x/y
u1 = Dummy('u1')
u2 = Dummy('u2')
s = "1st_homogeneous_coeff_subs"
s1 = s + "_dep_div_indep"
s2 = s + "_indep_div_dep"
if simplify((r[d] + u1*r[e]).subs({x: 1, y: u1})) != 0:
matching_hints[s1] = r
matching_hints[s1 + "_Integral"] = r
if simplify((r[e] + u2*r[d]).subs({x: u2, y: 1})) != 0:
matching_hints[s2] = r
matching_hints[s2 + "_Integral"] = r
if s1 in matching_hints and s2 in matching_hints:
matching_hints["1st_homogeneous_coeff_best"] = r
## Linear coefficients of the form
# y'+ F((a*x + b*y + c)/(a'*x + b'y + c')) = 0
# that can be reduced to homogeneous form.
F = num/den
params = _linear_coeff_match(F, func)
if params:
xarg, yarg = params
u = Dummy('u')
t = Dummy('t')
# Dummy substitution for df and f(x).
dummy_eq = reduced_eq.subs(((df, t), (f(x), u)))
reps = ((x, x + xarg), (u, u + yarg), (t, df), (u, f(x)))
dummy_eq = simplify(dummy_eq.subs(reps))
# get the re-cast values for e and d
r2 = collect(expand(dummy_eq), [df, f(x)]).match(e*df + d)
if r2:
orderd = homogeneous_order(r2[d], x, f(x))
if orderd is not None:
ordere = homogeneous_order(r2[e], x, f(x))
if orderd == ordere:
# Match arguments are passed in such a way that it
# is coherent with the already existing homogeneous
# functions.
r2[d] = r2[d].subs(f(x), y)
r2[e] = r2[e].subs(f(x), y)
r2.update({'xarg': xarg, 'yarg': yarg,
'd': d, 'e': e, 'y': y})
matching_hints["linear_coefficients"] = r2
matching_hints["linear_coefficients_Integral"] = r2
## Equation of the form y' + (y/x)*H(x^n*y) = 0
# that can be reduced to separable form
factor = simplify(x/f(x)*num/den)
# Try representing factor in terms of x^n*y
# where n is lowest power of x in factor;
# first remove terms like sqrt(2)*3 from factor.atoms(Mul)
u = None
for mul in ordered(factor.atoms(Mul)):
if mul.has(x):
_, u = mul.as_independent(x, f(x))
break
if u and u.has(f(x)):
h = x**(degree(Poly(u.subs(f(x), y), gen=x)))*f(x)
p = Wild('p')
if (u/h == 1) or ((u/h).simplify().match(x**p)):
t = Dummy('t')
r2 = {'t': t}
xpart, ypart = u.as_independent(f(x))
test = factor.subs(((u, t), (1/u, 1/t)))
free = test.free_symbols
if len(free) == 1 and free.pop() == t:
r2.update({'power': xpart.as_base_exp()[1], 'u': test})
matching_hints["separable_reduced"] = r2
matching_hints["separable_reduced_Integral"] = r2
## Almost-linear equation of the form f(x)*g(y)*y' + k(x)*l(y) + m(x) = 0
r = collect(eq, [df, f(x)]).match(e*df + d)
if r:
r2 = r.copy()
r2[c] = S.Zero
if r2[d].is_Add:
# Separate the terms having f(x) to r[d] and
# remaining to r[c]
no_f, r2[d] = r2[d].as_independent(f(x))
r2[c] += no_f
factor = simplify(r2[d].diff(f(x))/r[e])
if factor and not factor.has(f(x)):
r2[d] = factor_terms(r2[d])
u = r2[d].as_independent(f(x), as_Add=False)[1]
r2.update({'a': e, 'b': d, 'c': c, 'u': u})
r2[d] /= u
r2[e] /= u.diff(f(x))
matching_hints["almost_linear"] = r2
matching_hints["almost_linear_Integral"] = r2
elif order == 2:
# Liouville ODE in the form
# f(x).diff(x, 2) + g(f(x))*(f(x).diff(x))**2 + h(x)*f(x).diff(x)
# See Goldstein and Braun, "Advanced Methods for the Solution of
# Differential Equations", pg. 98
s = d*f(x).diff(x, 2) + e*df**2 + k*df
r = reduced_eq.match(s)
if r and r[d] != 0:
y = Dummy('y')
g = simplify(r[e]/r[d]).subs(f(x), y)
h = simplify(r[k]/r[d])
if h.has(f(x)) or g.has(x):
pass
else:
r = {'g': g, 'h': h, 'y': y}
matching_hints["Liouville"] = r
matching_hints["Liouville_Integral"] = r
# Homogeneous second order differential equation of the form
# a3*f(x).diff(x, 2) + b3*f(x).diff(x) + c3, where
# for simplicity, a3, b3 and c3 are assumed to be polynomials.
# It has a definite power series solution at point x0 if, b3/a3 and c3/a3
# are analytic at x0.
deq = a3*(f(x).diff(x, 2)) + b3*df + c3*f(x)
r = collect(reduced_eq,
[f(x).diff(x, 2), f(x).diff(x), f(x)]).match(deq)
ordinary = False
if r and r[a3] != 0:
if all([r[key].is_polynomial() for key in r]):
p = cancel(r[b3]/r[a3]) # Used below
q = cancel(r[c3]/r[a3]) # Used below
point = kwargs.get('x0', 0)
check = p.subs(x, point)
if not check.has(oo) and not check.has(NaN) and \
not check.has(zoo) and not check.has(-oo):
check = q.subs(x, point)
if not check.has(oo) and not check.has(NaN) and \
not check.has(zoo) and not check.has(-oo):
ordinary = True
r.update({'a3': a3, 'b3': b3, 'c3': c3, 'x0': point, 'terms': terms})
matching_hints["2nd_power_series_ordinary"] = r
# Checking if the differential equation has a regular singular point
# at x0. It has a regular singular point at x0, if (b3/a3)*(x - x0)
# and (c3/a3)*((x - x0)**2) are analytic at x0.
if not ordinary:
p = cancel((x - point)*p)
check = p.subs(x, point)
if not check.has(oo) and not check.has(NaN) and \
not check.has(zoo) and not check.has(-oo):
q = cancel(((x - point)**2)*q)
check = q.subs(x, point)
if not check.has(oo) and not check.has(NaN) and \
not check.has(zoo) and not check.has(-oo):
coeff_dict = {'p': p, 'q': q, 'x0': point, 'terms': terms}
matching_hints["2nd_power_series_regular"] = coeff_dict
if order > 0:
# nth order linear ODE
# a_n(x)y^(n) + ... + a_1(x)y' + a_0(x)y = F(x) = b
r = _nth_linear_match(reduced_eq, func, order)
# Constant coefficient case (a_i is constant for all i)
if r and not any(r[i].has(x) for i in r if i >= 0):
# Inhomogeneous case: F(x) is not identically 0
if r[-1]:
undetcoeff = _undetermined_coefficients_match(r[-1], x)
s = "nth_linear_constant_coeff_variation_of_parameters"
matching_hints[s] = r
matching_hints[s + "_Integral"] = r
if undetcoeff['test']:
r['trialset'] = undetcoeff['trialset']
matching_hints[
"nth_linear_constant_coeff_undetermined_coefficients"
] = r
# Homogeneous case: F(x) is identically 0
else:
matching_hints["nth_linear_constant_coeff_homogeneous"] = r
# nth order Euler equation a_n*x**n*y^(n) + ... + a_1*x*y' + a_0*y = F(x)
#In case of Homogeneous euler equation F(x) = 0
def _test_term(coeff, order):
r"""
Linear Euler ODEs have the form K*x**order*diff(y(x),x,order) = F(x),
where K is independent of x and y(x), order>= 0.
So we need to check that for each term, coeff == K*x**order from
some K. We have a few cases, since coeff may have several
different types.
"""
if order < 0:
raise ValueError("order should be greater than 0")
if coeff == 0:
return True
if order == 0:
if x in coeff.free_symbols:
return False
return True
if coeff.is_Mul:
if coeff.has(f(x)):
return False
return x**order in coeff.args
elif coeff.is_Pow:
return coeff.as_base_exp() == (x, order)
elif order == 1:
return x == coeff
return False
if r and not any(not _test_term(r[i], i) for i in r if i >= 0):
if not r[-1]:
matching_hints["nth_linear_euler_eq_homogeneous"] = r
else:
matching_hints["nth_linear_euler_eq_nonhomogeneous_variation_of_parameters"] = r
matching_hints["nth_linear_euler_eq_nonhomogeneous_variation_of_parameters_Integral"] = r
e, re = posify(r[-1].subs(x, exp(x)))
undetcoeff = _undetermined_coefficients_match(e.subs(re), x)
if undetcoeff['test']:
r['trialset'] = undetcoeff['trialset']
matching_hints["nth_linear_euler_eq_nonhomogeneous_undetermined_coefficients"] = r
# Order keys based on allhints.
retlist = [i for i in allhints if i in matching_hints]
if dict:
# Dictionaries are ordered arbitrarily, so make note of which
# hint would come first for dsolve(). Use an ordered dict in Py 3.
matching_hints["default"] = retlist[0] if retlist else None
matching_hints["ordered_hints"] = tuple(retlist)
return matching_hints
else:
return tuple(retlist)
def classify_sysode(eq, funcs=None, **kwargs):
r"""
Returns a dictionary of parameter names and values that define the system
of ordinary differential equations in ``eq``.
The parameters are further used in
:py:meth:`~sympy.solvers.ode.dsolve` for solving that system.
The parameter names and values are:
'is_linear' (boolean), which tells whether the given system is linear.
Note that "linear" here refers to the operator: terms such as ``x*diff(x,t)`` are
nonlinear, whereas terms like ``sin(t)*diff(x,t)`` are still linear operators.
'func' (list) contains the :py:class:`~sympy.core.function.Function`s that
appear with a derivative in the ODE, i.e. those that we are trying to solve
the ODE for.
'order' (dict) with the maximum derivative for each element of the 'func'
parameter.
'func_coeff' (dict) with the coefficient for each triple ``(equation number,
function, order)```. The coefficients are those subexpressions that do not
appear in 'func', and hence can be considered constant for purposes of ODE
solving.
'eq' (list) with the equations from ``eq``, sympified and transformed into
expressions (we are solving for these expressions to be zero).
'no_of_equations' (int) is the number of equations (same as ``len(eq)``).
'type_of_equation' (string) is an internal classification of the type of
ODE.
References
==========
-http://eqworld.ipmnet.ru/en/solutions/sysode/sode-toc1.htm
-A. D. Polyanin and A. V. Manzhirov, Handbook of Mathematics for Engineers and Scientists
Examples
========
>>> from sympy import Function, Eq, symbols, diff
>>> from sympy.solvers.ode import classify_sysode
>>> from sympy.abc import t
>>> f, x, y = symbols('f, x, y', function=True)
>>> k, l, m, n = symbols('k, l, m, n', Integer=True)
>>> x1 = diff(x(t), t) ; y1 = diff(y(t), t)
>>> x2 = diff(x(t), t, t) ; y2 = diff(y(t), t, t)
>>> eq = (Eq(5*x1, 12*x(t) - 6*y(t)), Eq(2*y1, 11*x(t) + 3*y(t)))
>>> classify_sysode(eq)
{'eq': [-12*x(t) + 6*y(t) + 5*Derivative(x(t), t), -11*x(t) - 3*y(t) + 2*Derivative(y(t), t)],
'func': [x(t), y(t)], 'func_coeff': {(0, x(t), 0): -12, (0, x(t), 1): 5, (0, y(t), 0): 6,
(0, y(t), 1): 0, (1, x(t), 0): -11, (1, x(t), 1): 0, (1, y(t), 0): -3, (1, y(t), 1): 2},
'is_linear': True, 'no_of_equation': 2, 'order': {x(t): 1, y(t): 1}, 'type_of_equation': 'type1'}
>>> eq = (Eq(diff(x(t),t), 5*t*x(t) + t**2*y(t)), Eq(diff(y(t),t), -t**2*x(t) + 5*t*y(t)))
>>> classify_sysode(eq)
{'eq': [-t**2*y(t) - 5*t*x(t) + Derivative(x(t), t), t**2*x(t) - 5*t*y(t) + Derivative(y(t), t)],
'func': [x(t), y(t)], 'func_coeff': {(0, x(t), 0): -5*t, (0, x(t), 1): 1, (0, y(t), 0): -t**2,
(0, y(t), 1): 0, (1, x(t), 0): t**2, (1, x(t), 1): 0, (1, y(t), 0): -5*t, (1, y(t), 1): 1},
'is_linear': True, 'no_of_equation': 2, 'order': {x(t): 1, y(t): 1}, 'type_of_equation': 'type4'}
"""
# Sympify equations and convert iterables of equations into
# a list of equations
def _sympify(eq):
return list(map(sympify, eq if iterable(eq) else [eq]))
eq, funcs = (_sympify(w) for w in [eq, funcs])
for i, fi in enumerate(eq):
if isinstance(fi, Equality):
eq[i] = fi.lhs - fi.rhs
matching_hints = {"no_of_equation":i+1}
matching_hints['eq'] = eq
if i==0:
raise ValueError("classify_sysode() works for systems of ODEs. "
"For scalar ODEs, classify_ode should be used")
t = list(list(eq[0].atoms(Derivative))[0].atoms(Symbol))[0]
# find all the functions if not given
order = dict()
if funcs==[None]:
funcs = []
for eqs in eq:
derivs = eqs.atoms(Derivative)
func = set().union(*[d.atoms(AppliedUndef) for d in derivs])
for func_ in func:
funcs.append(func_)
funcs = list(set(funcs))
if len(funcs) < len(eq):
raise ValueError("Number of functions given is less than number of equations %s" % funcs)
func_dict = dict()
for func in funcs:
if not order.get(func, False):
max_order = 0
for i, eqs_ in enumerate(eq):
order_ = ode_order(eqs_,func)
if max_order < order_:
max_order = order_
eq_no = i
if eq_no in func_dict:
list_func = []
list_func.append(func_dict[eq_no])
list_func.append(func)
func_dict[eq_no] = list_func
else:
func_dict[eq_no] = func
order[func] = max_order
funcs = [func_dict[i] for i in range(len(func_dict))]
matching_hints['func'] = funcs
for func in funcs:
if isinstance(func, list):
for func_elem in func:
if len(func_elem.args) != 1:
raise ValueError("dsolve() and classify_sysode() work with "
"functions of one variable only, not %s" % func)
else:
if func and len(func.args) != 1:
raise ValueError("dsolve() and classify_sysode() work with "
"functions of one variable only, not %s" % func)
# find the order of all equation in system of odes
matching_hints["order"] = order
# find coefficients of terms f(t), diff(f(t),t) and higher derivatives
# and similarly for other functions g(t), diff(g(t),t) in all equations.
# Here j denotes the equation number, funcs[l] denotes the function about
# which we are talking about and k denotes the order of function funcs[l]
# whose coefficient we are calculating.
def linearity_check(eqs, j, func, is_linear_):
for k in range(order[func]+1):
func_coef[j,func,k] = collect(eqs.expand(),[diff(func,t,k)]).coeff(diff(func,t,k))
if is_linear_ == True:
if func_coef[j,func,k]==0:
if k==0:
coef = eqs.as_independent(func)[1]
for xr in range(1, ode_order(eqs,func)+1):
coef -= eqs.as_independent(diff(func,t,xr))[1]
if coef != 0:
is_linear_ = False
else:
if eqs.as_independent(diff(func,t,k))[1]:
is_linear_ = False
else:
for func_ in funcs:
if isinstance(func_, list):
for elem_func_ in func_:
dep = func_coef[j,func,k].as_independent(elem_func_)[1]
if dep!=1 and dep!=0:
is_linear_ = False
else:
dep = func_coef[j,func,k].as_independent(func_)[1]
if dep!=1 and dep!=0:
is_linear_ = False
return is_linear_
func_coef = {}
is_linear = True
for j, eqs in enumerate(eq):
for func in funcs:
if isinstance(func, list):
for func_elem in func:
is_linear = linearity_check(eqs, j, func_elem, is_linear)
else:
is_linear = linearity_check(eqs, j, func, is_linear)
matching_hints['func_coeff'] = func_coef
matching_hints['is_linear'] = is_linear
if len(set(order.values()))==1:
order_eq = list(matching_hints['order'].values())[0]
if matching_hints['is_linear'] == True:
if matching_hints['no_of_equation'] == 2:
if order_eq == 1:
type_of_equation = check_linear_2eq_order1(eq, funcs, func_coef)
elif order_eq == 2:
type_of_equation = check_linear_2eq_order2(eq, funcs, func_coef)
else:
type_of_equation = None
elif matching_hints['no_of_equation'] == 3:
if order_eq == 1:
type_of_equation = check_linear_3eq_order1(eq, funcs, func_coef)
if type_of_equation==None:
type_of_equation = check_linear_neq_order1(eq, funcs, func_coef)
else:
type_of_equation = None
else:
if order_eq == 1:
type_of_equation = check_linear_neq_order1(eq, funcs, func_coef)
else:
type_of_equation = None
else:
if matching_hints['no_of_equation'] == 2:
if order_eq == 1:
type_of_equation = check_nonlinear_2eq_order1(eq, funcs, func_coef)
else:
type_of_equation = None
elif matching_hints['no_of_equation'] == 3:
if order_eq == 1:
type_of_equation = check_nonlinear_3eq_order1(eq, funcs, func_coef)
else:
type_of_equation = None
else:
type_of_equation = None
else:
type_of_equation = None
matching_hints['type_of_equation'] = type_of_equation
return matching_hints
def check_linear_2eq_order1(eq, func, func_coef):
x = func[0].func
y = func[1].func
fc = func_coef
t = list(list(eq[0].atoms(Derivative))[0].atoms(Symbol))[0]
r = dict()
# for equations Eq(a1*diff(x(t),t), b1*x(t) + c1*y(t) + d1)
# and Eq(a2*diff(y(t),t), b2*x(t) + c2*y(t) + d2)
r['a1'] = fc[0,x(t),1] ; r['a2'] = fc[1,y(t),1]
r['b1'] = -fc[0,x(t),0]/fc[0,x(t),1] ; r['b2'] = -fc[1,x(t),0]/fc[1,y(t),1]
r['c1'] = -fc[0,y(t),0]/fc[0,x(t),1] ; r['c2'] = -fc[1,y(t),0]/fc[1,y(t),1]
forcing = [S(0),S(0)]
for i in range(2):
for j in Add.make_args(eq[i]):
if not j.has(x(t), y(t)):
forcing[i] += j
if not (forcing[0].has(t) or forcing[1].has(t)):
# We can handle homogeneous case and simple constant forcings
r['d1'] = forcing[0]
r['d2'] = forcing[1]
else:
# Issue #9244: nonhomogeneous linear systems are not supported
return None
# Conditions to check for type 6 whose equations are Eq(diff(x(t),t), f(t)*x(t) + g(t)*y(t)) and
# Eq(diff(y(t),t), a*[f(t) + a*h(t)]x(t) + a*[g(t) - h(t)]*y(t))
p = 0
q = 0
p1 = cancel(r['b2']/(cancel(r['b2']/r['c2']).as_numer_denom()[0]))
p2 = cancel(r['b1']/(cancel(r['b1']/r['c1']).as_numer_denom()[0]))
for n, i in enumerate([p1, p2]):
for j in Mul.make_args(collect_const(i)):
if not j.has(t):
q = j
if q and n==0:
if ((r['b2']/j - r['b1'])/(r['c1'] - r['c2']/j)) == j:
p = 1
elif q and n==1:
if ((r['b1']/j - r['b2'])/(r['c2'] - r['c1']/j)) == j:
p = 2
# End of condition for type 6
if r['d1']!=0 or r['d2']!=0:
if not r['d1'].has(t) and not r['d2'].has(t):
if all(not r[k].has(t) for k in 'a1 a2 b1 b2 c1 c2'.split()):
# Equations for type 2 are Eq(a1*diff(x(t),t),b1*x(t)+c1*y(t)+d1) and Eq(a2*diff(y(t),t),b2*x(t)+c2*y(t)+d2)
return "type2"
else:
return None
else:
if all(not r[k].has(t) for k in 'a1 a2 b1 b2 c1 c2'.split()):
# Equations for type 1 are Eq(a1*diff(x(t),t),b1*x(t)+c1*y(t)) and Eq(a2*diff(y(t),t),b2*x(t)+c2*y(t))
return "type1"
else:
r['b1'] = r['b1']/r['a1'] ; r['b2'] = r['b2']/r['a2']
r['c1'] = r['c1']/r['a1'] ; r['c2'] = r['c2']/r['a2']
if (r['b1'] == r['c2']) and (r['c1'] == r['b2']):
# Equation for type 3 are Eq(diff(x(t),t), f(t)*x(t) + g(t)*y(t)) and Eq(diff(y(t),t), g(t)*x(t) + f(t)*y(t))
return "type3"
elif (r['b1'] == r['c2']) and (r['c1'] == -r['b2']) or (r['b1'] == -r['c2']) and (r['c1'] == r['b2']):
# Equation for type 4 are Eq(diff(x(t),t), f(t)*x(t) + g(t)*y(t)) and Eq(diff(y(t),t), -g(t)*x(t) + f(t)*y(t))
return "type4"
elif (not cancel(r['b2']/r['c1']).has(t) and not cancel((r['c2']-r['b1'])/r['c1']).has(t)) \
or (not cancel(r['b1']/r['c2']).has(t) and not cancel((r['c1']-r['b2'])/r['c2']).has(t)):
# Equations for type 5 are Eq(diff(x(t),t), f(t)*x(t) + g(t)*y(t)) and Eq(diff(y(t),t), a*g(t)*x(t) + [f(t) + b*g(t)]*y(t)
return "type5"
elif p:
return "type6"
else:
# Equations for type 7 are Eq(diff(x(t),t), f(t)*x(t) + g(t)*y(t)) and Eq(diff(y(t),t), h(t)*x(t) + p(t)*y(t))
return "type7"
def check_linear_2eq_order2(eq, func, func_coef):
x = func[0].func
y = func[1].func
fc = func_coef
t = list(list(eq[0].atoms(Derivative))[0].atoms(Symbol))[0]
r = dict()
a = Wild('a', exclude=[1/t])
b = Wild('b', exclude=[1/t**2])
u = Wild('u', exclude=[t, t**2])
v = Wild('v', exclude=[t, t**2])
w = Wild('w', exclude=[t, t**2])
p = Wild('p', exclude=[t, t**2])
r['a1'] = fc[0,x(t),2] ; r['a2'] = fc[1,y(t),2]
r['b1'] = fc[0,x(t),1] ; r['b2'] = fc[1,x(t),1]
r['c1'] = fc[0,y(t),1] ; r['c2'] = fc[1,y(t),1]
r['d1'] = fc[0,x(t),0] ; r['d2'] = fc[1,x(t),0]
r['e1'] = fc[0,y(t),0] ; r['e2'] = fc[1,y(t),0]
const = [S(0), S(0)]
for i in range(2):
for j in Add.make_args(eq[i]):
if not (j.has(x(t)) or j.has(y(t))):
const[i] += j
r['f1'] = const[0]
r['f2'] = const[1]
if r['f1']!=0 or r['f2']!=0:
if all(not r[k].has(t) for k in 'a1 a2 d1 d2 e1 e2 f1 f2'.split()) \
and r['b1']==r['c1']==r['b2']==r['c2']==0:
return "type2"
elif all(not r[k].has(t) for k in 'a1 a2 b1 b2 c1 c2 d1 d2 e1 e1'.split()):
p = [S(0), S(0)] ; q = [S(0), S(0)]
for n, e in enumerate([r['f1'], r['f2']]):
if e.has(t):
tpart = e.as_independent(t, Mul)[1]
for i in Mul.make_args(tpart):
if i.has(exp):
b, e = i.as_base_exp()
co = e.coeff(t)
if co and not co.has(t) and co.has(I):
p[n] = 1
else:
q[n] = 1
else:
q[n] = 1
else:
q[n] = 1
if p[0]==1 and p[1]==1 and q[0]==0 and q[1]==0:
return "type4"
else:
return None
else:
return None
else:
if r['b1']==r['b2']==r['c1']==r['c2']==0 and all(not r[k].has(t) \
for k in 'a1 a2 d1 d2 e1 e2'.split()):
return "type1"
elif r['b1']==r['e1']==r['c2']==r['d2']==0 and all(not r[k].has(t) \
for k in 'a1 a2 b2 c1 d1 e2'.split()) and r['c1'] == -r['b2'] and \
r['d1'] == r['e2']:
return "type3"
elif cancel(-r['b2']/r['d2'])==t and cancel(-r['c1']/r['e1'])==t and not \
(r['d2']/r['a2']).has(t) and not (r['e1']/r['a1']).has(t) and \
r['b1']==r['d1']==r['c2']==r['e2']==0:
return "type5"
elif ((r['a1']/r['d1']).expand()).match((p*(u*t**2+v*t+w)**2).expand()) and not \
(cancel(r['a1']*r['d2']/(r['a2']*r['d1']))).has(t) and not (r['d1']/r['e1']).has(t) and not \
(r['d2']/r['e2']).has(t) and r['b1'] == r['b2'] == r['c1'] == r['c2'] == 0:
return "type10"
elif not cancel(r['d1']/r['e1']).has(t) and not cancel(r['d2']/r['e2']).has(t) and not \
cancel(r['d1']*r['a2']/(r['d2']*r['a1'])).has(t) and r['b1']==r['b2']==r['c1']==r['c2']==0:
return "type6"
elif not cancel(r['b1']/r['c1']).has(t) and not cancel(r['b2']/r['c2']).has(t) and not \
cancel(r['b1']*r['a2']/(r['b2']*r['a1'])).has(t) and r['d1']==r['d2']==r['e1']==r['e2']==0:
return "type7"
elif cancel(-r['b2']/r['d2'])==t and cancel(-r['c1']/r['e1'])==t and not \
cancel(r['e1']*r['a2']/(r['d2']*r['a1'])).has(t) and r['e1'].has(t) \
and r['b1']==r['d1']==r['c2']==r['e2']==0:
return "type8"
elif (r['b1']/r['a1']).match(a/t) and (r['b2']/r['a2']).match(a/t) and not \
(r['b1']/r['c1']).has(t) and not (r['b2']/r['c2']).has(t) and \
(r['d1']/r['a1']).match(b/t**2) and (r['d2']/r['a2']).match(b/t**2) \
and not (r['d1']/r['e1']).has(t) and not (r['d2']/r['e2']).has(t):
return "type9"
elif -r['b1']/r['d1']==-r['c1']/r['e1']==-r['b2']/r['d2']==-r['c2']/r['e2']==t:
return "type11"
else:
return None
def check_linear_3eq_order1(eq, func, func_coef):
x = func[0].func
y = func[1].func
z = func[2].func
fc = func_coef
t = list(list(eq[0].atoms(Derivative))[0].atoms(Symbol))[0]
r = dict()
r['a1'] = fc[0,x(t),1]; r['a2'] = fc[1,y(t),1]; r['a3'] = fc[2,z(t),1]
r['b1'] = fc[0,x(t),0]; r['b2'] = fc[1,x(t),0]; r['b3'] = fc[2,x(t),0]
r['c1'] = fc[0,y(t),0]; r['c2'] = fc[1,y(t),0]; r['c3'] = fc[2,y(t),0]
r['d1'] = fc[0,z(t),0]; r['d2'] = fc[1,z(t),0]; r['d3'] = fc[2,z(t),0]
forcing = [S(0), S(0), S(0)]
for i in range(3):
for j in Add.make_args(eq[i]):
if not j.has(x(t), y(t), z(t)):
forcing[i] += j
if forcing[0].has(t) or forcing[1].has(t) or forcing[2].has(t):
# We can handle homogeneous case and simple constant forcings.
# Issue #9244: nonhomogeneous linear systems are not supported
return None
if all(not r[k].has(t) for k in 'a1 a2 a3 b1 b2 b3 c1 c2 c3 d1 d2 d3'.split()):
if r['c1']==r['d1']==r['d2']==0:
return 'type1'
elif r['c1'] == -r['b2'] and r['d1'] == -r['b3'] and r['d2'] == -r['c3'] \
and r['b1'] == r['c2'] == r['d3'] == 0:
return 'type2'
elif r['b1'] == r['c2'] == r['d3'] == 0 and r['c1']/r['a1'] == -r['d1']/r['a1'] \
and r['d2']/r['a2'] == -r['b2']/r['a2'] and r['b3']/r['a3'] == -r['c3']/r['a3']:
return 'type3'
else:
return None
else:
for k1 in 'c1 d1 b2 d2 b3 c3'.split():
if r[k1] == 0:
continue
else:
if all(not cancel(r[k1]/r[k]).has(t) for k in 'd1 b2 d2 b3 c3'.split() if r[k]!=0) \
and all(not cancel(r[k1]/(r['b1'] - r[k])).has(t) for k in 'b1 c2 d3'.split() if r['b1']!=r[k]):
return 'type4'
else:
break
return None
def check_linear_neq_order1(eq, func, func_coef):
x = func[0].func
y = func[1].func
z = func[2].func
fc = func_coef
t = list(list(eq[0].atoms(Derivative))[0].atoms(Symbol))[0]
r = dict()
n = len(eq)
for i in range(n):
for j in range(n):
if (fc[i,func[j],0]/fc[i,func[i],1]).has(t):
return None
if len(eq)==3:
return 'type6'
return 'type1'
def check_nonlinear_2eq_order1(eq, func, func_coef):
t = list(list(eq[0].atoms(Derivative))[0].atoms(Symbol))[0]
f = Wild('f')
g = Wild('g')
u, v = symbols('u, v', cls=Dummy)
def check_type(x, y):
r1 = eq[0].match(t*diff(x(t),t) - x(t) + f)
r2 = eq[1].match(t*diff(y(t),t) - y(t) + g)
if not (r1 and r2):
r1 = eq[0].match(diff(x(t),t) - x(t)/t + f/t)
r2 = eq[1].match(diff(y(t),t) - y(t)/t + g/t)
if not (r1 and r2):
r1 = (-eq[0]).match(t*diff(x(t),t) - x(t) + f)
r2 = (-eq[1]).match(t*diff(y(t),t) - y(t) + g)
if not (r1 and r2):
r1 = (-eq[0]).match(diff(x(t),t) - x(t)/t + f/t)
r2 = (-eq[1]).match(diff(y(t),t) - y(t)/t + g/t)
if r1 and r2 and not (r1[f].subs(diff(x(t),t),u).subs(diff(y(t),t),v).has(t) \
or r2[g].subs(diff(x(t),t),u).subs(diff(y(t),t),v).has(t)):
return 'type5'
else:
return None
for func_ in func:
if isinstance(func_, list):
x = func[0][0].func
y = func[0][1].func
eq_type = check_type(x, y)
if not eq_type:
eq_type = check_type(y, x)
return eq_type
x = func[0].func
y = func[1].func
fc = func_coef
n = Wild('n', exclude=[x(t),y(t)])
f1 = Wild('f1', exclude=[v,t])
f2 = Wild('f2', exclude=[v,t])
g1 = Wild('g1', exclude=[u,t])
g2 = Wild('g2', exclude=[u,t])
for i in range(2):
eqs = 0
for terms in Add.make_args(eq[i]):
eqs += terms/fc[i,func[i],1]
eq[i] = eqs
r = eq[0].match(diff(x(t),t) - x(t)**n*f)
if r:
g = (diff(y(t),t) - eq[1])/r[f]
if r and not (g.has(x(t)) or g.subs(y(t),v).has(t) or r[f].subs(x(t),u).subs(y(t),v).has(t)):
return 'type1'
r = eq[0].match(diff(x(t),t) - exp(n*x(t))*f)
if r:
g = (diff(y(t),t) - eq[1])/r[f]
if r and not (g.has(x(t)) or g.subs(y(t),v).has(t) or r[f].subs(x(t),u).subs(y(t),v).has(t)):
return 'type2'
g = Wild('g')
r1 = eq[0].match(diff(x(t),t) - f)
r2 = eq[1].match(diff(y(t),t) - g)
if r1 and r2 and not (r1[f].subs(x(t),u).subs(y(t),v).has(t) or \
r2[g].subs(x(t),u).subs(y(t),v).has(t)):
return 'type3'
r1 = eq[0].match(diff(x(t),t) - f)
r2 = eq[1].match(diff(y(t),t) - g)
num, den = (
(r1[f].subs(x(t),u).subs(y(t),v))/
(r2[g].subs(x(t),u).subs(y(t),v))).as_numer_denom()
R1 = num.match(f1*g1)
R2 = den.match(f2*g2)
phi = (r1[f].subs(x(t),u).subs(y(t),v))/num
if R1 and R2:
return 'type4'
return None
def check_nonlinear_2eq_order2(eq, func, func_coef):
return None
def check_nonlinear_3eq_order1(eq, func, func_coef):
x = func[0].func
y = func[1].func
z = func[2].func
fc = func_coef
t = list(list(eq[0].atoms(Derivative))[0].atoms(Symbol))[0]
u, v, w = symbols('u, v, w', cls=Dummy)
a = Wild('a', exclude=[x(t), y(t), z(t), t])
b = Wild('b', exclude=[x(t), y(t), z(t), t])
c = Wild('c', exclude=[x(t), y(t), z(t), t])
f = Wild('f')
F1 = Wild('F1')
F2 = Wild('F2')
F3 = Wild('F3')
for i in range(3):
eqs = 0
for terms in Add.make_args(eq[i]):
eqs += terms/fc[i,func[i],1]
eq[i] = eqs
r1 = eq[0].match(diff(x(t),t) - a*y(t)*z(t))
r2 = eq[1].match(diff(y(t),t) - b*z(t)*x(t))
r3 = eq[2].match(diff(z(t),t) - c*x(t)*y(t))
if r1 and r2 and r3:
num1, den1 = r1[a].as_numer_denom()
num2, den2 = r2[b].as_numer_denom()
num3, den3 = r3[c].as_numer_denom()
if solve([num1*u-den1*(v-w), num2*v-den2*(w-u), num3*w-den3*(u-v)],[u, v]):
return 'type1'
r = eq[0].match(diff(x(t),t) - y(t)*z(t)*f)
if r:
r1 = collect_const(r[f]).match(a*f)
r2 = ((diff(y(t),t) - eq[1])/r1[f]).match(b*z(t)*x(t))
r3 = ((diff(z(t),t) - eq[2])/r1[f]).match(c*x(t)*y(t))
if r1 and r2 and r3:
num1, den1 = r1[a].as_numer_denom()
num2, den2 = r2[b].as_numer_denom()
num3, den3 = r3[c].as_numer_denom()
if solve([num1*u-den1*(v-w), num2*v-den2*(w-u), num3*w-den3*(u-v)],[u, v]):
return 'type2'
r = eq[0].match(diff(x(t),t) - (F2-F3))
if r:
r1 = collect_const(r[F2]).match(c*F2)
r1.update(collect_const(r[F3]).match(b*F3))
if r1:
if eq[1].has(r1[F2]) and not eq[1].has(r1[F3]):
r1[F2], r1[F3] = r1[F3], r1[F2]
r1[c], r1[b] = -r1[b], -r1[c]
r2 = eq[1].match(diff(y(t),t) - a*r1[F3] + r1[c]*F1)
if r2:
r3 = (eq[2] == diff(z(t),t) - r1[b]*r2[F1] + r2[a]*r1[F2])
if r1 and r2 and r3:
return 'type3'
r = eq[0].match(diff(x(t),t) - z(t)*F2 + y(t)*F3)
if r:
r1 = collect_const(r[F2]).match(c*F2)
r1.update(collect_const(r[F3]).match(b*F3))
if r1:
if eq[1].has(r1[F2]) and not eq[1].has(r1[F3]):
r1[F2], r1[F3] = r1[F3], r1[F2]
r1[c], r1[b] = -r1[b], -r1[c]
r2 = (diff(y(t),t) - eq[1]).match(a*x(t)*r1[F3] - r1[c]*z(t)*F1)
if r2:
r3 = (diff(z(t),t) - eq[2] == r1[b]*y(t)*r2[F1] - r2[a]*x(t)*r1[F2])
if r1 and r2 and r3:
return 'type4'
r = (diff(x(t),t) - eq[0]).match(x(t)*(F2 - F3))
if r:
r1 = collect_const(r[F2]).match(c*F2)
r1.update(collect_const(r[F3]).match(b*F3))
if r1:
if eq[1].has(r1[F2]) and not eq[1].has(r1[F3]):
r1[F2], r1[F3] = r1[F3], r1[F2]
r1[c], r1[b] = -r1[b], -r1[c]
r2 = (diff(y(t),t) - eq[1]).match(y(t)*(a*r1[F3] - r1[c]*F1))
if r2:
r3 = (diff(z(t),t) - eq[2] == z(t)*(r1[b]*r2[F1] - r2[a]*r1[F2]))
if r1 and r2 and r3:
return 'type5'
return None
def check_nonlinear_3eq_order2(eq, func, func_coef):
return None
def checksysodesol(eqs, sols, func=None):
r"""
Substitutes corresponding ``sols`` for each functions into each ``eqs`` and
checks that the result of substitutions for each equation is ``0``. The
equations and solutions passed can be any iterable.
This only works when each ``sols`` have one function only, like `x(t)` or `y(t)`.
For each function, ``sols`` can have a single solution or a list of solutions.
In most cases it will not be necessary to explicitly identify the function,
but if the function cannot be inferred from the original equation it
can be supplied through the ``func`` argument.
When a sequence of equations is passed, the same sequence is used to return
the result for each equation with each function substitued with corresponding
solutions.
It tries the following method to find zero equivalence for each equation:
Substitute the solutions for functions, like `x(t)` and `y(t)` into the
original equations containing those functions.
This function returns a tuple. The first item in the tuple is ``True`` if
the substitution results for each equation is ``0``, and ``False`` otherwise.
The second item in the tuple is what the substitution results in. Each element
of the ``list`` should always be ``0`` corresponding to each equation if the
first item is ``True``. Note that sometimes this function may return ``False``,
but with an expression that is identically equal to ``0``, instead of returning
``True``. This is because :py:meth:`~sympy.simplify.simplify.simplify` cannot
reduce the expression to ``0``. If an expression returned by each function
vanishes identically, then ``sols`` really is a solution to ``eqs``.
If this function seems to hang, it is probably because of a difficult simplification.
Examples
========
>>> from sympy import Eq, diff, symbols, sin, cos, exp, sqrt, S
>>> from sympy.solvers.ode import checksysodesol
>>> C1, C2 = symbols('C1:3')
>>> t = symbols('t')
>>> x, y = symbols('x, y', function=True)
>>> eq = (Eq(diff(x(t),t), x(t) + y(t) + 17), Eq(diff(y(t),t), -2*x(t) + y(t) + 12))
>>> sol = [Eq(x(t), (C1*sin(sqrt(2)*t) + C2*cos(sqrt(2)*t))*exp(t) - S(5)/3),
... Eq(y(t), (sqrt(2)*C1*cos(sqrt(2)*t) - sqrt(2)*C2*sin(sqrt(2)*t))*exp(t) - S(46)/3)]
>>> checksysodesol(eq, sol)
(True, [0, 0])
>>> eq = (Eq(diff(x(t),t),x(t)*y(t)**4), Eq(diff(y(t),t),y(t)**3))
>>> sol = [Eq(x(t), C1*exp(-1/(4*(C2 + t)))), Eq(y(t), -sqrt(2)*sqrt(-1/(C2 + t))/2),
... Eq(x(t), C1*exp(-1/(4*(C2 + t)))), Eq(y(t), sqrt(2)*sqrt(-1/(C2 + t))/2)]
>>> checksysodesol(eq, sol)
(True, [0, 0])
"""
def _sympify(eq):
return list(map(sympify, eq if iterable(eq) else [eq]))
eqs = _sympify(eqs)
for i in range(len(eqs)):
if isinstance(eqs[i], Equality):
eqs[i] = eqs[i].lhs - eqs[i].rhs
if func is None:
funcs = []
for eq in eqs:
derivs = eq.atoms(Derivative)
func = set().union(*[d.atoms(AppliedUndef) for d in derivs])
for func_ in func:
funcs.append(func_)
funcs = list(set(funcs))
if not all(isinstance(func, AppliedUndef) and len(func.args) == 1 for func in funcs)\
and len({func.args for func in funcs})!=1:
raise ValueError("func must be a function of one variable, not %s" % func)
for sol in sols:
if len(sol.atoms(AppliedUndef)) != 1:
raise ValueError("solutions should have one function only")
if len(funcs) != len({sol.lhs for sol in sols}):
raise ValueError("number of solutions provided does not match the number of equations")
t = funcs[0].args[0]
dictsol = dict()
for sol in sols:
func = list(sol.atoms(AppliedUndef))[0]
if sol.rhs == func:
sol = sol.reversed
solved = sol.lhs == func and not sol.rhs.has(func)
if not solved:
rhs = solve(sol, func)
if not rhs:
raise NotImplementedError
else:
rhs = sol.rhs
dictsol[func] = rhs
checkeq = []
for eq in eqs:
for func in funcs:
eq = sub_func_doit(eq, func, dictsol[func])
ss = simplify(eq)
if ss != 0:
eq = ss.expand(force=True)
else:
eq = 0
checkeq.append(eq)
if len(set(checkeq)) == 1 and list(set(checkeq))[0] == 0:
return (True, checkeq)
else:
return (False, checkeq)
@vectorize(0)
def odesimp(eq, func, order, constants, hint):
r"""
Simplifies ODEs, including trying to solve for ``func`` and running
:py:meth:`~sympy.solvers.ode.constantsimp`.
It may use knowledge of the type of solution that the hint returns to
apply additional simplifications.
It also attempts to integrate any :py:class:`~sympy.integrals.Integral`\s
in the expression, if the hint is not an ``_Integral`` hint.
This function should have no effect on expressions returned by
:py:meth:`~sympy.solvers.ode.dsolve`, as
:py:meth:`~sympy.solvers.ode.dsolve` already calls
:py:meth:`~sympy.solvers.ode.odesimp`, but the individual hint functions
do not call :py:meth:`~sympy.solvers.ode.odesimp` (because the
:py:meth:`~sympy.solvers.ode.dsolve` wrapper does). Therefore, this
function is designed for mainly internal use.
Examples
========
>>> from sympy import sin, symbols, dsolve, pprint, Function
>>> from sympy.solvers.ode import odesimp
>>> x , u2, C1= symbols('x,u2,C1')
>>> f = Function('f')
>>> eq = dsolve(x*f(x).diff(x) - f(x) - x*sin(f(x)/x), f(x),
... hint='1st_homogeneous_coeff_subs_indep_div_dep_Integral',
... simplify=False)
>>> pprint(eq, wrap_line=False)
x
----
f(x)
/
|
| / 1 \
| -|u2 + -------|
| | /1 \|
| | sin|--||
| \ \u2//
log(f(x)) = log(C1) + | ---------------- d(u2)
| 2
| u2
|
/
>>> pprint(odesimp(eq, f(x), 1, {C1},
... hint='1st_homogeneous_coeff_subs_indep_div_dep'
... )) #doctest: +SKIP
x
--------- = C1
/f(x)\
tan|----|
\2*x /
"""
x = func.args[0]
f = func.func
C1 = get_numbered_constants(eq, num=1)
# First, integrate if the hint allows it.
eq = _handle_Integral(eq, func, order, hint)
if hint.startswith("nth_linear_euler_eq_nonhomogeneous"):
eq = simplify(eq)
if not isinstance(eq, Equality):
raise TypeError("eq should be an instance of Equality")
# Second, clean up the arbitrary constants.
# Right now, nth linear hints can put as many as 2*order constants in an
# expression. If that number grows with another hint, the third argument
# here should be raised accordingly, or constantsimp() rewritten to handle
# an arbitrary number of constants.
eq = constantsimp(eq, constants)
# Lastly, now that we have cleaned up the expression, try solving for func.
# When CRootOf is implemented in solve(), we will want to return a CRootOf
# everytime instead of an Equality.
# Get the f(x) on the left if possible.
if eq.rhs == func and not eq.lhs.has(func):
eq = [Eq(eq.rhs, eq.lhs)]
# make sure we are working with lists of solutions in simplified form.
if eq.lhs == func and not eq.rhs.has(func):
# The solution is already solved
eq = [eq]
# special simplification of the rhs
if hint.startswith("nth_linear_constant_coeff"):
# Collect terms to make the solution look nice.
# This is also necessary for constantsimp to remove unnecessary
# terms from the particular solution from variation of parameters
#
# Collect is not behaving reliably here. The results for
# some linear constant-coefficient equations with repeated
# roots do not properly simplify all constants sometimes.
# 'collectterms' gives different orders sometimes, and results
# differ in collect based on that order. The
# sort-reverse trick fixes things, but may fail in the
# future. In addition, collect is splitting exponentials with
# rational powers for no reason. We have to do a match
# to fix this using Wilds.
global collectterms
try:
collectterms.sort(key=default_sort_key)
collectterms.reverse()
except Exception:
pass
assert len(eq) == 1 and eq[0].lhs == f(x)
sol = eq[0].rhs
sol = expand_mul(sol)
for i, reroot, imroot in collectterms:
sol = collect(sol, x**i*exp(reroot*x)*sin(abs(imroot)*x))
sol = collect(sol, x**i*exp(reroot*x)*cos(imroot*x))
for i, reroot, imroot in collectterms:
sol = collect(sol, x**i*exp(reroot*x))
del collectterms
# Collect is splitting exponentials with rational powers for
# no reason. We call powsimp to fix.
sol = powsimp(sol)
eq[0] = Eq(f(x), sol)
else:
# The solution is not solved, so try to solve it
try:
floats = any(i.is_Float for i in eq.atoms(Number))
eqsol = solve(eq, func, force=True, rational=False if floats else None)
if not eqsol:
raise NotImplementedError
except (NotImplementedError, PolynomialError):
eq = [eq]
else:
def _expand(expr):
numer, denom = expr.as_numer_denom()
if denom.is_Add:
return expr
else:
return powsimp(expr.expand(), combine='exp', deep=True)
# XXX: the rest of odesimp() expects each ``t`` to be in a
# specific normal form: rational expression with numerator
# expanded, but with combined exponential functions (at
# least in this setup all tests pass).
eq = [Eq(f(x), _expand(t)) for t in eqsol]
# special simplification of the lhs.
if hint.startswith("1st_homogeneous_coeff"):
for j, eqi in enumerate(eq):
newi = logcombine(eqi, force=True)
if newi.lhs.func is log and newi.rhs == 0:
newi = Eq(newi.lhs.args[0]/C1, C1)
eq[j] = newi
# We cleaned up the constants before solving to help the solve engine with
# a simpler expression, but the solved expression could have introduced
# things like -C1, so rerun constantsimp() one last time before returning.
for i, eqi in enumerate(eq):
eq[i] = constantsimp(eqi, constants)
eq[i] = constant_renumber(eq[i], 'C', 1, 2*order)
# If there is only 1 solution, return it;
# otherwise return the list of solutions.
if len(eq) == 1:
eq = eq[0]
return eq
def checkodesol(ode, sol, func=None, order='auto', solve_for_func=True):
r"""
Substitutes ``sol`` into ``ode`` and checks that the result is ``0``.
This only works when ``func`` is one function, like `f(x)`. ``sol`` can
be a single solution or a list of solutions. Each solution may be an
:py:class:`~sympy.core.relational.Equality` that the solution satisfies,
e.g. ``Eq(f(x), C1), Eq(f(x) + C1, 0)``; or simply an
:py:class:`~sympy.core.expr.Expr`, e.g. ``f(x) - C1``. In most cases it
will not be necessary to explicitly identify the function, but if the
function cannot be inferred from the original equation it can be supplied
through the ``func`` argument.
If a sequence of solutions is passed, the same sort of container will be
used to return the result for each solution.
It tries the following methods, in order, until it finds zero equivalence:
1. Substitute the solution for `f` in the original equation. This only
works if ``ode`` is solved for `f`. It will attempt to solve it first
unless ``solve_for_func == False``.
2. Take `n` derivatives of the solution, where `n` is the order of
``ode``, and check to see if that is equal to the solution. This only
works on exact ODEs.
3. Take the 1st, 2nd, ..., `n`\th derivatives of the solution, each time
solving for the derivative of `f` of that order (this will always be
possible because `f` is a linear operator). Then back substitute each
derivative into ``ode`` in reverse order.
This function returns a tuple. The first item in the tuple is ``True`` if
the substitution results in ``0``, and ``False`` otherwise. The second
item in the tuple is what the substitution results in. It should always
be ``0`` if the first item is ``True``. Note that sometimes this function
will ``False``, but with an expression that is identically equal to ``0``,
instead of returning ``True``. This is because
:py:meth:`~sympy.simplify.simplify.simplify` cannot reduce the expression
to ``0``. If an expression returned by this function vanishes
identically, then ``sol`` really is a solution to ``ode``.
If this function seems to hang, it is probably because of a hard
simplification.
To use this function to test, test the first item of the tuple.
Examples
========
>>> from sympy import Eq, Function, checkodesol, symbols
>>> x, C1 = symbols('x,C1')
>>> f = Function('f')
>>> checkodesol(f(x).diff(x), Eq(f(x), C1))
(True, 0)
>>> assert checkodesol(f(x).diff(x), C1)[0]
>>> assert not checkodesol(f(x).diff(x), x)[0]
>>> checkodesol(f(x).diff(x, 2), x**2)
(False, 2)
"""
if not isinstance(ode, Equality):
ode = Eq(ode, 0)
if func is None:
try:
_, func = _preprocess(ode.lhs)
except ValueError:
funcs = [s.atoms(AppliedUndef) for s in (
sol if is_sequence(sol, set) else [sol])]
funcs = set().union(*funcs)
if len(funcs) != 1:
raise ValueError(
'must pass func arg to checkodesol for this case.')
func = funcs.pop()
if not isinstance(func, AppliedUndef) or len(func.args) != 1:
raise ValueError(
"func must be a function of one variable, not %s" % func)
if is_sequence(sol, set):
return type(sol)([checkodesol(ode, i, order=order, solve_for_func=solve_for_func) for i in sol])
if not isinstance(sol, Equality):
sol = Eq(func, sol)
elif sol.rhs == func:
sol = sol.reversed
if order == 'auto':
order = ode_order(ode, func)
solved = sol.lhs == func and not sol.rhs.has(func)
if solve_for_func and not solved:
rhs = solve(sol, func)
if rhs:
eqs = [Eq(func, t) for t in rhs]
if len(rhs) == 1:
eqs = eqs[0]
return checkodesol(ode, eqs, order=order,
solve_for_func=False)
s = True
testnum = 0
x = func.args[0]
while s:
if testnum == 0:
# First pass, try substituting a solved solution directly into the
# ODE. This has the highest chance of succeeding.
ode_diff = ode.lhs - ode.rhs
if sol.lhs == func:
s = sub_func_doit(ode_diff, func, sol.rhs)
else:
testnum += 1
continue
ss = simplify(s)
if ss:
# with the new numer_denom in power.py, if we do a simple
# expansion then testnum == 0 verifies all solutions.
s = ss.expand(force=True)
else:
s = 0
testnum += 1
elif testnum == 1:
# Second pass. If we cannot substitute f, try seeing if the nth
# derivative is equal, this will only work for odes that are exact,
# by definition.
s = simplify(
trigsimp(diff(sol.lhs, x, order) - diff(sol.rhs, x, order)) -
trigsimp(ode.lhs) + trigsimp(ode.rhs))
# s2 = simplify(
# diff(sol.lhs, x, order) - diff(sol.rhs, x, order) - \
# ode.lhs + ode.rhs)
testnum += 1
elif testnum == 2:
# Third pass. Try solving for df/dx and substituting that into the
# ODE. Thanks to Chris Smith for suggesting this method. Many of
# the comments below are his, too.
# The method:
# - Take each of 1..n derivatives of the solution.
# - Solve each nth derivative for d^(n)f/dx^(n)
# (the differential of that order)
# - Back substitute into the ODE in decreasing order
# (i.e., n, n-1, ...)
# - Check the result for zero equivalence
if sol.lhs == func and not sol.rhs.has(func):
diffsols = {0: sol.rhs}
elif sol.rhs == func and not sol.lhs.has(func):
diffsols = {0: sol.lhs}
else:
diffsols = {}
sol = sol.lhs - sol.rhs
for i in range(1, order + 1):
# Differentiation is a linear operator, so there should always
# be 1 solution. Nonetheless, we test just to make sure.
# We only need to solve once. After that, we automatically
# have the solution to the differential in the order we want.
if i == 1:
ds = sol.diff(x)
try:
sdf = solve(ds, func.diff(x, i))
if not sdf:
raise NotImplementedError
except NotImplementedError:
testnum += 1
break
else:
diffsols[i] = sdf[0]
else:
# This is what the solution says df/dx should be.
diffsols[i] = diffsols[i - 1].diff(x)
# Make sure the above didn't fail.
if testnum > 2:
continue
else:
# Substitute it into ODE to check for self consistency.
lhs, rhs = ode.lhs, ode.rhs
for i in range(order, -1, -1):
if i == 0 and 0 not in diffsols:
# We can only substitute f(x) if the solution was
# solved for f(x).
break
lhs = sub_func_doit(lhs, func.diff(x, i), diffsols[i])
rhs = sub_func_doit(rhs, func.diff(x, i), diffsols[i])
ode_or_bool = Eq(lhs, rhs)
ode_or_bool = simplify(ode_or_bool)
if isinstance(ode_or_bool, (bool, BooleanAtom)):
if ode_or_bool:
lhs = rhs = S.Zero
else:
lhs = ode_or_bool.lhs
rhs = ode_or_bool.rhs
# No sense in overworking simplify -- just prove that the
# numerator goes to zero
num = trigsimp((lhs - rhs).as_numer_denom()[0])
# since solutions are obtained using force=True we test
# using the same level of assumptions
## replace function with dummy so assumptions will work
_func = Dummy('func')
num = num.subs(func, _func)
## posify the expression
num, reps = posify(num)
s = simplify(num).xreplace(reps).xreplace({_func: func})
testnum += 1
else:
break
if not s:
return (True, s)
elif s is True: # The code above never was able to change s
raise NotImplementedError("Unable to test if " + str(sol) +
" is a solution to " + str(ode) + ".")
else:
return (False, s)
def ode_sol_simplicity(sol, func, trysolving=True):
r"""
Returns an extended integer representing how simple a solution to an ODE
is.
The following things are considered, in order from most simple to least:
- ``sol`` is solved for ``func``.
- ``sol`` is not solved for ``func``, but can be if passed to solve (e.g.,
a solution returned by ``dsolve(ode, func, simplify=False``).
- If ``sol`` is not solved for ``func``, then base the result on the
length of ``sol``, as computed by ``len(str(sol))``.
- If ``sol`` has any unevaluated :py:class:`~sympy.integrals.Integral`\s,
this will automatically be considered less simple than any of the above.
This function returns an integer such that if solution A is simpler than
solution B by above metric, then ``ode_sol_simplicity(sola, func) <
ode_sol_simplicity(solb, func)``.
Currently, the following are the numbers returned, but if the heuristic is
ever improved, this may change. Only the ordering is guaranteed.
+----------------------------------------------+-------------------+
| Simplicity | Return |
+==============================================+===================+
| ``sol`` solved for ``func`` | ``-2`` |
+----------------------------------------------+-------------------+
| ``sol`` not solved for ``func`` but can be | ``-1`` |
+----------------------------------------------+-------------------+
| ``sol`` is not solved nor solvable for | ``len(str(sol))`` |
| ``func`` | |
+----------------------------------------------+-------------------+
| ``sol`` contains an | ``oo`` |
| :py:class:`~sympy.integrals.Integral` | |
+----------------------------------------------+-------------------+
``oo`` here means the SymPy infinity, which should compare greater than
any integer.
If you already know :py:meth:`~sympy.solvers.solvers.solve` cannot solve
``sol``, you can use ``trysolving=False`` to skip that step, which is the
only potentially slow step. For example,
:py:meth:`~sympy.solvers.ode.dsolve` with the ``simplify=False`` flag
should do this.
If ``sol`` is a list of solutions, if the worst solution in the list
returns ``oo`` it returns that, otherwise it returns ``len(str(sol))``,
that is, the length of the string representation of the whole list.
Examples
========
This function is designed to be passed to ``min`` as the key argument,
such as ``min(listofsolutions, key=lambda i: ode_sol_simplicity(i,
f(x)))``.
>>> from sympy import symbols, Function, Eq, tan, cos, sqrt, Integral
>>> from sympy.solvers.ode import ode_sol_simplicity
>>> x, C1, C2 = symbols('x, C1, C2')
>>> f = Function('f')
>>> ode_sol_simplicity(Eq(f(x), C1*x**2), f(x))
-2
>>> ode_sol_simplicity(Eq(x**2 + f(x), C1), f(x))
-1
>>> ode_sol_simplicity(Eq(f(x), C1*Integral(2*x, x)), f(x))
oo
>>> eq1 = Eq(f(x)/tan(f(x)/(2*x)), C1)
>>> eq2 = Eq(f(x)/tan(f(x)/(2*x) + f(x)), C2)
>>> [ode_sol_simplicity(eq, f(x)) for eq in [eq1, eq2]]
[28, 35]
>>> min([eq1, eq2], key=lambda i: ode_sol_simplicity(i, f(x)))
Eq(f(x)/tan(f(x)/(2*x)), C1)
"""
# TODO: if two solutions are solved for f(x), we still want to be
# able to get the simpler of the two
# See the docstring for the coercion rules. We check easier (faster)
# things here first, to save time.
if iterable(sol):
# See if there are Integrals
for i in sol:
if ode_sol_simplicity(i, func, trysolving=trysolving) == oo:
return oo
return len(str(sol))
if sol.has(Integral):
return oo
# Next, try to solve for func. This code will change slightly when CRootOf
# is implemented in solve(). Probably a CRootOf solution should fall
# somewhere between a normal solution and an unsolvable expression.
# First, see if they are already solved
if sol.lhs == func and not sol.rhs.has(func) or \
sol.rhs == func and not sol.lhs.has(func):
return -2
# We are not so lucky, try solving manually
if trysolving:
try:
sols = solve(sol, func)
if not sols:
raise NotImplementedError
except NotImplementedError:
pass
else:
return -1
# Finally, a naive computation based on the length of the string version
# of the expression. This may favor combined fractions because they
# will not have duplicate denominators, and may slightly favor expressions
# with fewer additions and subtractions, as those are separated by spaces
# by the printer.
# Additional ideas for simplicity heuristics are welcome, like maybe
# checking if a equation has a larger domain, or if constantsimp has
# introduced arbitrary constants numbered higher than the order of a
# given ODE that sol is a solution of.
return len(str(sol))
def _get_constant_subexpressions(expr, Cs):
Cs = set(Cs)
Ces = []
def _recursive_walk(expr):
expr_syms = expr.free_symbols
if len(expr_syms) > 0 and expr_syms.issubset(Cs):
Ces.append(expr)
else:
if expr.func == exp:
expr = expr.expand(mul=True)
if expr.func in (Add, Mul):
d = sift(expr.args, lambda i : i.free_symbols.issubset(Cs))
if len(d[True]) > 1:
x = expr.func(*d[True])
if not x.is_number:
Ces.append(x)
elif isinstance(expr, Integral):
if expr.free_symbols.issubset(Cs) and \
all(len(x) == 3 for x in expr.limits):
Ces.append(expr)
for i in expr.args:
_recursive_walk(i)
return
_recursive_walk(expr)
return Ces
def __remove_linear_redundancies(expr, Cs):
cnts = {i: expr.count(i) for i in Cs}
Cs = [i for i in Cs if cnts[i] > 0]
def _linear(expr):
if expr.func is Add:
xs = [i for i in Cs if expr.count(i)==cnts[i] \
and 0 == expr.diff(i, 2)]
d = {}
for x in xs:
y = expr.diff(x)
if y not in d:
d[y]=[]
d[y].append(x)
for y in d:
if len(d[y]) > 1:
d[y].sort(key=str)
for x in d[y][1:]:
expr = expr.subs(x, 0)
return expr
def _recursive_walk(expr):
if len(expr.args) != 0:
expr = expr.func(*[_recursive_walk(i) for i in expr.args])
expr = _linear(expr)
return expr
if expr.func is Equality:
lhs, rhs = [_recursive_walk(i) for i in expr.args]
f = lambda i: isinstance(i, Number) or i in Cs
if lhs.func is Symbol and lhs in Cs:
rhs, lhs = lhs, rhs
if lhs.func in (Add, Symbol) and rhs.func in (Add, Symbol):
dlhs = sift([lhs] if isinstance(lhs, AtomicExpr) else lhs.args, f)
drhs = sift([rhs] if isinstance(rhs, AtomicExpr) else rhs.args, f)
for i in [True, False]:
for hs in [dlhs, drhs]:
if i not in hs:
hs[i] = [0]
# this calculation can be simplified
lhs = Add(*dlhs[False]) - Add(*drhs[False])
rhs = Add(*drhs[True]) - Add(*dlhs[True])
elif lhs.func in (Mul, Symbol) and rhs.func in (Mul, Symbol):
dlhs = sift([lhs] if isinstance(lhs, AtomicExpr) else lhs.args, f)
if True in dlhs:
if False not in dlhs:
dlhs[False] = [1]
lhs = Mul(*dlhs[False])
rhs = rhs/Mul(*dlhs[True])
return Eq(lhs, rhs)
else:
return _recursive_walk(expr)
@vectorize(0)
def constantsimp(expr, constants):
r"""
Simplifies an expression with arbitrary constants in it.
This function is written specifically to work with
:py:meth:`~sympy.solvers.ode.dsolve`, and is not intended for general use.
Simplification is done by "absorbing" the arbitrary constants into other
arbitrary constants, numbers, and symbols that they are not independent
of.
The symbols must all have the same name with numbers after it, for
example, ``C1``, ``C2``, ``C3``. The ``symbolname`` here would be
'``C``', the ``startnumber`` would be 1, and the ``endnumber`` would be 3.
If the arbitrary constants are independent of the variable ``x``, then the
independent symbol would be ``x``. There is no need to specify the
dependent function, such as ``f(x)``, because it already has the
independent symbol, ``x``, in it.
Because terms are "absorbed" into arbitrary constants and because
constants are renumbered after simplifying, the arbitrary constants in
expr are not necessarily equal to the ones of the same name in the
returned result.
If two or more arbitrary constants are added, multiplied, or raised to the
power of each other, they are first absorbed together into a single
arbitrary constant. Then the new constant is combined into other terms if
necessary.
Absorption of constants is done with limited assistance:
1. terms of :py:class:`~sympy.core.add.Add`\s are collected to try join
constants so `e^x (C_1 \cos(x) + C_2 \cos(x))` will simplify to `e^x
C_1 \cos(x)`;
2. powers with exponents that are :py:class:`~sympy.core.add.Add`\s are
expanded so `e^{C_1 + x}` will be simplified to `C_1 e^x`.
Use :py:meth:`~sympy.solvers.ode.constant_renumber` to renumber constants
after simplification or else arbitrary numbers on constants may appear,
e.g. `C_1 + C_3 x`.
In rare cases, a single constant can be "simplified" into two constants.
Every differential equation solution should have as many arbitrary
constants as the order of the differential equation. The result here will
be technically correct, but it may, for example, have `C_1` and `C_2` in
an expression, when `C_1` is actually equal to `C_2`. Use your discretion
in such situations, and also take advantage of the ability to use hints in
:py:meth:`~sympy.solvers.ode.dsolve`.
Examples
========
>>> from sympy import symbols
>>> from sympy.solvers.ode import constantsimp
>>> C1, C2, C3, x, y = symbols('C1, C2, C3, x, y')
>>> constantsimp(2*C1*x, {C1, C2, C3})
C1*x
>>> constantsimp(C1 + 2 + x, {C1, C2, C3})
C1 + x
>>> constantsimp(C1*C2 + 2 + C2 + C3*x, {C1, C2, C3})
C1 + C3*x
"""
# This function works recursively. The idea is that, for Mul,
# Add, Pow, and Function, if the class has a constant in it, then
# we can simplify it, which we do by recursing down and
# simplifying up. Otherwise, we can skip that part of the
# expression.
Cs = constants
orig_expr = expr
constant_subexprs = _get_constant_subexpressions(expr, Cs)
for xe in constant_subexprs:
xes = list(xe.free_symbols)
if not xes:
continue
if all([expr.count(c) == xe.count(c) for c in xes]):
xes.sort(key=str)
expr = expr.subs(xe, xes[0])
# try to perform common sub-expression elimination of constant terms
try:
commons, rexpr = cse(expr)
commons.reverse()
rexpr = rexpr[0]
for s in commons:
cs = list(s[1].atoms(Symbol))
if len(cs) == 1 and cs[0] in Cs:
rexpr = rexpr.subs(s[0], cs[0])
else:
rexpr = rexpr.subs(*s)
expr = rexpr
except Exception:
pass
expr = __remove_linear_redundancies(expr, Cs)
def _conditional_term_factoring(expr):
new_expr = terms_gcd(expr, clear=False, deep=True, expand=False)
# we do not want to factor exponentials, so handle this separately
if new_expr.is_Mul:
infac = False
asfac = False
for m in new_expr.args:
if m.func is exp:
asfac = True
elif m.is_Add:
infac = any(fi.func is exp for t in m.args
for fi in Mul.make_args(t))
if asfac and infac:
new_expr = expr
break
return new_expr
expr = _conditional_term_factoring(expr)
# call recursively if more simplification is possible
if orig_expr != expr:
return constantsimp(expr, Cs)
return expr
def constant_renumber(expr, symbolname, startnumber, endnumber):
r"""
Renumber arbitrary constants in ``expr`` to have numbers 1 through `N`
where `N` is ``endnumber - startnumber + 1`` at most.
In the process, this reorders expression terms in a standard way.
This is a simple function that goes through and renumbers any
:py:class:`~sympy.core.symbol.Symbol` with a name in the form ``symbolname
+ num`` where ``num`` is in the range from ``startnumber`` to
``endnumber``.
Symbols are renumbered based on ``.sort_key()``, so they should be
numbered roughly in the order that they appear in the final, printed
expression. Note that this ordering is based in part on hashes, so it can
produce different results on different machines.
The structure of this function is very similar to that of
:py:meth:`~sympy.solvers.ode.constantsimp`.
Examples
========
>>> from sympy import symbols, Eq, pprint
>>> from sympy.solvers.ode import constant_renumber
>>> x, C0, C1, C2, C3, C4 = symbols('x,C:5')
Only constants in the given range (inclusive) are renumbered;
the renumbering always starts from 1:
>>> constant_renumber(C1 + C3 + C4, 'C', 1, 3)
C1 + C2 + C4
>>> constant_renumber(C0 + C1 + C3 + C4, 'C', 2, 4)
C0 + 2*C1 + C2
>>> constant_renumber(C0 + 2*C1 + C2, 'C', 0, 1)
C1 + 3*C2
>>> pprint(C2 + C1*x + C3*x**2)
2
C1*x + C2 + C3*x
>>> pprint(constant_renumber(C2 + C1*x + C3*x**2, 'C', 1, 3))
2
C1 + C2*x + C3*x
"""
if type(expr) in (set, list, tuple):
return type(expr)(
[constant_renumber(i, symbolname=symbolname, startnumber=startnumber, endnumber=endnumber)
for i in expr]
)
global newstartnumber
newstartnumber = 1
constants_found = [None]*(endnumber + 2)
constantsymbols = [Symbol(
symbolname + "%d" % t) for t in range(startnumber,
endnumber + 1)]
# make a mapping to send all constantsymbols to S.One and use
# that to make sure that term ordering is not dependent on
# the indexed value of C
C_1 = [(ci, S.One) for ci in constantsymbols]
sort_key=lambda arg: default_sort_key(arg.subs(C_1))
def _constant_renumber(expr):
r"""
We need to have an internal recursive function so that
newstartnumber maintains its values throughout recursive calls.
"""
global newstartnumber
if isinstance(expr, Equality):
return Eq(
_constant_renumber(expr.lhs),
_constant_renumber(expr.rhs))
if type(expr) not in (Mul, Add, Pow) and not expr.is_Function and \
not expr.has(*constantsymbols):
# Base case, as above. Hope there aren't constants inside
# of some other class, because they won't be renumbered.
return expr
elif expr.is_Piecewise:
return expr
elif expr in constantsymbols:
if expr not in constants_found:
constants_found[newstartnumber] = expr
newstartnumber += 1
return expr
elif expr.is_Function or expr.is_Pow or isinstance(expr, Tuple):
return expr.func(
*[_constant_renumber(x) for x in expr.args])
else:
sortedargs = list(expr.args)
sortedargs.sort(key=sort_key)
return expr.func(*[_constant_renumber(x) for x in sortedargs])
expr = _constant_renumber(expr)
# Renumbering happens here
newconsts = symbols('C1:%d' % newstartnumber)
expr = expr.subs(zip(constants_found[1:], newconsts), simultaneous=True)
return expr
def _handle_Integral(expr, func, order, hint):
r"""
Converts a solution with Integrals in it into an actual solution.
For most hints, this simply runs ``expr.doit()``.
"""
global y
x = func.args[0]
f = func.func
if hint == "1st_exact":
sol = (expr.doit()).subs(y, f(x))
del y
elif hint == "1st_exact_Integral":
sol = Eq(Subs(expr.lhs, y, f(x)), expr.rhs)
del y
elif hint == "nth_linear_constant_coeff_homogeneous":
sol = expr
elif not hint.endswith("_Integral"):
sol = expr.doit()
else:
sol = expr
return sol
# FIXME: replace the general solution in the docstring with
# dsolve(equation, hint='1st_exact_Integral'). You will need to be able
# to have assumptions on P and Q that dP/dy = dQ/dx.
def ode_1st_exact(eq, func, order, match):
r"""
Solves 1st order exact ordinary differential equations.
A 1st order differential equation is called exact if it is the total
differential of a function. That is, the differential equation
.. math:: P(x, y) \,\partial{}x + Q(x, y) \,\partial{}y = 0
is exact if there is some function `F(x, y)` such that `P(x, y) =
\partial{}F/\partial{}x` and `Q(x, y) = \partial{}F/\partial{}y`. It can
be shown that a necessary and sufficient condition for a first order ODE
to be exact is that `\partial{}P/\partial{}y = \partial{}Q/\partial{}x`.
Then, the solution will be as given below::
>>> from sympy import Function, Eq, Integral, symbols, pprint
>>> x, y, t, x0, y0, C1= symbols('x,y,t,x0,y0,C1')
>>> P, Q, F= map(Function, ['P', 'Q', 'F'])
>>> pprint(Eq(Eq(F(x, y), Integral(P(t, y), (t, x0, x)) +
... Integral(Q(x0, t), (t, y0, y))), C1))
x y
/ /
| |
F(x, y) = | P(t, y) dt + | Q(x0, t) dt = C1
| |
/ /
x0 y0
Where the first partials of `P` and `Q` exist and are continuous in a
simply connected region.
A note: SymPy currently has no way to represent inert substitution on an
expression, so the hint ``1st_exact_Integral`` will return an integral
with `dy`. This is supposed to represent the function that you are
solving for.
Examples
========
>>> from sympy import Function, dsolve, cos, sin
>>> from sympy.abc import x
>>> f = Function('f')
>>> dsolve(cos(f(x)) - (x*sin(f(x)) - f(x)**2)*f(x).diff(x),
... f(x), hint='1st_exact')
Eq(x*cos(f(x)) + f(x)**3/3, C1)
References
==========
- http://en.wikipedia.org/wiki/Exact_differential_equation
- M. Tenenbaum & H. Pollard, "Ordinary Differential Equations",
Dover 1963, pp. 73
# indirect doctest
"""
x = func.args[0]
f = func.func
r = match # d+e*diff(f(x),x)
e = r[r['e']]
d = r[r['d']]
global y # This is the only way to pass dummy y to _handle_Integral
y = r['y']
C1 = get_numbered_constants(eq, num=1)
# Refer Joel Moses, "Symbolic Integration - The Stormy Decade",
# Communications of the ACM, Volume 14, Number 8, August 1971, pp. 558
# which gives the method to solve an exact differential equation.
sol = Integral(d, x) + Integral((e - (Integral(d, x).diff(y))), y)
return Eq(sol, C1)
def ode_1st_homogeneous_coeff_best(eq, func, order, match):
r"""
Returns the best solution to an ODE from the two hints
``1st_homogeneous_coeff_subs_dep_div_indep`` and
``1st_homogeneous_coeff_subs_indep_div_dep``.
This is as determined by :py:meth:`~sympy.solvers.ode.ode_sol_simplicity`.
See the
:py:meth:`~sympy.solvers.ode.ode_1st_homogeneous_coeff_subs_indep_div_dep`
and
:py:meth:`~sympy.solvers.ode.ode_1st_homogeneous_coeff_subs_dep_div_indep`
docstrings for more information on these hints. Note that there is no
``ode_1st_homogeneous_coeff_best_Integral`` hint.
Examples
========
>>> from sympy import Function, dsolve, pprint
>>> from sympy.abc import x
>>> f = Function('f')
>>> pprint(dsolve(2*x*f(x) + (x**2 + f(x)**2)*f(x).diff(x), f(x),
... hint='1st_homogeneous_coeff_best', simplify=False))
/ 2 \
| 3*x |
log|----- + 1|
| 2 |
\f (x) /
log(f(x)) = log(C1) - --------------
3
References
==========
- http://en.wikipedia.org/wiki/Homogeneous_differential_equation
- M. Tenenbaum & H. Pollard, "Ordinary Differential Equations",
Dover 1963, pp. 59
# indirect doctest
"""
# There are two substitutions that solve the equation, u1=y/x and u2=x/y
# They produce different integrals, so try them both and see which
# one is easier.
sol1 = ode_1st_homogeneous_coeff_subs_indep_div_dep(eq,
func, order, match)
sol2 = ode_1st_homogeneous_coeff_subs_dep_div_indep(eq,
func, order, match)
simplify = match.get('simplify', True)
if simplify:
# why is odesimp called here? Should it be at the usual spot?
constants = sol1.free_symbols.difference(eq.free_symbols)
sol1 = odesimp(
sol1, func, order, constants,
"1st_homogeneous_coeff_subs_indep_div_dep")
constants = sol2.free_symbols.difference(eq.free_symbols)
sol2 = odesimp(
sol2, func, order, constants,
"1st_homogeneous_coeff_subs_dep_div_indep")
return min([sol1, sol2], key=lambda x: ode_sol_simplicity(x, func,
trysolving=not simplify))
def ode_1st_homogeneous_coeff_subs_dep_div_indep(eq, func, order, match):
r"""
Solves a 1st order differential equation with homogeneous coefficients
using the substitution `u_1 = \frac{\text{<dependent
variable>}}{\text{<independent variable>}}`.
This is a differential equation
.. math:: P(x, y) + Q(x, y) dy/dx = 0
such that `P` and `Q` are homogeneous and of the same order. A function
`F(x, y)` is homogeneous of order `n` if `F(x t, y t) = t^n F(x, y)`.
Equivalently, `F(x, y)` can be rewritten as `G(y/x)` or `H(x/y)`. See
also the docstring of :py:meth:`~sympy.solvers.ode.homogeneous_order`.
If the coefficients `P` and `Q` in the differential equation above are
homogeneous functions of the same order, then it can be shown that the
substitution `y = u_1 x` (i.e. `u_1 = y/x`) will turn the differential
equation into an equation separable in the variables `x` and `u`. If
`h(u_1)` is the function that results from making the substitution `u_1 =
f(x)/x` on `P(x, f(x))` and `g(u_2)` is the function that results from the
substitution on `Q(x, f(x))` in the differential equation `P(x, f(x)) +
Q(x, f(x)) f'(x) = 0`, then the general solution is::
>>> from sympy import Function, dsolve, pprint
>>> from sympy.abc import x
>>> f, g, h = map(Function, ['f', 'g', 'h'])
>>> genform = g(f(x)/x) + h(f(x)/x)*f(x).diff(x)
>>> pprint(genform)
/f(x)\ /f(x)\ d
g|----| + h|----|*--(f(x))
\ x / \ x / dx
>>> pprint(dsolve(genform, f(x),
... hint='1st_homogeneous_coeff_subs_dep_div_indep_Integral'))
f(x)
----
x
/
|
| -h(u1)
log(x) = C1 + | ---------------- d(u1)
| u1*h(u1) + g(u1)
|
/
Where `u_1 h(u_1) + g(u_1) \ne 0` and `x \ne 0`.
See also the docstrings of
:py:meth:`~sympy.solvers.ode.ode_1st_homogeneous_coeff_best` and
:py:meth:`~sympy.solvers.ode.ode_1st_homogeneous_coeff_subs_indep_div_dep`.
Examples
========
>>> from sympy import Function, dsolve
>>> from sympy.abc import x
>>> f = Function('f')
>>> pprint(dsolve(2*x*f(x) + (x**2 + f(x)**2)*f(x).diff(x), f(x),
... hint='1st_homogeneous_coeff_subs_dep_div_indep', simplify=False))
/ 3 \
|3*f(x) f (x)|
log|------ + -----|
| x 3 |
\ x /
log(x) = log(C1) - -------------------
3
References
==========
- http://en.wikipedia.org/wiki/Homogeneous_differential_equation
- M. Tenenbaum & H. Pollard, "Ordinary Differential Equations",
Dover 1963, pp. 59
# indirect doctest
"""
x = func.args[0]
f = func.func
u = Dummy('u')
u1 = Dummy('u1') # u1 == f(x)/x
r = match # d+e*diff(f(x),x)
C1 = get_numbered_constants(eq, num=1)
xarg = match.get('xarg', 0)
yarg = match.get('yarg', 0)
int = Integral(
(-r[r['e']]/(r[r['d']] + u1*r[r['e']])).subs({x: 1, r['y']: u1}),
(u1, None, f(x)/x))
sol = logcombine(Eq(log(x), int + log(C1)), force=True)
sol = sol.subs(f(x), u).subs(((u, u - yarg), (x, x - xarg), (u, f(x))))
return sol
def ode_1st_homogeneous_coeff_subs_indep_div_dep(eq, func, order, match):
r"""
Solves a 1st order differential equation with homogeneous coefficients
using the substitution `u_2 = \frac{\text{<independent
variable>}}{\text{<dependent variable>}}`.
This is a differential equation
.. math:: P(x, y) + Q(x, y) dy/dx = 0
such that `P` and `Q` are homogeneous and of the same order. A function
`F(x, y)` is homogeneous of order `n` if `F(x t, y t) = t^n F(x, y)`.
Equivalently, `F(x, y)` can be rewritten as `G(y/x)` or `H(x/y)`. See
also the docstring of :py:meth:`~sympy.solvers.ode.homogeneous_order`.
If the coefficients `P` and `Q` in the differential equation above are
homogeneous functions of the same order, then it can be shown that the
substitution `x = u_2 y` (i.e. `u_2 = x/y`) will turn the differential
equation into an equation separable in the variables `y` and `u_2`. If
`h(u_2)` is the function that results from making the substitution `u_2 =
x/f(x)` on `P(x, f(x))` and `g(u_2)` is the function that results from the
substitution on `Q(x, f(x))` in the differential equation `P(x, f(x)) +
Q(x, f(x)) f'(x) = 0`, then the general solution is:
>>> from sympy import Function, dsolve, pprint
>>> from sympy.abc import x
>>> f, g, h = map(Function, ['f', 'g', 'h'])
>>> genform = g(x/f(x)) + h(x/f(x))*f(x).diff(x)
>>> pprint(genform)
/ x \ / x \ d
g|----| + h|----|*--(f(x))
\f(x)/ \f(x)/ dx
>>> pprint(dsolve(genform, f(x),
... hint='1st_homogeneous_coeff_subs_indep_div_dep_Integral'))
x
----
f(x)
/
|
| -g(u2)
| ---------------- d(u2)
| u2*g(u2) + h(u2)
|
/
<BLANKLINE>
f(x) = C1*e
Where `u_2 g(u_2) + h(u_2) \ne 0` and `f(x) \ne 0`.
See also the docstrings of
:py:meth:`~sympy.solvers.ode.ode_1st_homogeneous_coeff_best` and
:py:meth:`~sympy.solvers.ode.ode_1st_homogeneous_coeff_subs_dep_div_indep`.
Examples
========
>>> from sympy import Function, pprint, dsolve
>>> from sympy.abc import x
>>> f = Function('f')
>>> pprint(dsolve(2*x*f(x) + (x**2 + f(x)**2)*f(x).diff(x), f(x),
... hint='1st_homogeneous_coeff_subs_indep_div_dep',
... simplify=False))
/ 2 \
| 3*x |
log|----- + 1|
| 2 |
\f (x) /
log(f(x)) = log(C1) - --------------
3
References
==========
- http://en.wikipedia.org/wiki/Homogeneous_differential_equation
- M. Tenenbaum & H. Pollard, "Ordinary Differential Equations",
Dover 1963, pp. 59
# indirect doctest
"""
x = func.args[0]
f = func.func
u = Dummy('u')
u2 = Dummy('u2') # u2 == x/f(x)
r = match # d+e*diff(f(x),x)
C1 = get_numbered_constants(eq, num=1)
xarg = match.get('xarg', 0) # If xarg present take xarg, else zero
yarg = match.get('yarg', 0) # If yarg present take yarg, else zero
int = Integral(
simplify(
(-r[r['d']]/(r[r['e']] + u2*r[r['d']])).subs({x: u2, r['y']: 1})),
(u2, None, x/f(x)))
sol = logcombine(Eq(log(f(x)), int + log(C1)), force=True)
sol = sol.subs(f(x), u).subs(((u, u - yarg), (x, x - xarg), (u, f(x))))
return sol
# XXX: Should this function maybe go somewhere else?
def homogeneous_order(eq, *symbols):
r"""
Returns the order `n` if `g` is homogeneous and ``None`` if it is not
homogeneous.
Determines if a function is homogeneous and if so of what order. A
function `f(x, y, \cdots)` is homogeneous of order `n` if `f(t x, t y,
\cdots) = t^n f(x, y, \cdots)`.
If the function is of two variables, `F(x, y)`, then `f` being homogeneous
of any order is equivalent to being able to rewrite `F(x, y)` as `G(x/y)`
or `H(y/x)`. This fact is used to solve 1st order ordinary differential
equations whose coefficients are homogeneous of the same order (see the
docstrings of
:py:meth:`~solvers.ode.ode_1st_homogeneous_coeff_subs_dep_div_indep` and
:py:meth:`~solvers.ode.ode_1st_homogeneous_coeff_subs_indep_div_dep`).
Symbols can be functions, but every argument of the function must be a
symbol, and the arguments of the function that appear in the expression
must match those given in the list of symbols. If a declared function
appears with different arguments than given in the list of symbols,
``None`` is returned.
Examples
========
>>> from sympy import Function, homogeneous_order, sqrt
>>> from sympy.abc import x, y
>>> f = Function('f')
>>> homogeneous_order(f(x), f(x)) is None
True
>>> homogeneous_order(f(x,y), f(y, x), x, y) is None
True
>>> homogeneous_order(f(x), f(x), x)
1
>>> homogeneous_order(x**2*f(x)/sqrt(x**2+f(x)**2), x, f(x))
2
>>> homogeneous_order(x**2+f(x), x, f(x)) is None
True
"""
if not symbols:
raise ValueError("homogeneous_order: no symbols were given.")
symset = set(symbols)
eq = sympify(eq)
# The following are not supported
if eq.has(Order, Derivative):
return None
# These are all constants
if (eq.is_Number or
eq.is_NumberSymbol or
eq.is_number
):
return S.Zero
# Replace all functions with dummy variables
dum = numbered_symbols(prefix='d', cls=Dummy)
newsyms = set()
for i in [j for j in symset if getattr(j, 'is_Function')]:
iargs = set(i.args)
if iargs.difference(symset):
return None
else:
dummyvar = next(dum)
eq = eq.subs(i, dummyvar)
symset.remove(i)
newsyms.add(dummyvar)
symset.update(newsyms)
if not eq.free_symbols & symset:
return None
# assuming order of a nested function can only be equal to zero
if isinstance(eq, Function):
return None if homogeneous_order(
eq.args[0], *tuple(symset)) != 0 else S.Zero
# make the replacement of x with x*t and see if t can be factored out
t = Dummy('t', positive=True) # It is sufficient that t > 0
eqs = separatevars(eq.subs([(i, t*i) for i in symset]), [t], dict=True)[t]
if eqs is S.One:
return S.Zero # there was no term with only t
i, d = eqs.as_independent(t, as_Add=False)
b, e = d.as_base_exp()
if b == t:
return e
def ode_1st_linear(eq, func, order, match):
r"""
Solves 1st order linear differential equations.
These are differential equations of the form
.. math:: dy/dx + P(x) y = Q(x)\text{.}
These kinds of differential equations can be solved in a general way. The
integrating factor `e^{\int P(x) \,dx}` will turn the equation into a
separable equation. The general solution is::
>>> from sympy import Function, dsolve, Eq, pprint, diff, sin
>>> from sympy.abc import x
>>> f, P, Q = map(Function, ['f', 'P', 'Q'])
>>> genform = Eq(f(x).diff(x) + P(x)*f(x), Q(x))
>>> pprint(genform)
d
P(x)*f(x) + --(f(x)) = Q(x)
dx
>>> pprint(dsolve(genform, f(x), hint='1st_linear_Integral'))
/ / \
| | |
| | / | /
| | | | |
| | | P(x) dx | - | P(x) dx
| | | | |
| | / | /
f(x) = |C1 + | Q(x)*e dx|*e
| | |
\ / /
Examples
========
>>> f = Function('f')
>>> pprint(dsolve(Eq(x*diff(f(x), x) - f(x), x**2*sin(x)),
... f(x), '1st_linear'))
f(x) = x*(C1 - cos(x))
References
==========
- http://en.wikipedia.org/wiki/Linear_differential_equation#First_order_equation
- M. Tenenbaum & H. Pollard, "Ordinary Differential Equations",
Dover 1963, pp. 92
# indirect doctest
"""
x = func.args[0]
f = func.func
r = match # a*diff(f(x),x) + b*f(x) + c
C1 = get_numbered_constants(eq, num=1)
t = exp(Integral(r[r['b']]/r[r['a']], x))
tt = Integral(t*(-r[r['c']]/r[r['a']]), x)
f = match.get('u', f(x)) # take almost-linear u if present, else f(x)
return Eq(f, (tt + C1)/t)
def ode_Bernoulli(eq, func, order, match):
r"""
Solves Bernoulli differential equations.
These are equations of the form
.. math:: dy/dx + P(x) y = Q(x) y^n\text{, }n \ne 1`\text{.}
The substitution `w = 1/y^{1-n}` will transform an equation of this form
into one that is linear (see the docstring of
:py:meth:`~sympy.solvers.ode.ode_1st_linear`). The general solution is::
>>> from sympy import Function, dsolve, Eq, pprint
>>> from sympy.abc import x, n
>>> f, P, Q = map(Function, ['f', 'P', 'Q'])
>>> genform = Eq(f(x).diff(x) + P(x)*f(x), Q(x)*f(x)**n)
>>> pprint(genform)
d n
P(x)*f(x) + --(f(x)) = Q(x)*f (x)
dx
>>> pprint(dsolve(genform, f(x), hint='Bernoulli_Integral')) #doctest: +SKIP
1
----
1 - n
// / \ \
|| | | |
|| | / | / |
|| | | | | |
|| | (1 - n)* | P(x) dx | (-1 + n)* | P(x) dx|
|| | | | | |
|| | / | / |
f(x) = ||C1 + (-1 + n)* | -Q(x)*e dx|*e |
|| | | |
\\ / / /
Note that the equation is separable when `n = 1` (see the docstring of
:py:meth:`~sympy.solvers.ode.ode_separable`).
>>> pprint(dsolve(Eq(f(x).diff(x) + P(x)*f(x), Q(x)*f(x)), f(x),
... hint='separable_Integral'))
f(x)
/
| /
| 1 |
| - dy = C1 + | (-P(x) + Q(x)) dx
| y |
| /
/
Examples
========
>>> from sympy import Function, dsolve, Eq, pprint, log
>>> from sympy.abc import x
>>> f = Function('f')
>>> pprint(dsolve(Eq(x*f(x).diff(x) + f(x), log(x)*f(x)**2),
... f(x), hint='Bernoulli'))
1
f(x) = -------------------
/ log(x) 1\
x*|C1 + ------ + -|
\ x x/
References
==========
- http://en.wikipedia.org/wiki/Bernoulli_differential_equation
- M. Tenenbaum & H. Pollard, "Ordinary Differential Equations",
Dover 1963, pp. 95
# indirect doctest
"""
x = func.args[0]
f = func.func
r = match # a*diff(f(x),x) + b*f(x) + c*f(x)**n, n != 1
C1 = get_numbered_constants(eq, num=1)
t = exp((1 - r[r['n']])*Integral(r[r['b']]/r[r['a']], x))
tt = (r[r['n']] - 1)*Integral(t*r[r['c']]/r[r['a']], x)
return Eq(f(x), ((tt + C1)/t)**(1/(1 - r[r['n']])))
def ode_Riccati_special_minus2(eq, func, order, match):
r"""
The general Riccati equation has the form
.. math:: dy/dx = f(x) y^2 + g(x) y + h(x)\text{.}
While it does not have a general solution [1], the "special" form, `dy/dx
= a y^2 - b x^c`, does have solutions in many cases [2]. This routine
returns a solution for `a(dy/dx) = b y^2 + c y/x + d/x^2` that is obtained
by using a suitable change of variables to reduce it to the special form
and is valid when neither `a` nor `b` are zero and either `c` or `d` is
zero.
>>> from sympy.abc import x, y, a, b, c, d
>>> from sympy.solvers.ode import dsolve, checkodesol
>>> from sympy import pprint, Function
>>> f = Function('f')
>>> y = f(x)
>>> genform = a*y.diff(x) - (b*y**2 + c*y/x + d/x**2)
>>> sol = dsolve(genform, y)
>>> pprint(sol, wrap_line=False)
/ / __________________ \\
| __________________ | / 2 ||
| / 2 | \/ 4*b*d - (a + c) *log(x)||
-|a + c - \/ 4*b*d - (a + c) *tan|C1 + ----------------------------||
\ \ 2*a //
f(x) = ------------------------------------------------------------------------
2*b*x
>>> checkodesol(genform, sol, order=1)[0]
True
References
==========
1. http://www.maplesoft.com/support/help/Maple/view.aspx?path=odeadvisor/Riccati
2. http://eqworld.ipmnet.ru/en/solutions/ode/ode0106.pdf -
http://eqworld.ipmnet.ru/en/solutions/ode/ode0123.pdf
"""
x = func.args[0]
f = func.func
r = match # a2*diff(f(x),x) + b2*f(x) + c2*f(x)/x + d2/x**2
a2, b2, c2, d2 = [r[r[s]] for s in 'a2 b2 c2 d2'.split()]
C1 = get_numbered_constants(eq, num=1)
mu = sqrt(4*d2*b2 - (a2 - c2)**2)
return Eq(f(x), (a2 - c2 - mu*tan(mu/(2*a2)*log(x) + C1))/(2*b2*x))
def ode_Liouville(eq, func, order, match):
r"""
Solves 2nd order Liouville differential equations.
The general form of a Liouville ODE is
.. math:: \frac{d^2 y}{dx^2} + g(y) \left(\!
\frac{dy}{dx}\!\right)^2 + h(x)
\frac{dy}{dx}\text{.}
The general solution is:
>>> from sympy import Function, dsolve, Eq, pprint, diff
>>> from sympy.abc import x
>>> f, g, h = map(Function, ['f', 'g', 'h'])
>>> genform = Eq(diff(f(x),x,x) + g(f(x))*diff(f(x),x)**2 +
... h(x)*diff(f(x),x), 0)
>>> pprint(genform)
2 2
/d \ d d
g(f(x))*|--(f(x))| + h(x)*--(f(x)) + ---(f(x)) = 0
\dx / dx 2
dx
>>> pprint(dsolve(genform, f(x), hint='Liouville_Integral'))
f(x)
/ /
| |
| / | /
| | | |
| - | h(x) dx | | g(y) dy
| | | |
| / | /
C1 + C2* | e dx + | e dy = 0
| |
/ /
Examples
========
>>> from sympy import Function, dsolve, Eq, pprint
>>> from sympy.abc import x
>>> f = Function('f')
>>> pprint(dsolve(diff(f(x), x, x) + diff(f(x), x)**2/f(x) +
... diff(f(x), x)/x, f(x), hint='Liouville'))
________________ ________________
[f(x) = -\/ C1 + C2*log(x) , f(x) = \/ C1 + C2*log(x) ]
References
==========
- Goldstein and Braun, "Advanced Methods for the Solution of Differential
Equations", pp. 98
- http://www.maplesoft.com/support/help/Maple/view.aspx?path=odeadvisor/Liouville
# indirect doctest
"""
# Liouville ODE:
# f(x).diff(x, 2) + g(f(x))*(f(x).diff(x, 2))**2 + h(x)*f(x).diff(x)
# See Goldstein and Braun, "Advanced Methods for the Solution of
# Differential Equations", pg. 98, as well as
# http://www.maplesoft.com/support/help/view.aspx?path=odeadvisor/Liouville
x = func.args[0]
f = func.func
r = match # f(x).diff(x, 2) + g*f(x).diff(x)**2 + h*f(x).diff(x)
y = r['y']
C1, C2 = get_numbered_constants(eq, num=2)
int = Integral(exp(Integral(r['g'], y)), (y, None, f(x)))
sol = Eq(int + C1*Integral(exp(-Integral(r['h'], x)), x) + C2, 0)
return sol
def ode_2nd_power_series_ordinary(eq, func, order, match):
r"""
Gives a power series solution to a second order homogeneous differential
equation with polynomial coefficients at an ordinary point. A homogenous
differential equation is of the form
.. math :: P(x)\frac{d^2y}{dx^2} + Q(x)\frac{dy}{dx} + R(x) = 0
For simplicity it is assumed that `P(x)`, `Q(x)` and `R(x)` are polynomials,
it is sufficient that `\frac{Q(x)}{P(x)}` and `\frac{R(x)}{P(x)}` exists at
`x_{0}`. A recurrence relation is obtained by substituting `y` as `\sum_{n=0}^\infty a_{n}x^{n}`,
in the differential equation, and equating the nth term. Using this relation
various terms can be generated.
Examples
========
>>> from sympy import dsolve, Function, pprint
>>> from sympy.abc import x, y
>>> f = Function("f")
>>> eq = f(x).diff(x, 2) + f(x)
>>> pprint(dsolve(eq, hint='2nd_power_series_ordinary'))
/ 4 2 \ / 2 \
|x x | | x | / 6\
f(x) = C2*|-- - -- + 1| + C1*x*|- -- + 1| + O\x /
\24 2 / \ 6 /
References
==========
- http://tutorial.math.lamar.edu/Classes/DE/SeriesSolutions.aspx
- George E. Simmons, "Differential Equations with Applications and
Historical Notes", p.p 176 - 184
"""
x = func.args[0]
f = func.func
C0, C1 = get_numbered_constants(eq, num=2)
n = Dummy("n", integer=True)
s = Wild("s")
k = Wild("k", exclude=[x])
x0 = match.get('x0')
terms = match.get('terms', 5)
p = match[match['a3']]
q = match[match['b3']]
r = match[match['c3']]
seriesdict = {}
recurr = Function("r")
# Generating the recurrence relation which works this way:
# for the second order term the summation begins at n = 2. The coefficients
# p is multiplied with an*(n - 1)*(n - 2)*x**n-2 and a substitution is made such that
# the exponent of x becomes n.
# For example, if p is x, then the second degree recurrence term is
# an*(n - 1)*(n - 2)*x**n-1, substituting (n - 1) as n, it transforms to
# an+1*n*(n - 1)*x**n.
# A similar process is done with the first order and zeroth order term.
coefflist = [(recurr(n), r), (n*recurr(n), q), (n*(n - 1)*recurr(n), p)]
for index, coeff in enumerate(coefflist):
if coeff[1]:
f2 = powsimp(expand((coeff[1]*(x - x0)**(n - index)).subs(x, x + x0)))
if f2.is_Add:
addargs = f2.args
else:
addargs = [f2]
for arg in addargs:
powm = arg.match(s*x**k)
term = coeff[0]*powm[s]
if not powm[k].is_Symbol:
term = term.subs(n, n - powm[k].as_independent(n)[0])
startind = powm[k].subs(n, index)
# Seeing if the startterm can be reduced further.
# If it vanishes for n lesser than startind, it is
# equal to summation from n.
if startind:
for i in reversed(range(startind)):
if not term.subs(n, i):
seriesdict[term] = i
else:
seriesdict[term] = i + 1
break
else:
seriesdict[term] = S(0)
# Stripping of terms so that the sum starts with the same number.
teq = S(0)
suminit = seriesdict.values()
rkeys = seriesdict.keys()
req = Add(*rkeys)
if any(suminit):
maxval = max(suminit)
for term in seriesdict:
val = seriesdict[term]
if val != maxval:
for i in range(val, maxval):
teq += term.subs(n, val)
finaldict = {}
if teq:
fargs = teq.atoms(AppliedUndef)
if len(fargs) == 1:
finaldict[fargs.pop()] = 0
else:
maxf = max(fargs, key = lambda x: x.args[0])
sol = solve(teq, maxf)
if isinstance(sol, list):
sol = sol[0]
finaldict[maxf] = sol
# Finding the recurrence relation in terms of the largest term.
fargs = req.atoms(AppliedUndef)
maxf = max(fargs, key = lambda x: x.args[0])
minf = min(fargs, key = lambda x: x.args[0])
if minf.args[0].is_Symbol:
startiter = 0
else:
startiter = -minf.args[0].as_independent(n)[0]
lhs = maxf
rhs = solve(req, maxf)
if isinstance(rhs, list):
rhs = rhs[0]
# Checking how many values are already present
tcounter = len([t for t in finaldict.values() if t])
for _ in range(tcounter, terms - 3): # Assuming c0 and c1 to be arbitrary
check = rhs.subs(n, startiter)
nlhs = lhs.subs(n, startiter)
nrhs = check.subs(finaldict)
finaldict[nlhs] = nrhs
startiter += 1
# Post processing
series = C0 + C1*(x - x0)
for term in finaldict:
if finaldict[term]:
fact = term.args[0]
series += (finaldict[term].subs([(recurr(0), C0), (recurr(1), C1)])*(
x - x0)**fact)
series = collect(expand_mul(series), [C0, C1]) + Order(x**terms)
return Eq(f(x), series)
def ode_2nd_power_series_regular(eq, func, order, match):
r"""
Gives a power series solution to a second order homogeneous differential
equation with polynomial coefficients at a regular point. A second order
homogenous differential equation is of the form
.. math :: P(x)\frac{d^2y}{dx^2} + Q(x)\frac{dy}{dx} + R(x) = 0
A point is said to regular singular at `x0` if `x - x0\frac{Q(x)}{P(x)}`
and `(x - x0)^{2}\frac{R(x)}{P(x)}` are analytic at `x0`. For simplicity
`P(x)`, `Q(x)` and `R(x)` are assumed to be polynomials. The algorithm for
finding the power series solutions is:
1. Try expressing `(x - x0)P(x)` and `((x - x0)^{2})Q(x)` as power series
solutions about x0. Find `p0` and `q0` which are the constants of the
power series expansions.
2. Solve the indicial equation `f(m) = m(m - 1) + m*p0 + q0`, to obtain the
roots `m1` and `m2` of the indicial equation.
3. If `m1 - m2` is a non integer there exists two series solutions. If
`m1 = m2`, there exists only one solution. If `m1 - m2` is an integer,
then the existence of one solution is confirmed. The other solution may
or may not exist.
The power series solution is of the form `x^{m}\sum_{n=0}^\infty a_{n}x^{n}`. The
coefficients are determined by the following recurrence relation.
`a_{n} = -\frac{\sum_{k=0}^{n-1} q_{n-k} + (m + k)p_{n-k}}{f(m + n)}`. For the case
in which `m1 - m2` is an integer, it can be seen from the recurrence relation
that for the lower root `m`, when `n` equals the difference of both the
roots, the denominator becomes zero. So if the numerator is not equal to zero,
a second series solution exists.
Examples
========
>>> from sympy import dsolve, Function, pprint
>>> from sympy.abc import x, y
>>> f = Function("f")
>>> eq = x*(f(x).diff(x, 2)) + 2*(f(x).diff(x)) + x*f(x)
>>> pprint(dsolve(eq))
/ 6 4 2 \
| x x x |
/ 4 2 \ C1*|- --- + -- - -- + 1|
| x x | \ 720 24 2 / / 6\
f(x) = C2*|--- - -- + 1| + ------------------------ + O\x /
\120 6 / x
References
==========
- George E. Simmons, "Differential Equations with Applications and
Historical Notes", p.p 176 - 184
"""
x = func.args[0]
f = func.func
C0, C1 = get_numbered_constants(eq, num=2)
n = Dummy("n")
m = Dummy("m") # for solving the indicial equation
s = Wild("s")
k = Wild("k", exclude=[x])
x0 = match.get('x0')
terms = match.get('terms', 5)
p = match['p']
q = match['q']
# Generating the indicial equation
indicial = []
for term in [p, q]:
if not term.has(x):
indicial.append(term)
else:
term = series(term, n=1, x0=x0)
if isinstance(term, Order):
indicial.append(S(0))
else:
for arg in term.args:
if not arg.has(x):
indicial.append(arg)
break
p0, q0 = indicial
sollist = solve(m*(m - 1) + m*p0 + q0, m)
if sollist and isinstance(sollist, list) and all(
[sol.is_real for sol in sollist]):
serdict1 = {}
serdict2 = {}
if len(sollist) == 1:
# Only one series solution exists in this case.
m1 = m2 = sollist.pop()
if terms-m1-1 <= 0:
return Eq(f(x), Order(terms))
serdict1 = _frobenius(terms-m1-1, m1, p0, q0, p, q, x0, x, C0)
else:
m1 = sollist[0]
m2 = sollist[1]
if m1 < m2:
m1, m2 = m2, m1
# Irrespective of whether m1 - m2 is an integer or not, one
# Frobenius series solution exists.
serdict1 = _frobenius(terms-m1-1, m1, p0, q0, p, q, x0, x, C0)
if not (m1 - m2).is_integer:
# Second frobenius series solution exists.
serdict2 = _frobenius(terms-m2-1, m2, p0, q0, p, q, x0, x, C1)
else:
# Check if second frobenius series solution exists.
serdict2 = _frobenius(terms-m2-1, m2, p0, q0, p, q, x0, x, C1, check=m1)
if serdict1:
finalseries1 = C0
for key in serdict1:
power = int(key.name[1:])
finalseries1 += serdict1[key]*(x - x0)**power
finalseries1 = (x - x0)**m1*finalseries1
finalseries2 = S(0)
if serdict2:
for key in serdict2:
power = int(key.name[1:])
finalseries2 += serdict2[key]*(x - x0)**power
finalseries2 += C1
finalseries2 = (x - x0)**m2*finalseries2
return Eq(f(x), collect(finalseries1 + finalseries2,
[C0, C1]) + Order(x**terms))
def _frobenius(n, m, p0, q0, p, q, x0, x, c, check=None):
r"""
Returns a dict with keys as coefficients and values as their values in terms of C0
"""
n = int(n)
# In cases where m1 - m2 is not an integer
m2 = check
d = Dummy("d")
numsyms = numbered_symbols("C", start=0)
numsyms = [next(numsyms) for i in range(n + 1)]
C0 = Symbol("C0")
serlist = []
for ser in [p, q]:
# Order term not present
if ser.is_polynomial(x) and Poly(ser, x).degree() <= n:
if x0:
ser = ser.subs(x, x + x0)
dict_ = Poly(ser, x).as_dict()
# Order term present
else:
tseries = series(ser, x=x0, n=n+1)
# Removing order
dict_ = Poly(list(ordered(tseries.args))[: -1], x).as_dict()
# Fill in with zeros, if coefficients are zero.
for i in range(n + 1):
if (i,) not in dict_:
dict_[(i,)] = S(0)
serlist.append(dict_)
pseries = serlist[0]
qseries = serlist[1]
indicial = d*(d - 1) + d*p0 + q0
frobdict = {}
for i in range(1, n + 1):
num = c*(m*pseries[(i,)] + qseries[(i,)])
for j in range(1, i):
sym = Symbol("C" + str(j))
num += frobdict[sym]*((m + j)*pseries[(i - j,)] + qseries[(i - j,)])
# Checking for cases when m1 - m2 is an integer. If num equals zero
# then a second Frobenius series solution cannot be found. If num is not zero
# then set constant as zero and proceed.
if m2 is not None and i == m2 - m:
if num:
return False
else:
frobdict[numsyms[i]] = S(0)
else:
frobdict[numsyms[i]] = -num/(indicial.subs(d, m+i))
return frobdict
def _nth_linear_match(eq, func, order):
r"""
Matches a differential equation to the linear form:
.. math:: a_n(x) y^{(n)} + \cdots + a_1(x)y' + a_0(x) y + B(x) = 0
Returns a dict of order:coeff terms, where order is the order of the
derivative on each term, and coeff is the coefficient of that derivative.
The key ``-1`` holds the function `B(x)`. Returns ``None`` if the ODE is
not linear. This function assumes that ``func`` has already been checked
to be good.
Examples
========
>>> from sympy import Function, cos, sin
>>> from sympy.abc import x
>>> from sympy.solvers.ode import _nth_linear_match
>>> f = Function('f')
>>> _nth_linear_match(f(x).diff(x, 3) + 2*f(x).diff(x) +
... x*f(x).diff(x, 2) + cos(x)*f(x).diff(x) + x - f(x) -
... sin(x), f(x), 3)
{-1: x - sin(x), 0: -1, 1: cos(x) + 2, 2: x, 3: 1}
>>> _nth_linear_match(f(x).diff(x, 3) + 2*f(x).diff(x) +
... x*f(x).diff(x, 2) + cos(x)*f(x).diff(x) + x - f(x) -
... sin(f(x)), f(x), 3) == None
True
"""
x = func.args[0]
one_x = {x}
terms = {i: S.Zero for i in range(-1, order + 1)}
for i in Add.make_args(eq):
if not i.has(func):
terms[-1] += i
else:
c, f = i.as_independent(func)
if not ((isinstance(f, Derivative) and set(f.variables) == one_x) \
or f == func):
return None
else:
terms[len(f.args[1:])] += c
return terms
def ode_nth_linear_euler_eq_homogeneous(eq, func, order, match, returns='sol'):
r"""
Solves an `n`\th order linear homogeneous variable-coefficient
Cauchy-Euler equidimensional ordinary differential equation.
This is an equation with form `0 = a_0 f(x) + a_1 x f'(x) + a_2 x^2 f''(x)
\cdots`.
These equations can be solved in a general manner, by substituting
solutions of the form `f(x) = x^r`, and deriving a characteristic equation
for `r`. When there are repeated roots, we include extra terms of the
form `C_{r k} \ln^k(x) x^r`, where `C_{r k}` is an arbitrary integration
constant, `r` is a root of the characteristic equation, and `k` ranges
over the multiplicity of `r`. In the cases where the roots are complex,
solutions of the form `C_1 x^a \sin(b \log(x)) + C_2 x^a \cos(b \log(x))`
are returned, based on expansions with Eulers formula. The general
solution is the sum of the terms found. If SymPy cannot find exact roots
to the characteristic equation, a
:py:class:`~sympy.polys.rootoftools.CRootOf` instance will be returned
instead.
>>> from sympy import Function, dsolve, Eq
>>> from sympy.abc import x
>>> f = Function('f')
>>> dsolve(4*x**2*f(x).diff(x, 2) + f(x), f(x),
... hint='nth_linear_euler_eq_homogeneous')
... # doctest: +NORMALIZE_WHITESPACE
Eq(f(x), sqrt(x)*(C1 + C2*log(x)))
Note that because this method does not involve integration, there is no
``nth_linear_euler_eq_homogeneous_Integral`` hint.
The following is for internal use:
- ``returns = 'sol'`` returns the solution to the ODE.
- ``returns = 'list'`` returns a list of linearly independent solutions,
corresponding to the fundamental solution set, for use with non
homogeneous solution methods like variation of parameters and
undetermined coefficients. Note that, though the solutions should be
linearly independent, this function does not explicitly check that. You
can do ``assert simplify(wronskian(sollist)) != 0`` to check for linear
independence. Also, ``assert len(sollist) == order`` will need to pass.
- ``returns = 'both'``, return a dictionary ``{'sol': <solution to ODE>,
'list': <list of linearly independent solutions>}``.
Examples
========
>>> from sympy import Function, dsolve, pprint
>>> from sympy.abc import x
>>> f = Function('f')
>>> eq = f(x).diff(x, 2)*x**2 - 4*f(x).diff(x)*x + 6*f(x)
>>> pprint(dsolve(eq, f(x),
... hint='nth_linear_euler_eq_homogeneous'))
2
f(x) = x *(C1 + C2*x)
References
==========
- http://en.wikipedia.org/wiki/Cauchy%E2%80%93Euler_equation
- C. Bender & S. Orszag, "Advanced Mathematical Methods for Scientists and
Engineers", Springer 1999, pp. 12
# indirect doctest
"""
global collectterms
collectterms = []
x = func.args[0]
f = func.func
r = match
# First, set up characteristic equation.
chareq, symbol = S.Zero, Dummy('x')
for i in r.keys():
if not isinstance(i, str) and i >= 0:
chareq += (r[i]*diff(x**symbol, x, i)*x**-symbol).expand()
chareq = Poly(chareq, symbol)
chareqroots = [rootof(chareq, k) for k in range(chareq.degree())]
# A generator of constants
constants = list(get_numbered_constants(eq, num=chareq.degree()*2))
constants.reverse()
# Create a dict root: multiplicity or charroots
charroots = defaultdict(int)
for root in chareqroots:
charroots[root] += 1
gsol = S(0)
# We need keep track of terms so we can run collect() at the end.
# This is necessary for constantsimp to work properly.
ln = log
for root, multiplicity in charroots.items():
for i in range(multiplicity):
if isinstance(root, RootOf):
gsol += (x**root) * constants.pop()
if multiplicity != 1:
raise ValueError("Value should be 1")
collectterms = [(0, root, 0)] + collectterms
elif root.is_real:
gsol += ln(x)**i*(x**root) * constants.pop()
collectterms = [(i, root, 0)] + collectterms
else:
reroot = re(root)
imroot = im(root)
gsol += ln(x)**i * (x**reroot) * (
constants.pop() * sin(abs(imroot)*ln(x))
+ constants.pop() * cos(imroot*ln(x)))
# Preserve ordering (multiplicity, real part, imaginary part)
# It will be assumed implicitly when constructing
# fundamental solution sets.
collectterms = [(i, reroot, imroot)] + collectterms
if returns == 'sol':
return Eq(f(x), gsol)
elif returns in ('list' 'both'):
# HOW TO TEST THIS CODE? (dsolve does not pass 'returns' through)
# Create a list of (hopefully) linearly independent solutions
gensols = []
# Keep track of when to use sin or cos for nonzero imroot
for i, reroot, imroot in collectterms:
if imroot == 0:
gensols.append(ln(x)**i*x**reroot)
else:
sin_form = ln(x)**i*x**reroot*sin(abs(imroot)*ln(x))
if sin_form in gensols:
cos_form = ln(x)**i*x**reroot*cos(imroot*ln(x))
gensols.append(cos_form)
else:
gensols.append(sin_form)
if returns == 'list':
return gensols
else:
return {'sol': Eq(f(x), gsol), 'list': gensols}
else:
raise ValueError('Unknown value for key "returns".')
def ode_nth_linear_euler_eq_nonhomogeneous_undetermined_coefficients(eq, func, order, match, returns='sol'):
r"""
Solves an `n`\th order linear non homogeneous Cauchy-Euler equidimensional
ordinary differential equation using undetermined coefficients.
This is an equation with form `g(x) = a_0 f(x) + a_1 x f'(x) + a_2 x^2 f''(x)
\cdots`.
These equations can be solved in a general manner, by substituting
solutions of the form `x = exp(t)`, and deriving a characteristic equation
of form `g(exp(t)) = b_0 f(t) + b_1 f'(t) + b_2 f''(t) \cdots` which can
be then solved by nth_linear_constant_coeff_undetermined_coefficients if
g(exp(t)) has finite number of lineary independent derivatives.
Functions that fit this requirement are finite sums functions of the form
`a x^i e^{b x} \sin(c x + d)` or `a x^i e^{b x} \cos(c x + d)`, where `i`
is a non-negative integer and `a`, `b`, `c`, and `d` are constants. For
example any polynomial in `x`, functions like `x^2 e^{2 x}`, `x \sin(x)`,
and `e^x \cos(x)` can all be used. Products of `\sin`'s and `\cos`'s have
a finite number of derivatives, because they can be expanded into `\sin(a
x)` and `\cos(b x)` terms. However, SymPy currently cannot do that
expansion, so you will need to manually rewrite the expression in terms of
the above to use this method. So, for example, you will need to manually
convert `\sin^2(x)` into `(1 + \cos(2 x))/2` to properly apply the method
of undetermined coefficients on it.
After replacement of x by exp(t), this method works by creating a trial function
from the expression and all of its linear independent derivatives and
substituting them into the original ODE. The coefficients for each term
will be a system of linear equations, which are be solved for and
substituted, giving the solution. If any of the trial functions are linearly
dependent on the solution to the homogeneous equation, they are multiplied
by sufficient `x` to make them linearly independent.
Examples
========
>>> from sympy import dsolve, Function, Derivative, log
>>> from sympy.abc import x
>>> f = Function('f')
>>> eq = x**2*Derivative(f(x), x, x) - 2*x*Derivative(f(x), x) + 2*f(x) - log(x)
>>> dsolve(eq, f(x),
... hint='nth_linear_euler_eq_nonhomogeneous_undetermined_coefficients').expand()
Eq(f(x), C1*x + C2*x**2 + log(x)/2 + 3/4)
"""
x = func.args[0]
f = func.func
r = match
chareq, eq, symbol = S.Zero, S.Zero, Dummy('x')
for i in r.keys():
if not isinstance(i, str) and i >= 0:
chareq += (r[i]*diff(x**symbol, x, i)*x**-symbol).expand()
for i in range(1,degree(Poly(chareq, symbol))+1):
eq += chareq.coeff(symbol**i)*diff(f(x), x, i)
if chareq.as_coeff_add(symbol)[0]:
eq += chareq.as_coeff_add(symbol)[0]*f(x)
e, re = posify(r[-1].subs(x, exp(x)))
eq += e.subs(re)
match = _nth_linear_match(eq, f(x), ode_order(eq, f(x)))
match['trialset'] = r['trialset']
return ode_nth_linear_constant_coeff_undetermined_coefficients(eq, func, order, match).subs(x, log(x)).subs(f(log(x)), f(x)).expand()
def ode_nth_linear_euler_eq_nonhomogeneous_variation_of_parameters(eq, func, order, match, returns='sol'):
r"""
Solves an `n`\th order linear non homogeneous Cauchy-Euler equidimensional
ordinary differential equation using variation of parameters.
This is an equation with form `g(x) = a_0 f(x) + a_1 x f'(x) + a_2 x^2 f''(x)
\cdots`.
This method works by assuming that the particular solution takes the form
.. math:: \sum_{x=1}^{n} c_i(x) y_i(x) {a_n} {x^n} \text{,}
where `y_i` is the `i`\th solution to the homogeneous equation. The
solution is then solved using Wronskian's and Cramer's Rule. The
particular solution is given by multiplying eq given below with `a_n x^{n}`
.. math:: \sum_{x=1}^n \left( \int \frac{W_i(x)}{W(x)} \,dx
\right) y_i(x) \text{,}
where `W(x)` is the Wronskian of the fundamental system (the system of `n`
linearly independent solutions to the homogeneous equation), and `W_i(x)`
is the Wronskian of the fundamental system with the `i`\th column replaced
with `[0, 0, \cdots, 0, \frac{x^{- n}}{a_n} g{\left (x \right )}]`.
This method is general enough to solve any `n`\th order inhomogeneous
linear differential equation, but sometimes SymPy cannot simplify the
Wronskian well enough to integrate it. If this method hangs, try using the
``nth_linear_constant_coeff_variation_of_parameters_Integral`` hint and
simplifying the integrals manually. Also, prefer using
``nth_linear_constant_coeff_undetermined_coefficients`` when it
applies, because it doesn't use integration, making it faster and more
reliable.
Warning, using simplify=False with
'nth_linear_constant_coeff_variation_of_parameters' in
:py:meth:`~sympy.solvers.ode.dsolve` may cause it to hang, because it will
not attempt to simplify the Wronskian before integrating. It is
recommended that you only use simplify=False with
'nth_linear_constant_coeff_variation_of_parameters_Integral' for this
method, especially if the solution to the homogeneous equation has
trigonometric functions in it.
Examples
========
>>> from sympy import Function, dsolve, Derivative
>>> from sympy.abc import x
>>> f = Function('f')
>>> eq = x**2*Derivative(f(x), x, x) - 2*x*Derivative(f(x), x) + 2*f(x) - x**4
>>> dsolve(eq, f(x),
... hint='nth_linear_euler_eq_nonhomogeneous_variation_of_parameters').expand()
Eq(f(x), C1*x + C2*x**2 + x**4/6)
"""
x = func.args[0]
f = func.func
r = match
gensol = ode_nth_linear_euler_eq_homogeneous(eq, func, order, match, returns='both')
match.update(gensol)
r[-1] = r[-1]/r[ode_order(eq, f(x))]
sol = _solve_variation_of_parameters(eq, func, order, match)
return Eq(f(x), r['sol'].rhs + (sol.rhs - r['sol'].rhs)*r[ode_order(eq, f(x))])
def ode_almost_linear(eq, func, order, match):
r"""
Solves an almost-linear differential equation.
The general form of an almost linear differential equation is
.. math:: f(x) g(y) y + k(x) l(y) + m(x) = 0
\text{where} l'(y) = g(y)\text{.}
This can be solved by substituting `l(y) = u(y)`. Making the given
substitution reduces it to a linear differential equation of the form `u'
+ P(x) u + Q(x) = 0`.
The general solution is
>>> from sympy import Function, dsolve, Eq, pprint
>>> from sympy.abc import x, y, n
>>> f, g, k, l = map(Function, ['f', 'g', 'k', 'l'])
>>> genform = Eq(f(x)*(l(y).diff(y)) + k(x)*l(y) + g(x))
>>> pprint(genform)
d
f(x)*--(l(y)) + g(x) + k(x)*l(y) = 0
dy
>>> pprint(dsolve(genform, hint = 'almost_linear'))
/ // -y*g(x) \\
| || -------- for k(x) = 0||
| || f(x) || -y*k(x)
| || || --------
| || y*k(x) || f(x)
l(y) = |C1 + |< ------ ||*e
| || f(x) ||
| ||-g(x)*e ||
| ||-------------- otherwise ||
| || k(x) ||
\ \\ //
See Also
========
:meth:`sympy.solvers.ode.ode_1st_linear`
Examples
========
>>> from sympy import Function, Derivative, pprint
>>> from sympy.solvers.ode import dsolve, classify_ode
>>> from sympy.abc import x
>>> f = Function('f')
>>> d = f(x).diff(x)
>>> eq = x*d + x*f(x) + 1
>>> dsolve(eq, f(x), hint='almost_linear')
Eq(f(x), (C1 - Ei(x))*exp(-x))
>>> pprint(dsolve(eq, f(x), hint='almost_linear'))
-x
f(x) = (C1 - Ei(x))*e
References
==========
- Joel Moses, "Symbolic Integration - The Stormy Decade", Communications
of the ACM, Volume 14, Number 8, August 1971, pp. 558
"""
# Since ode_1st_linear has already been implemented, and the
# coefficients have been modified to the required form in
# classify_ode, just passing eq, func, order and match to
# ode_1st_linear will give the required output.
return ode_1st_linear(eq, func, order, match)
def _linear_coeff_match(expr, func):
r"""
Helper function to match hint ``linear_coefficients``.
Matches the expression to the form `(a_1 x + b_1 f(x) + c_1)/(a_2 x + b_2
f(x) + c_2)` where the following conditions hold:
1. `a_1`, `b_1`, `c_1`, `a_2`, `b_2`, `c_2` are Rationals;
2. `c_1` or `c_2` are not equal to zero;
3. `a_2 b_1 - a_1 b_2` is not equal to zero.
Return ``xarg``, ``yarg`` where
1. ``xarg`` = `(b_2 c_1 - b_1 c_2)/(a_2 b_1 - a_1 b_2)`
2. ``yarg`` = `(a_1 c_2 - a_2 c_1)/(a_2 b_1 - a_1 b_2)`
Examples
========
>>> from sympy import Function
>>> from sympy.abc import x
>>> from sympy.solvers.ode import _linear_coeff_match
>>> from sympy.functions.elementary.trigonometric import sin
>>> f = Function('f')
>>> _linear_coeff_match((
... (-25*f(x) - 8*x + 62)/(4*f(x) + 11*x - 11)), f(x))
(1/9, 22/9)
>>> _linear_coeff_match(
... sin((-5*f(x) - 8*x + 6)/(4*f(x) + x - 1)), f(x))
(19/27, 2/27)
>>> _linear_coeff_match(sin(f(x)/x), f(x))
"""
f = func.func
x = func.args[0]
def abc(eq):
r'''
Internal function of _linear_coeff_match
that returns Rationals a, b, c
if eq is a*x + b*f(x) + c, else None.
'''
eq = _mexpand(eq)
c = eq.as_independent(x, f(x), as_Add=True)[0]
if not c.is_Rational:
return
a = eq.coeff(x)
if not a.is_Rational:
return
b = eq.coeff(f(x))
if not b.is_Rational:
return
if eq == a*x + b*f(x) + c:
return a, b, c
def match(arg):
r'''
Internal function of _linear_coeff_match that returns Rationals a1,
b1, c1, a2, b2, c2 and a2*b1 - a1*b2 of the expression (a1*x + b1*f(x)
+ c1)/(a2*x + b2*f(x) + c2) if one of c1 or c2 and a2*b1 - a1*b2 is
non-zero, else None.
'''
n, d = arg.together().as_numer_denom()
m = abc(n)
if m is not None:
a1, b1, c1 = m
m = abc(d)
if m is not None:
a2, b2, c2 = m
d = a2*b1 - a1*b2
if (c1 or c2) and d:
return a1, b1, c1, a2, b2, c2, d
m = [fi.args[0] for fi in expr.atoms(Function) if fi.func != f and
len(fi.args) == 1 and not fi.args[0].is_Function] or {expr}
m1 = match(m.pop())
if m1 and all(match(mi) == m1 for mi in m):
a1, b1, c1, a2, b2, c2, denom = m1
return (b2*c1 - b1*c2)/denom, (a1*c2 - a2*c1)/denom
def ode_linear_coefficients(eq, func, order, match):
r"""
Solves a differential equation with linear coefficients.
The general form of a differential equation with linear coefficients is
.. math:: y' + F\left(\!\frac{a_1 x + b_1 y + c_1}{a_2 x + b_2 y +
c_2}\!\right) = 0\text{,}
where `a_1`, `b_1`, `c_1`, `a_2`, `b_2`, `c_2` are constants and `a_1 b_2
- a_2 b_1 \ne 0`.
This can be solved by substituting:
.. math:: x = x' + \frac{b_2 c_1 - b_1 c_2}{a_2 b_1 - a_1 b_2}
y = y' + \frac{a_1 c_2 - a_2 c_1}{a_2 b_1 - a_1
b_2}\text{.}
This substitution reduces the equation to a homogeneous differential
equation.
See Also
========
:meth:`sympy.solvers.ode.ode_1st_homogeneous_coeff_best`
:meth:`sympy.solvers.ode.ode_1st_homogeneous_coeff_subs_indep_div_dep`
:meth:`sympy.solvers.ode.ode_1st_homogeneous_coeff_subs_dep_div_indep`
Examples
========
>>> from sympy import Function, Derivative, pprint
>>> from sympy.solvers.ode import dsolve, classify_ode
>>> from sympy.abc import x
>>> f = Function('f')
>>> df = f(x).diff(x)
>>> eq = (x + f(x) + 1)*df + (f(x) - 6*x + 1)
>>> pprint(dsolve(eq, hint='linear_coefficients'))
___________ ___________
/ 2 / 2
[f(x) = -x - \/ C1 + 7*x - 1, f(x) = -x + \/ C1 + 7*x - 1]
References
==========
- Joel Moses, "Symbolic Integration - The Stormy Decade", Communications
of the ACM, Volume 14, Number 8, August 1971, pp. 558
"""
return ode_1st_homogeneous_coeff_best(eq, func, order, match)
def ode_separable_reduced(eq, func, order, match):
r"""
Solves a differential equation that can be reduced to the separable form.
The general form of this equation is
.. math:: y' + (y/x) H(x^n y) = 0\text{}.
This can be solved by substituting `u(y) = x^n y`. The equation then
reduces to the separable form `\frac{u'}{u (\mathrm{power} - H(u))} -
\frac{1}{x} = 0`.
The general solution is:
>>> from sympy import Function, dsolve, Eq, pprint
>>> from sympy.abc import x, n
>>> f, g = map(Function, ['f', 'g'])
>>> genform = f(x).diff(x) + (f(x)/x)*g(x**n*f(x))
>>> pprint(genform)
/ n \
d f(x)*g\x *f(x)/
--(f(x)) + ---------------
dx x
>>> pprint(dsolve(genform, hint='separable_reduced'))
n
x *f(x)
/
|
| 1
| ------------ dy = C1 + log(x)
| y*(n - g(y))
|
/
See Also
========
:meth:`sympy.solvers.ode.ode_separable`
Examples
========
>>> from sympy import Function, Derivative, pprint
>>> from sympy.solvers.ode import dsolve, classify_ode
>>> from sympy.abc import x
>>> f = Function('f')
>>> d = f(x).diff(x)
>>> eq = (x - x**2*f(x))*d - f(x)
>>> pprint(dsolve(eq, hint='separable_reduced'))
___________ ___________
/ 2 / 2
- \/ C1*x + 1 + 1 \/ C1*x + 1 + 1
[f(x) = --------------------, f(x) = ------------------]
x x
References
==========
- Joel Moses, "Symbolic Integration - The Stormy Decade", Communications
of the ACM, Volume 14, Number 8, August 1971, pp. 558
"""
# Arguments are passed in a way so that they are coherent with the
# ode_separable function
x = func.args[0]
f = func.func
y = Dummy('y')
u = match['u'].subs(match['t'], y)
ycoeff = 1/(y*(match['power'] - u))
m1 = {y: 1, x: -1/x, 'coeff': 1}
m2 = {y: ycoeff, x: 1, 'coeff': 1}
r = {'m1': m1, 'm2': m2, 'y': y, 'hint': x**match['power']*f(x)}
return ode_separable(eq, func, order, r)
def ode_1st_power_series(eq, func, order, match):
r"""
The power series solution is a method which gives the Taylor series expansion
to the solution of a differential equation.
For a first order differential equation `\frac{dy}{dx} = h(x, y)`, a power
series solution exists at a point `x = x_{0}` if `h(x, y)` is analytic at `x_{0}`.
The solution is given by
.. math:: y(x) = y(x_{0}) + \sum_{n = 1}^{\infty} \frac{F_{n}(x_{0},b)(x - x_{0})^n}{n!},
where `y(x_{0}) = b` is the value of y at the initial value of `x_{0}`.
To compute the values of the `F_{n}(x_{0},b)` the following algorithm is
followed, until the required number of terms are generated.
1. `F_1 = h(x_{0}, b)`
2. `F_{n+1} = \frac{\partial F_{n}}{\partial x} + \frac{\partial F_{n}}{\partial y}F_{1}`
Examples
========
>>> from sympy import Function, Derivative, pprint, exp
>>> from sympy.solvers.ode import dsolve
>>> from sympy.abc import x
>>> f = Function('f')
>>> eq = exp(x)*(f(x).diff(x)) - f(x)
>>> pprint(dsolve(eq, hint='1st_power_series'))
3 4 5
C1*x C1*x C1*x / 6\
f(x) = C1 + C1*x - ----- + ----- + ----- + O\x /
6 24 60
References
==========
- Travis W. Walker, Analytic power series technique for solving first-order
differential equations, p.p 17, 18
"""
x = func.args[0]
y = match['y']
f = func.func
h = -match[match['d']]/match[match['e']]
point = match.get('f0')
value = match.get('f0val')
terms = match.get('terms')
# First term
F = h
if not h:
return Eq(f(x), value)
# Initialisation
series = value
if terms > 1:
hc = h.subs({x: point, y: value})
if hc.has(oo) or hc.has(NaN) or hc.has(zoo):
# Derivative does not exist, not analytic
return Eq(f(x), oo)
elif hc:
series += hc*(x - point)
for factcount in range(2, terms):
Fnew = F.diff(x) + F.diff(y)*h
Fnewc = Fnew.subs({x: point, y: value})
# Same logic as above
if Fnewc.has(oo) or Fnewc.has(NaN) or Fnewc.has(-oo) or Fnewc.has(zoo):
return Eq(f(x), oo)
series += Fnewc*((x - point)**factcount)/factorial(factcount)
F = Fnew
series += Order(x**terms)
return Eq(f(x), series)
def ode_nth_linear_constant_coeff_homogeneous(eq, func, order, match,
returns='sol'):
r"""
Solves an `n`\th order linear homogeneous differential equation with
constant coefficients.
This is an equation of the form
.. math:: a_n f^{(n)}(x) + a_{n-1} f^{(n-1)}(x) + \cdots + a_1 f'(x)
+ a_0 f(x) = 0\text{.}
These equations can be solved in a general manner, by taking the roots of
the characteristic equation `a_n m^n + a_{n-1} m^{n-1} + \cdots + a_1 m +
a_0 = 0`. The solution will then be the sum of `C_n x^i e^{r x}` terms,
for each where `C_n` is an arbitrary constant, `r` is a root of the
characteristic equation and `i` is one of each from 0 to the multiplicity
of the root - 1 (for example, a root 3 of multiplicity 2 would create the
terms `C_1 e^{3 x} + C_2 x e^{3 x}`). The exponential is usually expanded
for complex roots using Euler's equation `e^{I x} = \cos(x) + I \sin(x)`.
Complex roots always come in conjugate pairs in polynomials with real
coefficients, so the two roots will be represented (after simplifying the
constants) as `e^{a x} \left(C_1 \cos(b x) + C_2 \sin(b x)\right)`.
If SymPy cannot find exact roots to the characteristic equation, a
:py:class:`~sympy.polys.rootoftools.CRootOf` instance will be return
instead.
>>> from sympy import Function, dsolve, Eq
>>> from sympy.abc import x
>>> f = Function('f')
>>> dsolve(f(x).diff(x, 5) + 10*f(x).diff(x) - 2*f(x), f(x),
... hint='nth_linear_constant_coeff_homogeneous')
... # doctest: +NORMALIZE_WHITESPACE
Eq(f(x), C1*exp(x*CRootOf(_x**5 + 10*_x - 2, 0)) +
C2*exp(x*CRootOf(_x**5 + 10*_x - 2, 1)) +
C3*exp(x*CRootOf(_x**5 + 10*_x - 2, 2)) +
C4*exp(x*CRootOf(_x**5 + 10*_x - 2, 3)) +
C5*exp(x*CRootOf(_x**5 + 10*_x - 2, 4)))
Note that because this method does not involve integration, there is no
``nth_linear_constant_coeff_homogeneous_Integral`` hint.
The following is for internal use:
- ``returns = 'sol'`` returns the solution to the ODE.
- ``returns = 'list'`` returns a list of linearly independent solutions,
for use with non homogeneous solution methods like variation of
parameters and undetermined coefficients. Note that, though the
solutions should be linearly independent, this function does not
explicitly check that. You can do ``assert simplify(wronskian(sollist))
!= 0`` to check for linear independence. Also, ``assert len(sollist) ==
order`` will need to pass.
- ``returns = 'both'``, return a dictionary ``{'sol': <solution to ODE>,
'list': <list of linearly independent solutions>}``.
Examples
========
>>> from sympy import Function, dsolve, pprint
>>> from sympy.abc import x
>>> f = Function('f')
>>> pprint(dsolve(f(x).diff(x, 4) + 2*f(x).diff(x, 3) -
... 2*f(x).diff(x, 2) - 6*f(x).diff(x) + 5*f(x), f(x),
... hint='nth_linear_constant_coeff_homogeneous'))
x -2*x
f(x) = (C1 + C2*x)*e + (C3*sin(x) + C4*cos(x))*e
References
==========
- http://en.wikipedia.org/wiki/Linear_differential_equation section:
Nonhomogeneous_equation_with_constant_coefficients
- M. Tenenbaum & H. Pollard, "Ordinary Differential Equations",
Dover 1963, pp. 211
# indirect doctest
"""
x = func.args[0]
f = func.func
r = match
# First, set up characteristic equation.
chareq, symbol = S.Zero, Dummy('x')
for i in r.keys():
if type(i) == str or i < 0:
pass
else:
chareq += r[i]*symbol**i
chareq = Poly(chareq, symbol)
chareqroots = [rootof(chareq, k) for k in range(chareq.degree())]
chareq_is_complex = not all([i.is_real for i in chareq.all_coeffs()])
# A generator of constants
constants = list(get_numbered_constants(eq, num=chareq.degree()*2))
# Create a dict root: multiplicity or charroots
charroots = defaultdict(int)
for root in chareqroots:
charroots[root] += 1
gsol = S(0)
# We need to keep track of terms so we can run collect() at the end.
# This is necessary for constantsimp to work properly.
global collectterms
collectterms = []
gensols = []
conjugate_roots = [] # used to prevent double-use of conjugate roots
for root, multiplicity in charroots.items():
for i in range(multiplicity):
if isinstance(root, RootOf):
gensols.append(exp(root*x))
if multiplicity != 1:
raise ValueError("Value should be 1")
# This ordering is important
collectterms = [(0, root, 0)] + collectterms
else:
if chareq_is_complex:
gensols.append(x**i*exp(root*x))
collectterms = [(i, root, 0)] + collectterms
continue
reroot = re(root)
imroot = im(root)
if imroot.has(atan2) and reroot.has(atan2):
# Remove this condition when re and im stop returning
# circular atan2 usages.
gensols.append(x**i*exp(root*x))
collectterms = [(i, root, 0)] + collectterms
else:
if root in conjugate_roots:
collectterms = [(i, reroot, imroot)] + collectterms
continue
if imroot == 0:
gensols.append(x**i*exp(reroot*x))
collectterms = [(i, reroot, 0)] + collectterms
continue
conjugate_roots.append(conjugate(root))
gensols.append(x**i*exp(reroot*x) * sin(abs(imroot) * x))
gensols.append(x**i*exp(reroot*x) * cos( imroot * x))
# This ordering is important
collectterms = [(i, reroot, imroot)] + collectterms
if returns == 'list':
return gensols
elif returns in ('sol' 'both'):
gsol = Add(*[i*j for (i,j) in zip(constants, gensols)])
if returns == 'sol':
return Eq(f(x), gsol)
else:
return {'sol': Eq(f(x), gsol), 'list': gensols}
else:
raise ValueError('Unknown value for key "returns".')
def ode_nth_linear_constant_coeff_undetermined_coefficients(eq, func, order, match):
r"""
Solves an `n`\th order linear differential equation with constant
coefficients using the method of undetermined coefficients.
This method works on differential equations of the form
.. math:: a_n f^{(n)}(x) + a_{n-1} f^{(n-1)}(x) + \cdots + a_1 f'(x)
+ a_0 f(x) = P(x)\text{,}
where `P(x)` is a function that has a finite number of linearly
independent derivatives.
Functions that fit this requirement are finite sums functions of the form
`a x^i e^{b x} \sin(c x + d)` or `a x^i e^{b x} \cos(c x + d)`, where `i`
is a non-negative integer and `a`, `b`, `c`, and `d` are constants. For
example any polynomial in `x`, functions like `x^2 e^{2 x}`, `x \sin(x)`,
and `e^x \cos(x)` can all be used. Products of `\sin`'s and `\cos`'s have
a finite number of derivatives, because they can be expanded into `\sin(a
x)` and `\cos(b x)` terms. However, SymPy currently cannot do that
expansion, so you will need to manually rewrite the expression in terms of
the above to use this method. So, for example, you will need to manually
convert `\sin^2(x)` into `(1 + \cos(2 x))/2` to properly apply the method
of undetermined coefficients on it.
This method works by creating a trial function from the expression and all
of its linear independent derivatives and substituting them into the
original ODE. The coefficients for each term will be a system of linear
equations, which are be solved for and substituted, giving the solution.
If any of the trial functions are linearly dependent on the solution to
the homogeneous equation, they are multiplied by sufficient `x` to make
them linearly independent.
Examples
========
>>> from sympy import Function, dsolve, pprint, exp, cos
>>> from sympy.abc import x
>>> f = Function('f')
>>> pprint(dsolve(f(x).diff(x, 2) + 2*f(x).diff(x) + f(x) -
... 4*exp(-x)*x**2 + cos(2*x), f(x),
... hint='nth_linear_constant_coeff_undetermined_coefficients'))
/ 4\
| x | -x 4*sin(2*x) 3*cos(2*x)
f(x) = |C1 + C2*x + --|*e - ---------- + ----------
\ 3 / 25 25
References
==========
- http://en.wikipedia.org/wiki/Method_of_undetermined_coefficients
- M. Tenenbaum & H. Pollard, "Ordinary Differential Equations",
Dover 1963, pp. 221
# indirect doctest
"""
gensol = ode_nth_linear_constant_coeff_homogeneous(eq, func, order, match,
returns='both')
match.update(gensol)
return _solve_undetermined_coefficients(eq, func, order, match)
def _solve_undetermined_coefficients(eq, func, order, match):
r"""
Helper function for the method of undetermined coefficients.
See the
:py:meth:`~sympy.solvers.ode.ode_nth_linear_constant_coeff_undetermined_coefficients`
docstring for more information on this method.
The parameter ``match`` should be a dictionary that has the following
keys:
``list``
A list of solutions to the homogeneous equation, such as the list
returned by
``ode_nth_linear_constant_coeff_homogeneous(returns='list')``.
``sol``
The general solution, such as the solution returned by
``ode_nth_linear_constant_coeff_homogeneous(returns='sol')``.
``trialset``
The set of trial functions as returned by
``_undetermined_coefficients_match()['trialset']``.
"""
x = func.args[0]
f = func.func
r = match
coeffs = numbered_symbols('a', cls=Dummy)
coefflist = []
gensols = r['list']
gsol = r['sol']
trialset = r['trialset']
notneedset = set([])
newtrialset = set([])
global collectterms
if len(gensols) != order:
raise NotImplementedError("Cannot find " + str(order) +
" solutions to the homogeneous equation necessary to apply" +
" undetermined coefficients to " + str(eq) +
" (number of terms != order)")
usedsin = set([])
mult = 0 # The multiplicity of the root
getmult = True
for i, reroot, imroot in collectterms:
if getmult:
mult = i + 1
getmult = False
if i == 0:
getmult = True
if imroot:
# Alternate between sin and cos
if (i, reroot) in usedsin:
check = x**i*exp(reroot*x)*cos(imroot*x)
else:
check = x**i*exp(reroot*x)*sin(abs(imroot)*x)
usedsin.add((i, reroot))
else:
check = x**i*exp(reroot*x)
if check in trialset:
# If an element of the trial function is already part of the
# homogeneous solution, we need to multiply by sufficient x to
# make it linearly independent. We also don't need to bother
# checking for the coefficients on those elements, since we
# already know it will be 0.
while True:
if check*x**mult in trialset:
mult += 1
else:
break
trialset.add(check*x**mult)
notneedset.add(check)
newtrialset = trialset - notneedset
trialfunc = 0
for i in newtrialset:
c = next(coeffs)
coefflist.append(c)
trialfunc += c*i
eqs = sub_func_doit(eq, f(x), trialfunc)
coeffsdict = dict(list(zip(trialset, [0]*(len(trialset) + 1))))
eqs = _mexpand(eqs)
for i in Add.make_args(eqs):
s = separatevars(i, dict=True, symbols=[x])
coeffsdict[s[x]] += s['coeff']
coeffvals = solve(list(coeffsdict.values()), coefflist)
if not coeffvals:
raise NotImplementedError(
"Could not solve `%s` using the "
"method of undetermined coefficients "
"(unable to solve for coefficients)." % eq)
psol = trialfunc.subs(coeffvals)
return Eq(f(x), gsol.rhs + psol)
def _undetermined_coefficients_match(expr, x):
r"""
Returns a trial function match if undetermined coefficients can be applied
to ``expr``, and ``None`` otherwise.
A trial expression can be found for an expression for use with the method
of undetermined coefficients if the expression is an
additive/multiplicative combination of constants, polynomials in `x` (the
independent variable of expr), `\sin(a x + b)`, `\cos(a x + b)`, and
`e^{a x}` terms (in other words, it has a finite number of linearly
independent derivatives).
Note that you may still need to multiply each term returned here by
sufficient `x` to make it linearly independent with the solutions to the
homogeneous equation.
This is intended for internal use by ``undetermined_coefficients`` hints.
SymPy currently has no way to convert `\sin^n(x) \cos^m(y)` into a sum of
only `\sin(a x)` and `\cos(b x)` terms, so these are not implemented. So,
for example, you will need to manually convert `\sin^2(x)` into `[1 +
\cos(2 x)]/2` to properly apply the method of undetermined coefficients on
it.
Examples
========
>>> from sympy import log, exp
>>> from sympy.solvers.ode import _undetermined_coefficients_match
>>> from sympy.abc import x
>>> _undetermined_coefficients_match(9*x*exp(x) + exp(-x), x)
{'test': True, 'trialset': {x*exp(x), exp(-x), exp(x)}}
>>> _undetermined_coefficients_match(log(x), x)
{'test': False}
"""
a = Wild('a', exclude=[x])
b = Wild('b', exclude=[x])
expr = powsimp(expr, combine='exp') # exp(x)*exp(2*x + 1) => exp(3*x + 1)
retdict = {}
def _test_term(expr, x):
r"""
Test if ``expr`` fits the proper form for undetermined coefficients.
"""
if expr.is_Add:
return all(_test_term(i, x) for i in expr.args)
elif expr.is_Mul:
if expr.has(sin, cos):
foundtrig = False
# Make sure that there is only one trig function in the args.
# See the docstring.
for i in expr.args:
if i.has(sin, cos):
if foundtrig:
return False
else:
foundtrig = True
return all(_test_term(i, x) for i in expr.args)
elif expr.is_Function:
if expr.func in (sin, cos, exp):
if expr.args[0].match(a*x + b):
return True
else:
return False
else:
return False
elif expr.is_Pow and expr.base.is_Symbol and expr.exp.is_Integer and \
expr.exp >= 0:
return True
elif expr.is_Pow and expr.base.is_number:
if expr.exp.match(a*x + b):
return True
else:
return False
elif expr.is_Symbol or expr.is_number:
return True
else:
return False
def _get_trial_set(expr, x, exprs=set([])):
r"""
Returns a set of trial terms for undetermined coefficients.
The idea behind undetermined coefficients is that the terms expression
repeat themselves after a finite number of derivatives, except for the
coefficients (they are linearly dependent). So if we collect these,
we should have the terms of our trial function.
"""
def _remove_coefficient(expr, x):
r"""
Returns the expression without a coefficient.
Similar to expr.as_independent(x)[1], except it only works
multiplicatively.
"""
term = S.One
if expr.is_Mul:
for i in expr.args:
if i.has(x):
term *= i
elif expr.has(x):
term = expr
return term
expr = expand_mul(expr)
if expr.is_Add:
for term in expr.args:
if _remove_coefficient(term, x) in exprs:
pass
else:
exprs.add(_remove_coefficient(term, x))
exprs = exprs.union(_get_trial_set(term, x, exprs))
else:
term = _remove_coefficient(expr, x)
tmpset = exprs.union({term})
oldset = set([])
while tmpset != oldset:
# If you get stuck in this loop, then _test_term is probably
# broken
oldset = tmpset.copy()
expr = expr.diff(x)
term = _remove_coefficient(expr, x)
if term.is_Add:
tmpset = tmpset.union(_get_trial_set(term, x, tmpset))
else:
tmpset.add(term)
exprs = tmpset
return exprs
retdict['test'] = _test_term(expr, x)
if retdict['test']:
# Try to generate a list of trial solutions that will have the
# undetermined coefficients. Note that if any of these are not linearly
# independent with any of the solutions to the homogeneous equation,
# then they will need to be multiplied by sufficient x to make them so.
# This function DOES NOT do that (it doesn't even look at the
# homogeneous equation).
retdict['trialset'] = _get_trial_set(expr, x)
return retdict
def ode_nth_linear_constant_coeff_variation_of_parameters(eq, func, order, match):
r"""
Solves an `n`\th order linear differential equation with constant
coefficients using the method of variation of parameters.
This method works on any differential equations of the form
.. math:: f^{(n)}(x) + a_{n-1} f^{(n-1)}(x) + \cdots + a_1 f'(x) + a_0
f(x) = P(x)\text{.}
This method works by assuming that the particular solution takes the form
.. math:: \sum_{x=1}^{n} c_i(x) y_i(x)\text{,}
where `y_i` is the `i`\th solution to the homogeneous equation. The
solution is then solved using Wronskian's and Cramer's Rule. The
particular solution is given by
.. math:: \sum_{x=1}^n \left( \int \frac{W_i(x)}{W(x)} \,dx
\right) y_i(x) \text{,}
where `W(x)` is the Wronskian of the fundamental system (the system of `n`
linearly independent solutions to the homogeneous equation), and `W_i(x)`
is the Wronskian of the fundamental system with the `i`\th column replaced
with `[0, 0, \cdots, 0, P(x)]`.
This method is general enough to solve any `n`\th order inhomogeneous
linear differential equation with constant coefficients, but sometimes
SymPy cannot simplify the Wronskian well enough to integrate it. If this
method hangs, try using the
``nth_linear_constant_coeff_variation_of_parameters_Integral`` hint and
simplifying the integrals manually. Also, prefer using
``nth_linear_constant_coeff_undetermined_coefficients`` when it
applies, because it doesn't use integration, making it faster and more
reliable.
Warning, using simplify=False with
'nth_linear_constant_coeff_variation_of_parameters' in
:py:meth:`~sympy.solvers.ode.dsolve` may cause it to hang, because it will
not attempt to simplify the Wronskian before integrating. It is
recommended that you only use simplify=False with
'nth_linear_constant_coeff_variation_of_parameters_Integral' for this
method, especially if the solution to the homogeneous equation has
trigonometric functions in it.
Examples
========
>>> from sympy import Function, dsolve, pprint, exp, log
>>> from sympy.abc import x
>>> f = Function('f')
>>> pprint(dsolve(f(x).diff(x, 3) - 3*f(x).diff(x, 2) +
... 3*f(x).diff(x) - f(x) - exp(x)*log(x), f(x),
... hint='nth_linear_constant_coeff_variation_of_parameters'))
/ 3 \
| 2 x *(6*log(x) - 11)| x
f(x) = |C1 + C2*x + C3*x + ------------------|*e
\ 36 /
References
==========
- http://en.wikipedia.org/wiki/Variation_of_parameters
- http://planetmath.org/VariationOfParameters
- M. Tenenbaum & H. Pollard, "Ordinary Differential Equations",
Dover 1963, pp. 233
# indirect doctest
"""
gensol = ode_nth_linear_constant_coeff_homogeneous(eq, func, order, match,
returns='both')
match.update(gensol)
return _solve_variation_of_parameters(eq, func, order, match)
def _solve_variation_of_parameters(eq, func, order, match):
r"""
Helper function for the method of variation of parameters and nonhomogeneous euler eq.
See the
:py:meth:`~sympy.solvers.ode.ode_nth_linear_constant_coeff_variation_of_parameters`
docstring for more information on this method.
The parameter ``match`` should be a dictionary that has the following
keys:
``list``
A list of solutions to the homogeneous equation, such as the list
returned by
``ode_nth_linear_constant_coeff_homogeneous(returns='list')``.
``sol``
The general solution, such as the solution returned by
``ode_nth_linear_constant_coeff_homogeneous(returns='sol')``.
"""
x = func.args[0]
f = func.func
r = match
psol = 0
gensols = r['list']
gsol = r['sol']
wr = wronskian(gensols, x)
if r.get('simplify', True):
wr = simplify(wr) # We need much better simplification for
# some ODEs. See issue 4662, for example.
# To reduce commonly occuring sin(x)**2 + cos(x)**2 to 1
wr = trigsimp(wr, deep=True, recursive=True)
if not wr:
# The wronskian will be 0 iff the solutions are not linearly
# independent.
raise NotImplementedError("Cannot find " + str(order) +
" solutions to the homogeneous equation nessesary to apply " +
"variation of parameters to " + str(eq) + " (Wronskian == 0)")
if len(gensols) != order:
raise NotImplementedError("Cannot find " + str(order) +
" solutions to the homogeneous equation nessesary to apply " +
"variation of parameters to " +
str(eq) + " (number of terms != order)")
negoneterm = (-1)**(order)
for i in gensols:
psol += negoneterm*Integral(wronskian([sol for sol in gensols if sol != i], x)*r[-1]/wr, x)*i/r[order]
negoneterm *= -1
if r.get('simplify', True):
psol = simplify(psol)
psol = trigsimp(psol, deep=True)
return Eq(f(x), gsol.rhs + psol)
def ode_separable(eq, func, order, match):
r"""
Solves separable 1st order differential equations.
This is any differential equation that can be written as `P(y)
\tfrac{dy}{dx} = Q(x)`. The solution can then just be found by
rearranging terms and integrating: `\int P(y) \,dy = \int Q(x) \,dx`.
This hint uses :py:meth:`sympy.simplify.simplify.separatevars` as its back
end, so if a separable equation is not caught by this solver, it is most
likely the fault of that function.
:py:meth:`~sympy.simplify.simplify.separatevars` is
smart enough to do most expansion and factoring necessary to convert a
separable equation `F(x, y)` into the proper form `P(x)\cdot{}Q(y)`. The
general solution is::
>>> from sympy import Function, dsolve, Eq, pprint
>>> from sympy.abc import x
>>> a, b, c, d, f = map(Function, ['a', 'b', 'c', 'd', 'f'])
>>> genform = Eq(a(x)*b(f(x))*f(x).diff(x), c(x)*d(f(x)))
>>> pprint(genform)
d
a(x)*b(f(x))*--(f(x)) = c(x)*d(f(x))
dx
>>> pprint(dsolve(genform, f(x), hint='separable_Integral'))
f(x)
/ /
| |
| b(y) | c(x)
| ---- dy = C1 + | ---- dx
| d(y) | a(x)
| |
/ /
Examples
========
>>> from sympy import Function, dsolve, Eq
>>> from sympy.abc import x
>>> f = Function('f')
>>> pprint(dsolve(Eq(f(x)*f(x).diff(x) + x, 3*x*f(x)**2), f(x),
... hint='separable', simplify=False))
/ 2 \ 2
log\3*f (x) - 1/ x
---------------- = C1 + --
6 2
References
==========
- M. Tenenbaum & H. Pollard, "Ordinary Differential Equations",
Dover 1963, pp. 52
# indirect doctest
"""
x = func.args[0]
f = func.func
C1 = get_numbered_constants(eq, num=1)
r = match # {'m1':m1, 'm2':m2, 'y':y}
u = r.get('hint', f(x)) # get u from separable_reduced else get f(x)
return Eq(Integral(r['m2']['coeff']*r['m2'][r['y']]/r['m1'][r['y']],
(r['y'], None, u)), Integral(-r['m1']['coeff']*r['m1'][x]/
r['m2'][x], x) + C1)
def checkinfsol(eq, infinitesimals, func=None, order=None):
r"""
This function is used to check if the given infinitesimals are the
actual infinitesimals of the given first order differential equation.
This method is specific to the Lie Group Solver of ODEs.
As of now, it simply checks, by substituting the infinitesimals in the
partial differential equation.
.. math:: \frac{\partial \eta}{\partial x} + \left(\frac{\partial \eta}{\partial y}
- \frac{\partial \xi}{\partial x}\right)*h
- \frac{\partial \xi}{\partial y}*h^{2}
- \xi\frac{\partial h}{\partial x} - \eta\frac{\partial h}{\partial y} = 0
where `\eta`, and `\xi` are the infinitesimals and `h(x,y) = \frac{dy}{dx}`
The infinitesimals should be given in the form of a list of dicts
``[{xi(x, y): inf, eta(x, y): inf}]``, corresponding to the
output of the function infinitesimals. It returns a list
of values of the form ``[(True/False, sol)]`` where ``sol`` is the value
obtained after substituting the infinitesimals in the PDE. If it
is ``True``, then ``sol`` would be 0.
"""
if isinstance(eq, Equality):
eq = eq.lhs - eq.rhs
if not func:
eq, func = _preprocess(eq)
variables = func.args
if len(variables) != 1:
raise ValueError("ODE's have only one independent variable")
else:
x = variables[0]
if not order:
order = ode_order(eq, func)
if order != 1:
raise NotImplementedError("Lie groups solver has been implemented "
"only for first order differential equations")
else:
df = func.diff(x)
a = Wild('a', exclude = [df])
b = Wild('b', exclude = [df])
match = collect(expand(eq), df).match(a*df + b)
if match:
h = -simplify(match[b]/match[a])
else:
try:
sol = solve(eq, df)
except NotImplementedError:
raise NotImplementedError("Infinitesimals for the "
"first order ODE could not be found")
else:
h = sol[0] # Find infinitesimals for one solution
y = Dummy('y')
h = h.subs(func, y)
xi = Function('xi')(x, y)
eta = Function('eta')(x, y)
dxi = Function('xi')(x, func)
deta = Function('eta')(x, func)
pde = (eta.diff(x) + (eta.diff(y) - xi.diff(x))*h -
(xi.diff(y))*h**2 - xi*(h.diff(x)) - eta*(h.diff(y)))
soltup = []
for sol in infinitesimals:
tsol = {xi: S(sol[dxi]).subs(func, y),
eta: S(sol[deta]).subs(func, y)}
sol = simplify(pde.subs(tsol).doit())
if sol:
soltup.append((False, sol.subs(y, func)))
else:
soltup.append((True, 0))
return soltup
def ode_lie_group(eq, func, order, match):
r"""
This hint implements the Lie group method of solving first order differential
equations. The aim is to convert the given differential equation from the
given coordinate given system into another coordinate system where it becomes
invariant under the one-parameter Lie group of translations. The converted ODE is
quadrature and can be solved easily. It makes use of the
:py:meth:`sympy.solvers.ode.infinitesimals` function which returns the
infinitesimals of the transformation.
The coordinates `r` and `s` can be found by solving the following Partial
Differential Equations.
.. math :: \xi\frac{\partial r}{\partial x} + \eta\frac{\partial r}{\partial y}
= 0
.. math :: \xi\frac{\partial s}{\partial x} + \eta\frac{\partial s}{\partial y}
= 1
The differential equation becomes separable in the new coordinate system
.. math :: \frac{ds}{dr} = \frac{\frac{\partial s}{\partial x} +
h(x, y)\frac{\partial s}{\partial y}}{
\frac{\partial r}{\partial x} + h(x, y)\frac{\partial r}{\partial y}}
After finding the solution by integration, it is then converted back to the original
coordinate system by subsituting `r` and `s` in terms of `x` and `y` again.
Examples
========
>>> from sympy import Function, dsolve, Eq, exp, pprint
>>> from sympy.abc import x
>>> f = Function('f')
>>> pprint(dsolve(f(x).diff(x) + 2*x*f(x) - x*exp(-x**2), f(x),
... hint='lie_group'))
/ 2\ 2
| x | -x
f(x) = |C1 + --|*e
\ 2 /
References
==========
- Solving differential equations by Symmetry Groups,
John Starrett, pp. 1 - pp. 14
"""
heuristics = lie_heuristics
inf = {}
f = func.func
x = func.args[0]
df = func.diff(x)
xi = Function("xi")
eta = Function("eta")
a = Wild('a', exclude = [df])
b = Wild('b', exclude = [df])
xis = match.pop('xi')
etas = match.pop('eta')
if match:
h = -simplify(match[match['d']]/match[match['e']])
y = match['y']
else:
try:
sol = solve(eq, df)
except NotImplementedError:
raise NotImplementedError("Unable to solve the differential equation " +
str(eq) + " by the lie group method")
else:
y = Dummy("y")
h = sol[0].subs(func, y)
if xis is not None and etas is not None:
inf = [{xi(x, f(x)): S(xis), eta(x, f(x)): S(etas)}]
if not checkinfsol(eq, inf, func=f(x), order=1)[0][0]:
raise ValueError("The given infinitesimals xi and eta"
" are not the infinitesimals to the given equation")
else:
heuristics = ["user_defined"]
match = {'h': h, 'y': y}
# This is done so that if:
# a] solve raises a NotImplementedError.
# b] any heuristic raises a ValueError
# another heuristic can be used.
tempsol = [] # Used by solve below
for heuristic in heuristics:
try:
if not inf:
inf = infinitesimals(eq, hint=heuristic, func=func, order=1, match=match)
except ValueError:
continue
else:
for infsim in inf:
xiinf = (infsim[xi(x, func)]).subs(func, y)
etainf = (infsim[eta(x, func)]).subs(func, y)
# This condition creates recursion while using pdsolve.
# Since the first step while solving a PDE of form
# a*(f(x, y).diff(x)) + b*(f(x, y).diff(y)) + c = 0
# is to solve the ODE dy/dx = b/a
if simplify(etainf/xiinf) == h:
continue
rpde = f(x, y).diff(x)*xiinf + f(x, y).diff(y)*etainf
r = pdsolve(rpde, func=f(x, y)).rhs
s = pdsolve(rpde - 1, func=f(x, y)).rhs
newcoord = [_lie_group_remove(coord) for coord in [r, s]]
r = Dummy("r")
s = Dummy("s")
C1 = Symbol("C1")
rcoord = newcoord[0]
scoord = newcoord[-1]
try:
sol = solve([r - rcoord, s - scoord], x, y, dict=True)
except NotImplementedError:
continue
else:
sol = sol[0]
xsub = sol[x]
ysub = sol[y]
num = simplify(scoord.diff(x) + scoord.diff(y)*h)
denom = simplify(rcoord.diff(x) + rcoord.diff(y)*h)
if num and denom:
diffeq = simplify((num/denom).subs([(x, xsub), (y, ysub)]))
sep = separatevars(diffeq, symbols=[r, s], dict=True)
if sep:
# Trying to separate, r and s coordinates
deq = integrate((1/sep[s]), s) + C1 - integrate(sep['coeff']*sep[r], r)
# Substituting and reverting back to original coordinates
deq = deq.subs([(r, rcoord), (s, scoord)])
try:
sdeq = solve(deq, y)
except NotImplementedError:
tempsol.append(deq)
else:
if len(sdeq) == 1:
return Eq(f(x), sdeq.pop())
else:
return [Eq(f(x), sol) for sol in sdeq]
elif denom: # (ds/dr) is zero which means s is constant
return Eq(f(x), solve(scoord - C1, y)[0])
elif num: # (dr/ds) is zero which means r is constant
return Eq(f(x), solve(rcoord - C1, y)[0])
# If nothing works, return solution as it is, without solving for y
if tempsol:
if len(tempsol) == 1:
return Eq(tempsol.pop().subs(y, f(x)), 0)
else:
return [Eq(sol.subs(y, f(x)), 0) for sol in tempsol]
raise NotImplementedError("The given ODE " + str(eq) + " cannot be solved by"
+ " the lie group method")
def _lie_group_remove(coords):
r"""
This function is strictly meant for internal use by the Lie group ODE solving
method. It replaces arbitrary functions returned by pdsolve with either 0 or 1 or the
args of the arbitrary function.
The algorithm used is:
1] If coords is an instance of an Undefined Function, then the args are returned
2] If the arbitrary function is present in an Add object, it is replaced by zero.
3] If the arbitrary function is present in an Mul object, it is replaced by one.
4] If coords has no Undefined Function, it is returned as it is.
Examples
========
>>> from sympy.solvers.ode import _lie_group_remove
>>> from sympy import Function
>>> from sympy.abc import x, y
>>> F = Function("F")
>>> eq = x**2*y
>>> _lie_group_remove(eq)
x**2*y
>>> eq = F(x**2*y)
>>> _lie_group_remove(eq)
x**2*y
>>> eq = y**2*x + F(x**3)
>>> _lie_group_remove(eq)
x*y**2
>>> eq = (F(x**3) + y)*x**4
>>> _lie_group_remove(eq)
x**4*y
"""
if isinstance(coords, AppliedUndef):
return coords.args[0]
elif coords.is_Add:
subfunc = coords.atoms(AppliedUndef)
if subfunc:
for func in subfunc:
coords = coords.subs(func, 0)
return coords
elif coords.is_Pow:
base, expr = coords.as_base_exp()
base = _lie_group_remove(base)
expr = _lie_group_remove(expr)
return base**expr
elif coords.is_Mul:
mulargs = []
coordargs = coords.args
for arg in coordargs:
if not isinstance(coords, AppliedUndef):
mulargs.append(_lie_group_remove(arg))
return Mul(*mulargs)
return coords
def infinitesimals(eq, func=None, order=None, hint='default', match=None):
r"""
The infinitesimal functions of an ordinary differential equation, `\xi(x,y)`
and `\eta(x,y)`, are the infinitesimals of the Lie group of point transformations
for which the differential equation is invariant. So, the ODE `y'=f(x,y)`
would admit a Lie group `x^*=X(x,y;\varepsilon)=x+\varepsilon\xi(x,y)`,
`y^*=Y(x,y;\varepsilon)=y+\varepsilon\eta(x,y)` such that `(y^*)'=f(x^*, y^*)`.
A change of coordinates, to `r(x,y)` and `s(x,y)`, can be performed so this Lie group
becomes the translation group, `r^*=r` and `s^*=s+\varepsilon`.
They are tangents to the coordinate curves of the new system.
Consider the transformation `(x, y) \to (X, Y)` such that the
differential equation remains invariant. `\xi` and `\eta` are the tangents to
the transformed coordinates `X` and `Y`, at `\varepsilon=0`.
.. math:: \left(\frac{\partial X(x,y;\varepsilon)}{\partial\varepsilon
}\right)|_{\varepsilon=0} = \xi,
\left(\frac{\partial Y(x,y;\varepsilon)}{\partial\varepsilon
}\right)|_{\varepsilon=0} = \eta,
The infinitesimals can be found by solving the following PDE:
>>> from sympy import Function, diff, Eq, pprint
>>> from sympy.abc import x, y
>>> xi, eta, h = map(Function, ['xi', 'eta', 'h'])
>>> h = h(x, y) # dy/dx = h
>>> eta = eta(x, y)
>>> xi = xi(x, y)
>>> genform = Eq(eta.diff(x) + (eta.diff(y) - xi.diff(x))*h
... - (xi.diff(y))*h**2 - xi*(h.diff(x)) - eta*(h.diff(y)), 0)
>>> pprint(genform)
/d d \ d 2 d
|--(eta(x, y)) - --(xi(x, y))|*h(x, y) - eta(x, y)*--(h(x, y)) - h (x, y)*--(x
\dy dx / dy dy
<BLANKLINE>
d d
i(x, y)) - xi(x, y)*--(h(x, y)) + --(eta(x, y)) = 0
dx dx
Solving the above mentioned PDE is not trivial, and can be solved only by
making intelligent assumptions for `\xi` and `\eta` (heuristics). Once an
infinitesimal is found, the attempt to find more heuristics stops. This is done to
optimise the speed of solving the differential equation. If a list of all the
infinitesimals is needed, ``hint`` should be flagged as ``all``, which gives
the complete list of infinitesimals. If the infinitesimals for a particular
heuristic needs to be found, it can be passed as a flag to ``hint``.
Examples
========
>>> from sympy import Function, diff
>>> from sympy.solvers.ode import infinitesimals
>>> from sympy.abc import x
>>> f = Function('f')
>>> eq = f(x).diff(x) - x**2*f(x)
>>> infinitesimals(eq)
[{eta(x, f(x)): exp(x**3/3), xi(x, f(x)): 0}]
References
==========
- Solving differential equations by Symmetry Groups,
John Starrett, pp. 1 - pp. 14
"""
if isinstance(eq, Equality):
eq = eq.lhs - eq.rhs
if not func:
eq, func = _preprocess(eq)
variables = func.args
if len(variables) != 1:
raise ValueError("ODE's have only one independent variable")
else:
x = variables[0]
if not order:
order = ode_order(eq, func)
if order != 1:
raise NotImplementedError("Infinitesimals for only "
"first order ODE's have been implemented")
else:
df = func.diff(x)
# Matching differential equation of the form a*df + b
a = Wild('a', exclude = [df])
b = Wild('b', exclude = [df])
if match: # Used by lie_group hint
h = match['h']
y = match['y']
else:
match = collect(expand(eq), df).match(a*df + b)
if match:
h = -simplify(match[b]/match[a])
else:
try:
sol = solve(eq, df)
except NotImplementedError:
raise NotImplementedError("Infinitesimals for the "
"first order ODE could not be found")
else:
h = sol[0] # Find infinitesimals for one solution
y = Dummy("y")
h = h.subs(func, y)
u = Dummy("u")
hx = h.diff(x)
hy = h.diff(y)
hinv = ((1/h).subs([(x, u), (y, x)])).subs(u, y) # Inverse ODE
match = {'h': h, 'func': func, 'hx': hx, 'hy': hy, 'y': y, 'hinv': hinv}
if hint == 'all':
xieta = []
for heuristic in lie_heuristics:
function = globals()['lie_heuristic_' + heuristic]
inflist = function(match, comp=True)
if inflist:
xieta.extend([inf for inf in inflist if inf not in xieta])
if xieta:
return xieta
else:
raise NotImplementedError("Infinitesimals could not be found for "
"the given ODE")
elif hint == 'default':
for heuristic in lie_heuristics:
function = globals()['lie_heuristic_' + heuristic]
xieta = function(match, comp=False)
if xieta:
return xieta
raise NotImplementedError("Infinitesimals could not be found for"
" the given ODE")
elif hint not in lie_heuristics:
raise ValueError("Heuristic not recognized: " + hint)
else:
function = globals()['lie_heuristic_' + hint]
xieta = function(match, comp=True)
if xieta:
return xieta
else:
raise ValueError("Infinitesimals could not be found using the"
" given heuristic")
def lie_heuristic_abaco1_simple(match, comp=False):
r"""
The first heuristic uses the following four sets of
assumptions on `\xi` and `\eta`
.. math:: \xi = 0, \eta = f(x)
.. math:: \xi = 0, \eta = f(y)
.. math:: \xi = f(x), \eta = 0
.. math:: \xi = f(y), \eta = 0
The success of this heuristic is determined by algebraic factorisation.
For the first assumption `\xi = 0` and `\eta` to be a function of `x`, the PDE
.. math:: \frac{\partial \eta}{\partial x} + (\frac{\partial \eta}{\partial y}
- \frac{\partial \xi}{\partial x})*h
- \frac{\partial \xi}{\partial y}*h^{2}
- \xi*\frac{\partial h}{\partial x} - \eta*\frac{\partial h}{\partial y} = 0
reduces to `f'(x) - f\frac{\partial h}{\partial y} = 0`
If `\frac{\partial h}{\partial y}` is a function of `x`, then this can usually
be integrated easily. A similar idea is applied to the other 3 assumptions as well.
References
==========
- E.S Cheb-Terrab, L.G.S Duarte and L.A,C.P da Mota, Computer Algebra
Solving of First Order ODEs Using Symmetry Methods, pp. 8
"""
xieta = []
y = match['y']
h = match['h']
func = match['func']
x = func.args[0]
hx = match['hx']
hy = match['hy']
xi = Function('xi')(x, func)
eta = Function('eta')(x, func)
hysym = hy.free_symbols
if y not in hysym:
try:
fx = exp(integrate(hy, x))
except NotImplementedError:
pass
else:
inf = {xi: S(0), eta: fx}
if not comp:
return [inf]
if comp and inf not in xieta:
xieta.append(inf)
factor = hy/h
facsym = factor.free_symbols
if x not in facsym:
try:
fy = exp(integrate(factor, y))
except NotImplementedError:
pass
else:
inf = {xi: S(0), eta: fy.subs(y, func)}
if not comp:
return [inf]
if comp and inf not in xieta:
xieta.append(inf)
factor = -hx/h
facsym = factor.free_symbols
if y not in facsym:
try:
fx = exp(integrate(factor, x))
except NotImplementedError:
pass
else:
inf = {xi: fx, eta: S(0)}
if not comp:
return [inf]
if comp and inf not in xieta:
xieta.append(inf)
factor = -hx/(h**2)
facsym = factor.free_symbols
if x not in facsym:
try:
fy = exp(integrate(factor, y))
except NotImplementedError:
pass
else:
inf = {xi: fy.subs(y, func), eta: S(0)}
if not comp:
return [inf]
if comp and inf not in xieta:
xieta.append(inf)
if xieta:
return xieta
def lie_heuristic_abaco1_product(match, comp=False):
r"""
The second heuristic uses the following two assumptions on `\xi` and `\eta`
.. math:: \eta = 0, \xi = f(x)*g(y)
.. math:: \eta = f(x)*g(y), \xi = 0
The first assumption of this heuristic holds good if
`\frac{1}{h^{2}}\frac{\partial^2}{\partial x \partial y}\log(h)` is
separable in `x` and `y`, then the separated factors containing `x`
is `f(x)`, and `g(y)` is obtained by
.. math:: e^{\int f\frac{\partial}{\partial x}\left(\frac{1}{f*h}\right)\,dy}
provided `f\frac{\partial}{\partial x}\left(\frac{1}{f*h}\right)` is a function
of `y` only.
The second assumption holds good if `\frac{dy}{dx} = h(x, y)` is rewritten as
`\frac{dy}{dx} = \frac{1}{h(y, x)}` and the same properties of the first assumption
satisifes. After obtaining `f(x)` and `g(y)`, the coordinates are again
interchanged, to get `\eta` as `f(x)*g(y)`
References
==========
- E.S. Cheb-Terrab, A.D. Roche, Symmetries and First Order
ODE Patterns, pp. 7 - pp. 8
"""
xieta = []
y = match['y']
h = match['h']
hinv = match['hinv']
func = match['func']
x = func.args[0]
xi = Function('xi')(x, func)
eta = Function('eta')(x, func)
inf = separatevars(((log(h).diff(y)).diff(x))/h**2, dict=True, symbols=[x, y])
if inf and inf['coeff']:
fx = inf[x]
gy = simplify(fx*((1/(fx*h)).diff(x)))
gysyms = gy.free_symbols
if x not in gysyms:
gy = exp(integrate(gy, y))
inf = {eta: S(0), xi: (fx*gy).subs(y, func)}
if not comp:
return [inf]
if comp and inf not in xieta:
xieta.append(inf)
u1 = Dummy("u1")
inf = separatevars(((log(hinv).diff(y)).diff(x))/hinv**2, dict=True, symbols=[x, y])
if inf and inf['coeff']:
fx = inf[x]
gy = simplify(fx*((1/(fx*hinv)).diff(x)))
gysyms = gy.free_symbols
if x not in gysyms:
gy = exp(integrate(gy, y))
etaval = fx*gy
etaval = (etaval.subs([(x, u1), (y, x)])).subs(u1, y)
inf = {eta: etaval.subs(y, func), xi: S(0)}
if not comp:
return [inf]
if comp and inf not in xieta:
xieta.append(inf)
if xieta:
return xieta
def lie_heuristic_bivariate(match, comp=False):
r"""
The third heuristic assumes the infinitesimals `\xi` and `\eta`
to be bi-variate polynomials in `x` and `y`. The assumption made here
for the logic below is that `h` is a rational function in `x` and `y`
though that may not be necessary for the infinitesimals to be
bivariate polynomials. The coefficients of the infinitesimals
are found out by substituting them in the PDE and grouping similar terms
that are polynomials and since they form a linear system, solve and check
for non trivial solutions. The degree of the assumed bivariates
are increased till a certain maximum value.
References
==========
- Lie Groups and Differential Equations
pp. 327 - pp. 329
"""
h = match['h']
hx = match['hx']
hy = match['hy']
func = match['func']
x = func.args[0]
y = match['y']
xi = Function('xi')(x, func)
eta = Function('eta')(x, func)
if h.is_rational_function():
# The maximum degree that the infinitesimals can take is
# calculated by this technique.
etax, etay, etad, xix, xiy, xid = symbols("etax etay etad xix xiy xid")
ipde = etax + (etay - xix)*h - xiy*h**2 - xid*hx - etad*hy
num, denom = cancel(ipde).as_numer_denom()
deg = Poly(num, x, y).total_degree()
deta = Function('deta')(x, y)
dxi = Function('dxi')(x, y)
ipde = (deta.diff(x) + (deta.diff(y) - dxi.diff(x))*h - (dxi.diff(y))*h**2
- dxi*hx - deta*hy)
xieq = Symbol("xi0")
etaeq = Symbol("eta0")
for i in range(deg + 1):
if i:
xieq += Add(*[
Symbol("xi_" + str(power) + "_" + str(i - power))*x**power*y**(i - power)
for power in range(i + 1)])
etaeq += Add(*[
Symbol("eta_" + str(power) + "_" + str(i - power))*x**power*y**(i - power)
for power in range(i + 1)])
pden, denom = (ipde.subs({dxi: xieq, deta: etaeq}).doit()).as_numer_denom()
pden = expand(pden)
# If the individual terms are monomials, the coefficients
# are grouped
if pden.is_polynomial(x, y) and pden.is_Add:
polyy = Poly(pden, x, y).as_dict()
if polyy:
symset = xieq.free_symbols.union(etaeq.free_symbols) - {x, y}
soldict = solve(polyy.values(), *symset)
if isinstance(soldict, list):
soldict = soldict[0]
if any(x for x in soldict.values()):
xired = xieq.subs(soldict)
etared = etaeq.subs(soldict)
# Scaling is done by substituting one for the parameters
# This can be any number except zero.
dict_ = dict((sym, 1) for sym in symset)
inf = {eta: etared.subs(dict_).subs(y, func),
xi: xired.subs(dict_).subs(y, func)}
return [inf]
def lie_heuristic_chi(match, comp=False):
r"""
The aim of the fourth heuristic is to find the function `\chi(x, y)`
that satisifies the PDE `\frac{d\chi}{dx} + h\frac{d\chi}{dx}
- \frac{\partial h}{\partial y}\chi = 0`.
This assumes `\chi` to be a bivariate polynomial in `x` and `y`. By intution,
`h` should be a rational function in `x` and `y`. The method used here is
to substitute a general binomial for `\chi` up to a certain maximum degree
is reached. The coefficients of the polynomials, are calculated by by collecting
terms of the same order in `x` and `y`.
After finding `\chi`, the next step is to use `\eta = \xi*h + \chi`, to
determine `\xi` and `\eta`. This can be done by dividing `\chi` by `h`
which would give `-\xi` as the quotient and `\eta` as the remainder.
References
==========
- E.S Cheb-Terrab, L.G.S Duarte and L.A,C.P da Mota, Computer Algebra
Solving of First Order ODEs Using Symmetry Methods, pp. 8
"""
h = match['h']
hx = match['hx']
hy = match['hy']
func = match['func']
x = func.args[0]
y = match['y']
xi = Function('xi')(x, func)
eta = Function('eta')(x, func)
if h.is_rational_function():
schi, schix, schiy = symbols("schi, schix, schiy")
cpde = schix + h*schiy - hy*schi
num, denom = cancel(cpde).as_numer_denom()
deg = Poly(num, x, y).total_degree()
chi = Function('chi')(x, y)
chix = chi.diff(x)
chiy = chi.diff(y)
cpde = chix + h*chiy - hy*chi
chieq = Symbol("chi")
for i in range(1, deg + 1):
chieq += Add(*[
Symbol("chi_" + str(power) + "_" + str(i - power))*x**power*y**(i - power)
for power in range(i + 1)])
cnum, cden = cancel(cpde.subs({chi : chieq}).doit()).as_numer_denom()
cnum = expand(cnum)
if cnum.is_polynomial(x, y) and cnum.is_Add:
cpoly = Poly(cnum, x, y).as_dict()
if cpoly:
solsyms = chieq.free_symbols - {x, y}
soldict = solve(cpoly.values(), *solsyms)
if isinstance(soldict, list):
soldict = soldict[0]
if any(x for x in soldict.values()):
chieq = chieq.subs(soldict)
dict_ = dict((sym, 1) for sym in solsyms)
chieq = chieq.subs(dict_)
# After finding chi, the main aim is to find out
# eta, xi by the equation eta = xi*h + chi
# One method to set xi, would be rearranging it to
# (eta/h) - xi = (chi/h). This would mean dividing
# chi by h would give -xi as the quotient and eta
# as the remainder. Thanks to Sean Vig for suggesting
# this method.
xic, etac = div(chieq, h)
inf = {eta: etac.subs(y, func), xi: -xic.subs(y, func)}
return [inf]
def lie_heuristic_function_sum(match, comp=False):
r"""
This heuristic uses the following two assumptions on `\xi` and `\eta`
.. math:: \eta = 0, \xi = f(x) + g(y)
.. math:: \eta = f(x) + g(y), \xi = 0
The first assumption of this heuristic holds good if
.. math:: \frac{\partial}{\partial y}[(h\frac{\partial^{2}}{
\partial x^{2}}(h^{-1}))^{-1}]
is separable in `x` and `y`,
1. The separated factors containing `y` is `\frac{\partial g}{\partial y}`.
From this `g(y)` can be determined.
2. The separated factors containing `x` is `f''(x)`.
3. `h\frac{\partial^{2}}{\partial x^{2}}(h^{-1})` equals
`\frac{f''(x)}{f(x) + g(y)}`. From this `f(x)` can be determined.
The second assumption holds good if `\frac{dy}{dx} = h(x, y)` is rewritten as
`\frac{dy}{dx} = \frac{1}{h(y, x)}` and the same properties of the first
assumption satisifes. After obtaining `f(x)` and `g(y)`, the coordinates
are again interchanged, to get `\eta` as `f(x) + g(y)`.
For both assumptions, the constant factors are separated among `g(y)`
and `f''(x)`, such that `f''(x)` obtained from 3] is the same as that
obtained from 2]. If not possible, then this heuristic fails.
References
==========
- E.S. Cheb-Terrab, A.D. Roche, Symmetries and First Order
ODE Patterns, pp. 7 - pp. 8
"""
xieta = []
h = match['h']
hx = match['hx']
hy = match['hy']
func = match['func']
hinv = match['hinv']
x = func.args[0]
y = match['y']
xi = Function('xi')(x, func)
eta = Function('eta')(x, func)
for odefac in [h, hinv]:
factor = odefac*((1/odefac).diff(x, 2))
sep = separatevars((1/factor).diff(y), dict=True, symbols=[x, y])
if sep and sep['coeff'] and sep[x].has(x) and sep[y].has(y):
k = Dummy("k")
try:
gy = k*integrate(sep[y], y)
except NotImplementedError:
pass
else:
fdd = 1/(k*sep[x]*sep['coeff'])
fx = simplify(fdd/factor - gy)
check = simplify(fx.diff(x, 2) - fdd)
if fx:
if not check:
fx = fx.subs(k, 1)
gy = (gy/k)
else:
sol = solve(check, k)
if sol:
sol = sol[0]
fx = fx.subs(k, sol)
gy = (gy/k)*sol
else:
continue
if odefac == hinv: # Inverse ODE
fx = fx.subs(x, y)
gy = gy.subs(y, x)
etaval = factor_terms(fx + gy)
if etaval.is_Mul:
etaval = Mul(*[arg for arg in etaval.args if arg.has(x, y)])
if odefac == hinv: # Inverse ODE
inf = {eta: etaval.subs(y, func), xi : S(0)}
else:
inf = {xi: etaval.subs(y, func), eta : S(0)}
if not comp:
return [inf]
else:
xieta.append(inf)
if xieta:
return xieta
def lie_heuristic_abaco2_similar(match, comp=False):
r"""
This heuristic uses the following two assumptions on `\xi` and `\eta`
.. math:: \eta = g(x), \xi = f(x)
.. math:: \eta = f(y), \xi = g(y)
For the first assumption,
1. First `\frac{\frac{\partial h}{\partial y}}{\frac{\partial^{2} h}{
\partial yy}}` is calculated. Let us say this value is A
2. If this is constant, then `h` is matched to the form `A(x) + B(x)e^{
\frac{y}{C}}` then, `\frac{e^{\int \frac{A(x)}{C} \,dx}}{B(x)}` gives `f(x)`
and `A(x)*f(x)` gives `g(x)`
3. Otherwise `\frac{\frac{\partial A}{\partial X}}{\frac{\partial A}{
\partial Y}} = \gamma` is calculated. If
a] `\gamma` is a function of `x` alone
b] `\frac{\gamma\frac{\partial h}{\partial y} - \gamma'(x) - \frac{
\partial h}{\partial x}}{h + \gamma} = G` is a function of `x` alone.
then, `e^{\int G \,dx}` gives `f(x)` and `-\gamma*f(x)` gives `g(x)`
The second assumption holds good if `\frac{dy}{dx} = h(x, y)` is rewritten as
`\frac{dy}{dx} = \frac{1}{h(y, x)}` and the same properties of the first assumption
satisifes. After obtaining `f(x)` and `g(x)`, the coordinates are again
interchanged, to get `\xi` as `f(x^*)` and `\eta` as `g(y^*)`
References
==========
- E.S. Cheb-Terrab, A.D. Roche, Symmetries and First Order
ODE Patterns, pp. 10 - pp. 12
"""
xieta = []
h = match['h']
hx = match['hx']
hy = match['hy']
func = match['func']
hinv = match['hinv']
x = func.args[0]
y = match['y']
xi = Function('xi')(x, func)
eta = Function('eta')(x, func)
factor = cancel(h.diff(y)/h.diff(y, 2))
factorx = factor.diff(x)
factory = factor.diff(y)
if not factor.has(x) and not factor.has(y):
A = Wild('A', exclude=[y])
B = Wild('B', exclude=[y])
C = Wild('C', exclude=[x, y])
match = h.match(A + B*exp(y/C))
try:
tau = exp(-integrate(match[A]/match[C]), x)/match[B]
except NotImplementedError:
pass
else:
gx = match[A]*tau
return [{xi: tau, eta: gx}]
else:
gamma = cancel(factorx/factory)
if not gamma.has(y):
tauint = cancel((gamma*hy - gamma.diff(x) - hx)/(h + gamma))
if not tauint.has(y):
try:
tau = exp(integrate(tauint, x))
except NotImplementedError:
pass
else:
gx = -tau*gamma
return [{xi: tau, eta: gx}]
factor = cancel(hinv.diff(y)/hinv.diff(y, 2))
factorx = factor.diff(x)
factory = factor.diff(y)
if not factor.has(x) and not factor.has(y):
A = Wild('A', exclude=[y])
B = Wild('B', exclude=[y])
C = Wild('C', exclude=[x, y])
match = h.match(A + B*exp(y/C))
try:
tau = exp(-integrate(match[A]/match[C]), x)/match[B]
except NotImplementedError:
pass
else:
gx = match[A]*tau
return [{eta: tau.subs(x, func), xi: gx.subs(x, func)}]
else:
gamma = cancel(factorx/factory)
if not gamma.has(y):
tauint = cancel((gamma*hinv.diff(y) - gamma.diff(x) - hinv.diff(x))/(
hinv + gamma))
if not tauint.has(y):
try:
tau = exp(integrate(tauint, x))
except NotImplementedError:
pass
else:
gx = -tau*gamma
return [{eta: tau.subs(x, func), xi: gx.subs(x, func)}]
def lie_heuristic_abaco2_unique_unknown(match, comp=False):
r"""
This heuristic assumes the presence of unknown functions or known functions
with non-integer powers.
1. A list of all functions and non-integer powers containing x and y
2. Loop over each element `f` in the list, find `\frac{\frac{\partial f}{\partial x}}{
\frac{\partial f}{\partial x}} = R`
If it is separable in `x` and `y`, let `X` be the factors containing `x`. Then
a] Check if `\xi = X` and `\eta = -\frac{X}{R}` satisfy the PDE. If yes, then return
`\xi` and `\eta`
b] Check if `\xi = \frac{-R}{X}` and `\eta = -\frac{1}{X}` satisfy the PDE.
If yes, then return `\xi` and `\eta`
If not, then check if
a] :math:`\xi = -R,\eta = 1`
b] :math:`\xi = 1, \eta = -\frac{1}{R}`
are solutions.
References
==========
- E.S. Cheb-Terrab, A.D. Roche, Symmetries and First Order
ODE Patterns, pp. 10 - pp. 12
"""
xieta = []
h = match['h']
hx = match['hx']
hy = match['hy']
func = match['func']
hinv = match['hinv']
x = func.args[0]
y = match['y']
xi = Function('xi')(x, func)
eta = Function('eta')(x, func)
funclist = []
for atom in h.atoms(Pow):
base, exp = atom.as_base_exp()
if base.has(x) and base.has(y):
if not exp.is_Integer:
funclist.append(atom)
for function in h.atoms(AppliedUndef):
syms = function.free_symbols
if x in syms and y in syms:
funclist.append(function)
for f in funclist:
frac = cancel(f.diff(y)/f.diff(x))
sep = separatevars(frac, dict=True, symbols=[x, y])
if sep and sep['coeff']:
xitry1 = sep[x]
etatry1 = -1/(sep[y]*sep['coeff'])
pde1 = etatry1.diff(y)*h - xitry1.diff(x)*h - xitry1*hx - etatry1*hy
if not simplify(pde1):
return [{xi: xitry1, eta: etatry1.subs(y, func)}]
xitry2 = 1/etatry1
etatry2 = 1/xitry1
pde2 = etatry2.diff(x) - (xitry2.diff(y))*h**2 - xitry2*hx - etatry2*hy
if not simplify(expand(pde2)):
return [{xi: xitry2.subs(y, func), eta: etatry2}]
else:
etatry = -1/frac
pde = etatry.diff(x) + etatry.diff(y)*h - hx - etatry*hy
if not simplify(pde):
return [{xi: S(1), eta: etatry.subs(y, func)}]
xitry = -frac
pde = -xitry.diff(x)*h -xitry.diff(y)*h**2 - xitry*hx -hy
if not simplify(expand(pde)):
return [{xi: xitry.subs(y, func), eta: S(1)}]
def lie_heuristic_abaco2_unique_general(match, comp=False):
r"""
This heuristic finds if infinitesimals of the form `\eta = f(x)`, `\xi = g(y)`
without making any assumptions on `h`.
The complete sequence of steps is given in the paper mentioned below.
References
==========
- E.S. Cheb-Terrab, A.D. Roche, Symmetries and First Order
ODE Patterns, pp. 10 - pp. 12
"""
xieta = []
h = match['h']
hx = match['hx']
hy = match['hy']
func = match['func']
hinv = match['hinv']
x = func.args[0]
y = match['y']
xi = Function('xi')(x, func)
eta = Function('eta')(x, func)
C = S(0)
A = hx.diff(y)
B = hy.diff(y) + hy**2
C = hx.diff(x) - hx**2
if not (A and B and C):
return
Ax = A.diff(x)
Ay = A.diff(y)
Axy = Ax.diff(y)
Axx = Ax.diff(x)
Ayy = Ay.diff(y)
D = simplify(2*Axy + hx*Ay - Ax*hy + (hx*hy + 2*A)*A)*A - 3*Ax*Ay
if not D:
E1 = simplify(3*Ax**2 + ((hx**2 + 2*C)*A - 2*Axx)*A)
if E1:
E2 = simplify((2*Ayy + (2*B - hy**2)*A)*A - 3*Ay**2)
if not E2:
E3 = simplify(
E1*((28*Ax + 4*hx*A)*A**3 - E1*(hy*A + Ay)) - E1.diff(x)*8*A**4)
if not E3:
etaval = cancel((4*A**3*(Ax - hx*A) + E1*(hy*A - Ay))/(S(2)*A*E1))
if x not in etaval:
try:
etaval = exp(integrate(etaval, y))
except NotImplementedError:
pass
else:
xival = -4*A**3*etaval/E1
if y not in xival:
return [{xi: xival, eta: etaval.subs(y, func)}]
else:
E1 = simplify((2*Ayy + (2*B - hy**2)*A)*A - 3*Ay**2)
if E1:
E2 = simplify(
4*A**3*D - D**2 + E1*((2*Axx - (hx**2 + 2*C)*A)*A - 3*Ax**2))
if not E2:
E3 = simplify(
-(A*D)*E1.diff(y) + ((E1.diff(x) - hy*D)*A + 3*Ay*D +
(A*hx - 3*Ax)*E1)*E1)
if not E3:
etaval = cancel(((A*hx - Ax)*E1 - (Ay + A*hy)*D)/(S(2)*A*D))
if x not in etaval:
try:
etaval = exp(integrate(etaval, y))
except NotImplementedError:
pass
else:
xival = -E1*etaval/D
if y not in xival:
return [{xi: xival, eta: etaval.subs(y, func)}]
def lie_heuristic_linear(match, comp=False):
r"""
This heuristic assumes
1. `\xi = ax + by + c` and
2. `\eta = fx + gy + h`
After substituting the following assumptions in the determining PDE, it
reduces to
.. math:: f + (g - a)h - bh^{2} - (ax + by + c)\frac{\partial h}{\partial x}
- (fx + gy + c)\frac{\partial h}{\partial y}
Solving the reduced PDE obtained, using the method of characteristics, becomes
impractical. The method followed is grouping similar terms and solving the system
of linear equations obtained. The difference between the bivariate heuristic is that
`h` need not be a rational function in this case.
References
==========
- E.S. Cheb-Terrab, A.D. Roche, Symmetries and First Order
ODE Patterns, pp. 10 - pp. 12
"""
xieta = []
h = match['h']
hx = match['hx']
hy = match['hy']
func = match['func']
hinv = match['hinv']
x = func.args[0]
y = match['y']
xi = Function('xi')(x, func)
eta = Function('eta')(x, func)
coeffdict = {}
symbols = numbered_symbols("c", cls=Dummy)
symlist = [next(symbols) for i in islice(symbols, 6)]
C0, C1, C2, C3, C4, C5 = symlist
pde = C3 + (C4 - C0)*h -(C0*x + C1*y + C2)*hx - (C3*x + C4*y + C5)*hy - C1*h**2
pde, denom = pde.as_numer_denom()
pde = powsimp(expand(pde))
if pde.is_Add:
terms = pde.args
for term in terms:
if term.is_Mul:
rem = Mul(*[m for m in term.args if not m.has(x, y)])
xypart = term/rem
if xypart not in coeffdict:
coeffdict[xypart] = rem
else:
coeffdict[xypart] += rem
else:
if term not in coeffdict:
coeffdict[term] = S(1)
else:
coeffdict[term] += S(1)
sollist = coeffdict.values()
soldict = solve(sollist, symlist)
if soldict:
if isinstance(soldict, list):
soldict = soldict[0]
subval = soldict.values()
if any(t for t in subval):
onedict = dict(zip(symlist, [1]*6))
xival = C0*x + C1*func + C2
etaval = C3*x + C4*func + C5
xival = xival.subs(soldict)
etaval = etaval.subs(soldict)
xival = xival.subs(onedict)
etaval = etaval.subs(onedict)
return [{xi: xival, eta: etaval}]
def sysode_linear_2eq_order1(match_):
x = match_['func'][0].func
y = match_['func'][1].func
func = match_['func']
fc = match_['func_coeff']
eq = match_['eq']
C1, C2, C3, C4 = get_numbered_constants(eq, num=4)
r = dict()
t = list(list(eq[0].atoms(Derivative))[0].atoms(Symbol))[0]
for i in range(2):
eqs = 0
for terms in Add.make_args(eq[i]):
eqs += terms/fc[i,func[i],1]
eq[i] = eqs
# for equations Eq(a1*diff(x(t),t), a*x(t) + b*y(t) + k1)
# and Eq(a2*diff(x(t),t), c*x(t) + d*y(t) + k2)
r['a'] = -fc[0,x(t),0]/fc[0,x(t),1]
r['c'] = -fc[1,x(t),0]/fc[1,y(t),1]
r['b'] = -fc[0,y(t),0]/fc[0,x(t),1]
r['d'] = -fc[1,y(t),0]/fc[1,y(t),1]
forcing = [S(0),S(0)]
for i in range(2):
for j in Add.make_args(eq[i]):
if not j.has(x(t), y(t)):
forcing[i] += j
if not (forcing[0].has(t) or forcing[1].has(t)):
r['k1'] = forcing[0]
r['k2'] = forcing[1]
else:
raise NotImplementedError("Only homogeneous problems are supported" +
" (and constant inhomogeneity)")
if match_['type_of_equation'] == 'type1':
sol = _linear_2eq_order1_type1(x, y, t, r, eq)
if match_['type_of_equation'] == 'type2':
gsol = _linear_2eq_order1_type1(x, y, t, r, eq)
psol = _linear_2eq_order1_type2(x, y, t, r, eq)
sol = [Eq(x(t), gsol[0].rhs+psol[0]), Eq(y(t), gsol[1].rhs+psol[1])]
if match_['type_of_equation'] == 'type3':
sol = _linear_2eq_order1_type3(x, y, t, r, eq)
if match_['type_of_equation'] == 'type4':
sol = _linear_2eq_order1_type4(x, y, t, r, eq)
if match_['type_of_equation'] == 'type5':
sol = _linear_2eq_order1_type5(x, y, t, r, eq)
if match_['type_of_equation'] == 'type6':
sol = _linear_2eq_order1_type6(x, y, t, r, eq)
if match_['type_of_equation'] == 'type7':
sol = _linear_2eq_order1_type7(x, y, t, r, eq)
return sol
def _linear_2eq_order1_type1(x, y, t, r, eq):
r"""
It is classified under system of two linear homogeneous first-order constant-coefficient
ordinary differential equations.
The equations which come under this type are
.. math:: x' = ax + by,
.. math:: y' = cx + dy
The characteristics equation is written as
.. math:: \lambda^{2} + (a+d) \lambda + ad - bc = 0
and its discriminant is `D = (a-d)^{2} + 4bc`. There are several cases
1. Case when `ad - bc \neq 0`. The origin of coordinates, `x = y = 0`,
is the only stationary point; it is
- a node if `D = 0`
- a node if `D > 0` and `ad - bc > 0`
- a saddle if `D > 0` and `ad - bc < 0`
- a focus if `D < 0` and `a + d \neq 0`
- a centre if `D < 0` and `a + d \neq 0`.
1.1. If `D > 0`. The characteristic equation has two distinct real roots
`\lambda_1` and `\lambda_ 2` . The general solution of the system in question is expressed as
.. math:: x = C_1 b e^{\lambda_1 t} + C_2 b e^{\lambda_2 t}
.. math:: y = C_1 (\lambda_1 - a) e^{\lambda_1 t} + C_2 (\lambda_2 - a) e^{\lambda_2 t}
where `C_1` and `C_2` being arbitary constants
1.2. If `D < 0`. The characteristics equation has two conjugate
roots, `\lambda_1 = \sigma + i \beta` and `\lambda_2 = \sigma - i \beta`.
The general solution of the system is given by
.. math:: x = b e^{\sigma t} (C_1 \sin(\beta t) + C_2 \cos(\beta t))
.. math:: y = e^{\sigma t} ([(\sigma - a) C_1 - \beta C_2] \sin(\beta t) + [\beta C_1 + (\sigma - a) C_2 \cos(\beta t)])
1.3. If `D = 0` and `a \neq d`. The characteristic equation has
two equal roots, `\lambda_1 = \lambda_2`. The general solution of the system is written as
.. math:: x = 2b (C_1 + \frac{C_2}{a-d} + C_2 t) e^{\frac{a+d}{2} t}
.. math:: y = [(d - a) C_1 + C_2 + (d - a) C_2 t] e^{\frac{a+d}{2} t}
1.4. If `D = 0` and `a = d \neq 0` and `b = 0`
.. math:: x = C_1 e^{a t} , y = (c C_1 t + C_2) e^{a t}
1.5. If `D = 0` and `a = d \neq 0` and `c = 0`
.. math:: x = (b C_1 t + C_2) e^{a t} , y = C_1 e^{a t}
2. Case when `ad - bc = 0` and `a^{2} + b^{2} > 0`. The whole straight
line `ax + by = 0` consists of singular points. The orginal system of differential
equaitons can be rewritten as
.. math:: x' = ax + by , y' = k (ax + by)
2.1 If `a + bk \neq 0`, solution will be
.. math:: x = b C_1 + C_2 e^{(a + bk) t} , y = -a C_1 + k C_2 e^{(a + bk) t}
2.2 If `a + bk = 0`, solution will be
.. math:: x = C_1 (bk t - 1) + b C_2 t , y = k^{2} b C_1 t + (b k^{2} t + 1) C_2
"""
# FIXME: at least some of these can fail to give two linearly
# independent solutions e.g., because they make assumptions about
# zero/nonzero of certain coefficients. I've "fixed" one and
# raised NotImplementedError in another. I think this should probably
# just be re-written in terms of eigenvectors...
l = Dummy('l')
C1, C2, C3, C4 = get_numbered_constants(eq, num=4)
l1 = rootof(l**2 - (r['a']+r['d'])*l + r['a']*r['d'] - r['b']*r['c'], l, 0)
l2 = rootof(l**2 - (r['a']+r['d'])*l + r['a']*r['d'] - r['b']*r['c'], l, 1)
D = (r['a'] - r['d'])**2 + 4*r['b']*r['c']
if (r['a']*r['d'] - r['b']*r['c']) != 0:
if D > 0:
if r['b'].is_zero:
# tempting to use this in all cases, but does not guarantee linearly independent eigenvectors
gsol1 = C1*(l1 - r['d'] + r['b'])*exp(l1*t) + C2*(l2 - r['d'] + r['b'])*exp(l2*t)
gsol2 = C1*(l1 - r['a'] + r['c'])*exp(l1*t) + C2*(l2 - r['a'] + r['c'])*exp(l2*t)
else:
gsol1 = C1*r['b']*exp(l1*t) + C2*r['b']*exp(l2*t)
gsol2 = C1*(l1 - r['a'])*exp(l1*t) + C2*(l2 - r['a'])*exp(l2*t)
if D < 0:
sigma = re(l1)
if im(l1).is_positive:
beta = im(l1)
else:
beta = im(l2)
if r['b'].is_zero:
raise NotImplementedError('b == 0 case not implemented')
gsol1 = r['b']*exp(sigma*t)*(C1*sin(beta*t)+C2*cos(beta*t))
gsol2 = exp(sigma*t)*(((C1*(sigma-r['a'])-C2*beta)*sin(beta*t)+(C1*beta+(sigma-r['a'])*C2)*cos(beta*t)))
if D == 0:
if r['a']!=r['d']:
gsol1 = 2*r['b']*(C1 + C2/(r['a']-r['d'])+C2*t)*exp((r['a']+r['d'])*t/2)
gsol2 = ((r['d']-r['a'])*C1+C2+(r['d']-r['a'])*C2*t)*exp((r['a']+r['d'])*t/2)
if r['a']==r['d'] and r['a']!=0 and r['b']==0:
gsol1 = C1*exp(r['a']*t)
gsol2 = (r['c']*C1*t+C2)*exp(r['a']*t)
if r['a']==r['d'] and r['a']!=0 and r['c']==0:
gsol1 = (r['b']*C1*t+C2)*exp(r['a']*t)
gsol2 = C1*exp(r['a']*t)
elif (r['a']*r['d'] - r['b']*r['c']) == 0 and (r['a']**2+r['b']**2) > 0:
k = r['c']/r['a']
if r['a']+r['b']*k != 0:
gsol1 = r['b']*C1 + C2*exp((r['a']+r['b']*k)*t)
gsol2 = -r['a']*C1 + k*C2*exp((r['a']+r['b']*k)*t)
else:
gsol1 = C1*(r['b']*k*t-1)+r['b']*C2*t
gsol2 = k**2*r['b']*C1*t+(r['b']*k**2*t+1)*C2
return [Eq(x(t), gsol1), Eq(y(t), gsol2)]
def _linear_2eq_order1_type2(x, y, t, r, eq):
r"""
The equations of this type are
.. math:: x' = ax + by + k1 , y' = cx + dy + k2
The general solution of this system is given by sum of its particular solution and the
general solution of the corresponding homogeneous system is obtained from type1.
1. When `ad - bc \neq 0`. The particular solution will be
`x = x_0` and `y = y_0` where `x_0` and `y_0` are determined by solving linear system of equations
.. math:: a x_0 + b y_0 + k1 = 0 , c x_0 + d y_0 + k2 = 0
2. When `ad - bc = 0` and `a^{2} + b^{2} > 0`. In this case, the system of equation becomes
.. math:: x' = ax + by + k_1 , y' = k (ax + by) + k_2
2.1 If `\sigma = a + bk \neq 0`, particular solution is given by
.. math:: x = b \sigma^{-1} (c_1 k - c_2) t - \sigma^{-2} (a c_1 + b c_2)
.. math:: y = kx + (c_2 - c_1 k) t
2.2 If `\sigma = a + bk = 0`, particular solution is given by
.. math:: x = \frac{1}{2} b (c_2 - c_1 k) t^{2} + c_1 t
.. math:: y = kx + (c_2 - c_1 k) t
"""
r['k1'] = -r['k1']; r['k2'] = -r['k2']
if (r['a']*r['d'] - r['b']*r['c']) != 0:
x0, y0 = symbols('x0, y0', cls=Dummy)
sol = solve((r['a']*x0+r['b']*y0+r['k1'], r['c']*x0+r['d']*y0+r['k2']), x0, y0)
psol = [sol[x0], sol[y0]]
elif (r['a']*r['d'] - r['b']*r['c']) == 0 and (r['a']**2+r['b']**2) > 0:
k = r['c']/r['a']
sigma = r['a'] + r['b']*k
if sigma != 0:
sol1 = r['b']*sigma**-1*(r['k1']*k-r['k2'])*t - sigma**-2*(r['a']*r['k1']+r['b']*r['k2'])
sol2 = k*sol1 + (r['k2']-r['k1']*k)*t
else:
# FIXME: a previous typo fix shows this is not covered by tests
sol1 = r['b']*(r['k2']-r['k1']*k)*t**2 + r['k1']*t
sol2 = k*sol1 + (r['k2']-r['k1']*k)*t
psol = [sol1, sol2]
return psol
def _linear_2eq_order1_type3(x, y, t, r, eq):
r"""
The equations of this type of ode are
.. math:: x' = f(t) x + g(t) y
.. math:: y' = g(t) x + f(t) y
The solution of such equations is given by
.. math:: x = e^{F} (C_1 e^{G} + C_2 e^{-G}) , y = e^{F} (C_1 e^{G} - C_2 e^{-G})
where `C_1` and `C_2` are arbitary constants, and
.. math:: F = \int f(t) \,dt , G = \int g(t) \,dt
"""
C1, C2, C3, C4 = get_numbered_constants(eq, num=4)
F = Integral(r['a'], t)
G = Integral(r['b'], t)
sol1 = exp(F)*(C1*exp(G) + C2*exp(-G))
sol2 = exp(F)*(C1*exp(G) - C2*exp(-G))
return [Eq(x(t), sol1), Eq(y(t), sol2)]
def _linear_2eq_order1_type4(x, y, t, r, eq):
r"""
The equations of this type of ode are .
.. math:: x' = f(t) x + g(t) y
.. math:: y' = -g(t) x + f(t) y
The solution is given by
.. math:: x = F (C_1 \cos(G) + C_2 \sin(G)), y = F (-C_1 \sin(G) + C_2 \cos(G))
where `C_1` and `C_2` are arbitary constants, and
.. math:: F = \int f(t) \,dt , G = \int g(t) \,dt
"""
C1, C2, C3, C4 = get_numbered_constants(eq, num=4)
if r['b'] == -r['c']:
F = exp(Integral(r['a'], t))
G = Integral(r['b'], t)
sol1 = F*(C1*cos(G) + C2*sin(G))
sol2 = F*(-C1*sin(G) + C2*cos(G))
elif r['d'] == -r['a']:
F = exp(Integral(r['c'], t))
G = Integral(r['d'], t)
sol1 = F*(-C1*sin(G) + C2*cos(G))
sol2 = F*(C1*cos(G) + C2*sin(G))
return [Eq(x(t), sol1), Eq(y(t), sol2)]
def _linear_2eq_order1_type5(x, y, t, r, eq):
r"""
The equations of this type of ode are .
.. math:: x' = f(t) x + g(t) y
.. math:: y' = a g(t) x + [f(t) + b g(t)] y
The transformation of
.. math:: x = e^{\int f(t) \,dt} u , y = e^{\int f(t) \,dt} v , T = \int g(t) \,dt
leads to a system of constant coefficient linear differential equations
.. math:: u'(T) = v , v'(T) = au + bv
"""
C1, C2, C3, C4 = get_numbered_constants(eq, num=4)
u, v = symbols('u, v', function=True)
T = Symbol('T')
if not cancel(r['c']/r['b']).has(t):
p = cancel(r['c']/r['b'])
q = cancel((r['d']-r['a'])/r['b'])
eq = (Eq(diff(u(T),T), v(T)), Eq(diff(v(T),T), p*u(T)+q*v(T)))
sol = dsolve(eq)
sol1 = exp(Integral(r['a'], t))*sol[0].rhs.subs(T, Integral(r['b'],t))
sol2 = exp(Integral(r['a'], t))*sol[1].rhs.subs(T, Integral(r['b'],t))
if not cancel(r['a']/r['d']).has(t):
p = cancel(r['a']/r['d'])
q = cancel((r['b']-r['c'])/r['d'])
sol = dsolve(Eq(diff(u(T),T), v(T)), Eq(diff(v(T),T), p*u(T)+q*v(T)))
sol1 = exp(Integral(r['c'], t))*sol[1].rhs.subs(T, Integral(r['d'],t))
sol2 = exp(Integral(r['c'], t))*sol[0].rhs.subs(T, Integral(r['d'],t))
return [Eq(x(t), sol1), Eq(y(t), sol2)]
def _linear_2eq_order1_type6(x, y, t, r, eq):
r"""
The equations of this type of ode are .
.. math:: x' = f(t) x + g(t) y
.. math:: y' = a [f(t) + a h(t)] x + a [g(t) - h(t)] y
This is solved by first multiplying the first equation by `-a` and adding
it to the second equation to obtain
.. math:: y' - a x' = -a h(t) (y - a x)
Setting `U = y - ax` and integrating the equation we arrive at
.. math:: y - ax = C_1 e^{-a \int h(t) \,dt}
and on substituing the value of y in first equation give rise to first order ODEs. After solving for
`x`, we can obtain `y` by substituting the value of `x` in second equation.
"""
C1, C2, C3, C4 = get_numbered_constants(eq, num=4)
p = 0
q = 0
p1 = cancel(r['c']/cancel(r['c']/r['d']).as_numer_denom()[0])
p2 = cancel(r['a']/cancel(r['a']/r['b']).as_numer_denom()[0])
for n, i in enumerate([p1, p2]):
for j in Mul.make_args(collect_const(i)):
if not j.has(t):
q = j
if q!=0 and n==0:
if ((r['c']/j - r['a'])/(r['b'] - r['d']/j)) == j:
p = 1
s = j
break
if q!=0 and n==1:
if ((r['a']/j - r['c'])/(r['d'] - r['b']/j)) == j:
p = 2
s = j
break
if p == 1:
equ = diff(x(t),t) - r['a']*x(t) - r['b']*(s*x(t) + C1*exp(-s*Integral(r['b'] - r['d']/s, t)))
hint1 = classify_ode(equ)[1]
sol1 = dsolve(equ, hint=hint1+'_Integral').rhs
sol2 = s*sol1 + C1*exp(-s*Integral(r['b'] - r['d']/s, t))
elif p ==2:
equ = diff(y(t),t) - r['c']*y(t) - r['d']*s*y(t) + C1*exp(-s*Integral(r['d'] - r['b']/s, t))
hint1 = classify_ode(equ)[1]
sol2 = dsolve(equ, hint=hint1+'_Integral').rhs
sol1 = s*sol2 + C1*exp(-s*Integral(r['d'] - r['b']/s, t))
return [Eq(x(t), sol1), Eq(y(t), sol2)]
def _linear_2eq_order1_type7(x, y, t, r, eq):
r"""
The equations of this type of ode are .
.. math:: x' = f(t) x + g(t) y
.. math:: y' = h(t) x + p(t) y
Differentiating the first equation and substituting the value of `y`
from second equation will give a second-order linear equation
.. math:: g x'' - (fg + gp + g') x' + (fgp - g^{2} h + f g' - f' g) x = 0
This above equation can be easily integrated if following conditions are satisfied.
1. `fgp - g^{2} h + f g' - f' g = 0`
2. `fgp - g^{2} h + f g' - f' g = ag, fg + gp + g' = bg`
If first condition is satisfied then it is solved by current dsolve solver and in second case it becomes
a constant cofficient differential equation which is also solved by current solver.
Otherwise if the above condition fails then,
a particular solution is assumed as `x = x_0(t)` and `y = y_0(t)`
Then the general solution is expressed as
.. math:: x = C_1 x_0(t) + C_2 x_0(t) \int \frac{g(t) F(t) P(t)}{x_0^{2}(t)} \,dt
.. math:: y = C_1 y_0(t) + C_2 [\frac{F(t) P(t)}{x_0(t)} + y_0(t) \int \frac{g(t) F(t) P(t)}{x_0^{2}(t)} \,dt]
where C1 and C2 are arbitary constants and
.. math:: F(t) = e^{\int f(t) \,dt} , P(t) = e^{\int p(t) \,dt}
"""
C1, C2, C3, C4 = get_numbered_constants(eq, num=4)
e1 = r['a']*r['b']*r['c'] - r['b']**2*r['c'] + r['a']*diff(r['b'],t) - diff(r['a'],t)*r['b']
e2 = r['a']*r['c']*r['d'] - r['b']*r['c']**2 + diff(r['c'],t)*r['d'] - r['c']*diff(r['d'],t)
m1 = r['a']*r['b'] + r['b']*r['d'] + diff(r['b'],t)
m2 = r['a']*r['c'] + r['c']*r['d'] + diff(r['c'],t)
if e1 == 0:
sol1 = dsolve(r['b']*diff(x(t),t,t) - m1*diff(x(t),t)).rhs
sol2 = dsolve(diff(y(t),t) - r['c']*sol1 - r['d']*y(t)).rhs
elif e2 == 0:
sol2 = dsolve(r['c']*diff(y(t),t,t) - m2*diff(y(t),t)).rhs
sol1 = dsolve(diff(x(t),t) - r['a']*x(t) - r['b']*sol2).rhs
elif not (e1/r['b']).has(t) and not (m1/r['b']).has(t):
sol1 = dsolve(diff(x(t),t,t) - (m1/r['b'])*diff(x(t),t) - (e1/r['b'])*x(t)).rhs
sol2 = dsolve(diff(y(t),t) - r['c']*sol1 - r['d']*y(t)).rhs
elif not (e2/r['c']).has(t) and not (m2/r['c']).has(t):
sol2 = dsolve(diff(y(t),t,t) - (m2/r['c'])*diff(y(t),t) - (e2/r['c'])*y(t)).rhs
sol1 = dsolve(diff(x(t),t) - r['a']*x(t) - r['b']*sol2).rhs
else:
x0, y0 = symbols('x0, y0') #x0 and y0 being particular solutions
F = exp(Integral(r['a'],t))
P = exp(Integral(r['d'],t))
sol1 = C1*x0 + C2*x0*Integral(r['b']*F*P/x0**2, t)
sol2 = C1*y0 + C2(F*P/x0 + y0*Integral(r['b']*F*P/x0**2, t))
return [Eq(x(t), sol1), Eq(y(t), sol2)]
def sysode_linear_2eq_order2(match_):
x = match_['func'][0].func
y = match_['func'][1].func
func = match_['func']
fc = match_['func_coeff']
eq = match_['eq']
C1, C2, C3, C4 = get_numbered_constants(eq, num=4)
r = dict()
t = list(list(eq[0].atoms(Derivative))[0].atoms(Symbol))[0]
for i in range(2):
eqs = []
for terms in Add.make_args(eq[i]):
eqs.append(terms/fc[i,func[i],2])
eq[i] = Add(*eqs)
# for equations Eq(diff(x(t),t,t), a1*diff(x(t),t)+b1*diff(y(t),t)+c1*x(t)+d1*y(t)+e1)
# and Eq(a2*diff(y(t),t,t), a2*diff(x(t),t)+b2*diff(y(t),t)+c2*x(t)+d2*y(t)+e2)
r['a1'] = -fc[0,x(t),1]/fc[0,x(t),2] ; r['a2'] = -fc[1,x(t),1]/fc[1,y(t),2]
r['b1'] = -fc[0,y(t),1]/fc[0,x(t),2] ; r['b2'] = -fc[1,y(t),1]/fc[1,y(t),2]
r['c1'] = -fc[0,x(t),0]/fc[0,x(t),2] ; r['c2'] = -fc[1,x(t),0]/fc[1,y(t),2]
r['d1'] = -fc[0,y(t),0]/fc[0,x(t),2] ; r['d2'] = -fc[1,y(t),0]/fc[1,y(t),2]
const = [S(0), S(0)]
for i in range(2):
for j in Add.make_args(eq[i]):
if not (j.has(x(t)) or j.has(y(t))):
const[i] += j
r['e1'] = -const[0]
r['e2'] = -const[1]
if match_['type_of_equation'] == 'type1':
sol = _linear_2eq_order2_type1(x, y, t, r, eq)
elif match_['type_of_equation'] == 'type2':
gsol = _linear_2eq_order2_type1(x, y, t, r, eq)
psol = _linear_2eq_order2_type2(x, y, t, r, eq)
sol = [Eq(x(t), gsol[0].rhs+psol[0]), Eq(y(t), gsol[1].rhs+psol[1])]
elif match_['type_of_equation'] == 'type3':
sol = _linear_2eq_order2_type3(x, y, t, r, eq)
elif match_['type_of_equation'] == 'type4':
sol = _linear_2eq_order2_type4(x, y, t, r, eq)
elif match_['type_of_equation'] == 'type5':
sol = _linear_2eq_order2_type5(x, y, t, r, eq)
elif match_['type_of_equation'] == 'type6':
sol = _linear_2eq_order2_type6(x, y, t, r, eq)
elif match_['type_of_equation'] == 'type7':
sol = _linear_2eq_order2_type7(x, y, t, r, eq)
elif match_['type_of_equation'] == 'type8':
sol = _linear_2eq_order2_type8(x, y, t, r, eq)
elif match_['type_of_equation'] == 'type9':
sol = _linear_2eq_order2_type9(x, y, t, r, eq)
elif match_['type_of_equation'] == 'type10':
sol = _linear_2eq_order2_type10(x, y, t, r, eq)
elif match_['type_of_equation'] == 'type11':
sol = _linear_2eq_order2_type11(x, y, t, r, eq)
return sol
def _linear_2eq_order2_type1(x, y, t, r, eq):
r"""
System of two constant-coefficient second-order linear homogeneous differential equations
.. math:: x'' = ax + by
.. math:: y'' = cx + dy
The charecteristic equation for above equations
.. math:: \lambda^4 - (a + d) \lambda^2 + ad - bc = 0
whose discriminant is `D = (a - d)^2 + 4bc \neq 0`
1. When `ad - bc \neq 0`
1.1. If `D \neq 0`. The characteristic equation has four distict roots, `\lambda_1, \lambda_2, \lambda_3, \lambda_4`.
The general solution of the system is
.. math:: x = C_1 b e^{\lambda_1 t} + C_2 b e^{\lambda_2 t} + C_3 b e^{\lambda_3 t} + C_4 b e^{\lambda_4 t}
.. math:: y = C_1 (\lambda_1^{2} - a) e^{\lambda_1 t} + C_2 (\lambda_2^{2} - a) e^{\lambda_2 t} + C_3 (\lambda_3^{2} - a) e^{\lambda_3 t} + C_4 (\lambda_4^{2} - a) e^{\lambda_4 t}
where `C_1,..., C_4` are arbitary constants.
1.2. If `D = 0` and `a \neq d`:
.. math:: x = 2 C_1 (bt + \frac{2bk}{a - d}) e^{\frac{kt}{2}} + 2 C_2 (bt + \frac{2bk}{a - d}) e^{\frac{-kt}{2}} + 2b C_3 t e^{\frac{kt}{2}} + 2b C_4 t e^{\frac{-kt}{2}}
.. math:: y = C_1 (d - a) t e^{\frac{kt}{2}} + C_2 (d - a) t e^{\frac{-kt}{2}} + C_3 [(d - a) t + 2k] e^{\frac{kt}{2}} + C_4 [(d - a) t - 2k] e^{\frac{-kt}{2}}
where `C_1,..., C_4` are arbitary constants and `k = \sqrt{2 (a + d)}`
1.3. If `D = 0` and `a = d \neq 0` and `b = 0`:
.. math:: x = 2 \sqrt{a} C_1 e^{\sqrt{a} t} + 2 \sqrt{a} C_2 e^{-\sqrt{a} t}
.. math:: y = c C_1 t e^{\sqrt{a} t} - c C_2 t e^{-\sqrt{a} t} + C_3 e^{\sqrt{a} t} + C_4 e^{-\sqrt{a} t}
1.4. If `D = 0` and `a = d \neq 0` and `c = 0`:
.. math:: x = b C_1 t e^{\sqrt{a} t} - b C_2 t e^{-\sqrt{a} t} + C_3 e^{\sqrt{a} t} + C_4 e^{-\sqrt{a} t}
.. math:: y = 2 \sqrt{a} C_1 e^{\sqrt{a} t} + 2 \sqrt{a} C_2 e^{-\sqrt{a} t}
2. When `ad - bc = 0` and `a^2 + b^2 > 0`. Then the original system becomes
.. math:: x'' = ax + by
.. math:: y'' = k (ax + by)
2.1. If `a + bk \neq 0`:
.. math:: x = C_1 e^{t \sqrt{a + bk}} + C_2 e^{-t \sqrt{a + bk}} + C_3 bt + C_4 b
.. math:: y = C_1 k e^{t \sqrt{a + bk}} + C_2 k e^{-t \sqrt{a + bk}} - C_3 at - C_4 a
2.2. If `a + bk = 0`:
.. math:: x = C_1 b t^3 + C_2 b t^2 + C_3 t + C_4
.. math:: y = kx + 6 C_1 t + 2 C_2
"""
r['a'] = r['c1']
r['b'] = r['d1']
r['c'] = r['c2']
r['d'] = r['d2']
l = Symbol('l')
C1, C2, C3, C4 = get_numbered_constants(eq, num=4)
chara_eq = l**4 - (r['a']+r['d'])*l**2 + r['a']*r['d'] - r['b']*r['c']
l1 = rootof(chara_eq, 0)
l2 = rootof(chara_eq, 1)
l3 = rootof(chara_eq, 2)
l4 = rootof(chara_eq, 3)
D = (r['a'] - r['d'])**2 + 4*r['b']*r['c']
if (r['a']*r['d'] - r['b']*r['c']) != 0:
if D != 0:
gsol1 = C1*r['b']*exp(l1*t) + C2*r['b']*exp(l2*t) + C3*r['b']*exp(l3*t) \
+ C4*r['b']*exp(l4*t)
gsol2 = C1*(l1**2-r['a'])*exp(l1*t) + C2*(l2**2-r['a'])*exp(l2*t) + \
C3*(l3**2-r['a'])*exp(l3*t) + C4*(l4**2-r['a'])*exp(l4*t)
else:
if r['a'] != r['d']:
k = sqrt(2*(r['a']+r['d']))
mid = r['b']*t+2*r['b']*k/(r['a']-r['d'])
gsol1 = 2*C1*mid*exp(k*t/2) + 2*C2*mid*exp(-k*t/2) + \
2*r['b']*C3*t*exp(k*t/2) + 2*r['b']*C4*t*exp(-k*t/2)
gsol2 = C1*(r['d']-r['a'])*t*exp(k*t/2) + C2*(r['d']-r['a'])*t*exp(-k*t/2) + \
C3*((r['d']-r['a'])*t+2*k)*exp(k*t/2) + C4*((r['d']-r['a'])*t-2*k)*exp(-k*t/2)
elif r['a'] == r['d'] != 0 and r['b'] == 0:
sa = sqrt(r['a'])
gsol1 = 2*sa*C1*exp(sa*t) + 2*sa*C2*exp(-sa*t)
gsol2 = r['c']*C1*t*exp(sa*t)-r['c']*C2*t*exp(-sa*t)+C3*exp(sa*t)+C4*exp(-sa*t)
elif r['a'] == r['d'] != 0 and r['c'] == 0:
sa = sqrt(r['a'])
gsol1 = r['b']*C1*t*exp(sa*t)-r['b']*C2*t*exp(-sa*t)+C3*exp(sa*t)+C4*exp(-sa*t)
gsol2 = 2*sa*C1*exp(sa*t) + 2*sa*C2*exp(-sa*t)
elif (r['a']*r['d'] - r['b']*r['c']) == 0 and (r['a']**2 + r['b']**2) > 0:
k = r['c']/r['a']
if r['a'] + r['b']*k != 0:
mid = sqrt(r['a'] + r['b']*k)
gsol1 = C1*exp(mid*t) + C2*exp(-mid*t) + C3*r['b']*t + C4*r['b']
gsol2 = C1*k*exp(mid*t) + C2*k*exp(-mid*t) - C3*r['a']*t - C4*r['a']
else:
gsol1 = C1*r['b']*t**3 + C2*r['b']*t**2 + C3*t + C4
gsol2 = k*gsol1 + 6*C1*t + 2*C2
return [Eq(x(t), gsol1), Eq(y(t), gsol2)]
def _linear_2eq_order2_type2(x, y, t, r, eq):
r"""
The equations in this type are
.. math:: x'' = a_1 x + b_1 y + c_1
.. math:: y'' = a_2 x + b_2 y + c_2
The general solution of this system is given by the sum of its particular solution
and the general solution of the homogeneous system. The general solution is given
by the linear system of 2 equation of order 2 and type 1
1. If `a_1 b_2 - a_2 b_1 \neq 0`. A particular solution will be `x = x_0` and `y = y_0`
where the constants `x_0` and `y_0` are determined by solving the linear algebraic system
.. math:: a_1 x_0 + b_1 y_0 + c_1 = 0, a_2 x_0 + b_2 y_0 + c_2 = 0
2. If `a_1 b_2 - a_2 b_1 = 0` and `a_1^2 + b_1^2 > 0`. In this case, the system in question becomes
.. math:: x'' = ax + by + c_1, y'' = k (ax + by) + c_2
2.1. If `\sigma = a + bk \neq 0`, the particular solution will be
.. math:: x = \frac{1}{2} b \sigma^{-1} (c_1 k - c_2) t^2 - \sigma^{-2} (a c_1 + b c_2)
.. math:: y = kx + \frac{1}{2} (c_2 - c_1 k) t^2
2.2. If `\sigma = a + bk = 0`, the particular solution will be
.. math:: x = \frac{1}{24} b (c_2 - c_1 k) t^4 + \frac{1}{2} c_1 t^2
.. math:: y = kx + \frac{1}{2} (c_2 - c_1 k) t^2
"""
x0, y0 = symbols('x0, y0')
if r['c1']*r['d2'] - r['c2']*r['d1'] != 0:
sol = solve((r['c1']*x0+r['d1']*y0+r['e1'], r['c2']*x0+r['d2']*y0+r['e2']), x0, y0)
psol = [sol[x0], sol[y0]]
elif r['c1']*r['d2'] - r['c2']*r['d1'] == 0 and (r['c1']**2 + r['d1']**2) > 0:
k = r['c2']/r['c1']
sig = r['c1'] + r['d1']*k
if sig != 0:
psol1 = r['d1']*sig**-1*(r['e1']*k-r['e2'])*t**2/2 - \
sig**-2*(r['c1']*r['e1']+r['d1']*r['e2'])
psol2 = k*psol1 + (r['e2'] - r['e1']*k)*t**2/2
psol = [psol1, psol2]
else:
psol1 = r['d1']*(r['e2']-r['e1']*k)*t**4/24 + r['e1']*t**2/2
psol2 = k*psol1 + (r['e2']-r['e1']*k)*t**2/2
psol = [psol1, psol2]
return psol
def _linear_2eq_order2_type3(x, y, t, r, eq):
r"""
These type of equation is used for describing the horizontal motion of a pendulum
taking into account the Earth rotation.
The solution is given with `a^2 + 4b > 0`:
.. math:: x = C_1 \cos(\alpha t) + C_2 \sin(\alpha t) + C_3 \cos(\beta t) + C_4 \sin(\beta t)
.. math:: y = -C_1 \sin(\alpha t) + C_2 \cos(\alpha t) - C_3 \sin(\beta t) + C_4 \cos(\beta t)
where `C_1,...,C_4` and
.. math:: \alpha = \frac{1}{2} a + \frac{1}{2} \sqrt{a^2 + 4b}, \beta = \frac{1}{2} a - \frac{1}{2} \sqrt{a^2 + 4b}
"""
C1, C2, C3, C4 = get_numbered_constants(eq, num=4)
if r['b1']**2 - 4*r['c1'] > 0:
r['a'] = r['b1'] ; r['b'] = -r['c1']
alpha = r['a']/2 + sqrt(r['a']**2 + 4*r['b'])/2
beta = r['a']/2 - sqrt(r['a']**2 + 4*r['b'])/2
sol1 = C1*cos(alpha*t) + C2*sin(alpha*t) + C3*cos(beta*t) + C4*sin(beta*t)
sol2 = -C1*sin(alpha*t) + C2*cos(alpha*t) - C3*sin(beta*t) + C4*cos(beta*t)
return [Eq(x(t), sol1), Eq(y(t), sol2)]
def _linear_2eq_order2_type4(x, y, t, r, eq):
r"""
These equations are found in the theory of oscillations
.. math:: x'' + a_1 x' + b_1 y' + c_1 x + d_1 y = k_1 e^{i \omega t}
.. math:: y'' + a_2 x' + b_2 y' + c_2 x + d_2 y = k_2 e^{i \omega t}
The general solution of this linear nonhomogeneous system of constant-coefficient
differential equations is given by the sum of its particular solution and the
general solution of the corresponding homogeneous system (with `k_1 = k_2 = 0`)
1. A particular solution is obtained by the method of undetermined coefficients:
.. math:: x = A_* e^{i \omega t}, y = B_* e^{i \omega t}
On substituting these expressions into the original system of differential equations,
one arrive at a linear nonhomogeneous system of algebraic equations for the
coefficients `A` and `B`.
2. The general solution of the homogeneous system of differential equations is determined
by a linear combination of linearly independent particular solutions determined by
the method of undetermined coefficients in the form of exponentials:
.. math:: x = A e^{\lambda t}, y = B e^{\lambda t}
On substituting these expressions into the original system and colleting the
coefficients of the unknown `A` and `B`, one obtains
.. math:: (\lambda^{2} + a_1 \lambda + c_1) A + (b_1 \lambda + d_1) B = 0
.. math:: (a_2 \lambda + c_2) A + (\lambda^{2} + b_2 \lambda + d_2) B = 0
The determinant of this system must vanish for nontrivial solutions A, B to exist.
This requirement results in the following characteristic equation for `\lambda`
.. math:: (\lambda^2 + a_1 \lambda + c_1) (\lambda^2 + b_2 \lambda + d_2) - (b_1 \lambda + d_1) (a_2 \lambda + c_2) = 0
If all roots `k_1,...,k_4` of this equation are distict, the general solution of the original
system of the differential equations has the form
.. math:: x = C_1 (b_1 \lambda_1 + d_1) e^{\lambda_1 t} - C_2 (b_1 \lambda_2 + d_1) e^{\lambda_2 t} - C_3 (b_1 \lambda_3 + d_1) e^{\lambda_3 t} - C_4 (b_1 \lambda_4 + d_1) e^{\lambda_4 t}
.. math:: y = C_1 (\lambda_1^{2} + a_1 \lambda_1 + c_1) e^{\lambda_1 t} + C_2 (\lambda_2^{2} + a_1 \lambda_2 + c_1) e^{\lambda_2 t} + C_3 (\lambda_3^{2} + a_1 \lambda_3 + c_1) e^{\lambda_3 t} + C_4 (\lambda_4^{2} + a_1 \lambda_4 + c_1) e^{\lambda_4 t}
"""
C1, C2, C3, C4 = get_numbered_constants(eq, num=4)
k = Symbol('k')
Ra, Ca, Rb, Cb = symbols('Ra, Ca, Rb, Cb')
a1 = r['a1'] ; a2 = r['a2']
b1 = r['b1'] ; b2 = r['b2']
c1 = r['c1'] ; c2 = r['c2']
d1 = r['d1'] ; d2 = r['d2']
k1 = r['e1'].expand().as_independent(t)[0]
k2 = r['e2'].expand().as_independent(t)[0]
ew1 = r['e1'].expand().as_independent(t)[1]
ew2 = powdenest(ew1).as_base_exp()[1]
ew3 = collect(ew2, t).coeff(t)
w = cancel(ew3/I)
# The particular solution is assumed to be (Ra+I*Ca)*exp(I*w*t) and
# (Rb+I*Cb)*exp(I*w*t) for x(t) and y(t) respectively
peq1 = (-w**2+c1)*Ra - a1*w*Ca + d1*Rb - b1*w*Cb - k1
peq2 = a1*w*Ra + (-w**2+c1)*Ca + b1*w*Rb + d1*Cb
peq3 = c2*Ra - a2*w*Ca + (-w**2+d2)*Rb - b2*w*Cb - k2
peq4 = a2*w*Ra + c2*Ca + b2*w*Rb + (-w**2+d2)*Cb
# FIXME: solve for what in what? Ra, Rb, etc I guess
# but then psol not used for anything?
psol = solve([peq1, peq2, peq3, peq4])
chareq = (k**2+a1*k+c1)*(k**2+b2*k+d2) - (b1*k+d1)*(a2*k+c2)
[k1, k2, k3, k4] = roots_quartic(Poly(chareq))
sol1 = -C1*(b1*k1+d1)*exp(k1*t) - C2*(b1*k2+d1)*exp(k2*t) - \
C3*(b1*k3+d1)*exp(k3*t) - C4*(b1*k4+d1)*exp(k4*t) + (Ra+I*Ca)*exp(I*w*t)
a1_ = (a1-1)
sol2 = C1*(k1**2+a1_*k1+c1)*exp(k1*t) + C2*(k2**2+a1_*k2+c1)*exp(k2*t) + \
C3*(k3**2+a1_*k3+c1)*exp(k3*t) + C4*(k4**2+a1_*k4+c1)*exp(k4*t) + (Rb+I*Cb)*exp(I*w*t)
return [Eq(x(t), sol1), Eq(y(t), sol2)]
def _linear_2eq_order2_type5(x, y, t, r, eq):
r"""
The equation which come under this catagory are
.. math:: x'' = a (t y' - y)
.. math:: y'' = b (t x' - x)
The transformation
.. math:: u = t x' - x, b = t y' - y
leads to the first-order system
.. math:: u' = atv, v' = btu
The general solution of this system is given by
If `ab > 0`:
.. math:: u = C_1 a e^{\frac{1}{2} \sqrt{ab} t^2} + C_2 a e^{-\frac{1}{2} \sqrt{ab} t^2}
.. math:: v = C_1 \sqrt{ab} e^{\frac{1}{2} \sqrt{ab} t^2} - C_2 \sqrt{ab} e^{-\frac{1}{2} \sqrt{ab} t^2}
If `ab < 0`:
.. math:: u = C_1 a \cos(\frac{1}{2} \sqrt{\left|ab\right|} t^2) + C_2 a \sin(-\frac{1}{2} \sqrt{\left|ab\right|} t^2)
.. math:: v = C_1 \sqrt{\left|ab\right|} \sin(\frac{1}{2} \sqrt{\left|ab\right|} t^2) + C_2 \sqrt{\left|ab\right|} \cos(-\frac{1}{2} \sqrt{\left|ab\right|} t^2)
where `C_1` and `C_2` are arbitary constants. On substituting the value of `u` and `v`
in above equations and integrating the resulting expressions, the general solution will become
.. math:: x = C_3 t + t \int \frac{u}{t^2} \,dt, y = C_4 t + t \int \frac{u}{t^2} \,dt
where `C_3` and `C_4` are arbitrary constants.
"""
C1, C2, C3, C4 = get_numbered_constants(eq, num=4)
r['a'] = -r['d1'] ; r['b'] = -r['c2']
mul = sqrt(abs(r['a']*r['b']))
if r['a']*r['b'] > 0:
u = C1*r['a']*exp(mul*t**2/2) + C2*r['a']*exp(-mul*t**2/2)
v = C1*mul*exp(mul*t**2/2) - C2*mul*exp(-mul*t**2/2)
else:
u = C1*r['a']*cos(mul*t**2/2) + C2*r['a']*sin(mul*t**2/2)
v = -C1*mul*sin(mul*t**2/2) + C2*mul*cos(mul*t**2/2)
sol1 = C3*t + t*Integral(u/t**2, t)
sol2 = C4*t + t*Integral(v/t**2, t)
return [Eq(x(t), sol1), Eq(y(t), sol2)]
def _linear_2eq_order2_type6(x, y, t, r, eq):
r"""
The equations are
.. math:: x'' = f(t) (a_1 x + b_1 y)
.. math:: y'' = f(t) (a_2 x + b_2 y)
If `k_1` and `k_2` are roots of the quadratic equation
.. math:: k^2 - (a_1 + b_2) k + a_1 b_2 - a_2 b_1 = 0
Then by multiplying appropriate constants and adding together original equations
we obtain two independent equations:
.. math:: z_1'' = k_1 f(t) z_1, z_1 = a_2 x + (k_1 - a_1) y
.. math:: z_2'' = k_2 f(t) z_2, z_2 = a_2 x + (k_2 - a_1) y
Solving the equations will give the values of `x` and `y` after obtaining the value
of `z_1` and `z_2` by solving the differential equation and substuting the result.
"""
C1, C2, C3, C4 = get_numbered_constants(eq, num=4)
k = Symbol('k')
z = Function('z')
num, den = cancel(
(r['c1']*x(t) + r['d1']*y(t))/
(r['c2']*x(t) + r['d2']*y(t))).as_numer_denom()
f = r['c1']/num.coeff(x(t))
a1 = num.coeff(x(t))
b1 = num.coeff(y(t))
a2 = den.coeff(x(t))
b2 = den.coeff(y(t))
chareq = k**2 - (a1 + b2)*k + a1*b2 - a2*b1
k1, k2 = [rootof(chareq, k) for k in range(Poly(chareq).degree())]
z1 = dsolve(diff(z(t),t,t) - k1*f*z(t)).rhs
z2 = dsolve(diff(z(t),t,t) - k2*f*z(t)).rhs
sol1 = (k1*z2 - k2*z1 + a1*(z1 - z2))/(a2*(k1-k2))
sol2 = (z1 - z2)/(k1 - k2)
return [Eq(x(t), sol1), Eq(y(t), sol2)]
def _linear_2eq_order2_type7(x, y, t, r, eq):
r"""
The equations are given as
.. math:: x'' = f(t) (a_1 x' + b_1 y')
.. math:: y'' = f(t) (a_2 x' + b_2 y')
If `k_1` and 'k_2` are roots of the quadratic equation
.. math:: k^2 - (a_1 + b_2) k + a_1 b_2 - a_2 b_1 = 0
Then the system can be reduced by adding together the two equations multiplied
by appropriate constants give following two independent equations:
.. math:: z_1'' = k_1 f(t) z_1', z_1 = a_2 x + (k_1 - a_1) y
.. math:: z_2'' = k_2 f(t) z_2', z_2 = a_2 x + (k_2 - a_1) y
Integrating these and returning to the original variables, one arrives at a linear
algebraic system for the unknowns `x` and `y`:
.. math:: a_2 x + (k_1 - a_1) y = C_1 \int e^{k_1 F(t)} \,dt + C_2
.. math:: a_2 x + (k_2 - a_1) y = C_3 \int e^{k_2 F(t)} \,dt + C_4
where `C_1,...,C_4` are arbitrary constants and `F(t) = \int f(t) \,dt`
"""
C1, C2, C3, C4 = get_numbered_constants(eq, num=4)
k = Symbol('k')
num, den = cancel(
(r['a1']*x(t) + r['b1']*y(t))/
(r['a2']*x(t) + r['b2']*y(t))).as_numer_denom()
f = r['a1']/num.coeff(x(t))
a1 = num.coeff(x(t))
b1 = num.coeff(y(t))
a2 = den.coeff(x(t))
b2 = den.coeff(y(t))
chareq = k**2 - (a1 + b2)*k + a1*b2 - a2*b1
[k1, k2] = [rootof(chareq, k) for k in range(Poly(chareq).degree())]
F = Integral(f, t)
z1 = C1*Integral(exp(k1*F), t) + C2
z2 = C3*Integral(exp(k2*F), t) + C4
sol1 = (k1*z2 - k2*z1 + a1*(z1 - z2))/(a2*(k1-k2))
sol2 = (z1 - z2)/(k1 - k2)
return [Eq(x(t), sol1), Eq(y(t), sol2)]
def _linear_2eq_order2_type8(x, y, t, r, eq):
r"""
The equation of this catagory are
.. math:: x'' = a f(t) (t y' - y)
.. math:: y'' = b f(t) (t x' - x)
The transformation
.. math:: u = t x' - x, v = t y' - y
leads to the system of first-order equations
.. math:: u' = a t f(t) v, v' = b t f(t) u
The general solution of this system has the form
If `ab > 0`:
.. math:: u = C_1 a e^{\sqrt{ab} \int t f(t) \,dt} + C_2 a e^{-\sqrt{ab} \int t f(t) \,dt}
.. math:: v = C_1 \sqrt{ab} e^{\sqrt{ab} \int t f(t) \,dt} - C_2 \sqrt{ab} e^{-\sqrt{ab} \int t f(t) \,dt}
If `ab < 0`:
.. math:: u = C_1 a \cos(\sqrt{\left|ab\right|} \int t f(t) \,dt) + C_2 a \sin(-\sqrt{\left|ab\right|} \int t f(t) \,dt)
.. math:: v = C_1 \sqrt{\left|ab\right|} \sin(\sqrt{\left|ab\right|} \int t f(t) \,dt) + C_2 \sqrt{\left|ab\right|} \cos(-\sqrt{\left|ab\right|} \int t f(t) \,dt)
where `C_1` and `C_2` are arbitary constants. On substituting the value of `u` and `v`
in above equations and integrating the resulting expressions, the general solution will become
.. math:: x = C_3 t + t \int \frac{u}{t^2} \,dt, y = C_4 t + t \int \frac{u}{t^2} \,dt
where `C_3` and `C_4` are arbitrary constants.
"""
C1, C2, C3, C4 = get_numbered_constants(eq, num=4)
num, den = cancel(r['d1']/r['c2']).as_numer_denom()
f = -r['d1']/num
a = num
b = den
mul = sqrt(abs(a*b))
Igral = Integral(t*f, t)
if a*b > 0:
u = C1*a*exp(mul*Igral) + C2*a*exp(-mul*Igral)
v = C1*mul*exp(mul*Igral) - C2*mul*exp(-mul*Igral)
else:
u = C1*a*cos(mul*Igral) + C2*a*sin(mul*Igral)
v = -C1*mul*sin(mul*Igral) + C2*mul*cos(mul*Igral)
sol1 = C3*t + t*Integral(u/t**2, t)
sol2 = C4*t + t*Integral(v/t**2, t)
return [Eq(x(t), sol1), Eq(y(t), sol2)]
def _linear_2eq_order2_type9(x, y, t, r, eq):
r"""
.. math:: t^2 x'' + a_1 t x' + b_1 t y' + c_1 x + d_1 y = 0
.. math:: t^2 y'' + a_2 t x' + b_2 t y' + c_2 x + d_2 y = 0
These system of equations are euler type.
The substitution of `t = \sigma e^{\tau} (\sigma \neq 0)` leads to the system of constant
coefficient linear differential equations
.. math:: x'' + (a_1 - 1) x' + b_1 y' + c_1 x + d_1 y = 0
.. math:: y'' + a_2 x' + (b_2 - 1) y' + c_2 x + d_2 y = 0
The general solution of the homogeneous system of differential equations is determined
by a linear combination of linearly independent particular solutions determined by
the method of undetermined coefficients in the form of exponentials
.. math:: x = A e^{\lambda t}, y = B e^{\lambda t}
On substituting these expressions into the original system and colleting the
coefficients of the unknown `A` and `B`, one obtains
.. math:: (\lambda^{2} + (a_1 - 1) \lambda + c_1) A + (b_1 \lambda + d_1) B = 0
.. math:: (a_2 \lambda + c_2) A + (\lambda^{2} + (b_2 - 1) \lambda + d_2) B = 0
The determinant of this system must vanish for nontrivial solutions A, B to exist.
This requirement results in the following characteristic equation for `\lambda`
.. math:: (\lambda^2 + (a_1 - 1) \lambda + c_1) (\lambda^2 + (b_2 - 1) \lambda + d_2) - (b_1 \lambda + d_1) (a_2 \lambda + c_2) = 0
If all roots `k_1,...,k_4` of this equation are distict, the general solution of the original
system of the differential equations has the form
.. math:: x = C_1 (b_1 \lambda_1 + d_1) e^{\lambda_1 t} - C_2 (b_1 \lambda_2 + d_1) e^{\lambda_2 t} - C_3 (b_1 \lambda_3 + d_1) e^{\lambda_3 t} - C_4 (b_1 \lambda_4 + d_1) e^{\lambda_4 t}
.. math:: y = C_1 (\lambda_1^{2} + (a_1 - 1) \lambda_1 + c_1) e^{\lambda_1 t} + C_2 (\lambda_2^{2} + (a_1 - 1) \lambda_2 + c_1) e^{\lambda_2 t} + C_3 (\lambda_3^{2} + (a_1 - 1) \lambda_3 + c_1) e^{\lambda_3 t} + C_4 (\lambda_4^{2} + (a_1 - 1) \lambda_4 + c_1) e^{\lambda_4 t}
"""
C1, C2, C3, C4 = get_numbered_constants(eq, num=4)
k = Symbol('k')
a1 = -r['a1']*t; a2 = -r['a2']*t
b1 = -r['b1']*t; b2 = -r['b2']*t
c1 = -r['c1']*t**2; c2 = -r['c2']*t**2
d1 = -r['d1']*t**2; d2 = -r['d2']*t**2
eq = (k**2+(a1-1)*k+c1)*(k**2+(b2-1)*k+d2)-(b1*k+d1)*(a2*k+c2)
[k1, k2, k3, k4] = roots_quartic(Poly(eq))
sol1 = -C1*(b1*k1+d1)*exp(k1*log(t)) - C2*(b1*k2+d1)*exp(k2*log(t)) - \
C3*(b1*k3+d1)*exp(k3*log(t)) - C4*(b1*k4+d1)*exp(k4*log(t))
a1_ = (a1-1)
sol2 = C1*(k1**2+a1_*k1+c1)*exp(k1*log(t)) + C2*(k2**2+a1_*k2+c1)*exp(k2*log(t)) \
+ C3*(k3**2+a1_*k3+c1)*exp(k3*log(t)) + C4*(k4**2+a1_*k4+c1)*exp(k4*log(t))
return [Eq(x(t), sol1), Eq(y(t), sol2)]
def _linear_2eq_order2_type10(x, y, t, r, eq):
r"""
The equation of this catagory are
.. math:: (\alpha t^2 + \beta t + \gamma)^{2} x'' = ax + by
.. math:: (\alpha t^2 + \beta t + \gamma)^{2} y'' = cx + dy
The transformation
.. math:: \tau = \int \frac{1}{\alpha t^2 + \beta t + \gamma} \,dt , u = \frac{x}{\sqrt{\left|\alpha t^2 + \beta t + \gamma\right|}} , v = \frac{y}{\sqrt{\left|\alpha t^2 + \beta t + \gamma\right|}}
leads to a constant coefficient linear system of equations
.. math:: u'' = (a - \alpha \gamma + \frac{1}{4} \beta^{2}) u + b v
.. math:: v'' = c u + (d - \alpha \gamma + \frac{1}{4} \beta^{2}) v
These system of equations obtained can be solved by type1 of System of two
constant-coefficient second-order linear homogeneous differential equations.
"""
C1, C2, C3, C4 = get_numbered_constants(eq, num=4)
u, v = symbols('u, v', function=True)
T = Symbol('T')
p = Wild('p', exclude=[t, t**2])
q = Wild('q', exclude=[t, t**2])
s = Wild('s', exclude=[t, t**2])
n = Wild('n', exclude=[t, t**2])
num, den = r['c1'].as_numer_denom()
dic = den.match((n*(p*t**2+q*t+s)**2).expand())
eqz = dic[p]*t**2 + dic[q]*t + dic[s]
a = num/dic[n]
b = cancel(r['d1']*eqz**2)
c = cancel(r['c2']*eqz**2)
d = cancel(r['d2']*eqz**2)
[msol1, msol2] = dsolve([Eq(diff(u(t), t, t), (a - dic[p]*dic[s] + dic[q]**2/4)*u(t) \
+ b*v(t)), Eq(diff(v(t),t,t), c*u(t) + (d - dic[p]*dic[s] + dic[q]**2/4)*v(t))])
sol1 = (msol1.rhs*sqrt(abs(eqz))).subs(t, Integral(1/eqz, t))
sol2 = (msol2.rhs*sqrt(abs(eqz))).subs(t, Integral(1/eqz, t))
return [Eq(x(t), sol1), Eq(y(t), sol2)]
def _linear_2eq_order2_type11(x, y, t, r, eq):
r"""
The equations which comes under this type are
.. math:: x'' = f(t) (t x' - x) + g(t) (t y' - y)
.. math:: y'' = h(t) (t x' - x) + p(t) (t y' - y)
The transformation
.. math:: u = t x' - x, v = t y' - y
leads to the linear system of first-order equations
.. math:: u' = t f(t) u + t g(t) v, v' = t h(t) u + t p(t) v
On substituting the value of `u` and `v` in transformed equation gives value of `x` and `y` as
.. math:: x = C_3 t + t \int \frac{u}{t^2} \,dt , y = C_4 t + t \int \frac{v}{t^2} \,dt.
where `C_3` and `C_4` are arbitrary constants.
"""
C1, C2, C3, C4 = get_numbered_constants(eq, num=4)
u, v = symbols('u, v', function=True)
f = -r['c1'] ; g = -r['d1']
h = -r['c2'] ; p = -r['d2']
[msol1, msol2] = dsolve([Eq(diff(u(t),t), t*f*u(t) + t*g*v(t)), Eq(diff(v(t),t), t*h*u(t) + t*p*v(t))])
sol1 = C3*t + t*Integral(msol1.rhs/t**2, t)
sol2 = C4*t + t*Integral(msol2.rhs/t**2, t)
return [Eq(x(t), sol1), Eq(y(t), sol2)]
def sysode_linear_3eq_order1(match_):
x = match_['func'][0].func
y = match_['func'][1].func
z = match_['func'][2].func
func = match_['func']
fc = match_['func_coeff']
eq = match_['eq']
C1, C2, C3, C4 = get_numbered_constants(eq, num=4)
r = dict()
t = list(list(eq[0].atoms(Derivative))[0].atoms(Symbol))[0]
for i in range(3):
eqs = 0
for terms in Add.make_args(eq[i]):
eqs += terms/fc[i,func[i],1]
eq[i] = eqs
# for equations:
# Eq(g1*diff(x(t),t), a1*x(t)+b1*y(t)+c1*z(t)+d1),
# Eq(g2*diff(y(t),t), a2*x(t)+b2*y(t)+c2*z(t)+d2), and
# Eq(g3*diff(z(t),t), a3*x(t)+b3*y(t)+c3*z(t)+d3)
r['a1'] = fc[0,x(t),0]/fc[0,x(t),1]; r['a2'] = fc[1,x(t),0]/fc[1,y(t),1];
r['a3'] = fc[2,x(t),0]/fc[2,z(t),1]
r['b1'] = fc[0,y(t),0]/fc[0,x(t),1]; r['b2'] = fc[1,y(t),0]/fc[1,y(t),1];
r['b3'] = fc[2,y(t),0]/fc[2,z(t),1]
r['c1'] = fc[0,z(t),0]/fc[0,x(t),1]; r['c2'] = fc[1,z(t),0]/fc[1,y(t),1];
r['c3'] = fc[2,z(t),0]/fc[2,z(t),1]
for i in range(3):
for j in Add.make_args(eq[i]):
if not j.has(x(t), y(t), z(t)):
raise NotImplementedError("Only homogeneous problems are supported, non-homogenous are not supported currently.")
if match_['type_of_equation'] == 'type1':
sol = _linear_3eq_order1_type1(x, y, z, t, r, eq)
if match_['type_of_equation'] == 'type2':
sol = _linear_3eq_order1_type2(x, y, z, t, r, eq)
if match_['type_of_equation'] == 'type3':
sol = _linear_3eq_order1_type3(x, y, z, t, r, eq)
if match_['type_of_equation'] == 'type4':
sol = _linear_3eq_order1_type4(x, y, z, t, r, eq)
if match_['type_of_equation'] == 'type6':
sol = _linear_neq_order1_type1(match_)
return sol
def _linear_3eq_order1_type1(x, y, z, t, r, eq):
r"""
.. math:: x' = ax
.. math:: y' = bx + cy
.. math:: z' = dx + ky + pz
Solution of such equations are forward substitution. Solving first equations
gives the value of `x`, substituting it in second and third equation and
solving second equation gives `y` and similarly substituting `y` in third
equation give `z`.
.. math:: x = C_1 e^{at}
.. math:: y = \frac{b C_1}{a - c} e^{at} + C_2 e^{ct}
.. math:: z = \frac{C_1}{a - p} (d + \frac{bk}{a - c}) e^{at} + \frac{k C_2}{c - p} e^{ct} + C_3 e^{pt}
where `C_1, C_2` and `C_3` are arbitrary constants.
"""
C1, C2, C3, C4 = get_numbered_constants(eq, num=4)
a = -r['a1']; b = -r['a2']; c = -r['b2']
d = -r['a3']; k = -r['b3']; p = -r['c3']
sol1 = C1*exp(a*t)
sol2 = b*C1*exp(a*t)/(a-c) + C2*exp(c*t)
sol3 = C1*(d+b*k/(a-c))*exp(a*t)/(a-p) + k*C2*exp(c*t)/(c-p) + C3*exp(p*t)
return [Eq(x(t), sol1), Eq(y(t), sol2), Eq(z(t), sol3)]
def _linear_3eq_order1_type2(x, y, z, t, r, eq):
r"""
The equations of this type are
.. math:: x' = cy - bz
.. math:: y' = az - cx
.. math:: z' = bx - ay
1. First integral:
.. math:: ax + by + cz = A \qquad - (1)
.. math:: x^2 + y^2 + z^2 = B^2 \qquad - (2)
where `A` and `B` are arbitrary constants. It follows from these integrals
that the integral lines are circles formed by the intersection of the planes
`(1)` and sphere `(2)`
2. Solution:
.. math:: x = a C_0 + k C_1 \cos(kt) + (c C_2 - b C_3) \sin(kt)
.. math:: y = b C_0 + k C_2 \cos(kt) + (a C_2 - c C_3) \sin(kt)
.. math:: z = c C_0 + k C_3 \cos(kt) + (b C_2 - a C_3) \sin(kt)
where `k = \sqrt{a^2 + b^2 + c^2}` and the four constants of integration,
`C_1,...,C_4` are constrained by a single relation,
.. math:: a C_1 + b C_2 + c C_3 = 0
"""
C0, C1, C2, C3 = get_numbered_constants(eq, num=4, start=0)
a = -r['c2']; b = -r['a3']; c = -r['b1']
k = sqrt(a**2 + b**2 + c**2)
C3 = (-a*C1 - b*C2)/c
sol1 = a*C0 + k*C1*cos(k*t) + (c*C2-b*C3)*sin(k*t)
sol2 = b*C0 + k*C2*cos(k*t) + (a*C3-c*C1)*sin(k*t)
sol3 = c*C0 + k*C3*cos(k*t) + (b*C1-a*C2)*sin(k*t)
return [Eq(x(t), sol1), Eq(y(t), sol2), Eq(z(t), sol3)]
def _linear_3eq_order1_type3(x, y, z, t, r, eq):
r"""
Equations of this system of ODEs
.. math:: a x' = bc (y - z)
.. math:: b y' = ac (z - x)
.. math:: c z' = ab (x - y)
1. First integral:
.. math:: a^2 x + b^2 y + c^2 z = A
where A is an arbitary constant. It follows that the integral lines are plane curves.
2. Solution:
.. math:: x = C_0 + k C_1 \cos(kt) + a^{-1} bc (C_2 - C_3) \sin(kt)
.. math:: y = C_0 + k C_2 \cos(kt) + a b^{-1} c (C_3 - C_1) \sin(kt)
.. math:: z = C_0 + k C_3 \cos(kt) + ab c^{-1} (C_1 - C_2) \sin(kt)
where `k = \sqrt{a^2 + b^2 + c^2}` and the four constants of integration,
`C_1,...,C_4` are constrained by a single relation
.. math:: a^2 C_1 + b^2 C_2 + c^2 C_3 = 0
"""
C0, C1, C2, C3 = get_numbered_constants(eq, num=4, start=0)
c = sqrt(r['b1']*r['c2'])
b = sqrt(r['b1']*r['a3'])
a = sqrt(r['c2']*r['a3'])
C3 = (-a**2*C1-b**2*C2)/c**2
k = sqrt(a**2 + b**2 + c**2)
sol1 = C0 + k*C1*cos(k*t) + a**-1*b*c*(C2-C3)*sin(k*t)
sol2 = C0 + k*C2*cos(k*t) + a*b**-1*c*(C3-C1)*sin(k*t)
sol3 = C0 + k*C3*cos(k*t) + a*b*c**-1*(C1-C2)*sin(k*t)
return [Eq(x(t), sol1), Eq(y(t), sol2), Eq(z(t), sol3)]
def _linear_3eq_order1_type4(x, y, z, t, r, eq):
r"""
Equations:
.. math:: x' = (a_1 f(t) + g(t)) x + a_2 f(t) y + a_3 f(t) z
.. math:: y' = b_1 f(t) x + (b_2 f(t) + g(t)) y + b_3 f(t) z
.. math:: z' = c_1 f(t) x + c_2 f(t) y + (c_3 f(t) + g(t)) z
The transformation
.. math:: x = e^{\int g(t) \,dt} u, y = e^{\int g(t) \,dt} v, z = e^{\int g(t) \,dt} w, \tau = \int f(t) \,dt
leads to the system of constant coefficient linear differential equations
.. math:: u' = a_1 u + a_2 v + a_3 w
.. math:: v' = b_1 u + b_2 v + b_3 w
.. math:: w' = c_1 u + c_2 v + c_3 w
These system of equations are solved by homogeneous linear system of constant
coefficients of `n` equations of first order. Then substituting the value of
`u, v` and `w` in transformed equation gives value of `x, y` and `z`.
"""
u, v, w = symbols('u, v, w', function=True)
a2, a3 = cancel(r['b1']/r['c1']).as_numer_denom()
f = cancel(r['b1']/a2)
b1 = cancel(r['a2']/f); b3 = cancel(r['c2']/f)
c1 = cancel(r['a3']/f); c2 = cancel(r['b3']/f)
a1, g = div(r['a1'],f)
b2 = div(r['b2'],f)[0]
c3 = div(r['c3'],f)[0]
trans_eq = (diff(u(t),t)-a1*u(t)-a2*v(t)-a3*w(t), diff(v(t),t)-b1*u(t)-\
b2*v(t)-b3*w(t), diff(w(t),t)-c1*u(t)-c2*v(t)-c3*w(t))
sol = dsolve(trans_eq)
sol1 = exp(Integral(g,t))*((sol[0].rhs).subs(t, Integral(f,t)))
sol2 = exp(Integral(g,t))*((sol[1].rhs).subs(t, Integral(f,t)))
sol3 = exp(Integral(g,t))*((sol[2].rhs).subs(t, Integral(f,t)))
return [Eq(x(t), sol1), Eq(y(t), sol2), Eq(z(t), sol3)]
def sysode_linear_neq_order1(match_):
sol = _linear_neq_order1_type1(match_)
def _linear_neq_order1_type1(match_):
r"""
System of n first-order constant-coefficient linear nonhomogeneous differential equation
.. math:: y'_k = a_{k1} y_1 + a_{k2} y_2 +...+ a_{kn} y_n; k = 1,2,...,n
or that can be written as `\vec{y'} = A . \vec{y}`
where `\vec{y}` is matrix of `y_k` for `k = 1,2,...n` and `A` is a `n \times n` matrix.
Since these equations are equivalent to a first order homogeneous linear
differential equation. So the general solution will contain `n` linearly
independent parts and solution will consist some type of exponential
functions. Assuming `y = \vec{v} e^{rt}` is a solution of the system where
`\vec{v}` is a vector of coefficients of `y_1,...,y_n`. Substituting `y` and
`y' = r v e^{r t}` into the equation `\vec{y'} = A . \vec{y}`, we get
.. math:: r \vec{v} e^{rt} = A \vec{v} e^{rt}
.. math:: r \vec{v} = A \vec{v}
where `r` comes out to be eigenvalue of `A` and vector `\vec{v}` is the eigenvector
of `A` corresponding to `r`. There are three possiblities of eigenvalues of `A`
- `n` distinct real eigenvalues
- complex conjugate eigenvalues
- eigenvalues with multiplicity `k`
1. When all eigenvalues `r_1,..,r_n` are distinct with `n` different eigenvectors
`v_1,...v_n` then the solution is given by
.. math:: \vec{y} = C_1 e^{r_1 t} \vec{v_1} + C_2 e^{r_2 t} \vec{v_2} +...+ C_n e^{r_n t} \vec{v_n}
where `C_1,C_2,...,C_n` are arbitrary constants.
2. When some eigenvalues are complex then in order to make the solution real,
we take a llinear combination: if `r = a + bi` has an eigenvector
`\vec{v} = \vec{w_1} + i \vec{w_2}` then to obtain real-valued solutions to
the system, replace the complex-valued solutions `e^{rx} \vec{v}`
with real-valued solution `e^{ax} (\vec{w_1} \cos(bx) - \vec{w_2} \sin(bx))`
and for `r = a - bi` replace the solution `e^{-r x} \vec{v}` with
`e^{ax} (\vec{w_1} \sin(bx) + \vec{w_2} \cos(bx))`
3. If some eigenvalues are repeated. Then we get fewer than `n` linearly
independent eigenvectors, we miss some of the solutions and need to
construct the missing ones. We do this via generalized eigenvectors, vectors
which are not eigenvectors but are close enough that we can use to write
down the remaining solutions. For a eigenvalue `r` with eigenvector `\vec{w}`
we obtain `\vec{w_2},...,\vec{w_k}` using
.. math:: (A - r I) . \vec{w_2} = \vec{w}
.. math:: (A - r I) . \vec{w_3} = \vec{w_2}
.. math:: \vdots
.. math:: (A - r I) . \vec{w_k} = \vec{w_{k-1}}
Then the solutions to the system for the eigenspace are `e^{rt} [\vec{w}],
e^{rt} [t \vec{w} + \vec{w_2}], e^{rt} [\frac{t^2}{2} \vec{w} + t \vec{w_2} + \vec{w_3}],
...,e^{rt} [\frac{t^{k-1}}{(k-1)!} \vec{w} + \frac{t^{k-2}}{(k-2)!} \vec{w_2} +...+ t \vec{w_{k-1}}
+ \vec{w_k}]`
So, If `\vec{y_1},...,\vec{y_n}` are `n` solution of obtained from three
categories of `A`, then general solution to the system `\vec{y'} = A . \vec{y}`
.. math:: \vec{y} = C_1 \vec{y_1} + C_2 \vec{y_2} + \cdots + C_n \vec{y_n}
"""
eq = match_['eq']
func = match_['func']
fc = match_['func_coeff']
n = len(eq)
t = list(list(eq[0].atoms(Derivative))[0].atoms(Symbol))[0]
constants = numbered_symbols(prefix='C', cls=Symbol, start=1)
M = Matrix(n,n,lambda i,j:-fc[i,func[j],0])
evector = M.eigenvects(simplify=True)
def is_complex(mat, root):
return Matrix(n, 1, lambda i,j: re(mat[i])*cos(im(root)*t) - im(mat[i])*sin(im(root)*t))
def is_complex_conjugate(mat, root):
return Matrix(n, 1, lambda i,j: re(mat[i])*sin(abs(im(root))*t) + im(mat[i])*cos(im(root)*t)*abs(im(root))/im(root))
conjugate_root = []
e_vector = zeros(n,1)
for evects in evector:
if evects[0] not in conjugate_root:
# If number of column of an eigenvector is not equal to the multiplicity
# of its eigenvalue then the legt eigenvectors are calculated
if len(evects[2])!=evects[1]:
var_mat = Matrix(n, 1, lambda i,j: Symbol('x'+str(i)))
Mnew = (M - evects[0]*eye(evects[2][-1].rows))*var_mat
w = [0 for i in range(evects[1])]
w[0] = evects[2][-1]
for r in range(1, evects[1]):
w_ = Mnew - w[r-1]
sol_dict = solve(list(w_), var_mat[1:])
sol_dict[var_mat[0]] = var_mat[0]
for key, value in sol_dict.items():
sol_dict[key] = value.subs(var_mat[0],1)
w[r] = Matrix(n, 1, lambda i,j: sol_dict[var_mat[i]])
evects[2].append(w[r])
for i in range(evects[1]):
C = next(constants)
for j in range(i+1):
if evects[0].has(I):
evects[2][j] = simplify(evects[2][j])
e_vector += C*is_complex(evects[2][j], evects[0])*t**(i-j)*exp(re(evects[0])*t)/factorial(i-j)
C = next(constants)
e_vector += C*is_complex_conjugate(evects[2][j], evects[0])*t**(i-j)*exp(re(evects[0])*t)/factorial(i-j)
else:
e_vector += C*evects[2][j]*t**(i-j)*exp(evects[0]*t)/factorial(i-j)
if evects[0].has(I):
conjugate_root.append(conjugate(evects[0]))
sol = []
for i in range(len(eq)):
sol.append(Eq(func[i],e_vector[i]))
return sol
def sysode_nonlinear_2eq_order1(match_):
func = match_['func']
eq = match_['eq']
fc = match_['func_coeff']
t = list(list(eq[0].atoms(Derivative))[0].atoms(Symbol))[0]
if match_['type_of_equation'] == 'type5':
sol = _nonlinear_2eq_order1_type5(func, t, eq)
return sol
x = func[0].func
y = func[1].func
for i in range(2):
eqs = 0
for terms in Add.make_args(eq[i]):
eqs += terms/fc[i,func[i],1]
eq[i] = eqs
if match_['type_of_equation'] == 'type1':
sol = _nonlinear_2eq_order1_type1(x, y, t, eq)
elif match_['type_of_equation'] == 'type2':
sol = _nonlinear_2eq_order1_type2(x, y, t, eq)
elif match_['type_of_equation'] == 'type3':
sol = _nonlinear_2eq_order1_type3(x, y, t, eq)
elif match_['type_of_equation'] == 'type4':
sol = _nonlinear_2eq_order1_type4(x, y, t, eq)
return sol
def _nonlinear_2eq_order1_type1(x, y, t, eq):
r"""
Equations:
.. math:: x' = x^n F(x,y)
.. math:: y' = g(y) F(x,y)
Solution:
.. math:: x = \varphi(y), \int \frac{1}{g(y) F(\varphi(y),y)} \,dy = t + C_2
where
if `n \neq 1`
.. math:: \varphi = [C_1 + (1-n) \int \frac{1}{g(y)} \,dy]^{\frac{1}{1-n}}
if `n = 1`
.. math:: \varphi = C_1 e^{\int \frac{1}{g(y)} \,dy}
where `C_1` and `C_2` are arbitrary constants.
"""
C1, C2 = get_numbered_constants(eq, num=2)
n = Wild('n', exclude=[x(t),y(t)])
f = Wild('f')
u, v, phi = symbols('u, v, phi', function=True)
r = eq[0].match(diff(x(t),t) - x(t)**n*f)
g = ((diff(y(t),t) - eq[1])/r[f]).subs(y(t),v)
F = r[f].subs(x(t),u).subs(y(t),v)
n = r[n]
if n!=1:
phi = (C1 + (1-n)*Integral(1/g, v))**(1/(1-n))
else:
phi = C1*exp(Integral(1/g, v))
phi = phi.doit()
sol2 = solve(Integral(1/(g*F.subs(u,phi)), v).doit() - t - C2, v)
sol = []
for sols in sol2:
sol.append(Eq(x(t),phi.subs(v, sols)))
sol.append(Eq(y(t), sols))
return sol
def _nonlinear_2eq_order1_type2(x, y, t, eq):
r"""
Equations:
.. math:: x' = e^{\lambda x} F(x,y)
.. math:: y' = g(y) F(x,y)
Solution:
.. math:: x = \varphi(y), \int \frac{1}{g(y) F(\varphi(y),y)} \,dy = t + C_2
where
if `\lambda \neq 0`
.. math:: \varphi = -\frac{1}{\lambda} log(C_1 - \lambda \int \frac{1}{g(y)} \,dy)
if `\lambda = 0`
.. math:: \varphi = C_1 + \int \frac{1}{g(y)} \,dy
where `C_1` and `C_2` are arbitrary constants.
"""
C1, C2 = get_numbered_constants(eq, num=2)
n = Wild('n', exclude=[x(t),y(t)])
f = Wild('f')
u, v, phi = symbols('u, v, phi', function=True)
r = eq[0].match(diff(x(t),t) - exp(n*x(t))*f)
g = ((diff(y(t),t) - eq[1])/r[f]).subs(y(t),v)
F = r[f].subs(x(t),u).subs(y(t),v)
n = r[n]
if n:
phi = -1/n*log(C1 - n*Integral(1/g, v))
else:
phi = C1 + Integral(1/g, v)
phi = phi.doit()
sol2 = solve(Integral(1/(g*F.subs(u,phi)), v).doit() - t - C2, v)
sol = []
for sols in sol2:
sol.append(Eq(x(t),phi.subs(v, sols)))
sol.append(Eq(y(t), sols))
return sol
def _nonlinear_2eq_order1_type3(x, y, t, eq):
r"""
Autonomous system of general form
.. math:: x' = F(x,y)
.. math:: y' = G(x,y)
Assuming `y = y(x, C_1)` where `C_1` is an arbitrary constant is the general
solution of the first-order equation
.. math:: F(x,y) y'_x = G(x,y)
Then the general solution of the original system of equations has the form
.. math:: \int \frac{1}{F(x,y(x,C_1))} \,dx = t + C_1
"""
C1, C2, C3, C4 = get_numbered_constants(eq, num=4)
u, v = symbols('u, v', function=True)
f = Wild('f')
g = Wild('g')
r1 = eq[0].match(diff(x(t),t) - f)
r2 = eq[1].match(diff(y(t),t) - g)
F = r1[f].subs(x(t),u).subs(y(t),v)
G = r2[g].subs(x(t),u).subs(y(t),v)
sol2r = dsolve(Eq(diff(v(u),u), G.subs(v,v(u))/F.subs(v,v(u))))
for sol2s in sol2r:
sol1 = solve(Integral(1/F.subs(v, sol2s.rhs), u).doit() - t - C2, u)
sol = []
for sols in sol1:
sol.append(Eq(x(t), sols))
sol.append(Eq(y(t), (sol2s.rhs).subs(u, sols)))
return sol
def _nonlinear_2eq_order1_type4(x, y, t, eq):
r"""
Equation:
.. math:: x' = f_1(x) g_1(y) \phi(x,y,t)
.. math:: y' = f_2(x) g_2(y) \phi(x,y,t)
First integral:
.. math:: \int \frac{f_2(x)}{f_1(x)} \,dx - \int \frac{g_1(y)}{g_2(y)} \,dy = C
where `C` is an arbitrary constant.
On solving the first integral for `x` (resp., `y` ) and on substituting the
resulting expression into either equation of the original solution, one
arrives at a firs-order equation for determining `y` (resp., `x` ).
"""
C1, C2 = get_numbered_constants(eq, num=2)
u, v = symbols('u, v')
f = Wild('f')
g = Wild('g')
f1 = Wild('f1', exclude=[v,t])
f2 = Wild('f2', exclude=[v,t])
g1 = Wild('g1', exclude=[u,t])
g2 = Wild('g2', exclude=[u,t])
r1 = eq[0].match(diff(x(t),t) - f)
r2 = eq[1].match(diff(y(t),t) - g)
num, den = (
(r1[f].subs(x(t),u).subs(y(t),v))/
(r2[g].subs(x(t),u).subs(y(t),v))).as_numer_denom()
R1 = num.match(f1*g1)
R2 = den.match(f2*g2)
phi = (r1[f].subs(x(t),u).subs(y(t),v))/num
F1 = R1[f1]; F2 = R2[f2]
G1 = R1[g1]; G2 = R2[g2]
sol1r = solve(Integral(F2/F1, u).doit() - Integral(G1/G2,v).doit() - C1, u)
sol2r = solve(Integral(F2/F1, u).doit() - Integral(G1/G2,v).doit() - C1, v)
sol = []
for sols in sol1r:
sol.append(Eq(y(t), dsolve(diff(v(t),t) - F2.subs(u,sols).subs(v,v(t))*G2.subs(v,v(t))*phi.subs(u,sols).subs(v,v(t))).rhs))
for sols in sol2r:
sol.append(Eq(x(t), dsolve(diff(u(t),t) - F1.subs(u,u(t))*G1.subs(v,sols).subs(u,u(t))*phi.subs(v,sols).subs(u,u(t))).rhs))
return set(sol)
def _nonlinear_2eq_order1_type5(func, t, eq):
r"""
Clairaut system of ODEs
.. math:: x = t x' + F(x',y')
.. math:: y = t y' + G(x',y')
The following are solutions of the system
`(i)` straight lines:
.. math:: x = C_1 t + F(C_1, C_2), y = C_2 t + G(C_1, C_2)
where `C_1` and `C_2` are arbitrary constants;
`(ii)` envelopes of the above lines;
`(iii)` continuously differentiable lines made up from segments of the lines
`(i)` and `(ii)`.
"""
C1, C2 = get_numbered_constants(eq, num=2)
f = Wild('f')
g = Wild('g')
def check_type(x, y):
r1 = eq[0].match(t*diff(x(t),t) - x(t) + f)
r2 = eq[1].match(t*diff(y(t),t) - y(t) + g)
if not (r1 and r2):
r1 = eq[0].match(diff(x(t),t) - x(t)/t + f/t)
r2 = eq[1].match(diff(y(t),t) - y(t)/t + g/t)
if not (r1 and r2):
r1 = (-eq[0]).match(t*diff(x(t),t) - x(t) + f)
r2 = (-eq[1]).match(t*diff(y(t),t) - y(t) + g)
if not (r1 and r2):
r1 = (-eq[0]).match(diff(x(t),t) - x(t)/t + f/t)
r2 = (-eq[1]).match(diff(y(t),t) - y(t)/t + g/t)
return [r1, r2]
for func_ in func:
if isinstance(func_, list):
x = func[0][0].func
y = func[0][1].func
[r1, r2] = check_type(x, y)
if not (r1 and r2):
[r1, r2] = check_type(y, x)
x, y = y, x
x1 = diff(x(t),t); y1 = diff(y(t),t)
return {Eq(x(t), C1*t + r1[f].subs(x1,C1).subs(y1,C2)), Eq(y(t), C2*t + r2[g].subs(x1,C1).subs(y1,C2))}
def sysode_nonlinear_3eq_order1(match_):
x = match_['func'][0].func
y = match_['func'][1].func
z = match_['func'][2].func
eq = match_['eq']
fc = match_['func_coeff']
func = match_['func']
t = list(list(eq[0].atoms(Derivative))[0].atoms(Symbol))[0]
if match_['type_of_equation'] == 'type1':
sol = _nonlinear_3eq_order1_type1(x, y, z, t, eq)
if match_['type_of_equation'] == 'type2':
sol = _nonlinear_3eq_order1_type2(x, y, z, t, eq)
if match_['type_of_equation'] == 'type3':
sol = _nonlinear_3eq_order1_type3(x, y, z, t, eq)
if match_['type_of_equation'] == 'type4':
sol = _nonlinear_3eq_order1_type4(x, y, z, t, eq)
if match_['type_of_equation'] == 'type5':
sol = _nonlinear_3eq_order1_type5(x, y, z, t, eq)
return sol
def _nonlinear_3eq_order1_type1(x, y, z, t, eq):
r"""
Equations:
.. math:: a x' = (b - c) y z, \enspace b y' = (c - a) z x, \enspace c z' = (a - b) x y
First Integrals:
.. math:: a x^{2} + b y^{2} + c z^{2} = C_1
.. math:: a^{2} x^{2} + b^{2} y^{2} + c^{2} z^{2} = C_2
where `C_1` and `C_2` are arbitrary constants. On solving the integrals for `y` and
`z` and on substituting the resulting expressions into the first equation of the
system, we arrives at a separable first-order equation on `x`. Similarly doing that
for other two equations, we will arrive at first order equation on `y` and `z` too.
References
==========
-http://eqworld.ipmnet.ru/en/solutions/sysode/sode0401.pdf
"""
C1, C2 = get_numbered_constants(eq, num=2)
u, v, w = symbols('u, v, w')
p = Wild('p', exclude=[x(t), y(t), z(t), t])
q = Wild('q', exclude=[x(t), y(t), z(t), t])
s = Wild('s', exclude=[x(t), y(t), z(t), t])
r = (diff(x(t),t) - eq[0]).match(p*y(t)*z(t))
r.update((diff(y(t),t) - eq[1]).match(q*z(t)*x(t)))
r.update((diff(z(t),t) - eq[2]).match(s*x(t)*y(t)))
n1, d1 = r[p].as_numer_denom()
n2, d2 = r[q].as_numer_denom()
n3, d3 = r[s].as_numer_denom()
val = solve([n1*u-d1*v+d1*w, d2*u+n2*v-d2*w, d3*u-d3*v-n3*w],[u,v])
vals = [val[v], val[u]]
c = lcm(vals[0].as_numer_denom()[1], vals[1].as_numer_denom()[1])
b = vals[0].subs(w,c)
a = vals[1].subs(w,c)
y_x = sqrt(((c*C1-C2) - a*(c-a)*x(t)**2)/(b*(c-b)))
z_x = sqrt(((b*C1-C2) - a*(b-a)*x(t)**2)/(c*(b-c)))
z_y = sqrt(((a*C1-C2) - b*(a-b)*y(t)**2)/(c*(a-c)))
x_y = sqrt(((c*C1-C2) - b*(c-b)*y(t)**2)/(a*(c-a)))
x_z = sqrt(((b*C1-C2) - c*(b-c)*z(t)**2)/(a*(b-a)))
y_z = sqrt(((a*C1-C2) - c*(a-c)*z(t)**2)/(b*(a-b)))
try:
sol1 = dsolve(a*diff(x(t),t) - (b-c)*y_x*z_x).rhs
except:
sol1 = dsolve(a*diff(x(t),t) - (b-c)*y_x*z_x, hint='separable_Integral')
try:
sol2 = dsolve(b*diff(y(t),t) - (c-a)*z_y*x_y).rhs
except:
sol2 = dsolve(b*diff(y(t),t) - (c-a)*z_y*x_y, hint='separable_Integral')
try:
sol3 = dsolve(c*diff(z(t),t) - (a-b)*x_z*y_z).rhs
except:
sol3 = dsolve(c*diff(z(t),t) - (a-b)*x_z*y_z, hint='separable_Integral')
return [Eq(x(t), sol1), Eq(y(t), sol2), Eq(z(t), sol3)]
def _nonlinear_3eq_order1_type2(x, y, z, t, eq):
r"""
Equations:
.. math:: a x' = (b - c) y z f(x, y, z, t)
.. math:: b y' = (c - a) z x f(x, y, z, t)
.. math:: c z' = (a - b) x y f(x, y, z, t)
First Integrals:
.. math:: a x^{2} + b y^{2} + c z^{2} = C_1
.. math:: a^{2} x^{2} + b^{2} y^{2} + c^{2} z^{2} = C_2
where `C_1` and `C_2` are arbitrary constants. On solving the integrals for `y` and
`z` and on substituting the resulting expressions into the first equation of the
system, we arrives at a first-order differential equations on `x`. Similarly doing
that for other two equations we will arrive at first order equation on `y` and `z`.
References
==========
-http://eqworld.ipmnet.ru/en/solutions/sysode/sode0402.pdf
"""
C1, C2 = get_numbered_constants(eq, num=2)
u, v, w = symbols('u, v, w')
p = Wild('p', exclude=[x(t), y(t), z(t), t])
q = Wild('q', exclude=[x(t), y(t), z(t), t])
s = Wild('s', exclude=[x(t), y(t), z(t), t])
f = Wild('f')
r1 = (diff(x(t),t) - eq[0]).match(y(t)*z(t)*f)
r = collect_const(r1[f]).match(p*f)
r.update(((diff(y(t),t) - eq[1])/r[f]).match(q*z(t)*x(t)))
r.update(((diff(z(t),t) - eq[2])/r[f]).match(s*x(t)*y(t)))
n1, d1 = r[p].as_numer_denom()
n2, d2 = r[q].as_numer_denom()
n3, d3 = r[s].as_numer_denom()
val = solve([n1*u-d1*v+d1*w, d2*u+n2*v-d2*w, -d3*u+d3*v+n3*w],[u,v])
vals = [val[v], val[u]]
c = lcm(vals[0].as_numer_denom()[1], vals[1].as_numer_denom()[1])
a = vals[0].subs(w,c)
b = vals[1].subs(w,c)
y_x = sqrt(((c*C1-C2) - a*(c-a)*x(t)**2)/(b*(c-b)))
z_x = sqrt(((b*C1-C2) - a*(b-a)*x(t)**2)/(c*(b-c)))
z_y = sqrt(((a*C1-C2) - b*(a-b)*y(t)**2)/(c*(a-c)))
x_y = sqrt(((c*C1-C2) - b*(c-b)*y(t)**2)/(a*(c-a)))
x_z = sqrt(((b*C1-C2) - c*(b-c)*z(t)**2)/(a*(b-a)))
y_z = sqrt(((a*C1-C2) - c*(a-c)*z(t)**2)/(b*(a-b)))
try:
sol1 = dsolve(a*diff(x(t),t) - (b-c)*y_x*z_x*r[f]).rhs
except:
sol1 = dsolve(a*diff(x(t),t) - (b-c)*y_x*z_x*r[f], hint='separable_Integral')
try:
sol2 = dsolve(b*diff(y(t),t) - (c-a)*z_y*x_y*r[f]).rhs
except:
sol2 = dsolve(b*diff(y(t),t) - (c-a)*z_y*x_y*r[f], hint='separable_Integral')
try:
sol3 = dsolve(c*diff(z(t),t) - (a-b)*x_z*y_z*r[f]).rhs
except:
sol3 = dsolve(c*diff(z(t),t) - (a-b)*x_z*y_z*r[f], hint='separable_Integral')
return [Eq(x(t), sol1), Eq(y(t), sol2), Eq(z(t), sol3)]
def _nonlinear_3eq_order1_type3(x, y, z, t, eq):
r"""
Equations:
.. math:: x' = c F_2 - b F_3, \enspace y' = a F_3 - c F_1, \enspace z' = b F_1 - a F_2
where `F_n = F_n(x, y, z, t)`.
1. First Integral:
.. math:: a x + b y + c z = C_1,
where C is an arbitrary constant.
2. If we assume function `F_n` to be independent of `t`,i.e, `F_n` = `F_n (x, y, z)`
Then, on eliminating `t` and `z` from the first two equation of the system, one
arrives at the first-order equation
.. math:: \frac{dy}{dx} = \frac{a F_3 (x, y, z) - c F_1 (x, y, z)}{c F_2 (x, y, z) -
b F_3 (x, y, z)}
where `z = \frac{1}{c} (C_1 - a x - b y)`
References
==========
-http://eqworld.ipmnet.ru/en/solutions/sysode/sode0404.pdf
"""
C1 = get_numbered_constants(eq, num=1)
u, v, w = symbols('u, v, w')
p = Wild('p', exclude=[x(t), y(t), z(t), t])
q = Wild('q', exclude=[x(t), y(t), z(t), t])
s = Wild('s', exclude=[x(t), y(t), z(t), t])
F1, F2, F3 = symbols('F1, F2, F3', cls=Wild)
r1 = (diff(x(t),t) - eq[0]).match(F2-F3)
r = collect_const(r1[F2]).match(s*F2)
r.update(collect_const(r1[F3]).match(q*F3))
if eq[1].has(r[F2]) and not eq[1].has(r[F3]):
r[F2], r[F3] = r[F3], r[F2]
r[s], r[q] = -r[q], -r[s]
r.update((diff(y(t),t) - eq[1]).match(p*r[F3] - r[s]*F1))
a = r[p]; b = r[q]; c = r[s]
F1 = r[F1].subs(x(t),u).subs(y(t),v).subs(z(t),w)
F2 = r[F2].subs(x(t),u).subs(y(t),v).subs(z(t),w)
F3 = r[F3].subs(x(t),u).subs(y(t),v).subs(z(t),w)
z_xy = (C1-a*u-b*v)/c
y_zx = (C1-a*u-c*w)/b
x_yz = (C1-b*v-c*w)/a
y_x = dsolve(diff(v(u),u) - ((a*F3-c*F1)/(c*F2-b*F3)).subs(w,z_xy).subs(v,v(u))).rhs
z_x = dsolve(diff(w(u),u) - ((b*F1-a*F2)/(c*F2-b*F3)).subs(v,y_zx).subs(w,w(u))).rhs
z_y = dsolve(diff(w(v),v) - ((b*F1-a*F2)/(a*F3-c*F1)).subs(u,x_yz).subs(w,w(v))).rhs
x_y = dsolve(diff(u(v),v) - ((c*F2-b*F3)/(a*F3-c*F1)).subs(w,z_xy).subs(u,u(v))).rhs
y_z = dsolve(diff(v(w),w) - ((a*F3-c*F1)/(b*F1-a*F2)).subs(u,x_yz).subs(v,v(w))).rhs
x_z = dsolve(diff(u(w),w) - ((c*F2-b*F3)/(b*F1-a*F2)).subs(v,y_zx).subs(u,u(w))).rhs
sol1 = dsolve(diff(u(t),t) - (c*F2 - b*F3).subs(v,y_x).subs(w,z_x).subs(u,u(t))).rhs
sol2 = dsolve(diff(v(t),t) - (a*F3 - c*F1).subs(u,x_y).subs(w,z_y).subs(v,v(t))).rhs
sol3 = dsolve(diff(w(t),t) - (b*F1 - a*F2).subs(u,x_z).subs(v,y_z).subs(w,w(t))).rhs
return [Eq(x(t), sol1), Eq(y(t), sol2), Eq(z(t), sol3)]
def _nonlinear_3eq_order1_type4(x, y, z, t, eq):
r"""
Equations:
.. math:: x' = c z F_2 - b y F_3, \enspace y' = a x F_3 - c z F_1, \enspace z' = b y F_1 - a x F_2
where `F_n = F_n (x, y, z, t)`
1. First integral:
.. math:: a x^{2} + b y^{2} + c z^{2} = C_1
where `C` is an arbitrary constant.
2. Assuming the function `F_n` is independent of `t`: `F_n = F_n (x, y, z)`. Then on
eliminating `t` and `z` from the first two equations of the system, one arrives at
the first-order equation
.. math:: \frac{dy}{dx} = \frac{a x F_3 (x, y, z) - c z F_1 (x, y, z)}
{c z F_2 (x, y, z) - b y F_3 (x, y, z)}
where `z = \pm \sqrt{\frac{1}{c} (C_1 - a x^{2} - b y^{2})}`
References
==========
-http://eqworld.ipmnet.ru/en/solutions/sysode/sode0405.pdf
"""
C1 = get_numbered_constants(eq, num=1)
u, v, w = symbols('u, v, w')
p = Wild('p', exclude=[x(t), y(t), z(t), t])
q = Wild('q', exclude=[x(t), y(t), z(t), t])
s = Wild('s', exclude=[x(t), y(t), z(t), t])
F1, F2, F3 = symbols('F1, F2, F3', cls=Wild)
r1 = eq[0].match(diff(x(t),t) - z(t)*F2 + y(t)*F3)
r = collect_const(r1[F2]).match(s*F2)
r.update(collect_const(r1[F3]).match(q*F3))
if eq[1].has(r[F2]) and not eq[1].has(r[F3]):
r[F2], r[F3] = r[F3], r[F2]
r[s], r[q] = -r[q], -r[s]
r.update((diff(y(t),t) - eq[1]).match(p*x(t)*r[F3] - r[s]*z(t)*F1))
a = r[p]; b = r[q]; c = r[s]
F1 = r[F1].subs(x(t),u).subs(y(t),v).subs(z(t),w)
F2 = r[F2].subs(x(t),u).subs(y(t),v).subs(z(t),w)
F3 = r[F3].subs(x(t),u).subs(y(t),v).subs(z(t),w)
x_yz = sqrt((C1 - b*v**2 - c*w**2)/a)
y_zx = sqrt((C1 - c*w**2 - a*u**2)/b)
z_xy = sqrt((C1 - a*u**2 - b*v**2)/c)
y_x = dsolve(diff(v(u),u) - ((a*u*F3-c*w*F1)/(c*w*F2-b*v*F3)).subs(w,z_xy).subs(v,v(u))).rhs
z_x = dsolve(diff(w(u),u) - ((b*v*F1-a*u*F2)/(c*w*F2-b*v*F3)).subs(v,y_zx).subs(w,w(u))).rhs
z_y = dsolve(diff(w(v),v) - ((b*v*F1-a*u*F2)/(a*u*F3-c*w*F1)).subs(u,x_yz).subs(w,w(v))).rhs
x_y = dsolve(diff(u(v),v) - ((c*w*F2-b*v*F3)/(a*u*F3-c*w*F1)).subs(w,z_xy).subs(u,u(v))).rhs
y_z = dsolve(diff(v(w),w) - ((a*u*F3-c*w*F1)/(b*v*F1-a*u*F2)).subs(u,x_yz).subs(v,v(w))).rhs
x_z = dsolve(diff(u(w),w) - ((c*w*F2-b*v*F3)/(b*v*F1-a*u*F2)).subs(v,y_zx).subs(u,u(w))).rhs
sol1 = dsolve(diff(u(t),t) - (c*w*F2 - b*v*F3).subs(v,y_x).subs(w,z_x).subs(u,u(t))).rhs
sol2 = dsolve(diff(v(t),t) - (a*u*F3 - c*w*F1).subs(u,x_y).subs(w,z_y).subs(v,v(t))).rhs
sol3 = dsolve(diff(w(t),t) - (b*v*F1 - a*u*F2).subs(u,x_z).subs(v,y_z).subs(w,w(t))).rhs
return [Eq(x(t), sol1), Eq(y(t), sol2), Eq(z(t), sol3)]
def _nonlinear_3eq_order1_type5(x, y, t, eq):
r"""
.. math:: x' = x (c F_2 - b F_3), \enspace y' = y (a F_3 - c F_1), \enspace z' = z (b F_1 - a F_2)
where `F_n = F_n (x, y, z, t)` and are arbitrary functions.
First Integral:
.. math:: \left|x\right|^{a} \left|y\right|^{b} \left|z\right|^{c} = C_1
where `C` is an arbitrary constant. If the function `F_n` is independent of `t`,
then, by eliminating `t` and `z` from the first two equations of the system, one
arrives at a first-order equation.
References
==========
-http://eqworld.ipmnet.ru/en/solutions/sysode/sode0406.pdf
"""
C1 = get_numbered_constants(eq, num=1)
u, v, w = symbols('u, v, w')
p = Wild('p', exclude=[x(t), y(t), z(t), t])
q = Wild('q', exclude=[x(t), y(t), z(t), t])
s = Wild('s', exclude=[x(t), y(t), z(t), t])
F1, F2, F3 = symbols('F1, F2, F3', cls=Wild)
r1 = eq[0].match(diff(x(t),t) - x(t)*(F2 - F3))
r = collect_const(r1[F2]).match(s*F2)
r.update(collect_const(r1[F3]).match(q*F3))
if eq[1].has(r[F2]) and not eq[1].has(r[F3]):
r[F2], r[F3] = r[F3], r[F2]
r[s], r[q] = -r[q], -r[s]
r.update((diff(y(t),t) - eq[1]).match(y(t)*(a*r[F3] - r[c]*F1)))
a = r[p]; b = r[q]; c = r[s]
F1 = r[F1].subs(x(t),u).subs(y(t),v).subs(z(t),w)
F2 = r[F2].subs(x(t),u).subs(y(t),v).subs(z(t),w)
F3 = r[F3].subs(x(t),u).subs(y(t),v).subs(z(t),w)
x_yz = (C1*v**-b*w**-c)**-a
y_zx = (C1*w**-c*u**-a)**-b
z_xy = (C1*u**-a*v**-b)**-c
y_x = dsolve(diff(v(u),u) - ((v*(a*F3-c*F1))/(u*(c*F2-b*F3))).subs(w,z_xy).subs(v,v(u))).rhs
z_x = dsolve(diff(w(u),u) - ((w*(b*F1-a*F2))/(u*(c*F2-b*F3))).subs(v,y_zx).subs(w,w(u))).rhs
z_y = dsolve(diff(w(v),v) - ((w*(b*F1-a*F2))/(v*(a*F3-c*F1))).subs(u,x_yz).subs(w,w(v))).rhs
x_y = dsolve(diff(u(v),v) - ((u*(c*F2-b*F3))/(v*(a*F3-c*F1))).subs(w,z_xy).subs(u,u(v))).rhs
y_z = dsolve(diff(v(w),w) - ((v*(a*F3-c*F1))/(w*(b*F1-a*F2))).subs(u,x_yz).subs(v,v(w))).rhs
x_z = dsolve(diff(u(w),w) - ((u*(c*F2-b*F3))/(w*(b*F1-a*F2))).subs(v,y_zx).subs(u,u(w))).rhs
sol1 = dsolve(diff(u(t),t) - (u*(c*F2-b*F3)).subs(v,y_x).subs(w,z_x).subs(u,u(t))).rhs
sol2 = dsolve(diff(v(t),t) - (v*(a*F3-c*F1)).subs(u,x_y).subs(w,z_y).subs(v,v(t))).rhs
sol3 = dsolve(diff(w(t),t) - (w*(b*F1-a*F2)).subs(u,x_z).subs(v,y_z).subs(w,w(t))).rhs
return [Eq(x(t), sol1), Eq(y(t), sol2), Eq(z(t), sol3)]
| gpl-3.0 |
jupiterben/shooter-player | Thirdparty/jsoncpp/test/rununittests.py | 249 | 2507 | import sys
import os
import os.path
import subprocess
from glob import glob
import optparse
VALGRIND_CMD = 'valgrind --tool=memcheck --leak-check=yes --undef-value-errors=yes'
class TestProxy(object):
def __init__( self, test_exe_path, use_valgrind=False ):
self.test_exe_path = os.path.normpath( os.path.abspath( test_exe_path ) )
self.use_valgrind = use_valgrind
def run( self, options ):
if self.use_valgrind:
cmd = VALGRIND_CMD.split()
else:
cmd = []
cmd.extend( [self.test_exe_path, '--test-auto'] + options )
process = subprocess.Popen( cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT )
stdout = process.communicate()[0]
if process.returncode:
return False, stdout
return True, stdout
def runAllTests( exe_path, use_valgrind=False ):
test_proxy = TestProxy( exe_path, use_valgrind=use_valgrind )
status, test_names = test_proxy.run( ['--list-tests'] )
if not status:
print >> sys.stderr, "Failed to obtain unit tests list:\n" + test_names
return 1
test_names = [name.strip() for name in test_names.strip().split('\n')]
failures = []
for name in test_names:
print 'TESTING %s:' % name,
succeed, result = test_proxy.run( ['--test', name] )
if succeed:
print 'OK'
else:
failures.append( (name, result) )
print 'FAILED'
failed_count = len(failures)
pass_count = len(test_names) - failed_count
if failed_count:
print
for name, result in failures:
print result
print '%d/%d tests passed (%d failure(s))' % (
pass_count, len(test_names), failed_count)
return 1
else:
print 'All %d tests passed' % len(test_names)
return 0
def main():
from optparse import OptionParser
parser = OptionParser( usage="%prog [options] <path to test_lib_json.exe>" )
parser.add_option("--valgrind",
action="store_true", dest="valgrind", default=False,
help="run all the tests using valgrind to detect memory leaks")
parser.enable_interspersed_args()
options, args = parser.parse_args()
if len(args) != 1:
parser.error( 'Must provides at least path to test_lib_json executable.' )
sys.exit( 1 )
exit_code = runAllTests( args[0], use_valgrind=options.valgrind )
sys.exit( exit_code )
if __name__ == '__main__':
main()
| gpl-2.0 |
vlitvak/fieldtrip | realtime/src/buffer/python/FieldTrip.py | 7 | 17758 | """
FieldTrip buffer (V1) client in pure Python
(C) 2010 S. Klanke
"""
# We need socket, struct, and numpy
import socket
import struct
import numpy
VERSION = 1
PUT_HDR = 0x0101
PUT_DAT = 0x0102
PUT_EVT = 0x0103
PUT_OK = 0x0104
PUT_ERR = 0x0105
GET_HDR = 0x0201
GET_DAT = 0x0202
GET_EVT = 0x0203
GET_OK = 0x0204
GET_ERR = 0x0205
FLUSH_HDR = 0x0301
FLUSH_DAT = 0x0302
FLUSH_EVT = 0x0303
FLUSH_OK = 0x0304
FLUSH_ERR = 0x0305
WAIT_DAT = 0x0402
WAIT_OK = 0x0404
WAIT_ERR = 0x0405
PUT_HDR_NORESPONSE = 0x0501
PUT_DAT_NORESPONSE = 0x0502
PUT_EVT_NORESPONSE = 0x0503
DATATYPE_CHAR = 0
DATATYPE_UINT8 = 1
DATATYPE_UINT16 = 2
DATATYPE_UINT32 = 3
DATATYPE_UINT64 = 4
DATATYPE_INT8 = 5
DATATYPE_INT16 = 6
DATATYPE_INT32 = 7
DATATYPE_INT64 = 8
DATATYPE_FLOAT32 = 9
DATATYPE_FLOAT64 = 10
DATATYPE_UNKNOWN = 0xFFFFFFFF
CHUNK_UNSPECIFIED = 0
CHUNK_CHANNEL_NAMES = 1
CHUNK_CHANNEL_FLAGS = 2
CHUNK_RESOLUTIONS = 3
CHUNK_ASCII_KEYVAL = 4
CHUNK_NIFTI1 = 5
CHUNK_SIEMENS_AP = 6
CHUNK_CTF_RES4 = 7
CHUNK_NEUROMAG_FIF = 8
CHUNK_NEUROMAG_ISOTRAK = 9
CHUNK_NEUROMAG_HPIRESULT = 10
# List for converting FieldTrip datatypes to Numpy datatypes
numpyType = ['int8', 'uint8', 'uint16', 'uint32', 'uint64',
'int8', 'int16', 'int32', 'int64', 'float32', 'float64']
# Corresponding word sizes
wordSize = [1, 1, 2, 4, 8, 1, 2, 4, 8, 4, 8]
# FieldTrip data type as indexed by numpy dtype.num
# this goes 0 => nothing, 1..4 => int8, uint8, int16, uint16, 7..10 =>
# int32, uint32, int64, uint64 11..12 => float32, float64
dataType = [-1, 5, 1, 6, 2, -1, -1, 7, 3, 8, 4, 9, 10]
def serialize(A):
"""
Returns FieldTrip data type and string representation of the given
object, if possible.
"""
if isinstance(A, str):
return (0, A)
if isinstance(A, numpy.ndarray):
dt = A.dtype
if not(dt.isnative) or dt.num < 1 or dt.num >= len(dataType):
return (DATATYPE_UNKNOWN, None)
ft = dataType[dt.num]
if ft == -1:
return (DATATYPE_UNKNOWN, None)
if A.flags['C_CONTIGUOUS']:
# great, just use the array's buffer interface
return (ft, str(A.data))
# otherwise, we need a copy to C order
AC = A.copy('C')
return (ft, str(AC.data))
if isinstance(A, int):
return (DATATYPE_INT32, struct.pack('i', A))
if isinstance(A, float):
return (DATATYPE_FLOAT64, struct.pack('d', A))
return (DATATYPE_UNKNOWN, None)
class Chunk:
def __init__(self):
self.type = 0
self.size = 0
self.buf = ''
class Header:
"""Class for storing header information in the FieldTrip buffer format"""
def __init__(self):
self.nChannels = 0
self.nSamples = 0
self.nEvents = 0
self.fSample = 0.0
self.dataType = 0
self.chunks = {}
self.labels = []
def __str__(self):
return ('Channels.: %i\nSamples..: %i\nEvents...: %i\nSampFreq.: '
'%f\nDataType.: %s\n'
% (self.nChannels, self.nSamples, self.nEvents,
self.fSample, numpyType[self.dataType]))
class Event:
"""Class for storing events in the FieldTrip buffer format"""
def __init__(self, S=None):
if S is None:
self.type = ''
self.value = ''
self.sample = 0
self.offset = 0
self.duration = 0
else:
self.deserialize(S)
def __str__(self):
return ('Type.....: %s\nValue....: %s\nSample...: %i\nOffset...: '
'%i\nDuration.: %i\n' % (str(self.type), str(self.value),
self.sample, self.offset,
self.duration))
def deserialize(self, buf):
bufsize = len(buf)
if bufsize < 32:
return 0
(type_type, type_numel, value_type, value_numel, sample,
offset, duration, bsiz) = struct.unpack('IIIIIiiI', buf[0:32])
self.sample = sample
self.offset = offset
self.duration = duration
st = type_numel * wordSize[type_type]
sv = value_numel * wordSize[value_type]
if bsiz + 32 > bufsize or st + sv > bsiz:
raise IOError(
'Invalid event definition -- does not fit in given buffer')
raw_type = buf[32:32 + st]
raw_value = buf[32 + st:32 + st + sv]
if type_type == 0:
self.type = raw_type
else:
self.type = numpy.ndarray(
(type_numel), dtype=numpyType[type_type], buffer=raw_type)
if value_type == 0:
self.value = raw_value
else:
self.value = numpy.ndarray(
(value_numel), dtype=numpyType[value_type], buffer=raw_value)
return bsiz + 32
def serialize(self):
"""
Returns the contents of this event as a string, ready to
send over the network, or None in case of conversion problems.
"""
type_type, type_buf = serialize(self.type)
if type_type == DATATYPE_UNKNOWN:
return None
type_size = len(type_buf)
type_numel = type_size / wordSize[type_type]
value_type, value_buf = serialize(self.value)
if value_type == DATATYPE_UNKNOWN:
return None
value_size = len(value_buf)
value_numel = value_size / wordSize[value_type]
bufsize = type_size + value_size
S = struct.pack('IIIIIiiI', type_type, type_numel, value_type,
value_numel, int(self.sample), int(self.offset),
int(self.duration), bufsize)
return S + type_buf + value_buf
class Client:
"""Class for managing a client connection to a FieldTrip buffer."""
def __init__(self):
self.isConnected = False
self.sock = []
def connect(self, hostname, port=1972):
"""
connect(hostname [, port]) -- make a connection, default port is
1972.
"""
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.connect((hostname, port))
self.sock.setblocking(True)
self.isConnected = True
def disconnect(self):
"""disconnect() -- close a connection."""
if self.isConnected:
self.sock.close()
self.sock = []
self.isConnected = False
def sendRaw(self, request):
"""Send all bytes of the string 'request' out to socket."""
if not(self.isConnected):
raise IOError('Not connected to FieldTrip buffer')
N = len(request)
nw = self.sock.send(request)
while nw < N:
nw += self.sock.send(request[nw:])
def sendRequest(self, command, payload=None):
if payload is None:
request = struct.pack('HHI', VERSION, command, 0)
else:
request = struct.pack(
'HHI', VERSION, command, len(payload)) + payload
self.sendRaw(request)
def receiveResponse(self, minBytes=0):
"""
Receive response from server on socket 's' and return it as
(status,bufsize,payload).
"""
resp_hdr = self.sock.recv(8)
while len(resp_hdr) < 8:
resp_hdr += self.sock.recv(8 - len(resp_hdr))
(version, command, bufsize) = struct.unpack('HHI', resp_hdr)
if version != VERSION:
self.disconnect()
raise IOError('Bad response from buffer server - disconnecting')
if bufsize > 0:
payload = self.sock.recv(bufsize)
while len(payload) < bufsize:
payload += self.sock.recv(bufsize - len(payload))
else:
payload = None
return (command, bufsize, payload)
def getHeader(self):
"""
getHeader() -- grabs header information from the buffer an returns
it as a Header object.
"""
self.sendRequest(GET_HDR)
(status, bufsize, payload) = self.receiveResponse()
if status == GET_ERR:
return None
if status != GET_OK:
self.disconnect()
raise IOError('Bad response from buffer server - disconnecting')
if bufsize < 24:
self.disconnect()
raise IOError('Invalid HEADER packet received (too few bytes) - '
'disconnecting')
(nchans, nsamp, nevt, fsamp, dtype,
bfsiz) = struct.unpack('IIIfII', payload[0:24])
H = Header()
H.nChannels = nchans
H.nSamples = nsamp
H.nEvents = nevt
H.fSample = fsamp
H.dataType = dtype
if bfsiz > 0:
offset = 24
while offset + 8 < bufsize:
(chunk_type, chunk_len) = struct.unpack(
'II', payload[offset:offset + 8])
offset += 8
if offset + chunk_len > bufsize:
break
H.chunks[chunk_type] = payload[offset:offset + chunk_len]
offset += chunk_len
if CHUNK_CHANNEL_NAMES in H.chunks:
L = H.chunks[CHUNK_CHANNEL_NAMES].split(b'\0')
numLab = len(L)
if numLab >= H.nChannels:
H.labels = [x.decode('utf-8') for x in L[0:H.nChannels]]
return H
def putHeader(self, nChannels, fSample, dataType, labels=None,
chunks=None, reponse=True):
haveLabels = False
extras = ''
if (type(labels)==list) and (len(labels)==0):
labels=None
if not(labels is None):
serLabels = ''
try:
for n in range(0, nChannels):
serLabels += labels[n] + '\0'
except:
raise ValueError('Channels names (labels), if given,'
' must be a list of N=numChannels strings')
extras = struct.pack('II', CHUNK_CHANNEL_NAMES,
len(serLabels)) + serLabels
haveLabels = True
if not(chunks is None):
for chunk_type, chunk_data in chunks:
if haveLabels and chunk_type == CHUNK_CHANNEL_NAMES:
# ignore channel names chunk in case we got labels
continue
extras += struct.pack('II', chunk_type,
len(chunk_data)) + chunk_data
sizeChunks = len(extras)
if reponse:
command = PUT_HDR
else:
command = PUT_HDR_NORESPONSE
hdef = struct.pack('IIIfII', nChannels, 0, 0,
fSample, dataType, sizeChunks)
request = struct.pack('HHI', VERSION, command,
sizeChunks + len(hdef)) + hdef + extras
self.sendRaw(request)
if reponse:
(status, bufsize, resp_buf) = self.receiveResponse()
if status != PUT_OK:
raise IOError('Header could not be written')
def getData(self, index=None):
"""
getData([indices]) -- retrieve data samples and return them as a
Numpy array, samples in rows(!). The 'indices' argument is optional,
and if given, must be a tuple or list with inclusive, zero-based
start/end indices.
"""
if index is None:
request = struct.pack('HHI', VERSION, GET_DAT, 0)
else:
indS = int(index[0])
indE = int(index[1])
request = struct.pack('HHIII', VERSION, GET_DAT, 8, indS, indE)
self.sendRaw(request)
(status, bufsize, payload) = self.receiveResponse()
if status == GET_ERR:
return None
if status != GET_OK:
self.disconnect()
raise IOError('Bad response from buffer server - disconnecting')
if bufsize < 16:
self.disconnect()
raise IOError('Invalid DATA packet received (too few bytes)')
(nchans, nsamp, datype, bfsiz) = struct.unpack('IIII', payload[0:16])
if bfsiz < bufsize - 16 or datype >= len(numpyType):
raise IOError('Invalid DATA packet received')
raw = payload[16:bfsiz + 16]
D = numpy.ndarray((nsamp, nchans), dtype=numpyType[datype], buffer=raw)
return D
def getEvents(self, index=None):
"""
getEvents([indices]) -- retrieve events and return them as a list
of Event objects. The 'indices' argument is optional, and if given,
must be a tuple or list with inclusive, zero-based start/end indices.
The 'type' and 'value' fields of the event will be converted to strings
or Numpy arrays.
"""
if index is None:
request = struct.pack('HHI', VERSION, GET_EVT, 0)
else:
indS = int(index[0])
indE = int(index[1])
request = struct.pack('HHIII', VERSION, GET_EVT, 8, indS, indE)
self.sendRaw(request)
(status, bufsize, resp_buf) = self.receiveResponse()
if status == GET_ERR:
return []
if status != GET_OK:
self.disconnect()
raise IOError('Bad response from buffer server - disconnecting')
offset = 0
E = []
while 1:
e = Event()
nextOffset = e.deserialize(resp_buf[offset:])
if nextOffset == 0:
break
E.append(e)
offset = offset + nextOffset
return E
def putEvents(self, E, reponse=True):
"""
putEvents(E) -- writes a single or multiple events, depending on
whether an 'Event' object, or a list of 'Event' objects is
given as an argument.
"""
if isinstance(E, Event):
buf = E.serialize()
else:
buf = ''
num = 0
for e in E:
if not(isinstance(e, Event)):
raise 'Element %i in given list is not an Event' % num
buf = buf + e.serialize()
num = num + 1
if reponse:
command = PUT_EVT
else:
command = PUT_EVT_NORESPONSE
self.sendRequest(command, buf)
if reponse:
(status, bufsize, resp_buf) = self.receiveResponse()
if status != PUT_OK:
raise IOError('Events could not be written.')
def putData(self, D, response=True):
"""
putData(D) -- writes samples that must be given as a NUMPY array,
samples x channels. The type of the samples (D) and the number of
channels must match the corresponding quantities in the FieldTrip
buffer.
"""
if not(isinstance(D, numpy.ndarray)) or len(D.shape) != 2:
raise ValueError(
'Data must be given as a NUMPY array (samples x channels)')
nSamp = D.shape[0]
nChan = D.shape[1]
(dataType, dataBuf) = serialize(D)
dataBufSize = len(dataBuf)
if reponse:
command = PUT_DAT
else:
command = PUT_DAT_NORESPONSE
request = struct.pack('HHI', VERSION, command, 16 + dataBufSize)
dataDef = struct.pack('IIII', nChan, nSamp, dataType, dataBufSize)
self.sendRaw(request + dataDef + dataBuf)
if response:
(status, bufsize, resp_buf) = self.receiveResponse()
if status != PUT_OK:
raise IOError('Samples could not be written.')
def poll(self):
request = struct.pack('HHIIII', VERSION, WAIT_DAT, 12, 0, 0, 0)
self.sendRaw(request)
(status, bufsize, resp_buf) = self.receiveResponse()
if status != WAIT_OK or bufsize < 8:
raise IOError('Polling failed.')
return struct.unpack('II', resp_buf[0:8])
def wait(self, nsamples, nevents, timeout):
request = struct.pack('HHIIII', VERSION, WAIT_DAT,
12, int(nsamples), int(nevents), int(timeout))
self.sendRaw(request)
(status, bufsize, resp_buf) = self.receiveResponse()
if status != WAIT_OK or bufsize < 8:
raise IOError('Wait request failed.')
return struct.unpack('II', resp_buf[0:8])
if __name__ == "__main__":
# Just a small demo for testing purposes...
# This should be moved to a separate file at some point
import sys
hostname = 'localhost'
port = 1972
if len(sys.argv) > 1:
hostname = sys.argv[1]
if len(sys.argv) > 2:
try:
port = int(sys.argv[2])
except:
print ('Error: second argument (%s) must be a valid (=integer)'
' port number' % sys.argv[2])
sys.exit(1)
ftc = Client()
print 'Trying to connect to buffer on %s:%i ...' % (hostname, port)
ftc.connect(hostname, port)
print '\nConnected - trying to read header...'
H = ftc.getHeader()
if H is None:
print 'Failed!'
else:
print H
print H.labels
if H.nSamples > 0:
print '\nTrying to read last sample...'
index = H.nSamples - 1
D = ftc.getData([index, index])
print D
if H.nEvents > 0:
print '\nTrying to read (all) events...'
E = ftc.getEvents()
for e in E:
print e
print ftc.poll()
ftc.disconnect()
| gpl-2.0 |
siutanwong/scikit-learn | examples/cluster/plot_mini_batch_kmeans.py | 265 | 4081 | """
====================================================================
Comparison of the K-Means and MiniBatchKMeans clustering algorithms
====================================================================
We want to compare the performance of the MiniBatchKMeans and KMeans:
the MiniBatchKMeans is faster, but gives slightly different results (see
:ref:`mini_batch_kmeans`).
We will cluster a set of data, first with KMeans and then with
MiniBatchKMeans, and plot the results.
We will also plot the points that are labelled differently between the two
algorithms.
"""
print(__doc__)
import time
import numpy as np
import matplotlib.pyplot as plt
from sklearn.cluster import MiniBatchKMeans, KMeans
from sklearn.metrics.pairwise import pairwise_distances_argmin
from sklearn.datasets.samples_generator import make_blobs
##############################################################################
# Generate sample data
np.random.seed(0)
batch_size = 45
centers = [[1, 1], [-1, -1], [1, -1]]
n_clusters = len(centers)
X, labels_true = make_blobs(n_samples=3000, centers=centers, cluster_std=0.7)
##############################################################################
# Compute clustering with Means
k_means = KMeans(init='k-means++', n_clusters=3, n_init=10)
t0 = time.time()
k_means.fit(X)
t_batch = time.time() - t0
k_means_labels = k_means.labels_
k_means_cluster_centers = k_means.cluster_centers_
k_means_labels_unique = np.unique(k_means_labels)
##############################################################################
# Compute clustering with MiniBatchKMeans
mbk = MiniBatchKMeans(init='k-means++', n_clusters=3, batch_size=batch_size,
n_init=10, max_no_improvement=10, verbose=0)
t0 = time.time()
mbk.fit(X)
t_mini_batch = time.time() - t0
mbk_means_labels = mbk.labels_
mbk_means_cluster_centers = mbk.cluster_centers_
mbk_means_labels_unique = np.unique(mbk_means_labels)
##############################################################################
# Plot result
fig = plt.figure(figsize=(8, 3))
fig.subplots_adjust(left=0.02, right=0.98, bottom=0.05, top=0.9)
colors = ['#4EACC5', '#FF9C34', '#4E9A06']
# We want to have the same colors for the same cluster from the
# MiniBatchKMeans and the KMeans algorithm. Let's pair the cluster centers per
# closest one.
order = pairwise_distances_argmin(k_means_cluster_centers,
mbk_means_cluster_centers)
# KMeans
ax = fig.add_subplot(1, 3, 1)
for k, col in zip(range(n_clusters), colors):
my_members = k_means_labels == k
cluster_center = k_means_cluster_centers[k]
ax.plot(X[my_members, 0], X[my_members, 1], 'w',
markerfacecolor=col, marker='.')
ax.plot(cluster_center[0], cluster_center[1], 'o', markerfacecolor=col,
markeredgecolor='k', markersize=6)
ax.set_title('KMeans')
ax.set_xticks(())
ax.set_yticks(())
plt.text(-3.5, 1.8, 'train time: %.2fs\ninertia: %f' % (
t_batch, k_means.inertia_))
# MiniBatchKMeans
ax = fig.add_subplot(1, 3, 2)
for k, col in zip(range(n_clusters), colors):
my_members = mbk_means_labels == order[k]
cluster_center = mbk_means_cluster_centers[order[k]]
ax.plot(X[my_members, 0], X[my_members, 1], 'w',
markerfacecolor=col, marker='.')
ax.plot(cluster_center[0], cluster_center[1], 'o', markerfacecolor=col,
markeredgecolor='k', markersize=6)
ax.set_title('MiniBatchKMeans')
ax.set_xticks(())
ax.set_yticks(())
plt.text(-3.5, 1.8, 'train time: %.2fs\ninertia: %f' %
(t_mini_batch, mbk.inertia_))
# Initialise the different array to all False
different = (mbk_means_labels == 4)
ax = fig.add_subplot(1, 3, 3)
for l in range(n_clusters):
different += ((k_means_labels == k) != (mbk_means_labels == order[k]))
identic = np.logical_not(different)
ax.plot(X[identic, 0], X[identic, 1], 'w',
markerfacecolor='#bbbbbb', marker='.')
ax.plot(X[different, 0], X[different, 1], 'w',
markerfacecolor='m', marker='.')
ax.set_title('Difference')
ax.set_xticks(())
ax.set_yticks(())
plt.show()
| bsd-3-clause |
StephaneP/volatility | volatility/plugins/mac/route.py | 44 | 3443 | # Volatility
# Copyright (C) 2007-2013 Volatility Foundation
#
# This file is part of Volatility.
#
# Volatility 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.
#
# Volatility 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 Volatility. If not, see <http://www.gnu.org/licenses/>.
#
"""
@author: Andrew Case
@license: GNU General Public License 2.0
@contact: [email protected]
@organization:
"""
import datetime
import volatility.obj as obj
import volatility.plugins.mac.common as common
class mac_route(common.AbstractMacCommand):
""" Prints the routing table """
def _get_table(self, tbl):
rnh = tbl #obj.Object("radix_node", offset=tbl.v(), vm=self.addr_space)
rn = rnh.rnh_treetop
while rn.is_valid() and rn.rn_bit >= 0:
rn = rn.rn_u.rn_node.rn_L
rnhash = {}
while rn.is_valid():
base = rn
if rn in rnhash:
break
rnhash[rn] = 1
while rn.is_valid() and rn.rn_parent.rn_u.rn_node.rn_R == rn and rn.rn_flags & 2 == 0:
rn = rn.rn_parent
rn = rn.rn_parent.rn_u.rn_node.rn_R
while rn.is_valid() and rn.rn_bit >= 0:
rn = rn.rn_u.rn_node.rn_L
nextptr = rn
while base.v() != 0:
rn = base
base = rn.rn_u.rn_leaf.rn_Dupedkey
if rn.rn_flags & 2 == 0:
rt = obj.Object("rtentry", offset = rn, vm = self.addr_space)
yield rt
rn = nextptr
if rn.rn_flags & 2 != 0:
break
def calculate(self):
common.set_plugin_members(self)
tables_addr = self.addr_space.profile.get_symbol("_rt_tables")
## FIXME: if we only use ents[2] why do we need to instantiate 32?
ents = obj.Object('Array', offset = tables_addr, vm = self.addr_space, targetType = 'Pointer', count = 32)
ipv4table = obj.Object("radix_node_head", offset = ents[2], vm = self.addr_space)
rts = self._get_table(ipv4table)
for rt in rts:
yield rt
def render_text(self, outfd, data):
self.table_header(outfd, [("Source IP", "24"),
("Dest. IP", "24"),
("Name", "^10"),
("Sent", "^18"),
("Recv", "^18"),
("Time", "^30"),
("Exp.", "^10"),
("Delta", "")])
for rt in data:
self.table_row(outfd,
rt.source_ip,
rt.dest_ip,
rt.name,
rt.sent, rt.rx,
rt.get_time(),
rt.rt_expire,
rt.delta)
| gpl-2.0 |
GhostThrone/django | tests/known_related_objects/tests.py | 363 | 6425 | from __future__ import unicode_literals
from django.test import TestCase
from .models import Organiser, Pool, PoolStyle, Tournament
class ExistingRelatedInstancesTests(TestCase):
@classmethod
def setUpTestData(cls):
cls.t1 = Tournament.objects.create(name='Tourney 1')
cls.t2 = Tournament.objects.create(name='Tourney 2')
cls.o1 = Organiser.objects.create(name='Organiser 1')
cls.p1 = Pool.objects.create(name='T1 Pool 1', tournament=cls.t1, organiser=cls.o1)
cls.p2 = Pool.objects.create(name='T1 Pool 2', tournament=cls.t1, organiser=cls.o1)
cls.p3 = Pool.objects.create(name='T2 Pool 1', tournament=cls.t2, organiser=cls.o1)
cls.p4 = Pool.objects.create(name='T2 Pool 2', tournament=cls.t2, organiser=cls.o1)
cls.ps1 = PoolStyle.objects.create(name='T1 Pool 2 Style', pool=cls.p2)
cls.ps2 = PoolStyle.objects.create(name='T2 Pool 1 Style', pool=cls.p3)
def test_foreign_key(self):
with self.assertNumQueries(2):
tournament = Tournament.objects.get(pk=self.t1.pk)
pool = tournament.pool_set.all()[0]
self.assertIs(tournament, pool.tournament)
def test_foreign_key_prefetch_related(self):
with self.assertNumQueries(2):
tournament = (Tournament.objects.prefetch_related('pool_set').get(pk=self.t1.pk))
pool = tournament.pool_set.all()[0]
self.assertIs(tournament, pool.tournament)
def test_foreign_key_multiple_prefetch(self):
with self.assertNumQueries(2):
tournaments = list(Tournament.objects.prefetch_related('pool_set').order_by('pk'))
pool1 = tournaments[0].pool_set.all()[0]
self.assertIs(tournaments[0], pool1.tournament)
pool2 = tournaments[1].pool_set.all()[0]
self.assertIs(tournaments[1], pool2.tournament)
def test_queryset_or(self):
tournament_1 = self.t1
tournament_2 = self.t2
with self.assertNumQueries(1):
pools = tournament_1.pool_set.all() | tournament_2.pool_set.all()
related_objects = set(pool.tournament for pool in pools)
self.assertEqual(related_objects, {tournament_1, tournament_2})
def test_queryset_or_different_cached_items(self):
tournament = self.t1
organiser = self.o1
with self.assertNumQueries(1):
pools = tournament.pool_set.all() | organiser.pool_set.all()
first = pools.filter(pk=self.p1.pk)[0]
self.assertIs(first.tournament, tournament)
self.assertIs(first.organiser, organiser)
def test_queryset_or_only_one_with_precache(self):
tournament_1 = self.t1
tournament_2 = self.t2
# 2 queries here as pool 3 has tournament 2, which is not cached
with self.assertNumQueries(2):
pools = tournament_1.pool_set.all() | Pool.objects.filter(pk=self.p3.pk)
related_objects = set(pool.tournament for pool in pools)
self.assertEqual(related_objects, {tournament_1, tournament_2})
# and the other direction
with self.assertNumQueries(2):
pools = Pool.objects.filter(pk=self.p3.pk) | tournament_1.pool_set.all()
related_objects = set(pool.tournament for pool in pools)
self.assertEqual(related_objects, {tournament_1, tournament_2})
def test_queryset_and(self):
tournament = self.t1
organiser = self.o1
with self.assertNumQueries(1):
pools = tournament.pool_set.all() & organiser.pool_set.all()
first = pools.filter(pk=self.p1.pk)[0]
self.assertIs(first.tournament, tournament)
self.assertIs(first.organiser, organiser)
def test_one_to_one(self):
with self.assertNumQueries(2):
style = PoolStyle.objects.get(pk=self.ps1.pk)
pool = style.pool
self.assertIs(style, pool.poolstyle)
def test_one_to_one_select_related(self):
with self.assertNumQueries(1):
style = PoolStyle.objects.select_related('pool').get(pk=self.ps1.pk)
pool = style.pool
self.assertIs(style, pool.poolstyle)
def test_one_to_one_multi_select_related(self):
with self.assertNumQueries(1):
poolstyles = list(PoolStyle.objects.select_related('pool').order_by('pk'))
self.assertIs(poolstyles[0], poolstyles[0].pool.poolstyle)
self.assertIs(poolstyles[1], poolstyles[1].pool.poolstyle)
def test_one_to_one_prefetch_related(self):
with self.assertNumQueries(2):
style = PoolStyle.objects.prefetch_related('pool').get(pk=self.ps1.pk)
pool = style.pool
self.assertIs(style, pool.poolstyle)
def test_one_to_one_multi_prefetch_related(self):
with self.assertNumQueries(2):
poolstyles = list(PoolStyle.objects.prefetch_related('pool').order_by('pk'))
self.assertIs(poolstyles[0], poolstyles[0].pool.poolstyle)
self.assertIs(poolstyles[1], poolstyles[1].pool.poolstyle)
def test_reverse_one_to_one(self):
with self.assertNumQueries(2):
pool = Pool.objects.get(pk=self.p2.pk)
style = pool.poolstyle
self.assertIs(pool, style.pool)
def test_reverse_one_to_one_select_related(self):
with self.assertNumQueries(1):
pool = Pool.objects.select_related('poolstyle').get(pk=self.p2.pk)
style = pool.poolstyle
self.assertIs(pool, style.pool)
def test_reverse_one_to_one_prefetch_related(self):
with self.assertNumQueries(2):
pool = Pool.objects.prefetch_related('poolstyle').get(pk=self.p2.pk)
style = pool.poolstyle
self.assertIs(pool, style.pool)
def test_reverse_one_to_one_multi_select_related(self):
with self.assertNumQueries(1):
pools = list(Pool.objects.select_related('poolstyle').order_by('pk'))
self.assertIs(pools[1], pools[1].poolstyle.pool)
self.assertIs(pools[2], pools[2].poolstyle.pool)
def test_reverse_one_to_one_multi_prefetch_related(self):
with self.assertNumQueries(2):
pools = list(Pool.objects.prefetch_related('poolstyle').order_by('pk'))
self.assertIs(pools[1], pools[1].poolstyle.pool)
self.assertIs(pools[2], pools[2].poolstyle.pool)
| bsd-3-clause |
epitron/youtube-dl | youtube_dl/extractor/abc.py | 13 | 7543 | from __future__ import unicode_literals
import hashlib
import hmac
import re
import time
from .common import InfoExtractor
from ..compat import compat_str
from ..utils import (
ExtractorError,
js_to_json,
int_or_none,
parse_iso8601,
try_get,
unescapeHTML,
update_url_query,
)
class ABCIE(InfoExtractor):
IE_NAME = 'abc.net.au'
_VALID_URL = r'https?://(?:www\.)?abc\.net\.au/news/(?:[^/]+/){1,2}(?P<id>\d+)'
_TESTS = [{
'url': 'http://www.abc.net.au/news/2014-11-05/australia-to-staff-ebola-treatment-centre-in-sierra-leone/5868334',
'md5': 'cb3dd03b18455a661071ee1e28344d9f',
'info_dict': {
'id': '5868334',
'ext': 'mp4',
'title': 'Australia to help staff Ebola treatment centre in Sierra Leone',
'description': 'md5:809ad29c67a05f54eb41f2a105693a67',
},
'skip': 'this video has expired',
}, {
'url': 'http://www.abc.net.au/news/2015-08-17/warren-entsch-introduces-same-sex-marriage-bill/6702326',
'md5': 'db2a5369238b51f9811ad815b69dc086',
'info_dict': {
'id': 'NvqvPeNZsHU',
'ext': 'mp4',
'upload_date': '20150816',
'uploader': 'ABC News (Australia)',
'description': 'Government backbencher Warren Entsch introduces a cross-party sponsored bill to legalise same-sex marriage, saying the bill is designed to promote "an inclusive Australia, not a divided one.". Read more here: http://ab.co/1Mwc6ef',
'uploader_id': 'NewsOnABC',
'title': 'Marriage Equality: Warren Entsch introduces same sex marriage bill',
},
'add_ie': ['Youtube'],
'skip': 'Not accessible from Travis CI server',
}, {
'url': 'http://www.abc.net.au/news/2015-10-23/nab-lifts-interest-rates-following-westpac-and-cba/6880080',
'md5': 'b96eee7c9edf4fc5a358a0252881cc1f',
'info_dict': {
'id': '6880080',
'ext': 'mp3',
'title': 'NAB lifts interest rates, following Westpac and CBA',
'description': 'md5:f13d8edc81e462fce4a0437c7dc04728',
},
}, {
'url': 'http://www.abc.net.au/news/2015-10-19/6866214',
'only_matching': True,
}]
def _real_extract(self, url):
video_id = self._match_id(url)
webpage = self._download_webpage(url, video_id)
mobj = re.search(
r'inline(?P<type>Video|Audio|YouTube)Data\.push\((?P<json_data>[^)]+)\);',
webpage)
if mobj is None:
expired = self._html_search_regex(r'(?s)class="expired-(?:video|audio)".+?<span>(.+?)</span>', webpage, 'expired', None)
if expired:
raise ExtractorError('%s said: %s' % (self.IE_NAME, expired), expected=True)
raise ExtractorError('Unable to extract video urls')
urls_info = self._parse_json(
mobj.group('json_data'), video_id, transform_source=js_to_json)
if not isinstance(urls_info, list):
urls_info = [urls_info]
if mobj.group('type') == 'YouTube':
return self.playlist_result([
self.url_result(url_info['url']) for url_info in urls_info])
formats = [{
'url': url_info['url'],
'vcodec': url_info.get('codec') if mobj.group('type') == 'Video' else 'none',
'width': int_or_none(url_info.get('width')),
'height': int_or_none(url_info.get('height')),
'tbr': int_or_none(url_info.get('bitrate')),
'filesize': int_or_none(url_info.get('filesize')),
} for url_info in urls_info]
self._sort_formats(formats)
return {
'id': video_id,
'title': self._og_search_title(webpage),
'formats': formats,
'description': self._og_search_description(webpage),
'thumbnail': self._og_search_thumbnail(webpage),
}
class ABCIViewIE(InfoExtractor):
IE_NAME = 'abc.net.au:iview'
_VALID_URL = r'https?://iview\.abc\.net\.au/(?:[^/]+/)*video/(?P<id>[^/?#]+)'
_GEO_COUNTRIES = ['AU']
# ABC iview programs are normally available for 14 days only.
_TESTS = [{
'url': 'https://iview.abc.net.au/show/ben-and-hollys-little-kingdom/series/0/video/ZX9371A050S00',
'md5': 'cde42d728b3b7c2b32b1b94b4a548afc',
'info_dict': {
'id': 'ZX9371A050S00',
'ext': 'mp4',
'title': "Gaston's Birthday",
'series': "Ben And Holly's Little Kingdom",
'description': 'md5:f9de914d02f226968f598ac76f105bcf',
'upload_date': '20180604',
'uploader_id': 'abc4kids',
'timestamp': 1528140219,
},
'params': {
'skip_download': True,
},
}]
def _real_extract(self, url):
video_id = self._match_id(url)
video_params = self._download_json(
'https://iview.abc.net.au/api/programs/' + video_id, video_id)
title = unescapeHTML(video_params.get('title') or video_params['seriesTitle'])
stream = next(s for s in video_params['playlist'] if s.get('type') in ('program', 'livestream'))
house_number = video_params.get('episodeHouseNumber') or video_id
path = '/auth/hls/sign?ts={0}&hn={1}&d=android-tablet'.format(
int(time.time()), house_number)
sig = hmac.new(
b'android.content.res.Resources',
path.encode('utf-8'), hashlib.sha256).hexdigest()
token = self._download_webpage(
'http://iview.abc.net.au{0}&sig={1}'.format(path, sig), video_id)
def tokenize_url(url, token):
return update_url_query(url, {
'hdnea': token,
})
for sd in ('sd', 'sd-low'):
sd_url = try_get(
stream, lambda x: x['streams']['hls'][sd], compat_str)
if not sd_url:
continue
formats = self._extract_m3u8_formats(
tokenize_url(sd_url, token), video_id, 'mp4',
entry_protocol='m3u8_native', m3u8_id='hls', fatal=False)
if formats:
break
self._sort_formats(formats)
subtitles = {}
src_vtt = stream.get('captions', {}).get('src-vtt')
if src_vtt:
subtitles['en'] = [{
'url': src_vtt,
'ext': 'vtt',
}]
is_live = video_params.get('livestream') == '1'
if is_live:
title = self._live_title(title)
return {
'id': video_id,
'title': title,
'description': video_params.get('description'),
'thumbnail': video_params.get('thumbnail'),
'duration': int_or_none(video_params.get('eventDuration')),
'timestamp': parse_iso8601(video_params.get('pubDate'), ' '),
'series': unescapeHTML(video_params.get('seriesTitle')),
'series_id': video_params.get('seriesHouseNumber') or video_id[:7],
'season_number': int_or_none(self._search_regex(
r'\bSeries\s+(\d+)\b', title, 'season number', default=None)),
'episode_number': int_or_none(self._search_regex(
r'\bEp\s+(\d+)\b', title, 'episode number', default=None)),
'episode_id': house_number,
'uploader_id': video_params.get('channel'),
'formats': formats,
'subtitles': subtitles,
'is_live': is_live,
}
| unlicense |
Yen-Chung-En/2015cdb_g1_0623-2 | static/Brython3.1.1-20150328-091302/Lib/unittest/test/test_suite.py | 791 | 12066 | import unittest
import sys
from .support import LoggingResult, TestEquality
### Support code for Test_TestSuite
################################################################
class Test(object):
class Foo(unittest.TestCase):
def test_1(self): pass
def test_2(self): pass
def test_3(self): pass
def runTest(self): pass
def _mk_TestSuite(*names):
return unittest.TestSuite(Test.Foo(n) for n in names)
################################################################
class Test_TestSuite(unittest.TestCase, TestEquality):
### Set up attributes needed by inherited tests
################################################################
# Used by TestEquality.test_eq
eq_pairs = [(unittest.TestSuite(), unittest.TestSuite())
,(unittest.TestSuite(), unittest.TestSuite([]))
,(_mk_TestSuite('test_1'), _mk_TestSuite('test_1'))]
# Used by TestEquality.test_ne
ne_pairs = [(unittest.TestSuite(), _mk_TestSuite('test_1'))
,(unittest.TestSuite([]), _mk_TestSuite('test_1'))
,(_mk_TestSuite('test_1', 'test_2'), _mk_TestSuite('test_1', 'test_3'))
,(_mk_TestSuite('test_1'), _mk_TestSuite('test_2'))]
################################################################
### /Set up attributes needed by inherited tests
### Tests for TestSuite.__init__
################################################################
# "class TestSuite([tests])"
#
# The tests iterable should be optional
def test_init__tests_optional(self):
suite = unittest.TestSuite()
self.assertEqual(suite.countTestCases(), 0)
# "class TestSuite([tests])"
# ...
# "If tests is given, it must be an iterable of individual test cases
# or other test suites that will be used to build the suite initially"
#
# TestSuite should deal with empty tests iterables by allowing the
# creation of an empty suite
def test_init__empty_tests(self):
suite = unittest.TestSuite([])
self.assertEqual(suite.countTestCases(), 0)
# "class TestSuite([tests])"
# ...
# "If tests is given, it must be an iterable of individual test cases
# or other test suites that will be used to build the suite initially"
#
# TestSuite should allow any iterable to provide tests
def test_init__tests_from_any_iterable(self):
def tests():
yield unittest.FunctionTestCase(lambda: None)
yield unittest.FunctionTestCase(lambda: None)
suite_1 = unittest.TestSuite(tests())
self.assertEqual(suite_1.countTestCases(), 2)
suite_2 = unittest.TestSuite(suite_1)
self.assertEqual(suite_2.countTestCases(), 2)
suite_3 = unittest.TestSuite(set(suite_1))
self.assertEqual(suite_3.countTestCases(), 2)
# "class TestSuite([tests])"
# ...
# "If tests is given, it must be an iterable of individual test cases
# or other test suites that will be used to build the suite initially"
#
# Does TestSuite() also allow other TestSuite() instances to be present
# in the tests iterable?
def test_init__TestSuite_instances_in_tests(self):
def tests():
ftc = unittest.FunctionTestCase(lambda: None)
yield unittest.TestSuite([ftc])
yield unittest.FunctionTestCase(lambda: None)
suite = unittest.TestSuite(tests())
self.assertEqual(suite.countTestCases(), 2)
################################################################
### /Tests for TestSuite.__init__
# Container types should support the iter protocol
def test_iter(self):
test1 = unittest.FunctionTestCase(lambda: None)
test2 = unittest.FunctionTestCase(lambda: None)
suite = unittest.TestSuite((test1, test2))
self.assertEqual(list(suite), [test1, test2])
# "Return the number of tests represented by the this test object.
# ...this method is also implemented by the TestSuite class, which can
# return larger [greater than 1] values"
#
# Presumably an empty TestSuite returns 0?
def test_countTestCases_zero_simple(self):
suite = unittest.TestSuite()
self.assertEqual(suite.countTestCases(), 0)
# "Return the number of tests represented by the this test object.
# ...this method is also implemented by the TestSuite class, which can
# return larger [greater than 1] values"
#
# Presumably an empty TestSuite (even if it contains other empty
# TestSuite instances) returns 0?
def test_countTestCases_zero_nested(self):
class Test1(unittest.TestCase):
def test(self):
pass
suite = unittest.TestSuite([unittest.TestSuite()])
self.assertEqual(suite.countTestCases(), 0)
# "Return the number of tests represented by the this test object.
# ...this method is also implemented by the TestSuite class, which can
# return larger [greater than 1] values"
def test_countTestCases_simple(self):
test1 = unittest.FunctionTestCase(lambda: None)
test2 = unittest.FunctionTestCase(lambda: None)
suite = unittest.TestSuite((test1, test2))
self.assertEqual(suite.countTestCases(), 2)
# "Return the number of tests represented by the this test object.
# ...this method is also implemented by the TestSuite class, which can
# return larger [greater than 1] values"
#
# Make sure this holds for nested TestSuite instances, too
def test_countTestCases_nested(self):
class Test1(unittest.TestCase):
def test1(self): pass
def test2(self): pass
test2 = unittest.FunctionTestCase(lambda: None)
test3 = unittest.FunctionTestCase(lambda: None)
child = unittest.TestSuite((Test1('test2'), test2))
parent = unittest.TestSuite((test3, child, Test1('test1')))
self.assertEqual(parent.countTestCases(), 4)
# "Run the tests associated with this suite, collecting the result into
# the test result object passed as result."
#
# And if there are no tests? What then?
def test_run__empty_suite(self):
events = []
result = LoggingResult(events)
suite = unittest.TestSuite()
suite.run(result)
self.assertEqual(events, [])
# "Note that unlike TestCase.run(), TestSuite.run() requires the
# "result object to be passed in."
def test_run__requires_result(self):
suite = unittest.TestSuite()
try:
suite.run()
except TypeError:
pass
else:
self.fail("Failed to raise TypeError")
# "Run the tests associated with this suite, collecting the result into
# the test result object passed as result."
def test_run(self):
events = []
result = LoggingResult(events)
class LoggingCase(unittest.TestCase):
def run(self, result):
events.append('run %s' % self._testMethodName)
def test1(self): pass
def test2(self): pass
tests = [LoggingCase('test1'), LoggingCase('test2')]
unittest.TestSuite(tests).run(result)
self.assertEqual(events, ['run test1', 'run test2'])
# "Add a TestCase ... to the suite"
def test_addTest__TestCase(self):
class Foo(unittest.TestCase):
def test(self): pass
test = Foo('test')
suite = unittest.TestSuite()
suite.addTest(test)
self.assertEqual(suite.countTestCases(), 1)
self.assertEqual(list(suite), [test])
# "Add a ... TestSuite to the suite"
def test_addTest__TestSuite(self):
class Foo(unittest.TestCase):
def test(self): pass
suite_2 = unittest.TestSuite([Foo('test')])
suite = unittest.TestSuite()
suite.addTest(suite_2)
self.assertEqual(suite.countTestCases(), 1)
self.assertEqual(list(suite), [suite_2])
# "Add all the tests from an iterable of TestCase and TestSuite
# instances to this test suite."
#
# "This is equivalent to iterating over tests, calling addTest() for
# each element"
def test_addTests(self):
class Foo(unittest.TestCase):
def test_1(self): pass
def test_2(self): pass
test_1 = Foo('test_1')
test_2 = Foo('test_2')
inner_suite = unittest.TestSuite([test_2])
def gen():
yield test_1
yield test_2
yield inner_suite
suite_1 = unittest.TestSuite()
suite_1.addTests(gen())
self.assertEqual(list(suite_1), list(gen()))
# "This is equivalent to iterating over tests, calling addTest() for
# each element"
suite_2 = unittest.TestSuite()
for t in gen():
suite_2.addTest(t)
self.assertEqual(suite_1, suite_2)
# "Add all the tests from an iterable of TestCase and TestSuite
# instances to this test suite."
#
# What happens if it doesn't get an iterable?
def test_addTest__noniterable(self):
suite = unittest.TestSuite()
try:
suite.addTests(5)
except TypeError:
pass
else:
self.fail("Failed to raise TypeError")
def test_addTest__noncallable(self):
suite = unittest.TestSuite()
self.assertRaises(TypeError, suite.addTest, 5)
def test_addTest__casesuiteclass(self):
suite = unittest.TestSuite()
self.assertRaises(TypeError, suite.addTest, Test_TestSuite)
self.assertRaises(TypeError, suite.addTest, unittest.TestSuite)
def test_addTests__string(self):
suite = unittest.TestSuite()
self.assertRaises(TypeError, suite.addTests, "foo")
def test_function_in_suite(self):
def f(_):
pass
suite = unittest.TestSuite()
suite.addTest(f)
# when the bug is fixed this line will not crash
suite.run(unittest.TestResult())
def test_basetestsuite(self):
class Test(unittest.TestCase):
wasSetUp = False
wasTornDown = False
@classmethod
def setUpClass(cls):
cls.wasSetUp = True
@classmethod
def tearDownClass(cls):
cls.wasTornDown = True
def testPass(self):
pass
def testFail(self):
fail
class Module(object):
wasSetUp = False
wasTornDown = False
@staticmethod
def setUpModule():
Module.wasSetUp = True
@staticmethod
def tearDownModule():
Module.wasTornDown = True
Test.__module__ = 'Module'
sys.modules['Module'] = Module
self.addCleanup(sys.modules.pop, 'Module')
suite = unittest.BaseTestSuite()
suite.addTests([Test('testPass'), Test('testFail')])
self.assertEqual(suite.countTestCases(), 2)
result = unittest.TestResult()
suite.run(result)
self.assertFalse(Module.wasSetUp)
self.assertFalse(Module.wasTornDown)
self.assertFalse(Test.wasSetUp)
self.assertFalse(Test.wasTornDown)
self.assertEqual(len(result.errors), 1)
self.assertEqual(len(result.failures), 0)
self.assertEqual(result.testsRun, 2)
def test_overriding_call(self):
class MySuite(unittest.TestSuite):
called = False
def __call__(self, *args, **kw):
self.called = True
unittest.TestSuite.__call__(self, *args, **kw)
suite = MySuite()
result = unittest.TestResult()
wrapper = unittest.TestSuite()
wrapper.addTest(suite)
wrapper(result)
self.assertTrue(suite.called)
# reusing results should be permitted even if abominable
self.assertFalse(result._testRunEntered)
if __name__ == '__main__':
unittest.main()
| gpl-3.0 |
traveloka/ansible | lib/ansible/modules/cloud/amazon/ec2_lc_facts.py | 23 | 7243 | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# This is a 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 Ansible library 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 library. If not, see <http://www.gnu.org/licenses/>.
ANSIBLE_METADATA = {'status': ['preview'],
'supported_by': 'community',
'version': '1.0'}
DOCUMENTATION = '''
---
module: ec2_lc_facts
short_description: Gather facts about AWS Autoscaling Launch Configurations
description:
- Gather facts about AWS Autoscaling Launch Configurations
version_added: "2.3"
author: "LoΓ―c Latreille (@psykotox)"
requirements: [ boto3 ]
options:
name:
description:
- A name or a list of name to match.
required: false
default: []
sort:
description:
- Optional attribute which with to sort the results.
choices: ['launch_configuration_name', 'image_id', 'created_time', 'instance_type', 'kernel_id', 'ramdisk_id', 'key_name']
default: null
required: false
sort_order:
description:
- Order in which to sort results.
- Only used when the 'sort' parameter is specified.
choices: ['ascending', 'descending']
default: 'ascending'
required: false
sort_start:
description:
- Which result to start with (when sorting).
- Corresponds to Python slice notation.
default: null
required: false
sort_end:
description:
- Which result to end with (when sorting).
- Corresponds to Python slice notation.
default: null
required: false
extends_documentation_fragment:
- aws
- ec2
'''
EXAMPLES = '''
# Note: These examples do not set authentication details, see the AWS Guide for details.
# Gather facts about all launch configurations
- ec2_lc_facts:
# Gather facts about launch configuration with name "example"
- ec2_lc_facts:
name: example
# Gather facts sorted by created_time from most recent to least recent
- ec2_lc_facts:
sort: created_time
sort_order: descending
'''
RETURN = '''
block_device_mapping:
description: Block device mapping for the instances of launch configuration
type: list of block devices
sample: "[{
'device_name': '/dev/xvda':,
'ebs': {
'delete_on_termination': true,
'volume_size': 8,
'volume_type': 'gp2'
}]"
classic_link_vpc_security_groups:
description: IDs of one or more security groups for the VPC specified in classic_link_vpc_id
type: string
sample:
created_time:
description: The creation date and time for the launch configuration
type: string
sample: "2016-05-27T13:47:44.216000+00:00"
ebs_optimized:
description: EBS I/O optimized (true ) or not (false )
type: bool
sample: true,
image_id:
description: ID of the Amazon Machine Image (AMI)
type: string
sample: "ami-12345678"
instance_monitoring:
description: Launched with detailed monitoring or not
type: dict
sample: "{
'enabled': true
}"
instance_type:
description: Instance type
type: string
sample: "t2.micro"
kernel_id:
description: ID of the kernel associated with the AMI
type: string
sample:
key_name:
description: Name of the key pair
type: string
sample: "user_app"
launch_configuration_arn:
description: Amazon Resource Name (ARN) of the launch configuration
type: string
sample: "arn:aws:autoscaling:us-east-1:666612345678:launchConfiguration:ba785e3a-dd42-6f02-4585-ea1a2b458b3d:launchConfigurationName/lc-app"
launch_configuration_name:
description: Name of the launch configuration
type: string
sample: "lc-app"
ramdisk_id:
description: ID of the RAM disk associated with the AMI
type: string
sample:
security_groups:
description: Security groups to associated
type: list
sample: "[
'web'
]"
user_data:
description: User data available
type: string
sample:
'''
try:
import boto3
from botocore.exceptions import ClientError, NoCredentialsError
HAS_BOTO3 = True
except ImportError:
HAS_BOTO3 = False
def list_launch_configs(connection, module):
launch_config_name = module.params.get("name")
sort = module.params.get('sort')
sort_order = module.params.get('sort_order')
sort_start = module.params.get('sort_start')
sort_end = module.params.get('sort_end')
try:
launch_configs = connection.describe_launch_configurations(LaunchConfigurationNames=launch_config_name)
except ClientError as e:
module.fail_json(msg=e.message)
snaked_launch_configs = []
for launch_config in launch_configs['LaunchConfigurations']:
snaked_launch_configs.append(camel_dict_to_snake_dict(launch_config))
for launch_config in snaked_launch_configs:
if 'CreatedTime' in launch_config:
launch_config['CreatedTime'] = str(launch_config['CreatedTime'])
if sort:
snaked_launch_configs.sort(key=lambda e: e[sort], reverse=(sort_order=='descending'))
try:
if sort and sort_start and sort_end:
snaked_launch_configs = snaked_launch_configs[int(sort_start):int(sort_end)]
elif sort and sort_start:
snaked_launch_configs = snaked_launch_configs[int(sort_start):]
elif sort and sort_end:
snaked_launch_configs = snaked_launch_configs[:int(sort_end)]
except TypeError:
module.fail_json(msg="Please supply numeric values for sort_start and/or sort_end")
module.exit_json(launch_configurations=snaked_launch_configs)
def main():
argument_spec = ec2_argument_spec()
argument_spec.update(
dict(
name = dict(required=False, default=[], type='list'),
sort = dict(required=False, default=None,
choices=['launch_configuration_name', 'image_id', 'created_time', 'instance_type', 'kernel_id', 'ramdisk_id', 'key_name']),
sort_order = dict(required=False, default='ascending',
choices=['ascending', 'descending']),
sort_start = dict(required=False),
sort_end = dict(required=False),
)
)
module = AnsibleModule(argument_spec=argument_spec)
if not HAS_BOTO3:
module.fail_json(msg='boto3 required for this module')
region, ec2_url, aws_connect_params = get_aws_connection_info(module, boto3=True)
if region:
connection = boto3_conn(module, conn_type='client', resource='autoscaling', region=region, endpoint=ec2_url, **aws_connect_params)
else:
module.fail_json(msg="region must be specified")
list_launch_configs(connection, module)
# import module snippets
from ansible.module_utils.basic import *
from ansible.module_utils.ec2 import *
if __name__ == '__main__':
main()
| gpl-3.0 |
WangYueFt/jieba | jieba/finalseg/__init__.py | 58 | 2709 | from __future__ import absolute_import, unicode_literals
import re
import os
import marshal
import sys
from .._compat import *
MIN_FLOAT = -3.14e100
PROB_START_P = "prob_start.p"
PROB_TRANS_P = "prob_trans.p"
PROB_EMIT_P = "prob_emit.p"
PrevStatus = {
'B': 'ES',
'M': 'MB',
'S': 'SE',
'E': 'BM'
}
def load_model():
_curpath = os.path.normpath(
os.path.join(os.getcwd(), os.path.dirname(__file__)))
start_p = {}
abs_path = os.path.join(_curpath, PROB_START_P)
with open(abs_path, 'rb') as f:
start_p = marshal.load(f)
trans_p = {}
abs_path = os.path.join(_curpath, PROB_TRANS_P)
with open(abs_path, 'rb') as f:
trans_p = marshal.load(f)
emit_p = {}
abs_path = os.path.join(_curpath, PROB_EMIT_P)
with open(abs_path, 'rb') as f:
emit_p = marshal.load(f)
return start_p, trans_p, emit_p
if sys.platform.startswith("java"):
start_P, trans_P, emit_P = load_model()
else:
from .prob_start import P as start_P
from .prob_trans import P as trans_P
from .prob_emit import P as emit_P
def viterbi(obs, states, start_p, trans_p, emit_p):
V = [{}] # tabular
path = {}
for y in states: # init
V[0][y] = start_p[y] + emit_p[y].get(obs[0], MIN_FLOAT)
path[y] = [y]
for t in xrange(1, len(obs)):
V.append({})
newpath = {}
for y in states:
em_p = emit_p[y].get(obs[t], MIN_FLOAT)
(prob, state) = max(
[(V[t - 1][y0] + trans_p[y0].get(y, MIN_FLOAT) + em_p, y0) for y0 in PrevStatus[y]])
V[t][y] = prob
newpath[y] = path[state] + [y]
path = newpath
(prob, state) = max((V[len(obs) - 1][y], y) for y in 'ES')
return (prob, path[state])
def __cut(sentence):
global emit_P
prob, pos_list = viterbi(sentence, 'BMES', start_P, trans_P, emit_P)
begin, nexti = 0, 0
# print pos_list, sentence
for i, char in enumerate(sentence):
pos = pos_list[i]
if pos == 'B':
begin = i
elif pos == 'E':
yield sentence[begin:i + 1]
nexti = i + 1
elif pos == 'S':
yield char
nexti = i + 1
if nexti < len(sentence):
yield sentence[nexti:]
re_han = re.compile("([\u4E00-\u9FA5]+)")
re_skip = re.compile("(\d+\.\d+|[a-zA-Z0-9]+)")
def cut(sentence):
sentence = strdecode(sentence)
blocks = re_han.split(sentence)
for blk in blocks:
if re_han.match(blk):
for word in __cut(blk):
yield word
else:
tmp = re_skip.split(blk)
for x in tmp:
if x:
yield x
| mit |
delving/nave | nave/void/migrations/0010_auto_20151111_1409.py | 1 | 5725 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import django.utils.timezone
import django_extensions.db.fields
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('contenttypes', '0002_remove_content_type_name'),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('void', '0009_auto_20151102_2135'),
]
operations = [
migrations.CreateModel(
name='ProxyMapping',
fields=[
('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True, serialize=False)),
('created', django_extensions.db.fields.CreationDateTimeField(default=django.utils.timezone.now, verbose_name='created', blank=True, editable=False)),
('modified', django_extensions.db.fields.ModificationDateTimeField(default=django.utils.timezone.now, verbose_name='modified', blank=True, editable=False)),
('user_uri', models.URLField()),
('proxy_resource_uri', models.URLField()),
('skos_concept_uri', models.URLField()),
('object_id', models.PositiveIntegerField(blank=True, null=True)),
('mapping_type', models.ForeignKey(blank=True, to='contenttypes.ContentType', null=True)),
],
options={
'verbose_name': 'Proxy Mapping',
'verbose_name_plural': 'Proxy Mappings',
},
),
migrations.CreateModel(
name='ProxyResource',
fields=[
('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True, serialize=False)),
('created', django_extensions.db.fields.CreationDateTimeField(default=django.utils.timezone.now, verbose_name='created', blank=True, editable=False)),
('modified', django_extensions.db.fields.ModificationDateTimeField(default=django.utils.timezone.now, verbose_name='modified', blank=True, editable=False)),
('proxy_uri', models.URLField(unique=True)),
('frequency', models.IntegerField(default=0)),
('label', models.TextField()),
('language', models.CharField(max_length=26, blank=True, null=True)),
],
options={
'verbose_name': 'Proxy Resource',
'verbose_name_plural': 'Proxy Resources',
},
),
migrations.CreateModel(
name='ProxyResourceField',
fields=[
('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True, serialize=False)),
('created', django_extensions.db.fields.CreationDateTimeField(default=django.utils.timezone.now, verbose_name='created', blank=True, editable=False)),
('modified', django_extensions.db.fields.ModificationDateTimeField(default=django.utils.timezone.now, verbose_name='modified', blank=True, editable=False)),
('property_uri', models.URLField()),
('search_label', models.CharField(max_length=56)),
('dataset_uri', models.URLField()),
],
options={
'verbose_name': 'Proxy Resource Field',
'verbose_name_plural': 'Proxy Resource Field',
},
),
migrations.AlterField(
model_name='dataset',
name='created',
field=django_extensions.db.fields.CreationDateTimeField(default=django.utils.timezone.now, verbose_name='created', blank=True, editable=False),
),
migrations.AlterField(
model_name='dataset',
name='modified',
field=django_extensions.db.fields.ModificationDateTimeField(default=django.utils.timezone.now, verbose_name='modified', blank=True, editable=False),
),
migrations.AlterField(
model_name='edmrecord',
name='created',
field=django_extensions.db.fields.CreationDateTimeField(default=django.utils.timezone.now, verbose_name='created', blank=True, editable=False),
),
migrations.AlterField(
model_name='edmrecord',
name='modified',
field=django_extensions.db.fields.ModificationDateTimeField(default=django.utils.timezone.now, verbose_name='modified', blank=True, editable=False),
),
migrations.AddField(
model_name='proxyresourcefield',
name='dataset',
field=models.ForeignKey(blank=True, to='void.DataSet', null=True),
),
migrations.AddField(
model_name='proxyresource',
name='dataset',
field=models.ForeignKey(to='void.DataSet'),
),
migrations.AddField(
model_name='proxyresource',
name='proxy_field',
field=models.ForeignKey(to='void.ProxyResourceField'),
),
migrations.AddField(
model_name='proxymapping',
name='proxy_resource',
field=models.ForeignKey(blank=True, to='void.ProxyResource', null=True),
),
migrations.AddField(
model_name='proxymapping',
name='user',
field=models.ForeignKey(blank=True, to=settings.AUTH_USER_MODEL, null=True),
),
migrations.AddField(
model_name='edmrecord',
name='proxy_resources',
field=models.ManyToManyField(to='void.ProxyResource'),
),
migrations.AlterUniqueTogether(
name='proxyresourcefield',
unique_together=set([('property_uri', 'dataset_uri')]),
),
]
| gpl-2.0 |
emergenzeHack/emergenzeHack.github.io | node_modules/node-gyp/gyp/pylib/gyp/mac_tool.py | 1569 | 23354 | #!/usr/bin/env python
# Copyright (c) 2012 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Utility functions to perform Xcode-style build steps.
These functions are executed via gyp-mac-tool when using the Makefile generator.
"""
import fcntl
import fnmatch
import glob
import json
import os
import plistlib
import re
import shutil
import string
import subprocess
import sys
import tempfile
def main(args):
executor = MacTool()
exit_code = executor.Dispatch(args)
if exit_code is not None:
sys.exit(exit_code)
class MacTool(object):
"""This class performs all the Mac tooling steps. The methods can either be
executed directly, or dispatched from an argument list."""
def Dispatch(self, args):
"""Dispatches a string command to a method."""
if len(args) < 1:
raise Exception("Not enough arguments")
method = "Exec%s" % self._CommandifyName(args[0])
return getattr(self, method)(*args[1:])
def _CommandifyName(self, name_string):
"""Transforms a tool name like copy-info-plist to CopyInfoPlist"""
return name_string.title().replace('-', '')
def ExecCopyBundleResource(self, source, dest, convert_to_binary):
"""Copies a resource file to the bundle/Resources directory, performing any
necessary compilation on each resource."""
extension = os.path.splitext(source)[1].lower()
if os.path.isdir(source):
# Copy tree.
# TODO(thakis): This copies file attributes like mtime, while the
# single-file branch below doesn't. This should probably be changed to
# be consistent with the single-file branch.
if os.path.exists(dest):
shutil.rmtree(dest)
shutil.copytree(source, dest)
elif extension == '.xib':
return self._CopyXIBFile(source, dest)
elif extension == '.storyboard':
return self._CopyXIBFile(source, dest)
elif extension == '.strings':
self._CopyStringsFile(source, dest, convert_to_binary)
else:
shutil.copy(source, dest)
def _CopyXIBFile(self, source, dest):
"""Compiles a XIB file with ibtool into a binary plist in the bundle."""
# ibtool sometimes crashes with relative paths. See crbug.com/314728.
base = os.path.dirname(os.path.realpath(__file__))
if os.path.relpath(source):
source = os.path.join(base, source)
if os.path.relpath(dest):
dest = os.path.join(base, dest)
args = ['xcrun', 'ibtool', '--errors', '--warnings', '--notices',
'--output-format', 'human-readable-text', '--compile', dest, source]
ibtool_section_re = re.compile(r'/\*.*\*/')
ibtool_re = re.compile(r'.*note:.*is clipping its content')
ibtoolout = subprocess.Popen(args, stdout=subprocess.PIPE)
current_section_header = None
for line in ibtoolout.stdout:
if ibtool_section_re.match(line):
current_section_header = line
elif not ibtool_re.match(line):
if current_section_header:
sys.stdout.write(current_section_header)
current_section_header = None
sys.stdout.write(line)
return ibtoolout.returncode
def _ConvertToBinary(self, dest):
subprocess.check_call([
'xcrun', 'plutil', '-convert', 'binary1', '-o', dest, dest])
def _CopyStringsFile(self, source, dest, convert_to_binary):
"""Copies a .strings file using iconv to reconvert the input into UTF-16."""
input_code = self._DetectInputEncoding(source) or "UTF-8"
# Xcode's CpyCopyStringsFile / builtin-copyStrings seems to call
# CFPropertyListCreateFromXMLData() behind the scenes; at least it prints
# CFPropertyListCreateFromXMLData(): Old-style plist parser: missing
# semicolon in dictionary.
# on invalid files. Do the same kind of validation.
import CoreFoundation
s = open(source, 'rb').read()
d = CoreFoundation.CFDataCreate(None, s, len(s))
_, error = CoreFoundation.CFPropertyListCreateFromXMLData(None, d, 0, None)
if error:
return
fp = open(dest, 'wb')
fp.write(s.decode(input_code).encode('UTF-16'))
fp.close()
if convert_to_binary == 'True':
self._ConvertToBinary(dest)
def _DetectInputEncoding(self, file_name):
"""Reads the first few bytes from file_name and tries to guess the text
encoding. Returns None as a guess if it can't detect it."""
fp = open(file_name, 'rb')
try:
header = fp.read(3)
except e:
fp.close()
return None
fp.close()
if header.startswith("\xFE\xFF"):
return "UTF-16"
elif header.startswith("\xFF\xFE"):
return "UTF-16"
elif header.startswith("\xEF\xBB\xBF"):
return "UTF-8"
else:
return None
def ExecCopyInfoPlist(self, source, dest, convert_to_binary, *keys):
"""Copies the |source| Info.plist to the destination directory |dest|."""
# Read the source Info.plist into memory.
fd = open(source, 'r')
lines = fd.read()
fd.close()
# Insert synthesized key/value pairs (e.g. BuildMachineOSBuild).
plist = plistlib.readPlistFromString(lines)
if keys:
plist = dict(plist.items() + json.loads(keys[0]).items())
lines = plistlib.writePlistToString(plist)
# Go through all the environment variables and replace them as variables in
# the file.
IDENT_RE = re.compile(r'[/\s]')
for key in os.environ:
if key.startswith('_'):
continue
evar = '${%s}' % key
evalue = os.environ[key]
lines = string.replace(lines, evar, evalue)
# Xcode supports various suffices on environment variables, which are
# all undocumented. :rfc1034identifier is used in the standard project
# template these days, and :identifier was used earlier. They are used to
# convert non-url characters into things that look like valid urls --
# except that the replacement character for :identifier, '_' isn't valid
# in a URL either -- oops, hence :rfc1034identifier was born.
evar = '${%s:identifier}' % key
evalue = IDENT_RE.sub('_', os.environ[key])
lines = string.replace(lines, evar, evalue)
evar = '${%s:rfc1034identifier}' % key
evalue = IDENT_RE.sub('-', os.environ[key])
lines = string.replace(lines, evar, evalue)
# Remove any keys with values that haven't been replaced.
lines = lines.split('\n')
for i in range(len(lines)):
if lines[i].strip().startswith("<string>${"):
lines[i] = None
lines[i - 1] = None
lines = '\n'.join(filter(lambda x: x is not None, lines))
# Write out the file with variables replaced.
fd = open(dest, 'w')
fd.write(lines)
fd.close()
# Now write out PkgInfo file now that the Info.plist file has been
# "compiled".
self._WritePkgInfo(dest)
if convert_to_binary == 'True':
self._ConvertToBinary(dest)
def _WritePkgInfo(self, info_plist):
"""This writes the PkgInfo file from the data stored in Info.plist."""
plist = plistlib.readPlist(info_plist)
if not plist:
return
# Only create PkgInfo for executable types.
package_type = plist['CFBundlePackageType']
if package_type != 'APPL':
return
# The format of PkgInfo is eight characters, representing the bundle type
# and bundle signature, each four characters. If that is missing, four
# '?' characters are used instead.
signature_code = plist.get('CFBundleSignature', '????')
if len(signature_code) != 4: # Wrong length resets everything, too.
signature_code = '?' * 4
dest = os.path.join(os.path.dirname(info_plist), 'PkgInfo')
fp = open(dest, 'w')
fp.write('%s%s' % (package_type, signature_code))
fp.close()
def ExecFlock(self, lockfile, *cmd_list):
"""Emulates the most basic behavior of Linux's flock(1)."""
# Rely on exception handling to report errors.
fd = os.open(lockfile, os.O_RDONLY|os.O_NOCTTY|os.O_CREAT, 0o666)
fcntl.flock(fd, fcntl.LOCK_EX)
return subprocess.call(cmd_list)
def ExecFilterLibtool(self, *cmd_list):
"""Calls libtool and filters out '/path/to/libtool: file: foo.o has no
symbols'."""
libtool_re = re.compile(r'^.*libtool: file: .* has no symbols$')
libtool_re5 = re.compile(
r'^.*libtool: warning for library: ' +
r'.* the table of contents is empty ' +
r'\(no object file members in the library define global symbols\)$')
env = os.environ.copy()
# Ref:
# http://www.opensource.apple.com/source/cctools/cctools-809/misc/libtool.c
# The problem with this flag is that it resets the file mtime on the file to
# epoch=0, e.g. 1970-1-1 or 1969-12-31 depending on timezone.
env['ZERO_AR_DATE'] = '1'
libtoolout = subprocess.Popen(cmd_list, stderr=subprocess.PIPE, env=env)
_, err = libtoolout.communicate()
for line in err.splitlines():
if not libtool_re.match(line) and not libtool_re5.match(line):
print >>sys.stderr, line
# Unconditionally touch the output .a file on the command line if present
# and the command succeeded. A bit hacky.
if not libtoolout.returncode:
for i in range(len(cmd_list) - 1):
if cmd_list[i] == "-o" and cmd_list[i+1].endswith('.a'):
os.utime(cmd_list[i+1], None)
break
return libtoolout.returncode
def ExecPackageFramework(self, framework, version):
"""Takes a path to Something.framework and the Current version of that and
sets up all the symlinks."""
# Find the name of the binary based on the part before the ".framework".
binary = os.path.basename(framework).split('.')[0]
CURRENT = 'Current'
RESOURCES = 'Resources'
VERSIONS = 'Versions'
if not os.path.exists(os.path.join(framework, VERSIONS, version, binary)):
# Binary-less frameworks don't seem to contain symlinks (see e.g.
# chromium's out/Debug/org.chromium.Chromium.manifest/ bundle).
return
# Move into the framework directory to set the symlinks correctly.
pwd = os.getcwd()
os.chdir(framework)
# Set up the Current version.
self._Relink(version, os.path.join(VERSIONS, CURRENT))
# Set up the root symlinks.
self._Relink(os.path.join(VERSIONS, CURRENT, binary), binary)
self._Relink(os.path.join(VERSIONS, CURRENT, RESOURCES), RESOURCES)
# Back to where we were before!
os.chdir(pwd)
def _Relink(self, dest, link):
"""Creates a symlink to |dest| named |link|. If |link| already exists,
it is overwritten."""
if os.path.lexists(link):
os.remove(link)
os.symlink(dest, link)
def ExecCompileXcassets(self, keys, *inputs):
"""Compiles multiple .xcassets files into a single .car file.
This invokes 'actool' to compile all the inputs .xcassets files. The
|keys| arguments is a json-encoded dictionary of extra arguments to
pass to 'actool' when the asset catalogs contains an application icon
or a launch image.
Note that 'actool' does not create the Assets.car file if the asset
catalogs does not contains imageset.
"""
command_line = [
'xcrun', 'actool', '--output-format', 'human-readable-text',
'--compress-pngs', '--notices', '--warnings', '--errors',
]
is_iphone_target = 'IPHONEOS_DEPLOYMENT_TARGET' in os.environ
if is_iphone_target:
platform = os.environ['CONFIGURATION'].split('-')[-1]
if platform not in ('iphoneos', 'iphonesimulator'):
platform = 'iphonesimulator'
command_line.extend([
'--platform', platform, '--target-device', 'iphone',
'--target-device', 'ipad', '--minimum-deployment-target',
os.environ['IPHONEOS_DEPLOYMENT_TARGET'], '--compile',
os.path.abspath(os.environ['CONTENTS_FOLDER_PATH']),
])
else:
command_line.extend([
'--platform', 'macosx', '--target-device', 'mac',
'--minimum-deployment-target', os.environ['MACOSX_DEPLOYMENT_TARGET'],
'--compile',
os.path.abspath(os.environ['UNLOCALIZED_RESOURCES_FOLDER_PATH']),
])
if keys:
keys = json.loads(keys)
for key, value in keys.iteritems():
arg_name = '--' + key
if isinstance(value, bool):
if value:
command_line.append(arg_name)
elif isinstance(value, list):
for v in value:
command_line.append(arg_name)
command_line.append(str(v))
else:
command_line.append(arg_name)
command_line.append(str(value))
# Note: actool crashes if inputs path are relative, so use os.path.abspath
# to get absolute path name for inputs.
command_line.extend(map(os.path.abspath, inputs))
subprocess.check_call(command_line)
def ExecMergeInfoPlist(self, output, *inputs):
"""Merge multiple .plist files into a single .plist file."""
merged_plist = {}
for path in inputs:
plist = self._LoadPlistMaybeBinary(path)
self._MergePlist(merged_plist, plist)
plistlib.writePlist(merged_plist, output)
def ExecCodeSignBundle(self, key, resource_rules, entitlements, provisioning):
"""Code sign a bundle.
This function tries to code sign an iOS bundle, following the same
algorithm as Xcode:
1. copy ResourceRules.plist from the user or the SDK into the bundle,
2. pick the provisioning profile that best match the bundle identifier,
and copy it into the bundle as embedded.mobileprovision,
3. copy Entitlements.plist from user or SDK next to the bundle,
4. code sign the bundle.
"""
resource_rules_path = self._InstallResourceRules(resource_rules)
substitutions, overrides = self._InstallProvisioningProfile(
provisioning, self._GetCFBundleIdentifier())
entitlements_path = self._InstallEntitlements(
entitlements, substitutions, overrides)
subprocess.check_call([
'codesign', '--force', '--sign', key, '--resource-rules',
resource_rules_path, '--entitlements', entitlements_path,
os.path.join(
os.environ['TARGET_BUILD_DIR'],
os.environ['FULL_PRODUCT_NAME'])])
def _InstallResourceRules(self, resource_rules):
"""Installs ResourceRules.plist from user or SDK into the bundle.
Args:
resource_rules: string, optional, path to the ResourceRules.plist file
to use, default to "${SDKROOT}/ResourceRules.plist"
Returns:
Path to the copy of ResourceRules.plist into the bundle.
"""
source_path = resource_rules
target_path = os.path.join(
os.environ['BUILT_PRODUCTS_DIR'],
os.environ['CONTENTS_FOLDER_PATH'],
'ResourceRules.plist')
if not source_path:
source_path = os.path.join(
os.environ['SDKROOT'], 'ResourceRules.plist')
shutil.copy2(source_path, target_path)
return target_path
def _InstallProvisioningProfile(self, profile, bundle_identifier):
"""Installs embedded.mobileprovision into the bundle.
Args:
profile: string, optional, short name of the .mobileprovision file
to use, if empty or the file is missing, the best file installed
will be used
bundle_identifier: string, value of CFBundleIdentifier from Info.plist
Returns:
A tuple containing two dictionary: variables substitutions and values
to overrides when generating the entitlements file.
"""
source_path, provisioning_data, team_id = self._FindProvisioningProfile(
profile, bundle_identifier)
target_path = os.path.join(
os.environ['BUILT_PRODUCTS_DIR'],
os.environ['CONTENTS_FOLDER_PATH'],
'embedded.mobileprovision')
shutil.copy2(source_path, target_path)
substitutions = self._GetSubstitutions(bundle_identifier, team_id + '.')
return substitutions, provisioning_data['Entitlements']
def _FindProvisioningProfile(self, profile, bundle_identifier):
"""Finds the .mobileprovision file to use for signing the bundle.
Checks all the installed provisioning profiles (or if the user specified
the PROVISIONING_PROFILE variable, only consult it) and select the most
specific that correspond to the bundle identifier.
Args:
profile: string, optional, short name of the .mobileprovision file
to use, if empty or the file is missing, the best file installed
will be used
bundle_identifier: string, value of CFBundleIdentifier from Info.plist
Returns:
A tuple of the path to the selected provisioning profile, the data of
the embedded plist in the provisioning profile and the team identifier
to use for code signing.
Raises:
SystemExit: if no .mobileprovision can be used to sign the bundle.
"""
profiles_dir = os.path.join(
os.environ['HOME'], 'Library', 'MobileDevice', 'Provisioning Profiles')
if not os.path.isdir(profiles_dir):
print >>sys.stderr, (
'cannot find mobile provisioning for %s' % bundle_identifier)
sys.exit(1)
provisioning_profiles = None
if profile:
profile_path = os.path.join(profiles_dir, profile + '.mobileprovision')
if os.path.exists(profile_path):
provisioning_profiles = [profile_path]
if not provisioning_profiles:
provisioning_profiles = glob.glob(
os.path.join(profiles_dir, '*.mobileprovision'))
valid_provisioning_profiles = {}
for profile_path in provisioning_profiles:
profile_data = self._LoadProvisioningProfile(profile_path)
app_id_pattern = profile_data.get(
'Entitlements', {}).get('application-identifier', '')
for team_identifier in profile_data.get('TeamIdentifier', []):
app_id = '%s.%s' % (team_identifier, bundle_identifier)
if fnmatch.fnmatch(app_id, app_id_pattern):
valid_provisioning_profiles[app_id_pattern] = (
profile_path, profile_data, team_identifier)
if not valid_provisioning_profiles:
print >>sys.stderr, (
'cannot find mobile provisioning for %s' % bundle_identifier)
sys.exit(1)
# If the user has multiple provisioning profiles installed that can be
# used for ${bundle_identifier}, pick the most specific one (ie. the
# provisioning profile whose pattern is the longest).
selected_key = max(valid_provisioning_profiles, key=lambda v: len(v))
return valid_provisioning_profiles[selected_key]
def _LoadProvisioningProfile(self, profile_path):
"""Extracts the plist embedded in a provisioning profile.
Args:
profile_path: string, path to the .mobileprovision file
Returns:
Content of the plist embedded in the provisioning profile as a dictionary.
"""
with tempfile.NamedTemporaryFile() as temp:
subprocess.check_call([
'security', 'cms', '-D', '-i', profile_path, '-o', temp.name])
return self._LoadPlistMaybeBinary(temp.name)
def _MergePlist(self, merged_plist, plist):
"""Merge |plist| into |merged_plist|."""
for key, value in plist.iteritems():
if isinstance(value, dict):
merged_value = merged_plist.get(key, {})
if isinstance(merged_value, dict):
self._MergePlist(merged_value, value)
merged_plist[key] = merged_value
else:
merged_plist[key] = value
else:
merged_plist[key] = value
def _LoadPlistMaybeBinary(self, plist_path):
"""Loads into a memory a plist possibly encoded in binary format.
This is a wrapper around plistlib.readPlist that tries to convert the
plist to the XML format if it can't be parsed (assuming that it is in
the binary format).
Args:
plist_path: string, path to a plist file, in XML or binary format
Returns:
Content of the plist as a dictionary.
"""
try:
# First, try to read the file using plistlib that only supports XML,
# and if an exception is raised, convert a temporary copy to XML and
# load that copy.
return plistlib.readPlist(plist_path)
except:
pass
with tempfile.NamedTemporaryFile() as temp:
shutil.copy2(plist_path, temp.name)
subprocess.check_call(['plutil', '-convert', 'xml1', temp.name])
return plistlib.readPlist(temp.name)
def _GetSubstitutions(self, bundle_identifier, app_identifier_prefix):
"""Constructs a dictionary of variable substitutions for Entitlements.plist.
Args:
bundle_identifier: string, value of CFBundleIdentifier from Info.plist
app_identifier_prefix: string, value for AppIdentifierPrefix
Returns:
Dictionary of substitutions to apply when generating Entitlements.plist.
"""
return {
'CFBundleIdentifier': bundle_identifier,
'AppIdentifierPrefix': app_identifier_prefix,
}
def _GetCFBundleIdentifier(self):
"""Extracts CFBundleIdentifier value from Info.plist in the bundle.
Returns:
Value of CFBundleIdentifier in the Info.plist located in the bundle.
"""
info_plist_path = os.path.join(
os.environ['TARGET_BUILD_DIR'],
os.environ['INFOPLIST_PATH'])
info_plist_data = self._LoadPlistMaybeBinary(info_plist_path)
return info_plist_data['CFBundleIdentifier']
def _InstallEntitlements(self, entitlements, substitutions, overrides):
"""Generates and install the ${BundleName}.xcent entitlements file.
Expands variables "$(variable)" pattern in the source entitlements file,
add extra entitlements defined in the .mobileprovision file and the copy
the generated plist to "${BundlePath}.xcent".
Args:
entitlements: string, optional, path to the Entitlements.plist template
to use, defaults to "${SDKROOT}/Entitlements.plist"
substitutions: dictionary, variable substitutions
overrides: dictionary, values to add to the entitlements
Returns:
Path to the generated entitlements file.
"""
source_path = entitlements
target_path = os.path.join(
os.environ['BUILT_PRODUCTS_DIR'],
os.environ['PRODUCT_NAME'] + '.xcent')
if not source_path:
source_path = os.path.join(
os.environ['SDKROOT'],
'Entitlements.plist')
shutil.copy2(source_path, target_path)
data = self._LoadPlistMaybeBinary(target_path)
data = self._ExpandVariables(data, substitutions)
if overrides:
for key in overrides:
if key not in data:
data[key] = overrides[key]
plistlib.writePlist(data, target_path)
return target_path
def _ExpandVariables(self, data, substitutions):
"""Expands variables "$(variable)" in data.
Args:
data: object, can be either string, list or dictionary
substitutions: dictionary, variable substitutions to perform
Returns:
Copy of data where each references to "$(variable)" has been replaced
by the corresponding value found in substitutions, or left intact if
the key was not found.
"""
if isinstance(data, str):
for key, value in substitutions.iteritems():
data = data.replace('$(%s)' % key, value)
return data
if isinstance(data, list):
return [self._ExpandVariables(v, substitutions) for v in data]
if isinstance(data, dict):
return {k: self._ExpandVariables(data[k], substitutions) for k in data}
return data
if __name__ == '__main__':
sys.exit(main(sys.argv[1:]))
| mit |
RossBrunton/django | django/contrib/gis/geos/prototypes/predicates.py | 339 | 1496 | """
This module houses the GEOS ctypes prototype functions for the
unary and binary predicate operations on geometries.
"""
from ctypes import c_char, c_char_p, c_double
from django.contrib.gis.geos.libgeos import GEOM_PTR, GEOSFuncFactory
from django.contrib.gis.geos.prototypes.errcheck import check_predicate
# ## Binary & unary predicate factories ##
class UnaryPredicate(GEOSFuncFactory):
"For GEOS unary predicate functions."
argtypes = [GEOM_PTR]
restype = c_char
errcheck = staticmethod(check_predicate)
class BinaryPredicate(UnaryPredicate):
"For GEOS binary predicate functions."
argtypes = [GEOM_PTR, GEOM_PTR]
# ## Unary Predicates ##
geos_hasz = UnaryPredicate('GEOSHasZ')
geos_isempty = UnaryPredicate('GEOSisEmpty')
geos_isring = UnaryPredicate('GEOSisRing')
geos_issimple = UnaryPredicate('GEOSisSimple')
geos_isvalid = UnaryPredicate('GEOSisValid')
# ## Binary Predicates ##
geos_contains = BinaryPredicate('GEOSContains')
geos_crosses = BinaryPredicate('GEOSCrosses')
geos_disjoint = BinaryPredicate('GEOSDisjoint')
geos_equals = BinaryPredicate('GEOSEquals')
geos_equalsexact = BinaryPredicate('GEOSEqualsExact', argtypes=[GEOM_PTR, GEOM_PTR, c_double])
geos_intersects = BinaryPredicate('GEOSIntersects')
geos_overlaps = BinaryPredicate('GEOSOverlaps')
geos_relatepattern = BinaryPredicate('GEOSRelatePattern', argtypes=[GEOM_PTR, GEOM_PTR, c_char_p])
geos_touches = BinaryPredicate('GEOSTouches')
geos_within = BinaryPredicate('GEOSWithin')
| bsd-3-clause |
MikeAmy/django | django/db/models/aggregates.py | 79 | 4984 | """
Classes to represent the definitions of aggregate functions.
"""
from django.core.exceptions import FieldError
from django.db.models.expressions import Func, Star
from django.db.models.fields import FloatField, IntegerField
__all__ = [
'Aggregate', 'Avg', 'Count', 'Max', 'Min', 'StdDev', 'Sum', 'Variance',
]
class Aggregate(Func):
contains_aggregate = True
name = None
def resolve_expression(self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False):
# Aggregates are not allowed in UPDATE queries, so ignore for_save
c = super(Aggregate, self).resolve_expression(query, allow_joins, reuse, summarize)
if not summarize:
expressions = c.get_source_expressions()
for index, expr in enumerate(expressions):
if expr.contains_aggregate:
before_resolved = self.get_source_expressions()[index]
name = before_resolved.name if hasattr(before_resolved, 'name') else repr(before_resolved)
raise FieldError("Cannot compute %s('%s'): '%s' is an aggregate" % (c.name, name, name))
return c
@property
def default_alias(self):
expressions = self.get_source_expressions()
if len(expressions) == 1 and hasattr(expressions[0], 'name'):
return '%s__%s' % (expressions[0].name, self.name.lower())
raise TypeError("Complex expressions require an alias")
def get_group_by_cols(self):
return []
class Avg(Aggregate):
function = 'AVG'
name = 'Avg'
def __init__(self, expression, **extra):
output_field = extra.pop('output_field', FloatField())
super(Avg, self).__init__(expression, output_field=output_field, **extra)
def as_oracle(self, compiler, connection):
if self.output_field.get_internal_type() == 'DurationField':
expression = self.get_source_expressions()[0]
from django.db.backends.oracle.functions import IntervalToSeconds, SecondsToInterval
return compiler.compile(
SecondsToInterval(Avg(IntervalToSeconds(expression)))
)
return super(Avg, self).as_sql(compiler, connection)
class Count(Aggregate):
function = 'COUNT'
name = 'Count'
template = '%(function)s(%(distinct)s%(expressions)s)'
def __init__(self, expression, distinct=False, **extra):
if expression == '*':
expression = Star()
super(Count, self).__init__(
expression, distinct='DISTINCT ' if distinct else '', output_field=IntegerField(), **extra)
def __repr__(self):
return "{}({}, distinct={})".format(
self.__class__.__name__,
self.arg_joiner.join(str(arg) for arg in self.source_expressions),
'False' if self.extra['distinct'] == '' else 'True',
)
def convert_value(self, value, expression, connection, context):
if value is None:
return 0
return int(value)
class Max(Aggregate):
function = 'MAX'
name = 'Max'
class Min(Aggregate):
function = 'MIN'
name = 'Min'
class StdDev(Aggregate):
name = 'StdDev'
def __init__(self, expression, sample=False, **extra):
self.function = 'STDDEV_SAMP' if sample else 'STDDEV_POP'
super(StdDev, self).__init__(expression, output_field=FloatField(), **extra)
def __repr__(self):
return "{}({}, sample={})".format(
self.__class__.__name__,
self.arg_joiner.join(str(arg) for arg in self.source_expressions),
'False' if self.function == 'STDDEV_POP' else 'True',
)
def convert_value(self, value, expression, connection, context):
if value is None:
return value
return float(value)
class Sum(Aggregate):
function = 'SUM'
name = 'Sum'
def as_oracle(self, compiler, connection):
if self.output_field.get_internal_type() == 'DurationField':
expression = self.get_source_expressions()[0]
from django.db.backends.oracle.functions import IntervalToSeconds, SecondsToInterval
return compiler.compile(
SecondsToInterval(Sum(IntervalToSeconds(expression)))
)
return super(Sum, self).as_sql(compiler, connection)
class Variance(Aggregate):
name = 'Variance'
def __init__(self, expression, sample=False, **extra):
self.function = 'VAR_SAMP' if sample else 'VAR_POP'
super(Variance, self).__init__(expression, output_field=FloatField(), **extra)
def __repr__(self):
return "{}({}, sample={})".format(
self.__class__.__name__,
self.arg_joiner.join(str(arg) for arg in self.source_expressions),
'False' if self.function == 'VAR_POP' else 'True',
)
def convert_value(self, value, expression, connection, context):
if value is None:
return value
return float(value)
| bsd-3-clause |
google/google-ctf | third_party/edk2/AppPkg/Applications/Python/Python-2.7.2/Lib/test/test_asyncore.py | 9 | 22912 | import asyncore
import unittest
import select
import os
import socket
import sys
import time
import warnings
import errno
from test import test_support
from test.test_support import TESTFN, run_unittest, unlink
from StringIO import StringIO
try:
import threading
except ImportError:
threading = None
HOST = test_support.HOST
class dummysocket:
def __init__(self):
self.closed = False
def close(self):
self.closed = True
def fileno(self):
return 42
class dummychannel:
def __init__(self):
self.socket = dummysocket()
def close(self):
self.socket.close()
class exitingdummy:
def __init__(self):
pass
def handle_read_event(self):
raise asyncore.ExitNow()
handle_write_event = handle_read_event
handle_close = handle_read_event
handle_expt_event = handle_read_event
class crashingdummy:
def __init__(self):
self.error_handled = False
def handle_read_event(self):
raise Exception()
handle_write_event = handle_read_event
handle_close = handle_read_event
handle_expt_event = handle_read_event
def handle_error(self):
self.error_handled = True
# used when testing senders; just collects what it gets until newline is sent
def capture_server(evt, buf, serv):
try:
serv.listen(5)
conn, addr = serv.accept()
except socket.timeout:
pass
else:
n = 200
while n > 0:
r, w, e = select.select([conn], [], [])
if r:
data = conn.recv(10)
# keep everything except for the newline terminator
buf.write(data.replace('\n', ''))
if '\n' in data:
break
n -= 1
time.sleep(0.01)
conn.close()
finally:
serv.close()
evt.set()
class HelperFunctionTests(unittest.TestCase):
def test_readwriteexc(self):
# Check exception handling behavior of read, write and _exception
# check that ExitNow exceptions in the object handler method
# bubbles all the way up through asyncore read/write/_exception calls
tr1 = exitingdummy()
self.assertRaises(asyncore.ExitNow, asyncore.read, tr1)
self.assertRaises(asyncore.ExitNow, asyncore.write, tr1)
self.assertRaises(asyncore.ExitNow, asyncore._exception, tr1)
# check that an exception other than ExitNow in the object handler
# method causes the handle_error method to get called
tr2 = crashingdummy()
asyncore.read(tr2)
self.assertEqual(tr2.error_handled, True)
tr2 = crashingdummy()
asyncore.write(tr2)
self.assertEqual(tr2.error_handled, True)
tr2 = crashingdummy()
asyncore._exception(tr2)
self.assertEqual(tr2.error_handled, True)
# asyncore.readwrite uses constants in the select module that
# are not present in Windows systems (see this thread:
# http://mail.python.org/pipermail/python-list/2001-October/109973.html)
# These constants should be present as long as poll is available
@unittest.skipUnless(hasattr(select, 'poll'), 'select.poll required')
def test_readwrite(self):
# Check that correct methods are called by readwrite()
attributes = ('read', 'expt', 'write', 'closed', 'error_handled')
expected = (
(select.POLLIN, 'read'),
(select.POLLPRI, 'expt'),
(select.POLLOUT, 'write'),
(select.POLLERR, 'closed'),
(select.POLLHUP, 'closed'),
(select.POLLNVAL, 'closed'),
)
class testobj:
def __init__(self):
self.read = False
self.write = False
self.closed = False
self.expt = False
self.error_handled = False
def handle_read_event(self):
self.read = True
def handle_write_event(self):
self.write = True
def handle_close(self):
self.closed = True
def handle_expt_event(self):
self.expt = True
def handle_error(self):
self.error_handled = True
for flag, expectedattr in expected:
tobj = testobj()
self.assertEqual(getattr(tobj, expectedattr), False)
asyncore.readwrite(tobj, flag)
# Only the attribute modified by the routine we expect to be
# called should be True.
for attr in attributes:
self.assertEqual(getattr(tobj, attr), attr==expectedattr)
# check that ExitNow exceptions in the object handler method
# bubbles all the way up through asyncore readwrite call
tr1 = exitingdummy()
self.assertRaises(asyncore.ExitNow, asyncore.readwrite, tr1, flag)
# check that an exception other than ExitNow in the object handler
# method causes the handle_error method to get called
tr2 = crashingdummy()
self.assertEqual(tr2.error_handled, False)
asyncore.readwrite(tr2, flag)
self.assertEqual(tr2.error_handled, True)
def test_closeall(self):
self.closeall_check(False)
def test_closeall_default(self):
self.closeall_check(True)
def closeall_check(self, usedefault):
# Check that close_all() closes everything in a given map
l = []
testmap = {}
for i in range(10):
c = dummychannel()
l.append(c)
self.assertEqual(c.socket.closed, False)
testmap[i] = c
if usedefault:
socketmap = asyncore.socket_map
try:
asyncore.socket_map = testmap
asyncore.close_all()
finally:
testmap, asyncore.socket_map = asyncore.socket_map, socketmap
else:
asyncore.close_all(testmap)
self.assertEqual(len(testmap), 0)
for c in l:
self.assertEqual(c.socket.closed, True)
def test_compact_traceback(self):
try:
raise Exception("I don't like spam!")
except:
real_t, real_v, real_tb = sys.exc_info()
r = asyncore.compact_traceback()
else:
self.fail("Expected exception")
(f, function, line), t, v, info = r
self.assertEqual(os.path.split(f)[-1], 'test_asyncore.py')
self.assertEqual(function, 'test_compact_traceback')
self.assertEqual(t, real_t)
self.assertEqual(v, real_v)
self.assertEqual(info, '[%s|%s|%s]' % (f, function, line))
class DispatcherTests(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
asyncore.close_all()
def test_basic(self):
d = asyncore.dispatcher()
self.assertEqual(d.readable(), True)
self.assertEqual(d.writable(), True)
def test_repr(self):
d = asyncore.dispatcher()
self.assertEqual(repr(d), '<asyncore.dispatcher at %#x>' % id(d))
def test_log(self):
d = asyncore.dispatcher()
# capture output of dispatcher.log() (to stderr)
fp = StringIO()
stderr = sys.stderr
l1 = "Lovely spam! Wonderful spam!"
l2 = "I don't like spam!"
try:
sys.stderr = fp
d.log(l1)
d.log(l2)
finally:
sys.stderr = stderr
lines = fp.getvalue().splitlines()
self.assertEqual(lines, ['log: %s' % l1, 'log: %s' % l2])
def test_log_info(self):
d = asyncore.dispatcher()
# capture output of dispatcher.log_info() (to stdout via print)
fp = StringIO()
stdout = sys.stdout
l1 = "Have you got anything without spam?"
l2 = "Why can't she have egg bacon spam and sausage?"
l3 = "THAT'S got spam in it!"
try:
sys.stdout = fp
d.log_info(l1, 'EGGS')
d.log_info(l2)
d.log_info(l3, 'SPAM')
finally:
sys.stdout = stdout
lines = fp.getvalue().splitlines()
expected = ['EGGS: %s' % l1, 'info: %s' % l2, 'SPAM: %s' % l3]
self.assertEqual(lines, expected)
def test_unhandled(self):
d = asyncore.dispatcher()
d.ignore_log_types = ()
# capture output of dispatcher.log_info() (to stdout via print)
fp = StringIO()
stdout = sys.stdout
try:
sys.stdout = fp
d.handle_expt()
d.handle_read()
d.handle_write()
d.handle_connect()
d.handle_accept()
finally:
sys.stdout = stdout
lines = fp.getvalue().splitlines()
expected = ['warning: unhandled incoming priority event',
'warning: unhandled read event',
'warning: unhandled write event',
'warning: unhandled connect event',
'warning: unhandled accept event']
self.assertEqual(lines, expected)
def test_issue_8594(self):
# XXX - this test is supposed to be removed in next major Python
# version
d = asyncore.dispatcher(socket.socket())
# make sure the error message no longer refers to the socket
# object but the dispatcher instance instead
self.assertRaisesRegexp(AttributeError, 'dispatcher instance',
getattr, d, 'foo')
# cheap inheritance with the underlying socket is supposed
# to still work but a DeprecationWarning is expected
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
family = d.family
self.assertEqual(family, socket.AF_INET)
self.assertEqual(len(w), 1)
self.assertTrue(issubclass(w[0].category, DeprecationWarning))
def test_strerror(self):
# refers to bug #8573
err = asyncore._strerror(errno.EPERM)
if hasattr(os, 'strerror'):
self.assertEqual(err, os.strerror(errno.EPERM))
err = asyncore._strerror(-1)
self.assertTrue(err != "")
class dispatcherwithsend_noread(asyncore.dispatcher_with_send):
def readable(self):
return False
def handle_connect(self):
pass
class DispatcherWithSendTests(unittest.TestCase):
usepoll = False
def setUp(self):
pass
def tearDown(self):
asyncore.close_all()
@unittest.skipUnless(threading, 'Threading required for this test.')
@test_support.reap_threads
def test_send(self):
evt = threading.Event()
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(3)
port = test_support.bind_port(sock)
cap = StringIO()
args = (evt, cap, sock)
t = threading.Thread(target=capture_server, args=args)
t.start()
try:
# wait a little longer for the server to initialize (it sometimes
# refuses connections on slow machines without this wait)
time.sleep(0.2)
data = "Suppose there isn't a 16-ton weight?"
d = dispatcherwithsend_noread()
d.create_socket(socket.AF_INET, socket.SOCK_STREAM)
d.connect((HOST, port))
# give time for socket to connect
time.sleep(0.1)
d.send(data)
d.send(data)
d.send('\n')
n = 1000
while d.out_buffer and n > 0:
asyncore.poll()
n -= 1
evt.wait()
self.assertEqual(cap.getvalue(), data*2)
finally:
t.join()
class DispatcherWithSendTests_UsePoll(DispatcherWithSendTests):
usepoll = True
@unittest.skipUnless(hasattr(asyncore, 'file_wrapper'),
'asyncore.file_wrapper required')
class FileWrapperTest(unittest.TestCase):
def setUp(self):
self.d = "It's not dead, it's sleeping!"
with file(TESTFN, 'w') as h:
h.write(self.d)
def tearDown(self):
unlink(TESTFN)
def test_recv(self):
fd = os.open(TESTFN, os.O_RDONLY)
w = asyncore.file_wrapper(fd)
os.close(fd)
self.assertNotEqual(w.fd, fd)
self.assertNotEqual(w.fileno(), fd)
self.assertEqual(w.recv(13), "It's not dead")
self.assertEqual(w.read(6), ", it's")
w.close()
self.assertRaises(OSError, w.read, 1)
def test_send(self):
d1 = "Come again?"
d2 = "I want to buy some cheese."
fd = os.open(TESTFN, os.O_WRONLY | os.O_APPEND)
w = asyncore.file_wrapper(fd)
os.close(fd)
w.write(d1)
w.send(d2)
w.close()
self.assertEqual(file(TESTFN).read(), self.d + d1 + d2)
@unittest.skipUnless(hasattr(asyncore, 'file_dispatcher'),
'asyncore.file_dispatcher required')
def test_dispatcher(self):
fd = os.open(TESTFN, os.O_RDONLY)
data = []
class FileDispatcher(asyncore.file_dispatcher):
def handle_read(self):
data.append(self.recv(29))
s = FileDispatcher(fd)
os.close(fd)
asyncore.loop(timeout=0.01, use_poll=True, count=2)
self.assertEqual(b"".join(data), self.d)
class BaseTestHandler(asyncore.dispatcher):
def __init__(self, sock=None):
asyncore.dispatcher.__init__(self, sock)
self.flag = False
def handle_accept(self):
raise Exception("handle_accept not supposed to be called")
def handle_connect(self):
raise Exception("handle_connect not supposed to be called")
def handle_expt(self):
raise Exception("handle_expt not supposed to be called")
def handle_close(self):
raise Exception("handle_close not supposed to be called")
def handle_error(self):
raise
class TCPServer(asyncore.dispatcher):
"""A server which listens on an address and dispatches the
connection to a handler.
"""
def __init__(self, handler=BaseTestHandler, host=HOST, port=0):
asyncore.dispatcher.__init__(self)
self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
self.set_reuse_addr()
self.bind((host, port))
self.listen(5)
self.handler = handler
@property
def address(self):
return self.socket.getsockname()[:2]
def handle_accept(self):
sock, addr = self.accept()
self.handler(sock)
def handle_error(self):
raise
class BaseClient(BaseTestHandler):
def __init__(self, address):
BaseTestHandler.__init__(self)
self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
self.connect(address)
def handle_connect(self):
pass
class BaseTestAPI(unittest.TestCase):
def tearDown(self):
asyncore.close_all()
def loop_waiting_for_flag(self, instance, timeout=5):
timeout = float(timeout) / 100
count = 100
while asyncore.socket_map and count > 0:
asyncore.loop(timeout=0.01, count=1, use_poll=self.use_poll)
if instance.flag:
return
count -= 1
time.sleep(timeout)
self.fail("flag not set")
def test_handle_connect(self):
# make sure handle_connect is called on connect()
class TestClient(BaseClient):
def handle_connect(self):
self.flag = True
server = TCPServer()
client = TestClient(server.address)
self.loop_waiting_for_flag(client)
def test_handle_accept(self):
# make sure handle_accept() is called when a client connects
class TestListener(BaseTestHandler):
def __init__(self):
BaseTestHandler.__init__(self)
self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
self.bind((HOST, 0))
self.listen(5)
self.address = self.socket.getsockname()[:2]
def handle_accept(self):
self.flag = True
server = TestListener()
client = BaseClient(server.address)
self.loop_waiting_for_flag(server)
def test_handle_read(self):
# make sure handle_read is called on data received
class TestClient(BaseClient):
def handle_read(self):
self.flag = True
class TestHandler(BaseTestHandler):
def __init__(self, conn):
BaseTestHandler.__init__(self, conn)
self.send('x' * 1024)
server = TCPServer(TestHandler)
client = TestClient(server.address)
self.loop_waiting_for_flag(client)
def test_handle_write(self):
# make sure handle_write is called
class TestClient(BaseClient):
def handle_write(self):
self.flag = True
server = TCPServer()
client = TestClient(server.address)
self.loop_waiting_for_flag(client)
def test_handle_close(self):
# make sure handle_close is called when the other end closes
# the connection
class TestClient(BaseClient):
def handle_read(self):
# in order to make handle_close be called we are supposed
# to make at least one recv() call
self.recv(1024)
def handle_close(self):
self.flag = True
self.close()
class TestHandler(BaseTestHandler):
def __init__(self, conn):
BaseTestHandler.__init__(self, conn)
self.close()
server = TCPServer(TestHandler)
client = TestClient(server.address)
self.loop_waiting_for_flag(client)
@unittest.skipIf(sys.platform.startswith("sunos"),
"OOB support is broken on Solaris")
def test_handle_expt(self):
# Make sure handle_expt is called on OOB data received.
# Note: this might fail on some platforms as OOB data is
# tenuously supported and rarely used.
class TestClient(BaseClient):
def handle_expt(self):
self.flag = True
class TestHandler(BaseTestHandler):
def __init__(self, conn):
BaseTestHandler.__init__(self, conn)
self.socket.send(chr(244), socket.MSG_OOB)
server = TCPServer(TestHandler)
client = TestClient(server.address)
self.loop_waiting_for_flag(client)
def test_handle_error(self):
class TestClient(BaseClient):
def handle_write(self):
1.0 / 0
def handle_error(self):
self.flag = True
try:
raise
except ZeroDivisionError:
pass
else:
raise Exception("exception not raised")
server = TCPServer()
client = TestClient(server.address)
self.loop_waiting_for_flag(client)
def test_connection_attributes(self):
server = TCPServer()
client = BaseClient(server.address)
# we start disconnected
self.assertFalse(server.connected)
self.assertTrue(server.accepting)
# this can't be taken for granted across all platforms
#self.assertFalse(client.connected)
self.assertFalse(client.accepting)
# execute some loops so that client connects to server
asyncore.loop(timeout=0.01, use_poll=self.use_poll, count=100)
self.assertFalse(server.connected)
self.assertTrue(server.accepting)
self.assertTrue(client.connected)
self.assertFalse(client.accepting)
# disconnect the client
client.close()
self.assertFalse(server.connected)
self.assertTrue(server.accepting)
self.assertFalse(client.connected)
self.assertFalse(client.accepting)
# stop serving
server.close()
self.assertFalse(server.connected)
self.assertFalse(server.accepting)
def test_create_socket(self):
s = asyncore.dispatcher()
s.create_socket(socket.AF_INET, socket.SOCK_STREAM)
self.assertEqual(s.socket.family, socket.AF_INET)
self.assertEqual(s.socket.type, socket.SOCK_STREAM)
def test_bind(self):
s1 = asyncore.dispatcher()
s1.create_socket(socket.AF_INET, socket.SOCK_STREAM)
s1.bind((HOST, 0))
s1.listen(5)
port = s1.socket.getsockname()[1]
s2 = asyncore.dispatcher()
s2.create_socket(socket.AF_INET, socket.SOCK_STREAM)
# EADDRINUSE indicates the socket was correctly bound
self.assertRaises(socket.error, s2.bind, (HOST, port))
def test_set_reuse_addr(self):
sock = socket.socket()
try:
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
except socket.error:
unittest.skip("SO_REUSEADDR not supported on this platform")
else:
# if SO_REUSEADDR succeeded for sock we expect asyncore
# to do the same
s = asyncore.dispatcher(socket.socket())
self.assertFalse(s.socket.getsockopt(socket.SOL_SOCKET,
socket.SO_REUSEADDR))
s.create_socket(socket.AF_INET, socket.SOCK_STREAM)
s.set_reuse_addr()
self.assertTrue(s.socket.getsockopt(socket.SOL_SOCKET,
socket.SO_REUSEADDR))
finally:
sock.close()
class TestAPI_UseSelect(BaseTestAPI):
use_poll = False
@unittest.skipUnless(hasattr(select, 'poll'), 'select.poll required')
class TestAPI_UsePoll(BaseTestAPI):
use_poll = True
def test_main():
tests = [HelperFunctionTests, DispatcherTests, DispatcherWithSendTests,
DispatcherWithSendTests_UsePoll, TestAPI_UseSelect,
TestAPI_UsePoll, FileWrapperTest]
run_unittest(*tests)
if __name__ == "__main__":
test_main()
| apache-2.0 |
mdworks2016/work_development | Python/20_Third_Certification/venv/lib/python3.7/site-packages/pip/_vendor/msgpack/fallback.py | 21 | 37133 | """Fallback pure Python implementation of msgpack"""
from datetime import datetime as _DateTime
import sys
import struct
PY2 = sys.version_info[0] == 2
if PY2:
int_types = (int, long)
def dict_iteritems(d):
return d.iteritems()
else:
int_types = int
unicode = str
xrange = range
def dict_iteritems(d):
return d.items()
if sys.version_info < (3, 5):
# Ugly hack...
RecursionError = RuntimeError
def _is_recursionerror(e):
return (
len(e.args) == 1
and isinstance(e.args[0], str)
and e.args[0].startswith("maximum recursion depth exceeded")
)
else:
def _is_recursionerror(e):
return True
if hasattr(sys, "pypy_version_info"):
# StringIO is slow on PyPy, StringIO is faster. However: PyPy's own
# StringBuilder is fastest.
from __pypy__ import newlist_hint
try:
from __pypy__.builders import BytesBuilder as StringBuilder
except ImportError:
from __pypy__.builders import StringBuilder
USING_STRINGBUILDER = True
class StringIO(object):
def __init__(self, s=b""):
if s:
self.builder = StringBuilder(len(s))
self.builder.append(s)
else:
self.builder = StringBuilder()
def write(self, s):
if isinstance(s, memoryview):
s = s.tobytes()
elif isinstance(s, bytearray):
s = bytes(s)
self.builder.append(s)
def getvalue(self):
return self.builder.build()
else:
USING_STRINGBUILDER = False
from io import BytesIO as StringIO
newlist_hint = lambda size: []
from .exceptions import BufferFull, OutOfData, ExtraData, FormatError, StackError
from .ext import ExtType, Timestamp
EX_SKIP = 0
EX_CONSTRUCT = 1
EX_READ_ARRAY_HEADER = 2
EX_READ_MAP_HEADER = 3
TYPE_IMMEDIATE = 0
TYPE_ARRAY = 1
TYPE_MAP = 2
TYPE_RAW = 3
TYPE_BIN = 4
TYPE_EXT = 5
DEFAULT_RECURSE_LIMIT = 511
def _check_type_strict(obj, t, type=type, tuple=tuple):
if type(t) is tuple:
return type(obj) in t
else:
return type(obj) is t
def _get_data_from_buffer(obj):
view = memoryview(obj)
if view.itemsize != 1:
raise ValueError("cannot unpack from multi-byte object")
return view
def unpackb(packed, **kwargs):
"""
Unpack an object from `packed`.
Raises ``ExtraData`` when *packed* contains extra bytes.
Raises ``ValueError`` when *packed* is incomplete.
Raises ``FormatError`` when *packed* is not valid msgpack.
Raises ``StackError`` when *packed* contains too nested.
Other exceptions can be raised during unpacking.
See :class:`Unpacker` for options.
"""
unpacker = Unpacker(None, max_buffer_size=len(packed), **kwargs)
unpacker.feed(packed)
try:
ret = unpacker._unpack()
except OutOfData:
raise ValueError("Unpack failed: incomplete input")
except RecursionError as e:
if _is_recursionerror(e):
raise StackError
raise
if unpacker._got_extradata():
raise ExtraData(ret, unpacker._get_extradata())
return ret
if sys.version_info < (2, 7, 6):
def _unpack_from(f, b, o=0):
"""Explicit type cast for legacy struct.unpack_from"""
return struct.unpack_from(f, bytes(b), o)
else:
_unpack_from = struct.unpack_from
class Unpacker(object):
"""Streaming unpacker.
Arguments:
:param file_like:
File-like object having `.read(n)` method.
If specified, unpacker reads serialized data from it and :meth:`feed()` is not usable.
:param int read_size:
Used as `file_like.read(read_size)`. (default: `min(16*1024, max_buffer_size)`)
:param bool use_list:
If true, unpack msgpack array to Python list.
Otherwise, unpack to Python tuple. (default: True)
:param bool raw:
If true, unpack msgpack raw to Python bytes.
Otherwise, unpack to Python str by decoding with UTF-8 encoding (default).
:param int timestamp:
Control how timestamp type is unpacked:
0 - Timestamp
1 - float (Seconds from the EPOCH)
2 - int (Nanoseconds from the EPOCH)
3 - datetime.datetime (UTC). Python 2 is not supported.
:param bool strict_map_key:
If true (default), only str or bytes are accepted for map (dict) keys.
:param callable object_hook:
When specified, it should be callable.
Unpacker calls it with a dict argument after unpacking msgpack map.
(See also simplejson)
:param callable object_pairs_hook:
When specified, it should be callable.
Unpacker calls it with a list of key-value pairs after unpacking msgpack map.
(See also simplejson)
:param str unicode_errors:
The error handler for decoding unicode. (default: 'strict')
This option should be used only when you have msgpack data which
contains invalid UTF-8 string.
:param int max_buffer_size:
Limits size of data waiting unpacked. 0 means 2**32-1.
The default value is 100*1024*1024 (100MiB).
Raises `BufferFull` exception when it is insufficient.
You should set this parameter when unpacking data from untrusted source.
:param int max_str_len:
Deprecated, use *max_buffer_size* instead.
Limits max length of str. (default: max_buffer_size)
:param int max_bin_len:
Deprecated, use *max_buffer_size* instead.
Limits max length of bin. (default: max_buffer_size)
:param int max_array_len:
Limits max length of array.
(default: max_buffer_size)
:param int max_map_len:
Limits max length of map.
(default: max_buffer_size//2)
:param int max_ext_len:
Deprecated, use *max_buffer_size* instead.
Limits max size of ext type. (default: max_buffer_size)
Example of streaming deserialize from file-like object::
unpacker = Unpacker(file_like)
for o in unpacker:
process(o)
Example of streaming deserialize from socket::
unpacker = Unpacker(max_buffer_size)
while True:
buf = sock.recv(1024**2)
if not buf:
break
unpacker.feed(buf)
for o in unpacker:
process(o)
Raises ``ExtraData`` when *packed* contains extra bytes.
Raises ``OutOfData`` when *packed* is incomplete.
Raises ``FormatError`` when *packed* is not valid msgpack.
Raises ``StackError`` when *packed* contains too nested.
Other exceptions can be raised during unpacking.
"""
def __init__(
self,
file_like=None,
read_size=0,
use_list=True,
raw=False,
timestamp=0,
strict_map_key=True,
object_hook=None,
object_pairs_hook=None,
list_hook=None,
unicode_errors=None,
max_buffer_size=100 * 1024 * 1024,
ext_hook=ExtType,
max_str_len=-1,
max_bin_len=-1,
max_array_len=-1,
max_map_len=-1,
max_ext_len=-1,
):
if unicode_errors is None:
unicode_errors = "strict"
if file_like is None:
self._feeding = True
else:
if not callable(file_like.read):
raise TypeError("`file_like.read` must be callable")
self.file_like = file_like
self._feeding = False
#: array of bytes fed.
self._buffer = bytearray()
#: Which position we currently reads
self._buff_i = 0
# When Unpacker is used as an iterable, between the calls to next(),
# the buffer is not "consumed" completely, for efficiency sake.
# Instead, it is done sloppily. To make sure we raise BufferFull at
# the correct moments, we have to keep track of how sloppy we were.
# Furthermore, when the buffer is incomplete (that is: in the case
# we raise an OutOfData) we need to rollback the buffer to the correct
# state, which _buf_checkpoint records.
self._buf_checkpoint = 0
if not max_buffer_size:
max_buffer_size = 2 ** 31 - 1
if max_str_len == -1:
max_str_len = max_buffer_size
if max_bin_len == -1:
max_bin_len = max_buffer_size
if max_array_len == -1:
max_array_len = max_buffer_size
if max_map_len == -1:
max_map_len = max_buffer_size // 2
if max_ext_len == -1:
max_ext_len = max_buffer_size
self._max_buffer_size = max_buffer_size
if read_size > self._max_buffer_size:
raise ValueError("read_size must be smaller than max_buffer_size")
self._read_size = read_size or min(self._max_buffer_size, 16 * 1024)
self._raw = bool(raw)
self._strict_map_key = bool(strict_map_key)
self._unicode_errors = unicode_errors
self._use_list = use_list
if not (0 <= timestamp <= 3):
raise ValueError("timestamp must be 0..3")
self._timestamp = timestamp
self._list_hook = list_hook
self._object_hook = object_hook
self._object_pairs_hook = object_pairs_hook
self._ext_hook = ext_hook
self._max_str_len = max_str_len
self._max_bin_len = max_bin_len
self._max_array_len = max_array_len
self._max_map_len = max_map_len
self._max_ext_len = max_ext_len
self._stream_offset = 0
if list_hook is not None and not callable(list_hook):
raise TypeError("`list_hook` is not callable")
if object_hook is not None and not callable(object_hook):
raise TypeError("`object_hook` is not callable")
if object_pairs_hook is not None and not callable(object_pairs_hook):
raise TypeError("`object_pairs_hook` is not callable")
if object_hook is not None and object_pairs_hook is not None:
raise TypeError(
"object_pairs_hook and object_hook are mutually " "exclusive"
)
if not callable(ext_hook):
raise TypeError("`ext_hook` is not callable")
def feed(self, next_bytes):
assert self._feeding
view = _get_data_from_buffer(next_bytes)
if len(self._buffer) - self._buff_i + len(view) > self._max_buffer_size:
raise BufferFull
# Strip buffer before checkpoint before reading file.
if self._buf_checkpoint > 0:
del self._buffer[: self._buf_checkpoint]
self._buff_i -= self._buf_checkpoint
self._buf_checkpoint = 0
# Use extend here: INPLACE_ADD += doesn't reliably typecast memoryview in jython
self._buffer.extend(view)
def _consume(self):
""" Gets rid of the used parts of the buffer. """
self._stream_offset += self._buff_i - self._buf_checkpoint
self._buf_checkpoint = self._buff_i
def _got_extradata(self):
return self._buff_i < len(self._buffer)
def _get_extradata(self):
return self._buffer[self._buff_i :]
def read_bytes(self, n):
ret = self._read(n)
self._consume()
return ret
def _read(self, n):
# (int) -> bytearray
self._reserve(n)
i = self._buff_i
self._buff_i = i + n
return self._buffer[i : i + n]
def _reserve(self, n):
remain_bytes = len(self._buffer) - self._buff_i - n
# Fast path: buffer has n bytes already
if remain_bytes >= 0:
return
if self._feeding:
self._buff_i = self._buf_checkpoint
raise OutOfData
# Strip buffer before checkpoint before reading file.
if self._buf_checkpoint > 0:
del self._buffer[: self._buf_checkpoint]
self._buff_i -= self._buf_checkpoint
self._buf_checkpoint = 0
# Read from file
remain_bytes = -remain_bytes
while remain_bytes > 0:
to_read_bytes = max(self._read_size, remain_bytes)
read_data = self.file_like.read(to_read_bytes)
if not read_data:
break
assert isinstance(read_data, bytes)
self._buffer += read_data
remain_bytes -= len(read_data)
if len(self._buffer) < n + self._buff_i:
self._buff_i = 0 # rollback
raise OutOfData
def _read_header(self, execute=EX_CONSTRUCT):
typ = TYPE_IMMEDIATE
n = 0
obj = None
self._reserve(1)
b = self._buffer[self._buff_i]
self._buff_i += 1
if b & 0b10000000 == 0:
obj = b
elif b & 0b11100000 == 0b11100000:
obj = -1 - (b ^ 0xFF)
elif b & 0b11100000 == 0b10100000:
n = b & 0b00011111
typ = TYPE_RAW
if n > self._max_str_len:
raise ValueError("%s exceeds max_str_len(%s)", n, self._max_str_len)
obj = self._read(n)
elif b & 0b11110000 == 0b10010000:
n = b & 0b00001111
typ = TYPE_ARRAY
if n > self._max_array_len:
raise ValueError("%s exceeds max_array_len(%s)", n, self._max_array_len)
elif b & 0b11110000 == 0b10000000:
n = b & 0b00001111
typ = TYPE_MAP
if n > self._max_map_len:
raise ValueError("%s exceeds max_map_len(%s)", n, self._max_map_len)
elif b == 0xC0:
obj = None
elif b == 0xC2:
obj = False
elif b == 0xC3:
obj = True
elif b == 0xC4:
typ = TYPE_BIN
self._reserve(1)
n = self._buffer[self._buff_i]
self._buff_i += 1
if n > self._max_bin_len:
raise ValueError("%s exceeds max_bin_len(%s)" % (n, self._max_bin_len))
obj = self._read(n)
elif b == 0xC5:
typ = TYPE_BIN
self._reserve(2)
n = _unpack_from(">H", self._buffer, self._buff_i)[0]
self._buff_i += 2
if n > self._max_bin_len:
raise ValueError("%s exceeds max_bin_len(%s)" % (n, self._max_bin_len))
obj = self._read(n)
elif b == 0xC6:
typ = TYPE_BIN
self._reserve(4)
n = _unpack_from(">I", self._buffer, self._buff_i)[0]
self._buff_i += 4
if n > self._max_bin_len:
raise ValueError("%s exceeds max_bin_len(%s)" % (n, self._max_bin_len))
obj = self._read(n)
elif b == 0xC7: # ext 8
typ = TYPE_EXT
self._reserve(2)
L, n = _unpack_from("Bb", self._buffer, self._buff_i)
self._buff_i += 2
if L > self._max_ext_len:
raise ValueError("%s exceeds max_ext_len(%s)" % (L, self._max_ext_len))
obj = self._read(L)
elif b == 0xC8: # ext 16
typ = TYPE_EXT
self._reserve(3)
L, n = _unpack_from(">Hb", self._buffer, self._buff_i)
self._buff_i += 3
if L > self._max_ext_len:
raise ValueError("%s exceeds max_ext_len(%s)" % (L, self._max_ext_len))
obj = self._read(L)
elif b == 0xC9: # ext 32
typ = TYPE_EXT
self._reserve(5)
L, n = _unpack_from(">Ib", self._buffer, self._buff_i)
self._buff_i += 5
if L > self._max_ext_len:
raise ValueError("%s exceeds max_ext_len(%s)" % (L, self._max_ext_len))
obj = self._read(L)
elif b == 0xCA:
self._reserve(4)
obj = _unpack_from(">f", self._buffer, self._buff_i)[0]
self._buff_i += 4
elif b == 0xCB:
self._reserve(8)
obj = _unpack_from(">d", self._buffer, self._buff_i)[0]
self._buff_i += 8
elif b == 0xCC:
self._reserve(1)
obj = self._buffer[self._buff_i]
self._buff_i += 1
elif b == 0xCD:
self._reserve(2)
obj = _unpack_from(">H", self._buffer, self._buff_i)[0]
self._buff_i += 2
elif b == 0xCE:
self._reserve(4)
obj = _unpack_from(">I", self._buffer, self._buff_i)[0]
self._buff_i += 4
elif b == 0xCF:
self._reserve(8)
obj = _unpack_from(">Q", self._buffer, self._buff_i)[0]
self._buff_i += 8
elif b == 0xD0:
self._reserve(1)
obj = _unpack_from("b", self._buffer, self._buff_i)[0]
self._buff_i += 1
elif b == 0xD1:
self._reserve(2)
obj = _unpack_from(">h", self._buffer, self._buff_i)[0]
self._buff_i += 2
elif b == 0xD2:
self._reserve(4)
obj = _unpack_from(">i", self._buffer, self._buff_i)[0]
self._buff_i += 4
elif b == 0xD3:
self._reserve(8)
obj = _unpack_from(">q", self._buffer, self._buff_i)[0]
self._buff_i += 8
elif b == 0xD4: # fixext 1
typ = TYPE_EXT
if self._max_ext_len < 1:
raise ValueError("%s exceeds max_ext_len(%s)" % (1, self._max_ext_len))
self._reserve(2)
n, obj = _unpack_from("b1s", self._buffer, self._buff_i)
self._buff_i += 2
elif b == 0xD5: # fixext 2
typ = TYPE_EXT
if self._max_ext_len < 2:
raise ValueError("%s exceeds max_ext_len(%s)" % (2, self._max_ext_len))
self._reserve(3)
n, obj = _unpack_from("b2s", self._buffer, self._buff_i)
self._buff_i += 3
elif b == 0xD6: # fixext 4
typ = TYPE_EXT
if self._max_ext_len < 4:
raise ValueError("%s exceeds max_ext_len(%s)" % (4, self._max_ext_len))
self._reserve(5)
n, obj = _unpack_from("b4s", self._buffer, self._buff_i)
self._buff_i += 5
elif b == 0xD7: # fixext 8
typ = TYPE_EXT
if self._max_ext_len < 8:
raise ValueError("%s exceeds max_ext_len(%s)" % (8, self._max_ext_len))
self._reserve(9)
n, obj = _unpack_from("b8s", self._buffer, self._buff_i)
self._buff_i += 9
elif b == 0xD8: # fixext 16
typ = TYPE_EXT
if self._max_ext_len < 16:
raise ValueError("%s exceeds max_ext_len(%s)" % (16, self._max_ext_len))
self._reserve(17)
n, obj = _unpack_from("b16s", self._buffer, self._buff_i)
self._buff_i += 17
elif b == 0xD9:
typ = TYPE_RAW
self._reserve(1)
n = self._buffer[self._buff_i]
self._buff_i += 1
if n > self._max_str_len:
raise ValueError("%s exceeds max_str_len(%s)", n, self._max_str_len)
obj = self._read(n)
elif b == 0xDA:
typ = TYPE_RAW
self._reserve(2)
(n,) = _unpack_from(">H", self._buffer, self._buff_i)
self._buff_i += 2
if n > self._max_str_len:
raise ValueError("%s exceeds max_str_len(%s)", n, self._max_str_len)
obj = self._read(n)
elif b == 0xDB:
typ = TYPE_RAW
self._reserve(4)
(n,) = _unpack_from(">I", self._buffer, self._buff_i)
self._buff_i += 4
if n > self._max_str_len:
raise ValueError("%s exceeds max_str_len(%s)", n, self._max_str_len)
obj = self._read(n)
elif b == 0xDC:
typ = TYPE_ARRAY
self._reserve(2)
(n,) = _unpack_from(">H", self._buffer, self._buff_i)
self._buff_i += 2
if n > self._max_array_len:
raise ValueError("%s exceeds max_array_len(%s)", n, self._max_array_len)
elif b == 0xDD:
typ = TYPE_ARRAY
self._reserve(4)
(n,) = _unpack_from(">I", self._buffer, self._buff_i)
self._buff_i += 4
if n > self._max_array_len:
raise ValueError("%s exceeds max_array_len(%s)", n, self._max_array_len)
elif b == 0xDE:
self._reserve(2)
(n,) = _unpack_from(">H", self._buffer, self._buff_i)
self._buff_i += 2
if n > self._max_map_len:
raise ValueError("%s exceeds max_map_len(%s)", n, self._max_map_len)
typ = TYPE_MAP
elif b == 0xDF:
self._reserve(4)
(n,) = _unpack_from(">I", self._buffer, self._buff_i)
self._buff_i += 4
if n > self._max_map_len:
raise ValueError("%s exceeds max_map_len(%s)", n, self._max_map_len)
typ = TYPE_MAP
else:
raise FormatError("Unknown header: 0x%x" % b)
return typ, n, obj
def _unpack(self, execute=EX_CONSTRUCT):
typ, n, obj = self._read_header(execute)
if execute == EX_READ_ARRAY_HEADER:
if typ != TYPE_ARRAY:
raise ValueError("Expected array")
return n
if execute == EX_READ_MAP_HEADER:
if typ != TYPE_MAP:
raise ValueError("Expected map")
return n
# TODO should we eliminate the recursion?
if typ == TYPE_ARRAY:
if execute == EX_SKIP:
for i in xrange(n):
# TODO check whether we need to call `list_hook`
self._unpack(EX_SKIP)
return
ret = newlist_hint(n)
for i in xrange(n):
ret.append(self._unpack(EX_CONSTRUCT))
if self._list_hook is not None:
ret = self._list_hook(ret)
# TODO is the interaction between `list_hook` and `use_list` ok?
return ret if self._use_list else tuple(ret)
if typ == TYPE_MAP:
if execute == EX_SKIP:
for i in xrange(n):
# TODO check whether we need to call hooks
self._unpack(EX_SKIP)
self._unpack(EX_SKIP)
return
if self._object_pairs_hook is not None:
ret = self._object_pairs_hook(
(self._unpack(EX_CONSTRUCT), self._unpack(EX_CONSTRUCT))
for _ in xrange(n)
)
else:
ret = {}
for _ in xrange(n):
key = self._unpack(EX_CONSTRUCT)
if self._strict_map_key and type(key) not in (unicode, bytes):
raise ValueError(
"%s is not allowed for map key" % str(type(key))
)
if not PY2 and type(key) is str:
key = sys.intern(key)
ret[key] = self._unpack(EX_CONSTRUCT)
if self._object_hook is not None:
ret = self._object_hook(ret)
return ret
if execute == EX_SKIP:
return
if typ == TYPE_RAW:
if self._raw:
obj = bytes(obj)
else:
obj = obj.decode("utf_8", self._unicode_errors)
return obj
if typ == TYPE_BIN:
return bytes(obj)
if typ == TYPE_EXT:
if n == -1: # timestamp
ts = Timestamp.from_bytes(bytes(obj))
if self._timestamp == 1:
return ts.to_unix()
elif self._timestamp == 2:
return ts.to_unix_nano()
elif self._timestamp == 3:
return ts.to_datetime()
else:
return ts
else:
return self._ext_hook(n, bytes(obj))
assert typ == TYPE_IMMEDIATE
return obj
def __iter__(self):
return self
def __next__(self):
try:
ret = self._unpack(EX_CONSTRUCT)
self._consume()
return ret
except OutOfData:
self._consume()
raise StopIteration
except RecursionError:
raise StackError
next = __next__
def skip(self):
self._unpack(EX_SKIP)
self._consume()
def unpack(self):
try:
ret = self._unpack(EX_CONSTRUCT)
except RecursionError:
raise StackError
self._consume()
return ret
def read_array_header(self):
ret = self._unpack(EX_READ_ARRAY_HEADER)
self._consume()
return ret
def read_map_header(self):
ret = self._unpack(EX_READ_MAP_HEADER)
self._consume()
return ret
def tell(self):
return self._stream_offset
class Packer(object):
"""
MessagePack Packer
Usage:
packer = Packer()
astream.write(packer.pack(a))
astream.write(packer.pack(b))
Packer's constructor has some keyword arguments:
:param callable default:
Convert user type to builtin type that Packer supports.
See also simplejson's document.
:param bool use_single_float:
Use single precision float type for float. (default: False)
:param bool autoreset:
Reset buffer after each pack and return its content as `bytes`. (default: True).
If set this to false, use `bytes()` to get content and `.reset()` to clear buffer.
:param bool use_bin_type:
Use bin type introduced in msgpack spec 2.0 for bytes.
It also enables str8 type for unicode. (default: True)
:param bool strict_types:
If set to true, types will be checked to be exact. Derived classes
from serializable types will not be serialized and will be
treated as unsupported type and forwarded to default.
Additionally tuples will not be serialized as lists.
This is useful when trying to implement accurate serialization
for python types.
:param bool datetime:
If set to true, datetime with tzinfo is packed into Timestamp type.
Note that the tzinfo is stripped in the timestamp.
You can get UTC datetime with `timestamp=3` option of the Unpacker.
(Python 2 is not supported).
:param str unicode_errors:
The error handler for encoding unicode. (default: 'strict')
DO NOT USE THIS!! This option is kept for very specific usage.
"""
def __init__(
self,
default=None,
use_single_float=False,
autoreset=True,
use_bin_type=True,
strict_types=False,
datetime=False,
unicode_errors=None,
):
self._strict_types = strict_types
self._use_float = use_single_float
self._autoreset = autoreset
self._use_bin_type = use_bin_type
self._buffer = StringIO()
if PY2 and datetime:
raise ValueError("datetime is not supported in Python 2")
self._datetime = bool(datetime)
self._unicode_errors = unicode_errors or "strict"
if default is not None:
if not callable(default):
raise TypeError("default must be callable")
self._default = default
def _pack(
self,
obj,
nest_limit=DEFAULT_RECURSE_LIMIT,
check=isinstance,
check_type_strict=_check_type_strict,
):
default_used = False
if self._strict_types:
check = check_type_strict
list_types = list
else:
list_types = (list, tuple)
while True:
if nest_limit < 0:
raise ValueError("recursion limit exceeded")
if obj is None:
return self._buffer.write(b"\xc0")
if check(obj, bool):
if obj:
return self._buffer.write(b"\xc3")
return self._buffer.write(b"\xc2")
if check(obj, int_types):
if 0 <= obj < 0x80:
return self._buffer.write(struct.pack("B", obj))
if -0x20 <= obj < 0:
return self._buffer.write(struct.pack("b", obj))
if 0x80 <= obj <= 0xFF:
return self._buffer.write(struct.pack("BB", 0xCC, obj))
if -0x80 <= obj < 0:
return self._buffer.write(struct.pack(">Bb", 0xD0, obj))
if 0xFF < obj <= 0xFFFF:
return self._buffer.write(struct.pack(">BH", 0xCD, obj))
if -0x8000 <= obj < -0x80:
return self._buffer.write(struct.pack(">Bh", 0xD1, obj))
if 0xFFFF < obj <= 0xFFFFFFFF:
return self._buffer.write(struct.pack(">BI", 0xCE, obj))
if -0x80000000 <= obj < -0x8000:
return self._buffer.write(struct.pack(">Bi", 0xD2, obj))
if 0xFFFFFFFF < obj <= 0xFFFFFFFFFFFFFFFF:
return self._buffer.write(struct.pack(">BQ", 0xCF, obj))
if -0x8000000000000000 <= obj < -0x80000000:
return self._buffer.write(struct.pack(">Bq", 0xD3, obj))
if not default_used and self._default is not None:
obj = self._default(obj)
default_used = True
continue
raise OverflowError("Integer value out of range")
if check(obj, (bytes, bytearray)):
n = len(obj)
if n >= 2 ** 32:
raise ValueError("%s is too large" % type(obj).__name__)
self._pack_bin_header(n)
return self._buffer.write(obj)
if check(obj, unicode):
obj = obj.encode("utf-8", self._unicode_errors)
n = len(obj)
if n >= 2 ** 32:
raise ValueError("String is too large")
self._pack_raw_header(n)
return self._buffer.write(obj)
if check(obj, memoryview):
n = len(obj) * obj.itemsize
if n >= 2 ** 32:
raise ValueError("Memoryview is too large")
self._pack_bin_header(n)
return self._buffer.write(obj)
if check(obj, float):
if self._use_float:
return self._buffer.write(struct.pack(">Bf", 0xCA, obj))
return self._buffer.write(struct.pack(">Bd", 0xCB, obj))
if check(obj, (ExtType, Timestamp)):
if check(obj, Timestamp):
code = -1
data = obj.to_bytes()
else:
code = obj.code
data = obj.data
assert isinstance(code, int)
assert isinstance(data, bytes)
L = len(data)
if L == 1:
self._buffer.write(b"\xd4")
elif L == 2:
self._buffer.write(b"\xd5")
elif L == 4:
self._buffer.write(b"\xd6")
elif L == 8:
self._buffer.write(b"\xd7")
elif L == 16:
self._buffer.write(b"\xd8")
elif L <= 0xFF:
self._buffer.write(struct.pack(">BB", 0xC7, L))
elif L <= 0xFFFF:
self._buffer.write(struct.pack(">BH", 0xC8, L))
else:
self._buffer.write(struct.pack(">BI", 0xC9, L))
self._buffer.write(struct.pack("b", code))
self._buffer.write(data)
return
if check(obj, list_types):
n = len(obj)
self._pack_array_header(n)
for i in xrange(n):
self._pack(obj[i], nest_limit - 1)
return
if check(obj, dict):
return self._pack_map_pairs(
len(obj), dict_iteritems(obj), nest_limit - 1
)
if self._datetime and check(obj, _DateTime):
obj = Timestamp.from_datetime(obj)
default_used = 1
continue
if not default_used and self._default is not None:
obj = self._default(obj)
default_used = 1
continue
raise TypeError("Cannot serialize %r" % (obj,))
def pack(self, obj):
try:
self._pack(obj)
except:
self._buffer = StringIO() # force reset
raise
if self._autoreset:
ret = self._buffer.getvalue()
self._buffer = StringIO()
return ret
def pack_map_pairs(self, pairs):
self._pack_map_pairs(len(pairs), pairs)
if self._autoreset:
ret = self._buffer.getvalue()
self._buffer = StringIO()
return ret
def pack_array_header(self, n):
if n >= 2 ** 32:
raise ValueError
self._pack_array_header(n)
if self._autoreset:
ret = self._buffer.getvalue()
self._buffer = StringIO()
return ret
def pack_map_header(self, n):
if n >= 2 ** 32:
raise ValueError
self._pack_map_header(n)
if self._autoreset:
ret = self._buffer.getvalue()
self._buffer = StringIO()
return ret
def pack_ext_type(self, typecode, data):
if not isinstance(typecode, int):
raise TypeError("typecode must have int type.")
if not 0 <= typecode <= 127:
raise ValueError("typecode should be 0-127")
if not isinstance(data, bytes):
raise TypeError("data must have bytes type")
L = len(data)
if L > 0xFFFFFFFF:
raise ValueError("Too large data")
if L == 1:
self._buffer.write(b"\xd4")
elif L == 2:
self._buffer.write(b"\xd5")
elif L == 4:
self._buffer.write(b"\xd6")
elif L == 8:
self._buffer.write(b"\xd7")
elif L == 16:
self._buffer.write(b"\xd8")
elif L <= 0xFF:
self._buffer.write(b"\xc7" + struct.pack("B", L))
elif L <= 0xFFFF:
self._buffer.write(b"\xc8" + struct.pack(">H", L))
else:
self._buffer.write(b"\xc9" + struct.pack(">I", L))
self._buffer.write(struct.pack("B", typecode))
self._buffer.write(data)
def _pack_array_header(self, n):
if n <= 0x0F:
return self._buffer.write(struct.pack("B", 0x90 + n))
if n <= 0xFFFF:
return self._buffer.write(struct.pack(">BH", 0xDC, n))
if n <= 0xFFFFFFFF:
return self._buffer.write(struct.pack(">BI", 0xDD, n))
raise ValueError("Array is too large")
def _pack_map_header(self, n):
if n <= 0x0F:
return self._buffer.write(struct.pack("B", 0x80 + n))
if n <= 0xFFFF:
return self._buffer.write(struct.pack(">BH", 0xDE, n))
if n <= 0xFFFFFFFF:
return self._buffer.write(struct.pack(">BI", 0xDF, n))
raise ValueError("Dict is too large")
def _pack_map_pairs(self, n, pairs, nest_limit=DEFAULT_RECURSE_LIMIT):
self._pack_map_header(n)
for (k, v) in pairs:
self._pack(k, nest_limit - 1)
self._pack(v, nest_limit - 1)
def _pack_raw_header(self, n):
if n <= 0x1F:
self._buffer.write(struct.pack("B", 0xA0 + n))
elif self._use_bin_type and n <= 0xFF:
self._buffer.write(struct.pack(">BB", 0xD9, n))
elif n <= 0xFFFF:
self._buffer.write(struct.pack(">BH", 0xDA, n))
elif n <= 0xFFFFFFFF:
self._buffer.write(struct.pack(">BI", 0xDB, n))
else:
raise ValueError("Raw is too large")
def _pack_bin_header(self, n):
if not self._use_bin_type:
return self._pack_raw_header(n)
elif n <= 0xFF:
return self._buffer.write(struct.pack(">BB", 0xC4, n))
elif n <= 0xFFFF:
return self._buffer.write(struct.pack(">BH", 0xC5, n))
elif n <= 0xFFFFFFFF:
return self._buffer.write(struct.pack(">BI", 0xC6, n))
else:
raise ValueError("Bin is too large")
def bytes(self):
"""Return internal buffer contents as bytes object"""
return self._buffer.getvalue()
def reset(self):
"""Reset internal buffer.
This method is useful only when autoreset=False.
"""
self._buffer = StringIO()
def getbuffer(self):
"""Return view of internal buffer."""
if USING_STRINGBUILDER or PY2:
return memoryview(self.bytes())
else:
return self._buffer.getbuffer()
| apache-2.0 |
yaroslavvb/tensorflow | tensorflow/python/ops/partitioned_variables.py | 132 | 12318 | # Copyright 2015 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.
# ==============================================================================
"""Helper functions for creating partitioned variables.
This is a convenient abstraction to partition a large variable across
multiple smaller variables that can be assigned to different devices.
The full variable can be reconstructed by concatenating the smaller variables.
Using partitioned variables instead of a single variable is mostly a
performance choice. It however also has an impact on:
1. Random initialization, as the random number generator is called once per
slice
2. Updates, as they happen in parallel across slices
A key design goal is to allow a different graph to repartition a variable
with the same name but different slicings, including possibly no partitions.
TODO(touts): If an initializer provides a seed, the seed must be changed
deterministically for each slice, maybe by adding one to it, otherwise each
slice will use the same values. Maybe this can be done by passing the
slice offsets to the initializer functions.
Typical usage:
```python
# Create a list of partitioned variables with:
vs = create_partitioned_variables(
<shape>, <slicing>, <initializer>, name=<optional-name>)
# Pass the list as inputs to embedding_lookup for sharded, parallel lookup:
y = embedding_lookup(vs, ids, partition_strategy="div")
# Or fetch the variables in parallel to speed up large matmuls:
z = matmul(x, concat(slice_dim, vs))
```
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import math
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import tensor_shape
from tensorflow.python.ops import variable_scope
from tensorflow.python.platform import tf_logging as logging
__all__ = [
"create_partitioned_variables",
"variable_axis_size_partitioner",
"min_max_variable_partitioner",
"fixed_size_partitioner",
]
def variable_axis_size_partitioner(
max_shard_bytes, axis=0, bytes_per_string_element=16, max_shards=None):
"""Get a partitioner for VariableScope to keep shards below `max_shard_bytes`.
This partitioner will shard a Variable along one axis, attempting to keep
the maximum shard size below `max_shard_bytes`. In practice, this is not
always possible when sharding along only one axis. When this happens,
this axis is sharded as much as possible (i.e., every dimension becomes
a separate shard).
If the partitioner hits the `max_shards` limit, then each shard may end up
larger than `max_shard_bytes`. By default `max_shards` equals `None` and no
limit on the number of shards is enforced.
One reasonable value for `max_shard_bytes` is `(64 << 20) - 1`, or almost
`64MB`, to keep below the protobuf byte limit.
Args:
max_shard_bytes: The maximum size any given shard is allowed to be.
axis: The axis to partition along. Default: outermost axis.
bytes_per_string_element: If the `Variable` is of type string, this provides
an estimate of how large each scalar in the `Variable` is.
max_shards: The maximum number of shards in int created taking precedence
over `max_shard_bytes`.
Returns:
A partition function usable as the `partitioner` argument to
`variable_scope`, `get_variable`, and `get_partitioned_variable_list`.
Raises:
ValueError: If any of the byte counts are non-positive.
"""
if max_shard_bytes < 1 or bytes_per_string_element < 1:
raise ValueError(
"Both max_shard_bytes and bytes_per_string_element must be positive.")
if max_shards and max_shards < 1:
raise ValueError(
"max_shards must be positive.")
def _partitioner(shape, dtype):
"""Partitioner that partitions shards to have max_shard_bytes total size.
Args:
shape: A `TensorShape`.
dtype: A `DType`.
Returns:
A tuple representing how much to slice each axis in shape.
Raises:
ValueError: If shape is not a fully defined `TensorShape` or dtype is not
a `DType`.
"""
if not isinstance(shape, tensor_shape.TensorShape):
raise ValueError("shape is not a TensorShape: %s" % shape)
if not shape.is_fully_defined():
raise ValueError("shape is not fully defined: %s" % shape)
if not isinstance(dtype, dtypes.DType):
raise ValueError("dtype is not a DType: %s" % dtype)
if dtype.base_dtype == dtypes.string:
element_size = bytes_per_string_element
else:
element_size = dtype.size
partitions = [1] * shape.ndims
bytes_per_slice = 1.0 * (
shape.num_elements() / shape[axis].value) * element_size
# How many slices can we fit on one shard of size at most max_shard_bytes?
# At least one slice is required.
slices_per_shard = max(1, math.floor(max_shard_bytes / bytes_per_slice))
# How many shards do we need for axis given that each shard fits
# slices_per_shard slices from a total of shape[axis].value slices?
axis_shards = int(math.ceil(1.0 * shape[axis].value / slices_per_shard))
if max_shards:
axis_shards = min(max_shards, axis_shards)
partitions[axis] = axis_shards
return partitions
return _partitioner
def min_max_variable_partitioner(max_partitions=1, axis=0,
min_slice_size=256 << 10,
bytes_per_string_element=16):
"""Partitioner to allocate minimum size per slice.
Returns a partitioner that partitions the variable of given shape and dtype
such that each partition has a minimum of `min_slice_size` slice of the
variable. The maximum number of such partitions (upper bound) is given by
`max_partitions`.
Args:
max_partitions: Upper bound on the number of partitions. Defaults to 1.
axis: Axis along which to partition the variable. Defaults to 0.
min_slice_size: Minimum size of the variable slice per partition. Defaults
to 256K.
bytes_per_string_element: If the `Variable` is of type string, this provides
an estimate of how large each scalar in the `Variable` is.
Returns:
A partition function usable as the `partitioner` argument to
`variable_scope`, `get_variable`, and `get_partitioned_variable_list`.
"""
def _partitioner(shape, dtype):
"""Partitioner that partitions list for a variable of given shape and type.
Ex: Consider partitioning a variable of type float32 with
shape=[1024, 1024].
If `max_partitions` >= 16, this function would return
[(1024 * 1024 * 4) / (256 * 1024), 1] = [16, 1].
If `max_partitions` < 16, this function would return
[`max_partitions`, 1].
Args:
shape: Shape of the variable.
dtype: Type of the variable.
Returns:
List of partitions for each axis (currently only one axis can be
partitioned).
Raises:
ValueError: If axis to partition along does not exist for the variable.
"""
if axis >= len(shape):
raise ValueError("Can not partition variable along axis %d when shape is "
"only %s" % (axis, shape))
if dtype.base_dtype == dtypes.string:
bytes_per_element = bytes_per_string_element
else:
bytes_per_element = dtype.size
total_size_bytes = shape.num_elements() * bytes_per_element
partitions = total_size_bytes / min_slice_size
partitions_list = [1] * len(shape)
# We can not partition the variable beyond what its shape or
# `max_partitions` allows.
partitions_list[axis] = max(1, min(shape[axis].value,
max_partitions,
int(math.ceil(partitions))))
return partitions_list
return _partitioner
def fixed_size_partitioner(num_shards, axis=0):
"""Partitioner to specify a fixed number of shards along given axis.
Args:
num_shards: `int`, number of shards to partition variable.
axis: `int`, axis to partition on.
Returns:
A partition function usable as the `partitioner` argument to
`variable_scope`, `get_variable`, and `get_partitioned_variable_list`.
"""
def _partitioner(shape, **unused_args):
partitions_list = [1] * len(shape)
partitions_list[axis] = min(num_shards, shape[axis].value)
return partitions_list
return _partitioner
def create_partitioned_variables(
shape, slicing, initializer, dtype=dtypes.float32,
trainable=True, collections=None, name=None, reuse=None):
"""Create a list of partitioned variables according to the given `slicing`.
Currently only one dimension of the full variable can be sliced, and the
full variable can be reconstructed by the concatenation of the returned
list along that dimension.
Args:
shape: List of integers. The shape of the full variable.
slicing: List of integers. How to partition the variable.
Must be of the same length as `shape`. Each value
indicate how many slices to create in the corresponding
dimension. Presently only one of the values can be more than 1;
that is, the variable can only be sliced along one dimension.
For convenience, The requested number of partitions does not have to
divide the corresponding dimension evenly. If it does not, the
shapes of the partitions are incremented by 1 starting from partition
0 until all slack is absorbed. The adjustment rules may change in the
future, but as you can save/restore these variables with different
slicing specifications this should not be a problem.
initializer: A `Tensor` of shape `shape` or a variable initializer
function. If a function, it will be called once for each slice,
passing the shape and data type of the slice as parameters. The
function must return a tensor with the same shape as the slice.
dtype: Type of the variables. Ignored if `initializer` is a `Tensor`.
trainable: If True also add all the variables to the graph collection
`GraphKeys.TRAINABLE_VARIABLES`.
collections: List of graph collections keys to add the variables to.
Defaults to `[GraphKeys.GLOBAL_VARIABLES]`.
name: Optional name for the full variable. Defaults to
`"PartitionedVariable"` and gets uniquified automatically.
reuse: Boolean or `None`; if `True` and name is set, it would reuse
previously created variables. if `False` it will create new variables.
if `None`, it would inherit the parent scope reuse.
Returns:
A list of Variables corresponding to the slicing.
Raises:
ValueError: If any of the arguments is malformed.
"""
logging.warn(
"create_partitioned_variables is deprecated. Use "
"tf.get_variable with a partitioner set, or "
"tf.get_partitioned_variable_list, instead.")
if len(shape) != len(slicing):
raise ValueError("The 'shape' and 'slicing' of a partitioned Variable "
"must have the length: shape: %s, slicing: %s" %
(shape, slicing))
if len(shape) < 1:
raise ValueError("A partitioned Variable must have rank at least 1: "
"shape: %s" % shape)
# Legacy: we are provided the slicing directly, so just pass it to
# the partitioner.
partitioner = lambda **unused_kwargs: slicing
with variable_scope.variable_scope(
name, "PartitionedVariable", reuse=reuse):
# pylint: disable=protected-access
partitioned_var = variable_scope._get_partitioned_variable(
name=None,
shape=shape,
dtype=dtype,
initializer=initializer,
trainable=trainable,
partitioner=partitioner,
collections=collections)
return list(partitioned_var)
# pylint: enable=protected-access
| apache-2.0 |
z1gm4/desarrollo_web_udp | env/lib/python2.7/site-packages/pip/_vendor/requests/adapters.py | 175 | 17495 | # -*- coding: utf-8 -*-
"""
requests.adapters
~~~~~~~~~~~~~~~~~
This module contains the transport adapters that Requests uses to define
and maintain connections.
"""
import os.path
import socket
from .models import Response
from .packages.urllib3.poolmanager import PoolManager, proxy_from_url
from .packages.urllib3.response import HTTPResponse
from .packages.urllib3.util import Timeout as TimeoutSauce
from .packages.urllib3.util.retry import Retry
from .compat import urlparse, basestring
from .utils import (DEFAULT_CA_BUNDLE_PATH, get_encoding_from_headers,
prepend_scheme_if_needed, get_auth_from_url, urldefragauth,
select_proxy)
from .structures import CaseInsensitiveDict
from .packages.urllib3.exceptions import ClosedPoolError
from .packages.urllib3.exceptions import ConnectTimeoutError
from .packages.urllib3.exceptions import HTTPError as _HTTPError
from .packages.urllib3.exceptions import MaxRetryError
from .packages.urllib3.exceptions import NewConnectionError
from .packages.urllib3.exceptions import ProxyError as _ProxyError
from .packages.urllib3.exceptions import ProtocolError
from .packages.urllib3.exceptions import ReadTimeoutError
from .packages.urllib3.exceptions import SSLError as _SSLError
from .packages.urllib3.exceptions import ResponseError
from .cookies import extract_cookies_to_jar
from .exceptions import (ConnectionError, ConnectTimeout, ReadTimeout, SSLError,
ProxyError, RetryError)
from .auth import _basic_auth_str
DEFAULT_POOLBLOCK = False
DEFAULT_POOLSIZE = 10
DEFAULT_RETRIES = 0
DEFAULT_POOL_TIMEOUT = None
class BaseAdapter(object):
"""The Base Transport Adapter"""
def __init__(self):
super(BaseAdapter, self).__init__()
def send(self):
raise NotImplementedError
def close(self):
raise NotImplementedError
class HTTPAdapter(BaseAdapter):
"""The built-in HTTP Adapter for urllib3.
Provides a general-case interface for Requests sessions to contact HTTP and
HTTPS urls by implementing the Transport Adapter interface. This class will
usually be created by the :class:`Session <Session>` class under the
covers.
:param pool_connections: The number of urllib3 connection pools to cache.
:param pool_maxsize: The maximum number of connections to save in the pool.
:param int max_retries: The maximum number of retries each connection
should attempt. Note, this applies only to failed DNS lookups, socket
connections and connection timeouts, never to requests where data has
made it to the server. By default, Requests does not retry failed
connections. If you need granular control over the conditions under
which we retry a request, import urllib3's ``Retry`` class and pass
that instead.
:param pool_block: Whether the connection pool should block for connections.
Usage::
>>> import requests
>>> s = requests.Session()
>>> a = requests.adapters.HTTPAdapter(max_retries=3)
>>> s.mount('http://', a)
"""
__attrs__ = ['max_retries', 'config', '_pool_connections', '_pool_maxsize',
'_pool_block']
def __init__(self, pool_connections=DEFAULT_POOLSIZE,
pool_maxsize=DEFAULT_POOLSIZE, max_retries=DEFAULT_RETRIES,
pool_block=DEFAULT_POOLBLOCK):
if max_retries == DEFAULT_RETRIES:
self.max_retries = Retry(0, read=False)
else:
self.max_retries = Retry.from_int(max_retries)
self.config = {}
self.proxy_manager = {}
super(HTTPAdapter, self).__init__()
self._pool_connections = pool_connections
self._pool_maxsize = pool_maxsize
self._pool_block = pool_block
self.init_poolmanager(pool_connections, pool_maxsize, block=pool_block)
def __getstate__(self):
return dict((attr, getattr(self, attr, None)) for attr in
self.__attrs__)
def __setstate__(self, state):
# Can't handle by adding 'proxy_manager' to self.__attrs__ because
# self.poolmanager uses a lambda function, which isn't pickleable.
self.proxy_manager = {}
self.config = {}
for attr, value in state.items():
setattr(self, attr, value)
self.init_poolmanager(self._pool_connections, self._pool_maxsize,
block=self._pool_block)
def init_poolmanager(self, connections, maxsize, block=DEFAULT_POOLBLOCK, **pool_kwargs):
"""Initializes a urllib3 PoolManager.
This method should not be called from user code, and is only
exposed for use when subclassing the
:class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.
:param connections: The number of urllib3 connection pools to cache.
:param maxsize: The maximum number of connections to save in the pool.
:param block: Block when no free connections are available.
:param pool_kwargs: Extra keyword arguments used to initialize the Pool Manager.
"""
# save these values for pickling
self._pool_connections = connections
self._pool_maxsize = maxsize
self._pool_block = block
self.poolmanager = PoolManager(num_pools=connections, maxsize=maxsize,
block=block, strict=True, **pool_kwargs)
def proxy_manager_for(self, proxy, **proxy_kwargs):
"""Return urllib3 ProxyManager for the given proxy.
This method should not be called from user code, and is only
exposed for use when subclassing the
:class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.
:param proxy: The proxy to return a urllib3 ProxyManager for.
:param proxy_kwargs: Extra keyword arguments used to configure the Proxy Manager.
:returns: ProxyManager
"""
if not proxy in self.proxy_manager:
proxy_headers = self.proxy_headers(proxy)
self.proxy_manager[proxy] = proxy_from_url(
proxy,
proxy_headers=proxy_headers,
num_pools=self._pool_connections,
maxsize=self._pool_maxsize,
block=self._pool_block,
**proxy_kwargs)
return self.proxy_manager[proxy]
def cert_verify(self, conn, url, verify, cert):
"""Verify a SSL certificate. This method should not be called from user
code, and is only exposed for use when subclassing the
:class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.
:param conn: The urllib3 connection object associated with the cert.
:param url: The requested URL.
:param verify: Whether we should actually verify the certificate.
:param cert: The SSL certificate to verify.
"""
if url.lower().startswith('https') and verify:
cert_loc = None
# Allow self-specified cert location.
if verify is not True:
cert_loc = verify
if not cert_loc:
cert_loc = DEFAULT_CA_BUNDLE_PATH
if not cert_loc:
raise Exception("Could not find a suitable SSL CA certificate bundle.")
conn.cert_reqs = 'CERT_REQUIRED'
if not os.path.isdir(cert_loc):
conn.ca_certs = cert_loc
else:
conn.ca_cert_dir = cert_loc
else:
conn.cert_reqs = 'CERT_NONE'
conn.ca_certs = None
conn.ca_cert_dir = None
if cert:
if not isinstance(cert, basestring):
conn.cert_file = cert[0]
conn.key_file = cert[1]
else:
conn.cert_file = cert
def build_response(self, req, resp):
"""Builds a :class:`Response <requests.Response>` object from a urllib3
response. This should not be called from user code, and is only exposed
for use when subclassing the
:class:`HTTPAdapter <requests.adapters.HTTPAdapter>`
:param req: The :class:`PreparedRequest <PreparedRequest>` used to generate the response.
:param resp: The urllib3 response object.
"""
response = Response()
# Fallback to None if there's no status_code, for whatever reason.
response.status_code = getattr(resp, 'status', None)
# Make headers case-insensitive.
response.headers = CaseInsensitiveDict(getattr(resp, 'headers', {}))
# Set encoding.
response.encoding = get_encoding_from_headers(response.headers)
response.raw = resp
response.reason = response.raw.reason
if isinstance(req.url, bytes):
response.url = req.url.decode('utf-8')
else:
response.url = req.url
# Add new cookies from the server.
extract_cookies_to_jar(response.cookies, req, resp)
# Give the Response some context.
response.request = req
response.connection = self
return response
def get_connection(self, url, proxies=None):
"""Returns a urllib3 connection for the given URL. This should not be
called from user code, and is only exposed for use when subclassing the
:class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.
:param url: The URL to connect to.
:param proxies: (optional) A Requests-style dictionary of proxies used on this request.
"""
proxy = select_proxy(url, proxies)
if proxy:
proxy = prepend_scheme_if_needed(proxy, 'http')
proxy_manager = self.proxy_manager_for(proxy)
conn = proxy_manager.connection_from_url(url)
else:
# Only scheme should be lower case
parsed = urlparse(url)
url = parsed.geturl()
conn = self.poolmanager.connection_from_url(url)
return conn
def close(self):
"""Disposes of any internal state.
Currently, this just closes the PoolManager, which closes pooled
connections.
"""
self.poolmanager.clear()
def request_url(self, request, proxies):
"""Obtain the url to use when making the final request.
If the message is being sent through a HTTP proxy, the full URL has to
be used. Otherwise, we should only use the path portion of the URL.
This should not be called from user code, and is only exposed for use
when subclassing the
:class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.
:param request: The :class:`PreparedRequest <PreparedRequest>` being sent.
:param proxies: A dictionary of schemes or schemes and hosts to proxy URLs.
"""
proxy = select_proxy(request.url, proxies)
scheme = urlparse(request.url).scheme
if proxy and scheme != 'https':
url = urldefragauth(request.url)
else:
url = request.path_url
return url
def add_headers(self, request, **kwargs):
"""Add any headers needed by the connection. As of v2.0 this does
nothing by default, but is left for overriding by users that subclass
the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.
This should not be called from user code, and is only exposed for use
when subclassing the
:class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.
:param request: The :class:`PreparedRequest <PreparedRequest>` to add headers to.
:param kwargs: The keyword arguments from the call to send().
"""
pass
def proxy_headers(self, proxy):
"""Returns a dictionary of the headers to add to any request sent
through a proxy. This works with urllib3 magic to ensure that they are
correctly sent to the proxy, rather than in a tunnelled request if
CONNECT is being used.
This should not be called from user code, and is only exposed for use
when subclassing the
:class:`HTTPAdapter <requests.adapters.HTTPAdapter>`.
:param proxies: The url of the proxy being used for this request.
"""
headers = {}
username, password = get_auth_from_url(proxy)
if username and password:
headers['Proxy-Authorization'] = _basic_auth_str(username,
password)
return headers
def send(self, request, stream=False, timeout=None, verify=True, cert=None, proxies=None):
"""Sends PreparedRequest object. Returns Response object.
:param request: The :class:`PreparedRequest <PreparedRequest>` being sent.
:param stream: (optional) Whether to stream the request content.
:param timeout: (optional) How long to wait for the server to send
data before giving up, as a float, or a :ref:`(connect timeout,
read timeout) <timeouts>` tuple.
:type timeout: float or tuple
:param verify: (optional) Whether to verify SSL certificates.
:param cert: (optional) Any user-provided SSL certificate to be trusted.
:param proxies: (optional) The proxies dictionary to apply to the request.
"""
conn = self.get_connection(request.url, proxies)
self.cert_verify(conn, request.url, verify, cert)
url = self.request_url(request, proxies)
self.add_headers(request)
chunked = not (request.body is None or 'Content-Length' in request.headers)
if isinstance(timeout, tuple):
try:
connect, read = timeout
timeout = TimeoutSauce(connect=connect, read=read)
except ValueError as e:
# this may raise a string formatting error.
err = ("Invalid timeout {0}. Pass a (connect, read) "
"timeout tuple, or a single float to set "
"both timeouts to the same value".format(timeout))
raise ValueError(err)
else:
timeout = TimeoutSauce(connect=timeout, read=timeout)
try:
if not chunked:
resp = conn.urlopen(
method=request.method,
url=url,
body=request.body,
headers=request.headers,
redirect=False,
assert_same_host=False,
preload_content=False,
decode_content=False,
retries=self.max_retries,
timeout=timeout
)
# Send the request.
else:
if hasattr(conn, 'proxy_pool'):
conn = conn.proxy_pool
low_conn = conn._get_conn(timeout=DEFAULT_POOL_TIMEOUT)
try:
low_conn.putrequest(request.method,
url,
skip_accept_encoding=True)
for header, value in request.headers.items():
low_conn.putheader(header, value)
low_conn.endheaders()
for i in request.body:
low_conn.send(hex(len(i))[2:].encode('utf-8'))
low_conn.send(b'\r\n')
low_conn.send(i)
low_conn.send(b'\r\n')
low_conn.send(b'0\r\n\r\n')
# Receive the response from the server
try:
# For Python 2.7+ versions, use buffering of HTTP
# responses
r = low_conn.getresponse(buffering=True)
except TypeError:
# For compatibility with Python 2.6 versions and back
r = low_conn.getresponse()
resp = HTTPResponse.from_httplib(
r,
pool=conn,
connection=low_conn,
preload_content=False,
decode_content=False
)
except:
# If we hit any problems here, clean up the connection.
# Then, reraise so that we can handle the actual exception.
low_conn.close()
raise
except (ProtocolError, socket.error) as err:
raise ConnectionError(err, request=request)
except MaxRetryError as e:
if isinstance(e.reason, ConnectTimeoutError):
# TODO: Remove this in 3.0.0: see #2811
if not isinstance(e.reason, NewConnectionError):
raise ConnectTimeout(e, request=request)
if isinstance(e.reason, ResponseError):
raise RetryError(e, request=request)
raise ConnectionError(e, request=request)
except ClosedPoolError as e:
raise ConnectionError(e, request=request)
except _ProxyError as e:
raise ProxyError(e)
except (_SSLError, _HTTPError) as e:
if isinstance(e, _SSLError):
raise SSLError(e, request=request)
elif isinstance(e, ReadTimeoutError):
raise ReadTimeout(e, request=request)
else:
raise
return self.build_response(request, resp)
| gpl-3.0 |
YachaoLiu/rk3288_kernel | tools/perf/scripts/python/sched-migration.py | 11215 | 11670 | #!/usr/bin/python
#
# Cpu task migration overview toy
#
# Copyright (C) 2010 Frederic Weisbecker <[email protected]>
#
# perf script event handlers have been generated by perf script -g python
#
# This software is distributed under the terms of the GNU General
# Public License ("GPL") version 2 as published by the Free Software
# Foundation.
import os
import sys
from collections import defaultdict
from UserList import UserList
sys.path.append(os.environ['PERF_EXEC_PATH'] + \
'/scripts/python/Perf-Trace-Util/lib/Perf/Trace')
sys.path.append('scripts/python/Perf-Trace-Util/lib/Perf/Trace')
from perf_trace_context import *
from Core import *
from SchedGui import *
threads = { 0 : "idle"}
def thread_name(pid):
return "%s:%d" % (threads[pid], pid)
class RunqueueEventUnknown:
@staticmethod
def color():
return None
def __repr__(self):
return "unknown"
class RunqueueEventSleep:
@staticmethod
def color():
return (0, 0, 0xff)
def __init__(self, sleeper):
self.sleeper = sleeper
def __repr__(self):
return "%s gone to sleep" % thread_name(self.sleeper)
class RunqueueEventWakeup:
@staticmethod
def color():
return (0xff, 0xff, 0)
def __init__(self, wakee):
self.wakee = wakee
def __repr__(self):
return "%s woke up" % thread_name(self.wakee)
class RunqueueEventFork:
@staticmethod
def color():
return (0, 0xff, 0)
def __init__(self, child):
self.child = child
def __repr__(self):
return "new forked task %s" % thread_name(self.child)
class RunqueueMigrateIn:
@staticmethod
def color():
return (0, 0xf0, 0xff)
def __init__(self, new):
self.new = new
def __repr__(self):
return "task migrated in %s" % thread_name(self.new)
class RunqueueMigrateOut:
@staticmethod
def color():
return (0xff, 0, 0xff)
def __init__(self, old):
self.old = old
def __repr__(self):
return "task migrated out %s" % thread_name(self.old)
class RunqueueSnapshot:
def __init__(self, tasks = [0], event = RunqueueEventUnknown()):
self.tasks = tuple(tasks)
self.event = event
def sched_switch(self, prev, prev_state, next):
event = RunqueueEventUnknown()
if taskState(prev_state) == "R" and next in self.tasks \
and prev in self.tasks:
return self
if taskState(prev_state) != "R":
event = RunqueueEventSleep(prev)
next_tasks = list(self.tasks[:])
if prev in self.tasks:
if taskState(prev_state) != "R":
next_tasks.remove(prev)
elif taskState(prev_state) == "R":
next_tasks.append(prev)
if next not in next_tasks:
next_tasks.append(next)
return RunqueueSnapshot(next_tasks, event)
def migrate_out(self, old):
if old not in self.tasks:
return self
next_tasks = [task for task in self.tasks if task != old]
return RunqueueSnapshot(next_tasks, RunqueueMigrateOut(old))
def __migrate_in(self, new, event):
if new in self.tasks:
self.event = event
return self
next_tasks = self.tasks[:] + tuple([new])
return RunqueueSnapshot(next_tasks, event)
def migrate_in(self, new):
return self.__migrate_in(new, RunqueueMigrateIn(new))
def wake_up(self, new):
return self.__migrate_in(new, RunqueueEventWakeup(new))
def wake_up_new(self, new):
return self.__migrate_in(new, RunqueueEventFork(new))
def load(self):
""" Provide the number of tasks on the runqueue.
Don't count idle"""
return len(self.tasks) - 1
def __repr__(self):
ret = self.tasks.__repr__()
ret += self.origin_tostring()
return ret
class TimeSlice:
def __init__(self, start, prev):
self.start = start
self.prev = prev
self.end = start
# cpus that triggered the event
self.event_cpus = []
if prev is not None:
self.total_load = prev.total_load
self.rqs = prev.rqs.copy()
else:
self.rqs = defaultdict(RunqueueSnapshot)
self.total_load = 0
def __update_total_load(self, old_rq, new_rq):
diff = new_rq.load() - old_rq.load()
self.total_load += diff
def sched_switch(self, ts_list, prev, prev_state, next, cpu):
old_rq = self.prev.rqs[cpu]
new_rq = old_rq.sched_switch(prev, prev_state, next)
if old_rq is new_rq:
return
self.rqs[cpu] = new_rq
self.__update_total_load(old_rq, new_rq)
ts_list.append(self)
self.event_cpus = [cpu]
def migrate(self, ts_list, new, old_cpu, new_cpu):
if old_cpu == new_cpu:
return
old_rq = self.prev.rqs[old_cpu]
out_rq = old_rq.migrate_out(new)
self.rqs[old_cpu] = out_rq
self.__update_total_load(old_rq, out_rq)
new_rq = self.prev.rqs[new_cpu]
in_rq = new_rq.migrate_in(new)
self.rqs[new_cpu] = in_rq
self.__update_total_load(new_rq, in_rq)
ts_list.append(self)
if old_rq is not out_rq:
self.event_cpus.append(old_cpu)
self.event_cpus.append(new_cpu)
def wake_up(self, ts_list, pid, cpu, fork):
old_rq = self.prev.rqs[cpu]
if fork:
new_rq = old_rq.wake_up_new(pid)
else:
new_rq = old_rq.wake_up(pid)
if new_rq is old_rq:
return
self.rqs[cpu] = new_rq
self.__update_total_load(old_rq, new_rq)
ts_list.append(self)
self.event_cpus = [cpu]
def next(self, t):
self.end = t
return TimeSlice(t, self)
class TimeSliceList(UserList):
def __init__(self, arg = []):
self.data = arg
def get_time_slice(self, ts):
if len(self.data) == 0:
slice = TimeSlice(ts, TimeSlice(-1, None))
else:
slice = self.data[-1].next(ts)
return slice
def find_time_slice(self, ts):
start = 0
end = len(self.data)
found = -1
searching = True
while searching:
if start == end or start == end - 1:
searching = False
i = (end + start) / 2
if self.data[i].start <= ts and self.data[i].end >= ts:
found = i
end = i
continue
if self.data[i].end < ts:
start = i
elif self.data[i].start > ts:
end = i
return found
def set_root_win(self, win):
self.root_win = win
def mouse_down(self, cpu, t):
idx = self.find_time_slice(t)
if idx == -1:
return
ts = self[idx]
rq = ts.rqs[cpu]
raw = "CPU: %d\n" % cpu
raw += "Last event : %s\n" % rq.event.__repr__()
raw += "Timestamp : %d.%06d\n" % (ts.start / (10 ** 9), (ts.start % (10 ** 9)) / 1000)
raw += "Duration : %6d us\n" % ((ts.end - ts.start) / (10 ** 6))
raw += "Load = %d\n" % rq.load()
for t in rq.tasks:
raw += "%s \n" % thread_name(t)
self.root_win.update_summary(raw)
def update_rectangle_cpu(self, slice, cpu):
rq = slice.rqs[cpu]
if slice.total_load != 0:
load_rate = rq.load() / float(slice.total_load)
else:
load_rate = 0
red_power = int(0xff - (0xff * load_rate))
color = (0xff, red_power, red_power)
top_color = None
if cpu in slice.event_cpus:
top_color = rq.event.color()
self.root_win.paint_rectangle_zone(cpu, color, top_color, slice.start, slice.end)
def fill_zone(self, start, end):
i = self.find_time_slice(start)
if i == -1:
return
for i in xrange(i, len(self.data)):
timeslice = self.data[i]
if timeslice.start > end:
return
for cpu in timeslice.rqs:
self.update_rectangle_cpu(timeslice, cpu)
def interval(self):
if len(self.data) == 0:
return (0, 0)
return (self.data[0].start, self.data[-1].end)
def nr_rectangles(self):
last_ts = self.data[-1]
max_cpu = 0
for cpu in last_ts.rqs:
if cpu > max_cpu:
max_cpu = cpu
return max_cpu
class SchedEventProxy:
def __init__(self):
self.current_tsk = defaultdict(lambda : -1)
self.timeslices = TimeSliceList()
def sched_switch(self, headers, prev_comm, prev_pid, prev_prio, prev_state,
next_comm, next_pid, next_prio):
""" Ensure the task we sched out this cpu is really the one
we logged. Otherwise we may have missed traces """
on_cpu_task = self.current_tsk[headers.cpu]
if on_cpu_task != -1 and on_cpu_task != prev_pid:
print "Sched switch event rejected ts: %s cpu: %d prev: %s(%d) next: %s(%d)" % \
(headers.ts_format(), headers.cpu, prev_comm, prev_pid, next_comm, next_pid)
threads[prev_pid] = prev_comm
threads[next_pid] = next_comm
self.current_tsk[headers.cpu] = next_pid
ts = self.timeslices.get_time_slice(headers.ts())
ts.sched_switch(self.timeslices, prev_pid, prev_state, next_pid, headers.cpu)
def migrate(self, headers, pid, prio, orig_cpu, dest_cpu):
ts = self.timeslices.get_time_slice(headers.ts())
ts.migrate(self.timeslices, pid, orig_cpu, dest_cpu)
def wake_up(self, headers, comm, pid, success, target_cpu, fork):
if success == 0:
return
ts = self.timeslices.get_time_slice(headers.ts())
ts.wake_up(self.timeslices, pid, target_cpu, fork)
def trace_begin():
global parser
parser = SchedEventProxy()
def trace_end():
app = wx.App(False)
timeslices = parser.timeslices
frame = RootFrame(timeslices, "Migration")
app.MainLoop()
def sched__sched_stat_runtime(event_name, context, common_cpu,
common_secs, common_nsecs, common_pid, common_comm,
comm, pid, runtime, vruntime):
pass
def sched__sched_stat_iowait(event_name, context, common_cpu,
common_secs, common_nsecs, common_pid, common_comm,
comm, pid, delay):
pass
def sched__sched_stat_sleep(event_name, context, common_cpu,
common_secs, common_nsecs, common_pid, common_comm,
comm, pid, delay):
pass
def sched__sched_stat_wait(event_name, context, common_cpu,
common_secs, common_nsecs, common_pid, common_comm,
comm, pid, delay):
pass
def sched__sched_process_fork(event_name, context, common_cpu,
common_secs, common_nsecs, common_pid, common_comm,
parent_comm, parent_pid, child_comm, child_pid):
pass
def sched__sched_process_wait(event_name, context, common_cpu,
common_secs, common_nsecs, common_pid, common_comm,
comm, pid, prio):
pass
def sched__sched_process_exit(event_name, context, common_cpu,
common_secs, common_nsecs, common_pid, common_comm,
comm, pid, prio):
pass
def sched__sched_process_free(event_name, context, common_cpu,
common_secs, common_nsecs, common_pid, common_comm,
comm, pid, prio):
pass
def sched__sched_migrate_task(event_name, context, common_cpu,
common_secs, common_nsecs, common_pid, common_comm,
comm, pid, prio, orig_cpu,
dest_cpu):
headers = EventHeaders(common_cpu, common_secs, common_nsecs,
common_pid, common_comm)
parser.migrate(headers, pid, prio, orig_cpu, dest_cpu)
def sched__sched_switch(event_name, context, common_cpu,
common_secs, common_nsecs, common_pid, common_comm,
prev_comm, prev_pid, prev_prio, prev_state,
next_comm, next_pid, next_prio):
headers = EventHeaders(common_cpu, common_secs, common_nsecs,
common_pid, common_comm)
parser.sched_switch(headers, prev_comm, prev_pid, prev_prio, prev_state,
next_comm, next_pid, next_prio)
def sched__sched_wakeup_new(event_name, context, common_cpu,
common_secs, common_nsecs, common_pid, common_comm,
comm, pid, prio, success,
target_cpu):
headers = EventHeaders(common_cpu, common_secs, common_nsecs,
common_pid, common_comm)
parser.wake_up(headers, comm, pid, success, target_cpu, 1)
def sched__sched_wakeup(event_name, context, common_cpu,
common_secs, common_nsecs, common_pid, common_comm,
comm, pid, prio, success,
target_cpu):
headers = EventHeaders(common_cpu, common_secs, common_nsecs,
common_pid, common_comm)
parser.wake_up(headers, comm, pid, success, target_cpu, 0)
def sched__sched_wait_task(event_name, context, common_cpu,
common_secs, common_nsecs, common_pid, common_comm,
comm, pid, prio):
pass
def sched__sched_kthread_stop_ret(event_name, context, common_cpu,
common_secs, common_nsecs, common_pid, common_comm,
ret):
pass
def sched__sched_kthread_stop(event_name, context, common_cpu,
common_secs, common_nsecs, common_pid, common_comm,
comm, pid):
pass
def trace_unhandled(event_name, context, common_cpu, common_secs, common_nsecs,
common_pid, common_comm):
pass
| gpl-2.0 |
Zhongqilong/kbengine | kbe/res/scripts/common/Lib/webbrowser.py | 81 | 21421 | #! /usr/bin/env python3
"""Interfaces for launching and remotely controlling Web browsers."""
# Maintained by Georg Brandl.
import os
import shlex
import shutil
import sys
import subprocess
__all__ = ["Error", "open", "open_new", "open_new_tab", "get", "register"]
class Error(Exception):
pass
_browsers = {} # Dictionary of available browser controllers
_tryorder = [] # Preference order of available browsers
def register(name, klass, instance=None, update_tryorder=1):
"""Register a browser connector and, optionally, connection."""
_browsers[name.lower()] = [klass, instance]
if update_tryorder > 0:
_tryorder.append(name)
elif update_tryorder < 0:
_tryorder.insert(0, name)
def get(using=None):
"""Return a browser launcher instance appropriate for the environment."""
if using is not None:
alternatives = [using]
else:
alternatives = _tryorder
for browser in alternatives:
if '%s' in browser:
# User gave us a command line, split it into name and args
browser = shlex.split(browser)
if browser[-1] == '&':
return BackgroundBrowser(browser[:-1])
else:
return GenericBrowser(browser)
else:
# User gave us a browser name or path.
try:
command = _browsers[browser.lower()]
except KeyError:
command = _synthesize(browser)
if command[1] is not None:
return command[1]
elif command[0] is not None:
return command[0]()
raise Error("could not locate runnable browser")
# Please note: the following definition hides a builtin function.
# It is recommended one does "import webbrowser" and uses webbrowser.open(url)
# instead of "from webbrowser import *".
def open(url, new=0, autoraise=True):
for name in _tryorder:
browser = get(name)
if browser.open(url, new, autoraise):
return True
return False
def open_new(url):
return open(url, 1)
def open_new_tab(url):
return open(url, 2)
def _synthesize(browser, update_tryorder=1):
"""Attempt to synthesize a controller base on existing controllers.
This is useful to create a controller when a user specifies a path to
an entry in the BROWSER environment variable -- we can copy a general
controller to operate using a specific installation of the desired
browser in this way.
If we can't create a controller in this way, or if there is no
executable for the requested browser, return [None, None].
"""
cmd = browser.split()[0]
if not shutil.which(cmd):
return [None, None]
name = os.path.basename(cmd)
try:
command = _browsers[name.lower()]
except KeyError:
return [None, None]
# now attempt to clone to fit the new name:
controller = command[1]
if controller and name.lower() == controller.basename:
import copy
controller = copy.copy(controller)
controller.name = browser
controller.basename = os.path.basename(browser)
register(browser, None, controller, update_tryorder)
return [None, controller]
return [None, None]
# General parent classes
class BaseBrowser(object):
"""Parent class for all browsers. Do not use directly."""
args = ['%s']
def __init__(self, name=""):
self.name = name
self.basename = name
def open(self, url, new=0, autoraise=True):
raise NotImplementedError
def open_new(self, url):
return self.open(url, 1)
def open_new_tab(self, url):
return self.open(url, 2)
class GenericBrowser(BaseBrowser):
"""Class for all browsers started with a command
and without remote functionality."""
def __init__(self, name):
if isinstance(name, str):
self.name = name
self.args = ["%s"]
else:
# name should be a list with arguments
self.name = name[0]
self.args = name[1:]
self.basename = os.path.basename(self.name)
def open(self, url, new=0, autoraise=True):
cmdline = [self.name] + [arg.replace("%s", url)
for arg in self.args]
try:
if sys.platform[:3] == 'win':
p = subprocess.Popen(cmdline)
else:
p = subprocess.Popen(cmdline, close_fds=True)
return not p.wait()
except OSError:
return False
class BackgroundBrowser(GenericBrowser):
"""Class for all browsers which are to be started in the
background."""
def open(self, url, new=0, autoraise=True):
cmdline = [self.name] + [arg.replace("%s", url)
for arg in self.args]
try:
if sys.platform[:3] == 'win':
p = subprocess.Popen(cmdline)
else:
p = subprocess.Popen(cmdline, close_fds=True,
start_new_session=True)
return (p.poll() is None)
except OSError:
return False
class UnixBrowser(BaseBrowser):
"""Parent class for all Unix browsers with remote functionality."""
raise_opts = None
background = False
redirect_stdout = True
# In remote_args, %s will be replaced with the requested URL. %action will
# be replaced depending on the value of 'new' passed to open.
# remote_action is used for new=0 (open). If newwin is not None, it is
# used for new=1 (open_new). If newtab is not None, it is used for
# new=3 (open_new_tab). After both substitutions are made, any empty
# strings in the transformed remote_args list will be removed.
remote_args = ['%action', '%s']
remote_action = None
remote_action_newwin = None
remote_action_newtab = None
def _invoke(self, args, remote, autoraise):
raise_opt = []
if remote and self.raise_opts:
# use autoraise argument only for remote invocation
autoraise = int(autoraise)
opt = self.raise_opts[autoraise]
if opt: raise_opt = [opt]
cmdline = [self.name] + raise_opt + args
if remote or self.background:
inout = subprocess.DEVNULL
else:
# for TTY browsers, we need stdin/out
inout = None
p = subprocess.Popen(cmdline, close_fds=True, stdin=inout,
stdout=(self.redirect_stdout and inout or None),
stderr=inout, start_new_session=True)
if remote:
# wait at most five seconds. If the subprocess is not finished, the
# remote invocation has (hopefully) started a new instance.
try:
rc = p.wait(5)
# if remote call failed, open() will try direct invocation
return not rc
except subprocess.TimeoutExpired:
return True
elif self.background:
if p.poll() is None:
return True
else:
return False
else:
return not p.wait()
def open(self, url, new=0, autoraise=True):
if new == 0:
action = self.remote_action
elif new == 1:
action = self.remote_action_newwin
elif new == 2:
if self.remote_action_newtab is None:
action = self.remote_action_newwin
else:
action = self.remote_action_newtab
else:
raise Error("Bad 'new' parameter to open(); " +
"expected 0, 1, or 2, got %s" % new)
args = [arg.replace("%s", url).replace("%action", action)
for arg in self.remote_args]
args = [arg for arg in args if arg]
success = self._invoke(args, True, autoraise)
if not success:
# remote invocation failed, try straight way
args = [arg.replace("%s", url) for arg in self.args]
return self._invoke(args, False, False)
else:
return True
class Mozilla(UnixBrowser):
"""Launcher class for Mozilla/Netscape browsers."""
raise_opts = ["-noraise", "-raise"]
remote_args = ['-remote', 'openURL(%s%action)']
remote_action = ""
remote_action_newwin = ",new-window"
remote_action_newtab = ",new-tab"
background = True
Netscape = Mozilla
class Galeon(UnixBrowser):
"""Launcher class for Galeon/Epiphany browsers."""
raise_opts = ["-noraise", ""]
remote_args = ['%action', '%s']
remote_action = "-n"
remote_action_newwin = "-w"
background = True
class Chrome(UnixBrowser):
"Launcher class for Google Chrome browser."
remote_args = ['%action', '%s']
remote_action = ""
remote_action_newwin = "--new-window"
remote_action_newtab = ""
background = True
Chromium = Chrome
class Opera(UnixBrowser):
"Launcher class for Opera browser."
raise_opts = ["-noraise", ""]
remote_args = ['-remote', 'openURL(%s%action)']
remote_action = ""
remote_action_newwin = ",new-window"
remote_action_newtab = ",new-page"
background = True
class Elinks(UnixBrowser):
"Launcher class for Elinks browsers."
remote_args = ['-remote', 'openURL(%s%action)']
remote_action = ""
remote_action_newwin = ",new-window"
remote_action_newtab = ",new-tab"
background = False
# elinks doesn't like its stdout to be redirected -
# it uses redirected stdout as a signal to do -dump
redirect_stdout = False
class Konqueror(BaseBrowser):
"""Controller for the KDE File Manager (kfm, or Konqueror).
See the output of ``kfmclient --commands``
for more information on the Konqueror remote-control interface.
"""
def open(self, url, new=0, autoraise=True):
# XXX Currently I know no way to prevent KFM from opening a new win.
if new == 2:
action = "newTab"
else:
action = "openURL"
devnull = subprocess.DEVNULL
try:
p = subprocess.Popen(["kfmclient", action, url],
close_fds=True, stdin=devnull,
stdout=devnull, stderr=devnull)
except OSError:
# fall through to next variant
pass
else:
p.wait()
# kfmclient's return code unfortunately has no meaning as it seems
return True
try:
p = subprocess.Popen(["konqueror", "--silent", url],
close_fds=True, stdin=devnull,
stdout=devnull, stderr=devnull,
start_new_session=True)
except OSError:
# fall through to next variant
pass
else:
if p.poll() is None:
# Should be running now.
return True
try:
p = subprocess.Popen(["kfm", "-d", url],
close_fds=True, stdin=devnull,
stdout=devnull, stderr=devnull,
start_new_session=True)
except OSError:
return False
else:
return (p.poll() is None)
class Grail(BaseBrowser):
# There should be a way to maintain a connection to Grail, but the
# Grail remote control protocol doesn't really allow that at this
# point. It probably never will!
def _find_grail_rc(self):
import glob
import pwd
import socket
import tempfile
tempdir = os.path.join(tempfile.gettempdir(),
".grail-unix")
user = pwd.getpwuid(os.getuid())[0]
filename = os.path.join(tempdir, user + "-*")
maybes = glob.glob(filename)
if not maybes:
return None
s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
for fn in maybes:
# need to PING each one until we find one that's live
try:
s.connect(fn)
except OSError:
# no good; attempt to clean it out, but don't fail:
try:
os.unlink(fn)
except OSError:
pass
else:
return s
def _remote(self, action):
s = self._find_grail_rc()
if not s:
return 0
s.send(action)
s.close()
return 1
def open(self, url, new=0, autoraise=True):
if new:
ok = self._remote("LOADNEW " + url)
else:
ok = self._remote("LOAD " + url)
return ok
#
# Platform support for Unix
#
# These are the right tests because all these Unix browsers require either
# a console terminal or an X display to run.
def register_X_browsers():
# use xdg-open if around
if shutil.which("xdg-open"):
register("xdg-open", None, BackgroundBrowser("xdg-open"))
# The default GNOME3 browser
if "GNOME_DESKTOP_SESSION_ID" in os.environ and shutil.which("gvfs-open"):
register("gvfs-open", None, BackgroundBrowser("gvfs-open"))
# The default GNOME browser
if "GNOME_DESKTOP_SESSION_ID" in os.environ and shutil.which("gnome-open"):
register("gnome-open", None, BackgroundBrowser("gnome-open"))
# The default KDE browser
if "KDE_FULL_SESSION" in os.environ and shutil.which("kfmclient"):
register("kfmclient", Konqueror, Konqueror("kfmclient"))
if shutil.which("x-www-browser"):
register("x-www-browser", None, BackgroundBrowser("x-www-browser"))
# The Mozilla/Netscape browsers
for browser in ("mozilla-firefox", "firefox",
"mozilla-firebird", "firebird",
"iceweasel", "iceape",
"seamonkey", "mozilla", "netscape"):
if shutil.which(browser):
register(browser, None, Mozilla(browser))
# Konqueror/kfm, the KDE browser.
if shutil.which("kfm"):
register("kfm", Konqueror, Konqueror("kfm"))
elif shutil.which("konqueror"):
register("konqueror", Konqueror, Konqueror("konqueror"))
# Gnome's Galeon and Epiphany
for browser in ("galeon", "epiphany"):
if shutil.which(browser):
register(browser, None, Galeon(browser))
# Skipstone, another Gtk/Mozilla based browser
if shutil.which("skipstone"):
register("skipstone", None, BackgroundBrowser("skipstone"))
# Google Chrome/Chromium browsers
for browser in ("google-chrome", "chrome", "chromium", "chromium-browser"):
if shutil.which(browser):
register(browser, None, Chrome(browser))
# Opera, quite popular
if shutil.which("opera"):
register("opera", None, Opera("opera"))
# Next, Mosaic -- old but still in use.
if shutil.which("mosaic"):
register("mosaic", None, BackgroundBrowser("mosaic"))
# Grail, the Python browser. Does anybody still use it?
if shutil.which("grail"):
register("grail", Grail, None)
# Prefer X browsers if present
if os.environ.get("DISPLAY"):
register_X_browsers()
# Also try console browsers
if os.environ.get("TERM"):
if shutil.which("www-browser"):
register("www-browser", None, GenericBrowser("www-browser"))
# The Links/elinks browsers <http://artax.karlin.mff.cuni.cz/~mikulas/links/>
if shutil.which("links"):
register("links", None, GenericBrowser("links"))
if shutil.which("elinks"):
register("elinks", None, Elinks("elinks"))
# The Lynx browser <http://lynx.isc.org/>, <http://lynx.browser.org/>
if shutil.which("lynx"):
register("lynx", None, GenericBrowser("lynx"))
# The w3m browser <http://w3m.sourceforge.net/>
if shutil.which("w3m"):
register("w3m", None, GenericBrowser("w3m"))
#
# Platform support for Windows
#
if sys.platform[:3] == "win":
class WindowsDefault(BaseBrowser):
def open(self, url, new=0, autoraise=True):
try:
os.startfile(url)
except OSError:
# [Error 22] No application is associated with the specified
# file for this operation: '<URL>'
return False
else:
return True
_tryorder = []
_browsers = {}
# First try to use the default Windows browser
register("windows-default", WindowsDefault)
# Detect some common Windows browsers, fallback to IE
iexplore = os.path.join(os.environ.get("PROGRAMFILES", "C:\\Program Files"),
"Internet Explorer\\IEXPLORE.EXE")
for browser in ("firefox", "firebird", "seamonkey", "mozilla",
"netscape", "opera", iexplore):
if shutil.which(browser):
register(browser, None, BackgroundBrowser(browser))
#
# Platform support for MacOS
#
if sys.platform == 'darwin':
# Adapted from patch submitted to SourceForge by Steven J. Burr
class MacOSX(BaseBrowser):
"""Launcher class for Aqua browsers on Mac OS X
Optionally specify a browser name on instantiation. Note that this
will not work for Aqua browsers if the user has moved the application
package after installation.
If no browser is specified, the default browser, as specified in the
Internet System Preferences panel, will be used.
"""
def __init__(self, name):
self.name = name
def open(self, url, new=0, autoraise=True):
assert "'" not in url
# hack for local urls
if not ':' in url:
url = 'file:'+url
# new must be 0 or 1
new = int(bool(new))
if self.name == "default":
# User called open, open_new or get without a browser parameter
script = 'open location "%s"' % url.replace('"', '%22') # opens in default browser
else:
# User called get and chose a browser
if self.name == "OmniWeb":
toWindow = ""
else:
# Include toWindow parameter of OpenURL command for browsers
# that support it. 0 == new window; -1 == existing
toWindow = "toWindow %d" % (new - 1)
cmd = 'OpenURL "%s"' % url.replace('"', '%22')
script = '''tell application "%s"
activate
%s %s
end tell''' % (self.name, cmd, toWindow)
# Open pipe to AppleScript through osascript command
osapipe = os.popen("osascript", "w")
if osapipe is None:
return False
# Write script to osascript's stdin
osapipe.write(script)
rc = osapipe.close()
return not rc
class MacOSXOSAScript(BaseBrowser):
def __init__(self, name):
self._name = name
def open(self, url, new=0, autoraise=True):
if self._name == 'default':
script = 'open location "%s"' % url.replace('"', '%22') # opens in default browser
else:
script = '''
tell application "%s"
activate
open location "%s"
end
'''%(self._name, url.replace('"', '%22'))
osapipe = os.popen("osascript", "w")
if osapipe is None:
return False
osapipe.write(script)
rc = osapipe.close()
return not rc
# Don't clear _tryorder or _browsers since OS X can use above Unix support
# (but we prefer using the OS X specific stuff)
register("safari", None, MacOSXOSAScript('safari'), -1)
register("firefox", None, MacOSXOSAScript('firefox'), -1)
register("MacOSX", None, MacOSXOSAScript('default'), -1)
# OK, now that we know what the default preference orders for each
# platform are, allow user to override them with the BROWSER variable.
if "BROWSER" in os.environ:
_userchoices = os.environ["BROWSER"].split(os.pathsep)
_userchoices.reverse()
# Treat choices in same way as if passed into get() but do register
# and prepend to _tryorder
for cmdline in _userchoices:
if cmdline != '':
cmd = _synthesize(cmdline, -1)
if cmd[1] is None:
register(cmdline, None, GenericBrowser(cmdline), -1)
cmdline = None # to make del work if _userchoices was empty
del cmdline
del _userchoices
# what to do if _tryorder is now empty?
def main():
import getopt
usage = """Usage: %s [-n | -t] url
-n: open new window
-t: open new tab""" % sys.argv[0]
try:
opts, args = getopt.getopt(sys.argv[1:], 'ntd')
except getopt.error as msg:
print(msg, file=sys.stderr)
print(usage, file=sys.stderr)
sys.exit(1)
new_win = 0
for o, a in opts:
if o == '-n': new_win = 1
elif o == '-t': new_win = 2
if len(args) != 1:
print(usage, file=sys.stderr)
sys.exit(1)
url = args[0]
open(url, new_win)
print("\a")
if __name__ == "__main__":
main()
| lgpl-3.0 |
JimCircadian/ansible | lib/ansible/modules/clustering/pacemaker_cluster.py | 73 | 7080 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2016, Mathieu Bultel <[email protected]>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = '''
---
module: pacemaker_cluster
short_description: Manage pacemaker clusters
version_added: "2.3"
author:
- Mathieu Bultel (@matbu)
description:
- This module can manage a pacemaker cluster and nodes from Ansible using
the pacemaker cli.
options:
state:
description:
- Indicate desired state of the cluster
choices: [ cleanup, offline, online, restart ]
required: yes
node:
description:
- Specify which node of the cluster you want to manage. None == the
cluster status itself, 'all' == check the status of all nodes.
timeout:
description:
- Timeout when the module should considered that the action has failed
default: 300
force:
description:
- Force the change of the cluster state
type: bool
default: 'yes'
'''
EXAMPLES = '''
---
- name: Set cluster Online
hosts: localhost
gather_facts: no
tasks:
- name: Get cluster state
pacemaker_cluster:
state: online
'''
RETURN = '''
changed:
description: True if the cluster state has changed
type: bool
returned: always
out:
description: The output of the current state of the cluster. It return a
list of the nodes state.
type: string
sample: 'out: [[" overcloud-controller-0", " Online"]]}'
returned: always
rc:
description: exit code of the module
type: bool
returned: always
'''
import time
from ansible.module_utils.basic import AnsibleModule
_PCS_CLUSTER_DOWN = "Error: cluster is not currently running on this node"
def get_cluster_status(module):
cmd = "pcs cluster status"
rc, out, err = module.run_command(cmd)
if out in _PCS_CLUSTER_DOWN:
return 'offline'
else:
return 'online'
def get_node_status(module, node='all'):
if node == 'all':
cmd = "pcs cluster pcsd-status %s" % node
else:
cmd = "pcs cluster pcsd-status"
rc, out, err = module.run_command(cmd)
if rc is 1:
module.fail_json(msg="Command execution failed.\nCommand: `%s`\nError: %s" % (cmd, err))
status = []
for o in out.splitlines():
status.append(o.split(':'))
return status
def clean_cluster(module, timeout):
cmd = "pcs resource cleanup"
rc, out, err = module.run_command(cmd)
if rc is 1:
module.fail_json(msg="Command execution failed.\nCommand: `%s`\nError: %s" % (cmd, err))
def set_cluster(module, state, timeout, force):
if state == 'online':
cmd = "pcs cluster start"
if state == 'offline':
cmd = "pcs cluster stop"
if force:
cmd = "%s --force" % cmd
rc, out, err = module.run_command(cmd)
if rc is 1:
module.fail_json(msg="Command execution failed.\nCommand: `%s`\nError: %s" % (cmd, err))
t = time.time()
ready = False
while time.time() < t + timeout:
cluster_state = get_cluster_status(module)
if cluster_state == state:
ready = True
break
if not ready:
module.fail_json(msg="Failed to set the state `%s` on the cluster\n" % (state))
def set_node(module, state, timeout, force, node='all'):
# map states
if state == 'online':
cmd = "pcs cluster start"
if state == 'offline':
cmd = "pcs cluster stop"
if force:
cmd = "%s --force" % cmd
nodes_state = get_node_status(module, node)
for node in nodes_state:
if node[1].strip().lower() != state:
cmd = "%s %s" % (cmd, node[0].strip())
rc, out, err = module.run_command(cmd)
if rc is 1:
module.fail_json(msg="Command execution failed.\nCommand: `%s`\nError: %s" % (cmd, err))
t = time.time()
ready = False
while time.time() < t + timeout:
nodes_state = get_node_status(module)
for node in nodes_state:
if node[1].strip().lower() == state:
ready = True
break
if not ready:
module.fail_json(msg="Failed to set the state `%s` on the cluster\n" % (state))
def main():
argument_spec = dict(
state=dict(type='str', choices=['online', 'offline', 'restart', 'cleanup']),
node=dict(type='str'),
timeout=dict(type='int', default=300),
force=dict(type='bool', default=True),
)
module = AnsibleModule(
argument_spec,
supports_check_mode=True,
)
changed = False
state = module.params['state']
node = module.params['node']
force = module.params['force']
timeout = module.params['timeout']
if state in ['online', 'offline']:
# Get cluster status
if node is None:
cluster_state = get_cluster_status(module)
if cluster_state == state:
module.exit_json(changed=changed, out=cluster_state)
else:
set_cluster(module, state, timeout, force)
cluster_state = get_cluster_status(module)
if cluster_state == state:
module.exit_json(changed=True, out=cluster_state)
else:
module.fail_json(msg="Fail to bring the cluster %s" % state)
else:
cluster_state = get_node_status(module, node)
# Check cluster state
for node_state in cluster_state:
if node_state[1].strip().lower() == state:
module.exit_json(changed=changed, out=cluster_state)
else:
# Set cluster status if needed
set_cluster(module, state, timeout, force)
cluster_state = get_node_status(module, node)
module.exit_json(changed=True, out=cluster_state)
if state in ['restart']:
set_cluster(module, 'offline', timeout, force)
cluster_state = get_cluster_status(module)
if cluster_state == 'offline':
set_cluster(module, 'online', timeout, force)
cluster_state = get_cluster_status(module)
if cluster_state == 'online':
module.exit_json(changed=True, out=cluster_state)
else:
module.fail_json(msg="Failed during the restart of the cluster, the cluster can't be started")
else:
module.fail_json(msg="Failed during the restart of the cluster, the cluster can't be stopped")
if state in ['cleanup']:
clean_cluster(module, timeout)
cluster_state = get_cluster_status(module)
module.exit_json(changed=True,
out=cluster_state)
if __name__ == '__main__':
main()
| gpl-3.0 |
redhatrises/freeipa | ipaclient/remote_plugins/2_164/sudocmdgroup.py | 16 | 14989 | #
# Copyright (C) 2016 FreeIPA Contributors see COPYING for license
#
# pylint: disable=unused-import
import six
from . import Command, Method, Object
from ipalib import api, parameters, output
from ipalib.parameters import DefaultFrom
from ipalib.plugable import Registry
from ipalib.text import _
from ipapython.dn import DN
from ipapython.dnsutil import DNSName
if six.PY3:
unicode = str
__doc__ = _("""
Groups of Sudo Commands
Manage groups of Sudo Commands.
EXAMPLES:
Add a new Sudo Command Group:
ipa sudocmdgroup-add --desc='administrators commands' admincmds
Remove a Sudo Command Group:
ipa sudocmdgroup-del admincmds
Manage Sudo Command Group membership, commands:
ipa sudocmdgroup-add-member --sudocmds=/usr/bin/less --sudocmds=/usr/bin/vim admincmds
Manage Sudo Command Group membership, commands:
ipa group-remove-member --sudocmds=/usr/bin/less admincmds
Show a Sudo Command Group:
ipa group-show localadmins
""")
register = Registry()
@register()
class sudocmdgroup(Object):
takes_params = (
parameters.Str(
'cn',
primary_key=True,
label=_(u'Sudo Command Group'),
),
parameters.Str(
'description',
required=False,
label=_(u'Description'),
doc=_(u'Group description'),
),
parameters.Str(
'membercmd_sudocmd',
required=False,
label=_(u'Commands'),
),
parameters.Str(
'membercmd_sudocmdgroup',
required=False,
label=_(u'Sudo Command Groups'),
),
parameters.Str(
'member_sudocmd',
required=False,
label=_(u'Member Sudo commands'),
),
)
@register()
class sudocmdgroup_add(Method):
__doc__ = _("Create new Sudo Command Group.")
takes_args = (
parameters.Str(
'cn',
cli_name='sudocmdgroup_name',
label=_(u'Sudo Command Group'),
no_convert=True,
),
)
takes_options = (
parameters.Str(
'description',
required=False,
cli_name='desc',
label=_(u'Description'),
doc=_(u'Group description'),
),
parameters.Str(
'setattr',
required=False,
multivalue=True,
doc=_(u'Set an attribute to a name/value pair. Format is attr=value.\nFor multi-valued attributes, the command replaces the values already present.'),
exclude=('webui',),
),
parameters.Str(
'addattr',
required=False,
multivalue=True,
doc=_(u'Add an attribute/value pair. Format is attr=value. The attribute\nmust be part of the schema.'),
exclude=('webui',),
),
parameters.Flag(
'all',
doc=_(u'Retrieve and print all attributes from the server. Affects command output.'),
exclude=('webui',),
default=False,
autofill=True,
),
parameters.Flag(
'raw',
doc=_(u'Print entries as stored on the server. Only affects output format.'),
exclude=('webui',),
default=False,
autofill=True,
),
parameters.Flag(
'no_members',
doc=_(u'Suppress processing of membership attributes.'),
exclude=('webui', 'cli'),
default=False,
autofill=True,
),
)
has_output = (
output.Output(
'summary',
(unicode, type(None)),
doc=_(u'User-friendly description of action performed'),
),
output.Entry(
'result',
),
output.PrimaryKey(
'value',
doc=_(u"The primary_key value of the entry, e.g. 'jdoe' for a user"),
),
)
@register()
class sudocmdgroup_add_member(Method):
__doc__ = _("Add members to Sudo Command Group.")
takes_args = (
parameters.Str(
'cn',
cli_name='sudocmdgroup_name',
label=_(u'Sudo Command Group'),
no_convert=True,
),
)
takes_options = (
parameters.Flag(
'all',
doc=_(u'Retrieve and print all attributes from the server. Affects command output.'),
exclude=('webui',),
default=False,
autofill=True,
),
parameters.Flag(
'raw',
doc=_(u'Print entries as stored on the server. Only affects output format.'),
exclude=('webui',),
default=False,
autofill=True,
),
parameters.Flag(
'no_members',
doc=_(u'Suppress processing of membership attributes.'),
exclude=('webui', 'cli'),
default=False,
autofill=True,
),
parameters.Str(
'sudocmd',
required=False,
multivalue=True,
cli_name='sudocmds',
label=_(u'member sudo command'),
doc=_(u'sudo commands to add'),
alwaysask=True,
),
)
has_output = (
output.Entry(
'result',
),
output.Output(
'failed',
dict,
doc=_(u'Members that could not be added'),
),
output.Output(
'completed',
int,
doc=_(u'Number of members added'),
),
)
@register()
class sudocmdgroup_del(Method):
__doc__ = _("Delete Sudo Command Group.")
takes_args = (
parameters.Str(
'cn',
multivalue=True,
cli_name='sudocmdgroup_name',
label=_(u'Sudo Command Group'),
no_convert=True,
),
)
takes_options = (
parameters.Flag(
'continue',
doc=_(u"Continuous mode: Don't stop on errors."),
default=False,
autofill=True,
),
)
has_output = (
output.Output(
'summary',
(unicode, type(None)),
doc=_(u'User-friendly description of action performed'),
),
output.Output(
'result',
dict,
doc=_(u'List of deletions that failed'),
),
output.ListOfPrimaryKeys(
'value',
),
)
@register()
class sudocmdgroup_find(Method):
__doc__ = _("Search for Sudo Command Groups.")
takes_args = (
parameters.Str(
'criteria',
required=False,
doc=_(u'A string searched in all relevant object attributes'),
),
)
takes_options = (
parameters.Str(
'cn',
required=False,
cli_name='sudocmdgroup_name',
label=_(u'Sudo Command Group'),
no_convert=True,
),
parameters.Str(
'description',
required=False,
cli_name='desc',
label=_(u'Description'),
doc=_(u'Group description'),
),
parameters.Int(
'timelimit',
required=False,
label=_(u'Time Limit'),
doc=_(u'Time limit of search in seconds (0 is unlimited)'),
),
parameters.Int(
'sizelimit',
required=False,
label=_(u'Size Limit'),
doc=_(u'Maximum number of entries returned (0 is unlimited)'),
),
parameters.Flag(
'all',
doc=_(u'Retrieve and print all attributes from the server. Affects command output.'),
exclude=('webui',),
default=False,
autofill=True,
),
parameters.Flag(
'raw',
doc=_(u'Print entries as stored on the server. Only affects output format.'),
exclude=('webui',),
default=False,
autofill=True,
),
parameters.Flag(
'no_members',
doc=_(u'Suppress processing of membership attributes.'),
exclude=('webui', 'cli'),
default=False,
autofill=True,
),
parameters.Flag(
'pkey_only',
required=False,
label=_(u'Primary key only'),
doc=_(u'Results should contain primary key attribute only ("sudocmdgroup-name")'),
default=False,
autofill=True,
),
)
has_output = (
output.Output(
'summary',
(unicode, type(None)),
doc=_(u'User-friendly description of action performed'),
),
output.ListOfEntries(
'result',
),
output.Output(
'count',
int,
doc=_(u'Number of entries returned'),
),
output.Output(
'truncated',
bool,
doc=_(u'True if not all results were returned'),
),
)
@register()
class sudocmdgroup_mod(Method):
__doc__ = _("Modify Sudo Command Group.")
takes_args = (
parameters.Str(
'cn',
cli_name='sudocmdgroup_name',
label=_(u'Sudo Command Group'),
no_convert=True,
),
)
takes_options = (
parameters.Str(
'description',
required=False,
cli_name='desc',
label=_(u'Description'),
doc=_(u'Group description'),
),
parameters.Str(
'setattr',
required=False,
multivalue=True,
doc=_(u'Set an attribute to a name/value pair. Format is attr=value.\nFor multi-valued attributes, the command replaces the values already present.'),
exclude=('webui',),
),
parameters.Str(
'addattr',
required=False,
multivalue=True,
doc=_(u'Add an attribute/value pair. Format is attr=value. The attribute\nmust be part of the schema.'),
exclude=('webui',),
),
parameters.Str(
'delattr',
required=False,
multivalue=True,
doc=_(u'Delete an attribute/value pair. The option will be evaluated\nlast, after all sets and adds.'),
exclude=('webui',),
),
parameters.Flag(
'rights',
label=_(u'Rights'),
doc=_(u'Display the access rights of this entry (requires --all). See ipa man page for details.'),
default=False,
autofill=True,
),
parameters.Flag(
'all',
doc=_(u'Retrieve and print all attributes from the server. Affects command output.'),
exclude=('webui',),
default=False,
autofill=True,
),
parameters.Flag(
'raw',
doc=_(u'Print entries as stored on the server. Only affects output format.'),
exclude=('webui',),
default=False,
autofill=True,
),
parameters.Flag(
'no_members',
doc=_(u'Suppress processing of membership attributes.'),
exclude=('webui', 'cli'),
default=False,
autofill=True,
),
)
has_output = (
output.Output(
'summary',
(unicode, type(None)),
doc=_(u'User-friendly description of action performed'),
),
output.Entry(
'result',
),
output.PrimaryKey(
'value',
doc=_(u"The primary_key value of the entry, e.g. 'jdoe' for a user"),
),
)
@register()
class sudocmdgroup_remove_member(Method):
__doc__ = _("Remove members from Sudo Command Group.")
takes_args = (
parameters.Str(
'cn',
cli_name='sudocmdgroup_name',
label=_(u'Sudo Command Group'),
no_convert=True,
),
)
takes_options = (
parameters.Flag(
'all',
doc=_(u'Retrieve and print all attributes from the server. Affects command output.'),
exclude=('webui',),
default=False,
autofill=True,
),
parameters.Flag(
'raw',
doc=_(u'Print entries as stored on the server. Only affects output format.'),
exclude=('webui',),
default=False,
autofill=True,
),
parameters.Flag(
'no_members',
doc=_(u'Suppress processing of membership attributes.'),
exclude=('webui', 'cli'),
default=False,
autofill=True,
),
parameters.Str(
'sudocmd',
required=False,
multivalue=True,
cli_name='sudocmds',
label=_(u'member sudo command'),
doc=_(u'sudo commands to remove'),
alwaysask=True,
),
)
has_output = (
output.Entry(
'result',
),
output.Output(
'failed',
dict,
doc=_(u'Members that could not be removed'),
),
output.Output(
'completed',
int,
doc=_(u'Number of members removed'),
),
)
@register()
class sudocmdgroup_show(Method):
__doc__ = _("Display Sudo Command Group.")
takes_args = (
parameters.Str(
'cn',
cli_name='sudocmdgroup_name',
label=_(u'Sudo Command Group'),
no_convert=True,
),
)
takes_options = (
parameters.Flag(
'rights',
label=_(u'Rights'),
doc=_(u'Display the access rights of this entry (requires --all). See ipa man page for details.'),
default=False,
autofill=True,
),
parameters.Flag(
'all',
doc=_(u'Retrieve and print all attributes from the server. Affects command output.'),
exclude=('webui',),
default=False,
autofill=True,
),
parameters.Flag(
'raw',
doc=_(u'Print entries as stored on the server. Only affects output format.'),
exclude=('webui',),
default=False,
autofill=True,
),
parameters.Flag(
'no_members',
doc=_(u'Suppress processing of membership attributes.'),
exclude=('webui', 'cli'),
default=False,
autofill=True,
),
)
has_output = (
output.Output(
'summary',
(unicode, type(None)),
doc=_(u'User-friendly description of action performed'),
),
output.Entry(
'result',
),
output.PrimaryKey(
'value',
doc=_(u"The primary_key value of the entry, e.g. 'jdoe' for a user"),
),
)
| gpl-3.0 |
rahuldhote/odoo | addons/sale_service/__openerp__.py | 260 | 2447 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 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/>.
#
##############################################################################
{
'name': 'Create Tasks on SO',
'version': '1.0',
'category': 'Project Management',
'description': """
Automatically creates project tasks from procurement lines.
===========================================================
This module will automatically create a new task for each procurement order line
(e.g. for sale order lines), if the corresponding product meets the following
characteristics:
* Product Type = Service
* Procurement Method (Order fulfillment) = MTO (Make to Order)
* Supply/Procurement Method = Manufacture
If on top of that a projet is specified on the product form (in the Procurement
tab), then the new task will be created in that specific project. Otherwise, the
new task will not belong to any project, and may be added to a project manually
later.
When the project task is completed or cancelled, the corresponding procurement
is updated accordingly. For example, if this procurement corresponds to a sale
order line, the sale order line will be considered delivered when the task is
completed.
""",
'author': 'OpenERP SA',
'website': 'https://www.odoo.com/page/crm',
'depends': ['project', 'procurement', 'sale', 'procurement_jit'],
'data': ['views/sale_service_view.xml'],
'demo': ['demo/sale_service_demo.xml'],
'test': ['test/project_task_procurement.yml'],
'installable': True,
'auto_install': False,
}
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
| agpl-3.0 |
chauhanmohit/phantomjs | src/qt/qtwebkit/Tools/Scripts/webkitperl/prepare-ChangeLog_unittest/resources/python_unittests.py | 130 | 1524 | #
# Copyright (C) 2011 Google Inc. All rights reserved.
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Library General Public
# License as published by the Free Software Foundation; either
# version 2 of the License, or (at your option) any later version.
#
# This library 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
# Library General Public License for more details.
#
# You should have received a copy of the GNU Library General Public License
# along with this library; see the file COPYING.LIB. If not, write to
# the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
# Boston, MA 02110-1301, USA.
#
def func1():
def func2():
return
def func3():
# comment
return
# def funcInsideComment():
def func4(a):
return
def func5(a, b, c):
return
def func6(a, b, \
c, d):
return
def funcOverloaded(a):
return
def funcOverloaded(a, b):
return
def funcOverloaded(a, b, c=100):
return
def func7():
pass
def func8():
pass
def func9():
pass
pass
pass
class Class1:
pass
class Class2:
pass
class Class3:
pass
class Class4:
pass
pass
pass
class Class5:
pass
def func10():
pass
pass
def func11():
pass
pass
| bsd-3-clause |
devigned/autorest | src/generator/AutoRest.Python.Tests/Expected/AcceptanceTests/Validation/autorestvalidationtest/models/product.py | 14 | 3026 | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
from .constant_product import ConstantProduct
from msrest.serialization import Model
class Product(Model):
"""The product documentation.
Variables are only populated by the server, and will be ignored when
sending a request.
:param display_names: Non required array of unique items from 0 to 6
elements.
:type display_names: list of str
:param capacity: Non required int betwen 0 and 100 exclusive.
:type capacity: int
:param image: Image URL representing the product.
:type image: str
:param child:
:type child: :class:`ChildProduct
<fixtures.acceptancetestsvalidation.models.ChildProduct>`
:ivar const_child:
:vartype const_child: :class:`ConstantProduct
<fixtures.acceptancetestsvalidation.models.ConstantProduct>`
:ivar const_int: Constant int. Default value: 0 .
:vartype const_int: int
:ivar const_string: Constant string. Default value: "constant" .
:vartype const_string: str
:param const_string_as_enum: Constant string as Enum. Possible values
include: 'constant_string_as_enum'
:type const_string_as_enum: str or :class:`EnumConst
<fixtures.acceptancetestsvalidation.models.EnumConst>`
"""
_validation = {
'display_names': {'max_items': 6, 'min_items': 0, 'unique': True},
'capacity': {'maximum_ex': 100, 'minimum_ex': 0},
'image': {'pattern': 'http://\w+'},
'child': {'required': True},
'const_child': {'required': True, 'constant': True},
'const_int': {'required': True, 'constant': True},
'const_string': {'required': True, 'constant': True},
}
_attribute_map = {
'display_names': {'key': 'display_names', 'type': '[str]'},
'capacity': {'key': 'capacity', 'type': 'int'},
'image': {'key': 'image', 'type': 'str'},
'child': {'key': 'child', 'type': 'ChildProduct'},
'const_child': {'key': 'constChild', 'type': 'ConstantProduct'},
'const_int': {'key': 'constInt', 'type': 'int'},
'const_string': {'key': 'constString', 'type': 'str'},
'const_string_as_enum': {'key': 'constStringAsEnum', 'type': 'EnumConst'},
}
const_child = ConstantProduct()
const_int = 0
const_string = "constant"
def __init__(self, child, display_names=None, capacity=None, image=None, const_string_as_enum=None):
self.display_names = display_names
self.capacity = capacity
self.image = image
self.child = child
self.const_string_as_enum = const_string_as_enum
| mit |
daafgo/CourseBuilder-Xapi | tools/etl/etl_lib.py | 10 | 7662 | # Copyright 2013 Google Inc. 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.
"""Libraries for writing extract-transform-load scripts."""
__author__ = [
'[email protected]',
]
import argparse
import datetime
import time
from controllers import sites
from models import courses
def get_context(course_url_prefix):
"""Gets requested application context from the given course URL prefix.
Args:
course_url_prefix: string. Value of etl.py's course_url_prefix flag.
Returns:
sites.ApplicationContext.
"""
found = None
for context in sites.get_all_courses():
if context.raw.startswith('course:%s:' % course_url_prefix):
found = context
break
return found
def get_course(app_context):
"""Gets a courses.Course from the given sites.ApplicationContext.
Does not ensure the course exists on the backend; validation should be done
by the caller when getting the app_context object.
Args:
app_context: sites.ApplicationContext. The context we're getting the
course for.
Returns:
courses.Course.
"""
class _Adapter(object):
def __init__(self, app_context):
self.app_context = app_context
return courses.Course(_Adapter(app_context))
class Job(object):
"""Abstract base class for user-defined custom ETL jobs.
Custom jobs can be executed by etl.py. The advantage of this is that they
can run arbitrary local computations, but calls to App Engine services
(db.get() or db.put(), for example) are executed against a remove server.
This allows you to perform arbitrary computations against your app's data,
and to construct data pipelines that are not possible within the App Engine
execution environment.
When you run your custom job under etl.py in this way, it authenticates
against the remove server, prompting the user for credentials if necessary.
It then configures the local environment so RPCs execute against the
requested remote endpoint.
It then imports your custom job. Your job must be a Python class that is
a child of this class. Before invoking etl.py, you must configure sys.path
so all required libraries are importable. See etl.py for details. Your
class must override main() with the computations you want your job to
perform.
You invoke your custom job via etl.py:
$ python etl.py run path.to.my.Job /cs101 myapp server.appspot.com \
--job_args='more_args --delegated_to my.Job'
Before main() is executed, arguments are parsed. The full set of parsed
arguments passed to etl.py are available in your job as self.etl_args. The
arguments passed as a quote-enclosed string to --job_args, if any, are
delegated to your job. An argument parser is available as self.parser. You
must override self._configure_parser to register command-line arguments for
parsing. They will be parsed in advance of running main() and will be
available as self.args.
See tools/etl/examples.py for some nontrivial sample job implementations.
"""
def __init__(self, parsed_etl_args):
"""Constructs a new job.
Args:
parsed_etl_args: argparse.Namespace. Parsed arguments passed to
etl.py.
"""
self._parsed_args = None
self._parsed_etl_args = parsed_etl_args
self._parser = None
def _configure_parser(self):
"""Configures custom command line parser for this job, if any.
For example:
self.parser.add_argument(
'my_arg', help='A required argument', type=str)
"""
pass
def main(self):
"""Computations made by this job; must be overridden in subclass."""
pass
@property
def args(self):
"""Returns etl.py's parsed --job_args, or None if run() not invoked."""
return self._parsed_args
@property
def etl_args(self):
"""Returns parsed etl.py arguments."""
return self._parsed_etl_args
@property
def parser(self):
"""Returns argparse.ArgumentParser, or None if run() not yet invoked."""
if not self._parser:
self._parser = argparse.ArgumentParser(
prog='%s.%s' % (
self.__class__.__module__, self.__class__.__name__),
usage=(
'etl.py run %(prog)s [etl.py options] [--job_args] '
'[%(prog)s options]'))
return self._parser
def _parse_args(self):
self._configure_parser()
self._parsed_args = self.parser.parse_args(
self._parsed_etl_args.job_args)
def run(self):
"""Executes the job; called for you by etl.py."""
self._parse_args()
self.main()
class _ProgressReporter(object):
"""Provide intermittent reports on progress of a long-running operation."""
def __init__(self, logger, verb, noun, chunk_size, total, num_history=10):
self._logger = logger
self._verb = verb
self._noun = noun
self._chunk_size = chunk_size
self._total = total
self._num_history = num_history
self._rate_history = []
self._start_time = self._chunk_start_time = time.time()
self._total_count = 0
self._chunk_count = 0
def count(self, quantity=1):
self._total_count += quantity
self._chunk_count += quantity
while self._chunk_count >= self._chunk_size:
now = time.time()
self._chunk_count -= self._chunk_size
self._rate_history.append(now - self._chunk_start_time)
self._chunk_start_time = now
while len(self._rate_history) > self._num_history:
del self._rate_history[0]
self.report()
def get_count(self):
return self._total_count
def report(self):
now = time.time()
total_time = datetime.timedelta(
days=0, seconds=int(now - self._start_time))
if not sum(self._rate_history):
rate = 0
time_left = 0
expected_total = 0
else:
rate = ((len(self._rate_history) * self._chunk_size) /
sum(self._rate_history))
time_left = datetime.timedelta(
days=0,
seconds=int((self._total - self._total_count) / rate))
expected_total = datetime.timedelta(
days=0, seconds=int(self._total / rate))
self._logger.info(
'%(verb)s %(total_count)9d of %(total)d %(noun)s '
'in %(total_time)s. Recent rate is %(rate)d/sec; '
'%(time_left)s seconds to go '
'(%(expected_total)s total) at this rate.' %
{
'verb': self._verb,
'total_count': self._total_count,
'total': self._total,
'noun': self._noun,
'total_time': total_time,
'rate': rate,
'time_left': time_left,
'expected_total': expected_total
})
| apache-2.0 |
kennedyshead/home-assistant | homeassistant/components/islamic_prayer_times/__init__.py | 2 | 6894 | """The islamic_prayer_times component."""
from datetime import timedelta
import logging
from prayer_times_calculator import PrayerTimesCalculator, exceptions
from requests.exceptions import ConnectionError as ConnError
import voluptuous as vol
from homeassistant.config_entries import SOURCE_IMPORT
from homeassistant.exceptions import ConfigEntryNotReady
from homeassistant.helpers import config_validation as cv
from homeassistant.helpers.dispatcher import async_dispatcher_send
from homeassistant.helpers.event import async_call_later, async_track_point_in_time
import homeassistant.util.dt as dt_util
from .const import (
CALC_METHODS,
CONF_CALC_METHOD,
DATA_UPDATED,
DEFAULT_CALC_METHOD,
DOMAIN,
)
_LOGGER = logging.getLogger(__name__)
PLATFORMS = ["sensor"]
CONFIG_SCHEMA = vol.Schema(
vol.All(
cv.deprecated(DOMAIN),
{
DOMAIN: {
vol.Optional(CONF_CALC_METHOD, default=DEFAULT_CALC_METHOD): vol.In(
CALC_METHODS
),
}
},
),
extra=vol.ALLOW_EXTRA,
)
async def async_setup(hass, config):
"""Import the Islamic Prayer component from config."""
if DOMAIN in config:
hass.async_create_task(
hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_IMPORT}, data=config[DOMAIN]
)
)
return True
async def async_setup_entry(hass, config_entry):
"""Set up the Islamic Prayer Component."""
client = IslamicPrayerClient(hass, config_entry)
if not await client.async_setup():
return False
hass.data.setdefault(DOMAIN, client)
return True
async def async_unload_entry(hass, config_entry):
"""Unload Islamic Prayer entry from config_entry."""
if hass.data[DOMAIN].event_unsub:
hass.data[DOMAIN].event_unsub()
hass.data.pop(DOMAIN)
return await hass.config_entries.async_unload_platforms(config_entry, PLATFORMS)
class IslamicPrayerClient:
"""Islamic Prayer Client Object."""
def __init__(self, hass, config_entry):
"""Initialize the Islamic Prayer client."""
self.hass = hass
self.config_entry = config_entry
self.prayer_times_info = {}
self.available = True
self.event_unsub = None
@property
def calc_method(self):
"""Return the calculation method."""
return self.config_entry.options[CONF_CALC_METHOD]
def get_new_prayer_times(self):
"""Fetch prayer times for today."""
calc = PrayerTimesCalculator(
latitude=self.hass.config.latitude,
longitude=self.hass.config.longitude,
calculation_method=self.calc_method,
date=str(dt_util.now().date()),
)
return calc.fetch_prayer_times()
async def async_schedule_future_update(self):
"""Schedule future update for sensors.
Midnight is a calculated time. The specifics of the calculation
depends on the method of the prayer time calculation. This calculated
midnight is the time at which the time to pray the Isha prayers have
expired.
Calculated Midnight: The Islamic midnight.
Traditional Midnight: 12:00AM
Update logic for prayer times:
If the Calculated Midnight is before the traditional midnight then wait
until the traditional midnight to run the update. This way the day
will have changed over and we don't need to do any fancy calculations.
If the Calculated Midnight is after the traditional midnight, then wait
until after the calculated Midnight. We don't want to update the prayer
times too early or else the timings might be incorrect.
Example:
calculated midnight = 11:23PM (before traditional midnight)
Update time: 12:00AM
calculated midnight = 1:35AM (after traditional midnight)
update time: 1:36AM.
"""
_LOGGER.debug("Scheduling next update for Islamic prayer times")
now = dt_util.utcnow()
midnight_dt = self.prayer_times_info["Midnight"]
if now > dt_util.as_utc(midnight_dt):
next_update_at = midnight_dt + timedelta(days=1, minutes=1)
_LOGGER.debug(
"Midnight is after day the changes so schedule update for after Midnight the next day"
)
else:
_LOGGER.debug(
"Midnight is before the day changes so schedule update for the next start of day"
)
next_update_at = dt_util.start_of_local_day(now + timedelta(days=1))
_LOGGER.info("Next update scheduled for: %s", next_update_at)
self.event_unsub = async_track_point_in_time(
self.hass, self.async_update, next_update_at
)
async def async_update(self, *_):
"""Update sensors with new prayer times."""
try:
prayer_times = await self.hass.async_add_executor_job(
self.get_new_prayer_times
)
self.available = True
except (exceptions.InvalidResponseError, ConnError):
self.available = False
_LOGGER.debug("Error retrieving prayer times")
async_call_later(self.hass, 60, self.async_update)
return
for prayer, time in prayer_times.items():
self.prayer_times_info[prayer] = dt_util.parse_datetime(
f"{dt_util.now().date()} {time}"
)
await self.async_schedule_future_update()
_LOGGER.debug("New prayer times retrieved. Updating sensors")
async_dispatcher_send(self.hass, DATA_UPDATED)
async def async_setup(self):
"""Set up the Islamic prayer client."""
await self.async_add_options()
try:
await self.hass.async_add_executor_job(self.get_new_prayer_times)
except (exceptions.InvalidResponseError, ConnError) as err:
raise ConfigEntryNotReady from err
await self.async_update()
self.config_entry.add_update_listener(self.async_options_updated)
self.hass.config_entries.async_setup_platforms(self.config_entry, PLATFORMS)
return True
async def async_add_options(self):
"""Add options for entry."""
if not self.config_entry.options:
data = dict(self.config_entry.data)
calc_method = data.pop(CONF_CALC_METHOD, DEFAULT_CALC_METHOD)
self.hass.config_entries.async_update_entry(
self.config_entry, data=data, options={CONF_CALC_METHOD: calc_method}
)
@staticmethod
async def async_options_updated(hass, entry):
"""Triggered by config entry options updates."""
if hass.data[DOMAIN].event_unsub:
hass.data[DOMAIN].event_unsub()
await hass.data[DOMAIN].async_update()
| apache-2.0 |
google-research/falken | service/learner/brains/brain_cache.py | 1 | 3449 | # Copyright 2021 Google LLC
#
# 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.
# Lint as: python3
"""LRU cache for brain instances."""
import collections
from learner.brains import continuous_imitation_brain
from log import falken_logging
class BrainCache:
"""Least Recently Used (LRU) cache of brain instances."""
def __init__(self, hparam_defaults_populator_and_validator, size=8):
"""Initialize the cache.
Args:
hparam_defaults_populator_and_validator: Callable that takes a dictionary
of hyperparameters, validates them, populates the dictionary with
defaults and returns the validated dictionary.
size: Number of brains to cache.
"""
# Cache of brains by an opaque key string.
# Items are ordered by most recently used first, least recently used last.
self._brains = collections.OrderedDict()
self._size = size
self._hparam_defaults_populator_and_validator = (
hparam_defaults_populator_and_validator)
def GetOrCreateBrain(self, hparams, brain_spec, checkpoint_path,
summary_path):
"""Get a brain from the cache or create a new one if it isn't found.
Args:
hparams: Hyperparmeters used to create the brain.
brain_spec: BrainSpec proto used to create the brain.
checkpoint_path: Path to store checkpoints of the brain.
summary_path: Path to store summaries of the brain.
Returns:
(brain, hparams) tuple where brain is a ContinuousImitationBrain instance
and hparams are the hyperparameters used to create the brain.
"""
hparams = self._hparam_defaults_populator_and_validator(hparams)
key = str(brain_spec) + str(hparams)
brain = self._brains.get(key)
if brain:
falken_logging.info(f'Retrieved cache brain, hparams: {hparams}\n'
f'Brain spec: {brain_spec}')
brain.summary_path = summary_path
brain.checkpoint_path = checkpoint_path
brain.reinitialize_agent()
brain.clear_step_buffers()
else:
# If we've exceeded the cache size, delete the least recently used item.
if len(self._brains) == self._size:
lru_brain = self._brains.popitem()
if lru_brain:
del lru_brain
falken_logging.info(f'Creating brain, hparams: {hparams}\n'
f'Brain spec: {brain_spec}')
brain = continuous_imitation_brain.ContinuousImitationBrain(
'', brain_spec, checkpoint_path=checkpoint_path,
summary_path=summary_path, hparams=hparams)
falken_logging.info(f'Brain created, hparams: {brain.hparams}')
self._brains[key] = brain
# Move the selected brain to the start of the cache.
self._brains.move_to_end(key, last=False)
# Return a copy of the hyperparameters with the brain's hyperparameters
# overlaid.
result_hparams = dict(hparams)
result_hparams.update(brain.hparams)
return (brain, result_hparams)
| apache-2.0 |
shyaken/cp.eaemcb | controllers/ldap/admin.py | 2 | 6571 | # Author: Zhang Huangbin <[email protected]>
import web
import settings
from libs import languages
from libs.ldaplib import decorators, admin, domain as domainlib, connUtils
session = web.config.get('_session')
#
# Admin related.
#
class List:
@decorators.require_global_admin
@decorators.require_login
def GET(self, cur_page=1):
i = web.input()
cur_page = int(cur_page)
if cur_page == 0:
cur_page == 1
adminLib = admin.Admin()
result = adminLib.listAccounts()
connutils = connUtils.Utils()
sl = connutils.getSizelimitFromAccountLists(
result[1],
curPage=cur_page,
sizelimit=settings.PAGE_SIZE_LIMIT,
)
if cur_page > sl.get('totalPages', 0):
cur_page = sl.get('totalPages', 0)
return web.render(
'ldap/admin/list.html',
cur_page=cur_page,
total=sl.get('totalAccounts'),
admins=sl.get('accountList'),
msg=i.get('msg', None),
)
# Delete, disable, enable admin accounts.
@decorators.require_global_admin
@decorators.csrf_protected
@decorators.require_login
def POST(self):
i = web.input(_unicode=False, mail=[])
self.mails = i.get('mail', [])
self.action = i.get('action', None)
adminLib = admin.Admin()
if self.action == 'delete':
result = adminLib.delete(mails=self.mails,)
msg = 'DELETED'
elif self.action == 'disable':
result = adminLib.enableOrDisableAccount(mails=self.mails, action='disable',)
msg = 'DISABLED'
elif self.action == 'enable':
result = adminLib.enableOrDisableAccount(mails=self.mails, action='enable',)
msg = 'ENABLED'
else:
result = (False, 'INVALID_ACTION')
msg = i.get('msg', None)
if result[0] is True:
raise web.seeother('/admins?msg=%s' % msg)
else:
raise web.seeother('/admins?msg=' + result[1])
class Create:
@decorators.require_global_admin
@decorators.require_login
def GET(self):
i = web.input()
return web.render('ldap/admin/create.html',
languagemaps=languages.get_language_maps(),
default_language=settings.default_language,
min_passwd_length=settings.min_passwd_length,
max_passwd_length=settings.max_passwd_length,
msg=i.get('msg'),
)
@decorators.require_global_admin
@decorators.csrf_protected
@decorators.require_login
def POST(self):
i = web.input()
self.mail = web.safestr(i.get('mail'))
adminLib = admin.Admin()
result = adminLib.add(data=i)
if result[0] is True:
# Redirect to assign domains.
raise web.seeother('/profile/admin/general/%s?msg=CREATED' % self.mail)
else:
raise web.seeother('/create/admin?msg=' + result[1])
class Profile:
@decorators.require_login
def GET(self, profile_type, mail):
self.mail = web.safestr(mail)
self.profile_type = web.safestr(profile_type)
if session.get('domainGlobalAdmin') is not True and session.get('username') != self.mail:
# Don't allow to view/update other admins' profile.
raise web.seeother('/profile/admin/general/%s?msg=PERMISSION_DENIED' % session.get('username'))
# Get admin profile.
adminLib = admin.Admin()
result = adminLib.profile(self.mail)
if result[0] is not True:
raise web.seeother('/admins?msg=' + result[1])
else:
self.admin_profile = result[1]
i = web.input()
if self.profile_type == 'general':
# Get available languages.
if result[0] is True:
###################
# Managed domains
#
# Check permission.
#if session.get('domainGlobalAdmin') is not True:
# raise web.seeother('/profile/admin/general/%s?msg=PERMISSION_DENIED' % self.mail)
# Get all domains.
domainLib = domainlib.Domain()
resultOfAllDomains = domainLib.listAccounts(attrs=['domainName', 'cn', ])
if resultOfAllDomains[0] is True:
self.allDomains = resultOfAllDomains[1]
else:
return resultOfAllDomains
return web.render(
'ldap/admin/profile.html',
mail=self.mail,
profile_type=self.profile_type,
profile=self.admin_profile,
languagemaps=languages.get_language_maps(),
allDomains=self.allDomains,
msg=i.get('msg', None),
)
else:
raise web.seeother('/profile/admin/%s/%s?msg=%s' % (self.profile_type, self.mail, result[1]))
elif self.profile_type == 'password':
return web.render('ldap/admin/profile.html',
mail=self.mail,
profile_type=self.profile_type,
profile=self.admin_profile,
min_passwd_length=settings.min_passwd_length,
max_passwd_length=settings.max_passwd_length,
msg=i.get('msg', None),
)
@decorators.csrf_protected
@decorators.require_login
def POST(self, profile_type, mail):
self.profile_type = web.safestr(profile_type)
self.mail = web.safestr(mail)
i = web.input(domainName=[],)
if session.get('domainGlobalAdmin') is not True and session.get('username') != self.mail:
# Don't allow to view/update other admins' profile.
raise web.seeother('/profile/admin/general/%s?msg=PERMISSION_DENIED' % session.get('username'))
adminLib = admin.Admin()
result = adminLib.update(
profile_type=self.profile_type,
mail=self.mail,
data=i,
)
if result[0] is True:
raise web.seeother('/profile/admin/%s/%s?msg=UPDATED' % (self.profile_type, self.mail))
else:
raise web.seeother('/profile/admin/%s/%s?msg=%s' % (self.profile_type, self.mail, result[1]))
| gpl-2.0 |
PennartLoettring/Poettrix | rootfs/usr/lib/python3.4/test/multibytecodec_support.py | 12 | 14592 | #
# multibytecodec_support.py
# Common Unittest Routines for CJK codecs
#
import codecs
import os
import re
import sys
import unittest
from http.client import HTTPException
from test import support
from io import BytesIO
class TestBase:
encoding = '' # codec name
codec = None # codec tuple (with 4 elements)
tstring = None # must set. 2 strings to test StreamReader
codectests = None # must set. codec test tuple
roundtriptest = 1 # set if roundtrip is possible with unicode
has_iso10646 = 0 # set if this encoding contains whole iso10646 map
xmlcharnametest = None # string to test xmlcharrefreplace
unmappedunicode = '\udeee' # a unicode codepoint that is not mapped.
def setUp(self):
if self.codec is None:
self.codec = codecs.lookup(self.encoding)
self.encode = self.codec.encode
self.decode = self.codec.decode
self.reader = self.codec.streamreader
self.writer = self.codec.streamwriter
self.incrementalencoder = self.codec.incrementalencoder
self.incrementaldecoder = self.codec.incrementaldecoder
def test_chunkcoding(self):
tstring_lines = []
for b in self.tstring:
lines = b.split(b"\n")
last = lines.pop()
assert last == b""
lines = [line + b"\n" for line in lines]
tstring_lines.append(lines)
for native, utf8 in zip(*tstring_lines):
u = self.decode(native)[0]
self.assertEqual(u, utf8.decode('utf-8'))
if self.roundtriptest:
self.assertEqual(native, self.encode(u)[0])
def test_errorhandle(self):
for source, scheme, expected in self.codectests:
if isinstance(source, bytes):
func = self.decode
else:
func = self.encode
if expected:
result = func(source, scheme)[0]
if func is self.decode:
self.assertTrue(type(result) is str, type(result))
self.assertEqual(result, expected,
'%a.decode(%r, %r)=%a != %a'
% (source, self.encoding, scheme, result,
expected))
else:
self.assertTrue(type(result) is bytes, type(result))
self.assertEqual(result, expected,
'%a.encode(%r, %r)=%a != %a'
% (source, self.encoding, scheme, result,
expected))
else:
self.assertRaises(UnicodeError, func, source, scheme)
def test_xmlcharrefreplace(self):
if self.has_iso10646:
self.skipTest('encoding contains full ISO 10646 map')
s = "\u0b13\u0b23\u0b60 nd eggs"
self.assertEqual(
self.encode(s, "xmlcharrefreplace")[0],
b"ଓଣୠ nd eggs"
)
def test_customreplace_encode(self):
if self.has_iso10646:
self.skipTest('encoding contains full ISO 10646 map')
from html.entities import codepoint2name
def xmlcharnamereplace(exc):
if not isinstance(exc, UnicodeEncodeError):
raise TypeError("don't know how to handle %r" % exc)
l = []
for c in exc.object[exc.start:exc.end]:
if ord(c) in codepoint2name:
l.append("&%s;" % codepoint2name[ord(c)])
else:
l.append("&#%d;" % ord(c))
return ("".join(l), exc.end)
codecs.register_error("test.xmlcharnamereplace", xmlcharnamereplace)
if self.xmlcharnametest:
sin, sout = self.xmlcharnametest
else:
sin = "\xab\u211c\xbb = \u2329\u1234\u232a"
sout = b"«ℜ» = ⟨ሴ⟩"
self.assertEqual(self.encode(sin,
"test.xmlcharnamereplace")[0], sout)
def test_callback_returns_bytes(self):
def myreplace(exc):
return (b"1234", exc.end)
codecs.register_error("test.cjktest", myreplace)
enc = self.encode("abc" + self.unmappedunicode + "def", "test.cjktest")[0]
self.assertEqual(enc, b"abc1234def")
def test_callback_wrong_objects(self):
def myreplace(exc):
return (ret, exc.end)
codecs.register_error("test.cjktest", myreplace)
for ret in ([1, 2, 3], [], None, object()):
self.assertRaises(TypeError, self.encode, self.unmappedunicode,
'test.cjktest')
def test_callback_long_index(self):
def myreplace(exc):
return ('x', int(exc.end))
codecs.register_error("test.cjktest", myreplace)
self.assertEqual(self.encode('abcd' + self.unmappedunicode + 'efgh',
'test.cjktest'), (b'abcdxefgh', 9))
def myreplace(exc):
return ('x', sys.maxsize + 1)
codecs.register_error("test.cjktest", myreplace)
self.assertRaises(IndexError, self.encode, self.unmappedunicode,
'test.cjktest')
def test_callback_None_index(self):
def myreplace(exc):
return ('x', None)
codecs.register_error("test.cjktest", myreplace)
self.assertRaises(TypeError, self.encode, self.unmappedunicode,
'test.cjktest')
def test_callback_backward_index(self):
def myreplace(exc):
if myreplace.limit > 0:
myreplace.limit -= 1
return ('REPLACED', 0)
else:
return ('TERMINAL', exc.end)
myreplace.limit = 3
codecs.register_error("test.cjktest", myreplace)
self.assertEqual(self.encode('abcd' + self.unmappedunicode + 'efgh',
'test.cjktest'),
(b'abcdREPLACEDabcdREPLACEDabcdREPLACEDabcdTERMINALefgh', 9))
def test_callback_forward_index(self):
def myreplace(exc):
return ('REPLACED', exc.end + 2)
codecs.register_error("test.cjktest", myreplace)
self.assertEqual(self.encode('abcd' + self.unmappedunicode + 'efgh',
'test.cjktest'), (b'abcdREPLACEDgh', 9))
def test_callback_index_outofbound(self):
def myreplace(exc):
return ('TERM', 100)
codecs.register_error("test.cjktest", myreplace)
self.assertRaises(IndexError, self.encode, self.unmappedunicode,
'test.cjktest')
def test_incrementalencoder(self):
UTF8Reader = codecs.getreader('utf-8')
for sizehint in [None] + list(range(1, 33)) + \
[64, 128, 256, 512, 1024]:
istream = UTF8Reader(BytesIO(self.tstring[1]))
ostream = BytesIO()
encoder = self.incrementalencoder()
while 1:
if sizehint is not None:
data = istream.read(sizehint)
else:
data = istream.read()
if not data:
break
e = encoder.encode(data)
ostream.write(e)
self.assertEqual(ostream.getvalue(), self.tstring[0])
def test_incrementaldecoder(self):
UTF8Writer = codecs.getwriter('utf-8')
for sizehint in [None, -1] + list(range(1, 33)) + \
[64, 128, 256, 512, 1024]:
istream = BytesIO(self.tstring[0])
ostream = UTF8Writer(BytesIO())
decoder = self.incrementaldecoder()
while 1:
data = istream.read(sizehint)
if not data:
break
else:
u = decoder.decode(data)
ostream.write(u)
self.assertEqual(ostream.getvalue(), self.tstring[1])
def test_incrementalencoder_error_callback(self):
inv = self.unmappedunicode
e = self.incrementalencoder()
self.assertRaises(UnicodeEncodeError, e.encode, inv, True)
e.errors = 'ignore'
self.assertEqual(e.encode(inv, True), b'')
e.reset()
def tempreplace(exc):
return ('called', exc.end)
codecs.register_error('test.incremental_error_callback', tempreplace)
e.errors = 'test.incremental_error_callback'
self.assertEqual(e.encode(inv, True), b'called')
# again
e.errors = 'ignore'
self.assertEqual(e.encode(inv, True), b'')
def test_streamreader(self):
UTF8Writer = codecs.getwriter('utf-8')
for name in ["read", "readline", "readlines"]:
for sizehint in [None, -1] + list(range(1, 33)) + \
[64, 128, 256, 512, 1024]:
istream = self.reader(BytesIO(self.tstring[0]))
ostream = UTF8Writer(BytesIO())
func = getattr(istream, name)
while 1:
data = func(sizehint)
if not data:
break
if name == "readlines":
ostream.writelines(data)
else:
ostream.write(data)
self.assertEqual(ostream.getvalue(), self.tstring[1])
def test_streamwriter(self):
readfuncs = ('read', 'readline', 'readlines')
UTF8Reader = codecs.getreader('utf-8')
for name in readfuncs:
for sizehint in [None] + list(range(1, 33)) + \
[64, 128, 256, 512, 1024]:
istream = UTF8Reader(BytesIO(self.tstring[1]))
ostream = self.writer(BytesIO())
func = getattr(istream, name)
while 1:
if sizehint is not None:
data = func(sizehint)
else:
data = func()
if not data:
break
if name == "readlines":
ostream.writelines(data)
else:
ostream.write(data)
self.assertEqual(ostream.getvalue(), self.tstring[0])
class TestBase_Mapping(unittest.TestCase):
pass_enctest = []
pass_dectest = []
supmaps = []
codectests = []
def __init__(self, *args, **kw):
unittest.TestCase.__init__(self, *args, **kw)
try:
self.open_mapping_file().close() # test it to report the error early
except (OSError, HTTPException):
self.skipTest("Could not retrieve "+self.mapfileurl)
def open_mapping_file(self):
return support.open_urlresource(self.mapfileurl)
def test_mapping_file(self):
if self.mapfileurl.endswith('.xml'):
self._test_mapping_file_ucm()
else:
self._test_mapping_file_plain()
def _test_mapping_file_plain(self):
unichrs = lambda s: ''.join(map(chr, map(eval, s.split('+'))))
urt_wa = {}
with self.open_mapping_file() as f:
for line in f:
if not line:
break
data = line.split('#')[0].strip().split()
if len(data) != 2:
continue
csetval = eval(data[0])
if csetval <= 0x7F:
csetch = bytes([csetval & 0xff])
elif csetval >= 0x1000000:
csetch = bytes([(csetval >> 24), ((csetval >> 16) & 0xff),
((csetval >> 8) & 0xff), (csetval & 0xff)])
elif csetval >= 0x10000:
csetch = bytes([(csetval >> 16), ((csetval >> 8) & 0xff),
(csetval & 0xff)])
elif csetval >= 0x100:
csetch = bytes([(csetval >> 8), (csetval & 0xff)])
else:
continue
unich = unichrs(data[1])
if ord(unich) == 0xfffd or unich in urt_wa:
continue
urt_wa[unich] = csetch
self._testpoint(csetch, unich)
def _test_mapping_file_ucm(self):
with self.open_mapping_file() as f:
ucmdata = f.read()
uc = re.findall('<a u="([A-F0-9]{4})" b="([0-9A-F ]+)"/>', ucmdata)
for uni, coded in uc:
unich = chr(int(uni, 16))
codech = bytes(int(c, 16) for c in coded.split())
self._testpoint(codech, unich)
def test_mapping_supplemental(self):
for mapping in self.supmaps:
self._testpoint(*mapping)
def _testpoint(self, csetch, unich):
if (csetch, unich) not in self.pass_enctest:
self.assertEqual(unich.encode(self.encoding), csetch)
if (csetch, unich) not in self.pass_dectest:
self.assertEqual(str(csetch, self.encoding), unich)
def test_errorhandle(self):
for source, scheme, expected in self.codectests:
if isinstance(source, bytes):
func = source.decode
else:
func = source.encode
if expected:
if isinstance(source, bytes):
result = func(self.encoding, scheme)
self.assertTrue(type(result) is str, type(result))
self.assertEqual(result, expected,
'%a.decode(%r, %r)=%a != %a'
% (source, self.encoding, scheme, result,
expected))
else:
result = func(self.encoding, scheme)
self.assertTrue(type(result) is bytes, type(result))
self.assertEqual(result, expected,
'%a.encode(%r, %r)=%a != %a'
% (source, self.encoding, scheme, result,
expected))
else:
self.assertRaises(UnicodeError, func, self.encoding, scheme)
def load_teststring(name):
dir = os.path.join(os.path.dirname(__file__), 'cjkencodings')
with open(os.path.join(dir, name + '.txt'), 'rb') as f:
encoded = f.read()
with open(os.path.join(dir, name + '-utf8.txt'), 'rb') as f:
utf8 = f.read()
return encoded, utf8
| gpl-2.0 |
SnappleCap/oh-mainline | vendor/packages/requests-oauthlib/requests_oauthlib/oauth1_session.py | 25 | 16131 | from __future__ import unicode_literals
try:
from urlparse import urlparse
except ImportError:
from urllib.parse import urlparse
import logging
from oauthlib.common import add_params_to_uri
from oauthlib.common import urldecode as _urldecode
from oauthlib.oauth1 import (
SIGNATURE_HMAC, SIGNATURE_RSA, SIGNATURE_TYPE_AUTH_HEADER
)
import requests
from . import OAuth1
import sys
if sys.version > "3":
unicode = str
log = logging.getLogger(__name__)
def urldecode(body):
"""Parse query or json to python dictionary"""
try:
return _urldecode(body)
except:
import json
return json.loads(body)
class TokenRequestDenied(ValueError):
def __init__(self, message, status_code):
super(TokenRequestDenied, self).__init__(message)
self.status_code = status_code
class TokenMissing(ValueError):
def __init__(self, message, response):
super(TokenMissing, self).__init__(message)
self.response = response
class VerifierMissing(ValueError):
pass
class OAuth1Session(requests.Session):
"""Request signing and convenience methods for the oauth dance.
What is the difference between OAuth1Session and OAuth1?
OAuth1Session actually uses OAuth1 internally and its purpose is to assist
in the OAuth workflow through convenience methods to prepare authorization
URLs and parse the various token and redirection responses. It also provide
rudimentary validation of responses.
An example of the OAuth workflow using a basic CLI app and Twitter.
>>> # Credentials obtained during the registration.
>>> client_key = 'client key'
>>> client_secret = 'secret'
>>> callback_uri = 'https://127.0.0.1/callback'
>>>
>>> # Endpoints found in the OAuth provider API documentation
>>> request_token_url = 'https://api.twitter.com/oauth/request_token'
>>> authorization_url = 'https://api.twitter.com/oauth/authorize'
>>> access_token_url = 'https://api.twitter.com/oauth/access_token'
>>>
>>> oauth_session = OAuth1Session(client_key,client_secret=client_secret, callback_uri=callback_uri)
>>>
>>> # First step, fetch the request token.
>>> oauth_session.fetch_request_token(request_token_url)
{
'oauth_token': 'kjerht2309u',
'oauth_token_secret': 'lsdajfh923874',
}
>>>
>>> # Second step. Follow this link and authorize
>>> oauth_session.authorization_url(authorization_url)
'https://api.twitter.com/oauth/authorize?oauth_token=sdf0o9823sjdfsdf&oauth_callback=https%3A%2F%2F127.0.0.1%2Fcallback'
>>>
>>> # Third step. Fetch the access token
>>> redirect_response = raw_input('Paste the full redirect URL here.')
>>> oauth_session.parse_authorization_response(redirect_response)
{
'oauth_token: 'kjerht2309u',
'oauth_token_secret: 'lsdajfh923874',
'oauth_verifier: 'w34o8967345',
}
>>> oauth_session.fetch_access_token(access_token_url)
{
'oauth_token': 'sdf0o9823sjdfsdf',
'oauth_token_secret': '2kjshdfp92i34asdasd',
}
>>> # Done. You can now make OAuth requests.
>>> status_url = 'http://api.twitter.com/1/statuses/update.json'
>>> new_status = {'status': 'hello world!'}
>>> oauth_session.post(status_url, data=new_status)
<Response [200]>
"""
def __init__(self, client_key,
client_secret=None,
resource_owner_key=None,
resource_owner_secret=None,
callback_uri=None,
signature_method=SIGNATURE_HMAC,
signature_type=SIGNATURE_TYPE_AUTH_HEADER,
rsa_key=None,
verifier=None,
client_class=None,
force_include_body=False,
**kwargs):
"""Construct the OAuth 1 session.
:param client_key: A client specific identifier.
:param client_secret: A client specific secret used to create HMAC and
plaintext signatures.
:param resource_owner_key: A resource owner key, also referred to as
request token or access token depending on
when in the workflow it is used.
:param resource_owner_secret: A resource owner secret obtained with
either a request or access token. Often
referred to as token secret.
:param callback_uri: The URL the user is redirect back to after
authorization.
:param signature_method: Signature methods determine how the OAuth
signature is created. The three options are
oauthlib.oauth1.SIGNATURE_HMAC (default),
oauthlib.oauth1.SIGNATURE_RSA and
oauthlib.oauth1.SIGNATURE_PLAIN.
:param signature_type: Signature type decides where the OAuth
parameters are added. Either in the
Authorization header (default) or to the URL
query parameters or the request body. Defined as
oauthlib.oauth1.SIGNATURE_TYPE_AUTH_HEADER,
oauthlib.oauth1.SIGNATURE_TYPE_QUERY and
oauthlib.oauth1.SIGNATURE_TYPE_BODY
respectively.
:param rsa_key: The private RSA key as a string. Can only be used with
signature_method=oauthlib.oauth1.SIGNATURE_RSA.
:param verifier: A verifier string to prove authorization was granted.
:param client_class: A subclass of `oauthlib.oauth1.Client` to use with
`requests_oauthlib.OAuth1` instead of the default
:param force_include_body: Always include the request body in the
signature creation.
:param **kwargs: Additional keyword arguments passed to `OAuth1`
"""
super(OAuth1Session, self).__init__()
self._client = OAuth1(client_key,
client_secret=client_secret,
resource_owner_key=resource_owner_key,
resource_owner_secret=resource_owner_secret,
callback_uri=callback_uri,
signature_method=signature_method,
signature_type=signature_type,
rsa_key=rsa_key,
verifier=verifier,
client_class=client_class,
force_include_body=force_include_body,
**kwargs)
self.auth = self._client
@property
def authorized(self):
"""Boolean that indicates whether this session has an OAuth token
or not. If `self.authorized` is True, you can reasonably expect
OAuth-protected requests to the resource to succeed. If
`self.authorized` is False, you need the user to go through the OAuth
authentication dance before OAuth-protected requests to the resource
will succeed.
"""
if self._client.client.signature_method == SIGNATURE_RSA:
# RSA only uses resource_owner_key
return bool(self._client.client.resource_owner_key)
else:
# other methods of authentication use all three pieces
return (
bool(self._client.client.client_secret) and
bool(self._client.client.resource_owner_key) and
bool(self._client.client.resource_owner_secret)
)
def authorization_url(self, url, request_token=None, **kwargs):
"""Create an authorization URL by appending request_token and optional
kwargs to url.
This is the second step in the OAuth 1 workflow. The user should be
redirected to this authorization URL, grant access to you, and then
be redirected back to you. The redirection back can either be specified
during client registration or by supplying a callback URI per request.
:param url: The authorization endpoint URL.
:param request_token: The previously obtained request token.
:param kwargs: Optional parameters to append to the URL.
:returns: The authorization URL with new parameters embedded.
An example using a registered default callback URI.
>>> request_token_url = 'https://api.twitter.com/oauth/request_token'
>>> authorization_url = 'https://api.twitter.com/oauth/authorize'
>>> oauth_session = OAuth1Session('client-key', client_secret='secret')
>>> oauth_session.fetch_request_token(request_token_url)
{
'oauth_token': 'sdf0o9823sjdfsdf',
'oauth_token_secret': '2kjshdfp92i34asdasd',
}
>>> oauth_session.authorization_url(authorization_url)
'https://api.twitter.com/oauth/authorize?oauth_token=sdf0o9823sjdfsdf'
>>> oauth_session.authorization_url(authorization_url, foo='bar')
'https://api.twitter.com/oauth/authorize?oauth_token=sdf0o9823sjdfsdf&foo=bar'
An example using an explicit callback URI.
>>> request_token_url = 'https://api.twitter.com/oauth/request_token'
>>> authorization_url = 'https://api.twitter.com/oauth/authorize'
>>> oauth_session = OAuth1Session('client-key', client_secret='secret', callback_uri='https://127.0.0.1/callback')
>>> oauth_session.fetch_request_token(request_token_url)
{
'oauth_token': 'sdf0o9823sjdfsdf',
'oauth_token_secret': '2kjshdfp92i34asdasd',
}
>>> oauth_session.authorization_url(authorization_url)
'https://api.twitter.com/oauth/authorize?oauth_token=sdf0o9823sjdfsdf&oauth_callback=https%3A%2F%2F127.0.0.1%2Fcallback'
"""
kwargs['oauth_token'] = request_token or self._client.client.resource_owner_key
log.debug('Adding parameters %s to url %s', kwargs, url)
return add_params_to_uri(url, kwargs.items())
def fetch_request_token(self, url, realm=None):
"""Fetch a request token.
This is the first step in the OAuth 1 workflow. A request token is
obtained by making a signed post request to url. The token is then
parsed from the application/x-www-form-urlencoded response and ready
to be used to construct an authorization url.
:param url: The request token endpoint URL.
:param realm: A list of realms to request access to.
:returns: The response in dict format.
Note that a previously set callback_uri will be reset for your
convenience, or else signature creation will be incorrect on
consecutive requests.
>>> request_token_url = 'https://api.twitter.com/oauth/request_token'
>>> oauth_session = OAuth1Session('client-key', client_secret='secret')
>>> oauth_session.fetch_request_token(request_token_url)
{
'oauth_token': 'sdf0o9823sjdfsdf',
'oauth_token_secret': '2kjshdfp92i34asdasd',
}
"""
self._client.client.realm = ' '.join(realm) if realm else None
token = self._fetch_token(url)
log.debug('Resetting callback_uri and realm (not needed in next phase).')
self._client.client.callback_uri = None
self._client.client.realm = None
return token
def fetch_access_token(self, url, verifier=None):
"""Fetch an access token.
This is the final step in the OAuth 1 workflow. An access token is
obtained using all previously obtained credentials, including the
verifier from the authorization step.
Note that a previously set verifier will be reset for your
convenience, or else signature creation will be incorrect on
consecutive requests.
>>> access_token_url = 'https://api.twitter.com/oauth/access_token'
>>> redirect_response = 'https://127.0.0.1/callback?oauth_token=kjerht2309uf&oauth_token_secret=lsdajfh923874&oauth_verifier=w34o8967345'
>>> oauth_session = OAuth1Session('client-key', client_secret='secret')
>>> oauth_session.parse_authorization_response(redirect_response)
{
'oauth_token: 'kjerht2309u',
'oauth_token_secret: 'lsdajfh923874',
'oauth_verifier: 'w34o8967345',
}
>>> oauth_session.fetch_access_token(access_token_url)
{
'oauth_token': 'sdf0o9823sjdfsdf',
'oauth_token_secret': '2kjshdfp92i34asdasd',
}
"""
if verifier:
self._client.client.verifier = verifier
if not getattr(self._client.client, 'verifier', None):
raise VerifierMissing('No client verifier has been set.')
token = self._fetch_token(url)
log.debug('Resetting verifier attribute, should not be used anymore.')
self._client.client.verifier = None
return token
def parse_authorization_response(self, url):
"""Extract parameters from the post authorization redirect response URL.
:param url: The full URL that resulted from the user being redirected
back from the OAuth provider to you, the client.
:returns: A dict of parameters extracted from the URL.
>>> redirect_response = 'https://127.0.0.1/callback?oauth_token=kjerht2309uf&oauth_token_secret=lsdajfh923874&oauth_verifier=w34o8967345'
>>> oauth_session = OAuth1Session('client-key', client_secret='secret')
>>> oauth_session.parse_authorization_response(redirect_response)
{
'oauth_token: 'kjerht2309u',
'oauth_token_secret: 'lsdajfh923874',
'oauth_verifier: 'w34o8967345',
}
"""
log.debug('Parsing token from query part of url %s', url)
token = dict(urldecode(urlparse(url).query))
log.debug('Updating internal client token attribute.')
self._populate_attributes(token)
return token
def _populate_attributes(self, token):
if 'oauth_token' in token:
self._client.client.resource_owner_key = token['oauth_token']
else:
raise TokenMissing(
'Response does not contain a token: {resp}'.format(resp=token),
token,
)
if 'oauth_token_secret' in token:
self._client.client.resource_owner_secret = (
token['oauth_token_secret'])
if 'oauth_verifier' in token:
self._client.client.verifier = token['oauth_verifier']
def _fetch_token(self, url):
log.debug('Fetching token from %s using client %s', url, self._client.client)
r = self.post(url)
if r.status_code >= 400:
error = "Token request failed with code %s, response was '%s'."
raise TokenRequestDenied(error % (r.status_code, r.text), r.status_code)
log.debug('Decoding token from response "%s"', r.text)
try:
token = dict(urldecode(r.text))
except ValueError as e:
error = ("Unable to decode token from token response. "
"This is commonly caused by an unsuccessful request where"
" a non urlencoded error message is returned. "
"The decoding error was %s""" % e)
raise ValueError(error)
log.debug('Obtained token %s', token)
log.debug('Updating internal client attributes from token data.')
self._populate_attributes(token)
return token
def rebuild_auth(self, prepared_request, response):
"""
When being redirected we should always strip Authorization
header, since nonce may not be reused as per OAuth spec.
"""
if 'Authorization' in prepared_request.headers:
# If we get redirected to a new host, we should strip out
# any authentication headers.
prepared_request.headers.pop('Authorization', True)
prepared_request.prepare_auth(self.auth)
return
| agpl-3.0 |
20uf/ansible | test/integration/cleanup_rax.py | 71 | 6516 | #!/usr/bin/env python
import os
import re
import yaml
import argparse
try:
import pyrax
HAS_PYRAX = True
except ImportError:
HAS_PYRAX = False
def rax_list_iterator(svc, *args, **kwargs):
method = kwargs.pop('method', 'list')
items = getattr(svc, method)(*args, **kwargs)
while items:
retrieved = getattr(svc, method)(*args, marker=items[-1].id, **kwargs)
if items and retrieved and items[-1].id == retrieved[0].id:
del items[-1]
items.extend(retrieved)
if len(retrieved) < 2:
break
return items
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('-y', '--yes', action='store_true', dest='assumeyes',
default=False, help="Don't prompt for confirmation")
parser.add_argument('--match', dest='match_re',
default='^ansible-testing',
help='Regular expression used to find resources '
'(default: %(default)s)')
return parser.parse_args()
def authenticate():
try:
with open(os.path.realpath('./credentials.yml')) as f:
credentials = yaml.load(f)
except Exception as e:
raise SystemExit(e)
try:
pyrax.set_credentials(credentials.get('rackspace_username'),
credentials.get('rackspace_api_key'))
except Exception as e:
raise SystemExit(e)
def prompt_and_delete(item, prompt, assumeyes):
if not assumeyes:
assumeyes = raw_input(prompt).lower() == 'y'
assert (hasattr(item, 'delete') or hasattr(item, 'terminate'),
"Class <%s> has no delete or terminate attribute" % item.__class__)
if assumeyes:
if hasattr(item, 'delete'):
item.delete()
print ("Deleted %s" % item)
if hasattr(item, 'terminate'):
item.terminate()
print ("Terminated %s" % item)
def delete_rax(args):
"""Function for deleting CloudServers"""
print ("--- Cleaning CloudServers matching '%s'" % args.match_re)
search_opts = dict(name='^%s' % args.match_re)
for region in pyrax.identity.services.compute.regions:
cs = pyrax.connect_to_cloudservers(region=region)
servers = rax_list_iterator(cs.servers, search_opts=search_opts)
for server in servers:
prompt_and_delete(server,
'Delete matching %s? [y/n]: ' % server,
args.assumeyes)
def delete_rax_clb(args):
"""Function for deleting Cloud Load Balancers"""
print ("--- Cleaning Cloud Load Balancers matching '%s'" % args.match_re)
for region in pyrax.identity.services.load_balancer.regions:
clb = pyrax.connect_to_cloud_loadbalancers(region=region)
for lb in rax_list_iterator(clb):
if re.search(args.match_re, lb.name):
prompt_and_delete(lb,
'Delete matching %s? [y/n]: ' % lb,
args.assumeyes)
def delete_rax_keypair(args):
"""Function for deleting Rackspace Key pairs"""
print ("--- Cleaning Key Pairs matching '%s'" % args.match_re)
for region in pyrax.identity.services.compute.regions:
cs = pyrax.connect_to_cloudservers(region=region)
for keypair in cs.keypairs.list():
if re.search(args.match_re, keypair.name):
prompt_and_delete(keypair,
'Delete matching %s? [y/n]: ' % keypair,
args.assumeyes)
def delete_rax_network(args):
"""Function for deleting Cloud Networks"""
print ("--- Cleaning Cloud Networks matching '%s'" % args.match_re)
for region in pyrax.identity.services.network.regions:
cnw = pyrax.connect_to_cloud_networks(region=region)
for network in cnw.list():
if re.search(args.match_re, network.name):
prompt_and_delete(network,
'Delete matching %s? [y/n]: ' % network,
args.assumeyes)
def delete_rax_cbs(args):
"""Function for deleting Cloud Networks"""
print ("--- Cleaning Cloud Block Storage matching '%s'" % args.match_re)
for region in pyrax.identity.services.network.regions:
cbs = pyrax.connect_to_cloud_blockstorage(region=region)
for volume in cbs.list():
if re.search(args.match_re, volume.name):
prompt_and_delete(volume,
'Delete matching %s? [y/n]: ' % volume,
args.assumeyes)
def delete_rax_cdb(args):
"""Function for deleting Cloud Databases"""
print ("--- Cleaning Cloud Databases matching '%s'" % args.match_re)
for region in pyrax.identity.services.database.regions:
cdb = pyrax.connect_to_cloud_databases(region=region)
for db in rax_list_iterator(cdb):
if re.search(args.match_re, db.name):
prompt_and_delete(db,
'Delete matching %s? [y/n]: ' % db,
args.assumeyes)
def _force_delete_rax_scaling_group(manager):
def wrapped(uri):
manager.api.method_delete('%s?force=true' % uri)
return wrapped
def delete_rax_scaling_group(args):
"""Function for deleting Autoscale Groups"""
print ("--- Cleaning Autoscale Groups matching '%s'" % args.match_re)
for region in pyrax.identity.services.autoscale.regions:
asg = pyrax.connect_to_autoscale(region=region)
for group in rax_list_iterator(asg):
if re.search(args.match_re, group.name):
group.manager._delete = \
_force_delete_rax_scaling_group(group.manager)
prompt_and_delete(group,
'Delete matching %s? [y/n]: ' % group,
args.assumeyes)
def main():
if not HAS_PYRAX:
raise SystemExit('The pyrax python module is required for this script')
args = parse_args()
authenticate()
funcs = [f for n, f in globals().items() if n.startswith('delete_rax')]
for func in sorted(funcs, key=lambda f: f.__name__):
try:
func(args)
except Exception as e:
print ("---- %s failed (%s)" % (func.__name__, e.message))
if __name__ == '__main__':
try:
main()
except KeyboardInterrupt:
print ('\nExiting...')
| gpl-3.0 |
mastak/Spirit | spirit/topic/private/views.py | 7 | 6200 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.contrib.auth.decorators import login_required
from django.core.urlresolvers import reverse
from django.contrib.auth import get_user_model
from django.shortcuts import render, redirect, get_object_or_404
from django.views.decorators.http import require_POST
from django.contrib import messages
from django.http import HttpResponsePermanentRedirect
from django.conf import settings
from djconfig import config
from ...core import utils
from ...core.utils.paginator import paginate, yt_paginate
from ...core.utils.ratelimit.decorators import ratelimit
from ...comment.forms import CommentForm
from ...comment.utils import comment_posted
from ...comment.models import Comment
from ..models import Topic
from ..utils import topic_viewed
from .utils import notify_access
from .models import TopicPrivate
from .forms import TopicPrivateManyForm, TopicForPrivateForm,\
TopicPrivateJoinForm, TopicPrivateInviteForm
from ..notification.models import TopicNotification
User = get_user_model()
@login_required
@ratelimit(rate='1/10s')
def publish(request, user_id=None):
if request.method == 'POST':
tform = TopicForPrivateForm(user=request.user, data=request.POST)
cform = CommentForm(user=request.user, data=request.POST)
tpform = TopicPrivateManyForm(user=request.user, data=request.POST)
if not request.is_limited and all([tform.is_valid(), cform.is_valid(), tpform.is_valid()]): # TODO: test!
# wrap in transaction.atomic?
topic = tform.save()
cform.topic = topic
comment = cform.save()
comment_posted(comment=comment, mentions=None)
tpform.topic = topic
tpform.save_m2m()
TopicNotification.bulk_create(users=tpform.get_users(), comment=comment)
return redirect(topic.get_absolute_url())
else:
tform = TopicForPrivateForm()
cform = CommentForm()
initial = None
if user_id:
user = get_object_or_404(User, pk=user_id)
initial = {'users': [user.username, ]}
tpform = TopicPrivateManyForm(initial=initial)
context = {
'tform': tform,
'cform': cform,
'tpform': tpform
}
return render(request, 'spirit/topic/private/publish.html', context)
@login_required
def detail(request, topic_id, slug):
topic_private = get_object_or_404(TopicPrivate.objects.select_related('topic'),
topic_id=topic_id,
user=request.user)
topic = topic_private.topic
if topic.slug != slug:
return HttpResponsePermanentRedirect(topic.get_absolute_url())
topic_viewed(request=request, topic=topic)
comments = Comment.objects\
.for_topic(topic=topic)\
.with_likes(user=request.user)\
.order_by('date')
comments = paginate(
comments,
per_page=config.comments_per_page,
page_number=request.GET.get('page', 1)
)
context = {
'topic': topic,
'topic_private': topic_private,
'comments': comments,
}
return render(request, 'spirit/topic/private/detail.html', context)
@login_required
@require_POST
def create_access(request, topic_id):
topic_private = TopicPrivate.objects.for_create_or_404(topic_id, request.user)
form = TopicPrivateInviteForm(topic=topic_private.topic, data=request.POST)
if form.is_valid():
form.save()
notify_access(user=form.get_user(), topic_private=topic_private)
else:
messages.error(request, utils.render_form_errors(form))
return redirect(request.POST.get('next', topic_private.get_absolute_url()))
@login_required
def delete_access(request, pk):
topic_private = TopicPrivate.objects.for_delete_or_404(pk, request.user)
if request.method == 'POST':
topic_private.delete()
if request.user.pk == topic_private.user_id:
return redirect(reverse("spirit:topic:private:index"))
return redirect(request.POST.get('next', topic_private.get_absolute_url()))
context = {'topic_private': topic_private, }
return render(request, 'spirit/topic/private/delete.html', context)
@login_required
def join_in(request, topic_id):
# todo: replace by create_access()?
# This is for topic creators who left their own topics and want to join again
topic = get_object_or_404(
Topic,
pk=topic_id,
user=request.user,
category_id=settings.ST_TOPIC_PRIVATE_CATEGORY_PK
)
if request.method == 'POST':
form = TopicPrivateJoinForm(topic=topic, user=request.user, data=request.POST)
if form.is_valid():
topic_private = form.save()
notify_access(user=form.get_user(), topic_private=topic_private)
return redirect(request.POST.get('next', topic.get_absolute_url()))
else:
form = TopicPrivateJoinForm()
context = {
'topic': topic,
'form': form
}
return render(request, 'spirit/topic/private/join.html', context)
@login_required
def index(request):
topics = Topic.objects\
.with_bookmarks(user=request.user)\
.filter(topics_private__user=request.user)
topics = yt_paginate(
topics,
per_page=config.topics_per_page,
page_number=request.GET.get('page', 1)
)
context = {'topics': topics, }
return render(request, 'spirit/topic/private/index.html', context)
@login_required
def index_author(request):
# Show created topics but exclude those the user is participating on
# TODO: show all, show join link in those the user is not participating
# TODO: move to manager
topics = Topic.objects\
.filter(user=request.user, category_id=settings.ST_TOPIC_PRIVATE_CATEGORY_PK)\
.exclude(topics_private__user=request.user)
topics = yt_paginate(
topics,
per_page=config.topics_per_page,
page_number=request.GET.get('page', 1)
)
context = {'topics': topics, }
return render(request, 'spirit/topic/private/index_author.html', context)
| mit |
reiven/pungabot | modules/module_alias.py | 1 | 1945 | # -*- coding: utf-8 -*-
import sys
aliases = {}
def init(config):
dbCursor.execute("SELECT alias, command FROM ALIASES")
for alias, command in dbCursor.fetchall():
config_alias(alias, command)
def config_alias(alias, command):
mod = globals()
aliases[alias] = command
mod['command_' + alias] = \
lambda *args: run_alias(alias, *args)
def set_alias(bot, alias, command):
config_alias(alias, command)
dbCursor.execute("DELETE FROM aliases WHERE alias = ?", (alias,))
dbCursor.execute("INSERT INTO aliases VALUES (?, ?)", (alias, command))
def clear_alias(bot, alias):
del aliases[alias]
del bot.factory.ns['module_alias.py'][0]['command_' + alias]
dbCursor.execute("DELETE FROM aliases WHERE alias = ?", (alias,))
def get_alias(bot, alias):
return aliases[alias]
def get_all_aliases(bot):
return aliases.keys()
def run_alias(alias, bot, user, channel, args):
cmd = get_alias(bot, alias) + " " + args
bot._command(user, channel, cmd)
def command_alias(bot, user, channel, args):
"""Manage aliases"""
if not args:
return bot.say(channel, 'Available aliases: %s' %
str(", ".join(get_all_aliases(bot)))
)
else:
args = args.split(" ")
aname = args[0]
rest = " ".join(args[1:])
if not rest:
try:
clear_alias(bot, aname)
except KeyError:
return bot.say(channel, '%s, no encontre el alias %s'
% (getNick(user), aname))
return bot.say(channel, '%s, alias %s borrado'
% (getNick(user), aname))
else:
if aname == 'alias':
return bot.say(channel, '%s, no gracias'
% (getNick(user),))
set_alias(bot, aname, rest)
return bot.say(channel, '%s, alias %s agregado'
% (getNick(user), aname)) | gpl-3.0 |
sadanandb/pmt | src/pyasm/widget/annotate_wdg.py | 6 | 11694 | ###########################################################
#
# Copyright (c) 2005, Southpaw Technology
# All Rights Reserved
#
# PROPRIETARY INFORMATION. This software is proprietary to
# Southpaw Technology, and is not to be reproduced, transmitted,
# or disclosed in any way without written permission.
#
#
#
__all__ = ['AnnotateLink', 'AnnotatePage', 'AnnotateWdg', 'AnnotateCbk']
from pyasm.web import *
from pyasm.command import Command
from pyasm.search import Search, SObject
from pyasm.biz import Snapshot, File
from pyasm.widget import BaseTableElementWdg, IconButtonWdg
from input_wdg import *
from dynamic_loader_page import *
from layout_wdg import TableWdg
from icon_wdg import *
class AnnotateLink(BaseTableElementWdg):
def get_annotate_wdg_class(my):
return "AnnotateWdg"
def get_display(my):
sobject = my.get_current_sobject()
url = WebContainer.get_web().get_widget_url()
url.set_option("widget", my.get_annotate_wdg_class() )
url.set_option("search_type", sobject.get_search_type() )
url.set_option("search_id", sobject.get_id() )
button = IconButtonWdg("Annotate", IconWdg.DETAILS, False)
button.add_event("onclick", \
"document.location='%s'" % url.to_string() )
widget = Widget()
widget.add(button)
return widget
class AnnotatePage(Widget):
def init(my):
WebContainer.register_cmd("pyasm.widget.AnnotateCbk")
sobject = my.get_current_sobject()
if not sobject:
if not my.__dict__.has_key("search_type"):
web = WebContainer.get_web()
my.search_type = web.get_form_value("search_type")
my.search_id = web.get_form_value("search_id")
if not my.search_type:
my.add("No search type")
return
search = Search(my.search_type)
search.add_id_filter(my.search_id)
sobject = search.get_sobject()
my.add("<h3>Design Review: Annotation</h3>")
table = TableWdg(my.search_type)
table.set_sobject(sobject)
my.add(table)
url = WebContainer.get_web().get_widget_url()
url.set_option("widget", "AnnotateWdg")
url.set_option("search_type", my.search_type)
url.set_option("search_id", my.search_id)
src = url.to_string()
my.add("<h3>Click on image to add an annotation</h3>")
my.add("The annotation will be located where you clicked on the image")
my.add( """
<iframe id="annotate_frame" scrolling="no" src="%s" style='width: 800; height: 450; margin-left: 30px; border: none;">
WARNING: iframes are not supported
</iframe>
""" % src )
class AnnotateWdg(Widget):
def set_search_type(my, search_type):
my.search_type = search_type
def set_search_id(my, search_id):
my.search_id = search_id
def init(my):
WebContainer.register_cmd("pyasm.widget.AnnotateCbk")
sobject = my.get_current_sobject()
if not sobject:
if not my.__dict__.has_key("search_type"):
web = WebContainer.get_web()
my.search_type = web.get_form_value("search_type")
my.search_id = web.get_form_value("search_id")
if not my.search_type:
my.add("No search type")
return
search = Search(my.search_type)
search.add_id_filter(my.search_id)
sobject = search.get_sobject()
snapshot = Snapshot.get_latest_by_sobject(sobject)
# TODO:
# this is a bit klunky
snapshot_xml = snapshot.get_xml_value("snapshot")
file_code = snapshot_xml.get_value("snapshot/file[@type='web']/@file_code")
file = File.get_by_code(file_code)
web_dir = snapshot.get_web_dir()
path = "%s/%s" % (web_dir, file.get_full_file_name() )
# add the annotate js object
script = HtmlElement.script("annotate = new Annotate()")
my.add(script)
# add the image
my.add("<h3>Image Annotations</h3>")
width = 600
img = HtmlElement.img(path)
img.add_style("position: absolute")
img.set_id("annotate_image")
img.add_style("left: 0px")
img.add_style("top: 0px")
img.add_style("opacity: 1.0")
img.add_style("z-index: 1")
img.add_style("width", width)
img.add_event("onmouseup", "annotate.add_new(event)")
my.add(img)
# test
version = snapshot.get_value("version")
if version != 1:
last_version = version - 1
snapshot = Snapshot.get_by_version( \
my.search_type, my.search_id, version=last_version )
snapshot_xml = snapshot.get_xml_value("snapshot")
file_code = snapshot_xml.get_value("snapshot/file[@type='web']/@file_code")
file = File.get_by_code(file_code)
web_dir = snapshot.get_web_dir()
path = "%s/%s" % (web_dir, file.get_full_file_name() )
img = HtmlElement.img(path)
img.set_id("annotate_image_alt")
img.add_style("position: absolute")
img.add_style("left: 0px")
img.add_style("top: 0px")
img.add_style("opacity: 1.0")
img.add_style("z-index: 0")
img.add_style("width", width)
img.add_event("onmouseup", "annotate.add_new(event)")
my.add(img)
#script = HtmlElement.script("align_element('%s','%s')" % \
# ("annotate_image", "annotate_image_alt") )
#my.add(script)
div = DivWdg()
div.add_style("position: absolute")
div.add_style("left: 620")
div.add_style("top: 300")
my.add(div)
button = IconButtonWdg("Switch", IconWdg.REFRESH, True)
button.add_event("onclick", "annotate.switch_alt()")
div.add(button)
button = IconButtonWdg("Opacity", IconWdg.LOAD, True)
button.add_event("onclick", "annotate.set_opacity()")
div.add(button)
# add the new annotation div
new_annotation_div = DivWdg()
new_annotation_div.set_id("annotate_msg")
new_annotation_div.set_class("annotate_new")
new_annotation_div.add_style("top: 0")
new_annotation_div.add_style("left: 0")
title = DivWdg("Enter Annotation:")
title.add_style("background-color: #000000")
title.add_style("color: #ffffff")
new_annotation_div.add(title)
text = TextAreaWdg("annotate_msg")
text.set_attr("cols", "30")
text.set_attr("rows", "3")
new_annotation_div.add(text)
new_annotation_div.add("<br/>")
cancel = ButtonWdg("Cancel")
cancel.add_style("float: right")
cancel.add_event("onclick", "toggle_display('annotate_msg')")
new_annotation_div.add( cancel )
submit = SubmitWdg("Add Annotation")
submit.add_style("float: right")
new_annotation_div.add( submit )
new_annotation_div.add_style("display: none")
new_annotation_div.add_style("position: absolute")
my.add(new_annotation_div)
# get all of the stored annotations for this image
search = Search("sthpw/annotation")
search.add_order_by("login")
search.add_filter("file_code", file_code)
annotations = search.get_sobjects()
# sort by user
sorted_annotations = {}
for annotation in annotations:
user = annotation.get_value("login")
if not sorted_annotations.has_key(user):
sorted_annotations[user] = []
sorted_annotations[user].append(annotation)
buttons = []
for user, annotations in sorted_annotations.items():
button = IconButtonWdg(user, IconWdg.INSERT, True)
button.add_event("onclick", "annotate.show_marks('%s','%s')" % (user, len(annotations)-1) )
buttons.append(button)
count = 0
for annotation in annotations:
my.add( my.get_annotate_wdg(annotation,count) )
count += 1
# add the user buttons
table = Table()
table.set_class("table")
table.add_style("width: 0px")
table.add_style("position: absolute")
table.add_style("left: 620")
table.add_style("top: 0")
table.add_row()
table.add_header("Annotations")
for button in buttons:
table.add_row()
legend_wdg = DivWdg()
legend_wdg.set_class("annotate_mark")
legend_wdg.add_style("position: relative")
legend_wdg.add(" ")
table.add_cell(legend_wdg)
table.add_cell(button)
my.add(table)
# add form elements
hidden = HiddenWdg("mouse_xpos")
my.add(hidden)
hidden = HiddenWdg("mouse_ypos")
my.add(hidden)
hidden = HiddenWdg("file_code", file_code)
my.add(hidden)
# move the rest below
my.add("<div style='height:300'> </div>")
def get_annotate_wdg(my, annotation, count):
# get information from annotation
x_pos = annotation.get_value("xpos")
y_pos = annotation.get_value("ypos")
user = annotation.get_value("login")
message = annotation.get_value("message")
widget = DivWdg()
widget.add_style("display: none")
widget.set_id( "annotate_div_%s_%s" % (user,count) )
# add the box
annotate_wdg = DivWdg()
annotate_wdg.set_class("annotate_mark")
annotate_wdg.set_id( "annotate_mark_%s_%s" % (user,count) )
annotate_wdg.add_style("display", "block")
annotate_wdg.add_style("left: %s" % x_pos )
annotate_wdg.add_style("top: %s" % y_pos )
# message
back_wdg = DivWdg()
back_wdg.set_class("annotate_back")
back_wdg.set_id("annotate_back_%s_%s" % (user,count) )
back_wdg.add_style("display", "block")
back_wdg.add_style("left: %s" % str(int(x_pos)+10) )
back_wdg.add_style("top: %s" % y_pos )
back_wdg.add(message)
msg_wdg = DivWdg()
msg_wdg.set_class("annotate_msg")
msg_wdg.set_id("annotate_msg_%s_%s" % (user,count) )
msg_wdg.add_style("display", "block")
msg_wdg.add_style("left: %s" % str(int(x_pos)+10) )
msg_wdg.add_style("top: %s" % y_pos )
msg_wdg.add(message)
widget.add(back_wdg)
widget.add(annotate_wdg)
widget.add(msg_wdg)
return widget
class AnnotateCbk(Command):
def get_title(my):
return "Annotate Image"
def execute(my):
web = WebContainer.get_web()
if web.get_form_value("Add Annotation") == "":
return
annotate_msg = web.get_form_value("annotate_msg")
if annotate_msg == "":
return
xpos = web.get_form_value("mouse_xpos")
ypos = web.get_form_value("mouse_ypos")
file_code = web.get_form_value("file_code")
user = web.get_user_name()
annotate = SObject("sthpw/annotation")
annotate.set_value("message", annotate_msg)
annotate.set_value("xpos", xpos)
annotate.set_value("ypos", ypos)
annotate.set_value("login", user)
annotate.set_value("file_code", file_code)
annotate.commit()
my.description = "Added annotation '%s'" % annotate_msg
| epl-1.0 |
gptech/ansible | lib/ansible/modules/windows/win_domain.py | 24 | 2003 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2017, Red Hat, Inc.
#
# This file is part of Ansible
#
# Ansible 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.
#
# Ansible 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 Ansible. If not, see <http://www.gnu.org/licenses/>.
ANSIBLE_METADATA = {'metadata_version': '1.0',
'status': ['preview'],
'supported_by': 'core'}
DOCUMENTATION='''
module: win_domain
short_description: Ensures the existence of a Windows domain.
version_added: 2.3
description:
- Ensure that the domain named by C(dns_domain_name) exists and is reachable. If the domain is not reachable, the domain is created in a new forest
on the target Windows Server 2012R2+ host. This module may require subsequent use of the M(win_reboot) action if changes are made.
options:
dns_domain_name:
description:
- the DNS name of the domain which should exist and be reachable or reside on the target Windows host
required: true
safe_mode_password:
description:
- safe mode password for the domain controller
required: true
author:
- Matt Davis (@nitzmahone)
'''
RETURN='''
reboot_required:
description: True if changes were made that require a reboot.
returned: always
type: boolean
sample: true
'''
EXAMPLES=r'''
# ensure the named domain is reachable from the target host; if not, create the domain in a new forest residing on the target host
- win_domain:
dns_domain_name: ansible.vagrant
safe_mode_password: password123!
'''
| gpl-3.0 |
iohannez/gnuradio | gr-wavelet/python/wavelet/__init__.py | 7 | 1101 | #
# Copyright 2011 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
#
# GNU Radio 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, or (at your option)
# any later version.
#
# GNU Radio 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 GNU Radio; see the file COPYING. If not, write to
# the Free Software Foundation, Inc., 51 Franklin Street,
# Boston, MA 02110-1301, USA.
#
'''
Processing blocks for wavelet transforms.
'''
from __future__ import unicode_literals
import os
try:
from .wavelet_swig import *
except ImportError:
dirname, filename = os.path.split(os.path.abspath(__file__))
__path__.append(os.path.join(dirname, "..", "..", "swig"))
from .wavelet_swig import *
| gpl-3.0 |
NavarraBiomed/cientifika | cientifika_app/models.py | 2 | 14864 | # coding: utf-8
# This is an auto-generated Django model module.
# You'll have to do the following manually to clean this up:
# * Rearrange models' order
# * Make sure each model has one field with primary_key=True
# Feel free to rename the models, but don't rename db_table values or field names.
#
# Also note: You'll have to insert the output of 'django-admin.py sqlcustom [appname]'
# into your database.
from django.db import models
class Centros(models.Model):
idcentro = models.CharField(max_length=765, db_column='IdCentro') # Field name made lowercase.
centro = models.CharField(max_length=765, db_column='Centro', blank=True) # Field name made lowercase.
nombre = models.CharField(max_length=765, db_column='Nombre', blank=True) # Field name made lowercase.
class Meta:
db_table = u'Centros'
class Contratos(models.Model):
investigador = models.CharField(max_length=750, db_column='Investigador', blank=True) # Field name made lowercase.
dni = models.CharField(max_length=765, db_column='DNI', blank=True) # Field name made lowercase.
centro = models.CharField(max_length=765, db_column='Centro', blank=True) # Field name made lowercase.
institucion = models.CharField(max_length=750, db_column='Institucion', blank=True) # Field name made lowercase.
fecha = models.IntegerField(null=True, db_column='A\xc3\xb1o', blank=True) # Field name made lowercase. aΓ±o -> fecha
class Meta:
db_table = u'Contratos'
class Coordinadoresareas(models.Model):
idarea = models.IntegerField(null=True, db_column='IdArea', blank=True) # Field name made lowercase.
area = models.CharField(max_length=765, db_column='Area', blank=True) # Field name made lowercase.
dni = models.CharField(max_length=765, db_column='DNI', blank=True) # Field name made lowercase.
nombre = models.CharField(max_length=765, db_column='Nombre', blank=True) # Field name made lowercase.
class Meta:
db_table = u'CoordinadoresAreas'
class Coordinadoresgrupos(models.Model):
idseccion = models.CharField(max_length=765, db_column='iDSeccion', blank=True) # Field name made lowercase.
seccion = models.CharField(max_length=765, db_column='Seccion', blank=True) # Field name made lowercase.
ip = models.CharField(max_length=765, db_column='IP', blank=True) # Field name made lowercase.
class Meta:
db_table = u'CoordinadoresGrupos'
class Grupos(models.Model):
#id = models.IntegerField(db_column='Id') # Field name made lowercase.
idseccion = models.CharField(max_length=765, db_column='IdSeccion', blank=True) # Field name made lowercase.
codigo = models.CharField(max_length=765, db_column='Codigo', blank=True) # Field name made lowercase.
seccion = models.CharField(max_length=765, db_column='Seccion', blank=True) # Field name made lowercase.
area = models.CharField(max_length=765, db_column='Area', blank=True) # Field name made lowercase.
tipo = models.CharField(max_length=765, db_column='Tipo', blank=True) # Field name made lowercase.
sistema = models.CharField(max_length=765, db_column='Sistema', blank=True) # Field name made lowercase.
class Meta:
db_table = u'Grupos'
class Institucionespublicaciones(models.Model):
ute = models.CharField(max_length=150, db_column='UTE') # Field name made lowercase.
instituciones = models.TextField(db_column='Instituciones', blank=True) # Field name made lowercase.
class Meta:
db_table = u'InstitucionesPublicaciones'
class Investigadores(models.Model):
#id = models.IntegerField(db_column='Id') # Field name made lowercase.
dni = models.CharField(max_length=765, db_column='DNI', blank=True) # Field name made lowercase.
nombre = models.CharField(max_length=765, db_column='Nombre', blank=True) # Field name made lowercase.
nombrecompleto = models.CharField(max_length=765, db_column='NombreCompleto', blank=True) # Field name made lowercase.
primerapellido = models.CharField(max_length=765, db_column='PrimerApellido', blank=True) # Field name made lowercase.
segundoapellido = models.CharField(max_length=765, db_column='SegundoApellido', blank=True) # Field name made lowercase.
investigador = models.CharField(max_length=765, db_column='Investigador', blank=True) # Field name made lowercase.
campo7 = models.CharField(max_length=765, db_column='Campo7', blank=True) # Field name made lowercase.
class Meta:
db_table = u'Investigadores'
class Investigadoresgrupos(models.Model):
investigador = models.CharField(max_length=750, db_column='Investigador', blank=True) # Field name made lowercase.
dni = models.CharField(max_length=765, db_column='DNI', blank=True) # Field name made lowercase.
idseccion = models.CharField(max_length=150, db_column='IdSeccion', blank=True) # Field name made lowercase.
seccion = models.CharField(max_length=750, db_column='Seccion', blank=True) # Field name made lowercase.
fecha = models.IntegerField(null=True, db_column='A\xc3\xb1o', blank=True) # Field name made lowercase. aΓ±o -> fecha
class Meta:
db_table = u'InvestigadoresGrupos'
class Investigadorespublicaciones(models.Model):
dni = models.CharField(max_length=765, db_column='DNI', blank=True) # Field name made lowercase.
nombrecompleto = models.CharField(max_length=765, db_column='NombreCompleto', blank=True) # Field name made lowercase.
idinvestigador = models.CharField(max_length=765, db_column='IdInvestigador', blank=True) # Field name made lowercase.
idprodrevistas = models.IntegerField(null=True, db_column='IdProdrevistas', blank=True) # Field name made lowercase.
firma = models.CharField(max_length=150, db_column='Firma', blank=True) # Field name made lowercase.
centro = models.CharField(max_length=765, db_column='Centro', blank=True) # Field name made lowercase.
idseccion = models.CharField(max_length=150, db_column='IdSeccion', blank=True) # Field name made lowercase.
class Meta:
db_table = u'InvestigadoresPublicaciones'
class Publicaciones(models.Model):
idprorevistas = models.IntegerField(null=True, db_column='IdProrevistas', blank=True) # Field name made lowercase.
autores = models.TextField(db_column='Autores', blank=True) # Field name made lowercase.
instituciones_1 = models.TextField(db_column='Instituciones_1', blank=True) # Field name made lowercase.
instituciones = models.TextField(db_column='Instituciones', blank=True) # Field name made lowercase.
titulo = models.TextField(db_column='Titulo', blank=True) # Field name made lowercase.
revista = models.CharField(max_length=765, db_column='Revista', blank=True) # Field name made lowercase.
fechapub = models.FloatField(null=True, db_column='A\xc3\xb1opub', blank=True) # Field name made lowercase. aΓ±opub -> fechapub
volumen = models.CharField(max_length=150, db_column='Volumen', blank=True) # Field name made lowercase.
numero = models.CharField(max_length=150, db_column='Numero', blank=True) # Field name made lowercase.
paginas = models.CharField(max_length=765, db_column='Paginas', blank=True) # Field name made lowercase.
tipodoc = models.CharField(max_length=765, db_column='Tipodoc', blank=True) # Field name made lowercase.
idioma = models.CharField(max_length=765, db_column='Idioma', blank=True) # Field name made lowercase.
citas = models.FloatField(null=True, db_column='Citas', blank=True) # Field name made lowercase.
issnstandar = models.CharField(max_length=765, db_column='ISSNStandar', blank=True) # Field name made lowercase.
issnplus = models.CharField(max_length=765, db_column='ISSNPlus', blank=True) # Field name made lowercase.
isbn = models.CharField(max_length=150, db_column='ISBN', blank=True) # Field name made lowercase.
basededatos = models.CharField(max_length=765, db_column='Basededatos', blank=True) # Field name made lowercase.
ute = models.CharField(max_length=150, db_column='UTE', blank=True) # Field name made lowercase.
doi = models.CharField(max_length=450, db_column='DOI', blank=True) # Field name made lowercase.
funding_wos1 = models.TextField(db_column='Funding Wos1', blank=True) # Field renamed to remove spaces. Field name made lowercase.
funding_wos2 = models.TextField(db_column='Funding Wos2', blank=True) # Field renamed to remove spaces. Field name made lowercase.
pubmedid_sc = models.CharField(max_length=150, db_column='PUBMEDID SC', blank=True) # Field renamed to remove spaces. Field name made lowercase.
keyword1 = models.TextField(db_column='Keyword1', blank=True) # Field name made lowercase.
keyword2 = models.TextField(db_column='Keyword2', blank=True) # Field name made lowercase.
disciplinaisi = models.TextField(db_column='DisciplinaISI', blank=True) # Field name made lowercase.
keywordisi1 = models.TextField(db_column='KeywordISI1', blank=True) # Field name made lowercase.
keywordisi2 = models.TextField(db_column='KeywordISI2', blank=True) # Field name made lowercase.
abstract = models.TextField(db_column='Abstract', blank=True) # Field name made lowercase.
class Meta:
db_table = u'Publicaciones'
class DjangoContentType(models.Model):
id = models.IntegerField(primary_key=True)
name = models.CharField(max_length=300)
app_label = models.CharField(unique=True, max_length=250)
model = models.CharField(unique=True, max_length=250)
class Meta:
db_table = u'django_content_type'
class AuthGroup(models.Model):
id = models.IntegerField(primary_key=True)
name = models.CharField(unique=True, max_length=240)
class Meta:
db_table = u'auth_group'
class AuthPermission(models.Model):
id = models.IntegerField(primary_key=True)
name = models.CharField(max_length=150)
content_type = models.ForeignKey(DjangoContentType)
codename = models.CharField(unique=True, max_length=250)
class Meta:
db_table = u'auth_permission'
class AuthGroupPermissions(models.Model):
id = models.IntegerField(primary_key=True)
group = models.ForeignKey(AuthGroup)
permission = models.ForeignKey(AuthPermission)
class Meta:
db_table = u'auth_group_permissions'
class AuthUser(models.Model):
id = models.IntegerField(primary_key=True)
username = models.CharField(unique=True, max_length=90)
first_name = models.CharField(max_length=90)
last_name = models.CharField(max_length=90)
email = models.CharField(max_length=225)
password = models.CharField(max_length=384)
is_staff = models.IntegerField()
is_active = models.IntegerField()
is_superuser = models.IntegerField()
last_login = models.DateTimeField()
date_joined = models.DateTimeField()
class Meta:
db_table = u'auth_user'
class AuthMessage(models.Model):
id = models.IntegerField(primary_key=True)
user = models.ForeignKey(AuthUser)
message = models.TextField()
class Meta:
db_table = u'auth_message'
class AuthUserGroups(models.Model):
id = models.IntegerField(primary_key=True)
user = models.ForeignKey(AuthUser)
group = models.ForeignKey(AuthGroup)
class Meta:
db_table = u'auth_user_groups'
class AuthUserUserPermissions(models.Model):
id = models.IntegerField(primary_key=True)
user = models.ForeignKey(AuthUser)
permission = models.ForeignKey(AuthPermission)
class Meta:
db_table = u'auth_user_user_permissions'
class DjangoAdminLog(models.Model):
id = models.IntegerField(primary_key=True)
action_time = models.DateTimeField()
user = models.ForeignKey(AuthUser)
content_type = models.ForeignKey(DjangoContentType, null=True, blank=True)
object_id = models.TextField(blank=True)
object_repr = models.CharField(max_length=600)
action_flag = models.IntegerField()
change_message = models.TextField()
class Meta:
db_table = u'django_admin_log'
class DjangoSession(models.Model):
session_key = models.CharField(max_length=120, primary_key=True)
session_data = models.TextField()
expire_date = models.DateTimeField()
class Meta:
db_table = u'django_session'
class ViewProductionRanking(models.Model):
idprorevistas = models.IntegerField(null=True, db_column='IdProRevistas', blank=True) # Field name made lowercase.
titulo = models.CharField(max_length=765, db_column='Titulo', blank=True) # Field name made lowercase.
autores = models.CharField(max_length=765, db_column='Autores', blank=True) # Field name made lowercase.
investigador = models.CharField(max_length=765, db_column='Investigador', blank=True) # Field name made lowercase.
centro = models.CharField(max_length=765, db_column='Centro', blank=True) # Field name made lowercase.
hospitalario = models.IntegerField(null=True, db_column='Hospitalario', blank=True) # Field name made lowercase.
cuartil = models.CharField(max_length=765, db_column='Cuartil', blank=True) # Field name made lowercase.
decil = models.IntegerField(null=True, db_column='Decil', blank=True) # Field name made lowercase.
top3 = models.IntegerField(null=True, db_column='Top3', blank=True) # Field name made lowercase.
area = models.CharField(max_length=765, db_column='Area', blank=True) # Field name made lowercase.
grupo = models.CharField(max_length=765, db_column='Grupo', blank=True) # Field name made lowercase.
fechapub = models.FloatField(null=True, db_column='A\xc3\xb1opub', blank=True) # Field name made lowercase. aΓ±opub -> fechapub
issnplus = models.CharField(max_length=765, db_column='ISSNPlus', blank=True) # Field name made lowercase.
revista = models.CharField(max_length=765, db_column='Revista', blank=True) # Field name made lowercase.
idcategoriaisi = models.CharField(max_length=765, db_column='IdCategoriaISI', blank=True) # Field name made lowercase.
impact = models.FloatField(null=True, db_column='Impact', blank=True) # Field name made lowercase.
impact5 = models.FloatField(null=True, db_column='5Impact', blank=True) # Field name made lowercase. 5impact -> impact5
citas = models.FloatField(null=True, db_column='Citas', blank=True) # Field name made lowercase.
categoriaisi = models.CharField(max_length=765, db_column='CategoriaISI', blank=True) # Field name made lowercase.
ute = models.CharField(max_length=765, db_column='UTE', blank=True) # Field name made lowercase.
instituciones = models.TextField(db_column='Instituciones', blank=True) # Field name made lowercase.
asistencial = models.CharField(max_length=765, db_column='Asistencial', blank=True) # Field name made lowercase.
publico = models.CharField(max_length=765, db_column='Publico', blank=True) # Field name made lowercase.
class Meta:
db_table = u'view_production_ranking'
| gpl-2.0 |
Opentrons/labware | api/src/opentrons/drivers/serial_communication.py | 3 | 3983 | import serial # type: ignore
from serial.tools import list_ports # type: ignore
import contextlib
import logging
log = logging.getLogger(__name__)
RECOVERY_TIMEOUT = 10
DEFAULT_SERIAL_TIMEOUT = 5
DEFAULT_WRITE_TIMEOUT = 30
class SerialNoResponse(Exception):
pass
def get_ports_by_name(device_name):
'''Returns all serial devices with a given name'''
filtered_devices = filter(
lambda device: device_name in device[1],
list_ports.comports()
)
device_ports = [device[0] for device in filtered_devices]
return device_ports
def get_port_by_VID(vid):
'''Returns first serial device with a given VID'''
for d in list_ports.comports():
if d.vid == vid:
return d[0]
@contextlib.contextmanager
def serial_with_temp_timeout(serial_connection, timeout):
'''Implements a temporary timeout for a serial connection'''
saved_timeout = serial_connection.timeout
if timeout is not None:
serial_connection.timeout = timeout
yield serial_connection
serial_connection.timeout = saved_timeout
def _parse_serial_response(response, ack):
if ack in response:
parsed_response = response.split(ack)[0]
return parsed_response.strip()
else:
return None
def clear_buffer(serial_connection):
serial_connection.reset_input_buffer()
def _write_to_device_and_return(cmd, ack, device_connection, tag=None):
'''Writes to a serial device.
- Formats command
- Wait for ack return
- return parsed response'''
if not tag:
tag = device_connection.port
encoded_write = cmd.encode()
encoded_ack = ack.encode()
log.debug(f'{tag}: Write -> {encoded_write}')
device_connection.write(encoded_write)
response = device_connection.read_until(encoded_ack)
log.debug(f'{tag}: Read <- {response}')
if encoded_ack not in response:
log.warning(f'{tag}: timed out after {device_connection.timeout}')
raise SerialNoResponse(
'No response from serial port after {} second(s)'.format(
device_connection.timeout))
clean_response = _parse_serial_response(response, encoded_ack)
if clean_response:
return clean_response.decode()
return ''
def _connect(port_name, baudrate):
ser = serial.Serial(
port=port_name,
baudrate=baudrate,
timeout=DEFAULT_SERIAL_TIMEOUT
)
log.debug(ser)
return ser
def _attempt_command_recovery(command, ack, serial_conn, tag=None):
'''Recovery after following a failed write_and_return() atempt'''
if not tag:
tag = serial_conn.port
with serial_with_temp_timeout(serial_conn, RECOVERY_TIMEOUT) as device:
response = _write_to_device_and_return(command, ack, device, tag=tag)
if response is None:
log.debug(f"{tag}: No valid response during _attempt_command_recovery")
raise RuntimeError(
"Recovery attempted - no valid serial response "
"for command: {} in {} seconds".format(
command.encode(), RECOVERY_TIMEOUT))
return response
def write_and_return(
command, ack, serial_connection,
timeout=DEFAULT_WRITE_TIMEOUT, tag=None):
'''Write a command and return the response'''
clear_buffer(serial_connection)
with serial_with_temp_timeout(
serial_connection, timeout) as device_connection:
response = _write_to_device_and_return(
command, ack, device_connection, tag)
return response
def connect(device_name=None, port=None, baudrate=115200):
'''
Creates a serial connection
:param device_name: defaults to 'Smoothieboard'
:param baudrate: integer frequency for serial communication
:return: serial.Serial connection
'''
if not port:
port = get_ports_by_name(device_name=device_name)[0]
log.debug("Device name: {}, Port: {}".format(device_name, port))
return _connect(port_name=port, baudrate=baudrate)
| apache-2.0 |
abergeron/pylearn2 | pylearn2/scripts/tests/test_dbm.py | 37 | 3931 | """
Tests scripts in the DBM folder
"""
import os
import pylearn2.scripts.dbm.show_negative_chains as negative_chains
import pylearn2.scripts.dbm.show_reconstructions as show_reconstruct
import pylearn2.scripts.dbm.show_samples as show_samples
import pylearn2.scripts.dbm.top_filters as top_filters
from pylearn2.config import yaml_parse
from pylearn2.models.dbm.layer import BinaryVector, BinaryVectorMaxPool
from pylearn2.datasets.mnist import MNIST
from pylearn2.models.dbm.dbm import DBM
from nose.tools import with_setup
from pylearn2.datasets import control
from pylearn2.utils import serial
from theano import function
from theano.compat.six.moves import cPickle
def setup():
"""
Create pickle file with a simple model.
"""
# tearDown is guaranteed to run pop_load_data.
control.push_load_data(False)
with open('dbm.pkl', 'wb') as f:
dataset = MNIST(which_set='train', start=0, stop=100, binarize=True)
vis_layer = BinaryVector(nvis=784, bias_from_marginals=dataset)
hid_layer1 = BinaryVectorMaxPool(layer_name='h1', pool_size=1,
irange=.05, init_bias=-2.,
detector_layer_dim=50)
hid_layer2 = BinaryVectorMaxPool(layer_name='h2', pool_size=1,
irange=.05, init_bias=-2.,
detector_layer_dim=10)
model = DBM(batch_size=20, niter=2, visible_layer=vis_layer,
hidden_layers=[hid_layer1, hid_layer2])
model.dataset_yaml_src = """
!obj:pylearn2.datasets.binarizer.Binarizer {
raw: !obj:pylearn2.datasets.mnist.MNIST {
which_set: "train",
start: 0,
stop: 100
}
}
"""
model.layer_to_chains = model.make_layer_to_state(1)
cPickle.dump(model, f, protocol=cPickle.HIGHEST_PROTOCOL)
def teardown():
"""Delete the pickle file created for the tests"""
if os.path.isfile('dbm.pkl'):
os.remove('dbm.pkl')
control.pop_load_data()
@with_setup(setup, teardown)
def test_show_negative_chains():
"""Test the show_negative_chains script main function"""
negative_chains.show_negative_chains('dbm.pkl')
@with_setup(setup, teardown)
def test_show_reconstructions():
"""Test the reconstruction update_viewer function"""
rows = 5
cols = 10
m = rows * cols
model = show_reconstruct.load_model('dbm.pkl', m)
dataset = show_reconstruct.load_dataset(model.dataset_yaml_src,
use_test_set='n')
batch = model.visible_layer.space.make_theano_batch()
reconstruction = model.reconstruct(batch)
recons_func = function([batch], reconstruction)
vis_batch = dataset.get_batch_topo(m)
patch_viewer = show_reconstruct.init_viewer(dataset, rows, cols, vis_batch)
show_reconstruct.update_viewer(dataset, batch, rows, cols, patch_viewer,
recons_func, vis_batch)
@with_setup(setup, teardown)
def test_show_samples():
"""Test the samples update_viewer function"""
rows = 10
cols = 10
m = rows * cols
model = show_samples.load_model('dbm.pkl', m)
dataset = yaml_parse.load(model.dataset_yaml_src)
samples_viewer = show_samples.init_viewer(dataset, rows, cols)
vis_batch = dataset.get_batch_topo(m)
show_samples.update_viewer(dataset, samples_viewer, vis_batch, rows, cols)
@with_setup(setup, teardown)
def test_top_filters():
"""Test the top_filters viewer functions"""
model = serial.load('dbm.pkl')
layer_1, layer_2 = model.hidden_layers[0:2]
W1 = layer_1.get_weights()
W2 = layer_2.get_weights()
top_filters.get_mat_product_viewer(W1, W2)
dataset_yaml_src = model.dataset_yaml_src
dataset = yaml_parse.load(dataset_yaml_src)
imgs = dataset.get_weights_view(W1.T)
top_filters.get_connections_viewer(imgs, W1, W2)
| bsd-3-clause |
vongochung/buiquocviet | django/contrib/gis/admin/options.py | 83 | 5247 | from django.contrib.admin import ModelAdmin
from django.contrib.gis.admin.widgets import OpenLayersWidget
from django.contrib.gis.gdal import OGRGeomType
from django.contrib.gis.db import models
class GeoModelAdmin(ModelAdmin):
"""
The administration options class for Geographic models. Map settings
may be overloaded from their defaults to create custom maps.
"""
# The default map settings that may be overloaded -- still subject
# to API changes.
default_lon = 0
default_lat = 0
default_zoom = 4
display_wkt = False
display_srid = False
extra_js = []
num_zoom = 18
max_zoom = False
min_zoom = False
units = False
max_resolution = False
max_extent = False
modifiable = True
mouse_position = True
scale_text = True
layerswitcher = True
scrollable = True
map_width = 600
map_height = 400
map_srid = 4326
map_template = 'gis/admin/openlayers.html'
openlayers_url = 'http://openlayers.org/api/2.11/OpenLayers.js'
point_zoom = num_zoom - 6
wms_url = 'http://vmap0.tiles.osgeo.org/wms/vmap0'
wms_layer = 'basic'
wms_name = 'OpenLayers WMS'
debug = False
widget = OpenLayersWidget
@property
def media(self):
"Injects OpenLayers JavaScript into the admin."
media = super(GeoModelAdmin, self).media
media.add_js([self.openlayers_url])
media.add_js(self.extra_js)
return media
def formfield_for_dbfield(self, db_field, **kwargs):
"""
Overloaded from ModelAdmin so that an OpenLayersWidget is used
for viewing/editing GeometryFields.
"""
if isinstance(db_field, models.GeometryField):
request = kwargs.pop('request', None)
# Setting the widget with the newly defined widget.
kwargs['widget'] = self.get_map_widget(db_field)
return db_field.formfield(**kwargs)
else:
return super(GeoModelAdmin, self).formfield_for_dbfield(db_field, **kwargs)
def get_map_widget(self, db_field):
"""
Returns a subclass of the OpenLayersWidget (or whatever was specified
in the `widget` attribute) using the settings from the attributes set
in this class.
"""
is_collection = db_field.geom_type in ('MULTIPOINT', 'MULTILINESTRING', 'MULTIPOLYGON', 'GEOMETRYCOLLECTION')
if is_collection:
if db_field.geom_type == 'GEOMETRYCOLLECTION': collection_type = 'Any'
else: collection_type = OGRGeomType(db_field.geom_type.replace('MULTI', ''))
else:
collection_type = 'None'
class OLMap(self.widget):
template = self.map_template
geom_type = db_field.geom_type
params = {'default_lon' : self.default_lon,
'default_lat' : self.default_lat,
'default_zoom' : self.default_zoom,
'display_wkt' : self.debug or self.display_wkt,
'geom_type' : OGRGeomType(db_field.geom_type),
'field_name' : db_field.name,
'is_collection' : is_collection,
'scrollable' : self.scrollable,
'layerswitcher' : self.layerswitcher,
'collection_type' : collection_type,
'is_linestring' : db_field.geom_type in ('LINESTRING', 'MULTILINESTRING'),
'is_polygon' : db_field.geom_type in ('POLYGON', 'MULTIPOLYGON'),
'is_point' : db_field.geom_type in ('POINT', 'MULTIPOINT'),
'num_zoom' : self.num_zoom,
'max_zoom' : self.max_zoom,
'min_zoom' : self.min_zoom,
'units' : self.units, #likely shoud get from object
'max_resolution' : self.max_resolution,
'max_extent' : self.max_extent,
'modifiable' : self.modifiable,
'mouse_position' : self.mouse_position,
'scale_text' : self.scale_text,
'map_width' : self.map_width,
'map_height' : self.map_height,
'point_zoom' : self.point_zoom,
'srid' : self.map_srid,
'display_srid' : self.display_srid,
'wms_url' : self.wms_url,
'wms_layer' : self.wms_layer,
'wms_name' : self.wms_name,
'debug' : self.debug,
}
return OLMap
from django.contrib.gis import gdal
if gdal.HAS_GDAL:
# Use the official spherical mercator projection SRID on versions
# of GDAL that support it; otherwise, fallback to 900913.
if gdal.GDAL_VERSION >= (1, 7):
spherical_mercator_srid = 3857
else:
spherical_mercator_srid = 900913
class OSMGeoAdmin(GeoModelAdmin):
map_template = 'gis/admin/osm.html'
num_zoom = 20
map_srid = spherical_mercator_srid
max_extent = '-20037508,-20037508,20037508,20037508'
max_resolution = '156543.0339'
point_zoom = num_zoom - 6
units = 'm'
| bsd-3-clause |
jupierce/openshift-tools | ansible/roles/lib_yaml_editor/build/ansible/yedit.py | 10 | 6223 | #pylint: skip-file
def get_curr_value(invalue, val_type):
'''return the current value'''
if invalue == None:
return None
curr_value = invalue
if val_type == 'yaml':
curr_value = yaml.load(invalue)
elif val_type == 'json':
curr_value = json.loads(invalue)
return curr_value
def parse_value(inc_value, vtype=''):
'''determine value type passed'''
true_bools = ['y', 'Y', 'yes', 'Yes', 'YES', 'true', 'True', 'TRUE', 'on', 'On', 'ON', ]
false_bools = ['n', 'N', 'no', 'No', 'NO', 'false', 'False', 'FALSE', 'off', 'Off', 'OFF']
# It came in as a string but you didn't specify value_type as string
# we will convert to bool if it matches any of the above cases
if isinstance(inc_value, str) and 'bool' in vtype:
if inc_value not in true_bools and inc_value not in false_bools:
raise YeditException('Not a boolean type. str=[%s] vtype=[%s]' % (inc_value, vtype))
elif isinstance(inc_value, bool) and 'str' in vtype:
inc_value = str(inc_value)
# There is a special case where '' will turn into None after yaml loading it so skip
if isinstance(inc_value, str) and inc_value == '':
pass
# If vtype is not str then go ahead and attempt to yaml load it.
elif isinstance(inc_value, str) and 'str' not in vtype:
try:
inc_value = yaml.load(inc_value)
except Exception as _:
raise YeditException('Could not determine type of incoming value. value=[%s] vtype=[%s]' \
% (type(inc_value), vtype))
return inc_value
# pylint: disable=too-many-branches
def main():
''' ansible oc module for secrets '''
module = AnsibleModule(
argument_spec=dict(
state=dict(default='present', type='str',
choices=['present', 'absent', 'list']),
debug=dict(default=False, type='bool'),
src=dict(default=None, type='str'),
content=dict(default=None),
content_type=dict(default='dict', choices=['dict']),
key=dict(default='', type='str'),
value=dict(),
value_type=dict(default='', type='str'),
update=dict(default=False, type='bool'),
append=dict(default=False, type='bool'),
index=dict(default=None, type='int'),
curr_value=dict(default=None, type='str'),
curr_value_format=dict(default='yaml', choices=['yaml', 'json', 'str'], type='str'),
backup=dict(default=True, type='bool'),
separator=dict(default='.', type='str'),
),
mutually_exclusive=[["curr_value", "index"], ['update', "append"]],
required_one_of=[["content", "src"]],
)
yamlfile = Yedit(filename=module.params['src'],
backup=module.params['backup'],
separator=module.params['separator'],
)
if module.params['src']:
rval = yamlfile.load()
if yamlfile.yaml_dict == None and module.params['state'] != 'present':
module.fail_json(msg='Error opening file [%s]. Verify that the' + \
' file exists, that it is has correct permissions, and is valid yaml.')
if module.params['state'] == 'list':
if module.params['content']:
content = parse_value(module.params['content'], module.params['content_type'])
yamlfile.yaml_dict = content
if module.params['key']:
rval = yamlfile.get(module.params['key']) or {}
module.exit_json(changed=False, result=rval, state="list")
elif module.params['state'] == 'absent':
if module.params['content']:
content = parse_value(module.params['content'], module.params['content_type'])
yamlfile.yaml_dict = content
if module.params['update']:
rval = yamlfile.pop(module.params['key'], module.params['value'])
else:
rval = yamlfile.delete(module.params['key'])
if rval[0] and module.params['src']:
yamlfile.write()
module.exit_json(changed=rval[0], result=rval[1], state="absent")
elif module.params['state'] == 'present':
# check if content is different than what is in the file
if module.params['content']:
content = parse_value(module.params['content'], module.params['content_type'])
# We had no edits to make and the contents are the same
if yamlfile.yaml_dict == content and module.params['value'] == None:
module.exit_json(changed=False, result=yamlfile.yaml_dict, state="present")
yamlfile.yaml_dict = content
# we were passed a value; parse it
if module.params['value'] is not None:
value = parse_value(module.params['value'], module.params['value_type'])
key = module.params['key']
if module.params['update']:
curr_value = get_curr_value(parse_value(module.params['curr_value']),
module.params['curr_value_format'])
rval = yamlfile.update(key, value, module.params['index'], curr_value)
elif module.params['append']:
rval = yamlfile.append(key, value)
else:
rval = yamlfile.put(key, value)
if rval[0] and module.params['src']:
yamlfile.write()
module.exit_json(changed=rval[0], result=rval[1], state="present")
# no edits to make
if module.params['src']:
rval = yamlfile.write()
module.exit_json(changed=rval[0], result=rval[1], state="present")
module.exit_json(changed=False, result=yamlfile.yaml_dict, state="present")
module.exit_json(failed=True,
changed=False,
results='Unknown state passed. %s' % module.params['state'],
state="unknown")
# pylint: disable=redefined-builtin, unused-wildcard-import, wildcard-import, locally-disabled
# import module snippets. This are required
if __name__ == '__main__':
from ansible.module_utils.basic import *
main()
| apache-2.0 |
KasenJ/CommunityPython | code/push/google/protobuf/text_format.py | 1 | 22190 | # Protocol Buffers - Google's data interchange format
# Copyright 2008 Google Inc. All rights reserved.
# http://code.google.com/p/protobuf/
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. 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.
"""Contains routines for printing protocol messages in text format."""
__author__ = '[email protected] (Kenton Varda)'
import cStringIO
import re
from collections import deque
from push.google.protobuf.internal import type_checkers
from push.google.protobuf import descriptor
__all__ = [ 'MessageToString', 'PrintMessage', 'PrintField',
'PrintFieldValue', 'Merge' ]
_INTEGER_CHECKERS = (type_checkers.Uint32ValueChecker(),
type_checkers.Int32ValueChecker(),
type_checkers.Uint64ValueChecker(),
type_checkers.Int64ValueChecker())
_FLOAT_INFINITY = re.compile('-?inf(?:inity)?f?', re.IGNORECASE)
_FLOAT_NAN = re.compile('nanf?', re.IGNORECASE)
class ParseError(Exception):
"""Thrown in case of ASCII parsing error."""
def MessageToString(message, as_utf8=False, as_one_line=False):
out = cStringIO.StringIO()
PrintMessage(message, out, as_utf8=as_utf8, as_one_line=as_one_line)
result = out.getvalue()
out.close()
if as_one_line:
return result.rstrip()
return result
def PrintMessage(message, out, indent=0, as_utf8=False, as_one_line=False):
for field, value in message.ListFields():
if field.label == descriptor.FieldDescriptor.LABEL_REPEATED:
for element in value:
PrintField(field, element, out, indent, as_utf8, as_one_line)
else:
PrintField(field, value, out, indent, as_utf8, as_one_line)
def PrintField(field, value, out, indent=0, as_utf8=False, as_one_line=False):
"""Print a single field name/value pair. For repeated fields, the value
should be a single element."""
out.write(' ' * indent);
if field.is_extension:
out.write('[')
if (field.containing_type.GetOptions().message_set_wire_format and
field.type == descriptor.FieldDescriptor.TYPE_MESSAGE and
field.message_type == field.extension_scope and
field.label == descriptor.FieldDescriptor.LABEL_OPTIONAL):
out.write(field.message_type.full_name)
else:
out.write(field.full_name)
out.write(']')
elif field.type == descriptor.FieldDescriptor.TYPE_GROUP:
# For groups, use the capitalized name.
out.write(field.message_type.name)
else:
out.write(field.name)
if field.cpp_type != descriptor.FieldDescriptor.CPPTYPE_MESSAGE:
# The colon is optional in this case, but our cross-language golden files
# don't include it.
out.write(': ')
PrintFieldValue(field, value, out, indent, as_utf8, as_one_line)
if as_one_line:
out.write(' ')
else:
out.write('\n')
def PrintFieldValue(field, value, out, indent=0,
as_utf8=False, as_one_line=False):
"""Print a single field value (not including name). For repeated fields,
the value should be a single element."""
if field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_MESSAGE:
if as_one_line:
out.write(' { ')
PrintMessage(value, out, indent, as_utf8, as_one_line)
out.write('}')
else:
out.write(' {\n')
PrintMessage(value, out, indent + 2, as_utf8, as_one_line)
out.write(' ' * indent + '}')
elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_ENUM:
enum_value = field.enum_type.values_by_number.get(value, None)
if enum_value is not None:
out.write(enum_value.name)
else:
out.write(str(value))
elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_STRING:
out.write('\"')
if type(value) is unicode:
out.write(_CEscape(value.encode('utf-8'), as_utf8))
else:
out.write(_CEscape(value, as_utf8))
out.write('\"')
elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_BOOL:
if value:
out.write("true")
else:
out.write("false")
else:
out.write(str(value))
def Merge(text, message):
"""Merges an ASCII representation of a protocol message into a message.
Args:
text: Message ASCII representation.
message: A protocol buffer message to merge into.
Raises:
ParseError: On ASCII parsing problems.
"""
tokenizer = _Tokenizer(text)
while not tokenizer.AtEnd():
_MergeField(tokenizer, message)
def _MergeField(tokenizer, message):
"""Merges a single protocol message field into a message.
Args:
tokenizer: A tokenizer to parse the field name and values.
message: A protocol message to record the data.
Raises:
ParseError: In case of ASCII parsing problems.
"""
message_descriptor = message.DESCRIPTOR
if tokenizer.TryConsume('['):
name = [tokenizer.ConsumeIdentifier()]
while tokenizer.TryConsume('.'):
name.append(tokenizer.ConsumeIdentifier())
name = '.'.join(name)
if not message_descriptor.is_extendable:
raise tokenizer.ParseErrorPreviousToken(
'Message type "%s" does not have extensions.' %
message_descriptor.full_name)
field = message.Extensions._FindExtensionByName(name)
if not field:
raise tokenizer.ParseErrorPreviousToken(
'Extension "%s" not registered.' % name)
elif message_descriptor != field.containing_type:
raise tokenizer.ParseErrorPreviousToken(
'Extension "%s" does not extend message type "%s".' % (
name, message_descriptor.full_name))
tokenizer.Consume(']')
else:
name = tokenizer.ConsumeIdentifier()
field = message_descriptor.fields_by_name.get(name, None)
# Group names are expected to be capitalized as they appear in the
# .proto file, which actually matches their type names, not their field
# names.
if not field:
field = message_descriptor.fields_by_name.get(name.lower(), None)
if field and field.type != descriptor.FieldDescriptor.TYPE_GROUP:
field = None
if (field and field.type == descriptor.FieldDescriptor.TYPE_GROUP and
field.message_type.name != name):
field = None
if not field:
raise tokenizer.ParseErrorPreviousToken(
'Message type "%s" has no field named "%s".' % (
message_descriptor.full_name, name))
if field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_MESSAGE:
tokenizer.TryConsume(':')
if tokenizer.TryConsume('<'):
end_token = '>'
else:
tokenizer.Consume('{')
end_token = '}'
if field.label == descriptor.FieldDescriptor.LABEL_REPEATED:
if field.is_extension:
sub_message = message.Extensions[field].add()
else:
sub_message = getattr(message, field.name).add()
else:
if field.is_extension:
sub_message = message.Extensions[field]
else:
sub_message = getattr(message, field.name)
sub_message.SetInParent()
while not tokenizer.TryConsume(end_token):
if tokenizer.AtEnd():
raise tokenizer.ParseErrorPreviousToken('Expected "%s".' % (end_token))
_MergeField(tokenizer, sub_message)
else:
_MergeScalarField(tokenizer, message, field)
def _MergeScalarField(tokenizer, message, field):
"""Merges a single protocol message scalar field into a message.
Args:
tokenizer: A tokenizer to parse the field value.
message: A protocol message to record the data.
field: The descriptor of the field to be merged.
Raises:
ParseError: In case of ASCII parsing problems.
RuntimeError: On runtime errors.
"""
tokenizer.Consume(':')
value = None
if field.type in (descriptor.FieldDescriptor.TYPE_INT32,
descriptor.FieldDescriptor.TYPE_SINT32,
descriptor.FieldDescriptor.TYPE_SFIXED32):
value = tokenizer.ConsumeInt32()
elif field.type in (descriptor.FieldDescriptor.TYPE_INT64,
descriptor.FieldDescriptor.TYPE_SINT64,
descriptor.FieldDescriptor.TYPE_SFIXED64):
value = tokenizer.ConsumeInt64()
elif field.type in (descriptor.FieldDescriptor.TYPE_UINT32,
descriptor.FieldDescriptor.TYPE_FIXED32):
value = tokenizer.ConsumeUint32()
elif field.type in (descriptor.FieldDescriptor.TYPE_UINT64,
descriptor.FieldDescriptor.TYPE_FIXED64):
value = tokenizer.ConsumeUint64()
elif field.type in (descriptor.FieldDescriptor.TYPE_FLOAT,
descriptor.FieldDescriptor.TYPE_DOUBLE):
value = tokenizer.ConsumeFloat()
elif field.type == descriptor.FieldDescriptor.TYPE_BOOL:
value = tokenizer.ConsumeBool()
elif field.type == descriptor.FieldDescriptor.TYPE_STRING:
value = tokenizer.ConsumeString()
elif field.type == descriptor.FieldDescriptor.TYPE_BYTES:
value = tokenizer.ConsumeByteString()
elif field.type == descriptor.FieldDescriptor.TYPE_ENUM:
value = tokenizer.ConsumeEnum(field)
else:
raise RuntimeError('Unknown field type %d' % field.type)
if field.label == descriptor.FieldDescriptor.LABEL_REPEATED:
if field.is_extension:
message.Extensions[field].append(value)
else:
getattr(message, field.name).append(value)
else:
if field.is_extension:
message.Extensions[field] = value
else:
setattr(message, field.name, value)
class _Tokenizer(object):
"""Protocol buffer ASCII representation tokenizer.
This class handles the lower level string parsing by splitting it into
meaningful tokens.
It was directly ported from the Java protocol buffer API.
"""
_WHITESPACE = re.compile('(\\s|(#.*$))+', re.MULTILINE)
_TOKEN = re.compile(
'[a-zA-Z_][0-9a-zA-Z_+-]*|' # an identifier
'[0-9+-][0-9a-zA-Z_.+-]*|' # a number
'\"([^\"\n\\\\]|\\\\.)*(\"|\\\\?$)|' # a double-quoted string
'\'([^\'\n\\\\]|\\\\.)*(\'|\\\\?$)') # a single-quoted string
_IDENTIFIER = re.compile('\w+')
def __init__(self, text_message):
self._text_message = text_message
self._position = 0
self._line = -1
self._column = 0
self._token_start = None
self.token = ''
self._lines = deque(text_message.split('\n'))
self._current_line = ''
self._previous_line = 0
self._previous_column = 0
self._SkipWhitespace()
self.NextToken()
def AtEnd(self):
"""Checks the end of the text was reached.
Returns:
True iff the end was reached.
"""
return self.token == ''
def _PopLine(self):
while len(self._current_line) <= self._column:
if not self._lines:
self._current_line = ''
return
self._line += 1
self._column = 0
self._current_line = self._lines.popleft()
def _SkipWhitespace(self):
while True:
self._PopLine()
match = self._WHITESPACE.match(self._current_line, self._column)
if not match:
break
length = len(match.group(0))
self._column += length
def TryConsume(self, token):
"""Tries to consume a given piece of text.
Args:
token: Text to consume.
Returns:
True iff the text was consumed.
"""
if self.token == token:
self.NextToken()
return True
return False
def Consume(self, token):
"""Consumes a piece of text.
Args:
token: Text to consume.
Raises:
ParseError: If the text couldn't be consumed.
"""
if not self.TryConsume(token):
raise self._ParseError('Expected "%s".' % token)
def ConsumeIdentifier(self):
"""Consumes protocol message field identifier.
Returns:
Identifier string.
Raises:
ParseError: If an identifier couldn't be consumed.
"""
result = self.token
if not self._IDENTIFIER.match(result):
raise self._ParseError('Expected identifier.')
self.NextToken()
return result
def ConsumeInt32(self):
"""Consumes a signed 32bit integer number.
Returns:
The integer parsed.
Raises:
ParseError: If a signed 32bit integer couldn't be consumed.
"""
try:
result = ParseInteger(self.token, is_signed=True, is_long=False)
except ValueError, e:
raise self._ParseError(str(e))
self.NextToken()
return result
def ConsumeUint32(self):
"""Consumes an unsigned 32bit integer number.
Returns:
The integer parsed.
Raises:
ParseError: If an unsigned 32bit integer couldn't be consumed.
"""
try:
result = ParseInteger(self.token, is_signed=False, is_long=False)
except ValueError, e:
raise self._ParseError(str(e))
self.NextToken()
return result
def ConsumeInt64(self):
"""Consumes a signed 64bit integer number.
Returns:
The integer parsed.
Raises:
ParseError: If a signed 64bit integer couldn't be consumed.
"""
try:
result = ParseInteger(self.token, is_signed=True, is_long=True)
except ValueError, e:
raise self._ParseError(str(e))
self.NextToken()
return result
def ConsumeUint64(self):
"""Consumes an unsigned 64bit integer number.
Returns:
The integer parsed.
Raises:
ParseError: If an unsigned 64bit integer couldn't be consumed.
"""
try:
result = ParseInteger(self.token, is_signed=False, is_long=True)
except ValueError, e:
raise self._ParseError(str(e))
self.NextToken()
return result
def ConsumeFloat(self):
"""Consumes an floating point number.
Returns:
The number parsed.
Raises:
ParseError: If a floating point number couldn't be consumed.
"""
try:
result = ParseFloat(self.token)
except ValueError, e:
raise self._ParseError(str(e))
self.NextToken()
return result
def ConsumeBool(self):
"""Consumes a boolean value.
Returns:
The bool parsed.
Raises:
ParseError: If a boolean value couldn't be consumed.
"""
try:
result = ParseBool(self.token)
except ValueError, e:
raise self._ParseError(str(e))
self.NextToken()
return result
def ConsumeString(self):
"""Consumes a string value.
Returns:
The string parsed.
Raises:
ParseError: If a string value couldn't be consumed.
"""
bytes = self.ConsumeByteString()
try:
return unicode(bytes, 'utf-8')
except UnicodeDecodeError, e:
raise self._StringParseError(e)
def ConsumeByteString(self):
"""Consumes a byte array value.
Returns:
The array parsed (as a string).
Raises:
ParseError: If a byte array value couldn't be consumed.
"""
list = [self._ConsumeSingleByteString()]
while len(self.token) > 0 and self.token[0] in ('\'', '"'):
list.append(self._ConsumeSingleByteString())
return "".join(list)
def _ConsumeSingleByteString(self):
"""Consume one token of a string literal.
String literals (whether bytes or text) can come in multiple adjacent
tokens which are automatically concatenated, like in C or Python. This
method only consumes one token.
"""
text = self.token
if len(text) < 1 or text[0] not in ('\'', '"'):
raise self._ParseError('Expected string.')
if len(text) < 2 or text[-1] != text[0]:
raise self._ParseError('String missing ending quote.')
try:
result = _CUnescape(text[1:-1])
except ValueError, e:
raise self._ParseError(str(e))
self.NextToken()
return result
def ConsumeEnum(self, field):
try:
result = ParseEnum(field, self.token)
except ValueError, e:
raise self._ParseError(str(e))
self.NextToken()
return result
def ParseErrorPreviousToken(self, message):
"""Creates and *returns* a ParseError for the previously read token.
Args:
message: A message to set for the exception.
Returns:
A ParseError instance.
"""
return ParseError('%d:%d : %s' % (
self._previous_line + 1, self._previous_column + 1, message))
def _ParseError(self, message):
"""Creates and *returns* a ParseError for the current token."""
return ParseError('%d:%d : %s' % (
self._line + 1, self._column + 1, message))
def _StringParseError(self, e):
return self._ParseError('Couldn\'t parse string: ' + str(e))
def NextToken(self):
"""Reads the next meaningful token."""
self._previous_line = self._line
self._previous_column = self._column
self._column += len(self.token)
self._SkipWhitespace()
if not self._lines and len(self._current_line) <= self._column:
self.token = ''
return
match = self._TOKEN.match(self._current_line, self._column)
if match:
token = match.group(0)
self.token = token
else:
self.token = self._current_line[self._column]
# text.encode('string_escape') does not seem to satisfy our needs as it
# encodes unprintable characters using two-digit hex escapes whereas our
# C++ unescaping function allows hex escapes to be any length. So,
# "\0011".encode('string_escape') ends up being "\\x011", which will be
# decoded in C++ as a single-character string with char code 0x11.
def _CEscape(text, as_utf8):
def escape(c):
o = ord(c)
if o == 10: return r"\n" # optional escape
if o == 13: return r"\r" # optional escape
if o == 9: return r"\t" # optional escape
if o == 39: return r"\'" # optional escape
if o == 34: return r'\"' # necessary escape
if o == 92: return r"\\" # necessary escape
# necessary escapes
if not as_utf8 and (o >= 127 or o < 32): return "\\%03o" % o
return c
return "".join([escape(c) for c in text])
_CUNESCAPE_HEX = re.compile(r'(\\+)x([0-9a-fA-F])(?![0-9a-fA-F])')
def _CUnescape(text):
def ReplaceHex(m):
# Only replace the match if the number of leading back slashes is odd. i.e.
# the slash itself is not escaped.
if len(m.group(1)) & 1:
return m.group(1) + 'x0' + m.group(2)
return m.group(0)
# This is required because the 'string_escape' encoding doesn't
# allow single-digit hex escapes (like '\xf').
result = _CUNESCAPE_HEX.sub(ReplaceHex, text)
return result.decode('string_escape')
def ParseInteger(text, is_signed=False, is_long=False):
"""Parses an integer.
Args:
text: The text to parse.
is_signed: True if a signed integer must be parsed.
is_long: True if a long integer must be parsed.
Returns:
The integer value.
Raises:
ValueError: Thrown Iff the text is not a valid integer.
"""
# Do the actual parsing. Exception handling is propagated to caller.
try:
result = int(text, 0)
except ValueError:
raise ValueError('Couldn\'t parse integer: %s' % text)
# Check if the integer is sane. Exceptions handled by callers.
checker = _INTEGER_CHECKERS[2 * int(is_long) + int(is_signed)]
checker.CheckValue(result)
return result
def ParseFloat(text):
"""Parse a floating point number.
Args:
text: Text to parse.
Returns:
The number parsed.
Raises:
ValueError: If a floating point number couldn't be parsed.
"""
try:
# Assume Python compatible syntax.
return float(text)
except ValueError:
# Check alternative spellings.
if _FLOAT_INFINITY.match(text):
if text[0] == '-':
return float('-inf')
else:
return float('inf')
elif _FLOAT_NAN.match(text):
return float('nan')
else:
# assume '1.0f' format
try:
return float(text.rstrip('f'))
except ValueError:
raise ValueError('Couldn\'t parse float: %s' % text)
def ParseBool(text):
"""Parse a boolean value.
Args:
text: Text to parse.
Returns:
Boolean values parsed
Raises:
ValueError: If text is not a valid boolean.
"""
if text in ('true', 't', '1'):
return True
elif text in ('false', 'f', '0'):
return False
else:
raise ValueError('Expected "true" or "false".')
def ParseEnum(field, value):
"""Parse an enum value.
The value can be specified by a number (the enum value), or by
a string literal (the enum name).
Args:
field: Enum field descriptor.
value: String value.
Returns:
Enum value number.
Raises:
ValueError: If the enum value could not be parsed.
"""
enum_descriptor = field.enum_type
try:
number = int(value, 0)
except ValueError:
# Identifier.
enum_value = enum_descriptor.values_by_name.get(value, None)
if enum_value is None:
raise ValueError(
'Enum type "%s" has no value named %s.' % (
enum_descriptor.full_name, value))
else:
# Numeric value.
enum_value = enum_descriptor.values_by_number.get(number, None)
if enum_value is None:
raise ValueError(
'Enum type "%s" has no value with number %d.' % (
enum_descriptor.full_name, number))
return enum_value.number
| gpl-2.0 |
2013Commons/hue | desktop/core/ext-py/PyYAML-3.09/lib/yaml/events.py | 985 | 2445 |
# Abstract classes.
class Event(object):
def __init__(self, start_mark=None, end_mark=None):
self.start_mark = start_mark
self.end_mark = end_mark
def __repr__(self):
attributes = [key for key in ['anchor', 'tag', 'implicit', 'value']
if hasattr(self, key)]
arguments = ', '.join(['%s=%r' % (key, getattr(self, key))
for key in attributes])
return '%s(%s)' % (self.__class__.__name__, arguments)
class NodeEvent(Event):
def __init__(self, anchor, start_mark=None, end_mark=None):
self.anchor = anchor
self.start_mark = start_mark
self.end_mark = end_mark
class CollectionStartEvent(NodeEvent):
def __init__(self, anchor, tag, implicit, start_mark=None, end_mark=None,
flow_style=None):
self.anchor = anchor
self.tag = tag
self.implicit = implicit
self.start_mark = start_mark
self.end_mark = end_mark
self.flow_style = flow_style
class CollectionEndEvent(Event):
pass
# Implementations.
class StreamStartEvent(Event):
def __init__(self, start_mark=None, end_mark=None, encoding=None):
self.start_mark = start_mark
self.end_mark = end_mark
self.encoding = encoding
class StreamEndEvent(Event):
pass
class DocumentStartEvent(Event):
def __init__(self, start_mark=None, end_mark=None,
explicit=None, version=None, tags=None):
self.start_mark = start_mark
self.end_mark = end_mark
self.explicit = explicit
self.version = version
self.tags = tags
class DocumentEndEvent(Event):
def __init__(self, start_mark=None, end_mark=None,
explicit=None):
self.start_mark = start_mark
self.end_mark = end_mark
self.explicit = explicit
class AliasEvent(NodeEvent):
pass
class ScalarEvent(NodeEvent):
def __init__(self, anchor, tag, implicit, value,
start_mark=None, end_mark=None, style=None):
self.anchor = anchor
self.tag = tag
self.implicit = implicit
self.value = value
self.start_mark = start_mark
self.end_mark = end_mark
self.style = style
class SequenceStartEvent(CollectionStartEvent):
pass
class SequenceEndEvent(CollectionEndEvent):
pass
class MappingStartEvent(CollectionStartEvent):
pass
class MappingEndEvent(CollectionEndEvent):
pass
| apache-2.0 |
ketjow4/NOV | Lib/site-packages/scipy/cluster/setup.py | 51 | 1313 | #!"C:\Users\hog\Documents\Visual Studio 2010\Projects\ArdupilotMega\ArdupilotMega\bin\Debug\ipy.exe"
import sys
from os.path import join
if sys.version_info[0] >= 3:
DEFINE_MACROS = [("SCIPY_PY3K", None)]
else:
DEFINE_MACROS = []
def configuration(parent_package = '', top_path = None):
from numpy.distutils.misc_util import Configuration, get_numpy_include_dirs
config = Configuration('cluster', parent_package, top_path)
config.add_data_dir('tests')
config.add_extension('_vq',
sources=[join('src', 'vq_module.c'), join('src', 'vq.c')],
include_dirs = [get_numpy_include_dirs()],
define_macros=DEFINE_MACROS)
config.add_extension('_hierarchy_wrap',
sources=[join('src', 'hierarchy_wrap.c'), join('src', 'hierarchy.c')],
include_dirs = [get_numpy_include_dirs()],
define_macros=DEFINE_MACROS)
return config
if __name__ == '__main__':
from numpy.distutils.core import setup
setup(maintainer = "SciPy Developers",
author = "Eric Jones",
maintainer_email = "[email protected]",
description = "Clustering Algorithms (Information Theory)",
url = "http://www.scipy.org",
license = "SciPy License (BSD Style)",
**configuration(top_path='').todict()
)
| gpl-3.0 |
ManjusakaSL/Practice | second/sunspots_roto.py | 1 | 1140 | from reportlab.lib import colors
from reportlab.graphics.shapes import *
from reportlab.graphics import renderPDF
data = [
# Year Month Predicted High Low
(2007, 8, 113.2, 114.2, 112.2),
(2007, 9, 112.8, 115.8, 109.8),
(2007, 10, 111.0, 116.0, 106.0),
(2007, 11, 109.8, 116.8, 102.8),
(2007, 12, 107.3, 115.3, 99.3),
(2008, 1, 105.2, 114.2, 96.2),
(2008, 2, 104.1, 114.1, 94.1),
(2008, 3, 99.9, 110.9, 88.9),
(2008, 4, 94.8, 106.8, 82.8),
(2008, 5, 91.2, 104.2, 78.2),
]
drawing = Drawing(200, 150)
pred = [row[2]-40 for row in data]
high = [row[3]-40 for row in data]
low = [row[4]-40 for row in data]
times = [200*((row[0] + row[1]/12.0) - 2007)-110 for row in data]
drawing.add(PolyLine(zip(times, pred), strokeColor=colors.blue))
drawing.add(PolyLine(zip(times, high), strokeColor=colors.red))
drawing.add(PolyLine(zip(times, low), strokeColor=colors.green))
drawing.add(String(65, 115, 'Sunspots', fontSize=18, fillColor=colors.red))
renderPDF.drawToFile(drawing, 'report1.pdf', 'Sunspots')
| gpl-3.0 |
Adel-Magebinary/odoo | addons/survey/wizard/survey_email_compose_message.py | 57 | 10954 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2010-Today OpenERP SA (<http://www.openerp.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, 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/>
#
##############################################################################
from openerp.osv import osv
from openerp.osv import fields
from openerp.tools.translate import _
from datetime import datetime
import re
import uuid
import urlparse
emails_split = re.compile(r"[;,\n\r]+")
class survey_mail_compose_message(osv.TransientModel):
_name = 'survey.mail.compose.message'
_inherit = 'mail.compose.message'
_description = 'Email composition wizard for Survey'
_log_access = True
def _get_public_url(self, cr, uid, ids, name, arg, context=None):
res = dict((id, 0) for id in ids)
survey_obj = self.pool.get('survey.survey')
for wizard in self.browse(cr, uid, ids, context=context):
res[wizard.id] = wizard.survey_id.public_url
return res
def _get_public_url_html(self, cr, uid, ids, name, arg, context=None):
""" Compute if the message is unread by the current user """
urls = self._get_public_url(cr, uid, ids, name, arg, context=context)
for key, url in urls.items():
urls[key] = '<a href="%s">%s</a>' % (url, _("Click here to start survey"))
return urls
_columns = {
'survey_id': fields.many2one('survey.survey', 'Survey', required=True),
'public': fields.selection([('public_link', 'Share the public web link to your audience.'),
('email_public_link', 'Send by email the public web link to your audience.'),
('email_private', 'Send private invitation to your audience (only one response per recipient and per invitation).')],
string='Share options', required=True),
'public_url': fields.function(_get_public_url, string="Public url", type="char"),
'public_url_html': fields.function(_get_public_url_html, string="Public HTML web link", type="char"),
'partner_ids': fields.many2many('res.partner',
'survey_mail_compose_message_res_partner_rel',
'wizard_id', 'partner_id', 'Existing contacts'),
'attachment_ids': fields.many2many('ir.attachment',
'survey_mail_compose_message_ir_attachments_rel',
'wizard_id', 'attachment_id', 'Attachments'),
'multi_email': fields.text(string='List of emails', help="This list of emails of recipients will not converted in contacts. Emails separated by commas, semicolons or newline."),
'date_deadline': fields.date(string="Deadline to which the invitation to respond is valid", help="Deadline to which the invitation to respond for this survey is valid. If the field is empty, the invitation is still valid."),
}
_defaults = {
'public': 'public_link',
'survey_id': lambda self, cr, uid, ctx={}: ctx.get('model') == 'survey.survey' and ctx.get('res_id') or None
}
def default_get(self, cr, uid, fields, context=None):
res = super(survey_mail_compose_message, self).default_get(cr, uid, fields, context=context)
if context.get('active_model') == 'res.partner' and context.get('active_ids'):
res.update({'partner_ids': context.get('active_ids')})
return res
def onchange_multi_email(self, cr, uid, ids, multi_email, context=None):
emails = list(set(emails_split.split(multi_email or "")))
emails_checked = []
error_message = ""
for email in emails:
email = email.strip()
if email:
if not re.search(r"^[^@]+@[^@]+$", email):
error_message += "\n'%s'" % email
else:
emails_checked.append(email)
if error_message:
raise osv.except_osv(_('Warning!'), _("One email at least is incorrect: %s" % error_message))
emails_checked.sort()
values = {'multi_email': '\n'.join(emails_checked)}
return {'value': values}
def onchange_survey_id(self, cr, uid, ids, survey_id, context=None):
""" Compute if the message is unread by the current user. """
if survey_id:
survey = self.pool.get('survey.survey').browse(cr, uid, survey_id, context=context)
return {
'value': {
'subject': survey.title,
'public_url': survey.public_url,
'public_url_html': '<a href="%s">%s</a>' % (survey.public_url, _("Click here to take survey")),
}}
else:
txt = _("Please select a survey")
return {
'value': {
'public_url': txt,
'public_url_html': txt,
}}
#------------------------------------------------------
# Wizard validation and send
#------------------------------------------------------
def send_mail(self, cr, uid, ids, context=None):
""" Process the wizard content and proceed with sending the related
email(s), rendering any template patterns on the fly if needed """
if context is None:
context = {}
survey_response_obj = self.pool.get('survey.user_input')
partner_obj = self.pool.get('res.partner')
mail_mail_obj = self.pool.get('mail.mail')
try:
model, anonymous_id = self.pool.get('ir.model.data').get_object_reference(cr, uid, 'portal', 'group_anonymous')
except ValueError:
anonymous_id = None
def create_response_and_send_mail(wizard, token, partner_id, email):
""" Create one mail by recipients and replace __URL__ by link with identification token """
#set url
url = wizard.survey_id.public_url
url = urlparse.urlparse(url).path[1:] # dirty hack to avoid incorrect urls
if token:
url = url + '/' + token
# post the message
values = {
'model': None,
'res_id': None,
'subject': wizard.subject,
'body': wizard.body.replace("__URL__", url),
'body_html': wizard.body.replace("__URL__", url),
'parent_id': None,
'partner_ids': partner_id and [(4, partner_id)] or None,
'notified_partner_ids': partner_id and [(4, partner_id)] or None,
'attachment_ids': wizard.attachment_ids and [(6, 0, wizard.attachment_ids.ids)] or None,
'email_from': wizard.email_from or None,
'email_to': email,
}
mail_id = mail_mail_obj.create(cr, uid, values, context=context)
mail_mail_obj.send(cr, uid, [mail_id], context=context)
def create_token(wizard, partner_id, email):
if context.get("survey_resent_token"):
response_ids = survey_response_obj.search(cr, uid, [('survey_id', '=', wizard.survey_id.id), ('state', 'in', ['new', 'skip']), '|', ('partner_id', '=', partner_id), ('email', '=', email)], context=context)
if response_ids:
return survey_response_obj.read(cr, uid, response_ids, ['token'], context=context)[0]['token']
if wizard.public != 'email_private':
return None
else:
token = uuid.uuid4().__str__()
# create response with token
survey_response_obj.create(cr, uid, {
'survey_id': wizard.survey_id.id,
'deadline': wizard.date_deadline,
'date_create': datetime.now(),
'type': 'link',
'state': 'new',
'token': token,
'partner_id': partner_id,
'email': email})
return token
for wizard in self.browse(cr, uid, ids, context=context):
# check if __URL__ is in the text
if wizard.body.find("__URL__") < 0:
raise osv.except_osv(_('Warning!'), _("The content of the text don't contain '__URL__'. \
__URL__ is automaticaly converted into the special url of the survey."))
if not wizard.multi_email and not wizard.partner_ids and (context.get('default_partner_ids') or context.get('default_multi_email')):
wizard.multi_email = context.get('default_multi_email')
wizard.partner_ids = context.get('default_partner_ids')
# quick check of email list
emails_list = []
if wizard.multi_email:
emails = list(set(emails_split.split(wizard.multi_email)) - set([partner.email for partner in wizard.partner_ids]))
for email in emails:
email = email.strip()
if re.search(r"^[^@]+@[^@]+$", email):
emails_list.append(email)
# remove public anonymous access
partner_list = []
for partner in wizard.partner_ids:
if not anonymous_id or not partner.user_ids or anonymous_id not in [x.id for x in partner.user_ids[0].groups_id]:
partner_list.append({'id': partner.id, 'email': partner.email})
if not len(emails_list) and not len(partner_list):
if wizard.model == 'res.partner' and wizard.res_id:
return False
raise osv.except_osv(_('Warning!'), _("Please enter at least one valid recipient."))
for email in emails_list:
partner_id = partner_obj.search(cr, uid, [('email', '=', email)], context=context)
partner_id = partner_id and partner_id[0] or None
token = create_token(wizard, partner_id, email)
create_response_and_send_mail(wizard, token, partner_id, email)
for partner in partner_list:
token = create_token(wizard, partner['id'], partner['email'])
create_response_and_send_mail(wizard, token, partner['id'], partner['email'])
return {'type': 'ir.actions.act_window_close'}
| agpl-3.0 |
paulcalabro/zato | code/zato-server/test/zato/server/connection/http_soap/test_outgoing.py | 5 | 24189 | # -*- coding: utf-8 -*-
"""
Copyright (C) 2013 Dariusz Suchojad <dsuch at zato.io>
Licensed under LGPLv3, see LICENSE.txt for terms and conditions.
"""
from __future__ import absolute_import, division, print_function, unicode_literals
# stdlib
import httplib, ssl
from datetime import datetime
from logging import getLogger
from tempfile import NamedTemporaryFile
from time import sleep
from unittest import TestCase
# bunch
from bunch import Bunch
# nose
from nose.tools import eq_
# requests
import requests
requests.packages.urllib3.disable_warnings()
# Zato
from zato.common import CONTENT_TYPE, DATA_FORMAT, SEC_DEF_TYPE, URL_TYPE, ZATO_NONE
from zato.common.util import get_component_name
from zato.common.test import rand_float, rand_int, rand_string
from zato.common.test.tls import TLSServer
from zato.common.test.tls_material import ca_cert, ca_cert_invalid, client1_cert, client1_key
from zato.server.connection.http_soap.outgoing import HTTPSOAPWrapper
logger = getLogger(__name__)
# ################################################################################################################################
class _FakeSession(object):
def __init__(self, *ignored, **kwargs):
self.pool_size = kwargs.get('pool_maxsize', 'missing')
self.request_args = None
self.request_kwargs = None
def request(self, *args, **kwargs):
self.request_args = args
self.request_kwargs = kwargs
return Bunch({'status_code':rand_string(), 'text':rand_string()})
def mount(self, *ignored):
pass
# ################################################################################################################################
class _FakeRequestsModule(object):
def __init__(self):
self.session_obj = None
def session(self, *args, **kwargs):
self.session_obj = _FakeSession(*args, **kwargs)
return self.session_obj
# ################################################################################################################################
class Base(object):
def _get_config(self):
return {'is_active':True, 'sec_type':rand_string(), 'address_host':rand_string(),
'address_url_path':rand_string(), 'ping_method':rand_string(), 'soap_version':'1.1',
'pool_size':rand_int(), 'serialization_type':'string', 'timeout':rand_int(),
'tls_verify':ZATO_NONE, 'data_format':'', 'content_type':''}
# ################################################################################################################################
class HTTPSOAPWrapperTestCase(TestCase, Base):
def test_ping_method(self):
""" https://github.com/zatosource/zato/issues/44 (outconn HTTP/SOAP ping method)
"""
config = self._get_config()
expected_ping_method = 'ping-{}'.format(rand_string())
config['ping_method'] = expected_ping_method
requests_module = _FakeRequestsModule()
wrapper = HTTPSOAPWrapper(config, requests_module)
wrapper.ping(rand_string())
ping_method = requests_module.session_obj.request_args[0]
eq_(expected_ping_method, ping_method)
def test_pool_size(self):
""" https://github.com/zatosource/zato/issues/77 (outconn HTTP/SOAP pool size)
"""
config = self._get_config()
expected_pool_size = rand_int()
config['pool_size'] = expected_pool_size
requests_module = _FakeRequestsModule()
wrapper = HTTPSOAPWrapper(config, requests_module)
wrapper.ping(rand_string())
eq_(expected_pool_size, requests_module.session_obj.pool_size)
def test_timeout(self):
""" https://github.com/zatosource/zato/issues/112 (HTTP timeouts)
"""
for name in 'ping', 'get', 'delete', 'options', 'post', 'send', 'put', 'patch':
for transport in URL_TYPE:
config = self._get_config()
config['transport'] = transport
expected_timeout = rand_float()
config['timeout'] = expected_timeout
requests_module = _FakeRequestsModule()
wrapper = HTTPSOAPWrapper(config, requests_module)
func = getattr(wrapper, name)
func(rand_string())
self.assertIn('timeout', requests_module.session_obj.request_kwargs)
eq_(expected_timeout, requests_module.session_obj.request_kwargs['timeout'])
def test_set_address(self):
address_host = rand_string()
config = self._get_config()
config['address_host'] = address_host
requests_module = _FakeRequestsModule()
for address_url_path in('/zzz', '/cust/{customer}/order/{order}/pid{process}/',):
config['address_url_path'] = address_url_path
wrapper = HTTPSOAPWrapper(config, requests_module)
eq_(wrapper.address, '{}{}'.format(address_host, address_url_path))
if address_url_path == '/zzz':
eq_(wrapper.path_params, [])
else:
eq_(wrapper.path_params, ['customer', 'order', 'process'])
def test_format_address(self):
cid = rand_string()
address_host = rand_string()
address_url_path = '/a/{a}/b{b}/c-{c}/{d}d/'
config = self._get_config()
config['address_host'] = address_host
config['address_url_path'] = address_url_path
requests_module = _FakeRequestsModule()
wrapper = HTTPSOAPWrapper(config, requests_module)
try:
wrapper.format_address(cid, None)
except ValueError, e:
eq_(e.message, 'CID:[{}] No parameters given for URL path'.format(cid))
else:
self.fail('Expected ValueError (params is None)')
a = rand_string()
b = rand_string()
c = rand_string()
d = rand_string()
e = rand_string()
f = rand_string()
params = {'a':a, 'b':b, 'c':c, 'd':d, 'e':e, 'f':f}
address, non_path_params = wrapper.format_address(cid, params)
eq_(address, '{}/a/{}/b{}/c-{}/{}d/'.format(address_host, a, b, c, d))
eq_(non_path_params, {'e':e, 'f':f})
params = {'a':a, 'b':b}
try:
address, non_path_params = wrapper.format_address(cid, params)
except ValueError, e:
eq_(e.message, 'CID:[{}] Could not build URL path'.format(cid))
else:
self.fail('Expected ValueError (not enough keys in params)')
def test_http_methods(self):
address_host = rand_string()
config = self._get_config()
config['is_active'] = True
config['soap_version'] = '1.2'
config['address_host'] = address_host
requests_module = _FakeRequestsModule()
wrapper = HTTPSOAPWrapper(config, requests_module)
for address_url_path in('/zzz', '/a/{a}/b/{b}'):
for transport in('soap', rand_string()):
for name in('get', 'delete', 'options', 'post', 'put', 'patch'):
config['transport'] = transport
_cid = rand_string()
_data = rand_string()
expected_http_request_value = rand_string()
expected_http_request_value = rand_string()
expected_params = rand_string()
expected_args1 = rand_string()
expected_args2 = rand_string()
expected_kwargs1 = rand_string()
expected_kwargs2 = rand_string()
def http_request(method, cid, data='', params=None, *args, **kwargs):
eq_(method, name.upper())
eq_(cid, _cid)
if name in('get', 'delete', 'options'):
eq_(data, '')
else:
eq_(data, _data)
eq_(params, expected_params)
eq_(args, (expected_args1, expected_args2))
eq_(sorted(kwargs.items()), [('bar', expected_kwargs2), ('foo', expected_kwargs1)])
return expected_http_request_value
def format_address(cid, params):
return expected_http_request_value
wrapper.http_request = http_request
wrapper.format_address = format_address
func = getattr(wrapper, name)
if name in('get', 'delete', 'options'):
http_request_value = func(
_cid, expected_params, expected_args1, expected_args2,
foo=expected_kwargs1, bar=expected_kwargs2)
else:
http_request_value = func(
_cid, _data, expected_params, expected_args1, expected_args2,
foo=expected_kwargs1, bar=expected_kwargs2)
eq_(http_request_value, expected_http_request_value)
def test_create_headers_json(self):
cid = rand_string()
now = datetime.utcnow().isoformat()
requests_module = _FakeRequestsModule()
config = self._get_config()
config['data_format'] = DATA_FORMAT.JSON
config['transport'] = URL_TYPE.PLAIN_HTTP
wrapper = HTTPSOAPWrapper(config, requests_module)
user_headers = {rand_string():rand_string(), rand_string():rand_string()}
headers = wrapper._create_headers(cid, user_headers, now)
eq_(headers.pop('X-Zato-CID'), cid)
eq_(headers.pop('X-Zato-Msg-TS'), now)
eq_(headers.pop('X-Zato-Component'), get_component_name())
eq_(headers.pop('Content-Type'), CONTENT_TYPE.JSON)
# Anything that is left must be user headers
self.assertDictEqual(headers, user_headers)
def test_create_headers_plain_xml(self):
cid = rand_string()
now = datetime.utcnow().isoformat()
requests_module = _FakeRequestsModule()
config = self._get_config()
config['data_format'] = DATA_FORMAT.XML
config['transport'] = URL_TYPE.PLAIN_HTTP
wrapper = HTTPSOAPWrapper(config, requests_module)
user_headers = {rand_string():rand_string(), rand_string():rand_string()}
headers = wrapper._create_headers(cid, user_headers, now)
eq_(headers.pop('X-Zato-CID'), cid)
eq_(headers.pop('X-Zato-Msg-TS'), now)
eq_(headers.pop('X-Zato-Component'), get_component_name())
eq_(headers.pop('Content-Type'), CONTENT_TYPE.PLAIN_XML)
# Anything that is left must be user headers
self.assertDictEqual(headers, user_headers)
def test_create_headers_soap11(self):
cid = rand_string()
now = datetime.utcnow().isoformat()
soap_action = rand_string()
requests_module = _FakeRequestsModule()
config = self._get_config()
config['data_format'] = DATA_FORMAT.XML
config['transport'] = URL_TYPE.SOAP
config['soap_action'] = soap_action
wrapper = HTTPSOAPWrapper(config, requests_module)
user_headers = {rand_string():rand_string(), rand_string():rand_string()}
headers = wrapper._create_headers(cid, user_headers, now)
eq_(headers.pop('X-Zato-CID'), cid)
eq_(headers.pop('X-Zato-Msg-TS'), now)
eq_(headers.pop('X-Zato-Component'), get_component_name())
eq_(headers.pop('SOAPAction'), soap_action)
eq_(headers.pop('Content-Type'), CONTENT_TYPE.SOAP11)
# Anything that is left must be user headers
self.assertDictEqual(headers, user_headers)
def test_create_headers_soap12(self):
cid = rand_string()
now = datetime.utcnow().isoformat()
soap_action = rand_string()
requests_module = _FakeRequestsModule()
config = self._get_config()
config['data_format'] = DATA_FORMAT.XML
config['transport'] = URL_TYPE.SOAP
config['soap_action'] = soap_action
config['soap_version'] = '1.2'
wrapper = HTTPSOAPWrapper(config, requests_module)
user_headers = {rand_string():rand_string(), rand_string():rand_string()}
headers = wrapper._create_headers(cid, user_headers, now)
eq_(headers.pop('X-Zato-CID'), cid)
eq_(headers.pop('X-Zato-Msg-TS'), now)
eq_(headers.pop('X-Zato-Component'), get_component_name())
eq_(headers.pop('SOAPAction'), soap_action)
eq_(headers.pop('Content-Type'), CONTENT_TYPE.SOAP12)
# Anything that is left must be user headers
self.assertDictEqual(headers, user_headers)
def test_create_headers_no_data_format(self):
cid = rand_string()
now = datetime.utcnow().isoformat()
requests_module = _FakeRequestsModule()
config = self._get_config()
wrapper = HTTPSOAPWrapper(config, requests_module)
user_headers = {rand_string():rand_string(), rand_string():rand_string()}
headers = wrapper._create_headers(cid, user_headers, now)
eq_(headers.pop('X-Zato-CID'), cid)
eq_(headers.pop('X-Zato-Msg-TS'), now)
eq_(headers.pop('X-Zato-Component'), get_component_name())
# Anything that is left must be user headers
# (note that there was no Content-Type because there was no data_format)
self.assertDictEqual(headers, user_headers)
def test_create_headers_user_default_data_format(self):
cid = rand_string()
now = datetime.utcnow().isoformat()
content_type = rand_string()
requests_module = _FakeRequestsModule()
config = self._get_config()
config['content_type'] = content_type
wrapper = HTTPSOAPWrapper(config, requests_module)
user_headers = {rand_string():rand_string(), rand_string():rand_string()}
headers = wrapper._create_headers(cid, user_headers, now)
eq_(headers.pop('X-Zato-CID'), cid)
eq_(headers.pop('X-Zato-Msg-TS'), now)
eq_(headers.pop('X-Zato-Component'), get_component_name())
eq_(headers.pop('Content-Type'), content_type)
# Anything that is left must be user headers
self.assertDictEqual(headers, user_headers)
def test_create_headers_user_headers_data_format(self):
cid = rand_string()
now = datetime.utcnow().isoformat()
content_type = rand_string()
requests_module = _FakeRequestsModule()
config = self._get_config()
wrapper = HTTPSOAPWrapper(config, requests_module)
user_headers = {rand_string():rand_string(), rand_string():rand_string(), 'Content-Type':content_type}
headers = wrapper._create_headers(cid, user_headers, now)
eq_(headers.pop('X-Zato-CID'), cid)
eq_(headers.pop('X-Zato-Msg-TS'), now)
eq_(headers.pop('X-Zato-Component'), get_component_name())
eq_(headers.pop('Content-Type'), content_type)
# Anything that is left must be user headers
self.assertDictEqual(headers, user_headers)
# ################################################################################################################################
class TLSPingTestCase(TestCase, Base):
def tearDown(self):
sleep(1) # So the server's thread can shut down cleanly
def test_ping_unknown_ca_verify_false(self):
server = TLSServer()
server.start()
sleep(0.3)
port = server.get_port()
config = self._get_config()
config['address_host'] = 'https://localhost:{}/'.format(port)
config['address_url_path'] = ''
config['ping_method'] = 'GET'
config['tls_verify'] = ZATO_NONE
wrapper = HTTPSOAPWrapper(config, requests)
self.assertIn('Code: 200', wrapper.ping(rand_string()))
def test_ping_unknown_ca_verify_invalid_ca_cert(self):
with NamedTemporaryFile(prefix='zato-tls', delete=False) as ca_cert_tf:
ca_cert_tf.write(ca_cert_invalid)
ca_cert_tf.flush()
server = TLSServer()
server.start()
sleep(1)
port = server.get_port()
config = self._get_config()
config['address_host'] = 'https://localhost:{}/'.format(port)
config['address_url_path'] = ''
config['ping_method'] = 'GET'
config['tls_verify'] = ca_cert_tf.name
wrapper = HTTPSOAPWrapper(config, requests)
try:
wrapper.ping(rand_string())
except Exception, e:
details = e.message[0][1][0][0]
self.assertEquals(details, ('SSL routines', 'SSL3_GET_SERVER_CERTIFICATE', 'certificate verify failed'))
else:
self.fail('Excepted a TLS error here because the CA is invalid')
def test_ping_client_cert_required_no_client_cert(self):
with NamedTemporaryFile(prefix='zato-tls', delete=False) as ca_cert_tf:
ca_cert_tf.write(ca_cert)
ca_cert_tf.flush()
server = TLSServer(cert_reqs=ssl.CERT_REQUIRED)
server.start()
sleep(0.3)
port = server.get_port()
config = self._get_config()
config['address_host'] = 'https://localhost:{}/'.format(port)
config['address_url_path'] = ''
config['ping_method'] = 'GET'
config['tls_verify'] = ca_cert_tf.name
wrapper = HTTPSOAPWrapper(config, requests)
try:
wrapper.ping(rand_string())
except Exception, e:
details = e.message[0][1][0][0]
self.assertEquals(details, ('SSL routines', 'SSL3_READ_BYTES', 'sslv3 alert handshake failure'))
else:
self.fail('Excepted a TLS error here because no TLS cert has been provided by client')
def test_ping_client_cert_required_has_client_cert(self):
with NamedTemporaryFile(prefix='zato-tls', delete=False) as ca_cert_tf:
ca_cert_tf.write(ca_cert)
ca_cert_tf.flush()
with NamedTemporaryFile(prefix='zato-tls', delete=False) as client_cert_tf:
client_cert_tf.write(client1_key)
client_cert_tf.write('\n')
client_cert_tf.write(client1_cert)
client_cert_tf.flush()
server = TLSServer(cert_reqs=ssl.CERT_REQUIRED)
server.start()
sleep(0.3)
port = server.get_port()
config = self._get_config()
config['address_host'] = 'https://localhost:{}/'.format(port)
config['address_url_path'] = ''
config['ping_method'] = 'GET'
config['tls_verify'] = ca_cert_tf.name
config['tls_key_cert_full_path'] = client_cert_tf.name
config['sec_type'] = SEC_DEF_TYPE.TLS_KEY_CERT
wrapper = HTTPSOAPWrapper(config, requests)
wrapper.ping(rand_string())
# ################################################################################################################################
class TLSHTTPTestCase(TestCase, Base):
def test_http_get_unknown_ca_verify_false(self):
server = TLSServer()
server.start()
sleep(0.3)
port = server.get_port()
config = self._get_config()
config['address_host'] = 'https://localhost:{}/'.format(port)
config['address_url_path'] = ''
config['ping_method'] = 'GET'
config['transport'] = URL_TYPE.PLAIN_HTTP
config['tls_verify'] = ZATO_NONE
wrapper = HTTPSOAPWrapper(config, requests)
self.assertEquals(httplib.OK, wrapper.get('123').status_code)
def test_http_get_unknown_ca_verify_invalid_ca_cert(self):
with NamedTemporaryFile(prefix='zato-tls', delete=False) as ca_cert_tf:
ca_cert_tf.write(ca_cert_invalid)
ca_cert_tf.flush()
server = TLSServer()
server.start()
sleep(0.3)
port = server.get_port()
config = self._get_config()
config['address_host'] = 'https://localhost:{}/'.format(port)
config['address_url_path'] = ''
config['ping_method'] = 'GET'
config['transport'] = URL_TYPE.PLAIN_HTTP
config['tls_verify'] = ca_cert_tf.name
wrapper = HTTPSOAPWrapper(config, requests)
try:
wrapper.get('123')
except Exception, e:
details = e.message[0][1][0][0]
self.assertEquals(details, ('SSL routines', 'SSL3_GET_SERVER_CERTIFICATE', 'certificate verify failed'))
else:
self.fail('Excepted a TLS error here because the CA is invalid')
def test_http_get_client_cert_required_no_client_cert(self):
with NamedTemporaryFile(prefix='zato-tls', delete=False) as ca_cert_tf:
ca_cert_tf.write(ca_cert)
ca_cert_tf.flush()
server = TLSServer(cert_reqs=ssl.CERT_REQUIRED)
server.start()
sleep(0.3)
port = server.get_port()
config = self._get_config()
config['address_host'] = 'https://localhost:{}/'.format(port)
config['address_url_path'] = ''
config['ping_method'] = 'GET'
config['transport'] = URL_TYPE.PLAIN_HTTP
config['tls_verify'] = ca_cert_tf.name
wrapper = HTTPSOAPWrapper(config, requests)
try:
wrapper.get('123')
except Exception, e:
details = e.message[0][1][0][0]
self.assertEquals(details, ('SSL routines', 'SSL3_READ_BYTES', 'sslv3 alert handshake failure'))
else:
self.fail('Excepted a TLS error here because no TLS cert has been provided by client')
def test_http_get_client_cert_required_has_client_cert(self):
with NamedTemporaryFile(prefix='zato-tls', delete=False) as ca_cert_tf:
ca_cert_tf.write(ca_cert)
ca_cert_tf.flush()
with NamedTemporaryFile(prefix='zato-tls', delete=False) as client_cert_tf:
client_cert_tf.write(client1_key)
client_cert_tf.write('\n')
client_cert_tf.write(client1_cert)
client_cert_tf.flush()
server = TLSServer(cert_reqs=ssl.CERT_REQUIRED)
server.start()
sleep(0.3)
port = server.get_port()
config = self._get_config()
config['ping_method'] = 'GET'
config['tls_verify'] = ca_cert_tf.name
config['tls_key_cert_full_path'] = client_cert_tf.name
config['sec_type'] = SEC_DEF_TYPE.TLS_KEY_CERT
config['address_host'] = 'https://localhost:{}/'.format(port)
uni_data = u'uni_data'
string_data = b'string_data'
needs_data = 'post', 'send', 'put', 'patch'
for url_type in URL_TYPE:
config['transport'] = url_type
for data_format in DATA_FORMAT:
config['data_format'] = data_format
for data in uni_data, string_data:
for name in('get', 'delete', 'options', 'post', 'send', 'put', 'patch'):
cid = '{}_{}'.format(name, data)
config['address_url_path'] = '{}-{}-{}'.format(url_type, data_format, data)
wrapper = HTTPSOAPWrapper(config, requests)
func = getattr(wrapper, name)
if name in needs_data:
func(cid, data=data)
else:
func(cid)
# ################################################################################################################################
| gpl-3.0 |
x2nie/odoo | openerp/modules/db.py | 442 | 6037 | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>).
# Copyright (C) 2010-2012 OpenERP s.a. (<http://openerp.com>).
#
# 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/>.
#
##############################################################################
import openerp.modules
import logging
_logger = logging.getLogger(__name__)
def is_initialized(cr):
""" Check if a database has been initialized for the ORM.
The database can be initialized with the 'initialize' function below.
"""
cr.execute("SELECT relname FROM pg_class WHERE relkind='r' AND relname='ir_module_module'")
return len(cr.fetchall()) > 0
def initialize(cr):
""" Initialize a database with for the ORM.
This executes base/base.sql, creates the ir_module_categories (taken
from each module descriptor file), and creates the ir_module_module
and ir_model_data entries.
"""
f = openerp.modules.get_module_resource('base', 'base.sql')
if not f:
m = "File not found: 'base.sql' (provided by module 'base')."
_logger.critical(m)
raise IOError(m)
base_sql_file = openerp.tools.misc.file_open(f)
try:
cr.execute(base_sql_file.read())
cr.commit()
finally:
base_sql_file.close()
for i in openerp.modules.get_modules():
mod_path = openerp.modules.get_module_path(i)
if not mod_path:
continue
# This will raise an exception if no/unreadable descriptor file.
info = openerp.modules.load_information_from_description_file(i)
if not info:
continue
categories = info['category'].split('/')
category_id = create_categories(cr, categories)
if info['installable']:
state = 'uninstalled'
else:
state = 'uninstallable'
cr.execute('INSERT INTO ir_module_module \
(author, website, name, shortdesc, description, \
category_id, auto_install, state, web, license, application, icon, sequence, summary) \
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s) RETURNING id', (
info['author'],
info['website'], i, info['name'],
info['description'], category_id,
info['auto_install'], state,
info['web'],
info['license'],
info['application'], info['icon'],
info['sequence'], info['summary']))
id = cr.fetchone()[0]
cr.execute('INSERT INTO ir_model_data \
(name,model,module, res_id, noupdate) VALUES (%s,%s,%s,%s,%s)', (
'module_'+i, 'ir.module.module', 'base', id, True))
dependencies = info['depends']
for d in dependencies:
cr.execute('INSERT INTO ir_module_module_dependency \
(module_id,name) VALUES (%s, %s)', (id, d))
# Install recursively all auto-installing modules
while True:
cr.execute("""SELECT m.name FROM ir_module_module m WHERE m.auto_install AND state != 'to install'
AND NOT EXISTS (
SELECT 1 FROM ir_module_module_dependency d JOIN ir_module_module mdep ON (d.name = mdep.name)
WHERE d.module_id = m.id AND mdep.state != 'to install'
)""")
to_auto_install = [x[0] for x in cr.fetchall()]
if not to_auto_install: break
cr.execute("""UPDATE ir_module_module SET state='to install' WHERE name in %s""", (tuple(to_auto_install),))
cr.commit()
def create_categories(cr, categories):
""" Create the ir_module_category entries for some categories.
categories is a list of strings forming a single category with its
parent categories, like ['Grand Parent', 'Parent', 'Child'].
Return the database id of the (last) category.
"""
p_id = None
category = []
while categories:
category.append(categories[0])
xml_id = 'module_category_' + ('_'.join(map(lambda x: x.lower(), category))).replace('&', 'and').replace(' ', '_')
# search via xml_id (because some categories are renamed)
cr.execute("SELECT res_id FROM ir_model_data WHERE name=%s AND module=%s AND model=%s",
(xml_id, "base", "ir.module.category"))
c_id = cr.fetchone()
if not c_id:
cr.execute('INSERT INTO ir_module_category \
(name, parent_id) \
VALUES (%s, %s) RETURNING id', (categories[0], p_id))
c_id = cr.fetchone()[0]
cr.execute('INSERT INTO ir_model_data (module, name, res_id, model) \
VALUES (%s, %s, %s, %s)', ('base', xml_id, c_id, 'ir.module.category'))
else:
c_id = c_id[0]
p_id = c_id
categories = categories[1:]
return p_id
def has_unaccent(cr):
""" Test if the database has an unaccent function.
The unaccent is supposed to be provided by the PostgreSQL unaccent contrib
module but any similar function will be picked by OpenERP.
"""
cr.execute("SELECT proname FROM pg_proc WHERE proname='unaccent'")
return len(cr.fetchall()) > 0
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
| agpl-3.0 |
zstackio/zstack-woodpecker | integrationtest/vm/perf/vm/test_reboot_vm_simple_scheduler_with_max_threads.py | 2 | 1675 | '''
New Perf Test for rebooting KVM VMs which were stopped.
The reboot number will depend on the environment variable: ZSTACK_TEST_NUM
This case's max thread is 1000
@author: Carl
'''
import os
import time
import zstackwoodpecker.operations.resource_operations as res_ops
import zstackwoodpecker.test_lib as test_lib
from test_stub import *
global reboot_date
global vm_stat_flag
class Reboot_VM_Simple_Scheduler_Parall(VM_Operation_Parall):
date=int(time.time())
def operate_vm_parall(self, vm_uuid):
try:
vm_ops.reboot_vm_scheduler(vm_uuid, 'simple', 'simple_reboot_vm_scheduler', 0, 1, 1)
except:
self.exc_info.append(sys.exc_info())
def check_operation_result(self):
time.sleep(30)
start_msg_mismatch = 1
for k in range(0, 100):
for i in range(0, self.i):
vm_stat_flag=0
if not test_lib.lib_find_in_local_management_server_log(self.date+k, '[msg send]: {"org.zstack.header.vm.RebootVmInstanceMsg', self.vms[i].uuid):
test_util.test_warn('RebootVmInstanceMsg is expected to execute at %s' % (self.date+k))
vm_stat_flag=1
start_msg_mismatch += 1
if vm_stat_flag == 0:
break
if start_msg_mismatch > 1000:
test_util.test_fail('%s of 1000 RebootVmInstanceMsg not executed at expected timestamp' % (start_msg_mismatch))
def test():
get_vm_con = res_ops.gen_query_conditions('state', '=', "Running")
rebootvms = Reboot_VM_Simple_Scheduler_Parall(get_vm_con, "Running")
rebootvms.parall_test_run()
rebootvms.check_operation_result()
| apache-2.0 |
karlnapf/shogun | examples/undocumented/python/kernel_comm_word_string.py | 4 | 1411 | #!/usr/bin/env python
from tools.load import LoadMatrix
import shogun as sg
lm=LoadMatrix()
traindat = lm.load_dna('../data/fm_train_dna.dat')
testdat = lm.load_dna('../data/fm_test_dna.dat')
parameter_list = [[traindat,testdat,4,0,False, False],[traindat,testdat,4,0,False,False]]
def kernel_comm_word_string (fm_train_dna=traindat, fm_test_dna=testdat, order=3, gap=0, reverse = False, use_sign = False):
from shogun import CommWordStringKernel
from shogun import StringWordFeatures, StringCharFeatures, DNA
charfeat=StringCharFeatures(DNA)
charfeat.set_features(fm_train_dna)
feats_train=StringWordFeatures(charfeat.get_alphabet())
feats_train.obtain_from_char(charfeat, order-1, order, gap, reverse)
preproc = sg.transformer("SortWordString")
preproc.fit(feats_train)
feats_train = preproc.transform(feats_train)
charfeat=StringCharFeatures(DNA)
charfeat.set_features(fm_test_dna)
feats_test=StringWordFeatures(charfeat.get_alphabet())
feats_test.obtain_from_char(charfeat, order-1, order, gap, reverse)
feats_test = preproc.transform(feats_test)
kernel=sg.kernel("CommWordStringKernel", use_sign=use_sign)
kernel.init(feats_train, feats_train)
km_train=kernel.get_kernel_matrix()
kernel.init(feats_train, feats_test)
km_test=kernel.get_kernel_matrix()
return km_train,km_test,kernel
if __name__=='__main__':
print('CommWordString')
kernel_comm_word_string(*parameter_list[0])
| bsd-3-clause |
OsirisSPS/osiris-sps | client/share/plugins/AF9A4C281070FDB0F34CF417CDB168AB38C8A388/lib/encodings/cp1026.py | 593 | 13369 | """ Python Character Mapping Codec cp1026 generated from 'MAPPINGS/VENDORS/MICSFT/EBCDIC/CP1026.TXT' with gencodec.py.
"""#"
import codecs
### Codec APIs
class Codec(codecs.Codec):
def encode(self,input,errors='strict'):
return codecs.charmap_encode(input,errors,encoding_table)
def decode(self,input,errors='strict'):
return codecs.charmap_decode(input,errors,decoding_table)
class IncrementalEncoder(codecs.IncrementalEncoder):
def encode(self, input, final=False):
return codecs.charmap_encode(input,self.errors,encoding_table)[0]
class IncrementalDecoder(codecs.IncrementalDecoder):
def decode(self, input, final=False):
return codecs.charmap_decode(input,self.errors,decoding_table)[0]
class StreamWriter(Codec,codecs.StreamWriter):
pass
class StreamReader(Codec,codecs.StreamReader):
pass
### encodings module API
def getregentry():
return codecs.CodecInfo(
name='cp1026',
encode=Codec().encode,
decode=Codec().decode,
incrementalencoder=IncrementalEncoder,
incrementaldecoder=IncrementalDecoder,
streamreader=StreamReader,
streamwriter=StreamWriter,
)
### Decoding Table
decoding_table = (
u'\x00' # 0x00 -> NULL
u'\x01' # 0x01 -> START OF HEADING
u'\x02' # 0x02 -> START OF TEXT
u'\x03' # 0x03 -> END OF TEXT
u'\x9c' # 0x04 -> CONTROL
u'\t' # 0x05 -> HORIZONTAL TABULATION
u'\x86' # 0x06 -> CONTROL
u'\x7f' # 0x07 -> DELETE
u'\x97' # 0x08 -> CONTROL
u'\x8d' # 0x09 -> CONTROL
u'\x8e' # 0x0A -> CONTROL
u'\x0b' # 0x0B -> VERTICAL TABULATION
u'\x0c' # 0x0C -> FORM FEED
u'\r' # 0x0D -> CARRIAGE RETURN
u'\x0e' # 0x0E -> SHIFT OUT
u'\x0f' # 0x0F -> SHIFT IN
u'\x10' # 0x10 -> DATA LINK ESCAPE
u'\x11' # 0x11 -> DEVICE CONTROL ONE
u'\x12' # 0x12 -> DEVICE CONTROL TWO
u'\x13' # 0x13 -> DEVICE CONTROL THREE
u'\x9d' # 0x14 -> CONTROL
u'\x85' # 0x15 -> CONTROL
u'\x08' # 0x16 -> BACKSPACE
u'\x87' # 0x17 -> CONTROL
u'\x18' # 0x18 -> CANCEL
u'\x19' # 0x19 -> END OF MEDIUM
u'\x92' # 0x1A -> CONTROL
u'\x8f' # 0x1B -> CONTROL
u'\x1c' # 0x1C -> FILE SEPARATOR
u'\x1d' # 0x1D -> GROUP SEPARATOR
u'\x1e' # 0x1E -> RECORD SEPARATOR
u'\x1f' # 0x1F -> UNIT SEPARATOR
u'\x80' # 0x20 -> CONTROL
u'\x81' # 0x21 -> CONTROL
u'\x82' # 0x22 -> CONTROL
u'\x83' # 0x23 -> CONTROL
u'\x84' # 0x24 -> CONTROL
u'\n' # 0x25 -> LINE FEED
u'\x17' # 0x26 -> END OF TRANSMISSION BLOCK
u'\x1b' # 0x27 -> ESCAPE
u'\x88' # 0x28 -> CONTROL
u'\x89' # 0x29 -> CONTROL
u'\x8a' # 0x2A -> CONTROL
u'\x8b' # 0x2B -> CONTROL
u'\x8c' # 0x2C -> CONTROL
u'\x05' # 0x2D -> ENQUIRY
u'\x06' # 0x2E -> ACKNOWLEDGE
u'\x07' # 0x2F -> BELL
u'\x90' # 0x30 -> CONTROL
u'\x91' # 0x31 -> CONTROL
u'\x16' # 0x32 -> SYNCHRONOUS IDLE
u'\x93' # 0x33 -> CONTROL
u'\x94' # 0x34 -> CONTROL
u'\x95' # 0x35 -> CONTROL
u'\x96' # 0x36 -> CONTROL
u'\x04' # 0x37 -> END OF TRANSMISSION
u'\x98' # 0x38 -> CONTROL
u'\x99' # 0x39 -> CONTROL
u'\x9a' # 0x3A -> CONTROL
u'\x9b' # 0x3B -> CONTROL
u'\x14' # 0x3C -> DEVICE CONTROL FOUR
u'\x15' # 0x3D -> NEGATIVE ACKNOWLEDGE
u'\x9e' # 0x3E -> CONTROL
u'\x1a' # 0x3F -> SUBSTITUTE
u' ' # 0x40 -> SPACE
u'\xa0' # 0x41 -> NO-BREAK SPACE
u'\xe2' # 0x42 -> LATIN SMALL LETTER A WITH CIRCUMFLEX
u'\xe4' # 0x43 -> LATIN SMALL LETTER A WITH DIAERESIS
u'\xe0' # 0x44 -> LATIN SMALL LETTER A WITH GRAVE
u'\xe1' # 0x45 -> LATIN SMALL LETTER A WITH ACUTE
u'\xe3' # 0x46 -> LATIN SMALL LETTER A WITH TILDE
u'\xe5' # 0x47 -> LATIN SMALL LETTER A WITH RING ABOVE
u'{' # 0x48 -> LEFT CURLY BRACKET
u'\xf1' # 0x49 -> LATIN SMALL LETTER N WITH TILDE
u'\xc7' # 0x4A -> LATIN CAPITAL LETTER C WITH CEDILLA
u'.' # 0x4B -> FULL STOP
u'<' # 0x4C -> LESS-THAN SIGN
u'(' # 0x4D -> LEFT PARENTHESIS
u'+' # 0x4E -> PLUS SIGN
u'!' # 0x4F -> EXCLAMATION MARK
u'&' # 0x50 -> AMPERSAND
u'\xe9' # 0x51 -> LATIN SMALL LETTER E WITH ACUTE
u'\xea' # 0x52 -> LATIN SMALL LETTER E WITH CIRCUMFLEX
u'\xeb' # 0x53 -> LATIN SMALL LETTER E WITH DIAERESIS
u'\xe8' # 0x54 -> LATIN SMALL LETTER E WITH GRAVE
u'\xed' # 0x55 -> LATIN SMALL LETTER I WITH ACUTE
u'\xee' # 0x56 -> LATIN SMALL LETTER I WITH CIRCUMFLEX
u'\xef' # 0x57 -> LATIN SMALL LETTER I WITH DIAERESIS
u'\xec' # 0x58 -> LATIN SMALL LETTER I WITH GRAVE
u'\xdf' # 0x59 -> LATIN SMALL LETTER SHARP S (GERMAN)
u'\u011e' # 0x5A -> LATIN CAPITAL LETTER G WITH BREVE
u'\u0130' # 0x5B -> LATIN CAPITAL LETTER I WITH DOT ABOVE
u'*' # 0x5C -> ASTERISK
u')' # 0x5D -> RIGHT PARENTHESIS
u';' # 0x5E -> SEMICOLON
u'^' # 0x5F -> CIRCUMFLEX ACCENT
u'-' # 0x60 -> HYPHEN-MINUS
u'/' # 0x61 -> SOLIDUS
u'\xc2' # 0x62 -> LATIN CAPITAL LETTER A WITH CIRCUMFLEX
u'\xc4' # 0x63 -> LATIN CAPITAL LETTER A WITH DIAERESIS
u'\xc0' # 0x64 -> LATIN CAPITAL LETTER A WITH GRAVE
u'\xc1' # 0x65 -> LATIN CAPITAL LETTER A WITH ACUTE
u'\xc3' # 0x66 -> LATIN CAPITAL LETTER A WITH TILDE
u'\xc5' # 0x67 -> LATIN CAPITAL LETTER A WITH RING ABOVE
u'[' # 0x68 -> LEFT SQUARE BRACKET
u'\xd1' # 0x69 -> LATIN CAPITAL LETTER N WITH TILDE
u'\u015f' # 0x6A -> LATIN SMALL LETTER S WITH CEDILLA
u',' # 0x6B -> COMMA
u'%' # 0x6C -> PERCENT SIGN
u'_' # 0x6D -> LOW LINE
u'>' # 0x6E -> GREATER-THAN SIGN
u'?' # 0x6F -> QUESTION MARK
u'\xf8' # 0x70 -> LATIN SMALL LETTER O WITH STROKE
u'\xc9' # 0x71 -> LATIN CAPITAL LETTER E WITH ACUTE
u'\xca' # 0x72 -> LATIN CAPITAL LETTER E WITH CIRCUMFLEX
u'\xcb' # 0x73 -> LATIN CAPITAL LETTER E WITH DIAERESIS
u'\xc8' # 0x74 -> LATIN CAPITAL LETTER E WITH GRAVE
u'\xcd' # 0x75 -> LATIN CAPITAL LETTER I WITH ACUTE
u'\xce' # 0x76 -> LATIN CAPITAL LETTER I WITH CIRCUMFLEX
u'\xcf' # 0x77 -> LATIN CAPITAL LETTER I WITH DIAERESIS
u'\xcc' # 0x78 -> LATIN CAPITAL LETTER I WITH GRAVE
u'\u0131' # 0x79 -> LATIN SMALL LETTER DOTLESS I
u':' # 0x7A -> COLON
u'\xd6' # 0x7B -> LATIN CAPITAL LETTER O WITH DIAERESIS
u'\u015e' # 0x7C -> LATIN CAPITAL LETTER S WITH CEDILLA
u"'" # 0x7D -> APOSTROPHE
u'=' # 0x7E -> EQUALS SIGN
u'\xdc' # 0x7F -> LATIN CAPITAL LETTER U WITH DIAERESIS
u'\xd8' # 0x80 -> LATIN CAPITAL LETTER O WITH STROKE
u'a' # 0x81 -> LATIN SMALL LETTER A
u'b' # 0x82 -> LATIN SMALL LETTER B
u'c' # 0x83 -> LATIN SMALL LETTER C
u'd' # 0x84 -> LATIN SMALL LETTER D
u'e' # 0x85 -> LATIN SMALL LETTER E
u'f' # 0x86 -> LATIN SMALL LETTER F
u'g' # 0x87 -> LATIN SMALL LETTER G
u'h' # 0x88 -> LATIN SMALL LETTER H
u'i' # 0x89 -> LATIN SMALL LETTER I
u'\xab' # 0x8A -> LEFT-POINTING DOUBLE ANGLE QUOTATION MARK
u'\xbb' # 0x8B -> RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK
u'}' # 0x8C -> RIGHT CURLY BRACKET
u'`' # 0x8D -> GRAVE ACCENT
u'\xa6' # 0x8E -> BROKEN BAR
u'\xb1' # 0x8F -> PLUS-MINUS SIGN
u'\xb0' # 0x90 -> DEGREE SIGN
u'j' # 0x91 -> LATIN SMALL LETTER J
u'k' # 0x92 -> LATIN SMALL LETTER K
u'l' # 0x93 -> LATIN SMALL LETTER L
u'm' # 0x94 -> LATIN SMALL LETTER M
u'n' # 0x95 -> LATIN SMALL LETTER N
u'o' # 0x96 -> LATIN SMALL LETTER O
u'p' # 0x97 -> LATIN SMALL LETTER P
u'q' # 0x98 -> LATIN SMALL LETTER Q
u'r' # 0x99 -> LATIN SMALL LETTER R
u'\xaa' # 0x9A -> FEMININE ORDINAL INDICATOR
u'\xba' # 0x9B -> MASCULINE ORDINAL INDICATOR
u'\xe6' # 0x9C -> LATIN SMALL LIGATURE AE
u'\xb8' # 0x9D -> CEDILLA
u'\xc6' # 0x9E -> LATIN CAPITAL LIGATURE AE
u'\xa4' # 0x9F -> CURRENCY SIGN
u'\xb5' # 0xA0 -> MICRO SIGN
u'\xf6' # 0xA1 -> LATIN SMALL LETTER O WITH DIAERESIS
u's' # 0xA2 -> LATIN SMALL LETTER S
u't' # 0xA3 -> LATIN SMALL LETTER T
u'u' # 0xA4 -> LATIN SMALL LETTER U
u'v' # 0xA5 -> LATIN SMALL LETTER V
u'w' # 0xA6 -> LATIN SMALL LETTER W
u'x' # 0xA7 -> LATIN SMALL LETTER X
u'y' # 0xA8 -> LATIN SMALL LETTER Y
u'z' # 0xA9 -> LATIN SMALL LETTER Z
u'\xa1' # 0xAA -> INVERTED EXCLAMATION MARK
u'\xbf' # 0xAB -> INVERTED QUESTION MARK
u']' # 0xAC -> RIGHT SQUARE BRACKET
u'$' # 0xAD -> DOLLAR SIGN
u'@' # 0xAE -> COMMERCIAL AT
u'\xae' # 0xAF -> REGISTERED SIGN
u'\xa2' # 0xB0 -> CENT SIGN
u'\xa3' # 0xB1 -> POUND SIGN
u'\xa5' # 0xB2 -> YEN SIGN
u'\xb7' # 0xB3 -> MIDDLE DOT
u'\xa9' # 0xB4 -> COPYRIGHT SIGN
u'\xa7' # 0xB5 -> SECTION SIGN
u'\xb6' # 0xB6 -> PILCROW SIGN
u'\xbc' # 0xB7 -> VULGAR FRACTION ONE QUARTER
u'\xbd' # 0xB8 -> VULGAR FRACTION ONE HALF
u'\xbe' # 0xB9 -> VULGAR FRACTION THREE QUARTERS
u'\xac' # 0xBA -> NOT SIGN
u'|' # 0xBB -> VERTICAL LINE
u'\xaf' # 0xBC -> MACRON
u'\xa8' # 0xBD -> DIAERESIS
u'\xb4' # 0xBE -> ACUTE ACCENT
u'\xd7' # 0xBF -> MULTIPLICATION SIGN
u'\xe7' # 0xC0 -> LATIN SMALL LETTER C WITH CEDILLA
u'A' # 0xC1 -> LATIN CAPITAL LETTER A
u'B' # 0xC2 -> LATIN CAPITAL LETTER B
u'C' # 0xC3 -> LATIN CAPITAL LETTER C
u'D' # 0xC4 -> LATIN CAPITAL LETTER D
u'E' # 0xC5 -> LATIN CAPITAL LETTER E
u'F' # 0xC6 -> LATIN CAPITAL LETTER F
u'G' # 0xC7 -> LATIN CAPITAL LETTER G
u'H' # 0xC8 -> LATIN CAPITAL LETTER H
u'I' # 0xC9 -> LATIN CAPITAL LETTER I
u'\xad' # 0xCA -> SOFT HYPHEN
u'\xf4' # 0xCB -> LATIN SMALL LETTER O WITH CIRCUMFLEX
u'~' # 0xCC -> TILDE
u'\xf2' # 0xCD -> LATIN SMALL LETTER O WITH GRAVE
u'\xf3' # 0xCE -> LATIN SMALL LETTER O WITH ACUTE
u'\xf5' # 0xCF -> LATIN SMALL LETTER O WITH TILDE
u'\u011f' # 0xD0 -> LATIN SMALL LETTER G WITH BREVE
u'J' # 0xD1 -> LATIN CAPITAL LETTER J
u'K' # 0xD2 -> LATIN CAPITAL LETTER K
u'L' # 0xD3 -> LATIN CAPITAL LETTER L
u'M' # 0xD4 -> LATIN CAPITAL LETTER M
u'N' # 0xD5 -> LATIN CAPITAL LETTER N
u'O' # 0xD6 -> LATIN CAPITAL LETTER O
u'P' # 0xD7 -> LATIN CAPITAL LETTER P
u'Q' # 0xD8 -> LATIN CAPITAL LETTER Q
u'R' # 0xD9 -> LATIN CAPITAL LETTER R
u'\xb9' # 0xDA -> SUPERSCRIPT ONE
u'\xfb' # 0xDB -> LATIN SMALL LETTER U WITH CIRCUMFLEX
u'\\' # 0xDC -> REVERSE SOLIDUS
u'\xf9' # 0xDD -> LATIN SMALL LETTER U WITH GRAVE
u'\xfa' # 0xDE -> LATIN SMALL LETTER U WITH ACUTE
u'\xff' # 0xDF -> LATIN SMALL LETTER Y WITH DIAERESIS
u'\xfc' # 0xE0 -> LATIN SMALL LETTER U WITH DIAERESIS
u'\xf7' # 0xE1 -> DIVISION SIGN
u'S' # 0xE2 -> LATIN CAPITAL LETTER S
u'T' # 0xE3 -> LATIN CAPITAL LETTER T
u'U' # 0xE4 -> LATIN CAPITAL LETTER U
u'V' # 0xE5 -> LATIN CAPITAL LETTER V
u'W' # 0xE6 -> LATIN CAPITAL LETTER W
u'X' # 0xE7 -> LATIN CAPITAL LETTER X
u'Y' # 0xE8 -> LATIN CAPITAL LETTER Y
u'Z' # 0xE9 -> LATIN CAPITAL LETTER Z
u'\xb2' # 0xEA -> SUPERSCRIPT TWO
u'\xd4' # 0xEB -> LATIN CAPITAL LETTER O WITH CIRCUMFLEX
u'#' # 0xEC -> NUMBER SIGN
u'\xd2' # 0xED -> LATIN CAPITAL LETTER O WITH GRAVE
u'\xd3' # 0xEE -> LATIN CAPITAL LETTER O WITH ACUTE
u'\xd5' # 0xEF -> LATIN CAPITAL LETTER O WITH TILDE
u'0' # 0xF0 -> DIGIT ZERO
u'1' # 0xF1 -> DIGIT ONE
u'2' # 0xF2 -> DIGIT TWO
u'3' # 0xF3 -> DIGIT THREE
u'4' # 0xF4 -> DIGIT FOUR
u'5' # 0xF5 -> DIGIT FIVE
u'6' # 0xF6 -> DIGIT SIX
u'7' # 0xF7 -> DIGIT SEVEN
u'8' # 0xF8 -> DIGIT EIGHT
u'9' # 0xF9 -> DIGIT NINE
u'\xb3' # 0xFA -> SUPERSCRIPT THREE
u'\xdb' # 0xFB -> LATIN CAPITAL LETTER U WITH CIRCUMFLEX
u'"' # 0xFC -> QUOTATION MARK
u'\xd9' # 0xFD -> LATIN CAPITAL LETTER U WITH GRAVE
u'\xda' # 0xFE -> LATIN CAPITAL LETTER U WITH ACUTE
u'\x9f' # 0xFF -> CONTROL
)
### Encoding table
encoding_table=codecs.charmap_build(decoding_table)
| gpl-3.0 |
Leblantoine/nanocloud | photon/merge_libs_wrapper.py | 5 | 5944 | import os
import sys
import vs_toolchain
if sys.platform == 'win32':
vs_toolchain.GetToolchainDir()
os.environ['PATH'] += os.pathsep + os.environ['GYP_MSVS_OVERRIDE_PATH'] + '\\VC\\bin'
#!/usr/bin/env python
# Copyright (c) 2011 The WebRTC project authors. All Rights Reserved.
#
# Use of this source code is governed by a BSD-style license
# that can be found in the LICENSE file in the root of the source
# tree. An additional intellectual property rights grant can be found
# in the file PATENTS. All contributing project authors may
# be found in the AUTHORS file in the root of the source tree.
# Searches for libraries or object files on the specified path and merges them
# them into a single library. Assumes ninja is used on all platforms.
import fnmatch
import os
import subprocess
import sys
IGNORE_PATTERNS = ['do_not_use', 'protoc', 'genperf']
def FindFiles(path, pattern):
"""Finds files matching |pattern| under |path|.
Returns a list of file paths matching |pattern|, by walking the directory tree
under |path|. Filenames containing the string 'do_not_use' or 'protoc' are
excluded.
Args:
path: The root path for the search.
pattern: A shell-style wildcard pattern to match filenames against.
(e.g. '*.a')
Returns:
A list of file paths, relative to the current working directory.
"""
files = []
for root, _, filenames in os.walk(path):
for filename in fnmatch.filter(filenames, pattern):
if all(pattern not in filename for pattern in IGNORE_PATTERNS):
# We use the relative path here to avoid "argument list too
# long" errors on Linux. Note: This doesn't always work, so
# we use the find command on Linux.
files.append(os.path.relpath(os.path.join(root, filename)))
return files
def main(argv):
if len(argv) != 3:
sys.stderr.write('Usage: ' + argv[0] + ' <search_path> <output_lib>\n')
return 1
search_path = os.path.normpath(argv[1])
output_lib = os.path.normpath(argv[2])
if not os.path.exists(search_path):
sys.stderr.write('search_path does not exist: %s\n' % search_path)
return 1
if os.path.isfile(output_lib):
os.remove(output_lib)
if sys.platform.startswith('linux'):
pattern = '*.o'
cmd = 'ar crs'
elif sys.platform == 'darwin':
pattern = '*.a'
cmd = 'libtool -static -v -o '
elif sys.platform == 'win32':
pattern = '*.lib'
cmd = 'lib /OUT:'
else:
sys.stderr.write('Platform not supported: %r\n\n' % sys.platform)
return 1
if sys.platform.startswith('linux'):
cmd = ' '.join(['find', search_path, '-name "' + pattern + '"' +
' -and -not -name ' +
' -and -not -name '.join(IGNORE_PATTERNS) +
' -exec', cmd, output_lib, '{} +'])
else:
cmd = ' '.join([cmd + output_lib] + FindFiles(search_path, pattern))
if sys.platform == 'win32':
cmd += ' src/out/Default/obj/third_party/libvpx/libvpx_intrinsics_avx/vp9_diamond_search_sad_avx.obj src/out/Default/obj/third_party/libvpx/libvpx_intrinsics_avx2/fwd_txfm_avx2.obj src/out/Default/obj/third_party/libvpx/libvpx_intrinsics_avx2/loopfilter_avx2.obj src/out/Default/obj/third_party/libvpx/libvpx_intrinsics_avx2/sad4d_avx2.obj src/out/Default/obj/third_party/libvpx/libvpx_intrinsics_avx2/sad_avx2.obj src/out/Default/obj/third_party/libvpx/libvpx_intrinsics_avx2/variance_avx2.obj src/out/Default/obj/third_party/libvpx/libvpx_intrinsics_avx2/variance_impl_avx2.obj src/out/Default/obj/third_party/libvpx/libvpx_intrinsics_avx2/vp9_error_intrin_avx2.obj src/out/Default/obj/third_party/libvpx/libvpx_intrinsics_avx2/vpx_subpixel_8t_intrin_avx2.obj src/out/Default/obj/third_party/libvpx/libvpx_intrinsics_mmx/idct_blk_mmx.obj src/out/Default/obj/third_party/libvpx/libvpx_intrinsics_mmx/vp8_enc_stubs_mmx.obj src/out/Default/obj/third_party/libvpx/libvpx_intrinsics_sse2/avg_intrin_sse2.obj src/out/Default/obj/third_party/libvpx/libvpx_intrinsics_sse2/denoising_sse2.obj src/out/Default/obj/third_party/libvpx/libvpx_intrinsics_sse2/fwd_txfm_sse2.obj src/out/Default/obj/third_party/libvpx/libvpx_intrinsics_sse2/highbd_loopfilter_sse2.obj src/out/Default/obj/third_party/libvpx/libvpx_intrinsics_sse2/highbd_quantize_intrin_sse2.obj src/out/Default/obj/third_party/libvpx/libvpx_intrinsics_sse2/highbd_variance_sse2.obj src/out/Default/obj/third_party/libvpx/libvpx_intrinsics_sse2/idct_blk_sse2.obj src/out/Default/obj/third_party/libvpx/libvpx_intrinsics_sse2/inv_txfm_sse2.obj src/out/Default/obj/third_party/libvpx/libvpx_intrinsics_sse2/loopfilter_sse2.obj src/out/Default/obj/third_party/libvpx/libvpx_intrinsics_sse2/quantize_sse2.obj src/out/Default/obj/third_party/libvpx/libvpx_intrinsics_sse2/sum_squares_sse2.obj src/out/Default/obj/third_party/libvpx/libvpx_intrinsics_sse2/variance_sse2.obj src/out/Default/obj/third_party/libvpx/libvpx_intrinsics_sse2/vp8_enc_stubs_sse2.obj src/out/Default/obj/third_party/libvpx/libvpx_intrinsics_sse2/vp8_quantize_sse2.obj src/out/Default/obj/third_party/libvpx/libvpx_intrinsics_sse2/vp9_dct_intrin_sse2.obj src/out/Default/obj/third_party/libvpx/libvpx_intrinsics_sse2/vp9_denoiser_sse2.obj src/out/Default/obj/third_party/libvpx/libvpx_intrinsics_sse2/vp9_highbd_block_error_intrin_sse2.obj src/out/Default/obj/third_party/libvpx/libvpx_intrinsics_sse2/vp9_idct_intrin_sse2.obj src/out/Default/obj/third_party/libvpx/libvpx_intrinsics_sse2/vp9_quantize_sse2.obj src/out/Default/obj/third_party/libvpx/libvpx_intrinsics_sse4_1/quantize_sse4.obj src/out/Default/obj/third_party/libvpx/libvpx_intrinsics_ssse3/quantize_ssse3.obj src/out/Default/obj/third_party/libvpx/libvpx_intrinsics_ssse3/vp9_dct_ssse3.obj src/out/Default/obj/third_party/libvpx/libvpx_intrinsics_ssse3/vpx_subpixel_8t_intrin_ssse3.obj'
print cmd
subprocess.check_call(cmd, shell=True)
return 0
if __name__ == '__main__':
sys.exit(main(sys.argv))
| agpl-3.0 |
jay-johnson/kubernetes | cluster/juju/charms/trusty/kubernetes-master/hooks/setup.py | 149 | 1410 | #!/usr/bin/env python
# Copyright 2015 The Kubernetes 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.
def pre_install():
"""
Do any setup required before the install hook.
"""
install_charmhelpers()
install_path()
def install_charmhelpers():
"""
Install the charmhelpers library, if not present.
"""
try:
import charmhelpers # noqa
except ImportError:
import subprocess
subprocess.check_call(['apt-get', 'install', '-y', 'python-pip'])
subprocess.check_call(['pip', 'install', 'charmhelpers'])
def install_path():
"""
Install the path.py library, when not present.
"""
try:
import path # noqa
except ImportError:
import subprocess
subprocess.check_call(['apt-get', 'install', '-y', 'python-pip'])
subprocess.check_call(['pip', 'install', 'path.py'])
| apache-2.0 |
margamanterola/Cinnamon | files/usr/share/cinnamon/cinnamon-settings/bin/tweenEquations.py | 16 | 7813 | """
made with the file cjs/tweener/equations.js
Original copyright notice of the source file:
Copyright 2008 litl, LLC.
Equations
Main equations for the Tweener class
@author Zeh Fernando, Nate Chatellier
@version 1.0.2
Disclaimer for Robert Penner's Easing Equations license:
TERMS OF USE - EASING EQUATIONS
Open source under the BSD License.
Copyright (c) 2001 Robert Penner
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of 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.
TWEENING EQUATIONS functions
(the original equations are Robert Penner's work as mentioned on the disclaimer)
"""
import math
def easeNone(t, b, c, d):
return c * t / d + b
def easeInQuad(t, b, c, d):
t /= d
return c * t * t + b
def easeOutQuad(t, b, c, d):
t /= d
return -c * t * (t - 2) + b
def easeInOutQuad(t, b, c, d):
t /= d / 2
if t < 1:
return c / 2 * t * t + b
t -= 1
return -c / 2 * (t * (t - 2) - 1) + b
def easeOutInQuad(t, b, c, d):
if t < d / 2:
return easeOutQuad(t * 2, b, c / 2, d)
return easeInQuad((t * 2) - d, b + c / 2, c / 2, d)
def easeInCubic(t, b, c, d):
t /= d
return c * t ** 3 + b
def easeOutCubic(t, b, c, d):
t = t / d - 1
return c * (t ** 3 + 1) + b
def easeInOutCubic(t, b, c, d):
t /= d / 2
if t < 1:
return c / 2 * t ** 3 + b
t -= 2
return c / 2 * (t ** 3 + 2) + b
def easeOutInCubic(t, b, c, d):
if t < d / 2:
return easeOutCubic (t * 2, b, c / 2, d)
return easeInCubic((t * 2) - d, b + c / 2, c / 2, d)
def easeInQuart(t, b, c, d):
t /= d
return c * t ** 4 + b
def easeOutQuart(t, b, c, d):
t = t / d - 1
return -c * (t ** 4 - 1) + b
def easeInOutQuart(t, b, c, d):
t /= d / 2
if t < 1:
return c / 2 * t ** 4 + b
t -= 2
return -c / 2 * (t ** 4 - 2) + b
def easeOutInQuart(t, b, c, d):
if t < d / 2:
return easeOutQuart(t * 2, b, c / 2, d)
return easeInQuart((t * 2) - d, b + c / 2, c / 2, d)
def easeInQuint(t, b, c, d):
t /= d
return c * t ** 5 + b
def easeOutQuint(t, b, c, d):
t = t / d - 1
return c * (t ** 5 + 1) + b
def easeInOutQuint(t, b, c, d):
t /= d / 2
if t < 1:
return c / 2 * t ** 5 + b
t -= 2
return c / 2 * (t ** 5 + 2) + b
def easeOutInQuint(t, b, c, d):
if t < d / 2:
return easeOutQuint (t * 2, b, c / 2, d)
return easeInQuint((t * 2) - d, b + c / 2, c / 2, d)
def easeInSine(t, b, c, d):
return -c * math.cos(t / d * (math.pi / 2)) + c + b
def easeOutSine(t, b, c, d):
return c * math.sin(t / d * (math.pi / 2)) + b
def easeInOutSine(t, b, c, d):
return -c / 2 * (math.cos(math.pi * t / d) - 1) + b
def easeOutInSine(t, b, c, d):
if t < d / 2:
return easeOutSine(t * 2, b, c / 2, d)
return easeInSine((t * 2) - d, b + c / 2, c / 2, d)
def easeInExpo(t, b, c, d):
if t <= 0:
return b
return c * pow(2, 10 * (t / d - 1)) + b
def easeOutExpo(t, b, c, d):
if t >= d:
return b + c
return c * (-pow(2, -10 * t / d) + 1) + b
def easeInOutExpo(t, b, c, d):
if t <= 0:
return b
if t >= d:
return b + c
t /= d / 2
if t < 1:
return c / 2 * pow(2, 10 * (t - 1)) + b
return c / 2 * (-pow(2, -10 * (t - 1)) + 2) + b
def easeOutInExpo(t, b, c, d):
if t < d / 2:
return easeOutExpo (t * 2, b, c / 2, d)
return easeInExpo((t * 2) - d, b + c / 2, c / 2, d)
def easeInCirc(t, b, c, d):
t /= d
return -c * (math.sqrt(1 - t * t) - 1) + b
def easeOutCirc(t, b, c, d):
t = t / d - 1
return c * math.sqrt(1 - t * t) + b
def easeInOutCirc(t, b, c, d):
t /= d / 2
if t < 1:
return -c / 2 * (math.sqrt(1 - t * t) - 1) + b
t -= 2
return c / 2 * (math.sqrt(1 - t * t) + 1) + b
def easeOutInCirc(t, b, c, d):
if t < d / 2:
return easeOutCirc(t * 2, b, c / 2, d)
return easeInCirc((t * 2) - d, b + c / 2, c / 2, d)
def easeInElastic(t, b, c, d):
if t <= 0:
return b
t /= d
if t >= 1:
return b + c
p = d * .3
a = c
s = p / 4
t -= 1
return -(a * pow(2, 10 * t) * math.sin((t * d - s) * (2 * math.pi) / p)) + b
def easeOutElastic(t, b, c, d):
if t <= 0:
return b
t /= d
if t >= 1:
return b + c
p = d * .3
a = c
s = p / 4
return (a * pow(2, -10 * t) * math.sin((t * d - s) * 2 * math.pi / p) + c + b)
def easeInOutElastic(t, b, c, d):
if t <= 0:
return b
t /= d / 2
if t >= 2:
return b + c
p = d * (.3 * 1.5)
s = p / 4
a = c
if t < 1:
t -= 1
return -.5 * (a * pow(2, (10 * t)) * math.sin((t * d - s) * 2 * math.pi / p)) + b
t -= 1
return a * pow(2, (-10 * t)) * math.sin((t * d - s) * 2 * math.pi / p) * .5 + c + b
def easeOutInElastic(t, b, c, d):
if t < d / 2:
return easeOutElastic (t * 2, b, c / 2, d)
return easeInElastic((t * 2) - d, b + c / 2, c / 2, d)
def easeInBack(t, b, c, d):
s = 1.70158
t /= d
return c * t * t * ((s + 1) * t - s) + b
def easeOutBack(t, b, c, d):
s = 1.70158
t = t / d - 1
return c * (t * t * ((s + 1) * t + s) + 1) + b
def easeInOutBack(t, b, c, d):
s = 1.70158 * 1.525
t /= d / 2
if t < 1:
return c / 2 * (t * t * ((s + 1) * t - s)) + b
t -= 2
return c / 2 * (t * t * ((s + 1) * t + s) + 2) + b
def easeOutInBack(t, b, c, d):
if t < d / 2:
return easeOutBack (t * 2, b, c / 2, d)
return easeInBack((t * 2) - d, b + c / 2, c / 2, d)
def easeInBounce(t, b, c, d):
return c - easeOutBounce (d - t, 0, c, d) + b
def easeOutBounce(t, b, c, d):
t /= d
if t < (1 / 2.75):
return c * (7.5625 * t * t) + b
elif t < (2 / 2.75):
t -= (1.5 / 2.75)
return c * (7.5625 * t * t + .75) + b
elif t < (2.5 / 2.75):
t -= (2.25 / 2.75)
return c * (7.5625 * t * t + .9375) + b
t -= (2.625 / 2.75)
return c * (7.5625 * t * t + .984375) + b
def easeInOutBounce(t, b, c, d):
if t < d / 2:
return easeInBounce (t * 2, 0, c, d) * .5 + b
return easeOutBounce (t * 2 - d, 0, c, d) * .5 + c*.5 + b
def easeOutInBounce(t, b, c, d):
if t < d / 2:
return easeOutBounce (t * 2, b, c / 2, d)
return easeInBounce((t * 2) - d, b + c / 2, c / 2, d)
| gpl-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.